<commit_before>#include <uri.hpp>
#include <iostream>

using namespace uri;

///////////////////////////////////////////////////////////////////////////////
const URI::Span_t URI::zero_span_;

URI::URI(const std::string&& data) :
  uri_str_ {std::forward<const std::string>(data)}
{
  init_spans();
}

URI::URI(const char* data) :
  uri_str_ {data}
{
  init_spans();
}

std::string URI::path() const {
  return uri_str_.substr(path_.begin, path_.end);
}

std::string URI::to_string() const{
  return uri_str_;
}

///////////////////////////////////////////////////////////////////////////////
void URI::parse(const std::string& uri) {
  static const std::regex uri_pattern_matcher
  {
    "^([\\w]+)?(\\://)?"        //< scheme
    "(([^:@]+)(\\:([^@]+))?@)?" //< username && password
    "([^/:?#]+)?(\\:(\\d+))?"   //< hostname && port
    "([^?#]+)"                  //< path
    "(\\?([^#]*))?"             //< query
    "(#(.*))?$"                 //< fragment
  };

  std::smatch uri_parts;

  if (std::regex_match(uri, uri_parts, uri_pattern_matcher)) {
    path_     = Span_t(uri_parts.position(10), uri_parts.length(10));

    userinfo_ = uri_parts.length(3)  ? Span_t(uri_parts.position(3),  uri_parts.length(3))  : zero_span_;
    host_     = uri_parts.length(7)  ? Span_t(uri_parts.position(7),  uri_parts.length(7))  : zero_span_;
    port_str_ = uri_parts.length(9)  ? Span_t(uri_parts.position(9),  uri_parts.length(9))  : zero_span_;
    query_    = uri_parts.length(11) ? Span_t(uri_parts.position(11), uri_parts.length(11)) : zero_span_;
    fragment_ = uri_parts.length(12) ? Span_t(uri_parts.position(12), uri_parts.length(12)) : zero_span_;
  }
}

std::ostream& uri::operator<< (std::ostream& out, const URI& uri) {
  out << uri.to_string();
  return out;
}
<commit_msg>Added seperators between method definitions<commit_after>#include <uri.hpp>
#include <iostream>

using namespace uri;

///////////////////////////////////////////////////////////////////////////////
const URI::Span_t URI::zero_span_;

///////////////////////////////////////////////////////////////////////////////
URI::URI(const std::string&& data) :
  uri_str_ {std::forward<const std::string>(data)}
{
  init_spans();
}

///////////////////////////////////////////////////////////////////////////////
URI::URI(const char* data) :
  uri_str_ {data}
{
  init_spans();
}

///////////////////////////////////////////////////////////////////////////////
std::string URI::path() const {
  return uri_str_.substr(path_.begin, path_.end);
}

///////////////////////////////////////////////////////////////////////////////
std::string URI::to_string() const{
  return uri_str_;
}

///////////////////////////////////////////////////////////////////////////////
void URI::parse(const std::string& uri) {
  static const std::regex uri_pattern_matcher
  {
    "^([\\w]+)?(\\://)?"        //< scheme
    "(([^:@]+)(\\:([^@]+))?@)?" //< username && password
    "([^/:?#]+)?(\\:(\\d+))?"   //< hostname && port
    "([^?#]+)"                  //< path
    "(\\?([^#]*))?"             //< query
    "(#(.*))?$"                 //< fragment
  };

  std::smatch uri_parts;

  if (std::regex_match(uri, uri_parts, uri_pattern_matcher)) {
    path_     = Span_t(uri_parts.position(10), uri_parts.length(10));

    userinfo_ = uri_parts.length(3)  ? Span_t(uri_parts.position(3),  uri_parts.length(3))  : zero_span_;
    host_     = uri_parts.length(7)  ? Span_t(uri_parts.position(7),  uri_parts.length(7))  : zero_span_;
    port_str_ = uri_parts.length(9)  ? Span_t(uri_parts.position(9),  uri_parts.length(9))  : zero_span_;
    query_    = uri_parts.length(11) ? Span_t(uri_parts.position(11), uri_parts.length(11)) : zero_span_;
    fragment_ = uri_parts.length(12) ? Span_t(uri_parts.position(12), uri_parts.length(12)) : zero_span_;
  }
}

///////////////////////////////////////////////////////////////////////////////
std::ostream& uri::operator<< (std::ostream& out, const URI& uri) {
  out << uri.to_string();
  return out;
}
<|endoftext|>


<commit_before>/*
 * This program is just for personal experiments here on AVR features and C++ stuff
 * This one is a proof of concept on I2C asynchronous handling specificaloly for
 * ATtiny architecture.
 * As a matter of fact, ATtiny USI feature is not very well suited for asynchronous
 * I2C handling as I2C master (this is easier for slaves).
 * This PoC will try to demonstrate working with DS1307 RTC chip from an ATtiny84 MCU,
 * using Timer0 as clock source for USI SCL clock.
 */

#include <util/delay_basic.h>

#include <fastarduino/boards/board.h>
#include <fastarduino/i2c.h>
#include <fastarduino/queue.h>
#include <fastarduino/time.h>
#include <fastarduino/interrupts.h>
#include <fastarduino/bits.h>
#include <fastarduino/utilities.h>
#include <fastarduino/iomanip.h>

#ifdef ARDUINO_UNO
#define HARD_UART
#include <fastarduino/uart.h>
static constexpr const board::USART UART = board::USART::USART0;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 128;
static constexpr uint8_t I2C_BUFFER_SIZE = 32;
static constexpr uint8_t MAX_FUTURES = 128;
static i2c::I2CCommand i2c_buffer[I2C_BUFFER_SIZE];
// Define vectors we need in the example
REGISTER_UATX_ISR(0)
#elif defined (BREADBOARD_ATTINYX4)
#include <fastarduino/soft_uart.h>
static constexpr const board::DigitalPin TX = board::DigitalPin::D8_PB0;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64;
static constexpr uint8_t MAX_FUTURES = 8;
#else
#error "Current target is not yet supported!"
#endif

#include "i2c_handler.h"
#include "ds1307.h"

// Setup debugging stuff
// #define DEBUG_STEPS
// #define DEBUG_SEND_OK
// #define DEBUG_SEND_ERR
// #define DEBUG_RECV_OK
// #define DEBUG_RECV_ERR
#include "debug.h"

#if defined(DEBUG_STEPS) || defined(DEBUG_SEND_OK) || defined(DEBUG_SEND_ERR) || defined(DEBUG_RECV_OK) || defined(DEBUG_RECV_ERR)
#define DEBUG_STATUS
#endif

// This is used when nothing works at all and this reduces the tests to only once get_ram() call
#define BASIC_DEBUG

// Actual test example
//=====================

#ifdef TWCR
REGISTER_I2C_ISR(i2c::I2CMode::STANDARD)
#endif

// Add utility ostream manipulator for FutureStatus
static const flash::FlashStorage* convert(future::FutureStatus s)
{
	switch (s)
	{
		case future::FutureStatus::INVALID:
		return F("INVALID");

		case future::FutureStatus::NOT_READY:
		return F("NOT_READY");

		case future::FutureStatus::READY:
		return F("READY");

		case future::FutureStatus::ERROR:
		return F("ERROR");
	}
}

streams::ostream& operator<<(streams::ostream& out, future::FutureStatus s)
{
	return out << convert(s);
}

void trace(streams::ostream& out)
{
#ifdef DEBUG_STATUS
	trace_states(out);
#endif
}

static char output_buffer[OUTPUT_BUFFER_SIZE];

using I2CHANDLER = i2c::I2CHandler<i2c::I2CMode::STANDARD>;
using namespace streams;

ostream* pout = nullptr;
#define OUT (*pout)

static void i2c_hook(i2c::DebugStatus status, uint8_t data)
{
	switch (status)
	{
		case i2c::DebugStatus::START:
		OUT << F("St ") << flush;
		break;

		case i2c::DebugStatus::REPEAT_START:
		OUT << F("RS ") << flush;
		break;

		case i2c::DebugStatus::STOP:
		OUT << F("Sp ") << flush;
		break;

		case i2c::DebugStatus::SLAW:
		OUT << F("AW ") << hex << data << ' ' << flush;
		break;

		case i2c::DebugStatus::SLAR:
		OUT << F("AR ") << hex << data << ' ' << flush;
		break;

		case i2c::DebugStatus::SEND:
		OUT << F("S ") << hex << data << ' ' << flush;
		break;

		case i2c::DebugStatus::SEND_OK:
		OUT << F("So ") << flush;
		break;

		case i2c::DebugStatus::SEND_ERROR:
		OUT << F("Se ") << flush;
		break;

		case i2c::DebugStatus::RECV:
		OUT << F("R ") << flush;
		break;

		case i2c::DebugStatus::RECV_LAST:
		OUT << F("RL ") << flush;
		break;

		case i2c::DebugStatus::RECV_OK:
		OUT << F("Ro ") << flush;
		break;

		case i2c::DebugStatus::RECV_ERROR:
		OUT << F("Re ") << flush;
		break;
	}
}

//TODO add call hook
int main() __attribute__((OS_main));
int main()
{
	board::init();

	// Enable interrupts at startup time
	sei();

	// Initialize debugging output
#ifdef HARD_UART
	serial::hard::UATX<UART> uatx{output_buffer};
#else
	serial::soft::UATX<TX> uatx{output_buffer};
#endif

	// Start UART
	uatx.begin(115200);
	ostream out = uatx.out();
	pout = &out;
	out << F("Starting...") << endl;

	// Initialize FutureManager
	future::FutureManager<MAX_FUTURES> future_manager;

	// Initialize I2C async handler
#ifdef TWCR
	I2CHANDLER handler{i2c_buffer, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS, debug_hook};
#else
	I2CHANDLER handler{i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS, i2c_hook};
#endif
	RTC rtc{handler};
	out << F("Before handler.begin()") << endl;
	out << boolalpha << showbase;

	handler.begin();

	constexpr uint8_t RAM_SIZE = rtc.ram_size();

#ifdef BASIC_DEBUG
	// INITIAL debug test with only one call, normally not part of complete unit tests
	{
		out << F("\nTEST #0 read one RAM byte") << endl;
		RTC::GET_RAM1 data{0};
		int ok = rtc.get_ram(data);
		out << F("get_ram()=") << dec << ok << endl;
		out << F("handler.status()=") << hex << handler.status() << endl;
		uint8_t id = data.id();
		future::FutureStatus status = data.status();
		out << F("id=") << dec << id << F(" status=") << status << endl;
		// out << F("id=") << dec << data.id() << F(" status=") << data.status() << endl;
		// time::delay_ms(1000);
		out << F("data await()=") << data.await() << endl;
		out << F("error()=") << dec << data.error() << endl;
		uint8_t result = 0;
		data.get(result);
		out << F("get()=") << hex << result << endl;
		trace(out);
	}
#else
	{
		out << F("\nTEST #0 read all RAM bytes, one by one") << endl;
		RTC::GET_RAM1 data[10];
		for (uint8_t i = 0; i < 10; ++i)
		{
			data[i] = RTC::GET_RAM1{i};
			int error = rtc.get_ram(data[i]);
			if (error)
				out << F("F") << dec << i << F(" ") << flush;
			// This delay is needed to give time to I2C transactions to finish
			// and free I2C commands in buffer (only 32)
			time::delay_us(200);
		}
		out << endl;
		for (uint8_t i = 0 ; i < 10; ++i)
		{
			out << F("data[") << dec << i << F("] await()=") << data[i].await() << endl;
			out << F("error()=") << dec << data[i].error() << endl;
			uint8_t result = 0;
			data[i].get(result);
			out << F("get()=") << hex << result << endl;
		}
		trace(out);
	}
#endif

	handler.end();
}
<commit_msg>Remove obsolete comment<commit_after>/*
 * This program is just for personal experiments here on AVR features and C++ stuff
 * This one is a proof of concept on I2C asynchronous handling specificaloly for
 * ATtiny architecture.
 * As a matter of fact, ATtiny USI feature is not very well suited for asynchronous
 * I2C handling as I2C master (this is easier for slaves).
 * This PoC will try to demonstrate working with DS1307 RTC chip from an ATtiny84 MCU,
 * using Timer0 as clock source for USI SCL clock.
 */

#include <util/delay_basic.h>

#include <fastarduino/boards/board.h>
#include <fastarduino/i2c.h>
#include <fastarduino/queue.h>
#include <fastarduino/time.h>
#include <fastarduino/interrupts.h>
#include <fastarduino/bits.h>
#include <fastarduino/utilities.h>
#include <fastarduino/iomanip.h>

