<commit_before>#pragma once

#include <gcl/mp/meta/functional.hpp>

namespace gcl::mp
{
    template <std::size_t index>
    struct type_index {};

    template <typename... types>
    struct tuple {

        constexpr static auto size = sizeof...(types);
        constexpr static auto empty = size == 0;
        template <std::size_t index>
        constexpr static auto valid_index = not empty and index <= (size - 1);

        constexpr tuple() requires(not empty)
            : storage{generate_storage(types{}...)}
        {}
        constexpr tuple(types&&... values)
            : storage{generate_storage(std::forward<decltype(values)>(values)...)}
        {}
        constexpr tuple(tuple&&) = default;

      private:

        // storage : by-pass missing features : auto non-static members, lambdas in unevaluated context
        using index_sequence = std::make_index_sequence<sizeof...(types)>;
        static constexpr auto generate_storage(types&&... values)
        { // defer parameter pack expansion (msvc-cl, Clang)
            return generate_storage_impl(index_sequence{}, std::forward<decltype(values)>(values)...);
        }
        template <std::size_t... indexes>
        static constexpr auto generate_storage_impl(std::index_sequence<indexes...>, types&&... values)
        {
            static_assert(sizeof...(indexes) == sizeof...(types));
            static_assert(sizeof...(indexes) == sizeof...(values));

            const auto generate_storage_entry = []<typename T, std::size_t index>(T && init_value) constexpr
            {
                return [value = init_value](type_index<index>) constexpr mutable noexcept -> auto&& { return value; };
            };
            return gcl::mp::meta::functional::overload{
                generate_storage_entry.template operator()<types, indexes>(std::forward<decltype(values)>(values))...};
        };
        using storage_type = decltype(generate_storage(types{}...));
        mutable storage_type storage;

        template <std::size_t index>
        requires(valid_index<index>)
        struct type_at_impl { // defer symbol (Clang)
            using type = std::remove_reference_t<decltype(std::declval<tuple>().template get<index>())>;
        };

      public:
        template <std::size_t index>
        requires(valid_index<index>)
        using type_at = typename type_at_impl<index>::type;

        template <std::size_t index>
        requires(valid_index<index>)
        constexpr auto& get() & noexcept
        {
            return storage(type_index<index>{});
        }
        template <std::size_t index>
        requires(valid_index<index>) constexpr const auto& get() const& noexcept
        {
            return storage(type_index<index>{});
        }
        template <std::size_t index>
        requires(valid_index<index>) constexpr auto&& get() && noexcept
        {
            return std::move(storage(type_index<index>{}));
        }
        template <std::size_t index>
        requires(valid_index<index>) constexpr const auto&& get() const&& noexcept
        {
            return std::move(storage(type_index<index>{}));
        }

        template <typename... arg_types>
        requires(sizeof...(arg_types) == size) constexpr bool operator==(
            const tuple<arg_types...>& other) const noexcept
        {
            return [ this, &other ]<std::size_t... indexes>(std::index_sequence<indexes...>)
            {
                return (((get<indexes>() == other.template get<indexes>()) && ...));
            }
            (std::make_index_sequence<size>{});
        }
    };
    // When Clang, Msvc-cl gets better, replace `tuple::generate_storage` implementation by :
    /*static constexpr auto generate_storage(types&&... values)
    {
        return [&values...]<std::size_t... indexes>(std::index_sequence<indexes...>)
        {
            static_assert(sizeof...(indexes) == sizeof...(types));
            static_assert(sizeof...(indexes) == sizeof...(values));

            const auto generate_storage_entry = []<typename T, std::size_t index>(T && init_value) constexpr
            {
                return [value = init_value](type_index<index>) mutable -> auto& { return value; };
            };
            return gcl::mp::meta::functional::overload{generate_storage_entry.template operator()<types, indexes>(
                std::forward<decltype(values)>(values))...};
        }
        (std::make_index_sequence<sizeof...(types)>{});
    };*/
}

namespace gcl::mp
{
    template <std::size_t I, class... Types>
    constexpr auto & get(tuple<Types...>& value) noexcept
    {
        return value.template get<I>();
    }

    template <std::size_t I, class... Types>
    constexpr auto && get(tuple<Types...>&& value) noexcept
    {
        return std::move(value.template get<I>());
    }
    template <std::size_t I, class... Types>
    constexpr auto const& get(const tuple<Types...>& value) noexcept
    {
        return value.template get<I>();
    }
    template <std::size_t I, class... Types>
    constexpr auto const&& get(const tuple<Types...>&& value) noexcept
    {
        return std::move(value.template get<I>());
    }

    template <class...>
    struct tuple_size;
    template <class... Types>
    struct tuple_size<tuple<Types...>> : std::integral_constant<std::size_t, sizeof...(Types)> {};
    template <class T>
    constexpr auto tuple_size_v = tuple_size<T>::value;

    template <class T, class... Types>
    constexpr T& get(tuple<Types...>& value) noexcept;
    template <class T, class... Types>
    constexpr T&& get(tuple<Types...>&& value) noexcept;
    template <class T, class... Types>
    constexpr const T& get(const tuple<Types...>& value) noexcept;
    template <class T, class... Types>
    constexpr const T&& get(const tuple<Types...>&& value) noexcept;
}

#if defined(GCL_ENABLE_COMPILE_TIME_TESTS)
#include <stdexcept>
#include <exception>
namespace gcl::mp::tests::tuples::values
{
    using namespace gcl::mp;

    using empty_tuple = tuple<>;
    using one_element_tuple = tuple<int>;
    using two_element_tuple = tuple<int, char>;

    static constexpr auto empty_tuple_default_init = empty_tuple{};
    static constexpr auto one_element_tuple_default_init = one_element_tuple{};
    static constexpr auto two_element_tuple_default_init = two_element_tuple{};

    static constexpr auto one_element_tuple_values_init = one_element_tuple{42};
    static constexpr auto two_element_tuple_values_init = two_element_tuple{42, 'a'};

    static_assert(std::is_same_v<tuple<int, char>, decltype(tuple{42, 'a'})>);

    static_assert(std::is_same_v<two_element_tuple::type_at<0>, int>);
    static_assert(std::is_same_v<two_element_tuple::type_at<1>, char>);

    static_assert(std::is_same_v<decltype(std::declval<two_element_tuple&>().get<0>()), int&>);
    static_assert(std::is_same_v<decltype(std::declval<const two_element_tuple&>().get<1>()), const char&>);
    static_assert(std::is_same_v<decltype(std::declval<two_element_tuple>().get<0>()), int&&>);
    static_assert(std::is_same_v<decltype(std::declval<two_element_tuple&&>().get<0>()), int&&>);

    void non_literal_type(){
        struct can_throw_constructor {
            can_throw_constructor() { throw std::runtime_error{""}; };
        };
        using faillible_tuple = tuple<can_throw_constructor>;
        [[maybe_unused]] const auto faillible_tuple_default_init = faillible_tuple{};
        [[maybe_unused]] const auto faillible_tuple_value_init = faillible_tuple{can_throw_constructor{}};
    }
}
namespace gcl::mp::tests::tuples::get
{
    using namespace gcl::mp;
    using tuple_type = tuple<int, char>;

    static_assert(std::is_same_v<char&, decltype(std::declval<tuple_type&>().get<1>())>);
    static_assert(std::is_same_v<char&&, decltype(std::declval<tuple_type&&>().get<1>())>);
    static_assert(std::is_same_v<const char&, decltype(std::declval<const tuple_type&>().get<1>())>);
    static_assert(std::is_same_v<const char&&, decltype(std::declval<const tuple_type&&>().get<1>())>);

    static_assert(std::is_same_v<char&, decltype(gcl::mp::get<1>(std::declval<tuple_type&>()))>);
    static_assert(std::is_same_v<char&&, decltype(gcl::mp::get<1>(std::declval<tuple_type&&>()))>);
    static_assert(std::is_same_v<const char&, decltype(gcl::mp::get<1>(std::declval<const tuple_type&>()))>);
    static_assert(std::is_same_v<const char&&, decltype(gcl::mp::get<1>(std::declval<const tuple_type&&>()))>);
}
namespace gcl::mp::tests::tuples::size
{
    using namespace gcl::mp;
    using tuple_type = tuple<int, char>;

    static_assert(tuple<>::size == 0);
    static_assert(tuple<>::size == tuple_size_v<tuple<>>);
    static_assert(tuple_type::size == 2);
    static_assert(tuple_type::size == tuple_size_v<tuple_type>);
}
#endif<commit_msg>[mp/meta/tuple] : tuple_element<commit_after>#pragma once

#include <gcl/mp/meta/functional.hpp>
#include <type_traits>

// todo : filter, apply, for_each, for_each_index

namespace gcl::mp
{
    template <std::size_t index>
    struct type_index {};

    template <typename... types>
    struct tuple {

        constexpr static auto size = sizeof...(types);
        constexpr static auto empty = size == 0;
        template <std::size_t index>
        constexpr static auto valid_index = not empty and index <= (size - 1);

        constexpr tuple() requires(not empty)
            : storage{generate_storage(types{}...)}
        {}
        constexpr tuple(types&&... values)
            : storage{generate_storage(std::forward<decltype(values)>(values)...)}
        {}
        constexpr tuple(tuple&&) = default;

      private:

        // storage : by-pass missing features : auto non-static members, lambdas in unevaluated context
        using index_sequence = std::make_index_sequence<sizeof...(types)>;
        static constexpr auto generate_storage(types&&... values)
        { // defer parameter pack expansion (msvc-cl, Clang)
            return generate_storage_impl(index_sequence{}, std::forward<decltype(values)>(values)...);
        }
        template <std::size_t... indexes>
        static constexpr auto generate_storage_impl(std::index_sequence<indexes...>, types&&... values)
        {
            static_assert(sizeof...(indexes) == sizeof...(types));
            static_assert(sizeof...(indexes) == sizeof...(values));

            const auto generate_storage_entry = []<typename T, std::size_t index>(T && init_value) constexpr
            {
                return [value = init_value](type_index<index>) constexpr mutable noexcept -> auto&& { return value; };
            };
            return gcl::mp::meta::functional::overload{
                generate_storage_entry.template operator()<types, indexes>(std::forward<decltype(values)>(values))...};
        };
        using storage_type = decltype(generate_storage(types{}...));
        mutable storage_type storage;

        template <std::size_t index>
        requires(valid_index<index>)
        struct type_at_impl { // defer symbol (Clang)
            using type = std::remove_reference_t<decltype(std::declval<tuple>().template get<index>())>;
        };

