<commit_before>//======================================================================
//-----------------------------------------------------------------------
/**
 * @file		iutest_filter_tests.cpp
 * @brief		filter 対応テスト
 *
 * @author		t.sirayanagi
 * @version		1.0
 *
 * @par			copyright
 * Copyright (C) 2012-2014, Takazumi Shirayanagi\n
 * This software is released under the new BSD License,
 * see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================

//======================================================================
// include
#include "../include/iutest.hpp"

IUTEST(Test, Fail)
{
	IUTEST_ASSERT_EQ(2, 3);
}

IUTEST(Fail, Test)
{
	IUTEST_ASSERT_EQ(2, 3);
}

IUTEST(Foo, Bar)
{
	IUTEST_ASSERT_EQ(3, 3);
}

IUTEST(Foo, Baz)
{
	IUTEST_ASSERT_EQ(3, 3);
}

IUTEST(Foo, BarFail)
{
	IUTEST_ASSERT_EQ(2, 3);
}

IUTEST(Foo, Qux)
{
	IUTEST_ASSERT_EQ(3, 3);
}

#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
	IUTEST_INIT(&argc, argv);
	{
		::iutest::IUTEST_FLAG(filter) = "*Fail*";
		const int ret = IUTEST_RUN_ALL_TESTS();

		if( ret == 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 3 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 );
#endif
#if !defined(IUTEST_USE_GTEST)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 3 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 );
#endif
	}
	{
		::iutest::IUTEST_FLAG(filter) = "-*Fail*";
		const int ret = IUTEST_RUN_ALL_TESTS();

		if( ret != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 3 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 );
#endif
#if !defined(IUTEST_USE_GTEST)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 3 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 );
#endif
	}
	{
		::iutest::IUTEST_FLAG(filter) = "Foo.Bar";
		const int ret = IUTEST_RUN_ALL_TESTS();

		if( ret != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 1 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 );
#endif
#if !defined(IUTEST_USE_GTEST)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 5 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 );
#endif
	}
	{
		::iutest::IUTEST_FLAG(filter) = "***.Bar";
		const int ret = IUTEST_RUN_ALL_TESTS();

		if( ret != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 1 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 );
#endif
#if !defined(IUTEST_USE_GTEST)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 5 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 );
#endif
	}
	{
		::iutest::IUTEST_FLAG(filter) = "???.Ba?";
		const int ret = IUTEST_RUN_ALL_TESTS();

		if( ret != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 2 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 );
#endif
#if !defined(IUTEST_USE_GTEST)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 4 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 );
#endif
	}
	{
		::iutest::IUTEST_FLAG(filter) = "Foo.Ba*-*Fail*";
		const int ret = IUTEST_RUN_ALL_TESTS();

		if( ret != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 2 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 );
#endif
#if !defined(IUTEST_USE_GTEST)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 4 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 );
#endif
	}
	{
		::iutest::IUTEST_FLAG(filter) = "Foo.Ba*:-*Fail*";
		const int ret = IUTEST_RUN_ALL_TESTS();

		if( ret == 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 4 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 );
#endif
#if !defined(IUTEST_USE_GTEST)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 2 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 );
#endif
	}
	{
		::iutest::IUTEST_FLAG(filter) = "*Baz*:*Qux*";
		const int ret = IUTEST_RUN_ALL_TESTS();

		if( ret != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 2 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 );
#endif
#if !defined(IUTEST_USE_GTEST)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 4 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 );
#endif
	}
	{
		::iutest::IUTEST_FLAG(filter) = ":::*Baz*:::::*Qux*:::";
		const int ret = IUTEST_RUN_ALL_TESTS();

		if( ret != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 2 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 );
#endif
#if !defined(IUTEST_USE_GTEST)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 4 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 );
#endif
	}
	printf("*** Successful ***\n");
	return 0;
}
<commit_msg>update r517<commit_after>//======================================================================
//-----------------------------------------------------------------------
/**
 * @file		iutest_filter_tests.cpp
 * @brief		filter 対応テスト
 *
 * @author		t.sirayanagi
 * @version		1.0
 *
 * @par			copyright
 * Copyright (C) 2012-2014, Takazumi Shirayanagi\n
 * This software is released under the new BSD License,
 * see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================

//======================================================================
// include
#include "../include/iutest.hpp"

IUTEST(Test, Fail)
{
	IUTEST_ASSERT_EQ(2, 3);
}

IUTEST(Fail, Test)
{
	IUTEST_ASSERT_EQ(2, 3);
}

IUTEST(Foo, Bar)
{
	IUTEST_ASSERT_EQ(3, 3);
}

IUTEST(Foo, Baz)
{
	IUTEST_ASSERT_EQ(3, 3);
}

IUTEST(Foo, BarFail)
{
	IUTEST_ASSERT_EQ(2, 3);
}

IUTEST(Foo, Qux)
{
	IUTEST_ASSERT_EQ(3, 3);
}

#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
	IUTEST_INIT(&argc, argv);
	{
		::iutest::IUTEST_FLAG(filter) = "*Fail*";
		const int ret = IUTEST_RUN_ALL_TESTS();

		if( ret == 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 3 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 );
#endif
#if !defined(IUTEST_USE_GTEST)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 3 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 );
#endif
	}
	{
		::iutest::IUTEST_FLAG(filter) = "-*Fail*";
		const int ret = IUTEST_RUN_ALL_TESTS();

		if( ret != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 3 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 );
#endif
#if !defined(IUTEST_USE_GTEST)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 3 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 );
#endif
	}
	{
		::iutest::IUTEST_FLAG(filter) = "Foo.Bar";
		const int ret = IUTEST_RUN_ALL_TESTS();

		if( ret != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 1 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 );
#endif
#if !defined(IUTEST_USE_GTEST)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 5 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 );
#endif
	}
	{
		::iutest::IUTEST_FLAG(filter) = "***.Bar";
		const int ret = IUTEST_RUN_ALL_TESTS();

		if( ret != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 1 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 );
#endif
#if !defined(IUTEST_USE_GTEST)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 5 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 );
#endif
	}
	{
		::iutest::IUTEST_FLAG(filter) = "???.Ba?";
		const int ret = IUTEST_RUN_ALL_TESTS();

		if( ret != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 2 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 );
#endif
#if !defined(IUTEST_USE_GTEST)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 4 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 );
#endif
	}
	{
		::iutest::IUTEST_FLAG(filter) = "Foo.Ba*-*Fail*";
		const int ret = IUTEST_RUN_ALL_TESTS();

		if( ret != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 2 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 );
#endif
#if !defined(IUTEST_USE_GTEST)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 4 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 );
#endif
	}
#if !defined(IUTEST_USE_GTEST)
	{
		::iutest::IUTEST_FLAG(filter) = "Foo.Ba*:-*Fail*";
		const int ret = IUTEST_RUN_ALL_TESTS();

		if( ret == 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 4 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 );
#endif
#if !defined(IUTEST_USE_GTEST)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 2 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 );
#endif
	}
#endif
	{
		::iutest::IUTEST_FLAG(filter) = "*Baz*:*Qux*";
		const int ret = IUTEST_RUN_ALL_TESTS();

		if( ret != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 2 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 );
#endif
#if !defined(IUTEST_USE_GTEST)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 4 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 );
#endif
	}
	{
		::iutest::IUTEST_FLAG(filter) = ":::*Baz*:::::*Qux*:::";
		const int ret = IUTEST_RUN_ALL_TESTS();

		if( ret != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_count() == 2 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == 0 );
#endif
#if !defined(IUTEST_USE_GTEST)
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->skip_test_count() == 4 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_skip_test_count() == 0 );
		IUTEST_ASSERT( ::iutest::UnitTest::GetInstance()->reportable_test_run_skipped_count() == 0 );
#endif
	}
	printf("*** Successful ***\n");
	return 0;
}
<|endoftext|>


<commit_before>/**
 * @file main.cpp
 *
 * @brief File containing main Q-Learning algorithm and all necessary associated functions to implementing this routine.
 *
 * @author Machine Learning Team 2015-2016
 * @date March, 2016
 */

#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
#include "StateSpace.h"
#include "PriorityQueue.h"
#include "State.h"
#include "encoder.h"
#include "CreateModule.h"

/**
* @brief Gives a std::string representation of a primitive type.
*
* @remark Can be used to print priority queue contents.
* @param x Primitive type such as int, double, long ...
* @return std::string conversion of param x
*/
template<typename T> std::string to_string(T x) {
	return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}

/**
 * @brief Analog to temperature variable in Boltzmann Distribution, computes 'evolution variable' of system.
 *
 * This function computes a normal distribution over the parameterised number of loop iterations in order
 * to provide a function which explores the state space dilligently initially which then decays off to the
 * optimal solution after a large number of loop iterations.
 *
 * The normal distribution used by this function is:
 *
 * \f[ a e^{-\frac{bt^2}{c}} + \epsilon \f]
 *
 * where a, b and c are scaling coefficients (see method body) and \f$\epsilon\f$ is some small offset.
 *
 * @param t Number of loop iterations.
 * @return Value of normal distribution at t loop iterations.
 */
double temperature(unsigned long t);

//function to select next action

/**
 * @brief Selects an action to perform based on experience, iterations and probabilities.
 *
 * @param a_queue A priority queue instance storing integral types with double type priorities,
 *		  represents the queue of possible actions with pre-initialised priority levels.
 * @param iterations Number of loop iterations completed.
 * @return integer corresponding to chosen action
 */
int selectAction(PriorityQueue<int, double>& a_queue, unsigned long iterations);

/**
 * @brief Updates the utility (Q-value) of the system.
 *
 * Utility (Q-Value) of the system is updated via the Temporal Difference Learning Rule given by the following equation,
 *
 * \f[ Q_{i+1} (s,a) = Q_i (s,a) + \alpha [R(s') + \gamma \underset{a}{max} Q(s',a) - Q_i (s,a)] \f]
 *
 * where Q represents the utility of a state-action pair, \f$ \alpha \f$ is the learning rate, \f$ \gamma \f$ is the discount
 * factor and \f$ max_a (Q) \f$ yields the action-maximum of the Q space. The learning rate should be set to a low value for
 * highly stochastic, asymmetric systems or a high value for a lowly stochastic, symmetric system - this value lies between 0 and 1.
 * The discount factor (also in the interval [0,1]) represents the time considerations of the learning algorithm, lower values indicate
 * "living in the moment", whilst higher values indicate "planning for the future".
 *
 * @param space Reference to StateSpace object
 * @param action Integer code to previous performed action
 * @param new_state Reference to State instance giving the new system state
 * @param old_state Reference to State instance giving the old system state
 * @param alpha Learning rate of temporal difference learning algorithm (in the interval [0,1])
 * @param gamma Discount factor applied to q-learning equation (in the interval [0,1])
 */
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma);

/**
 * @brief Program launcher!
 *
 * Contains all initialisations including setting up the StateSpace and connecting to robot via a proxy. Holds main
 * program loop to perform algorithm continuously using calls to selectAction and updateQ sequentially to update
 * utilities and choose most optimal actions to perform based on position and velocity.
 *
 * @return Program exit code
 */
