<commit_before>// Copyright (c) 2011, Robert Escriva
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of this project nor the names of its contributors may
//       be used to endorse or promote products derived from this software
//       without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#ifndef e_timer_h_
#define e_timer_h_

// C
#include <stdint.h>

#if HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef _MSC_VER
// Windows
#define _WINSOCKAPI_
#include <windows.h>
#endif

//mach
#ifdef HAVE_MACH_ABSOLUTE_TIME
#include <mach/mach_time.h>
#endif

// POSIX
#include <errno.h>
#include <time.h>

// STL
#include <exception>

// po6
#include <po6/error.h>

// e
#include "e/time.h"

uint64_t
e :: time()
{
#ifdef _MSC_VER
    LARGE_INTEGER tickfreq, timestamp;
    tickfreq.QuadPart = 0;
    timestamp.QuadPart = 0;
    QueryPerformanceFrequency((LARGE_INTEGER*)&tickfreq);
    QueryPerformanceCounter((LARGE_INTEGER*)&timestamp);
    return timestamp.QuadPart / (tickfreq.QuadPart/1000000000.0);
#elif defined HAVE_MACH_TIMEBASE_INFO
    mach_timebase_info_data_t info;
    mach_timebase_info(&info);
    return mach_absolute_time()*info.numer/info.denom;
#else
    timespec ts;

    if (clock_gettime(CLOCK_REALTIME, &ts) < 0)
    {
        throw po6::error(errno);
    }

    return ts.tv_sec * 1000000000 + ts.tv_nsec;
#endif
}

#endif // e_timer_h__
<commit_msg>fix ifdef for OSX<commit_after>// Copyright (c) 2011, Robert Escriva
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of this project nor the names of its contributors may
//       be used to endorse or promote products derived from this software
//       without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#ifndef e_timer_h_
#define e_timer_h_

// C
#include <stdint.h>

#if HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef _MSC_VER
// Windows
#define _WINSOCKAPI_
#include <windows.h>
#endif

//mach
#ifdef HAVE_MACH_ABSOLUTE_TIME
#include <mach/mach_time.h>
#endif

// POSIX
#include <errno.h>
#include <time.h>

// STL
#include <exception>

// po6
#include <po6/error.h>

// e
#include "e/time.h"

uint64_t
e :: time()
{
#ifdef _MSC_VER
    LARGE_INTEGER tickfreq, timestamp;
    tickfreq.QuadPart = 0;
    timestamp.QuadPart = 0;
    QueryPerformanceFrequency((LARGE_INTEGER*)&tickfreq);
    QueryPerformanceCounter((LARGE_INTEGER*)&timestamp);
    return timestamp.QuadPart / (tickfreq.QuadPart/1000000000.0);
#elif defined HAVE_MACH_ABSOLUTE_TIME
    mach_timebase_info_data_t info;
    mach_timebase_info(&info);
    return mach_absolute_time()*info.numer/info.denom;
#else
    timespec ts;

    if (clock_gettime(CLOCK_REALTIME, &ts) < 0)
    {
        throw po6::error(errno);
    }

    return ts.tv_sec * 1000000000 + ts.tv_nsec;
#endif
}

#endif // e_timer_h__
<|endoftext|>


<commit_before>#include "keyboardinterface.h"

#include <SDL2/SDL_keyboard.h>
#include <SDL2/SDL_events.h>

#include "context.h"

namespace sdli {

KeyboardInterface::KeyboardInterface(const int max_actions, const int max_axes)
    : logicAnalogData(max_axes),
      captureBuffer(max_actions)
{

}

KeyboardInterface::~KeyboardInterface()
{

}

void KeyboardInterface::poll(Context& ctx)
{
    auto sdl_keystate = SDL_GetKeyboardState(NULL);

    auto& keymap = ctx.keyboardKeys();
    auto& axisMap = ctx.axisMapping();

    auto axisIt = axisMap.begin();
    auto axisEnd = axisMap.end();

    for(;axisIt!=axisEnd;++axisIt)
    {
        if(axisIt->idx.deviceType == SDL_Axis::Type::Keyboard)
        {
            auto data = axisIt->data;

            auto pollResult = 0.0f;

            auto neg = sdl_keystate[axisIt->idx.axis.rawNegative];
            auto pos = sdl_keystate[axisIt->idx.axis.rawPositive];

            if(neg == SDL_PRESSED)
            {
                pollResult -= 1.0f;
            }
            if(pos == SDL_PRESSED)
            {
                pollResult += 1.0f;
            }
            if(logicAnalogData.at(data->axis)==nullptr)
            {
                logicAnalogData.emplace(data->axis);
            }

            auto& currentStatus = logicAnalogData.get(data->axis).currentStatus;
            if(currentStatus!=0.0f)
            {
                currentStatus = sdli::clamp(currentStatus + pollResult, -1, 1) / data->normalize;
            }
            else
            {
                currentStatus = pollResult / data->normalize;
            }
        }
    }

    auto it = keymap.begin();

    for(;it!=keymap.end();++it)
    {
        auto state = sdl_keystate[it->idx];
        auto action = *(it->data);
        if(captureBuffer.at(action)==nullptr)
        {
            captureBuffer.emplace(action);
        }

        captureBuffer.get(action).previousStatus = captureBuffer.get(action).currentStatus;
        captureBuffer.get(action).currentStatus = state;
    }
}

void KeyboardInterface::push(unsigned int rawInput, int value)
{
    perFrameCaptures.emplace_back(RawInputData{rawInput, value});
}

void KeyboardInterface::dispatch(Context& ctx)
{
    for(auto& raw : perFrameCaptures)
    {
        auto inputAction = ctx.keyAction(static_cast<SDL_Scancode>(raw.rawInput));
        if(captureBuffer.at(inputAction) == nullptr)
        {
            captureBuffer.emplace(inputAction);
        }
        auto& logic = captureBuffer.get(inputAction);

        logic.currentStatus = raw.pollResult;

        if(::sdli::isPressed(logic))
        {
            ctx.fireCallbacks(inputAction, sdli::CallType::OnPress);
        }

        if(::sdli::isReleased(logic))
        {
            ctx.fireCallbacks(inputAction, sdli::CallType::OnRelease);
        }
    }
    perFrameCaptures.clear();
}

float KeyboardInterface::getRange(InputAxis axis)
{
    if(logicAnalogData.at(axis) == nullptr)
    {
        return ::sdli::RANGE_UNDEFINED;
    }

    return logicAnalogData.get(axis).currentStatus;
}

bool KeyboardInterface::isPressed(InputAction action)
{
    if(captureBuffer.at(action) == nullptr)
    {
        return ::sdli::IS_PRESSED_UNDEFINED;
    }

    return ::sdli::isPressed(captureBuffer.get(action));
}

bool KeyboardInterface::isReleased(InputAction action)
{
    if(captureBuffer.at(action) == nullptr)
    {
        return ::sdli::IS_RELEASED_UNDEFINED;
    }

    return ::sdli::isReleased(captureBuffer.get(action));
}

bool KeyboardInterface::isDown(InputAction action)
{
    if(captureBuffer.at(action) == nullptr)
    {
        return ::sdli::IS_DOWN_UNDEFINED;
    }

    return ::sdli::isDown(captureBuffer.get(action));
}

bool KeyboardInterface::isUp(InputAction action)
{
    if(captureBuffer.at(action) == nullptr)
    {
        return ::sdli::IS_UP_UNDEFINED;
    }

    return ::sdli::isUp(captureBuffer.get(action));
}

void KeyboardInterface::swap()
{
    auto it = captureBuffer.dataBegin();
    auto end = captureBuffer.dataEnd();
    for(;it!=end;++it)
    {
        it->previousStatus = it->currentStatus;
    }

    auto pollIt = logicAnalogData.dataBegin();
    auto pollEnd= logicAnalogData.dataEnd();

    for(;pollIt!=pollEnd;++pollIt)
    {
        pollIt->currentStatus = 0.0f;
    }
}

} // sdli
<commit_msg>Fixed multiple keys for a single action not correctly fetching events (isPressed)<commit_after>#include "keyboardinterface.h"

#include <SDL2/SDL_keyboard.h>
#include <SDL2/SDL_events.h>

#include "context.h"

namespace sdli {

KeyboardInterface::KeyboardInterface(const int max_actions, const int max_axes)
    : logicAnalogData(max_axes),
      captureBuffer(max_actions)
{

}

KeyboardInterface::~KeyboardInterface()
{

}

void KeyboardInterface::poll(Context& ctx)
{
    auto sdl_keystate = SDL_GetKeyboardState(NULL);

    auto& keymap = ctx.keyboardKeys();
    auto& axisMap = ctx.axisMapping();

    auto axisIt = axisMap.begin();
    auto axisEnd = axisMap.end();

    for(;axisIt!=axisEnd;++axisIt)
    {
        if(axisIt->idx.deviceType == SDL_Axis::Type::Keyboard)
        {
            auto data = axisIt->data;

            auto pollResult = 0.0f;

            auto neg = sdl_keystate[axisIt->idx.axis.rawNegative];
            auto pos = sdl_keystate[axisIt->idx.axis.rawPositive];

            if(neg == SDL_PRESSED)
            {
                pollResult -= 1.0f;
            }
            if(pos == SDL_PRESSED)
            {
                pollResult += 1.0f;
            }
            if(logicAnalogData.at(data->axis)==nullptr)
            {
                logicAnalogData.emplace(data->axis);
            }

            auto& currentStatus = logicAnalogData.get(data->axis).currentStatus;
            if(currentStatus!=0.0f)
            {
                currentStatus = sdli::clamp(currentStatus + pollResult, -1, 1) / data->normalize;
            }
            else
            {
                currentStatus = pollResult / data->normalize;
            }
        }
    }

    auto it = keymap.begin();

    std::vector<unsigned int> polled(captureBuffer.size());
    auto hasPolled = [](unsigned int id, std::vector<unsigned int>& v)
    {
        auto it = v.cbegin();
        auto end = v.cend();
        for(;it!=end;++it)
        {
            if(id == *it)
                return true;
        }
        return false;
    };

    for(;it!=keymap.end();++it)
    {
        auto state = sdl_keystate[it->idx];
        auto action = *(it->data);
        if(captureBuffer.at(action)==nullptr)
        {
            captureBuffer.emplace(action);
        }

        if(hasPolled(action, polled))
        {
            captureBuffer.get(action).currentStatus |= state;
        }
        else
        {
            captureBuffer.get(action).previousStatus = captureBuffer.get(action).currentStatus;
            captureBuffer.get(action).currentStatus = state;
            polled.push_back(action);
        }
    }
}

void KeyboardInterface::push(unsigned int rawInput, int value)
{
    perFrameCaptures.emplace_back(RawInputData{rawInput, value});
}

void KeyboardInterface::dispatch(Context& ctx)
{
    for(auto& raw : perFrameCaptures)
    {
        auto inputAction = ctx.keyAction(static_cast<SDL_Scancode>(raw.rawInput));
        if(captureBuffer.at(inputAction) == nullptr)
        {
            captureBuffer.emplace(inputAction);
        }
        auto& logic = captureBuffer.get(inputAction);

        logic.currentStatus = raw.pollResult;

        if(::sdli::isPressed(logic))
        {
            ctx.fireCallbacks(inputAction, sdli::CallType::OnPress);
        }

        if(::sdli::isReleased(logic))
        {
            ctx.fireCallbacks(inputAction, sdli::CallType::OnRelease);
        }
    }
    perFrameCaptures.clear();
}

float KeyboardInterface::getRange(InputAxis axis)
{
    if(logicAnalogData.at(axis) == nullptr)
    {
        return ::sdli::RANGE_UNDEFINED;
    }

    return logicAnalogData.get(axis).currentStatus;
}

bool KeyboardInterface::isPressed(InputAction action)
{
    if(captureBuffer.at(action) == nullptr)
    {
        return ::sdli::IS_PRESSED_UNDEFINED;
    }

    return ::sdli::isPressed(captureBuffer.get(action));
}

bool KeyboardInterface::isReleased(InputAction action)
{
    if(captureBuffer.at(action) == nullptr)
    {
        return ::sdli::IS_RELEASED_UNDEFINED;
    }

    return ::sdli::isReleased(captureBuffer.get(action));
}

bool KeyboardInterface::isDown(InputAction action)
{
    if(captureBuffer.at(action) == nullptr)
    {
        return ::sdli::IS_DOWN_UNDEFINED;
    }

    return ::sdli::isDown(captureBuffer.get(action));
}

bool KeyboardInterface::isUp(InputAction action)
{
    if(captureBuffer.at(action) == nullptr)
    {
        return ::sdli::IS_UP_UNDEFINED;
    }

    return ::sdli::isUp(captureBuffer.get(action));
}

void KeyboardInterface::swap()
{
    auto it = captureBuffer.dataBegin();
    auto end = captureBuffer.dataEnd();
    for(;it!=end;++it)
    {
        it->previousStatus = it->currentStatus;
    }

    auto pollIt = logicAnalogData.dataBegin();
    auto pollEnd= logicAnalogData.dataEnd();

    for(;pollIt!=pollEnd;++pollIt)
    {
        pollIt->currentStatus = 0.0f;
    }
}

} // sdli
<|endoftext|>


