<commit_before>// Copyright GHI Electronics, LLC
//
// 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 <TinyCLR.h>
#include <Device.h>

#define TARGET(a) CONCAT(DEVICE_TARGET, a)

const TinyCLR_Api_Provider* globalApiProvider;

void OnSoftReset(const TinyCLR_Api_Provider* apiProvider) {
#ifdef INCLUDE_ADC
    apiProvider->Add(apiProvider, TARGET(_Adc_GetApi)());
    apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::AdcProvider, TARGET(_Adc_GetApi)()->Name);
#endif

#ifdef INCLUDE_DAC
    apiProvider->Add(apiProvider, TARGET(_Dac_GetApi)());
    apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::DacProvider, TARGET(_Dac_GetApi)()->Name);
#endif

#ifdef INCLUDE_DISPLAY
    apiProvider->Add(apiProvider, TARGET(_Display_GetApi)());
    apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::DisplayProvider, TARGET(_Display_GetApi)()->Name);
#endif

#ifdef INCLUDE_GPIO
    apiProvider->Add(apiProvider, TARGET(_Gpio_GetApi)());
    apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::GpioProvider, TARGET(_Gpio_GetApi)()->Name);
#endif

#ifdef INCLUDE_I2C
    apiProvider->Add(apiProvider, TARGET(_I2c_GetApi)());
#endif

#ifdef INCLUDE_PWM
    apiProvider->Add(apiProvider, TARGET(_Pwm_GetApi)());
#endif

#ifdef INCLUDE_SPI
    apiProvider->Add(apiProvider, TARGET(_Spi_GetApi)());
#endif

#ifdef INCLUDE_UART
    apiProvider->Add(apiProvider, TARGET(_Uart_GetApi)());
#endif

#ifdef INCLUDE_USBCLIENT
    apiProvider->Add(apiProvider, TARGET(_UsbClient_GetApi)());
#endif

#ifdef INCLUDE_CAN
    apiProvider->Add(apiProvider, TARGET(_Can_GetApi)());
    apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::CanProvider, TARGET(_Can_GetApi)()->Name);
#endif

    globalApiProvider = apiProvider;
}

int main() {
    TARGET(_Startup_Initialize)();

    uint8_t* heapStart;
    size_t heapLength;

    TARGET(_Startup_GetHeap)(heapStart, heapLength);
    TinyCLR_Startup_AddHeapRegion(heapStart, heapLength);

    const TinyCLR_Api_Info* debuggerApi;
    size_t debuggerIndex;

    TARGET(_Startup_GetDebugger)(debuggerApi, debuggerIndex);
    TinyCLR_Startup_SetDebugger(debuggerApi, debuggerIndex);

    TinyCLR_Startup_SetDeviceInformation(DEVICE_NAME, DEVICE_MANUFACTURER, DEVICE_VERSION);

    TinyCLR_Startup_SetRequiredProviders(TARGET(_Deployment_GetApi)(), TARGET(_Interrupt_GetApi)(), TARGET(_Power_GetApi)(), TARGET(_Time_GetApi)());

    auto runApp = true;

    TARGET(_Startup_GetRunApp)(runApp);
    TinyCLR_Startup_Start(&OnSoftReset, runApp);

    return 0;
}
<commit_msg>we will make another PR for globalApiProvider<commit_after>// Copyright GHI Electronics, LLC
//
// 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 <TinyCLR.h>
#include <Device.h>

#define TARGET(a) CONCAT(DEVICE_TARGET, a)

void OnSoftReset(const TinyCLR_Api_Provider* apiProvider) {
#ifdef INCLUDE_ADC
    apiProvider->Add(apiProvider, TARGET(_Adc_GetApi)());
    apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::AdcProvider, TARGET(_Adc_GetApi)()->Name);
#endif

#ifdef INCLUDE_DAC
    apiProvider->Add(apiProvider, TARGET(_Dac_GetApi)());
    apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::DacProvider, TARGET(_Dac_GetApi)()->Name);
#endif

#ifdef INCLUDE_DISPLAY
    apiProvider->Add(apiProvider, TARGET(_Display_GetApi)());
    apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::DisplayProvider, TARGET(_Display_GetApi)()->Name);
#endif

#ifdef INCLUDE_GPIO
    apiProvider->Add(apiProvider, TARGET(_Gpio_GetApi)());
    apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::GpioProvider, TARGET(_Gpio_GetApi)()->Name);
#endif

#ifdef INCLUDE_I2C
    apiProvider->Add(apiProvider, TARGET(_I2c_GetApi)());
#endif

#ifdef INCLUDE_PWM
    apiProvider->Add(apiProvider, TARGET(_Pwm_GetApi)());
#endif

#ifdef INCLUDE_SPI
    apiProvider->Add(apiProvider, TARGET(_Spi_GetApi)());
#endif

#ifdef INCLUDE_UART
    apiProvider->Add(apiProvider, TARGET(_Uart_GetApi)());
#endif

#ifdef INCLUDE_USBCLIENT
    apiProvider->Add(apiProvider, TARGET(_UsbClient_GetApi)());
#endif

#ifdef INCLUDE_CAN
    apiProvider->Add(apiProvider, TARGET(_Can_GetApi)());
    apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::CanProvider, TARGET(_Can_GetApi)()->Name);
#endif
}

int main() {
    TARGET(_Startup_Initialize)();

    uint8_t* heapStart;
    size_t heapLength;

    TARGET(_Startup_GetHeap)(heapStart, heapLength);
    TinyCLR_Startup_AddHeapRegion(heapStart, heapLength);

    const TinyCLR_Api_Info* debuggerApi;
    size_t debuggerIndex;

    TARGET(_Startup_GetDebugger)(debuggerApi, debuggerIndex);
    TinyCLR_Startup_SetDebugger(debuggerApi, debuggerIndex);

    TinyCLR_Startup_SetDeviceInformation(DEVICE_NAME, DEVICE_MANUFACTURER, DEVICE_VERSION);

    TinyCLR_Startup_SetRequiredProviders(TARGET(_Deployment_GetApi)(), TARGET(_Interrupt_GetApi)(), TARGET(_Power_GetApi)(), TARGET(_Time_GetApi)());

    auto runApp = true;

    TARGET(_Startup_GetRunApp)(runApp);
    TinyCLR_Startup_Start(&OnSoftReset, runApp);

    return 0;
}
<|endoftext|>


<commit_before>#include <array>
#include <list>
#include <deque>
#include <utility>
#include <algorithm>
#include <functional>

template <typename ValType, size_t NQueues, typename PriorityType,
         typename Comparator>
class NPriorityQueue{
public:
    //types
    using PriorityList = std::array<PriorityType, NQueues>;

    //functions
    NPriorityQueue& enqueue(ValType value, PriorityList priorities){
        elements_.push_front(value, priorities);
        for(size_t N=0; N<priorities.size(); ++N){
            insert_sorted_(N, elements_.begin());
        }
        return *this;
    }
    template<size_t N> ValType&& dequeue(){
        static_assert(N<NQueues, "dequeue()'s N out of bounds.");
        auto element = *priorities_[N].front();
        for(size_t listN = 0; listN<priorities_.size(); ++listN){
            auto to_erase = find_sorted_(N, element);
            priorities_[N].erase(to_erase);
        }
    }
    size_t count(){return elements_.size();}
    void clear(){elements_.clear(); priorities_.clear();}

private:
    //types
    using Element = std::pair<ValType, PriorityList>;
    using pElement = typename std::list<Element>::iterator;
    using PriorityListItr = typename std::deque<pElement>::iterator;

    //functions
    std::function<bool(const pElement&, const pElement&)> compare_(size_t N) const{
        return [N](const pElement& a, const pElement& b){
            return a->second[N] < b->second[N];
        };
    }

    void insert_sorted_(size_t N, pElement ptr){
        auto list = priorities_[N];
        auto position = std::lower_bound(list.cbegin(), list.cend(),
                compare_(N));
        priorities_.at(N).insert(position, ptr);
    }

    PriorityListItr find_sorted_(size_t N, Element el) const{
        auto list = priorities_[N];
        auto range = std::equal_range(list.begin(), list.end(),
                compare_(N));
        for(auto itr=range.first; itr!=range.second; ++itr){
            if(**itr==el) return itr;
        }
        return list.end(); //if not found
    }

    //members
    std::list<Element> elements_;
    std::array<std::deque<pElement>, NQueues> priorities_;
};

<commit_msg>Temporarily removed Comparator from NPriorityQueue<commit_after>#include <array>
#include <list>
#include <deque>
#include <utility>
#include <algorithm>
#include <functional>

template <typename ValType, size_t NQueues, typename PriorityType>
class NPriorityQueue{
public:
    //types
    using PriorityList = std::array<PriorityType, NQueues>;

    //functions
    NPriorityQueue& enqueue(ValType value, PriorityList priorities){
        elements_.push_front(value, priorities);
        for(size_t N=0; N<priorities.size(); ++N){
            insert_sorted_(N, elements_.begin());
        }
        return *this;
    }
    template<size_t N> ValType&& dequeue(){
        static_assert(N<NQueues, "dequeue()'s N out of bounds.");
        auto element = *priorities_[N].front();
        for(size_t listN = 0; listN<priorities_.size(); ++listN){
            auto to_erase = find_sorted_(N, element);
            priorities_[N].erase(to_erase);
        }
    }
    size_t count(){return elements_.size();}
    void clear(){elements_.clear(); priorities_.clear();}

private:
    //types
    using Element = std::pair<ValType, PriorityList>;
    using pElement = typename std::list<Element>::iterator;
    using PriorityListItr = typename std::deque<pElement>::iterator;

    //functions
    std::function<bool(const pElement&, const pElement&)> compare_(size_t N) const{
        return [N](const pElement& a, const pElement& b){
            return a->second[N] < b->second[N];
        };
    }

    void insert_sorted_(size_t N, pElement ptr){
        auto list = priorities_[N];
        auto position = std::lower_bound(list.cbegin(), list.cend(),
                compare_(N));
        priorities_.at(N).insert(position, ptr);
    }

    PriorityListItr find_sorted_(size_t N, Element el) const{
        auto list = priorities_[N];
        auto range = std::equal_range(list.begin(), list.end(),
                compare_(N));
        for(auto itr=range.first; itr!=range.second; ++itr){
            if(**itr==el) return itr;
        }
        return list.end(); //if not found
    }

    //members
    std::list<Element> elements_;
    std::array<std::deque<pElement>, NQueues> priorities_;
};

<|endoftext|>


<commit_before>#include "MoveDummy.h"
#include "ObjectDummy.h"
#include "BodyDummy.h"
#include "ShapeCapsule.h"

#include "Utils.h"
#include "Engine.h"
#include "Physics.h"
#include "Game.h"
#include "World.h"

#define MOVE_DUMMY_IFPS			(1.0f/100.0f)
#define MOVE_DUMMY_CLAMP           89.9f
#define MOVE_DUMMY_COLLISIONS		1

using namespace MathLib;

CMoveDummy::CMoveDummy()		//캯
{
	m_pObject = new CObjectDummy();		//һʵ
	m_pDummy = new CBodyDummy();
	m_pShape = new CShapeCapsule(0.5f, 1.0f);

	SetCollisionMask(1);
	Clear();
}

CMoveDummy::~CMoveDummy()
{
	m_pDummy->SetObject(NULL);
	SAFE_DELETE(m_pObject);
	SAFE_DELETE(m_pDummy);
}

