<commit_before>//=====================================================================//
/*!	@file
	@brief	R8C エンコーダー・メイン
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstring>
#include "main.hpp"
#include "system.hpp"
#include "clock.hpp"
#include "port.hpp"
#include "common/delay.hpp"
#include "common/port_map.hpp"
#include "common/format.hpp"

static uint8_t enc_lvl_ = 0;
static uint8_t enc_pos_ = 0;
static uint8_t enc_neg_ = 0;
static volatile int8_t enc_cnt_ = 0;

class encoder {
public:
	void operator() () {
		uint8_t lvl = device::P1();  ///< 状態の取得
		enc_pos_ = ~enc_lvl_ &  lvl;  ///< 立ち上がりエッジ検出
		enc_neg_ =  enc_lvl_ & ~lvl;  ///< 立ち下がりエッジ検出
		enc_lvl_ = lvl;  ///< 状態のセーブ

		if(enc_pos_ & device::P1.B0.b()) {
			if(enc_lvl_ & device::P1.B1.b()) {
				--enc_cnt_;
			} else {
				++enc_cnt_;
			}
		}
		if(enc_neg_ & device::P1.B0.b()) {
			if(enc_lvl_ & device::P1.B1.b()) {
				++enc_cnt_;
			} else {
				--enc_cnt_;
			}
		}
		if(enc_pos_ & device::P1.B1.b()) {
			if(enc_lvl_ & device::P1.B0.b()) {
				++enc_cnt_;
			} else {
				--enc_cnt_;
			}
		}
		if(enc_neg_ & device::P1.B1.b()) {
			if(enc_lvl_ & device::P1.B0.b()) {
				--enc_cnt_;
			} else {
				++enc_cnt_;
			}
		}
	}
};

static device::trb_io<encoder> timer_b_;
static uart0 uart0_;

extern "C" {
	void sci_putch(char ch) {
		uart0_.putch(ch);
	}

	char sci_getch(void) {
		return uart0_.getch();
	}

	uint16_t sci_length() {
		return uart0_.length();
	}

	void sci_puts(const char* str) {
		uart0_.puts(str);
	}
}

extern "C" {
	const void* variable_vectors_[] __attribute__ ((section (".vvec"))) = {
		(void*)brk_inst_,   nullptr,	// (0)
		(void*)null_task_,  nullptr,	// (1) flash_ready
		(void*)null_task_,  nullptr,	// (2)
		(void*)null_task_,  nullptr,	// (3)

		(void*)null_task_,  nullptr,	// (4) コンパレーターB1
		(void*)null_task_,  nullptr,	// (5) コンパレーターB3
		(void*)null_task_,  nullptr,	// (6)
		(void*)null_task_,  nullptr,	// (7) タイマＲＣ

		(void*)null_task_,  nullptr,	// (8)
		(void*)null_task_,  nullptr,	// (9)
		(void*)null_task_,  nullptr,	// (10)
		(void*)null_task_,  nullptr,	// (11)

		(void*)null_task_,  nullptr,	// (12)
		(void*)null_task_,  nullptr,	// (13) キー入力
		(void*)null_task_,  nullptr,	// (14) A/D 変換
		(void*)null_task_,  nullptr,	// (15)

		(void*)null_task_,  nullptr,	// (16)
		(void*)uart0_.send_task, nullptr,   // (17) UART0 送信
		(void*)uart0_.recv_task, nullptr,   // (18) UART0 受信
		(void*)null_task_,  nullptr,	// (19)

		(void*)null_task_,  nullptr,	// (20)
		(void*)null_task_,  nullptr,	// (21) /INT2
		(void*)null_task_,  nullptr,	// (22) タイマＲＪ２
		(void*)null_task_,  nullptr,	// (23) 周期タイマ

		(void*)timer_b_.itask,  nullptr,	// (24) タイマＲＢ２
		(void*)null_task_,  nullptr,	// (25) /INT1
		(void*)null_task_,  nullptr,	// (26) /INT3
		(void*)null_task_,  nullptr,	// (27)

		(void*)null_task_,  nullptr,	// (28)
		(void*)null_task_,  nullptr,	// (29) /INT0
		(void*)null_task_,  nullptr,	// (30)
		(void*)null_task_,  nullptr,	// (31)
	};
}

int main(int argc, char *argv[])
{
	using namespace device;

// クロック関係レジスタ・プロテクト解除
	PRCR.PRC0 = 1;

// 高速オンチップオシレーターへ切り替え(20MHz)
// ※ F_CLK を設定する事（Makefile内）
	OCOCR.HOCOE = 1;
	utils::delay::micro_second(1);	// >=30uS(125KHz)
	SCKCR.HSCKSEL = 1;
	CKSTPR.SCKSEL = 1;

	// エンコーダー入力の設定 P10: (Phi_A), P11: (Phi_B), Vss: (COM)
	{
		utils::PORT_MAP(utils::port_map::P10::PORT);
		utils::PORT_MAP(utils::port_map::P11::PORT);
		device::PD1.B0 = 0;
		device::PD1.B1 = 0;
		device::PUR1.B0 = 1;	///< プルアップ
		device::PUR1.B1 = 1;	///< プルアップ
	}

	// タイマーＢ初期化
	{
		uint8_t ir_level = 2;
		timer_b_.start_timer(240, ir_level);
	}

	// UART の設定 (P1_4: TXD0[in], P1_5: RXD0[in])
	// ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意！
	{
		utils::PORT_MAP(utils::port_map::P14::TXD0);
		utils::PORT_MAP(utils::port_map::P15::RXD0);
		uint8_t ir_level = 1;
		uart0_.start(19200, ir_level);
	}

	sci_puts("Start R8C ENCODER monitor\n");

	uint8_t cnt = 0;
	int8_t enc_cnt = 0;
	uint16_t count = 0;
	while(1) {
		timer_b_.sync();

		if((cnt & 3) == 0) {
			// エンコーダー値の表示
			if(enc_cnt != enc_cnt_) {
				int8_t d = enc_cnt - enc_cnt_;
				if(d >= 3 || d <= -3) {
					enc_cnt = enc_cnt_;
					if(d > 0) ++count;
					else --count;
					utils::format("%05d\n") % static_cast<uint32_t>(count);
				}
			}
		}

		++cnt;
	}
}
<commit_msg>Update loop<commit_after>//=====================================================================//
/*!	@file
	@brief	R8C エンコーダー・メイン
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstring>
#include "main.hpp"
#include "system.hpp"
#include "clock.hpp"
#include "port.hpp"
#include "common/delay.hpp"
#include "common/port_map.hpp"
#include "common/format.hpp"

static uint8_t enc_lvl_ = 0;
static uint8_t enc_pos_ = 0;
static uint8_t enc_neg_ = 0;
static volatile int8_t enc_cnt_ = 0;

class encoder {
public:
	void operator() () {
		uint8_t lvl = device::P1();  ///< 状態の取得
		enc_pos_ = ~enc_lvl_ &  lvl;  ///< 立ち上がりエッジ検出
		enc_neg_ =  enc_lvl_ & ~lvl;  ///< 立ち下がりエッジ検出
		enc_lvl_ = lvl;  ///< 状態のセーブ

		if(enc_pos_ & device::P1.B0.b()) {
			if(enc_lvl_ & device::P1.B1.b()) {
				--enc_cnt_;
			} else {
				++enc_cnt_;
			}
		}
		if(enc_neg_ & device::P1.B0.b()) {
			if(enc_lvl_ & device::P1.B1.b()) {
				++enc_cnt_;
			} else {
				--enc_cnt_;
			}
		}
		if(enc_pos_ & device::P1.B1.b()) {
			if(enc_lvl_ & device::P1.B0.b()) {
				++enc_cnt_;
			} else {
				--enc_cnt_;
			}
		}
		if(enc_neg_ & device::P1.B1.b()) {
			if(enc_lvl_ & device::P1.B0.b()) {
				--enc_cnt_;
			} else {
				++enc_cnt_;
			}
		}
	}
};

static device::trb_io<encoder> timer_b_;
static uart0 uart0_;

extern "C" {
	void sci_putch(char ch) {
		uart0_.putch(ch);
	}

	char sci_getch(void) {
		return uart0_.getch();
	}

	uint16_t sci_length() {
		return uart0_.length();
	}

	void sci_puts(const char* str) {
		uart0_.puts(str);
	}
}

extern "C" {
	const void* variable_vectors_[] __attribute__ ((section (".vvec"))) = {
		(void*)brk_inst_,   nullptr,	// (0)
		(void*)null_task_,  nullptr,	// (1) flash_ready
		(void*)null_task_,  nullptr,	// (2)
		(void*)null_task_,  nullptr,	// (3)

		(void*)null_task_,  nullptr,	// (4) コンパレーターB1
		(void*)null_task_,  nullptr,	// (5) コンパレーターB3
		(void*)null_task_,  nullptr,	// (6)
		(void*)null_task_,  nullptr,	// (7) タイマＲＣ

		(void*)null_task_,  nullptr,	// (8)
		(void*)null_task_,  nullptr,	// (9)
		(void*)null_task_,  nullptr,	// (10)
		(void*)null_task_,  nullptr,	// (11)

		(void*)null_task_,  nullptr,	// (12)
		(void*)null_task_,  nullptr,	// (13) キー入力
		(void*)null_task_,  nullptr,	// (14) A/D 変換
		(void*)null_task_,  nullptr,	// (15)

		(void*)null_task_,  nullptr,	// (16)
		(void*)uart0_.send_task, nullptr,   // (17) UART0 送信
		(void*)uart0_.recv_task, nullptr,   // (18) UART0 受信
		(void*)null_task_,  nullptr,	// (19)

		(void*)null_task_,  nullptr,	// (20)
		(void*)null_task_,  nullptr,	// (21) /INT2
		(void*)null_task_,  nullptr,	// (22) タイマＲＪ２
		(void*)null_task_,  nullptr,	// (23) 周期タイマ

		(void*)timer_b_.itask,  nullptr,	// (24) タイマＲＢ２
		(void*)null_task_,  nullptr,	// (25) /INT1
		(void*)null_task_,  nullptr,	// (26) /INT3
		(void*)null_task_,  nullptr,	// (27)

		(void*)null_task_,  nullptr,	// (28)
		(void*)null_task_,  nullptr,	// (29) /INT0
		(void*)null_task_,  nullptr,	// (30)
		(void*)null_task_,  nullptr,	// (31)
	};
}

int main(int argc, char *argv[])
{
	using namespace device;

// クロック関係レジスタ・プロテクト解除
	PRCR.PRC0 = 1;

// 高速オンチップオシレーターへ切り替え(20MHz)
// ※ F_CLK を設定する事（Makefile内）
	OCOCR.HOCOE = 1;
	utils::delay::micro_second(1);	// >=30uS(125KHz)
	SCKCR.HSCKSEL = 1;
	CKSTPR.SCKSEL = 1;

	// エンコーダー入力の設定 P10: (Phi_A), P11: (Phi_B), Vss: (COM)
	{
		utils::PORT_MAP(utils::port_map::P10::PORT);
		utils::PORT_MAP(utils::port_map::P11::PORT);
		device::PD1.B0 = 0;
		device::PD1.B1 = 0;
		device::PUR1.B0 = 1;	///< プルアップ
		device::PUR1.B1 = 1;	///< プルアップ
	}

	// タイマーＢ初期化
	{
		uint8_t ir_level = 2;
		timer_b_.start_timer(240, ir_level);
	}

	// UART の設定 (P1_4: TXD0[in], P1_5: RXD0[in])
	// ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意！
	{
		utils::PORT_MAP(utils::port_map::P14::TXD0);
		utils::PORT_MAP(utils::port_map::P15::RXD0);
		uint8_t ir_level = 1;
		uart0_.start(19200, ir_level);
	}

	sci_puts("Start R8C ENCODER monitor\n");

	uint8_t cnt = 0;
	int8_t enc_cnt = 0;
	uint16_t count = 0;
	uint16_t value = 0;
	while(1) {
		timer_b_.sync();

		// エンコーダー値の増減
		if(enc_cnt != enc_cnt_) {
			int8_t d = enc_cnt - enc_cnt_;
			if(d >= 4 || d <= -4) {
				enc_cnt = enc_cnt_;
				if(d > 0) ++count;
				else --count;
			}
		}

		// 表示ループは１／６０秒で動かす
		if((cnt & 3) == 0) {
			if(count != value) {
				value = count;
				utils::format("%05d\n") % static_cast<uint32_t>(count);
			}
		}

		++cnt;
	}
}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// query_statement.cpp
//
// Identification: src/codegen/query_statement.cpp
//
// Copyright (c) 2015-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "codegen/query.h"

#include "catalog/catalog.h"
#include "common/macros.h"

namespace peloton {
namespace codegen {

// Constructor
Query::Query(const planner::AbstractPlan &query_plan)
    : query_plan_(query_plan) {}

// Execute the query on the given database (and within the provided transaction)
// This really involves calling the init(), plan() and tearDown() functions, in
// that order. We also need to correctly handle cases where _any_ of those
// functions throw exceptions.
void Query::Execute(concurrency::Transaction &txn, char *consumer_arg,
                    RuntimeStats *stats) {
  CodeGen codegen{GetCodeContext()};

  llvm::Type *runtime_state_type = runtime_state_.FinalizeType(codegen);
  uint64_t parameter_size = codegen.SizeOf(runtime_state_type);
  PL_ASSERT(parameter_size % 8 == 0);

  // Allocate some space for the function arguments
  std::unique_ptr<char> param_data{new char[parameter_size]};

  // Grab an non-owning pointer to the space
  char *param = param_data.get();

  // Clean the space
  PL_MEMSET(param, 0, parameter_size);

  // We use this handy class to avoid complex casting and pointer manipulation
  struct FunctionArguments {
    concurrency::Transaction *txn;
    catalog::Catalog *catalog;
    char *consumer_arg;
    char rest[0];
  } PACKED;

  // Set up the function arguments
  auto *func_args = reinterpret_cast<FunctionArguments *>(param_data.get());
  func_args->txn = &txn;
  func_args->catalog = catalog::Catalog::GetInstance();
  func_args->consumer_arg = consumer_arg;

  // Timer
  Timer<std::ratio<1, 1000>> timer;
  timer.Start();

  // Call init
  LOG_DEBUG("Calling query's init() ...");
  try {
    init_func_(param);
  } catch (...) {
    // Cleanup if an exception is encountered
    tear_down_func_(param);
    throw;
  }

  // Time initialization
  if (stats != nullptr) {
    timer.Stop();
    stats->init_ms = timer.GetDuration();
    timer.Reset();
    timer.Start();
  }

  // Execute the query!
  LOG_DEBUG("Calling query's plan() ...");
  try {
    plan_func_(param);
  } catch (...) {
    // Cleanup if an exception is encountered
    tear_down_func_(param);
    throw;
  }

  // Timer plan execution
  if (stats != nullptr) {
    timer.Stop();
    stats->plan_ms = timer.GetDuration();
    timer.Reset();
    timer.Start();
  }

  // Clean up
  LOG_DEBUG("Calling query's tearDown() ...");
  tear_down_func_(param);

  // No need to cleanup if we get an exception while cleaning up...
  if (stats != nullptr) {
    timer.Stop();
    stats->tear_down_ms = timer.GetDuration();
  }
}

bool Query::Prepare(const QueryFunctions &query_funcs) {
  LOG_TRACE("Going to JIT the query ...");

  // Compile the code
  if (!code_context_.Compile()) {
    return false;
  }

  LOG_TRACE("Setting up Query ...");

  // Get pointers to the JITed functions
  init_func_ = (compiled_function_t)code_context_.GetFunctionPointer(
      query_funcs.init_func);
  PL_ASSERT(init_func_ != nullptr);

  plan_func_ = (compiled_function_t)code_context_.GetFunctionPointer(
      query_funcs.plan_func);
  PL_ASSERT(plan_func_ != nullptr);

  tear_down_func_ = (compiled_function_t)code_context_.GetFunctionPointer(
      query_funcs.tear_down_func);
  PL_ASSERT(tear_down_func_ != nullptr);

  LOG_TRACE("Query has been setup ...");

  // All is well
  return true;
}

}  // namespace codegen
}  // namespace peloton<commit_msg>Fix memory leak in query parameter creation<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// query_statement.cpp
//
// Identification: src/codegen/query_statement.cpp
//
// Copyright (c) 2015-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "codegen/query.h"

#include "catalog/catalog.h"
#include "common/macros.h"

namespace peloton {
namespace codegen {

// Constructor
Query::Query(const planner::AbstractPlan &query_plan)
    : query_plan_(query_plan) {}

// Execute the query on the given database (and within the provided transaction)
// This really involves calling the init(), plan() and tearDown() functions, in
// that order. We also need to correctly handle cases where _any_ of those
// functions throw exceptions.
void Query::Execute(concurrency::Transaction &txn, char *consumer_arg,
                    RuntimeStats *stats) {
  CodeGen codegen{GetCodeContext()};

  llvm::Type *runtime_state_type = runtime_state_.FinalizeType(codegen);
  uint64_t parameter_size = codegen.SizeOf(runtime_state_type);
  PL_ASSERT(parameter_size % 8 == 0);

  // Allocate some space for the function arguments
  std::unique_ptr<char[]> param_data{new char[parameter_size]};

  // Grab an non-owning pointer to the space
  char *param = param_data.get();

  // Clean the space
  PL_MEMSET(param, 0, parameter_size);

  // We use this handy class to avoid complex casting and pointer manipulation
  struct FunctionArguments {
    concurrency::Transaction *txn;
    catalog::Catalog *catalog;
    char *consumer_arg;
    char rest[0];
  } PACKED;

  // Set up the function arguments
  auto *func_args = reinterpret_cast<FunctionArguments *>(param_data.get());
  func_args->txn = &txn;
  func_args->catalog = catalog::Catalog::GetInstance();
  func_args->consumer_arg = consumer_arg;

  // Timer
  Timer<std::ratio<1, 1000>> timer;
  timer.Start();

  // Call init
  LOG_DEBUG("Calling query's init() ...");
  try {
    init_func_(param);
  } catch (...) {
    // Cleanup if an exception is encountered
    tear_down_func_(param);
    throw;
  }

  // Time initialization
  if (stats != nullptr) {
    timer.Stop();
    stats->init_ms = timer.GetDuration();
    timer.Reset();
    timer.Start();
  }

  // Execute the query!
  LOG_DEBUG("Calling query's plan() ...");
  try {
    plan_func_(param);
  } catch (...) {
    // Cleanup if an exception is encountered
    tear_down_func_(param);
    throw;
  }

  // Timer plan execution
  if (stats != nullptr) {
    timer.Stop();
    stats->plan_ms = timer.GetDuration();
    timer.Reset();
    timer.Start();
  }

  // Clean up
  LOG_DEBUG("Calling query's tearDown() ...");
  tear_down_func_(param);

  // No need to cleanup if we get an exception while cleaning up...
  if (stats != nullptr) {
    timer.Stop();
    stats->tear_down_ms = timer.GetDuration();
  }
}

bool Query::Prepare(const QueryFunctions &query_funcs) {
  LOG_TRACE("Going to JIT the query ...");

  // Compile the code
  if (!code_context_.Compile()) {
    return false;
  }

  LOG_TRACE("Setting up Query ...");

  // Get pointers to the JITed functions
  init_func_ = (compiled_function_t)code_context_.GetFunctionPointer(
      query_funcs.init_func);
  PL_ASSERT(init_func_ != nullptr);

  plan_func_ = (compiled_function_t)code_context_.GetFunctionPointer(
      query_funcs.plan_func);
  PL_ASSERT(plan_func_ != nullptr);

  tear_down_func_ = (compiled_function_t)code_context_.GetFunctionPointer(
      query_funcs.tear_down_func);
  PL_ASSERT(tear_down_func_ != nullptr);

  LOG_TRACE("Query has been setup ...");

  // All is well
  return true;
}

}  // namespace codegen
}  // namespace peloton<|endoftext|>


<commit_before>//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2017 Ryo Suzuki
//	Copyright (c) 2016-2017 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# pragma once
# include <cstdlib>
# include <memory>
# include <type_traits>
# include "Fwd.hpp"

namespace s3d
{
	/// <summary>
	/// アライメントを考慮して、指定した型のためのメモリ領域を確保します。
	/// </summary>
	/// <param name="n">
	/// 要素数。デフォルトは 1
	/// </param>
	/// <remarks>
	/// 確保したポインタは AlignedFree() で解放する必要があります。
	/// </remarks>
	/// <returns>
	/// 確保したメモリ領域の先頭ポインタ
	/// </returns>
	template <class Type, size_t Alignment = alignof(Type)>
	inline Type* AlignedMalloc(const size_t n = 1)
	{
	# if defined(SIV3D_TARGET_WINDOWS)

		return static_cast<Type*>(::_aligned_malloc(sizeof(Type) * n, Alignment));

	# else

		Type* p;
		::posix_memalign(&p, Alignment, sizeof(Type) * n);
		return p;

	# endif
	}

	/// <summary>
	/// AlignedMalloc() で確保したメモリ領域を解放します。
	/// </summary>
	/// <param name="p">
	/// 解放するメモリ領域の先頭ポインタ
	/// </param>
	/// <remarks>
	/// p が nullptr の場合は何も起こりません。
	/// </remarks>
	/// <returns>
	/// なし
	/// </returns>
	inline void AlignedFree(void* const p)
	{
	# if defined(SIV3D_TARGET_WINDOWS)

		::_aligned_free(p);

	# else

		::free(p);

	# endif
	}

	/// <summary>
	/// アライメントを考慮して、指定した型のためのメモリ領域を確保します。
	/// </summary>
	/// <param name="args">
	/// コンストラクタ引数
	/// </param>
	/// <remarks>
	/// 確保したポインタは AlignedDelete() で解放する必要があります。
	/// </remarks>
	/// <returns>
	/// 確保したメモリ領域の先頭ポインタ
	/// </returns>
	template <class Type, class ...Args>
	inline Type* AlignedNew(Args&&... args)
	{
		Type* p = AlignedMalloc<Type>();

		if (p == nullptr)
		{
			throw std::bad_alloc();
		}

		try
		{
			::new (p) Type(std::forward<Args>(args)...);
		}
		catch (...)
		{
			AlignedFree(p);

			throw;
		}

		return p;
	}

	/// <summary>
	/// AlignedNew() で確保したメモリ領域を解放します。
	/// </summary>
	/// <param name="p">
	/// 解放するメモリ領域の先頭ポインタ
	/// </param>
	/// <remarks>
	/// p が nullptr の場合は何も起こりません。
	/// </remarks>
	/// <returns>
	/// なし
	/// </returns>
	template <class Type>
	inline void AlignedDelete(Type* const p)
	{
		if (p == nullptr)
		{
			return;
		}

		p->~Type();

		AlignedFree(p);
	}

	/// <summary>
	/// ポインタがアライメントされているかを返します。
	/// </summary>
	/// <param name="p">
	/// アライメントを調べるポインタ
	/// </param>
	/// <param name="alignment">
	/// アライメント（バイト）
	/// </param>
	/// <returns>
	/// アライメントされている場合 true, それ以外の場合は false
	/// </returns>
	inline bool IsAligned(const void* const p, const size_t alignment) noexcept
	{
		return (reinterpret_cast<size_t>(p) % alignment) == 0;
	}

	/// <summary>
	/// アライメントを考慮したデリータ
	/// </summary>
	template <class Type>
	struct AlignedDeleter
	{
		void operator()(Type* p)
		{
			AlignedDelete(p);
		}
	};

	/// <summary>
	/// 明示的なアライメントの指定が必要な型であるかを判定します。
	/// </summary>
	template <class Type>
	struct HasAlignment
		: std::integral_constant<bool, (alignof(Type) > SIV3D_ALLOCATOR_MIN_ALIGNMENT)> {};

	template <class Type, class ...Args>
	std::unique_ptr<Type, AlignedDeleter<Type>> AlignedUnique(Args&&... args)
	{
		return std::unique_ptr<Type, AlignedDeleter<Type>>(AlignedNew<Type>(std::forward<Args>(args)...));
	}

	template <class Type, class ...Args>
	std::shared_ptr<Type> AlignedShared(Args&&... args)
	{
		return std::shared_ptr<Type>(AlignedNew<Type>(std::forward<Args>(args)...), AlignedDeleter<Type>());
	}

	template <class Type, class ...Args, std::enable_if_t<!HasAlignment<Type>::value>* = nullptr>
	std::unique_ptr<Type> MakeUnique(Args&&... args)
	{
		return std::make_unique<Type>(std::forward<Args>(args)...);
	}

	template <class Type, class ...Args, std::enable_if_t<HasAlignment<Type>::value>* = nullptr>
	std::unique_ptr<Type, AlignedDeleter<Type>> MakeUnique(Args&&... args)
	{
		return AlignedUnique<Type>(std::forward<Args>(args)...);
	}

	template <class Type, class ...Args, std::enable_if_t<!HasAlignment<Type>::value>* = nullptr>
	std::shared_ptr<Type> MakeShared(Args&&... args)
	{
		return std::make_shared<Type>(std::forward<Args>(args)...);
	}

	template <class Type, class ...Args, std::enable_if_t<HasAlignment<Type>::value>* = nullptr>
	std::shared_ptr<Type> MakeShared(Args&&... args)
	{
		return std::shared_ptr<Type>(AlignedNew<Type>(std::forward<Args>(args)...), AlignedDeleter<Type>());
	}
}
<commit_msg>update<commit_after>//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2017 Ryo Suzuki
//	Copyright (c) 2016-2017 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# pragma once
# include <cstdlib>
# include <memory>
# include <type_traits>
# include "Fwd.hpp"

namespace s3d
{
	/// <summary>
	/// アライメントを考慮して、指定した型のためのメモリ領域を確保します。
	/// </summary>
	/// <param name="n">
	/// 要素数。デフォルトは 1
	/// </param>
	/// <remarks>
	/// 確保したポインタは AlignedFree() で解放する必要があります。
	/// </remarks>
	/// <returns>
	/// 確保したメモリ領域の先頭ポインタ
	/// </returns>
	template <class Type, size_t Alignment = alignof(Type)>
	inline Type* AlignedMalloc(const size_t n = 1)
	{
	# if defined(SIV3D_TARGET_WINDOWS)

		return static_cast<Type*>(::_aligned_malloc(sizeof(Type) * n, Alignment));

	# else

		Type* p;
		::posix_memalign(&p, Alignment, sizeof(Type) * n);
		return p;

	# endif
	}

	/// <summary>
	/// AlignedMalloc() で確保したメモリ領域を解放します。
	/// </summary>
	/// <param name="p">
	/// 解放するメモリ領域の先頭ポインタ
	/// </param>
	/// <remarks>
	/// p が nullptr の場合は何も起こりません。
	/// </remarks>
	/// <returns>
	/// なし
	/// </returns>
	inline void AlignedFree(void* const p)
	{
	# if defined(SIV3D_TARGET_WINDOWS)

		::_aligned_free(p);

	# else

		::free(p);

	# endif
	}

	/// <summary>
	/// アライメントを考慮して、指定した型のためのメモリ領域を確保します。
	/// </summary>
	/// <param name="args">
	/// コンストラクタ引数
	/// </param>
	/// <remarks>
	/// 確保したポインタは AlignedDelete() で解放する必要があります。
	/// </remarks>
	/// <returns>
	/// 確保したメモリ領域の先頭ポインタ
	/// </returns>
	template <class Type, class ...Args>
	inline Type* AlignedNew(Args&&... args)
	{
		Type* p = AlignedMalloc<Type>();

		if (p == nullptr)
		{
			throw std::bad_alloc();
		}

		try
		{
			::new (p) Type(std::forward<Args>(args)...);
		}
		catch (...)
		{
			AlignedFree(p);

			throw;
		}

		return p;
	}

	/// <summary>
	/// AlignedNew() で確保したメモリ領域を解放します。
	/// </summary>
	/// <param name="p">
	/// 解放するメモリ領域の先頭ポインタ
	/// </param>
	/// <remarks>
	/// p が nullptr の場合は何も起こりません。
	/// </remarks>
	/// <returns>
	/// なし
	/// </returns>
	template <class Type>
	inline void AlignedDelete(Type* const p)
	{
		if (p == nullptr)
		{
			return;
		}

		p->~Type();

		AlignedFree(p);
	}

	/// <summary>
	/// ポインタがアライメントされているかを返します。
	/// </summary>
	/// <param name="p">
	/// アライメントを調べるポインタ
	/// </param>
	/// <param name="alignment">
	/// アライメント（バイト）
	/// </param>
	/// <returns>
	/// アライメントされている場合 true, それ以外の場合は false
	/// </returns>
	inline bool IsAligned(const void* const p, const size_t alignment) noexcept
	{
		return (reinterpret_cast<size_t>(p) % alignment) == 0;
	}

	/// <summary>
	/// アライメントを考慮したデリータ
	/// </summary>
	template <class Type>
	struct AlignedDeleter
	{
		void operator()(Type* p)
		{
			AlignedDelete(p);
		}
	};

	/// <summary>
	/// 明示的なアライメントの指定が必要な型であるかを判定します。
	/// </summary>
	template <class Type>
	struct HasAlignment
		: std::integral_constant<bool, (alignof(Type) > SIV3D_ALLOCATOR_MIN_ALIGNMENT)> {};

	/// <summary>
	/// アライメントを考慮して、unique_ptr を構築します。
	/// </summary>
	/// <param name="args">
	/// コンストラクタ引数
	/// </param>
	/// <returns>
	/// 構築した unique_ptr
	/// </returns>
	template <class Type, class ...Args, std::enable_if_t<!HasAlignment<Type>::value>* = nullptr>
	std::unique_ptr<Type> MakeUnique(Args&&... args)
	{
		return std::make_unique<Type>(std::forward<Args>(args)...);
	}

	/// <summary>
	/// アライメントを考慮して、unique_ptr を構築します。
	/// </summary>
	/// <param name="args">
	/// コンストラクタ引数
	/// </param>
	/// <returns>
	/// 構築した unique_ptr
	/// </returns>
	template <class Type, class ...Args, std::enable_if_t<HasAlignment<Type>::value>* = nullptr>
	std::unique_ptr<Type, AlignedDeleter<Type>> MakeUnique(Args&&... args)
	{
		return std::unique_ptr<Type, AlignedDeleter<Type>>(AlignedNew<Type>(std::forward<Args>(args)...))
	}

	/// <summary>
	/// アライメントを考慮して、shared_ptr を構築します。
	/// </summary>
	/// <param name="args">
	/// コンストラクタ引数
	/// </param>
	/// <returns>
	/// 構築した shared_ptr
	/// </returns>
	template <class Type, class ...Args, std::enable_if_t<!HasAlignment<Type>::value>* = nullptr>
	std::shared_ptr<Type> MakeShared(Args&&... args)
	{
		return std::make_shared<Type>(std::forward<Args>(args)...);
	}

	/// <summary>
	/// アライメントを考慮して、shared_ptr を構築します。
	/// </summary>
	/// <param name="args">
	/// コンストラクタ引数
	/// </param>
	/// <returns>
	/// 構築した shared_ptr
	/// </returns>
	template <class Type, class ...Args, std::enable_if_t<HasAlignment<Type>::value>* = nullptr>
	std::shared_ptr<Type> MakeShared(Args&&... args)
	{
		return std::shared_ptr<Type>(AlignedNew<Type>(std::forward<Args>(args)...), AlignedDeleter<Type>());
	}
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "EventReceiverTest.h"
#include "Autowiring/Autowired.h"
#include "Autowiring/CoreThread.h"

class CallableInterface:
  public EventReceiver
{
public:
  virtual void ZeroArgs(void) = 0;
  virtual void OneArg(int arg) = 0;
  virtual void AllDone(void) = 0;
};

class SimpleSender:
  public EventManager<CallableInterface>
{
};

class SimpleReceiver:
  public CoreThread,
  public CallableInterface
{
public:
  SimpleReceiver(void):
    CoreThread("SimpleReceiver"),
    m_zero(false),
    m_one(false),
    m_oneArg(0),
    m_barrier(2)
  {
    Ready();
  }

  // Manifest of functions called:
  bool m_zero;

  bool m_one;
  int m_oneArg;

  // Continuity barrier:
  boost::barrier m_barrier;

  void ZeroArgs(void) override {
    m_zero = true;
  }

  void OneArg(int arg) override {
    m_one = true;
    m_oneArg = arg;
  }

  void AllDone(void) override {
    Stop();
  }

  void Run(void) override {
    m_barrier.wait();
    CoreThread::Run();
  }
};

TEST_F(EventReceiverTest, SimpleMethodCall) {
  AutoCurrentContext ctxt;

  AutoRequired<SimpleReceiver> receiver;
  AutoRequired<SimpleSender> sender;

  // Start up the context:
  ctxt->InitiateCoreThreads();

  // Try firing the event first:
  sender->Fire(&CallableInterface::ZeroArgs)();
  sender->Fire(&CallableInterface::OneArg)(100);

  // Verify that stuff happens even when the thread isn't running:
  EXPECT_TRUE(receiver->m_zero);
  EXPECT_TRUE(receiver->m_one);
  EXPECT_EQ(100, receiver->m_oneArg);

  // Unblock:
  receiver->m_barrier.wait();
}

TEST_F(EventReceiverTest, DeferredInvoke) {
  AutoCurrentContext ctxt;

  // Create our transmitter and receiver and start:
  AutoRequired<SimpleReceiver> receiver;
  AutoRequired<SimpleSender> sender;

  // Start up the context:
  ctxt->InitiateCoreThreads();

  // Deferred fire:
  sender->Defer(&CallableInterface::ZeroArgs)();
  sender->Defer(&CallableInterface::OneArg)(101);
  sender->Defer(&CallableInterface::AllDone)();

  // Verify that nothing is hit yet:
  EXPECT_FALSE(receiver->m_zero) << "Zero-argument call made prematurely";
  EXPECT_FALSE(receiver->m_one) << "One-argument call made prematurely";
  EXPECT_TRUE(receiver->IsRunning()) << "Receiver is terminated";

  // Unblock:
  receiver->m_barrier.wait();

  // Now wait until all events are processed:
  receiver->Wait();

  // Validate deferred firing:
  EXPECT_TRUE(receiver->m_zero);
  EXPECT_TRUE(receiver->m_one);
  EXPECT_EQ(101, receiver->m_oneArg) << "Argument was not correctly propagated through a deferred call";
}<commit_msg>Adding nontrivial copy tests<commit_after>#include "stdafx.h"
#include "EventReceiverTest.h"
#include "Autowiring/Autowired.h"
#include "Autowiring/CoreThread.h"
#include <vector>

using namespace std;

class CallableInterface:
  public EventReceiver
{
public:
  virtual void ZeroArgs(void) = 0;
  virtual void OneArg(int arg) = 0;
  virtual void CopyVector(const vector<int>& vec) = 0;
  virtual void CopyVectorForwarded(vector<int>&& vec) = 0;
  virtual void AllDone(void) = 0;
};

class SimpleSender:
  public EventManager<CallableInterface>
{
};

class SimpleReceiver:
  public CoreThread,
  public CallableInterface
{
public:
  SimpleReceiver(void):
    CoreThread("SimpleReceiver"),
    m_zero(false),
    m_one(false),
    m_oneArg(0),
    m_barrier(2)
  {
    Ready();
  }

  // Manifest of functions called:
  bool m_zero;

  bool m_one;
  int m_oneArg;

  // Simple copy operation:
  vector<int> m_myVec;

  // Continuity barrier:
  boost::barrier m_barrier;

  void ZeroArgs(void) override {
    m_zero = true;
  }

  void OneArg(int arg) override {
    m_one = true;
    m_oneArg = arg;
  }

  void CopyVector(const vector<int>& vec) override {
    // Copy out the argument:
    m_myVec = vec;
  }

  void CopyVectorForwarded(vector<int>&& vec) override {
    // Copy out the argument:
    m_myVec = vec;
  }

  void AllDone(void) override {
    Stop();
  }

  void Run(void) override {
    m_barrier.wait();
    CoreThread::Run();
  }
};

TEST_F(EventReceiverTest, SimpleMethodCall) {
  AutoCurrentContext ctxt;

  AutoRequired<SimpleReceiver> receiver;
  AutoRequired<SimpleSender> sender;

  // Start up the context:
  ctxt->InitiateCoreThreads();

  // Try firing the event first:
  sender->Fire(&CallableInterface::ZeroArgs)();
  sender->Fire(&CallableInterface::OneArg)(100);

  // Verify that stuff happens even when the thread isn't running:
  EXPECT_TRUE(receiver->m_zero);
  EXPECT_TRUE(receiver->m_one);
  EXPECT_EQ(100, receiver->m_oneArg);

  // Unblock:
  receiver->m_barrier.wait();
}

TEST_F(EventReceiverTest, DeferredInvoke) {
  AutoCurrentContext ctxt;

  // Create our transmitter and receiver and start:
  AutoRequired<SimpleReceiver> receiver;
  AutoRequired<SimpleSender> sender;

  // Start up the context:
  ctxt->InitiateCoreThreads();

  // Deferred fire:
  sender->Defer(&CallableInterface::ZeroArgs)();
  sender->Defer(&CallableInterface::OneArg)(101);
  sender->Defer(&CallableInterface::AllDone)();

  // Verify that nothing is hit yet:
  EXPECT_FALSE(receiver->m_zero) << "Zero-argument call made prematurely";
  EXPECT_FALSE(receiver->m_one) << "One-argument call made prematurely";
  EXPECT_TRUE(receiver->IsRunning()) << "Receiver is terminated";

  // Unblock:
  receiver->m_barrier.wait();

  // Now wait until all events are processed:
  receiver->Wait();

  // Validate deferred firing:
  EXPECT_TRUE(receiver->m_zero);
  EXPECT_TRUE(receiver->m_one);
  EXPECT_EQ(101, receiver->m_oneArg) << "Argument was not correctly propagated through a deferred call";
}

TEST_F(EventReceiverTest, NontrivialCopy) {
  AutoCurrentContext ctxt;
  static const size_t sc_numElems = 10;

  // Create our transmitter and receiver and start:
  AutoRequired<SimpleReceiver> receiver;
  AutoRequired<SimpleSender> sender;

  // Start up the context:
  ctxt->InitiateCoreThreads();

  // Create the vector we're going to copy over:
  vector<int> ascending;
  for(size_t i = 0; i < sc_numElems; i++)
    ascending.push_back(i);

  // Deferred fire:
  sender->Defer(&CallableInterface::CopyVector)(ascending);
  sender->Defer(&CallableInterface::AllDone)();

  // Verify that nothing is hit yet:
  EXPECT_TRUE(receiver->m_myVec.empty()) << "Event handler invoked before barrier was hit; it should have been deferred";
  EXPECT_TRUE(receiver->IsRunning()) << "Receiver is terminated";

  // Unblock:
  receiver->m_barrier.wait();

  // Now wait until all events are processed:
  receiver->Wait();

  // Validate our vectors:
  ASSERT_EQ(10, receiver->m_myVec.size()) << "Receiver was not populated correctly with a vector";
  for(size_t i = 0; i < sc_numElems; i++)
    EXPECT_EQ(i, ascending[i]) << "Element at offset " << i << " was incorrectly copied";
}
<|endoftext|>


<commit_before>#ifndef DISABLE_VISP
//! needed to avoid a weird bug in ViSP
#define PNG_SKIP_SETJMP_CHECK
#endif
#ifdef _WIN32
#define hypot _hypot
#endif
#include "mtf/TrackerStruct.h"
#include "mtf/Utilities/miscUtils.h"

#include <vector>
#include <map>
#include <memory>

#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"

#include <Python.h>
#include <numpy/arrayobject.h>

using namespace std;
using namespace mtf::params;

static PyObject* initInput(PyObject* self, PyObject* args);
static PyObject* create(PyObject* self, PyObject* args);
static PyObject* getRegion(PyObject* self, PyObject* args);
static PyObject* setRegion(PyObject* self, PyObject* args);
static PyObject* remove(PyObject* self, PyObject* args);

//typedef unique_ptr<mtf::TrackerBase> Tracker_;
//static std::vector<Tracker_> trackers;
//static std::vector<PreProc_> pre_procs;
//static std::vector<bool> tracker_initialized;

static PyMethodDef pyMTFMethods[] = {
	{ "create", create, METH_VARARGS },
	{ "getRegion", getRegion, METH_VARARGS },
	{ "setRegion", setRegion, METH_VARARGS },
	{ "remove", remove, METH_VARARGS },
	{ NULL, NULL, 0, NULL }     /* Sentinel - marks the end of this structure */
};