int main() {
	// STUFF WE DONT UNDERSTAND, AND DONT NEED TO
	//__________________________________________________________________________________________
	//__________________________________________________________________________________________
	// Libraries to load
	std::string bodyLibName = "bodyinfo";
	std::string movementLibName = "movementtools";

	// Name of camera module in library
	std::string bodyModuleName = "BodyInfo";
	std::string movementModuleName = "MovementTools";

	// Set broker name, ip and port, finding first available port from 54000
	const std::string brokerName = "MotionTimingBroker";
	int brokerPort = qi::os::findAvailablePort(54000);
	const std::string brokerIp = "0.0.0.0";

	// Default parent port and ip
	int pport = 9559;
	std::string pip = "127.0.0.1";

	// Need this for SOAP serialisation of floats to work
	setlocale(LC_NUMERIC, "C");

	// Create a broker
	boost::shared_ptr<AL::ALBroker> broker;
	try {
		broker = AL::ALBroker::createBroker(
			brokerName,
			brokerIp,
			brokerPort,
			pip,
			pport,
			0);
	}
	// Throw error and quit if a broker could not be created
	catch (...) {
		std::cerr << "Failed to connect broker to: "
			<< pip
			<< ":"
			<< pport
			<< std::endl;
		AL::ALBrokerManager::getInstance()->killAllBroker();
		AL::ALBrokerManager::kill();

		return 1;
	}

	// Add the broker to NAOqi
	AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());
	AL::ALBrokerManager::getInstance()->addBroker(broker);

	CreateModule(movementLibName, movementModuleName, broker, false, true);
	CreateModule(bodyLibName, bodyModuleName, broker, false, true);

	AL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport);
	AL::ALProxy movementToolsProxy(movementModuleName, pip, pport);
	AL::ALMotionProxy motion(pip, pport);
	//__________________________________________________________________________________________
	//__________________________________________________________________________________________
	//END OF STUFF WE DONT UNDERSTAND, BREATHE NOW

	//learning factor
	const double alpha = 0.5;
	//discount factor
	const double gamma = 0.5;

	//seed rng
	std::srand(static_cast<unsigned int>(std::time(NULL)));

	int action_forwards = FORWARD;
	int action_backwards = BACKWARD;
	int chosen_action = action_forwards;

	//create a priority queue to copy to all the state space priority queues
	PriorityQueue<int, double> initiator_queue(MAX);
	initiator_queue.enqueueWithPriority(action_forwards, 0);
	initiator_queue.enqueueWithPriority(action_backwards, 0);

	//create encoder
	Encoder encoder;
	encoder.Calibrate();

	qi::os::msleep(5000);

	//create the state space
	StateSpace space(100, 50, M_PI * 0.25, 1.0, initiator_queue);

	//state objects
	State current_state(0, 0, FORWARD);
	State old_state(0, 0, FORWARD);

	unsigned long i = 0;
	while (true) {
		// set current state angle to angle received from encoder
		// and set current state velocity to difference in new and
		// old state angles over some time difference
		current_state.theta = M_PI * (encoder.GetAngle()) / 180;
		current_state.theta_dot = (current_state.theta - old_state.theta) / 700; //Needs actual time
		current_state.robot_state = static_cast<ROBOT_STATE>(chosen_action);

		// call updateQ function with state space, old and current states
		// and learning rate, discount factor
		updateQ(space, chosen_action, old_state, current_state, alpha, gamma);

		// set old_state to current_state
		old_state = current_state;

		// determine chosen_action for current state
		chosen_action = selectAction(space[current_state], i);

		// depending upon chosen action, call robot movement tools proxy with either
		// swingForwards or swingBackwards commands.
		(chosen_action) ? movementToolsProxy.callVoid("swingForwards") : movementToolsProxy.callVoid("swingBackwards");

		++i;
	}

	return 1;
}

double temperature(unsigned long t) {
	return 100.0*std::exp((-8.0*t*t) / (2600.0*2600.0)) + 0.1;//0.1 is an offset
}

int selectAction(PriorityQueue<int, double>& a_queue, unsigned long iterations) {

	typedef std::vector<std::pair<int, double> > VecPair ;

	//turn priority queue into a vector of pairs
	VecPair vec = a_queue.saveOrderedQueueAsVector();

    //sum for partition function
	double sum = 0.0;

	// calculate partition function by iterating over action-values
	for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
		sum += std::exp((iter->second) / temperature(iterations));
	}

	// compute Boltzmann factors for action-values and enqueue to vec
	for (VecPair::iterator iter = vec.begin(); iter < vec.end(); ++iter) {
		iter->second = std::exp(iter->second / temperature(iterations)) / sum;
	}

	// calculate cumulative probability distribution
	for (VecPair::iterator iter = vec.begin()++, end = vec.end(); iter < end; ++iter) {
        //second member of pair becomes addition of its current value
        //and that of the index before it
		iter->second += (iter-1)->second;
	}

	//generate RN between 0 and 1
	double rand_num = static_cast<double>(rand()) / RAND_MAX;

	// choose action based on random number relation to priorities within action queue
	for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
		if (rand_num < iter->second)
			return iter->first;
	}

	return -1; //note that this line should never be reached
}

void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma) {
	//oldQ value reference
	double oldQ = space[old_state].search(action).second;

	//reward given to current state
	double R = new_state.getReward();

	//optimal Q value for new state i.e. first element
	double maxQ = space[new_state].peekFront().second;

	//new Q value determined by Q learning algorithm
	double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);

	// change priority of action to new Q value
	space[old_state].changePriority(action, newQ);
}
/* OLD SELECT ACTION
int selectAction(const PriorityQueue<int, double>& a_queue, unsigned long iterations) {
	/*
	// queue to store action values
	PriorityQueue<int, double> actionQueue(MAX);
	double sum = 0.0;
	// calculate partition function by iterating over action-values
	for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(), end = a_queue.end(); iter < end; ++iter) {
		sum += std::exp((iter->second) / temperature(iterations));
	}
	// compute Boltzmann factors for action-values and enqueue to actionQueue
	for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(); iter < a_queue.end(); ++iter) {
		double priority = std::exp(iter.operator*().second / temperature(iterations)) / sum;
		actionQueue.enqueueWithPriority(iter.operator*().first, priority);
	}
	// calculate cumulative probability distribution
	for (PriorityQueue<int, double>::const_iterator it1 = actionQueue.begin()++, it2 = actionQueue.begin(), end = actionQueue.end(); it1 < end; ++it1, ++it2) {
		// change priority of it1->first data item in actionQueue to
		// sum of priorities of it1 and it2 items
		actionQueue.changePriority(it1->first, it1->second + it2->second);
	}
	//generate RN between 0 and 1
	double rand_num = static_cast<double>(rand()) / RAND_MAX;
	// choose action based on random number relation to priorities within action queue
	for (PriorityQueue<int, double>::const_iterator iter = actionQueue.begin(), end = actionQueue.end(); iter < end; ++iter) {
		if (rand_num < iter->second)
			return iter->first;
	}

	return -1; //note that this line should never be reached

	double rand_num = static_cast<double>(rand()) / RAND_MAX;

	return (rand_num > 0.5)?0:1;
}
*/
<commit_msg>renamed temperature to be more descriptive<commit_after>/**
 * @file main.cpp
 *
 * @brief File containing main Q-Learning algorithm and all necessary associated functions to implementing this routine.
 *
 * @author Machine Learning Team 2015-2016
 * @date March, 2016
 */

#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
#include "StateSpace.h"
#include "PriorityQueue.h"
#include "State.h"
#include "encoder.h"
#include "CreateModule.h"

/**
* @brief Gives a std::string representation of a primitive type.
*
* @remark Can be used to print priority queue contents.
* @param x Primitive type such as int, double, long ...
* @return std::string conversion of param x
*/
template<typename T> std::string to_string(T x) {
	return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}

/**
 * @brief Analog to temperature variable in Boltzmann Distribution, computes 'evolution variable' of system.
 *
 * This function computes a normal distribution over the parameterised number of loop iterations in order
 * to provide a function which explores the state space dilligently initially which then decays off to the
 * optimal solution after a large number of loop iterations.
 *
 * The normal distribution used by this function is:
 *
 * \f[ a e^{-\frac{bt^2}{c}} + \epsilon \f]
 *
 * where a, b and c are scaling coefficients (see method body) and \f$\epsilon\f$ is some small offset.
 *
 * @param t Number of loop iterations.
 * @return Value of normal distribution at t loop iterations.
 */
double probabilityFluxDensityCoeffieicent(unsigned long t);

//function to select next action

/**
 * @brief Selects an action to perform based on experience, iterations and probabilities.
 *
 * @param a_queue A priority queue instance storing integral types with double type priorities,
 *		  represents the queue of possible actions with pre-initialised priority levels.
 * @param iterations Number of loop iterations completed.
 * @return integer corresponding to chosen action
 */
int selectAction(PriorityQueue<int, double>& a_queue, unsigned long iterations);

/**
 * @brief Updates the utility (Q-value) of the system.
 *
 * Utility (Q-Value) of the system is updated via the Temporal Difference Learning Rule given by the following equation,
 *
 * \f[ Q_{i+1} (s,a) = Q_i (s,a) + \alpha [R(s') + \gamma \underset{a}{max} Q(s',a) - Q_i (s,a)] \f]
 *
 * where Q represents the utility of a state-action pair, \f$ \alpha \f$ is the learning rate, \f$ \gamma \f$ is the discount
 * factor and \f$ max_a (Q) \f$ yields the action-maximum of the Q space. The learning rate should be set to a low value for
 * highly stochastic, asymmetric systems or a high value for a lowly stochastic, symmetric system - this value lies between 0 and 1.
 * The discount factor (also in the interval [0,1]) represents the time considerations of the learning algorithm, lower values indicate
 * "living in the moment", whilst higher values indicate "planning for the future".
 *
 * @param space Reference to StateSpace object
 * @param action Integer code to previous performed action
 * @param new_state Reference to State instance giving the new system state
 * @param old_state Reference to State instance giving the old system state
 * @param alpha Learning rate of temporal difference learning algorithm (in the interval [0,1])
 * @param gamma Discount factor applied to q-learning equation (in the interval [0,1])
 */
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma);

/**
 * @brief Program launcher!
 *
 * Contains all initialisations including setting up the StateSpace and connecting to robot via a proxy. Holds main
 * program loop to perform algorithm continuously using calls to selectAction and updateQ sequentially to update
 * utilities and choose most optimal actions to perform based on position and velocity.
 *
 * @return Program exit code
 */
int main() {
	// STUFF WE DONT UNDERSTAND, AND DONT NEED TO
	//__________________________________________________________________________________________
	//__________________________________________________________________________________________
	// Libraries to load
	std::string bodyLibName = "bodyinfo";
	std::string movementLibName = "movementtools";

	// Name of camera module in library
	std::string bodyModuleName = "BodyInfo";
	std::string movementModuleName = "MovementTools";

	// Set broker name, ip and port, finding first available port from 54000
	const std::string brokerName = "MotionTimingBroker";
	int brokerPort = qi::os::findAvailablePort(54000);
	const std::string brokerIp = "0.0.0.0";

	// Default parent port and ip
	int pport = 9559;
	std::string pip = "127.0.0.1";

	// Need this for SOAP serialisation of floats to work
	setlocale(LC_NUMERIC, "C");

	// Create a broker
	boost::shared_ptr<AL::ALBroker> broker;
	try {
		broker = AL::ALBroker::createBroker(
			brokerName,
			brokerIp,
			brokerPort,
			pip,
			pport,
			0);
	}
	// Throw error and quit if a broker could not be created
	catch (...) {
		std::cerr << "Failed to connect broker to: "
			<< pip
			<< ":"
			<< pport
			<< std::endl;
		AL::ALBrokerManager::getInstance()->killAllBroker();
		AL::ALBrokerManager::kill();

		return 1;
	}

	// Add the broker to NAOqi
	AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());
	AL::ALBrokerManager::getInstance()->addBroker(broker);

	CreateModule(movementLibName, movementModuleName, broker, false, true);
	CreateModule(bodyLibName, bodyModuleName, broker, false, true);

	AL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport);
	AL::ALProxy movementToolsProxy(movementModuleName, pip, pport);
	AL::ALMotionProxy motion(pip, pport);
	//__________________________________________________________________________________________
	//__________________________________________________________________________________________
	//END OF STUFF WE DONT UNDERSTAND, BREATHE NOW

	//learning factor
	const double alpha = 0.5;
	//discount factor
	const double gamma = 0.5;

	//seed rng
	std::srand(static_cast<unsigned int>(std::time(NULL)));

	int action_forwards = FORWARD;
	int action_backwards = BACKWARD;
	int chosen_action = action_forwards;

	//create a priority queue to copy to all the state space priority queues
	PriorityQueue<int, double> initiator_queue(MAX);
	initiator_queue.enqueueWithPriority(action_forwards, 0);
	initiator_queue.enqueueWithPriority(action_backwards, 0);

	//create encoder
	Encoder encoder;
	encoder.Calibrate();

	qi::os::msleep(5000);

	//create the state space
	StateSpace space(100, 50, M_PI * 0.25, 1.0, initiator_queue);

	//state objects
	State current_state(0, 0, FORWARD);
	State old_state(0, 0, FORWARD);

	unsigned long i = 0;
	while (true) {
		// set current state angle to angle received from encoder
		// and set current state velocity to difference in new and
		// old state angles over some time difference
		current_state.theta = M_PI * (encoder.GetAngle()) / 180;
		current_state.theta_dot = (current_state.theta - old_state.theta) / 700; //Needs actual time
		current_state.robot_state = static_cast<ROBOT_STATE>(chosen_action);

		// call updateQ function with state space, old and current states
		// and learning rate, discount factor
		updateQ(space, chosen_action, old_state, current_state, alpha, gamma);

		// set old_state to current_state
		old_state = current_state;

		// determine chosen_action for current state
		chosen_action = selectAction(space[current_state], i);

		// depending upon chosen action, call robot movement tools proxy with either
		// swingForwards or swingBackwards commands.
		(chosen_action) ? movementToolsProxy.callVoid("swingForwards") : movementToolsProxy.callVoid("swingBackwards");

		++i;
	}

	return 1;
}

