<commit_before>/**
 *  @file
 *  @author     2012 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de)
 *  @copyright  Simplified BSD
 *
 *  @cond
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the FreeBSD license as published by the FreeBSD
 *  project.
 *
 *  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.
 *
 *  You should have received a copy of the FreeBSD license along with this
 *  program. If not, see <http://www.opensource.org/licenses/bsd-license>.
 *  @endcond
 */

#include "umundo/connection/zeromq/ZeroMQNode.h"

#include "umundo/connection/Publisher.h"
#include "umundo/common/Message.h"
#include "umundo/common/UUID.h"

// include order matters with MSVC ...
#include "umundo/connection/zeromq/ZeroMQSubscriber.h"

#include "umundo/config.h"
#if defined UNIX || defined IOS || defined IOSSIM
#include <stdio.h> // snprintf
#endif

namespace umundo {

shared_ptr<Implementation> ZeroMQSubscriber::create(void*) {
	shared_ptr<Implementation> instance(new ZeroMQSubscriber());
	return instance;
}

void ZeroMQSubscriber::destroy() {
	delete(this);
}

ZeroMQSubscriber::ZeroMQSubscriber() {
}

ZeroMQSubscriber::~ZeroMQSubscriber() {
	LOG_INFO("deleting subscriber for %s", _channelName.c_str());
	join();
	zmq_close(_closer) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
	zmq_close(_socket) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
}

void ZeroMQSubscriber::init(shared_ptr<Configuration> config) {
	_config = boost::static_pointer_cast<SubscriberConfig>(config);
	_uuid = (_uuid.length() > 0 ? _uuid : UUID::getUUID());
	assert(_uuid.length() == 36);

	void* ctx = ZeroMQNode::getZeroMQContext();
	(_socket = zmq_socket(ctx, ZMQ_SUB)) || LOG_WARN("zmq_socket: %s",zmq_strerror(errno));
	(_closer = zmq_socket(ctx, ZMQ_PUB)) || LOG_WARN("zmq_socket: %s",zmq_strerror(errno));

	assert(_channelName.size() > 0);
	int hwm = NET_ZEROMQ_RCV_HWM;
	zmq_setsockopt(_socket, ZMQ_RCVHWM, &hwm, sizeof(hwm)) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
	zmq_setsockopt(_socket, ZMQ_IDENTITY, _uuid.c_str(), _uuid.length()) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
	zmq_setsockopt(_socket, ZMQ_SUBSCRIBE, _channelName.c_str(), _channelName.size()) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
	LOG_DEBUG("Subscribing to %s", _channelName.c_str());
	zmq_setsockopt(_socket, ZMQ_SUBSCRIBE, _uuid.c_str(), _uuid.size()) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
	LOG_DEBUG("Subscribing to %s", SHORT_UUID(_uuid).c_str());

	// reconnection intervals
	int reconnect_ivl_min = 100;
	int reconnect_ivl_max = 200;
	zmq_setsockopt (_socket, ZMQ_RECONNECT_IVL, &reconnect_ivl_min, sizeof(int)) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
	zmq_setsockopt (_socket, ZMQ_RECONNECT_IVL_MAX, &reconnect_ivl_max, sizeof(int)) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));

	// make sure we can close the socket later
	std::stringstream ss;
	ss << "inproc://" << _uuid;
	zmq_bind(_closer, ss.str().c_str()) && LOG_WARN("zmq_bind: %s",zmq_strerror(errno));
	zmq_connect(_socket, ss.str().c_str()) && LOG_WARN("zmq_connect: %s",zmq_strerror(errno));

	LOG_INFO("creating subscriber for %s", _channelName.c_str());
	start();
}

/**
 * Break blocking zmq_recvmsg in ZeroMQSubscriber::run.
 */
void ZeroMQSubscriber::join() {
	UMUNDO_LOCK(_mutex);
	stop();

	// this is a hack .. the thread is blocking at zmq_recvmsg - unblock by sending a message
	zmq_msg_t channelEnvlp;
	ZMQ_PREPARE_STRING(channelEnvlp, _channelName.c_str(), _channelName.size());

	zmq_sendmsg(_closer, &channelEnvlp, 0) >= 0 || LOG_WARN("zmq_sendmsg: %s",zmq_strerror(errno));
	zmq_msg_close(&channelEnvlp) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));

	Thread::join();
	UMUNDO_UNLOCK(_mutex);
}

void ZeroMQSubscriber::suspend() {
	UMUNDO_LOCK(_mutex);
	if (_isSuspended) {
		UMUNDO_UNLOCK(_mutex);
		return;
	}
	_isSuspended = true;
	stop();
	join();

	_connections.clear();
	zmq_close(_closer) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
	zmq_close(_socket) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));

	UMUNDO_UNLOCK(_mutex);
}

void ZeroMQSubscriber::resume() {
	UMUNDO_LOCK(_mutex);
	if (!_isSuspended) {
		UMUNDO_UNLOCK(_mutex);
		return;
	}
	_isSuspended = false;
	init(_config);

	UMUNDO_UNLOCK(_mutex);
}

void ZeroMQSubscriber::run() {
	int32_t more;
	size_t more_size = sizeof(more);

	zmq_pollitem_t pollItem;
	pollItem.socket = _socket;
	pollItem.events = ZMQ_POLLIN | ZMQ_POLLOUT;

	while(isStarted()) {
		int rc = 0;
		{
			ScopeLock lock(&_mutex);
			zmq_poll(&pollItem, 1, 30);
		}
		if (rc < 0) {
			// an error occurred
			switch(rc) {
				case ETERM:
					LOG_WARN("zmq_poll called with terminated socket");
					break;
				case EFAULT:
					LOG_WARN("zmq_poll called with invalid items");
					break;
				case EINTR:
				default:
					break;
			}

		} else if (rc == 0) {
			// Nothing to read - released lock
			Thread::yield();
//			Thread::sleepMs(5);

		} if (rc > 0) {
			// there is a message to be read
			ScopeLock lock(&_mutex);
			Message* msg = new Message();
			while (1) {
			// read and dispatch the whole message
				zmq_msg_t message;
				zmq_msg_init(&message) && LOG_WARN("zmq_msg_init: %s",zmq_strerror(errno));

				while (zmq_recvmsg(_socket, &message, 0) < 0)
					if (errno != EINTR)
						LOG_WARN("zmq_recvmsg: %s",zmq_strerror(errno));

				size_t msgSize = zmq_msg_size(&message);

				if (!isStarted()) {
					zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
					return;
				}

				// last message contains actual data
				zmq_getsockopt(_socket, ZMQ_RCVMORE, &more, &more_size) && LOG_WARN("zmq_getsockopt: %s",zmq_strerror(errno));

				if (more) {
					char* key = (char*)zmq_msg_data(&message);
					char* value = ((char*)zmq_msg_data(&message) + strlen(key) + 1);

					// is this the first message with the channelname?
					if (strlen(key) + 1 == msgSize &&
					        msg->getMeta().find(key) == msg->getMeta().end()) {
						msg->putMeta("channel", key);
					} else {
						assert(strlen(key) + strlen(value) + 2 == msgSize);
						if (strlen(key) + strlen(value) + 2 != msgSize) {
							LOG_WARN("Received malformed message %d + %d + 2 != %d", strlen(key), strlen(value), msgSize);
							zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
							break;
						} else {
							msg->putMeta(key, value);
						}
					}
					zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
				} else {
					msg->setData((char*)zmq_msg_data(&message), msgSize);
					zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));

					if (_receiver != NULL) {
						_receiver->receive(msg);
						delete(msg);
					} else {
						ScopeLock lock(&_msgMutex);
						_msgQueue.push_back(msg);
					}
					break; // last message part
				}
			}
		}
	}
}

Message* ZeroMQSubscriber::getNextMsg() {
  if (_receiver != NULL) {
    LOG_WARN("getNextMsg not functional when a receiver is given");
    return NULL;
  }

	ScopeLock lock(&_msgMutex);
	Message* msg = NULL;
	if (_msgQueue.size() > 0) {
		msg = _msgQueue.front();
		_msgQueue.pop_front();
	}
	return msg;
}

Message* ZeroMQSubscriber::peekNextMsg() {
  if (_receiver != NULL) {
    LOG_WARN("peekNextMsg not functional when a receiver is given");
    return NULL;
  }

	ScopeLock lock(&_msgMutex);
	Message* msg = NULL;
	if (_msgQueue.size() > 0) {
		msg = _msgQueue.front();
	}
	return msg;
}

void ZeroMQSubscriber::added(shared_ptr<PublisherStub> pub) {
	std::stringstream ss;
	if (pub->isInProcess() && false) {
		ss << "inproc://" << pub->getUUID();
	} else {
		ss << pub->getTransport() << "://" << pub->getIP() << ":" << pub->getPort();
	}
	if (_connections.find(ss.str()) != _connections.end()) {
		LOG_INFO("Already connected to %s", ss.str().c_str());
		return;
	}

	ScopeLock lock(&_mutex);
	LOG_INFO("%s subscribing at %s", _channelName.c_str(), ss.str().c_str());
	zmq_connect(_socket, ss.str().c_str()) && LOG_WARN("zmq_connect: %s", zmq_strerror(errno));
	_connections.insert(ss.str());
}

void ZeroMQSubscriber::removed(shared_ptr<PublisherStub> pub) {
	ScopeLock lock(&_mutex);
	std::stringstream ss;
	if (pub->isInProcess() && false) {
		ss << "inproc://" << pub->getUUID();
	} else {
		ss << pub->getTransport() << "://" << pub->getIP() << ":" << pub->getPort();
	}
	if (_connections.find(ss.str()) == _connections.end()) {
		LOG_INFO("Never connected to %s won't disconnect", ss.str().c_str());
		return;
	}

	LOG_DEBUG("unsubscribing from %s", ss.str().c_str());
	zmq_connect(_socket, ss.str().c_str()) && LOG_WARN("zmq_disconnect: %s", zmq_strerror(errno));
	_connections.erase(ss.str());
}

void ZeroMQSubscriber::changed(shared_ptr<PublisherStub>) {
	// never called
}

}<commit_msg>Forgot to assign return value<commit_after>/**
 *  @file
 *  @author     2012 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de)
 *  @copyright  Simplified BSD
 *
 *  @cond
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the FreeBSD license as published by the FreeBSD
 *  project.
 *
 *  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.
 *
 *  You should have received a copy of the FreeBSD license along with this
 *  program. If not, see <http://www.opensource.org/licenses/bsd-license>.
 *  @endcond
 */

#include "umundo/connection/zeromq/ZeroMQNode.h"

#include "umundo/connection/Publisher.h"
#include "umundo/common/Message.h"
#include "umundo/common/UUID.h"

// include order matters with MSVC ...
#include "umundo/connection/zeromq/ZeroMQSubscriber.h"