<commit_before>#include "BinaryRRP.h"
#include "Exception.h"
#include "typedef.h"
#include "tools.h"
#include "Lzma.h"
#include "ImageIDer.h"

#include <json/json.h>
#include <assert.h>
#include <fstream>
#include <algorithm>

#include <dtex_rrp.h>

namespace epbin
{

static const uint8_t TYPE = 11;

BinaryRRP::BinaryRRP(const std::string& json_file, const std::string& img_id_file)
{
	Load(json_file, img_id_file);
}

BinaryRRP::~BinaryRRP()
{
	for (int i = 0, n = m_pics.size(); i < n; ++i) {
		Picture* pic = m_pics[i];
		for (int j = 0, m = pic->parts.size(); j < m; ++j) {
			delete pic->parts[j];
		}
		delete pic;
	}
}

void BinaryRRP::Pack(const std::string& outfile, bool compress) const
{
	int32_t pic_sz = m_pics.size();

	// data sz
	size_t data_sz = 0;
	data_sz += sizeof(int32_t);
	for (int i = 0; i < pic_sz; ++i) {
		data_sz += m_pics[i]->Size();
	}

	// fill buffer
	uint8_t* data_buf = new uint8_t[data_sz];
	uint8_t* ptr_data = data_buf;
	memcpy(ptr_data, &pic_sz, sizeof(pic_sz));
	ptr_data += sizeof(pic_sz);
	for (int i = 0; i < pic_sz; ++i) {
		m_pics[i]->Store(&ptr_data);
	}
	assert(ptr_data - data_buf == data_sz);

	// final
	size_t sz = data_sz + sizeof(uint8_t) + sizeof(uint32_t);
	uint8_t* buf = new uint8_t[sz];
	uint8_t* ptr = buf;
	memcpy(ptr, &TYPE, sizeof(uint8_t));
	ptr += sizeof(uint8_t);
	int cap = dtex_rrp_size(data_buf, data_sz);
	memcpy(ptr, &cap, sizeof(uint32_t));
	ptr += sizeof(uint32_t);
	memcpy(ptr, data_buf, data_sz);
	delete[] data_buf;

	// write to file
	std::ofstream fout(outfile.c_str(), std::ios::binary);
	if (compress)
	{
		uint8_t* dst = NULL;
		size_t dst_sz;
		Lzma::Compress(&dst, &dst_sz, buf, sz);

		fout.write(reinterpret_cast<const char*>(&dst_sz), sizeof(uint32_t));
		fout.write(reinterpret_cast<const char*>(dst), dst_sz);
	}
	else
	{
		int _sz = -(int)sz;
		fout.write(reinterpret_cast<const char*>(&_sz), sizeof(int32_t));
		fout.write(reinterpret_cast<const char*>(buf), sz);
	}
	delete[] buf;
	fout.close();
}

void BinaryRRP::Load(const std::string& json_file, const std::string& img_id_file)
{
	// load file
	Json::Value value;
	Json::Reader reader;
	std::locale::global(std::locale(""));
	std::ifstream fin(json_file.c_str());
	std::locale::global(std::locale("C"));
	reader.parse(fin, value);
	fin.close();

	// parser json
	std::vector<Part*> parts;
	int i = 0;
	Json::Value val = value["parts"][i++];
	while (!val.isNull()) {
		std::string path = val["filepath"].asString();
		Part* p = new Part;

		p->src.x = val["src"]["x"].asInt();
		p->src.y = val["src"]["y"].asInt();
		p->src.w = val["src"]["w"].asInt();
		p->src.h = val["src"]["h"].asInt();

		p->dst.x = val["dst"]["x"].asInt();
		p->dst.y = val["dst"]["y"].asInt();
		p->dst.w = val["dst"]["w"].asInt();
		p->dst.h = val["dst"]["h"].asInt();

		p->filepath = path;

		parts.push_back(p);
		val = value["parts"][i++];
	}
	if (parts.empty()) {
		return;
	}

	// part to pictures
	std::sort(parts.begin(), parts.end(), PartCmp());
	Picture* pic = new Picture;
	size_t ptr_s = parts[0]->filepath.find_last_of("\\")+1,
		ptr_e = parts[0]->filepath.find_first_of("#");
	pic->path = parts[0]->filepath.substr(ptr_s, ptr_e - ptr_s);
	pic->parts.push_back(parts[0]);
	for (int i = 1, n = parts.size(); i < n; ++i)
	{
		Part* p = parts[i];
		if (p->filepath.find(pic->path) != std::string::npos) {
			pic->parts.push_back(p);
		} else {
			m_pics.push_back(pic);
			pic = new Picture;
			size_t ptr_s = p->filepath.find_last_of("\\")+1,
				ptr_e = p->filepath.find_first_of("#");
			pic->path = p->filepath.substr(ptr_s, ptr_e - ptr_s);
			std::transform(pic->path.begin(), pic->path.end(), pic->path.begin(), ::tolower);
			pic->parts.push_back(p);
		}
	}
	m_pics.push_back(pic);

	// set picture region
	for (int i = 0, n = m_pics.size(); i < n; ++i) {
		Picture* pic = m_pics[i];
		int xmin = INT_MAX, ymin = INT_MAX,
			xmax = -INT_MAX, ymax = -INT_MAX;
		for (int j = 0, m = pic->parts.size(); j < m; ++j) {
			const Rect& r = pic->parts[j]->src;
			if (r.x < xmin) xmin = r.x;
			if (r.x+r.w > xmax) xmax = r.x+r.w;
			if (r.y < ymin) ymin = r.y;
			if (r.y+r.h > ymax) ymax = r.y+r.h;
		}
		pic->w = xmax - xmin;
		pic->h = ymax - ymin;
	}

	// set picture id
	ImageIDer ider(img_id_file);
	for (int i = 0, n = m_pics.size(); i < n; ++i) {
		m_pics[i]->id = ider.Query(pic->path);
	}
}

//////////////////////////////////////////////////////////////////////////
// struct BinaryRRP::Part
//////////////////////////////////////////////////////////////////////////

size_t BinaryRRP::Part::Size() const
{
	return sizeof(int16_t) * 6;
}

void BinaryRRP::Part::Store(uint8_t** ptr)
{
	memcpy(*ptr, &src.x, sizeof(src.x));
	*ptr += sizeof(src.x);
	memcpy(*ptr, &src.y, sizeof(src.y));
	*ptr += sizeof(src.y);

	memcpy(*ptr, &dst.x, sizeof(dst.x));
	*ptr += sizeof(dst.x);
	memcpy(*ptr, &dst.y, sizeof(dst.y));
	*ptr += sizeof(dst.y);

	int16_t w = src.w, h = src.h;
	if (src.w != dst.w) {
		assert(src.w == dst.h);
		w = -w; h = -h;
	}
	memcpy(*ptr, &w, sizeof(w));
	*ptr += sizeof(w);
	memcpy(*ptr, &h, sizeof(h));
	*ptr += sizeof(h);
}

//////////////////////////////////////////////////////////////////////////
// struct BinaryRRP::Picture
//////////////////////////////////////////////////////////////////////////

size_t BinaryRRP::Picture::Size() const
{
	size_t sz = 0;
	sz += sizeof(int16_t) * 4;
	for (int i = 0, n = parts.size(); i < n; ++i) {
		sz += parts[i]->Size();
	}
	return sz;
}

void BinaryRRP::Picture::Store(uint8_t** ptr)
{
	memcpy(*ptr, &id, sizeof(id));
	*ptr += sizeof(id);

	memcpy(*ptr, &w, sizeof(w));
	*ptr += sizeof(w);
	memcpy(*ptr, &h, sizeof(h));
	*ptr += sizeof(h);

	int16_t sz = parts.size();
	memcpy(*ptr, &sz, sizeof(sz));
	*ptr += sizeof(sz);
	for (int i = 0; i < sz; ++i) {
		parts[i]->Store(ptr);
	}
}

}<commit_msg>[FIXED] 打包rrp数据时y坐标转成向上<commit_after>#include "BinaryRRP.h"
#include "Exception.h"
#include "typedef.h"
#include "tools.h"
#include "Lzma.h"
#include "ImageIDer.h"

#include <json/json.h>
#include <assert.h>
#include <fstream>
#include <algorithm>

#include <dtex_rrp.h>

