text:
#include <iomanip>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/attributes/attribute.hpp>
#include <boost/log/attributes/clock.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <seq2map/common.hpp>

namespace fs = boost::filesystem;
namespace logging = boost::log;

using namespace seq2map;

namespace seq2map
{
    IndexList makeIndices(size_t start, size_t end)
    {
        IndexList idx;
        for (size_t i = start; i < end + 1; i++)
        {
            idx.push_back(i);
        }

        return idx;
    }

    double rad2deg(double radian)
    {
        return radian * 180.0f / CV_PI;
    }

    double deg2rad(double degree)
    {
        return degree * CV_PI / 180.0f;
    }

    int sub2symind(int i, int j, int n)
    {
        assert(i < n && j < n);

        if (i < j) return i * n - (i - 1) * i / 2 + j - i;
        else       return j * n - (j - 1) * j / 2 + i - j;
    }

    cv::Mat symmat(const cv::Mat& A)
    {
        assert(A.rows == A.cols);
        cv::Mat a(1, (A.rows + 1) * A.rows / 2, A.type());
        for (int i = 0; i < A.rows; i++)
        {
            for (int j = i; j < A.cols; j++)
            {
                a.at<double>(sub2symind(i, j, A.rows)) = A.at<double>(i, j);
            }
        }
        return a;
    }

    cv::Mat symmat(const cv::Mat& a, int n)
    {
        assert(a.total() == (n+1) * n / 2);
        cv::Mat A(n, n, a.type());
        for (int i = 0; i < A.rows; i++)
        {
            for (int j = 0; j < A.cols; j++)
            {
                A.at<double>(i, j) = a.at<double>(sub2symind(i, j, n));
            }
        }
        return A;
    }

    bool checkPositiveDefinite(const cv::Mat& A)
    {
        static const double EPS = 0; //1e-14;

        if (A.rows != A.cols || A.channels() != 1)
        {
            E_WARNING << "given matrix is not a one-channel square matrix";
            return false;
        }

        for (int i = 0; i < A.rows; i++)
        {
            if (cv::determinant(A.rowRange(0, i + 1).colRange(0, i + 1)) < EPS)
            {
                // cv::Mat Ai = A.rowRange(0, i + 1).colRange(0, i + 1);
                // double det = cv::determinant(Ai);
                // double d0 = Ai.at<double>(0, 0)*(Ai.at<double>(1, 1)*Ai.at<double>(2, 2) - Ai.at<double>(1, 2)*Ai.at<double>(2, 1));
                // double d1 = Ai.at<double>(0, 1)*(Ai.at<double>(1, 0)*Ai.at<double>(2, 2) - Ai.at<double>(1, 2)*Ai.at<double>(2, 0));
                // double d2 = Ai.at<double>(0, 2)*(Ai.at<double>(1, 0)*Ai.at<double>(2, 1) - Ai.at<double>(1, 1)*Ai.at<double>(2, 0));
                // if (det != 0)
                // {
                //     E_TRACE << mat2string(Ai, "Ai");
                //     E_TRACE << "det(Ai) = " << det;
                // }
                // E_TRACE << "d0 = " << d0;
                // E_TRACE << "d1 = " << d1;
                // E_TRACE << "d2 = " << d2;
                // E_TRACE << "eval = " <<(d0 - d1 + d2);

                return false;
            }
        }

        return true;
    }

    double rms(const cv::Mat& e)
    {
        size_t n = e.total();
        bool rowvec = n == e.rows;
        bool colvec = n == e.cols;

        assert(rowvec || colvec);

        cv::Mat e2 = rowvec ? e.t() * e : e * e.t();
        cv::Mat e64f;
        e2.convertTo(e64f, CV_64F);

        return std::sqrt(e2.ptr<double>()[0] / n);
    }

    String mat2string(const cv::Mat& x, const String& name, size_t precision)
    {
        cv::Mat x64f;
        x.convertTo(x64f, CV_64F);

        std::stringstream ss;

        ss << (name.empty() ? "" : name + " = ") << "[";

        for (size_t i = 0; i < x64f.rows; i++)
        {
            bool lastrow = i == x64f.rows - 1;
            for (size_t j = 0; j < x64f.cols; j++)
            {
                bool lastcol = j == x64f.cols - 1;

                ss << std::setprecision(precision) << x64f.at<double>(static_cast<int>(i), static_cast<int>(j));
                ss << (lastcol ? "" : ", ");
            }
            ss << (lastrow ? "" : "; ");
        }

        ss << "];";

        return ss.str();
    }

    bool mat2raw(const cv::Mat& im, const Path& path)
    {
        if (im.channels() > 1)
        {
            E_ERROR << "multi-channel images not supported (#ch=" << im.channels() << ")";
            return false;
        }

        if (im.dims > 2)
        {
            E_ERROR << "writing of " << im.dims << "-d matrix not supported";
            return false;
        }

        std::ofstream f(path.string().c_str(), std::ios::out | std::ios::binary);

        if (!f.is_open())
        {
            E_ERROR << "error opening output stream";
            return false;
        }

        f.write((char*)im.data, im.elemSize() * im.total());
        f.close();

        return true;
    }

    bool checkCameraMatrix(const cv::Mat& K)
    {
        if (K.rows != 3 || K.cols != 3 || (K.type() != CV_32F && K.type() != CV_64F))
        {
            E_WARNING << "the camera matrix has to be a 3-by-3 single/double matrix";
            return false;
        }

        cv::Mat K64f;
        K.convertTo(K64f, CV_64F);

        if (K64f.at<double>(1, 0) != 0 ||
            K64f.at<double>(2, 0) != 0 || K64f.at<double>(2, 1) != 0 ||
            K64f.at<double>(2, 2) != 1)
        {
            E_WARNING << "the camera matrix has to be an upper triangular matrix with the third diagonal entry set to 1";
            return false;
        }

        return true;
    }

    bool dirExists(const Path& path)
    {
        return fs::exists(path) && fs::is_directory(path);
    }

    bool fileExists(const Path& path)
    {
        return fs::exists(path) && fs::is_regular(path);
    }

    bool makeOutDir(const Path& path)
    {
        try
        {
            if (dirExists(path)) return true;
            else return fs::create_directories(path);
        }
        catch (std::exception& ex)
        {
            E_ERROR << "error making output directory " << path;
            E_ERROR << ex.what();

            return false;
        }
    }

    size_t filesize(const Path& path)
    {
        return fs::file_size(path);
    }

    Paths enumerateFiles(const Path& root, const String& ext)
    {
        Paths files;
        const fs::directory_iterator endItr;

        for (fs::directory_iterator itr(root); itr != endItr; itr++)
        {
            if (!fs::is_regular(*itr)) continue;

            bool check = ext.empty() || boost::iequals(ext, itr->path().extension().string());

            if (check)
            {
                files.push_back(*itr);
            }
        }

        return files;
    }

    Paths enumerateFiles(const Path& sample)
    {
        std::string ext = sample.extension().string();
        return enumerateFiles(ext.empty() ? sample : sample.parent_path(), ext);
    }

    Paths enumerateDirs(const Path& root)
    {
        if (!dirExists(root)) return Paths();

        Paths dirs;
        const fs::directory_iterator endItr;

        try
        {
            for (fs::directory_iterator itr(root); itr != endItr; itr++)
            {
                if (!fs::is_directory(*itr)) continue;
                dirs.push_back(*itr);
            }
        }
        catch (std::exception& ex)
        {
            E_ERROR << "error enumerating directories in " << root;
            E_ERROR << ex.what();
        }

        return dirs;
    }

    String removeFilenameExt(const String& filename)
    {
        return filename.substr(0, filename.find_last_of("."));
    }

    Path fullpath(const Path& path)
    {
        return fs::absolute(fs::canonical(path));
    }

    Path getRelativePath(const Path& path, const Path& base)
    {
#if BOOST_VERSION >= 106000
        // since Boost 1.60 we have a nice useful function
        return path.empty() ? path : fs::relative(fullpath(path), fullpath(base));
#else
        // for older Boost we have the code taken from a ticket
        if (path.empty()) return path;

        Path fullPath = fullpath(path);
        Path fullBase = fullpath(base);
        Path relPath;

        fs::path::const_iterator pathItr = fullPath.begin(), pathEnd = fullPath.end();
        fs::path::const_iterator baseItr = fullBase.begin(), baseEnd = fullBase.end();

        // skip the common part
        while (pathItr != pathEnd && baseItr != baseEnd && *pathItr == *baseItr)
        {
            pathItr++;
            baseItr++;
        }

        while (baseItr != baseEnd)
        {
            if (*baseItr != ".") relPath /= "..";
            baseItr++;
        }

        while (pathItr != pathEnd)
        {
            relPath /= *pathItr;
            pathItr++;
        }

        return relPath;
#endif
    }

    bool initLogFile(const Path& path)
    {
        try
        {
            logging::core::get()->add_global_attribute("TimeStamp", logging::attributes::local_clock());
            logging::add_console_log(std::cout, logging::keywords::format = "[%TimeStamp%] %Message%");

            if (!path.empty())
            {
                logging::add_file_log(path, logging::keywords::format = "[%TimeStamp%] %Message%");
            }
        }
        catch (std::exception& ex)
        {
            std::cerr << "error logging to file " << path.string() << std::endl;
            std::cerr << ex.what() << std::endl;

            return false;
        }

        return true;
    }

    String makeNameList(Strings names)
    {
        std::stringstream ss;
        for (size_t i = 0; i < names.size(); i++)
        {
            if (i > 0) // make a comma-separated sentence
            {
                ss << (i < names.size() - 1 ? ", " : " and ");
            }
            ss << "\"" << names[i] << "\"";
        }
        ss << ".";

        return ss.str();
    }

    Strings explode(const String& string, char delimiter)
    {
        String tok;
        Strings toks;
        std::istringstream iss(string);

        while (getline(iss, tok, delimiter)) toks.push_back(tok);
        return toks;
    }

    String indices2string(const IndexList& indices)
    {
        std::stringstream ss;
        IndexList::const_iterator idx, last = indices.end();

        for (idx = indices.begin(); idx != last; idx++)
        {
            ss << (*idx) << ((boost::next(idx) != last) ? ", " : "");
        }

        return ss.str();
    }

    String size2string(const cv::Size& size)
    {
        std::stringstream ss;
        ss << size.height << "x" << size.width;

        return ss.str();
    }

    cv::Mat strings2mat(const Strings& strings, const cv::Size& matSize)
    {
        if (matSize.height * matSize.width != strings.size())
        {
            E_ERROR << "given strings with " << strings.size()
                << " element(s) do not fit the desired matrix size of " << size2string(matSize);
            return cv::Mat();
        }

        std::vector<float> data(strings.size());

        for (size_t i = 0; i < strings.size(); i++)
        {
            data[i] = (float)atof(strings[i].c_str());
        }

        return cv::Mat(data).reshape(0, matSize.height).clone();
    }

    bool replace(String& subject, const String& from, const String& to)
    {
        size_t start_pos = subject.find(from);

        if (start_pos == String::npos) return false;
        subject.replace(start_pos, from.length(), to);

        return true;
    }

    cv::Mat rgb2gray(const cv::Mat& rgb)
    {
        cv::Mat gray;
        switch (rgb.channels())
        {
        case 1: gray = rgb.clone(); break;
        case 3: cv::cvtColor(rgb, gray, CV_RGB2GRAY); break;
        default: E_ERROR << "the source image has " << rgb.channels() << " channels, while 1 or 3 expected!!";
        }
        return gray;
    }

    cv::Mat gray2rgb(const cv::Mat& gray)
    {
        cv::Mat rgb;
        cv::cvtColor(gray, rgb, CV_GRAY2BGR);

        return rgb;
    }

