<commit_before>/*
 * AdapterBase.cpp
 *
 *  Created on: Oct 22, 2015
 *      Author: Péter Fankhauser
 *   Institute: ETH Zurich, Autonomous Systems Lab
 */

#include <free_gait_core/executor/AdapterBase.hpp>

namespace free_gait {

AdapterBase::AdapterBase()
{
}

AdapterBase::~AdapterBase()
{
}

bool AdapterBase::frameIdExists(const std::string& frameId) const
{
  if (frameId == "base") return true;
  if (frameId == getWorldFrameId()) return true;
  if (frameId == "map") return true;
  if (frameId == "map_ga") return true;
  return false;
}

Position AdapterBase::transformPosition(const std::string& inputFrameId,
                                        const std::string& outputFrameId,
                                        const Position& position) const
{
  Position transformedPosition;
  bool frameError = false;

  if (inputFrameId == "base") {

    if (outputFrameId == "base") {
      transformedPosition = position;
    } else if (outputFrameId == getWorldFrameId()) {
      transformedPosition = getPositionWorldToBaseInWorldFrame() + getOrientationWorldToBase().inverseRotate(position);
    } else if (outputFrameId == "map" || outputFrameId == "map_ga" ) {
      const Position positionInOdom = transformPosition(inputFrameId, getWorldFrameId(), position);
      transformedPosition = transformPosition(getWorldFrameId(), outputFrameId, positionInOdom);
    } else {
      frameError = true;
    }

  } else if (inputFrameId == getWorldFrameId()) {

    if (outputFrameId == "base") {
      transformedPosition = getOrientationWorldToBase().rotate(position - getPositionWorldToBaseInWorldFrame());
    } else if (outputFrameId == getWorldFrameId()) {
      transformedPosition = position;
    } else if (outputFrameId == "map" || outputFrameId == "map_ga" ) {
      // TODO Why does this not work?
//      transformedPosition = getFramePoseInWorld(outputFrameId).inverseTransform(position);
      const Pose pose(getFrameTransform(outputFrameId));
      transformedPosition = pose.getRotation().rotate((position - pose.getPosition()));
    } else {
      frameError = true;
    }

  } else if (inputFrameId == "map" || inputFrameId == "map_ga") {

    if (outputFrameId == "base") {
      const Position positionInOdom = transformPosition(inputFrameId, getWorldFrameId(), position);
      transformedPosition = transformPosition(getWorldFrameId(), outputFrameId, positionInOdom);
    } else if (outputFrameId == getWorldFrameId()) {
      // TODO Why does this not work?
//      transformedPosition = getFramePoseInWorld(inputFrameId).transform(position);
      const Pose pose(getFrameTransform(inputFrameId));
      transformedPosition = pose.getRotation().inverseRotate(position) + pose.getPosition();
    } else {
      frameError = true;
    }

  } else {
    frameError = true;
  }

  if (frameError) {
    const std::string message = "Invalid frame for transforming position (input frame: " + inputFrameId + ", output frame: " + outputFrameId + ").";
    throw std::invalid_argument(message);
  }
  return transformedPosition;
}

RotationQuaternion AdapterBase::transformOrientation(const std::string& inputFrameId,
                                                     const std::string& outputFrameId,
                                                     const RotationQuaternion& orientation) const
{
  RotationQuaternion transformedOrientation;
  bool frameError = false;

  if (inputFrameId == getWorldFrameId()) {

    if (outputFrameId == getWorldFrameId()) {
      transformedOrientation = orientation;
    } else if (outputFrameId == "map" || outputFrameId == "map_ga" ) {
      const Pose pose(getFrameTransform(outputFrameId));
      transformedOrientation = pose.getRotation().inverted() * orientation;
    } else {
      frameError = true;
    }

  } else if (inputFrameId == "map" || inputFrameId == "map_ga") {

    if (outputFrameId == getWorldFrameId()) {
      const Pose pose(getFrameTransform(inputFrameId));
      transformedOrientation = pose.getRotation() * orientation;
    } else {
      frameError = true;
    }

  } else {
    frameError = true;
  }

  if (frameError) {
    const std::string message = "Invalid frame for transforming orientation (input frame: " + inputFrameId + ", output frame: " + outputFrameId + ").";
    throw std::invalid_argument(message);
  }
  return transformedOrientation;
}

Pose AdapterBase::transformPose(const std::string& inputFrameId, const std::string& outputFrameId,
                                const Pose& pose) const
{
  Pose transformedPose;
  transformedPose.getPosition() = transformPosition(inputFrameId, outputFrameId, pose.getPosition());
  transformedPose.getRotation() = transformOrientation(inputFrameId, outputFrameId, pose.getRotation());
  return transformedPose;
}

} /* namespace free_gait */
<commit_msg>Fixed rotation order bug.<commit_after>/*
 * AdapterBase.cpp
 *
 *  Created on: Oct 22, 2015
 *      Author: Péter Fankhauser
 *   Institute: ETH Zurich, Autonomous Systems Lab
 */

#include <free_gait_core/executor/AdapterBase.hpp>

namespace free_gait {

AdapterBase::AdapterBase()
{
}

AdapterBase::~AdapterBase()
{
}

bool AdapterBase::frameIdExists(const std::string& frameId) const
{
  if (frameId == "base") return true;
  if (frameId == getWorldFrameId()) return true;
  if (frameId == "map") return true;
  if (frameId == "map_ga") return true;
  return false;
}

Position AdapterBase::transformPosition(const std::string& inputFrameId,
                                        const std::string& outputFrameId,
                                        const Position& position) const
{
  Position transformedPosition;
  bool frameError = false;

  if (inputFrameId == "base") {

    if (outputFrameId == "base") {
      transformedPosition = position;
    } else if (outputFrameId == getWorldFrameId()) {
      transformedPosition = getPositionWorldToBaseInWorldFrame() + getOrientationWorldToBase().inverseRotate(position);
    } else if (outputFrameId == "map" || outputFrameId == "map_ga" ) {
      const Position positionInOdom = transformPosition(inputFrameId, getWorldFrameId(), position);
      transformedPosition = transformPosition(getWorldFrameId(), outputFrameId, positionInOdom);
    } else {
      frameError = true;
    }

  } else if (inputFrameId == getWorldFrameId()) {

    if (outputFrameId == "base") {
      transformedPosition = getOrientationWorldToBase().rotate(position - getPositionWorldToBaseInWorldFrame());
    } else if (outputFrameId == getWorldFrameId()) {
      transformedPosition = position;
    } else if (outputFrameId == "map" || outputFrameId == "map_ga" ) {
      // TODO Why does this not work?
//      transformedPosition = getFramePoseInWorld(outputFrameId).inverseTransform(position);
      const Pose pose(getFrameTransform(outputFrameId));
      transformedPosition = pose.getRotation().rotate((position - pose.getPosition()));
    } else {
      frameError = true;
    }

  } else if (inputFrameId == "map" || inputFrameId == "map_ga") {

    if (outputFrameId == "base") {
      const Position positionInOdom = transformPosition(inputFrameId, getWorldFrameId(), position);
      transformedPosition = transformPosition(getWorldFrameId(), outputFrameId, positionInOdom);
    } else if (outputFrameId == getWorldFrameId()) {
      // TODO Why does this not work?
//      transformedPosition = getFramePoseInWorld(inputFrameId).transform(position);
      const Pose pose(getFrameTransform(inputFrameId));
      transformedPosition = pose.getRotation().inverseRotate(position) + pose.getPosition();
    } else {
      frameError = true;
    }

  } else {
    frameError = true;
  }

  if (frameError) {
    const std::string message = "Invalid frame for transforming position (input frame: " + inputFrameId + ", output frame: " + outputFrameId + ").";
    throw std::invalid_argument(message);
  }
  return transformedPosition;
}

RotationQuaternion AdapterBase::transformOrientation(const std::string& inputFrameId,
                                                     const std::string& outputFrameId,
                                                     const RotationQuaternion& orientation) const
{
  RotationQuaternion transformedOrientation;
  bool frameError = false;

  if (inputFrameId == getWorldFrameId()) {

    if (outputFrameId == getWorldFrameId()) {
      transformedOrientation = orientation;
    } else if (outputFrameId == "map" || outputFrameId == "map_ga" ) {
      const Pose pose(getFrameTransform(outputFrameId));
      transformedOrientation = orientation * pose.getRotation().inverted();
    } else {
      frameError = true;
    }

  } else if (inputFrameId == "map" || inputFrameId == "map_ga") {

    if (outputFrameId == getWorldFrameId()) {
      const Pose pose(getFrameTransform(inputFrameId));
      transformedOrientation = orientation * pose.getRotation();
    } else {
      frameError = true;
    }

  } else {
    frameError = true;
  }

  if (frameError) {
    const std::string message = "Invalid frame for transforming orientation (input frame: " + inputFrameId + ", output frame: " + outputFrameId + ").";
    throw std::invalid_argument(message);
  }
  return transformedOrientation;
}

Pose AdapterBase::transformPose(const std::string& inputFrameId, const std::string& outputFrameId,
                                const Pose& pose) const
{
  Pose transformedPose;
  transformedPose.getPosition() = transformPosition(inputFrameId, outputFrameId, pose.getPosition());
  transformedPose.getRotation() = transformOrientation(inputFrameId, outputFrameId, pose.getRotation());
  return transformedPose;
}

} /* namespace free_gait */
<|endoftext|>


<commit_before>/*
 * FUNCTION:
 * Potgres driver --
 *
 * Threading:
 * ----------
 * This class is thread-enabled but not thread-safe. Two threads should
 * not try to use one instance of this class at the same time. Each
 * thread should construct it's own instance of this class. This class
 * uses no globals.
 *
 * HISTORY:
 * Copyright (c) 2017 Linas Vepstas
 *
 * LICENSE:
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#ifdef HAVE_PGSQL_STORAGE

#include <libpq-fe.h>

#include <opencog/util/exceptions.h>
#include <opencog/util/Logger.h>
#include <opencog/util/platform.h>

#include "ll-pg-cxx.h"

#define PERR(...) \
	throw opencog::RuntimeException(TRACE_INFO, __VA_ARGS__);

/* =========================================================== */