double probabilityFluxDensityCoeffieicent(unsigned long t) {
	return 100.0*std::exp((-8.0*t*t) / (2600.0*2600.0)) + 0.1;//0.1 is an offset
}

int selectAction(PriorityQueue<int, double>& a_queue, unsigned long iterations) {

	typedef std::vector<std::pair<int, double> > VecPair ;

	//turn priority queue into a vector of pairs
	VecPair vec = a_queue.saveOrderedQueueAsVector();

    //sum for partition function
	double sum = 0.0;

	// calculate partition function by iterating over action-values
	for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
		sum += std::exp((iter->second) / probabilityFluxDensityCoeffieicent(iterations));
	}

	// compute Boltzmann factors for action-values and enqueue to vec
	for (VecPair::iterator iter = vec.begin(); iter < vec.end(); ++iter) {
		iter->second = std::exp(iter->second / probabilityFluxDensityCoeffieicent(iterations)) / sum;
	}

	// calculate cumulative probability distribution
	for (VecPair::iterator iter = vec.begin()++, end = vec.end(); iter < end; ++iter) {
        //second member of pair becomes addition of its current value
        //and that of the index before it
		iter->second += (iter-1)->second;
	}

	//generate RN between 0 and 1
	double rand_num = static_cast<double>(rand()) / RAND_MAX;

	// choose action based on random number relation to priorities within action queue
	for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
		if (rand_num < iter->second)
			return iter->first;
	}

	return -1; //note that this line should never be reached
}

void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma) {
	//oldQ value reference
	double oldQ = space[old_state].search(action).second;

	//reward given to current state
	double R = new_state.getReward();

	//optimal Q value for new state i.e. first element
	double maxQ = space[new_state].peekFront().second;

	//new Q value determined by Q learning algorithm
	double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);

	// change priority of action to new Q value
	space[old_state].changePriority(action, newQ);
}
/* OLD SELECT ACTION
int selectAction(const PriorityQueue<int, double>& a_queue, unsigned long iterations) {
	/*
	// queue to store action values
	PriorityQueue<int, double> actionQueue(MAX);
	double sum = 0.0;
	// calculate partition function by iterating over action-values
	for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(), end = a_queue.end(); iter < end; ++iter) {
		sum += std::exp((iter->second) / temperature(iterations));
	}
	// compute Boltzmann factors for action-values and enqueue to actionQueue
	for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(); iter < a_queue.end(); ++iter) {
		double priority = std::exp(iter.operator*().second / temperature(iterations)) / sum;
		actionQueue.enqueueWithPriority(iter.operator*().first, priority);
	}
	// calculate cumulative probability distribution
	for (PriorityQueue<int, double>::const_iterator it1 = actionQueue.begin()++, it2 = actionQueue.begin(), end = actionQueue.end(); it1 < end; ++it1, ++it2) {
		// change priority of it1->first data item in actionQueue to
		// sum of priorities of it1 and it2 items
		actionQueue.changePriority(it1->first, it1->second + it2->second);
	}
	//generate RN between 0 and 1
	double rand_num = static_cast<double>(rand()) / RAND_MAX;
	// choose action based on random number relation to priorities within action queue
	for (PriorityQueue<int, double>::const_iterator iter = actionQueue.begin(), end = actionQueue.end(); iter < end; ++iter) {
		if (rand_num < iter->second)
			return iter->first;
	}

	return -1; //note that this line should never be reached

	double rand_num = static_cast<double>(rand()) / RAND_MAX;

	return (rand_num > 0.5)?0:1;
}
*/
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
 *
 * 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.
 *
 */

// CLASS HEADER
#include "geometry-api.h"

// EXTERNAL INCLUDES
#include <dali/public-api/object/type-registry.h>

// INTERNAL INCLUDES
#include <v8-utils.h>
#include <rendering/geometry-wrapper.h>
#include <object/property-buffer-api.h>

namespace Dali
{

namespace V8Plugin
{

/**
 * ## Geometry API
 *
 * Geometry is handle to an object that can be used to define a geometric elements.
 *
 * @class Geometry
 * @extends Handle
 */

Geometry GeometryApi::GetGeometry( v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args )
{
  v8::HandleScope handleScope( isolate );

  v8::Local<v8::Object> object = args.This();
  v8::Local<v8::External> field = v8::Local<v8::External>::Cast( object->GetInternalField(0) );
  void* ptr = field->Value();

  GeometryWrapper* wrapper = static_cast< GeometryWrapper *>(ptr);
  return wrapper->GetGeometry();
}

Geometry GeometryApi::GetGeometryFromParams( int paramIndex,
                                             bool& found,
                                             v8::Isolate* isolate,
                                             const v8::FunctionCallbackInfo< v8::Value >& args )
{
  found = false;

  v8::HandleScope handleScope( isolate );
  BaseWrappedObject* wrappedObject = V8Utils::GetWrappedDaliObjectParameter( paramIndex, BaseWrappedObject::GEOMETRY, isolate, args );
  if( wrappedObject )
  {
    found = true;
    GeometryWrapper* wrapper = static_cast< GeometryWrapper *>(wrappedObject);
    return wrapper->GetGeometry();
  }
  else
  {
    return Geometry();
  }
}

/**
 * Create a new geometry object.
 *
 * @constructor
 * @method Geometry
 * @for Geometry
 * @return {Object} Geometry
 */
Geometry GeometryApi::New( const v8::FunctionCallbackInfo< v8::Value >& args )
{
  return Geometry::New();
}

/**
 * Add a PropertyBuffer to be used as source of geometry vertices
 *
 * @method addVertexBuffer
 * @for Geometry
 * @param {Object} vertexBuffer PropertyBuffer to be used as source of geometry vertices
 * @return {interger} Index of the newly added buffer, can be used with RemoveVertexBuffer
 *                    to remove this buffer if no longer required
 * @example
 *```
 *    var vertexFormat ={ "aPosition" : dali.PROPERTY_VECTOR2 };
 *    var vertexData = [    0,     1,
 *                      -0.95,  0.31,
 *                      -0.59, -0.81,
 *                       0.59, -0.81,
 *                       0.95,  0.31];
 *
 *    var vertexDataArray = new Float32Array(vertexData.length);
 *    vertexDataArray.set(vertexData, 0);
 *    var vertices = new dali.PropertyBuffer(vertexFormat, 5);
 *    vertices.setData(vertexDataArray);
 *
 *    var geometry = new dali.Geometry();
 *    geometry.addVertexBuffer( vertices );
 *```
 */
void GeometryApi::AddVertexBuffer( const v8::FunctionCallbackInfo< v8::Value >& args )
{
  v8::Isolate* isolate = args.GetIsolate();
  v8::HandleScope handleScope( isolate );

  Geometry geometry = GetGeometry( isolate, args );

  bool found( false );
  PropertyBuffer vertexBuffer = PropertyBufferApi::GetPropertyBufferFromParams( 0, found, isolate, args );
  if( !found )
  {
    DALI_SCRIPT_EXCEPTION( isolate, "invalid property buffer parameter" );
  }
  else
  {
    args.GetReturnValue().Set( v8::Integer::New( isolate, geometry.AddVertexBuffer(vertexBuffer) ) );
  }
}

/**
 * Retrieve the number of vertex buffers that have been added to this geometry
 *
 * @method getNumberOfVertexBuffers
 * @for Geometry
 * @return {integer} Number of vertex buffers that have been added to this geometry
 */
void GeometryApi::GetNumberOfVertexBuffers( const v8::FunctionCallbackInfo<v8::Value>& args )
{
  v8::Isolate* isolate = args.GetIsolate();
  v8::HandleScope handleScope( isolate );

  Geometry geometry = GetGeometry( isolate, args );

  args.GetReturnValue().Set( v8::Integer::New( isolate, geometry.GetNumberOfVertexBuffers() ) );
}

/**
 * Remove a vertex buffer
 *
 * @method removeVertexBuffer
 * @for Geometry
 * @param {integer} index Index to the vertex buffer to remove,
 *                  which must be between 0 and getNumberOfVertexBuffers()
 */
void GeometryApi::RemoveVertexBuffer( const v8::FunctionCallbackInfo< v8::Value >& args )
{
  v8::Isolate* isolate = args.GetIsolate();
  v8::HandleScope handleScope( isolate );

  Geometry geometry = GetGeometry( isolate, args );

  bool found( false );
  int index = V8Utils::GetIntegerParameter( PARAMETER_0, found, isolate, args, 0 /* default */);
  if( !found )
  {
    DALI_SCRIPT_EXCEPTION( isolate, "missing index from param 0" );
  }
  else
  {
    geometry.RemoveVertexBuffer(static_cast<std::size_t>(index));
  }
}

/**
 * Set a PropertyBuffer to be used as a source of indices for the geometry
 *
 * This buffer is required to have exactly one component and it must be of the
 * type dali.PROPERTY_INTEGER
 *
 * By setting this buffer it will cause the geometry to be rendered using indices.
 * To unset call SetIndexBuffer with an empty handle.
 *
 * @method setIndexBuffer
 * @for Geometry
 * @param {Uint32Array} data The data that will be copied to the buffer
 *
 * @example
 * var indexData = [0, 1, 1, 2, 2, 3, 3, 4, 4, 0];
 * var indexDataArray = new Uint32Array(indexData.length);
 * indexDataArray.set(indexData, 0);
 *
 * geometry.SetIndexBuffer( indexDataArray, indexDataArray.length );
 *```
 */
void GeometryApi::SetIndexBuffer( const v8::FunctionCallbackInfo<v8::Value>& args )
{
  v8::Isolate* isolate = args.GetIsolate();
  v8::HandleScope handleScope( isolate );

  Geometry geometry = GetGeometry( isolate, args );

  bool found( false );
  void* data = V8Utils::GetArrayBufferViewParameter( PARAMETER_0, found, isolate, args);

  if( ! found )
  {
    DALI_SCRIPT_EXCEPTION( isolate, "invalid data parameter" );
  }
  else
  {
    int size = V8Utils::GetIntegerParameter( PARAMETER_1, found, isolate, args, 0);
    if( !found )
    {
      DALI_SCRIPT_EXCEPTION( isolate, "missing buffer size from param 1" );
    }
    else
    {
      geometry.SetIndexBuffer( static_cast<const unsigned short*>(data), size );
    }
  }
}

/**
 * Set the type of primitives this geometry contains
 *
 * @method setGeometryType
 * @for Geometry
 * @param {integer} geometryType Type of primitives this geometry contains
 * @example
 *      // geometry type is one of the following
 *      dali.GEOMETRY_POINTS
 *      dali.GEOMETRY_LINES
 *      dali.GEOMETRY_LINE_LOOP
 *      dali.GEOMETRY_LINE_STRIP
 *      dali.GEOMETRY_TRIANGLES
 *      dali.GEOMETRY_TRIANGLE_FAN
 *      dali.GEOMETRY_TRIANGLE_STRIP
 *
 *      geometry.SetGeometryType( dali.GEOMETRY_LINES );
 */
void GeometryApi::SetGeometryType( const v8::FunctionCallbackInfo< v8::Value >& args )
{
  v8::Isolate* isolate = args.GetIsolate();
  v8::HandleScope handleScope( isolate );

  Geometry geometry = GetGeometry( isolate, args );

  bool found( false );
  int geometryType = V8Utils::GetIntegerParameter( PARAMETER_0, found, isolate, args, 0 /* default */);
  if( !found )
  {
    DALI_SCRIPT_EXCEPTION( isolate, "missing geometryType from param 0" );
  }
  else
  {
    geometry.SetGeometryType(static_cast<Geometry::GeometryType>(geometryType));
  }
}

/**
 * Get the type of primitives this geometry contains
 *
 * @method getGeometryType
 * @for Geometry
 * @return {integer} Type of primitives this geometry contains
 * @example
 *      // returns one of the following
 *      dali.GEOMETRY_POINTS
 *      dali.GEOMETRY_LINES
 *      dali.GEOMETRY_LINE_LOOP
 *      dali.GEOMETRY_LINE_STRIP
 *      dali.GEOMETRY_TRIANGLES
 *      dali.GEOMETRY_TRIANGLE_FAN
 *      dali.GEOMETRY_TRIANGLE_STRIP
 */
void GeometryApi::GetGeometryType( const v8::FunctionCallbackInfo< v8::Value >& args )
{
  v8::Isolate* isolate = args.GetIsolate();
  v8::HandleScope handleScope( isolate );

  Geometry geometry = GetGeometry( isolate, args );

  args.GetReturnValue().Set( v8::Integer::New( isolate, geometry.GetGeometryType() ) );
}

} // namespace V8Plugin

} // namespace Dali
<commit_msg>Fixed bug in SetIndexBuffer for v8 plugin<commit_after>/*
 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
 *
 * 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.
 *
 */