namespace epbin
{

static const uint8_t TYPE = 11;

BinaryRRP::BinaryRRP(const std::string& json_file, const std::string& img_id_file)
{
	Load(json_file, img_id_file);
}

BinaryRRP::~BinaryRRP()
{
	for (int i = 0, n = m_pics.size(); i < n; ++i) {
		Picture* pic = m_pics[i];
		for (int j = 0, m = pic->parts.size(); j < m; ++j) {
			delete pic->parts[j];
		}
		delete pic;
	}
}

void BinaryRRP::Pack(const std::string& outfile, bool compress) const
{
	int32_t pic_sz = m_pics.size();

	// data sz
	size_t data_sz = 0;
	data_sz += sizeof(int32_t);
	for (int i = 0; i < pic_sz; ++i) {
		data_sz += m_pics[i]->Size();
	}

	// fill buffer
	uint8_t* data_buf = new uint8_t[data_sz];
	uint8_t* ptr_data = data_buf;
	memcpy(ptr_data, &pic_sz, sizeof(pic_sz));
	ptr_data += sizeof(pic_sz);
	for (int i = 0; i < pic_sz; ++i) {
		m_pics[i]->Store(&ptr_data);
	}
	assert(ptr_data - data_buf == data_sz);

	// final
	size_t sz = data_sz + sizeof(uint8_t) + sizeof(uint32_t);
	uint8_t* buf = new uint8_t[sz];
	uint8_t* ptr = buf;
	memcpy(ptr, &TYPE, sizeof(uint8_t));
	ptr += sizeof(uint8_t);
	int cap = dtex_rrp_size(data_buf, data_sz);
	memcpy(ptr, &cap, sizeof(uint32_t));
	ptr += sizeof(uint32_t);
	memcpy(ptr, data_buf, data_sz);
	delete[] data_buf;

	// write to file
	std::ofstream fout(outfile.c_str(), std::ios::binary);
	if (compress)
	{
		uint8_t* dst = NULL;
		size_t dst_sz;
		Lzma::Compress(&dst, &dst_sz, buf, sz);

		fout.write(reinterpret_cast<const char*>(&dst_sz), sizeof(uint32_t));
		fout.write(reinterpret_cast<const char*>(dst), dst_sz);
	}
	else
	{
		int _sz = -(int)sz;
		fout.write(reinterpret_cast<const char*>(&_sz), sizeof(int32_t));
		fout.write(reinterpret_cast<const char*>(buf), sz);
	}
	delete[] buf;
	fout.close();
}

void BinaryRRP::Load(const std::string& json_file, const std::string& img_id_file)
{
	// load file
	Json::Value value;
	Json::Reader reader;
	std::locale::global(std::locale(""));
	std::ifstream fin(json_file.c_str());
	std::locale::global(std::locale("C"));
	reader.parse(fin, value);
	fin.close();

	// parser json
	int height = value["height"].asUInt();
	std::vector<Part*> parts;
	int i = 0;
	Json::Value val = value["parts"][i++];
	while (!val.isNull()) {
		std::string path = val["filepath"].asString();
		Part* p = new Part;

		p->src.x = val["src"]["x"].asInt();
		p->src.y = val["src"]["y"].asInt();
		p->src.w = val["src"]["w"].asInt();
		p->src.h = val["src"]["h"].asInt();

		p->dst.x = val["dst"]["x"].asInt();
		p->dst.y = val["dst"]["y"].asInt();
		p->dst.w = val["dst"]["w"].asInt();
		p->dst.h = val["dst"]["h"].asInt();

		p->dst.y = height - (p->dst.y + p->dst.h);

		p->filepath = path;

		parts.push_back(p);
		val = value["parts"][i++];
	}
	if (parts.empty()) {
		return;
	}

	// part to pictures
	std::sort(parts.begin(), parts.end(), PartCmp());
	Picture* pic = new Picture;
	size_t ptr_s = parts[0]->filepath.find_last_of("\\")+1,
		ptr_e = parts[0]->filepath.find_first_of("#");
	pic->path = parts[0]->filepath.substr(ptr_s, ptr_e - ptr_s);
	pic->parts.push_back(parts[0]);
	for (int i = 1, n = parts.size(); i < n; ++i)
	{
		Part* p = parts[i];
		if (p->filepath.find(pic->path) != std::string::npos) {
			pic->parts.push_back(p);
		} else {
			m_pics.push_back(pic);
			pic = new Picture;
			size_t ptr_s = p->filepath.find_last_of("\\")+1,
				ptr_e = p->filepath.find_first_of("#");
			pic->path = p->filepath.substr(ptr_s, ptr_e - ptr_s);
			std::transform(pic->path.begin(), pic->path.end(), pic->path.begin(), ::tolower);
			pic->parts.push_back(p);
		}
	}
	m_pics.push_back(pic);

	// set picture region
	for (int i = 0, n = m_pics.size(); i < n; ++i) {
		Picture* pic = m_pics[i];
		int xmin = INT_MAX, ymin = INT_MAX,
			xmax = -INT_MAX, ymax = -INT_MAX;
		for (int j = 0, m = pic->parts.size(); j < m; ++j) {
			const Rect& r = pic->parts[j]->src;
			if (r.x < xmin) xmin = r.x;
			if (r.x+r.w > xmax) xmax = r.x+r.w;
			if (r.y < ymin) ymin = r.y;
			if (r.y+r.h > ymax) ymax = r.y+r.h;
		}
		pic->w = xmax - xmin;
		pic->h = ymax - ymin;
	}

	// set picture id
	ImageIDer ider(img_id_file);
	for (int i = 0, n = m_pics.size(); i < n; ++i) {
		m_pics[i]->id = ider.Query(pic->path);
	}
}

//////////////////////////////////////////////////////////////////////////
// struct BinaryRRP::Part
//////////////////////////////////////////////////////////////////////////

size_t BinaryRRP::Part::Size() const
{
	return sizeof(int16_t) * 6;
}

void BinaryRRP::Part::Store(uint8_t** ptr)
{
	memcpy(*ptr, &src.x, sizeof(src.x));
	*ptr += sizeof(src.x);
	memcpy(*ptr, &src.y, sizeof(src.y));
	*ptr += sizeof(src.y);

	memcpy(*ptr, &dst.x, sizeof(dst.x));
	*ptr += sizeof(dst.x);
	memcpy(*ptr, &dst.y, sizeof(dst.y));
	*ptr += sizeof(dst.y);

	int16_t w = src.w, h = src.h;
	if (src.w != dst.w) {
		assert(src.w == dst.h);
		w = -w; h = -h;
	}
	memcpy(*ptr, &w, sizeof(w));
	*ptr += sizeof(w);
	memcpy(*ptr, &h, sizeof(h));
	*ptr += sizeof(h);
}

//////////////////////////////////////////////////////////////////////////
// struct BinaryRRP::Picture
//////////////////////////////////////////////////////////////////////////

size_t BinaryRRP::Picture::Size() const
{
	size_t sz = 0;
	sz += sizeof(int16_t) * 4;
	for (int i = 0, n = parts.size(); i < n; ++i) {
		sz += parts[i]->Size();
	}
	return sz;
}

void BinaryRRP::Picture::Store(uint8_t** ptr)
{
	memcpy(*ptr, &id, sizeof(id));
	*ptr += sizeof(id);

	memcpy(*ptr, &w, sizeof(w));
	*ptr += sizeof(w);
	memcpy(*ptr, &h, sizeof(h));
	*ptr += sizeof(h);

	int16_t sz = parts.size();
	memcpy(*ptr, &sz, sizeof(sz));
	*ptr += sizeof(sz);
	for (int i = 0; i < sz; ++i) {
		parts[i]->Store(ptr);
	}
}

}<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 * Vulkan Conformance Tests
 * ------------------------
 *
 * Copyright (c) 2016 The Khronos Group Inc.
 * Copyright (c) 2016 Samsung Electronics Co., Ltd.
 * Copyright (c) 2014 The Android Open Source Project
 *
 * 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.
 *
 *//*!
 * \file
 * \brief Compressed texture tests.
 *//*--------------------------------------------------------------------*/

#include "vktTextureCompressedFormatTests.hpp"

#include "deString.h"
#include "deStringUtil.hpp"
#include "tcuCompressedTexture.hpp"
#include "tcuTexture.hpp"
#include "tcuTextureUtil.hpp"
#include "tcuAstcUtil.hpp"
#include "vkImageUtil.hpp"
#include "vktTestGroupUtil.hpp"
#include "vktTextureTestUtil.hpp"
#include <string>
#include <vector>

namespace vkt
{
namespace texture
{
namespace
{

using namespace vk;
using namespace glu::TextureTestUtil;
using namespace texture::util;

using std::string;
using std::vector;
using tcu::Sampler;
using tcu::TestLog;

struct Compressed2DTestParameters : public Texture2DTestCaseParameters
{
										Compressed2DTestParameters	(void);
	TextureBinding::ImageBackingMode	backingMode;
};

Compressed2DTestParameters::Compressed2DTestParameters (void)
	: backingMode(TextureBinding::IMAGE_BACKING_MODE_REGULAR)
{
}

class Compressed2DTestInstance : public TestInstance
{
public:
	typedef Compressed2DTestParameters	ParameterType;

										Compressed2DTestInstance	(Context&				context,
																	 const ParameterType&	testParameters);
	tcu::TestStatus						iterate						(void);

private:
										Compressed2DTestInstance	(const Compressed2DTestInstance& other);
	Compressed2DTestInstance&			operator=					(const Compressed2DTestInstance& other);