      public:
        template <std::size_t index>
        requires(valid_index<index>)
        using type_at = typename type_at_impl<index>::type;

        template <std::size_t index>
        requires(valid_index<index>)
        constexpr auto& get() & noexcept
        {
            return storage(type_index<index>{});
        }
        template <std::size_t index>
        requires(valid_index<index>) [[nodiscard]] constexpr const auto& get() const& noexcept
        {
            return storage(type_index<index>{});
        }
        template <std::size_t index>
        requires(valid_index<index>) [[nodiscard]] constexpr auto&& get() && noexcept
        {
            return std::move(storage(type_index<index>{}));
        }
        template <std::size_t index>
        requires(valid_index<index>) [[nodiscard]] constexpr const auto&& get() const&& noexcept
        {
            return std::move(storage(type_index<index>{}));
        }

        template <typename... arg_types>
        requires(sizeof...(arg_types) == size) constexpr bool operator==(
            const tuple<arg_types...>& other) const noexcept
        {
            return [ this, &other ]<std::size_t... indexes>(std::index_sequence<indexes...>)
            {
                return (((get<indexes>() == other.template get<indexes>()) && ...));
            }
            (std::make_index_sequence<size>{});
        }
    };
    // When Clang, Msvc-cl gets better, replace `tuple::generate_storage` implementation by :
    /*static constexpr auto generate_storage(types&&... values)
    {
        return [&values...]<std::size_t... indexes>(std::index_sequence<indexes...>)
        {
            static_assert(sizeof...(indexes) == sizeof...(types));
            static_assert(sizeof...(indexes) == sizeof...(values));

            const auto generate_storage_entry = []<typename T, std::size_t index>(T && init_value) constexpr
            {
                return [value = init_value](type_index<index>) mutable -> auto& { return value; };
            };
            return gcl::mp::meta::functional::overload{generate_storage_entry.template operator()<types, indexes>(
                std::forward<decltype(values)>(values))...};
        }
        (std::make_index_sequence<sizeof...(types)>{});
    };*/
}

namespace gcl::mp
{
    template <std::size_t I, class... Types>
    [[nodiscard]] constexpr auto& get(tuple<Types...>& value) noexcept
    {
        return value.template get<I>();
    }
    template <std::size_t I, class... Types>
    [[nodiscard]] constexpr auto&& get(tuple<Types...>&& value) noexcept
    {
        return std::move(value.template get<I>());
    }
    template <std::size_t I, class... Types>
    [[nodiscard]] constexpr auto const& get(const tuple<Types...>& value) noexcept
    {
        return value.template get<I>();
    }
    template <std::size_t I, class... Types>
    [[nodiscard]] constexpr auto const&& get(const tuple<Types...>&& value) noexcept
    {
        return std::move(value.template get<I>());
    }

    template <class tuple_type>
    struct tuple_size;
    template <class... Types>
    struct tuple_size<tuple<Types...>> : std::integral_constant<std::size_t, sizeof...(Types)> {};
    template <class T>
    constexpr auto tuple_size_v = tuple_size<T>::value;

    // how to implement this without recursion ?
    template <std::size_t index, class tuple_type>
    struct tuple_element;
    template <std::size_t index, class first, class... rest>
    struct tuple_element<index, tuple<first, rest...>> : tuple_element<(index - 1), tuple<rest...>> {};
    template <class first, class... rest>
    struct tuple_element<0, tuple<first, rest...>> {
        using type = first;
    };
    template <size_t index>
    struct tuple_element<index, tuple<>> {
        static_assert([]() constexpr { return false; }(), "gcl::mp::tuple : out of range");
    };
    template <std::size_t index, class tuple_type>
    using tuple_element_t = typename tuple_element<index, tuple_type>::type;

    // https://quick-bench.com/q/va85-AzD0ppFuVO6zUTzrC1B6bE
    template <class T, class... Types>
    constexpr T& get(tuple<Types...>& value) noexcept;
    template <class T, class... Types>
    constexpr T&& get(tuple<Types...>&& value) noexcept;
    template <class T, class... Types>
    constexpr const T& get(const tuple<Types...>& value) noexcept;
    template <class T, class... Types>
    constexpr const T&& get(const tuple<Types...>&& value) noexcept;
}

#if defined(GCL_ENABLE_COMPILE_TIME_TESTS)
#include <stdexcept>
#include <exception>
namespace gcl::mp::tests::tuples::values
{
    using namespace gcl::mp;

    using empty_tuple = tuple<>;
    using one_element_tuple = tuple<int>;
    using two_element_tuple = tuple<int, char>;

    static constexpr auto empty_tuple_default_init = empty_tuple{};
    static constexpr auto one_element_tuple_default_init = one_element_tuple{};
    static constexpr auto two_element_tuple_default_init = two_element_tuple{};

    static constexpr auto one_element_tuple_values_init = one_element_tuple{42};
    static constexpr auto two_element_tuple_values_init = two_element_tuple{42, 'a'};

    static_assert(std::is_same_v<tuple<int, char>, decltype(tuple{42, 'a'})>);

    static_assert(std::is_same_v<two_element_tuple::type_at<0>, int>);
    static_assert(std::is_same_v<two_element_tuple::type_at<1>, char>);

    static_assert(std::is_same_v<decltype(std::declval<two_element_tuple&>().get<0>()), int&>);
    static_assert(std::is_same_v<decltype(std::declval<const two_element_tuple&>().get<1>()), const char&>);
    static_assert(std::is_same_v<decltype(std::declval<two_element_tuple>().get<0>()), int&&>);
    static_assert(std::is_same_v<decltype(std::declval<two_element_tuple&&>().get<0>()), int&&>);

    void non_literal_type(){
        struct can_throw_constructor {
            can_throw_constructor() { throw std::runtime_error{""}; };
        };
        using faillible_tuple = tuple<can_throw_constructor>;
        [[maybe_unused]] const auto faillible_tuple_default_init = faillible_tuple{};
        [[maybe_unused]] const auto faillible_tuple_value_init = faillible_tuple{can_throw_constructor{}};
    }
}
namespace gcl::mp::tests::tuples::get
{
    using namespace gcl::mp;
    using tuple_type = tuple<int, char>;

    static_assert(std::is_same_v<char&, decltype(std::declval<tuple_type&>().get<1>())>);
    static_assert(std::is_same_v<char&&, decltype(std::declval<tuple_type&&>().get<1>())>);
    static_assert(std::is_same_v<const char&, decltype(std::declval<const tuple_type&>().get<1>())>);
    static_assert(std::is_same_v<const char&&, decltype(std::declval<const tuple_type&&>().get<1>())>);

    static_assert(std::is_same_v<char&, decltype(gcl::mp::get<1>(std::declval<tuple_type&>()))>);
    static_assert(std::is_same_v<char&&, decltype(gcl::mp::get<1>(std::declval<tuple_type&&>()))>);
    static_assert(std::is_same_v<const char&, decltype(gcl::mp::get<1>(std::declval<const tuple_type&>()))>);
    static_assert(std::is_same_v<const char&&, decltype(gcl::mp::get<1>(std::declval<const tuple_type&&>()))>);
}
namespace gcl::mp::tests::tuples::size
{
    using namespace gcl::mp;
    using tuple_type = tuple<int, char>;

    static_assert(tuple<>::size == 0);
    static_assert(tuple<>::size == tuple_size_v<tuple<>>);
    static_assert(tuple_type::size == 2);
    static_assert(tuple_type::size == tuple_size_v<tuple_type>);
}
namespace gcl::mp::tests::tuples::tuple_element
{
    using namespace gcl::mp;
    using tuple_type = tuple<int, char>;

    static_assert(std::is_same_v<tuple_element_t<0, tuple_type>, int>);
    static_assert(std::is_same_v<tuple_element_t<1, tuple_type>, char>);
}
#endif<|endoftext|>


<commit_before>/******************************************************************************
*	Main script for the 2017 RoboFishy Scripps AUV
******************************************************************************/

#include "Mapper.h"

// Multithreading
#include <pthread.h>
#include <sched.h>
#include <unistd.h>

// Sampling Values
#define SAMPLE_RATE 200 // sample rate of main control loop (Hz)
#define DT 0.005		// timestep; make sure this is equal to 1/SAMPLE_RATE!

// Conversion Factors
#define UNITS_KPA 0.1 // converts pressure from mbar to kPa

/******************************************************************************
* Controller Gains
******************************************************************************/

// Yaw Controller
#define KP_YAW 0.01
#define KI_YAW 0
#define KD_YAW 1

// Depth Controller
#define KP_DEPTH 0
#define KI_DEPTH 0
#define KD_DEPTH 0

// Saturation Constants
#define YAW_SAT 1			// upper limit of yaw controller
#define DEPTH_SAT 1		// upper limit of depth controller
#define INT_SAT 10		// upper limit of integral windup
#define DINT_SAT 10		// upper limit of depth integral windup

// Filter Values
#define A1 0.3			// for MS5837 pressure sensor
#define A2 0.4			// for MS5837 pressure sensor

// Fluid Densities in kg/m^3
#define DENSITY_FRESHWATER 997
#define DENSITY_SALTWATER 1029

// Acceleration Due to Gravity in m/s^2
#define GRAVITY 9.81

// Depth Start Value
#define DEPTH_START 50 // starting depth (mm)

// Stop Timer
#define STOP_TIME 4		// seconds

// Leak Sensor Inpu and Power Pin
#define LEAKPIN 27		// connected to GPIO 27
#define LEAKPOWERPIN 17 // providing Vcc to leak board

/******************************************************************************
 * Declare Threads
******************************************************************************/

void *navigation(void* arg);
void *depth_thread(void* arg);
void *safety_thread(void* arg);

/******************************************************************************
 * Global Variables
******************************************************************************/

// Holds the setpoint data structure with current setpoints
//setpoint_t setpoint;

// Holds the calibration values for the MS5837 pressure sensor
pressure_calib_t pressure_calib;

// Holds the latest pressure value from the MS5837 pressure sensor
ms5837_t ms5837;

// Holds the latest temperature value from the temperature temperature sensor
float temperature;

// Holds the constants and latest errors of the yaw pid controller
pid_data_t yaw_pid;

// Holds the constants and latest errors of the depth pid controller
pid_data_t depth_pid;

// Motor channels
int motor_channels[] = {CHANNEL_1, CHANNEL_2, CHANNEL_3};

// Ignoring sstate
float depth = 0;

 // setmotor intialization