#if PY_MAJOR_VERSION < 3
PyMODINIT_FUNC initpyMTF()  {
	(void)Py_InitModule("pyMTF", pyMTFMethods);
	import_array();  // Must be present for NumPy.  Called first after above line.
}
#else
static struct PyModuleDef pyMTFModule = {
	PyModuleDef_HEAD_INIT,
	"pyMTF",   /* name of module */
	NULL, /* module documentation, may be NULL */
	-1,       /* size of per-interpreter state of the module,
			  or -1 if the module keeps state in global variables. */
	pyMTFMethods
};
PyMODINIT_FUNC PyInit_pyMTF(void) {
	import_array();
	return PyModule_Create(&pyMTFModule);
}
#endif

static std::map<int, TrackerStruct> trackers;
static unsigned int _tracker_id = 0;

static PyObject* create(PyObject* self, PyObject* args) {
	char* config_root_dir;
	PyArrayObject *img_py, *in_corners_py;

	if(!PyArg_ParseTuple(args, "O!O!|z", &PyArray_Type, &img_py,
		&PyArray_Type, &in_corners_py, &config_root_dir)) {
		PySys_WriteStdout("\n----pyMTF::create: Input arguments could not be parsed----\n\n");
		return Py_BuildValue("i", 0);
	}
	if(img_py == NULL) {
		PySys_WriteStdout("\n----pyMTF::initialize::init_img is NULL----\n\n");
		return Py_BuildValue("i", 0);
	}
	if(in_corners_py == NULL) {
		PySys_WriteStdout("\n----pyMTF::initialize::init_corners is NULL----\n\n");
		return Py_BuildValue("i", 0);
	}
	if(in_corners_py->dimensions[0] != 2 || in_corners_py->dimensions[1] != 4){
		PySys_WriteStdout("pyMTF::Initial corners matrix has incorrect dimensions: %ld, %ld\n",
			in_corners_py->dimensions[0], in_corners_py->dimensions[1]);
		return Py_BuildValue("i", 0);
	}
#ifdef USE_TBB
	Eigen::initParallel();
#endif
	if(!config_root_dir){
		config_root_dir = "../../Config";
		PySys_WriteStdout("Using default configuration folder: %s\n", config_root_dir);
	} else{
		PySys_WriteStdout("Reading MTF configuration files from: %s\n", config_root_dir);
	}
	config_dir = std::string(config_root_dir);
	if(!readParams(0, nullptr)){ return Py_BuildValue("i", 0); }

	PySys_WriteStdout("*******************************\n");
	PySys_WriteStdout("Using parameters:\n");
	PySys_WriteStdout("mtf_sm: %s\n", mtf_sm);
	PySys_WriteStdout("mtf_am: %s\n", mtf_am);
	PySys_WriteStdout("mtf_ssm: %s\n", mtf_ssm);
	PySys_WriteStdout("py_visualize: %d\n", py_visualize);
	PySys_WriteStdout("*******************************\n");

	int img_height = img_py->dimensions[0];
	int img_width = img_py->dimensions[1];
	int n_channels = img_py->nd == 3 ? img_py->dimensions[2] : 1;

	if(n_channels != 1 && n_channels != 3){
		PySys_WriteStdout("pyMTF:: Only grayscale and RGB images are supported\n");
		return Py_BuildValue("i", 0);
	}

	PySys_WriteStdout("img_height: %d\n", img_height);
	PySys_WriteStdout("img_width: %d\n", img_width);
	PySys_WriteStdout("n_channels: %d\n", n_channels);

	int img_type = n_channels == 3 ? CV_8UC3 : CV_8UC1;
	cv::Mat init_img_cv(img_height, img_width, img_type, img_py->data);
	cv::Mat temp(2, 4, CV_64FC1, in_corners_py->data);
	cv::Mat init_corners_cv(2, 4, CV_64FC1);
	init_corners_cv.at<double>(0, 0) = temp.at<double>(0, 0);
	init_corners_cv.at<double>(1, 0) = temp.at<double>(0, 1);
	init_corners_cv.at<double>(0, 1) = temp.at<double>(0, 2);
	init_corners_cv.at<double>(1, 1) = temp.at<double>(0, 3);
	init_corners_cv.at<double>(0, 2) = temp.at<double>(1, 0);
	init_corners_cv.at<double>(1, 2) = temp.at<double>(1, 1);
	init_corners_cv.at<double>(0, 3) = temp.at<double>(1, 2);
	init_corners_cv.at<double>(1, 3) = temp.at<double>(1, 3);

	// PySys_WriteStdout("init_corners_cv:\n");
	// for(unsigned int corner_id = 0; corner_id < 4; ++corner_id) {
	// PySys_WriteStdout("%d: (%f, %f)\n", corner_id, init_corners_cv.at<double>(0, corner_id), init_corners_cv.at<double>(1, corner_id));
	// }

	/*********************************** create and initialize tracker ***********************************/

	TrackerStruct tracker;
	if(!tracker.create(init_img_cv, init_corners_cv)){
		return Py_BuildValue("i", 0);
	}
	++_tracker_id;
	trackers.insert(std::pair<int, TrackerStruct>(_tracker_id, tracker));
	if(py_visualize) {
		cv::namedWindow("PyMTF", cv::WINDOW_AUTOSIZE);
	}
	return Py_BuildValue("i", _tracker_id);
}

