<commit_before>#include "dcplabel2imagecomponent.h"

#include <duilinearlayout.h>
#include <duigridlayout.h>
#include <duilabel.h>
#include <duibutton.h>
#include <duiimage.h>

#include <duitheme.h>

#include "dcpimageutils.h"
#include "dcpappletmetadata.h"

DcpLabel2ImageComponent::DcpLabel2ImageComponent(
                            DcpCategory *category,
                            DcpAppletMetadata * metadata,
                            Qt::Alignment alignment,
                            const QString& title,
                            QGraphicsWidget *parent):
    DcpBasicComponent(category, metadata, title, parent),
    m_Alignment(alignment)
{

//  qDebug() << "-----------------------------------  KONSTRUKTOR   " << "  DcpLabel2ImageComponent::DcpLabel2ImageComponent()";

    if (m_Alignment==Qt::AlignLeft)
        m_Type = DCPLABEL2IMAGELEFT;
    else
        m_Type = DCPLABEL2IMAGERIGHT;

    m_UpLabelText = this->metadata()->text1();
    m_DownLabelText = this->metadata()->text2();

    //dummy, must modify constructor
    m_SmallWidth = 20;    //0,1
    m_SpaceWidth = 5;     //3
    int m_ImageWidth = 115;     //4

    m_Width = m_SmallWidth*2 + m_LabelWidth + m_SpaceWidth + m_ImageWidth;

    m_Height = 100;

    m_ImageSize = 64;     //3

    createContents();
}

DcpLabel2ImageComponent::~DcpLabel2ImageComponent()
{

  //qDebug() << "-----------------------------------  DESRUKTOR    " << "  DcpLabel2ImageComponent::~DcpLabel2ImageComponent()";

    delete m_BigButton;
    delete m_TriangleButton;

    delete m_UpLabel;
    delete m_DownLabel;
    delete m_Image;
}

void DcpLabel2ImageComponent::createContents()
{

    m_BigButton = newButton(m_Width, m_Height, "BigButton");
    m_UpLabel = newLabel(m_Height/2, m_UpLabelText, "UpLabel", Qt::AlignLeft|Qt::AlignBottom);
    m_TriangleButton = newButton(16, "TriangleButton");
    m_TriangleButton->translate(0,7); //bad

  //  m_SpacerButton = newButton(5, m_Height*0.8f, "SpacerButton");

    //m_Image =  newImage(metadata()->image(), m_ImageSize, 2);
    m_Image =  newImage(metadata()->image(), m_ImageSize, 2);

    m_DownLabel = newLabel(m_Height/2, m_DownLabelText, "DownLabel", Qt::AlignLeft|Qt::AlignTop);

    initRow2(m_Height/2);

    if (m_Alignment==Qt::AlignLeft)
        initLeft();
    else
        initRight();

    connect(m_BigButton, SIGNAL(clicked()), this, SLOT(bigClicked()));

    initLayout();
}

void DcpLabel2ImageComponent::initRight()
{

    initColumn(m_SmallWidth, m_SmallWidth, m_LabelWidth, m_SpaceWidth, m_ImageWidth );

    m_GridLayout->addItem(m_BigButton, 0, 0, 2, 5, Qt::AlignLeft);

    m_GridLayout->addItem(m_TriangleButton, 0, 1, Qt::AlignCenter);

//m_GridLayout->addItem(m_SpacerButton, 0, 3, 2, 1, Qt::AlignCenter);

    m_GridLayout->addItem(m_Image, 0, 4, 2, 1, Qt::AlignCenter);

    m_GridLayout->addItem(m_UpLabel, 0, 2, Qt::AlignCenter);

    m_GridLayout->addItem(m_DownLabel, 1, 1, 1, 2, Qt::AlignCenter);

}

void DcpLabel2ImageComponent::initLeft()
{

    initColumn(m_ImageWidth, m_SpaceWidth, m_SmallWidth, m_SmallWidth, m_LabelWidth);

    m_GridLayout->addItem(m_BigButton, 0, 0, 2, 5, Qt::AlignLeft);

//m_GridLayout->addItem(m_SpacerButton, 0, 2, 2, 1, Qt::AlignCenter);

    m_GridLayout->addItem(m_TriangleButton, 0, 3, Qt::AlignCenter);

    m_GridLayout->addItem(m_Image, 0, 0, 2, 1, Qt::AlignCenter);
    m_Image->translate(15,0); // Qt::AlignCenter BUG

    m_GridLayout->addItem(m_UpLabel, 0, 4, Qt::AlignCenter);

    m_GridLayout->addItem(m_DownLabel, 1, 3, 1, 2, Qt::AlignCenter);
}
<commit_msg>bugfix grid size<commit_after>#include "dcplabel2imagecomponent.h"

#include <duilinearlayout.h>
#include <duigridlayout.h>
#include <duilabel.h>
#include <duibutton.h>
#include <duiimage.h>

#include <duitheme.h>

#include "dcpimageutils.h"
#include "dcpappletmetadata.h"

DcpLabel2ImageComponent::DcpLabel2ImageComponent(
                            DcpCategory *category,
                            DcpAppletMetadata * metadata,
                            Qt::Alignment alignment,
                            const QString& title,
                            QGraphicsWidget *parent):
    DcpBasicComponent(category, metadata, title, parent),
    m_Alignment(alignment)
{

//  qDebug() << "-----------------------------------  KONSTRUKTOR   " << "  DcpLabel2ImageComponent::DcpLabel2ImageComponent()";

    if (m_Alignment==Qt::AlignLeft)
        m_Type = DCPLABEL2IMAGELEFT;
    else
        m_Type = DCPLABEL2IMAGERIGHT;

    m_UpLabelText = this->metadata()->text1();
    m_DownLabelText = this->metadata()->text2();

    //dummy, must modify constructor
    m_SmallWidth = 20;    //0,1
    m_SpaceWidth = 5;     //3
    m_ImageWidth = 115;     //4

    m_Width = m_SmallWidth*2 + m_LabelWidth + m_SpaceWidth + m_ImageWidth;

    m_Height = 100;

    m_ImageSize = 64;     //3

    createContents();
}

DcpLabel2ImageComponent::~DcpLabel2ImageComponent()
{

  //qDebug() << "-----------------------------------  DESRUKTOR    " << "  DcpLabel2ImageComponent::~DcpLabel2ImageComponent()";

    delete m_BigButton;
    delete m_TriangleButton;

    delete m_UpLabel;
    delete m_DownLabel;
    delete m_Image;
}

void DcpLabel2ImageComponent::createContents()
{

    m_BigButton = newButton(m_Width, m_Height, "BigButton");
    m_UpLabel = newLabel(m_Height/2, m_UpLabelText, "UpLabel", Qt::AlignLeft|Qt::AlignBottom);
    m_TriangleButton = newButton(16, "TriangleButton");
    m_TriangleButton->translate(0,7); //bad

  //  m_SpacerButton = newButton(5, m_Height*0.8f, "SpacerButton");

    //m_Image =  newImage(metadata()->image(), m_ImageSize, 2);
    m_Image =  newImage(metadata()->image(), m_ImageSize, 2);

    m_DownLabel = newLabel(m_Height/2, m_DownLabelText, "DownLabel", Qt::AlignLeft|Qt::AlignTop);

    initRow2(m_Height/2);

    if (m_Alignment==Qt::AlignLeft)
        initLeft();
    else
        initRight();

    connect(m_BigButton, SIGNAL(clicked()), this, SLOT(bigClicked()));

    initLayout();
}

void DcpLabel2ImageComponent::initRight()
{

    initColumn(m_SmallWidth, m_SmallWidth, m_LabelWidth, m_SpaceWidth, m_ImageWidth );

    m_GridLayout->addItem(m_BigButton, 0, 0, 2, 5, Qt::AlignLeft);

    m_GridLayout->addItem(m_TriangleButton, 0, 1, Qt::AlignCenter);

//m_GridLayout->addItem(m_SpacerButton, 0, 3, 2, 1, Qt::AlignCenter);

    m_GridLayout->addItem(m_Image, 0, 4, 2, 1, Qt::AlignCenter);

    m_GridLayout->addItem(m_UpLabel, 0, 2, Qt::AlignCenter);

    m_GridLayout->addItem(m_DownLabel, 1, 1, 1, 2, Qt::AlignCenter);

}

void DcpLabel2ImageComponent::initLeft()
{

    initColumn(m_ImageWidth, m_SpaceWidth, m_SmallWidth, m_SmallWidth, m_LabelWidth);

    m_GridLayout->addItem(m_BigButton, 0, 0, 2, 5, Qt::AlignLeft);

//m_GridLayout->addItem(m_SpacerButton, 0, 2, 2, 1, Qt::AlignCenter);

    m_GridLayout->addItem(m_TriangleButton, 0, 3, Qt::AlignCenter);

    m_GridLayout->addItem(m_Image, 0, 0, 2, 1, Qt::AlignCenter);
    m_Image->translate(15,0); // Qt::AlignCenter BUG

    m_GridLayout->addItem(m_UpLabel, 0, 4, Qt::AlignCenter);

    m_GridLayout->addItem(m_DownLabel, 1, 3, 1, 2, Qt::AlignCenter);
}
<|endoftext|>


<commit_before>// Copyright Christian Neumller 2013. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef LUABIND_FUNCTION_CONVERTER_HPP_INCLUDED
#define LUABIND_FUNCTION_CONVERTER_HPP_INCLUDED
#include <functional>
#include <luabind/detail/deduce_signature.hpp>
#include <luabind/detail/conversion_policies/conversion_base.hpp>
#include <luabind/make_function.hpp>
#include <luabind/detail/call_function.hpp>

namespace luabind {

	template <typename R = object>
	struct function
	{
		typedef R result_type;

		function(luabind::object const& obj)
			: m_func(obj)
		{
		}

		template< typename... Args>
		R operator() ( Args&&... args )
		{
			return call_function<R>(m_func, std::forward<Args>(args)...);
		}

	private:
		object m_func;
	};

	namespace detail {

		template< typename T >
		struct is_function : public std::false_type {};

		template< typename T >
		struct is_function< std::function< T > > : public std::true_type {};

		template< typename R, typename... Args, typename WrappedType >
		struct call_types <std::function< R(Args...) >, WrappedType >
		{
			typedef meta::type_list< R, Args... > signature_type;
		};

	}

	template <typename F>
	struct default_converter<F, typename std::enable_if<detail::is_function<F>::value>::type>
	{
		typedef std::true_type is_native;

		enum { consumed_args = 1 };

		template <class U>
		void converter_postcall(lua_State*, U const&, int)
		{}

		template <class U>
		static int match(lua_State* L, U, int index)
		{
			if(lua_type(L, index)==LUA_TFUNCTION)
				return 0;
			if(luaL_getmetafield(L, index, "__call")) {
				lua_pop(L, 1);
				return 1;
			}
			return -1;
		}

		template <class U>
		F to_cpp(lua_State* L, U, int index)
		{
			// If you get a compiler error here, you are probably trying to
			// get a function pointer from Lua. This is not supported:
			// you must use a type which is constructible from a
			// luabind::function, e.g. std::function or boost::function.
			return function<typename F::result_type>(object(from_stack(L, index)));
		}

		void to_lua(lua_State* L, F value)
		{
			make_function(L, value).push(L);
		}
	};

} // namespace luabind

#endif // LUABIND_FUNCTION_CONVERTER_HPP_INCLUDED