float motor_percent = 0;

/******************************************************************************
* Main Function
******************************************************************************/

int main()
{
	// Initialize Python interpreter
	Py_Initialize();

	// Set up RasPi GPIO pins through wiringPi
	wiringPiSetupGpio();

	// Check if AUV is initialized correctly
	if( initialize_sensors() < 0 )
	{
		return -1;
	}
	printf("\nAll components are initialized\n");
	substate.mode = INITIALIZING;
    substate.laserarmed = ARMED;

	printf("Starting Threads\n");
	initializeTAttr();

	// Thread handles
	//pthread_t navigationThread;
	pthread_t depthThread;
	//pthread_t safetyThread;
	//pthread_t disarmlaserThread;

	// Create threads using modified attributes
	//pthread_create (&disarmlaserThread, &tattrlow, disarmLaser, NULL);
	//pthread_create (&safetyThread, &tattrlow, safety_thread, NULL);
	pthread_create (&depthThread, &tattrmed, depth_thread, NULL);

  // Destroy the thread attributes
 	destroyTAttr();

  printf("Threads started\n");
	// Start timer!
	time_t start = time(0);

	// Run main while loop, wait until it's time to stop
	while(substate.mode != STOPPED)
	{
		// Check if we've passed the stop time
		if(difftime(time(0),start) > STOP_TIME)
			substate.mode = STOPPED;

		// Sleep a little
		usleep(100000);
	}

	// Exit cleanly
	cleanup_auv();
	return 0;
}

/******************************************************************************
* Depth Thread
*
* For Recording Depth & Determining If AUV is in Water or Not
******************************************************************************/

void *depth_thread(void* arg)
{
	printf("Depth Thread Started\n");
	// Initialize pressure sensor
	//pressure_calib = init_pressure_sensor();

	while(substate.mode!=STOPPED)
	{
		printf("IN the depth thread while loop\n");
		// Read pressure sensor by passing calibration structure
		//ms5837 = read_pressure(pressure_calib);

		// Calculate depth (no idea what the magic numbers are)
		//depth = (ms5837.pressure-1013)*10.197-88.8; // units?
		// 1013: ambient pressure (mbar)
		// 10.197*p_mbar = p_mmH20

		//printf("Current Depth:\t %.3f\n",depth);
		//usleep(1000000);

		// read IMU values from fifo file
		substate.imu = read_imu_fifo();

		// Write IMU data
		printf("\nYaw: %f Roll: %f Pitch: %f p: %f q: %f r: %f Sys: %i Gyro: "
			"%i Accel: %i Mag: %i X_acc: %f Y_acc: %f Z_acc: %f\n ",
			 substate.imu.yaw, substate.imu.pitch, substate.imu.roll,
			 substate.imu.p, substate.imu.q, substate.imu.r,
			 substate.imu.sys, substate.imu.gyro, substate.imu.accel,
			 substate.imu.mag, substate.imu.x_acc, substate.imu.y_acc,
			 substate.imu.z_acc);

		sleep(1);
	 	//printf("\nYawPID_err: %f Motor Percent: %f ", yaw_pid.err, motor_percent);
	}

	pthread_exit(NULL);
}//*/

/******************************************************************************
 * Navigation Thread
 *
 * For yaw control
 *****************************************************************************/
/*void *navigation(void* arg)
{
	printf("Nav Thread Started\n");

	initialize_motors(motor_channels, HERTZ);

	float yaw = 0; 			  //Local variable for if statements

	/////////////////yaw controller initialization////////////////////////////////
	yaw_pid.old = 0;	    	// Initialize old imu data
	yaw_pid.setpoint = 0;   // Initialize setpoint

	yaw_pid.derr = 0;
	yaw_pid.ierr = 0;	    	// Initialize error values
	yaw_pid.perr = 0;

	yaw_pid.kp = KP_YAW;
	yaw_pid.kd = KD_YAW;		// Initialize gain values
	yaw_pid.ki = KI_YAW;

	yaw_pid.isat = INT_SAT;	// Initialize saturation values
	yaw_pid.sat  = YAW_SAT;

	yaw_pid.dt   = DT;      // initialize time step

	////////////////depth controller initialization///////////////////////////////
	depth_pid.setpoint = 2; 	// Range-from-bottom setpoint (meters)
	depth_pid.old	   = 0; 		// Initialize old depth
	depth_pid.dt 	   = DT;		// Initialize depth controller time step

	depth_pid.kp = KP_DEPTH;
	depth_pid.kd = KD_DEPTH;	// Depth controller gain initialization
	depth_pid.ki = KI_DEPTH;

	depth_pid.perr = 0;
	depth_pid.ierr = 0;	    	// Initialize depth controller error values
	depth_pid.derr = 0;

	depth_pid.isat = INT_SAT; 	// Depth controller saturation values
	depth_pid.sat  = DEPTH_SAT;

	while(substate.mode!=STOPPED)
	{
		// read IMU values from fifo file
		substate.imu = read_imu_fifo();

	  if (substate.imu.yaw < 180) // AUV pointed right
		{
			yaw = substate.imu.yaw;
		}
		else // AUV pointed left
		{
			yaw =(substate.imu.yaw-360);
		}

		//calculate yaw controller output
		motor_percent = marchPID(substate.imu, yaw);

		// Set port motor
		set_motor(0, motor_percent);

		// Set starboard motor
		set_motor(1, motor_percent);

		// Sleep for 5 ms
		usleep(5000);
	}

	// Turn motors off
	set_motor(0, 0);
	set_motor(1, 0);
	set_motor(2, 0);

	pthread_exit(NULL);
}//*/

/******************************************************************************
 * Safety Thread
 *
 * Shuts down AUV if vehicle goes belows 10m, temperature gets too high, or
 * water intrusion is detected
 *****************************************************************************/
/*void *safety_thread(void* arg)
{
	printf("Safety Thread Started\n");

	// Set up WiringPi for use // (not sure if actually needed)
	wiringPiSetup();

	// Leak detection pins
	pinMode(LEAKPIN, INPUT);					// set LEAKPIN as an INPUT
	pinMode(LEAKPOWERPIN, OUTPUT);		// set as output to provide Vcc
	digitalWrite(LEAKPOWERPIN, HIGH);	// write high to provide Vcc

	// Leak checking variables
	int leakState;	// holds the state (HIGH or LOW) of the LEAKPIN

	// Test if temp sensor reads anything
	temperature = read_temp_fifo();
	printf("Temperature: %f degC\n", temperature);

	while( substate.mode != STOPPED )
	{
		// Check if depth threshold has been exceeded
		if( substate.fdepth > DEPTH_STOP )
		{
			substate.mode = STOPPED;
			printf("We're too deep! Shutting down...\n");
			continue;
		}
		else
		{
			// We're still good
			substate.mode = RUNNING;
		}

		// Check temperature
		// Shut down AUV if housing temperature gets too high

		if( temperature > TEMP_STOP )
		{
			substate.mode = STOPPED;
			printf("It's too hot! Shutting down...\n");
			continue;
		}
		else
		{
			// We're still good
			substate.mode = RUNNING;
		}

		// Check for leak
		leakState = digitalRead(LEAKPIN);	// check the state of LEAKPIN
		if( leakState == HIGH )
		{
			substate.mode = STOPPED;
			printf("LEAK DETECTED! Shutting down...\n");
			continue;
		}
		else if (leakState == LOW)
		{
			// We're still good
			substate.mode = RUNNING;
		}

		// Check IMU accelerometer for collision (1+ g detected)
		if( (float)fabs(substate.imu.x_acc) > 1.0*GRAVITY
			|| (float)fabs(substate.imu.y_acc) > 1.0*GRAVITY
			|| (float)fabs(substate.imu.z_acc) > 1.0*GRAVITY )
		{
			substate.mode = STOPPED;
			printf("Collision detected. Shutting down...");
			continue;
		}
		else
		{
			// We're still good
			substate.mode = RUNNING;
		}

	}
    pthread_exit(NULL);

}//*/

/******************************************************************************
 * Logging Thread
 *
 * Logs the sensor output data into a file
 *****************************************************************************/
/*
PI_THREAD (logging_thread)
{
	while(substate.mode!=STOPPED){
		FILE *fd = fopen("log.txt", "a");
		char buffer[100] = {0};
		// add logging values to the next line
		sprintf(buffer, "%f %f %f %f %i %i %i %i %f %f %f %f\n",sstate.roll, sstate.pitch[0], sstate.yaw[0], sstate.depth[0],sstate.x[0],
		sstate.y[0], sstate.radius[0], setpoint.x - sstate.x[0], sstate.esc_out[0], sstate.esc_out[1], sstate.esc_out[2], sstate.esc_out[3]);
		fputs(buffer, fd);
		fclose(fd);
		//sleep for 100 ms

		usleep(100000);
	}
	return 0;
}
*/
<commit_msg>gasdg<commit_after>/******************************************************************************
*	Main script for the 2017 RoboFishy Scripps AUV
******************************************************************************/

#include "Mapper.h"

// Multithreading
#include <pthread.h>
#include <sched.h>
#include <unistd.h>

// Sampling Values
#define SAMPLE_RATE 200 // sample rate of main control loop (Hz)
#define DT 0.005		// timestep; make sure this is equal to 1/SAMPLE_RATE!

// Conversion Factors
#define UNITS_KPA 0.1 // converts pressure from mbar to kPa

/******************************************************************************
* Controller Gains
******************************************************************************/

// Yaw Controller
#define KP_YAW 0.01
#define KI_YAW 0
#define KD_YAW 1

// Depth Controller
#define KP_DEPTH 0
#define KI_DEPTH 0
#define KD_DEPTH 0

// Saturation Constants
#define YAW_SAT 1			// upper limit of yaw controller
#define DEPTH_SAT 1		// upper limit of depth controller
#define INT_SAT 10		// upper limit of integral windup
#define DINT_SAT 10		// upper limit of depth integral windup

// Filter Values
#define A1 0.3			// for MS5837 pressure sensor
#define A2 0.4			// for MS5837 pressure sensor

// Fluid Densities in kg/m^3
#define DENSITY_FRESHWATER 997
#define DENSITY_SALTWATER 1029

// Acceleration Due to Gravity in m/s^2
#define GRAVITY 9.81

// Depth Start Value
#define DEPTH_START 50 // starting depth (mm)

// Stop Timer
#define STOP_TIME 4		// seconds

// Leak Sensor Inpu and Power Pin
#define LEAKPIN 27		// connected to GPIO 27
#define LEAKPOWERPIN 17 // providing Vcc to leak board

