<commit_before>#include <sstream>
#include <fstream>
#include <stdexcept>
#include <map>
#include <cmath>

#include "cvrp.h"
#include "tsplib_format.h"

namespace VrpSolver {

    unsigned int Cvrp::demand(unsigned int node_id) const {
        if ((1 > node_id) || (node_id > dimension_))
            throw std::out_of_range("error: in Cvrp::demand");
        return demands_[node_id];
    }

    int Cvrp::distance(unsigned int from, unsigned int to) const {
        if ((1 > from) || (from > dimension_) ||
            (1 > to) || (to > dimension_))
            throw std::out_of_range("error: in Cvrp::distance");

        const int index = (to > from) ? ((to-2)*(to-1)/2+(from-1)) :
                                        ((from-2)*(from-1)/2+(to-1));
        return distances_[index];
    }

    // 文字列strからtrim_char文字列に含まれている文字を削除
    void trim(std::string& str, const std::string& trim_char) {
        size_t pos;
        while ((pos = str.find_first_of(trim_char)) != std::string::npos)
            str.erase(pos, 1);
    }

    // セミコロン以後の文字列(空白の直前まで)を読み取る
    std::string get_parameter(std::ifstream& ifs) {
        std::string param;
        ifs >> param;
        while (param == ":") ifs >> param; // ":"は読み飛ばす
        return param;
    }

    enum TsplibKeyword {
        NAME=100, TYPE, COMMENT, DIMENSION, CAPACITY,
        EDGE_WEIGHT_TYPE, EDGE_WEIGHT_FORMAT, EDGE_DATA_FORMAT,
        NODE_COORD_TYPE, DISPLAY_DATA_TYPE,
        NODE_COORD_SECTION, DEPOT_SECTION, DEMAND_SECTION,
        EDGE_DATA_SECTION, EDGE_WEIGHT_SECTION,
        END_OF_FILE
    };

    std::map<std::string, TsplibKeyword> keyword_map = {
        { "NAME",                NAME },
        { "TYPE",                TYPE },
        { "COMMENT",             COMMENT },
        { "DIMENSION",           DIMENSION },
        { "CAPACITY",            CAPACITY },
        { "EDGE_WEIGHT_TYPE",      EDGE_WEIGHT_TYPE },
        { "EDGE_WEIGHT_FORMAT",  EDGE_WEIGHT_FORMAT },
        { "EDGE_DATA_FORMAT",    EDGE_DATA_FORMAT },
        { "NODE_COORD_TYPE",     NODE_COORD_TYPE },
        { "DISPLAY_DATA_TYPE",   DISPLAY_DATA_TYPE },
        { "NODE_COORD_SECTION",  NODE_COORD_SECTION },
        { "DEPOT_SECTION",       DEPOT_SECTION },
        { "DEMAND_SECTION",      DEMAND_SECTION },
        { "EDGE_DATA_SECTION",   EDGE_DATA_SECTION },
        { "EDGE_WEIGHT_SECTION", EDGE_WEIGHT_SECTION },
        { "EOF",                 END_OF_FILE }
    };

    // infileから情報を読み取りCvrpクラスをセットアップする
    void read_vrp(Cvrp& cvrp, const std::string &infile) {
        std::ifstream ifs(infile.c_str());
        if (!ifs)
            throw std::runtime_error("error: can't open file " + infile);

        std::string edge_weight_type,
                    edge_weight_format,
                    display_data_type;

        while (ifs) {
            std::string tsp_keyword;
            ifs >> tsp_keyword;
            if (ifs.eof()) break;
            trim(tsp_keyword, " :");
            switch (keyword_map[tsp_keyword]) {

                // The specification part
                case NAME :
                    cvrp.name_ = get_parameter(ifs);
                    break;
                case TYPE :
                    {
                        std::string not_use;
                        getline(ifs, not_use);
                    }
                    break;
                case COMMENT :
                    {
                        std::string not_use;
                        getline(ifs, not_use);
                    }
                    break;
                case DIMENSION :
                    cvrp.dimension_ = stoi(get_parameter(ifs));
                    break;
                case CAPACITY :
                    cvrp.capacity_ = stoi(get_parameter(ifs));
                    break;
                case EDGE_WEIGHT_TYPE :
                    edge_weight_type = get_parameter(ifs);
                    break;
                case EDGE_WEIGHT_FORMAT :
                    edge_weight_format = get_parameter(ifs);
                    break;
                case EDGE_DATA_FORMAT :
                    {
                        std::string not_use;
                        getline(ifs, not_use);
                        break;
                    }
                case NODE_COORD_TYPE :
                    {
                        std::string not_use;
                        getline(ifs, not_use);
                        break;
                    }
                case DISPLAY_DATA_TYPE :
                    display_data_type = get_parameter(ifs);
                    break;

                // The data part
                case NODE_COORD_SECTION :
                    {
                        int n=0, m, x, y; // m do not use
                        for (int i=0; i != cvrp.dimension_; i++) {
                            ifs >> m >> x >> y;
                            std::pair<int,int> c(x,y);
                            cvrp.coords_.push_back(c);
                        }
                        break;
                    }
                case DEPOT_SECTION :
                    {
                        cvrp.depot_ = stoi(get_parameter(ifs));
                        if (stoi(get_parameter(ifs)) != -1)
                            throw std::runtime_error("error:"
                                    "can't handle multiple depots");
                        break;
                    }
                case DEMAND_SECTION :
                    {
                        cvrp.demands_.push_back(0); // 0要素目は0にしておく
                        for (int i=1; i <= cvrp.dimension_; i++) {
                            unsigned int node_id, demand;
                            ifs >> node_id >> demand;
                            if (node_id != i)
                                throw std::runtime_error("error:"
                                        "DEMAND_SECTION format may be different");
                            cvrp.demands_.push_back(demand);
                        }
                        break;
                    }
                case EDGE_DATA_SECTION :
                    throw std::runtime_error("Sorry, can not handle 'EDGE_DATA_SECTION'");
                    break;
                case EDGE_WEIGHT_SECTION :
                    {
                        if (edge_weight_format != "LOWER_ROW")
                            throw std::runtime_error("Sorry, can not handle except EDGE_WEIGHT_FORMAT == LOWER_ROW");
                        for (int i=0; i < cvrp.dimension_; i++) {
                            for (int j=0; j < i; j++) {
                                int distance;
                                ifs >> distance;
                                cvrp.distances_.push_back(distance);
                            }
                        }
                        break;
                    }
                case END_OF_FILE :
                    // do nothing
                    break;
                default :
                    throw std::runtime_error("error: unknown keyword '" + tsp_keyword + "'");
                    break;
            }
        }

        // distancesの設定
        if (edge_weight_type != Tsplib::EdgeWeightType::EXPLICIT) {
            auto& distances = cvrp.distances_;
            auto& coords    = cvrp.coords_;
            for (int i=0; i < cvrp.dimension_; i++) {
                for (int j=0; j < i; j++) {
                    int dx = coords[j].first  - coords[i].first;
                    int dy = coords[j].second - coords[i].second;
                    distances.push_back(floor(sqrt(dx*dx + dy*dy)+0.5));
                }
            }
        }
    }
} // namespace VrpSolver
<commit_msg>ヘッダーの順序をアルファベット順に治した<commit_after>#include <cmath>
#include <fstream>
#include <map>
#include <sstream>
#include <stdexcept>

#include "cvrp.h"
#include "tsplib_format.h"

namespace VrpSolver {

    unsigned int Cvrp::demand(unsigned int node_id) const {
        if ((1 > node_id) || (node_id > dimension_))
            throw std::out_of_range("error: in Cvrp::demand");
        return demands_[node_id];
    }

    int Cvrp::distance(unsigned int from, unsigned int to) const {
        if ((1 > from) || (from > dimension_) ||
            (1 > to) || (to > dimension_))
            throw std::out_of_range("error: in Cvrp::distance");

        const int index = (to > from) ? ((to-2)*(to-1)/2+(from-1)) :
                                        ((from-2)*(from-1)/2+(to-1));
        return distances_[index];
    }

    // 文字列strからtrim_char文字列に含まれている文字を削除
    void trim(std::string& str, const std::string& trim_char) {
        size_t pos;
        while ((pos = str.find_first_of(trim_char)) != std::string::npos)
            str.erase(pos, 1);
    }

    // セミコロン以後の文字列(空白の直前まで)を読み取る
    std::string get_parameter(std::ifstream& ifs) {
        std::string param;
        ifs >> param;
        while (param == ":") ifs >> param; // ":"は読み飛ばす
        return param;
    }

    enum TsplibKeyword {
        NAME, TYPE, COMMENT, DIMENSION, CAPACITY,
        EDGE_WEIGHT_TYPE, EDGE_WEIGHT_FORMAT, EDGE_DATA_FORMAT,
        NODE_COORD_TYPE, DISPLAY_DATA_TYPE,
        NODE_COORD_SECTION, DEPOT_SECTION, DEMAND_SECTION,
        EDGE_DATA_SECTION, EDGE_WEIGHT_SECTION,
        END_OF_FILE
    };

    std::map<std::string, TsplibKeyword> keyword_map = {
        { "NAME",                NAME },
        { "TYPE",                TYPE },
        { "COMMENT",             COMMENT },
        { "DIMENSION",           DIMENSION },
        { "CAPACITY",            CAPACITY },
        { "EDGE_WEIGHT_TYPE",      EDGE_WEIGHT_TYPE },
        { "EDGE_WEIGHT_FORMAT",  EDGE_WEIGHT_FORMAT },
        { "EDGE_DATA_FORMAT",    EDGE_DATA_FORMAT },
        { "NODE_COORD_TYPE",     NODE_COORD_TYPE },
        { "DISPLAY_DATA_TYPE",   DISPLAY_DATA_TYPE },
        { "NODE_COORD_SECTION",  NODE_COORD_SECTION },
        { "DEPOT_SECTION",       DEPOT_SECTION },
        { "DEMAND_SECTION",      DEMAND_SECTION },
        { "EDGE_DATA_SECTION",   EDGE_DATA_SECTION },
        { "EDGE_WEIGHT_SECTION", EDGE_WEIGHT_SECTION },
        { "EOF",                 END_OF_FILE }
    };

    // infileから情報を読み取りCvrpクラスをセットアップする
    void read_vrp(Cvrp& cvrp, const std::string &infile) {
        std::ifstream ifs(infile.c_str());
        if (!ifs)
            throw std::runtime_error("error: can't open file " + infile);

        std::string edge_weight_type,
                    edge_weight_format,
                    display_data_type;

        while (ifs) {
            std::string tsp_keyword;
            ifs >> tsp_keyword;
            if (ifs.eof()) break;
            trim(tsp_keyword, " :");
            switch (keyword_map[tsp_keyword]) {

                // The specification part
                case NAME :
                    cvrp.name_ = get_parameter(ifs);
                    break;
                case TYPE :
                    {
                        std::string not_use;
                        getline(ifs, not_use);
                    }
                    break;
                case COMMENT :
                    {
                        std::string not_use;
                        getline(ifs, not_use);
                    }
                    break;
                case DIMENSION :
                    cvrp.dimension_ = stoi(get_parameter(ifs));
                    break;
                case CAPACITY :
                    cvrp.capacity_ = stoi(get_parameter(ifs));
                    break;
                case EDGE_WEIGHT_TYPE :
                    edge_weight_type = get_parameter(ifs);
                    break;
                case EDGE_WEIGHT_FORMAT :
                    edge_weight_format = get_parameter(ifs);
                    break;
                case EDGE_DATA_FORMAT :
                    {
                        std::string not_use;
                        getline(ifs, not_use);
                        break;
                    }
                case NODE_COORD_TYPE :
                    {
                        std::string not_use;
                        getline(ifs, not_use);
                        break;
                    }
                case DISPLAY_DATA_TYPE :
                    display_data_type = get_parameter(ifs);
                    break;

                // The data part
                case NODE_COORD_SECTION :
                    {
                        int n=0, m, x, y; // m do not use
                        for (int i=0; i != cvrp.dimension_; i++) {
                            ifs >> m >> x >> y;
                            std::pair<int,int> c(x,y);
                            cvrp.coords_.push_back(c);
                        }
                        break;
                    }
                case DEPOT_SECTION :
                    {
                        cvrp.depot_ = stoi(get_parameter(ifs));
                        if (stoi(get_parameter(ifs)) != -1)
                            throw std::runtime_error("error:"
                                    "can't handle multiple depots");
                        break;
                    }
                case DEMAND_SECTION :
                    {
                        cvrp.demands_.push_back(0); // 0要素目は0にしておく
                        for (int i=1; i <= cvrp.dimension_; i++) {
                            unsigned int node_id, demand;
                            ifs >> node_id >> demand;
                            if (node_id != i)
                                throw std::runtime_error("error:"
                                        "DEMAND_SECTION format may be different");
                            cvrp.demands_.push_back(demand);
                        }
                        break;
                    }
                case EDGE_DATA_SECTION :
                    throw std::runtime_error("Sorry, can not handle 'EDGE_DATA_SECTION'");
                    break;
                case EDGE_WEIGHT_SECTION :
                    {
                        if (edge_weight_format != "LOWER_ROW")
                            throw std::runtime_error("Sorry, can not handle except EDGE_WEIGHT_FORMAT == LOWER_ROW");
                        for (int i=0; i < cvrp.dimension_; i++) {
                            for (int j=0; j < i; j++) {
                                int distance;
                                ifs >> distance;
                                cvrp.distances_.push_back(distance);
                            }
                        }
                        break;
                    }
                case END_OF_FILE :
                    // do nothing
                    break;
                default :
                    throw std::runtime_error("error: unknown keyword '" + tsp_keyword + "'");
                    break;
            }
        }

        // distancesの設定
        if (edge_weight_type != Tsplib::EdgeWeightType::EXPLICIT) {
            auto& distances = cvrp.distances_;
            auto& coords    = cvrp.coords_;
            for (int i=0; i < cvrp.dimension_; i++) {
                for (int j=0; j < i; j++) {
                    int dx = coords[j].first  - coords[i].first;
                    int dy = coords[j].second - coords[i].second;
                    distances.push_back(floor(sqrt(dx*dx + dy*dy)+0.5));
                }
            }
        }
    }

} // namespace VrpSolver
<|endoftext|>