void CMoveDummy::SetCollision(int c)
{
	m_nCollision = c;
}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "MoveDummy.h"
#include "ObjectDummy.h"
#include "BodyDummy.h"
#include "ShapeCapsule.h"

#include "Utils.h"
#include "Engine.h"
#include "Physics.h"
#include "Game.h"
#include "World.h"

#define MOVE_DUMMY_IFPS			(1.0f/100.0f)
#define MOVE_DUMMY_CLAMP           89.9f
#define MOVE_DUMMY_COLLISIONS		1

using namespace MathLib;

CMoveDummy::CMoveDummy()		//캯
{
	m_pObject = new CObjectDummy();		//һʵ
	m_pDummy = new CBodyDummy();
	m_pShape = new CShapeCapsule(0.5f, 1.0f);

	SetCollisionMask(1);
	Clear();
}

CMoveDummy::~CMoveDummy()
{
	m_pDummy->SetObject(NULL);
	SAFE_DELETE(m_pObject);
	SAFE_DELETE(m_pDummy);
}

void CMoveDummy::SetCollision(int c)
{
	m_nCollision = c;
}

int CMoveDummy::GetCollision() const
{
	return m_nCollision;
}

<|endoftext|>


<commit_before>#include "MoveDummy.h"
#include "ObjectDummy.h"
#include "BodyDummy.h"
#include "ShapeCapsule.h"

#include "Utils.h"
#include "Engine.h"
#include "Physics.h"
#include "Game.h"
#include "World.h"

#define MOVE_DUMMY_IFPS			(1.0f/100.0f)
#define MOVE_DUMMY_CLAMP           89.9f
#define MOVE_DUMMY_COLLISIONS		1

using namespace MathLib;

CMoveDummy::CMoveDummy()		//캯
{
	m_pObject = new CObjectDummy();		//һʵ
	m_pDummy = new CBodyDummy();
	m_pShape = new CShapeCapsule(0.5f, 1.0f);

	SetCollisionMask(1);
	Clear();
}

CMoveDummy::~CMoveDummy()
{
	m_pDummy->SetObject(NULL);
	SAFE_DELETE(m_pObject);
	SAFE_DELETE(m_pDummy);
}

void CMoveDummy::SetCollision(int c)
{
	m_nCollision = c;
}

int CMoveDummy::GetCollision() const
{
	return m_nCollision;
}

void CMoveDummy::SetCollisionMask(int m)
{
	m_pShape->SetCollisionMask(m);
}

int CMoveDummy::GetCollisionMask() const
{
	return m_nCollisionMask;
}

void CMoveDummy::SetGround(int g)
{
	m_nGround = g;
}

int CMoveDummy::GetGround() const
{
	return m_nGround;
}

void CMoveDummy::SetCeiling(int c)
{
	m_nCeiling = c;
}

int CMoveDummy::GetCeiling() const
{
	return m_nCeiling;
}

void CMoveDummy::SetPosition(const MathLib::vec3& p)
{
	m_vPosition = p;
}

const MathLib::vec3& CMoveDummy::GetPosition() const
{
	return m_vPosition;
}

void CMoveDummy::SetCollisionRadius(float radius)
{
	if (!Compare(m_pShape->GetRadius(), radius))
	{
		m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (radius - m_pShape->GetRadius()))) * m_pDummy->GetTransform());
		m_pShape->SetRadius(radius);
	}

	Update_Bounds();
}

float CMoveDummy::GetCollisionRadius() const
{
	return m_pShape->GetRadius();
}

void CMoveDummy::SetCollisionHeight(float height)
{
	if (!Compare(m_pShape->GetHeight(), height))
	{
		m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (height - m_pShape->GetHeight()) * 0.5f)) * m_pDummy->GetTransform());
		m_pShape->SetHeight(height);
	}

	Update_Bounds();
}
float CMoveDummy::GetCollisionHeight() const
{
	return m_pShape->GetHeight();
}

void CMoveDummy::SetUp(const MathLib::vec3& u)
{
	m_vUp = u;
}

const MathLib::vec3& CMoveDummy::GetUp() const
{
	return m_vUp;
}
void CMoveDummy::SetEnabled(int e)
{
	m_nEnabled = e;
}

float CMoveDummy::GetCollisionHeight() const
{
	return m_pShape->GetHeight();
}
void CMoveDummy::SetUp(const MathLib::vec3& u)
{
	m_vUp = u;
}

const MathLib::vec3& CMoveDummy::GetUp() const
{
	return m_vUp;
}
void CMoveDummy::SetEnabled(int e)
{
	m_nEnabled = e;
}

int CMoveDummy::GetEnabled() const
{
	return m_nEnabled;
}

void CMoveDummy::SetVelocity(const MathLib::vec3& v)
{
	m_vVelocity = v;
}

const MathLib::vec3& CMoveDummy::GetVelocity() const
{
	return m_vVelocity;
}

void CMoveDummy::SetMaxVelocity(float v)
{
	m_fMaxVelocity = v;
}
float CMoveDummy::GetMaxVelocity() const
{
	return m_fMaxVelocity;
}

void CMoveDummy::SetAcceleration(float a)
{
	m_fAcceleration = a;
}
float CMoveDummy::GetAcceleration() const
{
	return m_fAcceleration;
}
float CMoveDummy::GetMaxThrough() const
{
	return m_fMaxThrough;
}
void CMoveDummy::Clear()
{
	SetVelocity(vec3_zero);
	SetMaxVelocity(2.5f);
	SetAcceleration(15.0f);
	SetCollision(1);
	SetCollisionMask(1);
	SetGround(0);
	SetCeiling(0);
	SetPosition(vec3_zero);
	SetUp(vec3(0.0f, 0.0f, 1.0f));
	SetEnabled(1);
	m_pDummy->SetEnabled(1);
	m_pObject->SetBody(NULL);
	m_pObject->SetBody(m_pDummy);

	m_pShape->SetBody(NULL);
	m_pShape->SetBody(m_pDummy);
	m_pShape->SetExclusionMask(2);

	m_pObject->SetWorldTransform(Get_Body_Transform());

	SetCollisionRadius(0.5f);
	SetCollisionHeight(1.0f);

	SetMaxThrough(0.4f);

	m_vecContacts.Clear();

}
int CMoveDummy::Update(float fIfps, const MathLib::vec3& vDirection)
{
	return Update(fIfps, vDirection, m_vPosition);
}
int CMoveDummy::Update(float fIfps, const MathLib::vec3& vDirection, const MathLib::vec3& pos)
{
	SetPosition(pos);

	vec3 vOldPosition = m_vPosition;

	float fVVelocity = Dot(m_vVelocity, m_vUp);
	float fHVelocity = CMathCore::Sqrt(CMathCore::Abs(m_vVelocity.length2() - fVVelocity*fVVelocity));

	m_vVelocity = m_vUp * fVVelocity + vDirection * fHVelocity;
	// time
	float time = fIfps;// * g_Engine.pPhysics->GetScale();

	// penetration tolerance
	float penetration = g_Engine.pPhysics->GetPenetrationTolerance();
	float penetration_2 = penetration * 2.0f;
	// clear collision flags
	if (GetCollision())
	{
		m_nGround = 0;
		m_nCeiling = 0;
	}

	// frozen linear velocity
	float frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity();

	// movement
	do
	{
		// adaptive time step
		float ifps = Min(time, MOVE_DUMMY_IFPS);
		time -= ifps;
		// integrate velocity
		m_vVelocity += vDirection * (m_fAcceleration * ifps);
		m_vVelocity += g_Engine.pPhysics->GetGravity() * ifps;

		fVVelocity = Dot(m_vVelocity, m_vUp);
		fHVelocity = CMathCore::Sqrt(m_vVelocity.length2() - fVVelocity*fVVelocity);

		m_vVelocity = m_vUp * fVVelocity + vDirection * m_fMaxVelocity;

	}
	while (time > EPSILON);
	if (GetCollision())
	{
		int nSurface = -1;
	}

	Vec3 vStart = m_vPosition + vDirection * GetCollisionRadius() + Vec3(m_vUp * (m_pShape->GetHHeight() + m_pShape->GetRadius()));
	Vec3 vEnd = vOldPosition + Vec3(m_vUp * (m_pShape->GetHHeight() + m_pShape->GetRadius()));

}<commit_msg>Judge variable P<commit_after>#include "MoveDummy.h"
#include "ObjectDummy.h"
#include "BodyDummy.h"
#include "ShapeCapsule.h"

#include "Utils.h"
#include "Engine.h"
#include "Physics.h"
#include "Game.h"
#include "World.h"

#define MOVE_DUMMY_IFPS			(1.0f/100.0f)
#define MOVE_DUMMY_CLAMP           89.9f
#define MOVE_DUMMY_COLLISIONS		1

using namespace MathLib;

CMoveDummy::CMoveDummy()		//캯
{
	m_pObject = new CObjectDummy();		//һʵ
	m_pDummy = new CBodyDummy();
	m_pShape = new CShapeCapsule(0.5f, 1.0f);

	SetCollisionMask(1);
	Clear();
}

CMoveDummy::~CMoveDummy()
{
	m_pDummy->SetObject(NULL);
	SAFE_DELETE(m_pObject);
	SAFE_DELETE(m_pDummy);
}

void CMoveDummy::SetCollision(int c)
{
	m_nCollision = c;
}

int CMoveDummy::GetCollision() const
{
	return m_nCollision;
}

void CMoveDummy::SetCollisionMask(int m)
{
	m_pShape->SetCollisionMask(m);
}

int CMoveDummy::GetCollisionMask() const
{
	return m_nCollisionMask;
}

void CMoveDummy::SetGround(int g)
{
	m_nGround = g;
}

int CMoveDummy::GetGround() const
{
	return m_nGround;
}

void CMoveDummy::SetCeiling(int c)
{
	m_nCeiling = c;
}

int CMoveDummy::GetCeiling() const
{
	return m_nCeiling;
}

void CMoveDummy::SetPosition(const MathLib::vec3& p)
{
	m_vPosition = p;
}

const MathLib::vec3& CMoveDummy::GetPosition() const
{
	return m_vPosition;
}

void CMoveDummy::SetCollisionRadius(float radius)
{
	if (!Compare(m_pShape->GetRadius(), radius))
	{
		m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (radius - m_pShape->GetRadius()))) * m_pDummy->GetTransform());
		m_pShape->SetRadius(radius);
	}

	Update_Bounds();
}

float CMoveDummy::GetCollisionRadius() const
{
	return m_pShape->GetRadius();
}

void CMoveDummy::SetCollisionHeight(float height)
{
	if (!Compare(m_pShape->GetHeight(), height))
	{
		m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (height - m_pShape->GetHeight()) * 0.5f)) * m_pDummy->GetTransform());
		m_pShape->SetHeight(height);
	}

	Update_Bounds();
}
float CMoveDummy::GetCollisionHeight() const
{
	return m_pShape->GetHeight();
}

void CMoveDummy::SetUp(const MathLib::vec3& u)
{
	m_vUp = u;
}

const MathLib::vec3& CMoveDummy::GetUp() const
{
	return m_vUp;
}
void CMoveDummy::SetEnabled(int e)
{
	m_nEnabled = e;
}

float CMoveDummy::GetCollisionHeight() const
{
	return m_pShape->GetHeight();
}
void CMoveDummy::SetUp(const MathLib::vec3& u)
{
	m_vUp = u;
}