static PyObject* getRegion(PyObject* self, PyObject* args) {
	PyArrayObject *img_py, *out_corners_py;
	unsigned int tracker_id;
	/*parse first input array*/
	if(!PyArg_ParseTuple(args, "O!O!|i", &PyArray_Type, &img_py, &PyArray_Type, &out_corners_py, &tracker_id)) {
		PySys_WriteStdout("\n----pyMTF::update: Input arguments could not be parsed----\n\n");
		return Py_BuildValue("i", 0);
	}
	if(img_py == NULL) {
		PySys_WriteStdout("\n----pyMTF::update::input image is NULL----\n\n");
		return Py_BuildValue("i", 0);
	}
	int img_height = img_py->dimensions[0];
	int img_width = img_py->dimensions[1];
	int n_channels = img_py->nd == 3 ? img_py->dimensions[2] : 1;
	int img_type = n_channels == 3 ? CV_8UC3 : CV_8UC1;

	cv::Mat curr_img_cv(img_height, img_width, img_type, img_py->data);

	std::map<int, TrackerStruct>::iterator it = trackers.find(tracker_id);
	if(it == trackers.end()){
		printf("Invalid tracker ID: %d\n", tracker_id);
		return Py_BuildValue("i", 0);
	}
	cv::Mat out_corners;
	if(!it->second.update(curr_img_cv, out_corners)){
		return Py_BuildValue("i", 0);
	}

	if(py_visualize) {
		/* draw tracker positions to OpenCV window */
		cv::Point fps_origin(10, 20);
		double fps_font_size = 0.50;
		cv::Scalar fps_color(0, 255, 0);
		cv::Point2d corners[4];
		mtf::utils::Corners(out_corners).points(corners);
		line(curr_img_cv, corners[0], corners[1], CV_RGB(255, 0, 0), line_thickness);
		line(curr_img_cv, corners[1], corners[2], CV_RGB(255, 0, 0), line_thickness);
		line(curr_img_cv, corners[2], corners[3], CV_RGB(255, 0, 0), line_thickness);
		line(curr_img_cv, corners[3], corners[0], CV_RGB(255, 0, 0), line_thickness);
		putText(curr_img_cv, it->second.name(), corners[0],
			cv::FONT_HERSHEY_SIMPLEX, fps_font_size, CV_RGB(255, 0, 0));
		//std::string fps_text = cv::format("c: %12.6f cw: %12.6f", fps, fps_win);
		//putText(curr_img_cv, fps_text, fps_origin, cv::FONT_HERSHEY_SIMPLEX, fps_font_size, fps_color);
		imshow("PyMTF", curr_img_cv);
		cv::waitKey(1);
	}
	double* out_corners_data = (double*)out_corners_py->data;
	for(unsigned int corner_id = 0; corner_id < 4; ++corner_id) {
		out_corners_data[corner_id] = out_corners.at<double>(0, corner_id);
		out_corners_data[corner_id + 4] = out_corners.at<double>(1, corner_id);
	}
	return Py_BuildValue("i", 1);
}
static PyObject* setRegion(PyObject* self, PyObject* args) {
	PyArrayObject *in_corners_py;
	unsigned int tracker_id = trackers.size() == 0 ? 0 : trackers.size() - 1;
	/*parse first input array*/
	if(!PyArg_ParseTuple(args, "O!|i", &PyArray_Type, &in_corners_py, &tracker_id)) {
		PySys_WriteStdout("\n----pyMTF::setRegion: Input arguments could not be parsed----\n\n");
		return Py_BuildValue("i", 0);
	}
	if(in_corners_py == NULL) {
		PySys_WriteStdout("\n----pyMTF::setRegion::init_corners is NULL----\n\n");
		return Py_BuildValue("i", 0);
	}
	if(in_corners_py->dimensions[0] != 2 || in_corners_py->dimensions[1] != 4){
		PySys_WriteStdout("pyMTF:: Corners matrix has incorrect dimensions: %ld, %ld\n",
			in_corners_py->dimensions[0], in_corners_py->dimensions[1]);
		return Py_BuildValue("i", 0);
	}
	if(tracker_id >= trackers.size()){
		PySys_WriteStdout("\n----pyMTF::setRegion: tracker_id %d is invalid as only %lu trackers exist----\n\n",
			tracker_id, trackers.size());
		return Py_BuildValue("i", 0);
	}
	cv::Mat corners(2, 4, CV_64FC1);

	//cv::Mat temp(2, 4, CV_64FC1, in_corners_py->data);
	//corners.at<double>(0, 0) = temp.at<double>(0, 0);
	//corners.at<double>(1, 0) = temp.at<double>(0, 1);
	//corners.at<double>(0, 1) = temp.at<double>(0, 2);
	//corners.at<double>(1, 1) = temp.at<double>(0, 3);
	//corners.at<double>(0, 2) = temp.at<double>(1, 0);
	//corners.at<double>(1, 2) = temp.at<double>(1, 1);
	//corners.at<double>(0, 3) = temp.at<double>(1, 2);
	//corners.at<double>(1, 3) = temp.at<double>(1, 3);

	double* in_corners_data = (double*)in_corners_py->data;
	for(unsigned int corner_id = 0; corner_id < 4; ++corner_id) {
		corners.at<double>(0, corner_id) = in_corners_data[corner_id];
		corners.at<double>(1, corner_id) = in_corners_data[corner_id + 4];
	}

	//cout << "pyMTF :: setRegion: setting tracker to: \n" << corners << "\n";

	std::map<int, TrackerStruct>::iterator it = trackers.find(tracker_id);
	if(it == trackers.end()){
		printf("Invalid tracker ID: %d\n", tracker_id);
		return Py_BuildValue("i", 0);
	}
	try{
		it->second.setRegion(corners);
	} catch(const mtf::utils::Exception &err){
		printf("Exception of type %s encountered while resetting the tracker: %s\n",
			err.type(), err.what());
		return Py_BuildValue("i", 0);
	}
	return Py_BuildValue("i", 1);

}
static PyObject* remove(PyObject* self, PyObject* args) {
	unsigned int tracker_id;
	/*parse first input array*/
	if(!PyArg_ParseTuple(args, "|i", &PyArray_Type, &tracker_id)) {
		PySys_WriteStdout("\n----pyMTF::remove: Input arguments could not be parsed----\n\n");
		return Py_BuildValue("i", 0);
	}
	std::map<int, TrackerStruct>::iterator it = trackers.find(tracker_id);
	if(it == trackers.end()){
		printf("Invalid tracker ID: %d\n", tracker_id);
		return Py_BuildValue("i", 0);
	}
	trackers.erase(it);
	return Py_BuildValue("i", 1);
}
<commit_msg>fixes in pyMTF;<commit_after>#ifndef DISABLE_VISP
//! needed to avoid a weird bug in ViSP
#define PNG_SKIP_SETJMP_CHECK
#endif
#ifdef _WIN32
#define hypot _hypot
#endif
#include "mtf/TrackerStruct.h"
#include "mtf/Utilities/miscUtils.h"