<commit_before>//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2021 Ryo Suzuki
//	Copyright (c) 2016-2021 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# include <Siv3D/DLL.hpp>
# include <Siv3D/Window.hpp>
# include <Siv3D/EngineLog.hpp>
# include "D3D11SwapChain.hpp"
# include <dwmapi.h>
# include <VersionHelpers.h>

namespace s3d
{
	namespace detail
	{
		[[nodiscard]]
		static double GetPerformanceFrequency()
		{
			::LARGE_INTEGER frequency;
			::QueryPerformanceFrequency(&frequency);
			return static_cast<double>(frequency.QuadPart);
		}

		[[nodiscard]]
		static double ToMillisec(const uint64 count)
		{
			static const double scale = 1'000 / GetPerformanceFrequency();
			return count * scale;
		}

		[[nodiscard]]
		static double GetDisplayRefreshPeriodMillisec()
		{
			DWM_TIMING_INFO timingInfo = {};
			timingInfo.cbSize = sizeof(DWM_TIMING_INFO);
			::DwmGetCompositionTimingInfo(nullptr, &timingInfo);
			return ToMillisec(timingInfo.qpcRefreshPeriod);
		}
	}

	D3D11SwapChain::D3D11SwapChain(const D3D11Device& device, HWND hWnd, const Size& frameBufferSize)
		: m_hWnd(hWnd)
		, m_device(device.getDevice())
		, m_context(device.getContext())
	{
		LOG_SCOPED_TRACE(U"D3D11SwapChain::D3D11SwapChain()");

		m_desc.Width		= frameBufferSize.x;
		m_desc.Height		= frameBufferSize.y;
		m_desc.Format		= DXGI_FORMAT_R8G8B8A8_UNORM;
		m_desc.Stereo		= FALSE;
		m_desc.SampleDesc	= { 1, 0 };
		m_desc.BufferUsage	= DXGI_USAGE_RENDER_TARGET_OUTPUT;
		m_desc.BufferCount	= 3;
		m_desc.Scaling		= DXGI_SCALING_STRETCH;
		m_desc.SwapEffect	= (IsWindows10OrGreater() ? DXGI_SWAP_EFFECT_FLIP_DISCARD : DXGI_SWAP_EFFECT_DISCARD);
		m_desc.AlphaMode	= DXGI_ALPHA_MODE_IGNORE;
		m_desc.Flags		= 0;

		// Swap chain を作成
		{
			LOG_TRACE(U"IDXGIFactory2::CreateSwapChainForHwnd()");
			if (FAILED(device.getDXGIFactory2()->CreateSwapChainForHwnd(
				m_device,
				hWnd,
				&m_desc,
				nullptr,
				nullptr,
				&m_swapChain1)))
			{
				throw EngineError(U"IDXGIFactory2::CreateSwapChainForHwnd() failed");
			}
		}

		{
			LOG_TRACE(U"IDXGIFactory1::MakeWindowAssociation()");

			constexpr uint32 flags = (DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER);

			if (FAILED(device.getDXGIFactory2()->MakeWindowAssociation(hWnd, flags)))
			{
				throw EngineError(U"IDXGIFactory2::MakeWindowAssociation() failed");
			}
		}

		{
			LOG_TRACE(U"IDXGIDevice2::SetMaximumFrameLatency()");

			if (ComPtr<IDXGIDevice2> pDXGIDevice;
				SUCCEEDED(device.getDeiviceComPtr().As(&pDXGIDevice)))
			{
				pDXGIDevice->SetMaximumFrameLatency(2);
			}
		}

		updateDisplayInfo();
		m_previousWindowBounds = Window::GetState().bounds;
	}

	D3D11SwapChain::~D3D11SwapChain()
	{

	}

	bool D3D11SwapChain::present(const bool vSync)
	{
		if (const Rect windowBounds = Window::GetState().bounds;
			windowBounds != m_previousWindowBounds)
		{
			updateDisplayInfo();

			m_previousWindowBounds = windowBounds;
		}

		//const bool vSync = (not m_targetFrameRateHz.has_value())
		//	|| ((30.0 <= m_targetFrameRateHz) && (AbsDiff(m_targetFrameRateHz.value(), m_displayFrequency) <= 3.0));

		return vSync ? presentVSync() : presentNonVSync();
	}

	double D3D11SwapChain::getDisplayFrequency() const noexcept
	{
		return m_displayFrequency;
	}

	//void D3D11SwapChain::setTargetFrameRateHz(const Optional<double>& targetFrameRateHz)
	//{
	//	m_targetFrameRateHz = targetFrameRateHz;
	//}

	//const Optional<double>& D3D11SwapChain::getTargetFrameRateHz() const noexcept
	//{
	//	return m_targetFrameRateHz;
	//}

	IDXGISwapChain1* D3D11SwapChain::getSwapChain1() const noexcept
	{
		return m_swapChain1.Get();
	}

	Optional<Rect> D3D11SwapChain::getFullscreenRect()
	{
		LOG_TRACE(U"D3D11SwapChain::getFullscreenRect()");

		ComPtr<IDXGIOutput> pOutput;
		if (FAILED(m_swapChain1->GetContainingOutput(&pOutput)))
		{
			return none;
		}

		DXGI_OUTPUT_DESC desc;
		if (FAILED(pOutput->GetDesc(&desc)))
		{
			return none;
		}

		return Rect(desc.DesktopCoordinates.left, desc.DesktopCoordinates.top,
			(desc.DesktopCoordinates.right - desc.DesktopCoordinates.left),
			(desc.DesktopCoordinates.bottom - desc.DesktopCoordinates.top));
	}

	void D3D11SwapChain::updateDisplayInfo()
	{
		ComPtr<IDXGIOutput> pOutput;
		if (FAILED(m_swapChain1->GetContainingOutput(&pOutput)))
		{
			return;
		}

		{
			double displayFrequency;

			DXGI_OUTPUT_DESC desc;
			if (SUCCEEDED(pOutput->GetDesc(&desc)))
			{
				DEVMODE devMode = {};
				devMode.dmSize = sizeof(DEVMODE);
				::EnumDisplaySettingsW(desc.DeviceName, ENUM_CURRENT_SETTINGS, &devMode);
				displayFrequency = devMode.dmDisplayFrequency;
			}
			else
			{
				displayFrequency = detail::GetDisplayRefreshPeriodMillisec();
			}

			if (displayFrequency != m_displayFrequency)
			{
				m_displayFrequency = displayFrequency;
				LOG_INFO(U"Display refresh rate: {:.1f} Hz"_fmt(m_displayFrequency));
			}
		}
	}

	bool D3D11SwapChain::presentVSync()
	{
		const HRESULT hr = m_swapChain1->Present(1, 0);

		if (hr == DXGI_STATUS_OCCLUDED)
		{
			::Sleep(static_cast<int32>((1000 / m_displayFrequency) * 0.9));
		}
		else if (hr == DXGI_ERROR_DEVICE_RESET)
		{
			LOG_FAIL(U"❌ IDXGISwapChain1::Present() failed (DXGI_ERROR_DEVICE_RESET)");
			return false;
		}
		else if (hr == DXGI_ERROR_DEVICE_REMOVED)
		{
			LOG_FAIL(U"❌ IDXGISwapChain1::Present() failed (DXGI_ERROR_DEVICE_REMOVED)");
			return false;
		}

		LARGE_INTEGER counter;
		::QueryPerformanceCounter(&counter);
		m_lastPresentTime = counter.QuadPart;

		return true;
	}

	bool D3D11SwapChain::presentNonVSync()
	{
		/*
		const double targetRefreshRateHz = m_targetFrameRateHz.value();
		const double targetRefreshPeriodMillisec = (1000.0 / targetRefreshRateHz);
		const double displayRefreshPeriodMillisec = detail::GetDisplayRefreshPeriodMillisec();

		LARGE_INTEGER counter;
		::QueryPerformanceCounter(&counter);

		{
			m_context->Flush();

			double timeToSleepMillisec = 0.0;
			::timeBeginPeriod(1);

			do
			{
				::QueryPerformanceCounter(&counter);
				const double timeSinceFlipMillisec = detail::ToMillisec(counter.QuadPart - m_lastPresentTime);

				timeToSleepMillisec = (targetRefreshPeriodMillisec - timeSinceFlipMillisec);

				if (timeToSleepMillisec > 0.0)
				{
					::Sleep(static_cast<int32>(timeToSleepMillisec));
				}
			} while (timeToSleepMillisec > 0.5);

			::timeEndPeriod(1);
		}
		*/

		const HRESULT hr = m_swapChain1->Present(0, 0);

		if (hr == DXGI_STATUS_OCCLUDED)
		{
			::Sleep(static_cast<int32>((1000 / m_displayFrequency) * 0.9));
		}
		else if (hr == DXGI_ERROR_DEVICE_RESET)
		{
			LOG_FAIL(U"❌ IDXGISwapChain::Present() failed (DXGI_ERROR_DEVICE_RESET)");
			return false;
		}
		else if (hr == DXGI_ERROR_DEVICE_REMOVED)
		{
			LOG_FAIL(U"❌ IDXGISwapChain::Present() failed (DXGI_ERROR_DEVICE_REMOVED)");
			return false;
		}

		//m_lastPresentTime = counter.QuadPart;

		return true;
	}
}
<commit_msg>[D3D11] fix #652<commit_after>//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2021 Ryo Suzuki
//	Copyright (c) 2016-2021 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# include <Siv3D/DLL.hpp>
# include <Siv3D/Window.hpp>
# include <Siv3D/EngineLog.hpp>
# include "D3D11SwapChain.hpp"
# include <dwmapi.h>
# include <VersionHelpers.h>

namespace s3d
{
	namespace detail
	{
		[[nodiscard]]
		static double GetPerformanceFrequency()
		{
			::LARGE_INTEGER frequency;
			::QueryPerformanceFrequency(&frequency);
			return static_cast<double>(frequency.QuadPart);
		}

		[[nodiscard]]
		static double ToMillisec(const uint64 count)
		{
			static const double scale = 1'000 / GetPerformanceFrequency();
			return count * scale;
		}

		[[nodiscard]]
		static double GetDisplayRefreshPeriodMillisec()
		{
			DWM_TIMING_INFO timingInfo = {};
			timingInfo.cbSize = sizeof(DWM_TIMING_INFO);
			::DwmGetCompositionTimingInfo(nullptr, &timingInfo);
			return ToMillisec(timingInfo.qpcRefreshPeriod);
		}
	}

	D3D11SwapChain::D3D11SwapChain(const D3D11Device& device, HWND hWnd, const Size& frameBufferSize)
		: m_hWnd(hWnd)
		, m_device(device.getDevice())
		, m_context(device.getContext())
	{
		LOG_SCOPED_TRACE(U"D3D11SwapChain::D3D11SwapChain()");

		m_desc.Width		= frameBufferSize.x;
		m_desc.Height		= frameBufferSize.y;
		m_desc.Format		= DXGI_FORMAT_R8G8B8A8_UNORM;
		m_desc.Stereo		= FALSE;
		m_desc.SampleDesc	= { 1, 0 };
		m_desc.BufferUsage	= DXGI_USAGE_RENDER_TARGET_OUTPUT;
		m_desc.BufferCount	= 3;
		m_desc.Scaling		= DXGI_SCALING_STRETCH;
		m_desc.SwapEffect	= (device.getDXGIFactory5() ? DXGI_SWAP_EFFECT_FLIP_DISCARD : DXGI_SWAP_EFFECT_DISCARD);
		m_desc.AlphaMode	= DXGI_ALPHA_MODE_IGNORE;
		m_desc.Flags		= 0;

		// Swap chain を作成
		{
			LOG_TRACE(U"IDXGIFactory2::CreateSwapChainForHwnd()");
			if (FAILED(device.getDXGIFactory2()->CreateSwapChainForHwnd(
				m_device,
				hWnd,
				&m_desc,
				nullptr,
				nullptr,
				&m_swapChain1)))
			{
				throw EngineError(U"IDXGIFactory2::CreateSwapChainForHwnd() failed");
			}
		}

		{
			LOG_TRACE(U"IDXGIFactory1::MakeWindowAssociation()");

			constexpr uint32 flags = (DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER);

			if (FAILED(device.getDXGIFactory2()->MakeWindowAssociation(hWnd, flags)))
			{
				throw EngineError(U"IDXGIFactory2::MakeWindowAssociation() failed");
			}
		}

		{
			LOG_TRACE(U"IDXGIDevice2::SetMaximumFrameLatency()");

			if (ComPtr<IDXGIDevice2> pDXGIDevice;
				SUCCEEDED(device.getDeiviceComPtr().As(&pDXGIDevice)))
			{
				pDXGIDevice->SetMaximumFrameLatency(2);
			}
		}

		updateDisplayInfo();
		m_previousWindowBounds = Window::GetState().bounds;
	}