// CLASS HEADER
#include "geometry-api.h"

// EXTERNAL INCLUDES
#include <dali/public-api/object/type-registry.h>

// INTERNAL INCLUDES
#include <v8-utils.h>
#include <rendering/geometry-wrapper.h>
#include <object/property-buffer-api.h>

namespace Dali
{

namespace V8Plugin
{

/**
 * ## Geometry API
 *
 * Geometry is handle to an object that can be used to define a geometric elements.
 *
 * @class Geometry
 * @extends Handle
 */

Geometry GeometryApi::GetGeometry( v8::Isolate* isolate, const v8::FunctionCallbackInfo< v8::Value >& args )
{
  v8::HandleScope handleScope( isolate );

  v8::Local<v8::Object> object = args.This();
  v8::Local<v8::External> field = v8::Local<v8::External>::Cast( object->GetInternalField(0) );
  void* ptr = field->Value();

  GeometryWrapper* wrapper = static_cast< GeometryWrapper *>(ptr);
  return wrapper->GetGeometry();
}

Geometry GeometryApi::GetGeometryFromParams( int paramIndex,
                                             bool& found,
                                             v8::Isolate* isolate,
                                             const v8::FunctionCallbackInfo< v8::Value >& args )
{
  found = false;

  v8::HandleScope handleScope( isolate );
  BaseWrappedObject* wrappedObject = V8Utils::GetWrappedDaliObjectParameter( paramIndex, BaseWrappedObject::GEOMETRY, isolate, args );
  if( wrappedObject )
  {
    found = true;
    GeometryWrapper* wrapper = static_cast< GeometryWrapper *>(wrappedObject);
    return wrapper->GetGeometry();
  }
  else
  {
    return Geometry();
  }
}

/**
 * Create a new geometry object.
 *
 * @constructor
 * @method Geometry
 * @for Geometry
 * @return {Object} Geometry
 */
Geometry GeometryApi::New( const v8::FunctionCallbackInfo< v8::Value >& args )
{
  return Geometry::New();
}

/**
 * Add a PropertyBuffer to be used as source of geometry vertices
 *
 * @method addVertexBuffer
 * @for Geometry
 * @param {Object} vertexBuffer PropertyBuffer to be used as source of geometry vertices
 * @return {interger} Index of the newly added buffer, can be used with RemoveVertexBuffer
 *                    to remove this buffer if no longer required
 * @example
 *```
 *    var vertexFormat ={ "aPosition" : dali.PROPERTY_VECTOR2 };
 *    var vertexData = [    0,     1,
 *                      -0.95,  0.31,
 *                      -0.59, -0.81,
 *                       0.59, -0.81,
 *                       0.95,  0.31];
 *
 *    var vertexDataArray = new Float32Array(vertexData.length);
 *    vertexDataArray.set(vertexData, 0);
 *    var vertices = new dali.PropertyBuffer(vertexFormat, 5);
 *    vertices.setData(vertexDataArray);
 *
 *    var geometry = new dali.Geometry();
 *    geometry.addVertexBuffer( vertices );
 *```
 */
void GeometryApi::AddVertexBuffer( const v8::FunctionCallbackInfo< v8::Value >& args )
{
  v8::Isolate* isolate = args.GetIsolate();
  v8::HandleScope handleScope( isolate );

  Geometry geometry = GetGeometry( isolate, args );

  bool found( false );
  PropertyBuffer vertexBuffer = PropertyBufferApi::GetPropertyBufferFromParams( 0, found, isolate, args );
  if( !found )
  {
    DALI_SCRIPT_EXCEPTION( isolate, "invalid property buffer parameter" );
  }
  else
  {
    args.GetReturnValue().Set( v8::Integer::New( isolate, geometry.AddVertexBuffer(vertexBuffer) ) );
  }
}

/**
 * Retrieve the number of vertex buffers that have been added to this geometry
 *
 * @method getNumberOfVertexBuffers
 * @for Geometry
 * @return {integer} Number of vertex buffers that have been added to this geometry
 */
void GeometryApi::GetNumberOfVertexBuffers( const v8::FunctionCallbackInfo<v8::Value>& args )
{
  v8::Isolate* isolate = args.GetIsolate();
  v8::HandleScope handleScope( isolate );

  Geometry geometry = GetGeometry( isolate, args );

  args.GetReturnValue().Set( v8::Integer::New( isolate, geometry.GetNumberOfVertexBuffers() ) );
}

/**
 * Remove a vertex buffer
 *
 * @method removeVertexBuffer
 * @for Geometry
 * @param {integer} index Index to the vertex buffer to remove,
 *                  which must be between 0 and getNumberOfVertexBuffers()
 */
void GeometryApi::RemoveVertexBuffer( const v8::FunctionCallbackInfo< v8::Value >& args )
{
  v8::Isolate* isolate = args.GetIsolate();
  v8::HandleScope handleScope( isolate );

  Geometry geometry = GetGeometry( isolate, args );

  bool found( false );
  int index = V8Utils::GetIntegerParameter( PARAMETER_0, found, isolate, args, 0 /* default */);
  if( !found )
  {
    DALI_SCRIPT_EXCEPTION( isolate, "missing index from param 0" );
  }
  else
  {
    geometry.RemoveVertexBuffer(static_cast<std::size_t>(index));
  }
}

/**
 * Set a PropertyBuffer to be used as a source of indices for the geometry
 *
 * This buffer is required to have exactly one component and it must be of the
 * type dali.PROPERTY_INTEGER
 *
 * By setting this buffer it will cause the geometry to be rendered using indices.
 * To unset call SetIndexBuffer with an empty handle.
 *
 * @method setIndexBuffer
 * @for Geometry
 * @param {Uint32Array} data The data that will be copied to the buffer
 *
 * @example
 * var indexData = [0, 1, 1, 2, 2, 3, 3, 4, 4, 0];
 * var indexDataArray = new Uint32Array(indexData.length);
 * indexDataArray.set(indexData, 0);
 *
 * geometry.SetIndexBuffer( indexDataArray, indexDataArray.length );
 *```
 */
void GeometryApi::SetIndexBuffer( const v8::FunctionCallbackInfo<v8::Value>& args )
{
  v8::Isolate* isolate = args.GetIsolate();
  v8::HandleScope handleScope( isolate );

  Geometry geometry = GetGeometry( isolate, args );

  bool found( false );
  void* data = V8Utils::GetArrayBufferViewParameter( PARAMETER_0, found, isolate, args);

  if( ! found )
  {
    DALI_SCRIPT_EXCEPTION( isolate, "invalid data parameter" );
  }
  else
  {
    unsigned int size = V8Utils::GetIntegerParameter( PARAMETER_1, found, isolate, args, 0);
    if( !found )
    {
      DALI_SCRIPT_EXCEPTION( isolate, "missing buffer size from param 1" );
    }
    else
    {
      Dali::Vector<unsigned short> indices;
      indices.Resize( size );
      unsigned int* indexData = static_cast<unsigned int*>(data);
      for( size_t i(0); i<size; ++i )
      {
        indices[i] = indexData[i];
      }
      geometry.SetIndexBuffer( &indices[0], size );
    }
  }
}

/**
 * Set the type of primitives this geometry contains
 *
 * @method setGeometryType
 * @for Geometry
 * @param {integer} geometryType Type of primitives this geometry contains
 * @example
 *      // geometry type is one of the following
 *      dali.GEOMETRY_POINTS
 *      dali.GEOMETRY_LINES
 *      dali.GEOMETRY_LINE_LOOP
 *      dali.GEOMETRY_LINE_STRIP
 *      dali.GEOMETRY_TRIANGLES
 *      dali.GEOMETRY_TRIANGLE_FAN
 *      dali.GEOMETRY_TRIANGLE_STRIP
 *
 *      geometry.SetGeometryType( dali.GEOMETRY_LINES );
 */
void GeometryApi::SetGeometryType( const v8::FunctionCallbackInfo< v8::Value >& args )
{
  v8::Isolate* isolate = args.GetIsolate();
  v8::HandleScope handleScope( isolate );

  Geometry geometry = GetGeometry( isolate, args );

  bool found( false );
  int geometryType = V8Utils::GetIntegerParameter( PARAMETER_0, found, isolate, args, 0 /* default */);
  if( !found )
  {
    DALI_SCRIPT_EXCEPTION( isolate, "missing geometryType from param 0" );
  }
  else
  {
    geometry.SetGeometryType(static_cast<Geometry::GeometryType>(geometryType));
  }
}

/**
 * Get the type of primitives this geometry contains
 *
 * @method getGeometryType
 * @for Geometry
 * @return {integer} Type of primitives this geometry contains
 * @example
 *      // returns one of the following
 *      dali.GEOMETRY_POINTS
 *      dali.GEOMETRY_LINES
 *      dali.GEOMETRY_LINE_LOOP
 *      dali.GEOMETRY_LINE_STRIP
 *      dali.GEOMETRY_TRIANGLES
 *      dali.GEOMETRY_TRIANGLE_FAN
 *      dali.GEOMETRY_TRIANGLE_STRIP
 */
void GeometryApi::GetGeometryType( const v8::FunctionCallbackInfo< v8::Value >& args )
{
  v8::Isolate* isolate = args.GetIsolate();
  v8::HandleScope handleScope( isolate );

  Geometry geometry = GetGeometry( isolate, args );

  args.GetReturnValue().Set( v8::Integer::New( isolate, geometry.GetGeometryType() ) );
}

} // namespace V8Plugin

} // namespace Dali
<|endoftext|>