#ifdef ARDUINO_UNO
#define HARD_UART
#include <fastarduino/uart.h>
static constexpr const board::USART UART = board::USART::USART0;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 128;
static constexpr uint8_t I2C_BUFFER_SIZE = 32;
static constexpr uint8_t MAX_FUTURES = 128;
static i2c::I2CCommand i2c_buffer[I2C_BUFFER_SIZE];
// Define vectors we need in the example
REGISTER_UATX_ISR(0)
#elif defined (BREADBOARD_ATTINYX4)
#include <fastarduino/soft_uart.h>
static constexpr const board::DigitalPin TX = board::DigitalPin::D8_PB0;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64;
static constexpr uint8_t MAX_FUTURES = 8;
#else
#error "Current target is not yet supported!"
#endif

#include "i2c_handler.h"
#include "ds1307.h"

// Setup debugging stuff
// #define DEBUG_STEPS
// #define DEBUG_SEND_OK
// #define DEBUG_SEND_ERR
// #define DEBUG_RECV_OK
// #define DEBUG_RECV_ERR
#include "debug.h"

#if defined(DEBUG_STEPS) || defined(DEBUG_SEND_OK) || defined(DEBUG_SEND_ERR) || defined(DEBUG_RECV_OK) || defined(DEBUG_RECV_ERR)
#define DEBUG_STATUS
#endif

// This is used when nothing works at all and this reduces the tests to only once get_ram() call
#define BASIC_DEBUG

// Actual test example
//=====================

#ifdef TWCR
REGISTER_I2C_ISR(i2c::I2CMode::STANDARD)
#endif

// Add utility ostream manipulator for FutureStatus
static const flash::FlashStorage* convert(future::FutureStatus s)
{
	switch (s)
	{
		case future::FutureStatus::INVALID:
		return F("INVALID");

		case future::FutureStatus::NOT_READY:
		return F("NOT_READY");

		case future::FutureStatus::READY:
		return F("READY");

		case future::FutureStatus::ERROR:
		return F("ERROR");
	}
}

streams::ostream& operator<<(streams::ostream& out, future::FutureStatus s)
{
	return out << convert(s);
}

void trace(streams::ostream& out)
{
#ifdef DEBUG_STATUS
	trace_states(out);
#endif
}

static char output_buffer[OUTPUT_BUFFER_SIZE];

using I2CHANDLER = i2c::I2CHandler<i2c::I2CMode::STANDARD>;
using namespace streams;

ostream* pout = nullptr;
#define OUT (*pout)

static void i2c_hook(i2c::DebugStatus status, uint8_t data)
{
	switch (status)
	{
		case i2c::DebugStatus::START:
		OUT << F("St ") << flush;
		break;

		case i2c::DebugStatus::REPEAT_START:
		OUT << F("RS ") << flush;
		break;

		case i2c::DebugStatus::STOP:
		OUT << F("Sp ") << flush;
		break;

		case i2c::DebugStatus::SLAW:
		OUT << F("AW ") << hex << data << ' ' << flush;
		break;

		case i2c::DebugStatus::SLAR:
		OUT << F("AR ") << hex << data << ' ' << flush;
		break;

		case i2c::DebugStatus::SEND:
		OUT << F("S ") << hex << data << ' ' << flush;
		break;

		case i2c::DebugStatus::SEND_OK:
		OUT << F("So ") << flush;
		break;

		case i2c::DebugStatus::SEND_ERROR:
		OUT << F("Se ") << flush;
		break;

		case i2c::DebugStatus::RECV:
		OUT << F("R ") << flush;
		break;

		case i2c::DebugStatus::RECV_LAST:
		OUT << F("RL ") << flush;
		break;

		case i2c::DebugStatus::RECV_OK:
		OUT << F("Ro ") << flush;
		break;

		case i2c::DebugStatus::RECV_ERROR:
		OUT << F("Re ") << flush;
		break;
	}
}

int main() __attribute__((OS_main));
int main()
{
	board::init();

	// Enable interrupts at startup time
	sei();

	// Initialize debugging output
#ifdef HARD_UART
	serial::hard::UATX<UART> uatx{output_buffer};
#else
	serial::soft::UATX<TX> uatx{output_buffer};
#endif

	// Start UART
	uatx.begin(115200);
	ostream out = uatx.out();
	pout = &out;
	out << F("Starting...") << endl;

	// Initialize FutureManager
	future::FutureManager<MAX_FUTURES> future_manager;

	// Initialize I2C async handler
#ifdef TWCR
	I2CHANDLER handler{i2c_buffer, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS, debug_hook};
#else
	I2CHANDLER handler{i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS, i2c_hook};
#endif
	RTC rtc{handler};
	out << F("Before handler.begin()") << endl;
	out << boolalpha << showbase;

	handler.begin();

	constexpr uint8_t RAM_SIZE = rtc.ram_size();

#ifdef BASIC_DEBUG
	// INITIAL debug test with only one call, normally not part of complete unit tests
	{
		out << F("\nTEST #0 read one RAM byte") << endl;
		RTC::GET_RAM1 data{0};
		int ok = rtc.get_ram(data);
		out << F("get_ram()=") << dec << ok << endl;
		out << F("handler.status()=") << hex << handler.status() << endl;
		uint8_t id = data.id();
		future::FutureStatus status = data.status();
		out << F("id=") << dec << id << F(" status=") << status << endl;
		// out << F("id=") << dec << data.id() << F(" status=") << data.status() << endl;
		// time::delay_ms(1000);
		out << F("data await()=") << data.await() << endl;
		out << F("error()=") << dec << data.error() << endl;
		uint8_t result = 0;
		data.get(result);
		out << F("get()=") << hex << result << endl;
		trace(out);
	}
#else
	{
		out << F("\nTEST #0 read all RAM bytes, one by one") << endl;
		RTC::GET_RAM1 data[10];
		for (uint8_t i = 0; i < 10; ++i)
		{
			data[i] = RTC::GET_RAM1{i};
			int error = rtc.get_ram(data[i]);
			if (error)
				out << F("F") << dec << i << F(" ") << flush;
			// This delay is needed to give time to I2C transactions to finish
			// and free I2C commands in buffer (only 32)
			time::delay_us(200);
		}
		out << endl;
		for (uint8_t i = 0 ; i < 10; ++i)
		{
			out << F("data[") << dec << i << F("] await()=") << data[i].await() << endl;
			out << F("error()=") << dec << data[i].error() << endl;
			uint8_t result = 0;
			data[i].get(result);
			out << F("get()=") << hex << result << endl;
		}
		trace(out);
	}
#endif

	handler.end();
}
<|endoftext|>


<commit_before>// Message.cpp
// Implements the Message class.

#include "Message.h"

#include "CycException.h"
#include "Communicator.h"
#include "FacilityModel.h"
#include "MarketModel.h"
#include "InstModel.h"
#include "GenericResource.h"
#include "Logger.h"
#include "BookKeeper.h"

#include <iostream>