#include <vector>
#include <map>
#include <memory>

#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"

#include <Python.h>
#include <numpy/arrayobject.h>

using namespace std;
using namespace mtf::params;

static PyObject* initInput(PyObject* self, PyObject* args);
static PyObject* create(PyObject* self, PyObject* args);
static PyObject* getRegion(PyObject* self, PyObject* args);
static PyObject* setRegion(PyObject* self, PyObject* args);
static PyObject* remove(PyObject* self, PyObject* args);

//typedef unique_ptr<mtf::TrackerBase> Tracker_;
//static std::vector<Tracker_> trackers;
//static std::vector<PreProc_> pre_procs;
//static std::vector<bool> tracker_initialized;

static PyMethodDef pyMTFMethods[] = {
	{ "create", create, METH_VARARGS },
	{ "getRegion", getRegion, METH_VARARGS },
	{ "setRegion", setRegion, METH_VARARGS },
	{ "remove", remove, METH_VARARGS },
	{ NULL, NULL, 0, NULL }     /* Sentinel - marks the end of this structure */
};

#if PY_MAJOR_VERSION < 3
PyMODINIT_FUNC initpyMTF()  {
	(void)Py_InitModule("pyMTF", pyMTFMethods);
	import_array();  // Must be present for NumPy.  Called first after above line.
}
#else
static struct PyModuleDef pyMTFModule = {
	PyModuleDef_HEAD_INIT,
	"pyMTF",   /* name of module */
	NULL, /* module documentation, may be NULL */
	-1,       /* size of per-interpreter state of the module,
			  or -1 if the module keeps state in global variables. */
	pyMTFMethods
};
PyMODINIT_FUNC PyInit_pyMTF(void) {
	import_array();
	return PyModule_Create(&pyMTFModule);
}
#endif