LLPGConnection::LLPGConnection(const char * _dbname,
							   const char * _username,
							   const char * _authentication)
	: LLConnection(_dbname, _username, _authentication)
{
	is_connected = false;

	if (NULL == _dbname)
	{
		PERR("No DB specified");
		return;
	}

	std::string constr = "dbname = ";
	constr += _dbname;
	_pgconn = PQconnectdb(constr.c_str());

	if (PQstatus(_pgconn) != CONNECTION_OK)
	{
printf("duuuude %s", PQerrorMessage(_pgconn));
		opencog::logger().warn("%s", PQerrorMessage(_pgconn));
		PQfinish(_pgconn);
		PERR("Cannot conect to database");
	}

	is_connected = true;
}

/* =========================================================== */

LLPGConnection::~LLPGConnection()
{
	PQfinish(_pgconn);
}

/* =========================================================== */
#define DEFAULT_NUM_COLS 50

LLPGRecordSet * LLPGConnection::get_record_set(void)
{
	LLPGRecordSet *rs;
	if (!free_pool.empty())
	{
		LLRecordSet* llrs = free_pool.top();
		rs = dynamic_cast<LLPGRecordSet*>(llrs);
		free_pool.pop();
		rs->ncols = -1;
	}
	else
	{
		rs = new LLPGRecordSet(this);
	}

	rs->alloc_and_bind_cols(DEFAULT_NUM_COLS);

	return rs;
}

/* =========================================================== */

LLRecordSet *
LLPGConnection::exec(const char * buff)
{
	if (!is_connected) return NULL;

	LLPGRecordSet* rs = get_record_set();

if (PQstatus(_pgconn) != CONNECTION_OK)
{
printf("duuuude wtf.....\n");
}
	rs->_result = PQexec(_pgconn, buff);

	ExecStatusType rest = PQresultStatus(rs->_result);
printf("duuude try exec %s\n", buff);
	if (rest != PGRES_COMMAND_OK and
	    rest != PGRES_EMPTY_QUERY and
	    rest != PGRES_TUPLES_OK)
	{
		opencog::logger().warn("%s", PQresultErrorMessage(rs->_result));
printf("duuude %s", PQresultErrorMessage(rs->_result));
		rs->release();
		PERR("Failed to execute!");
	}

printf("duuude done exec %s\n", buff);
	/* Use numbr of columns to indicate that the query hasn't
	 * given results yet. */
	rs->ncols = -1;
	return rs;
}

/* =========================================================== */

void
LLPGRecordSet::alloc_and_bind_cols(int new_ncols)
{
	LLRecordSet::alloc_and_bind_cols(new_ncols);
}

/* =========================================================== */
/* pseudo-private routine */

LLPGRecordSet::LLPGRecordSet(LLPGConnection* _conn)
	: LLRecordSet(_conn)
{
}

/* =========================================================== */

void
LLPGRecordSet::release(void)
{
	PQclear(_result);
	LLRecordSet::release();
}

/* =========================================================== */

LLPGRecordSet::~LLPGRecordSet()
{
}

/* =========================================================== */

void
LLPGRecordSet::get_column_labels(void)
{
	if (0 <= ncols) return;

	/* If number of columns is negative, then we haven't
	 * gotten any results back yet.  Start by getting the
	 * column labels.
	 */

printf("duuuuuuuuuuuuuuude get teh column labs!!!!\n");
}

/* =========================================================== */

int
LLPGRecordSet::fetch_row(void)
{
	// Columns can have null values.  In this case, the PG shims
	// will neither set nor clear the value-strings. As a result,
	// some random value from a previous query will still be sitting
	// there, in the values, and get reported to the unlucky user.
	for (int i=0; i<ncols; i++) values[i][0] = 0;

printf("duuuuuuuuuuuuuuude get fetch the rowss!!!!\n");
	return 1;
}

#endif /* HAVE_PGSQL_STORAGE */
/* ============================= END OF FILE ================= */
<commit_msg>Working login credentials<commit_after>/*
 * FUNCTION:
 * Potgres driver --
 *
 * Threading:
 * ----------
 * This class is thread-enabled but not thread-safe. Two threads should
 * not try to use one instance of this class at the same time. Each
 * thread should construct it's own instance of this class. This class
 * uses no globals.
 *
 * HISTORY:
 * Copyright (c) 2017 Linas Vepstas
 *
 * LICENSE:
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#ifdef HAVE_PGSQL_STORAGE

#include <libpq-fe.h>

#include <opencog/util/exceptions.h>
#include <opencog/util/Logger.h>
#include <opencog/util/platform.h>

#include "ll-pg-cxx.h"

#define PERR(...) \
	throw opencog::RuntimeException(TRACE_INFO, __VA_ARGS__);

/* =========================================================== */

LLPGConnection::LLPGConnection(const char * _dbname,
							   const char * _username,
							   const char * _authentication)
	: LLConnection(_dbname, _username, _authentication)
{
	is_connected = false;

	if (NULL == _dbname)
	{
		PERR("No DB specified");
		return;
	}

	// XXX hack. We should probably use the postrges URI format, here.
	// The URI format allows a remote host to be specified, and to toggle
	// between unix-domain and tcp sockets, etc.
	std::string constr = "dbname=";
	constr += _dbname;
	constr += " user=";
	constr += _username;
	constr += " password=";
	constr += _authentication;
	_pgconn = PQconnectdb(constr.c_str());

	if (PQstatus(_pgconn) != CONNECTION_OK)
	{
		opencog::logger().warn("%s", PQerrorMessage(_pgconn));
		PQfinish(_pgconn);
		PERR("Cannot conect to database");
	}

	is_connected = true;
}

/* =========================================================== */

LLPGConnection::~LLPGConnection()
{
	PQfinish(_pgconn);
}

/* =========================================================== */
#define DEFAULT_NUM_COLS 50

LLPGRecordSet * LLPGConnection::get_record_set(void)
{
	LLPGRecordSet *rs;
	if (!free_pool.empty())
	{
		LLRecordSet* llrs = free_pool.top();
		rs = dynamic_cast<LLPGRecordSet*>(llrs);
		free_pool.pop();
		rs->ncols = -1;
	}
	else
	{
		rs = new LLPGRecordSet(this);
	}

	rs->alloc_and_bind_cols(DEFAULT_NUM_COLS);

	return rs;
}

/* =========================================================== */

LLRecordSet *
LLPGConnection::exec(const char * buff)
{
	if (!is_connected) return NULL;

	LLPGRecordSet* rs = get_record_set();

	rs->_result = PQexec(_pgconn, buff);

	ExecStatusType rest = PQresultStatus(rs->_result);
	if (rest != PGRES_COMMAND_OK and
	    rest != PGRES_EMPTY_QUERY and
	    rest != PGRES_TUPLES_OK)
	{
		opencog::logger().warn("%s", PQresultErrorMessage(rs->_result));
printf("duuude %s", PQresultErrorMessage(rs->_result));
		rs->release();
		PERR("Failed to execute!");
	}

printf("duuude done exec %s\n", buff);
	/* Use numbr of columns to indicate that the query hasn't
	 * given results yet. */
	rs->ncols = -1;
	return rs;
}

/* =========================================================== */

void
LLPGRecordSet::alloc_and_bind_cols(int new_ncols)
{
	LLRecordSet::alloc_and_bind_cols(new_ncols);
}

/* =========================================================== */
/* pseudo-private routine */

LLPGRecordSet::LLPGRecordSet(LLPGConnection* _conn)
	: LLRecordSet(_conn)
{
}

/* =========================================================== */

void
LLPGRecordSet::release(void)
{
	PQclear(_result);
	LLRecordSet::release();
}

/* =========================================================== */

LLPGRecordSet::~LLPGRecordSet()
{
}

/* =========================================================== */

void
LLPGRecordSet::get_column_labels(void)
{
	if (0 <= ncols) return;

	/* If number of columns is negative, then we haven't
	 * gotten any results back yet.  Start by getting the
	 * column labels.
	 */

printf("duuuuuuuuuuuuuuude get teh column labs!!!!\n");
}

/* =========================================================== */

int
LLPGRecordSet::fetch_row(void)
{
	// Columns can have null values.  In this case, the PG shims
	// will neither set nor clear the value-strings. As a result,
	// some random value from a previous query will still be sitting
	// there, in the values, and get reported to the unlucky user.
	for (int i=0; i<ncols; i++) values[i][0] = 0;

printf("duuuuuuuuuuuuuuude get fetch the rowss!!!!\n");
	return 0;
}

#endif /* HAVE_PGSQL_STORAGE */
/* ============================= END OF FILE ================= */
<|endoftext|>


<commit_before>#include <cstring>

#include <iostream>
#include <atomic>
#include <vector>
#include <functional>
#include <type_traits>
#include <stdexcept>

#include <flatbuffers/flatbuffers.h>
#include <flatbuffers/idl.h>
#include <flatbuffers/util.h>

#include "libvedis.h"
#include "libenet.h"
#include "signal_handlers.h"

#include "flightctrlstate_generated.h"
#include "netmessages_generated.h"
#include "server_generated.h"

using msg_handler = std::function<void(keron::net::host &, const keron::net::event &, const keron::messages::NetMessage &)>;
using config_ptr = std::unique_ptr<const keron::server::Configuration>;

void msg_none(keron::net::host &, const keron::net::event &, const keron::messages::NetMessage &)
{
	std::cout << "No message.\n";
}

void msg_chat(keron::net::host &host, const keron::net::event &event, const keron::messages::NetMessage &msg)
{
	auto chat = reinterpret_cast<const keron::messages::Chat *>(msg.message());
	std::cout << "Chat message: " << chat->message()->c_str() << std::endl;
	keron::net::packet response(event.packet->data, event.packet->dataLength, event.packet->flags);
	host.broadcast(event.channelID, response);
}

void msg_flightctrl(keron::net::host &host, const keron::net::event &event, const keron::messages::NetMessage &flight)
{
	auto flightCtrl = reinterpret_cast<const keron::messages::FlightCtrl *>(flight.message());
	std::cout << "Flight control state" << std::endl;
}

void load_configuration(flatbuffers::Parser &parser, const std::string &schema, const std::string &configfile)
{
	std::string serverschema;
	std::string configjson;
        parser.builder_.Clear();

	if (!flatbuffers::LoadFile(schema.c_str(), false, &serverschema))
                throw std::runtime_error("Cannot load server schema.");

	parser.Parse(serverschema.c_str());

	if (!flatbuffers::LoadFile(configfile.c_str(), false, &configjson)) {
		std::cerr << "No server configuration found. Creating a default one." << std::endl;
		flatbuffers::FlatBufferBuilder fbb;
		auto cfg = keron::server::CreateConfiguration(fbb, fbb.CreateString("*"), 18246, 8, fbb.CreateString("server.vdb"));
		auto generator = flatbuffers::GeneratorOptions();
		generator.strict_json = true;
		FinishConfigurationBuffer(fbb, cfg);
		flatbuffers::GenerateText(parser, fbb.GetBufferPointer(), generator, &configjson);

		if (!flatbuffers::SaveFile(configfile.c_str(), configjson.c_str(), configjson.size(), false))
                        throw std::runtime_error("Unable to write default configuration!");

                throw std::runtime_error(
			"A default configuration has been written. "
			"Check the content of `server.json`, and restart the server.");
	}

	parser.Parse(configjson.c_str());
}