    cv::Mat imfuse(const cv::Mat& im0, const cv::Mat& im1)
    {
        cv::Size sz = cv::Size(std::max(im0.cols, im1.cols), std::max(im0.rows, im1.rows));
        cv::Mat r = cv::Mat::zeros(sz, CV_8U);
        cv::Mat g = cv::Mat::zeros(sz, CV_8U);
        cv::Mat b = cv::Mat::zeros(sz, CV_8U);

        rgb2gray(im0).copyTo(r.rowRange(0, im0.rows).colRange(0, im0.cols));
        rgb2gray(im1).copyTo(b.rowRange(0, im1.rows).colRange(0, im1.cols));
        g = 0.5f * r + 0.5f * b;

        std::vector<cv::Mat> bgr;
        bgr.push_back(b);
        bgr.push_back(g);
        bgr.push_back(r);

        cv::Mat im;
        cv::merge(bgr, im);

        return im;
    }

    cv::Mat interp(const cv::Mat& src, const cv::Mat& sub, int method, bool useGpu)
    {
        if (sub.channels() != 2)
        {
            E_ERROR << "subscript matrix has to have 2 channels";
            return cv::Mat();
        }

        cv::Mat dst;

        if (useGpu && cv::cuda::getCudaEnabledDeviceCount() > 0)
        {
            cv::cuda::GpuMat gpuSrc;
            cv::cuda::GpuMat gpuDst;
            cv::cuda::GpuMat gpuMapX, gpuMapY;

            std::vector<cv::Mat> xy;
            cv::split(sub, xy);

            xy[0].convertTo(xy[0], CV_32F);
            xy[1].convertTo(xy[1], CV_32F);

            gpuSrc.upload(src);
            gpuMapX.upload(xy[0]);
            gpuMapY.upload(xy[1]);

            cv::cuda::remap(gpuSrc, gpuDst, gpuMapX, gpuMapY, method, cv::BORDER_REPLICATE);
            gpuDst.download(dst);
        }
        else
        {
            if (sub.rows < SHRT_MAX && sub.cols < SHRT_MAX)
            {
                cv::remap(src, dst, sub, cv::Mat(), method);
            }
            else
            {
                const int n = static_cast<int>(sub.total());
                const int k = src.channels();
                const int stride = SHRT_MAX - 1;

                cv::Mat map = sub.reshape(1, n);

                dst = cv::Mat(sub.rows, sub.cols, src.type());
                dst = dst.reshape(1, n);

                for (int i = 0; i < n; i += stride)
                {
                    const int i0 = i;
                    const int in = std::min(i + stride, n);
                    cv::remap(src, dst.rowRange(i0, in).reshape(k), map.rowRange(i0, in).reshape(2), cv::Mat(), method, cv::BORDER_REPLICATE);
                }

                dst = dst.reshape(k, sub.rows);
            }
        }

        return dst;
    }

    Time unow()
    {
        return boost::posix_time::microsec_clock::local_time();
    }

    String time2string(const Time& time)
    {
        return boost::posix_time::to_simple_string(time);
    }
}

//==[ PersistentMat ]=========================================================//

const seq2map::String PersistentMat::s_magicString = "CVMAT";

bool PersistentMat::Store(Path& to) const
{
    if (mat.dims > 2)
    {
        E_ERROR << "multi-dimensional matrix not supported";
        return false;
    }

    std::ofstream os(to.string().c_str(), std::ios::out | std::ios::binary);

    if (!os.is_open())
    {
        E_ERROR << "error opening output stream to " << to;
        return false;
    }

    try
    {
        // write header..
        os << s_magicString << " ";
        os << CvDepthToString(mat.depth()) << " ";

        const int m = mat.rows;
        const int n = mat.cols;
        const int k = mat.channels();

        os.write((char*)&m, sizeof m);
        os.write((char*)&n, sizeof n);
        os.write((char*)&k, sizeof k);

        Dump(mat, os); // write data

        os.close(); // finished
    }
    catch (std::exception& ex)
    {
        E_ERROR << "exception caught: " << ex.what();
        return false;
    }

    return true;
}

bool PersistentMat::Restore(const Path& from)
{
    std::ifstream is(from.string().c_str(), std::ios::in | std::ios::binary);

    if (!is.is_open())
    {
        E_ERROR << "error opening input stream from " << from;
        return false;
    }

    try
    {
        char magic[5];
        is.read((char*)&magic, sizeof magic);

        if (!boost::equal(magic, s_magicString))
        {
            E_ERROR << "magic string not found";
            return false;
        }

        String depthString;
        std::getline(is, depthString, ' ');

        int depth = StringToCvDepth(depthString);

        if (depth == CV_USRTYPE1)
        {
            E_ERROR << "invalid depth";
            return false;
        }

        int m, n, k;
        is.read((char*)&m, sizeof m);
        is.read((char*)&n, sizeof n);
        is.read((char*)&k, sizeof k);

        mat = cv::Mat(m, n, CV_MAKE_TYPE(depth, k));

        Dump(is, mat);

        is.close();
    }
    catch (std::exception& ex)
    {
        E_ERROR << "exception caught: " << ex.what();
        return false;
    }

    return true;
}

String PersistentMat::CvDepthToString(int depth)
{
    switch (depth)
    {
    case CV_8U:       return "8U";  break;
    case CV_8S:       return "8S";  break;
    case CV_16U:      return "16U"; break;
    case CV_16S:      return "16S"; break;
    case CV_32S:      return "32S"; break;
    case CV_32F:      return "32F"; break;
    case CV_64F:      return "64F"; break;
    case CV_USRTYPE1: return "USR"; break;
    }

    E_WARNING << "unknown matrix depth " << depth;

    return CvDepthToString(CV_USRTYPE1);
}

int PersistentMat::StringToCvDepth(const String& depth)
{
    if      (depth == "8U")   return CV_8U;
    else if (depth == "8S")   return CV_8S;
    else if (depth == "16U")  return CV_16U;
    else if (depth == "16S")  return CV_16S;
    else if (depth == "32S")  return CV_32S;
    else if (depth == "32F")  return CV_32F;
    else if (depth == "64F")  return CV_64F;
    else if (depth == "USR")  return CV_USRTYPE1;

    E_WARNING << "unknown depth string \"" << depth << "\"";

    return StringToCvDepth("USR");
}

void PersistentMat::Dump(const cv::Mat& mat, std::ostream& os)
{
    if (mat.isContinuous())
    {
        os.write((char*)mat.data, mat.elemSize() * mat.total());
    }
    else
    {
        const size_t bytesPerRow = mat.elemSize() * static_cast<size_t>(mat.cols);
        for (int i = 0; i < mat.rows; i++)
        {
            os.write(mat.ptr<char>(i), bytesPerRow);
        }
    }
}

void PersistentMat::Dump(std::istream& is, cv::Mat& mat)
{
    if (mat.isContinuous())
    {
        is.read((char*)mat.data, mat.elemSize() * mat.total());
    }
    else
    {
        const size_t bytesPerRow = mat.elemSize() * static_cast<size_t>(mat.cols);
        for (int i = 0; i < mat.rows; i++)
        {
            is.read(mat.ptr<char>(i), bytesPerRow);
        }
    }
}

//==[ Speedometre ]===========================================================//

void Speedometre::Start()
{
    if (!m_activated)
    {
        m_activated = true;
        m_timer.start();

        return;
    }

    if (!m_timer.is_stopped())
    {
        E_WARNING << "the operation takes no effect as the timer is already ticking!!";
        return;
    }

    m_timer.resume();
}

void Speedometre::Update(size_t amount)
{
    if (!m_activated || m_timer.is_stopped())
    {
        E_WARNING << "the operation takes no effect as the timer is not ticking!!";
        return;
    }

    m_accumulated += amount;
    m_freq++;
}

void Speedometre::Stop(size_t amount)
{
    Update(amount);
    m_timer.stop();
}

void Speedometre::Reset()
{
    m_activated = false;
    m_accumulated = 0;
    m_freq = 0;
    m_timer.stop();
}

double Speedometre::GetElapsedSeconds() const
{
    boost::timer::cpu_times elapsed = m_timer.elapsed();

    return (double) boost::chrono::duration_cast<boost::chrono::milliseconds>(
        boost::chrono::nanoseconds(elapsed.wall)).count() / 1000.0f;
}

String Speedometre::ToString() const
{
    std::stringstream ss;
    ss << m_displayName << ": " << std::fixed << std::setprecision(2) << GetSpeed() << " " << m_displayUnit;

    return ss.str();
}

ColourMap::ColourMap(size_t colours)
{
    m_cmap = cv::Mat(static_cast<int>(colours), 1, CV_64FC4);

    const int q0 = static_cast<int>((double)colours * 0.00f);
    const int q1 = static_cast<int>((double)colours * 0.25f);
    const int q2 = static_cast<int>((double)colours * 0.50f);
    const int q3 = static_cast<int>((double)colours * 0.75f);
    const int q4 = static_cast<int>((double)colours * 1.00f);

    m_cmap.at<cv::Scalar>(0) = cv::Scalar(120, 81, 169);

    for (int i = 1; i < static_cast<int>(colours); i++)
    {
        const double v = static_cast<double>(i);

        m_cmap.at<cv::Scalar>(i) = cv::Scalar(
            i < q2 ? 0 : (i < q3 ? 255 * (v - q2) / (q3 - q2) : 255),
            i < q1 ? 255 * (v - q0) / (q1 - q0) : (i < q3 ? 255 : 255 * (q4 - v) / (q4 - q3)),
            i < q1 ? 255 : (i < q2 ? 255 * (q2 - v) / (q2 - q1) : 0),
            0
        );
    }
}

cv::Scalar ColourMap::GetColour(double val, double min, double max)
{
    const int cidx = static_cast<int>((double)m_cmap.rows * (val - min) / (max - min));
    return m_cmap.at<cv::Scalar>(cidx < 0 ? 0 : (cidx < m_cmap.rows ? cidx : m_cmap.rows - 1));
};


text:
/*
 * Copyright (c) 2012 Jonathan Perry
 * This code is released under the MIT license (see LICENSE file).
 */
#include "channels/MimoChannel.h"

#include <boost/numeric/ublas/operation.hpp>

MimoChannel::MimoChannel(
		unsigned int nTransmitter,
		unsigned int nReceiver,
		const std::vector<ComplexNumber> & channelMatrix)
  : m_nTransmitter(nTransmitter),
    m_nReceiver(nReceiver),
    m_channelMatrix(nReceiver, nTransmitter)
{
	for(unsigned int row = 0; row < nReceiver; row++) {
		for(unsigned int col = 0; col < nTransmitter; col++) {
			m_channelMatrix(row, col) = channelMatrix[row * nTransmitter + col];
		}
	}
}

void MimoChannel::seed(unsigned int *const , int )
{
	// no RNG in this class
	return;
}

void MimoChannel::process(
		const std::vector<ComplexSymbol> & inSymbols,
		std::vector<ComplexSymbol> & outSymbols)
{
	unsigned int numIQSymbols = inSymbols.size();

	unsigned int numChannelUsages = numIQSymbols / m_nTransmitter;

	if (inSymbols.size() != m_nTransmitter * numChannelUsages) {
		throw std::runtime_error("input symbols size should contain symbols for all transmit antenna");
	}

	unsigned int numOutputSymbols = numChannelUsages * m_nReceiver;
	outSymbols.clear();
	outSymbols.resize(numOutputSymbols);

	// Initialize a matrix with all symbols
	boost::numeric::ublas::matrix<ComplexSymbol> symbolMatrix(m_nTransmitter,
															  numChannelUsages);
	unsigned int inSymbolIter = 0;
	for(unsigned int col = 0; col < numChannelUsages; col++) {
		for(unsigned int row = 0; row < m_nTransmitter; row++) {
			symbolMatrix(row, col) = inSymbols[inSymbolIter++];
		}
	}

	// Multiply channel matrix by symbol matrix
	boost::numeric::ublas::matrix<ComplexSymbol> outputMatrix(m_nReceiver,
															  numChannelUsages);
	axpy_prod(m_channelMatrix, symbolMatrix, outputMatrix, true);

	// Read the output symbols from outputMatrix
	unsigned int outSymbolIter = 0;
	for(unsigned int col = 0; col < numChannelUsages; col++) {
		for(unsigned int row = 0; row < m_nReceiver; row++) {
			outSymbols[outSymbolIter++] = outputMatrix(row, col);
		}
	}

}