<commit_msg>follow-up fix: function_converter was not returning the right value for non-matches.<commit_after>// Copyright Christian Neumller 2013. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef LUABIND_FUNCTION_CONVERTER_HPP_INCLUDED
#define LUABIND_FUNCTION_CONVERTER_HPP_INCLUDED
#include <functional>
#include <luabind/detail/deduce_signature.hpp>
#include <luabind/detail/conversion_policies/conversion_base.hpp>
#include <luabind/make_function.hpp>
#include <luabind/detail/call_function.hpp>

namespace luabind {

	template <typename R = object>
	struct function
	{
		typedef R result_type;

		function(luabind::object const& obj)
			: m_func(obj)
		{
		}

		template< typename... Args>
		R operator() ( Args&&... args )
		{
			return call_function<R>(m_func, std::forward<Args>(args)...);
		}

	private:
		object m_func;
	};

	namespace detail {

		template< typename T >
		struct is_function : public std::false_type {};

		template< typename T >
		struct is_function< std::function< T > > : public std::true_type {};

		template< typename R, typename... Args, typename WrappedType >
		struct call_types <std::function< R(Args...) >, WrappedType >
		{
			typedef meta::type_list< R, Args... > signature_type;
		};

	}

	template <typename F>
	struct default_converter<F, typename std::enable_if<detail::is_function<F>::value>::type>
	{
		typedef std::true_type is_native;

		enum { consumed_args = 1 };

		template <class U>
		void converter_postcall(lua_State*, U const&, int)
		{}

		template <class U>
		static int match(lua_State* L, U, int index)
		{
			if(lua_type(L, index)==LUA_TFUNCTION)
				return 0;
			if(luaL_getmetafield(L, index, "__call")) {
				lua_pop(L, 1);
				return 1;
			}
			return no_match;
		}

		template <class U>
		F to_cpp(lua_State* L, U, int index)
		{
			// If you get a compiler error here, you are probably trying to
			// get a function pointer from Lua. This is not supported:
			// you must use a type which is constructible from a
			// luabind::function, e.g. std::function or boost::function.
			return function<typename F::result_type>(object(from_stack(L, index)));
		}

		void to_lua(lua_State* L, F value)
		{
			make_function(L, value).push(L);
		}
	};

} // namespace luabind

#endif // LUABIND_FUNCTION_CONVERTER_HPP_INCLUDED

<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (c) 2019 ECL Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 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 <gtest/gtest.h>
#include <math.h>
#include <memory>
#include "EKF/ekf.h"
#include "sensor_simulator/sensor_simulator.h"

class EkfInitializationTest : public ::testing::Test {
 public:

	std::shared_ptr<Ekf> _ekf;
	SensorSimulator* _sensor_simulator;

	// Duration of initalization with only providing baro,mag and IMU
	const uint32_t _init_duration_us{2000000};	// 2s

	// Setup the Ekf with synthetic measurements
	void SetUp() override
	{
		_ekf = std::make_shared<Ekf>();
		_ekf->init(0);
		_sensor_simulator = new SensorSimulator(_ekf);

		_sensor_simulator->run(_init_duration_us);
	}

	// Use this method to clean up any memory, network etc. after each test
	void TearDown() override
	{
		delete _sensor_simulator;
	}
};

TEST_F(EkfInitializationTest, tiltAlign)
{
	// GIVEN: reasonable static sensor data for some duration
	// THEN: EKF should tilt align
	EXPECT_EQ(true,_ekf->attitude_valid());
}

TEST_F(EkfInitializationTest, initialControlMode)
{
	// GIVEN: reasonable static sensor data for some duration
	// THEN: EKF control status should be reasonable
	filter_control_status_u control_status;
	_ekf->get_control_mode(&control_status.value);

	EXPECT_EQ(1, (int) control_status.flags.tilt_align);
	EXPECT_EQ(1, (int) control_status.flags.yaw_align);
	EXPECT_EQ(0, (int) control_status.flags.gps);
	EXPECT_EQ(0, (int) control_status.flags.opt_flow);
	EXPECT_EQ(1, (int) control_status.flags.mag_hdg);
	EXPECT_EQ(0, (int) control_status.flags.mag_3D);
	EXPECT_EQ(0, (int) control_status.flags.mag_dec);
	EXPECT_EQ(0, (int) control_status.flags.in_air);
	EXPECT_EQ(0, (int) control_status.flags.wind);
	EXPECT_EQ(1, (int) control_status.flags.baro_hgt);
	EXPECT_EQ(0, (int) control_status.flags.rng_hgt);
	EXPECT_EQ(0, (int) control_status.flags.gps_hgt);
	EXPECT_EQ(0, (int) control_status.flags.ev_pos);
	EXPECT_EQ(0, (int) control_status.flags.ev_yaw);
	EXPECT_EQ(0, (int) control_status.flags.ev_hgt);
	EXPECT_EQ(0, (int) control_status.flags.fuse_beta);
	EXPECT_EQ(0, (int) control_status.flags.mag_field_disturbed);
	EXPECT_EQ(0, (int) control_status.flags.fixed_wing);
	EXPECT_EQ(0, (int) control_status.flags.mag_fault);
	EXPECT_EQ(0, (int) control_status.flags.gnd_effect);
	EXPECT_EQ(0, (int) control_status.flags.rng_stuck);
	EXPECT_EQ(0, (int) control_status.flags.gps_yaw);
	EXPECT_EQ(0, (int) control_status.flags.mag_aligned_in_flight);
	EXPECT_EQ(0, (int) control_status.flags.ev_vel);
	EXPECT_EQ(0, (int) control_status.flags.synthetic_mag_z);
}

TEST_F(EkfInitializationTest, convergesToZero)
{
	// GIVEN: initialized EKF with default IMU, baro and mag input for 2s
	// WHEN: Added more defautl sensor measurements
	_sensor_simulator->run(4000000); // for further 4s

	float converged_pos[3];
	float converged_vel[3];
	float converged_accel_bias[3];
	float converged_gyro_bias[3];
	_ekf->get_position(converged_pos);
	_ekf->get_velocity(converged_vel);
	_ekf->get_accel_bias(converged_accel_bias);
	_ekf->get_gyro_bias(converged_gyro_bias);

	// THEN: EKF should stay or converge to zero
	for(int i=0; i<3; ++i)
	{
		EXPECT_NEAR(0.0f,converged_pos[i],0.001f);
		EXPECT_NEAR(0.0f,converged_vel[i],0.001f);
		EXPECT_NEAR(0.0f,converged_accel_bias[i],0.001f);
		EXPECT_NEAR(0.0f,converged_gyro_bias[i],0.001f);
	}
}

TEST_F(EkfInitializationTest, gpsFusion)
{
	// GIVEN: initialized EKF with default IMU, baro and mag input for 2s
	// WHEN: setting GPS measurements for 11s, minimum GPS health time is set to 10 sec

	_sensor_simulator->startGps();
	_sensor_simulator->run(11000000); // for further 3s

	// THEN: EKF should fuse GPS, but no other position sensor
	filter_control_status_u control_status;
	_ekf->get_control_mode(&control_status.value);
	EXPECT_EQ(1, (int) control_status.flags.tilt_align);
	EXPECT_EQ(1, (int) control_status.flags.yaw_align);
	EXPECT_EQ(1, (int) control_status.flags.gps);
	EXPECT_EQ(0, (int) control_status.flags.opt_flow);
	EXPECT_EQ(1, (int) control_status.flags.mag_hdg);
	EXPECT_EQ(0, (int) control_status.flags.mag_3D);
	EXPECT_EQ(0, (int) control_status.flags.mag_dec);
	EXPECT_EQ(0, (int) control_status.flags.in_air);
	EXPECT_EQ(0, (int) control_status.flags.wind);
	EXPECT_EQ(1, (int) control_status.flags.baro_hgt);
	EXPECT_EQ(0, (int) control_status.flags.rng_hgt);
	EXPECT_EQ(0, (int) control_status.flags.gps_hgt);
	EXPECT_EQ(0, (int) control_status.flags.ev_pos);
	EXPECT_EQ(0, (int) control_status.flags.ev_yaw);
	EXPECT_EQ(0, (int) control_status.flags.ev_hgt);
	EXPECT_EQ(0, (int) control_status.flags.fuse_beta);
	EXPECT_EQ(0, (int) control_status.flags.mag_field_disturbed);
	EXPECT_EQ(0, (int) control_status.flags.fixed_wing);
	EXPECT_EQ(0, (int) control_status.flags.mag_fault);
	EXPECT_EQ(0, (int) control_status.flags.gnd_effect);
	EXPECT_EQ(0, (int) control_status.flags.rng_stuck);
	EXPECT_EQ(0, (int) control_status.flags.gps_yaw);
	EXPECT_EQ(0, (int) control_status.flags.mag_aligned_in_flight);
	EXPECT_EQ(0, (int) control_status.flags.ev_vel);
	EXPECT_EQ(0, (int) control_status.flags.synthetic_mag_z);
}

TEST_F(EkfInitializationTest, accleBiasEstimation)
{
	// GIVEN: initialized EKF with default IMU, baro and mag input for 2s
	// WHEN: Added more sensor measurements with accel bias and gps measurements
	Vector3f accel_bias = {0.0f,0.0f,0.1f};

	_sensor_simulator->startGps();
	_sensor_simulator->setImuBias(accel_bias, Vector3f{0.0f,0.0f,0.0f});
	_sensor_simulator->run(10000000);

	float converged_pos[3];
	float converged_vel[3];
	float converged_accel_bias[3];
	float converged_gyro_bias[3];
	_ekf->get_position(converged_pos);
	_ekf->get_velocity(converged_vel);
	_ekf->get_accel_bias(converged_accel_bias);
	_ekf->get_gyro_bias(converged_gyro_bias);

	// THEN: EKF should estimate bias correctelly
	for(int i=0; i<3; ++i)
	{
		EXPECT_NEAR(0.0f,converged_pos[i],0.001f) << "i: " << i;
		EXPECT_NEAR(0.0f,converged_vel[i],0.001f) << "i: " << i;
		EXPECT_NEAR(accel_bias(i),converged_accel_bias[i],0.001f) << "i: " << i;
		EXPECT_NEAR(0.0f,converged_gyro_bias[i],0.001f) << "i: " << i;
	}
}

// TODO: Add sampling tests
<commit_msg>make ekf a shared pointer<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2019 ECL Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 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 <gtest/gtest.h>
#include <math.h>
#include <memory>
#include "EKF/ekf.h"
#include "sensor_simulator/sensor_simulator.h"

class EkfInitializationTest : public ::testing::Test {
 public:
	EkfInitializationTest(): ::testing::Test(),
	_ekf{std::make_shared<Ekf>()},
	_sensor_simulator(_ekf) {};

	std::shared_ptr<Ekf> _ekf;
	SensorSimulator _sensor_simulator;

	// Duration of initalization with only providing baro,mag and IMU
	const uint32_t _init_duration_us{2000000};	// 2s

	// Setup the Ekf with synthetic measurements
	void SetUp() override
	{
		_ekf->init(0);
		_sensor_simulator.run(_init_duration_us);
	}

	// Use this method to clean up any memory, network etc. after each test
	void TearDown() override
	{
	}
};

TEST_F(EkfInitializationTest, tiltAlign)
{
	// GIVEN: reasonable static sensor data for some duration
	// THEN: EKF should tilt align
	EXPECT_EQ(true,_ekf->attitude_valid());
}