/******************************************************************************
 * Declare Threads
******************************************************************************/

void *navigation(void* arg);
void *depth_thread(void* arg);
void *safety_thread(void* arg);

/******************************************************************************
 * Global Variables
******************************************************************************/

// Holds the setpoint data structure with current setpoints
//setpoint_t setpoint;

// Holds the calibration values for the MS5837 pressure sensor
pressure_calib_t pressure_calib;

// Holds the latest pressure value from the MS5837 pressure sensor
ms5837_t ms5837;

// Holds the latest temperature value from the temperature temperature sensor
float temperature;

// Holds the constants and latest errors of the yaw pid controller
pid_data_t yaw_pid;

// Holds the constants and latest errors of the depth pid controller
pid_data_t depth_pid;

// Motor channels
int motor_channels[] = {CHANNEL_1, CHANNEL_2, CHANNEL_3};

// Ignoring sstate
float depth = 0;

 // setmotor intialization
float motor_percent = 0;

/******************************************************************************
* Main Function
******************************************************************************/

int main()
{
	// Initialize Python interpreter
	Py_Initialize();

	// Set up RasPi GPIO pins through wiringPi
	wiringPiSetupGpio();

	// Check if AUV is initialized correctly
	if( initialize_sensors() < 0 )
	{
		return -1;
	}
	printf("\nAll components are initialized\n");
	substate.mode = INITIALIZING;
    substate.laserarmed = ARMED;

	printf("Starting Threads\n");
	initializeTAttr();

	// Thread handles
	//pthread_t navigationThread;
	pthread_t depthThread;
	//pthread_t safetyThread;
	//pthread_t disarmlaserThread;

	// Create threads using modified attributes
	//pthread_create (&disarmlaserThread, &tattrlow, disarmLaser, NULL);
	//pthread_create (&safetyThread, &tattrlow, safety_thread, NULL);
	pthread_create (&depthThread, &tattrmed, depth_thread, NULL);

  // Destroy the thread attributes
 	destroyTAttr();

  printf("Threads started\n");
	// Start timer!
	time_t start = time(0);

	// Run main while loop, wait until it's time to stop
	while(substate.mode != STOPPED)
	{
		// Check if we've passed the stop time
		if(difftime(time(0),start) > STOP_TIME)
			substate.mode = STOPPED;

		// Sleep a little
		usleep(100000);
	}

	// Exit cleanly
	cleanup_auv();
	return 0;
}

/******************************************************************************
* Depth Thread
*
* For Recording Depth & Determining If AUV is in Water or Not
******************************************************************************/

void *depth_thread(void* arg)
{
	printf("Depth Thread Started\n");
	// Initialize pressure sensor
	//pressure_calib = init_pressure_sensor();

	while(substate.mode!=STOPPED)
	{
		printf("IN the depth thread while loop\n");
		// Read pressure sensor by passing calibration structure
		//ms5837 = read_pressure(pressure_calib);

		// Calculate depth (no idea what the magic numbers are)
		//depth = (ms5837.pressure-1013)*10.197-88.8; // units?
		// 1013: ambient pressure (mbar)
		// 10.197*p_mbar = p_mmH20

		//printf("Current Depth:\t %.3f\n",depth);
		//usleep(1000000);

		// read IMU values from fifo file
		substate.imu = read_imu_fifo();

		// Write IMU data
		//printf("\nYaw: %f Roll: %f Pitch: %f p: %f q: %f r: %f Sys: %i Gyro: "
		//	"%i Accel: %i Mag: %i X_acc: %f Y_acc: %f Z_acc: %f\n ",
		//	 substate.imu.yaw, substate.imu.pitch, substate.imu.roll,
		//	 substate.imu.p, substate.imu.q, substate.imu.r,
		//	 substate.imu.sys, substate.imu.gyro, substate.imu.accel,
		//	 substate.imu.mag, substate.imu.x_acc, substate.imu.y_acc,
		//	 substate.imu.z_acc);

		sleep(1);
	 	printf("\nYawPID_perr: %f Motor Percent: %f ", yaw_pid.perr, motor_percent);
	}

	pthread_exit(NULL);
}//*/

/******************************************************************************
 * Navigation Thread
 *
 * For yaw control
 *****************************************************************************/
void *navigation(void* arg)
{
	printf("Nav Thread Started\n");

	initialize_motors(motor_channels, HERTZ);

	float yaw = 0; 			  //Local variable for if statements

/******************************************************************************
 * Yaw Control Initialization
 *****************************************************************************/
	yaw_pid.old = 0;	    	// Initialize old imu data
	yaw_pid.setpoint = 0;   // Initialize setpoint

	yaw_pid.derr = 0;
	yaw_pid.ierr = 0;	    	// Initialize error values
	yaw_pid.perr = 0;

	yaw_pid.kp = KP_YAW;
	yaw_pid.kd = KD_YAW;		// Initialize gain values
	yaw_pid.ki = KI_YAW;

	yaw_pid.isat = INT_SAT;	// Initialize saturation values
	yaw_pid.sat  = YAW_SAT;

	yaw_pid.dt   = DT;      // initialize time step

/******************************************************************************
 * Depth Control Initialization
 *****************************************************************************/
	depth_pid.setpoint = 2; 	// Range-from-bottom setpoint (meters)
	depth_pid.old	   = 0; 		// Initialize old depth
	depth_pid.dt 	   = DT;		// Initialize depth controller time step

	depth_pid.kp = KP_DEPTH;
	depth_pid.kd = KD_DEPTH;	// Depth controller gain initialization
	depth_pid.ki = KI_DEPTH;

	depth_pid.perr = 0;
	depth_pid.ierr = 0;	    	// Initialize depth controller error values
	depth_pid.derr = 0;

	depth_pid.isat = INT_SAT; 	// Depth controller saturation values
	depth_pid.sat  = DEPTH_SAT;

	while(substate.mode!=STOPPED)
	{
		// read IMU values from fifo file
		substate.imu = read_imu_fifo();

	  if (substate.imu.yaw < 180) // AUV pointed right
		{
			yaw = substate.imu.yaw;
		}
		else // AUV pointed left
		{
			yaw =(substate.imu.yaw-360);
		}

		//calculate yaw controller output
		motor_percent = marchPID(substate.imu, yaw);

		// Set port motor
		set_motor(0, motor_percent);

		// Set starboard motor
		set_motor(1, motor_percent);

		// Sleep for 5 ms
		usleep(5000);
	}

	// Turn motors off
	set_motor(0, 0);
	set_motor(1, 0);
	set_motor(2, 0);

	pthread_exit(NULL);
}//*/

/******************************************************************************
 * Safety Thread
 *
 * Shuts down AUV if vehicle goes belows 10m, temperature gets too high, or
 * water intrusion is detected
 *****************************************************************************/
/*void *safety_thread(void* arg)
{
	printf("Safety Thread Started\n");

	// Set up WiringPi for use // (not sure if actually needed)
	wiringPiSetup();

	// Leak detection pins
	pinMode(LEAKPIN, INPUT);					// set LEAKPIN as an INPUT
	pinMode(LEAKPOWERPIN, OUTPUT);		// set as output to provide Vcc
	digitalWrite(LEAKPOWERPIN, HIGH);	// write high to provide Vcc

	// Leak checking variables
	int leakState;	// holds the state (HIGH or LOW) of the LEAKPIN

	// Test if temp sensor reads anything
	temperature = read_temp_fifo();
	printf("Temperature: %f degC\n", temperature);

	while( substate.mode != STOPPED )
	{
		// Check if depth threshold has been exceeded
		if( substate.fdepth > DEPTH_STOP )
		{
			substate.mode = STOPPED;
			printf("We're too deep! Shutting down...\n");
			continue;
		}
		else
		{
			// We're still good
			substate.mode = RUNNING;
		}

		// Check temperature
		// Shut down AUV if housing temperature gets too high

		if( temperature > TEMP_STOP )
		{
			substate.mode = STOPPED;
			printf("It's too hot! Shutting down...\n");
			continue;
		}
		else
		{
			// We're still good
			substate.mode = RUNNING;
		}

		// Check for leak
		leakState = digitalRead(LEAKPIN);	// check the state of LEAKPIN
		if( leakState == HIGH )
		{
			substate.mode = STOPPED;
			printf("LEAK DETECTED! Shutting down...\n");
			continue;
		}
		else if (leakState == LOW)
		{
			// We're still good
			substate.mode = RUNNING;
		}

		// Check IMU accelerometer for collision (1+ g detected)
		if( (float)fabs(substate.imu.x_acc) > 1.0*GRAVITY
			|| (float)fabs(substate.imu.y_acc) > 1.0*GRAVITY
			|| (float)fabs(substate.imu.z_acc) > 1.0*GRAVITY )
		{
			substate.mode = STOPPED;
			printf("Collision detected. Shutting down...");
			continue;
		}
		else
		{
			// We're still good
			substate.mode = RUNNING;
		}

	}
    pthread_exit(NULL);

}//*/

/******************************************************************************
 * Logging Thread
 *
 * Logs the sensor output data into a file
 *****************************************************************************/
/*
PI_THREAD (logging_thread)
{
	while(substate.mode!=STOPPED){
		FILE *fd = fopen("log.txt", "a");
		char buffer[100] = {0};
		// add logging values to the next line
		sprintf(buffer, "%f %f %f %f %i %i %i %i %f %f %f %f\n",sstate.roll, sstate.pitch[0], sstate.yaw[0], sstate.depth[0],sstate.x[0],
		sstate.y[0], sstate.radius[0], setpoint.x - sstate.x[0], sstate.esc_out[0], sstate.esc_out[1], sstate.esc_out[2], sstate.esc_out[3]);
		fputs(buffer, fd);
		fclose(fd);
		//sleep for 100 ms

		usleep(100000);
	}
	return 0;
}
*/
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _DXCANVAS_WINSTUFF_HXX
#define _DXCANVAS_WINSTUFF_HXX

#include <algorithm>

#include <boost/shared_ptr.hpp>

#include <basegfx/numeric/ftools.hxx>

#ifdef _WINDOWS_
#error someone else included <windows.h>
#endif

// Enabling Direct3D Debug Information Further more, with registry key
// \\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Direct3D\D3D9Debugging\\EnableCreationStack
// set to 1, sets a backtrace each time an object is created to the
// following global variable: LPCWSTR CreationCallStack
#if OSL_DEBUG_LEVEL > 0
# define D3D_DEBUG_INFO
#endif