std::vector<msg_handler> initialize_messages_handlers()
{
	using namespace keron::messages;

	std::vector<msg_handler> handlers(3);
	handlers[NetID_NONE] = msg_none;
	handlers[NetID_Chat] = msg_chat;
	handlers[NetID_FlightCtrl] = msg_flightctrl;

	return handlers;
}

ENetAddress initialize_server_address(const keron::server::Configuration &config)
{
	const std::string host(config.address()->c_str());
	uint16_t port{config.port()};

	ENetAddress address;

	if (host != "*")
		address.host = ENET_HOST_ANY;
	else
		enet_address_set_host(&address, host.c_str());

	address.port = port;
	return address;
}

int main(void)
{
	std::cout << "Registering signal handlers." << std::endl;
	int errcode = keron::server::register_signal_handlers();

	if (errcode)
		return errcode;

	std::cout << "Loading server configuration." << std::endl;
        flatbuffers::Parser parser;
        load_configuration(parser, "schemas/server.fbs", "server.json");

        auto settings = keron::server::GetConfiguration(parser.builder_.GetBufferPointer());

	std::cout << "Firing up storage." << std::endl;
        keron::db::store datastore(settings->datastore()->c_str());

	std::cout << "Preparing message handlers." << std::endl;
	std::vector<msg_handler> handlers = initialize_messages_handlers();

	std::cout << "Initializing network." << std::endl;
	keron::net::library enet;

	auto address = initialize_server_address(*settings);
	keron::net::host host(address, settings->maxclients(), 2);
	if (!host) {
		std::cerr << "ERROR: creating host." << std::endl;
		return -3;
	}

	keron::net::event event;

	std::cout << "Listening on " << settings->address()->c_str() << ":" << settings->port()
		<< " " << settings->maxclients() << " clients allowed." << std::endl;

	while (host.service(event, 100) >= 0 && !keron::server::stop) {
		switch (event.type) {
			case ENET_EVENT_TYPE_RECEIVE:
			{
				keron::net::packet packet(event.packet);
				keron::net::address address(event.peer->address);
				std::cout
					<< "Received packet from "
					<< address.ip()
					<< " on channel " << static_cast<int>(event.channelID)
					<< " size " << packet.length() << std::endl;

				flatbuffers::Verifier verifier(packet.data(), packet.length());
				if (!keron::messages::VerifyNetMessageBuffer(verifier)) {
					std::cout << "Incorrect buffer received." << std::endl;
					break;
				}

				auto message = keron::messages::GetNetMessage(packet.data());
				keron::messages::NetID id = message->message_type();
				std::cout << "Message is: " << keron::messages::EnumNameNetID(id) << std::endl;

				if (!(id < handlers.size())) {
					std::cout << "No available handlers.";
					break;
				}

				handlers.at(id)(host, event, *message);

			}
				break;
			case ENET_EVENT_TYPE_CONNECT:
			{
				keron::net::address address(event.peer->address);
				std::cout << "Connection from: " << address.ip() << std::endl;
			}
				break;
			case ENET_EVENT_TYPE_DISCONNECT:
			{
				keron::net::address address(event.peer->address);
				std::cout << "Disconnection from: " << address.ip() << std::endl;
			}
				break;
			case ENET_EVENT_TYPE_NONE:
				// reached timeout without incomings.
				break;
			default:
				std::cout << "Unhandled event `" << event.type << "`\n";
		}
	}

	std::cout << "Server is shutting down." << std::endl;

	return 0;
}

// vim: shiftwidth=4 tabstop=4
<commit_msg>Wrong condition!<commit_after>#include <cstring>

#include <iostream>
#include <atomic>
#include <vector>
#include <functional>
#include <type_traits>
#include <stdexcept>

#include <flatbuffers/flatbuffers.h>
#include <flatbuffers/idl.h>
#include <flatbuffers/util.h>

#include "libvedis.h"
#include "libenet.h"
#include "signal_handlers.h"

#include "flightctrlstate_generated.h"
#include "netmessages_generated.h"
#include "server_generated.h"

using msg_handler = std::function<void(keron::net::host &, const keron::net::event &, const keron::messages::NetMessage &)>;
using config_ptr = std::unique_ptr<const keron::server::Configuration>;

void msg_none(keron::net::host &, const keron::net::event &, const keron::messages::NetMessage &)
{
	std::cout << "No message.\n";
}

void msg_chat(keron::net::host &host, const keron::net::event &event, const keron::messages::NetMessage &msg)
{
	auto chat = reinterpret_cast<const keron::messages::Chat *>(msg.message());
	std::cout << "Chat message: " << chat->message()->c_str() << std::endl;
	keron::net::packet response(event.packet->data, event.packet->dataLength, event.packet->flags);
	host.broadcast(event.channelID, response);
}

void msg_flightctrl(keron::net::host &host, const keron::net::event &event, const keron::messages::NetMessage &flight)
{
	auto flightCtrl = reinterpret_cast<const keron::messages::FlightCtrl *>(flight.message());
	std::cout << "Flight control state" << std::endl;
}

void load_configuration(flatbuffers::Parser &parser, const std::string &schema, const std::string &configfile)
{
	std::string serverschema;
	std::string configjson;
        parser.builder_.Clear();

	if (!flatbuffers::LoadFile(schema.c_str(), false, &serverschema))
                throw std::runtime_error("Cannot load server schema.");

	parser.Parse(serverschema.c_str());

	if (!flatbuffers::LoadFile(configfile.c_str(), false, &configjson)) {
		std::cerr << "No server configuration found. Creating a default one." << std::endl;
		flatbuffers::FlatBufferBuilder fbb;
		auto cfg = keron::server::CreateConfiguration(fbb, fbb.CreateString("*"), 18246, 8, fbb.CreateString("server.vdb"));
		auto generator = flatbuffers::GeneratorOptions();
		generator.strict_json = true;
		FinishConfigurationBuffer(fbb, cfg);
		flatbuffers::GenerateText(parser, fbb.GetBufferPointer(), generator, &configjson);

		if (!flatbuffers::SaveFile(configfile.c_str(), configjson.c_str(), configjson.size(), false))
                        throw std::runtime_error("Unable to write default configuration!");

                throw std::runtime_error(
			"A default configuration has been written. "
			"Check the content of `server.json`, and restart the server.");
	}

	parser.Parse(configjson.c_str());
}

std::vector<msg_handler> initialize_messages_handlers()
{
	using namespace keron::messages;

	std::vector<msg_handler> handlers(3);
	handlers[NetID_NONE] = msg_none;
	handlers[NetID_Chat] = msg_chat;
	handlers[NetID_FlightCtrl] = msg_flightctrl;

	return handlers;
}

ENetAddress initialize_server_address(const keron::server::Configuration &config)
{
	const std::string host(config.address()->c_str());
	uint16_t port{config.port()};

	ENetAddress address;

	if (host == "*")
		address.host = ENET_HOST_ANY;
	else
		enet_address_set_host(&address, host.c_str());

	address.port = port;
	return address;
}

int main(void)
{
	std::cout << "Registering signal handlers." << std::endl;
	int errcode = keron::server::register_signal_handlers();

	if (errcode)
		return errcode;

	std::cout << "Loading server configuration." << std::endl;
        flatbuffers::Parser parser;
        load_configuration(parser, "schemas/server.fbs", "server.json");

        auto settings = keron::server::GetConfiguration(parser.builder_.GetBufferPointer());

	std::cout << "Firing up storage." << std::endl;
        keron::db::store datastore(settings->datastore()->c_str());

	std::cout << "Preparing message handlers." << std::endl;
	std::vector<msg_handler> handlers = initialize_messages_handlers();

	std::cout << "Initializing network." << std::endl;
	keron::net::library enet;

	auto address = initialize_server_address(*settings);
	keron::net::host host(address, settings->maxclients(), 2);
	if (!host) {
		std::cerr << "ERROR: creating host." << std::endl;
		return -3;
	}

	keron::net::event event;

	std::cout << "Listening on " << settings->address()->c_str() << ":" << settings->port()
		<< " " << settings->maxclients() << " clients allowed." << std::endl;

	while (host.service(event, 100) >= 0 && !keron::server::stop) {
		switch (event.type) {
			case ENET_EVENT_TYPE_RECEIVE:
			{
				keron::net::packet packet(event.packet);
				keron::net::address address(event.peer->address);
				std::cout
					<< "Received packet from "
					<< address.ip()
					<< " on channel " << static_cast<int>(event.channelID)
					<< " size " << packet.length() << std::endl;

				flatbuffers::Verifier verifier(packet.data(), packet.length());
				if (!keron::messages::VerifyNetMessageBuffer(verifier)) {
					std::cout << "Incorrect buffer received." << std::endl;
					break;
				}

				auto message = keron::messages::GetNetMessage(packet.data());
				keron::messages::NetID id = message->message_type();
				std::cout << "Message is: " << static_cast<int>(id) << " " << keron::messages::EnumNameNetID(id) << std::endl;

				if (!(id < handlers.size())) {
					std::cout << "No available handlers.";
					break;
				}

				handlers.at(id)(host, event, *message);

			}
				break;
			case ENET_EVENT_TYPE_CONNECT:
			{
				keron::net::address address(event.peer->address);
				std::cout << "Connection from: " << address.ip() << std::endl;
			}
				break;
			case ENET_EVENT_TYPE_DISCONNECT:
			{
				keron::net::address address(event.peer->address);
				std::cout << "Disconnection from: " << address.ip() << std::endl;
			}
				break;
			case ENET_EVENT_TYPE_NONE:
				// reached timeout without incomings.
				break;
			default:
				std::cout << "Unhandled event `" << event.type << "`\n";
		}
	}

	std::cout << "Server is shutting down." << std::endl;

	return 0;
}

// vim: shiftwidth=4 tabstop=4
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: dxfreprd.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: ka $ $Date: 2002-05-29 13:11:35 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <string.h>
#include <dxfreprd.hxx>