TEST_F(EkfInitializationTest, initialControlMode)
{
	// GIVEN: reasonable static sensor data for some duration
	// THEN: EKF control status should be reasonable
	filter_control_status_u control_status;
	_ekf->get_control_mode(&control_status.value);

	EXPECT_EQ(1, (int) control_status.flags.tilt_align);
	EXPECT_EQ(1, (int) control_status.flags.yaw_align);
	EXPECT_EQ(0, (int) control_status.flags.gps);
	EXPECT_EQ(0, (int) control_status.flags.opt_flow);
	EXPECT_EQ(1, (int) control_status.flags.mag_hdg);
	EXPECT_EQ(0, (int) control_status.flags.mag_3D);
	EXPECT_EQ(0, (int) control_status.flags.mag_dec);
	EXPECT_EQ(0, (int) control_status.flags.in_air);
	EXPECT_EQ(0, (int) control_status.flags.wind);
	EXPECT_EQ(1, (int) control_status.flags.baro_hgt);
	EXPECT_EQ(0, (int) control_status.flags.rng_hgt);
	EXPECT_EQ(0, (int) control_status.flags.gps_hgt);
	EXPECT_EQ(0, (int) control_status.flags.ev_pos);
	EXPECT_EQ(0, (int) control_status.flags.ev_yaw);
	EXPECT_EQ(0, (int) control_status.flags.ev_hgt);
	EXPECT_EQ(0, (int) control_status.flags.fuse_beta);
	EXPECT_EQ(0, (int) control_status.flags.mag_field_disturbed);
	EXPECT_EQ(0, (int) control_status.flags.fixed_wing);
	EXPECT_EQ(0, (int) control_status.flags.mag_fault);
	EXPECT_EQ(0, (int) control_status.flags.gnd_effect);
	EXPECT_EQ(0, (int) control_status.flags.rng_stuck);
	EXPECT_EQ(0, (int) control_status.flags.gps_yaw);
	EXPECT_EQ(0, (int) control_status.flags.mag_aligned_in_flight);
	EXPECT_EQ(0, (int) control_status.flags.ev_vel);
	EXPECT_EQ(0, (int) control_status.flags.synthetic_mag_z);
}

TEST_F(EkfInitializationTest, convergesToZero)
{
	// GIVEN: initialized EKF with default IMU, baro and mag input for 2s
	// WHEN: Added more defautl sensor measurements
	_sensor_simulator.run(4000000); // for further 4s

	float converged_pos[3];
	float converged_vel[3];
	float converged_accel_bias[3];
	float converged_gyro_bias[3];
	_ekf->get_position(converged_pos);
	_ekf->get_velocity(converged_vel);
	_ekf->get_accel_bias(converged_accel_bias);
	_ekf->get_gyro_bias(converged_gyro_bias);

	// THEN: EKF should stay or converge to zero
	for(int i=0; i<3; ++i)
	{
		EXPECT_NEAR(0.0f,converged_pos[i],0.001f);
		EXPECT_NEAR(0.0f,converged_vel[i],0.001f);
		EXPECT_NEAR(0.0f,converged_accel_bias[i],0.001f);
		EXPECT_NEAR(0.0f,converged_gyro_bias[i],0.001f);
	}
}

TEST_F(EkfInitializationTest, gpsFusion)
{
	// GIVEN: initialized EKF with default IMU, baro and mag input for 2s
	// WHEN: setting GPS measurements for 11s, minimum GPS health time is set to 10 sec

	_sensor_simulator.startGps();
	_sensor_simulator.run(11000000); // for further 3s

	// THEN: EKF should fuse GPS, but no other position sensor
	filter_control_status_u control_status;
	_ekf->get_control_mode(&control_status.value);
	EXPECT_EQ(1, (int) control_status.flags.tilt_align);
	EXPECT_EQ(1, (int) control_status.flags.yaw_align);
	EXPECT_EQ(1, (int) control_status.flags.gps);
	EXPECT_EQ(0, (int) control_status.flags.opt_flow);
	EXPECT_EQ(1, (int) control_status.flags.mag_hdg);
	EXPECT_EQ(0, (int) control_status.flags.mag_3D);
	EXPECT_EQ(0, (int) control_status.flags.mag_dec);
	EXPECT_EQ(0, (int) control_status.flags.in_air);
	EXPECT_EQ(0, (int) control_status.flags.wind);
	EXPECT_EQ(1, (int) control_status.flags.baro_hgt);
	EXPECT_EQ(0, (int) control_status.flags.rng_hgt);
	EXPECT_EQ(0, (int) control_status.flags.gps_hgt);
	EXPECT_EQ(0, (int) control_status.flags.ev_pos);
	EXPECT_EQ(0, (int) control_status.flags.ev_yaw);
	EXPECT_EQ(0, (int) control_status.flags.ev_hgt);
	EXPECT_EQ(0, (int) control_status.flags.fuse_beta);
	EXPECT_EQ(0, (int) control_status.flags.mag_field_disturbed);
	EXPECT_EQ(0, (int) control_status.flags.fixed_wing);
	EXPECT_EQ(0, (int) control_status.flags.mag_fault);
	EXPECT_EQ(0, (int) control_status.flags.gnd_effect);
	EXPECT_EQ(0, (int) control_status.flags.rng_stuck);
	EXPECT_EQ(0, (int) control_status.flags.gps_yaw);
	EXPECT_EQ(0, (int) control_status.flags.mag_aligned_in_flight);
	EXPECT_EQ(0, (int) control_status.flags.ev_vel);
	EXPECT_EQ(0, (int) control_status.flags.synthetic_mag_z);
}

TEST_F(EkfInitializationTest, accleBiasEstimation)
{
	// GIVEN: initialized EKF with default IMU, baro and mag input for 2s
	// WHEN: Added more sensor measurements with accel bias and gps measurements
	Vector3f accel_bias = {0.0f,0.0f,0.1f};

	_sensor_simulator.startGps();
	_sensor_simulator.setImuBias(accel_bias, Vector3f{0.0f,0.0f,0.0f});
	_sensor_simulator.run(10000000);

	float converged_pos[3];
	float converged_vel[3];
	float converged_accel_bias[3];
	float converged_gyro_bias[3];
	_ekf->get_position(converged_pos);
	_ekf->get_velocity(converged_vel);
	_ekf->get_accel_bias(converged_accel_bias);
	_ekf->get_gyro_bias(converged_gyro_bias);

	// THEN: EKF should estimate bias correctelly
	for(int i=0; i<3; ++i)
	{
		EXPECT_NEAR(0.0f,converged_pos[i],0.001f) << "i: " << i;
		EXPECT_NEAR(0.0f,converged_vel[i],0.001f) << "i: " << i;
		EXPECT_NEAR(accel_bias(i),converged_accel_bias[i],0.001f) << "i: " << i;
		EXPECT_NEAR(0.0f,converged_gyro_bias[i],0.001f) << "i: " << i;
	}
}

// TODO: Add sampling tests
<|endoftext|>


<commit_before>#include <algorithm>

#include "SpMP/CSR.hpp"

#include "CSR_Interface.h"

using namespace std;
using namespace SpMP;

// w = (alpha*A*x + beta*y + gamma)*z
template<class T, bool HAS_VALUE = true, bool HAS_Z = false>
static void SpMV_(
  int m,
  T *w,
  T alpha,
  const int *rowptr, const int *colidx, const T* values,
  const T *x,
  T beta,
  const T *y,
  T gamma,
  const T *z)
{
  assert(w != x);

  int base = rowptr[0];

  rowptr -= base;
  colidx -= base;
  if (values) values -= base;

  w -= base;
  x -= base;
  if (y) y -= base;
  if (z) z -= base;

//#define MEASURE_LOAD_BALANCE
#ifdef MEASURE_LOAD_BALANCE
  double barrierTimes[omp_get_max_threads()];
  double tBegin = omp_get_wtime();
#endif

#pragma omp parallel
  {
    int iBegin, iEnd;
    getLoadBalancedPartition(&iBegin, &iEnd, rowptr + base, m);
    iBegin += base;
    iEnd += base;

    if (1 == alpha) {
      if (0 == beta) {
        if (0 == gamma) {
          for (int i = iBegin; i < iEnd; ++i) {
            T sum = 0;
            for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
              if (HAS_VALUE) {
                sum += values[j]*x[colidx[j]];
              }
              else {
                sum += x[colidx[j]];
              }
            }
            if (HAS_Z) w[i] = z[i]*sum;
            else w[i] = sum;
          }
        }
        else {
          for (int i = iBegin; i < iEnd; ++i) {
            T sum = 0;
            for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
              if (HAS_VALUE) {
                sum += values[j]*x[colidx[j]];
              }
              else {
                sum += x[colidx[j]];
              }
            }
            sum += gamma;
            if (HAS_Z) w[i] = z[i]*sum;
            else w[i] = sum;
          }
        }
      }
      else {
        // alpha == 1 && beta != 0
        if (0 == gamma) {
          for (int i = iBegin; i < iEnd; ++i) {
            T sum = 0;
            for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
              if (HAS_VALUE) {
                sum += values[j]*x[colidx[j]];
              }
              else {
                sum += x[colidx[j]];
              }
            }
            sum += beta*y[i];
            if (HAS_Z) w[i] = z[i]*sum;
            else w[i] = sum;
          }
        }
        else {
          for (int i = iBegin; i < iEnd; ++i) {
            T sum = 0;
            for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
              if (HAS_VALUE) {
                sum += values[j]*x[colidx[j]];
              }
              else {
                sum += x[colidx[j]];
              }
            }
            sum += beta*y[i] + gamma;
            if (HAS_Z) w[i] = z[i]*sum;
            else w[i] = sum;
          }
        }
      }
    }
    else {
      // alpha != 1
      if (0 == beta) {
        if (0 == gamma) {
          for (int i = iBegin; i < iEnd; ++i) {
            T sum = 0;
            for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
              if (HAS_VALUE) {
                sum += values[j]*x[colidx[j]];
              }
              else {
                sum += x[colidx[j]];
              }
            }
            sum *= alpha;
            if (HAS_Z) w[i] = z[i]*sum;
            else w[i] = sum;
          }
        }
        else {
          for (int i = iBegin; i < iEnd; ++i) {
            T sum = 0;
            for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
              if (HAS_VALUE) {
                sum += values[j]*x[colidx[j]];
              }
              else {
                sum += x[colidx[j]];
              }
            }
            sum = alpha*sum + beta*y[i];
            if (HAS_Z) w[i] = z[i]*sum;
            else w[i] = sum;
          }
        }
      }
      else {
        // alpha != 1 && beta != 0
        if (0 == gamma) {
          for (int i = iBegin; i < iEnd; ++i) {
            T sum = 0;
            for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
              if (HAS_VALUE) {
                sum += values[j]*x[colidx[j]];
              }
              else {
                sum += x[colidx[j]];
              }
            }
            sum = alpha*sum + beta*y[i];
            if (HAS_Z) w[i] = z[i]*sum;
            else w[i] = sum;
          }
        }
        else {
          for (int i = iBegin; i < iEnd; ++i) {
            T sum = 0;
            for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
              if (HAS_VALUE) {
                sum += values[j]*x[colidx[j]];
              }
              else {
                sum += x[colidx[j]];
              }
            }
            sum = alpha*sum + beta*y[i] + gamma;
            if (HAS_Z) w[i] = z[i]*sum;
            else w[i] = sum;
          }
        }
      }
    } // alpha != 1

#ifdef MEASURE_LOAD_BALANCE
    double t = omp_get_wtime();
#pragma omp barrier
    barrierTimes[tid] = omp_get_wtime() - t;

#pragma omp barrier
#pragma omp master
    {
      double tEnd = omp_get_wtime();
      double barrierTimeSum = 0;
      for (int i = 0; i < nthreads; ++i) {
        barrierTimeSum += barrierTimes[i];
      }
      printf("%f load imbalance = %f\n", tEnd - tBegin, barrierTimeSum/(tEnd - tBegin)/nthreads);
    }
#undef MEASURE_LOAD_BALANCE
#endif // MEASURE_LOAD_BALANCE
  } // omp parallel
}