unsigned int MimoChannel::forecast(unsigned int numOutputs)
{
	unsigned int numChannelUsages = (numOutputs + m_nReceiver - 1) / m_nReceiver;
	return numChannelUsages * m_nTransmitter;
}

ext: cpp

max_stars_repo_name: yonch/wireless

max_issues_repo_name: darksidelemm/wireless

max_forks_repo_name: darksidelemm/wireless


text:
//          Copyright Alain Miniussi 20014.
// 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)

// A test of the sendrecv() operation.
#include <boost/mpi/communicator.hpp>
#include <boost/mpi/environment.hpp>
#include <boost/test/minimal.hpp>
#include <vector>
#include <algorithm>
#include <boost/serialization/string.hpp>
#include <boost/iterator/counting_iterator.hpp>
#include <boost/lexical_cast.hpp>
#include <numeric>

namespace mpi = boost::mpi;

struct blob {
  blob(int i) : value(i) {}
  int value;
  template<class Archive>
  void serialize(Archive& s, const unsigned int version) {
    s & value;
  }
};

std::ostream& operator<<(std::ostream& out, blob const& b) {
  out << "blob(" << b.value << ")";
  return out;
}

bool operator==(blob const& b1, blob const& b2) {
  return b1.value == b2.value;
}

template<typename T>
void test_sendrecv(mpi::communicator& com) {
  int const wrank = com.rank();
  int const wsize = com.size();
  int const wnext((wrank + 1) % wsize);
  int const wprev((wrank + wsize - 1) % wsize);
  T recv(-1);
  com.sendrecv(wnext, 1, T(wrank), wprev, 1, recv);
  for(int r = 0; r < wsize; ++r) {
    com.barrier();
    if (r == wrank) {
      std::cout << "rank " << wrank << " received " << recv << " from " << wprev << '\n';
    }
  }
  BOOST_CHECK(recv == T(wprev));
}

int test_main(int argc, char* argv[])
{
  mpi::environment env(argc, argv);
  mpi::communicator world;
  test_sendrecv<int>(world);
  test_sendrecv<blob>(world);
  return 0;
}


text:
#include "gtest/gtest.h"

#include "conex/exponential_map_pade.h"

#include <Eigen/Dense>
#include <unsupported/Eigen/MatrixFunctions>

#include "conex/debug_macros.h"

namespace conex {

using Eigen::Map;
using Eigen::MatrixXd;
using Eigen::VectorXd;

GTEST_TEST(ExponentialMapPadeApproximation, CompareWithEigen) {
  int n = 4;
  MatrixXd A(n, n);
  // clang-format off
  A << 3, 1, 0, 1,
       1, 3, 1, 0,
       0, 1, 4, 1,
       1, 0, 1, 5;
  // clang-format on
  A = A / A.trace();

  MatrixXd reference = A.exp();
  MatrixXd calculated(n, n);

  Map<MatrixXd, Eigen::Aligned> map(calculated.data(), n, n);
  ExponentialMapPadeApproximation(A, &map);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      EXPECT_NEAR(reference(i, j), calculated(i, j), 1e-7);
    }
  }
}

}  // namespace conex

ext: cc

max_stars_repo_name: frankpermenter/conex

max_issues_repo_name: frankpermenter/conex

max_forks_repo_name: frankpermenter/conex


text:
#if !defined(_DUDP_SERVER_HPP_)
#define _DUDP_SERVER_HPP_

#include <array>
#include <memory>
#include <string>

#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/udp.hpp>

namespace dudp {

class
server
{
private:
    boost::asio::ip::udp::socket socket_;
    boost::asio::ip::udp::endpoint remote_endpoint_;
    std::array<char, 1024> recv_buffer_;

public:
    server(boost::asio::io_service &service, uint16_t port);

protected:
    void start_receive();
    void handle_receive(const boost::system::error_code &error, std::size_t bytes_transferred);
    void handle_send(std::shared_ptr<std::string> message, const boost::system::error_code &error, std::size_t bytes_transferred);
};

}

#endif // !defined(_DUDP_SERVER_HPP_)

// vim:set sw=4 ts=4 et:

ext: hpp

max_stars_repo_name: swrh/dudp

max_issues_repo_name: swrh/dudp

max_forks_repo_name: swrh/dudp


text:
/**
 * Žr. licenzijos failą LICENSE source medžio viršuje. (LICENSE file at the top of the source tree.)
 *
 * Projektas LIEPA-2, 2017 - 2020 m. (https://liepa2.raštija.lt)
 * Vilniaus universitetas (https://www.vu.lt)
 *
 * @file main.cpp
 *
 * @author dr. Margarita Beniušė (margarita.beniuse@mif.vu.lt), dr. Pijus Kasparaitis (pkasparaitis@yahoo.com)
 * 2020 12 28
 */

#include <qi/applicationsession.hpp>
#include <boost/shared_ptr.hpp>
#include "liepaTTS.h"

int main(int argc, char* argv[])
{
    qi::ApplicationSession app(argc, argv);
    app.startSession();
    qi::SessionPtr session = app.session();
    session->registerService("LiepaTTS", qi::AnyObject(boost::make_shared<LiepaTTS>(session)));
    app.run();
    return 0;
}


text:
#pragma once

#include <iostream>
#include <vector>

#include <boost/serialization/access.hpp>

#include <graphtyper/graph/haplotype.hpp>
#include <graphtyper/typer/vcf_writer.hpp>

/*
namespace gyper
{

class HaplotypeCall
{
  friend class boost::serialization::access;

public:
  std::vector<uint16_t> calls;
  std::vector<Genotype> gts;
  std::vector<std::vector<ReadStrand> > read_strand;
  long num_samples{0};

  HaplotypeCall() = default;
  explicit HaplotypeCall(Haplotype const & hap);

  void merge_with(HaplotypeCall const & other);
  void make_calls_unique();

private:
  template <class Archive>
  void serialize(Archive & ar, unsigned int version);
};

class HaplotypeCalls
{
  friend class boost::serialization::access;

public:
  HaplotypeCalls() = default;
  explicit HaplotypeCalls(std::vector<HaplotypeCall> const & hap_calls);

  // \brief Return a list of haplotype calls.
  inline std::vector<HaplotypeCall>
  get_hap_calls()
  {
    return hap_calls;
  }

private:
  std::vector<HaplotypeCall> hap_calls;

  template <class Archive>
  void serialize(Archive & ar, unsigned int version);
};

void save_calls(HaplotypeCalls & calls, std::string const & filename);
std::vector<HaplotypeCall> load_calls(std::string const & filename);

} // namespace gyper
*/


text:
// -*- mode: C++ -*-
/**
   Dietrich Bollmann, Kamakura, 2015/01/01

   DMatrix-test.h

   Unit tests for class: DMatrix

   Copyright (c) 2015 Dietrich Bollmann

   This software may be modified and distributed under the terms
   of the MIT license.  See the LICENSE file for details.
*/

#define BOOST_TEST_DYN_LINK
#ifdef STAND_ALONE
#   define BOOST_TEST_MODULE Main
#endif
#include <boost/test/unit_test.hpp>

#include "DMatrix.h"

namespace nsl {

BOOST_AUTO_TEST_SUITE(TestSuite_DMatrix)

// Test equality operator
bool test_equality(const std::vector<std::vector<double> > &left,
		   const std::vector<std::vector<double> > &right)
{
  DMatrix vLeft(left);
  DMatrix vRight(right);

  return (vLeft == vRight);
}

BOOST_AUTO_TEST_CASE(Test_DMatrix_equality_operator)
{
  // equal
  BOOST_REQUIRE(   test_equality( {},          {}          ) );
  BOOST_REQUIRE(   test_equality( {{}},        {{}}        ) );
  BOOST_REQUIRE(   test_equality( {{1}},       {{1}}       ) );

  BOOST_REQUIRE(   test_equality( {{1, 2}},    {{1, 2}}    ) );
  BOOST_REQUIRE(   test_equality( {{1}, {2}},  {{1}, {2}}  ) );

  BOOST_REQUIRE(   test_equality( {{1, 2, 3}}, {{1, 2, 3}}         ) );
  BOOST_REQUIRE(   test_equality( {{1}, {2}, {3}}, {{1}, {2}, {3}} ) );

  BOOST_REQUIRE(   test_equality( {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}},
				  {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}  ) );

  // different dimensions
  BOOST_REQUIRE( ! test_equality( {{}},        {{1}}       ) );
  BOOST_REQUIRE( ! test_equality( {{1}},       {{}}        ) );
  BOOST_REQUIRE( ! test_equality( {{1}},       {{1, 2}}    ) );
  BOOST_REQUIRE( ! test_equality( {{1, 2}},    {{1}}       ) );
  BOOST_REQUIRE( ! test_equality( {{1, 2}},    {{1}, {2}}  ) );
  BOOST_REQUIRE( ! test_equality( {{1}, {2}},  {{1, 2}}    ) );

  // different elements
  BOOST_REQUIRE( ! test_equality( {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}},
				  {{0, 2, 3}, {4, 5, 6}, {7, 8, 9}}  ) );
  BOOST_REQUIRE( ! test_equality( {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}},
				  {{1, 2, 3}, {4, 0, 6}, {7, 8, 9}}  ) );
  BOOST_REQUIRE( ! test_equality( {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}},
				  {{1, 2, 3}, {4, 5, 6}, {7, 8, 0}}  ) );
}

// Test matrix vector multiplication
bool test_mvmult(const std::vector<std::vector<double> > &m,
		 const std::vector<double> &v,
		 const std::vector<double> &r)
{
  DMatrix m2(m);
  DVector v2(v);
  DVector r2(r);

  return (m2 * v2 == r2);
}

// Test matrix vector multiplication
bool test_mvmult2(const std::vector<std::vector<double> > &m,
		  const std::vector<double> &v,
		  const std::vector<double> &r)
{
  DMatrix m2(m);
  DVector v2(v);
  DVector r2(r);

  double ed = euclideanDistance((m2 * v2), r2);

  // DEBUG
  //| std::cout << "euclidian distance: " << ed << std::endl;

  return (ed < 1e-10);
}

BOOST_AUTO_TEST_CASE(Test_DVector_multiplication_operator)
{
  BOOST_REQUIRE( test_mvmult(                                {},         {},            {} ) );
  BOOST_REQUIRE( test_mvmult(                             {{2}},        {3},           {6} ) );
  BOOST_REQUIRE( test_mvmult(                          {{1, 2}},     {3, 4},          {11} ) );
  BOOST_REQUIRE( test_mvmult(                        {{1}, {2}},        {3},        {3, 6} ) );
  BOOST_REQUIRE( test_mvmult(                  {{1, 2}, {3, 4}},     {5, 6},      {17, 39} ) );
  BOOST_REQUIRE( test_mvmult( {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}},  {1, 2, 3},  {14, 32, 50} ) );

  BOOST_REQUIRE( test_mvmult2( {{ 1000,     0, -1000,     0},
 	                        {    0,  3000,     0, -3000},
			        {-1000,     0,  3000, -2000},
			        {    0, -3000, -2000,  5000}},
                               { 0, 0, 10.0/11.0, 15.0/11.0 },
                               { -10000.0/11.0, -45000.0/11.0, 0, 55000.0/11.0 } ) );
}

BOOST_AUTO_TEST_SUITE_END()

} // namespace nsl

/* fin */


text:
#include <iostream>

#include "crypto/secure_string.h"
#include "mess/game/Game.h"
#include "mess/game/Python.h"

#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

#include <unistd.h> // getpass

enum MainFunctionReturnValues {
  Success,
  InvalidArgument,
  PythonException,
  StdException,
  UnknownException
};

namespace fs = boost::filesystem;
namespace po = boost::program_options;

using namespace mess::game;

static crypto::secure_string prompt_for_password(const char *prompt) {
  using namespace crypto;
  auto buffer = buffer_view::make_mutable(getpass(prompt));
  return secure_string::clean_buffer_and_make(buffer);
}

static void do_the_thing(const GameSettings &settings) {
  boost::asio::io_service io_service;

  auto game_pwd = prompt_for_password("game password: ");
  auto master_pwd = prompt_for_password("admin password: ");

  Game game(io_service, settings, game_pwd, master_pwd);

  game_pwd.clear();
  master_pwd.clear();

  game.AsyncRun();

  io_service.run();
}