#include "umundo/config.h"
#if defined UNIX || defined IOS || defined IOSSIM
#include <stdio.h> // snprintf
#endif

namespace umundo {

shared_ptr<Implementation> ZeroMQSubscriber::create(void*) {
	shared_ptr<Implementation> instance(new ZeroMQSubscriber());
	return instance;
}

void ZeroMQSubscriber::destroy() {
	delete(this);
}

ZeroMQSubscriber::ZeroMQSubscriber() {
}

ZeroMQSubscriber::~ZeroMQSubscriber() {
	LOG_INFO("deleting subscriber for %s", _channelName.c_str());
	join();
	zmq_close(_closer) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
	zmq_close(_socket) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
}

void ZeroMQSubscriber::init(shared_ptr<Configuration> config) {
	_config = boost::static_pointer_cast<SubscriberConfig>(config);
	_uuid = (_uuid.length() > 0 ? _uuid : UUID::getUUID());
	assert(_uuid.length() == 36);

	void* ctx = ZeroMQNode::getZeroMQContext();
	(_socket = zmq_socket(ctx, ZMQ_SUB)) || LOG_WARN("zmq_socket: %s",zmq_strerror(errno));
	(_closer = zmq_socket(ctx, ZMQ_PUB)) || LOG_WARN("zmq_socket: %s",zmq_strerror(errno));

	assert(_channelName.size() > 0);
	int hwm = NET_ZEROMQ_RCV_HWM;
	zmq_setsockopt(_socket, ZMQ_RCVHWM, &hwm, sizeof(hwm)) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
	zmq_setsockopt(_socket, ZMQ_IDENTITY, _uuid.c_str(), _uuid.length()) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
	zmq_setsockopt(_socket, ZMQ_SUBSCRIBE, _channelName.c_str(), _channelName.size()) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
	LOG_DEBUG("Subscribing to %s", _channelName.c_str());
	zmq_setsockopt(_socket, ZMQ_SUBSCRIBE, _uuid.c_str(), _uuid.size()) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
	LOG_DEBUG("Subscribing to %s", SHORT_UUID(_uuid).c_str());

	// reconnection intervals
	int reconnect_ivl_min = 100;
	int reconnect_ivl_max = 200;
	zmq_setsockopt (_socket, ZMQ_RECONNECT_IVL, &reconnect_ivl_min, sizeof(int)) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));
	zmq_setsockopt (_socket, ZMQ_RECONNECT_IVL_MAX, &reconnect_ivl_max, sizeof(int)) && LOG_WARN("zmq_setsockopt: %s",zmq_strerror(errno));

	// make sure we can close the socket later
	std::stringstream ss;
	ss << "inproc://" << _uuid;
	zmq_bind(_closer, ss.str().c_str()) && LOG_WARN("zmq_bind: %s",zmq_strerror(errno));
	zmq_connect(_socket, ss.str().c_str()) && LOG_WARN("zmq_connect: %s",zmq_strerror(errno));

	LOG_INFO("creating subscriber for %s", _channelName.c_str());
	start();
}

/**
 * Break blocking zmq_recvmsg in ZeroMQSubscriber::run.
 */
void ZeroMQSubscriber::join() {
	UMUNDO_LOCK(_mutex);
	stop();

	// this is a hack .. the thread is blocking at zmq_recvmsg - unblock by sending a message
	zmq_msg_t channelEnvlp;
	ZMQ_PREPARE_STRING(channelEnvlp, _channelName.c_str(), _channelName.size());

	zmq_sendmsg(_closer, &channelEnvlp, 0) >= 0 || LOG_WARN("zmq_sendmsg: %s",zmq_strerror(errno));
	zmq_msg_close(&channelEnvlp) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));

	Thread::join();
	UMUNDO_UNLOCK(_mutex);
}

void ZeroMQSubscriber::suspend() {
	UMUNDO_LOCK(_mutex);
	if (_isSuspended) {
		UMUNDO_UNLOCK(_mutex);
		return;
	}
	_isSuspended = true;
	stop();
	join();

	_connections.clear();
	zmq_close(_closer) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));
	zmq_close(_socket) && LOG_WARN("zmq_close: %s",zmq_strerror(errno));

	UMUNDO_UNLOCK(_mutex);
}

void ZeroMQSubscriber::resume() {
	UMUNDO_LOCK(_mutex);
	if (!_isSuspended) {
		UMUNDO_UNLOCK(_mutex);
		return;
	}
	_isSuspended = false;
	init(_config);

	UMUNDO_UNLOCK(_mutex);
}

void ZeroMQSubscriber::run() {
	int32_t more;
	size_t more_size = sizeof(more);

	zmq_pollitem_t pollItem;
	pollItem.socket = _socket;
	pollItem.events = ZMQ_POLLIN | ZMQ_POLLOUT;

	while(isStarted()) {
		int rc = 0;
		{
			ScopeLock lock(&_mutex);
			rc = zmq_poll(&pollItem, 1, 30);
		}
		if (rc < 0) {
			// an error occurred
			switch(rc) {
				case ETERM:
					LOG_WARN("zmq_poll called with terminated socket");
					break;
				case EFAULT:
					LOG_WARN("zmq_poll called with invalid items");
					break;
				case EINTR:
				default:
					break;
			}

		} else if (rc == 0) {
			// Nothing to read - released lock
			Thread::yield();
//			Thread::sleepMs(5);

		} if (rc > 0) {
			// there is a message to be read
			ScopeLock lock(&_mutex);
			Message* msg = new Message();
			while (1) {
			// read and dispatch the whole message
				zmq_msg_t message;
				zmq_msg_init(&message) && LOG_WARN("zmq_msg_init: %s",zmq_strerror(errno));

				while (zmq_recvmsg(_socket, &message, 0) < 0)
					if (errno != EINTR)
						LOG_WARN("zmq_recvmsg: %s",zmq_strerror(errno));

				size_t msgSize = zmq_msg_size(&message);

				if (!isStarted()) {
					zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
					return;
				}

				// last message contains actual data
				zmq_getsockopt(_socket, ZMQ_RCVMORE, &more, &more_size) && LOG_WARN("zmq_getsockopt: %s",zmq_strerror(errno));

				if (more) {
					char* key = (char*)zmq_msg_data(&message);
					char* value = ((char*)zmq_msg_data(&message) + strlen(key) + 1);

					// is this the first message with the channelname?
					if (strlen(key) + 1 == msgSize &&
					        msg->getMeta().find(key) == msg->getMeta().end()) {
						msg->putMeta("channel", key);
					} else {
						assert(strlen(key) + strlen(value) + 2 == msgSize);
						if (strlen(key) + strlen(value) + 2 != msgSize) {
							LOG_WARN("Received malformed message %d + %d + 2 != %d", strlen(key), strlen(value), msgSize);
							zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
							break;
						} else {
							msg->putMeta(key, value);
						}
					}
					zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));
				} else {
					msg->setData((char*)zmq_msg_data(&message), msgSize);
					zmq_msg_close(&message) && LOG_WARN("zmq_msg_close: %s",zmq_strerror(errno));

					if (_receiver != NULL) {
						_receiver->receive(msg);
						delete(msg);
					} else {
						ScopeLock lock(&_msgMutex);
						_msgQueue.push_back(msg);
					}
					break; // last message part
				}
			}
		}
	}
}

Message* ZeroMQSubscriber::getNextMsg() {
  if (_receiver != NULL) {
    LOG_WARN("getNextMsg not functional when a receiver is given");
    return NULL;
  }

	ScopeLock lock(&_msgMutex);
	Message* msg = NULL;
	if (_msgQueue.size() > 0) {
		msg = _msgQueue.front();
		_msgQueue.pop_front();
	}
	return msg;
}

Message* ZeroMQSubscriber::peekNextMsg() {
  if (_receiver != NULL) {
    LOG_WARN("peekNextMsg not functional when a receiver is given");
    return NULL;
  }

	ScopeLock lock(&_msgMutex);
	Message* msg = NULL;
	if (_msgQueue.size() > 0) {
		msg = _msgQueue.front();
	}
	return msg;
}

void ZeroMQSubscriber::added(shared_ptr<PublisherStub> pub) {
	std::stringstream ss;
	if (pub->isInProcess() && false) {
		ss << "inproc://" << pub->getUUID();
	} else {
		ss << pub->getTransport() << "://" << pub->getIP() << ":" << pub->getPort();
	}
	if (_connections.find(ss.str()) != _connections.end()) {
		LOG_INFO("Already connected to %s", ss.str().c_str());
		return;
	}

	ScopeLock lock(&_mutex);
	LOG_INFO("%s subscribing at %s", _channelName.c_str(), ss.str().c_str());
	zmq_connect(_socket, ss.str().c_str()) && LOG_WARN("zmq_connect: %s", zmq_strerror(errno));
	_connections.insert(ss.str());
}

void ZeroMQSubscriber::removed(shared_ptr<PublisherStub> pub) {
	ScopeLock lock(&_mutex);
	std::stringstream ss;
	if (pub->isInProcess() && false) {
		ss << "inproc://" << pub->getUUID();
	} else {
		ss << pub->getTransport() << "://" << pub->getIP() << ":" << pub->getPort();
	}
	if (_connections.find(ss.str()) == _connections.end()) {
		LOG_INFO("Never connected to %s won't disconnect", ss.str().c_str());
		return;
	}

	LOG_DEBUG("unsubscribing from %s", ss.str().c_str());
	zmq_connect(_socket, ss.str().c_str()) && LOG_WARN("zmq_disconnect: %s", zmq_strerror(errno));
	_connections.erase(ss.str());
}

void ZeroMQSubscriber::changed(shared_ptr<PublisherStub>) {
	// never called
}

}<|endoftext|>


<commit_before>// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Models/Player.hpp>
#include <Rosetta/Tasks/PlayerTasks/EndTurnTask.hpp>

namespace RosettaStone::PlayerTasks
{
TaskID EndTurnTask::GetTaskID() const
{
    return TaskID::END_TURN;
}

TaskStatus EndTurnTask::Impl(Player& player)
{
    player.GetGame()->step = Step::MAIN_END;
    player.GetGame()->MainEnd();

    return TaskStatus::COMPLETE;
}
}  // namespace RosettaStone::PlayerTasks
<commit_msg>refactor: Use 'nextStep' instead of 'step' and call ProcessNextStep()<commit_after>// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Games/GameManager.hpp>
#include <Rosetta/Models/Player.hpp>
#include <Rosetta/Tasks/PlayerTasks/EndTurnTask.hpp>