#ifndef DIRECTX_VERSION
#error please define for which directx version we should compile
#endif

#if defined _MSC_VER
#pragma warning(push,1)
#endif

#define BOOL win32BOOL
#define INT32 win32INT32
#define UINT32 win32UINT32
#define GradientStyle_RECT win32GradientStyle_RECT
#define Polygon win32Polygon
#define PolyPolygon win32PolyPolygon
#undef WB_LEFT
#undef WB_RIGHT

#define WIN32_LEAN_AND_MEAN
#include <windows.h> // TODO(Q1): extract minimal set of required headers for gdiplus

#if DIRECTX_VERSION < 0x0900

    #include <multimon.h>

    // Be compatible with directdraw 3.0. Lets see how far this takes us
    #define DIRECTDRAW_VERSION 0x0300
    #include <ddraw.h>

    // Be compatible with direct3d 5.0. Lets see how far this takes us
    #define DIRECT3D_VERSION 0x0500
    #define D3D_OVERLOADS
    #include <d3d.h>

    typedef IDirectDrawSurface surface_type;

#else

    #include <d3d9.h>
    #include <d3dx9.h>
//  #include <dxerr9.h>     #i107614# removing include, it has been changed in the latest sdk fron August2009 from dxerr9.h into dxerr.h

    typedef IDirect3DSurface9 surface_type;

#endif

#undef DrawText

#ifdef __MINGW32__
using ::std::max;
using ::std::min;
#endif

#include <gdiplus.h>

#ifdef min
#   undef min
#endif
#ifdef max
#   undef max
#endif

namespace dxcanvas
{
    // some shared pointer typedefs to Gdiplus objects
    typedef ::boost::shared_ptr< Gdiplus::Graphics >        GraphicsSharedPtr;
    typedef ::boost::shared_ptr< Gdiplus::GraphicsPath >    GraphicsPathSharedPtr;
    typedef ::boost::shared_ptr< Gdiplus::Bitmap >          BitmapSharedPtr;
    typedef ::boost::shared_ptr< Gdiplus::CachedBitmap >    CachedBitmapSharedPtr;
    typedef ::boost::shared_ptr< Gdiplus::Font >            FontSharedPtr;
    typedef ::boost::shared_ptr< Gdiplus::Brush >           BrushSharedPtr;
    typedef ::boost::shared_ptr< Gdiplus::TextureBrush >    TextureBrushSharedPtr;

    /** COM object RAII wrapper

        This template wraps a Windows COM object, transparently
        handling lifetime issues the C++ way (i.e. releasing the
        reference when the object is destroyed)
     */
    template< typename T > class COMReference
    {
    public:
        typedef T Wrappee;

        COMReference() :
            mp( NULL )
        {
        }

        /** Create from raw pointer

            @attention This constructor assumes the interface is
            already acquired (unless p is NULL), no additional AddRef
            is called here.

            This caters e.g. for all DirectX factory methods, which
            return the created interfaces pre-acquired, into a raw
            pointer. Simply pass the pointer to this class, but don't
            call Release manually on it!

            @example IDirectDrawSurface* pSurface;
            pDD->CreateSurface(&aSurfaceDesc, &pSurface, NULL);
            mpSurface = COMReference< IDirectDrawSurface >(pSurface);

         */
        explicit COMReference( T* p ) :
            mp( p )
        {
        }

        COMReference( const COMReference& rNew ) :
            mp( NULL )
        {
            if( rNew.mp == NULL )
                return;

            rNew.mp->AddRef(); // do that _before_ assigning the
                               // pointer. Just in case...
            mp = rNew.mp;
        }

        COMReference& operator=( const COMReference& rRHS )
        {
            COMReference aTmp(rRHS);
            ::std::swap( mp, aTmp.mp );

            return *this;
        }

        ~COMReference()
        {
            reset();
        }

        int reset()
        {
            int refcount = 0;
            if( mp )
                refcount = mp->Release();

            mp = NULL;
            return refcount;
        }

        bool        is() const { return mp != NULL; }
        T*          get() const { return mp; }
        T*          operator->() const { return mp; }
        T&          operator*() const { return *mp; }

    private:
        T*  mp;
    };

    // get_pointer() enables boost::mem_fn to recognize COMReference
    template<class T> inline T * get_pointer(COMReference<T> const& p)
    {
        return p.get();
    }
}

#if defined _MSC_VER
#pragma warning(pop)
#endif

#undef DELETE
#undef BOOL
#undef INT32
#undef UINT32
#undef PolyPolygon

#endif /* _DXCANVAS_WINSTUFF_HXX */
<commit_msg>win32-dxsdk-200908.diff: Build also against DirectX SDK August 2009.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _DXCANVAS_WINSTUFF_HXX
#define _DXCANVAS_WINSTUFF_HXX

#include <algorithm>

#include <boost/shared_ptr.hpp>

#include <basegfx/numeric/ftools.hxx>

#ifdef _WINDOWS_
#error someone else included <windows.h>
#endif

// Enabling Direct3D Debug Information Further more, with registry key
// \\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Direct3D\D3D9Debugging\\EnableCreationStack
// set to 1, sets a backtrace each time an object is created to the
// following global variable: LPCWSTR CreationCallStack
#if OSL_DEBUG_LEVEL > 0
# define D3D_DEBUG_INFO
#endif

#ifndef DIRECTX_VERSION
#error please define for which directx version we should compile
#endif

#if defined _MSC_VER
#pragma warning(push,1)
#endif

#define BOOL win32BOOL
#define INT32 win32INT32
#define UINT32 win32UINT32
#define GradientStyle_RECT win32GradientStyle_RECT
#define Polygon win32Polygon
#define PolyPolygon win32PolyPolygon
#undef WB_LEFT
#undef WB_RIGHT

#define WIN32_LEAN_AND_MEAN
#include <windows.h> // TODO(Q1): extract minimal set of required headers for gdiplus

#if DIRECTX_VERSION < 0x0900

    #include <multimon.h>

    // Be compatible with directdraw 3.0. Lets see how far this takes us
    #define DIRECTDRAW_VERSION 0x0300
    #include <ddraw.h>

    // Be compatible with direct3d 5.0. Lets see how far this takes us
    #define DIRECT3D_VERSION 0x0500
    #define D3D_OVERLOADS
    #include <d3d.h>

    typedef IDirectDrawSurface surface_type;

#else

    #include <dxsdkver.h>
    #include <d3d9.h>
    #include <d3dx9.h>
    #if _DXSDK_BUILD_MAJOR < 1734 /* Earlier than the August 2009 DXSDK */
        #include <dxerr9.h>
    #else
        #include <dxerr.h>
    #endif

    typedef IDirect3DSurface9 surface_type;

#endif

#undef DrawText

#ifdef __MINGW32__
using ::std::max;
using ::std::min;
#endif

#include <gdiplus.h>

#ifdef min
#   undef min
#endif
#ifdef max
#   undef max
#endif

namespace dxcanvas
{
    // some shared pointer typedefs to Gdiplus objects
    typedef ::boost::shared_ptr< Gdiplus::Graphics >        GraphicsSharedPtr;
    typedef ::boost::shared_ptr< Gdiplus::GraphicsPath >    GraphicsPathSharedPtr;
    typedef ::boost::shared_ptr< Gdiplus::Bitmap >          BitmapSharedPtr;
    typedef ::boost::shared_ptr< Gdiplus::CachedBitmap >    CachedBitmapSharedPtr;
    typedef ::boost::shared_ptr< Gdiplus::Font >            FontSharedPtr;
    typedef ::boost::shared_ptr< Gdiplus::Brush >           BrushSharedPtr;
    typedef ::boost::shared_ptr< Gdiplus::TextureBrush >    TextureBrushSharedPtr;

    /** COM object RAII wrapper

        This template wraps a Windows COM object, transparently
        handling lifetime issues the C++ way (i.e. releasing the
        reference when the object is destroyed)
     */
    template< typename T > class COMReference
    {
    public:
        typedef T Wrappee;

        COMReference() :
            mp( NULL )
        {
        }

        /** Create from raw pointer

            @attention This constructor assumes the interface is
            already acquired (unless p is NULL), no additional AddRef
            is called here.

            This caters e.g. for all DirectX factory methods, which
            return the created interfaces pre-acquired, into a raw
            pointer. Simply pass the pointer to this class, but don't
            call Release manually on it!

            @example IDirectDrawSurface* pSurface;
            pDD->CreateSurface(&aSurfaceDesc, &pSurface, NULL);
            mpSurface = COMReference< IDirectDrawSurface >(pSurface);

         */
        explicit COMReference( T* p ) :
            mp( p )
        {
        }

        COMReference( const COMReference& rNew ) :
            mp( NULL )
        {
            if( rNew.mp == NULL )
                return;

            rNew.mp->AddRef(); // do that _before_ assigning the
                               // pointer. Just in case...
            mp = rNew.mp;
        }

        COMReference& operator=( const COMReference& rRHS )
        {
            COMReference aTmp(rRHS);
            ::std::swap( mp, aTmp.mp );

            return *this;
        }

        ~COMReference()
        {
            reset();
        }

        int reset()
        {
            int refcount = 0;
            if( mp )
                refcount = mp->Release();

            mp = NULL;
            return refcount;
        }

        bool        is() const { return mp != NULL; }
        T*          get() const { return mp; }
        T*          operator->() const { return mp; }
        T&          operator*() const { return *mp; }

    private:
        T*  mp;
    };

    // get_pointer() enables boost::mem_fn to recognize COMReference
    template<class T> inline T * get_pointer(COMReference<T> const& p)
    {
        return p.get();
    }
}

#if defined _MSC_VER
#pragma warning(pop)
#endif

#undef DELETE
#undef BOOL
#undef INT32
#undef UINT32
#undef PolyPolygon

#endif /* _DXCANVAS_WINSTUFF_HXX */
<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015-2016 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "version.h"

const TCHAR* PluginVersionString = _T("0.1.4-alpha");
<commit_msg>Bump plugin version to 0.1.5-alpha<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015-2016 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "version.h"

const TCHAR* PluginVersionString = _T("0.1.5-alpha");
<|endoftext|>


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

#include "nsdl.h"
#include "nme.h"
#include <stack>
#include <string.h>
#include <SDL_ttf.h>

#include <windows.h>
#include <gl/GL.h>

using namespace std;

// helper functions

DEFINE_KIND( k_surf );
DEFINE_KIND( k_snd );
DEFINE_KIND( k_mus );