<commit_before>#include <BALL/VIEW/RENDERING/RENDERERS/rtfactRenderer.h>
#include <RTfact/Config/Init.inc.cpp>
//#include <RTfact/Utils/Packets/Detail/Constants.inc.cpp>

#include <BALL/STRUCTURE/triangulatedSurface.h>
#include <BALL/VIEW/PRIMITIVES/sphere.h>
#include <BALL/VIEW/PRIMITIVES/twoColoredTube.h>

using namespace RTfact::Remote;

namespace BALL
{
	namespace VIEW
	{
		bool RTfactRenderer::init(const Scene& scene)
				throw()
		{
			scene_ = &scene;

			using RTfact::Triangle;
			using RTfact::Vec3f;
			using RTfact::Remote::GroupHandle;
			using RTfact::Remote::GeoHandle;
			using RTfact::Transform;
			using RTfact::Remote::float3;

			GroupHandle root = m_renderer.getRoot();
			TriangleVector faces;
			Triangle t(Vec3f<1>(0,0,0),Vec3f<1>(1,0,0),Vec3f<1>(1,1,0));
			t.texCoords[0] = std::make_pair(0.f,0.f);
			t.texCoords[1] = std::make_pair(0.f,512.f);
			t.texCoords[2] = std::make_pair(512.f,0.f);
			faces.push_back(t);

			for(TriangleVector::iterator it = faces.begin(); it != faces.end(); it++)
			{
				it->normals[0]=it->normal;
				it->normals[1]=it->normal;
				it->normals[2]=it->normal;
			}

			GeoHandle geo1 = m_renderer.createGeometry(faces);
			GroupHandle topGroup = m_renderer.createGroup(Transform::identity());
			topGroup->add(geo1);

			root->add(topGroup);

			RTfact::Remote::RTAppearanceHandle mat1 = m_renderer.createAppearance("PhongShader");
			mat1->setParam("diffuseColor", float3(1.0, 1.0, 0));
			mat1->setParam("ambientIntensity", float3(.7, .7, .7));

			geo1->setAppearance(mat1);

			m_renderer.setCameraPosition(
					float3(-1.48978, 4.14466, 11.4965),
					float3(0.864694, -0.481748, 0.142207),
					float3(0, 1, 0));

			//root->setTransform(Transform::rotationY(0.2f));
			//root->add(geo2);
			m_renderer.createAccelStruct();

			// prepare the sphere template
			TriangulatedSphere sphere_template;
			sphere_template.icosaeder();
			sphere_template.refine(3, true);

			sphere_template.exportSurface(sphere_template_);

			// prepare the tube template
			TriangulatedSurface* tube_template = TriangulatedSurface::createTube(18, 0, false, true);
			tube_template->exportSurface(tube_template_);
			delete (tube_template);

			return true;
		}

		void RTfactRenderer::prepareBufferedRendering(const Stage& stage)
		{
			Camera  const& camera = stage.getCamera();
			Vector3 const& position = camera.getViewPoint();
			Vector3 const& view_vector = camera.getViewVector();
			Vector3 const& look_up = camera.getLookUpVector();

			m_renderer.setCameraPosition(float3(position.x, position.y, position.z),
																	 float3(view_vector.x, view_vector.y, view_vector.z),
																	 float3(look_up.x, look_up.y, look_up.z));

			Size num_lights = lights_.size();

			Vector3 direction, light_position;
			Size current_light=0;
			List<LightSource>::ConstIterator it = stage.getLightSources().begin();
			for (; it != stage.getLightSources().end(); ++it, ++current_light)
			{
				if (current_light >= num_lights)
				{
					RTfact::Remote::RTLightHandle light;
					switch (it->getType())
					{
						case LightSource::DIRECTIONAL:
							light = m_renderer.createLight("DirectionalLight");
							break;
						case LightSource::POSITIONAL:
							light = m_renderer.createLight("PointLight");
							break;
						default:
							std::cerr << "Light source type not supported!" << std::endl;
							break;
					}
					lights_.push_back(light);
				}
				switch (it->getType())
				{
					case LightSource::DIRECTIONAL:
						direction = it->getDirection();
						if (it->isRelativeToCamera())
							direction = stage.calculateAbsoluteCoordinates(direction);

						lights_[current_light]->setParam("direction", float3(direction.x, direction.y, direction.z));
						break;
					case LightSource::POSITIONAL:
						light_position = it->getPosition();
						if (it->isRelativeToCamera())
						{
							light_position = stage.calculateAbsoluteCoordinates(it->getPosition())+stage.getCamera().getViewPoint();
						}
						lights_[current_light]->setParam("position", float3(light_position.x, light_position.y, light_position.z));
						break;
					default:
						std::cerr << "Light source type not supported!" << std::endl;
						break;
				}
				float intensity = it->getIntensity()*500;
				ColorRGBA const& color = it->getColor();

				lights_[current_light]->setParam("intensity", float3((float)color.getRed()*intensity,(float)color.getGreen()*intensity,(float)color.getBlue()*intensity));
			}
		}

		void RTfactRenderer::renderToBufferImpl(FrameBufferPtr buffer)
		{
			bool recreate_accel = false;
			RepresentationManager& pm = scene_->getMainControl()->getRepresentationManager();

			RepresentationList::ConstIterator it = pm.getRepresentations().begin();
			for (; it != pm.getRepresentations().end(); ++it)
			{
				Representation const* rep = *it;
				if (rep->isHidden()) continue;

				List<GeometricObject*>::ConstIterator it;
				for (it =  rep->getGeometricObjects().begin();
						it != rep->getGeometricObjects().end();
						it++)
				{
					if (objects_.find(*it) == objects_.end())
					{
						recreate_accel = true;
						objects_.insert(*it);
						if (RTTI::isKindOf<Mesh>(**it))
						{
							Mesh const& mesh = *(const Mesh*)*it;

							float const* vertices = reinterpret_cast<float const*>(&(mesh.vertex[0]));
							float const* normals  = reinterpret_cast<float const*>(&(mesh.normal[0]));
							Index const* indices = reinterpret_cast<Index const*>(&(mesh.triangle[0]));

							RTAppearanceHandle material = m_renderer.createAppearance("PhongShader");
							material->setParam("ambientIntensity", float3(0.25, 0.25, 0.25));
							material->setParam("specularColor", float3(0.774597, 0.774597, 0.774597));
							material->setParam("shininess", (float)76.8);

							GeoHandle handle;

							float const* colors = 0;
							if (mesh.colors.size() > 1)
							{
								colors  = reinterpret_cast<float const*>(&(mesh.colors[0]));
								material->setParam("useVertexColor", true);

							 	handle = m_renderer.createGeometry(vertices, normals, colors, (const unsigned int*)indices, (unsigned int)mesh.triangle.size(), material);
							}
							else
							{
								ColorRGBA const &c = (mesh.colors.size() == 1) ? mesh.colors[0] : ColorRGBA(1., 1., 1., 1.);

								material->setParam("diffuseColor", float3(c.getRed(), c.getGreen(), c.getBlue()));
								material->setParam("useVertexColor", false);

							 	handle = m_renderer.createGeometry(vertices, normals, (const unsigned int*)indices, (unsigned int)mesh.triangle.size(), material);
							}

							GroupHandle meshGroup = m_renderer.createGroup(Transform::identity());
							meshGroup->add(handle);
							m_renderer.getRoot()->add(meshGroup);
						}

						if (RTTI::isKindOf<Sphere>(**it))
						{
							Sphere const& sphere = *(const Sphere*)*it;

							float const* vertices = reinterpret_cast<float const*>(&(sphere_template_.vertex[0]));
							float const* normals  = reinterpret_cast<float const*>(&(sphere_template_.normal[0]));
							Index const* indices  = reinterpret_cast<Index const*>(&(sphere_template_.triangle[0]));

							// TEST
							ColorRGBA const& color = sphere.getColor();

							RTAppearanceHandle material = m_renderer.createAppearance("PhongShader");
							material->setParam("diffuseColor", float3(color.getRed(), color.getGreen(), color.getBlue()));
							material->setParam("ambientIntensity", float3(0.25, 0.25, 0.25));
							material->setParam("specularColor", float3(0.774597, 0.774597, 0.774597));
							material->setParam("shininess", (float)76.8);
							material->setParam("useVertexColor", false);

							GeoHandle handle   = m_renderer.createGeometry(vertices, normals, (const unsigned int*)indices, (unsigned int)sphere_template_.triangle.size(), material);

							Vector3 const& sphere_pos = sphere.getPosition();
							float radius = sphere.getRadius();

							GroupHandle sphereGroup = m_renderer.createGroup(  Transform::translation(sphere_pos.x, sphere_pos.y, sphere_pos.z)
																																*Transform::scale(Vec3f<1>(radius, radius, radius)));
							sphereGroup->add(handle);
							m_renderer.getRoot()->add(sphereGroup);
						}

						if (RTTI::isKindOf<TwoColoredTube>(**it))
						{
							TwoColoredTube const& tube = *(const TwoColoredTube*)*it;

							float const* vertices = reinterpret_cast<float const*>(&(tube_template_.vertex[0]));
							float const* normals  = reinterpret_cast<float const*>(&(tube_template_.normal[0]));
							Index const* indices  = reinterpret_cast<Index const*>(&(tube_template_.triangle[0]));

							// TEST
							std::vector<ColorRGBA> new_colors(tube_template_.vertex.size());
							Size num_triangles = tube_template_.triangle.size();

							for (Position i=0; i<num_triangles/2; ++i)
							{
								Surface::Triangle const& t = tube_template_.triangle[i];
								new_colors[t.v1] = tube.getColor();
								new_colors[t.v2] = tube.getColor();
								new_colors[t.v3] = tube.getColor();
							}

							for (Position i=num_triangles/2; i<num_triangles; ++i)
							{
								Surface::Triangle const& t = tube_template_.triangle[i];
								new_colors[t.v1] = tube.getColor2();
								new_colors[t.v2] = tube.getColor2();
								new_colors[t.v3] = tube.getColor2();
							}

							float const* colors  = reinterpret_cast<float const*>(&(new_colors[0]));

							RTAppearanceHandle material = m_renderer.createAppearance("PhongShader");
							material->setParam("diffuseColor", float3(0.4, 0.4, 0.4));
							material->setParam("ambientIntensity", float3(0.25, 0.25, 0.25));
							material->setParam("specularColor", float3(0.774597, 0.774597, 0.774597));
							material->setParam("shininess", (float)76.8);
							material->setParam("useVertexColor", true);

							GeoHandle handle   = m_renderer.createGeometry(vertices, normals, colors, (const unsigned int*)indices, (unsigned int)tube_template_.triangle.size(), material);

							GroupHandle tubeGroup = transformTube(tube);
							tubeGroup->add(handle);
							m_renderer.getRoot()->add(tubeGroup);
						}

					}
				}
			}
			if (recreate_accel)
				m_renderer.createAccelStruct();
			FrameBufferFormat fmt = buffer->getFormat();
			if (fmt.getPixelFormat() == PixelFormat::RGBF_96)
			{
				m_renderer.attachFrameBuffer(fmt.getWidth(), fmt.getHeight(), fmt.getPitch(), (float*)buffer->getData());
				m_renderer.renderToBuffer();
			}
		}