static std::map<int, TrackerStruct> trackers;
static unsigned int _tracker_id = 0;

static PyObject* create(PyObject* self, PyObject* args) {
	char* config_root_dir;
	PyArrayObject *img_py, *in_corners_py;

	if(!PyArg_ParseTuple(args, "O!O!|z", &PyArray_Type, &img_py,
		&PyArray_Type, &in_corners_py, &config_root_dir)) {
		PySys_WriteStdout("\n----pyMTF::create: Input arguments could not be parsed----\n\n");
		return Py_BuildValue("i", 0);
	}
	if(img_py == NULL) {
		PySys_WriteStdout("\n----pyMTF::initialize::init_img is NULL----\n\n");
		return Py_BuildValue("i", 0);
	}
	if(in_corners_py == NULL) {
		PySys_WriteStdout("\n----pyMTF::initialize::init_corners is NULL----\n\n");
		return Py_BuildValue("i", 0);
	}
	if(in_corners_py->dimensions[0] != 2 || in_corners_py->dimensions[1] != 4){
		PySys_WriteStdout("pyMTF::Initial corners matrix has incorrect dimensions: %ld, %ld\n",
			in_corners_py->dimensions[0], in_corners_py->dimensions[1]);
		return Py_BuildValue("i", 0);
	}
#ifdef USE_TBB
	Eigen::initParallel();
#endif
	if(!config_root_dir){
		config_root_dir = "../../Config";
		PySys_WriteStdout("Using default configuration folder: %s\n", config_root_dir);
	} else{
		PySys_WriteStdout("Reading MTF configuration files from: %s\n", config_root_dir);
	}
	config_dir = std::string(config_root_dir);
	if(!readParams(0, nullptr)){ return Py_BuildValue("i", 0); }

	PySys_WriteStdout("*******************************\n");
	PySys_WriteStdout("Using parameters:\n");
	PySys_WriteStdout("mtf_sm: %s\n", mtf_sm);
	PySys_WriteStdout("mtf_am: %s\n", mtf_am);
	PySys_WriteStdout("mtf_ssm: %s\n", mtf_ssm);
	PySys_WriteStdout("py_visualize: %d\n", py_visualize);
	PySys_WriteStdout("*******************************\n");

	int img_height = img_py->dimensions[0];
	int img_width = img_py->dimensions[1];
	int n_channels = img_py->nd == 3 ? img_py->dimensions[2] : 1;

	if(n_channels != 1 && n_channels != 3){
		PySys_WriteStdout("pyMTF:: Only grayscale and RGB images are supported\n");
		return Py_BuildValue("i", 0);
	}

	PySys_WriteStdout("img_height: %d\n", img_height);
	PySys_WriteStdout("img_width: %d\n", img_width);
	PySys_WriteStdout("n_channels: %d\n", n_channels);

	int img_type = n_channels == 3 ? CV_8UC3 : CV_8UC1;
	cv::Mat init_img_cv(img_height, img_width, img_type, img_py->data);
	cv::Mat temp(2, 4, CV_64FC1, in_corners_py->data);
	cv::Mat init_corners_cv(2, 4, CV_64FC1);
	init_corners_cv.at<double>(0, 0) = temp.at<double>(0, 0);
	init_corners_cv.at<double>(1, 0) = temp.at<double>(0, 1);
	init_corners_cv.at<double>(0, 1) = temp.at<double>(0, 2);
	init_corners_cv.at<double>(1, 1) = temp.at<double>(0, 3);
	init_corners_cv.at<double>(0, 2) = temp.at<double>(1, 0);
	init_corners_cv.at<double>(1, 2) = temp.at<double>(1, 1);
	init_corners_cv.at<double>(0, 3) = temp.at<double>(1, 2);
	init_corners_cv.at<double>(1, 3) = temp.at<double>(1, 3);

	// PySys_WriteStdout("init_corners_cv:\n");
	// for(unsigned int corner_id = 0; corner_id < 4; ++corner_id) {
	// PySys_WriteStdout("%d: (%f, %f)\n", corner_id, init_corners_cv.at<double>(0, corner_id), init_corners_cv.at<double>(1, corner_id));
	// }

	/*********************************** create and initialize tracker ***********************************/

	TrackerStruct tracker;
	if(!tracker.create(init_img_cv, init_corners_cv)){
		return Py_BuildValue("i", 0);
	}
	++_tracker_id;
	trackers.insert(std::pair<int, TrackerStruct>(_tracker_id, tracker));
	if(py_visualize) {
		cv::namedWindow("PyMTF", cv::WINDOW_AUTOSIZE);
	}
	return Py_BuildValue("I", _tracker_id);
}