namespace RosettaStone::PlayerTasks
{
TaskID EndTurnTask::GetTaskID() const
{
    return TaskID::END_TURN;
}

TaskStatus EndTurnTask::Impl(Player& player)
{
    auto game = player.GetGame();

    game->nextStep = Step::MAIN_END;
    GameManager::ProcessNextStep(*game, game->nextStep);

    return TaskStatus::COMPLETE;
}
}  // namespace RosettaStone::PlayerTasks
<|endoftext|>


<commit_before>// Copyright (c) 2020 The Orbit 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 "GraphTrack.h"

#include "GlCanvas.h"

GraphTrack::GraphTrack(TimeGraph* time_graph, std::string name)
    : Track(time_graph), name_(std::move(name)) {}

void GraphTrack::Draw(GlCanvas* canvas, PickingMode picking_mode) {
  Batcher* batcher = canvas->GetBatcher();

  float trackWidth = canvas->GetWorldWidth();
  const TimeGraphLayout& layout = time_graph_->GetLayout();

  pos_[0] = canvas->GetWorldTopLeftX();
  SetSize(trackWidth, GetHeight());
  Track::Draw(canvas, picking_mode);

  float x0 = pos_[0];
  float x1 = x0 + size_[0];

  float y0 = pos_[1];
  float y1 = y0 - size_[1];

  const Color kPickedColor(0, 128, 255, 128);
  Color color = color_;
  if (picked_) {
    // TODO: Is this really used? Is picked_ even a thing?
    color = kPickedColor;
  }

  float track_z = GlCanvas::kZValueTrack;

  Box box(pos_, Vec2(size_[0], -size_[1]), track_z);

  // Draw label with graph value at current mouse position.
  const Color kWhiteColor(255, 255, 255, 255);
  const Color kBlackColor(0, 0, 0, 255);
  double graph_value = GetValueAtTime(time_graph_->GetCurrentMouseTimeNs());

  int white_text_box_width =
      canvas->GetTextRenderer().GetStringWidth(std::to_string(graph_value).c_str());

  Vec2 white_text_box_size(white_text_box_width, layout.GetTextBoxHeight());
  auto rightmost_x_position = canvas->GetWorldTopLeftX() + canvas->GetWorldWidth() -
                              layout.GetRightMargin() - layout.GetSliderWidth() -
                              white_text_box_size[0];
  Vec2 white_text_box_position(
      std::min(canvas->GetMouseX(), rightmost_x_position),
      y0 - static_cast<float>((max_ - graph_value) * size_[1] / value_range_) -
          white_text_box_size[1] / 2.f);

  canvas->GetTextRenderer().AddText(std::to_string(graph_value).c_str(), white_text_box_position[0],
                                    white_text_box_position[1] + layout.GetTextOffset(),
                                    GlCanvas::kZValueTextUi, kBlackColor,
                                    time_graph_->CalculateZoomedFontSize(), white_text_box_size[0]);
  Box white_text_box(white_text_box_position, white_text_box_size, GlCanvas::kZValueUi);
  batcher->AddBox(white_text_box, kWhiteColor);

  batcher->AddBox(box, color, shared_from_this());

  if (canvas->GetPickingManager().IsThisElementPicked(this)) {
    color = Color(255, 255, 255, 255);
  }

  batcher->AddLine(pos_, Vec2(x1, y0), track_z, color, shared_from_this());
  batcher->AddLine(Vec2(x1, y1), Vec2(x0, y1), track_z, color, shared_from_this());

  const Color kLineColor(0, 128, 255, 128);

  // Current time window
  uint64_t min_ns = time_graph_->GetTickFromUs(time_graph_->GetMinTimeUs());
  uint64_t max_ns = time_graph_->GetTickFromUs(time_graph_->GetMaxTimeUs());
  double time_range = static_cast<float>(max_ns - min_ns);
  if (values_.size() < 2 || time_range == 0) return;

  auto it = values_.upper_bound(min_ns);
  if (it == values_.end()) return;
  if (it != values_.begin()) --it;
  uint64_t previous_time = it->first;
  double last_normalized_value = (it->second - min_) * inv_value_range_;
  for (++it; it != values_.end(); ++it) {
    if (previous_time > max_ns) break;
    uint64_t time = it->first;
    double normalized_value = (it->second - min_) * inv_value_range_;
    float base_y = pos_[1] - size_[1];
    float x0 = time_graph_->GetWorldFromTick(previous_time);
    float x1 = time_graph_->GetWorldFromTick(time);
    float y0 = base_y + static_cast<float>(last_normalized_value) * size_[1];
    float y1 = base_y + static_cast<float>(normalized_value) * size_[1];
    time_graph_->GetBatcher().AddLine(Vec2(x0, y0), Vec2(x1, y0), GlCanvas::kZValueText,
                                      kLineColor);
    time_graph_->GetBatcher().AddLine(Vec2(x1, y0), Vec2(x1, y1), GlCanvas::kZValueText,
                                      kLineColor);

    previous_time = time;
    last_normalized_value = normalized_value;
  }
}

void GraphTrack::AddValue(double value, uint64_t time) {
  values_[time] = value;
  max_ = std::max(max_, value);
  min_ = std::min(min_, value);
  value_range_ = max_ - min_;

  if (value_range_ > 0) inv_value_range_ = 1.0 / value_range_;
}

double GraphTrack::GetValueAtTime(uint64_t time, double default_value) const {
  auto iterator_lower = values_.upper_bound(time);
  if (iterator_lower == values_.end() || iterator_lower == values_.begin()) {
    return default_value;
  }
  --iterator_lower;
  return iterator_lower->second;
}

float GraphTrack::GetHeight() const {
  const TimeGraphLayout& layout = time_graph_->GetLayout();
  float height = layout.GetTextBoxHeight() + layout.GetSpaceBetweenTracksAndThread() +
                 layout.GetEventTrackHeight() + layout.GetTrackBottomMargin();
  return height;
}
<commit_msg>Fix bug when picking in GraphTrack<commit_after>// Copyright (c) 2020 The Orbit 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 "GraphTrack.h"

#include "GlCanvas.h"

GraphTrack::GraphTrack(TimeGraph* time_graph, std::string name)
    : Track(time_graph), name_(std::move(name)) {}

void GraphTrack::Draw(GlCanvas* canvas, PickingMode picking_mode) {
  Batcher* batcher = canvas->GetBatcher();

  float trackWidth = canvas->GetWorldWidth();
  const TimeGraphLayout& layout = time_graph_->GetLayout();
  const bool picking = picking_mode != PickingMode::kNone;

  pos_[0] = canvas->GetWorldTopLeftX();
  SetSize(trackWidth, GetHeight());
  Track::Draw(canvas, picking_mode);

  float x0 = pos_[0];
  float x1 = x0 + size_[0];

  float y0 = pos_[1];
  float y1 = y0 - size_[1];

  const Color kPickedColor(0, 128, 255, 128);
  Color color = color_;
  if (picked_) {
    // TODO: Is this really used? Is picked_ even a thing?
    color = kPickedColor;
  }

  float track_z = GlCanvas::kZValueTrack;

  Box box(pos_, Vec2(size_[0], -size_[1]), track_z);

  // Draw label with graph value at current mouse position.
  const Color kWhiteColor(255, 255, 255, 255);
  const Color kBlackColor(0, 0, 0, 255);
  double graph_value = GetValueAtTime(time_graph_->GetCurrentMouseTimeNs());

  int white_text_box_width =
      canvas->GetTextRenderer().GetStringWidth(std::to_string(graph_value).c_str());

  Vec2 white_text_box_size(white_text_box_width, layout.GetTextBoxHeight());
  auto rightmost_x_position = canvas->GetWorldTopLeftX() + canvas->GetWorldWidth() -
                              layout.GetRightMargin() - layout.GetSliderWidth() -
                              white_text_box_size[0];
  Vec2 white_text_box_position(
      std::min(canvas->GetMouseX(), rightmost_x_position),
      y0 - static_cast<float>((max_ - graph_value) * size_[1] / value_range_) -
          white_text_box_size[1] / 2.f);

  if (!picking) {
    canvas->GetTextRenderer().AddText(
        std::to_string(graph_value).c_str(), white_text_box_position[0],
        white_text_box_position[1] + layout.GetTextOffset(), GlCanvas::kZValueTextUi, kBlackColor,
        time_graph_->CalculateZoomedFontSize(), white_text_box_size[0]);
    Box white_text_box(white_text_box_position, white_text_box_size, GlCanvas::kZValueUi);
    batcher->AddBox(white_text_box, kWhiteColor);
  }

  batcher->AddBox(box, color, shared_from_this());

  if (canvas->GetPickingManager().IsThisElementPicked(this)) {
    color = Color(255, 255, 255, 255);
  }

  batcher->AddLine(pos_, Vec2(x1, y0), track_z, color, shared_from_this());
  batcher->AddLine(Vec2(x1, y1), Vec2(x0, y1), track_z, color, shared_from_this());

  const Color kLineColor(0, 128, 255, 128);

  if (!picking) {
    // Current time window
    uint64_t min_ns = time_graph_->GetTickFromUs(time_graph_->GetMinTimeUs());
    uint64_t max_ns = time_graph_->GetTickFromUs(time_graph_->GetMaxTimeUs());
    double time_range = static_cast<float>(max_ns - min_ns);
    if (values_.size() < 2 || time_range == 0) return;

    auto it = values_.upper_bound(min_ns);
    if (it == values_.end()) return;
    if (it != values_.begin()) --it;
    uint64_t previous_time = it->first;
    double last_normalized_value = (it->second - min_) * inv_value_range_;
    for (++it; it != values_.end(); ++it) {
      if (previous_time > max_ns) break;
      uint64_t time = it->first;
      double normalized_value = (it->second - min_) * inv_value_range_;
      float base_y = pos_[1] - size_[1];
      float x0 = time_graph_->GetWorldFromTick(previous_time);
      float x1 = time_graph_->GetWorldFromTick(time);
      float y0 = base_y + static_cast<float>(last_normalized_value) * size_[1];
      float y1 = base_y + static_cast<float>(normalized_value) * size_[1];
      time_graph_->GetBatcher().AddLine(Vec2(x0, y0), Vec2(x1, y0), GlCanvas::kZValueText,
                                        kLineColor);
      time_graph_->GetBatcher().AddLine(Vec2(x1, y0), Vec2(x1, y1), GlCanvas::kZValueText,
                                        kLineColor);

      previous_time = time;
      last_normalized_value = normalized_value;
    }
  }
}

void GraphTrack::AddValue(double value, uint64_t time) {
  values_[time] = value;
  max_ = std::max(max_, value);
  min_ = std::min(min_, value);
  value_range_ = max_ - min_;

  if (value_range_ > 0) inv_value_range_ = 1.0 / value_range_;
}

double GraphTrack::GetValueAtTime(uint64_t time, double default_value) const {
  auto iterator_lower = values_.upper_bound(time);
  if (iterator_lower == values_.end() || iterator_lower == values_.begin()) {
    return default_value;
  }
  --iterator_lower;
  return iterator_lower->second;
}