const MathLib::vec3& CMoveDummy::GetUp() const
{
	return m_vUp;
}
void CMoveDummy::SetEnabled(int e)
{
	m_nEnabled = e;
}

int CMoveDummy::GetEnabled() const
{
	return m_nEnabled;
}

void CMoveDummy::SetVelocity(const MathLib::vec3& v)
{
	m_vVelocity = v;
}

const MathLib::vec3& CMoveDummy::GetVelocity() const
{
	return m_vVelocity;
}

void CMoveDummy::SetMaxVelocity(float v)
{
	m_fMaxVelocity = v;
}
float CMoveDummy::GetMaxVelocity() const
{
	return m_fMaxVelocity;
}

void CMoveDummy::SetAcceleration(float a)
{
	m_fAcceleration = a;
}
float CMoveDummy::GetAcceleration() const
{
	return m_fAcceleration;
}
float CMoveDummy::GetMaxThrough() const
{
	return m_fMaxThrough;
}
void CMoveDummy::Clear()
{
	SetVelocity(vec3_zero);
	SetMaxVelocity(2.5f);
	SetAcceleration(15.0f);
	SetCollision(1);
	SetCollisionMask(1);
	SetGround(0);
	SetCeiling(0);
	SetPosition(vec3_zero);
	SetUp(vec3(0.0f, 0.0f, 1.0f));
	SetEnabled(1);
	m_pDummy->SetEnabled(1);
	m_pObject->SetBody(NULL);
	m_pObject->SetBody(m_pDummy);

	m_pShape->SetBody(NULL);
	m_pShape->SetBody(m_pDummy);
	m_pShape->SetExclusionMask(2);

	m_pObject->SetWorldTransform(Get_Body_Transform());

	SetCollisionRadius(0.5f);
	SetCollisionHeight(1.0f);

	SetMaxThrough(0.4f);

	m_vecContacts.Clear();

}
int CMoveDummy::Update(float fIfps, const MathLib::vec3& vDirection)
{
	return Update(fIfps, vDirection, m_vPosition);
}
int CMoveDummy::Update(float fIfps, const MathLib::vec3& vDirection, const MathLib::vec3& pos)
{
	SetPosition(pos);

	vec3 vOldPosition = m_vPosition;

	float fVVelocity = Dot(m_vVelocity, m_vUp);
	float fHVelocity = CMathCore::Sqrt(CMathCore::Abs(m_vVelocity.length2() - fVVelocity*fVVelocity));

	m_vVelocity = m_vUp * fVVelocity + vDirection * fHVelocity;
	// time
	float time = fIfps;// * g_Engine.pPhysics->GetScale();

	// penetration tolerance
	float penetration = g_Engine.pPhysics->GetPenetrationTolerance();
	float penetration_2 = penetration * 2.0f;
	// clear collision flags
	if (GetCollision())
	{
		m_nGround = 0;
		m_nCeiling = 0;
	}

	// frozen linear velocity
	float frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity();

	// movement
	do
	{
		// adaptive time step
		float ifps = Min(time, MOVE_DUMMY_IFPS);
		time -= ifps;
		// integrate velocity
		m_vVelocity += vDirection * (m_fAcceleration * ifps);
		m_vVelocity += g_Engine.pPhysics->GetGravity() * ifps;

		fVVelocity = Dot(m_vVelocity, m_vUp);
		fHVelocity = CMathCore::Sqrt(m_vVelocity.length2() - fVVelocity*fVVelocity);

		m_vVelocity = m_vUp * fVVelocity + vDirection * m_fMaxVelocity;

	}
	while (time > EPSILON);
	if (GetCollision())
	{
		int nSurface = -1;
	}

	Vec3 vStart = m_vPosition + vDirection * GetCollisionRadius() + Vec3(m_vUp * (m_pShape->GetHHeight() + m_pShape->GetRadius()));
	Vec3 vEnd = vOldPosition + Vec3(m_vUp * (m_pShape->GetHHeight() + m_pShape->GetRadius()));

	CBRObject *p = g_Engine.pWorld->GetIntersection(vStart, vEnd, 2, nSurface);

	if (p != NULL)
	{
		m_vPosition = vOldPosition;
	}
}

}<|endoftext|>


<commit_before>#pragma once
#include "ilayer.hpp"
#include <stdlib.h>

namespace Convolutional::Layer {

class FullyConnectedNeuralNetwork : public ILayer {
public:
	using ILayer::ILayer;

	class Neuron;

	class Connection {
	public:
		Neuron& from;
		Neuron& to;

		double weight = ((double) rand() / RAND_MAX * 2) - 1;

		Connection(Neuron& from, Neuron& to) : from(from), to(to) { };
	};

	class Neuron {
	public:
		Matrix::element_t lastActionPotential = 0;
		std::vector<Connection> connections;

		Neuron(std::size_t nConnections = 0) { connections.reserve(nConnections); };

		auto AddConnection(Connection& connection) -> void {
			connections.push_back(connection);
		}
	};

	class BiasNeuron: public Neuron {
	public:
		BiasNeuron(std::size_t nOutputs = 0) : Neuron(nOutputs) { lastActionPotential = 1.0; };
	};

	std::size_t nOutputs;
	std::vector<Neuron> inputNeurons;
	std::vector<Neuron> outputNeurons;

	FullyConnectedNeuralNetwork(std::size_t outputCount): nOutputs(outputCount), outputNeurons(outputCount, Neuron()) { };
	FullyConnectedNeuralNetwork(const FullyConnectedNeuralNetwork&) = default;
	FullyConnectedNeuralNetwork(FullyConnectedNeuralNetwork&&) = default;

	auto ProcessMultiMatrix(const MultiMatrix& multiMatrix) -> MultiMatrix override;
	auto GetReceptiveField(Matrix::Size size) const noexcept -> Matrix::Size override { return {1, 1}; }
	auto GetZeroPadding(Matrix::Size size) const noexcept -> Matrix::Size override { return {0, 0}; }
	auto GetStride(Matrix::Size size) const noexcept -> Matrix::Size override { return {1, 1}; }

	auto Clone() const noexcept -> std::unique_ptr<ILayer> override { return std::make_unique<FullyConnectedNeuralNetwork>(*this); }
};

}
<commit_msg>Cleanup ctors<commit_after>#pragma once
#include "ilayer.hpp"
#include <stdlib.h>

namespace Convolutional::Layer {

class FullyConnectedNeuralNetwork : public ILayer {
public:
	using ILayer::ILayer;

	class Neuron;

	class Connection {
	public:
		Neuron& from;
		Neuron& to;

		double weight = ((double) rand() / RAND_MAX * 2) - 1;

		Connection(Neuron& from, Neuron& to) : from(from), to(to) { };
	};

	class Neuron {
	public:
		Matrix::element_t lastActionPotential = 0;
		std::vector<Connection> connections;

		Neuron(std::size_t nConnections = 0) { connections.reserve(nConnections); };

		auto AddConnection(Connection& connection) -> void {
			connections.push_back(connection);
		}
	};

	class BiasNeuron: public Neuron {
	public:
		BiasNeuron() { lastActionPotential = 1.0; };
	};

	std::size_t nOutputs;
	std::vector<Neuron> inputNeurons;
	std::vector<Neuron> outputNeurons;

	FullyConnectedNeuralNetwork(std::size_t outputCount): nOutputs(outputCount), outputNeurons(outputCount, Neuron()) { };
	FullyConnectedNeuralNetwork(const FullyConnectedNeuralNetwork&) = default;
	FullyConnectedNeuralNetwork(FullyConnectedNeuralNetwork&&) = default;

	auto ProcessMultiMatrix(const MultiMatrix& multiMatrix) -> MultiMatrix override;
	auto GetReceptiveField(Matrix::Size size) const noexcept -> Matrix::Size override { return {1, 1}; }
	auto GetZeroPadding(Matrix::Size size) const noexcept -> Matrix::Size override { return {0, 0}; }
	auto GetStride(Matrix::Size size) const noexcept -> Matrix::Size override { return {1, 1}; }

	auto Clone() const noexcept -> std::unique_ptr<ILayer> override { return std::make_unique<FullyConnectedNeuralNetwork>(*this); }
};

}
<|endoftext|>


<commit_before>#pragma once

#include <cassert>
#include <cstring>
#include <ostream>
#include <sstream>
#include <string>

#include "fixfmt/base.hh"
#include "fixfmt/math.hh"
#include "fixfmt/text.hh"

//------------------------------------------------------------------------------

namespace fixfmt {

using std::string;

class Number
{
public:

  constexpr static char PAD_SPACE      = ' ';
  constexpr static char PAD_ZERO       = '0';

  constexpr static char SIGN_NONE      = ' ';
  constexpr static char SIGN_NEGATIVE  = '-';
  constexpr static char SIGN_ALWAYS    = '+';

  constexpr static int  PRECISION_NONE = -1;

  /*
   * Fixed scaling for rendering numbers.
   *
   * @factor
   *   The positive scale factor in which values are represented.  A value is
   *   divided by this value when formatted.  Use 0 for no scaling.
   * @suffix
   *   A suffix to append to formatted numbers to indicate scale.
   */
  struct Scale
  {
    double  factor          = 0;
    string  suffix          = "";

    bool enabled() const noexcept { return factor > 0; }
  };

  static Scale const    SCALE_NONE;

  static Scale const    SCALE_PERCENT;
  static Scale const    SCALE_PER_MILLE;
  static Scale const    SCALE_BASIS_POINTS;

  static Scale const    SCALE_TERA;
  static Scale const    SCALE_GIGA;
  static Scale const    SCALE_MEGA;
  static Scale const    SCALE_KILO;
  static Scale const    SCALE_DECI;
  static Scale const    SCALE_CENTI;
  static Scale const    SCALE_MILLI;
  static Scale const    SCALE_MICRO;
  static Scale const    SCALE_NANO;
  static Scale const    SCALE_PICO;
  static Scale const    SCALE_FEMTO;

  static Scale const    SCALE_GIBI;
  static Scale const    SCALE_MEBI;
  static Scale const    SCALE_KIBI;

  /*
   * Arguments to a number formatter.
   */
  struct Args
  {
    int     size            = 8;
    int     precision       = PRECISION_NONE;
    char    sign            = SIGN_NEGATIVE;
    char    pad             = ' ';
    char    point           = '.';
    char    bad             = '#';
    string  nan             = "NaN";
    string  inf             = "inf";
    Scale   scale           = {};
  };

  Number()                              = default;
  Number(Number const&)                 = default;
  Number(Number&&) noexcept             = default;
  Number& operator=(Number const&)      = default;
  Number& operator=(Number&&) noexcept  = default;
  ~Number() noexcept                    = default;

  Number(Args const& args)
    : args_(args) { check(args_); set_up(); }
  Number(Args&& args)
    : args_(std::move(args)) { check(args_); set_up(); }

  /*
   * Convenience ctor for the most common options.
   */
  explicit
  Number(
      int   const size,
      int   const precision =PRECISION_NONE,
      char  const sign      =SIGN_NEGATIVE)
  : Number(Args{size, .precision=precision, .sign=sign})
  {
  }

  Args const& get_args() const noexcept
    { return args_; }
  void set_args(Args const& args)
    { check(args); args_ = args; set_up(); }
  void set_args(Args&& args)
    { check(args); args_ = std::move(args); set_up(); }

  size_t        get_width() const noexcept { return width_; }
  string        operator()(long val) const;
  string        operator()(double val) const;