void multiplyWithVector(
  double *w,
  double alpha, const CSR *A, const double *x,
  double beta, const double *y,
  double gamma,
  const double *z)
{
  if (A->values) {
    if (z) {
      SpMV_<double, true, true>(
        A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z);
    }
    else {
      SpMV_<double, true, false>(
        A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z);
    }
  }
  else {
    if (z) {
      SpMV_<double, false, true>(
        A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z);
    }
    else {
      SpMV_<double, false, false>(
        A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z);
    }
  }
}

extern "C" {

void CSR_MultiplyWithVector(
  double *w,
  double alpha, const CSR_Handle *A, const double *x,
  double beta, const double *y,
  double gamma,
  const double *z)
{
  multiplyWithVector(w, alpha, (CSR *)A, x, beta, y, gamma, z);
}

void CSR_MultiplyWithDenseMatrix(
  double *W, int k, int wRowStride, int wColumnStride,
  double alpha, const CSR_Handle *A,
  const double *X, int xRowStride, int xColumnStride,
  double beta, const double *Y, int yRowStride, int yColumnStride,
  double gamma)
{
  ((CSR *)A)->multiplyWithDenseMatrix(
    W, k, wRowStride, wColumnStride,
    alpha,
    X, xRowStride, xColumnStride,
    beta, Y, yRowStride, yColumnStride,
    gamma);
}

} // extern "C"
<commit_msg>a bug fix<commit_after>#include <algorithm>

#include "SpMP/CSR.hpp"

#include "CSR_Interface.h"

using namespace std;
using namespace SpMP;

// w = (alpha*A*x + beta*y + gamma)*z
template<class T, bool HAS_VALUE = true, bool HAS_Z = false>
inline
static void SpMV_(
  int m,
  T *w,
  T alpha,
  const int *rowptr, const int *colidx, const T* values,
  const T *x,
  T beta,
  const T *y,
  T gamma,
  const T *z)
{
  assert(w != x);

  int base = rowptr[0];

  rowptr -= base;
  colidx -= base;
  if (values) values -= base;

  w -= base;
  x -= base;
  if (y) y -= base;
  if (z) z -= base;

//#define MEASURE_LOAD_BALANCE
#ifdef MEASURE_LOAD_BALANCE
  double barrierTimes[omp_get_max_threads()];
  double tBegin = omp_get_wtime();
#endif

#pragma omp parallel
  {
    int iBegin, iEnd;
    getLoadBalancedPartition(&iBegin, &iEnd, rowptr + base, m);
    iBegin += base;
    iEnd += base;

    if (1 == alpha) {
      if (0 == beta) {
        if (0 == gamma) {
          for (int i = iBegin; i < iEnd; ++i) {
            T sum = 0;
            for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
              if (HAS_VALUE) {
                sum += values[j]*x[colidx[j]];
              }
              else {
                sum += x[colidx[j]];
              }
            }
            if (HAS_Z) w[i] = z[i]*sum;
            else w[i] = sum;
          }
        }
        else {
          for (int i = iBegin; i < iEnd; ++i) {
            T sum = 0;
            for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
              if (HAS_VALUE) {
                sum += values[j]*x[colidx[j]];
              }
              else {
                sum += x[colidx[j]];
              }
            }
            sum += gamma;
            if (HAS_Z) w[i] = z[i]*sum;
            else w[i] = sum;
          }
        }
      }
      else {
        // alpha == 1 && beta != 0
        if (0 == gamma) {
          for (int i = iBegin; i < iEnd; ++i) {
            T sum = 0;
            for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
              if (HAS_VALUE) {
                sum += values[j]*x[colidx[j]];
              }
              else {
                sum += x[colidx[j]];
              }
            }
            sum += beta*y[i];
            if (HAS_Z) w[i] = z[i]*sum;
            else w[i] = sum;
          }
        }
        else {
          for (int i = iBegin; i < iEnd; ++i) {
            T sum = 0;
            for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
              if (HAS_VALUE) {
                sum += values[j]*x[colidx[j]];
              }
              else {
                sum += x[colidx[j]];
              }
            }
            sum += beta*y[i] + gamma;
            if (HAS_Z) w[i] = z[i]*sum;
            else w[i] = sum;
          }
        }
      }
    }
    else {
      // alpha != 1
      if (0 == beta) {
        if (0 == gamma) {
          for (int i = iBegin; i < iEnd; ++i) {
            T sum = 0;
            for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
              if (HAS_VALUE) {
                sum += values[j]*x[colidx[j]];
              }
              else {
                sum += x[colidx[j]];
              }
            }
            sum *= alpha;
            if (HAS_Z) w[i] = z[i]*sum;
            else w[i] = sum;
          }
        }
        else {
          if (HAS_Z) {
            if (HAS_VALUE) {
              for (int i = iBegin; i < iEnd; ++i) {
                T sum = 0;
                for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
                  sum += values[j]*x[colidx[j]];
                }
                w[i] = (alpha*sum + beta*y[i] + gamma)*z[i];
              }
            }
            else {
              for (int i = iBegin; i < iEnd; ++i) {
                T sum = 0;
                for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
                  sum += x[colidx[j]];
                }
                w[i] = (alpha*sum + beta*y[i] + gamma)*z[i];
              }
            }
          }
          else {
            if (HAS_VALUE) {
              for (int i = iBegin; i < iEnd; ++i) {
                T sum = 0;
                for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
                  sum += values[j]*x[colidx[j]];
                }
                w[i] = alpha*sum + beta*y[i] + gamma;
              }
            }
            else {
              for (int i = iBegin; i < iEnd; ++i) {
                T sum = 0;
                for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
                  sum += x[colidx[j]];
                }
                w[i] = alpha*sum + beta*y[i] + gamma;
              }
            }
          }
        }
      }
      else {
        // alpha != 1 && beta != 0
        if (0 == gamma) {
          for (int i = iBegin; i < iEnd; ++i) {
            T sum = 0;
            for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
              if (HAS_VALUE) {
                sum += values[j]*x[colidx[j]];
              }
              else {
                sum += x[colidx[j]];
              }
            }
            sum = alpha*sum + beta*y[i];
            if (HAS_Z) w[i] = z[i]*sum;
            else w[i] = sum;
          }
        }
        else {
          for (int i = iBegin; i < iEnd; ++i) {
            T sum = 0;
            for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) {
              if (HAS_VALUE) {
                sum += values[j]*x[colidx[j]];
              }
              else {
                sum += x[colidx[j]];
              }
            }
            sum = alpha*sum + beta*y[i] + gamma;
            if (HAS_Z) w[i] = z[i]*sum;
            else w[i] = sum;
          }
        }
      }
    } // alpha != 1

#ifdef MEASURE_LOAD_BALANCE
    double t = omp_get_wtime();
#pragma omp barrier
    barrierTimes[tid] = omp_get_wtime() - t;

#pragma omp barrier
#pragma omp master
    {
      double tEnd = omp_get_wtime();
      double barrierTimeSum = 0;
      for (int i = 0; i < nthreads; ++i) {
        barrierTimeSum += barrierTimes[i];
      }
      printf("%f load imbalance = %f\n", tEnd - tBegin, barrierTimeSum/(tEnd - tBegin)/nthreads);
    }
#undef MEASURE_LOAD_BALANCE
#endif // MEASURE_LOAD_BALANCE
  } // omp parallel
}

void multiplyWithVector(
  double *w,
  double alpha, const CSR *A, const double *x,
  double beta, const double *y,
  double gamma,
  const double *z)
{
  if (A->values) {
    if (z) {
      SpMV_<double, true, true>(
        A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z);
    }
    else {
      SpMV_<double, true, false>(
        A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z);
    }
  }
  else {
    if (z) {
      SpMV_<double, false, true>(
        A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z);
    }
    else {
      SpMV_<double, false, false>(
        A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z);
    }
  }
}

extern "C" {

void CSR_MultiplyWithVector(
  double *w,
  double alpha, const CSR_Handle *A, const double *x,
  double beta, const double *y,
  double gamma,
  const double *z)
{
  multiplyWithVector(w, alpha, (CSR *)A, x, beta, y, gamma, z);
}

void CSR_MultiplyWithDenseMatrix(
  double *W, int k, int wRowStride, int wColumnStride,
  double alpha, const CSR_Handle *A,
  const double *X, int xRowStride, int xColumnStride,
  double beta, const double *Y, int yRowStride, int yColumnStride,
  double gamma)
{
  ((CSR *)A)->multiplyWithDenseMatrix(
    W, k, wRowStride, wColumnStride,
    alpha,
    X, xRowStride, xColumnStride,
    beta, Y, yRowStride, yColumnStride,
    gamma);
}

} // extern "C"
<|endoftext|>


<commit_before>#include <BinaryTree.hpp>
#include <catch.hpp>

SCENARIO ("init", "[init]")
{
  BinaryTree<int> obj;
  REQUIRE(obj.root_() == nullptr);
}
<commit_msg>Update init.cpp<commit_after>#include <BinaryTree.hpp>
#include <catch.hpp>

SCENARIO ("init", "[init]")
{
  BinaryTree<int> obj;
  REQUIRE(obj.root_() == nullptr);
}

SCENARIO ("output to cout", "<<")
{
  BinaryTree<int> tree;
  tree.insert_node(3);
  REQUIRE( std::cout << tree );
}

SCENARIO("find_node", "[find_node]")
  {
    BinaryTree<int> obj;
    obj.insert_node(4);
    obj.insert_node(2);
    REQUIRE(obj.find_node(2, obj.root_()) != nullptr);
    REQUIRE(obj.find_node(2, obj.root_())->data == 2);
  }
<|endoftext|>