int main(int argc, char *argv[]) {
  try {

    GameSettings settings;

    {
      po::options_description desc("Allowed options");
      desc.add_options()
        ("help,h",
            "show this help message and exit")
        ("game-name",
            po::value<std::string>(&settings.game_name)->required(),
            "name of the game")
        ("python-folder",
            po::value<std::string>(&settings.python_code_folder),
            "folder containing the python code")
        ("port",
            po::value<uint32_t>(&settings.server_port),
            "output folder to save converted images")
      ;

    try {

        // Parse command-line args.
        po::variables_map vm;
        po::store(po::parse_command_line(argc, argv, desc), vm);

        // Print help and exit if requested.
        if (vm.count("help")) {
          std::cout << desc << "\n";
          return Success;
        }

        // Throw if any argument is invalid.
        po::notify(vm);

        // Check if input_folder exists.
        if (!fs::is_directory(settings.python_code_folder)) {
          throw std::invalid_argument("not a folder: " + settings.python_code_folder);
        }

      } catch (const po::error &e) {
        std::cerr << desc << "\n" << e.what() << std::endl;
        return InvalidArgument;
      }
    }

    do_the_thing(settings);

    return Success;
  } catch (const boost::python::error_already_set&) {
    Python::PrintError();
    return PythonException;
  } catch (const std::exception &e) {
    std::cerr << "EXCEPTION: " << e.what() << std::endl;
    return StdException;
  } catch (...) {
    std::cerr << "UNKNOWN EXCEPTION!" << std::endl;
    return UnknownException;
  }
}

max_stars_repo_name: nsubiron/mess-engine

max_issues_repo_name: nsubiron/mess-engine

max_forks_repo_name: nsubiron/mess-engine


text: #include <boost/mpl/aux_/preprocessed/bcc_pre590/set_c.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#ifndef CLIPPER_METRICS_HPP
#define CLIPPER_METRICS_HPP

#include <atomic>
#include <vector>
#include <mutex>
#include <shared_mutex>
#include <string>
#include <thread>

#include <boost/property_tree/ptree.hpp>

namespace clipper {

namespace metrics {

using std::vector;

enum class MetricType {
  Counter = 0,
  RatioCounter = 1,
  Meter = 2,
  Histogram = 3
};

class Metric {
 public:
  /**
   * @return The metric's type (Counter, RatioCounter, Meter, etc...)
   */
  virtual MetricType type() const = 0;
  /**
   *
   * @return The name of the metric, generally user-defined
   */
  virtual const std::string name() const = 0;
  /**
   * @return A boost property tree containing relevant metric attributes
   */
  virtual const boost::property_tree::ptree report_tree() = 0;
  /**
   * @return A json-formatted string containing relevant metric attributes
   */
  virtual const std::string report_str() = 0;
  /**
   * Resets all metric attributes to their default values (typically zero)
   */
  virtual void clear() = 0;

};

class Counter : public Metric {
 public:
  /** Creates a Counter with initial count zero */
  explicit Counter(const std::string name);
  explicit Counter(const std::string name, const int initial_count);

  // Disallow copy and move
  Counter(Counter &other) = delete;
  Counter &operator=(Counter &other) = delete;
  Counter(Counter &&other) = delete;
  Counter &operator=(Counter &&other) = delete;

  void increment(const int value);
  void decrement(const int value);
  int value() const;

  // Metric implementation
  MetricType type() const override;
  const std::string name() const override;
  const boost::property_tree::ptree report_tree() override;
  const std::string report_str() override;
  void clear() override;

 private:
  const std::string name_;
  std::atomic_int count_;

};

/**
 * Represents a numerator/denominator ratio, where both
 * numerator and denominator are positive integers.
 */
class RatioCounter : public Metric {
 public:
  /** Creates a RatioCounter with numerator 0 and denominator 0 **/
  explicit RatioCounter(const std::string name);
  explicit RatioCounter(const std::string name, const uint32_t num, const uint32_t denom);

  // Disallow copy and move
  RatioCounter(RatioCounter &other) = delete;
  RatioCounter &operator=(RatioCounter &other) = delete;
  RatioCounter(RatioCounter &&other) = delete;
  RatioCounter &operator=(RatioCounter &&other) = delete;

  void increment(const uint32_t num_incr, const uint32_t denom_incr);
  double get_ratio();

  // Metric implementation
  MetricType type() const override;
  const std::string name() const override;
  const boost::property_tree::ptree report_tree() override;
  const std::string report_str() override;
  void clear() override;

 private:
  const std::string name_;
  std::shared_timed_mutex ratio_lock_;
  std::atomic<uint32_t> numerator_;
  std::atomic<uint32_t> denominator_;

};

class MeterClock {
 public:
  virtual long get_time_micros() const = 0;
};

class RealTimeClock : public MeterClock {
 public:
  long get_time_micros() const override;
};

/**
 * A manually adjustable clock used for testing
 * exponentially weighted moving average (EWMA)
 * functionality
 */
class PresetClock : public MeterClock {
 public:
  long get_time_micros() const override;
  void set_time_micros(const long time_micros);

 private:
  long time_ = 0;
};

/// Represents the different load average options for exponentially
/// weighted moving averages (EWMA) within meters. For a one minute EWMA,
/// we use the OneMinute load average, etc...
enum class LoadAverage {
  OneMinute,
  FiveMinute,
  FifteenMinute
};

/// Represents an exponentially weighted moving average.
/// Multiple EWMAs are included within a single meter
/// corresponding to different load averages.
///
/// The EWMA is updated using "ticks" at a frequency determined
/// by a specified tick interval. For a detailed explanation of the update
/// (tick) procedure and decay mechanisms, see the following:
/// 1. http://www.teamquest.com/pdfs/whitepaper/ldavg1.pdf
/// 2. http://www.teamquest.com/pdfs/whitepaper/ldavg2.pdf
/// 3. http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
class EWMA {
 public:
  EWMA(long tick_interval_seconds, LoadAverage load_average);
  void tick();
  void mark_uncounted(uint32_t num);
  void reset();
  double get_rate_seconds();

 private:
  // The time interval between ticks
  const long tick_interval_seconds_;
  // The exponential decay factor applied to the previous
  // rate at every tick
  double alpha_;
  double rate_ = -1;
  std::shared_timed_mutex rate_lock_;
  // The number of new events to be included
  // in the rate at the next tick
  std::atomic<uint32_t> uncounted_;

};

class Meter : public Metric {
 public:
  explicit Meter(std::string name, std::shared_ptr<MeterClock> clock);

  // Disallow copy and move
  Meter(Meter &other) = delete;
  Meter &operator=(Meter &other) = delete;
  Meter(Meter &&other) = delete;
  Meter &operator=(Meter &&other) = delete;

  void mark(uint32_t num);

  /**
   * @return The rate of this meter, in events-per-microsecond, since
   * the time of initialization
   */
  double get_rate_micros();

  /**
   * @return The rate of this meter, in events-per-second, since the
   * time of initialization
   */
  double get_rate_seconds();

  /**
   * @return The rate of this meter, in events-per-second, for the last minute
   * This rate is calculated using an expontentially weighted moving average
   */
  double get_one_minute_rate_seconds();

  /**
   * @return the rate of this meter, in events-per-second, for the last five minutes
   * This rate is calculated using an expontentially weighted moving average.
   */
  double get_five_minute_rate_seconds();

  /**
   * @return the rate of this meter, in events-per-second, for the last fifteen minutes
   * This rate is calculated using an expontentially weighted moving average.
   */
  double get_fifteen_minute_rate_seconds();

  // Metric implementation
  MetricType type() const override;
  const std::string name() const override;
  const boost::property_tree::ptree report_tree() override;
  const std::string report_str() override;
  void clear() override;

 private:
  const std::string unit_ = "events per second";
  std::string name_;
  std::shared_ptr<MeterClock> clock_;
  std::atomic<uint32_t> count_;
  std::shared_timed_mutex start_time_lock_;
  long start_time_micros_;

  // EWMA
  void tick_if_necessary();
  const long ewma_tick_interval_seconds_ = 5;
  std::atomic_long last_ewma_tick_micros_;
  EWMA m1_rate;
  EWMA m5_rate;
  EWMA m15_rate;

};

class ReservoirSampler {
 public:
  explicit ReservoirSampler(size_t sample_size);

  // Disallow copy and move
  ReservoirSampler(ReservoirSampler &other) = delete;
  ReservoirSampler &operator=(ReservoirSampler &other) = delete;
  ReservoirSampler(ReservoirSampler &&other) = delete;
  ReservoirSampler &operator=(ReservoirSampler &&other) = delete;

  void sample(const int64_t value);
  void clear();
  const std::vector<int64_t> snapshot() const;

 private:
  size_t sample_size_;
  size_t n_ = 0;
  std::vector<int64_t> reservoir_;

};

class HistogramStats {
 public:
  /** Constructs a HistogramStats object with all values zero **/
  explicit HistogramStats() {};
  explicit HistogramStats(size_t data_size,
                          int64_t min,
                          int64_t max,
                          double mean,
                          double std_dev,
                          double p50,
                          double p95,
                          double p99);

  size_t data_size_ = 0;
  int64_t min_ = 0;
  int64_t max_ = 0;
  double mean_ = 0;
  double std_dev_ = 0;
  double p50_ = 0;
  double p95_ = 0;
  double p99_ = 0;
};

class Histogram : public Metric {
 public:
  explicit Histogram(const std::string name, const std::string unit, const size_t sample_size);

  // Disallow copy and move
  Histogram(Histogram &other) = delete;
  Histogram &operator=(Histogram &other) = delete;
  Histogram(Histogram &&other) = delete;
  Histogram &operator=(Histogram &&other) = delete;

  void insert(const int64_t value);
  const HistogramStats compute_stats();
  static double percentile(std::vector<int64_t> snapshot, double rank);

  // Metric implementation
  MetricType type() const override;
  const std::string name() const override;
  const std::string report_str() override;
  const boost::property_tree::ptree report_tree() override;
  void clear() override;

 private:
  std::string name_;
  std::string unit_;
  ReservoirSampler sampler_;
  std::shared_timed_mutex sampler_lock_;

};

/**
 * Obtains a human readable string representation of the provided MetricType
 */
const std::string get_metrics_category_name(MetricType type);

/**
 * Singleton object that manages creation, logging, and persistence
 * of system metrics.
 */
class MetricsRegistry {

 public:
  /**
   * Obtains an instance of the MetricsRegistry singleton
   * that can be used to create new metrics
   */
  static MetricsRegistry &get_metrics();
  /**
   * @return A JSON-formatted string containing structured reports
   * of all metrics in the registry. The schema is as follows:
   * {
   *  "counters" : [{counter_name: counter_report}, {counter_name: counter_report}],
   *  "histograms": [{counter_name: counter_report}, {counter_name: counter_report}],
   *  ...
   * }
   */
  const std::string report_metrics(const bool clear=false);

  /** Creates a Counter with initial value zero */
  std::shared_ptr<Counter> create_counter(const std::string name);
  std::shared_ptr<Counter> create_counter(const std::string name, const int initial_count);
  /** Creates a RatioCounter with initial value zero */
  std::shared_ptr<RatioCounter> create_ratio_counter(const std::string name);
  std::shared_ptr<RatioCounter> create_ratio_counter(const std::string name, const uint32_t num, const uint32_t denom);
  std::shared_ptr<Meter> create_meter(const std::string name);
  std::shared_ptr<Histogram> create_histogram(const std::string name, const std::string unit, const size_t sample_size);

 private:
  MetricsRegistry();
  MetricsRegistry(MetricsRegistry &other) = delete;
  MetricsRegistry &operator=(MetricsRegistry &other) = delete;
  MetricsRegistry(MetricsRegistry &&other) = delete;
  MetricsRegistry &operator=(MetricsRegistry &&other) = delete;

  void manage_metrics();
  std::shared_ptr<vector<std::shared_ptr<Metric>>> metrics_;
  std::shared_ptr<std::mutex> metrics_lock_;

};

} // namespace metrics

} // namespace clipper