float GraphTrack::GetHeight() const {
  const TimeGraphLayout& layout = time_graph_->GetLayout();
  float height = layout.GetTextBoxHeight() + layout.GetSpaceBetweenTracksAndThread() +
                 layout.GetEventTrackHeight() + layout.GetTrackBottomMargin();
  return height;
}
<|endoftext|>


<commit_before>#ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH
#define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH

#ifdef HAVE_CMAKE_CONFIG
 #include "cmake_config.h"
#else
 #include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG

#include <vector>

#if HAVE_DUNE_GEOMETRY
#include <dune/geometry/referenceelements.hh>
#else
#include <dune/grid/common/genericreferenceelements.hh>
#endif

#include <dune/common/shared_ptr.hh>
#include <dune/common/fvector.hh>
#include <dune/grid/common/backuprestore.hh>
#include <dune/grid/common/grid.hh>
#include <dune/grid/common/gridview.hh>
#include <dune/grid/common/entity.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/aliases.hh>
#include <dune/stuff/fem/namespace.hh>

#ifdef HAVE_DUNE_FEM
  #include <dune/fem/function/common/discretefunction.hh>
  #include <dune/fem/quadrature/cachingquadrature.hh>
#endif

#include <dune/grid/io/file/vtk/function.hh>

#include <boost/range/iterator_range.hpp>

namespace Dune {
namespace Stuff {

template <class ViewTraits>
class StrategyBase {
public:
  typedef typename ViewTraits::template Codim<0>::Entity EntityType;
  typedef typename EntityType::Geometry::LocalCoordinate LocalCoordinateType;
  typedef typename EntityType::Geometry::GlobalCoordinate GlobalCoordinateType;
  typedef std::vector<typename EntityType::EntityPointer> EntityPointerVector;
};

template <class ViewTraits>
class InlevelSearchStrategy : public StrategyBase<ViewTraits> {
  typedef StrategyBase<ViewTraits> BaseType;
  typedef GenericReferenceElements< typename  BaseType::LocalCoordinateType::value_type,
                                              BaseType::LocalCoordinateType::dimension >
        RefElementType;
  typedef typename Dune::GridView<ViewTraits>::template Codim< 0 >::Iterator IteratorType;

  inline bool check_add(const typename BaseType::EntityType& entity,
                        const typename BaseType::GlobalCoordinateType& point,
                        typename BaseType::EntityPointerVector& ret) const {
    const auto& geometry = entity.geometry();
    const auto& refElement = RefElementType::general(geometry.type());
    if(refElement.checkInside(geometry.local(point)))
    {
      ret.emplace_back(entity);
      return true;
    }
    return false;
  }
public:
  InlevelSearchStrategy(const Dune::GridView<ViewTraits>& gridview)
    : gridview_(gridview)
    , it_last_(gridview_.template begin< 0 >())
  {}

  template <class QuadpointContainerType>
  typename BaseType::EntityPointerVector operator() (const QuadpointContainerType& quad_points)
  {
    const auto max_size = quad_points.size();

    const IteratorType begin = gridview_.template begin< 0 >();
    const IteratorType end = gridview_.template end< 0 >();
    std::vector<typename BaseType::EntityType::EntityPointer> ret;
    for(const auto& point : quad_points)
    {
      IteratorType it_current = it_last_;
      bool it_reset = true;
      for(; it_current != end && ret.size() < max_size; ++it_current)
      {
        if(check_add(*it_current, point, ret)) {
          it_reset = false;
          it_last_ = it_current;
          break;
        }
      }
      if(!it_reset)
        continue;
      for(it_current = begin;
          it_current != it_last_ && ret.size() < max_size;
          ++it_current)
      {
        if(check_add(*it_current, point, ret)) {
          it_reset = false;
          it_last_ = it_current;
          break;
        }
      }
      assert(!it_reset);
    }
    return ret;
  }

private:
  const Dune::GridView<ViewTraits>& gridview_;
  IteratorType it_last_;
};

template <class ViewTraits>
class HierarchicSearchStrategy : public StrategyBase<ViewTraits> {
  typedef StrategyBase<ViewTraits> BaseType;

  const Dune::GridView<ViewTraits>& gridview_;
  const int start_level_;

public:
  HierarchicSearchStrategy(const Dune::GridView<ViewTraits>& gridview)
    : gridview_(gridview)
    , start_level_(0)
  {}

  template <class QuadpointContainerType>
  typename BaseType::EntityPointerVector
  operator() (const QuadpointContainerType& quad_points) const
  {
    auto level = std::min(gridview_.grid().maxLevel(), start_level_);
    auto range = DSC::viewRange(gridview_.grid().levelView(level));
    return process(quad_points, range);
  }

private:

  template <class QuadpointContainerType, class RangeType>
  std::vector<typename BaseType::EntityType::EntityPointer>
  process(const QuadpointContainerType& quad_points,
          const RangeType& range) const
  {
    typedef GenericReferenceElements< typename BaseType::LocalCoordinateType::value_type,
        BaseType::LocalCoordinateType::dimension > RefElementType;
    std::vector<typename BaseType::EntityType::EntityPointer> ret;

    for(const auto& my_ent : range) {
      const int my_level = my_ent.level();
      const auto& geometry = my_ent.geometry();
      const auto& refElement = RefElementType::general(geometry.type());
      for(const auto& point : quad_points)
      {
        if(refElement.checkInside(geometry.local(point)))
        {
          //if I cannot descend further add this entity even if it's not my view
          if(gridview_.grid().maxLevel() <= my_level || gridview_.contains(my_ent)) {
            ret.emplace_back(my_ent);
          }
          else {
            const auto h_end = my_ent.hend(my_level+1);
            const auto h_begin = my_ent.hbegin(my_level+1);
            const auto h_range = boost::make_iterator_range(h_begin, h_end);
            const auto kids = process(QuadpointContainerType(1, point), h_range);
            ret.insert(ret.end(), kids.begin(), kids.end());
          }
        }
      }
    }
    return ret;
  }
};

template <template <class> class SearchStrategy = InlevelSearchStrategy>
class HeterogenousProjection
{
public:
#ifdef HAVE_DUNE_FEM
  template < class SourceDFImp, class TargetDFImp >
  static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,
                      Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target)
  {
    typedef SearchStrategy<typename SourceDFImp::GridType::LeafGridView::Traits> SearchStrategyType;
    typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType;
    typedef typename TargetDFImp::DofType TargetDofType;
    static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange;

    const auto& space =  target.space();
    const auto infinity = std::numeric_limits< TargetDofType >::infinity();

    // set all DoFs to infinity
    const auto dend = target.dend();
    for( auto dit = target.dbegin(); dit != dend; ++dit )
      *dit = infinity;

    SearchStrategyType search(source.gridPart().grid().leafView());
    const auto endit = space.end();
    for(auto it = space.begin(); it != endit ; ++it)
    {
      const auto& target_entity = *it;
      const auto& target_geometry = target_entity.geometry();
      auto target_local_function = target.localFunction(target_entity);
      const auto& target_lagrangepoint_set = space.lagrangePointSet(target_entity);
      const auto quadNop = target_lagrangepoint_set.nop();

      typename TargetDiscreteFunctionSpaceType::RangeType source_value;

      std::vector<typename TargetDiscreteFunctionSpaceType::DomainType> global_quads(quadNop);
      for(size_t qP = 0; qP < quadNop ; ++qP) {
        global_quads[qP] = target_geometry.global(target_lagrangepoint_set.point(qP));
      }
      const auto evaluation_entities = search(global_quads);
      assert(evaluation_entities.size() == global_quads.size());

      int k = 0;
      for(size_t qP = 0; qP < quadNop ; ++qP)
      {
        if(std::isinf(target_local_function[ k ]))
        {
          const auto& global_point = global_quads[qP];
          // evaluate source function
          const auto source_entity = evaluation_entities[qP];
          const auto& source_geometry = source_entity->geometry();
          const auto& source_local_point = source_geometry.local(global_point);
          const auto& source_local_function = source.localFunction(*source_entity);
          source_local_function.evaluate(source_local_point, source_value);
          for(int i = 0; i < target_dimRange; ++i, ++k)
            target_local_function[k] = source_value[i];
        }
        else
          k += target_dimRange;
      }
    }
  } // ... project(...)
#endif // HAVE_DUNE_FEM

} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH
<commit_msg>[discretefunction.projection] make use of grid.search<commit_after>#ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH
#define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH

#include <dune/common/fvector.hh>
#include <dune/grid/common/backuprestore.hh>
#include <dune/grid/common/grid.hh>
#include <dune/grid/common/entity.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/aliases.hh>
#include <dune/stuff/fem/namespace.hh>

#ifdef HAVE_DUNE_FEM
  #include <dune/fem/function/common/discretefunction.hh>
  #include <dune/fem/quadrature/cachingquadrature.hh>
#endif

#include <dune/grid/io/file/vtk/function.hh>

#include <dune/stuff/grid/search.hh>

namespace Dune {
namespace Stuff {

#ifdef HAVE_DUNE_FEM
template< template< class > class SearchStrategy = Grid::EntityInlevelSearch >
class HeterogenousProjection
{
public:
  template < class SourceDFImp, class TargetDFImp >
  static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,
                      Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target)
  {
    typedef SearchStrategy<typename SourceDFImp::GridType::LeafGridView> SearchStrategyType;
    typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType;
    typedef typename TargetDFImp::DofType TargetDofType;
    static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange;

    const auto& space =  target.space();
    const auto infinity = std::numeric_limits< TargetDofType >::infinity();

    // set all DoFs to infinity
    const auto dend = target.dend();
    for( auto dit = target.dbegin(); dit != dend; ++dit )
      *dit = infinity;

    SearchStrategyType search(source.gridPart().grid().leafView());
    const auto endit = space.end();
    for(auto it = space.begin(); it != endit ; ++it)
    {
      const auto& target_entity = *it;
      const auto& target_geometry = target_entity.geometry();
      auto target_local_function = target.localFunction(target_entity);
      const auto& target_lagrangepoint_set = space.lagrangePointSet(target_entity);
      const auto quadNop = target_lagrangepoint_set.nop();

      typename TargetDiscreteFunctionSpaceType::RangeType source_value;

      std::vector<typename TargetDiscreteFunctionSpaceType::DomainType> global_quads(quadNop);
      for(size_t qP = 0; qP < quadNop ; ++qP) {
        global_quads[qP] = target_geometry.global(target_lagrangepoint_set.point(qP));
      }
      const auto evaluation_entities = search(global_quads);
      assert(evaluation_entities.size() == global_quads.size());

      int k = 0;
      for(size_t qP = 0; qP < quadNop ; ++qP)
      {
        if(std::isinf(target_local_function[ k ]))
        {
          const auto& global_point = global_quads[qP];
          // evaluate source function
          const auto source_entity = evaluation_entities[qP];
          const auto& source_geometry = source_entity->geometry();
          const auto& source_local_point = source_geometry.local(global_point);
          const auto& source_local_function = source.localFunction(*source_entity);
          source_local_function.evaluate(source_local_point, source_value);
          for(int i = 0; i < target_dimRange; ++i, ++k)
            target_local_function[k] = source_value[i];
        }
        else
          k += target_dimRange;
      }
    }
  } // ... project(...)
}; // class HeterogenousProjection
#endif // HAVE_DUNE_FEM

} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: datalistener.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-23 11:50:42 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SVX_DATALISTENER_HXX
#define _SVX_DATALISTENER_HXX

#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_
#include <com/sun/star/container/XContainerListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAMEACTIONLISTENER_HPP_
#include <com/sun/star/frame/XFrameActionListener.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_DOM_EVENTS_XEVENTLISTENER_HPP_
#include <com/sun/star/xml/dom/events/XEventListener.hpp>
#endif

//............................................................................
namespace svxform
{
//............................................................................