<commit_before>#include "Stack.h"
#include <catch.hpp>
using namespace std;
SCENARIO("Stack count", "[count]"){
	bool mark=false;
	stack<int> st;
	if ((st.count()==0))
	{
		mark=true;
	}
	st.push(1);
	if ((st.count()==1))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Stack push", "[push]"){
	bool mark=false;
	stack<int> st;
	st.push(1);
	if ((st.count()==1)&&(st.top()==1))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Stack pop", "[pop]"){
	bool mark=false;
	stack<int> st;
	st.push(123);
	st.pop();
	if (st.count()==0)
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Stack top", "[top]"){
	bool mark=false;
	stack<int> st;
	st.push(11);
	st.push(22);
	int v=st.top();
	if (v==22)
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Assign", "[assign]"){
	bool mark=false;
	stack<int> st;
	st.push(10);
	stack<int> st_;
	st_=st;
	std::cout << "st_.count_=" << st_.count() << std::endl;
	std::cout << "st_.top=" << st_.top() << std::endl;
	if ((st_.count()==1) && (st_.top()==10))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Copy","[copy]"){
	bool mark=false;
	stack<int> st;
	st.push(10);
	stack<int> st_=st;
	std::cout << "st_.count_=" << st_.count() << std::endl;
	std::cout << "st_.top=" << st_.top() << std::endl;
	if ((st_.count()==1) && (st_.top()==10))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Empty","[empty]"){
	bool mark=false;
	bool mark_empty,mark_full;
	stack<int> st;
	mark_empty=st.empty();
	st.push(10);
	mark_full=st.empty();
	if ((mark_empty==true) && (mark_full==false))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("threads","[TH]"){
	stack<int> st;
	st.push(1);
	st.push(2);
	st.push(3);
	std::thread t1([&st](){
		st.push(4);
		st.push(5);
	});
	std::thread t2([&st](){
		st.pop();
		st.pop();
	});
	t1.join();
	t2.join();
	REQUIRE(st.count()==3);
}
<commit_msg>Update init.cpp<commit_after>#include "Stack.h"
#include <catch.hpp>
using namespace std;
SCENARIO("Stack count", "[count]"){
	bool mark=false;
	stack<int> st;
	if ((st.count()==0))
	{
		mark=true;
	}
	st.push(1);
	if ((st.count()==1))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Stack push", "[push]"){
	bool mark=false;
	stack<int> st;
	st.push(1);
	if ((st.count()==1)&&(st.top()==1))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Stack pop", "[pop]"){
	bool mark=false;
	stack<int> st;
	st.push(123);
	st.pop();
	if (st.count()==0)
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Stack top", "[top]"){
	bool mark=false;
	stack<int> st;
	st.push(11);
	st.push(22);
	int v=st.top();
	if (v==22)
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Assign", "[assign]"){
	bool mark=false;
	stack<int> st;
	st.push(10);
	stack<int> st_;
	st_=st;
	std::cout << "st_.count_=" << st_.count() << std::endl;
	std::cout << "st_.top=" << st_.top() << std::endl;
	if ((st_.count()==1) && (st_.top()==10))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Empty","[empty]"){
	bool mark=false;
	bool mark_empty,mark_full;
	stack<int> st;
	mark_empty=st.empty();
	st.push(10);
	mark_full=st.empty();
	if ((mark_empty==true) && (mark_full==false))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("threads","[TH]"){
	stack<int> st;
	st.push(1);
	st.push(2);
	st.push(3);
	std::thread t1([&st](){
		st.push(4);
		st.push(5);
	});
	std::thread t2([&st](){
		st.pop();
		st.pop();
	});
	t1.join();
	t2.join();
	REQUIRE(st.count()==3);
}
<|endoftext|>


<commit_before>#include <vector.hpp>
#include <catch.hpp>

SCENARIO("default constructor")
{
	vector_t vector;
	REQUIRE(vector.size() == 0);
	REQUIRE(vector.capacity() == 0);
}

SCENARIO("constructor with params")
{
	vector_t vector(1);
	REQUIRE(vector.size() == 1);
	REQUIRE(vector.capacity() == 1);
	REQUIRE(vector[0] == 0);
}

SCENARIO("copy constructor")
{
	vector_t vector1(1);
	vector_t vector2(vector1);
	REQUIRE(vector1.size() == vector2.size());
	REQUIRE(vector1.capacity() == vector2.capacity());
	REQUIRE(vector1[0] == vector2[0]);
}

SCENARIO("=")
{
	vector_t vector1(1);
	vector_t vector2 = vector1;
	REQUIRE(vector1.size() == vector2.size());
	REQUIRE(vector1.capacity() == vector2.capacity());
	REQUIRE(vector1[0] == vector2[0]);
}

SCENARIO("push")
{
	vector_t vector(1);
	vector.push_back(2);
	vector.push_back(3);
	REQUIRE(vector.size() == 3);
	REQUIRE(vector.capacity() == 4);
	REQUIRE(vector[0] == 0);
	REQUIRE(vector[1] == 2);
	REQUIRE(vector[2] == 3);
}

SCENARIO("[]")
{
	vector_t vector(2);
	REQUIRE(vector.size() == 2);
	REQUIRE(vector.capacity() == 2);
	REQUIRE(vector[0] == 0);
	REQUIRE(vector[1] == 0);
}
<commit_msg>Update init.cpp<commit_after>#include <vector.hpp>
#include <catch.hpp>

SCENARIO("default constructor")
{
	vector_t vector;
	REQUIRE(vector.size() == 0);
	REQUIRE(vector.capacity() == 0);
}
SCENARIO("constructor with params")
{
	vector_t vector(1);
	REQUIRE(vector.size() == 1);
	REQUIRE(vector.capacity() == 1);
	REQUIRE(vector[0] == 0);
}
SCENARIO("copy constructor")
{
	vector_t vector1(1);
	vector_t vector2(vector1);
	REQUIRE(vector1.size() == vector2.size());
	REQUIRE(vector1.capacity() == vector2.capacity());
	REQUIRE(vector1[0] == vector2[0]);
}
SCENARIO("=")
{
	vector_t vector1(1);
	vector_t vector2 = vector1;
	REQUIRE(vector1.size() == vector2.size());
	REQUIRE(vector1.capacity() == vector2.capacity());
	REQUIRE(vector1[0] == vector2[0]);
}
SCENARIO("push")
{
	vector_t vector(1);
	vector.push_back(2);
	vector.push_back(3);
	REQUIRE(vector.size() == 3);
	REQUIRE(vector.capacity() == 4);
	REQUIRE(vector[0] == 0);
	REQUIRE(vector[1] == 2);
	REQUIRE(vector[2] == 3);
}
SCENARIO("[]")
{
	vector_t vector(2);
	REQUIRE(vector.size() == 2);
	REQUIRE(vector.capacity() == 2);
	REQUIRE(vector[0] == 0);
	REQUIRE(vector[1] == 0);
}
<|endoftext|>


<commit_before>#include <binary_search_tree.hpp>
#include <catch.hpp>

SCENARIO("default constructor")
{
	BinarySearchTree<int> bst;
	REQUIRE(bst.root() == nullptr);
	REQUIRE(bst.count() == 0);
}

SCENARIO("insertElement")
{
	BinarySearchTree<int> bst;
	bst.insert(7);
	REQUIRE(bts.value_() == 7);
	REQUIRE(bts.leftNode_() == nullptr);
	REQUIRE(bts.rightNode_() == nullptr);
}
<commit_msg>Update init.cpp<commit_after>#include <binary_search_tree.hpp>
#include <catch.hpp>

SCENARIO("default constructor")
{
	BinarySearchTree<int> bst;
	REQUIRE(bst.root() == nullptr);
	REQUIRE(bst.count() == 0);
}

SCENARIO("insertElement")
{
	BinarySearchTree<int> bst;
	bst.insert(7);
	REQUIRE(bst.value_() == 7);
	REQUIRE(bst.leftNode_() == nullptr);
	REQUIRE(bst.rightNode_() == nullptr);
}
<|endoftext|>


<commit_before>/* vim: set ts=2 expandtab: */
/**
 *       @file  test.cpp
 *      @brief
 *
 *     @author  Josh King (jheretic), jking@chambana.net
 *
 *   @internal
 *      Created  11/17/2013 06:01:11 PM
 *     Compiler  gcc/g++
 * Organization  The Open Technology Institute
 *    Copyright  Copyright (c) 2013, Josh King
 *
 * This file is part of Commotion, Copyright (c) 2013, Josh King
 *
 * Commotion is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Commotion 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Commotion.  If not, see <http://www.gnu.org/licenses/>.
 *
 * =====================================================================================
 */
extern "C" {
#include "../src/obj.h"
#include "../src/list.h"
#include "../src/tree.h"
}
#include "gtest/gtest.h"

class ListTest : public ::testing::Test
{
  protected:
    co_obj_t *List16;
    co_obj_t *List32;
    void InsertObj();
    void DeleteObj();
    void FirstLast();
    co_obj_t *TestString1;
    co_obj_t *TestString2;
    co_obj_t *TestString3;
    co_obj_t *TestString4;

    int ret;
    co_obj_t *ptr;

    ListTest()
    {
      List16 = co_list16_create();
      List32 = co_list32_create();

      TestString1 = co_bin8_create("1TESTVALUE1", 12, 0);
      TestString2 = co_bin8_create("2TESTVALUE2", 12, 0);
      TestString3 = co_bin8_create("3TESTVALUE3", 12, 0);
      TestString4 = co_bin8_create("4TESTVALUE4", 12, 0);

      ret = 0;
      ptr = NULL;
    }

    virtual void SetUp()
    {
    }

    ~ListTest()
    {
      co_obj_free(List16);
      co_obj_free(List32);
    }
};

void ListTest::InsertObj()
{
  ret = co_list_append(List16, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_list_contains(List16, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_list_append(List16, TestString2);
  ASSERT_EQ(1, ret);

  ret = co_list_contains(List16, TestString2);
  ASSERT_EQ(1, ret);

  // insert before
  ret = co_list_insert_before(List16, TestString3, TestString1);
  ASSERT_EQ(1, ret);

  ptr = co_list_get_first(List16);
  ASSERT_EQ(ptr, TestString3);

  // insert after
  ret = co_list_insert_after(List16, TestString4, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_list_contains(List16, TestString4);
  ASSERT_EQ(1, ret);

  // repeat for List32
  ret = co_list_append(List32, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_list_contains(List32, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_list_append(List32, TestString2);
  ASSERT_EQ(1, ret);

  ret = co_list_contains(List32, TestString2);
  ASSERT_EQ(1, ret);

  // insert before
  ret = co_list_insert_before(List32, TestString3, TestString1);
  ASSERT_EQ(1, ret);

  ptr = co_list_get_first(List32);
  ASSERT_EQ(ptr, TestString3);

  // insert after
  ret = co_list_insert_after(List16, TestString4, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_list_contains(List16, TestString4);
  ASSERT_EQ(1, ret);
}

void ListTest::DeleteObj()
{
  ret = co_list_append(List16, TestString1);
  ASSERT_EQ(1, ret);

  co_obj_t *ptr = co_list_delete(List16, TestString1);
  ASSERT_EQ(TestString1, ptr);

  ret = co_list_append(List16, TestString2);
  ASSERT_EQ(1, ret);

  ptr = co_list_delete(List16, TestString2);
  ASSERT_EQ(TestString2, ptr);

  // confirm deletions
  ret = co_list_contains(List16, TestString1);
  ASSERT_EQ(0, ret);

  ret = co_list_contains(List16, TestString1);
  ASSERT_EQ(0, ret);

  // repeat for List32
  ret = co_list_append(List32, TestString1);
  ASSERT_EQ(1, ret);

  ptr = co_list_delete(List32, TestString1);
  ASSERT_EQ(TestString1, ptr);

  ret = co_list_append(List32, TestString2);
  ASSERT_EQ(1, ret);

  ptr = co_list_delete(List32, TestString2);
  ASSERT_EQ(TestString2, ptr);

  // confirm deletions
  ret = co_list_contains(List32, TestString1);
  ASSERT_EQ(0, ret);

  ret = co_list_contains(List32, TestString1);
  ASSERT_EQ(0, ret);
}

void ListTest::FirstLast()
{
  ret = co_list_append(List16, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_list_append(List16, TestString2);
  ASSERT_EQ(1, ret);

  ret = co_list_append(List16, TestString3);
  ASSERT_EQ(1, ret);

  // get first node
  ptr = co_list_get_first(List16);
  ASSERT_EQ(TestString1, ptr);

  // get last node
  ptr = co_list_get_last(List16);
  ASSERT_EQ(TestString3, ptr);

  // repeat for List32
  ret = co_list_append(List32, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_list_append(List32, TestString2);
  ASSERT_EQ(1, ret);

  ret = co_list_append(List32, TestString3);
  ASSERT_EQ(1, ret);

  // get first node
  ptr = co_list_get_first(List32);
  ASSERT_EQ(TestString1, ptr);

  // get last node
  ptr = co_list_get_last(List32);
  ASSERT_EQ(TestString3, ptr);
}

TEST_F(ListTest, ListInsertTest)
{
  InsertObj();
}

TEST_F(ListTest, ListDeleteTest)
{
  DeleteObj();
}

TEST_F(ListTest, FirstLast)
{
  FirstLast();
}<commit_msg>added append/prepend tests<commit_after>/* vim: set ts=2 expandtab: */
/**
 *       @file  test.cpp
 *      @brief
 *
 *     @author  Josh King (jheretic), jking@chambana.net
 *
 *   @internal
 *      Created  11/17/2013 06:01:11 PM
 *     Compiler  gcc/g++
 * Organization  The Open Technology Institute
 *    Copyright  Copyright (c) 2013, Josh King
 *
 * This file is part of Commotion, Copyright (c) 2013, Josh King
 *
 * Commotion is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * Commotion 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Commotion.  If not, see <http://www.gnu.org/licenses/>.
 *
 * =====================================================================================
 */
extern "C" {
#include "../src/obj.h"
#include "../src/list.h"
#include "../src/tree.h"
}
#include "gtest/gtest.h"

class ListTest : public ::testing::Test
{
  protected:
    co_obj_t *List16;
    co_obj_t *List32;
    void InsertObj();
    void DeleteObj();
    void FirstLast();
    co_obj_t *TestString1;
    co_obj_t *TestString2;
    co_obj_t *TestString3;
    co_obj_t *TestString4;
    co_obj_t *TestString5;
    co_obj_t *TestString6;

    int ret;
    co_obj_t *ptr;

    ListTest()
    {
      List16 = co_list16_create();
      List32 = co_list32_create();

      TestString1 = co_bin8_create("1TESTVALUE1", 12, 0);
      TestString2 = co_bin8_create("2TESTVALUE2", 12, 0);
      TestString3 = co_bin8_create("3TESTVALUE3", 12, 0);
      TestString4 = co_bin8_create("4TESTVALUE4", 12, 0);
      TestString5 = co_bin8_create("5TESTVALUE5", 12, 0);
      TestString6 = co_bin8_create("6TESTVALUE6", 12, 0);

      ret = 0;
      ptr = NULL;
    }

    virtual void SetUp()
    {
    }

    ~ListTest()
    {
      co_obj_free(List16);
      co_obj_free(List32);
    }
};

void ListTest::InsertObj()
{
  ret = co_list_append(List16, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_list_contains(List16, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_list_append(List16, TestString2);
  ASSERT_EQ(1, ret);

  ret = co_list_contains(List16, TestString2);
  ASSERT_EQ(1, ret);

  // insert before
  ret = co_list_insert_before(List16, TestString3, TestString1);
  ASSERT_EQ(1, ret);

  ptr = co_list_get_first(List16);
  ASSERT_EQ(ptr, TestString3);

  // insert after
  ret = co_list_insert_after(List16, TestString4, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_list_contains(List16, TestString4);
  ASSERT_EQ(1, ret);

  // append
  ret = co_list_append(List16, TestString5);
  ASSERT_EQ(1, ret);

  ptr = co_list_get_last(List16);
  ASSERT_EQ(ptr, TestString5);

  // prepend
  ret = co_list_prepend(List16, TestString6);
  ASSERT_EQ(1, ret);

  ptr = co_list_get_first(List16);
  ASSERT_EQ(ptr, TestString6);

  // repeat for List32
  ret = co_list_append(List32, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_list_contains(List32, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_list_append(List32, TestString2);
  ASSERT_EQ(1, ret);

  ret = co_list_contains(List32, TestString2);
  ASSERT_EQ(1, ret);

  // insert before
  ret = co_list_insert_before(List32, TestString3, TestString1);
  ASSERT_EQ(1, ret);

  ptr = co_list_get_first(List32);
  ASSERT_EQ(ptr, TestString3);

  // insert after
  ret = co_list_insert_after(List32, TestString4, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_list_contains(List32, TestString4);
  ASSERT_EQ(1, ret);

  // append
  ret = co_list_append(List32, TestString5);
  ASSERT_EQ(1, ret);

  ptr = co_list_get_last(List32);
  ASSERT_EQ(ptr, TestString5);

  // prepend
  ret = co_list_prepend(List32, TestString6);
  ASSERT_EQ(1, ret);

  ptr = co_list_get_first(List32);
  ASSERT_EQ(ptr, TestString6);
}

void ListTest::DeleteObj()
{
  ret = co_list_append(List16, TestString1);
  ASSERT_EQ(1, ret);

  co_obj_t *ptr = co_list_delete(List16, TestString1);
  ASSERT_EQ(TestString1, ptr);

  ret = co_list_append(List16, TestString2);
  ASSERT_EQ(1, ret);

  ptr = co_list_delete(List16, TestString2);
  ASSERT_EQ(TestString2, ptr);

  // confirm deletions
  ret = co_list_contains(List16, TestString1);
  ASSERT_EQ(0, ret);

  ret = co_list_contains(List16, TestString1);
  ASSERT_EQ(0, ret);

  // repeat for List32
  ret = co_list_append(List32, TestString1);
  ASSERT_EQ(1, ret);

  ptr = co_list_delete(List32, TestString1);
  ASSERT_EQ(TestString1, ptr);

  ret = co_list_append(List32, TestString2);
  ASSERT_EQ(1, ret);

  ptr = co_list_delete(List32, TestString2);
  ASSERT_EQ(TestString2, ptr);

  // confirm deletions
  ret = co_list_contains(List32, TestString1);
  ASSERT_EQ(0, ret);

  ret = co_list_contains(List32, TestString1);
  ASSERT_EQ(0, ret);
}

void ListTest::FirstLast()
{
  ret = co_list_append(List16, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_list_append(List16, TestString2);
  ASSERT_EQ(1, ret);

  ret = co_list_append(List16, TestString3);
  ASSERT_EQ(1, ret);

  // get first node
  ptr = co_list_get_first(List16);
  ASSERT_EQ(TestString1, ptr);

  // get last node
  ptr = co_list_get_last(List16);
  ASSERT_EQ(TestString3, ptr);

  // repeat for List32
  ret = co_list_append(List32, TestString1);
  ASSERT_EQ(1, ret);

  ret = co_list_append(List32, TestString2);
  ASSERT_EQ(1, ret);

  ret = co_list_append(List32, TestString3);
  ASSERT_EQ(1, ret);

  // get first node
  ptr = co_list_get_first(List32);
  ASSERT_EQ(TestString1, ptr);

  // get last node
  ptr = co_list_get_last(List32);
  ASSERT_EQ(TestString3, ptr);
}

TEST_F(ListTest, ListInsertTest)
{
  InsertObj();
}

TEST_F(ListTest, ListDeleteTest)
{
  DeleteObj();
}

TEST_F(ListTest, FirstLast)
{
  FirstLast();
}<|endoftext|>


<commit_before>/*  This file is part of the Vc library.

    Copyright (C) 2009 Matthias Kretz <kretz@kde.org>

    Vc is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as
    published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    Vc 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 Vc.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <Vc/Vc>
#include "unittest.h"
#include <iostream>

using namespace Vc;

template<typename Vec> void checkAlignment()
{
    unsigned char i = 1;
    Vec a[10];
    unsigned long mask = VectorAlignment - 1;
    if (Vec::Size == 1 && sizeof(typename Vec::EntryType) != VectorAlignment) {
        mask = sizeof(typename Vec::EntryType) - 1;
    }
#ifdef VC_IMPL_AVX
    if (sizeof(typename Vec::EntryType) == 2) {
        mask = sizeof(Vec) - 1;
    }
#endif
    for (i = 0; i < 10; ++i) {
        VERIFY((reinterpret_cast<unsigned long>(&a[i]) & mask) == 0);
    }
    const char *data = reinterpret_cast<const char *>(&a[0]);
    for (i = 0; i < 10; ++i) {
        VERIFY(&data[i * Vec::Size * sizeof(typename Vec::EntryType)] == reinterpret_cast<const char *>(&a[i]));
    }
}

template<typename Vec> void loadArray()
{
    typedef typename Vec::EntryType T;
    typedef typename Vec::IndexType I;

    enum { count = 256 * 1024 / sizeof(T) };
    Vc::Memory<Vec, count> array;
    for (int i = 0; i < count; ++i) {
        array[i] = i;
    }

    const I indexesFromZero(IndexesFromZero);

    const Vec offsets(indexesFromZero);
    for (int i = 0; i < count; i += Vec::Size) {
        const T *const addr = &array[i];
        Vec ii(i);
        ii += offsets;

        Vec a(addr);
        COMPARE(a, ii);

        Vec b = Vec::Zero();
        b.load(addr);
        COMPARE(b, ii);
    }
}

template<typename Vec> void loadArrayShort()
{
    typedef typename Vec::EntryType T;

    enum { count = 32 * 1024 };
    Vc::Memory<Vec, count> array;
    for (int i = 0; i < count; ++i) {
        array[i] = i;
    }

    const Vec &offsets = static_cast<Vec>(ushort_v::IndexesFromZero());
    for (int i = 0; i < count; i += Vec::Size) {
        const T *const addr = &array[i];
        Vec ii(i);
        ii += offsets;

        Vec a(addr);
        COMPARE(a, ii);

        Vec b = Vec::Zero();
        b.load(addr);
        COMPARE(b, ii);
    }
}

template<typename Vec> void streamingLoad()
{
    typedef typename Vec::EntryType T;

    enum {
        count = 1024
    };
    Vc::Memory<Vec, count> data;
    data[0] = static_cast<T>(-count/2);
    for (int i = 1; i < count; ++i) {
        data[i] = data[i - 1];
        ++data[i];
    }

    Vec ref = data.firstVector();
    for (int i = 0; i < count - Vec::Size; ++i, ++ref) {
        Vec v1, v2;
        if (0 == i % Vec::Size) {
            v1 = Vec(&data[i], Vc::Streaming | Vc::Aligned);
            v2.load (&data[i], Vc::Streaming | Vc::Aligned);
        } else {
            v1 = Vec(&data[i], Vc::Streaming | Vc::Unaligned);
            v2.load (&data[i], Vc::Streaming | Vc::Unaligned);
        }
        COMPARE(v1, ref);
        COMPARE(v2, ref);
    }
}

template<typename T> struct TypeInfo;
template<> struct TypeInfo<double        > { static const char *string() { return "double"; } };
template<> struct TypeInfo<float         > { static const char *string() { return "float"; } };
template<> struct TypeInfo<int           > { static const char *string() { return "int"; } };
template<> struct TypeInfo<unsigned int  > { static const char *string() { return "uint"; } };
template<> struct TypeInfo<short         > { static const char *string() { return "short"; } };
template<> struct TypeInfo<unsigned short> { static const char *string() { return "ushort"; } };
template<> struct TypeInfo<signed char   > { static const char *string() { return "schar"; } };
template<> struct TypeInfo<unsigned char > { static const char *string() { return "uchar"; } };
template<> struct TypeInfo<double_v      > { static const char *string() { return "double_v"; } };
template<> struct TypeInfo<float_v       > { static const char *string() { return "float_v"; } };
#ifdef VC_IMPL_SSE
template<> struct TypeInfo<sfloat_v      > { static const char *string() { return "sfloat_v"; } };
#endif
template<> struct TypeInfo<int_v         > { static const char *string() { return "int_v"; } };
template<> struct TypeInfo<uint_v        > { static const char *string() { return "uint_v"; } };
template<> struct TypeInfo<short_v       > { static const char *string() { return "short_v"; } };
template<> struct TypeInfo<ushort_v      > { static const char *string() { return "ushort_v"; } };

template<typename T, typename Current = void> struct SupportedConversions { typedef void Next; };
template<> struct SupportedConversions<float, void>           { typedef double         Next; };
template<> struct SupportedConversions<float, double>         { typedef int            Next; };
template<> struct SupportedConversions<float, int>            { typedef unsigned int   Next; };
template<> struct SupportedConversions<float, unsigned int>   { typedef short          Next; };
template<> struct SupportedConversions<float, short>          { typedef unsigned short Next; };
template<> struct SupportedConversions<float, unsigned short> { typedef signed char    Next; };
template<> struct SupportedConversions<float, signed char>    { typedef unsigned char  Next; };
template<> struct SupportedConversions<float, unsigned char>  { typedef void           Next; };
template<> struct SupportedConversions<int  , void          > { typedef unsigned int   Next; };
template<> struct SupportedConversions<int  , unsigned int  > { typedef short          Next; };
template<> struct SupportedConversions<int  , short         > { typedef unsigned short Next; };
template<> struct SupportedConversions<int  , unsigned short> { typedef signed char    Next; };
template<> struct SupportedConversions<int  , signed char   > { typedef unsigned char  Next; };
template<> struct SupportedConversions<int  , unsigned char > { typedef void           Next; };
template<> struct SupportedConversions<unsigned int, void          > { typedef unsigned short Next; };
template<> struct SupportedConversions<unsigned int, unsigned short> { typedef unsigned char  Next; };
template<> struct SupportedConversions<unsigned int, unsigned char > { typedef void           Next; };
template<> struct SupportedConversions<unsigned short, void          > { typedef unsigned char  Next; };
template<> struct SupportedConversions<unsigned short, unsigned char > { typedef void           Next; };
template<> struct SupportedConversions<         short, void          > { typedef unsigned char  Next; };
template<> struct SupportedConversions<         short, unsigned char > { typedef signed char    Next; };
template<> struct SupportedConversions<         short,   signed char > { typedef void           Next; };

template<typename Vec, typename MemT> struct LoadCvt {
    static void test() {
        typedef typename Vec::EntryType VecT;
        MemT *data = Vc::malloc<MemT, Vc::AlignOnCacheline>(128);
        for (size_t i = 0; i < 128; ++i) {
            data[i] = static_cast<MemT>(i - 64);
        }

        for (size_t i = 0; i < 128 - Vec::Size + 1; ++i) {
            Vec v;
            if (i % (2 * Vec::Size) == 0) {
                v = Vec(&data[i]);
            } else if (i % Vec::Size == 0) {
                v = Vec(&data[i], Vc::Aligned);
            } else {
                v = Vec(&data[i], Vc::Unaligned);
            }
            for (size_t j = 0; j < Vec::Size; ++j) {
                COMPARE(v[j], static_cast<VecT>(data[i + j])) << " " << TypeInfo<MemT>::string();
            }
        }
        for (size_t i = 0; i < 128 - Vec::Size + 1; ++i) {
            Vec v;
            if (i % (2 * Vec::Size) == 0) {
                v.load(&data[i]);
            } else if (i % Vec::Size == 0) {
                v.load(&data[i], Vc::Aligned);
            } else {
                v.load(&data[i], Vc::Unaligned);
            }
            for (size_t j = 0; j < Vec::Size; ++j) {
                COMPARE(v[j], static_cast<VecT>(data[i + j])) << " " << TypeInfo<MemT>::string();
            }
        }
        for (size_t i = 0; i < 128 - Vec::Size + 1; ++i) {
            Vec v;
            if (i % (2 * Vec::Size) == 0) {
                v = Vec(&data[i], Vc::Streaming);
            } else if (i % Vec::Size == 0) {
                v = Vec(&data[i], Vc::Streaming | Vc::Aligned);
            } else {
                v = Vec(&data[i], Vc::Streaming | Vc::Unaligned);
            }
            for (size_t j = 0; j < Vec::Size; ++j) {
                COMPARE(v[j], static_cast<VecT>(data[i + j])) << " " << TypeInfo<MemT>::string();
            }
        }

        ADD_PASS() << "loadCvt: load " << TypeInfo<MemT>::string() << "* as " << TypeInfo<Vec>::string();
        LoadCvt<Vec, typename SupportedConversions<VecT, MemT>::Next>::test();
    }
};
template<typename Vec> struct LoadCvt<Vec, void> { static void test() {} };

template<typename Vec> void loadCvt()
{
    typedef typename Vec::EntryType T;
    LoadCvt<Vec, typename SupportedConversions<T>::Next>::test();
}

int main()
{
    runTest(checkAlignment<int_v>);
    runTest(checkAlignment<uint_v>);
    runTest(checkAlignment<float_v>);
    runTest(checkAlignment<double_v>);
    runTest(checkAlignment<short_v>);
    runTest(checkAlignment<ushort_v>);
    runTest(checkAlignment<sfloat_v>);
    runTest(loadArray<int_v>);
    runTest(loadArray<uint_v>);
    runTest(loadArray<float_v>);
    runTest(loadArray<double_v>);
    runTest(loadArray<sfloat_v>);
    runTest(loadArrayShort<short_v>);
    runTest(loadArrayShort<ushort_v>);

    testAllTypes(streamingLoad);

    testAllTypes(loadCvt);
    return 0;
}
<commit_msg>also check alignment of Vc::Memory<commit_after>/*  This file is part of the Vc library.

    Copyright (C) 2009 Matthias Kretz <kretz@kde.org>

    Vc is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as
    published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    Vc 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 Vc.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <Vc/Vc>
#include "unittest.h"
#include <iostream>

using namespace Vc;

template<typename Vec> void checkAlignment()
{
    unsigned char i = 1;
    Vec a[10];
    unsigned long mask = VectorAlignment - 1;
    if (Vec::Size == 1 && sizeof(typename Vec::EntryType) != VectorAlignment) {
        mask = sizeof(typename Vec::EntryType) - 1;
    }
#ifdef VC_IMPL_AVX
    if (sizeof(typename Vec::EntryType) == 2) {
        mask = sizeof(Vec) - 1;
    }
#endif
    for (i = 0; i < 10; ++i) {
        VERIFY((reinterpret_cast<size_t>(&a[i]) & mask) == 0);
    }
    const char *data = reinterpret_cast<const char *>(&a[0]);
    for (i = 0; i < 10; ++i) {
        VERIFY(&data[i * Vec::Size * sizeof(typename Vec::EntryType)] == reinterpret_cast<const char *>(&a[i]));
    }
}

template<typename Vec> void checkMemoryAlignment()
{
    unsigned char i = 1;
    Vc::Memory<Vec, 10> a;
    unsigned long mask = VectorAlignment - 1;
    if (Vec::Size == 1 && sizeof(typename Vec::EntryType) != VectorAlignment) {
        mask = sizeof(typename Vec::EntryType) - 1;
    }
#ifdef VC_IMPL_AVX
    if (sizeof(typename Vec::EntryType) == 2) {
        mask = sizeof(Vec) - 1;
    }
#endif
    for (i = 0; i < 10; ++i) {
        VERIFY((reinterpret_cast<size_t>(&a[i]) & mask) == 0);
    }
    const char *data = reinterpret_cast<const char *>(&a[0]);
    for (i = 0; i < 10; ++i) {
        VERIFY(&data[i * Vec::Size * sizeof(typename Vec::EntryType)] == reinterpret_cast<const char *>(&a[i]));
    }
}

template<typename Vec> void loadArray()
{
    typedef typename Vec::EntryType T;
    typedef typename Vec::IndexType I;

    enum { count = 256 * 1024 / sizeof(T) };
    Vc::Memory<Vec, count> array;
    for (int i = 0; i < count; ++i) {
        array[i] = i;
    }

    const I indexesFromZero(IndexesFromZero);

    const Vec offsets(indexesFromZero);
    for (int i = 0; i < count; i += Vec::Size) {
        const T *const addr = &array[i];
        Vec ii(i);
        ii += offsets;

        Vec a(addr);
        COMPARE(a, ii);

        Vec b = Vec::Zero();
        b.load(addr);
        COMPARE(b, ii);
    }
}

template<typename Vec> void loadArrayShort()
{
    typedef typename Vec::EntryType T;

    enum { count = 32 * 1024 };
    Vc::Memory<Vec, count> array;
    for (int i = 0; i < count; ++i) {
        array[i] = i;
    }

    const Vec &offsets = static_cast<Vec>(ushort_v::IndexesFromZero());
    for (int i = 0; i < count; i += Vec::Size) {
        const T *const addr = &array[i];
        Vec ii(i);
        ii += offsets;

        Vec a(addr);
        COMPARE(a, ii);

        Vec b = Vec::Zero();
        b.load(addr);
        COMPARE(b, ii);
    }
}

template<typename Vec> void streamingLoad()
{
    typedef typename Vec::EntryType T;

    enum {
        count = 1024
    };
    Vc::Memory<Vec, count> data;
    data[0] = static_cast<T>(-count/2);
    for (int i = 1; i < count; ++i) {
        data[i] = data[i - 1];
        ++data[i];
    }

    Vec ref = data.firstVector();
    for (int i = 0; i < count - Vec::Size; ++i, ++ref) {
        Vec v1, v2;
        if (0 == i % Vec::Size) {
            v1 = Vec(&data[i], Vc::Streaming | Vc::Aligned);
            v2.load (&data[i], Vc::Streaming | Vc::Aligned);
        } else {
            v1 = Vec(&data[i], Vc::Streaming | Vc::Unaligned);
            v2.load (&data[i], Vc::Streaming | Vc::Unaligned);
        }
        COMPARE(v1, ref);
        COMPARE(v2, ref);
    }
}

template<typename T> struct TypeInfo;
template<> struct TypeInfo<double        > { static const char *string() { return "double"; } };
template<> struct TypeInfo<float         > { static const char *string() { return "float"; } };
template<> struct TypeInfo<int           > { static const char *string() { return "int"; } };
template<> struct TypeInfo<unsigned int  > { static const char *string() { return "uint"; } };
template<> struct TypeInfo<short         > { static const char *string() { return "short"; } };
template<> struct TypeInfo<unsigned short> { static const char *string() { return "ushort"; } };
template<> struct TypeInfo<signed char   > { static const char *string() { return "schar"; } };
template<> struct TypeInfo<unsigned char > { static const char *string() { return "uchar"; } };
template<> struct TypeInfo<double_v      > { static const char *string() { return "double_v"; } };
template<> struct TypeInfo<float_v       > { static const char *string() { return "float_v"; } };
#ifdef VC_IMPL_SSE
template<> struct TypeInfo<sfloat_v      > { static const char *string() { return "sfloat_v"; } };
#endif
template<> struct TypeInfo<int_v         > { static const char *string() { return "int_v"; } };
template<> struct TypeInfo<uint_v        > { static const char *string() { return "uint_v"; } };
template<> struct TypeInfo<short_v       > { static const char *string() { return "short_v"; } };
template<> struct TypeInfo<ushort_v      > { static const char *string() { return "ushort_v"; } };

template<typename T, typename Current = void> struct SupportedConversions { typedef void Next; };
template<> struct SupportedConversions<float, void>           { typedef double         Next; };
template<> struct SupportedConversions<float, double>         { typedef int            Next; };
template<> struct SupportedConversions<float, int>            { typedef unsigned int   Next; };
template<> struct SupportedConversions<float, unsigned int>   { typedef short          Next; };
template<> struct SupportedConversions<float, short>          { typedef unsigned short Next; };
template<> struct SupportedConversions<float, unsigned short> { typedef signed char    Next; };
template<> struct SupportedConversions<float, signed char>    { typedef unsigned char  Next; };
template<> struct SupportedConversions<float, unsigned char>  { typedef void           Next; };
template<> struct SupportedConversions<int  , void          > { typedef unsigned int   Next; };
template<> struct SupportedConversions<int  , unsigned int  > { typedef short          Next; };
template<> struct SupportedConversions<int  , short         > { typedef unsigned short Next; };
template<> struct SupportedConversions<int  , unsigned short> { typedef signed char    Next; };
template<> struct SupportedConversions<int  , signed char   > { typedef unsigned char  Next; };
template<> struct SupportedConversions<int  , unsigned char > { typedef void           Next; };
template<> struct SupportedConversions<unsigned int, void          > { typedef unsigned short Next; };
template<> struct SupportedConversions<unsigned int, unsigned short> { typedef unsigned char  Next; };
template<> struct SupportedConversions<unsigned int, unsigned char > { typedef void           Next; };
template<> struct SupportedConversions<unsigned short, void          > { typedef unsigned char  Next; };
template<> struct SupportedConversions<unsigned short, unsigned char > { typedef void           Next; };
template<> struct SupportedConversions<         short, void          > { typedef unsigned char  Next; };
template<> struct SupportedConversions<         short, unsigned char > { typedef signed char    Next; };
template<> struct SupportedConversions<         short,   signed char > { typedef void           Next; };

template<typename Vec, typename MemT> struct LoadCvt {
    static void test() {
        typedef typename Vec::EntryType VecT;
        MemT *data = Vc::malloc<MemT, Vc::AlignOnCacheline>(128);
        for (size_t i = 0; i < 128; ++i) {
            data[i] = static_cast<MemT>(i - 64);
        }

        for (size_t i = 0; i < 128 - Vec::Size + 1; ++i) {
            Vec v;
            if (i % (2 * Vec::Size) == 0) {
                v = Vec(&data[i]);
            } else if (i % Vec::Size == 0) {
                v = Vec(&data[i], Vc::Aligned);
            } else {
                v = Vec(&data[i], Vc::Unaligned);
            }
            for (size_t j = 0; j < Vec::Size; ++j) {
                COMPARE(v[j], static_cast<VecT>(data[i + j])) << " " << TypeInfo<MemT>::string();
            }
        }
        for (size_t i = 0; i < 128 - Vec::Size + 1; ++i) {
            Vec v;
            if (i % (2 * Vec::Size) == 0) {
                v.load(&data[i]);
            } else if (i % Vec::Size == 0) {
                v.load(&data[i], Vc::Aligned);
            } else {
                v.load(&data[i], Vc::Unaligned);
            }
            for (size_t j = 0; j < Vec::Size; ++j) {
                COMPARE(v[j], static_cast<VecT>(data[i + j])) << " " << TypeInfo<MemT>::string();
            }
        }
        for (size_t i = 0; i < 128 - Vec::Size + 1; ++i) {
            Vec v;
            if (i % (2 * Vec::Size) == 0) {
                v = Vec(&data[i], Vc::Streaming);
            } else if (i % Vec::Size == 0) {
                v = Vec(&data[i], Vc::Streaming | Vc::Aligned);
            } else {
                v = Vec(&data[i], Vc::Streaming | Vc::Unaligned);
            }
            for (size_t j = 0; j < Vec::Size; ++j) {
                COMPARE(v[j], static_cast<VecT>(data[i + j])) << " " << TypeInfo<MemT>::string();
            }
        }

        ADD_PASS() << "loadCvt: load " << TypeInfo<MemT>::string() << "* as " << TypeInfo<Vec>::string();
        LoadCvt<Vec, typename SupportedConversions<VecT, MemT>::Next>::test();
    }
};
template<typename Vec> struct LoadCvt<Vec, void> { static void test() {} };

template<typename Vec> void loadCvt()
{
    typedef typename Vec::EntryType T;
    LoadCvt<Vec, typename SupportedConversions<T>::Next>::test();
}

int main()
{
    runTest(checkAlignment<int_v>);
    runTest(checkAlignment<uint_v>);
    runTest(checkAlignment<float_v>);
    runTest(checkAlignment<double_v>);
    runTest(checkAlignment<short_v>);
    runTest(checkAlignment<ushort_v>);
    runTest(checkAlignment<sfloat_v>);
    testAllTypes(checkMemoryAlignment);
    runTest(loadArray<int_v>);
    runTest(loadArray<uint_v>);
    runTest(loadArray<float_v>);
    runTest(loadArray<double_v>);
    runTest(loadArray<sfloat_v>);
    runTest(loadArrayShort<short_v>);
    runTest(loadArrayShort<ushort_v>);

    testAllTypes(streamingLoad);

    testAllTypes(loadCvt);
    return 0;
}
<|endoftext|>


<commit_before>/*
* Copyright (C) 2007-2013 German Aerospace Center (DLR/SC)
*
* Created: 2012-10-17 Markus Litz <Markus.Litz@dlr.de>
*
* 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 "gtest/gtest.h"
#include "CTiglLogging.h"
#include <tixi.h>

#ifdef HAVE_VLD
#include <vld.h>
#endif

// make tixi quiet
void tixiSilentMessage(MessageType , const char *, ...){}

int main(int argc, char **argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    tigl::CTiglLogging::Instance().SetTimeIdInFilenameEnabled(false);
    // disable any console logging
    tigl::CTiglLogging::Instance().SetConsoleVerbosity(TILOG_SILENT);
    tigl::CTiglLogging::Instance().LogToFile("tigltest");
    // disable tixi output
    tixiSetPrintMsgFunc(tixiSilentMessage);
    int retval = RUN_ALL_TESTS();
    tixiCleanup();
    return retval;
}
<commit_msg>Fixed build issue<commit_after>/*
* Copyright (C) 2007-2013 German Aerospace Center (DLR/SC)
*
* Created: 2012-10-17 Markus Litz <Markus.Litz@dlr.de>
*
* 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 "gtest/gtest.h"
#include "CTiglLogging.h"
#include <tixi.h>

#ifdef HAVE_VLD
#include <vld.h>
#endif

// make tixi quiet
void tixiSilentMessage(MessageType , const char *){}

int main(int argc, char **argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    tigl::CTiglLogging::Instance().SetTimeIdInFilenameEnabled(false);
    // disable any console logging
    tigl::CTiglLogging::Instance().SetConsoleVerbosity(TILOG_SILENT);
    tigl::CTiglLogging::Instance().LogToFile("tigltest");
    // disable tixi output
    tixiSetPrintMsgFunc(tixiSilentMessage);
    int retval = RUN_ALL_TESTS();
    tixiCleanup();
    return retval;
}
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program 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 General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "Sofa_test.h"

#include <SofaLoader/MeshObjLoader.h>

using namespace sofa::component::loader;

namespace sofa {

class SOFA_TestPlugin_API MeshObjLoader_test  : public ::testing::Test, public MeshObjLoader
{
public :

    /**
     * Constructor call for each test
     */
    void SetUp(){}

    /**
     * Helper function to check mesh loading.
     * Compare basic values from a mesh with given results.
     */
    void loadTest(std::string filename, int pointNb, int edgeNb, int triangleNb,  int quadNb, int polygonNb,
                  int tetraNb, int hexaNb, int normalPerVertexNb, int normalListNb, int texCoordListNb, int materialNb)
    {
        this->setFilename(sofa::helper::system::DataRepository.getFile(filename));
        this->load();
        EXPECT_EQ(pointNb, this->positions.getValue().size());
        EXPECT_EQ(edgeNb, this->edges.getValue().size());
        EXPECT_EQ(triangleNb, this->triangles.getValue().size());
        EXPECT_EQ(quadNb, this->quads.getValue().size());
        EXPECT_EQ(polygonNb, this->polygons.getValue().size());
        EXPECT_EQ(tetraNb, this->tetrahedra.getValue().size());
        EXPECT_EQ(hexaNb, this->hexahedra.getValue().size());
        EXPECT_EQ(normalPerVertexNb, this->normals.getValue().size());
        EXPECT_EQ(normalListNb, this->normalsList.getValue().size());
        EXPECT_EQ(texCoordListNb, this->texCoordsList.getValue().size());
        EXPECT_EQ(materialNb, this->materials.getValue().size());
    }

};

/** MeshObjLoader::load()
 * For a given meshes check that imported data are correct
 */
TEST_F(MeshObjLoader_test, LoadCall)
{
    //Check loader high level result
    EXPECT_FALSE(this->load());
    this->setFilename(sofa::helper::system::DataRepository.getFile("mesh/square.obj"));
    EXPECT_TRUE(this->load());

    //Use several meshes to test : edges, triangles, quads, normals, materials NUMBER
    loadTest("mesh/square.obj", 4, 4, 0,  0, 0, 0, 0, 0, 0, 0, 0);
    loadTest("mesh/dragon.obj", 1190, 0, 2564,  0, 0, 0, 0, 0, 0, 0, 0);
    loadTest("mesh/box.obj", 4, 0, 4,  0, 0, 0, 0, 4, 2, 0, 0);
    loadTest("mesh/cube.obj", 8, 0, 12,  0, 0, 0, 0, 8, 8, 0, 0);
    loadTest("mesh/caducee_base.obj", 3576, 0, 420,  3350, 0, 0, 0, 0, 0, 0, 8);
    loadTest("mesh/torus.obj", 800, 0, 1600,  0, 0, 0, 0, 0, 0, 861, 0);
}

} // namespace sofa
<commit_msg>FIX: compilation with MSVC 2010<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program 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 General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "Sofa_test.h"

#include <SofaLoader/MeshObjLoader.h>

using namespace sofa::component::loader;

namespace sofa {

class MeshObjLoader_test  : public ::testing::Test, public MeshObjLoader
{
public :

    /**
     * Constructor call for each test
     */
    void SetUp(){}

    /**
     * Helper function to check mesh loading.
     * Compare basic values from a mesh with given results.
     */
    void loadTest(std::string filename, int pointNb, int edgeNb, int triangleNb,  int quadNb, int polygonNb,
                  int tetraNb, int hexaNb, int normalPerVertexNb, int normalListNb, int texCoordListNb, int materialNb)
    {
        this->setFilename(sofa::helper::system::DataRepository.getFile(filename));
        this->load();
        EXPECT_EQ(pointNb, this->positions.getValue().size());
        EXPECT_EQ(edgeNb, this->edges.getValue().size());
        EXPECT_EQ(triangleNb, this->triangles.getValue().size());
        EXPECT_EQ(quadNb, this->quads.getValue().size());
        EXPECT_EQ(polygonNb, this->polygons.getValue().size());
        EXPECT_EQ(tetraNb, this->tetrahedra.getValue().size());
        EXPECT_EQ(hexaNb, this->hexahedra.getValue().size());
        EXPECT_EQ(normalPerVertexNb, this->normals.getValue().size());
        EXPECT_EQ(normalListNb, this->normalsList.getValue().size());
        EXPECT_EQ(texCoordListNb, this->texCoordsList.getValue().size());
        EXPECT_EQ(materialNb, this->materials.getValue().size());
    }

};

/** MeshObjLoader::load()
 * For a given meshes check that imported data are correct
 */
TEST_F(MeshObjLoader_test, LoadCall)
{
    //Check loader high level result
    EXPECT_FALSE(this->load());
    this->setFilename(sofa::helper::system::DataRepository.getFile("mesh/square.obj"));
    EXPECT_TRUE(this->load());

    //Use several meshes to test : edges, triangles, quads, normals, materials NUMBER
    loadTest("mesh/square.obj", 4, 4, 0,  0, 0, 0, 0, 0, 0, 0, 0);
    loadTest("mesh/dragon.obj", 1190, 0, 2564,  0, 0, 0, 0, 0, 0, 0, 0);
    loadTest("mesh/box.obj", 4, 0, 4,  0, 0, 0, 0, 4, 2, 0, 0);
    loadTest("mesh/cube.obj", 8, 0, 12,  0, 0, 0, 0, 8, 8, 0, 0);
    loadTest("mesh/caducee_base.obj", 3576, 0, 420,  3350, 0, 0, 0, 0, 0, 0, 8);
    loadTest("mesh/torus.obj", 800, 0, 1600,  0, 0, 0, 0, 0, 0, 861, 0);
}

} // namespace sofa
<|endoftext|>