<commit_before>/*
 *  SystemFunctions.cpp
 *  OpenLieroX
 *
 *  Created by Albert Zeyer on 01.12.09.
 *  code under LGPL
 *
 */

#include <iomanip>
#include <time.h>
#include <SDL.h>
#define Font Font_Xlib // Hack to prevent name clash in precompiled header
#include <SDL_syswm.h>
#undef Font
#ifdef REAL_OPENGL
#include <SDL_opengl.h>
#endif
#include <cstdlib>
#include <sstream>
#include <cstring>

#if defined(__APPLE__)
#include <mach/host_info.h>
#include <mach/mach_host.h>
#include <mach/mach_init.h>
#include <sys/sysctl.h>
#include <mach/mach_traps.h>
#elif defined(WIN32) || defined(WIN64)
#include <windows.h>
#else
#include <cstdio>
#include <unistd.h>
#endif

#ifdef __FREEBSD__
#include <sys/sysctl.h>
#include <vm/vm_param.h>
#include <sys/vmmeter.h>
#endif

#ifndef WIN32
#include <sys/types.h>
#include <sys/resource.h>
#include <unistd.h>
#include <signal.h>
#endif

#include "StringUtils.h"
#include "ThreadPool.h"
#include "util/macros.h"

#if !defined(WIN32) || defined(HAVE_PTHREAD)
#include <pthread.h>
#ifndef HAVE_PTHREAD
#define HAVE_PTHREAD
#endif

#ifndef HAVE_PTHREAD_NAME
// pthread_setname_np only available since MacOSX SDK 10.6
#if defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
#define HAVE_PTHREAD_NAME
// glibc 2.12 introduced this
#elif __GLIBC_PREREQ(2,12)
#define HAVE_PTHREAD_NAME
#endif
#endif

#endif

#ifdef THREADNAME_VIA_SIGUSR1
static void setCurThreadName__signalraiser(const char* name) {
#ifndef _MSC_VER
	// this signal is only for debuggers, we should ignore it
	signal( SIGUSR1, SIG_IGN );

	// KDevelop will catch this, read the 'name' parameter and continue execution
	raise( SIGUSR1 );
#endif
}
#endif

ThreadId getCurrentThreadId() {
#ifdef HAVE_PTHREAD
	return (ThreadId) pthread_self();
#else
	// SDL_ThreadID returns a Uint32.
	// On 64bit systems, this might not be enough information about the current thread.
	// Win64 thread HANDLE is 64bit, aswell as pthread_t.
	return (ThreadId) SDL_ThreadID();
#endif
}

//////////////////
// Gives a name to the thread
// Code taken from http://www.codeproject.com/KB/threads/Name_threads_in_debugger.aspx
void setCurThreadName(const std::string& name)
{
#ifdef _MSC_VER // Currently only for MSVC, haven't found a Windows-general way (I doubt there is one)
	typedef struct tagTHREADNAME_INFO
	{
		DWORD dwType; // Must be 0x1000.
		LPCSTR szName; // Pointer to name (in user addr space).
		DWORD dwThreadID; // Thread ID (-1=caller thread).
		DWORD dwFlags; // Reserved for future use, must be zero.
	} THREADNAME_INFO;

	THREADNAME_INFO info;
	{
		info.dwType = 0x1000;
		info.szName = name.c_str();
		info.dwThreadID = (DWORD)-1;
		info.dwFlags = 0;
	}

	__try
	{
		RaiseException( 0x406D1388 /* MSVC EXCEPTION */, 0, sizeof(info)/sizeof(DWORD), (DWORD*)&info );
	}
	__except (EXCEPTION_CONTINUE_EXECUTION)
	{
	}
#endif

#ifdef THREADNAME_VIA_SIGUSR1
	setCurThreadName__signalraiser(name.c_str());
#endif

#ifdef HAVE_PTHREAD_NAME
	pthread_setname_np(pthread_self(), name.c_str());
#endif
}

std::string getThreadName(ThreadId tid) {
#ifdef HAVE_PTHREAD_NAME
	char buf[128] = "\0";
	if(pthread_getname_np((pthread_t) tid, buf, sizeof(buf)) == 0)
		if(strlen(buf) > 0)
			return buf;
#endif

	if(threadPool) {
		std::map<ThreadId, std::string> threads;
		threadPool->getAllWorkingThreads(threads);
		foreach(t, threads) {
			if(t->first == tid)
				return t->second;
		}
	}

	return "";
}

void setCurThreadPriority(float p) {
#ifdef WIN32

#elif defined(__APPLE__)
	//int curp = getpriority(PRIO_DARWIN_THREAD, 0);
	//int newp = p >= 0 ? 0 : 1;
	//notes << "curp:" << curp << ", newp:" << newp << endl;
	//setpriority(PRIO_DARWIN_THREAD, 0, newp);
#endif
}

size_t GetFreeSysMemory() {
#if defined(__APPLE__)
	vm_statistics_data_t page_info;
	vm_size_t pagesize;
	mach_msg_type_number_t count;
	kern_return_t kret;

	pagesize = 0;
	kret = host_page_size (mach_host_self(), &pagesize);
	count = HOST_VM_INFO_COUNT;

	kret = host_statistics (mach_host_self(), HOST_VM_INFO,(host_info_t)&page_info, &count);
	return page_info.free_count * pagesize;
#elif defined(__WIN64__)
	MEMORYSTATUSEX memStatex;
	memStatex.dwLength = sizeof (memStatex);
	::GlobalMemoryStatusEx (&memStatex);
	return memStatex.ullAvailPhys;
#elif defined(__WIN32__)
	MEMORYSTATUS memStatus;
	memStatus.dwLength = sizeof(MEMORYSTATUS);
	::GlobalMemoryStatus(&memStatus);
	return memStatus.dwAvailPhys;
#elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
	return sysconf(_SC_AVPHYS_PAGES) * sysconf(_SC_PAGESIZE);
#elif defined(__FREEBSD__)
	int vm_vmtotal[] = { CTL_VM, VM_METER };
	struct vmtotal vmdata;

	size_t len = sizeof(vmdata);
	int result = sysctl(vm_vmtotal, sizeof(vm_vmtotal) / sizeof(*vm_vmtotal), &vmdata, &len, NULL, 0);
	if(result != 0) return 0;

	return vmdata.t_free * sysconf(_SC_PAGESIZE);
#elif defined(__linux__)

	// get it from /proc/meminfo
	FILE *fp = fopen("/proc/meminfo", "r");
	if ( fp )
	{
		unsigned long freeMem = 0;
		unsigned long buffersMem = 0;
		unsigned long cachedMem = 0;
		struct SearchTerm { const char* name; unsigned long* var; };
		SearchTerm terms[] = { {"MemFree:", &freeMem}, {"Buffers:", &buffersMem}, {"Cached:", &cachedMem} };

		char buf[1024];
		int n = fread(buf, sizeof(char), sizeof(buf) - 1, fp);
		buf[sizeof(buf)-1] = '\0';
		if(n > 0) {
			for(unsigned int i = 0; i < sizeof(terms) / sizeof(SearchTerm); ++i) {
				char* p = strstr(buf, terms[i].name);
				if(p) {
					p += strlen(terms[i].name);
					*terms[i].var = strtoul(p, NULL, 10);
				}
			}
		}

		fclose(fp);
		// it's written in KB in meminfo
		return ((size_t)freeMem + (size_t)buffersMem + (size_t)cachedMem) * 1024;
	}

	return 0;
#else
#warning No GetFreeSysMemory implementation for this arch/sys
	return 50 * 1024 * 1024; // return 50 MB (really randomly made up, but helps for cache system)
#endif
}

std::string GetDateTimeText()
{
	time_t t = time(NULL);

	if (t == (time_t)-1)
		return "TIME-ERROR1";

	char* timeCstr = ctime(&t);
	if(timeCstr == NULL)
		return "TIME-ERROR2";

	std::string timeStr(timeCstr);
	TrimSpaces(timeStr);
	return timeStr;
}

std::string GetDateTimeFilename()
{
	// Add date and server name to screenshot filename
	time_t curtime1 = time(NULL);
	if (curtime1 == (time_t)-1)
		return "TIME-ERROR1";
	struct tm *curtime = localtime(&curtime1);
	if (curtime == NULL)
		return "TIME-ERROR2";
	char filePrefixTime[200] = {0};
	strftime(filePrefixTime, sizeof(filePrefixTime), "%Y%m%d-%H%M", curtime);
	return filePrefixTime;
}

<commit_msg>small fix<commit_after>/*
 *  SystemFunctions.cpp
 *  OpenLieroX
 *
 *  Created by Albert Zeyer on 01.12.09.
 *  code under LGPL
 *
 */

#include <iomanip>
#include <time.h>
#include <SDL.h>
#define Font Font_Xlib // Hack to prevent name clash in precompiled header
#include <SDL_syswm.h>
#undef Font
#ifdef REAL_OPENGL
#include <SDL_opengl.h>
#endif
#include <cstdlib>
#include <sstream>
#include <cstring>

#if defined(__APPLE__)
#include <mach/host_info.h>
#include <mach/mach_host.h>
#include <mach/mach_init.h>
#include <sys/sysctl.h>
#include <mach/mach_traps.h>
#elif defined(WIN32) || defined(WIN64)
#include <windows.h>
#else
#include <cstdio>
#include <unistd.h>
#endif

#ifdef __FREEBSD__
#include <sys/sysctl.h>
#include <vm/vm_param.h>
#include <sys/vmmeter.h>
#endif

#ifndef WIN32
#include <sys/types.h>
#include <sys/resource.h>
#include <unistd.h>
#include <signal.h>
#endif

#include "StringUtils.h"
#include "ThreadPool.h"
#include "util/macros.h"

#if !defined(WIN32) || defined(HAVE_PTHREAD)
#include <pthread.h>
#ifndef HAVE_PTHREAD
#define HAVE_PTHREAD
#endif

#ifndef HAVE_PTHREAD_NAME
// pthread_setname_np only available since MacOSX SDK 10.6
#if defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
#define HAVE_PTHREAD_NAME
// glibc 2.12 introduced this
#elif __GLIBC_PREREQ(2,12)
#define HAVE_PTHREAD_NAME
#endif
#endif

#endif

#ifdef THREADNAME_VIA_SIGUSR1
static void setCurThreadName__signalraiser(const char* name) {
#ifndef _MSC_VER
	// this signal is only for debuggers, we should ignore it
	signal( SIGUSR1, SIG_IGN );

	// KDevelop will catch this, read the 'name' parameter and continue execution
	raise( SIGUSR1 );
#endif
}
#endif

ThreadId getCurrentThreadId() {
#ifdef HAVE_PTHREAD
	return (ThreadId) pthread_self();
#else
	// SDL_ThreadID returns a Uint32.
	// On 64bit systems, this might not be enough information about the current thread.
	// Win64 thread HANDLE is 64bit, aswell as pthread_t.
	return (ThreadId) SDL_ThreadID();
#endif
}

//////////////////
// Gives a name to the thread
// Code taken from http://www.codeproject.com/KB/threads/Name_threads_in_debugger.aspx
void setCurThreadName(const std::string& name)
{
#ifdef _MSC_VER // Currently only for MSVC, haven't found a Windows-general way (I doubt there is one)
	typedef struct tagTHREADNAME_INFO
	{
		DWORD dwType; // Must be 0x1000.
		LPCSTR szName; // Pointer to name (in user addr space).
		DWORD dwThreadID; // Thread ID (-1=caller thread).
		DWORD dwFlags; // Reserved for future use, must be zero.
	} THREADNAME_INFO;

	THREADNAME_INFO info;
	{
		info.dwType = 0x1000;
		info.szName = name.c_str();
		info.dwThreadID = (DWORD)-1;
		info.dwFlags = 0;
	}

	__try
	{
		RaiseException( 0x406D1388 /* MSVC EXCEPTION */, 0, sizeof(info)/sizeof(DWORD), (DWORD*)&info );
	}
	__except (EXCEPTION_CONTINUE_EXECUTION)
	{
	}
#endif

#ifdef THREADNAME_VIA_SIGUSR1
	setCurThreadName__signalraiser(name.c_str());
#endif

#ifdef HAVE_PTHREAD_NAME
// http://stackoverflow.com/questions/2369738/can-i-set-the-name-of-a-thread-in-pthreads-linux/7989973#7989973
#ifdef __APPLE__
	pthread_setname_np(name.c_str());
#else
	pthread_setname_np(pthread_self(), name.c_str());
#endif
#endif
}