static PyObject* getRegion(PyObject* self, PyObject* args) {
	PyArrayObject *img_py, *out_corners_py;
	unsigned int tracker_id;
	/*parse first input array*/
	if(!PyArg_ParseTuple(args, "O!O!I", &PyArray_Type, &img_py, &PyArray_Type, &out_corners_py, &tracker_id)) {
		PySys_WriteStdout("\n----pyMTF::update: Input arguments could not be parsed----\n\n");
		return Py_BuildValue("i", 0);
	}
	if(img_py == NULL) {
		PySys_WriteStdout("\n----pyMTF::update::input image is NULL----\n\n");
		return Py_BuildValue("i", 0);
	}
	int img_height = img_py->dimensions[0];
	int img_width = img_py->dimensions[1];
	int n_channels = img_py->nd == 3 ? img_py->dimensions[2] : 1;
	int img_type = n_channels == 3 ? CV_8UC3 : CV_8UC1;

	cv::Mat curr_img_cv(img_height, img_width, img_type, img_py->data);

	std::map<int, TrackerStruct>::iterator it = trackers.find(tracker_id);
	if(it == trackers.end()){
		printf("Invalid tracker ID: %d\n", tracker_id);
		return Py_BuildValue("i", 0);
	}
	cv::Mat out_corners;
	if(!it->second.update(curr_img_cv, out_corners)){
		return Py_BuildValue("i", 0);
	}

	if(py_visualize) {
		/* draw tracker positions to OpenCV window */
		cv::Point fps_origin(10, 20);
		double fps_font_size = 0.50;
		cv::Scalar fps_color(0, 255, 0);
		cv::Point2d corners[4];
		mtf::utils::Corners(out_corners).points(corners);
		line(curr_img_cv, corners[0], corners[1], CV_RGB(255, 0, 0), line_thickness);
		line(curr_img_cv, corners[1], corners[2], CV_RGB(255, 0, 0), line_thickness);
		line(curr_img_cv, corners[2], corners[3], CV_RGB(255, 0, 0), line_thickness);
		line(curr_img_cv, corners[3], corners[0], CV_RGB(255, 0, 0), line_thickness);
		putText(curr_img_cv, it->second.name(), corners[0],
			cv::FONT_HERSHEY_SIMPLEX, fps_font_size, CV_RGB(255, 0, 0));
		//std::string fps_text = cv::format("c: %12.6f cw: %12.6f", fps, fps_win);
		//putText(curr_img_cv, fps_text, fps_origin, cv::FONT_HERSHEY_SIMPLEX, fps_font_size, fps_color);
		imshow("PyMTF", curr_img_cv);
		cv::waitKey(1);
	}
	double* out_corners_data = (double*)out_corners_py->data;
	for(unsigned int corner_id = 0; corner_id < 4; ++corner_id) {
		out_corners_data[corner_id] = out_corners.at<double>(0, corner_id);
		out_corners_data[corner_id + 4] = out_corners.at<double>(1, corner_id);
	}
	return Py_BuildValue("i", 1);
}
static PyObject* setRegion(PyObject* self, PyObject* args) {
	PyArrayObject *in_corners_py;
	unsigned int tracker_id = trackers.size() == 0 ? 0 : trackers.size() - 1;
	/*parse first input array*/
	if(!PyArg_ParseTuple(args, "O!I", &PyArray_Type, &in_corners_py, &tracker_id)) {
		PySys_WriteStdout("\n----pyMTF::setRegion: Input arguments could not be parsed----\n\n");
		return Py_BuildValue("i", 0);
	}
	if(in_corners_py == NULL) {
		PySys_WriteStdout("\n----pyMTF::setRegion::init_corners is NULL----\n\n");
		return Py_BuildValue("i", 0);
	}
	if(in_corners_py->dimensions[0] != 2 || in_corners_py->dimensions[1] != 4){
		PySys_WriteStdout("pyMTF:: Corners matrix has incorrect dimensions: %ld, %ld\n",
			in_corners_py->dimensions[0], in_corners_py->dimensions[1]);
		return Py_BuildValue("i", 0);
	}
	cv::Mat corners(2, 4, CV_64FC1);

	//cv::Mat temp(2, 4, CV_64FC1, in_corners_py->data);
	//corners.at<double>(0, 0) = temp.at<double>(0, 0);
	//corners.at<double>(1, 0) = temp.at<double>(0, 1);
	//corners.at<double>(0, 1) = temp.at<double>(0, 2);
	//corners.at<double>(1, 1) = temp.at<double>(0, 3);
	//corners.at<double>(0, 2) = temp.at<double>(1, 0);
	//corners.at<double>(1, 2) = temp.at<double>(1, 1);
	//corners.at<double>(0, 3) = temp.at<double>(1, 2);
	//corners.at<double>(1, 3) = temp.at<double>(1, 3);

	double* in_corners_data = (double*)in_corners_py->data;
	for(unsigned int corner_id = 0; corner_id < 4; ++corner_id) {
		corners.at<double>(0, corner_id) = in_corners_data[corner_id];
		corners.at<double>(1, corner_id) = in_corners_data[corner_id + 4];
	}

	//cout << "pyMTF :: setRegion: setting tracker to: \n" << corners << "\n";

	std::map<int, TrackerStruct>::iterator it = trackers.find(tracker_id);
	if(it == trackers.end()){
		printf("Invalid tracker ID: %d\n", tracker_id);
		return Py_BuildValue("i", 0);
	}
	try{
		it->second.setRegion(corners);
	} catch(const mtf::utils::Exception &err){
		printf("Exception of type %s encountered while resetting the tracker: %s\n",
			err.type(), err.what());
		return Py_BuildValue("i", 0);
	}
	return Py_BuildValue("i", 1);

}
static PyObject* remove(PyObject* self, PyObject* args) {
	unsigned int tracker_id;
	/*parse first input array*/
	if(!PyArg_ParseTuple(args, "I", &PyArray_Type, &tracker_id)) {
		PySys_WriteStdout("\n----pyMTF::remove: Input arguments could not be parsed----\n\n");
		return Py_BuildValue("i", 0);
	}
	std::map<int, TrackerStruct>::iterator it = trackers.find(tracker_id);
	if(it == trackers.end()){
		printf("Invalid tracker ID: %d\n", tracker_id);
		return Py_BuildValue("i", 0);
	}
	trackers.erase(it);
	return Py_BuildValue("i", 1);
}
<|endoftext|>


<commit_before>/*
  Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <amr_single_step.h>
#include <fclaw2d_map.h>
#include <p4est_connectivity.h>

#include <amr_forestclaw.H>
#include <amr_utils.H>
#include <fclaw_options.h>

#include <fclaw2d_map_query.h>

#include <fclaw_package.h>
#include <fc2d_clawpack46.H>

#include "sphere_user.H"

typedef struct user_options
{
    int example;
    int is_registered;

} user_options_t;

static void *
    options_register_user (fclaw_app_t * app, void *package, sc_options_t * opt)
{
    user_options_t* user = (user_options_t*) package;

    sc_options_add_int (opt, 0, "example", &user->example, 0,
                        "[user] 1 for pillow grid, "    \
                        "2 for cubed sphere ");
    user->is_registered = 1;
    return NULL;
}

static fclaw_exit_type_t
    options_check_user (fclaw_app_t * app, void *package, void *registered)
{
    user_options_t* user = (user_options_t*) package;
    if (user->example < 1 || user->example > 2) {
        fclaw_global_essentialf ("Option --user:example must be 1 or 2\n");
        return FCLAW_EXIT_ERROR;
    }
    return FCLAW_NOEXIT;
}

static const fclaw_app_options_vtable_t options_vtable_user = {
    options_register_user,
    NULL,      /* options_postprocess_user */
    options_check_user,
    NULL       /* options_destroy_user */
};

void static
    register_user_options (fclaw_app_t * app,
                           const char *configfile,
                           user_options_t* user)
{
    FCLAW_ASSERT (app != NULL);

    fclaw_app_options_register (app,"user", configfile, &options_vtable_user,
                                user);
}

static
    void run_program(fclaw_app_t* app, amr_options_t* gparms,
                     fc2d_clawpack46_options_t* clawpack_options,
                     user_options_t* user)
    {
        sc_MPI_Comm            mpicomm;

        /* Mapped, multi-block domain */
        p4est_connectivity_t     *conn = NULL;
        fclaw2d_domain_t	 *domain;
        fclaw2d_map_context_t    *cont = NULL;

        /* Used locally */
        double pi = M_PI;
        double rotate[2];

        mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);

        rotate[0] = pi*gparms->theta/180.0;
        rotate[1] = pi*gparms->phi/180.0;

        switch (user->example) {
        case 1:
            conn = p4est_connectivity_new_pillow();
            cont = fclaw2d_map_new_pillowsphere(gparms->scale,gparms->shift,rotate);
            break;
        case 2:
            conn = p4est_connectivity_new_cubed();
            cont = fclaw2d_map_new_cubedsphere(gparms->scale,gparms->shift,rotate);
            break;
        default:
            SC_ABORT_NOT_REACHED (); /* must be checked in torus_checkparms */
        }

        domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont);

        fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_ESSENTIAL);
        fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);

        /* ---------------------------------------------------------------
           Set domain data.
           --------------------------------------------------------------- */
        init_domain_data(domain);

        /* Store parameters */
        set_domain_parms(domain,gparms);
        fc2d_clawpack46_set_options (domain,clawpack_options);

        /* Link solvers to the domain */
        link_problem_setup(domain,fc2d_clawpack46_setprob);

        sphere_link_solvers(domain);

        /* --------------------------------------------------
           Initialize and run the simulation
           -------------------------------------------------- */
        amrinit(&domain);
        amrrun(&domain);
        amrreset(&domain);

        /* --------------------------------------------------
           Clean up the mapping context.
           -------------------------------------------------- */
        fclaw2d_map_destroy (cont);
    }

int main (int argc, char **argv)
{
    fclaw_app_t *app;
    int first_arg;
    fclaw_exit_type_t vexit;

    /* Options */
    sc_options_t             *options;
    amr_options_t            samr_options,      *gparms = &samr_options;
    fc2d_clawpack46_options_t     sclawpack_options, *clawpack_options = &sclawpack_options;
    user_options_t           suser_options,     *user = &suser_options;

    int retval;

    /* Initialize application */
    app = fclaw_app_new (&argc, &argv, user);
    options = fclaw_app_get_options (app);
    fclaw_package_container_new(app);

    /*  Register options for each package */
    fclaw_options_register_general (app, "fclaw_options.ini", gparms);
    fc2d_clawpack46_options_register (app, "fclaw_options.ini", clawpack_options);

    register_user_options (app, "fclaw_options.ini", user);

    /* Read configuration file(s) and command line, and process options */
    retval = fclaw_options_read_from_file(options);
    vexit =  fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used");

    /* Register packages */
    fc2d_clawpack46_package_register(app,clawpack_options);

    link_app_to_clawpatch(app);

    /* Run program */
    if (!retval & !vexit)
    {
        run_program(app, gparms, clawpack_options, user);
    }

    fclaw_package_container_destroy(app);
    fclaw_app_destroy (app);

    return 0;
}
<commit_msg>(sphere) Trying out new registration process<commit_after>/*
  Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <amr_single_step.h>
#include <fclaw2d_map.h>
#include <p4est_connectivity.h>

#include <amr_forestclaw.H>
#include <amr_utils.H>
#include <fclaw_options.h>

#include <fclaw2d_map_query.h>

#include <fclaw_package.h>
#include <fclaw_register.h>
#include <fc2d_clawpack46.H>

#include "sphere_user.H"

typedef struct user_options
{
    int example;
    int is_registered;

} user_options_t;

static void *
    options_register_user (fclaw_app_t * app, void *package, sc_options_t * opt)
{
    user_options_t* user = (user_options_t*) package;

    sc_options_add_int (opt, 0, "example", &user->example, 0,
                        "[user] 1 for pillow grid, "    \
                        "2 for cubed sphere ");
    user->is_registered = 1;
    return NULL;
}

static fclaw_exit_type_t
    options_check_user (fclaw_app_t * app, void *package, void *registered)
{
    user_options_t* user = (user_options_t*) package;
    if (user->example < 1 || user->example > 2) {
        fclaw_global_essentialf ("Option --user:example must be 1 or 2\n");
        return FCLAW_EXIT_ERROR;
    }
    return FCLAW_NOEXIT;
}

static const fclaw_app_options_vtable_t options_vtable_user = {
    options_register_user,
    NULL,      /* options_postprocess_user */
    options_check_user,
    NULL       /* options_destroy_user */
};

void static
    register_user_options (fclaw_app_t * app,
                           const char *configfile,
                           user_options_t* user)
{
    FCLAW_ASSERT (app != NULL);

    fclaw_app_options_register (app,"user", configfile, &options_vtable_user,
                                user);
}