	D3D11SwapChain::~D3D11SwapChain()
	{

	}

	bool D3D11SwapChain::present(const bool vSync)
	{
		if (const Rect windowBounds = Window::GetState().bounds;
			windowBounds != m_previousWindowBounds)
		{
			updateDisplayInfo();

			m_previousWindowBounds = windowBounds;
		}

		//const bool vSync = (not m_targetFrameRateHz.has_value())
		//	|| ((30.0 <= m_targetFrameRateHz) && (AbsDiff(m_targetFrameRateHz.value(), m_displayFrequency) <= 3.0));

		return vSync ? presentVSync() : presentNonVSync();
	}

	double D3D11SwapChain::getDisplayFrequency() const noexcept
	{
		return m_displayFrequency;
	}

	//void D3D11SwapChain::setTargetFrameRateHz(const Optional<double>& targetFrameRateHz)
	//{
	//	m_targetFrameRateHz = targetFrameRateHz;
	//}

	//const Optional<double>& D3D11SwapChain::getTargetFrameRateHz() const noexcept
	//{
	//	return m_targetFrameRateHz;
	//}

	IDXGISwapChain1* D3D11SwapChain::getSwapChain1() const noexcept
	{
		return m_swapChain1.Get();
	}

	Optional<Rect> D3D11SwapChain::getFullscreenRect()
	{
		LOG_TRACE(U"D3D11SwapChain::getFullscreenRect()");

		ComPtr<IDXGIOutput> pOutput;
		if (FAILED(m_swapChain1->GetContainingOutput(&pOutput)))
		{
			return none;
		}

		DXGI_OUTPUT_DESC desc;
		if (FAILED(pOutput->GetDesc(&desc)))
		{
			return none;
		}

		return Rect(desc.DesktopCoordinates.left, desc.DesktopCoordinates.top,
			(desc.DesktopCoordinates.right - desc.DesktopCoordinates.left),
			(desc.DesktopCoordinates.bottom - desc.DesktopCoordinates.top));
	}

	void D3D11SwapChain::updateDisplayInfo()
	{
		ComPtr<IDXGIOutput> pOutput;
		if (FAILED(m_swapChain1->GetContainingOutput(&pOutput)))
		{
			return;
		}

		{
			double displayFrequency;

			DXGI_OUTPUT_DESC desc;
			if (SUCCEEDED(pOutput->GetDesc(&desc)))
			{
				DEVMODE devMode = {};
				devMode.dmSize = sizeof(DEVMODE);
				::EnumDisplaySettingsW(desc.DeviceName, ENUM_CURRENT_SETTINGS, &devMode);
				displayFrequency = devMode.dmDisplayFrequency;
			}
			else
			{
				displayFrequency = detail::GetDisplayRefreshPeriodMillisec();
			}

			if (displayFrequency != m_displayFrequency)
			{
				m_displayFrequency = displayFrequency;
				LOG_INFO(U"Display refresh rate: {:.1f} Hz"_fmt(m_displayFrequency));
			}
		}
	}

	bool D3D11SwapChain::presentVSync()
	{
		const HRESULT hr = m_swapChain1->Present(1, 0);

		if (hr == DXGI_STATUS_OCCLUDED)
		{
			::Sleep(static_cast<int32>((1000 / m_displayFrequency) * 0.9));
		}
		else if (hr == DXGI_ERROR_DEVICE_RESET)
		{
			LOG_FAIL(U"❌ IDXGISwapChain1::Present() failed (DXGI_ERROR_DEVICE_RESET)");
			return false;
		}
		else if (hr == DXGI_ERROR_DEVICE_REMOVED)
		{
			LOG_FAIL(U"❌ IDXGISwapChain1::Present() failed (DXGI_ERROR_DEVICE_REMOVED)");
			return false;
		}

		LARGE_INTEGER counter;
		::QueryPerformanceCounter(&counter);
		m_lastPresentTime = counter.QuadPart;

		return true;
	}

	bool D3D11SwapChain::presentNonVSync()
	{
		/*
		const double targetRefreshRateHz = m_targetFrameRateHz.value();
		const double targetRefreshPeriodMillisec = (1000.0 / targetRefreshRateHz);
		const double displayRefreshPeriodMillisec = detail::GetDisplayRefreshPeriodMillisec();

		LARGE_INTEGER counter;
		::QueryPerformanceCounter(&counter);

		{
			m_context->Flush();

			double timeToSleepMillisec = 0.0;
			::timeBeginPeriod(1);

			do
			{
				::QueryPerformanceCounter(&counter);
				const double timeSinceFlipMillisec = detail::ToMillisec(counter.QuadPart - m_lastPresentTime);

				timeToSleepMillisec = (targetRefreshPeriodMillisec - timeSinceFlipMillisec);

				if (timeToSleepMillisec > 0.0)
				{
					::Sleep(static_cast<int32>(timeToSleepMillisec));
				}
			} while (timeToSleepMillisec > 0.5);

			::timeEndPeriod(1);
		}
		*/

		const HRESULT hr = m_swapChain1->Present(0, 0);

		if (hr == DXGI_STATUS_OCCLUDED)
		{
			::Sleep(static_cast<int32>((1000 / m_displayFrequency) * 0.9));
		}
		else if (hr == DXGI_ERROR_DEVICE_RESET)
		{
			LOG_FAIL(U"❌ IDXGISwapChain::Present() failed (DXGI_ERROR_DEVICE_RESET)");
			return false;
		}
		else if (hr == DXGI_ERROR_DEVICE_REMOVED)
		{
			LOG_FAIL(U"❌ IDXGISwapChain::Present() failed (DXGI_ERROR_DEVICE_REMOVED)");
			return false;
		}

		//m_lastPresentTime = counter.QuadPart;

		return true;
	}
}
<|endoftext|>


<commit_before>#include <ctime>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include "camera.hpp"

static const int WIDTH = 640;
static const int HEIGHT = 480;
static const int FPS = 6;
static const int DEVICE = 0;
static const std::string DIRECTORY_PATH = "/home/pi/Pictures/";//pathの先頭
static const std::string FILE_EXTENTION = ".jpg";//拡張子

static const int AOV = 62.2;//ANGLE OF VIEW
//明度について
static const int MAX_VALUE = 255;//明るさ最大
static const int NO_VALUE = 0;//明るさ最小

Camera::Camera()
{
	if(!capture.open(DEVICE))
	{
		std::cout<<"capture is not opened 1"<<std::endl;
	}
	if (!capture.isOpened())
	{
		std::cout<<"capture is not opened 2"<<std::endl;
	}
	capture.set(CV_CAP_PROP_FRAME_WIDTH,WIDTH);
	capture.set(CV_CAP_PROP_FRAME_HEIGHT,HEIGHT);
	capture.set(CV_CAP_PROP_FPS,FPS);
	//以下 対応してない
	//capture.set(CV_CAP_PROP_BUFFERSIZE, 1);
}

Camera::~Camera()
{
	capture.release();
}

int Camera::takePhoto()
{
	makeTimePath();
	cv::Mat frame;
	for (int i = 0; i < 5; i++)
	{
			capture.grab();
	}
	do
	{
		capture>>frame;
	} while(frame.empty());
	input = frame;
	imwrite(timePath+FILE_EXTENTION,input);
	return 0;
}

//時間を元にtimePathを作る
int Camera::makeTimePath(void)
{
	time_t timer;//時刻を受け取る変数
	struct tm *timeptr;//日時を集めた構造体ポインタ
	char buffer[80];
	time(&timer);//現在時刻の取得
	timeptr = localtime(&timer);//ポインタ
	strftime(buffer, sizeof(buffer), "%Y%m%d-%H%M%S", timeptr);//日時を文字列に変換してｓに代入
	std::string str(buffer);
	timePath = DIRECTORY_PATH+str;
  return 0;
}

//ノイズ除去
cv::Mat Camera::rmNoise(cv::Mat src)
{
	cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),10);//縮小処理
	cv::dilate(src,src,cv::Mat(),cv::Point(-1, -1),25);//膨張処理
	cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),15);//縮小処理
	return src;
}