std::string getThreadName(ThreadId tid) {
#ifdef HAVE_PTHREAD_NAME
	char buf[128] = "\0";
	if(pthread_getname_np((pthread_t) tid, buf, sizeof(buf)) == 0)
		if(strlen(buf) > 0)
			return buf;
#endif

	if(threadPool) {
		std::map<ThreadId, std::string> threads;
		threadPool->getAllWorkingThreads(threads);
		foreach(t, threads) {
			if(t->first == tid)
				return t->second;
		}
	}

	return "";
}

void setCurThreadPriority(float p) {
#ifdef WIN32

#elif defined(__APPLE__)
	//int curp = getpriority(PRIO_DARWIN_THREAD, 0);
	//int newp = p >= 0 ? 0 : 1;
	//notes << "curp:" << curp << ", newp:" << newp << endl;
	//setpriority(PRIO_DARWIN_THREAD, 0, newp);
#endif
}

size_t GetFreeSysMemory() {
#if defined(__APPLE__)
	vm_statistics_data_t page_info;
	vm_size_t pagesize;
	mach_msg_type_number_t count;
	kern_return_t kret;

	pagesize = 0;
	kret = host_page_size (mach_host_self(), &pagesize);
	count = HOST_VM_INFO_COUNT;

	kret = host_statistics (mach_host_self(), HOST_VM_INFO,(host_info_t)&page_info, &count);
	return page_info.free_count * pagesize;
#elif defined(__WIN64__)
	MEMORYSTATUSEX memStatex;
	memStatex.dwLength = sizeof (memStatex);
	::GlobalMemoryStatusEx (&memStatex);
	return memStatex.ullAvailPhys;
#elif defined(__WIN32__)
	MEMORYSTATUS memStatus;
	memStatus.dwLength = sizeof(MEMORYSTATUS);
	::GlobalMemoryStatus(&memStatus);
	return memStatus.dwAvailPhys;
#elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
	return sysconf(_SC_AVPHYS_PAGES) * sysconf(_SC_PAGESIZE);
#elif defined(__FREEBSD__)
	int vm_vmtotal[] = { CTL_VM, VM_METER };
	struct vmtotal vmdata;

	size_t len = sizeof(vmdata);
	int result = sysctl(vm_vmtotal, sizeof(vm_vmtotal) / sizeof(*vm_vmtotal), &vmdata, &len, NULL, 0);
	if(result != 0) return 0;

	return vmdata.t_free * sysconf(_SC_PAGESIZE);
#elif defined(__linux__)

	// get it from /proc/meminfo
	FILE *fp = fopen("/proc/meminfo", "r");
	if ( fp )
	{
		unsigned long freeMem = 0;
		unsigned long buffersMem = 0;
		unsigned long cachedMem = 0;
		struct SearchTerm { const char* name; unsigned long* var; };
		SearchTerm terms[] = { {"MemFree:", &freeMem}, {"Buffers:", &buffersMem}, {"Cached:", &cachedMem} };

		char buf[1024];
		int n = fread(buf, sizeof(char), sizeof(buf) - 1, fp);
		buf[sizeof(buf)-1] = '\0';
		if(n > 0) {
			for(unsigned int i = 0; i < sizeof(terms) / sizeof(SearchTerm); ++i) {
				char* p = strstr(buf, terms[i].name);
				if(p) {
					p += strlen(terms[i].name);
					*terms[i].var = strtoul(p, NULL, 10);
				}
			}
		}

		fclose(fp);
		// it's written in KB in meminfo
		return ((size_t)freeMem + (size_t)buffersMem + (size_t)cachedMem) * 1024;
	}

	return 0;
#else
#warning No GetFreeSysMemory implementation for this arch/sys
	return 50 * 1024 * 1024; // return 50 MB (really randomly made up, but helps for cache system)
#endif
}

std::string GetDateTimeText()
{
	time_t t = time(NULL);

	if (t == (time_t)-1)
		return "TIME-ERROR1";

	char* timeCstr = ctime(&t);
	if(timeCstr == NULL)
		return "TIME-ERROR2";

	std::string timeStr(timeCstr);
	TrimSpaces(timeStr);
	return timeStr;
}

std::string GetDateTimeFilename()
{
	// Add date and server name to screenshot filename
	time_t curtime1 = time(NULL);
	if (curtime1 == (time_t)-1)
		return "TIME-ERROR1";
	struct tm *curtime = localtime(&curtime1);
	if (curtime == NULL)
		return "TIME-ERROR2";
	char filePrefixTime[200] = {0};
	strftime(filePrefixTime, sizeof(filePrefixTime), "%Y%m%d-%H%M", curtime);
	return filePrefixTime;
}

<|endoftext|>


<commit_before>#include <vector>
#include <iomanip>
#include <cassert>
#include <iostream>
#include <algorithm>

#include "test.hpp"

#include "cppa/cppa.hpp"
#include "cppa/opencl.hpp"

using namespace std;
using namespace cppa;
using namespace cppa::opencl;

namespace {

using ivec = vector<int>;

constexpr size_t matrix_size = 4;
constexpr const char* kernel_name = "matrix_square";

constexpr const char* kernel_source = R"__(
    __kernel void matrix_square(__global int* matrix,
                                __global int* output) {
        size_t size = get_global_size(0); // == get_global_size_(1);
        size_t x = get_global_id(0);
        size_t y = get_global_id(1);
        int result = 0;
        for (size_t idx = 0; idx < size; ++idx) {
            result += matrix[idx + y * size] * matrix[x + idx * size];
        }
        output[x + y * size] = result;
    }
)__";

constexpr const char* kernel_source_error = R"__(
    __kernel void matrix_square(__global int*) {
        size_t semicolon
    }
)__";

}

template<size_t Size>
class square_matrix {

 public:

    static constexpr size_t num_elements = Size * Size;

    square_matrix(square_matrix&&) = default;
    square_matrix(const square_matrix&) = default;
    square_matrix& operator=(square_matrix&&) = default;
    square_matrix& operator=(const square_matrix&) = default;

    square_matrix() : m_data(num_elements) { }

    explicit square_matrix(ivec d) : m_data(move(d)) {
        assert(m_data.size() == num_elements);
    }

    inline float& operator()(size_t column, size_t row) {
        return m_data[column + row * Size];
    }

    inline const float& operator()(size_t column, size_t row) const {
        return m_data[column + row * Size];
    }

    inline void iota_fill() {
        iota(m_data.begin(), m_data.end(), 0);
    }

    typedef typename ivec::const_iterator const_iterator;

    const_iterator begin() const { return m_data.begin(); }

    const_iterator end() const { return m_data.end(); }

    ivec& data() { return m_data; }

    const ivec& data() const { return m_data; }

 private:

    ivec m_data;

};

template<size_t Size>
inline bool operator==(const square_matrix<Size>& lhs,
                       const square_matrix<Size>& rhs) {
    return equal(lhs.begin(), lhs.end(), rhs.begin());
}

template<size_t Size>
inline bool operator!=(const square_matrix<Size>& lhs,
                       const square_matrix<Size>& rhs) {
    return !(lhs == rhs);
}

using matrix_type = square_matrix<matrix_size>;

int main() {
    CPPA_TEST(test_opencl);

    announce<ivec>();
    announce<matrix_type>();

    const ivec expected1{ 56, 62, 68, 74
                        , 152, 174, 196, 218
                        , 248, 286, 324, 362
                        , 344, 398, 452, 506};

    auto worker1 = spawn_cl<ivec(ivec&)>(program::create(kernel_source),
                                         kernel_name,
                                         {matrix_size, matrix_size});
    ivec m1(matrix_size * matrix_size);
    iota(m1.begin(), m1.end(), 0);
    send(worker1, move(m1));
    receive (
        on_arg_match >> [&] (const ivec& result) {
            CPPA_CHECK(equal(begin(expected1), end(expected1), begin(result)));
        }
    );

    auto worker2 = spawn_cl<ivec(ivec&)>(kernel_source,
                                         kernel_name,
                                         {matrix_size, matrix_size});
    ivec m2(matrix_size * matrix_size);
    iota(m2.begin(), m2.end(), 0);
    send(worker2, move(m2));
    receive (
        on_arg_match >> [&] (const ivec& result) {
            CPPA_CHECK(equal(begin(expected1), end(expected1), begin(result)));
        }
    );

    const matrix_type expected2(move(expected1));

    auto map_args = [] (any_tuple msg) -> optional<cow_tuple<ivec>> {
        auto opt = tuple_cast<matrix_type>(msg);
        if (opt) {
            return {make_cow_tuple(move(get_ref<0>(*opt).data()))};
        }
        return {};
    };

    auto map_results = [] (ivec& result) -> any_tuple {
        return make_any_tuple(matrix_type{move(result)});
    };

    matrix_type m3;
    m3.iota_fill();
    auto worker3 = spawn_cl(program::create(kernel_source), kernel_name,
                            map_args, map_results,
                            {matrix_size, matrix_size});
    send(worker3, move(m3));
    receive (
        on_arg_match >> [&] (const matrix_type& result) {
            CPPA_CHECK(expected2 == result);
        }
    );

    matrix_type m4;
    m4.iota_fill();
    auto worker4 = spawn_cl(kernel_source, kernel_name,
                            map_args, map_results,
                            {matrix_size, matrix_size}
    );
    send(worker4, move(m4));
    receive (
        on_arg_match >> [&] (const matrix_type& result) {
            CPPA_CHECK(expected2 == result);
        }
    );

    try {
        program create_error = program::create(kernel_source_error);
    }
    catch (const exception& exc) {
        cout << exc.what() << endl;
        CPPA_CHECK_EQUAL("clBuildProgram: CL_BUILD_PROGRAM_FAILURE", exc.what());
    }

    cppa::await_all_others_done();
    cppa::shutdown();

    return CPPA_TEST_RESULT();
}
<commit_msg>fixed opencl unit test<commit_after>#include <vector>
#include <iomanip>
#include <cassert>
#include <iostream>
#include <algorithm>

#include "test.hpp"

#include "cppa/cppa.hpp"
#include "cppa/opencl.hpp"

using namespace std;
using namespace cppa;
using namespace cppa::opencl;

namespace {

using ivec = vector<int>;

constexpr size_t matrix_size = 4;
constexpr const char* kernel_name = "matrix_square";

constexpr const char* kernel_source = R"__(
    __kernel void matrix_square(__global int* matrix,
                                __global int* output) {
        size_t size = get_global_size(0); // == get_global_size_(1);
        size_t x = get_global_id(0);
        size_t y = get_global_id(1);
        int result = 0;
        for (size_t idx = 0; idx < size; ++idx) {
            result += matrix[idx + y * size] * matrix[x + idx * size];
        }
        output[x + y * size] = result;
    }
)__";

constexpr const char* kernel_source_error = R"__(
    __kernel void matrix_square(__global int*) {
        size_t semicolon
    }
)__";

}

template<size_t Size>
class square_matrix {

 public:

    static constexpr size_t num_elements = Size * Size;

    square_matrix(square_matrix&&) = default;
    square_matrix(const square_matrix&) = default;
    square_matrix& operator=(square_matrix&&) = default;
    square_matrix& operator=(const square_matrix&) = default;

    square_matrix() : m_data(num_elements) { }

    explicit square_matrix(ivec d) : m_data(move(d)) {
        assert(m_data.size() == num_elements);
    }

    inline float& operator()(size_t column, size_t row) {
        return m_data[column + row * Size];
    }

    inline const float& operator()(size_t column, size_t row) const {
        return m_data[column + row * Size];
    }

    inline void iota_fill() {
        iota(m_data.begin(), m_data.end(), 0);
    }

    typedef typename ivec::const_iterator const_iterator;

    const_iterator begin() const { return m_data.begin(); }

    const_iterator end() const { return m_data.end(); }

    ivec& data() { return m_data; }

    const ivec& data() const { return m_data; }

 private:

    ivec m_data;

};

template<size_t Size>
inline bool operator==(const square_matrix<Size>& lhs,
                       const square_matrix<Size>& rhs) {
    return equal(lhs.begin(), lhs.end(), rhs.begin());
}