		GroupHandle RTfactRenderer::transformTube(const TwoColoredTube& tube)
		{
			Vector3 vec = tube.getVertex2() - tube.getVertex1();
			const double len = vec.getLength();
			const double angle = acos(vec.z / len); // the denominator accounts for the non-normalized rotation axis
			const float radius = tube.getRadius();

			Matrix4x4 trafo = Matrix4x4::getIdentity();
			//Rotate the vector around the normal
			vec /= sqrt(vec.x*vec.x + vec.y*vec.y);

			trafo.rotate(Angle(-angle), vec.y, -vec.x, 0);

			Matrix4f matrix(trafo.m11, trafo.m12, trafo.m13, trafo.m14,
											trafo.m21, trafo.m22, trafo.m23, trafo.m24,
											trafo.m31, trafo.m32, trafo.m33, trafo.m34,
											trafo.m41, trafo.m42, trafo.m43, trafo.m44);

			Vector3 const& midpoint = tube.getVertex1();

			return m_renderer.createGroup(	Transform::translation(midpoint.x, midpoint.y, midpoint.z)
																		 *matrix*Transform::scale(Vec3f<1>(radius, radius, len)));
		}
	}
}
<commit_msg>Raytraced tubes and spheres look now a bit nicer.<commit_after>#include <BALL/VIEW/RENDERING/RENDERERS/rtfactRenderer.h>
#include <RTfact/Config/Init.inc.cpp>
//#include <RTfact/Utils/Packets/Detail/Constants.inc.cpp>

#include <BALL/STRUCTURE/triangulatedSurface.h>
#include <BALL/VIEW/PRIMITIVES/sphere.h>
#include <BALL/VIEW/PRIMITIVES/twoColoredTube.h>

using namespace RTfact::Remote;

namespace BALL
{
	namespace VIEW
	{
		bool RTfactRenderer::init(const Scene& scene)
				throw()
		{
			scene_ = &scene;

			using RTfact::Triangle;
			using RTfact::Vec3f;
			using RTfact::Remote::GroupHandle;
			using RTfact::Remote::GeoHandle;
			using RTfact::Transform;
			using RTfact::Remote::float3;

			GroupHandle root = m_renderer.getRoot();
			TriangleVector faces;
			Triangle t(Vec3f<1>(0,0,0),Vec3f<1>(1,0,0),Vec3f<1>(1,1,0));
			t.texCoords[0] = std::make_pair(0.f,0.f);
			t.texCoords[1] = std::make_pair(0.f,512.f);
			t.texCoords[2] = std::make_pair(512.f,0.f);
			faces.push_back(t);

			for(TriangleVector::iterator it = faces.begin(); it != faces.end(); it++)
			{
				it->normals[0]=it->normal;
				it->normals[1]=it->normal;
				it->normals[2]=it->normal;
			}

			GeoHandle geo1 = m_renderer.createGeometry(faces);
			GroupHandle topGroup = m_renderer.createGroup(Transform::identity());
			topGroup->add(geo1);

			root->add(topGroup);

			RTfact::Remote::RTAppearanceHandle mat1 = m_renderer.createAppearance("PhongShader");
			mat1->setParam("diffuseColor", float3(1.0, 1.0, 0));
			mat1->setParam("ambientIntensity", float3(.7, .7, .7));

			geo1->setAppearance(mat1);

			m_renderer.setCameraPosition(
					float3(-1.48978, 4.14466, 11.4965),
					float3(0.864694, -0.481748, 0.142207),
					float3(0, 1, 0));

			//root->setTransform(Transform::rotationY(0.2f));
			//root->add(geo2);
			m_renderer.createAccelStruct();

			// prepare the sphere template
			TriangulatedSphere sphere_template;
			sphere_template.icosaeder();
			sphere_template.refine(3, true);

			sphere_template.exportSurface(sphere_template_);

			// prepare the tube template
			TriangulatedSurface* tube_template = TriangulatedSurface::createTube(18, 0, false, true);
			tube_template->exportSurface(tube_template_);
			delete (tube_template);

			return true;
		}

		void RTfactRenderer::prepareBufferedRendering(const Stage& stage)
		{
			Camera  const& camera = stage.getCamera();
			Vector3 const& position = camera.getViewPoint();
			Vector3 const& view_vector = camera.getViewVector();
			Vector3 const& look_up = camera.getLookUpVector();

			m_renderer.setCameraPosition(float3(position.x, position.y, position.z),
																	 float3(view_vector.x, view_vector.y, view_vector.z),
																	 float3(look_up.x, look_up.y, look_up.z));

			Size num_lights = lights_.size();

			Vector3 direction, light_position;
			Size current_light=0;
			List<LightSource>::ConstIterator it = stage.getLightSources().begin();
			for (; it != stage.getLightSources().end(); ++it, ++current_light)
			{
				if (current_light >= num_lights)
				{
					RTfact::Remote::RTLightHandle light;
					switch (it->getType())
					{
						case LightSource::DIRECTIONAL:
							light = m_renderer.createLight("DirectionalLight");
							break;
						case LightSource::POSITIONAL:
							light = m_renderer.createLight("PointLight");
							break;
						default:
							std::cerr << "Light source type not supported!" << std::endl;
							break;
					}
					lights_.push_back(light);
				}
				switch (it->getType())
				{
					case LightSource::DIRECTIONAL:
						direction = it->getDirection();
						if (it->isRelativeToCamera())
							direction = stage.calculateAbsoluteCoordinates(direction);

						lights_[current_light]->setParam("direction", float3(direction.x, direction.y, direction.z));
						break;
					case LightSource::POSITIONAL:
						light_position = it->getPosition();
						if (it->isRelativeToCamera())
						{
							light_position = stage.calculateAbsoluteCoordinates(it->getPosition())+stage.getCamera().getViewPoint();
						}
						lights_[current_light]->setParam("position", float3(light_position.x, light_position.y, light_position.z));
						break;
					default:
						std::cerr << "Light source type not supported!" << std::endl;
						break;
				}
				float intensity = it->getIntensity()*500;
				ColorRGBA const& color = it->getColor();

				lights_[current_light]->setParam("intensity", float3((float)color.getRed()*intensity,(float)color.getGreen()*intensity,(float)color.getBlue()*intensity));
			}
		}

		void RTfactRenderer::renderToBufferImpl(FrameBufferPtr buffer)
		{
			bool recreate_accel = false;
			RepresentationManager& pm = scene_->getMainControl()->getRepresentationManager();

			RepresentationList::ConstIterator it = pm.getRepresentations().begin();
			for (; it != pm.getRepresentations().end(); ++it)
			{
				Representation const* rep = *it;
				if (rep->isHidden()) continue;

				List<GeometricObject*>::ConstIterator it;
				for (it =  rep->getGeometricObjects().begin();
						it != rep->getGeometricObjects().end();
						it++)
				{
					if (objects_.find(*it) == objects_.end())
					{
						recreate_accel = true;
						objects_.insert(*it);
						if (RTTI::isKindOf<Mesh>(**it))
						{
							Mesh const& mesh = *(const Mesh*)*it;

							float const* vertices = reinterpret_cast<float const*>(&(mesh.vertex[0]));
							float const* normals  = reinterpret_cast<float const*>(&(mesh.normal[0]));
							Index const* indices = reinterpret_cast<Index const*>(&(mesh.triangle[0]));

							RTAppearanceHandle material = m_renderer.createAppearance("PhongShader");
							material->setParam("ambientIntensity", float3(0.25, 0.25, 0.25));
							material->setParam("specularColor", float3(0.774597, 0.774597, 0.774597));
							material->setParam("reflective", float3(0.0, 0.0, 0.0));
							material->setParam("shininess", (float)76.8);

							GeoHandle handle;

							float const* colors = 0;
							if (mesh.colors.size() > 1)
							{
								colors  = reinterpret_cast<float const*>(&(mesh.colors[0]));
								material->setParam("useVertexColor", true);

							 	handle = m_renderer.createGeometry(vertices, normals, colors, (const unsigned int*)indices, (unsigned int)mesh.triangle.size(), material);
							}
							else
							{
								ColorRGBA const &c = (mesh.colors.size() == 1) ? mesh.colors[0] : ColorRGBA(1., 1., 1., 1.);

								material->setParam("diffuseColor", float3(c.getRed(), c.getGreen(), c.getBlue()));
								material->setParam("useVertexColor", false);

							 	handle = m_renderer.createGeometry(vertices, normals, (const unsigned int*)indices, (unsigned int)mesh.triangle.size(), material);
							}

							GroupHandle meshGroup = m_renderer.createGroup(Transform::identity());
							meshGroup->add(handle);
							m_renderer.getRoot()->add(meshGroup);
						}

						if (RTTI::isKindOf<Sphere>(**it))
						{
							Sphere const& sphere = *(const Sphere*)*it;

							float const* vertices = reinterpret_cast<float const*>(&(sphere_template_.vertex[0]));
							float const* normals  = reinterpret_cast<float const*>(&(sphere_template_.normal[0]));
							Index const* indices  = reinterpret_cast<Index const*>(&(sphere_template_.triangle[0]));

							ColorRGBA const& color = sphere.getColor();

							RTAppearanceHandle material = m_renderer.createAppearance("PhongShader");
							material->setParam("diffuseColor", float3(color.getRed(), color.getGreen(), color.getBlue()));
							material->setParam("ambientIntensity", float3(0.25, 0.25, 0.25));
							material->setParam("specularColor", float3(0.774597, 0.774597, 0.774597));
							material->setParam("shininess", (float)76.8);
							material->setParam("useVertexColor", false);

							GeoHandle handle   = m_renderer.createGeometry(vertices, normals, (const unsigned int*)indices, (unsigned int)sphere_template_.triangle.size(), material);

							Vector3 const& sphere_pos = sphere.getPosition();
							float radius = sphere.getRadius();

							GroupHandle sphereGroup = m_renderer.createGroup(  Transform::translation(sphere_pos.x, sphere_pos.y, sphere_pos.z)
																																*Transform::scale(Vec3f<1>(radius, radius, radius)));
							sphereGroup->add(handle);
							m_renderer.getRoot()->add(sphereGroup);
						}

						if (RTTI::isKindOf<TwoColoredTube>(**it))
						{
							TwoColoredTube const& old_tube = *(const TwoColoredTube*)*it;

							float const* vertices = reinterpret_cast<float const*>(&(tube_template_.vertex[0]));
							float const* normals  = reinterpret_cast<float const*>(&(tube_template_.normal[0]));
							Index const* indices  = reinterpret_cast<Index const*>(&(tube_template_.triangle[0]));

							// we will produce two tubes using the same vertex/normal/color values, just with the correct offsets
							ColorRGBA const& color1 = old_tube.getColor();
							ColorRGBA const& color2 = old_tube.getColor2();

							RTAppearanceHandle material_1 = m_renderer.createAppearance("PhongShader");
							material_1->setParam("diffuseColor", float3(color1.getRed(), color1.getGreen(), color1.getBlue()));
							material_1->setParam("ambientIntensity", float3(0.25, 0.25, 0.25));
							material_1->setParam("specularColor", float3(0.774597, 0.774597, 0.774597));
							material_1->setParam("shininess", (float)76.8);
							material_1->setParam("useVertexColor", false);

							GeoHandle handle_1 = m_renderer.createGeometry(vertices, normals, (const unsigned int*)indices, (unsigned int)tube_template_.triangle.size(), material_1);

							if (color1 == color2)
							{
								GroupHandle tubeGroup = transformTube(old_tube);
								tubeGroup->add(handle_1);

								m_renderer.getRoot()->add(tubeGroup);
							}
							else
							{
								RTAppearanceHandle material_2 = m_renderer.createAppearance("PhongShader");
								material_2->setParam("diffuseColor", float3(color2.getRed(), color2.getGreen(), color2.getBlue()));
								material_2->setParam("ambientIntensity", float3(0.25, 0.25, 0.25));
								material_2->setParam("specularColor", float3(0.774597, 0.774597, 0.774597));
								material_2->setParam("shininess", (float)76.8);
								material_2->setParam("useVertexColor", false);

								GeoHandle handle_2 = m_renderer.createGeometry(vertices, normals, (const unsigned int*)indices, (unsigned int)tube_template_.triangle.size(), material_2);

								TwoColoredTube new_tube = old_tube;
								new_tube.setVertex2(old_tube.getMiddleVertex());

								GroupHandle tubeGroup_1 = transformTube(new_tube);
								tubeGroup_1->add(handle_1);

								new_tube.setVertex1(old_tube.getVertex2());
								new_tube.setVertex2(old_tube.getMiddleVertex());
								GroupHandle tubeGroup_2 = transformTube(new_tube);
								tubeGroup_2->add(handle_2);

								m_renderer.getRoot()->add(tubeGroup_1);
								m_renderer.getRoot()->add(tubeGroup_2);
							}
						}

					}
				}
			}
			if (recreate_accel)
				m_renderer.createAccelStruct();
			FrameBufferFormat fmt = buffer->getFormat();
			if (fmt.getPixelFormat() == PixelFormat::RGBF_96)
			{
				m_renderer.attachFrameBuffer(fmt.getWidth(), fmt.getHeight(), fmt.getPitch(), (float*)buffer->getData());
				m_renderer.renderToBuffer();
			}
		}