//------------------DXFBoundingBox--------------------------------------------

void DXFBoundingBox::Union(const DXFVector & rVector)
{
    if (bEmpty==TRUE) {
        fMinX=rVector.fx;
        fMinY=rVector.fy;
        fMinZ=rVector.fz;
        fMaxX=rVector.fx;
        fMaxY=rVector.fy;
        fMaxZ=rVector.fz;
        bEmpty=FALSE;
    }
    else {
        if (fMinX>rVector.fx) fMinX=rVector.fx;
        if (fMinY>rVector.fy) fMinY=rVector.fy;
        if (fMinZ>rVector.fz) fMinZ=rVector.fz;
        if (fMaxX<rVector.fx) fMaxX=rVector.fx;
        if (fMaxY<rVector.fy) fMaxY=rVector.fy;
        if (fMaxZ<rVector.fz) fMaxZ=rVector.fz;
    }
}

//------------------DXFPalette------------------------------------------------

DXFPalette::DXFPalette()
{
    short i,j,nHue,nNSat,nVal,nC[3],nmax,nmed,nmin;
    BYTE nV;

    pRed  =new BYTE[256];
    pGreen=new BYTE[256];
    pBlue =new BYTE[256];

    // Farben 0 - 9 (normale Farben)
    SetColor(0, 0x00, 0x00, 0x00); // eigentlich nie benutzt
    SetColor(1, 0xff, 0x00, 0x00);
    SetColor(2, 0xff, 0xff, 0x00);
    SetColor(3, 0x00, 0xff, 0x00);
    SetColor(4, 0x00, 0xff, 0xff);
    SetColor(5, 0x00, 0x00, 0xff);
    SetColor(6, 0xff, 0x00, 0xff);
    SetColor(7, 0x0f, 0x0f, 0x0f); // eigentlich weiss ???
    SetColor(8, 0x80, 0x80, 0x80);
    SetColor(9, 0xc0, 0xc0, 0xc0);

    // Farben 10 - 249
    // (Universal-Palette: 24 Farbtoene * 5 Helligkeiten * 2 Saettigungen )
    i=10;
    for (nHue=0; nHue<24; nHue++) {
        for (nVal=5; nVal>=1; nVal--) {
            for (nNSat=0; nNSat<2; nNSat++) {
                nmax=((nHue+3)>>3)%3;
                j=nHue-(nmax<<3); if (j>4) j=j-24;
                if (j>=0) {
                    nmed=(nmax+1)%3;
                    nmin=(nmax+2)%3;
                }
                else {
                    nmed=(nmax+2)%3;
                    nmin=(nmax+1)%3;
                    j=-j;
                }
                nC[nmin]=0;
                nC[nmed]=255*j/4;
                nC[nmax]=255;
                if (nNSat!=0) {
                    for (j=0; j<3; j++) nC[j]=(nC[j]>>1)+128;
                }
                for (j=0; j<3; j++) nC[j]=nC[j]*nVal/5;
                SetColor((BYTE)(i++),(BYTE)nC[0],(BYTE)nC[1],(BYTE)nC[2]);
            }
        }
    }

    // Farben 250 - 255 (Grautoenne)
    for (i=0; i<6; i++) {
        nV=(BYTE)(i*38+65);
        SetColor((BYTE)(250+i),nV,nV,nV);
    }
}

DXFPalette::~DXFPalette()
{
    delete[] pBlue;
    delete[] pGreen;
    delete[] pRed;
}

void DXFPalette::SetColor(BYTE nIndex, BYTE nRed, BYTE nGreen, BYTE nBlue)
{
    pRed[nIndex]=nRed;
    pGreen[nIndex]=nGreen;
    pBlue[nIndex]=nBlue;
}

//------------------DXFRepresentation-----------------------------------------

DXFRepresentation::DXFRepresentation()
{
}

DXFRepresentation::~DXFRepresentation()
{
}

BOOL DXFRepresentation::Read(SvStream & rIStream,
                             PFilterCallback pCallback, void * pCallerData,
                             USHORT nMinPercent, USHORT nMaxPercent)
{
    DXFGroupReader * pDGR;
    BOOL bRes;

    aTables.Clear();
    aBlocks.Clear();
    aEntities.Clear();

    pDGR = new DXFGroupReader(rIStream,pCallback,pCallerData,nMinPercent,nMaxPercent);

    pDGR->Read();
    while (pDGR->GetG()!=0 || strcmp(pDGR->GetS(),"EOF")!=0) {
        if (pDGR->GetG()==0 && strcmp(pDGR->GetS(),"SECTION")==0) {
            if (pDGR->Read()!=2) {
                pDGR->SetError();
                break;
            }
            if      (strcmp(pDGR->GetS(),"HEADER"  )==0) ReadHeader(*pDGR);
            else if (strcmp(pDGR->GetS(),"TABLES"  )==0) aTables.Read(*pDGR);
            else if (strcmp(pDGR->GetS(),"BLOCKS"  )==0) aBlocks.Read(*pDGR);
            else if (strcmp(pDGR->GetS(),"ENTITIES")==0) aEntities.Read(*pDGR);
            else pDGR->Read();
        }
        else pDGR->Read();
    }

    bRes=pDGR->GetStatus();

    delete pDGR;

    if (bRes==TRUE && aBoundingBox.bEmpty==TRUE)
        CalcBoundingBox(aEntities,aBoundingBox);

    return bRes;
}

void DXFRepresentation::ReadHeader(DXFGroupReader & rDGR)
{

    while (rDGR.GetG()!=0 || (strcmp(rDGR.GetS(),"EOF")!=0 &&
                              strcmp(rDGR.GetS(),"ENDSEC")!=0) )
    {
        if (rDGR.GetG()==9) {
            if (strcmp(rDGR.GetS(),"$EXTMIN")==0 ||
                strcmp(rDGR.GetS(),"$EXTMAX")==0)
            {
                DXFVector aVector;
                rDGR.SetF(10,0.0);
                rDGR.SetF(20,0.0);
                rDGR.SetF(30,0.0);
                do {
                    rDGR.Read();
                } while (rDGR.GetG()!=9 && rDGR.GetG()!=0);
                aVector.fx=rDGR.GetF(10);
                aVector.fy=rDGR.GetF(20);
                aVector.fz=rDGR.GetF(30);
                aBoundingBox.Union(aVector);
            }
            else rDGR.Read();
        }
        else rDGR.Read();
    }
}

void DXFRepresentation::CalcBoundingBox(const DXFEntities & rEntities,
                                        DXFBoundingBox & rBox)
{
    DXFBasicEntity * pBE=rEntities.pFirst;
    while (pBE!=NULL) {
        switch (pBE->eType) {
            case DXF_LINE: {
                const DXFLineEntity * pE = (DXFLineEntity*)pBE;
                rBox.Union(pE->aP0);
                rBox.Union(pE->aP1);
                break;
            }
            case DXF_POINT: {
                const DXFPointEntity * pE = (DXFPointEntity*)pBE;
                rBox.Union(pE->aP0);
                break;
            }
            case DXF_CIRCLE: {
                const DXFCircleEntity * pE = (DXFCircleEntity*)pBE;
                DXFVector aP;
                aP=pE->aP0;
                aP.fx-=pE->fRadius;
                aP.fy-=pE->fRadius;
                rBox.Union(aP);
                aP=pE->aP0;
                aP.fx+=pE->fRadius;
                aP.fy+=pE->fRadius;
                rBox.Union(aP);
                break;
            }
            case DXF_ARC: {
                const DXFArcEntity * pE = (DXFArcEntity*)pBE;
                DXFVector aP;
                aP=pE->aP0;
                aP.fx-=pE->fRadius;
                aP.fy-=pE->fRadius;
                rBox.Union(aP);
                aP=pE->aP0;
                aP.fx+=pE->fRadius;
                aP.fy+=pE->fRadius;
                rBox.Union(aP);
                break;
            }
            case DXF_TRACE: {
                const DXFTraceEntity * pE = (DXFTraceEntity*)pBE;
                rBox.Union(pE->aP0);
                rBox.Union(pE->aP1);
                rBox.Union(pE->aP2);
                rBox.Union(pE->aP3);
                break;
            }
            case DXF_SOLID: {
                const DXFSolidEntity * pE = (DXFSolidEntity*)pBE;
                rBox.Union(pE->aP0);
                rBox.Union(pE->aP1);
                rBox.Union(pE->aP2);
                rBox.Union(pE->aP3);
                break;
            }
            case DXF_TEXT: {
                const DXFTextEntity * pE = (DXFTextEntity*)pBE;
                //???
                break;
            }
            case DXF_SHAPE: {
                const DXFShapeEntity * pE = (DXFShapeEntity*)pBE;
                //???
                break;
            }
            case DXF_INSERT: {
                const DXFInsertEntity * pE = (DXFInsertEntity*)pBE;
                DXFBlock * pB;
                DXFBoundingBox aBox;
                DXFVector aP;
                pB=aBlocks.Search(pE->sName);
                if (pB==NULL) break;
                CalcBoundingBox(*pB,aBox);
                if (aBox.bEmpty==TRUE) break;
                aP.fx=(aBox.fMinX-pB->aBasePoint.fx)*pE->fXScale+pE->aP0.fx;
                aP.fy=(aBox.fMinY-pB->aBasePoint.fy)*pE->fYScale+pE->aP0.fy;
                aP.fz=(aBox.fMinZ-pB->aBasePoint.fz)*pE->fZScale+pE->aP0.fz;
                rBox.Union(aP);
                aP.fx=(aBox.fMaxX-pB->aBasePoint.fx)*pE->fXScale+pE->aP0.fx;
                aP.fy=(aBox.fMaxY-pB->aBasePoint.fy)*pE->fYScale+pE->aP0.fy;
                aP.fz=(aBox.fMaxZ-pB->aBasePoint.fz)*pE->fZScale+pE->aP0.fz;
                rBox.Union(aP);
                break;
            }
            case DXF_ATTDEF: {
                const DXFAttDefEntity * pE = (DXFAttDefEntity*)pBE;
                //???
                break;
            }
            case DXF_ATTRIB: {
                const DXFAttribEntity * pE = (DXFAttribEntity*)pBE;
                //???
                break;
            }
            case DXF_VERTEX: {
                const DXFVertexEntity * pE = (DXFVertexEntity*)pBE;
                rBox.Union(pE->aP0);
                break;
            }
            case DXF_3DFACE: {
                const DXF3DFaceEntity * pE = (DXF3DFaceEntity*)pBE;
                rBox.Union(pE->aP0);
                rBox.Union(pE->aP1);
                rBox.Union(pE->aP2);
                rBox.Union(pE->aP3);
                break;
            }
            case DXF_DIMENSION: {
                const DXFDimensionEntity * pE = (DXFDimensionEntity*)pBE;
                DXFBlock * pB;
                DXFBoundingBox aBox;
                DXFVector aP;
                pB=aBlocks.Search(pE->sPseudoBlock);
                if (pB==NULL) break;
                CalcBoundingBox(*pB,aBox);
                if (aBox.bEmpty==TRUE) break;
                aP.fx=aBox.fMinX-pB->aBasePoint.fx;
                aP.fy=aBox.fMinY-pB->aBasePoint.fy;
                aP.fz=aBox.fMinZ-pB->aBasePoint.fz;
                rBox.Union(aP);
                aP.fx=aBox.fMaxX-pB->aBasePoint.fx;
                aP.fy=aBox.fMaxY-pB->aBasePoint.fy;
                aP.fz=aBox.fMaxZ-pB->aBasePoint.fz;
                rBox.Union(aP);
                break;
            }
        }
        pBE=pBE->pSucc;
    }
}