template<size_t Size>
inline bool operator!=(const square_matrix<Size>& lhs,
                       const square_matrix<Size>& rhs) {
    return !(lhs == rhs);
}

using matrix_type = square_matrix<matrix_size>;

int main() {
    CPPA_TEST(test_opencl);

    announce<ivec>();
    announce<matrix_type>();

    const ivec expected1{ 56, 62, 68, 74
                        , 152, 174, 196, 218
                        , 248, 286, 324, 362
                        , 344, 398, 452, 506};

    auto worker1 = spawn_cl<ivec(ivec&)>(program::create(kernel_source),
                                         kernel_name,
                                         {matrix_size, matrix_size});
    ivec m1(matrix_size * matrix_size);
    iota(m1.begin(), m1.end(), 0);
    send(worker1, move(m1));
    receive (
        on_arg_match >> [&] (const ivec& result) {
            CPPA_CHECK(equal(begin(expected1), end(expected1), begin(result)));
        }
    );

    auto worker2 = spawn_cl<ivec(ivec&)>(kernel_source,
                                         kernel_name,
                                         {matrix_size, matrix_size});
    ivec m2(matrix_size * matrix_size);
    iota(m2.begin(), m2.end(), 0);
    send(worker2, move(m2));
    receive (
        on_arg_match >> [&] (const ivec& result) {
            CPPA_CHECK(equal(begin(expected1), end(expected1), begin(result)));
        }
    );

    const matrix_type expected2(move(expected1));

    auto map_args = [] (any_tuple msg) -> optional<cow_tuple<ivec>> {
        auto opt = tuple_cast<matrix_type>(msg);
        if (opt) {
            return make_cow_tuple(move(get_ref<0>(*opt).data()));
        }
        return none;
    };

    auto map_results = [] (ivec& result) -> any_tuple {
        return make_any_tuple(matrix_type{move(result)});
    };

    matrix_type m3;
    m3.iota_fill();
    auto worker3 = spawn_cl(program::create(kernel_source), kernel_name,
                            map_args, map_results,
                            {matrix_size, matrix_size});
    send(worker3, move(m3));
    receive (
        on_arg_match >> [&] (const matrix_type& result) {
            CPPA_CHECK(expected2 == result);
        }
    );

    matrix_type m4;
    m4.iota_fill();
    auto worker4 = spawn_cl(kernel_source, kernel_name,
                            map_args, map_results,
                            {matrix_size, matrix_size}
    );
    send(worker4, move(m4));
    receive (
        on_arg_match >> [&] (const matrix_type& result) {
            CPPA_CHECK(expected2 == result);
        }
    );

    try {
        program create_error = program::create(kernel_source_error);
    }
    catch (const exception& exc) {
        cout << exc.what() << endl;
        CPPA_CHECK_EQUAL("clBuildProgram: CL_BUILD_PROGRAM_FAILURE", exc.what());
    }

    cppa::await_all_others_done();
    cppa::shutdown();

    return CPPA_TEST_RESULT();
}
<|endoftext|>


<commit_before>#include <boost/test/unit_test.hpp>
#include <boost/test/test_case_template.hpp>

#include "args.hpp"
#include "fixture.hpp"
#include "coordinates.hpp"

#include "osrm/route_parameters.hpp"

#include "osrm/coordinate.hpp"
#include "osrm/engine_config.hpp"
#include "osrm/json_container.hpp"
#include "osrm/status.hpp"
#include "osrm/osrm.hpp"

BOOST_AUTO_TEST_SUITE(route)