  // Make sure we use the integer implementation for integral types.
  string operator()(int            val) const { return operator()((long) val); }
  string operator()(short          val) const { return operator()((long) val); }
  string operator()(char           val) const { return operator()((long) val); }
  string operator()(unsigned long  val) const { return operator()((long) val); }
  string operator()(unsigned int   val) const { return operator()((long) val); }
  string operator()(unsigned short val) const { return operator()((long) val); }
  string operator()(unsigned char  val) const { return operator()((long) val); }

private:

  static void check(Args const&);
  char get_sign_char(bool nonneg) const;
  string format_inf_nan(string const& str, int sign) const;
  void set_up();

  Args      args_ = {};

  // Display width.
  size_t    width_;
  // Maximum allocation size.
  size_t    alloc_size_;

  string    nan_;
  string    pos_inf_;
  string    neg_inf_;
  string    bad_;

};

//------------------------------------------------------------------------------

inline void
Number::check(
  Args const& args)
{
  // FIXME: Use Expect() or similar.
  assert(args.size >= 0);
  assert(args.precision == PRECISION_NONE || args.precision >= 0);
  assert(args.size > 0 || args.precision > 0);
  assert(args.pad == PAD_SPACE || args.pad == PAD_ZERO);
  assert(
         args.sign == SIGN_NONE
      || args.sign == SIGN_NEGATIVE
      || args.sign == SIGN_ALWAYS);
  assert(args.scale.factor >= 0);
}

inline char
Number::get_sign_char(
  bool const nonneg)
  const
{
  assert(args_.sign != SIGN_NONE);
  return nonneg ? (args_.sign == SIGN_ALWAYS ? '+' : ' ') : '-';
}

inline string
Number::format_inf_nan(
  string const& str,
  int const sign)
  const
{
  // Tack on the sign.
  bool const has_sign = args_.sign != SIGN_NONE;
  string result =
    ! has_sign || sign == 0 ? str
    : get_sign_char(sign > 0) + str;
  int const len = string_length(result);
  int const size = args_.size + has_sign;

  // Try to put it in the integer part.
  if (len <= (int) width_)
    result = pad(
      pad(result, size, " ", PAD_POSITION_RIGHT_JUSTIFY),
      width_, " ", PAD_POSITION_LEFT_JUSTIFY);
  else
    // Doesn't fit at all.
    string_truncate(result, width_);

  return result;
}

inline void
Number::set_up()
{
  auto sz =
        args_.size
      + (args_.precision == PRECISION_NONE ? 0 : 1 + args_.precision)
      + (args_.sign == SIGN_NEGATIVE || args_.sign == SIGN_ALWAYS ? 1 : 0);
  width_ = sz + (args_.scale.enabled() ? string_length(args_.scale.suffix) : 0);
  alloc_size_ = sz + (args_.scale.enabled() ? args_.scale.suffix.size() : 0);

  nan_ = format_inf_nan(args_.nan, 0);
  pos_inf_ = format_inf_nan(args_.inf,  1);
  neg_inf_ = format_inf_nan(args_.inf, -1);
  bad_ = std::string(width_, args_.bad);
}

}  // namespace fixfmt

<commit_msg>Remove noexcet from some defaulted methods.<commit_after>#pragma once

#include <cassert>
#include <cstring>
#include <ostream>
#include <sstream>
#include <string>

#include "fixfmt/base.hh"
#include "fixfmt/math.hh"
#include "fixfmt/text.hh"

//------------------------------------------------------------------------------

namespace fixfmt {

using std::string;

class Number
{
public:

  constexpr static char PAD_SPACE      = ' ';
  constexpr static char PAD_ZERO       = '0';

  constexpr static char SIGN_NONE      = ' ';
  constexpr static char SIGN_NEGATIVE  = '-';
  constexpr static char SIGN_ALWAYS    = '+';

  constexpr static int  PRECISION_NONE = -1;

  /*
   * Fixed scaling for rendering numbers.
   *
   * @factor
   *   The positive scale factor in which values are represented.  A value is
   *   divided by this value when formatted.  Use 0 for no scaling.
   * @suffix
   *   A suffix to append to formatted numbers to indicate scale.
   */
  struct Scale
  {
    double  factor          = 0;
    string  suffix          = "";

    bool enabled() const noexcept { return factor > 0; }
  };

  static Scale const    SCALE_NONE;

  static Scale const    SCALE_PERCENT;
  static Scale const    SCALE_PER_MILLE;
  static Scale const    SCALE_BASIS_POINTS;

  static Scale const    SCALE_TERA;
  static Scale const    SCALE_GIGA;
  static Scale const    SCALE_MEGA;
  static Scale const    SCALE_KILO;
  static Scale const    SCALE_DECI;
  static Scale const    SCALE_CENTI;
  static Scale const    SCALE_MILLI;
  static Scale const    SCALE_MICRO;
  static Scale const    SCALE_NANO;
  static Scale const    SCALE_PICO;
  static Scale const    SCALE_FEMTO;

  static Scale const    SCALE_GIBI;
  static Scale const    SCALE_MEBI;
  static Scale const    SCALE_KIBI;

  /*
   * Arguments to a number formatter.
   */
  struct Args
  {
    int     size            = 8;
    int     precision       = PRECISION_NONE;
    char    sign            = SIGN_NEGATIVE;
    char    pad             = ' ';
    char    point           = '.';
    char    bad             = '#';
    string  nan             = "NaN";
    string  inf             = "inf";
    Scale   scale           = {};
  };

  Number()                              = default;
  Number(Number const&)                 = default;
  Number(Number&&)                      = default;
  Number& operator=(Number const&)      = default;
  Number& operator=(Number&&)           = default;
  ~Number() noexcept                    = default;

  Number(Args const& args)
    : args_(args) { check(args_); set_up(); }
  Number(Args&& args)
    : args_(std::move(args)) { check(args_); set_up(); }

  /*
   * Convenience ctor for the most common options.
   */
  explicit
  Number(
      int   const size,
      int   const precision =PRECISION_NONE,
      char  const sign      =SIGN_NEGATIVE)
  : Number(Args{size, .precision=precision, .sign=sign})
  {
  }

  Args const& get_args() const noexcept
    { return args_; }
  void set_args(Args const& args)
    { check(args); args_ = args; set_up(); }
  void set_args(Args&& args)
    { check(args); args_ = std::move(args); set_up(); }

  size_t        get_width() const noexcept { return width_; }
  string        operator()(long val) const;
  string        operator()(double val) const;

  // Make sure we use the integer implementation for integral types.
  string operator()(int            val) const { return operator()((long) val); }
  string operator()(short          val) const { return operator()((long) val); }
  string operator()(char           val) const { return operator()((long) val); }
  string operator()(unsigned long  val) const { return operator()((long) val); }
  string operator()(unsigned int   val) const { return operator()((long) val); }
  string operator()(unsigned short val) const { return operator()((long) val); }
  string operator()(unsigned char  val) const { return operator()((long) val); }

private:

  static void check(Args const&);
  char get_sign_char(bool nonneg) const;
  string format_inf_nan(string const& str, int sign) const;
  void set_up();

  Args      args_ = {};

  // Display width.
  size_t    width_;
  // Maximum allocation size.
  size_t    alloc_size_;

  string    nan_;
  string    pos_inf_;
  string    neg_inf_;
  string    bad_;

};

//------------------------------------------------------------------------------

inline void
Number::check(
  Args const& args)
{
  // FIXME: Use Expect() or similar.
  assert(args.size >= 0);
  assert(args.precision == PRECISION_NONE || args.precision >= 0);
  assert(args.size > 0 || args.precision > 0);
  assert(args.pad == PAD_SPACE || args.pad == PAD_ZERO);
  assert(
         args.sign == SIGN_NONE
      || args.sign == SIGN_NEGATIVE
      || args.sign == SIGN_ALWAYS);
  assert(args.scale.factor >= 0);
}

inline char
Number::get_sign_char(
  bool const nonneg)
  const
{
  assert(args_.sign != SIGN_NONE);
  return nonneg ? (args_.sign == SIGN_ALWAYS ? '+' : ' ') : '-';
}

inline string
Number::format_inf_nan(
  string const& str,
  int const sign)
  const
{
  // Tack on the sign.
  bool const has_sign = args_.sign != SIGN_NONE;
  string result =
    ! has_sign || sign == 0 ? str
    : get_sign_char(sign > 0) + str;
  int const len = string_length(result);
  int const size = args_.size + has_sign;

  // Try to put it in the integer part.
  if (len <= (int) width_)
    result = pad(
      pad(result, size, " ", PAD_POSITION_RIGHT_JUSTIFY),
      width_, " ", PAD_POSITION_LEFT_JUSTIFY);
  else
    // Doesn't fit at all.
    string_truncate(result, width_);

  return result;
}

inline void
Number::set_up()
{
  auto sz =
        args_.size
      + (args_.precision == PRECISION_NONE ? 0 : 1 + args_.precision)
      + (args_.sign == SIGN_NEGATIVE || args_.sign == SIGN_ALWAYS ? 1 : 0);
  width_ = sz + (args_.scale.enabled() ? string_length(args_.scale.suffix) : 0);
  alloc_size_ = sz + (args_.scale.enabled() ? args_.scale.suffix.size() : 0);

  nan_ = format_inf_nan(args_.nan, 0);
  pos_inf_ = format_inf_nan(args_.inf,  1);
  neg_inf_ = format_inf_nan(args_.inf, -1);
  bad_ = std::string(width_, args_.bad);
}

}  // namespace fixfmt

<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  Copyright (c) 2012-, Open Perception, Inc.
 *
 *  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 the copyright holder(s) 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.
 *
 *
 */
#include <pcl/io/image_grabber.h>
#include <pcl/console/parse.h>
#include <pcl/console/print.h>
#include <pcl/visualization/boost.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/visualization/image_viewer.h>
#include <pcl/io/pcd_io.h>

using pcl::console::print_error;
using pcl::console::print_info;
using pcl::console::print_value;

//boost::mutex mutex_;
boost::shared_ptr<pcl::ImageGrabber<pcl::PointXYZRGBA> > grabber;
pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr cloud_;
std::string out_folder;
int counter;

void
printHelp (int, char **argv)
{
  print_error ("Syntax is: %s <options>\n", argv[0]);
  print_info (" where options are:\n");
  print_info ("\t-rgb_dir   \t<directory_path>    \t= directory path to RGB images to be read from\n");
  print_info ("\t-depth_dir \t<directory_path>    \t= directory path to Depth images to be read from\n");
  print_info ("\t-out_dir   \t<directory_path>    \t= directory path to put the pcd files\n");
  //print_info ("\t-fps frequency           = frames per second\n");
  print_info ("\n");
}

struct EventHelper
{
  void
  cloud_cb (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr & cloud)
  {
    std::stringstream ss;
    ss << out_folder << "/" << grabber->getPrevDepthFileName() << ".pcd";
    pcl::io::savePCDFileASCII (ss.str(), *cloud);
  }
};