<commit_msg>INTEGRATION: CWS geordi2q11 (1.2.128); FILE MERGED 2003/12/16 12:42:40 hr 1.2.128.1: #111934#: join CWS ooo111fix1<commit_after>/*************************************************************************
 *
 *  $RCSfile: dxfreprd.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2003-12-17 18:25:52 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <string.h>
#include <dxfreprd.hxx>

//------------------DXFBoundingBox--------------------------------------------

void DXFBoundingBox::Union(const DXFVector & rVector)
{
    if (bEmpty==TRUE) {
        fMinX=rVector.fx;
        fMinY=rVector.fy;
        fMinZ=rVector.fz;
        fMaxX=rVector.fx;
        fMaxY=rVector.fy;
        fMaxZ=rVector.fz;
        bEmpty=FALSE;
    }
    else {
        if (fMinX>rVector.fx) fMinX=rVector.fx;
        if (fMinY>rVector.fy) fMinY=rVector.fy;
        if (fMinZ>rVector.fz) fMinZ=rVector.fz;
        if (fMaxX<rVector.fx) fMaxX=rVector.fx;
        if (fMaxY<rVector.fy) fMaxY=rVector.fy;
        if (fMaxZ<rVector.fz) fMaxZ=rVector.fz;
    }
}

//------------------DXFPalette------------------------------------------------

DXFPalette::DXFPalette()
{
    short i,j,nHue,nNSat,nVal,nC[3],nmax,nmed,nmin;
    BYTE nV;

    pRed  =new BYTE[256];
    pGreen=new BYTE[256];
    pBlue =new BYTE[256];

    // Farben 0 - 9 (normale Farben)
    SetColor(0, 0x00, 0x00, 0x00); // eigentlich nie benutzt
    SetColor(1, 0xff, 0x00, 0x00);
    SetColor(2, 0xff, 0xff, 0x00);
    SetColor(3, 0x00, 0xff, 0x00);
    SetColor(4, 0x00, 0xff, 0xff);
    SetColor(5, 0x00, 0x00, 0xff);
    SetColor(6, 0xff, 0x00, 0xff);
    SetColor(7, 0x0f, 0x0f, 0x0f); // eigentlich weiss ???
    SetColor(8, 0x80, 0x80, 0x80);
    SetColor(9, 0xc0, 0xc0, 0xc0);

    // Farben 10 - 249
    // (Universal-Palette: 24 Farbtoene * 5 Helligkeiten * 2 Saettigungen )
    i=10;
    for (nHue=0; nHue<24; nHue++) {
        for (nVal=5; nVal>=1; nVal--) {
            for (nNSat=0; nNSat<2; nNSat++) {
                nmax=((nHue+3)>>3)%3;
                j=nHue-(nmax<<3); if (j>4) j=j-24;
                if (j>=0) {
                    nmed=(nmax+1)%3;
                    nmin=(nmax+2)%3;
                }
                else {
                    nmed=(nmax+2)%3;
                    nmin=(nmax+1)%3;
                    j=-j;
                }
                nC[nmin]=0;
                nC[nmed]=255*j/4;
                nC[nmax]=255;
                if (nNSat!=0) {
                    for (j=0; j<3; j++) nC[j]=(nC[j]>>1)+128;
                }
                for (j=0; j<3; j++) nC[j]=nC[j]*nVal/5;
                SetColor((BYTE)(i++),(BYTE)nC[0],(BYTE)nC[1],(BYTE)nC[2]);
            }
        }
    }

    // Farben 250 - 255 (Grautoenne)
    for (i=0; i<6; i++) {
        nV=(BYTE)(i*38+65);
        SetColor((BYTE)(250+i),nV,nV,nV);
    }
}

DXFPalette::~DXFPalette()
{
    delete[] pBlue;
    delete[] pGreen;
    delete[] pRed;
}

void DXFPalette::SetColor(BYTE nIndex, BYTE nRed, BYTE nGreen, BYTE nBlue)
{
    pRed[nIndex]=nRed;
    pGreen[nIndex]=nGreen;
    pBlue[nIndex]=nBlue;
}

//------------------DXFRepresentation-----------------------------------------

DXFRepresentation::DXFRepresentation()
{
  setTextEncoding(RTL_TEXTENCODING_IBM_437);
}

DXFRepresentation::~DXFRepresentation()
{
}

BOOL DXFRepresentation::Read(SvStream & rIStream,
                             PFilterCallback pCallback, void * pCallerData,
                             USHORT nMinPercent, USHORT nMaxPercent)
{
    DXFGroupReader * pDGR;
    BOOL bRes;

    aTables.Clear();
    aBlocks.Clear();
    aEntities.Clear();

    pDGR = new DXFGroupReader(rIStream,pCallback,pCallerData,nMinPercent,nMaxPercent);

    pDGR->Read();
    while (pDGR->GetG()!=0 || strcmp(pDGR->GetS(),"EOF")!=0) {
        if (pDGR->GetG()==0 && strcmp(pDGR->GetS(),"SECTION")==0) {
            if (pDGR->Read()!=2) {
                pDGR->SetError();
                break;
            }
            if      (strcmp(pDGR->GetS(),"HEADER"  )==0) ReadHeader(*pDGR);
            else if (strcmp(pDGR->GetS(),"TABLES"  )==0) aTables.Read(*pDGR);
            else if (strcmp(pDGR->GetS(),"BLOCKS"  )==0) aBlocks.Read(*pDGR);
            else if (strcmp(pDGR->GetS(),"ENTITIES")==0) aEntities.Read(*pDGR);
            else pDGR->Read();
        }
        else pDGR->Read();
    }

    bRes=pDGR->GetStatus();

    delete pDGR;

    if (bRes==TRUE && aBoundingBox.bEmpty==TRUE)
        CalcBoundingBox(aEntities,aBoundingBox);

    return bRes;
}

void DXFRepresentation::ReadHeader(DXFGroupReader & rDGR)
{

         while (rDGR.GetG()!=0 || (strcmp(rDGR.GetS(),"EOF")!=0 &&  strcmp(rDGR.GetS(),"ENDSEC")!=0) )
         {
                 if (rDGR.GetG()==9) {
                         if (strcmp(rDGR.GetS(),"$EXTMIN")==0 ||
                                 strcmp(rDGR.GetS(),"$EXTMAX")==0)
                         {
                                 DXFVector aVector;
                                 rDGR.SetF(10,0.0);
                                 rDGR.SetF(20,0.0);
                                 rDGR.SetF(30,0.0);
                                 do {
                                         rDGR.Read();
                                 } while (rDGR.GetG()!=9 && rDGR.GetG()!=0);
                                 aVector.fx=rDGR.GetF(10);
                                 aVector.fy=rDGR.GetF(20);
                                 aVector.fz=rDGR.GetF(30);
                                 aBoundingBox.Union(aVector);
                         } else {
                                 if (strcmp(rDGR.GetS(),"$DWGCODEPAGE")==0)
                                 {
                                         rDGR.Read();

                                         // FIXME: we really need a whole table of
                                         // $DWGCODEPAGE to encodings mappings
                                         if ( (strcmp(rDGR.GetS(),"ANSI_932")==0) ||
                                              (strcmp(rDGR.GetS(),"DOS932")==0) )
                                         {
                                                 setTextEncoding(RTL_TEXTENCODING_MS_932);
                                         }
                                 }
                                 else rDGR.Read();
                         }
                 }
                 else rDGR.Read();
         }
}