int Camera::binarize()
{
	cv::Mat hsv;
	cv::Mat hsv_filtered15 ;//画像の初期化
	cv::Mat hsv_filtered180;//画像の初期化
	cv::cvtColor(input, hsv, CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換
	//inRange(入力画像,下界画像,上界画像,出力画像)
	//「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)
	cv::inRange(hsv, cv::Scalar(0, 70, 60), cv::Scalar(2, 255, MAX_VALUE), hsv_filtered15);
	cv::inRange(hsv, cv::Scalar(160, 70, 60), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180);
	cv::add(hsv_filtered15,hsv_filtered180,hsv);
	output = rmNoise(hsv);
	imwrite(timePath+"BINARY"+FILE_EXTENTION,output);
	return 0;
}

//二値化した画像から1の面積を抽出
double Camera::countArea()
{

	double Area = output.rows*output.cols;//全ピクセル数
	double redCount = 0; //赤色を認識したピクセルの数
	redCount = cv::countNonZero(output);//赤色部分の面積を計算
	double percentage = 0; //割合
	percentage = (redCount / Area)*100;//割合を計算
	std::cout<<"面積のPercentageは"<<percentage<<std::endl;
	return percentage;
}

//二値化画像のcenterを角度で返す
double Camera::getCenter()
{
	cv::Moments mu = cv::moments(output, false);//重心の計算結果をmuに代入
	double mc = mu.m10 / mu.m00;//重心のx座標
	double center = (mc - output.cols / 2) * AOV / output.cols;//正規化
	std::cout<<"重心の位置は"<<center<<std::endl;
	return center;
}
<commit_msg>Update camera.cpp<commit_after>#include <ctime>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include "camera.hpp"

static const int WIDTH = 640;
static const int HEIGHT = 480;
static const int FPS = 6;
static const int DEVICE = 0;
static const std::string DIRECTORY_PATH = "/home/pi/Pictures/";//pathの先頭
static const std::string FILE_EXTENTION = ".jpg";//拡張子

static const int AOV = 62.2;//ANGLE OF VIEW
//明度について
static const int MAX_VALUE = 255;//明るさ最大
static const int NO_VALUE = 0;//明るさ最小

Camera::Camera()
{
	if(!capture.open(DEVICE))
	{
		std::cout<<"capture is not opened 1"<<std::endl;
	}
	if (!capture.isOpened())
	{
		std::cout<<"capture is not opened 2"<<std::endl;
	}
	capture.set(CV_CAP_PROP_FRAME_WIDTH,WIDTH);
	capture.set(CV_CAP_PROP_FRAME_HEIGHT,HEIGHT);
	capture.set(CV_CAP_PROP_FPS,FPS);
	//以下 対応してない
	//capture.set(CV_CAP_PROP_BUFFERSIZE, 1);
}

Camera::~Camera()
{
	capture.release();
}

int Camera::takePhoto()
{
	makeTimePath();
	cv::Mat frame;
	for (int i = 0; i < 5; i++)
	{
			capture.grab();
	}
	do
	{
		capture>>frame;
	} while(frame.empty());
	input = frame;
	imwrite(timePath+FILE_EXTENTION,input);
	return 0;
}

//時間を元にtimePathを作る
int Camera::makeTimePath(void)
{
	time_t timer;//時刻を受け取る変数
	struct tm *timeptr;//日時を集めた構造体ポインタ
	char buffer[80];
	time(&timer);//現在時刻の取得
	timeptr = localtime(&timer);//ポインタ
	strftime(buffer, sizeof(buffer), "%Y%m%d-%H%M%S", timeptr);//日時を文字列に変換してｓに代入
	std::string str(buffer);
	timePath = DIRECTORY_PATH+str;
  return 0;
}

//ノイズ除去
cv::Mat Camera::rmNoise(cv::Mat src, int a)
{
	std::vector<std::vector<cv::Point> > contours; cv::findContours(src, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
 	std::vector<std::vector<cv::Point> > contours_subset;
 	for (int i = 0; i<contours.size(); i++)
	{
		double area = cv::contourArea(contours.at(i));
		if (area>a)
		{
			contours_subset.push_back(contours.at(i));
		}
	}
	cv::Mat mask = cv::Mat::zeros(src.rows, src.cols, CV_8UC1);
	cv::drawContours(mask, contours_subset, -1, cv::Scalar(255), -1);
 	return mask;
}

int Camera::binarize()
{
	cv::Mat hsv;
	cv::Mat hsv_filtered15 ;//画像の初期化
	cv::Mat hsv_filtered180;//画像の初期化
	cv::cvtColor(input, hsv, CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換
	//inRange(入力画像,下界画像,上界画像,出力画像)
	//「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)
	cv::inRange(hsv, cv::Scalar(0, 70, 60), cv::Scalar(2, 255, MAX_VALUE), hsv_filtered15);
	cv::inRange(hsv, cv::Scalar(160, 70, 60), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180);
	cv::add(hsv_filtered15,hsv_filtered180,hsv);
	output = rmNoise(hsv, 1);
	imwrite(timePath+"BINARY"+FILE_EXTENTION,output);
	return 0;
}

//二値化した画像から1の面積を抽出
double Camera::countArea()
{

	double Area = output.rows*output.cols;//全ピクセル数
	double redCount = 0; //赤色を認識したピクセルの数
	redCount = cv::countNonZero(output);//赤色部分の面積を計算
	double percentage = 0; //割合
	percentage = (redCount / Area)*100;//割合を計算
	std::cout<<"面積のPercentageは"<<percentage<<std::endl;
	return percentage;
}

//二値化画像のcenterを角度で返す
double Camera::getCenter()
{
	cv::Moments mu = cv::moments(output, false);//重心の計算結果をmuに代入
	double mc = mu.m10 / mu.m00;//重心のx座標
	double center = (mc - output.cols / 2) * AOV / output.cols;//正規化
	std::cout<<"重心の位置は"<<center<<std::endl;
	return center;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "camera.hpp"

#pragma comment(lib,"opencv_world320.lib")

static const int N = 256;//文字列の長さ
static const int AOV = 62.2;//ANGLE OF VIEW
//明度について
static const int MAX_VALUE = 255;//明るさ最大
static const int NO_VALUE = 0;//明るさ最小

//時間を元にStringを作る
char* makeTimeString(void)
{
	static char timeString[N];
	time_t timer;//時刻を受け取る変数
	struct tm *timeptr;//日時を集めた構造体ポインタ
	time(&timer);//現在時刻の取得
	timeptr = localtime(&timer);//ポインタ
	strftime(timeString, N, "%Y%m%d-%H%M%S", timeptr);//日時を文字列に変換してｓに代入
	return timeString;
}

char* makeBinaryString(char *timeString)
{
	static char binaryString[N];
	sprintf(binaryString, "%s%s",timeString,"Binary");
}

//full_pathを作る
char* makePath(char* name)
{
	static char full_path[N];//NOTE 自動変数をreturn するために使った. smartなやり方か?
	char directry_path[] = "/home/pi/Pictures/";//pathの先頭
	char file_extention[] = ".jpg";//拡張子
	sprintf(full_path, "%s%s%s",directry_path,name, file_extention);
	return full_path;
}
//写真をとる
int takePhoto(char* name)
{
	char full_command[N];
	char front_command[] = "raspistill -o ";//command
	sprintf(full_command, "%s%s", front_command, makePath(name));//コマンドの文字列をつなげる。
	system(full_command);//raspistillで静止画を撮って日時を含むファイル名で保存。
	printf("%s\n",full_command);
	//NOTE system関数以外を使うべきか?
	return 0;
}

//二値化画像を作成
cv::Mat binarize(cv::Mat src)
{
	cv::Mat hsv;
	cv::Mat hsv_filtered15 ;//画像の初期化
	cv::Mat hsv_filtered180;//画像の初期化
	cv::cvtColor(src, hsv, CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換
	//inRange(入力画像,下界画像,上界画像,出力画像)
	//「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)
	cv::inRange(hsv, cv::Scalar(0, 45, 70), cv::Scalar(12, 255, MAX_VALUE), hsv_filtered15);
	cv::inRange(hsv, cv::Scalar(160, 45, 70), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180);
	cv::add(hsv_filtered15,hsv_filtered180,hsv);
	return hsv;
}
//ノイズ除去
cv::Mat rmNoize(cv::Mat src)
{
	cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),10);//縮小処理
	cv::dilate(src,src,cv::Mat(),cv::Point(-1, -1),25);//膨張処理
	cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),15);//縮小処理
	return src;
}

int saveBinary(cv::Mat src,char* path)
{
	cv::Mat binary_img;
	cv::resize(src,binary_img,cv::Size(),0.25,0.25);
	return 0;
}

//写真を撮り画像処理する
cv::Mat Mred(void)
{
	char* stime = makeTimeString();
	char* sbtime = makeBinaryString(btime);
	char* path = makePath(stime);
	char* bpath = makePath(sbtime);
	takePhoto(path);
 	cv::Mat src = cv::imread(path);//画像の読み込み
	cv::Mat hsv;
	hsv = rmNoize(binarize(src));
	saveBinary(hsv,bpath);
	return hsv;
}

//二値化した画像から1の面積を抽出
double countArea(cv::Mat src)
{

	double Area = src.rows*src.cols;//全ピクセル数
	double redCount = 0; //赤色を認識したピクセルの数
	redCount = cv::countNonZero(src);//赤色部分の面積を計算
	double percentage = 0; //割合
	percentage = (redCount / Area)*100;//割合を計算
	printf("面積のPercentageは%f\n", percentage);
	return percentage;
}

//二値化画像のcenterを角度で返す
double getCenter(cv::Mat src)
{
	cv::Moments mu = cv::moments(src, false);//重心の計算結果をmuに代入
	double mc = mu.m10 / mu.m00;//重心のx座標
	double center = (mc - src.cols / 2) * AOV / src.cols;//正規化
	printf("重心の位置は%f\n",center);
	return center;
}
<commit_msg>dbeug<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "camera.hpp"

#pragma comment(lib,"opencv_world320.lib")

static const int N = 256;//文字列の長さ
static const int AOV = 62.2;//ANGLE OF VIEW
//明度について
static const int MAX_VALUE = 255;//明るさ最大
static const int NO_VALUE = 0;//明るさ最小

//時間を元にStringを作る
char* makeTimeString(void)
{
	static char timeString[N];
	time_t timer;//時刻を受け取る変数
	struct tm *timeptr;//日時を集めた構造体ポインタ
	time(&timer);//現在時刻の取得
	timeptr = localtime(&timer);//ポインタ
	strftime(timeString, N, "%Y%m%d-%H%M%S", timeptr);//日時を文字列に変換してｓに代入
	return timeString;
}

char* makeBinaryString(char *timeString)
{
	static char binaryString[N];
	sprintf(binaryString, "%s%s",timeString,"Binary");
}

//full_pathを作る
char* makePath(char* name)
{
	static char full_path[N];//NOTE 自動変数をreturn するために使った. smartなやり方か?
	char directry_path[] = "/home/pi/Pictures/";//pathの先頭
	char file_extention[] = ".jpg";//拡張子
	sprintf(full_path, "%s%s%s",directry_path,name, file_extention);
	return full_path;
}
//写真をとる
int takePhoto(char* name)
{
	char full_command[N];
	char front_command[] = "raspistill -o ";//command
	sprintf(full_command, "%s%s", front_command, makePath(name));//コマンドの文字列をつなげる。
	system(full_command);//raspistillで静止画を撮って日時を含むファイル名で保存。
	printf("%s\n",full_command);
	//NOTE system関数以外を使うべきか?
	return 0;
}

//二値化画像を作成
cv::Mat binarize(cv::Mat src)
{
	cv::Mat hsv;
	cv::Mat hsv_filtered15 ;//画像の初期化
	cv::Mat hsv_filtered180;//画像の初期化
	cv::cvtColor(src, hsv, CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換
	//inRange(入力画像,下界画像,上界画像,出力画像)
	//「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)
	cv::inRange(hsv, cv::Scalar(0, 45, 70), cv::Scalar(12, 255, MAX_VALUE), hsv_filtered15);
	cv::inRange(hsv, cv::Scalar(160, 45, 70), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180);
	cv::add(hsv_filtered15,hsv_filtered180,hsv);
	return hsv;
}
//ノイズ除去
cv::Mat rmNoize(cv::Mat src)
{
	cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),10);//縮小処理
	cv::dilate(src,src,cv::Mat(),cv::Point(-1, -1),25);//膨張処理
	cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),15);//縮小処理
	return src;
}

int saveBinary(cv::Mat src,char* path)
{
	cv::Mat binary_img;
	cv::resize(src,binary_img,cv::Size(),0.25,0.25);
	return 0;
}

//写真を撮り画像処理する
cv::Mat Mred(void)
{
	char* stime = makeTimeString();
	char* sbtime = makeBinaryString(stime);
	char* path = makePath(stime);
	char* bpath = makePath(sbtime);
	takePhoto(path);
 	cv::Mat src = cv::imread(path);//画像の読み込み
	cv::Mat hsv;
	hsv = rmNoize(binarize(src));
	saveBinary(hsv,bpath);
	return hsv;
}

//二値化した画像から1の面積を抽出
double countArea(cv::Mat src)
{

	double Area = src.rows*src.cols;//全ピクセル数
	double redCount = 0; //赤色を認識したピクセルの数
	redCount = cv::countNonZero(src);//赤色部分の面積を計算
	double percentage = 0; //割合
	percentage = (redCount / Area)*100;//割合を計算
	printf("面積のPercentageは%f\n", percentage);
	return percentage;
}

//二値化画像のcenterを角度で返す
double getCenter(cv::Mat src)
{
	cv::Moments mu = cv::moments(src, false);//重心の計算結果をmuに代入
	double mc = mu.m10 / mu.m00;//重心のx座標
	double center = (mc - src.cols / 2) * AOV / src.cols;//正規化
	printf("重心の位置は%f\n",center);
	return center;
}
<|endoftext|>


<commit_before>#define _USE_MATH_DEFINES
#include <iostream>
#include "Neuralnetwork.h"
using namespace std;

int main () {
	/* xor example:*/
	/*
	vector<int> init{2, 3, 1};
	vector<vector<double>> inputs(2);
	vector<vector<double>> outputs(1);
	inputs[0] = vector<double>{ 0, 0, 1, 1};
	inputs[1] = vector<double>{ 0, 1, 0, 1};
	outputs[0] = vector<double>{0, 1, 1, 0};
	Neural_network nn{init, 0.1};
	nn(inputs, outputs, 10000);

	Neural_network::test(nn, vector<double>{1, 1}, vector<double>{0});
	Neural_network::test(nn, vector<double>{1., 0}, vector<double>{1});
	Neural_network::test(nn, vector<double>{0, 1.}, vector<double>{1});
	Neural_network::test(nn, vector<double>{0, 0}, vector<double>{0});
	/**/

	/*sine example:*/

	vector<int> init{1, 2, 1};
	vector<vector<double>> inputs(1);
	vector<vector<double>> outputs(1);
	Neural_network nn{init, 0.1};

	inputs[0] = vector<double>(50);
	outputs[0] = vector<double>(50);
	for (size_t i=0; i < inputs[0].size(); i++) {
		inputs[0][i] = i*M_PI*2./double(inputs[0].size());
		outputs[0][i] = sin(inputs[0][i]);
	}
	nn(inputs, outputs, 10000);

	Neural_network::test(nn, vector<double>{0.}, vector<double>{sin(0.)});
	Neural_network::test(nn, vector<double>{0.5}, vector<double>{sin(0.5)});
	Neural_network::test(nn, vector<double>{1.5}, vector<double>{sin(1.5)});
	Neural_network::test(nn, vector<double>{3.1}, vector<double>{sin(3.1)});
	Neural_network::test(nn, vector<double>{4.}, vector<double>{sin(4.)});
	Neural_network::test(nn, vector<double>{4.5}, vector<double>{sin(4.5)});
	/**/

	return 0;
}
<commit_msg>negative codomain of sine is not calculated correctly.<commit_after>#define _USE_MATH_DEFINES
#include <iostream>
#include "Neuralnetwork.h"
using namespace std;

int main () {
	/* xor example:*/
	/*
	vector<int> init{2, 3, 1};
	vector<vector<double>> inputs(2);
	vector<vector<double>> outputs(1);
	inputs[0] = vector<double>{ 0, 0, 1, 1};
	inputs[1] = vector<double>{ 0, 1, 0, 1};
	outputs[0] = vector<double>{0, 1, 1, 0};
	Neural_network nn{init, 0.1};
	nn(inputs, outputs, 10000);

	Neural_network::test(nn, vector<double>{1, 1}, vector<double>{0});
	Neural_network::test(nn, vector<double>{1., 0}, vector<double>{1});
	Neural_network::test(nn, vector<double>{0, 1.}, vector<double>{1});
	Neural_network::test(nn, vector<double>{0, 0}, vector<double>{0});
	/**/

	/*sine example:*/

	vector<int> init{1, 3, 1};
	vector<vector<double>> inputs(1);
	vector<vector<double>> outputs(1);
	Neural_network nn{init, 0.1};

	inputs[0] = vector<double>(30);
	outputs[0] = vector<double>(30);
	for (size_t i=0; i < inputs[0].size(); i++) {
		inputs[0][i] = i*M_PI*2./double(inputs[0].size());
		outputs[0][i] = sin(inputs[0][i]);
	}
	nn(inputs, outputs, 20000);

	Neural_network::test(nn, vector<double>{0.}, vector<double>{sin(0.)});
	Neural_network::test(nn, vector<double>{0.5}, vector<double>{sin(0.5)});
	Neural_network::test(nn, vector<double>{1.5}, vector<double>{sin(1.5)});
	Neural_network::test(nn, vector<double>{3.1}, vector<double>{sin(3.1)});
	Neural_network::test(nn, vector<double>{4.}, vector<double>{sin(4.)});
	Neural_network::test(nn, vector<double>{4.5}, vector<double>{sin(4.5)});
	Neural_network::test(nn, vector<double>{5.}, vector<double>{sin(5)});
	Neural_network::test(nn, vector<double>{6.}, vector<double>{sin(6)});
	/**/

	return 0;
}
<|endoftext|>


<commit_before>#pragma once

#include "message.hpp"

#include <cstdlib>
#include <new>
#include <utility>
#include <cinttypes>
#include <condition_variable>
#include <mutex>
#include <list>
#include <Utils/Profiler.hpp>

#include <queue>

// tmp
#include "Utils/Debug.hpp"

AGE_NOT_OPTIMIZED_BLOCK_BEGIN

namespace TMQ
{
	class ReleasableQueue;
	class Dispatcher;
	class Messsage;
	class ImmediateQueue;
	class HybridQueue;