#endif //CLIPPER_METRICS_HPP

max_stars_repo_name: yujialuo/Clipper

max_issues_repo_name: yujialuo/Clipper

max_forks_repo_name: yujialuo/Clipper


text:
#pragma once

#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>

#include <array>
#include <tuple>
#include <string>
#include <queue>
#include <memory>
#include <chrono>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <cwctype>

#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS
#define _ATL_NO_AUTOMATIC_NAMESPACE
#define _WTL_NO_AUTOMATIC_NAMESPACE

#include <atlbase.h>
#include <atlstr.h>
#include <atlapp.h>

#define _WTL_NO_CSTRING
#include <atlmisc.h>

#include <atlwin.h>
#include <atlframe.h>
#include <atlcrack.h>

#include <imm.h>
#pragma comment(lib, "imm32.lib")

#include <usp10.h>
#pragma comment(lib, "usp10.lib")

#include <boost/cast.hpp>
#include <boost/operators.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/intrusive/list.hpp>
#include <boost/intrusive/list_hook.hpp>
#include <boost/signals2.hpp>
#include <boost/exception/all.hpp>
#include <boost/optional.hpp>
#include <boost/utility.hpp>

#include "window_scheduler.hpp"

#include "schedulable_signal.hpp"

#include "observation.hpp"

#include "reactive.hpp"
#include "reactive_property.hpp"
#include "reactive_functions.hpp"

#include "function_command.hpp"

#include "window.hpp"
#include "message_loop.hpp"

#include "stack_view.hpp"
#include "dock_view.hpp"
#include "margin_view.hpp"
#include "limit_view.hpp"
#include "clip_view.hpp"
#include "rectangle_view.hpp"
#include "text_view.hpp"
#include "text_box_view.hpp"
#include "button_view.hpp"
#include "scroll_bar_view.hpp"
#include "scroll_view.hpp"

max_stars_repo_name: planaria/rewin

max_issues_repo_name: planaria/rewin

max_forks_repo_name: planaria/rewin


text:
#ifndef MYSQL_ASIO_IMPL_SERIALIZATION_HPP
#define MYSQL_ASIO_IMPL_SERIALIZATION_HPP

#include <boost/endian/conversion.hpp>
#include <boost/endian/buffers.hpp>
#include <boost/asio/buffer.hpp>
#include <vector>
#include <type_traits>
#include <cassert>
#include <algorithm>
#include <variant>
#include "mysql/impl/basic_types.hpp"
#include "mysql/impl/capabilities.hpp"
#include "mysql/error.hpp"

namespace mysql
{
namespace detail
{

class DeserializationContext
{
	ReadIterator first_;
	ReadIterator last_;
	capabilities capabilities_;
public:
	DeserializationContext(ReadIterator first, ReadIterator last, capabilities caps) noexcept:
		first_(first), last_(last), capabilities_(caps) { assert(last_ >= first_); };
	DeserializationContext(boost::asio::const_buffer buff, capabilities caps) noexcept:
		DeserializationContext(
				static_cast<const std::uint8_t*>(buff.data()),
				static_cast<const std::uint8_t*>(buff.data()) + buff.size(),
				caps
		) {};
	ReadIterator first() const noexcept { return first_; }
	ReadIterator last() const noexcept { return last_; }
	void set_first(ReadIterator new_first) noexcept { first_ = new_first; assert(last_ >= first_); }
	void advance(std::size_t sz) noexcept { first_ += sz; assert(last_ >= first_); }
	void rewind(std::size_t sz) noexcept { first_ -= sz; }
	std::size_t size() const noexcept { return last_ - first_; }
	bool empty() const noexcept { return last_ == first_; }
	bool enough_size(std::size_t required_size) const noexcept { return size() >= required_size; }
	capabilities get_capabilities() const noexcept { return capabilities_; }
	Error copy(void* to, std::size_t sz) noexcept
	{
		if (!enough_size(sz)) return Error::incomplete_message;
		memcpy(to, first_, sz);
		advance(sz);
		return Error::ok;
	}
};

class SerializationContext
{
	WriteIterator first_;
	capabilities capabilities_;
public:
	SerializationContext(capabilities caps, WriteIterator first = nullptr) noexcept:
		first_(first), capabilities_(caps) {};
	WriteIterator first() const noexcept { return first_; }
	void set_first(WriteIterator new_first) noexcept { first_ = new_first; }
	void set_first(boost::asio::mutable_buffer buff) noexcept { first_ = static_cast<std::uint8_t*>(buff.data()); }
	void advance(std::size_t size) noexcept { first_ += size; }
	capabilities get_capabilities() const noexcept { return capabilities_; }
	void write(const void* buffer, std::size_t size) noexcept { memcpy(first_, buffer, size); advance(size); }
	void write(std::uint8_t elm) noexcept { *first_ = elm; ++first_; }
};

/**
 * Base forms:
 *  Error deserialize(T& output, DeserializationContext&) noexcept
 *  void  serialize(const T& input, SerializationContext&) noexcept
 *  std::size_t get_size(const T& input, const SerializationContext&) noexcept
 */

// Fixed-size types
struct get_value_type_helper
{
    struct no_value_type {};

    template <typename T>
    static constexpr typename T::value_type get(typename T::value_type*);

    template <typename T>
    static constexpr no_value_type get(...);
};

template <typename T>
struct get_value_type
{
    using type = decltype(get_value_type_helper().get<T>(nullptr));
    using no_value_type = get_value_type_helper::no_value_type;
};

template <typename T>
struct is_fixed_size
{
private:
	using value_type = typename get_value_type<T>::type;
public:
	static constexpr bool value =
			std::is_integral_v<value_type> &&
			std::is_base_of_v<value_holder<value_type>, T>;
};

// Serialization of these types relies on this fact
static_assert(std::numeric_limits<float>::is_iec559);
static_assert(std::numeric_limits<double>::is_iec559);

template <> struct is_fixed_size<int_lenenc> : std::false_type {};
template <std::size_t N> struct is_fixed_size<string_fixed<N>>: std::true_type {};

template <typename T> constexpr bool is_fixed_size_v = is_fixed_size<T>::value;

template <typename T>
struct get_fixed_size
{
	static_assert(is_fixed_size_v<T>);
	static constexpr std::size_t value = sizeof(T::value);
};

template <> struct get_fixed_size<int3> { static constexpr std::size_t value = 3; };
template <> struct get_fixed_size<int6> { static constexpr std::size_t value = 6; };
template <std::size_t N> struct get_fixed_size<string_fixed<N>> { static constexpr std::size_t value = N; };

template <typename T> void little_to_native_inplace(value_holder<T>& value) noexcept { boost::endian::little_to_native_inplace(value.value); }
template <std::size_t size> void little_to_native_inplace(string_fixed<size>&) noexcept {}

template <typename T> void native_to_little_inplace(value_holder<T>& value) noexcept { boost::endian::native_to_little_inplace(value.value); }
template <std::size_t size> void native_to_little_inplace(string_fixed<size>&) noexcept {}

template <typename T>
std::enable_if_t<is_fixed_size_v<T>, Error>
deserialize(T& output, DeserializationContext& ctx) noexcept
{
	static_assert(std::is_standard_layout_v<decltype(T::value)>);

	constexpr auto size = get_fixed_size<T>::value;
	if (!ctx.enough_size(size))
	{
		return Error::incomplete_message;
	}

	memset(&output.value, 0, sizeof(output.value));
	memcpy(&output.value, ctx.first(), size);
	little_to_native_inplace(output);
	ctx.advance(size);

	return Error::ok;
}

template <typename T>
std::enable_if_t<is_fixed_size_v<T>>
serialize(T input, SerializationContext& ctx) noexcept
{
	native_to_little_inplace(input);
	ctx.write(&input.value, get_fixed_size<T>::value);
}

template <typename T>
constexpr std::enable_if_t<is_fixed_size_v<T>, std::size_t>
get_size(T, const SerializationContext&) noexcept
{
	return get_fixed_size<T>::value;
}

// int_lenenc
inline Error deserialize(int_lenenc& output, DeserializationContext& ctx) noexcept
{
	int1 first_byte;
	Error err = deserialize(first_byte, ctx);
	if (err != Error::ok)
	{
		return err;
	}

	if (first_byte.value == 0xFC)
	{
		int2 value;
		err = deserialize(value, ctx);
		output.value = value.value;
	}
	else if (first_byte.value == 0xFD)
	{
		int3 value;
		err = deserialize(value, ctx);
		output.value = value.value;
	}
	else if (first_byte.value == 0xFE)
	{
		int8 value;
		err = deserialize(value, ctx);
		output.value = value.value;
	}
	else
	{
		err = Error::ok;
		output.value = first_byte.value;
	}
	return err;
}
inline void serialize(int_lenenc input, SerializationContext& ctx) noexcept
{
	if (input.value < 251)
	{
		serialize(int1(static_cast<std::uint8_t>(input.value)), ctx);
	}
	else if (input.value < 0x10000)
	{
		ctx.write(0xfc);
		serialize(int2(static_cast<std::uint16_t>(input.value)), ctx);
	}
	else if (input.value < 0x1000000)
	{
		ctx.write(0xfd);
		serialize(int3(static_cast<std::uint32_t>(input.value)), ctx);
	}
	else
	{
		ctx.write(0xfe);
		serialize(int8(static_cast<std::uint64_t>(input.value)), ctx);
	}
}
inline std::size_t get_size(int_lenenc input, const SerializationContext&) noexcept
{
	if (input.value < 251) return 1;
	else if (input.value < 0x10000) return 3;
	else if (input.value < 0x1000000) return 4;
	else return 9;
}

// Helper for strings
inline std::string_view get_string(ReadIterator from, std::size_t size)
{
	return std::string_view (reinterpret_cast<const char*>(from), size);
}

// string_null
inline Error deserialize(string_null& output, DeserializationContext& ctx) noexcept
{
	ReadIterator string_end = std::find(ctx.first(), ctx.last(), 0);
	if (string_end == ctx.last())
	{
		return Error::incomplete_message;
	}
	output.value = get_string(ctx.first(), string_end-ctx.first());
	ctx.set_first(string_end + 1); // skip the null terminator
	return Error::ok;
}
inline void serialize(string_null input, SerializationContext& ctx) noexcept
{
	ctx.write(input.value.data(), input.value.size());
	ctx.write(0); // null terminator
}
inline std::size_t get_size(string_null input, const SerializationContext&) noexcept
{
	return input.value.size() + 1;
}

// string_eof
inline Error deserialize(string_eof& output, DeserializationContext& ctx) noexcept
{
	output.value = get_string(ctx.first(), ctx.last()-ctx.first());
	ctx.set_first(ctx.last());
	return Error::ok;
}
inline void serialize(string_eof input, SerializationContext& ctx) noexcept
{
	ctx.write(input.value.data(), input.value.size());
}
inline std::size_t get_size(string_eof input, const SerializationContext&) noexcept
{
	return input.value.size();
}

// string_lenenc
inline Error deserialize(string_lenenc& output, DeserializationContext& ctx) noexcept
{
	int_lenenc length;
	Error err = deserialize(length, ctx);
	if (err != Error::ok)
	{
		return err;
	}
	if (!ctx.enough_size(length.value))
	{
		return Error::incomplete_message;
	}

	output.value = get_string(ctx.first(), length.value);
	ctx.advance(length.value);
	return Error::ok;
}
inline void serialize(string_lenenc input, SerializationContext& ctx) noexcept
{
	int_lenenc length;
	length.value = input.value.size();
	serialize(length, ctx);
	ctx.write(input.value.data(), input.value.size());
}
inline std::size_t get_size(string_lenenc input, const SerializationContext& ctx) noexcept
{
	int_lenenc length;
	length.value = input.value.size();
	return get_size(length, ctx) + input.value.size();
}

// Enums
template <typename T, typename=std::enable_if_t<std::is_enum_v<T>>>
Error deserialize(T& output, DeserializationContext& ctx) noexcept
{
	value_holder<std::underlying_type_t<T>> value;
	Error err = deserialize(value, ctx);
	if (err != Error::ok)
	{
		return err;
	}
	output = static_cast<T>(value.value);
	return Error::ok;
}

template <typename T, typename=std::enable_if_t<std::is_enum_v<T>>>
void serialize(T input, SerializationContext& ctx) noexcept
{
	value_holder<std::underlying_type_t<T>> value {static_cast<std::underlying_type_t<T>>(input)};
	serialize(value, ctx);
}

template <typename T, typename=std::enable_if_t<std::is_enum_v<T>>>
std::size_t get_size(T, const SerializationContext&) noexcept
{
	return get_fixed_size<value_holder<std::underlying_type_t<T>>>::value;
}

// Floating points
template <typename T, typename=std::enable_if_t<std::is_floating_point_v<T>>>
Error deserialize(value_holder<T>& output, DeserializationContext& ctx) noexcept
{
	// Size check
	if (!ctx.enough_size(sizeof(T))) return Error::incomplete_message;

	// Endianness conversion
	// Boost.Endian support for floats start at 1.71. TODO: maybe update requirements and CI
#if BOOST_ENDIAN_BIG_BYTE
	char buf [sizeof(T)];
	std::memcpy(buf, ctx.first(), sizeof(T));
	std::reverse(buf, buf + sizeof(T));
	std::memcpy(&output.value, buf, sizeof(T));
#else
	std::memcpy(&output.value, ctx.first(), sizeof(T));
#endif
	ctx.advance(sizeof(T));
	return Error::ok;
}

template <typename T, typename=std::enable_if_t<std::is_floating_point_v<T>>>
void serialize(const value_holder<T>& input, SerializationContext& ctx) noexcept
{
	// Endianness conversion
#if BOOST_ENDIAN_BIG_BYTE
	char buf [sizeof(T)];
	std::memcpy(buf, &input.value, sizeof(T));
	std::reverse(buf, buf + sizeof(T));
	ctx.write(buf, sizeof(T));
#else
	ctx.write(&input.value, sizeof(T));
#endif
}

template <typename T, typename=std::enable_if_t<std::is_floating_point_v<T>>>
std::size_t get_size(const value_holder<T>&, const SerializationContext&) noexcept
{
	return sizeof(T);
}

// Structs. To allow a limited way of reflection, structs should
// specialize get_struct_fields with a tuple of pointers to members,
// thus defining which fields should be (de)serialized in the struct
// and in which order
struct not_a_struct_with_fields {}; // Tag indicating a type is not a struct with fields

template <typename T>
struct get_struct_fields
{
	static constexpr not_a_struct_with_fields value {};
};

template <typename T>
struct is_struct_with_fields
{
	static constexpr bool value = !std::is_same_v<
		std::decay_t<decltype(get_struct_fields<T>::value)>,
		not_a_struct_with_fields
	>;
};

struct is_command_helper
{
    template <typename T>
    static constexpr std::true_type get(decltype(T::command_id)*);