	const ParameterType&				m_testParameters;
	const tcu::CompressedTexFormat		m_compressedFormat;
	TestTexture2DSp						m_texture;
	TextureRenderer						m_renderer;
};

Compressed2DTestInstance::Compressed2DTestInstance (Context&				context,
													const ParameterType&	testParameters)
	: TestInstance			(context)
	, m_testParameters		(testParameters)
	, m_compressedFormat	(mapVkCompressedFormat(testParameters.format))
	, m_texture				(TestTexture2DSp(new pipeline::TestTexture2D(m_compressedFormat, testParameters.width, testParameters.height)))
	, m_renderer			(context, testParameters.sampleCount, testParameters.width, testParameters.height)
{
	m_renderer.add2DTexture(m_texture, testParameters.backingMode);
}

tcu::TestStatus Compressed2DTestInstance::iterate (void)
{
	tcu::TestLog&					log				= m_context.getTestContext().getLog();
	const pipeline::TestTexture2D&	texture			= m_renderer.get2DTexture(0);
	const tcu::TextureFormat		textureFormat	= texture.getTextureFormat();
	const tcu::TextureFormatInfo	formatInfo		= tcu::getTextureFormatInfo(textureFormat);

	ReferenceParams					sampleParams	(TEXTURETYPE_2D);
	tcu::Surface					rendered		(m_renderer.getRenderWidth(), m_renderer.getRenderHeight());
	vector<float>					texCoord;

	// Setup params for reference.
	sampleParams.sampler			= util::createSampler(m_testParameters.wrapS, m_testParameters.wrapT, m_testParameters.minFilter, m_testParameters.magFilter);
	sampleParams.samplerType		= SAMPLERTYPE_FLOAT;
	sampleParams.lodMode			= LODMODE_EXACT;
	if (isAstcFormat(m_compressedFormat))
	{
		sampleParams.colorBias			= tcu::Vec4(0.0f);
		sampleParams.colorScale			= tcu::Vec4(1.0f);
	}
	else
	{
		sampleParams.colorBias			= formatInfo.lookupBias;
		sampleParams.colorScale			= formatInfo.lookupScale;
	}

	log << TestLog::Message << "Compare reference value = " << sampleParams.ref << TestLog::EndMessage;

	// Compute texture coordinates.
	computeQuadTexCoord2D(texCoord, tcu::Vec2(0.0f, 0.0f), tcu::Vec2(1.0f, 1.0f));

	m_renderer.renderQuad(rendered, 0, &texCoord[0], sampleParams);

	// Compute reference.
	const tcu::IVec4		formatBitDepth	= getTextureFormatBitDepth(vk::mapVkFormat(VK_FORMAT_R8G8B8A8_UNORM));
	const tcu::PixelFormat	pixelFormat		(formatBitDepth[0], formatBitDepth[1], formatBitDepth[2], formatBitDepth[3]);
	tcu::Surface			referenceFrame	(m_renderer.getRenderWidth(), m_renderer.getRenderHeight());
	sampleTexture(tcu::SurfaceAccess(referenceFrame, pixelFormat), m_texture->getTexture(), &texCoord[0], sampleParams);

	// Compare and log.
	tcu::RGBA threshold;

	if (isBcBitExactFormat(m_compressedFormat))
		threshold = tcu::RGBA(1, 1, 1, 1);
	else if (isBcFormat(m_compressedFormat))
		threshold = tcu::RGBA(8, 8, 8, 8);
	else
		threshold = pixelFormat.getColorThreshold() + tcu::RGBA(2, 2, 2, 2);

	const bool isOk = compareImages(log, referenceFrame, rendered, threshold);

	return isOk ? tcu::TestStatus::pass("Pass") : tcu::TestStatus::fail("Image verification failed");
}

void populateTextureCompressedFormatTests (tcu::TestCaseGroup* compressedTextureTests)
{
	tcu::TestContext&	testCtx	= compressedTextureTests->getTestContext();

	// ETC2 and EAC compressed formats.
	static const struct {
		const VkFormat	format;
	} formats[] =
	{
		{ VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK		},
		{ VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK		},
		{ VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK	},
		{ VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK	},
		{ VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK	},
		{ VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK	},

		{ VK_FORMAT_EAC_R11_UNORM_BLOCK			},
		{ VK_FORMAT_EAC_R11_SNORM_BLOCK			},
		{ VK_FORMAT_EAC_R11G11_UNORM_BLOCK		},
		{ VK_FORMAT_EAC_R11G11_SNORM_BLOCK		},

		{ VK_FORMAT_ASTC_4x4_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_4x4_SRGB_BLOCK			},
		{ VK_FORMAT_ASTC_5x4_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_5x4_SRGB_BLOCK			},
		{ VK_FORMAT_ASTC_5x5_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_5x5_SRGB_BLOCK			},
		{ VK_FORMAT_ASTC_6x5_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_6x5_SRGB_BLOCK			},
		{ VK_FORMAT_ASTC_6x6_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_6x6_SRGB_BLOCK			},
		{ VK_FORMAT_ASTC_8x5_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_8x5_SRGB_BLOCK			},
		{ VK_FORMAT_ASTC_8x6_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_8x6_SRGB_BLOCK			},
		{ VK_FORMAT_ASTC_8x8_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_8x8_SRGB_BLOCK			},
		{ VK_FORMAT_ASTC_10x5_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_10x5_SRGB_BLOCK		},
		{ VK_FORMAT_ASTC_10x6_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_10x6_SRGB_BLOCK		},
		{ VK_FORMAT_ASTC_10x8_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_10x8_SRGB_BLOCK		},
		{ VK_FORMAT_ASTC_10x10_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_10x10_SRGB_BLOCK		},
		{ VK_FORMAT_ASTC_12x10_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_12x10_SRGB_BLOCK		},
		{ VK_FORMAT_ASTC_12x12_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_12x12_SRGB_BLOCK		},

		{ VK_FORMAT_BC1_RGB_UNORM_BLOCK			},
		{ VK_FORMAT_BC1_RGB_SRGB_BLOCK			},
		{ VK_FORMAT_BC1_RGBA_UNORM_BLOCK		},
		{ VK_FORMAT_BC1_RGBA_SRGB_BLOCK			},
		{ VK_FORMAT_BC2_UNORM_BLOCK				},
		{ VK_FORMAT_BC2_SRGB_BLOCK				},
		{ VK_FORMAT_BC3_UNORM_BLOCK				},
		{ VK_FORMAT_BC3_SRGB_BLOCK				},
		{ VK_FORMAT_BC4_UNORM_BLOCK				},
		{ VK_FORMAT_BC4_SNORM_BLOCK				},
		{ VK_FORMAT_BC5_UNORM_BLOCK				},
		{ VK_FORMAT_BC5_SNORM_BLOCK				},
		{ VK_FORMAT_BC6H_UFLOAT_BLOCK			},
		{ VK_FORMAT_BC6H_SFLOAT_BLOCK			},
		{ VK_FORMAT_BC7_UNORM_BLOCK				},
		{ VK_FORMAT_BC7_SRGB_BLOCK				}
	};

	static const struct {
		const int	width;
		const int	height;
		const char*	name;
	} sizes[] =
	{
		{ 128, 64, "pot"  },
		{ 51,  65, "npot" },
	};

	static const struct {
		const char*								name;
		const TextureBinding::ImageBackingMode	backingMode;
	} backingModes[] =
	{
		{ "",			TextureBinding::IMAGE_BACKING_MODE_REGULAR	},
		{ "_sparse",	TextureBinding::IMAGE_BACKING_MODE_SPARSE	}
	};

	for (int sizeNdx = 0; sizeNdx < DE_LENGTH_OF_ARRAY(sizes); sizeNdx++)
	for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(formats); formatNdx++)
	for (int backingNdx = 0; backingNdx < DE_LENGTH_OF_ARRAY(backingModes); backingNdx++)
	{
		const string	formatStr	= de::toString(getFormatStr(formats[formatNdx].format));
		const string	nameBase	= de::toLower(formatStr.substr(10));

		Compressed2DTestParameters	testParameters;
		testParameters.format		= formats[formatNdx].format;
		testParameters.backingMode	= backingModes[backingNdx].backingMode;
		testParameters.width		= sizes[sizeNdx].width;
		testParameters.height		= sizes[sizeNdx].height;
		testParameters.minFilter	= tcu::Sampler::NEAREST;
		testParameters.magFilter	= tcu::Sampler::NEAREST;
		testParameters.programs.push_back(PROGRAM_2D_FLOAT);

		compressedTextureTests->addChild(new TextureTestCase<Compressed2DTestInstance>(testCtx, (nameBase + "_2d_" + sizes[sizeNdx].name + backingModes[backingNdx].name).c_str(), (formatStr + ", TEXTURETYPE_2D").c_str(), testParameters));
	}
}

} // anonymous

tcu::TestCaseGroup* createTextureCompressedFormatTests (tcu::TestContext& testCtx)
{
	return createTestGroup(testCtx, "compressed", "Texture compressed format tests.", populateTextureCompressedFormatTests);
}

} // texture
} // vkt
<commit_msg>Fixed color bias and scale for BC4-5 tests<commit_after>/*-------------------------------------------------------------------------
 * Vulkan Conformance Tests
 * ------------------------
 *
 * Copyright (c) 2016 The Khronos Group Inc.
 * Copyright (c) 2016 Samsung Electronics Co., Ltd.
 * Copyright (c) 2014 The Android Open Source Project
 *
 * 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.
 *
 *//*!
 * \file
 * \brief Compressed texture tests.
 *//*--------------------------------------------------------------------*/

#include "vktTextureCompressedFormatTests.hpp"

#include "deString.h"
#include "deStringUtil.hpp"
#include "tcuCompressedTexture.hpp"
#include "tcuTexture.hpp"
#include "tcuTextureUtil.hpp"
#include "tcuAstcUtil.hpp"
#include "vkImageUtil.hpp"
#include "vktTestGroupUtil.hpp"
#include "vktTextureTestUtil.hpp"
#include <string>
#include <vector>

namespace vkt
{
namespace texture
{
namespace
{

using namespace vk;
using namespace glu::TextureTestUtil;
using namespace texture::util;

using std::string;
using std::vector;
using tcu::Sampler;
using tcu::TestLog;

struct Compressed2DTestParameters : public Texture2DTestCaseParameters
{
										Compressed2DTestParameters	(void);
	TextureBinding::ImageBackingMode	backingMode;
};

Compressed2DTestParameters::Compressed2DTestParameters (void)
	: backingMode(TextureBinding::IMAGE_BACKING_MODE_REGULAR)
{
}

class Compressed2DTestInstance : public TestInstance
{
public:
	typedef Compressed2DTestParameters	ParameterType;

										Compressed2DTestInstance	(Context&				context,
																	 const ParameterType&	testParameters);
	tcu::TestStatus						iterate						(void);

private:
										Compressed2DTestInstance	(const Compressed2DTestInstance& other);
	Compressed2DTestInstance&			operator=					(const Compressed2DTestInstance& other);