void DXFRepresentation::CalcBoundingBox(const DXFEntities & rEntities,
                                        DXFBoundingBox & rBox)
{
    DXFBasicEntity * pBE=rEntities.pFirst;
    while (pBE!=NULL) {
        switch (pBE->eType) {
            case DXF_LINE: {
                const DXFLineEntity * pE = (DXFLineEntity*)pBE;
                rBox.Union(pE->aP0);
                rBox.Union(pE->aP1);
                break;
            }
            case DXF_POINT: {
                const DXFPointEntity * pE = (DXFPointEntity*)pBE;
                rBox.Union(pE->aP0);
                break;
            }
            case DXF_CIRCLE: {
                const DXFCircleEntity * pE = (DXFCircleEntity*)pBE;
                DXFVector aP;
                aP=pE->aP0;
                aP.fx-=pE->fRadius;
                aP.fy-=pE->fRadius;
                rBox.Union(aP);
                aP=pE->aP0;
                aP.fx+=pE->fRadius;
                aP.fy+=pE->fRadius;
                rBox.Union(aP);
                break;
            }
            case DXF_ARC: {
                const DXFArcEntity * pE = (DXFArcEntity*)pBE;
                DXFVector aP;
                aP=pE->aP0;
                aP.fx-=pE->fRadius;
                aP.fy-=pE->fRadius;
                rBox.Union(aP);
                aP=pE->aP0;
                aP.fx+=pE->fRadius;
                aP.fy+=pE->fRadius;
                rBox.Union(aP);
                break;
            }
            case DXF_TRACE: {
                const DXFTraceEntity * pE = (DXFTraceEntity*)pBE;
                rBox.Union(pE->aP0);
                rBox.Union(pE->aP1);
                rBox.Union(pE->aP2);
                rBox.Union(pE->aP3);
                break;
            }
            case DXF_SOLID: {
                const DXFSolidEntity * pE = (DXFSolidEntity*)pBE;
                rBox.Union(pE->aP0);
                rBox.Union(pE->aP1);
                rBox.Union(pE->aP2);
                rBox.Union(pE->aP3);
                break;
            }
            case DXF_TEXT: {
                const DXFTextEntity * pE = (DXFTextEntity*)pBE;
                //???
                break;
            }
            case DXF_SHAPE: {
                const DXFShapeEntity * pE = (DXFShapeEntity*)pBE;
                //???
                break;
            }
            case DXF_INSERT: {
                const DXFInsertEntity * pE = (DXFInsertEntity*)pBE;
                DXFBlock * pB;
                DXFBoundingBox aBox;
                DXFVector aP;
                pB=aBlocks.Search(pE->sName);
                if (pB==NULL) break;
                CalcBoundingBox(*pB,aBox);
                if (aBox.bEmpty==TRUE) break;
                aP.fx=(aBox.fMinX-pB->aBasePoint.fx)*pE->fXScale+pE->aP0.fx;
                aP.fy=(aBox.fMinY-pB->aBasePoint.fy)*pE->fYScale+pE->aP0.fy;
                aP.fz=(aBox.fMinZ-pB->aBasePoint.fz)*pE->fZScale+pE->aP0.fz;
                rBox.Union(aP);
                aP.fx=(aBox.fMaxX-pB->aBasePoint.fx)*pE->fXScale+pE->aP0.fx;
                aP.fy=(aBox.fMaxY-pB->aBasePoint.fy)*pE->fYScale+pE->aP0.fy;
                aP.fz=(aBox.fMaxZ-pB->aBasePoint.fz)*pE->fZScale+pE->aP0.fz;
                rBox.Union(aP);
                break;
            }
            case DXF_ATTDEF: {
                const DXFAttDefEntity * pE = (DXFAttDefEntity*)pBE;
                //???
                break;
            }
            case DXF_ATTRIB: {
                const DXFAttribEntity * pE = (DXFAttribEntity*)pBE;
                //???
                break;
            }
            case DXF_VERTEX: {
                const DXFVertexEntity * pE = (DXFVertexEntity*)pBE;
                rBox.Union(pE->aP0);
                break;
            }
            case DXF_3DFACE: {
                const DXF3DFaceEntity * pE = (DXF3DFaceEntity*)pBE;
                rBox.Union(pE->aP0);
                rBox.Union(pE->aP1);
                rBox.Union(pE->aP2);
                rBox.Union(pE->aP3);
                break;
            }
            case DXF_DIMENSION: {
                const DXFDimensionEntity * pE = (DXFDimensionEntity*)pBE;
                DXFBlock * pB;
                DXFBoundingBox aBox;
                DXFVector aP;
                pB=aBlocks.Search(pE->sPseudoBlock);
                if (pB==NULL) break;
                CalcBoundingBox(*pB,aBox);
                if (aBox.bEmpty==TRUE) break;
                aP.fx=aBox.fMinX-pB->aBasePoint.fx;
                aP.fy=aBox.fMinY-pB->aBasePoint.fy;
                aP.fz=aBox.fMinZ-pB->aBasePoint.fz;
                rBox.Union(aP);
                aP.fx=aBox.fMaxX-pB->aBasePoint.fx;
                aP.fy=aBox.fMaxY-pB->aBasePoint.fy;
                aP.fz=aBox.fMaxZ-pB->aBasePoint.fz;
                rBox.Union(aP);
                break;
            }
        }
        pBE=pBE->pSucc;
    }
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dxfreprd.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:56:13 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _DXFREPRD_HXX
#define _DXFREPRD_HXX

#ifndef _DXFBLKRD_HXX
#include <dxfblkrd.hxx>
#endif

#ifndef _DXFTBLRD_HXX
#include <dxftblrd.hxx>
#endif

//----------------------------------------------------------------------------
//--------------------Nebensachen---------------------------------------------
//----------------------------------------------------------------------------

//-------------------Eine 3D-Min/Max-Box--------------------------------------

class DXFBoundingBox {
public:
    BOOL bEmpty;
    double fMinX;
    double fMinY;
    double fMinZ;
    double fMaxX;
    double fMaxY;
    double fMaxZ;

    DXFBoundingBox() { bEmpty=TRUE; }
    void Union(const DXFVector & rVector);
};

//-------------------Die (konstante) Palette fuer DXF-------------------------

class DXFPalette {

public:

    DXFPalette();
    ~DXFPalette();

    BYTE GetRed(BYTE nIndex) const;
    BYTE GetGreen(BYTE nIndex) const;
    BYTE GetBlue(BYTE nIndex) const;

private:
    BYTE * pRed;
    BYTE * pGreen;
    BYTE * pBlue;
    void SetColor(BYTE nIndex, BYTE nRed, BYTE nGreen, BYTE nBlue);
};

//----------------------------------------------------------------------------
//-----------------DXF Datei lesen und repraesentieren------------------------
//----------------------------------------------------------------------------

class DXFRepresentation {

public:

    DXFPalette aPalette;
        // Die immer gleiche DXF-Farb-Palette

    DXFBoundingBox aBoundingBox;
        // Ist gleich den AutoCAD-Variablen EXTMIN, EXTMAX sofern in DXF-Datei
        // vorhanden, anderenfalls wird die BoundingBox berechnet (in Read()).

    DXFTables aTables;
        // Die Tabellen der DXF-Datei

    DXFBlocks aBlocks;
        // Die Bloecke der DXF-Datei

    DXFEntities aEntities;
        // Die Entities (aus der Entities-Section) der DXF-Datei

    rtl_TextEncoding mEnc;

    DXFRepresentation();
    ~DXFRepresentation();

        rtl_TextEncoding getTextEncoding() const;
        void setTextEncoding(rtl_TextEncoding aEnc);

    BOOL Read(SvStream & rIStream,
              PFilterCallback pCallback, void * pCallerData,
              USHORT nMinPercent, USHORT nMaxPercent);
        // Liesst die komplette DXF-Datei ein.

private:

    void ReadHeader(DXFGroupReader & rDGR);
    void CalcBoundingBox(const DXFEntities & rEntities,
                         DXFBoundingBox & rBox);
};

//----------------------------------------------------------------------------
//-------------------inlines--------------------------------------------------
//----------------------------------------------------------------------------

inline BYTE DXFPalette::GetRed(BYTE nIndex) const { return pRed[nIndex]; }
inline BYTE DXFPalette::GetGreen(BYTE nIndex) const { return pGreen[nIndex]; }
inline BYTE DXFPalette::GetBlue(BYTE nIndex) const { return pBlue[nIndex]; }
inline rtl_TextEncoding DXFRepresentation::getTextEncoding() const { return mEnc; }
inline void DXFRepresentation::setTextEncoding(rtl_TextEncoding aEnc) { mEnc = aEnc; }

#endif

<commit_msg>INTEGRATION: CWS aw024 (1.2.76); FILE MERGED 2005/09/20 04:43:24 aw 1.2.76.2: RESYNC: (1.2-1.3); FILE MERGED 2005/08/04 14:47:08 sj 1.2.76.1: #48467# using GraphicExporter component for exports, graphic filter progress now works now via xStatusIndicater instead of callback mechanism<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dxfreprd.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: ihi $ $Date: 2006-11-14 16:14:46 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _DXFREPRD_HXX
#define _DXFREPRD_HXX

#ifndef _DXFBLKRD_HXX
#include <dxfblkrd.hxx>
#endif

#ifndef _DXFTBLRD_HXX
#include <dxftblrd.hxx>
#endif

//----------------------------------------------------------------------------
//--------------------Nebensachen---------------------------------------------
//----------------------------------------------------------------------------

//-------------------Eine 3D-Min/Max-Box--------------------------------------

class DXFBoundingBox {
public:
    BOOL bEmpty;
    double fMinX;
    double fMinY;
    double fMinZ;
    double fMaxX;
    double fMaxY;
    double fMaxZ;

    DXFBoundingBox() { bEmpty=TRUE; }
    void Union(const DXFVector & rVector);
};

//-------------------Die (konstante) Palette fuer DXF-------------------------

class DXFPalette {

public:

    DXFPalette();
    ~DXFPalette();

    BYTE GetRed(BYTE nIndex) const;
    BYTE GetGreen(BYTE nIndex) const;
    BYTE GetBlue(BYTE nIndex) const;

private:
    BYTE * pRed;
    BYTE * pGreen;
    BYTE * pBlue;
    void SetColor(BYTE nIndex, BYTE nRed, BYTE nGreen, BYTE nBlue);
};

//----------------------------------------------------------------------------
//-----------------DXF Datei lesen und repraesentieren------------------------
//----------------------------------------------------------------------------

class DXFRepresentation {

public:

    DXFPalette aPalette;
        // Die immer gleiche DXF-Farb-Palette

    DXFBoundingBox aBoundingBox;
        // Ist gleich den AutoCAD-Variablen EXTMIN, EXTMAX sofern in DXF-Datei
        // vorhanden, anderenfalls wird die BoundingBox berechnet (in Read()).

    DXFTables aTables;
        // Die Tabellen der DXF-Datei

    DXFBlocks aBlocks;
        // Die Bloecke der DXF-Datei

    DXFEntities aEntities;
        // Die Entities (aus der Entities-Section) der DXF-Datei

    rtl_TextEncoding mEnc;

    DXFRepresentation();
    ~DXFRepresentation();

        rtl_TextEncoding getTextEncoding() const;
        void setTextEncoding(rtl_TextEncoding aEnc);

    BOOL Read( SvStream & rIStream, USHORT nMinPercent, USHORT nMaxPercent);
        // Liesst die komplette DXF-Datei ein.

private:

    void ReadHeader(DXFGroupReader & rDGR);
    void CalcBoundingBox(const DXFEntities & rEntities,
                         DXFBoundingBox & rBox);
};

//----------------------------------------------------------------------------
//-------------------inlines--------------------------------------------------
//----------------------------------------------------------------------------

inline BYTE DXFPalette::GetRed(BYTE nIndex) const { return pRed[nIndex]; }
inline BYTE DXFPalette::GetGreen(BYTE nIndex) const { return pGreen[nIndex]; }
inline BYTE DXFPalette::GetBlue(BYTE nIndex) const { return pBlue[nIndex]; }
inline rtl_TextEncoding DXFRepresentation::getTextEncoding() const { return mEnc; }
inline void DXFRepresentation::setTextEncoding(rtl_TextEncoding aEnc) { mEnc = aEnc; }

#endif

<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "base/test_file_util.h"
#include "base/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"

using base::TimeDelta;
using base::TimeTicks;

namespace {

class StartupTest : public UITest {
 public:
  StartupTest() {
    show_window_ = true;
    pages_ = "about:blank";
  }
  void SetUp() {}
  void TearDown() {}

  // Load a file on startup rather than about:blank.  This tests a longer
  // startup path, including resource loading and the loading of gears.dll.
  void SetUpWithFileURL() {
    FilePath file_url;
    ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &file_url));
    file_url = file_url.AppendASCII("empty.html");
    ASSERT_TRUE(file_util::PathExists(file_url));
    launch_arguments_.AppendLooseValue(file_url.ToWStringHack());

    pages_ = WideToUTF8(file_url.ToWStringHack());
  }

  // Use the given profile in the test data extensions/profiles dir.  This tests
  // startup with extensions installed.
  void SetUpWithExtensionsProfile(const char* profile) {
    FilePath data_dir;
    PathService::Get(chrome::DIR_TEST_DATA, &data_dir);
    data_dir = data_dir.AppendASCII("extensions").AppendASCII("profiles").
        AppendASCII(profile);
    set_template_user_data(data_dir.ToWStringHack());
  }

  void RunStartupTest(const char* graph, const char* trace,
      bool test_cold, bool important, int profile_type) {
    profile_type_ = profile_type;

    // Sets the profile data for the run.  For now, this is only used for
    // the non-default themes test.
    if (profile_type != UITest::DEFAULT_THEME) {
      set_template_user_data(UITest::ComputeTypicalUserDataSource(
          profile_type).ToWStringHack());
    }

    const int kNumCyclesMax = 20;
    int numCycles = kNumCyclesMax;
// It's ok for unit test code to use getenv(), isn't it?
#if defined(OS_WIN)
#pragma warning( disable : 4996 )
#endif
    const char* numCyclesEnv = getenv("STARTUP_TESTS_NUMCYCLES");
    if (numCyclesEnv && StringToInt(numCyclesEnv, &numCycles))
      LOG(INFO) << "STARTUP_TESTS_NUMCYCLES set in environment, "
                << "so setting numCycles to " << numCycles;

    TimeDelta timings[kNumCyclesMax];
    for (int i = 0; i < numCycles; ++i) {
      if (test_cold) {
        FilePath dir_app;
        ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir_app));

        FilePath chrome_exe(dir_app.Append(
            FilePath::FromWStringHack(chrome::kBrowserProcessExecutablePath)));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_exe));