    class DataNavigatorWindow;

    typedef cppu::WeakImplHelper3<
        com::sun::star::container::XContainerListener,
        com::sun::star::frame::XFrameActionListener,
        com::sun::star::xml::dom::events::XEventListener > DataListener_t;

    class DataListener : public DataListener_t
    {
    private:
        DataNavigatorWindow*        m_pNaviWin;

    public:
        DataListener( DataNavigatorWindow* pNaviWin );

    protected:
        ~DataListener();

    public:
        // XContainerListener
        virtual void SAL_CALL elementInserted( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL elementRemoved( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL elementReplaced( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException);

        // XFrameActionListener
        virtual void SAL_CALL frameAction( const ::com::sun::star::frame::FrameActionEvent& Action ) throw (::com::sun::star::uno::RuntimeException);

        // xml::dom::events::XEventListener
        virtual void SAL_CALL handleEvent( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::events::XEvent >& evt ) throw (::com::sun::star::uno::RuntimeException);

        // lang::XEventListener
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);
    };

//............................................................................
}   // namespace svxform
//............................................................................

#endif // #ifndef _SVX_DATALISTENER_HXX

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.252); FILE MERGED 2005/09/05 14:25:01 rt 1.3.252.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: datalistener.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 23:11:48 $
 *
 *  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 _SVX_DATALISTENER_HXX
#define _SVX_DATALISTENER_HXX

#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_
#include <com/sun/star/container/XContainerListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAMEACTIONLISTENER_HPP_
#include <com/sun/star/frame/XFrameActionListener.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_DOM_EVENTS_XEVENTLISTENER_HPP_
#include <com/sun/star/xml/dom/events/XEventListener.hpp>
#endif

//............................................................................
namespace svxform
{
//............................................................................

    class DataNavigatorWindow;

    typedef cppu::WeakImplHelper3<
        com::sun::star::container::XContainerListener,
        com::sun::star::frame::XFrameActionListener,
        com::sun::star::xml::dom::events::XEventListener > DataListener_t;

    class DataListener : public DataListener_t
    {
    private:
        DataNavigatorWindow*        m_pNaviWin;

    public:
        DataListener( DataNavigatorWindow* pNaviWin );

    protected:
        ~DataListener();