	const ParameterType&				m_testParameters;
	const tcu::CompressedTexFormat		m_compressedFormat;
	TestTexture2DSp						m_texture;
	TextureRenderer						m_renderer;
};

Compressed2DTestInstance::Compressed2DTestInstance (Context&				context,
													const ParameterType&	testParameters)
	: TestInstance			(context)
	, m_testParameters		(testParameters)
	, m_compressedFormat	(mapVkCompressedFormat(testParameters.format))
	, m_texture				(TestTexture2DSp(new pipeline::TestTexture2D(m_compressedFormat, testParameters.width, testParameters.height)))
	, m_renderer			(context, testParameters.sampleCount, testParameters.width, testParameters.height)
{
	m_renderer.add2DTexture(m_texture, testParameters.backingMode);
}

tcu::TestStatus Compressed2DTestInstance::iterate (void)
{
	tcu::TestLog&					log				= m_context.getTestContext().getLog();
	const pipeline::TestTexture2D&	texture			= m_renderer.get2DTexture(0);
	const tcu::TextureFormat		textureFormat	= texture.getTextureFormat();
	const tcu::TextureFormatInfo	formatInfo		= tcu::getTextureFormatInfo(textureFormat);

	ReferenceParams					sampleParams	(TEXTURETYPE_2D);
	tcu::Surface					rendered		(m_renderer.getRenderWidth(), m_renderer.getRenderHeight());
	vector<float>					texCoord;

	// Setup params for reference.
	sampleParams.sampler			= util::createSampler(m_testParameters.wrapS, m_testParameters.wrapT, m_testParameters.minFilter, m_testParameters.magFilter);
	sampleParams.samplerType		= SAMPLERTYPE_FLOAT;
	sampleParams.lodMode			= LODMODE_EXACT;

	if (isAstcFormat(m_compressedFormat)
		|| m_compressedFormat == tcu::COMPRESSEDTEXFORMAT_BC4_UNORM_BLOCK
		|| m_compressedFormat == tcu::COMPRESSEDTEXFORMAT_BC5_UNORM_BLOCK)
	{
		sampleParams.colorBias			= tcu::Vec4(0.0f);
		sampleParams.colorScale			= tcu::Vec4(1.0f);
	}
	else if (m_compressedFormat == tcu::COMPRESSEDTEXFORMAT_BC4_SNORM_BLOCK)
	{
		sampleParams.colorBias			= tcu::Vec4(0.5f, 0.0f, 0.0f, 0.0f);
		sampleParams.colorScale			= tcu::Vec4(0.5f, 1.0f, 1.0f, 1.0f);
	}
	else if (m_compressedFormat == tcu::COMPRESSEDTEXFORMAT_BC5_SNORM_BLOCK)
	{
		sampleParams.colorBias			= tcu::Vec4(0.5f, 0.5f, 0.0f, 0.0f);
		sampleParams.colorScale			= tcu::Vec4(0.5f, 0.5f, 1.0f, 1.0f);
	}
	else
	{
		sampleParams.colorBias			= formatInfo.lookupBias;
		sampleParams.colorScale			= formatInfo.lookupScale;
	}

	log << TestLog::Message << "Compare reference value = " << sampleParams.ref << TestLog::EndMessage;

	// Compute texture coordinates.
	computeQuadTexCoord2D(texCoord, tcu::Vec2(0.0f, 0.0f), tcu::Vec2(1.0f, 1.0f));

	m_renderer.renderQuad(rendered, 0, &texCoord[0], sampleParams);

	// Compute reference.
	const tcu::IVec4		formatBitDepth	= getTextureFormatBitDepth(vk::mapVkFormat(VK_FORMAT_R8G8B8A8_UNORM));
	const tcu::PixelFormat	pixelFormat		(formatBitDepth[0], formatBitDepth[1], formatBitDepth[2], formatBitDepth[3]);
	tcu::Surface			referenceFrame	(m_renderer.getRenderWidth(), m_renderer.getRenderHeight());
	sampleTexture(tcu::SurfaceAccess(referenceFrame, pixelFormat), m_texture->getTexture(), &texCoord[0], sampleParams);

	// Compare and log.
	tcu::RGBA threshold;

	if (isBcBitExactFormat(m_compressedFormat))
		threshold = tcu::RGBA(1, 1, 1, 1);
	else if (isBcFormat(m_compressedFormat))
		threshold = tcu::RGBA(8, 8, 8, 8);
	else
		threshold = pixelFormat.getColorThreshold() + tcu::RGBA(2, 2, 2, 2);

	const bool isOk = compareImages(log, referenceFrame, rendered, threshold);

	return isOk ? tcu::TestStatus::pass("Pass") : tcu::TestStatus::fail("Image verification failed");
}

void populateTextureCompressedFormatTests (tcu::TestCaseGroup* compressedTextureTests)
{
	tcu::TestContext&	testCtx	= compressedTextureTests->getTestContext();

	// ETC2 and EAC compressed formats.
	static const struct {
		const VkFormat	format;
	} formats[] =
	{
		{ VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK		},
		{ VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK		},
		{ VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK	},
		{ VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK	},
		{ VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK	},
		{ VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK	},

		{ VK_FORMAT_EAC_R11_UNORM_BLOCK			},
		{ VK_FORMAT_EAC_R11_SNORM_BLOCK			},
		{ VK_FORMAT_EAC_R11G11_UNORM_BLOCK		},
		{ VK_FORMAT_EAC_R11G11_SNORM_BLOCK		},

		{ VK_FORMAT_ASTC_4x4_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_4x4_SRGB_BLOCK			},
		{ VK_FORMAT_ASTC_5x4_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_5x4_SRGB_BLOCK			},
		{ VK_FORMAT_ASTC_5x5_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_5x5_SRGB_BLOCK			},
		{ VK_FORMAT_ASTC_6x5_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_6x5_SRGB_BLOCK			},
		{ VK_FORMAT_ASTC_6x6_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_6x6_SRGB_BLOCK			},
		{ VK_FORMAT_ASTC_8x5_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_8x5_SRGB_BLOCK			},
		{ VK_FORMAT_ASTC_8x6_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_8x6_SRGB_BLOCK			},
		{ VK_FORMAT_ASTC_8x8_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_8x8_SRGB_BLOCK			},
		{ VK_FORMAT_ASTC_10x5_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_10x5_SRGB_BLOCK		},
		{ VK_FORMAT_ASTC_10x6_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_10x6_SRGB_BLOCK		},
		{ VK_FORMAT_ASTC_10x8_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_10x8_SRGB_BLOCK		},
		{ VK_FORMAT_ASTC_10x10_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_10x10_SRGB_BLOCK		},
		{ VK_FORMAT_ASTC_12x10_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_12x10_SRGB_BLOCK		},
		{ VK_FORMAT_ASTC_12x12_UNORM_BLOCK		},
		{ VK_FORMAT_ASTC_12x12_SRGB_BLOCK		},

		{ VK_FORMAT_BC1_RGB_UNORM_BLOCK			},
		{ VK_FORMAT_BC1_RGB_SRGB_BLOCK			},
		{ VK_FORMAT_BC1_RGBA_UNORM_BLOCK		},
		{ VK_FORMAT_BC1_RGBA_SRGB_BLOCK			},
		{ VK_FORMAT_BC2_UNORM_BLOCK				},
		{ VK_FORMAT_BC2_SRGB_BLOCK				},
		{ VK_FORMAT_BC3_UNORM_BLOCK				},
		{ VK_FORMAT_BC3_SRGB_BLOCK				},
		{ VK_FORMAT_BC4_UNORM_BLOCK				},
		{ VK_FORMAT_BC4_SNORM_BLOCK				},
		{ VK_FORMAT_BC5_UNORM_BLOCK				},
		{ VK_FORMAT_BC5_SNORM_BLOCK				},
		{ VK_FORMAT_BC6H_UFLOAT_BLOCK			},
		{ VK_FORMAT_BC6H_SFLOAT_BLOCK			},
		{ VK_FORMAT_BC7_UNORM_BLOCK				},
		{ VK_FORMAT_BC7_SRGB_BLOCK				}
	};

	static const struct {
		const int	width;
		const int	height;
		const char*	name;
	} sizes[] =
	{
		{ 128, 64, "pot"  },
		{ 51,  65, "npot" },
	};

	static const struct {
		const char*								name;
		const TextureBinding::ImageBackingMode	backingMode;
	} backingModes[] =
	{
		{ "",			TextureBinding::IMAGE_BACKING_MODE_REGULAR	},
		{ "_sparse",	TextureBinding::IMAGE_BACKING_MODE_SPARSE	}
	};

	for (int sizeNdx = 0; sizeNdx < DE_LENGTH_OF_ARRAY(sizes); sizeNdx++)
	for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(formats); formatNdx++)
	for (int backingNdx = 0; backingNdx < DE_LENGTH_OF_ARRAY(backingModes); backingNdx++)
	{
		const string	formatStr	= de::toString(getFormatStr(formats[formatNdx].format));
		const string	nameBase	= de::toLower(formatStr.substr(10));

		Compressed2DTestParameters	testParameters;
		testParameters.format		= formats[formatNdx].format;
		testParameters.backingMode	= backingModes[backingNdx].backingMode;
		testParameters.width		= sizes[sizeNdx].width;
		testParameters.height		= sizes[sizeNdx].height;
		testParameters.minFilter	= tcu::Sampler::NEAREST;
		testParameters.magFilter	= tcu::Sampler::NEAREST;
		testParameters.programs.push_back(PROGRAM_2D_FLOAT);

		compressedTextureTests->addChild(new TextureTestCase<Compressed2DTestInstance>(testCtx, (nameBase + "_2d_" + sizes[sizeNdx].name + backingModes[backingNdx].name).c_str(), (formatStr + ", TEXTURETYPE_2D").c_str(), testParameters));
	}
}

} // anonymous

tcu::TestCaseGroup* createTextureCompressedFormatTests (tcu::TestContext& testCtx)
{
	return createTestGroup(testCtx, "compressed", "Texture compressed format tests.", populateTextureCompressedFormatTests);
}

} // texture
} // vkt
<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "DebugOperatorNew.h"

#include "NaaliApplication.h"
#include "Framework.h"
#include "ConfigurationManager.h"

#include <QDir>
#include <QGraphicsView>
#include <QTranslator>
#include <QLocale>
#include <QIcon>
#include <QWebSettings>

#include "MemoryLeakCheck.h"

namespace Foundation
{
    NaaliApplication::NaaliApplication(Framework *framework, int &argc, char **argv) :
        QApplication(argc, argv),
        framework_(framework),
        app_activated_(true),
        native_translator_(new QTranslator),
        app_translator_(new QTranslator)//,
//        main_window_(new MainWindow(framework_))
    {
        QApplication::setApplicationName("realXtend-Naali");

#ifdef Q_WS_WIN
        // If under windows, add run_dir/plugins as library path
        // unix users will get plugins from their OS Qt installation folder automatically
        QString run_directory = applicationDirPath();
        run_directory += "/qtplugins";
        addLibraryPath(run_directory);
#endif

        QDir dir("data/translations/qt_native_translations");
        QStringList qmFiles = GetQmFiles(dir);

        // Search then that is there corresponding native translations for system locals.
        QString loc = QLocale::system().name();
        loc.chop(3);

        QString name = "data/translations/qt_native_translations/qt_" + loc + ".qm";
        QStringList lst = qmFiles.filter(name);
        if (!lst.empty() )
            native_translator_->load(lst[0]);

        this->installTranslator(native_translator_);

        std::string default_language = framework_->GetConfigManager()->DeclareSetting(Framework::ConfigurationGroup(),
            "language", std::string("data/translations/naali_en"));
        ChangeLanguage(QString::fromStdString(default_language));

        QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true); //enablig flash
    }

    NaaliApplication::~NaaliApplication()
    {
//        view_.reset();
        SAFE_DELETE(native_translator_);
        SAFE_DELETE(app_translator_);
//        SAFE_DELETE(main_window_);
    }