SDL_Surface* nme_loadimage( value file )
{
	val_check( file, string );

	SDL_Surface* surf;
	surf = IMG_Load( val_string( file ) );
	if ( !surf )
		surf = SDL_LoadBMP( val_string( file ) );
	if ( !surf )
		return NULL;
	//SDL_Surface *surface = SDL_DisplayFormat( surf );
  	//SDL_FreeSurface( surf );
	return surf;
}

// creates a surface with alpha channel
value nme_create_image_32( value flags, value width, value height )
{
	val_check( flags, int );
	val_check( width, int );
	val_check( height, int );

//	return alloc_abstract( k_surf, sge_CreateAlphaSurface( val_int( flags ), val_int( width ), val_int( height ) ) );
	return alloc_int(0);
}

value nme_copy_surface( value surf )
{
	return alloc_int(0);
	/*
	val_check_kind( surf, k_surf );

	SDL_Surface* scr = SURFACE(surf);

	return alloc_abstract( k_surf, sge_copy_surface( scr ) );
	*/
}

// surface relative functions

static value nme_surface_clear( value surf, value c )
{
	val_check_kind( surf, k_surf );

	val_check( c, int );
	SDL_Surface* scr = SURFACE(surf);

	Uint8 r = RRGB( c );
	Uint8 g = GRGB( c );
	Uint8 b = BRGB( c );

	SDL_FillRect( scr, NULL, SDL_MapRGB( scr->format, r, g, b ) );

	return alloc_int( 0 );

}

void nme_surface_free( value surface )
{
	if ( val_is_kind( surface, k_surf ) )
	{
		val_gc( surface, NULL );

		SDL_Surface* surf = SURFACE( surface );
		SDL_FreeSurface( surf );
	}
}

value nme_surface_colourkey( value surface, value r, value g, value b )
{
	val_check_kind( surface, k_surf );
	val_check( r, int );
	val_check( g, int );
	val_check( b, int );

	SDL_Surface* surf = SURFACE( surface );
	if( !surf )
		return alloc_bool( false );
	unsigned int key = SDL_MapRGB( surf->format, val_int( r ), val_int( g ), val_int( b ) );
	SDL_SetColorKey( surf, SDL_RLEACCEL | SDL_SRCCOLORKEY, key );
	return alloc_bool( true );
}

// screen relative functions

static bool sOpenGL = false;

value nme_delay( value period )
{
	val_check( period, int );
	SDL_Delay( val_int( period ) );
	return alloc_int( 0 );
}

value nme_flipbuffer( value buff )
{
   if (sOpenGL)
   {
	SDL_GL_SwapBuffers();
   }
   else
   {
	val_check_kind( buff, k_surf );

	SDL_Surface* srf = SURFACE( buff );
	SDL_Flip( srf );
	SDL_Delay( 1 );
   }

    return alloc_int( 0 );
}

value nme_swapbuffer()
{
	return alloc_int( 0 );
}

value nme_screen_flip()
{
	value o = val_this();
	val_check( o, object );
	nme_flipbuffer( val_field( o, val_id( "screen" ) ) );
	return alloc_int( 0 );
}

#define NME_FULLSCREEN 0x0001
#define NME_OPENGL     0x0002

value nme_screen_init( value width, value height, value title, value in_flags, value icon )
{
	val_check( in_flags, int );
        bool fullscreen = (val_int(in_flags) & NME_FULLSCREEN) != 0;
        bool opengl = (val_int(in_flags) & NME_OPENGL) != 0;

        sOpenGL = opengl;

        Uint32 init_flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER;
        if (opengl)
           init_flags |= SDL_OPENGL;
	if ( SDL_Init( init_flags ) == -1 ) failure( SDL_GetError() );

	val_check( width, int );
	val_check( height, int );
	val_check( title, string );

	Uint32 flags = opengl ? SDL_HWSURFACE | SDL_OPENGL :
	                        SDL_HWSURFACE | SDL_DOUBLEBUF;
	int bpp = 24;

        if ( fullscreen )
        {
                flags |= SDL_FULLSCREEN;
                if (!opengl)
                    bpp = 16;
        }

	if ( val_is_string( icon ) )
	{
		SDL_Surface *icn = nme_loadimage( icon );
		if ( icn != NULL )
		{
			SDL_WM_SetIcon( icn, NULL );
		}
	}

        SDL_Surface* screen = 0;
        if (opengl)
        {
            int rgb_size[3];
            /* Initialize the display */
            switch (bpp)
            {
            case 8:
                rgb_size[0] = 2;
                rgb_size[1] = 3;
                rgb_size[2] = 3;
                break;
            case 15:
            case 16:
                rgb_size[0] = 5;
                rgb_size[1] = 5;
                rgb_size[2] = 5;
                break;
            default:
                rgb_size[0] = 8;
                rgb_size[1] = 8;
                rgb_size[2] = 8;
                break;
            }
            SDL_GL_SetAttribute(SDL_GL_RED_SIZE, rgb_size[0]);
            SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, rgb_size[1]);
            SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, rgb_size[2]);
            SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, bpp);
            SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

            if ( (screen = SDL_SetVideoMode( val_int( width ), val_int( height ), bpp, flags )) == NULL)
            {
                fprintf(stderr, "Couldn't set GL mode: %s\n", SDL_GetError());
                SDL_Quit();
                exit(1);
            }
        }
        else
        {
        	screen = SDL_SetVideoMode( val_int( width ), val_int( height ), bpp, flags );
	        if (!screen) failure( SDL_GetError() );

        }

	if ( TTF_Init() != 0 )
		printf("unable to initialize the truetype font support\n");

	SDL_WM_SetCaption( val_string( title ), 0 );

	if ( Mix_OpenAudio( MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 4096 ) != 0 )
		printf("unable to initialize the sound support\n");

	return alloc_abstract( k_surf, screen );
}

value nme_event()
{
	SDL_Event event;
	value evt = alloc_object(NULL);

	if (SDL_PollEvent(&event))
	{
		if (event.type == SDL_QUIT)
		{
			alloc_field( evt, val_id( "type" ), alloc_int( et_quit ) );
			return alloc_object( evt );
		}
		if (event.type == SDL_KEYDOWN)
		{
			alloc_field( evt, val_id( "type" ), alloc_int( et_keydown ) );
			alloc_field( evt, val_id( "key" ), alloc_int( event.key.keysym.sym ) );
			alloc_field( evt, val_id( "shift" ), alloc_bool( event.key.keysym.mod & KMOD_SHIFT ) );
			alloc_field( evt, val_id( "ctrl" ), alloc_bool( event.key.keysym.mod & KMOD_CTRL ) );
			alloc_field( evt, val_id( "alt" ), alloc_bool( event.key.keysym.mod & KMOD_ALT ) );
			return alloc_object( evt );
		}
		if (event.type == SDL_KEYUP)
		{
			alloc_field( evt, val_id( "type" ), alloc_int( et_keyup ) );
			alloc_field( evt, val_id( "key" ), alloc_int( event.key.keysym.sym ) );
			alloc_field( evt, val_id( "shift" ), alloc_bool( event.key.keysym.mod & KMOD_SHIFT ) );
			alloc_field( evt, val_id( "ctrl" ), alloc_bool( event.key.keysym.mod & KMOD_CTRL ) );
			alloc_field( evt, val_id( "alt" ), alloc_bool( event.key.keysym.mod & KMOD_ALT ) );
			return alloc_object( evt );
		}
		if (event.type == SDL_MOUSEMOTION)
		{
			alloc_field( evt, val_id( "type" ), alloc_int( et_motion ) );
			alloc_field( evt, val_id( "state" ), alloc_int( event.motion.state ) );
			alloc_field( evt, val_id( "x" ), alloc_int( event.motion.x ) );
			alloc_field( evt, val_id( "y" ), alloc_int( event.motion.y ) );
			alloc_field( evt, val_id( "xrel" ), alloc_int( event.motion.xrel ) );
			alloc_field( evt, val_id( "yrel" ), alloc_int( event.motion.yrel ) );
			return alloc_object( evt );
		}
		if (event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP)
		{
			alloc_field( evt, val_id( "type" ), alloc_int( et_button ) );
			alloc_field( evt, val_id( "state" ), alloc_int( event.button.state ) );
			alloc_field( evt, val_id( "x" ), alloc_int( event.button.x ) );
			alloc_field( evt, val_id( "y" ), alloc_int( event.button.y ) );
			alloc_field( evt, val_id( "which" ), alloc_int( event.button.which ) );
			alloc_field( evt, val_id( "button" ), alloc_int( event.button.button ) );
			return alloc_object( evt );
		}
		if (event.type == SDL_JOYAXISMOTION)
		{
			alloc_field( evt, val_id( "type" ), alloc_int( et_jaxis ) );
			alloc_field( evt, val_id( "axis" ), alloc_int( event.jaxis.axis ) );
			alloc_field( evt, val_id( "value" ), alloc_int( event.jaxis.value ) );
			alloc_field( evt, val_id( "which" ), alloc_int( event.jaxis.which ) );
			return alloc_object( evt );
		}
		if (event.type == SDL_JOYBUTTONDOWN || event.type == SDL_JOYBUTTONUP)
		{
			alloc_field( evt, val_id( "type" ), alloc_int( et_jbutton ) );
			alloc_field( evt, val_id( "button" ), alloc_int( event.jbutton.button ) );
			alloc_field( evt, val_id( "state" ), alloc_int( event.jbutton.state ) );
			alloc_field( evt, val_id( "which" ), alloc_int( event.jbutton.which ) );
			return alloc_object( evt );
		}
		if (event.type == SDL_JOYHATMOTION)
		{
			alloc_field( evt, val_id( "type" ), alloc_int( et_jhat ) );
			alloc_field( evt, val_id( "button" ), alloc_int( event.jhat.hat ) );
			alloc_field( evt, val_id( "value" ), alloc_int( event.jhat.value ) );
			alloc_field( evt, val_id( "which" ), alloc_int( event.jhat.which ) );
			return alloc_object( evt );
		}
		if (event.type == SDL_JOYBALLMOTION)
		{
			alloc_field( evt, val_id( "type" ), alloc_int( et_jball ) );
			alloc_field( evt, val_id( "ball" ), alloc_int( event.jball.ball ) );
			alloc_field( evt, val_id( "xrel" ), alloc_int( event.jball.xrel ) );
			alloc_field( evt, val_id( "yrel" ), alloc_int( event.jball.yrel ) );
			alloc_field( evt, val_id( "which" ), alloc_int( event.jball.which ) );
			return alloc_object( evt );
		}
	}
	alloc_field( evt, val_id( "type" ), alloc_int( et_noevent ) );
	return evt;
}