	class PtrQueue
	{
	public:
		PtrQueue(const TMQ::PtrQueue &o);
		PtrQueue& operator=(const TMQ::PtrQueue &o);
		PtrQueue(std::size_t chunkSize = 1024);
		PtrQueue& operator=(TMQ::PtrQueue &&o);
		PtrQueue(TMQ::PtrQueue &&o);
		~PtrQueue();
		void pop();
		MessageBase *front();
		std::size_t getFrontSize();
		void clear();
		void eraseAll();
		bool empty();
	private:
		std::size_t _chunkSize;
		struct Chunk
		{
			char *_data;
			std::size_t _cursor;
			std::size_t _size;
			std::size_t _to;

			Chunk() = delete;
			Chunk(const Chunk &o) = delete;
			Chunk& operator=(const Chunk &o) = delete;
			Chunk(std::size_t chunkSize);
			Chunk& operator=(Chunk &&o);
			Chunk(Chunk &&o);
			~Chunk();
			void pop();
			MessageBase *front();
			std::size_t getFrontSize();
			void clear();
			void eraseAll();
			void release();
			bool empty();

			template <typename T>
			T* push(const T& e)
			{
				std::size_t sizeOfInt = sizeof(std::size_t);
				std::size_t s = sizeof(Message<T>);
				assert(s < _chunkSize + sizeOfInt);

				if (_size - _to < s + sizeOfInt)
				{
					return nullptr;
				}

				char *tmp = _data;
				tmp += _to;
				memcpy(tmp, &s, sizeOfInt);
				tmp += sizeOfInt;
				Message<T>* res = new(tmp)Message<T>(e);
				_to += sizeOfInt + s;
				return &res->_data;
			}

			template <typename T>
			T* push(T&& e)
			{
				assert(sizeof(T) % 4 == 0);
				std::size_t s = sizeof(Message<T>);
				std::size_t sizeOfInt = sizeof(std::size_t);

				if (_size - _to < s + sizeOfInt)
				{
					return nullptr;
				}

				char *tmp = _data;
				tmp += _to;
				memcpy(tmp, &s, sizeOfInt);
				tmp += sizeOfInt;
				Message<T>* res = new(tmp)Message<T>(std::move(e));
				_to += sizeOfInt + s;
				return &res->_data;
			}

			bool move(MessageBase *e, std::size_t size)
			{
				std::size_t s = size;
				std::size_t sizeOfInt = sizeof(std::size_t);

				if (_size - _to < s + sizeOfInt)
				{
					return false;
				}

				char *tmp = _data;
				tmp += _to;
				memcpy(tmp, &s, sizeOfInt);
				tmp += sizeOfInt;
				e->clone(tmp);
				auto test = (MessageBase*)(tmp);
				_to += sizeOfInt + s;
				return true;
			}

			template <typename T, typename ...Args>
			T* emplace(Args ...args)
			{
				assert(sizeof(T) % 4 == 0);
				std::size_t s = sizeof(Message<T>);
				std::size_t sizeOfInt = sizeof(std::size_t);

				if (_size - _to < s + sizeOfInt)
				{
					return nullptr;
				}

				char *tmp = _data;
				tmp += _to;
				memcpy(tmp, &s, sizeOfInt);
				tmp += sizeOfInt;
				Message<T>* res = new(tmp)Message<T>(args...);
				_to += sizeOfInt + s;
				return &res->_data;
			}
		};
		std::list<Chunk*> _list;
		std::list<Chunk*>::iterator _listReader;
		std::list<Chunk*>::iterator _listWriter;

		template <typename T>
		T* push(const T& e)
		{
			assert(sizeof(T) % 4 == 0);
			std::size_t s = sizeof(Message<T>);
			std::size_t sizeOfInt = sizeof(std::size_t);
			assert(s + sizeOfInt < _chunkSize);

			auto res = (*_listWriter)->push(e);
			if (!res)
			{
				if (_listWriter == --std::end(_list))
				{
					_list.push_back(new Chunk(_chunkSize));
					_listWriter = --std::end(_list);
				}
				else
					++_listWriter;
				return push(e);
			}
		}

		template <typename T>
		T* push(T&& e)
		{
			assert(sizeof(T) % 4 == 0);
			std::size_t s = sizeof(Message<T>);
			std::size_t sizeOfInt = sizeof(std::size_t);
			assert(s + sizeOfInt < _chunkSize);

			auto res = (*_listWriter)->push(std::move(e));
			if (!res)
			{
				if (_listWriter == --std::end(_list))
				{
					_list.push_back(new Chunk(_chunkSize));
					_listWriter = --std::end(_list);
				}
				else
					++_listWriter;
				return push(e);
			}
		}

		bool move(MessageBase *e, std::size_t size)
		{
			std::size_t s = size;
			std::size_t sizeOfInt = sizeof(std::size_t);
			assert(s + sizeOfInt < _chunkSize);

			if ((*_listWriter)->move(std::move(e), size))
				return true;
			if (_listWriter == --std::end(_list))
			{
				_list.push_back(new Chunk(_chunkSize));
				_listWriter = --std::end(_list);
			}
			else
				++_listWriter;
			return (*_listWriter)->move(std::move(e), size);
		}

		template <typename T, typename ...Args>
		T* emplace(Args ...args)
		{
			assert(sizeof(T) % 4 == 0);
			std::size_t s = sizeof(Message<T>);
			std::size_t sizeOfInt = sizeof(std::size_t);
			assert(s + sizeOfInt < _chunkSize);

			auto res = (*_listWriter)->emplace<T>(args...);
			if (!res)
			{
				if (_listWriter == --std::end(_list))
				{
					_list.push_back(new Chunk(_chunkSize));
					_listWriter = --std::end(_list);
				}
				else
					++_listWriter;
				return emplace<T>(args...);
			}
			return res;
		}
		friend class ReleasableQueue;
		friend class ImmediateQueue;
		friend class HybridQueue;
	};

	class HybridQueue
	{
		static std::queue<MessageBase*>              _sharedQueue;
		std::queue<MessageBase*>                     _individualQueue;
		static std::mutex              _mutex;
		static std::condition_variable _condition;
	public:
		HybridQueue();

		HybridQueue(const HybridQueue&) = delete;
		HybridQueue &operator=(const HybridQueue&) = delete;
		HybridQueue(HybridQueue &&) = delete;
		HybridQueue &operator=(HybridQueue &&) = delete;

		void getTask(MessageBase *& task);
		void tryToGetTask(MessageBase *& task, std::size_t microSeconds);

		//////////////
		//// TASKS

		template <typename T>
		void pushTask(const T& e)
		{
			SCOPE_profile_cpu_function("TMQ");
			{
				std::lock_guard<std::mutex> lock(_mutex);
				_individualQueue.push(new Message<T>(e));
			}
			_condition.notify_all();
		}

		template <typename T, typename ...Args>
		void emplaceTask(Args ...args)
		{
			SCOPE_profile_cpu_function("TMQ");
			{
				std::lock_guard<std::mutex> lock(_mutex);
				_individualQueue.push(new Message<T>(args...));
			}
			_condition.notify_all();
		}

		template <typename T, typename F>
		std::future<F> pushFutureTask(const T &e)
		{
			SCOPE_profile_cpu_function("TMQ");
			auto tmp = new Message<T>(e);
			f = tmp->getData().getFuture();
			std::future < F > f;
			{
				std::lock_guard<std::mutex> lock(_mutex);
				_individualQueue.push(tmp);
			}
			_condition.notify_all();
			return f;
		}

		template <typename T, typename F, typename ...Args>
		std::future<F> emplaceFutureTask(Args ...args)
		{
			SCOPE_profile_cpu_function("TMQ");
			std::future< F > f;
			auto tmp = new Message<T>(args...);
			f = tmp->getData().getFuture();
			{
				std::lock_guard<std::mutex> lock(_mutex);
				_individualQueue.push(tmp);
			}
			_condition.notify_all();
			return f;
		}

		///////
		// SHARED

		template <typename T>
		static void pushSharedTask(const T& e)
		{
			SCOPE_profile_cpu_function("TMQ");
			{
				std::lock_guard<std::mutex> lock(_mutex);
				_sharedQueue.push(new Message<T>(e));
			}
			_condition.notify_all();
		}

		template <typename T, typename ...Args>
		static void emplaceSharedTask(Args ...args)
		{
			SCOPE_profile_cpu_function("TMQ");
			{
				std::lock_guard<std::mutex> lock(_mutex);
				_sharedQueue.push(new Message<T>(args...));
			}
			_condition.notify_all();
		}

		template <typename T, typename F>
		static std::future<F> pushSharedFutureTask(const T &e)
		{
			SCOPE_profile_cpu_function("TMQ");
			std::future < F > f;
			auto tmp = new Message<T>(e);
			f = tmp->getData().getFuture();
			{
				std::lock_guard<std::mutex> lock(_mutex);
				_sharedQueue.push(tmp);
			}
			_condition.notify_all();
			return f;
		}

		template <typename T, typename F, typename ...Args>
		static std::future<F> emplaceSharedFutureTask(Args ...args)
		{
			SCOPE_profile_cpu_function("TMQ");
			std::future< F > f;
			auto tmp = new Message<T>(args...);
			f = tmp->getData().getFuture();
			{
				std::lock_guard<std::mutex> lock(_mutex);
				_sharedQueue.push(tmp);
			}
			_condition.notify_all();
			return f;
		}

	};

}
AGE_NOT_OPTIMIZED_BLOCK_END
<commit_msg>Queue optimized<commit_after>#pragma once

#include "message.hpp"

#include <cstdlib>
#include <new>
#include <utility>
#include <cinttypes>
#include <condition_variable>
#include <mutex>
#include <list>
#include <Utils/Profiler.hpp>

#include <queue>

// tmp
#include "Utils/Debug.hpp"

namespace TMQ
{
	class ReleasableQueue;
	class Dispatcher;
	class Messsage;
	class ImmediateQueue;
	class HybridQueue;

	class PtrQueue
	{
	public:
		PtrQueue(const TMQ::PtrQueue &o);
		PtrQueue& operator=(const TMQ::PtrQueue &o);
		PtrQueue(std::size_t chunkSize = 1024);
		PtrQueue& operator=(TMQ::PtrQueue &&o);
		PtrQueue(TMQ::PtrQueue &&o);
		~PtrQueue();
		void pop();
		MessageBase *front();
		std::size_t getFrontSize();
		void clear();
		void eraseAll();
		bool empty();
	private:
		std::size_t _chunkSize;
		struct Chunk
		{
			char *_data;
			std::size_t _cursor;
			std::size_t _size;
			std::size_t _to;

			Chunk() = delete;
			Chunk(const Chunk &o) = delete;
			Chunk& operator=(const Chunk &o) = delete;
			Chunk(std::size_t chunkSize);
			Chunk& operator=(Chunk &&o);
			Chunk(Chunk &&o);
			~Chunk();
			void pop();
			MessageBase *front();
			std::size_t getFrontSize();
			void clear();
			void eraseAll();
			void release();
			bool empty();

			template <typename T>
			T* push(const T& e)
			{
				std::size_t sizeOfInt = sizeof(std::size_t);
				std::size_t s = sizeof(Message<T>);
				assert(s < _chunkSize + sizeOfInt);

				if (_size - _to < s + sizeOfInt)
				{
					return nullptr;
				}

				char *tmp = _data;
				tmp += _to;
				memcpy(tmp, &s, sizeOfInt);
				tmp += sizeOfInt;
				Message<T>* res = new(tmp)Message<T>(e);
				_to += sizeOfInt + s;
				return &res->_data;
			}

			template <typename T>
			T* push(T&& e)
			{
				assert(sizeof(T) % 4 == 0);
				std::size_t s = sizeof(Message<T>);
				std::size_t sizeOfInt = sizeof(std::size_t);

				if (_size - _to < s + sizeOfInt)
				{
					return nullptr;
				}

				char *tmp = _data;
				tmp += _to;
				memcpy(tmp, &s, sizeOfInt);
				tmp += sizeOfInt;
				Message<T>* res = new(tmp)Message<T>(std::move(e));
				_to += sizeOfInt + s;
				return &res->_data;
			}

			bool move(MessageBase *e, std::size_t size)
			{
				std::size_t s = size;
				std::size_t sizeOfInt = sizeof(std::size_t);

				if (_size - _to < s + sizeOfInt)
				{
					return false;
				}

				char *tmp = _data;
				tmp += _to;
				memcpy(tmp, &s, sizeOfInt);
				tmp += sizeOfInt;
				e->clone(tmp);
				auto test = (MessageBase*)(tmp);
				_to += sizeOfInt + s;
				return true;
			}

			template <typename T, typename ...Args>
			T* emplace(Args ...args)
			{
				assert(sizeof(T) % 4 == 0);
				std::size_t s = sizeof(Message<T>);
				std::size_t sizeOfInt = sizeof(std::size_t);

				if (_size - _to < s + sizeOfInt)
				{
					return nullptr;
				}

				char *tmp = _data;
				tmp += _to;
				memcpy(tmp, &s, sizeOfInt);
				tmp += sizeOfInt;
				Message<T>* res = new(tmp)Message<T>(args...);
				_to += sizeOfInt + s;
				return &res->_data;
			}
		};
		std::list<Chunk*> _list;
		std::list<Chunk*>::iterator _listReader;
		std::list<Chunk*>::iterator _listWriter;

		template <typename T>
		T* push(const T& e)
		{
			assert(sizeof(T) % 4 == 0);
			std::size_t s = sizeof(Message<T>);
			std::size_t sizeOfInt = sizeof(std::size_t);
			assert(s + sizeOfInt < _chunkSize);

			auto res = (*_listWriter)->push(e);
			if (!res)
			{
				if (_listWriter == --std::end(_list))
				{
					_list.push_back(new Chunk(_chunkSize));
					_listWriter = --std::end(_list);
				}
				else
					++_listWriter;
				return push(e);
			}
		}