    template <typename T>
    static constexpr std::false_type get(...);
};

template <typename T>
struct is_command : decltype(is_command_helper::get<T>(nullptr))
{
};

template <std::size_t index, typename T>
Error deserialize_struct(
	[[maybe_unused]] T& output,
	[[maybe_unused]] DeserializationContext& ctx
) noexcept
{
	constexpr auto fields = get_struct_fields<T>::value;
	if constexpr (index == std::tuple_size<decltype(fields)>::value)
	{
		return Error::ok;
	}
	else
	{
		constexpr auto pmem = std::get<index>(fields);
		Error err = deserialize(output.*pmem, ctx);
		if (err != Error::ok)
		{
			return err;
		}
		else
		{
			return deserialize_struct<index+1>(output, ctx);
		}
	}
}

template <typename T>
std::enable_if_t<is_struct_with_fields<T>::value, Error>
deserialize(T& output, DeserializationContext& ctx) noexcept
{
	return deserialize_struct<0>(output, ctx);
}

template <std::size_t index, typename T>
void serialize_struct(
	[[maybe_unused]] const T& value,
	[[maybe_unused]] SerializationContext& ctx
) noexcept
{
	constexpr auto fields = get_struct_fields<T>::value;
	if constexpr (index < std::tuple_size<decltype(fields)>::value)
	{
		auto pmem = std::get<index>(fields);
		serialize(value.*pmem, ctx);
		serialize_struct<index+1>(value, ctx);
	}
}

template <typename T>
std::enable_if_t<is_struct_with_fields<T>::value>
serialize(
	[[maybe_unused]] const T& input,
	[[maybe_unused]] SerializationContext& ctx
) noexcept
{
	// For commands, add the command ID. Commands are only sent by the client,
	// so this is not considered in the deserialization functions.
	if constexpr (is_command<T>::value)
	{
		serialize(int1(T::command_id), ctx);
	}
	serialize_struct<0>(input, ctx);
}

template <std::size_t index, typename T>
std::size_t get_size_struct(
	[[maybe_unused]] const T& input,
	[[maybe_unused]] const SerializationContext& ctx
) noexcept
{
	constexpr auto fields = get_struct_fields<T>::value;
	if constexpr (index == std::tuple_size<decltype(fields)>::value)
	{
		return 0;
	}
	else
	{
		constexpr auto pmem = std::get<index>(fields);
		return get_size_struct<index+1>(input, ctx) +
		       get_size(input.*pmem, ctx);
	}
}

template <typename T>
std::enable_if_t<is_struct_with_fields<T>::value, std::size_t>
get_size(const T& input, const SerializationContext& ctx) noexcept
{
	std::size_t res = is_command<T>::value ? 1 : 0;
	res += get_size_struct<0>(input, ctx);
	return res;
}

// Helper to write custom struct (de)serialize()
template <typename FirstType>
Error deserialize_fields(DeserializationContext& ctx, FirstType& field) noexcept { return deserialize(field, ctx); }

template <typename FirstType, typename... Types>
Error deserialize_fields(DeserializationContext& ctx, FirstType& field, Types&... fields_tail) noexcept
{
	Error err = deserialize(field, ctx);
	if (err == Error::ok)
	{
		err = deserialize_fields(ctx, fields_tail...);
	}
	return err;
}

template <typename FirstType>
void serialize_fields(SerializationContext& ctx, const FirstType& field) noexcept { serialize(field, ctx); }

template <typename FirstType, typename... Types>
void serialize_fields(SerializationContext& ctx, const FirstType& field, const Types&... fields_tail)
{
	serialize(field, ctx);
	serialize_fields(ctx, fields_tail...);
}

// Dummy type to indicate no (de)serialization is required
struct dummy_serializable
{
	dummy_serializable(...) {} // Make it constructible from anything
};
inline std::size_t get_size(dummy_serializable, const SerializationContext&) noexcept { return 0; }
inline void serialize(dummy_serializable, SerializationContext&) noexcept {}
inline Error deserialize(dummy_serializable, DeserializationContext&) noexcept { return Error::ok; }

}
}

#endif

max_stars_repo_name: dendisuhubdy/mysql-asio

max_issues_repo_name: dendisuhubdy/mysql-asio

max_forks_repo_name: dendisuhubdy/mysql-asio


text:
#ifndef BOOST_ARCHIVE_DETAIL_ISERIALIZER_HPP
#define BOOST_ARCHIVE_DETAIL_ISERIALIZER_HPP

// MS compatible compilers support #pragma once
#if defined(BOOST_MSVC)
# pragma once
#if !defined(__clang__)
#pragma inline_depth(255)
#pragma inline_recursion(on)
#endif
#endif

#if defined(__MWERKS__)
#pragma inline_depth(255)
#endif

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// iserializer.hpp: interface for serialization system.

// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to 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)

//  See http://www.boost.org for updates, documentation, and revision history.

#include <new>     // for placement new
#include <cstddef> // size_t, NULL

#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
#if defined(BOOST_NO_STDC_NAMESPACE)
namespace std{
    using ::size_t;
} // namespace std
#endif

#include <boost/static_assert.hpp>

#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/mpl/greater_equal.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/core/no_exceptions_support.hpp>

#ifndef BOOST_SERIALIZATION_DEFAULT_TYPE_INFO
    #include <boost/serialization/extended_type_info_typeid.hpp>
#endif
#include <boost/serialization/throw_exception.hpp>
#include <boost/serialization/smart_cast.hpp>
#include <boost/serialization/static_warning.hpp>

#include <boost/type_traits/is_pointer.hpp>
#include <boost/type_traits/is_enum.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/type_traits/remove_extent.hpp>
#include <boost/type_traits/is_polymorphic.hpp>

#include <boost/serialization/assume_abstract.hpp>

#if !defined(BOOST_MSVC) && \
    (BOOST_WORKAROUND(__IBMCPP__, < 1210) || \
    defined(__SUNPRO_CC) && (__SUNPRO_CC < 0x590))
    #define BOOST_SERIALIZATION_DONT_USE_HAS_NEW_OPERATOR 1
#else
    #define BOOST_SERIALIZATION_DONT_USE_HAS_NEW_OPERATOR 0
#endif

#if ! BOOST_SERIALIZATION_DONT_USE_HAS_NEW_OPERATOR
#include <boost/type_traits/has_new_operator.hpp>
#endif

#include <boost/serialization/serialization.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/level.hpp>
#include <boost/serialization/tracking.hpp>
#include <boost/serialization/type_info_implementation.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/void_cast.hpp>
#include <boost/serialization/collection_size_type.hpp>
#include <boost/serialization/singleton.hpp>
#include <boost/serialization/wrapper.hpp>
#include <boost/serialization/array_wrapper.hpp>

// the following is need only for dynamic cast of polymorphic pointers
#include <boost/archive/archive_exception.hpp>
#include <boost/archive/detail/basic_iarchive.hpp>
#include <boost/archive/detail/basic_iserializer.hpp>
#include <boost/archive/detail/basic_pointer_iserializer.hpp>
#include <boost/archive/detail/archive_serializer_map.hpp>
#include <boost/archive/detail/check.hpp>

#include <boost/core/addressof.hpp>