		GroupHandle RTfactRenderer::transformTube(const TwoColoredTube& tube)
		{
			Vector3 vec = tube.getVertex2() - tube.getVertex1();
			const double len = vec.getLength();
			const double angle = acos(vec.z / len); // the denominator accounts for the non-normalized rotation axis
			const float radius = tube.getRadius();

			Matrix4x4 trafo = Matrix4x4::getIdentity();
			//Rotate the vector around the normal
			vec /= sqrt(vec.x*vec.x + vec.y*vec.y);

			trafo.rotate(Angle(-angle), vec.y, -vec.x, 0);

			Matrix4f matrix(trafo.m11, trafo.m12, trafo.m13, trafo.m14,
											trafo.m21, trafo.m22, trafo.m23, trafo.m24,
											trafo.m31, trafo.m32, trafo.m33, trafo.m34,
											trafo.m41, trafo.m42, trafo.m43, trafo.m44);

			Vector3 const& midpoint = tube.getVertex1();

			return m_renderer.createGroup(	Transform::translation(midpoint.x, midpoint.y, midpoint.z)
																		 *matrix*Transform::scale(Vec3f<1>(radius, radius, len)));
		}
	}
}
<|endoftext|>


<commit_before>#include "rForcom.h"

#include "de/hackcraft/psi3d/GLF.h"
#include "de/hackcraft/psi3d/GLS.h"

#include "de/hackcraft/world/Message.h"

std::string rForcom::cname = "FORCOM";
unsigned int rForcom::cid = 1032;

rForcom::rForcom(Entity* obj) {
    object = obj;

    quat_zero(ori);
    vector_zero(twr);
}

void rForcom::message(Message* message) {
    mMessage = message->getText();
}

void rForcom::animate(float spf) {
}

void rForcom::drawHUD() {
    if (!active) return;

    // Reticle in screen center.
    if (reticle) {
        glPushMatrix();
        {
            glTranslatef(0.5, 0.5, 0);
            glScalef(0.03, 0.04, 1);
            glPointSize(2);
            glBegin(GL_POINTS);
            {
                glColor4f(1, 0, 0, 0.2);
                glVertex3f(0, 0, 0);
            }
            glEnd();
            glBegin(GL_LINES);
            {
                const float a = 0.7;
                // left
                glVertex3f(-1, 0, 0);
                glVertex3f(-a, 0, 0);
                // low
                glVertex3f(0, -1, 0);
                glVertex3f(0, -a, 0);
                // right
                glVertex3f(+1, 0, 0);
                glVertex3f(+a, 0, 0);
                // diagonal
                glVertex3f(-a, 0, 0);
                glVertex3f(0, -a, 0);
                glVertex3f(0, -a, 0);
                glVertex3f(+a, 0, 0);
            }
            glEnd();
        }
        glPopMatrix();
    }

    // Compass-Lines at top of HUD
    if (!true) {
        glPushMatrix();
        {
            glTranslatef(0.5, 0.97, 0);
            glScalef(1.0, 0.02, 1.0);
            glColor4f(0, 1, 0, 0.2);

            float r = atan2(ori[1], ori[3]) / PI_OVER_180;
            if (r > 180) r -= 360;
            const float d = 1.0f / 360.0f;

            glLineWidth(3);
            glBegin(GL_LINES);
            {
                glColor4f(0, 0.3, 1, 0.2);
                float s = 1.2;
                for (int i = -180; i < 180; i += 10) {
                    float t = fmod(r, 10);
                    glVertex3f((i + t) * d, -s, 0);
                    glVertex3f((i + t) * d, +s, 0);
                }
            }
            glEnd();

            glLineWidth(1);
            glBegin(GL_LINES);
            {
                glColor4f(1, 1, 1, 0.6);
                float s = 1.0;
                for (int i = -180; i < 180; i += 10) {
                    float t = fmod(r, 10);
                    glVertex3f((i + t) * d, -s, 0);
                    glVertex3f((i + t) * d, +s, 0);
                }
            }
            glEnd();

        }
        glPopMatrix();
    } // Compass

    // Ornamental HUD-Border-Frame
    if (true) {
        glLineWidth(5);
        glColor4f(1, 1, 0, 0.2);
        glBegin(GL_LINE_STRIP);
        {
            glVertex3f(0.8, 0.1, 0);
            glVertex3f(0.9, 0.2, 0);
            glVertex3f(0.9, 0.8, 0);
            glVertex3f(0.8, 0.9, 0);
        }
        glEnd();
        glBegin(GL_LINE_STRIP);
        {
            glVertex3f(0.2, 0.9, 0);
            glVertex3f(0.1, 0.8, 0);
            glVertex3f(0.1, 0.2, 0);
            glVertex3f(0.2, 0.1, 0);
        }
        glEnd();
        glLineWidth(1);
        glLineStipple(1, 0xFF55);
        glColor4f(1, 1, 1, 0.6);
        glEnable(GL_LINE_STIPPLE);
        glBegin(GL_LINE_STRIP);
        {
            glVertex3f(0.8, 0.1, 0);
            glVertex3f(0.9, 0.2, 0);
            glVertex3f(0.9, 0.8, 0);
            glVertex3f(0.8, 0.9, 0);
        }
        glEnd();
        glBegin(GL_LINE_STRIP);
        {
            glVertex3f(0.2, 0.9, 0);
            glVertex3f(0.1, 0.8, 0);
            glVertex3f(0.1, 0.2, 0);
            glVertex3f(0.2, 0.1, 0);
        }
        glEnd();
        /*
        glBegin(GL_LINE_STRIP);
        {
            glVertex3f(0.2, 0.1, 0);
            glVertex3f(0.8, 0.1, 0);
            glVertex3f(0.9, 0.2, 0);
            glVertex3f(0.9, 0.8, 0);
            glVertex3f(0.8, 0.9, 0);
            glVertex3f(0.2, 0.9, 0);
            glVertex3f(0.1, 0.8, 0);
            glVertex3f(0.1, 0.2, 0);
            glVertex3f(0.2, 0.1, 0);
        }
        glEnd();
         */
        glDisable(GL_LINE_STIPPLE);
    } // Border

    float f = 1.0f / (250 * 0.017453f);

    // Tower angle indicator
    if (true) {
        glLineWidth(3);

        // Tower left/right indication bar.
        glBegin(GL_LINES);
        {
            glColor4f(0, 0.2, 0.7, 0.4);
            glVertex3f(0.5, 0.1, 0);
            glVertex3f(0.5 + twr[1] * f, 0.1, 0);

            glVertex3f(0.5 + twr[1] * f, 0.08, 0);
            glVertex3f(0.5 + twr[1] * f, 0.12, 0);

            glVertex3f(0.5, 0.9, 0);
            glVertex3f(0.5 + twr[1] * f, 0.9, 0);

            glVertex3f(0.5 + twr[1] * f, 0.88, 0);
            glVertex3f(0.5 + twr[1] * f, 0.92, 0);
        }
        glEnd();

        // Tower up/down indication bar.
        glBegin(GL_LINES);
        {
            glColor4f(0, 0.2, 0.7, 0.4);
            glVertex3f(0.1, 0.5, 0);
            glVertex3f(0.1, 0.5 + twr[0] * f, 0);

            glVertex3f(0.08, 0.5 + twr[0] * f, 0);
            glVertex3f(0.12, 0.5 + twr[0] * f, 0);

            glVertex3f(0.9, 0.5, 0);
            glVertex3f(0.9, 0.5 + twr[0] * f, 0);

            glVertex3f(0.88, 0.5 + twr[0] * f, 0);
            glVertex3f(0.92, 0.5 + twr[0] * f, 0);
        }
        glEnd();

    } // Tower angle indicator

    // Message display
    if (true) {
        glPushMatrix();
        {
            glColor4f(0.99, 0.99, 0.19, 1);
            glTranslatef(0, 1, 0);
            glScalef(1.0f / 60.0f, 1.0f / 20.0f, 1.0f);
            glColor4f(0.09, 0.99, 0.09, 1);
            glTranslatef(0, -0, 0);
            GLF::glprint(mMessage.c_str());
            //GLF::glprintf("TEST TEST TEST ... TEST TEST TEST\ntest test test");
        }
        glPopMatrix();
    } // Message display
}

<commit_msg>Mobile-System: Cleaning initialization issues (removing empty copy constructor).<commit_after>#include "rForcom.h"

#include "de/hackcraft/psi3d/GLF.h"
#include "de/hackcraft/psi3d/GLS.h"

#include "de/hackcraft/world/Message.h"

std::string rForcom::cname = "FORCOM";
unsigned int rForcom::cid = 1032;

rForcom::rForcom(Entity* obj) {
    object = obj;

    quat_zero(ori);
    vector_zero(twr);
    reticle = true;
}

void rForcom::message(Message* message) {
    mMessage = message->getText();
}

void rForcom::animate(float spf) {
}