		template <typename T>
		T* push(T&& e)
		{
			assert(sizeof(T) % 4 == 0);
			std::size_t s = sizeof(Message<T>);
			std::size_t sizeOfInt = sizeof(std::size_t);
			assert(s + sizeOfInt < _chunkSize);

			auto res = (*_listWriter)->push(std::move(e));
			if (!res)
			{
				if (_listWriter == --std::end(_list))
				{
					_list.push_back(new Chunk(_chunkSize));
					_listWriter = --std::end(_list);
				}
				else
					++_listWriter;
				return push(e);
			}
		}

		bool move(MessageBase *e, std::size_t size)
		{
			std::size_t s = size;
			std::size_t sizeOfInt = sizeof(std::size_t);
			assert(s + sizeOfInt < _chunkSize);

			if ((*_listWriter)->move(std::move(e), size))
				return true;
			if (_listWriter == --std::end(_list))
			{
				_list.push_back(new Chunk(_chunkSize));
				_listWriter = --std::end(_list);
			}
			else
				++_listWriter;
			return (*_listWriter)->move(std::move(e), size);
		}

		template <typename T, typename ...Args>
		T* emplace(Args ...args)
		{
			assert(sizeof(T) % 4 == 0);
			std::size_t s = sizeof(Message<T>);
			std::size_t sizeOfInt = sizeof(std::size_t);
			assert(s + sizeOfInt < _chunkSize);

			auto res = (*_listWriter)->emplace<T>(args...);
			if (!res)
			{
				if (_listWriter == --std::end(_list))
				{
					_list.push_back(new Chunk(_chunkSize));
					_listWriter = --std::end(_list);
				}
				else
					++_listWriter;
				return emplace<T>(args...);
			}
			return res;
		}
		friend class ReleasableQueue;
		friend class ImmediateQueue;
		friend class HybridQueue;
	};

	class HybridQueue
	{
		static std::queue<MessageBase*>              _sharedQueue;
		std::queue<MessageBase*>                     _individualQueue;
		static std::mutex              _mutex;
		static std::condition_variable _condition;
	public:
		HybridQueue();

		HybridQueue(const HybridQueue&) = delete;
		HybridQueue &operator=(const HybridQueue&) = delete;
		HybridQueue(HybridQueue &&) = delete;
		HybridQueue &operator=(HybridQueue &&) = delete;

		void getTask(MessageBase *& task);
		void tryToGetTask(MessageBase *& task, std::size_t microSeconds);

		//////////////
		//// TASKS

		template <typename T>
		void pushTask(const T& e)
		{
			SCOPE_profile_cpu_function("TMQ");
			{
				std::lock_guard<std::mutex> lock(_mutex);
				_individualQueue.push(new Message<T>(e));
			}
			_condition.notify_all();
		}

		template <typename T, typename ...Args>
		void emplaceTask(Args ...args)
		{
			SCOPE_profile_cpu_function("TMQ");
			{
				std::lock_guard<std::mutex> lock(_mutex);
				_individualQueue.push(new Message<T>(args...));
			}
			_condition.notify_all();
		}

		template <typename T, typename F>
		std::future<F> pushFutureTask(const T &e)
		{
			SCOPE_profile_cpu_function("TMQ");
			auto tmp = new Message<T>(e);
			f = tmp->getData().getFuture();
			std::future < F > f;
			{
				std::lock_guard<std::mutex> lock(_mutex);
				_individualQueue.push(tmp);
			}
			_condition.notify_all();
			return f;
		}

		template <typename T, typename F, typename ...Args>
		std::future<F> emplaceFutureTask(Args ...args)
		{
			SCOPE_profile_cpu_function("TMQ");
			std::future< F > f;
			auto tmp = new Message<T>(args...);
			f = tmp->getData().getFuture();
			{
				std::lock_guard<std::mutex> lock(_mutex);
				_individualQueue.push(tmp);
			}
			_condition.notify_all();
			return f;
		}

		///////
		// SHARED

		template <typename T>
		static void pushSharedTask(const T& e)
		{
			SCOPE_profile_cpu_function("TMQ");
			{
				std::lock_guard<std::mutex> lock(_mutex);
				_sharedQueue.push(new Message<T>(e));
			}
			_condition.notify_all();
		}

		template <typename T, typename ...Args>
		static void emplaceSharedTask(Args ...args)
		{
			SCOPE_profile_cpu_function("TMQ");
			{
				std::lock_guard<std::mutex> lock(_mutex);
				_sharedQueue.push(new Message<T>(args...));
			}
			_condition.notify_all();
		}

		template <typename T, typename F>
		static std::future<F> pushSharedFutureTask(const T &e)
		{
			SCOPE_profile_cpu_function("TMQ");
			std::future < F > f;
			auto tmp = new Message<T>(e);
			f = tmp->getData().getFuture();
			{
				std::lock_guard<std::mutex> lock(_mutex);
				_sharedQueue.push(tmp);
			}
			_condition.notify_all();
			return f;
		}

		template <typename T, typename F, typename ...Args>
		static std::future<F> emplaceSharedFutureTask(Args ...args)
		{
			SCOPE_profile_cpu_function("TMQ");
			std::future< F > f;
			auto tmp = new Message<T>(args...);
			f = tmp->getData().getFuture();
			{
				std::lock_guard<std::mutex> lock(_mutex);
				_sharedQueue.push(tmp);
			}
			_condition.notify_all();
			return f;
		}

	};

}
<|endoftext|>


<commit_before>// Minimal usage example: prints a hash. Tested on x86, ppc, arm.

#include "highwayhash/highwayhash.h"

#include <algorithm>
#include <iostream>

using namespace highwayhash;

int main(int argc, char* argv[]) {
  // Please use a different key to ensure your hashes aren't identical.
  const HHKey key HH_ALIGNAS(32) = {1, 2, 3, 4};
  // Aligning inputs to 32 bytes may help but is not required.
  const char in[] = "bytes_to_hash";
  // Type determines the hash size; can also be HHResult128 or HHResult256.
  HHResult64 result;
  // HH_TARGET_PREFERRED expands to the best specialization available for the
  // CPU detected via compiler flags (e.g. AVX2 #ifdef __AVX2__).
  HHStateT<HH_TARGET_PREFERRED> state(key);
  // Using argc prevents the compiler from eliding the hash computations.
  const size_t size = std::min(sizeof(in), static_cast<size_t>(argc));
  HighwayHashT(&state, in, size, &result);
  std::cout << "Hash   : " << result << std::endl;

  HighwayHashCatT<HH_TARGET_PREFERRED> cat(key);
  cat.Append(in, size);
  cat.Finalize(&result);
  std::cout << "HashCat: " << result << std::endl;
  return 0;
}
<commit_msg>Simplified example, thanks Lode Vandevenne<commit_after>// Minimal usage example: prints a hash. Tested on x86, ppc, arm.

#include "highwayhash/highwayhash.h"

#include <algorithm>
#include <iostream>

using namespace highwayhash;

int main(int argc, char* argv[]) {
  // We read from the args on purpose, to ensure a compile time constant will
  // not be used, for verifying assembly on the supported platforms.
  if (argc != 2) {
    std::cout << "Please provide 1 argument with a text to hash" << std::endl;
    return 1;
  }

  // Please use a different key to ensure your hashes aren't identical.
  const HHKey key HH_ALIGNAS(32) = {1, 2, 3, 4};

  // Aligning inputs to 32 bytes may help but is not required.
  const char* in = argv[1];
  const size_t size = strlen(in);

  // Type determines the hash size; can also be HHResult128 or HHResult256.
  HHResult64 result;

  // HH_TARGET_PREFERRED expands to the best specialization available for the
  // CPU detected via compiler flags (e.g. AVX2 #ifdef __AVX2__).
  HHStateT<HH_TARGET_PREFERRED> state(key);
  HighwayHashT(&state, in, size, &result);
  std::cout << "Hash   : " << result << std::endl;

  HighwayHashCatT<HH_TARGET_PREFERRED> cat(key);
  cat.Append(in, size);
  cat.Finalize(&result);
  std::cout << "HashCat: " << result << std::endl;
  return 0;
}
<|endoftext|>


<commit_before>// Convert file supported by xylib to ascii format
// Licence: Lesser GNU Public License 2.1 (LGPL)
// $Id$

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <string.h>

#include "xylib/xylib.h"

using namespace std;

void print_usage()
{
    cout <<
"Usage:\n"
"\txyconv [-t FILETYPE] INPUT_FILE OUTPUT_FILE\n"
"\txyconv [-t FILETYPE] -m INPUT_FILE1 ...\n"
"\txyconv -i FILETYPE\n"
"\txyconv -g INPUT_FILE ...\n"
"\txyconv [-l|-v|-h]\n"
"  Converts INPUT_FILE to ascii OUTPUT_FILE\n"
"  -t     specify filetype of input file\n"
"  -m     convert one or multiple files; output files have the same name\n"
"         as input, but with extension changed to .xy\n"
"  -l     list all supported file types\n"
"  -v     output version information and exit\n"
"  -h     show this help message and exit\n"
"  -i     show information about filetype\n"
"  -s     do not output metadata\n"
"  -g     guess filetype of file \n";
}

// Print version of the library. This program is too small to have own version.
void print_version()
{
    cout << XYLIB_VERSION / 10000 << "."
         << XYLIB_VERSION / 100 % 100 << "."
         << XYLIB_VERSION % 100 << endl;
}

void list_supported_formats()
{
    const xylibFormat* format = NULL;
    for (int i = 0; (format = xylib_get_format(i)) != NULL; ++i)
        cout << setw(20) << left << format->name << ": "
             << format->desc << endl;
}

int print_guessed_filetype(int n, char** paths)
{
    bool ok = true;
    for (int i = 0; i < n; ++i) {
        const char* path = paths[i];
        if (n > 1)
            cout << path << ": ";
        try {
            ifstream is(path);
            if (!is) {
                cout << "Error: can't open input file: " << path;
                ok = false;
            }
            xylib::FormatInfo const* fi = xylib::guess_filetype(path, is);
            if (fi)
                cout << fi->name << ": " << fi->desc << endl;
            else
                cout << "Format of the file was not detected\n";
        } catch (runtime_error const& e) {
            cout << "Error: " << e.what() << endl;
            ok = false;
        }
    }
    return ok ? 0 : -1;
}

void print_filetype_info(string const& filetype)
{
        xylibFormat const* fi = xylib_get_format_by_name(filetype.c_str());
        if (fi) {
            cout << "Name: " << fi->name << endl;
            cout << "Description: " << fi->desc << endl;
            bool has_exts = (strlen(fi->exts) != 0);
            cout << "Possible extensions: "
                 << (has_exts ? fi->exts : "(not specified)") << endl;
            cout << "Other flags: "
                << (fi->binary ? "binary-file" : "text-file") << " "
                << (fi->multiblock ? "multi-block" : "single-block") << endl;
        }
        else
            cout << "Unknown file format." << endl;
}

void export_metadata(ostream &of, xylib::MetaData const& meta)
{
    for (size_t i = 0; i != meta.size(); ++i) {
        const string& key = meta.get_key(i);
        const string& value = meta.get(key);
        of << "# " << key << ": ";
        // value can be multiline
        for (string::const_iterator j = value.begin(); j != value.end(); ++j) {
            of << *j;
            if (*j == '\n')
                of << "# " << key << ": ";
        }
        of << endl;
    }
}

void export_plain_text(xylib::DataSet const *d, string const &fname,
                       bool with_metadata)
{
    int range_num = d->get_block_count();
    ofstream of(fname.c_str());
    if (!of)
        throw xylib::RunTimeError("can't create file: " + fname);

    // output the file-level meta-info
    of << "# exported by xylib from a " << d->fi->name << " file" << endl;
    if (with_metadata) {
        export_metadata(of, d->meta);
        of << endl;
    }

    for (int i = 0; i < range_num; ++i) {
        const xylib::Block *block = d->get_block(i);
        if (range_num > 1 || !block->get_name().empty())
            of << "\n### block #" << i << " " << block->get_name() << endl;
        if (with_metadata)
            export_metadata(of, block->meta);

        int ncol = block->get_column_count();
        of << "# ";
        // column 0 is pseudo-column with point indices, we skip it
        for (int k = 1; k <= ncol; ++k) {
            string const& name = block->get_column(k).get_name();
            if (k > 1)
                of << "\t";
            if (name.empty())
                of << "column_" << k;
            else
                of << name;
        }
        of << endl;

        int nrow = block->get_point_count();

        for (int j = 0; j < nrow; ++j) {
            for (int k = 1; k <= ncol; ++k) {
                if (k > 1)
                    of << "\t";
                of << setfill(' ') << setiosflags(ios::fixed)
                    << setprecision(6) << setw(8)
                    << block->get_column(k).get_value(j);
            }
            of << endl;
        }
    }
}

int convert_file(string const& input, string const& output,
                 string const& filetype, bool with_metadata)
{
    try {
        xylib::DataSet *d = xylib::load_file(input, filetype);
        export_plain_text(d, output, with_metadata);
        delete d;
    } catch (runtime_error const& e) {
        cerr << "Error. " << e.what() << endl;
        return -1;
    }
    return 0;
}