namespace boost {

namespace serialization {
    class extended_type_info;
} // namespace serialization

namespace archive {

// an accessor to permit friend access to archives.  Needed because
// some compilers don't handle friend templates completely
class load_access {
public:
    template<class Archive, class T>
    static void load_primitive(Archive &ar, T &t){
        ar.load(t);
    }
};

namespace detail {

#ifdef BOOST_MSVC
#  pragma warning(push)
#  pragma warning(disable : 4511 4512)
#endif

template<class Archive, class T>
class iserializer : public basic_iserializer
{
private:
    void destroy(/*const*/ void *address) const BOOST_OVERRIDE {
        boost::serialization::access::destroy(static_cast<T *>(address));
    }
public:
    explicit iserializer() :
        basic_iserializer(
            boost::serialization::singleton<
                typename
                boost::serialization::type_info_implementation< T >::type
            >::get_const_instance()
        )
    {}
    BOOST_DLLEXPORT void load_object_data(
        basic_iarchive & ar,
        void *x,
        const unsigned int file_version
    ) const BOOST_OVERRIDE BOOST_USED;
    bool class_info() const BOOST_OVERRIDE {
        return boost::serialization::implementation_level< T >::value
            >= boost::serialization::object_class_info;
    }
    bool tracking(const unsigned int /* flags */) const BOOST_OVERRIDE {
        return boost::serialization::tracking_level< T >::value
                == boost::serialization::track_always
            || ( boost::serialization::tracking_level< T >::value
                == boost::serialization::track_selectively
                && serialized_as_pointer());
    }
    version_type version() const BOOST_OVERRIDE {
        return version_type(::boost::serialization::version< T >::value);
    }
    bool is_polymorphic() const BOOST_OVERRIDE {
        return boost::is_polymorphic< T >::value;
    }
    ~iserializer() BOOST_OVERRIDE {}
};

#ifdef BOOST_MSVC
#  pragma warning(pop)
#endif

template<class Archive, class T>
BOOST_DLLEXPORT void iserializer<Archive, T>::load_object_data(
    basic_iarchive & ar,
    void *x,
    const unsigned int file_version
) const {
    // note: we now comment this out. Before we permited archive
    // version # to be very large.  Now we don't.  To permit
    // readers of these old archives, we have to suppress this
    // code.  Perhaps in the future we might re-enable it but
    // permit its suppression with a runtime switch.
    #if 0
    // trap case where the program cannot handle the current version
    if(file_version > static_cast<const unsigned int>(version()))
        boost::serialization::throw_exception(
            archive::archive_exception(
                boost::archive::archive_exception::unsupported_class_version,
                get_debug_info()
            )
        );
    #endif
    // make sure call is routed through the higest interface that might
    // be specialized by the user.
    boost::serialization::serialize_adl(
        boost::serialization::smart_cast_reference<Archive &>(ar),
        * static_cast<T *>(x),
        file_version
    );
}

#ifdef BOOST_MSVC
#  pragma warning(push)
#  pragma warning(disable : 4511 4512)
#endif

// the purpose of this code is to allocate memory for an object
// without requiring the constructor to be called.  Presumably
// the allocated object will be subsequently initialized with
// "placement new".
// note: we have the boost type trait has_new_operator but we
// have no corresponding has_delete_operator.  So we presume
// that the former being true would imply that the a delete
// operator is also defined for the class T.

template<class T>
struct heap_allocation {
    // boost::has_new_operator< T > doesn't work on these compilers
    #if BOOST_SERIALIZATION_DONT_USE_HAS_NEW_OPERATOR
        // This doesn't handle operator new overload for class T
        static T * invoke_new(){
            return static_cast<T *>(operator new(sizeof(T)));
        }
        static void invoke_delete(T *t){
            (operator delete(t));
        }
    #else
        // note: we presume that a true value for has_new_operator
        // implies the existence of a class specific delete operator as well
        // as a class specific new operator.
        struct has_new_operator {
            static T * invoke_new() {
                return static_cast<T *>((T::operator new)(sizeof(T)));
            }
            static void invoke_delete(T * t) {
                // if compilation fails here, the likely cause that the class
                // T has a class specific new operator but no class specific
                // delete operator which matches the following signature.
                // note that this solution addresses the issue that two
                // possible signatures.  But it doesn't address the possibility
                // that the class might have class specific new with NO
                // class specific delete at all.  Patches (compatible with
                // C++03) welcome!
                (operator delete)(t);
            }
        };
        struct doesnt_have_new_operator {
            static T* invoke_new() {
                return static_cast<T *>(operator new(sizeof(T)));
            }
            static void invoke_delete(T * t) {
                // Note: I'm reliance upon automatic conversion from T * to void * here
                (operator delete)(t);
            }
        };
        static T * invoke_new() {
            typedef typename
                mpl::eval_if<
                    boost::has_new_operator< T >,
                    mpl::identity<has_new_operator >,
                    mpl::identity<doesnt_have_new_operator >
                >::type typex;
            return typex::invoke_new();
        }
        static void invoke_delete(T *t) {
            typedef typename
                mpl::eval_if<
                    boost::has_new_operator< T >,
                    mpl::identity<has_new_operator >,
                    mpl::identity<doesnt_have_new_operator >
                >::type typex;
            typex::invoke_delete(t);
        }
    #endif
    explicit heap_allocation(){
        m_p = invoke_new();
    }
    ~heap_allocation(){
        if (0 != m_p)
            invoke_delete(m_p);
    }
    T* get() const {
        return m_p;
    }

    T* release() {
        T* p = m_p;
        m_p = 0;
        return p;
    }
private:
    T* m_p;
};

template<class Archive, class T>
class pointer_iserializer :
    public basic_pointer_iserializer
{
private:
    void * heap_allocation() const BOOST_OVERRIDE {
        detail::heap_allocation<T> h;
        T * t = h.get();
        h.release();
        return t;
    }
    const basic_iserializer & get_basic_serializer() const BOOST_OVERRIDE {
        return boost::serialization::singleton<
            iserializer<Archive, T>
        >::get_const_instance();
    }
    BOOST_DLLEXPORT void load_object_ptr(
        basic_iarchive & ar,
        void * x,
        const unsigned int file_version
    ) const BOOST_OVERRIDE BOOST_USED;
public:
    // this should alway be a singleton so make the constructor protected
    pointer_iserializer();
    ~pointer_iserializer() BOOST_OVERRIDE;
};

#ifdef BOOST_MSVC
#  pragma warning(pop)
#endif

// note: BOOST_DLLEXPORT is so that code for polymorphic class
// serialized only through base class won't get optimized out
template<class Archive, class T>
BOOST_DLLEXPORT void pointer_iserializer<Archive, T>::load_object_ptr(
    basic_iarchive & ar,
    void * t,
    const unsigned int file_version
) const
{
    Archive & ar_impl =
        boost::serialization::smart_cast_reference<Archive &>(ar);

    // note that the above will throw std::bad_alloc if the allocation
    // fails so we don't have to address this contingency here.

    // catch exception during load_construct_data so that we don't
    // automatically delete the t which is most likely not fully
    // constructed
    BOOST_TRY {
        // this addresses an obscure situation that occurs when
        // load_constructor de-serializes something through a pointer.
        ar.next_object_pointer(t);
        boost::serialization::load_construct_data_adl<Archive, T>(
            ar_impl,
            static_cast<T *>(t),
            file_version
        );
    }
    BOOST_CATCH(...){
        // if we get here the load_construct failed.  The heap_allocation
        // will be automatically deleted so we don't have to do anything
        // special here.
        BOOST_RETHROW;
    }
    BOOST_CATCH_END

    ar_impl >> boost::serialization::make_nvp(NULL, * static_cast<T *>(t));
}

template<class Archive, class T>
pointer_iserializer<Archive, T>::pointer_iserializer() :
    basic_pointer_iserializer(
        boost::serialization::singleton<
            typename
            boost::serialization::type_info_implementation< T >::type
        >::get_const_instance()
    )
{
    boost::serialization::singleton<
        iserializer<Archive, T>
    >::get_mutable_instance().set_bpis(this);
    archive_serializer_map<Archive>::insert(this);
}

template<class Archive, class T>
pointer_iserializer<Archive, T>::~pointer_iserializer(){
    archive_serializer_map<Archive>::erase(this);
}

template<class Archive>
struct load_non_pointer_type {
    // note this bounces the call right back to the archive
    // with no runtime overhead
    struct load_primitive {
        template<class T>
        static void invoke(Archive & ar, T & t){
            load_access::load_primitive(ar, t);
        }
    };
    // note this bounces the call right back to the archive
    // with no runtime overhead
    struct load_only {
        template<class T>
        static void invoke(Archive & ar, const T & t){
            // short cut to user's serializer
            // make sure call is routed through the higest interface that might
            // be specialized by the user.
            boost::serialization::serialize_adl(
                ar,
                const_cast<T &>(t),
                boost::serialization::version< T >::value
            );
        }
    };

    // note this save class information including version
    // and serialization level to the archive
    struct load_standard {
        template<class T>
        static void invoke(Archive &ar, const T & t){
            void * x = boost::addressof(const_cast<T &>(t));
            ar.load_object(
                x,
                boost::serialization::singleton<
                    iserializer<Archive, T>
                >::get_const_instance()
            );
        }
    };

    struct load_conditional {
        template<class T>
        static void invoke(Archive &ar, T &t){
            //if(0 == (ar.get_flags() & no_tracking))
                load_standard::invoke(ar, t);
            //else
            //    load_only::invoke(ar, t);
        }
    };

    template<class T>
    static void invoke(Archive & ar, T &t){
        typedef typename mpl::eval_if<
                // if its primitive
                mpl::equal_to<
                    boost::serialization::implementation_level< T >,
                    mpl::int_<boost::serialization::primitive_type>
                >,
                mpl::identity<load_primitive>,
            // else
            typename mpl::eval_if<
            // class info / version
            mpl::greater_equal<
                        boost::serialization::implementation_level< T >,
                        mpl::int_<boost::serialization::object_class_info>
                    >,
            // do standard load
            mpl::identity<load_standard>,
        // else
        typename mpl::eval_if<
            // no tracking
                    mpl::equal_to<
                        boost::serialization::tracking_level< T >,
                        mpl::int_<boost::serialization::track_never>
                >,
                // do a fast load
                mpl::identity<load_only>,
            // else
            // do a fast load only tracking is turned off
            mpl::identity<load_conditional>
        > > >::type typex;
        check_object_versioning< T >();
        check_object_level< T >();
        typex::invoke(ar, t);
    }
};

template<class Archive>
struct load_pointer_type {
    struct abstract
    {
        template<class T>
        static const basic_pointer_iserializer * register_type(Archive & /* ar */){
            // it has? to be polymorphic
            BOOST_STATIC_ASSERT(boost::is_polymorphic< T >::value);
            return static_cast<basic_pointer_iserializer *>(NULL);
         }
    };

    struct non_abstract
    {
        template<class T>
        static const basic_pointer_iserializer * register_type(Archive & ar){
            return ar.register_type(static_cast<T *>(NULL));
        }
    };

    template<class T>
    static const basic_pointer_iserializer * register_type(Archive &ar, const T* const /*t*/){
        // there should never be any need to load an abstract polymorphic
        // class pointer.  Inhibiting code generation for this
        // permits abstract base classes to be used - note: exception
        // virtual serialize functions used for plug-ins
        typedef typename
            mpl::eval_if<
                boost::serialization::is_abstract<const T>,
                boost::mpl::identity<abstract>,
                boost::mpl::identity<non_abstract>
            >::type typex;
        return typex::template register_type< T >(ar);
    }

    template<class T>
    static T * pointer_tweak(
        const boost::serialization::extended_type_info & eti,
        void const * const t,
        const T &
    ) {
        // tweak the pointer back to the base class
        void * upcast = const_cast<void *>(
            boost::serialization::void_upcast(
                eti,
                boost::serialization::singleton<
                    typename
                    boost::serialization::type_info_implementation< T >::type
                >::get_const_instance(),
                t
            )
        );
        if(NULL == upcast)
            boost::serialization::throw_exception(
                archive_exception(archive_exception::unregistered_class)
            );
        return static_cast<T *>(upcast);
    }

    template<class T>
    static void check_load(T * const /* t */){
        check_pointer_level< T >();
        check_pointer_tracking< T >();
    }

    static const basic_pointer_iserializer *
    find(const boost::serialization::extended_type_info & type){
        return static_cast<const basic_pointer_iserializer *>(
            archive_serializer_map<Archive>::find(type)
        );
    }

    template<class Tptr>
    static void invoke(Archive & ar, Tptr & t){
        check_load(t);
        const basic_pointer_iserializer * bpis_ptr = register_type(ar, t);
        const basic_pointer_iserializer * newbpis_ptr = ar.load_pointer(
            // note major hack here !!!
            // I tried every way to convert Tptr &t (where Tptr might
            // include const) to void * &.  This is the only way
            // I could make it work. RR
            (void * & )t,
            bpis_ptr,
            find
        );
        // if the pointer isn't that of the base class
        if(newbpis_ptr != bpis_ptr){
            t = pointer_tweak(newbpis_ptr->get_eti(), t, *t);
        }
    }
};

template<class Archive>
struct load_enum_type {
    template<class T>
    static void invoke(Archive &ar, T &t){
        // convert integers to correct enum to load
        int i;
        ar >> boost::serialization::make_nvp(NULL, i);
        t = static_cast< T >(i);
    }
};

template<class Archive>
struct load_array_type {
    template<class T>
    static void invoke(Archive &ar, T &t){
        typedef typename remove_extent< T >::type value_type;

        // convert integers to correct enum to load
        // determine number of elements in the array. Consider the
        // fact that some machines will align elements on boundaries
        // other than characters.
        std::size_t current_count = sizeof(t) / (
            static_cast<char *>(static_cast<void *>(&t[1]))
            - static_cast<char *>(static_cast<void *>(&t[0]))
        );
        boost::serialization::collection_size_type count;
        ar >> BOOST_SERIALIZATION_NVP(count);
        if(static_cast<std::size_t>(count) > current_count)
            boost::serialization::throw_exception(
                archive::archive_exception(
                    boost::archive::archive_exception::array_size_too_short
                )
            );
        // explict template arguments to pass intel C++ compiler
        ar >> serialization::make_array<
            value_type,
            boost::serialization::collection_size_type
        >(
            static_cast<value_type *>(&t[0]),
            count
        );
    }
};

} // detail

template<class Archive, class T>
inline void load(Archive & ar, T &t){
    // if this assertion trips. It means we're trying to load a
    // const object with a compiler that doesn't have correct
    // function template ordering.  On other compilers, this is
    // handled below.
    detail::check_const_loading< T >();
    typedef
        typename mpl::eval_if<is_pointer< T >,
            mpl::identity<detail::load_pointer_type<Archive> >
        ,//else
        typename mpl::eval_if<is_array< T >,
            mpl::identity<detail::load_array_type<Archive> >
        ,//else
        typename mpl::eval_if<is_enum< T >,
            mpl::identity<detail::load_enum_type<Archive> >
        ,//else
            mpl::identity<detail::load_non_pointer_type<Archive> >
        >
        >
        >::type typex;
    typex::invoke(ar, t);
}

} // namespace archive
} // namespace boost