    public:
        // XContainerListener
        virtual void SAL_CALL elementInserted( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL elementRemoved( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL elementReplaced( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException);

        // XFrameActionListener
        virtual void SAL_CALL frameAction( const ::com::sun::star::frame::FrameActionEvent& Action ) throw (::com::sun::star::uno::RuntimeException);

        // xml::dom::events::XEventListener
        virtual void SAL_CALL handleEvent( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::events::XEvent >& evt ) throw (::com::sun::star::uno::RuntimeException);

        // lang::XEventListener
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);
    };

//............................................................................
}   // namespace svxform
//............................................................................

#endif // #ifndef _SVX_DATALISTENER_HXX

<|endoftext|>


<commit_before>/*
 *   Copyright (c) 2020 Project CHIP Authors
 *   All rights reserved.
 *
 *   Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

#include "PairingCommand.h"
#include "platform/PlatformManager.h"
#include <controller/ExampleOperationalCredentialsIssuer.h>
#include <crypto/CHIPCryptoPAL.h>
#include <lib/core/CHIPSafeCasts.h>
#include <lib/support/logging/CHIPLogging.h>
#include <protocols/secure_channel/PASESession.h>

#include <setup_payload/ManualSetupPayloadParser.h>
#include <setup_payload/QRCodeSetupPayloadParser.h>

using namespace ::chip;
using namespace ::chip::Controller;

CHIP_ERROR PairingCommand::RunCommand()
{
    CurrentCommissioner().RegisterPairingDelegate(this);
    return RunInternal(mNodeId);
}

CHIP_ERROR PairingCommand::RunInternal(NodeId remoteId)
{
    CHIP_ERROR err = CHIP_NO_ERROR;

    switch (mPairingMode)
    {
    case PairingMode::None:
        err = Unpair(remoteId);
        break;
    case PairingMode::QRCode:
        err = PairWithCode(remoteId);
        break;
    case PairingMode::ManualCode:
        err = PairWithCode(remoteId);
        break;
    case PairingMode::QRCodePaseOnly:
    case PairingMode::ManualCodePaseOnly:
        err = PaseWithCode(remoteId);
        break;
    case PairingMode::Ble:
        err = Pair(remoteId, PeerAddress::BLE());
        break;
    case PairingMode::OnNetwork:
        err = PairWithMdns(remoteId);
        break;
    case PairingMode::SoftAP:
        err = Pair(remoteId, PeerAddress::UDP(mRemoteAddr.address, mRemotePort));
        break;
    case PairingMode::Ethernet:
        err = Pair(remoteId, PeerAddress::UDP(mRemoteAddr.address, mRemotePort));
        break;
    }

    return err;
}

CommissioningParameters PairingCommand::GetCommissioningParameters()
{
    switch (mNetworkType)
    {
    case PairingNetworkType::WiFi:
        return CommissioningParameters().SetWiFiCredentials(Controller::WiFiCredentials(mSSID, mPassword));
    case PairingNetworkType::Thread:
        return CommissioningParameters().SetThreadOperationalDataset(mOperationalDataset);
    case PairingNetworkType::Ethernet:
    case PairingNetworkType::None:
        return CommissioningParameters();
    }
    return CommissioningParameters();
}

CHIP_ERROR PairingCommand::PaseWithCode(NodeId remoteId)
{
    return CurrentCommissioner().EstablishPASEConnection(remoteId, mOnboardingPayload);
}

CHIP_ERROR PairingCommand::PairWithCode(NodeId remoteId)
{
    CommissioningParameters commissioningParams = GetCommissioningParameters();
    return CurrentCommissioner().PairDevice(remoteId, mOnboardingPayload, commissioningParams);
}

CHIP_ERROR PairingCommand::Pair(NodeId remoteId, PeerAddress address)
{
    RendezvousParameters params =
        RendezvousParameters().SetSetupPINCode(mSetupPINCode).SetDiscriminator(mDiscriminator).SetPeerAddress(address);
    CommissioningParameters commissioningParams = GetCommissioningParameters();
    return CurrentCommissioner().PairDevice(remoteId, params, commissioningParams);
}

CHIP_ERROR PairingCommand::PairWithMdns(NodeId remoteId)
{
    Dnssd::DiscoveryFilter filter(mFilterType);
    switch (mFilterType)
    {
    case chip::Dnssd::DiscoveryFilterType::kNone:
        break;
    case chip::Dnssd::DiscoveryFilterType::kShortDiscriminator:
    case chip::Dnssd::DiscoveryFilterType::kLongDiscriminator:
    case chip::Dnssd::DiscoveryFilterType::kCompressedFabricId:
    case chip::Dnssd::DiscoveryFilterType::kVendorId:
    case chip::Dnssd::DiscoveryFilterType::kDeviceType:
        filter.code = mDiscoveryFilterCode;
        break;
    case chip::Dnssd::DiscoveryFilterType::kCommissioningMode:
        break;
    case chip::Dnssd::DiscoveryFilterType::kCommissioner:
        filter.code = 1;
        break;
    case chip::Dnssd::DiscoveryFilterType::kInstanceName:
        filter.code         = 0;
        filter.instanceName = mDiscoveryFilterInstanceName;
        break;
    }

    CurrentCommissioner().RegisterDeviceDiscoveryDelegate(this);
    return CurrentCommissioner().DiscoverCommissionableNodes(filter);
}

CHIP_ERROR PairingCommand::Unpair(NodeId remoteId)
{
    CHIP_ERROR err = CurrentCommissioner().UnpairDevice(remoteId);
    SetCommandExitStatus(err);
    return err;
}

void PairingCommand::OnStatusUpdate(DevicePairingDelegate::Status status)
{
    switch (status)
    {
    case DevicePairingDelegate::Status::SecurePairingSuccess:
        ChipLogProgress(chipTool, "Secure Pairing Success");
        break;
    case DevicePairingDelegate::Status::SecurePairingFailed:
        ChipLogError(chipTool, "Secure Pairing Failed");
        break;
    }
}

void PairingCommand::OnPairingComplete(CHIP_ERROR err)
{
    if (err == CHIP_NO_ERROR)
    {
        ChipLogProgress(chipTool, "Pairing Success");
        if (mPairingMode == PairingMode::QRCodePaseOnly || mPairingMode == PairingMode::ManualCodePaseOnly)
        {
            SetCommandExitStatus(err);
        }
    }
    else
    {
        ChipLogProgress(chipTool, "Pairing Failure: %s", ErrorStr(err));
    }

    if (err != CHIP_NO_ERROR)
    {
        SetCommandExitStatus(err);
    }
}

void PairingCommand::OnPairingDeleted(CHIP_ERROR err)
{
    if (err == CHIP_NO_ERROR)
    {
        ChipLogProgress(chipTool, "Pairing Deleted Success");
    }
    else
    {
        ChipLogProgress(chipTool, "Pairing Deleted Failure: %s", ErrorStr(err));
    }

    SetCommandExitStatus(err);
}

void PairingCommand::OnCommissioningComplete(NodeId nodeId, CHIP_ERROR err)
{
    if (err == CHIP_NO_ERROR)
    {
        ChipLogProgress(chipTool, "Device commissioning completed with success");
    }
    else
    {
        ChipLogProgress(chipTool, "Device commissioning Failure: %s", ErrorStr(err));
    }

    SetCommandExitStatus(err);
}

void PairingCommand::OnDiscoveredDevice(const chip::Dnssd::DiscoveredNodeData & nodeData)
{
    const uint16_t port = nodeData.port;
    char buf[chip::Inet::IPAddress::kMaxStringLength];
    nodeData.ipAddress[0].ToString(buf);
    ChipLogProgress(chipTool, "Discovered Device: %s:%u", buf, port);

    // Stop Mdns discovery. Is it the right method ?
    CurrentCommissioner().RegisterDeviceDiscoveryDelegate(nullptr);

    Inet::InterfaceId interfaceId = nodeData.ipAddress[0].IsIPv6LinkLocal() ? nodeData.interfaceId : Inet::InterfaceId::Null();
    PeerAddress peerAddress       = PeerAddress::UDP(nodeData.ipAddress[0], port, interfaceId);
    CHIP_ERROR err                = Pair(mNodeId, peerAddress);
    if (CHIP_NO_ERROR != err)
    {
        SetCommandExitStatus(err);
    }
}
<commit_msg>[chip-tool] Filter out non-commissionable devices (#16221)<commit_after>/*
 *   Copyright (c) 2020 Project CHIP Authors
 *   All rights reserved.
 *
 *   Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

#include "PairingCommand.h"
#include "platform/PlatformManager.h"
#include <controller/ExampleOperationalCredentialsIssuer.h>
#include <crypto/CHIPCryptoPAL.h>
#include <lib/core/CHIPSafeCasts.h>
#include <lib/support/logging/CHIPLogging.h>
#include <protocols/secure_channel/PASESession.h>

#include <setup_payload/ManualSetupPayloadParser.h>
#include <setup_payload/QRCodeSetupPayloadParser.h>

using namespace ::chip;
using namespace ::chip::Controller;

CHIP_ERROR PairingCommand::RunCommand()
{
    CurrentCommissioner().RegisterPairingDelegate(this);
    return RunInternal(mNodeId);
}

CHIP_ERROR PairingCommand::RunInternal(NodeId remoteId)
{
    CHIP_ERROR err = CHIP_NO_ERROR;

    switch (mPairingMode)
    {
    case PairingMode::None:
        err = Unpair(remoteId);
        break;
    case PairingMode::QRCode:
        err = PairWithCode(remoteId);
        break;
    case PairingMode::ManualCode:
        err = PairWithCode(remoteId);
        break;
    case PairingMode::QRCodePaseOnly:
    case PairingMode::ManualCodePaseOnly:
        err = PaseWithCode(remoteId);
        break;
    case PairingMode::Ble:
        err = Pair(remoteId, PeerAddress::BLE());
        break;
    case PairingMode::OnNetwork:
        err = PairWithMdns(remoteId);
        break;
    case PairingMode::SoftAP:
        err = Pair(remoteId, PeerAddress::UDP(mRemoteAddr.address, mRemotePort));
        break;
    case PairingMode::Ethernet:
        err = Pair(remoteId, PeerAddress::UDP(mRemoteAddr.address, mRemotePort));
        break;
    }

    return err;
}

CommissioningParameters PairingCommand::GetCommissioningParameters()
{
    switch (mNetworkType)
    {
    case PairingNetworkType::WiFi:
        return CommissioningParameters().SetWiFiCredentials(Controller::WiFiCredentials(mSSID, mPassword));
    case PairingNetworkType::Thread:
        return CommissioningParameters().SetThreadOperationalDataset(mOperationalDataset);
    case PairingNetworkType::Ethernet:
    case PairingNetworkType::None:
        return CommissioningParameters();
    }
    return CommissioningParameters();
}

CHIP_ERROR PairingCommand::PaseWithCode(NodeId remoteId)
{
    return CurrentCommissioner().EstablishPASEConnection(remoteId, mOnboardingPayload);
}

CHIP_ERROR PairingCommand::PairWithCode(NodeId remoteId)
{
    CommissioningParameters commissioningParams = GetCommissioningParameters();
    return CurrentCommissioner().PairDevice(remoteId, mOnboardingPayload, commissioningParams);
}

CHIP_ERROR PairingCommand::Pair(NodeId remoteId, PeerAddress address)
{
    RendezvousParameters params =
        RendezvousParameters().SetSetupPINCode(mSetupPINCode).SetDiscriminator(mDiscriminator).SetPeerAddress(address);
    CommissioningParameters commissioningParams = GetCommissioningParameters();
    return CurrentCommissioner().PairDevice(remoteId, params, commissioningParams);
}

CHIP_ERROR PairingCommand::PairWithMdns(NodeId remoteId)
{
    Dnssd::DiscoveryFilter filter(mFilterType);
    switch (mFilterType)
    {
    case chip::Dnssd::DiscoveryFilterType::kNone:
        break;
    case chip::Dnssd::DiscoveryFilterType::kShortDiscriminator:
    case chip::Dnssd::DiscoveryFilterType::kLongDiscriminator:
    case chip::Dnssd::DiscoveryFilterType::kCompressedFabricId:
    case chip::Dnssd::DiscoveryFilterType::kVendorId:
    case chip::Dnssd::DiscoveryFilterType::kDeviceType:
        filter.code = mDiscoveryFilterCode;
        break;
    case chip::Dnssd::DiscoveryFilterType::kCommissioningMode:
        break;
    case chip::Dnssd::DiscoveryFilterType::kCommissioner:
        filter.code = 1;
        break;
    case chip::Dnssd::DiscoveryFilterType::kInstanceName:
        filter.code         = 0;
        filter.instanceName = mDiscoveryFilterInstanceName;
        break;
    }

    CurrentCommissioner().RegisterDeviceDiscoveryDelegate(this);
    return CurrentCommissioner().DiscoverCommissionableNodes(filter);
}

CHIP_ERROR PairingCommand::Unpair(NodeId remoteId)
{
    CHIP_ERROR err = CurrentCommissioner().UnpairDevice(remoteId);
    SetCommandExitStatus(err);
    return err;
}

void PairingCommand::OnStatusUpdate(DevicePairingDelegate::Status status)
{
    switch (status)
    {
    case DevicePairingDelegate::Status::SecurePairingSuccess:
        ChipLogProgress(chipTool, "Secure Pairing Success");
        break;
    case DevicePairingDelegate::Status::SecurePairingFailed:
        ChipLogError(chipTool, "Secure Pairing Failed");
        break;
    }
}

void PairingCommand::OnPairingComplete(CHIP_ERROR err)
{
    if (err == CHIP_NO_ERROR)
    {
        ChipLogProgress(chipTool, "Pairing Success");
        if (mPairingMode == PairingMode::QRCodePaseOnly || mPairingMode == PairingMode::ManualCodePaseOnly)
        {
            SetCommandExitStatus(err);
        }
    }
    else
    {
        ChipLogProgress(chipTool, "Pairing Failure: %s", ErrorStr(err));
    }

    if (err != CHIP_NO_ERROR)
    {
        SetCommandExitStatus(err);
    }
}

void PairingCommand::OnPairingDeleted(CHIP_ERROR err)
{
    if (err == CHIP_NO_ERROR)
    {
        ChipLogProgress(chipTool, "Pairing Deleted Success");
    }
    else
    {
        ChipLogProgress(chipTool, "Pairing Deleted Failure: %s", ErrorStr(err));
    }

    SetCommandExitStatus(err);
}

void PairingCommand::OnCommissioningComplete(NodeId nodeId, CHIP_ERROR err)
{
    if (err == CHIP_NO_ERROR)
    {
        ChipLogProgress(chipTool, "Device commissioning completed with success");
    }
    else
    {
        ChipLogProgress(chipTool, "Device commissioning Failure: %s", ErrorStr(err));
    }

    SetCommandExitStatus(err);
}

void PairingCommand::OnDiscoveredDevice(const chip::Dnssd::DiscoveredNodeData & nodeData)
{
    // Ignore nodes with closed comissioning window
    VerifyOrReturn(nodeData.commissioningMode != 0);

    const uint16_t port = nodeData.port;
    char buf[chip::Inet::IPAddress::kMaxStringLength];
    nodeData.ipAddress[0].ToString(buf);
    ChipLogProgress(chipTool, "Discovered Device: %s:%u", buf, port);

    // Stop Mdns discovery. Is it the right method ?
    CurrentCommissioner().RegisterDeviceDiscoveryDelegate(nullptr);

    Inet::InterfaceId interfaceId = nodeData.ipAddress[0].IsIPv6LinkLocal() ? nodeData.interfaceId : Inet::InterfaceId::Null();
    PeerAddress peerAddress       = PeerAddress::UDP(nodeData.ipAddress[0], port, interfaceId);
    CHIP_ERROR err                = Pair(mNodeId, peerAddress);
    if (CHIP_NO_ERROR != err)
    {
        SetCommandExitStatus(err);
    }
}
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2011 Heiko Strathmann
 * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
 */

#include <shogun/base/init.h>
#include <shogun/base/ParameterMap.h>

using namespace shogun;

void print_message(FILE* target, const char* str)
{
	fprintf(target, "%s", str);
}

void print_value(CSGParamInfo* key, CParameterMap* map)
{
	CSGParamInfo* current=map->get(key);
	SG_SPRINT("key: ");
	key->print();
	SG_SPRINT("value: ");

	if (current)
		current->print();
	else
		SG_SPRINT("no element\n");

	SG_SPRINT("\n");

	SG_UNREF(current);
}

int main(int argc, char **argv)
{
	init_shogun(&print_message, &print_message, &print_message);

	CParameterMap* map=new CParameterMap();

	EContainerType cfrom=CT_SCALAR;
	EContainerType cto=CT_MATRIX;

	EStructType sfrom=ST_NONE;
	EStructType sto=ST_STRING;

	EPrimitiveType pfrom=PT_BOOL;
	EPrimitiveType pto=PT_SGOBJECT;

	map->put(new CSGParamInfo("1", cfrom, sfrom, pfrom),
			new CSGParamInfo("eins", cto, sto, pto));
	map->put(new CSGParamInfo("2", cfrom, sfrom, pfrom),
			new CSGParamInfo("zwei", cto, sto, pto));
	map->put(new CSGParamInfo("3", cfrom, sfrom, pfrom),
			new CSGParamInfo("drei", cto, sto, pto));
	map->put(new CSGParamInfo("4", cfrom, sfrom, pfrom),
			new CSGParamInfo("vier", cto, sto, pto));

	CSGParamInfo* key;

	key=new CSGParamInfo("1", cfrom, sfrom, pfrom);
	print_value(key, map);
	SG_UNREF(key);

	key=new CSGParamInfo("2", cfrom, sfrom, pfrom);
	print_value(key, map);
	SG_UNREF(key);

	key=new CSGParamInfo("2", cto, sfrom, pfrom);
	print_value(key, map);
	SG_UNREF(key);

	key=new CSGParamInfo("2", cfrom, sto, pfrom);
	print_value(key, map);
	SG_UNREF(key);

	key=new CSGParamInfo("2", cfrom, sfrom, pto);
	print_value(key, map);
	SG_UNREF(key);

	key=new CSGParamInfo("5", cfrom, sfrom, pfrom);
	print_value(key, map);
	SG_UNREF(key);

	SG_UNREF(map);

	exit_shogun();

	return 0;
}

<commit_msg>applied changes in parameter map to example<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2011 Heiko Strathmann
 * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
 */

#include <shogun/base/init.h>
#include <shogun/base/ParameterMap.h>

using namespace shogun;

void print_message(FILE* target, const char* str)
{
	fprintf(target, "%s", str);
}

void print_value(CSGParamInfo* key, CParameterMap* map)
{
	CSGParamInfo* current=map->get(key);
	key->print_param_info();
	SG_SPRINT("value: ");

	if (current)
		current->print_param_info();
	else
		SG_SPRINT("no element\n");

	SG_SPRINT("\n");

	SG_UNREF(current);
}

int main(int argc, char **argv)
{
	init_shogun(&print_message, &print_message, &print_message);

	CParameterMap* map=new CParameterMap();

	EContainerType cfrom=CT_SCALAR;
	EContainerType cto=CT_MATRIX;

	EStructType sfrom=ST_NONE;
	EStructType sto=ST_STRING;

	EPrimitiveType pfrom=PT_BOOL;
	EPrimitiveType pto=PT_SGOBJECT;

	map->put(new CSGParamInfo("2", cfrom, sfrom, pfrom),
			new CSGParamInfo("zwei", cto, sto, pto));
	map->put(new CSGParamInfo("1", cfrom, sfrom, pfrom),
			new CSGParamInfo("eins", cto, sto, pto));
	map->put(new CSGParamInfo("4", cfrom, sfrom, pfrom),
			new CSGParamInfo("vier", cto, sto, pto));
	map->put(new CSGParamInfo("3", cfrom, sfrom, pfrom),
			new CSGParamInfo("drei", cto, sto, pto));

	SG_SPRINT("before finalization:\n");
	map->print_map();
	map->finalize_map();

	SG_SPRINT("\n\nafter finalization:\n");
	map->print_map();

	CSGParamInfo* key;

	SG_SPRINT("\n\ntesting map\n");
	key=new CSGParamInfo("1", cfrom, sfrom, pfrom);
	SG_REF(key);
	print_value(key, map);
	SG_UNREF(key);

	key=new CSGParamInfo("2", cfrom, sfrom, pfrom);
	SG_REF(key);
	print_value(key, map);
	SG_UNREF(key);

	key=new CSGParamInfo("2", cto, sfrom, pfrom);
	SG_REF(key);
	print_value(key, map);
	SG_UNREF(key);

	key=new CSGParamInfo("2", cfrom, sto, pfrom);
	SG_REF(key);
	print_value(key, map);
	SG_UNREF(key);

	key=new CSGParamInfo("2", cfrom, sfrom, pto);
	SG_REF(key);
	print_value(key, map);
	SG_UNREF(key);

	key=new CSGParamInfo("5", cfrom, sfrom, pfrom);
	SG_REF(key);
	print_value(key, map);
	SG_UNREF(key);

	SG_UNREF(map);

	exit_shogun();

	return 0;
}

<|endoftext|>


<commit_before>//
// Copyright (c) 2018-2020, University of Edinburgh, University of Oxford
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  * Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of  nor the names of its contributors may be used to
//    endorse or promote products derived from this software without specific
//    prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//

#include <exotica_ik_solver/ik_solver.h>

REGISTER_MOTIONSOLVER_TYPE("IKSolver", exotica::IKSolver)

namespace exotica
{
void IKSolver::SpecifyProblem(PlanningProblemPtr pointer)
{
    if (pointer->type() != "exotica::UnconstrainedEndPoseProblem")
    {
        ThrowNamed("This IKSolver can't solve problem of type '" << pointer->type() << "'!");
    }
    MotionSolver::SpecifyProblem(pointer);
    prob_ = std::static_pointer_cast<UnconstrainedEndPoseProblem>(pointer);

    W_inv_ = prob_->W.inverse();

    // Check dimension of W_ as this is a public member of the problem, and thus, can be edited by error.
    if (W_inv_.rows() != prob_->N || W_inv_.cols() != prob_->N)
        ThrowNamed("Size of W incorrect: (" << W_inv_.rows() << ", " << W_inv_.cols() << "), when expected: (" << prob_->N << ", " << prob_->N << ")");

    // Warn if deprecated MaxStep configuration detected:
    if (parameters_.MaxStep != 0.0 && GetNumberOfMaxIterations() != 1)
        WARNING_NAMED("IKSolver", "Deprecated configuration detected: MaxStep (given: " << parameters_.MaxStep << ") only works if MaxIterations == 1 (given: " << GetNumberOfMaxIterations() << ")");

    // Set up backtracking line-search coefficients
    alpha_space_ = Eigen::VectorXd::LinSpaced(10, 1.0, 0.1);

    lambda_ = parameters_.RegularizationRate;
    th_stepinc_ = parameters_.ThresholdRegularizationIncrease;
    th_stepdec_ = parameters_.ThresholdRegularizationDecrease;

    th_stop_ = parameters_.GradientToleranceConvergenceThreshold;

    // Allocate variables
    q_.resize(prob_->N);
    qd_.resize(prob_->N);
    yd_.resize(prob_->cost.length_jacobian);
    cost_jacobian_.resize(prob_->cost.length_jacobian, prob_->N);
    J_pseudo_inverse_.resize(prob_->N, prob_->cost.length_jacobian);
    J_tmp_.resize(prob_->cost.length_jacobian, prob_->cost.length_jacobian);
}

void IKSolver::Solve(Eigen::MatrixXd& solution)
{
    if (!prob_) ThrowNamed("Solver has not been initialized!");

    Timer timer;

    prob_->ResetCostEvolution(GetNumberOfMaxIterations() + 1);
    lambda_ = parameters_.RegularizationRate;
    q_ = prob_->ApplyStartState();

    if (prob_->q_nominal.rows() == prob_->N)
    {
        WARNING("Nominal state regularization is no longer supported - please use a JointPose task-map.");
    }

    int i;
    for (i = 0; i < GetNumberOfMaxIterations(); ++i)
    {
        prob_->Update(q_);
        error_ = prob_->GetScalarCost();
        prob_->SetCostEvolution(i, error_);

        // Absolute function tolerance check
        if (error_ < parameters_.Tolerance)
        {
            prob_->termination_criterion = TerminationCriterion::FunctionTolerance;
            break;
        }

        yd_.noalias() = prob_->cost.S * prob_->cost.ydiff;
        cost_jacobian_.noalias() = prob_->cost.S * prob_->cost.jacobian;

        // Weighted Regularized Pseudo-Inverse
        //   J_pseudo_inverse_ = W_inv_ * cost_jacobian_.transpose() * ( cost_jacobian_ * W_inv_ * cost_jacobian_.transpose() + C_ ).inverse();

        bool decomposition_ok = false;
        while (!decomposition_ok)
        {
            J_tmp_.noalias() = cost_jacobian_ * W_inv_ * cost_jacobian_.transpose();
            J_tmp_.diagonal().array() += lambda_;  // Add regularisation
            J_decomposition_.compute(J_tmp_);
            if (J_decomposition_.info() != Eigen::Success)
            {
                IncreaseRegularization();
                if (lambda_ > parameters_.MaximumRegularization)
                {
                    WARNING("Divergence in Cholesky decomposition :-(");
                    prob_->termination_criterion = TerminationCriterion::Divergence;
                    break;
                }
                // ThrowPretty("Error during matrix decomposition of J_tmp_ (lambda=" << lambda_ << "):\n"
                //                                                                 << J_tmp_);
            }
            else
            {
                decomposition_ok = true;
            }
        }
        J_tmp_.noalias() = J_decomposition_.solve(Eigen::MatrixXd::Identity(prob_->cost.length_jacobian, prob_->cost.length_jacobian));  // Inverse
        J_pseudo_inverse_.noalias() = W_inv_ * cost_jacobian_.transpose() * J_tmp_;

        qd_.noalias() = J_pseudo_inverse_ * yd_;

        // Support for a maximum step, e.g., when used as real-time, interactive IK
        if (GetNumberOfMaxIterations() == 1 && parameters_.MaxStep != 0.0)
        {
            ScaleToStepSize(qd_);
        }

        // Line search
        for (int ai = 0; ai < alpha_space_.size(); ++ai)
        {
            steplength_ = alpha_space_(ai);
            Eigen::VectorXd q_tmp = q_ - steplength_ * qd_;
            prob_->Update(q_tmp);
            if (prob_->GetScalarCost() < error_)
            {
                q_ = q_tmp;
                qd_ *= steplength_;
                break;
            }
        }

        // Step tolerance parameter
        step_ = qd_.squaredNorm();

        // Gradient tolerance
        stop_ = cost_jacobian_.norm();

        // Debug output
        if (debug_) PrintDebug(i);

        // Check step tolerance
        if (step_ < parameters_.StepToleranceConvergenceThreshold)
        {
            prob_->termination_criterion = TerminationCriterion::StepTolerance;
            break;
        }

        // Check gradient tolerance (convergence)
        if (stop_ < parameters_.GradientToleranceConvergenceThreshold)
        {
            prob_->termination_criterion = TerminationCriterion::GradientTolerance;
            break;
        }

        // Adapt regularization based on step-length
        if (steplength_ > th_stepdec_)
        {
            DecreaseRegularization();
        }
        if (steplength_ <= th_stepinc_)
        {
            IncreaseRegularization();
            if (lambda_ == regmax_)
            {
                prob_->termination_criterion = TerminationCriterion::Divergence;
                break;
            }
        }
    }

    // Check if we ran out of iterations
    if (i == GetNumberOfMaxIterations())
    {
        prob_->termination_criterion = TerminationCriterion::IterationLimit;
    }
    else
    {
        if (debug_) PrintDebug(i);
    }

    if (debug_)
    {
        switch (prob_->termination_criterion)
        {
            case TerminationCriterion::GradientTolerance:
                HIGHLIGHT_NAMED("IKSolver", "Reached convergence (" << std::scientific << stop_ << " < " << parameters_.GradientToleranceConvergenceThreshold << ")");
                break;
            case TerminationCriterion::FunctionTolerance:
                HIGHLIGHT_NAMED("IKSolver", "Reached absolute function tolerance (" << std::scientific << error_ << " < " << parameters_.Tolerance << ")");
                break;
            case TerminationCriterion::StepTolerance:
                HIGHLIGHT_NAMED("IKSolver", "Reached step tolerance (" << std::scientific << step_ << " < " << parameters_.StepToleranceConvergenceThreshold << ")");
                break;
            case TerminationCriterion::Divergence:
                WARNING_NAMED("IKSolver", "Regularization exceeds maximum regularization: " << lambda_ << " > " << regmax_);
                break;
            case TerminationCriterion::IterationLimit:
                HIGHLIGHT_NAMED("IKSolver", "Reached iteration limit.");
                break;

            default:
                break;
        }
    }

    solution.resize(1, prob_->N);
    solution.row(0) = q_.transpose();
    planning_time_ = timer.GetDuration();
}

void IKSolver::ScaleToStepSize(Eigen::VectorXdRef xd)
{
    const double max_vel = xd.cwiseAbs().maxCoeff();
    if (max_vel > parameters_.MaxStep)
    {
        xd = xd * parameters_.MaxStep / max_vel;
    }
}
}  // namespace exotica
<commit_msg>[exotica_ik_solver] Do not exit for high regularisation<commit_after>//
// Copyright (c) 2018-2020, University of Edinburgh, University of Oxford
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  * Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of  nor the names of its contributors may be used to
//    endorse or promote products derived from this software without specific
//    prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//

#include <exotica_ik_solver/ik_solver.h>

REGISTER_MOTIONSOLVER_TYPE("IKSolver", exotica::IKSolver)

namespace exotica
{
void IKSolver::SpecifyProblem(PlanningProblemPtr pointer)
{
    if (pointer->type() != "exotica::UnconstrainedEndPoseProblem")
    {
        ThrowNamed("This IKSolver can't solve problem of type '" << pointer->type() << "'!");
    }
    MotionSolver::SpecifyProblem(pointer);
    prob_ = std::static_pointer_cast<UnconstrainedEndPoseProblem>(pointer);

    W_inv_ = prob_->W.inverse();

    // Check dimension of W_ as this is a public member of the problem, and thus, can be edited by error.
    if (W_inv_.rows() != prob_->N || W_inv_.cols() != prob_->N)
        ThrowNamed("Size of W incorrect: (" << W_inv_.rows() << ", " << W_inv_.cols() << "), when expected: (" << prob_->N << ", " << prob_->N << ")");

    // Warn if deprecated MaxStep configuration detected:
    if (parameters_.MaxStep != 0.0 && GetNumberOfMaxIterations() != 1)
        WARNING_NAMED("IKSolver", "Deprecated configuration detected: MaxStep (given: " << parameters_.MaxStep << ") only works if MaxIterations == 1 (given: " << GetNumberOfMaxIterations() << ")");

    // Set up backtracking line-search coefficients
    alpha_space_ = Eigen::VectorXd::LinSpaced(10, 1.0, 0.1);

    lambda_ = parameters_.RegularizationRate;
    th_stepinc_ = parameters_.ThresholdRegularizationIncrease;
    th_stepdec_ = parameters_.ThresholdRegularizationDecrease;

    th_stop_ = parameters_.GradientToleranceConvergenceThreshold;

    // Allocate variables
    q_.resize(prob_->N);
    qd_.resize(prob_->N);
    yd_.resize(prob_->cost.length_jacobian);
    cost_jacobian_.resize(prob_->cost.length_jacobian, prob_->N);
    J_pseudo_inverse_.resize(prob_->N, prob_->cost.length_jacobian);
    J_tmp_.resize(prob_->cost.length_jacobian, prob_->cost.length_jacobian);
}

void IKSolver::Solve(Eigen::MatrixXd& solution)
{
    if (!prob_) ThrowNamed("Solver has not been initialized!");

    Timer timer;

    prob_->ResetCostEvolution(GetNumberOfMaxIterations() + 1);
    lambda_ = parameters_.RegularizationRate;
    q_ = prob_->ApplyStartState();

    if (prob_->q_nominal.rows() == prob_->N)
    {
        WARNING("Nominal state regularization is no longer supported - please use a JointPose task-map.");
    }

    int i;
    for (i = 0; i < GetNumberOfMaxIterations(); ++i)
    {
        prob_->Update(q_);
        error_ = prob_->GetScalarCost();
        prob_->SetCostEvolution(i, error_);

        // Absolute function tolerance check
        if (error_ < parameters_.Tolerance)
        {
            prob_->termination_criterion = TerminationCriterion::FunctionTolerance;
            break;
        }

        yd_.noalias() = prob_->cost.S * prob_->cost.ydiff;
        cost_jacobian_.noalias() = prob_->cost.S * prob_->cost.jacobian;

        // Weighted Regularized Pseudo-Inverse
        //   J_pseudo_inverse_ = W_inv_ * cost_jacobian_.transpose() * ( cost_jacobian_ * W_inv_ * cost_jacobian_.transpose() + C_ ).inverse();

        bool decomposition_ok = false;
        while (!decomposition_ok)
        {
            J_tmp_.noalias() = cost_jacobian_ * W_inv_ * cost_jacobian_.transpose();
            J_tmp_.diagonal().array() += lambda_;  // Add regularisation
            J_decomposition_.compute(J_tmp_);
            if (J_decomposition_.info() != Eigen::Success)
            {
                IncreaseRegularization();
                if (lambda_ > parameters_.MaximumRegularization)
                {
                    WARNING("Divergence in Cholesky decomposition :-(");
                    prob_->termination_criterion = TerminationCriterion::Divergence;
                    break;
                }
                // ThrowPretty("Error during matrix decomposition of J_tmp_ (lambda=" << lambda_ << "):\n"
                //                                                                 << J_tmp_);
            }
            else
            {
                decomposition_ok = true;
            }
        }
        J_tmp_.noalias() = J_decomposition_.solve(Eigen::MatrixXd::Identity(prob_->cost.length_jacobian, prob_->cost.length_jacobian));  // Inverse
        J_pseudo_inverse_.noalias() = W_inv_ * cost_jacobian_.transpose() * J_tmp_;

        qd_.noalias() = J_pseudo_inverse_ * yd_;

        // Support for a maximum step, e.g., when used as real-time, interactive IK
        if (GetNumberOfMaxIterations() == 1 && parameters_.MaxStep != 0.0)
        {
            ScaleToStepSize(qd_);
        }

        // Line search
        for (int ai = 0; ai < alpha_space_.size(); ++ai)
        {
            steplength_ = alpha_space_(ai);
            Eigen::VectorXd q_tmp = q_ - steplength_ * qd_;
            prob_->Update(q_tmp);
            if (prob_->GetScalarCost() < error_)
            {
                q_ = q_tmp;
                qd_ *= steplength_;
                break;
            }
        }

        // Step tolerance parameter
        step_ = qd_.squaredNorm();

        // Gradient tolerance
        stop_ = cost_jacobian_.norm();

        // Debug output
        if (debug_) PrintDebug(i);

        // Check step tolerance
        if (step_ < parameters_.StepToleranceConvergenceThreshold)
        {
            prob_->termination_criterion = TerminationCriterion::StepTolerance;
            break;
        }

        // Check gradient tolerance (convergence)
        if (stop_ < parameters_.GradientToleranceConvergenceThreshold)
        {
            prob_->termination_criterion = TerminationCriterion::GradientTolerance;
            break;
        }

        // Adapt regularization based on step-length
        if (steplength_ > th_stepdec_)
        {
            DecreaseRegularization();
        }
        if (steplength_ <= th_stepinc_)
        {
            IncreaseRegularization();
            // if (lambda_ == regmax_)
            // {
            //     prob_->termination_criterion = TerminationCriterion::Divergence;
            //     break;
            // }
        }
    }

    // Check if we ran out of iterations
    if (i == GetNumberOfMaxIterations())
    {
        prob_->termination_criterion = TerminationCriterion::IterationLimit;
    }
    else
    {
        if (debug_) PrintDebug(i);
    }

    if (debug_)
    {
        switch (prob_->termination_criterion)
        {
            case TerminationCriterion::GradientTolerance:
                HIGHLIGHT_NAMED("IKSolver", "Reached convergence (" << std::scientific << stop_ << " < " << parameters_.GradientToleranceConvergenceThreshold << ")");
                break;
            case TerminationCriterion::FunctionTolerance:
                HIGHLIGHT_NAMED("IKSolver", "Reached absolute function tolerance (" << std::scientific << error_ << " < " << parameters_.Tolerance << ")");
                break;
            case TerminationCriterion::StepTolerance:
                HIGHLIGHT_NAMED("IKSolver", "Reached step tolerance (" << std::scientific << step_ << " < " << parameters_.StepToleranceConvergenceThreshold << ")");
                break;
            case TerminationCriterion::Divergence:
                WARNING_NAMED("IKSolver", "Regularization exceeds maximum regularization: " << lambda_ << " > " << regmax_);
                break;
            case TerminationCriterion::IterationLimit:
                HIGHLIGHT_NAMED("IKSolver", "Reached iteration limit.");
                break;

            default:
                break;
        }
    }

    solution.resize(1, prob_->N);
    solution.row(0) = q_.transpose();
    planning_time_ = timer.GetDuration();
}

void IKSolver::ScaleToStepSize(Eigen::VectorXdRef xd)
{
    const double max_vel = xd.cwiseAbs().maxCoeff();
    if (max_vel > parameters_.MaxStep)
    {
        xd = xd * parameters_.MaxStep / max_vel;
    }
}
}  // namespace exotica
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: swuipardlg.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 10:06:05 $
 *
 *  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 _SWUI_PARDLG_HXX
#define _SWUI_PARDLG_HXX
#include "pardlg.hxx"

class SwParaDlg: public SfxTabDialog
{
    SwView& rView;
    USHORT nHtmlMode;
    BYTE nDlgMode;
    BOOL bDrawParaDlg;

    void PageCreated(USHORT nID, SfxTabPage& rPage);

public:
    SwParaDlg(  Window *pParent,
                SwView& rVw,
                const SfxItemSet&,
                BYTE nDialogMode,
                const String *pCollName = 0,
                BOOL bDraw = FALSE,
                UINT16 nDefPage = 0);
    ~SwParaDlg();
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.1202); FILE MERGED 2008/03/31 16:58:40 rt 1.4.1202.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: swuipardlg.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SWUI_PARDLG_HXX
#define _SWUI_PARDLG_HXX
#include "pardlg.hxx"

class SwParaDlg: public SfxTabDialog
{
    SwView& rView;
    USHORT nHtmlMode;
    BYTE nDlgMode;
    BOOL bDrawParaDlg;

    void PageCreated(USHORT nID, SfxTabPage& rPage);

public:
    SwParaDlg(  Window *pParent,
                SwView& rVw,
                const SfxItemSet&,
                BYTE nDialogMode,
                const String *pCollName = 0,
                BOOL bDraw = FALSE,
                UINT16 nDefPage = 0);
    ~SwParaDlg();
};

#endif
<|endoftext|>