/* ---[ */
int
main (int argc, char** argv)
{
  counter = 0;
  out_folder.clear();

  if (argc > 1)
  {
    for (int i = 1; i < argc; i++)
    {
      if (std::string (argv[i]) == "-h")
      {
        printHelp (argc, argv);
        return (-1);
      }
    }
  }

  float frames_per_second = 0; // 0 means only if triggered!
  pcl::console::parse (argc, argv, "-fps", frames_per_second);
  if (frames_per_second < 0)
    frames_per_second = 0.0;

  float focal_length = 525.0;
  pcl::console::parse (argc, argv, "-focal", focal_length);

  std::string depth_path = "";
  pcl::console::parse_argument (argc, argv, "-depth_dir", depth_path);

  std::string rgb_path = "";
  pcl::console::parse_argument (argc, argv, "-rgb_dir", rgb_path);

  pcl::console::parse_argument (argc, argv, "-out_dir", out_folder);

  if (out_folder == "" || !boost::filesystem::exists (out_folder))
  {
    PCL_INFO("No correct directory was given with the -out_dir flag. Setting to current dir\n");
    out_folder = "./";
  }
  else
    PCL_INFO("Using %s as output dir", out_folder);

  if (rgb_path != "" && depth_path != "" && boost::filesystem::exists (rgb_path) && boost::filesystem::exists (depth_path))
  {
    grabber.reset (new pcl::ImageGrabber<pcl::PointXYZRGBA> (depth_path, rgb_path, frames_per_second, false));
  }
  else
  {
    PCL_INFO("No directory was given with the -<rgb/depth>_dir flag.");
    printHelp (argc, argv);
    return (-1);
  }
  grabber->setDepthImageUnits (float (1E-3));
  //grabber->setFocalLength(focal_length); // FIXME

  EventHelper h;
  boost::function<void(const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr&) > f = boost::bind (&EventHelper::cloud_cb, &h, _1);
  boost::signals2::connection c1 = grabber->registerCallback (f);

  do
  {
    grabber->trigger();
  }
  while (!grabber->atLastFrame());
  grabber->trigger(); // Attempt to process the last frame
  grabber->stop ();
}
/* ]--- */
<commit_msg>small error in print statement<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  Copyright (c) 2012-, Open Perception, Inc.
 *
 *  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 the copyright holder(s) 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.
 *
 *
 */
#include <pcl/io/image_grabber.h>
#include <pcl/console/parse.h>
#include <pcl/console/print.h>
#include <pcl/visualization/boost.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/visualization/image_viewer.h>
#include <pcl/io/pcd_io.h>

using pcl::console::print_error;
using pcl::console::print_info;
using pcl::console::print_value;

//boost::mutex mutex_;
boost::shared_ptr<pcl::ImageGrabber<pcl::PointXYZRGBA> > grabber;
pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr cloud_;
std::string out_folder;
int counter;

void
printHelp (int, char **argv)
{
  print_error ("Syntax is: %s <options>\n", argv[0]);
  print_info (" where options are:\n");
  print_info ("\t-rgb_dir   \t<directory_path>    \t= directory path to RGB images to be read from\n");
  print_info ("\t-depth_dir \t<directory_path>    \t= directory path to Depth images to be read from\n");
  print_info ("\t-out_dir   \t<directory_path>    \t= directory path to put the pcd files\n");
  //print_info ("\t-fps frequency           = frames per second\n");
  print_info ("\n");
}

struct EventHelper
{
  void
  cloud_cb (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr & cloud)
  {
    std::stringstream ss;
    ss << out_folder << "/" << grabber->getPrevDepthFileName() << ".pcd";
    pcl::io::savePCDFileASCII (ss.str(), *cloud);
  }
};

/* ---[ */
int
main (int argc, char** argv)
{
  counter = 0;
  out_folder.clear();

  if (argc > 1)
  {
    for (int i = 1; i < argc; i++)
    {
      if (std::string (argv[i]) == "-h")
      {
        printHelp (argc, argv);
        return (-1);
      }
    }
  }

  float frames_per_second = 0; // 0 means only if triggered!
  pcl::console::parse (argc, argv, "-fps", frames_per_second);
  if (frames_per_second < 0)
    frames_per_second = 0.0;

  float focal_length = 525.0;
  pcl::console::parse (argc, argv, "-focal", focal_length);

  std::string depth_path = "";
  pcl::console::parse_argument (argc, argv, "-depth_dir", depth_path);

  std::string rgb_path = "";
  pcl::console::parse_argument (argc, argv, "-rgb_dir", rgb_path);

  pcl::console::parse_argument (argc, argv, "-out_dir", out_folder);

  if (out_folder == "" || !boost::filesystem::exists (out_folder))
  {
    PCL_INFO("No correct directory was given with the -out_dir flag. Setting to current dir\n");
    out_folder = "./";
  }
  else
    PCL_INFO("Using %s as output dir", out_folder.c_str());

  if (rgb_path != "" && depth_path != "" && boost::filesystem::exists (rgb_path) && boost::filesystem::exists (depth_path))
  {
    grabber.reset (new pcl::ImageGrabber<pcl::PointXYZRGBA> (depth_path, rgb_path, frames_per_second, false));
  }
  else
  {
    PCL_INFO("No directory was given with the -<rgb/depth>_dir flag.");
    printHelp (argc, argv);
    return (-1);
  }
  grabber->setDepthImageUnits (float (1E-3));
  //grabber->setFocalLength(focal_length); // FIXME

  EventHelper h;
  boost::function<void(const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr&) > f = boost::bind (&EventHelper::cloud_cb, &h, _1);
  boost::signals2::connection c1 = grabber->registerCallback (f);

  do
  {
    grabber->trigger();
  }
  while (!grabber->atLastFrame());
  grabber->trigger(); // Attempt to process the last frame
  grabber->stop ();
}
/* ]--- */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: arealink.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: kz $ $Date: 2004-10-04 20:03:30 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SC_AREALINK_HXX
#define SC_AREALINK_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_REFRESHTIMER_HXX
#include "refreshtimer.hxx"
#endif

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

#ifndef _LNKBASE_HXX //autogen
#include <sfx2/lnkbase.hxx>
#endif

class ScDocShell;
class SfxObjectShell;

class ScAreaLink : public ::sfx2::SvBaseLink, public ScRefreshTimer
{
private:
    ScDocShell* pDocShell;      // Container
    String      aFileName;
    String      aFilterName;
    String      aOptions;
    String      aSourceArea;
    ScRange     aDestArea;
    BOOL        bAddUndo;
    BOOL        bInCreate;
    BOOL        bDoInsert;      // wird fuer das erste Update auf FALSE gesetzt

    BOOL        FindExtRange( ScRange& rRange, ScDocument* pSrcDoc, const String& rAreaName );

public:
    TYPEINFO();
    ScAreaLink( SfxObjectShell* pShell, const String& rFile,
                    const String& rFilter, const String& rOpt,
                    const String& rArea, const ScRange& rDest, ULONG nRefresh );
    virtual ~ScAreaLink();

    virtual void Closed();
    virtual void DataChanged( const String& rMimeType,
                              const ::com::sun::star::uno::Any & rValue );

    virtual BOOL Edit(Window* pParent);

    BOOL    Refresh( const String& rNewFile, const String& rNewFilter,
                    const String& rNewArea, ULONG nNewRefresh );

    void    SetInCreate(BOOL bSet)                  { bInCreate = bSet; }
    void    SetDoInsert(BOOL bSet)                  { bDoInsert = bSet; }
    void    SetDestArea(const ScRange& rNew);
    void    SetSource(const String& rDoc, const String& rFlt, const String& rOpt,
                        const String& rArea);

    BOOL    IsEqual( const String& rFile, const String& rFilter, const String& rOpt,
                        const String& rSource, const ScRange& rDest ) const;

    const String&   GetFile() const         { return aFileName;     }
    const String&   GetFilter() const       { return aFilterName;   }
    const String&   GetOptions() const      { return aOptions;      }
    const String&   GetSource() const       { return aSourceArea;   }
    const ScRange&  GetDestArea() const     { return aDestArea;     }

    DECL_LINK( RefreshHdl, ScAreaLink* );

};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.326); FILE MERGED 2005/09/05 15:00:32 rt 1.7.326.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: arealink.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:22:38 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SC_AREALINK_HXX
#define SC_AREALINK_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_REFRESHTIMER_HXX
#include "refreshtimer.hxx"
#endif

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

#ifndef _LNKBASE_HXX //autogen
#include <sfx2/lnkbase.hxx>
#endif

class ScDocShell;
class SfxObjectShell;

class ScAreaLink : public ::sfx2::SvBaseLink, public ScRefreshTimer
{
private:
    ScDocShell* pDocShell;      // Container
    String      aFileName;
    String      aFilterName;
    String      aOptions;
    String      aSourceArea;
    ScRange     aDestArea;
    BOOL        bAddUndo;
    BOOL        bInCreate;
    BOOL        bDoInsert;      // wird fuer das erste Update auf FALSE gesetzt

    BOOL        FindExtRange( ScRange& rRange, ScDocument* pSrcDoc, const String& rAreaName );

public:
    TYPEINFO();
    ScAreaLink( SfxObjectShell* pShell, const String& rFile,
                    const String& rFilter, const String& rOpt,
                    const String& rArea, const ScRange& rDest, ULONG nRefresh );
    virtual ~ScAreaLink();

    virtual void Closed();
    virtual void DataChanged( const String& rMimeType,
                              const ::com::sun::star::uno::Any & rValue );

    virtual BOOL Edit(Window* pParent);

    BOOL    Refresh( const String& rNewFile, const String& rNewFilter,
                    const String& rNewArea, ULONG nNewRefresh );

    void    SetInCreate(BOOL bSet)                  { bInCreate = bSet; }
    void    SetDoInsert(BOOL bSet)                  { bDoInsert = bSet; }
    void    SetDestArea(const ScRange& rNew);
    void    SetSource(const String& rDoc, const String& rFlt, const String& rOpt,
                        const String& rArea);

    BOOL    IsEqual( const String& rFile, const String& rFilter, const String& rOpt,
                        const String& rSource, const ScRange& rDest ) const;

    const String&   GetFile() const         { return aFileName;     }
    const String&   GetFilter() const       { return aFilterName;   }
    const String&   GetOptions() const      { return aOptions;      }
    const String&   GetSource() const       { return aSourceArea;   }
    const ScRange&  GetDestArea() const     { return aDestArea;     }

    DECL_LINK( RefreshHdl, ScAreaLink* );

};

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: BorderHandler.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-05 16:49:04 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef INCLUDED_BORDERHANDLER_HXX
#define INCLUDED_BORDERHANDLER_HXX

#ifndef INCLUDED_WRITERFILTERDLLAPI_H
#include <WriterFilterDllApi.hxx>
#endif
#include <resourcemodel/WW8ResourceModel.hxx>
#include <boost/shared_ptr.hpp>
#ifndef _COM_SUN_STAR_TABLE_BORDERLINE_HPP_
#include <com/sun/star/table/BorderLine.hpp>
#endif

namespace writerfilter {
namespace dmapper
{
class PropertyMap;
class WRITERFILTER_DLLPRIVATE BorderHandler : public Properties
{
public:
    //todo: order is a guess
    enum BorderPosition
    {
        BORDER_TOP,
        BORDER_LEFT,
        BORDER_BOTTOM,
        BORDER_RIGHT,
        BORDER_HORIZONTAL,
        BORDER_VERTICAL,
        BORDER_COUNT
    };

private:
    sal_Int8        m_nCurrentBorderPosition;
    //values of the current border
    sal_Int32       m_nLineWidth;
    sal_Int32       m_nLineType;
    sal_Int32       m_nLineColor;
    sal_Int32       m_nLineDistance;
    bool            m_bOOXML;

    ::com::sun::star::table::BorderLine         m_aBorderLines[BORDER_COUNT];

public:
    BorderHandler( bool bOOXML );
    virtual ~BorderHandler();