int main(int argc, char **argv)
{
    // options -l -h -i -g -v are not combined with other options

    if (argc == 2 && strcmp(argv[1], "-l") == 0) {
        list_supported_formats();
        return 0;
    }
    else if (argc == 2 &&
            (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) {
        print_usage();
        return 0;
    }
    else if (argc == 2 &&
            (strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--version") == 0)) {
        print_version();
        return 0;
    }
    else if (argc == 3 && strcmp(argv[1], "-i") == 0) {
        print_filetype_info(argv[2]);
        return 0;
    }
    else if (argc >= 3 && strcmp(argv[1], "-g") == 0)
        return print_guessed_filetype(argc - 2, argv + 2);
    else if (argc < 3) {
        print_usage();
        return -1;
    }

    string filetype;
    bool option_m = false;
    bool option_s = false;
    int n = 1;
    while (n < argc - 1) {
        if (strcmp(argv[n], "-m") == 0) {
            option_m = true;
            ++n;
        }
        else if (strcmp(argv[n], "-s") == 0) {
            option_s = true;
            ++n;
        }
        else if (strcmp(argv[n], "-t") == 0 && n+1 < argc - 1) {
            filetype = argv[n+1];
            n += 2;
        }
        else
            break;
    }
    if (!option_m && n != argc - 2) {
        print_usage();
        return -1;
    }
    if (option_m) {
        for ( ; n < argc; ++n) {
            string out = argv[n];
            size_t p = out.rfind('.');
            if (p != string::npos)
                out.erase(p);
            out += ".xy";
            cout << "converting " << argv[n] << " to " << out << endl;
            convert_file(argv[n], out, filetype, !option_s);
        }
        return 0;
    }
    else
        return convert_file(argv[argc-2], argv[argc-1], filetype, !option_s);
}

<commit_msg>cosmetic tweaks in xyconv<commit_after>// Convert file supported by xylib to ascii format
// Licence: Lesser GNU Public License 2.1 (LGPL)
// $Id$

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <string.h>

#include "xylib/xylib.h"

using namespace std;

void print_usage()
{
    cout <<
"Usage:\n"
"\txyconv [-t FILETYPE] INPUT_FILE OUTPUT_FILE\n"
"\txyconv [-t FILETYPE] -m INPUT_FILE1 ...\n"
"\txyconv -i FILETYPE\n"
"\txyconv -g INPUT_FILE ...\n"
"\txyconv [-l|-v|-h]\n"
"  Converts INPUT_FILE to ascii OUTPUT_FILE\n"
"  -t     specify filetype of input file\n"
"  -m     convert one or multiple files; output files have the same name\n"
"         as input, but with extension changed to .xy\n"
"  -l     list all supported file types\n"
"  -v     output version information and exit\n"
"  -h     show this help message and exit\n"
"  -i     show information about filetype\n"
"  -s     do not output metadata\n"
"  -g     guess filetype of file \n";
}

// Print version of the library. This program is too small to have own version.
void print_version()
{
    cout << XYLIB_VERSION / 10000 << "."
         << XYLIB_VERSION / 100 % 100 << "."
         << XYLIB_VERSION % 100 << endl;
}

void list_supported_formats()
{
    const xylibFormat* format = NULL;
    for (int i = 0; (format = xylib_get_format(i)) != NULL; ++i)
        cout << setw(20) << left << format->name << ": "
             << format->desc << endl;
}

int print_guessed_filetype(int n, char** paths)
{
    bool ok = true;
    for (int i = 0; i < n; ++i) {
        const char* path = paths[i];
        if (n > 1)
            cout << path << ": ";
        try {
            ifstream is(path);
            if (!is) {
                cout << "Error: can't open input file: " << path << endl;
                ok = false;
                continue;
            }
            xylib::FormatInfo const* fi = xylib::guess_filetype(path, is);
            if (fi)
                cout << fi->name << ": " << fi->desc << endl;
            else
                cout << "Format of the file was not detected\n";
        } catch (runtime_error const& e) {
            cout << "Error: " << e.what() << endl;
            ok = false;
        }
    }
    return ok ? 0 : -1;
}

void print_filetype_info(string const& filetype)
{
        xylibFormat const* fi = xylib_get_format_by_name(filetype.c_str());
        if (fi) {
            cout << "Name: " << fi->name << endl;
            cout << "Description: " << fi->desc << endl;
            bool has_exts = (strlen(fi->exts) != 0);
            cout << "Possible extensions: "
                 << (has_exts ? fi->exts : "(not specified)") << endl;
            cout << "Other flags: "
                << (fi->binary ? "binary-file" : "text-file") << " "
                << (fi->multiblock ? "multi-block" : "single-block") << endl;
        }
        else
            cout << "Unknown file format." << endl;
}

void export_metadata(ostream &of, xylib::MetaData const& meta)
{
    for (size_t i = 0; i != meta.size(); ++i) {
        const string& key = meta.get_key(i);
        const string& value = meta.get(key);
        of << "# " << key << ": ";
        // value can be multiline
        for (string::const_iterator j = value.begin(); j != value.end(); ++j) {
            of << *j;
            if (*j == '\n')
                of << "# " << key << ": ";
        }
        of << endl;
    }
}

void export_plain_text(xylib::DataSet const *d, string const &fname,
                       bool with_metadata)
{
    int range_num = d->get_block_count();
    ofstream of(fname.c_str());
    if (!of)
        throw xylib::RunTimeError("can't create file: " + fname);

    // output the file-level meta-info
    of << "# exported by xylib from a " << d->fi->name << " file" << endl;
    if (with_metadata) {
        export_metadata(of, d->meta);
        of << endl;
    }

    for (int i = 0; i < range_num; ++i) {
        const xylib::Block *block = d->get_block(i);
        if (range_num > 1 || !block->get_name().empty())
            of << "\n### block #" << i << " " << block->get_name() << endl;
        if (with_metadata)
            export_metadata(of, block->meta);

        int ncol = block->get_column_count();
        of << "# ";
        // column 0 is pseudo-column with point indices, we skip it
        for (int k = 1; k <= ncol; ++k) {
            string const& name = block->get_column(k).get_name();
            if (k > 1)
                of << "\t";
            if (name.empty())
                of << "column_" << k;
            else
                of << name;
        }
        of << endl;

        int nrow = block->get_point_count();

        for (int j = 0; j < nrow; ++j) {
            for (int k = 1; k <= ncol; ++k) {
                if (k > 1)
                    of << "\t";
                of << setfill(' ') << setiosflags(ios::fixed)
                    << setprecision(6) << setw(8)
                    << block->get_column(k).get_value(j);
            }
            of << endl;
        }
    }
}

int convert_file(string const& input, string const& output,
                 string const& filetype, bool with_metadata)
{
    try {
        xylib::DataSet *d = xylib::load_file(input, filetype);
        export_plain_text(d, output, with_metadata);
        delete d;
    } catch (runtime_error const& e) {
        cerr << "Error. " << e.what() << endl;
        return -1;
    }
    return 0;
}

int main(int argc, char **argv)
{
    // options -l -h -i -g -v are not combined with other options

    if (argc == 2 && strcmp(argv[1], "-l") == 0) {
        list_supported_formats();
        return 0;
    }
    else if (argc == 2 &&
            (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) {
        print_usage();
        return 0;
    }
    else if (argc == 2 &&
            (strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--version") == 0)) {
        print_version();
        return 0;
    }
    else if (argc == 3 && strcmp(argv[1], "-i") == 0) {
        print_filetype_info(argv[2]);
        return 0;
    }
    else if (argc >= 3 && strcmp(argv[1], "-g") == 0)
        return print_guessed_filetype(argc - 2, argv + 2);
    else if (argc < 3) {
        print_usage();
        return -1;
    }

    string filetype;
    bool option_m = false;
    bool option_s = false;
    int n = 1;
    while (n < argc - 1) {
        if (strcmp(argv[n], "-m") == 0) {
            option_m = true;
            ++n;
        }
        else if (strcmp(argv[n], "-s") == 0) {
            option_s = true;
            ++n;
        }
        else if (strcmp(argv[n], "-t") == 0 && n+1 < argc - 1) {
            filetype = argv[n+1];
            n += 2;
        }
        else
            break;
    }
    if (!option_m && n != argc - 2) {
        print_usage();
        return -1;
    }
    if (option_m) {
        for ( ; n < argc; ++n) {
            string out = argv[n];
            size_t p = out.rfind('.');
            if (p != string::npos)
                out.erase(p);
            out += ".xy";
            cout << "converting " << argv[n] << " to " << out << endl;
            convert_file(argv[n], out, filetype, !option_s);
        }
        return 0;
    }
    else
        return convert_file(argv[argc-2], argv[argc-1], filetype, !option_s);
}

<|endoftext|>


<commit_before>#include "ros/ros.h"
#include "std_msgs/String.h"
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/LaserScan.h>

#include <sstream>
#include "math.h"

//velocity of the robot
double linear_x;
double angular_z;

//pose of the robot
double px;
double py;
double theta;

void StageOdom_callback(nav_msgs::Odometry msg)
{
	//This is the call back function to process odometry messages coming from Stage.

	px = 5 + msg.pose.pose.position.x;
	py =10 + msg.pose.pose.position.y;
	//printf("%f",px);

	// If the current position is the same the previous position, then the robot is stuck and needs to move around
	if ((px == prevpx) && (py == prevpy)) {
		//msg.pose.pose.position.x = 5;
		//ROS_INFO("Prevpx: %f",prevpx);

		// Note the negative linear_x
		linear_x=-0.2;
		angular_z=1;

		//theta=10;
		//px = 5;
		//py= 5;
		//printf("Robot stuck");
	} else {
		// One the robot becomes unstuck, then it moves around again normally
		linear_x = 0.2;
		angular_z = 0.2;
	}
	ROS_INFO("Current x position is: %f", px);
	ROS_INFO("Current y position is: %f", py);
	prevpx = px;
	prevpy = py;
}

void StageLaser_callback(sensor_msgs::LaserScan msg)
{
	//This is the callback function to process laser scan messages
	//you can access the range data from msg.ranges[i]. i = sample number

}

int main(int argc, char **argv)
{

 //initialize robot parameters
	//Initial pose. This is same as the pose that you used in the world file to set	the robot pose.
	theta = M_PI/2.0;
	px = 5;
	py = 10;
	prevpx=0;
	prevpy=0;

	//Initial velocity
	linear_x = 0.2;
	angular_z = 0.2;

//You must call ros::init() first of all. ros::init() function needs to see argc and argv. The third argument is the name of the node
ros::init(argc, argv, "RobotNode1");

//NodeHandle is the main access point to communicate with ros.
ros::NodeHandle n;

//advertise() function will tell ROS that you want to publish on a given topic_
//to stage
ros::Publisher RobotNode_stage_pub = n.advertise<geometry_msgs::Twist>("robot_1/cmd_vel",1000);

//subscribe to listen to messages coming from stage
ros::Subscriber StageOdo_sub = n.subscribe<nav_msgs::Odometry>("robot_1/odom",1000, StageOdom_callback);
ros::Subscriber StageLaser_sub = n.subscribe<sensor_msgs::LaserScan>("robot_1/base_scan",1000,StageLaser_callback);

ros::Rate loop_rate(10);

//a count of howmany messages we have sent
int count = 0;

////messages
//velocity of this RobotNode
geometry_msgs::Twist RobotNode_cmdvel;

while (ros::ok())
{
	//messages to stage
	RobotNode_cmdvel.linear.x = linear_x;
	RobotNode_cmdvel.angular.z = angular_z;

	//publish the message
	RobotNode_stage_pub.publish(RobotNode_cmdvel);

	ros::spinOnce();

	loop_rate.sleep();
	++count;
}

return 0;

}

<commit_msg>added initialisation of prevpx & prevpy<commit_after>#include "ros/ros.h"
#include "std_msgs/String.h"
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/LaserScan.h>

#include <sstream>
#include "math.h"

//velocity of the robot
double linear_x;
double angular_z;

//pose of the robot
double px;
double py;
double prevpx;
double prevpy;
double theta;

void StageOdom_callback(nav_msgs::Odometry msg)
{
	//This is the call back function to process odometry messages coming from Stage.

	px = 5 + msg.pose.pose.position.x;
	py =10 + msg.pose.pose.position.y;
	//printf("%f",px);

	// If the current position is the same the previous position, then the robot is stuck and needs to move around
	if ((px == prevpx) && (py == prevpy)) {
		//msg.pose.pose.position.x = 5;
		//ROS_INFO("Prevpx: %f",prevpx);

		// Note the negative linear_x
		linear_x=-0.2;
		angular_z=1;

		//theta=10;
		//px = 5;
		//py= 5;
		//printf("Robot stuck");
	} else {
		// One the robot becomes unstuck, then it moves around again normally
		linear_x = 0.2;
		angular_z = 0.2;
	}
	ROS_INFO("Current x position is: %f", px);
	ROS_INFO("Current y position is: %f", py);
	prevpx = px;
	prevpy = py;
}

void StageLaser_callback(sensor_msgs::LaserScan msg)
{
	//This is the callback function to process laser scan messages
	//you can access the range data from msg.ranges[i]. i = sample number

}

int main(int argc, char **argv)
{

 //initialize robot parameters
	//Initial pose. This is same as the pose that you used in the world file to set	the robot pose.
	theta = M_PI/2.0;
	px = 5;
	py = 10;
	prevpx=0;
	prevpy=0;

	//Initial velocity
	linear_x = 0.2;
	angular_z = 0.2;

//You must call ros::init() first of all. ros::init() function needs to see argc and argv. The third argument is the name of the node
ros::init(argc, argv, "RobotNode1");

//NodeHandle is the main access point to communicate with ros.
ros::NodeHandle n;

//advertise() function will tell ROS that you want to publish on a given topic_
//to stage
ros::Publisher RobotNode_stage_pub = n.advertise<geometry_msgs::Twist>("robot_1/cmd_vel",1000);

//subscribe to listen to messages coming from stage
ros::Subscriber StageOdo_sub = n.subscribe<nav_msgs::Odometry>("robot_1/odom",1000, StageOdom_callback);
ros::Subscriber StageLaser_sub = n.subscribe<sensor_msgs::LaserScan>("robot_1/base_scan",1000,StageLaser_callback);

ros::Rate loop_rate(10);

//a count of howmany messages we have sent
int count = 0;

////messages
//velocity of this RobotNode
geometry_msgs::Twist RobotNode_cmdvel;

while (ros::ok())
{
	//messages to stage
	RobotNode_cmdvel.linear.x = linear_x;
	RobotNode_cmdvel.angular.z = angular_z;

	//publish the message
	RobotNode_stage_pub.publish(RobotNode_cmdvel);

	ros::spinOnce();

	loop_rate.sleep();
	++count;
}

return 0;

}

<|endoftext|>


<commit_before>// Copyright (c) 2014 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "global.h"
#include "snippet.h"
#include "expr.h"

uint32_t Expr::var_index_ = 0;
Expr::VariableMap Expr::variables_;
Expr::BreakListStack Expr::end_;
Expr::ContinueListStack Expr::start_;
Expr::UintListStack Expr::scope_;

Expr::Expr(void)
  : left_(ExprPtr(nullptr))
  , right_(ExprPtr(nullptr)) {
}

Expr::~Expr(void) {
}

void Expr::PushResolve(void) {
  end_.push(std::list<BreakPtr>());
  start_.push(std::list<ContinuePtr>());
  scope_.push(std::list<uint32_t>());
}

void Expr::Resolve(FilePtr& out, uint32_t start_addr, uint32_t end_addr) {
  for (auto c : start_.top())
    c->Resolve(out, start_addr);
  start_.pop();

  for (auto b : end_.top())
    b->Resolve(out, end_addr);
  end_.pop();

  uint8_t cmd = static_cast<uint8_t>(OpCode::OPCODE_DEL);
  for (auto i : scope_.top()) {
  }
  scope_.pop();
}

OpCode Expr::GetType(const std::string& token) {
  OpCode code = OpCode::OPCODE_INVAL;

  if (token == "true" || token == "false")
    return OpCode::OPCODE_BOOL;
  else if (token.empty())
    return OpCode::OPCODE_STRING;

  for (auto c : token) {
    if (!isdigit(c) && '.' != c) {
      code = OpCode::OPCODE_STRING;
      break;
    }
    else if (code != OpCode::OPCODE_REAL) {
      code = OpCode::OPCODE_INT;
    }

    if ('.' == c)
      code = OpCode::OPCODE_REAL;
  }

  return code;
}

void Expr::Reset(void) {
  var_index_ = 0;
  variables_.clear();

  while (!end_.empty())
    end_.pop();

  while (!start_.empty())
    start_.pop();

  while (!scope_.empty())
    scope_.pop();
}

void Expr::EvalChildren(FilePtr& out) {
  if (left_)
    left_->Execute(out);

  if (right_)
    right_->Execute(out);
}
<commit_msg>implementation of BlockExpr<commit_after>// Copyright (c) 2014 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "global.h"
#include "snippet.h"
#include "expr.h"

uint32_t Expr::var_index_ = 0;
Expr::VariableMap Expr::variables_;
Expr::BreakListStack Expr::end_;
Expr::ContinueListStack Expr::start_;
Expr::UintListStack Expr::scope_;

Expr::Expr(void)
  : left_(ExprPtr(nullptr))
  , right_(ExprPtr(nullptr)) {
}

Expr::~Expr(void) {
}

void Expr::PushResolve(void) {
  end_.push(std::list<BreakPtr>());
  start_.push(std::list<ContinuePtr>());
  scope_.push(std::list<uint32_t>());
}

void Expr::Resolve(FilePtr& out, uint32_t start_addr, uint32_t end_addr) {
  for (auto c : start_.top())
    c->Resolve(out, start_addr);
  start_.pop();

  for (auto b : end_.top())
    b->Resolve(out, end_addr);
  end_.pop();

  uint8_t cmd = static_cast<uint8_t>(OpCode::OPCODE_DEL);
  for (auto i : scope_.top()) {
  }
  scope_.pop();
}

OpCode Expr::GetType(const std::string& token) {
  OpCode code = OpCode::OPCODE_INVAL;

  if (token == "true" || token == "false")
    return OpCode::OPCODE_BOOL;
  else if (token.empty())
    return OpCode::OPCODE_STRING;

  for (auto c : token) {
    if (!isdigit(c) && '.' != c) {
      code = OpCode::OPCODE_STRING;
      break;
    }
    else if (code != OpCode::OPCODE_REAL) {
      code = OpCode::OPCODE_INT;
    }

    if ('.' == c)
      code = OpCode::OPCODE_REAL;
  }

  return code;
}

void Expr::Reset(void) {
  var_index_ = 0;
  variables_.clear();

  while (!end_.empty())
    end_.pop();

  while (!start_.empty())
    start_.pop();

  while (!scope_.empty())
    scope_.pop();
}

void Expr::EvalChildren(FilePtr& out) {
  if (left_)
    left_->Execute(out);

  if (right_)
    right_->Execute(out);
}

BlockExpr::~BlockExpr(void) {
  blocks_.clear();
}

void BlockExpr::Execute(FilePtr& out) {
  for (auto expr : blocks_)
    expr->Execute(out);
}

void ValueExpr::Execute(FilePtr& out) {
  EvalChildren(out);

  OpCode code = GetType(value_);
  switch (code) {
  case OpCode::OPCODE_BOOL:
    {
      bool v = false;
      if (value_ == "true")
        v = true;
    } break;
  case OpCode::OPCODE_INT:
    {
      int v = atoi(value_.c_str());
    } break;
  case OpCode::OPCODE_REAL:
    {
      float v = static_cast<float>(atof(value_.c_str()));
    } break;
  case OpCode::OPCODE_STRING:
    break;
  default:
    break;
  }
}
<|endoftext|>


<commit_before>#include <ncurses.h>
#include <string>
#include <vector>

#include "configuration.hh"
#include "contents.hh"
#include "hooks.hh"
#include "file_contents.hh"
#include "visual.hh"
#include "show_message.hh"

static contents cont;

void init(std::vector<std::string> vec) {
    cont = contents(vec);
    print_contents(cont);
}

contents& get_contents() { return cont; }

void print_contents(contents& contents) {
    if(contents.y - contents.y_offset >= contents.max_y - 1) {
        contents.y_offset = contents.y - contents.y_offset + 1;
        show_message("hi");
    }
    if(contents.y < contents.y_offset) {
        contents.y_offset = contents.y;
        show_message("bye");
    }

    clear();
    int y = 0;

    int fin_y,fin_x; // if none set then random!

    for(unsigned int i = contents.y_offset;
        i < contents.cont.size()
            && i < contents.max_y - 1 + contents.y_offset; i++) {

        unsigned int x = 0;
        const std::string& line = contents.cont[i];
        int til = 0;

        if(line.begin() == line.end()) {
            if(contents.y == i && contents.x == 0) {
                fin_y = y;
                fin_x = x;
            }
        } else {
            for(std::string::const_iterator it = line.begin(); it < line.end(); it++) {
                if(*it == '\t') {
                    x += TAB_SIZE - til - 1;
                    if(x >= contents.max_x) {
                        x = -1;
                        y++;
                    }
                    move(y,x);
                    til = 0;
                } else {
                    addch(*it);
                    til++;
                    til %= TAB_SIZE;
                }
                if(x == contents.max_x) {
                    til = 0;
                    move(++y, x = 0);
                    addch(*it);
                }
                if(contents.y == i && contents.x == it - line.begin()) {
                    fin_y = y;
                    fin_x = x;
                }
                x++;
                move(y,x);
            }
            if(contents.y == i && contents.x >= line.size()) {
                fin_y = y;
                fin_x = x + (contents.is_inserting ? 0 : -1);
            }
        }
        move(++y,0);
    }
    //contents.y, to_visual(contents.cont[contents.y],contents.x)
    move(fin_y,fin_x);
    proc_hook(Hook::REFRESH);
}
<commit_msg>Use auto for iterator type deduction<commit_after>#include <ncurses.h>
#include <string>
#include <vector>

#include "configuration.hh"
#include "contents.hh"
#include "hooks.hh"
#include "file_contents.hh"
#include "visual.hh"
#include "show_message.hh"

static contents cont;

void init(std::vector<std::string> vec) {
    cont = contents(vec);
    print_contents(cont);
}

contents& get_contents() { return cont; }

void print_contents(contents& contents) {
    if(contents.y - contents.y_offset >= contents.max_y - 1) {
        contents.y_offset = contents.y - contents.y_offset + 1;
        show_message("hi");
    }
    if(contents.y < contents.y_offset) {
        contents.y_offset = contents.y;
        show_message("bye");
    }

    clear();
    int y = 0;

    int fin_y,fin_x; // if none set then random!

    for(unsigned int i = contents.y_offset;
        i < contents.cont.size()
            && i < contents.max_y - 1 + contents.y_offset; i++) {

        unsigned int x = 0;
        const std::string& line = contents.cont[i];
        int til = 0;

        if(line.begin() == line.end()) {
            if(contents.y == i && contents.x == 0) {
                fin_y = y;
                fin_x = x;
            }
        } else {
            for(auto it = line.begin(); it < line.end(); it++) {
                if(*it == '\t') {
                    x += TAB_SIZE - til - 1;
                    if(x >= contents.max_x) {
                        x = -1;
                        y++;
                    }
                    move(y,x);
                    til = 0;
                } else {
                    addch(*it);
                    til++;
                    til %= TAB_SIZE;
                }
                if(x == contents.max_x) {
                    til = 0;
                    move(++y, x = 0);
                    addch(*it);
                }
                if(contents.y == i && contents.x == it - line.begin()) {
                    fin_y = y;
                    fin_x = x;
                }
                x++;
                move(y,x);
            }
            if(contents.y == i && contents.x >= line.size()) {
                fin_y = y;
                fin_x = x + (contents.is_inserting ? 0 : -1);
            }
        }
        move(++y,0);
    }
    //contents.y, to_visual(contents.cont[contents.y],contents.x)
    move(fin_y,fin_x);
    proc_hook(Hook::REFRESH);
}
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Jules Cléro
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "libDroneVideo/FrameGrabber.hpp"

#include <boost/log/trivial.hpp>

#include <sys/stat.h>
#include <fcntl.h>

#include <chrono>
#include <thread>

namespace ghost
{
namespace libDroneVideo
{

FrameGrabber::FrameGrabber() : mDroneVerticalFrame({ 0 })
{
}

int FrameGrabber::getVerticalFrameWidth()
{
    return libDroneVideoSharing::CameraDefinition::mVerticalImgWidth;
}

int FrameGrabber::getVerticalFrameHeight()
{
    return libDroneVideoSharing::CameraDefinition::mVerticalImgHeight;
}

FrameGrabber::DroneVerticalFrame& FrameGrabber::getNextVerticalFrame()
{

    int query = 0;
    int failThreshold = 5;

    do {
        // Check if the frame is ready
        if (access(CAMV_READY, F_OK) != -1) {
            int fd = open(CAMV_BUFFER, O_RDONLY);

            // Get the frame
            read(fd,
                 &mDroneVerticalFrame[0],
                 libDroneVideoSharing::CameraDefinition::mVerticalImgSize);
            close(fd);
            remove(CAMV_READY);

            break;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(25));
    } while (++query != failThreshold);

    if (query == failThreshold) {
        BOOST_LOG_TRIVIAL(warning) << "Vertical camera buffer unaivalable";
    }

    return std::ref(mDroneVerticalFrame);
}

} /* libDroneVideo namespace */
} /* ghost namespace  */
<commit_msg>[libDroneVideo] Change FrameGrabber timeout timing<commit_after>/*
 * Copyright 2014 Jules Cléro
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "libDroneVideo/FrameGrabber.hpp"

#include <boost/log/trivial.hpp>

#include <sys/stat.h>
#include <fcntl.h>

#include <chrono>
#include <thread>

namespace ghost
{
namespace libDroneVideo
{

FrameGrabber::FrameGrabber() : mDroneVerticalFrame({ 0 })
{
}

int FrameGrabber::getVerticalFrameWidth()
{
    return libDroneVideoSharing::CameraDefinition::mVerticalImgWidth;
}

int FrameGrabber::getVerticalFrameHeight()
{
    return libDroneVideoSharing::CameraDefinition::mVerticalImgHeight;
}

FrameGrabber::DroneVerticalFrame& FrameGrabber::getNextVerticalFrame()
{

    int query = 0;
    int failThreshold = 20;

    do {
        // Check if the frame is ready
        if (access(CAMV_READY, F_OK) != -1) {
            int fd = open(CAMV_BUFFER, O_RDONLY);

            // Get the frame
            read(fd,
                 &mDroneVerticalFrame[0],
                 libDroneVideoSharing::CameraDefinition::mVerticalImgSize);
            close(fd);
            remove(CAMV_READY);

            break;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(5));
    } while (++query != failThreshold);

    if (query == failThreshold) {
        BOOST_LOG_TRIVIAL(warning) << "Vertical camera buffer unaivalable";
    }

    return std::ref(mDroneVerticalFrame);
}

} /* libDroneVideo namespace */
} /* ghost namespace  */
<|endoftext|>