BOOST_AUTO_TEST_CASE(test_route_same_coordinates)
{
    const auto args = get_args();
    auto osrm = get_osrm(args.at(0));

    using namespace osrm;

    RouteParameters params;
    params.coordinates.push_back(get_dummy_location());
    params.coordinates.push_back(get_dummy_location());
    params.coordinates.push_back(get_dummy_location());

    json::Object result;
    const auto rc = osrm.Route(params, result);
    BOOST_CHECK(rc == Status::Ok);

    const auto code = result.values.at("code").get<json::String>().value;
    BOOST_CHECK_EQUAL(code, "ok");

    const auto &waypoints = result.values.at("waypoints").get<json::Array>().values;
    BOOST_CHECK(!waypoints.empty());

    for (const auto &waypoint : waypoints)
    {
        const auto &waypoint_object = waypoint.get<json::Object>();

        // nothing can be said about name, empty or contains name of the street
        const auto name = waypoint_object.values.at("name").get<json::String>().value;
        BOOST_CHECK(((void)name, true));

        const auto location = waypoint_object.values.at("location").get<json::Array>().values;
        const auto longitude = location[0].get<json::Number>().value;
        const auto latitude = location[1].get<json::Number>().value;
        BOOST_CHECK(longitude >= -180. && longitude <= 180.);
        BOOST_CHECK(latitude >= -90. && latitude <= 90.);

        const auto hint = waypoint_object.values.at("hint").get<json::String>().value;
        BOOST_CHECK(!hint.empty());
    }

    // alternative=true by default
    const auto &routes = result.values.at("routes").get<json::Array>().values;
    BOOST_CHECK(!routes.empty());
    BOOST_CHECK(routes.size() > 1);

    for (const auto &route : routes)
    {
        const auto &route_object = route.get<json::Object>();

        const auto distance = route_object.values.at("distance").get<json::Number>().value;
        BOOST_CHECK(distance == 0);

        const auto duration = route_object.values.at("duration").get<json::Number>().value;
        BOOST_CHECK(duration == 0);

        // geometries=polyline by default
        const auto geometry = route_object.values.at("geometry").get<json::String>().value;
        BOOST_CHECK(!geometry.empty());

        const auto &legs = route_object.values.at("legs").get<json::Array>().values;
        BOOST_CHECK(!legs.empty());

        for (const auto &leg : legs)
        {
            const auto &leg_object = leg.get<json::Object>();

            const auto distance = leg_object.values.at("distance").get<json::Number>().value;
            BOOST_CHECK(distance == 0);

            const auto duration = leg_object.values.at("duration").get<json::Number>().value;
            BOOST_CHECK(duration == 0);

            // nothing can be said about summary, empty or contains human readable summary
            const auto summary = leg_object.values.at("summary").get<json::String>().value;
            BOOST_CHECK(((void)summary, true));

            // steps=true by default
            const auto &steps = leg_object.values.at("steps").get<json::Array>().values;
            BOOST_CHECK(!steps.empty());

            for (const auto &step : steps)
            {
                const auto &step_object = step.get<json::Object>();

                const auto distance = step_object.values.at("distance").get<json::Number>().value;
                BOOST_CHECK(distance == 0);

                const auto duration = step_object.values.at("duration").get<json::Number>().value;
                BOOST_CHECK(duration == 0);

                // geometries=polyline by default
                const auto geometry = step_object.values.at("geometry").get<json::String>().value;
                BOOST_CHECK(!geometry.empty());

                // nothing can be said about name, empty or contains way name
                const auto name = step_object.values.at("name").get<json::String>().value;
                BOOST_CHECK(((void)name, true));

                // nothing can be said about mode, contains mode of transportation
                const auto mode = step_object.values.at("mode").get<json::String>().value;
                BOOST_CHECK(!name.empty());

                const auto &maneuver = step_object.values.at("maneuver").get<json::Object>().values;

                const auto location = maneuver.at("location").get<json::Array>().values;
                const auto longitude = location[0].get<json::Number>().value;
                const auto latitude = location[1].get<json::Number>().value;
                BOOST_CHECK(longitude >= -180. && longitude <= 180.);
                BOOST_CHECK(latitude >= -90. && latitude <= 90.);

                const auto bearing_before = maneuver.at("bearing_before").get<json::Number>().value;
                const auto bearing_after = maneuver.at("bearing_after").get<json::Number>().value;
                BOOST_CHECK(bearing_before >= 0. && bearing_before <= 360.);
                BOOST_CHECK(bearing_after >= 0. && bearing_after <= 360.);

                const auto type = maneuver.at("type").get<json::String>().value;
                BOOST_CHECK(!type.empty());

                // modifier is optional
                // TODO(daniel-j-h):

                // exit is optional
                // TODO(daniel-j-h):
            }
        }
    }
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Make test assumption failure output violation in Route unit tests<commit_after>#include <boost/test/unit_test.hpp>
#include <boost/test/test_case_template.hpp>

#include "args.hpp"
#include "fixture.hpp"
#include "coordinates.hpp"

#include "osrm/route_parameters.hpp"

#include "osrm/coordinate.hpp"
#include "osrm/engine_config.hpp"
#include "osrm/json_container.hpp"
#include "osrm/status.hpp"
#include "osrm/osrm.hpp"

BOOST_AUTO_TEST_SUITE(route)

BOOST_AUTO_TEST_CASE(test_route_same_coordinates)
{
    const auto args = get_args();
    auto osrm = get_osrm(args.at(0));

    using namespace osrm;

    RouteParameters params;
    params.coordinates.push_back(get_dummy_location());
    params.coordinates.push_back(get_dummy_location());
    params.coordinates.push_back(get_dummy_location());

    json::Object result;
    const auto rc = osrm.Route(params, result);
    BOOST_CHECK(rc == Status::Ok);

    const auto code = result.values.at("code").get<json::String>().value;
    BOOST_CHECK_EQUAL(code, "ok");

    const auto &waypoints = result.values.at("waypoints").get<json::Array>().values;
    BOOST_CHECK(!waypoints.empty());

    for (const auto &waypoint : waypoints)
    {
        const auto &waypoint_object = waypoint.get<json::Object>();

        // nothing can be said about name, empty or contains name of the street
        const auto name = waypoint_object.values.at("name").get<json::String>().value;
        BOOST_CHECK(((void)name, true));

        const auto location = waypoint_object.values.at("location").get<json::Array>().values;
        const auto longitude = location[0].get<json::Number>().value;
        const auto latitude = location[1].get<json::Number>().value;
        BOOST_CHECK(longitude >= -180. && longitude <= 180.);
        BOOST_CHECK(latitude >= -90. && latitude <= 90.);

        const auto hint = waypoint_object.values.at("hint").get<json::String>().value;
        BOOST_CHECK(!hint.empty());
    }

    // alternative=true by default
    const auto &routes = result.values.at("routes").get<json::Array>().values;
    BOOST_CHECK(!routes.empty());
    BOOST_CHECK(routes.size() > 1);

    for (const auto &route : routes)
    {
        const auto &route_object = route.get<json::Object>();

        const auto distance = route_object.values.at("distance").get<json::Number>().value;
        BOOST_CHECK_EQUAL(distance, 0);

        const auto duration = route_object.values.at("duration").get<json::Number>().value;
        BOOST_CHECK_EQUAL(duration, 0);

        // geometries=polyline by default
        const auto geometry = route_object.values.at("geometry").get<json::String>().value;
        BOOST_CHECK(!geometry.empty());

        const auto &legs = route_object.values.at("legs").get<json::Array>().values;
        BOOST_CHECK(!legs.empty());

        for (const auto &leg : legs)
        {
            const auto &leg_object = leg.get<json::Object>();

            const auto distance = leg_object.values.at("distance").get<json::Number>().value;
            BOOST_CHECK_EQUAL(distance, 0);

            const auto duration = leg_object.values.at("duration").get<json::Number>().value;
            BOOST_CHECK_EQUAL(duration, 0);

            // nothing can be said about summary, empty or contains human readable summary
            const auto summary = leg_object.values.at("summary").get<json::String>().value;
            BOOST_CHECK(((void)summary, true));

            // steps=true by default
            const auto &steps = leg_object.values.at("steps").get<json::Array>().values;
            BOOST_CHECK(!steps.empty());

            for (const auto &step : steps)
            {
                const auto &step_object = step.get<json::Object>();

                const auto distance = step_object.values.at("distance").get<json::Number>().value;
                BOOST_CHECK_EQUAL(distance, 0);

                const auto duration = step_object.values.at("duration").get<json::Number>().value;
                BOOST_CHECK_EQUAL(duration, 0);

                // geometries=polyline by default
                const auto geometry = step_object.values.at("geometry").get<json::String>().value;
                BOOST_CHECK(!geometry.empty());

                // nothing can be said about name, empty or contains way name
                const auto name = step_object.values.at("name").get<json::String>().value;
                BOOST_CHECK(((void)name, true));

                // nothing can be said about mode, contains mode of transportation
                const auto mode = step_object.values.at("mode").get<json::String>().value;
                BOOST_CHECK(!name.empty());

                const auto &maneuver = step_object.values.at("maneuver").get<json::Object>().values;

                const auto location = maneuver.at("location").get<json::Array>().values;
                const auto longitude = location[0].get<json::Number>().value;
                const auto latitude = location[1].get<json::Number>().value;
                BOOST_CHECK(longitude >= -180. && longitude <= 180.);
                BOOST_CHECK(latitude >= -90. && latitude <= 90.);

                const auto bearing_before = maneuver.at("bearing_before").get<json::Number>().value;
                const auto bearing_after = maneuver.at("bearing_after").get<json::Number>().value;
                BOOST_CHECK(bearing_before >= 0. && bearing_before <= 360.);
                BOOST_CHECK(bearing_after >= 0. && bearing_after <= 360.);

                const auto type = maneuver.at("type").get<json::String>().value;
                BOOST_CHECK(!type.empty());

                // modifier is optional
                // TODO(daniel-j-h):

                // exit is optional
                // TODO(daniel-j-h):
            }
        }
    }
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include "utest_helper.hpp"

namespace {

typedef struct {
  unsigned long x;
  unsigned long y;
  unsigned long z;
  unsigned long w;
}ulong4;

typedef struct {
  uint32_t x;
  uint32_t y;
  uint32_t z;
  uint32_t w;
} uint4;

typedef struct {
  uint16_t x;
  uint16_t y;
  uint16_t z;
  uint16_t w;
} ushort4;

typedef struct {
  uint8_t x;
  uint8_t y;
  uint8_t z;
  uint8_t w;
} uchar4;

template <typename U>
U get_max()
{
  int shift_bit = sizeof(U)*8;
  U u_max = 0;
  for (int i = 0; i < shift_bit; i++)
    u_max |= 1<<(shift_bit-i-1);
  return u_max;
}

template<typename T, typename U>
void test(const char *kernel_name, int func_type)
{
  const size_t n = 16;

  // Setup kernel and buffers
  OCL_CREATE_KERNEL_FROM_FILE("compiler_overflow", kernel_name);
  OCL_CREATE_BUFFER(buf[0], 0, n * sizeof(T), NULL);
  OCL_CREATE_BUFFER(buf[1], 0, n * sizeof(T), NULL);
  OCL_CREATE_BUFFER(buf[2], 0, n * sizeof(T), NULL);
  OCL_SET_ARG(0, sizeof(cl_mem), &buf[0]);
  OCL_SET_ARG(1, sizeof(cl_mem), &buf[1]);
  OCL_SET_ARG(2, sizeof(cl_mem), &buf[2]);

  U max = get_max<U>();

  OCL_MAP_BUFFER(0);
  for (uint32_t i = 0; i < n; ++i) {
    if(func_type == 0) {
      ((T*)buf_data[0])[i].x = max;
      ((T*)buf_data[0])[i].y = max;
      ((T*)buf_data[0])[i].z = max;
      ((T*)buf_data[0])[i].w = i;
    }else if(func_type == 1) {
      ((T*)buf_data[0])[i].x = 0;
      ((T*)buf_data[0])[i].y = 0;
      ((T*)buf_data[0])[i].z = 0;
      ((T*)buf_data[0])[i].w = n+2-i;
    }else
      OCL_ASSERT(0);
  }
  OCL_UNMAP_BUFFER(0);
  OCL_MAP_BUFFER(1);
  for (uint32_t i = 0; i < n; ++i) {
      ((T*)buf_data[1])[i].x = 1;
      ((T*)buf_data[1])[i].y = 1;
      ((T*)buf_data[1])[i].z = 1;
      ((T*)buf_data[1])[i].w = 1;
  }
  OCL_UNMAP_BUFFER(1);

  globals[0] = n;
  locals[0] = 16;
  OCL_NDRANGE(1);
  OCL_MAP_BUFFER(2);
  for (uint32_t i = 0; i < 16; ++i) {
   // printf("%u,%u,%u,%u\n", ((T*)buf_data[2])[i].x,((T*)buf_data[2])[i].y, ((T*)buf_data[2])[i].z, ((T*)buf_data[2])[i].w  );
    if(func_type == 0) {
      OCL_ASSERT(((T*)buf_data[2])[i].x == 0);
      OCL_ASSERT(((T*)buf_data[2])[i].y == 1);
      OCL_ASSERT(((T*)buf_data[2])[i].z == 1);
      OCL_ASSERT(((T*)buf_data[2])[i].w == i+2);
    }else if(func_type == 1) {
      OCL_ASSERT(((T*)buf_data[2])[i].x == max);
      OCL_ASSERT(((T*)buf_data[2])[i].y == max-1);
      OCL_ASSERT(((T*)buf_data[2])[i].z == max-1);
      OCL_ASSERT(((T*)buf_data[2])[i].w == n-i);
    }else
      OCL_ASSERT(0);
  }
  OCL_UNMAP_BUFFER(2);
}

}

#define compiler_overflow_add(type, subtype, kernel, func_type) \
static void compiler_overflow_add_ ##type(void)\
{\
  test<type, subtype>(# kernel, func_type);\
}\
MAKE_UTEST_FROM_FUNCTION(compiler_overflow_add_ ## type);

#define compiler_overflow_sub(type, subtype, kernel, func_type) \
static void compiler_overflow_sub_ ##type(void)\
{\
  test<type, subtype>(# kernel, func_type);\
}\
MAKE_UTEST_FROM_FUNCTION(compiler_overflow_sub_ ## type);

compiler_overflow_add(ulong4, unsigned long, compiler_overflow_ulong4_add, 0)
compiler_overflow_add(uint4, uint32_t, compiler_overflow_uint4_add, 0)
compiler_overflow_add(ushort4, uint16_t, compiler_overflow_ushort4_add, 0)
compiler_overflow_add(uchar4, uint8_t, compiler_overflow_uchar4_add, 0)

// as llvm intrincs function doesn't support byte/short overflow,
// we just test uint overflow here.
compiler_overflow_sub(uint4, uint32_t, compiler_overflow_uint4_sub, 1)
<commit_msg>refine overflow utest to cover nsetc fail cases.<commit_after>#include "utest_helper.hpp"

namespace {

typedef struct {
  unsigned long x;
  unsigned long y;
  unsigned long z;
  unsigned long w;
}ulong4;

typedef struct {
  uint32_t x;
  uint32_t y;
  uint32_t z;
  uint32_t w;
} uint4;

typedef struct {
  uint16_t x;
  uint16_t y;
  uint16_t z;
  uint16_t w;
} ushort4;

typedef struct {
  uint8_t x;
  uint8_t y;
  uint8_t z;
  uint8_t w;
} uchar4;

template <typename U>
U get_max()
{
  int shift_bit = sizeof(U)*8;
  U u_max = 0;
  for (int i = 0; i < shift_bit; i++)
    u_max |= 1<<(shift_bit-i-1);
  return u_max;
}

template<typename T, typename U>
void test(const char *kernel_name, int func_type)
{
  const size_t n = 16;

  // Setup kernel and buffers
  OCL_CREATE_KERNEL_FROM_FILE("compiler_overflow", kernel_name);
  OCL_CREATE_BUFFER(buf[0], 0, n * sizeof(T), NULL);
  OCL_CREATE_BUFFER(buf[1], 0, n * sizeof(T), NULL);
  OCL_CREATE_BUFFER(buf[2], 0, n * sizeof(T), NULL);
  OCL_SET_ARG(0, sizeof(cl_mem), &buf[0]);
  OCL_SET_ARG(1, sizeof(cl_mem), &buf[1]);
  OCL_SET_ARG(2, sizeof(cl_mem), &buf[2]);

  U max = get_max<U>();

  // test add and sub overflow when src1 is 1:
  // uadd.with.overflow: max + 1
  // usub.with.overflow: 0 - 1
  OCL_MAP_BUFFER(0);
  for (uint32_t i = 0; i < n; ++i) {
    if(func_type == 0) {
      ((T*)buf_data[0])[i].x = max;
      ((T*)buf_data[0])[i].y = max;
      ((T*)buf_data[0])[i].z = max;
      ((T*)buf_data[0])[i].w = i;
    }else if(func_type == 1) {
      ((T*)buf_data[0])[i].x = 0;
      ((T*)buf_data[0])[i].y = 0;
      ((T*)buf_data[0])[i].z = 0;
      ((T*)buf_data[0])[i].w = n+2-i;
    }else
      OCL_ASSERT(0);
  }
  OCL_UNMAP_BUFFER(0);
  OCL_MAP_BUFFER(1);
  for (uint32_t i = 0; i < n; ++i) {
      ((T*)buf_data[1])[i].x = 1;
      ((T*)buf_data[1])[i].y = 1;
      ((T*)buf_data[1])[i].z = 1;
      ((T*)buf_data[1])[i].w = 1;
  }
  OCL_UNMAP_BUFFER(1);

  globals[0] = n;
  locals[0] = 16;
  OCL_NDRANGE(1);
  OCL_MAP_BUFFER(2);
  for (uint32_t i = 0; i < 16; ++i) {
   // printf("%u,%u,%u,%u\n", ((T*)buf_data[2])[i].x,((T*)buf_data[2])[i].y, ((T*)buf_data[2])[i].z, ((T*)buf_data[2])[i].w  );
    if(func_type == 0) {
      OCL_ASSERT(((T*)buf_data[2])[i].x == 0);
      OCL_ASSERT(((T*)buf_data[2])[i].y == 1);
      OCL_ASSERT(((T*)buf_data[2])[i].z == 1);
      OCL_ASSERT(((T*)buf_data[2])[i].w == i+2);
    }else if(func_type == 1) {
      OCL_ASSERT(((T*)buf_data[2])[i].x == max);
      OCL_ASSERT(((T*)buf_data[2])[i].y == max-1);
      OCL_ASSERT(((T*)buf_data[2])[i].z == max-1);
      OCL_ASSERT(((T*)buf_data[2])[i].w == n-i);
    }else
      OCL_ASSERT(0);
  }
  OCL_UNMAP_BUFFER(2);

  // test add and sub overflow when src1 is max:
  // uadd.with.overflow: max + max
  // usub.with.overflow: 0 - max
  OCL_MAP_BUFFER(0);
  for (uint32_t i = 0; i < n; ++i) {
    if(func_type == 0) {
      ((T*)buf_data[0])[i].x = max;
      ((T*)buf_data[0])[i].y = max;
      ((T*)buf_data[0])[i].z = max;
      ((T*)buf_data[0])[i].w = i;
    }else if(func_type == 1) {
      ((T*)buf_data[0])[i].x = 0;
      ((T*)buf_data[0])[i].y = 0;
      ((T*)buf_data[0])[i].z = 0;
      ((T*)buf_data[0])[i].w = n+2-i;
    }else
      OCL_ASSERT(0);
  }
  OCL_UNMAP_BUFFER(0);
  OCL_MAP_BUFFER(1);
  for (uint32_t i = 0; i < n; ++i) {
      ((T*)buf_data[1])[i].x = max;
      ((T*)buf_data[1])[i].y = max;
      ((T*)buf_data[1])[i].z = max;
      ((T*)buf_data[1])[i].w = 1;
  }
  OCL_UNMAP_BUFFER(1);

  globals[0] = n;
  locals[0] = 16;
  OCL_NDRANGE(1);
  OCL_MAP_BUFFER(2);
  for (uint32_t i = 0; i < 16; ++i) {
    // printf("%u,%u,%u,%u\n", ((T*)buf_data[2])[i].x,((T*)buf_data[2])[i].y, ((T*)buf_data[2])[i].z, ((T*)buf_data[2])[i].w  );
    if(func_type == 0) {
      OCL_ASSERT(((T*)buf_data[2])[i].x == max-1);
      OCL_ASSERT(((T*)buf_data[2])[i].y == max);
      OCL_ASSERT(((T*)buf_data[2])[i].z == max);
      OCL_ASSERT(((T*)buf_data[2])[i].w == i+2);
    }else if(func_type == 1) {
      OCL_ASSERT(((T*)buf_data[2])[i].x == 1);
      OCL_ASSERT(((T*)buf_data[2])[i].y == 0);
      OCL_ASSERT(((T*)buf_data[2])[i].z == 0);
      OCL_ASSERT(((T*)buf_data[2])[i].w == n-i);
    }else
      OCL_ASSERT(0);
  }
  OCL_UNMAP_BUFFER(2);
}

}

#define compiler_overflow_add(type, subtype, kernel, func_type) \
static void compiler_overflow_add_ ##type(void)\
{\
  test<type, subtype>(# kernel, func_type);\
}\
MAKE_UTEST_FROM_FUNCTION(compiler_overflow_add_ ## type);

#define compiler_overflow_sub(type, subtype, kernel, func_type) \
static void compiler_overflow_sub_ ##type(void)\
{\
  test<type, subtype>(# kernel, func_type);\
}\
MAKE_UTEST_FROM_FUNCTION(compiler_overflow_sub_ ## type);

compiler_overflow_add(ulong4, unsigned long, compiler_overflow_ulong4_add, 0)
compiler_overflow_add(uint4, uint32_t, compiler_overflow_uint4_add, 0)
compiler_overflow_add(ushort4, uint16_t, compiler_overflow_ushort4_add, 0)
compiler_overflow_add(uchar4, uint8_t, compiler_overflow_uchar4_add, 0)

// as llvm intrincs function doesn't support byte/short overflow,
// we just test uint overflow here.
compiler_overflow_sub(uint4, uint32_t, compiler_overflow_uint4_sub, 1)
<|endoftext|>


<commit_before><commit_msg>Don't use the CoreUI private framework when sandboxed (i.e., for App Store)<commit_after><|endoftext|>


<commit_before><commit_msg>Hack to make an in-destruction SystemWindow no longer claim to be one<commit_after><|endoftext|>


<commit_before>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "video_engine/vie_renderer.h"

#include "common_video/libyuv/include/webrtc_libyuv.h"
#include "webrtc/modules/video_render/include/video_render.h"
#include "webrtc/modules/video_render/include/video_render_defines.h"
#include "video_engine/vie_render_manager.h"

namespace webrtc {

ViERenderer* ViERenderer::CreateViERenderer(const WebRtc_Word32 render_id,
                                            const WebRtc_Word32 engine_id,
                                            VideoRender& render_module,
                                            ViERenderManager& render_manager,
                                            const WebRtc_UWord32 z_order,
                                            const float left,
                                            const float top,
                                            const float right,
                                            const float bottom) {
  ViERenderer* self = new ViERenderer(render_id, engine_id, render_module,
                                      render_manager);
  if (!self || self->Init(z_order, left, top, right, bottom) != 0) {
    delete self;
    self = NULL;
  }
  return self;
}

ViERenderer::~ViERenderer(void) {
  if (render_callback_)
    render_module_.DeleteIncomingRenderStream(render_id_);

  if (incoming_external_callback_)
    delete incoming_external_callback_;
}

WebRtc_Word32 ViERenderer::StartRender() {
  return render_module_.StartRender(render_id_);
}
WebRtc_Word32 ViERenderer::StopRender() {
  return render_module_.StopRender(render_id_);
}

WebRtc_Word32 ViERenderer::GetLastRenderedFrame(const WebRtc_Word32 renderID,
                                                I420VideoFrame& video_frame) {
  return render_module_.GetLastRenderedFrame(renderID, video_frame);
}

int ViERenderer::SetExpectedRenderDelay(int render_delay) {
  return render_module_.SetExpectedRenderDelay(render_id_, render_delay);
}

WebRtc_Word32 ViERenderer::ConfigureRenderer(const unsigned int z_order,
                                             const float left,
                                             const float top,
                                             const float right,
                                             const float bottom) {
  return render_module_.ConfigureRenderer(render_id_, z_order, left, top, right,
                                          bottom);
}

VideoRender& ViERenderer::RenderModule() {
  return render_module_;
}

WebRtc_Word32 ViERenderer::EnableMirroring(const WebRtc_Word32 render_id,
                                           const bool enable,
                                           const bool mirror_xaxis,
                                           const bool mirror_yaxis) {
  return render_module_.MirrorRenderStream(render_id, enable, mirror_xaxis,
                                           mirror_yaxis);
}

WebRtc_Word32 ViERenderer::SetTimeoutImage(const I420VideoFrame& timeout_image,
                                           const WebRtc_Word32 timeout_value) {
  return render_module_.SetTimeoutImage(render_id_, timeout_image,
                                        timeout_value);
}

WebRtc_Word32  ViERenderer::SetRenderStartImage(
    const I420VideoFrame& start_image) {
  return render_module_.SetStartImage(render_id_, start_image);
}

WebRtc_Word32 ViERenderer::SetExternalRenderer(
    const WebRtc_Word32 render_id,
    RawVideoType video_input_format,
    ExternalRenderer* external_renderer) {
  if (!incoming_external_callback_)
    return -1;

  incoming_external_callback_->SetViEExternalRenderer(external_renderer,
                                                      video_input_format);
  return render_module_.AddExternalRenderCallback(render_id,
                                                  incoming_external_callback_);
}

ViERenderer::ViERenderer(const WebRtc_Word32 render_id,
                         const WebRtc_Word32 engine_id,
                         VideoRender& render_module,
                         ViERenderManager& render_manager)
    : render_id_(render_id),
      render_module_(render_module),
      render_manager_(render_manager),
      render_callback_(NULL),
      incoming_external_callback_(new ViEExternalRendererImpl()) {
}

WebRtc_Word32 ViERenderer::Init(const WebRtc_UWord32 z_order,
                                const float left,
                                const float top,
                                const float right,
                                const float bottom) {
  render_callback_ =
      static_cast<VideoRenderCallback*>(render_module_.AddIncomingRenderStream(
          render_id_, z_order, left, top, right, bottom));
  if (!render_callback_) {
    // Logging done.
    return -1;
  }
  return 0;
}

void ViERenderer::DeliverFrame(int id,
                               I420VideoFrame* video_frame,
                               int num_csrcs,
                               const WebRtc_UWord32 CSRC[kRtpCsrcSize]) {
  render_callback_->RenderFrame(render_id_, *video_frame);
}

void ViERenderer::DelayChanged(int id, int frame_delay) {}

int ViERenderer::GetPreferedFrameSettings(int* width,
                                          int* height,
                                          int* frame_rate) {
    return -1;
}

void ViERenderer::ProviderDestroyed(int id) {
  // Remove the render stream since the provider is destroyed.
  render_manager_.RemoveRenderStream(render_id_);
}

ViEExternalRendererImpl::ViEExternalRendererImpl()
    : external_renderer_(NULL),
      external_renderer_format_(kVideoUnknown),
      external_renderer_width_(0),
      external_renderer_height_(0),
      converted_frame_(new VideoFrame()) {
}

int ViEExternalRendererImpl::SetViEExternalRenderer(
    ExternalRenderer* external_renderer,
    RawVideoType video_input_format) {
  external_renderer_ = external_renderer;
  external_renderer_format_ = video_input_format;
  return 0;
}

WebRtc_Word32 ViEExternalRendererImpl::RenderFrame(
    const WebRtc_UWord32 stream_id,
    I420VideoFrame&   video_frame) {
  VideoFrame* out_frame = converted_frame_.get();

  // Convert to requested format.
  VideoType type =
      RawVideoTypeToCommonVideoVideoType(external_renderer_format_);
  int buffer_size = CalcBufferSize(type, video_frame.width(),
                                   video_frame.height());
  if (buffer_size <= 0) {
    // Unsupported video format.
    assert(false);
    return -1;
  }
  converted_frame_->VerifyAndAllocate(buffer_size);

  switch (external_renderer_format_) {
    case kVideoI420: {
      // TODO(mikhal): need to copy the buffer as is.
      // can the output here be a I420 frame?
      int length = ExtractBuffer(video_frame, out_frame->Size(),
                                 out_frame->Buffer());
      if (length < 0)
        return -1;
      out_frame->SetLength(length);
      break;
    }
    case kVideoYV12:
    case kVideoYUY2:
    case kVideoUYVY:
    case kVideoARGB:
    case kVideoRGB24:
    case kVideoRGB565:
    case kVideoARGB4444:
    case kVideoARGB1555 :
      {
        ConvertFromI420(video_frame, type, 0, converted_frame_->Buffer());
      }
      break;
    case kVideoIYUV:
      // no conversion available
      break;
    default:
      assert(false);
      out_frame = NULL;
      break;
  }

  if (external_renderer_width_ != video_frame.width() ||
      external_renderer_height_ != video_frame.height()) {
    external_renderer_width_ = video_frame.width();
    external_renderer_height_ = video_frame.height();
    external_renderer_->FrameSizeChange(external_renderer_width_,
                                        external_renderer_height_, stream_id);
  }

  if (out_frame) {
    external_renderer_->DeliverFrame(out_frame->Buffer(),
                                     out_frame->Length(),
                                     video_frame.timestamp(),
                                     video_frame.render_time_ms());
  }
  return 0;
}

}  // namespace webrtc
<commit_msg>Set frame length for frame converting in external renderer<commit_after>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "video_engine/vie_renderer.h"

#include "common_video/libyuv/include/webrtc_libyuv.h"
#include "webrtc/modules/video_render/include/video_render.h"
#include "webrtc/modules/video_render/include/video_render_defines.h"
#include "video_engine/vie_render_manager.h"

namespace webrtc {

ViERenderer* ViERenderer::CreateViERenderer(const WebRtc_Word32 render_id,
                                            const WebRtc_Word32 engine_id,
                                            VideoRender& render_module,
                                            ViERenderManager& render_manager,
                                            const WebRtc_UWord32 z_order,
                                            const float left,
                                            const float top,
                                            const float right,
                                            const float bottom) {
  ViERenderer* self = new ViERenderer(render_id, engine_id, render_module,
                                      render_manager);
  if (!self || self->Init(z_order, left, top, right, bottom) != 0) {
    delete self;
    self = NULL;
  }
  return self;
}

ViERenderer::~ViERenderer(void) {
  if (render_callback_)
    render_module_.DeleteIncomingRenderStream(render_id_);

  if (incoming_external_callback_)
    delete incoming_external_callback_;
}

WebRtc_Word32 ViERenderer::StartRender() {
  return render_module_.StartRender(render_id_);
}
WebRtc_Word32 ViERenderer::StopRender() {
  return render_module_.StopRender(render_id_);
}

WebRtc_Word32 ViERenderer::GetLastRenderedFrame(const WebRtc_Word32 renderID,
                                                I420VideoFrame& video_frame) {
  return render_module_.GetLastRenderedFrame(renderID, video_frame);
}

int ViERenderer::SetExpectedRenderDelay(int render_delay) {
  return render_module_.SetExpectedRenderDelay(render_id_, render_delay);
}

WebRtc_Word32 ViERenderer::ConfigureRenderer(const unsigned int z_order,
                                             const float left,
                                             const float top,
                                             const float right,
                                             const float bottom) {
  return render_module_.ConfigureRenderer(render_id_, z_order, left, top, right,
                                          bottom);
}

VideoRender& ViERenderer::RenderModule() {
  return render_module_;
}

WebRtc_Word32 ViERenderer::EnableMirroring(const WebRtc_Word32 render_id,
                                           const bool enable,
                                           const bool mirror_xaxis,
                                           const bool mirror_yaxis) {
  return render_module_.MirrorRenderStream(render_id, enable, mirror_xaxis,
                                           mirror_yaxis);
}

WebRtc_Word32 ViERenderer::SetTimeoutImage(const I420VideoFrame& timeout_image,
                                           const WebRtc_Word32 timeout_value) {
  return render_module_.SetTimeoutImage(render_id_, timeout_image,
                                        timeout_value);
}

WebRtc_Word32  ViERenderer::SetRenderStartImage(
    const I420VideoFrame& start_image) {
  return render_module_.SetStartImage(render_id_, start_image);
}

WebRtc_Word32 ViERenderer::SetExternalRenderer(
    const WebRtc_Word32 render_id,
    RawVideoType video_input_format,
    ExternalRenderer* external_renderer) {
  if (!incoming_external_callback_)
    return -1;

  incoming_external_callback_->SetViEExternalRenderer(external_renderer,
                                                      video_input_format);
  return render_module_.AddExternalRenderCallback(render_id,
                                                  incoming_external_callback_);
}

ViERenderer::ViERenderer(const WebRtc_Word32 render_id,
                         const WebRtc_Word32 engine_id,
                         VideoRender& render_module,
                         ViERenderManager& render_manager)
    : render_id_(render_id),
      render_module_(render_module),
      render_manager_(render_manager),
      render_callback_(NULL),
      incoming_external_callback_(new ViEExternalRendererImpl()) {
}

WebRtc_Word32 ViERenderer::Init(const WebRtc_UWord32 z_order,
                                const float left,
                                const float top,
                                const float right,
                                const float bottom) {
  render_callback_ =
      static_cast<VideoRenderCallback*>(render_module_.AddIncomingRenderStream(
          render_id_, z_order, left, top, right, bottom));
  if (!render_callback_) {
    // Logging done.
    return -1;
  }
  return 0;
}

void ViERenderer::DeliverFrame(int id,
                               I420VideoFrame* video_frame,
                               int num_csrcs,
                               const WebRtc_UWord32 CSRC[kRtpCsrcSize]) {
  render_callback_->RenderFrame(render_id_, *video_frame);
}

void ViERenderer::DelayChanged(int id, int frame_delay) {}

int ViERenderer::GetPreferedFrameSettings(int* width,
                                          int* height,
                                          int* frame_rate) {
    return -1;
}

void ViERenderer::ProviderDestroyed(int id) {
  // Remove the render stream since the provider is destroyed.
  render_manager_.RemoveRenderStream(render_id_);
}

ViEExternalRendererImpl::ViEExternalRendererImpl()
    : external_renderer_(NULL),
      external_renderer_format_(kVideoUnknown),
      external_renderer_width_(0),
      external_renderer_height_(0),
      converted_frame_(new VideoFrame()) {
}

int ViEExternalRendererImpl::SetViEExternalRenderer(
    ExternalRenderer* external_renderer,
    RawVideoType video_input_format) {
  external_renderer_ = external_renderer;
  external_renderer_format_ = video_input_format;
  return 0;
}

WebRtc_Word32 ViEExternalRendererImpl::RenderFrame(
    const WebRtc_UWord32 stream_id,
    I420VideoFrame&   video_frame) {
  VideoFrame* out_frame = converted_frame_.get();

  // Convert to requested format.
  VideoType type =
      RawVideoTypeToCommonVideoVideoType(external_renderer_format_);
  int buffer_size = CalcBufferSize(type, video_frame.width(),
                                   video_frame.height());
  if (buffer_size <= 0) {
    // Unsupported video format.
    assert(false);
    return -1;
  }
  converted_frame_->VerifyAndAllocate(buffer_size);

  switch (external_renderer_format_) {
    case kVideoI420: {
      // TODO(mikhal): need to copy the buffer as is.
      // can the output here be a I420 frame?
      int length = ExtractBuffer(video_frame, out_frame->Size(),
                                 out_frame->Buffer());
      if (length < 0)
        return -1;
      out_frame->SetLength(length);
      break;
    }
    case kVideoYV12:
    case kVideoYUY2:
    case kVideoUYVY:
    case kVideoARGB:
    case kVideoRGB24:
    case kVideoRGB565:
    case kVideoARGB4444:
    case kVideoARGB1555 :
      {
        if (ConvertFromI420(video_frame, type, 0,
                            converted_frame_->Buffer()) < 0)
          return -1;
        converted_frame_->SetLength(buffer_size);
      }
      break;
    case kVideoIYUV:
      // no conversion available
      break;
    default:
      assert(false);
      out_frame = NULL;
      break;
  }

  if (external_renderer_width_ != video_frame.width() ||
      external_renderer_height_ != video_frame.height()) {
    external_renderer_width_ = video_frame.width();
    external_renderer_height_ = video_frame.height();
    external_renderer_->FrameSizeChange(external_renderer_width_,
                                        external_renderer_height_, stream_id);
  }

  if (out_frame) {
    external_renderer_->DeliverFrame(out_frame->Buffer(),
                                     out_frame->Length(),
                                     video_frame.timestamp(),
                                     video_frame.render_time_ms());
  }
  return 0;
}

}  // namespace webrtc
<|endoftext|>


<commit_before>#ifndef VIENNAGRID_STORAGE_RANGE_HPP
#define VIENNAGRID_STORAGE_RANGE_HPP

#include "viennagrid/forwards.hpp"

namespace viennagrid
{

    namespace storage
    {

        template<typename container_type>
        class container_range_wrapper
        {
            friend class container_range_wrapper<const container_type>;

        public:

            container_range_wrapper(container_type & _container) : container(&_container) {}

            typedef typename container_type::size_type size_type;
            typedef typename container_type::value_type value_type;

            typedef typename container_type::reference reference;
            typedef typename container_type::const_reference const_reference;

            typedef typename container_type::pointer pointer;
            typedef typename container_type::const_pointer const_pointer;

            typedef typename container_type::iterator iterator;
            typedef typename container_type::const_iterator const_iterator;

            typedef typename container_type::reverse_iterator reverse_iterator;
            typedef typename container_type::const_reverse_iterator const_reverse_iterator;

            iterator begin() { return container->begin(); }
            const_iterator begin() const { return container->begin(); }
            iterator end() { return container->end(); }
            const_iterator end() const { return container->end(); }

            reverse_iterator rbegin() { return container->rbegin(); }
            const_reverse_iterator rbegin() const { return container->rbegin(); }
            reverse_iterator rend() { return container->rend(); }
            const_reverse_iterator rend() const { return container->rend(); }

            reference front() { return container->front(); }
            const_reference front() const { return container->front(); }
            reference back() { return container->back(); }
            const_reference back() const { return container->back(); }

            reference operator[] (size_type index) { return (*container)[index]; }
            const_reference operator[] (size_type index) const { return (*container)[index]; }

            bool empty() const { return container->empty(); }
            size_type size() const { return container->size(); }

            typedef typename container_type::hook_type hook_type;
            typedef typename container_type::hook_iterator hook_iterator;
            hook_iterator hook_begin() { return container->hook_begin(); }
            hook_iterator hook_end() { return container->hook_end(); }

            typedef typename container_type::const_hook_type const_hook_type;
            typedef typename container_type::const_hook_iterator const_hook_iterator;
            const_hook_iterator hook_begin() const { return container->hook_begin(); }
            const_hook_iterator hook_end() const { return container->hook_end(); }

            hook_type hook_at(std::size_t pos)
            {
                return *viennagrid::advance(hook_begin(), pos);
//                 hook_iterator it = hook_begin();
//                 std::advance( it, pos );
//                 return *it;
            }

            const_hook_type hook_at(std::size_t pos) const
            {
                return *viennagrid::advance(hook_begin(), pos);
//                 const_hook_iterator it = hook_begin();
//                 std::advance( it, pos );
//                 return *it;
            }

        private:

            container_type * container;
        };

        template<typename container_type>
        class container_range_wrapper<const container_type>
        {
        public:

            container_range_wrapper(const container_type & _container) : container(&_container) {}
            container_range_wrapper(const container_range_wrapper<container_type> & rhs) : container(rhs.container) {}

            typedef typename container_type::size_type size_type;
            typedef typename container_type::value_type value_type;

            typedef typename container_type::const_reference reference;
            typedef typename container_type::const_reference const_reference;

            typedef typename container_type::const_pointer pointer;
            typedef typename container_type::const_pointer const_pointer;

            typedef typename container_type::const_iterator iterator;
            typedef typename container_type::const_iterator const_iterator;

            typedef typename container_type::const_reverse_iterator reverse_iterator;
            typedef typename container_type::const_reverse_iterator const_reverse_iterator;

            iterator begin() { return container->begin(); }
            const_iterator begin() const { return container->begin(); }
            iterator end() { return container->end(); }
            const_iterator end() const { return container->end(); }

            reverse_iterator rbegin() { return container->rbegin(); }
            const_reverse_iterator rbegin() const { return container->rbegin(); }
            reverse_iterator rend() { return container->rend(); }
            const_reverse_iterator rend() const { return container->rend(); }

            reference front() { return container->front(); }
            const_reference front() const { return container->front(); }
            reference back() { return container->back(); }
            const_reference back() const { return container->back(); }

            reference operator[] (size_type index) { return (*container)[index]; }
            const_reference operator[] (size_type index) const { return (*container)[index]; }

            bool empty() const { return container->empty(); }
            size_type size() const { return container->size(); }

            typedef typename container_type::const_hook_type hook_type;
            typedef typename container_type::const_hook_iterator hook_iterator;
            hook_iterator hook_begin() { return container->hook_begin(); }
            hook_iterator hook_end() { return container->hook_end(); }

            typedef typename container_type::const_hook_type const_hook_type;
            typedef typename container_type::const_hook_iterator const_hook_iterator;
            const_hook_iterator hook_begin() const { return container->hook_begin(); }
            const_hook_iterator hook_end() const { return container->hook_end(); }

            hook_type hook_at(std::size_t pos)
            {
                return *viennagrid::advance(hook_begin(), pos);
//                 hook_iterator it = hook_begin();
//                 std::advance( it, pos );
//                 return *it;
            }

            const_hook_type hook_at(std::size_t pos) const
            {
                return *viennagrid::advance(hook_begin(), pos);
//                 const_hook_iterator it = hook_begin();
//                 std::advance( it, pos );
//                 return *it;
            }

        private:

            const container_type * container;
        };

        template<typename iterator_type>
        class forward_iterator_range
        {
        public:

            forward_iterator_range(iterator_type _first, iterator_type _last) : first(_first), last(_last) {}

            typedef typename iterator_type::T value_type;

            typedef typename iterator_type::Reference reference;
            typedef const typename iterator_type::Reference const_reference;

            typedef typename iterator_type::Pointer pointer;
            typedef const typename iterator_type::Pointer const_pointer;

            typedef iterator_type iterator;
            typedef const iterator_type const_iterator;

            iterator begin() { return first; }
            const_iterator begin() const { return first; }
            iterator end() { return last; }
            const_iterator end() const { return last; }

            reference front() { return *first; }
            const_reference front() const { return *first; }
            reference back() { iterator_type tmp = last; return *(--tmp); }
            const_reference back() const { iterator_type tmp = last; return *(--tmp); }

            bool empty() const { return first == last; }

        private:
            iterator_type first;
            iterator_type last;
        };

    }

}

#endif

<commit_msg>added functionality for accessing base container (needed for creating views from a range)<commit_after>#ifndef VIENNAGRID_STORAGE_RANGE_HPP
#define VIENNAGRID_STORAGE_RANGE_HPP

#include "viennagrid/forwards.hpp"

namespace viennagrid
{

    namespace storage
    {

        template<typename container_type>
        class container_range_wrapper
        {
            friend class container_range_wrapper<const container_type>;

        public:

            typedef container_type base_container_type;

            container_range_wrapper(container_type & _container) : container(&_container) {}

            typedef typename container_type::size_type size_type;
            typedef typename container_type::value_type value_type;

            typedef typename container_type::reference reference;
            typedef typename container_type::const_reference const_reference;

            typedef typename container_type::pointer pointer;
            typedef typename container_type::const_pointer const_pointer;

            typedef typename container_type::iterator iterator;
            typedef typename container_type::const_iterator const_iterator;

            typedef typename container_type::reverse_iterator reverse_iterator;
            typedef typename container_type::const_reverse_iterator const_reverse_iterator;

            iterator begin() { return container->begin(); }
            const_iterator begin() const { return container->begin(); }
            iterator end() { return container->end(); }
            const_iterator end() const { return container->end(); }

            reverse_iterator rbegin() { return container->rbegin(); }
            const_reverse_iterator rbegin() const { return container->rbegin(); }
            reverse_iterator rend() { return container->rend(); }
            const_reverse_iterator rend() const { return container->rend(); }

            reference front() { return container->front(); }
            const_reference front() const { return container->front(); }
            reference back() { return container->back(); }
            const_reference back() const { return container->back(); }

            reference operator[] (size_type index) { return (*container)[index]; }
            const_reference operator[] (size_type index) const { return (*container)[index]; }

            bool empty() const { return container->empty(); }
            size_type size() const { return container->size(); }

            typedef typename container_type::hook_type hook_type;
            typedef typename container_type::hook_iterator hook_iterator;
            hook_iterator hook_begin() { return container->hook_begin(); }
            hook_iterator hook_end() { return container->hook_end(); }

            typedef typename container_type::const_hook_type const_hook_type;
            typedef typename container_type::const_hook_iterator const_hook_iterator;
            const_hook_iterator hook_begin() const { return container->hook_begin(); }
            const_hook_iterator hook_end() const { return container->hook_end(); }

            hook_type hook_at(std::size_t pos)
            { return *viennagrid::advance(hook_begin(), pos); }
            const_hook_type hook_at(std::size_t pos) const
            { return *viennagrid::advance(hook_begin(), pos); }

            container_type * get_base_container() { return container; }
            const container_type * get_base_container() const { return container; }

        private:

            container_type * container;
        };

        template<typename container_type>
        class container_range_wrapper<const container_type>
        {
        public:

            typedef const container_type base_container_type;

            container_range_wrapper(const container_type & _container) : container(&_container) {}
            container_range_wrapper(const container_range_wrapper<container_type> & rhs) : container(rhs.container) {}

            typedef typename container_type::size_type size_type;
            typedef typename container_type::value_type value_type;

            typedef typename container_type::const_reference reference;
            typedef typename container_type::const_reference const_reference;

            typedef typename container_type::const_pointer pointer;
            typedef typename container_type::const_pointer const_pointer;

            typedef typename container_type::const_iterator iterator;
            typedef typename container_type::const_iterator const_iterator;

            typedef typename container_type::const_reverse_iterator reverse_iterator;
            typedef typename container_type::const_reverse_iterator const_reverse_iterator;

            iterator begin() { return container->begin(); }
            const_iterator begin() const { return container->begin(); }
            iterator end() { return container->end(); }
            const_iterator end() const { return container->end(); }

            reverse_iterator rbegin() { return container->rbegin(); }
            const_reverse_iterator rbegin() const { return container->rbegin(); }
            reverse_iterator rend() { return container->rend(); }
            const_reverse_iterator rend() const { return container->rend(); }

            reference front() { return container->front(); }
            const_reference front() const { return container->front(); }
            reference back() { return container->back(); }
            const_reference back() const { return container->back(); }

            reference operator[] (size_type index) { return (*container)[index]; }
            const_reference operator[] (size_type index) const { return (*container)[index]; }

            bool empty() const { return container->empty(); }
            size_type size() const { return container->size(); }

            typedef typename container_type::const_hook_type hook_type;
            typedef typename container_type::const_hook_iterator hook_iterator;
            hook_iterator hook_begin() { return container->hook_begin(); }
            hook_iterator hook_end() { return container->hook_end(); }

            typedef typename container_type::const_hook_type const_hook_type;
            typedef typename container_type::const_hook_iterator const_hook_iterator;
            const_hook_iterator hook_begin() const { return container->hook_begin(); }
            const_hook_iterator hook_end() const { return container->hook_end(); }

            hook_type hook_at(std::size_t pos)
            { return *viennagrid::advance(hook_begin(), pos); }
            const_hook_type hook_at(std::size_t pos) const
            { return *viennagrid::advance(hook_begin(), pos); }

            const container_type * get_base_container() const { return container; }

        private:

            const container_type * container;
        };

        template<typename iterator_type>
        class forward_iterator_range
        {
        public:

            forward_iterator_range(iterator_type _first, iterator_type _last) : first(_first), last(_last) {}

            typedef typename iterator_type::T value_type;

            typedef typename iterator_type::Reference reference;
            typedef const typename iterator_type::Reference const_reference;

            typedef typename iterator_type::Pointer pointer;
            typedef const typename iterator_type::Pointer const_pointer;

            typedef iterator_type iterator;
            typedef const iterator_type const_iterator;

            iterator begin() { return first; }
            const_iterator begin() const { return first; }
            iterator end() { return last; }
            const_iterator end() const { return last; }

            reference front() { return *first; }
            const_reference front() const { return *first; }
            reference back() { iterator_type tmp = last; return *(--tmp); }
            const_reference back() const { iterator_type tmp = last; return *(--tmp); }

            bool empty() const { return first == last; }

        private:
            iterator_type first;
            iterator_type last;
        };

    }

}

#endif

<|endoftext|>


<commit_before>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include <GL/glew.h>

#include "vvcanvas.h"

#include <virvo/vvdebugmsg.h>
#include <virvo/vvfileio.h>
#include <virvo/vvgltools.h>

#include <QSettings>
#include <QTimer>

#include <iostream>

using vox::vvObjView;

vvCanvas::vvCanvas(const QGLFormat& format, const QString& filename, QWidget* parent)
  : QGLWidget(format, parent)
  , _vd(NULL)
  , _renderer(NULL)
  , _projectionType(vox::vvObjView::PERSPECTIVE)
  , _doubleBuffering(format.doubleBuffer())
  , _superSamples(format.samples())
{
  vvDebugMsg::msg(1, "vvCanvas::vvCanvas()");

  if (filename != "")
  {
    _vd = new vvVolDesc(filename.toStdString().c_str());
  }
  else
  {
    // load default volume
    _vd = new vvVolDesc;
    _vd->vox[0] = 32;
    _vd->vox[1] = 32;
    _vd->vox[2] = 32;
    _vd->frames = 0;
  }

  // init ui
  setMouseTracking(true);
  setFocusPolicy(Qt::StrongFocus);

  // read persistent settings
  QSettings settings;
  QColor qcolor = settings.value("canvas/bgcolor").value<QColor>();
  _bgColor = vvColor(qcolor.redF(), qcolor.greenF(), qcolor.blueF());

  _animTimer = new QTimer(this);
  connect(_animTimer, SIGNAL(timeout()), this, SLOT(incTimeStep()));
}

vvCanvas::~vvCanvas()
{
  vvDebugMsg::msg(1, "vvCanvas::~vvCanvas()");

  delete _renderer;
  delete _vd;
}

void vvCanvas::setParameter(ParameterType param, const vvParam& value)
{
  vvDebugMsg::msg(3, "vvCanvas::setParameter()");

  switch (param)
  {
  case VV_BG_COLOR:
    _bgColor = value;
    break;
  case VV_DOUBLEBUFFERING:
    _doubleBuffering = value;
    break;
  case VV_SUPERSAMPLES:
    _superSamples = value;
    break;
  default:
    break;
  }
}

void vvCanvas::setVolDesc(vvVolDesc* vd)
{
  vvDebugMsg::msg(3, "vvCanvas::setVolDesc()");

  delete _vd;
  _vd = vd;

  if (_vd != NULL)
  {
    createRenderer();
  }

  foreach (vvPlugin* plugin, _plugins)
  {
    plugin->setVolDesc(_vd);
  }

  emit newVolDesc(_vd);
}

void vvCanvas::setPlugins(const QList<vvPlugin*>& plugins)
{
  vvDebugMsg::msg(3, "vvCanvas::setPlugins()");

  _plugins = plugins;
}

vvVolDesc* vvCanvas::getVolDesc() const
{
  vvDebugMsg::msg(3, "vvCanvas::getVolDesc()");

  return _vd;
}

vvRenderer* vvCanvas::getRenderer() const
{
  vvDebugMsg::msg(3, "vvCanvas::getRenderer()");

  return _renderer;
}

void vvCanvas::loadCamera(const QString& filename)
{
  vvDebugMsg::msg(3, "vvCanvas::loadCamera()");

  QByteArray ba = filename.toLatin1();
  _ov.loadCamera(ba.data());
}

void vvCanvas::saveCamera(const QString& filename)
{
  vvDebugMsg::msg(3, "vvCanvas::saveCamera()");

  QByteArray ba = filename.toLatin1();
  _ov.saveCamera(ba.data());
}

void vvCanvas::initializeGL()
{
  vvDebugMsg::msg(1, "vvCanvas::initializeGL()");

  glewInit();
  init();
}

void vvCanvas::paintGL()
{
  vvDebugMsg::msg(3, "vvCanvas::paintGL()");

  if (_renderer == NULL)
  {
    return;
  }

  if (_doubleBuffering)
  {
    glDrawBuffer(GL_BACK);
  }
  else
  {
    glDrawBuffer(GL_FRONT);
  }

  glClearColor(_bgColor[0], _bgColor[1], _bgColor[2], 0.0f);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  glMatrixMode(GL_MODELVIEW);
  _ov.setModelviewMatrix(vvObjView::CENTER);

  foreach (vvPlugin* plugin, _plugins)
  {
    if (plugin->isActive())
    {
      plugin->prerender();
    }
  }

  _renderer->renderVolumeGL();

  foreach (vvPlugin* plugin, _plugins)
  {
    if (plugin->isActive())
    {
      plugin->postrender();
    }
  }
}

void vvCanvas::resizeGL(const int w, const int h)
{
  vvDebugMsg::msg(3, "vvCanvas::resizeGL()");

  glViewport(0, 0, w, h);
  if (h > 0)
  {
    _ov.setAspectRatio(static_cast<float>(w) / static_cast<float>(h));
  }
  updateGL();

  emit resized(QSize(w, h));
}

void vvCanvas::mouseMoveEvent(QMouseEvent* event)
{
  vvDebugMsg::msg(3, "vvCanvas::mouseMoveEvent()");

  switch (_mouseButton)
  {
  case Qt::LeftButton:
  {
    _ov._camera.trackballRotation(width(), height(),
      _lastMousePos.x(), _lastMousePos.y(),
      event->pos().x(), event->pos().y());
    break;
  }
  case Qt::MiddleButton:
  {
    const float pixelInWorld = _ov.getViewportWidth() / static_cast<float>(width());
    const float dx = static_cast<float>(event->pos().x() - _lastMousePos.x());
    const float dy = static_cast<float>(event->pos().y() - _lastMousePos.y());
    vvVector2f pan(pixelInWorld * dx, pixelInWorld * dy);
    _ov._camera.translate(pan[0], -pan[1], 0.0f);
    break;
  }
  case Qt::RightButton:
  {
    const float factor = event->pos().y() - _lastMousePos.y();
    _ov._camera.translate(0.0f, 0.0f, factor);
    break;
  }
  default:
    break;
  }
  _lastMousePos = event->pos();
  updateGL();
}

void vvCanvas::mousePressEvent(QMouseEvent* event)
{
  vvDebugMsg::msg(3, "vvCanvas::mousePressEvent()");

  _mouseButton = event->button();
  _lastMousePos = event->pos();
}

void vvCanvas::mouseReleaseEvent(QMouseEvent*)
{
  vvDebugMsg::msg(3, "vvCanvas::mouseReleaseEvent()");

  _mouseButton = Qt::NoButton;
}

void vvCanvas::init()
{
  vvDebugMsg::msg(3, "vvCanvas::init()");

  vvFileIO* fio = new vvFileIO;
  fio->loadVolumeData(_vd, vvFileIO::ALL_DATA);
  delete fio;

  // default transfer function
  if (_vd->tf.isEmpty())
  {
    _vd->tf.setDefaultAlpha(0, _vd->real[0], _vd->real[1]);
    _vd->tf.setDefaultColors((_vd->chan == 1) ? 0 : 3, _vd->real[0], _vd->real[1]);
  }

  // init renderer
  if (_vd != NULL)
  {
    _currentRenderer = "viewport";
    _currentOptions["voxeltype"] = "arb";
    createRenderer();
  }

  updateProjection();

  foreach (vvPlugin* plugin, _plugins)
  {
    plugin->setVolDesc(_vd);
  }

  emit newVolDesc(_vd);
}

void vvCanvas::createRenderer()
{
  vvDebugMsg::msg(3, "vvCanvas::createRenderer()");

  vvRenderState state;
  if (_renderer)
  {
    state = *_renderer;
    delete _renderer;
  }

  vvRendererFactory::Options opt(_currentOptions);
  _renderer = vvRendererFactory::create(_vd, state, _currentRenderer.c_str(), opt);
}

void vvCanvas::updateProjection()
{
  vvDebugMsg::msg(3, "vvCanvas::updateProjection()");

  if (_projectionType == vvObjView::PERSPECTIVE)
  {
    _ov.setProjection(vvObjView::PERSPECTIVE, vvObjView::DEF_FOV, vvObjView::DEF_CLIP_NEAR, vvObjView::DEF_CLIP_FAR);
  }
  else if (_projectionType == vvObjView::ORTHO)
  {
    _ov.setProjection(vvObjView::ORTHO, vvObjView::DEF_VIEWPORT_WIDTH, vvObjView::DEF_CLIP_NEAR, vvObjView::DEF_CLIP_FAR);
  }
}

void vvCanvas::setCurrentFrame(const int frame)
{
  vvDebugMsg::msg(3, "vvCanvas::setCurrentFrame()");

  _renderer->setCurrentFrame(frame);
  emit currentFrame(frame);
  updateGL();
}

void vvCanvas::startAnimation(const double fps)
{
  vvDebugMsg::msg(3, "vvCanvas::startAnimation()");

  _vd->dt = 1.0f / static_cast<float>(fps);
  const float delay = std::abs(_vd->dt * 1000.0f);
  _animTimer->start(static_cast<int>(delay));
}

void vvCanvas::stopAnimation()
{
  vvDebugMsg::msg(3, "vvCanvas::stopAnimation()");

  _animTimer->stop();
}

void vvCanvas::setTimeStep(const int step)
{
  vvDebugMsg::msg(3, "vvCanvas::setTimeStep()");

  int f = step;
  while (f < 0)
  {
    f += _vd->frames;
  }

  while (f >= _vd->frames)
  {
    f -= _vd->frames;
  }

  _renderer->setCurrentFrame(f);
  // don't emit currentFrame!
  updateGL();
}

void vvCanvas::incTimeStep()
{
  vvDebugMsg::msg(3, "vvCanvas::incTimeStep()");

  int f = _renderer->getCurrentFrame();
  f = (f >= _vd->frames - 1) ? 0 : f + 1;
  setCurrentFrame(f);
}

void vvCanvas::decTimeStep()
{
  vvDebugMsg::msg(3, "vvCanvas::decTimeStep()");

  int f = _renderer->getCurrentFrame();
  f = (f <= 0) ? _vd->frames - 1 : f - 1;
  setCurrentFrame(f);
}

void vvCanvas::firstTimeStep()
{
  vvDebugMsg::msg(3, "vvCanvas::firstTimeStep()");

  setCurrentFrame(0);
}

void vvCanvas::lastTimeStep()
{
  vvDebugMsg::msg(3, "vvCanvas::lastTimeStep()");

  setCurrentFrame(_vd->frames - 1);
}

<commit_msg>Bug fix<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include <GL/glew.h>

#include "vvcanvas.h"

#include <virvo/vvdebugmsg.h>
#include <virvo/vvfileio.h>
#include <virvo/vvgltools.h>

#include <QSettings>
#include <QTimer>

#include <iostream>

using vox::vvObjView;

vvCanvas::vvCanvas(const QGLFormat& format, const QString& filename, QWidget* parent)
  : QGLWidget(format, parent)
  , _vd(NULL)
  , _renderer(NULL)
  , _projectionType(vox::vvObjView::PERSPECTIVE)
  , _doubleBuffering(format.doubleBuffer())
  , _superSamples(format.samples())
{
  vvDebugMsg::msg(1, "vvCanvas::vvCanvas()");

  if (filename != "")
  {
    _vd = new vvVolDesc(filename.toStdString().c_str());
  }
  else
  {
    // load default volume
    _vd = new vvVolDesc;
    _vd->vox[0] = 32;
    _vd->vox[1] = 32;
    _vd->vox[2] = 32;
    _vd->frames = 0;
  }

  // init ui
  setMouseTracking(true);
  setFocusPolicy(Qt::StrongFocus);

  // read persistent settings
  QSettings settings;
  QColor qcolor = settings.value("canvas/bgcolor").value<QColor>();
  _bgColor = vvColor(qcolor.redF(), qcolor.greenF(), qcolor.blueF());

  _animTimer = new QTimer(this);
  connect(_animTimer, SIGNAL(timeout()), this, SLOT(incTimeStep()));
}

vvCanvas::~vvCanvas()
{
  vvDebugMsg::msg(1, "vvCanvas::~vvCanvas()");

  delete _renderer;
  delete _vd;
}

void vvCanvas::setParameter(ParameterType param, const vvParam& value)
{
  vvDebugMsg::msg(3, "vvCanvas::setParameter()");

  switch (param)
  {
  case VV_BG_COLOR:
    _bgColor = value;
    break;
  case VV_DOUBLEBUFFERING:
    _doubleBuffering = value;
    break;
  case VV_SUPERSAMPLES:
    _superSamples = value;
    break;
  default:
    break;
  }
}

void vvCanvas::setVolDesc(vvVolDesc* vd)
{
  vvDebugMsg::msg(3, "vvCanvas::setVolDesc()");

  delete _vd;
  _vd = vd;

  if (_vd != NULL)
  {
    createRenderer();
  }

  foreach (vvPlugin* plugin, _plugins)
  {
    plugin->setVolDesc(_vd);
  }

  emit newVolDesc(_vd);
}

void vvCanvas::setPlugins(const QList<vvPlugin*>& plugins)
{
  vvDebugMsg::msg(3, "vvCanvas::setPlugins()");

  _plugins = plugins;
}

vvVolDesc* vvCanvas::getVolDesc() const
{
  vvDebugMsg::msg(3, "vvCanvas::getVolDesc()");

  return _vd;
}

vvRenderer* vvCanvas::getRenderer() const
{
  vvDebugMsg::msg(3, "vvCanvas::getRenderer()");

  return _renderer;
}

void vvCanvas::loadCamera(const QString& filename)
{
  vvDebugMsg::msg(3, "vvCanvas::loadCamera()");

  QByteArray ba = filename.toLatin1();
  _ov.loadCamera(ba.data());
}

void vvCanvas::saveCamera(const QString& filename)
{
  vvDebugMsg::msg(3, "vvCanvas::saveCamera()");

  QByteArray ba = filename.toLatin1();
  _ov.saveCamera(ba.data());
}

void vvCanvas::initializeGL()
{
  vvDebugMsg::msg(1, "vvCanvas::initializeGL()");

  glewInit();
  init();
}

void vvCanvas::paintGL()
{
  vvDebugMsg::msg(3, "vvCanvas::paintGL()");

  if (_renderer == NULL)
  {
    return;
  }

  if (_doubleBuffering)
  {
    glDrawBuffer(GL_BACK);
  }
  else
  {
    glDrawBuffer(GL_FRONT);
  }

  glClearColor(_bgColor[0], _bgColor[1], _bgColor[2], 0.0f);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  glMatrixMode(GL_MODELVIEW);
  _ov.setModelviewMatrix(vvObjView::CENTER);

  foreach (vvPlugin* plugin, _plugins)
  {
    if (plugin->isActive())
    {
      plugin->prerender();
    }
  }

  _renderer->renderVolumeGL();

  foreach (vvPlugin* plugin, _plugins)
  {
    if (plugin->isActive())
    {
      plugin->postrender();
    }
  }
}

void vvCanvas::resizeGL(const int w, const int h)
{
  vvDebugMsg::msg(3, "vvCanvas::resizeGL()");

  glViewport(0, 0, w, h);
  if (h > 0)
  {
    _ov.setAspectRatio(static_cast<float>(w) / static_cast<float>(h));
  }
  updateGL();

  emit resized(QSize(w, h));
}

void vvCanvas::mouseMoveEvent(QMouseEvent* event)
{
  vvDebugMsg::msg(3, "vvCanvas::mouseMoveEvent()");

  switch (_mouseButton)
  {
  case Qt::LeftButton:
  {
    _ov._camera.trackballRotation(width(), height(),
      _lastMousePos.x(), _lastMousePos.y(),
      event->pos().x(), event->pos().y());
    break;
  }
  case Qt::MiddleButton:
  {
    const float pixelInWorld = _ov.getViewportWidth() / static_cast<float>(width());
    const float dx = static_cast<float>(event->pos().x() - _lastMousePos.x());
    const float dy = static_cast<float>(event->pos().y() - _lastMousePos.y());
    vvVector2f pan(pixelInWorld * dx, pixelInWorld * dy);
    _ov._camera.translate(pan[0], -pan[1], 0.0f);
    break;
  }
  case Qt::RightButton:
  {
    const float factor = event->pos().y() - _lastMousePos.y();
    _ov._camera.translate(0.0f, 0.0f, factor);
    break;
  }
  default:
    break;
  }
  _lastMousePos = event->pos();
  updateGL();
}

void vvCanvas::mousePressEvent(QMouseEvent* event)
{
  vvDebugMsg::msg(3, "vvCanvas::mousePressEvent()");

  _mouseButton = event->button();
  _lastMousePos = event->pos();
}

void vvCanvas::mouseReleaseEvent(QMouseEvent*)
{
  vvDebugMsg::msg(3, "vvCanvas::mouseReleaseEvent()");

  _mouseButton = Qt::NoButton;
}

void vvCanvas::init()
{
  vvDebugMsg::msg(3, "vvCanvas::init()");

  vvFileIO* fio = new vvFileIO;
  fio->loadVolumeData(_vd, vvFileIO::ALL_DATA);
  delete fio;

  // default transfer function
  if (_vd->tf.isEmpty())
  {
    _vd->tf.setDefaultAlpha(0, _vd->real[0], _vd->real[1]);
    _vd->tf.setDefaultColors((_vd->chan == 1) ? 0 : 3, _vd->real[0], _vd->real[1]);
  }

  // init renderer
  if (_vd != NULL)
  {
    _currentRenderer = "viewport";
    _currentOptions["voxeltype"] = "arb";
    createRenderer();
  }

  updateProjection();

  foreach (vvPlugin* plugin, _plugins)
  {
    plugin->setVolDesc(_vd);
  }

  emit newVolDesc(_vd);
}

void vvCanvas::createRenderer()
{
  vvDebugMsg::msg(3, "vvCanvas::createRenderer()");

  vvRenderState state;
  if (_renderer)
  {
    state = *_renderer;
    delete _renderer;
  }

  vvRendererFactory::Options opt(_currentOptions);
  _renderer = vvRendererFactory::create(_vd, state, _currentRenderer.c_str(), opt);
}

void vvCanvas::updateProjection()
{
  vvDebugMsg::msg(3, "vvCanvas::updateProjection()");

  if (_projectionType == vvObjView::PERSPECTIVE)
  {
    _ov.setProjection(vvObjView::PERSPECTIVE, vvObjView::DEF_FOV, vvObjView::DEF_CLIP_NEAR, vvObjView::DEF_CLIP_FAR);
  }
  else if (_projectionType == vvObjView::ORTHO)
  {
    _ov.setProjection(vvObjView::ORTHO, vvObjView::DEF_VIEWPORT_WIDTH, vvObjView::DEF_CLIP_NEAR, vvObjView::DEF_CLIP_FAR);
  }
}

void vvCanvas::setCurrentFrame(const int frame)
{
  vvDebugMsg::msg(3, "vvCanvas::setCurrentFrame()");

  _renderer->setCurrentFrame(frame);
  emit currentFrame(frame);
  updateGL();
}

void vvCanvas::startAnimation(const double fps)
{
  vvDebugMsg::msg(3, "vvCanvas::startAnimation()");

  _vd->dt = 1.0f / static_cast<float>(fps);
  const float delay = std::abs(_vd->dt * 1000.0f);
  _animTimer->start(static_cast<int>(delay));
}

void vvCanvas::stopAnimation()
{
  vvDebugMsg::msg(3, "vvCanvas::stopAnimation()");

  _animTimer->stop();
}

void vvCanvas::setTimeStep(const int step)
{
  vvDebugMsg::msg(3, "vvCanvas::setTimeStep()");

  int f = step;
  while (f < 0)
  {
    f += _vd->frames;
  }

  while (f >= _vd->frames)
  {
    f -= _vd->frames;
  }

  setCurrentFrame(f);
}

void vvCanvas::incTimeStep()
{
  vvDebugMsg::msg(3, "vvCanvas::incTimeStep()");

  int f = _renderer->getCurrentFrame();
  f = (f >= _vd->frames - 1) ? 0 : f + 1;
  setCurrentFrame(f);
}

void vvCanvas::decTimeStep()
{
  vvDebugMsg::msg(3, "vvCanvas::decTimeStep()");

  int f = _renderer->getCurrentFrame();
  f = (f <= 0) ? _vd->frames - 1 : f - 1;
  setCurrentFrame(f);
}

void vvCanvas::firstTimeStep()
{
  vvDebugMsg::msg(3, "vvCanvas::firstTimeStep()");

  setCurrentFrame(0);
}

void vvCanvas::lastTimeStep()
{
  vvDebugMsg::msg(3, "vvCanvas::lastTimeStep()");

  setCurrentFrame(_vd->frames - 1);
}

<|endoftext|>