    // Properties
    virtual void attribute(Id Name, Value & val);
    virtual void sprm(Sprm & sprm);

    ::boost::shared_ptr<PropertyMap>            getProperties();
    ::com::sun::star::table::BorderLine         getBorderLine();
    sal_Int32                                   getLineDistance() const { return m_nLineDistance;}
};
typedef boost::shared_ptr< BorderHandler >          BorderHandlerPtr;
}}

#endif //
<commit_msg>INTEGRATION: CWS changefileheader (1.4.4); FILE MERGED 2008/04/01 13:02:26 thb 1.4.4.2: #i85898# Stripping all external header guards 2008/03/28 15:52:59 rt 1.4.4.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: BorderHandler.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef INCLUDED_BORDERHANDLER_HXX
#define INCLUDED_BORDERHANDLER_HXX

#include <WriterFilterDllApi.hxx>
#include <resourcemodel/WW8ResourceModel.hxx>
#include <boost/shared_ptr.hpp>
#include <com/sun/star/table/BorderLine.hpp>

namespace writerfilter {
namespace dmapper
{
class PropertyMap;
class WRITERFILTER_DLLPRIVATE BorderHandler : public Properties
{
public:
    //todo: order is a guess
    enum BorderPosition
    {
        BORDER_TOP,
        BORDER_LEFT,
        BORDER_BOTTOM,
        BORDER_RIGHT,
        BORDER_HORIZONTAL,
        BORDER_VERTICAL,
        BORDER_COUNT
    };

private:
    sal_Int8        m_nCurrentBorderPosition;
    //values of the current border
    sal_Int32       m_nLineWidth;
    sal_Int32       m_nLineType;
    sal_Int32       m_nLineColor;
    sal_Int32       m_nLineDistance;
    bool            m_bOOXML;

    ::com::sun::star::table::BorderLine         m_aBorderLines[BORDER_COUNT];

public:
    BorderHandler( bool bOOXML );
    virtual ~BorderHandler();

    // Properties
    virtual void attribute(Id Name, Value & val);
    virtual void sprm(Sprm & sprm);

    ::boost::shared_ptr<PropertyMap>            getProperties();
    ::com::sun::star::table::BorderLine         getBorderLine();
    sal_Int32                                   getLineDistance() const { return m_nLineDistance;}
};
typedef boost::shared_ptr< BorderHandler >          BorderHandlerPtr;
}}

#endif //
<|endoftext|>


<commit_before>#include "EEPROM_ACCESS_PARTICLE.h"

//typedef struct reading {
//    String data;					//Assuming a maximum of 30 characters
//    struct reading * next;
//} reading_t;

//reading_t * reading_queue_head = NULL;

void storeData(String msg)
{
	int position;
	int offset;

	EEPROM.put(0, DATA_IN_EEP);		//Indicates that data is present in EEPROM
	EEPROM.get(5, position);		//The starting position of most recently stored data

	if(position == 0)				//Sets the start point of the new data to be stored
	{
		offset = position + 10;
	}else
	{
		offset = position + STRING_LEN;
	}

	EEPROM.put(offset, msg);

	EEPROM.put(5, offset);			//Updates the start position
}

/*void addToQueue(String msg)
{
  reading_t * new_reading = new reading_t;
  new_reading->next = reading_queue_head;
  reading_queue_head = new_reading;//store the value
  new_reading->data = msg;
}

void processQueue()
{
	reading_t * current = reading_queue_head;

  while(reading_queue_head != NULL){
    current = reading_queue_head;
    boolean success = Particle.publish("colorinfo", reading_queue_head->data);	//I assume that colorinfo is used everywhere

    if(success){					//message was sent
      reading_queue_head = reading_queue_head->next;
      free(current);
      if(reading_queue_head != NULL){
        delay(1000); 				//wait a second before trying the next message Particle does not let us go faster than this
      }else{						//we are done here
        break;
      }
    }else{							//we failed to send try again later
		break;
    }
  }
}*/

void processData()
{
	int status;
	EEPROM.get(0,status);

	if(status == DATA_IN_EEP)
	{
		int position;
		String msg;
		boolean fail;

		EEPROM.get(5,position);			//Gets position of latestest data stored

		while(position > 10)
		{
			EEPROM.get(position, msg);	//copies data
			boolean success = Particle.publish("colorinfo", msg);	//publishes data onto the cloud
			if(!success)				//data to cloud transfer is unsuccesful
			{
				EEPROM.put(5, position);	//the position of latest data changes
				fail = TRUE;
				break;
			}
			//addToQueue(msg);			//adds data onto Q.
			position = position - STRING_LEN;	//position is shifted to next data stored
		}

		if(!fail)
		{
			position = 0;

			EEPROM.clear();					//clears all data in  EEPROM
			EEPROM.put(5, position);		//sets initial position
			EEPROM.put(0, NO_DATA_IN_EEP);		//indicates no data in EEPROM
		}
		//processQueue();					//processes data in correct order of stroage
	}
}
<commit_msg>Update EEPROM_ACCESS_PARTICLE.cpp<commit_after>#include "EEPROM_ACCESS_PARTICLE.h"

//typedef struct reading {
//    String data;					//Assuming a maximum of 30 characters
//    struct reading * next;
//} reading_t;

//reading_t * reading_queue_head = NULL;

void storeData(String msg)
{
	int position;
	int offset;

	EEPROM.put(0, DATA_IN_EEP);		//Indicates that data is present in EEPROM
	EEPROM.get(5, position);		//The starting position of most recently stored data

	if(position == 0)				//Sets the start point of the new data to be stored
	{
		offset = position + 10;
	}else
	{
		offset = position + STRING_LEN;
	}

	EEPROM.put(offset, msg);

	EEPROM.put(5, offset);			//Updates the start position
}

/*void addToQueue(String msg)
{
  reading_t * new_reading = new reading_t;
  new_reading->next = reading_queue_head;
  reading_queue_head = new_reading;//store the value
  new_reading->data = msg;
}

void processQueue()
{
	reading_t * current = reading_queue_head;

  while(reading_queue_head != NULL){
    current = reading_queue_head;
    boolean success = Particle.publish("colorinfo", reading_queue_head->data);	//I assume that colorinfo is used everywhere

    if(success){					//message was sent
      reading_queue_head = reading_queue_head->next;
      free(current);
      if(reading_queue_head != NULL){
        delay(1000); 				//wait a second before trying the next message Particle does not let us go faster than this
      }else{						//we are done here
        break;
      }
    }else{							//we failed to send try again later
		break;
    }
  }
}*/

void processData()
{
	int status;
	EEPROM.get(0,status);

	if(status == DATA_IN_EEP)
	{
		int position;
		char msg[32];
		boolean fail;

		EEPROM.get(5,position);			//Gets position of latestest data stored

		while(position > 10)
		{
			EEPROM.get(position, msg);	//copies data
			boolean success = Particle.publish("colorinfo", msg);	//publishes data onto the cloud
			if(!success)				//data to cloud transfer is unsuccesful
			{
				EEPROM.put(5, position);	//the position of latest data changes
				fail = TRUE;
				break;
			}
			//addToQueue(msg);			//adds data onto Q.
			position = position - STRING_LEN;	//position is shifted to next data stored
		}

		if(!fail)
		{
			position = 0;

			EEPROM.clear();					//clears all data in  EEPROM
			EEPROM.put(5, position);		//sets initial position
			EEPROM.put(0, NO_DATA_IN_EEP);		//indicates no data in EEPROM
		}
		//processQueue();					//processes data in correct order of stroage
	}
}
<|endoftext|>


<commit_before>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Utility/PixelFormat.hpp>
#include <Nazara/Core/Error.hpp>
#include <algorithm>
#include <array>
#include <cstring>
#include <Nazara/Utility/Debug.hpp>

namespace Nz
{
	inline PixelFormatInfo::PixelFormatInfo() :
	content(PixelFormatContent_Undefined),
	bitsPerPixel(0)
	{
	}

	inline PixelFormatInfo::PixelFormatInfo(PixelFormatContent formatContent, UInt8 bpp, PixelFormatSubType subType) :
	content(formatContent),
	redType(subType),
	greenType(subType),
	blueType(subType),
	alphaType(subType),
	bitsPerPixel(bpp)
	{
	}

	inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, UInt8 bpp, PixelFormatSubType subType) :
	content(formatContent),
	redType(subType),
	greenType(subType),
	blueType(subType),
	alphaType(subType),
	name(formatName),
	bitsPerPixel(bpp)
	{
	}

	inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, Bitset<> rMask, Bitset<> gMask, Bitset<> bMask, Bitset<> aMask, PixelFormatSubType subType) :
	redMask(rMask),
	greenMask(gMask),
	blueMask(bMask),
	alphaMask(aMask),
	content(formatContent),
	redType(subType),
	greenType(subType),
	blueType(subType),
	alphaType(subType),
	name(formatName)
	{
		RecomputeBitsPerPixel();
	}

	inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, PixelFormatSubType rType, Bitset<> rMask, PixelFormatSubType gType, Bitset<> gMask, PixelFormatSubType bType, Bitset<> bMask, PixelFormatSubType aType, Bitset<> aMask, UInt8 bpp) :
	redMask(rMask),
	greenMask(gMask),
	blueMask(bMask),
	alphaMask(aMask),
	content(formatContent),
	redType(rType),
	greenType(gType),
	blueType(bType),
	alphaType(aType),
	name(formatName)
	{
		if (bpp == 0)
			RecomputeBitsPerPixel();
	}

	inline void PixelFormatInfo::Clear()
	{
		bitsPerPixel = 0;
		alphaMask.Clear();
		blueMask.Clear();
		greenMask.Clear();
		redMask.Clear();
		name.Clear();
	}

	inline bool PixelFormatInfo::IsCompressed() const
	{
		return redType   == PixelFormatSubType_Compressed ||
		       greenType == PixelFormatSubType_Compressed ||
		       blueType  == PixelFormatSubType_Compressed ||
		       alphaType == PixelFormatSubType_Compressed;
	}

	inline bool PixelFormatInfo::IsValid() const
	{
		return bitsPerPixel != 0;
	}

	inline void PixelFormatInfo::RecomputeBitsPerPixel()
	{
		Bitset<> counter;
		counter |= redMask;
		counter |= greenMask;
		counter |= blueMask;
		counter |= alphaMask;

		bitsPerPixel = counter.Count();
	}

	inline bool PixelFormatInfo::Validate() const
	{
		if (!IsValid())
			return false;

		if (content <= PixelFormatContent_Undefined || content > PixelFormatContent_Max)
			return false;

		std::array<const Nz::Bitset<>*, 4> masks = {&redMask, &greenMask, &blueMask, &alphaMask};
		std::array<PixelFormatSubType, 4> types = {redType, greenType, blueType, alphaType};

		for (unsigned int i = 0; i < 4; ++i)
		{
			unsigned int usedBits = masks[i]->Count();
			if (usedBits == 0)
				continue;

			if (usedBits > bitsPerPixel)
				return false;

			switch (types[i])
			{
				case PixelFormatSubType_Half:
					if (usedBits != 16)
						return false;

					break;

				case PixelFormatSubType_Float:
					if (usedBits != 32)
						return false;

					break;

				default:
					break;
			}
		}

		return true;
	}

	inline std::size_t PixelFormat::ComputeSize(PixelFormatType format, unsigned int width, unsigned int height, unsigned int depth)
	{
		if (IsCompressed(format))
		{
			switch (format)
			{
				case PixelFormatType_DXT1:
				case PixelFormatType_DXT3:
				case PixelFormatType_DXT5:
					return (((width + 3) / 4) * ((height + 3) / 4) * (format == PixelFormatType_DXT1) ? 8 : 16) * depth;

				default:
					NazaraError("Unsupported format");
					return 0;
			}
		}
		else
			return width * height * depth * GetBytesPerPixel(format);
	}

	inline bool PixelFormat::Convert(PixelFormatType srcFormat, PixelFormatType dstFormat, const void* src, void* dst)
	{
		if (srcFormat == dstFormat)
		{
			std::memcpy(dst, src, GetBytesPerPixel(srcFormat));
			return true;
		}

		#if NAZARA_UTILITY_SAFE
		if (IsCompressed(srcFormat))
		{
			NazaraError("Cannot convert single pixel from compressed format");
			return false;
		}

		if (IsCompressed(dstFormat))
		{
			NazaraError("Cannot convert single pixel to compressed format");
			return false;
		}
		#endif

		ConvertFunction func = s_convertFunctions[srcFormat][dstFormat];
		if (!func)
		{
			NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " is not supported");
			return false;
		}

		if (!func(reinterpret_cast<const UInt8*>(src), reinterpret_cast<const UInt8*>(src) + GetBytesPerPixel(srcFormat), reinterpret_cast<UInt8*>(dst)))
		{
			NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " failed");
			return false;
		}

		return true;
	}

	inline bool PixelFormat::Convert(PixelFormatType srcFormat, PixelFormatType dstFormat, const void* start, const void* end, void* dst)
	{
		if (srcFormat == dstFormat)
		{
			std::memcpy(dst, start, reinterpret_cast<const UInt8*>(end)-reinterpret_cast<const UInt8*>(start));
			return true;
		}

		ConvertFunction func = s_convertFunctions[srcFormat][dstFormat];
		if (!func)
		{
			NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " is not supported");
			return false;
		}

		if (!func(reinterpret_cast<const UInt8*>(start), reinterpret_cast<const UInt8*>(end), reinterpret_cast<UInt8*>(dst)))
		{
			NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " failed");
			return false;
		}

		return true;
	}

	inline bool PixelFormat::Flip(PixelFlipping flipping, PixelFormatType format, unsigned int width, unsigned int height, unsigned int depth, const void* src, void* dst)
	{
		#if NAZARA_UTILITY_SAFE
		if (!IsValid(format))
		{
			NazaraError("Invalid pixel format");
			return false;
		}
		#endif

		auto it = s_flipFunctions[flipping].find(format);
		if (it != s_flipFunctions[flipping].end())
			it->second(width, height, depth, reinterpret_cast<const UInt8*>(src), reinterpret_cast<UInt8*>(dst));
		else
		{
			// Flipping générique

			#if NAZARA_UTILITY_SAFE
			if (IsCompressed(format))
			{
				NazaraError("No function to flip compressed format");
				return false;
			}
			#endif

			UInt8 bpp = GetBytesPerPixel(format);
			unsigned int lineStride = width*bpp;
			switch (flipping)
			{
				case PixelFlipping_Horizontally:
				{
					if (src == dst)
					{
						for (unsigned int z = 0; z < depth; ++z)
						{
							UInt8* ptr = reinterpret_cast<UInt8*>(dst) + width*height*z;
							for (unsigned int y = 0; y < height/2; ++y)
								std::swap_ranges(&ptr[y*lineStride], &ptr[(y+1)*lineStride-1], &ptr[(height-y-1)*lineStride]);
						}
					}
					else
					{
						for (unsigned int z = 0; z < depth; ++z)
						{
							const UInt8* srcPtr = reinterpret_cast<const UInt8*>(src);
							UInt8* dstPtr = reinterpret_cast<UInt8*>(dst) + (width-1)*height*depth*bpp;
							for (unsigned int y = 0; y < height; ++y)
							{
								std::memcpy(dstPtr, srcPtr, lineStride);

								srcPtr += lineStride;
								dstPtr -= lineStride;
							}
						}
					}
					break;
				}

				case PixelFlipping_Vertically:
				{
					if (src == dst)
					{
						for (unsigned int z = 0; z < depth; ++z)
						{
							UInt8* ptr = reinterpret_cast<UInt8*>(dst) + width*height*z;
							for (unsigned int y = 0; y < height; ++y)
							{
								for (unsigned int x = 0; x < width/2; ++x)
									std::swap_ranges(&ptr[x*bpp], &ptr[(x+1)*bpp], &ptr[(width-x)*bpp]);

								ptr += lineStride;
							}
						}
					}
					else
					{
						for (unsigned int z = 0; z < depth; ++z)
						{
							UInt8* ptr = reinterpret_cast<UInt8*>(dst) + width*height*z;
							for (unsigned int y = 0; y < height; ++y)
							{
								for (unsigned int x = 0; x < width; ++x)
									std::memcpy(&ptr[x*bpp], &ptr[(width-x)*bpp], bpp);

								ptr += lineStride;
							}
						}
					}
					break;
				}
			}
		}

		return true;
	}

	inline UInt8 PixelFormat::GetBitsPerPixel(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].bitsPerPixel;
	}

	inline UInt8 PixelFormat::GetBytesPerPixel(PixelFormatType format)
	{
		return GetBitsPerPixel(format)/8;
	}

	inline PixelFormatContent PixelFormat::GetContent(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].content;
	}

	inline const PixelFormatInfo& PixelFormat::GetInfo(PixelFormatType format)
	{
		return s_pixelFormatInfos[format];
	}

	inline const String& PixelFormat::GetName(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].name;
	}

	inline bool PixelFormat::HasAlpha(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].alphaMask.TestAny();
	}

	inline bool PixelFormat::IsCompressed(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].IsCompressed();
	}

	inline bool PixelFormat::IsConversionSupported(PixelFormatType srcFormat, PixelFormatType dstFormat)
	{
		if (srcFormat == dstFormat)
			return true;

		return s_convertFunctions[srcFormat][dstFormat] != nullptr;
	}

	inline bool PixelFormat::IsValid(PixelFormatType format)
	{
		return format != PixelFormatType_Undefined;
	}

	inline void PixelFormat::SetConvertFunction(PixelFormatType srcFormat, PixelFormatType dstFormat, ConvertFunction func)
	{
		s_convertFunctions[srcFormat][dstFormat] = func;
	}

	inline void PixelFormat::SetFlipFunction(PixelFlipping flipping, PixelFormatType format, FlipFunction func)
	{
		s_flipFunctions[flipping][format] = func;
	}
}

#include <Nazara/Utility/DebugOff.hpp>
<commit_msg>Utility/PixelFormat: Fix ComputeSize for DXT formats<commit_after>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Utility/PixelFormat.hpp>
#include <Nazara/Core/Error.hpp>
#include <algorithm>
#include <array>
#include <cstring>
#include <Nazara/Utility/Debug.hpp>

namespace Nz
{
	inline PixelFormatInfo::PixelFormatInfo() :
	content(PixelFormatContent_Undefined),
	bitsPerPixel(0)
	{
	}

	inline PixelFormatInfo::PixelFormatInfo(PixelFormatContent formatContent, UInt8 bpp, PixelFormatSubType subType) :
	content(formatContent),
	redType(subType),
	greenType(subType),
	blueType(subType),
	alphaType(subType),
	bitsPerPixel(bpp)
	{
	}

	inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, UInt8 bpp, PixelFormatSubType subType) :
	content(formatContent),
	redType(subType),
	greenType(subType),
	blueType(subType),
	alphaType(subType),
	name(formatName),
	bitsPerPixel(bpp)
	{
	}

	inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, Bitset<> rMask, Bitset<> gMask, Bitset<> bMask, Bitset<> aMask, PixelFormatSubType subType) :
	redMask(rMask),
	greenMask(gMask),
	blueMask(bMask),
	alphaMask(aMask),
	content(formatContent),
	redType(subType),
	greenType(subType),
	blueType(subType),
	alphaType(subType),
	name(formatName)
	{
		RecomputeBitsPerPixel();
	}

	inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, PixelFormatSubType rType, Bitset<> rMask, PixelFormatSubType gType, Bitset<> gMask, PixelFormatSubType bType, Bitset<> bMask, PixelFormatSubType aType, Bitset<> aMask, UInt8 bpp) :
	redMask(rMask),
	greenMask(gMask),
	blueMask(bMask),
	alphaMask(aMask),
	content(formatContent),
	redType(rType),
	greenType(gType),
	blueType(bType),
	alphaType(aType),
	name(formatName)
	{
		if (bpp == 0)
			RecomputeBitsPerPixel();
	}

	inline void PixelFormatInfo::Clear()
	{
		bitsPerPixel = 0;
		alphaMask.Clear();
		blueMask.Clear();
		greenMask.Clear();
		redMask.Clear();
		name.Clear();
	}

	inline bool PixelFormatInfo::IsCompressed() const
	{
		return redType   == PixelFormatSubType_Compressed ||
		       greenType == PixelFormatSubType_Compressed ||
		       blueType  == PixelFormatSubType_Compressed ||
		       alphaType == PixelFormatSubType_Compressed;
	}

	inline bool PixelFormatInfo::IsValid() const
	{
		return bitsPerPixel != 0;
	}

	inline void PixelFormatInfo::RecomputeBitsPerPixel()
	{
		Bitset<> counter;
		counter |= redMask;
		counter |= greenMask;
		counter |= blueMask;
		counter |= alphaMask;

		bitsPerPixel = counter.Count();
	}

	inline bool PixelFormatInfo::Validate() const
	{
		if (!IsValid())
			return false;

		if (content <= PixelFormatContent_Undefined || content > PixelFormatContent_Max)
			return false;

		std::array<const Nz::Bitset<>*, 4> masks = {&redMask, &greenMask, &blueMask, &alphaMask};
		std::array<PixelFormatSubType, 4> types = {redType, greenType, blueType, alphaType};

		for (unsigned int i = 0; i < 4; ++i)
		{
			unsigned int usedBits = masks[i]->Count();
			if (usedBits == 0)
				continue;

			if (usedBits > bitsPerPixel)
				return false;

			switch (types[i])
			{
				case PixelFormatSubType_Half:
					if (usedBits != 16)
						return false;

					break;

				case PixelFormatSubType_Float:
					if (usedBits != 32)
						return false;

					break;

				default:
					break;
			}
		}

		return true;
	}

	inline std::size_t PixelFormat::ComputeSize(PixelFormatType format, unsigned int width, unsigned int height, unsigned int depth)
	{
		if (IsCompressed(format))
		{
			switch (format)
			{
				case PixelFormatType_DXT1:
				case PixelFormatType_DXT3:
				case PixelFormatType_DXT5:
					return (((width + 3) / 4) * ((height + 3) / 4) * ((format == PixelFormatType_DXT1) ? 8 : 16)) * depth;

				default:
					NazaraError("Unsupported format");
					return 0;
			}
		}
		else
			return width * height * depth * GetBytesPerPixel(format);
	}

	inline bool PixelFormat::Convert(PixelFormatType srcFormat, PixelFormatType dstFormat, const void* src, void* dst)
	{
		if (srcFormat == dstFormat)
		{
			std::memcpy(dst, src, GetBytesPerPixel(srcFormat));
			return true;
		}

		#if NAZARA_UTILITY_SAFE
		if (IsCompressed(srcFormat))
		{
			NazaraError("Cannot convert single pixel from compressed format");
			return false;
		}

		if (IsCompressed(dstFormat))
		{
			NazaraError("Cannot convert single pixel to compressed format");
			return false;
		}
		#endif

		ConvertFunction func = s_convertFunctions[srcFormat][dstFormat];
		if (!func)
		{
			NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " is not supported");
			return false;
		}

		if (!func(reinterpret_cast<const UInt8*>(src), reinterpret_cast<const UInt8*>(src) + GetBytesPerPixel(srcFormat), reinterpret_cast<UInt8*>(dst)))
		{
			NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " failed");
			return false;
		}

		return true;
	}

	inline bool PixelFormat::Convert(PixelFormatType srcFormat, PixelFormatType dstFormat, const void* start, const void* end, void* dst)
	{
		if (srcFormat == dstFormat)
		{
			std::memcpy(dst, start, reinterpret_cast<const UInt8*>(end)-reinterpret_cast<const UInt8*>(start));
			return true;
		}

		ConvertFunction func = s_convertFunctions[srcFormat][dstFormat];
		if (!func)
		{
			NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " is not supported");
			return false;
		}

		if (!func(reinterpret_cast<const UInt8*>(start), reinterpret_cast<const UInt8*>(end), reinterpret_cast<UInt8*>(dst)))
		{
			NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " failed");
			return false;
		}

		return true;
	}

	inline bool PixelFormat::Flip(PixelFlipping flipping, PixelFormatType format, unsigned int width, unsigned int height, unsigned int depth, const void* src, void* dst)
	{
		#if NAZARA_UTILITY_SAFE
		if (!IsValid(format))
		{
			NazaraError("Invalid pixel format");
			return false;
		}
		#endif

		auto it = s_flipFunctions[flipping].find(format);
		if (it != s_flipFunctions[flipping].end())
			it->second(width, height, depth, reinterpret_cast<const UInt8*>(src), reinterpret_cast<UInt8*>(dst));
		else
		{
			// Flipping générique

			#if NAZARA_UTILITY_SAFE
			if (IsCompressed(format))
			{
				NazaraError("No function to flip compressed format");
				return false;
			}
			#endif

			UInt8 bpp = GetBytesPerPixel(format);
			unsigned int lineStride = width*bpp;
			switch (flipping)
			{
				case PixelFlipping_Horizontally:
				{
					if (src == dst)
					{
						for (unsigned int z = 0; z < depth; ++z)
						{
							UInt8* ptr = reinterpret_cast<UInt8*>(dst) + width*height*z;
							for (unsigned int y = 0; y < height/2; ++y)
								std::swap_ranges(&ptr[y*lineStride], &ptr[(y+1)*lineStride-1], &ptr[(height-y-1)*lineStride]);
						}
					}
					else
					{
						for (unsigned int z = 0; z < depth; ++z)
						{
							const UInt8* srcPtr = reinterpret_cast<const UInt8*>(src);
							UInt8* dstPtr = reinterpret_cast<UInt8*>(dst) + (width-1)*height*depth*bpp;
							for (unsigned int y = 0; y < height; ++y)
							{
								std::memcpy(dstPtr, srcPtr, lineStride);

								srcPtr += lineStride;
								dstPtr -= lineStride;
							}
						}
					}
					break;
				}

				case PixelFlipping_Vertically:
				{
					if (src == dst)
					{
						for (unsigned int z = 0; z < depth; ++z)
						{
							UInt8* ptr = reinterpret_cast<UInt8*>(dst) + width*height*z;
							for (unsigned int y = 0; y < height; ++y)
							{
								for (unsigned int x = 0; x < width/2; ++x)
									std::swap_ranges(&ptr[x*bpp], &ptr[(x+1)*bpp], &ptr[(width-x)*bpp]);

								ptr += lineStride;
							}
						}
					}
					else
					{
						for (unsigned int z = 0; z < depth; ++z)
						{
							UInt8* ptr = reinterpret_cast<UInt8*>(dst) + width*height*z;
							for (unsigned int y = 0; y < height; ++y)
							{
								for (unsigned int x = 0; x < width; ++x)
									std::memcpy(&ptr[x*bpp], &ptr[(width-x)*bpp], bpp);

								ptr += lineStride;
							}
						}
					}
					break;
				}
			}
		}

		return true;
	}

	inline UInt8 PixelFormat::GetBitsPerPixel(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].bitsPerPixel;
	}

	inline UInt8 PixelFormat::GetBytesPerPixel(PixelFormatType format)
	{
		return GetBitsPerPixel(format)/8;
	}

	inline PixelFormatContent PixelFormat::GetContent(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].content;
	}

	inline const PixelFormatInfo& PixelFormat::GetInfo(PixelFormatType format)
	{
		return s_pixelFormatInfos[format];
	}

	inline const String& PixelFormat::GetName(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].name;
	}

	inline bool PixelFormat::HasAlpha(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].alphaMask.TestAny();
	}

	inline bool PixelFormat::IsCompressed(PixelFormatType format)
	{
		return s_pixelFormatInfos[format].IsCompressed();
	}

	inline bool PixelFormat::IsConversionSupported(PixelFormatType srcFormat, PixelFormatType dstFormat)
	{
		if (srcFormat == dstFormat)
			return true;

		return s_convertFunctions[srcFormat][dstFormat] != nullptr;
	}

	inline bool PixelFormat::IsValid(PixelFormatType format)
	{
		return format != PixelFormatType_Undefined;
	}

	inline void PixelFormat::SetConvertFunction(PixelFormatType srcFormat, PixelFormatType dstFormat, ConvertFunction func)
	{
		s_convertFunctions[srcFormat][dstFormat] = func;
	}

	inline void PixelFormat::SetFlipFunction(PixelFlipping flipping, PixelFormatType format, FlipFunction func)
	{
		s_flipFunctions[flipping][format] = func;
	}
}

#include <Nazara/Utility/DebugOff.hpp>
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/nacl/nacl_browsertest_util.h"

namespace {

// These tests fail on Linux ASAN bots: <http://crbug.com/161709>.
#if defined(OS_LINUX) && defined(ADDRESS_SANITIZER)
#define MAYBE_SimpleLoad DISABLED_SimpleLoad
#define MAYBE_ExitStatus DISABLED_ExitStatus
#define MAYBE_PPAPICore DISABLED_PPAPICore
#define MAYBE_ProgressEvents DISABLED_ProgressEvents
#define MAYBE_CrossOriginCORS DISABLED_CrossOriginCORS
#define MAYBE_CrossOriginFail DISABLED_CrossOriginFail
#else
#define MAYBE_SimpleLoad SimpleLoad
#define MAYBE_PPAPICore PPAPICore
#define MAYBE_ProgressEvents ProgressEvents
#define MAYBE_CrossOriginCORS CrossOriginCORS
#define MAYBE_CrossOriginFail CrossOriginFail
#if defined(OS_WIN) && !defined(NDEBUG)
// http://crbug.com/174380
#define MAYBE_ExitStatus DISABLED_ExitStatus
#else
#define MAYBE_ExitStatus ExitStatus
#endif
#endif

NACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_SimpleLoad, {
  RunLoadTest(FILE_PATH_LITERAL("nacl_load_test.html"));
})

NACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_ExitStatus, {
  RunNaClIntegrationTest(FILE_PATH_LITERAL(
      "pm_exit_status_test.html?trigger=exit0&expected_exit=0"));
  RunNaClIntegrationTest(FILE_PATH_LITERAL(
      "pm_exit_status_test.html?trigger=exit7&expected_exit=7"));
  RunNaClIntegrationTest(FILE_PATH_LITERAL(
      "pm_exit_status_test.html?trigger=exit254&expected_exit=254"));
  RunNaClIntegrationTest(FILE_PATH_LITERAL(
      "pm_exit_status_test.html?trigger=exitneg2&expected_exit=254"));
})

NACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_PPAPICore, {
  RunNaClIntegrationTest(FILE_PATH_LITERAL("ppapi_ppb_core.html"));
})

NACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_ProgressEvents, {
  RunNaClIntegrationTest(FILE_PATH_LITERAL("ppapi_progress_events.html"));
})

IN_PROC_BROWSER_TEST_F(NaClBrowserTestStatic, MAYBE_CrossOriginCORS) {
  RunLoadTest(FILE_PATH_LITERAL("cross_origin/cors.html"));
}

IN_PROC_BROWSER_TEST_F(NaClBrowserTestStatic, MAYBE_CrossOriginFail) {
  RunLoadTest(FILE_PATH_LITERAL("cross_origin/fail.html"));
}

}  // namespace anonymous
<commit_msg>NaCl: split exit status browser test into 3 smaller tests.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/nacl/nacl_browsertest_util.h"

namespace {

// These tests fail on Linux ASAN bots: <http://crbug.com/161709>.
#if defined(OS_LINUX) && defined(ADDRESS_SANITIZER)
#define MAYBE_SimpleLoad DISABLED_SimpleLoad
#define MAYBE_ExitStatus0 DISABLED_ExitStatus0
#define MAYBE_ExitStatus254 DISABLED_ExitStatus254
#define MAYBE_ExitStatusNeg2 DISABLED_ExitStatusNeg2
#define MAYBE_PPAPICore DISABLED_PPAPICore
#define MAYBE_ProgressEvents DISABLED_ProgressEvents
#define MAYBE_CrossOriginCORS DISABLED_CrossOriginCORS
#define MAYBE_CrossOriginFail DISABLED_CrossOriginFail
#else
#define MAYBE_SimpleLoad SimpleLoad
#define MAYBE_ExitStatus0 ExitStatus0
#define MAYBE_ExitStatus254 ExitStatus254
#define MAYBE_ExitStatusNeg2 ExitStatusNeg2
#define MAYBE_PPAPICore PPAPICore
#define MAYBE_ProgressEvents ProgressEvents
#define MAYBE_CrossOriginCORS CrossOriginCORS
#define MAYBE_CrossOriginFail CrossOriginFail
#endif

NACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_SimpleLoad, {
  RunLoadTest(FILE_PATH_LITERAL("nacl_load_test.html"));
})

NACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_ExitStatus0, {
  RunNaClIntegrationTest(FILE_PATH_LITERAL(
      "pm_exit_status_test.html?trigger=exit0&expected_exit=0"));
})

NACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_ExitStatus254, {
  RunNaClIntegrationTest(FILE_PATH_LITERAL(
      "pm_exit_status_test.html?trigger=exit254&expected_exit=254"));
})

NACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_ExitStatusNeg2, {
  RunNaClIntegrationTest(FILE_PATH_LITERAL(
      "pm_exit_status_test.html?trigger=exitneg2&expected_exit=254"));
})

NACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_PPAPICore, {
  RunNaClIntegrationTest(FILE_PATH_LITERAL("ppapi_ppb_core.html"));
})

NACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_ProgressEvents, {
  RunNaClIntegrationTest(FILE_PATH_LITERAL("ppapi_progress_events.html"));
})

IN_PROC_BROWSER_TEST_F(NaClBrowserTestStatic, MAYBE_CrossOriginCORS) {
  RunLoadTest(FILE_PATH_LITERAL("cross_origin/cors.html"));
}

IN_PROC_BROWSER_TEST_F(NaClBrowserTestStatic, MAYBE_CrossOriginFail) {
  RunLoadTest(FILE_PATH_LITERAL("cross_origin/fail.html"));
}

}  // namespace anonymous
<|endoftext|>