value nme_screen_close()
{
	Mix_CloseAudio();
	//sge_TTF_Quit();
	SDL_Quit();
	return alloc_int( 0 );
}

DEFINE_PRIM(nme_event, 0);
DEFINE_PRIM(nme_delay, 1);
DEFINE_PRIM(nme_flipbuffer, 1);

DEFINE_PRIM(nme_create_image_32,3);
DEFINE_PRIM(nme_copy_surface,1);

DEFINE_PRIM(nme_screen_init, 5);
DEFINE_PRIM(nme_screen_close, 0);

DEFINE_PRIM(nme_surface_clear, 2);
DEFINE_PRIM(nme_surface_free, 1);
DEFINE_PRIM(nme_surface_colourkey, 4);
<commit_msg>Added width and height<commit_after>/*
 * Copyright (c) 2006, Lee McColl Sylvester - www.designrealm.co.uk
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE HAXE PROJECT CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE HAXE PROJECT CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 */

#include "nsdl.h"
#include "nme.h"
#include <stack>
#include <string.h>
#include <SDL_ttf.h>

#include <windows.h>
#include <gl/GL.h>

using namespace std;

// helper functions

DEFINE_KIND( k_surf );
DEFINE_KIND( k_snd );
DEFINE_KIND( k_mus );

SDL_Surface* nme_loadimage( value file )
{
	val_check( file, string );

	SDL_Surface* surf;
	surf = IMG_Load( val_string( file ) );
	if ( !surf )
		surf = SDL_LoadBMP( val_string( file ) );
	if ( !surf )
		return NULL;
	//SDL_Surface *surface = SDL_DisplayFormat( surf );
  	//SDL_FreeSurface( surf );
	return surf;
}

// creates a surface with alpha channel
value nme_create_image_32( value flags, value width, value height )
{
	val_check( flags, int );
	val_check( width, int );
	val_check( height, int );

//	return alloc_abstract( k_surf, sge_CreateAlphaSurface( val_int( flags ), val_int( width ), val_int( height ) ) );
	return alloc_int(0);
}

value nme_copy_surface( value surf )
{
	return alloc_int(0);
	/*
	val_check_kind( surf, k_surf );

	SDL_Surface* scr = SURFACE(surf);

	return alloc_abstract( k_surf, sge_copy_surface( scr ) );
	*/
}

// surface relative functions

static value nme_surface_clear( value surf, value c )
{
	val_check_kind( surf, k_surf );

	val_check( c, int );
	SDL_Surface* scr = SURFACE(surf);

	Uint8 r = RRGB( c );
	Uint8 g = GRGB( c );
	Uint8 b = BRGB( c );

	SDL_FillRect( scr, NULL, SDL_MapRGB( scr->format, r, g, b ) );

	return alloc_int( 0 );

}

value nme_surface_width( value surface )
{
	val_check_kind( surface, k_surf );

	SDL_Surface* surf = SURFACE(surface);
        return alloc_int(surf->w);
}

value nme_surface_height( value surface )
{
	val_check_kind( surface, k_surf );

	SDL_Surface* surf = SURFACE(surface);
        return alloc_int(surf->h);
}

void nme_surface_free( value surface )
{
	if ( val_is_kind( surface, k_surf ) )
	{
		val_gc( surface, NULL );

		SDL_Surface* surf = SURFACE( surface );
		SDL_FreeSurface( surf );
	}
}

value nme_surface_colourkey( value surface, value r, value g, value b )
{
	val_check_kind( surface, k_surf );
	val_check( r, int );
	val_check( g, int );
	val_check( b, int );

	SDL_Surface* surf = SURFACE( surface );
	if( !surf )
		return alloc_bool( false );
	unsigned int key = SDL_MapRGB( surf->format, val_int( r ), val_int( g ), val_int( b ) );
	SDL_SetColorKey( surf, SDL_RLEACCEL | SDL_SRCCOLORKEY, key );
	return alloc_bool( true );
}

// screen relative functions

static bool sOpenGL = false;

value nme_delay( value period )
{
	val_check( period, int );
	SDL_Delay( val_int( period ) );
	return alloc_int( 0 );
}

value nme_flipbuffer( value buff )
{
   if (sOpenGL)
   {
	SDL_GL_SwapBuffers();
   }
   else
   {
	val_check_kind( buff, k_surf );

	SDL_Surface* srf = SURFACE( buff );
	SDL_Flip( srf );
	SDL_Delay( 1 );
   }

    return alloc_int( 0 );
}

value nme_swapbuffer()
{
	return alloc_int( 0 );
}

value nme_screen_flip()
{
	value o = val_this();
	val_check( o, object );
	nme_flipbuffer( val_field( o, val_id( "screen" ) ) );
	return alloc_int( 0 );
}

#define NME_FULLSCREEN 0x0001
#define NME_OPENGL     0x0002

value nme_screen_init( value width, value height, value title, value in_flags, value icon )
{
	val_check( in_flags, int );
        bool fullscreen = (val_int(in_flags) & NME_FULLSCREEN) != 0;
        bool opengl = (val_int(in_flags) & NME_OPENGL) != 0;

        sOpenGL = opengl;

        Uint32 init_flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER;
        if (opengl)
           init_flags |= SDL_OPENGL;
	if ( SDL_Init( init_flags ) == -1 ) failure( SDL_GetError() );

	val_check( width, int );
	val_check( height, int );
	val_check( title, string );

	Uint32 flags = opengl ? SDL_HWSURFACE | SDL_OPENGL :
	                        SDL_HWSURFACE | SDL_DOUBLEBUF;
	int bpp = 24;

        if ( fullscreen )
        {
                flags |= SDL_FULLSCREEN;
                if (!opengl)
                    bpp = 16;
        }

	if ( val_is_string( icon ) )
	{
		SDL_Surface *icn = nme_loadimage( icon );
		if ( icn != NULL )
		{
			SDL_WM_SetIcon( icn, NULL );
		}
	}

        SDL_Surface* screen = 0;
        if (opengl)
        {
            int rgb_size[3];
            /* Initialize the display */
            switch (bpp)
            {
            case 8:
                rgb_size[0] = 2;
                rgb_size[1] = 3;
                rgb_size[2] = 3;
                break;
            case 15:
            case 16:
                rgb_size[0] = 5;
                rgb_size[1] = 5;
                rgb_size[2] = 5;
                break;
            default:
                rgb_size[0] = 8;
                rgb_size[1] = 8;
                rgb_size[2] = 8;
                break;
            }
            SDL_GL_SetAttribute(SDL_GL_RED_SIZE, rgb_size[0]);
            SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, rgb_size[1]);
            SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, rgb_size[2]);
            SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, bpp);
            SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

            if ( (screen = SDL_SetVideoMode( val_int( width ), val_int( height ), bpp, flags )) == NULL)
            {
                fprintf(stderr, "Couldn't set GL mode: %s\n", SDL_GetError());
                SDL_Quit();
                exit(1);
            }
        }
        else
        {
        	screen = SDL_SetVideoMode( val_int( width ), val_int( height ), bpp, flags );
	        if (!screen) failure( SDL_GetError() );

        }

	if ( TTF_Init() != 0 )
		printf("unable to initialize the truetype font support\n");

	SDL_WM_SetCaption( val_string( title ), 0 );

	if ( Mix_OpenAudio( MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 4096 ) != 0 )
		printf("unable to initialize the sound support\n");

	return alloc_abstract( k_surf, screen );
}

value nme_event()
{
	SDL_Event event;
	value evt = alloc_object(NULL);

	if (SDL_PollEvent(&event))
	{
		if (event.type == SDL_QUIT)
		{
			alloc_field( evt, val_id( "type" ), alloc_int( et_quit ) );
			return alloc_object( evt );
		}
		if (event.type == SDL_KEYDOWN)
		{
			alloc_field( evt, val_id( "type" ), alloc_int( et_keydown ) );
			alloc_field( evt, val_id( "key" ), alloc_int( event.key.keysym.sym ) );
			alloc_field( evt, val_id( "shift" ), alloc_bool( event.key.keysym.mod & KMOD_SHIFT ) );
			alloc_field( evt, val_id( "ctrl" ), alloc_bool( event.key.keysym.mod & KMOD_CTRL ) );
			alloc_field( evt, val_id( "alt" ), alloc_bool( event.key.keysym.mod & KMOD_ALT ) );
			return alloc_object( evt );
		}
		if (event.type == SDL_KEYUP)
		{
			alloc_field( evt, val_id( "type" ), alloc_int( et_keyup ) );
			alloc_field( evt, val_id( "key" ), alloc_int( event.key.keysym.sym ) );
			alloc_field( evt, val_id( "shift" ), alloc_bool( event.key.keysym.mod & KMOD_SHIFT ) );
			alloc_field( evt, val_id( "ctrl" ), alloc_bool( event.key.keysym.mod & KMOD_CTRL ) );
			alloc_field( evt, val_id( "alt" ), alloc_bool( event.key.keysym.mod & KMOD_ALT ) );
			return alloc_object( evt );
		}
		if (event.type == SDL_MOUSEMOTION)
		{
			alloc_field( evt, val_id( "type" ), alloc_int( et_motion ) );
			alloc_field( evt, val_id( "state" ), alloc_int( event.motion.state ) );
			alloc_field( evt, val_id( "x" ), alloc_int( event.motion.x ) );
			alloc_field( evt, val_id( "y" ), alloc_int( event.motion.y ) );
			alloc_field( evt, val_id( "xrel" ), alloc_int( event.motion.xrel ) );
			alloc_field( evt, val_id( "yrel" ), alloc_int( event.motion.yrel ) );
			return alloc_object( evt );
		}
		if (event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP)
		{
			alloc_field( evt, val_id( "type" ), alloc_int( et_button ) );
			alloc_field( evt, val_id( "state" ), alloc_int( event.button.state ) );
			alloc_field( evt, val_id( "x" ), alloc_int( event.button.x ) );
			alloc_field( evt, val_id( "y" ), alloc_int( event.button.y ) );
			alloc_field( evt, val_id( "which" ), alloc_int( event.button.which ) );
			alloc_field( evt, val_id( "button" ), alloc_int( event.button.button ) );
			return alloc_object( evt );
		}
		if (event.type == SDL_JOYAXISMOTION)
		{
			alloc_field( evt, val_id( "type" ), alloc_int( et_jaxis ) );
			alloc_field( evt, val_id( "axis" ), alloc_int( event.jaxis.axis ) );
			alloc_field( evt, val_id( "value" ), alloc_int( event.jaxis.value ) );
			alloc_field( evt, val_id( "which" ), alloc_int( event.jaxis.which ) );
			return alloc_object( evt );
		}
		if (event.type == SDL_JOYBUTTONDOWN || event.type == SDL_JOYBUTTONUP)
		{
			alloc_field( evt, val_id( "type" ), alloc_int( et_jbutton ) );
			alloc_field( evt, val_id( "button" ), alloc_int( event.jbutton.button ) );
			alloc_field( evt, val_id( "state" ), alloc_int( event.jbutton.state ) );
			alloc_field( evt, val_id( "which" ), alloc_int( event.jbutton.which ) );
			return alloc_object( evt );
		}
		if (event.type == SDL_JOYHATMOTION)
		{
			alloc_field( evt, val_id( "type" ), alloc_int( et_jhat ) );
			alloc_field( evt, val_id( "button" ), alloc_int( event.jhat.hat ) );
			alloc_field( evt, val_id( "value" ), alloc_int( event.jhat.value ) );
			alloc_field( evt, val_id( "which" ), alloc_int( event.jhat.which ) );
			return alloc_object( evt );
		}
		if (event.type == SDL_JOYBALLMOTION)
		{
			alloc_field( evt, val_id( "type" ), alloc_int( et_jball ) );
			alloc_field( evt, val_id( "ball" ), alloc_int( event.jball.ball ) );
			alloc_field( evt, val_id( "xrel" ), alloc_int( event.jball.xrel ) );
			alloc_field( evt, val_id( "yrel" ), alloc_int( event.jball.yrel ) );
			alloc_field( evt, val_id( "which" ), alloc_int( event.jball.which ) );
			return alloc_object( evt );
		}
	}
	alloc_field( evt, val_id( "type" ), alloc_int( et_noevent ) );
	return evt;
}