#if defined(OS_WIN)
        // chrome.dll is windows specific.
        FilePath chrome_dll(dir_app.Append(FILE_PATH_LITERAL("chrome.dll")));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_dll));
#endif

#if defined(OS_WIN)
        // TODO(port): Re-enable once gears is working on mac/linux.
        FilePath gears_dll;
        ASSERT_TRUE(PathService::Get(chrome::FILE_GEARS_PLUGIN, &gears_dll));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(gears_dll));
#else
        NOTIMPLEMENTED() << "gears not enabled yet";
#endif
      }
      UITest::SetUp();
      TimeTicks end_time = TimeTicks::Now();
      timings[i] = end_time - browser_launch_time_;
      // TODO(beng): Can't shut down so quickly. Figure out why, and fix. If we
      // do, we crash.
      PlatformThread::Sleep(50);
      UITest::TearDown();

      if (i == 0) {
        // Re-use the profile data after first run so that the noise from
        // creating databases doesn't impact all the runs.
        clear_profile_ = false;
        // Clear template_user_data_ so we don't try to copy it over each time
        // through.
        set_template_user_data(L"");
      }
    }

    std::string times;
    for (int i = 0; i < numCycles; ++i)
      StringAppendF(&times, "%.2f,", timings[i].InMillisecondsF());
    PrintResultList(graph, "", trace, times, "ms", important);
  }

 protected:
  std::string pages_;
};

class StartupReferenceTest : public StartupTest {
 public:
  // override the browser directory that is used by UITest::SetUp to cause it
  // to use the reference build instead.
  void SetUp() {
    FilePath dir;
    PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
    dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
    dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
    dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
    dir = dir.AppendASCII("chrome_mac");
#endif
    browser_directory_ = dir;
  }
};

TEST_F(StartupTest, Perf) {
  RunStartupTest("warm", "t", false /* not cold */, true /* important */,
                 UITest::DEFAULT_THEME);
}

// TODO(port): We need a mac reference build checked in for this.
TEST_F(StartupReferenceTest, Perf) {
  RunStartupTest("warm", "t_ref", false /* not cold */,
                 true /* important */, UITest::DEFAULT_THEME);
}

// TODO(mpcomplete): Should we have reference timings for all these?

TEST_F(StartupTest, PerfCold) {
  RunStartupTest("cold", "t", true /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

#if defined(OS_MACOSX)
// TODO(mpcomplete): running these tests on a mac builder results in leaked
// chrome processes, causing the build slave to hang.
// http://code.google.com/p/chromium/issues/detail?id=22287
#else
TEST_F(StartupTest, PerfExtensionEmpty) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("empty");
  RunStartupTest("warm", "t", false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}
x

TEST_F(StartupTest, PerfExtensionToolstrips1) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("toolstrips1");
  RunStartupTest("warm", "extension_toolstrip1",
                 false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfExtensionToolstrips50) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("toolstrips50");
  RunStartupTest("warm", "extension_toolstrip50",
                 false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfExtensionContentScript1) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("content_scripts1");
  RunStartupTest("warm", "extension_content_scripts1",
                 false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfExtensionContentScript50) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("content_scripts50");
  RunStartupTest("warm", "extension_content_scripts50",
                 false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}
#endif

#if defined(OS_WIN)
// TODO(port): Enable gears tests on linux/mac once gears is working.
TEST_F(StartupTest, PerfGears) {
  SetUpWithFileURL();
  RunStartupTest("warm", "gears", false /* not cold */,
                 false /* not important */, UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfColdGears) {
  SetUpWithFileURL();
  RunStartupTest("cold", "gears", true /* cold */,
                 false /* not important */, UITest::DEFAULT_THEME);
}
#endif

TEST_F(StartupTest, PerfColdComplexTheme) {
  RunStartupTest("warm", "t-theme", false /* warm */,
                 false /* not important */, UITest::COMPLEX_THEME);
}

#if defined(OS_LINUX)
TEST_F(StartupTest, PerfColdGtkTheme) {
  RunStartupTest("warm", "gtk-theme", false /* warm */,
                 false /* not important */, UITest::NATIVE_THEME);
}

TEST_F(StartupTest, PrefColdNativeFrame) {
  RunStartupTest("warm", "custom-frame", false /* warm */,
                 false /* not important */, UITest::CUSTOM_FRAME);
}

TEST_F(StartupTest, PerfColdNativeFrameGtkTheme) {
  RunStartupTest("warm", "custom-frame-gtk-theme", false /* warm */,
                 false /* not important */, UITest::CUSTOM_FRAME_NATIVE_THEME);
}
#endif

}  // namespace
<commit_msg>Last checkin contained a typo. Fixing.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "base/test_file_util.h"
#include "base/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"

using base::TimeDelta;
using base::TimeTicks;

namespace {

class StartupTest : public UITest {
 public:
  StartupTest() {
    show_window_ = true;
    pages_ = "about:blank";
  }
  void SetUp() {}
  void TearDown() {}

  // Load a file on startup rather than about:blank.  This tests a longer
  // startup path, including resource loading and the loading of gears.dll.
  void SetUpWithFileURL() {
    FilePath file_url;
    ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &file_url));
    file_url = file_url.AppendASCII("empty.html");
    ASSERT_TRUE(file_util::PathExists(file_url));
    launch_arguments_.AppendLooseValue(file_url.ToWStringHack());

    pages_ = WideToUTF8(file_url.ToWStringHack());
  }

  // Use the given profile in the test data extensions/profiles dir.  This tests
  // startup with extensions installed.
  void SetUpWithExtensionsProfile(const char* profile) {
    FilePath data_dir;
    PathService::Get(chrome::DIR_TEST_DATA, &data_dir);
    data_dir = data_dir.AppendASCII("extensions").AppendASCII("profiles").
        AppendASCII(profile);
    set_template_user_data(data_dir.ToWStringHack());
  }

  void RunStartupTest(const char* graph, const char* trace,
      bool test_cold, bool important, int profile_type) {
    profile_type_ = profile_type;

    // Sets the profile data for the run.  For now, this is only used for
    // the non-default themes test.
    if (profile_type != UITest::DEFAULT_THEME) {
      set_template_user_data(UITest::ComputeTypicalUserDataSource(
          profile_type).ToWStringHack());
    }

    const int kNumCyclesMax = 20;
    int numCycles = kNumCyclesMax;
// It's ok for unit test code to use getenv(), isn't it?
#if defined(OS_WIN)
#pragma warning( disable : 4996 )
#endif
    const char* numCyclesEnv = getenv("STARTUP_TESTS_NUMCYCLES");
    if (numCyclesEnv && StringToInt(numCyclesEnv, &numCycles))
      LOG(INFO) << "STARTUP_TESTS_NUMCYCLES set in environment, "
                << "so setting numCycles to " << numCycles;

    TimeDelta timings[kNumCyclesMax];
    for (int i = 0; i < numCycles; ++i) {
      if (test_cold) {
        FilePath dir_app;
        ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir_app));

        FilePath chrome_exe(dir_app.Append(
            FilePath::FromWStringHack(chrome::kBrowserProcessExecutablePath)));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_exe));
#if defined(OS_WIN)
        // chrome.dll is windows specific.
        FilePath chrome_dll(dir_app.Append(FILE_PATH_LITERAL("chrome.dll")));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_dll));
#endif

#if defined(OS_WIN)
        // TODO(port): Re-enable once gears is working on mac/linux.
        FilePath gears_dll;
        ASSERT_TRUE(PathService::Get(chrome::FILE_GEARS_PLUGIN, &gears_dll));
        ASSERT_TRUE(EvictFileFromSystemCacheWrapper(gears_dll));
#else
        NOTIMPLEMENTED() << "gears not enabled yet";