static
    void run_program(fclaw_app_t* app,
                     user_options_t* user)
    {
        sc_MPI_Comm            mpicomm;

        /* Mapped, multi-block domain */
        p4est_connectivity_t     *conn = NULL;
        fclaw2d_domain_t	 *domain;
        fclaw2d_map_context_t    *cont = NULL;

        amr_options_t            *gparms;
        fc2d_clawpack46_options_t    *clawpack_options;

        /* Used locally */
        double pi = M_PI;
        double rotate[2];

        gparms = fclaw_forestclaw_get_options(app);
        clawpack_options = fc2d_clawpack46_get_options(app);

        mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);

        rotate[0] = pi*gparms->theta/180.0;
        rotate[1] = pi*gparms->phi/180.0;

        switch (user->example) {
        case 1:
            conn = p4est_connectivity_new_pillow();
            cont = fclaw2d_map_new_pillowsphere(gparms->scale,gparms->shift,rotate);
            break;
        case 2:
            conn = p4est_connectivity_new_cubed();
            cont = fclaw2d_map_new_cubedsphere(gparms->scale,gparms->shift,rotate);
            break;
        default:
            SC_ABORT_NOT_REACHED (); /* must be checked in torus_checkparms */
        }

        domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont);

        fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_ESSENTIAL);
        fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);

        /* ---------------------------------------------------------------
           Set domain data.
           --------------------------------------------------------------- */
        init_domain_data(domain);

        /* Store parameters */
        set_domain_parms(domain,gparms);
        fc2d_clawpack46_set_options (domain,clawpack_options);

        /* Link solvers to the domain */
        link_problem_setup(domain,fc2d_clawpack46_setprob);

        sphere_link_solvers(domain);

        /* --------------------------------------------------
           Initialize and run the simulation
           -------------------------------------------------- */
        amrinit(&domain);
        amrrun(&domain);
        amrreset(&domain);

        /* --------------------------------------------------
           Clean up the mapping context.
           -------------------------------------------------- */
        fclaw2d_map_destroy (cont);
    }

int main (int argc, char **argv)
{
    fclaw_app_t *app;
    int first_arg;
    fclaw_exit_type_t vexit;

    /* Options */
    sc_options_t             *options;
    user_options_t           suser_options,     *user = &suser_options;

    int retval;

    /* Initialize application */
    app = fclaw_app_new (&argc, &argv, user);

    fclaw_forestclaw_register(app,"fclaw_options.ini");
    fc2d_clawpack46_register(app,"fclaw_options.ini");

    register_user_options (app, "fclaw_options.ini", user);

    /* Read configuration file(s) and command line, and process options */
    options = fclaw_app_get_options (app);
    retval = fclaw_options_read_from_file(options);
    vexit =  fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used");

    link_app_to_clawpatch(app);

    /* Run program */
    if (!retval & !vexit)
    {
        run_program(app, user);
    }

    fclaw_forestclaw_destroy(app);
    fc2d_clawpack46_destroy(app);
    fclaw_app_destroy (app);

    return 0;
}
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include "../lib/SofaModeler.h"

#include <sofa/helper/system/glut.h>
#include <sofa/helper/system/SetDirectory.h>
#include <sofa/helper/system/PluginManager.h>
#include <sofa/helper/system/FileSystem.h>
#include <sofa/helper/Utils.h>

#include <sofa/simulation/tree/init.h>
#include <sofa/simulation/tree/TreeSimulation.h>

#include <SofaComponentMain/init.h>

#include <QtGui/QApplication>

#include <iostream>
#include <fstream>

using sofa::helper::system::FileSystem;
using sofa::helper::Utils;

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

int main(int argc, char** argv)
{
    glutInit(&argc,argv);
    sofa::simulation::tree::init();
    sofa::component::init();

    QApplication* application = new QApplication(argc, argv);
    (void)application;

    sofa::simulation::setSimulation(new sofa::simulation::tree::TreeSimulation());

    const std::string etcDir = Utils::getSofaPathPrefix() + "/etc";
    const std::string sofaIniFilePath = etcDir + "/sofa.ini";
    std::map<std::string, std::string> iniFileValues = Utils::readBasicIniFile(sofaIniFilePath);

    if (iniFileValues.find("SHARE_DIR") != iniFileValues.end())
    {
        std::string shareDir = iniFileValues["SHARE_DIR"];
        if (!FileSystem::isAbsolute(shareDir))
            shareDir = etcDir + "/" + shareDir;
        sofa::helper::system::DataRepository.addFirstPath(shareDir);
    }

    if (iniFileValues.find("EXAMPLES_DIR") != iniFileValues.end())
    {
        std::string examplesDir = iniFileValues["EXAMPLES_DIR"];
        if (!FileSystem::isAbsolute(examplesDir))
            examplesDir = etcDir + "/" + examplesDir;
        sofa::helper::system::DataRepository.addFirstPath(examplesDir);
    }

#ifdef WIN32
    const std::string pluginDir = Utils::getExecutableDirectory();
#else
    const std::string pluginDir = Utils::getSofaPathPrefix() + "/lib";
#endif
    sofa::helper::system::PluginRepository.addFirstPath(pluginDir);

	Q_INIT_RESOURCE(icons);
    sofa::gui::qt::SofaModeler* sofaModeler = new sofa::gui::qt::SofaModeler();

    application->setMainWidget(sofaModeler);
    sofaModeler->show();

    std::string binaryName=argv[0];
#ifdef WIN32
    const std::string exe=".exe";
    if (binaryName.size() > exe.size()) binaryName = binaryName.substr(0, binaryName.size()-exe.size());
#endif
    if (!binaryName.empty() && binaryName[binaryName.size()-1] == 'd') sofaModeler->setDebugBinary(true);

    QString pathIcon=(sofa::helper::system::DataRepository.getFirstPath() + std::string( "/icons/MODELER.png" )).c_str();
    application->setWindowIcon(QIcon(pathIcon));

    for (int i=1; i<argc; ++i)
    {
        //Try to open the simulations passed in command line
        sofaModeler->fileOpen(std::string(argv[i]));
    }
    if (argc <= 1 ) sofaModeler->newTab();

    return application->exec();
}
<commit_msg>Modeler : cleanup before exiting<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include "../lib/SofaModeler.h"

#include <sofa/helper/system/glut.h>
#include <sofa/helper/system/SetDirectory.h>
#include <sofa/helper/system/PluginManager.h>
#include <sofa/helper/system/FileSystem.h>
#include <sofa/helper/Utils.h>

#include <sofa/simulation/tree/init.h>
#include <sofa/simulation/tree/TreeSimulation.h>

#include <SofaComponentMain/init.h>

#include <QtGui/QApplication>

#include <iostream>
#include <fstream>

using sofa::helper::system::FileSystem;
using sofa::helper::Utils;

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

int main(int argc, char** argv)
{
    glutInit(&argc,argv);
    sofa::simulation::tree::init();
    sofa::component::init();

    QApplication* application = new QApplication(argc, argv);
    (void)application;

    sofa::simulation::setSimulation(new sofa::simulation::tree::TreeSimulation());

    const std::string etcDir = Utils::getSofaPathPrefix() + "/etc";
    const std::string sofaIniFilePath = etcDir + "/sofa.ini";
    std::map<std::string, std::string> iniFileValues = Utils::readBasicIniFile(sofaIniFilePath);

    if (iniFileValues.find("SHARE_DIR") != iniFileValues.end())
    {
        std::string shareDir = iniFileValues["SHARE_DIR"];
        if (!FileSystem::isAbsolute(shareDir))
            shareDir = etcDir + "/" + shareDir;
        sofa::helper::system::DataRepository.addFirstPath(shareDir);
    }

    if (iniFileValues.find("EXAMPLES_DIR") != iniFileValues.end())
    {
        std::string examplesDir = iniFileValues["EXAMPLES_DIR"];
        if (!FileSystem::isAbsolute(examplesDir))
            examplesDir = etcDir + "/" + examplesDir;
        sofa::helper::system::DataRepository.addFirstPath(examplesDir);
    }

#ifdef WIN32
    const std::string pluginDir = Utils::getExecutableDirectory();
#else
    const std::string pluginDir = Utils::getSofaPathPrefix() + "/lib";
#endif
    sofa::helper::system::PluginRepository.addFirstPath(pluginDir);

	Q_INIT_RESOURCE(icons);
    sofa::gui::qt::SofaModeler* sofaModeler = new sofa::gui::qt::SofaModeler();

    application->setMainWidget(sofaModeler);
    sofaModeler->show();

    std::string binaryName=argv[0];
#ifdef WIN32
    const std::string exe=".exe";
    if (binaryName.size() > exe.size()) binaryName = binaryName.substr(0, binaryName.size()-exe.size());
#endif
    if (!binaryName.empty() && binaryName[binaryName.size()-1] == 'd') sofaModeler->setDebugBinary(true);

    QString pathIcon=(sofa::helper::system::DataRepository.getFirstPath() + std::string( "/icons/MODELER.png" )).c_str();
    application->setWindowIcon(QIcon(pathIcon));

    for (int i=1; i<argc; ++i)
    {
        //Try to open the simulations passed in command line
        sofaModeler->fileOpen(std::string(argv[i]));
    }
    if (argc <= 1 ) sofaModeler->newTab();

    int appReturnCode = application->exec();
    sofa::simulation::tree::cleanup();
    return appReturnCode;
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <algorithm>

#include "il/IntermediateProgram.hpp"
#include "il/Instruction.hpp"

#include "il/InstructionFactory32.hpp"

using namespace eddic;

IntermediateProgram::IntermediateProgram(){
    m_factory = std::make_shared<InstructionFactory>();
}

const InstructionFactory& IntermediateProgram::factory(){
    return *m_factory;
}

void IntermediateProgram::addInstruction(std::shared_ptr<Instruction> instruction){
    m_instructions.push_back(instruction);
}

void IntermediateProgram::writeAsm(AssemblyFileWriter& writer){
    for_each(m_instructions.begin(), m_instructions.end(), [&](std::shared_ptr<Instruction> i){ i->write(writer); });
}
<commit_msg>Fix make_shared<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <algorithm>

#include "il/IntermediateProgram.hpp"
#include "il/Instruction.hpp"

#include "il/InstructionFactory32.hpp"

using namespace eddic;

IntermediateProgram::IntermediateProgram(){
    m_factory = std::make_shared<InstructionFactory32>();
}

const InstructionFactory& IntermediateProgram::factory(){
    return *m_factory;
}

void IntermediateProgram::addInstruction(std::shared_ptr<Instruction> instruction){
    m_instructions.push_back(instruction);
}

void IntermediateProgram::writeAsm(AssemblyFileWriter& writer){
    for_each(m_instructions.begin(), m_instructions.end(), [&](std::shared_ptr<Instruction> i){ i->write(writer); });
}
<|endoftext|>


<commit_before>// File_Scte20 - Info for SCTE 20 streams
// Copyright (C) 2010-2010 MediaArea.net SARL, Info@MediaArea.net
//
// This library is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// 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. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// Compilation conditions
#include "MediaInfo/Setup.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_SCTE20_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Text/File_Scte20.h"
#if defined(MEDIAINFO_EIA608_YES)
    #include "MediaInfo/Text/File_Eia608.h"
#endif
#if defined(MEDIAINFO_EIA708_YES)
    #include "MediaInfo/Text/File_Eia708.h"
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//---------------------------------------------------------------------------

//***************************************************************************
// Infos
//***************************************************************************

//---------------------------------------------------------------------------
const char* Scte20_field_number (int8u field_number)
{
    switch (field_number)
    {
        case  0 : return "Forbidden";
        case  1 : return "1st display field";
        case  2 : return "2nd display field";
        case  3 : return "3rd display fieldt";
        default : return "";
    }
}

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
File_Scte20::File_Scte20()
:File__Analyze()
{
    //Configuration
    PTS_DTS_Needed=true;

    //In
    AspectRatio=0;

    //Temp
    Streams.resize(3); //CEA-608 Field 1, CEA-608 Field 2, CEA-708 Channel
    Streams_Count=0;
}

//---------------------------------------------------------------------------
File_Scte20::~File_Scte20()
{
    for (size_t Pos=0; Pos<Streams.size(); Pos++)
        delete Streams[Pos]; //Streams[Pos]=NULL
}

//***************************************************************************
// Streams management
//***************************************************************************

//---------------------------------------------------------------------------
void File_Scte20::Streams_Fill()
{
    //Filling
    for (size_t Pos=0; Pos<Streams.size(); Pos++)
        if (Streams[Pos] && Streams[Pos]->Parser && Streams[Pos]->Parser->Status[IsFilled])
        {
            Merge(*Streams[Pos]->Parser);
            if (Pos<2)
                Fill(Stream_Text, StreamPos_Last, Text_ID, _T("608-")+Ztring::ToZtring(Pos));
            Fill(Stream_Text, StreamPos_Last, "MuxingMode", _T("SCTE 20"));
        }
}

//---------------------------------------------------------------------------
void File_Scte20::Streams_Finish()
{
    //Filling
    for (size_t Pos=0; Pos<Streams.size(); Pos++)
        if (Streams[Pos] && Streams[Pos]->Parser && Streams[Pos]->Parser->Status[IsFilled])
            Finish(Streams[Pos]->Parser);
}

//***************************************************************************
// Buffer - Synchro
//***************************************************************************

//---------------------------------------------------------------------------
void File_Scte20::Read_Buffer_Unsynched()
{
    //Parsing
    for (size_t Pos=0; Pos<Streams.size(); Pos++)
        if (Streams[Pos] && Streams[Pos]->Parser)
            Streams[Pos]->Parser->Open_Buffer_Unsynch();
}

//***************************************************************************
// Buffer - Global
//***************************************************************************

static inline int8u ReverseBits(int8u c)
{
    // Input: bit order is 76543210
    //Output: bit order is 01234567
    c = (c & 0x0F) << 4 | (c & 0xF0) >> 4;
    c = (c & 0x33) << 2 | (c & 0xCC) >> 2;
    c = (c & 0x55) << 1 | (c & 0xAA) >> 1;
    return c;
}

//---------------------------------------------------------------------------
void File_Scte20::Read_Buffer_Continue()
{
    //Parsing
    Element_Begin("SCTE 20");
    int8u  cc_count;
    bool vbi_data_flag;
    BS_Begin();
    Mark_1_NoTrustError();
    Mark_0_NoTrustError();
    Mark_0_NoTrustError();
    Mark_0_NoTrustError();
    Mark_0_NoTrustError();
    Mark_0_NoTrustError();
    Mark_0_NoTrustError();
    Get_SB (vbi_data_flag,                                      "vbi_data_flag");
    if (vbi_data_flag)
    {
        Get_S1 (5, cc_count,                                    "cc_count");
        for (int8u Pos=0; Pos<cc_count; Pos++)
        {
            Element_Begin("cc");
            int8u cc_data[2];
            int8u field_number, cc_data_1, cc_data_2;
            Skip_S1(2,                                          "cc_priority");
            Get_S1 (2, field_number,                            "field_number"); Param_Info(Scte20_field_number(field_number));
            Skip_S1(5,                                          "line_offset");
            Get_S1 (8, cc_data_1,                               "cc_data_1");
            cc_data[0]=ReverseBits(cc_data_1);
            Param_Info(Ztring::ToZtring(cc_data[0], 16));
            Get_S1 (8, cc_data_2,                               "cc_data_2");
            cc_data[1]=ReverseBits(cc_data_2);
            Param_Info(Ztring::ToZtring(cc_data[1], 16));
            Mark_1_NoTrustError();
            Element_Begin("cc_data");
                //Parsing
                if (Streams[field_number]==NULL)
                    Streams[field_number]=new stream;
                if (Streams[field_number]->Parser==NULL)
                {
                    Streams[field_number]->Parser=new File_Eia608();
                    Open_Buffer_Init(Streams[field_number]->Parser);
                }
                if (!Streams[field_number]->Parser->Status[IsFinished])
                {
                    //Parsing
                    if (Streams[field_number]->Parser->PTS_DTS_Needed)
                    {
                        Streams[field_number]->Parser->PCR=PCR;
                        Streams[field_number]->Parser->PTS=PTS;
                        Streams[field_number]->Parser->DTS=DTS;
                    }
                    Open_Buffer_Continue(Streams[field_number]->Parser, cc_data, 2);
                    Element_Show();

                    //Filled
                    if (!Streams[field_number]->IsFilled && Streams[field_number]->Parser->Status[IsFilled])
                    {
                        if (Count_Get(Stream_General)==0)
                            Accept("SCTE 20");
                        Streams_Count++;
                        if (Streams_Count==3)
                            Fill("SCTE 20");
                        Streams[field_number]->IsFilled=true;
                    }
                }
                else
                    Skip_XX(2,                                  "Data");
            Element_End();
            Element_End();
        }
    }
    Skip_S1(4,                                                  "non_real_time_video_count");
    BS_End();

    if (Element_Size-Element_Offset)
        Skip_XX(Element_Size-Element_Offset,                    "non_real_time_video + reserved");
    Element_End();
    Element_Show();
}

//***************************************************************************
// C++
//***************************************************************************

} //NameSpace