/*
    QGraphicsView *NaaliApplication::GetUIView() const
    {
        return view_.get();
    }

    void NaaliApplication::SetUIView(std::auto_ptr <QGraphicsView> view)
    {
        view_ = view;
    }

    MainWindow *NaaliApplication::GetMainWindow() const
    {
        return main_window_;
    }
*/
    QStringList NaaliApplication::GetQmFiles(const QDir& dir)
    {
         QStringList fileNames = dir.entryList(QStringList("*.qm"), QDir::Files, QDir::Name);
         QMutableStringListIterator i(fileNames);
         while (i.hasNext())
         {
             i.next();
             i.setValue(dir.filePath(i.value()));
         }
         return fileNames;
    }

    void NaaliApplication::Go()
    {
        installEventFilter(this);

        QObject::connect(&frame_update_timer_, SIGNAL(timeout()), this, SLOT(UpdateFrame()));
        frame_update_timer_.setSingleShot (true);
        frame_update_timer_.start (0);

        try
        {
            exec ();
        }
        catch(const std::exception &e)
        {
            RootLogCritical(std::string("NaaliApplication::Go caught an exception: ") + (e.what() ? e.what() : "(null)"));
            throw;
        }
        catch(...)
        {
            RootLogCritical(std::string("NaaliApplication::Go caught an unknown exception!"));
            throw;
        }
    }

    bool NaaliApplication::eventFilter(QObject *obj,  QEvent *event)
    {
        try
        {
            if (obj == this)
            {
                if (event->type() == QEvent::ApplicationActivate)
                    app_activated_ = true;
                if (event->type() == QEvent::ApplicationDeactivate)
                    app_activated_ = false;
                /*
                if (event->type() == QEvent::LanguageChange)
                {
                    // Now if exist remove our default translation engine.
                    if (translator_ != 0)
                        this->removeTranslator(translator_);
                }
                */
            }
            return QObject::eventFilter(obj, event);
        }
        catch(const std::exception &e)
        {
            std::cout << std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)") << std::endl;
            RootLogCritical(std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)"));
            throw;
        } catch(...)
        {
            std::cout << std::string("QApp::eventFilter caught an unknown exception!") << std::endl;
            RootLogCritical(std::string("QApp::eventFilter caught an unknown exception!"));
            throw;
        }
        return true;
    }

    void NaaliApplication::ChangeLanguage(const QString& file)
    {
        QString filename = file;
        if (!filename.endsWith(".qm", Qt::CaseInsensitive))
            filename.append(".qm");
        QString tmp = filename;
        tmp.chop(3);
        QString str = tmp.right(2);

        QString name = "data/translations/qt_native_translations/qt_" + str + ".qm";

        // Remove old translators then change them to new.
        removeTranslator(native_translator_);

        if ( QFile::exists(name) )
        {
            if ( native_translator_ != 0)
            {
                native_translator_->load(name);
                installTranslator(native_translator_);
            }
        }
        else
        {
            if (native_translator_ != 0 && native_translator_->isEmpty())
            {
                installTranslator(native_translator_);
            }
            else
            {
                SAFE_DELETE(native_translator_);
                native_translator_ = new QTranslator;
                installTranslator(native_translator_);
            }
        }

        // Remove old translators then change them to new.
        removeTranslator(app_translator_);
        if (app_translator_->load(filename))
        {
            installTranslator(app_translator_);
            framework_->GetConfigManager()->SetSetting(Framework::ConfigurationGroup(), "language", file.toStdString());
        }

        emit LanguageChanged();
    }

    bool NaaliApplication::notify(QObject *receiver, QEvent *event)
    {
        try
        {
            return QApplication::notify(receiver, event);
        } catch(const std::exception &e)
        {
            std::cout << std::string("QApp::notify caught an exception: ") << (e.what() ? e.what() : "(null)") << std::endl;
            RootLogCritical(std::string("QApp::notify caught an exception: ") + (e.what() ? e.what() : "(null)"));
            throw;
        } catch(...)
        {
            std::cout << std::string("QApp::notify caught an unknown exception!") << std::endl;
            RootLogCritical(std::string("QApp::notify caught an unknown exception!"));
            throw;
        }
        return true;
    }

    void NaaliApplication::UpdateFrame()
    {
        try
        {
            QApplication::processEvents (QEventLoop::AllEvents, 1);
            QApplication::sendPostedEvents ();

            framework_-> ProcessOneFrame();

            // Reduce framerate when unfocused
            if (app_activated_)
                frame_update_timer_.start(0);
            else
                frame_update_timer_.start(5);
        }
        catch(const std::exception &e)
        {
            std::cout << "QApp::UpdateFrame caught an exception: " << (e.what() ? e.what() : "(null)") << std::endl;
            RootLogCritical(std::string("QApp::UpdateFrame caught an exception: ") + (e.what() ? e.what() : "(null)"));
            throw;
        }
        catch(...)
        {
            std::cout << "QApp::UpdateFrame caught an unknown exception!" << std::endl;
            RootLogCritical(std::string("QApp::UpdateFrame caught an unknown exception!"));
            throw;
        }
    }

    void NaaliApplication::AboutToExit()
    {
        emit ExitRequested();

        // If no-one canceled the exit as a response to the signal, exit
        if (framework_->IsExiting())
            quit();
    }
}
<commit_msg>Make possible to run naali from another directories.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "DebugOperatorNew.h"

#include "NaaliApplication.h"
#include "Framework.h"
#include "ConfigurationManager.h"

#include <QDir>
#include <QGraphicsView>
#include <QTranslator>
#include <QLocale>
#include <QIcon>
#include <QWebSettings>

#include "MemoryLeakCheck.h"

namespace Foundation
{
    NaaliApplication::NaaliApplication(Framework *framework, int &argc, char **argv) :
        QApplication(argc, argv),
        framework_(framework),
        app_activated_(true),
        native_translator_(new QTranslator),
        app_translator_(new QTranslator)//,
//        main_window_(new MainWindow(framework_))
    {
        QApplication::setApplicationName("realXtend-Naali");

#ifdef Q_WS_WIN

        // On Windows the current directory have to be the application installation directory
        QDir::setCurrent(applicationDirPath());

        // If under windows, add run_dir/plugins as library path
        // unix users will get plugins from their OS Qt installation folder automatically
        QString run_directory = applicationDirPath();
        run_directory += "/qtplugins";
        addLibraryPath(run_directory);
#endif

        QDir dir("data/translations/qt_native_translations");
        QStringList qmFiles = GetQmFiles(dir);

        // Search then that is there corresponding native translations for system locals.
        QString loc = QLocale::system().name();
        loc.chop(3);

        QString name = "data/translations/qt_native_translations/qt_" + loc + ".qm";
        QStringList lst = qmFiles.filter(name);
        if (!lst.empty() )
            native_translator_->load(lst[0]);

        this->installTranslator(native_translator_);

        std::string default_language = framework_->GetConfigManager()->DeclareSetting(Framework::ConfigurationGroup(),
            "language", std::string("data/translations/naali_en"));
        ChangeLanguage(QString::fromStdString(default_language));

        QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true); //enablig flash
    }

    NaaliApplication::~NaaliApplication()
    {
//        view_.reset();
        SAFE_DELETE(native_translator_);
        SAFE_DELETE(app_translator_);
//        SAFE_DELETE(main_window_);
    }
/*
    QGraphicsView *NaaliApplication::GetUIView() const
    {
        return view_.get();
    }

    void NaaliApplication::SetUIView(std::auto_ptr <QGraphicsView> view)
    {
        view_ = view;
    }

    MainWindow *NaaliApplication::GetMainWindow() const
    {
        return main_window_;
    }
*/
    QStringList NaaliApplication::GetQmFiles(const QDir& dir)
    {
         QStringList fileNames = dir.entryList(QStringList("*.qm"), QDir::Files, QDir::Name);
         QMutableStringListIterator i(fileNames);
         while (i.hasNext())
         {
             i.next();
             i.setValue(dir.filePath(i.value()));
         }
         return fileNames;
    }

    void NaaliApplication::Go()
    {
        installEventFilter(this);

        QObject::connect(&frame_update_timer_, SIGNAL(timeout()), this, SLOT(UpdateFrame()));
        frame_update_timer_.setSingleShot (true);
        frame_update_timer_.start (0);

        try
        {
            exec ();
        }
        catch(const std::exception &e)
        {
            RootLogCritical(std::string("NaaliApplication::Go caught an exception: ") + (e.what() ? e.what() : "(null)"));
            throw;
        }
        catch(...)
        {
            RootLogCritical(std::string("NaaliApplication::Go caught an unknown exception!"));
            throw;
        }
    }

    bool NaaliApplication::eventFilter(QObject *obj,  QEvent *event)
    {
        try
        {
            if (obj == this)
            {
                if (event->type() == QEvent::ApplicationActivate)
                    app_activated_ = true;
                if (event->type() == QEvent::ApplicationDeactivate)
                    app_activated_ = false;
                /*
                if (event->type() == QEvent::LanguageChange)
                {
                    // Now if exist remove our default translation engine.
                    if (translator_ != 0)
                        this->removeTranslator(translator_);
                }
                */
            }
            return QObject::eventFilter(obj, event);
        }
        catch(const std::exception &e)
        {
            std::cout << std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)") << std::endl;
            RootLogCritical(std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)"));
            throw;
        } catch(...)
        {
            std::cout << std::string("QApp::eventFilter caught an unknown exception!") << std::endl;
            RootLogCritical(std::string("QApp::eventFilter caught an unknown exception!"));
            throw;
        }
        return true;
    }

    void NaaliApplication::ChangeLanguage(const QString& file)
    {
        QString filename = file;
        if (!filename.endsWith(".qm", Qt::CaseInsensitive))
            filename.append(".qm");
        QString tmp = filename;
        tmp.chop(3);
        QString str = tmp.right(2);

        QString name = "data/translations/qt_native_translations/qt_" + str + ".qm";

        // Remove old translators then change them to new.
        removeTranslator(native_translator_);

        if ( QFile::exists(name) )
        {
            if ( native_translator_ != 0)
            {
                native_translator_->load(name);
                installTranslator(native_translator_);
            }
        }
        else
        {
            if (native_translator_ != 0 && native_translator_->isEmpty())
            {
                installTranslator(native_translator_);
            }
            else
            {
                SAFE_DELETE(native_translator_);
                native_translator_ = new QTranslator;
                installTranslator(native_translator_);
            }
        }

        // Remove old translators then change them to new.
        removeTranslator(app_translator_);
        if (app_translator_->load(filename))
        {
            installTranslator(app_translator_);
            framework_->GetConfigManager()->SetSetting(Framework::ConfigurationGroup(), "language", file.toStdString());
        }

        emit LanguageChanged();
    }

    bool NaaliApplication::notify(QObject *receiver, QEvent *event)
    {
        try
        {
            return QApplication::notify(receiver, event);
        } catch(const std::exception &e)
        {
            std::cout << std::string("QApp::notify caught an exception: ") << (e.what() ? e.what() : "(null)") << std::endl;
            RootLogCritical(std::string("QApp::notify caught an exception: ") + (e.what() ? e.what() : "(null)"));
            throw;
        } catch(...)
        {
            std::cout << std::string("QApp::notify caught an unknown exception!") << std::endl;
            RootLogCritical(std::string("QApp::notify caught an unknown exception!"));
            throw;
        }
        return true;
    }

    void NaaliApplication::UpdateFrame()
    {
        try
        {
            QApplication::processEvents (QEventLoop::AllEvents, 1);
            QApplication::sendPostedEvents ();

            framework_-> ProcessOneFrame();

            // Reduce framerate when unfocused
            if (app_activated_)
                frame_update_timer_.start(0);
            else
                frame_update_timer_.start(5);
        }
        catch(const std::exception &e)
        {
            std::cout << "QApp::UpdateFrame caught an exception: " << (e.what() ? e.what() : "(null)") << std::endl;
            RootLogCritical(std::string("QApp::UpdateFrame caught an exception: ") + (e.what() ? e.what() : "(null)"));
            throw;
        }
        catch(...)
        {
            std::cout << "QApp::UpdateFrame caught an unknown exception!" << std::endl;
            RootLogCritical(std::string("QApp::UpdateFrame caught an unknown exception!"));
            throw;
        }
    }

    void NaaliApplication::AboutToExit()
    {
        emit ExitRequested();

        // If no-one canceled the exit as a response to the signal, exit
        if (framework_->IsExiting())
            quit();
    }
}
<|endoftext|>