#endif
      }
      UITest::SetUp();
      TimeTicks end_time = TimeTicks::Now();
      timings[i] = end_time - browser_launch_time_;
      // TODO(beng): Can't shut down so quickly. Figure out why, and fix. If we
      // do, we crash.
      PlatformThread::Sleep(50);
      UITest::TearDown();

      if (i == 0) {
        // Re-use the profile data after first run so that the noise from
        // creating databases doesn't impact all the runs.
        clear_profile_ = false;
        // Clear template_user_data_ so we don't try to copy it over each time
        // through.
        set_template_user_data(L"");
      }
    }

    std::string times;
    for (int i = 0; i < numCycles; ++i)
      StringAppendF(&times, "%.2f,", timings[i].InMillisecondsF());
    PrintResultList(graph, "", trace, times, "ms", important);
  }

 protected:
  std::string pages_;
};

class StartupReferenceTest : public StartupTest {
 public:
  // override the browser directory that is used by UITest::SetUp to cause it
  // to use the reference build instead.
  void SetUp() {
    FilePath dir;
    PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
    dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
    dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
    dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
    dir = dir.AppendASCII("chrome_mac");
#endif
    browser_directory_ = dir;
  }
};

TEST_F(StartupTest, Perf) {
  RunStartupTest("warm", "t", false /* not cold */, true /* important */,
                 UITest::DEFAULT_THEME);
}

// TODO(port): We need a mac reference build checked in for this.
TEST_F(StartupReferenceTest, Perf) {
  RunStartupTest("warm", "t_ref", false /* not cold */,
                 true /* important */, UITest::DEFAULT_THEME);
}

// TODO(mpcomplete): Should we have reference timings for all these?

TEST_F(StartupTest, PerfCold) {
  RunStartupTest("cold", "t", true /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

#if defined(OS_MACOSX)
// TODO(mpcomplete): running these tests on a mac builder results in leaked
// chrome processes, causing the build slave to hang.
// http://code.google.com/p/chromium/issues/detail?id=22287
#else
TEST_F(StartupTest, PerfExtensionEmpty) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("empty");
  RunStartupTest("warm", "t", false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfExtensionToolstrips1) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("toolstrips1");
  RunStartupTest("warm", "extension_toolstrip1",
                 false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfExtensionToolstrips50) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("toolstrips50");
  RunStartupTest("warm", "extension_toolstrip50",
                 false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfExtensionContentScript1) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("content_scripts1");
  RunStartupTest("warm", "extension_content_scripts1",
                 false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfExtensionContentScript50) {
  SetUpWithFileURL();
  SetUpWithExtensionsProfile("content_scripts50");
  RunStartupTest("warm", "extension_content_scripts50",
                 false /* cold */, false /* not important */,
                 UITest::DEFAULT_THEME);
}
#endif

#if defined(OS_WIN)
// TODO(port): Enable gears tests on linux/mac once gears is working.
TEST_F(StartupTest, PerfGears) {
  SetUpWithFileURL();
  RunStartupTest("warm", "gears", false /* not cold */,
                 false /* not important */, UITest::DEFAULT_THEME);
}

TEST_F(StartupTest, PerfColdGears) {
  SetUpWithFileURL();
  RunStartupTest("cold", "gears", true /* cold */,
                 false /* not important */, UITest::DEFAULT_THEME);
}
#endif

TEST_F(StartupTest, PerfColdComplexTheme) {
  RunStartupTest("warm", "t-theme", false /* warm */,
                 false /* not important */, UITest::COMPLEX_THEME);
}

#if defined(OS_LINUX)
TEST_F(StartupTest, PerfColdGtkTheme) {
  RunStartupTest("warm", "gtk-theme", false /* warm */,
                 false /* not important */, UITest::NATIVE_THEME);
}

TEST_F(StartupTest, PrefColdNativeFrame) {
  RunStartupTest("warm", "custom-frame", false /* warm */,
                 false /* not important */, UITest::CUSTOM_FRAME);
}

TEST_F(StartupTest, PerfColdNativeFrameGtkTheme) {
  RunStartupTest("warm", "custom-frame-gtk-theme", false /* warm */,
                 false /* not important */, UITest::CUSTOM_FRAME_NATIVE_THEME);
}
#endif

}  // namespace
<|endoftext|>


<commit_before>#include <gtest/gtest.h>

#include "gisfacisa.h"

#include <iostream>
#include "agent_tests.h"
#include "context.h"
#include "facility_tests.h"

using cyclus::GISFacisa;

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class GISFacisaTest : public ::testing::Test {
 protected:
  cyclus::TestContext tc_;
  GISFacisa* facility_a_;
  GISFacisa* facility_b_;

  virtual void SetUp() {
    facility_a_ = new GISFacisa(tc_.get());
    facility_b_ = new GISFacisa(tc_.get());
  }

  virtual void TearDown() {
    delete facility_a_;
    delete facility_b_;
  }
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(GISFacisaTest, set_longitude) {
  facility_a_->set_longitude(46.545821);
  EXPECT_NEAR(facility_a_->get_longitude(), 46.545821, 32.5 * 0.01);
  facility_a_->set_longitude(-82.5546);
  EXPECT_NEAR(facility_a_->get_longitude(), -82.5546, 82.5546 * 0.01);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(GISFacisaTest, set_latitude) {
  facility_a_->set_latitude(32.5);
  EXPECT_NEAR(facility_a_->get_latitude(), 32.5, 32.5 * 0.01);
  facility_a_->set_latitude(-2.5546);
  EXPECT_NEAR(facility_a_->get_latitude(), -2.5546, 2.5546 * 0.01);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(GISFacisaTest, InitialState) {
  // Test things about the initial state of the facility here
  EXPECT_NEAR(facility_a_->get_longitude(), 0, 0.001);
  EXPECT_NEAR(facility_a_->get_latitude(), 0, 0.001);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(GISFacisaTest, Constructor) {
  facility_a_->set_latitude(48.858222);
  facility_a_->set_longitude(2.2945);
  EXPECT_NEAR(facility_a_->get_latitude(), 48.858222, 48.858222 * 0.01);
  EXPECT_NEAR(facility_a_->get_longitude(), 2.2945, 2.2945 * 0.01);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(GISFacisaTest, Distance) {
  EXPECT_NEAR(facility_a_->Distance(*(facility_b_)), 0, 0.0001);
  facility_a_->set_latitude(48.858222);
  facility_a_->set_longitude(2.2945);
  facility_b_->set_latitude(52.37305);
  facility_b_->set_longitude(4.892222);
  EXPECT_NEAR(facility_a_->Distance(*(facility_b_)), 432.126, 432.126 * 0.01);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cyclus::Agent* GISFacisaConstructor(cyclus::Context* ctx) {
  return new GISFacisa(ctx);
}

// Required to get functionality in cyclus agent unit tests library
#ifndef CYCLUS_AGENT_TESTS_CONNECTED
int ConnectAgentTests();
static int cyclus_agent_tests_connected = ConnectAgentTests();
#define CYCLUS_AGENT_TESTS_CONNECTED cyclus_agent_tests_connected
#endif  // CYCLUS_AGENT_TESTS_CONNECTED

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
INSTANTIATE_TEST_CASE_P(GISFacisaFac, FacilityTests,
                        ::testing::Values(&GISFacisaConstructor));

INSTANTIATE_TEST_CASE_P(GISFacisaFac, AgentTests,
                        ::testing::Values(&GISFacisaConstructor));
<commit_msg>Initial edit of gisfac_tests to include gisfac class in tests<commit_after>#include <gtest/gtest.h>

#include "tests/test_agents/gisfac.h"

#include <iostream>
#include "agent_tests.h"
#include "context.h"
#include "facility_tests.h"

using cyclus::GISFacisa;

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class GISFacisaTest : public ::testing::Test {
 protected:
  cyclus::TestContext tc_;
  GISFacisa* facility_a_;
  GISFacisa* facility_b_;

  virtual void SetUp() {
    facility_a_ = new GISFacisa(tc_.get());
    facility_b_ = new GISFacisa(tc_.get());
  }

  virtual void TearDown() {
    delete facility_a_;
    delete facility_b_;
  }
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(GISFacisaTest, set_longitude) {
  facility_a_->set_longitude(46.545821);
  EXPECT_NEAR(facility_a_->get_longitude(), 46.545821, 32.5 * 0.01);
  facility_a_->set_longitude(-82.5546);
  EXPECT_NEAR(facility_a_->get_longitude(), -82.5546, 82.5546 * 0.01);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(GISFacisaTest, set_latitude) {
  facility_a_->set_latitude(32.5);
  EXPECT_NEAR(facility_a_->get_latitude(), 32.5, 32.5 * 0.01);
  facility_a_->set_latitude(-2.5546);
  EXPECT_NEAR(facility_a_->get_latitude(), -2.5546, 2.5546 * 0.01);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(GISFacisaTest, InitialState) {
  // Test things about the initial state of the facility here
  EXPECT_NEAR(facility_a_->get_longitude(), 0, 0.001);
  EXPECT_NEAR(facility_a_->get_latitude(), 0, 0.001);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(GISFacisaTest, Constructor) {
  facility_a_->set_latitude(48.858222);
  facility_a_->set_longitude(2.2945);
  EXPECT_NEAR(facility_a_->get_latitude(), 48.858222, 48.858222 * 0.01);
  EXPECT_NEAR(facility_a_->get_longitude(), 2.2945, 2.2945 * 0.01);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(GISFacisaTest, Distance) {
  EXPECT_NEAR(facility_a_->Distance(*(facility_b_)), 0, 0.0001);
  facility_a_->set_latitude(48.858222);
  facility_a_->set_longitude(2.2945);
  facility_b_->set_latitude(52.37305);
  facility_b_->set_longitude(4.892222);
  EXPECT_NEAR(facility_a_->Distance(*(facility_b_)), 432.126, 432.126 * 0.01);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cyclus::Agent* GISFacisaConstructor(cyclus::Context* ctx) {
  return new GISFacisa(ctx);
}

// Required to get functionality in cyclus agent unit tests library
#ifndef CYCLUS_AGENT_TESTS_CONNECTED
int ConnectAgentTests();
static int cyclus_agent_tests_connected = ConnectAgentTests();
#define CYCLUS_AGENT_TESTS_CONNECTED cyclus_agent_tests_connected
#endif  // CYCLUS_AGENT_TESTS_CONNECTED

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
INSTANTIATE_TEST_CASE_P(GISFacisaFac, FacilityTests,
                        ::testing::Values(&GISFacisaConstructor));

INSTANTIATE_TEST_CASE_P(GISFacisaFac, AgentTests,
                        ::testing::Values(&GISFacisaConstructor));
<|endoftext|>