#endif //MEDIAINFO_SCTE20_YES

<commit_msg>+ SCTE 20 closed caption support<commit_after>// File_Scte20 - Info for SCTE 20 streams
// Copyright (C) 2010-2010 MediaArea.net SARL, Info@MediaArea.net
//
// This library is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// 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. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// Compilation conditions
#include "MediaInfo/Setup.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_SCTE20_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Text/File_Scte20.h"
#if defined(MEDIAINFO_EIA608_YES)
    #include "MediaInfo/Text/File_Eia608.h"
#endif
#if defined(MEDIAINFO_EIA708_YES)
    #include "MediaInfo/Text/File_Eia708.h"
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//---------------------------------------------------------------------------

//***************************************************************************
// Infos
//***************************************************************************

//---------------------------------------------------------------------------
const char* Scte20_field_number (int8u field_number)
{
    switch (field_number)
    {
        case  0 : return "Forbidden";
        case  1 : return "1st display field";
        case  2 : return "2nd display field";
        case  3 : return "3rd display fieldt";
        default : return "";
    }
}

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
File_Scte20::File_Scte20()
:File__Analyze()
{
    //Configuration
    PTS_DTS_Needed=true;

    //In
    AspectRatio=0;

    //Temp
    Streams.resize(4); //Forbidden, CEA-608 Field 1, CEA-608 Field 2, CEA-608 Field 3
    Streams_Count=0;
}

//---------------------------------------------------------------------------
File_Scte20::~File_Scte20()
{
    for (size_t Pos=0; Pos<Streams.size(); Pos++)
        delete Streams[Pos]; //Streams[Pos]=NULL
}

//***************************************************************************
// Streams management
//***************************************************************************

//---------------------------------------------------------------------------
void File_Scte20::Streams_Fill()
{
    //Filling
    for (size_t Pos=0; Pos<Streams.size(); Pos++)
        if (Streams[Pos] && Streams[Pos]->Parser && Streams[Pos]->Parser->Status[IsFilled])
        {
            Merge(*Streams[Pos]->Parser);
            if (Pos<2)
                Fill(Stream_Text, StreamPos_Last, Text_ID, _T("608-")+Ztring::ToZtring(Pos));
            Fill(Stream_Text, StreamPos_Last, "MuxingMode", _T("SCTE 20"));
        }
}

//---------------------------------------------------------------------------
void File_Scte20::Streams_Finish()
{
    //Filling
    for (size_t Pos=0; Pos<Streams.size(); Pos++)
        if (Streams[Pos] && Streams[Pos]->Parser && Streams[Pos]->Parser->Status[IsFilled])
            Finish(Streams[Pos]->Parser);
}

//***************************************************************************
// Buffer - Synchro
//***************************************************************************

//---------------------------------------------------------------------------
void File_Scte20::Read_Buffer_Unsynched()
{
    //Parsing
    for (size_t Pos=0; Pos<Streams.size(); Pos++)
        if (Streams[Pos] && Streams[Pos]->Parser)
            Streams[Pos]->Parser->Open_Buffer_Unsynch();
}

//***************************************************************************
// Buffer - Global
//***************************************************************************

static inline int8u ReverseBits(int8u c)
{
    // Input: bit order is 76543210
    //Output: bit order is 01234567
    c = (c & 0x0F) << 4 | (c & 0xF0) >> 4;
    c = (c & 0x33) << 2 | (c & 0xCC) >> 2;
    c = (c & 0x55) << 1 | (c & 0xAA) >> 1;
    return c;
}

//---------------------------------------------------------------------------
void File_Scte20::Read_Buffer_Continue()
{
    //Parsing
    Element_Begin("SCTE 20");
    int8u  cc_count;
    bool vbi_data_flag;
    BS_Begin();
    Mark_1_NoTrustError();
    Mark_0_NoTrustError();
    Mark_0_NoTrustError();
    Mark_0_NoTrustError();
    Mark_0_NoTrustError();
    Mark_0_NoTrustError();
    Mark_0_NoTrustError();
    Get_SB (vbi_data_flag,                                      "vbi_data_flag");
    if (vbi_data_flag)
    {
        Get_S1 (5, cc_count,                                    "cc_count");
        for (int8u Pos=0; Pos<cc_count; Pos++)
        {
            Element_Begin("cc");
            int8u cc_data[2];
            int8u field_number, cc_data_1, cc_data_2;
            Skip_S1(2,                                          "cc_priority");
            Get_S1 (2, field_number,                            "field_number"); Param_Info(Scte20_field_number(field_number));
            Skip_S1(5,                                          "line_offset");
            Get_S1 (8, cc_data_1,                               "cc_data_1");
            cc_data[0]=ReverseBits(cc_data_1);
            Param_Info(Ztring::ToZtring(cc_data[0], 16));
            Get_S1 (8, cc_data_2,                               "cc_data_2");
            cc_data[1]=ReverseBits(cc_data_2);
            Param_Info(Ztring::ToZtring(cc_data[1], 16));
            Mark_1_NoTrustError();
            Element_Begin("cc_data");
                //Parsing
                if (Streams[field_number]==NULL)
                    Streams[field_number]=new stream;
                if (Streams[field_number]->Parser==NULL)
                {
                    Streams[field_number]->Parser=new File_Eia608();
                    Open_Buffer_Init(Streams[field_number]->Parser);
                }
                if (!Streams[field_number]->Parser->Status[IsFinished])
                {
                    //Parsing
                    if (Streams[field_number]->Parser->PTS_DTS_Needed)
                    {
                        Streams[field_number]->Parser->PCR=PCR;
                        Streams[field_number]->Parser->PTS=PTS;
                        Streams[field_number]->Parser->DTS=DTS;
                    }
                    Open_Buffer_Continue(Streams[field_number]->Parser, cc_data, 2);
                    Element_Show();

                    //Filled
                    if (!Streams[field_number]->IsFilled && Streams[field_number]->Parser->Status[IsFilled])
                    {
                        if (Count_Get(Stream_General)==0)
                            Accept("SCTE 20");
                        Streams_Count++;
                        if (Streams_Count==3)
                            Fill("SCTE 20");
                        Streams[field_number]->IsFilled=true;
                    }
                }
                else
                    Skip_XX(2,                                  "Data");
            Element_End();
            Element_End();
        }
    }
    Skip_S1(4,                                                  "non_real_time_video_count");
    BS_End();

    if (Element_Size-Element_Offset)
        Skip_XX(Element_Size-Element_Offset,                    "non_real_time_video + reserved");
    Element_End();
    Element_Show();
}

//***************************************************************************
// C++
//***************************************************************************

} //NameSpace

#endif //MEDIAINFO_SCTE20_YES

<|endoftext|>


<commit_before>#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include "AnalogAccel.h"

int main()
{
	sei();

	AnalogAccel analogAccel;
	DDRB |= _BV(DDB5);

	while(true)
	{
		if(analogAccel.getZ() > 512)
			PORTB |= _BV(PORTB5);
		else
			PORTB &= ~_BV(PORTB5);
	}
}
<commit_msg>Added test for timer<commit_after>#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include "AnalogAccel.h"
#include "Timer.h"

int main()
{
	sei();

	AnalogAccel analogAccel;
	Timer timer(1000); //Count increases 1000x per second (every 1 ms)

	DDRB |= _BV(DDB5);

	while(true)
	{
		if((timer.getCount() < 10000) != (analogAccel.getZ() > 512))
			PORTB |= _BV(PORTB5);
		else
			PORTB &= ~_BV(PORTB5);
	}
}
<|endoftext|>