void rForcom::drawHUD() {
    if (!active) return;

    // Reticle in screen center.
    if (reticle) {
        glPushMatrix();
        {
            glTranslatef(0.5, 0.5, 0);
            glScalef(0.03, 0.04, 1);
            glPointSize(2);
            glBegin(GL_POINTS);
            {
                glColor4f(1, 0, 0, 0.2);
                glVertex3f(0, 0, 0);
            }
            glEnd();
            glBegin(GL_LINES);
            {
                const float a = 0.7;
                // left
                glVertex3f(-1, 0, 0);
                glVertex3f(-a, 0, 0);
                // low
                glVertex3f(0, -1, 0);
                glVertex3f(0, -a, 0);
                // right
                glVertex3f(+1, 0, 0);
                glVertex3f(+a, 0, 0);
                // diagonal
                glVertex3f(-a, 0, 0);
                glVertex3f(0, -a, 0);
                glVertex3f(0, -a, 0);
                glVertex3f(+a, 0, 0);
            }
            glEnd();
        }
        glPopMatrix();
    }

    // Compass-Lines at top of HUD
    if (!true) {
        glPushMatrix();
        {
            glTranslatef(0.5, 0.97, 0);
            glScalef(1.0, 0.02, 1.0);
            glColor4f(0, 1, 0, 0.2);

            float r = atan2(ori[1], ori[3]) / PI_OVER_180;
            if (r > 180) r -= 360;
            const float d = 1.0f / 360.0f;

            glLineWidth(3);
            glBegin(GL_LINES);
            {
                glColor4f(0, 0.3, 1, 0.2);
                float s = 1.2;
                for (int i = -180; i < 180; i += 10) {
                    float t = fmod(r, 10);
                    glVertex3f((i + t) * d, -s, 0);
                    glVertex3f((i + t) * d, +s, 0);
                }
            }
            glEnd();

            glLineWidth(1);
            glBegin(GL_LINES);
            {
                glColor4f(1, 1, 1, 0.6);
                float s = 1.0;
                for (int i = -180; i < 180; i += 10) {
                    float t = fmod(r, 10);
                    glVertex3f((i + t) * d, -s, 0);
                    glVertex3f((i + t) * d, +s, 0);
                }
            }
            glEnd();

        }
        glPopMatrix();
    } // Compass

    // Ornamental HUD-Border-Frame
    if (true) {
        glLineWidth(5);
        glColor4f(1, 1, 0, 0.2);
        glBegin(GL_LINE_STRIP);
        {
            glVertex3f(0.8, 0.1, 0);
            glVertex3f(0.9, 0.2, 0);
            glVertex3f(0.9, 0.8, 0);
            glVertex3f(0.8, 0.9, 0);
        }
        glEnd();
        glBegin(GL_LINE_STRIP);
        {
            glVertex3f(0.2, 0.9, 0);
            glVertex3f(0.1, 0.8, 0);
            glVertex3f(0.1, 0.2, 0);
            glVertex3f(0.2, 0.1, 0);
        }
        glEnd();
        glLineWidth(1);
        glLineStipple(1, 0xFF55);
        glColor4f(1, 1, 1, 0.6);
        glEnable(GL_LINE_STIPPLE);
        glBegin(GL_LINE_STRIP);
        {
            glVertex3f(0.8, 0.1, 0);
            glVertex3f(0.9, 0.2, 0);
            glVertex3f(0.9, 0.8, 0);
            glVertex3f(0.8, 0.9, 0);
        }
        glEnd();
        glBegin(GL_LINE_STRIP);
        {
            glVertex3f(0.2, 0.9, 0);
            glVertex3f(0.1, 0.8, 0);
            glVertex3f(0.1, 0.2, 0);
            glVertex3f(0.2, 0.1, 0);
        }
        glEnd();
        /*
        glBegin(GL_LINE_STRIP);
        {
            glVertex3f(0.2, 0.1, 0);
            glVertex3f(0.8, 0.1, 0);
            glVertex3f(0.9, 0.2, 0);
            glVertex3f(0.9, 0.8, 0);
            glVertex3f(0.8, 0.9, 0);
            glVertex3f(0.2, 0.9, 0);
            glVertex3f(0.1, 0.8, 0);
            glVertex3f(0.1, 0.2, 0);
            glVertex3f(0.2, 0.1, 0);
        }
        glEnd();
         */
        glDisable(GL_LINE_STIPPLE);
    } // Border

    float f = 1.0f / (250 * 0.017453f);

    // Tower angle indicator
    if (true) {
        glLineWidth(3);

        // Tower left/right indication bar.
        glBegin(GL_LINES);
        {
            glColor4f(0, 0.2, 0.7, 0.4);
            glVertex3f(0.5, 0.1, 0);
            glVertex3f(0.5 + twr[1] * f, 0.1, 0);

            glVertex3f(0.5 + twr[1] * f, 0.08, 0);
            glVertex3f(0.5 + twr[1] * f, 0.12, 0);

            glVertex3f(0.5, 0.9, 0);
            glVertex3f(0.5 + twr[1] * f, 0.9, 0);

            glVertex3f(0.5 + twr[1] * f, 0.88, 0);
            glVertex3f(0.5 + twr[1] * f, 0.92, 0);
        }
        glEnd();

        // Tower up/down indication bar.
        glBegin(GL_LINES);
        {
            glColor4f(0, 0.2, 0.7, 0.4);
            glVertex3f(0.1, 0.5, 0);
            glVertex3f(0.1, 0.5 + twr[0] * f, 0);

            glVertex3f(0.08, 0.5 + twr[0] * f, 0);
            glVertex3f(0.12, 0.5 + twr[0] * f, 0);

            glVertex3f(0.9, 0.5, 0);
            glVertex3f(0.9, 0.5 + twr[0] * f, 0);

            glVertex3f(0.88, 0.5 + twr[0] * f, 0);
            glVertex3f(0.92, 0.5 + twr[0] * f, 0);
        }
        glEnd();

    } // Tower angle indicator

    // Message display
    if (true) {
        glPushMatrix();
        {
            glColor4f(0.99, 0.99, 0.19, 1);
            glTranslatef(0, 1, 0);
            glScalef(1.0f / 60.0f, 1.0f / 20.0f, 1.0f);
            glColor4f(0.09, 0.99, 0.09, 1);
            glTranslatef(0, -0, 0);
            GLF::glprint(mMessage.c_str());
            //GLF::glprintf("TEST TEST TEST ... TEST TEST TEST\ntest test test");
        }
        glPopMatrix();
    } // Message display
}

<|endoftext|>


<commit_before>// Copyright 2015 The Crashpad Authors. All rights reserved.
//
// 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 "test/scoped_temp_dir.h"

#include <fcntl.h>
#include <string.h>

#include "base/posix/eintr_wrapper.h"
#include "build/build_config.h"
#include "gtest/gtest.h"
#include "test/errors.h"
#include "test/file.h"

#if defined(OS_POSIX)
#include <unistd.h>
#elif defined(OS_WIN)
#include <direct.h>
#include <io.h>
#endif  // OS_POSIX

namespace crashpad {
namespace test {
namespace {

void CreateFile(const base::FilePath& path) {
#if defined(OS_POSIX)
  int fd = HANDLE_EINTR(creat(path.value().c_str(), 0644));
  ASSERT_GE(fd, 0) << ErrnoMessage("creat") << " " << path.value();
  ASSERT_EQ(IGNORE_EINTR(close(fd)), 0) << ErrnoMessage("close") << " "
                                        << path.value();
#elif defined(OS_WIN)
  int fd = _wcreat(path.value().c_str(), _S_IREAD | _S_IWRITE);
  ASSERT_GE(fd, 0) << ErrnoMessage("_wcreat") << " " << path.value();
  ASSERT_EQ(_close(fd), 0) << ErrnoMessage("_close") << " " << path.value();
#else
#error "Not implemented"
#endif
  EXPECT_TRUE(FileExists(path));
}

void CreateDirectory(const base::FilePath& path) {
#if defined(OS_POSIX)
  ASSERT_EQ(mkdir(path.value().c_str(), 0755), 0) << ErrnoMessage("mkdir")
                                                  << " " << path.value();
#elif defined(OS_WIN)
  ASSERT_EQ(_wmkdir(path.value().c_str()), 0) << ErrnoMessage("_wmkdir") << " "
                                              << path.value();
#else
#error "Not implemented"
#endif
  ASSERT_TRUE(FileExists(path));
}

TEST(ScopedTempDir, Empty) {
  base::FilePath path;
  {
    ScopedTempDir dir;
    path = dir.path();
    EXPECT_TRUE(FileExists(path));
  }
  EXPECT_FALSE(FileExists(path));
}

TEST(ScopedTempDir, WithTwoFiles) {
  base::FilePath parent, file1, file2;

  {
    ScopedTempDir dir;
    parent = dir.path();
    ASSERT_TRUE(FileExists(parent));

    file1 = parent.Append(FILE_PATH_LITERAL("test1"));
    CreateFile(file1);

    file2 = parent.Append(FILE_PATH_LITERAL("test 2"));
    CreateFile(file2);
  }

  EXPECT_FALSE(FileExists(file1));
  EXPECT_FALSE(FileExists(file2));
  EXPECT_FALSE(FileExists(parent));
}

TEST(ScopedTempDir, WithRecursiveDirectory) {
  base::FilePath parent, file1, child_dir, file2;

  {
    ScopedTempDir dir;
    parent = dir.path();
    ASSERT_TRUE(FileExists(parent));

    file1 = parent.Append(FILE_PATH_LITERAL(".first-level file"));
    CreateFile(file1);

    child_dir = parent.Append(FILE_PATH_LITERAL("subdir"));
    CreateDirectory(child_dir);

    file2 = child_dir.Append(FILE_PATH_LITERAL("second level file"));
    CreateFile(file2);
  }

  EXPECT_FALSE(FileExists(file1));
  EXPECT_FALSE(FileExists(file2));
  EXPECT_FALSE(FileExists(child_dir));
  EXPECT_FALSE(FileExists(parent));
}

}  // namespace
}  // namespace test
}  // namespace crashpad
<commit_msg>Fix crashpad_util_test build with GCC after 4b450c813795<commit_after>// Copyright 2015 The Crashpad Authors. All rights reserved.
//
// 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 "test/scoped_temp_dir.h"

#include <fcntl.h>
#include <string.h>

#include "base/posix/eintr_wrapper.h"
#include "build/build_config.h"
#include "gtest/gtest.h"
#include "test/errors.h"
#include "test/file.h"

#if defined(OS_POSIX)
#include <unistd.h>
#elif defined(OS_WIN)
#include <direct.h>
#include <io.h>
#endif  // OS_POSIX

namespace crashpad {
namespace test {
namespace {

void CreateFile(const base::FilePath& path) {
#if defined(OS_POSIX)
  int fd = HANDLE_EINTR(creat(path.value().c_str(), 0644));
  ASSERT_GE(fd, 0) << ErrnoMessage("creat") << " " << path.value();

  // gcc refuses to compile ASSERT_EQ(IGNORE_EINTR(close(fd)), 0).
  int close_rv = IGNORE_EINTR(close(fd));
  ASSERT_EQ(close_rv, 0) << ErrnoMessage("close") << " " << path.value();
#elif defined(OS_WIN)
  int fd = _wcreat(path.value().c_str(), _S_IREAD | _S_IWRITE);
  ASSERT_GE(fd, 0) << ErrnoMessage("_wcreat") << " " << path.value();
  ASSERT_EQ(_close(fd), 0) << ErrnoMessage("_close") << " " << path.value();
#else
#error "Not implemented"
#endif
  EXPECT_TRUE(FileExists(path));
}

void CreateDirectory(const base::FilePath& path) {
#if defined(OS_POSIX)
  ASSERT_EQ(mkdir(path.value().c_str(), 0755), 0) << ErrnoMessage("mkdir")
                                                  << " " << path.value();
#elif defined(OS_WIN)
  ASSERT_EQ(_wmkdir(path.value().c_str()), 0) << ErrnoMessage("_wmkdir") << " "
                                              << path.value();
#else
#error "Not implemented"
#endif
  ASSERT_TRUE(FileExists(path));
}

TEST(ScopedTempDir, Empty) {
  base::FilePath path;
  {
    ScopedTempDir dir;
    path = dir.path();
    EXPECT_TRUE(FileExists(path));
  }
  EXPECT_FALSE(FileExists(path));
}

TEST(ScopedTempDir, WithTwoFiles) {
  base::FilePath parent, file1, file2;

  {
    ScopedTempDir dir;
    parent = dir.path();
    ASSERT_TRUE(FileExists(parent));

    file1 = parent.Append(FILE_PATH_LITERAL("test1"));
    CreateFile(file1);

    file2 = parent.Append(FILE_PATH_LITERAL("test 2"));
    CreateFile(file2);
  }

  EXPECT_FALSE(FileExists(file1));
  EXPECT_FALSE(FileExists(file2));
  EXPECT_FALSE(FileExists(parent));
}

TEST(ScopedTempDir, WithRecursiveDirectory) {
  base::FilePath parent, file1, child_dir, file2;

  {
    ScopedTempDir dir;
    parent = dir.path();
    ASSERT_TRUE(FileExists(parent));

    file1 = parent.Append(FILE_PATH_LITERAL(".first-level file"));
    CreateFile(file1);

    child_dir = parent.Append(FILE_PATH_LITERAL("subdir"));
    CreateDirectory(child_dir);

    file2 = child_dir.Append(FILE_PATH_LITERAL("second level file"));
    CreateFile(file2);
  }

  EXPECT_FALSE(FileExists(file1));
  EXPECT_FALSE(FileExists(file2));
  EXPECT_FALSE(FileExists(child_dir));
  EXPECT_FALSE(FileExists(parent));
}

}  // namespace
}  // namespace test
}  // namespace crashpad
<|endoftext|>