value nme_screen_close()
{
	Mix_CloseAudio();
	//sge_TTF_Quit();
	SDL_Quit();
	return alloc_int( 0 );
}

DEFINE_PRIM(nme_event, 0);
DEFINE_PRIM(nme_delay, 1);
DEFINE_PRIM(nme_flipbuffer, 1);

DEFINE_PRIM(nme_create_image_32,3);
DEFINE_PRIM(nme_copy_surface,1);

DEFINE_PRIM(nme_screen_init, 5);
DEFINE_PRIM(nme_screen_close, 0);

DEFINE_PRIM(nme_surface_clear, 2);
DEFINE_PRIM(nme_surface_free, 1);
DEFINE_PRIM(nme_surface_width, 1);
DEFINE_PRIM(nme_surface_height, 1);
DEFINE_PRIM(nme_surface_colourkey, 4);
<|endoftext|>


<commit_before>/*****************************************************************************
 * Project: RooFit                                                           *
 * Package: RooFitCore                                                       *
 *    File: $Id: makedocs.cc,v 1.11 2002/09/05 04:34:04 verkerke Exp $
 * Authors:                                                                  *
 *   WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu       *
 *   DK, David Kirkby,    UC Irvine,         dkirkby@uci.edu                 *
 *                                                                           *
 * Copyright (c) 2000-2002, Regents of the University of California          *
 *                          and Stanford University. All rights reserved.    *
 *                                                                           *
 * Redistribution and use in source and binary forms,                        *
 * with or without modification, are permitted according to the terms        *
 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)             *
 *****************************************************************************/

void makedocs(const char *version="Development", const char *where= "./html", Bool_t doTutorial=kFALSE)
{
  const char *bfarch= gSystem->Getenv("BFARCH");
  TString sourceDir("RELEASE/RooFitCore:RELEASE/tmp/");
  sourceDir.Append(bfarch);
  sourceDir.Append("/RooFitCore");
  gEnv->SetValue("Root.Html.SourceDir",sourceDir.Data());
  gEnv->SetValue("Root.Html.OutputDir",where);
  gEnv->SetValue("Root.Html.Description","// -- CLASS DESCRIPTION");
  gEnv->SetValue("Root.Html.LastUpdate"," *    File: $Id: ");

  RooHtml docMaker(version);
  docMaker.setHeaderColor("#FFFFFF") ;

  if (doTutorial) {
    docMaker.Convert("intro1.cc","Elementary operations on a gaussian PDF") ;
    docMaker.Convert("intro2.cc","Building more complex PDFs via addition") ;
    docMaker.Convert("intro3.cc","Adding more dimensions, multiplying PDFs") ;
    docMaker.Convert("intro4.cc","Extend PDFs via composition") ;
    docMaker.Convert("intro5.cc","Discrete variables") ;
    docMaker.Convert("intro6.cc","Convoluted PDFs") ;
    docMaker.Convert("intro7.cc","Extended likelihood PDFs") ;
    docMaker.Convert("intro8.cc","Dataset operations") ;
    docMaker.Convert("intro9.cc","Observables vs parameters") ;
    docMaker.Convert("plot1.cc","Using variable binning") ;
    docMaker.Convert("plot2.cc","Plotting a PDF projection on a subset of the event sample") ;
    docMaker.Convert("plot3.cc","Plotting with a cut on the projected likelihood") ;
    docMaker.Convert("plot4.cc","Plotting slices of simultaneous PDFs") ;
    docMaker.Convert("mgmt1.cc","BMixing with per-event errors") ;
    docMaker.Convert("mgmt2.cc","Using RooSimPdfBuilder to replicate and customize PDFs") ;
    docMaker.Convert("mgmt3.cc","Blinding parameters") ;
    docMaker.Convert("fitgen1.cc","Interactive MINUIT") ;
    docMaker.Convert("fitgen2.cc","Adding penalty functions/Langrange multipliers") ;
    docMaker.Convert("fitgen3.cc","NLL versus Chi2 fits") ;
  }

  docMaker.MakeAll(kTRUE,"Roo*");
  docMaker.MakeIndexNew("Roo*");

  docMaker.addTopic("PDF","Probability Density functions") ;
  docMaker.addTopic("REAL","Real valued functions") ;
  docMaker.addTopic("CAT","Discrete valued functions") ;
  docMaker.addTopic("DATA","Unbinned and binned data") ;
  docMaker.addTopic("PLOT","Plotting and tabulating") ;
  docMaker.addTopic("CONT","Container classes") ;
  docMaker.addTopic("MISC","Miscellaneous") ;
  docMaker.addTopic("USER","Other user classes") ;
  docMaker.addTopic("AUX","Auxiliary classes for internal use") ;
  docMaker.MakeIndexOfTopics() ;
}
<commit_msg><commit_after>/*****************************************************************************
 * Project: RooFit                                                           *
 * Package: RooFitCore                                                       *
 *    File: $Id: makedocs.cc,v 1.12 2002/09/17 06:39:35 verkerke Exp $
 * Authors:                                                                  *
 *   WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu       *
 *   DK, David Kirkby,    UC Irvine,         dkirkby@uci.edu                 *
 *                                                                           *
 * Copyright (c) 2000-2002, Regents of the University of California          *
 *                          and Stanford University. All rights reserved.    *
 *                                                                           *
 * Redistribution and use in source and binary forms,                        *
 * with or without modification, are permitted according to the terms        *
 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)             *
 *****************************************************************************/

void makedocs(const char *version="Development", const char *where= "./html", Bool_t doTutorial=kFALSE)
{
  const char *bfarch= gSystem->Getenv("BFARCH");
  TString sourceDir("RELEASE/RooFitCore:RELEASE/tmp/");
  sourceDir.Append(bfarch);
  sourceDir.Append("/RooFitCore");
  gEnv->SetValue("Root.Html.SourceDir",sourceDir.Data());
  gEnv->SetValue("Root.Html.OutputDir",where);
  gEnv->SetValue("Root.Html.Description","// -- CLASS DESCRIPTION");
  gEnv->SetValue("Root.Html.LastUpdate"," *    File: $Id: ");

  RooHtml docMaker(version);
  docMaker.setHeaderColor("#FFFFFF") ;

  if (doTutorial) {
    docMaker.Convert("intro1.cc","Elementary operations on a gaussian PDF") ;
    docMaker.Convert("intro2.cc","Building more complex PDFs via addition") ;
    docMaker.Convert("intro3.cc","Adding more dimensions, multiplying PDFs") ;
    docMaker.Convert("intro4.cc","Extend PDFs via composition") ;
    docMaker.Convert("intro5.cc","Discrete variables") ;
    docMaker.Convert("intro6.cc","Convoluted PDFs") ;
    docMaker.Convert("intro7.cc","Extended likelihood PDFs") ;
    docMaker.Convert("intro8.cc","Dataset operations") ;
    docMaker.Convert("intro9.cc","Observables vs parameters") ;
    docMaker.Convert("plot1.cc","Using variable binning") ;
    docMaker.Convert("plot2.cc","Plotting a PDF projection on a subset of the event sample") ;
    docMaker.Convert("plot3.cc","Plotting with a cut on the projected likelihood") ;
    docMaker.Convert("plot4.cc","Plotting slices of simultaneous PDFs") ;
    docMaker.Convert("mgmt1.cc","BMixing with per-event errors") ;
    docMaker.Convert("mgmt2.cc","Using RooSimPdfBuilder to replicate and customize PDFs") ;
    docMaker.Convert("mgmt3.cc","Blinding parameters") ;
    docMaker.Convert("fitgen1.cc","Interactive MINUIT") ;
    docMaker.Convert("fitgen2.cc","Adding penalty functions/Langrange multipliers") ;
    docMaker.Convert("fitgen3.cc","NLL versus Chi2 fits") ;
  }

  docMaker.MakeAll(kTRUE,"Roo*");
  docMaker.MakeIndexNew("Roo*");

  docMaker.addTopic("PDF","Probability Density functions") ;
  docMaker.addTopic("REAL","Real valued functions") ;
  docMaker.addTopic("CAT","Discrete valued functions") ;
  docMaker.addTopic("DATA","Unbinned and binned data") ;
  docMaker.addTopic("PLOT","Plotting and tabulating") ;
  docMaker.addTopic("CONT","Container classes") ;
  docMaker.addTopic("MISC","Miscellaneous") ;
  docMaker.addTopic("USER","Other user classes") ;
  docMaker.addTopic("AUX","Auxiliary classes for internal use") ;
  docMaker.MakeIndexOfTopics() ;
}

<|endoftext|>