<commit_before>#pragma once

#include "logger.hpp"

namespace blackhole {

class scoped_attributes_t :
    public scoped_attributes_concept_t
{
    // Attributes provided by this guard.
    mutable log::attributes_t m_guard_attributes;
    // Merged attributes are provided by this guard and all the parent guards.
    // This value is computed lazily.
    mutable log::attributes_t m_merged_attributes;

public:
    scoped_attributes_t(logger_base_t& logger, log::attributes_t&& attributes) :
        scoped_attributes_concept_t(logger),
        m_guard_attributes(std::move(attributes))
    { }

    virtual
    const log::attributes_t&
    attributes() const {
        if (m_merged_attributes.empty()) {
            m_merged_attributes = std::move(m_guard_attributes);
            if (has_parent()) {
                const auto &parent_attributes = parent().attributes();
                m_merged_attributes.insert(parent_attributes.begin(), parent_attributes.end());
            }
        }
        return m_merged_attributes;
    }
};

} // namespace blackhole
<commit_msg>[Code Style] Now it's time for scoped attributes.<commit_after>#pragma once

#include "logger.hpp"

namespace blackhole {

class scoped_attributes_t : public scoped_attributes_concept_t {
    // Attributes provided by this guard.
    mutable log::attributes_t m_guard_attributes;
    // Merged attributes are provided by this guard and all the parent guards.
    // This value is computed lazily.
    mutable log::attributes_t m_merged_attributes;

public:
    scoped_attributes_t(logger_base_t& logger, log::attributes_t&& attributes) :
        scoped_attributes_concept_t(logger),
        m_guard_attributes(std::move(attributes))
    {}

    virtual
    const log::attributes_t&
    attributes() const {
        if (m_merged_attributes.empty()) {
            m_merged_attributes = std::move(m_guard_attributes);
            if (has_parent()) {
                const auto& parent_attributes = parent().attributes();
                m_merged_attributes.insert(parent_attributes.begin(), parent_attributes.end());
            }
        }
        return m_merged_attributes;
    }
};

} // namespace blackhole
<|endoftext|>


<commit_before>/*
 * Copyright(c) 2021 Intel Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this software except as stipulated in 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.
 */
#ifdef __cplusplus
extern "C" {
#endif
//#include <tdi/common/c_frontend/tdi_common.h>
#include <tdi/common/tdi_defs.h>

#include <tdi/common/c_frontend/tdi_table_data.h>

#ifdef __cplusplus
}
#endif

#include <tdi/common/tdi_table_data.hpp>
//#include <tdi_common/tdi_table_data_impl.hpp>

/* Data field setters/getter */
tdi_status_t tdi_data_field_set_value(tdi_table_data_hdl *data_hdl,
                                       const tdi_id_t field_id,
                                       const uint64_t val) {
  auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl);
  return data_field->setValue(field_id, val);
}

tdi_status_t tdi_data_field_set_float(tdi_table_data_hdl *data_hdl,
                                       const tdi_id_t field_id,
                                       const float val) {
  auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl);
  return data_field->setValue(field_id, val);
}

tdi_status_t tdi_data_field_set_value_ptr(tdi_table_data_hdl *data_hdl,
                                           const tdi_id_t field_id,
                                           const uint8_t *val,
                                           const size_t s) {
  auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl);
  return data_field->setValue(field_id, val, s);
}

tdi_status_t tdi_data_field_set_value_array(tdi_table_data_hdl *data_hdl,
                                             const tdi_id_t field_id,
                                             const uint32_t *val,
                                             const uint32_t num_array) {
  auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl);
  // array pointers work as iterators
  const auto vec = std::vector<tdi_id_t>(val, val + num_array);
  return data_field->setValue(field_id, vec);
}

tdi_status_t tdi_data_field_set_value_bool_array(
    tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    const bool *val,
    const uint32_t num_array) {
  auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl);
  // array pointers work as iterators
  const auto vec = std::vector<bool>(val, val + num_array);
  return data_field->setValue(field_id, vec);
}

tdi_status_t tdi_data_field_set_value_str_array(tdi_table_data_hdl *data_hdl,
                                                 const tdi_id_t field_id,
                                                 const char *val) {
  auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl);
  std::vector<std::string> vec;
  char *token = strtok(strdup(val), " ");
  while (token != NULL) {
    vec.push_back(std::string(token));
    token = strtok(NULL, " ");
  }
  return data_field->setValue(field_id, vec);
}

tdi_status_t tdi_data_field_set_value_data_field_array(
    tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    tdi_table_data_hdl *val[],
    const uint32_t num_array) {
  std::vector<std::unique_ptr<tdi::TableData>> inner_vec;
  for (uint32_t i = 0; i < num_array; i++) {
    auto inner_data = std::unique_ptr<tdi::TableData>(
        reinterpret_cast<tdi::TableData *>(val[i]));
    inner_vec.push_back(std::move(inner_data));
  }
  auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl);
  return data_field->setValue(field_id, std::move(inner_vec));
}

tdi_status_t tdi_data_field_set_bool(tdi_table_data_hdl *data_hdl,
                                      const tdi_id_t field_id,
                                      const bool val) {
  auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl);
  return data_field->setValue(field_id, val);
}

tdi_status_t tdi_data_field_set_string(tdi_table_data_hdl *data_hdl,
                                        const tdi_id_t field_id,
                                        const char *val) {
  auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl);
  const std::string str_val(val);
  return data_field->setValue(field_id, str_val);
}

tdi_status_t tdi_data_field_get_value(const tdi_table_data_hdl *data_hdl,
                                       const tdi_id_t field_id,
                                       uint64_t *val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  return data_field->getValue(field_id, val);
}

tdi_status_t tdi_data_field_get_value_ptr(const tdi_table_data_hdl *data_hdl,
                                           const tdi_id_t field_id,
                                           const size_t size,
                                           uint8_t *val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  return data_field->getValue(field_id, size, val);
}

tdi_status_t tdi_data_field_get_value_array(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    uint32_t *val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<tdi_id_t> vec;
  auto status = data_field->getValue(field_id, &vec);
  int i = 0;
  for (auto const &item : vec) {
    val[i++] = item;
  }
  return status;
}

tdi_status_t tdi_data_field_get_value_array_size(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    uint32_t *array_size) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<tdi_id_t> vec;
  auto status = data_field->getValue(field_id, &vec);
  *array_size = vec.size();
  return status;
}

tdi_status_t tdi_data_field_get_value_bool_array(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    bool *val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<bool> vec;
  auto status = data_field->getValue(field_id, &vec);
  int i = 0;
  for (auto const &item : vec) {
    val[i++] = item;
  }
  return status;
}

tdi_status_t tdi_data_field_get_value_bool_array_size(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    uint32_t *array_size) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<bool> vec;
  auto status = data_field->getValue(field_id, &vec);
  *array_size = vec.size();
  return status;
}

tdi_status_t tdi_data_field_get_value_str_array(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    uint32_t size,
    char *val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<std::string> vec;
  auto status = data_field->getValue(field_id, &vec);
  if ((size == 0) && (vec.size() == 0)) return status;
  bool first_item = true;
  for (auto const &item : vec) {
    if (first_item) {
      first_item = false;
    } else {
      if (size == 0) return TDI_INVALID_ARG;
      val[0] = ' ';
      val++;
      size--;
    }
    if (size <= item.size()) return TDI_INVALID_ARG;
    item.copy(val, item.size());
    val += item.size();
    size -= item.size();
  }
  if (size == 0) return TDI_INVALID_ARG;
  val[0] = '\0';
  return status;
}

tdi_status_t tdi_data_field_get_value_str_array_size(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    uint32_t *array_size) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<std::string> vec;
  auto status = data_field->getValue(field_id, &vec);
  /* Return the size of all strings plus white spaces between them. */
  for (auto const &item : vec) *array_size += (item.size() + 1);
  return status;
}

tdi_status_t tdi_data_field_get_float(const tdi_table_data_hdl *data_hdl,
                                       const tdi_id_t field_id,
                                       float *val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  return data_field->getValue(field_id, val);
}

tdi_status_t tdi_data_field_get_bool(const tdi_table_data_hdl *data_hdl,
                                      const tdi_id_t field_id,
                                      bool *val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  return data_field->getValue(field_id, val);
}

tdi_status_t tdi_data_field_get_string_size(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    uint32_t *str_size) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::string str;
  auto status = data_field->getValue(field_id, &str);
  *str_size = str.size();
  return status;
}

tdi_status_t tdi_data_field_get_string(const tdi_table_data_hdl *data_hdl,
                                        const tdi_id_t field_id,
                                        char *val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::string str;
  auto status = data_field->getValue(field_id, &str);
  str.copy(val, str.size());
  return status;
}

tdi_status_t tdi_data_field_get_value_u64_array(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    uint64_t *val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<uint64_t> vec;
  auto status = data_field->getValue(field_id, &vec);
  int i = 0;
  for (auto const &item : vec) {
    val[i++] = item;
  }
  return status;
}

tdi_status_t tdi_data_field_get_value_u64_array_size(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    uint32_t *array_size) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<uint64_t> vec;
  auto status = data_field->getValue(field_id, &vec);
  *array_size = vec.size();
  return status;
}

tdi_status_t tdi_data_field_get_value_data_field_array(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    tdi_table_data_hdl **val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<tdi::TableData *> vec;
  auto status = data_field->getValue(field_id, &vec);
  int i = 0;
  for (auto const &item : vec) {
    val[i++] = reinterpret_cast<tdi_table_data_hdl *>(item);
  }
  return status;
}

tdi_status_t tdi_data_field_get_value_data_field_array_size(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    uint32_t *array_size) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<tdi::TableData *> vec;
  auto status = data_field->getValue(field_id, &vec);
  *array_size = vec.size();
  return status;
}

tdi_status_t tdi_data_action_id_get(const tdi_table_data_hdl *data_hdl,
                                     uint32_t *action_id) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  *action_id = data_field->actionIdGet();
  return TDI_SUCCESS;
}