#endif // BOOST_ARCHIVE_DETAIL_ISERIALIZER_HPP


text:
/*
 * Deferred renderer file
 *
 * This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns)
 * See "SoftPixelEngine.hpp" for license information.
 */

#include "RenderSystem/AdvancedRenderer/spDeferredRenderer.hpp"

#if defined(SP_COMPILE_WITH_ADVANCEDRENDERER)

#include "RenderSystem/spRenderSystem.hpp"
#include "RenderSystem/spShaderClass.hpp"
#include "RenderSystem/spShaderResource.hpp"
#include "SceneGraph/spSceneGraph.hpp"
#include "Platform/spSoftPixelDevice.hpp"

#include <boost/foreach.hpp>

namespace sp
{

extern SoftPixelDevice* GlbEngineDev;
extern video::RenderSystem* GlbRenderSys;
extern scene::SceneGraph* GlbSceneGraph;

namespace video
{

#define ISFLAG(n) ((Config_.Flags & RENDERERFLAG_##n) != 0)

extern s32 GlbDfRnFlags;
extern s32 GlbDfRnLightGridRowSize;

DeferredRenderer::DeferredRenderer() :
    AdvancedRenderer        (ADVANCEDRENDERER_DEFERRED  ),
    GBufferShader_          (0                          ),
    DeferredShader_         (0                          ),
    LowResVPLShader_        (0                          ),
    UseDefaultGBufferShader_(true                       )
{
}
DeferredRenderer::~DeferredRenderer()
{
    releaseResources();
}

io::stringc DeferredRenderer::getDescription() const
{
    return "Deferred Renderer";
}

void DeferredRenderer::releaseResources()
{
    AdvancedRenderer::releaseResources();

    deleteAllShaders();
    GBuffer_.deleteGBuffer();
}

void DeferredRenderer::renderScene(scene::SceneGraph* Graph, scene::Camera* ActiveCamera)
{
    if (!Graph || !GBufferShader_ || !DeferredShader_)
    {
        #ifdef SP_DEBUGMODE
        io::Log::debug(
            "DeferredRenderer::renderScene",
            Graph != 0 ? "No valid shaders" : "No valid scene graph",
            io::LOG_UNIQUE
        );
        #endif
        return;
    }

    /* Get active camera */
    if (!getActiveCamera(Graph, ActiveCamera))
        return;

    /* Store flags in global space */
    GlbDfRnFlags = Config_.Flags;

    Texture* RenderTarget = GlbRenderSys->getRenderTarget();

    /* Update light sources and render scene */
    updateLightSources(Graph, ActiveCamera);

    renderSceneIntoGBuffer(Graph, ActiveCamera);

    if (ISFLAG(GLOBAL_ILLUMINATION) && ISFLAG(USE_VPL_OPTIMIZATION))
        renderLowResVPLShading();

    renderDeferredShading(RenderTarget);

    if (ISFLAG(BLOOM))
        BloomEffect_.drawEffect(RenderTarget);

    if (ISFLAG(DEBUG_VIRTUALPOINTLIGHTS) && DebugVPL_.Enabled)
        renderDebugVPLs(ActiveCamera);
}

void DeferredRenderer::setGIReflectivity(f32 Reflectivity)
{
    /* Store new GI reflectivity setting */
    AdvancedRenderer::setGIReflectivity(Reflectivity);

    /* Update deferred shader constant */
    if (DeferredShader_)
    {
        Shader* FragShd = DeferredShader_->getPixelShader();

        if (RenderSys_ == RENDERER_DIRECT3D11)
            FragShd->setConstantBuffer("BufferShading", &ShadingDesc_);
        else
            FragShd->setConstant("GIReflectivity", ShadingDesc_.GIReflectivity);
    }

    /* Update low-resolution VPL shader constant */
    if (LowResVPLShader_)
    {
        Shader* FragShd = LowResVPLShader_->getPixelShader();

        #if 0//!!!
        if (RenderSys_ == RENDERER_DIRECT3D11)
            //todo
        else
        #endif
            FragShd->setConstant("GIReflectivity", ShadingDesc_.GIReflectivity);
    }
}

void DeferredRenderer::setAmbientColor(const dim::vector3df &ColorVec)
{
    /* Store new color setting */
    AdvancedRenderer::setAmbientColor(ColorVec);

    /* Update shader constant */
    if (DeferredShader_)
    {
        Shader* FragShd = DeferredShader_->getPixelShader();

        if (RenderSys_ == RENDERER_DIRECT3D11)
            FragShd->setConstantBuffer("BufferShading", &ShadingDesc_);
        else
            FragShd->setConstant("AmbientColor", ShadingDesc_.AmbientColor);
    }
}

void DeferredRenderer::setResolution(const dim::size2di &Resolution)
{
    if (Resolution_ == Resolution)
        return;

    GBuffer_.setResolution(Resolution);

    AdvancedRenderer::setResolution(Resolution);
}

/*
 * ======= Protected: =======
 */

void DeferredRenderer::updateLightSources(scene::SceneGraph* Graph, scene::Camera* ActiveCamera)
{
    s32 i = 0, iEx = 0;
    AdvancedRenderer::updateLightSources(
        Graph, ActiveCamera,
        GBuffer_.getTexture(GBuffer::RENDERTARGET_NORMAL_AND_DEPTH),
        i, iEx
    );

    Shader* FragShd = 0;

    /* Update low-resolution VPL shader constants */
    if (ISFLAG(USE_VPL_OPTIMIZATION))
    {
        FragShd = LowResVPLShader_->getPixelShader();

        FragShd->setConstant("LightCount", i);

        FragShd->setConstantBuffer("BufferLight", Lights_.getArray());
        FragShd->setConstantBuffer("BufferLightEx", LightsEx_.getArray());
    }

    /* Update deferred shader constants */
    FragShd = DeferredShader_->getPixelShader();

    if (RenderSys_ == RENDERER_DIRECT3D11)
    {
        ShadingDesc_.LightCount = i;
        FragShd->setConstantBuffer("BufferShading", &ShadingDesc_);
    }
    else
        FragShd->setConstant(LightDesc_.LightCountConstant, i);

    FragShd->setConstantBuffer("BufferLight", Lights_.getArray());
    FragShd->setConstantBuffer("BufferLightEx", LightsEx_.getArray());
}

void DeferredRenderer::renderSceneIntoGBuffer(scene::SceneGraph* Graph, scene::Camera* ActiveCamera)
{
    ShaderClass* PrevShaderClass = 0;

    if (UseDefaultGBufferShader_)
    {
        PrevShaderClass = GlbRenderSys->getGlobalShaderClass();
        GlbRenderSys->setGlobalShaderClass(GBufferShader_);
    }

    GBuffer_.bindRenderTargets();
    GlbRenderSys->clearBuffers();

    GlbEngineDev->setActiveSceneGraph(Graph);

    if (ActiveCamera)
        Graph->renderScene(ActiveCamera);
    else
        Graph->renderScene();

    if (UseDefaultGBufferShader_)
        GlbRenderSys->setGlobalShaderClass(PrevShaderClass);
}

void DeferredRenderer::renderLowResVPLShading()
{
    GlbRenderSys->setRenderTarget(GBuffer_.getTexture(GBuffer::RENDERTARGET_LOWRES_VPL));

    GlbRenderSys->setRenderMode(RENDERMODE_DRAWING_2D);
    LowResVPLShader_->bind();
    {
        /* Bind shadow map texture-array and draw low-resolution VPL deferred-shading */
        ShadowMapper_.bind(1);

        GBuffer_.drawLowResVPLDeferredShading();

        ShadowMapper_.unbind(1);
    }
    LowResVPLShader_->unbind();

    GlbRenderSys->setRenderTarget(0);
}

void DeferredRenderer::renderDeferredShading(Texture* RenderTarget)
{
    /* Get shadow map layer base index */
    s32 ShadowMapLayerBase = 2;
    s32 NextLayerBase = 0;

    if (ISFLAG(HAS_LIGHT_MAP))
        ++ShadowMapLayerBase;
    if (ISFLAG(USE_VPL_OPTIMIZATION))
        ++ShadowMapLayerBase;

    /* Draw deferred shading 2D quad */
    if (ISFLAG(BLOOM))
        BloomEffect_.bindRenderTargets();
    else
        GlbRenderSys->setRenderTarget(RenderTarget);

    GlbRenderSys->setRenderMode(RENDERMODE_DRAWING_2D);
    DeferredShader_->bind();
    {
        /* Bind texture layers for deferred-rendering */
        NextLayerBase = ShadowMapper_.bind(ShadowMapLayerBase);

        if (ISFLAG(TILED_SHADING))
            LightGrid_.bind(NextLayerBase);

        /* Draw the deferred shading 2D quad */
        GBuffer_.drawDeferredShading();

        /* Unbind texture layers for deferred-rendering */
        NextLayerBase = ShadowMapper_.unbind(ShadowMapLayerBase);

        if (ISFLAG(TILED_SHADING))
            LightGrid_.unbind(NextLayerBase);
    }
    DeferredShader_->unbind();

    GlbRenderSys->setRenderTarget(0);
}

bool DeferredRenderer::loadAllShaders()
{
    return
        AdvancedRenderer::loadAllShaders() &&
        loadGBufferShader               () &&
        loadDeferredShader              () &&
        loadLowResVPLShader             ();
}

void DeferredRenderer::deleteAllShaders()
{
    AdvancedRenderer::deleteAllShaders();

    deleteShader(GBufferShader_     );
    deleteShader(DeferredShader_    );
    deleteShader(LowResVPLShader_   );
}

bool DeferredRenderer::setupFinalResources()
{
    if (!AdvancedRenderer::setupFinalResources())
        return false;

    /* Bind light grid shader resoruces to deferred shader */
    if (ISFLAG(TILED_SHADING))
    {
        DeferredShader_->addShaderResource(LightGrid_.getLGShaderResource(),    RESOURCE_ACCESS_READ);
        DeferredShader_->addShaderResource(LightGrid_.getTLIShaderResource(),   RESOURCE_ACCESS_READ);

        #ifdef _DEB_DEPTH_EXTENT_
        DeferredShader_->addShaderResource(_debDepthExt_, RESOURCE_ACCESS_READ);
        #endif
    }

    /* Build g-buffer */
    if ( !GBuffer_.createGBuffer(
            Resolution_, Config_.MultiSampling, ISFLAG(HAS_LIGHT_MAP),
            ISFLAG(GLOBAL_ILLUMINATION) && ISFLAG(USE_VPL_OPTIMIZATION)) )
    {
        return false;
    }

    return true;
}

void DeferredRenderer::createVertexFormats()
{
    AdvancedRenderer::createVertexFormats();

    /* Create 2D image vertex format */
    ImageVertexFormat_.clear();

    ImageVertexFormat_.addCoord(DATATYPE_FLOAT, 2);
    ImageVertexFormat_.addTexCoord();
}

#undef ISFLAG

} // /namespace video

} // /namespace sp

#endif

// ================================================================================

max_stars_repo_name: rontrek/softpixel

max_issues_repo_name: rontrek/softpixel

max_forks_repo_name: rontrek/softpixel