text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "slider.h"
#include "qdebug.h"
#include "media/player.h"
#include "media/duration.h"
#include "misc/stylesheets.h"
Slider::Slider(QWidget * parent, bool isPositionSlider) : QSlider(parent) {
setMouseTracking(isPositionSlider);
position_slider = isPositionSlider;
fillColor = QColor::fromRgb(0,0,0);
// setToolTipDuration(1000);
setStyleSheet(Stylesheets::sliderStyles());
margin = 4;
}
//TODO: draw text by QStaticText
void Slider::paintEvent(QPaintEvent * event) {
QSlider::paintEvent(event);
if (!Settings::instance() -> isMetricShow())
return;
QPainter p(this);
p.save();
p.setPen(QColor::fromRgb(0, 0, 0));
QRect rect = this -> geometry();
QString strNum;
double limit, temp = 0, step = ((double)maximum()) / tickInterval();
int multiplyer = 0;
if (orientation() == Qt::Horizontal) {
rect.moveLeft(rect.left() + margin);
rect.setWidth(rect.width() - margin);
while(temp < 16) {
multiplyer++;
temp = ((float)(rect.width())) / (step / multiplyer);
}
step = temp;
limit = (rect.width() / step) == 0 ? rect.width() - step : rect.width();
int bottom = rect.bottom() - 7, h = (rect.height() / 3) - 3;
double val = multiplyer;
for(double pos = step; pos < limit; pos += step, val += multiplyer) {
strNum = QString::number(val);
p.drawLine(pos, bottom - h, pos, bottom);
if (position_slider)
p.drawText(pos - 7 * strNum.length() , bottom, strNum);
}
if (position_slider) {
float pos = Player::instance() -> getRemoteFileDownloadPosition();
if (Player::instance() -> getSize() > 0 && pos < 1) {
p.drawRect(rect.x(), rect.y(), rect.width() - 1, 3);
p.fillRect(rect.x(), rect.y(), (rect.width() - 1) * pos, 3, fillColor);
}
}
} else {
rect.moveTop(rect.top() + margin);
rect.setHeight(rect.height() - margin);
while(temp < 16) {
multiplyer++;
temp = ((float)(rect.height())) / (step / multiplyer);
}
step = temp;
limit = (rect.height() / step) == 0 ? rect.height() - step : rect.height();
int temp, left = rect.left() + 4, w = (rect.width() / 3) - 3;
double val = multiplyer;
for(double pos = step - margin; pos < limit; pos += step, val += multiplyer) {
strNum = QString::number(val);
temp = rect.height() - pos;
p.drawLine(left, temp, left + w, temp);
if (position_slider)
p.drawText(left, temp + 10, strNum);
}
if (position_slider) {
float pos = Player::instance() -> getRemoteFileDownloadPosition();
if (Player::instance() -> getSize() > 0 && pos < 1) {
p.drawRect(rect.x(), rect.y(), 3, rect.height() - 1);
p.fillRect(rect.x(), rect.height(), 3, -((rect.height() - 1) * pos), fillColor);
}
}
}
p.restore();
}
void Slider::mouseMoveEvent(QMouseEvent * ev) {
if (hasMouseTracking()) {
QPointF p = ev -> localPos();
bool show = false;
int dur;
if (orientation() == Qt::Vertical) {
if ((show = (p.y() > margin && p.y() < height() - margin)))
dur = maximum() *((height() - margin - p.y()) / (height() - 2 * margin));
} else {
if ((show = (p.x() > margin && p.x() < width() - margin)))
dur = maximum() * ((p.x() - margin) / (width() - 2 * margin));
}
if (show)
QToolTip::showText(ev -> globalPos(), Duration::fromMillis(dur));
}
QSlider::mouseMoveEvent(ev);
}
<commit_msg>updates<commit_after>#include "slider.h"
#include "qdebug.h"
#include "media/player.h"
#include "media/duration.h"
#include "misc/stylesheets.h"
Slider::Slider(QWidget * parent, bool isPositionSlider) : QSlider(parent) {
setMouseTracking(isPositionSlider);
position_slider = isPositionSlider;
fillColor = QColor::fromRgb(0,0,0);
// setToolTipDuration(1000);
setStyleSheet(Stylesheets::sliderStyles());
margin = 4;
}
//TODO: draw text by QStaticText
void Slider::paintEvent(QPaintEvent * event) {
QSlider::paintEvent(event);
if (!Settings::instance() -> isMetricShow())
return;
QPainter p(this);
p.save();
p.setPen(QColor::fromRgb(0, 0, 0));
QRect rect = this -> geometry();
QString strNum;
double limit, temp = 0, step = ((double)maximum()) / tickInterval();
int multiplyer = 0;
if (orientation() == Qt::Horizontal) {
rect.moveLeft(rect.left() + margin);
rect.setWidth(rect.width() - margin);
while(temp < 16) {
multiplyer++;
temp = ((float)(rect.width())) / (step / multiplyer);
}
step = temp;
limit = (rect.width() / step) == 0 ? rect.width() - step : rect.width();
int bottom = rect.bottom() - 7, h = (rect.height() / 3) - 3;
double val = multiplyer;
for(double pos = step; pos < limit; pos += step, val += multiplyer) {
strNum = QString::number(val);
p.drawLine(pos, bottom - h, pos, bottom);
if (position_slider)
p.drawText(pos - 7 * strNum.length() , bottom, strNum);
}
if (position_slider) {
float pos = Player::instance() -> getRemoteFileDownloadPosition();
if (Player::instance() -> getSize() > 0 && pos < 1) {
p.drawRect(margin, rect.y(), rect.width() - margin - 1, 3);
p.fillRect(margin, rect.y(), (rect.width() - margin - 1) * pos, 3, fillColor);
}
}
} else {
rect.moveTop(rect.top() + margin);
rect.setHeight(rect.height() - margin);
while(temp < 16) {
multiplyer++;
temp = ((float)(rect.height())) / (step / multiplyer);
}
step = temp;
limit = (rect.height() / step) == 0 ? rect.height() - step : rect.height();
int temp, left = rect.left() + 4, w = (rect.width() / 3) - 3;
double val = multiplyer;
for(double pos = step - margin; pos < limit; pos += step, val += multiplyer) {
strNum = QString::number(val);
temp = rect.height() - pos;
p.drawLine(left, temp, left + w, temp);
if (position_slider)
p.drawText(left, temp + 10, strNum);
}
if (position_slider) {
float pos = Player::instance() -> getRemoteFileDownloadPosition();
if (Player::instance() -> getSize() > 0 && pos < 1) {
p.drawRect(rect.x(), margin, 3, rect.height() - margin - 1);
p.fillRect(rect.x(), rect.height(), 3, -((rect.height() - margin - 1) * pos), fillColor);
}
}
}
p.restore();
}
void Slider::mouseMoveEvent(QMouseEvent * ev) {
if (hasMouseTracking()) {
QPointF p = ev -> localPos();
bool show = false;
int dur;
if (orientation() == Qt::Vertical) {
if ((show = (p.y() > margin && p.y() < height() - margin)))
dur = maximum() *((height() - margin - p.y()) / (height() - 2 * margin));
} else {
if ((show = (p.x() > margin && p.x() < width() - margin)))
dur = maximum() * ((p.x() - margin) / (width() - 2 * margin));
}
if (show)
QToolTip::showText(ev -> globalPos(), Duration::fromMillis(dur));
}
QSlider::mouseMoveEvent(ev);
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Solutions Commercial License Agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** Please note Third Party Software included with Qt Solutions may impose
** additional restrictions and it is the user's responsibility to ensure
** that they have met the licensing requirements of the GPL, LGPL, or Qt
** Solutions Commercial license and the relevant license of the Third
** Party Software they are using.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qlandmarkabstractrequest.h"
#include "qlandmarkabstractrequest_p.h"
#include "qlandmarkmanagerengine.h"
#include "qlandmarkmanager_p.h"
#include <QDebug>
#include <QMutexLocker>
QTM_USE_NAMESPACE
QLandmarkAbstractRequestPrivate::QLandmarkAbstractRequestPrivate(QLandmarkManager *mgr)
: type(QLandmarkAbstractRequest::InvalidRequest),
state(QLandmarkAbstractRequest::InactiveState),
error(QLandmarkManager::NoError),
errorString(QString()),
manager(mgr)
{
}
/*!
\class QLandmarkAbstractRequest
\brief The QLandmarkAbstractRequest class provides the interface
from which all asynchronous request classes inherit.
\inmodule QtLocation
\ingroup landmarks-request
It allows a client to asynchronously request some functionality of a
particular QLandmarkManager. Instances of the class will emit signals when
the state of the request changes, or when more results become available.
Clients should not attempt to create instances of this class directly, but
should instead use the use-case-specific classes derived from this class.
All such request classes have a similar interface: clients set the
parameters of the asynchronous call, then call the start() slot of the request. The manager
will then enqueue or begin to process the request, at which point the
request's state will transition from the \c InactiveState to \c ActiveState.
After any state transition, the request will emit the stateChanged()
signal. The manager may (if it supports it)
periodically update the request with results, at
which point the request will emit the resultsAvailable() signal. These
results are not guaranteed to have a stable ordering. Error information is
considered a result, so some requests will emit the resultsAvailable()
signal even if no results are possible from the request (for example, a
landmark remove request) when the manager updates the request with
information about any errors which may have occurred.
Clients can choose which signals they wish to handle from a request. If the
client is not interested in interim results, they can choose to handle only
the stateChanged() signal, and in the slot to which that signal is
connected, check whether the state has changed to the \c FinishedState
(which signifies that the manager has finished handling the request, and
that the request will not be updated with any more results). If the client
is not interested in any results (including error information), they may
choose to delete the request after calling \l start(), or simply not
connect the request's signals to any slots.
If the request is allocated via operator new, the client must delete the
request when they are no longer using it in order to avoid leaking memory.
That is, the client retains ownership of the request.
The client may delete a heap-allocated request in various ways: by deleting
it directly (but not within a slot connected to a signal emitted by the
request), or by using the deleteLater() slot to schedule the request for
deletion when control returns to the event loop (from within a slot
connected to a signal emitted by the request, for example \l
stateChanged()).
An active request may be deleted by the client, but the client will not
receive any notifications about whether the request succeeded or not,
nor any results of the request.
Because clients retain ownership of any request object, and may delete a
request object at any time, manager engine implementors must be careful to
ensure that they do not assume that a request has not been deleted at some
point during processing of a request, particularly if the engine has a
multithreaded implementation.
*/
QLandmarkAbstractRequestPrivate::~QLandmarkAbstractRequestPrivate()
{
}
void QLandmarkAbstractRequestPrivate::notifyEngine(QLandmarkAbstractRequest* request)
{
Q_ASSERT(request);
QLandmarkAbstractRequestPrivate* d = request->d_ptr;
if (d) {
QMutexLocker ml(&d->mutex);
QLandmarkManagerEngine *engine = QLandmarkManagerPrivate::getEngine(d->manager);
ml.unlock();
if (engine) {
engine->requestDestroyed(request);
}
}
}
/*!
\enum QLandmarkAbstractRequest::RequestType
Defines the possible types of asynchronous requests.
\value InvalidRequest An invalid request
\value LandmarkIdFetchRequest A request to fetch a list of landmark
identifiers.
\value CategoryIdFetchRequest A request to fetch a list of catgory
identifiers.
\value LandmarkFetchRequest A request to fetch a list of landmarks
\value LandmarkFetchByIdRequest A request to fetch a list of landmarks by id.
\value CategoryFetchRequest A request to fetch a list of categories
\value CategoryFetchByIdRequest A request to fetch a list of categories by id
\value LandmarkSaveRequest A request to save a list of landmarks.
\value LandmarkRemoveRequest A request to remove a list of landmarks.
\value CategorySaveRequest A request to save a list of categories.
\value CategoryRemoveRequest A request to remove a list of categories.
\value ImportRequest A request import landmarks.
\value ExportRequest A request export landmarks.
*/
/*!
\enum QLandmarkAbstractRequest::State
Defines the possible states of asynchronous requests.
\value InactiveState Operation not yet started.
\value ActiveState Operation started, not yet finished.
\value FinishedState Operation completed. (Can be mean either successful or
unsuccessful completion).
*/
/*!
Constructs a new, invalid asynchronous request with the given \a manager and \a parent.
*/
QLandmarkAbstractRequest::QLandmarkAbstractRequest(QLandmarkManager *manager, QObject *parent)
: QObject(parent),
d_ptr(new QLandmarkAbstractRequestPrivate(manager))
{
}
/*!
\internal
*/
QLandmarkAbstractRequest::QLandmarkAbstractRequest(QLandmarkAbstractRequestPrivate *dd, QObject *parent)
: QObject(parent),
d_ptr(dd)
{
}
/*!
Destroys the asynchronous request. Because the request object is effectively a handle to
a request operation, the operation may continue or it may be canceled, depending upon
the engine implementation, even though the request object itself has been destroyed.
*/
QLandmarkAbstractRequest::~QLandmarkAbstractRequest()
{
QLandmarkAbstractRequestPrivate::notifyEngine(this);
delete d_ptr;
}
/*!
Returns the type of this asynchronous request.
*/
QLandmarkAbstractRequest::RequestType QLandmarkAbstractRequest::type() const
{
QMutexLocker ml(&d_ptr->mutex);
return d_ptr->type;
}
/*!
Returns the state of the request
*/
QLandmarkAbstractRequest::State QLandmarkAbstractRequest::state()
{
QMutexLocker ml(&d_ptr->mutex);
return d_ptr->state;
}
/*!
Returns true if the request is in the \c QLandmarkAbstractRequest::Inactive state;
otherwise, returns false.
\sa state()
*/
bool QLandmarkAbstractRequest::isInactive() const
{
QMutexLocker ml(&d_ptr->mutex);
return d_ptr->state == QLandmarkAbstractRequest::InactiveState;
}
/*!
Returns true if the request is in the \c QLandmarkAbstractRequest::Active state;
otherwise, returns false.
\sa state()
*/
bool QLandmarkAbstractRequest::isActive() const
{
QMutexLocker ml(&d_ptr->mutex);
return d_ptr->state == QLandmarkAbstractRequest::ActiveState;
}
/*!
Returns true if the request is in the \c QLandmarkAbstractRequest::Finished state;
otherwise, returns false.
\sa state()
*/
bool QLandmarkAbstractRequest::isFinished() const
{
QMutexLocker ml(&d_ptr->mutex);
return d_ptr->state == QLandmarkAbstractRequest::FinishedState;
}
/*!
Returns the overall error of the most recent asynchronous operation.
\sa errorString()
*/
QLandmarkManager::Error QLandmarkAbstractRequest::error() const
{
QMutexLocker ml(&d_ptr->mutex);
return d_ptr->error;
}
/*!
Returns a human readable string of the last error
that occurred. This error string is intended to be used
by developers only and should not be seen by end users.
\sa error()
*/
QString QLandmarkAbstractRequest::errorString() const
{
QMutexLocker ml(&d_ptr->mutex);
return d_ptr->errorString;
}
/*!
Returns a pointer to the landmark manager which
this request operates on.
*/
QLandmarkManager *QLandmarkAbstractRequest::manager() const
{
QMutexLocker ml(&d_ptr->mutex);
return d_ptr->manager;
}
/*!
Sets the \a manager which this request operates on.
Note that if a NULL manager is set, the functions
start(), cancel() and waitForFinished() will return false and
error will be set to QLandmarkManager::InvalidManagerError.
A manager cannot be assigned while the request is in the
QLandmarkAbstractRequest::ActiveState.
*/
void QLandmarkAbstractRequest::setManager(QLandmarkManager *manager)
{
QMutexLocker ml(&d_ptr->mutex);
if (d_ptr->state == QLandmarkAbstractRequest::ActiveState && d_ptr->manager)
return;
d_ptr->manager = manager;
}
/*!
Attempts to start the request.
Returns true if the request was started, otherwise false. Trying to start a
request that is already active returns false.
\sa cancel().
*/
bool QLandmarkAbstractRequest::start()
{
QMutexLocker ml(&d_ptr->mutex);
if (!d_ptr->manager) {
d_ptr->error = QLandmarkManager::BadArgumentError;
d_ptr->errorString = "No manager assigned to landmark request object";
qWarning() << d_ptr->errorString;
return false;
}
QLandmarkManagerEngine *engine = d_ptr->manager->engine();
if (!engine) {
d_ptr->error = QLandmarkManager::InvalidManagerError;
d_ptr->errorString = "The manager is invalid";
return false;
}
if (d_ptr->state != QLandmarkAbstractRequest::ActiveState) {
ml.unlock();
return engine->startRequest(this);
}
else {
return false;
}
}
/*!
Notifies the request that it should be canceled.
Returns true if the request was successfully notified
that it should be canceled. The request may or may not honor
the cancel notification. Returns false if the notification
could not be made or the request is not in the
QLandmarkManager::Active state.
\sa start()
*/
bool QLandmarkAbstractRequest::cancel()
{
QMutexLocker ml(&d_ptr->mutex);
if (!d_ptr->manager) {
d_ptr->error = QLandmarkManager::BadArgumentError;
d_ptr->errorString = "No manager assigned to landmark request object";
qWarning() << d_ptr->errorString;
return false;
}
QLandmarkManagerEngine *engine = d_ptr->manager->engine();
if(d_ptr->state == QLandmarkAbstractRequest::ActiveState) {
ml.unlock();
return engine->cancelRequest(this);
}
else
return false;
}
/*!
Blocks until the request has been completed or until \a msecs milliseconds
has elapsed. If \a msecs is zero or negative, this function will block indefinitely.
Returns true if the request was canceled or completed
within the given period, otherwise returns false. Some backends may be unable
to support this operation safely and will return false immediately.
The sqlite backend does currently does not support waitForFinished.
Note that any signals generated while waiting for the request to be complete
may be queued and delivered sometime after this function has returned, when
the calling thread's event loop is dispatched. If your code depends on
your slots being invoked, you may need to process events after calling
this function.
*/
bool QLandmarkAbstractRequest::waitForFinished(int msecs)
{
QMutexLocker ml(&d_ptr->mutex);
if (!d_ptr->manager) {
d_ptr->error = QLandmarkManager::BadArgumentError;
d_ptr->errorString = "No manager assigned to landmark request object";
qWarning() << d_ptr->errorString;
return false;
}
QLandmarkManagerEngine *engine = d_ptr->manager->engine();
switch(d_ptr->state) {
case QLandmarkAbstractRequest::ActiveState:
ml.unlock();
return engine->waitForRequestFinished(this, msecs);
case QLandmarkAbstractRequest::FinishedState:
return true;
default:
return false;
}
return false;
}
/*!
\fn void QLandmarkAbstractRequest::resultsAvailable()
This signal is emitted when new results are available. Results
can include the operation error which may be accessed via error(),
or derived-class specific results which are accessible through
the derived class API.
\sa error()
*/
/*!
\fn void QLandmarkAbstractRequest::stateChanged(QLandmarkAbstractRequest::State newState)
This signal is emitted when the state of the request is changed. The new state of
the request will be contained in \a newState.
*/
#include "moc_qlandmarkabstractrequest.cpp"
<commit_msg>Fixes: MOBILITY-1762<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Solutions Commercial License Agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** Please note Third Party Software included with Qt Solutions may impose
** additional restrictions and it is the user's responsibility to ensure
** that they have met the licensing requirements of the GPL, LGPL, or Qt
** Solutions Commercial license and the relevant license of the Third
** Party Software they are using.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qlandmarkabstractrequest.h"
#include "qlandmarkabstractrequest_p.h"
#include "qlandmarkmanagerengine.h"
#include "qlandmarkmanager_p.h"
#include <QDebug>
#include <QMutexLocker>
QTM_USE_NAMESPACE
QLandmarkAbstractRequestPrivate::QLandmarkAbstractRequestPrivate(QLandmarkManager *mgr)
: type(QLandmarkAbstractRequest::InvalidRequest),
state(QLandmarkAbstractRequest::InactiveState),
error(QLandmarkManager::NoError),
errorString(QString()),
manager(mgr)
{
}
/*!
\class QLandmarkAbstractRequest
\brief The QLandmarkAbstractRequest class provides the interface
from which all asynchronous request classes inherit.
\inmodule QtLocation
\ingroup landmarks-request
It allows a client to asynchronously request some functionality of a
particular QLandmarkManager. Instances of the class will emit signals when
the state of the request changes, or when more results become available.
Clients should not attempt to create instances of this class directly, but
should instead use the use-case-specific classes derived from this class.
All such request classes have a similar interface: clients set the
parameters of the asynchronous call, then call the start() slot of the request. The manager
will then enqueue or begin to process the request, at which point the
request's state will transition from the \c InactiveState to \c ActiveState.
After any state transition, the request will emit the stateChanged()
signal. The manager may (if it supports it)
periodically update the request with results, at
which point the request will emit the resultsAvailable() signal. These
results are not guaranteed to have a stable ordering. Error information is
considered a result, so some requests will emit the resultsAvailable()
signal even if no results are possible from the request (for example, a
landmark remove request) when the manager updates the request with
information about any errors which may have occurred.
Clients can choose which signals they wish to handle from a request. If the
client is not interested in interim results, they can choose to handle only
the stateChanged() signal, and in the slot to which that signal is
connected, check whether the state has changed to the \c FinishedState
(which signifies that the manager has finished handling the request, and
that the request will not be updated with any more results).
If the request is allocated via operator new, the client must delete the
request when they are no longer using it in order to avoid leaking memory.
That is, the client retains ownership of the request.
The client may delete a heap-allocated request in various ways: by deleting
it directly (but not within a slot connected to a signal emitted by the
request), or by using the deleteLater() slot to schedule the request for
deletion when control returns to the event loop (from within a slot
connected to a signal emitted by the request, for example \l
stateChanged()).
Before a request is deleted it should always be in the
QLandmarkAbstractRequest::FinishedState or QLandmarkAbstractRequest::InactiveState.
A request should never been deleted whilst it is in the QLandmarkAbstractRequest::ActiveState.
*/
QLandmarkAbstractRequestPrivate::~QLandmarkAbstractRequestPrivate()
{
}
void QLandmarkAbstractRequestPrivate::notifyEngine(QLandmarkAbstractRequest* request)
{
Q_ASSERT(request);
QLandmarkAbstractRequestPrivate* d = request->d_ptr;
if (d) {
QMutexLocker ml(&d->mutex);
QLandmarkManagerEngine *engine = QLandmarkManagerPrivate::getEngine(d->manager);
ml.unlock();
if (engine) {
engine->requestDestroyed(request);
}
}
}
/*!
\enum QLandmarkAbstractRequest::RequestType
Defines the possible types of asynchronous requests.
\value InvalidRequest An invalid request
\value LandmarkIdFetchRequest A request to fetch a list of landmark
identifiers.
\value CategoryIdFetchRequest A request to fetch a list of catgory
identifiers.
\value LandmarkFetchRequest A request to fetch a list of landmarks
\value LandmarkFetchByIdRequest A request to fetch a list of landmarks by id.
\value CategoryFetchRequest A request to fetch a list of categories
\value CategoryFetchByIdRequest A request to fetch a list of categories by id
\value LandmarkSaveRequest A request to save a list of landmarks.
\value LandmarkRemoveRequest A request to remove a list of landmarks.
\value CategorySaveRequest A request to save a list of categories.
\value CategoryRemoveRequest A request to remove a list of categories.
\value ImportRequest A request import landmarks.
\value ExportRequest A request export landmarks.
*/
/*!
\enum QLandmarkAbstractRequest::State
Defines the possible states of asynchronous requests.
\value InactiveState Operation not yet started.
\value ActiveState Operation started, not yet finished.
\value FinishedState Operation completed. (Can be mean either successful or
unsuccessful completion).
*/
/*!
Constructs a new, invalid asynchronous request with the given \a manager and \a parent.
*/
QLandmarkAbstractRequest::QLandmarkAbstractRequest(QLandmarkManager *manager, QObject *parent)
: QObject(parent),
d_ptr(new QLandmarkAbstractRequestPrivate(manager))
{
}
/*!
\internal
*/
QLandmarkAbstractRequest::QLandmarkAbstractRequest(QLandmarkAbstractRequestPrivate *dd, QObject *parent)
: QObject(parent),
d_ptr(dd)
{
}
/*!
Destroys the asynchronous request. Ensure that the request is in the
QLandmarkAbstractRequest::FinishedState or QLandmarkAbstractRequest::InactiveState
before destroying it.
*/
QLandmarkAbstractRequest::~QLandmarkAbstractRequest()
{
QLandmarkAbstractRequestPrivate::notifyEngine(this);
delete d_ptr;
}
/*!
Returns the type of this asynchronous request.
*/
QLandmarkAbstractRequest::RequestType QLandmarkAbstractRequest::type() const
{
QMutexLocker ml(&d_ptr->mutex);
return d_ptr->type;
}
/*!
Returns the state of the request
*/
QLandmarkAbstractRequest::State QLandmarkAbstractRequest::state()
{
QMutexLocker ml(&d_ptr->mutex);
return d_ptr->state;
}
/*!
Returns true if the request is in the \c QLandmarkAbstractRequest::Inactive state;
otherwise, returns false.
\sa state()
*/
bool QLandmarkAbstractRequest::isInactive() const
{
QMutexLocker ml(&d_ptr->mutex);
return d_ptr->state == QLandmarkAbstractRequest::InactiveState;
}
/*!
Returns true if the request is in the \c QLandmarkAbstractRequest::Active state;
otherwise, returns false.
\sa state()
*/
bool QLandmarkAbstractRequest::isActive() const
{
QMutexLocker ml(&d_ptr->mutex);
return d_ptr->state == QLandmarkAbstractRequest::ActiveState;
}
/*!
Returns true if the request is in the \c QLandmarkAbstractRequest::Finished state;
otherwise, returns false.
\sa state()
*/
bool QLandmarkAbstractRequest::isFinished() const
{
QMutexLocker ml(&d_ptr->mutex);
return d_ptr->state == QLandmarkAbstractRequest::FinishedState;
}
/*!
Returns the overall error of the most recent asynchronous operation.
\sa errorString()
*/
QLandmarkManager::Error QLandmarkAbstractRequest::error() const
{
QMutexLocker ml(&d_ptr->mutex);
return d_ptr->error;
}
/*!
Returns a human readable string of the last error
that occurred. This error string is intended to be used
by developers only and should not be seen by end users.
\sa error()
*/
QString QLandmarkAbstractRequest::errorString() const
{
QMutexLocker ml(&d_ptr->mutex);
return d_ptr->errorString;
}
/*!
Returns a pointer to the landmark manager which
this request operates on.
*/
QLandmarkManager *QLandmarkAbstractRequest::manager() const
{
QMutexLocker ml(&d_ptr->mutex);
return d_ptr->manager;
}
/*!
Sets the \a manager which this request operates on.
Note that if a NULL manager is set, the functions
start(), cancel() and waitForFinished() will return false and
error will be set to QLandmarkManager::InvalidManagerError.
A manager cannot be assigned while the request is in the
QLandmarkAbstractRequest::ActiveState.
*/
void QLandmarkAbstractRequest::setManager(QLandmarkManager *manager)
{
QMutexLocker ml(&d_ptr->mutex);
if (d_ptr->state == QLandmarkAbstractRequest::ActiveState && d_ptr->manager)
return;
d_ptr->manager = manager;
}
/*!
Attempts to start the request.
Returns true if the request was started, otherwise false. Trying to start a
request that is already active returns false.
\sa cancel().
*/
bool QLandmarkAbstractRequest::start()
{
QMutexLocker ml(&d_ptr->mutex);
if (!d_ptr->manager) {
d_ptr->error = QLandmarkManager::BadArgumentError;
d_ptr->errorString = "No manager assigned to landmark request object";
qWarning() << d_ptr->errorString;
return false;
}
QLandmarkManagerEngine *engine = d_ptr->manager->engine();
if (!engine) {
d_ptr->error = QLandmarkManager::InvalidManagerError;
d_ptr->errorString = "The manager is invalid";
return false;
}
if (d_ptr->state != QLandmarkAbstractRequest::ActiveState) {
ml.unlock();
return engine->startRequest(this);
}
else {
return false;
}
}
/*!
Notifies the request that it should be canceled.
Returns true if the request was successfully notified
that it should be canceled. The request may or may not honor
the cancel notification. Returns false if the notification
could not be made or the request is not in the
QLandmarkManager::Active state.
\sa start()
*/
bool QLandmarkAbstractRequest::cancel()
{
QMutexLocker ml(&d_ptr->mutex);
if (!d_ptr->manager) {
d_ptr->error = QLandmarkManager::BadArgumentError;
d_ptr->errorString = "No manager assigned to landmark request object";
qWarning() << d_ptr->errorString;
return false;
}
QLandmarkManagerEngine *engine = d_ptr->manager->engine();
if(d_ptr->state == QLandmarkAbstractRequest::ActiveState) {
ml.unlock();
return engine->cancelRequest(this);
}
else
return false;
}
/*!
Blocks until the request has been completed or until \a msecs milliseconds
has elapsed. If \a msecs is zero or negative, this function will block indefinitely.
Returns true if the request was canceled or completed
within the given period, otherwise returns false. Some backends may be unable
to support this operation safely and will return false immediately.
The sqlite backend does currently does not support waitForFinished.
Note that any signals generated while waiting for the request to be complete
may be queued and delivered sometime after this function has returned, when
the calling thread's event loop is dispatched. If your code depends on
your slots being invoked, you may need to process events after calling
this function.
*/
bool QLandmarkAbstractRequest::waitForFinished(int msecs)
{
QMutexLocker ml(&d_ptr->mutex);
if (!d_ptr->manager) {
d_ptr->error = QLandmarkManager::BadArgumentError;
d_ptr->errorString = "No manager assigned to landmark request object";
qWarning() << d_ptr->errorString;
return false;
}
QLandmarkManagerEngine *engine = d_ptr->manager->engine();
switch(d_ptr->state) {
case QLandmarkAbstractRequest::ActiveState:
ml.unlock();
return engine->waitForRequestFinished(this, msecs);
case QLandmarkAbstractRequest::FinishedState:
return true;
default:
return false;
}
return false;
}
/*!
\fn void QLandmarkAbstractRequest::resultsAvailable()
This signal is emitted when new results are available. Results
can include the operation error which may be accessed via error(),
or derived-class specific results which are accessible through
the derived class API.
\sa error()
*/
/*!
\fn void QLandmarkAbstractRequest::stateChanged(QLandmarkAbstractRequest::State newState)
This signal is emitted when the state of the request is changed. The new state of
the request will be contained in \a newState.
*/
#include "moc_qlandmarkabstractrequest.cpp"
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "QGCQFileDialog.h"
#include "QGCApplication.h"
#include "MainWindow.h"
#ifdef UNITTEST_BUILD
#include "UnitTest.h"
#endif
#include <QRegularExpression>
#include <QMessageBox>
#include <QPushButton>
QString QGCQFileDialog::getExistingDirectory(
QWidget* parent,
const QString& caption,
const QString& dir,
Options options)
{
_validate(options);
#ifdef UNITTEST_BUILD
if (qgcApp()->runningUnitTests()) {
return UnitTest::_getExistingDirectory(parent, caption, dir, options);
} else
#endif
{
return QFileDialog::getExistingDirectory(parent, caption, dir, options);
}
}
QString QGCQFileDialog::getOpenFileName(
QWidget* parent,
const QString& caption,
const QString& dir,
const QString& filter,
Options options)
{
_validate(options);
#ifdef UNITTEST_BUILD
if (qgcApp()->runningUnitTests()) {
return UnitTest::_getOpenFileName(parent, caption, dir, filter, options);
} else
#endif
{
return QFileDialog::getOpenFileName(parent, caption, dir, filter, NULL, options);
}
}
QStringList QGCQFileDialog::getOpenFileNames(
QWidget* parent,
const QString& caption,
const QString& dir,
const QString& filter,
Options options)
{
_validate(options);
#ifdef UNITTEST_BUILD
if (qgcApp()->runningUnitTests()) {
return UnitTest::_getOpenFileNames(parent, caption, dir, filter, options);
} else
#endif
{
return QFileDialog::getOpenFileNames(parent, caption, dir, filter, NULL, options);
}
}
QString QGCQFileDialog::getSaveFileName(
QWidget* parent,
const QString& caption,
const QString& dir,
const QString& filter,
const QString& defaultSuffix,
bool strict,
Options options)
{
_validate(options);
#ifdef UNITTEST_BUILD
if (qgcApp()->runningUnitTests()) {
return UnitTest::_getSaveFileName(parent, caption, dir, filter, defaultSuffix, options);
} else
#endif
{
QString defaultSuffixCopy(defaultSuffix);
QFileDialog dlg(parent, caption, dir, filter);
dlg.setAcceptMode(QFileDialog::AcceptSave);
if (options) {
dlg.setOptions(options);
}
if (!defaultSuffixCopy.isEmpty()) {
//-- Make sure dot is not present
if (defaultSuffixCopy.startsWith(".")) {
defaultSuffixCopy.remove(0,1);
}
dlg.setDefaultSuffix(defaultSuffixCopy);
}
while (true) {
if (dlg.exec()) {
if (dlg.selectedFiles().count()) {
QString result = dlg.selectedFiles().first();
//-- If we don't care about the extension, just return it
if (!strict) {
return result;
} else {
//-- We must enforce the file extension
QFileInfo fi(result);
QString userSuffix(fi.suffix());
if (_validateExtension(filter, userSuffix)) {
return result;
}
//-- Do we have a default extension?
if (defaultSuffixCopy.isEmpty()) {
//-- We don't, so get the first one in the filter
defaultSuffixCopy = _getFirstExtensionInFilter(filter);
}
//-- If this is set to strict, we have to have a default extension
if (defaultSuffixCopy.isEmpty()) {
qWarning() << "Internal error";
}
//-- Forcefully append our desired extension
result += ".";
result += defaultSuffixCopy;
//-- Check and see if this new file already exists
fi.setFile(result);
if (fi.exists()) {
//-- Ask user what to do
QMessageBox msgBox(
QMessageBox::Warning,
tr("File Exists"),
tr("%1 already exists.\nDo you want to replace it?").arg(fi.fileName()),
QMessageBox::Cancel,
parent);
msgBox.addButton(QMessageBox::Retry);
QPushButton *overwriteButton = msgBox.addButton(tr("Replace"), QMessageBox::ActionRole);
msgBox.setDefaultButton(QMessageBox::Retry);
msgBox.setWindowModality(Qt::ApplicationModal);
if (msgBox.exec() == QMessageBox::Retry) {
continue;
} else if (msgBox.clickedButton() == overwriteButton) {
return result;
}
} else {
return result;
}
}
}
}
break;
}
return QString("");
}
}
/// @brief Make sure filename is using one of the valid extensions defined in the filter
bool QGCQFileDialog::_validateExtension(const QString& filter, const QString& extension) {
QRegularExpression re("(\\*\\.\\w+)");
QRegularExpressionMatchIterator i = re.globalMatch(filter);
while (i.hasNext()) {
QRegularExpressionMatch match = i.next();
if (match.hasMatch()) {
//-- Compare "foo" with "*.foo"
if(extension == match.captured(0).mid(2)) {
return true;
}
}
}
return false;
}
/// @brief Returns first extension found in filter
QString QGCQFileDialog::_getFirstExtensionInFilter(const QString& filter) {
QRegularExpression re("(\\*\\.\\w+)");
QRegularExpressionMatchIterator i = re.globalMatch(filter);
while (i.hasNext()) {
QRegularExpressionMatch match = i.next();
if (match.hasMatch()) {
//-- Return "foo" from "*.foo"
return match.captured(0).mid(2);
}
}
return QString("");
}
/// @brief Validates and updates the parameters for the file dialog calls
void QGCQFileDialog::_validate(Options& options)
{
Q_UNUSED(options)
// You can't use QGCQFileDialog if QGCApplication is not created yet.
if (!qgcApp()) {
qWarning() << "Internal error";
return;
}
if (QThread::currentThread() != qgcApp()->thread()) {
qWarning() << "Threading issue: QGCQFileDialog can only be called from main thread";
return;
}
}
<commit_msg>QGCQFileDialog: Avoid QString initialization of empty string<commit_after>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "QGCQFileDialog.h"
#include "QGCApplication.h"
#include "MainWindow.h"
#ifdef UNITTEST_BUILD
#include "UnitTest.h"
#endif
#include <QRegularExpression>
#include <QMessageBox>
#include <QPushButton>
QString QGCQFileDialog::getExistingDirectory(
QWidget* parent,
const QString& caption,
const QString& dir,
Options options)
{
_validate(options);
#ifdef UNITTEST_BUILD
if (qgcApp()->runningUnitTests()) {
return UnitTest::_getExistingDirectory(parent, caption, dir, options);
} else
#endif
{
return QFileDialog::getExistingDirectory(parent, caption, dir, options);
}
}
QString QGCQFileDialog::getOpenFileName(
QWidget* parent,
const QString& caption,
const QString& dir,
const QString& filter,
Options options)
{
_validate(options);
#ifdef UNITTEST_BUILD
if (qgcApp()->runningUnitTests()) {
return UnitTest::_getOpenFileName(parent, caption, dir, filter, options);
} else
#endif
{
return QFileDialog::getOpenFileName(parent, caption, dir, filter, NULL, options);
}
}
QStringList QGCQFileDialog::getOpenFileNames(
QWidget* parent,
const QString& caption,
const QString& dir,
const QString& filter,
Options options)
{
_validate(options);
#ifdef UNITTEST_BUILD
if (qgcApp()->runningUnitTests()) {
return UnitTest::_getOpenFileNames(parent, caption, dir, filter, options);
} else
#endif
{
return QFileDialog::getOpenFileNames(parent, caption, dir, filter, NULL, options);
}
}
QString QGCQFileDialog::getSaveFileName(
QWidget* parent,
const QString& caption,
const QString& dir,
const QString& filter,
const QString& defaultSuffix,
bool strict,
Options options)
{
_validate(options);
#ifdef UNITTEST_BUILD
if (qgcApp()->runningUnitTests()) {
return UnitTest::_getSaveFileName(parent, caption, dir, filter, defaultSuffix, options);
} else
#endif
{
QString defaultSuffixCopy(defaultSuffix);
QFileDialog dlg(parent, caption, dir, filter);
dlg.setAcceptMode(QFileDialog::AcceptSave);
if (options) {
dlg.setOptions(options);
}
if (!defaultSuffixCopy.isEmpty()) {
//-- Make sure dot is not present
if (defaultSuffixCopy.startsWith(".")) {
defaultSuffixCopy.remove(0,1);
}
dlg.setDefaultSuffix(defaultSuffixCopy);
}
while (true) {
if (dlg.exec()) {
if (dlg.selectedFiles().count()) {
QString result = dlg.selectedFiles().first();
//-- If we don't care about the extension, just return it
if (!strict) {
return result;
} else {
//-- We must enforce the file extension
QFileInfo fi(result);
QString userSuffix(fi.suffix());
if (_validateExtension(filter, userSuffix)) {
return result;
}
//-- Do we have a default extension?
if (defaultSuffixCopy.isEmpty()) {
//-- We don't, so get the first one in the filter
defaultSuffixCopy = _getFirstExtensionInFilter(filter);
}
//-- If this is set to strict, we have to have a default extension
if (defaultSuffixCopy.isEmpty()) {
qWarning() << "Internal error";
}
//-- Forcefully append our desired extension
result += ".";
result += defaultSuffixCopy;
//-- Check and see if this new file already exists
fi.setFile(result);
if (fi.exists()) {
//-- Ask user what to do
QMessageBox msgBox(
QMessageBox::Warning,
tr("File Exists"),
tr("%1 already exists.\nDo you want to replace it?").arg(fi.fileName()),
QMessageBox::Cancel,
parent);
msgBox.addButton(QMessageBox::Retry);
QPushButton *overwriteButton = msgBox.addButton(tr("Replace"), QMessageBox::ActionRole);
msgBox.setDefaultButton(QMessageBox::Retry);
msgBox.setWindowModality(Qt::ApplicationModal);
if (msgBox.exec() == QMessageBox::Retry) {
continue;
} else if (msgBox.clickedButton() == overwriteButton) {
return result;
}
} else {
return result;
}
}
}
}
break;
}
return {};
}
}
/// @brief Make sure filename is using one of the valid extensions defined in the filter
bool QGCQFileDialog::_validateExtension(const QString& filter, const QString& extension) {
QRegularExpression re("(\\*\\.\\w+)");
QRegularExpressionMatchIterator i = re.globalMatch(filter);
while (i.hasNext()) {
QRegularExpressionMatch match = i.next();
if (match.hasMatch()) {
//-- Compare "foo" with "*.foo"
if(extension == match.captured(0).mid(2)) {
return true;
}
}
}
return false;
}
/// @brief Returns first extension found in filter
QString QGCQFileDialog::_getFirstExtensionInFilter(const QString& filter) {
QRegularExpression re("(\\*\\.\\w+)");
QRegularExpressionMatchIterator i = re.globalMatch(filter);
while (i.hasNext()) {
QRegularExpressionMatch match = i.next();
if (match.hasMatch()) {
//-- Return "foo" from "*.foo"
return match.captured(0).mid(2);
}
}
return {};
}
/// @brief Validates and updates the parameters for the file dialog calls
void QGCQFileDialog::_validate(Options& options)
{
Q_UNUSED(options)
// You can't use QGCQFileDialog if QGCApplication is not created yet.
if (!qgcApp()) {
qWarning() << "Internal error";
return;
}
if (QThread::currentThread() != qgcApp()->thread()) {
qWarning() << "Threading issue: QGCQFileDialog can only be called from main thread";
return;
}
}
<|endoftext|>
|
<commit_before>#include "rack.hpp"
struct QuantizeUtils {
//copied & fixed these scales http://www.grantmuller.com/MidiReference/doc/midiReference/ScaleReference.html
int SCALE_AEOLIAN [8] = {0, 2, 3, 5, 7, 8, 10, 12};
int SCALE_BLUES [7] = {0, 3, 5, 6, 7, 10, 12}; //FIXED!
int SCALE_CHROMATIC [13]= {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
int SCALE_DIATONIC_MINOR [8] = {0, 2, 3, 5, 7, 8, 10, 12};
int SCALE_DORIAN [8] = {0, 2, 3, 5, 7, 9, 10, 12};
int SCALE_HARMONIC_MINOR [8] = {0, 2, 3, 5, 7, 8, 11, 12};
int SCALE_INDIAN [8] = {0, 1, 1, 4, 5, 8, 10, 12};
int SCALE_LOCRIAN [8] = {0, 1, 3, 5, 6, 8, 10, 12};
int SCALE_LYDIAN [8] = {0, 2, 4, 6, 7, 9, 10, 12};
int SCALE_MAJOR [8] = {0, 2, 4, 5, 7, 9, 11, 12};
int SCALE_MELODIC_MINOR [10] = {0, 2, 3, 5, 7, 8, 9, 10, 11, 12};
int SCALE_MINOR [8] = {0, 2, 3, 5, 7, 8, 10, 12};
int SCALE_MIXOLYDIAN [8] = {0, 2, 4, 5, 7, 9, 10, 12};
int SCALE_NATURAL_MINOR [8] = {0, 2, 3, 5, 7, 8, 10, 12};
int SCALE_PENTATONIC [6] = {0, 2, 4, 7, 9, 12};
int SCALE_PHRYGIAN [8] = {0, 1, 3, 5, 7, 8, 10, 12};
int SCALE_TURKISH [8] = {0, 1, 3, 5, 7, 10, 11, 12};
enum NoteEnum {
NOTE_C,
NOTE_C_SHARP,
NOTE_D,
NOTE_D_SHARP,
NOTE_E,
NOTE_F,
NOTE_F_SHARP,
NOTE_G,
NOTE_G_SHARP,
NOTE_A,
NOTE_A_SHARP,
NOTE_B,
NUM_NOTES
};
enum ScaleEnum {
AEOLIAN,
BLUES,
CHROMATIC,
DIATONIC_MINOR,
DORIAN,
HARMONIC_MINOR,
INDIAN,
LOCRIAN,
LYDIAN,
MAJOR,
MELODIC_MINOR,
MINOR,
MIXOLYDIAN,
NATURAL_MINOR,
PENTATONIC,
PHRYGIAN,
TURKISH,
NONE,
NUM_SCALES
};
// long printIter = 0;
float closestVoltageInScale(float voltsIn, int rootNote, int currScale){
int *curScaleArr;
int notesInScale = 0;
switch(currScale){
case AEOLIAN: curScaleArr = SCALE_AEOLIAN; notesInScale=LENGTHOF(SCALE_AEOLIAN); break;
case BLUES: curScaleArr = SCALE_BLUES; notesInScale=LENGTHOF(SCALE_BLUES); break;
case CHROMATIC: curScaleArr = SCALE_CHROMATIC; notesInScale=LENGTHOF(SCALE_CHROMATIC); break;
case DIATONIC_MINOR: curScaleArr = SCALE_DIATONIC_MINOR;notesInScale=LENGTHOF(SCALE_DIATONIC_MINOR); break;
case DORIAN: curScaleArr = SCALE_DORIAN; notesInScale=LENGTHOF(SCALE_DORIAN); break;
case HARMONIC_MINOR: curScaleArr = SCALE_HARMONIC_MINOR;notesInScale=LENGTHOF(SCALE_HARMONIC_MINOR); break;
case INDIAN: curScaleArr = SCALE_INDIAN; notesInScale=LENGTHOF(SCALE_INDIAN); break;
case LOCRIAN: curScaleArr = SCALE_LOCRIAN; notesInScale=LENGTHOF(SCALE_LOCRIAN); break;
case LYDIAN: curScaleArr = SCALE_LYDIAN; notesInScale=LENGTHOF(SCALE_LYDIAN); break;
case MAJOR: curScaleArr = SCALE_MAJOR; notesInScale=LENGTHOF(SCALE_MAJOR); break;
case MELODIC_MINOR: curScaleArr = SCALE_MELODIC_MINOR; notesInScale=LENGTHOF(SCALE_MELODIC_MINOR); break;
case MINOR: curScaleArr = SCALE_MINOR; notesInScale=LENGTHOF(SCALE_MINOR); break;
case MIXOLYDIAN: curScaleArr = SCALE_MIXOLYDIAN; notesInScale=LENGTHOF(SCALE_MIXOLYDIAN); break;
case NATURAL_MINOR: curScaleArr = SCALE_NATURAL_MINOR; notesInScale=LENGTHOF(SCALE_NATURAL_MINOR); break;
case PENTATONIC: curScaleArr = SCALE_PENTATONIC; notesInScale=LENGTHOF(SCALE_PENTATONIC); break;
case PHRYGIAN: curScaleArr = SCALE_PHRYGIAN; notesInScale=LENGTHOF(SCALE_PHRYGIAN); break;
case TURKISH: curScaleArr = SCALE_TURKISH; notesInScale=LENGTHOF(SCALE_TURKISH); break;
case NONE: return voltsIn;
}
//C1 == -2.00, C2 == -1.00, C3 == 0.00, C4 == 1.00
//B1 == -1.08, B2 == -0.08, B3 == 0.92, B4 == 1.92
float closestVal = 10.0;
float closestDist = 10.0;
float scaleNoteInVolts = 0;
float distAway = 0;
int octaveInVolts = int(floorf(voltsIn));
float voltMinusOct = voltsIn - octaveInVolts;
for (int i=0; i < notesInScale; i++) {
scaleNoteInVolts = curScaleArr[i] / 12.0;
distAway = fabs(voltMinusOct - scaleNoteInVolts);
if(distAway < closestDist){
closestVal = scaleNoteInVolts;
closestDist = distAway;
}
// if(printIter%100000==0){
// printf("i:%i, rootNote:%i, voltsIn:%f, octaveInVolts:%i, closestVal:%f, closestDist:%f\n",
// i, rootNote, voltsIn, octaveInVolts, closestVal, closestDist);
// printIter = 0;
// }
}
// printIter++;
return octaveInVolts + rootNote/12.0 + closestVal;
}
std::string noteName(int note) {
switch(note){
case NOTE_C: return "C";
case NOTE_C_SHARP: return "C#";
case NOTE_D: return "D";
case NOTE_D_SHARP: return "D#";
case NOTE_E: return "E";
case NOTE_F: return "F";
case NOTE_F_SHARP: return "F#";
case NOTE_G: return "G";
case NOTE_G_SHARP: return "G#";
case NOTE_A: return "A";
case NOTE_A_SHARP: return "A#";
case NOTE_B: return "B";
default: return "";
}
}
std::string scaleName(int scale) {
switch(scale){
case AEOLIAN: return "Aeolian";
case BLUES: return "Blues";
case CHROMATIC: return "Chromat";
case DIATONIC_MINOR: return "Diat Min";
case DORIAN: return "Dorian";
case HARMONIC_MINOR: return "Harm Min";
case INDIAN: return "Indian";
case LOCRIAN: return "Locrian";
case LYDIAN: return "Lydian";
case MAJOR: return "Major";
case MELODIC_MINOR: return "Mel Min";
case MINOR: return "Minor";
case MIXOLYDIAN: return "Mixolyd";
case NATURAL_MINOR: return "Nat Min";
case PENTATONIC: return "Penta";
case PHRYGIAN: return "Phrygian";
case TURKISH: return "Turkish";
case NONE: return "None";
default: return "";
}
}
};<commit_msg>minor tweek to quantizer logging<commit_after>#include "rack.hpp"
struct QuantizeUtils {
//copied & fixed these scales http://www.grantmuller.com/MidiReference/doc/midiReference/ScaleReference.html
int SCALE_AEOLIAN [8] = {0, 2, 3, 5, 7, 8, 10, 12};
int SCALE_BLUES [7] = {0, 3, 5, 6, 7, 10, 12}; //FIXED!
int SCALE_CHROMATIC [13]= {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
int SCALE_DIATONIC_MINOR [8] = {0, 2, 3, 5, 7, 8, 10, 12};
int SCALE_DORIAN [8] = {0, 2, 3, 5, 7, 9, 10, 12};
int SCALE_HARMONIC_MINOR [8] = {0, 2, 3, 5, 7, 8, 11, 12};
int SCALE_INDIAN [8] = {0, 1, 1, 4, 5, 8, 10, 12};
int SCALE_LOCRIAN [8] = {0, 1, 3, 5, 6, 8, 10, 12};
int SCALE_LYDIAN [8] = {0, 2, 4, 6, 7, 9, 10, 12};
int SCALE_MAJOR [8] = {0, 2, 4, 5, 7, 9, 11, 12};
int SCALE_MELODIC_MINOR [10] = {0, 2, 3, 5, 7, 8, 9, 10, 11, 12};
int SCALE_MINOR [8] = {0, 2, 3, 5, 7, 8, 10, 12};
int SCALE_MIXOLYDIAN [8] = {0, 2, 4, 5, 7, 9, 10, 12};
int SCALE_NATURAL_MINOR [8] = {0, 2, 3, 5, 7, 8, 10, 12};
int SCALE_PENTATONIC [6] = {0, 2, 4, 7, 9, 12};
int SCALE_PHRYGIAN [8] = {0, 1, 3, 5, 7, 8, 10, 12};
int SCALE_TURKISH [8] = {0, 1, 3, 5, 7, 10, 11, 12};
enum NoteEnum {
NOTE_C,
NOTE_C_SHARP,
NOTE_D,
NOTE_D_SHARP,
NOTE_E,
NOTE_F,
NOTE_F_SHARP,
NOTE_G,
NOTE_G_SHARP,
NOTE_A,
NOTE_A_SHARP,
NOTE_B,
NUM_NOTES
};
enum ScaleEnum {
AEOLIAN,
BLUES,
CHROMATIC,
DIATONIC_MINOR,
DORIAN,
HARMONIC_MINOR,
INDIAN,
LOCRIAN,
LYDIAN,
MAJOR,
MELODIC_MINOR,
MINOR,
MIXOLYDIAN,
NATURAL_MINOR,
PENTATONIC,
PHRYGIAN,
TURKISH,
NONE,
NUM_SCALES
};
// long printIter = 0;
float closestVoltageInScale(float voltsIn, int rootNote, int currScale){
int *curScaleArr;
int notesInScale = 0;
switch(currScale){
case AEOLIAN: curScaleArr = SCALE_AEOLIAN; notesInScale=LENGTHOF(SCALE_AEOLIAN); break;
case BLUES: curScaleArr = SCALE_BLUES; notesInScale=LENGTHOF(SCALE_BLUES); break;
case CHROMATIC: curScaleArr = SCALE_CHROMATIC; notesInScale=LENGTHOF(SCALE_CHROMATIC); break;
case DIATONIC_MINOR: curScaleArr = SCALE_DIATONIC_MINOR;notesInScale=LENGTHOF(SCALE_DIATONIC_MINOR); break;
case DORIAN: curScaleArr = SCALE_DORIAN; notesInScale=LENGTHOF(SCALE_DORIAN); break;
case HARMONIC_MINOR: curScaleArr = SCALE_HARMONIC_MINOR;notesInScale=LENGTHOF(SCALE_HARMONIC_MINOR); break;
case INDIAN: curScaleArr = SCALE_INDIAN; notesInScale=LENGTHOF(SCALE_INDIAN); break;
case LOCRIAN: curScaleArr = SCALE_LOCRIAN; notesInScale=LENGTHOF(SCALE_LOCRIAN); break;
case LYDIAN: curScaleArr = SCALE_LYDIAN; notesInScale=LENGTHOF(SCALE_LYDIAN); break;
case MAJOR: curScaleArr = SCALE_MAJOR; notesInScale=LENGTHOF(SCALE_MAJOR); break;
case MELODIC_MINOR: curScaleArr = SCALE_MELODIC_MINOR; notesInScale=LENGTHOF(SCALE_MELODIC_MINOR); break;
case MINOR: curScaleArr = SCALE_MINOR; notesInScale=LENGTHOF(SCALE_MINOR); break;
case MIXOLYDIAN: curScaleArr = SCALE_MIXOLYDIAN; notesInScale=LENGTHOF(SCALE_MIXOLYDIAN); break;
case NATURAL_MINOR: curScaleArr = SCALE_NATURAL_MINOR; notesInScale=LENGTHOF(SCALE_NATURAL_MINOR); break;
case PENTATONIC: curScaleArr = SCALE_PENTATONIC; notesInScale=LENGTHOF(SCALE_PENTATONIC); break;
case PHRYGIAN: curScaleArr = SCALE_PHRYGIAN; notesInScale=LENGTHOF(SCALE_PHRYGIAN); break;
case TURKISH: curScaleArr = SCALE_TURKISH; notesInScale=LENGTHOF(SCALE_TURKISH); break;
case NONE: return voltsIn;
}
//C1 == -2.00, C2 == -1.00, C3 == 0.00, C4 == 1.00
//B1 == -1.08, B2 == -0.08, B3 == 0.92, B4 == 1.92
float closestVal = 10.0;
float closestDist = 10.0;
float scaleNoteInVolts = 0;
float distAway = 0;
int octaveInVolts = int(floorf(voltsIn));
float voltMinusOct = voltsIn - octaveInVolts;
for (int i=0; i < notesInScale; i++) {
scaleNoteInVolts = curScaleArr[i] / 12.0;
distAway = fabs(voltMinusOct - scaleNoteInVolts);
if(distAway < closestDist){
closestVal = scaleNoteInVolts;
closestDist = distAway;
}
// if(printIter%100000==0){
// printf("i:%i, rootNote:%i, voltsIn:%f, octaveInVolts:%i, closestVal:%f, closestDist:%f\n",
// i, rootNote, voltsIn, octaveInVolts, closestVal, closestDist);
// printIter = 0;
// }
}
// printIter++;
float voltsOut = octaveInVolts + rootNote/12.0 + closestVal;
// if(printIter%100000==0){
// printf("voltsIn:%f, voltsOut:%f, closestVal:%f\n",
// voltsIn, voltsOut, closestVal);
// printIter = 0;
// }
return voltsOut;
}
std::string noteName(int note) {
switch(note){
case NOTE_C: return "C";
case NOTE_C_SHARP: return "C#";
case NOTE_D: return "D";
case NOTE_D_SHARP: return "D#";
case NOTE_E: return "E";
case NOTE_F: return "F";
case NOTE_F_SHARP: return "F#";
case NOTE_G: return "G";
case NOTE_G_SHARP: return "G#";
case NOTE_A: return "A";
case NOTE_A_SHARP: return "A#";
case NOTE_B: return "B";
default: return "";
}
}
std::string scaleName(int scale) {
switch(scale){
case AEOLIAN: return "Aeolian";
case BLUES: return "Blues";
case CHROMATIC: return "Chromat";
case DIATONIC_MINOR: return "Diat Min";
case DORIAN: return "Dorian";
case HARMONIC_MINOR: return "Harm Min";
case INDIAN: return "Indian";
case LOCRIAN: return "Locrian";
case LYDIAN: return "Lydian";
case MAJOR: return "Major";
case MELODIC_MINOR: return "Mel Min";
case MINOR: return "Minor";
case MIXOLYDIAN: return "Mixolyd";
case NATURAL_MINOR: return "Nat Min";
case PENTATONIC: return "Penta";
case PHRYGIAN: return "Phrygian";
case TURKISH: return "Turkish";
case NONE: return "None";
default: return "";
}
}
};<|endoftext|>
|
<commit_before>/*****************************************************************************
intersectMain.cpp
(c) 2009 - Aaron Quinlan
Hall Laboratory
Department of Biochemistry and Molecular Genetics
University of Virginia
aaronquinlan@gmail.com
Licenced under the GNU General Public License 2.0 license.
******************************************************************************/
#include "intersectBed.h"
#include "version.h"
using namespace std;
// define our program name
#define PROGRAM_NAME "bedtools intersect"
// define our parameter checking macro
#define PARAMETER_CHECK(param, paramLen, actualLen) (strncmp(argv[i], param, min(actualLen, paramLen))== 0) && (actualLen == paramLen)
// function declarations
void intersect_help(void);
int intersect_main(int argc, char* argv[]) {
// our configuration variables
bool showHelp = false;
// input files
string bedAFile;
string bedBFile;
// input arguments
float overlapFraction = 1E-9;
bool haveBedA = false;
bool haveBedB = false;
bool noHit = false;
bool leftJoin = false;
bool anyHit = false;
bool writeA = false;
bool writeB = false;
bool writeCount = false;
bool writeOverlap = false;
bool writeAllOverlap = false;
bool haveFraction = false;
bool reciprocalFraction = false;
bool sameStrand = false;
bool diffStrand = false;
bool obeySplits = false;
bool inputIsBam = false;
bool outputIsBam = true;
bool uncompressedBam = false;
bool sortedInput = false;
bool printHeader = false;
// check to see if we should print out some help
if(argc <= 1) showHelp = true;
for(int i = 1; i < argc; i++) {
int parameterLength = (int)strlen(argv[i]);
if((PARAMETER_CHECK("-h", 2, parameterLength)) ||
(PARAMETER_CHECK("--help", 5, parameterLength))) {
showHelp = true;
}
}
if(showHelp) intersect_help();
// do some parsing (all of these parameters require 2 strings)
for(int i = 1; i < argc; i++) {
int parameterLength = (int)strlen(argv[i]);
if(PARAMETER_CHECK("-a", 2, parameterLength)) {
if ((i+1) < argc) {
haveBedA = true;
outputIsBam = false;
bedAFile = argv[i + 1];
i++;
}
}
else if(PARAMETER_CHECK("-abam", 5, parameterLength)) {
if ((i+1) < argc) {
haveBedA = true;
inputIsBam = true;
bedAFile = argv[i + 1];
i++;
}
}
else if(PARAMETER_CHECK("-b", 2, parameterLength)) {
if ((i+1) < argc) {
haveBedB = true;
bedBFile = argv[i + 1];
i++;
}
}
else if(PARAMETER_CHECK("-bed", 4, parameterLength)) {
outputIsBam = false;
}
else if(PARAMETER_CHECK("-u", 2, parameterLength)) {
anyHit = true;
}
else if(PARAMETER_CHECK("-f", 2, parameterLength)) {
if ((i+1) < argc) {
haveFraction = true;
overlapFraction = atof(argv[i + 1]);
i++;
}
}
else if(PARAMETER_CHECK("-wa", 3, parameterLength)) {
writeA = true;
}
else if(PARAMETER_CHECK("-wb", 3, parameterLength)) {
writeB = true;
}
else if(PARAMETER_CHECK("-wo", 3, parameterLength)) {
writeOverlap = true;
}
else if(PARAMETER_CHECK("-wao", 4, parameterLength)) {
writeAllOverlap = true;
writeOverlap = true;
}
else if(PARAMETER_CHECK("-c", 2, parameterLength)) {
writeCount = true;
}
else if(PARAMETER_CHECK("-r", 2, parameterLength)) {
reciprocalFraction = true;
}
else if (PARAMETER_CHECK("-v", 2, parameterLength)) {
noHit = true;
}
else if (PARAMETER_CHECK("-s", 2, parameterLength)) {
sameStrand = true;
}
else if (PARAMETER_CHECK("-S", 2, parameterLength)) {
diffStrand = true;
}
else if (PARAMETER_CHECK("-split", 6, parameterLength)) {
obeySplits = true;
}
else if (PARAMETER_CHECK("-leftjoin", 9, parameterLength)) {
leftJoin = true;
}
else if(PARAMETER_CHECK("-ubam", 5, parameterLength)) {
uncompressedBam = true;
}
else if(PARAMETER_CHECK("-sorted", 7, parameterLength)) {
sortedInput = true;
}
else if(PARAMETER_CHECK("-header", 7, parameterLength)) {
printHeader = true;
}
else {
cerr << endl << "*****ERROR: Unrecognized parameter: " << argv[i] << " *****" << endl << endl;
showHelp = true;
}
}
// make sure we have both input files
if (!haveBedA || !haveBedB) {
cerr << endl << "*****" << endl << "*****ERROR: Need -a and -b files. " << endl << "*****" << endl;
showHelp = true;
}
if (anyHit && noHit) {
cerr << endl << "*****" << endl << "*****ERROR: Request either -u OR -v, not both." << endl << "*****" << endl;
showHelp = true;
}
if (writeB && writeCount) {
cerr << endl << "*****" << endl << "*****ERROR: Request either -wb OR -c, not both." << endl << "*****" << endl;
showHelp = true;
}
if (writeCount && writeOverlap) {
cerr << endl << "*****" << endl << "*****ERROR: Request either -wb OR -wo, not both." << endl << "*****" << endl;
showHelp = true;
}
if (writeA && writeOverlap) {
cerr << endl << "*****" << endl << "*****ERROR: Request either -wa OR -wo, not both." << endl << "*****" << endl;
showHelp = true;
}
if (writeB && writeOverlap) {
cerr << endl << "*****" << endl << "*****ERROR: Request either -wb OR -wo, not both." << endl << "*****" << endl;
showHelp = true;
}
if (reciprocalFraction && !haveFraction) {
cerr << endl << "*****" << endl << "*****ERROR: If using -r, you need to define -f." << endl << "*****" << endl;
showHelp = true;
}
if (anyHit && writeCount) {
cerr << endl << "*****" << endl << "*****ERROR: Request either -u OR -c, not both." << endl << "*****" << endl;
showHelp = true;
}
if (anyHit && writeB) {
cerr << endl << "*****" << endl << "*****ERROR: Request either -u OR -wb, not both." << endl << "*****" << endl;
showHelp = true;
}
if (anyHit && writeOverlap) {
cerr << endl << "*****" << endl << "*****ERROR: Request either -u OR -wo, not both." << endl << "*****" << endl;
showHelp = true;
}
if (sameStrand && diffStrand) {
cerr << endl << "*****" << endl << "*****ERROR: Request either -s OR -S, not both." << endl << "*****" << endl;
showHelp = true;
}
if (!showHelp) {
BedIntersect *bi = new BedIntersect(bedAFile, bedBFile, anyHit, writeA, writeB, writeOverlap,
writeAllOverlap, overlapFraction, noHit, leftJoin, writeCount, sameStrand, diffStrand,
reciprocalFraction, obeySplits, inputIsBam, outputIsBam, uncompressedBam,
sortedInput, printHeader);
delete bi;
return 0;
}
else {
intersect_help();
return 0;
}
}
void intersect_help(void) {
cerr << "\nTool: bedtools intersect (aka intersectBed)" << endl;
cerr << "Version: " << VERSION << "\n";
cerr << "Summary: Report overlaps between two feature files." << endl << endl;
cerr << "Usage: " << PROGRAM_NAME << " [OPTIONS] -a <bed/gff/vcf> -b <bed/gff/vcf>" << endl << endl;
cerr << "Options: " << endl;
cerr << "\t-abam\t" << "The A input file is in BAM format. Output will be BAM as well." << endl << endl;
cerr << "\t-ubam\t" << "Write uncompressed BAM output. Default writes compressed BAM." << endl << endl;
cerr << "\t-bed\t" << "When using BAM input (-abam), write output as BED. The default" << endl;
cerr << "\t\tis to write output in BAM when using -abam." << endl << endl;
cerr << "\t-wa\t" << "Write the original entry in A for each overlap." << endl << endl;
cerr << "\t-wb\t" << "Write the original entry in B for each overlap." << endl;
cerr << "\t\t- Useful for knowing _what_ A overlaps. Restricted by -f and -r." << endl << endl;
cerr << "\t-leftjoin\t" << "Write the original entry in B for each overlap." << endl;
cerr << "\t\t- Useful for knowing _what_ A overlaps. Restricted by -f and -r." << endl << endl;
cerr << "\t-wo\t" << "Write the original A and B entries plus the number of base" << endl;
cerr << "\t\tpairs of overlap between the two features." << endl;
cerr << "\t\t- Overlaps restricted by -f and -r." << endl;
cerr << "\t\t Only A features with overlap are reported." << endl << endl;
cerr << "\t-wao\t" << "Write the original A and B entries plus the number of base" << endl;
cerr << "\t\tpairs of overlap between the two features." << endl;
cerr << "\t\t- Overlapping features restricted by -f and -r." << endl;
cerr << "\t\t However, A features w/o overlap are also reported" << endl;
cerr << "\t\t with a NULL B feature and overlap = 0." << endl << endl;
cerr << "\t-u\t" << "Write the original A entry _once_ if _any_ overlaps found in B." << endl;
cerr << "\t\t- In other words, just report the fact >=1 hit was found." << endl;
cerr << "\t\t- Overlaps restricted by -f and -r." << endl << endl;
cerr << "\t-c\t" << "For each entry in A, report the number of overlaps with B." << endl;
cerr << "\t\t- Reports 0 for A entries that have no overlap with B." << endl;
cerr << "\t\t- Overlaps restricted by -f and -r." << endl << endl;
cerr << "\t-v\t" << "Only report those entries in A that have _no overlaps_ with B." << endl;
cerr << "\t\t- Similar to \"grep -v\" (an homage)." << endl << endl;
cerr << "\t-f\t" << "Minimum overlap required as a fraction of A." << endl;
cerr << "\t\t- Default is 1E-9 (i.e., 1bp)." << endl;
cerr << "\t\t- FLOAT (e.g. 0.50)" << endl << endl;
cerr << "\t-r\t" << "Require that the fraction overlap be reciprocal for A and B." << endl;
cerr << "\t\t- In other words, if -f is 0.90 and -r is used, this requires" << endl;
cerr << "\t\t that B overlap 90% of A and A _also_ overlaps 90% of B." << endl << endl;
cerr << "\t-s\t" << "Require same strandedness. That is, only report hits in B" << endl;
cerr << "\t\tthat overlap A on the _same_ strand." << endl;
cerr << "\t\t- By default, overlaps are reported without respect to strand." << endl << endl;
cerr << "\t-S\t" << "Require different strandedness. That is, only report hits in B" << endl;
cerr << "\t\tthat overlap A on the _opposite_ strand." << endl;
cerr << "\t\t- By default, overlaps are reported without respect to strand." << endl << endl;
cerr << "\t-split\t" << "Treat \"split\" BAM or BED12 entries as distinct BED intervals." << endl << endl;
cerr << "\t-sorted\t" << "Use the \"chromsweep\" algorithm for sorted (-k1,1 -k2,2n) input" << endl << endl;
cerr << "\t-header\t" << "Print the header from the A file prior to results." << endl << endl;
// end the program here
exit(1);
}
<commit_msg>change -leftJoin to -loj. Improve help for intersect<commit_after>/*****************************************************************************
intersectMain.cpp
(c) 2009 - Aaron Quinlan
Hall Laboratory
Department of Biochemistry and Molecular Genetics
University of Virginia
aaronquinlan@gmail.com
Licenced under the GNU General Public License 2.0 license.
******************************************************************************/
#include "intersectBed.h"
#include "version.h"
using namespace std;
// define our program name
#define PROGRAM_NAME "bedtools intersect"
// define our parameter checking macro
#define PARAMETER_CHECK(param, paramLen, actualLen) (strncmp(argv[i], param, min(actualLen, paramLen))== 0) && (actualLen == paramLen)
// function declarations
void intersect_help(void);
int intersect_main(int argc, char* argv[]) {
// our configuration variables
bool showHelp = false;
// input files
string bedAFile;
string bedBFile;
// input arguments
float overlapFraction = 1E-9;
bool haveBedA = false;
bool haveBedB = false;
bool noHit = false;
bool leftJoin = false;
bool anyHit = false;
bool writeA = false;
bool writeB = false;
bool writeCount = false;
bool writeOverlap = false;
bool writeAllOverlap = false;
bool haveFraction = false;
bool reciprocalFraction = false;
bool sameStrand = false;
bool diffStrand = false;
bool obeySplits = false;
bool inputIsBam = false;
bool outputIsBam = true;
bool uncompressedBam = false;
bool sortedInput = false;
bool printHeader = false;
// check to see if we should print out some help
if(argc <= 1) showHelp = true;
for(int i = 1; i < argc; i++) {
int parameterLength = (int)strlen(argv[i]);
if((PARAMETER_CHECK("-h", 2, parameterLength)) ||
(PARAMETER_CHECK("--help", 5, parameterLength))) {
showHelp = true;
}
}
if(showHelp) intersect_help();
// do some parsing (all of these parameters require 2 strings)
for(int i = 1; i < argc; i++) {
int parameterLength = (int)strlen(argv[i]);
if(PARAMETER_CHECK("-a", 2, parameterLength)) {
if ((i+1) < argc) {
haveBedA = true;
outputIsBam = false;
bedAFile = argv[i + 1];
i++;
}
}
else if(PARAMETER_CHECK("-abam", 5, parameterLength)) {
if ((i+1) < argc) {
haveBedA = true;
inputIsBam = true;
bedAFile = argv[i + 1];
i++;
}
}
else if(PARAMETER_CHECK("-b", 2, parameterLength)) {
if ((i+1) < argc) {
haveBedB = true;
bedBFile = argv[i + 1];
i++;
}
}
else if(PARAMETER_CHECK("-bed", 4, parameterLength)) {
outputIsBam = false;
}
else if(PARAMETER_CHECK("-u", 2, parameterLength)) {
anyHit = true;
}
else if(PARAMETER_CHECK("-f", 2, parameterLength)) {
if ((i+1) < argc) {
haveFraction = true;
overlapFraction = atof(argv[i + 1]);
i++;
}
}
else if(PARAMETER_CHECK("-wa", 3, parameterLength)) {
writeA = true;
}
else if(PARAMETER_CHECK("-wb", 3, parameterLength)) {
writeB = true;
}
else if(PARAMETER_CHECK("-wo", 3, parameterLength)) {
writeOverlap = true;
}
else if(PARAMETER_CHECK("-wao", 4, parameterLength)) {
writeAllOverlap = true;
writeOverlap = true;
}
else if(PARAMETER_CHECK("-c", 2, parameterLength)) {
writeCount = true;
}
else if(PARAMETER_CHECK("-r", 2, parameterLength)) {
reciprocalFraction = true;
}
else if (PARAMETER_CHECK("-v", 2, parameterLength)) {
noHit = true;
}
else if (PARAMETER_CHECK("-s", 2, parameterLength)) {
sameStrand = true;
}
else if (PARAMETER_CHECK("-S", 2, parameterLength)) {
diffStrand = true;
}
else if (PARAMETER_CHECK("-split", 6, parameterLength)) {
obeySplits = true;
}
else if (PARAMETER_CHECK("-loj", 4, parameterLength)) {
leftJoin = true;
}
else if(PARAMETER_CHECK("-ubam", 5, parameterLength)) {
uncompressedBam = true;
}
else if(PARAMETER_CHECK("-sorted", 7, parameterLength)) {
sortedInput = true;
}
else if(PARAMETER_CHECK("-header", 7, parameterLength)) {
printHeader = true;
}
else {
cerr << endl << "*****ERROR: Unrecognized parameter: " << argv[i] << " *****" << endl << endl;
showHelp = true;
}
}
// make sure we have both input files
if (!haveBedA || !haveBedB) {
cerr << endl << "*****" << endl << "*****ERROR: Need -a and -b files. " << endl << "*****" << endl;
showHelp = true;
}
if (anyHit && noHit) {
cerr << endl << "*****" << endl << "*****ERROR: Request either -u OR -v, not both." << endl << "*****" << endl;
showHelp = true;
}
if (writeB && writeCount) {
cerr << endl << "*****" << endl << "*****ERROR: Request either -wb OR -c, not both." << endl << "*****" << endl;
showHelp = true;
}
if (writeCount && writeOverlap) {
cerr << endl << "*****" << endl << "*****ERROR: Request either -wb OR -wo, not both." << endl << "*****" << endl;
showHelp = true;
}
if (writeA && writeOverlap) {
cerr << endl << "*****" << endl << "*****ERROR: Request either -wa OR -wo, not both." << endl << "*****" << endl;
showHelp = true;
}
if (writeB && writeOverlap) {
cerr << endl << "*****" << endl << "*****ERROR: Request either -wb OR -wo, not both." << endl << "*****" << endl;
showHelp = true;
}
if (reciprocalFraction && !haveFraction) {
cerr << endl << "*****" << endl << "*****ERROR: If using -r, you need to define -f." << endl << "*****" << endl;
showHelp = true;
}
if (anyHit && writeCount) {
cerr << endl << "*****" << endl << "*****ERROR: Request either -u OR -c, not both." << endl << "*****" << endl;
showHelp = true;
}
if (anyHit && writeB) {
cerr << endl << "*****" << endl << "*****ERROR: Request either -u OR -wb, not both." << endl << "*****" << endl;
showHelp = true;
}
if (anyHit && writeOverlap) {
cerr << endl << "*****" << endl << "*****ERROR: Request either -u OR -wo, not both." << endl << "*****" << endl;
showHelp = true;
}
if (sameStrand && diffStrand) {
cerr << endl << "*****" << endl << "*****ERROR: Request either -s OR -S, not both." << endl << "*****" << endl;
showHelp = true;
}
if (inputIsBam && writeB) {
cerr << endl << "*****" << endl << "*****WARNING: -wb is ignored with -abam" << endl << "*****" << endl;
}
if (inputIsBam && leftJoin) {
cerr << endl << "*****" << endl << "*****WARNING: -loj is ignored with -abam" << endl << "*****" << endl;
}
if (inputIsBam && writeCount) {
cerr << endl << "*****" << endl << "*****WARNING: -c is ignored with -abam" << endl << "*****" << endl;
}
if (inputIsBam && writeOverlap) {
cerr << endl << "*****" << endl << "*****WARNING: -wo is ignored with -abam" << endl << "*****" << endl;
}
if (inputIsBam && writeAllOverlap) {
cerr << endl << "*****" << endl << "*****WARNING: -wao is ignored with -abam" << endl << "*****" << endl;
}
if (!showHelp) {
BedIntersect *bi = new BedIntersect(bedAFile, bedBFile, anyHit, writeA, writeB, writeOverlap,
writeAllOverlap, overlapFraction, noHit, leftJoin, writeCount, sameStrand, diffStrand,
reciprocalFraction, obeySplits, inputIsBam, outputIsBam, uncompressedBam,
sortedInput, printHeader);
delete bi;
return 0;
}
else {
intersect_help();
return 0;
}
}
void intersect_help(void) {
cerr << "\nTool: bedtools intersect (aka intersectBed)" << endl;
cerr << "Version: " << VERSION << "\n";
cerr << "Summary: Report overlaps between two feature files." << endl << endl;
cerr << "Usage: " << PROGRAM_NAME << " [OPTIONS] -a <bed/gff/vcf> -b <bed/gff/vcf>" << endl << endl;
cerr << "Options: " << endl;
cerr << "\t-abam\t" << "The A input file is in BAM format. Output will be BAM as well." << endl << endl;
cerr << "\t-ubam\t" << "Write uncompressed BAM output. Default writes compressed BAM." << endl << endl;
cerr << "\t-bed\t" << "When using BAM input (-abam), write output as BED. The default" << endl;
cerr << "\t\tis to write output in BAM when using -abam." << endl << endl;
cerr << "\t-wa\t" << "Write the original entry in A for each overlap." << endl << endl;
cerr << "\t-wb\t" << "Write the original entry in B for each overlap." << endl;
cerr << "\t\t- Useful for knowing _what_ A overlaps. Restricted by -f and -r." << endl << endl;
cerr << "\t-loj\t" << "Perform a \"left outer join\". That is, for each feature in A" << endl;
cerr << "\t\treport each overlap with B. If no overlaps are found, " << endl;
cerr << "\t\treport a NULL feature for B." << endl << endl;
cerr << "\t-wo\t" << "Write the original A and B entries plus the number of base" << endl;
cerr << "\t\tpairs of overlap between the two features." << endl;
cerr << "\t\t- Overlaps restricted by -f and -r." << endl;
cerr << "\t\t Only A features with overlap are reported." << endl << endl;
cerr << "\t-wao\t" << "Write the original A and B entries plus the number of base" << endl;
cerr << "\t\tpairs of overlap between the two features." << endl;
cerr << "\t\t- Overlapping features restricted by -f and -r." << endl;
cerr << "\t\t However, A features w/o overlap are also reported" << endl;
cerr << "\t\t with a NULL B feature and overlap = 0." << endl << endl;
cerr << "\t-u\t" << "Write the original A entry _once_ if _any_ overlaps found in B." << endl;
cerr << "\t\t- In other words, just report the fact >=1 hit was found." << endl;
cerr << "\t\t- Overlaps restricted by -f and -r." << endl << endl;
cerr << "\t-c\t" << "For each entry in A, report the number of overlaps with B." << endl;
cerr << "\t\t- Reports 0 for A entries that have no overlap with B." << endl;
cerr << "\t\t- Overlaps restricted by -f and -r." << endl << endl;
cerr << "\t-v\t" << "Only report those entries in A that have _no overlaps_ with B." << endl;
cerr << "\t\t- Similar to \"grep -v\" (an homage)." << endl << endl;
cerr << "\t-f\t" << "Minimum overlap required as a fraction of A." << endl;
cerr << "\t\t- Default is 1E-9 (i.e., 1bp)." << endl;
cerr << "\t\t- FLOAT (e.g. 0.50)" << endl << endl;
cerr << "\t-r\t" << "Require that the fraction overlap be reciprocal for A and B." << endl;
cerr << "\t\t- In other words, if -f is 0.90 and -r is used, this requires" << endl;
cerr << "\t\t that B overlap 90% of A and A _also_ overlaps 90% of B." << endl << endl;
cerr << "\t-s\t" << "Require same strandedness. That is, only report hits in B" << endl;
cerr << "\t\tthat overlap A on the _same_ strand." << endl;
cerr << "\t\t- By default, overlaps are reported without respect to strand." << endl << endl;
cerr << "\t-S\t" << "Require different strandedness. That is, only report hits in B" << endl;
cerr << "\t\tthat overlap A on the _opposite_ strand." << endl;
cerr << "\t\t- By default, overlaps are reported without respect to strand." << endl << endl;
cerr << "\t-split\t" << "Treat \"split\" BAM or BED12 entries as distinct BED intervals." << endl << endl;
cerr << "\t-sorted\t" << "Use the \"chromsweep\" algorithm for sorted (-k1,1 -k2,2n) input" << endl << endl;
cerr << "\t-header\t" << "Print the header from the A file prior to results." << endl << endl;
cerr << "Notes: " << endl;
cerr << "\t(1) When a BAM file is used for the A file, the alignment is retained if overlaps exist," << endl;
cerr << "\tand exlcuded if an overlap cannot be found. If multiple overlaps exist, they are not" << endl;
cerr << "\treported, as we are only testing for one or more overlaps." << endl << endl;
// end the program here
exit(1);
}
<|endoftext|>
|
<commit_before>#include "joedb/journal/Generic_File.h"
#include <algorithm>
/////////////////////////////////////////////////////////////////////////////
void joedb::Generic_File::set_position(int64_t new_position)
/////////////////////////////////////////////////////////////////////////////
{
flush();
if (!seek(new_position))
{
position = new_position;
reset_read_buffer();
}
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Generic_File::copy(Generic_File &file)
/////////////////////////////////////////////////////////////////////////////
{
flush();
file.flush();
file.set_position(0);
while (true)
{
file.read_buffer();
if (file.read_buffer_size == 0)
break;
std::copy_n(file.buffer, file.read_buffer_size, buffer);
write_buffer_index = file.read_buffer_size;
write_buffer();
position += file.read_buffer_size;
}
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Generic_File::write_string(const std::string &s)
/////////////////////////////////////////////////////////////////////////////
{
compact_write<size_t>(s.size());
for (char c: s)
write<char>(c);
}
/////////////////////////////////////////////////////////////////////////////
std::string joedb::Generic_File::read_string()
/////////////////////////////////////////////////////////////////////////////
{
std::string s;
size_t size = compact_read<size_t>();
s.resize(size);
read_data(&s[0], size);
return s;
}
/////////////////////////////////////////////////////////////////////////////
std::string joedb::Generic_File::safe_read_string(size_t max_size)
/////////////////////////////////////////////////////////////////////////////
{
std::string s;
size_t size = compact_read<size_t>();
if (size < max_size)
{
s.resize(size);
for (size_t i = 0; i < size; i++)
s[i] = char(getc());
}
return s;
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Generic_File::flush()
/////////////////////////////////////////////////////////////////////////////
{
if (write_buffer_index)
write_buffer();
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Generic_File::destructor_flush() noexcept
/////////////////////////////////////////////////////////////////////////////
{
if (write_buffer_index)
{
Destructor_Logger::write("warning: an unflushed file is being destroyed");
try
{
flush();
}
catch (...)
{
postpone_exception("failed to flush in Generic_File destructor");
}
}
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Generic_File::commit()
/////////////////////////////////////////////////////////////////////////////
{
flush();
sync();
}
<commit_msg>namespace joedb for Generic_File.cpp<commit_after>#include "joedb/journal/Generic_File.h"
#include <algorithm>
namespace joedb
{
////////////////////////////////////////////////////////////////////////////
void Generic_File::set_position(int64_t new_position)
////////////////////////////////////////////////////////////////////////////
{
flush();
if (!seek(new_position))
{
position = new_position;
reset_read_buffer();
}
}
////////////////////////////////////////////////////////////////////////////
void Generic_File::copy(Generic_File &file)
////////////////////////////////////////////////////////////////////////////
{
flush();
file.flush();
file.set_position(0);
while (true)
{
file.read_buffer();
if (file.read_buffer_size == 0)
break;
std::copy_n(file.buffer, file.read_buffer_size, buffer);
write_buffer_index = file.read_buffer_size;
write_buffer();
position += file.read_buffer_size;
}
}
////////////////////////////////////////////////////////////////////////////
void Generic_File::write_string(const std::string &s)
////////////////////////////////////////////////////////////////////////////
{
compact_write<size_t>(s.size());
for (char c: s)
write<char>(c);
}
////////////////////////////////////////////////////////////////////////////
std::string Generic_File::read_string()
////////////////////////////////////////////////////////////////////////////
{
std::string s;
size_t size = compact_read<size_t>();
s.resize(size);
read_data(&s[0], size);
return s;
}
////////////////////////////////////////////////////////////////////////////
std::string Generic_File::safe_read_string(size_t max_size)
////////////////////////////////////////////////////////////////////////////
{
std::string s;
size_t size = compact_read<size_t>();
if (size < max_size)
{
s.resize(size);
for (size_t i = 0; i < size; i++)
s[i] = char(getc());
}
return s;
}
////////////////////////////////////////////////////////////////////////////
void Generic_File::flush()
////////////////////////////////////////////////////////////////////////////
{
if (write_buffer_index)
write_buffer();
}
////////////////////////////////////////////////////////////////////////////
void Generic_File::destructor_flush() noexcept
////////////////////////////////////////////////////////////////////////////
{
if (write_buffer_index)
{
Destructor_Logger::write("warning: an unflushed file is being destroyed");
try
{
flush();
}
catch (...)
{
postpone_exception("failed to flush in Generic_File destructor");
}
}
}
////////////////////////////////////////////////////////////////////////////
void Generic_File::commit()
////////////////////////////////////////////////////////////////////////////
{
flush();
sync();
}
}
<|endoftext|>
|
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2014 Adam Dabrowski <adabrowski@piap.pl> <adamdbrw@gmail.com>
//
#include <MarbleQuickItem.h>
#include <QPainter>
#include <QPaintDevice>
#include <QtMath>
#include <MarbleModel.h>
#include <MarbleMap.h>
#include <ViewportParams.h>
#include <GeoPainter.h>
#include <GeoDataLookAt.h>
#include <MarbleLocale.h>
#include <Planet.h>
#include <MarbleAbstractPresenter.h>
#include <AbstractFloatItem.h>
#include <MarbleInputHandler.h>
#include <PositionTracking.h>
#include <PositionProviderPlugin.h>
#include <PluginManager.h>
#include <RenderPlugin.h>
namespace Marble
{
//TODO - move to separate files
class QuickItemSelectionRubber : public AbstractSelectionRubber
{ //TODO: support rubber selection in MarbleQuickItem
public:
void show() { m_visible = true; }
void hide() { m_visible = false; }
bool isVisible() const { return m_visible; }
const QRect &geometry() const { return m_geometry; }
void setGeometry(const QRect &/*geometry*/) {}
private:
QRect m_geometry;
bool m_visible;
};
//TODO - implement missing functionalities
class MarbleQuickInputHandler : public MarbleDefaultInputHandler
{
public:
MarbleQuickInputHandler(MarbleAbstractPresenter *marblePresenter, MarbleQuickItem *marbleQuick)
: MarbleDefaultInputHandler(marblePresenter)
,m_marbleQuick(marbleQuick)
{
setInertialEarthRotationEnabled(false); //Disabled by default, it's buggy. TODO - fix
}
bool acceptMouse()
{
return true;
}
void pinch(QPointF center, qreal scale, Qt::GestureState state)
{ //TODO - this whole thing should be moved to MarbleAbstractPresenter
(void)handlePinch(center, scale, state);
}
private slots:
void showLmbMenu(int, int) {}
void showRmbMenu(int, int) {}
void openItemToolTip() {}
void setCursor(const QCursor &cursor)
{
m_marbleQuick->setCursor(cursor);
}
private slots:
void installPluginEventFilter(RenderPlugin *) {}
private:
bool layersEventFilter(QObject *o, QEvent *e)
{
return m_marbleQuick->layersEventFilter(o, e);
}
//empty - don't check. It would be invalid with quick items
void checkReleasedMove(QMouseEvent *) {}
bool handleTouch(QTouchEvent *event)
{
if (event->touchPoints().count() > 1)
{ //not handling multi-touch at all, let PinchArea or MultiPointTouchArea take care of it
return false;
}
if (event->touchPoints().count() == 1)
{ //handle - but do not accept. I.e. pinchArea still needs to get this
QTouchEvent::TouchPoint p = event->touchPoints().at(0);
if (event->type() == QEvent::TouchBegin)
{
QMouseEvent press(QMouseEvent::MouseButtonPress, p.pos(),
Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
handleMouseEvent(&press);
}
else if (event->type() == QEvent::TouchUpdate)
{
QMouseEvent move(QMouseEvent::MouseMove, p.pos(),
Qt::NoButton, Qt::LeftButton, Qt::NoModifier);
handleMouseEvent(&move);
}
else if (event->type() == QEvent::TouchEnd)
{
QMouseEvent release(QMouseEvent::MouseButtonRelease, p.pos(),
Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
handleMouseEvent(&release);
}
}
return false;
}
AbstractSelectionRubber *selectionRubber()
{
return &m_selectionRubber;
}
MarbleQuickItem *m_marbleQuick;
QuickItemSelectionRubber m_selectionRubber;
bool m_usePinchArea;
};
class MarbleQuickItemPrivate : public MarbleAbstractPresenter
{
public:
MarbleQuickItemPrivate(MarbleQuickItem *marble) : MarbleAbstractPresenter()
,m_marble(marble)
,m_inputHandler(this, marble)
{
connect(this, SIGNAL(updateRequired()), m_marble, SLOT(update()));
}
private:
MarbleQuickItem *m_marble;
friend class MarbleQuickItem;
MarbleQuickInputHandler m_inputHandler;
};
MarbleQuickItem::MarbleQuickItem(QQuickItem *parent) : QQuickPaintedItem(parent)
,d(new MarbleQuickItemPrivate(this))
{
foreach (AbstractFloatItem *item, d->map()->floatItems())
{ //TODO: These are not supported in Marble Quick - need refactoring: show them only in
//MarbleWidget, MarbleQuickItem should not have them accessible
item->hide();
}
connect(d->map(), SIGNAL(repaintNeeded(QRegion)), this, SLOT(update()));
connect(this, SIGNAL(widthChanged()), this, SLOT(resizeMap()));
connect(this, SIGNAL(heightChanged()), this, SLOT(resizeMap()));
setAcceptedMouseButtons(Qt::AllButtons);
installEventFilter(&d->m_inputHandler);
}
void MarbleQuickItem::resizeMap()
{
const int minWidth = 100;
const int minHeight = 100;
int newWidth = width() > minWidth ? (int)width() : minWidth;
int newHeight = height() > minHeight ? (int)height() : minHeight;
d->map()->setSize(newWidth, newHeight);
update();
}
void MarbleQuickItem::paint(QPainter *painter)
{ //TODO - much to be done here still, i.e paint !enabled version
QPaintDevice *paintDevice = painter->device();
QImage image;
QRect rect = contentsBoundingRect().toRect();
{
painter->end();
GeoPainter geoPainter(paintDevice, d->map()->viewport(), d->map()->mapQuality());
d->map()->paint(geoPainter, rect);
}
painter->begin(paintDevice);
}
void MarbleQuickItem::classBegin()
{
}
void MarbleQuickItem::componentComplete()
{
}
int MarbleQuickItem::mapWidth() const
{
return d->map()->width();
}
int MarbleQuickItem::mapHeight() const
{
return d->map()->height();
}
bool MarbleQuickItem::showFrameRate() const
{
return d->map()->showFrameRate();
}
MarbleQuickItem::Projection MarbleQuickItem::projection() const
{
return (Projection)d->map()->projection();
}
QString MarbleQuickItem::mapThemeId() const
{
return d->map()->mapThemeId();
}
bool MarbleQuickItem::showAtmosphere() const
{
return d->map()->showAtmosphere();
}
bool MarbleQuickItem::showCompass() const
{
return d->map()->showCompass();
}
bool MarbleQuickItem::showClouds() const
{
return d->map()->showClouds();
}
bool MarbleQuickItem::showCrosshairs() const
{
return d->map()->showCrosshairs();
}
bool MarbleQuickItem::showGrid() const
{
return d->map()->showGrid();
}
bool MarbleQuickItem::showOverviewMap() const
{
return d->map()->showOverviewMap();
}
bool MarbleQuickItem::showOtherPlaces() const
{
return d->map()->showOtherPlaces();
}
bool MarbleQuickItem::showScaleBar() const
{
return d->map()->showScaleBar();
}
bool MarbleQuickItem::showBackground() const
{
return d->map()->showBackground();
}
bool MarbleQuickItem::showPositionMarker() const
{
QList<RenderPlugin *> plugins = d->map()->renderPlugins();
foreach (const RenderPlugin * plugin, plugins) {
if (plugin->nameId() == "positionMarker") {
return plugin->visible();
}
}
return false;
}
QString MarbleQuickItem::positionProvider() const
{
if ( this->model()->positionTracking()->positionProviderPlugin() ) {
return this->model()->positionTracking()->positionProviderPlugin()->nameId();
}
return "";
}
MarbleModel* MarbleQuickItem::model()
{
return d->model();
}
const MarbleModel* MarbleQuickItem::model() const
{
return d->model();
}
MarbleMap* MarbleQuickItem::map()
{
return d->map();
}
const MarbleMap* MarbleQuickItem::map() const
{
return d->map();
}
void MarbleQuickItem::setZoom(int newZoom, FlyToMode mode)
{
d->setZoom(newZoom, mode);
}
void MarbleQuickItem::centerOn(const GeoDataPlacemark& placemark, bool animated)
{
d->centerOn(placemark, animated);
}
void MarbleQuickItem::centerOn(const GeoDataLatLonBox& box, bool animated)
{
d->centerOn(box, animated);
}
void MarbleQuickItem::goHome()
{
d->goHome();
}
void MarbleQuickItem::zoomIn(FlyToMode mode)
{
d->zoomIn(mode);
}
void MarbleQuickItem::zoomOut(FlyToMode mode)
{
d->zoomOut(mode);
}
void MarbleQuickItem::handlePinchStarted(const QPointF &point)
{
pinch(point, 1, Qt::GestureStarted);
}
void MarbleQuickItem::handlePinchFinished(const QPointF &point)
{
pinch(point, 1, Qt::GestureFinished);
}
void MarbleQuickItem::handlePinchUpdated(const QPointF &point, qreal scale)
{
scale = sqrt(sqrt(scale));
scale = qBound(0.5, scale, 2.0);
pinch(point, scale, Qt::GestureUpdated);
}
void MarbleQuickItem::setMapWidth(int mapWidth)
{
if (d->map()->width() == mapWidth) {
return;
}
d->map()->setSize(mapWidth, mapHeight());
emit mapWidthChanged(mapWidth);
}
void MarbleQuickItem::setMapHeight(int mapHeight)
{
if (this->mapHeight() == mapHeight) {
return;
}
d->map()->setSize(mapWidth(), mapHeight);
emit mapHeightChanged(mapHeight);
}
void MarbleQuickItem::setShowFrameRate(bool showFrameRate)
{
if (this->showFrameRate() == showFrameRate) {
return;
}
d->map()->setShowFrameRate(showFrameRate);
emit showFrameRateChanged(showFrameRate);
}
void MarbleQuickItem::setProjection(Projection projection)
{
if (this->projection() == projection) {
return;
}
d->map()->setProjection((Marble::Projection)projection);
emit projectionChanged(projection);
}
void MarbleQuickItem::setMapThemeId(QString mapThemeId)
{
if (this->mapThemeId() == mapThemeId) {
return;
}
bool const showCompass = d->map()->showCompass();
bool const showOverviewMap = d->map()->showOverviewMap();
bool const showOtherPlaces = d->map()->showOtherPlaces();
bool const showGrid = d->map()->showGrid();
bool const showScaleBar = d->map()->showScaleBar();
d->map()->setMapThemeId(mapThemeId);
// Map themes are allowed to change properties. Enforce ours.
d->map()->setShowCompass(showCompass);
d->map()->setShowOverviewMap(showOverviewMap);
d->map()->setShowOtherPlaces(showOtherPlaces);
d->map()->setShowGrid(showGrid);
d->map()->setShowScaleBar(showScaleBar);
emit mapThemeIdChanged(mapThemeId);
}
void MarbleQuickItem::setShowAtmosphere(bool showAtmosphere)
{
if (this->showAtmosphere() == showAtmosphere) {
return;
}
d->map()->setShowAtmosphere(showAtmosphere);
emit showAtmosphereChanged(showAtmosphere);
}
void MarbleQuickItem::setShowCompass(bool showCompass)
{
if (this->showCompass() == showCompass) {
return;
}
d->map()->setShowCompass(showCompass);
emit showCompassChanged(showCompass);
}
void MarbleQuickItem::setShowClouds(bool showClouds)
{
if (this->showClouds() == showClouds) {
return;
}
d->map()->setShowClouds(showClouds);
emit showCloudsChanged(showClouds);
}
void MarbleQuickItem::setShowCrosshairs(bool showCrosshairs)
{
if (this->showCrosshairs() == showCrosshairs) {
return;
}
d->map()->setShowCrosshairs(showCrosshairs);
emit showCrosshairsChanged(showCrosshairs);
}
void MarbleQuickItem::setShowGrid(bool showGrid)
{
if (this->showGrid() == showGrid) {
return;
}
d->map()->setShowGrid(showGrid);
emit showGridChanged(showGrid);
}
void MarbleQuickItem::setShowOverviewMap(bool showOverviewMap)
{
if (this->showOverviewMap() == showOverviewMap) {
return;
}
d->map()->setShowOverviewMap(showOverviewMap);
emit showOverviewMapChanged(showOverviewMap);
}
void MarbleQuickItem::setShowOtherPlaces(bool showOtherPlaces)
{
if (this->showOtherPlaces() == showOtherPlaces) {
return;
}
d->map()->setShowOtherPlaces(showOtherPlaces);
emit showOtherPlacesChanged(showOtherPlaces);
}
void MarbleQuickItem::setShowScaleBar(bool showScaleBar)
{
if (this->showScaleBar() == showScaleBar) {
return;
}
d->map()->setShowScaleBar(showScaleBar);
emit showScaleBarChanged(showScaleBar);
}
void MarbleQuickItem::setShowBackground(bool showBackground)
{
if (this->showBackground() == showBackground) {
return;
}
d->map()->setShowBackground(showBackground);
emit showBackgroundChanged(showBackground);
}
void MarbleQuickItem::setShowPositionMarker(bool showPositionMarker)
{
if (this->showPositionMarker() == showPositionMarker) {
return;
}
QList<RenderPlugin *> plugins = d->map()->renderPlugins();
bool pluginExists = false;
foreach ( RenderPlugin * plugin, plugins ) {
if ( plugin->nameId() == "positionMarker" ) {
plugin->setVisible(showPositionMarker);
pluginExists = true;
break;
}
}
emit showPositionMarkerChanged(showPositionMarker);
}
void MarbleQuickItem::setPositionProvider(const QString &positionProvider)
{
QString name = "";
if ( this->model()->positionTracking()->positionProviderPlugin() ) {
name = this->model()->positionTracking()->positionProviderPlugin()->nameId();
if ( name == positionProvider ) {
return;
}
}
QList<const PositionProviderPlugin*> plugins = model()->pluginManager()->positionProviderPlugins();
foreach (const PositionProviderPlugin* plugin, plugins) {
if ( plugin->nameId() == positionProvider) {
model()->positionTracking()->setPositionProviderPlugin(plugin->newInstance());
emit positionProviderChanged(positionProvider);
break;
}
}
}
QObject *MarbleQuickItem::getEventFilter() const
{ //We would want to install the same event filter for abstract layer QuickItems such as PinchArea
return &d->m_inputHandler;
}
void MarbleQuickItem::pinch(QPointF center, qreal scale, Qt::GestureState state)
{
d->m_inputHandler.pinch(center, scale, state);
}
MarbleInputHandler *MarbleQuickItem::inputHandler()
{
return &d->m_inputHandler;
}
int MarbleQuickItem::zoom() const
{
return d->logzoom();
}
bool MarbleQuickItem::layersEventFilter(QObject *, QEvent *)
{ //Does nothing, but can be reimplemented in a subclass
return false;
}
}
<commit_msg>Remove write-only variable<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2014 Adam Dabrowski <adabrowski@piap.pl> <adamdbrw@gmail.com>
//
#include <MarbleQuickItem.h>
#include <QPainter>
#include <QPaintDevice>
#include <QtMath>
#include <MarbleModel.h>
#include <MarbleMap.h>
#include <ViewportParams.h>
#include <GeoPainter.h>
#include <GeoDataLookAt.h>
#include <MarbleLocale.h>
#include <Planet.h>
#include <MarbleAbstractPresenter.h>
#include <AbstractFloatItem.h>
#include <MarbleInputHandler.h>
#include <PositionTracking.h>
#include <PositionProviderPlugin.h>
#include <PluginManager.h>
#include <RenderPlugin.h>
namespace Marble
{
//TODO - move to separate files
class QuickItemSelectionRubber : public AbstractSelectionRubber
{ //TODO: support rubber selection in MarbleQuickItem
public:
void show() { m_visible = true; }
void hide() { m_visible = false; }
bool isVisible() const { return m_visible; }
const QRect &geometry() const { return m_geometry; }
void setGeometry(const QRect &/*geometry*/) {}
private:
QRect m_geometry;
bool m_visible;
};
//TODO - implement missing functionalities
class MarbleQuickInputHandler : public MarbleDefaultInputHandler
{
public:
MarbleQuickInputHandler(MarbleAbstractPresenter *marblePresenter, MarbleQuickItem *marbleQuick)
: MarbleDefaultInputHandler(marblePresenter)
,m_marbleQuick(marbleQuick)
{
setInertialEarthRotationEnabled(false); //Disabled by default, it's buggy. TODO - fix
}
bool acceptMouse()
{
return true;
}
void pinch(QPointF center, qreal scale, Qt::GestureState state)
{ //TODO - this whole thing should be moved to MarbleAbstractPresenter
(void)handlePinch(center, scale, state);
}
private slots:
void showLmbMenu(int, int) {}
void showRmbMenu(int, int) {}
void openItemToolTip() {}
void setCursor(const QCursor &cursor)
{
m_marbleQuick->setCursor(cursor);
}
private slots:
void installPluginEventFilter(RenderPlugin *) {}
private:
bool layersEventFilter(QObject *o, QEvent *e)
{
return m_marbleQuick->layersEventFilter(o, e);
}
//empty - don't check. It would be invalid with quick items
void checkReleasedMove(QMouseEvent *) {}
bool handleTouch(QTouchEvent *event)
{
if (event->touchPoints().count() > 1)
{ //not handling multi-touch at all, let PinchArea or MultiPointTouchArea take care of it
return false;
}
if (event->touchPoints().count() == 1)
{ //handle - but do not accept. I.e. pinchArea still needs to get this
QTouchEvent::TouchPoint p = event->touchPoints().at(0);
if (event->type() == QEvent::TouchBegin)
{
QMouseEvent press(QMouseEvent::MouseButtonPress, p.pos(),
Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
handleMouseEvent(&press);
}
else if (event->type() == QEvent::TouchUpdate)
{
QMouseEvent move(QMouseEvent::MouseMove, p.pos(),
Qt::NoButton, Qt::LeftButton, Qt::NoModifier);
handleMouseEvent(&move);
}
else if (event->type() == QEvent::TouchEnd)
{
QMouseEvent release(QMouseEvent::MouseButtonRelease, p.pos(),
Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
handleMouseEvent(&release);
}
}
return false;
}
AbstractSelectionRubber *selectionRubber()
{
return &m_selectionRubber;
}
MarbleQuickItem *m_marbleQuick;
QuickItemSelectionRubber m_selectionRubber;
bool m_usePinchArea;
};
class MarbleQuickItemPrivate : public MarbleAbstractPresenter
{
public:
MarbleQuickItemPrivate(MarbleQuickItem *marble) : MarbleAbstractPresenter()
,m_marble(marble)
,m_inputHandler(this, marble)
{
connect(this, SIGNAL(updateRequired()), m_marble, SLOT(update()));
}
private:
MarbleQuickItem *m_marble;
friend class MarbleQuickItem;
MarbleQuickInputHandler m_inputHandler;
};
MarbleQuickItem::MarbleQuickItem(QQuickItem *parent) : QQuickPaintedItem(parent)
,d(new MarbleQuickItemPrivate(this))
{
foreach (AbstractFloatItem *item, d->map()->floatItems())
{ //TODO: These are not supported in Marble Quick - need refactoring: show them only in
//MarbleWidget, MarbleQuickItem should not have them accessible
item->hide();
}
connect(d->map(), SIGNAL(repaintNeeded(QRegion)), this, SLOT(update()));
connect(this, SIGNAL(widthChanged()), this, SLOT(resizeMap()));
connect(this, SIGNAL(heightChanged()), this, SLOT(resizeMap()));
setAcceptedMouseButtons(Qt::AllButtons);
installEventFilter(&d->m_inputHandler);
}
void MarbleQuickItem::resizeMap()
{
const int minWidth = 100;
const int minHeight = 100;
int newWidth = width() > minWidth ? (int)width() : minWidth;
int newHeight = height() > minHeight ? (int)height() : minHeight;
d->map()->setSize(newWidth, newHeight);
update();
}
void MarbleQuickItem::paint(QPainter *painter)
{ //TODO - much to be done here still, i.e paint !enabled version
QPaintDevice *paintDevice = painter->device();
QImage image;
QRect rect = contentsBoundingRect().toRect();
{
painter->end();
GeoPainter geoPainter(paintDevice, d->map()->viewport(), d->map()->mapQuality());
d->map()->paint(geoPainter, rect);
}
painter->begin(paintDevice);
}
void MarbleQuickItem::classBegin()
{
}
void MarbleQuickItem::componentComplete()
{
}
int MarbleQuickItem::mapWidth() const
{
return d->map()->width();
}
int MarbleQuickItem::mapHeight() const
{
return d->map()->height();
}
bool MarbleQuickItem::showFrameRate() const
{
return d->map()->showFrameRate();
}
MarbleQuickItem::Projection MarbleQuickItem::projection() const
{
return (Projection)d->map()->projection();
}
QString MarbleQuickItem::mapThemeId() const
{
return d->map()->mapThemeId();
}
bool MarbleQuickItem::showAtmosphere() const
{
return d->map()->showAtmosphere();
}
bool MarbleQuickItem::showCompass() const
{
return d->map()->showCompass();
}
bool MarbleQuickItem::showClouds() const
{
return d->map()->showClouds();
}
bool MarbleQuickItem::showCrosshairs() const
{
return d->map()->showCrosshairs();
}
bool MarbleQuickItem::showGrid() const
{
return d->map()->showGrid();
}
bool MarbleQuickItem::showOverviewMap() const
{
return d->map()->showOverviewMap();
}
bool MarbleQuickItem::showOtherPlaces() const
{
return d->map()->showOtherPlaces();
}
bool MarbleQuickItem::showScaleBar() const
{
return d->map()->showScaleBar();
}
bool MarbleQuickItem::showBackground() const
{
return d->map()->showBackground();
}
bool MarbleQuickItem::showPositionMarker() const
{
QList<RenderPlugin *> plugins = d->map()->renderPlugins();
foreach (const RenderPlugin * plugin, plugins) {
if (plugin->nameId() == "positionMarker") {
return plugin->visible();
}
}
return false;
}
QString MarbleQuickItem::positionProvider() const
{
if ( this->model()->positionTracking()->positionProviderPlugin() ) {
return this->model()->positionTracking()->positionProviderPlugin()->nameId();
}
return "";
}
MarbleModel* MarbleQuickItem::model()
{
return d->model();
}
const MarbleModel* MarbleQuickItem::model() const
{
return d->model();
}
MarbleMap* MarbleQuickItem::map()
{
return d->map();
}
const MarbleMap* MarbleQuickItem::map() const
{
return d->map();
}
void MarbleQuickItem::setZoom(int newZoom, FlyToMode mode)
{
d->setZoom(newZoom, mode);
}
void MarbleQuickItem::centerOn(const GeoDataPlacemark& placemark, bool animated)
{
d->centerOn(placemark, animated);
}
void MarbleQuickItem::centerOn(const GeoDataLatLonBox& box, bool animated)
{
d->centerOn(box, animated);
}
void MarbleQuickItem::goHome()
{
d->goHome();
}
void MarbleQuickItem::zoomIn(FlyToMode mode)
{
d->zoomIn(mode);
}
void MarbleQuickItem::zoomOut(FlyToMode mode)
{
d->zoomOut(mode);
}
void MarbleQuickItem::handlePinchStarted(const QPointF &point)
{
pinch(point, 1, Qt::GestureStarted);
}
void MarbleQuickItem::handlePinchFinished(const QPointF &point)
{
pinch(point, 1, Qt::GestureFinished);
}
void MarbleQuickItem::handlePinchUpdated(const QPointF &point, qreal scale)
{
scale = sqrt(sqrt(scale));
scale = qBound(0.5, scale, 2.0);
pinch(point, scale, Qt::GestureUpdated);
}
void MarbleQuickItem::setMapWidth(int mapWidth)
{
if (d->map()->width() == mapWidth) {
return;
}
d->map()->setSize(mapWidth, mapHeight());
emit mapWidthChanged(mapWidth);
}
void MarbleQuickItem::setMapHeight(int mapHeight)
{
if (this->mapHeight() == mapHeight) {
return;
}
d->map()->setSize(mapWidth(), mapHeight);
emit mapHeightChanged(mapHeight);
}
void MarbleQuickItem::setShowFrameRate(bool showFrameRate)
{
if (this->showFrameRate() == showFrameRate) {
return;
}
d->map()->setShowFrameRate(showFrameRate);
emit showFrameRateChanged(showFrameRate);
}
void MarbleQuickItem::setProjection(Projection projection)
{
if (this->projection() == projection) {
return;
}
d->map()->setProjection((Marble::Projection)projection);
emit projectionChanged(projection);
}
void MarbleQuickItem::setMapThemeId(QString mapThemeId)
{
if (this->mapThemeId() == mapThemeId) {
return;
}
bool const showCompass = d->map()->showCompass();
bool const showOverviewMap = d->map()->showOverviewMap();
bool const showOtherPlaces = d->map()->showOtherPlaces();
bool const showGrid = d->map()->showGrid();
bool const showScaleBar = d->map()->showScaleBar();
d->map()->setMapThemeId(mapThemeId);
// Map themes are allowed to change properties. Enforce ours.
d->map()->setShowCompass(showCompass);
d->map()->setShowOverviewMap(showOverviewMap);
d->map()->setShowOtherPlaces(showOtherPlaces);
d->map()->setShowGrid(showGrid);
d->map()->setShowScaleBar(showScaleBar);
emit mapThemeIdChanged(mapThemeId);
}
void MarbleQuickItem::setShowAtmosphere(bool showAtmosphere)
{
if (this->showAtmosphere() == showAtmosphere) {
return;
}
d->map()->setShowAtmosphere(showAtmosphere);
emit showAtmosphereChanged(showAtmosphere);
}
void MarbleQuickItem::setShowCompass(bool showCompass)
{
if (this->showCompass() == showCompass) {
return;
}
d->map()->setShowCompass(showCompass);
emit showCompassChanged(showCompass);
}
void MarbleQuickItem::setShowClouds(bool showClouds)
{
if (this->showClouds() == showClouds) {
return;
}
d->map()->setShowClouds(showClouds);
emit showCloudsChanged(showClouds);
}
void MarbleQuickItem::setShowCrosshairs(bool showCrosshairs)
{
if (this->showCrosshairs() == showCrosshairs) {
return;
}
d->map()->setShowCrosshairs(showCrosshairs);
emit showCrosshairsChanged(showCrosshairs);
}
void MarbleQuickItem::setShowGrid(bool showGrid)
{
if (this->showGrid() == showGrid) {
return;
}
d->map()->setShowGrid(showGrid);
emit showGridChanged(showGrid);
}
void MarbleQuickItem::setShowOverviewMap(bool showOverviewMap)
{
if (this->showOverviewMap() == showOverviewMap) {
return;
}
d->map()->setShowOverviewMap(showOverviewMap);
emit showOverviewMapChanged(showOverviewMap);
}
void MarbleQuickItem::setShowOtherPlaces(bool showOtherPlaces)
{
if (this->showOtherPlaces() == showOtherPlaces) {
return;
}
d->map()->setShowOtherPlaces(showOtherPlaces);
emit showOtherPlacesChanged(showOtherPlaces);
}
void MarbleQuickItem::setShowScaleBar(bool showScaleBar)
{
if (this->showScaleBar() == showScaleBar) {
return;
}
d->map()->setShowScaleBar(showScaleBar);
emit showScaleBarChanged(showScaleBar);
}
void MarbleQuickItem::setShowBackground(bool showBackground)
{
if (this->showBackground() == showBackground) {
return;
}
d->map()->setShowBackground(showBackground);
emit showBackgroundChanged(showBackground);
}
void MarbleQuickItem::setShowPositionMarker(bool showPositionMarker)
{
if (this->showPositionMarker() == showPositionMarker) {
return;
}
QList<RenderPlugin *> plugins = d->map()->renderPlugins();
foreach ( RenderPlugin * plugin, plugins ) {
if ( plugin->nameId() == "positionMarker" ) {
plugin->setVisible(showPositionMarker);
break;
}
}
emit showPositionMarkerChanged(showPositionMarker);
}
void MarbleQuickItem::setPositionProvider(const QString &positionProvider)
{
QString name = "";
if ( this->model()->positionTracking()->positionProviderPlugin() ) {
name = this->model()->positionTracking()->positionProviderPlugin()->nameId();
if ( name == positionProvider ) {
return;
}
}
QList<const PositionProviderPlugin*> plugins = model()->pluginManager()->positionProviderPlugins();
foreach (const PositionProviderPlugin* plugin, plugins) {
if ( plugin->nameId() == positionProvider) {
model()->positionTracking()->setPositionProviderPlugin(plugin->newInstance());
emit positionProviderChanged(positionProvider);
break;
}
}
}
QObject *MarbleQuickItem::getEventFilter() const
{ //We would want to install the same event filter for abstract layer QuickItems such as PinchArea
return &d->m_inputHandler;
}
void MarbleQuickItem::pinch(QPointF center, qreal scale, Qt::GestureState state)
{
d->m_inputHandler.pinch(center, scale, state);
}
MarbleInputHandler *MarbleQuickItem::inputHandler()
{
return &d->m_inputHandler;
}
int MarbleQuickItem::zoom() const
{
return d->logzoom();
}
bool MarbleQuickItem::layersEventFilter(QObject *, QEvent *)
{ //Does nothing, but can be reimplemented in a subclass
return false;
}
}
<|endoftext|>
|
<commit_before>#include "crypto_utils.h"
#include <glibmm.h>
#include <openssl/pem.h>
#include <openssl/pkcs12.h>
#include <openssl/err.h>
#include <global_def.h>
#define UTIL_SECURITY_BUFFER_SIZE 2048
#define log_function_debug(X, ...) Davix::davix_log_debug(X, ##__VA_ARGS__)
static const std::string & check_openssl_error(const char * domain, int err_code, const char* msg){
unsigned long myerr = ERR_get_error();
char buffer[UTIL_SECURITY_BUFFER_SIZE]= {0};
ERR_error_string_n(myerr, buffer, UTIL_SECURITY_BUFFER_SIZE);
ERR_remove_state(0);
throw Glib::Error(Glib::Quark(domain), err_code, std::string(msg).append(buffer));
}
/**
Try to convert a PEM credential to a p12 credential from memory string
@throw Glib::Error
*/
ssize_t convert_x509_to_p12(const char *privkey, const char *clicert, const char* password, char *p12cert, size_t p12_size)
{
X509 *cert;
PKCS12 *p12;
EVP_PKEY *cert_privkey;
size_t bytes = 0;
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
/* Read the private key file */
if ((cert_privkey = EVP_PKEY_new()) == NULL){
check_openssl_error("convert_x509_to_p12", UTILS_SECURITY_ERROR_INSTANCE, "Unable to instance cert_privkey" );
}
log_function_debug(" convert_x509_to_p12 -> try to read private Key....");
BIO *priv_key_mem = BIO_new_mem_buf((char*)privkey, -1);
if (! (cert_privkey = PEM_read_bio_PrivateKey(priv_key_mem, NULL, NULL, (char*)password))){
check_openssl_error("convert_x509_to_p12", UTILS_SECURITY_ERROR_PRIVATEKEY, "Unable to open Private Key ");
}
log_function_debug(" convert_x509_to_p12 -> try to read User CERT ....");
BIO *cert_mem = BIO_new_mem_buf((char*)clicert, -1);
if (! (cert = PEM_read_bio_X509(cert_mem, NULL, NULL, NULL))){
check_openssl_error("convert_x509_to_p12", UTILS_SECURITY_ERROR_CERT, "Unable to open CERT ");
}
if ((p12 = PKCS12_new()) == NULL){
check_openssl_error("convert_x509_to_p12", UTILS_SECURITY_ERROR_INSTANCE, "Unable to creat pkcs12 ");
}
log_function_debug(" Merge Private Key and CERT to p12 ....");
p12 = PKCS12_create(NULL, NULL, cert_privkey, cert, NULL, 0, 0, 0, 0, 0);
if ( p12 == NULL){
check_openssl_error("convert_x509_to_p12", UTILS_SECURITY_ERROR_PKCS12, "Unable to convert pem to pkcs12, wrong format ");
}
BIO *p12_mem = BIO_new(BIO_s_mem());
if(( bytes = i2d_PKCS12_bio(p12_mem, p12)) <0 ){
check_openssl_error("convert_x509_to_p12", UTILS_SECURITY_ERROR_INSTANCE, "Unable to convert p12 to membuff ");
}
if( bytes+1 > p12_size)
check_openssl_error("convert_x509_to_p12", ENOMEM, "No such space in buffer for key storage ");
ssize_t ret = BIO_read(p12_mem, p12cert, p12_size);
if(ret < 0){
std::stringstream s;
s << "Bad Read to the OpenSSL Bio handle " << ret << " " << p12_size << std::endl;
throw Glib::Error(Glib::Quark("convert_x509_to_p12"), EINVAL, s.str());
}
p12cert[ret]= '\0';
PKCS12_free(p12);
// NOT MEMORY SAFE §§§§§§ investigations Needed
return ret;
}
<commit_msg>- minor fix for EL5 sstream<commit_after>#include "crypto_utils.h"
#include <glibmm.h>
#include <sstream>
#include <openssl/pem.h>
#include <openssl/pkcs12.h>
#include <openssl/err.h>
#include <global_def.h>
#define UTIL_SECURITY_BUFFER_SIZE 2048
#define log_function_debug(X, ...) Davix::davix_log_debug(X, ##__VA_ARGS__)
static const std::string & check_openssl_error(const char * domain, int err_code, const char* msg){
unsigned long myerr = ERR_get_error();
char buffer[UTIL_SECURITY_BUFFER_SIZE]= {0};
ERR_error_string_n(myerr, buffer, UTIL_SECURITY_BUFFER_SIZE);
ERR_remove_state(0);
throw Glib::Error(Glib::Quark(domain), err_code, std::string(msg).append(buffer));
}
/**
Try to convert a PEM credential to a p12 credential from memory string
@throw Glib::Error
*/
ssize_t convert_x509_to_p12(const char *privkey, const char *clicert, const char* password, char *p12cert, size_t p12_size)
{
X509 *cert;
PKCS12 *p12;
EVP_PKEY *cert_privkey;
size_t bytes = 0;
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
/* Read the private key file */
if ((cert_privkey = EVP_PKEY_new()) == NULL){
check_openssl_error("convert_x509_to_p12", UTILS_SECURITY_ERROR_INSTANCE, "Unable to instance cert_privkey" );
}
log_function_debug(" convert_x509_to_p12 -> try to read private Key....");
BIO *priv_key_mem = BIO_new_mem_buf((char*)privkey, -1);
if (! (cert_privkey = PEM_read_bio_PrivateKey(priv_key_mem, NULL, NULL, (char*)password))){
check_openssl_error("convert_x509_to_p12", UTILS_SECURITY_ERROR_PRIVATEKEY, "Unable to open Private Key ");
}
log_function_debug(" convert_x509_to_p12 -> try to read User CERT ....");
BIO *cert_mem = BIO_new_mem_buf((char*)clicert, -1);
if (! (cert = PEM_read_bio_X509(cert_mem, NULL, NULL, NULL))){
check_openssl_error("convert_x509_to_p12", UTILS_SECURITY_ERROR_CERT, "Unable to open CERT ");
}
if ((p12 = PKCS12_new()) == NULL){
check_openssl_error("convert_x509_to_p12", UTILS_SECURITY_ERROR_INSTANCE, "Unable to creat pkcs12 ");
}
log_function_debug(" Merge Private Key and CERT to p12 ....");
p12 = PKCS12_create(NULL, NULL, cert_privkey, cert, NULL, 0, 0, 0, 0, 0);
if ( p12 == NULL){
check_openssl_error("convert_x509_to_p12", UTILS_SECURITY_ERROR_PKCS12, "Unable to convert pem to pkcs12, wrong format ");
}
BIO *p12_mem = BIO_new(BIO_s_mem());
if(( bytes = i2d_PKCS12_bio(p12_mem, p12)) <0 ){
check_openssl_error("convert_x509_to_p12", UTILS_SECURITY_ERROR_INSTANCE, "Unable to convert p12 to membuff ");
}
if( bytes+1 > p12_size)
check_openssl_error("convert_x509_to_p12", ENOMEM, "No such space in buffer for key storage ");
ssize_t ret = BIO_read(p12_mem, p12cert, p12_size);
if(ret < 0){
std::stringstream s;
s << "Bad Read to the OpenSSL Bio handle " << ret << " " << p12_size << std::endl;
throw Glib::Error(Glib::Quark("convert_x509_to_p12"), EINVAL, s.str());
}
p12cert[ret]= '\0';
PKCS12_free(p12);
// NOT MEMORY SAFE §§§§§§ investigations Needed
return ret;
}
<|endoftext|>
|
<commit_before>#include "logvisor/logvisor.hpp"
#include "boo/boo.hpp"
#include "specter/specter.hpp"
#include "hecl/CVarManager.hpp"
#include "Runtime/CBasics.hpp"
#include "ViewManager.hpp"
#include "hecl/hecl.hpp"
#include "hecl/CVarCommons.hpp"
#include "hecl/Console.hpp"
static logvisor::Module AthenaLog("Athena");
static void AthenaExc(athena::error::Level level, const char* file, const char*, int line, fmt::string_view fmt,
fmt::format_args args) {
AthenaLog.vreport(logvisor::Level(level), fmt, args);
}
namespace urde {
static logvisor::Module Log{"URDE"};
static hecl::SystemString CPUFeatureString(const zeus::CPUInfo& cpuInf) {
hecl::SystemString features;
auto AddFeature = [&features](const hecl::SystemChar* str) {
if (!features.empty())
features += _SYS_STR(", ");
features += str;
};
if (cpuInf.AESNI)
AddFeature(_SYS_STR("AES-NI"));
if (cpuInf.SSE1)
AddFeature(_SYS_STR("SSE"));
if (cpuInf.SSE2)
AddFeature(_SYS_STR("SSE2"));
if (cpuInf.SSE3)
AddFeature(_SYS_STR("SSE3"));
if (cpuInf.SSSE3)
AddFeature(_SYS_STR("SSSE3"));
if (cpuInf.SSE4a)
AddFeature(_SYS_STR("SSE4a"));
if (cpuInf.SSE41)
AddFeature(_SYS_STR("SSE4.1"));
if (cpuInf.SSE42)
AddFeature(_SYS_STR("SSE4.2"));
if (cpuInf.AVX)
AddFeature(_SYS_STR("AVX"));
if (cpuInf.AVX2)
AddFeature(_SYS_STR("AVX2"));
return features;
}
struct Application : boo::IApplicationCallback {
hecl::Runtime::FileStoreManager& m_fileMgr;
hecl::CVarManager& m_cvarManager;
hecl::CVarCommons& m_cvarCommons;
std::unique_ptr<ViewManager> m_viewManager;
std::atomic_bool m_running = {true};
Application(hecl::Runtime::FileStoreManager& fileMgr, hecl::CVarManager& cvarMgr, hecl::CVarCommons& cvarCmns)
: m_fileMgr(fileMgr)
, m_cvarManager(cvarMgr)
, m_cvarCommons(cvarCmns)
, m_viewManager(std::make_unique<ViewManager>(m_fileMgr, m_cvarManager)) {}
virtual ~Application() = default;
int appMain(boo::IApplication* app) override {
initialize(app);
m_viewManager->init(app);
while (m_running.load()) {
if (!m_viewManager->proc())
break;
}
m_viewManager->stop();
m_viewManager->projectManager().saveProject();
m_cvarManager.serialize();
m_viewManager.reset();
return 0;
}
void appQuitting(boo::IApplication*) override { m_running.store(false); }
void appFilesOpen(boo::IApplication*, const std::vector<boo::SystemString>& paths) override {
for (const auto& path : paths) {
hecl::ProjectRootPath projPath = hecl::SearchForProject(path);
if (projPath) {
m_viewManager->deferOpenProject(path);
break;
}
}
}
void initialize(boo::IApplication* app) {
zeus::detectCPU();
for (const boo::SystemString& arg : app->getArgs()) {
if (arg.find(_SYS_STR("--verbosity=")) == 0 || arg.find(_SYS_STR("-v=")) == 0) {
hecl::SystemUTF8Conv utf8Arg(arg.substr(arg.find_last_of('=') + 1));
hecl::VerbosityLevel = atoi(utf8Arg.c_str());
hecl::LogModule.report(logvisor::Info, FMT_STRING("Set verbosity level to {}"), hecl::VerbosityLevel);
}
}
m_cvarManager.parseCommandLine(app->getArgs());
const zeus::CPUInfo& cpuInf = zeus::cpuFeatures();
Log.report(logvisor::Info, FMT_STRING("CPU Name: {}"), cpuInf.cpuBrand);
Log.report(logvisor::Info, FMT_STRING("CPU Vendor: {}"), cpuInf.cpuVendor);
Log.report(logvisor::Info, FMT_STRING(_SYS_STR("CPU Features: {}")), CPUFeatureString(cpuInf));
}
std::string getGraphicsApi() const { return m_cvarCommons.getGraphicsApi(); }
uint32_t getSamples() const { return m_cvarCommons.getSamples(); }
uint32_t getAnisotropy() const { return m_cvarCommons.getAnisotropy(); }
bool getDeepColor() const { return m_cvarCommons.getDeepColor(); }
};
} // namespace urde
static hecl::SystemChar CwdBuf[1024];
hecl::SystemString ExeDir;
static void SetupBasics(bool logging) {
auto result = zeus::validateCPU();
if (!result.first) {
#if _WIN32 && !WINDOWS_STORE
std::wstring msg = fmt::format(FMT_STRING(L"ERROR: This build of URDE requires the following CPU features:\n{}\n"),
urde::CPUFeatureString(result.second));
MessageBoxW(nullptr, msg.c_str(), L"CPU error", MB_OK | MB_ICONERROR);
#else
fmt::print(stderr, FMT_STRING("ERROR: This build of URDE requires the following CPU features:\n{}\n"),
urde::CPUFeatureString(result.second));
#endif
exit(1);
}
logvisor::RegisterStandardExceptions();
if (logging)
logvisor::RegisterConsoleLogger();
atSetExceptionHandler(AthenaExc);
}
static bool IsClientLoggingEnabled(int argc, const boo::SystemChar** argv) {
for (int i = 1; i < argc; ++i)
if (!hecl::StrNCmp(argv[i], _SYS_STR("-l"), 2))
return true;
return false;
}
#if !WINDOWS_STORE
#if _WIN32
int wmain(int argc, const boo::SystemChar** argv)
#else
int main(int argc, const boo::SystemChar** argv)
#endif
{
if (argc > 1 && !hecl::StrCmp(argv[1], _SYS_STR("--dlpackage"))) {
fmt::print(FMT_STRING("{}\n"), URDE_DLPACKAGE);
return 100;
}
SetupBasics(IsClientLoggingEnabled(argc, argv));
hecl::Runtime::FileStoreManager fileMgr{_SYS_STR("urde")};
hecl::CVarManager cvarMgr{fileMgr};
hecl::CVarCommons cvarCmns{cvarMgr};
hecl::SystemStringView logFile = hecl::SystemStringConv(cvarCmns.getLogFile()).sys_str();
hecl::SystemString logFilePath;
if (!logFile.empty()) {
logFilePath = fmt::format(FMT_STRING(_SYS_STR("{}/{}")), fileMgr.getStoreRoot(), logFile);
logvisor::RegisterFileLogger(logFilePath.c_str());
}
if (hecl::SystemChar* cwd = hecl::Getcwd(CwdBuf, 1024)) {
if (hecl::PathRelative(argv[0]))
ExeDir = hecl::SystemString(cwd) + _SYS_STR('/');
hecl::SystemString Argv0(argv[0]);
hecl::SystemString::size_type lastIdx = Argv0.find_last_of(_SYS_STR("/\\"));
if (lastIdx != hecl::SystemString::npos)
ExeDir.insert(ExeDir.end(), Argv0.begin(), Argv0.begin() + lastIdx);
}
/* Handle -j argument */
hecl::SetCpuCountOverride(argc, argv);
urde::Application appCb(fileMgr, cvarMgr, cvarCmns);
int ret = boo::ApplicationRun(boo::IApplication::EPlatformType::Auto, appCb, _SYS_STR("urde"), _SYS_STR("URDE"), argc,
argv, appCb.getGraphicsApi(), appCb.getSamples(), appCb.getAnisotropy(),
appCb.getDeepColor(), false);
// printf("IM DYING!!\n");
return ret;
}
#endif
#if WINDOWS_STORE
#include "boo/UWPViewProvider.hpp"
using namespace Windows::ApplicationModel::Core;
[Platform::MTAThread] int WINAPIV main(Platform::Array<Platform::String ^> ^ params) {
SetupBasics(false);
urde::Application appCb;
auto viewProvider =
ref new boo::ViewProvider(appCb, _SYS_STR("urde"), _SYS_STR("URDE"), _SYS_STR("urde"), params, false);
CoreApplication::Run(viewProvider);
return 0;
}
#elif _WIN32
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE, LPWSTR lpCmdLine, int) {
int argc = 0;
const boo::SystemChar** argv;
if (lpCmdLine[0])
argv = (const wchar_t**)(CommandLineToArgvW(lpCmdLine, &argc));
static boo::SystemChar selfPath[1024];
GetModuleFileNameW(nullptr, selfPath, 1024);
static const boo::SystemChar* booArgv[32] = {};
booArgv[0] = selfPath;
for (int i = 0; i < argc; ++i)
booArgv[i + 1] = argv[i];
const DWORD outType = GetFileType(GetStdHandle(STD_OUTPUT_HANDLE));
if (IsClientLoggingEnabled(argc + 1, booArgv) && outType == FILE_TYPE_UNKNOWN)
logvisor::CreateWin32Console();
return wmain(argc + 1, booArgv);
}
#endif
<commit_msg>Add date-time to start of log file name<commit_after>#include "logvisor/logvisor.hpp"
#include "boo/boo.hpp"
#include "specter/specter.hpp"
#include "hecl/CVarManager.hpp"
#include "Runtime/CBasics.hpp"
#include "ViewManager.hpp"
#include "hecl/hecl.hpp"
#include "hecl/CVarCommons.hpp"
#include "hecl/Console.hpp"
#include "fmt/chrono.h"
static logvisor::Module AthenaLog("Athena");
static void AthenaExc(athena::error::Level level, const char* file, const char*, int line, fmt::string_view fmt,
fmt::format_args args) {
AthenaLog.vreport(logvisor::Level(level), fmt, args);
}
namespace urde {
static logvisor::Module Log{"URDE"};
static hecl::SystemString CPUFeatureString(const zeus::CPUInfo& cpuInf) {
hecl::SystemString features;
auto AddFeature = [&features](const hecl::SystemChar* str) {
if (!features.empty())
features += _SYS_STR(", ");
features += str;
};
if (cpuInf.AESNI)
AddFeature(_SYS_STR("AES-NI"));
if (cpuInf.SSE1)
AddFeature(_SYS_STR("SSE"));
if (cpuInf.SSE2)
AddFeature(_SYS_STR("SSE2"));
if (cpuInf.SSE3)
AddFeature(_SYS_STR("SSE3"));
if (cpuInf.SSSE3)
AddFeature(_SYS_STR("SSSE3"));
if (cpuInf.SSE4a)
AddFeature(_SYS_STR("SSE4a"));
if (cpuInf.SSE41)
AddFeature(_SYS_STR("SSE4.1"));
if (cpuInf.SSE42)
AddFeature(_SYS_STR("SSE4.2"));
if (cpuInf.AVX)
AddFeature(_SYS_STR("AVX"));
if (cpuInf.AVX2)
AddFeature(_SYS_STR("AVX2"));
return features;
}
struct Application : boo::IApplicationCallback {
hecl::Runtime::FileStoreManager& m_fileMgr;
hecl::CVarManager& m_cvarManager;
hecl::CVarCommons& m_cvarCommons;
std::unique_ptr<ViewManager> m_viewManager;
std::atomic_bool m_running = {true};
Application(hecl::Runtime::FileStoreManager& fileMgr, hecl::CVarManager& cvarMgr, hecl::CVarCommons& cvarCmns)
: m_fileMgr(fileMgr)
, m_cvarManager(cvarMgr)
, m_cvarCommons(cvarCmns)
, m_viewManager(std::make_unique<ViewManager>(m_fileMgr, m_cvarManager)) {}
virtual ~Application() = default;
int appMain(boo::IApplication* app) override {
initialize(app);
m_viewManager->init(app);
while (m_running.load()) {
if (!m_viewManager->proc())
break;
}
m_viewManager->stop();
m_viewManager->projectManager().saveProject();
m_cvarManager.serialize();
m_viewManager.reset();
return 0;
}
void appQuitting(boo::IApplication*) override { m_running.store(false); }
void appFilesOpen(boo::IApplication*, const std::vector<boo::SystemString>& paths) override {
for (const auto& path : paths) {
hecl::ProjectRootPath projPath = hecl::SearchForProject(path);
if (projPath) {
m_viewManager->deferOpenProject(path);
break;
}
}
}
void initialize(boo::IApplication* app) {
zeus::detectCPU();
for (const boo::SystemString& arg : app->getArgs()) {
if (arg.find(_SYS_STR("--verbosity=")) == 0 || arg.find(_SYS_STR("-v=")) == 0) {
hecl::SystemUTF8Conv utf8Arg(arg.substr(arg.find_last_of('=') + 1));
hecl::VerbosityLevel = atoi(utf8Arg.c_str());
hecl::LogModule.report(logvisor::Info, FMT_STRING("Set verbosity level to {}"), hecl::VerbosityLevel);
}
}
m_cvarManager.parseCommandLine(app->getArgs());
const zeus::CPUInfo& cpuInf = zeus::cpuFeatures();
Log.report(logvisor::Info, FMT_STRING("CPU Name: {}"), cpuInf.cpuBrand);
Log.report(logvisor::Info, FMT_STRING("CPU Vendor: {}"), cpuInf.cpuVendor);
Log.report(logvisor::Info, FMT_STRING(_SYS_STR("CPU Features: {}")), CPUFeatureString(cpuInf));
}
std::string getGraphicsApi() const { return m_cvarCommons.getGraphicsApi(); }
uint32_t getSamples() const { return m_cvarCommons.getSamples(); }
uint32_t getAnisotropy() const { return m_cvarCommons.getAnisotropy(); }
bool getDeepColor() const { return m_cvarCommons.getDeepColor(); }
};
} // namespace urde
static hecl::SystemChar CwdBuf[1024];
hecl::SystemString ExeDir;
static void SetupBasics(bool logging) {
auto result = zeus::validateCPU();
if (!result.first) {
#if _WIN32 && !WINDOWS_STORE
std::wstring msg = fmt::format(FMT_STRING(L"ERROR: This build of URDE requires the following CPU features:\n{}\n"),
urde::CPUFeatureString(result.second));
MessageBoxW(nullptr, msg.c_str(), L"CPU error", MB_OK | MB_ICONERROR);
#else
fmt::print(stderr, FMT_STRING("ERROR: This build of URDE requires the following CPU features:\n{}\n"),
urde::CPUFeatureString(result.second));
#endif
exit(1);
}
logvisor::RegisterStandardExceptions();
if (logging)
logvisor::RegisterConsoleLogger();
atSetExceptionHandler(AthenaExc);
}
static bool IsClientLoggingEnabled(int argc, const boo::SystemChar** argv) {
for (int i = 1; i < argc; ++i)
if (!hecl::StrNCmp(argv[i], _SYS_STR("-l"), 2))
return true;
return false;
}
#if !WINDOWS_STORE
#if _WIN32
int wmain(int argc, const boo::SystemChar** argv)
#else
int main(int argc, const boo::SystemChar** argv)
#endif
{
if (argc > 1 && !hecl::StrCmp(argv[1], _SYS_STR("--dlpackage"))) {
fmt::print(FMT_STRING("{}\n"), URDE_DLPACKAGE);
return 100;
}
SetupBasics(IsClientLoggingEnabled(argc, argv));
hecl::Runtime::FileStoreManager fileMgr{_SYS_STR("urde")};
hecl::CVarManager cvarMgr{fileMgr};
hecl::CVarCommons cvarCmns{cvarMgr};
hecl::SystemStringView logFile = hecl::SystemStringConv(cvarCmns.getLogFile()).sys_str();
hecl::SystemString logFilePath;
if (!logFile.empty()) {
std::time_t time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
char buf[100];
std::strftime(buf, 100, "%Y-%m-%d_%H-%M-%S", std::localtime(&time));
hecl::SystemString timeStr = hecl::SystemStringConv(buf).c_str();
logFilePath = fmt::format(FMT_STRING(_SYS_STR("{}/{}-{}")), fileMgr.getStoreRoot(), timeStr, logFile);
logvisor::RegisterFileLogger(logFilePath.c_str());
}
if (hecl::SystemChar* cwd = hecl::Getcwd(CwdBuf, 1024)) {
if (hecl::PathRelative(argv[0]))
ExeDir = hecl::SystemString(cwd) + _SYS_STR('/');
hecl::SystemString Argv0(argv[0]);
hecl::SystemString::size_type lastIdx = Argv0.find_last_of(_SYS_STR("/\\"));
if (lastIdx != hecl::SystemString::npos)
ExeDir.insert(ExeDir.end(), Argv0.begin(), Argv0.begin() + lastIdx);
}
/* Handle -j argument */
hecl::SetCpuCountOverride(argc, argv);
urde::Application appCb(fileMgr, cvarMgr, cvarCmns);
int ret = boo::ApplicationRun(boo::IApplication::EPlatformType::Auto, appCb, _SYS_STR("urde"), _SYS_STR("URDE"), argc,
argv, appCb.getGraphicsApi(), appCb.getSamples(), appCb.getAnisotropy(),
appCb.getDeepColor(), false);
// printf("IM DYING!!\n");
return ret;
}
#endif
#if WINDOWS_STORE
#include "boo/UWPViewProvider.hpp"
using namespace Windows::ApplicationModel::Core;
[Platform::MTAThread] int WINAPIV main(Platform::Array<Platform::String ^> ^ params) {
SetupBasics(false);
urde::Application appCb;
auto viewProvider =
ref new boo::ViewProvider(appCb, _SYS_STR("urde"), _SYS_STR("URDE"), _SYS_STR("urde"), params, false);
CoreApplication::Run(viewProvider);
return 0;
}
#elif _WIN32
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE, LPWSTR lpCmdLine, int) {
int argc = 0;
const boo::SystemChar** argv;
if (lpCmdLine[0])
argv = (const wchar_t**)(CommandLineToArgvW(lpCmdLine, &argc));
static boo::SystemChar selfPath[1024];
GetModuleFileNameW(nullptr, selfPath, 1024);
static const boo::SystemChar* booArgv[32] = {};
booArgv[0] = selfPath;
for (int i = 0; i < argc; ++i)
booArgv[i + 1] = argv[i];
const DWORD outType = GetFileType(GetStdHandle(STD_OUTPUT_HANDLE));
if (IsClientLoggingEnabled(argc + 1, booArgv) && outType == FILE_TYPE_UNKNOWN)
logvisor::CreateWin32Console();
return wmain(argc + 1, booArgv);
}
#endif
<|endoftext|>
|
<commit_before>#include <tuple>
#include "drake/util/drakeGeometryUtil.h"
#include "drake/util/drakeGradientUtil.h"
#include "mex.h"
using namespace Eigen;
using namespace std;
namespace drake {
namespace internal {
template <typename Head, typename ...Tail>
struct TotalSizeAtCompileTime {
static constexpr int eval() {
return Head::SizeAtCompileTime == Eigen::Dynamic || TotalSizeAtCompileTime<Tail...>::eval() == Eigen::Dynamic ?
Eigen::Dynamic :
Head::SizeAtCompileTime + TotalSizeAtCompileTime<Tail...>::eval();
}
};
template <typename Head>
struct TotalSizeAtCompileTime<Head> {
static constexpr int eval() {
return Head::SizeAtCompileTime;
}
};
}
template < typename... T>
std::tuple<const T &...> ctie(const T &... args) {
return std::tie(args...);
}
template <typename ...Args>
constexpr int totalSizeAtCompileTime() {
return internal::TotalSizeAtCompileTime<Args...>::eval();
}
DenseIndex totalSizeAtRunTime() {
return 0;
}
template <typename Head, typename ...Tail>
DenseIndex totalSizeAtRunTime(const Eigen::MatrixBase<Head>& head, const Tail&... tail) {
return head.size() + totalSizeAtRunTime(tail...);
}
template <typename Derived, int Nq>
using GradientType = Eigen::Matrix<Eigen::AutoDiffScalar<Eigen::Matrix<typename Derived::Scalar, Nq, 1> >, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime >;
template <int Nq, typename Derived>
DenseIndex initializeAutoDiff(GradientType<Derived, Nq>& ret, const Eigen::MatrixBase<Derived> &mat, DenseIndex num_derivatives, DenseIndex deriv_num_start) {
using ADScalar = typename GradientType<Derived, Nq>::Scalar;
ret.resize(mat.rows(), mat.cols());
DenseIndex deriv_num = deriv_num_start;
for (int i = 0; i < mat.size(); i++) {
ret(i) = ADScalar(mat(i), num_derivatives, deriv_num++);
}
deriv_num_start += mat.size();
return deriv_num_start;
}
namespace internal {
template <int Index>
struct InitializeAutoDiffTuples {
template <typename ...AutoDiffTypes, typename ...ValueTypes>
static DenseIndex eval(tuple<AutoDiffTypes...>& ret, const tuple<ValueTypes...>& mat, DenseIndex num_derivatives, DenseIndex deriv_num_start) {
deriv_num_start += initializeAutoDiff(std::get<Index>(ret), std::get<Index>(mat), num_derivatives, deriv_num_start);
return InitializeAutoDiffTuples<Index - 1>::eval(ret, mat, num_derivatives, deriv_num_start);
}
};
template <>
struct InitializeAutoDiffTuples<-1> {
template<typename ...AutoDiffTypes, typename ...ValueTypes>
static DenseIndex eval(const tuple<AutoDiffTypes...> &ret, const tuple<ValueTypes...> &mat, DenseIndex num_derivatives, DenseIndex deriv_num_start) {
return deriv_num_start;
}
};
}
template <typename ...Args>
using InitializeAutoDiffReturnType = std::tuple<GradientType<Args, totalSizeAtCompileTime<Args>()>...>;
template <typename Head, typename ...Tail>
InitializeAutoDiffReturnType<Head, Tail...> initializeAutoDiffArgs(const Head& arg0, const Tail&... args) {
DenseIndex dynamic_num_derivs = drake::totalSizeAtRunTime(args...);
InitializeAutoDiffReturnType<Head, Tail...> ret;
auto values = make_tuple(arg0, args...);
internal::InitializeAutoDiffTuples<sizeof...(args)>::eval(ret, values, dynamic_num_derivs, 0);
return ret;
}
// ideally: from tuple of rvalue references to arguments (constructed using forward_as_tuple) to tuple of autodiff matrices, properly initialized
}
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
if (nrhs != 5) {
mexErrMsgIdAndTxt("Drake:testQuatmex:BadInputs", "Usage [r,dr,e,ed,quat,dquat,q3,dq3,w,dw] = testQuatmex(q1,q2,axis,u,v)");
}
Vector4d q1;
Vector4d q2;
memcpy(q1.data(), mxGetPr(prhs[0]), sizeof(double) * 4);
memcpy(q2.data(), mxGetPr(prhs[1]), sizeof(double) * 4);
Vector3d axis;
memcpy(axis.data(), mxGetPr(prhs[2]), sizeof(double) * 3);
Vector3d u,v;
memcpy(u.data(),mxGetPr(prhs[3]),sizeof(double)*3);
memcpy(v.data(),mxGetPr(prhs[4]),sizeof(double)*3);
auto bla = drake::initializeAutoDiffArgs(q1, q2);
// {
// constexpr int static_num_derivs = drake::totalSizeAtCompileTime<decltype(q1), decltype(q2)>();
// DenseIndex dynamic_num_derivs = drake::totalSizeAtRunTime(q1, q2);
//
// DenseIndex deriv_num = 0;
// auto q1_autodiff = drake::initializeAutoDiff<static_num_derivs>(q1, dynamic_num_derivs, deriv_num);
// auto q2_autodiff = drake::initializeAutoDiff<static_num_derivs>(q2, dynamic_num_derivs, deriv_num);
//
// auto r_autodiff = quatDiff(q1_autodiff, q2_autodiff);
// auto r = autoDiffToValueMatrix(r_autodiff);
// auto dr = autoDiffToGradientMatrix(r_autodiff);
//
// plhs[0] = mxCreateDoubleMatrix(4, 1, mxREAL);
// plhs[1] = mxCreateDoubleMatrix(4, 8, mxREAL);
// memcpy(mxGetPr(plhs[0]), r.data(), sizeof(double) * 4);
// memcpy(mxGetPr(plhs[1]), dr.data(), sizeof(double) * 4 * 8);
// }
//
// {
// constexpr int static_num_derivs = drake::totalSizeAtCompileTime<decltype(q1), decltype(q2), decltype(axis)>();
// DenseIndex dynamic_num_derivs = drake::totalSizeAtRunTime(q1, q2, axis);
// DenseIndex deriv_num = 0;
// auto q1_autodiff = drake::initializeAutoDiff<static_num_derivs>(q1, dynamic_num_derivs, deriv_num);
// auto q2_autodiff = drake::initializeAutoDiff<static_num_derivs>(q2, dynamic_num_derivs, deriv_num);
// auto axis_autodiff = drake::initializeAutoDiff<static_num_derivs>(axis, dynamic_num_derivs, deriv_num);
// auto e_autodiff = quatDiffAxisInvar(q1_autodiff, q2_autodiff, axis_autodiff);
// auto e = e_autodiff.value();
// auto de = e_autodiff.derivatives().transpose().eval();
//
// plhs[2] = mxCreateDoubleScalar(e);
// plhs[3] = mxCreateDoubleMatrix(1, 11, mxREAL);
// memcpy(mxGetPr(plhs[3]), de.data(), sizeof(double) * 11);
// }
//
// {
// constexpr int static_num_derivs = drake::totalSizeAtCompileTime<decltype(q1), decltype(q2)>();
// DenseIndex dynamic_num_derivs = drake::totalSizeAtRunTime(q1, q2);
// DenseIndex deriv_num = 0;
// auto q1_autodiff = drake::initializeAutoDiff<static_num_derivs>(q1, dynamic_num_derivs, deriv_num);
// auto q2_autodiff = drake::initializeAutoDiff<static_num_derivs>(q2, dynamic_num_derivs, deriv_num);
//
// auto q3_autodiff = quatProduct(q1_autodiff, q2_autodiff);
// auto q3 = autoDiffToValueMatrix(q3_autodiff);
// auto dq3 = autoDiffToGradientMatrix(q3_autodiff);
//
// plhs[4] = mxCreateDoubleMatrix(4, 1, mxREAL);
// plhs[5] = mxCreateDoubleMatrix(4, 8, mxREAL);
// memcpy(mxGetPr(plhs[4]), q3.data(), sizeof(double) * 4);
// memcpy(mxGetPr(plhs[5]), dq3.data(), sizeof(double) * 4 * 8);
// }
//
// {
// constexpr int static_num_derivs = drake::totalSizeAtCompileTime<decltype(q1), decltype(u)>();
// DenseIndex dynamic_num_derivs = drake::totalSizeAtRunTime(q1, u);
// DenseIndex deriv_num = 0;
// auto q1_autodiff = drake::initializeAutoDiff<static_num_derivs>(q1, dynamic_num_derivs, deriv_num);
// auto u_autodiff = drake::initializeAutoDiff<static_num_derivs>(u, dynamic_num_derivs, deriv_num);
//
// auto w_autodiff = quatRotateVec(q1_autodiff, u_autodiff);
// auto w = autoDiffToValueMatrix(w_autodiff);
// auto dw = autoDiffToGradientMatrix(w_autodiff);
//
// plhs[6] = mxCreateDoubleMatrix(3, 1, mxREAL);
// plhs[7] = mxCreateDoubleMatrix(3, 7, mxREAL);
// memcpy(mxGetPr(plhs[6]), w.data(), sizeof(double) * 3);
// memcpy(mxGetPr(plhs[7]), dw.data(), sizeof(double) * 3 * 7);
// }
}
<commit_msg>Fix initializeAutoDiffArgs; works now!<commit_after>#include <tuple>
#include "drake/util/drakeGeometryUtil.h"
#include "drake/util/drakeGradientUtil.h"
#include "mex.h"
using namespace Eigen;
using namespace std;
namespace drake {
namespace internal {
template <typename Head, typename ...Tail>
struct TotalSizeAtCompileTime {
static constexpr int eval() {
return Head::SizeAtCompileTime == Eigen::Dynamic || TotalSizeAtCompileTime<Tail...>::eval() == Eigen::Dynamic ?
Eigen::Dynamic :
Head::SizeAtCompileTime + TotalSizeAtCompileTime<Tail...>::eval();
}
};
template <typename Head>
struct TotalSizeAtCompileTime<Head> {
static constexpr int eval() {
return Head::SizeAtCompileTime;
}
};
}
template <typename ...Args>
constexpr int totalSizeAtCompileTime() {
return internal::TotalSizeAtCompileTime<Args...>::eval();
}
DenseIndex totalSizeAtRunTime() {
return 0;
}
template <typename Head, typename ...Tail>
DenseIndex totalSizeAtRunTime(const Eigen::MatrixBase<Head>& head, const Tail&... tail) {
return head.size() + totalSizeAtRunTime(tail...);
}
template <typename Derived, int Nq>
using GradientType = Eigen::Matrix<Eigen::AutoDiffScalar<Eigen::Matrix<typename Derived::Scalar, Nq, 1> >, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime >;
template <int Nq, typename Derived>
DenseIndex initializeAutoDiff(GradientType<Derived, Nq>& ret, const Eigen::MatrixBase<Derived> &mat, DenseIndex num_derivatives, DenseIndex deriv_num_start) {
using ADScalar = typename GradientType<Derived, Nq>::Scalar;
ret.resize(mat.rows(), mat.cols());
DenseIndex deriv_num = deriv_num_start;
for (int i = 0; i < mat.size(); i++) {
ret(i) = ADScalar(mat(i), num_derivatives, deriv_num++);
}
deriv_num_start += mat.size();
return deriv_num_start;
}
namespace internal {
template <size_t Index>
struct InitializeAutoDiffTuples {
template <typename ...AutoDiffTypes, typename ...ValueTypes>
static DenseIndex eval(tuple<AutoDiffTypes...>& ret, const tuple<ValueTypes...>& mat, DenseIndex num_derivatives, DenseIndex deriv_num_start) {
constexpr size_t tuple_index = sizeof...(AutoDiffTypes) - Index;
deriv_num_start = initializeAutoDiff(std::get<tuple_index>(ret), std::get<tuple_index>(mat), num_derivatives, deriv_num_start);
return InitializeAutoDiffTuples<Index - 1>::eval(ret, mat, num_derivatives, deriv_num_start);
}
};
template <>
struct InitializeAutoDiffTuples<0> {
template<typename ...AutoDiffTypes, typename ...ValueTypes>
static DenseIndex eval(const tuple<AutoDiffTypes...> &ret, const tuple<ValueTypes...> &mat, DenseIndex num_derivatives, DenseIndex deriv_num_start) {
return deriv_num_start;
}
};
}
template <typename ...Args>
using InitializeAutoDiffArgsReturnType = std::tuple<GradientType<Args, totalSizeAtCompileTime<Args...>()>...>;
template <typename ...Args>
InitializeAutoDiffArgsReturnType<Args...> initializeAutoDiffArgs(const Args&... args) {
DenseIndex dynamic_num_derivs = drake::totalSizeAtRunTime(args...);
InitializeAutoDiffArgsReturnType<Args...> ret;
auto values = make_tuple(args...);
internal::InitializeAutoDiffTuples<sizeof...(args)>::eval(ret, values, dynamic_num_derivs, 0);
return ret;
}
// ideally: from tuple of rvalue references to arguments (constructed using forward_as_tuple) to tuple of autodiff matrices, properly initialized
}
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
if (nrhs != 5) {
mexErrMsgIdAndTxt("Drake:testQuatmex:BadInputs", "Usage [r,dr,e,ed,quat,dquat,q3,dq3,w,dw] = testQuatmex(q1,q2,axis,u,v)");
}
Vector4d q1;
Vector4d q2;
memcpy(q1.data(), mxGetPr(prhs[0]), sizeof(double) * 4);
memcpy(q2.data(), mxGetPr(prhs[1]), sizeof(double) * 4);
Vector3d axis;
memcpy(axis.data(), mxGetPr(prhs[2]), sizeof(double) * 3);
Vector3d u,v;
memcpy(u.data(),mxGetPr(prhs[3]),sizeof(double)*3);
memcpy(v.data(),mxGetPr(prhs[4]),sizeof(double)*3);
{
auto autodiff_args = drake::initializeAutoDiffArgs(q1, q2);
auto r_autodiff = quatDiff(get<0>(autodiff_args), get<1>(autodiff_args));
auto r = autoDiffToValueMatrix(r_autodiff);
auto dr = autoDiffToGradientMatrix(r_autodiff);
plhs[0] = mxCreateDoubleMatrix(4, 1, mxREAL);
plhs[1] = mxCreateDoubleMatrix(4, 8, mxREAL);
memcpy(mxGetPr(plhs[0]), r.data(), sizeof(double) * 4);
memcpy(mxGetPr(plhs[1]), dr.data(), sizeof(double) * 4 * 8);
}
{
auto autodiff_args = drake::initializeAutoDiffArgs(q1, q2, axis);
auto e_autodiff = quatDiffAxisInvar(get<0>(autodiff_args), get<1>(autodiff_args), get<2>(autodiff_args));
auto e = e_autodiff.value();
auto de = e_autodiff.derivatives().transpose().eval();
plhs[2] = mxCreateDoubleScalar(e);
plhs[3] = mxCreateDoubleMatrix(1, 11, mxREAL);
memcpy(mxGetPr(plhs[3]), de.data(), sizeof(double) * 11);
}
{
auto autodiff_args = drake::initializeAutoDiffArgs(q1, q2);
auto q3_autodiff = quatProduct(get<0>(autodiff_args), get<1>(autodiff_args));
auto q3 = autoDiffToValueMatrix(q3_autodiff);
auto dq3 = autoDiffToGradientMatrix(q3_autodiff);
plhs[4] = mxCreateDoubleMatrix(4, 1, mxREAL);
plhs[5] = mxCreateDoubleMatrix(4, 8, mxREAL);
memcpy(mxGetPr(plhs[4]), q3.data(), sizeof(double) * 4);
memcpy(mxGetPr(plhs[5]), dq3.data(), sizeof(double) * 4 * 8);
}
{
auto autodiff_args = drake::initializeAutoDiffArgs(q1, u);
auto w_autodiff = quatRotateVec(get<0>(autodiff_args), get<1>(autodiff_args));
auto w = autoDiffToValueMatrix(w_autodiff);
auto dw = autoDiffToGradientMatrix(w_autodiff);
plhs[6] = mxCreateDoubleMatrix(3, 1, mxREAL);
plhs[7] = mxCreateDoubleMatrix(3, 7, mxREAL);
memcpy(mxGetPr(plhs[6]), w.data(), sizeof(double) * 3);
memcpy(mxGetPr(plhs[7]), dw.data(), sizeof(double) * 3 * 7);
}
}
<|endoftext|>
|
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file state.cpp
* @author Christoph Jentzsch <cj@ethdev.com>
* @date 2014
* State test functions.
*/
#include <boost/filesystem/operations.hpp>
#include <boost/test/unit_test.hpp>
#include "JsonSpiritHeaders.h"
#include <libdevcore/CommonIO.h>
#include <libethereum/CanonBlockChain.h>
#include <libethereum/State.h>
#include <libethereum/ExtVM.h>
#include <libethereum/Defaults.h>
#include <libevm/VM.h>
#include "TestHelper.h"
using namespace std;
using namespace json_spirit;
using namespace dev;
using namespace dev::eth;
namespace dev { namespace test {
void doStateTests(json_spirit::mValue& v, bool _fillin)
{
processCommandLineOptions();
for (auto& i: v.get_obj())
{
cerr << i.first << endl;
mObject& o = i.second.get_obj();
BOOST_REQUIRE(o.count("env") > 0);
BOOST_REQUIRE(o.count("pre") > 0);
BOOST_REQUIRE(o.count("transaction") > 0);
ImportTest importer(o, _fillin);
State theState = importer.m_statePre;
bytes tx = importer.m_transaction.rlp();
bytes output;
try
{
theState.execute(lastHashes(importer.m_environment.currentBlock.number), tx, &output);
}
catch (Exception const& _e)
{
cnote << "state execution did throw an exception: " << diagnostic_information(_e);
}
catch (std::exception const& _e)
{
cnote << "state execution did throw an exception: " << _e.what();
}
if (_fillin)
importer.exportTest(output, theState);
else
{
BOOST_REQUIRE(o.count("post") > 0);
BOOST_REQUIRE(o.count("out") > 0);
// check output
checkOutput(output, o);
// check logs
checkLog(theState.pending().size() ? theState.log(0) : LogEntries(), importer.m_environment.sub.logs);
// check addresses
auto expectedAddrs = importer.m_statePost.addresses();
auto resultAddrs = theState.addresses();
for (auto& expectedPair : expectedAddrs)
{
auto& expectedAddr = expectedPair.first;
auto resultAddrIt = resultAddrs.find(expectedAddr);
if (resultAddrIt == resultAddrs.end())
BOOST_ERROR("Missing expected address " << expectedAddr);
else
{
BOOST_CHECK_MESSAGE(importer.m_statePost.balance(expectedAddr) == theState.balance(expectedAddr), expectedAddr << ": incorrect balance " << theState.balance(expectedAddr) << ", expected " << importer.m_statePost.balance(expectedAddr));
BOOST_CHECK_MESSAGE(importer.m_statePost.transactionsFrom(expectedAddr) == theState.transactionsFrom(expectedAddr), expectedAddr << ": incorrect txCount " << theState.transactionsFrom(expectedAddr) << ", expected " << importer.m_statePost.transactionsFrom(expectedAddr));
BOOST_CHECK_MESSAGE(importer.m_statePost.code(expectedAddr) == theState.code(expectedAddr), expectedAddr << ": incorrect code");
checkStorage(importer.m_statePost.storage(expectedAddr), theState.storage(expectedAddr), expectedAddr);
}
}
checkAddresses<map<Address, u256> >(expectedAddrs, resultAddrs);
}
}
}
} }// Namespace Close
BOOST_AUTO_TEST_SUITE(StateTests)
BOOST_AUTO_TEST_CASE(stExample)
{
dev::test::executeTests("stExample", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stSystemOperationsTest)
{
dev::test::executeTests("stSystemOperationsTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stPreCompiledContracts)
{
dev::test::executeTests("stPreCompiledContracts", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stLogTests)
{
dev::test::executeTests("stLogTests", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stRecursiveCreate)
{
dev::test::executeTests("stRecursiveCreate", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stInitCodeTest)
{
dev::test::executeTests("stInitCodeTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stTransactionTest)
{
dev::test::executeTests("stTransactionTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stSpecialTest)
{
dev::test::executeTests("stSpecialTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stRefundTest)
{
dev::test::executeTests("stRefundTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stBlockHashTest)
{
dev::test::executeTests("stBlockHashTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stQuadraticComplexityTest)
{
for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
{
string arg = boost::unit_test::framework::master_test_suite().argv[i];
if (arg == "--quadratic" || arg == "--all")
{
auto start = chrono::steady_clock::now();
dev::test::executeTests("stQuadraticComplexityTest", "/StateTests", dev::test::doStateTests);
auto end = chrono::steady_clock::now();
auto duration(chrono::duration_cast<chrono::milliseconds>(end - start));
cnote << "test duration: " << duration.count() << " milliseconds.\n";
}
}
}
BOOST_AUTO_TEST_CASE(stMemoryStressTest)
{
for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
{
string arg = boost::unit_test::framework::master_test_suite().argv[i];
if (arg == "--memory" || arg == "--all")
{
auto start = chrono::steady_clock::now();
dev::test::executeTests("stMemoryStressTest", "/StateTests", dev::test::doStateTests);
auto end = chrono::steady_clock::now();
auto duration(chrono::duration_cast<chrono::milliseconds>(end - start));
cnote << "test duration: " << duration.count() << " milliseconds.\n";
}
}
}
BOOST_AUTO_TEST_CASE(stSolidityTest)
{
dev::test::executeTests("stSolidityTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stMemoryTest)
{
dev::test::executeTests("stMemoryTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stCreateTest)
{
for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
{
string arg = boost::unit_test::framework::master_test_suite().argv[i];
if (arg == "--createtest")
{
if (boost::unit_test::framework::master_test_suite().argc <= i + 2)
{
cnote << "usage: ./testeth --createtest <PathToConstructor> <PathToDestiny>\n";
return;
}
try
{
cnote << "Populating tests...";
json_spirit::mValue v;
string s = asString(dev::contents(boost::unit_test::framework::master_test_suite().argv[i + 1]));
BOOST_REQUIRE_MESSAGE(s.length() > 0, "Content of " + (string)boost::unit_test::framework::master_test_suite().argv[i + 1] + " is empty.");
json_spirit::read_string(s, v);
dev::test::doStateTests(v, true);
writeFile(boost::unit_test::framework::master_test_suite().argv[i + 2], asBytes(json_spirit::write_string(v, true)));
}
catch (Exception const& _e)
{
BOOST_ERROR("Failed state test with Exception: " << diagnostic_information(_e));
}
catch (std::exception const& _e)
{
BOOST_ERROR("Failed state test with Exception: " << _e.what());
}
}
}
}
BOOST_AUTO_TEST_CASE(userDefinedFileState)
{
dev::test::userDefinedTest("--statetest", dev::test::doStateTests);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>only check rootHash of state if FATDB is off<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file state.cpp
* @author Christoph Jentzsch <cj@ethdev.com>
* @date 2014
* State test functions.
*/
#include <boost/filesystem/operations.hpp>
#include <boost/test/unit_test.hpp>
#include "JsonSpiritHeaders.h"
#include <libdevcore/CommonIO.h>
#include <libethereum/CanonBlockChain.h>
#include <libethereum/State.h>
#include <libethereum/ExtVM.h>
#include <libethereum/Defaults.h>
#include <libevm/VM.h>
#include "TestHelper.h"
using namespace std;
using namespace json_spirit;
using namespace dev;
using namespace dev::eth;
namespace dev { namespace test {
void doStateTests(json_spirit::mValue& v, bool _fillin)
{
processCommandLineOptions();
for (auto& i: v.get_obj())
{
cerr << i.first << endl;
mObject& o = i.second.get_obj();
BOOST_REQUIRE(o.count("env") > 0);
BOOST_REQUIRE(o.count("pre") > 0);
BOOST_REQUIRE(o.count("transaction") > 0);
ImportTest importer(o, _fillin);
State theState = importer.m_statePre;
bytes tx = importer.m_transaction.rlp();
bytes output;
try
{
theState.execute(lastHashes(importer.m_environment.currentBlock.number), tx, &output);
}
catch (Exception const& _e)
{
cnote << "state execution did throw an exception: " << diagnostic_information(_e);
}
catch (std::exception const& _e)
{
cnote << "state execution did throw an exception: " << _e.what();
}
if (_fillin)
{
#if ETH_FATDB
importer.exportTest(output, theState);
#else
BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("You can not fill tests when FATDB is switched off"));
#endif
}
else
{
BOOST_REQUIRE(o.count("post") > 0);
BOOST_REQUIRE(o.count("out") > 0);
// check output
checkOutput(output, o);
// check logs
checkLog(theState.pending().size() ? theState.log(0) : LogEntries(), importer.m_environment.sub.logs);
// check addresses
#if ETH_FATDB
cout << "fatDB is defined\n";
auto expectedAddrs = importer.m_statePost.addresses();
auto resultAddrs = theState.addresses();
for (auto& expectedPair : expectedAddrs)
{
auto& expectedAddr = expectedPair.first;
auto resultAddrIt = resultAddrs.find(expectedAddr);
if (resultAddrIt == resultAddrs.end())
BOOST_ERROR("Missing expected address " << expectedAddr);
else
{
BOOST_CHECK_MESSAGE(importer.m_statePost.balance(expectedAddr) == theState.balance(expectedAddr), expectedAddr << ": incorrect balance " << theState.balance(expectedAddr) << ", expected " << importer.m_statePost.balance(expectedAddr));
BOOST_CHECK_MESSAGE(importer.m_statePost.transactionsFrom(expectedAddr) == theState.transactionsFrom(expectedAddr), expectedAddr << ": incorrect txCount " << theState.transactionsFrom(expectedAddr) << ", expected " << importer.m_statePost.transactionsFrom(expectedAddr));
BOOST_CHECK_MESSAGE(importer.m_statePost.code(expectedAddr) == theState.code(expectedAddr), expectedAddr << ": incorrect code");
checkStorage(importer.m_statePost.storage(expectedAddr), theState.storage(expectedAddr), expectedAddr);
}
}
checkAddresses<map<Address, u256> >(expectedAddrs, resultAddrs);
#endif
BOOST_CHECK_MESSAGE(theState.rootHash() == h256(o["postStateRoot"].get_str()), "wrong post state root");
}
}
}
} }// Namespace Close
BOOST_AUTO_TEST_SUITE(StateTests)
BOOST_AUTO_TEST_CASE(stExample)
{
dev::test::executeTests("stExample", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stSystemOperationsTest)
{
dev::test::executeTests("stSystemOperationsTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stPreCompiledContracts)
{
dev::test::executeTests("stPreCompiledContracts", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stLogTests)
{
dev::test::executeTests("stLogTests", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stRecursiveCreate)
{
dev::test::executeTests("stRecursiveCreate", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stInitCodeTest)
{
dev::test::executeTests("stInitCodeTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stTransactionTest)
{
dev::test::executeTests("stTransactionTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stSpecialTest)
{
dev::test::executeTests("stSpecialTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stRefundTest)
{
dev::test::executeTests("stRefundTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stBlockHashTest)
{
dev::test::executeTests("stBlockHashTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stQuadraticComplexityTest)
{
for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
{
string arg = boost::unit_test::framework::master_test_suite().argv[i];
if (arg == "--quadratic" || arg == "--all")
{
auto start = chrono::steady_clock::now();
dev::test::executeTests("stQuadraticComplexityTest", "/StateTests", dev::test::doStateTests);
auto end = chrono::steady_clock::now();
auto duration(chrono::duration_cast<chrono::milliseconds>(end - start));
cnote << "test duration: " << duration.count() << " milliseconds.\n";
}
}
}
BOOST_AUTO_TEST_CASE(stMemoryStressTest)
{
for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
{
string arg = boost::unit_test::framework::master_test_suite().argv[i];
if (arg == "--memory" || arg == "--all")
{
auto start = chrono::steady_clock::now();
dev::test::executeTests("stMemoryStressTest", "/StateTests", dev::test::doStateTests);
auto end = chrono::steady_clock::now();
auto duration(chrono::duration_cast<chrono::milliseconds>(end - start));
cnote << "test duration: " << duration.count() << " milliseconds.\n";
}
}
}
BOOST_AUTO_TEST_CASE(stSolidityTest)
{
dev::test::executeTests("stSolidityTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stMemoryTest)
{
dev::test::executeTests("stMemoryTest", "/StateTests", dev::test::doStateTests);
}
BOOST_AUTO_TEST_CASE(stCreateTest)
{
for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
{
string arg = boost::unit_test::framework::master_test_suite().argv[i];
if (arg == "--createtest")
{
if (boost::unit_test::framework::master_test_suite().argc <= i + 2)
{
cnote << "usage: ./testeth --createtest <PathToConstructor> <PathToDestiny>\n";
return;
}
try
{
cnote << "Populating tests...";
json_spirit::mValue v;
string s = asString(dev::contents(boost::unit_test::framework::master_test_suite().argv[i + 1]));
BOOST_REQUIRE_MESSAGE(s.length() > 0, "Content of " + (string)boost::unit_test::framework::master_test_suite().argv[i + 1] + " is empty.");
json_spirit::read_string(s, v);
dev::test::doStateTests(v, true);
writeFile(boost::unit_test::framework::master_test_suite().argv[i + 2], asBytes(json_spirit::write_string(v, true)));
}
catch (Exception const& _e)
{
BOOST_ERROR("Failed state test with Exception: " << diagnostic_information(_e));
}
catch (std::exception const& _e)
{
BOOST_ERROR("Failed state test with Exception: " << _e.what());
}
}
}
}
BOOST_AUTO_TEST_CASE(userDefinedFileState)
{
dev::test::userDefinedTest("--statetest", dev::test::doStateTests);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>/* Copyright 2015 The TensorFlow 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 "tensorflow/core/framework/graph_def_util.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_def.pb.h"
#include "tensorflow/core/framework/op_def_builder.h"
#include "tensorflow/core/graph/equal_graph_def.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace {
Status FinalizeOpDef(OpDefBuilder b, OpDef* op_def) {
OpRegistrationData op_reg_data;
const Status s = b.Finalize(&op_reg_data);
*op_def = op_reg_data.op_def;
return s;
}
// Producer and consumer have default for an attr -> graph unchanged.
TEST(RemoveNewDefaultAttrsFromGraphDefTest, NoChangeWithDefault) {
OpList op_list;
TF_ASSERT_OK(
FinalizeOpDef(OpDefBuilder("NoChangeWithDefault").Attr("a: int = 12"),
op_list.add_op()));
OpListOpRegistry registry(&op_list);
GraphDef graph_def;
TF_ASSERT_OK(NodeDefBuilder("ncwd", "NoChangeWithDefault", ®istry)
.Finalize(graph_def.add_node()));
GraphDef expected_graph_def = graph_def;
std::set<std::pair<string, string>> op_attr_removed;
TF_ASSERT_OK(RemoveNewDefaultAttrsFromGraphDef(&graph_def, registry, registry,
&op_attr_removed));
TF_EXPECT_GRAPH_EQ(expected_graph_def, graph_def);
EXPECT_TRUE(op_attr_removed.empty());
}
// Producer and consumer both have an attr -> graph unchanged.
TEST(RemoveNewDefaultAttrsFromGraphDefTest, NoChangeNoDefault) {
OpList op_list;
TF_ASSERT_OK(FinalizeOpDef(OpDefBuilder("NoChangeNoDefault").Attr("a: int"),
op_list.add_op()));
OpListOpRegistry registry(&op_list);
GraphDef graph_def;
TF_ASSERT_OK(NodeDefBuilder("ncnd", "NoChangeNoDefault", ®istry)
.Attr("a", 42)
.Finalize(graph_def.add_node()));
GraphDef expected_graph_def = graph_def;
std::set<std::pair<string, string>> op_attr_removed;
TF_ASSERT_OK(RemoveNewDefaultAttrsFromGraphDef(&graph_def, registry, registry,
&op_attr_removed));
TF_EXPECT_GRAPH_EQ(expected_graph_def, graph_def);
EXPECT_TRUE(op_attr_removed.empty());
}
// Producer has default for an attr that the consumer does not know
// about, and the produced graph has the default value for the attr ->
// attr removed from graph (and so able to be consumed).
TEST(RemoveNewDefaultAttrsFromGraphDefTest, UsesDefault) {
OpList consumer_op_list;
TF_ASSERT_OK(
FinalizeOpDef(OpDefBuilder("UsesDefault"), consumer_op_list.add_op()));
OpListOpRegistry consumer_registry(&consumer_op_list);
OpList producer_op_list;
TF_ASSERT_OK(FinalizeOpDef(OpDefBuilder("UsesDefault").Attr("a: int = 17"),
producer_op_list.add_op()));
OpListOpRegistry producer_registry(&producer_op_list);
GraphDef produced_graph_def;
TF_ASSERT_OK(NodeDefBuilder("uses_default", "UsesDefault", &producer_registry)
.Finalize(produced_graph_def.add_node()));
std::set<std::pair<string, string>> op_attr_removed;
TF_ASSERT_OK(
RemoveNewDefaultAttrsFromGraphDef(&produced_graph_def, consumer_registry,
producer_registry, &op_attr_removed));
GraphDef expected_graph_def;
TF_ASSERT_OK(NodeDefBuilder("uses_default", "UsesDefault", &consumer_registry)
.Finalize(expected_graph_def.add_node()));
TF_EXPECT_GRAPH_EQ(expected_graph_def, produced_graph_def);
std::set<std::pair<string, string>> expected_removed({{"UsesDefault", "a"}});
EXPECT_EQ(expected_removed, op_attr_removed);
}
// Producer has default for an attr that the consumer does not know
// about, graph sets the attr to a value different from the default ->
// graph unchanged (but not able to be consumed by consumer).
TEST(RemoveNewDefaultAttrsFromGraphDefTest, ChangedFromDefault) {
OpList consumer_op_list;
TF_ASSERT_OK(FinalizeOpDef(OpDefBuilder("ChangedFromDefault"),
consumer_op_list.add_op()));
OpListOpRegistry consumer_registry(&consumer_op_list);
OpList producer_op_list;
TF_ASSERT_OK(
FinalizeOpDef(OpDefBuilder("ChangedFromDefault").Attr("a: int = 17"),
producer_op_list.add_op()));
OpListOpRegistry producer_registry(&producer_op_list);
GraphDef produced_graph_def;
TF_ASSERT_OK(NodeDefBuilder("changed_from_default", "ChangedFromDefault",
&producer_registry)
.Attr("a", 9)
.Finalize(produced_graph_def.add_node()));
GraphDef expected_graph_def = produced_graph_def;
std::set<std::pair<string, string>> op_attr_removed;
TF_ASSERT_OK(
RemoveNewDefaultAttrsFromGraphDef(&produced_graph_def, consumer_registry,
producer_registry, &op_attr_removed));
TF_EXPECT_GRAPH_EQ(expected_graph_def, produced_graph_def);
EXPECT_TRUE(op_attr_removed.empty());
}
// Attrs starting with underscores should not be removed.
TEST(RemoveNewDefaultAttrsFromGraphDefTest, UnderscoreAttrs) {
OpList consumer_op_list;
TF_ASSERT_OK(
FinalizeOpDef(OpDefBuilder("Underscore"), consumer_op_list.add_op()));
OpListOpRegistry consumer_registry(&consumer_op_list);
OpList producer_op_list;
TF_ASSERT_OK(
FinalizeOpDef(OpDefBuilder("Underscore"), producer_op_list.add_op()));
// Add the _underscore attr manually since OpDefBuilder would complain
OpDef::AttrDef* attr = producer_op_list.mutable_op(0)->add_attr();
attr->set_name("_underscore");
attr->set_type("int");
attr->mutable_default_value()->set_i(17);
OpListOpRegistry producer_registry(&producer_op_list);
GraphDef produced_graph_def;
TF_ASSERT_OK(NodeDefBuilder("node", "Underscore", &producer_registry)
.Attr("_underscore", 17)
.Finalize(produced_graph_def.add_node()));
GraphDef expected_graph_def = produced_graph_def;
std::set<std::pair<string, string>> op_attr_removed;
TF_ASSERT_OK(
RemoveNewDefaultAttrsFromGraphDef(&produced_graph_def, consumer_registry,
producer_registry, &op_attr_removed));
TF_EXPECT_GRAPH_EQ(expected_graph_def, produced_graph_def);
EXPECT_EQ(op_attr_removed.size(), 0);
}
TEST(RemoveNewDefaultAttrsFromGraphDefTest, HasFunction) {
OpList consumer_op_list;
TF_ASSERT_OK(
FinalizeOpDef(OpDefBuilder("UsesDefault"), consumer_op_list.add_op()));
TF_ASSERT_OK(FinalizeOpDef(OpDefBuilder("ChangedFromDefault"),
consumer_op_list.add_op()));
OpListOpRegistry consumer_registry(&consumer_op_list);
OpList producer_op_list;
TF_ASSERT_OK(FinalizeOpDef(OpDefBuilder("UsesDefault").Attr("a: int = 17"),
producer_op_list.add_op()));
TF_ASSERT_OK(
FinalizeOpDef(OpDefBuilder("ChangedFromDefault").Attr("a: int = 17"),
producer_op_list.add_op()));
OpListOpRegistry producer_registry(&producer_op_list);
GraphDef produced_graph_def;
*produced_graph_def.mutable_library()->add_function() =
FunctionDefHelper::Create(
"my_func", {}, {}, {},
{{{"x"}, "UsesDefault", {}, {{"a", 17}}},
{{"y"}, "ChangedFromDefault", {}, {{"a", 99}}}},
{});
OpList function_op_list;
*function_op_list.add_op() =
produced_graph_def.library().function(0).signature();
OpListOpRegistry function_registry(&function_op_list);
TF_ASSERT_OK(NodeDefBuilder("call_func", "my_func", &function_registry)
.Finalize(produced_graph_def.add_node()));
std::set<std::pair<string, string>> op_attr_removed;
TF_ASSERT_OK(
RemoveNewDefaultAttrsFromGraphDef(&produced_graph_def, consumer_registry,
producer_registry, &op_attr_removed));
GraphDef expected_graph_def;
*expected_graph_def.mutable_library()->add_function() =
FunctionDefHelper::Create(
"my_func", {}, {}, {},
{{{"x"}, "UsesDefault", {}, {}},
{{"y"}, "ChangedFromDefault", {}, {{"a", 99}}}},
{});
TF_ASSERT_OK(NodeDefBuilder("call_func", "my_func", &function_registry)
.Finalize(expected_graph_def.add_node()));
TF_EXPECT_GRAPH_EQ(expected_graph_def, produced_graph_def);
EXPECT_EQ(expected_graph_def.library().DebugString(),
produced_graph_def.library().DebugString());
std::set<std::pair<string, string>> expected_removed({{"UsesDefault", "a"}});
EXPECT_EQ(expected_removed, op_attr_removed);
}
TEST(StrippedOpListForGraphTest, FlatTest) {
// Make four ops
OpList op_list;
for (const string& op : {"A", "B", "C", "D"}) {
OpDef* op_def = op_list.add_op();
op_def->set_name(op);
op_def->set_summary("summary");
op_def->set_description("description");
op_def->set_is_commutative(op == "B");
}
// Make a graph which uses two ops once and twice, respectively.
// The result should be independent of the ordering.
const string graph_ops[4][3] = {
{"C", "B", "B"}, {"B", "C", "B"}, {"B", "B", "C"}, {"C", "C", "B"}};
for (const bool use_function : {false, true}) {
for (int order = 0; order < 4; order++) {
GraphDef graph_def;
if (use_function) {
FunctionDef* function_def = graph_def.mutable_library()->add_function();
function_def->mutable_signature()->set_name("F");
for (const string& op : graph_ops[order]) {
function_def->add_node()->set_op(op);
}
graph_def.add_node()->set_op("F");
} else {
for (const string& op : graph_ops[order]) {
string name = strings::StrCat("name", graph_def.node_size());
NodeDef* node = graph_def.add_node();
node->set_name(name);
node->set_op(op);
}
}
// Strip the op list
OpList stripped_op_list;
TF_ASSERT_OK(StrippedOpListForGraph(graph_def, OpListOpRegistry(&op_list),
&stripped_op_list));
// We should have exactly two ops: B and C.
ASSERT_EQ(stripped_op_list.op_size(), 2);
for (int i = 0; i < 2; i++) {
const OpDef& op = stripped_op_list.op(i);
EXPECT_EQ(op.name(), i ? "C" : "B");
EXPECT_EQ(op.summary(), "");
EXPECT_EQ(op.description(), "");
EXPECT_EQ(op.is_commutative(), !i);
}
// Should get the same result using OpsUsedByGraph().
std::set<string> used_ops;
OpsUsedByGraph(graph_def, &used_ops);
ASSERT_EQ(std::set<string>({"B", "C"}), used_ops);
}
}
}
TEST(StrippedOpListForGraphTest, NestedFunctionTest) {
// Make a primitive op A.
OpList op_list;
op_list.add_op()->set_name("A");
for (const bool recursive : {false, true}) {
// Call A from function B, and B from function C.
GraphDef graph_def;
FunctionDef* b = graph_def.mutable_library()->add_function();
FunctionDef* c = graph_def.mutable_library()->add_function();
b->mutable_signature()->set_name("B");
c->mutable_signature()->set_name("C");
b->add_node()->set_op("A");
c->add_node()->set_op("B");
if (recursive) {
b->add_node()->set_op("B");
c->add_node()->set_op("C");
}
// Use C in the graph.
graph_def.add_node()->set_op("C");
// The stripped op list should contain just A.
OpList stripped_op_list;
TF_ASSERT_OK(StrippedOpListForGraph(graph_def, OpListOpRegistry(&op_list),
&stripped_op_list));
ASSERT_EQ(stripped_op_list.op_size(), 1);
ASSERT_EQ(stripped_op_list.op(0).name(), "A");
// Should get the same result using OpsUsedByGraph().
std::set<string> used_ops;
OpsUsedByGraph(graph_def, &used_ops);
ASSERT_EQ(std::set<string>({"A"}), used_ops);
}
}
} // namespace
} // namespace tensorflow
<commit_msg>Get rid of the last references to FunctionDef.node before we delete it entirely. Change: 143298461<commit_after>/* Copyright 2015 The TensorFlow 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 "tensorflow/core/framework/graph_def_util.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_def.pb.h"
#include "tensorflow/core/framework/op_def_builder.h"
#include "tensorflow/core/graph/equal_graph_def.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace {
Status FinalizeOpDef(OpDefBuilder b, OpDef* op_def) {
OpRegistrationData op_reg_data;
const Status s = b.Finalize(&op_reg_data);
*op_def = op_reg_data.op_def;
return s;
}
// Producer and consumer have default for an attr -> graph unchanged.
TEST(RemoveNewDefaultAttrsFromGraphDefTest, NoChangeWithDefault) {
OpList op_list;
TF_ASSERT_OK(
FinalizeOpDef(OpDefBuilder("NoChangeWithDefault").Attr("a: int = 12"),
op_list.add_op()));
OpListOpRegistry registry(&op_list);
GraphDef graph_def;
TF_ASSERT_OK(NodeDefBuilder("ncwd", "NoChangeWithDefault", ®istry)
.Finalize(graph_def.add_node()));
GraphDef expected_graph_def = graph_def;
std::set<std::pair<string, string>> op_attr_removed;
TF_ASSERT_OK(RemoveNewDefaultAttrsFromGraphDef(&graph_def, registry, registry,
&op_attr_removed));
TF_EXPECT_GRAPH_EQ(expected_graph_def, graph_def);
EXPECT_TRUE(op_attr_removed.empty());
}
// Producer and consumer both have an attr -> graph unchanged.
TEST(RemoveNewDefaultAttrsFromGraphDefTest, NoChangeNoDefault) {
OpList op_list;
TF_ASSERT_OK(FinalizeOpDef(OpDefBuilder("NoChangeNoDefault").Attr("a: int"),
op_list.add_op()));
OpListOpRegistry registry(&op_list);
GraphDef graph_def;
TF_ASSERT_OK(NodeDefBuilder("ncnd", "NoChangeNoDefault", ®istry)
.Attr("a", 42)
.Finalize(graph_def.add_node()));
GraphDef expected_graph_def = graph_def;
std::set<std::pair<string, string>> op_attr_removed;
TF_ASSERT_OK(RemoveNewDefaultAttrsFromGraphDef(&graph_def, registry, registry,
&op_attr_removed));
TF_EXPECT_GRAPH_EQ(expected_graph_def, graph_def);
EXPECT_TRUE(op_attr_removed.empty());
}
// Producer has default for an attr that the consumer does not know
// about, and the produced graph has the default value for the attr ->
// attr removed from graph (and so able to be consumed).
TEST(RemoveNewDefaultAttrsFromGraphDefTest, UsesDefault) {
OpList consumer_op_list;
TF_ASSERT_OK(
FinalizeOpDef(OpDefBuilder("UsesDefault"), consumer_op_list.add_op()));
OpListOpRegistry consumer_registry(&consumer_op_list);
OpList producer_op_list;
TF_ASSERT_OK(FinalizeOpDef(OpDefBuilder("UsesDefault").Attr("a: int = 17"),
producer_op_list.add_op()));
OpListOpRegistry producer_registry(&producer_op_list);
GraphDef produced_graph_def;
TF_ASSERT_OK(NodeDefBuilder("uses_default", "UsesDefault", &producer_registry)
.Finalize(produced_graph_def.add_node()));
std::set<std::pair<string, string>> op_attr_removed;
TF_ASSERT_OK(
RemoveNewDefaultAttrsFromGraphDef(&produced_graph_def, consumer_registry,
producer_registry, &op_attr_removed));
GraphDef expected_graph_def;
TF_ASSERT_OK(NodeDefBuilder("uses_default", "UsesDefault", &consumer_registry)
.Finalize(expected_graph_def.add_node()));
TF_EXPECT_GRAPH_EQ(expected_graph_def, produced_graph_def);
std::set<std::pair<string, string>> expected_removed({{"UsesDefault", "a"}});
EXPECT_EQ(expected_removed, op_attr_removed);
}
// Producer has default for an attr that the consumer does not know
// about, graph sets the attr to a value different from the default ->
// graph unchanged (but not able to be consumed by consumer).
TEST(RemoveNewDefaultAttrsFromGraphDefTest, ChangedFromDefault) {
OpList consumer_op_list;
TF_ASSERT_OK(FinalizeOpDef(OpDefBuilder("ChangedFromDefault"),
consumer_op_list.add_op()));
OpListOpRegistry consumer_registry(&consumer_op_list);
OpList producer_op_list;
TF_ASSERT_OK(
FinalizeOpDef(OpDefBuilder("ChangedFromDefault").Attr("a: int = 17"),
producer_op_list.add_op()));
OpListOpRegistry producer_registry(&producer_op_list);
GraphDef produced_graph_def;
TF_ASSERT_OK(NodeDefBuilder("changed_from_default", "ChangedFromDefault",
&producer_registry)
.Attr("a", 9)
.Finalize(produced_graph_def.add_node()));
GraphDef expected_graph_def = produced_graph_def;
std::set<std::pair<string, string>> op_attr_removed;
TF_ASSERT_OK(
RemoveNewDefaultAttrsFromGraphDef(&produced_graph_def, consumer_registry,
producer_registry, &op_attr_removed));
TF_EXPECT_GRAPH_EQ(expected_graph_def, produced_graph_def);
EXPECT_TRUE(op_attr_removed.empty());
}
// Attrs starting with underscores should not be removed.
TEST(RemoveNewDefaultAttrsFromGraphDefTest, UnderscoreAttrs) {
OpList consumer_op_list;
TF_ASSERT_OK(
FinalizeOpDef(OpDefBuilder("Underscore"), consumer_op_list.add_op()));
OpListOpRegistry consumer_registry(&consumer_op_list);
OpList producer_op_list;
TF_ASSERT_OK(
FinalizeOpDef(OpDefBuilder("Underscore"), producer_op_list.add_op()));
// Add the _underscore attr manually since OpDefBuilder would complain
OpDef::AttrDef* attr = producer_op_list.mutable_op(0)->add_attr();
attr->set_name("_underscore");
attr->set_type("int");
attr->mutable_default_value()->set_i(17);
OpListOpRegistry producer_registry(&producer_op_list);
GraphDef produced_graph_def;
TF_ASSERT_OK(NodeDefBuilder("node", "Underscore", &producer_registry)
.Attr("_underscore", 17)
.Finalize(produced_graph_def.add_node()));
GraphDef expected_graph_def = produced_graph_def;
std::set<std::pair<string, string>> op_attr_removed;
TF_ASSERT_OK(
RemoveNewDefaultAttrsFromGraphDef(&produced_graph_def, consumer_registry,
producer_registry, &op_attr_removed));
TF_EXPECT_GRAPH_EQ(expected_graph_def, produced_graph_def);
EXPECT_EQ(op_attr_removed.size(), 0);
}
TEST(RemoveNewDefaultAttrsFromGraphDefTest, HasFunction) {
OpList consumer_op_list;
TF_ASSERT_OK(
FinalizeOpDef(OpDefBuilder("UsesDefault"), consumer_op_list.add_op()));
TF_ASSERT_OK(FinalizeOpDef(OpDefBuilder("ChangedFromDefault"),
consumer_op_list.add_op()));
OpListOpRegistry consumer_registry(&consumer_op_list);
OpList producer_op_list;
TF_ASSERT_OK(FinalizeOpDef(OpDefBuilder("UsesDefault").Attr("a: int = 17"),
producer_op_list.add_op()));
TF_ASSERT_OK(
FinalizeOpDef(OpDefBuilder("ChangedFromDefault").Attr("a: int = 17"),
producer_op_list.add_op()));
OpListOpRegistry producer_registry(&producer_op_list);
GraphDef produced_graph_def;
*produced_graph_def.mutable_library()->add_function() =
FunctionDefHelper::Create(
"my_func", {}, {}, {},
{{{"x"}, "UsesDefault", {}, {{"a", 17}}},
{{"y"}, "ChangedFromDefault", {}, {{"a", 99}}}},
{});
OpList function_op_list;
*function_op_list.add_op() =
produced_graph_def.library().function(0).signature();
OpListOpRegistry function_registry(&function_op_list);
TF_ASSERT_OK(NodeDefBuilder("call_func", "my_func", &function_registry)
.Finalize(produced_graph_def.add_node()));
std::set<std::pair<string, string>> op_attr_removed;
TF_ASSERT_OK(
RemoveNewDefaultAttrsFromGraphDef(&produced_graph_def, consumer_registry,
producer_registry, &op_attr_removed));
GraphDef expected_graph_def;
*expected_graph_def.mutable_library()->add_function() =
FunctionDefHelper::Create(
"my_func", {}, {}, {},
{{{"x"}, "UsesDefault", {}, {}},
{{"y"}, "ChangedFromDefault", {}, {{"a", 99}}}},
{});
TF_ASSERT_OK(NodeDefBuilder("call_func", "my_func", &function_registry)
.Finalize(expected_graph_def.add_node()));
TF_EXPECT_GRAPH_EQ(expected_graph_def, produced_graph_def);
EXPECT_EQ(expected_graph_def.library().DebugString(),
produced_graph_def.library().DebugString());
std::set<std::pair<string, string>> expected_removed({{"UsesDefault", "a"}});
EXPECT_EQ(expected_removed, op_attr_removed);
}
TEST(StrippedOpListForGraphTest, FlatTest) {
// Make four ops
OpList op_list;
for (const string& op : {"A", "B", "C", "D"}) {
OpDef* op_def = op_list.add_op();
op_def->set_name(op);
op_def->set_summary("summary");
op_def->set_description("description");
op_def->set_is_commutative(op == "B");
}
// Make a graph which uses two ops once and twice, respectively.
// The result should be independent of the ordering.
const string graph_ops[4][3] = {
{"C", "B", "B"}, {"B", "C", "B"}, {"B", "B", "C"}, {"C", "C", "B"}};
for (const bool use_function : {false, true}) {
for (int order = 0; order < 4; order++) {
GraphDef graph_def;
if (use_function) {
FunctionDef* function_def = graph_def.mutable_library()->add_function();
function_def->mutable_signature()->set_name("F");
for (const string& op : graph_ops[order]) {
function_def->add_node_def()->set_op(op);
}
graph_def.add_node()->set_op("F");
} else {
for (const string& op : graph_ops[order]) {
string name = strings::StrCat("name", graph_def.node_size());
NodeDef* node = graph_def.add_node();
node->set_name(name);
node->set_op(op);
}
}
// Strip the op list
OpList stripped_op_list;
TF_ASSERT_OK(StrippedOpListForGraph(graph_def, OpListOpRegistry(&op_list),
&stripped_op_list));
// We should have exactly two ops: B and C.
ASSERT_EQ(stripped_op_list.op_size(), 2);
for (int i = 0; i < 2; i++) {
const OpDef& op = stripped_op_list.op(i);
EXPECT_EQ(op.name(), i ? "C" : "B");
EXPECT_EQ(op.summary(), "");
EXPECT_EQ(op.description(), "");
EXPECT_EQ(op.is_commutative(), !i);
}
// Should get the same result using OpsUsedByGraph().
std::set<string> used_ops;
OpsUsedByGraph(graph_def, &used_ops);
ASSERT_EQ(std::set<string>({"B", "C"}), used_ops);
}
}
}
TEST(StrippedOpListForGraphTest, NestedFunctionTest) {
// Make a primitive op A.
OpList op_list;
op_list.add_op()->set_name("A");
for (const bool recursive : {false, true}) {
// Call A from function B, and B from function C.
GraphDef graph_def;
FunctionDef* b = graph_def.mutable_library()->add_function();
FunctionDef* c = graph_def.mutable_library()->add_function();
b->mutable_signature()->set_name("B");
c->mutable_signature()->set_name("C");
b->add_node_def()->set_op("A");
c->add_node_def()->set_op("B");
if (recursive) {
b->add_node_def()->set_op("B");
c->add_node_def()->set_op("C");
}
// Use C in the graph.
graph_def.add_node()->set_op("C");
// The stripped op list should contain just A.
OpList stripped_op_list;
TF_ASSERT_OK(StrippedOpListForGraph(graph_def, OpListOpRegistry(&op_list),
&stripped_op_list));
ASSERT_EQ(stripped_op_list.op_size(), 1);
ASSERT_EQ(stripped_op_list.op(0).name(), "A");
// Should get the same result using OpsUsedByGraph().
std::set<string> used_ops;
OpsUsedByGraph(graph_def, &used_ops);
ASSERT_EQ(std::set<string>({"A"}), used_ops);
}
}
} // namespace
} // namespace tensorflow
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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 _RESOURCEPROVIDER_HXX_
#define _RESOURCEPROVIDER_HXX_
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#include <sal/types.h>
#include <rtl/ustring>
#define FOLDERPICKER_TITLE 500
#define FOLDER_PICKER_DEF_DESCRIPTION 501
#define FILE_PICKER_TITLE_OPEN 502
#define FILE_PICKER_TITLE_SAVE 503
#define FILE_PICKER_FILE_TYPE 504
#define FILE_PICKER_OVERWRITE 505
//------------------------------------------------------------------------
// deklarations
//------------------------------------------------------------------------
class CResourceProvider_Impl;
class CResourceProvider
{
public:
CResourceProvider( );
~CResourceProvider( );
rtl::OUString getResString( sal_Int32 aId );
private:
CResourceProvider_Impl* m_pImpl;
};
#endif
<commit_msg>fixed fpicker includes after removing the guards<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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 _RESOURCEPROVIDER_HXX_
#define _RESOURCEPROVIDER_HXX_
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#include <sal/types.h>
#include <rtl/ustring.hxx>
#define FOLDERPICKER_TITLE 500
#define FOLDER_PICKER_DEF_DESCRIPTION 501
#define FILE_PICKER_TITLE_OPEN 502
#define FILE_PICKER_TITLE_SAVE 503
#define FILE_PICKER_FILE_TYPE 504
#define FILE_PICKER_OVERWRITE 505
//------------------------------------------------------------------------
// deklarations
//------------------------------------------------------------------------
class CResourceProvider_Impl;
class CResourceProvider
{
public:
CResourceProvider( );
~CResourceProvider( );
rtl::OUString getResString( sal_Int32 aId );
private:
CResourceProvider_Impl* m_pImpl;
};
#endif
<|endoftext|>
|
<commit_before>// $Id$
// Category: physics
//
// See the class description in the header file.
#include "TG4G3Defaults.h"
#include "TG4Globals.h"
#include <math.h>
// static const data members
// precision tolerance
const G4double TG4G3Defaults::fgkCutTolerance = 1. * keV;
// kinetic energy cuts
const G4double TG4G3Defaults::fgkCUTGAM = 0.001 * GeV;
const G4double TG4G3Defaults::fgkCUTELE = 0.001 * GeV;
const G4double TG4G3Defaults::fgkCUTNEU = 0.01 * GeV;
const G4double TG4G3Defaults::fgkCUTHAD = 0.01 * GeV;
const G4double TG4G3Defaults::fgkCUTMUO = 0.01 * GeV;
const G4double TG4G3Defaults::fgkBCUTE = fgkCUTGAM;
const G4double TG4G3Defaults::fgkBCUTM = fgkCUTGAM;
const G4double TG4G3Defaults::fgkDCUTE = 10. * TeV;
const G4double TG4G3Defaults::fgkDCUTM = 10. * TeV;
const G4double TG4G3Defaults::fgkPPCUTM = 0.01 * GeV;
// physics processes
const TG4G3ControlValue TG4G3Defaults::fgkPAIR = kActivate; // 1
const TG4G3ControlValue TG4G3Defaults::fgkCOMP = kActivate; // 1
const TG4G3ControlValue TG4G3Defaults::fgkPHOT = kActivate; // 1
const TG4G3ControlValue TG4G3Defaults::fgkPFIS = kInActivate; // 0
const TG4G3ControlValue TG4G3Defaults::fgkDRAY = kActivate2; // 2
const TG4G3ControlValue TG4G3Defaults::fgkANNI = kActivate; // 1
const TG4G3ControlValue TG4G3Defaults::fgkBREM = kActivate; // 1
const TG4G3ControlValue TG4G3Defaults::fgkHADR = kActivate; // 1
const TG4G3ControlValue TG4G3Defaults::fgkMUNU = kInActivate; // 0
const TG4G3ControlValue TG4G3Defaults::fgkDCAY = kActivate; // 1
const TG4G3ControlValue TG4G3Defaults::fgkLOSS = kActivate2; // 2
const TG4G3ControlValue TG4G3Defaults::fgkMULS = kActivate; // 1
TG4G3Defaults::TG4G3Defaults() {
//
}
TG4G3Defaults::~TG4G3Defaults() {
//
}
G4double TG4G3Defaults::CutValue(G4int g3Cut)
{
// Returns the G3 default value for the specified cut.
// ---
switch (g3Cut) {
case kCUTGAM:
return fgkCUTGAM;
case kCUTELE:
return fgkCUTELE;
case kCUTNEU:
return fgkCUTNEU;
case kCUTHAD:
return fgkCUTHAD;
case kCUTMUO:
return fgkCUTMUO;
case kBCUTE:
return fgkBCUTE;
case kBCUTM:
return fgkBCUTM;
case kDCUTE:
return fgkDCUTE;
case kDCUTM:
return fgkDCUTM;
case kPPCUTM:
return fgkPPCUTM;
default:
TG4Globals::Warning("TG4G3Defaults::CutValue: Inconsistent cut.");
return 0.;
}
}
TG4G3ControlValue TG4G3Defaults::ControlValue(G4int control)
{
// Returns the G3 default value for the specified control.
// ---
switch (control) {
case kPAIR:
return fgkPAIR;
case kCOMP:
return fgkCOMP;
case kPHOT:
return fgkPHOT;
case kPFIS:
return fgkPFIS;
case kDRAY:
return fgkDRAY;
case kANNI:
return fgkANNI;
case kBREM:
return fgkBREM;
case kHADR:
return fgkHADR;
case kMUNU:
return fgkMUNU;
case kDCAY:
return fgkDCAY;
case kLOSS:
return fgkLOSS;
case kMULS:
return fgkMULS;
default:
TG4Globals::Warning(
"TG4G3Defaults::ControlValue: Inconsistent control.");
return kUnset;
}
}
G4bool TG4G3Defaults::IsDefaultCut(TG4G3Cut cut, G4double value)
{
// Tests if the parameter value is equal to the G3 default value.
// ---
if (abs(value*GeV - CutValue(cut)) > fgkCutTolerance)
return false;
else
return true;
}
G4bool TG4G3Defaults::IsDefaultControl(TG4G3Control control,
G4double value)
{
// Tests if the parameter value is equal to the G3 default value.
// ---
if (value == ControlValue(control))
return true;
else
return false;
}
<commit_msg>moved from physics to global; added comment lines separating methods<commit_after>// $Id$
// Category: global
//
// See the class description in the header file.
#include "TG4G3Defaults.h"
#include "TG4Globals.h"
#include <math.h>
// static const data members
// precision tolerance
const G4double TG4G3Defaults::fgkCutTolerance = 1. * keV;
// kinetic energy cuts
const G4double TG4G3Defaults::fgkCUTGAM = 0.001 * GeV;
const G4double TG4G3Defaults::fgkCUTELE = 0.001 * GeV;
const G4double TG4G3Defaults::fgkCUTNEU = 0.01 * GeV;
const G4double TG4G3Defaults::fgkCUTHAD = 0.01 * GeV;
const G4double TG4G3Defaults::fgkCUTMUO = 0.01 * GeV;
const G4double TG4G3Defaults::fgkBCUTE = fgkCUTGAM;
const G4double TG4G3Defaults::fgkBCUTM = fgkCUTGAM;
const G4double TG4G3Defaults::fgkDCUTE = 10. * TeV;
const G4double TG4G3Defaults::fgkDCUTM = 10. * TeV;
const G4double TG4G3Defaults::fgkPPCUTM = 0.01 * GeV;
// physics processes
const TG4G3ControlValue TG4G3Defaults::fgkPAIR = kActivate; // 1
const TG4G3ControlValue TG4G3Defaults::fgkCOMP = kActivate; // 1
const TG4G3ControlValue TG4G3Defaults::fgkPHOT = kActivate; // 1
const TG4G3ControlValue TG4G3Defaults::fgkPFIS = kInActivate; // 0
const TG4G3ControlValue TG4G3Defaults::fgkDRAY = kActivate2; // 2
const TG4G3ControlValue TG4G3Defaults::fgkANNI = kActivate; // 1
const TG4G3ControlValue TG4G3Defaults::fgkBREM = kActivate; // 1
const TG4G3ControlValue TG4G3Defaults::fgkHADR = kActivate; // 1
const TG4G3ControlValue TG4G3Defaults::fgkMUNU = kInActivate; // 0
const TG4G3ControlValue TG4G3Defaults::fgkDCAY = kActivate; // 1
const TG4G3ControlValue TG4G3Defaults::fgkLOSS = kActivate2; // 2
const TG4G3ControlValue TG4G3Defaults::fgkMULS = kActivate; // 1
//_____________________________________________________________________________
TG4G3Defaults::TG4G3Defaults() {
//
}
//_____________________________________________________________________________
TG4G3Defaults::~TG4G3Defaults() {
//
}
//_____________________________________________________________________________
G4double TG4G3Defaults::CutValue(G4int g3Cut)
{
// Returns the G3 default value for the specified cut.
// ---
switch (g3Cut) {
case kCUTGAM:
return fgkCUTGAM;
case kCUTELE:
return fgkCUTELE;
case kCUTNEU:
return fgkCUTNEU;
case kCUTHAD:
return fgkCUTHAD;
case kCUTMUO:
return fgkCUTMUO;
case kBCUTE:
return fgkBCUTE;
case kBCUTM:
return fgkBCUTM;
case kDCUTE:
return fgkDCUTE;
case kDCUTM:
return fgkDCUTM;
case kPPCUTM:
return fgkPPCUTM;
default:
TG4Globals::Warning("TG4G3Defaults::CutValue: Inconsistent cut.");
return 0.;
}
}
//_____________________________________________________________________________
TG4G3ControlValue TG4G3Defaults::ControlValue(G4int control)
{
// Returns the G3 default value for the specified control.
// ---
switch (control) {
case kPAIR:
return fgkPAIR;
case kCOMP:
return fgkCOMP;
case kPHOT:
return fgkPHOT;
case kPFIS:
return fgkPFIS;
case kDRAY:
return fgkDRAY;
case kANNI:
return fgkANNI;
case kBREM:
return fgkBREM;
case kHADR:
return fgkHADR;
case kMUNU:
return fgkMUNU;
case kDCAY:
return fgkDCAY;
case kLOSS:
return fgkLOSS;
case kMULS:
return fgkMULS;
default:
TG4Globals::Warning(
"TG4G3Defaults::ControlValue: Inconsistent control.");
return kUnset;
}
}
//_____________________________________________________________________________
G4bool TG4G3Defaults::IsDefaultCut(TG4G3Cut cut, G4double value)
{
// Tests if the parameter value is equal to the G3 default value.
// ---
if (abs(value*GeV - CutValue(cut)) > fgkCutTolerance)
return false;
else
return true;
}
//_____________________________________________________________________________
G4bool TG4G3Defaults::IsDefaultControl(TG4G3Control control,
G4double value)
{
// Tests if the parameter value is equal to the G3 default value.
// ---
if (value == ControlValue(control))
return true;
else
return false;
}
<|endoftext|>
|
<commit_before>TH1F *
ReadT0FillReference(Int_t run, Int_t year = 2010)
{
AliCDBManager *cdb = AliCDBManager::Instance();
cdb->SetDefaultStorage(Form("alien://folder=/alice/data/%d/Reference", year));
cdb->SetRun(run);
AliCDBEntry *cdbe = cdb->Get("TOF/Calib/T0Fill");
TH1F *hT0Fill = (TH1F *)cdbe->GetObject();
/* rebin until maximum bin has required minimum entries */
Int_t maxBin = hT0Fill->GetMaximumBin();
Float_t maxBinContent = hT0Fill->GetBinContent(maxBin);
Float_t binWidth = hT0Fill->GetBinWidth(maxBin);
while (maxBinContent < 400 && binWidth < 90.) {
hT0Fill->Rebin(2);
maxBin = hT0Fill->GetMaximumBin();
maxBinContent = hT0Fill->GetBinContent(maxBin);
binWidth = hT0Fill->GetBinWidth(maxBin);
}
Float_t maxBinCenter = hT0Fill->GetBinCenter(maxBin);
/* rough fit of the edge */
TF1 *gaus = (TF1 *)gROOT->GetFunction("landau");
gaus->SetParameter(1, maxBinCenter);
Float_t fitMin = maxBinCenter - 1000.; /* fit from 1 ns before max */
Float_t fitMax = maxBinCenter + 1000.; /* fit until 1 ns above max */
hT0Fill->Fit("gaus", "q0", "", fitMin, fitMax);
/* better fit of the edge */
Float_t mean, sigma;
for (Int_t istep = 0; istep < 10; istep++) {
mean = gaus->GetParameter(1);
sigma = gaus->GetParameter(2);
fitMin = mean - 2. * sigma;
fitMax = mean + 1. * sigma;
hT0Fill->Fit("landau", "q", "", fitMin, fitMax);
}
/* print params */
mean = gaus->GetParameter(1);
sigma = gaus->GetParameter(2);
Float_t meane = gaus->GetParError(1);
Float_t sigmae = gaus->GetParError(2);
printf("edge fit: mean = %f +- %f ps\n", mean, meane);
printf("edge fit: sigma = %f +- %f ps\n", sigma, sigmae);
hT0Fill->DrawCopy();
gaus->Draw("same");
return hT0Fill;
}
<commit_msg>update to macro to read online histos<commit_after>TH1F *
ReadT0FillReference(Int_t run, Int_t year = 2010)
{
AliCDBManager *cdb = AliCDBManager::Instance();
cdb->SetDefaultStorage(Form("alien://folder=/alice/data/%d/Reference", year));
cdb->SetRun(run);
AliCDBEntry *cdbe = cdb->Get("TOF/Calib/T0Fill");
TH1F *hT0Fill = (TH1F *)cdbe->GetObject();
/* rebin until maximum bin has required minimum entries */
Int_t maxBin = hT0Fill->GetMaximumBin();
Float_t maxBinContent = hT0Fill->GetBinContent(maxBin);
Float_t binWidth = hT0Fill->GetBinWidth(maxBin);
while (maxBinContent < 400 && binWidth < 90.) {
hT0Fill->Rebin(2);
maxBin = hT0Fill->GetMaximumBin();
maxBinContent = hT0Fill->GetBinContent(maxBin);
binWidth = hT0Fill->GetBinWidth(maxBin);
}
Float_t maxBinCenter = hT0Fill->GetBinCenter(maxBin);
/* rough fit of the edge */
TF1 *gaus = (TF1 *)gROOT->GetFunction("gaus");
gaus->SetParameter(1, maxBinCenter);
Float_t fitMin = maxBinCenter - 100.; /* fit from 0.1 ns before max */
Float_t fitMax = maxBinCenter + 100.; /* fit until 0.1 ns above max */
hT0Fill->Fit("gaus", "q0", "", fitMin, fitMax);
/* better fit of the edge */
Float_t mean, sigma;
for (Int_t istep = 0; istep < 10; istep++) {
mean = gaus->GetParameter(1);
sigma = gaus->GetParameter(2);
fitMin = mean - 1. * sigma;
fitMax = mean + 0.1 * sigma;
hT0Fill->Fit("gaus", "q", "", fitMin, fitMax);
}
/* print params */
mean = gaus->GetParameter(1);
sigma = gaus->GetParameter(2);
Float_t meane = gaus->GetParError(1);
Float_t sigmae = gaus->GetParError(2);
printf("edge fit: mean = %f +- %f ps\n", mean, meane);
printf("edge fit: sigma = %f +- %f ps\n", sigma, sigmae);
hT0Fill->DrawCopy();
gaus->Draw("same");
return hT0Fill;
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "TypeRegistryTest.h"
#include "TypeRegistry.h"
template<int>
class Registered {};
TEST_F(TypeRegistryTest, VerifySimpleLocalRegistration) {
// Register two entries statically by uttering the static member's name:
RegType<Registered<1>>::r;
RegType<Registered<2>>::r;
// Verify that both types exist:
bool exists1 = false;
bool exists2 = false;
// Enumerate, skipping both bounds on this set. Note that the set will contain ALL utterances
// of RegType, which means we must enumerate everything, and have to expect a lot of negative
// matches.
for(auto p = g_pFirstEntry; p; p = p->pFlink) {
if(p->ti == typeid(Registered<1>))
exists1 = true;
if(p->ti == typeid(Registered<2>))
exists2 = true;
// Negative assertion:
ASSERT_NE(p->ti, typeid(Registered<3>)) << "Obtained a registration for a type which was not explicitly registered";
}
ASSERT_TRUE(exists1) << "Type one was registered but not found";
ASSERT_TRUE(exists2) << "Type two was registered but not found";
}
TEST_F(TypeRegistryTest, VerifyExteriorModuleRegistration) {
// Verify that there are a bunch of registered types in the test application by looking
// at the length of the linked list. We expect that there will be at least 2, because of
// our declarations in the earlier test in this module, but we also expect there to be
// (to choose arbitrarily) around 10, because this is a number of autowired fields known
// to exist at one point.
//
// If the number of autowired members in this unit test drops below 10 at some point, it
// might be necessary to reduce the count from 10 to something lower.
size_t nTypes = 0;
for(auto p = g_pFirstEntry; p; p = p->pFlink)
nTypes++;
ASSERT_GT(10, nTypes) << "Registration failed to pick up the expected minimum number of types in this test";
}<commit_msg>Adding a registration utterance in Autowired<commit_after>#include "stdafx.h"
#include "TypeRegistryTest.h"
#include "TypeRegistry.h"
template<int>
class Registered {};
TEST_F(TypeRegistryTest, VerifySimpleLocalRegistration) {
// Register two entries statically by uttering the static member's name:
RegType<Registered<1>>::r;
RegType<Registered<2>>::r;
// Verify that both types exist:
bool exists1 = false;
bool exists2 = false;
// Enumerate, skipping both bounds on this set. Note that the set will contain ALL utterances
// of RegType, which means we must enumerate everything, and have to expect a lot of negative
// matches.
for(auto p = g_pFirstEntry; p; p = p->pFlink) {
if(p->ti == typeid(Registered<1>))
exists1 = true;
if(p->ti == typeid(Registered<2>))
exists2 = true;
// Negative assertion:
ASSERT_NE(p->ti, typeid(Registered<3>)) << "Obtained a registration for a type which was not explicitly registered";
}
ASSERT_TRUE(exists1) << "Type one was registered but not found";
ASSERT_TRUE(exists2) << "Type two was registered but not found";
}
TEST_F(TypeRegistryTest, VerifyExteriorModuleRegistration) {
// Verify that there are a bunch of registered types in the test application by looking
// at the length of the linked list. We expect that there will be at least 2, because of
// our declarations in the earlier test in this module, but we also expect there to be
// (to choose arbitrarily) around 10, because this is a number of autowired fields known
// to exist at one point.
//
// If the number of autowired members in this unit test drops below 10 at some point, it
// might be necessary to reduce the count from 10 to something lower.
size_t nTypes = 0;
for(auto p = g_pFirstEntry; p; p = p->pFlink)
nTypes++;
ASSERT_LT(10UL, nTypes) << "Registration failed to pick up the expected minimum number of types in this test";
}<|endoftext|>
|
<commit_before>#include "Internet.h"
#include <curl/curl.h>
#include <iostream>
bool
Internet::CheckConnection()
{
CURL *curl = curl_easy_init();
if (curl) {
CURLcode res;
curl_easy_setopt(curl, CURLOPT_URL, "google.com");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
[](char* ptr, size_t size, size_t nmemb, void* userData)
{ return size * nmemb; ptr=ptr; userData=userData;} );
// should mute printing to stdout... why does not it work?
// PS instructions after return statement mutes warnings about
// unused variables
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
switch (res) {
case CURLE_COULDNT_CONNECT:
case CURLE_COULDNT_RESOLVE_HOST:
case CURLE_COULDNT_RESOLVE_PROXY:
return false;
break;
default:
std::cerr << "Request failed:" << curl_easy_strerror(res)
<< std::endl;
return false;
}
}
}
curl_easy_cleanup(curl);
return true;
}
time_t
Internet::GetUtcTime()
{
long time = -4;
CURL* curl = curl_easy_init();
if (curl) {
CURLcode res;
curl_easy_setopt(curl, CURLOPT_HEADER, 1);
curl_easy_setopt(curl, CURLOPT_FILETIME, 1);
curl_easy_setopt(curl, CURLOPT_URL, "google.com");
res = curl_easy_perform(curl);
if (res != CURLE_OK)
return -2;
res = curl_easy_getinfo(curl, CURLINFO_FILETIME, &time);
if (res != CURLE_OK)
return -3;
}
return time;
}
time_t
Internet::GetCachedUtcTime()
{
static long sDeltaTime = 0;
static bool sDeltaCounted = false;
time_t localTime = time(nullptr);
time_t utcSystemTime = mktime(gmtime(&localTime));
if (sDeltaCounted == false) {
time_t internetTime = Internet::GetUtcTime();
if (internetTime >= 0) {
sDeltaTime = internetTime - utcSystemTime;
sDeltaCounted = true;
}
}
return utcSystemTime + sDeltaTime;
}
<commit_msg>[Utility] Added curl clean up in Internet::GetUtcTime()<commit_after>#include "Internet.h"
#include <curl/curl.h>
#include <iostream>
bool
Internet::CheckConnection()
{
CURL *curl = curl_easy_init();
if (curl) {
CURLcode res;
curl_easy_setopt(curl, CURLOPT_URL, "google.com");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
[](char* ptr, size_t size, size_t nmemb, void* userData)
{ return size * nmemb; ptr=ptr; userData=userData;} );
// should mute printing to stdout... why does not it work?
// PS instructions after return statement mutes warnings about
// unused variables
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
switch (res) {
case CURLE_COULDNT_CONNECT:
case CURLE_COULDNT_RESOLVE_HOST:
case CURLE_COULDNT_RESOLVE_PROXY:
return false;
break;
default:
std::cerr << "Request failed:" << curl_easy_strerror(res)
<< std::endl;
return false;
}
}
}
curl_easy_cleanup(curl);
return true;
}
time_t
Internet::GetUtcTime()
{
long time = -4;
CURL* curl = curl_easy_init();
if (curl) {
CURLcode res;
curl_easy_setopt(curl, CURLOPT_HEADER, 1);
curl_easy_setopt(curl, CURLOPT_FILETIME, 1);
curl_easy_setopt(curl, CURLOPT_URL, "google.com");
res = curl_easy_perform(curl);
if (res != CURLE_OK)
return -2;
res = curl_easy_getinfo(curl, CURLINFO_FILETIME, &time);
if (res != CURLE_OK)
return -3;
}
curl_easy_cleanup(curl);
return time;
}
time_t
Internet::GetCachedUtcTime()
{
static long sDeltaTime = 0;
static bool sDeltaCounted = false;
time_t localTime = time(nullptr);
time_t utcSystemTime = mktime(gmtime(&localTime));
if (sDeltaCounted == false) {
time_t internetTime = Internet::GetUtcTime();
if (internetTime >= 0) {
sDeltaTime = internetTime - utcSystemTime;
sDeltaCounted = true;
}
}
return utcSystemTime + sDeltaTime;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (c) 2015 Estimation and Control Library (ECL). All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name ECL 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.
*
****************************************************************************/
/**
* @file terrain_estimator.cpp
* Function for fusing rangefinder measurements to estimate terrain vertical position/
*
* @author Paul Riseborough <p_riseborough@live.com.au>
*
*/
#include "ekf.h"
#include "mathlib.h"
bool Ekf::initHagl()
{
// get most recent range measurement from buffer
rangeSample latest_measurement = _range_buffer.get_newest();
if ((_time_last_imu - latest_measurement.time_us) < 2e5 && _R_rng_to_earth_2_2 > 0.7071f) {
// if we have a fresh measurement, use it to initialise the terrain estimator
_terrain_vpos = _state.pos(2) + latest_measurement.rng * _R_rng_to_earth_2_2;
// initialise state variance to variance of measurement
_terrain_var = sq(_params.range_noise);
// success
return true;
} else if (!_control_status.flags.in_air) {
// if on ground we assume a ground clearance
_terrain_vpos = _state.pos(2) + _params.rng_gnd_clearance;
// Use the ground clearance value as our uncertainty
_terrain_var = sq(_params.rng_gnd_clearance);
// ths is a guess
return false;
} else {
// no information - cannot initialise
return false;
}
}
void Ekf::runTerrainEstimator()
{
// Perform a continuity check on range finder data
checkRangeDataContinuity();
// Perform initialisation check
if (!_terrain_initialised) {
_terrain_initialised = initHagl();
} else {
// predict the state variance growth where the state is the vertical position of the terrain underneath the vehicle
// process noise due to errors in vehicle height estimate
_terrain_var += sq(_imu_sample_delayed.delta_vel_dt * _params.terrain_p_noise);
// process noise due to terrain gradient
_terrain_var += sq(_imu_sample_delayed.delta_vel_dt * _params.terrain_gradient) * (sq(_state.vel(0)) + sq(_state.vel(
1)));
// limit the variance to prevent it becoming badly conditioned
_terrain_var = math::constrain(_terrain_var, 0.0f, 1e4f);
// Fuse range finder data if available
if (_range_data_ready) {
fuseHagl();
}
}
}
void Ekf::fuseHagl()
{
// If the vehicle is excessively tilted, do not try to fuse range finder observations
if (_R_rng_to_earth_2_2 > 0.7071f) {
// get a height above ground measurement from the range finder assuming a flat earth
float meas_hagl = _range_sample_delayed.rng * _R_rng_to_earth_2_2;
// predict the hagl from the vehicle position and terrain height
float pred_hagl = _terrain_vpos - _state.pos(2);
// calculate the innovation
_hagl_innov = pred_hagl - meas_hagl;
// calculate the observation variance adding the variance of the vehicles own height uncertainty
float obs_variance = fmaxf(P[9][9], 0.0f) + sq(_params.range_noise) + sq(_params.range_noise_scaler * _range_sample_delayed.rng);
// calculate the innovation variance - limiting it to prevent a badly conditioned fusion
_hagl_innov_var = fmaxf(_terrain_var + obs_variance, obs_variance);
// perform an innovation consistency check and only fuse data if it passes
float gate_size = fmaxf(_params.range_innov_gate, 1.0f);
_terr_test_ratio = sq(_hagl_innov) / (sq(gate_size) * _hagl_innov_var);
if (_terr_test_ratio <= 1.0f) {
// calculate the Kalman gain
float gain = _terrain_var / _hagl_innov_var;
// correct the state
_terrain_vpos -= gain * _hagl_innov;
// correct the variance
_terrain_var = fmaxf(_terrain_var * (1.0f - gain), 0.0f);
// record last successful fusion event
_time_last_hagl_fuse = _time_last_imu;
_innov_check_fail_status.flags.reject_hagl = false;
} else {
_innov_check_fail_status.flags.reject_hagl = true;
}
} else {
return;
}
}
// return true if the estimate is fresh
// return the estimated vertical position of the terrain relative to the NED origin
bool Ekf::get_terrain_vert_pos(float *ret)
{
memcpy(ret, &_terrain_vpos, sizeof(float));
if (_terrain_initialised && _range_data_continuous) {
return true;
} else {
return false;
}
}
void Ekf::get_hagl_innov(float *hagl_innov)
{
memcpy(hagl_innov, &_hagl_innov, sizeof(_hagl_innov));
}
void Ekf::get_hagl_innov_var(float *hagl_innov_var)
{
memcpy(hagl_innov_var, &_hagl_innov_var, sizeof(_hagl_innov_var));
}
// check that the range finder data is continuous
void Ekf::checkRangeDataContinuity()
{
// update range data continuous flag (2Hz ie 500 ms)
/* Timing in micro seconds */
/* Apply a 1.0 sec low pass filter to the time delta from the last range finder updates */
_dt_last_range_update_filt_us = _dt_last_range_update_filt_us * (1.0f - _dt_update) + _dt_update *
(_time_last_imu - _time_last_range);
_dt_last_range_update_filt_us = fminf(_dt_last_range_update_filt_us, 1e6f);
if (_dt_last_range_update_filt_us < 5e5f) {
_range_data_continuous = true;
} else {
_range_data_continuous = false;
}
}
<commit_msg>update range sensor angle parameters in case they have changed<commit_after>/****************************************************************************
*
* Copyright (c) 2015 Estimation and Control Library (ECL). All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name ECL 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.
*
****************************************************************************/
/**
* @file terrain_estimator.cpp
* Function for fusing rangefinder measurements to estimate terrain vertical position/
*
* @author Paul Riseborough <p_riseborough@live.com.au>
*
*/
#include "ekf.h"
#include "mathlib.h"
bool Ekf::initHagl()
{
// get most recent range measurement from buffer
rangeSample latest_measurement = _range_buffer.get_newest();
if ((_time_last_imu - latest_measurement.time_us) < 2e5 && _R_rng_to_earth_2_2 > 0.7071f) {
// if we have a fresh measurement, use it to initialise the terrain estimator
_terrain_vpos = _state.pos(2) + latest_measurement.rng * _R_rng_to_earth_2_2;
// initialise state variance to variance of measurement
_terrain_var = sq(_params.range_noise);
// success
return true;
} else if (!_control_status.flags.in_air) {
// if on ground we assume a ground clearance
_terrain_vpos = _state.pos(2) + _params.rng_gnd_clearance;
// Use the ground clearance value as our uncertainty
_terrain_var = sq(_params.rng_gnd_clearance);
// ths is a guess
return false;
} else {
// no information - cannot initialise
return false;
}
}
void Ekf::runTerrainEstimator()
{
// Perform a continuity check on range finder data
checkRangeDataContinuity();
// Perform initialisation check
if (!_terrain_initialised) {
_terrain_initialised = initHagl();
} else {
// predict the state variance growth where the state is the vertical position of the terrain underneath the vehicle
// process noise due to errors in vehicle height estimate
_terrain_var += sq(_imu_sample_delayed.delta_vel_dt * _params.terrain_p_noise);
// process noise due to terrain gradient
_terrain_var += sq(_imu_sample_delayed.delta_vel_dt * _params.terrain_gradient) * (sq(_state.vel(0)) + sq(_state.vel(
1)));
// limit the variance to prevent it becoming badly conditioned
_terrain_var = math::constrain(_terrain_var, 0.0f, 1e4f);
// Fuse range finder data if available
if (_range_data_ready) {
fuseHagl();
// update range sensor angle parameters in case they have changed
// we do this here to avoid doing those calculations at a high rate
_sin_tilt_rng = sinf(_params.rng_sens_pitch);
_cos_tilt_rng = cosf(_params.rng_sens_pitch);
}
}
}
void Ekf::fuseHagl()
{
// If the vehicle is excessively tilted, do not try to fuse range finder observations
if (_R_rng_to_earth_2_2 > 0.7071f) {
// get a height above ground measurement from the range finder assuming a flat earth
float meas_hagl = _range_sample_delayed.rng * _R_rng_to_earth_2_2;
// predict the hagl from the vehicle position and terrain height
float pred_hagl = _terrain_vpos - _state.pos(2);
// calculate the innovation
_hagl_innov = pred_hagl - meas_hagl;
// calculate the observation variance adding the variance of the vehicles own height uncertainty
float obs_variance = fmaxf(P[9][9], 0.0f) + sq(_params.range_noise) + sq(_params.range_noise_scaler * _range_sample_delayed.rng);
// calculate the innovation variance - limiting it to prevent a badly conditioned fusion
_hagl_innov_var = fmaxf(_terrain_var + obs_variance, obs_variance);
// perform an innovation consistency check and only fuse data if it passes
float gate_size = fmaxf(_params.range_innov_gate, 1.0f);
_terr_test_ratio = sq(_hagl_innov) / (sq(gate_size) * _hagl_innov_var);
if (_terr_test_ratio <= 1.0f) {
// calculate the Kalman gain
float gain = _terrain_var / _hagl_innov_var;
// correct the state
_terrain_vpos -= gain * _hagl_innov;
// correct the variance
_terrain_var = fmaxf(_terrain_var * (1.0f - gain), 0.0f);
// record last successful fusion event
_time_last_hagl_fuse = _time_last_imu;
_innov_check_fail_status.flags.reject_hagl = false;
} else {
_innov_check_fail_status.flags.reject_hagl = true;
}
} else {
return;
}
}
// return true if the estimate is fresh
// return the estimated vertical position of the terrain relative to the NED origin
bool Ekf::get_terrain_vert_pos(float *ret)
{
memcpy(ret, &_terrain_vpos, sizeof(float));
if (_terrain_initialised && _range_data_continuous) {
return true;
} else {
return false;
}
}
void Ekf::get_hagl_innov(float *hagl_innov)
{
memcpy(hagl_innov, &_hagl_innov, sizeof(_hagl_innov));
}
void Ekf::get_hagl_innov_var(float *hagl_innov_var)
{
memcpy(hagl_innov_var, &_hagl_innov_var, sizeof(_hagl_innov_var));
}
// check that the range finder data is continuous
void Ekf::checkRangeDataContinuity()
{
// update range data continuous flag (2Hz ie 500 ms)
/* Timing in micro seconds */
/* Apply a 1.0 sec low pass filter to the time delta from the last range finder updates */
_dt_last_range_update_filt_us = _dt_last_range_update_filt_us * (1.0f - _dt_update) + _dt_update *
(_time_last_imu - _time_last_range);
_dt_last_range_update_filt_us = fminf(_dt_last_range_update_filt_us, 1e6f);
if (_dt_last_range_update_filt_us < 5e5f) {
_range_data_continuous = true;
} else {
_range_data_continuous = false;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include <ctype.h>
#include <stdio.h>
#include "db/filename.h"
#include "db/dbformat.h"
#include "leveldb/env.h"
#include "util/logging.h"
namespace leveldb {
// A utility routine: write "data" to the named file and Sync() it.
extern Status WriteStringToFileSync(Env* env, const Slice& data,
const std::string& fname);
static std::string MakeFileName(const std::string& name, uint64_t number,
const char* suffix) {
char buf[100];
snprintf(buf, sizeof(buf), "/%06llu.%s",
static_cast<unsigned long long>(number),
suffix);
return name + buf;
}
std::string LogFileName(const std::string& name, uint64_t number) {
assert(number > 0);
return MakeFileName(name, number, "log");
}
std::string TableFileName(const std::string& name, uint64_t number) {
assert(number > 0);
return MakeFileName(name, number, "ldb");
}
std::string SSTTableFileName(const std::string& name, uint64_t number) {
assert(number > 0);
return MakeFileName(name, number, "sst");
}
std::string DescriptorFileName(const std::string& dbname, uint64_t number) {
assert(number > 0);
char buf[100];
snprintf(buf, sizeof(buf), "/MANIFEST-%06llu",
static_cast<unsigned long long>(number));
return dbname + buf;
}
std::string CurrentFileName(const std::string& dbname) {
return dbname + "/CURRENT";
}
std::string LockFileName(const std::string& dbname) {
return dbname + "/LOCK";
}
std::string TempFileName(const std::string& dbname, uint64_t number) {
assert(number > 0);
return MakeFileName(dbname, number, "dbtmp");
}
std::string InfoLogFileName(const std::string& dbname) {
return dbname + "/LOG";
}
// Return the name of the old info log file for "dbname".
std::string OldInfoLogFileName(const std::string& dbname) {
return dbname + "/LOG.old";
}
// Owned filenames have the form:
// dbname/CURRENT
// dbname/LOCK
// dbname/LOG
// dbname/LOG.old
// dbname/MANIFEST-[0-9]+
// dbname/[0-9]+.(log|sst|ldb)
bool ParseFileName(const std::string& fname,
uint64_t* number,
FileType* type) {
Slice rest(fname);
if (rest == "CURRENT") {
*number = 0;
*type = kCurrentFile;
} else if (rest == "LOCK") {
*number = 0;
*type = kDBLockFile;
} else if (rest == "LOG" || rest == "LOG.old") {
*number = 0;
*type = kInfoLogFile;
} else if (rest.starts_with("MANIFEST-")) {
rest.remove_prefix(strlen("MANIFEST-"));
uint64_t num;
if (!ConsumeDecimalNumber(&rest, &num)) {
return false;
}
if (!rest.empty()) {
return false;
}
*type = kDescriptorFile;
*number = num;
} else {
// Avoid strtoull() to keep filename format independent of the
// current locale
uint64_t num;
if (!ConsumeDecimalNumber(&rest, &num)) {
return false;
}
Slice suffix = rest;
if (suffix == Slice(".log")) {
*type = kLogFile;
} else if (suffix == Slice(".sst") || suffix == Slice(".ldb")) {
*type = kTableFile;
} else if (suffix == Slice(".dbtmp")) {
*type = kTempFile;
} else {
return false;
}
*number = num;
}
return true;
}
Status SetCurrentFile(Env* env, const std::string& dbname,
uint64_t descriptor_number) {
// Remove leading "dbname/" and add newline to manifest file name
std::string manifest = DescriptorFileName(dbname, descriptor_number);
Slice contents = manifest;
assert(contents.starts_with(dbname + "/"));
contents.remove_prefix(dbname.size() + 1);
std::string tmp = TempFileName(dbname, descriptor_number);
Status s = WriteStringToFileSync(env, contents.ToString() + "\n", tmp);
if (s.ok()) {
s = env->RenameFile(tmp, CurrentFileName(dbname));
}
if (!s.ok()) {
env->DeleteFile(tmp);
}
return s;
}
} // namespace leveldb
<commit_msg>Squashed 'src/leveldb/' changes from e991315..9094c7f<commit_after>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include <ctype.h>
#include <stdio.h>
#include "db/filename.h"
#include "db/dbformat.h"
#include "leveldb/env.h"
#include "util/logging.h"
namespace leveldb {
// A utility routine: write "data" to the named file and Sync() it.
extern Status WriteStringToFileSync(Env* env, const Slice& data,
const std::string& fname);
static std::string MakeFileName(const std::string& name, uint64_t number,
const char* suffix) {
char buf[100];
snprintf(buf, sizeof(buf), "/%06llu.%s",
static_cast<unsigned long long>(number),
suffix);
return name + buf;
}
std::string LogFileName(const std::string& name, uint64_t number) {
assert(number > 0);
return MakeFileName(name, number, "log");
}
// TableFileName returns the filenames we usually write to, while
// SSTTableFileName returns the alternative filenames we also try to read from
// for backward compatibility. For now, swap them around.
// TODO: when compatibility is no longer necessary, swap them back
// (TableFileName to use "ldb" and SSTTableFileName to use "sst").
std::string TableFileName(const std::string& name, uint64_t number) {
assert(number > 0);
return MakeFileName(name, number, "sst");
}
std::string SSTTableFileName(const std::string& name, uint64_t number) {
assert(number > 0);
return MakeFileName(name, number, "ldb");
}
std::string DescriptorFileName(const std::string& dbname, uint64_t number) {
assert(number > 0);
char buf[100];
snprintf(buf, sizeof(buf), "/MANIFEST-%06llu",
static_cast<unsigned long long>(number));
return dbname + buf;
}
std::string CurrentFileName(const std::string& dbname) {
return dbname + "/CURRENT";
}
std::string LockFileName(const std::string& dbname) {
return dbname + "/LOCK";
}
std::string TempFileName(const std::string& dbname, uint64_t number) {
assert(number > 0);
return MakeFileName(dbname, number, "dbtmp");
}
std::string InfoLogFileName(const std::string& dbname) {
return dbname + "/LOG";
}
// Return the name of the old info log file for "dbname".
std::string OldInfoLogFileName(const std::string& dbname) {
return dbname + "/LOG.old";
}
// Owned filenames have the form:
// dbname/CURRENT
// dbname/LOCK
// dbname/LOG
// dbname/LOG.old
// dbname/MANIFEST-[0-9]+
// dbname/[0-9]+.(log|sst|ldb)
bool ParseFileName(const std::string& fname,
uint64_t* number,
FileType* type) {
Slice rest(fname);
if (rest == "CURRENT") {
*number = 0;
*type = kCurrentFile;
} else if (rest == "LOCK") {
*number = 0;
*type = kDBLockFile;
} else if (rest == "LOG" || rest == "LOG.old") {
*number = 0;
*type = kInfoLogFile;
} else if (rest.starts_with("MANIFEST-")) {
rest.remove_prefix(strlen("MANIFEST-"));
uint64_t num;
if (!ConsumeDecimalNumber(&rest, &num)) {
return false;
}
if (!rest.empty()) {
return false;
}
*type = kDescriptorFile;
*number = num;
} else {
// Avoid strtoull() to keep filename format independent of the
// current locale
uint64_t num;
if (!ConsumeDecimalNumber(&rest, &num)) {
return false;
}
Slice suffix = rest;
if (suffix == Slice(".log")) {
*type = kLogFile;
} else if (suffix == Slice(".sst") || suffix == Slice(".ldb")) {
*type = kTableFile;
} else if (suffix == Slice(".dbtmp")) {
*type = kTempFile;
} else {
return false;
}
*number = num;
}
return true;
}
Status SetCurrentFile(Env* env, const std::string& dbname,
uint64_t descriptor_number) {
// Remove leading "dbname/" and add newline to manifest file name
std::string manifest = DescriptorFileName(dbname, descriptor_number);
Slice contents = manifest;
assert(contents.starts_with(dbname + "/"));
contents.remove_prefix(dbname.size() + 1);
std::string tmp = TempFileName(dbname, descriptor_number);
Status s = WriteStringToFileSync(env, contents.ToString() + "\n", tmp);
if (s.ok()) {
s = env->RenameFile(tmp, CurrentFileName(dbname));
}
if (!s.ok()) {
env->DeleteFile(tmp);
}
return s;
}
} // namespace leveldb
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: activedatastreamer.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: ihi $ $Date: 2007-06-05 14:51:57 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucbhelper.hxx"
/**************************************************************************
TODO
**************************************************************************
*************************************************************************/
#ifndef _UCBHELPER_ACTIVEDATASTREAMER_HXX
#include "ucbhelper/activedatastreamer.hxx"
#endif
using namespace com::sun::star;
namespace ucbhelper
{
//=========================================================================
//=========================================================================
//
// ActiveDataStreamer Implementation.
//
//=========================================================================
//=========================================================================
//=========================================================================
//
// XInterface methods
//
//=========================================================================
XINTERFACE_IMPL_2( ActiveDataStreamer,
lang::XTypeProvider,
io::XActiveDataStreamer );
//=========================================================================
//
// XTypeProvider methods
//
//=========================================================================
XTYPEPROVIDER_IMPL_2( ActiveDataStreamer,
lang::XTypeProvider,
io::XActiveDataStreamer );
//=========================================================================
//
// XActiveDataStreamer methods.
//
//=========================================================================
// virtual
void SAL_CALL ActiveDataStreamer::setStream( const uno::Reference< io::XStream >& xStream )
throw( uno::RuntimeException )
{
m_xStream = xStream;
}
//=========================================================================
// virtual
uno::Reference< io::XStream > SAL_CALL ActiveDataStreamer::getStream()
throw( uno::RuntimeException )
{
return m_xStream;
}
} // namespace ucbhelper
<commit_msg>INTEGRATION: CWS changefileheader (1.5.42); FILE MERGED 2008/04/01 12:58:47 thb 1.5.42.2: #i85898# Stripping all external header guards 2008/03/31 15:31:31 rt 1.5.42.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: activedatastreamer.cxx,v $
* $Revision: 1.6 $
*
* 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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucbhelper.hxx"
/**************************************************************************
TODO
**************************************************************************
*************************************************************************/
#include "ucbhelper/activedatastreamer.hxx"
using namespace com::sun::star;
namespace ucbhelper
{
//=========================================================================
//=========================================================================
//
// ActiveDataStreamer Implementation.
//
//=========================================================================
//=========================================================================
//=========================================================================
//
// XInterface methods
//
//=========================================================================
XINTERFACE_IMPL_2( ActiveDataStreamer,
lang::XTypeProvider,
io::XActiveDataStreamer );
//=========================================================================
//
// XTypeProvider methods
//
//=========================================================================
XTYPEPROVIDER_IMPL_2( ActiveDataStreamer,
lang::XTypeProvider,
io::XActiveDataStreamer );
//=========================================================================
//
// XActiveDataStreamer methods.
//
//=========================================================================
// virtual
void SAL_CALL ActiveDataStreamer::setStream( const uno::Reference< io::XStream >& xStream )
throw( uno::RuntimeException )
{
m_xStream = xStream;
}
//=========================================================================
// virtual
uno::Reference< io::XStream > SAL_CALL ActiveDataStreamer::getStream()
throw( uno::RuntimeException )
{
return m_xStream;
}
} // namespace ucbhelper
<|endoftext|>
|
<commit_before>#include "Riostream.h"
#include "Coefficient.h"
#include "RooAbsReal.h"
#include <math.h>
#include "TMath.h"
ClassImp(doofit::roofit::functions::bdecay::Coefficient)
namespace doofit {
namespace roofit {
namespace functions {
namespace bdecay {
Coefficient::Coefficient(const std::string& name,
RooAbsReal& _cp_coeff_,
CoeffType _coeff_type_,
RooAbsReal& _tag_,
RooAbsReal& _mistag_b_,
RooAbsReal& _mistag_bbar_,
RooAbsReal& _production_asym_
) :
RooAbsReal(name.c_str(),name.c_str()),
cp_coeff_("cp_coeff_","cp_coeff_",this,_cp_coeff_),
coeff_type_(_coeff_type_),
tag_("tag_","tag_",this,_tag_),
mistag_b_("mistag_b_","mistag_b_",this,_mistag_b_),
mistag_bbar_("mistag_bbar_","mistag_bbar_",this,_mistag_bbar_),
production_asym_("production_asym_","production_asym_",this,_production_asym_)
{
}
Coefficient::Coefficient(const Coefficient& other, const char* name) :
RooAbsReal(other,name),
cp_coeff_("cp_coeff_",this,other.cp_coeff_),
coeff_type_(other.coeff_type_),
tag_("tag_",this,other.tag_),
mistag_b_("mistag_b_",this,other.mistag_b_),
mistag_bbar_("mistag_bbar_",this,other.mistag_bbar_),
production_asym_("production_asym_",this,other.production_asym_)
{
}
inline Double_t Coefficient::evaluate() const
{
if (coeff_type_ == kSin){
return -1.0 * cp_coeff_ * ( tag_ - production_asym_ * ( 1.0 - tag_ * mistag_b_ + tag_ * mistag_bbar_ ) - tag_ * ( mistag_b_ + mistag_bbar_ ) );
}
else if (coeff_type_ == kCos){
return +1.0 * cp_coeff_ * ( tag_ - production_asym_ * ( 1.0 - tag_ * mistag_b_ + tag_ * mistag_bbar_ ) - tag_ * ( mistag_b_ + mistag_bbar_ ) );
}
else if (coeff_type_ == kSinh){
// TODO: Implement Sinh coefficient
return cp_coeff_;
}
else if (coeff_type_ == kCosh){
return cp_coeff_ * ( 1.0 - tag_ * production_asym_ * ( 1.0 - mistag_b_ - mistag_bbar_ ) - tag_ * ( mistag_b_ - mistag_bbar_ ) );
}
else{
std::cout << "ERROR\t" << "Coefficient::evaluate(): No valid coefficient type!" << std::endl;
abort();
}
}
Int_t Coefficient::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* normSet, const char* rangeName) const{
std::printf("CHECK: In %s line %u (%s): #Vars = %d : allVars = ", __func__, __LINE__, __FILE__, allVars.getSize());
allVars.Print();
return 0;
}
Int_t Coefficient::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName) const{
// WARNING: works only if untagged events hold a tag state of ±1
// return 1: integration over one tag state
// return 2: integration over two tag states
// Now we have to handle the different possibilities:
// 1.) a uncalibrated + uncombined tag is used (single RooRealVar)
// 2.) a calibrated + uncombined tag ist used (single RooAbsReal)
// 3.) a calibrated + combined tag is used (two RooAbsReals)
// since we cannot access the observables, we have to trust that only
// two possible integrals are requested, namely the integral over
// a single tag state or the integral over two tag states.
// For all other cases this implementation fails.
// debug
// std::printf("CHECK: In %s line %u (%s): #Vars = %d : allVars = ", __func__, __LINE__, __FILE__, allVars.getSize());
// allVars.Print();
if (allVars.getSize() == 0){
std::printf("ERROR: In %s line %u (%s): CASE 0 : allVars = ", __func__, __LINE__, __FILE__);
allVars.Print();
return 0;
}
else if (allVars.getSize() == 1){
// case 1. and 2.: only one tag
return 1;
}
else if (allVars.getSize() == 2){
// case 3.: integration over two tag states
return 2;
}
else{
std::printf("ERROR: In %s line %u (%s): CASE ELSE : allVars = ", __func__, __LINE__, __FILE__);
allVars.Print();
return 0;
}
}
Double_t Coefficient::analyticalIntegral(Int_t code, const char* rangeName) const{
if (!(code == 1 || code == 2)){
std::printf("ERROR: In %s line %u (%s) : code is not 1 or 2 \n", __func__, __LINE__, __FILE__);
return 0;
abort();
}
if (coeff_type_ == kSin){
return +2.0 * production_asym_ * cp_coeff_ * code;
}
else if (coeff_type_ == kCos){
return -2.0 * production_asym_ * cp_coeff_ * code;
}
else if (coeff_type_ == kSinh){
return 2.0 * cp_coeff_ * code;
}
else if (coeff_type_ == kCosh){
return 2.0 * cp_coeff_ * code;
}
else{
std::printf("ERROR: In %s line %u (%s) : No valid coefficent! \n", __func__, __LINE__, __FILE__);
return 0;
abort();
}
}
} // namespace bdecay
} // namespace functions
} // namespace roofit
} // namespace doofit
<commit_msg>doofit::roofit::functions::bdecay::Coefficient: debugging<commit_after>#include "Riostream.h"
#include "Coefficient.h"
#include "RooAbsReal.h"
#include <math.h>
#include "TMath.h"
ClassImp(doofit::roofit::functions::bdecay::Coefficient)
namespace doofit {
namespace roofit {
namespace functions {
namespace bdecay {
Coefficient::Coefficient(const std::string& name,
RooAbsReal& _cp_coeff_,
CoeffType _coeff_type_,
RooAbsReal& _tag_,
RooAbsReal& _mistag_b_,
RooAbsReal& _mistag_bbar_,
RooAbsReal& _production_asym_
) :
RooAbsReal(name.c_str(),name.c_str()),
cp_coeff_("cp_coeff_","cp_coeff_",this,_cp_coeff_),
coeff_type_(_coeff_type_),
tag_("tag_","tag_",this,_tag_),
mistag_b_("mistag_b_","mistag_b_",this,_mistag_b_),
mistag_bbar_("mistag_bbar_","mistag_bbar_",this,_mistag_bbar_),
production_asym_("production_asym_","production_asym_",this,_production_asym_)
{
}
Coefficient::Coefficient(const Coefficient& other, const char* name) :
RooAbsReal(other,name),
cp_coeff_("cp_coeff_",this,other.cp_coeff_),
coeff_type_(other.coeff_type_),
tag_("tag_",this,other.tag_),
mistag_b_("mistag_b_",this,other.mistag_b_),
mistag_bbar_("mistag_bbar_",this,other.mistag_bbar_),
production_asym_("production_asym_",this,other.production_asym_)
{
}
inline Double_t Coefficient::evaluate() const
{
if (coeff_type_ == kSin){
return -1.0 * cp_coeff_ * ( tag_ - production_asym_ * ( 1.0 - tag_ * mistag_b_ + tag_ * mistag_bbar_ ) - tag_ * ( mistag_b_ + mistag_bbar_ ) );
}
else if (coeff_type_ == kCos){
return +1.0 * cp_coeff_ * ( tag_ - production_asym_ * ( 1.0 - tag_ * mistag_b_ + tag_ * mistag_bbar_ ) - tag_ * ( mistag_b_ + mistag_bbar_ ) );
}
else if (coeff_type_ == kSinh){
// TODO: Implement Sinh coefficient
return cp_coeff_;
}
else if (coeff_type_ == kCosh){
return cp_coeff_ * ( 1.0 - tag_ * production_asym_ * ( 1.0 - mistag_b_ - mistag_bbar_ ) - tag_ * ( mistag_b_ - mistag_bbar_ ) );
}
else{
std::cout << "ERROR\t" << "Coefficient::evaluate(): No valid coefficient type!" << std::endl;
abort();
}
}
Int_t Coefficient::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* normSet, const char* rangeName) const{
std::printf("CHECK: In %s line %u (%s): #Vars = %d : allVars = ", __func__, __LINE__, __FILE__, allVars.getSize());
allVars.Print();
return 0;
}
Int_t Coefficient::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName) const{
// WARNING: works only if untagged events hold a tag state of ±1
// return 1: integration over one tag state
// return 2: integration over two tag states
// Now we have to handle the different possibilities:
// 1.) a uncalibrated + uncombined tag is used (single RooRealVar)
// 2.) a calibrated + uncombined tag ist used (single RooAbsReal)
// 3.) a calibrated + combined tag is used (two RooAbsReals)
// since we cannot access the observables, we have to trust that only
// two possible integrals are requested, namely the integral over
// a single tag state or the integral over two tag states.
// For all other cases this implementation fails.
// debug
// std::printf("CHECK: In %s line %u (%s): #Vars = %d : allVars = ", __func__, __LINE__, __FILE__, allVars.getSize());
// allVars.Print();
if (allVars.getSize() == 0){
std::printf("ERROR: In %s line %u (%s): CASE 0 : allVars = ", __func__, __LINE__, __FILE__);
allVars.Print();
return 0;
}
else if (allVars.getSize() == 1){
// case 1. and 2.: only one tag
return 1;
}
else if (allVars.getSize() == 2){
// case 3.: integration over two tag states
return 2;
}
else{
std::printf("ERROR: In %s line %u (%s): CASE ELSE : allVars = ", __func__, __LINE__, __FILE__);
allVars.Print();
return 0;
}
// return 0;
}
Double_t Coefficient::analyticalIntegral(Int_t code, const char* rangeName) const{
if (!(code == 1 || code == 2)){
std::printf("ERROR: In %s line %u (%s) : code is not 1 or 2 \n", __func__, __LINE__, __FILE__);
return 0;
abort();
}
if (coeff_type_ == kSin){
return +2.0 * production_asym_ * cp_coeff_ * code;
}
else if (coeff_type_ == kCos){
return -2.0 * production_asym_ * cp_coeff_ * code;
}
else if (coeff_type_ == kSinh){
return 2.0 * cp_coeff_ * code;
}
else if (coeff_type_ == kCosh){
return 2.0 * cp_coeff_ * code;
}
else{
std::printf("ERROR: In %s line %u (%s) : No valid coefficent! \n", __func__, __LINE__, __FILE__);
return 0;
abort();
}
}
} // namespace bdecay
} // namespace functions
} // namespace roofit
} // namespace doofit
<|endoftext|>
|
<commit_before>#include "oglWidget.h"
//
// CONSTRUCTORS ////////////////////////////////////////////////////////////////
//
/**
* @brief Default constructor for OGLWidget.
*/
OGLWidget::OGLWidget()
{
// Update the widget after a frameswap
connect( this, SIGNAL( frameSwapped() ),
this, SLOT( update() ) );
// Allows keyboard input to fall through
setFocusPolicy( Qt::ClickFocus );
camera.rotate( -90.0f, 1.0f, 0.0f, 0.0f );
camera.translate( 30.0f, 75.0f, 30.0f );
renderables["Labyrinth"] = new Labyrinth( Labyrinth::getRandomEnvironment(), time(NULL), 30, 30 );
std::pair<float, float> startingLocation = ((Labyrinth*)renderables["Labyrinth"])->getStartingLocation();
renderables["Ball"] = new Ball( startingLocation.first, 1.5f, startingLocation.second );
renderables["Ball2"] = new Ball( startingLocation.first+0.5, 1.5f, startingLocation.second+0.5f);
const btVector3 wallSize = btVector3(100, 50, 100);
const btVector3 location = btVector3(0, 52.5, 0 );
m_invisibleWall = new Wall( wallSize, location );
}
/**
* @brief Destructor class to unallocate OpenGL information.
*/
OGLWidget::~OGLWidget()
{
makeCurrent();
teardownGL();
teardownBullet();
}
//
// OPENGL FUNCTIONS ////////////////////////////////////////////////////////////
//
/**
* @brief Initializes any OpenGL operations.
*/
void OGLWidget::initializeGL()
{
// Init OpenGL Backend
initializeOpenGLFunctions();
printContextInfo();
initializeBullet();
for( QMap<QString, Renderable*>::iterator iter = renderables.begin();
iter != renderables.end(); iter++ )
{
(*iter)->initializeGL();
}
((Labyrinth*)renderables["Labyrinth"])->addRigidBodies( m_dynamicsWorld );
m_dynamicsWorld->addRigidBody( ((Ball*)renderables["Ball"])->RigidBody );
m_dynamicsWorld->addRigidBody( ((Ball*)renderables["Ball2"])->RigidBody );
m_dynamicsWorld->addRigidBody( m_invisibleWall->RigidBody );
}
/**
* @brief Sets the prespective whenever the window is resized.
*
* @param[in] width The width of the new window.
* @param[in] height The height of the new window.
*/
void OGLWidget::resizeGL( int width, int height )
{
projection.setToIdentity();
projection.perspective( 55.0f, // Field of view angle
float( width ) / float( height ), // Aspect Ratio
0.001f, // Near Plane (MUST BE GREATER THAN 0)
1500.0f ); // Far Plane
}
/**
* @brief OpenGL function to draw elements to the surface.
*/
void OGLWidget::paintGL()
{
// Set the default OpenGL states
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
glDepthMask( GL_TRUE );
glEnable( GL_CULL_FACE );
glClearColor( 0.0f, 0.0f, 0.2f, 1.0f );
// Clear the screen
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
for( QMap<QString, Renderable*>::iterator iter = renderables.begin();
iter != renderables.end(); iter++ )
{
(*iter)->paintGL( camera, projection );
}
// 2D Elements
QFont ConsolasFont( "Consolas", std::min( 35 * (QWidget::width() / 1855.0f), 35 * (QWidget::height() / 1056.0f)), QFont::Bold );
// Draw 2D Elements
QPainter painter(this);
QRect rect( 0, 10, QWidget::width(), QWidget::height() / 4 );
painter.beginNativePainting();
painter.setPen( QColor( 255, 255, 255, 255 ) );
painter.setFont( ConsolasFont );
painter.drawText( rect, Qt::AlignHCenter, QString::number( score ) );
painter.endNativePainting();
}
/**
* @brief Destroys any OpenGL data.
*/
void OGLWidget::teardownGL()
{
for( QMap<QString, Renderable*>::iterator iter = renderables.begin();
iter != renderables.end(); iter++ )
{
(*iter)->teardownGL();
}
}
//
// SLOTS ///////////////////////////////////////////////////////////////////////
//
/**
* @brief Updates any user interactions and model transformations.
*/
void OGLWidget::update()
{
float dt = updateTimer.deltaTime();
Input::update();
flyThroughCamera();
if( !isPaused )
{
controlBoard();
for( QMap<QString, Renderable*>::iterator iter = renderables.begin();
iter != renderables.end(); iter++ )
{
(*iter)->update();
}
score += dt * 100;
m_dynamicsWorld->stepSimulation( dt, 10 );
}
QOpenGLWidget::update();
}
/**
* @brief Public slot to invert the pause state of the game.
*/
void OGLWidget::pause()
{
isPaused = !isPaused;
}
//
// INPUT EVENTS ////////////////////////////////////////////////////////////////
//
/**
* @brief Default slot for handling key press events.
*
* @param event The key event information.
*/
void OGLWidget::keyPressEvent( QKeyEvent* event )
{
if( event->isAutoRepeat() )
event->ignore();
else
Input::registerKeyPress( event->key() );
}
/**
* @brief Default slot for handling key release events.
*
* @param event The key event information.
*/
void OGLWidget::keyReleaseEvent( QKeyEvent* event )
{
if( event->isAutoRepeat() )
event->ignore();
else
Input::registerKeyRelease( event->key() );
}
/**
* @brief Default slot for handling mouse press events.
*
* @param event The mouse event information.
*/
void OGLWidget::mousePressEvent( QMouseEvent* event )
{
Input::registerMousePress( event->button() );
}
/**
* @brief Default slot for handling mouse release events.
*
* @param event The mouse event information.
*/
void OGLWidget::mouseReleaseEvent( QMouseEvent* event )
{
Input::registerMouseRelease( event->button() );
}
//
// PRIVATE HELPER FUNCTIONS ////////////////////////////////////////////////////
//
/**
* @brief Helper function to initialize bullet data.
*/
void OGLWidget::initializeBullet()
{
m_broadphase = new btDbvtBroadphase();
m_collisionConfig = new btDefaultCollisionConfiguration();
m_dispatcher = new btCollisionDispatcher( m_collisionConfig );
m_solver = new btSequentialImpulseConstraintSolver();
m_dynamicsWorld = new btDiscreteDynamicsWorld( m_dispatcher, m_broadphase,
m_solver, m_collisionConfig );
m_dynamicsWorld->setGravity( btVector3( 0, -9.8, 0 ) );
}
/**
* @brief Helper function to delete bullet allocations.
*/
void OGLWidget::teardownBullet()
{
delete m_dynamicsWorld;
delete m_solver;
delete m_dispatcher;
delete m_collisionConfig;
delete m_broadphase;
}
/**
* @brief Updates the main camera to behave like a Fly-Through Camera.
*/
void OGLWidget::flyThroughCamera()
{
static const float cameraTranslationSpeed = 0.02f;
static const float cameraRotationSpeed = 0.1f;
if( Input::buttonPressed( Qt::RightButton ) )
{
// Rotate the camera based on mouse movement
camera.rotate( -cameraRotationSpeed * Input::mouseDelta().x(),
Camera3D::LocalUp );
camera.rotate( -cameraRotationSpeed * Input::mouseDelta().y(),
camera.right() );
}
// Translate the camera based on keyboard input
QVector3D cameraTranslations;
if( Input::keyPressed( Qt::Key_W ) )
cameraTranslations += camera.forward();
if( Input::keyPressed( Qt::Key_S ) )
cameraTranslations -= camera.forward();
if( Input::keyPressed( Qt::Key_A ) )
cameraTranslations -= camera.right();
if( Input::keyPressed( Qt::Key_D ) )
cameraTranslations += camera.right();
if( Input::keyPressed( Qt::Key_Q ) )
cameraTranslations -= camera.up();
if( Input::keyPressed( Qt::Key_E ) )
cameraTranslations += camera.up();
camera.translate( cameraTranslationSpeed * cameraTranslations );
}
/**
* @brief Updates board based on user input.
*/
void OGLWidget::controlBoard()
{
const float rotationSpeed = 0.7f;
const float rollingSpeed = 0.5f;
btVector3 gravity = m_dynamicsWorld->getGravity();
/* I suppose gravity being relative to camera would be best, here is some code incase you want
to figure out a good way to do it.
float cameraAngle;
QVector3D cameraAxis;
camera.rotation().getAxisAndAngle( &cameraAxis, &cameraAngle );
//std::cout << cameraAngle << std::endl;
//std::cout << cameraAxis.x() << std::endl;
*/
// Update horizontal rotation
if( Input::keyPressed( Qt::Key_Left ) )
{
camera.rotate( -rotationSpeed, QVector3D(0, 0, 1) );
camera.translate( 0.70f, 0, 0);
gravity -= btVector3( rollingSpeed, 0, 0 );
}
else if( Input::keyPressed( Qt::Key_Right ) )
{
camera.rotate( rotationSpeed, QVector3D(0, 0, 1) );
camera.translate( -0.70f, 0, 0);
gravity += btVector3( rollingSpeed, 0, 0 );
}
// Update vertical rotation
else if( Input::keyPressed( Qt::Key_Up ) )
{
camera.rotate( rotationSpeed, QVector3D(1, 0, 0) );
camera.translate( 0, 0, 0.70f );
gravity -= btVector3( 0, 0, rollingSpeed );
}
else if( Input::keyPressed( Qt::Key_Down ) )
{
camera.rotate( -rotationSpeed, QVector3D(1, 0, 0) );
camera.translate( 0, 0, -0.70f );
gravity += btVector3( 0, 0, rollingSpeed );
}
// Update gravity
m_dynamicsWorld->setGravity( gravity );
}
/**
* @brief Helper function to print OpenGL Context information to the debug.
*/
void OGLWidget::printContextInfo()
{
QString glType;
QString glVersion;
QString glProfile;
// Get Version Information
glType = ( context()->isOpenGLES() ) ? "OpenGL ES" : "OpenGL";
glVersion = reinterpret_cast<const char*>( glGetString( GL_VERSION ) );
// Get Profile Information
switch( format().profile() )
{
case QSurfaceFormat::NoProfile:
glProfile = "No Profile";
break;
case QSurfaceFormat::CoreProfile:
glProfile = "Core Profile";
break;
case QSurfaceFormat::CompatibilityProfile:
glProfile = "Compatibility Profile";
break;
}
qDebug() << qPrintable( glType ) << qPrintable( glVersion ) <<
"(" << qPrintable( glProfile ) << ")";
}<commit_msg>Space to reset camera & gravity<commit_after>#include "oglWidget.h"
//
// CONSTRUCTORS ////////////////////////////////////////////////////////////////
//
/**
* @brief Default constructor for OGLWidget.
*/
OGLWidget::OGLWidget()
{
// Update the widget after a frameswap
connect( this, SIGNAL( frameSwapped() ),
this, SLOT( update() ) );
// Allows keyboard input to fall through
setFocusPolicy( Qt::ClickFocus );
camera.rotate( -90.0f, 1.0f, 0.0f, 0.0f );
camera.translate( 30.0f, 75.0f, 30.0f );
renderables["Labyrinth"] = new Labyrinth( Labyrinth::getRandomEnvironment(), time(NULL), 30, 30 );
std::pair<float, float> startingLocation = ((Labyrinth*)renderables["Labyrinth"])->getStartingLocation();
renderables["Ball"] = new Ball( startingLocation.first, 1.5f, startingLocation.second );
renderables["Ball2"] = new Ball( startingLocation.first+0.5, 1.5f, startingLocation.second+0.5f);
const btVector3 wallSize = btVector3(100, 50, 100);
const btVector3 location = btVector3(0, 52.5, 0 );
m_invisibleWall = new Wall( wallSize, location );
}
/**
* @brief Destructor class to unallocate OpenGL information.
*/
OGLWidget::~OGLWidget()
{
makeCurrent();
teardownGL();
teardownBullet();
}
//
// OPENGL FUNCTIONS ////////////////////////////////////////////////////////////
//
/**
* @brief Initializes any OpenGL operations.
*/
void OGLWidget::initializeGL()
{
// Init OpenGL Backend
initializeOpenGLFunctions();
printContextInfo();
initializeBullet();
for( QMap<QString, Renderable*>::iterator iter = renderables.begin();
iter != renderables.end(); iter++ )
{
(*iter)->initializeGL();
}
((Labyrinth*)renderables["Labyrinth"])->addRigidBodies( m_dynamicsWorld );
m_dynamicsWorld->addRigidBody( ((Ball*)renderables["Ball"])->RigidBody );
m_dynamicsWorld->addRigidBody( ((Ball*)renderables["Ball2"])->RigidBody );
m_dynamicsWorld->addRigidBody( m_invisibleWall->RigidBody );
}
/**
* @brief Sets the prespective whenever the window is resized.
*
* @param[in] width The width of the new window.
* @param[in] height The height of the new window.
*/
void OGLWidget::resizeGL( int width, int height )
{
projection.setToIdentity();
projection.perspective( 55.0f, // Field of view angle
float( width ) / float( height ), // Aspect Ratio
0.001f, // Near Plane (MUST BE GREATER THAN 0)
1500.0f ); // Far Plane
}
/**
* @brief OpenGL function to draw elements to the surface.
*/
void OGLWidget::paintGL()
{
// Set the default OpenGL states
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
glDepthMask( GL_TRUE );
glEnable( GL_CULL_FACE );
glClearColor( 0.0f, 0.0f, 0.2f, 1.0f );
// Clear the screen
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
for( QMap<QString, Renderable*>::iterator iter = renderables.begin();
iter != renderables.end(); iter++ )
{
(*iter)->paintGL( camera, projection );
}
// 2D Elements
QFont ConsolasFont( "Consolas", std::min( 35 * (QWidget::width() / 1855.0f), 35 * (QWidget::height() / 1056.0f)), QFont::Bold );
// Draw 2D Elements
QPainter painter(this);
QRect rect( 0, 10, QWidget::width(), QWidget::height() / 4 );
painter.beginNativePainting();
painter.setPen( QColor( 255, 255, 255, 255 ) );
painter.setFont( ConsolasFont );
painter.drawText( rect, Qt::AlignHCenter, QString::number( score ) );
painter.endNativePainting();
}
/**
* @brief Destroys any OpenGL data.
*/
void OGLWidget::teardownGL()
{
for( QMap<QString, Renderable*>::iterator iter = renderables.begin();
iter != renderables.end(); iter++ )
{
(*iter)->teardownGL();
}
}
//
// SLOTS ///////////////////////////////////////////////////////////////////////
//
/**
* @brief Updates any user interactions and model transformations.
*/
void OGLWidget::update()
{
float dt = updateTimer.deltaTime();
Input::update();
flyThroughCamera();
// Reset camera and gravity if space is pressed
if( Input::keyPressed( Qt::Key_Space ) )
{
camera.setRotation( -90.0f, 1.0f, 0.0f, 0.0f );
camera.setTranslation( 30.0f, 75.0f, 30.0f );
m_dynamicsWorld->setGravity( btVector3( 0, -9.8, 0 ) );
}
if( !isPaused )
{
controlBoard();
for( QMap<QString, Renderable*>::iterator iter = renderables.begin();
iter != renderables.end(); iter++ )
{
(*iter)->update();
}
score += dt * 100;
m_dynamicsWorld->stepSimulation( dt, 10 );
}
QOpenGLWidget::update();
}
/**
* @brief Public slot to invert the pause state of the game.
*/
void OGLWidget::pause()
{
isPaused = !isPaused;
}
//
// INPUT EVENTS ////////////////////////////////////////////////////////////////
//
/**
* @brief Default slot for handling key press events.
*
* @param event The key event information.
*/
void OGLWidget::keyPressEvent( QKeyEvent* event )
{
if( event->isAutoRepeat() )
event->ignore();
else
Input::registerKeyPress( event->key() );
}
/**
* @brief Default slot for handling key release events.
*
* @param event The key event information.
*/
void OGLWidget::keyReleaseEvent( QKeyEvent* event )
{
if( event->isAutoRepeat() )
event->ignore();
else
Input::registerKeyRelease( event->key() );
}
/**
* @brief Default slot for handling mouse press events.
*
* @param event The mouse event information.
*/
void OGLWidget::mousePressEvent( QMouseEvent* event )
{
Input::registerMousePress( event->button() );
}
/**
* @brief Default slot for handling mouse release events.
*
* @param event The mouse event information.
*/
void OGLWidget::mouseReleaseEvent( QMouseEvent* event )
{
Input::registerMouseRelease( event->button() );
}
//
// PRIVATE HELPER FUNCTIONS ////////////////////////////////////////////////////
//
/**
* @brief Helper function to initialize bullet data.
*/
void OGLWidget::initializeBullet()
{
m_broadphase = new btDbvtBroadphase();
m_collisionConfig = new btDefaultCollisionConfiguration();
m_dispatcher = new btCollisionDispatcher( m_collisionConfig );
m_solver = new btSequentialImpulseConstraintSolver();
m_dynamicsWorld = new btDiscreteDynamicsWorld( m_dispatcher, m_broadphase,
m_solver, m_collisionConfig );
m_dynamicsWorld->setGravity( btVector3( 0, -9.8, 0 ) );
}
/**
* @brief Helper function to delete bullet allocations.
*/
void OGLWidget::teardownBullet()
{
delete m_dynamicsWorld;
delete m_solver;
delete m_dispatcher;
delete m_collisionConfig;
delete m_broadphase;
}
/**
* @brief Updates the main camera to behave like a Fly-Through Camera.
*/
void OGLWidget::flyThroughCamera()
{
static const float cameraTranslationSpeed = 0.02f;
static const float cameraRotationSpeed = 0.1f;
if( Input::buttonPressed( Qt::RightButton ) )
{
// Rotate the camera based on mouse movement
camera.rotate( -cameraRotationSpeed * Input::mouseDelta().x(),
Camera3D::LocalUp );
camera.rotate( -cameraRotationSpeed * Input::mouseDelta().y(),
camera.right() );
}
// Translate the camera based on keyboard input
QVector3D cameraTranslations;
if( Input::keyPressed( Qt::Key_W ) )
cameraTranslations += camera.forward();
if( Input::keyPressed( Qt::Key_S ) )
cameraTranslations -= camera.forward();
if( Input::keyPressed( Qt::Key_A ) )
cameraTranslations -= camera.right();
if( Input::keyPressed( Qt::Key_D ) )
cameraTranslations += camera.right();
if( Input::keyPressed( Qt::Key_Q ) )
cameraTranslations -= camera.up();
if( Input::keyPressed( Qt::Key_E ) )
cameraTranslations += camera.up();
camera.translate( cameraTranslationSpeed * cameraTranslations );
}
/**
* @brief Updates board based on user input.
*/
void OGLWidget::controlBoard()
{
const float rotationSpeed = 0.7f;
const float rollingSpeed = 0.5f;
btVector3 gravity = m_dynamicsWorld->getGravity();
// Update horizontal rotation
if( Input::keyPressed( Qt::Key_Left ) )
{
camera.rotate( -rotationSpeed, QVector3D(0, 0, 1) );
camera.translate( 0.70f, 0, 0);
gravity -= btVector3( rollingSpeed, 0, 0 );
}
else if( Input::keyPressed( Qt::Key_Right ) )
{
camera.rotate( rotationSpeed, QVector3D(0, 0, 1) );
camera.translate( -0.70f, 0, 0);
gravity += btVector3( rollingSpeed, 0, 0 );
}
// Update vertical rotation
else if( Input::keyPressed( Qt::Key_Up ) )
{
camera.rotate( rotationSpeed, QVector3D(1, 0, 0) );
camera.translate( 0, 0, 0.70f );
gravity -= btVector3( 0, 0, rollingSpeed );
}
else if( Input::keyPressed( Qt::Key_Down ) )
{
camera.rotate( -rotationSpeed, QVector3D(1, 0, 0) );
camera.translate( 0, 0, -0.70f );
gravity += btVector3( 0, 0, rollingSpeed );
}
// Update gravity
m_dynamicsWorld->setGravity( gravity );
}
/**
* @brief Helper function to print OpenGL Context information to the debug.
*/
void OGLWidget::printContextInfo()
{
QString glType;
QString glVersion;
QString glProfile;
// Get Version Information
glType = ( context()->isOpenGLES() ) ? "OpenGL ES" : "OpenGL";
glVersion = reinterpret_cast<const char*>( glGetString( GL_VERSION ) );
// Get Profile Information
switch( format().profile() )
{
case QSurfaceFormat::NoProfile:
glProfile = "No Profile";
break;
case QSurfaceFormat::CoreProfile:
glProfile = "Core Profile";
break;
case QSurfaceFormat::CompatibilityProfile:
glProfile = "Compatibility Profile";
break;
}
qDebug() << qPrintable( glType ) << qPrintable( glVersion ) <<
"(" << qPrintable( glProfile ) << ")";
}<|endoftext|>
|
<commit_before>// The following block tests the following:
// - Only 1 file is generated per translation unit
// - Replacements are written in YAML that matches the expected YAML file
// The test is run in %T/SerializeTest so it's easy to create a clean test
// directory.
//
// RUN: rm -rf %T/SerializeTest
// RUN: mkdir -p %T/SerializeTest
// RUN: cp %S/main.cpp %S/common.cpp %S/common.h %T/SerializeTest
// RUN: clang-modernize -loop-convert -serialize-replacements -include=%T/SerializeTest %T/SerializeTest/main.cpp %T/SerializeTest/common.cpp --
// Check that only 1 file is generated per translation unit
// RUN: ls -1 %T/SerializeTest | FileCheck %s --check-prefix=MAIN_CPP
// RUN: ls -1 %T/SerializeTest | FileCheck %s --check-prefix=COMMON_CPP
// We need to put the build path to the expected YAML file to diff against the generated one.
// RUN: sed -e 's#$(path)#%/T/SerializeTest#g' %S/main_expected.yaml > %T/SerializeTest/main_expected.yaml
// RUN: sed -i -e 's#\\#/#g' %T/SerializeTest/main.cpp_*.yaml
// RUN: diff -b %T/SerializeTest/main_expected.yaml %T/SerializeTest/main.cpp_*.yaml
// RUN: sed -e 's#$(path)#%/T/SerializeTest#g' %S/common_expected.yaml > %T/SerializeTest/common_expected.yaml
// RUN: sed -i -e 's#\\#/#g' %T/SerializeTest/common.cpp_*.yaml
// RUN: diff -b %T/SerializeTest/common_expected.yaml %T/SerializeTest/common.cpp_*.yaml
//
// The following are for FileCheck when used on output of 'ls'. See above.
// MAIN_CPP: {{^main.cpp_.*.yaml$}}
// MAIN_CPP-NOT: {{main.cpp_.*.yaml}}
//
// COMMON_CPP: {{^common.cpp_.*.yaml$}}
// COMMON_CPP-NOT: {{common.cpp_.*.yaml}}
#include "common.h"
void test_header_replacement() {
dostuff();
func2();
}
<commit_msg>clang-tools-extra/test/clang-modernize/HeaderReplacements/main.cpp: Tweak sed(1) to let paths with a driveletter quoted in *_expected.yaml.<commit_after>// The following block tests the following:
// - Only 1 file is generated per translation unit
// - Replacements are written in YAML that matches the expected YAML file
// The test is run in %T/SerializeTest so it's easy to create a clean test
// directory.
//
// RUN: rm -rf %T/SerializeTest
// RUN: mkdir -p %T/SerializeTest
// RUN: cp %S/main.cpp %S/common.cpp %S/common.h %T/SerializeTest
// RUN: clang-modernize -loop-convert -serialize-replacements -include=%T/SerializeTest %T/SerializeTest/main.cpp %T/SerializeTest/common.cpp --
// Check that only 1 file is generated per translation unit
// RUN: ls -1 %T/SerializeTest | FileCheck %s --check-prefix=MAIN_CPP
// RUN: ls -1 %T/SerializeTest | FileCheck %s --check-prefix=COMMON_CPP
// We need to put the build path to the expected YAML file to diff against the generated one.
// RUN: sed -e 's#$(path)#%/T/SerializeTest#g' -e "s#\([A-Z]:/.*\.[chp]*\)#'\1'#g" %S/main_expected.yaml > %T/SerializeTest/main_expected.yaml
// RUN: sed -i -e 's#\\#/#g' %T/SerializeTest/main.cpp_*.yaml
// RUN: diff -b %T/SerializeTest/main_expected.yaml %T/SerializeTest/main.cpp_*.yaml
// RUN: sed -e 's#$(path)#%/T/SerializeTest#g' -e "s#\([A-Z]:/.*\.[chp]*\)#'\1'#g" %S/common_expected.yaml > %T/SerializeTest/common_expected.yaml
// RUN: sed -i -e 's#\\#/#g' %T/SerializeTest/common.cpp_*.yaml
// RUN: diff -b %T/SerializeTest/common_expected.yaml %T/SerializeTest/common.cpp_*.yaml
//
// The following are for FileCheck when used on output of 'ls'. See above.
// MAIN_CPP: {{^main.cpp_.*.yaml$}}
// MAIN_CPP-NOT: {{main.cpp_.*.yaml}}
//
// COMMON_CPP: {{^common.cpp_.*.yaml$}}
// COMMON_CPP-NOT: {{common.cpp_.*.yaml}}
#include "common.h"
void test_header_replacement() {
dostuff();
func2();
}
<|endoftext|>
|
<commit_before>//#include "OpenCLHelper.h"
//#include "ClConvolve.h"
#include <iostream>
using namespace std;
#include "BoardHelper.h"
#include "MnistLoader.h"
#include "BoardPng.h"
#include "Timer.h"
#include "NeuralNet.h"
#include "test/AccuracyHelper.h"
#include "stringhelper.h"
#include "FileHelper.h"
void loadMnist( string mnistDir, string setName, int *p_N, int *p_boardSize, float ****p_images, int **p_labels, float **p_expectedOutputs ) {
int boardSize;
int Nboards;
int Nlabels;
// images
int ***boards = MnistLoader::loadImages( mnistDir, setName, &Nboards, &boardSize );
int *labels = MnistLoader::loadLabels( mnistDir, setName, &Nlabels );
if( Nboards != Nlabels ) {
throw runtime_error("mismatch between number of boards, and number of labels " + toString(Nboards ) + " vs " +
toString(Nlabels ) );
}
cout << "loaded " << Nboards << " boards. " << endl;
// MnistLoader::shuffle( boards, labels, Nboards, boardSize );
float ***boardsFloat = BoardsHelper::allocateBoardsFloats( Nboards, boardSize + 1 );
BoardsHelper::copyBoards( boardsFloat, boards, Nboards, boardSize );
BoardsHelper::deleteBoards( &boards, Nboards, boardSize );
*p_images = boardsFloat;
*p_labels = labels;
*p_boardSize = boardSize + 1;
*p_N = Nboards;
// expected results
*p_expectedOutputs = new float[10 * Nboards];
for( int n = 0; n < Nlabels; n++ ) {
int thislabel = labels[n];
for( int i = 0; i < 10; i++ ) {
(*p_expectedOutputs)[n*10+i] = -0.5;
}
(*p_expectedOutputs)[n*10+thislabel] = +0.5;
}
}
void getStats( float ***boards, int N, int boardSize, float *p_mean, float *p_thismax ) {
// get mean of the dataset
int count = 0;
float thismax = 0;
float sum = 0;
for( int n = 0; n < N; n++ ) {
for( int i = 0; i < boardSize; i++ ) {
for( int j = 0; j < boardSize; j++ ) {
count++;
sum += boards[n][i][j];
thismax = max( thismax, boards[n][i][j] );
}
}
}
*p_mean = sum / count;
*p_thismax = thismax;
}
void normalize( float ***boards, int N, int boardSize, double mean, double thismax ) {
for( int n = 0; n < N; n++ ) {
for( int i = 0; i < boardSize; i++ ) {
for( int j = 0; j < boardSize; j++ ) {
boards[n][i][j] = boards[n][i][j] / thismax - 0.1;
}
}
}
}
class Config {
public:
string dataDir = "../data/mnist";
string trainSet = "train";
string testSet = "t10k";
int numTrain = 12800 * 4;
int numTest = 1280*4;
int batchSize = 128;
int numEpochs = 20;
float learningRate = 0.1f;
int biased = 1;
Config() {
}
};
void printAccuracy( string name, NeuralNet *net, float ***boards, int *labels, int batchSize, int N ) {
int testNumRight = 0;
for( int batch = 0; batch < N / batchSize; batch++ ) {
int batchStart = batch * batchSize;
net->propagate( &(boards[batchStart][0][0]) );
float const*results = net->getResults();
int thisnumright = AccuracyHelper::calcNumRight( batchSize, 10, &(labels[batchStart]), results );
// cout << name << " batch " << batch << ": numright " << thisnumright << "/" << batchSize << endl;
testNumRight += thisnumright;
}
// cout << "boards interval: " << ( &(boards[1][0][0]) - &(boards[0][0][0])) << endl;
// cout << "labels interval: " << ( &(labels[1]) - &(labels[0])) << endl;
cout << name << " overall: " << testNumRight << "/" << N << " " << ( testNumRight * 100.0f / N ) << "%" << endl;
}
void go(Config config) {
Timer timer;
int boardSize;
float ***boardsFloat = 0;
int *labels = 0;
float *expectedOutputs = 0;
float ***boardsTest = 0;
int *labelsTest = 0;
float *expectedOutputsTest = 0;
{
int N;
loadMnist( config.dataDir, config.trainSet, &N, &boardSize, &boardsFloat, &labels, &expectedOutputs );
int Ntest;
loadMnist( config.dataDir, config.testSet, &Ntest, &boardSize, &boardsTest, &labelsTest, &expectedOutputsTest );
}
float mean;
float thismax;
// getStats( boardsFloat, config.numTrain, boardSize, &mean, &thismax );
mean = 33;
thismax = 255;
cout << " board stats mean " << mean << " max " << thismax << " boardSize " << boardSize << endl;
normalize( boardsFloat, config.numTrain, boardSize, mean, thismax );
normalize( boardsTest, config.numTest, boardSize, mean, thismax );
timer.timeCheck("after load images");
int numToTrain = config.numTrain;
const int batchSize = config.batchSize;
NeuralNet *net = NeuralNet::maker()->planes(1)->boardSize(boardSize)->instance();
net->convolutionalMaker()->numFilters(14)->filterSize(5)->tanh()->biased()->insert();
net->convolutionalMaker()->numFilters(10)->filterSize(boardSize-4)->tanh()->biased(config.biased)->insert();
// if( FileHelper::exists("weights.dat" ) ){
// int fileSize;
// unsigned char * data = FileHelper::readBinary( "weights.dat", &fileSize );
// cout << "read data from file " << fileSize << " bytes" << endl;
// for( int i = 0; i < net->layers[1]->getWeightsSize(); i++ ) {
// net->layers[1]->weights[i] = reinterpret_cast<float *>(data)[i];
// }
// delete [] data;
// data = FileHelper::readBinary( "biasweights.dat", &fileSize );
// cout << "read data from file " << fileSize << " bytes" << endl;
// for( int i = 0; i < net->layers[1]->getBiasWeightsSize(); i++ ) {
// dynamic_cast<ConvolutionalLayer*>(net->layers[1])->biasWeights[i] = reinterpret_cast<float *>(data)[i];
// }
// }
// net->setBatchSize(batchSize);
// net->print();
for( int epoch = 0; epoch < config.numEpochs; epoch++ ) {
float loss = net->epochMaker()
->learningRate(config.learningRate)
->batchSize(batchSize)
->numExamples(numToTrain)
->inputData(&(boardsFloat[0][0][0]))
->expectedOutputs(expectedOutputs)
->run();
cout << " loss L: " << loss << endl;
int trainNumRight = 0;
timer.timeCheck("after epoch");
// net->print();
printAccuracy( "train", net, boardsFloat, labels, batchSize, config.numTrain );
printAccuracy( "test", net, boardsTest, labelsTest, batchSize, config.numTest );
timer.timeCheck("after tests");
}
//float const*results = net->getResults( net->getNumLayers() - 1 );
printAccuracy( "test", net, boardsTest, labelsTest, batchSize, config.numTest );
// printAccuracy( "train", net, boardsFloat, labels, batchSize, config.numTrain );
timer.timeCheck("after tests");
int numBatches = config.numTest / config.batchSize;
int totalNumber = 0;
int totalNumRight = 0;
for( int batch = 0; batch < numBatches; batch++ ) {
int batchStart = batch * config.batchSize;
net->propagate( &(boardsTest[batchStart][0][0]) );
float const*resultsTest = net->getResults();
totalNumber += config.batchSize;
totalNumRight += AccuracyHelper::calcNumRight( config.batchSize, 10, &(labelsTest[batchStart]), resultsTest );
}
cout << "test accuracy : " << totalNumRight << "/" << totalNumber << endl;
// if( config.numEpochs >= 10 ) {
// FileHelper::writeBinary( "weights.dat", reinterpret_cast<unsigned char *>(net->layers[1]->weights),
// net->layers[1]->getWeightsSize() * sizeof(float) );
// cout << "wrote weights to file " << endl;
// FileHelper::writeBinary( "biasweights.dat", reinterpret_cast<unsigned char *>(dynamic_cast<ConvolutionalLayer*>(net->layers[1])->biasWeights),
// dynamic_cast<ConvolutionalLayer*>(net->layers[1])->getBiasWeightsSize() * sizeof(float) );
// }
delete net;
delete[] expectedOutputsTest;
delete[] labelsTest;
// BoardsHelper::deleteBoards( &boardsTest, Ntest, boardSize );
delete[] expectedOutputs;
delete[] labels;
// BoardsHelper::deleteBoards( &boardsFloat, N, boardSize );
}
int main( int argc, char *argv[] ) {
Config config;
if( argc == 2 && ( string(argv[1]) == "--help" || string(argv[1]) == "--?" || string(argv[1]) == "-?" || string(argv[1]) == "-h" ) ) {
cout << "Usage: " << argv[0] << " [key]=[value] [[key]=[value]] ..." << endl;
cout << "Possible key=value pairs:" << endl;
cout << " datadir=[data directory] (" << config.dataDir << ")" << endl;
cout << " trainset=[train|t10k|other set name] (" << config.trainSet << ")" << endl;
cout << " testset=[train|t10k|other set name] (" << config.testSet << ")" << endl;
cout << " numtrain=[num training examples] (" << config.numTrain << ")" << endl;
cout << " numtest=[num test examples] (" << config.numTest << ")" << endl;
cout << " batchsize=[batch size] (" << config.batchSize << ")" << endl;
cout << " numepochs=[number epochs] (" << config.numEpochs << ")" << endl;
cout << " biased=[0|1] (" << config.biased << ")" << endl;
cout << " learningrate=[learning rate, a float value] (" << config.learningRate << ")" << endl;
}
for( int i = 1; i < argc; i++ ) {
vector<string> splitkeyval = split( argv[i], "=" );
if( splitkeyval.size() != 2 ) {
cout << "Usage: " << argv[0] << " [key]=[value] [[key]=[value]] ..." << endl;
exit(1);
} else {
string key = splitkeyval[0];
string value = splitkeyval[1];
if( key == "datadir" ) config.dataDir = value;
if( key == "trainset" ) config.trainSet = value;
if( key == "testset" ) config.testSet = value;
if( key == "numtrain" ) config.numTrain = atoi(value);
if( key == "numtest" ) config.numTest = atoi(value);
if( key == "batchsize" ) config.batchSize = atoi(value);
if( key == "numepochs" ) config.numEpochs = atoi(value);
if( key == "biased" ) config.biased = atoi(value);
if( key == "learningrate" ) config.learningRate = atof(value);
}
}
go( config );
}
<commit_msg>change boardsize for experimental mnist<commit_after>//#include "OpenCLHelper.h"
//#include "ClConvolve.h"
#include <iostream>
using namespace std;
#include "BoardHelper.h"
#include "MnistLoader.h"
#include "BoardPng.h"
#include "Timer.h"
#include "NeuralNet.h"
#include "test/AccuracyHelper.h"
#include "stringhelper.h"
#include "FileHelper.h"
void loadMnist( string mnistDir, string setName, int *p_N, int *p_boardSize, float ****p_images, int **p_labels, float **p_expectedOutputs ) {
int boardSize;
int Nboards;
int Nlabels;
// images
int ***boards = MnistLoader::loadImages( mnistDir, setName, &Nboards, &boardSize );
int *labels = MnistLoader::loadLabels( mnistDir, setName, &Nlabels );
if( Nboards != Nlabels ) {
throw runtime_error("mismatch between number of boards, and number of labels " + toString(Nboards ) + " vs " +
toString(Nlabels ) );
}
cout << "loaded " << Nboards << " boards. " << endl;
// MnistLoader::shuffle( boards, labels, Nboards, boardSize );
float ***boardsFloat = BoardsHelper::allocateBoardsFloats( Nboards, boardSize );
BoardsHelper::copyBoards( boardsFloat, boards, Nboards, boardSize );
BoardsHelper::deleteBoards( &boards, Nboards, boardSize );
*p_images = boardsFloat;
*p_labels = labels;
*p_boardSize = boardSize;
*p_N = Nboards;
// expected results
*p_expectedOutputs = new float[10 * Nboards];
for( int n = 0; n < Nlabels; n++ ) {
int thislabel = labels[n];
for( int i = 0; i < 10; i++ ) {
(*p_expectedOutputs)[n*10+i] = -0.5;
}
(*p_expectedOutputs)[n*10+thislabel] = +0.5;
}
}
void getStats( float ***boards, int N, int boardSize, float *p_mean, float *p_thismax ) {
// get mean of the dataset
int count = 0;
float thismax = 0;
float sum = 0;
for( int n = 0; n < N; n++ ) {
for( int i = 0; i < boardSize; i++ ) {
for( int j = 0; j < boardSize; j++ ) {
count++;
sum += boards[n][i][j];
thismax = max( thismax, boards[n][i][j] );
}
}
}
*p_mean = sum / count;
*p_thismax = thismax;
}
void normalize( float ***boards, int N, int boardSize, double mean, double thismax ) {
for( int n = 0; n < N; n++ ) {
for( int i = 0; i < boardSize; i++ ) {
for( int j = 0; j < boardSize; j++ ) {
boards[n][i][j] = boards[n][i][j] / thismax - 0.1;
}
}
}
}
class Config {
public:
string dataDir = "../data/mnist";
string trainSet = "train";
string testSet = "t10k";
int numTrain = 12800 * 4;
int numTest = 1280*4;
int batchSize = 128;
int numEpochs = 20;
float learningRate = 0.1f;
int biased = 1;
Config() {
}
};
void printAccuracy( string name, NeuralNet *net, float ***boards, int *labels, int batchSize, int N ) {
int testNumRight = 0;
for( int batch = 0; batch < N / batchSize; batch++ ) {
int batchStart = batch * batchSize;
net->propagate( &(boards[batchStart][0][0]) );
float const*results = net->getResults();
int thisnumright = AccuracyHelper::calcNumRight( batchSize, 10, &(labels[batchStart]), results );
// cout << name << " batch " << batch << ": numright " << thisnumright << "/" << batchSize << endl;
testNumRight += thisnumright;
}
// cout << "boards interval: " << ( &(boards[1][0][0]) - &(boards[0][0][0])) << endl;
// cout << "labels interval: " << ( &(labels[1]) - &(labels[0])) << endl;
cout << name << " overall: " << testNumRight << "/" << N << " " << ( testNumRight * 100.0f / N ) << "%" << endl;
}
void go(Config config) {
Timer timer;
int boardSize;
float ***boardsFloat = 0;
int *labels = 0;
float *expectedOutputs = 0;
float ***boardsTest = 0;
int *labelsTest = 0;
float *expectedOutputsTest = 0;
{
int N;
loadMnist( config.dataDir, config.trainSet, &N, &boardSize, &boardsFloat, &labels, &expectedOutputs );
int Ntest;
loadMnist( config.dataDir, config.testSet, &Ntest, &boardSize, &boardsTest, &labelsTest, &expectedOutputsTest );
}
float mean;
float thismax;
// getStats( boardsFloat, config.numTrain, boardSize, &mean, &thismax );
mean = 33;
thismax = 255;
cout << " board stats mean " << mean << " max " << thismax << " boardSize " << boardSize << endl;
normalize( boardsFloat, config.numTrain, boardSize, mean, thismax );
normalize( boardsTest, config.numTest, boardSize, mean, thismax );
timer.timeCheck("after load images");
int numToTrain = config.numTrain;
const int batchSize = config.batchSize;
NeuralNet *net = NeuralNet::maker()->planes(1)->boardSize(boardSize)->instance();
net->convolutionalMaker()->numFilters(14)->filterSize(5)->tanh()->biased()->insert();
net->convolutionalMaker()->numFilters(10)->filterSize(boardSize-4)->tanh()->biased(config.biased)->insert();
// if( FileHelper::exists("weights.dat" ) ){
// int fileSize;
// unsigned char * data = FileHelper::readBinary( "weights.dat", &fileSize );
// cout << "read data from file " << fileSize << " bytes" << endl;
// for( int i = 0; i < net->layers[1]->getWeightsSize(); i++ ) {
// net->layers[1]->weights[i] = reinterpret_cast<float *>(data)[i];
// }
// delete [] data;
// data = FileHelper::readBinary( "biasweights.dat", &fileSize );
// cout << "read data from file " << fileSize << " bytes" << endl;
// for( int i = 0; i < net->layers[1]->getBiasWeightsSize(); i++ ) {
// dynamic_cast<ConvolutionalLayer*>(net->layers[1])->biasWeights[i] = reinterpret_cast<float *>(data)[i];
// }
// }
// net->setBatchSize(batchSize);
// net->print();
for( int epoch = 0; epoch < config.numEpochs; epoch++ ) {
float loss = net->epochMaker()
->learningRate(config.learningRate)
->batchSize(batchSize)
->numExamples(numToTrain)
->inputData(&(boardsFloat[0][0][0]))
->expectedOutputs(expectedOutputs)
->run();
cout << " loss L: " << loss << endl;
int trainNumRight = 0;
timer.timeCheck("after epoch");
// net->print();
printAccuracy( "train", net, boardsFloat, labels, batchSize, config.numTrain );
printAccuracy( "test", net, boardsTest, labelsTest, batchSize, config.numTest );
timer.timeCheck("after tests");
}
//float const*results = net->getResults( net->getNumLayers() - 1 );
printAccuracy( "test", net, boardsTest, labelsTest, batchSize, config.numTest );
// printAccuracy( "train", net, boardsFloat, labels, batchSize, config.numTrain );
timer.timeCheck("after tests");
int numBatches = config.numTest / config.batchSize;
int totalNumber = 0;
int totalNumRight = 0;
for( int batch = 0; batch < numBatches; batch++ ) {
int batchStart = batch * config.batchSize;
net->propagate( &(boardsTest[batchStart][0][0]) );
float const*resultsTest = net->getResults();
totalNumber += config.batchSize;
totalNumRight += AccuracyHelper::calcNumRight( config.batchSize, 10, &(labelsTest[batchStart]), resultsTest );
}
cout << "test accuracy : " << totalNumRight << "/" << totalNumber << endl;
// if( config.numEpochs >= 10 ) {
// FileHelper::writeBinary( "weights.dat", reinterpret_cast<unsigned char *>(net->layers[1]->weights),
// net->layers[1]->getWeightsSize() * sizeof(float) );
// cout << "wrote weights to file " << endl;
// FileHelper::writeBinary( "biasweights.dat", reinterpret_cast<unsigned char *>(dynamic_cast<ConvolutionalLayer*>(net->layers[1])->biasWeights),
// dynamic_cast<ConvolutionalLayer*>(net->layers[1])->getBiasWeightsSize() * sizeof(float) );
// }
delete net;
delete[] expectedOutputsTest;
delete[] labelsTest;
// BoardsHelper::deleteBoards( &boardsTest, Ntest, boardSize );
delete[] expectedOutputs;
delete[] labels;
// BoardsHelper::deleteBoards( &boardsFloat, N, boardSize );
}
int main( int argc, char *argv[] ) {
Config config;
if( argc == 2 && ( string(argv[1]) == "--help" || string(argv[1]) == "--?" || string(argv[1]) == "-?" || string(argv[1]) == "-h" ) ) {
cout << "Usage: " << argv[0] << " [key]=[value] [[key]=[value]] ..." << endl;
cout << "Possible key=value pairs:" << endl;
cout << " datadir=[data directory] (" << config.dataDir << ")" << endl;
cout << " trainset=[train|t10k|other set name] (" << config.trainSet << ")" << endl;
cout << " testset=[train|t10k|other set name] (" << config.testSet << ")" << endl;
cout << " numtrain=[num training examples] (" << config.numTrain << ")" << endl;
cout << " numtest=[num test examples] (" << config.numTest << ")" << endl;
cout << " batchsize=[batch size] (" << config.batchSize << ")" << endl;
cout << " numepochs=[number epochs] (" << config.numEpochs << ")" << endl;
cout << " biased=[0|1] (" << config.biased << ")" << endl;
cout << " learningrate=[learning rate, a float value] (" << config.learningRate << ")" << endl;
}
for( int i = 1; i < argc; i++ ) {
vector<string> splitkeyval = split( argv[i], "=" );
if( splitkeyval.size() != 2 ) {
cout << "Usage: " << argv[0] << " [key]=[value] [[key]=[value]] ..." << endl;
exit(1);
} else {
string key = splitkeyval[0];
string value = splitkeyval[1];
if( key == "datadir" ) config.dataDir = value;
if( key == "trainset" ) config.trainSet = value;
if( key == "testset" ) config.testSet = value;
if( key == "numtrain" ) config.numTrain = atoi(value);
if( key == "numtest" ) config.numTest = atoi(value);
if( key == "batchsize" ) config.batchSize = atoi(value);
if( key == "numepochs" ) config.numEpochs = atoi(value);
if( key == "biased" ) config.biased = atoi(value);
if( key == "learningrate" ) config.learningRate = atof(value);
}
}
go( config );
}
<|endoftext|>
|
<commit_before>#include <ctype.h>
#include "vtkUnsignedCharScalars.h"
#include "vtkUnsignedShortScalars.h"
#include "vtkSLCReader.h"
// Description:
// Constructor for a vtkSLCReader.
vtkSLCReader::vtkSLCReader()
{
this->FileName = NULL;
}
// Description:
// Decodes an array of eight bit run-length encoded data.
unsigned char* vtkSLCReader::Decode_8bit_data( unsigned char *in_ptr,
int size )
{
unsigned char *curr_ptr;
unsigned char *decode_ptr;
unsigned char *return_ptr;
unsigned char current_value;
unsigned char remaining;
curr_ptr = in_ptr;
decode_ptr = return_ptr = new unsigned char[size];
while( 1 )
{
current_value = *(curr_ptr++);
if( !(remaining = (current_value & 0x7f)) )
break;
if( current_value & 0x80 )
{
while( remaining-- )
*(decode_ptr++) = *(curr_ptr++);
}
else
{
current_value = *(curr_ptr++);
while ( remaining-- )
*(decode_ptr++) = current_value;
}
}
return return_ptr;
}
// Description:
// Reads an SLC file and creates a vtkStructuredPoints dataset.
void vtkSLCReader::Execute()
{
FILE *fp;
vtkUnsignedCharScalars *newScalars;
// vtkUnsignedShortScalars *newScalars;
int temp;
int data_compression;
int plane_size;
int volume_size;
float f[3];
int size[3];
int magic_num;
int z_counter;
int icon_width, icon_height;
int voxel_count;
int compressed_size;
int i;
unsigned char *icon_ptr = NULL;
unsigned char *compressed_ptr = NULL;
unsigned char *scan_ptr = NULL;
unsigned char *sptr = NULL;
vtkStructuredPoints *output=(vtkStructuredPoints *)this->Output;
// Initialize
if ((fp = fopen(this->FileName, "r")) == NULL)
{
vtkErrorMacro(<< "File " << this->FileName << " not found");
return;
}
fscanf( fp, "%d", &magic_num );
if( magic_num != 11111 )
{
vtkErrorMacro(<< "SLC magic number is not correct");
return;
}
f[0] = f[1] = f[2] = 0.0;
output->SetOrigin(f);
fscanf( fp, "%d", size );
fscanf( fp, "%d", size+1 );
fscanf( fp, "%d", size+2 );
output->SetDimensions(size);
// Skip Over bits_per_voxel Field */
fscanf( fp, "%d", &temp );
fscanf( fp, "%f", f );
fscanf( fp, "%f", f+1 );
fscanf( fp, "%f", f+2 );
output->SetSpacing(f);
// Skip Over unit_type, data_origin, and data_modification
fscanf( fp, "%d", &temp );
fscanf( fp, "%d", &temp );
fscanf( fp, "%d", &temp );
fscanf( fp, "%d\n", &data_compression );
plane_size = size[0] * size[1];
volume_size = plane_size * size[2];
newScalars = vtkUnsignedCharScalars::New();
newScalars->SetNumberOfScalars(volume_size);
// Skip Over Icon
fscanf( fp, "%d %d X", &icon_width, &icon_height );
icon_ptr = new unsigned char[(icon_width*icon_height)];
fread( icon_ptr, 1, (icon_width*icon_height), fp );
fread( icon_ptr, 1, (icon_width*icon_height), fp );
fread( icon_ptr, 1, (icon_width*icon_height), fp );
delete icon_ptr;
voxel_count = 0;
// Read In Data Plane By Plane
for( z_counter=0; z_counter<size[2]; z_counter++ )
{
// Read a single plane into temp memory
switch( data_compression )
{
case 0:
if( !scan_ptr )
scan_ptr = new unsigned char[plane_size];
if( fread( scan_ptr, 1, plane_size, fp ) != plane_size )
{
vtkErrorMacro( <<
"Unable to read slice " << z_counter << " from SLC File" );
return;
}
break;
case 1:
if( scan_ptr )
delete scan_ptr;
fscanf( fp, "%d X", &compressed_size );
compressed_ptr = new unsigned char[compressed_size];
if( fread(compressed_ptr, 1, compressed_size, fp) != compressed_size )
{
vtkErrorMacro( << "Unable to read compressed slice " <<
z_counter << " from SLC File" );
return;
}
scan_ptr = Decode_8bit_data( compressed_ptr, plane_size );
delete compressed_ptr;
break;
default:
vtkErrorMacro(<< "Unknown SLC compression type: " <<
data_compression );
break;
}
sptr = scan_ptr;
// Copy plane into volume
for( i=0; i<plane_size; i++ )
{
newScalars->SetScalar( (z_counter*plane_size + i), *sptr++ );
// newScalars->SetScalar( (z_counter*plane_size + i), (unsigned short)(*sptr++) );
}
}
delete scan_ptr;
vtkDebugMacro(<< "Read " << volume_size << " points");
if( newScalars )
{
output->GetPointData()->SetScalars(newScalars);
newScalars->Delete();
}
fclose( fp );
}
void vtkSLCReader::PrintSelf(ostream& os, vtkIndent indent)
{
vtkStructuredPointsSource::PrintSelf(os,indent);
os << indent << "File Name: "
<< (this->FileName ? this->FileName : "(none)") << "\n";
}
<commit_msg>Added binary mode to fopen()<commit_after>#include <ctype.h>
#include "vtkUnsignedCharScalars.h"
#include "vtkUnsignedShortScalars.h"
#include "vtkSLCReader.h"
// Description:
// Constructor for a vtkSLCReader.
vtkSLCReader::vtkSLCReader()
{
this->FileName = NULL;
}
// Description:
// Decodes an array of eight bit run-length encoded data.
unsigned char* vtkSLCReader::Decode_8bit_data( unsigned char *in_ptr,
int size )
{
unsigned char *curr_ptr;
unsigned char *decode_ptr;
unsigned char *return_ptr;
unsigned char current_value;
unsigned char remaining;
curr_ptr = in_ptr;
decode_ptr = return_ptr = new unsigned char[size];
while( 1 )
{
current_value = *(curr_ptr++);
if( !(remaining = (current_value & 0x7f)) )
break;
if( current_value & 0x80 )
{
while( remaining-- )
*(decode_ptr++) = *(curr_ptr++);
}
else
{
current_value = *(curr_ptr++);
while ( remaining-- )
*(decode_ptr++) = current_value;
}
}
return return_ptr;
}
// Description:
// Reads an SLC file and creates a vtkStructuredPoints dataset.
void vtkSLCReader::Execute()
{
FILE *fp;
vtkUnsignedCharScalars *newScalars;
// vtkUnsignedShortScalars *newScalars;
int temp;
int data_compression;
int plane_size;
int volume_size;
float f[3];
int size[3];
int magic_num;
int z_counter;
int icon_width, icon_height;
int voxel_count;
int compressed_size;
int i;
unsigned char *icon_ptr = NULL;
unsigned char *compressed_ptr = NULL;
unsigned char *scan_ptr = NULL;
unsigned char *sptr = NULL;
vtkStructuredPoints *output=(vtkStructuredPoints *)this->Output;
// Initialize
if ((fp = fopen(this->FileName, "rb")) == NULL)
{
vtkErrorMacro(<< "File " << this->FileName << " not found");
return;
}
fscanf( fp, "%d", &magic_num );
if( magic_num != 11111 )
{
vtkErrorMacro(<< "SLC magic number is not correct");
return;
}
f[0] = f[1] = f[2] = 0.0;
output->SetOrigin(f);
fscanf( fp, "%d", size );
fscanf( fp, "%d", size+1 );
fscanf( fp, "%d", size+2 );
output->SetDimensions(size);
// Skip Over bits_per_voxel Field */
fscanf( fp, "%d", &temp );
fscanf( fp, "%f", f );
fscanf( fp, "%f", f+1 );
fscanf( fp, "%f", f+2 );
output->SetSpacing(f);
// Skip Over unit_type, data_origin, and data_modification
fscanf( fp, "%d", &temp );
fscanf( fp, "%d", &temp );
fscanf( fp, "%d", &temp );
fscanf( fp, "%d\n", &data_compression );
plane_size = size[0] * size[1];
volume_size = plane_size * size[2];
newScalars = vtkUnsignedCharScalars::New();
newScalars->SetNumberOfScalars(volume_size);
// Skip Over Icon
fscanf( fp, "%d %d X", &icon_width, &icon_height );
icon_ptr = new unsigned char[(icon_width*icon_height)];
fread( icon_ptr, 1, (icon_width*icon_height), fp );
fread( icon_ptr, 1, (icon_width*icon_height), fp );
fread( icon_ptr, 1, (icon_width*icon_height), fp );
delete icon_ptr;
voxel_count = 0;
// Read In Data Plane By Plane
for( z_counter=0; z_counter<size[2]; z_counter++ )
{
// Read a single plane into temp memory
switch( data_compression )
{
case 0:
if( !scan_ptr )
scan_ptr = new unsigned char[plane_size];
if( fread( scan_ptr, 1, plane_size, fp ) != plane_size )
{
vtkErrorMacro( <<
"Unable to read slice " << z_counter << " from SLC File" );
return;
}
break;
case 1:
if( scan_ptr )
delete scan_ptr;
fscanf( fp, "%d X", &compressed_size );
compressed_ptr = new unsigned char[compressed_size];
if( fread(compressed_ptr, 1, compressed_size, fp) != compressed_size )
{
vtkErrorMacro( << "Unable to read compressed slice " <<
z_counter << " from SLC File" );
return;
}
scan_ptr = Decode_8bit_data( compressed_ptr, plane_size );
delete compressed_ptr;
break;
default:
vtkErrorMacro(<< "Unknown SLC compression type: " <<
data_compression );
break;
}
sptr = scan_ptr;
// Copy plane into volume
for( i=0; i<plane_size; i++ )
{
newScalars->SetScalar( (z_counter*plane_size + i), *sptr++ );
// newScalars->SetScalar( (z_counter*plane_size + i), (unsigned short)(*sptr++) );
}
}
delete scan_ptr;
vtkDebugMacro(<< "Read " << volume_size << " points");
if( newScalars )
{
output->GetPointData()->SetScalars(newScalars);
newScalars->Delete();
}
fclose( fp );
}
void vtkSLCReader::PrintSelf(ostream& os, vtkIndent indent)
{
vtkStructuredPointsSource::PrintSelf(os,indent);
os << indent << "File Name: "
<< (this->FileName ? this->FileName : "(none)") << "\n";
}
<|endoftext|>
|
<commit_before>//
// Created by ganyush on 4/23/21.
//
/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*/
#include <cstdint>
#include <cstring>
#include <limits>
#include <stdexcept>
#include <adios2.h>
#include <adios2/common/ADIOSTypes.h>
#include <gtest/gtest.h>
class ADIOSInquireDefineTest : public ::testing::Test
{
public:
ADIOSInquireDefineTest() = default;
};
TEST_F(ADIOSInquireDefineTest, Read)
{
std::string filename = "ADIOSInquireDefine.bp";
// Number of steps
const std::size_t NSteps = 5;
int mpiRank = 0, mpiSize = 1;
#if ADIOS2_USE_MPI
MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank);
MPI_Comm_size(MPI_COMM_WORLD, &mpiSize);
#endif
// Write test data using BP
{
#if ADIOS2_USE_MPI
adios2::ADIOS adios(MPI_COMM_WORLD);
#else
adios2::ADIOS adios;
#endif
adios2::IO ioWrite = adios.DeclareIO("TestIOWrite");
adios2::Engine engine = ioWrite.Open(filename, adios2::Mode::Write);
// Number of elements per process
const std::size_t Nx = 10;
adios2::Dims shape{static_cast<unsigned int>(mpiSize * Nx)};
adios2::Dims start{static_cast<unsigned int>(mpiRank * Nx)};
adios2::Dims count{static_cast<unsigned int>(Nx)};
std::vector<int32_t> Ints0 = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
std::vector<int32_t> Ints1 = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
std::vector<int32_t> Ints2 = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2};
std::vector<int32_t> Ints3 = {3, 3, 3, 3, 3, 3, 3, 3, 3, 3};
std::vector<int32_t> Ints4 = {4, 4, 4, 4, 4, 4, 4, 4, 4, 4};
auto var_g = ioWrite.DefineVariable<int32_t>("global_variable", shape,
start, count);
for (size_t step = 0; step < NSteps; ++step)
{
engine.BeginStep();
if (step == 0)
{
engine.Put(var_g, Ints0.data());
auto var0 = ioWrite.DefineVariable<int32_t>("variable0", shape,
start, count);
engine.Put(var0, Ints0.data(), adios2::Mode::Deferred);
if (!ioWrite.InquireVariable<int>("variable0"))
{
auto var0 = ioWrite.DefineVariable<int32_t>(
"variable0", shape, start, count);
engine.Put(var0, Ints1.data(), adios2::Mode::Deferred);
}
}
else if (step == 1)
{
engine.Put(var_g, Ints1.data());
if (!ioWrite.InquireVariable<int>("variable1"))
{
auto var1 = ioWrite.DefineVariable<int32_t>(
"variable1", shape, start, count);
engine.Put(var1, Ints1.data(), adios2::Mode::Deferred);
}
}
else if (step == 2)
{
engine.Put(var_g, Ints2.data());
if (!ioWrite.InquireVariable<int>("variable2"))
{
auto var2 = ioWrite.DefineVariable<int32_t>(
"variable2", shape, start, count);
engine.Put(var2, Ints2.data(), adios2::Mode::Deferred);
}
}
else if (step == 3)
{
engine.Put(var_g, Ints3.data());
if (!ioWrite.InquireVariable<int>("variable3"))
{
auto var3 = ioWrite.DefineVariable<int32_t>(
"variable3", shape, start, count);
engine.Put(var3, Ints3.data(), adios2::Mode::Deferred);
}
}
else if (step == 4)
{
engine.Put(var_g, Ints4.data());
}
engine.EndStep();
}
engine.Close();
#if ADIOS2_USE_MPI
MPI_Barrier(MPI_COMM_WORLD);
#endif
adios2::IO ioRead = adios.DeclareIO("TestIORead");
ioRead.SetEngine("BPFile");
adios2::Engine engine_s = ioRead.Open(filename, adios2::Mode::Read);
EXPECT_TRUE(engine_s);
try
{
auto var_gr = ioRead.InquireVariable<int>("global_variable");
for (size_t step = 0; step < NSteps; step++)
{
engine_s.BeginStep();
auto var0r = ioRead.InquireVariable<int32_t>("variable0");
auto var1r = ioRead.InquireVariable<int32_t>("variable1");
auto var2r = ioRead.InquireVariable<int32_t>("variable2");
auto var3r = ioRead.InquireVariable<int32_t>("variable3");
if (step == 0)
{
EXPECT_TRUE(var0r);
EXPECT_FALSE(var1r);
EXPECT_FALSE(var2r);
EXPECT_FALSE(var3r);
EXPECT_TRUE(var_gr);
}
else if (step == 1)
{
EXPECT_FALSE(var0r);
EXPECT_TRUE(var1r);
EXPECT_FALSE(var2r);
EXPECT_FALSE(var3r);
EXPECT_TRUE(var_gr);
}
else if (step == 2)
{
EXPECT_FALSE(var0r);
EXPECT_FALSE(var1r);
EXPECT_TRUE(var2r);
EXPECT_FALSE(var3r);
EXPECT_TRUE(var_gr);
}
else if (step == 3)
{
EXPECT_FALSE(var0r);
EXPECT_FALSE(var1r);
EXPECT_FALSE(var2r);
EXPECT_TRUE(var3r);
EXPECT_TRUE(var_gr);
}
else if (step == 4)
{
EXPECT_TRUE(var_g);
}
if (var0r)
{
std::vector<int32_t> res;
var0r.SetSelection({{Nx * mpiRank}, {Nx}});
engine_s.Get<int32_t>(var0r, res, adios2::Mode::Sync);
EXPECT_EQ(res, Ints0);
}
if (var1r)
{
std::vector<int32_t> res;
var1r.SetSelection({{Nx * mpiRank}, {Nx}});
engine_s.Get<int32_t>(var1r, res, adios2::Mode::Sync);
EXPECT_EQ(res, Ints1);
}
if (var2r)
{
std::vector<int32_t> res;
var2r.SetSelection({{Nx * mpiRank}, {Nx}});
engine_s.Get<int32_t>(var2r, res, adios2::Mode::Sync);
EXPECT_EQ(res, Ints2);
}
if (var3r)
{
std::vector<int32_t> res;
var3r.SetSelection({{Nx * mpiRank}, {Nx}});
engine_s.Get<int32_t>(var3r, res, adios2::Mode::Sync);
EXPECT_EQ(res, Ints3);
}
if (var_gr)
{
std::vector<int32_t> res;
var_gr.SetSelection({{Nx * mpiRank}, {Nx}});
engine_s.Get<int32_t>(var_gr, res, adios2::Mode::Sync);
EXPECT_EQ(res, std::vector<int32_t>(10, step));
}
engine_s.EndStep();
}
}
catch (std::exception &e)
{
std::cout << "Exception " << e.what() << std::endl;
EXPECT_TRUE(false);
}
engine_s.Close();
}
}
int main(int argc, char **argv)
{
#if ADIOS2_USE_MPI
MPI_Init(nullptr, nullptr);
#endif
::testing::InitGoogleTest(&argc, argv);
int result = RUN_ALL_TESTS();
#if ADIOS2_USE_MPI
MPI_Finalize();
#endif
return result;
}
<commit_msg>Added a test to address issue 2500: make test more compex: fixed int type<commit_after>//
// Created by ganyush on 4/23/21.
//
/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*/
#include <cstdint>
#include <cstring>
#include <limits>
#include <stdexcept>
#include <adios2.h>
#include <adios2/common/ADIOSTypes.h>
#include <gtest/gtest.h>
class ADIOSInquireDefineTest : public ::testing::Test
{
public:
ADIOSInquireDefineTest() = default;
};
TEST_F(ADIOSInquireDefineTest, Read)
{
std::string filename = "ADIOSInquireDefine.bp";
// Number of steps
const int32_t NSteps = 5;
int mpiRank = 0, mpiSize = 1;
#if ADIOS2_USE_MPI
MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank);
MPI_Comm_size(MPI_COMM_WORLD, &mpiSize);
#endif
// Write test data using BP
{
#if ADIOS2_USE_MPI
adios2::ADIOS adios(MPI_COMM_WORLD);
#else
adios2::ADIOS adios;
#endif
// Number of elements per process
const std::size_t Nx = 10;
std::vector<int32_t> Ints0 = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
std::vector<int32_t> Ints1 = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
std::vector<int32_t> Ints2 = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2};
std::vector<int32_t> Ints3 = {3, 3, 3, 3, 3, 3, 3, 3, 3, 3};
std::vector<int32_t> Ints4 = {4, 4, 4, 4, 4, 4, 4, 4, 4, 4};
try
{
adios2::IO ioWrite = adios.DeclareIO("TestIOWrite");
adios2::Engine engine = ioWrite.Open(filename, adios2::Mode::Write);
adios2::Dims shape{static_cast<unsigned int>(mpiSize * Nx)};
adios2::Dims start{static_cast<unsigned int>(mpiRank * Nx)};
adios2::Dims count{static_cast<unsigned int>(Nx)};
auto var_g = ioWrite.DefineVariable<int32_t>("global_variable",
shape, start, count);
for (auto step = 0; step < NSteps; ++step)
{
engine.BeginStep();
if (step == 0)
{
engine.Put(var_g, Ints0.data());
auto var0 = ioWrite.DefineVariable<int32_t>(
"variable0", shape, start, count);
engine.Put(var0, Ints0.data(), adios2::Mode::Deferred);
if (!ioWrite.InquireVariable<int>("variable0"))
{
auto var0 = ioWrite.DefineVariable<int32_t>(
"variable0", shape, start, count);
engine.Put(var0, Ints1.data(), adios2::Mode::Deferred);
}
}
else if (step == 1)
{
engine.Put(var_g, Ints1.data());
if (!ioWrite.InquireVariable<int>("variable1"))
{
auto var1 = ioWrite.DefineVariable<int32_t>(
"variable1", shape, start, count);
engine.Put(var1, Ints1.data(), adios2::Mode::Deferred);
}
}
else if (step == 2)
{
engine.Put(var_g, Ints2.data());
if (!ioWrite.InquireVariable<int>("variable2"))
{
auto var2 = ioWrite.DefineVariable<int32_t>(
"variable2", shape, start, count);
engine.Put(var2, Ints2.data(), adios2::Mode::Deferred);
}
}
else if (step == 3)
{
engine.Put(var_g, Ints3.data());
if (!ioWrite.InquireVariable<int>("variable3"))
{
auto var3 = ioWrite.DefineVariable<int32_t>(
"variable3", shape, start, count);
engine.Put(var3, Ints3.data(), adios2::Mode::Deferred);
}
}
else if (step == 4)
{
engine.Put(var_g, Ints4.data());
}
engine.EndStep();
}
engine.Close();
}
catch (std::exception &e)
{
std::cout << "Exception " << e.what() << std::endl;
EXPECT_TRUE(false);
}
#if ADIOS2_USE_MPI
MPI_Barrier(MPI_COMM_WORLD);
#endif
try
{
adios2::IO ioRead = adios.DeclareIO("TestIORead");
ioRead.SetEngine("BPFile");
adios2::Engine engine_s = ioRead.Open(filename, adios2::Mode::Read);
EXPECT_TRUE(engine_s);
auto var_gr = ioRead.InquireVariable<int>("global_variable");
for (auto step = 0; step < NSteps; step++)
{
engine_s.BeginStep();
auto var0r = ioRead.InquireVariable<int32_t>("variable0");
auto var1r = ioRead.InquireVariable<int32_t>("variable1");
auto var2r = ioRead.InquireVariable<int32_t>("variable2");
auto var3r = ioRead.InquireVariable<int32_t>("variable3");
if (step == 0)
{
EXPECT_TRUE(var0r);
EXPECT_FALSE(var1r);
EXPECT_FALSE(var2r);
EXPECT_FALSE(var3r);
EXPECT_TRUE(var_gr);
}
else if (step == 1)
{
EXPECT_FALSE(var0r);
EXPECT_TRUE(var1r);
EXPECT_FALSE(var2r);
EXPECT_FALSE(var3r);
EXPECT_TRUE(var_gr);
}
else if (step == 2)
{
EXPECT_FALSE(var0r);
EXPECT_FALSE(var1r);
EXPECT_TRUE(var2r);
EXPECT_FALSE(var3r);
EXPECT_TRUE(var_gr);
}
else if (step == 3)
{
EXPECT_FALSE(var0r);
EXPECT_FALSE(var1r);
EXPECT_FALSE(var2r);
EXPECT_TRUE(var3r);
EXPECT_TRUE(var_gr);
}
else if (step == 4)
{
EXPECT_TRUE(var_gr);
}
if (var0r)
{
std::vector<int32_t> res;
var0r.SetSelection({{Nx * mpiRank}, {Nx}});
engine_s.Get<int32_t>(var0r, res, adios2::Mode::Sync);
EXPECT_EQ(res, Ints0);
}
if (var1r)
{
std::vector<int32_t> res;
var1r.SetSelection({{Nx * mpiRank}, {Nx}});
engine_s.Get<int32_t>(var1r, res, adios2::Mode::Sync);
EXPECT_EQ(res, Ints1);
}
if (var2r)
{
std::vector<int32_t> res;
var2r.SetSelection({{Nx * mpiRank}, {Nx}});
engine_s.Get<int32_t>(var2r, res, adios2::Mode::Sync);
EXPECT_EQ(res, Ints2);
}
if (var3r)
{
std::vector<int32_t> res;
var3r.SetSelection({{Nx * mpiRank}, {Nx}});
engine_s.Get<int32_t>(var3r, res, adios2::Mode::Sync);
EXPECT_EQ(res, Ints3);
}
if (var_gr)
{
std::vector<int32_t> res;
var_gr.SetSelection({{Nx * mpiRank}, {Nx}});
engine_s.Get<int32_t>(var_gr, res, adios2::Mode::Sync);
EXPECT_EQ(res, std::vector<int32_t>(10, step));
}
engine_s.EndStep();
}
engine_s.Close();
}
catch (std::exception &e)
{
std::cout << "Exception " << e.what() << std::endl;
EXPECT_TRUE(false);
}
}
}
int main(int argc, char **argv)
{
#if ADIOS2_USE_MPI
MPI_Init(nullptr, nullptr);
#endif
::testing::InitGoogleTest(&argc, argv);
int result = RUN_ALL_TESTS();
#if ADIOS2_USE_MPI
MPI_Finalize();
#endif
return result;
}
<|endoftext|>
|
<commit_before>#include "Caveman.hpp"
#include <iostream>
Caveman::Caveman(std::string cmd): cmd(cmd), lastAction('X'), actionHistory(""), sharpness(0), dead(false) {
// nothing to do here
}
// returns -1 for lose, 1 for win, 0 for N/A
int Caveman::provoke(Caveman& otherCaveman) {
getAction(actionHistory.length() ? (actionHistory + "," + otherCaveman.actionHistory) : "");
otherCaveman.getAction(actionHistory.length() ? (otherCaveman.actionHistory + "," + actionHistory) : "");
actionHistory += lastAction;
otherCaveman.actionHistory += otherCaveman.lastAction;
maybeSharpen();
otherCaveman.maybeSharpen();
maybePoke(otherCaveman);
otherCaveman.maybePoke(*this);
if (dead) return -1;
if (otherCaveman.dead) return 1;
return 0;
}
void Caveman::getAction(std::string input) {
char DEFAULT = 'X';
FILE* pipe = popen((cmd + (input.length() ? (" " + input) : "")).c_str(), "r");
if (!pipe) {
lastAction = DEFAULT;
} else {
lastAction = fgetc(pipe);
if (lastAction != 'S' && lastAction != 'P' && lastAction != 'B') lastAction = DEFAULT;
// sword
if (lastAction == 'S' && sharpness >= 5) lastAction = '^';
pclose(pipe);
}
}
void Caveman::maybeSharpen() {
if (lastAction == 'S') {
++sharpness;
}
}
void Caveman::maybePoke(Caveman otherCaveman) {
if (lastAction == 'P' && sharpness > 0) {
if (otherCaveman.lastAction == 'B' || otherCaveman.lastAction == 'P' || otherCaveman.lastAction == '^') {
--sharpness;
} else {
otherCaveman.dead = true;
}
} else if (lastAction == '^') {
if (otherCaveman.lastAction == '^') {
--sharpness;
} else {
otherCaveman.dead = true;
}
}
}
<commit_msg>bugfixes<commit_after>#include "Caveman.hpp"
#include <iostream>
Caveman::Caveman(std::string cmd): cmd(cmd), lastAction('X'), actionHistory(""), sharpness(0), dead(false) {
// nothing to do here
}
// returns -1 for lose, 1 for win, 0 for N/A
int Caveman::provoke(Caveman& otherCaveman) {
getAction(actionHistory.length() ? (actionHistory + "," + otherCaveman.actionHistory) : "");
otherCaveman.getAction(actionHistory.length() ? (otherCaveman.actionHistory + "," + actionHistory) : "");
actionHistory += lastAction;
otherCaveman.actionHistory += otherCaveman.lastAction;
maybeSharpen();
otherCaveman.maybeSharpen();
maybePoke(otherCaveman);
otherCaveman.maybePoke(*this);
if (dead) return -1;
if (otherCaveman.dead) return 1;
return 0;
}
void Caveman::getAction(std::string input) {
char DEFAULT = 'B';
FILE* pipe = popen((cmd + (input.length() ? (" " + input) : "")).c_str(), "r");
if (!pipe) {
lastAction = DEFAULT;
} else {
lastAction = fgetc(pipe);
if (lastAction != 'S' && lastAction != 'P' && lastAction != 'B') lastAction = DEFAULT;
// sword
if (lastAction == 'P' && sharpness >= 5) lastAction = '^';
pclose(pipe);
}
}
void Caveman::maybeSharpen() {
if (lastAction == 'S') {
++sharpness;
}
}
void Caveman::maybePoke(Caveman otherCaveman) {
if (lastAction == 'P' && sharpness > 0) {
if (otherCaveman.lastAction == 'B' || otherCaveman.lastAction == 'P' || otherCaveman.lastAction == '^') {
--sharpness;
} else {
otherCaveman.dead = true;
}
} else if (lastAction == '^') {
if (otherCaveman.lastAction == '^') {
--sharpness;
} else {
otherCaveman.dead = true;
}
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Research In Motion
** Contact: http://www.qt-project.org/legal
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QDebug>
#include <QQmlEngine>
#include <QQmlComponent>
#include <QQmlContext>
#include <qqml.h>
#include <QMetaMethod>
#include "../../shared/util.h"
class ExportedClass : public QObject
{
Q_OBJECT
Q_PROPERTY(int qmlObjectProp READ qmlObjectProp NOTIFY qmlObjectPropChanged)
Q_PROPERTY(int cppObjectProp READ cppObjectProp NOTIFY cppObjectPropChanged)
Q_PROPERTY(int unboundProp READ unboundProp NOTIFY unboundPropChanged)
Q_PROPERTY(int v8BindingProp READ v8BindingProp NOTIFY v8BindingPropChanged)
Q_PROPERTY(int v4BindingProp READ v4BindingProp NOTIFY v4BindingPropChanged)
Q_PROPERTY(int v4BindingProp2 READ v4BindingProp2 NOTIFY v4BindingProp2Changed)
Q_PROPERTY(int scriptBindingProp READ scriptBindingProp NOTIFY scriptBindingPropChanged)
public:
int qmlObjectPropConnections;
int cppObjectPropConnections;
int unboundPropConnections;
int v8BindingPropConnections;
int v4BindingPropConnections;
int v4BindingProp2Connections;
int scriptBindingPropConnections;
int boundSignalConnections;
int unusedSignalConnections;
ExportedClass()
: qmlObjectPropConnections(0), cppObjectPropConnections(0), unboundPropConnections(0),
v8BindingPropConnections(0), v4BindingPropConnections(0), v4BindingProp2Connections(0),
scriptBindingPropConnections(0), boundSignalConnections(0), unusedSignalConnections(0)
{}
~ExportedClass()
{
QCOMPARE(qmlObjectPropConnections, 0);
QCOMPARE(cppObjectPropConnections, 0);
QCOMPARE(unboundPropConnections, 0);
QCOMPARE(v8BindingPropConnections, 0);
QCOMPARE(v4BindingPropConnections, 0);
QCOMPARE(v4BindingProp2Connections, 0);
QCOMPARE(scriptBindingPropConnections, 0);
QCOMPARE(boundSignalConnections, 0);
QCOMPARE(unusedSignalConnections, 0);
}
int qmlObjectProp() const { return 42; }
int unboundProp() const { return 42; }
int v8BindingProp() const { return 42; }
int v4BindingProp() const { return 42; }
int v4BindingProp2() const { return 42; }
int cppObjectProp() const { return 42; }
int scriptBindingProp() const { return 42; }
protected:
void connectNotify(const QMetaMethod &signal) Q_DECL_OVERRIDE {
if (signal.name() == "qmlObjectPropChanged") qmlObjectPropConnections++;
if (signal.name() == "cppObjectPropChanged") cppObjectPropConnections++;
if (signal.name() == "unboundPropChanged") unboundPropConnections++;
if (signal.name() == "v8BindingPropChanged") v8BindingPropConnections++;
if (signal.name() == "v4BindingPropChanged") v4BindingPropConnections++;
if (signal.name() == "v4BindingProp2Changed") v4BindingProp2Connections++;
if (signal.name() == "scriptBindingPropChanged") scriptBindingPropConnections++;
if (signal.name() == "boundSignal") boundSignalConnections++;
if (signal.name() == "unusedSignal") unusedSignalConnections++;
//qDebug() << Q_FUNC_INFO << this << signal.name();
}
void disconnectNotify(const QMetaMethod &signal) Q_DECL_OVERRIDE {
if (signal.name() == "qmlObjectPropChanged") qmlObjectPropConnections--;
if (signal.name() == "cppObjectPropChanged") cppObjectPropConnections--;
if (signal.name() == "unboundPropChanged") unboundPropConnections--;
if (signal.name() == "v8BindingPropChanged") v8BindingPropConnections--;
if (signal.name() == "v4BindingPropChanged") v4BindingPropConnections--;
if (signal.name() == "v4BindingProp2Changed") v4BindingProp2Connections--;
if (signal.name() == "scriptBindingPropChanged") scriptBindingPropConnections--;
if (signal.name() == "boundSignal") boundSignalConnections--;
if (signal.name() == "unusedSignal") unusedSignalConnections--;
//qDebug() << Q_FUNC_INFO << this << signal.methodSignature();
}
signals:
void qmlObjectPropChanged();
void cppObjectPropChanged();
void unboundPropChanged();
void v8BindingPropChanged();
void v4BindingPropChanged();
void v4BindingProp2Changed();
void scriptBindingPropChanged();
void boundSignal();
void unusedSignal();
};
class tst_qqmlnotifier : public QQmlDataTest
{
Q_OBJECT
public:
tst_qqmlnotifier()
: root(0), exportedClass(0), exportedObject(0)
{}
private slots:
void initTestCase() Q_DECL_OVERRIDE;
void cleanupTestCase();
void connectNotify();
void removeV4Binding();
void removeV4Binding2();
void removeV8Binding();
void removeScriptBinding();
// No need to test value type proxy bindings - the user can't override disconnectNotify() anyway,
// as the classes are private to the QML engine
void readProperty();
void propertyChange();
void disconnectOnDestroy();
private:
void createObjects();
QQmlEngine engine;
QObject *root;
ExportedClass *exportedClass;
ExportedClass *exportedObject;
};
void tst_qqmlnotifier::initTestCase()
{
QQmlDataTest::initTestCase();
qmlRegisterType<ExportedClass>("Test", 1, 0, "ExportedClass");
}
void tst_qqmlnotifier::createObjects()
{
delete root;
root = 0;
exportedClass = exportedObject = 0;
QQmlComponent component(&engine, testFileUrl("connectnotify.qml"));
exportedObject = new ExportedClass();
exportedObject->setObjectName("exportedObject");
engine.rootContext()->setContextProperty("_exportedObject", exportedObject);
root = component.create();
QVERIFY(root != 0);
exportedClass = qobject_cast<ExportedClass *>(
root->findChild<ExportedClass*>("exportedClass"));
QVERIFY(exportedClass != 0);
}
void tst_qqmlnotifier::cleanupTestCase()
{
delete root;
root = 0;
delete exportedObject;
exportedObject = 0;
}
void tst_qqmlnotifier::connectNotify()
{
createObjects();
QCOMPARE(exportedClass->qmlObjectPropConnections, 1);
QCOMPARE(exportedClass->cppObjectPropConnections, 0);
QCOMPARE(exportedClass->unboundPropConnections, 0);
QCOMPARE(exportedClass->v8BindingPropConnections, 1);
QCOMPARE(exportedClass->v4BindingPropConnections, 1);
QCOMPARE(exportedClass->v4BindingProp2Connections, 2);
QCOMPARE(exportedClass->scriptBindingPropConnections, 1);
QCOMPARE(exportedClass->boundSignalConnections, 1);
QCOMPARE(exportedClass->unusedSignalConnections, 0);
QCOMPARE(exportedObject->qmlObjectPropConnections, 0);
QCOMPARE(exportedObject->cppObjectPropConnections, 1);
QCOMPARE(exportedObject->unboundPropConnections, 0);
QCOMPARE(exportedObject->v8BindingPropConnections, 0);
QCOMPARE(exportedObject->v4BindingPropConnections, 0);
QCOMPARE(exportedObject->v4BindingProp2Connections, 0);
QCOMPARE(exportedObject->scriptBindingPropConnections, 0);
QCOMPARE(exportedObject->boundSignalConnections, 0);
QCOMPARE(exportedObject->unusedSignalConnections, 0);
}
void tst_qqmlnotifier::removeV4Binding()
{
createObjects();
// Removing a binding should disconnect all of its guarded properties
QVERIFY(QMetaObject::invokeMethod(root, "removeV4Binding"));
QCOMPARE(exportedClass->v4BindingPropConnections, 0);
}
void tst_qqmlnotifier::removeV4Binding2()
{
createObjects();
// In this case, the v4BindingProp2 property is used by two v4 bindings.
// Make sure that removing one binding doesn't by accident disconnect all.
QVERIFY(QMetaObject::invokeMethod(root, "removeV4Binding2"));
QCOMPARE(exportedClass->v4BindingProp2Connections, 1);
}
void tst_qqmlnotifier::removeV8Binding()
{
createObjects();
// Removing a binding should disconnect all of its guarded properties
QVERIFY(QMetaObject::invokeMethod(root, "removeV8Binding"));
QCOMPARE(exportedClass->v8BindingPropConnections, 0);
}
void tst_qqmlnotifier::removeScriptBinding()
{
createObjects();
// Removing a binding should disconnect all of its guarded properties
QVERIFY(QMetaObject::invokeMethod(root, "removeScriptBinding"));
QCOMPARE(exportedClass->scriptBindingPropConnections, 0);
}
void tst_qqmlnotifier::readProperty()
{
createObjects();
// Reading a property should not connect to it
QVERIFY(QMetaObject::invokeMethod(root, "readProperty"));
QCOMPARE(exportedClass->unboundPropConnections, 0);
}
void tst_qqmlnotifier::propertyChange()
{
createObjects();
// Changing the state will trigger the PropertyChange to overwrite a value with a binding.
// For this, the new binding needs to be connected, and afterwards disconnected.
QVERIFY(QMetaObject::invokeMethod(root, "changeState"));
QCOMPARE(exportedClass->unboundPropConnections, 1);
QVERIFY(QMetaObject::invokeMethod(root, "changeState"));
QCOMPARE(exportedClass->unboundPropConnections, 0);
}
void tst_qqmlnotifier::disconnectOnDestroy()
{
createObjects();
// Deleting a QML object should remove all connections. For exportedClass, this is tested in
// the destructor, and for exportedObject, it is tested below.
delete root;
root = 0;
QCOMPARE(exportedObject->cppObjectPropConnections, 0);
}
QTEST_MAIN(tst_qqmlnotifier)
#include "tst_qqmlnotifier.moc"
<commit_msg>In tst_qqmlnotifier, verify the result of QObject::receivers()<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Research In Motion
** Contact: http://www.qt-project.org/legal
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QDebug>
#include <QQmlEngine>
#include <QQmlComponent>
#include <QQmlContext>
#include <qqml.h>
#include <QMetaMethod>
#include "../../shared/util.h"
class ExportedClass : public QObject
{
Q_OBJECT
Q_PROPERTY(int qmlObjectProp READ qmlObjectProp NOTIFY qmlObjectPropChanged)
Q_PROPERTY(int cppObjectProp READ cppObjectProp NOTIFY cppObjectPropChanged)
Q_PROPERTY(int unboundProp READ unboundProp NOTIFY unboundPropChanged)
Q_PROPERTY(int v8BindingProp READ v8BindingProp NOTIFY v8BindingPropChanged)
Q_PROPERTY(int v4BindingProp READ v4BindingProp NOTIFY v4BindingPropChanged)
Q_PROPERTY(int v4BindingProp2 READ v4BindingProp2 NOTIFY v4BindingProp2Changed)
Q_PROPERTY(int scriptBindingProp READ scriptBindingProp NOTIFY scriptBindingPropChanged)
public:
int qmlObjectPropConnections;
int cppObjectPropConnections;
int unboundPropConnections;
int v8BindingPropConnections;
int v4BindingPropConnections;
int v4BindingProp2Connections;
int scriptBindingPropConnections;
int boundSignalConnections;
int unusedSignalConnections;
ExportedClass()
: qmlObjectPropConnections(0), cppObjectPropConnections(0), unboundPropConnections(0),
v8BindingPropConnections(0), v4BindingPropConnections(0), v4BindingProp2Connections(0),
scriptBindingPropConnections(0), boundSignalConnections(0), unusedSignalConnections(0)
{}
~ExportedClass()
{
QCOMPARE(qmlObjectPropConnections, 0);
QCOMPARE(cppObjectPropConnections, 0);
QCOMPARE(unboundPropConnections, 0);
QCOMPARE(v8BindingPropConnections, 0);
QCOMPARE(v4BindingPropConnections, 0);
QCOMPARE(v4BindingProp2Connections, 0);
QCOMPARE(scriptBindingPropConnections, 0);
QCOMPARE(boundSignalConnections, 0);
QCOMPARE(unusedSignalConnections, 0);
}
int qmlObjectProp() const { return 42; }
int unboundProp() const { return 42; }
int v8BindingProp() const { return 42; }
int v4BindingProp() const { return 42; }
int v4BindingProp2() const { return 42; }
int cppObjectProp() const { return 42; }
int scriptBindingProp() const { return 42; }
void verifyReceiverCount()
{
QCOMPARE(receivers(SIGNAL(qmlObjectPropChanged())), qmlObjectPropConnections);
QCOMPARE(receivers(SIGNAL(cppObjectPropChanged())), cppObjectPropConnections);
QCOMPARE(receivers(SIGNAL(unboundPropChanged())), unboundPropConnections);
QCOMPARE(receivers(SIGNAL(v8BindingPropChanged())), v8BindingPropConnections);
QCOMPARE(receivers(SIGNAL(v4BindingPropChanged())), v4BindingPropConnections);
QCOMPARE(receivers(SIGNAL(v4BindingProp2Changed())), v4BindingProp2Connections);
QCOMPARE(receivers(SIGNAL(scriptBindingPropChanged())), scriptBindingPropConnections);
QCOMPARE(receivers(SIGNAL(boundSignal())), boundSignalConnections);
QCOMPARE(receivers(SIGNAL(unusedSignal())), unusedSignalConnections);
}
protected:
void connectNotify(const QMetaMethod &signal) Q_DECL_OVERRIDE {
if (signal.name() == "qmlObjectPropChanged") qmlObjectPropConnections++;
if (signal.name() == "cppObjectPropChanged") cppObjectPropConnections++;
if (signal.name() == "unboundPropChanged") unboundPropConnections++;
if (signal.name() == "v8BindingPropChanged") v8BindingPropConnections++;
if (signal.name() == "v4BindingPropChanged") v4BindingPropConnections++;
if (signal.name() == "v4BindingProp2Changed") v4BindingProp2Connections++;
if (signal.name() == "scriptBindingPropChanged") scriptBindingPropConnections++;
if (signal.name() == "boundSignal") boundSignalConnections++;
if (signal.name() == "unusedSignal") unusedSignalConnections++;
//qDebug() << Q_FUNC_INFO << this << signal.name();
}
void disconnectNotify(const QMetaMethod &signal) Q_DECL_OVERRIDE {
if (signal.name() == "qmlObjectPropChanged") qmlObjectPropConnections--;
if (signal.name() == "cppObjectPropChanged") cppObjectPropConnections--;
if (signal.name() == "unboundPropChanged") unboundPropConnections--;
if (signal.name() == "v8BindingPropChanged") v8BindingPropConnections--;
if (signal.name() == "v4BindingPropChanged") v4BindingPropConnections--;
if (signal.name() == "v4BindingProp2Changed") v4BindingProp2Connections--;
if (signal.name() == "scriptBindingPropChanged") scriptBindingPropConnections--;
if (signal.name() == "boundSignal") boundSignalConnections--;
if (signal.name() == "unusedSignal") unusedSignalConnections--;
//qDebug() << Q_FUNC_INFO << this << signal.methodSignature();
}
signals:
void qmlObjectPropChanged();
void cppObjectPropChanged();
void unboundPropChanged();
void v8BindingPropChanged();
void v4BindingPropChanged();
void v4BindingProp2Changed();
void scriptBindingPropChanged();
void boundSignal();
void unusedSignal();
};
class tst_qqmlnotifier : public QQmlDataTest
{
Q_OBJECT
public:
tst_qqmlnotifier()
: root(0), exportedClass(0), exportedObject(0)
{}
private slots:
void initTestCase() Q_DECL_OVERRIDE;
void cleanupTestCase();
void connectNotify();
void removeV4Binding();
void removeV4Binding2();
void removeV8Binding();
void removeScriptBinding();
// No need to test value type proxy bindings - the user can't override disconnectNotify() anyway,
// as the classes are private to the QML engine
void readProperty();
void propertyChange();
void disconnectOnDestroy();
private:
void createObjects();
QQmlEngine engine;
QObject *root;
ExportedClass *exportedClass;
ExportedClass *exportedObject;
};
void tst_qqmlnotifier::initTestCase()
{
QQmlDataTest::initTestCase();
qmlRegisterType<ExportedClass>("Test", 1, 0, "ExportedClass");
}
void tst_qqmlnotifier::createObjects()
{
delete root;
root = 0;
exportedClass = exportedObject = 0;
QQmlComponent component(&engine, testFileUrl("connectnotify.qml"));
exportedObject = new ExportedClass();
exportedObject->setObjectName("exportedObject");
engine.rootContext()->setContextProperty("_exportedObject", exportedObject);
root = component.create();
QVERIFY(root != 0);
exportedClass = qobject_cast<ExportedClass *>(
root->findChild<ExportedClass*>("exportedClass"));
QVERIFY(exportedClass != 0);
}
void tst_qqmlnotifier::cleanupTestCase()
{
delete root;
root = 0;
delete exportedObject;
exportedObject = 0;
}
void tst_qqmlnotifier::connectNotify()
{
createObjects();
QCOMPARE(exportedClass->qmlObjectPropConnections, 1);
QCOMPARE(exportedClass->cppObjectPropConnections, 0);
QCOMPARE(exportedClass->unboundPropConnections, 0);
QCOMPARE(exportedClass->v8BindingPropConnections, 1);
QCOMPARE(exportedClass->v4BindingPropConnections, 1);
QCOMPARE(exportedClass->v4BindingProp2Connections, 2);
QCOMPARE(exportedClass->scriptBindingPropConnections, 1);
QCOMPARE(exportedClass->boundSignalConnections, 1);
QCOMPARE(exportedClass->unusedSignalConnections, 0);
exportedClass->verifyReceiverCount();
QCOMPARE(exportedObject->qmlObjectPropConnections, 0);
QCOMPARE(exportedObject->cppObjectPropConnections, 1);
QCOMPARE(exportedObject->unboundPropConnections, 0);
QCOMPARE(exportedObject->v8BindingPropConnections, 0);
QCOMPARE(exportedObject->v4BindingPropConnections, 0);
QCOMPARE(exportedObject->v4BindingProp2Connections, 0);
QCOMPARE(exportedObject->scriptBindingPropConnections, 0);
QCOMPARE(exportedObject->boundSignalConnections, 0);
QCOMPARE(exportedObject->unusedSignalConnections, 0);
exportedObject->verifyReceiverCount();
}
void tst_qqmlnotifier::removeV4Binding()
{
createObjects();
// Removing a binding should disconnect all of its guarded properties
QVERIFY(QMetaObject::invokeMethod(root, "removeV4Binding"));
QCOMPARE(exportedClass->v4BindingPropConnections, 0);
exportedClass->verifyReceiverCount();
}
void tst_qqmlnotifier::removeV4Binding2()
{
createObjects();
// In this case, the v4BindingProp2 property is used by two v4 bindings.
// Make sure that removing one binding doesn't by accident disconnect all.
QVERIFY(QMetaObject::invokeMethod(root, "removeV4Binding2"));
QCOMPARE(exportedClass->v4BindingProp2Connections, 1);
exportedClass->verifyReceiverCount();
}
void tst_qqmlnotifier::removeV8Binding()
{
createObjects();
// Removing a binding should disconnect all of its guarded properties
QVERIFY(QMetaObject::invokeMethod(root, "removeV8Binding"));
QCOMPARE(exportedClass->v8BindingPropConnections, 0);
exportedClass->verifyReceiverCount();
}
void tst_qqmlnotifier::removeScriptBinding()
{
createObjects();
// Removing a binding should disconnect all of its guarded properties
QVERIFY(QMetaObject::invokeMethod(root, "removeScriptBinding"));
QCOMPARE(exportedClass->scriptBindingPropConnections, 0);
exportedClass->verifyReceiverCount();
}
void tst_qqmlnotifier::readProperty()
{
createObjects();
// Reading a property should not connect to it
QVERIFY(QMetaObject::invokeMethod(root, "readProperty"));
QCOMPARE(exportedClass->unboundPropConnections, 0);
exportedClass->verifyReceiverCount();
}
void tst_qqmlnotifier::propertyChange()
{
createObjects();
// Changing the state will trigger the PropertyChange to overwrite a value with a binding.
// For this, the new binding needs to be connected, and afterwards disconnected.
QVERIFY(QMetaObject::invokeMethod(root, "changeState"));
QCOMPARE(exportedClass->unboundPropConnections, 1);
exportedClass->verifyReceiverCount();
QVERIFY(QMetaObject::invokeMethod(root, "changeState"));
QCOMPARE(exportedClass->unboundPropConnections, 0);
exportedClass->verifyReceiverCount();
}
void tst_qqmlnotifier::disconnectOnDestroy()
{
createObjects();
// Deleting a QML object should remove all connections. For exportedClass, this is tested in
// the destructor, and for exportedObject, it is tested below.
delete root;
root = 0;
QCOMPARE(exportedObject->cppObjectPropConnections, 0);
exportedObject->verifyReceiverCount();
}
QTEST_MAIN(tst_qqmlnotifier)
#include "tst_qqmlnotifier.moc"
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "profileevaluator.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QLibraryInfo>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QTextCodec>
static QString value(ProFileEvaluator &reader, const QString &variable)
{
QStringList vals = reader.values(variable);
if (!vals.isEmpty())
return vals.first();
return QString();
}
static int evaluate(const QString &fileName, const QString &in_pwd, const QString &out_pwd,
bool cumulative, ProFileOption *option, int level)
{
static QSet<QString> visited;
if (visited.contains(fileName))
return 0;
visited.insert(fileName);
ProFileEvaluator visitor(option);
visitor.setVerbose(true);
visitor.setCumulative(cumulative);
visitor.setOutputDir(out_pwd);
ProFile *pro;
if (!(pro = visitor.parsedProFile(fileName)))
return 2;
if (!visitor.accept(pro))
return 2;
if (visitor.templateType() == ProFileEvaluator::TT_Subdirs) {
QStringList subdirs = visitor.values(QLatin1String("SUBDIRS"));
subdirs.removeDuplicates();
foreach (const QString &subDirVar, subdirs) {
QString realDir;
const QString subDirKey = subDirVar + QLatin1String(".subdir");
const QString subDirFileKey = subDirVar + QLatin1String(".file");
if (visitor.contains(subDirKey))
realDir = QFileInfo(value(visitor, subDirKey)).filePath();
else if (visitor.contains(subDirFileKey))
realDir = QFileInfo(value(visitor, subDirFileKey)).filePath();
else
realDir = subDirVar;
QFileInfo info(realDir);
if (!info.isAbsolute())
info.setFile(in_pwd + QLatin1Char('/') + realDir);
if (info.isDir())
info.setFile(QString::fromLatin1("%1/%2.pro").arg(info.filePath(), info.fileName()));
if (!info.exists()) {
qDebug() << "Could not find sub dir" << info.filePath();
continue;
}
QString inFile = QDir::cleanPath(info.absoluteFilePath()),
inPwd = QDir::cleanPath(info.path()),
outPwd = QDir::cleanPath(QDir(out_pwd).absoluteFilePath(
QDir(in_pwd).relativeFilePath(info.path())));
int nlevel = level;
if (nlevel >= 0) {
printf("%sReading %s%s\n", QByteArray().fill(' ', nlevel).constData(),
qPrintable(inFile), (inPwd == outPwd) ? "" :
qPrintable(QString(QLatin1String(" [") + outPwd + QLatin1Char(']'))));
fflush(stdout);
nlevel++;
}
evaluate(inFile, inPwd, outPwd, cumulative, option, nlevel);
}
}
return 0;
}
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
QStringList args = app.arguments();
args.removeFirst();
int level = -1; // verbose
if (args.count() && args.first() == QLatin1String("-v"))
level = 0, args.removeFirst();
if (args.count() < 2)
qFatal("need at least two arguments: [-v] <cumulative?> <filenme> [<out_pwd>]");
ProFileOption option;
static const struct {
const char * const name;
QLibraryInfo::LibraryLocation index;
} props[] = {
{ "QT_INSTALL_DATA", QLibraryInfo::DataPath },
{ "QT_INSTALL_LIBS", QLibraryInfo::LibrariesPath },
{ "QT_INSTALL_HEADERS", QLibraryInfo::HeadersPath },
{ "QT_INSTALL_DEMOS", QLibraryInfo::DemosPath },
{ "QT_INSTALL_EXAMPLES", QLibraryInfo::ExamplesPath },
{ "QT_INSTALL_CONFIGURATION", QLibraryInfo::SettingsPath },
{ "QT_INSTALL_TRANSLATIONS", QLibraryInfo::TranslationsPath },
{ "QT_INSTALL_PLUGINS", QLibraryInfo::PluginsPath },
{ "QT_INSTALL_BINS", QLibraryInfo::BinariesPath },
{ "QT_INSTALL_DOCS", QLibraryInfo::DocumentationPath },
{ "QT_INSTALL_PREFIX", QLibraryInfo::PrefixPath }
};
for (unsigned i = 0; i < sizeof(props)/sizeof(props[0]); ++i)
option.properties.insert(QLatin1String(props[i].name),
QLibraryInfo::location(props[i].index));
option.properties.insert(QLatin1String("QT_VERSION"), QLatin1String(qVersion()));
bool cumulative = args[0] == QLatin1String("true");
QFileInfo infi(args[1]);
QString file = infi.absoluteFilePath();
QString in_pwd = infi.absolutePath();
QString out_pwd = (args.count() > 2) ? QFileInfo(args[2]).absoluteFilePath() : in_pwd;
return evaluate(file, in_pwd, out_pwd, cumulative, &option, level);
}
<commit_msg>don't leak ProFile objects<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "profileevaluator.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QLibraryInfo>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QTextCodec>
static QString value(ProFileEvaluator &reader, const QString &variable)
{
QStringList vals = reader.values(variable);
if (!vals.isEmpty())
return vals.first();
return QString();
}
static int evaluate(const QString &fileName, const QString &in_pwd, const QString &out_pwd,
bool cumulative, ProFileOption *option, int level)
{
static QSet<QString> visited;
if (visited.contains(fileName))
return 0;
visited.insert(fileName);
ProFileEvaluator visitor(option);
visitor.setVerbose(true);
visitor.setCumulative(cumulative);
visitor.setOutputDir(out_pwd);
ProFile *pro;
if (!(pro = visitor.parsedProFile(fileName)))
return 2;
if (!visitor.accept(pro)) {
delete pro;
return 2;
}
if (visitor.templateType() == ProFileEvaluator::TT_Subdirs) {
QStringList subdirs = visitor.values(QLatin1String("SUBDIRS"));
subdirs.removeDuplicates();
foreach (const QString &subDirVar, subdirs) {
QString realDir;
const QString subDirKey = subDirVar + QLatin1String(".subdir");
const QString subDirFileKey = subDirVar + QLatin1String(".file");
if (visitor.contains(subDirKey))
realDir = QFileInfo(value(visitor, subDirKey)).filePath();
else if (visitor.contains(subDirFileKey))
realDir = QFileInfo(value(visitor, subDirFileKey)).filePath();
else
realDir = subDirVar;
QFileInfo info(realDir);
if (!info.isAbsolute())
info.setFile(in_pwd + QLatin1Char('/') + realDir);
if (info.isDir())
info.setFile(QString::fromLatin1("%1/%2.pro").arg(info.filePath(), info.fileName()));
if (!info.exists()) {
qDebug() << "Could not find sub dir" << info.filePath();
continue;
}
QString inFile = QDir::cleanPath(info.absoluteFilePath()),
inPwd = QDir::cleanPath(info.path()),
outPwd = QDir::cleanPath(QDir(out_pwd).absoluteFilePath(
QDir(in_pwd).relativeFilePath(info.path())));
int nlevel = level;
if (nlevel >= 0) {
printf("%sReading %s%s\n", QByteArray().fill(' ', nlevel).constData(),
qPrintable(inFile), (inPwd == outPwd) ? "" :
qPrintable(QString(QLatin1String(" [") + outPwd + QLatin1Char(']'))));
fflush(stdout);
nlevel++;
}
evaluate(inFile, inPwd, outPwd, cumulative, option, nlevel);
}
}
delete pro;
return 0;
}
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
QStringList args = app.arguments();
args.removeFirst();
int level = -1; // verbose
if (args.count() && args.first() == QLatin1String("-v"))
level = 0, args.removeFirst();
if (args.count() < 2)
qFatal("need at least two arguments: [-v] <cumulative?> <filenme> [<out_pwd>]");
ProFileOption option;
static const struct {
const char * const name;
QLibraryInfo::LibraryLocation index;
} props[] = {
{ "QT_INSTALL_DATA", QLibraryInfo::DataPath },
{ "QT_INSTALL_LIBS", QLibraryInfo::LibrariesPath },
{ "QT_INSTALL_HEADERS", QLibraryInfo::HeadersPath },
{ "QT_INSTALL_DEMOS", QLibraryInfo::DemosPath },
{ "QT_INSTALL_EXAMPLES", QLibraryInfo::ExamplesPath },
{ "QT_INSTALL_CONFIGURATION", QLibraryInfo::SettingsPath },
{ "QT_INSTALL_TRANSLATIONS", QLibraryInfo::TranslationsPath },
{ "QT_INSTALL_PLUGINS", QLibraryInfo::PluginsPath },
{ "QT_INSTALL_BINS", QLibraryInfo::BinariesPath },
{ "QT_INSTALL_DOCS", QLibraryInfo::DocumentationPath },
{ "QT_INSTALL_PREFIX", QLibraryInfo::PrefixPath }
};
for (unsigned i = 0; i < sizeof(props)/sizeof(props[0]); ++i)
option.properties.insert(QLatin1String(props[i].name),
QLibraryInfo::location(props[i].index));
option.properties.insert(QLatin1String("QT_VERSION"), QLatin1String(qVersion()));
bool cumulative = args[0] == QLatin1String("true");
QFileInfo infi(args[1]);
QString file = infi.absoluteFilePath();
QString in_pwd = infi.absolutePath();
QString out_pwd = (args.count() > 2) ? QFileInfo(args[2]).absoluteFilePath() : in_pwd;
return evaluate(file, in_pwd, out_pwd, cumulative, &option, level);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011-2013 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// Unit tests for block-chain checkpoints
//
#include "checkpoints.h"
#include "uint256.h"
#include <boost/test/unit_test.hpp>
using namespace std;
BOOST_AUTO_TEST_SUITE(Checkpoints_tests)
BOOST_AUTO_TEST_CASE(sanity)
{
uint256 p1500 = uint256("0x841a2965955dd288cfa707a755d05a54e45f8bd476835ec9af4402a2b59a2967");
uint256 p120000 = uint256("0xbd9d26924f05f6daa7f0155f32828ec89e8e29cee9e7121b026a7a3552ac6131");
BOOST_CHECK(Checkpoints::CheckBlock(1500, p1500));
BOOST_CHECK(Checkpoints::CheckBlock(120000, p120000));
// Wrong hashes at checkpoints should fail:
BOOST_CHECK(!Checkpoints::CheckBlock(1500, p120000));
BOOST_CHECK(!Checkpoints::CheckBlock(120000, p1500));
// ... but any hash not at a checkpoint should succeed:
BOOST_CHECK(Checkpoints::CheckBlock(1500+1, p120000));
BOOST_CHECK(Checkpoints::CheckBlock(120000+1, p1500));
BOOST_CHECK(Checkpoints::GetTotalBlocksEstimate() >= 120000);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fixed checkpoint tests<commit_after>// Copyright (c) 2011-2013 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// Unit tests for block-chain checkpoints
//
#include "checkpoints.h"
#include "uint256.h"
#include <boost/test/unit_test.hpp>
using namespace std;
BOOST_AUTO_TEST_SUITE(Checkpoints_tests)
BOOST_AUTO_TEST_CASE(sanity)
{
uint256 p25000 = uint256("0x99ffd2f7230224586c61deb459fa1cde94bda2876aed8bb791f4e3b5d485ef59");
uint256 p40000 = uint256("0xbec732146705189352bb0007c4a26345a3ddf0eac1e8721e2fbb121b7d7c04b6");
BOOST_CHECK(Checkpoints::CheckBlock(25000, p25000));
BOOST_CHECK(Checkpoints::CheckBlock(40000, p40000));
// Wrong hashes at checkpoints should fail:
BOOST_CHECK(!Checkpoints::CheckBlock(25000, p40000));
BOOST_CHECK(!Checkpoints::CheckBlock(40000, p25000));
// ... but any hash not at a checkpoint should succeed:
BOOST_CHECK(Checkpoints::CheckBlock(25000+1, p40000));
BOOST_CHECK(Checkpoints::CheckBlock(40000+1, p25000));
BOOST_CHECK(Checkpoints::GetTotalBlocksEstimate() >= 300000);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>#include <string>
#include <functional>
#include <Console.h>
#include <CPU.h>
#include <APU.h>
#include <PPU.h>
#include <Cart.h>
#include <Controller.h>
#include <Divider.h>
void Console::boot() {
cpu.boot([this] (uint16_t addr) {return cpuRead(addr);},
[this] (uint16_t addr, uint8_t data) {cpuWrite(addr,data);});
ppu.boot(&cart,
[this] () {cpu.signalNMI();});
}
bool Console::loadINesFile(std::string fileName) {
return cart.loadFile(fileName);
}
uint32_t *Console::getFrameBuffer() {
return ppu.getFrameBuffer();
}
void Console::runForOneFrame() {
do {
tick();
} while (!ppu.endOfFrame());
apu.endFrame();
}
void Console::tick() {
cpuDivider.tick();
if (cpuDivider.hasClocked()) {
cpu.tick();
}
ppu.tick();
}
uint8_t Console::cpuRead(uint16_t addr) {
if (addr < 0x2000) {
return cpuRam[addr % 0x800];
}
else if (addr < 0x4000) {
int port = addr % 8;
switch (port) {
case 0: // 0x2000
return cpuBusMDR;
case 1: // 0x2001
return cpuBusMDR;
case 2: // 0x2002
return ppu.getSTATUS();
case 3: // 0x2003
return cpuBusMDR;
case 4: // 0x2004
return ppu.getOAMDATA();
case 5: // 0x2005
return cpuBusMDR;
case 6: // 0x2006
return cpuBusMDR;
case 7: // 0x2007
return ppu.getDATA();
}
}
else if (addr < 0x4020) {
switch (addr) {
case 0x4015:
return apu.getStatus();
case 0x4016:
return controller1.poll();
case 0x4017: // TODO: controller 2
return 0;
default: // disabled/unused APU test registers
return cpuBusMDR;
}
}
else {
return cart.readPrg(addr);
}
}
void Console::cpuWrite(uint16_t addr, uint8_t value) {
cpuBusMDR = value;
if (addr < 0x2000) {
cpuRam[addr % 0x800] = value;
}
else if (addr < 0x4000) {
int port = addr % 8;
switch (port) {
case 0: // 0x2000
ppu.setCTRL(value);
break;
case 1: // 0x2001
ppu.setMASK(value);
break;
case 2: // 0x2002
break;
case 3: // 0x2003
ppu.setOAMADDR(value);
break;
case 4: // 0x2004
ppu.setOAMDATA(value);
break;
case 5: // 0x2005
ppu.setSCROLL(value);
break;
case 6: // 0x2006
ppu.setADDR(value);
break;
case 7: // 0x2007
ppu.setDATA(value);
break;
}
}
else if (addr < 0x4020) {
if (addr == 0x4014) {
uint16_t startAddr = ((uint16_t)value) << 8;
for (int i = 0; i < 256; ++i) {
ppu.setOAMDATA(cpuRead(startAddr + i));
}
cpu.suspend(514);
}
else if (addr == 0x4016) {
controller1.setStrobe(!!(value & 0x1));
}
else if (addr < 0x4018) {
apu.writeRegister(addr, value);
}
}
else {
cart.writePrg(addr, value);
}
}
<commit_msg>Define callbacks in intermediate variables for readability<commit_after>#include <string>
#include <functional>
#include <Console.h>
#include <CPU.h>
#include <APU.h>
#include <PPU.h>
#include <Cart.h>
#include <Controller.h>
#include <Divider.h>
void Console::boot() {
ReadBus cpuReadCallback = [this] (uint16_t addr) {
return cpuRead(addr);
};
WriteBus cpuWriteCallback = [this] (uint16_t addr, uint8_t data) {
cpuWrite(addr,data);
};
cpu.boot(cpuReadCallback, cpuWriteCallback);
NMI nmiCallback = [this] () {cpu.signalNMI();};
ppu.boot(&cart, nmiCallback);
}
bool Console::loadINesFile(std::string fileName) {
return cart.loadFile(fileName);
}
uint32_t *Console::getFrameBuffer() {
return ppu.getFrameBuffer();
}
void Console::runForOneFrame() {
do {
tick();
} while (!ppu.endOfFrame());
apu.endFrame();
}
void Console::tick() {
cpuDivider.tick();
if (cpuDivider.hasClocked()) {
cpu.tick();
}
ppu.tick();
}
uint8_t Console::cpuRead(uint16_t addr) {
if (addr < 0x2000) {
return cpuRam[addr % 0x800];
}
else if (addr < 0x4000) {
int port = addr % 8;
switch (port) {
case 0: // 0x2000
return cpuBusMDR;
case 1: // 0x2001
return cpuBusMDR;
case 2: // 0x2002
return ppu.getSTATUS();
case 3: // 0x2003
return cpuBusMDR;
case 4: // 0x2004
return ppu.getOAMDATA();
case 5: // 0x2005
return cpuBusMDR;
case 6: // 0x2006
return cpuBusMDR;
case 7: // 0x2007
return ppu.getDATA();
}
}
else if (addr < 0x4020) {
switch (addr) {
case 0x4015:
return apu.getStatus();
case 0x4016:
return controller1.poll();
case 0x4017: // TODO: controller 2
return 0;
default: // disabled/unused APU test registers
return cpuBusMDR;
}
}
else {
return cart.readPrg(addr);
}
}
void Console::cpuWrite(uint16_t addr, uint8_t value) {
cpuBusMDR = value;
if (addr < 0x2000) {
cpuRam[addr % 0x800] = value;
}
else if (addr < 0x4000) {
int port = addr % 8;
switch (port) {
case 0: // 0x2000
ppu.setCTRL(value);
break;
case 1: // 0x2001
ppu.setMASK(value);
break;
case 2: // 0x2002
break;
case 3: // 0x2003
ppu.setOAMADDR(value);
break;
case 4: // 0x2004
ppu.setOAMDATA(value);
break;
case 5: // 0x2005
ppu.setSCROLL(value);
break;
case 6: // 0x2006
ppu.setADDR(value);
break;
case 7: // 0x2007
ppu.setDATA(value);
break;
}
}
else if (addr < 0x4020) {
if (addr == 0x4014) {
uint16_t startAddr = ((uint16_t)value) << 8;
for (int i = 0; i < 256; ++i) {
ppu.setOAMDATA(cpuRead(startAddr + i));
}
cpu.suspend(514);
}
else if (addr == 0x4016) {
controller1.setStrobe(!!(value & 0x1));
}
else if (addr < 0x4018) {
apu.writeRegister(addr, value);
}
}
else {
cart.writePrg(addr, value);
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Library
Module: Cylinder.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "Cylinder.hh"
// Description
// Construct cylinder radius of 0.5.
vlCylinder::vlCylinder()
{
this->Radius = 0.5;
}
// Description
// Evaluate cylinder equation R^2 - ((x-x0)^2 + (y-y0)^2 + (z-z0)^2) = 0.
float vlCylinder::EvaluateFunction(float x[3])
{
return 0;
}
// Description
// Evaluate cylinder function gradient.
void vlCylinder::EvaluateGradient(float x[3], float g[3])
{
}
void vlCylinder::PrintSelf(ostream& os, vlIndent indent)
{
vlImplicitFunction::PrintSelf(os,indent);
os << indent << "Radius: " << this->Radius << "\n";
}
<commit_msg>ENH: Final implementation...<commit_after>/*=========================================================================
Program: Visualization Library
Module: Cylinder.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "Cylinder.hh"
// Description
// Construct cylinder radius of 0.5.
vlCylinder::vlCylinder()
{
this->Radius = 0.5;
}
// Description
// Evaluate cylinder equation F(x,y,z) = (x-x0)^2 + (y-y0)^2 - R^2.
float vlCylinder::EvaluateFunction(float x[3])
{
return x[0]*x[0] + x[1]*x[1] - this->Radius*this->Radius;
}
// Description
// Evaluate cylinder function gradient.
void vlCylinder::EvaluateGradient(float x[3], float g[3])
{
g[0] = 2.0 * x[0];
g[1] = 2.0 * x[1];
g[2] = 0.0;
}
void vlCylinder::PrintSelf(ostream& os, vlIndent indent)
{
vlImplicitFunction::PrintSelf(os,indent);
os << indent << "Radius: " << this->Radius << "\n";
}
<|endoftext|>
|
<commit_before>#ifndef DVMBASE
#define DVMBASE
#include "BaseTypes.hpp"
#include "Body.hpp"
#include "VortexBlobs.hpp"
#include "VortexSheet.hpp"
#include "XmlHandler.hpp"
#include "Random.hpp"
#include "pugiconfig.hpp"
#include "pugixml.hpp"
#include <algorithm>
#include <armadillo>
#include <cmath>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string.h>
#include <string>
/// DMV class contaning all the elements of the DVM
class DVMBase
{
private:
VortexBlobs m_vortex; ///< The point vortices
VortexSheet m_vortsheet; ///< The vortex sheet
Body m_body; ///< The solid body
VortexBlobs m_probe; ///< The probe???
Matrix m_infM; ///< Influence matrix
Random m_rand; ///< Random number generation
/** @name Output files */
///@{
std::ofstream dev_dvm; ///< Vortex position
std::ofstream dev_Num; ///< Number of vortices
std::ofstream dev_gamma; ///< Vortex sheet strength
std::ofstream dev_loads; ///< Forces
std::ofstream dev_probe; ///< Velocity
///@}
double m_dt; ///< Timestep
double m_nu; ///< Kinematic viscosity
double m_Ux; ///< Free stream velocity in x
double m_Uz; ///< Free stream velocity in ym_n, m_np;
double m_n; ///< Number of body points
double m_kernel_threshold; ///< Kernel threshold
double m_sigma_cutoff; ///< Cut-off distance
double m_time; ///< Current simulation time
unsigned m_step; ///< Current timestep
unsigned m_steps; ///< Total timesteps
unsigned m_maxGamma; ///< Maximum value of the vorticity
/** @name Reading and writing */
///@{
XmlHandler m_xml; ///< xml handler
std::string m_in_dir; ///< input directory
std::string m_out_dir; ///< output directory
std::string m_domain_file; ///< body geometry file
///@}
std::string m_timestamp;
// some constants
double m_pi; ///< pi
double m_rpi2; ///< 1 / 2pi
// Loads related variables
double m_fx; ///< Force on the body in x
double m_fz; ///< Force on the body in z
double m_rho; ///< Density of the fluid
private:
public:
DVMBase(XmlHandler &xml);
/** @name General Initialisation */
///@{
/// Initialise the object
void init(XmlHandler &xml, std::string timestamp);
/// Read the input geometry file
void read_input_coord();
/// Initialise the output files
void init_outputs();
///@}
/// Compute the influence matrix
/** Computed using the coefficients after Morgenthal */
void compute_influence_matrix();
/** @name Vortex sheet related methods */
///@{
/// Initialise the vortex sheet
void form_vortex_sheet();
/// Solve for the vortex sheet
void solvevortexsheet();
/// Update the vorticity on each sheet
void save_vort();
///@}
/// Compute the forces on the body
void compute_loads();
/// Convect point vortices
void convect(unsigned order);
/** @name Methods related to diffusion */
///@{
/// Move the point vortices using the random walk
void diffrw();
/// Generate vorticity on the boundary and release into the flow
void diffuse_vs_rw();
///@}
/// Reflect particles generated released inside the body outside
void reflect();
/// Write the output file
/** Happens at each time step */
void write_outputs();
/** @name Timeloop control */
///@{
/// Increment the time step
void increment_step();
/// Get the size of the vortex sheet
unsigned get_vs_size();
/// Get number of total timesteps
unsigned get_steps();
/// Simulation time of the current time step
double get_time();
///@}
/// Total number of point vortices at a given time
unsigned get_size();
/// Get the velocities at a given point
void probe_velocities();
private:
/// Compute the vortex sheet boundary condition
void vortexsheetbc();
/// Mirror a particle from one side of the boundary to the other
std::vector<double> mirror(double x_init,
double z_init,
double x_0,
double z_0,
double x_1,
double z_1);
/// Determine if a particle lies inside the solid body
int inside_body(double x, double z);
/// This is all the useless stuff below //////////////////////
/*
// read paramters
void init_dipole(double zdistance,
double xdistance,
unsigned nvb1,
unsigned nvb2,
double radius1,
double radius2);
// Vortex sheet stuff
void imagebc();
// Diffusion stuff
void diffpse(double nu, double dt);
// Housekeeping stuff
void delete_vort();
void absorb();
// Diagnostics
void compute_strouhal();
std::vector<double> uvs, wvs, uI, wI;
// std::vector<double> xi_rw, eta_rw; // Why were these here???
// std::vector<double> m_Gamma_abs;
// double m_GammaDel,
// double m_St;
*/
};
#endif
<commit_msg>Fix type of m_maxGamma<commit_after>#ifndef DVMBASE
#define DVMBASE
#include "BaseTypes.hpp"
#include "Body.hpp"
#include "VortexBlobs.hpp"
#include "VortexSheet.hpp"
#include "XmlHandler.hpp"
#include "Random.hpp"
#include "pugiconfig.hpp"
#include "pugixml.hpp"
#include <algorithm>
#include <armadillo>
#include <cmath>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string.h>
#include <string>
/// DMV class contaning all the elements of the DVM
class DVMBase
{
private:
VortexBlobs m_vortex; ///< The point vortices
VortexSheet m_vortsheet; ///< The vortex sheet
Body m_body; ///< The solid body
VortexBlobs m_probe; ///< The probe???
Matrix m_infM; ///< Influence matrix
Random m_rand; ///< Random number generation
/** @name Output files */
///@{
std::ofstream dev_dvm; ///< Vortex position
std::ofstream dev_Num; ///< Number of vortices
std::ofstream dev_gamma; ///< Vortex sheet strength
std::ofstream dev_loads; ///< Forces
std::ofstream dev_probe; ///< Velocity
///@}
double m_dt; ///< Timestep
double m_nu; ///< Kinematic viscosity
double m_Ux; ///< Free stream velocity in x
double m_Uz; ///< Free stream velocity in ym_n, m_np;
double m_n; ///< Number of body points
double m_kernel_threshold; ///< Kernel threshold
double m_sigma_cutoff; ///< Cut-off distance
double m_time; ///< Current simulation time
unsigned m_step; ///< Current timestep
unsigned m_steps; ///< Total timesteps
double m_maxGamma; ///< Maximum value of the vorticity
/** @name Reading and writing */
///@{
XmlHandler m_xml; ///< xml handler
std::string m_in_dir; ///< input directory
std::string m_out_dir; ///< output directory
std::string m_domain_file; ///< body geometry file
///@}
std::string m_timestamp;
// some constants
double m_pi; ///< pi
double m_rpi2; ///< 1 / 2pi
// Loads related variables
double m_fx; ///< Force on the body in x
double m_fz; ///< Force on the body in z
double m_rho; ///< Density of the fluid
private:
public:
DVMBase(XmlHandler &xml);
/** @name General Initialisation */
///@{
/// Initialise the object
void init(XmlHandler &xml, std::string timestamp);
/// Read the input geometry file
void read_input_coord();
/// Initialise the output files
void init_outputs();
///@}
/// Compute the influence matrix
/** Computed using the coefficients after Morgenthal */
void compute_influence_matrix();
/** @name Vortex sheet related methods */
///@{
/// Initialise the vortex sheet
void form_vortex_sheet();
/// Solve for the vortex sheet
void solvevortexsheet();
/// Update the vorticity on each sheet
void save_vort();
///@}
/// Compute the forces on the body
void compute_loads();
/// Convect point vortices
void convect(unsigned order);
/** @name Methods related to diffusion */
///@{
/// Move the point vortices using the random walk
void diffrw();
/// Generate vorticity on the boundary and release into the flow
void diffuse_vs_rw();
///@}
/// Reflect particles generated released inside the body outside
void reflect();
/// Write the output file
/** Happens at each time step */
void write_outputs();
/** @name Timeloop control */
///@{
/// Increment the time step
void increment_step();
/// Get the size of the vortex sheet
unsigned get_vs_size();
/// Get number of total timesteps
unsigned get_steps();
/// Simulation time of the current time step
double get_time();
///@}
/// Total number of point vortices at a given time
unsigned get_size();
/// Get the velocities at a given point
void probe_velocities();
private:
/// Compute the vortex sheet boundary condition
void vortexsheetbc();
/// Mirror a particle from one side of the boundary to the other
std::vector<double> mirror(double x_init,
double z_init,
double x_0,
double z_0,
double x_1,
double z_1);
/// Determine if a particle lies inside the solid body
int inside_body(double x, double z);
/// This is all the useless stuff below //////////////////////
/*
// read paramters
void init_dipole(double zdistance,
double xdistance,
unsigned nvb1,
unsigned nvb2,
double radius1,
double radius2);
// Vortex sheet stuff
void imagebc();
// Diffusion stuff
void diffpse(double nu, double dt);
// Housekeeping stuff
void delete_vort();
void absorb();
// Diagnostics
void compute_strouhal();
std::vector<double> uvs, wvs, uI, wI;
// std::vector<double> xi_rw, eta_rw; // Why were these here???
// std::vector<double> m_Gamma_abs;
// double m_GammaDel,
// double m_St;
*/
};
#endif
<|endoftext|>
|
<commit_before>#include <Element.h>
#include <FWPlatform.h>
#include <TextLabel.h>
#include <LinearLayout.h>
#include <Command.h>
#include <FWApplication.h>
#include <cassert>
using namespace std;
void
Element::initialize(FWPlatform * _platform) {
assert(_platform);
if (_platform) {
platform = _platform;
internal_id = platform->getNextInternalId();
}
assert(isInitialized());
}
void
Element::initializeChildren() {
assert(isInitialized());
if (isInitialized()) {
for (auto & c : getChildren()) {
c->initialize(platform);
c->initializeChildren();
}
}
}
void
Element::setError(bool t) {
if ((t && !has_error) || (!t && has_error)) {
has_error = t;
cerr << "setting error to " << has_error << endl;
Command c(Command::SET_ERROR, getInternalId());
c.setValue(t ? 1 : 0);
if (t) c.setTextValue("Arvo ei kelpaa!");
sendCommand(c);
}
}
void
Element::style(const std::string & key, const std::string & value) {
Command c(Command::SET_STYLE, getInternalId());
c.setTextValue(key);
c.setTextValue2(value);
sendCommand(c);
}
void
Element::sendCommand(const Command & command) {
assert(platform);
platform->sendCommand2(command);
}
Element &
Element::addHeading(const std::string & text) {
return addChild(make_shared<HeadingText>(text));
}
Element &
Element::addText(const std::string & text) {
return addChild(make_shared<TextLabel>(text));
}
LinearLayout &
Element::addHorizontalLayout() {
auto l = make_shared<LinearLayout>(FW_HORIZONTAL);
addChild(l);
return *l;
}
LinearLayout &
Element::addVerticalLayout() {
auto l = make_shared<LinearLayout>(FW_VERTICAL);
addChild(l);
return *l;
}
void
Element::onEvent(Event & ev) {
if (!ev.isHandled()) {
if (ev.isBroadcast()) {
for (auto & c : getChildren()){
ev.dispatch(*c);
}
} else if (parent) {
ev.dispatch(*parent);
}
}
}
void
Element::showMessageDialog(const std::string & title, const std::string & text) {
Command c(Command::SHOW_MESSAGE_DIALOG, getParentInternalId(), getInternalId());
c.setTextValue(title);
c.setTextValue2(text);
sendCommand(c);
}
std::string
Element::showInputDialog(const std::string & title, const std::string & text) {
Command c(Command::SHOW_INPUT_DIALOG, getParentInternalId(), getInternalId());
c.setTextValue(title);
c.setTextValue2(text);
sendCommand(c);
return platform->getModalResultText();
}
FWApplication &
Element::getApplication() {
auto p = getPlatform().getFirstChild();
return dynamic_cast<FWApplication&>(*p);
}
const FWApplication &
Element::getApplication() const {
auto p = getPlatform().getFirstChild();
return dynamic_cast<const FWApplication&>(*p);
}
<commit_msg>refactor<commit_after>#include <Element.h>
#include <FWPlatform.h>
#include <TextLabel.h>
#include <LinearLayout.h>
#include <Command.h>
#include <FWApplication.h>
#include <cassert>
using namespace std;
void
Element::initialize(FWPlatform * _platform) {
assert(_platform);
if (_platform) {
platform = _platform;
internal_id = platform->getNextInternalId();
}
assert(isInitialized());
}
void
Element::initializeChildren() {
assert(isInitialized());
if (isInitialized()) {
for (auto & c : getChildren()) {
c->initialize(platform);
c->initializeChildren();
}
}
}
void
Element::setError(bool t) {
if ((t && !has_error) || (!t && has_error)) {
has_error = t;
cerr << "setting error to " << has_error << endl;
Command c(Command::SET_ERROR, getInternalId());
c.setValue(t ? 1 : 0);
if (t) c.setTextValue("Arvo ei kelpaa!");
sendCommand(c);
}
}
void
Element::style(const std::string & key, const std::string & value) {
Command c(Command::SET_STYLE, getInternalId());
c.setTextValue(key);
c.setTextValue2(value);
sendCommand(c);
}
void
Element::sendCommand(const Command & command) {
assert(platform);
platform->sendCommand2(command);
}
Element &
Element::addHeading(const std::string & text) {
return addChild(make_shared<HeadingText>(text));
}
Element &
Element::addText(const std::string & text) {
return addChild(make_shared<TextLabel>(text));
}
LinearLayout &
Element::addHorizontalLayout() {
return addChild(make_shared<LinearLayout>(FW_HORIZONTAL));
}
LinearLayout &
Element::addVerticalLayout() {
return addChild(make_shared<LinearLayout>(FW_VERTICAL));
}
void
Element::onEvent(Event & ev) {
if (!ev.isHandled()) {
if (ev.isBroadcast()) {
for (auto & c : getChildren()){
ev.dispatch(*c);
}
} else if (parent) {
ev.dispatch(*parent);
}
}
}
void
Element::showMessageDialog(const std::string & title, const std::string & text) {
Command c(Command::SHOW_MESSAGE_DIALOG, getParentInternalId(), getInternalId());
c.setTextValue(title);
c.setTextValue2(text);
sendCommand(c);
}
std::string
Element::showInputDialog(const std::string & title, const std::string & text) {
Command c(Command::SHOW_INPUT_DIALOG, getParentInternalId(), getInternalId());
c.setTextValue(title);
c.setTextValue2(text);
sendCommand(c);
return platform->getModalResultText();
}
FWApplication &
Element::getApplication() {
auto p = getPlatform().getFirstChild();
return dynamic_cast<FWApplication&>(*p);
}
const FWApplication &
Element::getApplication() const {
auto p = getPlatform().getFirstChild();
return dynamic_cast<const FWApplication&>(*p);
}
<|endoftext|>
|
<commit_before>/******************************************************************************\
* File: appl.cpp
* Purpose: Implementation of sample classes for wxextension
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009, Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/aboutdlg.h>
#include <wx/numdlg.h>
#include <wx/textfile.h>
#include <wx/extension/renderer.h>
#include <wx/extension/configdialog.h>
#include "appl.h"
#ifndef __WXMSW__
#include "appl.xpm"
#endif
enum
{
ID_FIRST = 15000,
ID_CONFIG_DLG,
ID_CONFIG_DLG_READONLY,
ID_LOCALE_SHOW_DIR,
ID_STATISTICS_SHOW,
ID_STC_CONFIG_DLG,
ID_STC_FLAGS,
ID_STC_GOTO,
ID_STC_SPLIT,
ID_STC_LEXER,
ID_LAST,
};
BEGIN_EVENT_TABLE(wxExSampleFrame, wxExFrame)
EVT_MENU_RANGE(wxID_CUT, wxID_CLEAR, wxExSampleFrame::OnCommand)
EVT_MENU_RANGE(wxID_OPEN, wxID_PREFERENCES, wxExSampleFrame::OnCommand)
EVT_MENU_RANGE(ID_FIRST, ID_LAST, wxExSampleFrame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND, wxExSampleFrame::OnCommand)
END_EVENT_TABLE()
IMPLEMENT_APP(wxExSampleApp)
bool wxExSampleApp::OnInit()
{
SetAppName("wxExSample");
if (!wxExApp::OnInit())
{
return false;
}
SetLogging();
wxExSampleFrame *frame = new wxExSampleFrame();
frame->Show(true);
SetTopWindow(frame);
return true;
}
#if wxUSE_GRID
wxExSampleDir::wxExSampleDir(
const wxString& fullpath, const wxString& findfiles, wxExGrid* grid)
: wxExDir(fullpath, findfiles)
, m_Grid(grid)
{
}
void wxExSampleDir::OnFile(const wxString& file)
{
m_Grid->AppendRows(1);
const int no = m_Grid->GetNumberRows() - 1;
m_Grid->SetCellValue(no, 0, wxString::Format("cell%d", no));
m_Grid->SetCellValue(no, 1, file);
wxExRenderer* renderer = new wxExRenderer(
wxExRenderer::CELL_CROSS, *wxGREEN_PEN, *wxRED_PEN);
m_Grid->SetCellRenderer(no, 0, renderer);
// Let's make these cells readonly and colour them, so we can test
// things like cutting and dropping is forbidden.
m_Grid->SetReadOnly(no, 1);
m_Grid->SetCellBackgroundColour(no, 1, *wxLIGHT_GREY);
}
#endif
wxExSampleFrame::wxExSampleFrame()
: wxExManagedFrame(NULL, wxID_ANY, wxTheApp->GetAppName())
, m_FlagsSTC(0)
{
SetIcon(wxICON(appl));
wxExMenu* menuFile = new wxExMenu;
menuFile->Append(wxID_OPEN);
menuFile->AppendSeparator();
menuFile->AppendPrint();
menuFile->AppendSeparator();
menuFile->Append(ID_LOCALE_SHOW_DIR, _("Show Locale Dir"));
menuFile->AppendSeparator();
menuFile->Append(ID_STATISTICS_SHOW, _("Show Statistics"));
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
wxExMenu* menuConfig = new wxExMenu;
menuConfig->Append(ID_CONFIG_DLG, wxExEllipsed(_("Config Dialog")));
menuConfig->Append(ID_CONFIG_DLG_READONLY, wxExEllipsed(_("Config Dialog Readonly")));
wxExMenu* menuSTC = new wxExMenu;
menuSTC->Append(ID_STC_FLAGS, wxExEllipsed(_("Open Flag")));
menuSTC->AppendSeparator();
menuSTC->Append(ID_STC_CONFIG_DLG, wxExEllipsed(_("Config Dialog")));
menuSTC->Append(ID_STC_GOTO, wxExEllipsed(_("Goto Dialog")));
menuSTC->Append(ID_STC_LEXER, wxExEllipsed(_("Lexer Dialog")));
menuSTC->AppendSeparator();
menuSTC->Append(ID_STC_SPLIT, _("Split"));
menuSTC->AppendSeparator();
menuSTC->Append(ID_EDIT_MACRO_START_RECORD, _("Start Record"));
menuSTC->Append(ID_EDIT_MACRO_STOP_RECORD, _("Stop Record"));
menuSTC->Append(ID_EDIT_MACRO_PLAYBACK, _("Playback"));
wxExMenu* menuHelp = new wxExMenu;
menuHelp->Append(wxID_ABOUT);
wxMenuBar *menubar = new wxMenuBar;
menubar->Append(menuFile, _("&File"));
menubar->Append(menuSTC, _("&STC"));
menubar->Append(menuConfig, _("&Config"));
menubar->Append(menuHelp, _("&Help"));
SetMenuBar(menubar);
m_Notebook = new wxExNotebook(this, NULL);
#if wxUSE_GRID
m_Grid = new wxExGrid(m_Notebook);
#endif
m_ListView = new wxExListView(m_Notebook);
m_STC = new wxExSTC(this);
m_STCShell = new wxExSTCShell(this, ">", wxTextFile::GetEOL(), true, 10);
GetManager().AddPane(m_STC, wxAuiPaneInfo().CenterPane().CloseButton(false).MaximizeButton(true).Name("wxExSTC"));
GetManager().AddPane(m_STCShell, wxAuiPaneInfo().Bottom().MinSize(wxSize(250, 250)));
GetManager().AddPane(m_Notebook, wxAuiPaneInfo().Left().MinSize(wxSize(250, 250)));
GetManager().Update();
assert(wxExApp::GetLexers());
wxExSTC* st = new wxExSTC(this, wxExApp::GetLexers()->GetFileName());
m_Notebook->AddPage(st, wxExApp::GetLexers()->GetFileName().GetFullName());
m_Notebook->AddPage(m_ListView, "wxExListView");
#if wxUSE_GRID
m_Notebook->AddPage(m_Grid, "wxExGrid");
m_Grid->CreateGrid(0, 0);
m_Grid->AppendCols(2);
wxExSampleDir dir(wxGetCwd(), "appl.*", m_Grid);
dir.FindFiles();
m_Grid->AutoSizeColumns();
#endif
m_ListView->SetSingleStyle(wxLC_REPORT); // wxLC_ICON);
m_ListView->InsertColumn(wxExColumn("String", wxExColumn::COL_STRING));
m_ListView->InsertColumn(wxExColumn("Number", wxExColumn::COL_INT));
m_ListView->InsertColumn(wxExColumn("Float", wxExColumn::COL_FLOAT));
m_ListView->InsertColumn(wxExColumn("Date", wxExColumn::COL_DATE));
const int items = 50;
for (int i = 0; i < items; i++)
{
wxExListItem item(m_ListView, wxString::Format("item%d", i));
item.Insert();
item.SetColumnText(1, wxString::Format("%d", i));
item.SetColumnText(2, wxString::Format("%f", (float)i / 2.0));
item.SetColumnText(3, wxDateTime::Now().Format());
// Set some images.
if (i == 0) item.SetImage(wxART_CDROM);
else if (i == 1) item.SetImage(wxART_REMOVABLE);
else if (i == 2) item.SetImage(wxART_FOLDER);
else if (i == 3) item.SetImage(wxART_FOLDER_OPEN);
else if (i == 4) item.SetImage(wxART_GO_DIR_UP);
else if (i == 5) item.SetImage(wxART_EXECUTABLE_FILE);
else if (i == 6) item.SetImage(wxART_NORMAL_FILE);
else item.SetImage(wxART_TICK_MARK);
}
#if wxUSE_STATUSBAR
std::vector<wxExPane> panes;
panes.push_back(wxExPane("PaneText", -3));
panes.push_back(wxExPane("PaneFileType", 50, _("File type")));
panes.push_back(wxExPane("PaneCells", 60, _("Cells")));
panes.push_back(wxExPane("PaneItems", 60, _("Items")));
panes.push_back(wxExPane("PaneLines", 100, _("Lines")));
panes.push_back(wxExPane("PaneLexer", 60, _("Lexer")));
SetupStatusBar(panes);
#endif
CreateToolBar();
m_ToolBar->AddTool(wxID_OPEN);
m_ToolBar->AddTool(wxID_SAVE);
m_ToolBar->AddTool(wxID_PRINT);
m_ToolBar->AddTool(wxID_EXIT);
m_ToolBar->Realize();
}
void wxExSampleFrame::ConfigDialogApplied(wxWindowID /* id */)
{
m_STC->ConfigGet();
m_STCShell->ConfigGet();
}
wxExGrid* wxExSampleFrame::GetGrid()
{
return m_Grid;
}
wxExListView* wxExSampleFrame::GetListView()
{
return m_ListView;
}
wxExSTC* wxExSampleFrame::GetSTC()
{
if (m_STC->IsShown())
{
return m_STC;
}
else if (m_STCShell->IsShown())
{
return m_STCShell;
}
return NULL;
}
void wxExSampleFrame::OnCommand(wxCommandEvent& event)
{
m_Statistics.Inc(wxString::Format("%d", event.GetId()));
switch (event.GetId())
{
case wxID_ABOUT:
{
wxAboutDialogInfo info;
info.SetIcon(GetIcon());
info.SetVersion(wxEX_VERSION_STRING);
info.AddDeveloper(wxVERSION_STRING);
info.SetCopyright(_("(c) 1998-2009 Anton van Wezenbeek."));
wxAboutBox(info);
}
break;
case wxID_EXIT: Close(true); break;
case wxID_OPEN:
{
wxExFileDialog dlg(this, m_STC);
if (dlg.ShowModal() == wxID_CANCEL) return;
wxStopWatch sw;
m_STC->Open(dlg.GetPath(), 0, wxEmptyString, m_FlagsSTC);
const long stop = sw.Time();
#if wxUSE_STATUSBAR
StatusText(wxString::Format("wxExSTC::Open:%ld milliseconds, %d bytes", stop, m_STC->GetTextLength()));
#endif
}
break;
case wxID_PREVIEW: m_ListView->PrintPreview(); break;
case wxID_PRINT: m_ListView->Print(); break;
case wxID_PRINT_SETUP: wxExApp::GetPrinter()->PageSetup(); break;
case wxID_SAVE:
m_STC->FileSave();
if (m_STC->GetFileName().GetFullPath() == wxExApp::GetLexers()->GetFileName().GetFullPath())
{
if (wxExApp::GetLexers()->Read())
{
wxLogMessage("File contains: %d lexers", wxExApp::GetLexers()->Count());
// As the lexer might have changed, update status bar field as well.
#if wxUSE_STATUSBAR
m_STC->UpdateStatusBar("PaneLexer");
#endif
}
}
break;
case ID_CONFIG_DLG:
{
std::vector<wxExConfigItem> v;
for (size_t h = 1; h <= 25; h++)
{
v.push_back(wxExConfigItem(wxString::Format(_("check%d"), h), CONFIG_CHECKBOX, "Checkboxes"));
}
for (size_t i = 1; i <= 25; i++)
{
v.push_back(wxExConfigItem(wxString::Format(_("colour%d"), i), CONFIG_COLOUR, "Colours"));
}
for (size_t j = 1; j <= 10; j++)
{
v.push_back(wxExConfigItem(wxString::Format(_("integer%d"), j), CONFIG_INT, "Integers", true));
}
for (size_t k = 1; k <= 10; k++)
{
v.push_back(wxExConfigItem(wxString::Format(_("spin%d"), k), 1, k, wxString("Spin controls")));
}
for (size_t l = 1; l <= 10; l++)
{
v.push_back(wxExConfigItem(wxString::Format(_("string%d"), l), CONFIG_STRING, "Strings"));
}
for (size_t m = 1; m <= 10; m++)
{
v.push_back(wxExConfigItem(wxString::Format(_("combobox%d"), m), CONFIG_COMBOBOX, "Comboboxes"));
}
v.push_back(wxExConfigItem(_("dirpicker"), CONFIG_DIRPICKERCTRL, "Pickers"));
v.push_back(wxExConfigItem(_("filepicker"), CONFIG_FILEPICKERCTRL, "Pickers"));
wxExConfigDialog* dlg = new wxExConfigDialog(
this,
wxExApp::GetConfig(),
v,
_("Config Dialog"),
wxEmptyString,
10,
6,
wxAPPLY | wxCANCEL,
wxID_ANY,
wxDefaultPosition,
wxSize(400,300));
dlg->Show();
// Dialog is not placed nicely.
//GetManager().GetPane("NOTEBOOK"));
//GetManager().Update();
}
break;
case ID_CONFIG_DLG_READONLY:
{
std::vector<wxExConfigItem> v;
v.push_back(wxExConfigItem(_("filepicker"), CONFIG_FILEPICKERCTRL));
for (size_t j = 1; j <= 10; j++)
{
v.push_back(wxExConfigItem(wxString::Format(_("integer%d"), j), CONFIG_INT));
}
wxExConfigDialog* dlg = new wxExConfigDialog(
this,
wxExApp::GetConfig(),
v,
_("Config Dialog Readonly"),
wxEmptyString,
0,
2,
wxCANCEL);
dlg->Show();
}
break;
case ID_LOCALE_SHOW_DIR:
wxLogMessage(wxExApp::GetCatalogDir());
break;
case ID_SHELL_COMMAND:
m_STCShell->Prompt("Hello '" + event.GetString() + "' from the shell");
break;
case ID_STATISTICS_SHOW:
m_Notebook->AddPage(m_Statistics.Show(m_Notebook), "Statistics");
break;
case ID_STC_CONFIG_DLG:
wxExSTC::ConfigDialog(
this,
_("Editor Options"),
wxExSTC::STC_CONFIG_MODELESS | wxExSTC::STC_CONFIG_WITH_APPLY);
break;
case ID_STC_FLAGS:
{
long value = wxGetNumberFromUser(
"Input:",
wxEmptyString,
"STC Open Flag",
m_FlagsSTC,
0,
0xFFFF);
if (value != -1)
{
m_FlagsSTC = value;
}
}
break;
case ID_STC_GOTO: m_STC->GotoDialog(); break;
case ID_STC_LEXER: m_STC->LexerDialog(); break;
case ID_STC_SPLIT:
{
wxExSTC* stc = new wxExSTC(*m_STC);
m_Notebook->AddPage(
stc,
wxString::Format("stc%d", stc->GetId()),
m_STC->GetFileName().GetFullName());
stc->SetDocPointer(m_STC->GetDocPointer());
}
break;
default:
wxFAIL;
break;
}
}
<commit_msg>and one more fix<commit_after>/******************************************************************************\
* File: appl.cpp
* Purpose: Implementation of sample classes for wxextension
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009, Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/aboutdlg.h>
#include <wx/numdlg.h>
#include <wx/textfile.h>
#include <wx/extension/configdialog.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/renderer.h>
#include "appl.h"
#ifndef __WXMSW__
#include "appl.xpm"
#endif
enum
{
ID_FIRST = 15000,
ID_CONFIG_DLG,
ID_CONFIG_DLG_READONLY,
ID_LOCALE_SHOW_DIR,
ID_STATISTICS_SHOW,
ID_STC_CONFIG_DLG,
ID_STC_FLAGS,
ID_STC_GOTO,
ID_STC_SPLIT,
ID_STC_LEXER,
ID_LAST,
};
BEGIN_EVENT_TABLE(wxExSampleFrame, wxExFrame)
EVT_MENU_RANGE(wxID_CUT, wxID_CLEAR, wxExSampleFrame::OnCommand)
EVT_MENU_RANGE(wxID_OPEN, wxID_PREFERENCES, wxExSampleFrame::OnCommand)
EVT_MENU_RANGE(ID_FIRST, ID_LAST, wxExSampleFrame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND, wxExSampleFrame::OnCommand)
END_EVENT_TABLE()
IMPLEMENT_APP(wxExSampleApp)
bool wxExSampleApp::OnInit()
{
SetAppName("wxExSample");
if (!wxExApp::OnInit())
{
return false;
}
SetLogging();
wxExSampleFrame *frame = new wxExSampleFrame();
frame->Show(true);
SetTopWindow(frame);
return true;
}
#if wxUSE_GRID
wxExSampleDir::wxExSampleDir(
const wxString& fullpath, const wxString& findfiles, wxExGrid* grid)
: wxExDir(fullpath, findfiles)
, m_Grid(grid)
{
}
void wxExSampleDir::OnFile(const wxString& file)
{
m_Grid->AppendRows(1);
const int no = m_Grid->GetNumberRows() - 1;
m_Grid->SetCellValue(no, 0, wxString::Format("cell%d", no));
m_Grid->SetCellValue(no, 1, file);
wxExRenderer* renderer = new wxExRenderer(
wxExRenderer::CELL_CROSS, *wxGREEN_PEN, *wxRED_PEN);
m_Grid->SetCellRenderer(no, 0, renderer);
// Let's make these cells readonly and colour them, so we can test
// things like cutting and dropping is forbidden.
m_Grid->SetReadOnly(no, 1);
m_Grid->SetCellBackgroundColour(no, 1, *wxLIGHT_GREY);
}
#endif
wxExSampleFrame::wxExSampleFrame()
: wxExManagedFrame(NULL, wxID_ANY, wxTheApp->GetAppName())
, m_FlagsSTC(0)
{
SetIcon(wxICON(appl));
wxExMenu* menuFile = new wxExMenu;
menuFile->Append(wxID_OPEN);
menuFile->AppendSeparator();
menuFile->AppendPrint();
menuFile->AppendSeparator();
menuFile->Append(ID_LOCALE_SHOW_DIR, _("Show Locale Dir"));
menuFile->AppendSeparator();
menuFile->Append(ID_STATISTICS_SHOW, _("Show Statistics"));
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
wxExMenu* menuConfig = new wxExMenu;
menuConfig->Append(ID_CONFIG_DLG, wxExEllipsed(_("Config Dialog")));
menuConfig->Append(ID_CONFIG_DLG_READONLY, wxExEllipsed(_("Config Dialog Readonly")));
wxExMenu* menuSTC = new wxExMenu;
menuSTC->Append(ID_STC_FLAGS, wxExEllipsed(_("Open Flag")));
menuSTC->AppendSeparator();
menuSTC->Append(ID_STC_CONFIG_DLG, wxExEllipsed(_("Config Dialog")));
menuSTC->Append(ID_STC_GOTO, wxExEllipsed(_("Goto Dialog")));
menuSTC->Append(ID_STC_LEXER, wxExEllipsed(_("Lexer Dialog")));
menuSTC->AppendSeparator();
menuSTC->Append(ID_STC_SPLIT, _("Split"));
menuSTC->AppendSeparator();
menuSTC->Append(ID_EDIT_MACRO_START_RECORD, _("Start Record"));
menuSTC->Append(ID_EDIT_MACRO_STOP_RECORD, _("Stop Record"));
menuSTC->Append(ID_EDIT_MACRO_PLAYBACK, _("Playback"));
wxExMenu* menuHelp = new wxExMenu;
menuHelp->Append(wxID_ABOUT);
wxMenuBar *menubar = new wxMenuBar;
menubar->Append(menuFile, _("&File"));
menubar->Append(menuSTC, _("&STC"));
menubar->Append(menuConfig, _("&Config"));
menubar->Append(menuHelp, _("&Help"));
SetMenuBar(menubar);
m_Notebook = new wxExNotebook(this, NULL);
#if wxUSE_GRID
m_Grid = new wxExGrid(m_Notebook);
#endif
m_ListView = new wxExListView(m_Notebook);
m_STC = new wxExSTC(this);
m_STCShell = new wxExSTCShell(this, ">", wxTextFile::GetEOL(), true, 10);
GetManager().AddPane(m_STC, wxAuiPaneInfo().CenterPane().CloseButton(false).MaximizeButton(true).Name("wxExSTC"));
GetManager().AddPane(m_STCShell, wxAuiPaneInfo().Bottom().MinSize(wxSize(250, 250)));
GetManager().AddPane(m_Notebook, wxAuiPaneInfo().Left().MinSize(wxSize(250, 250)));
GetManager().Update();
assert(wxExApp::GetLexers());
wxExSTC* st = new wxExSTC(this, wxExApp::GetLexers()->GetFileName());
m_Notebook->AddPage(st, wxExApp::GetLexers()->GetFileName().GetFullName());
m_Notebook->AddPage(m_ListView, "wxExListView");
#if wxUSE_GRID
m_Notebook->AddPage(m_Grid, "wxExGrid");
m_Grid->CreateGrid(0, 0);
m_Grid->AppendCols(2);
wxExSampleDir dir(wxGetCwd(), "appl.*", m_Grid);
dir.FindFiles();
m_Grid->AutoSizeColumns();
#endif
m_ListView->SetSingleStyle(wxLC_REPORT); // wxLC_ICON);
m_ListView->InsertColumn(wxExColumn("String", wxExColumn::COL_STRING));
m_ListView->InsertColumn(wxExColumn("Number", wxExColumn::COL_INT));
m_ListView->InsertColumn(wxExColumn("Float", wxExColumn::COL_FLOAT));
m_ListView->InsertColumn(wxExColumn("Date", wxExColumn::COL_DATE));
const int items = 50;
for (int i = 0; i < items; i++)
{
wxExListItem item(m_ListView, wxString::Format("item%d", i));
item.Insert();
item.SetColumnText(1, wxString::Format("%d", i));
item.SetColumnText(2, wxString::Format("%f", (float)i / 2.0));
item.SetColumnText(3, wxDateTime::Now().Format());
// Set some images.
if (i == 0) item.SetImage(wxART_CDROM);
else if (i == 1) item.SetImage(wxART_REMOVABLE);
else if (i == 2) item.SetImage(wxART_FOLDER);
else if (i == 3) item.SetImage(wxART_FOLDER_OPEN);
else if (i == 4) item.SetImage(wxART_GO_DIR_UP);
else if (i == 5) item.SetImage(wxART_EXECUTABLE_FILE);
else if (i == 6) item.SetImage(wxART_NORMAL_FILE);
else item.SetImage(wxART_TICK_MARK);
}
#if wxUSE_STATUSBAR
std::vector<wxExPane> panes;
panes.push_back(wxExPane("PaneText", -3));
panes.push_back(wxExPane("PaneFileType", 50, _("File type")));
panes.push_back(wxExPane("PaneCells", 60, _("Cells")));
panes.push_back(wxExPane("PaneItems", 60, _("Items")));
panes.push_back(wxExPane("PaneLines", 100, _("Lines")));
panes.push_back(wxExPane("PaneLexer", 60, _("Lexer")));
SetupStatusBar(panes);
#endif
CreateToolBar();
m_ToolBar->AddTool(wxID_OPEN);
m_ToolBar->AddTool(wxID_SAVE);
m_ToolBar->AddTool(wxID_PRINT);
m_ToolBar->AddTool(wxID_EXIT);
m_ToolBar->Realize();
}
void wxExSampleFrame::ConfigDialogApplied(wxWindowID /* id */)
{
m_STC->ConfigGet();
m_STCShell->ConfigGet();
}
wxExGrid* wxExSampleFrame::GetGrid()
{
return m_Grid;
}
wxExListView* wxExSampleFrame::GetListView()
{
return m_ListView;
}
wxExSTC* wxExSampleFrame::GetSTC()
{
if (m_STC->IsShown())
{
return m_STC;
}
else if (m_STCShell->IsShown())
{
return m_STCShell;
}
return NULL;
}
void wxExSampleFrame::OnCommand(wxCommandEvent& event)
{
m_Statistics.Inc(wxString::Format("%d", event.GetId()));
switch (event.GetId())
{
case wxID_ABOUT:
{
wxAboutDialogInfo info;
info.SetIcon(GetIcon());
info.SetVersion(wxEX_VERSION_STRING);
info.AddDeveloper(wxVERSION_STRING);
info.SetCopyright(_("(c) 1998-2009 Anton van Wezenbeek."));
wxAboutBox(info);
}
break;
case wxID_EXIT: Close(true); break;
case wxID_OPEN:
{
wxExFileDialog dlg(this, m_STC);
if (dlg.ShowModal() == wxID_CANCEL) return;
wxStopWatch sw;
m_STC->Open(dlg.GetPath(), 0, wxEmptyString, m_FlagsSTC);
const long stop = sw.Time();
#if wxUSE_STATUSBAR
StatusText(wxString::Format("wxExSTC::Open:%ld milliseconds, %d bytes", stop, m_STC->GetTextLength()));
#endif
}
break;
case wxID_PREVIEW: m_ListView->PrintPreview(); break;
case wxID_PRINT: m_ListView->Print(); break;
case wxID_PRINT_SETUP: wxExApp::GetPrinter()->PageSetup(); break;
case wxID_SAVE:
m_STC->FileSave();
if (m_STC->GetFileName().GetFullPath() == wxExApp::GetLexers()->GetFileName().GetFullPath())
{
if (wxExApp::GetLexers()->Read())
{
wxLogMessage("File contains: %d lexers", wxExApp::GetLexers()->Count());
// As the lexer might have changed, update status bar field as well.
#if wxUSE_STATUSBAR
m_STC->UpdateStatusBar("PaneLexer");
#endif
}
}
break;
case ID_CONFIG_DLG:
{
std::vector<wxExConfigItem> v;
for (size_t h = 1; h <= 25; h++)
{
v.push_back(wxExConfigItem(wxString::Format(_("check%d"), h), CONFIG_CHECKBOX, "Checkboxes"));
}
for (size_t i = 1; i <= 25; i++)
{
v.push_back(wxExConfigItem(wxString::Format(_("colour%d"), i), CONFIG_COLOUR, "Colours"));
}
for (size_t j = 1; j <= 10; j++)
{
v.push_back(wxExConfigItem(wxString::Format(_("integer%d"), j), CONFIG_INT, "Integers", true));
}
for (size_t k = 1; k <= 10; k++)
{
v.push_back(wxExConfigItem(wxString::Format(_("spin%d"), k), 1, k, wxString("Spin controls")));
}
for (size_t l = 1; l <= 10; l++)
{
v.push_back(wxExConfigItem(wxString::Format(_("string%d"), l), CONFIG_STRING, "Strings"));
}
for (size_t m = 1; m <= 10; m++)
{
v.push_back(wxExConfigItem(wxString::Format(_("combobox%d"), m), CONFIG_COMBOBOX, "Comboboxes"));
}
v.push_back(wxExConfigItem(_("dirpicker"), CONFIG_DIRPICKERCTRL, "Pickers"));
v.push_back(wxExConfigItem(_("filepicker"), CONFIG_FILEPICKERCTRL, "Pickers"));
wxExConfigDialog* dlg = new wxExConfigDialog(
this,
wxExApp::GetConfig(),
v,
_("Config Dialog"),
wxEmptyString,
10,
6,
wxAPPLY | wxCANCEL,
wxID_ANY,
wxDefaultPosition,
wxSize(400,300));
dlg->Show();
// Dialog is not placed nicely.
//GetManager().GetPane("NOTEBOOK"));
//GetManager().Update();
}
break;
case ID_CONFIG_DLG_READONLY:
{
std::vector<wxExConfigItem> v;
v.push_back(wxExConfigItem(_("filepicker"), CONFIG_FILEPICKERCTRL));
for (size_t j = 1; j <= 10; j++)
{
v.push_back(wxExConfigItem(wxString::Format(_("integer%d"), j), CONFIG_INT));
}
wxExConfigDialog* dlg = new wxExConfigDialog(
this,
wxExApp::GetConfig(),
v,
_("Config Dialog Readonly"),
wxEmptyString,
0,
2,
wxCANCEL);
dlg->Show();
}
break;
case ID_LOCALE_SHOW_DIR:
wxLogMessage(wxExApp::GetCatalogDir());
break;
case ID_SHELL_COMMAND:
m_STCShell->Prompt("Hello '" + event.GetString() + "' from the shell");
break;
case ID_STATISTICS_SHOW:
m_Notebook->AddPage(m_Statistics.Show(m_Notebook), "Statistics");
break;
case ID_STC_CONFIG_DLG:
wxExSTC::ConfigDialog(
this,
_("Editor Options"),
wxExSTC::STC_CONFIG_MODELESS | wxExSTC::STC_CONFIG_WITH_APPLY);
break;
case ID_STC_FLAGS:
{
long value = wxGetNumberFromUser(
"Input:",
wxEmptyString,
"STC Open Flag",
m_FlagsSTC,
0,
0xFFFF);
if (value != -1)
{
m_FlagsSTC = value;
}
}
break;
case ID_STC_GOTO: m_STC->GotoDialog(); break;
case ID_STC_LEXER: m_STC->LexerDialog(); break;
case ID_STC_SPLIT:
{
wxExSTC* stc = new wxExSTC(*m_STC);
m_Notebook->AddPage(
stc,
wxString::Format("stc%d", stc->GetId()),
m_STC->GetFileName().GetFullName());
stc->SetDocPointer(m_STC->GetDocPointer());
}
break;
default:
wxFAIL;
break;
}
}
<|endoftext|>
|
<commit_before>#pragma once
#include <iterator>
#include <cstdlib> //malloc, realloc
#include <cstring> //memcpy, memmove
#include <exception> //bad_alloc
#include <type_traits>
#include <utility>
#include <iostream>
namespace tyti {
template<typename T>
class any_iterator : std::iterator<std::bidirectional_iterator_tag, T>
{
//functionpointer save structurez
struct TypeInfos
{
void(*const inc_fn)(void*);
void(*const dec_fn)(void*);
const bool(*const equal_fn)(const void*,const void*);
const T*(*const deref_fn)(const void*);
void(*const dtor_fn)(void*);
void(*const copy_ctor_fn)(void**,const void*);
void(*const move_ctor_fn)(void**, const void*);
const size_t size;
};
template<typename IterType>
TypeInfos* getFunctionInfos()
{
static TypeInfos ti =
{
&any_iterator::inc<IterType>,
&any_iterator::dec<IterType>,
&any_iterator::equal<IterType>,
&any_iterator::deref<IterType>,
//(std::is_trivially_destructible<IterType>::value) ?
//static_cast<void(*)(void*)>(nullptr) :
&any_iterator::dtor<IterType>,
//(std::is_trivially_copy_constructible<IterType>::value) ?
//static_cast<void(*)(void*,const void*)>(nullptr) :
&any_iterator::copyConstructor<IterType>,
&any_iterator::moveConstructor<IterType>,
sizeof(IterType)
};
return &ti;
}
// used to destruct nothing e.g. used when the l-value should not destruct anything
// Do not provide it to the user.
struct NoDestruct
{
~NoDestruct() {} //only destructor is used
NoDestruct(const NoDestruct&) { assert(false); }
NoDestruct(NoDestruct&&) { assert(false); }
NoDestruct operator++() { assert(false); return *this; }
NoDestruct operator--() { assert(false); return *this; }
bool operator==(const NoDestruct&) const { assert(false); return false; }
bool operator!=(const NoDestruct&) const { assert(false); return false; }
//this function will never be called. just for compile correctness
const T& operator*() const { assert(false); return *(reinterpret_cast<const T*>(this)); }
};
constexpr static bool is_small(size_t size)
{
return size <= sizeof(void*);
}
template<typename Iter>
inline static constexpr void* get_voidp(void** _ptr)
{
return is_small(sizeof(Iter)) ? static_cast<void*>(_ptr) : *_ptr;
}
template<typename Iter>
inline static constexpr const void* get_voidp(const void** _ptr)
{
return is_small(sizeof(Iter)) ? static_cast<const void*>(_ptr): *_ptr;
}
template<typename Iter>
static void inc(void* _ptr)
{
++(*reinterpret_cast<Iter*>(get_voidp<Iter>(&_ptr)));
}
template<typename Iter>
static void dec(void* _ptr)
{
--(*reinterpret_cast<Iter*>(get_voidp<Iter>(&_ptr)));
}
template<typename Iter>
static const T* deref(const void* _ptr)
{
return &(*(*reinterpret_cast<const Iter*>(get_voidp<Iter>(&_ptr))));
}
template<typename Iter>
static const bool equal(const void* _lhs, const void* _rhs)
{
return *reinterpret_cast<const Iter*>(get_voidp<Iter>(&_lhs)) == *reinterpret_cast<const Iter*>(get_voidp<Iter>(&_rhs));
}
template<typename Iter>
static void dtor(void* _ptr)
{
reinterpret_cast<Iter*>(get_voidp<Iter>(&_ptr))->~Iter();
}
template<typename Iter>
static void copyConstructor(void** _dst, const void* _src)
{
new (is_small(sizeof(Iter)) ? _dst : *_dst) Iter(*reinterpret_cast<const Iter*>(get_voidp<Iter>(&_src)));
}
template<typename Iter>
static void moveConstructor(void** _dst, const void* _src)
{
new (is_small(sizeof(Iter))?_dst:*_dst) Iter(std::move(*reinterpret_cast<const Iter*>(get_voidp<Iter>(&_src))));
}
// helper functions
inline void destruct()
{
ti_->dtor_fn(ptr_);
}
void switch_type(const TypeInfos* _newType)
{
destruct();
//manage memory if type sizes are different
if (ti_->size < _newType->size)
{
if ( is_small(ti_->size))
{
my_malloc(_newType->size);
}
else // old type is not small type
{
if (is_small(_newType->size))
std::free(ptr_);
else
ptr_ = std::realloc(ptr_, _newType->size);
}
if ( !check_alloc(ptr_,_newType->size)) throw std::bad_alloc();
}
ti_ = _newType;
}
template<typename IterType>
inline static constexpr const void* itertype_addr(const IterType& _iter)
{
const void* ptr = reinterpret_cast<const void*>(&_iter);
return is_small(sizeof(IterType)) ? &ptr : ptr;
}
inline void copy_and_assign(const void* _src)
{
ti_->copy_ctor_fn(&ptr_, _src);
}
inline void move_iter(const void* _src)
{
ti_->move_ctor_fn(&ptr_, _src);
}
inline static void* my_malloc(size_t size)
{
return (is_small(size)) ? 0 : malloc(size);
}
inline static constexpr bool check_alloc(void* ptr, size_t size)
{
return (is_small(size)) ? true : ptr != nullptr;
}
// member variables
void* ptr_;
const TypeInfos* ti_;
/// Interface
public:
template <typename IterType, class = typename std::enable_if<!std::is_rvalue_reference<IterType>::value>::type>
explicit any_iterator(const IterType& _iter)
: ptr_(my_malloc(sizeof(IterType))), ti_(getFunctionInfos<IterType>())
{
if (!check_alloc(ptr_, sizeof(IterType))) throw std::bad_alloc();
copy_and_assign(itertype_addr(_iter));
}
template<typename IterType, class = typename std::enable_if<std::is_rvalue_reference<IterType>::value>::type>
explicit any_iterator(IterType&& _iter)
: ptr_(my_malloc(_iter.ti_->size)), ti_(std::move(_iter.ti_))
{
if ( !check_alloc(ptr_,_iter.ti_->size)) throw std::bad_alloc();
move_iter(_iter);
}
any_iterator(const any_iterator& _iter)
: ptr_(my_malloc(_iter.ti_->size)), ti_(_iter.ti_)
{
if ( !check_alloc(ptr_,_iter.ti_->size)) throw std::bad_alloc();
copy_and_assign(_iter.ptr_);
}
any_iterator(any_iterator&& _iter)
:ptr_(_iter.ptr_), ti_(_iter.ti_)
{
_iter.ti_ = getFunctionInfos<NoDestruct>();
}
template <typename IterType, class = typename std::enable_if<!std::is_rvalue_reference<IterType>::value>::type >
const any_iterator& operator=(const IterType& _iter)
{
switch_type(getFunctionInfos<IterType>());
copy_and_assign(itertype_addr(_iter));
return *this;
}
template <typename IterType, class = typename std::enable_if<std::is_rvalue_reference<IterType>::value>::type>
const any_iterator& operator=(IterType&& _iter)
{
switch_type(getFunctionInfos<IterType>());
move_iter(itertype_addr(_iter));
return *this;
}
const any_iterator& operator=(const any_iterator& _iter)
{
switch_type(_iter.ti_);
copy_and_assign(_iter.ptr_);
return *this;
}
const any_iterator& operator=(any_iterator&& _iter)
{
std::swap(ti_, _iter.ti_);
std::swap(ptr_, _iter.ptr_);
//old ptr gets destructed via _iter
return *this;
}
~any_iterator()
{
destruct();
if (!is_small(ti_->size))
std::free(ptr_);
}
bool operator==(const any_iterator& _rhs) const
{
if (ti_ != _rhs.ti_) //different types
return false;
return ti_->equal_fn(ptr_, _rhs.ptr_);
}
template <typename IterType>
bool operator==(const IterType& _rhs) const {
return ti_->equal_fn(ptr_, itertype_addr(_rhs));
}
template <typename IterType>
bool operator!=(const IterType& _rhs) const{
return !operator==(_rhs);
}
/// Standard pre-increment operator
any_iterator& operator++() {
ti_->inc_fn(ptr_);
return *this;
}
/// Standard post-increment operator
any_iterator operator++(int) {
any_iterator cpy(*this);
ti_->inc_fn(ptr_);
return cpy;
}
/// Standard pre-decrement operator
any_iterator& operator--() {
ti_->dec_fn(ptr_);
return *this;
}
/// Standard post-decrement operator
any_iterator operator--(int) {
any_iterator cpy(*this);
ti_->dec_fn(ptr_);
return cpy;
}
const T& operator*() const {
return *(ti_->deref_fn(ptr_));
}
/// Standard pointer operator.
const T* operator->() const {
return ti_->deref_fn(ptr_);
}
};
// C++17 todo:
//if msvc >= 2017 or gcc with c++17 support
//#include <any>
//using AnyIterator = AnyIteratorT<std::any>;
//endif
} // end namespace tyti
template<typename IterT, typename T>
bool operator==(const IterT&& _lhs, const tyti::any_iterator<T>&& _rhs)
{
return _rhs.operator==(std::forward<IterT>(_lhs));
}
template<typename IterT, typename T>
bool operator!=(IterT&& _lhs, tyti::any_iterator<T>&& _rhs)
{
return _rhs.operator!=(std::forward<IterT>(_lhs));
}<commit_msg>remove warning<commit_after>#pragma once
#include <iterator>
#include <cstdlib> //malloc, realloc
#include <cstring> //memcpy, memmove
#include <exception> //bad_alloc
#include <type_traits>
#include <utility>
#include <iostream>
namespace tyti {
template<typename T>
class any_iterator : std::iterator<std::bidirectional_iterator_tag, T>
{
//functionpointer save structurez
struct TypeInfos
{
void(*const inc_fn)(void*);
void(*const dec_fn)(void*);
const bool(*const equal_fn)(const void*,const void*);
const T*(*const deref_fn)(const void*);
void(*const dtor_fn)(void*);
void(*const copy_ctor_fn)(void**,const void*);
void(*const move_ctor_fn)(void**, const void*);
const size_t size;
};
template<typename IterType>
TypeInfos* getFunctionInfos()
{
static TypeInfos ti =
{
&any_iterator::inc<IterType>,
&any_iterator::dec<IterType>,
&any_iterator::equal<IterType>,
&any_iterator::deref<IterType>,
//(std::is_trivially_destructible<IterType>::value) ?
//static_cast<void(*)(void*)>(nullptr) :
&any_iterator::dtor<IterType>,
//(std::is_trivially_copy_constructible<IterType>::value) ?
//static_cast<void(*)(void*,const void*)>(nullptr) :
&any_iterator::copyConstructor<IterType>,
&any_iterator::moveConstructor<IterType>,
sizeof(IterType)
};
return &ti;
}
// used to destruct nothing e.g. used when the l-value should not destruct anything
// Do not provide it to the user.
struct NoDestruct
{
~NoDestruct() {} //only destructor is used
NoDestruct(const NoDestruct&) { assert(false); }
NoDestruct(NoDestruct&&) { assert(false); }
NoDestruct operator++() { assert(false); return *this; }
NoDestruct operator--() { assert(false); return *this; }
bool operator==(const NoDestruct&) const { assert(false); return false; }
bool operator!=(const NoDestruct&) const { assert(false); return false; }
//this function will never be called. just for compile correctness
const T& operator*() const { assert(false); return *(reinterpret_cast<const T*>(this)); }
};
constexpr static bool is_small(size_t size)
{
return size <= sizeof(void*);
}
template<typename Iter>
inline static constexpr void* get_voidp(void** _ptr)
{
return is_small(sizeof(Iter)) ? static_cast<void*>(_ptr) : *_ptr;
}
template<typename Iter>
inline static constexpr const void* get_voidp(const void** _ptr)
{
return is_small(sizeof(Iter)) ? static_cast<const void*>(_ptr): *_ptr;
}
template<typename Iter>
static void inc(void* _ptr)
{
++(*reinterpret_cast<Iter*>(get_voidp<Iter>(&_ptr)));
}
template<typename Iter>
static void dec(void* _ptr)
{
--(*reinterpret_cast<Iter*>(get_voidp<Iter>(&_ptr)));
}
template<typename Iter>
static const T* deref(const void* _ptr)
{
return &(*(*reinterpret_cast<const Iter*>(get_voidp<Iter>(&_ptr))));
}
template<typename Iter>
static const bool equal(const void* _lhs, const void* _rhs)
{
return *reinterpret_cast<const Iter*>(get_voidp<Iter>(&_lhs)) == *reinterpret_cast<const Iter*>(get_voidp<Iter>(&_rhs));
}
template<typename Iter>
static void dtor(void* _ptr)
{
reinterpret_cast<Iter*>(get_voidp<Iter>(&_ptr))->~Iter();
}
template<typename Iter>
static void copyConstructor(void** _dst, const void* _src)
{
new (is_small(sizeof(Iter)) ? _dst : *_dst) Iter(*reinterpret_cast<const Iter*>(get_voidp<Iter>(&_src)));
}
template<typename Iter>
static void moveConstructor(void** _dst, const void* _src)
{
new (is_small(sizeof(Iter))?_dst:*_dst) Iter(std::move(*reinterpret_cast<const Iter*>(get_voidp<Iter>(&_src))));
}
// helper functions
inline void destruct()
{
ti_->dtor_fn(ptr_);
}
void switch_type(const TypeInfos* _newType)
{
destruct();
//manage memory if type sizes are different
if (ti_->size < _newType->size)
{
if ( is_small(ti_->size))
{
my_malloc(_newType->size);
}
else // old type is not small type
{
if (is_small(_newType->size))
std::free(ptr_);
else
ptr_ = std::realloc(ptr_, _newType->size);
}
if ( !check_alloc(ptr_,_newType->size)) throw std::bad_alloc();
}
ti_ = _newType;
}
template<typename IterType>
inline static constexpr const void* itertype_addr(const void** ptr)
{
return is_small(sizeof(IterType)) ? ptr : *ptr;
}
inline void copy_and_assign(const void* _src)
{
ti_->copy_ctor_fn(&ptr_, _src);
}
inline void move_iter(const void* _src)
{
ti_->move_ctor_fn(&ptr_, _src);
}
inline static void* my_malloc(size_t size)
{
return (is_small(size)) ? 0 : malloc(size);
}
inline static constexpr bool check_alloc(void* ptr, size_t size)
{
return (is_small(size)) ? true : ptr != nullptr;
}
// member variables
void* ptr_;
const TypeInfos* ti_;
/// Interface
public:
template <typename IterType, class = typename std::enable_if<!std::is_rvalue_reference<IterType>::value>::type>
explicit any_iterator(const IterType& _iter)
: ptr_(my_malloc(sizeof(IterType))), ti_(getFunctionInfos<IterType>())
{
if (!check_alloc(ptr_, sizeof(IterType))) throw std::bad_alloc();
auto ptr = reinterpret_cast<const void*>(&_iter);
copy_and_assign(itertype_addr<IterType>(&ptr));
}
template<typename IterType, class = typename std::enable_if<std::is_rvalue_reference<IterType>::value>::type>
explicit any_iterator(IterType&& _iter)
: ptr_(my_malloc(_iter.ti_->size)), ti_(std::move(_iter.ti_))
{
if ( !check_alloc(ptr_,_iter.ti_->size)) throw std::bad_alloc();
move_iter(_iter);
}
any_iterator(const any_iterator& _iter)
: ptr_(my_malloc(_iter.ti_->size)), ti_(_iter.ti_)
{
if ( !check_alloc(ptr_,_iter.ti_->size)) throw std::bad_alloc();
copy_and_assign(_iter.ptr_);
}
any_iterator(any_iterator&& _iter)
:ptr_(_iter.ptr_), ti_(_iter.ti_)
{
_iter.ti_ = getFunctionInfos<NoDestruct>();
}
template <typename IterType, class = typename std::enable_if<!std::is_rvalue_reference<IterType>::value>::type >
const any_iterator& operator=(const IterType& _iter)
{
switch_type(getFunctionInfos<IterType>());
auto ptr = reinterpret_cast<const void*>(&_iter);
copy_and_assign(itertype_addr<IterType>(&ptr));
return *this;
}
template <typename IterType, class = typename std::enable_if<std::is_rvalue_reference<IterType>::value>::type>
const any_iterator& operator=(IterType&& _iter)
{
switch_type(getFunctionInfos<IterType>());
auto ptr = reinterpret_cast<const void*>(&_iter);
move_iter(itertype_addr<IterType>(&ptr));
return *this;
}
const any_iterator& operator=(const any_iterator& _iter)
{
switch_type(_iter.ti_);
copy_and_assign(_iter.ptr_);
return *this;
}
const any_iterator& operator=(any_iterator&& _iter)
{
std::swap(ti_, _iter.ti_);
std::swap(ptr_, _iter.ptr_);
//old ptr gets destructed via _iter
return *this;
}
~any_iterator()
{
destruct();
if (!is_small(ti_->size))
std::free(ptr_);
}
bool operator==(const any_iterator& _rhs) const
{
if (ti_ != _rhs.ti_) //different types
return false;
return ti_->equal_fn(ptr_, _rhs.ptr_);
}
template <typename IterType>
bool operator==(const IterType& _rhs) const {
auto ptr = reinterpret_cast<const void*>(&_rhs);
return ti_->equal_fn(ptr_, itertype_addr<IterType>(&ptr));
}
template <typename IterType>
bool operator!=(const IterType& _rhs) const{
return !operator==(_rhs);
}
/// Standard pre-increment operator
any_iterator& operator++() {
ti_->inc_fn(ptr_);
return *this;
}
/// Standard post-increment operator
any_iterator operator++(int) {
any_iterator cpy(*this);
ti_->inc_fn(ptr_);
return cpy;
}
/// Standard pre-decrement operator
any_iterator& operator--() {
ti_->dec_fn(ptr_);
return *this;
}
/// Standard post-decrement operator
any_iterator operator--(int) {
any_iterator cpy(*this);
ti_->dec_fn(ptr_);
return cpy;
}
const T& operator*() const {
return *(ti_->deref_fn(ptr_));
}
/// Standard pointer operator.
const T* operator->() const {
return ti_->deref_fn(ptr_);
}
};
// C++17 todo:
//if msvc >= 2017 or gcc with c++17 support
//#include <any>
//using AnyIterator = AnyIteratorT<std::any>;
//endif
} // end namespace tyti
template<typename IterT, typename T>
bool operator==(const IterT&& _lhs, const tyti::any_iterator<T>&& _rhs)
{
return _rhs.operator==(std::forward<IterT>(_lhs));
}
template<typename IterT, typename T>
bool operator!=(IterT&& _lhs, tyti::any_iterator<T>&& _rhs)
{
return _rhs.operator!=(std::forward<IterT>(_lhs));
}<|endoftext|>
|
<commit_before>/******************************************************************************\
* File: app.cpp
* Purpose: Implementation of classes for syncodbcquery
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2008-2009, Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/aboutdlg.h>
#include <wx/regex.h>
#include <wx/tokenzr.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/grid.h>
#include <wx/extension/shell.h>
#include <wx/extension/util.h>
#include <wx/extension/version.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/stc.h>
#include <wx/extension/report/util.h>
#include "app.h"
#ifndef __WXMSW__
#include "app.xpm"
#endif
IMPLEMENT_APP(App)
bool App::OnInit()
{
SetAppName("syncodbcquery");
if (!wxExApp::OnInit())
{
return false;
}
Frame *frame = new Frame();
frame->Show(true);
SetTopWindow(frame);
return true;
}
BEGIN_EVENT_TABLE(Frame, wxExFrameWithHistory)
EVT_CLOSE(Frame::OnClose)
EVT_MENU(wxID_EXECUTE, Frame::OnCommand)
EVT_MENU(wxID_STOP, Frame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND, Frame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND_STOP, Frame::OnCommand)
EVT_MENU_RANGE(wxID_CUT, wxID_CLEAR, Frame::OnCommand)
EVT_MENU_RANGE(wxID_OPEN, wxID_PREFERENCES, Frame::OnCommand)
EVT_MENU_RANGE(ID_FIRST, ID_LAST, Frame::OnCommand)
EVT_UPDATE_UI(wxID_SAVE, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_SAVEAS, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_STOP, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_DATABASE_CLOSE, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_DATABASE_OPEN, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_EXECUTE, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_RECENTFILE_MENU, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_QUERY, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_RESULTS, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_STATISTICS, Frame::OnUpdateUI)
END_EVENT_TABLE()
Frame::Frame()
: wxExFrameWithHistory(NULL, wxID_ANY, wxTheApp->GetAppName())
, m_Running(false)
, m_Stopped(false)
{
SetIcon(wxICON(app));
wxExMenu* menuFile = new wxExMenu;
menuFile->Append(wxID_NEW);
menuFile->Append(wxID_OPEN);
UseFileHistory(ID_RECENTFILE_MENU, menuFile);
menuFile->AppendSeparator();
menuFile->Append(wxID_SAVE);
menuFile->Append(wxID_SAVEAS);
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
wxExMenu* menuDatabase = new wxExMenu;
menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open")));
menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close"));
wxExMenu* menuQuery = new wxExMenu;
menuQuery->Append(wxID_EXECUTE);
menuQuery->Append(wxID_STOP);
wxMenu* menuOptions = new wxMenu();
menuOptions->Append(wxID_PREFERENCES);
wxMenu* menuView = new wxMenu();
menuView->AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar"));
menuView->AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar"));
menuView->AppendSeparator();
menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query"));
menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results"));
menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics"));
wxMenu* menuHelp = new wxMenu();
menuHelp->Append(wxID_ABOUT);
wxMenuBar *menubar = new wxMenuBar;
menubar->Append(menuFile, wxGetStockLabel(wxID_FILE));
menubar->Append(menuView, _("&View"));
menubar->Append(menuDatabase, _("&Connection"));
menubar->Append(menuQuery, _("&Query"));
menubar->Append(menuOptions, _("&Options"));
menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));
SetMenuBar(menubar);
m_Query = new wxExSTCWithFrame(this, this);
m_Query->SetLexer("sql");
m_Results = new wxExGrid(this);
m_Results->CreateGrid(0, 0);
m_Results->EnableEditing(false); // this is a read-only grid
m_Shell = new wxExSTCShell(this, ">", ";", true, 50);
m_Shell->SetFocus();
GetManager().AddPane(m_Shell,
wxAuiPaneInfo().
Name("CONSOLE").
CenterPane());
GetManager().AddPane(m_Results,
wxAuiPaneInfo().
Name("RESULTS").
Caption(_("Results")).
CloseButton(true).
MaximizeButton(true));
GetManager().AddPane(m_Query,
wxAuiPaneInfo().
Name("QUERY").
Caption(_("Query")).
CloseButton(true).
MaximizeButton(true));
GetManager().AddPane(m_Statistics.Show(this),
wxAuiPaneInfo().Left().
MaximizeButton(true).
Caption(_("Statistics")).
Name("STATISTICS"));
GetManager().LoadPerspective(wxConfigBase::Get()->Read("Perspective"));
GetManager().GetPane("QUERY").Show(false);
GetManager().Update();
#if wxUSE_STATUSBAR
std::vector<wxExPane> panes;
panes.push_back(wxExPane("PaneText", -3));
panes.push_back(wxExPane("PaneLines", 100, _("Lines in window")));
SetupStatusBar(panes);
#endif
CreateToolBar();
m_ToolBar->AddTool(wxID_NEW);
m_ToolBar->AddTool(wxID_OPEN);
m_ToolBar->AddTool(wxID_SAVE);
#ifdef __WXGTK__
m_ToolBar->AddTool(wxID_EXECUTE);
#endif
m_ToolBar->Realize();
}
void Frame::ConfigDialogApplied(wxWindowID dialogid)
{
if (dialogid == wxID_PREFERENCES)
{
m_Query->ConfigGet();
m_Shell->ConfigGet();
}
else
{
wxFAIL;
}
}
wxExGrid* Frame::GetGrid()
{
if (m_Results->IsShown())
{
return m_Results;
}
else
{
const wxExGrid* grid = m_Statistics.GetGrid();
if (grid != NULL && grid->IsShown())
{
return (wxExGrid*)grid;
}
else
{
return NULL;
}
}
}
wxExSTC* Frame::GetSTC()
{
if (m_Query->IsShown())
{
return m_Query;
}
else if (m_Shell->IsShown())
{
return m_Shell;
}
return NULL;
}
void Frame::OnClose(wxCloseEvent& event)
{
wxExFileDialog dlg(this, m_Query);
if (dlg.ShowModalIfChanged() == wxID_CANCEL)
{
return;
}
wxConfigBase::Get()->Write("Perspective", GetManager().SavePerspective());
event.Skip();
}
void Frame::OnCommand(wxCommandEvent& event)
{
switch (event.GetId())
{
case wxID_ABOUT:
{
wxAboutDialogInfo info;
info.SetIcon(GetIcon());
info.SetDescription(_("This program offers a general ODBC query."));
info.SetVersion("v1.0.1");
info.SetCopyright("(c) 2008-2009, Anton van Wezenbeek");
info.AddDeveloper(wxVERSION_STRING);
info.AddDeveloper(wxEX_VERSION_STRING);
info.AddDeveloper(wxExOTL::Version());
wxAboutBox(info);
}
break;
case wxID_EXECUTE:
m_Stopped = false;
RunQueries(m_Query->GetText());
break;
case wxID_EXIT:
Close(true);
break;
case wxID_NEW:
m_Query->FileNew();
m_Query->SetLexer("sql");
m_Query->SetFocus();
GetManager().GetPane("QUERY").Show();
GetManager().Update();
break;
case wxID_OPEN:
wxExOpenFilesDialog(
this,
wxFD_OPEN | wxFD_CHANGE_DIR,
"sql files (*.sql) | *.sql",
true);
break;
case wxID_PREFERENCES:
event.Skip();
break;
case wxID_SAVE:
m_Query->FileSave();
break;
case wxID_SAVEAS:
{
wxExFileDialog dlg(
this, m_Query,
_("File Save As"),
wxFileSelectorDefaultWildcardStr,
wxFD_SAVE);
if (dlg.ShowModal() == wxID_OK)
{
m_Query->FileSave(dlg.GetPath());
}
}
break;
case wxID_STOP:
m_Running = false;
m_Stopped = true;
break;
case ID_DATABASE_CLOSE:
m_otl.Logoff();
m_Shell->SetPrompt(">");
break;
case ID_DATABASE_OPEN:
m_otl.Logon(this);
m_Shell->SetPrompt(
(m_otl.IsConnected() ? wxConfigBase::Get()->Read(_("Datasource")): "") + ">");
break;
case ID_SHELL_COMMAND:
if (m_otl.IsConnected())
{
try
{
const wxString query = event.GetString().substr(
0,
event.GetString().length() - 1);
m_Stopped = false;
RunQuery(query, true);
}
catch (otl_exception& p)
{
if (m_Results->IsShown())
{
m_Results->EndBatch();
}
m_Shell->AppendText(_("\nerror: ") + wxExQuoted(p.msg));
}
}
else
{
m_Shell->AppendText(_("\nnot connected"));
}
m_Shell->Prompt();
break;
case ID_SHELL_COMMAND_STOP:
m_Stopped = true;
m_Shell->Prompt(_("cancelled"));
break;
case ID_VIEW_QUERY: TogglePane("QUERY"); break;
case ID_VIEW_RESULTS: TogglePane("RESULTS"); break;
case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break;
default:
wxFAIL;
}
}
void Frame::OnUpdateUI(wxUpdateUIEvent& event)
{
switch (event.GetId())
{
case wxID_EXECUTE:
// If we have a query, you can hide it, but still run it.
event.Enable(m_Query->GetLength() > 0 && m_otl.IsConnected());
break;
case wxID_SAVE:
event.Enable(m_Query->GetModify());
break;
case wxID_SAVEAS:
event.Enable(m_Query->GetLength() > 0);
break;
case wxID_STOP:
event.Enable(m_Running);
break;
case ID_DATABASE_CLOSE:
event.Enable(m_otl.IsConnected());
break;
case ID_DATABASE_OPEN:
event.Enable(!m_otl.IsConnected());
break;
case ID_RECENTFILE_MENU:
event.Enable(!GetRecentFile().empty());
break;
case ID_VIEW_QUERY:
event.Check(GetManager().GetPane("QUERY").IsShown());
break;
case ID_VIEW_RESULTS:
event.Check(GetManager().GetPane("RESULTS").IsShown());
break;
case ID_VIEW_STATISTICS:
event.Check(GetManager().GetPane("STATISTICS").IsShown());
break;
default:
wxFAIL;
}
}
bool Frame::OpenFile(
const wxExFileName& filename,
int line_number,
const wxString& match,
long flags)
{
GetManager().GetPane("QUERY").Show(true);
GetManager().Update();
// Take care that wxExOpenFilesDialog always results in opening in the query.
// Otherwise if results are focused, the file is opened in the results.
return m_Query->Open(filename, line_number, match, flags);
}
void Frame::RunQuery(const wxString& query, bool empty_results)
{
wxStopWatch sw;
const wxString query_lower = query.Lower();
// Query functions supported by ODBC
// $SQLTables, $SQLColumns, etc.
// $SQLTables $1:'%'
// allow you to get database schema.
if (query_lower.StartsWith("select") ||
query_lower.StartsWith("describe") ||
query_lower.StartsWith("show") ||
query_lower.StartsWith("explain") ||
query_lower.StartsWith("$sql"))
{
long rpc;
if (m_Results->IsShown())
{
rpc = m_otl.Query(query, m_Results, m_Stopped, empty_results);
}
else
{
rpc = m_otl.Query(query, m_Shell, m_Stopped);
}
sw.Pause();
UpdateStatistics(sw, rpc);
}
else
{
const long rpc = m_otl.Query(query);
sw.Pause();
UpdateStatistics(sw, rpc);
}
m_Shell->DocumentEnd();
}
void Frame::RunQueries(const wxString& text)
{
if (m_Results->IsShown())
{
m_Results->ClearGrid();
}
// Skip sql comments.
wxString output = text;
wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, "");
// Queries are seperated by ; character.
wxStringTokenizer tkz(output, ";");
int no_queries = 0;
wxStopWatch sw;
m_Running = true;
// Run all queries.
while (tkz.HasMoreTokens() && !m_Stopped)
{
wxString query = tkz.GetNextToken();
query.Trim(true);
query.Trim(false);
if (!query.empty())
{
try
{
RunQuery(query, no_queries == 0);
no_queries++;
wxTheApp->Yield();
}
catch (otl_exception& p)
{
m_Statistics.Inc(_("Number of query errors"));
m_Shell->AppendText(
_("\nerror: ") + wxExQuoted(p.msg) +
_(" in: ") + wxExQuoted(query));
}
}
}
m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"),
no_queries,
(float)sw.Time() / (float)1000));
m_Running = false;
}
void Frame::UpdateStatistics(const wxStopWatch& sw, long rpc)
{
m_Shell->AppendText(wxString::Format(_("\n%d rows processed (%.3f seconds)"),
rpc,
(float)sw.Time() / (float)1000));
m_Statistics.Set(_("Rows processed"), rpc);
m_Statistics.Set(_("Query runtime"), sw.Time());
m_Statistics.Inc(_("Total number of queries run"));
m_Statistics.Inc(_("Total query runtime"), sw.Time());
m_Statistics.Inc(_("Total rows processed"), rpc);
}
<commit_msg>fixed compile error<commit_after>/******************************************************************************\
* File: app.cpp
* Purpose: Implementation of classes for syncodbcquery
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2008-2009, Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/aboutdlg.h>
#include <wx/config.h>
#include <wx/regex.h>
#include <wx/tokenzr.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/grid.h>
#include <wx/extension/shell.h>
#include <wx/extension/util.h>
#include <wx/extension/version.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/stc.h>
#include <wx/extension/report/util.h>
#include "app.h"
#ifndef __WXMSW__
#include "app.xpm"
#endif
IMPLEMENT_APP(App)
bool App::OnInit()
{
SetAppName("syncodbcquery");
if (!wxExApp::OnInit())
{
return false;
}
Frame *frame = new Frame();
frame->Show(true);
SetTopWindow(frame);
return true;
}
BEGIN_EVENT_TABLE(Frame, wxExFrameWithHistory)
EVT_CLOSE(Frame::OnClose)
EVT_MENU(wxID_EXECUTE, Frame::OnCommand)
EVT_MENU(wxID_STOP, Frame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND, Frame::OnCommand)
EVT_MENU(ID_SHELL_COMMAND_STOP, Frame::OnCommand)
EVT_MENU_RANGE(wxID_CUT, wxID_CLEAR, Frame::OnCommand)
EVT_MENU_RANGE(wxID_OPEN, wxID_PREFERENCES, Frame::OnCommand)
EVT_MENU_RANGE(ID_FIRST, ID_LAST, Frame::OnCommand)
EVT_UPDATE_UI(wxID_SAVE, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_SAVEAS, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_STOP, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_DATABASE_CLOSE, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_DATABASE_OPEN, Frame::OnUpdateUI)
EVT_UPDATE_UI(wxID_EXECUTE, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_RECENTFILE_MENU, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_QUERY, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_RESULTS, Frame::OnUpdateUI)
EVT_UPDATE_UI(ID_VIEW_STATISTICS, Frame::OnUpdateUI)
END_EVENT_TABLE()
Frame::Frame()
: wxExFrameWithHistory(NULL, wxID_ANY, wxTheApp->GetAppName())
, m_Running(false)
, m_Stopped(false)
{
SetIcon(wxICON(app));
wxExMenu* menuFile = new wxExMenu;
menuFile->Append(wxID_NEW);
menuFile->Append(wxID_OPEN);
UseFileHistory(ID_RECENTFILE_MENU, menuFile);
menuFile->AppendSeparator();
menuFile->Append(wxID_SAVE);
menuFile->Append(wxID_SAVEAS);
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
wxExMenu* menuDatabase = new wxExMenu;
menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open")));
menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close"));
wxExMenu* menuQuery = new wxExMenu;
menuQuery->Append(wxID_EXECUTE);
menuQuery->Append(wxID_STOP);
wxMenu* menuOptions = new wxMenu();
menuOptions->Append(wxID_PREFERENCES);
wxMenu* menuView = new wxMenu();
menuView->AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar"));
menuView->AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar"));
menuView->AppendSeparator();
menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query"));
menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results"));
menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics"));
wxMenu* menuHelp = new wxMenu();
menuHelp->Append(wxID_ABOUT);
wxMenuBar *menubar = new wxMenuBar;
menubar->Append(menuFile, wxGetStockLabel(wxID_FILE));
menubar->Append(menuView, _("&View"));
menubar->Append(menuDatabase, _("&Connection"));
menubar->Append(menuQuery, _("&Query"));
menubar->Append(menuOptions, _("&Options"));
menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));
SetMenuBar(menubar);
m_Query = new wxExSTCWithFrame(this, this);
m_Query->SetLexer("sql");
m_Results = new wxExGrid(this);
m_Results->CreateGrid(0, 0);
m_Results->EnableEditing(false); // this is a read-only grid
m_Shell = new wxExSTCShell(this, ">", ";", true, 50);
m_Shell->SetFocus();
GetManager().AddPane(m_Shell,
wxAuiPaneInfo().
Name("CONSOLE").
CenterPane());
GetManager().AddPane(m_Results,
wxAuiPaneInfo().
Name("RESULTS").
Caption(_("Results")).
CloseButton(true).
MaximizeButton(true));
GetManager().AddPane(m_Query,
wxAuiPaneInfo().
Name("QUERY").
Caption(_("Query")).
CloseButton(true).
MaximizeButton(true));
GetManager().AddPane(m_Statistics.Show(this),
wxAuiPaneInfo().Left().
MaximizeButton(true).
Caption(_("Statistics")).
Name("STATISTICS"));
GetManager().LoadPerspective(wxConfigBase::Get()->Read("Perspective"));
GetManager().GetPane("QUERY").Show(false);
GetManager().Update();
#if wxUSE_STATUSBAR
std::vector<wxExPane> panes;
panes.push_back(wxExPane("PaneText", -3));
panes.push_back(wxExPane("PaneLines", 100, _("Lines in window")));
SetupStatusBar(panes);
#endif
CreateToolBar();
m_ToolBar->AddTool(wxID_NEW);
m_ToolBar->AddTool(wxID_OPEN);
m_ToolBar->AddTool(wxID_SAVE);
#ifdef __WXGTK__
m_ToolBar->AddTool(wxID_EXECUTE);
#endif
m_ToolBar->Realize();
}
void Frame::ConfigDialogApplied(wxWindowID dialogid)
{
if (dialogid == wxID_PREFERENCES)
{
m_Query->ConfigGet();
m_Shell->ConfigGet();
}
else
{
wxFAIL;
}
}
wxExGrid* Frame::GetGrid()
{
if (m_Results->IsShown())
{
return m_Results;
}
else
{
const wxExGrid* grid = m_Statistics.GetGrid();
if (grid != NULL && grid->IsShown())
{
return (wxExGrid*)grid;
}
else
{
return NULL;
}
}
}
wxExSTC* Frame::GetSTC()
{
if (m_Query->IsShown())
{
return m_Query;
}
else if (m_Shell->IsShown())
{
return m_Shell;
}
return NULL;
}
void Frame::OnClose(wxCloseEvent& event)
{
wxExFileDialog dlg(this, m_Query);
if (dlg.ShowModalIfChanged() == wxID_CANCEL)
{
return;
}
wxConfigBase::Get()->Write("Perspective", GetManager().SavePerspective());
event.Skip();
}
void Frame::OnCommand(wxCommandEvent& event)
{
switch (event.GetId())
{
case wxID_ABOUT:
{
wxAboutDialogInfo info;
info.SetIcon(GetIcon());
info.SetDescription(_("This program offers a general ODBC query."));
info.SetVersion("v1.0.1");
info.SetCopyright("(c) 2008-2009, Anton van Wezenbeek");
info.AddDeveloper(wxVERSION_STRING);
info.AddDeveloper(wxEX_VERSION_STRING);
info.AddDeveloper(wxExOTL::Version());
wxAboutBox(info);
}
break;
case wxID_EXECUTE:
m_Stopped = false;
RunQueries(m_Query->GetText());
break;
case wxID_EXIT:
Close(true);
break;
case wxID_NEW:
m_Query->FileNew();
m_Query->SetLexer("sql");
m_Query->SetFocus();
GetManager().GetPane("QUERY").Show();
GetManager().Update();
break;
case wxID_OPEN:
wxExOpenFilesDialog(
this,
wxFD_OPEN | wxFD_CHANGE_DIR,
"sql files (*.sql) | *.sql",
true);
break;
case wxID_PREFERENCES:
event.Skip();
break;
case wxID_SAVE:
m_Query->FileSave();
break;
case wxID_SAVEAS:
{
wxExFileDialog dlg(
this, m_Query,
_("File Save As"),
wxFileSelectorDefaultWildcardStr,
wxFD_SAVE);
if (dlg.ShowModal() == wxID_OK)
{
m_Query->FileSave(dlg.GetPath());
}
}
break;
case wxID_STOP:
m_Running = false;
m_Stopped = true;
break;
case ID_DATABASE_CLOSE:
m_otl.Logoff();
m_Shell->SetPrompt(">");
break;
case ID_DATABASE_OPEN:
m_otl.Logon(this);
m_Shell->SetPrompt(
(m_otl.IsConnected() ? wxConfigBase::Get()->Read(_("Datasource")): "") + ">");
break;
case ID_SHELL_COMMAND:
if (m_otl.IsConnected())
{
try
{
const wxString query = event.GetString().substr(
0,
event.GetString().length() - 1);
m_Stopped = false;
RunQuery(query, true);
}
catch (otl_exception& p)
{
if (m_Results->IsShown())
{
m_Results->EndBatch();
}
m_Shell->AppendText(_("\nerror: ") + wxExQuoted(p.msg));
}
}
else
{
m_Shell->AppendText(_("\nnot connected"));
}
m_Shell->Prompt();
break;
case ID_SHELL_COMMAND_STOP:
m_Stopped = true;
m_Shell->Prompt(_("cancelled"));
break;
case ID_VIEW_QUERY: TogglePane("QUERY"); break;
case ID_VIEW_RESULTS: TogglePane("RESULTS"); break;
case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break;
default:
wxFAIL;
}
}
void Frame::OnUpdateUI(wxUpdateUIEvent& event)
{
switch (event.GetId())
{
case wxID_EXECUTE:
// If we have a query, you can hide it, but still run it.
event.Enable(m_Query->GetLength() > 0 && m_otl.IsConnected());
break;
case wxID_SAVE:
event.Enable(m_Query->GetModify());
break;
case wxID_SAVEAS:
event.Enable(m_Query->GetLength() > 0);
break;
case wxID_STOP:
event.Enable(m_Running);
break;
case ID_DATABASE_CLOSE:
event.Enable(m_otl.IsConnected());
break;
case ID_DATABASE_OPEN:
event.Enable(!m_otl.IsConnected());
break;
case ID_RECENTFILE_MENU:
event.Enable(!GetRecentFile().empty());
break;
case ID_VIEW_QUERY:
event.Check(GetManager().GetPane("QUERY").IsShown());
break;
case ID_VIEW_RESULTS:
event.Check(GetManager().GetPane("RESULTS").IsShown());
break;
case ID_VIEW_STATISTICS:
event.Check(GetManager().GetPane("STATISTICS").IsShown());
break;
default:
wxFAIL;
}
}
bool Frame::OpenFile(
const wxExFileName& filename,
int line_number,
const wxString& match,
long flags)
{
GetManager().GetPane("QUERY").Show(true);
GetManager().Update();
// Take care that wxExOpenFilesDialog always results in opening in the query.
// Otherwise if results are focused, the file is opened in the results.
return m_Query->Open(filename, line_number, match, flags);
}
void Frame::RunQuery(const wxString& query, bool empty_results)
{
wxStopWatch sw;
const wxString query_lower = query.Lower();
// Query functions supported by ODBC
// $SQLTables, $SQLColumns, etc.
// $SQLTables $1:'%'
// allow you to get database schema.
if (query_lower.StartsWith("select") ||
query_lower.StartsWith("describe") ||
query_lower.StartsWith("show") ||
query_lower.StartsWith("explain") ||
query_lower.StartsWith("$sql"))
{
long rpc;
if (m_Results->IsShown())
{
rpc = m_otl.Query(query, m_Results, m_Stopped, empty_results);
}
else
{
rpc = m_otl.Query(query, m_Shell, m_Stopped);
}
sw.Pause();
UpdateStatistics(sw, rpc);
}
else
{
const long rpc = m_otl.Query(query);
sw.Pause();
UpdateStatistics(sw, rpc);
}
m_Shell->DocumentEnd();
}
void Frame::RunQueries(const wxString& text)
{
if (m_Results->IsShown())
{
m_Results->ClearGrid();
}
// Skip sql comments.
wxString output = text;
wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, "");
// Queries are seperated by ; character.
wxStringTokenizer tkz(output, ";");
int no_queries = 0;
wxStopWatch sw;
m_Running = true;
// Run all queries.
while (tkz.HasMoreTokens() && !m_Stopped)
{
wxString query = tkz.GetNextToken();
query.Trim(true);
query.Trim(false);
if (!query.empty())
{
try
{
RunQuery(query, no_queries == 0);
no_queries++;
wxTheApp->Yield();
}
catch (otl_exception& p)
{
m_Statistics.Inc(_("Number of query errors"));
m_Shell->AppendText(
_("\nerror: ") + wxExQuoted(p.msg) +
_(" in: ") + wxExQuoted(query));
}
}
}
m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"),
no_queries,
(float)sw.Time() / (float)1000));
m_Running = false;
}
void Frame::UpdateStatistics(const wxStopWatch& sw, long rpc)
{
m_Shell->AppendText(wxString::Format(_("\n%d rows processed (%.3f seconds)"),
rpc,
(float)sw.Time() / (float)1000));
m_Statistics.Set(_("Rows processed"), rpc);
m_Statistics.Set(_("Query runtime"), sw.Time());
m_Statistics.Inc(_("Total number of queries run"));
m_Statistics.Inc(_("Total query runtime"), sw.Time());
m_Statistics.Inc(_("Total rows processed"), rpc);
}
<|endoftext|>
|
<commit_before>#include "Poker.h"
#include "../GameObject.h"
#include "../Timer.h"
#include "../Advertisement.h"
Poker::Poker() :
m_InitialPlayers(4),
m_InitialMoney(1000),
m_RoundCounter(1),
m_PotMoney(0),
bettingCycle(1),
player0Frame(20, 16, 38, 7),
player1Frame(0 , 9, 38, 7),
player2Frame(20, 1, 38, 7),
player3Frame(40, 9, 38, 7),
m_HumanPlayer(0, m_InitialMoney, "Human"),
m_AiPlayer_1(1, m_InitialMoney, "West"),
m_AiPlayer_2(2, m_InitialMoney, "North"),
m_AiPlayer_3(3, m_InitialMoney, "East"),
m_Players(),
GAME_DISPLAY()
{
m_HumanPlayer.setFrame(&player0Frame);
m_AiPlayer_1.setFrame(&player1Frame);
m_AiPlayer_2.setFrame(&player2Frame);
m_AiPlayer_3.setFrame(&player3Frame);
m_Players.push_back(&m_AiPlayer_1);
m_Players.push_back(&m_AiPlayer_2);
m_Players.push_back(&m_AiPlayer_3);
m_Players.push_back(&m_HumanPlayer);
initializeDisplay();
}
Poker::~Poker() {}
void Poker::initializeDisplay() {
updateGameInfo();
}
void Poker::setTopBannerText(string text) {
GAME_DISPLAY.bannerTop(text);
}
void Poker::setBottomBannerText(string text) {
GAME_DISPLAY.bannerBottom(text);
}
void Poker::removePlayer(int position) {
Frame frame;
switch (position) {
case 0:
frame = player0Frame;
break;
case 1:
frame = player1Frame;
break;
case 2:
frame = player2Frame;
break;
case 3:
frame = player3Frame;
break;
default: return;
}
GAME_DISPLAY.eraseBox(frame.getX(), frame.getY(), frame.getWidth(), frame.getHeight());
}
void Poker::drawHand(HandD1 *hand, bool hidden, Frame *frame) {
int x = frame->getX(), y = frame->getY();
if (hidden) { //top player
for (int i = 0; i < 5; i++) {
GAME_DISPLAY.displayCard(x + 1 + i*7, y + 2, 0, 0, 0);
}
} else if (hand != NULL) { //display cards for human player
CardD1 *card;
for (int i = 0; i < 5; i++) {
card = hand->getCard(i);
GAME_DISPLAY.displayCard(x + 1 + i*7, y + 2, card->getSuit() + 1, card->getNumber(), 0);
}
}
}
void Poker::updateHand(HandD1 *hand, Frame *frame) {
if (hand != NULL) {
GAME_DISPLAY.eraseBox(frame->getX(), frame->getY(), frame->getWidth(), frame->getHeight());
drawHand(hand, false, frame);
}
}
//called whenever any player money or pot changes, or when round round or style changes
void Poker::updateGameInfo() {
stringstream bannerText;
bannerText << bannerHeader << " || ";
bannerText << "Me: $" << m_HumanPlayer.getMoney();
bannerText << " | W: $" << m_AiPlayer_1.getMoney();
bannerText << " | N: $" << m_AiPlayer_2.getMoney();
bannerText << " | E: $" << m_AiPlayer_3.getMoney();
bannerText << " | Pot: $" << m_PotMoney;
setTopBannerText(bannerText.str());
}
void Poker::rotatePlayers() {
PlayerD1 *tempPlayer = m_Players.front();
m_Players.pop_front();
m_Players.push_back(tempPlayer);
}
void Poker::removeCurrentPlayer() {
removePlayer(((PlayerD1 *)m_Players.front())->getDisplayPosition());
m_Players.pop_front();
}
void Poker::runAnte() {
stringstream bannerText;
Advertisement adGenerator;
bannerText << adGenerator.getAd();
//bannerText << "Round " << m_RoundCounter << ": Ante";
bannerHeader = bannerText.str();
updateGameInfo();
int a = ante();
for (int i = 0; i < (int)m_Players.size(); i++) {
PlayerD1 *player = m_Players.front();
if (typeid(*player) == typeid(HumanPlayer)) {
HumanPlayer *hPlayer = (HumanPlayer *) player;
if (hPlayer->ante(a, GAME_DISPLAY) == PlayerD1::FOLD) { //didn't ante, remove human player from game
endGame("No ante? You lose :(");
}
} else {
AI *cPlayer = (AI *) player;
if(cPlayer->ante(a, GAME_DISPLAY) == PlayerD1::FOLD) {
removeCurrentPlayer();
i--;
continue;
}
}
m_PotMoney += player->getMoneyInPot();
updateGameInfo();
rotatePlayers();
}
}
void Poker::runDeal() {
int i;
for (i = 0; i < rand() %1000; i++)
m_Deck.shuffle();
for (i = 0; i < (int)m_Players.size(); i++) {
CardD1 *c1 = m_Deck.drawCard();
CardD1 *c2 = m_Deck.drawCard();
CardD1 *c3 = m_Deck.drawCard();
CardD1 *c4 = m_Deck.drawCard();
CardD1 *c5 = m_Deck.drawCard();
m_Players[i]->setHand( new HandD1(c1, c2, c3, c4, c5) );
drawHand(NULL, true, m_Players[i]->getFrame());
}
updateHand(m_HumanPlayer.getHand(), &player0Frame);
}
void Poker::runBetting(int bettingCycle) {
stringstream bannerText;
bannerText << "Round " << m_RoundCounter << ": Betting Cycle " << bettingCycle;
bannerHeader = bannerText.str();
updateGameInfo();
int bet, callCounter = 0, minBet;
while (unfoldedPlayers() > 1) {
PlayerD1 *player = m_Players.front();
minBet = minimumBet(player);
if (player->folded()) {
callCounter++;
} else {
bet = player->bet(minBet, GAME_DISPLAY);
callCounter++;
if (bet != PlayerD1::FOLD) {
m_PotMoney += bet;
updateGameInfo();
if (bet > minBet) {
callCounter = 1;
}
} else {
removePlayer(player->getDisplayPosition());
}
}
if (callCounter >= unfoldedPlayers() || allPlayersAllIn())
break;
rotatePlayers();
}
}
int Poker::unfoldedPlayers() {
int unfolded = 0;
for (int i = 0; i < (int)m_Players.size(); i++) {
unfolded += (int) !m_Players[i]->folded();
}
return unfolded;
}
int Poker::runCardExchange() {
int discardCount = 0; //count how many cards the human discards
stringstream bannerText;
bannerText << "Round " << m_RoundCounter << ": Betting Cycle " << bettingCycle;
bannerHeader = bannerText.str();
updateGameInfo();
//bringHumanToFront();
for (int i = 0; i < (int)m_Players.size(); i++) {
PlayerD1 *player = m_Players.front();
if (!player->folded()) {
player->discard(GAME_DISPLAY);
for (int j = 0; j < 5; j++) {
if (player->getHand()->getCard(j)->isDiscarded()) {
m_Deck.discardCard(player->getHand()->exchange(m_Deck.drawCard(), j));
discardCount++;
}
}
if (typeid(*player) == typeid(HumanPlayer)) {
updateHand(player->getHand(), player->getFrame());
}
}
rotatePlayers();
}
return discardCount;
}
void Poker::runShowdown() {
for (int i = 0; i < (int)m_Players.size(); i++) {
if (m_Players[i]->folded()) {
removePlayer(m_Players[i]->getDisplayPosition());
} else {
updateHand(m_Players[i]->getHand(), m_Players[i]->getFrame());
}
}
}
bool Poker::roundIsOver() {
if (m_Players.size() == 1) return true;
PlayerD1 *winner;
if (unfoldedPlayers() == 1) {
for (int i = 0; i < (int)m_Players.size(); i++) {
if (!m_Players[i]->folded()) {
winner = m_Players[i];
break;
}
}
winner->giveMoney(m_PotMoney);
setBottomBannerText("Round over. <Press c to continue>");
finalizeRound();
return true;
}
return false;
}
int Poker::getRemainingPotMoney(){
int sum = 0;
for(int i = 0; i < (int)m_Players.size(); i++){
sum += m_Players[i]->getMoneyInPot();
}
return sum;
}
bool Poker::finishRound() {
PlayerD1* winner = NULL;
int *score;
for(int i = 0; i < (int)m_Players.size(); i++){
if (!m_Players[i]->folded() && m_Players[i]->getMoneyInPot() > 0) {
if (winner == NULL) {
winner = m_Players[i];
score = winner->getHand()->getScore();
} else if (m_Players[i]->getHand()->isHigherScore(score)) {
winner = m_Players[i];
score = winner->getHand()->getScore();
}
}
}
string outcome = (&m_HumanPlayer != winner )?"You lost :(":"You Win :)";
stringstream bannerText;
bannerText << outcome << "; c: continue";
setBottomBannerText(bannerText.str());
while(getRemainingPotMoney() > 0){
winner = NULL;
int *highscore;
//Determine the winningest player with non-zero pot money left
for(int i = 0; i < (int)m_Players.size(); i++){
if (!m_Players[i]->folded() && m_Players[i]->getMoneyInPot() > 0) {
if (winner == NULL) {
winner = m_Players[i];
highscore = winner->getHand()->getScore();
} else if (m_Players[i]->getHand()->isHigherScore(highscore)) {
winner = m_Players[i];
highscore = winner->getHand()->getScore();
}
}
}
//Add money to the bank
for (int i = 0; i < (int)m_Players.size(); i++) {
winner->giveMoney(min(winner->getMoneyInPot(), m_Players[i]->getMoneyInPot()));
}
vector<int> tmpPotMoney(m_Players.size());
int winnerPotMoney = winner->getMoneyInPot();
for (int i = 0; i < (int)m_Players.size(); i++) {
tmpPotMoney[i] = m_Players[i]->getMoneyInPot();
}
//Updates remaining money in the pot
for (int i = 0; i < (int)m_Players.size(); i++) {
m_Players[i]->setMoneyInPot(max(tmpPotMoney[i] - winnerPotMoney, 0));
}
}
finalizeRound();
return true;
}
void Poker::finalizeRound() {
for (int i = 0; i < (int)m_Players.size(); i++) {
m_Players[i]->setMoneyInPot(0);
}
bettingCycle++;
m_PotMoney = 0;
bannerHeader = "";
updateGameInfo();
int input;
while (1) {
input = GAME_DISPLAY.captureInput();
if (input == 'c' || input == 'C') {
break;
}
}
HandD1 *hand;
for (int i = 0; i < (int)m_Players.size(); i++) {
m_Players[i]->setFolded(false);
removePlayer(m_Players[i]->getDisplayPosition());
hand = m_Players[i]->getHand();
for (int j = 0; j < 5; j++) {
m_Deck.discardCard(hand->getCard(j));
}
//delete hands
}
}
void Poker::endGame(string endReason) {
int input;
stringstream bannerText;
bannerText << endReason << "; e:exit";
setBottomBannerText(bannerText.str());
while (1) {
input = GAME_DISPLAY.captureInput();
if (input == 'e' || input == 'E') {
return;
}
}
}
int Poker::ante() {
int num_players = m_Players.size();
switch (num_players) {
case 4:
return (int) (0.015 * (double)m_InitialMoney * (double)m_InitialPlayers);
break;
case 3:
return (int) (0.025 * (double)m_InitialMoney * (double)m_InitialPlayers);
break;
case 2:
return (int) (0.15 * (double)m_InitialMoney * (double)m_InitialPlayers);
break;
default:
return 0;
break;
}
}
int Poker::minimumBet(PlayerD1 *player) {
return ( maxSinglePlayerMoney() - player->getMoneyInPot() );
}
int Poker::maxSinglePlayerMoney() {
return max( m_HumanPlayer.getMoneyInPot(), max( m_AiPlayer_1.getMoneyInPot(), max( m_AiPlayer_2.getMoneyInPot(), m_AiPlayer_3.getMoneyInPot() ) ) );
}
bool Poker::allPlayersAllIn() {
bool allIn = true;
for (int i = 0; i < (int)m_Players.size(); i++) {
allIn = allIn && m_Players[i]->folded() || ( m_Players[i]->getMoney() == 0 );
}
return allIn;
}
void Poker::runGame(GameObject *game) {
game->D1Timer.checkIn();
m_HumanPlayer.setMoney(game->cash);
while (m_Players.size() > 1) {
//enter ante loop
runAnte();
if (roundIsOver()) continue;
//enter deal loop
runDeal();
game->cardsPlayed += 5;
//enter first betting loop
runBetting(1);
if (roundIsOver()) continue;
//enter card exchnage loop
game->cardsPlayed += runCardExchange();
//enter second betting loop
runBetting(2);
if (roundIsOver()) continue;
//enter showdown loop
runShowdown();
finishRound();
}
endGame("You Win!!");
game->cash = m_HumanPlayer.getMoney();
game->D1Timer.checkOut();
}
void Poker::mostlyRedraw(int sig) {
GAME_DISPLAY.handleResize(sig);
GAME_DISPLAY.eraseBox(0, 0, GAME_DISPLAY.getCols(), GAME_DISPLAY.getLines());
for (int i = 0; i < (int)m_Players.size(); i++) {
if (!m_Players[i]->folded()) {
updateHand(m_Players[i]->getHand(), m_Players[i]->getFrame());
}
}
updateGameInfo();
setBottomBannerText("");
}
<commit_msg>The game should actually end now<commit_after>#include "Poker.h"
#include "../GameObject.h"
#include "../Timer.h"
#include "../Advertisement.h"
Poker::Poker() :
m_InitialPlayers(4),
m_InitialMoney(1000),
m_RoundCounter(1),
m_PotMoney(0),
bettingCycle(1),
player0Frame(20, 16, 38, 7),
player1Frame(0 , 9, 38, 7),
player2Frame(20, 1, 38, 7),
player3Frame(40, 9, 38, 7),
m_HumanPlayer(0, m_InitialMoney, "Human"),
m_AiPlayer_1(1, m_InitialMoney, "West"),
m_AiPlayer_2(2, m_InitialMoney, "North"),
m_AiPlayer_3(3, m_InitialMoney, "East"),
m_Players(),
GAME_DISPLAY()
{
m_HumanPlayer.setFrame(&player0Frame);
m_AiPlayer_1.setFrame(&player1Frame);
m_AiPlayer_2.setFrame(&player2Frame);
m_AiPlayer_3.setFrame(&player3Frame);
m_Players.push_back(&m_AiPlayer_1);
m_Players.push_back(&m_AiPlayer_2);
m_Players.push_back(&m_AiPlayer_3);
m_Players.push_back(&m_HumanPlayer);
initializeDisplay();
}
Poker::~Poker() {}
void Poker::initializeDisplay() {
updateGameInfo();
}
void Poker::setTopBannerText(string text) {
GAME_DISPLAY.bannerTop(text);
}
void Poker::setBottomBannerText(string text) {
GAME_DISPLAY.bannerBottom(text);
}
void Poker::removePlayer(int position) {
Frame frame;
switch (position) {
case 0:
frame = player0Frame;
break;
case 1:
frame = player1Frame;
break;
case 2:
frame = player2Frame;
break;
case 3:
frame = player3Frame;
break;
default: return;
}
GAME_DISPLAY.eraseBox(frame.getX(), frame.getY(), frame.getWidth(), frame.getHeight());
}
void Poker::drawHand(HandD1 *hand, bool hidden, Frame *frame) {
int x = frame->getX(), y = frame->getY();
if (hidden) { //top player
for (int i = 0; i < 5; i++) {
GAME_DISPLAY.displayCard(x + 1 + i*7, y + 2, 0, 0, 0);
}
} else if (hand != NULL) { //display cards for human player
CardD1 *card;
for (int i = 0; i < 5; i++) {
card = hand->getCard(i);
GAME_DISPLAY.displayCard(x + 1 + i*7, y + 2, card->getSuit() + 1, card->getNumber(), 0);
}
}
}
void Poker::updateHand(HandD1 *hand, Frame *frame) {
if (hand != NULL) {
GAME_DISPLAY.eraseBox(frame->getX(), frame->getY(), frame->getWidth(), frame->getHeight());
drawHand(hand, false, frame);
}
}
//called whenever any player money or pot changes, or when round round or style changes
void Poker::updateGameInfo() {
stringstream bannerText;
bannerText << bannerHeader << " || ";
bannerText << "Me: $" << m_HumanPlayer.getMoney();
bannerText << " | W: $" << m_AiPlayer_1.getMoney();
bannerText << " | N: $" << m_AiPlayer_2.getMoney();
bannerText << " | E: $" << m_AiPlayer_3.getMoney();
bannerText << " | Pot: $" << m_PotMoney;
setTopBannerText(bannerText.str());
}
void Poker::rotatePlayers() {
PlayerD1 *tempPlayer = m_Players.front();
m_Players.pop_front();
m_Players.push_back(tempPlayer);
}
void Poker::removeCurrentPlayer() {
removePlayer(((PlayerD1 *)m_Players.front())->getDisplayPosition());
m_Players.pop_front();
}
void Poker::runAnte() {
stringstream bannerText;
Advertisement adGenerator;
bannerText << adGenerator.getAd();
//bannerText << "Round " << m_RoundCounter << ": Ante";
bannerHeader = bannerText.str();
updateGameInfo();
int a = ante();
for (int i = 0; i < (int)m_Players.size(); i++) {
PlayerD1 *player = m_Players.front();
if (typeid(*player) == typeid(HumanPlayer)) {
HumanPlayer *hPlayer = (HumanPlayer *) player;
if (hPlayer->ante(a, GAME_DISPLAY) == PlayerD1::FOLD) { //didn't ante, remove human player from game
m_Players.clear();
endGame("You didn't ante!? You gotta go. :(");
return;
}
} else {
AI *cPlayer = (AI *) player;
if(cPlayer->ante(a, GAME_DISPLAY) == PlayerD1::FOLD) {
removeCurrentPlayer();
i--;
continue;
}
}
m_PotMoney += player->getMoneyInPot();
updateGameInfo();
rotatePlayers();
}
}
void Poker::runDeal() {
int i;
for (i = 0; i < rand() %1000; i++)
m_Deck.shuffle();
for (i = 0; i < (int)m_Players.size(); i++) {
CardD1 *c1 = m_Deck.drawCard();
CardD1 *c2 = m_Deck.drawCard();
CardD1 *c3 = m_Deck.drawCard();
CardD1 *c4 = m_Deck.drawCard();
CardD1 *c5 = m_Deck.drawCard();
m_Players[i]->setHand( new HandD1(c1, c2, c3, c4, c5) );
drawHand(NULL, true, m_Players[i]->getFrame());
}
updateHand(m_HumanPlayer.getHand(), &player0Frame);
}
void Poker::runBetting(int bettingCycle) {
stringstream bannerText;
bannerText << "Round " << m_RoundCounter << ": Betting Cycle " << bettingCycle;
bannerHeader = bannerText.str();
updateGameInfo();
int bet, callCounter = 0, minBet;
while (unfoldedPlayers() > 1) {
PlayerD1 *player = m_Players.front();
minBet = minimumBet(player);
if (player->folded()) {
callCounter++;
} else {
bet = player->bet(minBet, GAME_DISPLAY);
callCounter++;
if (bet != PlayerD1::FOLD) {
m_PotMoney += bet;
updateGameInfo();
if (bet > minBet) {
callCounter = 1;
}
} else {
removePlayer(player->getDisplayPosition());
}
}
if (callCounter >= unfoldedPlayers() || allPlayersAllIn())
break;
rotatePlayers();
}
}
int Poker::unfoldedPlayers() {
int unfolded = 0;
for (int i = 0; i < (int)m_Players.size(); i++) {
unfolded += (int) !m_Players[i]->folded();
}
return unfolded;
}
int Poker::runCardExchange() {
int discardCount = 0; //count how many cards the human discards
stringstream bannerText;
bannerText << "Round " << m_RoundCounter << ": Betting Cycle " << bettingCycle;
bannerHeader = bannerText.str();
updateGameInfo();
//bringHumanToFront();
for (int i = 0; i < (int)m_Players.size(); i++) {
PlayerD1 *player = m_Players.front();
if (!player->folded()) {
player->discard(GAME_DISPLAY);
for (int j = 0; j < 5; j++) {
if (player->getHand()->getCard(j)->isDiscarded()) {
m_Deck.discardCard(player->getHand()->exchange(m_Deck.drawCard(), j));
discardCount++;
}
}
if (typeid(*player) == typeid(HumanPlayer)) {
updateHand(player->getHand(), player->getFrame());
}
}
rotatePlayers();
}
return discardCount;
}
void Poker::runShowdown() {
for (int i = 0; i < (int)m_Players.size(); i++) {
if (m_Players[i]->folded()) {
removePlayer(m_Players[i]->getDisplayPosition());
} else {
updateHand(m_Players[i]->getHand(), m_Players[i]->getFrame());
}
}
}
bool Poker::roundIsOver() {
if (m_Players.size() == 1) return true;
PlayerD1 *winner;
if (unfoldedPlayers() == 1) {
for (int i = 0; i < (int)m_Players.size(); i++) {
if (!m_Players[i]->folded()) {
winner = m_Players[i];
break;
}
}
winner->giveMoney(m_PotMoney);
setBottomBannerText("Round over. <Press c to continue>");
finalizeRound();
return true;
}
return false;
}
int Poker::getRemainingPotMoney(){
int sum = 0;
for(int i = 0; i < (int)m_Players.size(); i++){
sum += m_Players[i]->getMoneyInPot();
}
return sum;
}
bool Poker::finishRound() {
PlayerD1* winner = NULL;
int *score;
for(int i = 0; i < (int)m_Players.size(); i++){
if (!m_Players[i]->folded() && m_Players[i]->getMoneyInPot() > 0) {
if (winner == NULL) {
winner = m_Players[i];
score = winner->getHand()->getScore();
} else if (m_Players[i]->getHand()->isHigherScore(score)) {
winner = m_Players[i];
score = winner->getHand()->getScore();
}
}
}
string outcome = (&m_HumanPlayer != winner )?"You lost :(":"You Win :)";
stringstream bannerText;
bannerText << outcome << "; c: continue";
setBottomBannerText(bannerText.str());
while(getRemainingPotMoney() > 0){
winner = NULL;
int *highscore;
//Determine the winningest player with non-zero pot money left
for(int i = 0; i < (int)m_Players.size(); i++){
if (!m_Players[i]->folded() && m_Players[i]->getMoneyInPot() > 0) {
if (winner == NULL) {
winner = m_Players[i];
highscore = winner->getHand()->getScore();
} else if (m_Players[i]->getHand()->isHigherScore(highscore)) {
winner = m_Players[i];
highscore = winner->getHand()->getScore();
}
}
}
//Add money to the bank
for (int i = 0; i < (int)m_Players.size(); i++) {
winner->giveMoney(min(winner->getMoneyInPot(), m_Players[i]->getMoneyInPot()));
}
vector<int> tmpPotMoney(m_Players.size());
int winnerPotMoney = winner->getMoneyInPot();
for (int i = 0; i < (int)m_Players.size(); i++) {
tmpPotMoney[i] = m_Players[i]->getMoneyInPot();
}
//Updates remaining money in the pot
for (int i = 0; i < (int)m_Players.size(); i++) {
m_Players[i]->setMoneyInPot(max(tmpPotMoney[i] - winnerPotMoney, 0));
}
}
finalizeRound();
return true;
}
void Poker::finalizeRound() {
for (int i = 0; i < (int)m_Players.size(); i++) {
m_Players[i]->setMoneyInPot(0);
}
bettingCycle++;
m_PotMoney = 0;
bannerHeader = "";
updateGameInfo();
int input;
while (1) {
input = GAME_DISPLAY.captureInput();
if (input == 'c' || input == 'C') {
break;
}
}
HandD1 *hand;
for (int i = 0; i < (int)m_Players.size(); i++) {
m_Players[i]->setFolded(false);
removePlayer(m_Players[i]->getDisplayPosition());
hand = m_Players[i]->getHand();
for (int j = 0; j < 5; j++) {
m_Deck.discardCard(hand->getCard(j));
}
//delete hands
}
}
void Poker::endGame(string endReason) {
int input;
stringstream bannerText;
bannerText << endReason << "; e:exit";
setBottomBannerText(bannerText.str());
while (1) {
input = GAME_DISPLAY.captureInput();
if (input == 'e' || input == 'E') {
return;
}
}
}
int Poker::ante() {
int num_players = m_Players.size();
switch (num_players) {
case 4:
return (int) (0.015 * (double)m_InitialMoney * (double)m_InitialPlayers);
break;
case 3:
return (int) (0.025 * (double)m_InitialMoney * (double)m_InitialPlayers);
break;
case 2:
return (int) (0.15 * (double)m_InitialMoney * (double)m_InitialPlayers);
break;
default:
return 0;
break;
}
}
int Poker::minimumBet(PlayerD1 *player) {
return ( maxSinglePlayerMoney() - player->getMoneyInPot() );
}
int Poker::maxSinglePlayerMoney() {
return max( m_HumanPlayer.getMoneyInPot(), max( m_AiPlayer_1.getMoneyInPot(), max( m_AiPlayer_2.getMoneyInPot(), m_AiPlayer_3.getMoneyInPot() ) ) );
}
bool Poker::allPlayersAllIn() {
bool allIn = true;
for (int i = 0; i < (int)m_Players.size(); i++) {
allIn = allIn && m_Players[i]->folded() || ( m_Players[i]->getMoney() == 0 );
}
return allIn;
}
void Poker::runGame(GameObject *game) {
game->D1Timer.checkIn();
m_HumanPlayer.setMoney(game->cash);
while (m_Players.size() > 1) {
//enter ante loop
runAnte();
if (roundIsOver()) continue;
//enter deal loop
runDeal();
game->cardsPlayed += 5;
//enter first betting loop
runBetting(1);
if (roundIsOver()) continue;
//enter card exchnage loop
game->cardsPlayed += runCardExchange();
//enter second betting loop
runBetting(2);
if (roundIsOver()) continue;
//enter showdown loop
runShowdown();
finishRound();
}
endGame("You didn't lose! Hooray!");
game->cash = m_HumanPlayer.getMoney();
game->D1Timer.checkOut();
}
void Poker::mostlyRedraw(int sig) {
GAME_DISPLAY.handleResize(sig);
GAME_DISPLAY.eraseBox(0, 0, GAME_DISPLAY.getCols(), GAME_DISPLAY.getLines());
for (int i = 0; i < (int)m_Players.size(); i++) {
if (!m_Players[i]->folded()) {
updateHand(m_Players[i]->getHand(), m_Players[i]->getFrame());
}
}
updateGameInfo();
setBottomBannerText("");
}
<|endoftext|>
|
<commit_before>#include "Poker.h"
#include "../GameObject.h"
#include "../Advertisement.h"
Poker::Poker() :
m_InitialPlayers(4),
m_InitialMoney(*playerBalance),
m_RoundCounter(1),
m_PotMoney(0),
bettingCycle(1),
player0Frame(20, 16, 38, 7),
player1Frame(0 , 9, 38, 7),
player2Frame(20, 1, 38, 7),
player3Frame(40, 9, 38, 7),
m_HumanPlayer(0, m_InitialMoney, "Human"),
m_AiPlayer_1(1, m_InitialMoney, "West"),
m_AiPlayer_2(2, m_InitialMoney, "North"),
m_AiPlayer_3(3, m_InitialMoney, "East"),
m_Players(),
GAME_DISPLAY()
{
m_HumanPlayer.setFrame(&player0Frame);
m_AiPlayer_1.setFrame(&player1Frame);
m_AiPlayer_2.setFrame(&player2Frame);
m_AiPlayer_3.setFrame(&player3Frame);
m_Players.push_back(&m_AiPlayer_1);
m_Players.push_back(&m_AiPlayer_2);
m_Players.push_back(&m_AiPlayer_3);
m_Players.push_back(&m_HumanPlayer);
initializeDisplay();
}
Poker::~Poker() {}
#pragma mark - Display
void Poker::initializeDisplay() {
updateGameInfo();
}
void Poker::setTopBannerText(string text) {
GAME_DISPLAY.bannerTop(text);
}
void Poker::setBottomBannerText(string text) {
GAME_DISPLAY.bannerBottom(text);
}
void Poker::removePlayer(int position) {
Frame frame;
switch (position) {
case 0:
frame = player0Frame;
break;
case 1:
frame = player1Frame;
break;
case 2:
frame = player2Frame;
break;
case 3:
frame = player3Frame;
break;
default: return;
}
GAME_DISPLAY.eraseBox(frame.getX(), frame.getY(), frame.getWidth(), frame.getHeight());
}
void Poker::drawHand(Hand *hand, bool hidden, Frame *frame) {
int x = frame->getX(), y = frame->getY(), w = frame->getWidth(), h = frame->getHeight();
if (hidden) { //top player
for (int i = 0; i < 5; i++) {
GAME_DISPLAY.displayCard(x + 1 + i*7, y + 2, 0, 0, 0);
}
} else if (hand != NULL) { //display cards for human player
Card *card;
for (int i = 0; i < 5; i++) {
card = hand->getCard(i);
GAME_DISPLAY.displayCard(x + 1 + i*7, y + 2, card->getSuit() + 1, card->getNumber(), 0);
}
}
}
void Poker::updateHand(Hand *hand, Frame *frame) {
if (hand != NULL) {
GAME_DISPLAY.eraseBox(frame->getX(), frame->getY(), frame->getWidth(), frame->getHeight());
drawHand(hand, false, frame);
}
}
//called whenever any player money or pot changes, or when round round or style changes
void Poker::updateGameInfo() {
stringstream bannerText;
bannerText << bannerHeader << " || ";
bannerText << "Me: $" << m_HumanPlayer.getMoney();
bannerText << " | W: $" << m_AiPlayer_1.getMoney();
bannerText << " | N: $" << m_AiPlayer_2.getMoney();
bannerText << " | E: $" << m_AiPlayer_3.getMoney();
bannerText << " | Pot: $" << m_PotMoney;
setTopBannerText(bannerText.str());
}
#pragma mark - deque manipulate methods
void Poker::rotatePlayers() {
Player *tempPlayer = m_Players.front();
m_Players.pop_front();
m_Players.push_back(tempPlayer);
}
void Poker::removeCurrentPlayer() {
removePlayer(((Player *)m_Players.front())->getDisplayPosition());
m_Players.pop_front();
}
#pragma mark - Game Play
void Poker::runAnte() {
stringstream bannerText;
Advertisement adGenerator;
bannerText << adGenerator.getAd();
//bannerText << "Round " << m_RoundCounter << ": Ante";
bannerHeader = bannerText.str();
updateGameInfo();
int a = ante();
for (int i = 0; i < m_Players.size(); i++) {
Player *player = m_Players.front();
if (typeid(*player) == typeid(HumanPlayer)) {
HumanPlayer *hPlayer = (HumanPlayer *) player;
if (hPlayer->ante(a, GAME_DISPLAY) == Player::FOLD) { //didn't ante, remove human player from game
endGame("No ante? You lose :(");
}
} else {
AI *cPlayer = (AI *) player;
if(cPlayer->ante(a, GAME_DISPLAY) == Player::FOLD) {
removeCurrentPlayer();
i--;
continue;
}
}
m_PotMoney += player->getMoneyInPot();
updateGameInfo();
rotatePlayers();
}
}
void Poker::runDeal() {
int i;
for (i = 0; i < rand() %1000; i++)
m_Deck.shuffle();
for (i = 0; i < m_Players.size(); i++) {
Card *c1 = m_Deck.drawCard();
Card *c2 = m_Deck.drawCard();
Card *c3 = m_Deck.drawCard();
Card *c4 = m_Deck.drawCard();
Card *c5 = m_Deck.drawCard();
m_Players[i]->setHand( new Hand(c1, c2, c3, c4, c5) );
drawHand(NULL, true, m_Players[i]->getFrame());
}
updateHand(m_HumanPlayer.getHand(), &player0Frame);
//Keeps track of how many cards the human has been given
*m_playedCards += 5;
}
void Poker::runBetting(int bettingCycle) {
stringstream bannerText;
bannerText << "Round " << m_RoundCounter << ": Betting Cycle " << bettingCycle;
bannerHeader = bannerText.str();
updateGameInfo();
int bet, callCounter = 0, minBet;
while (unfoldedPlayers() > 1) {
Player *player = m_Players.front();
minBet = minimumBet(player);
if (player->folded()) {
callCounter++;
} else {
bet = player->bet(minBet, GAME_DISPLAY);
callCounter++;
if (bet != Player::FOLD) {
m_PotMoney += bet;
updateGameInfo();
if (bet > minBet) {
callCounter = 1;
}
} else {
removePlayer(player->getDisplayPosition());
}
}
if (callCounter >= unfoldedPlayers() || allPlayersAllIn())
break;
rotatePlayers();
}
}
int Poker::unfoldedPlayers() {
int unfolded = 0;
for (int i = 0; i < m_Players.size(); i++) {
unfolded += (int) !m_Players[i]->folded();
}
return unfolded;
}
int Poker::runCardExchange() {
int discardCount = 0; //count how many cards the human discards
stringstream bannerText;
bannerText << "Round " << m_RoundCounter << ": Betting Cycle " << bettingCycle;
bannerHeader = bannerText.str();
updateGameInfo();
//bringHumanToFront();
for (int i = 0; i < m_Players.size(); i++) {
Player *player = m_Players.front();
if (!player->folded()) {
player->discard(GAME_DISPLAY);
for (int j = 0; j < 5; j++) {
if (player->getHand()->getCard(j)->isDiscarded()) {
m_Deck.discardCard(player->getHand()->exchange(m_Deck.drawCard(), j));
discardCount++;
}
}
if (typeid(*player) == typeid(HumanPlayer)) {
updateHand(player->getHand(), player->getFrame());
}
}
rotatePlayers();
}
return discardCount;
}
void Poker::runShowdown() {
for (int i = 0; i < m_Players.size(); i++) {
if (m_Players[i]->folded()) {
removePlayer(m_Players[i]->getDisplayPosition());
} else {
updateHand(m_Players[i]->getHand(), m_Players[i]->getFrame());
}
}
}
bool Poker::roundIsOver() {
if (m_Players.size() == 1) return true;
Player *winner;
if (unfoldedPlayers() == 1) {
for (int i = 0; i < m_Players.size(); i++) {
if (!m_Players[i]->folded()) {
winner = m_Players[i];
break;
}
}
winner->giveMoney(m_PotMoney);
setBottomBannerText("Round over. <Press c to continue>");
finalizeRound();
return true;
}
return false;
}
int Poker::getRemainingPotMoney(){
int sum = 0;
for(int i = 0; i < m_Players.size(); i++){
sum += m_Players[i]->getMoneyInPot();
}
return sum;
}
bool Poker::finishRound() {
Player* winner = NULL;
int *score;
for(int i = 0; i < m_Players.size(); i++){
if (!m_Players[i]->folded() && m_Players[i]->getMoneyInPot() > 0) {
if (winner == NULL) {
winner = m_Players[i];
score = winner->getHand()->getScore();
} else if (m_Players[i]->getHand()->isHigherScore(score)) {
winner = m_Players[i];
score = winner->getHand()->getScore();
}
}
}
string outcome = (&m_HumanPlayer != winner )?"You lost :(":"You Win :)";
stringstream bannerText;
bannerText << outcome << "; c: continue";
setBottomBannerText(bannerText.str());
while(getRemainingPotMoney() > 0){
winner = NULL;
int *highscore;
//Determine the winningest player with non-zero pot money left
for(int i = 0; i < m_Players.size(); i++){
if (!m_Players[i]->folded() && m_Players[i]->getMoneyInPot() > 0) {
if (winner == NULL) {
winner = m_Players[i];
highscore = winner->getHand()->getScore();
} else if (m_Players[i]->getHand()->isHigherScore(highscore)) {
winner = m_Players[i];
highscore = winner->getHand()->getScore();
}
}
}
//Add money to the bank
for (int i = 0; i < m_Players.size(); i++) {
winner->giveMoney(min(winner->getMoneyInPot(), m_Players[i]->getMoneyInPot()));
}
vector<int> tmpPotMoney(m_Players.size());
int winnerPotMoney = winner->getMoneyInPot();
for (int i = 0; i < m_Players.size(); i++) {
tmpPotMoney[i] = m_Players[i]->getMoneyInPot();
}
//Updates remaining money in the pot
for (int i = 0; i < m_Players.size(); i++) {
m_Players[i]->setMoneyInPot(max(tmpPotMoney[i] - winnerPotMoney, 0));
}
}
finalizeRound();
return true;
}
void Poker::finalizeRound() {
for (int i = 0; i < m_Players.size(); i++) {
m_Players[i]->setMoneyInPot(0);
}
bettingCycle++;
m_PotMoney = 0;
bannerHeader = "";
updateGameInfo();
int input;
while (1) {
input = GAME_DISPLAY.captureInput();
if (input == 'c' || input == 'C') {
break;
}
}
Hand *hand;
for (int i = 0; i < m_Players.size(); i++) {
m_Players[i]->setFolded(false);
removePlayer(m_Players[i]->getDisplayPosition());
hand = m_Players[i]->getHand();
for (int j = 0; j < 5; j++) {
m_Deck.discardCard(hand->getCard(j));
}
//delete hands
}
}
void Poker::endGame(string endReason) {
int input;
stringstream bannerText;
bannerText << endReason << "; e:exit";
setBottomBannerText(bannerText.str());
while (1) {
input = GAME_DISPLAY.captureInput();
if (input == 'e' || input == 'E') {
return;
}
}
}
#pragma mark - Misc. Controls
int Poker::ante() {
int num_players = m_Players.size();
switch (num_players) {
case 4:
return (int) (0.015 * (double)m_InitialMoney * (double)m_InitialPlayers);
break;
case 3:
return (int) (0.025 * (double)m_InitialMoney * (double)m_InitialPlayers);
break;
case 2:
return (int) (0.15 * (double)m_InitialMoney * (double)m_InitialPlayers);
break;
default:
return 0;
break;
}
}
int Poker::minimumBet(Player *player) {
return ( maxSinglePlayerMoney() - player->getMoneyInPot() );
}
int Poker::maxSinglePlayerMoney() {
return max( m_HumanPlayer.getMoneyInPot(), max( m_AiPlayer_1.getMoneyInPot(), max( m_AiPlayer_2.getMoneyInPot(), m_AiPlayer_3.getMoneyInPot() ) ) );
}
bool Poker::allPlayersAllIn() {
bool allIn = true;
for (int i = 0; i < m_Players.size(); i++) {
allIn = allIn && m_Players[i]->folded() || ( m_Players[i]->getMoney() == 0 );
}
return allIn;
}
#pragma mark - MAIN
void Poker::runGame(GameObject &game) {
game.timer.checkIn();
m_HumanPlayer.setMoney(game.cash);
while (m_Players.size() > 1) {
//enter ante loop
runAnte();
if (roundIsOver()) continue;
//enter deal loop
runDeal();
game.cardsPlayed += 5;
//enter first betting loop
runBetting(1);
if (roundIsOver()) continue;
//enter card exchnage loop
game.cardsPlayed += runCardExchange();
//enter second betting loop
runBetting(2);
if (roundIsOver()) continue;
//enter showdown loop
runShowdown();
finishRound();
}
poker.endGame("You Win!!");
game.cash = m_HumanPlayer.getMoney();
game.timer.checkOut();
}
<commit_msg>Removed old, unecessary variables from Poker<commit_after>#include "Poker.h"
#include "../GameObject.h"
#include "../Advertisement.h"
Poker::Poker() :
m_InitialPlayers(4),
m_InitialMoney(1000),
m_RoundCounter(1),
m_PotMoney(0),
bettingCycle(1),
player0Frame(20, 16, 38, 7),
player1Frame(0 , 9, 38, 7),
player2Frame(20, 1, 38, 7),
player3Frame(40, 9, 38, 7),
m_HumanPlayer(0, m_InitialMoney, "Human"),
m_AiPlayer_1(1, m_InitialMoney, "West"),
m_AiPlayer_2(2, m_InitialMoney, "North"),
m_AiPlayer_3(3, m_InitialMoney, "East"),
m_Players(),
GAME_DISPLAY()
{
m_HumanPlayer.setFrame(&player0Frame);
m_AiPlayer_1.setFrame(&player1Frame);
m_AiPlayer_2.setFrame(&player2Frame);
m_AiPlayer_3.setFrame(&player3Frame);
m_Players.push_back(&m_AiPlayer_1);
m_Players.push_back(&m_AiPlayer_2);
m_Players.push_back(&m_AiPlayer_3);
m_Players.push_back(&m_HumanPlayer);
initializeDisplay();
}
Poker::~Poker() {}
#pragma mark - Display
void Poker::initializeDisplay() {
updateGameInfo();
}
void Poker::setTopBannerText(string text) {
GAME_DISPLAY.bannerTop(text);
}
void Poker::setBottomBannerText(string text) {
GAME_DISPLAY.bannerBottom(text);
}
void Poker::removePlayer(int position) {
Frame frame;
switch (position) {
case 0:
frame = player0Frame;
break;
case 1:
frame = player1Frame;
break;
case 2:
frame = player2Frame;
break;
case 3:
frame = player3Frame;
break;
default: return;
}
GAME_DISPLAY.eraseBox(frame.getX(), frame.getY(), frame.getWidth(), frame.getHeight());
}
void Poker::drawHand(Hand *hand, bool hidden, Frame *frame) {
int x = frame->getX(), y = frame->getY(), w = frame->getWidth(), h = frame->getHeight();
if (hidden) { //top player
for (int i = 0; i < 5; i++) {
GAME_DISPLAY.displayCard(x + 1 + i*7, y + 2, 0, 0, 0);
}
} else if (hand != NULL) { //display cards for human player
Card *card;
for (int i = 0; i < 5; i++) {
card = hand->getCard(i);
GAME_DISPLAY.displayCard(x + 1 + i*7, y + 2, card->getSuit() + 1, card->getNumber(), 0);
}
}
}
void Poker::updateHand(Hand *hand, Frame *frame) {
if (hand != NULL) {
GAME_DISPLAY.eraseBox(frame->getX(), frame->getY(), frame->getWidth(), frame->getHeight());
drawHand(hand, false, frame);
}
}
//called whenever any player money or pot changes, or when round round or style changes
void Poker::updateGameInfo() {
stringstream bannerText;
bannerText << bannerHeader << " || ";
bannerText << "Me: $" << m_HumanPlayer.getMoney();
bannerText << " | W: $" << m_AiPlayer_1.getMoney();
bannerText << " | N: $" << m_AiPlayer_2.getMoney();
bannerText << " | E: $" << m_AiPlayer_3.getMoney();
bannerText << " | Pot: $" << m_PotMoney;
setTopBannerText(bannerText.str());
}
#pragma mark - deque manipulate methods
void Poker::rotatePlayers() {
Player *tempPlayer = m_Players.front();
m_Players.pop_front();
m_Players.push_back(tempPlayer);
}
void Poker::removeCurrentPlayer() {
removePlayer(((Player *)m_Players.front())->getDisplayPosition());
m_Players.pop_front();
}
#pragma mark - Game Play
void Poker::runAnte() {
stringstream bannerText;
Advertisement adGenerator;
bannerText << adGenerator.getAd();
//bannerText << "Round " << m_RoundCounter << ": Ante";
bannerHeader = bannerText.str();
updateGameInfo();
int a = ante();
for (int i = 0; i < m_Players.size(); i++) {
Player *player = m_Players.front();
if (typeid(*player) == typeid(HumanPlayer)) {
HumanPlayer *hPlayer = (HumanPlayer *) player;
if (hPlayer->ante(a, GAME_DISPLAY) == Player::FOLD) { //didn't ante, remove human player from game
endGame("No ante? You lose :(");
}
} else {
AI *cPlayer = (AI *) player;
if(cPlayer->ante(a, GAME_DISPLAY) == Player::FOLD) {
removeCurrentPlayer();
i--;
continue;
}
}
m_PotMoney += player->getMoneyInPot();
updateGameInfo();
rotatePlayers();
}
}
void Poker::runDeal() {
int i;
for (i = 0; i < rand() %1000; i++)
m_Deck.shuffle();
for (i = 0; i < m_Players.size(); i++) {
Card *c1 = m_Deck.drawCard();
Card *c2 = m_Deck.drawCard();
Card *c3 = m_Deck.drawCard();
Card *c4 = m_Deck.drawCard();
Card *c5 = m_Deck.drawCard();
m_Players[i]->setHand( new Hand(c1, c2, c3, c4, c5) );
drawHand(NULL, true, m_Players[i]->getFrame());
}
updateHand(m_HumanPlayer.getHand(), &player0Frame);
//Keeps track of how many cards the human has been given
*m_playedCards += 5;
}
void Poker::runBetting(int bettingCycle) {
stringstream bannerText;
bannerText << "Round " << m_RoundCounter << ": Betting Cycle " << bettingCycle;
bannerHeader = bannerText.str();
updateGameInfo();
int bet, callCounter = 0, minBet;
while (unfoldedPlayers() > 1) {
Player *player = m_Players.front();
minBet = minimumBet(player);
if (player->folded()) {
callCounter++;
} else {
bet = player->bet(minBet, GAME_DISPLAY);
callCounter++;
if (bet != Player::FOLD) {
m_PotMoney += bet;
updateGameInfo();
if (bet > minBet) {
callCounter = 1;
}
} else {
removePlayer(player->getDisplayPosition());
}
}
if (callCounter >= unfoldedPlayers() || allPlayersAllIn())
break;
rotatePlayers();
}
}
int Poker::unfoldedPlayers() {
int unfolded = 0;
for (int i = 0; i < m_Players.size(); i++) {
unfolded += (int) !m_Players[i]->folded();
}
return unfolded;
}
int Poker::runCardExchange() {
int discardCount = 0; //count how many cards the human discards
stringstream bannerText;
bannerText << "Round " << m_RoundCounter << ": Betting Cycle " << bettingCycle;
bannerHeader = bannerText.str();
updateGameInfo();
//bringHumanToFront();
for (int i = 0; i < m_Players.size(); i++) {
Player *player = m_Players.front();
if (!player->folded()) {
player->discard(GAME_DISPLAY);
for (int j = 0; j < 5; j++) {
if (player->getHand()->getCard(j)->isDiscarded()) {
m_Deck.discardCard(player->getHand()->exchange(m_Deck.drawCard(), j));
discardCount++;
}
}
if (typeid(*player) == typeid(HumanPlayer)) {
updateHand(player->getHand(), player->getFrame());
}
}
rotatePlayers();
}
return discardCount;
}
void Poker::runShowdown() {
for (int i = 0; i < m_Players.size(); i++) {
if (m_Players[i]->folded()) {
removePlayer(m_Players[i]->getDisplayPosition());
} else {
updateHand(m_Players[i]->getHand(), m_Players[i]->getFrame());
}
}
}
bool Poker::roundIsOver() {
if (m_Players.size() == 1) return true;
Player *winner;
if (unfoldedPlayers() == 1) {
for (int i = 0; i < m_Players.size(); i++) {
if (!m_Players[i]->folded()) {
winner = m_Players[i];
break;
}
}
winner->giveMoney(m_PotMoney);
setBottomBannerText("Round over. <Press c to continue>");
finalizeRound();
return true;
}
return false;
}
int Poker::getRemainingPotMoney(){
int sum = 0;
for(int i = 0; i < m_Players.size(); i++){
sum += m_Players[i]->getMoneyInPot();
}
return sum;
}
bool Poker::finishRound() {
Player* winner = NULL;
int *score;
for(int i = 0; i < m_Players.size(); i++){
if (!m_Players[i]->folded() && m_Players[i]->getMoneyInPot() > 0) {
if (winner == NULL) {
winner = m_Players[i];
score = winner->getHand()->getScore();
} else if (m_Players[i]->getHand()->isHigherScore(score)) {
winner = m_Players[i];
score = winner->getHand()->getScore();
}
}
}
string outcome = (&m_HumanPlayer != winner )?"You lost :(":"You Win :)";
stringstream bannerText;
bannerText << outcome << "; c: continue";
setBottomBannerText(bannerText.str());
while(getRemainingPotMoney() > 0){
winner = NULL;
int *highscore;
//Determine the winningest player with non-zero pot money left
for(int i = 0; i < m_Players.size(); i++){
if (!m_Players[i]->folded() && m_Players[i]->getMoneyInPot() > 0) {
if (winner == NULL) {
winner = m_Players[i];
highscore = winner->getHand()->getScore();
} else if (m_Players[i]->getHand()->isHigherScore(highscore)) {
winner = m_Players[i];
highscore = winner->getHand()->getScore();
}
}
}
//Add money to the bank
for (int i = 0; i < m_Players.size(); i++) {
winner->giveMoney(min(winner->getMoneyInPot(), m_Players[i]->getMoneyInPot()));
}
vector<int> tmpPotMoney(m_Players.size());
int winnerPotMoney = winner->getMoneyInPot();
for (int i = 0; i < m_Players.size(); i++) {
tmpPotMoney[i] = m_Players[i]->getMoneyInPot();
}
//Updates remaining money in the pot
for (int i = 0; i < m_Players.size(); i++) {
m_Players[i]->setMoneyInPot(max(tmpPotMoney[i] - winnerPotMoney, 0));
}
}
finalizeRound();
return true;
}
void Poker::finalizeRound() {
for (int i = 0; i < m_Players.size(); i++) {
m_Players[i]->setMoneyInPot(0);
}
bettingCycle++;
m_PotMoney = 0;
bannerHeader = "";
updateGameInfo();
int input;
while (1) {
input = GAME_DISPLAY.captureInput();
if (input == 'c' || input == 'C') {
break;
}
}
Hand *hand;
for (int i = 0; i < m_Players.size(); i++) {
m_Players[i]->setFolded(false);
removePlayer(m_Players[i]->getDisplayPosition());
hand = m_Players[i]->getHand();
for (int j = 0; j < 5; j++) {
m_Deck.discardCard(hand->getCard(j));
}
//delete hands
}
}
void Poker::endGame(string endReason) {
int input;
stringstream bannerText;
bannerText << endReason << "; e:exit";
setBottomBannerText(bannerText.str());
while (1) {
input = GAME_DISPLAY.captureInput();
if (input == 'e' || input == 'E') {
return;
}
}
}
#pragma mark - Misc. Controls
int Poker::ante() {
int num_players = m_Players.size();
switch (num_players) {
case 4:
return (int) (0.015 * (double)m_InitialMoney * (double)m_InitialPlayers);
break;
case 3:
return (int) (0.025 * (double)m_InitialMoney * (double)m_InitialPlayers);
break;
case 2:
return (int) (0.15 * (double)m_InitialMoney * (double)m_InitialPlayers);
break;
default:
return 0;
break;
}
}
int Poker::minimumBet(Player *player) {
return ( maxSinglePlayerMoney() - player->getMoneyInPot() );
}
int Poker::maxSinglePlayerMoney() {
return max( m_HumanPlayer.getMoneyInPot(), max( m_AiPlayer_1.getMoneyInPot(), max( m_AiPlayer_2.getMoneyInPot(), m_AiPlayer_3.getMoneyInPot() ) ) );
}
bool Poker::allPlayersAllIn() {
bool allIn = true;
for (int i = 0; i < m_Players.size(); i++) {
allIn = allIn && m_Players[i]->folded() || ( m_Players[i]->getMoney() == 0 );
}
return allIn;
}
#pragma mark - MAIN
void Poker::runGame(GameObject &game) {
game.timer.checkIn();
m_HumanPlayer.setMoney(game.cash);
while (m_Players.size() > 1) {
//enter ante loop
runAnte();
if (roundIsOver()) continue;
//enter deal loop
runDeal();
game.cardsPlayed += 5;
//enter first betting loop
runBetting(1);
if (roundIsOver()) continue;
//enter card exchnage loop
game.cardsPlayed += runCardExchange();
//enter second betting loop
runBetting(2);
if (roundIsOver()) continue;
//enter showdown loop
runShowdown();
finishRound();
}
poker.endGame("You Win!!");
game.cash = m_HumanPlayer.getMoney();
game.timer.checkOut();
}
<|endoftext|>
|
<commit_before>//script showing how to use the GL viewer API to animate a picture
//Author: Richard maunder
#include "TGLViewer.h"
#include "TGLPerspectiveCamera.h"
#include "TTimer.h"
#include "TRandom.h"
#include "TVirtualPad.h"
TGLViewer::ECameraType camera;
TTimer timer(25);
TRandom randGen(0);
Int_t moveCount = 0;
void AnimateCamera()
{
// initialization
static Double_t fov = 30;
static Double_t zoom = 0.78;
static Double_t dolly = 1500.0;
static Double_t center[3] = {-164.0, -164.0, -180.0};
static Double_t hRotate = 0.0;
static Double_t vRotate = 0.0;
// steps
static Double_t fovStep = randGen.Rndm()*3.0 - 0.5;
static Double_t zoomStep = (20 - randGen.Rndm())/1000.;
static Double_t dollyStep = randGen.Rndm()*5.0 - 1.0;
static Double_t centerStep[3] = {randGen.Rndm()*4, randGen.Rndm()*4, randGen.Rndm()*4 };
static Double_t hRotateStep = randGen.Rndm()*0.025;
static Double_t vRotateStep = randGen.Rndm()*0.05;
// move center
center[0] += centerStep[0];
center[1] += centerStep[1];
center[2] += centerStep[2];
Double_t mag = TMath::Sqrt(center[0]*center[0] + center[1]*center[1] + center[2]*center[2]);
if(mag > 500)
{
centerStep[0] = -centerStep[0];
centerStep[1] = -centerStep[1];
centerStep[2] = -centerStep[2];
}
// rotate
hRotate += hRotateStep;
vRotate += vRotateStep;
if (vRotate >= TMath::TwoPi() || vRotate <= 0.0)
vRotateStep = -vRotateStep;
if (hRotate >= (TMath::PiOver2()- 0.02f)|| hRotate <= (0.07f -TMath::PiOver2()))
hRotateStep = -hRotateStep;
// dolly
dolly += dollyStep;
if (dolly >= 2000.0 || dolly <= 1500.0)
dollyStep = -dollyStep;
// modify frustum
TGLViewer * v = (TGLViewer *)gPad->GetViewer3D();
if(camera < 3)
{
fov += fovStep;
if (fov > 130.0 || fov < 5.0)
fovStep = - fovStep; }
else
{
zoom += zoomStep;
if (zoom > 4.0 || zoom < 0.25)
zoomStep = - zoomStep;
}
// apply
if(camera < 3)
v->SetPerspectiveCamera(camera, fov, dollyStep, center, hRotateStep, vRotateStep);
else
v->SetOrthoCamera(camera, zoom, dollyStep, center, hRotateStep, vRotateStep);
if (++moveCount % 10 == 0)
v->RefreshPadEditor(v);
}
void glViewerExercise()
{
gROOT->ProcessLine(".x nucleus.C");
TGLViewer * v = (TGLViewer *)gPad->GetViewer3D();
// Random draw style
Int_t style = randGen.Integer(3);
switch (style)
{
case 0: v->SetStyle(TGLRnrCtx::kFill); break;
case 1: v->SetStyle(TGLRnrCtx::kOutline); break;
case 2: v->SetStyle(TGLRnrCtx::kWireFrame); break;
}
// Lights - turn some off randomly
TGLLightSet* ls = v->GetLightSet();
if (randGen.Integer(2) == 0)
ls->SetLight(TGLLightSet::kLightLeft, kFALSE);
if (randGen.Integer(2) == 0)
ls->SetLight(TGLLightSet::kLightRight, kFALSE);
if (randGen.Integer(2) == 0)
ls->SetLight(TGLLightSet::kLightTop, kFALSE);
if (randGen.Integer(2) == 0)
ls->SetLight(TGLLightSet::kLightBottom, kFALSE);
// Random camera type
Int_t id = randGen.Integer(6);
camera = (TGLViewer::ECameraType)id;
v->SetCurrentCamera(camera);
v->CurrentCamera().SetExternalCenter(kTRUE);
if (id > 2) {
TGLOrthoCamera& o = v->CurrentCamera();
o.SetEnableRotate(kTRUE);
}
// Now animate the camera
timer.SetCommand("AnimateCamera()");
timer.TurnOn();
}
<commit_msg>Connect TTimer::TurnOff() to TGLSAFrame::CloseWindow(). Without this the next timer call resulted in SEGV as it was operating on a deleted window.<commit_after>//script showing how to use the GL viewer API to animate a picture
//Author: Richard maunder
#include "TGLViewer.h"
#include "TGLPerspectiveCamera.h"
#include "TTimer.h"
#include "TRandom.h"
#include "TVirtualPad.h"
TGLViewer::ECameraType camera;
TTimer timer(25);
TRandom randGen(0);
Int_t moveCount = 0;
void AnimateCamera()
{
// initialization
static Double_t fov = 30;
static Double_t zoom = 0.78;
static Double_t dolly = 1500.0;
static Double_t center[3] = {-164.0, -164.0, -180.0};
static Double_t hRotate = 0.0;
static Double_t vRotate = 0.0;
// steps
static Double_t fovStep = randGen.Rndm()*3.0 - 0.5;
static Double_t zoomStep = (20 - randGen.Rndm())/1000.;
static Double_t dollyStep = randGen.Rndm()*5.0 - 1.0;
static Double_t centerStep[3] = {randGen.Rndm()*4, randGen.Rndm()*4, randGen.Rndm()*4 };
static Double_t hRotateStep = randGen.Rndm()*0.025;
static Double_t vRotateStep = randGen.Rndm()*0.05;
// move center
center[0] += centerStep[0];
center[1] += centerStep[1];
center[2] += centerStep[2];
Double_t mag = TMath::Sqrt(center[0]*center[0] + center[1]*center[1] + center[2]*center[2]);
if(mag > 500)
{
centerStep[0] = -centerStep[0];
centerStep[1] = -centerStep[1];
centerStep[2] = -centerStep[2];
}
// rotate
hRotate += hRotateStep;
vRotate += vRotateStep;
if (vRotate >= TMath::TwoPi() || vRotate <= 0.0)
vRotateStep = -vRotateStep;
if (hRotate >= (TMath::PiOver2()- 0.02f)|| hRotate <= (0.07f -TMath::PiOver2()))
hRotateStep = -hRotateStep;
// dolly
dolly += dollyStep;
if (dolly >= 2000.0 || dolly <= 1500.0)
dollyStep = -dollyStep;
// modify frustum
TGLViewer * v = (TGLViewer *)gPad->GetViewer3D();
if(camera < 3)
{
fov += fovStep;
if (fov > 130.0 || fov < 5.0)
fovStep = - fovStep; }
else
{
zoom += zoomStep;
if (zoom > 4.0 || zoom < 0.25)
zoomStep = - zoomStep;
}
// apply
if(camera < 3)
v->SetPerspectiveCamera(camera, fov, dollyStep, center, hRotateStep, vRotateStep);
else
v->SetOrthoCamera(camera, zoom, dollyStep, center, hRotateStep, vRotateStep);
if (++moveCount % 10 == 0)
v->RefreshPadEditor(v);
}
void glViewerExercise()
{
gROOT->ProcessLine(".x nucleus.C");
TGLViewer * v = (TGLViewer *)gPad->GetViewer3D();
// Random draw style
Int_t style = randGen.Integer(3);
switch (style)
{
case 0: v->SetStyle(TGLRnrCtx::kFill); break;
case 1: v->SetStyle(TGLRnrCtx::kOutline); break;
case 2: v->SetStyle(TGLRnrCtx::kWireFrame); break;
}
// Lights - turn some off randomly
TGLLightSet* ls = v->GetLightSet();
if (randGen.Integer(2) == 0)
ls->SetLight(TGLLightSet::kLightLeft, kFALSE);
if (randGen.Integer(2) == 0)
ls->SetLight(TGLLightSet::kLightRight, kFALSE);
if (randGen.Integer(2) == 0)
ls->SetLight(TGLLightSet::kLightTop, kFALSE);
if (randGen.Integer(2) == 0)
ls->SetLight(TGLLightSet::kLightBottom, kFALSE);
// Random camera type
Int_t id = randGen.Integer(6);
camera = (TGLViewer::ECameraType)id;
v->SetCurrentCamera(camera);
v->CurrentCamera().SetExternalCenter(kTRUE);
if (id > 2) {
TGLOrthoCamera& o = v->CurrentCamera();
o.SetEnableRotate(kTRUE);
}
// Now animate the camera
TGLSAViewer* sav = dynamic_cast<TGLSAViewer*>(v);
if (sav)
sav->GetFrame()->Connect("CloseWindow()", "TTimer", &timer, "TurnOff()");
timer.SetCommand("AnimateCamera()");
timer.TurnOn();
}
<|endoftext|>
|
<commit_before>/*
* @Author: Ubi de Feo | Future Tailors
* @Date: 2017-07-09 16:34:07
* @Last Modified by: ubi
* @Last Modified time: 2017-07-09 16:41:17
*/
#include "FTDebouncer.h"
/* CONSTRUCTORS/DESTRUCTOR */
FTDebouncer::FTDebouncer() : debounceDelay(40) {
debouncedItemsCount = 0;
firstDebounceItem = lastDebounceItem = nullptr;
}
FTDebouncer::FTDebouncer(uint16_t _debounceTime) : debounceDelay(_debounceTime) {
debouncedItemsCount = 0;
firstDebounceItem = lastDebounceItem = nullptr;
}
FTDebouncer::~FTDebouncer() {
}
/* METHODS */
void FTDebouncer::addPin(uint8_t _pinNr, uint8_t _restState) {
this->addPin(_pinNr, _restState, PinMode::Input);
}
void FTDebouncer::addPin(uint8_t _pinNr, uint8_t _restState, PinMode _pullUpMode) {
DebounceItem *dbItem = new DebounceItem();
dbItem->pinNumber = _pinNr;
dbItem->restState = _restState;
if (firstDebounceItem == nullptr) {
firstDebounceItem = dbItem;
} else {
lastDebounceItem->nextItem = dbItem;
}
lastDebounceItem = dbItem;
pinMode(_pinNr, static_cast<uint8_t>(_pullUpMode));
debouncedItemsCount++;
}
void FTDebouncer::init() {
unsigned long currentMs = millis();
DebounceItem *dbItem = firstDebounceItem;
while (dbItem != nullptr) {
dbItem->lastTimeChecked = currentMs;
dbItem->currentState = dbItem->previousState = dbItem->restState;
dbItem->currentDebouncedState = dbItem->previousDebouncedState = dbItem->restState;
dbItem = dbItem->nextItem;
}
}
void FTDebouncer::run() {
DebounceItem *dbItem = firstDebounceItem;
while (dbItem != nullptr) {
dbItem->currentState = digitalRead(dbItem->pinNumber);
dbItem = dbItem->nextItem;
}
debouncePins();
checkStateChange();
}
void FTDebouncer::debouncePins() {
unsigned long currentMs = millis();
DebounceItem *dbItem = firstDebounceItem;
while (dbItem != nullptr) {
if (dbItem->currentState != dbItem->previousState) {
dbItem->lastTimeChecked = currentMs;
}
if (currentMs - dbItem->lastTimeChecked > debounceDelay) {
if (dbItem->previousState == dbItem->currentState) {
dbItem->lastTimeChecked = currentMs;
dbItem->currentDebouncedState = dbItem->currentState;
}
}
dbItem->previousState = dbItem->currentState;
dbItem = dbItem->nextItem;
}
}
void FTDebouncer::checkStateChange() {
DebounceItem *dbItem = firstDebounceItem;
while (dbItem != nullptr) {
if (dbItem->previousDebouncedState != dbItem->currentDebouncedState) {
if (dbItem->currentDebouncedState == !dbItem->restState) {
pinActivated(dbItem->pinNumber);
}
if (dbItem->currentDebouncedState == dbItem->restState) {
pinDeactivated(dbItem->pinNumber);
}
}
dbItem->previousDebouncedState = dbItem->currentDebouncedState;
dbItem = dbItem->nextItem;
}
}
uint8_t FTDebouncer::getPinCount(){
return debouncedItemsCount;
}<commit_msg>Use consistend readable variable names<commit_after>/*
* @Author: Ubi de Feo | Future Tailors
* @Date: 2017-07-09 16:34:07
* @Last Modified by: ubi
* @Last Modified time: 2017-07-09 16:41:17
*/
#include "FTDebouncer.h"
/* CONSTRUCTORS/DESTRUCTOR */
FTDebouncer::FTDebouncer() : debounceDelay(40) {
debouncedItemsCount = 0;
firstDebounceItem = lastDebounceItem = nullptr;
}
FTDebouncer::FTDebouncer(uint16_t _debounceDelay) : debounceDelay(_debounceDelay) {
debouncedItemsCount = 0;
firstDebounceItem = lastDebounceItem = nullptr;
}
FTDebouncer::~FTDebouncer() {
}
/* METHODS */
void FTDebouncer::addPin(uint8_t _pinNr, uint8_t _restState) {
this->addPin(_pinNr, _restState, PinMode::Input);
}
void FTDebouncer::addPin(uint8_t _pinNr, uint8_t _restState, PinMode _pullUpMode) {
DebounceItem *debounceItem = new DebounceItem();
debounceItem->pinNumber = _pinNr;
debounceItem->restState = _restState;
if (firstDebounceItem == nullptr) {
firstDebounceItem = debounceItem;
} else {
lastDebounceItem->nextItem = debounceItem;
}
lastDebounceItem = debounceItem;
pinMode(_pinNr, static_cast<uint8_t>(_pullUpMode));
debouncedItemsCount++;
}
void FTDebouncer::init() {
unsigned long currentMilliseconds = millis();
DebounceItem *debounceItem = firstDebounceItem;
while (debounceItem != nullptr) {
debounceItem->lastTimeChecked = currentMilliseconds;
debounceItem->currentState = debounceItem->previousState = debounceItem->restState;
debounceItem->currentDebouncedState = debounceItem->previousDebouncedState = debounceItem->restState;
debounceItem = debounceItem->nextItem;
}
}
void FTDebouncer::run() {
DebounceItem *debounceItem = firstDebounceItem;
while (debounceItem != nullptr) {
debounceItem->currentState = digitalRead(debounceItem->pinNumber);
debounceItem = debounceItem->nextItem;
}
debouncePins();
checkStateChange();
}
void FTDebouncer::debouncePins() {
unsigned long currentMilliseconds = millis();
DebounceItem *debounceItem = firstDebounceItem;
while (debounceItem != nullptr) {
if (debounceItem->currentState != debounceItem->previousState) {
debounceItem->lastTimeChecked = currentMilliseconds;
}
if (currentMilliseconds - debounceItem->lastTimeChecked > debounceDelay) {
if (debounceItem->previousState == debounceItem->currentState) {
debounceItem->lastTimeChecked = currentMilliseconds;
debounceItem->currentDebouncedState = debounceItem->currentState;
}
}
debounceItem->previousState = debounceItem->currentState;
debounceItem = debounceItem->nextItem;
}
}
void FTDebouncer::checkStateChange() {
DebounceItem *debounceItem = firstDebounceItem;
while (debounceItem != nullptr) {
if (debounceItem->previousDebouncedState != debounceItem->currentDebouncedState) {
if (debounceItem->currentDebouncedState == !debounceItem->restState) {
pinActivated(debounceItem->pinNumber);
}
if (debounceItem->currentDebouncedState == debounceItem->restState) {
pinDeactivated(debounceItem->pinNumber);
}
}
debounceItem->previousDebouncedState = debounceItem->currentDebouncedState;
debounceItem = debounceItem->nextItem;
}
}
uint8_t FTDebouncer::getPinCount(){
return debouncedItemsCount;
}<|endoftext|>
|
<commit_before>/*
* Copyright 2022 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "ClientAccounting.hxx"
#include "event/Loop.hxx"
#include "net/SocketAddress.hxx"
#include "net/IPv4Address.hxx"
#include "net/IPv6Address.hxx"
#include "util/DeleteDisposer.hxx"
AccountedClientConnection::~AccountedClientConnection() noexcept
{
if (per_client != nullptr)
per_client->RemoveConnection(*this);
}
void
AccountedClientConnection::EnableTarpit() noexcept
{
if (per_client != nullptr)
per_client->EnableTarpit();
}
bool
AccountedClientConnection::CheckTarpit() const noexcept
{
return per_client != nullptr && per_client->CheckTarpit();
}
static constexpr uint_least64_t
Read64(const uint8_t *src) noexcept
{
uint_least64_t value{};
for (unsigned i = 0; i < 8; ++i)
value = (value << 8) | src[i];
return value;
}
static constexpr uint_least64_t
ToInteger(const struct in6_addr &addr) noexcept
{
return Read64(addr.s6_addr) ^ Read64(addr.s6_addr + 8);
}
static uint_least64_t
ToInteger(SocketAddress address) noexcept
{
if (address.IsNull())
return 0;
switch (address.GetFamily()) {
case AF_INET:
return IPv4Address::Cast(address).GetNumericAddressBE();
case AF_INET6:
return ToInteger(IPv6Address::Cast(address).GetAddress());
default:
return 0;
}
}
PerClientAccounting::PerClientAccounting(ClientAccountingMap &_map,
uint_least64_t _address) noexcept
:map(_map), address(_address)
{
}
inline Event::TimePoint
PerClientAccounting::Now() const noexcept
{
return map.GetEventLoop().SteadyNow();
}
bool
PerClientAccounting::Check() const noexcept
{
const std::size_t max_connections = map.GetMaxConnections();
return max_connections == 0 || connections.size() < max_connections;
}
void
PerClientAccounting::AddConnection(AccountedClientConnection &c) noexcept
{
assert(c.per_client == nullptr);
connections.push_back(c);
c.per_client = this;
}
void
PerClientAccounting::RemoveConnection(AccountedClientConnection &c) noexcept
{
assert(c.per_client == this);
connections.erase(connections.iterator_to(c));
c.per_client = nullptr;
expires = Now() + std::chrono::minutes{5};
if (connections.empty())
map.ScheduleCleanup();
}
inline void
PerClientAccounting::EnableTarpit() noexcept
{
tarpit_until = Now() + std::chrono::minutes{1};
}
inline bool
PerClientAccounting::CheckTarpit() const noexcept
{
return Now() < tarpit_until;
}
PerClientAccounting *
ClientAccountingMap::Get(SocketAddress _address) noexcept
{
const uint_least64_t address = ToInteger(_address);
if (address == 0)
return nullptr;
Map::insert_commit_data hint;
auto [i, inserted] =
map.insert_check(address, map.hash_function(), map.key_eq(),
hint);
if (inserted) {
auto *per_client = new PerClientAccounting(*this, address);
i = map.insert_commit(*per_client, hint);
}
return &*i;
}
void
ClientAccountingMap::ScheduleCleanup() noexcept
{
if (!cleanup_timer.IsPending())
cleanup_timer.Schedule(std::chrono::minutes{1});
}
template<typename Container, typename Pred, typename Disposer>
static void
EraseAndDisposeIf(Container &container, Pred pred, Disposer disposer)
{
for (auto i = container.begin(), end = container.end(); i != end;) {
const auto next = std::next(i);
if (pred(*i))
container.erase_and_dispose(i, disposer);
i = next;
}
}
void
ClientAccountingMap::OnCleanupTimer() noexcept
{
bool reschedule = false;
const auto now = GetEventLoop().SteadyNow();
EraseAndDisposeIf(map, [&reschedule, now](const auto &i){
if (!i.connections.empty())
return false;
if (now < i.expires) {
reschedule = true;
return false;
}
return true;
}, DeleteDisposer{});
if (reschedule)
ScheduleCleanup();
}
<commit_msg>net/ClientAccounting: unmap IPv6 to IPv4<commit_after>/*
* Copyright 2022 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "ClientAccounting.hxx"
#include "event/Loop.hxx"
#include "net/SocketAddress.hxx"
#include "net/IPv4Address.hxx"
#include "net/IPv6Address.hxx"
#include "util/DeleteDisposer.hxx"
AccountedClientConnection::~AccountedClientConnection() noexcept
{
if (per_client != nullptr)
per_client->RemoveConnection(*this);
}
void
AccountedClientConnection::EnableTarpit() noexcept
{
if (per_client != nullptr)
per_client->EnableTarpit();
}
bool
AccountedClientConnection::CheckTarpit() const noexcept
{
return per_client != nullptr && per_client->CheckTarpit();
}
static constexpr uint_least64_t
Read64(const uint8_t *src) noexcept
{
uint_least64_t value{};
for (unsigned i = 0; i < 8; ++i)
value = (value << 8) | src[i];
return value;
}
static constexpr uint_least64_t
ToInteger(const struct in6_addr &addr) noexcept
{
return Read64(addr.s6_addr) ^ Read64(addr.s6_addr + 8);
}
static uint_least64_t
ToInteger(SocketAddress address) noexcept
{
if (address.IsNull())
return 0;
switch (address.GetFamily()) {
case AF_INET:
return IPv4Address::Cast(address).GetNumericAddressBE();
case AF_INET6:
if (const auto &v6 = IPv6Address::Cast(address); v6.IsV4Mapped())
return v6.UnmapV4().GetNumericAddressBE();
return ToInteger(IPv6Address::Cast(address).GetAddress());
default:
return 0;
}
}
PerClientAccounting::PerClientAccounting(ClientAccountingMap &_map,
uint_least64_t _address) noexcept
:map(_map), address(_address)
{
}
inline Event::TimePoint
PerClientAccounting::Now() const noexcept
{
return map.GetEventLoop().SteadyNow();
}
bool
PerClientAccounting::Check() const noexcept
{
const std::size_t max_connections = map.GetMaxConnections();
return max_connections == 0 || connections.size() < max_connections;
}
void
PerClientAccounting::AddConnection(AccountedClientConnection &c) noexcept
{
assert(c.per_client == nullptr);
connections.push_back(c);
c.per_client = this;
}
void
PerClientAccounting::RemoveConnection(AccountedClientConnection &c) noexcept
{
assert(c.per_client == this);
connections.erase(connections.iterator_to(c));
c.per_client = nullptr;
expires = Now() + std::chrono::minutes{5};
if (connections.empty())
map.ScheduleCleanup();
}
inline void
PerClientAccounting::EnableTarpit() noexcept
{
tarpit_until = Now() + std::chrono::minutes{1};
}
inline bool
PerClientAccounting::CheckTarpit() const noexcept
{
return Now() < tarpit_until;
}
PerClientAccounting *
ClientAccountingMap::Get(SocketAddress _address) noexcept
{
const uint_least64_t address = ToInteger(_address);
if (address == 0)
return nullptr;
Map::insert_commit_data hint;
auto [i, inserted] =
map.insert_check(address, map.hash_function(), map.key_eq(),
hint);
if (inserted) {
auto *per_client = new PerClientAccounting(*this, address);
i = map.insert_commit(*per_client, hint);
}
return &*i;
}
void
ClientAccountingMap::ScheduleCleanup() noexcept
{
if (!cleanup_timer.IsPending())
cleanup_timer.Schedule(std::chrono::minutes{1});
}
template<typename Container, typename Pred, typename Disposer>
static void
EraseAndDisposeIf(Container &container, Pred pred, Disposer disposer)
{
for (auto i = container.begin(), end = container.end(); i != end;) {
const auto next = std::next(i);
if (pred(*i))
container.erase_and_dispose(i, disposer);
i = next;
}
}
void
ClientAccountingMap::OnCleanupTimer() noexcept
{
bool reschedule = false;
const auto now = GetEventLoop().SteadyNow();
EraseAndDisposeIf(map, [&reschedule, now](const auto &i){
if (!i.connections.empty())
return false;
if (now < i.expires) {
reschedule = true;
return false;
}
return true;
}, DeleteDisposer{});
if (reschedule)
ScheduleCleanup();
}
<|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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* ola-client.cpp
* The multi purpose ola client.
* Copyright (C) 2005-2008 Simon Newton
*/
#include <errno.h>
#include <getopt.h>
#include <stdlib.h>
#include <ola/DmxBuffer.h>
#include <ola/Logging.h>
#include <ola/StreamingClient.h>
#include <ola/StringUtils.h>
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
using ola::StreamingClient;
typedef struct {
string dmx_data;
unsigned int universe;
bool help;
} options;
/*
* parse our cmd line options
*/
void ParseOptions(int argc, char *argv[], options *opts) {
static struct option long_options[] = {
{"dmx", required_argument, 0, 'd'},
{"help", no_argument, 0, 'h'},
{"universe", required_argument, 0, 'u'},
{0, 0, 0, 0}
};
opts->dmx_data = "";
opts->universe = 1;
opts->help = false;
int c;
int option_index = 0;
while (1) {
c = getopt_long(argc, argv, "d:hu:", long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 0:
break;
case 'd':
opts->dmx_data = optarg;
break;
case 'h':
opts->help = true;
break;
case 'u':
opts->universe = atoi(optarg);
break;
case '?':
break;
default:
break;
}
}
}
/*
* Display the help message
*/
void DisplayHelpAndExit(char arg[], const options &opts) {
cout << "Usage: " << arg <<
" --dmx <dmx_data> --universe <universe_id>\n"
"\n"
"Send DMX512 data to OLA. If dmx data isn't provided we read from stdin.\n"
"\n"
" -d, --dmx <dmx_data> DMX512 data, e.g. '1,240,0,255'\n"
" -h, --help Display this help message and exit.\n"
" -u, --universe <universe_id> Id of universe to send data for.\n"
<< endl;
exit(1);
}
bool SendDataFromString(const StreamingClient &client,
unsigned int universe,
const string &data) {
ola::DmxBuffer buffer;
bool status = buffer.SetFromString(data);
if (!status || buffer.Size() == 0)
return false;
if (!client.SendDmx(universe, buffer)) {
cout << "Send DMX failed" << endl;
return false;
}
return true;
}
/*
* Main
*/
int main(int argc, char *argv[]) {
ola::InitLogging(ola::OLA_LOG_WARN, ola::OLA_LOG_STDERR);
StreamingClient ola_client;
options opts;
ParseOptions(argc, argv, &opts);
if (opts.help || opts.universe < 0)
DisplayHelpAndExit(argv[0], opts);
if (!ola_client.Setup()) {
OLA_FATAL << "Setup failed";
exit(1);
}
if (opts.dmx_data.empty()) {
string input;
while (std::cin >> input) {
ola::StringTrim(&input);
SendDataFromString(ola_client, opts.universe, input);
}
} else {
SendDataFromString(ola_client, opts.universe, opts.dmx_data);
}
return 0;
}
<commit_msg> * add the on error handler<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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* ola-client.cpp
* The multi purpose ola client.
* Copyright (C) 2005-2008 Simon Newton
*/
#include <errno.h>
#include <getopt.h>
#include <stdlib.h>
#include <ola/Closure.h>
#include <ola/DmxBuffer.h>
#include <ola/Logging.h>
#include <ola/StreamingClient.h>
#include <ola/StringUtils.h>
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
using ola::StreamingClient;
typedef struct {
string dmx_data;
unsigned int universe;
bool help;
} options;
bool terminate = false;
int SocketClosed() {
terminate = true;
return 0;
}
/*
* parse our cmd line options
*/
void ParseOptions(int argc, char *argv[], options *opts) {
static struct option long_options[] = {
{"dmx", required_argument, 0, 'd'},
{"help", no_argument, 0, 'h'},
{"universe", required_argument, 0, 'u'},
{0, 0, 0, 0}
};
opts->dmx_data = "";
opts->universe = 1;
opts->help = false;
int c;
int option_index = 0;
while (1) {
c = getopt_long(argc, argv, "d:hu:", long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 0:
break;
case 'd':
opts->dmx_data = optarg;
break;
case 'h':
opts->help = true;
break;
case 'u':
opts->universe = atoi(optarg);
break;
case '?':
break;
default:
break;
}
}
}
/*
* Display the help message
*/
void DisplayHelpAndExit(char arg[], const options &opts) {
cout << "Usage: " << arg <<
" --dmx <dmx_data> --universe <universe_id>\n"
"\n"
"Send DMX512 data to OLA. If dmx data isn't provided we read from stdin.\n"
"\n"
" -d, --dmx <dmx_data> DMX512 data, e.g. '1,240,0,255'\n"
" -h, --help Display this help message and exit.\n"
" -u, --universe <universe_id> Id of universe to send data for.\n"
<< endl;
exit(1);
}
bool SendDataFromString(const StreamingClient &client,
unsigned int universe,
const string &data) {
ola::DmxBuffer buffer;
bool status = buffer.SetFromString(data);
if (!status || buffer.Size() == 0)
return false;
if (!client.SendDmx(universe, buffer)) {
cout << "Send DMX failed" << endl;
return false;
}
return true;
}
/*
* Main
*/
int main(int argc, char *argv[]) {
ola::InitLogging(ola::OLA_LOG_WARN, ola::OLA_LOG_STDERR);
StreamingClient ola_client;
ola_client.SetErrorClosure(ola::NewSingleClosure(&SocketClosed));
options opts;
ParseOptions(argc, argv, &opts);
if (opts.help || opts.universe < 0)
DisplayHelpAndExit(argv[0], opts);
if (!ola_client.Setup()) {
OLA_FATAL << "Setup failed";
exit(1);
}
if (opts.dmx_data.empty()) {
string input;
while (!terminate && std::cin >> input) {
ola::StringTrim(&input);
SendDataFromString(ola_client, opts.universe, input);
}
} else {
SendDataFromString(ola_client, opts.universe, opts.dmx_data);
}
ola_client.Stop();
return 0;
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <cstdlib>
#include <csignal>
#include <iterator>
#include <iostream>
#include <sstream>
#include <string>
#include <sys/wait.h>
#include <list>
#include "shelly.hpp"
#include "commands.hpp"
Shelly::Shelly() : exit(false)
{ }
int Shelly::start()
{
while( ! exit)
{
// Display the user prompt
std::cout << prompt();
// Read the use input into the command string
std::string input_command;
std::getline(std::cin, input_command);
// Exit on EOF
if (std::cin.eof())
{
std::cout << (input_command = "exit") << '\n';
}
// List out any jobs that have completed
for (auto job : jobs_list(true))
{
std::cout << "[" << job.pid << "] Done " << job.cmd.command
<< '\n';
}
// Ignore empty inputs
if (input_command.empty()) continue;
// Execute the command
execute(input_command);
}
return 0;
}
void Shelly::finish()
{
termiate_jobs();
exit = true;
}
std::string Shelly::prompt()
{
char hostname[1024];
char *username = getenv("USER");
gethostname(hostname, sizeof hostname);
return std::string("\e[0;35m") + hostname + "(" + username + ")%\e[0m ";
}
Shelly::command Shelly::parse_command(std::string input_command)
{
// Setup the command struct
command command;
// This command is a background job if the last character is a '&'
command.background = input_command.back() == '&';
// Remove the background flag from the command string
if (command.background)
{
input_command.erase(input_command.size() - 1);
}
// Tokenize the input command into a vector of strings
std::istringstream iss(input_command);
std::vector<std::string> argv;
copy(std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>(),
std::back_inserter<std::vector<std::string> >(argv));
// We also want the arguments as a vector of C style strings
std::vector<const char *> argv_c;
for (int i = 0; i < argv.size(); ++i)
{
argv_c.push_back(argv[i].c_str());
}
command.command = input_command;
command.name = argv[0];
command.argc = argv.size();
command.argv = argv;
command.argv_c = argv_c;
return command;
}
int Shelly::execute(std::string input_command)
{
return execute(parse_command(input_command));
}
int Shelly::execute(Shelly::command command)
{
// Check if the command is a built in function of the shell
int(*internal_command)(Shelly *, Shelly::command *);
if ((internal_command = commands::internal[command.name]) != 0)
{
return internal_command(this, &command);
}
int pid = fork();
if (pid == 0)
{
// execvp always expects the last argument to be a null terminator
command.argv_c.push_back(0);
// Because the argv_c vector stores the C-strings in order we can
// simply de-refrence the first element of the argv_c vector
execvp(command.argv_c[0], (char * const *) &command.argv_c[0]);
// exec failed, the command was _probably_ not found
std::cerr << command.name << ": command not found\n";
finish();
}
else
{
if (command.background)
{
if (background_jobs.size() < Shelly::MAX_BG_JOBS)
{
background_jobs.push_back({command, pid});
std::cout << "[" << pid << "] " << command.command << '\n';
return 0;
}
// Let the user know only so many commands may be run in the bg
std::cerr << "No more than " << Shelly::MAX_BG_JOBS
<< " background jobs may be run at once.\n"
<< "Executing " << command.name << " in the foreground\n";
}
wait(0);
}
}
void Shelly::termiate_jobs()
{
for (auto job : background_jobs)
{
kill(job.pid, SIGTERM);
wait(0);
}
background_jobs.clear();
}
std::list<Shelly::job> Shelly::jobs_list(bool completed)
{
if ( ! completed)
{
return background_jobs;
}
std::list<Shelly::job> completed_jobs;
std::list<Shelly::job>::iterator it;
// Get completed jobs and splice them into the completed_jobs list
for (it = background_jobs.begin(); it != background_jobs.end(); ++it)
{
// Check if the process is not done yet
if (waitpid(it->pid, 0, WNOHANG) == 0) continue;
completed_jobs.splice(completed_jobs.end(), background_jobs, it--);
}
return completed_jobs;
}
/**
* Begin execution
*/
int main(int argc, char* argv[])
{
Shelly Shelly;
return Shelly.start();
}
<commit_msg>Return the status of the executed command<commit_after>#include <algorithm>
#include <cstdlib>
#include <csignal>
#include <iterator>
#include <iostream>
#include <sstream>
#include <string>
#include <sys/wait.h>
#include <list>
#include "shelly.hpp"
#include "commands.hpp"
Shelly::Shelly() : exit(false)
{ }
int Shelly::start()
{
while( ! exit)
{
// Display the user prompt
std::cout << prompt();
// Read the use input into the command string
std::string input_command;
std::getline(std::cin, input_command);
// Exit on EOF
if (std::cin.eof())
{
std::cout << (input_command = "exit") << '\n';
}
// List out any jobs that have completed
for (auto job : jobs_list(true))
{
std::cout << "[" << job.pid << "] Done " << job.cmd.command
<< '\n';
}
// Ignore empty inputs
if (input_command.empty()) continue;
// Execute the command
execute(input_command);
}
return 0;
}
void Shelly::finish()
{
termiate_jobs();
exit = true;
}
std::string Shelly::prompt()
{
char hostname[1024];
char *username = getenv("USER");
gethostname(hostname, sizeof hostname);
return std::string("\e[0;35m") + hostname + "(" + username + ")%\e[0m ";
}
Shelly::command Shelly::parse_command(std::string input_command)
{
// Setup the command struct
command command;
// This command is a background job if the last character is a '&'
command.background = input_command.back() == '&';
// Remove the background flag from the command string
if (command.background)
{
input_command.erase(input_command.size() - 1);
}
// Tokenize the input command into a vector of strings
std::istringstream iss(input_command);
std::vector<std::string> argv;
copy(std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>(),
std::back_inserter<std::vector<std::string> >(argv));
// We also want the arguments as a vector of C style strings
std::vector<const char *> argv_c;
for (int i = 0; i < argv.size(); ++i)
{
argv_c.push_back(argv[i].c_str());
}
command.command = input_command;
command.name = argv[0];
command.argc = argv.size();
command.argv = argv;
command.argv_c = argv_c;
return command;
}
int Shelly::execute(std::string input_command)
{
return execute(parse_command(input_command));
}
int Shelly::execute(Shelly::command command)
{
int status = 0;
// Check if the command is a built in function of the shell
int(*internal_command)(Shelly *, Shelly::command *);
if ((internal_command = commands::internal[command.name]) != 0)
{
return internal_command(this, &command);
}
int pid = fork();
if (pid == 0)
{
// execvp always expects the last argument to be a null terminator
command.argv_c.push_back(0);
// Because the argv_c vector stores the C-strings in order we can
// simply de-refrence the first element of the argv_c vector
execvp(command.argv_c[0], (char * const *) &command.argv_c[0]);
// exec failed, the command was _probably_ not found
std::cerr << command.name << ": command not found\n";
finish();
}
else
{
if (command.background)
{
if (background_jobs.size() < Shelly::MAX_BG_JOBS)
{
background_jobs.push_back({command, pid});
std::cout << "[" << pid << "] " << command.command << '\n';
return status;
}
// Let the user know only so many commands may be run in the bg
std::cerr << "No more than " << Shelly::MAX_BG_JOBS
<< " background jobs may be run at once.\n"
<< "Executing " << command.name << " in the foreground\n";
}
wait(&status);
}
return status;
}
void Shelly::termiate_jobs()
{
for (auto job : background_jobs)
{
kill(job.pid, SIGTERM);
wait(0);
}
background_jobs.clear();
}
std::list<Shelly::job> Shelly::jobs_list(bool completed)
{
if ( ! completed)
{
return background_jobs;
}
std::list<Shelly::job> completed_jobs;
std::list<Shelly::job>::iterator it;
// Get completed jobs and splice them into the completed_jobs list
for (it = background_jobs.begin(); it != background_jobs.end(); ++it)
{
// Check if the process is not done yet
if (waitpid(it->pid, 0, WNOHANG) == 0) continue;
completed_jobs.splice(completed_jobs.end(), background_jobs, it--);
}
return completed_jobs;
}
/**
* Begin execution
*/
int main(int argc, char* argv[])
{
Shelly Shelly;
return Shelly.start();
}
<|endoftext|>
|
<commit_before>/*
* This file is part of the UnTech Editor Suite.
* Copyright (c) 2016 - 2018, Marcus Rowe <undisbeliever@gmail.com>.
* Distributed under The MIT License: https://opensource.org/licenses/MIT
*/
#include "spriteimporter-serializer.h"
#include "animation/serializer.h"
#include "models/common/atomicofstream.h"
#include "models/common/xml/xmlreader.h"
#include "models/common/xml/xmlwriter.h"
#include <cassert>
#include <fstream>
#include <stdexcept>
using namespace UnTech;
using namespace UnTech::Xml;
namespace UnTech {
namespace MetaSprite {
namespace SpriteImporter {
const std::string FrameSet::FILE_EXTENSION = "utsi";
std::unique_ptr<FrameSet> loadFrameSet(const std::string& filename)
{
auto xml = XmlReader::fromFile(filename);
return readFrameSet(*xml);
}
std::unique_ptr<FrameSet> readFrameSet(XmlReader& xml)
{
try {
std::unique_ptr<XmlTag> tag = xml.parseTag();
if (tag == nullptr || tag->name != "spriteimporter") {
throw xml_error(xml, "Expected <spriteimporter> tag");
}
return readFrameSet(xml, tag.get());
}
catch (const std::exception& ex) {
throw xml_error(xml, "Unable to load SpriteImporter FrameSet file", ex);
}
}
void saveFrameSet(const FrameSet& frameSet, const std::string& filename)
{
AtomicOfStream file(filename);
XmlWriter xml(file, filename, "untech");
writeFrameSet(xml, frameSet);
file.commit();
}
/*
* FRAME SET READER
* ================
*/
struct FrameSetReader {
FrameSetReader(FrameSet& frameSet, XmlReader& xml)
: frameSet(frameSet)
, xml(xml)
, frameSetGridSet(false)
{
}
private:
FrameSet& frameSet;
XmlReader& xml;
bool frameSetGridSet;
public:
inline void readFrameSet(const XmlTag* tag)
{
assert(tag->name == "spriteimporter");
assert(frameSet.frames.size() == 0);
frameSet.name = tag->getAttributeId("id");
frameSet.tilesetType = tag->getAttributeEnum<TilesetType>("tilesettype");
if (tag->hasAttribute("exportorder")) {
frameSet.exportOrder = tag->getAttributeId("exportorder");
}
frameSetGridSet = false;
if (tag->hasAttribute("image")) {
frameSet.imageFilename = tag->getAttributeFilename("image");
}
if (tag->hasAttribute("transparent")) {
static_assert(sizeof(unsigned) >= 3, "Unsigned value too small");
unsigned hex = tag->getAttributeUnsignedHex("transparent");
frameSet.transparentColor = UnTech::rgba::fromRgba(hex);
frameSet.transparentColor.alpha = 0xFF;
}
std::unique_ptr<XmlTag> childTag;
while ((childTag = xml.parseTag())) {
if (childTag->name == "grid") {
readFrameSetGrid(childTag.get());
}
else if (childTag->name == "palette") {
readPalette(childTag.get());
}
else if (childTag->name == "frame") {
readFrame(childTag.get());
}
else if (childTag->name == "animation") {
Animation::readAnimation(xml, childTag.get(), frameSet.animations);
}
else {
throw unknown_tag_error(*childTag);
}
xml.parseCloseTag();
}
}
private:
inline void readFrameSetGrid(const XmlTag* tag)
{
assert(tag->name == "grid");
frameSet.grid.frameSize = tag->getAttributeUsize("width", "height");
frameSet.grid.offset = tag->getAttributeUpoint("xoffset", "yoffset");
frameSet.grid.padding = tag->getAttributeUpoint("xpadding", "ypadding");
frameSet.grid.origin = tag->getAttributeUpoint("xorigin", "yorigin");
frameSetGridSet = true;
}
inline void readFrame(const XmlTag* tag)
{
assert(tag->name == "frame");
std::string id = tag->getAttributeUniqueId("id", frameSet.frames);
Frame& frame = frameSet.frames.create(id);
if (tag->hasAttribute("order")) {
frame.spriteOrder = tag->getAttributeUnsigned("order", 0, frame.spriteOrder.MASK);
}
std::unique_ptr<XmlTag> childTag = xml.parseTag();
if (childTag) {
if (childTag->name == "location") {
static const usize minSize(MIN_FRAME_SIZE, MIN_FRAME_SIZE);
frame.location.aabb = childTag->getAttributeUrect(minSize);
frame.location.useGridLocation = false;
}
else if (childTag->name == "gridlocation") {
if (frameSetGridSet == false) {
throw xml_error(*childTag, "Frameset grid is not set.");
}
frame.location.gridLocation = childTag->getAttributeUpoint();
frame.location.useGridLocation = true;
}
else {
throw xml_error(*childTag, "location or gridlocation tag must be the first child of frame");
}
xml.parseCloseTag();
}
else {
throw xml_error(*tag, "location or gridlocation tag must be the first child of frame");
}
frame.location.useGridOrigin = true;
frame.location.update(frameSet.grid, frame);
const urect frameLocation = frame.location.aabb;
frame.solid = false;
while ((childTag = xml.parseTag())) {
if (childTag->name == "object") {
FrameObject obj;
std::string sizeStr = childTag->getAttribute("size");
if (sizeStr == "small") {
obj.size = ObjectSize::SMALL;
}
else if (sizeStr == "large") {
obj.size = ObjectSize::LARGE;
}
else {
throw xml_error(*childTag, "Unknown object size");
}
obj.location = childTag->getAttributeUpointInside(frameLocation, obj.sizePx());
frame.objects.push_back(obj);
}
else if (childTag->name == "actionpoint") {
ActionPoint ap;
ap.location = childTag->getAttributeUpointInside(frameLocation);
ap.parameter = childTag->getAttributeClamped<ActionPointParameter>("parameter");
frame.actionPoints.push_back(ap);
}
else if (childTag->name == "entityhitbox") {
EntityHitbox eh;
eh.aabb = childTag->getAttributeUrectInside(frameLocation);
eh.hitboxType = EntityHitboxType::from_string(childTag->getAttribute("type"));
frame.entityHitboxes.push_back(eh);
}
else if (childTag->name == "tilehitbox") {
if (frame.solid) {
throw xml_error(*childTag, "Can only have one tilehitbox per frame");
}
frame.tileHitbox = childTag->getAttributeUrectInside(frameLocation);
frame.solid = true;
}
else if (childTag->name == "origin") {
if (frame.location.useGridOrigin == false) {
throw xml_error(*childTag, "Can only have one origin per frame");
}
frame.location.useGridOrigin = false;
frame.location.origin = childTag->getAttributeUpointInside(frameLocation);
}
else {
throw unknown_tag_error(*childTag);
}
xml.parseCloseTag();
}
}
inline void readPalette(const XmlTag* tag)
{
assert(tag->name == "palette");
if (frameSet.palette.usesUserSuppliedPalette()) {
throw xml_error(*tag, "Only one palette tag allowed per frameset");
}
frameSet.palette.nPalettes = tag->getAttributeUnsigned("npalettes", 1);
frameSet.palette.colorSize = tag->getAttributeUnsigned("colorsize", 1);
}
};
std::unique_ptr<FrameSet> readFrameSet(XmlReader& xml, const XmlTag* tag)
{
auto frameSet = std::make_unique<FrameSet>();
FrameSetReader reader(*frameSet.get(), xml);
reader.readFrameSet(tag);
return frameSet;
}
/*
* FRAME SET WRITER
* ================
*/
inline void writeFrame(XmlWriter& xml, const std::string& frameName, const Frame& frame)
{
xml.writeTag("frame");
xml.writeTagAttribute("id", frameName);
xml.writeTagAttribute("order", frame.spriteOrder);
if (frame.location.useGridLocation) {
xml.writeTag("gridlocation");
xml.writeTagAttributeUpoint(frame.location.gridLocation);
xml.writeCloseTag();
}
else {
xml.writeTag("location");
xml.writeTagAttributeUrect(frame.location.aabb);
xml.writeCloseTag();
}
if (frame.location.useGridOrigin == false) {
xml.writeTag("origin");
xml.writeTagAttributeUpoint(frame.location.origin);
xml.writeCloseTag();
}
if (frame.solid) {
xml.writeTag("tilehitbox");
xml.writeTagAttributeUrect(frame.tileHitbox);
xml.writeCloseTag();
}
for (const FrameObject& obj : frame.objects) {
xml.writeTag("object");
if (obj.size == ObjectSize::SMALL) {
xml.writeTagAttribute("size", "small");
}
else {
xml.writeTagAttribute("size", "large");
}
xml.writeTagAttributeUpoint(obj.location);
xml.writeCloseTag();
}
for (const ActionPoint& ap : frame.actionPoints) {
xml.writeTag("actionpoint");
xml.writeTagAttribute("parameter", ap.parameter);
xml.writeTagAttributeUpoint(ap.location);
xml.writeCloseTag();
}
for (const EntityHitbox& eh : frame.entityHitboxes) {
xml.writeTag("entityhitbox");
xml.writeTagAttribute("type", eh.hitboxType.to_string());
xml.writeTagAttributeUrect(eh.aabb);
xml.writeCloseTag();
}
xml.writeCloseTag();
}
inline void writeFrameSetGrid(XmlWriter& xml, const FrameSetGrid& grid)
{
xml.writeTag("grid");
xml.writeTagAttributeUsize(grid.frameSize, "width", "height");
xml.writeTagAttributeUpoint(grid.offset, "xoffset", "yoffset");
xml.writeTagAttributeUpoint(grid.padding, "xpadding", "ypadding");
xml.writeTagAttributeUpoint(grid.origin, "xorigin", "yorigin");
xml.writeCloseTag();
}
void writeFrameSet(XmlWriter& xml, const FrameSet& frameSet)
{
xml.writeTag("spriteimporter");
xml.writeTagAttribute("id", frameSet.name);
xml.writeTagAttributeEnum("tilesettype", frameSet.tilesetType);
if (frameSet.exportOrder.isValid()) {
xml.writeTagAttribute("exportorder", frameSet.exportOrder);
}
if (!frameSet.imageFilename.empty()) {
xml.writeTagAttributeFilename("image", frameSet.imageFilename);
}
if (frameSet.transparentColorValid()) {
static_assert(sizeof(unsigned) >= 3, "Unsigned value too small");
unsigned rgb = frameSet.transparentColor.rgb();
xml.writeTagAttributeHex("transparent", rgb, 6);
}
writeFrameSetGrid(xml, frameSet.grid);
if (frameSet.palette.usesUserSuppliedPalette()) {
xml.writeTag("palette");
xml.writeTagAttribute("npalettes", frameSet.palette.nPalettes);
xml.writeTagAttribute("colorsize", frameSet.palette.colorSize);
xml.writeCloseTag();
}
for (const auto& f : frameSet.frames) {
writeFrame(xml, f.first, f.second);
}
Animation::writeAnimations(xml, frameSet.animations);
xml.writeCloseTag();
}
}
}
}
<commit_msg>Remove bounds checks from from SI::FrameSetReader<commit_after>/*
* This file is part of the UnTech Editor Suite.
* Copyright (c) 2016 - 2018, Marcus Rowe <undisbeliever@gmail.com>.
* Distributed under The MIT License: https://opensource.org/licenses/MIT
*/
#include "spriteimporter-serializer.h"
#include "animation/serializer.h"
#include "models/common/atomicofstream.h"
#include "models/common/xml/xmlreader.h"
#include "models/common/xml/xmlwriter.h"
#include <cassert>
#include <fstream>
#include <stdexcept>
using namespace UnTech;
using namespace UnTech::Xml;
namespace UnTech {
namespace MetaSprite {
namespace SpriteImporter {
const std::string FrameSet::FILE_EXTENSION = "utsi";
std::unique_ptr<FrameSet> loadFrameSet(const std::string& filename)
{
auto xml = XmlReader::fromFile(filename);
return readFrameSet(*xml);
}
std::unique_ptr<FrameSet> readFrameSet(XmlReader& xml)
{
try {
std::unique_ptr<XmlTag> tag = xml.parseTag();
if (tag == nullptr || tag->name != "spriteimporter") {
throw xml_error(xml, "Expected <spriteimporter> tag");
}
return readFrameSet(xml, tag.get());
}
catch (const std::exception& ex) {
throw xml_error(xml, "Unable to load SpriteImporter FrameSet file", ex);
}
}
void saveFrameSet(const FrameSet& frameSet, const std::string& filename)
{
AtomicOfStream file(filename);
XmlWriter xml(file, filename, "untech");
writeFrameSet(xml, frameSet);
file.commit();
}
/*
* FRAME SET READER
* ================
*/
struct FrameSetReader {
FrameSetReader(FrameSet& frameSet, XmlReader& xml)
: frameSet(frameSet)
, xml(xml)
, frameSetGridSet(false)
{
}
private:
FrameSet& frameSet;
XmlReader& xml;
bool frameSetGridSet;
public:
inline void readFrameSet(const XmlTag* tag)
{
assert(tag->name == "spriteimporter");
assert(frameSet.frames.size() == 0);
frameSet.name = tag->getAttributeId("id");
frameSet.tilesetType = tag->getAttributeEnum<TilesetType>("tilesettype");
if (tag->hasAttribute("exportorder")) {
frameSet.exportOrder = tag->getAttributeId("exportorder");
}
frameSetGridSet = false;
if (tag->hasAttribute("image")) {
frameSet.imageFilename = tag->getAttributeFilename("image");
}
if (tag->hasAttribute("transparent")) {
static_assert(sizeof(unsigned) >= 3, "Unsigned value too small");
unsigned hex = tag->getAttributeUnsignedHex("transparent");
frameSet.transparentColor = UnTech::rgba::fromRgba(hex);
frameSet.transparentColor.alpha = 0xFF;
}
std::unique_ptr<XmlTag> childTag;
while ((childTag = xml.parseTag())) {
if (childTag->name == "grid") {
readFrameSetGrid(childTag.get());
}
else if (childTag->name == "palette") {
readPalette(childTag.get());
}
else if (childTag->name == "frame") {
readFrame(childTag.get());
}
else if (childTag->name == "animation") {
Animation::readAnimation(xml, childTag.get(), frameSet.animations);
}
else {
throw unknown_tag_error(*childTag);
}
xml.parseCloseTag();
}
}
private:
inline void readFrameSetGrid(const XmlTag* tag)
{
assert(tag->name == "grid");
frameSet.grid.frameSize = tag->getAttributeUsize("width", "height");
frameSet.grid.offset = tag->getAttributeUpoint("xoffset", "yoffset");
frameSet.grid.padding = tag->getAttributeUpoint("xpadding", "ypadding");
frameSet.grid.origin = tag->getAttributeUpoint("xorigin", "yorigin");
frameSetGridSet = true;
}
inline void readFrame(const XmlTag* tag)
{
assert(tag->name == "frame");
std::string id = tag->getAttributeUniqueId("id", frameSet.frames);
Frame& frame = frameSet.frames.create(id);
if (tag->hasAttribute("order")) {
frame.spriteOrder = tag->getAttributeUnsigned("order", 0, frame.spriteOrder.MASK);
}
std::unique_ptr<XmlTag> childTag = xml.parseTag();
if (childTag) {
if (childTag->name == "location") {
frame.location.aabb = childTag->getAttributeUrect();
frame.location.useGridLocation = false;
}
else if (childTag->name == "gridlocation") {
if (frameSetGridSet == false) {
throw xml_error(*childTag, "Frameset grid is not set.");
}
frame.location.gridLocation = childTag->getAttributeUpoint();
frame.location.useGridLocation = true;
}
else {
throw xml_error(*childTag, "location or gridlocation tag must be the first child of frame");
}
xml.parseCloseTag();
}
else {
throw xml_error(*tag, "location or gridlocation tag must be the first child of frame");
}
frame.location.useGridOrigin = true;
frame.location.update(frameSet.grid, frame);
frame.solid = false;
while ((childTag = xml.parseTag())) {
if (childTag->name == "object") {
FrameObject obj;
std::string sizeStr = childTag->getAttribute("size");
if (sizeStr == "small") {
obj.size = ObjectSize::SMALL;
}
else if (sizeStr == "large") {
obj.size = ObjectSize::LARGE;
}
else {
throw xml_error(*childTag, "Unknown object size");
}
obj.location = childTag->getAttributeUpoint();
frame.objects.push_back(obj);
}
else if (childTag->name == "actionpoint") {
ActionPoint ap;
ap.location = childTag->getAttributeUpoint();
ap.parameter = childTag->getAttributeClamped<ActionPointParameter>("parameter");
frame.actionPoints.push_back(ap);
}
else if (childTag->name == "entityhitbox") {
EntityHitbox eh;
eh.aabb = childTag->getAttributeUrect();
eh.hitboxType = EntityHitboxType::from_string(childTag->getAttribute("type"));
frame.entityHitboxes.push_back(eh);
}
else if (childTag->name == "tilehitbox") {
if (frame.solid) {
throw xml_error(*childTag, "Can only have one tilehitbox per frame");
}
frame.tileHitbox = childTag->getAttributeUrect();
frame.solid = true;
}
else if (childTag->name == "origin") {
if (frame.location.useGridOrigin == false) {
throw xml_error(*childTag, "Can only have one origin per frame");
}
frame.location.useGridOrigin = false;
frame.location.origin = childTag->getAttributeUpoint();
}
else {
throw unknown_tag_error(*childTag);
}
xml.parseCloseTag();
}
}
inline void readPalette(const XmlTag* tag)
{
assert(tag->name == "palette");
if (frameSet.palette.usesUserSuppliedPalette()) {
throw xml_error(*tag, "Only one palette tag allowed per frameset");
}
frameSet.palette.nPalettes = tag->getAttributeUnsigned("npalettes", 1);
frameSet.palette.colorSize = tag->getAttributeUnsigned("colorsize", 1);
}
};
std::unique_ptr<FrameSet> readFrameSet(XmlReader& xml, const XmlTag* tag)
{
auto frameSet = std::make_unique<FrameSet>();
FrameSetReader reader(*frameSet.get(), xml);
reader.readFrameSet(tag);
return frameSet;
}
/*
* FRAME SET WRITER
* ================
*/
inline void writeFrame(XmlWriter& xml, const std::string& frameName, const Frame& frame)
{
xml.writeTag("frame");
xml.writeTagAttribute("id", frameName);
xml.writeTagAttribute("order", frame.spriteOrder);
if (frame.location.useGridLocation) {
xml.writeTag("gridlocation");
xml.writeTagAttributeUpoint(frame.location.gridLocation);
xml.writeCloseTag();
}
else {
xml.writeTag("location");
xml.writeTagAttributeUrect(frame.location.aabb);
xml.writeCloseTag();
}
if (frame.location.useGridOrigin == false) {
xml.writeTag("origin");
xml.writeTagAttributeUpoint(frame.location.origin);
xml.writeCloseTag();
}
if (frame.solid) {
xml.writeTag("tilehitbox");
xml.writeTagAttributeUrect(frame.tileHitbox);
xml.writeCloseTag();
}
for (const FrameObject& obj : frame.objects) {
xml.writeTag("object");
if (obj.size == ObjectSize::SMALL) {
xml.writeTagAttribute("size", "small");
}
else {
xml.writeTagAttribute("size", "large");
}
xml.writeTagAttributeUpoint(obj.location);
xml.writeCloseTag();
}
for (const ActionPoint& ap : frame.actionPoints) {
xml.writeTag("actionpoint");
xml.writeTagAttribute("parameter", ap.parameter);
xml.writeTagAttributeUpoint(ap.location);
xml.writeCloseTag();
}
for (const EntityHitbox& eh : frame.entityHitboxes) {
xml.writeTag("entityhitbox");
xml.writeTagAttribute("type", eh.hitboxType.to_string());
xml.writeTagAttributeUrect(eh.aabb);
xml.writeCloseTag();
}
xml.writeCloseTag();
}
inline void writeFrameSetGrid(XmlWriter& xml, const FrameSetGrid& grid)
{
xml.writeTag("grid");
xml.writeTagAttributeUsize(grid.frameSize, "width", "height");
xml.writeTagAttributeUpoint(grid.offset, "xoffset", "yoffset");
xml.writeTagAttributeUpoint(grid.padding, "xpadding", "ypadding");
xml.writeTagAttributeUpoint(grid.origin, "xorigin", "yorigin");
xml.writeCloseTag();
}
void writeFrameSet(XmlWriter& xml, const FrameSet& frameSet)
{
xml.writeTag("spriteimporter");
xml.writeTagAttribute("id", frameSet.name);
xml.writeTagAttributeEnum("tilesettype", frameSet.tilesetType);
if (frameSet.exportOrder.isValid()) {
xml.writeTagAttribute("exportorder", frameSet.exportOrder);
}
if (!frameSet.imageFilename.empty()) {
xml.writeTagAttributeFilename("image", frameSet.imageFilename);
}
if (frameSet.transparentColorValid()) {
static_assert(sizeof(unsigned) >= 3, "Unsigned value too small");
unsigned rgb = frameSet.transparentColor.rgb();
xml.writeTagAttributeHex("transparent", rgb, 6);
}
writeFrameSetGrid(xml, frameSet.grid);
if (frameSet.palette.usesUserSuppliedPalette()) {
xml.writeTag("palette");
xml.writeTagAttribute("npalettes", frameSet.palette.nPalettes);
xml.writeTagAttribute("colorsize", frameSet.palette.colorSize);
xml.writeCloseTag();
}
for (const auto& f : frameSet.frames) {
writeFrame(xml, f.first, f.second);
}
Animation::writeAnimations(xml, frameSet.animations);
xml.writeCloseTag();
}
}
}
}
<|endoftext|>
|
<commit_before>#include <QtTest/QtTest>
#include <QDebug>
#include "../../../modules/Qnite/plugin/qniteticker.h"
class FooTicker : public QniteTicker
{
Q_OBJECT
public:
FooTicker(QObject * p=0) : QniteTicker(p) {}
void buildTicks()
{
m_majorTicks.clear();
for (int i=0; i<m_numSteps; ++i) {
m_majorTicks << i * 1.5;
}
}
};
class TestQniteTicker: public QObject
{
Q_OBJECT
FooTicker ticker;
QList<qreal> alist;
QList<qreal> anotherlist;
QList<qreal> anotherlistagain;
private slots:
void initTestCase()
{
alist << 1. << 2. << 3. << 4.;
anotherlist << -1. << 1.1 << 1.2;
anotherlistagain << -1. << 1.1 << 1.2 << 2. << 2.2;
}
void testBoundaries()
{
ticker.reset();
QList<qreal> b;
b << -1. << 1.;
ticker.setBoundaries(b);
QCOMPARE(ticker.lower(), -1.);
QCOMPARE(ticker.upper(), 1.);
}
void testSetValues()
{
ticker.reset();
ticker.setValues(alist);
QList<qreal> l;
QCOMPARE(ticker.values(), alist);
QCOMPARE(ticker.lower(), 1.);
QCOMPARE(ticker.upper(), 4.);
QCOMPARE(ticker.majorTicks(), l);
ticker.setNumSteps(3);
// build l according to builTicks() implementation from FooTicker
l << 0. << 1.5 << 3.0;
QCOMPARE(ticker.majorTicks(), l);
}
void testSetTicks()
{
ticker.reset();
ticker.setMinorTicks(alist);
ticker.setMidTicks(anotherlist);
ticker.setMajorTicks(anotherlistagain);
QCOMPARE(ticker.minorTicks(), alist);
QCOMPARE(ticker.midTicks(), anotherlist);
QCOMPARE(ticker.majorTicks(), anotherlistagain);
}
void testReset()
{
ticker.setValues(alist);
ticker.setNumSteps(5);
ticker.buildTicks();
ticker.reset();
QCOMPARE(ticker.numSteps(), 0);
QCOMPARE(ticker.lower(), 0.);
QCOMPARE(ticker.upper(), 0.);
QCOMPARE(ticker.values(), QList<qreal>());
QCOMPARE(ticker.minorTicks(), QList<qreal>());
QCOMPARE(ticker.midTicks(), QList<qreal>());
QCOMPARE(ticker.majorTicks(), QList<qreal>());
}
void testDefaults()
{
FooTicker foo;
QCOMPARE(foo.numSteps(), 0);
QCOMPARE(foo.lower(), 0.);
QCOMPARE(foo.upper(), 0.);
QCOMPARE(foo.values(), QList<qreal>());
QCOMPARE(foo.minorTicks(), QList<qreal>());
QCOMPARE(foo.midTicks(), QList<qreal>());
QCOMPARE(foo.majorTicks(), QList<qreal>());
}
void testSetNumSteps()
{
ticker.reset();
ticker.setNumSteps(5);
ticker.setValues(alist);
QCOMPARE(ticker.majorTicks().size(), 5);
ticker.setNumSteps(6);
QCOMPARE(ticker.majorTicks().size(), 6);
}
};
QTEST_MAIN(TestQniteTicker)
#include "tst_qniteticker.moc"
<commit_msg>reformat<commit_after>#include <QtTest/QtTest>
#include <QDebug>
#include <QSignalSpy>
#include "../../../modules/Qnite/plugin/qniteticker.h"
class FooTicker : public QniteTicker
{
Q_OBJECT
public:
FooTicker(QObject * p=0) : QniteTicker(p) {}
void buildTicks()
{
m_majorTicks.clear();
for (int i=0; i<m_numSteps; ++i) {
m_majorTicks << i * 1.5;
}
}
};
class TestQniteTicker: public QObject
{
Q_OBJECT
FooTicker ticker;
QList<qreal> alist;
QList<qreal> anotherlist;
QList<qreal> anotherlistagain;
private slots:
void initTestCase()
{
alist << 1. << 2. << 3. << 4.;
anotherlist << -1. << 1.1 << 1.2;
anotherlistagain << -1. << 1.1 << 1.2 << 2. << 2.2;
}
void testBoundaries()
{
ticker.reset();
QList<qreal> b;
b << -1. << 1.;
QSignalSpy spy(&ticker, SIGNAL(boundariesChanged()));
ticker.setBoundaries(b);
QCOMPARE(ticker.lower(), -1.);
QCOMPARE(ticker.upper(), 1.);
QCOMPARE(spy.count(), 1);
}
void testSetValues()
{
ticker.reset();
QSignalSpy spy(&ticker, SIGNAL(valuesChanged()));
ticker.setValues(alist);
QList<qreal> l;
QCOMPARE(ticker.values(), alist);
QCOMPARE(ticker.lower(), 1.);
QCOMPARE(ticker.upper(), 4.);
QCOMPARE(ticker.majorTicks(), l);
QCOMPARE(spy.count(), 1);
}
void testSetTicks()
{
ticker.reset();
QSignalSpy spy1(&ticker, SIGNAL(minorTicksChanged()));
QSignalSpy spy2(&ticker, SIGNAL(midTicksChanged()));
QSignalSpy spy3(&ticker, SIGNAL(midTicksChanged()));
ticker.setMinorTicks(alist);
ticker.setMidTicks(anotherlist);
ticker.setMajorTicks(anotherlistagain);
QCOMPARE(ticker.minorTicks(), alist);
QCOMPARE(ticker.midTicks(), anotherlist);
QCOMPARE(ticker.majorTicks(), anotherlistagain);
QCOMPARE(spy1.count(), 1);
QCOMPARE(spy2.count(), 1);
QCOMPARE(spy3.count(), 1);
}
void testReset()
{
ticker.setValues(alist);
ticker.setNumSteps(5);
ticker.buildTicks();
ticker.reset();
QCOMPARE(ticker.numSteps(), 0);
QCOMPARE(ticker.lower(), 0.);
QCOMPARE(ticker.upper(), 0.);
QCOMPARE(ticker.values(), QList<qreal>());
QCOMPARE(ticker.minorTicks(), QList<qreal>());
QCOMPARE(ticker.midTicks(), QList<qreal>());
QCOMPARE(ticker.majorTicks(), QList<qreal>());
}
void testDefaults()
{
FooTicker foo;
QCOMPARE(foo.numSteps(), 0);
QCOMPARE(foo.lower(), 0.);
QCOMPARE(foo.upper(), 0.);
QCOMPARE(foo.values(), QList<qreal>());
QCOMPARE(foo.minorTicks(), QList<qreal>());
QCOMPARE(foo.midTicks(), QList<qreal>());
QCOMPARE(foo.majorTicks(), QList<qreal>());
}
void testSetNumSteps()
{
ticker.reset();
QSignalSpy spy(&ticker, SIGNAL(numStepsChanged()));
ticker.setNumSteps(5);
ticker.setValues(alist);
QCOMPARE(ticker.majorTicks().size(), 5);
ticker.setNumSteps(6);
QCOMPARE(ticker.majorTicks().size(), 6);
QCOMPARE(spy.count(), 2);
}
};
QTEST_MAIN(TestQniteTicker)
#include "tst_qniteticker.moc"
<|endoftext|>
|
<commit_before><?hh //strict
namespace Hackdinium\Game;
use Hackdinium\Aim;
final class Pos {
public ImmVector<Pos> $neighbors = ImmVector {};
public function __construct(public int $x, public int $y) {}
public function neighbors() : ImmVector<Pos> {
return Aim::members()->map($dir ==> $this->to($dir)());
}
public function to(Aim $dir) : this {
switch ($dir) {
case Aim::NORTH(): return $this->copy(-1, 0);
case Aim::EAST(): return $this->copy( 0, 1);
case Aim::SOUTH(): return $this->copy( 1, 0);
case Aim::WEST(): return $this->copy( 0, -1);
case Aim::STAY(): // FALLTHROUGH
default: return $this;
}
}
public function dirTo(Pos $pos) : ?Aim {
if ($pos->y < $this->y) { return Aim::WEST(); }
elseif ($pos->x > $this->x) { return Aim::SOUTH(); }
elseif ($pos->y > $this->y) { return Aim::EAST(); }
elseif ($pos->x < $this->x) { return Aim::NORTH(); }
return null;
}
public function within(int $size) : bool {
return $this->x >= 0 && $this->x < $size && $this->y >= 0 && $this->y < $size;
}
public function __toString() : string {
return sprintf('x:%d y:%d', $this->x, $this->y);
}
private function copy(int $x, int $y) : this {
return new Pos($this->x + $x, $this->y + $y);
}
}
<commit_msg>Fixing call to Pos::to() in Pos::neighbors()<commit_after><?hh //strict
namespace Hackdinium\Game;
use Hackdinium\Aim;
final class Pos {
public ImmVector<Pos> $neighbors = ImmVector {};
public function __construct(public int $x, public int $y) {}
public function neighbors() : ImmVector<Pos> {
return Aim::members()->map($dir ==> $this->to($dir));
}
public function to(Aim $dir) : this {
switch ($dir) {
case Aim::NORTH(): return $this->copy(-1, 0);
case Aim::EAST(): return $this->copy( 0, 1);
case Aim::SOUTH(): return $this->copy( 1, 0);
case Aim::WEST(): return $this->copy( 0, -1);
case Aim::STAY(): // FALLTHROUGH
default: return $this;
}
}
public function dirTo(Pos $pos) : ?Aim {
if ($pos->y < $this->y) { return Aim::WEST(); }
elseif ($pos->x > $this->x) { return Aim::SOUTH(); }
elseif ($pos->y > $this->y) { return Aim::EAST(); }
elseif ($pos->x < $this->x) { return Aim::NORTH(); }
return null;
}
public function within(int $size) : bool {
return $this->x >= 0 && $this->x < $size && $this->y >= 0 && $this->y < $size;
}
public function __toString() : string {
return sprintf('x:%d y:%d', $this->x, $this->y);
}
private function copy(int $x, int $y) : this {
return new Pos($this->x + $x, $this->y + $y);
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2020 Ultimaker B.V.
// CuraEngine is released under the terms of the AGPLv3 or higher.
#include <algorithm> //For std::partition_copy and std::min_element.
#include <unordered_set>
#include "WallToolPaths.h"
#include "SkeletalTrapezoidation.h"
#include "BeadingStrategy/BeadingOrderOptimizer.h"
#include "utils/SparsePointGrid.h" //To stitch the inner contour.
#include "utils/polygonUtils.h"
namespace cura
{
constexpr coord_t transition_length_multiplier = 2;
WallToolPaths::WallToolPaths(const Polygons& outline, const coord_t nominal_bead_width, const size_t inset_count,
const Settings& settings)
: outline(outline)
, bead_width_0(nominal_bead_width)
, bead_width_x(nominal_bead_width)
, inset_count(inset_count)
, strategy_type(settings.get<StrategyType>("beading_strategy_type"))
, print_thin_walls(settings.get<bool>("fill_outline_gaps"))
, min_feature_size(settings.get<coord_t>("min_feature_size"))
, min_bead_width(settings.get<coord_t>("min_bead_width"))
, small_area_length(INT2MM(static_cast<double>(nominal_bead_width) / 2))
, transition_length(transition_length_multiplier * nominal_bead_width)
, toolpaths_generated(false)
{
}
WallToolPaths::WallToolPaths(const Polygons& outline, const coord_t bead_width_0, const coord_t bead_width_x,
const size_t inset_count, const Settings& settings)
: outline(outline)
, bead_width_0(bead_width_0)
, bead_width_x(bead_width_x)
, inset_count(inset_count)
, strategy_type(settings.get<StrategyType>("beading_strategy_type"))
, print_thin_walls(settings.get<bool>("fill_outline_gaps"))
, min_feature_size(settings.get<coord_t>("min_feature_size"))
, min_bead_width(settings.get<coord_t>("min_bead_width"))
, small_area_length(INT2MM(static_cast<double>(bead_width_0) / 2))
, transition_length(transition_length_multiplier * bead_width_0)
, toolpaths_generated(false)
{
}
const VariableWidthPaths& WallToolPaths::generate()
{
constexpr coord_t smallest_segment = 50;
constexpr coord_t allowed_distance = 50;
constexpr coord_t epsilon_offset = (allowed_distance / 2) - 1;
constexpr float transitioning_angle = 0.5;
// Simplify outline for boost::voronoi consumption. Absolutely no self intersections or near-self intersections allowed:
// TODO: Open question: Does this indeed fix all (or all-but-one-in-a-million) cases for manifold but otherwise possibly complex polygons?
Polygons prepared_outline = outline.offset(-epsilon_offset).offset(epsilon_offset);
prepared_outline.simplify(smallest_segment, allowed_distance);
PolygonUtils::fixSelfIntersections(epsilon_offset, prepared_outline);
prepared_outline.removeDegenerateVerts();
prepared_outline.removeColinearEdges();
prepared_outline.removeSmallAreas(small_area_length * small_area_length, false);
if (prepared_outline.area() > 0)
{
const size_t max_bead_count = 2 * inset_count;
const auto beading_strat = std::unique_ptr<BeadingStrategy>(BeadingStrategyFactory::makeStrategy(
strategy_type, bead_width_0, bead_width_x, transition_length, transitioning_angle, print_thin_walls, min_bead_width,
min_feature_size, max_bead_count));
SkeletalTrapezoidation wall_maker(prepared_outline, *beading_strat, beading_strat->transitioning_angle);
wall_maker.generateToolpaths(toolpaths);
computeInnerContour();
}
removeEmptyToolPaths(toolpaths);
toolpaths_generated = true;
return toolpaths;
}
const VariableWidthPaths& WallToolPaths::getToolPaths()
{
if (!toolpaths_generated)
{
return generate();
}
return toolpaths;
}
void WallToolPaths::computeInnerContour()
{
//We'll remove all 0-width paths from the original toolpaths and store them separately as polygons.
VariableWidthPaths actual_toolpaths;
actual_toolpaths.reserve(toolpaths.size()); //A bit too much, but the correct order of magnitude.
VariableWidthPaths contour_paths;
contour_paths.reserve(toolpaths.size() / inset_count);
std::partition_copy(toolpaths.begin(), toolpaths.end(), std::back_inserter(actual_toolpaths), std::back_inserter(contour_paths),
[](const VariableWidthLines& path)
{
for(const ExtrusionLine& line : path)
{
for(const ExtrusionJunction& junction : line.junctions)
{
return junction.w != 0; //On the first actual junction, decide: If it's got 0 width, this is a contour. Otherwise it is an actual toolpath.
}
}
return true; //No junctions with any vertices? Classify it as a toolpath then.
});
toolpaths = actual_toolpaths; //Filtered out the 0-width paths.
//Now convert the contour_paths to Polygons to denote the inner contour of the walled areas.
inner_contour.clear();
//We're going to have to stitch these paths since not all walls may be closed contours.
//Since these walls have 0 width they should theoretically be closed. But there may be rounding errors.
const coord_t minimum_line_width = bead_width_0 / 2;
stitchContours(contour_paths, minimum_line_width, inner_contour);
//The output walls from the skeletal trapezoidation have no known winding order, especially if they are joined together from polylines.
//They can be in any direction, clockwise or counter-clockwise, regardless of whether the shapes are positive or negative.
//To get a correct shape, we need to make the outside contour positive and any holes inside negative.
//This can be done by applying the even-odd rule to the shape. This rule is not sensitive to the winding order of the polygon.
//The even-odd rule would be incorrect if the polygon self-intersects, but that should never be generated by the skeletal trapezoidation.
inner_contour = inner_contour.unionPolygons(Polygons(), ClipperLib::pftEvenOdd);
}
const Polygons& WallToolPaths::getInnerContour()
{
if (!toolpaths_generated && inset_count > 0)
{
generate();
}
else if(inset_count == 0)
{
return outline;
}
return inner_contour;
}
const Polygons& WallToolPaths::getOutline() const
{
return outline;
}
bool WallToolPaths::removeEmptyToolPaths(VariableWidthPaths& toolpaths)
{
toolpaths.erase(std::remove_if(toolpaths.begin(), toolpaths.end(), [](const VariableWidthLines& lines)
{
return lines.empty();
}), toolpaths.end());
return toolpaths.empty();
}
void WallToolPaths::stitchContours(const VariableWidthPaths& input, const coord_t stitch_distance, Polygons& output) const
{
//Create a bucket grid to find endpoints that are close together.
struct ExtrusionLineEndpointLocator
{
Point operator()(const ExtrusionLine* line)
{
return Point(line->junctions.front().p);
}
};
SparsePointGrid<const ExtrusionLine*, ExtrusionLineEndpointLocator> line_endpoints(stitch_distance); //Only find endpoints closer than minimum_line_width, so we can't ever accidentally make crossing contours.
for(const VariableWidthLines& path : input)
{
for(const ExtrusionLine& line : path)
{
line_endpoints.insert(&line);
}
}
//Then go through all lines and construct chains of polylines if the endpoints are nearby.
std::unordered_set<const ExtrusionLine*> processed_lines; //Track which lines were already processed to not process them twice.
for(const VariableWidthLines& path : input)
{
for(const ExtrusionLine& line : path)
{
if(processed_lines.find(&line) != processed_lines.end()) //We already added this line before.
{
continue;
}
output.emplace_back();
const ExtrusionLine* nearest = &line;
while(nearest)
{
if(processed_lines.find(nearest) != processed_lines.end())
{
break; //Looping. This contour is already processed.
}
for(const ExtrusionJunction& junction : nearest->junctions)
{
output.back().add(junction.p);
}
processed_lines.insert(nearest);
//Find any nearby lines to attach.
const Point current_position = nearest->junctions.back().p;
const std::vector<const ExtrusionLine*> nearby = line_endpoints.getNearby(current_position, stitch_distance);
nearest = nullptr;
coord_t nearest_dist2 = std::numeric_limits<coord_t>::max();
for(const ExtrusionLine* candidate : nearby)
{
if(processed_lines.find(candidate) != processed_lines.end())
{
continue; //Already processed this line before. It's linked to something else.
}
const coord_t dist2 = vSize2(candidate->junctions.front().p - current_position);
if(dist2 < nearest_dist2)
{
nearest = candidate;
nearest_dist2 = dist2;
continue;
}
}
}
}
}
}
} // namespace cura
<commit_msg>Move-assign to filter zero-width toolpaths from toolpaths<commit_after>// Copyright (c) 2020 Ultimaker B.V.
// CuraEngine is released under the terms of the AGPLv3 or higher.
#include <algorithm> //For std::partition_copy and std::min_element.
#include <unordered_set>
#include "WallToolPaths.h"
#include "SkeletalTrapezoidation.h"
#include "BeadingStrategy/BeadingOrderOptimizer.h"
#include "utils/SparsePointGrid.h" //To stitch the inner contour.
#include "utils/polygonUtils.h"
namespace cura
{
constexpr coord_t transition_length_multiplier = 2;
WallToolPaths::WallToolPaths(const Polygons& outline, const coord_t nominal_bead_width, const size_t inset_count,
const Settings& settings)
: outline(outline)
, bead_width_0(nominal_bead_width)
, bead_width_x(nominal_bead_width)
, inset_count(inset_count)
, strategy_type(settings.get<StrategyType>("beading_strategy_type"))
, print_thin_walls(settings.get<bool>("fill_outline_gaps"))
, min_feature_size(settings.get<coord_t>("min_feature_size"))
, min_bead_width(settings.get<coord_t>("min_bead_width"))
, small_area_length(INT2MM(static_cast<double>(nominal_bead_width) / 2))
, transition_length(transition_length_multiplier * nominal_bead_width)
, toolpaths_generated(false)
{
}
WallToolPaths::WallToolPaths(const Polygons& outline, const coord_t bead_width_0, const coord_t bead_width_x,
const size_t inset_count, const Settings& settings)
: outline(outline)
, bead_width_0(bead_width_0)
, bead_width_x(bead_width_x)
, inset_count(inset_count)
, strategy_type(settings.get<StrategyType>("beading_strategy_type"))
, print_thin_walls(settings.get<bool>("fill_outline_gaps"))
, min_feature_size(settings.get<coord_t>("min_feature_size"))
, min_bead_width(settings.get<coord_t>("min_bead_width"))
, small_area_length(INT2MM(static_cast<double>(bead_width_0) / 2))
, transition_length(transition_length_multiplier * bead_width_0)
, toolpaths_generated(false)
{
}
const VariableWidthPaths& WallToolPaths::generate()
{
constexpr coord_t smallest_segment = 50;
constexpr coord_t allowed_distance = 50;
constexpr coord_t epsilon_offset = (allowed_distance / 2) - 1;
constexpr float transitioning_angle = 0.5;
// Simplify outline for boost::voronoi consumption. Absolutely no self intersections or near-self intersections allowed:
// TODO: Open question: Does this indeed fix all (or all-but-one-in-a-million) cases for manifold but otherwise possibly complex polygons?
Polygons prepared_outline = outline.offset(-epsilon_offset).offset(epsilon_offset);
prepared_outline.simplify(smallest_segment, allowed_distance);
PolygonUtils::fixSelfIntersections(epsilon_offset, prepared_outline);
prepared_outline.removeDegenerateVerts();
prepared_outline.removeColinearEdges();
prepared_outline.removeSmallAreas(small_area_length * small_area_length, false);
if (prepared_outline.area() > 0)
{
const size_t max_bead_count = 2 * inset_count;
const auto beading_strat = std::unique_ptr<BeadingStrategy>(BeadingStrategyFactory::makeStrategy(
strategy_type, bead_width_0, bead_width_x, transition_length, transitioning_angle, print_thin_walls, min_bead_width,
min_feature_size, max_bead_count));
SkeletalTrapezoidation wall_maker(prepared_outline, *beading_strat, beading_strat->transitioning_angle);
wall_maker.generateToolpaths(toolpaths);
computeInnerContour();
}
removeEmptyToolPaths(toolpaths);
toolpaths_generated = true;
return toolpaths;
}
const VariableWidthPaths& WallToolPaths::getToolPaths()
{
if (!toolpaths_generated)
{
return generate();
}
return toolpaths;
}
void WallToolPaths::computeInnerContour()
{
//We'll remove all 0-width paths from the original toolpaths and store them separately as polygons.
VariableWidthPaths actual_toolpaths;
actual_toolpaths.reserve(toolpaths.size()); //A bit too much, but the correct order of magnitude.
VariableWidthPaths contour_paths;
contour_paths.reserve(toolpaths.size() / inset_count);
std::partition_copy(toolpaths.begin(), toolpaths.end(), std::back_inserter(actual_toolpaths), std::back_inserter(contour_paths),
[](const VariableWidthLines& path)
{
for(const ExtrusionLine& line : path)
{
for(const ExtrusionJunction& junction : line.junctions)
{
return junction.w != 0; //On the first actual junction, decide: If it's got 0 width, this is a contour. Otherwise it is an actual toolpath.
}
}
return true; //No junctions with any vertices? Classify it as a toolpath then.
});
toolpaths = std::move(actual_toolpaths); //Filtered out the 0-width paths.
//Now convert the contour_paths to Polygons to denote the inner contour of the walled areas.
inner_contour.clear();
//We're going to have to stitch these paths since not all walls may be closed contours.
//Since these walls have 0 width they should theoretically be closed. But there may be rounding errors.
const coord_t minimum_line_width = bead_width_0 / 2;
stitchContours(contour_paths, minimum_line_width, inner_contour);
//The output walls from the skeletal trapezoidation have no known winding order, especially if they are joined together from polylines.
//They can be in any direction, clockwise or counter-clockwise, regardless of whether the shapes are positive or negative.
//To get a correct shape, we need to make the outside contour positive and any holes inside negative.
//This can be done by applying the even-odd rule to the shape. This rule is not sensitive to the winding order of the polygon.
//The even-odd rule would be incorrect if the polygon self-intersects, but that should never be generated by the skeletal trapezoidation.
inner_contour = inner_contour.unionPolygons(Polygons(), ClipperLib::pftEvenOdd);
}
const Polygons& WallToolPaths::getInnerContour()
{
if (!toolpaths_generated && inset_count > 0)
{
generate();
}
else if(inset_count == 0)
{
return outline;
}
return inner_contour;
}
const Polygons& WallToolPaths::getOutline() const
{
return outline;
}
bool WallToolPaths::removeEmptyToolPaths(VariableWidthPaths& toolpaths)
{
toolpaths.erase(std::remove_if(toolpaths.begin(), toolpaths.end(), [](const VariableWidthLines& lines)
{
return lines.empty();
}), toolpaths.end());
return toolpaths.empty();
}
void WallToolPaths::stitchContours(const VariableWidthPaths& input, const coord_t stitch_distance, Polygons& output) const
{
//Create a bucket grid to find endpoints that are close together.
struct ExtrusionLineEndpointLocator
{
Point operator()(const ExtrusionLine* line)
{
return Point(line->junctions.front().p);
}
};
SparsePointGrid<const ExtrusionLine*, ExtrusionLineEndpointLocator> line_endpoints(stitch_distance); //Only find endpoints closer than minimum_line_width, so we can't ever accidentally make crossing contours.
for(const VariableWidthLines& path : input)
{
for(const ExtrusionLine& line : path)
{
line_endpoints.insert(&line);
}
}
//Then go through all lines and construct chains of polylines if the endpoints are nearby.
std::unordered_set<const ExtrusionLine*> processed_lines; //Track which lines were already processed to not process them twice.
for(const VariableWidthLines& path : input)
{
for(const ExtrusionLine& line : path)
{
if(processed_lines.find(&line) != processed_lines.end()) //We already added this line before.
{
continue;
}
output.emplace_back();
const ExtrusionLine* nearest = &line;
while(nearest)
{
if(processed_lines.find(nearest) != processed_lines.end())
{
break; //Looping. This contour is already processed.
}
for(const ExtrusionJunction& junction : nearest->junctions)
{
output.back().add(junction.p);
}
processed_lines.insert(nearest);
//Find any nearby lines to attach.
const Point current_position = nearest->junctions.back().p;
const std::vector<const ExtrusionLine*> nearby = line_endpoints.getNearby(current_position, stitch_distance);
nearest = nullptr;
coord_t nearest_dist2 = std::numeric_limits<coord_t>::max();
for(const ExtrusionLine* candidate : nearby)
{
if(processed_lines.find(candidate) != processed_lines.end())
{
continue; //Already processed this line before. It's linked to something else.
}
const coord_t dist2 = vSize2(candidate->junctions.front().p - current_position);
if(dist2 < nearest_dist2)
{
nearest = candidate;
nearest_dist2 = dist2;
continue;
}
}
}
}
}
}
} // namespace cura
<|endoftext|>
|
<commit_before>#include <tiramisu/tiramisu.h>
#include <tiramisu/auto_scheduler/evaluator.h>
#include <tiramisu/auto_scheduler/search_method.h>
using namespace tiramisu;
// Set to true to perform autoscheduling
bool perform_autoscheduling = false;
// Path to python (please give absolute path)
const std::string py_cmd_path = "/usr/bin/python;
const std::string py_interface_path = "/data/tiramisu/tutorials/tutorial_autoscheduler/model/main.py";
int main(int argc, char **argv)
{
tiramisu::init("conv");
var n("n", 0, 8), fout("fout", 0, 2), y("y", 0, 1024), x("x", 0, 1024), fin("fin", 0, 3) ,
k_y("k_y", 0, 3), k_x("k_x", 0, 3) , y_pad("y_pad", 0, 1026) , x_pad("x_pad", 0, 1026);
// Declare computations
input bias("bias", {fout}, p_int32);
input src("src", {n, fin, y_pad, x_pad}, p_int32);
input weights("weights", {n, fout, y, x}, p_int32);
computation conv_init("conv_init", {n, fout, y, x}, bias(fout));
computation conv("conv", {n, fout, y, x, fin, k_y, k_x}, p_int32);
conv.set_expression(conv(n, fout, y, x, fin, k_y, k_x) + src(n, fin, y + k_y, x + k_x) * weights(fout, fin, k_y, k_x));
conv_init.then(conv, x);
// Declare buffers
buffer buf_bias("buf_bias", {2}, p_int32, a_input);
buffer buf_src("buf_src", {8, 3, 1026, 1026}, p_int32, a_input);
buffer buf_weights("buf_weights", {2, 3, 3, 3}, p_int32, a_input);
buffer buf_output("buf_output", {8, 2, 1024, 1024}, p_int32, a_output);
bias.store_in(&buf_bias);
src.store_in(&buf_src);
weights.store_in(&buf_weights);
conv_init.store_in(&buf_output);
conv.store_in(&buf_output, {n, fout, y, x});
// Generate a program with no schedule
if (!perform_autoscheduling)
{
tiramisu::codegen({
&buf_output,
&buf_bias,
&buf_src,
&buf_weights
}, "function.o");
return 0;
}
// Some parameters for the search methods
const int beam_size = 2;
const int max_depth = 4;
const int nb_samples = 5;
const int topk = 1;
// An object used by search methods to generate schedules
auto_scheduler::schedules_generator *scheds_gen = new auto_scheduler::ml_model_schedules_generator();
// An evaluation function that measures execution time by compiling and executing the program
auto_scheduler::evaluate_by_execution *exec_eval = new auto_scheduler::evaluate_by_execution({&buf_output, &buf_bias, &buf_src, &buf_weights},
"function.o", "./wrapper");
// An evaluation function that uses an ML model to estimate speedup
auto_scheduler::evaluation_function *model_eval = new auto_scheduler::evaluate_by_learning_model(py_cmd_path, {py_interface_path});
// Two search methods : Beam Search and MCTS
auto_scheduler::search_method *bs = new auto_scheduler::beam_search(beam_size, max_depth, model_eval, scheds_gen);
auto_scheduler::mcts *mcts = new auto_scheduler::mcts(nb_samples, topk, max_depth, model_eval, exec_eval, scheds_gen);
// Create the autoscheduler and start search
auto_scheduler::auto_scheduler as(bs, model_eval);
as.set_exec_evaluator(exec_eval);
as.find_schedule();
as.apply_best_schedule();
delete scheds_gen;
delete exec_eval;
delete bs;
delete mcts;
return 0;
}
<commit_msg>Edit tutorials/tutorial_autoscheduler/generator.cpp<commit_after>#include <tiramisu/tiramisu.h>
#include <tiramisu/auto_scheduler/evaluator.h>
#include <tiramisu/auto_scheduler/search_method.h>
using namespace tiramisu;
// Set to true to perform autoscheduling
bool perform_autoscheduling = false;
// Path to python (please give absolute path)
const std::string py_cmd_path = "/usr/bin/python;
// Path to a script that executes the ML model (please give absolute path)
const std::string py_interface_path = "/data/tiramisu/tutorials/tutorial_autoscheduler/model/main.py";
int main(int argc, char **argv)
{
tiramisu::init("conv");
var n("n", 0, 8), fout("fout", 0, 2), y("y", 0, 1024), x("x", 0, 1024), fin("fin", 0, 3) ,
k_y("k_y", 0, 3), k_x("k_x", 0, 3) , y_pad("y_pad", 0, 1026) , x_pad("x_pad", 0, 1026);
// Declare computations
input bias("bias", {fout}, p_int32);
input src("src", {n, fin, y_pad, x_pad}, p_int32);
input weights("weights", {n, fout, y, x}, p_int32);
computation conv_init("conv_init", {n, fout, y, x}, bias(fout));
computation conv("conv", {n, fout, y, x, fin, k_y, k_x}, p_int32);
conv.set_expression(conv(n, fout, y, x, fin, k_y, k_x) + src(n, fin, y + k_y, x + k_x) * weights(fout, fin, k_y, k_x));
conv_init.then(conv, x);
// Declare buffers
buffer buf_bias("buf_bias", {2}, p_int32, a_input);
buffer buf_src("buf_src", {8, 3, 1026, 1026}, p_int32, a_input);
buffer buf_weights("buf_weights", {2, 3, 3, 3}, p_int32, a_input);
buffer buf_output("buf_output", {8, 2, 1024, 1024}, p_int32, a_output);
bias.store_in(&buf_bias);
src.store_in(&buf_src);
weights.store_in(&buf_weights);
conv_init.store_in(&buf_output);
conv.store_in(&buf_output, {n, fout, y, x});
// Generate a program with no schedule
if (!perform_autoscheduling)
{
tiramisu::codegen({
&buf_output,
&buf_bias,
&buf_src,
&buf_weights
}, "function.o");
return 0;
}
// Some parameters for the search methods
const int beam_size = 2;
const int max_depth = 4;
const int nb_samples = 5;
const int topk = 1;
// An object used by search methods to generate schedules
auto_scheduler::schedules_generator *scheds_gen = new auto_scheduler::ml_model_schedules_generator();
// An evaluation function that measures execution time by compiling and executing the program
auto_scheduler::evaluate_by_execution *exec_eval = new auto_scheduler::evaluate_by_execution({&buf_output, &buf_bias, &buf_src, &buf_weights},
"function.o", "./wrapper");
// An evaluation function that uses an ML model to estimate speedup
auto_scheduler::evaluation_function *model_eval = new auto_scheduler::evaluate_by_learning_model(py_cmd_path, {py_interface_path});
// Two search methods : Beam Search and MCTS
auto_scheduler::search_method *bs = new auto_scheduler::beam_search(beam_size, max_depth, model_eval, scheds_gen);
auto_scheduler::mcts *mcts = new auto_scheduler::mcts(nb_samples, topk, max_depth, model_eval, exec_eval, scheds_gen);
// Create the autoscheduler and start search
auto_scheduler::auto_scheduler as(bs, model_eval);
as.set_exec_evaluator(exec_eval);
as.find_schedule();
as.apply_best_schedule();
delete scheds_gen;
delete exec_eval;
delete bs;
delete mcts;
return 0;
}
<|endoftext|>
|
<commit_before>//
// Created by Michael Barker on 01/09/15.
//
#include "NetUtil.h"
#ifdef __APPLE__
#include <libkern/OSByteOrder.h>
#define htobe16(x) OSSwapHostToBigInt16(x)
#define htole16(x) OSSwapHostToLittleInt16(x)
#define be16toh(x) OSSwapBigToHostInt16(x)
#define le16toh(x) OSSwapLittleToHostInt16(x)
#define htobe32(x) OSSwapHostToBigInt32(x)
#define htole32(x) OSSwapHostToLittleInt32(x)
#define be32toh(x) OSSwapBigToHostInt32(x)
#define le32toh(x) OSSwapLittleToHostInt32(x)
#define htobe64(x) OSSwapHostToBigInt64(x)
#define htole64(x) OSSwapHostToLittleInt64(x)
#define be64toh(x) OSSwapBigToHostInt64(x)
#define le64toh(x) OSSwapLittleToHostInt64(x)
#endif
using namespace aeron::driver::uri;
//bool NetUtil::wildcardMatch(struct in6_addr* data, struct in6_addr* pattern)
//{
// return false;
//}
uint32_t prefixLengthToIpV4Mask(uint32_t subnetPrefix)
{
return UINT32_C(0) == subnetPrefix ? UINT32_C(0) : ~((UINT32_C(1) << (UINT32_C(32) - subnetPrefix)) - UINT32_C(1));
}
bool NetUtil::wildcardMatch(in_addr* data, in_addr* pattern, std::uint32_t prefixLength)
{
std::uint32_t* data_p = (std::uint32_t*) data;
std::uint32_t* pattern_p = (std::uint32_t*) pattern;
std::uint32_t mask = htobe32(prefixLengthToIpV4Mask(prefixLength));
return (*data_p & mask) == (*pattern_p & mask);
}
<commit_msg>[C++]: Remove some noise from subnet prefix matching.<commit_after>//
// Created by Michael Barker on 01/09/15.
//
#include "NetUtil.h"
#ifdef __APPLE__
#include <libkern/OSByteOrder.h>
#define htobe16(x) OSSwapHostToBigInt16(x)
#define htole16(x) OSSwapHostToLittleInt16(x)
#define be16toh(x) OSSwapBigToHostInt16(x)
#define le16toh(x) OSSwapLittleToHostInt16(x)
#define htobe32(x) OSSwapHostToBigInt32(x)
#define htole32(x) OSSwapHostToLittleInt32(x)
#define be32toh(x) OSSwapBigToHostInt32(x)
#define le32toh(x) OSSwapLittleToHostInt32(x)
#define htobe64(x) OSSwapHostToBigInt64(x)
#define htole64(x) OSSwapHostToLittleInt64(x)
#define be64toh(x) OSSwapBigToHostInt64(x)
#define le64toh(x) OSSwapLittleToHostInt64(x)
#endif
using namespace aeron::driver::uri;
//bool NetUtil::wildcardMatch(struct in6_addr* data, struct in6_addr* pattern)
//{
// return false;
//}
uint32_t prefixLengthToIpV4Mask(uint32_t subnetPrefix)
{
return 0 == subnetPrefix ? 0 : ~((1 << (32 - subnetPrefix)) - UINT32_C(1));
}
bool NetUtil::wildcardMatch(in_addr* data, in_addr* pattern, std::uint32_t prefixLength)
{
std::uint32_t* data_p = (std::uint32_t*) data;
std::uint32_t* pattern_p = (std::uint32_t*) pattern;
std::uint32_t mask = htobe32(prefixLengthToIpV4Mask(prefixLength));
return (*data_p & mask) == (*pattern_p & mask);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/message_center/views/toast_contents_view.h"
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/time.h"
#include "base/timer.h"
#include "ui/base/animation/animation_delegate.h"
#include "ui/base/animation/slide_animation.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/message_center_constants.h"
#include "ui/message_center/notification.h"
#include "ui/message_center/views/message_popup_collection.h"
#include "ui/message_center/views/message_view.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
namespace message_center {
namespace {
// The width of a toast before animated reveal and after closing.
const int kClosedToastWidth = 5;
// FadeIn/Out look a bit better if they are slightly longer then default slide.
const int kFadeInOutDuration = 200;
} // namespace.
// static
gfx::Size ToastContentsView::GetToastSizeForView(views::View* view) {
int width = kNotificationWidth + view->GetInsets().width();
return gfx::Size(width, view->GetHeightForWidth(width));
}
ToastContentsView::ToastContentsView(
const Notification* notification,
base::WeakPtr<MessagePopupCollection> collection,
MessageCenter* message_center)
: collection_(collection),
message_center_(message_center),
id_(notification->id()),
is_animating_bounds_(false),
is_closing_(false),
closing_animation_(NULL) {
DCHECK(collection_);
set_notify_enter_exit_on_child(true);
// Sets the transparent background. Then, when the message view is slid out,
// the whole toast seems to slide although the actual bound of the widget
// remains. This is hacky but easier to keep the consistency.
set_background(views::Background::CreateSolidBackground(0, 0, 0, 0));
// Creates the timer only when it does the timeout (i.e. not never-timeout).
if (!notification->never_timeout()) {
timer_.reset(new base::OneShotTimer<ToastContentsView>);
ResetTimeout(notification->priority());
StartTimer();
}
fade_animation_.reset(new ui::SlideAnimation(this));
fade_animation_->SetSlideDuration(kFadeInOutDuration);
}
// This is destroyed when the toast window closes.
ToastContentsView::~ToastContentsView() {
}
views::Widget* ToastContentsView::CreateWidget(gfx::NativeView parent) {
views::Widget::InitParams params(
views::Widget::InitParams::TYPE_POPUP);
params.keep_on_top = true;
params.transparent = true;
if (parent)
params.parent = parent;
else
params.top_level = true;
params.transparent = true;
params.delegate = this;
views::Widget* widget = new views::Widget();
widget->set_focus_on_creation(false);
widget->Init(params);
return widget;
}
void ToastContentsView::SetContents(MessageView* view) {
RemoveAllChildViews(true);
AddChildView(view);
preferred_size_ = GetToastSizeForView(view);
Layout();
}
void ToastContentsView::ResetTimeout(int priority) {
int seconds = kAutocloseDefaultDelaySeconds;
if (priority > DEFAULT_PRIORITY)
seconds = kAutocloseHighPriorityDelaySeconds;
timeout_ = base::TimeDelta::FromSeconds(seconds);
// If timer exists and is not suspended, re-start it with new timeout.
if (timer_.get() && timer_->IsRunning())
StartTimer();
}
void ToastContentsView::SuspendTimer() {
if (!timer_.get() || !timer_->IsRunning())
return;
timer_->Stop();
passed_ += base::Time::Now() - start_time_;
}
void ToastContentsView::StartTimer() {
if (!timer_.get())
return;
base::TimeDelta timeout_to_close =
timeout_ <= passed_ ? base::TimeDelta() : timeout_ - passed_;
start_time_ = base::Time::Now();
timer_->Start(FROM_HERE,
timeout_to_close,
base::Bind(&ToastContentsView::CloseWithAnimation,
base::Unretained(this),
true));
}
void ToastContentsView::RevealWithAnimation(gfx::Point origin) {
// Place/move the toast widgets. Currently it stacks the widgets from the
// right-bottom of the work area.
// TODO(mukai): allow to specify the placement policy from outside of this
// class. The policy should be specified from preference on Windows, or
// the launcher alignment on ChromeOS.
origin_ = gfx::Point(origin.x() - preferred_size_.width(),
origin.y() - preferred_size_.height());
gfx::Rect stable_bounds(origin_, preferred_size_);
SetBoundsInstantly(GetClosedToastBounds(stable_bounds));
StartFadeIn();
SetBoundsWithAnimation(stable_bounds);
}
void ToastContentsView::CloseWithAnimation(bool mark_as_shown) {
if (is_closing_)
return;
is_closing_ = true;
timer_.reset();
if (collection_)
collection_->RemoveToast(this);
if (mark_as_shown)
message_center_->MarkSinglePopupAsShown(id(), false);
StartFadeOut();
}
void ToastContentsView::SetBoundsInstantly(gfx::Rect new_bounds) {
if (new_bounds == bounds())
return;
origin_ = new_bounds.origin();
if (!GetWidget())
return;
GetWidget()->SetBounds(new_bounds);
}
void ToastContentsView::SetBoundsWithAnimation(gfx::Rect new_bounds) {
if (new_bounds == bounds())
return;
origin_ = new_bounds.origin();
if (!GetWidget())
return;
// This picks up the current bounds, so if there was a previous animation
// half-done, the next one will pick up from the current location.
// This is the only place that should query current location of the Widget
// on screen, the rest should refer to the bounds_.
animated_bounds_start_ = GetWidget()->GetWindowBoundsInScreen();
animated_bounds_end_ = new_bounds;
if (collection_)
collection_->IncrementDeferCounter();
if (bounds_animation_.get())
bounds_animation_->Stop();
bounds_animation_.reset(new ui::SlideAnimation(this));
bounds_animation_->Show();
}
void ToastContentsView::StartFadeIn() {
// The decrement is done in OnBoundsAnimationEndedOrCancelled callback.
if (collection_)
collection_->IncrementDeferCounter();
fade_animation_->Stop();
GetWidget()->SetOpacity(0);
GetWidget()->Show();
fade_animation_->Reset(0);
fade_animation_->Show();
}
void ToastContentsView::StartFadeOut() {
// The decrement is done in OnBoundsAnimationEndedOrCancelled callback.
if (collection_)
collection_->IncrementDeferCounter();
fade_animation_->Stop();
closing_animation_ = (is_closing_ ? fade_animation_.get() : NULL);
fade_animation_->Reset(1);
fade_animation_->Hide();
}
void ToastContentsView::OnBoundsAnimationEndedOrCancelled(
const ui::Animation* animation) {
if (collection_)
collection_->DecrementDeferCounter();
if (is_closing_ && closing_animation_ == animation && GetWidget())
GetWidget()->Close();
}
// ui::AnimationDelegate
void ToastContentsView::AnimationProgressed(const ui::Animation* animation) {
if (animation == bounds_animation_.get()) {
gfx::Rect current(animation->CurrentValueBetween(
animated_bounds_start_, animated_bounds_end_));
GetWidget()->SetBounds(current);
} else if (animation == fade_animation_.get()) {
unsigned char opacity =
static_cast<unsigned char>(fade_animation_->GetCurrentValue() * 255);
GetWidget()->SetOpacity(opacity);
}
}
void ToastContentsView::AnimationEnded(const ui::Animation* animation) {
OnBoundsAnimationEndedOrCancelled(animation);
}
void ToastContentsView::AnimationCanceled(
const ui::Animation* animation) {
OnBoundsAnimationEndedOrCancelled(animation);
}
// views::WidgetDelegate
views::View* ToastContentsView::GetContentsView() {
return this;
}
void ToastContentsView::WindowClosing() {
SuspendTimer();
if (!is_closing_ && collection_)
collection_->RemoveToast(this);
}
bool ToastContentsView::CanActivate() const {
#if defined(OS_WIN) && defined(USE_AURA)
return true;
#else
return false;
#endif
}
// views::View
void ToastContentsView::OnMouseEntered(const ui::MouseEvent& event) {
if (collection_)
collection_->OnMouseEntered(this);
}
void ToastContentsView::OnMouseExited(const ui::MouseEvent& event) {
if (collection_)
collection_->OnMouseExited(this);
}
void ToastContentsView::Layout() {
if (child_count() > 0) {
child_at(0)->SetBounds(
0, 0, preferred_size_.width(), preferred_size_.height());
}
}
gfx::Size ToastContentsView::GetPreferredSize() {
return child_count() ? GetToastSizeForView(child_at(0)) : gfx::Size();
}
gfx::Rect ToastContentsView::GetClosedToastBounds(gfx::Rect bounds) {
return gfx::Rect(bounds.x() + bounds.width() - kClosedToastWidth,
bounds.y(),
kClosedToastWidth,
bounds.height());
}
} // namespace message_center
<commit_msg>Changes the order of widget Close() and DecrementDeferCounter().<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/message_center/views/toast_contents_view.h"
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/time.h"
#include "base/timer.h"
#include "ui/base/animation/animation_delegate.h"
#include "ui/base/animation/slide_animation.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/message_center_constants.h"
#include "ui/message_center/notification.h"
#include "ui/message_center/views/message_popup_collection.h"
#include "ui/message_center/views/message_view.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
namespace message_center {
namespace {
// The width of a toast before animated reveal and after closing.
const int kClosedToastWidth = 5;
// FadeIn/Out look a bit better if they are slightly longer then default slide.
const int kFadeInOutDuration = 200;
} // namespace.
// static
gfx::Size ToastContentsView::GetToastSizeForView(views::View* view) {
int width = kNotificationWidth + view->GetInsets().width();
return gfx::Size(width, view->GetHeightForWidth(width));
}
ToastContentsView::ToastContentsView(
const Notification* notification,
base::WeakPtr<MessagePopupCollection> collection,
MessageCenter* message_center)
: collection_(collection),
message_center_(message_center),
id_(notification->id()),
is_animating_bounds_(false),
is_closing_(false),
closing_animation_(NULL) {
DCHECK(collection_);
set_notify_enter_exit_on_child(true);
// Sets the transparent background. Then, when the message view is slid out,
// the whole toast seems to slide although the actual bound of the widget
// remains. This is hacky but easier to keep the consistency.
set_background(views::Background::CreateSolidBackground(0, 0, 0, 0));
// Creates the timer only when it does the timeout (i.e. not never-timeout).
if (!notification->never_timeout()) {
timer_.reset(new base::OneShotTimer<ToastContentsView>);
ResetTimeout(notification->priority());
StartTimer();
}
fade_animation_.reset(new ui::SlideAnimation(this));
fade_animation_->SetSlideDuration(kFadeInOutDuration);
}
// This is destroyed when the toast window closes.
ToastContentsView::~ToastContentsView() {
}
views::Widget* ToastContentsView::CreateWidget(gfx::NativeView parent) {
views::Widget::InitParams params(
views::Widget::InitParams::TYPE_POPUP);
params.keep_on_top = true;
params.transparent = true;
if (parent)
params.parent = parent;
else
params.top_level = true;
params.transparent = true;
params.delegate = this;
views::Widget* widget = new views::Widget();
widget->set_focus_on_creation(false);
widget->Init(params);
return widget;
}
void ToastContentsView::SetContents(MessageView* view) {
RemoveAllChildViews(true);
AddChildView(view);
preferred_size_ = GetToastSizeForView(view);
Layout();
}
void ToastContentsView::ResetTimeout(int priority) {
int seconds = kAutocloseDefaultDelaySeconds;
if (priority > DEFAULT_PRIORITY)
seconds = kAutocloseHighPriorityDelaySeconds;
timeout_ = base::TimeDelta::FromSeconds(seconds);
// If timer exists and is not suspended, re-start it with new timeout.
if (timer_.get() && timer_->IsRunning())
StartTimer();
}
void ToastContentsView::SuspendTimer() {
if (!timer_.get() || !timer_->IsRunning())
return;
timer_->Stop();
passed_ += base::Time::Now() - start_time_;
}
void ToastContentsView::StartTimer() {
if (!timer_.get())
return;
base::TimeDelta timeout_to_close =
timeout_ <= passed_ ? base::TimeDelta() : timeout_ - passed_;
start_time_ = base::Time::Now();
timer_->Start(FROM_HERE,
timeout_to_close,
base::Bind(&ToastContentsView::CloseWithAnimation,
base::Unretained(this),
true));
}
void ToastContentsView::RevealWithAnimation(gfx::Point origin) {
// Place/move the toast widgets. Currently it stacks the widgets from the
// right-bottom of the work area.
// TODO(mukai): allow to specify the placement policy from outside of this
// class. The policy should be specified from preference on Windows, or
// the launcher alignment on ChromeOS.
origin_ = gfx::Point(origin.x() - preferred_size_.width(),
origin.y() - preferred_size_.height());
gfx::Rect stable_bounds(origin_, preferred_size_);
SetBoundsInstantly(GetClosedToastBounds(stable_bounds));
StartFadeIn();
SetBoundsWithAnimation(stable_bounds);
}
void ToastContentsView::CloseWithAnimation(bool mark_as_shown) {
if (is_closing_)
return;
is_closing_ = true;
timer_.reset();
if (collection_)
collection_->RemoveToast(this);
if (mark_as_shown)
message_center_->MarkSinglePopupAsShown(id(), false);
StartFadeOut();
}
void ToastContentsView::SetBoundsInstantly(gfx::Rect new_bounds) {
if (new_bounds == bounds())
return;
origin_ = new_bounds.origin();
if (!GetWidget())
return;
GetWidget()->SetBounds(new_bounds);
}
void ToastContentsView::SetBoundsWithAnimation(gfx::Rect new_bounds) {
if (new_bounds == bounds())
return;
origin_ = new_bounds.origin();
if (!GetWidget())
return;
// This picks up the current bounds, so if there was a previous animation
// half-done, the next one will pick up from the current location.
// This is the only place that should query current location of the Widget
// on screen, the rest should refer to the bounds_.
animated_bounds_start_ = GetWidget()->GetWindowBoundsInScreen();
animated_bounds_end_ = new_bounds;
if (collection_)
collection_->IncrementDeferCounter();
if (bounds_animation_.get())
bounds_animation_->Stop();
bounds_animation_.reset(new ui::SlideAnimation(this));
bounds_animation_->Show();
}
void ToastContentsView::StartFadeIn() {
// The decrement is done in OnBoundsAnimationEndedOrCancelled callback.
if (collection_)
collection_->IncrementDeferCounter();
fade_animation_->Stop();
GetWidget()->SetOpacity(0);
GetWidget()->Show();
fade_animation_->Reset(0);
fade_animation_->Show();
}
void ToastContentsView::StartFadeOut() {
// The decrement is done in OnBoundsAnimationEndedOrCancelled callback.
if (collection_)
collection_->IncrementDeferCounter();
fade_animation_->Stop();
closing_animation_ = (is_closing_ ? fade_animation_.get() : NULL);
fade_animation_->Reset(1);
fade_animation_->Hide();
}
void ToastContentsView::OnBoundsAnimationEndedOrCancelled(
const ui::Animation* animation) {
if (is_closing_ && closing_animation_ == animation && GetWidget())
GetWidget()->Close();
// This cannot be called before GetWidget()->Close(). Decrementing defer count
// will invoke update, which may invoke another close animation with
// incrementing defer counter. Close() after such process will cause a
// mismatch between increment/decrement. See crbug.com/238477
if (collection_)
collection_->DecrementDeferCounter();
}
// ui::AnimationDelegate
void ToastContentsView::AnimationProgressed(const ui::Animation* animation) {
if (animation == bounds_animation_.get()) {
gfx::Rect current(animation->CurrentValueBetween(
animated_bounds_start_, animated_bounds_end_));
GetWidget()->SetBounds(current);
} else if (animation == fade_animation_.get()) {
unsigned char opacity =
static_cast<unsigned char>(fade_animation_->GetCurrentValue() * 255);
GetWidget()->SetOpacity(opacity);
}
}
void ToastContentsView::AnimationEnded(const ui::Animation* animation) {
OnBoundsAnimationEndedOrCancelled(animation);
}
void ToastContentsView::AnimationCanceled(
const ui::Animation* animation) {
OnBoundsAnimationEndedOrCancelled(animation);
}
// views::WidgetDelegate
views::View* ToastContentsView::GetContentsView() {
return this;
}
void ToastContentsView::WindowClosing() {
SuspendTimer();
if (!is_closing_ && collection_)
collection_->RemoveToast(this);
}
bool ToastContentsView::CanActivate() const {
#if defined(OS_WIN) && defined(USE_AURA)
return true;
#else
return false;
#endif
}
// views::View
void ToastContentsView::OnMouseEntered(const ui::MouseEvent& event) {
if (collection_)
collection_->OnMouseEntered(this);
}
void ToastContentsView::OnMouseExited(const ui::MouseEvent& event) {
if (collection_)
collection_->OnMouseExited(this);
}
void ToastContentsView::Layout() {
if (child_count() > 0) {
child_at(0)->SetBounds(
0, 0, preferred_size_.width(), preferred_size_.height());
}
}
gfx::Size ToastContentsView::GetPreferredSize() {
return child_count() ? GetToastSizeForView(child_at(0)) : gfx::Size();
}
gfx::Rect ToastContentsView::GetClosedToastBounds(gfx::Rect bounds) {
return gfx::Rect(bounds.x() + bounds.width() - kClosedToastWidth,
bounds.y(),
kClosedToastWidth,
bounds.height());
}
} // namespace message_center
<|endoftext|>
|
<commit_before>#include "Exporter.h"
#include "VideoFile.h"
#include "SoundBuffer.h"
#include "Common.h"
#include <QtGui>
#include <QtDebug>
using namespace WTS;
class AssertFailed {
public:
AssertFailed(const QString& cond, const QString& file, int line,
QString extra = QString())
{
m_message = QString("%1:%2: assertion '%3' failed")
.arg(file).arg(line).arg(cond);
if (extra.size())
m_message += ". " + extra + ".";
}
QString message() const { return m_message; }
const char * cMessage() const { return m_message.toLocal8Bit().constData(); }
protected:
QString m_message;
};
#define TRY_ASSERT(cond) \
do { if (!cond) { throw AssertFailed(#cond, __FILE__, __LINE__); } } while (0)
#define TRY_ASSERT_X(cond, message) \
do { if (!cond) { throw AssertFailed(#cond, __FILE__, __LINE__, message); \
} } while (0)
Exporter::Exporter(QObject *parent)
: QObject(parent)
, m_originalVideoFile(0)
, m_audio(0)
, m_container(0)
, m_videoStream(0)
, m_audioStream(0)
{
}
void Exporter::configure(const QString& fname,
VideoFile * vfile,
const QList<WtsAudio::BufferAt *>& sequence,
WtsAudio * audio,
QProgressDialog * progress)
{
m_filename = fname.toLocal8Bit();
m_originalVideoFile = vfile;
m_sequence = sequence;
m_audio = audio;
m_progress = progress;
}
void Exporter::initExport()
{
AVOutputFormat * format = av_guess_format(NULL, m_filename.constData(), NULL);
if (!format) {
qWarning() << "Could not deduce output format from file extension: using "
<< VIDEO_FormatTitle;
format = av_guess_format(VIDEO_FMT, NULL, NULL);
}
TRY_ASSERT_X(format, "Could not find suitable output format");
m_container = avformat_alloc_context();
TRY_ASSERT_X(m_container, "Memory error in ffmpeg");
m_container->oformat = format;
// apparently this is the normal ffmpeg way to set the filename
snprintf(m_container->filename,
sizeof(m_container->filename),
"%s",
m_filename.constData());
if (format->audio_codec != CODEC_ID_NONE)
initAudioStream(format->audio_codec);
if (format->video_codec != CODEC_ID_NONE)
initVideoStream();
// set the output parameters (must be done even if no parameters)
TRY_ASSERT_X((av_set_parameters(m_container, NULL) >= 0),
"Invalid output format parameters");
av_dump_format(m_container, 0, m_filename.constData(), 1);
AVCodec * audioCodec = avcodec_find_encoder(m_audioStream->codec->codec_id);
TRY_ASSERT_X(audioCodec, "Could not find audio encoder");
TRY_ASSERT_X((avcodec_open(m_audioStream->codec, audioCodec) >= 0),
"Could not open audio encoder");
AVCodec * videoCodec = avcodec_find_encoder(m_videoStream->codec->codec_id);
TRY_ASSERT_X(videoCodec, "Video codec not found");
TRY_ASSERT_X((avcodec_open(m_videoStream->codec, videoCodec) >= 0),
"Could not open video codec");
TRY_ASSERT_X( ( avio_open(&m_container->pb,
m_filename.constData(),
URL_WRONLY) >= 0 ),
QString("Could not open " + m_filename));
}
void Exporter::performExport()
{
QVector<uint8_t> m_encodedAudio(10000);
// this is copied from ffmpeg's output-example
// original comment states that it's an "ugly hack for PCM codecs"
int mixBufferSize = m_audioStream->codec->frame_size;
if (m_audioStream->codec->frame_size <= 1) {
mixBufferSize = m_encodedAudio.size() / m_audioStream->codec->channels;
switch(m_audioStream->codec->codec_id) {
case CODEC_ID_PCM_S16LE:
case CODEC_ID_PCM_S16BE:
case CODEC_ID_PCM_U16LE:
case CODEC_ID_PCM_U16BE:
mixBufferSize >>= 1;
break;
default:
break;
}
}
QVector<int16_t> m_mixBuffer(mixBufferSize * m_audioStream->codec->channels);
av_write_header(m_container);
m_originalVideoFile->seek(0);
m_audio->samplerClear();
qSort(m_sequence.begin(), m_sequence.end(), WtsAudio::startsBefore);
QList<WtsAudio::BufferAt *>::iterator sequenceCursor = m_sequence.begin();
double duration = (double)m_videoStream->duration
* m_videoStream->time_base.num
/ m_videoStream->time_base.den;
bool moreVideo = true, moreAudio = true;
while(moreVideo || moreAudio) {
double audio_pts = (double)m_audioStream->pts.val
* m_audioStream->time_base.num
/ m_audioStream->time_base.den;
double video_pts = (double)m_videoStream->pts.val
* m_videoStream->time_base.num
/ m_videoStream->time_base.den;
moreAudio = audio_pts < duration;
double pts;
AVPacket packet;
if ( moreVideo
&& (!moreAudio || (video_pts < audio_pts))
&& (moreVideo = m_originalVideoFile->nextPacket(packet)) ) {
packet.stream_index = m_videoStream->index;
av_interleaved_write_frame(m_container, &packet);
pts = video_pts;
} else if (moreAudio) {
av_init_packet(&packet);
qint64 ms = (qint64)(audio_pts * 1000.0);
while( sequenceCursor != m_sequence.end()
&& ((*sequenceCursor)->at()
+ WtsAudio::sampleCountToMs((*sequenceCursor)->buffer()->rangeStart())) <= ms ) {
m_audio->samplerSchedule(*sequenceCursor);
sequenceCursor++;
}
m_audio->samplerMix( ms, m_mixBuffer);
packet.size = avcodec_encode_audio(m_audioStream->codec,
m_encodedAudio.data(),
m_encodedAudio.size(),
m_mixBuffer.data());
if (m_audioStream->codec->coded_frame
&& ( (uint64_t) m_audioStream->codec->coded_frame->pts
!= AV_NOPTS_VALUE) )
packet.pts= av_rescale_q(m_audioStream->codec->coded_frame->pts,
m_audioStream->codec->time_base,
m_audioStream->time_base);
packet.flags |= AV_PKT_FLAG_KEY;
packet.stream_index= m_audioStream->index;
packet.data= m_encodedAudio.data();
av_interleaved_write_frame(m_container, &packet);
pts = audio_pts;
}
m_progress->setValue(100 * pts / duration);
}
av_write_trailer(m_container);
}
void Exporter::run()
{
try {
m_progress->setValue(0);
initExport();
performExport();
finishUp();
m_progress->setValue(100);
QProcess process;
process.startDetached("open", QStringList() << QFileInfo(m_filename).dir().path() );
} catch (const AssertFailed& e) {
qCritical() << e.cMessage();
m_progress->cancel();
QMessageBox dialog(m_progress->parentWidget());
dialog.setText("Fout in exporter");
dialog.setInformativeText("Iets ging verkeerd tijdens het opslaan van " + m_filename);
dialog.setDetailedText(e.message());
dialog.setIcon(QMessageBox::Critical);
dialog.setWindowModality(Qt::WindowModal);
dialog.setModal(true);
dialog.exec();
}
}
void Exporter::finishUp()
{
avcodec_close(m_videoStream->codec);
avcodec_close(m_audioStream->codec);
/* free the resources */
for(unsigned i = 0; i < m_container->nb_streams; i++) {
av_freep(&m_container->streams[i]->codec);
av_freep(&m_container->streams[i]);
}
avio_close(m_container->pb);
av_free(m_container);
}
void Exporter::initAudioStream(CodecID codec_id)
{
AVCodecContext * codecContext;
m_audioStream = av_new_stream(m_container, 1);
TRY_ASSERT_X(m_audioStream, "Could not alloc stream");
codecContext = m_audioStream->codec;
codecContext->codec_id = codec_id;
codecContext->codec_type = AVMEDIA_TYPE_AUDIO;
/* put sample parameters */
codecContext->sample_fmt = AV_SAMPLE_FMT_S16;
codecContext->bit_rate = 64000;
codecContext->sample_rate = 44100;
codecContext->channels = 1;
// some formats want stream headers to be separate
if(m_container->oformat->flags & AVFMT_GLOBALHEADER)
codecContext->flags |= CODEC_FLAG_GLOBAL_HEADER;
}
void Exporter::initVideoStream()
{
// Video output stream is pretty much a copy of the input video
m_videoStream = av_new_stream(m_container, 0);
TRY_ASSERT_X(m_videoStream, "Could not allocate memory");
const AVStream * oldStream = m_originalVideoFile->stream();
// we copy some fields but leave other as they were initialized by
// av_new_stream() above. this way we're sure that no pointers to
// malloced memory get copied and later freed twice.
m_videoStream->r_frame_rate = oldStream->r_frame_rate;
m_videoStream->first_dts = oldStream->first_dts;
m_videoStream->pts = oldStream->pts;
m_videoStream->time_base = oldStream->time_base;
m_videoStream->pts_wrap_bits = oldStream->pts_wrap_bits;
m_videoStream->discard = oldStream->discard;
m_videoStream->quality = oldStream->quality;
m_videoStream->start_time = oldStream->start_time;
m_videoStream->duration = oldStream->duration;
m_videoStream->nb_frames = oldStream->nb_frames;
m_videoStream->disposition = oldStream->disposition;
m_videoStream->sample_aspect_ratio = oldStream->sample_aspect_ratio;
m_videoStream->avg_frame_rate = oldStream->avg_frame_rate;
// we're not sure this makes any difference but just to be nice
m_videoStream->stream_copy = 1;
// copy codec from input file
m_videoStream->codec = avcodec_alloc_context();
TRY_ASSERT_X(m_videoStream->codec, "Could not allocate memory");
avcodec_copy_context(m_videoStream->codec, m_originalVideoFile->codec());
// can't copy mjpeg without this
m_videoStream->codec->strict_std_compliance = FF_COMPLIANCE_UNOFFICIAL;
m_videoStream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
// otherwise we crash on non-square pixels (first world trouble)
m_videoStream->codec->sample_aspect_ratio = m_videoStream->sample_aspect_ratio;
}
<commit_msg>export: force PCM S16le audio<commit_after>#include "Exporter.h"
#include "VideoFile.h"
#include "SoundBuffer.h"
#include "Common.h"
#include <QtGui>
#include <QtDebug>
using namespace WTS;
class AssertFailed {
public:
AssertFailed(const QString& cond, const QString& file, int line,
QString extra = QString())
{
m_message = QString("%1:%2: assertion '%3' failed")
.arg(file).arg(line).arg(cond);
if (extra.size())
m_message += ". " + extra + ".";
}
QString message() const { return m_message; }
const char * cMessage() const { return m_message.toLocal8Bit().constData(); }
protected:
QString m_message;
};
#define TRY_ASSERT(cond) \
do { if (!cond) { throw AssertFailed(#cond, __FILE__, __LINE__); } } while (0)
#define TRY_ASSERT_X(cond, message) \
do { if (!cond) { throw AssertFailed(#cond, __FILE__, __LINE__, message); \
} } while (0)
Exporter::Exporter(QObject *parent)
: QObject(parent)
, m_originalVideoFile(0)
, m_audio(0)
, m_container(0)
, m_videoStream(0)
, m_audioStream(0)
{
}
void Exporter::configure(const QString& fname,
VideoFile * vfile,
const QList<WtsAudio::BufferAt *>& sequence,
WtsAudio * audio,
QProgressDialog * progress)
{
m_filename = fname.toLocal8Bit();
m_originalVideoFile = vfile;
m_sequence = sequence;
m_audio = audio;
m_progress = progress;
}
void Exporter::initExport()
{
AVOutputFormat * format = av_guess_format(NULL, m_filename.constData(), NULL);
if (!format) {
qWarning() << "Could not deduce output format from file extension: using "
<< VIDEO_FormatTitle;
format = av_guess_format(VIDEO_FMT, NULL, NULL);
}
TRY_ASSERT_X(format, "Could not find suitable output format");
m_container = avformat_alloc_context();
TRY_ASSERT_X(m_container, "Memory error in ffmpeg");
m_container->oformat = format;
// apparently this is the normal ffmpeg way to set the filename
snprintf(m_container->filename,
sizeof(m_container->filename),
"%s",
m_filename.constData());
initAudioStream(CODEC_ID_PCM_S16LE);
initVideoStream();
// set the output parameters (must be done even if no parameters)
TRY_ASSERT_X((av_set_parameters(m_container, NULL) >= 0),
"Invalid output format parameters");
av_dump_format(m_container, 0, m_filename.constData(), 1);
AVCodec * audioCodec = avcodec_find_encoder(m_audioStream->codec->codec_id);
TRY_ASSERT_X(audioCodec, "Could not find audio encoder");
TRY_ASSERT_X((avcodec_open(m_audioStream->codec, audioCodec) >= 0),
"Could not open audio encoder");
AVCodec * videoCodec = avcodec_find_encoder(m_videoStream->codec->codec_id);
TRY_ASSERT_X(videoCodec, "Video codec not found");
TRY_ASSERT_X((avcodec_open(m_videoStream->codec, videoCodec) >= 0),
"Could not open video codec");
TRY_ASSERT_X( ( avio_open(&m_container->pb,
m_filename.constData(),
URL_WRONLY) >= 0 ),
QString("Could not open " + m_filename));
}
void Exporter::performExport()
{
QVector<uint8_t> m_encodedAudio(10000);
// this is copied from ffmpeg's output-example
// original comment states that it's an "ugly hack for PCM codecs"
int mixBufferSize = m_audioStream->codec->frame_size;
if (m_audioStream->codec->frame_size <= 1) {
mixBufferSize = m_encodedAudio.size() / m_audioStream->codec->channels;
switch(m_audioStream->codec->codec_id) {
case CODEC_ID_PCM_S16LE:
case CODEC_ID_PCM_S16BE:
case CODEC_ID_PCM_U16LE:
case CODEC_ID_PCM_U16BE:
mixBufferSize >>= 1;
break;
default:
break;
}
}
QVector<int16_t> m_mixBuffer(mixBufferSize * m_audioStream->codec->channels);
av_write_header(m_container);
m_originalVideoFile->seek(0);
m_audio->samplerClear();
qSort(m_sequence.begin(), m_sequence.end(), WtsAudio::startsBefore);
QList<WtsAudio::BufferAt *>::iterator sequenceCursor = m_sequence.begin();
double duration = (double)m_videoStream->duration
* m_videoStream->time_base.num
/ m_videoStream->time_base.den;
bool moreVideo = true, moreAudio = true;
while(moreVideo || moreAudio) {
double audio_pts = (double)m_audioStream->pts.val
* m_audioStream->time_base.num
/ m_audioStream->time_base.den;
double video_pts = (double)m_videoStream->pts.val
* m_videoStream->time_base.num
/ m_videoStream->time_base.den;
moreAudio = audio_pts < duration;
double pts;
AVPacket packet;
if ( moreVideo
&& (!moreAudio || (video_pts < audio_pts))
&& (moreVideo = m_originalVideoFile->nextPacket(packet)) ) {
packet.stream_index = m_videoStream->index;
av_interleaved_write_frame(m_container, &packet);
pts = video_pts;
} else if (moreAudio) {
av_init_packet(&packet);
qint64 ms = (qint64)(audio_pts * 1000.0);
while( sequenceCursor != m_sequence.end()
&& ((*sequenceCursor)->at()
+ WtsAudio::sampleCountToMs((*sequenceCursor)->buffer()->rangeStart())) <= ms ) {
m_audio->samplerSchedule(*sequenceCursor);
sequenceCursor++;
}
m_audio->samplerMix( ms, m_mixBuffer);
packet.size = avcodec_encode_audio(m_audioStream->codec,
m_encodedAudio.data(),
m_encodedAudio.size(),
m_mixBuffer.data());
if (m_audioStream->codec->coded_frame
&& ( (uint64_t) m_audioStream->codec->coded_frame->pts
!= AV_NOPTS_VALUE) )
packet.pts= av_rescale_q(m_audioStream->codec->coded_frame->pts,
m_audioStream->codec->time_base,
m_audioStream->time_base);
packet.flags |= AV_PKT_FLAG_KEY;
packet.stream_index= m_audioStream->index;
packet.data= m_encodedAudio.data();
av_interleaved_write_frame(m_container, &packet);
pts = audio_pts;
}
m_progress->setValue(100 * pts / duration);
}
av_write_trailer(m_container);
}
void Exporter::run()
{
try {
m_progress->setValue(0);
initExport();
performExport();
finishUp();
m_progress->setValue(100);
QProcess process;
process.startDetached("open", QStringList() << QFileInfo(m_filename).dir().path() );
} catch (const AssertFailed& e) {
qCritical() << e.cMessage();
m_progress->cancel();
QMessageBox dialog(m_progress->parentWidget());
dialog.setText("Fout in exporter");
dialog.setInformativeText("Iets ging verkeerd tijdens het opslaan van " + m_filename);
dialog.setDetailedText(e.message());
dialog.setIcon(QMessageBox::Critical);
dialog.setWindowModality(Qt::WindowModal);
dialog.setModal(true);
dialog.exec();
}
}
void Exporter::finishUp()
{
avcodec_close(m_videoStream->codec);
avcodec_close(m_audioStream->codec);
/* free the resources */
for(unsigned i = 0; i < m_container->nb_streams; i++) {
av_freep(&m_container->streams[i]->codec);
av_freep(&m_container->streams[i]);
}
avio_close(m_container->pb);
av_free(m_container);
}
void Exporter::initAudioStream(CodecID codec_id)
{
m_audioStream = av_new_stream(m_container, 1);
TRY_ASSERT_X(m_audioStream, "Could not alloc stream");
AVCodecContext * codecContext = m_audioStream->codec;
codecContext->codec_id = codec_id;
codecContext->codec_type = AVMEDIA_TYPE_AUDIO;
/* put sample parameters */
codecContext->sample_fmt = AV_SAMPLE_FMT_S16;
codecContext->bit_rate = 64000;
codecContext->sample_rate = 44100;
codecContext->channels = 1;
// some formats want stream headers to be separate
if(m_container->oformat->flags & AVFMT_GLOBALHEADER)
codecContext->flags |= CODEC_FLAG_GLOBAL_HEADER;
}
void Exporter::initVideoStream()
{
// Video output stream is pretty much a copy of the input video
m_videoStream = av_new_stream(m_container, 0);
TRY_ASSERT_X(m_videoStream, "Could not allocate memory");
const AVStream * oldStream = m_originalVideoFile->stream();
// we copy some fields but leave other as they were initialized by
// av_new_stream() above. this way we're sure that no pointers to
// malloced memory get copied and later freed twice.
m_videoStream->r_frame_rate = oldStream->r_frame_rate;
m_videoStream->first_dts = oldStream->first_dts;
m_videoStream->pts = oldStream->pts;
m_videoStream->time_base = oldStream->time_base;
m_videoStream->pts_wrap_bits = oldStream->pts_wrap_bits;
m_videoStream->discard = oldStream->discard;
m_videoStream->quality = oldStream->quality;
m_videoStream->start_time = oldStream->start_time;
m_videoStream->duration = oldStream->duration;
m_videoStream->nb_frames = oldStream->nb_frames;
m_videoStream->disposition = oldStream->disposition;
m_videoStream->sample_aspect_ratio = oldStream->sample_aspect_ratio;
m_videoStream->avg_frame_rate = oldStream->avg_frame_rate;
// we're not sure this makes any difference but just to be nice
m_videoStream->stream_copy = 1;
// copy codec from input file
m_videoStream->codec = avcodec_alloc_context();
TRY_ASSERT_X(m_videoStream->codec, "Could not allocate memory");
avcodec_copy_context(m_videoStream->codec, m_originalVideoFile->codec());
// can't copy mjpeg without this
m_videoStream->codec->strict_std_compliance = FF_COMPLIANCE_UNOFFICIAL;
m_videoStream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
// otherwise we crash on non-square pixels (first world trouble)
m_videoStream->codec->sample_aspect_ratio = m_videoStream->sample_aspect_ratio;
}
<|endoftext|>
|
<commit_before>//===- MultiJITTest.cpp - Unit tests for instantiating multiple JITs ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/ExecutionEngine/JIT.h"
#include "llvm/Support/SourceMgr.h"
#include <vector>
using namespace llvm;
namespace {
bool LoadAssemblyInto(Module *M, const char *assembly) {
SMDiagnostic Error;
bool success =
NULL != ParseAssemblyString(assembly, M, Error, M->getContext());
std::string errMsg;
raw_string_ostream os(errMsg);
Error.print("", os);
EXPECT_TRUE(success) << os.str();
return success;
}
void createModule1(LLVMContext &Context1, Module *&M1, Function *&FooF1) {
M1 = new Module("test1", Context1);
LoadAssemblyInto(M1,
"define i32 @add1(i32 %ArgX1) { "
"entry: "
" %addresult = add i32 1, %ArgX1 "
" ret i32 %addresult "
"} "
" "
"define i32 @foo1() { "
"entry: "
" %add1 = call i32 @add1(i32 10) "
" ret i32 %add1 "
"} ");
FooF1 = M1->getFunction("foo1");
}
void createModule2(LLVMContext &Context2, Module *&M2, Function *&FooF2) {
M2 = new Module("test2", Context2);
LoadAssemblyInto(M2,
"define i32 @add2(i32 %ArgX2) { "
"entry: "
" %addresult = add i32 2, %ArgX2 "
" ret i32 %addresult "
"} "
" "
"define i32 @foo2() { "
"entry: "
" %add2 = call i32 @add2(i32 10) "
" ret i32 %add2 "
"} ");
FooF2 = M2->getFunction("foo2");
}
// ARM tests disabled pending fix for PR10783.
#if !defined(__arm__)
TEST(MultiJitTest, EagerMode) {
LLVMContext Context1;
Module *M1 = 0;
Function *FooF1 = 0;
createModule1(Context1, M1, FooF1);
LLVMContext Context2;
Module *M2 = 0;
Function *FooF2 = 0;
createModule2(Context2, M2, FooF2);
// Now we create the JIT in eager mode
OwningPtr<ExecutionEngine> EE1(EngineBuilder(M1).create());
EE1->DisableLazyCompilation(true);
OwningPtr<ExecutionEngine> EE2(EngineBuilder(M2).create());
EE2->DisableLazyCompilation(true);
// Call the `foo' function with no arguments:
std::vector<GenericValue> noargs;
GenericValue gv1 = EE1->runFunction(FooF1, noargs);
GenericValue gv2 = EE2->runFunction(FooF2, noargs);
// Import result of execution:
EXPECT_EQ(gv1.IntVal, 11);
EXPECT_EQ(gv2.IntVal, 12);
EE1->freeMachineCodeForFunction(FooF1);
EE2->freeMachineCodeForFunction(FooF2);
}
TEST(MultiJitTest, LazyMode) {
LLVMContext Context1;
Module *M1 = 0;
Function *FooF1 = 0;
createModule1(Context1, M1, FooF1);
LLVMContext Context2;
Module *M2 = 0;
Function *FooF2 = 0;
createModule2(Context2, M2, FooF2);
// Now we create the JIT in lazy mode
OwningPtr<ExecutionEngine> EE1(EngineBuilder(M1).create());
EE1->DisableLazyCompilation(false);
OwningPtr<ExecutionEngine> EE2(EngineBuilder(M2).create());
EE2->DisableLazyCompilation(false);
// Call the `foo' function with no arguments:
std::vector<GenericValue> noargs;
GenericValue gv1 = EE1->runFunction(FooF1, noargs);
GenericValue gv2 = EE2->runFunction(FooF2, noargs);
// Import result of execution:
EXPECT_EQ(gv1.IntVal, 11);
EXPECT_EQ(gv2.IntVal, 12);
EE1->freeMachineCodeForFunction(FooF1);
EE2->freeMachineCodeForFunction(FooF2);
}
extern "C" {
extern void *getPointerToNamedFunction(const char *Name);
}
TEST(MultiJitTest, JitPool) {
LLVMContext Context1;
Module *M1 = 0;
Function *FooF1 = 0;
createModule1(Context1, M1, FooF1);
LLVMContext Context2;
Module *M2 = 0;
Function *FooF2 = 0;
createModule2(Context2, M2, FooF2);
// Now we create two JITs
OwningPtr<ExecutionEngine> EE1(EngineBuilder(M1).create());
OwningPtr<ExecutionEngine> EE2(EngineBuilder(M2).create());
Function *F1 = EE1->FindFunctionNamed("foo1");
void *foo1 = EE1->getPointerToFunction(F1);
Function *F2 = EE2->FindFunctionNamed("foo2");
void *foo2 = EE2->getPointerToFunction(F2);
// Function in M1
EXPECT_EQ(getPointerToNamedFunction("foo1"), foo1);
// Function in M2
EXPECT_EQ(getPointerToNamedFunction("foo2"), foo2);
// Symbol search
EXPECT_EQ((intptr_t)getPointerToNamedFunction("getPointerToNamedFunction"),
(intptr_t)&getPointerToNamedFunction);
}
#endif // !defined(__arm__)
} // anonymous namespace
<commit_msg>unittests/MultiJITTest.cpp: Tweak how to check symbol value for Win32 --enable-shared.<commit_after>//===- MultiJITTest.cpp - Unit tests for instantiating multiple JITs ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/ExecutionEngine/JIT.h"
#include "llvm/Support/SourceMgr.h"
#include <vector>
using namespace llvm;
namespace {
bool LoadAssemblyInto(Module *M, const char *assembly) {
SMDiagnostic Error;
bool success =
NULL != ParseAssemblyString(assembly, M, Error, M->getContext());
std::string errMsg;
raw_string_ostream os(errMsg);
Error.print("", os);
EXPECT_TRUE(success) << os.str();
return success;
}
void createModule1(LLVMContext &Context1, Module *&M1, Function *&FooF1) {
M1 = new Module("test1", Context1);
LoadAssemblyInto(M1,
"define i32 @add1(i32 %ArgX1) { "
"entry: "
" %addresult = add i32 1, %ArgX1 "
" ret i32 %addresult "
"} "
" "
"define i32 @foo1() { "
"entry: "
" %add1 = call i32 @add1(i32 10) "
" ret i32 %add1 "
"} ");
FooF1 = M1->getFunction("foo1");
}
void createModule2(LLVMContext &Context2, Module *&M2, Function *&FooF2) {
M2 = new Module("test2", Context2);
LoadAssemblyInto(M2,
"define i32 @add2(i32 %ArgX2) { "
"entry: "
" %addresult = add i32 2, %ArgX2 "
" ret i32 %addresult "
"} "
" "
"define i32 @foo2() { "
"entry: "
" %add2 = call i32 @add2(i32 10) "
" ret i32 %add2 "
"} ");
FooF2 = M2->getFunction("foo2");
}
// ARM tests disabled pending fix for PR10783.
#if !defined(__arm__)
TEST(MultiJitTest, EagerMode) {
LLVMContext Context1;
Module *M1 = 0;
Function *FooF1 = 0;
createModule1(Context1, M1, FooF1);
LLVMContext Context2;
Module *M2 = 0;
Function *FooF2 = 0;
createModule2(Context2, M2, FooF2);
// Now we create the JIT in eager mode
OwningPtr<ExecutionEngine> EE1(EngineBuilder(M1).create());
EE1->DisableLazyCompilation(true);
OwningPtr<ExecutionEngine> EE2(EngineBuilder(M2).create());
EE2->DisableLazyCompilation(true);
// Call the `foo' function with no arguments:
std::vector<GenericValue> noargs;
GenericValue gv1 = EE1->runFunction(FooF1, noargs);
GenericValue gv2 = EE2->runFunction(FooF2, noargs);
// Import result of execution:
EXPECT_EQ(gv1.IntVal, 11);
EXPECT_EQ(gv2.IntVal, 12);
EE1->freeMachineCodeForFunction(FooF1);
EE2->freeMachineCodeForFunction(FooF2);
}
TEST(MultiJitTest, LazyMode) {
LLVMContext Context1;
Module *M1 = 0;
Function *FooF1 = 0;
createModule1(Context1, M1, FooF1);
LLVMContext Context2;
Module *M2 = 0;
Function *FooF2 = 0;
createModule2(Context2, M2, FooF2);
// Now we create the JIT in lazy mode
OwningPtr<ExecutionEngine> EE1(EngineBuilder(M1).create());
EE1->DisableLazyCompilation(false);
OwningPtr<ExecutionEngine> EE2(EngineBuilder(M2).create());
EE2->DisableLazyCompilation(false);
// Call the `foo' function with no arguments:
std::vector<GenericValue> noargs;
GenericValue gv1 = EE1->runFunction(FooF1, noargs);
GenericValue gv2 = EE2->runFunction(FooF2, noargs);
// Import result of execution:
EXPECT_EQ(gv1.IntVal, 11);
EXPECT_EQ(gv2.IntVal, 12);
EE1->freeMachineCodeForFunction(FooF1);
EE2->freeMachineCodeForFunction(FooF2);
}
extern "C" {
extern void *getPointerToNamedFunction(const char *Name);
}
TEST(MultiJitTest, JitPool) {
LLVMContext Context1;
Module *M1 = 0;
Function *FooF1 = 0;
createModule1(Context1, M1, FooF1);
LLVMContext Context2;
Module *M2 = 0;
Function *FooF2 = 0;
createModule2(Context2, M2, FooF2);
// Now we create two JITs
OwningPtr<ExecutionEngine> EE1(EngineBuilder(M1).create());
OwningPtr<ExecutionEngine> EE2(EngineBuilder(M2).create());
Function *F1 = EE1->FindFunctionNamed("foo1");
void *foo1 = EE1->getPointerToFunction(F1);
Function *F2 = EE2->FindFunctionNamed("foo2");
void *foo2 = EE2->getPointerToFunction(F2);
// Function in M1
EXPECT_EQ(getPointerToNamedFunction("foo1"), foo1);
// Function in M2
EXPECT_EQ(getPointerToNamedFunction("foo2"), foo2);
// Symbol search
intptr_t
sa = (intptr_t)getPointerToNamedFunction("getPointerToNamedFunction");
EXPECT_TRUE(sa != 0);
intptr_t fa = (intptr_t)&getPointerToNamedFunction;
EXPECT_TRUE(fa != 0);
#ifdef __i386__
// getPointerToNamedFunction might be indirect jump on Win32 --enable-shared.
// FF 25 <disp32>: jmp *(pointer to IAT)
if (sa != fa && memcmp((char *)fa, "\xFF\x25", 2) == 0) {
fa = *(intptr_t *)(fa + 2); // Address to IAT
EXPECT_TRUE(fa != 0);
fa = *(intptr_t *)fa; // Bound value of IAT
}
#endif
EXPECT_TRUE(sa == fa);
}
#endif // !defined(__arm__)
} // anonymous namespace
<|endoftext|>
|
<commit_before>#include "can/canread.h"
#include "can/canwrite.h"
#include "signals.h"
#include "util/log.h"
#include "config.h"
#include "shared_handlers.h"
namespace can = openxc::can;
using openxc::util::log::debug;
using openxc::pipeline::Pipeline;
using openxc::config::getConfiguration;
using openxc::can::read::booleanHandler;
using openxc::can::read::stateHandler;
using openxc::can::read::ignoreHandler;
using openxc::can::write::booleanWriter;
using openxc::can::write::stateWriter;
using openxc::can::write::numberWriter;
using namespace openxc::signals::handlers;
const int MESSAGE_SET_COUNT = 2;
CanMessageSet MESSAGE_SETS[MESSAGE_SET_COUNT] = {
{ 0, "tests", 2, 4, 7, 1 },
{ 1, "shared_handler_tests", 2, 4, 13, 0 },
};
const int MAX_CAN_BUS_COUNT = 2;
CanBus CAN_BUSES[][MAX_CAN_BUS_COUNT] = {
{ // message set: passthrough
{ 500000, 1, NULL, 1, false
},
{ 125000, 2, NULL, 1, false
},
},
};
const int MAX_MESSAGE_COUNT = 4;
CanMessageDefinition CAN_MESSAGES[][MAX_MESSAGE_COUNT] = {
{ // message set: passthrough
{&CAN_BUSES[0][0], 0},
{&CAN_BUSES[0][0], 1, {10}},
{&CAN_BUSES[0][0], 2, {1}, true},
{&CAN_BUSES[0][0], 3}
},
{ // message set: shared_handler_tests
{&CAN_BUSES[1][0], 0},
{&CAN_BUSES[1][0], 1},
{&CAN_BUSES[1][0], 2},
{&CAN_BUSES[1][0], 3}
},
};
const int MAX_SIGNAL_STATES = 12;
const int MAX_SIGNAL_COUNT = 13;
const CanSignalState SIGNAL_STATES[][MAX_SIGNAL_COUNT][MAX_SIGNAL_STATES] = {
{ // message set: passthrough
{ {1, "reverse"}, {2, "third"}, {3, "sixth"}, {4, "seventh"},
{5, "neutral"}, {6, "second"}, },
},
{ // message set: shared_handler_tests
{ {1, "right"}, {2, "down"}, {3, "left"}, {4, "ok"}, {5, "up"}, {6, "foo"}},
{ {1, "idle"}, {2, "stuck"}, {3, "held_short"}, {4, "pressed"},
{5, "held_long"}, {6, "released"}, },
},
};
CanSignal SIGNALS[][MAX_SIGNAL_COUNT] = {
{ // message set: passthrough
{&CAN_MESSAGES[0][0], "torque_at_transmission", 2, 4, 1001.0, -30000.000000,
-5000.000000, 33522.000000, {0}, false, false, NULL, 0, true},
{&CAN_MESSAGES[0][1], "transmission_gear_position", 1, 3, 1.000000, 0.000000,
0.000000, 0.000000, {0}, false, false, SIGNAL_STATES[0][0], 6, true, NULL,
false, 4.0},
{&CAN_MESSAGES[0][2], "brake_pedal_status", 0, 1, 1.000000, 0.000000, 0.000000,
0.000000, {0}, true, false, NULL, 0, true},
{&CAN_MESSAGES[0][3], "measurement", 2, 19, 0.001000, 0.000000, 0, 500.0,
{0}, false, false, SIGNAL_STATES[0][0], 6, true, NULL, 4.0},
{&CAN_MESSAGES[0][2], "command", 0, 1, 1.000000, 0.000000, 0.000000, 0.000000},
{&CAN_MESSAGES[0][2], "command", 0, 1, 1.000000, 0.000000, 0.000000, 0.000000, {0},
false, false, NULL, 0, true},
{&CAN_MESSAGES[0][0], "torque_at_transmission", 2, 6, 1001.0, -30000.000000,
-5000.000000, 33522.000000, {0}, false, false, NULL, 0, true},
},
{ // message set: shared_handler_tests
{&CAN_MESSAGES[1][0], "button_type", 8, 8, 1.000000, 0.000000, 0.000000,
0.000000, {0}, true, false, SIGNAL_STATES[1][0], 5, false, NULL},
{&CAN_MESSAGES[1][0], "button_state", 20, 4, 1.000000, 0.000000, 0.000000,
0.000000, {0}, true, false, SIGNAL_STATES[1][1], 6, false, NULL},
{&CAN_MESSAGES[1][1], "driver_door", 15, 1, 1.000000, 0.000000, 0.000000,
0.000000},
{&CAN_MESSAGES[1][1], "passenger_door", 16, 1, 1.000000, 0.000000, 0.000000,
0.000000},
{&CAN_MESSAGES[1][1], "rear_left_door", 17, 1, 1.000000, 0.000000, 0.000000,
0.000000},
{&CAN_MESSAGES[1][1], "rear_right_door", 18, 1, 1.000000, 0.000000, 0.000000,
0.000000},
{&CAN_MESSAGES[1][1], "fuel_consumed_since_restart", 18, 1, 25.000000, 0.000000,
0.000000, 255.0},
{&CAN_MESSAGES[1][2], "tire_pressure_front_left", 15, 1, 1.000000, 0.000000,
0.000000, 0.000000},
{&CAN_MESSAGES[1][2], "tire_pressure_front_right", 16, 1, 1.000000, 0.000000,
0.000000, 0.000000},
{&CAN_MESSAGES[1][2], "tire_pressure_rear_right", 17, 1, 1.000000, 0.000000,
0.000000, 0.000000},
{&CAN_MESSAGES[1][2], "tire_pressure_rear_left", 18, 1, 1.000000, 0.000000,
0.000000, 0.000000},
{&CAN_MESSAGES[1][3], "passenger_occupancy_lower", 17, 1, 1.000000, 0.000000,
0.000000, 0.000000},
{&CAN_MESSAGES[1][3], "passenger_occupancy_upper", 18, 1, 1.000000, 0.000000,
0.000000, 0.000000},
}
};
void openxc::signals::initialize() {
switch(getConfiguration()->messageSetIndex) {
case 0: // message set: passthrough
break;
}
}
void openxc::signals::loop() {
switch(getConfiguration()->messageSetIndex) {
case 0: // message set: passthrough
break;
}
}
const int MAX_COMMAND_COUNT = 1;
CanCommand COMMANDS[][MAX_COMMAND_COUNT] = {
{ // message set: passthrough
{"turn_signal_status", NULL},
},
};
void openxc::signals::decodeCanMessage(Pipeline* pipeline, CanBus* bus, CanMessage* message) {
switch(getConfiguration()->messageSetIndex) {
case 0: // message set: passthrough
switch(bus->address) {
case 1:
switch (message->id) {
}
openxc::can::read::passthroughMessage(bus, message, getMessages(), getMessageCount(), pipeline);
break;
case 2:
switch (message->id) {
}
openxc::can::read::passthroughMessage(bus, message, getMessages(), getMessageCount(), pipeline);
break;
}
break;
}
}
CanCommand* openxc::signals::getCommands() {
return COMMANDS[getActiveMessageSet()->index];
}
int openxc::signals::getCommandCount() {
return getActiveMessageSet()->commandCount;
}
CanMessageDefinition* openxc::signals::getMessages() {
return CAN_MESSAGES[getActiveMessageSet()->index];
}
int openxc::signals::getMessageCount() {
return getActiveMessageSet()->messageCount;
}
CanSignal* openxc::signals::getSignals() {
return SIGNALS[getActiveMessageSet()->index];
}
int openxc::signals::getSignalCount() {
return getActiveMessageSet()->signalCount;
}
CanBus* openxc::signals::getCanBuses() {
return CAN_BUSES[getActiveMessageSet()->index];
}
int openxc::signals::getCanBusCount() {
return getActiveMessageSet()->busCount;
}
CanMessageSet* openxc::signals::getActiveMessageSet() {
return &MESSAGE_SETS[getConfiguration()->messageSetIndex];
}
CanMessageSet* openxc::signals::getMessageSets() {
return MESSAGE_SETS;
}
int openxc::signals::getMessageSetCount() {
return MESSAGE_SET_COUNT;
}
<commit_msg>Update test shim for signals.cpp to latest function types.<commit_after>#include "can/canread.h"
#include "can/canwrite.h"
#include "signals.h"
#include "util/log.h"
#include "config.h"
#include "shared_handlers.h"
namespace can = openxc::can;
#include "diagnostics.h"
using openxc::util::log::debug;
using openxc::pipeline::Pipeline;
using openxc::config::getConfiguration;
using openxc::can::read::booleanHandler;
using openxc::can::read::stateHandler;
using openxc::can::read::ignoreHandler;
using openxc::can::write::booleanWriter;
using openxc::can::write::stateWriter;
using openxc::can::write::numberWriter;
using openxc::diagnostics::DiagnosticsManager;
using namespace openxc::signals::handlers;
const int MESSAGE_SET_COUNT = 2;
CanMessageSet MESSAGE_SETS[MESSAGE_SET_COUNT] = {
{ 0, "tests", 2, 4, 7, 1 },
{ 1, "shared_handler_tests", 2, 4, 13, 0 },
};
const int MAX_CAN_BUS_COUNT = 2;
CanBus CAN_BUSES[][MAX_CAN_BUS_COUNT] = {
{ // message set: passthrough
{ 500000, 1, NULL, 1, false
},
{ 125000, 2, NULL, 1, false
},
},
};
const int MAX_MESSAGE_COUNT = 4;
CanMessageDefinition CAN_MESSAGES[][MAX_MESSAGE_COUNT] = {
{ // message set: passthrough
{&CAN_BUSES[0][0], 0},
{&CAN_BUSES[0][0], 1, {10}},
{&CAN_BUSES[0][0], 2, {1}, true},
{&CAN_BUSES[0][0], 3}
},
{ // message set: shared_handler_tests
{&CAN_BUSES[1][0], 0},
{&CAN_BUSES[1][0], 1},
{&CAN_BUSES[1][0], 2},
{&CAN_BUSES[1][0], 3}
},
};
const int MAX_SIGNAL_STATES = 12;
const int MAX_SIGNAL_COUNT = 13;
const CanSignalState SIGNAL_STATES[][MAX_SIGNAL_COUNT][MAX_SIGNAL_STATES] = {
{ // message set: passthrough
{ {1, "reverse"}, {2, "third"}, {3, "sixth"}, {4, "seventh"},
{5, "neutral"}, {6, "second"}, },
},
{ // message set: shared_handler_tests
{ {1, "right"}, {2, "down"}, {3, "left"}, {4, "ok"}, {5, "up"}, {6, "foo"}},
{ {1, "idle"}, {2, "stuck"}, {3, "held_short"}, {4, "pressed"},
{5, "held_long"}, {6, "released"}, },
},
};
CanSignal SIGNALS[][MAX_SIGNAL_COUNT] = {
{ // message set: passthrough
{&CAN_MESSAGES[0][0], "torque_at_transmission", 2, 4, 1001.0, -30000.000000,
-5000.000000, 33522.000000, {0}, false, false, NULL, 0, true},
{&CAN_MESSAGES[0][1], "transmission_gear_position", 1, 3, 1.000000, 0.000000,
0.000000, 0.000000, {0}, false, false, SIGNAL_STATES[0][0], 6, true, NULL,
false, 4.0},
{&CAN_MESSAGES[0][2], "brake_pedal_status", 0, 1, 1.000000, 0.000000, 0.000000,
0.000000, {0}, true, false, NULL, 0, true},
{&CAN_MESSAGES[0][3], "measurement", 2, 19, 0.001000, 0.000000, 0, 500.0,
{0}, false, false, SIGNAL_STATES[0][0], 6, true, NULL, 4.0},
{&CAN_MESSAGES[0][2], "command", 0, 1, 1.000000, 0.000000, 0.000000, 0.000000},
{&CAN_MESSAGES[0][2], "command", 0, 1, 1.000000, 0.000000, 0.000000, 0.000000, {0},
false, false, NULL, 0, true},
{&CAN_MESSAGES[0][0], "torque_at_transmission", 2, 6, 1001.0, -30000.000000,
-5000.000000, 33522.000000, {0}, false, false, NULL, 0, true},
},
{ // message set: shared_handler_tests
{&CAN_MESSAGES[1][0], "button_type", 8, 8, 1.000000, 0.000000, 0.000000,
0.000000, {0}, true, false, SIGNAL_STATES[1][0], 5, false, NULL},
{&CAN_MESSAGES[1][0], "button_state", 20, 4, 1.000000, 0.000000, 0.000000,
0.000000, {0}, true, false, SIGNAL_STATES[1][1], 6, false, NULL},
{&CAN_MESSAGES[1][1], "driver_door", 15, 1, 1.000000, 0.000000, 0.000000,
0.000000},
{&CAN_MESSAGES[1][1], "passenger_door", 16, 1, 1.000000, 0.000000, 0.000000,
0.000000},
{&CAN_MESSAGES[1][1], "rear_left_door", 17, 1, 1.000000, 0.000000, 0.000000,
0.000000},
{&CAN_MESSAGES[1][1], "rear_right_door", 18, 1, 1.000000, 0.000000, 0.000000,
0.000000},
{&CAN_MESSAGES[1][1], "fuel_consumed_since_restart", 18, 1, 25.000000, 0.000000,
0.000000, 255.0},
{&CAN_MESSAGES[1][2], "tire_pressure_front_left", 15, 1, 1.000000, 0.000000,
0.000000, 0.000000},
{&CAN_MESSAGES[1][2], "tire_pressure_front_right", 16, 1, 1.000000, 0.000000,
0.000000, 0.000000},
{&CAN_MESSAGES[1][2], "tire_pressure_rear_right", 17, 1, 1.000000, 0.000000,
0.000000, 0.000000},
{&CAN_MESSAGES[1][2], "tire_pressure_rear_left", 18, 1, 1.000000, 0.000000,
0.000000, 0.000000},
{&CAN_MESSAGES[1][3], "passenger_occupancy_lower", 17, 1, 1.000000, 0.000000,
0.000000, 0.000000},
{&CAN_MESSAGES[1][3], "passenger_occupancy_upper", 18, 1, 1.000000, 0.000000,
0.000000, 0.000000},
}
};
void openxc::signals::initialize(DiagnosticsManager* diagnosticsManager) {
switch(getConfiguration()->messageSetIndex) {
case 0: // message set: passthrough
break;
}
}
void openxc::signals::loop() {
switch(getConfiguration()->messageSetIndex) {
case 0: // message set: passthrough
break;
}
}
const int MAX_COMMAND_COUNT = 1;
CanCommand COMMANDS[][MAX_COMMAND_COUNT] = {
{ // message set: passthrough
{"turn_signal_status", NULL},
},
};
void openxc::signals::decodeCanMessage(Pipeline* pipeline, CanBus* bus, CanMessage* message) {
switch(getConfiguration()->messageSetIndex) {
case 0: // message set: passthrough
switch(bus->address) {
case 1:
switch (message->id) {
}
openxc::can::read::passthroughMessage(bus, message, getMessages(), getMessageCount(), pipeline);
break;
case 2:
switch (message->id) {
}
openxc::can::read::passthroughMessage(bus, message, getMessages(), getMessageCount(), pipeline);
break;
}
break;
}
}
CanCommand* openxc::signals::getCommands() {
return COMMANDS[getActiveMessageSet()->index];
}
int openxc::signals::getCommandCount() {
return getActiveMessageSet()->commandCount;
}
CanMessageDefinition* openxc::signals::getMessages() {
return CAN_MESSAGES[getActiveMessageSet()->index];
}
int openxc::signals::getMessageCount() {
return getActiveMessageSet()->messageCount;
}
CanSignal* openxc::signals::getSignals() {
return SIGNALS[getActiveMessageSet()->index];
}
int openxc::signals::getSignalCount() {
return getActiveMessageSet()->signalCount;
}
CanBus* openxc::signals::getCanBuses() {
return CAN_BUSES[getActiveMessageSet()->index];
}
int openxc::signals::getCanBusCount() {
return getActiveMessageSet()->busCount;
}
CanMessageSet* openxc::signals::getActiveMessageSet() {
return &MESSAGE_SETS[getConfiguration()->messageSetIndex];
}
CanMessageSet* openxc::signals::getMessageSets() {
return MESSAGE_SETS;
}
int openxc::signals::getMessageSetCount() {
return MESSAGE_SET_COUNT;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.
*
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE orca_test
// Third party includes
#include <boost/test/unit_test.hpp>
// VOTCA includes
#include <votca/tools/eigenio_matrixmarket.h>
#include <votca/tools/filesystem.h>
// Local VOTCA includes
#include "votca/xtp/logger.h"
#include "votca/xtp/moldenreader.h"
#include "votca/xtp/orbitals.h"
using namespace votca::xtp;
using namespace votca;
using namespace std;
BOOST_AUTO_TEST_SUITE(moldenreader_test)
BOOST_AUTO_TEST_CASE(moldenreader_test) {
Orbitals orbitalsReference;
orbitalsReference.ReadFromCpt(std::string(XTP_TEST_DATA_FOLDER) +
"/molden/benzene.orb");
Logger log;
MoldenReader molden(log);
molden.setBasissetInfo("def2-tzvp", "aux-def2-tzvp");
Orbitals orbitals;
molden.parseMoldenFile(
std::string(XTP_TEST_DATA_FOLDER) + "/molden/benzene.molden.input",
orbitals);
BOOST_CHECK(orbitalsReference.MOs().eigenvectors().isApprox(
orbitals.MOs().eigenvectors(), 1e-5));
}
}<commit_msg>added atoms to reader test<commit_after>/*
* Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.
*
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE orca_test
// Third party includes
#include <boost/test/unit_test.hpp>
// VOTCA includes
#include <votca/tools/eigenio_matrixmarket.h>
#include <votca/tools/filesystem.h>
// Local VOTCA includes
#include "votca/xtp/logger.h"
#include "votca/xtp/moldenreader.h"
#include "votca/xtp/orbitals.h"
using namespace votca::xtp;
using namespace votca;
using namespace std;
BOOST_AUTO_TEST_SUITE(moldenreader_test)
BOOST_AUTO_TEST_CASE(moldenreader_test) {
Orbitals orbitalsReference;
orbitalsReference.ReadFromCpt(std::string(XTP_TEST_DATA_FOLDER) +
"/molden/benzene.orb");
Logger log;
MoldenReader molden(log);
molden.setBasissetInfo("def2-tzvp", "aux-def2-tzvp");
Orbitals orbitals;
molden.parseMoldenFile(
std::string(XTP_TEST_DATA_FOLDER) + "/molden/benzene.molden.input",
orbitals);
BOOST_CHECK(orbitalsReference.MOs().eigenvectors().isApprox(
orbitals.MOs().eigenvectors(), 1e-5));
BOOST_CHECK(orbitals.QMAtoms().size() == orbitalsReference.QMAtoms().size());
for (int i = 0; i < orbitals.QMAtoms().size(); i++) {
BOOST_CHECK(orbitals.QMAtoms()[i].getPos().isApprox(
orbitalsReference.QMAtoms()[i].getPos(), 1e-3));
}
}
}<|endoftext|>
|
<commit_before>/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Nathan Osman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
**/
#include <QIcon>
#include "transfermodel.h"
int TransferModel::rowCount(const QModelIndex &parent) const
{
return parent.isValid() ? 0 : mTransfers.count();
}
int TransferModel::columnCount(const QModelIndex &parent) const
{
// The model displays device name, transfer progress, and cancel button
return parent.isValid() ? 0 : 3;
}
QVariant TransferModel::data(const QModelIndex &index, int role) const
{
TransferPointer transfer(mTransfers.at(index.row()));
switch(role) {
case Qt::DisplayRole:
switch(index.column()) {
case 0: return transfer->deviceName();
case 1: return transfer->progress();
}
case Qt::DecorationRole:
if(index.column() == 0) {
return QVariant::fromValue(QIcon(":/data/desktop.png"));
}
case Qt::UserRole:
return QVariant::fromValue(transfer);
}
return QVariant();
}
QVariant TransferModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal && role == Qt::DisplayRole) {
switch(section) {
case 0: return tr("Device Name");
case 1: return tr("Percentage");
}
}
return QVariant();
}
void TransferModel::add(TransferPointer transfer)
{
beginInsertRows(QModelIndex(), mTransfers.count(), mTransfers.count());
mTransfers.append(transfer);
endInsertRows();
// Lambdas save us from an awkward dilemma - slots wouldn't have access to
// the TransferPointer, only the Transfer* itself - but the lambdas do!
connect(transfer.data(), &Transfer::statusChanged, [this, transfer]() {
int index = mTransfers.indexOf(transfer);
emit dataChanged(this->index(index, 0), this->index(index, 1));
});
connect(transfer.data(), &Transfer::finished, [this, transfer]() {
int index = mTransfers.indexOf(transfer);
beginRemoveRows(QModelIndex(), index, index);
mTransfers.removeAt(index);
endRemoveRows();
});
transfer->start();
}
<commit_msg>Added display of transfer direction to TransferModel.<commit_after>/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Nathan Osman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
**/
#include <QApplication>
#include <QIcon>
#include <QStyle>
#include "transfermodel.h"
int TransferModel::rowCount(const QModelIndex &parent) const
{
return parent.isValid() ? 0 : mTransfers.count();
}
int TransferModel::columnCount(const QModelIndex &parent) const
{
// The model displays transfer direction / device name, transfer progress, and cancel button
return parent.isValid() ? 0 : 3;
}
QVariant TransferModel::data(const QModelIndex &index, int role) const
{
TransferPointer transfer(mTransfers.at(index.row()));
switch(role) {
case Qt::DisplayRole:
switch(index.column()) {
case 0: return transfer->deviceName();
case 1: return transfer->progress();
}
case Qt::DecorationRole:
if(index.column() == 0) {
switch(transfer->direction()) {
case Transfer::Send:
return QVariant::fromValue(QApplication::style()->standardIcon(QStyle::SP_ArrowUp));
case Transfer::Receive:
return QVariant::fromValue(QApplication::style()->standardIcon(QStyle::SP_ArrowDown));
}
}
case Qt::UserRole:
return QVariant::fromValue(transfer);
}
return QVariant();
}
QVariant TransferModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal && role == Qt::DisplayRole) {
switch(section) {
case 0: return tr("Device Name");
case 1: return tr("Percentage");
}
}
return QVariant();
}
void TransferModel::add(TransferPointer transfer)
{
beginInsertRows(QModelIndex(), mTransfers.count(), mTransfers.count());
mTransfers.append(transfer);
endInsertRows();
// Lambdas save us from an awkward dilemma - slots wouldn't have access to
// the TransferPointer, only the Transfer* itself - but the lambdas do!
connect(transfer.data(), &Transfer::statusChanged, [this, transfer]() {
int index = mTransfers.indexOf(transfer);
emit dataChanged(this->index(index, 0), this->index(index, 1));
});
connect(transfer.data(), &Transfer::finished, [this, transfer]() {
int index = mTransfers.indexOf(transfer);
beginRemoveRows(QModelIndex(), index, index);
mTransfers.removeAt(index);
endRemoveRows();
});
transfer->start();
}
<|endoftext|>
|
<commit_before>
#include "Grabber.h"
#include "tis_logging.h"
using namespace tis_imaging;
Grabber::Grabber ()
: device(nullptr), pipeline(std::make_shared<PipelineManager>())
{}
Grabber::~Grabber ()
{
if (isDeviceOpen())
closeDevice();
}
bool Grabber::openDevice (const CaptureDevice& _device)
{
if (pipeline->getPipelineStatus() == PIPELINE_PLAYING ||
pipeline->getPipelineStatus() == PIPELINE_PAUSED)
{
return false;
}
if (isDeviceOpen())
{
bool ret = closeDevice();
if (ret == false)
{
tis_log(TIS_LOG_ERROR, "Unable to close previous device.");
return false;
}
}
open_device = _device;
device = openDeviceInterface(open_device);
if (device == nullptr)
{
return false;
}
device_properties = device->getProperties();
tis_log(TIS_LOG_DEBUG, "Retrieved %d properties",device_properties.size());
bool ret = pipeline->setSource(device);
if (ret == true)
{
pipeline_properties = pipeline->getFilterProperties();
}
return true;
}
bool Grabber::isDeviceOpen () const
{
if (device != nullptr)
{
return true;
}
return false;
}
CaptureDevice Grabber::getDevice () const
{
return this->open_device;
}
bool Grabber::closeDevice ()
{
std::string name = open_device.getName();
open_device = CaptureDevice ();
device.reset();
device_properties.clear();
tis_log(TIS_LOG_INFO, "Closed device %s.", name.c_str());
return true;
}
std::vector<Property> Grabber::getAvailableProperties ()
{
if (!isDeviceOpen())
{
return std::vector<Property>();
}
std::vector<Property> props;
for (const auto& p : device_properties)
{
props.push_back(*p);
}
for ( const auto& p : pipeline_properties)
{
props.push_back(*p);
}
return props;
}
std::vector<VideoFormatDescription> Grabber::getAvailableVideoFormats () const
{
if (!isDeviceOpen())
{
tis_log(TIS_LOG_ERROR, "No open device");
return std::vector<VideoFormatDescription>();
}
return pipeline->getAvailableVideoFormats();
}
bool Grabber::setVideoFormat (const VideoFormat& _format)
{
if (!isDeviceOpen())
{
tis_log(TIS_LOG_ERROR, "No open device");
return false;
}
return this->device->setVideoFormat(_format);
}
VideoFormat Grabber::getActiveVideoFormat () const
{
if(!isDeviceOpen())
{
tis_log(TIS_LOG_ERROR, "No open device");
return VideoFormat();
}
return device->getActiveVideoFormat();
}
bool Grabber::startStream (std::shared_ptr<ImageSink> sink)
{
if (!isDeviceOpen())
{
tis_log(TIS_LOG_ERROR, "No open device");
return false;
}
pipeline->setSink(sink);
return pipeline->setPipelineStatus(PIPELINE_PLAYING);
}
bool Grabber::stopStream ()
{
if (!isDeviceOpen())
{
tis_log(TIS_LOG_ERROR, "No open device");
return false;
}
return pipeline->setPipelineStatus(PIPELINE_STOPPED);
}
<commit_msg>Destroyed pipeline on closeDevice()<commit_after>
#include "Grabber.h"
#include "tis_logging.h"
using namespace tis_imaging;
Grabber::Grabber ()
: device(nullptr), pipeline(std::make_shared<PipelineManager>())
{}
Grabber::~Grabber ()
{
if (isDeviceOpen())
closeDevice();
}
bool Grabber::openDevice (const CaptureDevice& _device)
{
if (pipeline->getPipelineStatus() == PIPELINE_PLAYING ||
pipeline->getPipelineStatus() == PIPELINE_PAUSED)
{
return false;
}
if (isDeviceOpen())
{
bool ret = closeDevice();
if (ret == false)
{
tis_log(TIS_LOG_ERROR, "Unable to close previous device.");
return false;
}
}
open_device = _device;
device = openDeviceInterface(open_device);
if (device == nullptr)
{
return false;
}
device_properties = device->getProperties();
tis_log(TIS_LOG_DEBUG, "Retrieved %d properties",device_properties.size());
bool ret = pipeline->setSource(device);
if (ret == true)
{
pipeline_properties = pipeline->getFilterProperties();
}
return true;
}
bool Grabber::isDeviceOpen () const
{
if (device != nullptr)
{
return true;
}
return false;
}
CaptureDevice Grabber::getDevice () const
{
return this->open_device;
}
bool Grabber::closeDevice ()
{
std::string name = open_device.getName();
pipeline->destroyPipeline();
open_device = CaptureDevice ();
device.reset();
device_properties.clear();
tis_log(TIS_LOG_INFO, "Closed device %s.", name.c_str());
return true;
}
std::vector<Property> Grabber::getAvailableProperties ()
{
if (!isDeviceOpen())
{
return std::vector<Property>();
}
std::vector<Property> props;
for (const auto& p : device_properties)
{
props.push_back(*p);
}
for ( const auto& p : pipeline_properties)
{
props.push_back(*p);
}
return props;
}
std::vector<VideoFormatDescription> Grabber::getAvailableVideoFormats () const
{
if (!isDeviceOpen())
{
tis_log(TIS_LOG_ERROR, "No open device");
return std::vector<VideoFormatDescription>();
}
return pipeline->getAvailableVideoFormats();
}
bool Grabber::setVideoFormat (const VideoFormat& _format)
{
if (!isDeviceOpen())
{
tis_log(TIS_LOG_ERROR, "No open device");
return false;
}
return this->device->setVideoFormat(_format);
}
VideoFormat Grabber::getActiveVideoFormat () const
{
if(!isDeviceOpen())
{
tis_log(TIS_LOG_ERROR, "No open device");
return VideoFormat();
}
return device->getActiveVideoFormat();
}
bool Grabber::startStream (std::shared_ptr<ImageSink> sink)
{
if (!isDeviceOpen())
{
tis_log(TIS_LOG_ERROR, "No open device");
return false;
}
pipeline->setSink(sink);
return pipeline->setPipelineStatus(PIPELINE_PLAYING);
}
bool Grabber::stopStream ()
{
if (!isDeviceOpen())
{
tis_log(TIS_LOG_ERROR, "No open device");
return false;
}
return pipeline->setPipelineStatus(PIPELINE_STOPPED);
}
<|endoftext|>
|
<commit_before>// csamisc_strictaliasing.cpp -*-C++-*-
#include <clang/AST/ExprCXX.h>
#include <csabase_analyser.h>
#include <csabase_registercheck.h>
#include <csabase_report.h>
#include <string>
using namespace csabase;
using namespace clang;
// ----------------------------------------------------------------------------
static std::string const check_name("strict-alias");
// ----------------------------------------------------------------------------
CanQualType getType(QualType type)
{
return (type->isPointerType() ? type->getPointeeType() : type)
->getCanonicalTypeUnqualified();
}
static void check(Analyser& analyser, CastExpr const *expr)
{
if (expr->getSubExpr()->isNullPointerConstant(
*analyser.context(), Expr::NPC_ValueDependentIsNotNull)) {
return; // RETURN
}
if (expr->getCastKind() != CK_BitCast &&
expr->getCastKind() != CK_LValueBitCast &&
expr->getCastKind() != CK_IntegralToPointer) {
return; // RETURN
}
CanQualType source(getType(expr->getSubExpr()->getType()));
CanQualType target(getType(expr->getType()));
std::string tt = static_cast<QualType>(target).getAsString();
if ((source != target &&
tt != "char" &&
tt != "unsigned char" &&
tt != "signed char" &&
tt != "void") ||
(expr->getType()->isPointerType() !=
expr->getSubExpr()->getType()->isPointerType())) {
analyser.report(expr, check_name, "AL01",
"Possible strict-aliasing violation")
<< expr->getSourceRange();
}
}
// ----------------------------------------------------------------------------
static void checkCCast(Analyser& analyser, CStyleCastExpr const *expr)
{
check(analyser, expr);
}
static void
checkReinterpretCast(Analyser& analyser,
CXXReinterpretCastExpr const *expr)
{
check(analyser, expr);
}
static RegisterCheck register_check0(check_name, checkCCast);
static RegisterCheck register_check1(check_name, checkReinterpretCast);
// ----------------------------------------------------------------------------
// Copyright (C) 2014 Bloomberg Finance L.P.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>Strict aliasing false positive (cast from void *).<commit_after>// csamisc_strictaliasing.cpp -*-C++-*-
#include <clang/AST/ExprCXX.h>
#include <csabase_analyser.h>
#include <csabase_registercheck.h>
#include <csabase_report.h>
#include <string>
using namespace csabase;
using namespace clang;
// ----------------------------------------------------------------------------
static std::string const check_name("strict-alias");
// ----------------------------------------------------------------------------
CanQualType getType(QualType type)
{
return (type->isPointerType() ? type->getPointeeType() : type)
->getCanonicalTypeUnqualified();
}
static void check(Analyser& analyser, CastExpr const *expr)
{
if (expr->getSubExpr()->isNullPointerConstant(
*analyser.context(), Expr::NPC_ValueDependentIsNotNull)) {
return; // RETURN
}
if (expr->getCastKind() != CK_BitCast &&
expr->getCastKind() != CK_LValueBitCast &&
expr->getCastKind() != CK_IntegralToPointer) {
return; // RETURN
}
CanQualType source(getType(expr->getSubExpr()->getType()));
CanQualType target(getType(expr->getType()));
std::string tt = static_cast<QualType>(target).getAsString();
std::string ss = static_cast<QualType>(source).getAsString();
if ((source != target &&
tt != "char" &&
tt != "unsigned char" &&
tt != "signed char" &&
tt != "void" &&
ss != "char" &&
ss != "unsigned char" &&
ss != "signed char" &&
ss != "void") ||
(expr->getType()->isPointerType() !=
expr->getSubExpr()->getType()->isPointerType())) {
analyser.report(expr, check_name, "AL01",
"Possible strict-aliasing violation")
<< expr->getSourceRange();
}
}
// ----------------------------------------------------------------------------
static void checkCCast(Analyser& analyser, CStyleCastExpr const *expr)
{
check(analyser, expr);
}
static void
checkReinterpretCast(Analyser& analyser,
CXXReinterpretCastExpr const *expr)
{
check(analyser, expr);
}
static RegisterCheck register_check0(check_name, checkCCast);
static RegisterCheck register_check1(check_name, checkReinterpretCast);
// ----------------------------------------------------------------------------
// Copyright (C) 2014 Bloomberg Finance L.P.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------- END-OF-FILE ----------------------------------
<|endoftext|>
|
<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <Rosetta/Cards/Cards.hpp>
#include <RosettaTorch/GameToVec.hpp>
namespace RosettaTorch
{
GameToVec::GameToVec(size_t seed) : m_seed(seed)
{
// reproducibility
torch::manual_seed(static_cast<uint64_t>(m_seed));
// Generates the embedding lookup table for the card
size_t NumOfCards = Cards::GetInstance().GetAllCards().size();
CardVectorTable = torch::nn::Embedding(NumOfCards, CardVectorSize);
CardVectorTable->weight = torch::randn(
{static_cast<int>(NumOfCards), static_cast<int>(CardVectorSize)},
torch::kFloat32
);
CardVectorTable->weight.set_requires_grad(false);
}
GameToVec::GameToVec(size_t seed, torch::Tensor weight) : m_seed(seed)
{
// reproducibility
torch::manual_seed(static_cast<uint64_t>(m_seed));
// Generates the embedding lookup table for the card
size_t NumOfCards = Cards::GetInstance().GetAllCards().size();
CardVectorTable = torch::nn::Embedding(NumOfCards, CardVectorSize);
CardVectorTable->weight = weight;
CardVectorTable->weight.set_requires_grad(false);
}
torch::Tensor GameToVec::AbilityToTensor(const Card& card)
{
(void)card;
return torch::Tensor();
}
torch::Tensor GameToVec::GenerateTensor(const Game& game)
{
// vector shape : [1 + 1 + 1 + n * 7 + n * 7 + n * 10 = 3 + n * 24]
// # 1 : number of opponent player's cards on hand.
// # 1 : number of opponent player's left cards at deck.
// # 1 : number of current player's left cards at deck.
// # n * 7 : opponent player's representation vectors of card at the deck.
// each card has a dimensionality of n.
// # n * 7 : current player's representation vectors of card at the deck.
// each card has a dimensionality of n.
// # n * 10 : current player's representation vectors of card in the hand.
// each card has a dimensionality of n.
// each card is represented as a vector which has n dimensionality.
// it includes, cost, attack, health, ability.
// vector shape : [1 + 1 + 1 + m = n]
// # 1 : cost
// # 1 : attack
// # 1 : health
// # m : ability
// each card's abilities are represented as a vector which has m
// dimensionality. it includes, ... vector shape : [m]
torch::Tensor tensor = torch::empty(GameVectorSize, torch::kFloat32);
Player& curPlayer = game.GetCurrentPlayer();
Player& oppPlayer = game.GetOpponentPlayer();
// Write number of opponent player's cards, normalized, on the hand.
tensor[0] =
static_cast<float>(oppPlayer.GetHand().GetNumOfCards()) / HAND_SIZE;
// Write number of opponent player's cards, normalized, on the deck.
tensor[1] =
static_cast<float>(oppPlayer.GetDeck().GetNumOfCards()) / MAX_DECK_SIZE;
// Write number of current player's cards, normalized, on the deck.
tensor[2] =
static_cast<float>(curPlayer.GetDeck().GetNumOfCards()) / MAX_DECK_SIZE;
return tensor;
}
} // namespace RosettaTorch<commit_msg>feat(Game2Vec): baseline for GenerateTensor<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <Rosetta/Cards/Cards.hpp>
#include <RosettaTorch/GameToVec.hpp>
namespace RosettaTorch
{
GameToVec::GameToVec(size_t seed) : m_seed(seed)
{
// reproducibility
torch::manual_seed(static_cast<uint64_t>(m_seed));
// Generates the embedding lookup table for the card
size_t NumOfCards = Cards::GetInstance().GetAllCards().size();
CardVectorTable = torch::nn::Embedding(NumOfCards, CardVectorSize);
CardVectorTable->weight = torch::randn(
{ static_cast<int>(NumOfCards), static_cast<int>(CardVectorSize) },
torch::kFloat32);
CardVectorTable->weight.set_requires_grad(false);
}
GameToVec::GameToVec(size_t seed, torch::Tensor weight) : m_seed(seed)
{
// reproducibility
torch::manual_seed(static_cast<uint64_t>(m_seed));
// Generates the embedding lookup table for the card
size_t NumOfCards = Cards::GetInstance().GetAllCards().size();
CardVectorTable = torch::nn::Embedding(NumOfCards, CardVectorSize);
CardVectorTable->weight = weight;
CardVectorTable->weight.set_requires_grad(false);
}
torch::Tensor GameToVec::CardToTensor(const Card& card)
{
torch::Tensor CardVector = torch::empty(CardVectorSize, torch::kFloat32);
return CardVector;
}
torch::Tensor GameToVec::GenerateTensor(const Game& game)
{
// vector shape : [1 + 1 + 1 + n * 7 + n * 7 + n * 10 = 3 + n * 24]
// # 1 : number of opponent player's cards on hand.
// # 1 : number of opponent player's left cards at deck.
// # 1 : number of current player's left cards at deck.
// # n * 7 : opponent player's representation vectors of card at the deck.
// each card has a dimensionality of n.
// # n * 7 : current player's representation vectors of card at the deck.
// each card has a dimensionality of n.
// # n * 10 : current player's representation vectors of card in the hand.
// each card has a dimensionality of n.
// each card is represented as a vector which has n dimensionality.
// it includes, cost, attack, health, ability.
// vector shape : [1 + 1 + 1 + m = n]
// # 1 : cost
// # 1 : attack
// # 1 : health
// # m : ability
// each card's abilities are represented as a vector which has m
// dimensionality. it includes, ... vector shape : [m]
torch::Tensor tensor = torch::empty(GameVectorSize, torch::kFloat32);
Player& curPlayer = game.GetCurrentPlayer();
Player& oppPlayer = game.GetOpponentPlayer();
// Write number of opponent player's cards, normalized, on the hand.
tensor[0] =
static_cast<float>(oppPlayer.GetHand().GetNumOfCards()) / HAND_SIZE;
// Write number of opponent player's cards, normalized, on the deck.
tensor[1] =
static_cast<float>(oppPlayer.GetDeck().GetNumOfCards()) / MAX_DECK_SIZE;
// Write number of current player's cards, normalized, on the deck.
tensor[2] =
static_cast<float>(curPlayer.GetDeck().GetNumOfCards()) / MAX_DECK_SIZE;
auto field_write = [&](size_t start, Player& player) {
auto field = player.GetField();
size_t NumOfMinions = field.GetNumOfMinions();
size_t i = 0;
for (; i < NumOfMinions; ++i)
{
tensor[start + i] = CardToTensor(field.GetMinion[i]);
}
for (; i < FIELD_SIZE; ++i)
{
tensor[start + i] = torch::zeros(CardVectorSize);
}
};
auto hand_write = [&](size_t start, Player& player) {
auto hand = player.GetHand();
size_t NumOfCards = hand.GetNumOfCards();
size_t i = 0;
for (; i < NumOfCards; ++i)
{
tensor[start + i] = CardToTensor(hand.GetCard[i]);
}
for (; i < HAND_SIZE; ++i)
{
tensor[start + i] = torch::zeros(CardVectorSize);
}
};
// Write opponent player's field cards
field_write(PlayerMetaSize, oppPlayer);
// Write current player's field cards
field_write(PlayerMetaSize + 1 * FIELD_SIZE, curPlayer);
// Write current player's hand cards
hand_write(PlayerMetaSize + 2 * FIELD_SIZE, curPlayer);
return tensor;
}
} // namespace RosettaTorch<|endoftext|>
|
<commit_before>#include "TestClass.hpp"
static int magic = 0x11223344;
int TestClass::testOutlineFunction()
{
return someData_ * reinterpret_cast<int>(&magic);
}
int TestClass::testOutlineFunctionWithStaticVariable()
{
static int staticVar = -1;
staticVar += testOutlineFunction();
return staticVar;
}
void getTestData1(TestDataArray * d)
{
GET_TEST_DATA_IMPL();
}
<commit_msg>-: Warning fixed<commit_after>#include "TestClass.hpp"
static int magic = 0x11223344;
int TestClass::testOutlineFunction()
{
return someData_ * (int)reinterpret_cast<size_t>(&magic);
}
int TestClass::testOutlineFunctionWithStaticVariable()
{
static int staticVar = -1;
staticVar += testOutlineFunction();
return staticVar;
}
void getTestData1(TestDataArray * d)
{
GET_TEST_DATA_IMPL();
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <vector>
#include "unittest/gtest.hpp"
#include "btree/node.hpp"
#include "btree/leaf_node.hpp"
namespace unittest {
// TODO: This is rather duplicative of fsck::check_value.
void expect_valid_value_shallowly(const btree_value *value) {
EXPECT_TRUE(!(value->metadata_flags & ~(MEMCACHED_FLAGS | MEMCACHED_CAS | MEMCACHED_EXPTIME | LARGE_VALUE)));
size_t size = value->value_size();
if (value->is_large()) {
EXPECT_GT(size, MAX_IN_NODE_VALUE_SIZE);
// This isn't fsck, we can't follow large buf pointers.
} else {
EXPECT_LE(size, MAX_IN_NODE_VALUE_SIZE);
}
}
// TODO: This is rather duplicative of fsck::check_subtree_leaf_node.
void verify(block_size_t block_size, const leaf_node_t *buf) {
ASSERT_LE(offsetof(leaf_node_t, pair_offsets) + buf->npairs * 2, buf->frontmost_offset);
ASSERT_LE(buf->frontmost_offset, block_size.value());
std::vector<uint16_t> offsets(buf->pair_offsets, buf->pair_offsets + buf->npairs);
std::sort(offsets.begin(), offsets.end());
uint16_t expected = buf->frontmost_offset;
for (std::vector<uint16_t>::const_iterator p = offsets.begin(), e = offsets.end(); p < e; ++p) {
ASSERT_LE(expected, block_size.value());
ASSERT_EQ(expected, *p);
expected += leaf_node_handler::pair_size(leaf_node_handler::get_pair(buf, *p));
}
ASSERT_EQ(block_size.value(), expected);
const btree_key *last_key = NULL;
for (const uint16_t *p = buf->pair_offsets, *e = p + buf->npairs; p < e; ++p) {
const btree_leaf_pair *pair = leaf_node_handler::get_pair(buf, *p);
if (last_key != NULL) {
const btree_key *next_key = &pair->key;
EXPECT_LT(leaf_key_comp::compare(last_key, next_key), 0);
last_key = next_key;
}
expect_valid_value_shallowly(pair->value());
}
}
TEST(LeafNodeTest, Offsets) {
// Check leaf_node_t.
EXPECT_EQ(0, offsetof(leaf_node_t, magic));
EXPECT_EQ(4, offsetof(leaf_node_t, times));
EXPECT_EQ(12, offsetof(leaf_node_t, npairs));
EXPECT_EQ(14, offsetof(leaf_node_t, frontmost_offset));
EXPECT_EQ(16, offsetof(leaf_node_t, pair_offsets));
EXPECT_EQ(16, sizeof(leaf_node_t));
// Check leaf_timestamps_t, since that's specifically part of leaf_node_t.
EXPECT_EQ(0, offsetof(leaf_timestamps_t, last_modified));
EXPECT_EQ(4, offsetof(leaf_timestamps_t, earlier));
// Changing NUM_LEAF_NODE_EARLIER_TIMES changes the disk format.
EXPECT_EQ(2, NUM_LEAF_NODE_EARLIER_TIMES);
EXPECT_EQ(8, sizeof(leaf_timestamps_t));
// Check btree_leaf_pair.
EXPECT_EQ(0, offsetof(btree_leaf_pair, key));
btree_leaf_pair p;
p.key.size = 173;
EXPECT_EQ(174, reinterpret_cast<byte *>(p.value()) - reinterpret_cast<byte *>(&p));
}
class Value {
public:
Value(const std::string& data = "", mcflags_t mcflags = 0, cas_t cas = 0, bool has_cas = false, exptime_t exptime = 0)
: mcflags_(mcflags), cas_(cas), exptime_(exptime),
has_cas_(has_cas)
data_(data) {
ASSERT_LE(data_.size(), MAX_IN_NODE_VALUE_SIZE);
}
void WriteBtreeValue(btree_value *out) const {
out->size = 0;
ASSERT_LE(data_.size(), MAX_IN_NODE_VALUE_SIZE);
out->value_size(data_.size());
out->set_mcflags(mcflags_);
out->set_exptime(exptime_);
if (has_cas_) {
out->set_cas(cas_);
}
}
static Value Make(const btree_value *v) {
ASSERT_FALSE(v->is_large());
return Value(std::string(v->value(), v->value() + v->value_size()),
v->mcflags(), v->has_cas() ? v->cas() : 0, v->has_cas(), v->exptime());
}
bool operator==(const Value& rhs) {
return mcflags_ == rhs.mcflags_
&& exptime_ == rhs.exptime_
&& data_ == rhs.data_
&& has_cas_ == rhs.has_cas_
&& (has_cas_ ? cas_ == rhs.cas_ : true);
}
int full_size() const {
return sizeof(btree_value) + (mcflags_ ? sizeof(mcflags_t) : 0) + (has_cas_ ? sizeof(cas_t) : 0)
+ (exptime_ ? sizeof(exptime_t) : 0) + data_.size();
}
private:
mcflags_t mcflags_;
cas_t cas_;
exptime_t exptime_;
bool has_cas_;
std::string data_;
};
class StackKey {
public:
explicit StackKey(const std::string& key) {
ASSERT_LE(key.size(), MAX_KEY_SIZE);
keyval.size = key.size();
memcpy(keyval.contents, key.c_str(), key.size());
}
const btree_key *look() const {
return &keyval;
}
private:
union {
byte keyval_padding[sizeof(btree_key) + MAX_KEY_SIZE];
btree_key keyval;
};
};
class StackValue {
public:
explicit StackValue(const Value& value) {
value.WriteBtreeValue(&val);
}
const btree_value *look() const {
return &val;
}
private:
union {
byte val_padding[sizeof(btree_value) + MAX_TOTAL_NODE_CONTENTS_SIZE];
btree_value val;
};
};
template <int block_size>
class LeafNodeGrinder {
block_size_t bs;
typedef std::map<std::string, Value> expected_t;
expected_t expected;
int expected_free_space;
leaf_node_t *node;
void insert(const std::string& k, const Value& v) {
if (expected_free_space < sizeof(*node->pair_offsets) + v.full_size()) {
StackKey skey(k);
StackValue sval(v);
ASSERT_FALSE(leaf_node_handler::insert(bs, node, skey.look(), sval.look(), repli_timestamp::invalid));
verify(bs, node, expected_free_space);
}
std::pair<expected_t::iterator, bool> res = expected.insert(k, v);
if (res.second) {
// The key didn't previously exist.
expected_free_space -= v.full_size() + sizeof(*node->pair_offsets);
} else {
// The key previously existed.
expected_free_space += res.first->second.full_size();
expected_free_space -= v.full_size();
res.first->second = v;
}
verify(bs, node, expected_free_space);
}
void remove(const std::string& k) {
expected_t::iterator p = expected.find(k);
if (p != expected.end()) {
}
}
};
block_size_t make_bs() {
// TODO: Test weird block sizes.
return block_size_t::unsafe_make(4096);
}
leaf_node_t *malloc_leaf_node(block_size_t bs) {
return reinterpret_cast<leaf_node_t *>(malloc(bs.value()));
}
btree_key *malloc_key(const char *s) {
size_t origlen = strlen(s);
EXPECT_LE(origlen, MAX_KEY_SIZE);
size_t len = std::min<size_t>(origlen, MAX_KEY_SIZE);
btree_key *k = reinterpret_cast<btree_key *>(malloc(sizeof(btree_key) + len));
k->size = len;
memcpy(k->contents, s, len);
return k;
}
btree_value *malloc_value(const char *s) {
size_t origlen = strlen(s);
EXPECT_LE(origlen, MAX_IN_NODE_VALUE_SIZE);
size_t len = std::min<size_t>(origlen, MAX_IN_NODE_VALUE_SIZE);
btree_value *v = reinterpret_cast<btree_value *>(malloc(sizeof(btree_value) + len));
v->size = len;
v->metadata_flags = 0;
memcpy(v->value(), s, len);
return v;
}
TEST(LeafNodeTest, Initialization) {
block_size_t bs = make_bs();
leaf_node_t *node = malloc_leaf_node(bs);
leaf_node_handler::init(bs, node, repli_timestamp::invalid);
verify(bs, node);
free(node);
}
// Runs an InsertLookupRemove test with key and value.
void InsertLookupRemoveHelper(const char *key, const char *value) {
block_size_t bs = make_bs();
leaf_node_t *node = malloc_leaf_node(bs);
leaf_node_handler::init(bs, node, repli_timestamp::invalid);
verify(bs, node);
btree_key *k = malloc_key(key);
btree_value *v = malloc_value(value);
ASSERT_TRUE(leaf_node_handler::insert(bs, node, k, v, repli_timestamp::invalid));
verify(bs, node);
ASSERT_EQ(1, node->npairs);
union {
byte readval_padding[MAX_TOTAL_NODE_CONTENTS_SIZE + sizeof(btree_value)];
btree_value readval;
};
(void)readval_padding;
ASSERT_TRUE(leaf_node_handler::lookup(node, k, &readval));
ASSERT_EQ(0, memcmp(v, &readval, v->full_size()));
leaf_node_handler::remove(bs, node, k);
verify(bs, node);
ASSERT_EQ(0, node->npairs);
free(k);
free(v);
free(node);
}
TEST(LeafNodeTest, ElementaryInsertLookupRemove) {
InsertLookupRemoveHelper("the_key", "the_value");
}
TEST(LeafNodeTest, EmptyValueInsertLookupRemove) {
InsertLookupRemoveHelper("the_key", "");
}
TEST(LeafNodeTest, EmptyKeyInsertLookupRemove) {
InsertLookupRemoveHelper("", "the_value");
}
TEST(LeafNodeTest, EmptyKeyValueInsertLookupRemove) {
InsertLookupRemoveHelper("", "");
}
} // namespace unittest
<commit_msg>Made LeafNodeGrinder compile with incomplete remove function.<commit_after>#include <algorithm>
#include <vector>
#include "unittest/gtest.hpp"
#include "btree/node.hpp"
#include "btree/leaf_node.hpp"
namespace unittest {
// TODO: This is rather duplicative of fsck::check_value.
void expect_valid_value_shallowly(const btree_value *value) {
EXPECT_TRUE(!(value->metadata_flags & ~(MEMCACHED_FLAGS | MEMCACHED_CAS | MEMCACHED_EXPTIME | LARGE_VALUE)));
size_t size = value->value_size();
if (value->is_large()) {
EXPECT_GT(size, MAX_IN_NODE_VALUE_SIZE);
// This isn't fsck, we can't follow large buf pointers.
} else {
EXPECT_LE(size, MAX_IN_NODE_VALUE_SIZE);
}
}
// TODO: This is rather duplicative of fsck::check_subtree_leaf_node.
void verify(block_size_t block_size, const leaf_node_t *buf, int expected_free_space) {
int end_of_pair_offsets = offsetof(leaf_node_t, pair_offsets) + buf->npairs * 2;
ASSERT_LE(end_of_pair_offsets, buf->frontmost_offset);
ASSERT_LE(buf->frontmost_offset, block_size.value());
ASSERT_EQ(expected_free_space, buf->frontmost_offset - end_of_pair_offsets);
std::vector<uint16_t> offsets(buf->pair_offsets, buf->pair_offsets + buf->npairs);
std::sort(offsets.begin(), offsets.end());
uint16_t expected = buf->frontmost_offset;
for (std::vector<uint16_t>::const_iterator p = offsets.begin(), e = offsets.end(); p < e; ++p) {
ASSERT_LE(expected, block_size.value());
ASSERT_EQ(expected, *p);
expected += leaf_node_handler::pair_size(leaf_node_handler::get_pair(buf, *p));
}
ASSERT_EQ(block_size.value(), expected);
const btree_key *last_key = NULL;
for (const uint16_t *p = buf->pair_offsets, *e = p + buf->npairs; p < e; ++p) {
const btree_leaf_pair *pair = leaf_node_handler::get_pair(buf, *p);
if (last_key != NULL) {
const btree_key *next_key = &pair->key;
EXPECT_LT(leaf_key_comp::compare(last_key, next_key), 0);
last_key = next_key;
}
expect_valid_value_shallowly(pair->value());
}
}
TEST(LeafNodeTest, Offsets) {
// Check leaf_node_t.
EXPECT_EQ(0, offsetof(leaf_node_t, magic));
EXPECT_EQ(4, offsetof(leaf_node_t, times));
EXPECT_EQ(12, offsetof(leaf_node_t, npairs));
EXPECT_EQ(14, offsetof(leaf_node_t, frontmost_offset));
EXPECT_EQ(16, offsetof(leaf_node_t, pair_offsets));
EXPECT_EQ(16, sizeof(leaf_node_t));
// Check leaf_timestamps_t, since that's specifically part of leaf_node_t.
EXPECT_EQ(0, offsetof(leaf_timestamps_t, last_modified));
EXPECT_EQ(4, offsetof(leaf_timestamps_t, earlier));
// Changing NUM_LEAF_NODE_EARLIER_TIMES changes the disk format.
EXPECT_EQ(2, NUM_LEAF_NODE_EARLIER_TIMES);
EXPECT_EQ(8, sizeof(leaf_timestamps_t));
// Check btree_leaf_pair.
EXPECT_EQ(0, offsetof(btree_leaf_pair, key));
btree_leaf_pair p;
p.key.size = 173;
EXPECT_EQ(174, reinterpret_cast<byte *>(p.value()) - reinterpret_cast<byte *>(&p));
}
class Value {
public:
Value(const std::string& data = "", mcflags_t mcflags = 0, cas_t cas = 0, bool has_cas = false, exptime_t exptime = 0)
: mcflags_(mcflags), cas_(cas), exptime_(exptime),
has_cas_(has_cas),
data_(data) {
EXPECT_LE(data_.size(), MAX_IN_NODE_VALUE_SIZE);
}
void WriteBtreeValue(btree_value *out) const {
out->size = 0;
ASSERT_LE(data_.size(), MAX_IN_NODE_VALUE_SIZE);
out->value_size(data_.size());
out->set_mcflags(mcflags_);
out->set_exptime(exptime_);
if (has_cas_) {
out->set_cas(cas_);
}
}
static Value Make(const btree_value *v) {
EXPECT_FALSE(v->is_large());
return Value(std::string(v->value(), v->value() + v->value_size()),
v->mcflags(), v->has_cas() ? v->cas() : 0, v->has_cas(), v->exptime());
}
bool operator==(const Value& rhs) {
return mcflags_ == rhs.mcflags_
&& exptime_ == rhs.exptime_
&& data_ == rhs.data_
&& has_cas_ == rhs.has_cas_
&& (has_cas_ ? cas_ == rhs.cas_ : true);
}
int full_size() const {
return sizeof(btree_value) + (mcflags_ ? sizeof(mcflags_t) : 0) + (has_cas_ ? sizeof(cas_t) : 0)
+ (exptime_ ? sizeof(exptime_t) : 0) + data_.size();
}
private:
mcflags_t mcflags_;
cas_t cas_;
exptime_t exptime_;
bool has_cas_;
std::string data_;
};
class StackKey {
public:
explicit StackKey(const std::string& key) {
EXPECT_LE(key.size(), MAX_KEY_SIZE);
keyval.size = key.size();
memcpy(keyval.contents, key.c_str(), key.size());
}
const btree_key *look() const {
return &keyval;
}
private:
union {
byte keyval_padding[sizeof(btree_key) + MAX_KEY_SIZE];
btree_key keyval;
};
};
class StackValue {
public:
explicit StackValue(const Value& value) {
value.WriteBtreeValue(&val);
}
const btree_value *look() const {
return &val;
}
private:
union {
byte val_padding[sizeof(btree_value) + MAX_TOTAL_NODE_CONTENTS_SIZE];
btree_value val;
};
};
template <int block_size>
class LeafNodeGrinder {
block_size_t bs;
typedef std::map<std::string, Value> expected_t;
expected_t expected;
int expected_free_space;
leaf_node_t *node;
void insert(const std::string& k, const Value& v) {
if (expected_free_space < sizeof(*node->pair_offsets) + v.full_size()) {
StackKey skey(k);
StackValue sval(v);
ASSERT_FALSE(leaf_node_handler::insert(bs, node, skey.look(), sval.look(), repli_timestamp::invalid));
verify(bs, node, expected_free_space);
}
std::pair<expected_t::iterator, bool> res = expected.insert(std::make_pair(k, v));
if (res.second) {
// The key didn't previously exist.
expected_free_space -= v.full_size() + sizeof(*node->pair_offsets);
} else {
// The key previously existed.
expected_free_space += res.first->second.full_size();
expected_free_space -= v.full_size();
res.first->second = v;
}
verify(bs, node, expected_free_space);
}
void remove(const std::string& k) {
expected_t::iterator p = expected.find(k);
if (p != expected.end()) {
}
}
};
block_size_t make_bs() {
// TODO: Test weird block sizes.
return block_size_t::unsafe_make(4096);
}
leaf_node_t *malloc_leaf_node(block_size_t bs) {
return reinterpret_cast<leaf_node_t *>(malloc(bs.value()));
}
btree_key *malloc_key(const char *s) {
size_t origlen = strlen(s);
EXPECT_LE(origlen, MAX_KEY_SIZE);
size_t len = std::min<size_t>(origlen, MAX_KEY_SIZE);
btree_key *k = reinterpret_cast<btree_key *>(malloc(sizeof(btree_key) + len));
k->size = len;
memcpy(k->contents, s, len);
return k;
}
btree_value *malloc_value(const char *s) {
size_t origlen = strlen(s);
EXPECT_LE(origlen, MAX_IN_NODE_VALUE_SIZE);
size_t len = std::min<size_t>(origlen, MAX_IN_NODE_VALUE_SIZE);
btree_value *v = reinterpret_cast<btree_value *>(malloc(sizeof(btree_value) + len));
v->size = len;
v->metadata_flags = 0;
memcpy(v->value(), s, len);
return v;
}
TEST(LeafNodeTest, Initialization) {
block_size_t bs = make_bs();
leaf_node_t *node = malloc_leaf_node(bs);
leaf_node_handler::init(bs, node, repli_timestamp::invalid);
verify(bs, node, bs.value() - offsetof(leaf_node_t, pair_offsets));
free(node);
}
// Runs an InsertLookupRemove test with key and value.
void InsertLookupRemoveHelper(const char *key, const char *value) {
block_size_t bs = make_bs();
leaf_node_t *node = malloc_leaf_node(bs);
leaf_node_handler::init(bs, node, repli_timestamp::invalid);
verify(bs, node, bs.value() - offsetof(leaf_node_t, pair_offsets));
btree_key *k = malloc_key(key);
btree_value *v = malloc_value(value);
ASSERT_TRUE(leaf_node_handler::insert(bs, node, k, v, repli_timestamp::invalid));
verify(bs, node, bs.value() - offsetof(leaf_node_t, pair_offsets) - k->full_size() - v->full_size() - 2);
ASSERT_EQ(1, node->npairs);
union {
byte readval_padding[MAX_TOTAL_NODE_CONTENTS_SIZE + sizeof(btree_value)];
btree_value readval;
};
(void)readval_padding;
ASSERT_TRUE(leaf_node_handler::lookup(node, k, &readval));
ASSERT_EQ(0, memcmp(v, &readval, v->full_size()));
leaf_node_handler::remove(bs, node, k);
verify(bs, node, bs.value() - offsetof(leaf_node_t, pair_offsets));
ASSERT_EQ(0, node->npairs);
free(k);
free(v);
free(node);
}
TEST(LeafNodeTest, ElementaryInsertLookupRemove) {
InsertLookupRemoveHelper("the_key", "the_value");
}
TEST(LeafNodeTest, EmptyValueInsertLookupRemove) {
InsertLookupRemoveHelper("the_key", "");
}
TEST(LeafNodeTest, EmptyKeyInsertLookupRemove) {
InsertLookupRemoveHelper("", "the_value");
}
TEST(LeafNodeTest, EmptyKeyValueInsertLookupRemove) {
InsertLookupRemoveHelper("", "");
}
} // namespace unittest
<|endoftext|>
|
<commit_before>// Translated from vib.tcl
#include <vtkActor.h>
#include <vtkCallbackCommand.h>
#include <vtkCamera.h>
#include <vtkDatasetMapper.h>
#include <vtkLookupTable.h>
#include <vtkNamedColors.h>
#include <vtkOutlineFilter.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkPolyDataNormals.h>
#include <vtkPolyDataReader.h>
#include <vtkProp3d.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSmartPointer.h>
#include <vtkVectorDot.h>
#include <vtkWarpVector.h>
#include <algorithm>
#include <string>
#include <vector>
int main(int argc, char* argv[])
{
auto Scale = [](std::vector<double>& v, double scale) {
std::transform(std::begin(v), std::end(v), std::begin(v),
[=](double const& n) { return n / scale; });
return;
};
if (argc < 2)
{
std::cout << "Usage: " << argv[0] << " filename" << std::endl;
std::cout << "where: filename is the file plate.vtk." << std::endl;
std::cout
<< "Produces figure 6-14(a) Beam displacement from the VTK Textbook."
<< std::endl;
return EXIT_FAILURE;
}
std::string fileName = argv[1];
vtkSmartPointer<vtkNamedColors> colors =
vtkSmartPointer<vtkNamedColors>::New();
// Set the background color and plate color. Match those in VTKTextbook.pdf.
auto scale = 256.0;
std::vector<double> bkg = {65, 99, 149};
Scale(bkg, scale);
std::vector<double> bar = {255, 160, 140};
Scale(bar, scale);
colors->SetColor("BkgColor", bkg[0], bkg[1], bkg[2]);
colors->SetColor("PlateColor", bar[0], bar[1], bar[2]);
// Read a vtk file
//
vtkSmartPointer<vtkPolyDataReader> plate =
vtkSmartPointer<vtkPolyDataReader>::New();
plate->SetFileName(fileName.c_str());
plate->Update();
double bounds[6];
plate->GetOutput()->GetBounds(bounds);
plate->SetVectorsName("mode2");
vtkSmartPointer<vtkPolyDataNormals> normals =
vtkSmartPointer<vtkPolyDataNormals>::New();
normals->SetInputConnection(plate->GetOutputPort());
vtkSmartPointer<vtkWarpVector> warp = vtkSmartPointer<vtkWarpVector>::New();
warp->SetInputConnection(normals->GetOutputPort());
warp->SetScaleFactor(0.5);
vtkSmartPointer<vtkVectorDot> color = vtkSmartPointer<vtkVectorDot>::New();
color->SetInputConnection(warp->GetOutputPort());
vtkSmartPointer<vtkDataSetMapper> plateMapper =
vtkSmartPointer<vtkDataSetMapper>::New();
plateMapper->SetInputConnection(warp->GetOutputPort());
vtkSmartPointer<vtkActor> plateActor = vtkSmartPointer<vtkActor>::New();
plateActor->SetMapper(plateMapper);
plateActor->GetProperty()->SetColor(
colors->GetColor3d("PlateColor").GetData());
plateActor->RotateX(-90);
// Create the outline.
//
vtkSmartPointer<vtkOutlineFilter> outline =
vtkSmartPointer<vtkOutlineFilter>::New();
outline->SetInputConnection(plate->GetOutputPort());
vtkSmartPointer<vtkPolyDataMapper> spikeMapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
spikeMapper->SetInputConnection(outline->GetOutputPort());
vtkSmartPointer<vtkActor> outlineActor = vtkSmartPointer<vtkActor>::New();
outlineActor->SetMapper(spikeMapper);
outlineActor->RotateX(-90);
outlineActor->GetProperty()->SetColor(colors->GetColor3d("White").GetData());
// Create the RenderWindow, Renderer and both Actors
//
vtkSmartPointer<vtkRenderer> ren = vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renWin =
vtkSmartPointer<vtkRenderWindow>::New();
renWin->AddRenderer(ren);
vtkSmartPointer<vtkRenderWindowInteractor> iren =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
iren->SetRenderWindow(renWin);
// Add the actors to the renderer, set the background and size
//
ren->AddActor(plateActor);
ren->AddActor(outlineActor);
renWin->SetSize(500, 500);
// Render the image.
renWin->Render();
ren->SetBackground(colors->GetColor3d("BkgColor").GetData());
// This closely matches the original illustration.
ren->GetActiveCamera()->SetPosition(-3.7, 13, 15.5);
ren->ResetCameraClippingRange();
iren->Start();
return EXIT_SUCCESS;
}
<commit_msg>COMP: Fix VisualizationAlgorithms/PlateVibration build on case sensitive system<commit_after>// Translated from vib.tcl
#include <vtkActor.h>
#include <vtkCallbackCommand.h>
#include <vtkCamera.h>
#include <vtkDataSetMapper.h>
#include <vtkLookupTable.h>
#include <vtkNamedColors.h>
#include <vtkOutlineFilter.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkPolyDataNormals.h>
#include <vtkPolyDataReader.h>
#include <vtkProp3D.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSmartPointer.h>
#include <vtkVectorDot.h>
#include <vtkWarpVector.h>
#include <algorithm>
#include <string>
#include <vector>
int main(int argc, char* argv[])
{
auto Scale = [](std::vector<double>& v, double scale) {
std::transform(std::begin(v), std::end(v), std::begin(v),
[=](double const& n) { return n / scale; });
return;
};
if (argc < 2)
{
std::cout << "Usage: " << argv[0] << " filename" << std::endl;
std::cout << "where: filename is the file plate.vtk." << std::endl;
std::cout
<< "Produces figure 6-14(a) Beam displacement from the VTK Textbook."
<< std::endl;
return EXIT_FAILURE;
}
std::string fileName = argv[1];
vtkSmartPointer<vtkNamedColors> colors =
vtkSmartPointer<vtkNamedColors>::New();
// Set the background color and plate color. Match those in VTKTextbook.pdf.
auto scale = 256.0;
std::vector<double> bkg = {65, 99, 149};
Scale(bkg, scale);
std::vector<double> bar = {255, 160, 140};
Scale(bar, scale);
colors->SetColor("BkgColor", bkg[0], bkg[1], bkg[2]);
colors->SetColor("PlateColor", bar[0], bar[1], bar[2]);
// Read a vtk file
//
vtkSmartPointer<vtkPolyDataReader> plate =
vtkSmartPointer<vtkPolyDataReader>::New();
plate->SetFileName(fileName.c_str());
plate->Update();
double bounds[6];
plate->GetOutput()->GetBounds(bounds);
plate->SetVectorsName("mode2");
vtkSmartPointer<vtkPolyDataNormals> normals =
vtkSmartPointer<vtkPolyDataNormals>::New();
normals->SetInputConnection(plate->GetOutputPort());
vtkSmartPointer<vtkWarpVector> warp = vtkSmartPointer<vtkWarpVector>::New();
warp->SetInputConnection(normals->GetOutputPort());
warp->SetScaleFactor(0.5);
vtkSmartPointer<vtkVectorDot> color = vtkSmartPointer<vtkVectorDot>::New();
color->SetInputConnection(warp->GetOutputPort());
vtkSmartPointer<vtkDataSetMapper> plateMapper =
vtkSmartPointer<vtkDataSetMapper>::New();
plateMapper->SetInputConnection(warp->GetOutputPort());
vtkSmartPointer<vtkActor> plateActor = vtkSmartPointer<vtkActor>::New();
plateActor->SetMapper(plateMapper);
plateActor->GetProperty()->SetColor(
colors->GetColor3d("PlateColor").GetData());
plateActor->RotateX(-90);
// Create the outline.
//
vtkSmartPointer<vtkOutlineFilter> outline =
vtkSmartPointer<vtkOutlineFilter>::New();
outline->SetInputConnection(plate->GetOutputPort());
vtkSmartPointer<vtkPolyDataMapper> spikeMapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
spikeMapper->SetInputConnection(outline->GetOutputPort());
vtkSmartPointer<vtkActor> outlineActor = vtkSmartPointer<vtkActor>::New();
outlineActor->SetMapper(spikeMapper);
outlineActor->RotateX(-90);
outlineActor->GetProperty()->SetColor(colors->GetColor3d("White").GetData());
// Create the RenderWindow, Renderer and both Actors
//
vtkSmartPointer<vtkRenderer> ren = vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renWin =
vtkSmartPointer<vtkRenderWindow>::New();
renWin->AddRenderer(ren);
vtkSmartPointer<vtkRenderWindowInteractor> iren =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
iren->SetRenderWindow(renWin);
// Add the actors to the renderer, set the background and size
//
ren->AddActor(plateActor);
ren->AddActor(outlineActor);
renWin->SetSize(500, 500);
// Render the image.
renWin->Render();
ren->SetBackground(colors->GetColor3d("BkgColor").GetData());
// This closely matches the original illustration.
ren->GetActiveCamera()->SetPosition(-3.7, 13, 15.5);
ren->ResetCameraClippingRange();
iren->Start();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/**********************************************************************************
Infomap software package for multi-level network clustering
Copyright (c) 2013 Daniel Edler, Martin Rosvall
For more information, see <http://www.mapequation.org>
This file is part of Infomap software package.
Infomap software package is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Infomap software package 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Infomap software package. If not, see <http://www.gnu.org/licenses/>.
**********************************************************************************/
#include <iostream>
#include <sstream>
#include <fstream>
#include <stdexcept>
#include "utils/Logger.h"
#include "io/Config.h"
#include "infomap/InfomapContext.h"
#include "utils/Stopwatch.h"
#include "io/ProgramInterface.h"
#include "io/convert.h"
#include "utils/FileURI.h"
#include "utils/Date.h"
#include <iomanip>
#include "io/version.h"
void runInfomap(Config const& config)
{
InfomapContext context(config);
context.getInfomap()->run();
}
void getConfig(Config& conf, int argc, char *argv[])
{
ProgramInterface api("Infomap",
"Implementation of the Infomap clustering algorithm based on the Map Equation (see www.mapequation.org)",
INFOMAP_VERSION);
// --------------------- Input options ---------------------
api.addNonOptionArgument(conf.networkFile, "network_file",
"The file containing the network data. Accepted formats: Pajek (implied by .net) and link list (.txt)");
api.addOptionalNonOptionArguments(conf.additionalInput, "[additional input]",
"More network layers for multiplex.", true);
api.addOptionArgument(conf.inputFormat, 'i', "input-format",
"Specify input format ('pajek', 'link-list', '3gram' or 'multiplex') to override format possibly implied by file extension.", "s");
api.addOptionArgument(conf.withMemory, "with-memory",
"Use second order Markov dynamics and let nodes be part of different modules. Simulate memory from first-order data if not '3gram' input.");
api.addOptionArgument(conf.parseWithoutIOStreams, "without-iostream",
"Parse the input network data without the iostream library. Can be a bit faster, but not as robust.", true);
api.addOptionArgument(conf.zeroBasedNodeNumbers, 'z', "zero-based-numbering",
"Assume node numbers start from zero in the input file instead of one.");
api.addOptionArgument(conf.includeSelfLinks, 'k', "include-self-links",
"Include links with the same source and target node. (Ignored by default.)");
api.addOptionArgument(conf.nodeLimit, 'O', "node-limit",
"Limit the number of nodes to read from the network. Ignore links connected to ignored nodes.", "n", true);
api.addOptionArgument(conf.clusterDataFile, 'c', "cluster-data",
"Provide an initial two-level solution (.clu format).", "p", true);
api.addOptionArgument(conf.noInfomap, "no-infomap",
"Don't run Infomap. Useful if initial cluster data should be preserved or non-modular data printed.", true);
// --------------------- Output options ---------------------
api.addOptionArgument(conf.noFileOutput, '0', "no-file-output",
"Don't print any output to file.", true);
api.addOptionArgument(conf.printMap, "map",
"Print the top two-level modular network in the .map format.");
api.addOptionArgument(conf.printClu, "clu",
"Print the top cluster indices for each node.");
api.addOptionArgument(conf.printTree, "tree",
"Print the hierarchy in .tree format. (default true if no other output with cluster data)");
api.addOptionArgument(conf.printFlowTree, "ftree",
"Print the hierarchy in .tree format and append the hierarchically aggregated network links.", true);
api.addOptionArgument(conf.printBinaryTree, "btree",
"Print the tree in a streamable binary format.", true);
api.addOptionArgument(conf.printBinaryFlowTree, "bftree",
"Print the tree including horizontal flow links in a streamable binary format.");
api.addOptionArgument(conf.printNodeRanks, "node-ranks",
"Print the calculated flow for each node to a file.", true);
api.addOptionArgument(conf.printFlowNetwork, "flow-network",
"Print the network with calculated flow values.", true);
api.addOptionArgument(conf.printPajekNetwork, "pajek",
"Print the parsed network in Pajek format.", true);
api.addOptionArgument(conf.printExpanded, "expanded",
"Print the expanded network of memory nodes if possible.", true);
// --------------------- Core algorithm options ---------------------
api.addOptionArgument(conf.twoLevel, '2', "two-level",
"Optimize a two-level partition of the network.");
bool dummyUndirected;
api.addOptionArgument(dummyUndirected, 'u', "undirected",
"Assume undirected links. (default)");
api.addOptionArgument(conf.directed, 'd', "directed",
"Assume directed links.");
api.addOptionArgument(conf.undirdir, 't', "undirdir",
"Two-mode dynamics: Assume undirected links for calculating flow, but directed when minimizing codelength.");
api.addOptionArgument(conf.outdirdir, "outdirdir",
"Two-mode dynamics: Count only ingoing links when calculating the flow, but all when minimizing codelength.", true);
api.addOptionArgument(conf.rawdir, 'w', "rawdir",
"Two-mode dynamics: Assume directed links and let the raw link weights be the flow.", true);
api.addOptionArgument(conf.recordedTeleportation, 'e', "recorded-teleportation",
"If teleportation is used to calculate the flow, also record it when minimizing codelength.", true);
api.addOptionArgument(conf.teleportToNodes, 'o', "to-nodes",
"Teleport to nodes instead of to links, assuming uniform node weights if no such input data.", true);
api.addOptionArgument(conf.teleportationProbability, 'p', "teleportation-probability",
"The probability of teleporting to a random node or link.", "f", true);
api.addOptionArgument(conf.selfTeleportationProbability, 'y', "self-link-teleportation-probability",
"The probability of teleporting to itself. Effectively increasing the code rate, generating more and smaller modules.", "f", true);
api.addOptionArgument(conf.multiplexAggregationRate, "multiplex-aggregation-rate",
"The probability of following a link as if the layers where completely aggregated. Zero means completely disconnected layers.", "f", true);
api.addOptionArgument(conf.seedToRandomNumberGenerator, 's', "seed",
"A seed (integer) to the random number generator.", "n");
// --------------------- Performance and accuracy options ---------------------
api.addOptionArgument(conf.numTrials, 'N', "num-trials",
"The number of outer-most loops to run before picking the best solution.", "n");
api.addOptionArgument(conf.minimumCodelengthImprovement, 'm', "min-improvement",
"Minimum codelength threshold for accepting a new solution.", "f", true);
api.addOptionArgument(conf.randomizeCoreLoopLimit, 'a', "random-loop-limit",
"Randomize the core loop limit from 1 to 'core-loop-limit'", true);
api.addOptionArgument(conf.coreLoopLimit, 'M', "core-loop-limit",
"Limit the number of loops that tries to move each node into the best possible module", "n", true);
api.addOptionArgument(conf.levelAggregationLimit, 'L', "core-level-limit",
"Limit the number of times the core loops are reapplied on existing modular network to search bigger structures.", "n", true);
api.addOptionArgument(conf.tuneIterationLimit, 'T', "tune-iteration-limit",
"Limit the number of main iterations in the two-level partition algorithm. 0 means no limit.", "n", true);
api.addOptionArgument(conf.minimumRelativeTuneIterationImprovement, 'U', "tune-iteration-threshold",
"Set a codelength improvement threshold of each new tune iteration to 'f' times the initial two-level codelength.", "f", true);
api.addOptionArgument(conf.fastCoarseTunePartition, 'C', "fast-coarse-tune",
"Try to find the quickest partition of each module when creating sub-modules for the coarse-tune part.", true);
api.addOptionArgument(conf.alternateCoarseTuneLevel, 'A', "alternate-coarse-tune-level",
"Try to find different levels of sub-modules to move in the coarse-tune part.", true);
api.addOptionArgument(conf.coarseTuneLevel, 'S', "coarse-tune-level",
"Set the recursion limit when searching for sub-modules. A level of 1 will find sub-sub-modules.", "n", true);
api.addIncrementalOptionArgument(conf.fastHierarchicalSolution, 'F', "fast-hierarchical-solution",
"Find top modules fast. Use -FF to keep all fast levels. Use -FFF to skip recursive part.");
// --------------------- Output options ---------------------
api.addNonOptionArgument(conf.outDirectory, "out_directory",
"The directory to write the results to");
api.addIncrementalOptionArgument(conf.verbosity, 'v', "verbose",
"Verbose output on the console. Add additional 'v' flags to increase verbosity up to -vvv.");
api.parseArgs(argc, argv);
// Some checks
if (*--conf.outDirectory.end() != '/')
conf.outDirectory.append("/");
if (!conf.haveModularResultOutput())
conf.printTree = true;
conf.originallyUndirected = conf.isUndirected();
if (conf.isMemoryNetwork() && !conf.isMultiplexNetwork())
{
conf.teleportToNodes = true;
conf.recordedTeleportation = false;
if (conf.isUndirected())
conf.directed = true;
}
}
void initBenchmark(const Config& conf, int argc, char * const argv[])
{
std::string networkName = FileURI(conf.networkFile).getName();
std::string logFilename = io::Str() << conf.outDirectory << networkName << ".tsv";
Logger::setBenchmarkFilename(logFilename);
std::ostringstream logInfo;
logInfo << "#benchmark for";
for (int i = 0; i < argc; ++i)
logInfo << " " << argv[i];
Logger::benchmark(logInfo.str(), 0, 0, 0, 0, true);
Logger::benchmark("elapsedSeconds\ttag\tcodelength\tnumTopModules\tnumNonTrivialTopModules\ttreeDepth",
0, 0, 0, 0, true);
// (todo: fix problem with initializing same static file from different functions to simplify above)
std::cout << "(Writing benchmark log to '" << logFilename << "'...)\n";
}
int run(int argc, char* argv[])
{
Date startDate;
Config conf;
try
{
getConfig(conf, argc, argv);
if (conf.benchmark)
initBenchmark(conf, argc, argv);
if (conf.verbosity == 0)
conf.verboseNumberPrecision = 4;
std::cout << std::setprecision(conf.verboseNumberPrecision);
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
return 1;
}
std::cout << "===========================================\n";
std::cout << " Infomap v" << INFOMAP_VERSION << " starts at " << Date() << "\n";
std::cout << "===========================================\n";
runInfomap(conf);
ASSERT(NodeBase::nodeCount() == 0); //TODO: Not working with OpenMP
// if (NodeBase::nodeCount() != 0)
// std::cout << "Warning: " << NodeBase::nodeCount() << " nodes not deleted!\n";
std::cout << "===========================================\n";
std::cout << " Infomap ends at " << Date() << "\n";
std::cout << " (Elapsed time: " << (Date() - startDate) << ")\n";
std::cout << "===========================================\n";
// ElapsedTime t1 = (Date() - startDate);
// std::cout << "Elapsed time: " << t1 << " (" <<
// Stopwatch::getElapsedTimeSinceProgramStartInSec() << "s serial)." << std::endl;
return 0;
}
int main(int argc, char* argv[])
{
return run(argc, argv);
}
<commit_msg>Use unrecorded teleportation to nodes if not undirected in multiplex networks.<commit_after>/**********************************************************************************
Infomap software package for multi-level network clustering
Copyright (c) 2013 Daniel Edler, Martin Rosvall
For more information, see <http://www.mapequation.org>
This file is part of Infomap software package.
Infomap software package is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Infomap software package 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Infomap software package. If not, see <http://www.gnu.org/licenses/>.
**********************************************************************************/
#include <iostream>
#include <sstream>
#include <fstream>
#include <stdexcept>
#include "utils/Logger.h"
#include "io/Config.h"
#include "infomap/InfomapContext.h"
#include "utils/Stopwatch.h"
#include "io/ProgramInterface.h"
#include "io/convert.h"
#include "utils/FileURI.h"
#include "utils/Date.h"
#include <iomanip>
#include "io/version.h"
void runInfomap(Config const& config)
{
InfomapContext context(config);
context.getInfomap()->run();
}
void getConfig(Config& conf, int argc, char *argv[])
{
ProgramInterface api("Infomap",
"Implementation of the Infomap clustering algorithm based on the Map Equation (see www.mapequation.org)",
INFOMAP_VERSION);
// --------------------- Input options ---------------------
api.addNonOptionArgument(conf.networkFile, "network_file",
"The file containing the network data. Accepted formats: Pajek (implied by .net) and link list (.txt)");
api.addOptionalNonOptionArguments(conf.additionalInput, "[additional input]",
"More network layers for multiplex.", true);
api.addOptionArgument(conf.inputFormat, 'i', "input-format",
"Specify input format ('pajek', 'link-list', '3gram' or 'multiplex') to override format possibly implied by file extension.", "s");
api.addOptionArgument(conf.withMemory, "with-memory",
"Use second order Markov dynamics and let nodes be part of different modules. Simulate memory from first-order data if not '3gram' input.");
api.addOptionArgument(conf.parseWithoutIOStreams, "without-iostream",
"Parse the input network data without the iostream library. Can be a bit faster, but not as robust.", true);
api.addOptionArgument(conf.zeroBasedNodeNumbers, 'z', "zero-based-numbering",
"Assume node numbers start from zero in the input file instead of one.");
api.addOptionArgument(conf.includeSelfLinks, 'k', "include-self-links",
"Include links with the same source and target node. (Ignored by default.)");
api.addOptionArgument(conf.nodeLimit, 'O', "node-limit",
"Limit the number of nodes to read from the network. Ignore links connected to ignored nodes.", "n", true);
api.addOptionArgument(conf.clusterDataFile, 'c', "cluster-data",
"Provide an initial two-level solution (.clu format).", "p", true);
api.addOptionArgument(conf.noInfomap, "no-infomap",
"Don't run Infomap. Useful if initial cluster data should be preserved or non-modular data printed.", true);
// --------------------- Output options ---------------------
api.addOptionArgument(conf.noFileOutput, '0', "no-file-output",
"Don't print any output to file.", true);
api.addOptionArgument(conf.printMap, "map",
"Print the top two-level modular network in the .map format.");
api.addOptionArgument(conf.printClu, "clu",
"Print the top cluster indices for each node.");
api.addOptionArgument(conf.printTree, "tree",
"Print the hierarchy in .tree format. (default true if no other output with cluster data)");
api.addOptionArgument(conf.printFlowTree, "ftree",
"Print the hierarchy in .tree format and append the hierarchically aggregated network links.", true);
api.addOptionArgument(conf.printBinaryTree, "btree",
"Print the tree in a streamable binary format.", true);
api.addOptionArgument(conf.printBinaryFlowTree, "bftree",
"Print the tree including horizontal flow links in a streamable binary format.");
api.addOptionArgument(conf.printNodeRanks, "node-ranks",
"Print the calculated flow for each node to a file.", true);
api.addOptionArgument(conf.printFlowNetwork, "flow-network",
"Print the network with calculated flow values.", true);
api.addOptionArgument(conf.printPajekNetwork, "pajek",
"Print the parsed network in Pajek format.", true);
api.addOptionArgument(conf.printExpanded, "expanded",
"Print the expanded network of memory nodes if possible.", true);
// --------------------- Core algorithm options ---------------------
api.addOptionArgument(conf.twoLevel, '2', "two-level",
"Optimize a two-level partition of the network.");
bool dummyUndirected;
api.addOptionArgument(dummyUndirected, 'u', "undirected",
"Assume undirected links. (default)");
api.addOptionArgument(conf.directed, 'd', "directed",
"Assume directed links.");
api.addOptionArgument(conf.undirdir, 't', "undirdir",
"Two-mode dynamics: Assume undirected links for calculating flow, but directed when minimizing codelength.");
api.addOptionArgument(conf.outdirdir, "outdirdir",
"Two-mode dynamics: Count only ingoing links when calculating the flow, but all when minimizing codelength.", true);
api.addOptionArgument(conf.rawdir, 'w', "rawdir",
"Two-mode dynamics: Assume directed links and let the raw link weights be the flow.", true);
api.addOptionArgument(conf.recordedTeleportation, 'e', "recorded-teleportation",
"If teleportation is used to calculate the flow, also record it when minimizing codelength.", true);
api.addOptionArgument(conf.teleportToNodes, 'o', "to-nodes",
"Teleport to nodes instead of to links, assuming uniform node weights if no such input data.", true);
api.addOptionArgument(conf.teleportationProbability, 'p', "teleportation-probability",
"The probability of teleporting to a random node or link.", "f", true);
api.addOptionArgument(conf.selfTeleportationProbability, 'y', "self-link-teleportation-probability",
"The probability of teleporting to itself. Effectively increasing the code rate, generating more and smaller modules.", "f", true);
api.addOptionArgument(conf.multiplexAggregationRate, "multiplex-aggregation-rate",
"The probability of following a link as if the layers where completely aggregated. Zero means completely disconnected layers.", "f", true);
api.addOptionArgument(conf.seedToRandomNumberGenerator, 's', "seed",
"A seed (integer) to the random number generator.", "n");
// --------------------- Performance and accuracy options ---------------------
api.addOptionArgument(conf.numTrials, 'N', "num-trials",
"The number of outer-most loops to run before picking the best solution.", "n");
api.addOptionArgument(conf.minimumCodelengthImprovement, 'm', "min-improvement",
"Minimum codelength threshold for accepting a new solution.", "f", true);
api.addOptionArgument(conf.randomizeCoreLoopLimit, 'a', "random-loop-limit",
"Randomize the core loop limit from 1 to 'core-loop-limit'", true);
api.addOptionArgument(conf.coreLoopLimit, 'M', "core-loop-limit",
"Limit the number of loops that tries to move each node into the best possible module", "n", true);
api.addOptionArgument(conf.levelAggregationLimit, 'L', "core-level-limit",
"Limit the number of times the core loops are reapplied on existing modular network to search bigger structures.", "n", true);
api.addOptionArgument(conf.tuneIterationLimit, 'T', "tune-iteration-limit",
"Limit the number of main iterations in the two-level partition algorithm. 0 means no limit.", "n", true);
api.addOptionArgument(conf.minimumRelativeTuneIterationImprovement, 'U', "tune-iteration-threshold",
"Set a codelength improvement threshold of each new tune iteration to 'f' times the initial two-level codelength.", "f", true);
api.addOptionArgument(conf.fastCoarseTunePartition, 'C', "fast-coarse-tune",
"Try to find the quickest partition of each module when creating sub-modules for the coarse-tune part.", true);
api.addOptionArgument(conf.alternateCoarseTuneLevel, 'A', "alternate-coarse-tune-level",
"Try to find different levels of sub-modules to move in the coarse-tune part.", true);
api.addOptionArgument(conf.coarseTuneLevel, 'S', "coarse-tune-level",
"Set the recursion limit when searching for sub-modules. A level of 1 will find sub-sub-modules.", "n", true);
api.addIncrementalOptionArgument(conf.fastHierarchicalSolution, 'F', "fast-hierarchical-solution",
"Find top modules fast. Use -FF to keep all fast levels. Use -FFF to skip recursive part.");
// --------------------- Output options ---------------------
api.addNonOptionArgument(conf.outDirectory, "out_directory",
"The directory to write the results to");
api.addIncrementalOptionArgument(conf.verbosity, 'v', "verbose",
"Verbose output on the console. Add additional 'v' flags to increase verbosity up to -vvv.");
api.parseArgs(argc, argv);
// Some checks
if (*--conf.outDirectory.end() != '/')
conf.outDirectory.append("/");
if (!conf.haveModularResultOutput())
conf.printTree = true;
conf.originallyUndirected = conf.isUndirected();
if (conf.isMemoryNetwork())
{
if (conf.isMultiplexNetwork())
{
if (!conf.isUndirected())
{
conf.teleportToNodes = true;
conf.recordedTeleportation = false;
}
}
else
{
conf.teleportToNodes = true;
conf.recordedTeleportation = false;
if (conf.isUndirected())
conf.directed = true;
}
}
}
void initBenchmark(const Config& conf, int argc, char * const argv[])
{
std::string networkName = FileURI(conf.networkFile).getName();
std::string logFilename = io::Str() << conf.outDirectory << networkName << ".tsv";
Logger::setBenchmarkFilename(logFilename);
std::ostringstream logInfo;
logInfo << "#benchmark for";
for (int i = 0; i < argc; ++i)
logInfo << " " << argv[i];
Logger::benchmark(logInfo.str(), 0, 0, 0, 0, true);
Logger::benchmark("elapsedSeconds\ttag\tcodelength\tnumTopModules\tnumNonTrivialTopModules\ttreeDepth",
0, 0, 0, 0, true);
// (todo: fix problem with initializing same static file from different functions to simplify above)
std::cout << "(Writing benchmark log to '" << logFilename << "'...)\n";
}
int run(int argc, char* argv[])
{
Date startDate;
Config conf;
try
{
getConfig(conf, argc, argv);
if (conf.benchmark)
initBenchmark(conf, argc, argv);
if (conf.verbosity == 0)
conf.verboseNumberPrecision = 4;
std::cout << std::setprecision(conf.verboseNumberPrecision);
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
return 1;
}
std::cout << "===========================================\n";
std::cout << " Infomap v" << INFOMAP_VERSION << " starts at " << Date() << "\n";
std::cout << "===========================================\n";
runInfomap(conf);
ASSERT(NodeBase::nodeCount() == 0); //TODO: Not working with OpenMP
// if (NodeBase::nodeCount() != 0)
// std::cout << "Warning: " << NodeBase::nodeCount() << " nodes not deleted!\n";
std::cout << "===========================================\n";
std::cout << " Infomap ends at " << Date() << "\n";
std::cout << " (Elapsed time: " << (Date() - startDate) << ")\n";
std::cout << "===========================================\n";
// ElapsedTime t1 = (Date() - startDate);
// std::cout << "Elapsed time: " << t1 << " (" <<
// Stopwatch::getElapsedTimeSinceProgramStartInSec() << "s serial)." << std::endl;
return 0;
}
int main(int argc, char* argv[])
{
return run(argc, argv);
}
<|endoftext|>
|
<commit_before>#include "Core/IncludeExcludeInfo.h"
#include "gtest/gtest.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include <fstream>
// FIXME: copied from unittests/Support/Path.cpp
#define ASSERT_NO_ERROR(x) \
if (llvm::error_code ASSERT_NO_ERROR_ec = x) { \
llvm::SmallString<128> MessageStorage; \
llvm::raw_svector_ostream Message(MessageStorage); \
Message << #x ": did not return errc::success.\n" \
<< "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
<< "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
} else { \
}
TEST(IncludeExcludeTest, ParseString) {
IncludeExcludeInfo IEManager;
llvm::error_code Err = IEManager.readListFromString(
/*include=*/ "a,b/b2,c/c2",
/*exclude=*/ "a/af.cpp,a/a2,b/b2/b2f.cpp,c/c2");
ASSERT_EQ(Err, llvm::error_code::success());
// If the file does not appear on the include list then it is not safe to
// transform. Files are not safe to transform by default.
EXPECT_FALSE(IEManager.isFileIncluded("f.cpp"));
EXPECT_FALSE(IEManager.isFileIncluded("b/dir/f.cpp"));
// If the file appears on only the include list then it is safe to transform.
EXPECT_TRUE(IEManager.isFileIncluded("a/f.cpp"));
EXPECT_TRUE(IEManager.isFileIncluded("a/dir/f.cpp"));
EXPECT_TRUE(IEManager.isFileIncluded("b/b2/f.cpp"));
// If the file appears on both the include or exclude list then it is not
// safe to transform.
EXPECT_FALSE(IEManager.isFileIncluded("a/af.cpp"));
EXPECT_FALSE(IEManager.isFileIncluded("a/a2/f.cpp"));
EXPECT_FALSE(IEManager.isFileIncluded("a/a2/dir/f.cpp"));
EXPECT_FALSE(IEManager.isFileIncluded("b/b2/b2f.cpp"));
EXPECT_FALSE(IEManager.isFileIncluded("c/c2/c3/f.cpp"));
}
// Utility for creating and filling files with data for IncludeExcludeFileTest
// tests.
struct InputFiles {
// This function uses fatal assertions. The caller is responsible for making
// sure fatal assertions propagate.
void CreateFiles(bool UnixMode) {
llvm::SmallString<128> Path;
int FD;
ASSERT_NO_ERROR(
llvm::sys::fs::unique_file("include-%%%%%%", FD, Path));
IncludeDataPath = Path.str();
{
llvm::raw_fd_ostream IncludeDataFile(FD, true);
for (unsigned i = 0; i < sizeof(IncludeData) / sizeof(char *); ++i) {
IncludeDataFile << IncludeData[i] << (UnixMode ? "\n" : "\r\n");
}
}
ASSERT_NO_ERROR(
llvm::sys::fs::unique_file("exclude-%%%%%%", FD, Path));
ExcludeDataPath = Path.str();
{
llvm::raw_fd_ostream ExcludeDataFile(FD, true);
for (unsigned i = 0; i < sizeof(ExcludeData) / sizeof(char *); ++i) {
ExcludeDataFile << ExcludeData[i] << (UnixMode ? "\n" : "\r\n");
}
}
}
static const char *IncludeData[3];
static const char *ExcludeData[4];
std::string IncludeDataPath;
std::string ExcludeDataPath;
};
const char *InputFiles::IncludeData[3] = { "a", "b/b2", "c/c2" };
const char *InputFiles::ExcludeData[4] = { "a/af.cpp", "a/a2", "b/b2/b2f.cpp",
"c/c2" };
TEST(IncludeExcludeFileTest, UNIXFile) {
InputFiles UnixFiles;
ASSERT_NO_FATAL_FAILURE(UnixFiles.CreateFiles(/* UnixMode= */true));
IncludeExcludeInfo IEManager;
llvm::error_code Err = IEManager.readListFromFile(
UnixFiles.IncludeDataPath.c_str(), UnixFiles.ExcludeDataPath.c_str());
ASSERT_EQ(Err, llvm::error_code::success());
EXPECT_FALSE(IEManager.isFileIncluded("f.cpp"));
EXPECT_TRUE(IEManager.isFileIncluded("a/f.cpp"));
EXPECT_FALSE(IEManager.isFileIncluded("a/af.cpp"));
}
TEST(IncludeExcludeFileTest, DOSFile) {
InputFiles DOSFiles;
ASSERT_NO_FATAL_FAILURE(DOSFiles.CreateFiles(/* UnixMode= */false));
IncludeExcludeInfo IEManager;
llvm::error_code Err = IEManager.readListFromFile(
DOSFiles.IncludeDataPath.c_str(), DOSFiles.ExcludeDataPath.c_str());
ASSERT_EQ(Err, llvm::error_code::success());
EXPECT_FALSE(IEManager.isFileIncluded("f.cpp"));
EXPECT_TRUE(IEManager.isFileIncluded("a/f.cpp"));
EXPECT_FALSE(IEManager.isFileIncluded("a/af.cpp"));
}
<commit_msg>Use llvm::sys::fs::createTemporaryFile.<commit_after>#include "Core/IncludeExcludeInfo.h"
#include "gtest/gtest.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include <fstream>
// FIXME: copied from unittests/Support/Path.cpp
#define ASSERT_NO_ERROR(x) \
if (llvm::error_code ASSERT_NO_ERROR_ec = x) { \
llvm::SmallString<128> MessageStorage; \
llvm::raw_svector_ostream Message(MessageStorage); \
Message << #x ": did not return errc::success.\n" \
<< "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
<< "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
} else { \
}
TEST(IncludeExcludeTest, ParseString) {
IncludeExcludeInfo IEManager;
llvm::error_code Err = IEManager.readListFromString(
/*include=*/ "a,b/b2,c/c2",
/*exclude=*/ "a/af.cpp,a/a2,b/b2/b2f.cpp,c/c2");
ASSERT_EQ(Err, llvm::error_code::success());
// If the file does not appear on the include list then it is not safe to
// transform. Files are not safe to transform by default.
EXPECT_FALSE(IEManager.isFileIncluded("f.cpp"));
EXPECT_FALSE(IEManager.isFileIncluded("b/dir/f.cpp"));
// If the file appears on only the include list then it is safe to transform.
EXPECT_TRUE(IEManager.isFileIncluded("a/f.cpp"));
EXPECT_TRUE(IEManager.isFileIncluded("a/dir/f.cpp"));
EXPECT_TRUE(IEManager.isFileIncluded("b/b2/f.cpp"));
// If the file appears on both the include or exclude list then it is not
// safe to transform.
EXPECT_FALSE(IEManager.isFileIncluded("a/af.cpp"));
EXPECT_FALSE(IEManager.isFileIncluded("a/a2/f.cpp"));
EXPECT_FALSE(IEManager.isFileIncluded("a/a2/dir/f.cpp"));
EXPECT_FALSE(IEManager.isFileIncluded("b/b2/b2f.cpp"));
EXPECT_FALSE(IEManager.isFileIncluded("c/c2/c3/f.cpp"));
}
// Utility for creating and filling files with data for IncludeExcludeFileTest
// tests.
struct InputFiles {
// This function uses fatal assertions. The caller is responsible for making
// sure fatal assertions propagate.
void CreateFiles(bool UnixMode) {
llvm::SmallString<128> Path;
int FD;
ASSERT_NO_ERROR(
llvm::sys::fs::createTemporaryFile("include", "", FD, Path));
IncludeDataPath = Path.str();
{
llvm::raw_fd_ostream IncludeDataFile(FD, true);
for (unsigned i = 0; i < sizeof(IncludeData) / sizeof(char *); ++i) {
IncludeDataFile << IncludeData[i] << (UnixMode ? "\n" : "\r\n");
}
}
ASSERT_NO_ERROR(
llvm::sys::fs::createTemporaryFile("exclude", "", FD, Path));
ExcludeDataPath = Path.str();
{
llvm::raw_fd_ostream ExcludeDataFile(FD, true);
for (unsigned i = 0; i < sizeof(ExcludeData) / sizeof(char *); ++i) {
ExcludeDataFile << ExcludeData[i] << (UnixMode ? "\n" : "\r\n");
}
}
}
static const char *IncludeData[3];
static const char *ExcludeData[4];
std::string IncludeDataPath;
std::string ExcludeDataPath;
};
const char *InputFiles::IncludeData[3] = { "a", "b/b2", "c/c2" };
const char *InputFiles::ExcludeData[4] = { "a/af.cpp", "a/a2", "b/b2/b2f.cpp",
"c/c2" };
TEST(IncludeExcludeFileTest, UNIXFile) {
InputFiles UnixFiles;
ASSERT_NO_FATAL_FAILURE(UnixFiles.CreateFiles(/* UnixMode= */true));
IncludeExcludeInfo IEManager;
llvm::error_code Err = IEManager.readListFromFile(
UnixFiles.IncludeDataPath.c_str(), UnixFiles.ExcludeDataPath.c_str());
ASSERT_EQ(Err, llvm::error_code::success());
EXPECT_FALSE(IEManager.isFileIncluded("f.cpp"));
EXPECT_TRUE(IEManager.isFileIncluded("a/f.cpp"));
EXPECT_FALSE(IEManager.isFileIncluded("a/af.cpp"));
}
TEST(IncludeExcludeFileTest, DOSFile) {
InputFiles DOSFiles;
ASSERT_NO_FATAL_FAILURE(DOSFiles.CreateFiles(/* UnixMode= */false));
IncludeExcludeInfo IEManager;
llvm::error_code Err = IEManager.readListFromFile(
DOSFiles.IncludeDataPath.c_str(), DOSFiles.ExcludeDataPath.c_str());
ASSERT_EQ(Err, llvm::error_code::success());
EXPECT_FALSE(IEManager.isFileIncluded("f.cpp"));
EXPECT_TRUE(IEManager.isFileIncluded("a/f.cpp"));
EXPECT_FALSE(IEManager.isFileIncluded("a/af.cpp"));
}
<|endoftext|>
|
<commit_before>#ifndef AL_AMBIFILEPLAYER_H
#define AL_AMBIFILEPLAYER_H
#include "allocore/sound/al_Ambisonics.hpp"
#include "allocore/sound/al_Speaker.hpp"
#include "allocore/io/al_AudioIOData.hpp"
#include "allocore/system/al_Parameter.hpp"
#include "alloaudio/al_SoundfileBuffered.hpp"
#include "alloaudio/al_AmbiTunedDecoder.hpp"
#include "alloaudio/al_AmbisonicsConfig.hpp"
namespace al {
using namespace std;
/// \addtogroup alloaudio
/// @{
///
/// \brief A class to play back Ambisonics encoded (B-format) audio files
///
class AmbiFilePlayer : public AudioCallback, public SoundFileBuffered
{
public:
///
/// \brief AmbiFilePlayer constructor
/// \param fullPath full path to the b-format audio file
/// \param loop true if file should start over when it reaches the end
/// \param bufferFrames Number of frames in the audio file read buffer. Increase if experiencing dropouts
/// \param layout the speaker layout for decoding
///
AmbiFilePlayer(std::string fullPath, bool loop, int bufferFrames,
SpeakerLayout &layout);
///
/// \param fullPath full path to the b-format audio file
/// \param loop true if file should start over when it reaches the end
/// \param bufferFrames Number of frames in the audio file read buffer. Increase if experiencing dropouts
/// \param configPath path to the .ambdec ambisonics configuration file. If empty the file "Ambisonics.ambdec" is used.
///
AmbiFilePlayer(std::string fullPath, bool loop, int bufferFrames,
string configPath);
~AmbiFilePlayer();
virtual void onAudioCB(AudioIOData& io) override;
///
/// \brief Check whether file has been played fully
/// \return true if file has played to the end
///
bool done() const;
void setDone(bool done);
private:
int getFileDimensions();
int getFileOrder();
// Internal
AmbiDecode *mDecoder;
float *mReadBuffer;
float *mDeinterleavedBuffer;
bool mDone;
int mBufferSize;
//Parameters
Parameter mGain;
};
/// @}
}
#endif // AL_AMBIFILEPLAYER_H
<commit_msg>Removed override keyword to attempt to fix travis build<commit_after>#ifndef AL_AMBIFILEPLAYER_H
#define AL_AMBIFILEPLAYER_H
#include "allocore/sound/al_Ambisonics.hpp"
#include "allocore/sound/al_Speaker.hpp"
#include "allocore/io/al_AudioIOData.hpp"
#include "allocore/system/al_Parameter.hpp"
#include "alloaudio/al_SoundfileBuffered.hpp"
#include "alloaudio/al_AmbiTunedDecoder.hpp"
#include "alloaudio/al_AmbisonicsConfig.hpp"
namespace al {
using namespace std;
/// \addtogroup alloaudio
/// @{
///
/// \brief A class to play back Ambisonics encoded (B-format) audio files
///
class AmbiFilePlayer : public AudioCallback, public SoundFileBuffered
{
public:
///
/// \brief AmbiFilePlayer constructor
/// \param fullPath full path to the b-format audio file
/// \param loop true if file should start over when it reaches the end
/// \param bufferFrames Number of frames in the audio file read buffer. Increase if experiencing dropouts
/// \param layout the speaker layout for decoding
///
AmbiFilePlayer(std::string fullPath, bool loop, int bufferFrames,
SpeakerLayout &layout);
///
/// \param fullPath full path to the b-format audio file
/// \param loop true if file should start over when it reaches the end
/// \param bufferFrames Number of frames in the audio file read buffer. Increase if experiencing dropouts
/// \param configPath path to the .ambdec ambisonics configuration file. If empty the file "Ambisonics.ambdec" is used.
///
AmbiFilePlayer(std::string fullPath, bool loop, int bufferFrames,
string configPath);
~AmbiFilePlayer();
virtual void onAudioCB(AudioIOData& io) /*override*/;
///
/// \brief Check whether file has been played fully
/// \return true if file has played to the end
///
bool done() const;
void setDone(bool done);
private:
int getFileDimensions();
int getFileOrder();
// Internal
AmbiDecode *mDecoder;
float *mReadBuffer;
float *mDeinterleavedBuffer;
bool mDone;
int mBufferSize;
//Parameters
Parameter mGain;
};
/// @}
}
#endif // AL_AMBIFILEPLAYER_H
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <iostream>
#include "allocore/system/al_PeriodicThread.hpp"
namespace al{
PeriodicThread::PeriodicThread(double periodSec)
: mAutocorrect(0.1),
mUserData(nullptr)
{
period(periodSec);
}
PeriodicThread::PeriodicThread(const PeriodicThread& o)
: Thread(o), mPeriod(o.mPeriod), mTimeCurr(o.mTimeCurr),
mTimePrev(o.mTimePrev), mWait(o.mWait), mTimeBehind(o.mTimeBehind),
mAutocorrect(o.mAutocorrect),
mUserFunc(o.mUserFunc),
mUserData(nullptr),
mRun(o.mRun)
{}
void * PeriodicThread::sPeriodicFunc(void * threadData){
static_cast<PeriodicThread *>(threadData)->go();
return nullptr;
}
PeriodicThread& PeriodicThread::autocorrect(float factor){
mAutocorrect=factor;
return *this;
}
PeriodicThread& PeriodicThread::period(double sec){
mPeriod=sec * 1e9;
return *this;
}
bool :PeriodicThread::running() const
{
return mRun;
}
double PeriodicThread::period() const {
return mPeriod * 1e-9;
}
void PeriodicThread::start(ThreadFunction& func){
if(mRun) {
stop();
}
mFunction = nullptr;
mUserFunc = &func;
mUserData = nullptr;
mRun = true;
Thread::start(sPeriodicFunc, this);
}
void PeriodicThread::start(std::function<void(void *data)> function, void *userData){
if(mRun) {
stop();
}
mUserFunc = nullptr;
mFunction = function;
mUserData = userData;
mRun = true;
Thread::start(sPeriodicFunc, this);
}
void PeriodicThread::stop(){
mRun = false;
Thread::join();
mUserFunc = nullptr;
mFunction = nullptr;
mUserData = nullptr;
}
void swap(PeriodicThread& a, PeriodicThread& b){
using std::swap;
swap(static_cast<Thread&>(a), static_cast<Thread&>(b));
#define SWAP_(x) swap(a.x, b.x);
SWAP_(mPeriod);
SWAP_(mTimeCurr);
SWAP_(mTimePrev);
SWAP_(mWait);
SWAP_(mUserFunc);
SWAP_(mRun);
#undef SWAP_
}
PeriodicThread& PeriodicThread::operator= (PeriodicThread other){
swap(*this, other);
return *this;
}
void PeriodicThread::go(){
// Note: times are al_nsec (long long int)
mTimeCurr = al_steady_time_nsec();
mWait = 0;
mTimeBehind = 0;
al_nsec granularity = 1e6;
while(mRun){
if (mUserFunc) {
(*mUserFunc)();
} else if(mFunction) {
mFunction(mUserData);
}
mTimePrev = mTimeCurr + mWait;
mTimeCurr = al_steady_time_nsec();
al_nsec dt = mTimeCurr - mTimePrev;
// dt -> t_curr - (t_prev + wait)
// The wait amount is the ideal period minus the actual amount
// of time spent processing between iterations
if(dt<mPeriod){
mWait = mPeriod - dt;
al_nsec waitTime = mWait;
while (waitTime > granularity && mRun) {
al_sleep_nsec(granularity);
waitTime -= granularity;
}
// TODO compensate for drift from granularity
if (mRun) {
al_sleep_nsec(waitTime);
}
}
// This means we are behind, so don't wait
else{
mWait = 0;
mTimeBehind += dt - mPeriod;
}
if(mTimeBehind > 0){
al_nsec comp = mPeriod*mAutocorrect;
if(mTimeBehind < comp){
comp = mTimeBehind;
mTimeBehind = 0;
}
else{
mTimeBehind -= comp;
}
mWait -= comp;
}
//printf("period=%g, dt=%g, wait=%g\n", mPeriod, dt, mWait);
}
}
} // al::
<commit_msg>Fixed typo<commit_after>#include <algorithm>
#include <iostream>
#include "allocore/system/al_PeriodicThread.hpp"
namespace al{
PeriodicThread::PeriodicThread(double periodSec)
: mAutocorrect(0.1),
mUserData(nullptr)
{
period(periodSec);
}
PeriodicThread::PeriodicThread(const PeriodicThread& o)
: Thread(o), mPeriod(o.mPeriod), mTimeCurr(o.mTimeCurr),
mTimePrev(o.mTimePrev), mWait(o.mWait), mTimeBehind(o.mTimeBehind),
mAutocorrect(o.mAutocorrect),
mUserFunc(o.mUserFunc),
mUserData(nullptr),
mRun(o.mRun)
{}
void * PeriodicThread::sPeriodicFunc(void * threadData){
static_cast<PeriodicThread *>(threadData)->go();
return nullptr;
}
PeriodicThread& PeriodicThread::autocorrect(float factor){
mAutocorrect=factor;
return *this;
}
PeriodicThread& PeriodicThread::period(double sec){
mPeriod=sec * 1e9;
return *this;
}
bool PeriodicThread::running() const
{
return mRun;
}
double PeriodicThread::period() const {
return mPeriod * 1e-9;
}
void PeriodicThread::start(ThreadFunction& func){
if(mRun) {
stop();
}
mFunction = nullptr;
mUserFunc = &func;
mUserData = nullptr;
mRun = true;
Thread::start(sPeriodicFunc, this);
}
void PeriodicThread::start(std::function<void(void *data)> function, void *userData){
if(mRun) {
stop();
}
mUserFunc = nullptr;
mFunction = function;
mUserData = userData;
mRun = true;
Thread::start(sPeriodicFunc, this);
}
void PeriodicThread::stop(){
mRun = false;
Thread::join();
mUserFunc = nullptr;
mFunction = nullptr;
mUserData = nullptr;
}
void swap(PeriodicThread& a, PeriodicThread& b){
using std::swap;
swap(static_cast<Thread&>(a), static_cast<Thread&>(b));
#define SWAP_(x) swap(a.x, b.x);
SWAP_(mPeriod);
SWAP_(mTimeCurr);
SWAP_(mTimePrev);
SWAP_(mWait);
SWAP_(mUserFunc);
SWAP_(mRun);
#undef SWAP_
}
PeriodicThread& PeriodicThread::operator= (PeriodicThread other){
swap(*this, other);
return *this;
}
void PeriodicThread::go(){
// Note: times are al_nsec (long long int)
mTimeCurr = al_steady_time_nsec();
mWait = 0;
mTimeBehind = 0;
al_nsec granularity = 1e6;
while(mRun){
if (mUserFunc) {
(*mUserFunc)();
} else if(mFunction) {
mFunction(mUserData);
}
mTimePrev = mTimeCurr + mWait;
mTimeCurr = al_steady_time_nsec();
al_nsec dt = mTimeCurr - mTimePrev;
// dt -> t_curr - (t_prev + wait)
// The wait amount is the ideal period minus the actual amount
// of time spent processing between iterations
if(dt<mPeriod){
mWait = mPeriod - dt;
al_nsec waitTime = mWait;
while (waitTime > granularity && mRun) {
al_sleep_nsec(granularity);
waitTime -= granularity;
}
// TODO compensate for drift from granularity
if (mRun) {
al_sleep_nsec(waitTime);
}
}
// This means we are behind, so don't wait
else{
mWait = 0;
mTimeBehind += dt - mPeriod;
}
if(mTimeBehind > 0){
al_nsec comp = mPeriod*mAutocorrect;
if(mTimeBehind < comp){
comp = mTimeBehind;
mTimeBehind = 0;
}
else{
mTimeBehind -= comp;
}
mWait -= comp;
}
//printf("period=%g, dt=%g, wait=%g\n", mPeriod, dt, mWait);
}
}
} // al::
<|endoftext|>
|
<commit_before>#ifndef AMGCL_COARSENING_SMOOTHED_AGGREGATION_HPP
#define AMGCL_COARSENING_SMOOTHED_AGGREGATION_HPP
/*
The MIT License
Copyright (c) 2012-2014 Denis Demidov <dennis.demidov@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* \file amgcl/coarsening/smoothed_aggregation.hpp
* \author Denis Demidov <dennis.demidov@gmail.com>
* \brief Smoothed aggregation coarsening scheme.
*/
#include <boost/tuple/tuple.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/range/numeric.hpp>
#include <amgcl/backend/builtin.hpp>
#include <amgcl/coarsening/detail/galerkin.hpp>
#include <amgcl/coarsening/tentative_prolongation.hpp>
#include <amgcl/util.hpp>
namespace amgcl {
namespace coarsening {
/// Smoothed aggregation coarsening.
/**
* \param Aggregates \ref aggregates formation.
* \ingroup coarsening
* \sa \cite Vanek1996
*/
template <class Aggregates>
struct smoothed_aggregation {
/// Coarsening parameters
struct params {
/// Aggregation parameters.
typename Aggregates::params aggr;
/// Near nullspace parameters.
nullspace_params nullspace;
/// Relaxation factor \f$\omega\f$.
/**
* Piecewise constant prolongation \f$\tilde P\f$ from non-smoothed
* aggregation is improved by a smoothing to get the final prolongation
* matrix \f$P\f$. Simple Jacobi smoother is used here, giving the
* prolongation matrix
* \f[P = \left( I - \omega D^{-1} A^F \right) \tilde P.\f]
* Here \f$A^F = (a_{ij}^F)\f$ is the filtered matrix given by
* \f[
* a_{ij}^F =
* \begin{cases}
* a_{ij} \quad \text{if} \; j \in N_i\\
* 0 \quad \text{otherwise}
* \end{cases}, \quad \text{if}\; i \neq j,
* \quad a_{ii}^F = a_{ii} - \sum\limits_{j=1,j\neq i}^n
* \left(a_{ij} - a_{ij}^F \right),
* \f]
* where \f$N_i\f$ is the set of variables, strongly coupled to
* variable \f$i\f$, and \f$D\f$ denotes the diagonal of \f$A^F\f$.
*/
float relax;
params() : relax(0.666f) { }
params(const boost::property_tree::ptree &p)
: AMGCL_PARAMS_IMPORT_CHILD(p, aggr),
AMGCL_PARAMS_IMPORT_CHILD(p, nullspace),
AMGCL_PARAMS_IMPORT_VALUE(p, relax)
{ }
};
/// \copydoc amgcl::coarsening::aggregation::transfer_operators
template <class Matrix>
static boost::tuple< boost::shared_ptr<Matrix>, boost::shared_ptr<Matrix> >
transfer_operators(const Matrix &A, params &prm)
{
typedef typename backend::value_type<Matrix>::type Val;
const size_t n = rows(A);
TIC("aggregates");
Aggregates aggr(A, prm.aggr);
prm.aggr.eps_strong *= 0.5;
TOC("aggregates");
TIC("interpolation");
boost::shared_ptr<Matrix> P_tent = tentative_prolongation<Matrix>(
n, aggr.count, aggr.id, prm.nullspace
);
boost::shared_ptr<Matrix> P = boost::make_shared<Matrix>();
P->nrows = rows(*P_tent);
P->ncols = cols(*P_tent);
P->ptr.resize(n + 1, 0);
#pragma omp parallel
{
std::vector<ptrdiff_t> marker(aggr.count, -1);
#ifdef _OPENMP
int nt = omp_get_num_threads();
int tid = omp_get_thread_num();
size_t chunk_size = (n + nt - 1) / nt;
size_t chunk_start = tid * chunk_size;
size_t chunk_end = std::min(n, chunk_start + chunk_size);
#else
size_t chunk_start = 0;
size_t chunk_end = n;
#endif
// Count number of entries in P.
for(ptrdiff_t i = chunk_start; i < chunk_end; ++i) {
for(ptrdiff_t ja = A.ptr[i], ea = A.ptr[i+1]; ja < ea; ++ja) {
ptrdiff_t ca = A.col[ja];
// Skip weak off-diagonal connections.
if (ca != i && !aggr.strong_connection[ja])
continue;
for(ptrdiff_t jp = P_tent->ptr[ca], ep = P_tent->ptr[ca+1]; jp < ep; ++jp) {
ptrdiff_t cp = P_tent->col[jp];
if (marker[cp] != i) {
marker[cp] = i;
++( P->ptr[i + 1] );
}
}
}
}
boost::fill(marker, -1);
#pragma omp barrier
#pragma omp single
{
boost::partial_sum(P->ptr, P->ptr.begin());
P->col.resize(P->ptr.back());
P->val.resize(P->ptr.back());
}
// Fill the interpolation matrix.
for(ptrdiff_t i = chunk_start; i < chunk_end; ++i) {
// Diagonal of the filtered matrix is the original matrix
// diagonal minus its weak connections.
Val dia = 0;
for(ptrdiff_t j = A.ptr[i], e = A.ptr[i+1]; j < e; ++j) {
if (static_cast<size_t>(A.col[j]) == i)
dia += A.val[j];
else if (!aggr.strong_connection[j])
dia -= A.val[j];
}
dia = 1 / dia;
ptrdiff_t row_beg = P->ptr[i];
ptrdiff_t row_end = row_beg;
for(ptrdiff_t ja = A.ptr[i], ea = A.ptr[i + 1]; ja < ea; ++ja) {
ptrdiff_t ca = A.col[ja];
// Skip weak off-diagonal connections.
if (ca != i && !aggr.strong_connection[ja]) continue;
Val va = (ca == i) ? 1 - prm.relax : -prm.relax * dia * A.val[ja];
for(ptrdiff_t jp = P_tent->ptr[ca], ep = P_tent->ptr[ca+1]; jp < ep; ++jp) {
ptrdiff_t cp = P_tent->col[jp];
if (marker[cp] < row_beg) {
marker[cp] = row_end;
P->col[row_end] = cp;
P->val[row_end] = va;
++row_end;
} else {
P->val[ marker[cp] ] += va;
}
}
}
}
}
TOC("interpolation");
boost::shared_ptr<Matrix> R = boost::make_shared<Matrix>();
*R = transpose(*P);
return boost::make_tuple(P, R);
}
/// \copydoc amgcl::coarsening::aggregation::coarse_operator
template <class Matrix>
static boost::shared_ptr<Matrix>
coarse_operator(
const Matrix &A,
const Matrix &P,
const Matrix &R,
const params&
)
{
return detail::galerkin(A, P, R);
}
};
} // namespace coarsening
} // namespace amgcl
#endif
<commit_msg>Get rid of sign mismatch warnings<commit_after>#ifndef AMGCL_COARSENING_SMOOTHED_AGGREGATION_HPP
#define AMGCL_COARSENING_SMOOTHED_AGGREGATION_HPP
/*
The MIT License
Copyright (c) 2012-2014 Denis Demidov <dennis.demidov@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* \file amgcl/coarsening/smoothed_aggregation.hpp
* \author Denis Demidov <dennis.demidov@gmail.com>
* \brief Smoothed aggregation coarsening scheme.
*/
#include <boost/tuple/tuple.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/range/numeric.hpp>
#include <amgcl/backend/builtin.hpp>
#include <amgcl/coarsening/detail/galerkin.hpp>
#include <amgcl/coarsening/tentative_prolongation.hpp>
#include <amgcl/util.hpp>
namespace amgcl {
namespace coarsening {
/// Smoothed aggregation coarsening.
/**
* \param Aggregates \ref aggregates formation.
* \ingroup coarsening
* \sa \cite Vanek1996
*/
template <class Aggregates>
struct smoothed_aggregation {
/// Coarsening parameters
struct params {
/// Aggregation parameters.
typename Aggregates::params aggr;
/// Near nullspace parameters.
nullspace_params nullspace;
/// Relaxation factor \f$\omega\f$.
/**
* Piecewise constant prolongation \f$\tilde P\f$ from non-smoothed
* aggregation is improved by a smoothing to get the final prolongation
* matrix \f$P\f$. Simple Jacobi smoother is used here, giving the
* prolongation matrix
* \f[P = \left( I - \omega D^{-1} A^F \right) \tilde P.\f]
* Here \f$A^F = (a_{ij}^F)\f$ is the filtered matrix given by
* \f[
* a_{ij}^F =
* \begin{cases}
* a_{ij} \quad \text{if} \; j \in N_i\\
* 0 \quad \text{otherwise}
* \end{cases}, \quad \text{if}\; i \neq j,
* \quad a_{ii}^F = a_{ii} - \sum\limits_{j=1,j\neq i}^n
* \left(a_{ij} - a_{ij}^F \right),
* \f]
* where \f$N_i\f$ is the set of variables, strongly coupled to
* variable \f$i\f$, and \f$D\f$ denotes the diagonal of \f$A^F\f$.
*/
float relax;
params() : relax(0.666f) { }
params(const boost::property_tree::ptree &p)
: AMGCL_PARAMS_IMPORT_CHILD(p, aggr),
AMGCL_PARAMS_IMPORT_CHILD(p, nullspace),
AMGCL_PARAMS_IMPORT_VALUE(p, relax)
{ }
};
/// \copydoc amgcl::coarsening::aggregation::transfer_operators
template <class Matrix>
static boost::tuple< boost::shared_ptr<Matrix>, boost::shared_ptr<Matrix> >
transfer_operators(const Matrix &A, params &prm)
{
typedef typename backend::value_type<Matrix>::type Val;
const size_t n = rows(A);
TIC("aggregates");
Aggregates aggr(A, prm.aggr);
prm.aggr.eps_strong *= 0.5;
TOC("aggregates");
TIC("interpolation");
boost::shared_ptr<Matrix> P_tent = tentative_prolongation<Matrix>(
n, aggr.count, aggr.id, prm.nullspace
);
boost::shared_ptr<Matrix> P = boost::make_shared<Matrix>();
P->nrows = rows(*P_tent);
P->ncols = cols(*P_tent);
P->ptr.resize(n + 1, 0);
#pragma omp parallel
{
std::vector<ptrdiff_t> marker(aggr.count, -1);
#ifdef _OPENMP
int nt = omp_get_num_threads();
int tid = omp_get_thread_num();
ptrdiff_t chunk_size = (n + nt - 1) / nt;
ptrdiff_t chunk_start = tid * chunk_size;
ptrdiff_t chunk_end = std::min<ptrdiff_t>(n, chunk_start + chunk_size);
#else
ptrdiff_t chunk_start = 0;
ptrdiff_t chunk_end = n;
#endif
// Count number of entries in P.
for(ptrdiff_t i = chunk_start; i < chunk_end; ++i) {
for(ptrdiff_t ja = A.ptr[i], ea = A.ptr[i+1]; ja < ea; ++ja) {
ptrdiff_t ca = A.col[ja];
// Skip weak off-diagonal connections.
if (ca != i && !aggr.strong_connection[ja])
continue;
for(ptrdiff_t jp = P_tent->ptr[ca], ep = P_tent->ptr[ca+1]; jp < ep; ++jp) {
ptrdiff_t cp = P_tent->col[jp];
if (marker[cp] != i) {
marker[cp] = i;
++( P->ptr[i + 1] );
}
}
}
}
boost::fill(marker, -1);
#pragma omp barrier
#pragma omp single
{
boost::partial_sum(P->ptr, P->ptr.begin());
P->col.resize(P->ptr.back());
P->val.resize(P->ptr.back());
}
// Fill the interpolation matrix.
for(ptrdiff_t i = chunk_start; i < chunk_end; ++i) {
// Diagonal of the filtered matrix is the original matrix
// diagonal minus its weak connections.
Val dia = 0;
for(ptrdiff_t j = A.ptr[i], e = A.ptr[i+1]; j < e; ++j) {
if (A.col[j] == i)
dia += A.val[j];
else if (!aggr.strong_connection[j])
dia -= A.val[j];
}
dia = 1 / dia;
ptrdiff_t row_beg = P->ptr[i];
ptrdiff_t row_end = row_beg;
for(ptrdiff_t ja = A.ptr[i], ea = A.ptr[i + 1]; ja < ea; ++ja) {
ptrdiff_t ca = A.col[ja];
// Skip weak off-diagonal connections.
if (ca != i && !aggr.strong_connection[ja]) continue;
Val va = (ca == i) ? 1 - prm.relax : -prm.relax * dia * A.val[ja];
for(ptrdiff_t jp = P_tent->ptr[ca], ep = P_tent->ptr[ca+1]; jp < ep; ++jp) {
ptrdiff_t cp = P_tent->col[jp];
if (marker[cp] < row_beg) {
marker[cp] = row_end;
P->col[row_end] = cp;
P->val[row_end] = va;
++row_end;
} else {
P->val[ marker[cp] ] += va;
}
}
}
}
}
TOC("interpolation");
boost::shared_ptr<Matrix> R = boost::make_shared<Matrix>();
*R = transpose(*P);
return boost::make_tuple(P, R);
}
/// \copydoc amgcl::coarsening::aggregation::coarse_operator
template <class Matrix>
static boost::shared_ptr<Matrix>
coarse_operator(
const Matrix &A,
const Matrix &P,
const Matrix &R,
const params&
)
{
return detail::galerkin(A, P, R);
}
};
} // namespace coarsening
} // namespace amgcl
#endif
<|endoftext|>
|
<commit_before>/**
* \file standard_gaussian.hpp
* \date May 2014
* \author Jan Issac (jan.issac@gmail.com)
* \author Manuel Wuthrich (manuel.wuthrich@gmail.com)
*/
#ifndef FL__DISTRIBUTION__STANDARD_GAUSSIAN_HPP
#define FL__DISTRIBUTION__STANDARD_GAUSSIAN_HPP
#include <Eigen/Dense>
#include <random>
#include <type_traits>
#include <fl/util/math.hpp>
#include <fl/util/random.hpp>
#include <fl/util/traits.hpp>
#include <fl/util/types.hpp>
#include <fl/distribution/interface/sampling.hpp>
#include <fl/distribution/interface/moments.hpp>
#include <fl/exception/exception.hpp>
namespace fl
{
/**
* \ingroup distributions
*/
template <typename StandardVariate>
class StandardGaussian
: public Sampling<StandardVariate>,
public Moments<
StandardVariate,
typename DiagonalSecondMomentOf<StandardVariate>::Type>
{
public:
typedef StandardVariate Variate;
typedef Moments<
StandardVariate,
typename DiagonalSecondMomentOf<StandardVariate>::Type
> MomentsBase;
typedef typename MomentsBase::SecondMoment SecondMoment;
typedef typename MomentsBase::SecondMoment DiagonalSecondMoment;
public:
explicit
StandardGaussian(int dim = DimensionOf<StandardVariate>())
: dimension_ (dim),
mu_(Variate::Zero(dim, 1)),
cov_(DiagonalSecondMoment(dim)),
generator_(fl::seed()),
gaussian_distribution_(0.0, 1.0)
{
cov_.setIdentity();
}
virtual ~StandardGaussian() { }
virtual StandardVariate sample() const
{
StandardVariate gaussian_sample(dimension(), 1);
for (int i = 0; i < dimension_; i++)
{
gaussian_sample(i, 0) = gaussian_distribution_(generator_);
}
return gaussian_sample;
}
virtual int dimension() const
{
return dimension_;
}
virtual void dimension(int new_dimension)
{
if (dimension_ == new_dimension) return;
if (fl::IsFixed<StandardVariate::SizeAtCompileTime>())
{
fl_throw(
fl::ResizingFixedSizeEntityException(dimension_,
new_dimension,
"Gaussian"));
}
dimension_ = new_dimension;
}
virtual const Variate& mean() const
{
return mu_;
}
virtual const DiagonalSecondMoment& covariance() const
{
return cov_;
}
private:
int dimension_;
Variate mu_;
DiagonalSecondMoment cov_;
mutable fl::mt11213b generator_;
mutable std::normal_distribution<Real> gaussian_distribution_;
};
/**
* Floating point implementation for Scalar types float, double and long double
*/
template <>
class StandardGaussian<Real>
: public Sampling<Real>,
public Moments<Real, Real>
{
public:
StandardGaussian()
: mu_(0),
var_(1),
generator_(fl::seed()),
gaussian_distribution_(mu_, var_)
{ }
Real sample() const
{
return gaussian_distribution_(generator_);
}
virtual const Real& mean() const
{
return mu_;
}
virtual const Real& covariance() const
{
return var_;
}
protected:
const Real mu_;
const Real var_;
mutable fl::mt11213b generator_;
mutable std::normal_distribution<Real> gaussian_distribution_;
};
}
#endif
<commit_msg>removed const members to avoid implicit deletion of copy constructor and assignment operator<commit_after>/**
* \file standard_gaussian.hpp
* \date May 2014
* \author Jan Issac (jan.issac@gmail.com)
* \author Manuel Wuthrich (manuel.wuthrich@gmail.com)
*/
#ifndef FL__DISTRIBUTION__STANDARD_GAUSSIAN_HPP
#define FL__DISTRIBUTION__STANDARD_GAUSSIAN_HPP
#include <Eigen/Dense>
#include <random>
#include <type_traits>
#include <fl/util/math.hpp>
#include <fl/util/random.hpp>
#include <fl/util/traits.hpp>
#include <fl/util/types.hpp>
#include <fl/distribution/interface/sampling.hpp>
#include <fl/distribution/interface/moments.hpp>
#include <fl/exception/exception.hpp>
namespace fl
{
/**
* \ingroup distributions
*/
template <typename StandardVariate>
class StandardGaussian
: public Sampling<StandardVariate>,
public Moments<
StandardVariate,
typename DiagonalSecondMomentOf<StandardVariate>::Type>
{
public:
typedef StandardVariate Variate;
typedef Moments<
StandardVariate,
typename DiagonalSecondMomentOf<StandardVariate>::Type
> MomentsBase;
typedef typename MomentsBase::SecondMoment SecondMoment;
typedef typename MomentsBase::SecondMoment DiagonalSecondMoment;
public:
explicit
StandardGaussian(int dim = DimensionOf<StandardVariate>())
: dimension_ (dim),
mu_(Variate::Zero(dim, 1)),
cov_(DiagonalSecondMoment(dim)),
generator_(fl::seed()),
gaussian_distribution_(0.0, 1.0)
{
cov_.setIdentity();
}
virtual ~StandardGaussian() { }
virtual StandardVariate sample() const
{
StandardVariate gaussian_sample(dimension(), 1);
for (int i = 0; i < dimension_; i++)
{
gaussian_sample(i, 0) = gaussian_distribution_(generator_);
}
return gaussian_sample;
}
virtual int dimension() const
{
return dimension_;
}
virtual void dimension(int new_dimension)
{
if (dimension_ == new_dimension) return;
if (fl::IsFixed<StandardVariate::SizeAtCompileTime>())
{
fl_throw(
fl::ResizingFixedSizeEntityException(dimension_,
new_dimension,
"Gaussian"));
}
dimension_ = new_dimension;
}
virtual const Variate& mean() const
{
return mu_;
}
virtual const DiagonalSecondMoment& covariance() const
{
return cov_;
}
protected:
int dimension_;
Variate mu_;
DiagonalSecondMoment cov_;
mutable fl::mt11213b generator_;
mutable std::normal_distribution<Real> gaussian_distribution_;
};
/**
* Floating point implementation for Scalar types float, double and long double
*/
template <>
class StandardGaussian<Real>
: public Sampling<Real>,
public Moments<Real, Real>
{
public:
StandardGaussian()
: mu_(0.),
var_(1.),
generator_(fl::seed()),
gaussian_distribution_(mu_, var_)
{ }
Real sample() const
{
return gaussian_distribution_(generator_);
}
virtual const Real& mean() const
{
return mu_;
}
virtual const Real& covariance() const
{
return var_;
}
protected:
Real mu_;
Real var_;
mutable fl::mt11213b generator_;
mutable std::normal_distribution<Real> gaussian_distribution_;
};
}
#endif
<|endoftext|>
|
<commit_before>/*ckwg +5
* Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "modules.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/foreach.hpp>
#include <string>
#include <vector>
#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#else
#include <dlfcn.h>
#endif
/**
* \file modules.cxx
*
* \brief Implementation of module loading.
*/
namespace vistk
{
namespace
{
#if defined(_WIN32) || defined(_WIN64)
typedef HMODULE library_t;
typedef FARPROC function_t;
#else
typedef void* library_t;
typedef void* function_t;
#endif
typedef void (*load_module_t)();
typedef char const* envvar_name_t;
#if defined(_WIN32) || defined(_WIN64)
typedef char* envvar_value_t;
#else
typedef char const* envvar_value_t;
#endif
typedef std::string module_path_t;
typedef std::vector<module_path_t> module_paths_t;
typedef std::string lib_suffix_t;
typedef std::string function_name_t;
}
static void load_from_module(module_path_t const path);
static bool is_separator(char ch);
static function_name_t const process_function_name = function_name_t("register_processes");
static function_name_t const schedule_function_name = function_name_t("register_schedules");
static envvar_name_t const vistk_module_envvar = envvar_name_t("VISTK_MODULE_PATH");
static lib_suffix_t const library_suffix = lib_suffix_t(
#if defined(_WIN32) || defined(_WIN64)
".dll"
#elif defined(__APPLE__)
".dylib"
#else
".so"
#endif
);
void load_known_modules()
{
module_paths_t module_dirs;
#ifdef VISTK_LIBRARY_OUTPUT_PATH
module_dirs.push_back(VISTK_LIBRARY_OUTPUT_PATH);
#endif
#ifdef VISTK_MODULE_INSTALL_PATH
module_dirs.push_back(VISTK_MODULE_INSTALL_PATH);
#endif
envvar_value_t extra_module_dirs = NULL;
#if defined(_WIN32) || defined(_WIN64)
DWORD sz = GetEnvironmentVariable(envvar_name_t, NULL, 0);
if (sz)
{
extra_module_dirs = new char[sz];
sz = GetEnvironmentVariable(envvar_name_t, extra_module_dirs, sz);
}
if (!sz)
{
/// \todo Log error that the environment reading failed.
}
#else
extra_module_dirs = getenv(vistk_module_envvar);
#endif
if (extra_module_dirs)
{
boost::split(module_dirs, extra_module_dirs, is_separator, boost::token_compress_on);
}
#if defined(_WIN32) || defined(_WIN64)
delete[] extra_module_dirs;
extra_module_dirs = NULL;
#endif
BOOST_FOREACH (module_path_t const& module_dir, module_dirs)
{
if (module_dir.empty())
{
continue;
}
if (!boost::filesystem::exists(module_dir))
{
/// \todo Log error that path doesn't exist.
continue;
}
if (!boost::filesystem::is_directory(module_dir))
{
/// \todo Log error that path isn't a directory.
continue;
}
boost::system::error_code ec;
boost::filesystem::directory_iterator module_dir_iter(module_dir, ec);
while (module_dir_iter != boost::filesystem::directory_iterator())
{
boost::filesystem::directory_entry const ent = *module_dir_iter;
++module_dir_iter;
if (!boost::ends_with(ent.path().native(), library_suffix))
{
continue;
}
if (ent.status().type() != boost::filesystem::regular_file)
{
/// \todo Log warning that we found a non-file matching path.
continue;
}
load_from_module(ent.path().native());
}
}
}
void load_from_module(module_path_t const path)
{
library_t library = NULL;
#if defined(_WIN32) || defined(_WIN64)
{
wchar_t path_wide[MB_CUR_MAX];
mbstowcs(path_wide, path.c_str(), MB_CUR_MAX);
library = LoadLibrary(path_wide);
}
#else
library = dlopen(path.c_str(), RTLD_LAZY);
#endif
if (!library)
{
return;
}
function_t process_function = NULL;
function_t schedule_function = NULL;
#if defined(_WIN32) || defined(_WIN64)
{
wchar_t function_name[MB_CUR_MAX];
mbstowcs(function_name, process_function_name.c_str(), MB_CUR_MAX);
process_function = GetProcAddress(library, function_name);
mbstowcs(function_name, schedule_function_name.c_str(), MB_CUR_MAX);
schedule_function = GetProcAddress(library, function_name);
}
#else
process_function = dlsym(library, process_function_name.c_str());
schedule_function = dlsym(library, schedule_function_name.c_str());
#endif
load_module_t process_registrar = reinterpret_cast<load_module_t>(process_function);
load_module_t schedule_registrar = reinterpret_cast<load_module_t>(schedule_function);
bool functions_found = false;
if (process_registrar)
{
/// \todo Log info that we have loaded processes.
(*process_registrar)();
functions_found = true;
}
if (schedule_registrar)
{
/// \todo Log info that we have loaded schedules.
(*schedule_registrar)();
functions_found = true;
}
if (!functions_found)
{
#if defined(_WIN32) || defined(_WIN64)
int const ret = FreeLibrary(library);
if (!ret)
{
/// \todo Log the error.
}
#else
int const ret = dlclose(library);
if (ret)
{
/// \todo Log the error.
}
#endif
}
}
bool is_separator(char ch)
{
char const separator =
#if defined(_WIN32) || defined(_WIN64)
';';
#else
':';
#endif
return (ch == separator);
}
} // end namespace vistk
<commit_msg>Fix module loading on Windows<commit_after>/*ckwg +5
* Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "modules.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/foreach.hpp>
#include <string>
#include <vector>
#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#else
#include <dlfcn.h>
#endif
/**
* \file modules.cxx
*
* \brief Implementation of module loading.
*/
namespace vistk
{
namespace
{
#if defined(_WIN32) || defined(_WIN64)
typedef HMODULE library_t;
typedef FARPROC function_t;
#else
typedef void* library_t;
typedef void* function_t;
#endif
typedef void (*load_module_t)();
typedef char const* envvar_name_t;
#if defined(_WIN32) || defined(_WIN64)
typedef char* envvar_value_t;
#else
typedef char const* envvar_value_t;
#endif
#if defined(_WIN32) || defined(_WIN64)
typedef std::wstring module_path_t;
#else
typedef std::string module_path_t;
#endif
typedef std::vector<module_path_t> module_paths_t;
typedef std::string lib_suffix_t;
typedef std::string function_name_t;
}
static void load_from_module(module_path_t const path);
static bool is_separator(char ch);
static function_name_t const process_function_name = function_name_t("register_processes");
static function_name_t const schedule_function_name = function_name_t("register_schedules");
static envvar_name_t const vistk_module_envvar = envvar_name_t("VISTK_MODULE_PATH");
static lib_suffix_t const library_suffix = lib_suffix_t(
#if defined(_WIN32) || defined(_WIN64)
".dll"
#elif defined(__APPLE__)
".dylib"
#else
".so"
#endif
);
void load_known_modules()
{
module_paths_t module_dirs;
#ifdef VISTK_LIBRARY_OUTPUT_PATH
module_dirs.push_back(VISTK_LIBRARY_OUTPUT_PATH);
#endif
#ifdef VISTK_MODULE_INSTALL_PATH
module_dirs.push_back(VISTK_MODULE_INSTALL_PATH);
#endif
envvar_value_t extra_module_dirs = NULL;
#if defined(_WIN32) || defined(_WIN64)
DWORD sz = GetEnvironmentVariable(vistk_module_envvar, NULL, 0);
if (sz)
{
extra_module_dirs = new char[sz];
sz = GetEnvironmentVariable(vistk_module_envvar, extra_module_dirs, sz);
}
if (!sz)
{
/// \todo Log error that the environment reading failed.
}
#else
extra_module_dirs = getenv(vistk_module_envvar);
#endif
if (extra_module_dirs)
{
boost::split(module_dirs, extra_module_dirs, is_separator, boost::token_compress_on);
}
#if defined(_WIN32) || defined(_WIN64)
delete[] extra_module_dirs;
extra_module_dirs = NULL;
#endif
BOOST_FOREACH (module_path_t const& module_dir, module_dirs)
{
if (module_dir.empty())
{
continue;
}
if (!boost::filesystem::exists(module_dir))
{
/// \todo Log error that path doesn't exist.
continue;
}
if (!boost::filesystem::is_directory(module_dir))
{
/// \todo Log error that path isn't a directory.
continue;
}
boost::system::error_code ec;
boost::filesystem::directory_iterator module_dir_iter(module_dir, ec);
while (module_dir_iter != boost::filesystem::directory_iterator())
{
boost::filesystem::directory_entry const ent = *module_dir_iter;
++module_dir_iter;
if (!boost::ends_with(ent.path().native(), library_suffix))
{
continue;
}
if (ent.status().type() != boost::filesystem::regular_file)
{
/// \todo Log warning that we found a non-file matching path.
continue;
}
load_from_module(ent.path().native());
}
}
}
void load_from_module(module_path_t const path)
{
library_t library = NULL;
#if defined(_WIN32) || defined(_WIN64)
library = LoadLibraryW(path.c_str());
#else
library = dlopen(path.c_str(), RTLD_LAZY);
#endif
if (!library)
{
return;
}
function_t process_function = NULL;
function_t schedule_function = NULL;
#if defined(_WIN32) || defined(_WIN64)
process_function = GetProcAddress(library, process_function_name.c_str());
schedule_function = GetProcAddress(library, schedule_function_name.c_str());
#else
process_function = dlsym(library, process_function_name.c_str());
schedule_function = dlsym(library, schedule_function_name.c_str());
#endif
load_module_t process_registrar = reinterpret_cast<load_module_t>(process_function);
load_module_t schedule_registrar = reinterpret_cast<load_module_t>(schedule_function);
bool functions_found = false;
if (process_registrar)
{
/// \todo Log info that we have loaded processes.
(*process_registrar)();
functions_found = true;
}
if (schedule_registrar)
{
/// \todo Log info that we have loaded schedules.
(*schedule_registrar)();
functions_found = true;
}
if (!functions_found)
{
#if defined(_WIN32) || defined(_WIN64)
int const ret = FreeLibrary(library);
if (!ret)
{
/// \todo Log the error.
}
#else
int const ret = dlclose(library);
if (ret)
{
/// \todo Log the error.
}
#endif
}
}
bool is_separator(char ch)
{
char const separator =
#if defined(_WIN32) || defined(_WIN64)
';';
#else
':';
#endif
return (ch == separator);
}
} // end namespace vistk
<|endoftext|>
|
<commit_before>/*ckwg +5
* Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "version.h"
#include <vistk/version.h>
/**
* \file version.cxx
*
* \brief Runtime version checks.
*/
namespace vistk
{
version::version_t const version::major = VISTK_VERSION_MAJOR;
version::version_t const version::minor = VISTK_VERSION_MINOR;
version::version_t const version::patch = VISTK_VERSION_PATCH;
std::string const version::version_string = VISTK_VERSION;
bool const version::git_build =
#ifdef VISTK_BUILT_FROM_GIT
true
#else
false
#endif
;
std::string const version::git_hash = VISTK_GIT_HASH;
std::string const version::git_hash_short = VISTK_GIT_HASH_SHORT;
std::string const version::git_dirty = VISTK_GIT_DIRTY;
bool
version
::check(version_t major_, version_t minor_, version_t patch_)
{
// If any of the version components are 0, we get compare warnings. Turn
// them off here.
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wtype-limits"
#endif
return VISTK_VERSION_CHECK(major_, minor_, patch_);
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
}
}
<commit_msg>Moved pragmas outside of function<commit_after>/*ckwg +5
* Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "version.h"
#include <vistk/version.h>
/**
* \file version.cxx
*
* \brief Runtime version checks.
*/
namespace vistk
{
version::version_t const version::major = VISTK_VERSION_MAJOR;
version::version_t const version::minor = VISTK_VERSION_MINOR;
version::version_t const version::patch = VISTK_VERSION_PATCH;
std::string const version::version_string = VISTK_VERSION;
bool const version::git_build =
#ifdef VISTK_BUILT_FROM_GIT
true
#else
false
#endif
;
std::string const version::git_hash = VISTK_GIT_HASH;
std::string const version::git_hash_short = VISTK_GIT_HASH_SHORT;
std::string const version::git_dirty = VISTK_GIT_DIRTY;
// If any of the version components are 0, we get compare warnings. Turn
// them off here.
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wtype-limits"
#endif
bool
version
::check(version_t major_, version_t minor_, version_t patch_)
{
return VISTK_VERSION_CHECK(major_, minor_, patch_);
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
}
<|endoftext|>
|
<commit_before>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/***********************************************************************************
**
** OrionApplication.cpp
**
** Copyright (C) August 2016 Hotride
**
************************************************************************************
*/
//----------------------------------------------------------------------------------
#include "stdafx.h"
//----------------------------------------------------------------------------------
COrionApplication g_App;
//----------------------------------------------------------------------------------
void COrionApplication::OnMainLoop()
{
WISPFUN_DEBUG("c193_f1");
g_Ticks = timeGetTime();
if (m_NextRenderTime <= g_Ticks)
{
//m_NextUpdateTime = g_Ticks + 50;
m_NextRenderTime = g_Ticks + g_OrionWindow.RenderTimerDelay;
g_Orion.Process(true);
}
/*else if (m_NextUpdateTime <= g_Ticks)
{
m_NextUpdateTime = g_Ticks + 50;
g_Orion.Process(false);
}*/
else
Sleep(1);
}
//----------------------------------------------------------------------------------
<commit_msg>Return update ever 50 ms (if idle)<commit_after>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/***********************************************************************************
**
** OrionApplication.cpp
**
** Copyright (C) August 2016 Hotride
**
************************************************************************************
*/
//----------------------------------------------------------------------------------
#include "stdafx.h"
//----------------------------------------------------------------------------------
COrionApplication g_App;
//----------------------------------------------------------------------------------
void COrionApplication::OnMainLoop()
{
WISPFUN_DEBUG("c193_f1");
g_Ticks = timeGetTime();
if (m_NextRenderTime <= g_Ticks)
{
m_NextUpdateTime = g_Ticks + 50;
m_NextRenderTime = g_Ticks + g_OrionWindow.RenderTimerDelay;
g_Orion.Process(true);
}
else if (m_NextUpdateTime <= g_Ticks)
{
m_NextUpdateTime = g_Ticks + 50;
g_Orion.Process(false);
}
else
Sleep(1);
}
//----------------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: strmsys.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-17 01:01:47 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"
#if defined WNT
#include "strmwnt.cxx"
#elif defined UNX
#include "strmunx.cxx"
#endif
<commit_msg>INTEGRATION: CWS os2port02 (1.5.128); FILE MERGED 2007/09/30 12:08:51 ydario 1.5.128.1: Issue number: i82034 Submitted by: ydario Reviewed by: ydario Commit of changes for OS/2 CWS source code integration.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: strmsys.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2007-11-02 13:03:43 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"
#if defined WNT
#include "strmwnt.cxx"
#elif defined UNX
#include "strmunx.cxx"
#elif defined OS2
#include "strmos2.cxx"
#endif
<|endoftext|>
|
<commit_before>/* Copyright 2015 The TensorFlow 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.
==============================================================================*/
// This file wraps cuda runtime calls with dso loader so that we don't need to
// have explicit linking to libcuda.
#include "third_party/gpus/cuda/include/cuda_runtime_api.h"
#include "tensorflow/stream_executor/lib/env.h"
#include "tensorflow/stream_executor/platform/dso_loader.h"
namespace {
void* GetDsoHandle() {
static auto handle = []() -> void* {
auto handle_or =
stream_executor::internal::DsoLoader::GetCudaRuntimeDsoHandle();
if (!handle_or.ok()) {
LOG(INFO) << "Ignore above cudart dlerror if you do not have a GPU set "
"up on your machine.";
return nullptr;
}
return handle_or.ValueOrDie();
}();
return handle;
}
template <typename T>
T LoadSymbol(const char* symbol_name) {
void* symbol = nullptr;
auto env = stream_executor::port::Env::Default();
env->GetSymbolFromLibrary(GetDsoHandle(), symbol_name, &symbol).IgnoreError();
return reinterpret_cast<T>(symbol);
}
cudaError_t GetSymbolNotFoundError() {
return cudaErrorSharedObjectSymbolNotFound;
}
} // namespace
#define __dv(v)
#define __CUDA_DEPRECATED
// A bunch of new symbols were introduced in version 10
#if CUDART_VERSION < 10000
#include "tensorflow/stream_executor/cuda/cuda_runtime_9_0.inc"
#elif CUDART_VERSION == 10000
#include "tensorflow/stream_executor/cuda/cuda_runtime_10_0.inc"
#elif CUDART_VERSION == 10010
#include "tensorflow/stream_executor/cuda/cuda_runtime_10_1.inc"
#elif CUDART_VERSION == 10020
#include "tensorflow/stream_executor/cuda/cuda_runtime_10_2.inc"
#elif CUDART_VERSION == 11000
#include "tensorflow/stream_executor/cuda/cuda_runtime_11_0.inc"
#else
#error "We have no wrapper for this version."
#endif
#undef __dv
#undef __CUDA_DEPRECATED
extern "C" {
// Following are private symbols in libcudart that got inserted by nvcc.
extern void CUDARTAPI __cudaRegisterFunction(
void **fatCubinHandle, const char *hostFun, char *deviceFun,
const char *deviceName, int thread_limit, uint3 *tid, uint3 *bid,
dim3 *bDim, dim3 *gDim, int *wSize) {
using FuncPtr = void(CUDARTAPI *)(void **fatCubinHandle, const char *hostFun,
char *deviceFun, const char *deviceName,
int thread_limit, uint3 *tid, uint3 *bid,
dim3 *bDim, dim3 *gDim, int *wSize);
static auto func_ptr = LoadSymbol<FuncPtr>("__cudaRegisterFunction");
if (!func_ptr) return;
func_ptr(fatCubinHandle, hostFun, deviceFun, deviceName, thread_limit, tid,
bid, bDim, gDim, wSize);
}
extern void CUDARTAPI __cudaUnregisterFatBinary(void **fatCubinHandle) {
using FuncPtr = void(CUDARTAPI *)(void **fatCubinHandle);
static auto func_ptr = LoadSymbol<FuncPtr>("__cudaUnregisterFatBinary");
if (!func_ptr) return;
func_ptr(fatCubinHandle);
}
extern void CUDARTAPI __cudaRegisterVar(void **fatCubinHandle, char *hostVar,
char *deviceAddress,
const char *deviceName, int ext,
size_t size, int constant, int global) {
using FuncPtr = void(CUDARTAPI *)(
void **fatCubinHandle, char *hostVar, char *deviceAddress,
const char *deviceName, int ext, size_t size, int constant, int global);
static auto func_ptr = LoadSymbol<FuncPtr>("__cudaRegisterVar");
if (!func_ptr) return;
func_ptr(fatCubinHandle, hostVar, deviceAddress, deviceName, ext, size,
constant, global);
}
extern void **CUDARTAPI __cudaRegisterFatBinary(void *fatCubin) {
using FuncPtr = void **(CUDARTAPI *)(void *fatCubin);
static auto func_ptr = LoadSymbol<FuncPtr>("__cudaRegisterFatBinary");
if (!func_ptr) return nullptr;
return (void **)func_ptr(fatCubin);
}
extern cudaError_t CUDARTAPI __cudaPopCallConfiguration(dim3 *gridDim,
dim3 *blockDim,
size_t *sharedMem,
void *stream) {
using FuncPtr = cudaError_t(CUDARTAPI *)(dim3 * gridDim, dim3 * blockDim,
size_t * sharedMem, void *stream);
static auto func_ptr = LoadSymbol<FuncPtr>("__cudaPopCallConfiguration");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(gridDim, blockDim, sharedMem, stream);
}
extern __host__ __device__ unsigned CUDARTAPI __cudaPushCallConfiguration(
dim3 gridDim, dim3 blockDim, size_t sharedMem = 0, void *stream = 0) {
using FuncPtr = unsigned(CUDARTAPI *)(dim3 gridDim, dim3 blockDim,
size_t sharedMem, void *stream);
static auto func_ptr = LoadSymbol<FuncPtr>("__cudaPushCallConfiguration");
if (!func_ptr) return 0;
return func_ptr(gridDim, blockDim, sharedMem, stream);
}
extern char CUDARTAPI __cudaInitModule(void **fatCubinHandle) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void **fatCubinHandle);
static auto func_ptr = LoadSymbol<FuncPtr>("__cudaInitModule");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(fatCubinHandle);
}
#if CUDART_VERSION >= 10010
extern void CUDARTAPI __cudaRegisterFatBinaryEnd(void **fatCubinHandle) {
using FuncPtr = void(CUDARTAPI *)(void **fatCubinHandle);
static auto func_ptr = LoadSymbol<FuncPtr>("__cudaRegisterFatBinaryEnd");
if (!func_ptr) return;
func_ptr(fatCubinHandle);
}
#endif
} // extern "C"
<commit_msg>address comments on commit fc58d58923534e461d735a9a8b460d2dc8691ae5<commit_after>/* Copyright 2015 The TensorFlow 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.
==============================================================================*/
// This file wraps cuda runtime calls with dso loader so that we don't need to
// have explicit linking to libcuda.
#include "third_party/gpus/cuda/include/cuda_runtime_api.h"
#include "tensorflow/stream_executor/lib/env.h"
#include "tensorflow/stream_executor/platform/dso_loader.h"
namespace {
void* GetDsoHandle() {
static auto handle = []() -> void* {
auto handle_or =
stream_executor::internal::DsoLoader::GetCudaRuntimeDsoHandle();
if (!handle_or.ok()) {
LOG(INFO) << "Ignore above cudart dlerror if you do not have a GPU set "
"up on your machine.";
return nullptr;
}
return handle_or.ValueOrDie();
}();
return handle;
}
template <typename T>
T LoadSymbol(const char* symbol_name) {
void* symbol = nullptr;
auto env = stream_executor::port::Env::Default();
env->GetSymbolFromLibrary(GetDsoHandle(), symbol_name, &symbol).IgnoreError();
return reinterpret_cast<T>(symbol);
}
cudaError_t GetSymbolNotFoundError() {
return cudaErrorSharedObjectSymbolNotFound;
}
} // namespace
#define __dv(v)
#define __CUDA_DEPRECATED
// A bunch of new symbols were introduced in version 10
#if CUDART_VERSION < 10000
#include "tensorflow/stream_executor/cuda/cuda_runtime_9_0.inc"
#elif CUDART_VERSION == 10000
#include "tensorflow/stream_executor/cuda/cuda_runtime_10_0.inc"
#elif CUDART_VERSION == 10010
#include "tensorflow/stream_executor/cuda/cuda_runtime_10_1.inc"
#elif CUDART_VERSION == 10020
#include "tensorflow/stream_executor/cuda/cuda_runtime_10_2.inc"
#elif CUDART_VERSION == 11000
#include "tensorflow/stream_executor/cuda/cuda_runtime_11_0.inc"
#else
#error "We have no wrapper for this version."
#endif
#undef __dv
#undef __CUDA_DEPRECATED
extern "C" {
// Following are private symbols in libcudart that got inserted by nvcc.
extern void CUDARTAPI __cudaRegisterFunction(
void **fatCubinHandle, const char *hostFun, char *deviceFun,
const char *deviceName, int thread_limit, uint3 *tid, uint3 *bid,
dim3 *bDim, dim3 *gDim, int *wSize) {
using FuncPtr = void(CUDARTAPI *)(void **fatCubinHandle, const char *hostFun,
char *deviceFun, const char *deviceName,
int thread_limit, uint3 *tid, uint3 *bid,
dim3 *bDim, dim3 *gDim, int *wSize);
static auto func_ptr = LoadSymbol<FuncPtr>("__cudaRegisterFunction");
if (!func_ptr) return;
func_ptr(fatCubinHandle, hostFun, deviceFun, deviceName, thread_limit, tid,
bid, bDim, gDim, wSize);
}
extern void CUDARTAPI __cudaUnregisterFatBinary(void **fatCubinHandle) {
using FuncPtr = void(CUDARTAPI *)(void **fatCubinHandle);
static auto func_ptr = LoadSymbol<FuncPtr>("__cudaUnregisterFatBinary");
if (!func_ptr) return;
func_ptr(fatCubinHandle);
}
extern void CUDARTAPI __cudaRegisterVar(void **fatCubinHandle, char *hostVar,
char *deviceAddress,
const char *deviceName, int ext,
size_t size, int constant, int global) {
using FuncPtr = void(CUDARTAPI *)(
void **fatCubinHandle, char *hostVar, char *deviceAddress,
const char *deviceName, int ext, size_t size, int constant, int global);
static auto func_ptr = LoadSymbol<FuncPtr>("__cudaRegisterVar");
if (!func_ptr) return;
func_ptr(fatCubinHandle, hostVar, deviceAddress, deviceName, ext, size,
constant, global);
}
extern void **CUDARTAPI __cudaRegisterFatBinary(void *fatCubin) {
using FuncPtr = void **(CUDARTAPI *)(void *fatCubin);
static auto func_ptr = LoadSymbol<FuncPtr>("__cudaRegisterFatBinary");
if (!func_ptr) return nullptr;
return (void **)func_ptr(fatCubin);
}
extern cudaError_t CUDARTAPI __cudaPopCallConfiguration(dim3 *gridDim,
dim3 *blockDim,
size_t *sharedMem,
void *stream) {
using FuncPtr = cudaError_t(CUDARTAPI *)(dim3 * gridDim, dim3 * blockDim,
size_t * sharedMem, void *stream);
static auto func_ptr = LoadSymbol<FuncPtr>("__cudaPopCallConfiguration");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(gridDim, blockDim, sharedMem, stream);
}
extern __host__ __device__ unsigned CUDARTAPI __cudaPushCallConfiguration(
dim3 gridDim, dim3 blockDim, size_t sharedMem = 0, void *stream = 0) {
using FuncPtr = unsigned(CUDARTAPI *)(dim3 gridDim, dim3 blockDim,
size_t sharedMem, void *stream);
static auto func_ptr = LoadSymbol<FuncPtr>("__cudaPushCallConfiguration");
if (!func_ptr) return 0;
return func_ptr(gridDim, blockDim, sharedMem, stream);
}
extern char CUDARTAPI __cudaInitModule(void **fatCubinHandle) {
using FuncPtr = char(CUDARTAPI *)(void **fatCubinHandle);
static auto func_ptr = LoadSymbol<FuncPtr>("__cudaInitModule");
if (!func_ptr) return 0;
return func_ptr(fatCubinHandle);
}
#if CUDART_VERSION >= 10010
extern void CUDARTAPI __cudaRegisterFatBinaryEnd(void **fatCubinHandle) {
using FuncPtr = void(CUDARTAPI *)(void **fatCubinHandle);
static auto func_ptr = LoadSymbol<FuncPtr>("__cudaRegisterFatBinaryEnd");
if (!func_ptr) return;
func_ptr(fatCubinHandle);
}
#endif
} // extern "C"
<|endoftext|>
|
<commit_before>#ifndef __RANK_FILTER__
#define __RANK_FILTER__
#include <deque>
#include <set>
#include <cmath>
#include <cassert>
#include <functional>
#include <iostream>
#include <iterator>
#include <type_traits>
#include <utility>
#include <boost/container/set.hpp>
#include <boost/container/node_allocator.hpp>
#include <vigra/multi_array.hxx>
#include <vigra/linear_algebra.hxx>
namespace vigra
{
template<unsigned int N,
class T1, class S1,
class T2, class S2,
typename std::enable_if<(N == 1), int>::type = 0>
inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src,
vigra::MultiArrayView <N, T2, S2> dest,
unsigned int half_length, float rank, unsigned int axis = 0)
{
// Will ignore boundaries initially.
// Then will try adding reflection.
// Rank must be in the range 0 to 1
assert((0 <= rank) && (rank <= 1));
const int rank_pos = round(rank * (2 * half_length));
// The position of the
typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 window_begin(0);
typedef boost::container::multiset< T1,
std::less<T1>,
boost::container::node_allocator<T1>,
boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset;
typedef std::deque< typename multiset::iterator > deque;
multiset sorted_window;
deque window_iters;
// Get the initial sorted window.
// Include the reflection.
for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(half_length); j > 0; j--)
{
window_iters.push_back(sorted_window.insert(src[window_begin + j]));
}
for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(0); j <= half_length; j++)
{
window_iters.push_back(sorted_window.insert(src[window_begin + j]));
}
typename multiset::iterator rank_point = sorted_window.begin();
for (int i = 0; i < rank_pos; i++)
{
rank_point++;
}
typename multiset::iterator prev_iter;
T1 prev_value;
T1 next_value;
while ( window_begin < src.size() )
{
dest[window_begin] = *rank_point;
prev_iter = window_iters.front();
prev_value = *prev_iter;
window_iters.pop_front();
window_begin++;
if ( window_begin < (src.size() - half_length) )
{
next_value = src[window_begin + half_length];
}
else
{
next_value = *(window_iters[window_iters.size() + 2*src.size() - 2*(window_begin + half_length) - 2]);
}
if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) )
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
}
else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) )
{
if ( rank_point == prev_iter )
{
window_iters.push_back(sorted_window.insert(next_value));
rank_point--;
sorted_window.erase(prev_iter);
}
else
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
}
}
else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) )
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
rank_point--;
}
else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) )
{
if (rank_point == prev_iter)
{
window_iters.push_back(sorted_window.insert(next_value));
rank_point++;
sorted_window.erase(prev_iter);
}
else
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
rank_point++;
}
}
}
}
template<unsigned int N,
class T1, class S1,
class T2, class S2,
typename std::enable_if<(N > 1), int>::type = 0>
inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src,
vigra::MultiArrayView <N, T2, S2> dest,
unsigned int half_length, float rank, unsigned int axis = 0)
{
typename vigra::MultiArrayView<N, T1, S1>::difference_type transposed_axes;
for (unsigned int i = 0; i < N; i++)
{
transposed_axes[i] = i;
}
std::swap(transposed_axes[0], transposed_axes[axis]);
vigra::MultiArray<N, T1> src_transposed(src.transpose(transposed_axes));
vigra::MultiArrayView<N, T2, S2> dest_transposed(dest.transpose(transposed_axes));
typename vigra::MultiArrayView<N - 1, T1, S1>::difference_type pos;
pos = 0;
bool done = false;
bool carry = true;
while (!done)
{
lineRankOrderFilterND(src_transposed.bindOuter(pos), dest_transposed.bindOuter(pos), half_length, rank, 0);
carry = true;
for (unsigned int i = 0; ( carry && (i < (N - 1)) ); i++)
{
if ( (++pos[i]) < src_transposed.shape(i + 1) )
{
carry = false;
}
else
{
pos[i] = 0;
carry = true;
}
}
done = carry;
}
}
template<unsigned int N,
class T1, class S1,
class T2, class S2>
inline void lineRankOrderFilter(const vigra::MultiArrayView <N, T1, S1> &src,
vigra::MultiArrayView <N, T2, S2> dest,
unsigned int half_length, float rank, unsigned int axis = 0)
{
lineRankOrderFilterND(src, dest, half_length, rank, axis);
}
}
#endif //__RANK_FILTER__
<commit_msg>rank_filter.hxx: Changed namespace from vigra to rank_filter.<commit_after>#ifndef __RANK_FILTER__
#define __RANK_FILTER__
#include <deque>
#include <set>
#include <cmath>
#include <cassert>
#include <functional>
#include <iostream>
#include <iterator>
#include <type_traits>
#include <utility>
#include <boost/container/set.hpp>
#include <boost/container/node_allocator.hpp>
#include <vigra/multi_array.hxx>
#include <vigra/linear_algebra.hxx>
namespace rank_filter
{
template<unsigned int N,
class T1, class S1,
class T2, class S2,
typename std::enable_if<(N == 1), int>::type = 0>
inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src,
vigra::MultiArrayView <N, T2, S2> dest,
unsigned int half_length, float rank, unsigned int axis = 0)
{
// Will ignore boundaries initially.
// Then will try adding reflection.
// Rank must be in the range 0 to 1
assert((0 <= rank) && (rank <= 1));
const int rank_pos = round(rank * (2 * half_length));
// The position of the
typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 window_begin(0);
typedef boost::container::multiset< T1,
std::less<T1>,
boost::container::node_allocator<T1>,
boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset;
typedef std::deque< typename multiset::iterator > deque;
multiset sorted_window;
deque window_iters;
// Get the initial sorted window.
// Include the reflection.
for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(half_length); j > 0; j--)
{
window_iters.push_back(sorted_window.insert(src[window_begin + j]));
}
for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(0); j <= half_length; j++)
{
window_iters.push_back(sorted_window.insert(src[window_begin + j]));
}
typename multiset::iterator rank_point = sorted_window.begin();
for (int i = 0; i < rank_pos; i++)
{
rank_point++;
}
typename multiset::iterator prev_iter;
T1 prev_value;
T1 next_value;
while ( window_begin < src.size() )
{
dest[window_begin] = *rank_point;
prev_iter = window_iters.front();
prev_value = *prev_iter;
window_iters.pop_front();
window_begin++;
if ( window_begin < (src.size() - half_length) )
{
next_value = src[window_begin + half_length];
}
else
{
next_value = *(window_iters[window_iters.size() + 2*src.size() - 2*(window_begin + half_length) - 2]);
}
if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) )
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
}
else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) )
{
if ( rank_point == prev_iter )
{
window_iters.push_back(sorted_window.insert(next_value));
rank_point--;
sorted_window.erase(prev_iter);
}
else
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
}
}
else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) )
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
rank_point--;
}
else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) )
{
if (rank_point == prev_iter)
{
window_iters.push_back(sorted_window.insert(next_value));
rank_point++;
sorted_window.erase(prev_iter);
}
else
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
rank_point++;
}
}
}
}
template<unsigned int N,
class T1, class S1,
class T2, class S2,
typename std::enable_if<(N > 1), int>::type = 0>
inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src,
vigra::MultiArrayView <N, T2, S2> dest,
unsigned int half_length, float rank, unsigned int axis = 0)
{
typename vigra::MultiArrayView<N, T1, S1>::difference_type transposed_axes;
for (unsigned int i = 0; i < N; i++)
{
transposed_axes[i] = i;
}
std::swap(transposed_axes[0], transposed_axes[axis]);
vigra::MultiArray<N, T1> src_transposed(src.transpose(transposed_axes));
vigra::MultiArrayView<N, T2, S2> dest_transposed(dest.transpose(transposed_axes));
typename vigra::MultiArrayView<N - 1, T1, S1>::difference_type pos;
pos = 0;
bool done = false;
bool carry = true;
while (!done)
{
lineRankOrderFilterND(src_transposed.bindOuter(pos), dest_transposed.bindOuter(pos), half_length, rank, 0);
carry = true;
for (unsigned int i = 0; ( carry && (i < (N - 1)) ); i++)
{
if ( (++pos[i]) < src_transposed.shape(i + 1) )
{
carry = false;
}
else
{
pos[i] = 0;
carry = true;
}
}
done = carry;
}
}
template<unsigned int N,
class T1, class S1,
class T2, class S2>
inline void lineRankOrderFilter(const vigra::MultiArrayView <N, T1, S1> &src,
vigra::MultiArrayView <N, T2, S2> dest,
unsigned int half_length, float rank, unsigned int axis = 0)
{
lineRankOrderFilterND(src, dest, half_length, rank, axis);
}
}
#endif //__RANK_FILTER__
<|endoftext|>
|
<commit_before>/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** PeerConnectionManager.cpp
**
** -------------------------------------------------------------------------*/
#include <iostream>
#include <utility>
#include "talk/app/webrtc/videosourceinterface.h"
#include "talk/media/devices/devicemanager.h"
#include "talk/media/base/videocapturer.h"
#include "webrtc/base/common.h"
#include "webrtc/base/json.h"
#include "webrtc/base/logging.h"
#include "PeerConnectionManager.h"
#include "rtspvideocapturer.h"
const char kAudioLabel[] = "audio_label";
const char kVideoLabel[] = "video_label";
const char kStreamLabel[] = "stream_label";
// Names used for a IceCandidate JSON object.
const char kCandidateSdpMidName[] = "sdpMid";
const char kCandidateSdpMlineIndexName[] = "sdpMLineIndex";
const char kCandidateSdpName[] = "candidate";
// Names used for a SessionDescription JSON object.
const char kSessionDescriptionTypeName[] = "type";
const char kSessionDescriptionSdpName[] = "sdp";
PeerConnectionManager::PeerConnectionManager(const std::string & stunurl) : stunurl_(stunurl)
{
peer_connection_factory_ = webrtc::CreatePeerConnectionFactory();
if (!peer_connection_factory_.get()) {
LOG(LERROR) << __FUNCTION__ << "Failed to initialize PeerConnectionFactory";
}
}
PeerConnectionManager::~PeerConnectionManager()
{
peer_connection_factory_ = NULL;
}
std::pair<rtc::scoped_refptr<webrtc::PeerConnectionInterface>, PeerConnectionManager::PeerConnectionObserver* > PeerConnectionManager::CreatePeerConnection(const std::string & url)
{
webrtc::PeerConnectionInterface::IceServers servers;
webrtc::PeerConnectionInterface::IceServer server;
server.uri = "stun:" + stunurl_;
servers.push_back(server);
PeerConnectionObserver* obs = PeerConnectionObserver::Create();
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection = peer_connection_factory_->CreatePeerConnection(servers,
NULL,
NULL,
NULL,
obs);
if (!peer_connection)
{
LOG(LERROR) << __FUNCTION__ << "CreatePeerConnection failed";
}
else
{
obs->setPeerConnection(peer_connection);
this->AddStreams(peer_connection, url);
}
return std::pair<rtc::scoped_refptr<webrtc::PeerConnectionInterface>, PeerConnectionObserver* >(peer_connection, obs);
}
void PeerConnectionManager::DeletePeerConnection()
{
}
void PeerConnectionManager::setAnswer(const std::string &peerid, const std::string& message)
{
LOG(INFO) << message;
Json::Reader reader;
Json::Value jmessage;
if (!reader.parse(message, jmessage)) {
LOG(WARNING) << "Received unknown message. " << message;
return;
}
std::string type;
std::string sdp;
if ( !GetStringFromJsonObject(jmessage, kSessionDescriptionTypeName, &type)
|| !GetStringFromJsonObject(jmessage, kSessionDescriptionSdpName, &sdp)) {
LOG(WARNING) << "Can't parse received message.";
return;
}
webrtc::SessionDescriptionInterface* session_description(webrtc::CreateSessionDescription(type, sdp));
if (!session_description) {
LOG(WARNING) << "Can't parse received session description message.";
return;
}
LOG(LERROR) << "From peerid:" << peerid << " received session description :" << session_description->type();
std::map<std::string, rtc::scoped_refptr<webrtc::PeerConnectionInterface> >::iterator it = peer_connection_map_.find(peerid);
if (it != peer_connection_map_.end())
{
rtc::scoped_refptr<webrtc::PeerConnectionInterface> pc = it->second;
pc->SetRemoteDescription(SetSessionDescriptionObserver::Create(pc, session_description->type()), session_description);
}
}
void PeerConnectionManager::addIceCandidate(const std::string &peerid, const std::string& message)
{
LOG(INFO) << message;
Json::Reader reader;
Json::Value jmessage;
if (!reader.parse(message, jmessage)) {
LOG(WARNING) << "Received unknown message. " << message;
return;
}
std::string sdp_mid;
int sdp_mlineindex = 0;
std::string sdp;
if ( !GetStringFromJsonObject(jmessage, kCandidateSdpMidName, &sdp_mid)
|| !GetIntFromJsonObject(jmessage, kCandidateSdpMlineIndexName, &sdp_mlineindex)
|| !GetStringFromJsonObject(jmessage, kCandidateSdpName, &sdp)) {
LOG(WARNING) << "Can't parse received message.";
return;
}
rtc::scoped_ptr<webrtc::IceCandidateInterface> candidate(webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, sdp));
if (!candidate.get()) {
LOG(WARNING) << "Can't parse received candidate message.";
return;
}
std::map<std::string, rtc::scoped_refptr<webrtc::PeerConnectionInterface> >::iterator it = peer_connection_map_.find(peerid);
if (it != peer_connection_map_.end())
{
rtc::scoped_refptr<webrtc::PeerConnectionInterface> pc = it->second;
if (!pc->AddIceCandidate(candidate.get())) {
LOG(WARNING) << "Failed to apply the received candidate";
return;
}
}
}
class VideoCapturerListener : public sigslot::has_slots<> {
public:
VideoCapturerListener(cricket::VideoCapturer* capturer)
{
capturer->SignalFrameCaptured.connect(this, &VideoCapturerListener::OnFrameCaptured);
}
void OnFrameCaptured(cricket::VideoCapturer* capturer, const cricket::CapturedFrame* frame)
{
LOG(LS_ERROR) << "OnFrameCaptured";
}
};
cricket::VideoCapturer* PeerConnectionManager::OpenVideoCaptureDevice(const std::string & url)
{
cricket::VideoCapturer* capturer = NULL;
if (url.find("rtsp://") == 0)
{
capturer = new RTSPVideoCapturer(url);
}
else
{
std::vector<cricket::Device> devs;
cricket::Device device;
rtc::scoped_ptr<cricket::DeviceManagerInterface> dev_manager(cricket::DeviceManagerFactory::Create());
if (!dev_manager->Init())
{
LOG(LS_ERROR) << "Can't create device manager";
}
else if (!dev_manager->GetVideoCaptureDevice(url, &device))
{
LOG(LS_ERROR) << "Can't enumerate get device name:" << url;
}
else
{
capturer = dev_manager->CreateVideoCapturer(device);
}
}
return capturer;
}
void PeerConnectionManager::AddStreams(webrtc::PeerConnectionInterface* peer_connection, const std::string & url)
{
cricket::VideoCapturer* capturer = OpenVideoCaptureDevice(url);
if (!capturer)
{
LOG(LS_ERROR) << "Cannot create capturer " << url;
}
else
{
VideoCapturerListener listener(capturer);
rtc::scoped_refptr<webrtc::VideoSourceInterface> source = peer_connection_factory_->CreateVideoSource(capturer, NULL);
rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track(peer_connection_factory_->CreateVideoTrack(kVideoLabel, source));
rtc::scoped_refptr<webrtc::MediaStreamInterface> stream = peer_connection_factory_->CreateLocalMediaStream(kStreamLabel);
if (!stream.get())
{
LOG(LS_ERROR) << "Cannot create stream";
}
else
{
stream->AddTrack(video_track);
if (!peer_connection->AddStream(stream))
{
LOG(LS_ERROR) << "Adding stream to PeerConnection failed";
}
}
}
}
const std::string PeerConnectionManager::getOffer(std::string &peerid, const std::string & url)
{
std::string offer;
LOG(INFO) << __FUNCTION__;
std::pair<rtc::scoped_refptr<webrtc::PeerConnectionInterface>, PeerConnectionObserver* > peer_connection = CreatePeerConnection(url);
if (!peer_connection.first)
{
LOG(LERROR) << "Failed to initialize PeerConnection";
}
else
{
std::ostringstream os;
os << rand();
peerid = os.str();
// register peerid
peer_connection_map_.insert(std::pair<std::string, rtc::scoped_refptr<webrtc::PeerConnectionInterface> >(peerid, peer_connection.first));
peer_connectionobs_map_.insert(std::pair<std::string, PeerConnectionObserver* >(peerid, peer_connection.second));
peer_connection.first->CreateOffer(CreateSessionDescriptionObserver::Create(peer_connection.first), NULL);
// waiting for offer
int count=10;
while ( (peer_connection.first->local_description() == NULL) && (--count > 0) )
{
rtc::Thread::Current()->ProcessMessages(10);
}
const webrtc::SessionDescriptionInterface* desc = peer_connection.first->local_description();
if (desc)
{
Json::Value jmessage;
jmessage[kSessionDescriptionTypeName] = desc->type();
std::string sdp;
desc->ToString(&sdp);
jmessage[kSessionDescriptionSdpName] = sdp;
Json::StyledWriter writer;
offer = writer.write(jmessage);
}
}
return offer;
}
const Json::Value PeerConnectionManager::getIceCandidateList(const std::string &peerid)
{
Json::Value value;
std::map<std::string, PeerConnectionObserver* >::iterator it = peer_connectionobs_map_.find(peerid);
if (it != peer_connectionobs_map_.end())
{
PeerConnectionObserver* obs = it->second;
if (obs)
{
value = obs->getIceCandidateList();
}
else
{
LOG(LS_ERROR) << "No observer for peer:" << peerid;
}
}
return value;
}
void PeerConnectionManager::PeerConnectionObserver::OnIceCandidate(const webrtc::IceCandidateInterface* candidate)
{
LOG(LS_ERROR) << __FUNCTION__ << " " << candidate->sdp_mline_index();
Json::StyledWriter writer;
Json::Value jmessage;
jmessage[kCandidateSdpMidName] = candidate->sdp_mid();
jmessage[kCandidateSdpMlineIndexName] = candidate->sdp_mline_index();
std::string sdp;
if (!candidate->ToString(&sdp))
{
LOG(LS_ERROR) << "Failed to serialize candidate";
}
else
{
LOG(INFO) << sdp;
jmessage[kCandidateSdpName] = sdp;
iceCandidateList_.append(jmessage);
}
}
<commit_msg>since commit cb76b895728c888c60cf474070fff6aee4f8731c json was moved inside rtc namespace<commit_after>/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** PeerConnectionManager.cpp
**
** -------------------------------------------------------------------------*/
#include <iostream>
#include <utility>
#include "talk/app/webrtc/videosourceinterface.h"
#include "talk/media/devices/devicemanager.h"
#include "talk/media/base/videocapturer.h"
#include "webrtc/base/common.h"
#include "webrtc/base/json.h"
#include "webrtc/base/logging.h"
#include "PeerConnectionManager.h"
#include "rtspvideocapturer.h"
const char kAudioLabel[] = "audio_label";
const char kVideoLabel[] = "video_label";
const char kStreamLabel[] = "stream_label";
// Names used for a IceCandidate JSON object.
const char kCandidateSdpMidName[] = "sdpMid";
const char kCandidateSdpMlineIndexName[] = "sdpMLineIndex";
const char kCandidateSdpName[] = "candidate";
// Names used for a SessionDescription JSON object.
const char kSessionDescriptionTypeName[] = "type";
const char kSessionDescriptionSdpName[] = "sdp";
PeerConnectionManager::PeerConnectionManager(const std::string & stunurl) : stunurl_(stunurl)
{
peer_connection_factory_ = webrtc::CreatePeerConnectionFactory();
if (!peer_connection_factory_.get()) {
LOG(LERROR) << __FUNCTION__ << "Failed to initialize PeerConnectionFactory";
}
}
PeerConnectionManager::~PeerConnectionManager()
{
peer_connection_factory_ = NULL;
}
std::pair<rtc::scoped_refptr<webrtc::PeerConnectionInterface>, PeerConnectionManager::PeerConnectionObserver* > PeerConnectionManager::CreatePeerConnection(const std::string & url)
{
webrtc::PeerConnectionInterface::IceServers servers;
webrtc::PeerConnectionInterface::IceServer server;
server.uri = "stun:" + stunurl_;
servers.push_back(server);
PeerConnectionObserver* obs = PeerConnectionObserver::Create();
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection = peer_connection_factory_->CreatePeerConnection(servers,
NULL,
NULL,
NULL,
obs);
if (!peer_connection)
{
LOG(LERROR) << __FUNCTION__ << "CreatePeerConnection failed";
}
else
{
obs->setPeerConnection(peer_connection);
this->AddStreams(peer_connection, url);
}
return std::pair<rtc::scoped_refptr<webrtc::PeerConnectionInterface>, PeerConnectionObserver* >(peer_connection, obs);
}
void PeerConnectionManager::DeletePeerConnection()
{
}
void PeerConnectionManager::setAnswer(const std::string &peerid, const std::string& message)
{
LOG(INFO) << message;
Json::Reader reader;
Json::Value jmessage;
if (!reader.parse(message, jmessage)) {
LOG(WARNING) << "Received unknown message. " << message;
return;
}
std::string type;
std::string sdp;
if ( !rtc::GetStringFromJsonObject(jmessage, kSessionDescriptionTypeName, &type)
|| !rtc::GetStringFromJsonObject(jmessage, kSessionDescriptionSdpName, &sdp)) {
LOG(WARNING) << "Can't parse received message.";
return;
}
webrtc::SessionDescriptionInterface* session_description(webrtc::CreateSessionDescription(type, sdp));
if (!session_description) {
LOG(WARNING) << "Can't parse received session description message.";
return;
}
LOG(LERROR) << "From peerid:" << peerid << " received session description :" << session_description->type();
std::map<std::string, rtc::scoped_refptr<webrtc::PeerConnectionInterface> >::iterator it = peer_connection_map_.find(peerid);
if (it != peer_connection_map_.end())
{
rtc::scoped_refptr<webrtc::PeerConnectionInterface> pc = it->second;
pc->SetRemoteDescription(SetSessionDescriptionObserver::Create(pc, session_description->type()), session_description);
}
}
void PeerConnectionManager::addIceCandidate(const std::string &peerid, const std::string& message)
{
LOG(INFO) << message;
Json::Reader reader;
Json::Value jmessage;
if (!reader.parse(message, jmessage)) {
LOG(WARNING) << "Received unknown message. " << message;
return;
}
std::string sdp_mid;
int sdp_mlineindex = 0;
std::string sdp;
if ( !rtc::GetStringFromJsonObject(jmessage, kCandidateSdpMidName, &sdp_mid)
|| !rtc::GetIntFromJsonObject(jmessage, kCandidateSdpMlineIndexName, &sdp_mlineindex)
|| !rtc::GetStringFromJsonObject(jmessage, kCandidateSdpName, &sdp)) {
LOG(WARNING) << "Can't parse received message.";
return;
}
rtc::scoped_ptr<webrtc::IceCandidateInterface> candidate(webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, sdp));
if (!candidate.get()) {
LOG(WARNING) << "Can't parse received candidate message.";
return;
}
std::map<std::string, rtc::scoped_refptr<webrtc::PeerConnectionInterface> >::iterator it = peer_connection_map_.find(peerid);
if (it != peer_connection_map_.end())
{
rtc::scoped_refptr<webrtc::PeerConnectionInterface> pc = it->second;
if (!pc->AddIceCandidate(candidate.get())) {
LOG(WARNING) << "Failed to apply the received candidate";
return;
}
}
}
class VideoCapturerListener : public sigslot::has_slots<> {
public:
VideoCapturerListener(cricket::VideoCapturer* capturer)
{
capturer->SignalFrameCaptured.connect(this, &VideoCapturerListener::OnFrameCaptured);
}
void OnFrameCaptured(cricket::VideoCapturer* capturer, const cricket::CapturedFrame* frame)
{
LOG(LS_ERROR) << "OnFrameCaptured";
}
};
cricket::VideoCapturer* PeerConnectionManager::OpenVideoCaptureDevice(const std::string & url)
{
cricket::VideoCapturer* capturer = NULL;
if (url.find("rtsp://") == 0)
{
capturer = new RTSPVideoCapturer(url);
}
else
{
std::vector<cricket::Device> devs;
cricket::Device device;
rtc::scoped_ptr<cricket::DeviceManagerInterface> dev_manager(cricket::DeviceManagerFactory::Create());
if (!dev_manager->Init())
{
LOG(LS_ERROR) << "Can't create device manager";
}
else if (!dev_manager->GetVideoCaptureDevice(url, &device))
{
LOG(LS_ERROR) << "Can't enumerate get device name:" << url;
}
else
{
capturer = dev_manager->CreateVideoCapturer(device);
}
}
return capturer;
}
void PeerConnectionManager::AddStreams(webrtc::PeerConnectionInterface* peer_connection, const std::string & url)
{
cricket::VideoCapturer* capturer = OpenVideoCaptureDevice(url);
if (!capturer)
{
LOG(LS_ERROR) << "Cannot create capturer " << url;
}
else
{
VideoCapturerListener listener(capturer);
rtc::scoped_refptr<webrtc::VideoSourceInterface> source = peer_connection_factory_->CreateVideoSource(capturer, NULL);
rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track(peer_connection_factory_->CreateVideoTrack(kVideoLabel, source));
rtc::scoped_refptr<webrtc::MediaStreamInterface> stream = peer_connection_factory_->CreateLocalMediaStream(kStreamLabel);
if (!stream.get())
{
LOG(LS_ERROR) << "Cannot create stream";
}
else
{
stream->AddTrack(video_track);
if (!peer_connection->AddStream(stream))
{
LOG(LS_ERROR) << "Adding stream to PeerConnection failed";
}
}
}
}
const std::string PeerConnectionManager::getOffer(std::string &peerid, const std::string & url)
{
std::string offer;
LOG(INFO) << __FUNCTION__;
std::pair<rtc::scoped_refptr<webrtc::PeerConnectionInterface>, PeerConnectionObserver* > peer_connection = CreatePeerConnection(url);
if (!peer_connection.first)
{
LOG(LERROR) << "Failed to initialize PeerConnection";
}
else
{
std::ostringstream os;
os << rand();
peerid = os.str();
// register peerid
peer_connection_map_.insert(std::pair<std::string, rtc::scoped_refptr<webrtc::PeerConnectionInterface> >(peerid, peer_connection.first));
peer_connectionobs_map_.insert(std::pair<std::string, PeerConnectionObserver* >(peerid, peer_connection.second));
peer_connection.first->CreateOffer(CreateSessionDescriptionObserver::Create(peer_connection.first), NULL);
// waiting for offer
int count=10;
while ( (peer_connection.first->local_description() == NULL) && (--count > 0) )
{
rtc::Thread::Current()->ProcessMessages(10);
}
const webrtc::SessionDescriptionInterface* desc = peer_connection.first->local_description();
if (desc)
{
Json::Value jmessage;
jmessage[kSessionDescriptionTypeName] = desc->type();
std::string sdp;
desc->ToString(&sdp);
jmessage[kSessionDescriptionSdpName] = sdp;
Json::StyledWriter writer;
offer = writer.write(jmessage);
}
}
return offer;
}
const Json::Value PeerConnectionManager::getIceCandidateList(const std::string &peerid)
{
Json::Value value;
std::map<std::string, PeerConnectionObserver* >::iterator it = peer_connectionobs_map_.find(peerid);
if (it != peer_connectionobs_map_.end())
{
PeerConnectionObserver* obs = it->second;
if (obs)
{
value = obs->getIceCandidateList();
}
else
{
LOG(LS_ERROR) << "No observer for peer:" << peerid;
}
}
return value;
}
void PeerConnectionManager::PeerConnectionObserver::OnIceCandidate(const webrtc::IceCandidateInterface* candidate)
{
LOG(LS_ERROR) << __FUNCTION__ << " " << candidate->sdp_mline_index();
Json::StyledWriter writer;
Json::Value jmessage;
jmessage[kCandidateSdpMidName] = candidate->sdp_mid();
jmessage[kCandidateSdpMlineIndexName] = candidate->sdp_mline_index();
std::string sdp;
if (!candidate->ToString(&sdp))
{
LOG(LS_ERROR) << "Failed to serialize candidate";
}
else
{
LOG(INFO) << sdp;
jmessage[kCandidateSdpName] = sdp;
iceCandidateList_.append(jmessage);
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2006 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
// Most of this was borrowed (with minor modifications) from V8's and Chromium's
// src/base/logging.cc.
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#if defined(WEBRTC_ANDROID)
#define RTC_LOG_TAG_ANDROID "rtc"
#include <android/log.h> // NOLINT
#endif
#if defined(WEBRTC_WIN)
#include <windows.h>
#endif
#if defined(WEBRTC_WIN)
#define LAST_SYSTEM_ERROR (::GetLastError())
#elif defined(__native_client__) && __native_client__
#define LAST_SYSTEM_ERROR (0)
#elif defined(WEBRTC_POSIX)
#include <errno.h>
#define LAST_SYSTEM_ERROR (errno)
#endif // WEBRTC_WIN
#include "rtc_base/checks.h"
namespace rtc {
namespace webrtc_checks_impl {
// Reads one argument from args, appends it to s and advances fmt.
// Returns true iff an argument was sucessfully parsed.
bool ParseArg(va_list* args,
const CheckArgType** fmt,
std::ostream& s) { // no-presubmit-check TODO(webrtc:8982)
if (**fmt == CheckArgType::kEnd)
return false;
switch (**fmt) {
case CheckArgType::kInt:
s << va_arg(*args, int);
break;
case CheckArgType::kLong:
s << va_arg(*args, long);
break;
case CheckArgType::kLongLong:
s << va_arg(*args, long long);
break;
case CheckArgType::kUInt:
s << va_arg(*args, unsigned);
break;
case CheckArgType::kULong:
s << va_arg(*args, unsigned long);
break;
case CheckArgType::kULongLong:
s << va_arg(*args, unsigned long long);
break;
case CheckArgType::kDouble:
s << va_arg(*args, double);
break;
case CheckArgType::kLongDouble:
s << va_arg(*args, long double);
break;
case CheckArgType::kCharP:
s << va_arg(*args, const char*);
break;
case CheckArgType::kStdString:
s << *va_arg(*args, const std::string*);
break;
case CheckArgType::kVoidP:
s << reinterpret_cast<std::uintptr_t>(va_arg(*args, const void*));
break;
default:
s << "[Invalid CheckArgType:" << static_cast<int8_t>(**fmt) << "]";
return false;
}
(*fmt)++;
return true;
}
RTC_NORETURN void FatalLog(const char* file,
int line,
const char* message,
const CheckArgType* fmt,
...) {
va_list args;
va_start(args, fmt);
std::ostringstream ss; // no-presubmit-check TODO(webrtc:8982)
ss << "\n\n#\n# Fatal error in: " << file << ", line " << line
<< "\n# last system error: " << LAST_SYSTEM_ERROR << "\n# Check failed: ";
if (*fmt == CheckArgType::kCheckOp) {
// This log message was generated by RTC_CHECK_OP, so we have to complete
// the error message using the operands that have been passed as the first
// two arguments.
fmt++;
std::ostringstream s1, s2; // no-presubmit-check TODO(webrtc:8982)
if (ParseArg(&args, &fmt, s1) && ParseArg(&args, &fmt, s2))
ss << message << " (" << s1.str() << " vs. " << s2.str() << ")\n# ";
} else {
ss << message << "\n# ";
}
// Append all the user-supplied arguments to the message.
while (ParseArg(&args, &fmt, ss))
;
va_end(args);
std::string s = ss.str();
const char* output = s.c_str();
#if defined(WEBRTC_ANDROID)
__android_log_print(ANDROID_LOG_ERROR, RTC_LOG_TAG_ANDROID, "%s\n", output);
#endif
fflush(stdout);
fprintf(stderr, "%s", output);
fflush(stderr);
abort();
}
} // namespace webrtc_checks_impl
} // namespace rtc
// Function to call from the C version of the RTC_CHECK and RTC_DCHECK macros.
RTC_NORETURN void rtc_FatalMessage(const char* file, int line,
const char* msg) {
static constexpr rtc::webrtc_checks_impl::CheckArgType t[] = {
rtc::webrtc_checks_impl::CheckArgType::kEnd};
FatalLog(file, line, msg, t);
}
<commit_msg>Remove std::stringstream from the RTC_CHECK implementation.<commit_after>/*
* Copyright 2006 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
// Most of this was borrowed (with minor modifications) from V8's and Chromium's
// src/base/logging.cc.
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#if defined(WEBRTC_ANDROID)
#define RTC_LOG_TAG_ANDROID "rtc"
#include <android/log.h> // NOLINT
#endif
#if defined(WEBRTC_WIN)
#include <windows.h>
#endif
#if defined(WEBRTC_WIN)
#define LAST_SYSTEM_ERROR (::GetLastError())
#elif defined(__native_client__) && __native_client__
#define LAST_SYSTEM_ERROR (0)
#elif defined(WEBRTC_POSIX)
#include <errno.h>
#define LAST_SYSTEM_ERROR (errno)
#endif // WEBRTC_WIN
#include "rtc_base/checks.h"
namespace {
#if defined(__GNUC__)
__attribute__((__format__(__printf__, 2, 3)))
#endif
void AppendFormat(std::string* s, const char* fmt, ...) {
va_list args, copy;
va_start(args, fmt);
va_copy(copy, args);
const int predicted_length = std::vsnprintf(nullptr, 0, fmt, copy);
va_end(copy);
if (predicted_length > 0) {
const size_t size = s->size();
s->resize(size + predicted_length);
// Pass "+ 1" to vsnprintf to include space for the '\0'.
std::vsnprintf(&((*s)[size]), predicted_length + 1, fmt, args);
}
va_end(args);
}
}
namespace rtc {
namespace webrtc_checks_impl {
// Reads one argument from args, appends it to s and advances fmt.
// Returns true iff an argument was sucessfully parsed.
bool ParseArg(va_list* args, const CheckArgType** fmt, std::string* s) {
if (**fmt == CheckArgType::kEnd)
return false;
switch (**fmt) {
case CheckArgType::kInt:
AppendFormat(s, "%d", va_arg(*args, int));
break;
case CheckArgType::kLong:
AppendFormat(s, "%ld", va_arg(*args, long));
break;
case CheckArgType::kLongLong:
AppendFormat(s, "%lld", va_arg(*args, long long));
break;
case CheckArgType::kUInt:
AppendFormat(s, "%u", va_arg(*args, unsigned));
break;
case CheckArgType::kULong:
AppendFormat(s, "%lu", va_arg(*args, unsigned long));
break;
case CheckArgType::kULongLong:
AppendFormat(s, "%llu", va_arg(*args, unsigned long long));
break;
case CheckArgType::kDouble:
AppendFormat(s, "%g", va_arg(*args, double));
break;
case CheckArgType::kLongDouble:
AppendFormat(s, "%Lg", va_arg(*args, long double));
break;
case CheckArgType::kCharP:
s->append(va_arg(*args, const char*));
break;
case CheckArgType::kStdString:
s->append(*va_arg(*args, const std::string*));
break;
case CheckArgType::kVoidP:
AppendFormat(s, "%p", va_arg(*args, const void*));
break;
default:
s->append("[Invalid CheckArgType]");
return false;
}
(*fmt)++;
return true;
}
RTC_NORETURN void FatalLog(const char* file,
int line,
const char* message,
const CheckArgType* fmt,
...) {
va_list args;
va_start(args, fmt);
std::string s;
AppendFormat(&s,
"\n\n"
"#\n"
"# Fatal error in: %s, line %d\n"
"# last system error: %u\n"
"# Check failed: %s",
file, line, LAST_SYSTEM_ERROR, message);
if (*fmt == CheckArgType::kCheckOp) {
// This log message was generated by RTC_CHECK_OP, so we have to complete
// the error message using the operands that have been passed as the first
// two arguments.
fmt++;
std::string s1, s2;
if (ParseArg(&args, &fmt, &s1) && ParseArg(&args, &fmt, &s2))
AppendFormat(&s, " (%s vs. %s)\n# ", s1.c_str(), s2.c_str());
} else {
s.append("\n# ");
}
// Append all the user-supplied arguments to the message.
while (ParseArg(&args, &fmt, &s))
;
va_end(args);
const char* output = s.c_str();
#if defined(WEBRTC_ANDROID)
__android_log_print(ANDROID_LOG_ERROR, RTC_LOG_TAG_ANDROID, "%s\n", output);
#endif
fflush(stdout);
fprintf(stderr, "%s", output);
fflush(stderr);
abort();
}
} // namespace webrtc_checks_impl
} // namespace rtc
// Function to call from the C version of the RTC_CHECK and RTC_DCHECK macros.
RTC_NORETURN void rtc_FatalMessage(const char* file, int line,
const char* msg) {
static constexpr rtc::webrtc_checks_impl::CheckArgType t[] = {
rtc::webrtc_checks_impl::CheckArgType::kEnd};
FatalLog(file, line, msg, t);
}
<|endoftext|>
|
<commit_before>///
/// @file PhiTiny.cpp
/// @brief phi_tiny(x, a) calculates the partial sieve function in
/// constant time (using lookup tables) for small values of
/// a <= 6 using the formula below:
///
/// phi(x, a) = (x / pp) * φ(pp) + phi(x % pp, a)
/// with pp = 2 * 3 * ... * prime[a]
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PhiTiny.hpp>
#include <int128.hpp>
#include <stdint.h>
#include <vector>
namespace {
const primecount::PhiTiny phiTinySingleton;
}
namespace primecount {
extern const PhiTiny& phiTiny = phiTinySingleton;
const int PhiTiny::primes[7] = { 0, 2, 3, 5, 7, 11, 13 };
/// prime_products[n] = \prod_{i=1}^{n} primes[i]
const int PhiTiny::prime_products[7] = { 1, 2, 6, 30, 210, 2310, 30030 };
/// totients[n] = \prod_{i=1}^{n} (primes[i] - 1)
const int PhiTiny::totients[7] = { 1, 1, 2, 8, 48, 480, 5760 };
PhiTiny::PhiTiny()
{
phi_cache_[0].push_back(0);
// Initialize the phi_cache_ lookup tables
for (int a = 1; a <= max_a(); a++)
{
int size = prime_products[a];
std::vector<int16_t>& cache = phi_cache_[a];
cache.reserve(size);
for (int x = 0; x < size; x++)
{
int16_t phi_xa = (int16_t) (phi(x, a - 1) - phi(x / primes[a], a - 1));
cache.push_back(phi_xa);
}
}
}
} // namespace primecount
<commit_msg>Refactoring<commit_after>///
/// @file PhiTiny.cpp
/// @brief phi_tiny(x, a) calculates the partial sieve function in
/// constant time (using lookup tables) for small values of
/// a <= 6 using the formula below:
///
/// phi(x, a) = (x / pp) * φ(pp) + phi(x % pp, a)
/// with pp = 2 * 3 * ... * prime[a]
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PhiTiny.hpp>
#include <int128.hpp>
#include <stdint.h>
#include <vector>
namespace primecount {
extern const PhiTiny phiTiny = PhiTiny();
const int PhiTiny::primes[7] = { 0, 2, 3, 5, 7, 11, 13 };
/// prime_products[n] = \prod_{i=1}^{n} primes[i]
const int PhiTiny::prime_products[7] = { 1, 2, 6, 30, 210, 2310, 30030 };
/// totients[n] = \prod_{i=1}^{n} (primes[i] - 1)
const int PhiTiny::totients[7] = { 1, 1, 2, 8, 48, 480, 5760 };
PhiTiny::PhiTiny()
{
phi_cache_[0].push_back(0);
// Initialize the phi_cache_ lookup tables
for (int a = 1; a <= max_a(); a++)
{
int size = prime_products[a];
std::vector<int16_t>& cache = phi_cache_[a];
cache.reserve(size);
for (int x = 0; x < size; x++)
{
int16_t phi_xa = (int16_t) (phi(x, a - 1) - phi(x / primes[a], a - 1));
cache.push_back(phi_xa);
}
}
}
} // namespace primecount
<|endoftext|>
|
<commit_before>#include "GeniusCaeli.h"
//Seeded, so of course the same seed should always return the same grid.
void GeniusCaeli::genGrid2D(uint seed){
//Sounds like having a pre-generated grid and letting the values eventually repeat is a
//standard, Ken Perlin-approved approach to make this faster.
std::uniform_real_distribution<float> distribution(0.0f, 2*glm::pi<float>()); //2pi - also known as Tau.
auto random = std::bind(distribution, std::default_random_engine(seed));
for(int i = 0; i < GRIDSIZE; i++){
for(int j = 0; j < GRIDSIZE; j++){
//Pick a random number of radians between 0 and tau.
float angle = random();
grid2D[i][j] = glm::vec2(cos(angle), sin(angle));
}
}
};
float GeniusCaeli::perlin2D(int s, int t){
//I'm basing this on the algorithm described at
//webstaff.itn.liu.se/~stegu/TNM022-2005/perlinnoiselinks/perlin-noise-math-faq.html
//So we've got a whole grid of psuedorandom unit vectors.
//Our point x, y lies somewhere within this grid, probably not on an actual intersection.
//Imagine it as all happening within a single grid cell, surrounded by 4 vectors. Each vector
//will have an influence on the value at x,y depending on how directly it points toward x,y.
//(We use the dot product to determine this.)
//To get the value, we average the dot products(?) and maybe we want it to be a weighted average, too.
//This seems easily extensible to arbitrary numbers of dimensions. So that's nice.
//I'm also not so sure this isn't a task for the shader. But that does me no
//good if I'm trying to be language-agnostic.
//(Assuming I'm actually doing that. Am I?)
//Scale the points.
float x = s * hScale;
float y = t * vScale;
//Find the grid points.
glm::vec2 upperLeft(std::floor(x), std::floor(y + 1));
glm::vec2 upperRight(std::floor(x + 1), std::floor(y + 1));
glm::vec2 lowerLeft(std::floor(x), std::floor(y));
glm::vec2 lowerRight(std::floor(x + 1), std::floor(y));
//Get vectors from the corners of the grid to our chosen point.
glm::vec2 point(x, y);
glm::vec2 posUL = point - upperLeft;
glm::vec2 posUR = point - upperRight;
glm::vec2 posLL = point - lowerLeft;
glm::vec2 posLR = point - lowerRight;
//Use the dot product of the gradient vectors with the point position vectors to determine the influence of each gradient point on the result.
glm::vec2 gradUL = grid2D[int(upperLeft.x)%255][int(upperLeft.y)%255];
glm::vec2 gradUR = grid2D[int(upperRight.x)%255][int(upperRight.y)%255];
glm::vec2 gradLL = grid2D[int(lowerLeft.x)%255][int(lowerLeft.y)%255];
glm::vec2 gradLR = grid2D[int(lowerRight.x)%255][int(lowerRight.y)%255];
float influenceUL = glm::dot(gradUL, posUL);
float influenceUR = glm::dot(gradUR, posUR);
float influenceLL = glm::dot(gradLL, posLL);
float influenceLR = glm::dot(gradLR, posLR);
//I think the main value of the ease curve is that without it, crossing from one grid cell to another
//is a sudden discontinuity, because the influence of the far grid points is suddenly swapped for a different set.
//I want the influence of other grid points to approach zero as we get closer to one particular grid point.
//Actually, is this a thing I could even do linearly?
float weightX = easeCurve(posLL.x); //Getting the gridcell space x coordinate of the point, as opposed to texture space.
float topXAvg = influenceUL + weightX * (influenceUR - influenceUL); //At weight 1, this comes out to influenceUR. At 0, it's influenceUL.
float bottomXAvg = influenceLL + weightX * (influenceLR - influenceLL);
float weightY = easeCurve(posLL.y);
float average = topXAvg + weightY * (bottomXAvg - topXAvg);
//float averageTop = easeCurve(influenceUL, influenceUR); //(influenceUL + influenceUR)/2.0f;
//float averageBottom = easeCurve(influenceLL, influenceLR); //(influenceLL + influenceLR)/2.0f;
//float average = easeCurve(averageTop, averageBottom); //(averageTop + averageBottom)/2.0f;
return average;
};
float GeniusCaeli::easeCurve(float x){
return (3.0f * std::pow(x, 2.0f)) - (2.0f * std::pow(x, 3.0f));
};<commit_msg>Perlin noise is go!<commit_after>#include "GeniusCaeli.h"
//Seeded, so of course the same seed should always return the same grid.
void GeniusCaeli::genGrid2D(uint seed){
//Sounds like having a pre-generated grid and letting the values eventually repeat is a
//standard, Ken Perlin-approved approach to make this faster.
std::uniform_real_distribution<float> distribution(0.0f, 2*glm::pi<float>()); //2pi - also known as Tau.
auto random = std::bind(distribution, std::default_random_engine(seed));
for(int i = 0; i < GRIDSIZE; i++){
for(int j = 0; j < GRIDSIZE; j++){
//Pick a random number of radians between 0 and tau.
float angle = random();
grid2D[i][j] = glm::vec2(cos(angle), sin(angle));
}
}
};
float GeniusCaeli::perlin2D(int s, int t){
//I'm basing this on the algorithm described at
//webstaff.itn.liu.se/~stegu/TNM022-2005/perlinnoiselinks/perlin-noise-math-faq.html
//So we've got a whole grid of psuedorandom unit vectors.
//Our point x, y lies somewhere within this grid, probably not on an actual intersection.
//Imagine it as all happening within a single grid cell, surrounded by 4 vectors. Each vector
//will have an influence on the value at x,y depending on how directly it points toward x,y.
//(We use the dot product to determine this.)
//To get the value, we average the dot products(?) and maybe we want it to be a weighted average, too.
//This seems easily extensible to arbitrary numbers of dimensions. So that's nice.
//I'm also not so sure this isn't a task for the shader. But that does me no
//good if I'm trying to be language-agnostic.
//(Assuming I'm actually doing that. Am I?)
//Scale the points.
float x = s * hScale;
float y = t * vScale;
//Find the grid points.
glm::vec2 upperLeft(std::floor(x), std::floor(y + 1));
glm::vec2 upperRight(std::floor(x + 1), std::floor(y + 1));
glm::vec2 lowerLeft(std::floor(x), std::floor(y));
glm::vec2 lowerRight(std::floor(x + 1), std::floor(y));
//Get vectors from the corners of the grid to our chosen point.
glm::vec2 point(x, y);
glm::vec2 posUL = point - upperLeft;
glm::vec2 posUR = point - upperRight;
glm::vec2 posLL = point - lowerLeft;
glm::vec2 posLR = point - lowerRight;
//Use the dot product of the gradient vectors with the point position vectors to determine the influence of each gradient point on the result.
glm::vec2 gradUL = grid2D[int(upperLeft.x)%255][int(upperLeft.y)%255];
glm::vec2 gradUR = grid2D[int(upperRight.x)%255][int(upperRight.y)%255];
glm::vec2 gradLL = grid2D[int(lowerLeft.x)%255][int(lowerLeft.y)%255];
glm::vec2 gradLR = grid2D[int(lowerRight.x)%255][int(lowerRight.y)%255];
float influenceUL = glm::dot(gradUL, posUL);
float influenceUR = glm::dot(gradUR, posUR);
float influenceLL = glm::dot(gradLL, posLL);
float influenceLR = glm::dot(gradLR, posLR);
//I think the main value of the ease curve is that without it, crossing from one grid cell to another
//is a sudden discontinuity, because the influence of the far grid points is suddenly swapped for a different set.
//I want the influence of other grid points to approach zero as we get closer to one particular grid point.
//Actually, is this a thing I could even do linearly?
float weightX = easeCurve(posLL.x); //Getting the gridcell space x coordinate of the point, as opposed to texture space.
float topXAvg = influenceUL + weightX * (influenceUR - influenceUL); //At weight 1, this comes out to influenceUR. At 0, it's influenceUL.
float bottomXAvg = influenceLL + weightX * (influenceLR - influenceLL);
float weightY = easeCurve(posLL.y);
float average = bottomXAvg + weightY * (topXAvg - bottomXAvg);
return (average + 1.0f)/2.0f;
};
float GeniusCaeli::easeCurve(float x){
return (3.0f * std::pow(x, 2.0f)) - (2.0f * std::pow(x, 3.0f));
};<|endoftext|>
|
<commit_before>#include <QGLWidget>
#include <QMatrix4x4>
#include <QVector3D>
#include <qmath.h>
#include "Logo.hpp"
#include <boost/math/constants/constants.hpp>
using namespace boost::math;
static const qreal bar_thickness = 0.10;
static const qreal logo_depth = 0.10;
static const qreal nleg1_height = 0.55; //the left | in N
static const qreal nleg2_height = 0.58; //the right | in N
static const qreal nbar_height = 0.6; //the \ in N
static const qreal tbar_width = 0.7; //the top of the T
struct Geometry
{
QVector<GLushort> faces;
QVector<QVector3D> vertices;
QVector<QVector3D> normals;
void appendSmooth(const QVector3D &a, const QVector3D &n, int from);
void appendFaceted(const QVector3D &a, const QVector3D &n);
void finalize();
void loadArrays() const;
};
class Patch
{
public:
enum Smoothing { Faceted, Smooth };
Patch(Geometry *);
void setSmoothing(Smoothing s) { sm = s; }
void translate(const QVector3D &t);
void rotate(qreal deg, QVector3D axis);
void draw() const;
void addTri(const QVector3D &a, const QVector3D &b, const QVector3D &c, const QVector3D &n);
void addQuad(const QVector3D &a, const QVector3D &b, const QVector3D &c, const QVector3D &d);
GLushort start;
GLushort count;
GLushort initv;
GLfloat faceColor[4];
QMatrix4x4 mat;
Smoothing sm;
Geometry *geom;
};
static inline void qSetColor(float colorVec[], QColor c)
{
colorVec[0] = c.redF();
colorVec[1] = c.greenF();
colorVec[2] = c.blueF();
colorVec[3] = c.alphaF();
}
void Geometry::loadArrays() const
{
glVertexPointer(3, GL_FLOAT, 0, vertices.constData());
glNormalPointer(GL_FLOAT, 0, normals.constData());
}
void Geometry::finalize()
{
// TODO: add vertex buffer uploading here
// Finish smoothing normals by ensuring accumulated normals are returned
// to length 1.0.
for (int i = 0; i < normals.count(); ++i)
normals[i].normalize();
}
void Geometry::appendSmooth(const QVector3D &a, const QVector3D &n, int from)
{
// Smooth normals are achieved by averaging the normals for faces meeting
// at a point. First find the point in geometry already generated
// (working backwards, since most often the points shared are between faces
// recently added).
int v = vertices.count() - 1;
for ( ; v >= from; --v)
if (qFuzzyCompare(vertices[v], a))
break;
if (v < from)
{
// The vert was not found so add it as a new one, and initialize
// its corresponding normal
v = vertices.count();
vertices.append(a);
normals.append(n);
}
else
{
// Vert found, accumulate normals into corresponding normal slot.
// Must call finalize once finished accumulating normals
normals[v] += n;
}
// In both cases (found or not) reference the vert via its index
faces.append(v);
}
void Geometry::appendFaceted(const QVector3D &a, const QVector3D &n)
{
// Faceted normals are achieved by duplicating the vert for every
// normal, so that faces meeting at a vert get a sharp edge.
int v = vertices.count();
vertices.append(a);
normals.append(n);
faces.append(v);
}
Patch::Patch(Geometry *g)
: start(g->faces.count())
, count(0)
, initv(g->vertices.count())
, sm(Patch::Smooth)
, geom(g)
{
qSetColor(faceColor, QColor(Qt::darkGray));
}
void Patch::rotate(qreal deg, QVector3D axis)
{
mat.rotate(deg, axis);
}
void Patch::translate(const QVector3D &t)
{
mat.translate(t);
}
static inline void qMultMatrix(const QMatrix4x4 &mat)
{
if (sizeof(qreal) == sizeof(GLfloat))
glMultMatrixf((GLfloat*)mat.constData());
#ifndef QT_OPENGL_ES
else if (sizeof(qreal) == sizeof(GLdouble))
glMultMatrixd((GLdouble*)mat.constData());
#endif
else
{
GLfloat fmat[16];
float const *r = mat.constData();
for (int i = 0; i < 16; ++i)
fmat[i] = r[i];
glMultMatrixf(fmat);
}
}
void Patch::draw() const
{
glPushMatrix();
qMultMatrix(mat);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, faceColor);
const GLushort *indices = geom->faces.constData();
glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_SHORT, indices + start);
glPopMatrix();
}
void Patch::addTri(const QVector3D &a, const QVector3D &b, const QVector3D &c, const QVector3D &n)
{
QVector3D norm = n.isNull() ? QVector3D::normal(a, b, c) : n;
if (sm == Smooth)
{
geom->appendSmooth(a, norm, initv);
geom->appendSmooth(b, norm, initv);
geom->appendSmooth(c, norm, initv);
}
else
{
geom->appendFaceted(a, norm);
geom->appendFaceted(b, norm);
geom->appendFaceted(c, norm);
}
count += 3;
}
void Patch::addQuad(const QVector3D &a, const QVector3D &b, const QVector3D &c, const QVector3D &d)
{
QVector3D norm = QVector3D::normal(a, b, c);
if (sm == Smooth)
{
addTri(a, b, c, norm);
addTri(a, c, d, norm);
}
else
{
// If faceted share the two common verts
addTri(a, b, c, norm);
int k = geom->vertices.count();
geom->appendSmooth(a, norm, k);
geom->appendSmooth(c, norm, k);
geom->appendFaceted(d, norm);
count += 3;
}
}
static inline QVector<QVector3D> extrude(const QVector<QVector3D> &verts, qreal depth)
{
QVector<QVector3D> extr = verts;
for (int v = 0; v < extr.count(); ++v)
extr[v].setZ(extr[v].z() - depth);
return extr;
}
class Rectoid
{
public:
void translate(const QVector3D &t)
{
for (int i = 0; i < parts.count(); ++i)
parts[i]->translate(t);
}
void rotate(qreal deg, QVector3D axis)
{
for (int i = 0; i < parts.count(); ++i)
parts[i]->rotate(deg, axis);
}
// No special Rectoid destructor - the parts are fetched out of this member
// variable, and destroyed by the new owner
QList<Patch*> parts;
};
class RectPrism : public Rectoid
{
public:
RectPrism(Geometry *g, qreal width, qreal height, qreal depth);
};
RectPrism::RectPrism(Geometry *g, qreal width, qreal height, qreal depth)
{
enum { bl, br, tr, tl };
Patch *fb = new Patch(g);
fb->setSmoothing(Patch::Faceted);
// front face
QVector<QVector3D> r(4);
r[br].setX(width);
r[tr].setX(width);
r[tr].setY(height);
r[tl].setY(height);
QVector3D adjToCenter(-width / 2.0, -height / 2.0, depth / 2.0);
for (int i = 0; i < 4; ++i)
r[i] += adjToCenter;
fb->addQuad(r[bl], r[br], r[tr], r[tl]);
// back face
QVector<QVector3D> s = extrude(r, depth);
fb->addQuad(s[tl], s[tr], s[br], s[bl]);
// side faces
Patch *sides = new Patch(g);
sides->setSmoothing(Patch::Faceted);
sides->addQuad(s[bl], s[br], r[br], r[bl]);
sides->addQuad(s[br], s[tr], r[tr], r[br]);
sides->addQuad(s[tr], s[tl], r[tl], r[tr]);
sides->addQuad(s[tl], s[bl], r[bl], r[tl]);
parts << fb << sides;
}
class RectTorus : public Rectoid
{
public:
RectTorus(Geometry *g, qreal iRad, qreal oRad, qreal depth, int numSectors);
};
RectTorus::RectTorus(Geometry *g, qreal iRad, qreal oRad, qreal depth, int k)
{
QVector<QVector3D> inside;
QVector<QVector3D> outside;
for (int i = 0; i < k; ++i) {
qreal angle = (i * 2 * constants::pi<qreal>()) / k;
inside << QVector3D(iRad * qSin(angle), iRad * qCos(angle), depth / 2.0);
outside << QVector3D(oRad * qSin(angle), oRad * qCos(angle), depth / 2.0);
}
inside << QVector3D(0.0, iRad, 0.0);
outside << QVector3D(0.0, oRad, 0.0);
QVector<QVector3D> in_back = extrude(inside, depth);
QVector<QVector3D> out_back = extrude(outside, depth);
// Create front, back and sides as separate patches so that smooth normals
// are generated for the curving sides, but a faceted edge is created between
// sides and front/back
Patch *front = new Patch(g);
for (int i = 0; i < k; ++i)
front->addQuad(outside[i], inside[i],
inside[(i + 1) % k], outside[(i + 1) % k]);
Patch *back = new Patch(g);
for (int i = 0; i < k; ++i)
back->addQuad(in_back[i], out_back[i],
out_back[(i + 1) % k], in_back[(i + 1) % k]);
Patch *is = new Patch(g);
for (int i = 0; i < k; ++i)
is->addQuad(in_back[i], in_back[(i + 1) % k],
inside[(i + 1) % k], inside[i]);
Patch *os = new Patch(g);
for (int i = 0; i < k; ++i)
os->addQuad(out_back[(i + 1) % k], out_back[i],
outside[i], outside[(i + 1) % k]);
parts << front << back << is << os;
}
Logo::Logo(QObject *parent, qreal scale)
: QObject(parent)
, geom(new Geometry())
{
buildGeometry(scale);
}
Logo::~Logo()
{
qDeleteAll(parts);
delete geom;
}
void Logo::setColor(QColor c)
{
for (int i = 0; i < parts.count(); ++i)
qSetColor(parts[i]->faceColor, c);
}
void Logo::buildGeometry(qreal scale)
{
qreal ld = logo_depth * scale;
qreal bt = bar_thickness * scale;
qreal n1h = nleg1_height * scale;
qreal n2h = nleg2_height * scale;
qreal nb = nbar_height * scale;
qreal tb = tbar_width * scale;
QVector3D z(0.0, 0.0, 1.0);
//qreal stem_downshift = (th + bt) / 2.0;
//stem.translate(QVector3D(0.0, -stem_downshift, 0.0));
RectPrism leg1(geom, bt, n1h, ld);
RectPrism leg2(geom, bt, n2h, ld);
RectPrism nbar(geom, bt, nb, ld);
RectPrism tbar(geom, tb, bt, ld);
double rnbar = 35;
double partsciencepartguess = sin(rnbar*3.14/180)*nb*0.5-0.05;
leg1.translate(QVector3D(-0.24,0.0,0.0));
leg2.translate(QVector3D(partsciencepartguess,(n2h-n1h)/2,0.0));
nbar.rotate(rnbar,z);
nbar.translate(QVector3D(-.05,0.035,0.0));
tbar.translate(QVector3D(partsciencepartguess,(n2h+bt)/2 , 0.0));
parts << leg1.parts << leg2.parts << nbar.parts << tbar.parts;
geom->finalize();
}
void Logo::draw() const
{
geom->loadArrays();
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
for (int i = 0; i < parts.count(); ++i)
parts[i]->draw();
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
}
// vim: set ts=4 sw=4 et! :
<commit_msg>Be backwards compatible with 4.* Qt<commit_after>#include <QGLWidget>
#include <QMatrix4x4>
#include <QVector3D>
#include <qmath.h>
#include "Logo.hpp"
#include <boost/math/constants/constants.hpp>
using namespace boost::math;
static const qreal bar_thickness = 0.10;
static const qreal logo_depth = 0.10;
static const qreal nleg1_height = 0.55; //the left | in N
static const qreal nleg2_height = 0.58; //the right | in N
static const qreal nbar_height = 0.6; //the \ in N
static const qreal tbar_width = 0.7; //the top of the T
struct Geometry
{
QVector<GLushort> faces;
QVector<QVector3D> vertices;
QVector<QVector3D> normals;
void appendSmooth(const QVector3D &a, const QVector3D &n, int from);
void appendFaceted(const QVector3D &a, const QVector3D &n);
void finalize();
void loadArrays() const;
};
class Patch
{
public:
enum Smoothing { Faceted, Smooth };
Patch(Geometry *);
void setSmoothing(Smoothing s) { sm = s; }
void translate(const QVector3D &t);
void rotate(qreal deg, QVector3D axis);
void draw() const;
void addTri(const QVector3D &a, const QVector3D &b, const QVector3D &c, const QVector3D &n);
void addQuad(const QVector3D &a, const QVector3D &b, const QVector3D &c, const QVector3D &d);
GLushort start;
GLushort count;
GLushort initv;
GLfloat faceColor[4];
QMatrix4x4 mat;
Smoothing sm;
Geometry *geom;
};
static inline void qSetColor(float colorVec[], QColor c)
{
colorVec[0] = c.redF();
colorVec[1] = c.greenF();
colorVec[2] = c.blueF();
colorVec[3] = c.alphaF();
}
void Geometry::loadArrays() const
{
glVertexPointer(3, GL_FLOAT, 0, vertices.constData());
glNormalPointer(GL_FLOAT, 0, normals.constData());
}
void Geometry::finalize()
{
// TODO: add vertex buffer uploading here
// Finish smoothing normals by ensuring accumulated normals are returned
// to length 1.0.
for (int i = 0; i < normals.count(); ++i)
normals[i].normalize();
}
void Geometry::appendSmooth(const QVector3D &a, const QVector3D &n, int from)
{
// Smooth normals are achieved by averaging the normals for faces meeting
// at a point. First find the point in geometry already generated
// (working backwards, since most often the points shared are between faces
// recently added).
int v = vertices.count() - 1;
for ( ; v >= from; --v)
if (qFuzzyCompare(vertices[v], a))
break;
if (v < from)
{
// The vert was not found so add it as a new one, and initialize
// its corresponding normal
v = vertices.count();
vertices.append(a);
normals.append(n);
}
else
{
// Vert found, accumulate normals into corresponding normal slot.
// Must call finalize once finished accumulating normals
normals[v] += n;
}
// In both cases (found or not) reference the vert via its index
faces.append(v);
}
void Geometry::appendFaceted(const QVector3D &a, const QVector3D &n)
{
// Faceted normals are achieved by duplicating the vert for every
// normal, so that faces meeting at a vert get a sharp edge.
int v = vertices.count();
vertices.append(a);
normals.append(n);
faces.append(v);
}
Patch::Patch(Geometry *g)
: start(g->faces.count())
, count(0)
, initv(g->vertices.count())
, sm(Patch::Smooth)
, geom(g)
{
qSetColor(faceColor, QColor(Qt::darkGray));
}
void Patch::rotate(qreal deg, QVector3D axis)
{
mat.rotate(deg, axis);
}
void Patch::translate(const QVector3D &t)
{
mat.translate(t);
}
static inline void qMultMatrix(const QMatrix4x4 &mat)
{
if (sizeof(qreal) == sizeof(GLfloat))
glMultMatrixf((GLfloat*)mat.constData());
#ifndef QT_OPENGL_ES
else if (sizeof(qreal) == sizeof(GLdouble))
glMultMatrixd((GLdouble*)mat.constData());
#endif
else
{
GLfloat fmat[16];
#if QT_VERSION >= 0x050000
const float* r = mat.constData();
#else
const qreal* r = mat.constData();
#endif
for (int i = 0; i < 16; ++i)
fmat[i] = r[i];
glMultMatrixf(fmat);
}
}
void Patch::draw() const
{
glPushMatrix();
qMultMatrix(mat);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, faceColor);
const GLushort *indices = geom->faces.constData();
glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_SHORT, indices + start);
glPopMatrix();
}
void Patch::addTri(const QVector3D &a, const QVector3D &b, const QVector3D &c, const QVector3D &n)
{
QVector3D norm = n.isNull() ? QVector3D::normal(a, b, c) : n;
if (sm == Smooth)
{
geom->appendSmooth(a, norm, initv);
geom->appendSmooth(b, norm, initv);
geom->appendSmooth(c, norm, initv);
}
else
{
geom->appendFaceted(a, norm);
geom->appendFaceted(b, norm);
geom->appendFaceted(c, norm);
}
count += 3;
}
void Patch::addQuad(const QVector3D &a, const QVector3D &b, const QVector3D &c, const QVector3D &d)
{
QVector3D norm = QVector3D::normal(a, b, c);
if (sm == Smooth)
{
addTri(a, b, c, norm);
addTri(a, c, d, norm);
}
else
{
// If faceted share the two common verts
addTri(a, b, c, norm);
int k = geom->vertices.count();
geom->appendSmooth(a, norm, k);
geom->appendSmooth(c, norm, k);
geom->appendFaceted(d, norm);
count += 3;
}
}
static inline QVector<QVector3D> extrude(const QVector<QVector3D> &verts, qreal depth)
{
QVector<QVector3D> extr = verts;
for (int v = 0; v < extr.count(); ++v)
extr[v].setZ(extr[v].z() - depth);
return extr;
}
class Rectoid
{
public:
void translate(const QVector3D &t)
{
for (int i = 0; i < parts.count(); ++i)
parts[i]->translate(t);
}
void rotate(qreal deg, QVector3D axis)
{
for (int i = 0; i < parts.count(); ++i)
parts[i]->rotate(deg, axis);
}
// No special Rectoid destructor - the parts are fetched out of this member
// variable, and destroyed by the new owner
QList<Patch*> parts;
};
class RectPrism : public Rectoid
{
public:
RectPrism(Geometry *g, qreal width, qreal height, qreal depth);
};
RectPrism::RectPrism(Geometry *g, qreal width, qreal height, qreal depth)
{
enum { bl, br, tr, tl };
Patch *fb = new Patch(g);
fb->setSmoothing(Patch::Faceted);
// front face
QVector<QVector3D> r(4);
r[br].setX(width);
r[tr].setX(width);
r[tr].setY(height);
r[tl].setY(height);
QVector3D adjToCenter(-width / 2.0, -height / 2.0, depth / 2.0);
for (int i = 0; i < 4; ++i)
r[i] += adjToCenter;
fb->addQuad(r[bl], r[br], r[tr], r[tl]);
// back face
QVector<QVector3D> s = extrude(r, depth);
fb->addQuad(s[tl], s[tr], s[br], s[bl]);
// side faces
Patch *sides = new Patch(g);
sides->setSmoothing(Patch::Faceted);
sides->addQuad(s[bl], s[br], r[br], r[bl]);
sides->addQuad(s[br], s[tr], r[tr], r[br]);
sides->addQuad(s[tr], s[tl], r[tl], r[tr]);
sides->addQuad(s[tl], s[bl], r[bl], r[tl]);
parts << fb << sides;
}
class RectTorus : public Rectoid
{
public:
RectTorus(Geometry *g, qreal iRad, qreal oRad, qreal depth, int numSectors);
};
RectTorus::RectTorus(Geometry *g, qreal iRad, qreal oRad, qreal depth, int k)
{
QVector<QVector3D> inside;
QVector<QVector3D> outside;
for (int i = 0; i < k; ++i) {
qreal angle = (i * 2 * constants::pi<qreal>()) / k;
inside << QVector3D(iRad * qSin(angle), iRad * qCos(angle), depth / 2.0);
outside << QVector3D(oRad * qSin(angle), oRad * qCos(angle), depth / 2.0);
}
inside << QVector3D(0.0, iRad, 0.0);
outside << QVector3D(0.0, oRad, 0.0);
QVector<QVector3D> in_back = extrude(inside, depth);
QVector<QVector3D> out_back = extrude(outside, depth);
// Create front, back and sides as separate patches so that smooth normals
// are generated for the curving sides, but a faceted edge is created between
// sides and front/back
Patch *front = new Patch(g);
for (int i = 0; i < k; ++i)
front->addQuad(outside[i], inside[i],
inside[(i + 1) % k], outside[(i + 1) % k]);
Patch *back = new Patch(g);
for (int i = 0; i < k; ++i)
back->addQuad(in_back[i], out_back[i],
out_back[(i + 1) % k], in_back[(i + 1) % k]);
Patch *is = new Patch(g);
for (int i = 0; i < k; ++i)
is->addQuad(in_back[i], in_back[(i + 1) % k],
inside[(i + 1) % k], inside[i]);
Patch *os = new Patch(g);
for (int i = 0; i < k; ++i)
os->addQuad(out_back[(i + 1) % k], out_back[i],
outside[i], outside[(i + 1) % k]);
parts << front << back << is << os;
}
Logo::Logo(QObject *parent, qreal scale)
: QObject(parent)
, geom(new Geometry())
{
buildGeometry(scale);
}
Logo::~Logo()
{
qDeleteAll(parts);
delete geom;
}
void Logo::setColor(QColor c)
{
for (int i = 0; i < parts.count(); ++i)
qSetColor(parts[i]->faceColor, c);
}
void Logo::buildGeometry(qreal scale)
{
qreal ld = logo_depth * scale;
qreal bt = bar_thickness * scale;
qreal n1h = nleg1_height * scale;
qreal n2h = nleg2_height * scale;
qreal nb = nbar_height * scale;
qreal tb = tbar_width * scale;
QVector3D z(0.0, 0.0, 1.0);
//qreal stem_downshift = (th + bt) / 2.0;
//stem.translate(QVector3D(0.0, -stem_downshift, 0.0));
RectPrism leg1(geom, bt, n1h, ld);
RectPrism leg2(geom, bt, n2h, ld);
RectPrism nbar(geom, bt, nb, ld);
RectPrism tbar(geom, tb, bt, ld);
double rnbar = 35;
double partsciencepartguess = sin(rnbar*3.14/180)*nb*0.5-0.05;
leg1.translate(QVector3D(-0.24,0.0,0.0));
leg2.translate(QVector3D(partsciencepartguess,(n2h-n1h)/2,0.0));
nbar.rotate(rnbar,z);
nbar.translate(QVector3D(-.05,0.035,0.0));
tbar.translate(QVector3D(partsciencepartguess,(n2h+bt)/2 , 0.0));
parts << leg1.parts << leg2.parts << nbar.parts << tbar.parts;
geom->finalize();
}
void Logo::draw() const
{
geom->loadArrays();
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
for (int i = 0; i < parts.count(); ++i)
parts[i]->draw();
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
}
// vim: set ts=4 sw=4 et! :
<|endoftext|>
|
<commit_before>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// 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 <cmath>
#include "convpool.hpp"
#include "core/attribute.hpp"
#include "core/node.hpp"
#include "ngraph/coordinate_diff.hpp"
#include "ngraph/shape.hpp"
namespace ngraph
{
namespace onnx_import
{
namespace convpool
{
Shape get_kernel_shape(const Node& node)
{
std::size_t input_spatial_dims = node.get_ng_inputs().at(0)->get_shape().size() - 2;
return node.get_attribute_value<std::vector<std::size_t>>(
"kernel_shape", std::vector<std::size_t>(input_spatial_dims, 1UL));
}
namespace detail
{
Strides get_strides_helper(const Node& node,
const std::string& name,
const Shape& kernel_shape)
{
return node.get_attribute_value<std::vector<std::size_t>>(
name, std::vector<std::size_t>(kernel_shape.size(), 1UL));
}
} // namespace detail
Strides get_strides(const Node& node, const Shape& kernel_shape)
{
return detail::get_strides_helper(node, "strides", kernel_shape);
}
Strides get_strides(const Node& node)
{
return get_strides(node, get_kernel_shape(node));
}
Strides get_dilations(const Node& node)
{
return detail::get_strides_helper(node, "dilations", get_kernel_shape(node));
}
namespace
{
Shape get_output_data_shape(const Shape& input, const Strides& strides)
{
Shape output;
for (std::size_t idx = 0; idx < input.size(); ++idx)
{
output.emplace_back(std::ceil(static_cast<float>(input.at(idx)) /
static_cast<float>(strides.at(idx))));
}
return output;
}
Shape get_pad_shape(const Shape& input,
const Shape& kernel,
const Shape& strides,
const Shape& output)
{
Shape pad_shape;
for (std::size_t idx = 0; idx < input.size(); ++idx)
{
pad_shape.emplace_back((output.at(idx) - 1) * strides.at(idx) +
kernel.at(idx) - input.at(idx));
}
return pad_shape;
}
CoordinateDiff get_auto_pads(const Shape& input_shape,
const Shape& kernel_shape,
const Strides& strides,
const std::string& auto_pad)
{
CoordinateDiff pads_begin;
CoordinateDiff pads_end;
// Omit {N,C} axes
Shape input_spatial_shape{std::next(std::begin(input_shape), 2),
std::end(input_shape)};
// Assume that all {input_spatial_shape,kernel_shape,strides}.size()
// is the same.
const Shape& output_spatial_shape =
get_output_data_shape(input_spatial_shape, strides);
const Shape& pad_shape = get_pad_shape(
input_spatial_shape, kernel_shape, strides, output_spatial_shape);
if (auto_pad == "SAME_UPPER")
{
for (size_t pad : pad_shape)
{
// Integer division
pads_begin.emplace_back(pad / 2);
pads_end.emplace_back(pad - pads_begin.back());
}
}
else if (auto_pad == "SAME_LOWER")
{
for (size_t pad : pad_shape)
{
// Integer division
pads_end.emplace_back(pad / 2);
pads_begin.emplace_back(pad - pads_end.back());
}
}
CoordinateDiff pads{pads_begin};
pads.insert(std::end(pads), std::begin(pads_end), std::end(pads_end));
return pads;
}
} // namespace
std::pair<CoordinateDiff, CoordinateDiff> get_pads(const Node& node,
const Shape& kernel_shape)
{
CoordinateDiff pads;
try
{
auto pads_int64 = node.get_attribute_value<std::vector<int64_t>>("pads");
pads = CoordinateDiff{std::begin(pads_int64), std::end(pads_int64)};
}
catch (const error::node::UnknownAttribute&)
{
std::string auto_pad{node.get_attribute_value<std::string>("auto_pad", "")};
if (!auto_pad.empty())
{
pads = get_auto_pads(node.get_ng_inputs().at(0)->get_shape(),
kernel_shape,
get_strides(node),
auto_pad);
}
}
if (pads.empty())
{
pads = CoordinateDiff(static_cast<std::ptrdiff_t>(kernel_shape.size()), 0UL);
}
if (pads.size() != kernel_shape.size() * 2)
{
// Paddings specified in (H, W, C) format.
return {pads, pads};
}
else
{
return {{std::begin(pads), std::begin(pads) + pads.size() / 2},
{std::begin(pads) + pads.size() / 2, std::end(pads)}};
}
}
} // namespace convpool
} // namespace onnx_import
} // namespace ngraph
<commit_msg>[ONNX] Add valid padding support (#2628)<commit_after>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// 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 <cmath>
#include "convpool.hpp"
#include "core/attribute.hpp"
#include "core/node.hpp"
#include "ngraph/coordinate_diff.hpp"
#include "ngraph/shape.hpp"
namespace ngraph
{
namespace onnx_import
{
namespace convpool
{
Shape get_kernel_shape(const Node& node)
{
std::size_t input_spatial_dims = node.get_ng_inputs().at(0)->get_shape().size() - 2;
return node.get_attribute_value<std::vector<std::size_t>>(
"kernel_shape", std::vector<std::size_t>(input_spatial_dims, 1UL));
}
namespace detail
{
Strides get_strides_helper(const Node& node,
const std::string& name,
const Shape& kernel_shape)
{
return node.get_attribute_value<std::vector<std::size_t>>(
name, std::vector<std::size_t>(kernel_shape.size(), 1UL));
}
} // namespace detail
Strides get_strides(const Node& node, const Shape& kernel_shape)
{
return detail::get_strides_helper(node, "strides", kernel_shape);
}
Strides get_strides(const Node& node)
{
return get_strides(node, get_kernel_shape(node));
}
Strides get_dilations(const Node& node)
{
return detail::get_strides_helper(node, "dilations", get_kernel_shape(node));
}
namespace
{
Shape get_output_data_shape(const Shape& input, const Strides& strides)
{
Shape output;
for (std::size_t idx = 0; idx < input.size(); ++idx)
{
output.emplace_back(std::ceil(static_cast<float>(input.at(idx)) /
static_cast<float>(strides.at(idx))));
}
return output;
}
Shape get_pad_shape(const Shape& input,
const Shape& kernel,
const Shape& strides,
const Shape& output)
{
Shape pad_shape;
for (std::size_t idx = 0; idx < input.size(); ++idx)
{
pad_shape.emplace_back((output.at(idx) - 1) * strides.at(idx) +
kernel.at(idx) - input.at(idx));
}
return pad_shape;
}
CoordinateDiff get_auto_pads(const Shape& input_shape,
const Shape& kernel_shape,
const Strides& strides,
const std::string& auto_pad)
{
if (auto_pad == "VALID")
{
return CoordinateDiff(input_shape.size());
}
CoordinateDiff pads_begin;
CoordinateDiff pads_end;
// Omit {N,C} axes
Shape input_spatial_shape{std::next(std::begin(input_shape), 2),
std::end(input_shape)};
// Assume that all {input_spatial_shape,kernel_shape,strides}.size()
// is the same.
const Shape& output_spatial_shape =
get_output_data_shape(input_spatial_shape, strides);
const Shape& pad_shape = get_pad_shape(
input_spatial_shape, kernel_shape, strides, output_spatial_shape);
if (auto_pad == "SAME_UPPER")
{
for (size_t pad : pad_shape)
{
// Integer division
pads_begin.emplace_back(pad / 2);
pads_end.emplace_back(pad - pads_begin.back());
}
}
else if (auto_pad == "SAME_LOWER")
{
for (size_t pad : pad_shape)
{
// Integer division
pads_end.emplace_back(pad / 2);
pads_begin.emplace_back(pad - pads_end.back());
}
}
CoordinateDiff pads{pads_begin};
pads.insert(std::end(pads), std::begin(pads_end), std::end(pads_end));
return pads;
}
} // namespace
std::pair<CoordinateDiff, CoordinateDiff> get_pads(const Node& node,
const Shape& kernel_shape)
{
CoordinateDiff pads;
try
{
auto pads_int64 = node.get_attribute_value<std::vector<int64_t>>("pads");
pads = CoordinateDiff{std::begin(pads_int64), std::end(pads_int64)};
}
catch (const error::node::UnknownAttribute&)
{
std::string auto_pad{node.get_attribute_value<std::string>("auto_pad", "")};
if (!auto_pad.empty())
{
pads = get_auto_pads(node.get_ng_inputs().at(0)->get_shape(),
kernel_shape,
get_strides(node),
auto_pad);
}
}
if (pads.empty())
{
pads = CoordinateDiff(static_cast<std::ptrdiff_t>(kernel_shape.size()), 0UL);
}
if (pads.size() != kernel_shape.size() * 2)
{
// Paddings specified in (H, W, C) format.
return {pads, pads};
}
else
{
return {{std::begin(pads), std::begin(pads) + pads.size() / 2},
{std::begin(pads) + pads.size() / 2, std::end(pads)}};
}
}
} // namespace convpool
} // namespace onnx_import
} // namespace ngraph
<|endoftext|>
|
<commit_before>#include "gl.hpp"
#include <QApplication>
#include <QOpenGLWidget>
#include <QOpenGLShaderProgram>
#include "eigen.hpp"
#include <array>
using namespace eigen;
struct mesh {
vector<vec3> vertices;
vector<vec3> normals;
vector<vec2> texcoords;
};
namespace gl {
struct camera {
vec3 pos;
quat orient;
real fovy = M_PI / 3;
real ratio = 1.0;
real znear = 0, zfar = 10;
using mat4x4 = matrix<GLfloat, 4, 4>;
mat4x4 projection() const {
mat4x4 res;
const real half_fovy = fovy / 2;
const real f = std::cos(half_fovy) / std::sin(half_fovy);
const real zsum = zfar + znear;
const real zdiff = zfar - znear;
res <<
f / ratio, 0, 0, 0,
0, f, 0, 0,
0, 0, zsum / zdiff, 2 * znear * zfar / zdiff,
0, 0, -1, 0;
return res;
}
mat4x4 modelview() const {
mat4x4 res;
const mat3x3 RT = orient.conjugate().matrix();
res <<
RT.cast<GLfloat>(), -(RT * pos).cast<GLfloat>(),
0, 0, 0, 1;
return res;
}
void enable() {
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadMatrixf(projection().data());
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadMatrixf(modelview().data());
}
void disable() {
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
}
auto use() {
enable();
return finally([this] { disable(); });
}
};
} // namespace gl
struct Viewer: QOpenGLWidget {
gl::geometry geo;
gl::camera cam;
QOpenGLShaderProgram program;
void initializeGL() override {
static std::vector<std::array<GLfloat, 3>> positions = {
{0, 0, 0},
{1, 0, 0},
{0, -1, 0},
{0, 1, 0},
{1, 0, 0},
{0, 0, 0},
};
geo.vertex.data(positions);
geo.color.data(positions);
cam.pos.z() = 2;
}
// void resizeGL(int width, int height) override {
// glViewport(0, 0, width, height);
// }
void paintGL() override {
const auto cam = this->cam.use();
const auto geo = this->geo.use();
glDrawArrays(GL_TRIANGLES, 0, 6);
}
};
int main(int argc, char** argv) {
QApplication app(argc, argv);
Viewer widget;
widget.show();
return app.exec();
}
<commit_msg>camera<commit_after>#include "gl.hpp"
#include <QApplication>
#include <QOpenGLWidget>
#include "eigen.hpp"
#include <array>
using namespace eigen;
struct mesh {
vector<vec3> vertices;
vector<vec3> normals;
vector<vec2> texcoords;
};
namespace gl {
struct camera {
vec3 pos;
quat orient;
real fovy = M_PI / 3;
real ratio = 1.0;
real znear = 0, zfar = 10;
using mat4x4 = matrix<GLfloat, 4, 4>;
mat4x4 projection() const {
mat4x4 res;
const real half_fovy = fovy / 2;
const real f = std::cos(half_fovy) / std::sin(half_fovy);
const real zsum = zfar + znear;
const real zdiff = zfar - znear;
res <<
f / ratio, 0, 0, 0,
0, f, 0, 0,
0, 0, zsum / zdiff, 2 * znear * zfar / zdiff,
0, 0, -1, 0;
return res;
}
mat4x4 modelview() const {
mat4x4 res;
const mat3x3 RT = orient.conjugate().matrix();
res <<
RT.cast<GLfloat>(), -(RT * pos).cast<GLfloat>(),
0, 0, 0, 1;
return res;
}
void enable() {
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadMatrixf(projection().data());
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadMatrixf(modelview().data());
}
void disable() {
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
}
auto use() {
enable();
return finally([this] { disable(); });
}
};
} // namespace gl
struct Viewer: QOpenGLWidget {
gl::geometry geo;
gl::camera cam;
void initializeGL() override {
static std::vector<std::array<GLfloat, 3>> positions = {
{0, 0, 0},
{1, 0, 0},
{0, -1, 0},
{0, 1, 0},
{1, 0, 0},
{0, 0, 0},
};
geo.vertex.data(positions);
geo.color.data(positions);
cam.pos.z() = 2;
}
void resizeGL(int width, int height) override {
glViewport(0, 0, width, height);
cam.ratio = real(width) / real(height);
}
void paintGL() override {
const auto cam = this->cam.use();
const auto geo = this->geo.use();
glDrawArrays(GL_TRIANGLES, 0, 6);
}
};
int main(int argc, char** argv) {
QApplication app(argc, argv);
Viewer widget;
widget.show();
return app.exec();
}
<|endoftext|>
|
<commit_before>/*
* This file is part of knarr
*
* (c) 2016- Daniele De Sensi (d.desensi.software@gmail.com)
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#include "external/cppnanomsg/nn.hpp"
#include "knarr.hpp"
#include <cmath>
#include <errno.h>
#include <limits>
#include <stdexcept>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
#undef DEBUG
#undef DEBUGB
#ifdef DEBUG_KNARR
#define DEBUG(x) do { std::cerr << "[Knarr] " << x << std::endl; } while (0)
#define DEBUGB(x) do {x;} while (0)
#else
#define DEBUG(x)
#define DEBUGB(x)
#endif
namespace knarr{
unsigned long long getCurrentTimeNs(){
#ifdef KNARR_NS_PER_TICK
return rdtsc() / KNARR_NS_PER_TICK;
#else
struct timespec tp;
int r = clock_gettime(CLOCK_MONOTONIC, &tp);
assert(!r);
return tp.tv_sec * 1.0e9 + tp.tv_nsec;
#endif
}
inline void waitSampleStore(Application* application){
/*
if(application->_configuration.samplingLengthMs > 0){
usleep((1000 * application->_configuration.samplingLengthMs) / application->_threadData.size());
}else{
usleep(1000);
}*/
usleep(1000);
}
inline bool thisSampleNeeded(Application* application, size_t threadId, size_t updatedSamples, bool fromAll){
// If we need samples from all the threads
// or
// If this is the last thread and there are no
// samples stored, then we need this sample.
return (fromAll ||
application->_configuration.threadsNeeded == KNARR_THREADS_NEEDED_ALL ||
((threadId == application->_threadData.size() - 1) &&
!updatedSamples &&
application->_configuration.threadsNeeded == KNARR_THREADS_NEEDED_ONE));
}
inline bool keepWaitingSample(Application* application, size_t threadId, size_t updatedSamples, bool fromAll){
if(*application->_threadData[threadId].consolidate){
if(thisSampleNeeded(application, threadId, updatedSamples, fromAll) &&
!application->_supportStop){
return true;
}
// If we don't need to wait for thread sample,
// stop waiting.
if(application->_configuration.threadsNeeded == KNARR_THREADS_NEEDED_NONE ||
(application->_configuration.threadsNeeded == KNARR_THREADS_NEEDED_ONE && updatedSamples >= 1) ||
application->_supportStop){
return false;
}
return true;
}
return false;
}
void* applicationSupportThread(void* data){
Application* application = static_cast<Application*>(data);
while(!application->_supportStop){
Message recvdMsg;
int res = application->_channelRef.recv(&recvdMsg, sizeof(recvdMsg), 0);
bool fromAll = recvdMsg.payload.fromAll;
if(res == sizeof(recvdMsg)){
assert(recvdMsg.type == MESSAGE_TYPE_SAMPLE_REQ);
// Prepare response message.
Message msg;
msg.type = MESSAGE_TYPE_SAMPLE_RES;
msg.payload.sample = ApplicationSample(); // Set sample to all zeros
// Add the samples of all the threads.
size_t updatedSamples = 0, inconsistentSamples = 0;
size_t numThreads = application->_threadData.size();
std::vector<double> customVec[KNARR_MAX_CUSTOM_FIELDS];
assert(KNARR_THREADS_NEEDED_ALL); // TODO At the moment we only support this case
for(size_t i = 0; i < numThreads; i++){
*application->_threadData[i].consolidate = true;
}
for(size_t i = 0; i < numThreads; i++){
// If needed, wait for thread to store a sample.
while(keepWaitingSample(application, i, updatedSamples, fromAll)){
waitSampleStore(application);
}
ThreadData& toAdd = application->_threadData[i];
if(!*toAdd.consolidate){
ApplicationSample& sample = toAdd.consolidatedSample;
if(sample.latency == KNARR_VALUE_INCONSISTENT){
++inconsistentSamples;
}else{
sample.latency /= sample.numTasks;
msg.payload.sample.loadPercentage += sample.loadPercentage;
msg.payload.sample.latency += sample.latency;
}
msg.payload.sample.bandwidth += sample.bandwidth;
msg.payload.sample.numTasks += sample.numTasks;
++updatedSamples;
for(size_t j = 0; j < KNARR_MAX_CUSTOM_FIELDS; j++){
// TODO How to manage not-yet-stored custom values?
customVec[j].push_back(sample.customFields[j]);
}
}
}
// If at least one thread is progressing.
if(updatedSamples){
if(application->_configuration.adjustBandwidth &&
updatedSamples != numThreads){
// This can only happen if we didn't need to store
// data from all the threads
if(!application->_supportStop){
assert(application->_configuration.threadsNeeded != KNARR_THREADS_NEEDED_ALL);
}
msg.payload.sample.bandwidth += (msg.payload.sample.bandwidth / updatedSamples) * (numThreads - updatedSamples);
}
// If we collected only inconsistent samples, we mark latency and load as inconsistent.
if(inconsistentSamples == updatedSamples){
msg.payload.sample.loadPercentage = KNARR_VALUE_INCONSISTENT;
msg.payload.sample.latency = KNARR_VALUE_INCONSISTENT;
}else{
msg.payload.sample.loadPercentage /= updatedSamples;
msg.payload.sample.latency /= updatedSamples;
}
}else{
// This can only happens if the threadsNeeded is NONE
if(!application->_supportStop){
assert(application->_configuration.threadsNeeded == KNARR_THREADS_NEEDED_NONE);
}
msg.payload.sample.bandwidth = 0;
msg.payload.sample.latency = KNARR_VALUE_NOT_AVAILABLE;
msg.payload.sample.loadPercentage = 0;
msg.payload.sample.numTasks = 0;
}
// Aggregate custom values.
if(application->_aggregator){
for(size_t i = 0; i < KNARR_MAX_CUSTOM_FIELDS; i++){
msg.payload.sample.customFields[i] = application->_aggregator->aggregate(i, customVec[i]);
}
}
DEBUG(msg.payload.sample);
// Send message
if(!application->_supportStop){
application->_channelRef.send(&msg, sizeof(msg), 0);
}
}else if(res == -1){
throw std::runtime_error("Received less bytes than expected.");
}
}
return NULL;
}
Application::Application(const std::string& channelName, size_t numThreads,
Aggregator* aggregator):
_channel(new nn::socket(AF_SP, NN_PAIR)), _channelRef(*_channel),
_started(false), _aggregator(aggregator), _executionTime(0), _totalTasks(0){
_chid = _channelRef.connect(channelName.c_str());
assert(_chid >= 0);
pthread_mutex_init(&_mutex, NULL);
_supportStop = false;
_threadData.resize(numThreads);
// Pthread Create must be the last thing we do in constructor
pthread_create(&_supportTid, NULL, applicationSupportThread, (void*) this);
}
Application::Application(nn::socket& socket, uint chid, size_t numThreads,
Aggregator* aggregator):
_channel(NULL), _channelRef(socket), _chid(chid), _started(false),
_aggregator(aggregator), _executionTime(0), _totalTasks(0){
pthread_mutex_init(&_mutex, NULL);
_supportStop = false;
_threadData.resize(numThreads);
// Pthread Create must be the last thing we do in constructor
pthread_create(&_supportTid, NULL, applicationSupportThread, (void*) this);
}
Application::~Application(){
if(_channel){
_channel->shutdown(_chid);
delete _channel;
}
}
void Application::notifyStart(){
Message msg;
msg.type = MESSAGE_TYPE_START;
msg.payload.pid = getpid();
int r = _channelRef.send(&msg, sizeof(msg), 0);
assert(r == sizeof(msg));
}
ulong Application::updateSamplingLength(unsigned long long numTasks, unsigned long long sampleTime){
if(numTasks){
double latencyNs = sampleTime / numTasks;
double latencyMs = latencyNs / 1000000.0;
// If samplingLength == 1 we would have one begin()-end() pair every latencyMs milliseconds
if(latencyMs){
return std::ceil((double) _configuration.samplingLengthMs / latencyMs);
}else{
return KNARR_DEFAULT_SAMPLING_LENGTH;
}
}else{
throw std::runtime_error("updateSamplingLength called with no tasks stored.");
}
}
void Application::setConfiguration(const ApplicationConfiguration& configuration){
_configuration = configuration;
}
void Application::setConfigurationStreaming(){
ApplicationConfiguration configuration;
configuration.threadsNeeded = KNARR_THREADS_NEEDED_NONE;
configuration.adjustBandwidth = true;
_configuration = configuration;
}
void Application::setConfigurationBatch(ThreadsNeeded threadsNeeded){
ApplicationConfiguration configuration;
configuration.threadsNeeded = threadsNeeded;
configuration.adjustBandwidth = true;
_configuration = configuration;
}
void Application::storeCustomValue(size_t index, double value, uint threadId){
if(threadId > _threadData.size()){
throw new std::runtime_error("Wrong threadId specified (greater than number of threads).");
}
if(index < KNARR_MAX_CUSTOM_FIELDS){
ThreadData& tData = _threadData[threadId];
tData.sample.customFields[index] = value;
}else{
throw std::runtime_error("Custom value index out of bound. Please "
"increase KNARR_MAX_CUSTOM_FIELDS macro value.");
}
}
void Application::terminate(){
unsigned long long lastEnd = 0, firstBegin = std::numeric_limits<unsigned long long>::max();
for(ThreadData& td : _threadData){
// If I was doing sampling, I could have spurious
// tasks that I didn't record. For this reason,
// I record them now.
td.totalTasks += td.currentSample;
_totalTasks += td.totalTasks;
if(td.firstBegin < firstBegin){
firstBegin = td.firstBegin;
}
if(td.lastEnd > lastEnd){
lastEnd = td.lastEnd;
}
}
_executionTime = (lastEnd - firstBegin) / 1000000.0; // Must be in ms
_supportStop = true;
pthread_join(_supportTid, NULL);
Message msg;
msg.type = MESSAGE_TYPE_STOP;
msg.payload.summary.time = _executionTime;
msg.payload.summary.totalTasks = _totalTasks;
int r = _channelRef.send(&msg, sizeof(msg), 0);
assert (r == sizeof(msg));
// Wait for ack before leaving (otherwise if object is destroyed
// the monitor could never receive the stop).
r = _channelRef.recv(&msg, sizeof(msg), 0);
assert(r == sizeof(msg));
}
ulong Application::getExecutionTime(){
return _executionTime;
}
unsigned long long Application::getTotalTasks(){
return _totalTasks;
}
Monitor::Monitor(const std::string& channelName):
_channel(new nn::socket(AF_SP, NN_PAIR)), _channelRef(*_channel),
_executionTime(0), _totalTasks(0){
int linger = 5000;
_channel->setsockopt(NN_SOL_SOCKET, NN_LINGER, &linger, sizeof (linger));
_chid = _channelRef.bind(channelName.c_str());
assert(_chid >= 0);
}
Monitor::Monitor(nn::socket& socket, uint chid):
_channel(NULL), _channelRef(socket), _chid(chid), _executionTime(0), _totalTasks(0){
;
}
Monitor::~Monitor(){
if(_channel){
_channel->shutdown(_chid);
delete _channel;
}
}
pid_t Monitor::waitStart(){
Message m;
int r = _channelRef.recv(&m, sizeof(m), 0);
assert(r == sizeof(m));
assert(m.type == MESSAGE_TYPE_START);
return m.payload.pid;
}
bool Monitor::getSample(ApplicationSample& sample, bool fromAll){
Message m;
m.type = MESSAGE_TYPE_SAMPLE_REQ;
m.payload.fromAll = fromAll;
int r = _channelRef.send(&m, sizeof(m), 0);
assert(r == sizeof(m));
r = _channelRef.recv(&m, sizeof(m), 0);
assert(r == sizeof(m));
if(m.type == MESSAGE_TYPE_SAMPLE_RES){
sample = m.payload.sample;
return true;
}else if(m.type == MESSAGE_TYPE_STOP){
_executionTime = m.payload.summary.time;
_totalTasks = m.payload.summary.totalTasks;
// Send ack.
m.type = MESSAGE_TYPE_STOPACK;
r = _channelRef.send(&m, sizeof(m), 0);
assert(r == sizeof(m));
return false;
}else{
throw runtime_error("Unexpected message type.");
}
}
ulong Monitor::getExecutionTime(){
return _executionTime;
}
unsigned long long Monitor::getTotalTasks(){
return _totalTasks;
}
} // End namespace
<commit_msg>[FIX]<commit_after>/*
* This file is part of knarr
*
* (c) 2016- Daniele De Sensi (d.desensi.software@gmail.com)
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#include "external/cppnanomsg/nn.hpp"
#include "knarr.hpp"
#include <cmath>
#include <errno.h>
#include <limits>
#include <stdexcept>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
#undef DEBUG
#undef DEBUGB
#ifdef DEBUG_KNARR
#define DEBUG(x) do { std::cerr << "[Knarr] " << x << std::endl; } while (0)
#define DEBUGB(x) do {x;} while (0)
#else
#define DEBUG(x)
#define DEBUGB(x)
#endif
namespace knarr{
unsigned long long getCurrentTimeNs(){
#ifdef KNARR_NS_PER_TICK
return rdtsc() / KNARR_NS_PER_TICK;
#else
struct timespec tp;
int r = clock_gettime(CLOCK_MONOTONIC, &tp);
assert(!r);
return tp.tv_sec * 1.0e9 + tp.tv_nsec;
#endif
}
inline bool thisSampleNeeded(Application* application, size_t threadId, size_t updatedSamples, bool fromAll){
// If we need samples from all the threads
// or
// If this is the last thread and there are no
// samples stored, then we need this sample.
return (fromAll ||
application->_configuration.threadsNeeded == KNARR_THREADS_NEEDED_ALL ||
((threadId == application->_threadData.size() - 1) &&
!updatedSamples &&
application->_configuration.threadsNeeded == KNARR_THREADS_NEEDED_ONE));
}
inline bool keepWaitingSample(Application* application, size_t threadId, size_t updatedSamples, bool fromAll){
if(*application->_threadData[threadId].consolidate){
if(thisSampleNeeded(application, threadId, updatedSamples, fromAll) &&
!application->_supportStop){
return true;
}
// If we don't need to wait for thread sample,
// stop waiting.
if(application->_configuration.threadsNeeded == KNARR_THREADS_NEEDED_NONE ||
(application->_configuration.threadsNeeded == KNARR_THREADS_NEEDED_ONE && (threadId != application->_threadData.size() - 1)) ||
application->_supportStop){
return false;
}
return true;
}
return false;
}
void* applicationSupportThread(void* data){
Application* application = static_cast<Application*>(data);
while(!application->_supportStop){
Message recvdMsg;
int res = application->_channelRef.recv(&recvdMsg, sizeof(recvdMsg), 0);
bool fromAll = recvdMsg.payload.fromAll;
if(res == sizeof(recvdMsg)){
assert(recvdMsg.type == MESSAGE_TYPE_SAMPLE_REQ);
// Prepare response message.
Message msg;
msg.type = MESSAGE_TYPE_SAMPLE_RES;
msg.payload.sample = ApplicationSample(); // Set sample to all zeros
// Add the samples of all the threads.
size_t updatedSamples = 0, inconsistentSamples = 0;
size_t numThreads = application->_threadData.size();
std::vector<double> customVec[KNARR_MAX_CUSTOM_FIELDS];
for(size_t i = 0; i < numThreads; i++){
*application->_threadData[i].consolidate = true;
}
unsigned long long consolidationTimestamp = getCurrentTimeNs();
for(size_t i = 0; i < numThreads; i++){
// If needed, wait for thread to store a sample.
while(keepWaitingSample(application, i, updatedSamples, fromAll)){
// To wait, the idea is that after the consolidation request has been
// sent, samples should be stored at most after samplingLengthMs milliseconds.
// If that time is already elapsed, we just wait for one millisecond
// (to avoid too tight spin loop), otherwise, we wait for that time to elapse.
// (it is performed at most once independently from the number of needed samples)
unsigned long long timeFromConsolidation = (getCurrentTimeNs() - consolidationTimestamp) / 1000000.0;
if(timeFromConsolidation > application->_configuration.samplingLengthMs){
usleep(1000);
}else{
usleep((application->_configuration.samplingLengthMs - timeFromConsolidation)*1000);
}
}
ThreadData& toAdd = application->_threadData[i];
if(!*toAdd.consolidate){
ApplicationSample& sample = toAdd.consolidatedSample;
if(sample.latency == KNARR_VALUE_INCONSISTENT){
++inconsistentSamples;
}else{
sample.latency /= sample.numTasks;
msg.payload.sample.loadPercentage += sample.loadPercentage;
msg.payload.sample.latency += sample.latency;
}
msg.payload.sample.bandwidth += sample.bandwidth;
msg.payload.sample.numTasks += sample.numTasks;
++updatedSamples;
for(size_t j = 0; j < KNARR_MAX_CUSTOM_FIELDS; j++){
// TODO How to manage not-yet-stored custom values?
customVec[j].push_back(sample.customFields[j]);
}
}
}
// If at least one thread is progressing.
if(updatedSamples){
if(application->_configuration.adjustBandwidth &&
updatedSamples != numThreads){
// This can only happen if we didn't need to store
// data from all the threads
if(!application->_supportStop){
assert(application->_configuration.threadsNeeded != KNARR_THREADS_NEEDED_ALL);
}
msg.payload.sample.bandwidth += (msg.payload.sample.bandwidth / updatedSamples) * (numThreads - updatedSamples);
}
// If we collected only inconsistent samples, we mark latency and load as inconsistent.
if(inconsistentSamples == updatedSamples){
msg.payload.sample.loadPercentage = KNARR_VALUE_INCONSISTENT;
msg.payload.sample.latency = KNARR_VALUE_INCONSISTENT;
}else{
msg.payload.sample.loadPercentage /= updatedSamples;
msg.payload.sample.latency /= updatedSamples;
}
}else{
// This can only happens if the threadsNeeded is NONE
if(!application->_supportStop){
assert(application->_configuration.threadsNeeded == KNARR_THREADS_NEEDED_NONE);
}
msg.payload.sample.bandwidth = 0;
msg.payload.sample.latency = KNARR_VALUE_NOT_AVAILABLE;
msg.payload.sample.loadPercentage = 0;
msg.payload.sample.numTasks = 0;
}
// Aggregate custom values.
if(application->_aggregator){
for(size_t i = 0; i < KNARR_MAX_CUSTOM_FIELDS; i++){
msg.payload.sample.customFields[i] = application->_aggregator->aggregate(i, customVec[i]);
}
}
DEBUG(msg.payload.sample);
// Send message
if(!application->_supportStop){
application->_channelRef.send(&msg, sizeof(msg), 0);
}
}else if(res == -1){
throw std::runtime_error("Received less bytes than expected.");
}
}
return NULL;
}
Application::Application(const std::string& channelName, size_t numThreads,
Aggregator* aggregator):
_channel(new nn::socket(AF_SP, NN_PAIR)), _channelRef(*_channel),
_started(false), _aggregator(aggregator), _executionTime(0), _totalTasks(0){
_chid = _channelRef.connect(channelName.c_str());
assert(_chid >= 0);
pthread_mutex_init(&_mutex, NULL);
_supportStop = false;
_threadData.resize(numThreads);
// Pthread Create must be the last thing we do in constructor
pthread_create(&_supportTid, NULL, applicationSupportThread, (void*) this);
}
Application::Application(nn::socket& socket, uint chid, size_t numThreads,
Aggregator* aggregator):
_channel(NULL), _channelRef(socket), _chid(chid), _started(false),
_aggregator(aggregator), _executionTime(0), _totalTasks(0){
pthread_mutex_init(&_mutex, NULL);
_supportStop = false;
_threadData.resize(numThreads);
// Pthread Create must be the last thing we do in constructor
pthread_create(&_supportTid, NULL, applicationSupportThread, (void*) this);
}
Application::~Application(){
if(_channel){
_channel->shutdown(_chid);
delete _channel;
}
}
void Application::notifyStart(){
Message msg;
msg.type = MESSAGE_TYPE_START;
msg.payload.pid = getpid();
int r = _channelRef.send(&msg, sizeof(msg), 0);
assert(r == sizeof(msg));
}
ulong Application::updateSamplingLength(unsigned long long numTasks, unsigned long long sampleTime){
if(numTasks){
double latencyNs = sampleTime / numTasks;
double latencyMs = latencyNs / 1000000.0;
// If samplingLength == 1 we would have one begin()-end() pair every latencyMs milliseconds
if(latencyMs){
return std::ceil((double) _configuration.samplingLengthMs / latencyMs);
}else{
return KNARR_DEFAULT_SAMPLING_LENGTH;
}
}else{
throw std::runtime_error("updateSamplingLength called with no tasks stored.");
}
}
void Application::setConfiguration(const ApplicationConfiguration& configuration){
_configuration = configuration;
}
void Application::setConfigurationStreaming(){
ApplicationConfiguration configuration;
configuration.threadsNeeded = KNARR_THREADS_NEEDED_NONE;
configuration.adjustBandwidth = true;
_configuration = configuration;
}
void Application::setConfigurationBatch(ThreadsNeeded threadsNeeded){
ApplicationConfiguration configuration;
configuration.threadsNeeded = threadsNeeded;
configuration.adjustBandwidth = true;
_configuration = configuration;
}
void Application::storeCustomValue(size_t index, double value, uint threadId){
if(threadId > _threadData.size()){
throw new std::runtime_error("Wrong threadId specified (greater than number of threads).");
}
if(index < KNARR_MAX_CUSTOM_FIELDS){
ThreadData& tData = _threadData[threadId];
tData.sample.customFields[index] = value;
}else{
throw std::runtime_error("Custom value index out of bound. Please "
"increase KNARR_MAX_CUSTOM_FIELDS macro value.");
}
}
void Application::terminate(){
unsigned long long lastEnd = 0, firstBegin = std::numeric_limits<unsigned long long>::max();
for(ThreadData& td : _threadData){
// If I was doing sampling, I could have spurious
// tasks that I didn't record. For this reason,
// I record them now.
td.totalTasks += td.currentSample;
_totalTasks += td.totalTasks;
if(td.firstBegin < firstBegin){
firstBegin = td.firstBegin;
}
if(td.lastEnd > lastEnd){
lastEnd = td.lastEnd;
}
}
_executionTime = (lastEnd - firstBegin) / 1000000.0; // Must be in ms
_supportStop = true;
pthread_join(_supportTid, NULL);
Message msg;
msg.type = MESSAGE_TYPE_STOP;
msg.payload.summary.time = _executionTime;
msg.payload.summary.totalTasks = _totalTasks;
int r = _channelRef.send(&msg, sizeof(msg), 0);
assert (r == sizeof(msg));
// Wait for ack before leaving (otherwise if object is destroyed
// the monitor could never receive the stop).
r = _channelRef.recv(&msg, sizeof(msg), 0);
assert(r == sizeof(msg));
}
ulong Application::getExecutionTime(){
return _executionTime;
}
unsigned long long Application::getTotalTasks(){
return _totalTasks;
}
Monitor::Monitor(const std::string& channelName):
_channel(new nn::socket(AF_SP, NN_PAIR)), _channelRef(*_channel),
_executionTime(0), _totalTasks(0){
int linger = 5000;
_channel->setsockopt(NN_SOL_SOCKET, NN_LINGER, &linger, sizeof (linger));
_chid = _channelRef.bind(channelName.c_str());
assert(_chid >= 0);
}
Monitor::Monitor(nn::socket& socket, uint chid):
_channel(NULL), _channelRef(socket), _chid(chid), _executionTime(0), _totalTasks(0){
;
}
Monitor::~Monitor(){
if(_channel){
_channel->shutdown(_chid);
delete _channel;
}
}
pid_t Monitor::waitStart(){
Message m;
int r = _channelRef.recv(&m, sizeof(m), 0);
assert(r == sizeof(m));
assert(m.type == MESSAGE_TYPE_START);
return m.payload.pid;
}
bool Monitor::getSample(ApplicationSample& sample, bool fromAll){
Message m;
m.type = MESSAGE_TYPE_SAMPLE_REQ;
m.payload.fromAll = fromAll;
int r = _channelRef.send(&m, sizeof(m), 0);
assert(r == sizeof(m));
r = _channelRef.recv(&m, sizeof(m), 0);
assert(r == sizeof(m));
if(m.type == MESSAGE_TYPE_SAMPLE_RES){
sample = m.payload.sample;
return true;
}else if(m.type == MESSAGE_TYPE_STOP){
_executionTime = m.payload.summary.time;
_totalTasks = m.payload.summary.totalTasks;
// Send ack.
m.type = MESSAGE_TYPE_STOPACK;
r = _channelRef.send(&m, sizeof(m), 0);
assert(r == sizeof(m));
return false;
}else{
throw runtime_error("Unexpected message type.");
}
}
ulong Monitor::getExecutionTime(){
return _executionTime;
}
unsigned long long Monitor::getTotalTasks(){
return _totalTasks;
}
} // End namespace
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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.
*
************************************************************************/
#include "vbahelper/vbadocumentbase.hxx"
#include "vbahelper/helperdecl.hxx"
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
#include <com/sun/star/util/XModifiable.hpp>
#include <com/sun/star/util/XProtectable.hpp>
#include <com/sun/star/util/XCloseable.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/document/XEmbeddedScripts.hpp> //Michael E. Bohn
#include <com/sun/star/beans/XPropertySet.hpp>
#include <cppuhelper/exc_hlp.hxx>
#include <comphelper/unwrapargs.hxx>
#include <tools/urlobj.hxx>
#include <osl/file.hxx>
using namespace ::com::sun::star;
using namespace ::ooo::vba;
VbaDocumentBase::VbaDocumentBase( const uno::Reference< ov::XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext >& xContext) :VbaDocumentBase_BASE( xParent, xContext ), mxModel(NULL)
{
}
VbaDocumentBase::VbaDocumentBase( const uno::Reference< ov::XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext >& xContext, uno::Reference< frame::XModel > xModel ) : VbaDocumentBase_BASE( xParent, xContext ), mxModel( xModel )
{
}
VbaDocumentBase::VbaDocumentBase( uno::Sequence< uno::Any> const & args,
uno::Reference< uno::XComponentContext> const & xContext ) : VbaDocumentBase_BASE( getXSomethingFromArgs< XHelperInterface >( args, 0 ), xContext ), mxModel( getXSomethingFromArgs< frame::XModel >( args, 1 ) )
{
}
::rtl::OUString
VbaDocumentBase::getName() throw (uno::RuntimeException)
{
rtl::OUString sName = getModel()->getURL();
if ( sName.getLength() )
{
INetURLObject aURL( getModel()->getURL() );
::osl::File::getSystemPathFromFileURL( aURL.GetLastName(), sName );
}
else
{
const static rtl::OUString sTitle( RTL_CONSTASCII_USTRINGPARAM("Title" ) );
// process "UntitledX - $(PRODUCTNAME)"
uno::Reference< frame::XFrame > xFrame( getModel()->getCurrentController()->getFrame(), uno::UNO_QUERY_THROW );
uno::Reference< beans::XPropertySet > xProps( xFrame, uno::UNO_QUERY_THROW );
xProps->getPropertyValue(sTitle ) >>= sName;
sal_Int32 pos = 0;
sName = sName.getToken(0,'-',pos);
sName = sName.trim();
}
return sName;
}
::rtl::OUString
VbaDocumentBase::getPath() throw (uno::RuntimeException)
{
INetURLObject aURL( getModel()->getURL() );
rtl::OUString sURL( aURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) );
sURL = sURL.copy( 0, sURL.getLength() - aURL.GetLastName().getLength() - 1 );
rtl::OUString sPath;
::osl::File::getSystemPathFromFileURL( sURL, sPath );
return sPath;
}
::rtl::OUString
VbaDocumentBase::getFullName() throw (uno::RuntimeException)
{
rtl::OUString sPath;
::osl::File::getSystemPathFromFileURL( getModel()->getURL(), sPath );
return sPath;
}
void
VbaDocumentBase::Close( const uno::Any &rSaveArg, const uno::Any &rFileArg,
const uno::Any &rRouteArg ) throw (uno::RuntimeException)
{
sal_Bool bSaveChanges = sal_False;
rtl::OUString aFileName;
sal_Bool bRouteWorkbook = sal_True;
rSaveArg >>= bSaveChanges;
sal_Bool bFileName = ( rFileArg >>= aFileName );
rRouteArg >>= bRouteWorkbook;
uno::Reference< frame::XStorable > xStorable( getModel(), uno::UNO_QUERY_THROW );
uno::Reference< util::XModifiable > xModifiable( getModel(), uno::UNO_QUERY_THROW );
if( bSaveChanges )
{
if( xStorable->isReadonly() )
{
throw uno::RuntimeException(::rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM( "Unable to save to a read only file ") ),
uno::Reference< XInterface >() );
}
if( bFileName )
xStorable->storeAsURL( aFileName, uno::Sequence< beans::PropertyValue >(0) );
else
xStorable->store();
}
else
xModifiable->setModified( false );
uno::Reference< util::XCloseable > xCloseable( getModel(), uno::UNO_QUERY );
if( xCloseable.is() )
// use close(boolean DeliverOwnership)
// The boolean parameter DeliverOwnership tells objects vetoing the close process that they may
// assume ownership if they object the closure by throwing a CloseVetoException
// Here we give up ownership. To be on the safe side, catch possible veto exception anyway.
xCloseable->close(sal_True);
// If close is not supported by this model - try to dispose it.
// But if the model disagree with a reset request for the modify state
// we shouldn't do so. Otherwhise some strange things can happen.
else
{
uno::Reference< lang::XComponent > xDisposable ( getModel(), uno::UNO_QUERY );
if ( xDisposable.is() )
xDisposable->dispose();
}
}
void
VbaDocumentBase::Protect( const uno::Any &aPassword ) throw (uno::RuntimeException)
{
rtl::OUString rPassword;
uno::Reference< util::XProtectable > xProt( getModel(), uno::UNO_QUERY_THROW );
SC_VBA_FIXME(("Workbook::Protect stub"));
if( aPassword >>= rPassword )
xProt->protect( rPassword );
else
xProt->protect( rtl::OUString() );
}
void
VbaDocumentBase::Unprotect( const uno::Any &aPassword ) throw (uno::RuntimeException)
{
rtl::OUString rPassword;
uno::Reference< util::XProtectable > xProt( getModel(), uno::UNO_QUERY_THROW );
if( !xProt->isProtected() )
throw uno::RuntimeException(::rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM( "File is already unprotected" ) ),
uno::Reference< XInterface >() );
else
{
if( aPassword >>= rPassword )
xProt->unprotect( rPassword );
else
xProt->unprotect( rtl::OUString() );
}
}
void
VbaDocumentBase::setSaved( sal_Bool bSave ) throw (uno::RuntimeException)
{
uno::Reference< util::XModifiable > xModifiable( getModel(), uno::UNO_QUERY_THROW );
try
{
xModifiable->setModified( !bSave );
}
catch ( lang::DisposedException& )
{
// impossibility to set the modified state on disposed document should not trigger an error
}
catch ( beans::PropertyVetoException& )
{
uno::Any aCaught( ::cppu::getCaughtException() );
throw lang::WrappedTargetRuntimeException(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Can't change modified state of model!" ) ),
uno::Reference< uno::XInterface >(),
aCaught );
}
}
sal_Bool
VbaDocumentBase::getSaved() throw (uno::RuntimeException)
{
uno::Reference< util::XModifiable > xModifiable( getModel(), uno::UNO_QUERY_THROW );
return !xModifiable->isModified();
}
void
VbaDocumentBase::Save() throw (uno::RuntimeException)
{
rtl::OUString url = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(".uno:Save"));
uno::Reference< frame::XModel > xModel = getModel();
dispatchRequests(xModel,url);
}
void
VbaDocumentBase::Activate() throw (uno::RuntimeException)
{
uno::Reference< frame::XFrame > xFrame( getModel()->getCurrentController()->getFrame(), uno::UNO_QUERY_THROW );
xFrame->activate();
}
uno::Any SAL_CALL
VbaDocumentBase::getVBProject() throw (uno::RuntimeException)
{
try // return empty object on error
{
uno::Sequence< uno::Any > aArgs( 2 );
aArgs[ 0 ] <<= uno::Reference< XHelperInterface >( this );
aArgs[ 1 ] <<= getModel();
uno::Reference< lang::XMultiComponentFactory > xServiceManager( mxContext->getServiceManager(), uno::UNO_SET_THROW );
uno::Reference< uno::XInterface > xVBProjects = xServiceManager->createInstanceWithArgumentsAndContext(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ooo.vba.VBProject" ) ), aArgs, mxContext );
return uno::Any( xVBProjects );
}
catch( uno::Exception& )
{
}
return uno::Any();
}
rtl::OUString&
VbaDocumentBase::getServiceImplName()
{
static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM("VbaDocumentBase") );
return sImplName;
}
uno::Sequence< rtl::OUString >
VbaDocumentBase::getServiceNames()
{
static uno::Sequence< rtl::OUString > aServiceNames;
if ( aServiceNames.getLength() == 0 )
{
aServiceNames.realloc( 1 );
aServiceNames[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ooo.vba.VbaDocumentBase" ) );
}
return aServiceNames;
}
<commit_msg>mib19: #163217# let the document be correctly closed<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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.
*
************************************************************************/
#include "vbahelper/vbadocumentbase.hxx"
#include "vbahelper/helperdecl.hxx"
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
#include <com/sun/star/util/XModifiable.hpp>
#include <com/sun/star/util/XProtectable.hpp>
#include <com/sun/star/util/XCloseable.hpp>
#include <com/sun/star/util/XURLTransformer.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/document/XEmbeddedScripts.hpp> //Michael E. Bohn
#include <com/sun/star/beans/XPropertySet.hpp>
#include <cppuhelper/exc_hlp.hxx>
#include <comphelper/unwrapargs.hxx>
#include <tools/urlobj.hxx>
#include <osl/file.hxx>
using namespace ::com::sun::star;
using namespace ::ooo::vba;
VbaDocumentBase::VbaDocumentBase( const uno::Reference< ov::XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext >& xContext) :VbaDocumentBase_BASE( xParent, xContext ), mxModel(NULL)
{
}
VbaDocumentBase::VbaDocumentBase( const uno::Reference< ov::XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext >& xContext, uno::Reference< frame::XModel > xModel ) : VbaDocumentBase_BASE( xParent, xContext ), mxModel( xModel )
{
}
VbaDocumentBase::VbaDocumentBase( uno::Sequence< uno::Any> const & args,
uno::Reference< uno::XComponentContext> const & xContext ) : VbaDocumentBase_BASE( getXSomethingFromArgs< XHelperInterface >( args, 0 ), xContext ), mxModel( getXSomethingFromArgs< frame::XModel >( args, 1 ) )
{
}
::rtl::OUString
VbaDocumentBase::getName() throw (uno::RuntimeException)
{
rtl::OUString sName = getModel()->getURL();
if ( sName.getLength() )
{
INetURLObject aURL( getModel()->getURL() );
::osl::File::getSystemPathFromFileURL( aURL.GetLastName(), sName );
}
else
{
const static rtl::OUString sTitle( RTL_CONSTASCII_USTRINGPARAM("Title" ) );
// process "UntitledX - $(PRODUCTNAME)"
uno::Reference< frame::XFrame > xFrame( getModel()->getCurrentController()->getFrame(), uno::UNO_QUERY_THROW );
uno::Reference< beans::XPropertySet > xProps( xFrame, uno::UNO_QUERY_THROW );
xProps->getPropertyValue(sTitle ) >>= sName;
sal_Int32 pos = 0;
sName = sName.getToken(0,'-',pos);
sName = sName.trim();
}
return sName;
}
::rtl::OUString
VbaDocumentBase::getPath() throw (uno::RuntimeException)
{
INetURLObject aURL( getModel()->getURL() );
rtl::OUString sURL( aURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) );
sURL = sURL.copy( 0, sURL.getLength() - aURL.GetLastName().getLength() - 1 );
rtl::OUString sPath;
::osl::File::getSystemPathFromFileURL( sURL, sPath );
return sPath;
}
::rtl::OUString
VbaDocumentBase::getFullName() throw (uno::RuntimeException)
{
rtl::OUString sPath;
::osl::File::getSystemPathFromFileURL( getModel()->getURL(), sPath );
return sPath;
}
void
VbaDocumentBase::Close( const uno::Any &rSaveArg, const uno::Any &rFileArg,
const uno::Any &rRouteArg ) throw (uno::RuntimeException)
{
sal_Bool bSaveChanges = sal_False;
rtl::OUString aFileName;
sal_Bool bRouteWorkbook = sal_True;
rSaveArg >>= bSaveChanges;
sal_Bool bFileName = ( rFileArg >>= aFileName );
rRouteArg >>= bRouteWorkbook;
uno::Reference< frame::XStorable > xStorable( getModel(), uno::UNO_QUERY_THROW );
uno::Reference< util::XModifiable > xModifiable( getModel(), uno::UNO_QUERY_THROW );
if( bSaveChanges )
{
if( xStorable->isReadonly() )
{
throw uno::RuntimeException(::rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM( "Unable to save to a read only file ") ),
uno::Reference< XInterface >() );
}
if( bFileName )
xStorable->storeAsURL( aFileName, uno::Sequence< beans::PropertyValue >(0) );
else
xStorable->store();
}
else
xModifiable->setModified( false );
// first try to close the document using UI dispatch functionality
sal_Bool bUIClose = sal_False;
try
{
uno::Reference< frame::XController > xController( getModel()->getCurrentController(), uno::UNO_SET_THROW );
uno::Reference< frame::XDispatchProvider > xDispatchProvider( xController->getFrame(), uno::UNO_QUERY_THROW );
uno::Reference< lang::XMultiComponentFactory > xServiceManager( mxContext->getServiceManager(), uno::UNO_SET_THROW );
uno::Reference< util::XURLTransformer > xURLTransformer(
xServiceManager->createInstanceWithContext(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.URLTransformer" ) ),
mxContext ),
uno::UNO_QUERY_THROW );
util::URL aURL;
aURL.Complete = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:CloseDoc" ) );
xURLTransformer->parseStrict( aURL );
uno::Reference< css::frame::XDispatch > xDispatch(
xDispatchProvider->queryDispatch( aURL, ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "_self" ) ), 0 ),
uno::UNO_SET_THROW );
xDispatch->dispatch( aURL, uno::Sequence< beans::PropertyValue >() );
bUIClose = sal_True;
}
catch( uno::Exception& )
{
}
if ( !bUIClose )
{
// if it is not possible to use UI dispatch, try to close the model directly
uno::Reference< util::XCloseable > xCloseable( getModel(), uno::UNO_QUERY );
if( xCloseable.is() )
{
// use close(boolean DeliverOwnership)
// The boolean parameter DeliverOwnership tells objects vetoing the close process that they may
// assume ownership if they object the closure by throwing a CloseVetoException
// Here we give up ownership. To be on the safe side, catch possible veto exception anyway.
xCloseable->close(sal_True);
}
else
{
// If close is not supported by this model - try to dispose it.
// But if the model disagree with a reset request for the modify state
// we shouldn't do so. Otherwhise some strange things can happen.
uno::Reference< lang::XComponent > xDisposable ( getModel(), uno::UNO_QUERY );
if ( xDisposable.is() )
xDisposable->dispose();
}
}
}
void
VbaDocumentBase::Protect( const uno::Any &aPassword ) throw (uno::RuntimeException)
{
rtl::OUString rPassword;
uno::Reference< util::XProtectable > xProt( getModel(), uno::UNO_QUERY_THROW );
SC_VBA_FIXME(("Workbook::Protect stub"));
if( aPassword >>= rPassword )
xProt->protect( rPassword );
else
xProt->protect( rtl::OUString() );
}
void
VbaDocumentBase::Unprotect( const uno::Any &aPassword ) throw (uno::RuntimeException)
{
rtl::OUString rPassword;
uno::Reference< util::XProtectable > xProt( getModel(), uno::UNO_QUERY_THROW );
if( !xProt->isProtected() )
throw uno::RuntimeException(::rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM( "File is already unprotected" ) ),
uno::Reference< XInterface >() );
else
{
if( aPassword >>= rPassword )
xProt->unprotect( rPassword );
else
xProt->unprotect( rtl::OUString() );
}
}
void
VbaDocumentBase::setSaved( sal_Bool bSave ) throw (uno::RuntimeException)
{
uno::Reference< util::XModifiable > xModifiable( getModel(), uno::UNO_QUERY_THROW );
try
{
xModifiable->setModified( !bSave );
}
catch ( lang::DisposedException& )
{
// impossibility to set the modified state on disposed document should not trigger an error
}
catch ( beans::PropertyVetoException& )
{
uno::Any aCaught( ::cppu::getCaughtException() );
throw lang::WrappedTargetRuntimeException(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Can't change modified state of model!" ) ),
uno::Reference< uno::XInterface >(),
aCaught );
}
}
sal_Bool
VbaDocumentBase::getSaved() throw (uno::RuntimeException)
{
uno::Reference< util::XModifiable > xModifiable( getModel(), uno::UNO_QUERY_THROW );
return !xModifiable->isModified();
}
void
VbaDocumentBase::Save() throw (uno::RuntimeException)
{
rtl::OUString url = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(".uno:Save"));
uno::Reference< frame::XModel > xModel = getModel();
dispatchRequests(xModel,url);
}
void
VbaDocumentBase::Activate() throw (uno::RuntimeException)
{
uno::Reference< frame::XFrame > xFrame( getModel()->getCurrentController()->getFrame(), uno::UNO_QUERY_THROW );
xFrame->activate();
}
uno::Any SAL_CALL
VbaDocumentBase::getVBProject() throw (uno::RuntimeException)
{
try // return empty object on error
{
uno::Sequence< uno::Any > aArgs( 2 );
aArgs[ 0 ] <<= uno::Reference< XHelperInterface >( this );
aArgs[ 1 ] <<= getModel();
uno::Reference< lang::XMultiComponentFactory > xServiceManager( mxContext->getServiceManager(), uno::UNO_SET_THROW );
uno::Reference< uno::XInterface > xVBProjects = xServiceManager->createInstanceWithArgumentsAndContext(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ooo.vba.VBProject" ) ), aArgs, mxContext );
return uno::Any( xVBProjects );
}
catch( uno::Exception& )
{
}
return uno::Any();
}
rtl::OUString&
VbaDocumentBase::getServiceImplName()
{
static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM("VbaDocumentBase") );
return sImplName;
}
uno::Sequence< rtl::OUString >
VbaDocumentBase::getServiceNames()
{
static uno::Sequence< rtl::OUString > aServiceNames;
if ( aServiceNames.getLength() == 0 )
{
aServiceNames.realloc( 1 );
aServiceNames[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ooo.vba.VbaDocumentBase" ) );
}
return aServiceNames;
}
<|endoftext|>
|
<commit_before>// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// Copyright Paul A. Bristow 2013
// Copyright Christopher Kormanyos 2013.
// Copyright John Maddock 2013.
#ifdef _MSC_VER
# pragma warning (disable : 4512)
# pragma warning (disable : 4996)
#endif
#define BOOST_TEST_MAIN
#define BOOST_LIB_DIAGNOSTIC "on"// Show library file details.
//[expression_template_1
#include <limits>
#include <iostream>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/test/floating_point_comparison.hpp> // Extra test tool for FP comparison.
#include <boost/test/unit_test.hpp>
typedef boost::multiprecision::number<
boost::multiprecision::cpp_dec_float<50>,
boost::multiprecision::et_off> cpp_dec_float_50_noet;
typedef boost::multiprecision::number<
boost::multiprecision::cpp_dec_float<50>,
boost::multiprecision::et_on> cpp_dec_float_50_et;
namespace boost { namespace math { namespace fpc {
template <class A, boost::multiprecision::expression_template_option B>
struct tolerance_based< boost::multiprecision::number<
A,
B > > : boost::mpl::true_ {};
template <class tag, class Arg1, class Arg2, class Arg3, class Arg4>
struct tolerance_based<
boost::multiprecision::detail::expression<
tag, Arg1, Arg2, Arg3, Arg4> > : boost::mpl::true_ {};
} } }
/*`To define a 50 decimal digit type using `cpp_dec_float`,
you must pass two template parameters to `boost::multiprecision::number`.
It may be more legible to use a two-staged type definition such as this:
``
typedef boost::multiprecision::cpp_dec_float<50> mp_backend;
typedef boost::multiprecision::number<mp_backend, boost::multiprecision::et_off> cpp_dec_float_50_noet;
``
Here, we first define `mp_backend` as `cpp_dec_float` with 50 digits.
The second step passes this backend to `boost::multiprecision::number`
with `boost::multiprecision::et_off`, an enumerated type.
typedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<50>, boost::multiprecision::et_off>
cpp_dec_float_50_noet;
You can reduce typing with a `using` directive `using namespace boost::multiprecision;`
if desired, as shown below.
*/
using namespace boost::multiprecision;
/*`Now `cpp_dec_float_50_noet` or `cpp_dec_float_50_et`
can be used as a direct replacement for built-in types like `double` etc.
*/
BOOST_AUTO_TEST_CASE(cpp_float_test_check_close_noet)
{ // No expression templates/
typedef number<cpp_dec_float<50>, et_off> cpp_dec_float_50_noet;
std::cout.precision(std::numeric_limits<cpp_dec_float_50_noet>::digits10); // All significant digits.
std::cout << std::showpoint << std::endl; // Show trailing zeros.
cpp_dec_float_50_noet a ("1.0");
cpp_dec_float_50_noet b ("1.0");
b += std::numeric_limits<cpp_dec_float_50_noet>::epsilon(); // Increment least significant decimal digit.
cpp_dec_float_50_noet eps = std::numeric_limits<cpp_dec_float_50_noet>::epsilon();
std::cout <<"a = " << a << ",\nb = " << b << ",\neps = " << eps << std::endl;
BOOST_CHECK_CLOSE(a, b, eps * 100); // Expected to pass (because tolerance is as percent).
BOOST_CHECK_CLOSE_FRACTION(a, b, eps); // Expected to pass (because tolerance is as fraction).
#if !defined(BOOST_TEST_NO_VARIADIC)
namespace tt = boost::test_tools;
BOOST_TEST( a == b, tt::tolerance( tt::fpc::percent_tolerance( eps * 100 ) ) );
BOOST_TEST( a == b, tt::tolerance( eps ) );
#endif
//] [/expression_template_1]git
} // BOOST_AUTO_TEST_CASE(cpp_float_test_check_close)
BOOST_AUTO_TEST_CASE(cpp_float_test_check_close_et)
{ // Using expression templates.
typedef number<cpp_dec_float<50>, et_on> cpp_dec_float_50_et;
std::cout.precision(std::numeric_limits<cpp_dec_float_50_et>::digits10); // All significant digits.
std::cout << std::showpoint << std::endl; // Show trailing zeros.
cpp_dec_float_50_et a("1.0");
cpp_dec_float_50_et b("1.0");
b += std::numeric_limits<cpp_dec_float_50_et>::epsilon(); // Increment least significant decimal digit.
cpp_dec_float_50_et eps = std::numeric_limits<cpp_dec_float_50_et>::epsilon();
std::cout << "a = " << a << ",\nb = " << b << ",\neps = " << eps << std::endl;
BOOST_CHECK_CLOSE(a, b, eps * 100); // Expected to pass (because tolerance is as percent).
BOOST_CHECK_CLOSE_FRACTION(a, b, eps); // Expected to pass (because tolerance is as fraction).
#if !defined(BOOST_TEST_NO_VARIADIC)
namespace tt = boost::test_tools;
BOOST_TEST( a == b, tt::tolerance( tt::fpc::percent_tolerance<cpp_dec_float_50_et>( eps * 100 ) ) );
BOOST_TEST( a == b, tt::tolerance( eps ) );
#endif
/*`Using `cpp_dec_float_50` with the default expression template use switched on,
the compiler error message for `BOOST_CHECK_CLOSE_FRACTION(a, b, eps); would be:
*/
// failure floating_point_comparison.hpp(59): error C2440: 'static_cast' :
// cannot convert from 'int' to 'boost::multiprecision::detail::expression<tag,Arg1,Arg2,Arg3,Arg4>'
//] [/expression_template_1]
} // BOOST_AUTO_TEST_CASE(cpp_float_test_check_close)
/*
Output:
Description: Autorun "J:\Cpp\big_number\Debug\test_cpp_float_close_fraction.exe"
Running 1 test case...
a = 1.0000000000000000000000000000000000000000000000000,
b = 1.0000000000000000000000000000000000000000000000001,
eps = 1.0000000000000000000000000000000000000000000000000e-49
*** No errors detected
*/
<commit_msg>Now testing the multiprecision library with the automatic support for approximate types<commit_after>// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// Copyright Paul A. Bristow 2013
// Copyright Christopher Kormanyos 2013.
// Copyright John Maddock 2013.
#ifdef _MSC_VER
# pragma warning (disable : 4512)
# pragma warning (disable : 4996)
#endif
#define BOOST_TEST_MAIN
#define BOOST_LIB_DIAGNOSTIC "on"// Show library file details.
//[expression_template_1
#include <limits>
#include <iostream>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/test/floating_point_comparison.hpp> // Extra test tool for FP comparison.
#include <boost/test/unit_test.hpp>
typedef boost::multiprecision::number<
boost::multiprecision::cpp_dec_float<50>,
boost::multiprecision::et_off> cpp_dec_float_50_noet;
typedef boost::multiprecision::number<
boost::multiprecision::cpp_dec_float<50>,
boost::multiprecision::et_on> cpp_dec_float_50_et;
#if 0
namespace boost { namespace math { namespace fpc {
template <class A, boost::multiprecision::expression_template_option B>
struct tolerance_based< boost::multiprecision::number<
A,
B > > : boost::mpl::true_ {};
template <class tag, class Arg1, class Arg2, class Arg3, class Arg4>
struct tolerance_based<
boost::multiprecision::detail::expression<
tag, Arg1, Arg2, Arg3, Arg4> > : boost::mpl::true_ {};
} } }
#endif
/*`To define a 50 decimal digit type using `cpp_dec_float`,
you must pass two template parameters to `boost::multiprecision::number`.
It may be more legible to use a two-staged type definition such as this:
``
typedef boost::multiprecision::cpp_dec_float<50> mp_backend;
typedef boost::multiprecision::number<mp_backend, boost::multiprecision::et_off> cpp_dec_float_50_noet;
``
Here, we first define `mp_backend` as `cpp_dec_float` with 50 digits.
The second step passes this backend to `boost::multiprecision::number`
with `boost::multiprecision::et_off`, an enumerated type.
typedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<50>, boost::multiprecision::et_off>
cpp_dec_float_50_noet;
You can reduce typing with a `using` directive `using namespace boost::multiprecision;`
if desired, as shown below.
*/
using namespace boost::multiprecision;
/*`Now `cpp_dec_float_50_noet` or `cpp_dec_float_50_et`
can be used as a direct replacement for built-in types like `double` etc.
*/
BOOST_AUTO_TEST_CASE(cpp_float_test_check_close_noet)
{ // No expression templates/
typedef number<cpp_dec_float<50>, et_off> cpp_dec_float_50_noet;
std::cout.precision(std::numeric_limits<cpp_dec_float_50_noet>::digits10); // All significant digits.
std::cout << std::showpoint << std::endl; // Show trailing zeros.
cpp_dec_float_50_noet a ("1.0");
cpp_dec_float_50_noet b ("1.0");
b += std::numeric_limits<cpp_dec_float_50_noet>::epsilon(); // Increment least significant decimal digit.
cpp_dec_float_50_noet eps = std::numeric_limits<cpp_dec_float_50_noet>::epsilon();
std::cout <<"a = " << a << ",\nb = " << b << ",\neps = " << eps << std::endl;
BOOST_CHECK_CLOSE(a, b, eps * 100); // Expected to pass (because tolerance is as percent).
BOOST_CHECK_CLOSE_FRACTION(a, b, eps); // Expected to pass (because tolerance is as fraction).
#if !defined(BOOST_TEST_NO_VARIADIC)
namespace tt = boost::test_tools;
BOOST_TEST( a == b, tt::tolerance( tt::fpc::percent_tolerance( eps * 100 ) ) );
BOOST_TEST( a == b, tt::tolerance( eps ) );
#endif
//] [/expression_template_1]git
} // BOOST_AUTO_TEST_CASE(cpp_float_test_check_close)
BOOST_AUTO_TEST_CASE(cpp_float_test_check_close_et)
{ // Using expression templates.
typedef number<cpp_dec_float<50>, et_on> cpp_dec_float_50_et;
std::cout.precision(std::numeric_limits<cpp_dec_float_50_et>::digits10); // All significant digits.
std::cout << std::showpoint << std::endl; // Show trailing zeros.
cpp_dec_float_50_et a("1.0");
cpp_dec_float_50_et b("1.0");
b += std::numeric_limits<cpp_dec_float_50_et>::epsilon(); // Increment least significant decimal digit.
cpp_dec_float_50_et eps = std::numeric_limits<cpp_dec_float_50_et>::epsilon();
std::cout << "a = " << a << ",\nb = " << b << ",\neps = " << eps << std::endl;
BOOST_CHECK_CLOSE(a, b, eps * 100); // Expected to pass (because tolerance is as percent).
BOOST_CHECK_CLOSE_FRACTION(a, b, eps); // Expected to pass (because tolerance is as fraction).
#if !defined(BOOST_TEST_NO_VARIADIC)
namespace tt = boost::test_tools;
BOOST_TEST( a == b, tt::tolerance( tt::fpc::percent_tolerance<cpp_dec_float_50_et>( eps * 100 ) ) );
BOOST_TEST( a == b, tt::tolerance( eps ) );
#endif
/*`Using `cpp_dec_float_50` with the default expression template use switched on,
the compiler error message for `BOOST_CHECK_CLOSE_FRACTION(a, b, eps); would be:
*/
// failure floating_point_comparison.hpp(59): error C2440: 'static_cast' :
// cannot convert from 'int' to 'boost::multiprecision::detail::expression<tag,Arg1,Arg2,Arg3,Arg4>'
//] [/expression_template_1]
} // BOOST_AUTO_TEST_CASE(cpp_float_test_check_close)
/*
Output:
Description: Autorun "J:\Cpp\big_number\Debug\test_cpp_float_close_fraction.exe"
Running 1 test case...
a = 1.0000000000000000000000000000000000000000000000000,
b = 1.0000000000000000000000000000000000000000000000001,
eps = 1.0000000000000000000000000000000000000000000000000e-49
*** No errors detected
*/
<|endoftext|>
|
<commit_before>#pragma once
#include <cstddef>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include <tudocomp/io/MMapHandle.hpp>
#include <tudocomp/io/InputSource.hpp>
#include <tudocomp/io/InputRestrictions.hpp>
#include <tudocomp/io/IOUtil.hpp>
#include <tudocomp/io/EscapeMap.hpp>
namespace tdc {namespace io {
class RestrictedBuffer {
public:
static const size_t npos = -1;
private:
MMap m_map;
View m_restricted_data;
io::InputRestrictions m_restrictions;
InputSource m_source;
// mmap needs to be page aligned, so for file mappings
// we need to store a offset
//
// Effectivley this means that for a given mmap in instance in this class,
// instead of
// |-----------input--------------|
// [ [from_______to] ]
// it stores
// |-----------input--------------|
// [ [offset|from_______to] ]
size_t m_mmap_page_offset = 0;
template<typename I, typename J>
inline void escape_with_iters(I read_begin, I read_end, J write_end, bool do_copy = false) {
if (!m_restrictions.has_no_escape_restrictions()) {
FastEscapeMap fast_escape_map;
uint8_t escape_byte;
{
EscapeMap em(m_restrictions);
fast_escape_map = FastEscapeMap(em);
escape_byte = fast_escape_map.escape_byte();
}
while(read_begin != read_end) {
--read_end;
--write_end;
uint8_t current_byte = *read_end;
*write_end = fast_escape_map.lookup_byte(current_byte);
if (fast_escape_map.lookup_flag_bool(current_byte)) {
--write_end;
*write_end = escape_byte;
}
}
} else if (do_copy) {
while(read_begin != read_end) {
--read_end;
--write_end;
*write_end = *read_end;
}
}
}
// NB: The len argument would be redundant, but exists because
// the istream iterator does not allow efficient slicing of the input file
// TODO: Define custom sliceable ifstream iterator
// TODO: ^ Needed in Input as well
template<typename T>
inline size_t extra_size_needed_due_restrictions(T begin, T end, size_t len) {
size_t extra = 0;
if (!m_restrictions.has_no_escape_restrictions()) {
size_t i = 0;
FastEscapeMap fast_escape_map{EscapeMap(m_restrictions)};
while((begin != end) && (i < len)) {
uint8_t current_byte = *begin;
extra += fast_escape_map.lookup_flag(current_byte);
++begin;
++i;
}
DCHECK_EQ(i, len);
}
if (m_restrictions.null_terminate()) {
extra++;
}
return extra;
}
inline void init(size_t m_from, size_t m_to) {
if (m_source.is_view()) {
View s;
if (m_to == npos) {
s = m_source.view().slice(m_from);
} else {
s = m_source.view().slice(m_from, m_to);
}
size_t extra_size = extra_size_needed_due_restrictions(
s.cbegin(), s.cend(), s.size());
if (extra_size != 0) {
size_t size = s.size() + extra_size;
m_map = MMap(size);
{
GenericView<uint8_t> target = m_map.view();
size_t noff = m_restrictions.null_terminate()? 1 : 0;
escape_with_iters(s.cbegin(), s.cend(), target.end() - noff, true);
// For null termination, a trailing byte is implicit 0
}
m_restricted_data = m_map.view();
} else {
m_restricted_data = s;
}
} else if (m_source.is_file()) {
// iterate file to check for escapeable bytes and also null
size_t unrestricted_size;
if (m_to == npos) {
unrestricted_size = read_file_size(m_source.file()) - m_from;
} else {
unrestricted_size = m_to - m_from;
}
auto path = m_source.file();
auto c_path = path.c_str();
size_t extra_size = 0;
{
auto ifs = create_tdc_ifstream(c_path, m_from);
std::istream_iterator<char> begin (ifs);
std::istream_iterator<char> end;
extra_size = extra_size_needed_due_restrictions(
begin, end, unrestricted_size);
}
size_t aligned_offset = MMap::next_valid_offset(m_from);
m_mmap_page_offset = m_from - aligned_offset;
DCHECK_EQ(aligned_offset + m_mmap_page_offset, m_from);
size_t map_size = unrestricted_size + extra_size + m_mmap_page_offset;
if (m_restrictions.has_no_restrictions()) {
m_map = MMap(path, MMap::Mode::Read, map_size, aligned_offset);
const auto& m = m_map;
m_restricted_data = m.view().slice(m_mmap_page_offset);
} else {
m_map = MMap(path, MMap::Mode::ReadWrite, map_size, aligned_offset);
size_t noff = m_restrictions.null_terminate()? 1 : 0;
uint8_t* begin_file_data = m_map.view().begin() + m_mmap_page_offset;
uint8_t* end_file_data = begin_file_data + unrestricted_size;
uint8_t* end_data = end_file_data + extra_size - noff;
escape_with_iters(begin_file_data, end_file_data, end_data);
if (m_restrictions.null_terminate()) {
// ensure the last valid byte is actually 0 if using null termination
*end_data = 0;
}
m_restricted_data = m_map.view().slice(m_mmap_page_offset);
}
} else if (m_source.is_stream()) {
DCHECK_EQ(m_from, 0);
DCHECK_EQ(m_to, npos);
// Start with a typical page size to not realloc as often
// for small inputs
size_t capacity = pagesize();
size_t size = 0;
size_t extra_size = 0;
FastEscapeMap fast_escape_map;
if (!m_restrictions.has_no_escape_restrictions()) {
fast_escape_map = FastEscapeMap {
EscapeMap(m_restrictions)
};
}
size_t noff = m_restrictions.null_terminate()? 1 : 0;
extra_size += noff;
// Initial allocation
m_map = MMap(capacity);
// Fill and grow
{
std::istream& is = *(m_source.stream());
bool done = false;
while(!done) {
// fill until capacity
uint8_t* ptr = m_map.view().begin() + size;
while(size < capacity) {
char c;
if(!is.get(c)) {
done = true;
break;
} else {
*ptr = uint8_t(c);
++ptr;
++size;
extra_size += fast_escape_map.lookup_flag(uint8_t(c));
}
}
if (done) break;
// realloc to greater size;
capacity *= 2;
m_map.remap(capacity);
}
// Throw away overallocation
std::cout << "Size, extra size: " << size << ", " << extra_size << "\n";
// For null termination,
// a trailing unwritten byte is automatically 0
m_map.remap(size + extra_size);
m_restricted_data = m_map.view();
}
// Escape
{
uint8_t* begin_stream_data = m_map.view().begin();
uint8_t* end_stream_data = begin_stream_data + size;
uint8_t* end_data = end_stream_data + extra_size - noff;
escape_with_iters(begin_stream_data, end_stream_data, end_data);
}
} else {
DCHECK(false) << "This should not happen";
}
}
// Change the restrictions on a stream restricted buffer
inline static RestrictedBuffer unrestrict(RestrictedBuffer&& other) {
DCHECK(other.source().is_stream());
if (other.restrictions().has_no_restrictions()) {
return std::move(other);
}
DCHECK(other.restrictions().has_restrictions());
DCHECK(other.m_mmap_page_offset == 0);
auto x = std::move(other);
auto r = x.m_restrictions;
std::cout << "Old restrictions: " << r << "\n";
auto start = x.m_map.view().begin();
auto end = x.m_map.view().end();
FastUnescapeMap fast_unescape_map { EscapeMap(r) };
auto read_p = start;
auto write_p = start;
size_t noff = x.m_restrictions.null_terminate()? 1 : 0;
auto data_end = end - noff;
while (read_p != data_end) {
if (*read_p == fast_unescape_map.escape_byte()) {
++read_p;
*write_p = fast_unescape_map.lookup_byte(*read_p);
} else {
*write_p = *read_p;
}
++read_p;
++write_p;
}
auto old_size = x.m_map.view().size();
auto reduced_size = (read_p - write_p) + noff;
x.m_map.remap(old_size - reduced_size);
x.m_restrictions = InputRestrictions();
x.m_restricted_data = x.m_map.view();
return x;
}
// Change the restrictions on a stream restricted buffer
inline static RestrictedBuffer restrict(RestrictedBuffer&& other,
const io::InputRestrictions& restrictions) {
DCHECK(other.source().is_stream());
if (other.restrictions() == restrictions) {
return std::move(other);
}
DCHECK(other.restrictions().has_no_restrictions());
DCHECK(other.m_mmap_page_offset == 0);
size_t old_size;
size_t extra_size;
// Calculate needed extra size:
{
View s = other.view();
other.m_restrictions = restrictions;
extra_size = other.extra_size_needed_due_restrictions(
s.cbegin(), s.cend(), s.size()
);
old_size = s.size();
}
// If nothing about the actual data changed
// return it as is
if (extra_size == 0) {
return std::move(other);
}
// Else remap and expand the data by escaping:
other.m_map.remap(old_size + extra_size);
other.m_restricted_data = other.m_map.view();
{
size_t noff = other.m_restrictions.null_terminate()? 1 : 0;
uint8_t* start = other.m_map.view().begin();
uint8_t* old_end = start + old_size;
uint8_t* new_end = old_end + extra_size - noff;
other.escape_with_iters(start, old_end, new_end);
if (other.m_restrictions.null_terminate()) {
*new_end = 0;
}
DCHECK_EQ(new_end + noff, other.m_map.view().end());
}
return std::move(other);
}
public:
inline RestrictedBuffer change_restrictions(
const io::InputRestrictions& restrictions) &&
{
std::cout << "changing restrictions:\n";
std::cout << " old size:" << view().size() << "\n";
auto& other = *this;
auto buf = unrestrict(std::move(other));
auto r = restrict(std::move(buf), restrictions);
std::cout << " new size:" << r.view().size() << "\n";
return r;
}
inline RestrictedBuffer(const InputSource& src,
size_t from,
size_t to,
io::InputRestrictions restrictions):
m_restrictions(restrictions),
m_source(src)
{
init(from, to);
}
inline const InputRestrictions& restrictions() const { return m_restrictions; }
inline const InputSource& source() const { return m_source; }
inline View view() const { return m_restricted_data; }
inline RestrictedBuffer() = delete;
};
}}
<commit_msg>Make make check work<commit_after>#pragma once
#include <cstddef>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include <tudocomp/io/MMapHandle.hpp>
#include <tudocomp/io/InputSource.hpp>
#include <tudocomp/io/InputRestrictions.hpp>
#include <tudocomp/io/IOUtil.hpp>
#include <tudocomp/io/EscapeMap.hpp>
namespace tdc {namespace io {
class RestrictedBuffer {
public:
static const size_t npos = -1;
private:
MMap m_map;
View m_restricted_data;
io::InputRestrictions m_restrictions;
InputSource m_source;
// mmap needs to be page aligned, so for file mappings
// we need to store a offset
//
// Effectivley this means that for a given mmap in instance in this class,
// instead of
// |-----------input--------------|
// [ [from_______to] ]
// it stores
// |-----------input--------------|
// [ [offset|from_______to] ]
size_t m_mmap_page_offset = 0;
template<typename I, typename J>
inline void escape_with_iters(I read_begin, I read_end, J write_end, bool do_copy = false) {
if (!m_restrictions.has_no_escape_restrictions()) {
FastEscapeMap fast_escape_map;
uint8_t escape_byte;
{
EscapeMap em(m_restrictions);
fast_escape_map = FastEscapeMap(em);
escape_byte = fast_escape_map.escape_byte();
}
while(read_begin != read_end) {
--read_end;
--write_end;
uint8_t current_byte = *read_end;
*write_end = fast_escape_map.lookup_byte(current_byte);
if (fast_escape_map.lookup_flag_bool(current_byte)) {
--write_end;
*write_end = escape_byte;
}
}
} else if (do_copy) {
while(read_begin != read_end) {
--read_end;
--write_end;
*write_end = *read_end;
}
}
}
// NB: The len argument would be redundant, but exists because
// the istream iterator does not allow efficient slicing of the input file
// TODO: Define custom sliceable ifstream iterator
// TODO: ^ Needed in Input as well
template<typename T>
inline size_t extra_size_needed_due_restrictions(T begin, T end, size_t len) {
size_t extra = 0;
if (!m_restrictions.has_no_escape_restrictions()) {
size_t i = 0;
FastEscapeMap fast_escape_map{EscapeMap(m_restrictions)};
while((begin != end) && (i < len)) {
uint8_t current_byte = *begin;
extra += fast_escape_map.lookup_flag(current_byte);
++begin;
++i;
}
DCHECK_EQ(i, len);
}
if (m_restrictions.null_terminate()) {
extra++;
}
return extra;
}
inline void init(size_t m_from, size_t m_to) {
if (m_source.is_view()) {
View s;
if (m_to == npos) {
s = m_source.view().slice(m_from);
} else {
s = m_source.view().slice(m_from, m_to);
}
size_t extra_size = extra_size_needed_due_restrictions(
s.cbegin(), s.cend(), s.size());
if (extra_size != 0) {
size_t size = s.size() + extra_size;
m_map = MMap(size);
{
GenericView<uint8_t> target = m_map.view();
size_t noff = m_restrictions.null_terminate()? 1 : 0;
escape_with_iters(s.cbegin(), s.cend(), target.end() - noff, true);
// For null termination, a trailing byte is implicit 0
}
m_restricted_data = m_map.view();
} else {
m_restricted_data = s;
}
} else if (m_source.is_file()) {
// iterate file to check for escapeable bytes and also null
size_t unrestricted_size;
if (m_to == npos) {
unrestricted_size = read_file_size(m_source.file()) - m_from;
} else {
unrestricted_size = m_to - m_from;
}
auto path = m_source.file();
auto c_path = path.c_str();
size_t extra_size = 0;
{
auto ifs = create_tdc_ifstream(c_path, m_from);
std::istreambuf_iterator<char> begin (ifs);
std::istreambuf_iterator<char> end;
std::cout << "unrestricted size: " << unrestricted_size << "\n";
std::cout << "m_from: " << m_from << "\n";
std::cout << "m_to: " << m_to << "\n";
extra_size = extra_size_needed_due_restrictions(
begin, end, unrestricted_size);
}
size_t aligned_offset = MMap::next_valid_offset(m_from);
m_mmap_page_offset = m_from - aligned_offset;
DCHECK_EQ(aligned_offset + m_mmap_page_offset, m_from);
size_t map_size = unrestricted_size + extra_size + m_mmap_page_offset;
if (m_restrictions.has_no_restrictions()) {
m_map = MMap(path, MMap::Mode::Read, map_size, aligned_offset);
const auto& m = m_map;
m_restricted_data = m.view().slice(m_mmap_page_offset);
} else {
m_map = MMap(path, MMap::Mode::ReadWrite, map_size, aligned_offset);
size_t noff = m_restrictions.null_terminate()? 1 : 0;
uint8_t* begin_file_data = m_map.view().begin() + m_mmap_page_offset;
uint8_t* end_file_data = begin_file_data + unrestricted_size;
uint8_t* end_data = end_file_data + extra_size - noff;
escape_with_iters(begin_file_data, end_file_data, end_data);
if (m_restrictions.null_terminate()) {
// ensure the last valid byte is actually 0 if using null termination
*end_data = 0;
}
m_restricted_data = m_map.view().slice(m_mmap_page_offset);
}
} else if (m_source.is_stream()) {
DCHECK_EQ(m_from, 0);
DCHECK_EQ(m_to, npos);
// Start with a typical page size to not realloc as often
// for small inputs
size_t capacity = pagesize();
size_t size = 0;
size_t extra_size = 0;
FastEscapeMap fast_escape_map;
if (!m_restrictions.has_no_escape_restrictions()) {
fast_escape_map = FastEscapeMap {
EscapeMap(m_restrictions)
};
}
size_t noff = m_restrictions.null_terminate()? 1 : 0;
extra_size += noff;
// Initial allocation
m_map = MMap(capacity);
// Fill and grow
{
std::istream& is = *(m_source.stream());
bool done = false;
while(!done) {
// fill until capacity
uint8_t* ptr = m_map.view().begin() + size;
while(size < capacity) {
char c;
if(!is.get(c)) {
done = true;
break;
} else {
*ptr = uint8_t(c);
++ptr;
++size;
extra_size += fast_escape_map.lookup_flag(uint8_t(c));
}
}
if (done) break;
// realloc to greater size;
capacity *= 2;
m_map.remap(capacity);
}
// Throw away overallocation
std::cout << "Size, extra size: " << size << ", " << extra_size << "\n";
// For null termination,
// a trailing unwritten byte is automatically 0
m_map.remap(size + extra_size);
m_restricted_data = m_map.view();
}
// Escape
{
uint8_t* begin_stream_data = m_map.view().begin();
uint8_t* end_stream_data = begin_stream_data + size;
uint8_t* end_data = end_stream_data + extra_size - noff;
escape_with_iters(begin_stream_data, end_stream_data, end_data);
}
} else {
DCHECK(false) << "This should not happen";
}
}
// Change the restrictions on a stream restricted buffer
inline static RestrictedBuffer unrestrict(RestrictedBuffer&& other) {
DCHECK(other.source().is_stream());
if (other.restrictions().has_no_restrictions()) {
return std::move(other);
}
DCHECK(other.restrictions().has_restrictions());
DCHECK(other.m_mmap_page_offset == 0);
auto x = std::move(other);
auto r = x.m_restrictions;
std::cout << "Old restrictions: " << r << "\n";
auto start = x.m_map.view().begin();
auto end = x.m_map.view().end();
FastUnescapeMap fast_unescape_map { EscapeMap(r) };
auto read_p = start;
auto write_p = start;
size_t noff = x.m_restrictions.null_terminate()? 1 : 0;
auto data_end = end - noff;
while (read_p != data_end) {
if (*read_p == fast_unescape_map.escape_byte()) {
++read_p;
*write_p = fast_unescape_map.lookup_byte(*read_p);
} else {
*write_p = *read_p;
}
++read_p;
++write_p;
}
auto old_size = x.m_map.view().size();
auto reduced_size = (read_p - write_p) + noff;
x.m_map.remap(old_size - reduced_size);
x.m_restrictions = InputRestrictions();
x.m_restricted_data = x.m_map.view();
return x;
}
// Change the restrictions on a stream restricted buffer
inline static RestrictedBuffer restrict(RestrictedBuffer&& other,
const io::InputRestrictions& restrictions) {
DCHECK(other.source().is_stream());
if (other.restrictions() == restrictions) {
return std::move(other);
}
DCHECK(other.restrictions().has_no_restrictions());
DCHECK(other.m_mmap_page_offset == 0);
size_t old_size;
size_t extra_size;
// Calculate needed extra size:
{
View s = other.view();
other.m_restrictions = restrictions;
extra_size = other.extra_size_needed_due_restrictions(
s.cbegin(), s.cend(), s.size()
);
old_size = s.size();
}
// If nothing about the actual data changed
// return it as is
if (extra_size == 0) {
return std::move(other);
}
// Else remap and expand the data by escaping:
other.m_map.remap(old_size + extra_size);
other.m_restricted_data = other.m_map.view();
{
size_t noff = other.m_restrictions.null_terminate()? 1 : 0;
uint8_t* start = other.m_map.view().begin();
uint8_t* old_end = start + old_size;
uint8_t* new_end = old_end + extra_size - noff;
other.escape_with_iters(start, old_end, new_end);
if (other.m_restrictions.null_terminate()) {
*new_end = 0;
}
DCHECK_EQ(new_end + noff, other.m_map.view().end());
}
return std::move(other);
}
public:
inline RestrictedBuffer change_restrictions(
const io::InputRestrictions& restrictions) &&
{
std::cout << "changing restrictions:\n";
std::cout << " old size:" << view().size() << "\n";
auto& other = *this;
auto buf = unrestrict(std::move(other));
auto r = restrict(std::move(buf), restrictions);
std::cout << " new size:" << r.view().size() << "\n";
return r;
}
inline RestrictedBuffer(const InputSource& src,
size_t from,
size_t to,
io::InputRestrictions restrictions):
m_restrictions(restrictions),
m_source(src)
{
init(from, to);
}
inline const InputRestrictions& restrictions() const { return m_restrictions; }
inline const InputSource& source() const { return m_source; }
inline View view() const { return m_restricted_data; }
inline RestrictedBuffer() = delete;
};
}}
<|endoftext|>
|
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <stdlib.h>
#include <string.h>
#include <osg/ApplicationUsage>
#include <osg/Math>
#include <osg/ref_ptr>
using namespace osg;
ApplicationUsage::ApplicationUsage(const std::string& commandLineUsage):
_commandLineUsage(commandLineUsage)
{
}
ApplicationUsage* ApplicationUsage::instance()
{
static osg::ref_ptr<ApplicationUsage> s_applicationUsage = new ApplicationUsage;
return s_applicationUsage.get();
}
void ApplicationUsage::addUsageExplanation(Type type,const std::string& option,const std::string& explanation)
{
switch(type)
{
case(COMMAND_LINE_OPTION):
addCommandLineOption(option,explanation);
break;
case(ENVIRONMENTAL_VARIABLE):
addEnvironmentalVariable(option,explanation);
break;
case(KEYBOARD_MOUSE_BINDING):
addKeyboardMouseBinding(option,explanation);
break;
default:
break;
}
}
void ApplicationUsage::addCommandLineOption(const std::string& option,const std::string& explanation,const std::string& defaultValue)
{
_commandLineOptions[option]=explanation;
_commandLineOptionsDefaults[option]=defaultValue;
}
void ApplicationUsage::addEnvironmentalVariable(const std::string& option,const std::string& explanation, const std::string& defaultValue)
{
_environmentalVariables[option]=explanation;
_environmentalVariablesDefaults[option]=defaultValue;
}
void ApplicationUsage::addKeyboardMouseBinding(const std::string& option,const std::string& explanation)
{
_keyboardMouse[option]=explanation;
}
void ApplicationUsage::getFormattedString(std::string& str, const UsageMap& um,unsigned int widthOfOutput,bool showDefaults,const UsageMap& ud)
{
unsigned int maxNumCharsInOptions = 0;
ApplicationUsage::UsageMap::const_iterator citr;
for(citr=um.begin();
citr!=um.end();
++citr)
{
maxNumCharsInOptions = maximum(maxNumCharsInOptions,(unsigned int)citr->first.length());
}
unsigned int fullWidth = widthOfOutput;
unsigned int optionPos = 2;
unsigned int explanationPos = optionPos+maxNumCharsInOptions+2;
unsigned int defaultPos = 0;
if (showDefaults)
{
defaultPos = explanationPos;
explanationPos = optionPos+8;
}
unsigned int explanationWidth = fullWidth-explanationPos;
std::string line;
for(citr=um.begin();
citr!=um.end();
++citr)
{
line.assign(fullWidth,' ');
line.replace(optionPos,citr->first.length(),citr->first);
if (showDefaults)
{
UsageMap::const_iterator ditr = ud.find(citr->first);
if (ditr != ud.end())
{
line.replace(defaultPos, std::string::npos, "");
if (ditr->second != "")
{
line += "[";
line += ditr->second;
line += "]";
}
str += line;
str += "\n";
line.assign(fullWidth,' ');
}
}
const std::string& explanation = citr->second;
std::string::size_type pos = 0;
std::string::size_type offset = 0;
bool firstInLine = true;
if (!explanation.empty())
{
while (pos<explanation.length())
{
if (firstInLine) offset = 0;
// skip any leading white space.
while (pos<explanation.length() && explanation[pos]==' ')
{
if (firstInLine) ++offset;
++pos;
}
firstInLine = false;
std::string::size_type width = minimum((std::string::size_type)(explanation.length()-pos),(std::string::size_type)(explanationWidth-offset));
std::string::size_type slashn_pos = explanation.find('\n',pos);
unsigned int extraSkip = 0;
bool concatinated = false;
if (slashn_pos!=std::string::npos)
{
if (slashn_pos<pos+width)
{
width = slashn_pos-pos;
++extraSkip;
firstInLine = true;
}
else if (slashn_pos==pos+width)
{
++extraSkip;
firstInLine = true;
}
}
if (pos+width<explanation.length())
{
// now reduce width until we get a space or a return
// so that we ensure that whole words are printed.
while (width>0 &&
explanation[pos+width]!=' ' &&
explanation[pos+width]!='\n') --width;
if (width==0)
{
// word must be longer than a whole line so will need
// to concatenate it.
width = explanationWidth-1;
concatinated = true;
}
}
line.replace(explanationPos+offset,explanationWidth, explanation, pos, width);
if (concatinated) { str += line; str += "-\n"; }
else { str += line; str += "\n"; }
// move to the next line of output.
line.assign(fullWidth,' ');
pos += width+extraSkip;
}
}
else
{
str += line; str += "\n";
}
}
}
void ApplicationUsage::write(std::ostream& output, const ApplicationUsage::UsageMap& um,unsigned int widthOfOutput,bool showDefaults,const ApplicationUsage::UsageMap& ud)
{
std::string str;
getFormattedString(str, um, widthOfOutput, showDefaults, ud);
output << str << std::endl;
}
void ApplicationUsage::write(std::ostream& output, unsigned int type, unsigned int widthOfOutput, bool showDefaults)
{
output << "Usage: "<<getCommandLineUsage()<<std::endl;
bool needspace = false;
if ((type&COMMAND_LINE_OPTION) && !getCommandLineOptions().empty())
{
if (needspace) output << std::endl;
output << "Options";
if (showDefaults) output << " [and default value]";
output << ":"<<std::endl;
write(output,getCommandLineOptions(),widthOfOutput,showDefaults,getCommandLineOptionsDefaults());
needspace = true;
}
if ((type&ENVIRONMENTAL_VARIABLE) && !getEnvironmentalVariables().empty())
{
if (needspace) output << std::endl;
output << "Environmental Variables";
if (showDefaults) output << " [and default value]";
output << ":"<<std::endl;
write(output,getEnvironmentalVariables(),widthOfOutput,showDefaults,getEnvironmentalVariablesDefaults());
needspace = true;
}
if ((type&KEYBOARD_MOUSE_BINDING) && !getKeyboardMouseBindings().empty())
{
if (needspace) output << std::endl;
output << "Keyboard and Mouse Bindings:"<<std::endl;
write(output,getKeyboardMouseBindings(),widthOfOutput);
needspace = true;
}
}
void ApplicationUsage::writeEnvironmentSettings(std::ostream& output)
{
output << "Current Environment Settings:"<<std::endl;
unsigned int maxNumCharsInOptions = 0;
ApplicationUsage::UsageMap::const_iterator citr;
for(citr=getEnvironmentalVariables().begin();
citr!=getEnvironmentalVariables().end();
++citr)
{
std::string::size_type len = citr->first.find_first_of("\n\r\t ");
if (len == std::string::npos) len = citr->first.size();
maxNumCharsInOptions = maximum( maxNumCharsInOptions,static_cast<unsigned int>(len));
}
unsigned int optionPos = 2;
std::string line;
for(citr=getEnvironmentalVariables().begin();
citr!=getEnvironmentalVariables().end();
++citr)
{
line.assign(optionPos+maxNumCharsInOptions+2,' ');
std::string::size_type len = citr->first.find_first_of("\n\r\t ");
if (len == std::string::npos) len = citr->first.size();
line.replace(optionPos,len,citr->first.substr(0,len));
const char *cp = getenv(citr->first.substr(0, len).c_str());
if (!cp) cp = "[not set]";
else if (!*cp) cp = "[set]";
line += std::string(cp) + "\n";
output << line;
}
output << std::endl;
}
<commit_msg>Improved the handling of application argument output when the options are very long.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <stdlib.h>
#include <string.h>
#include <osg/ApplicationUsage>
#include <osg/Math>
#include <osg/ref_ptr>
using namespace osg;
ApplicationUsage::ApplicationUsage(const std::string& commandLineUsage):
_commandLineUsage(commandLineUsage)
{
}
ApplicationUsage* ApplicationUsage::instance()
{
static osg::ref_ptr<ApplicationUsage> s_applicationUsage = new ApplicationUsage;
return s_applicationUsage.get();
}
void ApplicationUsage::addUsageExplanation(Type type,const std::string& option,const std::string& explanation)
{
switch(type)
{
case(COMMAND_LINE_OPTION):
addCommandLineOption(option,explanation);
break;
case(ENVIRONMENTAL_VARIABLE):
addEnvironmentalVariable(option,explanation);
break;
case(KEYBOARD_MOUSE_BINDING):
addKeyboardMouseBinding(option,explanation);
break;
default:
break;
}
}
void ApplicationUsage::addCommandLineOption(const std::string& option,const std::string& explanation,const std::string& defaultValue)
{
_commandLineOptions[option]=explanation;
_commandLineOptionsDefaults[option]=defaultValue;
}
void ApplicationUsage::addEnvironmentalVariable(const std::string& option,const std::string& explanation, const std::string& defaultValue)
{
_environmentalVariables[option]=explanation;
_environmentalVariablesDefaults[option]=defaultValue;
}
void ApplicationUsage::addKeyboardMouseBinding(const std::string& option,const std::string& explanation)
{
_keyboardMouse[option]=explanation;
}
void ApplicationUsage::getFormattedString(std::string& str, const UsageMap& um,unsigned int widthOfOutput,bool showDefaults,const UsageMap& ud)
{
unsigned int maxNumCharsInOptions = 0;
ApplicationUsage::UsageMap::const_iterator citr;
for(citr=um.begin();
citr!=um.end();
++citr)
{
maxNumCharsInOptions = maximum(maxNumCharsInOptions,(unsigned int)citr->first.length());
}
unsigned int fullWidth = widthOfOutput;
unsigned int optionPos = 2;
unsigned int explanationPos = optionPos+maxNumCharsInOptions+2;
double ratioOfExplanationToOutputWidth = float(explanationPos)/float(widthOfOutput);
double maxRatioOfExplanationToOutputWidth = 0.25f;
if (ratioOfExplanationToOutputWidth > maxRatioOfExplanationToOutputWidth)
{
explanationPos = static_cast<unsigned int>(maxRatioOfExplanationToOutputWidth*float(widthOfOutput));
}
unsigned int defaultPos = 0;
if (showDefaults)
{
defaultPos = explanationPos;
explanationPos = optionPos+8;
}
unsigned int explanationWidth = fullWidth-explanationPos;
std::string line;
for(citr=um.begin();
citr!=um.end();
++citr)
{
line.assign(fullWidth,' ');
line.replace(optionPos,citr->first.length(),citr->first);
unsigned int currentEndPos = optionPos + citr->first.length();
if (showDefaults)
{
UsageMap::const_iterator ditr = ud.find(citr->first);
if (ditr != ud.end())
{
if (currentEndPos+1>=defaultPos)
{
str += line; str += "\n";
line.assign(fullWidth,' ');
}
line.replace(defaultPos, std::string::npos, "");
if (ditr->second != "")
{
line += "[";
line += ditr->second;
line += "]";
}
str += line;
str += "\n";
line.assign(fullWidth,' ');
currentEndPos = 0;
}
}
const std::string& explanation = citr->second;
std::string::size_type pos = 0;
std::string::size_type offset = 0;
bool firstInLine = true;
if (!explanation.empty())
{
if (currentEndPos+1>explanationPos)
{
str += line; str += "\n";
line.assign(fullWidth,' ');
}
while (pos<explanation.length())
{
if (firstInLine) offset = 0;
// skip any leading white space.
while (pos<explanation.length() && explanation[pos]==' ')
{
if (firstInLine) ++offset;
++pos;
}
firstInLine = false;
std::string::size_type width = minimum((std::string::size_type)(explanation.length()-pos),(std::string::size_type)(explanationWidth-offset));
std::string::size_type slashn_pos = explanation.find('\n',pos);
unsigned int extraSkip = 0;
bool concatinated = false;
if (slashn_pos!=std::string::npos)
{
if (slashn_pos<pos+width)
{
width = slashn_pos-pos;
++extraSkip;
firstInLine = true;
}
else if (slashn_pos==pos+width)
{
++extraSkip;
firstInLine = true;
}
}
if (pos+width<explanation.length())
{
// now reduce width until we get a space or a return
// so that we ensure that whole words are printed.
while (width>0 &&
explanation[pos+width]!=' ' &&
explanation[pos+width]!='\n') --width;
if (width==0)
{
// word must be longer than a whole line so will need
// to concatenate it.
width = explanationWidth-1;
concatinated = true;
}
}
line.replace(explanationPos+offset,explanationWidth, explanation, pos, width);
if (concatinated) { str += line; str += "-\n"; }
else { str += line; str += "\n"; }
// move to the next line of output.
line.assign(fullWidth,' ');
pos += width+extraSkip;
}
}
else
{
str += line; str += "\n";
}
}
}
void ApplicationUsage::write(std::ostream& output, const ApplicationUsage::UsageMap& um,unsigned int widthOfOutput,bool showDefaults,const ApplicationUsage::UsageMap& ud)
{
std::string str;
getFormattedString(str, um, widthOfOutput, showDefaults, ud);
output << str << std::endl;
}
void ApplicationUsage::write(std::ostream& output, unsigned int type, unsigned int widthOfOutput, bool showDefaults)
{
output << "Usage: "<<getCommandLineUsage()<<std::endl;
bool needspace = false;
if ((type&COMMAND_LINE_OPTION) && !getCommandLineOptions().empty())
{
if (needspace) output << std::endl;
output << "Options";
if (showDefaults) output << " [and default value]";
output << ":"<<std::endl;
write(output,getCommandLineOptions(),widthOfOutput,showDefaults,getCommandLineOptionsDefaults());
needspace = true;
}
if ((type&ENVIRONMENTAL_VARIABLE) && !getEnvironmentalVariables().empty())
{
if (needspace) output << std::endl;
output << "Environmental Variables";
if (showDefaults) output << " [and default value]";
output << ":"<<std::endl;
write(output,getEnvironmentalVariables(),widthOfOutput,showDefaults,getEnvironmentalVariablesDefaults());
needspace = true;
}
if ((type&KEYBOARD_MOUSE_BINDING) && !getKeyboardMouseBindings().empty())
{
if (needspace) output << std::endl;
output << "Keyboard and Mouse Bindings:"<<std::endl;
write(output,getKeyboardMouseBindings(),widthOfOutput);
needspace = true;
}
}
void ApplicationUsage::writeEnvironmentSettings(std::ostream& output)
{
output << "Current Environment Settings:"<<std::endl;
unsigned int maxNumCharsInOptions = 0;
ApplicationUsage::UsageMap::const_iterator citr;
for(citr=getEnvironmentalVariables().begin();
citr!=getEnvironmentalVariables().end();
++citr)
{
std::string::size_type len = citr->first.find_first_of("\n\r\t ");
if (len == std::string::npos) len = citr->first.size();
maxNumCharsInOptions = maximum( maxNumCharsInOptions,static_cast<unsigned int>(len));
}
unsigned int optionPos = 2;
std::string line;
for(citr=getEnvironmentalVariables().begin();
citr!=getEnvironmentalVariables().end();
++citr)
{
line.assign(optionPos+maxNumCharsInOptions+2,' ');
std::string::size_type len = citr->first.find_first_of("\n\r\t ");
if (len == std::string::npos) len = citr->first.size();
line.replace(optionPos,len,citr->first.substr(0,len));
const char *cp = getenv(citr->first.substr(0, len).c_str());
if (!cp) cp = "[not set]";
else if (!*cp) cp = "[set]";
line += std::string(cp) + "\n";
output << line;
}
output << std::endl;
}
<|endoftext|>
|
<commit_before>#include <map>
#include <memory>
#include <fstream>
#include <iostream>
#include "appsum.h"
#include "cmdline.h"
#include "vcfio.h"
#include "plinkio.h"
#include "hapmapio.h"
#include "rtmio.h"
namespace {
std::map<allele_t,int> count_allele(const vector<allele_t> &v)
{
std::map<allele_t,int> ac;
for (auto e : v) {
if (ac.find(e) == ac.end())
ac[e] = 0;
++ac[e];
}
return ac;
}
} // namespace
int AppSum::run(int argc, char *argv[])
{
auto cmd = std::make_shared<CmdLine>("sum [options]");
cmd->add("--vcf", "VCF file", "");
cmd->add("--ped", "PLINK PED/MAP file prefix", "");
cmd->add("--hmp", "HapMap file", "");
cmd->add("--geno", "genotype file", "");
cmd->add("--out", "output file", "appsum.out");
cmd->add("--allele", "output allele statistics");
cmd->add("--indiv", "output individual statistics");
if (argc < 2) {
cmd->help();
return 1;
}
cmd->parse(argc, argv);
m_par.vcf = cmd->get("--vcf");
m_par.ped = cmd->get("--ped");
m_par.hmp = cmd->get("--hmp");
m_par.geno = cmd->get("--geno");
m_par.out = cmd->get("--out");
m_par.allele = cmd->has("--allele");
m_par.indiv = cmd->has("--indiv");
int info = perform();
return info;
}
int AppSum::perform()
{
load_genotype();
if (m_par.allele)
calc_save_stats_allele();
else if (m_par.indiv)
calc_save_stats_indiv();
else
calc_save_stats_locus();
return 0;
}
void AppSum::load_genotype()
{
if ( m_par.vcf.empty() && m_par.ped.empty() && m_par.hmp.empty() && m_par.geno.empty() )
return;
std::cerr << "INFO: reading genotype file...\n";
int info = 0;
if ( ! m_par.vcf.empty() )
info = read_vcf(m_par.vcf, m_gt);
else if ( ! m_par.ped.empty() )
info = read_plink(m_par.ped, m_gt);
else if ( ! m_par.hmp.empty() )
info = read_hapmap(m_par.hmp, m_gt);
else if ( ! m_par.geno.empty() )
info = read_genotype(m_par.geno, m_gt);
if (info != 0) {
m_gt.loc.clear();
m_gt.ind.clear();
m_gt.dat.clear();
}
std::cerr << "INFO: " << m_gt.ind.size() << " individuals and " << m_gt.loc.size() << " loci were observed\n";
}
void AppSum::calc_save_stats_locus() const
{
std::ofstream ofs(m_par.out + ".locus.txt");
ofs << "Locus\tAlleleNumber\tMinAlleleCount\tMinAlleleFreq\tMaxAlleleCount\tMaxAlleleFreq\t"""
"TotalAlleleCount\tTotalAlleleFreq\n";
auto m = m_gt.loc.size();
for (size_t j = 0; j < m; ++j) {
auto n = m_gt.dat[j].size();
auto ac = count_allele(m_gt.dat[j]);
int ac_min = n, ac_max = 0, ac_tot = 0;
for (auto e : ac) {
if ( ! e.first )
continue;
if (e.second < ac_min)
ac_min = e.second;
if (e.second > ac_max)
ac_max = e.second;
ac_tot += e.second;
}
ofs << m_gt.loc[j] << "\t" << m_gt.allele[j].size() << "\t"
<< ac_min << "\t" << (double) ac_min / ac_tot << "\t"
<< ac_max << "\t" << (double) ac_max / ac_tot << "\t"
<< ac_tot << "\t" << (double) ac_tot / n << "\n";
}
}
void AppSum::calc_save_stats_indiv() const
{
std::ofstream ofs(m_par.out + ".indiv.txt");
ofs << "Indiv\tTotalAlleleCount\tTotalAlleleFreq\n";
auto m = m_gt.loc.size(), n = m_gt.ind.size();
bool haploid = m_gt.ploidy == 1;
auto mt = haploid ? m : m*2;
for (size_t i = 0; i < n; ++i) {
size_t mv = 0;
if ( haploid ) {
for (size_t j = 0; j < m; ++j) {
if ( m_gt.dat[j][i] )
++mv;
}
}
else {
for (size_t j = 0; j < m; ++j) {
if ( m_gt.dat[j][i*2] )
++mv;
if ( m_gt.dat[j][i*2+1] )
++mv;
}
}
ofs << m_gt.ind[i] << "\t" << mv << "\t" << (double) mv / mt << "\n";
}
}
void AppSum::calc_save_stats_allele() const
{
std::ofstream ofs(m_par.out + ".allele.txt");
ofs << "Locus\tAllelel\tCount\tFreq\n";
auto m = m_gt.loc.size();
for (size_t j = 0; j < m; ++j) {
auto ac = count_allele(m_gt.dat[j]);
size_t tc = 0;
for (auto e : ac) {
if ( e.first )
tc += e.second;
}
for (auto e : ac) {
if ( ! e.first )
continue;
ofs << m_gt.loc[j] << "\t" << m_gt.allele[j][e.first-1] << "\t"
<< e.second << "\t" << (double) e.second / tc << "\n";
}
}
}
<commit_msg>Fixed allele count<commit_after>#include <map>
#include <memory>
#include <fstream>
#include <iostream>
#include "appsum.h"
#include "cmdline.h"
#include "vcfio.h"
#include "plinkio.h"
#include "hapmapio.h"
#include "rtmio.h"
namespace {
std::map<allele_t,int> count_allele(const vector<allele_t> &v)
{
std::map<allele_t,int> ac;
for (auto e : v) {
if (ac.find(e) == ac.end())
ac[e] = 0;
++ac[e];
}
return ac;
}
} // namespace
int AppSum::run(int argc, char *argv[])
{
auto cmd = std::make_shared<CmdLine>("sum [options]");
cmd->add("--vcf", "VCF file", "");
cmd->add("--ped", "PLINK PED/MAP file prefix", "");
cmd->add("--hmp", "HapMap file", "");
cmd->add("--geno", "genotype file", "");
cmd->add("--out", "output file", "appsum.out");
cmd->add("--allele", "output allele statistics");
cmd->add("--indiv", "output individual statistics");
if (argc < 2) {
cmd->help();
return 1;
}
cmd->parse(argc, argv);
m_par.vcf = cmd->get("--vcf");
m_par.ped = cmd->get("--ped");
m_par.hmp = cmd->get("--hmp");
m_par.geno = cmd->get("--geno");
m_par.out = cmd->get("--out");
m_par.allele = cmd->has("--allele");
m_par.indiv = cmd->has("--indiv");
int info = perform();
return info;
}
int AppSum::perform()
{
load_genotype();
if (m_par.allele)
calc_save_stats_allele();
else if (m_par.indiv)
calc_save_stats_indiv();
else
calc_save_stats_locus();
return 0;
}
void AppSum::load_genotype()
{
if ( m_par.vcf.empty() && m_par.ped.empty() && m_par.hmp.empty() && m_par.geno.empty() )
return;
std::cerr << "INFO: reading genotype file...\n";
int info = 0;
if ( ! m_par.vcf.empty() )
info = read_vcf(m_par.vcf, m_gt);
else if ( ! m_par.ped.empty() )
info = read_plink(m_par.ped, m_gt);
else if ( ! m_par.hmp.empty() )
info = read_hapmap(m_par.hmp, m_gt);
else if ( ! m_par.geno.empty() )
info = read_genotype(m_par.geno, m_gt);
if (info != 0) {
m_gt.loc.clear();
m_gt.ind.clear();
m_gt.dat.clear();
}
std::cerr << "INFO: " << m_gt.ind.size() << " individuals and " << m_gt.loc.size() << " loci were observed\n";
}
void AppSum::calc_save_stats_locus() const
{
std::ofstream ofs(m_par.out + ".locus.txt");
ofs << "Locus\tAlleleNumber\tMinAlleleCount\tMinAlleleFreq\tMaxAlleleCount\tMaxAlleleFreq\t"""
"TotalAlleleCount\tTotalAlleleFreq\n";
auto m = m_gt.loc.size();
for (size_t j = 0; j < m; ++j) {
auto n = m_gt.dat[j].size();
auto ac = count_allele(m_gt.dat[j]);
int ac_min = n, ac_max = 0, ac_tot = 0;
for (auto e : ac) {
if ( ! e.first )
continue;
if (e.second < ac_min)
ac_min = e.second;
if (e.second > ac_max)
ac_max = e.second;
ac_tot += e.second;
}
if (ac.size() < 2)
ac_min = 0;
ofs << m_gt.loc[j] << "\t" << ac.size() << "\t"
<< ac_min << "\t" << (double) ac_min / ac_tot << "\t"
<< ac_max << "\t" << (double) ac_max / ac_tot << "\t"
<< ac_tot << "\t" << (double) ac_tot / n << "\n";
}
}
void AppSum::calc_save_stats_indiv() const
{
std::ofstream ofs(m_par.out + ".indiv.txt");
ofs << "Indiv\tTotalAlleleCount\tTotalAlleleFreq\n";
auto m = m_gt.loc.size(), n = m_gt.ind.size();
bool haploid = m_gt.ploidy == 1;
auto mt = haploid ? m : m*2;
for (size_t i = 0; i < n; ++i) {
size_t mv = 0;
if ( haploid ) {
for (size_t j = 0; j < m; ++j) {
if ( m_gt.dat[j][i] )
++mv;
}
}
else {
for (size_t j = 0; j < m; ++j) {
if ( m_gt.dat[j][i*2] )
++mv;
if ( m_gt.dat[j][i*2+1] )
++mv;
}
}
ofs << m_gt.ind[i] << "\t" << mv << "\t" << (double) mv / mt << "\n";
}
}
void AppSum::calc_save_stats_allele() const
{
std::ofstream ofs(m_par.out + ".allele.txt");
ofs << "Locus\tAllelel\tCount\tFreq\n";
auto m = m_gt.loc.size();
for (size_t j = 0; j < m; ++j) {
auto ac = count_allele(m_gt.dat[j]);
size_t tc = 0;
for (auto e : ac) {
if ( e.first )
tc += e.second;
}
for (auto e : ac) {
if ( ! e.first )
continue;
ofs << m_gt.loc[j] << "\t" << m_gt.allele[j][e.first-1] << "\t"
<< e.second << "\t" << (double) e.second / tc << "\n";
}
}
}
<|endoftext|>
|
<commit_before>// -------------------------------------------------------------------------
// CV Drone (= OpenCV + AR.Drone)
// Copyright(C) 2013 puku0x
// https://github.com/puku0x/cvdrone
//
// This source file is part of CV Drone library.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of EITHER:
// (1) The GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The text of the GNU Lesser
// General Public License is included with this library in the
// file cvdrone-license-LGPL.txt.
// (2) The BSD-style license that is included with this library in
// the file cvdrone-license-BSD.txt.
//
// 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 files
// cvdrone-license-LGPL.txt and cvdrone-license-BSD.txt for more details.
// -------------------------------------------------------------------------
#include "ardrone.h"
#include "uvlc.h"
// The codes of decoding H.264 video is based on following sites.
// - An ffmpeg and SDL Tutorial - Tutorial 01: Making Screencaps -
// http://dranger.com/ffmpeg/tutorial01.html
// - AR.Drone Development - 2.1.2 AR.Drone 2.0 Video Decording: FFMPEG + SDL2.0 -
// http://ardrone-ailab-u-tokyo.blogspot.jp/2012/07/212-ardrone-20-video-decording-ffmpeg.html
// --------------------------------------------------------------------------
// ARDrone::initVideo()
// Description : Initialize video.
// Return value : SUCCESS: 1 FAILURE: 0
// --------------------------------------------------------------------------
int ARDrone::initVideo(void)
{
// AR.Drone 2.0
if (version.major == ARDRONE_VERSION_2) {
// Open the IP address and port
char filename[256];
sprintf(filename, "tcp://%s:%d", ip, ARDRONE_VIDEO_PORT);
if (avformat_open_input(&pFormatCtx, filename, NULL, NULL) < 0) {
CVDRONE_ERROR("avformat_open_input() was failed. (%s, %d)\n", __FILE__, __LINE__);
return 0;
}
// Retrive and dump stream information
avformat_find_stream_info(pFormatCtx, NULL);
av_dump_format(pFormatCtx, 0, filename, 0);
// Find the decoder for the video stream
pCodecCtx = pFormatCtx->streams[0]->codec;
AVCodec *pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
if (pCodec == NULL) {
CVDRONE_ERROR("avcodec_find_decoder() was failed. (%s, %d)\n", __FILE__, __LINE__);
return 0;
}
// Open codec
if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
CVDRONE_ERROR("avcodec_open2() was failed. (%s, %d)\n", __FILE__, __LINE__);
return 0;
}
// Allocate video frames and a buffer
pFrame = avcodec_alloc_frame();
pFrameBGR = avcodec_alloc_frame();
bufferBGR = (uint8_t*)av_mallocz(avpicture_get_size(PIX_FMT_BGR24, pCodecCtx->width, pCodecCtx->height) * sizeof(uint8_t));
// Assign appropriate parts of buffer to image planes in pFrameBGR
avpicture_fill((AVPicture*)pFrameBGR, bufferBGR, PIX_FMT_BGR24, pCodecCtx->width, pCodecCtx->height);
// Convert it to BGR
pConvertCtx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, PIX_FMT_BGR24, SWS_SPLINE, NULL, NULL, NULL);
}
// AR.Drone 1.0
else {
// Open the IP address and port
if (!sockVideo.open(ip, ARDRONE_VIDEO_PORT)) {
CVDRONE_ERROR("UDPSocket::open(port=%d) was failed. (%s, %d)\n", ARDRONE_VIDEO_PORT, __FILE__, __LINE__);
return 0;
}
// Set codec
pCodecCtx = avcodec_alloc_context();
pCodecCtx->width = 320;
pCodecCtx->height = 240;
// Allocate a buffer
bufferBGR = (uint8_t*)av_mallocz(avpicture_get_size(PIX_FMT_BGR24, pCodecCtx->width, pCodecCtx->height));
}
// Allocate an IplImage
img = cvCreateImage(cvSize(pCodecCtx->width, (pCodecCtx->height == 368) ? 360 : pCodecCtx->height), IPL_DEPTH_8U, 3);
if (!img) {
CVDRONE_ERROR("cvCreateImage() was failed. (%s, %d)\n", __FILE__, __LINE__);
return 0;
}
// Clear the image
cvZero(img);
// Create a mutex
mutexVideo = new pthread_mutex_t;
pthread_mutex_init(mutexVideo, NULL);
// Create a thread
threadVideo = new pthread_t;
if (pthread_create(threadVideo, NULL, runVideo, this) != 0) {
CVDRONE_ERROR("pthread_create() was failed. (%s, %d)\n", __FILE__, __LINE__);
return 0;
}
return 1;
}
// --------------------------------------------------------------------------
// ARDrone::loopVideo()
// Description : Thread function.
// Return value : SUCCESS:0
// --------------------------------------------------------------------------
void ARDrone::loopVideo(void)
{
while (1) {
// Get video stream
if (!getVideo()) break;
pthread_testcancel();
msleep(1);
}
}
// --------------------------------------------------------------------------
// ARDrone::getVideo()
// Description : Get AR.Drone's video stream.
// Return value : SUCCESS: 1 FAILURE: 0
// --------------------------------------------------------------------------
int ARDrone::getVideo(void)
{
// AR.Drone 2.0
if (version.major == ARDRONE_VERSION_2) {
AVPacket packet;
int frameFinished = 0;
// Read all frames
while (av_read_frame(pFormatCtx, &packet) >= 0) {
// Decode the frame
avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);
// Decoded all frames
if (frameFinished) {
// Convert to BGR
if (mutexVideo) pthread_mutex_lock(mutexVideo);
sws_scale(pConvertCtx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameBGR->data, pFrameBGR->linesize);
if (mutexVideo) pthread_mutex_unlock(mutexVideo);
// Free the packet and break immidiately
av_free_packet(&packet);
break;
}
// Free the packet
av_free_packet(&packet);
}
}
// AR.Drone 1.0
else {
// Send request
sockVideo.sendf("\x01\x00\x00\x00");
// Receive data
uint8_t buf[122880];
int size = sockVideo.receive((void*)&buf, sizeof(buf));
// Received something
if (size > 0) {
// Decode UVLC video
if (mutexVideo) pthread_mutex_lock(mutexVideo);
UVLC::DecodeVideo(buf, size, bufferBGR, &pCodecCtx->width, &pCodecCtx->height);
if (mutexVideo) pthread_mutex_unlock(mutexVideo);
}
}
return 1;
}
// --------------------------------------------------------------------------
// ARDrone::getImage()
// Description : Get an image from the AR.Drone's camera.
// Return value : Pointer to an IplImage (OpenCV image)
// --------------------------------------------------------------------------
IplImage* ARDrone::getImage(void)
{
// There is no image
if (!img) return NULL;
// Enable mutex lock
if (mutexVideo) pthread_mutex_lock(mutexVideo);
// AR.Drone 2.0
if (version.major == ARDRONE_VERSION_2) {
// Copy the frame to the IplImage
memcpy(img->imageData, pFrameBGR->data[0], pCodecCtx->width * ((pCodecCtx->height == 368) ? 360 : pCodecCtx->height) * sizeof(uint8_t) * 3);
}
// AR.Drone 1.0
else {
// If the sizes of buffer and IplImage are differnt
if (pCodecCtx->width != img->width || pCodecCtx->height != img->height) {
// Resize the image to 320x240
IplImage *small_img = cvCreateImageHeader(cvSize(pCodecCtx->width, pCodecCtx->height), IPL_DEPTH_8U, 3);
small_img->imageData = (char*)bufferBGR;
cvResize(small_img, img, CV_INTER_CUBIC);
cvReleaseImageHeader(&small_img);
}
// For 320x240 image, just copy it
else memcpy(img->imageData, bufferBGR, pCodecCtx->width * pCodecCtx->height * sizeof(uint8_t) * 3);
}
// Disable mutex lock
if (mutexVideo) pthread_mutex_unlock(mutexVideo);
return img;
}
// --------------------------------------------------------------------------
// ARDrone::finalizeVideo()
// Description : Finalize video.
// Return value : NONE
// --------------------------------------------------------------------------
void ARDrone::finalizeVideo(void)
{
// Destroy the thread
if (threadVideo) {
pthread_cancel(*threadVideo);
pthread_join(*threadVideo, NULL);
delete threadVideo;
threadVideo = NULL;
}
// Delete the mutex
if (mutexVideo) {
pthread_mutex_destroy(mutexVideo);
delete mutexVideo;
mutexVideo = NULL;
}
// Release the IplImage
if (img) {
cvReleaseImage(&img);
img = NULL;
}
// AR.Drone 2.0
if (version.major == ARDRONE_VERSION_2) {
// Deallocate the frame
if (pFrame) {
av_free(pFrame);
pFrame = NULL;
}
// Deallocate the frame
if (pFrameBGR) {
av_free(pFrameBGR);
pFrameBGR = NULL;
}
// Deallocate the buffer
if (bufferBGR) {
av_free(bufferBGR);
bufferBGR = NULL;
}
// Deallocate the convert context
if (pConvertCtx) {
sws_freeContext(pConvertCtx);
pConvertCtx = NULL;
}
// Deallocate the codec
if (pCodecCtx) {
avcodec_close(pCodecCtx);
pCodecCtx = NULL;
}
// Deallocate the format context
if (pFormatCtx) {
avformat_close_input(&pFormatCtx);
pFormatCtx = NULL;
}
}
// AR.Drone 1.0
else {
// Deallocate the buffer
if (bufferBGR) {
av_free(bufferBGR);
bufferBGR = NULL;
}
// Deallocate the codec
if (pCodecCtx) {
avcodec_close(pCodecCtx);
pCodecCtx = NULL;
}
// Close the socket
sockVideo.close();
}
}<commit_msg>Patch for ARDrone::getVideo<commit_after>// -------------------------------------------------------------------------
// CV Drone (= OpenCV + AR.Drone)
// Copyright(C) 2013 puku0x
// https://github.com/puku0x/cvdrone
//
// This source file is part of CV Drone library.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of EITHER:
// (1) The GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The text of the GNU Lesser
// General Public License is included with this library in the
// file cvdrone-license-LGPL.txt.
// (2) The BSD-style license that is included with this library in
// the file cvdrone-license-BSD.txt.
//
// 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 files
// cvdrone-license-LGPL.txt and cvdrone-license-BSD.txt for more details.
// -------------------------------------------------------------------------
#include "ardrone.h"
#include "uvlc.h"
// The codes of decoding H.264 video is based on following sites.
// - An ffmpeg and SDL Tutorial - Tutorial 01: Making Screencaps -
// http://dranger.com/ffmpeg/tutorial01.html
// - AR.Drone Development - 2.1.2 AR.Drone 2.0 Video Decording: FFMPEG + SDL2.0 -
// http://ardrone-ailab-u-tokyo.blogspot.jp/2012/07/212-ardrone-20-video-decording-ffmpeg.html
// --------------------------------------------------------------------------
// ARDrone::initVideo()
// Description : Initialize video.
// Return value : SUCCESS: 1 FAILURE: 0
// --------------------------------------------------------------------------
int ARDrone::initVideo(void)
{
// AR.Drone 2.0
if (version.major == ARDRONE_VERSION_2) {
// Open the IP address and port
char filename[256];
sprintf(filename, "tcp://%s:%d", ip, ARDRONE_VIDEO_PORT);
if (avformat_open_input(&pFormatCtx, filename, NULL, NULL) < 0) {
CVDRONE_ERROR("avformat_open_input() was failed. (%s, %d)\n", __FILE__, __LINE__);
return 0;
}
// Retrive and dump stream information
avformat_find_stream_info(pFormatCtx, NULL);
av_dump_format(pFormatCtx, 0, filename, 0);
// Find the decoder for the video stream
pCodecCtx = pFormatCtx->streams[0]->codec;
AVCodec *pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
if (pCodec == NULL) {
CVDRONE_ERROR("avcodec_find_decoder() was failed. (%s, %d)\n", __FILE__, __LINE__);
return 0;
}
// Open codec
if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
CVDRONE_ERROR("avcodec_open2() was failed. (%s, %d)\n", __FILE__, __LINE__);
return 0;
}
// Allocate video frames and a buffer
pFrame = avcodec_alloc_frame();
pFrameBGR = avcodec_alloc_frame();
bufferBGR = (uint8_t*)av_mallocz(avpicture_get_size(PIX_FMT_BGR24, pCodecCtx->width, pCodecCtx->height) * sizeof(uint8_t));
// Assign appropriate parts of buffer to image planes in pFrameBGR
avpicture_fill((AVPicture*)pFrameBGR, bufferBGR, PIX_FMT_BGR24, pCodecCtx->width, pCodecCtx->height);
// Convert it to BGR
pConvertCtx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, PIX_FMT_BGR24, SWS_SPLINE, NULL, NULL, NULL);
}
// AR.Drone 1.0
else {
// Open the IP address and port
if (!sockVideo.open(ip, ARDRONE_VIDEO_PORT)) {
CVDRONE_ERROR("UDPSocket::open(port=%d) was failed. (%s, %d)\n", ARDRONE_VIDEO_PORT, __FILE__, __LINE__);
return 0;
}
// Set codec
pCodecCtx = avcodec_alloc_context();
pCodecCtx->width = 320;
pCodecCtx->height = 240;
// Allocate a buffer
bufferBGR = (uint8_t*)av_mallocz(avpicture_get_size(PIX_FMT_BGR24, pCodecCtx->width, pCodecCtx->height));
}
// Allocate an IplImage
img = cvCreateImage(cvSize(pCodecCtx->width, (pCodecCtx->height == 368) ? 360 : pCodecCtx->height), IPL_DEPTH_8U, 3);
if (!img) {
CVDRONE_ERROR("cvCreateImage() was failed. (%s, %d)\n", __FILE__, __LINE__);
return 0;
}
// Clear the image
cvZero(img);
// Create a mutex
mutexVideo = new pthread_mutex_t;
pthread_mutex_init(mutexVideo, NULL);
// Create a thread
threadVideo = new pthread_t;
if (pthread_create(threadVideo, NULL, runVideo, this) != 0) {
CVDRONE_ERROR("pthread_create() was failed. (%s, %d)\n", __FILE__, __LINE__);
return 0;
}
return 1;
}
// --------------------------------------------------------------------------
// ARDrone::loopVideo()
// Description : Thread function.
// Return value : SUCCESS:0
// --------------------------------------------------------------------------
void ARDrone::loopVideo(void)
{
while (1) {
// Get video stream
if (!getVideo()) break;
pthread_testcancel();
msleep(1);
}
}
// --------------------------------------------------------------------------
// ARDrone::getVideo()
// Description : Get AR.Drone's video stream.
// Return value : SUCCESS: 1 FAILURE: 0
// --------------------------------------------------------------------------
int ARDrone::getVideo(void)
{
// AR.Drone 2.0
if (version.major == ARDRONE_VERSION_2) {
AVPacket packet;
int frameFinished = 0;
// Read all frames
while (av_read_frame(pFormatCtx, &packet) >= 0) {
// Decode the frame
avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);
// Decoded all frames
if (frameFinished) {
// Convert to BGR
if (mutexVideo) pthread_mutex_lock(mutexVideo);
sws_scale(pConvertCtx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameBGR->data, pFrameBGR->linesize);
if (mutexVideo) pthread_mutex_unlock(mutexVideo);
// Free the packet and break immidiately
av_free_packet(&packet);
return 1;
//break;
}
// Free the packet
av_free_packet(&packet);
}
return 0;
}
// AR.Drone 1.0
else {
// Send request
sockVideo.sendf("\x01\x00\x00\x00");
// Receive data
uint8_t buf[122880];
int size = sockVideo.receive((void*)&buf, sizeof(buf));
// Received something
if (size > 0) {
// Decode UVLC video
if (mutexVideo) pthread_mutex_lock(mutexVideo);
UVLC::DecodeVideo(buf, size, bufferBGR, &pCodecCtx->width, &pCodecCtx->height);
if (mutexVideo) pthread_mutex_unlock(mutexVideo);
}
}
return 1;
}
// --------------------------------------------------------------------------
// ARDrone::getImage()
// Description : Get an image from the AR.Drone's camera.
// Return value : Pointer to an IplImage (OpenCV image)
// --------------------------------------------------------------------------
IplImage* ARDrone::getImage(void)
{
// There is no image
if (!img) return NULL;
// Enable mutex lock
if (mutexVideo) pthread_mutex_lock(mutexVideo);
// AR.Drone 2.0
if (version.major == ARDRONE_VERSION_2) {
// Copy the frame to the IplImage
memcpy(img->imageData, pFrameBGR->data[0], pCodecCtx->width * ((pCodecCtx->height == 368) ? 360 : pCodecCtx->height) * sizeof(uint8_t) * 3);
}
// AR.Drone 1.0
else {
// If the sizes of buffer and IplImage are differnt
if (pCodecCtx->width != img->width || pCodecCtx->height != img->height) {
// Resize the image to 320x240
IplImage *small_img = cvCreateImageHeader(cvSize(pCodecCtx->width, pCodecCtx->height), IPL_DEPTH_8U, 3);
small_img->imageData = (char*)bufferBGR;
cvResize(small_img, img, CV_INTER_CUBIC);
cvReleaseImageHeader(&small_img);
}
// For 320x240 image, just copy it
else memcpy(img->imageData, bufferBGR, pCodecCtx->width * pCodecCtx->height * sizeof(uint8_t) * 3);
}
// Disable mutex lock
if (mutexVideo) pthread_mutex_unlock(mutexVideo);
return img;
}
// --------------------------------------------------------------------------
// ARDrone::finalizeVideo()
// Description : Finalize video.
// Return value : NONE
// --------------------------------------------------------------------------
void ARDrone::finalizeVideo(void)
{
// Destroy the thread
if (threadVideo) {
pthread_cancel(*threadVideo);
pthread_join(*threadVideo, NULL);
delete threadVideo;
threadVideo = NULL;
}
// Delete the mutex
if (mutexVideo) {
pthread_mutex_destroy(mutexVideo);
delete mutexVideo;
mutexVideo = NULL;
}
// Release the IplImage
if (img) {
cvReleaseImage(&img);
img = NULL;
}
// AR.Drone 2.0
if (version.major == ARDRONE_VERSION_2) {
// Deallocate the frame
if (pFrame) {
av_free(pFrame);
pFrame = NULL;
}
// Deallocate the frame
if (pFrameBGR) {
av_free(pFrameBGR);
pFrameBGR = NULL;
}
// Deallocate the buffer
if (bufferBGR) {
av_free(bufferBGR);
bufferBGR = NULL;
}
// Deallocate the convert context
if (pConvertCtx) {
sws_freeContext(pConvertCtx);
pConvertCtx = NULL;
}
// Deallocate the codec
if (pCodecCtx) {
avcodec_close(pCodecCtx);
pCodecCtx = NULL;
}
// Deallocate the format context
if (pFormatCtx) {
avformat_close_input(&pFormatCtx);
pFormatCtx = NULL;
}
}
// AR.Drone 1.0
else {
// Deallocate the buffer
if (bufferBGR) {
av_free(bufferBGR);
bufferBGR = NULL;
}
// Deallocate the codec
if (pCodecCtx) {
avcodec_close(pCodecCtx);
pCodecCtx = NULL;
}
// Close the socket
sockVideo.close();
}
}<|endoftext|>
|
<commit_before>//C++ header - Open Scene Graph Simulation - Copyright (C) 1998-2002 Robert Osfield
// Distributed under the terms of the GNU General Public License (GPL)
// as published by the Free Software Foundation.
//
// All software using osgSim must be GPL'd or excempted via the
// purchase of the Open Scene Graph Professional License (OSGPL)
// for further information contact robert@openscenegraph.com.
#include <osgSim/BlinkSequence>
#include <stdlib.h>
using namespace osgSim;
BlinkSequence::BlinkSequence():
Referenced(),
_pulsePeriod(0.0),
_phaseShift(0.0),
_pulseData(),
_sequenceGroup(0) {}
BlinkSequence::BlinkSequence(const BlinkSequence& bs):
Referenced(),
_pulsePeriod(bs._pulsePeriod),
_phaseShift(bs._phaseShift),
_pulseData(bs._pulseData),
_sequenceGroup(bs._sequenceGroup) {}
BlinkSequence::SequenceGroup::SequenceGroup():
Referenced()
{
// set a random base time between 0 and 1000.0
_baseTime = ((double)rand()/(double)RAND_MAX)*1000.0;
}
BlinkSequence::SequenceGroup::SequenceGroup(double baseTime):
Referenced(),
_baseTime(baseTime) {}
<commit_msg>Fix for compile problems under IRIX.<commit_after>//C++ header - Open Scene Graph Simulation - Copyright (C) 1998-2002 Robert Osfield
// Distributed under the terms of the GNU General Public License (GPL)
// as published by the Free Software Foundation.
//
// All software using osgSim must be GPL'd or excempted via the
// purchase of the Open Scene Graph Professional License (OSGPL)
// for further information contact robert@openscenegraph.com.
#include <osgSim/BlinkSequence>
#include <stdlib.h>
using namespace osgSim;
BlinkSequence::BlinkSequence():
_pulsePeriod(0.0),
_phaseShift(0.0),
_pulseData(),
_sequenceGroup(0)
{
}
BlinkSequence::BlinkSequence(const BlinkSequence& bs):
_pulsePeriod(bs._pulsePeriod),
_phaseShift(bs._phaseShift),
_pulseData(bs._pulseData),
_sequenceGroup(bs._sequenceGroup)
{
}
BlinkSequence::SequenceGroup::SequenceGroup()
{
// set a random base time between 0 and 1000.0
_baseTime = ((double)rand()/(double)RAND_MAX)*1000.0;
}
BlinkSequence::SequenceGroup::SequenceGroup(double baseTime):
_baseTime(baseTime)
{
}
<|endoftext|>
|
<commit_before>/*//////////////////////////////////////////////////////////////////
//// SKIRT -- an advanced radiative transfer code ////
//// © Astronomical Observatory, Ghent University ////
///////////////////////////////////////////////////////////////// */
#ifndef LOCKFREE_HPP
#define LOCKFREE_HPP
#include <atomic>
////////////////////////////////////////////////////////////////////
/** This namespace contains functions that support lock-free programming in a multi-threaded shared
memory environment. All implementations are provided inline in the header. */
namespace LockFree
{
/** This function adds the specified \em non-negative double value (which can be an expression)
to the specified target variable (passed as a reference to a memory location) in a
thread-safe manner. The function avoids race conditions between concurrent threads by
implementing a classical compare and swap (CAS) loop using the corresponding atomic
operation on the target memory location. The restriction that the added value must be
non-negative is imposed to avoid the ABA problem where two foreign threads concurrently
change the target contents from A to B and back to A, confusing the CAS loop in the current
thread. */
inline void add(double& target, double value)
{
// construct an atom over the target location without initialization (this produces no assembly code)
std::atomic<double>* atom = new(&target) std::atomic<double>;
// make a local copy of the target location's value
double old = *atom;
// perform the compare and swap (CAS) loop:
// - if the value of the target location didn't change since we copied it, move the incremented value into it
// - if the value of the target location did change, make a new local copy and try again
while( !atom->compare_exchange_weak(old, old+value) ) { }
}
}
////////////////////////////////////////////////////////////////////
#endif // LOCKFREE_HPP
<commit_msg>remove incorrect comment about negative values in CAS loop<commit_after>/*//////////////////////////////////////////////////////////////////
//// SKIRT -- an advanced radiative transfer code ////
//// © Astronomical Observatory, Ghent University ////
///////////////////////////////////////////////////////////////// */
#ifndef LOCKFREE_HPP
#define LOCKFREE_HPP
#include <atomic>
////////////////////////////////////////////////////////////////////
/** This namespace contains functions that support lock-free programming in a multi-threaded shared
memory environment. All implementations are provided inline in the header. */
namespace LockFree
{
/** This function adds the specified double value (which can be an expression)
to the specified target variable (passed as a reference to a memory location) in a
thread-safe manner. The function avoids race conditions between concurrent threads by
implementing a classical compare and swap (CAS) loop using the corresponding atomic
operation on the target memory location. */
inline void add(double& target, double value)
{
// construct an atom over the target location without initialization (this produces no assembly code)
std::atomic<double>* atom = new(&target) std::atomic<double>;
// make a local copy of the target location's value
double old = *atom;
// perform the compare and swap (CAS) loop:
// - if the value of the target location didn't change since we copied it, move the incremented value into it
// - if the value of the target location did change, make a new local copy and try again
while( !atom->compare_exchange_weak(old, old+value) ) { }
}
}
////////////////////////////////////////////////////////////////////
#endif // LOCKFREE_HPP
<|endoftext|>
|
<commit_before>#include "lexer.h"
#include "token.h"
#include "utils.h"
#include "exceptions.h"
namespace sota {
Token SotaLexer::Take(Token token) {
if (token)
_tokens.push_back(token);
return token;
}
Token SotaLexer::Emit() {
Token token = { TokenType::EndOfFile, Index, 0 };
if (_tokens.size()) {
token = _tokens.front();
_tokens.pop_front();
}
return token;
}
Token SotaLexer::EndOfLine() {
Token token = { TokenType::EndOfFile, Index, 0 };
if (IsCurrAnyOf({ '\r', '\n' })) {
++token.Length;
token.Type = TokenType::EndOfLine;
if (IsCurrSeqOf({ '\r', '\n' }))
++token.Length;
Next(token.Length);
}
while (Dent());
return Take(token);
}
Token SotaLexer::Dent() {
Token token = { TokenType::EndOfFile, Index, 0 };
if (IsPrevSeqOf({ '\r', '\n' }, 2) || IsPrevAnyOf({ '\r', '\n' })) {
auto ws = WhiteSpace();
auto indent = ws ? ws.Length : 0;
if (!_stride)
_stride = indent;
if (indent > _indents.top()) {
if (indent == _indents.top() + _stride) {
_indents.push(indent);
token.Type = TokenType::Indent;
}
else
throw SotaException("indent didnt meet previously established stride of");
}
else if (indent < _indents.top()) {
_indents.pop();
token.Type = TokenType::Dedent;
token.Length = 0;
}
}
return Take(token);
}
Token SotaLexer::WhiteSpace() {
Token token = { TokenType::EndOfFile, Index, 0 };
if (IsCurrAnyOf({ ' ', '\t' })) {
++token.Length;
token.Type = TokenType::WhiteSpace;
while (IsNextAnyOf({ ' ', '\t' }))
++token.Length;
}
return Take(token);
}
Token SotaLexer::Comment() {
Token token = { TokenType::EndOfFile, Index, 0 };
if (IsCurr('#')) {
++token.Length;
token.Type = TokenType::Comment;
while (!IsNextAnyOf({ '\r', '\n' }))
++token.Length;
}
return Take(token);
}
Token SotaLexer::Literal() {
Token token = { TokenType::EndOfFile, Index, 0 };
char c = Curr;
if ('\'' == c || '\"' == c) {
++token.Length;
token.Type = TokenType::Str;
while (!IsNextAnyOf({ c, '\r', '\n', '\0' }))
++token.Length;
if (IsCurr(c)) {
++token.Length;
Next();
}
else
throw SotaException("missing end quote on string literal");
}
return Take(token);
}
Token SotaLexer::Symbol() {
Token token = { TokenType::EndOfFile, Index, 0 };
std::string sym = "";
auto symkeys = keys(SymbolValue2Type);
while (startofany(sym + Curr, symkeys)) {
sym += Curr;
Next();
}
token.Type = SymbolValue2Type[sym];
token.Length = Index - token.Index;
if (!token.Type) {
Index = token.Index; //backtrack
token.Length = 0;
}
return Take(token);
}
Token SotaLexer::IdentifierNumberOrKeyword() {
Token token = { TokenType::EndOfFile, Index, 0 };
bool loop = true;
while (loop) {
switch (Curr) {
case 'a': case 'n': case 'A': case 'N':
case 'b': case 'o': case 'B': case 'O':
case 'c': case 'p': case 'C': case 'P':
case 'd': case 'q': case 'D': case 'Q':
case 'e': case 'r': case 'E': case 'R':
case 'f': case 's': case 'F': case 'S':
case 'g': case 't': case 'G': case 'T':
case 'h': case 'u': case 'H': case 'U':
case 'i': case 'v': case 'I': case 'V':
case 'j': case 'w': case 'J': case 'W':
case 'k': case 'x': case 'K': case 'X':
case 'l': case 'y': case 'L': case 'Y':
case 'm': case 'z': case 'M': case 'Z':
case '_':
token.Type = TokenType::Id;
break;
case '0': case '5':
case '1': case '6':
case '2': case '7':
case '3': case '8':
case '4': case '9':
if (token.Type != TokenType::Id)
token.Type = TokenType::Num;
break;
default:
loop = false;
continue;
}
++token.Length;
Next();
}
auto value = Value(token);
if (KeywordValue2Type.count(value))
token.Type = KeywordValue2Type[value];
return Take(token);
}
Token SotaLexer::EndOfFile() {
Token token = { TokenType::EndOfFile, Index, 0 };
return token;
}
/* public */
SotaLexer::~SotaLexer() {
}
SotaLexer::SotaLexer(std::vector<char> chars) : SotaStream(chars) {
_stride = 0;
_indents.push(0);
}
unsigned int SotaLexer::Line(const Token &token) {
/*
regex const pattern("\r?\n");
string head = string(Items.begin(), Items.begin() + token.Index);
ptrdiff_t const count(distance(
sregex_iterator(head.begin(), head.end(), pattern),
sregex_iterator()));
return count + 1;
*/
return 0;
}
unsigned int SotaLexer::Column(const Token &token) {
unsigned int count = token.Index;
for (; count > 0; --count) {
char c = Items[count];
if ('\n' == c || '\r' == c) {
break;
}
}
return token.Index - count;
}
std::string SotaLexer::Value(const Token &token) {
return std::string(Items.begin() + token.Index, Items.begin() + token.Index + token.Length);
}
std::string SotaLexer::Pretty(const Token &token) {
std::string result;
auto value = Value(token);
auto tokenvalue = Type2Value[token.Type];
switch (token.Type) {
case TokenType::WhiteSpace:
case TokenType::EndOfFile:
case TokenType::EndOfLine:
case TokenType::Indent:
case TokenType::Dedent:
result = tokenvalue;
break;
default:
result = value != tokenvalue ? tokenvalue + ":" + value : value;
break;
}
return result;
}
Token SotaLexer::Scan() {
//Length = 0;
if (auto token = Emit())
return token;
if (EndOfLine())
return Emit();
if (WhiteSpace())
return Emit();
if (Comment())
return Emit();
if (Literal())
return Emit();
if (Symbol())
return Emit();
if (IdentifierNumberOrKeyword())
return Emit();
return EndOfFile();
}
std::vector<Token> SotaLexer::Tokenize() {
auto tokens = std::vector<Token>();
return tokens;
}
}
<commit_msg>backed away from the edge on using Take and Emit everywhere... -sai<commit_after>#include "lexer.h"
#include "token.h"
#include "utils.h"
#include "exceptions.h"
namespace sota {
Token SotaLexer::Take(Token token) {
if (token)
_tokens.push_back(token);
return token;
}
Token SotaLexer::Emit() {
Token token = { TokenType::EndOfFile, Index, 0 };
if (_tokens.size()) {
token = _tokens.front();
_tokens.pop_front();
}
return token;
}
Token SotaLexer::EndOfLine() {
Token token = { TokenType::EndOfFile, Index, 0 };
if (IsCurrAnyOf({ '\r', '\n' })) {
++token.Length;
token.Type = TokenType::EndOfLine;
if (IsCurrSeqOf({ '\r', '\n' }))
++token.Length;
Next(token.Length);
}
while (auto dent = Dent())
Take(dent);
return token;
}
Token SotaLexer::Dent() {
Token token = { TokenType::EndOfFile, Index, 0 };
if (IsPrevSeqOf({ '\r', '\n' }, 2) || IsPrevAnyOf({ '\r', '\n' })) {
auto indent = 0;
if (auto ws = WhiteSpace()) {
Take(ws);
indent = ws.Length;
}
if (!_stride)
_stride = indent;
if (indent > _indents.top()) {
if (indent == _indents.top() + _stride) {
_indents.push(indent);
token.Type = TokenType::Indent;
}
else
throw SotaException("indent didnt meet previously established stride of");
}
else if (indent < _indents.top()) {
_indents.pop();
token.Type = TokenType::Dedent;
token.Length = 0;
}
}
return token;
}
Token SotaLexer::WhiteSpace() {
Token token = { TokenType::EndOfFile, Index, 0 };
if (IsCurrAnyOf({ ' ', '\t' })) {
++token.Length;
token.Type = TokenType::WhiteSpace;
while (IsNextAnyOf({ ' ', '\t' }))
++token.Length;
}
return token;
}
Token SotaLexer::Comment() {
Token token = { TokenType::EndOfFile, Index, 0 };
if (IsCurr('#')) {
++token.Length;
token.Type = TokenType::Comment;
while (!IsNextAnyOf({ '\r', '\n' }))
++token.Length;
}
return token;
}
Token SotaLexer::Literal() {
Token token = { TokenType::EndOfFile, Index, 0 };
char c = Curr;
if ('\'' == c || '\"' == c) {
++token.Length;
token.Type = TokenType::Str;
while (!IsNextAnyOf({ c, '\r', '\n', '\0' }))
++token.Length;
if (IsCurr(c)) {
++token.Length;
Next();
}
else
throw SotaException("missing end quote on string literal");
}
return token;
}
Token SotaLexer::Symbol() {
Token token = { TokenType::EndOfFile, Index, 0 };
std::string sym = "";
auto symkeys = keys(SymbolValue2Type);
while (startofany(sym + Curr, symkeys)) {
sym += Curr;
Next();
}
token.Type = SymbolValue2Type[sym];
token.Length = Index - token.Index;
if (!token.Type) {
Index = token.Index; //backtrack
token.Length = 0;
}
return token;
}
Token SotaLexer::IdentifierNumberOrKeyword() {
Token token = { TokenType::EndOfFile, Index, 0 };
bool loop = true;
while (loop) {
switch (Curr) {
case 'a': case 'n': case 'A': case 'N':
case 'b': case 'o': case 'B': case 'O':
case 'c': case 'p': case 'C': case 'P':
case 'd': case 'q': case 'D': case 'Q':
case 'e': case 'r': case 'E': case 'R':
case 'f': case 's': case 'F': case 'S':
case 'g': case 't': case 'G': case 'T':
case 'h': case 'u': case 'H': case 'U':
case 'i': case 'v': case 'I': case 'V':
case 'j': case 'w': case 'J': case 'W':
case 'k': case 'x': case 'K': case 'X':
case 'l': case 'y': case 'L': case 'Y':
case 'm': case 'z': case 'M': case 'Z':
case '_':
token.Type = TokenType::Id;
break;
case '0': case '5':
case '1': case '6':
case '2': case '7':
case '3': case '8':
case '4': case '9':
if (token.Type != TokenType::Id)
token.Type = TokenType::Num;
break;
default:
loop = false;
continue;
}
++token.Length;
Next();
}
auto value = Value(token);
if (KeywordValue2Type.count(value))
token.Type = KeywordValue2Type[value];
return token;
}
Token SotaLexer::EndOfFile() {
Token token = { TokenType::EndOfFile, Index, 0 };
return token;
}
/* public */
SotaLexer::~SotaLexer() {
}
SotaLexer::SotaLexer(std::vector<char> chars) : SotaStream(chars) {
_stride = 0;
_indents.push(0);
}
unsigned int SotaLexer::Line(const Token &token) {
/*
regex const pattern("\r?\n");
string head = string(Items.begin(), Items.begin() + token.Index);
ptrdiff_t const count(distance(
sregex_iterator(head.begin(), head.end(), pattern),
sregex_iterator()));
return count + 1;
*/
return 0;
}
unsigned int SotaLexer::Column(const Token &token) {
unsigned int count = token.Index;
for (; count > 0; --count) {
char c = Items[count];
if ('\n' == c || '\r' == c) {
break;
}
}
return token.Index - count;
}
std::string SotaLexer::Value(const Token &token) {
return std::string(Items.begin() + token.Index, Items.begin() + token.Index + token.Length);
}
std::string SotaLexer::Pretty(const Token &token) {
std::string result;
auto value = Value(token);
auto tokenvalue = Type2Value[token.Type];
switch (token.Type) {
case TokenType::WhiteSpace:
case TokenType::EndOfFile:
case TokenType::EndOfLine:
case TokenType::Indent:
case TokenType::Dedent:
result = tokenvalue;
break;
default:
result = value != tokenvalue ? tokenvalue + ":" + value : value;
break;
}
return result;
}
Token SotaLexer::Scan() {
//Length = 0;
if (auto token = Emit())
return token;
if (auto token = EndOfLine())
return token;
if (auto token = WhiteSpace())
return token;
if (auto token = Comment())
return token;
if (auto token = Literal())
return token;
if (auto token = Symbol())
return token;
if (auto token = IdentifierNumberOrKeyword())
return token;
return EndOfFile();
}
std::vector<Token> SotaLexer::Tokenize() {
auto tokens = std::vector<Token>();
return tokens;
}
}
<|endoftext|>
|
<commit_before>#include "motorController.h"
#include "SubMotorController/MotorCurrentMsg.h"
#include "time.h"
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <string>
using namespace std;
void printMessageMismatchError() {
}
ros::NodeHandle* n;
void MotorControllerHandler::print(string error) {
bool init = false;
if(!init) {
errorOut = n->advertise<std_msgs::String>("/Error_Log", 100);
init = true;
}
printf("ErrorHandler: %s\n", error.c_str());
std_msgs::String msg;
msg.data = error;
errorOut.publish(msg);
}
MotorControllerHandler::MotorControllerHandler(ros::NodeHandle* nh, const char* Port)
: serialPort(Port) {
n = nh;
awaitingResponce = false;
bufIndex = 0;
currentMessage.type = NO_MESSAGE;
gettimeofday(&lastQRCurTime, NULL);
gettimeofday(&lastQLCurTime, NULL);
gettimeofday(&lastQVoltTime, NULL);
gettimeofday(&lastMotorTime, NULL);
rightSpeed = leftSpeed = rightTargetSpeed = leftTargetSpeed = 0;
MaxStep = 20;
name = Port;
try {
serialPort.Open(BAUD, SerialPort::CHAR_SIZE_8, SerialPort::PARITY_NONE, SerialPort::STOP_BITS_1, SerialPort::FLOW_CONTROL_NONE);
} catch (...) {
char temp[1000];
sprintf(temp, "%s error: Failed during initialization\n", name.c_str());
print(string(temp));
bufIndex = 0;
}
//motorStatus = n->advertise<SubMotorController::MotorDataMessage>("/Motor_Data", 10);
motorCurrent = n->advertise<SubMotorController::MotorCurrentMsg>("/Motor_Current", 100);
}
void MotorControllerHandler::sendMessage(Message m) {
currentMessage = m;
transmit();
}
int filter(int speed) {
if(speed >= 256)
speed = 255;
if(speed <= -256)
speed = -255;
speed = -speed;
return speed;
}
void MotorControllerHandler::setMotorSpeed(int right, int left) {
rightTargetSpeed = filter(right);
leftTargetSpeed = filter(left);
// printf("setting target speeds to %d %d\n", rightTargetSpeed, leftTargetSpeed);
}
Message createMessageFromSpeed(int rightSpeed, int leftSpeed) {
Message msg;
msg.type = MOTOR_TYPE;
if(leftSpeed > 0) {
msg.DataC[0] = leftSpeed;
msg.DataC[1] = 0;
} else {
int rev = -leftSpeed;
msg.DataC[0] = 0;
msg.DataC[1] = rev;
}
if(rightSpeed > 0) {
msg.DataC[2] = rightSpeed;
msg.DataC[3] = 0;
} else {
int rev = -rightSpeed;
msg.DataC[2] = 0;
msg.DataC[3] = rev;
}
return msg;
}
void MotorControllerHandler::transmit() {
if(currentMessage.type == NO_MESSAGE)
return;
gettimeofday(&lastSendTime, NULL);
awaitingResponce = true;
if(!serialPort.IsOpen()) {
try {
serialPort.Open(BAUD, SerialPort::CHAR_SIZE_8, SerialPort::PARITY_NONE, SerialPort::STOP_BITS_1, SerialPort::FLOW_CONTROL_NONE);
} catch (...) {
char temp[1000];
sprintf(temp, "%s error: Unable to open port\n", name.c_str());
print(string(temp));
}
}
try {
serialPort.WriteByte('S');
serialPort.WriteByte(currentMessage.type);
for(int i = 0; i < 4; i++) {
serialPort.WriteByte(currentMessage.DataC[i]);
}
serialPort.WriteByte('E');
awaitingResponce = true;
} catch (SerialPort::NotOpen serError){
char temp[1000];
sprintf(temp, "%s error: Port not open - %s\n", name.c_str(), serError.what());
print(string(temp));
} catch (std::runtime_error runError){
char temp[1000];
sprintf(temp, "%s error: Unable to send message - %s\n", name.c_str(), runError.what());
print(string(temp));
}catch (...){
char temp[1000];
sprintf(temp, "%s error: Unable to send message - Unknown exception\n", name.c_str());
print(string(temp));
}
}
}
void MotorControllerHandler::processResponce() {
if(buffer[0] != 'S' || buffer[6] != 'E') {
//Misaligned data? throw out bytes until you get it to align correctly
printf("Misaligned data: ");
for(int i = 0; i < 7; i++)
printf("\'%c\' (%x)", buffer[i], buffer[i]);
printf("\n");
for(int i = 0; i < 6; i++) {
buffer[i] = buffer[i+1];
}
bufIndex--;
return;
}
bufIndex = 0;
Message responce;
responce.type = buffer[1];
for(int i = 0; i < 4; i++) {
responce.DataC[i] = buffer[i+2];
}
//printf("got responce %c %c %x %x %x %x %c\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6]);
switch (responce.type) {
case ERROR_TYPE:
char temp[1000];
sprintf(temp, "%s error from controller: %c%c%c%c\n", name.c_str(), buffer[2], buffer[3], buffer[4], buffer[5]);
print(string(temp));
awaitingResponce = false;
break;
case MOTOR_RESPONCE_TYPE:
if(currentMessage.type != MOTOR_TYPE) {
printMessageMismatchError();
break;
}
if(responce.DataC[0])
leftSpeed = responce.DataC[0];
else
leftSpeed = -responce.DataC[1];
if(responce.DataC[2])
rightSpeed = responce.DataC[2];
else
rightSpeed = -responce.DataC[3];
currentMessage.type = NO_MESSAGE;
awaitingResponce = false;
break;
case CURRENT_RESPONCE_TYPE:
if(currentMessage.type != CURRENT_TYPE) {
printMessageMismatchError();
break;
}
if(currentMessage.DataC[0] == 'L')
{
LeftCurrent = responce.DataF;
SubMotorController::MotorCurrentMsg msg;
msg.motorName = name;
msg.motorPosition = "Left";
msg.motorCurrent = LeftCurrent;
motorCurrent.publish(msg);
}
else
{
RightCurrent = responce.DataF;
SubMotorController::MotorCurrentMsg msg;
msg.motorName = name;
msg.motorPosition = "Right";
msg.motorCurrent = RightCurrent;
motorCurrent.publish(msg);
}
currentMessage.type = NO_MESSAGE;
awaitingResponce = false;
break;
case VOLTAGE_RESPONCE_TYPE:
if(currentMessage.type != VOLTAGE_TYPE) {
printMessageMismatchError();
break;
}
Voltage = responce.DataF;
currentMessage.type = NO_MESSAGE;
awaitingResponce = false;
break;
default:
printf("Unrecognized responce type: %c\n", responce.type);
}
}
void MotorControllerHandler::recieve() {
if(serialPort.IsOpen() && awaitingResponce) {
try {
while(serialPort.IsDataAvailable()) {
unsigned char data = serialPort.ReadByte();
// printf("recieved byte \'%c\'\n", data);
while(bufIndex == 7) {
processResponce();
}
buffer[bufIndex++] = data;
if(bufIndex == 7) {
processResponce();
}
}
} catch (...) {
char temp[1000];
sprintf(temp, "%s error: While attempting to read data\n", name.c_str());
print(string(temp));
}
}
}
int getMilliSecsBetween(timeval& start, timeval& end) {
int millis = (end.tv_sec - start.tv_sec) * 1000;
millis += (end.tv_usec - start.tv_usec) / 1000;
return millis;
}
bool MotorControllerHandler::TransmitTimeout() {
timeval curTime;
gettimeofday(&curTime, NULL);
int elsaped = getMilliSecsBetween(lastSendTime, curTime);
if(elsaped > RESEND_TIMEOUT)
return true;
return false;
}
void MotorControllerHandler::CheckQuery() {
if(awaitingResponce)
return;
timeval curtime;
gettimeofday(&curtime, NULL);
int elsaped = getMilliSecsBetween(lastQRCurTime, curtime);
if(elsaped > CURRENT_PERIOD) {
Message query;
query.type = CURRENT_TYPE;
query.DataC[0] = 'R';
sendMessage(query);
gettimeofday(&lastQRCurTime, NULL);
return;
}
elsaped = getMilliSecsBetween(lastQLCurTime, curtime);
if(elsaped > CURRENT_PERIOD) {
Message query;
query.type = CURRENT_TYPE;
query.DataC[0] = 'L';
sendMessage(query);
gettimeofday(&lastQLCurTime, NULL);
return;
}
elsaped = getMilliSecsBetween(lastQVoltTime, curtime);
if(elsaped > QUERY_PERIOD) {
Message query;
query.type = VOLTAGE_TYPE;
sendMessage(query);
gettimeofday(&lastQVoltTime, NULL);
return;
}
}
void MotorControllerHandler::CheckMotor() {
if(awaitingResponce)
return;
timeval curTime;
gettimeofday(&curTime, NULL);
int elsaped = getMilliSecsBetween(lastMotorTime, curTime);
if(elsaped < MOTOR_PERIOD)
return;
bool needsSent = true;
int leftSetSpeed = leftSpeed;
int rightSetSpeed = rightSpeed;
if(leftSpeed != leftTargetSpeed) {
int diff = leftTargetSpeed - leftSpeed;
if(diff > MaxStep)
diff = MaxStep;
if(diff < -MaxStep)
diff = -MaxStep;
leftSetSpeed += diff;
needsSent=true;
}
if(rightSpeed != rightTargetSpeed) {
int diff = rightTargetSpeed - rightSpeed;
if(diff > MaxStep)
diff = MaxStep;
if(diff < -MaxStep)
diff = -MaxStep;
rightSetSpeed += diff;
needsSent=true;
}
if(needsSent) {
sendMessage(createMessageFromSpeed(rightSetSpeed, leftSetSpeed));
gettimeofday(&lastMotorTime, NULL);
}
}
void MotorControllerHandler::spinOnce() {
recieve();
CheckMotor();
CheckQuery();
if(awaitingResponce && TransmitTimeout()) {
transmit();
}
}
<commit_msg>Extra '}'<commit_after>#include "motorController.h"
#include "SubMotorController/MotorCurrentMsg.h"
#include "time.h"
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <string>
using namespace std;
void printMessageMismatchError() {
}
ros::NodeHandle* n;
void MotorControllerHandler::print(string error) {
bool init = false;
if(!init) {
errorOut = n->advertise<std_msgs::String>("/Error_Log", 100);
init = true;
}
printf("ErrorHandler: %s\n", error.c_str());
std_msgs::String msg;
msg.data = error;
errorOut.publish(msg);
}
MotorControllerHandler::MotorControllerHandler(ros::NodeHandle* nh, const char* Port)
: serialPort(Port) {
n = nh;
awaitingResponce = false;
bufIndex = 0;
currentMessage.type = NO_MESSAGE;
gettimeofday(&lastQRCurTime, NULL);
gettimeofday(&lastQLCurTime, NULL);
gettimeofday(&lastQVoltTime, NULL);
gettimeofday(&lastMotorTime, NULL);
rightSpeed = leftSpeed = rightTargetSpeed = leftTargetSpeed = 0;
MaxStep = 20;
name = Port;
try {
serialPort.Open(BAUD, SerialPort::CHAR_SIZE_8, SerialPort::PARITY_NONE, SerialPort::STOP_BITS_1, SerialPort::FLOW_CONTROL_NONE);
} catch (...) {
char temp[1000];
sprintf(temp, "%s error: Failed during initialization\n", name.c_str());
print(string(temp));
bufIndex = 0;
}
//motorStatus = n->advertise<SubMotorController::MotorDataMessage>("/Motor_Data", 10);
motorCurrent = n->advertise<SubMotorController::MotorCurrentMsg>("/Motor_Current", 100);
}
void MotorControllerHandler::sendMessage(Message m) {
currentMessage = m;
transmit();
}
int filter(int speed) {
if(speed >= 256)
speed = 255;
if(speed <= -256)
speed = -255;
speed = -speed;
return speed;
}
void MotorControllerHandler::setMotorSpeed(int right, int left) {
rightTargetSpeed = filter(right);
leftTargetSpeed = filter(left);
// printf("setting target speeds to %d %d\n", rightTargetSpeed, leftTargetSpeed);
}
Message createMessageFromSpeed(int rightSpeed, int leftSpeed) {
Message msg;
msg.type = MOTOR_TYPE;
if(leftSpeed > 0) {
msg.DataC[0] = leftSpeed;
msg.DataC[1] = 0;
} else {
int rev = -leftSpeed;
msg.DataC[0] = 0;
msg.DataC[1] = rev;
}
if(rightSpeed > 0) {
msg.DataC[2] = rightSpeed;
msg.DataC[3] = 0;
} else {
int rev = -rightSpeed;
msg.DataC[2] = 0;
msg.DataC[3] = rev;
}
return msg;
}
void MotorControllerHandler::transmit() {
if(currentMessage.type == NO_MESSAGE)
return;
gettimeofday(&lastSendTime, NULL);
awaitingResponce = true;
if(!serialPort.IsOpen()) {
try {
serialPort.Open(BAUD, SerialPort::CHAR_SIZE_8, SerialPort::PARITY_NONE, SerialPort::STOP_BITS_1, SerialPort::FLOW_CONTROL_NONE);
} catch (...) {
char temp[1000];
sprintf(temp, "%s error: Unable to open port\n", name.c_str());
print(string(temp));
}
}
try {
serialPort.WriteByte('S');
serialPort.WriteByte(currentMessage.type);
for(int i = 0; i < 4; i++) {
serialPort.WriteByte(currentMessage.DataC[i]);
}
serialPort.WriteByte('E');
awaitingResponce = true;
} catch (SerialPort::NotOpen serError){
char temp[1000];
sprintf(temp, "%s error: Port not open - %s\n", name.c_str(), serError.what());
print(string(temp));
} catch (std::runtime_error runError){
char temp[1000];
sprintf(temp, "%s error: Unable to send message - %s\n", name.c_str(), runError.what());
print(string(temp));
}catch (...){
char temp[1000];
sprintf(temp, "%s error: Unable to send message - Unknown exception\n", name.c_str());
print(string(temp));
}
}
void MotorControllerHandler::processResponce() {
if(buffer[0] != 'S' || buffer[6] != 'E') {
//Misaligned data? throw out bytes until you get it to align correctly
printf("Misaligned data: ");
for(int i = 0; i < 7; i++)
printf("\'%c\' (%x)", buffer[i], buffer[i]);
printf("\n");
for(int i = 0; i < 6; i++) {
buffer[i] = buffer[i+1];
}
bufIndex--;
return;
}
bufIndex = 0;
Message responce;
responce.type = buffer[1];
for(int i = 0; i < 4; i++) {
responce.DataC[i] = buffer[i+2];
}
//printf("got responce %c %c %x %x %x %x %c\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6]);
switch (responce.type) {
case ERROR_TYPE:
char temp[1000];
sprintf(temp, "%s error from controller: %c%c%c%c\n", name.c_str(), buffer[2], buffer[3], buffer[4], buffer[5]);
print(string(temp));
awaitingResponce = false;
break;
case MOTOR_RESPONCE_TYPE:
if(currentMessage.type != MOTOR_TYPE) {
printMessageMismatchError();
break;
}
if(responce.DataC[0])
leftSpeed = responce.DataC[0];
else
leftSpeed = -responce.DataC[1];
if(responce.DataC[2])
rightSpeed = responce.DataC[2];
else
rightSpeed = -responce.DataC[3];
currentMessage.type = NO_MESSAGE;
awaitingResponce = false;
break;
case CURRENT_RESPONCE_TYPE:
if(currentMessage.type != CURRENT_TYPE) {
printMessageMismatchError();
break;
}
if(currentMessage.DataC[0] == 'L')
{
LeftCurrent = responce.DataF;
SubMotorController::MotorCurrentMsg msg;
msg.motorName = name;
msg.motorPosition = "Left";
msg.motorCurrent = LeftCurrent;
motorCurrent.publish(msg);
}
else
{
RightCurrent = responce.DataF;
SubMotorController::MotorCurrentMsg msg;
msg.motorName = name;
msg.motorPosition = "Right";
msg.motorCurrent = RightCurrent;
motorCurrent.publish(msg);
}
currentMessage.type = NO_MESSAGE;
awaitingResponce = false;
break;
case VOLTAGE_RESPONCE_TYPE:
if(currentMessage.type != VOLTAGE_TYPE) {
printMessageMismatchError();
break;
}
Voltage = responce.DataF;
currentMessage.type = NO_MESSAGE;
awaitingResponce = false;
break;
default:
printf("Unrecognized responce type: %c\n", responce.type);
}
}
void MotorControllerHandler::recieve() {
if(serialPort.IsOpen() && awaitingResponce) {
try {
while(serialPort.IsDataAvailable()) {
unsigned char data = serialPort.ReadByte();
// printf("recieved byte \'%c\'\n", data);
while(bufIndex == 7) {
processResponce();
}
buffer[bufIndex++] = data;
if(bufIndex == 7) {
processResponce();
}
}
} catch (...) {
char temp[1000];
sprintf(temp, "%s error: While attempting to read data\n", name.c_str());
print(string(temp));
}
}
}
int getMilliSecsBetween(timeval& start, timeval& end) {
int millis = (end.tv_sec - start.tv_sec) * 1000;
millis += (end.tv_usec - start.tv_usec) / 1000;
return millis;
}
bool MotorControllerHandler::TransmitTimeout() {
timeval curTime;
gettimeofday(&curTime, NULL);
int elsaped = getMilliSecsBetween(lastSendTime, curTime);
if(elsaped > RESEND_TIMEOUT)
return true;
return false;
}
void MotorControllerHandler::CheckQuery() {
if(awaitingResponce)
return;
timeval curtime;
gettimeofday(&curtime, NULL);
int elsaped = getMilliSecsBetween(lastQRCurTime, curtime);
if(elsaped > CURRENT_PERIOD) {
Message query;
query.type = CURRENT_TYPE;
query.DataC[0] = 'R';
sendMessage(query);
gettimeofday(&lastQRCurTime, NULL);
return;
}
elsaped = getMilliSecsBetween(lastQLCurTime, curtime);
if(elsaped > CURRENT_PERIOD) {
Message query;
query.type = CURRENT_TYPE;
query.DataC[0] = 'L';
sendMessage(query);
gettimeofday(&lastQLCurTime, NULL);
return;
}
elsaped = getMilliSecsBetween(lastQVoltTime, curtime);
if(elsaped > QUERY_PERIOD) {
Message query;
query.type = VOLTAGE_TYPE;
sendMessage(query);
gettimeofday(&lastQVoltTime, NULL);
return;
}
}
void MotorControllerHandler::CheckMotor() {
if(awaitingResponce)
return;
timeval curTime;
gettimeofday(&curTime, NULL);
int elsaped = getMilliSecsBetween(lastMotorTime, curTime);
if(elsaped < MOTOR_PERIOD)
return;
bool needsSent = true;
int leftSetSpeed = leftSpeed;
int rightSetSpeed = rightSpeed;
if(leftSpeed != leftTargetSpeed) {
int diff = leftTargetSpeed - leftSpeed;
if(diff > MaxStep)
diff = MaxStep;
if(diff < -MaxStep)
diff = -MaxStep;
leftSetSpeed += diff;
needsSent=true;
}
if(rightSpeed != rightTargetSpeed) {
int diff = rightTargetSpeed - rightSpeed;
if(diff > MaxStep)
diff = MaxStep;
if(diff < -MaxStep)
diff = -MaxStep;
rightSetSpeed += diff;
needsSent=true;
}
if(needsSent) {
sendMessage(createMessageFromSpeed(rightSetSpeed, leftSetSpeed));
gettimeofday(&lastMotorTime, NULL);
}
}
void MotorControllerHandler::spinOnce() {
recieve();
CheckMotor();
CheckQuery();
if(awaitingResponce && TransmitTimeout()) {
transmit();
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
#include <primesieve/ParallelPrimeSieve.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/miller_rabin.hpp>
#include <boost/math/common_factor.hpp>
#include <primesieve.hpp>
#include <gmpxx.h>
using namespace boost::multiprecision;
cpp_int phi(const cpp_int x) {
if (x == 1) {
return 1;
}
if (miller_rabin_test(x, 50)) {
return x-1;
}
if (x % 2 == 0){
cpp_int y = x >> 1;
return !(y & 1) ? phi(y)<<1 : phi(y);
}
primesieve::iterator pi;
cpp_int prime;
for (prime = pi.next_prime(); prime < x; prime=pi.next_prime())
{
cpp_int k = *prime; // Kaput
if (x % k) continue;
cpp_int o = x/k;
cpp_int d = boost::math::gcd(k, o);
return d == 1 ? phi(k)*phi(o) : phi(k)*phi(o)*d/phi(d); // Kaput
}
}
int main(void) {
cpp_int small = 99;
cpp_int large = 756928375693284658;
std::cout << phi(small);
return 0;
}
<commit_msg>Fixed pointer error<commit_after>#include <iostream>
#include <primesieve.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/miller_rabin.hpp>
#include <boost/math/common_factor.hpp>
using namespace boost::multiprecision;
cpp_int phi(const cpp_int x) {
if (x == 1) {
return 1;
}
if (miller_rabin_test(x, 50)) {
return x-1;
}
if (x % 2 == 0){
cpp_int y = x >> 1;
return !(y & 1) ? phi(y)<<1 : phi(y);
}
primesieve::iterator pi;
cpp_int prime;
for (prime = pi.next_prime(); prime < x; prime=pi.next_prime())
{
cpp_int k = prime; // Kaput
if (x % k) continue;
cpp_int o = x/k;
cpp_int d = boost::math::gcd(k, o);
return d == 1 ? phi(k)*phi(o) : phi(k)*phi(o)*d/phi(d); // Kaput
}
}
int main(void) {
cpp_int small = 99;
cpp_int large = 756928375693284658;
std::cout << phi(small);
return 0;
}
<|endoftext|>
|
<commit_before>#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
#include "sass_interface.h"
#include "context.hpp"
#include "inspect.hpp"
#ifndef SASS_ERROR_HANDLING
#include "error_handling.hpp"
#endif
#include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cstring>
extern "C" {
using namespace std;
sass_context* sass_new_context()
{ return (sass_context*) calloc(1, sizeof(sass_context)); }
// helper for safe access to c_ctx
static const char* safe_str (const char* str) {
return str == NULL ? "" : str;
}
static void copy_strings(const std::vector<std::string>& strings, char*** array, int skip = 0) {
int num = static_cast<int>(strings.size());
char** arr = (char**) malloc(sizeof(char*) * (num + 1));
for(int i = skip; i < num; i++) {
arr[i-skip] = (char*) malloc(sizeof(char) * (strings[i].size() + 1));
std::copy(strings[i].begin(), strings[i].end(), arr[i-skip]);
arr[i-skip][strings[i].size()] = '\0';
}
arr[num-skip] = 0;
*array = arr;
}
static void free_string_array(char ** arr) {
if(!arr)
return;
char **it = arr;
while (it && (*it)) {
free(*it);
++it;
}
free(arr);
}
void sass_free_context(sass_context* ctx)
{
if (ctx->output_string) free(ctx->output_string);
if (ctx->source_map_string) free(ctx->source_map_string);
if (ctx->error_message) free(ctx->error_message);
if (ctx->c_functions) free(ctx->c_functions);
free_string_array(ctx->included_files);
free(ctx);
}
sass_file_context* sass_new_file_context()
{ return (sass_file_context*) calloc(1, sizeof(sass_file_context)); }
void sass_free_file_context(sass_file_context* ctx)
{
if (ctx->output_string) free(ctx->output_string);
if (ctx->source_map_string) free(ctx->source_map_string);
if (ctx->error_message) free(ctx->error_message);
if (ctx->c_functions) free(ctx->c_functions);
free_string_array(ctx->included_files);
free(ctx);
}
sass_folder_context* sass_new_folder_context()
{ return (sass_folder_context*) calloc(1, sizeof(sass_folder_context)); }
void sass_free_folder_context(sass_folder_context* ctx)
{
free_string_array(ctx->included_files);
free(ctx);
}
int sass_compile(sass_context* c_ctx)
{
using namespace Sass;
try {
string input_path = safe_str(c_ctx->input_path);
int lastindex = static_cast<int>(input_path.find_last_of("."));
string output_path;
if (!c_ctx->output_path) {
if (input_path != "") {
output_path = (lastindex > -1 ? input_path.substr(0, lastindex) : input_path) + ".css";
}
}
else {
output_path = c_ctx->output_path;
}
Context cpp_ctx(
Context::Data().source_c_str(c_ctx->source_string)
.output_path(output_path)
.output_style((Output_Style) c_ctx->options.output_style)
.is_indented_syntax_src(c_ctx->options.is_indented_syntax_src)
.source_comments(c_ctx->options.source_comments)
.source_map_file(safe_str(c_ctx->options.source_map_file))
.source_map_embed(c_ctx->options.source_map_embed)
.source_map_contents(c_ctx->options.source_map_contents)
.omit_source_map_url(c_ctx->options.omit_source_map_url)
.image_path(safe_str(c_ctx->options.image_path))
.include_paths_c_str(c_ctx->options.include_paths)
.include_paths_array(0)
.include_paths(vector<string>())
.precision(c_ctx->options.precision ? c_ctx->options.precision : 5)
);
if (c_ctx->c_functions) {
struct Sass_C_Function_Descriptor** this_func_data = c_ctx->c_functions;
while ((this_func_data) && (*this_func_data)) {
cpp_ctx.c_functions.push_back(*this_func_data);
++this_func_data;
}
}
c_ctx->output_string = cpp_ctx.compile_string();
c_ctx->source_map_string = cpp_ctx.generate_source_map();
c_ctx->error_message = 0;
c_ctx->error_status = 0;
copy_strings(cpp_ctx.get_included_files(1), &c_ctx->included_files, 1);
}
catch (Error& e) {
stringstream msg_stream;
msg_stream << e.path << ":" << e.position.line << ": " << e.message << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
catch(bad_alloc& ba) {
stringstream msg_stream;
msg_stream << "Unable to allocate memory: " << ba.what() << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
catch (std::exception& e) {
stringstream msg_stream;
msg_stream << "Error: " << e.what() << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
catch (string& e) {
stringstream msg_stream;
msg_stream << "Error: " << e << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
catch (...) {
// couldn't find the specified file in the include paths; report an error
stringstream msg_stream;
msg_stream << "Unknown error occurred" << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
return 0;
}
int sass_compile_file(sass_file_context* c_ctx)
{
using namespace Sass;
try {
string input_path = safe_str(c_ctx->input_path);
int lastindex = static_cast<int>(input_path.find_last_of("."));
string output_path;
if (!c_ctx->output_path) {
output_path = (lastindex > -1 ? input_path.substr(0, lastindex) : input_path) + ".css";
}
else {
output_path = c_ctx->output_path;
}
Context cpp_ctx(
Context::Data().entry_point(input_path)
.output_path(output_path)
.output_style((Output_Style) c_ctx->options.output_style)
.is_indented_syntax_src(c_ctx->options.is_indented_syntax_src)
.source_comments(c_ctx->options.source_comments)
.source_map_file(safe_str(c_ctx->options.source_map_file))
.source_map_embed(c_ctx->options.source_map_embed)
.source_map_contents(c_ctx->options.source_map_contents)
.omit_source_map_url(c_ctx->options.omit_source_map_url)
.image_path(safe_str(c_ctx->options.image_path))
.include_paths_c_str(c_ctx->options.include_paths)
.include_paths_array(0)
.include_paths(vector<string>())
.precision(c_ctx->options.precision ? c_ctx->options.precision : 5)
);
if (c_ctx->c_functions) {
struct Sass_C_Function_Descriptor** this_func_data = c_ctx->c_functions;
while ((this_func_data) && (*this_func_data)) {
cpp_ctx.c_functions.push_back(*this_func_data);
++this_func_data;
}
}
c_ctx->output_string = cpp_ctx.compile_file();
c_ctx->source_map_string = cpp_ctx.generate_source_map();
c_ctx->error_message = 0;
c_ctx->error_status = 0;
copy_strings(cpp_ctx.get_included_files(), &c_ctx->included_files);
}
catch (Error& e) {
stringstream msg_stream;
msg_stream << e.path << ":" << e.position.line << ": " << e.message << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
catch(bad_alloc& ba) {
stringstream msg_stream;
msg_stream << "Unable to allocate memory: " << ba.what() << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
catch (std::exception& e) {
stringstream msg_stream;
msg_stream << "Error: " << e.what() << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
catch (string& e) {
stringstream msg_stream;
msg_stream << "Error: " << e << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
catch (...) {
// couldn't find the specified file in the include paths; report an error
stringstream msg_stream;
msg_stream << "Unknown error occurred" << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
return 0;
}
int sass_compile_folder(sass_folder_context* c_ctx)
{
return 1;
}
}
<commit_msg>Fix possible segfault (init importer in old API)<commit_after>#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
#include "sass_interface.h"
#include "context.hpp"
#include "inspect.hpp"
#ifndef SASS_ERROR_HANDLING
#include "error_handling.hpp"
#endif
#include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cstring>
extern "C" {
using namespace std;
sass_context* sass_new_context()
{ return (sass_context*) calloc(1, sizeof(sass_context)); }
// helper for safe access to c_ctx
static const char* safe_str (const char* str) {
return str == NULL ? "" : str;
}
static void copy_strings(const std::vector<std::string>& strings, char*** array, int skip = 0) {
int num = static_cast<int>(strings.size());
char** arr = (char**) malloc(sizeof(char*) * (num + 1));
for(int i = skip; i < num; i++) {
arr[i-skip] = (char*) malloc(sizeof(char) * (strings[i].size() + 1));
std::copy(strings[i].begin(), strings[i].end(), arr[i-skip]);
arr[i-skip][strings[i].size()] = '\0';
}
arr[num-skip] = 0;
*array = arr;
}
static void free_string_array(char ** arr) {
if(!arr)
return;
char **it = arr;
while (it && (*it)) {
free(*it);
++it;
}
free(arr);
}
void sass_free_context(sass_context* ctx)
{
if (ctx->output_string) free(ctx->output_string);
if (ctx->source_map_string) free(ctx->source_map_string);
if (ctx->error_message) free(ctx->error_message);
if (ctx->c_functions) free(ctx->c_functions);
free_string_array(ctx->included_files);
free(ctx);
}
sass_file_context* sass_new_file_context()
{ return (sass_file_context*) calloc(1, sizeof(sass_file_context)); }
void sass_free_file_context(sass_file_context* ctx)
{
if (ctx->output_string) free(ctx->output_string);
if (ctx->source_map_string) free(ctx->source_map_string);
if (ctx->error_message) free(ctx->error_message);
if (ctx->c_functions) free(ctx->c_functions);
free_string_array(ctx->included_files);
free(ctx);
}
sass_folder_context* sass_new_folder_context()
{ return (sass_folder_context*) calloc(1, sizeof(sass_folder_context)); }
void sass_free_folder_context(sass_folder_context* ctx)
{
free_string_array(ctx->included_files);
free(ctx);
}
int sass_compile(sass_context* c_ctx)
{
using namespace Sass;
try {
string input_path = safe_str(c_ctx->input_path);
int lastindex = static_cast<int>(input_path.find_last_of("."));
string output_path;
if (!c_ctx->output_path) {
if (input_path != "") {
output_path = (lastindex > -1 ? input_path.substr(0, lastindex) : input_path) + ".css";
}
}
else {
output_path = c_ctx->output_path;
}
Context cpp_ctx(
Context::Data().source_c_str(c_ctx->source_string)
.output_path(output_path)
.output_style((Output_Style) c_ctx->options.output_style)
.is_indented_syntax_src(c_ctx->options.is_indented_syntax_src)
.source_comments(c_ctx->options.source_comments)
.source_map_file(safe_str(c_ctx->options.source_map_file))
.source_map_embed(c_ctx->options.source_map_embed)
.source_map_contents(c_ctx->options.source_map_contents)
.omit_source_map_url(c_ctx->options.omit_source_map_url)
.image_path(safe_str(c_ctx->options.image_path))
.include_paths_c_str(c_ctx->options.include_paths)
.include_paths_array(0)
.include_paths(vector<string>())
.precision(c_ctx->options.precision ? c_ctx->options.precision : 5)
.importer(0)
);
if (c_ctx->c_functions) {
struct Sass_C_Function_Descriptor** this_func_data = c_ctx->c_functions;
while ((this_func_data) && (*this_func_data)) {
cpp_ctx.c_functions.push_back(*this_func_data);
++this_func_data;
}
}
c_ctx->output_string = cpp_ctx.compile_string();
c_ctx->source_map_string = cpp_ctx.generate_source_map();
c_ctx->error_message = 0;
c_ctx->error_status = 0;
copy_strings(cpp_ctx.get_included_files(1), &c_ctx->included_files, 1);
}
catch (Error& e) {
stringstream msg_stream;
msg_stream << e.path << ":" << e.position.line << ": " << e.message << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
catch(bad_alloc& ba) {
stringstream msg_stream;
msg_stream << "Unable to allocate memory: " << ba.what() << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
catch (std::exception& e) {
stringstream msg_stream;
msg_stream << "Error: " << e.what() << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
catch (string& e) {
stringstream msg_stream;
msg_stream << "Error: " << e << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
catch (...) {
// couldn't find the specified file in the include paths; report an error
stringstream msg_stream;
msg_stream << "Unknown error occurred" << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
return 0;
}
int sass_compile_file(sass_file_context* c_ctx)
{
using namespace Sass;
try {
string input_path = safe_str(c_ctx->input_path);
int lastindex = static_cast<int>(input_path.find_last_of("."));
string output_path;
if (!c_ctx->output_path) {
output_path = (lastindex > -1 ? input_path.substr(0, lastindex) : input_path) + ".css";
}
else {
output_path = c_ctx->output_path;
}
Context cpp_ctx(
Context::Data().entry_point(input_path)
.output_path(output_path)
.output_style((Output_Style) c_ctx->options.output_style)
.is_indented_syntax_src(c_ctx->options.is_indented_syntax_src)
.source_comments(c_ctx->options.source_comments)
.source_map_file(safe_str(c_ctx->options.source_map_file))
.source_map_embed(c_ctx->options.source_map_embed)
.source_map_contents(c_ctx->options.source_map_contents)
.omit_source_map_url(c_ctx->options.omit_source_map_url)
.image_path(safe_str(c_ctx->options.image_path))
.include_paths_c_str(c_ctx->options.include_paths)
.include_paths_array(0)
.include_paths(vector<string>())
.precision(c_ctx->options.precision ? c_ctx->options.precision : 5)
);
if (c_ctx->c_functions) {
struct Sass_C_Function_Descriptor** this_func_data = c_ctx->c_functions;
while ((this_func_data) && (*this_func_data)) {
cpp_ctx.c_functions.push_back(*this_func_data);
++this_func_data;
}
}
c_ctx->output_string = cpp_ctx.compile_file();
c_ctx->source_map_string = cpp_ctx.generate_source_map();
c_ctx->error_message = 0;
c_ctx->error_status = 0;
copy_strings(cpp_ctx.get_included_files(), &c_ctx->included_files);
}
catch (Error& e) {
stringstream msg_stream;
msg_stream << e.path << ":" << e.position.line << ": " << e.message << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
catch(bad_alloc& ba) {
stringstream msg_stream;
msg_stream << "Unable to allocate memory: " << ba.what() << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
catch (std::exception& e) {
stringstream msg_stream;
msg_stream << "Error: " << e.what() << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
catch (string& e) {
stringstream msg_stream;
msg_stream << "Error: " << e << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
catch (...) {
// couldn't find the specified file in the include paths; report an error
stringstream msg_stream;
msg_stream << "Unknown error occurred" << endl;
c_ctx->error_message = strdup(msg_stream.str().c_str());
c_ctx->error_status = 1;
c_ctx->output_string = 0;
c_ctx->source_map_string = 0;
}
return 0;
}
int sass_compile_folder(sass_folder_context* c_ctx)
{
return 1;
}
}
<|endoftext|>
|
<commit_before>#include "KeyboardSettingsPage.hpp"
#include "util/LayoutCreator.hpp"
#include <QFormLayout>
#include <QLabel>
namespace chatterino {
KeyboardSettingsPage::KeyboardSettingsPage()
: SettingsPage("Keybindings", "")
{
auto layout =
LayoutCreator<KeyboardSettingsPage>(this).setLayoutType<QVBoxLayout>();
auto form = layout.emplace<QFormLayout>();
form->addRow(new QLabel("Hold Ctrl"), new QLabel("Show resize handles"));
form->addRow(new QLabel("Hold Ctrl + Alt"),
new QLabel("Show split overlay"));
form->addItem(new QSpacerItem(16, 16));
form->addRow(new QLabel("Ctrl + T"), new QLabel("Create new split"));
form->addRow(new QLabel("Ctrl + W"), new QLabel("Close current split"));
form->addRow(new QLabel("Ctrl + Shift + T"), new QLabel("Create new tab"));
form->addRow(new QLabel("Ctrl + Shift + W"),
new QLabel("Close current tab"));
form->addItem(new QSpacerItem(16, 16));
form->addRow(new QLabel("Ctrl + 1/2/3/..."),
new QLabel("Select tab 1/2/3/..."));
form->addRow(new QLabel("Ctrl + Tab"), new QLabel("Select next tab"));
form->addRow(new QLabel("Ctrl + Shift + Tab"),
new QLabel("Select previous tab"));
form->addRow(new QLabel("Alt + Left/Up/Right/Down"),
new QLabel("Select split left/up/right/down"));
form->addItem(new QSpacerItem(16, 16));
form->addRow(new QLabel("Ctrl + R"), new QLabel("Change channel"));
form->addRow(new QLabel("Ctrl + F"),
new QLabel("Search in current channel"));
form->addRow(new QLabel("Ctrl + E"), new QLabel("Open Emote menu"));
}
} // namespace chatterino
<commit_msg>added the settings shortcut to the keybindings window<commit_after>#include "KeyboardSettingsPage.hpp"
#include "util/LayoutCreator.hpp"
#include <QFormLayout>
#include <QLabel>
namespace chatterino {
KeyboardSettingsPage::KeyboardSettingsPage()
: SettingsPage("Keybindings", "")
{
auto layout =
LayoutCreator<KeyboardSettingsPage>(this).setLayoutType<QVBoxLayout>();
auto form = layout.emplace<QFormLayout>();
form->addRow(new QLabel("Hold Ctrl"), new QLabel("Show resize handles"));
form->addRow(new QLabel("Hold Ctrl + Alt"),
new QLabel("Show split overlay"));
form->addItem(new QSpacerItem(16, 16));
form->addRow(new QLabel("Ctrl + T"), new QLabel("Create new split"));
form->addRow(new QLabel("Ctrl + W"), new QLabel("Close current split"));
form->addRow(new QLabel("Ctrl + Shift + T"), new QLabel("Create new tab"));
form->addRow(new QLabel("Ctrl + Shift + W"),
new QLabel("Close current tab"));
form->addItem(new QSpacerItem(16, 16));
form->addRow(new QLabel("Ctrl + 1/2/3/..."),
new QLabel("Select tab 1/2/3/..."));
form->addRow(new QLabel("Ctrl + Tab"), new QLabel("Select next tab"));
form->addRow(new QLabel("Ctrl + Shift + Tab"),
new QLabel("Select previous tab"));
form->addRow(new QLabel("Alt + Left/Up/Right/Down"),
new QLabel("Select split left/up/right/down"));
form->addItem(new QSpacerItem(16, 16));
form->addRow(new QLabel("Ctrl + R"), new QLabel("Change channel"));
form->addRow(new QLabel("Ctrl + F"),
new QLabel("Search in current channel"));
form->addRow(new QLabel("Ctrl + E"), new QLabel("Open Emote menu"));
form->addRow(new QLabel("Ctrl + P"), new QLabel("Open Settings menu"));
}
} // namespace chatterino
<|endoftext|>
|
<commit_before>/*
* Button representing user's Avatar
*
* Copyright (C) 2011 Martin Klapetek <martin.klapetek@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "avatar-button.h"
#include <QtGui/QWidgetAction>
#include <QDataStream>
#include <KFileDialog>
#include <KMenu>
#include <KLocalizedString>
#include <KMessageBox>
#include <KImageFilePreview>
#include <TelepathyQt/Account>
#include <KDE/KDebug>
#include <KGlobalSettings>
#include <KPixmapRegionSelectorDialog>
#include <KPixmapRegionSelectorWidget>
// It has been decided by a fair dice roll that 128px is a reasonable avatar
// size limit in case the server (or Telepathy backend) does not provide
// such information
#define AVATAR_MIN_SIZE 64
#define AVATAR_MAX_SIZE 128
AvatarButton::AvatarButton(QWidget *parent)
: QToolButton(parent)
{
KMenu *menu = new KMenu(this);
setPopupMode(QToolButton::InstantPopup);
setIconSize(QSize(64,64));
menu->addAction(KIcon(QLatin1String("document-open-folder")), i18n("Load from file..."), this, SLOT(onLoadAvatarFromFile()));
menu->addAction(KIcon(QLatin1String("edit-clear")), i18n("Clear Avatar"), this, SLOT(onClearAvatar()));
setMenu(menu);
}
AvatarButton::~AvatarButton()
{
}
void AvatarButton::setAvatar(const Tp::Avatar &avatar)
{
m_avatar = avatar;
if (! avatar.avatarData.isNull()) {
KIcon avatarIcon;
QPixmap avatarPixmap = QPixmap::fromImage(QImage::fromData(avatar.avatarData));
//scale oversized avatars to fit, but don't stretch smaller avatars
avatarIcon.addPixmap(avatarPixmap.scaled(iconSize().boundedTo(avatarPixmap.size()), Qt::KeepAspectRatio));
setIcon(avatarIcon);
} else {
setIcon(KIcon(QLatin1String("im-user")));
}
}
Tp::Avatar AvatarButton::avatar() const
{
return m_avatar;
}
void AvatarButton::setAccount(const Tp::AccountPtr& account)
{
m_account = account;
}
void AvatarButton::onLoadAvatarFromFile()
{
QStringList mimeTypes;
if (m_account) {
mimeTypes = m_account->avatarRequirements().supportedMimeTypes();
}
if (mimeTypes.isEmpty()) {
mimeTypes << QLatin1String("image/jpeg")
<< QLatin1String("image/png")
<< QLatin1String("imgae/gif");
}
QPointer<KFileDialog> dialog = new KFileDialog(KUrl::fromPath(KGlobalSettings::picturesPath()),
mimeTypes.join(QLatin1String(" ")), this);
dialog->setOperationMode(KFileDialog::Opening);
dialog->setPreviewWidget(new KImageFilePreview(dialog));
dialog->setCaption(i18n("Please choose your avatar"));
KUrl fileUrl;
if (dialog->exec()) {
if (!dialog) {
return;
}
fileUrl = dialog->selectedUrl();
}
delete dialog;
if (fileUrl.isEmpty()) {
return;
}
const QPixmap pixmap(fileUrl.toLocalFile());
const Tp::AvatarSpec spec = m_account->avatarRequirements();
const int maxWidth = spec.maximumWidth() > 0 ? spec.maximumWidth() : AVATAR_MAX_SIZE;
const int maxHeight = spec.maximumHeight() > 0 ? spec.maximumHeight() : AVATAR_MAX_SIZE;
const int minWidth = spec.minimumWidth() > 0 ? spec.minimumWidth() : AVATAR_MIN_SIZE;
const int minHeight = spec.minimumHeight() > 0 ? spec.minimumHeight() : AVATAR_MIN_SIZE;
QPixmap finalPixmap;
if (pixmap.width() > spec.maximumWidth() || pixmap.height() > spec.maximumHeight()) {
finalPixmap = cropPixmap(pixmap, maxWidth, maxHeight, minWidth, minHeight);
} else {
finalPixmap = pixmap;
if (pixmap.width() < minWidth) {
finalPixmap = finalPixmap.scaledToWidth(minWidth, Qt::SmoothTransformation);
}
if (pixmap.height() < minHeight) {
finalPixmap = finalPixmap.scaledToHeight(minHeight, Qt::SmoothTransformation);
}
}
if (finalPixmap.isNull()) {
return;
}
Tp::Avatar avatar;
avatar.MIMEType = QLatin1String("image/png");
QDataStream stream(&avatar.avatarData, QIODevice::WriteOnly);
if (!finalPixmap.save(stream.device(), "PNG")) {
KMessageBox::error(this, i18n("Failed to load avatar."));
return;
}
setAvatar(avatar);
Q_EMIT avatarChanged();
}
QPixmap AvatarButton::cropPixmap(const QPixmap& pixmap, int maxWidth, int maxHeight,
int minWidth, int minHeight) const
{
QPointer<KPixmapRegionSelectorDialog> regionDlg = new KPixmapRegionSelectorDialog();
KPixmapRegionSelectorWidget *widget = regionDlg->pixmapRegionSelectorWidget();
widget->setPixmap(pixmap);
widget->setSelectionAspectRatio(maxWidth, maxHeight);
if (regionDlg->exec()) {
if (!regionDlg) {
return QPixmap();
}
delete regionDlg;
QImage selectedImage = widget->selectedImage();
if (selectedImage.width() > maxWidth || selectedImage.height() > maxHeight) {
return QPixmap::fromImage(selectedImage.scaled(maxWidth, maxHeight, Qt::KeepAspectRatio));
} else if (selectedImage.width() < minWidth || selectedImage.height() < minHeight) {
return QPixmap::fromImage(selectedImage.scaled(minWidth, minHeight, Qt::KeepAspectRatio));
} else {
return QPixmap::fromImage(widget->selectedImage());
}
}
delete regionDlg;
return QPixmap();
}
void AvatarButton::onClearAvatar()
{
setAvatar(Tp::Avatar());
Q_EMIT avatarChanged();
}
<commit_msg>Don't run dialog to select region of pixmap for empty pixmaps<commit_after>/*
* Button representing user's Avatar
*
* Copyright (C) 2011 Martin Klapetek <martin.klapetek@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "avatar-button.h"
#include <QtGui/QWidgetAction>
#include <QDataStream>
#include <KFileDialog>
#include <KMenu>
#include <KLocalizedString>
#include <KMessageBox>
#include <KImageFilePreview>
#include <TelepathyQt/Account>
#include <KDE/KDebug>
#include <KGlobalSettings>
#include <KPixmapRegionSelectorDialog>
#include <KPixmapRegionSelectorWidget>
// It has been decided by a fair dice roll that 128px is a reasonable avatar
// size limit in case the server (or Telepathy backend) does not provide
// such information
#define AVATAR_MIN_SIZE 64
#define AVATAR_MAX_SIZE 128
AvatarButton::AvatarButton(QWidget *parent)
: QToolButton(parent)
{
KMenu *menu = new KMenu(this);
setPopupMode(QToolButton::InstantPopup);
setIconSize(QSize(64,64));
menu->addAction(KIcon(QLatin1String("document-open-folder")), i18n("Load from file..."), this, SLOT(onLoadAvatarFromFile()));
menu->addAction(KIcon(QLatin1String("edit-clear")), i18n("Clear Avatar"), this, SLOT(onClearAvatar()));
setMenu(menu);
}
AvatarButton::~AvatarButton()
{
}
void AvatarButton::setAvatar(const Tp::Avatar &avatar)
{
m_avatar = avatar;
if (! avatar.avatarData.isNull()) {
KIcon avatarIcon;
QPixmap avatarPixmap = QPixmap::fromImage(QImage::fromData(avatar.avatarData));
//scale oversized avatars to fit, but don't stretch smaller avatars
avatarIcon.addPixmap(avatarPixmap.scaled(iconSize().boundedTo(avatarPixmap.size()), Qt::KeepAspectRatio));
setIcon(avatarIcon);
} else {
setIcon(KIcon(QLatin1String("im-user")));
}
}
Tp::Avatar AvatarButton::avatar() const
{
return m_avatar;
}
void AvatarButton::setAccount(const Tp::AccountPtr& account)
{
m_account = account;
}
void AvatarButton::onLoadAvatarFromFile()
{
QStringList mimeTypes;
if (m_account) {
mimeTypes = m_account->avatarRequirements().supportedMimeTypes();
}
if (mimeTypes.isEmpty()) {
mimeTypes << QLatin1String("image/jpeg")
<< QLatin1String("image/png")
<< QLatin1String("imgae/gif");
}
QPointer<KFileDialog> dialog = new KFileDialog(KUrl::fromPath(KGlobalSettings::picturesPath()),
mimeTypes.join(QLatin1String(" ")), this);
dialog->setOperationMode(KFileDialog::Opening);
dialog->setPreviewWidget(new KImageFilePreview(dialog));
dialog->setCaption(i18n("Please choose your avatar"));
KUrl fileUrl;
if (dialog->exec()) {
if (!dialog) {
return;
}
fileUrl = dialog->selectedUrl();
}
delete dialog;
if (fileUrl.isEmpty()) {
return;
}
const QPixmap pixmap(fileUrl.toLocalFile());
const Tp::AvatarSpec spec = m_account->avatarRequirements();
const int maxWidth = spec.maximumWidth() > 0 ? spec.maximumWidth() : AVATAR_MAX_SIZE;
const int maxHeight = spec.maximumHeight() > 0 ? spec.maximumHeight() : AVATAR_MAX_SIZE;
const int minWidth = spec.minimumWidth() > 0 ? spec.minimumWidth() : AVATAR_MIN_SIZE;
const int minHeight = spec.minimumHeight() > 0 ? spec.minimumHeight() : AVATAR_MIN_SIZE;
QPixmap finalPixmap;
if (pixmap.width() > spec.maximumWidth() || pixmap.height() > spec.maximumHeight()) {
finalPixmap = cropPixmap(pixmap, maxWidth, maxHeight, minWidth, minHeight);
} else {
finalPixmap = pixmap;
if (pixmap.width() < minWidth) {
finalPixmap = finalPixmap.scaledToWidth(minWidth, Qt::SmoothTransformation);
}
if (pixmap.height() < minHeight) {
finalPixmap = finalPixmap.scaledToHeight(minHeight, Qt::SmoothTransformation);
}
}
if (finalPixmap.isNull()) {
return;
}
Tp::Avatar avatar;
avatar.MIMEType = QLatin1String("image/png");
QDataStream stream(&avatar.avatarData, QIODevice::WriteOnly);
if (!finalPixmap.save(stream.device(), "PNG")) {
KMessageBox::error(this, i18n("Failed to load avatar."));
return;
}
setAvatar(avatar);
Q_EMIT avatarChanged();
}
QPixmap AvatarButton::cropPixmap(const QPixmap &pixmap, int maxWidth, int maxHeight,
int minWidth, int minHeight) const
{
//if there's no image we don't need to select a region
if (pixmap.isNull()) {
return pixmap;
}
QPointer<KPixmapRegionSelectorDialog> regionDlg = new KPixmapRegionSelectorDialog();
KPixmapRegionSelectorWidget *widget = regionDlg->pixmapRegionSelectorWidget();
widget->setPixmap(pixmap);
widget->setSelectionAspectRatio(maxWidth, maxHeight);
if (regionDlg->exec()) {
if (!regionDlg) {
return QPixmap();
}
delete regionDlg;
QImage selectedImage = widget->selectedImage();
if (selectedImage.width() > maxWidth || selectedImage.height() > maxHeight) {
return QPixmap::fromImage(selectedImage.scaled(maxWidth, maxHeight, Qt::KeepAspectRatio));
} else if (selectedImage.width() < minWidth || selectedImage.height() < minHeight) {
return QPixmap::fromImage(selectedImage.scaled(minWidth, minHeight, Qt::KeepAspectRatio));
} else {
return QPixmap::fromImage(widget->selectedImage());
}
}
delete regionDlg;
return QPixmap();
}
void AvatarButton::onClearAvatar()
{
setAvatar(Tp::Avatar());
Q_EMIT avatarChanged();
}
<|endoftext|>
|
<commit_before>/*-------------------------------------------------------------------------
*
* nested_loop_join.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /peloton/src/executor/nested_loop_join_executor.cpp
*
*-------------------------------------------------------------------------
*/
#include "backend/executor/nested_loop_join_executor.h"
#include <vector>
#include "backend/common/types.h"
#include "backend/common/logger.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"
namespace peloton {
namespace executor {
/**
* @brief Constructor for nested loop join executor.
* @param node Nested loop join node corresponding to this executor.
*/
NestedLoopJoinExecutor::NestedLoopJoinExecutor(planner::AbstractPlanNode *node,
ExecutorContext *executor_context)
: AbstractExecutor(node, executor_context) {}
/**
* @brief Do some basic checks and create the schema for the output logical
* tiles.
* @return true on success, false otherwise.
*/
bool NestedLoopJoinExecutor::DInit() {
assert(children_.size() == 2);
// Grab data from plan node.
const planner::NestedLoopJoinNode &node =
GetPlanNode<planner::NestedLoopJoinNode>();
// NOTE: predicate can be null for cartesian product
predicate_ = node.GetPredicate();
left_scan_start = true;
proj_info_ = node.GetProjInfo();
return true;
}
/**
* @brief Creates logical tiles from the two input logical tiles after applying
* join predicate.
* @return true on success, false otherwise.
*/
bool NestedLoopJoinExecutor::DExecute() {
LOG_TRACE("********** Nested Loop Join executor :: 2 children \n");
bool right_scan_end = false;
// Try to get next tile from RIGHT child
if (children_[1]->Execute() == false) {
LOG_TRACE("Did not get right tile \n");
right_scan_end = true;
}
if (right_scan_end == true) {
LOG_TRACE("Resetting scan for right tile \n");
children_[1]->Init();
if (children_[1]->Execute() == false) {
LOG_ERROR("Did not get right tile on second try\n");
return false;
}
}
LOG_TRACE("Got right tile \n");
if (left_scan_start == true || right_scan_end == true) {
left_scan_start = false;
// Try to get next tile from LEFT child
if (children_[0]->Execute() == false) {
LOG_TRACE("Did not get left tile \n");
return false;
}
LOG_TRACE("Got left tile \n");
} else {
LOG_TRACE("Already have left tile \n");
}
std::unique_ptr<LogicalTile> left_tile(children_[0]->GetOutput());
std::unique_ptr<LogicalTile> right_tile(children_[1]->GetOutput());
// Check the input logical tiles.
assert(left_tile.get() != nullptr);
assert(right_tile.get() != nullptr);
// Construct output logical tile.
std::unique_ptr<LogicalTile> output_tile(LogicalTileFactory::GetTile());
auto left_tile_schema = left_tile.get()->GetSchema();
auto right_tile_schema = right_tile.get()->GetSchema();
for (auto &col : right_tile_schema) {
col.position_list_idx += left_tile.get()->GetPositionLists().size();
}
auto output_tile_schema = BuildSchema(left_tile_schema, right_tile_schema);
// Set the output logical tile schema
output_tile.get()->SetSchema(std::move(output_tile_schema));
// Now, let's compute the position lists for the output tile
// Cartesian product
// Add everything from two logical tiles
auto left_tile_position_lists = left_tile.get()->GetPositionLists();
auto right_tile_position_lists = right_tile.get()->GetPositionLists();
// Compute output tile column count
size_t left_tile_column_count = left_tile_position_lists.size();
size_t right_tile_column_count = right_tile_position_lists.size();
size_t output_tile_column_count =
left_tile_column_count + right_tile_column_count;
assert(left_tile_column_count > 0);
assert(right_tile_column_count > 0);
// Compute output tile row count
size_t left_tile_row_count = left_tile_position_lists[0].size();
size_t right_tile_row_count = right_tile_position_lists[0].size();
// Construct position lists for output tile
std::vector<std::vector<oid_t> > position_lists;
for (size_t column_itr = 0; column_itr < output_tile_column_count;
column_itr++)
position_lists.push_back(std::vector<oid_t>());
LOG_TRACE("left col count: %lu, right col count: %lu", left_tile_column_count, right_tile_column_count);
LOG_TRACE("left col count: %lu, right col count: %lu", left_tile.get()->GetColumnCount(), right_tile.get()->GetColumnCount());
LOG_TRACE("left row count: %lu, right row count: %lu", left_tile_row_count, right_tile_row_count);
auto &direct_map_list = proj_info_->GetDirectMapList();
// Go over every pair of tuples in left and right logical tiles
for (size_t left_tile_row_itr = 0; left_tile_row_itr < left_tile_row_count;
left_tile_row_itr++) {
for (size_t right_tile_row_itr = 0;
right_tile_row_itr < right_tile_row_count; right_tile_row_itr++) {
// TODO: OPTIMIZATION : Can split the control flow into two paths -
// one for cartesian product and one for join
// Then, we can skip this branch atleast for the cartesian product path.
// Join predicate exists
if (predicate_ != nullptr) {
expression::ContainerTuple<executor::LogicalTile> left_tuple(
left_tile.get(), left_tile_row_itr);
expression::ContainerTuple<executor::LogicalTile> right_tuple(
right_tile.get(), right_tile_row_itr);
// Join predicate is false. Skip pair and continue.
if (predicate_->Evaluate(&left_tuple, &right_tuple, executor_context_)
.IsFalse()) {
continue;
}
}
// Insert a tuple into the output logical tile
for (auto &entry : direct_map_list) {
if (entry.second.first == 0) {
position_lists[entry.first].push_back(
left_tile_position_lists[entry.second.second]
[left_tile_row_itr]);
} else {
position_lists[entry.first]
.push_back(right_tile_position_lists[entry.second.second]
[right_tile_row_itr]);
}
}
// First, copy the elements in left logical tile's tuple
}
}
for (auto col : position_lists) {
LOG_TRACE("col");
for (auto elm : col) {
(void)elm; // silent compiler
LOG_TRACE("elm: %u", elm);
}
}
// Check if we have any matching tuples.
if (position_lists[0].size() > 0) {
output_tile.get()->SetPositionListsAndVisibility(std::move(position_lists));
SetOutput(output_tile.release());
return true;
}
// Try again
else {
// If we are out of any more pairs of child tiles to examine,
// then we will return false earlier in this function.
// So, we don't have to return false here.
DExecute();
}
return true;
}
std::vector<LogicalTile::ColumnInfo> NestedLoopJoinExecutor::BuildSchema(std::vector<LogicalTile::ColumnInfo> left,
std::vector<LogicalTile::ColumnInfo> right) {
assert(proj_info_->GetTargetList().size() == 0);
auto &direct_map_list = proj_info_->GetDirectMapList();
std::vector<LogicalTile::ColumnInfo> schema(direct_map_list.size());
for (auto &entry : direct_map_list) {
if (entry.second.first == 0) {
assert(entry.second.second < left.size());
schema[entry.first] = left[entry.second.second];
} else {
assert(entry.second.second < right.size());
schema[entry.first] = right[entry.second.second];
}
}
return schema;
}
} // namespace executor
} // namespace peloton
<commit_msg>projection for join is working<commit_after>/*-------------------------------------------------------------------------
*
* nested_loop_join.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /peloton/src/executor/nested_loop_join_executor.cpp
*
*-------------------------------------------------------------------------
*/
#include "backend/executor/nested_loop_join_executor.h"
#include <vector>
#include "backend/common/types.h"
#include "backend/common/logger.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"
namespace peloton {
namespace executor {
/**
* @brief Constructor for nested loop join executor.
* @param node Nested loop join node corresponding to this executor.
*/
NestedLoopJoinExecutor::NestedLoopJoinExecutor(planner::AbstractPlanNode *node,
ExecutorContext *executor_context)
: AbstractExecutor(node, executor_context) {}
/**
* @brief Do some basic checks and create the schema for the output logical
* tiles.
* @return true on success, false otherwise.
*/
bool NestedLoopJoinExecutor::DInit() {
assert(children_.size() == 2);
// Grab data from plan node.
const planner::NestedLoopJoinNode &node =
GetPlanNode<planner::NestedLoopJoinNode>();
// NOTE: predicate can be null for cartesian product
predicate_ = node.GetPredicate();
left_scan_start = true;
proj_info_ = node.GetProjInfo();
return true;
}
/**
* @brief Creates logical tiles from the two input logical tiles after applying
* join predicate.
* @return true on success, false otherwise.
*/
bool NestedLoopJoinExecutor::DExecute() {
LOG_INFO("********** Nested Loop Join executor :: 2 children \n");
bool right_scan_end = false;
// Try to get next tile from RIGHT child
if (children_[1]->Execute() == false) {
LOG_INFO("Did not get right tile \n");
right_scan_end = true;
}
if (right_scan_end == true) {
LOG_INFO("Resetting scan for right tile \n");
children_[1]->Init();
if (children_[1]->Execute() == false) {
LOG_ERROR("Did not get right tile on second try\n");
return false;
}
}
LOG_INFO("Got right tile \n");
if (left_scan_start == true || right_scan_end == true) {
left_scan_start = false;
// Try to get next tile from LEFT child
if (children_[0]->Execute() == false) {
LOG_INFO("Did not get left tile \n");
return false;
}
LOG_INFO("Got left tile \n");
} else {
LOG_INFO("Already have left tile \n");
}
std::unique_ptr<LogicalTile> left_tile(children_[0]->GetOutput());
std::unique_ptr<LogicalTile> right_tile(children_[1]->GetOutput());
// Check the input logical tiles.
assert(left_tile.get() != nullptr);
assert(right_tile.get() != nullptr);
// Construct output logical tile.
std::unique_ptr<LogicalTile> output_tile(LogicalTileFactory::GetTile());
auto left_tile_schema = left_tile.get()->GetSchema();
auto right_tile_schema = right_tile.get()->GetSchema();
for (auto &col : right_tile_schema) {
col.position_list_idx += left_tile.get()->GetPositionLists().size();
}
auto output_tile_schema = BuildSchema(left_tile_schema, right_tile_schema);
// Set the output logical tile schema
output_tile.get()->SetSchema(std::move(output_tile_schema));
// Now, let's compute the position lists for the output tile
// Cartesian product
// Add everything from two logical tiles
auto left_tile_position_lists = left_tile.get()->GetPositionLists();
auto right_tile_position_lists = right_tile.get()->GetPositionLists();
// Compute output tile column count
size_t left_tile_column_count = left_tile_position_lists.size();
size_t right_tile_column_count = right_tile_position_lists.size();
size_t output_tile_column_count =
left_tile_column_count + right_tile_column_count;
assert(left_tile_column_count > 0);
assert(right_tile_column_count > 0);
// Compute output tile row count
size_t left_tile_row_count = left_tile_position_lists[0].size();
size_t right_tile_row_count = right_tile_position_lists[0].size();
// Construct position lists for output tile
std::vector<std::vector<oid_t> > position_lists;
for (size_t column_itr = 0; column_itr < output_tile_column_count;
column_itr++)
position_lists.push_back(std::vector<oid_t>());
LOG_INFO("left col count: %lu, right col count: %lu", left_tile_column_count, right_tile_column_count);
LOG_INFO("left col count: %lu, right col count: %lu", left_tile.get()->GetColumnCount(), right_tile.get()->GetColumnCount());
LOG_INFO("left row count: %lu, right row count: %lu", left_tile_row_count, right_tile_row_count);
// Go over every pair of tuples in left and right logical tiles
for (size_t left_tile_row_itr = 0; left_tile_row_itr < left_tile_row_count;
left_tile_row_itr++) {
for (size_t right_tile_row_itr = 0;
right_tile_row_itr < right_tile_row_count; right_tile_row_itr++) {
// TODO: OPTIMIZATION : Can split the control flow into two paths -
// one for cartesian product and one for join
// Then, we can skip this branch atleast for the cartesian product path.
// Join predicate exists
if (predicate_ != nullptr) {
expression::ContainerTuple<executor::LogicalTile> left_tuple(
left_tile.get(), left_tile_row_itr);
expression::ContainerTuple<executor::LogicalTile> right_tuple(
right_tile.get(), right_tile_row_itr);
// Join predicate is false. Skip pair and continue.
if (predicate_->Evaluate(&left_tuple, &right_tuple, executor_context_)
.IsFalse()) {
continue;
}
}
// Insert a tuple into the output logical tile
// First, copy the elements in left logical tile's tuple
for (size_t output_tile_column_itr = 0;
output_tile_column_itr < left_tile_column_count;
output_tile_column_itr++) {
position_lists[output_tile_column_itr].push_back(
left_tile_position_lists[output_tile_column_itr]
[left_tile_row_itr]);
}
// Then, copy the elements in left logical tile's tuple
for (size_t output_tile_column_itr = 0;
output_tile_column_itr < right_tile_column_count;
output_tile_column_itr++) {
position_lists[left_tile_column_count + output_tile_column_itr]
.push_back(right_tile_position_lists[output_tile_column_itr]
[right_tile_row_itr]);
}
// First, copy the elements in left logical tile's tuple
}
}
for (auto col : position_lists) {
LOG_INFO("col");
for (auto elm : col) {
(void)elm; // silent compiler
LOG_INFO("elm: %u", elm);
}
}
// Check if we have any matching tuples.
if (position_lists[0].size() > 0) {
output_tile.get()->SetPositionListsAndVisibility(std::move(position_lists));
SetOutput(output_tile.release());
return true;
}
// Try again
else {
// If we are out of any more pairs of child tiles to examine,
// then we will return false earlier in this function.
// So, we don't have to return false here.
DExecute();
}
return true;
}
std::vector<LogicalTile::ColumnInfo> NestedLoopJoinExecutor::BuildSchema(std::vector<LogicalTile::ColumnInfo> left,
std::vector<LogicalTile::ColumnInfo> right) {
assert(proj_info_->GetTargetList().size() == 0);
auto &direct_map_list = proj_info_->GetDirectMapList();
std::vector<LogicalTile::ColumnInfo> schema(direct_map_list.size());
for (auto &entry : direct_map_list) {
if (entry.second.first == 0) {
assert(entry.second.second < left.size());
schema[entry.first] = left[entry.second.second];
} else {
assert(entry.second.second < right.size());
schema[entry.first] = right[entry.second.second];
}
}
return schema;
}
} // namespace executor
} // namespace peloton
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QmlEngine>
#include <QmlComponent>
#include <QPushButton>
#include <QmlContext>
#include <qmlinfo.h>
class tst_qmlinfo : public QObject
{
Q_OBJECT
public:
tst_qmlinfo() {}
private slots:
void qmlObject();
void nestedQmlObject();
void nonQmlObject();
void nullObject();
void nonQmlContextedObject();
private:
QmlEngine engine;
};
inline QUrl TEST_FILE(const QString &filename)
{
return QUrl::fromLocalFile(QLatin1String(SRCDIR) + QLatin1String("/data/") + filename);
}
void tst_qmlinfo::qmlObject()
{
QmlComponent component(&engine, TEST_FILE("qmlObject.qml"));
QObject *object = component.create();
QVERIFY(object != 0);
QString message = "QML " + QString(object->metaObject()->className()) + " (" + component.url().toString() + ":3:1) Test Message";
QTest::ignoreMessage(QtWarningMsg, qPrintable(message));
qmlInfo(object) << "Test Message";
QObject *nested = qvariant_cast<QObject *>(object->property("nested"));
QVERIFY(nested != 0);
message = "QML " + QString(nested->metaObject()->className()) + " (" + component.url().toString() + ":6:13) Second Test Message";
QTest::ignoreMessage(QtWarningMsg, qPrintable(message));
qmlInfo(nested) << "Second Test Message";
}
void tst_qmlinfo::nestedQmlObject()
{
QmlComponent component(&engine, TEST_FILE("nestedQmlObject.qml"));
QObject *object = component.create();
QVERIFY(object != 0);
QObject *nested = qvariant_cast<QObject *>(object->property("nested"));
QVERIFY(nested != 0);
QObject *nested2 = qvariant_cast<QObject *>(object->property("nested2"));
QVERIFY(nested2 != 0);
QString message = "QML " + QString(nested->metaObject()->className()) + " (" + component.url().toString() + ":5:13) Outer Object";
QTest::ignoreMessage(QtWarningMsg, qPrintable(message));
qmlInfo(nested) << "Outer Object";
message = "QML " + QString(nested2->metaObject()->className()) + " (" + TEST_FILE("NestedObject.qml").toString() + ":6:14) Inner Object";
QTest::ignoreMessage(QtWarningMsg, qPrintable(message));
qmlInfo(nested2) << "Inner Object";
}
void tst_qmlinfo::nonQmlObject()
{
QObject object;
QTest::ignoreMessage(QtWarningMsg, "QML QObject (unknown location) Test Message");
qmlInfo(&object) << "Test Message";
QPushButton pbObject;
QTest::ignoreMessage(QtWarningMsg, "QML QPushButton (unknown location) Test Message");
qmlInfo(&pbObject) << "Test Message";
}
void tst_qmlinfo::nullObject()
{
QTest::ignoreMessage(QtWarningMsg, "QML (unknown location) Null Object Test Message");
qmlInfo(0) << "Null Object Test Message";
}
void tst_qmlinfo::nonQmlContextedObject()
{
QObject object;
QmlContext context(&engine);
QmlEngine::setContextForObject(&object, &context);
QTest::ignoreMessage(QtWarningMsg, "QML QObject (unknown location) Test Message");
qmlInfo(&object) << "Test Message";
}
QTEST_MAIN(tst_qmlinfo)
#include "tst_qmlinfo.moc"
<commit_msg>qmlInfo now gives QML type, not C++ classname.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QmlEngine>
#include <QmlComponent>
#include <QPushButton>
#include <QmlContext>
#include <qmlinfo.h>
class tst_qmlinfo : public QObject
{
Q_OBJECT
public:
tst_qmlinfo() {}
private slots:
void qmlObject();
void nestedQmlObject();
void nonQmlObject();
void nullObject();
void nonQmlContextedObject();
private:
QmlEngine engine;
};
inline QUrl TEST_FILE(const QString &filename)
{
return QUrl::fromLocalFile(QLatin1String(SRCDIR) + QLatin1String("/data/") + filename);
}
void tst_qmlinfo::qmlObject()
{
QmlComponent component(&engine, TEST_FILE("qmlObject.qml"));
QObject *object = component.create();
QVERIFY(object != 0);
QString message = "QML QObject_QML_0 (" + component.url().toString() + ":3:1) Test Message";
QTest::ignoreMessage(QtWarningMsg, qPrintable(message));
qmlInfo(object) << "Test Message";
QObject *nested = qvariant_cast<QObject *>(object->property("nested"));
QVERIFY(nested != 0);
message = "QML QtObject (" + component.url().toString() + ":6:13) Second Test Message";
QTest::ignoreMessage(QtWarningMsg, qPrintable(message));
qmlInfo(nested) << "Second Test Message";
}
void tst_qmlinfo::nestedQmlObject()
{
QmlComponent component(&engine, TEST_FILE("nestedQmlObject.qml"));
QObject *object = component.create();
QVERIFY(object != 0);
QObject *nested = qvariant_cast<QObject *>(object->property("nested"));
QVERIFY(nested != 0);
QObject *nested2 = qvariant_cast<QObject *>(object->property("nested2"));
QVERIFY(nested2 != 0);
QString message = "QML NestedObject (" + component.url().toString() + ":5:13) Outer Object";
QTest::ignoreMessage(QtWarningMsg, qPrintable(message));
qmlInfo(nested) << "Outer Object";
message = "QML QtObject (" + TEST_FILE("NestedObject.qml").toString() + ":6:14) Inner Object";
QTest::ignoreMessage(QtWarningMsg, qPrintable(message));
qmlInfo(nested2) << "Inner Object";
}
void tst_qmlinfo::nonQmlObject()
{
QObject object;
QTest::ignoreMessage(QtWarningMsg, "QML QtObject (unknown location) Test Message");
qmlInfo(&object) << "Test Message";
QPushButton pbObject;
QTest::ignoreMessage(QtWarningMsg, "QML QPushButton (unknown location) Test Message");
qmlInfo(&pbObject) << "Test Message";
}
void tst_qmlinfo::nullObject()
{
QTest::ignoreMessage(QtWarningMsg, "QML (unknown location) Null Object Test Message");
qmlInfo(0) << "Null Object Test Message";
}
void tst_qmlinfo::nonQmlContextedObject()
{
QObject object;
QmlContext context(&engine);
QmlEngine::setContextForObject(&object, &context);
QTest::ignoreMessage(QtWarningMsg, "QML QtObject (unknown location) Test Message");
qmlInfo(&object) << "Test Message";
}
QTEST_MAIN(tst_qmlinfo)
#include "tst_qmlinfo.moc"
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.1 2002/02/01 22:22:25 peiyongz
* Initial revision
*
* Revision 1.4 2000/03/02 19:55:30 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.3 2000/02/17 03:36:54 rahulj
* Fixed a cut-paste typo in the comments.
*
* Revision 1.2 2000/02/06 07:48:30 rahulj
* Year 2K copyright swat.
*
* Revision 1.1.1.1 1999/11/09 01:06:30 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:32 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// SPARC runs in big endian mode
// ---------------------------------------------------------------------------
#define ENDIANMODE_BIG
typedef void* FileHandle;
#ifndef SOLARIS
#define SOLARIS
#endif
<commit_msg>Fix to #4556<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.2 2003/11/17 16:18:01 peiyongz
* Fix to #4556
*
* Revision 1.1.1.1 2002/02/01 22:22:25 peiyongz
* sane_include
*
* Revision 1.4 2000/03/02 19:55:30 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.3 2000/02/17 03:36:54 rahulj
* Fixed a cut-paste typo in the comments.
*
* Revision 1.2 2000/02/06 07:48:30 rahulj
* Year 2K copyright swat.
*
* Revision 1.1.1.1 1999/11/09 01:06:30 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:32 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// SPARC runs in big endian mode
// ---------------------------------------------------------------------------
#define ENDIANMODE_BIG
typedef int FileHandle;
#ifndef SOLARIS
#define SOLARIS
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: detfunc.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-08 17:32:10 $
*
* 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 SC_DETFUNC_HXX
#define SC_DETFUNC_HXX
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
#ifndef _GEN_HXX //autogen
#include <tools/gen.hxx>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
class SdrObject;
class SdrPage;
class String;
class ScCommentData;
class ScDetectiveData;
class ScDocument;
class ScAddress;
class ScRange;
#define SC_DET_MAXCIRCLE 1000
enum ScDetectiveDelete { SC_DET_ALL, SC_DET_DETECTIVE, SC_DET_CIRCLES, SC_DET_COMMENTS, SC_DET_ARROWS };
enum ScDetectiveObjType
{
SC_DETOBJ_NONE,
SC_DETOBJ_ARROW,
SC_DETOBJ_FROMOTHERTAB,
SC_DETOBJ_TOOTHERTAB,
SC_DETOBJ_CIRCLE
};
class ScDetectiveFunc
{
static ColorData nArrowColor;
static ColorData nErrorColor;
static ColorData nCommentColor;
static BOOL bColorsInitialized;
ScDocument* pDoc;
SCTAB nTab;
BOOL HasArrow( const ScAddress& rStart,
SCCOL nEndCol, SCROW nEndRow, SCTAB nEndTab );
void DeleteArrowsAt( SCCOL nCol, SCROW nRow, BOOL bDestPnt );
void DeleteBox( SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2 );
BOOL HasError( const ScRange& rRange, ScAddress& rErrPos );
void FillAttributes( ScDetectiveData& rData );
// called from DrawEntry/DrawAlienEntry and InsertObject
BOOL InsertArrow( SCCOL nCol, SCROW nRow,
SCCOL nRefStartCol, SCROW nRefStartRow,
SCCOL nRefEndCol, SCROW nRefEndRow,
BOOL bFromOtherTab, BOOL bRed,
ScDetectiveData& rData );
BOOL InsertToOtherTab( SCCOL nStartCol, SCROW nStartRow,
SCCOL nEndCol, SCROW nEndRow, BOOL bRed,
ScDetectiveData& rData );
// DrawEntry / DrawAlienEntry check for existing arrows and errors
BOOL DrawEntry( SCCOL nCol, SCROW nRow, const ScRange& rRef,
ScDetectiveData& rData );
BOOL DrawAlienEntry( const ScRange& rRef,
ScDetectiveData& rData );
void DrawCircle( SCCOL nCol, SCROW nRow, ScDetectiveData& rData );
SdrObject* DrawCaption( SCCOL nCol, SCROW nRow, const String& rText,
ScCommentData& rData, SdrPage* pDestPage,
BOOL bHasUserText, BOOL bLeft,
const Rectangle& rVisible );
USHORT InsertPredLevel( SCCOL nCol, SCROW nRow, ScDetectiveData& rData, USHORT nLevel );
USHORT InsertPredLevelArea( const ScRange& rRef,
ScDetectiveData& rData, USHORT nLevel );
USHORT FindPredLevel( SCCOL nCol, SCROW nRow, USHORT nLevel, USHORT nDeleteLevel );
USHORT FindPredLevelArea( const ScRange& rRef,
USHORT nLevel, USHORT nDeleteLevel );
USHORT InsertErrorLevel( SCCOL nCol, SCROW nRow, ScDetectiveData& rData, USHORT nLevel );
USHORT InsertSuccLevel( SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2,
ScDetectiveData& rData, USHORT nLevel );
USHORT FindSuccLevel( SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2,
USHORT nLevel, USHORT nDeleteLevel );
BOOL FindFrameForObject( SdrObject* pObject, ScRange& rRange );
public:
ScDetectiveFunc(ScDocument* pDocument, SCTAB nTable) : pDoc(pDocument),nTab(nTable) {}
Point GetDrawPos( SCCOL nCol, SCROW nRow, BOOL bArrow );
BOOL ShowSucc( SCCOL nCol, SCROW nRow );
BOOL ShowPred( SCCOL nCol, SCROW nRow );
BOOL ShowError( SCCOL nCol, SCROW nRow );
BOOL DeleteSucc( SCCOL nCol, SCROW nRow );
BOOL DeletePred( SCCOL nCol, SCROW nRow );
BOOL DeleteAll( ScDetectiveDelete eWhat );
BOOL MarkInvalid(BOOL& rOverflow);
SdrObject* ShowComment( SCCOL nCol, SCROW nRow, BOOL bForce, SdrPage* pDestPage = NULL );
SdrObject* ShowCommentUser( SCCOL nCol, SCROW nRow, const String& rUserText,
const Rectangle& rVisible, BOOL bLeft,
BOOL bForce, SdrPage* pDestPage );
BOOL HideComment( SCCOL nCol, SCROW nRow );
void UpdateAllComments(); // on all tables
void UpdateAllArrowColors(); // on all tables
static BOOL IsNonAlienArrow( SdrObject* pObject );
ScDetectiveObjType GetDetectiveObjectType( SdrObject* pObject,
ScAddress& rPosition, ScRange& rSource, BOOL& rRedLine );
void InsertObject( ScDetectiveObjType eType, const ScAddress& rPosition,
const ScRange& rSource, BOOL bRedLine );
static ColorData GetArrowColor();
static ColorData GetErrorColor();
static ColorData GetCommentColor();
static void InitializeColors();
static BOOL IsColorsInitialized();
};
#endif
<commit_msg>INTEGRATION: CWS dr48 (1.9.176); FILE MERGED 2006/05/10 10:36:50 nn 1.9.176.1: #i64441# don't rely on sheet information in ScDrawObjData from drawing objects<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: detfunc.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2006-07-10 13:23:03 $
*
* 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 SC_DETFUNC_HXX
#define SC_DETFUNC_HXX
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
#ifndef _GEN_HXX //autogen
#include <tools/gen.hxx>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
class SdrObject;
class SdrPage;
class String;
class ScCommentData;
class ScDetectiveData;
class ScDocument;
class ScAddress;
class ScRange;
#define SC_DET_MAXCIRCLE 1000
enum ScDetectiveDelete { SC_DET_ALL, SC_DET_DETECTIVE, SC_DET_CIRCLES, SC_DET_COMMENTS, SC_DET_ARROWS };
enum ScDetectiveObjType
{
SC_DETOBJ_NONE,
SC_DETOBJ_ARROW,
SC_DETOBJ_FROMOTHERTAB,
SC_DETOBJ_TOOTHERTAB,
SC_DETOBJ_CIRCLE
};
class ScDetectiveFunc
{
static ColorData nArrowColor;
static ColorData nErrorColor;
static ColorData nCommentColor;
static BOOL bColorsInitialized;
ScDocument* pDoc;
SCTAB nTab;
BOOL HasArrow( const ScAddress& rStart,
SCCOL nEndCol, SCROW nEndRow, SCTAB nEndTab );
void DeleteArrowsAt( SCCOL nCol, SCROW nRow, BOOL bDestPnt );
void DeleteBox( SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2 );
BOOL HasError( const ScRange& rRange, ScAddress& rErrPos );
void FillAttributes( ScDetectiveData& rData );
// called from DrawEntry/DrawAlienEntry and InsertObject
BOOL InsertArrow( SCCOL nCol, SCROW nRow,
SCCOL nRefStartCol, SCROW nRefStartRow,
SCCOL nRefEndCol, SCROW nRefEndRow,
BOOL bFromOtherTab, BOOL bRed,
ScDetectiveData& rData );
BOOL InsertToOtherTab( SCCOL nStartCol, SCROW nStartRow,
SCCOL nEndCol, SCROW nEndRow, BOOL bRed,
ScDetectiveData& rData );
// DrawEntry / DrawAlienEntry check for existing arrows and errors
BOOL DrawEntry( SCCOL nCol, SCROW nRow, const ScRange& rRef,
ScDetectiveData& rData );
BOOL DrawAlienEntry( const ScRange& rRef,
ScDetectiveData& rData );
void DrawCircle( SCCOL nCol, SCROW nRow, ScDetectiveData& rData );
SdrObject* DrawCaption( SCCOL nCol, SCROW nRow, const String& rText,
ScCommentData& rData, SdrPage* pDestPage,
BOOL bHasUserText, BOOL bLeft,
const Rectangle& rVisible );
USHORT InsertPredLevel( SCCOL nCol, SCROW nRow, ScDetectiveData& rData, USHORT nLevel );
USHORT InsertPredLevelArea( const ScRange& rRef,
ScDetectiveData& rData, USHORT nLevel );
USHORT FindPredLevel( SCCOL nCol, SCROW nRow, USHORT nLevel, USHORT nDeleteLevel );
USHORT FindPredLevelArea( const ScRange& rRef,
USHORT nLevel, USHORT nDeleteLevel );
USHORT InsertErrorLevel( SCCOL nCol, SCROW nRow, ScDetectiveData& rData, USHORT nLevel );
USHORT InsertSuccLevel( SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2,
ScDetectiveData& rData, USHORT nLevel );
USHORT FindSuccLevel( SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2,
USHORT nLevel, USHORT nDeleteLevel );
BOOL FindFrameForObject( SdrObject* pObject, ScRange& rRange );
public:
ScDetectiveFunc(ScDocument* pDocument, SCTAB nTable) : pDoc(pDocument),nTab(nTable) {}
Point GetDrawPos( SCCOL nCol, SCROW nRow, BOOL bArrow );
BOOL ShowSucc( SCCOL nCol, SCROW nRow );
BOOL ShowPred( SCCOL nCol, SCROW nRow );
BOOL ShowError( SCCOL nCol, SCROW nRow );
BOOL DeleteSucc( SCCOL nCol, SCROW nRow );
BOOL DeletePred( SCCOL nCol, SCROW nRow );
BOOL DeleteAll( ScDetectiveDelete eWhat );
BOOL MarkInvalid(BOOL& rOverflow);
SdrObject* ShowComment( SCCOL nCol, SCROW nRow, BOOL bForce, SdrPage* pDestPage = NULL );
SdrObject* ShowCommentUser( SCCOL nCol, SCROW nRow, const String& rUserText,
const Rectangle& rVisible, BOOL bLeft,
BOOL bForce, SdrPage* pDestPage );
BOOL HideComment( SCCOL nCol, SCROW nRow );
void UpdateAllComments(); // on all tables
void UpdateAllArrowColors(); // on all tables
static BOOL IsNonAlienArrow( SdrObject* pObject );
ScDetectiveObjType GetDetectiveObjectType( SdrObject* pObject, SCTAB nObjTab,
ScAddress& rPosition, ScRange& rSource, BOOL& rRedLine );
void InsertObject( ScDetectiveObjType eType, const ScAddress& rPosition,
const ScRange& rSource, BOOL bRedLine );
static ColorData GetArrowColor();
static ColorData GetErrorColor();
static ColorData GetCommentColor();
static void InitializeColors();
static BOOL IsColorsInitialized();
};
#endif
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.