tdi_status_t tdi_data_field_is_active(const tdi_table_data_hdl *data_hdl,
                                       const tdi_id_t field_id,
                                       bool *is_active) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  return data_field->isActive(field_id, is_active);
}
<commit_msg>Fix for memory leak: klocwork ipdk-tdi #717 (#64)<commit_after>/*
 * Copyright(c) 2021 Intel Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this software except as stipulated in 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.
 */
#ifdef __cplusplus
extern "C" {
#endif
//#include <tdi/common/c_frontend/tdi_common.h>
#include <tdi/common/tdi_defs.h>

#include <tdi/common/c_frontend/tdi_table_data.h>

#ifdef __cplusplus
}
#endif

#include <tdi/common/tdi_table_data.hpp>
//#include <tdi_common/tdi_table_data_impl.hpp>

/* Data field setters/getter */
tdi_status_t tdi_data_field_set_value(tdi_table_data_hdl *data_hdl,
                                       const tdi_id_t field_id,
                                       const uint64_t val) {
  auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl);
  return data_field->setValue(field_id, val);
}

tdi_status_t tdi_data_field_set_float(tdi_table_data_hdl *data_hdl,
                                       const tdi_id_t field_id,
                                       const float val) {
  auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl);
  return data_field->setValue(field_id, val);
}

tdi_status_t tdi_data_field_set_value_ptr(tdi_table_data_hdl *data_hdl,
                                           const tdi_id_t field_id,
                                           const uint8_t *val,
                                           const size_t s) {
  auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl);
  return data_field->setValue(field_id, val, s);
}

tdi_status_t tdi_data_field_set_value_array(tdi_table_data_hdl *data_hdl,
                                             const tdi_id_t field_id,
                                             const uint32_t *val,
                                             const uint32_t num_array) {
  auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl);
  // array pointers work as iterators
  const auto vec = std::vector<tdi_id_t>(val, val + num_array);
  return data_field->setValue(field_id, vec);
}

tdi_status_t tdi_data_field_set_value_bool_array(
    tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    const bool *val,
    const uint32_t num_array) {
  auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl);
  // array pointers work as iterators
  const auto vec = std::vector<bool>(val, val + num_array);
  return data_field->setValue(field_id, vec);
}

tdi_status_t tdi_data_field_set_value_str_array(tdi_table_data_hdl *data_hdl,
                                                 const tdi_id_t field_id,
                                                 const char *val) {
  auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl);
  std::vector<std::string> vec;
  char *val_dup = strdup(val);
  char *token = strtok(val_dup, " ");
  while (token != NULL) {
    vec.push_back(std::string(token));
    token = strtok(NULL, " ");
  }
  free(val_dup);
  return data_field->setValue(field_id, vec);
}

tdi_status_t tdi_data_field_set_value_data_field_array(
    tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    tdi_table_data_hdl *val[],
    const uint32_t num_array) {
  std::vector<std::unique_ptr<tdi::TableData>> inner_vec;
  for (uint32_t i = 0; i < num_array; i++) {
    auto inner_data = std::unique_ptr<tdi::TableData>(
        reinterpret_cast<tdi::TableData *>(val[i]));
    inner_vec.push_back(std::move(inner_data));
  }
  auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl);
  return data_field->setValue(field_id, std::move(inner_vec));
}

tdi_status_t tdi_data_field_set_bool(tdi_table_data_hdl *data_hdl,
                                      const tdi_id_t field_id,
                                      const bool val) {
  auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl);
  return data_field->setValue(field_id, val);
}

tdi_status_t tdi_data_field_set_string(tdi_table_data_hdl *data_hdl,
                                        const tdi_id_t field_id,
                                        const char *val) {
  auto data_field = reinterpret_cast<tdi::TableData *>(data_hdl);
  const std::string str_val(val);
  return data_field->setValue(field_id, str_val);
}

tdi_status_t tdi_data_field_get_value(const tdi_table_data_hdl *data_hdl,
                                       const tdi_id_t field_id,
                                       uint64_t *val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  return data_field->getValue(field_id, val);
}

tdi_status_t tdi_data_field_get_value_ptr(const tdi_table_data_hdl *data_hdl,
                                           const tdi_id_t field_id,
                                           const size_t size,
                                           uint8_t *val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  return data_field->getValue(field_id, size, val);
}

tdi_status_t tdi_data_field_get_value_array(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    uint32_t *val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<tdi_id_t> vec;
  auto status = data_field->getValue(field_id, &vec);
  int i = 0;
  for (auto const &item : vec) {
    val[i++] = item;
  }
  return status;
}

tdi_status_t tdi_data_field_get_value_array_size(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    uint32_t *array_size) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<tdi_id_t> vec;
  auto status = data_field->getValue(field_id, &vec);
  *array_size = vec.size();
  return status;
}

tdi_status_t tdi_data_field_get_value_bool_array(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    bool *val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<bool> vec;
  auto status = data_field->getValue(field_id, &vec);
  int i = 0;
  for (auto const &item : vec) {
    val[i++] = item;
  }
  return status;
}

tdi_status_t tdi_data_field_get_value_bool_array_size(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    uint32_t *array_size) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<bool> vec;
  auto status = data_field->getValue(field_id, &vec);
  *array_size = vec.size();
  return status;
}

tdi_status_t tdi_data_field_get_value_str_array(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    uint32_t size,
    char *val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<std::string> vec;
  auto status = data_field->getValue(field_id, &vec);
  if ((size == 0) && (vec.size() == 0)) return status;
  bool first_item = true;
  for (auto const &item : vec) {
    if (first_item) {
      first_item = false;
    } else {
      if (size == 0) return TDI_INVALID_ARG;
      val[0] = ' ';
      val++;
      size--;
    }
    if (size <= item.size()) return TDI_INVALID_ARG;
    item.copy(val, item.size());
    val += item.size();
    size -= item.size();
  }
  if (size == 0) return TDI_INVALID_ARG;
  val[0] = '\0';
  return status;
}

tdi_status_t tdi_data_field_get_value_str_array_size(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    uint32_t *array_size) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<std::string> vec;
  auto status = data_field->getValue(field_id, &vec);
  /* Return the size of all strings plus white spaces between them. */
  for (auto const &item : vec) *array_size += (item.size() + 1);
  return status;
}

tdi_status_t tdi_data_field_get_float(const tdi_table_data_hdl *data_hdl,
                                       const tdi_id_t field_id,
                                       float *val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  return data_field->getValue(field_id, val);
}

tdi_status_t tdi_data_field_get_bool(const tdi_table_data_hdl *data_hdl,
                                      const tdi_id_t field_id,
                                      bool *val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  return data_field->getValue(field_id, val);
}

tdi_status_t tdi_data_field_get_string_size(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    uint32_t *str_size) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::string str;
  auto status = data_field->getValue(field_id, &str);
  *str_size = str.size();
  return status;
}

tdi_status_t tdi_data_field_get_string(const tdi_table_data_hdl *data_hdl,
                                        const tdi_id_t field_id,
                                        char *val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::string str;
  auto status = data_field->getValue(field_id, &str);
  str.copy(val, str.size());
  return status;
}

tdi_status_t tdi_data_field_get_value_u64_array(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    uint64_t *val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<uint64_t> vec;
  auto status = data_field->getValue(field_id, &vec);
  int i = 0;
  for (auto const &item : vec) {
    val[i++] = item;
  }
  return status;
}

tdi_status_t tdi_data_field_get_value_u64_array_size(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    uint32_t *array_size) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<uint64_t> vec;
  auto status = data_field->getValue(field_id, &vec);
  *array_size = vec.size();
  return status;
}

tdi_status_t tdi_data_field_get_value_data_field_array(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    tdi_table_data_hdl **val) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<tdi::TableData *> vec;
  auto status = data_field->getValue(field_id, &vec);
  int i = 0;
  for (auto const &item : vec) {
    val[i++] = reinterpret_cast<tdi_table_data_hdl *>(item);
  }
  return status;
}

tdi_status_t tdi_data_field_get_value_data_field_array_size(
    const tdi_table_data_hdl *data_hdl,
    const tdi_id_t field_id,
    uint32_t *array_size) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  std::vector<tdi::TableData *> vec;
  auto status = data_field->getValue(field_id, &vec);
  *array_size = vec.size();
  return status;
}

tdi_status_t tdi_data_action_id_get(const tdi_table_data_hdl *data_hdl,
                                     uint32_t *action_id) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  *action_id = data_field->actionIdGet();
  return TDI_SUCCESS;
}

tdi_status_t tdi_data_field_is_active(const tdi_table_data_hdl *data_hdl,
                                       const tdi_id_t field_id,
                                       bool *is_active) {
  auto data_field = reinterpret_cast<const tdi::TableData *>(data_hdl);
  return data_field->isActive(field_id, is_active);
}
<|endoftext|>


<commit_before>/*!
@file

@copyright Edouard Alligand and Joel Falcou 2015-2017
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_BRIGAND_ALGORITHMS_DETAIL_FIND_HPP
#define BOOST_BRIGAND_ALGORITHMS_DETAIL_FIND_HPP

#include <brigand/functions/lambda/apply.hpp>
#include <brigand/types/bool.hpp>

namespace brigand
{
namespace detail
{

    template <template <typename...> class S, template <typename...> class F, typename... Ts>
    struct finder
    {
        template <typename T>
        using P = F<Ts..., T>;

        template <bool InNext8, bool Match, typename... Ls>
        struct find
        {
            using type = S<>; // not found case because none left
        };

        template <typename L>
        struct find<true, false, L>
        {
            using type = S<>; // not found case because only one left and not true
        };

        template <typename L, typename... Ls> // match case
        struct find<true, true, L, Ls...>
        {
            using type = S<L, Ls...>;
        };

        template <typename L1, typename L2, typename... Ls> // not match case
        struct find<true, false, L1, L2, Ls...> : find<true, F<Ts..., L2>::value, L2, Ls...>
        {
        };

        template <typename L0, typename L1, typename L2, typename L3, typename L4, typename L5,
                  typename L6, typename L7, typename L8,
                  typename... Ls> // not match no longer fast track case
        struct find<false, false, L0, L1, L2, L3, L4, L5, L6, L7, L8, Ls...>
            : find<true, F<Ts..., L8>::value, L8, Ls...>
        {
        };

        template <typename L1, typename L2, typename L3, typename L4, typename L5, typename L6,
                  typename L7, typename L8, typename L9, typename L10, typename L11, typename L12,
                  typename L13, typename L14, typename L15, typename L16,
                  typename... Ls> // not match can fast track again case
        struct find<false, false, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12, L13, L14, L15,
                    L16, Ls...>
            : find<(P<L9>::value || P<L10>::value || P<L11>::value || P<L12>::value ||
                    P<L13>::value || P<L14>::value || P<L15>::value || P<L16>::value),
                   P<L9>::value, L9, L10, L11, L12, L13, L14, L15, L16, Ls...>
        {
        };
    };
}
}
#endif
<commit_msg>Delete find.hpp<commit_after><|endoftext|>