// initialize static variables
int Message::nextID_ = 1;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Message::Message(Communicator* sender) {

  dir_ = UP_MSG;
  sender_ = sender;
  recipient_ = NULL;
  path_stack_ = vector<Communicator*>();
  current_owner_ = sender;

  trans_.supplier = NULL;
  trans_.requester = NULL;
  trans_.is_offer = NULL;
  trans_.resource = NULL;
  trans_.minfrac = 0;
  trans_.price = 0;

  setRealParticipant(sender);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Message::Message(Communicator* sender, Communicator* receiver) {

  dir_ = UP_MSG;
  sender_ = sender;
  recipient_ = receiver;

  trans_.supplier = NULL;
  trans_.requester = NULL;
  trans_.is_offer = NULL;
  trans_.resource = NULL;
  trans_.minfrac = 0;
  trans_.price = 0;

  setRealParticipant(sender);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Message::Message(Communicator* sender, Communicator* receiver,
                 Transaction thisTrans) {

  dir_ = UP_MSG;
  trans_ = thisTrans;
  sender_ = sender;
  recipient_ = receiver;
  setResource(thisTrans.resource);

  if (trans_.is_offer) {
    // if this message is an offer, the sender is the supplier
    setSupplier(dynamic_cast<Model*>(sender_));
  } else if (!trans_.is_offer) {
    // if this message is a request, the sender is the requester
    setRequester(dynamic_cast<Model*>(sender_));
  }

  setRealParticipant(sender);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::setRealParticipant(Communicator* who) {
  try {
    dynamic_cast<Model*>(who)->isTemplate() = false;
  } catch(...) {
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::printTrans() {
  std::cout << "Transaction info (via Message):" << std::endl <<
    "    Transaction ID: " << trans_.ID << std::endl <<
    "    Requester ID: " << trans_.requester->ID() << std::endl <<
    "    Supplier ID: " << trans_.supplier->ID() << std::endl <<
    "    Price: "  << trans_.price << std::endl;
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Message* Message::clone() {
  Message* new_msg = new Message(*this);
  new_msg->setResource(getResource());
  return new_msg;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::sendOn() {
  validateForSend();

  if (dir_ == DOWN_MSG) {
    path_stack_.pop_back();
  }

  Communicator* next_stop = path_stack_.back();

  setRealParticipant(next_stop);

  current_owner_ = next_stop;
  next_stop->receiveMessage(this);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::validateForSend() {
  int next_stop_index = -1;
  bool receiver_specified = false;
  Communicator* next_stop;

  if (dir_ == UP_MSG) {
    receiver_specified = (path_stack_.size() > 0);
    next_stop_index = path_stack_.size() - 1;
  } else if (dir_ == DOWN_MSG) {
    receiver_specified = (path_stack_.size() > 1);
    next_stop_index = path_stack_.size() - 2;
  }

  if (!receiver_specified) {
    string err_msg = "Can't send the message: next dest is unspecified.";
    throw CycMessageException(err_msg);
  }

  next_stop = path_stack_[next_stop_index];
  if (next_stop == current_owner_) {
    string err_msg = "Message receiver and sender are the same.";
    throw CycMessageException(err_msg);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::setNextDest(Communicator* next_stop) {
  if (dir_ == UP_MSG) {
    if (path_stack_.size() == 0) {
      path_stack_.push_back(sender_);
    }

    path_stack_.push_back(next_stop);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::reverseDirection() {
  if (DOWN_MSG == dir_) {
    dir_ = UP_MSG;
  } else {
  	dir_ = DOWN_MSG;
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MessageDir Message::getDir() const {
  return dir_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::setDir(MessageDir newDir) {
  dir_ = newDir;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Communicator* Message::getMarket() {
  MarketModel* market = MarketModel::marketForCommod(trans_.commod);
  return dynamic_cast<Communicator*>(market);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Communicator* Message::getRecipient() const {
  if (recipient_ == NULL) {
    string err_msg = "Uninitilized message recipient.";
    throw CycMessageException(err_msg);
  }

  return recipient_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model* Message::getSupplier() const {
  if (trans_.supplier == NULL) {
    string err_msg = "Uninitilized message supplier.";
    throw CycMessageException(err_msg);
  }

  return trans_.supplier;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model* Message::getRequester() const {
  if (trans_.requester == NULL) {
    string err_msg = "Uninitilized message requester.";
    throw CycMessageException(err_msg);
  }

  return trans_.requester;
}

void Message::approveTransfer() {
  Model* requester = getRequester();
  Model* supplier = getSupplier();
  vector<Resource*> manifest = supplier->removeResource(this);
  requester->addResource(getTrans(), manifest);

  BI->registerTrans(this, manifest);

  for (int i = 0; i < manifest.size(); i++) {
    try {
      BI->registerMatState(getTrans().ID, dynamic_cast<Material*>(manifest.at(i)));
    } catch (...) {}
  }

  LOG(LEV_DEBUG2) << "Material sent from " << supplier->ID() << " to "
                  << requester->ID() << ".";
}
<commit_msg>fixed bug introduced in r636 that caused segfault in message class tests.<commit_after>// Message.cpp
// Implements the Message class.

#include "Message.h"

#include "CycException.h"
#include "Communicator.h"
#include "FacilityModel.h"
#include "MarketModel.h"
#include "InstModel.h"
#include "GenericResource.h"
#include "Logger.h"
#include "BookKeeper.h"

#include <iostream>

// initialize static variables
int Message::nextID_ = 1;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Message::Message(Communicator* sender) {

  dir_ = UP_MSG;
  sender_ = sender;
  recipient_ = NULL;
  path_stack_ = vector<Communicator*>();
  current_owner_ = sender;

  trans_.supplier = NULL;
  trans_.requester = NULL;
  trans_.is_offer = NULL;
  trans_.resource = NULL;
  trans_.minfrac = 0;
  trans_.price = 0;

  setRealParticipant(sender);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Message::Message(Communicator* sender, Communicator* receiver) {

  dir_ = UP_MSG;
  sender_ = sender;
  recipient_ = receiver;

  trans_.supplier = NULL;
  trans_.requester = NULL;
  trans_.is_offer = NULL;
  trans_.resource = NULL;
  trans_.minfrac = 0;
  trans_.price = 0;

  setRealParticipant(sender);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Message::Message(Communicator* sender, Communicator* receiver,
                 Transaction thisTrans) {

  dir_ = UP_MSG;
  trans_ = thisTrans;
  sender_ = sender;
  recipient_ = receiver;
  setResource(thisTrans.resource);

  if (trans_.is_offer) {
    // if this message is an offer, the sender is the supplier
    setSupplier(dynamic_cast<Model*>(sender_));
  } else if (!trans_.is_offer) {
    // if this message is a request, the sender is the requester
    setRequester(dynamic_cast<Model*>(sender_));
  }

  setRealParticipant(sender);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::setRealParticipant(Communicator* who) {
  Model* model = NULL;
  model = dynamic_cast<Model*>(who);
  if (model != NULL) {model->isTemplate() = false;}
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::printTrans() {
  std::cout << "Transaction info (via Message):" << std::endl <<
    "    Transaction ID: " << trans_.ID << std::endl <<
    "    Requester ID: " << trans_.requester->ID() << std::endl <<
    "    Supplier ID: " << trans_.supplier->ID() << std::endl <<
    "    Price: "  << trans_.price << std::endl;
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Message* Message::clone() {
  Message* new_msg = new Message(*this);
  new_msg->setResource(getResource());
  return new_msg;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::sendOn() {
  validateForSend();

  if (dir_ == DOWN_MSG) {
    path_stack_.pop_back();
  }

  Communicator* next_stop = path_stack_.back();

  setRealParticipant(next_stop);

  current_owner_ = next_stop;
  next_stop->receiveMessage(this);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::validateForSend() {
  int next_stop_index = -1;
  bool receiver_specified = false;
  Communicator* next_stop;

  if (dir_ == UP_MSG) {
    receiver_specified = (path_stack_.size() > 0);
    next_stop_index = path_stack_.size() - 1;
  } else if (dir_ == DOWN_MSG) {
    receiver_specified = (path_stack_.size() > 1);
    next_stop_index = path_stack_.size() - 2;
  }

  if (!receiver_specified) {
    string err_msg = "Can't send the message: next dest is unspecified.";
    throw CycMessageException(err_msg);
  }

  next_stop = path_stack_[next_stop_index];
  if (next_stop == current_owner_) {
    string err_msg = "Message receiver and sender are the same.";
    throw CycMessageException(err_msg);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::setNextDest(Communicator* next_stop) {
  if (dir_ == UP_MSG) {
    if (path_stack_.size() == 0) {
      path_stack_.push_back(sender_);
    }

    path_stack_.push_back(next_stop);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::reverseDirection() {
  if (DOWN_MSG == dir_) {
    dir_ = UP_MSG;
  } else {
  	dir_ = DOWN_MSG;
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MessageDir Message::getDir() const {
  return dir_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::setDir(MessageDir newDir) {
  dir_ = newDir;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Communicator* Message::getMarket() {
  MarketModel* market = MarketModel::marketForCommod(trans_.commod);
  return dynamic_cast<Communicator*>(market);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Communicator* Message::getRecipient() const {
  if (recipient_ == NULL) {
    string err_msg = "Uninitilized message recipient.";
    throw CycMessageException(err_msg);
  }

  return recipient_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model* Message::getSupplier() const {
  if (trans_.supplier == NULL) {
    string err_msg = "Uninitilized message supplier.";
    throw CycMessageException(err_msg);
  }

  return trans_.supplier;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model* Message::getRequester() const {
  if (trans_.requester == NULL) {
    string err_msg = "Uninitilized message requester.";
    throw CycMessageException(err_msg);
  }

  return trans_.requester;
}

void Message::approveTransfer() {
  Model* requester = getRequester();
  Model* supplier = getSupplier();
  vector<Resource*> manifest = supplier->removeResource(this);
  requester->addResource(getTrans(), manifest);

  BI->registerTrans(this, manifest);

  for (int i = 0; i < manifest.size(); i++) {
    try {
      BI->registerMatState(getTrans().ID, dynamic_cast<Material*>(manifest.at(i)));
    } catch (...) {}
  }

  LOG(LEV_DEBUG2) << "Material sent from " << supplier->ID() << " to "
                  << requester->ID() << ".";
}
<|endoftext|>


<commit_before>//===- GdbIndex.cpp -------------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The -gdb-index option instructs the linker to emit a .gdb_index section.
// The section contains information to make gdb startup faster.
// The format of the section is described at
// https://sourceware.org/gdb/onlinedocs/gdb/Index-Section-Format.html.
//
//===----------------------------------------------------------------------===//

#include "GdbIndex.h"
#include "Memory.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
#include "llvm/Object/ELFObjectFile.h"

using namespace llvm;
using namespace llvm::object;
using namespace lld;
using namespace lld::elf;

std::pair<bool, GdbSymbol *> GdbHashTab::add(uint32_t Hash, size_t Offset) {
  GdbSymbol *&Sym = Map[Offset];
  if (Sym)
    return {false, Sym};
  Sym = make<GdbSymbol>(Hash, Offset);
  return {true, Sym};
}

void GdbHashTab::finalizeContents() {
  uint32_t Size = std::max<uint32_t>(1024, NextPowerOf2(Map.size() * 4 / 3));
  uint32_t Mask = Size - 1;
  Table.resize(Size);

  for (auto &P : Map) {
    GdbSymbol *Sym = P.second;
    uint32_t I = Sym->NameHash & Mask;
    uint32_t Step = ((Sym->NameHash * 17) & Mask) | 1;

    while (Table[I])
      I = (I + Step) & Mask;
    Table[I] = Sym;
  }
}

template <class ELFT>
LLDDwarfObj<ELFT>::LLDDwarfObj(ObjFile<ELFT> *Obj) : Obj(Obj) {
  for (InputSectionBase *Sec : Obj->getSections()) {
    if (!Sec)
      continue;
    if (LLDDWARFSection *M = StringSwitch<LLDDWARFSection *>(Sec->Name)
                                 .Case(".debug_info", &InfoSection)
                                 .Case(".debug_ranges", &RangeSection)
                                 .Case(".debug_line", &LineSection)
                                 .Default(nullptr)) {
      M->Data = toStringRef(Sec->Data);
      M->Sec = Sec;
      continue;
    }
    if (Sec->Name == ".debug_abbrev")
      AbbrevSection = toStringRef(Sec->Data);
    else if (Sec->Name == ".debug_gnu_pubnames")
      GnuPubNamesSection = toStringRef(Sec->Data);
    else if (Sec->Name == ".debug_gnu_pubtypes")
      GnuPubTypesSection = toStringRef(Sec->Data);
  }
}

// Find if there is a relocation at Pos in Sec.  The code is a bit
// more complicated than usual because we need to pass a section index
// to llvm since it has no idea about InputSection.
template <class ELFT>
template <class RelTy>
Optional<RelocAddrEntry>
LLDDwarfObj<ELFT>::findAux(const InputSectionBase &Sec, uint64_t Pos,
                           ArrayRef<RelTy> Rels) const {
  auto I = llvm::find_if(Rels,
                         [=](const RelTy &Rel) { return Rel.r_offset == Pos; });
  if (I == Rels.end())
    return None;
  const RelTy &Rel = *I;
  const ObjFile<ELFT> *File = Sec.getFile<ELFT>();
  uint32_t SymIndex = Rel.getSymbol(Config->IsMips64EL);
  const typename ELFT::Sym &Sym = File->getELFSymbols()[SymIndex];
  uint32_t SecIndex = File->getSectionIndex(Sym);
  SymbolBody &B = File->getRelocTargetSym(Rel);
  auto &DR = cast<DefinedRegular>(B);
  uint64_t Val = DR.Value + getAddend<ELFT>(Rel);

  // FIXME: We should be consistent about always adding the file
  // offset or not.
  if (DR.Section->Flags & ELF::SHF_ALLOC)
    Val += cast<InputSection>(DR.Section)->getOffsetInFile();

  RelocAddrEntry Ret{SecIndex, Val};
  return Ret;
}

template <class ELFT>
Optional<RelocAddrEntry> LLDDwarfObj<ELFT>::find(const llvm::DWARFSection &S,
                                                 uint64_t Pos) const {
  auto &Sec = static_cast<const LLDDWARFSection &>(S);
  if (Sec.Sec->AreRelocsRela)
    return findAux(*Sec.Sec, Pos, Sec.Sec->template relas<ELFT>());
  return findAux(*Sec.Sec, Pos, Sec.Sec->template rels<ELFT>());
}

template class elf::LLDDwarfObj<ELF32LE>;
template class elf::LLDDwarfObj<ELF32BE>;
template class elf::LLDDwarfObj<ELF64LE>;
template class elf::LLDDwarfObj<ELF64BE>;
<commit_msg>Binary search to find a relocation.<commit_after>//===- GdbIndex.cpp -------------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The -gdb-index option instructs the linker to emit a .gdb_index section.
// The section contains information to make gdb startup faster.
// The format of the section is described at
// https://sourceware.org/gdb/onlinedocs/gdb/Index-Section-Format.html.
//
//===----------------------------------------------------------------------===//

#include "GdbIndex.h"
#include "Memory.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
#include "llvm/Object/ELFObjectFile.h"

using namespace llvm;
using namespace llvm::object;
using namespace lld;
using namespace lld::elf;

std::pair<bool, GdbSymbol *> GdbHashTab::add(uint32_t Hash, size_t Offset) {
  GdbSymbol *&Sym = Map[Offset];
  if (Sym)
    return {false, Sym};
  Sym = make<GdbSymbol>(Hash, Offset);
  return {true, Sym};
}

void GdbHashTab::finalizeContents() {
  uint32_t Size = std::max<uint32_t>(1024, NextPowerOf2(Map.size() * 4 / 3));
  uint32_t Mask = Size - 1;
  Table.resize(Size);

  for (auto &P : Map) {
    GdbSymbol *Sym = P.second;
    uint32_t I = Sym->NameHash & Mask;
    uint32_t Step = ((Sym->NameHash * 17) & Mask) | 1;

    while (Table[I])
      I = (I + Step) & Mask;
    Table[I] = Sym;
  }
}

template <class ELFT>
LLDDwarfObj<ELFT>::LLDDwarfObj(ObjFile<ELFT> *Obj) : Obj(Obj) {
  for (InputSectionBase *Sec : Obj->getSections()) {
    if (!Sec)
      continue;
    if (LLDDWARFSection *M = StringSwitch<LLDDWARFSection *>(Sec->Name)
                                 .Case(".debug_info", &InfoSection)
                                 .Case(".debug_ranges", &RangeSection)
                                 .Case(".debug_line", &LineSection)
                                 .Default(nullptr)) {
      M->Data = toStringRef(Sec->Data);
      M->Sec = Sec;
      continue;
    }
    if (Sec->Name == ".debug_abbrev")
      AbbrevSection = toStringRef(Sec->Data);
    else if (Sec->Name == ".debug_gnu_pubnames")
      GnuPubNamesSection = toStringRef(Sec->Data);
    else if (Sec->Name == ".debug_gnu_pubtypes")
      GnuPubTypesSection = toStringRef(Sec->Data);
  }
}

// Find if there is a relocation at Pos in Sec.  The code is a bit
// more complicated than usual because we need to pass a section index
// to llvm since it has no idea about InputSection.
template <class ELFT>
template <class RelTy>
Optional<RelocAddrEntry>
LLDDwarfObj<ELFT>::findAux(const InputSectionBase &Sec, uint64_t Pos,
                           ArrayRef<RelTy> Rels) const {
  auto It = std::lower_bound(
      Rels.begin(), Rels.end(), Pos,
      [](const RelTy &A, uint64_t B) { return A.r_offset < B; });
  if (It == Rels.end() || It->r_offset != Pos)
    return None;
  const RelTy &Rel = *It;

  const ObjFile<ELFT> *File = Sec.getFile<ELFT>();
  uint32_t SymIndex = Rel.getSymbol(Config->IsMips64EL);
  const typename ELFT::Sym &Sym = File->getELFSymbols()[SymIndex];
  uint32_t SecIndex = File->getSectionIndex(Sym);
  SymbolBody &B = File->getRelocTargetSym(Rel);
  auto &DR = cast<DefinedRegular>(B);
  uint64_t Val = DR.Value + getAddend<ELFT>(Rel);

  // FIXME: We should be consistent about always adding the file
  // offset or not.
  if (DR.Section->Flags & ELF::SHF_ALLOC)
    Val += cast<InputSection>(DR.Section)->getOffsetInFile();

  RelocAddrEntry Ret{SecIndex, Val};
  return Ret;
}

template <class ELFT>
Optional<RelocAddrEntry> LLDDwarfObj<ELFT>::find(const llvm::DWARFSection &S,
                                                 uint64_t Pos) const {
  auto &Sec = static_cast<const LLDDWARFSection &>(S);
  if (Sec.Sec->AreRelocsRela)
    return findAux(*Sec.Sec, Pos, Sec.Sec->template relas<ELFT>());
  return findAux(*Sec.Sec, Pos, Sec.Sec->template rels<ELFT>());
}

template class elf::LLDDwarfObj<ELF32LE>;
template class elf::LLDDwarfObj<ELF32BE>;
template class elf::LLDDwarfObj<ELF64LE>;
template class elf::LLDDwarfObj<ELF64BE>;
<|endoftext|>


<commit_before>#include "Input.h"

#include <SDL/SDL.h>
#include <SDL/SDL_OpenGL.h>

#include <queue>

namespace Input
{

namespace Internal
{

std::string MapKey ( SDLKey k )
{
	switch (k)
	{
#define KEYCASE(sym, string) case SDLK_ ## sym: return string
#define DIRECTCASE(sym) KEYCASE(sym, #sym)
		DIRECTCASE(a);
		DIRECTCASE(b);
		DIRECTCASE(c);
		DIRECTCASE(d);
		DIRECTCASE(e);
		DIRECTCASE(f);
		DIRECTCASE(g);
		DIRECTCASE(h);
		DIRECTCASE(i);
		DIRECTCASE(j);
		DIRECTCASE(k);
		DIRECTCASE(l);
		DIRECTCASE(m);
		DIRECTCASE(n);
		DIRECTCASE(o);
		DIRECTCASE(p);
		DIRECTCASE(q);
		DIRECTCASE(r);
		DIRECTCASE(s);
		DIRECTCASE(t);
		DIRECTCASE(u);
		DIRECTCASE(v);
		DIRECTCASE(w);
		DIRECTCASE(x);
		DIRECTCASE(y);
		DIRECTCASE(z);
		DIRECTCASE(0);
		DIRECTCASE(1);
		DIRECTCASE(2);
		DIRECTCASE(3);
		DIRECTCASE(4);
		DIRECTCASE(5);
		DIRECTCASE(6);
		DIRECTCASE(7);
		DIRECTCASE(8);
		DIRECTCASE(9);
		DIRECTCASE(F1);
		DIRECTCASE(F2);
		DIRECTCASE(F3);
		DIRECTCASE(F4);
		DIRECTCASE(F5);
		DIRECTCASE(F6);
		DIRECTCASE(F7);
		DIRECTCASE(F8);
		DIRECTCASE(F9);
		DIRECTCASE(F10);
		DIRECTCASE(F11);
		DIRECTCASE(F12);
		DIRECTCASE(KP0);
		DIRECTCASE(KP1);
		DIRECTCASE(KP2);
		DIRECTCASE(KP3);
		DIRECTCASE(KP4);
		DIRECTCASE(KP5);
		DIRECTCASE(KP6);
		DIRECTCASE(KP7);
		DIRECTCASE(KP8);
		DIRECTCASE(KP9);
		KEYCASE(BACKSPACE, "backspace");
		KEYCASE(TAB, "tab");
		KEYCASE(RETURN, "return");
		KEYCASE(ESCAPE, "escape");
		KEYCASE(SPACE, " ");
		KEYCASE(QUOTE, "\'");
		KEYCASE(LEFTPAREN, "(");
		KEYCASE(RIGHTPAREN, ")");
		KEYCASE(ASTERISK, "*");
		KEYCASE(PLUS, "+");
		KEYCASE(COMMA, ",");
		KEYCASE(MINUS, "-");
		KEYCASE(PERIOD, ".");
		KEYCASE(SLASH, "/");
		KEYCASE(COLON, ":");
		KEYCASE(SEMICOLON, ";");
		KEYCASE(AT, "at_sign");
		KEYCASE(LESS, "<");
		KEYCASE(EQUALS, "=");
		KEYCASE(GREATER, ">");
		KEYCASE(QUESTION, "?");
		KEYCASE(LEFTBRACKET, "[");
		KEYCASE(RIGHTBRACKET, "]");
		KEYCASE(BACKSLASH, "backslash");
		KEYCASE(CARET, "^");
		KEYCASE(UNDERSCORE, "_");
		KEYCASE(LEFT, "left");
		KEYCASE(RIGHT, "right");
		KEYCASE(UP, "up");
		KEYCASE(DOWN, "down");
		KEYCASE(KP_PERIOD, "KPperiod");
		KEYCASE(KP_DIVIDE, "KPdivide");
		KEYCASE(KP_MULTIPLY, "KPmultiply");
		KEYCASE(KP_MINUS, "KPminus");
		KEYCASE(KP_PLUS, "KPplus");
		KEYCASE(KP_ENTER, "KPenter");
		KEYCASE(KP_EQUALS, "KPequals");
		KEYCASE(INSERT, "ins");
		KEYCASE(HOME, "home");
		KEYCASE(END, "end");
		KEYCASE(PAGEUP, "pgup");
		KEYCASE(PAGEDOWN, "pgdn");
		KEYCASE(DELETE, "del");
		//modifier keys
		KEYCASE(CAPSLOCK, "Mcaps");
		KEYCASE(RSHIFT, "MshiftR");
		KEYCASE(LSHIFT, "MshiftL");
		KEYCASE(RCTRL, "MctrlR");
		KEYCASE(LCTRL, "MctrlL");
		KEYCASE(RALT, "MaltR");
		KEYCASE(LALT, "MaltL");
		KEYCASE(RMETA, "MmetaR");
		KEYCASE(LMETA, "MmetaL");
	}
	return "unhandled";
}

std::queue<Event*> events;
Event* currentEvent = NULL;
vec2 mousePosition;
double xdest = 0.0;
double ydest = 0.0;
double zdest = 0.0;
bool lmbPressed = false;

void UpdateMouse ( Sint16 px, Sint16 py )
{
    SDL_Surface* screen = SDL_GetVideoSurface();
    mousePosition.X() = float(px) / float(screen->w);
    mousePosition.Y() = 1.0f - (float(py) / float(screen->h));
}

std::string MouseButtonName ( Uint32 button )
{
	switch (button)
	{
		case SDL_BUTTON_LEFT:
			return "left";
			break;
		case SDL_BUTTON_MIDDLE:
			return "middle";
			break;
		case SDL_BUTTON_RIGHT:
			return "right";
			break;
	}
	return "unknown";
}

}

using namespace Internal;

void Pump ()
{
    SDL_Event evt;
    while (SDL_PollEvent(&evt))
    {
        switch (evt.type)
        {
            case SDL_KEYDOWN:
                events.push(new Event(Event::KEYDOWN, MapKey(evt.key.keysym.sym), mousePosition));
                break;
            case SDL_KEYUP:
                events.push(new Event(Event::KEYUP, MapKey(evt.key.keysym.sym), mousePosition));
                break;
            case SDL_QUIT:
                events.push(new Event(Event::QUIT, "", mousePosition));
                break;
            case SDL_MOUSEMOTION:
            	UpdateMouse(evt.button.x, evt.button.y);
            	break;
			case SDL_MOUSEBUTTONDOWN:
				UpdateMouse(evt.button.x, evt.button.y);
				events.push(new Event(Event::CLICK, MouseButtonName(evt.button.button), mousePosition));
				break;
			case SDL_MOUSEBUTTONUP:
				UpdateMouse(evt.button.x, evt.button.y);
				events.push(new Event(Event::RELEASE, MouseButtonName(evt.button.button), mousePosition));
				break;
        }
    }
}

Event* Next ()
{
    if (currentEvent)
        delete currentEvent;
    if (events.empty())
    {
        currentEvent = NULL;
        return NULL;
    }
    else
    {
        currentEvent = events.front();
        events.pop();
        return currentEvent;
    }
}

vec2 MousePosition ()
{
	return mousePosition;
}

}
<commit_msg>Created a somewhat kludgy system for zooming with the scroll wheel.<commit_after>#include "Input.h"

#include <SDL/SDL.h>
#include <SDL/SDL_OpenGL.h>

#include <queue>

namespace Input
{

namespace Internal
{

std::string MapKey ( SDLKey k )
{
	switch (k)
	{
#define KEYCASE(sym, string) case SDLK_ ## sym: return string
#define DIRECTCASE(sym) KEYCASE(sym, #sym)
		DIRECTCASE(a);
		DIRECTCASE(b);
		DIRECTCASE(c);
		DIRECTCASE(d);
		DIRECTCASE(e);
		DIRECTCASE(f);
		DIRECTCASE(g);
		DIRECTCASE(h);
		DIRECTCASE(i);
		DIRECTCASE(j);
		DIRECTCASE(k);
		DIRECTCASE(l);
		DIRECTCASE(m);
		DIRECTCASE(n);
		DIRECTCASE(o);
		DIRECTCASE(p);
		DIRECTCASE(q);
		DIRECTCASE(r);
		DIRECTCASE(s);
		DIRECTCASE(t);
		DIRECTCASE(u);
		DIRECTCASE(v);
		DIRECTCASE(w);
		DIRECTCASE(x);
		DIRECTCASE(y);
		DIRECTCASE(z);
		DIRECTCASE(0);
		DIRECTCASE(1);
		DIRECTCASE(2);
		DIRECTCASE(3);
		DIRECTCASE(4);
		DIRECTCASE(5);
		DIRECTCASE(6);
		DIRECTCASE(7);
		DIRECTCASE(8);
		DIRECTCASE(9);
		DIRECTCASE(F1);
		DIRECTCASE(F2);
		DIRECTCASE(F3);
		DIRECTCASE(F4);
		DIRECTCASE(F5);
		DIRECTCASE(F6);
		DIRECTCASE(F7);
		DIRECTCASE(F8);
		DIRECTCASE(F9);
		DIRECTCASE(F10);
		DIRECTCASE(F11);
		DIRECTCASE(F12);
		DIRECTCASE(KP0);
		DIRECTCASE(KP1);
		DIRECTCASE(KP2);
		DIRECTCASE(KP3);
		DIRECTCASE(KP4);
		DIRECTCASE(KP5);
		DIRECTCASE(KP6);
		DIRECTCASE(KP7);
		DIRECTCASE(KP8);
		DIRECTCASE(KP9);
		KEYCASE(BACKSPACE, "backspace");
		KEYCASE(TAB, "tab");
		KEYCASE(RETURN, "return");
		KEYCASE(ESCAPE, "escape");
		KEYCASE(SPACE, " ");
		KEYCASE(QUOTE, "\'");
		KEYCASE(LEFTPAREN, "(");
		KEYCASE(RIGHTPAREN, ")");
		KEYCASE(ASTERISK, "*");
		KEYCASE(PLUS, "+");
		KEYCASE(COMMA, ",");
		KEYCASE(MINUS, "-");
		KEYCASE(PERIOD, ".");
		KEYCASE(SLASH, "/");
		KEYCASE(COLON, ":");
		KEYCASE(SEMICOLON, ";");
		KEYCASE(AT, "at_sign");
		KEYCASE(LESS, "<");
		KEYCASE(EQUALS, "=");
		KEYCASE(GREATER, ">");
		KEYCASE(QUESTION, "?");
		KEYCASE(LEFTBRACKET, "[");
		KEYCASE(RIGHTBRACKET, "]");
		KEYCASE(BACKSLASH, "backslash");
		KEYCASE(CARET, "^");
		KEYCASE(UNDERSCORE, "_");
		KEYCASE(LEFT, "left");
		KEYCASE(RIGHT, "right");
		KEYCASE(UP, "up");
		KEYCASE(DOWN, "down");
		KEYCASE(KP_PERIOD, "KPperiod");
		KEYCASE(KP_DIVIDE, "KPdivide");
		KEYCASE(KP_MULTIPLY, "KPmultiply");
		KEYCASE(KP_MINUS, "KPminus");
		KEYCASE(KP_PLUS, "KPplus");
		KEYCASE(KP_ENTER, "KPenter");
		KEYCASE(KP_EQUALS, "KPequals");
		KEYCASE(INSERT, "ins");
		KEYCASE(HOME, "home");
		KEYCASE(END, "end");
		KEYCASE(PAGEUP, "pgup");
		KEYCASE(PAGEDOWN, "pgdn");
		KEYCASE(DELETE, "del");
		//modifier keys
		KEYCASE(CAPSLOCK, "Mcaps");
		KEYCASE(RSHIFT, "MshiftR");
		KEYCASE(LSHIFT, "MshiftL");
		KEYCASE(RCTRL, "MctrlR");
		KEYCASE(LCTRL, "MctrlL");
		KEYCASE(RALT, "MaltR");
		KEYCASE(LALT, "MaltL");
		KEYCASE(RMETA, "MmetaR");
		KEYCASE(LMETA, "MmetaL");
	}
	return "unhandled";
}

std::queue<Event*> events;
Event* currentEvent = NULL;
vec2 mousePosition;
double xdest = 0.0;
double ydest = 0.0;
double zdest = 0.0;
bool lmbPressed = false;

void UpdateMouse ( Sint16 px, Sint16 py )
{
    SDL_Surface* screen = SDL_GetVideoSurface();
    mousePosition.X() = float(px) / float(screen->w);
    mousePosition.Y() = 1.0f - (float(py) / float(screen->h));
}

std::string MouseButtonName ( Uint32 button )
{
	switch (button)
	{
		case SDL_BUTTON_LEFT:
			return "left";
			break;
		case SDL_BUTTON_MIDDLE:
			return "middle";
			break;
		case SDL_BUTTON_RIGHT:
			return "right";
			break;
		case SDL_BUTTON_WHEELDOWN:
			return "wheel_down";
			break;
		case SDL_BUTTON_WHEELUP:
			return "wheel_up";
			break;
	}
	return "unknown";
}

}

using namespace Internal;

void Pump ()
{
    SDL_Event evt;
    while (SDL_PollEvent(&evt))
    {
        switch (evt.type)
        {
            case SDL_KEYDOWN:
                events.push(new Event(Event::KEYDOWN, MapKey(evt.key.keysym.sym), mousePosition));
                break;
            case SDL_KEYUP:
                events.push(new Event(Event::KEYUP, MapKey(evt.key.keysym.sym), mousePosition));
                break;
            case SDL_QUIT:
                events.push(new Event(Event::QUIT, "", mousePosition));
                break;
            case SDL_MOUSEMOTION:
            	UpdateMouse(evt.button.x, evt.button.y);
            	break;
			case SDL_MOUSEBUTTONDOWN:
				UpdateMouse(evt.button.x, evt.button.y);
				events.push(new Event(Event::CLICK, MouseButtonName(evt.button.button), mousePosition));
				break;
			case SDL_MOUSEBUTTONUP:
				UpdateMouse(evt.button.x, evt.button.y);
				events.push(new Event(Event::RELEASE, MouseButtonName(evt.button.button), mousePosition));
				break;
        }
    }
}

Event* Next ()
{
    if (currentEvent)
        delete currentEvent;
    if (events.empty())
    {
        currentEvent = NULL;
        return NULL;
    }
    else
    {
        currentEvent = events.front();
        events.pop();
        return currentEvent;
    }
}

vec2 MousePosition ()
{
	return mousePosition;
}

}
<|endoftext|>


<commit_before>#include <future>
#include <iostream>
#include <cassert>
#include <csignal>
#include <unistd.h>

#include <capnp/message.h>
#include <capnp/serialize-packed.h>

#include "json11.hpp"
#include "cereal/gen/cpp/log.capnp.h"

#include "common/swaglog.h"
#include "common/messaging.h"
#include "common/params.h"
#include "common/timing.h"

#include "messaging.hpp"
#include "locationd_yawrate.h"
#include "params_learner.h"

#include "common/util.h"

void sigpipe_handler(int sig) {
  LOGE("SIGPIPE received");
}

int main(int argc, char *argv[]) {
  signal(SIGPIPE, (sighandler_t)sigpipe_handler);

  Context * c = Context::create();
  SubSocket * controls_state_sock = SubSocket::create(c, "controlsState");
  SubSocket * sensor_events_sock = SubSocket::create(c, "sensorEvents");
  SubSocket * camera_odometry_sock = SubSocket::create(c, "cameraOdometry");
  PubSocket * live_parameters_sock = PubSocket::create(c, "liveParameters");

  assert(controls_state_sock != NULL);
  assert(sensor_events_sock != NULL);
  assert(camera_odometry_sock != NULL);
  assert(live_parameters_sock != NULL);

  Poller * poller = Poller::create({controls_state_sock, sensor_events_sock, camera_odometry_sock});

  Localizer localizer;

  // Read car params
  char *value;
  size_t value_sz = 0;

  LOGW("waiting for params to set vehicle model");
  while (true) {
    read_db_value(NULL, "CarParams", &value, &value_sz);
    if (value_sz > 0) break;
    usleep(100*1000);
  }
  LOGW("got %d bytes CarParams", value_sz);

  // make copy due to alignment issues
  auto amsg = kj::heapArray<capnp::word>((value_sz / sizeof(capnp::word)) + 1);
  memcpy(amsg.begin(), value, value_sz);
  free(value);

  capnp::FlatArrayMessageReader cmsg(amsg);
  cereal::CarParams::Reader car_params = cmsg.getRoot<cereal::CarParams>();

  // Read params from previous run
  const int result = read_db_value(NULL, "LiveParameters", &value, &value_sz);

  std::string fingerprint = car_params.getCarFingerprint();
  std::string vin = car_params.getCarVin();
  double sR = car_params.getSteerRatio();
  double x = 1.0;
  double ao = 0.0;
  double posenet_invalid_count = 0;

  if (result == 0){
    auto str = std::string(value, value_sz);
    free(value);

    std::string err;
    auto json = json11::Json::parse(str, err);
    if (json.is_null() || !err.empty()) {
      std::string log = "Error parsing json: " + err;
      LOGW(log.c_str());
    } else {
      std::string new_fingerprint = json["carFingerprint"].string_value();
      std::string new_vin = json["carVin"].string_value();

      if (fingerprint == new_fingerprint && vin == new_vin) {
        std::string log = "Parameter starting with: " + str;
        LOGW(log.c_str());

        sR = json["steerRatio"].number_value();
        x = json["stiffnessFactor"].number_value();
        ao = json["angleOffsetAverage"].number_value();
      }
    }
  }

  ParamsLearner learner(car_params, ao, x, sR, 1.0);

  // Main loop
  int save_counter = 0;
  while (true){
    for (auto s : poller->poll(100)){
      Message * msg = s->receive();

      auto amsg = kj::heapArray<capnp::word>((msg->getSize() / sizeof(capnp::word)) + 1);
      memcpy(amsg.begin(), msg->getData(), msg->getSize());

      capnp::FlatArrayMessageReader capnp_msg(amsg);
      cereal::Event::Reader event = capnp_msg.getRoot<cereal::Event>();

      localizer.handle_log(event);

      auto which = event.which();
      // Throw vision failure if posenet and odometric speed too different
      if (which == cereal::Event::CAMERA_ODOMETRY){
        if (std::abs(localizer.posenet_speed - localizer.car_speed) > std::max(0.4 * localizer.car_speed, 5.0)) {
          posenet_invalid_count++;
        } else {
          posenet_invalid_count = 0;
        }
      } else if (which == cereal::Event::CONTROLS_STATE){
        save_counter++;

        double yaw_rate = -localizer.x[0];
        bool valid = learner.update(yaw_rate, localizer.car_speed, localizer.steering_angle);

        // TODO: Fix in replay
        double sensor_data_age = localizer.controls_state_time - localizer.sensor_data_time;
        double camera_odometry_age = localizer.controls_state_time - localizer.camera_odometry_time;

        double angle_offset_degrees = RADIANS_TO_DEGREES * learner.ao;
        double angle_offset_average_degrees = RADIANS_TO_DEGREES * learner.slow_ao;

        capnp::MallocMessageBuilder msg;
        cereal::Event::Builder event = msg.initRoot<cereal::Event>();
        event.setLogMonoTime(nanos_since_boot());
        auto live_params = event.initLiveParameters();
        live_params.setValid(valid);
        live_params.setYawRate(localizer.x[0]);
        live_params.setGyroBias(localizer.x[2]);
        live_params.setSensorValid(sensor_data_age < 5.0);
        live_params.setAngleOffset(angle_offset_degrees);
        live_params.setAngleOffsetAverage(angle_offset_average_degrees);
        live_params.setStiffnessFactor(learner.x);
        live_params.setSteerRatio(learner.sR);
        live_params.setPosenetSpeed(localizer.posenet_speed);
        live_params.setPosenetValid((posenet_invalid_count < 4) && (camera_odometry_age < 5.0));

        auto words = capnp::messageToFlatArray(msg);
        auto bytes = words.asBytes();
        live_parameters_sock->send((char*)bytes.begin(), bytes.size());

        // Save parameters every minute
        if (save_counter % 6000 == 0) {
          json11::Json json = json11::Json::object {
                                                    {"carVin", vin},
                                                    {"carFingerprint", fingerprint},
                                                    {"steerRatio", learner.sR},
                                                    {"stiffnessFactor", learner.x},
                                                    {"angleOffsetAverage", angle_offset_average_degrees},
          };

          std::string out = json.dump();
          std::async(std::launch::async,
                     [out]{
                       write_db_value(NULL, "LiveParameters", out.c_str(), out.length());
                     });
        }
      }
      delete msg;
    }
  }

  delete live_parameters_sock;
  delete controls_state_sock;
  delete camera_odometry_sock;
  delete sensor_events_sock;
  delete poller;
  delete c;

  return 0;
}
<commit_msg>Fix bias state number in paramsd too<commit_after>#include <future>
#include <iostream>
#include <cassert>
#include <csignal>
#include <unistd.h>

#include <capnp/message.h>
#include <capnp/serialize-packed.h>

#include "json11.hpp"
#include "cereal/gen/cpp/log.capnp.h"

#include "common/swaglog.h"
#include "common/messaging.h"
#include "common/params.h"
#include "common/timing.h"

#include "messaging.hpp"
#include "locationd_yawrate.h"
#include "params_learner.h"

#include "common/util.h"

void sigpipe_handler(int sig) {
  LOGE("SIGPIPE received");
}

int main(int argc, char *argv[]) {
  signal(SIGPIPE, (sighandler_t)sigpipe_handler);

  Context * c = Context::create();
  SubSocket * controls_state_sock = SubSocket::create(c, "controlsState");
  SubSocket * sensor_events_sock = SubSocket::create(c, "sensorEvents");
  SubSocket * camera_odometry_sock = SubSocket::create(c, "cameraOdometry");
  PubSocket * live_parameters_sock = PubSocket::create(c, "liveParameters");

  assert(controls_state_sock != NULL);
  assert(sensor_events_sock != NULL);
  assert(camera_odometry_sock != NULL);
  assert(live_parameters_sock != NULL);

  Poller * poller = Poller::create({controls_state_sock, sensor_events_sock, camera_odometry_sock});

  Localizer localizer;

  // Read car params
  char *value;
  size_t value_sz = 0;

  LOGW("waiting for params to set vehicle model");
  while (true) {
    read_db_value(NULL, "CarParams", &value, &value_sz);
    if (value_sz > 0) break;
    usleep(100*1000);
  }
  LOGW("got %d bytes CarParams", value_sz);

  // make copy due to alignment issues
  auto amsg = kj::heapArray<capnp::word>((value_sz / sizeof(capnp::word)) + 1);
  memcpy(amsg.begin(), value, value_sz);
  free(value);

  capnp::FlatArrayMessageReader cmsg(amsg);
  cereal::CarParams::Reader car_params = cmsg.getRoot<cereal::CarParams>();

  // Read params from previous run
  const int result = read_db_value(NULL, "LiveParameters", &value, &value_sz);

  std::string fingerprint = car_params.getCarFingerprint();
  std::string vin = car_params.getCarVin();
  double sR = car_params.getSteerRatio();
  double x = 1.0;
  double ao = 0.0;
  double posenet_invalid_count = 0;

  if (result == 0){
    auto str = std::string(value, value_sz);
    free(value);

    std::string err;
    auto json = json11::Json::parse(str, err);
    if (json.is_null() || !err.empty()) {
      std::string log = "Error parsing json: " + err;
      LOGW(log.c_str());
    } else {
      std::string new_fingerprint = json["carFingerprint"].string_value();
      std::string new_vin = json["carVin"].string_value();

      if (fingerprint == new_fingerprint && vin == new_vin) {
        std::string log = "Parameter starting with: " + str;
        LOGW(log.c_str());

        sR = json["steerRatio"].number_value();
        x = json["stiffnessFactor"].number_value();
        ao = json["angleOffsetAverage"].number_value();
      }
    }
  }

  ParamsLearner learner(car_params, ao, x, sR, 1.0);

  // Main loop
  int save_counter = 0;
  while (true){
    for (auto s : poller->poll(100)){
      Message * msg = s->receive();

      auto amsg = kj::heapArray<capnp::word>((msg->getSize() / sizeof(capnp::word)) + 1);
      memcpy(amsg.begin(), msg->getData(), msg->getSize());

      capnp::FlatArrayMessageReader capnp_msg(amsg);
      cereal::Event::Reader event = capnp_msg.getRoot<cereal::Event>();

      localizer.handle_log(event);

      auto which = event.which();
      // Throw vision failure if posenet and odometric speed too different
      if (which == cereal::Event::CAMERA_ODOMETRY){
        if (std::abs(localizer.posenet_speed - localizer.car_speed) > std::max(0.4 * localizer.car_speed, 5.0)) {
          posenet_invalid_count++;
        } else {
          posenet_invalid_count = 0;
        }
      } else if (which == cereal::Event::CONTROLS_STATE){
        save_counter++;

        double yaw_rate = -localizer.x[0];
        bool valid = learner.update(yaw_rate, localizer.car_speed, localizer.steering_angle);

        // TODO: Fix in replay
        double sensor_data_age = localizer.controls_state_time - localizer.sensor_data_time;
        double camera_odometry_age = localizer.controls_state_time - localizer.camera_odometry_time;

        double angle_offset_degrees = RADIANS_TO_DEGREES * learner.ao;
        double angle_offset_average_degrees = RADIANS_TO_DEGREES * learner.slow_ao;

        capnp::MallocMessageBuilder msg;
        cereal::Event::Builder event = msg.initRoot<cereal::Event>();
        event.setLogMonoTime(nanos_since_boot());
        auto live_params = event.initLiveParameters();
        live_params.setValid(valid);
        live_params.setYawRate(localizer.x[0]);
        live_params.setGyroBias(localizer.x[1]);
        live_params.setSensorValid(sensor_data_age < 5.0);
        live_params.setAngleOffset(angle_offset_degrees);
        live_params.setAngleOffsetAverage(angle_offset_average_degrees);
        live_params.setStiffnessFactor(learner.x);
        live_params.setSteerRatio(learner.sR);
        live_params.setPosenetSpeed(localizer.posenet_speed);
        live_params.setPosenetValid((posenet_invalid_count < 4) && (camera_odometry_age < 5.0));

        auto words = capnp::messageToFlatArray(msg);
        auto bytes = words.asBytes();
        live_parameters_sock->send((char*)bytes.begin(), bytes.size());

        // Save parameters every minute
        if (save_counter % 6000 == 0) {
          json11::Json json = json11::Json::object {
                                                    {"carVin", vin},
                                                    {"carFingerprint", fingerprint},
                                                    {"steerRatio", learner.sR},
                                                    {"stiffnessFactor", learner.x},
                                                    {"angleOffsetAverage", angle_offset_average_degrees},
          };

          std::string out = json.dump();
          std::async(std::launch::async,
                     [out]{
                       write_db_value(NULL, "LiveParameters", out.c_str(), out.length());
                     });
        }
      }
      delete msg;
    }
  }

  delete live_parameters_sock;
  delete controls_state_sock;
  delete camera_odometry_sock;
  delete sensor_events_sock;
  delete poller;
  delete c;

  return 0;
}
<|endoftext|>


<commit_before>// Test for direct coverage writing with dlopen.
// RUN: %clangxx_asan -fsanitize-coverage=1 -DSHARED %s -shared -o %T/libcoverage_direct_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=1 -DSO_DIR=\"%T\" %s %libdl -o %t

// RUN: rm -rf %T/coverage-direct

// RUN: mkdir -p %T/coverage-direct/normal
// RUN: ASAN_OPTIONS=coverage=1:coverage_direct=0:coverage_dir=%T/coverage-direct/normal:verbosity=1 %run %t
// RUN: %sancov print %T/coverage-direct/normal/*.sancov >%T/coverage-direct/normal/out.txt

// RUN: mkdir -p %T/coverage-direct/direct
// RUN: ASAN_OPTIONS=coverage=1:coverage_direct=1:coverage_dir=%T/coverage-direct/direct:verbosity=1 %run %t
// RUN: cd %T/coverage-direct/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov >out.txt
// RUN: cd ../..

// RUN: diff -u coverage-direct/normal/out.txt coverage-direct/direct/out.txt
//
// XFAIL: android

#include <assert.h>
#include <dlfcn.h>
#include <stdio.h>
#include <unistd.h>

#ifdef SHARED
extern "C" {
void bar() { printf("bar\n"); }
}
#else

int main(int argc, char **argv) {
  fprintf(stderr, "PID: %d\n", getpid());
  void *handle1 =
      dlopen(SO_DIR "/libcoverage_direct_test_1.so", RTLD_LAZY);
  assert(handle1);
  void (*bar1)() = (void (*)())dlsym(handle1, "bar");
  assert(bar1);
  bar1();

  return 0;
}
#endif
<commit_msg>[asan] Add tests for direct (mmap-ed) mode for BB- and edge-level coverage.<commit_after>// Test for direct coverage writing with dlopen at coverage level 1 to 3.

// RUN: %clangxx_asan -fsanitize-coverage=1 -DSHARED %s -shared -o %T/libcoverage_direct_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=1 -DSO_DIR=\"%T\" %s %libdl -o %t

// RUN: rm -rf %T/coverage-direct

// RUN: mkdir -p %T/coverage-direct/normal
// RUN: ASAN_OPTIONS=coverage=1:coverage_direct=0:coverage_dir=%T/coverage-direct/normal:verbosity=1 %run %t
// RUN: %sancov print %T/coverage-direct/normal/*.sancov >%T/coverage-direct/normal/out.txt

// RUN: mkdir -p %T/coverage-direct/direct
// RUN: ASAN_OPTIONS=coverage=1:coverage_direct=1:coverage_dir=%T/coverage-direct/direct:verbosity=1 %run %t
// RUN: cd %T/coverage-direct/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov >out.txt
// RUN: cd ../..

// RUN: diff -u coverage-direct/normal/out.txt coverage-direct/direct/out.txt

// RUN: %clangxx_asan -fsanitize-coverage=2 -DSHARED %s -shared -o %T/libcoverage_direct_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=2 -DSO_DIR=\"%T\" %s %libdl -o %t

// RUN: rm -rf %T/coverage-direct

// RUN: mkdir -p %T/coverage-direct/normal
// RUN: ASAN_OPTIONS=coverage=1:coverage_direct=0:coverage_dir=%T/coverage-direct/normal:verbosity=1 %run %t
// RUN: %sancov print %T/coverage-direct/normal/*.sancov >%T/coverage-direct/normal/out.txt

// RUN: mkdir -p %T/coverage-direct/direct
// RUN: ASAN_OPTIONS=coverage=1:coverage_direct=1:coverage_dir=%T/coverage-direct/direct:verbosity=1 %run %t
// RUN: cd %T/coverage-direct/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov >out.txt
// RUN: cd ../..

// RUN: diff -u coverage-direct/normal/out.txt coverage-direct/direct/out.txt

// RUN: %clangxx_asan -fsanitize-coverage=3 -DSHARED %s -shared -o %T/libcoverage_direct_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=3 -DSO_DIR=\"%T\" %s %libdl -o %t

// RUN: rm -rf %T/coverage-direct

// RUN: mkdir -p %T/coverage-direct/normal
// RUN: ASAN_OPTIONS=coverage=1:coverage_direct=0:coverage_dir=%T/coverage-direct/normal:verbosity=1 %run %t
// RUN: %sancov print %T/coverage-direct/normal/*.sancov >%T/coverage-direct/normal/out.txt

// RUN: mkdir -p %T/coverage-direct/direct
// RUN: ASAN_OPTIONS=coverage=1:coverage_direct=1:coverage_dir=%T/coverage-direct/direct:verbosity=1 %run %t
// RUN: cd %T/coverage-direct/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov >out.txt
// RUN: cd ../..

// RUN: diff -u coverage-direct/normal/out.txt coverage-direct/direct/out.txt

// XFAIL: android

#include <assert.h>
#include <dlfcn.h>
#include <stdio.h>
#include <unistd.h>

#ifdef SHARED
extern "C" {
void bar() { printf("bar\n"); }
}
#else

int main(int argc, char **argv) {
  fprintf(stderr, "PID: %d\n", getpid());
  void *handle1 =
      dlopen(SO_DIR "/libcoverage_direct_test_1.so", RTLD_LAZY);
  assert(handle1);
  void (*bar1)() = (void (*)())dlsym(handle1, "bar");
  assert(bar1);
  bar1();

  return 0;
}
#endif
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2014 Artem Pavlenko
 *
 * 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 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

// mapnik
#include <mapnik/make_unique.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/global.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/util/noncopyable.hpp>
#include <mapnik/geometry_adapters.hpp>
#include <mapnik/geometry_correct.hpp>

namespace mapnik
{

struct wkb_reader : util::noncopyable
{
private:
    const char* wkb_;
    std::size_t size_;
    std::size_t pos_;
    wkbByteOrder byteOrder_;
    bool needSwap_;
    wkbFormat format_;

public:

    enum wkbGeometryType {
        wkbPoint=1,
        wkbLineString=2,
        wkbPolygon=3,
        wkbMultiPoint=4,
        wkbMultiLineString=5,
        wkbMultiPolygon=6,
        wkbGeometryCollection=7,
        // Z
        wkbPointZ=1001,
        wkbLineStringZ=1002,
        wkbPolygonZ=1003,
        wkbMultiPointZ=1004,
        wkbMultiLineStringZ=1005,
        wkbMultiPolygonZ=1006,
        wkbGeometryCollectionZ=1007,
        // M
        wkbPointM=2001,
        wkbLineStringM=2002,
        wkbPolygonM=2003,
        wkbMultiPointM=2004,
        wkbMultiLineStringM=2005,
        wkbMultiPolygonM=2006,
        wkbGeometryCollectionM=2007,
        // ZM
        wkbPointZM=3001,
        wkbLineStringZM=3002,
        wkbPolygonZM=3003,
        wkbMultiPointZM=3004,
        wkbMultiLineStringZM=3005,
        wkbMultiPolygonZM=3006,
        wkbGeometryCollectionZM=3007
    };

    wkb_reader(const char* wkb, std::size_t size, wkbFormat format)
        : wkb_(wkb),
          size_(size),
          pos_(0),
          format_(format)
    {
        // try to determine WKB format automatically
        if (format_ == wkbAuto)
        {
            if (size_ >= 44
                && static_cast<unsigned char>(wkb_[0]) == static_cast<unsigned char>(0x00)
                && static_cast<unsigned char>(wkb_[38]) == static_cast<unsigned char>(0x7C)
                && static_cast<unsigned char>(wkb_[size_ - 1]) == static_cast<unsigned char>(0xFE))
            {
                format_ = wkbSpatiaLite;
            }
            else
            {
                format_ = wkbGeneric;
            }
        }

        switch (format_)
        {
        case wkbSpatiaLite:
            byteOrder_ = (wkbByteOrder) wkb_[1];
            pos_ = 39;
            break;

        case wkbGeneric:
        default:
            byteOrder_ = (wkbByteOrder) wkb_[0];
            pos_ = 1;
            break;
        }

        needSwap_ = byteOrder_ ? wkbXDR : wkbNDR;
    }

    mapnik::geometry::geometry read()
    {
        mapnik::geometry::geometry geom = mapnik::geometry::geometry_empty();
        int type = read_integer();
        switch (type)
        {
        case wkbPoint:
            geom = std::move(read_point());
            break;
        case wkbLineString:
            geom = std::move(read_linestring());
            break;
        case wkbPolygon:
            geom = std::move(read_polygon());
            break;
        case wkbMultiPoint:
            geom = std::move(read_multipoint());
            break;
        case wkbMultiLineString:
            geom = std::move(read_multilinestring());
            break;
        case wkbMultiPolygon:
            geom = std::move(read_multipolygon());
            break;
        case wkbGeometryCollection:
            geom = std::move(read_collection());
            break;
        case wkbPointZ:
        case wkbPointM:
            geom = std::move(read_point<true>());
            break;
        case wkbPointZM:
            geom = std::move(read_point<true,true>());
            break;
        case wkbLineStringZ:
        case wkbLineStringM:
            geom = std::move(read_linestring<true>());
            break;
        case wkbLineStringZM:
            geom = std::move(read_linestring<true,true>());
            break;
        case wkbPolygonZ:
        case wkbPolygonM:
            geom = std::move(read_polygon<true>());
            break;
        case wkbPolygonZM:
            geom = std::move(read_polygon<true,true>());
        case wkbMultiPointZ:
        case wkbMultiPointM:
            geom = std::move(read_multipoint<true>());
            break;
        case wkbMultiPointZM:
            geom = std::move(read_multipoint<true,true>());
            break;
        case wkbMultiLineStringZ:
        case wkbMultiLineStringM:
            geom = std::move(read_multilinestring<true>());
            break;
        case wkbMultiLineStringZM:
            geom = std::move(read_multilinestring<true,true>());
            break;
        case wkbMultiPolygonZ:
        case wkbMultiPolygonM:
            geom = std::move(read_multipolygon<true>());
            break;
        case wkbMultiPolygonZM:
            geom = std::move(read_multipolygon<true,true>());
            break;
        case wkbGeometryCollectionZ:
        case wkbGeometryCollectionM:
        case wkbGeometryCollectionZM:
            geom = std::move(read_collection());
            break;
        default:
            break;
        }
        return geom;
    }

private:

    int read_integer()
    {
        std::int32_t n;
        if (needSwap_)
        {
            read_int32_xdr(wkb_ + pos_, n);
        }
        else
        {
            read_int32_ndr(wkb_ + pos_, n);
        }
        pos_ += 4;

        return n;
    }

    double read_double()
    {
        double d;
        if (needSwap_)
        {
            read_double_xdr(wkb_ + pos_, d);
        }
        else
        {
            read_double_ndr(wkb_ + pos_, d);
        }
        pos_ += 8;

        return d;
    }

    template <typename Ring, bool Z = false, bool M = false>
    void read_coords(Ring & ring, std::size_t num_points)
    {
        double x,y;
        if (!needSwap_)
        {
            for (std::size_t i = 0; i < num_points; ++i)
            {
                read_double_ndr(wkb_ + pos_, x);
                read_double_ndr(wkb_ + pos_ + 8, y);
                ring.emplace_back(x,y);
                pos_ += 16; // skip XY
                if (Z) pos_ += 8;
                if (M) pos_ += 8;
            }
        }
        else
        {
            for (std::size_t i = 0; i < num_points; ++i)
            {
                read_double_xdr(wkb_ + pos_, x);
                read_double_xdr(wkb_ + pos_ + 8, y);
                ring.emplace_back(x,y);
                pos_ += 16; // skip XY
                if (Z) pos_ += 8;
                if (M) pos_ += 8;
            }
        }
    }

    template <bool Z = false, bool M = false>
    mapnik::geometry::point read_point()
    {
        double x = read_double();
        double y = read_double();
        if (Z) pos_ += 8;
        if (M) pos_ += 8;
        return mapnik::geometry::point(x, y);
    }

    template <bool Z = false, bool M = false>
    mapnik::geometry::multi_point read_multipoint()
    {
        mapnik::geometry::multi_point multi_point;
        int num_points = read_integer();
        multi_point.reserve(num_points);
        for (int i = 0; i < num_points; ++i)
        {
            pos_ += 5;
            multi_point.emplace_back(read_point<Z,M>());
        }
        return multi_point;
    }

    template <bool M = false, bool Z = false>
    mapnik::geometry::line_string read_linestring()
    {
        mapnik::geometry::line_string line;
        int num_points = read_integer();
        if (num_points > 0)
        {
            line.reserve(num_points);
            read_coords<mapnik::geometry::line_string, M, Z>(line, num_points);
        }
        return line;
    }

    template <bool M = false, bool Z = false>
    mapnik::geometry::multi_line_string read_multilinestring()
    {
        int num_lines = read_integer();
        mapnik::geometry::multi_line_string multi_line;
        multi_line.reserve(num_lines);
        for (int i = 0; i < num_lines; ++i)
        {
            pos_ += 5;
            multi_line.push_back(std::move(read_linestring<M, Z>()));
        }
        return multi_line;
    }

    template <bool M = false, bool Z = false>
    mapnik::geometry::polygon read_polygon()
    {
        int num_rings = read_integer();
        mapnik::geometry::polygon poly;
        if (num_rings > 1)
        {
            poly.interior_rings.reserve(num_rings - 1);
        }

        for (int i = 0; i < num_rings; ++i)
        {
            mapnik::geometry::linear_ring ring;
            int num_points = read_integer();
            if (num_points > 0)
            {
                ring.reserve(num_points);
                read_coords<mapnik::geometry::linear_ring, M, Z>(ring, num_points);
            }
            if ( i == 0) poly.set_exterior_ring(std::move(ring));
            else poly.add_hole(std::move(ring));
        }
        return poly;
    }

    template <bool M = false, bool Z = false>
    mapnik::geometry::multi_polygon read_multipolygon()
    {
        int num_polys = read_integer();
        mapnik::geometry::multi_polygon multi_poly;
        for (int i = 0; i < num_polys; ++i)
        {
            pos_ += 5;
            multi_poly.push_back(std::move(read_polygon<M, Z>()));
        }
        return multi_poly;
    }

    mapnik::geometry::geometry_collection read_collection()
    {
        int num_geometries = read_integer();
        mapnik::geometry::geometry_collection collection;
        for (int i = 0; i < num_geometries; ++i)
        {
            pos_ += 1; // skip byte order
            collection.push_back(std::move(read()));
         }
        return collection;
     }

    std::string wkb_geometry_type_string(int type)
    {
        std::stringstream s;

        switch (type)
        {
        case wkbPoint:               s << "Point"; break;
        case wkbPointZ:              s << "PointZ"; break;
        case wkbPointM:              s << "PointM"; break;
        case wkbPointZM:             s << "PointZM"; break;
        case wkbMultiPoint:          s << "MultiPoint"; break;
        case wkbMultiPointZ:         s << "MultiPointZ"; break;
        case wkbMultiPointM:         s << "MultiPointM"; break;
        case wkbMultiPointZM:        s << "MultiPointZM"; break;
        case wkbLineString:          s << "LineString"; break;
        case wkbLineStringZ:         s << "LineStringZ"; break;
        case wkbLineStringM:         s << "LineStringM"; break;
        case wkbLineStringZM:        s << "LineStringZM"; break;
        case wkbMultiLineString:     s << "MultiLineString"; break;
        case wkbMultiLineStringZ:    s << "MultiLineStringZ"; break;
        case wkbMultiLineStringM:    s << "MultiLineStringM"; break;
        case wkbMultiLineStringZM:   s << "MultiLineStringZM"; break;
        case wkbPolygon:             s << "Polygon"; break;
        case wkbPolygonZ:            s << "PolygonZ"; break;
        case wkbPolygonM:            s << "PolygonM"; break;
        case wkbPolygonZM:           s << "PolygonZM"; break;
        case wkbMultiPolygon:        s << "MultiPolygon"; break;
        case wkbMultiPolygonZ:       s << "MultiPolygonZ"; break;
        case wkbMultiPolygonM:       s << "MultiPolygonM"; break;
        case wkbMultiPolygonZM:      s << "MultiPolygonZM"; break;
        case wkbGeometryCollection:  s << "GeometryCollection"; break;
        case wkbGeometryCollectionZ: s << "GeometryCollectionZ"; break;
        case wkbGeometryCollectionM: s << "GeometryCollectionM"; break;
        case wkbGeometryCollectionZM:s << "GeometryCollectionZM"; break;
        default:                     s << "wkbUnknown(" << type << ")"; break;
        }

        return s.str();
    }

};

mapnik::geometry::geometry geometry_utils::from_wkb(const char* wkb,
                                                        unsigned size,
                                                        wkbFormat format)
{
    wkb_reader reader(wkb, size, format);
    mapnik::geometry::geometry geom(reader.read());
    mapnik::geometry::correct(geom);
    return geom;
}

} // namespace mapnik
<commit_msg>bug fix - add missing break statement<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2014 Artem Pavlenko
 *
 * 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 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

// mapnik
#include <mapnik/make_unique.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/global.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/util/noncopyable.hpp>
#include <mapnik/geometry_adapters.hpp>
#include <mapnik/geometry_correct.hpp>

namespace mapnik
{

struct wkb_reader : util::noncopyable
{
private:
    const char* wkb_;
    std::size_t size_;
    std::size_t pos_;
    wkbByteOrder byteOrder_;
    bool needSwap_;
    wkbFormat format_;

public:

    enum wkbGeometryType {
        wkbPoint=1,
        wkbLineString=2,
        wkbPolygon=3,
        wkbMultiPoint=4,
        wkbMultiLineString=5,
        wkbMultiPolygon=6,
        wkbGeometryCollection=7,
        // Z
        wkbPointZ=1001,
        wkbLineStringZ=1002,
        wkbPolygonZ=1003,
        wkbMultiPointZ=1004,
        wkbMultiLineStringZ=1005,
        wkbMultiPolygonZ=1006,
        wkbGeometryCollectionZ=1007,
        // M
        wkbPointM=2001,
        wkbLineStringM=2002,
        wkbPolygonM=2003,
        wkbMultiPointM=2004,
        wkbMultiLineStringM=2005,
        wkbMultiPolygonM=2006,
        wkbGeometryCollectionM=2007,
        // ZM
        wkbPointZM=3001,
        wkbLineStringZM=3002,
        wkbPolygonZM=3003,
        wkbMultiPointZM=3004,
        wkbMultiLineStringZM=3005,
        wkbMultiPolygonZM=3006,
        wkbGeometryCollectionZM=3007
    };

    wkb_reader(const char* wkb, std::size_t size, wkbFormat format)
        : wkb_(wkb),
          size_(size),
          pos_(0),
          format_(format)
    {
        // try to determine WKB format automatically
        if (format_ == wkbAuto)
        {
            if (size_ >= 44
                && static_cast<unsigned char>(wkb_[0]) == static_cast<unsigned char>(0x00)
                && static_cast<unsigned char>(wkb_[38]) == static_cast<unsigned char>(0x7C)
                && static_cast<unsigned char>(wkb_[size_ - 1]) == static_cast<unsigned char>(0xFE))
            {
                format_ = wkbSpatiaLite;
            }
            else
            {
                format_ = wkbGeneric;
            }
        }

        switch (format_)
        {
        case wkbSpatiaLite:
            byteOrder_ = (wkbByteOrder) wkb_[1];
            pos_ = 39;
            break;

        case wkbGeneric:
        default:
            byteOrder_ = (wkbByteOrder) wkb_[0];
            pos_ = 1;
            break;
        }

        needSwap_ = byteOrder_ ? wkbXDR : wkbNDR;
    }

    mapnik::geometry::geometry read()
    {
        mapnik::geometry::geometry geom = mapnik::geometry::geometry_empty();
        int type = read_integer();
        switch (type)
        {
        case wkbPoint:
            geom = std::move(read_point());
            break;
        case wkbLineString:
            geom = std::move(read_linestring());
            break;
        case wkbPolygon:
            geom = std::move(read_polygon());
            break;
        case wkbMultiPoint:
            geom = std::move(read_multipoint());
            break;
        case wkbMultiLineString:
            geom = std::move(read_multilinestring());
            break;
        case wkbMultiPolygon:
            geom = std::move(read_multipolygon());
            break;
        case wkbGeometryCollection:
            geom = std::move(read_collection());
            break;
        case wkbPointZ:
        case wkbPointM:
            geom = std::move(read_point<true>());
            break;
        case wkbPointZM:
            geom = std::move(read_point<true,true>());
            break;
        case wkbLineStringZ:
        case wkbLineStringM:
            geom = std::move(read_linestring<true>());
            break;
        case wkbLineStringZM:
            geom = std::move(read_linestring<true,true>());
            break;
        case wkbPolygonZ:
        case wkbPolygonM:
            geom = std::move(read_polygon<true>());
            break;
        case wkbPolygonZM:
            geom = std::move(read_polygon<true,true>());
            break;
        case wkbMultiPointZ:
        case wkbMultiPointM:
            geom = std::move(read_multipoint<true>());
            break;
        case wkbMultiPointZM:
            geom = std::move(read_multipoint<true,true>());
            break;
        case wkbMultiLineStringZ:
        case wkbMultiLineStringM:
            geom = std::move(read_multilinestring<true>());
            break;
        case wkbMultiLineStringZM:
            geom = std::move(read_multilinestring<true,true>());
            break;
        case wkbMultiPolygonZ:
        case wkbMultiPolygonM:
            geom = std::move(read_multipolygon<true>());
            break;
        case wkbMultiPolygonZM:
            geom = std::move(read_multipolygon<true,true>());
            break;
        case wkbGeometryCollectionZ:
        case wkbGeometryCollectionM:
        case wkbGeometryCollectionZM:
            geom = std::move(read_collection());
            break;
        default:
            break;
        }
        return geom;
    }

private:

    int read_integer()
    {
        std::int32_t n;
        if (needSwap_)
        {
            read_int32_xdr(wkb_ + pos_, n);
        }
        else
        {
            read_int32_ndr(wkb_ + pos_, n);
        }
        pos_ += 4;

        return n;
    }

    double read_double()
    {
        double d;
        if (needSwap_)
        {
            read_double_xdr(wkb_ + pos_, d);
        }
        else
        {
            read_double_ndr(wkb_ + pos_, d);
        }
        pos_ += 8;

        return d;
    }

    template <typename Ring, bool Z = false, bool M = false>
    void read_coords(Ring & ring, std::size_t num_points)
    {
        double x,y;
        if (!needSwap_)
        {
            for (std::size_t i = 0; i < num_points; ++i)
            {
                read_double_ndr(wkb_ + pos_, x);
                read_double_ndr(wkb_ + pos_ + 8, y);
                ring.emplace_back(x,y);
                pos_ += 16; // skip XY
                if (Z) pos_ += 8;
                if (M) pos_ += 8;
            }
        }
        else
        {
            for (std::size_t i = 0; i < num_points; ++i)
            {
                read_double_xdr(wkb_ + pos_, x);
                read_double_xdr(wkb_ + pos_ + 8, y);
                ring.emplace_back(x,y);
                pos_ += 16; // skip XY
                if (Z) pos_ += 8;
                if (M) pos_ += 8;
            }
        }
    }

    template <bool Z = false, bool M = false>
    mapnik::geometry::point read_point()
    {
        double x = read_double();
        double y = read_double();
        if (Z) pos_ += 8;
        if (M) pos_ += 8;
        return mapnik::geometry::point(x, y);
    }

    template <bool Z = false, bool M = false>
    mapnik::geometry::multi_point read_multipoint()
    {
        mapnik::geometry::multi_point multi_point;
        int num_points = read_integer();
        multi_point.reserve(num_points);
        for (int i = 0; i < num_points; ++i)
        {
            pos_ += 5;
            multi_point.emplace_back(read_point<Z,M>());
        }
        return multi_point;
    }

    template <bool M = false, bool Z = false>
    mapnik::geometry::line_string read_linestring()
    {
        mapnik::geometry::line_string line;
        int num_points = read_integer();
        if (num_points > 0)
        {
            line.reserve(num_points);
            read_coords<mapnik::geometry::line_string, M, Z>(line, num_points);
        }
        return line;
    }

    template <bool M = false, bool Z = false>
    mapnik::geometry::multi_line_string read_multilinestring()
    {
        int num_lines = read_integer();
        mapnik::geometry::multi_line_string multi_line;
        multi_line.reserve(num_lines);
        for (int i = 0; i < num_lines; ++i)
        {
            pos_ += 5;
            multi_line.push_back(std::move(read_linestring<M, Z>()));
        }
        return multi_line;
    }

    template <bool M = false, bool Z = false>
    mapnik::geometry::polygon read_polygon()
    {
        int num_rings = read_integer();
        mapnik::geometry::polygon poly;
        if (num_rings > 1)
        {
            poly.interior_rings.reserve(num_rings - 1);
        }

        for (int i = 0; i < num_rings; ++i)
        {
            mapnik::geometry::linear_ring ring;
            int num_points = read_integer();
            if (num_points > 0)
            {
                ring.reserve(num_points);
                read_coords<mapnik::geometry::linear_ring, M, Z>(ring, num_points);
            }
            if ( i == 0) poly.set_exterior_ring(std::move(ring));
            else poly.add_hole(std::move(ring));
        }
        return poly;
    }

    template <bool M = false, bool Z = false>
    mapnik::geometry::multi_polygon read_multipolygon()
    {
        int num_polys = read_integer();
        mapnik::geometry::multi_polygon multi_poly;
        for (int i = 0; i < num_polys; ++i)
        {
            pos_ += 5;
            multi_poly.push_back(std::move(read_polygon<M, Z>()));
        }
        return multi_poly;
    }

    mapnik::geometry::geometry_collection read_collection()
    {
        int num_geometries = read_integer();
        mapnik::geometry::geometry_collection collection;
        for (int i = 0; i < num_geometries; ++i)
        {
            pos_ += 1; // skip byte order
            collection.push_back(std::move(read()));
         }
        return collection;
     }

    std::string wkb_geometry_type_string(int type)
    {
        std::stringstream s;

        switch (type)
        {
        case wkbPoint:               s << "Point"; break;
        case wkbPointZ:              s << "PointZ"; break;
        case wkbPointM:              s << "PointM"; break;
        case wkbPointZM:             s << "PointZM"; break;
        case wkbMultiPoint:          s << "MultiPoint"; break;
        case wkbMultiPointZ:         s << "MultiPointZ"; break;
        case wkbMultiPointM:         s << "MultiPointM"; break;
        case wkbMultiPointZM:        s << "MultiPointZM"; break;
        case wkbLineString:          s << "LineString"; break;
        case wkbLineStringZ:         s << "LineStringZ"; break;
        case wkbLineStringM:         s << "LineStringM"; break;
        case wkbLineStringZM:        s << "LineStringZM"; break;
        case wkbMultiLineString:     s << "MultiLineString"; break;
        case wkbMultiLineStringZ:    s << "MultiLineStringZ"; break;
        case wkbMultiLineStringM:    s << "MultiLineStringM"; break;
        case wkbMultiLineStringZM:   s << "MultiLineStringZM"; break;
        case wkbPolygon:             s << "Polygon"; break;
        case wkbPolygonZ:            s << "PolygonZ"; break;
        case wkbPolygonM:            s << "PolygonM"; break;
        case wkbPolygonZM:           s << "PolygonZM"; break;
        case wkbMultiPolygon:        s << "MultiPolygon"; break;
        case wkbMultiPolygonZ:       s << "MultiPolygonZ"; break;
        case wkbMultiPolygonM:       s << "MultiPolygonM"; break;
        case wkbMultiPolygonZM:      s << "MultiPolygonZM"; break;
        case wkbGeometryCollection:  s << "GeometryCollection"; break;
        case wkbGeometryCollectionZ: s << "GeometryCollectionZ"; break;
        case wkbGeometryCollectionM: s << "GeometryCollectionM"; break;
        case wkbGeometryCollectionZM:s << "GeometryCollectionZM"; break;
        default:                     s << "wkbUnknown(" << type << ")"; break;
        }

        return s.str();
    }

};

mapnik::geometry::geometry geometry_utils::from_wkb(const char* wkb,
                                                        unsigned size,
                                                        wkbFormat format)
{
    wkb_reader reader(wkb, size, format);
    mapnik::geometry::geometry geom(reader.read());
    mapnik::geometry::correct(geom);
    return geom;
}

} // namespace mapnik
<|endoftext|>


<commit_before>#include "FPSRoleLocal.h"
#include "Creature.h"
#include "Engine.h"
#include "Input.h"
#include "App.h"
#include "ObjectMeshSkinned.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "game.h"
#include "RayControl.h"
#include "Common.h"
#include "ControlsApp.h"

CFPSRoleLocal::CFPSRoleLocal(void)
{
	m_nCharMode = 0;
	m_nMuzzleBone = -1;
	m_nUpdateMove = 0;
}

CFPSRoleLocal::~CFPSRoleLocal(void)
{
	delete m_pActorBase;
}

int CFPSRoleLocal::Init( int nRoleID,const char* strCharFile )
{
	CFPSRole::Init(nRoleID,strCharFile);

	m_pCreature->SetupBody(1,1);
	m_pCreature->SetHighShadow(1);
	SetupArms(2,0);

	m_pActorBase = new CActorBase();
	m_pActorBase->SetEnabled(1);

	//
	//m_vCameraOffset = vec3(0.0f,0.0f,1.8f);
	m_vCameraOffset = vec3(0.0f,0.0f,1.8f);
	//m_vGunOffset = vec3(0.0,0.0,-0.0f);
	m_vGunOffset = vec3(0.2,0.2,0.2f);
	//m_vRotateOffset = vec3(-0.076326f, 0.018540f, -1.725809f); // gua dian  weizhi);
	m_vRotateOffset = vec3(-0.076326f, 0.018540f, -1.725809f); // gua dian  weizhi);

	return 1;
}

void CFPSRoleLocal::Update( float ifps )
{
	if(m_pFire[0] && m_pFire[1])
	{
		//if(g_Engine.pApp->GetMouseButtonState(CApp::BUTTON_LEFT) || g_Engine.pApp->GetMouseButtonState(CApp::BUTTON_LDCLICK) )
		if(g_Engine.pInput->IsLBDownPress()||g_Engine.pInput->IsLBDBDown())
		{
			OpenFire();		//굥
		}
		else
		{
			CloseFire();
		}
	}

	CFPSRole::Update(ifps);
	CRayControl::Instance().Update(m_matMuzzleTransform,vec3(0.0f,0.5f,-0.03f));
}

void CFPSRoleLocal::OnFire( float fCoolingTime )
{
	CFPSRole::OnFire(fCoolingTime);
}

void CFPSRoleLocal::UpdateTransform( const MathLib::mat4 & matRotate )
{
	mat4 m = Translate(m_pActorBase->GetPosition()+ m_vCameraOffset) * Translate(m_vGunOffset) * matRotate * Translate(m_vRotateOffset);

}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "FPSRoleLocal.h"
#include "Creature.h"
#include "Engine.h"
#include "Input.h"
#include "App.h"
#include "ObjectMeshSkinned.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "game.h"
#include "RayControl.h"
#include "Common.h"
#include "ControlsApp.h"

CFPSRoleLocal::CFPSRoleLocal(void)
{
	m_nCharMode = 0;
	m_nMuzzleBone = -1;
	m_nUpdateMove = 0;
}

CFPSRoleLocal::~CFPSRoleLocal(void)
{
	delete m_pActorBase;
}

int CFPSRoleLocal::Init( int nRoleID,const char* strCharFile )
{
	CFPSRole::Init(nRoleID,strCharFile);

	m_pCreature->SetupBody(1,1);
	m_pCreature->SetHighShadow(1);
	SetupArms(2,0);

	m_pActorBase = new CActorBase();
	m_pActorBase->SetEnabled(1);

	//
	//m_vCameraOffset = vec3(0.0f,0.0f,1.8f);
	m_vCameraOffset = vec3(0.0f,0.0f,1.8f);
	//m_vGunOffset = vec3(0.0,0.0,-0.0f);
	m_vGunOffset = vec3(0.2,0.2,0.2f);
	//m_vRotateOffset = vec3(-0.076326f, 0.018540f, -1.725809f); // gua dian  weizhi);
	m_vRotateOffset = vec3(-0.076326f, 0.018540f, -1.725809f); // gua dian  weizhi);

	return 1;
}

void CFPSRoleLocal::Update( float ifps )
{
	if(m_pFire[0] && m_pFire[1])
	{
		//if(g_Engine.pApp->GetMouseButtonState(CApp::BUTTON_LEFT) || g_Engine.pApp->GetMouseButtonState(CApp::BUTTON_LDCLICK) )
		if(g_Engine.pInput->IsLBDownPress()||g_Engine.pInput->IsLBDBDown())
		{
			OpenFire();		//굥
		}
		else
		{
			CloseFire();
		}
	}

	CFPSRole::Update(ifps);
	CRayControl::Instance().Update(m_matMuzzleTransform,vec3(0.0f,0.5f,-0.03f));
}

void CFPSRoleLocal::OnFire( float fCoolingTime )
{
	CFPSRole::OnFire(fCoolingTime);
}

void CFPSRoleLocal::UpdateTransform( const MathLib::mat4 & matRotate )
{
	mat4 m = Translate(m_pActorBase->GetPosition()+ m_vCameraOffset) * Translate(m_vGunOffset) * matRotate * Translate(m_vRotateOffset);
	m_pCreature->GetMainObjectMesh()->SetWorldTransform(m);
}

<|endoftext|>


<commit_before>/*-
 * Copyright (c) 2016 Frederic Culot <culot@FreeBSD.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer
 *    in this position and unchanged.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``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 AUTHOR(S) 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 <tuple>
#include <curses.h>

#include "event.h"
#include "inputwindow.h"

namespace portal {
namespace gfx {

InputWindow::InputWindow(const Point& pos, int len)
  : Window() {
  Size size;
  size.setHeight(3);
  size.setWidth(len + 2);
  setSize(size);

  Point position;
  position.setX(pos.x() - 1);
  position.setY(pos.y() - 1);
  setPosition(position);

  Style style;
  style.underline = true;
  setStyle(style);

  draw();
}

std::string InputWindow::getInput() {
  for (;;) {
    portal::Event event;
    event.poll();
    clear();
    switch (event.type()) {
      case portal::Event::Type::enter:
        return content_;
      case portal::Event::Type::keyBackspace:
        content_.pop_back();
        break;
      case portal::Event::Type::character:
        content_.push_back(event.character());
        break;
      default:
        // DO NOTHING
        break;
    }
    print(content_);
  }
}

void InputWindow::setContent(const std::string& content) {
  content_ = content;
  print(content_);
}

}
}
<commit_msg>Fix input window position<commit_after>/*-
 * Copyright (c) 2016 Frederic Culot <culot@FreeBSD.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer
 *    in this position and unchanged.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``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 AUTHOR(S) 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 <tuple>
#include <curses.h>

#include "event.h"
#include "inputwindow.h"

namespace portal {
namespace gfx {

InputWindow::InputWindow(const Point& pos, int len)
  : Window() {
  Size size;
  size.setHeight(1);
  size.setWidth(len + 2);
  setSize(size);

  Point position;
  position.setX(pos.x() - len / 2);
  position.setY(pos.y());
  setPosition(position);

  Style style;
  style.underline = true;
  setStyle(style);

  draw();
}

std::string InputWindow::getInput() {
  for (;;) {
    portal::Event event;
    event.poll();
    clear();
    switch (event.type()) {
      case portal::Event::Type::enter:
        return content_;
      case portal::Event::Type::keyBackspace:
        content_.pop_back();
        break;
      case portal::Event::Type::character:
        content_.push_back(event.character());
        break;
      default:
        // DO NOTHING
        break;
    }
    print(content_);
  }
}

void InputWindow::setContent(const std::string& content) {
  content_ = content;
  print(content_);
}

}
}
<|endoftext|>