text
stringlengths 54
60.6k
|
---|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkVoronoi2DDiagramTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2001 Insight Consortium
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* The name of the Insight Consortium, nor the names of any consortium members,
nor of any contributors, may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS 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 "itkVoronoi2DDiagram.h"
#include <stdio.h>
const double HEI=400;
const double WID=400;
const int NUMSEEDS=20;
int main(void){
typedef itk::Voronoi2DDiagram<double> Vor;
typedef Vor::PointType PointType;
typedef Vor::Cell Cell;
typedef Vor::CellPointer CellPointer;
typedef Cell::PointIdIterator PointIdIterator;
typedef Vor::NeighborIdIterator NeighborIdIterator;
Vor::Pointer testVor(Vor::New());
PointType insize;
insize[0]=WID;
insize[1]=HEI;
testVor->SetBoundary(insize);
testVor->SetRandomSeeds(NUMSEEDS);
testVor->GenerateDiagram();
for(int i=0;i<NUMSEEDS; i++){
PointType currP=testVor->getSeed(i);
std::cout<<"Seed No."<<i<<": At ("<<currP[0]<<"," <<currP[1]<<")"<<std::endl;
std::cout<<" Boundary Vertices List (in order):";
CellPointer currCell;
currCell=testVor->GetCellId(i);
PointIdIterator currCellP;
for(currCellP=currCell->PointIdsBegin();currCellP!=currCell->PointIdsEnd();++currCellP)
{
std::cout<<(*currCellP)<<",";
}
std::cout<<std::endl;
std::cout<<" Neighbors (Seed No.):";
NeighborIdIterator currNeibor;
for(currNeibor=testVor->NeighborIdsBegin(i);currNeibor!=testVor->NeighborIdsEnd(i);++currNeibor)
{
std::cout<<(*currNeibor)<<",";
}
std::cout<<std::endl<<std::endl;
}
std::cout<<"Vertices Informations:"<<std::endl;
Vor::VertexIterator allVerts;
int j = 0;
for(allVerts=testVor->VertexBegin();allVerts!=testVor->VertexEnd();++allVerts)
{
std::cout<<"Vertices No."<<j;
j++;
std::cout<<": At ("<<(*allVerts)[0]<<","<<(*allVerts)[1]<<")"<<std::endl;
}
return 0;
}
<commit_msg>rename<commit_after><|endoftext|> |
<commit_before>#include "bilibilicrawler.h"
#include "ui_bilibilicrawler.h"
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QRegExp>
#include <QDebug>
//#include <QStringList>
bilibiliCrawler::bilibiliCrawler(QWidget *parent) :
QWidget(parent),
ui(new Ui::bilibiliCrawler)
{
ui->setupUi(this);
content = new QString();
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(getID(QNetworkReply*)));
// connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(query(QNetworkReply*)));
}
bilibiliCrawler::~bilibiliCrawler()
{
delete ui;
}
void bilibiliCrawler::getID(QNetworkReply *reply) {
// ui->textBrowser->setText("get");
QString buffer = reply->readAll();
int pos;
// qDebug() << mode;
// qDebug() << clickInfo;
// QRegExp exp("cid=[0-9]+\\&aid=[0-9]+");
// int pos = exp.indexIn(buffer);
// QStringList list = exp.capturedTexts();
// qDebug() << list.at(0);
// ui->textBrowser->setText(list.at(0));
// clickInfo = interface.append(list.at(0));
qDebug() << clickInfo;
if (mode == HTMLPAGE) {
QRegExp exp("cid=[0-9]+\\&aid=[0-9]+");
pos = exp.indexIn(buffer);
QStringList list = exp.capturedTexts();
qDebug() << list.at(0);
// ui->textBrowser->setText(list.at(0));
content->append(list.at(0)+"\n");
clickInfo = interface.append(list.at(0));
//get cid
exp.setPattern("cid=[0-9]+");
pos = exp.indexIn(buffer);
list = exp.capturedTexts();
qDebug() << list.at(0);
cid = list.at(0);
qDebug() << "cid="<< cid;
// get aid
exp.setPattern("aid=[0-9]+");
pos = exp.indexIn(buffer);
list = exp.capturedTexts();
qDebug() << list.at(0);
aid = list.at(0).mid(1);
qDebug() << "aid="<< aid;
QNetworkRequest *req = new QNetworkRequest(QUrl(clickInfo));
req->setRawHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");
req->setAttribute(QNetworkRequest::FollowRedirectsAttribute, QVariant(true));
manager->get(*req);
mode = INFOPAGE;
} else {
QRegExp exp("<click>[0-9]+");
pos = exp.indexIn(buffer);
QStringList list = exp.capturedTexts();
qDebug() << list.at(0).mid(QString("<click>").size());
content->append("click: "+list.at(0).mid(QString("<click>").size())+"\n");
exp.setPattern("<coins>[0-9]+");
pos = exp.indexIn(buffer);
list = exp.capturedTexts();
qDebug() << list.at(0).mid(QString("<coins>").size());
content->append("coins: "+list.at(0).mid(QString("<coins>").size())+"\n");
exp.setPattern("<favourites>[0-9]+");
pos = exp.indexIn(buffer);
list = exp.capturedTexts();
qDebug() << list.at(0).mid(QString("<favourites>").size());
content->append("favourites: "+list.at(0).mid(QString("<favourites>").size())+"\n");
QStringList parms;
QString ts = "ts="+QString::number(QDateTime::currentMSecsSinceEpoch()/1000);
parms << "accel=1" << cid << "player=1" << ts;
// parms.pop_front();
getSign(parms, appkey);
mode = HTMLPAGE;
}
ui->textBrowser->setText(*content);
// else if (mode == INFOPAGE) {
// qDebug() << (mode == INFOPAGE);
// QRegExp exp("<click>[0-9]+");
// ui->textBrowser->setText(buffer);
// }
// buffer.append(list.at(0));
// QNetworkRequest *req = new QNetworkRequest(QUrl(clickInfo));
// req->setRawHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");
// req->setAttribute(QNetworkRequest::FollowRedirectsAttribute, QVariant(true));
// manager->get(*req);
}
void bilibiliCrawler::getInfo(QNetworkReply *reply) {
QString buffer = reply->readAll();
ui->textBrowser->setText(buffer);
}
void bilibiliCrawler::getSign(QStringList arg, QString appkey) {
qStableSort(arg);
qDebug() << arg;
QString par = QString();
QString playurl = "http://interface.bilibili.com/playurl?";
for(int i = 0; i < arg.size(); i++) {
par.append(/*QString::number(i)+"="+*/QUrl::toPercentEncoding(arg.at(i), "", "=")+(i < arg.size()-1 ?"&":""));
// QUrl::toPercentEncoding(arg.at(i), "", "=");
playurl.append(arg.at(i)+(i < arg.size()-1 ?"&":""));
}
// QUrl url(par);
QByteArray str;
str.append(par+appkey);
QString sign = QString(QCryptographicHash::hash(str, QCryptographicHash::Md5).toHex());
qDebug() << par;
qDebug() << sign;
playurl.append("&sign="+sign);
content->append(sign + "\n");
// qDebug() << QCryptographicHash::hash(str, QCryptographicHash::Md5).toHex();
// qDebug() << QUrl::toPercentEncoding(par, "", "=");
QDateTime local(QDateTime::currentDateTime());
QDateTime UTC(local.toUTC());
qDebug() << "Local time is:" << local;
qDebug() << "UTC time is:" << UTC;
qDebug() << "No difference between times:" << local.secsTo(UTC);
qDebug() << QDateTime::currentMSecsSinceEpoch()/1000;
content->append(playurl);
// QString playurl = "http://interface.bilibili.com/playurl?";
}
void bilibiliCrawler::on_goButton_clicked() {
QString input = ui->lineEdit->text();
QString baseurl = "http://www.bilibili.com/video/";
baseurl.append(input);
// ui->textBrowser->setPlainText(baseurl);
content->append(baseurl+"\n");
// manager->get(QNetworkRequest(QUrl(baseurl)));
QNetworkRequest *req = new QNetworkRequest(QUrl(baseurl));
req->setRawHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");
// ui->textBrowser->setPlainText(*req->KnownHeaders);
req->setAttribute(QNetworkRequest::FollowRedirectsAttribute, QVariant(true));
qDebug() << baseurl;
qDebug() << req->rawHeaderList();
qDebug() << mode;
mode = HTMLPAGE;
manager->get(*req);
qDebug() << clickInfo;
// if (mode == HTMLPAGE) {
// manager->get(*req);
// // mode = INFOPAGE;
// } else if (mode == INFOPAGE) {
// qDebug() << clickInfo;
// }
}
<commit_msg>get download url<commit_after>#include "bilibilicrawler.h"
#include "ui_bilibilicrawler.h"
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QRegExp>
#include <QDebug>
//#include <QStringList>
bilibiliCrawler::bilibiliCrawler(QWidget *parent) :
QWidget(parent),
ui(new Ui::bilibiliCrawler)
{
ui->setupUi(this);
content = new QString();
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(getID(QNetworkReply*)));
// connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(query(QNetworkReply*)));
}
bilibiliCrawler::~bilibiliCrawler()
{
delete ui;
}
void bilibiliCrawler::getID(QNetworkReply *reply) {
// ui->textBrowser->setText("get");
QString buffer = reply->readAll();
int pos;
// qDebug() << mode;
// qDebug() << clickInfo;
// QRegExp exp("cid=[0-9]+\\&aid=[0-9]+");
// int pos = exp.indexIn(buffer);
// QStringList list = exp.capturedTexts();
// qDebug() << list.at(0);
// ui->textBrowser->setText(list.at(0));
// clickInfo = interface.append(list.at(0));
qDebug() << clickInfo;
if (mode == HTMLPAGE) {
QRegExp exp("cid=[0-9]+\\&aid=[0-9]+");
pos = exp.indexIn(buffer);
QStringList list = exp.capturedTexts();
qDebug() << list.at(0);
// ui->textBrowser->setText(list.at(0));
content->append(list.at(0)+"\n");
clickInfo = interface.append(list.at(0));
//get cid
exp.setPattern("cid=[0-9]+");
pos = exp.indexIn(buffer);
list = exp.capturedTexts();
qDebug() << list.at(0);
cid = list.at(0);
qDebug() << "cid="<< cid;
// get aid
exp.setPattern("aid=[0-9]+");
pos = exp.indexIn(buffer);
list = exp.capturedTexts();
qDebug() << list.at(0);
aid = list.at(0).mid(1);
qDebug() << "aid="<< aid;
QNetworkRequest *req = new QNetworkRequest(QUrl(clickInfo));
req->setRawHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");
req->setAttribute(QNetworkRequest::FollowRedirectsAttribute, QVariant(true));
manager->get(*req);
mode = INFOPAGE;
} else if (mode == INFOPAGE) {
QRegExp exp("<click>[0-9]+");
pos = exp.indexIn(buffer);
QStringList list = exp.capturedTexts();
qDebug() << list.at(0).mid(QString("<click>").size());
content->append("click: "+list.at(0).mid(QString("<click>").size())+"\n");
exp.setPattern("<coins>[0-9]+");
pos = exp.indexIn(buffer);
list = exp.capturedTexts();
qDebug() << list.at(0).mid(QString("<coins>").size());
content->append("coins: "+list.at(0).mid(QString("<coins>").size())+"\n");
exp.setPattern("<favourites>[0-9]+");
pos = exp.indexIn(buffer);
list = exp.capturedTexts();
qDebug() << list.at(0).mid(QString("<favourites>").size());
content->append("favourites: "+list.at(0).mid(QString("<favourites>").size())+"\n");
QStringList parms;
QString ts = "ts="+QString::number(QDateTime::currentMSecsSinceEpoch()/1000);
parms << "accel=1" << cid << "player=1" << ts;
// parms.pop_front();
getSign(parms, appkey);
QNetworkRequest *req = new QNetworkRequest(QUrl(download));
req->setRawHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");
req->setAttribute(QNetworkRequest::FollowRedirectsAttribute, QVariant(true));
manager->get(*req);
mode = DOWNLOADPAGE;
} else {
qDebug() << "end";
qDebug() << buffer;
}
ui->textBrowser->setText(*content);
// else if (mode == INFOPAGE) {
// qDebug() << (mode == INFOPAGE);
// QRegExp exp("<click>[0-9]+");
// ui->textBrowser->setText(buffer);
// }
// buffer.append(list.at(0));
// QNetworkRequest *req = new QNetworkRequest(QUrl(clickInfo));
// req->setRawHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");
// req->setAttribute(QNetworkRequest::FollowRedirectsAttribute, QVariant(true));
// manager->get(*req);
}
void bilibiliCrawler::getInfo(QNetworkReply *reply) {
QString buffer = reply->readAll();
ui->textBrowser->setText(buffer);
}
void bilibiliCrawler::getSign(QStringList arg, QString appkey) {
qStableSort(arg);
qDebug() << arg;
QString par = QString();
QString playurl = "http://interface.bilibili.com/playurl?";
for(int i = 0; i < arg.size(); i++) {
par.append(/*QString::number(i)+"="+*/QUrl::toPercentEncoding(arg.at(i), "", "=")+(i < arg.size()-1 ?"&":""));
// QUrl::toPercentEncoding(arg.at(i), "", "=");
playurl.append(arg.at(i)+(i < arg.size()-1 ?"&":""));
}
// QUrl url(par);
QByteArray str;
str.append(par+appkey);
QString sign = QString(QCryptographicHash::hash(str, QCryptographicHash::Md5).toHex());
qDebug() << par;
qDebug() << sign;
playurl.append("&sign="+sign);
download = "http://interface.bilibili.com/playurl?platform=android&otype=json&appkey=86385cdc024c0f6c&"+cid+"&quality=3&type=flv";
content->append(sign + "\n");
// qDebug() << QCryptographicHash::hash(str, QCryptographicHash::Md5).toHex();
// qDebug() << QUrl::toPercentEncoding(par, "", "=");
QDateTime local(QDateTime::currentDateTime());
QDateTime UTC(local.toUTC());
qDebug() << "Local time is:" << local;
qDebug() << "UTC time is:" << UTC;
qDebug() << "No difference between times:" << local.secsTo(UTC);
qDebug() << QDateTime::currentMSecsSinceEpoch()/1000;
content->append(playurl+"\n");
content->append(download);
// QString playurl = "http://interface.bilibili.com/playurl?";
}
void bilibiliCrawler::on_goButton_clicked() {
QString input = ui->lineEdit->text();
QString baseurl = "http://www.bilibili.com/video/";
baseurl.append(input);
// ui->textBrowser->setPlainText(baseurl);
content->append(baseurl+"\n");
// manager->get(QNetworkRequest(QUrl(baseurl)));
QNetworkRequest *req = new QNetworkRequest(QUrl(baseurl));
req->setRawHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");
// ui->textBrowser->setPlainText(*req->KnownHeaders);
req->setAttribute(QNetworkRequest::FollowRedirectsAttribute, QVariant(true));
qDebug() << baseurl;
qDebug() << req->rawHeaderList();
qDebug() << mode;
mode = HTMLPAGE;
manager->get(*req);
qDebug() << clickInfo;
// if (mode == HTMLPAGE) {
// manager->get(*req);
// // mode = INFOPAGE;
// } else if (mode == INFOPAGE) {
// qDebug() << clickInfo;
// }
}
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of mcompositor.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#ifdef DESKTOP_VERSION
#define GL_GLEXT_PROTOTYPES 1
#endif
#include "mtexturepixmapitem.h"
#include "texturepixmapshaders.h"
#include <QX11Info>
#include <QRect>
#include <X11/Xlib.h>
#include <X11/extensions/Xcomposite.h>
#include <X11/extensions/Xrender.h>
#ifdef GLES2_VERSION
#include <GLES2/gl2.h>
#elif DESKTOP_VERSION
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glx.h>
#include <GL/glxext.h>
#endif
#include "mtexturepixmapitem_p.h"
bool MTexturePixmapPrivate::inverted_texture = true;
MGLResourceManager *MTexturePixmapPrivate::glresource = 0;
static const GLuint D_VERTEX_COORDS = 0;
static const GLuint D_TEXTURE_COORDS = 1;
#ifdef QT_OPENGL_LIB
static void bindAttribLocation(QGLShaderProgram *p, const char *attrib, int location)
{
p->bindAttributeLocation(attrib, location);
}
// OpenGL ES 2.0 / OpenGL 2.0 - compatible texture painter
class MGLResourceManager: public QObject
{
public:
/* add more values here as we add more effects */
enum ShaderType {
NormalShader = 0,
BlurShader,
ShaderTotal
};
MGLResourceManager(QGLWidget *glwidget)
: QObject(glwidget),
currentShader(0) {
QGLShader *sharedVertexShader = new QGLShader(QGLShader::Vertex,
glwidget->context(), this);
if (!sharedVertexShader->compileSourceCode(QLatin1String(TexpVertShaderSource)))
qWarning("vertex shader failed to compile");
QGLShaderProgram *normalShader = new QGLShaderProgram(glwidget->context(), this);
shader[NormalShader] = normalShader;
normalShader->addShader(sharedVertexShader);
if (!normalShader->addShaderFromSourceCode(QGLShader::Fragment,
QLatin1String(TexpFragShaderSource)))
qWarning("normal fragment shader failed to compile");
QGLShaderProgram *blurShader = new QGLShaderProgram(glwidget->context(), this);
shader[BlurShader] = blurShader;
blurShader->addShader(sharedVertexShader);
if (!blurShader->addShaderFromSourceCode(QGLShader::Fragment,
QLatin1String(blurshader)))
qWarning("blur fragment shader failed to compile");
bindAttribLocation(normalShader, "inputVertex", D_VERTEX_COORDS);
bindAttribLocation(normalShader, "textureCoord", D_TEXTURE_COORDS);
bindAttribLocation(blurShader, "inputVertex", D_VERTEX_COORDS);
bindAttribLocation(blurShader, "textureCoord", D_TEXTURE_COORDS);
normalShader->link();
blurShader->link();
}
void initVertices(QGLWidget *glwidget) {
texCoords[0] = 0.0f; texCoords[1] = 1.0f;
texCoords[2] = 0.0f; texCoords[3] = 0.0f;
texCoords[4] = 1.0f; texCoords[5] = 0.0f;
texCoords[6] = 1.0f; texCoords[7] = 1.0f;
texCoordsInv[0] = 0.0f; texCoordsInv[1] = 0.0f;
texCoordsInv[2] = 0.0f; texCoordsInv[3] = 1.0f;
texCoordsInv[4] = 1.0f; texCoordsInv[5] = 1.0f;
texCoordsInv[6] = 1.0f; texCoordsInv[7] = 0.0f;
projMatrix[0][0] = 2.0 / glwidget->width(); projMatrix[1][0] = 0.0;
projMatrix[2][0] = 0.0; projMatrix[3][0] = -1.0;
projMatrix[0][1] = 0.0; projMatrix[1][1] = -2.0 / glwidget->height();
projMatrix[2][1] = 0.0; projMatrix[3][1] = 1.0;
projMatrix[0][2] = 0.0; projMatrix[1][2] = 0.0;
projMatrix[2][2] = -1.0; projMatrix[3][2] = 0.0;
projMatrix[0][3] = 0.0; projMatrix[1][3] = 0.0;
projMatrix[2][3] = 0.0; projMatrix[3][3] = 1.0;
worldMatrix[0][2] = 0.0;
worldMatrix[1][2] = 0.0;
worldMatrix[2][0] = 0.0;
worldMatrix[2][1] = 0.0;
worldMatrix[2][2] = 1.0;
worldMatrix[2][3] = 0.0;
worldMatrix[3][2] = 0.0;
width = glwidget->width();
height = glwidget->height();
glViewport(0, 0, width, height);
for (int i = 0; i < ShaderTotal; i++) {
shader[i]->bind();
shader[i]->setUniformValue("matProj", projMatrix);
}
}
void updateVertices(const QTransform &t, ShaderType type) {
if (shader[type] != currentShader)
currentShader = shader[type];
worldMatrix[0][0] = t.m11();
worldMatrix[0][1] = t.m12();
worldMatrix[0][3] = t.m13();
worldMatrix[1][0] = t.m21();
worldMatrix[1][1] = t.m22();
worldMatrix[1][3] = t.m23();
worldMatrix[3][0] = t.dx();
worldMatrix[3][1] = t.dy();
worldMatrix[3][3] = t.m33();
currentShader->bind();
currentShader->setUniformValue("matWorld", worldMatrix);
}
private:
static QGLShaderProgram *shader[ShaderTotal];
GLfloat projMatrix[4][4];
GLfloat worldMatrix[4][4];
GLfloat vertCoords[8];
GLfloat texCoords[8];
GLfloat texCoordsInv[8];
QGLShaderProgram *currentShader;
int width;
int height;
friend class MTexturePixmapPrivate;
};
QGLShaderProgram *MGLResourceManager::shader[ShaderTotal];
#endif
void MTexturePixmapPrivate::drawTexture(const QTransform &transform, const QRectF &drawRect, qreal opacity)
{
glwidget->makeCurrent();
// TODO only update if matrix is dirty
glresource->updateVertices(transform, item->blurred() ?
MGLResourceManager::BlurShader :
MGLResourceManager::NormalShader);
GLfloat vertexCoords[] = {
drawRect.left(), drawRect.top(),
drawRect.left(), drawRect.bottom(),
drawRect.right(), drawRect.bottom(),
drawRect.right(), drawRect.top()
};
glEnableVertexAttribArray(D_VERTEX_COORDS);
glEnableVertexAttribArray(D_TEXTURE_COORDS);
glVertexAttribPointer(D_VERTEX_COORDS, 2, GL_FLOAT, GL_FALSE, 0, vertexCoords);
if (inverted_texture)
glVertexAttribPointer(D_TEXTURE_COORDS, 2, GL_FLOAT, GL_FALSE, 0,
glresource->texCoordsInv);
else
glVertexAttribPointer(D_TEXTURE_COORDS, 2, GL_FLOAT, GL_FALSE, 0,
glresource->texCoords);
if (item->blurred())
glresource->currentShader->setUniformValue("blurstep", (GLfloat) 0.5);
glresource->currentShader->setUniformValue("opacity", (GLfloat) opacity);
glresource->currentShader->setUniformValue("texture", 0);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glDisableVertexAttribArray(D_VERTEX_COORDS);
glDisableVertexAttribArray(D_TEXTURE_COORDS);
glwidget->paintEngine()->syncState();
glActiveTexture(GL_TEXTURE0);
}
void MTexturePixmapPrivate::init()
{
if (!item->is_valid)
return;
if (!glresource) {
glresource = new MGLResourceManager(glwidget);
glresource->initVertices(glwidget);
}
XRenderPictFormat *format = XRenderFindVisualFormat(QX11Info::display(),
item->windowAttributes()->visual);
has_alpha = (format && format->type == PictTypeDirect && format->direct.alphaMask);
resize(item->windowAttributes()->width, item->windowAttributes()->height);
item->setPos(item->windowAttributes()->x, item->windowAttributes()->y);
}
MTexturePixmapPrivate::MTexturePixmapPrivate(Qt::HANDLE window, QGLWidget *w, MTexturePixmapItem *p)
: ctx(0),
glwidget(w),
window(window),
windowp(0),
#ifdef DESKTOP_VERSION
glpixmap(0),
#endif
textureId(0),
ctextureId(0),
custom_tfp(false),
has_alpha(false),
direct_fb_render(false),
angle(0),
item(p)
{
damageTracking(true);
init();
}
MTexturePixmapPrivate::~MTexturePixmapPrivate()
{
damageTracking(false);
}
void MTexturePixmapPrivate::damageTracking(bool enabled)
{
if (damage_object) {
XDamageDestroy(QX11Info::display(), damage_object);
damage_object = NULL;
}
if (enabled && !damage_object)
damage_object = XDamageCreate(QX11Info::display(), window,
XDamageReportNonEmpty);
}
void MTexturePixmapPrivate::saveBackingStore(bool renew)
{
XWindowAttributes a;
if (!XGetWindowAttributes(QX11Info::display(), item->window(), &a)) {
qWarning("%s: invalid window 0x%lx", __func__, item->window());
return;
}
if (a.map_state != IsViewable)
return;
if (windowp)
XFreePixmap(QX11Info::display(), windowp);
Pixmap px = XCompositeNameWindowPixmap(QX11Info::display(), item->window());
windowp = px;
if (renew)
item->rebindPixmap();
}
void MTexturePixmapPrivate::windowRaised()
{
XRaiseWindow(QX11Info::display(), item->window());
}
void MTexturePixmapPrivate::resize(int w, int h)
{
if (!brect.isEmpty() && !item->isDirectRendered() && (brect.width() != w || brect.height() != h)) {
item->saveBackingStore(true);
item->updateWindowPixmap();
}
brect.setWidth(w);
brect.setHeight(h);
}
bool MTexturePixmapPrivate::hasAlpha() const
{
return has_alpha;
}
void MTexturePixmapPrivate::setValid(bool valid)
{
item->is_valid = valid;
}
<commit_msg>mtexturepixmapitem: no need to make glwidget current<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of mcompositor.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#ifdef DESKTOP_VERSION
#define GL_GLEXT_PROTOTYPES 1
#endif
#include "mtexturepixmapitem.h"
#include "texturepixmapshaders.h"
#include <QX11Info>
#include <QRect>
#include <X11/Xlib.h>
#include <X11/extensions/Xcomposite.h>
#include <X11/extensions/Xrender.h>
#ifdef GLES2_VERSION
#include <GLES2/gl2.h>
#elif DESKTOP_VERSION
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glx.h>
#include <GL/glxext.h>
#endif
#include "mtexturepixmapitem_p.h"
bool MTexturePixmapPrivate::inverted_texture = true;
MGLResourceManager *MTexturePixmapPrivate::glresource = 0;
static const GLuint D_VERTEX_COORDS = 0;
static const GLuint D_TEXTURE_COORDS = 1;
#ifdef QT_OPENGL_LIB
static void bindAttribLocation(QGLShaderProgram *p, const char *attrib, int location)
{
p->bindAttributeLocation(attrib, location);
}
// OpenGL ES 2.0 / OpenGL 2.0 - compatible texture painter
class MGLResourceManager: public QObject
{
public:
/* add more values here as we add more effects */
enum ShaderType {
NormalShader = 0,
BlurShader,
ShaderTotal
};
MGLResourceManager(QGLWidget *glwidget)
: QObject(glwidget),
currentShader(0) {
QGLShader *sharedVertexShader = new QGLShader(QGLShader::Vertex,
glwidget->context(), this);
if (!sharedVertexShader->compileSourceCode(QLatin1String(TexpVertShaderSource)))
qWarning("vertex shader failed to compile");
QGLShaderProgram *normalShader = new QGLShaderProgram(glwidget->context(), this);
shader[NormalShader] = normalShader;
normalShader->addShader(sharedVertexShader);
if (!normalShader->addShaderFromSourceCode(QGLShader::Fragment,
QLatin1String(TexpFragShaderSource)))
qWarning("normal fragment shader failed to compile");
QGLShaderProgram *blurShader = new QGLShaderProgram(glwidget->context(), this);
shader[BlurShader] = blurShader;
blurShader->addShader(sharedVertexShader);
if (!blurShader->addShaderFromSourceCode(QGLShader::Fragment,
QLatin1String(blurshader)))
qWarning("blur fragment shader failed to compile");
bindAttribLocation(normalShader, "inputVertex", D_VERTEX_COORDS);
bindAttribLocation(normalShader, "textureCoord", D_TEXTURE_COORDS);
bindAttribLocation(blurShader, "inputVertex", D_VERTEX_COORDS);
bindAttribLocation(blurShader, "textureCoord", D_TEXTURE_COORDS);
normalShader->link();
blurShader->link();
}
void initVertices(QGLWidget *glwidget) {
texCoords[0] = 0.0f; texCoords[1] = 1.0f;
texCoords[2] = 0.0f; texCoords[3] = 0.0f;
texCoords[4] = 1.0f; texCoords[5] = 0.0f;
texCoords[6] = 1.0f; texCoords[7] = 1.0f;
texCoordsInv[0] = 0.0f; texCoordsInv[1] = 0.0f;
texCoordsInv[2] = 0.0f; texCoordsInv[3] = 1.0f;
texCoordsInv[4] = 1.0f; texCoordsInv[5] = 1.0f;
texCoordsInv[6] = 1.0f; texCoordsInv[7] = 0.0f;
projMatrix[0][0] = 2.0 / glwidget->width(); projMatrix[1][0] = 0.0;
projMatrix[2][0] = 0.0; projMatrix[3][0] = -1.0;
projMatrix[0][1] = 0.0; projMatrix[1][1] = -2.0 / glwidget->height();
projMatrix[2][1] = 0.0; projMatrix[3][1] = 1.0;
projMatrix[0][2] = 0.0; projMatrix[1][2] = 0.0;
projMatrix[2][2] = -1.0; projMatrix[3][2] = 0.0;
projMatrix[0][3] = 0.0; projMatrix[1][3] = 0.0;
projMatrix[2][3] = 0.0; projMatrix[3][3] = 1.0;
worldMatrix[0][2] = 0.0;
worldMatrix[1][2] = 0.0;
worldMatrix[2][0] = 0.0;
worldMatrix[2][1] = 0.0;
worldMatrix[2][2] = 1.0;
worldMatrix[2][3] = 0.0;
worldMatrix[3][2] = 0.0;
width = glwidget->width();
height = glwidget->height();
glViewport(0, 0, width, height);
for (int i = 0; i < ShaderTotal; i++) {
shader[i]->bind();
shader[i]->setUniformValue("matProj", projMatrix);
}
}
void updateVertices(const QTransform &t, ShaderType type) {
if (shader[type] != currentShader)
currentShader = shader[type];
worldMatrix[0][0] = t.m11();
worldMatrix[0][1] = t.m12();
worldMatrix[0][3] = t.m13();
worldMatrix[1][0] = t.m21();
worldMatrix[1][1] = t.m22();
worldMatrix[1][3] = t.m23();
worldMatrix[3][0] = t.dx();
worldMatrix[3][1] = t.dy();
worldMatrix[3][3] = t.m33();
currentShader->bind();
currentShader->setUniformValue("matWorld", worldMatrix);
}
private:
static QGLShaderProgram *shader[ShaderTotal];
GLfloat projMatrix[4][4];
GLfloat worldMatrix[4][4];
GLfloat vertCoords[8];
GLfloat texCoords[8];
GLfloat texCoordsInv[8];
QGLShaderProgram *currentShader;
int width;
int height;
friend class MTexturePixmapPrivate;
};
QGLShaderProgram *MGLResourceManager::shader[ShaderTotal];
#endif
void MTexturePixmapPrivate::drawTexture(const QTransform &transform, const QRectF &drawRect, qreal opacity)
{
// TODO only update if matrix is dirty
glresource->updateVertices(transform, item->blurred() ?
MGLResourceManager::BlurShader :
MGLResourceManager::NormalShader);
GLfloat vertexCoords[] = {
drawRect.left(), drawRect.top(),
drawRect.left(), drawRect.bottom(),
drawRect.right(), drawRect.bottom(),
drawRect.right(), drawRect.top()
};
glEnableVertexAttribArray(D_VERTEX_COORDS);
glEnableVertexAttribArray(D_TEXTURE_COORDS);
glVertexAttribPointer(D_VERTEX_COORDS, 2, GL_FLOAT, GL_FALSE, 0, vertexCoords);
if (inverted_texture)
glVertexAttribPointer(D_TEXTURE_COORDS, 2, GL_FLOAT, GL_FALSE, 0,
glresource->texCoordsInv);
else
glVertexAttribPointer(D_TEXTURE_COORDS, 2, GL_FLOAT, GL_FALSE, 0,
glresource->texCoords);
if (item->blurred())
glresource->currentShader->setUniformValue("blurstep", (GLfloat) 0.5);
glresource->currentShader->setUniformValue("opacity", (GLfloat) opacity);
glresource->currentShader->setUniformValue("texture", 0);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glDisableVertexAttribArray(D_VERTEX_COORDS);
glDisableVertexAttribArray(D_TEXTURE_COORDS);
glwidget->paintEngine()->syncState();
glActiveTexture(GL_TEXTURE0);
}
void MTexturePixmapPrivate::init()
{
if (!item->is_valid)
return;
if (!glresource) {
glresource = new MGLResourceManager(glwidget);
glresource->initVertices(glwidget);
}
XRenderPictFormat *format = XRenderFindVisualFormat(QX11Info::display(),
item->windowAttributes()->visual);
has_alpha = (format && format->type == PictTypeDirect && format->direct.alphaMask);
resize(item->windowAttributes()->width, item->windowAttributes()->height);
item->setPos(item->windowAttributes()->x, item->windowAttributes()->y);
}
MTexturePixmapPrivate::MTexturePixmapPrivate(Qt::HANDLE window, QGLWidget *w, MTexturePixmapItem *p)
: ctx(0),
glwidget(w),
window(window),
windowp(0),
#ifdef DESKTOP_VERSION
glpixmap(0),
#endif
textureId(0),
ctextureId(0),
custom_tfp(false),
has_alpha(false),
direct_fb_render(false),
angle(0),
item(p)
{
damageTracking(true);
init();
}
MTexturePixmapPrivate::~MTexturePixmapPrivate()
{
damageTracking(false);
}
void MTexturePixmapPrivate::damageTracking(bool enabled)
{
if (damage_object) {
XDamageDestroy(QX11Info::display(), damage_object);
damage_object = NULL;
}
if (enabled && !damage_object)
damage_object = XDamageCreate(QX11Info::display(), window,
XDamageReportNonEmpty);
}
void MTexturePixmapPrivate::saveBackingStore(bool renew)
{
XWindowAttributes a;
if (!XGetWindowAttributes(QX11Info::display(), item->window(), &a)) {
qWarning("%s: invalid window 0x%lx", __func__, item->window());
return;
}
if (a.map_state != IsViewable)
return;
if (windowp)
XFreePixmap(QX11Info::display(), windowp);
Pixmap px = XCompositeNameWindowPixmap(QX11Info::display(), item->window());
windowp = px;
if (renew)
item->rebindPixmap();
}
void MTexturePixmapPrivate::windowRaised()
{
XRaiseWindow(QX11Info::display(), item->window());
}
void MTexturePixmapPrivate::resize(int w, int h)
{
if (!brect.isEmpty() && !item->isDirectRendered() && (brect.width() != w || brect.height() != h)) {
item->saveBackingStore(true);
item->updateWindowPixmap();
}
brect.setWidth(w);
brect.setHeight(h);
}
bool MTexturePixmapPrivate::hasAlpha() const
{
return has_alpha;
}
void MTexturePixmapPrivate::setValid(bool valid)
{
item->is_valid = valid;
}
<|endoftext|> |
<commit_before>#include "util/bitmap.h"
#include "mugen/option_options.h"
#include "mugen/game.h"
#include "mugen/mugen_menu.h"
#include "mugen/config.h"
#include "mugen/mugen_font.h"
#include "mugen/mugen_sound.h"
#include "mugen/background.h"
#include "ast/all.h"
#include "parser/all.h"
#include "init.h"
#include "util/funcs.h"
#include "util/file-system.h"
#include "util/timedifference.h"
#include "input/input-manager.h"
#include "return_exception.h"
#include "globals.h"
namespace PaintownUtil = ::Util;
using namespace std;
using namespace Mugen;
const int DEFAULT_WIDTH = 320;
const int DEFAULT_HEIGHT = 240;
OptionOptions::OptionOptions(Token *token) throw (LoadException):
MenuOption(token, Event){
// notin
}
OptionOptions::OptionOptions( const std::string &name ) throw( LoadException ):
MenuOption(0, Event){
if (name.empty()){
throw LoadException("No name given to Options");
}
this->setText(name);
}
OptionOptions::~OptionOptions(){
// Nothing
}
void OptionOptions::logic(){
}
void OptionOptions::run(bool &endGame){
std::string systemFile = Mugen::Data::getInstance().getFileFromMotif(Mugen::Data::getInstance().getMotif());
// Lets look for our def since some people think that all file systems are case insensitive
std::string baseDir = Mugen::Util::getFileDir(systemFile);
Global::debug(1) << baseDir << endl;
if (systemFile.empty()){
throw MugenException( "Cannot locate character select definition file for: " + systemFile );
}
TimeDifference diff;
diff.startTime();
Ast::AstParse parsed((list<Ast::Section*>*) Mugen::Def::main(systemFile));
diff.endTime();
Global::debug(1) << "Parsed mugen file " + systemFile + " in" + diff.printTime("") << endl;
Mugen::Background * background = 0;
std::vector< MugenFont *> fonts;
Mugen::SoundMap sounds;
Mugen::Point moveSound;
Mugen::Point doneSound;
Mugen::Point cancelSound;
for (Ast::AstParse::section_iterator section_it = parsed.getSections()->begin(); section_it != parsed.getSections()->end(); section_it++){
Ast::Section * section = *section_it;
std::string head = section->getName();
if (head == "Files"){
class FileWalker: public Ast::Walker{
public:
FileWalker(std::vector<MugenFont *> & fonts, Mugen::SoundMap & sounds, const string & baseDir):
fonts(fonts),
sounds(sounds),
baseDir(baseDir){
}
std::vector<MugenFont *> & fonts;
Mugen::SoundMap & sounds;
const string & baseDir;
virtual void onAttributeSimple(const Ast::AttributeSimple & simple){
if (simple == "snd"){
std::string file;
simple >> file;
Mugen::Util::readSounds( Mugen::Util::getCorrectFileLocation(baseDir, file ), sounds);
Global::debug(1) << "Got Sound File: '" << file << "'" << endl;
} else if (PaintownUtil::matchRegex(simple.idString(), "^font")){
std::string temp;
simple >> temp;
fonts.push_back(new MugenFont(Mugen::Util::getCorrectFileLocation(baseDir, temp)));
Global::debug(1) << "Got Font File: '" << temp << "'" << endl;
}
}
};
FileWalker walker(fonts, sounds, baseDir);
section->walk(walker);
} else if (head == "Option Info"){
class InfoWalker: public Ast::Walker{
public:
InfoWalker(Mugen::Point & moveSound, Mugen::Point & doneSound, Mugen::Point & cancelSound):
moveSound(moveSound),
doneSound(doneSound),
cancelSound(cancelSound){
}
Mugen::Point & moveSound;
Mugen::Point & doneSound;
Mugen::Point & cancelSound;
virtual void onAttributeSimple(const Ast::AttributeSimple & simple){
if (simple == "cursor.move.snd"){
try{
simple >> moveSound.x >> moveSound.y;
} catch (const Ast::Exception & e){
}
} else if (simple == "cursor.done.snd"){
try{
simple >> doneSound.x >> doneSound.y;
} catch (const Ast::Exception & e){
}
} else if (simple == "cancel.snd"){
try{
simple >> cancelSound.x >> cancelSound.y;
} catch (const Ast::Exception & e){
}
}
}
};
InfoWalker walker(moveSound, doneSound, cancelSound);
section->walk(walker);
} else if (head == "OptionBGdef"){
/* Background management */
background = new Mugen::Background(systemFile, "optionbg");
}
}
// Run options
Bitmap workArea(DEFAULT_WIDTH,DEFAULT_HEIGHT);
Bitmap screen(GFX_X, GFX_Y);
bool done = false;
bool escaped = false;
int ticker = 0;
double runCounter = 0;
Global::speed_counter = 0;
Global::second_counter = 0;
int game_time = 100;
// Set game keys temporary
InputMap<Mugen::Keys> gameInput;
gameInput.set(Keyboard::Key_ESC, 10, true, Mugen::Esc);
// Our Font
MugenFont * font = fonts[1];
while (!done){
bool draw = false;
if ( Global::speed_counter > 0 ){
draw = true;
runCounter += Global::speed_counter * Global::LOGIC_MULTIPLIER;
while ( runCounter >= 1.0 ){
// tick tock
ticker++;
runCounter -= 1;
// Key handler
InputManager::poll();
InputMap<Mugen::Keys>::Output out = InputManager::getMap(gameInput);
if (out[Mugen::Esc]){
done = escaped = true;
if (sounds[cancelSound.x][cancelSound.y]){
sounds[cancelSound.x][cancelSound.y]->play();
}
InputManager::waitForRelease(gameInput, Mugen::Esc);
}
// Backgrounds
background->act();
}
Global::speed_counter = 0;
}
while ( Global::second_counter > 0 ){
game_time--;
Global::second_counter--;
if ( game_time < 0 ){
game_time = 0;
}
}
if ( draw ){
// render backgrounds
background->renderBackground(0,0,workArea);
// render fonts
font->render(DEFAULT_WIDTH/2, 20, 0, 0, workArea, "OPTIONS" );
// render Foregrounds
background->renderForeground(0,0,workArea);
// Finally render to screen
workArea.Stretch(screen);
screen.BlitToScreen();
}
while ( Global::speed_counter < 1 ){
PaintownUtil::rest( 1 );
}
}
delete background;
// Get rid of sprites
for( std::vector<MugenFont *>::iterator i = fonts.begin() ; i != fonts.end() ; ++i ){
if (*i){
delete *i;
}
}
// Get rid of sounds
for( std::map< unsigned int, std::map< unsigned int, MugenSound * > >::iterator i = sounds.begin() ; i != sounds.end() ; ++i ){
for( std::map< unsigned int, MugenSound * >::iterator j = i->second.begin() ; j != i->second.end() ; ++j ){
if (j->second){
delete j->second;
}
}
}
// **FIXME Hack figure something out
if (escaped){
throw ReturnException();
}
}
<commit_msg>Added options box.<commit_after>#include "util/bitmap.h"
#include "mugen/option_options.h"
#include "mugen/game.h"
#include "mugen/mugen_menu.h"
#include "mugen/config.h"
#include "mugen/mugen_font.h"
#include "mugen/mugen_sound.h"
#include "mugen/background.h"
#include "ast/all.h"
#include "parser/all.h"
#include "init.h"
#include "util/funcs.h"
#include "util/file-system.h"
#include "util/timedifference.h"
#include "input/input-manager.h"
#include "return_exception.h"
#include "gui/box.h"
#include "globals.h"
namespace PaintownUtil = ::Util;
using namespace std;
using namespace Mugen;
const int DEFAULT_WIDTH = 320;
const int DEFAULT_HEIGHT = 240;
OptionOptions::OptionOptions(Token *token) throw (LoadException):
MenuOption(token, Event){
// notin
}
OptionOptions::OptionOptions( const std::string &name ) throw( LoadException ):
MenuOption(0, Event){
if (name.empty()){
throw LoadException("No name given to Options");
}
this->setText(name);
}
OptionOptions::~OptionOptions(){
// Nothing
}
void OptionOptions::logic(){
}
void OptionOptions::run(bool &endGame){
std::string systemFile = Mugen::Data::getInstance().getFileFromMotif(Mugen::Data::getInstance().getMotif());
// Lets look for our def since some people think that all file systems are case insensitive
std::string baseDir = Mugen::Util::getFileDir(systemFile);
Global::debug(1) << baseDir << endl;
if (systemFile.empty()){
throw MugenException( "Cannot locate character select definition file for: " + systemFile );
}
TimeDifference diff;
diff.startTime();
Ast::AstParse parsed((list<Ast::Section*>*) Mugen::Def::main(systemFile));
diff.endTime();
Global::debug(1) << "Parsed mugen file " + systemFile + " in" + diff.printTime("") << endl;
Mugen::Background * background = 0;
std::vector< MugenFont *> fonts;
Mugen::SoundMap sounds;
Mugen::Point moveSound;
Mugen::Point doneSound;
Mugen::Point cancelSound;
for (Ast::AstParse::section_iterator section_it = parsed.getSections()->begin(); section_it != parsed.getSections()->end(); section_it++){
Ast::Section * section = *section_it;
std::string head = section->getName();
if (head == "Files"){
class FileWalker: public Ast::Walker{
public:
FileWalker(std::vector<MugenFont *> & fonts, Mugen::SoundMap & sounds, const string & baseDir):
fonts(fonts),
sounds(sounds),
baseDir(baseDir){
}
std::vector<MugenFont *> & fonts;
Mugen::SoundMap & sounds;
const string & baseDir;
virtual void onAttributeSimple(const Ast::AttributeSimple & simple){
if (simple == "snd"){
std::string file;
simple >> file;
Mugen::Util::readSounds( Mugen::Util::getCorrectFileLocation(baseDir, file ), sounds);
Global::debug(1) << "Got Sound File: '" << file << "'" << endl;
} else if (PaintownUtil::matchRegex(simple.idString(), "^font")){
std::string temp;
simple >> temp;
fonts.push_back(new MugenFont(Mugen::Util::getCorrectFileLocation(baseDir, temp)));
Global::debug(1) << "Got Font File: '" << temp << "'" << endl;
}
}
};
FileWalker walker(fonts, sounds, baseDir);
section->walk(walker);
} else if (head == "Option Info"){
class InfoWalker: public Ast::Walker{
public:
InfoWalker(Mugen::Point & moveSound, Mugen::Point & doneSound, Mugen::Point & cancelSound):
moveSound(moveSound),
doneSound(doneSound),
cancelSound(cancelSound){
}
Mugen::Point & moveSound;
Mugen::Point & doneSound;
Mugen::Point & cancelSound;
virtual void onAttributeSimple(const Ast::AttributeSimple & simple){
if (simple == "cursor.move.snd"){
try{
simple >> moveSound.x >> moveSound.y;
} catch (const Ast::Exception & e){
}
} else if (simple == "cursor.done.snd"){
try{
simple >> doneSound.x >> doneSound.y;
} catch (const Ast::Exception & e){
}
} else if (simple == "cancel.snd"){
try{
simple >> cancelSound.x >> cancelSound.y;
} catch (const Ast::Exception & e){
}
}
}
};
InfoWalker walker(moveSound, doneSound, cancelSound);
section->walk(walker);
} else if (head == "OptionBGdef"){
/* Background management */
background = new Mugen::Background(systemFile, "optionbg");
}
}
// Run options
Bitmap workArea(DEFAULT_WIDTH,DEFAULT_HEIGHT);
Bitmap screen(GFX_X, GFX_Y);
bool done = false;
bool escaped = false;
int ticker = 0;
double runCounter = 0;
Global::speed_counter = 0;
Global::second_counter = 0;
int game_time = 100;
// Set game keys temporary
InputMap<Mugen::Keys> gameInput;
gameInput.set(Keyboard::Key_ESC, 10, true, Mugen::Esc);
// Our Font
MugenFont * font = fonts[1];
// Box
Box optionArea;
optionArea.position.width = 200;
optionArea.position.height = 180;
optionArea.position.x = (DEFAULT_WIDTH/2) - (optionArea.position.width/2);
optionArea.position.y = (DEFAULT_HEIGHT/2) - (optionArea.position.height/2);
optionArea.position.radius = 5;
optionArea.position.body = Bitmap::makeColor(0,0,60);
optionArea.position.bodyAlpha = 150;
optionArea.position.border = Bitmap::makeColor(0,0,20);
while (!done){
bool draw = false;
if ( Global::speed_counter > 0 ){
draw = true;
runCounter += Global::speed_counter * Global::LOGIC_MULTIPLIER;
while ( runCounter >= 1.0 ){
// tick tock
ticker++;
runCounter -= 1;
// Key handler
InputManager::poll();
InputMap<Mugen::Keys>::Output out = InputManager::getMap(gameInput);
if (out[Mugen::Esc]){
done = escaped = true;
if (sounds[cancelSound.x][cancelSound.y]){
sounds[cancelSound.x][cancelSound.y]->play();
}
InputManager::waitForRelease(gameInput, Mugen::Esc);
}
// Backgrounds
background->act();
}
Global::speed_counter = 0;
}
while ( Global::second_counter > 0 ){
game_time--;
Global::second_counter--;
if ( game_time < 0 ){
game_time = 0;
}
}
if ( draw ){
// render backgrounds
background->renderBackground(0,0,workArea);
// render fonts
font->render(DEFAULT_WIDTH/2, 20, 0, 0, workArea, "OPTIONS" );
optionArea.render(&workArea);
// render Foregrounds
background->renderForeground(0,0,workArea);
// Finally render to screen
workArea.Stretch(screen);
screen.BlitToScreen();
}
while ( Global::speed_counter < 1 ){
PaintownUtil::rest( 1 );
}
}
delete background;
// Get rid of sprites
for( std::vector<MugenFont *>::iterator i = fonts.begin() ; i != fonts.end() ; ++i ){
if (*i){
delete *i;
}
}
// Get rid of sounds
for( std::map< unsigned int, std::map< unsigned int, MugenSound * > >::iterator i = sounds.begin() ; i != sounds.end() ; ++i ){
for( std::map< unsigned int, MugenSound * >::iterator j = i->second.begin() ; j != i->second.end() ; ++j ){
if (j->second){
delete j->second;
}
}
}
// **FIXME Hack figure something out
if (escaped){
throw ReturnException();
}
}
<|endoftext|> |
<commit_before>/**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include "growl_osx.h"
#import "GrowlApplicationBridge.h"
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#include <sys/types.h>
#include <sys/stat.h>
using namespace kroll;
using namespace ti;
namespace ti {
GrowlOSX::GrowlOSX(SharedBoundObject global) : GrowlBinding(global) {
delegate = [[TiGrowlDelegate alloc] init];
[delegate retain];
}
GrowlOSX::~GrowlOSX() {
[delegate release];
}
void GrowlOSX::ShowNotification(std::string& title, std::string& description, std::string& iconURL, int notification_delay, SharedBoundMethod callback)
{
NSData *iconData = [NSData data];
if (iconURL.size() > 0) {
SharedValue iconPathValue = global->CallNS("App.appURLToPath", Value::NewString(iconURL));
if (iconPathValue->IsString()) {
std::string iconPath = iconPathValue->ToString();
iconData = [NSData dataWithContentsOfFile:[NSString stringWithCString:iconPath.c_str()]];
}
}
NSMutableDictionary* clickContext = [[NSMutableDictionary alloc] initWithCapacity:10];
if (!callback.isNull()) {
[clickContext setObject:[[MethodWrapper alloc] initWithMethod:new SharedBoundMethod(callback)] forKey:@"method_wrapper"];
}
[GrowlApplicationBridge
notifyWithTitle:[NSString stringWithCString:title.c_str()]
description:[NSString stringWithCString:description.c_str()]
notificationName:@"tiNotification"
iconData:iconData
priority:0
isSticky:NO
clickContext:clickContext];
}
bool GrowlOSX::IsRunning()
{
return [GrowlApplicationBridge isGrowlRunning];
}
void GrowlOSX::CopyToApp(kroll::Host *host, kroll::Module *module)
{
std::string dir = host->GetApplicationHome() + KR_PATH_SEP + "Contents" +
KR_PATH_SEP + "Frameworks" + KR_PATH_SEP + "Growl.framework";
if (!FileUtils::IsDirectory(dir))
{
NSFileManager *fm = [NSFileManager defaultManager];
NSString *src = [NSString stringWithFormat:@"%s/Resources/Growl.framework", module->GetPath()];
NSString *dest = [NSString stringWithFormat:@"%s/Contents/Frameworks", host->GetApplicationHome().c_str()];
[fm copyPath:src toPath:dest handler:nil];
src = [NSString stringWithFormat:@"%s/Resources/Growl Registration Ticket.growlRegDict", module->GetPath()];
dest = [NSString stringWithFormat:@"%s/Contents/Resources", host->GetApplicationHome().c_str()];
[fm copyPath:src toPath:dest handler:nil];
}
}
}
<commit_msg>Unicode support in growl. TI-107<commit_after>/**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include "growl_osx.h"
#import "GrowlApplicationBridge.h"
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#include <sys/types.h>
#include <sys/stat.h>
using namespace kroll;
using namespace ti;
namespace ti {
GrowlOSX::GrowlOSX(SharedBoundObject global) : GrowlBinding(global) {
delegate = [[TiGrowlDelegate alloc] init];
[delegate retain];
}
GrowlOSX::~GrowlOSX() {
[delegate release];
}
void GrowlOSX::ShowNotification(std::string& title, std::string& description, std::string& iconURL, int notification_delay, SharedBoundMethod callback)
{
NSData *iconData = [NSData data];
if (iconURL.size() > 0) {
SharedValue iconPathValue = global->CallNS("App.appURLToPath", Value::NewString(iconURL));
if (iconPathValue->IsString()) {
std::string iconPath = iconPathValue->ToString();
const char * iconPathCString = iconPath.c_str();
if (iconPathCString != NULL) {
iconData = [NSData dataWithContentsOfFile:[NSString stringWithUTF8String:iconPathCString]];
}
}
}
NSMutableDictionary* clickContext = [[NSMutableDictionary alloc] initWithCapacity:10];
if (!callback.isNull()) {
[clickContext setObject:[[MethodWrapper alloc] initWithMethod:new SharedBoundMethod(callback)] forKey:@"method_wrapper"];
}
const char * titleCString = title.c_str();
NSString * titleString = nil;
if (titleCString != NULL) {
titleString = [NSString stringWithUTF8String:titleCString];
}
const char * descriptionCString = description.c_str();
NSString * descriptionString = nil;
if (descriptionCString != NULL) {
descriptionString = [NSString stringWithUTF8String:descriptionCString];
}
[GrowlApplicationBridge
notifyWithTitle:titleString
description:descriptionString
notificationName:@"tiNotification"
iconData:iconData
priority:0
isSticky:NO
clickContext:clickContext];
}
bool GrowlOSX::IsRunning()
{
return [GrowlApplicationBridge isGrowlRunning];
}
void GrowlOSX::CopyToApp(kroll::Host *host, kroll::Module *module)
{
std::string dir = host->GetApplicationHome() + KR_PATH_SEP + "Contents" +
KR_PATH_SEP + "Frameworks" + KR_PATH_SEP + "Growl.framework";
if (!FileUtils::IsDirectory(dir))
{
NSFileManager *fm = [NSFileManager defaultManager];
NSString *src = [NSString stringWithFormat:@"%s/Resources/Growl.framework", module->GetPath()];
NSString *dest = [NSString stringWithFormat:@"%s/Contents/Frameworks", host->GetApplicationHome().c_str()];
[fm copyPath:src toPath:dest handler:nil];
src = [NSString stringWithFormat:@"%s/Resources/Growl Registration Ticket.growlRegDict", module->GetPath()];
dest = [NSString stringWithFormat:@"%s/Contents/Resources", host->GetApplicationHome().c_str()];
[fm copyPath:src toPath:dest handler:nil];
}
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** 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.
**
****************************************************************************/
#include "cmakeprojectmanager.h"
#include "cmakeopenprojectwizard.h"
#include "cmakeprojectconstants.h"
#include "cmakeproject.h"
#include <utils/synchronousprocess.h>
#include <utils/qtcprocess.h>
#include <coreplugin/icore.h>
#include <coreplugin/id.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/target.h>
#include <utils/QtConcurrentTools>
#include <QtConcurrentRun>
#include <QCoreApplication>
#include <QDateTime>
#include <QDesktopServices>
using namespace CMakeProjectManager::Internal;
CMakeManager::CMakeManager(CMakeSettingsPage *cmakeSettingsPage)
: m_settingsPage(cmakeSettingsPage)
{
ProjectExplorer::ProjectExplorerPlugin *projectExplorer = ProjectExplorer::ProjectExplorerPlugin::instance();
connect(projectExplorer, SIGNAL(aboutToShowContextMenu(ProjectExplorer::Project*,ProjectExplorer::Node*)),
this, SLOT(updateContextMenu(ProjectExplorer::Project*,ProjectExplorer::Node*)));
Core::ActionContainer *mbuild =
Core::ActionManager::actionContainer(ProjectExplorer::Constants::M_BUILDPROJECT);
Core::ActionContainer *mproject =
Core::ActionManager::actionContainer(ProjectExplorer::Constants::M_PROJECTCONTEXT);
Core::ActionContainer *msubproject =
Core::ActionManager::actionContainer(ProjectExplorer::Constants::M_SUBPROJECTCONTEXT);
const Core::Context projectContext(CMakeProjectManager::Constants::PROJECTCONTEXT);
m_runCMakeAction = new QAction(QIcon(), tr("Run CMake"), this);
Core::Command *command = Core::ActionManager::registerAction(m_runCMakeAction,
Constants::RUNCMAKE, projectContext);
command->setAttribute(Core::Command::CA_Hide);
mbuild->addAction(command, ProjectExplorer::Constants::G_BUILD_DEPLOY);
connect(m_runCMakeAction, SIGNAL(triggered()), this, SLOT(runCMake()));
m_runCMakeActionContextMenu = new QAction(QIcon(), tr("Run CMake"), this);
command = Core::ActionManager::registerAction(m_runCMakeActionContextMenu,
Constants::RUNCMAKECONTEXTMENU, projectContext);
command->setAttribute(Core::Command::CA_Hide);
mproject->addAction(command, ProjectExplorer::Constants::G_PROJECT_BUILD);
msubproject->addAction(command, ProjectExplorer::Constants::G_PROJECT_BUILD);
connect(m_runCMakeActionContextMenu, SIGNAL(triggered()), this, SLOT(runCMakeContextMenu()));
}
void CMakeManager::updateContextMenu(ProjectExplorer::Project *project, ProjectExplorer::Node *node)
{
Q_UNUSED(node);
m_contextProject = project;
}
void CMakeManager::runCMake()
{
runCMake(ProjectExplorer::ProjectExplorerPlugin::currentProject());
}
void CMakeManager::runCMakeContextMenu()
{
runCMake(m_contextProject);
}
void CMakeManager::runCMake(ProjectExplorer::Project *project)
{
if (!project)
return;
CMakeProject *cmakeProject = qobject_cast<CMakeProject *>(project);
if (!cmakeProject || !cmakeProject->activeTarget() || !cmakeProject->activeTarget()->activeBuildConfiguration())
return;
if (!ProjectExplorer::ProjectExplorerPlugin::instance()->saveModifiedFiles())
return;
CMakeBuildConfiguration *bc
= static_cast<CMakeBuildConfiguration *>(cmakeProject->activeTarget()->activeBuildConfiguration());
CMakeBuildInfo info(bc);
CMakeOpenProjectWizard copw(Core::ICore::mainWindow(), this, CMakeOpenProjectWizard::WantToUpdate, &info);
if (copw.exec() == QDialog::Accepted)
cmakeProject->parseCMakeLists();
}
ProjectExplorer::Project *CMakeManager::openProject(const QString &fileName, QString *errorString)
{
if (!QFileInfo(fileName).isFile()) {
if (errorString)
*errorString = tr("Failed opening project '%1': Project is not a file")
.arg(fileName);
return 0;
}
return new CMakeProject(this, fileName);
}
QString CMakeManager::mimeType() const
{
return QLatin1String(Constants::CMAKEMIMETYPE);
}
QString CMakeManager::cmakeExecutable() const
{
return m_settingsPage->cmakeExecutable();
}
bool CMakeManager::isCMakeExecutableValid() const
{
return m_settingsPage->isCMakeExecutableValid();
}
void CMakeManager::setCMakeExecutable(const QString &executable)
{
m_settingsPage->setCMakeExecutable(executable);
}
bool CMakeManager::hasCodeBlocksMsvcGenerator() const
{
return m_settingsPage->hasCodeBlocksMsvcGenerator();
}
bool CMakeManager::hasCodeBlocksNinjaGenerator() const
{
return m_settingsPage->hasCodeBlocksNinjaGenerator();
}
bool CMakeManager::preferNinja() const
{
return m_settingsPage->preferNinja();
}
// need to refactor this out
// we probably want the process instead of this function
// cmakeproject then could even run the cmake process in the background, adding the files afterwards
// sounds like a plan
void CMakeManager::createXmlFile(Utils::QtcProcess *proc, const QString &arguments,
const QString &sourceDirectory, const QDir &buildDirectory,
const Utils::Environment &env, const QString &generator)
{
// We create a cbp file, only if we didn't find a cbp file in the base directory
// Yet that can still override cbp files in subdirectories
// And we are creating tons of files in the source directories
// All of that is not really nice.
// The mid term plan is to move away from the CodeBlocks Generator and use our own
// QtCreator generator, which actually can be very similar to the CodeBlock Generator
QString buildDirectoryPath = buildDirectory.absolutePath();
buildDirectory.mkpath(buildDirectoryPath);
proc->setWorkingDirectory(buildDirectoryPath);
proc->setEnvironment(env);
const QString srcdir = buildDirectory.exists(QLatin1String("CMakeCache.txt")) ?
QString(QLatin1Char('.')) : sourceDirectory;
QString args;
Utils::QtcProcess::addArg(&args, srcdir);
Utils::QtcProcess::addArgs(&args, arguments);
Utils::QtcProcess::addArg(&args, generator);
proc->setCommand(cmakeExecutable(), args);
proc->start();
}
QString CMakeManager::findCbpFile(const QDir &directory)
{
// Find the cbp file
// the cbp file is named like the project() command in the CMakeList.txt file
// so this function below could find the wrong cbp file, if the user changes the project()
// 2name
QDateTime t;
QString file;
foreach (const QString &cbpFile , directory.entryList()) {
if (cbpFile.endsWith(QLatin1String(".cbp"))) {
QFileInfo fi(directory.path() + QLatin1Char('/') + cbpFile);
if (t.isNull() || fi.lastModified() > t) {
file = directory.path() + QLatin1Char('/') + cbpFile;
t = fi.lastModified();
}
}
}
return file;
}
// This code is duplicated from qtversionmanager
QString CMakeManager::qtVersionForQMake(const QString &qmakePath)
{
QProcess qmake;
qmake.start(qmakePath, QStringList(QLatin1String("--version")));
if (!qmake.waitForStarted()) {
qWarning("Cannot start '%s': %s", qPrintable(qmakePath), qPrintable(qmake.errorString()));
return QString();
}
if (!qmake.waitForFinished()) {
Utils::SynchronousProcess::stopProcess(qmake);
qWarning("Timeout running '%s'.", qPrintable(qmakePath));
return QString();
}
QString output = QString::fromLocal8Bit(qmake.readAllStandardOutput());
QRegExp regexp(QLatin1String("(QMake version|Qmake version:)[\\s]*([\\d.]*)"));
regexp.indexIn(output);
if (regexp.cap(2).startsWith(QLatin1String("2."))) {
QRegExp regexp2(QLatin1String("Using Qt version[\\s]*([\\d\\.]*)"));
regexp2.indexIn(output);
return regexp2.cap(1);
}
return QString();
}
<commit_msg>CMakeProjectManager: Remove outdated comment<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** 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.
**
****************************************************************************/
#include "cmakeprojectmanager.h"
#include "cmakeopenprojectwizard.h"
#include "cmakeprojectconstants.h"
#include "cmakeproject.h"
#include <utils/synchronousprocess.h>
#include <utils/qtcprocess.h>
#include <coreplugin/icore.h>
#include <coreplugin/id.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/target.h>
#include <utils/QtConcurrentTools>
#include <QtConcurrentRun>
#include <QCoreApplication>
#include <QDateTime>
#include <QDesktopServices>
using namespace CMakeProjectManager::Internal;
CMakeManager::CMakeManager(CMakeSettingsPage *cmakeSettingsPage)
: m_settingsPage(cmakeSettingsPage)
{
ProjectExplorer::ProjectExplorerPlugin *projectExplorer = ProjectExplorer::ProjectExplorerPlugin::instance();
connect(projectExplorer, SIGNAL(aboutToShowContextMenu(ProjectExplorer::Project*,ProjectExplorer::Node*)),
this, SLOT(updateContextMenu(ProjectExplorer::Project*,ProjectExplorer::Node*)));
Core::ActionContainer *mbuild =
Core::ActionManager::actionContainer(ProjectExplorer::Constants::M_BUILDPROJECT);
Core::ActionContainer *mproject =
Core::ActionManager::actionContainer(ProjectExplorer::Constants::M_PROJECTCONTEXT);
Core::ActionContainer *msubproject =
Core::ActionManager::actionContainer(ProjectExplorer::Constants::M_SUBPROJECTCONTEXT);
const Core::Context projectContext(CMakeProjectManager::Constants::PROJECTCONTEXT);
m_runCMakeAction = new QAction(QIcon(), tr("Run CMake"), this);
Core::Command *command = Core::ActionManager::registerAction(m_runCMakeAction,
Constants::RUNCMAKE, projectContext);
command->setAttribute(Core::Command::CA_Hide);
mbuild->addAction(command, ProjectExplorer::Constants::G_BUILD_DEPLOY);
connect(m_runCMakeAction, SIGNAL(triggered()), this, SLOT(runCMake()));
m_runCMakeActionContextMenu = new QAction(QIcon(), tr("Run CMake"), this);
command = Core::ActionManager::registerAction(m_runCMakeActionContextMenu,
Constants::RUNCMAKECONTEXTMENU, projectContext);
command->setAttribute(Core::Command::CA_Hide);
mproject->addAction(command, ProjectExplorer::Constants::G_PROJECT_BUILD);
msubproject->addAction(command, ProjectExplorer::Constants::G_PROJECT_BUILD);
connect(m_runCMakeActionContextMenu, SIGNAL(triggered()), this, SLOT(runCMakeContextMenu()));
}
void CMakeManager::updateContextMenu(ProjectExplorer::Project *project, ProjectExplorer::Node *node)
{
Q_UNUSED(node);
m_contextProject = project;
}
void CMakeManager::runCMake()
{
runCMake(ProjectExplorer::ProjectExplorerPlugin::currentProject());
}
void CMakeManager::runCMakeContextMenu()
{
runCMake(m_contextProject);
}
void CMakeManager::runCMake(ProjectExplorer::Project *project)
{
if (!project)
return;
CMakeProject *cmakeProject = qobject_cast<CMakeProject *>(project);
if (!cmakeProject || !cmakeProject->activeTarget() || !cmakeProject->activeTarget()->activeBuildConfiguration())
return;
if (!ProjectExplorer::ProjectExplorerPlugin::instance()->saveModifiedFiles())
return;
CMakeBuildConfiguration *bc
= static_cast<CMakeBuildConfiguration *>(cmakeProject->activeTarget()->activeBuildConfiguration());
CMakeBuildInfo info(bc);
CMakeOpenProjectWizard copw(Core::ICore::mainWindow(), this, CMakeOpenProjectWizard::WantToUpdate, &info);
if (copw.exec() == QDialog::Accepted)
cmakeProject->parseCMakeLists();
}
ProjectExplorer::Project *CMakeManager::openProject(const QString &fileName, QString *errorString)
{
if (!QFileInfo(fileName).isFile()) {
if (errorString)
*errorString = tr("Failed opening project '%1': Project is not a file")
.arg(fileName);
return 0;
}
return new CMakeProject(this, fileName);
}
QString CMakeManager::mimeType() const
{
return QLatin1String(Constants::CMAKEMIMETYPE);
}
QString CMakeManager::cmakeExecutable() const
{
return m_settingsPage->cmakeExecutable();
}
bool CMakeManager::isCMakeExecutableValid() const
{
return m_settingsPage->isCMakeExecutableValid();
}
void CMakeManager::setCMakeExecutable(const QString &executable)
{
m_settingsPage->setCMakeExecutable(executable);
}
bool CMakeManager::hasCodeBlocksMsvcGenerator() const
{
return m_settingsPage->hasCodeBlocksMsvcGenerator();
}
bool CMakeManager::hasCodeBlocksNinjaGenerator() const
{
return m_settingsPage->hasCodeBlocksNinjaGenerator();
}
bool CMakeManager::preferNinja() const
{
return m_settingsPage->preferNinja();
}
// need to refactor this out
// we probably want the process instead of this function
// cmakeproject then could even run the cmake process in the background, adding the files afterwards
// sounds like a plan
void CMakeManager::createXmlFile(Utils::QtcProcess *proc, const QString &arguments,
const QString &sourceDirectory, const QDir &buildDirectory,
const Utils::Environment &env, const QString &generator)
{
QString buildDirectoryPath = buildDirectory.absolutePath();
buildDirectory.mkpath(buildDirectoryPath);
proc->setWorkingDirectory(buildDirectoryPath);
proc->setEnvironment(env);
const QString srcdir = buildDirectory.exists(QLatin1String("CMakeCache.txt")) ?
QString(QLatin1Char('.')) : sourceDirectory;
QString args;
Utils::QtcProcess::addArg(&args, srcdir);
Utils::QtcProcess::addArgs(&args, arguments);
Utils::QtcProcess::addArg(&args, generator);
proc->setCommand(cmakeExecutable(), args);
proc->start();
}
QString CMakeManager::findCbpFile(const QDir &directory)
{
// Find the cbp file
// the cbp file is named like the project() command in the CMakeList.txt file
// so this function below could find the wrong cbp file, if the user changes the project()
// 2name
QDateTime t;
QString file;
foreach (const QString &cbpFile , directory.entryList()) {
if (cbpFile.endsWith(QLatin1String(".cbp"))) {
QFileInfo fi(directory.path() + QLatin1Char('/') + cbpFile);
if (t.isNull() || fi.lastModified() > t) {
file = directory.path() + QLatin1Char('/') + cbpFile;
t = fi.lastModified();
}
}
}
return file;
}
// This code is duplicated from qtversionmanager
QString CMakeManager::qtVersionForQMake(const QString &qmakePath)
{
QProcess qmake;
qmake.start(qmakePath, QStringList(QLatin1String("--version")));
if (!qmake.waitForStarted()) {
qWarning("Cannot start '%s': %s", qPrintable(qmakePath), qPrintable(qmake.errorString()));
return QString();
}
if (!qmake.waitForFinished()) {
Utils::SynchronousProcess::stopProcess(qmake);
qWarning("Timeout running '%s'.", qPrintable(qmakePath));
return QString();
}
QString output = QString::fromLocal8Bit(qmake.readAllStandardOutput());
QRegExp regexp(QLatin1String("(QMake version|Qmake version:)[\\s]*([\\d.]*)"));
regexp.indexIn(output);
if (regexp.cap(2).startsWith(QLatin1String("2."))) {
QRegExp regexp2(QLatin1String("Using Qt version[\\s]*([\\d\\.]*)"));
regexp2.indexIn(output);
return regexp2.cap(1);
}
return QString();
}
<|endoftext|> |
<commit_before>/**
* @file
* @author Jason Lingle
* @date 2012.02.03
* @brief Contains the NetworkAssembly class
*/
#ifndef NETWORK_ASSEMBLY_HXX_
#define NETWORK_ASSEMBLY_HXX_
#include <vector>
#include "src/core/aobject.hxx"
class Antenna;
class Tuner;
class NetworkConnection;
class PacketProcessor;
/**
* Manages the various objects that are used to provide a functional network
* system.
*
* This is essentially a convenience class for managing the list of connections
* and the memory used by the various PacketProcessors.
*/
class NetworkAssembly: public AObject {
std::vector<NetworkConnection*> connections;
std::vector<PacketProcessor*> packetProcessors;
Tuner tuner;
///Not implemented, do not use
NetworkAssembly(const NetworkAssembly&);
public:
/**
* Constructs a NetworkAssembly on the given Antenna.
* There are initially no connections or packet processors.
*/
NetworkAssembly(Antenna*);
virtual ~NetworkAssembly();
/**
* Returns the Tuner associated with this NetworkAssembly.
*/
Tuner* getTuner() noth;
/**
* Returns the number of NetworkConnections contained in this
* NetworkAssembly.
*/
unsigned numConnections() const noth;
/**
* Returns the NetworkConnection at the given index.
*/
NetworkConnection* getConnection(unsigned ix) const noth;
/**
* Removes and deletes the NetworkConnection at the given index.
*/
void removeConnection(unsigned ix) noth;
/**
* Removes and deletes the given NetworkConnection, which must
* exist within this NetworkAssembly's connection list.
*/
void removeConnection(NetworkConnection*) noth;
/**
* Adds the given PacketProcessor to those managed by this instance.
* The PacketProcessor will be deleted when this NetworkAssembly is deleted.
*/
void addPacketProcessor(PacketProcessor*) noth;
/**
* Updates all NetworkConnections.
* @param et the number of milliseconds that have elapsed since the last
* call to update()
*/
void update(unsigned et) noth;
};
#endif /* NETWORK_ASSEMBLY_HXX_ */
<commit_msg>Add GameField information to NetworkAssembly.<commit_after>/**
* @file
* @author Jason Lingle
* @date 2012.02.03
* @brief Contains the NetworkAssembly class
*/
#ifndef NETWORK_ASSEMBLY_HXX_
#define NETWORK_ASSEMBLY_HXX_
#include <vector>
#include "src/core/aobject.hxx"
class Antenna;
class Tuner;
class NetworkConnection;
class PacketProcessor;
/**
* Manages the various objects that are used to provide a functional network
* system.
*
* This is essentially a convenience class for managing the list of connections
* and the memory used by the various PacketProcessors.
*/
class NetworkAssembly: public AObject {
std::vector<NetworkConnection*> connections;
std::vector<PacketProcessor*> packetProcessors;
Tuner tuner;
///Not implemented, do not use
NetworkAssembly(const NetworkAssembly&);
public:
/**
* The GameField used by the networking system.
*/
GameField*const field;
/**
* The Antenna used for communication.
*/
Antenna*const antenna;
/**
* Constructs a NetworkAssembly on the given GameField and Antenna.
* There are initially no connections or packet processors.
*
* @param field the GameField the network operates on
* @param antenna the Antenna to use for sending and receiving of messages
*/
NetworkAssembly(GameField* field, Antenna* antenna);
virtual ~NetworkAssembly();
/**
* Returns the Tuner associated with this NetworkAssembly.
*/
Tuner* getTuner() noth;
/**
* Returns the number of NetworkConnections contained in this
* NetworkAssembly.
*/
unsigned numConnections() const noth;
/**
* Returns the NetworkConnection at the given index.
*/
NetworkConnection* getConnection(unsigned ix) const noth;
/**
* Removes and deletes the NetworkConnection at the given index.
*/
void removeConnection(unsigned ix) noth;
/**
* Removes and deletes the given NetworkConnection, which must
* exist within this NetworkAssembly's connection list.
*/
void removeConnection(NetworkConnection*) noth;
/**
* Adds the given PacketProcessor to those managed by this instance.
* The PacketProcessor will be deleted when this NetworkAssembly is deleted.
*/
void addPacketProcessor(PacketProcessor*) noth;
/**
* Updates all NetworkConnections.
* @param et the number of milliseconds that have elapsed since the last
* call to update()
*/
void update(unsigned et) noth;
};
#endif /* NETWORK_ASSEMBLY_HXX_ */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* 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: null_spritehelper.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_canvas.hxx"
#include <canvas/debug.hxx>
#include <canvas/verbosetrace.hxx>
#include <rtl/logfile.hxx>
#include <rtl/math.hxx>
#include <canvas/canvastools.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygonrasterconverter.hxx>
#include <basegfx/polygon/b2dpolygontriangulator.hxx>
#include <basegfx/polygon/b2dpolygoncutandtouch.hxx>
#include "null_canvascustomsprite.hxx"
#include "null_spritehelper.hxx"
#include <memory>
using namespace ::com::sun::star;
namespace nullcanvas
{
SpriteHelper::SpriteHelper() :
mpSpriteCanvas(),
mbTextureDirty( true )
{
}
void SpriteHelper::init( const geometry::RealSize2D& rSpriteSize,
const SpriteCanvasRef& rSpriteCanvas )
{
ENSURE_AND_THROW( rSpriteCanvas.get(),
"SpriteHelper::init(): Invalid device, sprite canvas or surface" );
mpSpriteCanvas = rSpriteCanvas;
mbTextureDirty = true;
// also init base class
CanvasCustomSpriteHelper::init( rSpriteSize,
rSpriteCanvas.get() );
}
void SpriteHelper::disposing()
{
mpSpriteCanvas.clear();
// forward to parent
CanvasCustomSpriteHelper::disposing();
}
void SpriteHelper::redraw( bool& /*io_bSurfaceDirty*/ ) const
{
// TODO
}
::basegfx::B2DPolyPolygon SpriteHelper::polyPolygonFromXPolyPolygon2D( uno::Reference< rendering::XPolyPolygon2D >& xPoly ) const
{
return ::canvas::tools::polyPolygonFromXPolyPolygon2D( xPoly );
}
}
<commit_msg>INTEGRATION: CWS canvas05 (1.5.26); FILE MERGED 2008/04/21 07:27:40 thb 1.5.26.2: RESYNC: (1.5-1.6); FILE MERGED 2007/10/01 13:02:02 thb 1.5.26.1: #i78888# #i78925# #i79258# #i79437# Merge from CWS picom<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: null_spritehelper.cxx,v $
* $Revision: 1.7 $
*
* 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_canvas.hxx"
#include <canvas/debug.hxx>
#include <tools/diagnose_ex.h>
#include <canvas/verbosetrace.hxx>
#include <rtl/logfile.hxx>
#include <rtl/math.hxx>
#include <canvas/canvastools.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygonrasterconverter.hxx>
#include <basegfx/polygon/b2dpolygontriangulator.hxx>
#include <basegfx/polygon/b2dpolygoncutandtouch.hxx>
#include "null_canvascustomsprite.hxx"
#include "null_spritehelper.hxx"
#include <memory>
using namespace ::com::sun::star;
namespace nullcanvas
{
SpriteHelper::SpriteHelper() :
mpSpriteCanvas(),
mbTextureDirty( true )
{
}
void SpriteHelper::init( const geometry::RealSize2D& rSpriteSize,
const SpriteCanvasRef& rSpriteCanvas )
{
ENSURE_OR_THROW( rSpriteCanvas.get(),
"SpriteHelper::init(): Invalid device, sprite canvas or surface" );
mpSpriteCanvas = rSpriteCanvas;
mbTextureDirty = true;
// also init base class
CanvasCustomSpriteHelper::init( rSpriteSize,
rSpriteCanvas.get() );
}
void SpriteHelper::disposing()
{
mpSpriteCanvas.clear();
// forward to parent
CanvasCustomSpriteHelper::disposing();
}
void SpriteHelper::redraw( bool& /*io_bSurfaceDirty*/ ) const
{
// TODO
}
::basegfx::B2DPolyPolygon SpriteHelper::polyPolygonFromXPolyPolygon2D( uno::Reference< rendering::XPolyPolygon2D >& xPoly ) const
{
return ::basegfx::unotools::b2DPolyPolygonFromXPolyPolygon2D( xPoly );
}
}
<|endoftext|> |
<commit_before>#include "analyzer.h"
#include <boost/log/trivial.hpp>
#include <unistd.h>
using namespace std;
namespace analyzer
{
AnalyzerPtr Analyzer::Create() {
BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::Create: Function call";
auto ptr = AnalyzerPtr(new Analyzer());
return ptr;
}
void Analyzer::StartLoop() {
BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StartLoop: Function call";
is_loop_running_ = true;
while (is_loop_running_) {
BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StartLoop: Loop is running";
ExecuteAll();
sleep(1);
}
}
void Analyzer::StopLoop() {
BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StopLoop: Function call";
is_loop_running_ = false;
}
bool Analyzer::IsLoopRunning() const {
return is_loop_running_;
}
void Analyzer::StartAnalyzing() {
BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StartAnalyzing: Function call";
is_analyzing_ = true;
}
bool Analyzer::IsAnalyzing() const {
return is_analyzing_;
}
void Analyzer::AddObject(AnalyzerObjectInterfacePtr object) {
BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StartAnalyzing: Function call";
objects_.insert(object);
}
Analyzer::Analyzer() :
is_loop_running_(false),
is_analyzing_(false) {
}
void Analyzer::ExecuteAll() {
BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::ExecuteAll: Function call";
if (is_analyzing_) {
BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::ExecuteAll: Analyzing started";
for (auto obj : objects_) {
obj->Analyze();
}
BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::ExecuteAll: Analyzing finished";
is_analyzing_ = false;
}
}
}
<commit_msg>Change logs classification<commit_after>#include "analyzer.h"
#include <boost/log/trivial.hpp>
#include <unistd.h>
using namespace std;
namespace analyzer
{
AnalyzerPtr Analyzer::Create() {
BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::Create: Function call";
auto ptr = AnalyzerPtr(new Analyzer());
return ptr;
}
void Analyzer::StartLoop() {
BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StartLoop: Function call";
is_loop_running_ = true;
while (is_loop_running_) {
BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StartLoop: Loop is running";
ExecuteAll();
sleep(1);
}
}
void Analyzer::StopLoop() {
BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StopLoop: Function call";
is_loop_running_ = false;
}
bool Analyzer::IsLoopRunning() const {
return is_loop_running_;
}
void Analyzer::StartAnalyzing() {
BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StartAnalyzing: Function call";
is_analyzing_ = true;
}
bool Analyzer::IsAnalyzing() const {
return is_analyzing_;
}
void Analyzer::AddObject(AnalyzerObjectInterfacePtr object) {
BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StartAnalyzing: Function call";
objects_.insert(object);
}
Analyzer::Analyzer() :
is_loop_running_(false),
is_analyzing_(false) {
}
void Analyzer::ExecuteAll() {
BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::ExecuteAll: Function call";
if (is_analyzing_) {
BOOST_LOG_TRIVIAL(info) << "analyzer::Analyzer::ExecuteAll: Analyzing started";
for (auto obj : objects_) {
obj->Analyze();
}
BOOST_LOG_TRIVIAL(info) << "analyzer::Analyzer::ExecuteAll: Analyzing finished";
is_analyzing_ = false;
}
}
}
<|endoftext|> |
<commit_before>#ifndef __CINT__
#include <iostream.h>
#include "AliRun.h"
#include "AliITS.h"
#include "AliITSgeom.h"
#include "AliITSRecPoint.h"
#include "AliITSclusterV2.h"
#include "TFile.h"
#include "TTree.h"
#include "TParticle.h"
#endif
Int_t AliITSFindClustersV2(Char_t SlowOrFast='f') {
/****************************************************************
* This macro converts AliITSRecPoint(s) to AliITSclusterV2(s) *
****************************************************************/
cerr<<"AliITSRecPoint(s) -> AliITSclusterV2(s)...\n";
if (gAlice) {delete gAlice; gAlice=0;}
TFile *in=TFile::Open("galice.root");
if (!in->IsOpen()) { cerr<<"Can't open galice.root !\n"; return 1; }
if (!(gAlice=(AliRun*)in->Get("gAlice"))) {
cerr<<"Can't find gAlice !\n";
return 2;
}
gAlice->GetEvent(0);
AliITS *ITS = (AliITS*)gAlice->GetModule("ITS");
if (!ITS) { cerr<<"Can't find the ITS !\n"; return 3; }
AliITSgeom *geom=ITS->GetITSgeom();
TFile *out=TFile::Open("AliITSclustersV2.root","new");
if (!out->IsOpen()) {
cerr<<"Delete old AliITSclustersV2.root !\n";
return 4;
}
geom->Write();
TClonesArray *clusters=new TClonesArray("AliITSclusterV2",10000);
TTree *cTree=new TTree("TreeC_ITS_0","ITS clusters");
cTree->Branch("Clusters",&clusters);
TTree *pTree=gAlice->TreeR();
if (!pTree) { cerr<<"Can't get TreeR !\n"; return 5; }
TBranch *branch = 0;
if (SlowOrFast=='f') {
branch = pTree->GetBranch("ITSRecPointsF");
}
else {
branch = pTree->GetBranch("ITSRecPoints");
}
if (!branch) { cerr<<"Can't get ITSRecPoints branch !\n"; return 6; }
TClonesArray *points=new TClonesArray("AliITSRecPoint",10000);
branch->SetAddress(&points);
TClonesArray &cl=*clusters;
Int_t nclusters=0;
Int_t nentr=(Int_t)branch->GetEntries();
cerr<<"Number of entries: "<<nentr<<endl;
Float_t lp[5]; Int_t lab[6]; //Why can't it be inside a loop ?
for (Int_t i=0; i<nentr; i++) {
points->Clear();
branch->GetEvent(i);
Int_t ncl=points->GetEntriesFast(); if (ncl==0){cTree->Fill();continue;}
Int_t lay,lad,det; geom->GetModuleId(i,lay,lad,det);
Float_t x,y,zshift; geom->GetTrans(lay,lad,det,x,y,zshift);
Double_t rot[9]; geom->GetRotMatrix(lay,lad,det,rot);
Double_t yshift = x*rot[0] + y*rot[1];
Int_t ndet=(lad-1)*geom->GetNdetectors(lay) + (det-1);
nclusters+=ncl;
Float_t kmip=1; // ADC->mip normalization factor for the SDD and SSD
if(lay==4 || lay==3){kmip=280.;};
if(lay==6 || lay==5){kmip=38.;};
for (Int_t j=0; j<ncl; j++) {
AliITSRecPoint *p=(AliITSRecPoint*)points->UncheckedAt(j);
//Float_t lp[5];
lp[0]=-p->GetX()-yshift; if (lay==1) lp[0]=-lp[0];
lp[1]=p->GetZ()+zshift;
lp[2]=p->GetSigmaX2();
lp[3]=p->GetSigmaZ2();
lp[4]=p->GetQ(); lp[4]/=kmip;
//Int_t lab[6];
lab[0]=p->GetLabel(0);lab[1]=p->GetLabel(1);lab[2]=p->GetLabel(2);
lab[3]=ndet;
Int_t label=lab[0];
if (label>=0) {
TParticle *part=(TParticle*)gAlice->Particle(label);
label=-3;
while (part->P() < 0.005) {
Int_t m=part->GetFirstMother();
if (m<0) {cerr<<"Primary momentum: "<<part->P()<<endl; break;}
label=m;
part=(TParticle*)gAlice->Particle(label);
}
if (lab[1]<0) lab[1]=label;
else if (lab[2]<0) lab[2]=label;
else cerr<<"No empty labels !\n";
}
new(cl[j]) AliITSclusterV2(lab,lp);
}
cTree->Fill(); clusters->Delete();
points->Delete();
}
cTree->Write();
cerr<<"Number of clusters: "<<nclusters<<endl;
delete cTree; delete clusters; delete points;
delete gAlice; gAlice=0;
in->Close();
out->Close();
return 0;
}
<commit_msg>Using pointers instead of arrays (Alpha)<commit_after>#ifndef __CINT__
#include <iostream.h>
#include "AliRun.h"
#include "AliITS.h"
#include "AliITSgeom.h"
#include "AliITSRecPoint.h"
#include "AliITSclusterV2.h"
#include "TFile.h"
#include "TTree.h"
#include "TParticle.h"
#endif
Int_t AliITSFindClustersV2(Char_t SlowOrFast='f') {
/****************************************************************
* This macro converts AliITSRecPoint(s) to AliITSclusterV2(s) *
****************************************************************/
cerr<<"AliITSRecPoint(s) -> AliITSclusterV2(s)...\n";
if (gAlice) {delete gAlice; gAlice=0;}
TFile *in=TFile::Open("galice.root");
if (!in->IsOpen()) { cerr<<"Can't open galice.root !\n"; return 1; }
if (!(gAlice=(AliRun*)in->Get("gAlice"))) {
cerr<<"Can't find gAlice !\n";
return 2;
}
gAlice->GetEvent(0);
AliITS *ITS = (AliITS*)gAlice->GetModule("ITS");
if (!ITS) { cerr<<"Can't find the ITS !\n"; return 3; }
AliITSgeom *geom=ITS->GetITSgeom();
TFile *out=TFile::Open("AliITSclustersV2.root","new");
if (!out->IsOpen()) {
cerr<<"Delete old AliITSclustersV2.root !\n";
return 4;
}
geom->Write();
TClonesArray *clusters=new TClonesArray("AliITSclusterV2",10000);
TTree *cTree=new TTree("TreeC_ITS_0","ITS clusters");
cTree->Branch("Clusters",&clusters);
TTree *pTree=gAlice->TreeR();
if (!pTree) { cerr<<"Can't get TreeR !\n"; return 5; }
TBranch *branch = 0;
if (SlowOrFast=='f') {
branch = pTree->GetBranch("ITSRecPointsF");
}
else {
branch = pTree->GetBranch("ITSRecPoints");
}
if (!branch) { cerr<<"Can't get ITSRecPoints branch !\n"; return 6; }
TClonesArray *points=new TClonesArray("AliITSRecPoint",10000);
branch->SetAddress(&points);
TClonesArray &cl=*clusters;
Int_t nclusters=0;
Int_t nentr=(Int_t)branch->GetEntries();
cerr<<"Number of entries: "<<nentr<<endl;
// Float_t lp[5]; Int_t lab[6]; //Why can't it be inside a loop ?
Float_t * lp = new Float_t[5];
Int_t * lab = new Int_t[6];
for (Int_t i=0; i<nentr; i++) {
points->Clear();
branch->GetEvent(i);
Int_t ncl=points->GetEntriesFast(); if (ncl==0){cTree->Fill();continue;}
Int_t lay,lad,det; geom->GetModuleId(i,lay,lad,det);
Float_t x,y,zshift; geom->GetTrans(lay,lad,det,x,y,zshift);
Double_t rot[9]; geom->GetRotMatrix(lay,lad,det,rot);
Double_t yshift = x*rot[0] + y*rot[1];
Int_t ndet=(lad-1)*geom->GetNdetectors(lay) + (det-1);
nclusters+=ncl;
Float_t kmip=1; // ADC->mip normalization factor for the SDD and SSD
if(lay==4 || lay==3){kmip=280.;};
if(lay==6 || lay==5){kmip=38.;};
for (Int_t j=0; j<ncl; j++) {
AliITSRecPoint *p=(AliITSRecPoint*)points->UncheckedAt(j);
//Float_t lp[5];
lp[0]=-p->GetX()-yshift; if (lay==1) lp[0]=-lp[0];
lp[1]=p->GetZ()+zshift;
lp[2]=p->GetSigmaX2();
lp[3]=p->GetSigmaZ2();
lp[4]=p->GetQ(); lp[4]/=kmip;
//Int_t lab[6];
lab[0]=p->GetLabel(0);lab[1]=p->GetLabel(1);lab[2]=p->GetLabel(2);
lab[3]=ndet;
Int_t label=lab[0];
if (label>=0) {
TParticle *part=(TParticle*)gAlice->Particle(label);
label=-3;
while (part->P() < 0.005) {
Int_t m=part->GetFirstMother();
if (m<0) {cerr<<"Primary momentum: "<<part->P()<<endl; break;}
label=m;
part=(TParticle*)gAlice->Particle(label);
}
if (lab[1]<0) lab[1]=label;
else if (lab[2]<0) lab[2]=label;
else cerr<<"No empty labels !\n";
}
new(cl[j]) AliITSclusterV2(lab,lp);
}
cTree->Fill(); clusters->Delete();
points->Delete();
}
cTree->Write();
cerr<<"Number of clusters: "<<nclusters<<endl;
delete [] lp;
delete [] lab;
delete cTree; delete clusters; delete points;
delete gAlice; gAlice=0;
in->Close();
out->Close();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef SERVER_HPP
#define SERVER_HPP
#include <map>
#include <memory>
#include <thread>
#include <mutex>
#include "alias_for_boost.hpp"
#include "users.hpp"
namespace fs{
class Server
{
public:
using SharedUserTable = std::shared_ptr<fs::Users>;
using SocketsMap = std::map<Tcp::endpoint, Tcp::socket>;
using SharedSocketsMap = std::shared_ptr<SocketsMap>;
using ThreadVector = std::vector<std::thread>;
Server():
Server(1234,5678)
{}
Server(unsigned short ctrl_port, unsigned short data_port):
user_table_{std::make_shared<fs::Users>("users")},
io_service_{},
ctrl_acceptor_{io_service_, Tcp::endpoint{Tcp::v4(), ctrl_port}},
data_acceptor_{io_service_, Tcp::endpoint{Tcp::v4(), data_port}},
data_sockets_{std::make_shared<SocketsMap>()},
threads_vector_{}
{
add_thread(make_thread_for_data_acceptor());
}
~Server()
{
wait_for_all_done();
}
private:
static std::mutex m;
SharedUserTable user_table_;
Io_service io_service_;
Acceptor ctrl_acceptor_;
Acceptor data_acceptor_;
SharedSocketsMap data_sockets_;
ThreadVector threads_vector_;
void add_thread(std::thread&& t)
{
threads_vector_.push_back(std::move(t));
}
void wait_for_all_done()
{
for(auto& t : threads_vector_) t.join();
}
std::thread make_thread_for_data_acceptor()
{
std::thread t
{
[this]{
std::cout << ">accepting data connections" << std::endl;
while(true)
{
Tcp::socket soc(io_service_);
data_acceptor_.accept(soc);
std::cout << ">new data socket generated" << std::endl;
using Element = std::pair<Tcp::endpoint, Tcp::socket>;
data_sockets_->insert(std::move(Element({soc.remote_endpoint(), std::move(soc)})));
}
}
};
return t;
}
};
std::mutex Server::m;
}//namespace
#endif // SERVER_HPP
<commit_msg> modified: ftp/server.hpp<commit_after>#ifndef SERVER_HPP
#define SERVER_HPP
#include <map>
#include <memory>
#include <thread>
#include <mutex>
#include "alias_for_boost.hpp"
#include "users.hpp"
namespace fs{
class Server
{
public:
using SharedUserTable = std::shared_ptr<fs::Users>;
using SocketsMap = std::map<Tcp::endpoint, Tcp::socket>;
using SharedSocketsMap = std::shared_ptr<SocketsMap>;
using ThreadVector = std::vector<std::thread>;
Server():
Server(1234,5678)
{}
Server(unsigned short ctrl_port, unsigned short data_port):
user_table_{std::make_shared<fs::Users>("users")},
io_service_{},
ctrl_acceptor_{io_service_, Tcp::endpoint{Tcp::v4(), ctrl_port}},
data_acceptor_{io_service_, Tcp::endpoint{Tcp::v4(), data_port}},
data_sockets_{std::make_shared<SocketsMap>()},
threads_vector_{}
{
add_thread(make_thread_for_data_acceptor());
}
~Server()
{
wait_for_all_done();
}
private:
static std::mutex m_;
SharedUserTable user_table_;
Io_service io_service_;
Acceptor ctrl_acceptor_;
Acceptor data_acceptor_;
SharedSocketsMap data_sockets_;
ThreadVector threads_vector_;
void add_thread(std::thread&& t)
{
threads_vector_.push_back(std::move(t));
}
void wait_for_all_done()
{
for(auto& t : threads_vector_) t.join();
}
std::thread make_thread_for_data_acceptor()
{
std::thread t
{
[this]{
std::cout << ">accepting data connections" << std::endl;
while(true)
{
Tcp::socket soc(io_service_);
data_acceptor_.accept(soc);
std::cout << ">new data socket generated" << std::endl;
using Element = std::pair<Tcp::endpoint, Tcp::socket>;
data_sockets_->insert(std::move(Element({soc.remote_endpoint(), std::move(soc)})));
}
}
};
return t;
}
};
std::mutex Server::m_;
}//namespace
#endif // SERVER_HPP
<|endoftext|> |
<commit_before><commit_msg>compilation fix<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/dom_ui/dom_ui_contents.h"
#include "chrome/browser/dom_ui/dom_ui.h"
#include "chrome/browser/dom_ui/history_ui.h"
#include "chrome/browser/navigation_entry.h"
#include "chrome/browser/render_view_host.h"
#include "chrome/common/resource_bundle.h"
// The scheme used for DOMUIContentses
// TODO(glen): Merge this with the scheme in chrome_url_data_manager
static const char kURLScheme[] = "chrome";
// The path used in internal URLs to thumbnail data.
static const char kThumbnailPath[] = "thumb";
// The path used in internal URLs to favicon data.
static const char kFavIconPath[] = "favicon";
///////////////////////////////////////////////////////////////////////////////
// FavIconSource
FavIconSource::FavIconSource(Profile* profile)
: DataSource(kFavIconPath, MessageLoop::current()), profile_(profile) {}
void FavIconSource::StartDataRequest(const std::string& path, int request_id) {
HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
if (hs) {
HistoryService::Handle handle;
if (path.size() > 8 && path.substr(0, 8) == "iconurl/") {
handle = hs->GetFavIcon(
GURL(path.substr(8)),
&cancelable_consumer_,
NewCallback(this, &FavIconSource::OnFavIconDataAvailable));
} else {
handle = hs->GetFavIconForURL(
GURL(path),
&cancelable_consumer_,
NewCallback(this, &FavIconSource::OnFavIconDataAvailable));
}
// Attach the ChromeURLDataManager request ID to the history request.
cancelable_consumer_.SetClientData(hs, handle, request_id);
} else {
SendResponse(request_id, NULL);
}
}
void FavIconSource::OnFavIconDataAvailable(
HistoryService::Handle request_handle,
bool know_favicon,
scoped_refptr<RefCountedBytes> data,
bool expired,
GURL icon_url) {
HistoryService* hs =
profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
int request_id = cancelable_consumer_.GetClientData(hs, request_handle);
if (know_favicon && data.get() && !data->data.empty()) {
// Forward the data along to the networking system.
SendResponse(request_id, data);
} else {
if (!default_favicon_.get()) {
default_favicon_ = new RefCountedBytes;
ResourceBundle::GetSharedInstance().LoadImageResourceBytes(
IDR_DEFAULT_FAVICON, &default_favicon_->data);
}
SendResponse(request_id, default_favicon_);
}
}
///////////////////////////////////////////////////////////////////////////////
// ThumbnailSource
ThumbnailSource::ThumbnailSource(Profile* profile)
: DataSource(kThumbnailPath, MessageLoop::current()), profile_(profile) {}
void ThumbnailSource::StartDataRequest(const std::string& path,
int request_id) {
HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
if (hs) {
HistoryService::Handle handle = hs->GetPageThumbnail(
GURL(path),
&cancelable_consumer_,
NewCallback(this, &ThumbnailSource::OnThumbnailDataAvailable));
// Attach the ChromeURLDataManager request ID to the history request.
cancelable_consumer_.SetClientData(hs, handle, request_id);
} else {
// Tell the caller that no thumbnail is available.
SendResponse(request_id, NULL);
}
}
void ThumbnailSource::OnThumbnailDataAvailable(
HistoryService::Handle request_handle,
scoped_refptr<RefCountedBytes> data) {
HistoryService* hs =
profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
int request_id = cancelable_consumer_.GetClientData(hs, request_handle);
// Forward the data along to the networking system.
if (data.get() && !data->data.empty()) {
SendResponse(request_id, data);
} else {
if (!default_thumbnail_.get()) {
default_thumbnail_ = new RefCountedBytes;
ResourceBundle::GetSharedInstance().LoadImageResourceBytes(
IDR_DEFAULT_THUMBNAIL, &default_thumbnail_->data);
}
SendResponse(request_id, default_thumbnail_);
}
}
///////////////////////////////////////////////////////////////////////////////
// DOMUIContents
// This is the top-level URL handler for chrome: URLs, and exposed in
// our header file. The individual DOMUIs provide a chrome:
// HTML source at the same host/path.
bool DOMUIContentsCanHandleURL(GURL* url,
TabContentsType* result_type) {
if (!url->SchemeIs(kURLScheme))
return false;
// TODO: remove once the debugger is using DOMContentsUI
if (url->host().compare("debugger") == 0)
return false;
*result_type = TAB_CONTENTS_DOM_UI;
return true;
}
DOMUIContents::DOMUIContents(Profile* profile,
SiteInstance* instance,
RenderViewHostFactory* render_view_factory)
: WebContents(profile,
instance,
render_view_factory,
MSG_ROUTING_NONE,
NULL),
current_ui_(NULL) {
set_type(TAB_CONTENTS_DOM_UI);
}
DOMUIContents::~DOMUIContents() {
if (current_ui_)
delete current_ui_;
}
bool DOMUIContents::CreateRenderViewForRenderManager(
RenderViewHost* render_view_host) {
// Be sure to enable DOM UI bindings on the RenderViewHost before
// CreateRenderView is called. Since a cross-site transition may be
// involved, this may or may not be the same RenderViewHost that we had when
// we were created.
render_view_host->AllowDOMUIBindings();
return WebContents::CreateRenderViewForRenderManager(render_view_host);
}
WebPreferences DOMUIContents::GetWebkitPrefs() {
// Get the users preferences then force image loading to always be on.
WebPreferences web_prefs = WebContents::GetWebkitPrefs();
web_prefs.loads_images_automatically = true;
web_prefs.javascript_enabled = true;
return web_prefs;
}
bool DOMUIContents::NavigateToPendingEntry(bool reload) {
if (current_ui_) {
// Shut down our existing DOMUI.
delete current_ui_;
current_ui_ = NULL;
}
// Set up a new DOMUI.
NavigationEntry* pending_entry = controller()->GetPendingEntry();
current_ui_ = GetDOMUIForURL(pending_entry->url());
if (current_ui_)
current_ui_->Init();
else
return false;
// Let WebContents do whatever it's meant to do.
return WebContents::NavigateToPendingEntry(reload);
}
DOMUI* DOMUIContents::GetDOMUIForURL(const GURL &url) {
if (url.host() == HistoryUI::GetBaseURL().host())
return new HistoryUI(this);
return NULL;
}
void DOMUIContents::ProcessDOMUIMessage(const std::string& message,
const std::string& content) {
DCHECK(current_ui_);
current_ui_->ProcessDOMUIMessage(message, content);
}
// static
const std::string DOMUIContents::GetScheme() {
return kURLScheme;
}<commit_msg>Let the debugger work again. Error was due to me not noticing the change in debugger URL.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/dom_ui/dom_ui_contents.h"
#include "chrome/browser/dom_ui/dom_ui.h"
#include "chrome/browser/dom_ui/history_ui.h"
#include "chrome/browser/navigation_entry.h"
#include "chrome/browser/render_view_host.h"
#include "chrome/common/resource_bundle.h"
// The scheme used for DOMUIContentses
// TODO(glen): Merge this with the scheme in chrome_url_data_manager
static const char kURLScheme[] = "chrome";
// The path used in internal URLs to thumbnail data.
static const char kThumbnailPath[] = "thumb";
// The path used in internal URLs to favicon data.
static const char kFavIconPath[] = "favicon";
///////////////////////////////////////////////////////////////////////////////
// FavIconSource
FavIconSource::FavIconSource(Profile* profile)
: DataSource(kFavIconPath, MessageLoop::current()), profile_(profile) {}
void FavIconSource::StartDataRequest(const std::string& path, int request_id) {
HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
if (hs) {
HistoryService::Handle handle;
if (path.size() > 8 && path.substr(0, 8) == "iconurl/") {
handle = hs->GetFavIcon(
GURL(path.substr(8)),
&cancelable_consumer_,
NewCallback(this, &FavIconSource::OnFavIconDataAvailable));
} else {
handle = hs->GetFavIconForURL(
GURL(path),
&cancelable_consumer_,
NewCallback(this, &FavIconSource::OnFavIconDataAvailable));
}
// Attach the ChromeURLDataManager request ID to the history request.
cancelable_consumer_.SetClientData(hs, handle, request_id);
} else {
SendResponse(request_id, NULL);
}
}
void FavIconSource::OnFavIconDataAvailable(
HistoryService::Handle request_handle,
bool know_favicon,
scoped_refptr<RefCountedBytes> data,
bool expired,
GURL icon_url) {
HistoryService* hs =
profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
int request_id = cancelable_consumer_.GetClientData(hs, request_handle);
if (know_favicon && data.get() && !data->data.empty()) {
// Forward the data along to the networking system.
SendResponse(request_id, data);
} else {
if (!default_favicon_.get()) {
default_favicon_ = new RefCountedBytes;
ResourceBundle::GetSharedInstance().LoadImageResourceBytes(
IDR_DEFAULT_FAVICON, &default_favicon_->data);
}
SendResponse(request_id, default_favicon_);
}
}
///////////////////////////////////////////////////////////////////////////////
// ThumbnailSource
ThumbnailSource::ThumbnailSource(Profile* profile)
: DataSource(kThumbnailPath, MessageLoop::current()), profile_(profile) {}
void ThumbnailSource::StartDataRequest(const std::string& path,
int request_id) {
HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
if (hs) {
HistoryService::Handle handle = hs->GetPageThumbnail(
GURL(path),
&cancelable_consumer_,
NewCallback(this, &ThumbnailSource::OnThumbnailDataAvailable));
// Attach the ChromeURLDataManager request ID to the history request.
cancelable_consumer_.SetClientData(hs, handle, request_id);
} else {
// Tell the caller that no thumbnail is available.
SendResponse(request_id, NULL);
}
}
void ThumbnailSource::OnThumbnailDataAvailable(
HistoryService::Handle request_handle,
scoped_refptr<RefCountedBytes> data) {
HistoryService* hs =
profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
int request_id = cancelable_consumer_.GetClientData(hs, request_handle);
// Forward the data along to the networking system.
if (data.get() && !data->data.empty()) {
SendResponse(request_id, data);
} else {
if (!default_thumbnail_.get()) {
default_thumbnail_ = new RefCountedBytes;
ResourceBundle::GetSharedInstance().LoadImageResourceBytes(
IDR_DEFAULT_THUMBNAIL, &default_thumbnail_->data);
}
SendResponse(request_id, default_thumbnail_);
}
}
///////////////////////////////////////////////////////////////////////////////
// DOMUIContents
// This is the top-level URL handler for chrome: URLs, and exposed in
// our header file. The individual DOMUIs provide a chrome:
// HTML source at the same host/path.
bool DOMUIContentsCanHandleURL(GURL* url,
TabContentsType* result_type) {
if (!url->SchemeIs(kURLScheme))
return false;
// TODO: remove once the debugger is using DOMContentsUI
if (url->host().compare("inspector") == 0 &&
url->path().compare("/debugger.html") == 0)
return false;
*result_type = TAB_CONTENTS_DOM_UI;
return true;
}
DOMUIContents::DOMUIContents(Profile* profile,
SiteInstance* instance,
RenderViewHostFactory* render_view_factory)
: WebContents(profile,
instance,
render_view_factory,
MSG_ROUTING_NONE,
NULL),
current_ui_(NULL) {
set_type(TAB_CONTENTS_DOM_UI);
}
DOMUIContents::~DOMUIContents() {
if (current_ui_)
delete current_ui_;
}
bool DOMUIContents::CreateRenderViewForRenderManager(
RenderViewHost* render_view_host) {
// Be sure to enable DOM UI bindings on the RenderViewHost before
// CreateRenderView is called. Since a cross-site transition may be
// involved, this may or may not be the same RenderViewHost that we had when
// we were created.
render_view_host->AllowDOMUIBindings();
return WebContents::CreateRenderViewForRenderManager(render_view_host);
}
WebPreferences DOMUIContents::GetWebkitPrefs() {
// Get the users preferences then force image loading to always be on.
WebPreferences web_prefs = WebContents::GetWebkitPrefs();
web_prefs.loads_images_automatically = true;
web_prefs.javascript_enabled = true;
return web_prefs;
}
bool DOMUIContents::NavigateToPendingEntry(bool reload) {
if (current_ui_) {
// Shut down our existing DOMUI.
delete current_ui_;
current_ui_ = NULL;
}
// Set up a new DOMUI.
NavigationEntry* pending_entry = controller()->GetPendingEntry();
current_ui_ = GetDOMUIForURL(pending_entry->url());
if (current_ui_)
current_ui_->Init();
else
return false;
// Let WebContents do whatever it's meant to do.
return WebContents::NavigateToPendingEntry(reload);
}
DOMUI* DOMUIContents::GetDOMUIForURL(const GURL &url) {
if (url.host() == HistoryUI::GetBaseURL().host())
return new HistoryUI(this);
return NULL;
}
void DOMUIContents::ProcessDOMUIMessage(const std::string& message,
const std::string& content) {
DCHECK(current_ui_);
current_ui_->ProcessDOMUIMessage(message, content);
}
// static
const std::string DOMUIContents::GetScheme() {
return kURLScheme;
}<|endoftext|> |
<commit_before><commit_msg>reindent<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2009 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 "chrome/browser/dom_ui/new_tab_ui.h"
#include "chrome/browser/renderer_host/test_render_view_host.h"
#include "chrome/common/url_constants.h"
#include "testing/gtest/include/gtest/gtest.h"
class DOMUITest : public RenderViewHostTestHarness {
public:
DOMUITest() {}
// Tests navigating with a DOM UI from a fresh (nothing pending or committed)
// state, through pending, committed, then another navigation. The first page
// ID that we should use is passed as a parameter. We'll use the next two
// values. This must be increasing for the life of the tests.
static void DoNavigationTest(WebContents* contents, int page_id) {
NavigationController* controller = contents->controller();
// Start a pending load.
GURL new_tab_url(chrome::kChromeUINewTabURL);
controller->LoadURL(new_tab_url, GURL(), PageTransition::LINK);
// The navigation entry should be pending with no committed entry.
ASSERT_TRUE(controller->GetPendingEntry());
ASSERT_FALSE(controller->GetLastCommittedEntry());
// Check the things the pending DOM UI should have set.
EXPECT_FALSE(contents->ShouldDisplayURL());
EXPECT_FALSE(contents->ShouldDisplayFavIcon());
EXPECT_TRUE(contents->IsBookmarkBarAlwaysVisible());
EXPECT_TRUE(contents->FocusLocationBarByDefault());
// Now commit the load.
static_cast<TestRenderViewHost*>(
contents->render_view_host())->SendNavigate(page_id, new_tab_url);
// The same flags should be set as before now that the load has committed.
EXPECT_FALSE(contents->ShouldDisplayURL());
EXPECT_FALSE(contents->ShouldDisplayFavIcon());
EXPECT_TRUE(contents->IsBookmarkBarAlwaysVisible());
EXPECT_TRUE(contents->FocusLocationBarByDefault());
// Start a pending navigation to a regular page.
GURL next_url("http://google.com/");
controller->LoadURL(next_url, GURL(), PageTransition::LINK);
// Check the flags. Some should reflect the new page (URL, title), some
// should reflect the old one (bookmark bar) until it has committed.
EXPECT_TRUE(contents->ShouldDisplayURL());
EXPECT_TRUE(contents->ShouldDisplayFavIcon());
EXPECT_TRUE(contents->IsBookmarkBarAlwaysVisible());
EXPECT_FALSE(contents->FocusLocationBarByDefault());
// Commit the regular page load. Note that we must send it to the "pending"
// RenderViewHost, since this transition will also cause a process
// transition, and our RVH pointer will be the "committed" one.
static_cast<TestRenderViewHost*>(
contents->render_manager()->pending_render_view_host())->SendNavigate(
page_id + 1, next_url);
// The state should now reflect a regular page.
EXPECT_TRUE(contents->ShouldDisplayURL());
EXPECT_TRUE(contents->ShouldDisplayFavIcon());
EXPECT_FALSE(contents->IsBookmarkBarAlwaysVisible());
EXPECT_FALSE(contents->FocusLocationBarByDefault());
}
private:
DISALLOW_COPY_AND_ASSIGN(DOMUITest);
};
// Tests that the New Tab Page flags are correctly set and propogated by
// WebContents when we first navigate to a DOM UI page, then to a standard
// non-DOM-UI page.
/* TODO(brettw) uncomment this test when it doesn't crash.
TEST_F(DOMUITest, DOMUIToStandard) {
DoNavigationTest(contents(), 1);
// Check for a non-first
WebContents* contents2 = new TestWebContents(profile_.get(), NULL,
&rvh_factory_);
DoNavigationTest(contents2, 101);
contents2->CloseContents();
}
*/
TEST_F(DOMUITest, DOMUIToDOMUI) {
// Do a load (this state is tested above).
GURL new_tab_url(chrome::kChromeUINewTabURL);
controller()->LoadURL(new_tab_url, GURL(), PageTransition::LINK);
rvh()->SendNavigate(1, new_tab_url);
// Start another pending load of the new tab page.
controller()->LoadURL(new_tab_url, GURL(), PageTransition::LINK);
rvh()->SendNavigate(2, new_tab_url);
// The flags should be the same as the non-pending state.
EXPECT_FALSE(contents()->ShouldDisplayURL());
EXPECT_FALSE(contents()->ShouldDisplayFavIcon());
EXPECT_TRUE(contents()->IsBookmarkBarAlwaysVisible());
EXPECT_TRUE(contents()->FocusLocationBarByDefault());
}
TEST_F(DOMUITest, StandardToDOMUI) {
// Start a pending navigation to a regular page.
GURL std_url("http://google.com/");
controller()->LoadURL(std_url, GURL(), PageTransition::LINK);
// The state should now reflect the default.
EXPECT_TRUE(contents()->ShouldDisplayURL());
EXPECT_TRUE(contents()->ShouldDisplayFavIcon());
EXPECT_FALSE(contents()->IsBookmarkBarAlwaysVisible());
EXPECT_FALSE(contents()->FocusLocationBarByDefault());
// Commit the load, the state should be the same.
rvh()->SendNavigate(1, std_url);
EXPECT_TRUE(contents()->ShouldDisplayURL());
EXPECT_TRUE(contents()->ShouldDisplayFavIcon());
EXPECT_FALSE(contents()->IsBookmarkBarAlwaysVisible());
EXPECT_FALSE(contents()->FocusLocationBarByDefault());
// Start a pending load for a DOMUI.
GURL new_tab_url(chrome::kChromeUINewTabURL);
controller()->LoadURL(new_tab_url, GURL(), PageTransition::LINK);
EXPECT_FALSE(contents()->ShouldDisplayURL());
EXPECT_FALSE(contents()->ShouldDisplayFavIcon());
EXPECT_FALSE(contents()->IsBookmarkBarAlwaysVisible());
EXPECT_TRUE(contents()->FocusLocationBarByDefault());
// Committing DOM UI is tested above.
}
<commit_msg>Fix the DOMUIToStandard unit test and uncomment it. The NavigationController wasn't getting hooked up properly to the WebContents, and we were getting the wrong RenderViewHost out of it later on in the test. Review URL: http://codereview.chromium.org/55045<commit_after>// Copyright (c) 2009 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 "chrome/browser/dom_ui/new_tab_ui.h"
#include "chrome/browser/renderer_host/test_render_view_host.h"
#include "chrome/common/url_constants.h"
#include "testing/gtest/include/gtest/gtest.h"
class DOMUITest : public RenderViewHostTestHarness {
public:
DOMUITest() {}
// Tests navigating with a DOM UI from a fresh (nothing pending or committed)
// state, through pending, committed, then another navigation. The first page
// ID that we should use is passed as a parameter. We'll use the next two
// values. This must be increasing for the life of the tests.
static void DoNavigationTest(WebContents* contents, int page_id) {
NavigationController* controller = contents->controller();
// Start a pending load.
GURL new_tab_url(chrome::kChromeUINewTabURL);
controller->LoadURL(new_tab_url, GURL(), PageTransition::LINK);
// The navigation entry should be pending with no committed entry.
ASSERT_TRUE(controller->GetPendingEntry());
ASSERT_FALSE(controller->GetLastCommittedEntry());
// Check the things the pending DOM UI should have set.
EXPECT_FALSE(contents->ShouldDisplayURL());
EXPECT_FALSE(contents->ShouldDisplayFavIcon());
EXPECT_TRUE(contents->IsBookmarkBarAlwaysVisible());
EXPECT_TRUE(contents->FocusLocationBarByDefault());
// Now commit the load.
static_cast<TestRenderViewHost*>(
contents->render_view_host())->SendNavigate(page_id, new_tab_url);
// The same flags should be set as before now that the load has committed.
EXPECT_FALSE(contents->ShouldDisplayURL());
EXPECT_FALSE(contents->ShouldDisplayFavIcon());
EXPECT_TRUE(contents->IsBookmarkBarAlwaysVisible());
EXPECT_TRUE(contents->FocusLocationBarByDefault());
// Start a pending navigation to a regular page.
GURL next_url("http://google.com/");
controller->LoadURL(next_url, GURL(), PageTransition::LINK);
// Check the flags. Some should reflect the new page (URL, title), some
// should reflect the old one (bookmark bar) until it has committed.
EXPECT_TRUE(contents->ShouldDisplayURL());
EXPECT_TRUE(contents->ShouldDisplayFavIcon());
EXPECT_TRUE(contents->IsBookmarkBarAlwaysVisible());
EXPECT_FALSE(contents->FocusLocationBarByDefault());
// Commit the regular page load. Note that we must send it to the "pending"
// RenderViewHost if there is one, since this transition will also cause a
// process transition, and our RVH pointer will be the "committed" one.
// In the second call to this function from DOMUIToStandard, it won't
// actually be pending, which is the point of this test.
if (contents->render_manager()->pending_render_view_host()) {
static_cast<TestRenderViewHost*>(
contents->render_manager()->pending_render_view_host())->SendNavigate(
page_id + 1, next_url);
} else {
static_cast<TestRenderViewHost*>(
contents->render_view_host())->SendNavigate(page_id + 1, next_url);
}
// The state should now reflect a regular page.
EXPECT_TRUE(contents->ShouldDisplayURL());
EXPECT_TRUE(contents->ShouldDisplayFavIcon());
EXPECT_FALSE(contents->IsBookmarkBarAlwaysVisible());
EXPECT_FALSE(contents->FocusLocationBarByDefault());
}
private:
DISALLOW_COPY_AND_ASSIGN(DOMUITest);
};
// Tests that the New Tab Page flags are correctly set and propogated by
// WebContents when we first navigate to a DOM UI page, then to a standard
// non-DOM-UI page.
TEST_F(DOMUITest, DOMUIToStandard) {
DoNavigationTest(contents(), 1);
// Test the case where we're not doing the initial navigation. This is
// slightly different than the very-first-navigation case since the
// SiteInstance will be the same (the original WebContents must still be
// alive), which will trigger different behavior in RenderViewHostManager.
WebContents* contents2 = new TestWebContents(profile_.get(), NULL,
&rvh_factory_);
NavigationController* controller2 =
new NavigationController(contents2, profile_.get());
contents2->set_controller(controller2);
DoNavigationTest(contents2, 101);
contents2->CloseContents();
}
TEST_F(DOMUITest, DOMUIToDOMUI) {
// Do a load (this state is tested above).
GURL new_tab_url(chrome::kChromeUINewTabURL);
controller()->LoadURL(new_tab_url, GURL(), PageTransition::LINK);
rvh()->SendNavigate(1, new_tab_url);
// Start another pending load of the new tab page.
controller()->LoadURL(new_tab_url, GURL(), PageTransition::LINK);
rvh()->SendNavigate(2, new_tab_url);
// The flags should be the same as the non-pending state.
EXPECT_FALSE(contents()->ShouldDisplayURL());
EXPECT_FALSE(contents()->ShouldDisplayFavIcon());
EXPECT_TRUE(contents()->IsBookmarkBarAlwaysVisible());
EXPECT_TRUE(contents()->FocusLocationBarByDefault());
}
TEST_F(DOMUITest, StandardToDOMUI) {
// Start a pending navigation to a regular page.
GURL std_url("http://google.com/");
controller()->LoadURL(std_url, GURL(), PageTransition::LINK);
// The state should now reflect the default.
EXPECT_TRUE(contents()->ShouldDisplayURL());
EXPECT_TRUE(contents()->ShouldDisplayFavIcon());
EXPECT_FALSE(contents()->IsBookmarkBarAlwaysVisible());
EXPECT_FALSE(contents()->FocusLocationBarByDefault());
// Commit the load, the state should be the same.
rvh()->SendNavigate(1, std_url);
EXPECT_TRUE(contents()->ShouldDisplayURL());
EXPECT_TRUE(contents()->ShouldDisplayFavIcon());
EXPECT_FALSE(contents()->IsBookmarkBarAlwaysVisible());
EXPECT_FALSE(contents()->FocusLocationBarByDefault());
// Start a pending load for a DOMUI.
GURL new_tab_url(chrome::kChromeUINewTabURL);
controller()->LoadURL(new_tab_url, GURL(), PageTransition::LINK);
EXPECT_FALSE(contents()->ShouldDisplayURL());
EXPECT_FALSE(contents()->ShouldDisplayFavIcon());
EXPECT_FALSE(contents()->IsBookmarkBarAlwaysVisible());
EXPECT_TRUE(contents()->FocusLocationBarByDefault());
// Committing DOM UI is tested above.
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 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.
//
// Download utility implementation
#include "chrome/browser/download/download_util.h"
#include <string>
#include "app/gfx/canvas.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/download/download_item_model.h"
#include "chrome/browser/download/download_manager.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "skia/ext/image_operations.h"
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/core/SkShader.h"
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
#include "app/os_exchange_data.h"
#endif
#if defined(OS_WIN)
#include "base/base_drag_source.h"
#include "views/drag_utils.h"
#endif
namespace download_util {
// How many times to cycle the complete animation. This should be an odd number
// so that the animation ends faded out.
static const int kCompleteAnimationCycles = 5;
// Download opening ------------------------------------------------------------
bool CanOpenDownload(DownloadItem* download) {
FilePath file_to_use = download->full_path();
if (!download->original_name().value().empty())
file_to_use = download->original_name();
const FilePath::StringType extension =
file_util::GetFileExtensionFromPath(file_to_use);
return !download->manager()->IsExecutable(extension);
}
void OpenDownload(DownloadItem* download) {
if (download->state() == DownloadItem::IN_PROGRESS) {
download->set_open_when_complete(!download->open_when_complete());
} else if (download->state() == DownloadItem::COMPLETE) {
download->NotifyObserversDownloadOpened();
download->manager()->OpenDownload(download, NULL);
}
}
// Download progress painting --------------------------------------------------
// Common bitmaps used for download progress animations. We load them once the
// first time we do a progress paint, then reuse them as they are always the
// same.
SkBitmap* g_foreground_16 = NULL;
SkBitmap* g_background_16 = NULL;
SkBitmap* g_foreground_32 = NULL;
SkBitmap* g_background_32 = NULL;
void PaintDownloadProgress(gfx::Canvas* canvas,
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
views::View* containing_view,
#endif
int origin_x,
int origin_y,
int start_angle,
int percent_done,
PaintDownloadProgressSize size) {
// Load up our common bitmaps
if (!g_background_16) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
g_foreground_16 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_16);
g_background_16 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_BACKGROUND_16);
g_foreground_32 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_32);
g_background_32 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_BACKGROUND_32);
}
SkBitmap* background = (size == BIG) ? g_background_32 : g_background_16;
SkBitmap* foreground = (size == BIG) ? g_foreground_32 : g_foreground_16;
const int kProgressIconSize = (size == BIG) ? kBigProgressIconSize :
kSmallProgressIconSize;
// We start by storing the bounds of the background and foreground bitmaps
// so that it is easy to mirror the bounds if the UI layout is RTL.
gfx::Rect background_bounds(origin_x, origin_y,
background->width(), background->height());
gfx::Rect foreground_bounds(origin_x, origin_y,
foreground->width(), foreground->height());
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
// Mirror the positions if necessary.
int mirrored_x = containing_view->MirroredLeftPointForRect(background_bounds);
background_bounds.set_x(mirrored_x);
mirrored_x = containing_view->MirroredLeftPointForRect(foreground_bounds);
foreground_bounds.set_x(mirrored_x);
#endif
// Draw the background progress image.
SkPaint background_paint;
canvas->DrawBitmapInt(*background,
background_bounds.x(),
background_bounds.y(),
background_paint);
// Layer the foreground progress image in an arc proportional to the download
// progress. The arc grows clockwise, starting in the midnight position, as
// the download progresses. However, if the download does not have known total
// size (the server didn't give us one), then we just spin an arc around until
// we're done.
float sweep_angle = 0.0;
float start_pos = static_cast<float>(kStartAngleDegrees);
if (percent_done < 0) {
sweep_angle = kUnknownAngleDegrees;
start_pos = static_cast<float>(start_angle);
} else if (percent_done > 0) {
sweep_angle = static_cast<float>(kMaxDegrees / 100.0 * percent_done);
}
// Set up an arc clipping region for the foreground image. Don't bother using
// a clipping region if it would round to 360 (really 0) degrees, since that
// would eliminate the foreground completely and be quite confusing (it would
// look like 0% complete when it should be almost 100%).
SkPaint foreground_paint;
if (sweep_angle < static_cast<float>(kMaxDegrees - 1)) {
SkRect oval;
oval.set(SkIntToScalar(foreground_bounds.x()),
SkIntToScalar(foreground_bounds.y()),
SkIntToScalar(foreground_bounds.x() + kProgressIconSize),
SkIntToScalar(foreground_bounds.y() + kProgressIconSize));
SkPath path;
path.arcTo(oval,
SkFloatToScalar(start_pos),
SkFloatToScalar(sweep_angle), false);
path.lineTo(SkIntToScalar(foreground_bounds.x() + kProgressIconSize / 2),
SkIntToScalar(foreground_bounds.y() + kProgressIconSize / 2));
SkShader* shader =
SkShader::CreateBitmapShader(*foreground,
SkShader::kClamp_TileMode,
SkShader::kClamp_TileMode);
SkMatrix shader_scale;
shader_scale.setTranslate(SkIntToScalar(foreground_bounds.x()),
SkIntToScalar(foreground_bounds.y()));
shader->setLocalMatrix(shader_scale);
foreground_paint.setShader(shader);
foreground_paint.setAntiAlias(true);
shader->unref();
canvas->drawPath(path, foreground_paint);
return;
}
canvas->DrawBitmapInt(*foreground,
foreground_bounds.x(),
foreground_bounds.y(),
foreground_paint);
}
void PaintDownloadComplete(gfx::Canvas* canvas,
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
views::View* containing_view,
#endif
int origin_x,
int origin_y,
double animation_progress,
PaintDownloadProgressSize size) {
// Load up our common bitmaps.
if (!g_foreground_16) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
g_foreground_16 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_16);
g_foreground_32 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_32);
}
SkBitmap* complete = (size == BIG) ? g_foreground_32 : g_foreground_16;
gfx::Rect complete_bounds(origin_x, origin_y,
complete->width(), complete->height());
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
// Mirror the positions if necessary.
complete_bounds.set_x(
containing_view->MirroredLeftPointForRect(complete_bounds));
#endif
// Start at full opacity, then loop back and forth five times before ending
// at zero opacity.
static const double PI = 3.141592653589793;
double opacity = sin(animation_progress * PI * kCompleteAnimationCycles +
PI/2) / 2 + 0.5;
SkRect bounds;
bounds.set(SkIntToScalar(complete_bounds.x()),
SkIntToScalar(complete_bounds.y()),
SkIntToScalar(complete_bounds.x() + complete_bounds.width()),
SkIntToScalar(complete_bounds.y() + complete_bounds.height()));
canvas->saveLayerAlpha(&bounds,
static_cast<int>(255.0 * opacity),
SkCanvas::kARGB_ClipLayer_SaveFlag);
canvas->drawARGB(0, 255, 255, 255, SkXfermode::kClear_Mode);
canvas->DrawBitmapInt(*complete, complete_bounds.x(), complete_bounds.y());
canvas->restore();
}
// Load a language dependent height so that the dangerous download confirmation
// message doesn't overlap with the download link label.
int GetBigProgressIconSize() {
static int big_progress_icon_size = 0;
if (big_progress_icon_size == 0) {
string16 locale_size_str =
WideToUTF16Hack(
l10n_util::GetString(IDS_DOWNLOAD_BIG_PROGRESS_SIZE));
bool rc = StringToInt(locale_size_str, &big_progress_icon_size);
if (!rc || big_progress_icon_size < kBigProgressIconSize) {
NOTREACHED();
big_progress_icon_size = kBigProgressIconSize;
}
}
return big_progress_icon_size;
}
int GetBigProgressIconOffset() {
return (GetBigProgressIconSize() - kBigIconSize) / 2;
}
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
// Download dragging
void DragDownload(const DownloadItem* download, SkBitmap* icon) {
#if defined(OS_WIN)
DCHECK(download);
// Set up our OLE machinery
scoped_refptr<OSExchangeData> data(new OSExchangeData);
if (icon)
drag_utils::CreateDragImageForFile(download->file_name().ToWStringHack(),
icon, data);
data->SetFilename(download->full_path().ToWStringHack());
scoped_refptr<BaseDragSource> drag_source(new BaseDragSource);
// Run the drag and drop loop
DWORD effects;
DoDragDrop(data.get(), drag_source.get(), DROPEFFECT_COPY | DROPEFFECT_LINK,
&effects);
#else
NOTIMPLEMENTED();
#endif
}
#endif
} // namespace download_util
<commit_msg>Commit patch for Pierre-Antoine LaFayette, original CL: http://codereview.chromium.org/164119<commit_after>// Copyright (c) 2009 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.
//
// Download utility implementation
#include "chrome/browser/download/download_util.h"
#include <string>
#include "app/gfx/canvas.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/download/download_item_model.h"
#include "chrome/browser/download/download_manager.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "net/base/mime_util.h"
#include "skia/ext/image_operations.h"
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/core/SkShader.h"
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
#include "app/os_exchange_data.h"
#endif
#if defined(OS_WIN)
#include "base/base_drag_source.h"
#include "views/drag_utils.h"
#endif
namespace download_util {
// How many times to cycle the complete animation. This should be an odd number
// so that the animation ends faded out.
static const int kCompleteAnimationCycles = 5;
// Download opening ------------------------------------------------------------
bool CanOpenDownload(DownloadItem* download) {
FilePath file_to_use = download->full_path();
if (!download->original_name().value().empty())
file_to_use = download->original_name();
const FilePath::StringType extension =
file_util::GetFileExtensionFromPath(file_to_use);
return !download->manager()->IsExecutable(extension);
}
void OpenDownload(DownloadItem* download) {
if (download->state() == DownloadItem::IN_PROGRESS) {
download->set_open_when_complete(!download->open_when_complete());
} else if (download->state() == DownloadItem::COMPLETE) {
download->NotifyObserversDownloadOpened();
download->manager()->OpenDownload(download, NULL);
}
}
// Download progress painting --------------------------------------------------
// Common bitmaps used for download progress animations. We load them once the
// first time we do a progress paint, then reuse them as they are always the
// same.
SkBitmap* g_foreground_16 = NULL;
SkBitmap* g_background_16 = NULL;
SkBitmap* g_foreground_32 = NULL;
SkBitmap* g_background_32 = NULL;
void PaintDownloadProgress(gfx::Canvas* canvas,
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
views::View* containing_view,
#endif
int origin_x,
int origin_y,
int start_angle,
int percent_done,
PaintDownloadProgressSize size) {
// Load up our common bitmaps
if (!g_background_16) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
g_foreground_16 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_16);
g_background_16 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_BACKGROUND_16);
g_foreground_32 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_32);
g_background_32 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_BACKGROUND_32);
}
SkBitmap* background = (size == BIG) ? g_background_32 : g_background_16;
SkBitmap* foreground = (size == BIG) ? g_foreground_32 : g_foreground_16;
const int kProgressIconSize = (size == BIG) ? kBigProgressIconSize :
kSmallProgressIconSize;
// We start by storing the bounds of the background and foreground bitmaps
// so that it is easy to mirror the bounds if the UI layout is RTL.
gfx::Rect background_bounds(origin_x, origin_y,
background->width(), background->height());
gfx::Rect foreground_bounds(origin_x, origin_y,
foreground->width(), foreground->height());
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
// Mirror the positions if necessary.
int mirrored_x = containing_view->MirroredLeftPointForRect(background_bounds);
background_bounds.set_x(mirrored_x);
mirrored_x = containing_view->MirroredLeftPointForRect(foreground_bounds);
foreground_bounds.set_x(mirrored_x);
#endif
// Draw the background progress image.
SkPaint background_paint;
canvas->DrawBitmapInt(*background,
background_bounds.x(),
background_bounds.y(),
background_paint);
// Layer the foreground progress image in an arc proportional to the download
// progress. The arc grows clockwise, starting in the midnight position, as
// the download progresses. However, if the download does not have known total
// size (the server didn't give us one), then we just spin an arc around until
// we're done.
float sweep_angle = 0.0;
float start_pos = static_cast<float>(kStartAngleDegrees);
if (percent_done < 0) {
sweep_angle = kUnknownAngleDegrees;
start_pos = static_cast<float>(start_angle);
} else if (percent_done > 0) {
sweep_angle = static_cast<float>(kMaxDegrees / 100.0 * percent_done);
}
// Set up an arc clipping region for the foreground image. Don't bother using
// a clipping region if it would round to 360 (really 0) degrees, since that
// would eliminate the foreground completely and be quite confusing (it would
// look like 0% complete when it should be almost 100%).
SkPaint foreground_paint;
if (sweep_angle < static_cast<float>(kMaxDegrees - 1)) {
SkRect oval;
oval.set(SkIntToScalar(foreground_bounds.x()),
SkIntToScalar(foreground_bounds.y()),
SkIntToScalar(foreground_bounds.x() + kProgressIconSize),
SkIntToScalar(foreground_bounds.y() + kProgressIconSize));
SkPath path;
path.arcTo(oval,
SkFloatToScalar(start_pos),
SkFloatToScalar(sweep_angle), false);
path.lineTo(SkIntToScalar(foreground_bounds.x() + kProgressIconSize / 2),
SkIntToScalar(foreground_bounds.y() + kProgressIconSize / 2));
SkShader* shader =
SkShader::CreateBitmapShader(*foreground,
SkShader::kClamp_TileMode,
SkShader::kClamp_TileMode);
SkMatrix shader_scale;
shader_scale.setTranslate(SkIntToScalar(foreground_bounds.x()),
SkIntToScalar(foreground_bounds.y()));
shader->setLocalMatrix(shader_scale);
foreground_paint.setShader(shader);
foreground_paint.setAntiAlias(true);
shader->unref();
canvas->drawPath(path, foreground_paint);
return;
}
canvas->DrawBitmapInt(*foreground,
foreground_bounds.x(),
foreground_bounds.y(),
foreground_paint);
}
void PaintDownloadComplete(gfx::Canvas* canvas,
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
views::View* containing_view,
#endif
int origin_x,
int origin_y,
double animation_progress,
PaintDownloadProgressSize size) {
// Load up our common bitmaps.
if (!g_foreground_16) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
g_foreground_16 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_16);
g_foreground_32 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_32);
}
SkBitmap* complete = (size == BIG) ? g_foreground_32 : g_foreground_16;
gfx::Rect complete_bounds(origin_x, origin_y,
complete->width(), complete->height());
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
// Mirror the positions if necessary.
complete_bounds.set_x(
containing_view->MirroredLeftPointForRect(complete_bounds));
#endif
// Start at full opacity, then loop back and forth five times before ending
// at zero opacity.
static const double PI = 3.141592653589793;
double opacity = sin(animation_progress * PI * kCompleteAnimationCycles +
PI/2) / 2 + 0.5;
SkRect bounds;
bounds.set(SkIntToScalar(complete_bounds.x()),
SkIntToScalar(complete_bounds.y()),
SkIntToScalar(complete_bounds.x() + complete_bounds.width()),
SkIntToScalar(complete_bounds.y() + complete_bounds.height()));
canvas->saveLayerAlpha(&bounds,
static_cast<int>(255.0 * opacity),
SkCanvas::kARGB_ClipLayer_SaveFlag);
canvas->drawARGB(0, 255, 255, 255, SkXfermode::kClear_Mode);
canvas->DrawBitmapInt(*complete, complete_bounds.x(), complete_bounds.y());
canvas->restore();
}
// Load a language dependent height so that the dangerous download confirmation
// message doesn't overlap with the download link label.
int GetBigProgressIconSize() {
static int big_progress_icon_size = 0;
if (big_progress_icon_size == 0) {
string16 locale_size_str =
WideToUTF16Hack(
l10n_util::GetString(IDS_DOWNLOAD_BIG_PROGRESS_SIZE));
bool rc = StringToInt(locale_size_str, &big_progress_icon_size);
if (!rc || big_progress_icon_size < kBigProgressIconSize) {
NOTREACHED();
big_progress_icon_size = kBigProgressIconSize;
}
}
return big_progress_icon_size;
}
int GetBigProgressIconOffset() {
return (GetBigProgressIconSize() - kBigIconSize) / 2;
}
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
// Download dragging
void DragDownload(const DownloadItem* download, SkBitmap* icon) {
#if defined(OS_WIN)
DCHECK(download);
// Set up our OLE machinery
scoped_refptr<OSExchangeData> data(new OSExchangeData);
const FilePath::StringType file_name = download->file_name().value();
if (icon)
drag_utils::CreateDragImageForFile(file_name, icon, data);
const FilePath full_path = download->full_path();
data->SetFilename(full_path.value());
std::string mime_type = download->mime_type();
if (mime_type.empty())
net::GetMimeTypeFromFile(full_path, &mime_type);
// Add URL so that we can load supported files when dragged to TabContents.
if (net::IsSupportedMimeType(mime_type))
data->SetURL(GURL(full_path.value()), file_name);
scoped_refptr<BaseDragSource> drag_source(new BaseDragSource);
// Run the drag and drop loop
DWORD effects;
DoDragDrop(data.get(), drag_source.get(), DROPEFFECT_COPY | DROPEFFECT_LINK,
&effects);
#else
NOTIMPLEMENTED();
#endif
}
#endif
} // namespace download_util
<|endoftext|> |
<commit_before>/*
* QueueCommand.cpp
*
* Created on: 22/05/2010
* Author: victor
*/
#include "QueueCommand.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/objects/player/FactionStatus.h"
#include "server/zone/objects/tangible/weapon/WeaponObject.h"
#include "server/zone/managers/combat/CombatManager.h"
QueueCommand::QueueCommand(const String& skillname, ZoneProcessServer* serv) : Logger() {
server = serv;
name = skillname;
nameCRC = skillname.hashCode();
maxRangeToTarget = 0;
commandGroup = 0;
stateMask = 0;
targetType = 0;
disabled = false;
addToQueue = false;
admin = false;
defaultTime = 0.f;
cooldown = 0;
defaultPriority = NORMAL;
setLogging(true);
setGlobalLogging(true);
setLoggingName("QueueCommand " + skillname);
}
/*
* Sets the invalid locomotion for this command.
* Parses the string from LUA's. Format: "4,12,13,"
*/
void QueueCommand::setInvalidLocomotions(const String& lStr) {
StringTokenizer tokenizer(lStr);
tokenizer.setDelimeter(",");
String token = "";
while (tokenizer.hasMoreTokens()) {
tokenizer.getStringToken(token);
if(!token.isEmpty())
invalidLocomotion.add(Integer::valueOf(token));
}
}
/*
* Checks each invalid locomotion with the player's current locomotion
*/
bool QueueCommand::checkInvalidLocomotions(CreatureObject* creature) const {
for (int i = 0; i < invalidLocomotion.size(); ++i) {
if (invalidLocomotion.get(i) == creature->getLocomotion())
return false;
}
return true;
}
void QueueCommand::onStateFail(CreatureObject* creature, uint32 actioncntr) const {
if (!addToQueue)
return;
uint64 states = stateMask & creature->getStateBitmask();
uint64 state = 1;
int num = 0;
while (num < 34) {
if (states & state) {
creature->clearQueueAction(actioncntr, 0, 5, num);
return;
}
state *= 2;
++num;
}
creature->error("unknown invalid state in onStateFail");
}
void QueueCommand::onLocomotionFail(CreatureObject* creature, uint32 actioncntr) const {
if (!checkInvalidLocomotions(creature))
creature->clearQueueAction(actioncntr, 0, 1, creature->getLocomotion());
}
/*
* Unsuccessful command completion alerts the player of the invalid state
*/
void QueueCommand::onFail(uint32 actioncntr, CreatureObject* creature, uint32 errorNumber) const {
StringIdChatParameter prm;
switch (errorNumber) {
case INVALIDSYNTAX:
creature->sendSystemMessage(getSyntax());
if (addToQueue)
creature->clearQueueAction(actioncntr);
break;
case INVALIDSTATE:
onStateFail(creature, actioncntr);
break;
case INVALIDLOCOMOTION:
onLocomotionFail(creature, actioncntr);
break;
case INVALIDTARGET:
if (addToQueue)
creature->clearQueueAction(actioncntr, 0, 3, 0);
break;
case INVALIDWEAPON: // this only gets returned from combat commands
switch (creature->getWeapon()->getAttackType()) {
case WeaponObject::RANGEDATTACK:
creature->sendSystemMessage("@cbt_spam:no_attack_ranged_single");
break;
case WeaponObject::MELEEATTACK:
creature->sendSystemMessage("@cbt_spam:no_attack_melee_single");
break;
default:
creature->sendSystemMessage("@cbt_spam:no_attack_wrong_weapon"); // Can't be done with this weapon
break;
}
if (addToQueue)
creature->clearQueueAction(actioncntr);
break;
case TOOFAR:
if (addToQueue)
creature->clearQueueAction(actioncntr, 0, 4, 0);
break;
case NOJEDIARMOR:
creature->sendSystemMessage("@jedi_spam:not_with_armor"); // You cannot use Force powers or lightsaber abilities while wearing armor.
if (addToQueue)
creature->clearQueueAction(actioncntr);
break;
case NOPRONE:
if (addToQueue)
creature->clearQueueAction(actioncntr, 0, 1, 7);
break;
case NOKNEELING:
if (addToQueue)
creature->clearQueueAction(actioncntr, 0, 1, 4);
break;
case INSUFFICIENTPERMISSION:
creature->sendSystemMessage("@error_message:insufficient_permissions"); //You do not have sufficient permissions to perform the requested action.
if (addToQueue)
creature->clearQueueAction(actioncntr);
break;
case TOOCLOSE:
prm.setStringId("combat_effects", "prone_ranged_too_close");
creature->sendSystemMessage(prm);
if (addToQueue)
creature->clearQueueAction(actioncntr);
break;
default:
if (addToQueue)
creature->clearQueueAction(actioncntr);
break;
}
}
void QueueCommand::onComplete(uint32 actioncntr, CreatureObject* player, float commandDuration) const {
if (!player->isPlayerCreature())
return;
if (addToQueue)
player->clearQueueAction(actioncntr, commandDuration);
}
int QueueCommand::doCommonMedicalCommandChecks(CreatureObject* creature) const {
if (!checkStateMask(creature))
return INVALIDSTATE;
if (!checkInvalidLocomotions(creature))
return INVALIDLOCOMOTION;
if (creature->hasAttackDelay() || !creature->checkPostureChangeDelay()) // no message associated with this
return GENERALERROR;
if (creature->isProne() || creature->isMeditating() || creature->isSwimming()) {
creature->sendSystemMessage("@error_message:wrong_state"); //You cannot complete that action while in your current state.
return GENERALERROR;
}
if (creature->isRidingMount()) {
creature->sendSystemMessage("@error_message:survey_on_mount"); //You cannot perform that action while mounted on a creature or driving a vehicle.
return GENERALERROR;
}
return SUCCESS;
}
void QueueCommand::checkForTef(CreatureObject* creature, CreatureObject* target) const {
if (!creature->isPlayerCreature() || creature == target)
return;
PlayerObject* ghost = creature->getPlayerObject().get();
if (ghost == NULL)
return;
if (target->isPlayerCreature()) {
PlayerObject* targetGhost = target->getPlayerObject().get();
if (!CombatManager::instance()->areInDuel(creature, target)
&& targetGhost != NULL && targetGhost->getFactionStatus() == FactionStatus::OVERT) {
ghost->updateLastPvpCombatActionTimestamp();
}
} else if (target->isPet()) {
ManagedReference<CreatureObject*> owner = target->getLinkedCreature().get();
if (owner != NULL && owner->isPlayerCreature()) {
PlayerObject* ownerGhost = owner->getPlayerObject().get();
if (!CombatManager::instance()->areInDuel(creature, owner)
&& ownerGhost != NULL && ownerGhost->getFactionStatus() == FactionStatus::OVERT) {
ghost->updateLastPvpCombatActionTimestamp();
}
}
}
}
<commit_msg>[Fixed] pvp healing only causes a tef if the target has a tef - mantis 6255<commit_after>/*
* QueueCommand.cpp
*
* Created on: 22/05/2010
* Author: victor
*/
#include "QueueCommand.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/objects/player/FactionStatus.h"
#include "server/zone/objects/tangible/weapon/WeaponObject.h"
#include "server/zone/managers/combat/CombatManager.h"
QueueCommand::QueueCommand(const String& skillname, ZoneProcessServer* serv) : Logger() {
server = serv;
name = skillname;
nameCRC = skillname.hashCode();
maxRangeToTarget = 0;
commandGroup = 0;
stateMask = 0;
targetType = 0;
disabled = false;
addToQueue = false;
admin = false;
defaultTime = 0.f;
cooldown = 0;
defaultPriority = NORMAL;
setLogging(true);
setGlobalLogging(true);
setLoggingName("QueueCommand " + skillname);
}
/*
* Sets the invalid locomotion for this command.
* Parses the string from LUA's. Format: "4,12,13,"
*/
void QueueCommand::setInvalidLocomotions(const String& lStr) {
StringTokenizer tokenizer(lStr);
tokenizer.setDelimeter(",");
String token = "";
while (tokenizer.hasMoreTokens()) {
tokenizer.getStringToken(token);
if(!token.isEmpty())
invalidLocomotion.add(Integer::valueOf(token));
}
}
/*
* Checks each invalid locomotion with the player's current locomotion
*/
bool QueueCommand::checkInvalidLocomotions(CreatureObject* creature) const {
for (int i = 0; i < invalidLocomotion.size(); ++i) {
if (invalidLocomotion.get(i) == creature->getLocomotion())
return false;
}
return true;
}
void QueueCommand::onStateFail(CreatureObject* creature, uint32 actioncntr) const {
if (!addToQueue)
return;
uint64 states = stateMask & creature->getStateBitmask();
uint64 state = 1;
int num = 0;
while (num < 34) {
if (states & state) {
creature->clearQueueAction(actioncntr, 0, 5, num);
return;
}
state *= 2;
++num;
}
creature->error("unknown invalid state in onStateFail");
}
void QueueCommand::onLocomotionFail(CreatureObject* creature, uint32 actioncntr) const {
if (!checkInvalidLocomotions(creature))
creature->clearQueueAction(actioncntr, 0, 1, creature->getLocomotion());
}
/*
* Unsuccessful command completion alerts the player of the invalid state
*/
void QueueCommand::onFail(uint32 actioncntr, CreatureObject* creature, uint32 errorNumber) const {
StringIdChatParameter prm;
switch (errorNumber) {
case INVALIDSYNTAX:
creature->sendSystemMessage(getSyntax());
if (addToQueue)
creature->clearQueueAction(actioncntr);
break;
case INVALIDSTATE:
onStateFail(creature, actioncntr);
break;
case INVALIDLOCOMOTION:
onLocomotionFail(creature, actioncntr);
break;
case INVALIDTARGET:
if (addToQueue)
creature->clearQueueAction(actioncntr, 0, 3, 0);
break;
case INVALIDWEAPON: // this only gets returned from combat commands
switch (creature->getWeapon()->getAttackType()) {
case WeaponObject::RANGEDATTACK:
creature->sendSystemMessage("@cbt_spam:no_attack_ranged_single");
break;
case WeaponObject::MELEEATTACK:
creature->sendSystemMessage("@cbt_spam:no_attack_melee_single");
break;
default:
creature->sendSystemMessage("@cbt_spam:no_attack_wrong_weapon"); // Can't be done with this weapon
break;
}
if (addToQueue)
creature->clearQueueAction(actioncntr);
break;
case TOOFAR:
if (addToQueue)
creature->clearQueueAction(actioncntr, 0, 4, 0);
break;
case NOJEDIARMOR:
creature->sendSystemMessage("@jedi_spam:not_with_armor"); // You cannot use Force powers or lightsaber abilities while wearing armor.
if (addToQueue)
creature->clearQueueAction(actioncntr);
break;
case NOPRONE:
if (addToQueue)
creature->clearQueueAction(actioncntr, 0, 1, 7);
break;
case NOKNEELING:
if (addToQueue)
creature->clearQueueAction(actioncntr, 0, 1, 4);
break;
case INSUFFICIENTPERMISSION:
creature->sendSystemMessage("@error_message:insufficient_permissions"); //You do not have sufficient permissions to perform the requested action.
if (addToQueue)
creature->clearQueueAction(actioncntr);
break;
case TOOCLOSE:
prm.setStringId("combat_effects", "prone_ranged_too_close");
creature->sendSystemMessage(prm);
if (addToQueue)
creature->clearQueueAction(actioncntr);
break;
default:
if (addToQueue)
creature->clearQueueAction(actioncntr);
break;
}
}
void QueueCommand::onComplete(uint32 actioncntr, CreatureObject* player, float commandDuration) const {
if (!player->isPlayerCreature())
return;
if (addToQueue)
player->clearQueueAction(actioncntr, commandDuration);
}
int QueueCommand::doCommonMedicalCommandChecks(CreatureObject* creature) const {
if (!checkStateMask(creature))
return INVALIDSTATE;
if (!checkInvalidLocomotions(creature))
return INVALIDLOCOMOTION;
if (creature->hasAttackDelay() || !creature->checkPostureChangeDelay()) // no message associated with this
return GENERALERROR;
if (creature->isProne() || creature->isMeditating() || creature->isSwimming()) {
creature->sendSystemMessage("@error_message:wrong_state"); //You cannot complete that action while in your current state.
return GENERALERROR;
}
if (creature->isRidingMount()) {
creature->sendSystemMessage("@error_message:survey_on_mount"); //You cannot perform that action while mounted on a creature or driving a vehicle.
return GENERALERROR;
}
return SUCCESS;
}
void QueueCommand::checkForTef(CreatureObject* creature, CreatureObject* target) const {
if (!creature->isPlayerCreature() || creature == target)
return;
PlayerObject* ghost = creature->getPlayerObject().get();
if (ghost == NULL)
return;
if (target->isPlayerCreature()) {
PlayerObject* targetGhost = target->getPlayerObject().get();
if (!CombatManager::instance()->areInDuel(creature, target)
&& targetGhost != NULL && targetGhost->getFactionStatus() == FactionStatus::OVERT && targetGhost->hasPvpTef()) {
ghost->updateLastPvpCombatActionTimestamp();
}
} else if (target->isPet()) {
ManagedReference<CreatureObject*> owner = target->getLinkedCreature().get();
if (owner != NULL && owner->isPlayerCreature()) {
PlayerObject* ownerGhost = owner->getPlayerObject().get();
if (!CombatManager::instance()->areInDuel(creature, owner)
&& ownerGhost != NULL && ownerGhost->getFactionStatus() == FactionStatus::OVERT && ownerGhost->hasPvpTef()) {
ghost->updateLastPvpCombatActionTimestamp();
}
}
}
}
<|endoftext|> |
<commit_before>#ifdef _MSC_VER
#include <vector>
#endif
#include <omp.h>
#include "aligned_malloc.h"
#include "uvg11_full.h"
#include "mkHalideBuf.h"
#include "scatter_gridder_w_dependent_dyn_1p_1gcf_halide.h"
using namespace std;
#define __tod(a, ...) reinterpret_cast<__VA_ARGS__ double *>(a)
const int over = 8;
void gridKernel_scatter_halide(
double scale
, double wstep
, int baselines
, const BlWMap bl_wp_map[/* baselines */]
, const int bl_supps[/* baselines */] // computed from previous
, complexd grids[]
// w-planes length array of pointers
// to [over][over][gcf_supp][gcf_supp] arrays
, const complexd * gcf[]
, const Double3 * _uvw[]
, const complexd * _vis[]
, int ts_ch
, int grid_pitch
, int grid_size
) {
auto gcf_buf = mkInterleavedHalideBufs<2, double>();
// FIXME: add an API
gcf_buf[0].extent[2] = gcf_buf[1].extent[2] =
gcf_buf[0].extent[3] = gcf_buf[1].extent[3] = over;
buffer_t uvw_buf = mkHalideBuf<3, double>(ts_ch);
buffer_t vis_buf = mkHalideBuf<2, double>(ts_ch);
#pragma omp parallel
{
int siz = grid_size*grid_pitch;
complexd * grid = grids + omp_get_thread_num() * siz;
memset(grid, 0, sizeof(complexd) * siz);
buffer_t grid_buf = mkHalideBufPadded<2>(__tod(grid), grid_size, grid_pitch-grid_size);
#pragma omp for schedule(dynamic,23)
for(int bl = 0; bl < baselines; bl++){
setHalideBuf(__tod(_uvw[bl], const), uvw_buf);
setHalideBuf(__tod(_vis[bl], const), vis_buf);
int curr_wp = bl_wp_map[bl].wp;
setInterleavedHalideBufs(gcf[curr_wp], gcf_buf);
int supp = bl_supps[curr_wp];
// FIXME: add an API
gcf_buf[0].extent[0] = gcf_buf[0].extent[1] =
gcf_buf[1].extent[0] = gcf_buf[1].extent[1] = supp;
set_strides(&gcf_buf[0]);
set_strides(&gcf_buf[1]);
uvg11_full(
scale
, wstep
, ts_ch
, &uvw_buf
, &vis_buf
, supp
, &gcf_buf[0]
, &gcf_buf[1]
, &grid_buf
);
}
}
}
inline
void addGrids(
complexd dst[]
, const complexd srcs[]
, int nthreads
, int grid_pitch
, int grid_size
)
{
int siz = grid_size*grid_pitch;
#pragma omp parallel for
for (int i = 0; size_t(i) < siz*sizeof(complexd)/__MMSIZE; i++) {
__mdType sum = asMdpc(srcs)[i];
// __m256d sum = _mm256_loadu_pd(reinterpret_cast<const double*>(as256pc(srcs)+i));
for (int g = 1; g < nthreads; g ++)
sum = _mm_add_pd(sum, asMdpc(srcs + g * siz)[i]);
asMdp(dst)[i] = sum;
}
}
void gridKernel_scatter_halide_full(
double scale
, double wstep
, int baselines
, const BlWMap bl_wp_map[/* baselines */]
, const int bl_supps[/* baselines */] // computed from previous
, complexd grid[]
// w-planes length array of pointers
// to [over][over][gcf_supp][gcf_supp] arrays
, const complexd * gcf[]
, const Double3 * uvw[]
, const complexd * vis[]
, int ts_ch
, int grid_pitch
, int grid_size
) {
int siz = grid_size*grid_pitch;
int nthreads;
#pragma omp parallel
#pragma omp single
nthreads = omp_get_num_threads();
// Nullify incoming grid, allocate thread-local grids
memset(grid, 0, sizeof(complexd) * siz);
complexd * tmpgrids = alignedMallocArray<complexd>(siz * nthreads, 32);
gridKernel_scatter_halide(
scale
, wstep
, baselines
, bl_wp_map
, bl_supps
, tmpgrids
, gcf
, uvw
, vis
, ts_ch
, grid_pitch
, grid_size
);
addGrids(grid, tmpgrids, nthreads, grid_pitch, grid_size);
_aligned_free(tmpgrids);
}
<commit_msg>Stupid bug in gridder wrapper.<commit_after>#ifdef _MSC_VER
#include <vector>
#endif
#include <omp.h>
#include "aligned_malloc.h"
#include "uvg11_full.h"
#include "mkHalideBuf.h"
#include "scatter_gridder_w_dependent_dyn_1p_1gcf_halide.h"
using namespace std;
#define __tod(a, ...) reinterpret_cast<__VA_ARGS__ double *>(a)
const int over = 8;
void gridKernel_scatter_halide(
double scale
, double wstep
, int baselines
, const BlWMap bl_wp_map[/* baselines */]
, const int bl_supps[/* baselines */] // computed from previous
, complexd grids[]
// w-planes length array of pointers
// to [over][over][gcf_supp][gcf_supp] arrays
, const complexd * gcf[]
, const Double3 * _uvw[]
, const complexd * _vis[]
, int ts_ch
, int grid_pitch
, int grid_size
) {
auto gcf_buf = mkInterleavedHalideBufs<2, double>();
// FIXME: add an API
gcf_buf[0].extent[2] = gcf_buf[1].extent[2] =
gcf_buf[0].extent[3] = gcf_buf[1].extent[3] = over;
buffer_t uvw_buf = mkHalideBuf<3, double>(ts_ch);
buffer_t vis_buf = mkHalideBuf<2, double>(ts_ch);
#pragma omp parallel
{
int siz = grid_size*grid_pitch;
complexd * grid = grids + omp_get_thread_num() * siz;
memset(grid, 0, sizeof(complexd) * siz);
buffer_t grid_buf = mkHalideBufPadded<2>(__tod(grid), grid_size, grid_pitch-grid_size);
#pragma omp for schedule(dynamic,23)
for(int bl = 0; bl < baselines; bl++){
setHalideBuf(__tod(_uvw[bl], const), uvw_buf);
setHalideBuf(__tod(_vis[bl], const), vis_buf);
int curr_wp = bl_wp_map[bl].wp;
setInterleavedHalideBufs(gcf[curr_wp], gcf_buf);
int supp = bl_supps[bl];
// FIXME: add an API
gcf_buf[0].extent[0] = gcf_buf[0].extent[1] =
gcf_buf[1].extent[0] = gcf_buf[1].extent[1] = supp;
set_strides(&gcf_buf[0]);
set_strides(&gcf_buf[1]);
uvg11_full(
scale
, wstep
, ts_ch
, &uvw_buf
, &vis_buf
, supp
, &gcf_buf[0]
, &gcf_buf[1]
, &grid_buf
);
}
}
}
inline
void addGrids(
complexd dst[]
, const complexd srcs[]
, int nthreads
, int grid_pitch
, int grid_size
)
{
int siz = grid_size*grid_pitch;
#pragma omp parallel for
for (int i = 0; size_t(i) < siz*sizeof(complexd)/__MMSIZE; i++) {
__mdType sum = asMdpc(srcs)[i];
// __m256d sum = _mm256_loadu_pd(reinterpret_cast<const double*>(as256pc(srcs)+i));
for (int g = 1; g < nthreads; g ++)
sum = _mm_add_pd(sum, asMdpc(srcs + g * siz)[i]);
asMdp(dst)[i] = sum;
}
}
void gridKernel_scatter_halide_full(
double scale
, double wstep
, int baselines
, const BlWMap bl_wp_map[/* baselines */]
, const int bl_supps[/* baselines */] // computed from previous
, complexd grid[]
// w-planes length array of pointers
// to [over][over][gcf_supp][gcf_supp] arrays
, const complexd * gcf[]
, const Double3 * uvw[]
, const complexd * vis[]
, int ts_ch
, int grid_pitch
, int grid_size
) {
int siz = grid_size*grid_pitch;
int nthreads;
#pragma omp parallel
#pragma omp single
nthreads = omp_get_num_threads();
// Nullify incoming grid, allocate thread-local grids
memset(grid, 0, sizeof(complexd) * siz);
complexd * tmpgrids = alignedMallocArray<complexd>(siz * nthreads, 32);
gridKernel_scatter_halide(
scale
, wstep
, baselines
, bl_wp_map
, bl_supps
, tmpgrids
, gcf
, uvw
, vis
, ts_ch
, grid_pitch
, grid_size
);
addGrids(grid, tmpgrids, nthreads, grid_pitch, grid_size);
_aligned_free(tmpgrids);
}
<|endoftext|> |
<commit_before><commit_msg>Fallback to RSockets if cert exchange fails<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2011 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 "chrome/browser/prefs/pref_value_store.h"
#include "chrome/browser/prefs/pref_notifier.h"
PrefValueStore::PrefStoreKeeper::PrefStoreKeeper()
: pref_value_store_(NULL),
type_(PrefValueStore::INVALID_STORE) {
}
PrefValueStore::PrefStoreKeeper::~PrefStoreKeeper() {
if (pref_store_.get())
pref_store_->RemoveObserver(this);
}
void PrefValueStore::PrefStoreKeeper::Initialize(
PrefValueStore* store,
PrefStore* pref_store,
PrefValueStore::PrefStoreType type) {
if (pref_store_.get())
pref_store_->RemoveObserver(this);
type_ = type;
pref_value_store_ = store;
pref_store_ = pref_store;
if (pref_store_.get())
pref_store_->AddObserver(this);
}
void PrefValueStore::PrefStoreKeeper::OnPrefValueChanged(
const std::string& key) {
pref_value_store_->OnPrefValueChanged(type_, key);
}
void PrefValueStore::PrefStoreKeeper::OnInitializationCompleted() {
pref_value_store_->OnInitializationCompleted(type_);
}
PrefValueStore::PrefValueStore(PrefStore* managed_platform_prefs,
PrefStore* device_management_prefs,
PrefStore* extension_prefs,
PrefStore* command_line_prefs,
PrefStore* user_prefs,
PrefStore* recommended_prefs,
PrefStore* default_prefs,
PrefNotifier* pref_notifier)
: pref_notifier_(pref_notifier) {
InitPrefStore(MANAGED_PLATFORM_STORE, managed_platform_prefs);
InitPrefStore(DEVICE_MANAGEMENT_STORE, device_management_prefs);
InitPrefStore(EXTENSION_STORE, extension_prefs);
InitPrefStore(COMMAND_LINE_STORE, command_line_prefs);
InitPrefStore(USER_STORE, user_prefs);
InitPrefStore(RECOMMENDED_STORE, recommended_prefs);
InitPrefStore(DEFAULT_STORE, default_prefs);
CheckInitializationCompleted();
}
PrefValueStore::~PrefValueStore() {}
PrefValueStore* PrefValueStore::CloneAndSpecialize(
PrefStore* managed_platform_prefs,
PrefStore* device_management_prefs,
PrefStore* extension_prefs,
PrefStore* command_line_prefs,
PrefStore* user_prefs,
PrefStore* recommended_prefs,
PrefStore* default_prefs,
PrefNotifier* pref_notifier) {
DCHECK(pref_notifier);
if (!managed_platform_prefs)
managed_platform_prefs = GetPrefStore(MANAGED_PLATFORM_STORE);
if (!device_management_prefs)
device_management_prefs = GetPrefStore(DEVICE_MANAGEMENT_STORE);
if (!extension_prefs)
extension_prefs = GetPrefStore(EXTENSION_STORE);
if (!command_line_prefs)
command_line_prefs = GetPrefStore(COMMAND_LINE_STORE);
if (!user_prefs)
user_prefs = GetPrefStore(USER_STORE);
if (!recommended_prefs)
recommended_prefs = GetPrefStore(RECOMMENDED_STORE);
if (!default_prefs)
default_prefs = GetPrefStore(DEFAULT_STORE);
return new PrefValueStore(
managed_platform_prefs, device_management_prefs, extension_prefs,
command_line_prefs, user_prefs, recommended_prefs, default_prefs,
pref_notifier);
}
bool PrefValueStore::GetValue(const std::string& name,
Value::ValueType type,
Value** out_value) const {
*out_value = NULL;
// Check the |PrefStore|s in order of their priority from highest to lowest
// to find the value of the preference described by the given preference name.
for (size_t i = 0; i <= PREF_STORE_TYPE_MAX; ++i) {
if (GetValueFromStore(name.c_str(), static_cast<PrefStoreType>(i),
out_value)) {
if (!(*out_value)->IsType(type)) {
LOG(WARNING) << "Expected type for " << name << " is " << type
<< " but got " << (*out_value)->GetType()
<< " in store " << i;
continue;
}
return true;
}
}
return false;
}
void PrefValueStore::NotifyPrefChanged(
const char* path,
PrefValueStore::PrefStoreType new_store) {
DCHECK(new_store != INVALID_STORE);
bool changed = true;
// Replying that the pref has changed in case the new store is invalid may
// cause problems, but it's the safer choice.
if (new_store != INVALID_STORE) {
PrefStoreType controller = ControllingPrefStoreForPref(path);
DCHECK(controller != INVALID_STORE);
// If the pref is controlled by a higher-priority store, its effective value
// cannot have changed.
if (controller != INVALID_STORE &&
controller < new_store) {
changed = false;
}
}
if (changed)
pref_notifier_->OnPreferenceChanged(path);
}
bool PrefValueStore::PrefValueInManagedPlatformStore(const char* name) const {
return PrefValueInStore(name, MANAGED_PLATFORM_STORE);
}
bool PrefValueStore::PrefValueInDeviceManagementStore(const char* name) const {
return PrefValueInStore(name, DEVICE_MANAGEMENT_STORE);
}
bool PrefValueStore::PrefValueInExtensionStore(const char* name) const {
return PrefValueInStore(name, EXTENSION_STORE);
}
bool PrefValueStore::PrefValueInUserStore(const char* name) const {
return PrefValueInStore(name, USER_STORE);
}
bool PrefValueStore::PrefValueFromExtensionStore(const char* name) const {
return ControllingPrefStoreForPref(name) == EXTENSION_STORE;
}
bool PrefValueStore::PrefValueFromUserStore(const char* name) const {
return ControllingPrefStoreForPref(name) == USER_STORE;
}
bool PrefValueStore::PrefValueFromDefaultStore(const char* name) const {
return ControllingPrefStoreForPref(name) == DEFAULT_STORE;
}
bool PrefValueStore::PrefValueUserModifiable(const char* name) const {
PrefStoreType effective_store = ControllingPrefStoreForPref(name);
return effective_store >= USER_STORE ||
effective_store == INVALID_STORE;
}
bool PrefValueStore::PrefValueInStore(
const char* name,
PrefValueStore::PrefStoreType store) const {
// Declare a temp Value* and call GetValueFromStore,
// ignoring the output value.
Value* tmp_value = NULL;
return GetValueFromStore(name, store, &tmp_value);
}
bool PrefValueStore::PrefValueInStoreRange(
const char* name,
PrefValueStore::PrefStoreType first_checked_store,
PrefValueStore::PrefStoreType last_checked_store) const {
if (first_checked_store > last_checked_store) {
NOTREACHED();
return false;
}
for (size_t i = first_checked_store;
i <= static_cast<size_t>(last_checked_store); ++i) {
if (PrefValueInStore(name, static_cast<PrefStoreType>(i)))
return true;
}
return false;
}
PrefValueStore::PrefStoreType PrefValueStore::ControllingPrefStoreForPref(
const char* name) const {
for (size_t i = 0; i <= PREF_STORE_TYPE_MAX; ++i) {
if (PrefValueInStore(name, static_cast<PrefStoreType>(i)))
return static_cast<PrefStoreType>(i);
}
return INVALID_STORE;
}
bool PrefValueStore::GetValueFromStore(const char* name,
PrefValueStore::PrefStoreType store_type,
Value** out_value) const {
// Only return true if we find a value and it is the correct type, so stale
// values with the incorrect type will be ignored.
const PrefStore* store = GetPrefStore(static_cast<PrefStoreType>(store_type));
if (store) {
switch (store->GetValue(name, out_value)) {
case PrefStore::READ_USE_DEFAULT:
store = GetPrefStore(DEFAULT_STORE);
if (!store || store->GetValue(name, out_value) != PrefStore::READ_OK) {
*out_value = NULL;
return false;
}
// Fall through...
case PrefStore::READ_OK:
return true;
case PrefStore::READ_NO_VALUE:
break;
}
}
// No valid value found for the given preference name: set the return false.
*out_value = NULL;
return false;
}
void PrefValueStore::OnPrefValueChanged(PrefValueStore::PrefStoreType type,
const std::string& key) {
NotifyPrefChanged(key.c_str(), type);
}
void PrefValueStore::OnInitializationCompleted(
PrefValueStore::PrefStoreType type) {
CheckInitializationCompleted();
}
void PrefValueStore::InitPrefStore(PrefValueStore::PrefStoreType type,
PrefStore* pref_store) {
pref_stores_[type].Initialize(this, pref_store, type);
}
void PrefValueStore::CheckInitializationCompleted() {
for (size_t i = 0; i <= PREF_STORE_TYPE_MAX; ++i) {
scoped_refptr<PrefStore> store =
GetPrefStore(static_cast<PrefStoreType>(i));
if (store && !store->IsInitializationComplete())
return;
}
pref_notifier_->OnInitializationCompleted();
}
<commit_msg>Simplified PrefValueStore::NotifyPrefChanged.<commit_after>// Copyright (c) 2011 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 "chrome/browser/prefs/pref_value_store.h"
#include "chrome/browser/prefs/pref_notifier.h"
PrefValueStore::PrefStoreKeeper::PrefStoreKeeper()
: pref_value_store_(NULL),
type_(PrefValueStore::INVALID_STORE) {
}
PrefValueStore::PrefStoreKeeper::~PrefStoreKeeper() {
if (pref_store_.get())
pref_store_->RemoveObserver(this);
}
void PrefValueStore::PrefStoreKeeper::Initialize(
PrefValueStore* store,
PrefStore* pref_store,
PrefValueStore::PrefStoreType type) {
if (pref_store_.get())
pref_store_->RemoveObserver(this);
type_ = type;
pref_value_store_ = store;
pref_store_ = pref_store;
if (pref_store_.get())
pref_store_->AddObserver(this);
}
void PrefValueStore::PrefStoreKeeper::OnPrefValueChanged(
const std::string& key) {
pref_value_store_->OnPrefValueChanged(type_, key);
}
void PrefValueStore::PrefStoreKeeper::OnInitializationCompleted() {
pref_value_store_->OnInitializationCompleted(type_);
}
PrefValueStore::PrefValueStore(PrefStore* managed_platform_prefs,
PrefStore* device_management_prefs,
PrefStore* extension_prefs,
PrefStore* command_line_prefs,
PrefStore* user_prefs,
PrefStore* recommended_prefs,
PrefStore* default_prefs,
PrefNotifier* pref_notifier)
: pref_notifier_(pref_notifier) {
InitPrefStore(MANAGED_PLATFORM_STORE, managed_platform_prefs);
InitPrefStore(DEVICE_MANAGEMENT_STORE, device_management_prefs);
InitPrefStore(EXTENSION_STORE, extension_prefs);
InitPrefStore(COMMAND_LINE_STORE, command_line_prefs);
InitPrefStore(USER_STORE, user_prefs);
InitPrefStore(RECOMMENDED_STORE, recommended_prefs);
InitPrefStore(DEFAULT_STORE, default_prefs);
CheckInitializationCompleted();
}
PrefValueStore::~PrefValueStore() {}
PrefValueStore* PrefValueStore::CloneAndSpecialize(
PrefStore* managed_platform_prefs,
PrefStore* device_management_prefs,
PrefStore* extension_prefs,
PrefStore* command_line_prefs,
PrefStore* user_prefs,
PrefStore* recommended_prefs,
PrefStore* default_prefs,
PrefNotifier* pref_notifier) {
DCHECK(pref_notifier);
if (!managed_platform_prefs)
managed_platform_prefs = GetPrefStore(MANAGED_PLATFORM_STORE);
if (!device_management_prefs)
device_management_prefs = GetPrefStore(DEVICE_MANAGEMENT_STORE);
if (!extension_prefs)
extension_prefs = GetPrefStore(EXTENSION_STORE);
if (!command_line_prefs)
command_line_prefs = GetPrefStore(COMMAND_LINE_STORE);
if (!user_prefs)
user_prefs = GetPrefStore(USER_STORE);
if (!recommended_prefs)
recommended_prefs = GetPrefStore(RECOMMENDED_STORE);
if (!default_prefs)
default_prefs = GetPrefStore(DEFAULT_STORE);
return new PrefValueStore(
managed_platform_prefs, device_management_prefs, extension_prefs,
command_line_prefs, user_prefs, recommended_prefs, default_prefs,
pref_notifier);
}
bool PrefValueStore::GetValue(const std::string& name,
Value::ValueType type,
Value** out_value) const {
*out_value = NULL;
// Check the |PrefStore|s in order of their priority from highest to lowest
// to find the value of the preference described by the given preference name.
for (size_t i = 0; i <= PREF_STORE_TYPE_MAX; ++i) {
if (GetValueFromStore(name.c_str(), static_cast<PrefStoreType>(i),
out_value)) {
if (!(*out_value)->IsType(type)) {
LOG(WARNING) << "Expected type for " << name << " is " << type
<< " but got " << (*out_value)->GetType()
<< " in store " << i;
continue;
}
return true;
}
}
return false;
}
void PrefValueStore::NotifyPrefChanged(
const char* path,
PrefValueStore::PrefStoreType new_store) {
DCHECK(new_store != INVALID_STORE);
// If the pref is controlled by a higher-priority store, its effective value
// cannot have changed.
PrefStoreType controller = ControllingPrefStoreForPref(path);
if (controller == INVALID_STORE || controller >= new_store)
pref_notifier_->OnPreferenceChanged(path);
}
bool PrefValueStore::PrefValueInManagedPlatformStore(const char* name) const {
return PrefValueInStore(name, MANAGED_PLATFORM_STORE);
}
bool PrefValueStore::PrefValueInDeviceManagementStore(const char* name) const {
return PrefValueInStore(name, DEVICE_MANAGEMENT_STORE);
}
bool PrefValueStore::PrefValueInExtensionStore(const char* name) const {
return PrefValueInStore(name, EXTENSION_STORE);
}
bool PrefValueStore::PrefValueInUserStore(const char* name) const {
return PrefValueInStore(name, USER_STORE);
}
bool PrefValueStore::PrefValueFromExtensionStore(const char* name) const {
return ControllingPrefStoreForPref(name) == EXTENSION_STORE;
}
bool PrefValueStore::PrefValueFromUserStore(const char* name) const {
return ControllingPrefStoreForPref(name) == USER_STORE;
}
bool PrefValueStore::PrefValueFromDefaultStore(const char* name) const {
return ControllingPrefStoreForPref(name) == DEFAULT_STORE;
}
bool PrefValueStore::PrefValueUserModifiable(const char* name) const {
PrefStoreType effective_store = ControllingPrefStoreForPref(name);
return effective_store >= USER_STORE ||
effective_store == INVALID_STORE;
}
bool PrefValueStore::PrefValueInStore(
const char* name,
PrefValueStore::PrefStoreType store) const {
// Declare a temp Value* and call GetValueFromStore,
// ignoring the output value.
Value* tmp_value = NULL;
return GetValueFromStore(name, store, &tmp_value);
}
bool PrefValueStore::PrefValueInStoreRange(
const char* name,
PrefValueStore::PrefStoreType first_checked_store,
PrefValueStore::PrefStoreType last_checked_store) const {
if (first_checked_store > last_checked_store) {
NOTREACHED();
return false;
}
for (size_t i = first_checked_store;
i <= static_cast<size_t>(last_checked_store); ++i) {
if (PrefValueInStore(name, static_cast<PrefStoreType>(i)))
return true;
}
return false;
}
PrefValueStore::PrefStoreType PrefValueStore::ControllingPrefStoreForPref(
const char* name) const {
for (size_t i = 0; i <= PREF_STORE_TYPE_MAX; ++i) {
if (PrefValueInStore(name, static_cast<PrefStoreType>(i)))
return static_cast<PrefStoreType>(i);
}
return INVALID_STORE;
}
bool PrefValueStore::GetValueFromStore(const char* name,
PrefValueStore::PrefStoreType store_type,
Value** out_value) const {
// Only return true if we find a value and it is the correct type, so stale
// values with the incorrect type will be ignored.
const PrefStore* store = GetPrefStore(static_cast<PrefStoreType>(store_type));
if (store) {
switch (store->GetValue(name, out_value)) {
case PrefStore::READ_USE_DEFAULT:
store = GetPrefStore(DEFAULT_STORE);
if (!store || store->GetValue(name, out_value) != PrefStore::READ_OK) {
*out_value = NULL;
return false;
}
// Fall through...
case PrefStore::READ_OK:
return true;
case PrefStore::READ_NO_VALUE:
break;
}
}
// No valid value found for the given preference name: set the return false.
*out_value = NULL;
return false;
}
void PrefValueStore::OnPrefValueChanged(PrefValueStore::PrefStoreType type,
const std::string& key) {
NotifyPrefChanged(key.c_str(), type);
}
void PrefValueStore::OnInitializationCompleted(
PrefValueStore::PrefStoreType type) {
CheckInitializationCompleted();
}
void PrefValueStore::InitPrefStore(PrefValueStore::PrefStoreType type,
PrefStore* pref_store) {
pref_stores_[type].Initialize(this, pref_store, type);
}
void PrefValueStore::CheckInitializationCompleted() {
for (size_t i = 0; i <= PREF_STORE_TYPE_MAX; ++i) {
scoped_refptr<PrefStore> store =
GetPrefStore(static_cast<PrefStoreType>(i));
if (store && !store->IsInitializationComplete())
return;
}
pref_notifier_->OnInitializationCompleted();
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkHistogramVisualizationWidget.h"
#include <QClipboard>
QmitkHistogramVisualizationWidget::QmitkHistogramVisualizationWidget(QWidget* parent) : QWidget(parent)
{
m_Controls.setupUi(this);
m_Controls.checkBoxShowSubchart->setChecked(false);
m_Controls.spinBoxNBins->setValue(m_DefaultNBins);
m_Controls.spinBoxNBins->setMinimum(m_MinNBins);
m_Controls.spinBoxNBins->setMaximum(m_MaxNBins);
CreateConnections();
}
void QmitkHistogramVisualizationWidget::SetHistogram(itk::Statistics::Histogram<double>::ConstPointer histogram, const std::string& dataLabel)
{
if (histogram == nullptr)
return;
m_Histogram = histogram;
m_Controls.chartWidget->AddData2D(ConvertHistogramToMap(m_Histogram), dataLabel);
m_Controls.chartWidget->SetChartType(dataLabel, QmitkChartWidget::ChartType::bar);
m_Controls.chartWidget->SetXAxisLabel("Gray value");
m_Controls.chartWidget->SetYAxisLabel("Frequency");
m_Controls.chartWidget->Show(m_Controls.checkBoxShowSubchart->isChecked());
SetGUIElementsEnabled(true);
}
void QmitkHistogramVisualizationWidget::Reset()
{
m_Controls.chartWidget->Clear();
SetGUIElementsEnabled(false);
}
void QmitkHistogramVisualizationWidget::SetTheme(QmitkChartWidget::ColorTheme style)
{
m_Controls.chartWidget->SetTheme(style);
}
void QmitkHistogramVisualizationWidget::CreateConnections()
{
connect(m_Controls.buttonCopyHistogramToClipboard, &QPushButton::clicked, this, &QmitkHistogramVisualizationWidget::OnClipboardButtonClicked);
connect(m_Controls.checkBoxUseDefaultNBins, &QCheckBox::clicked, this, &QmitkHistogramVisualizationWidget::OnDefaultNBinsCheckBoxChanged);
connect(m_Controls.spinBoxNBins, &QSpinBox::editingFinished, this, &QmitkHistogramVisualizationWidget::OnNBinsSpinBoxValueChanged);
connect(m_Controls.checkBoxShowSubchart, &QCheckBox::clicked, this, &QmitkHistogramVisualizationWidget::OnShowSubchartCheckBoxChanged);
connect(m_Controls.checkBoxViewMinMax, &QCheckBox::clicked, this, &QmitkHistogramVisualizationWidget::OnViewMinMaxCheckBoxChanged);
connect(m_Controls.doubleSpinBoxMaxValue, &QSpinBox::editingFinished, this, &QmitkHistogramVisualizationWidget::OnMaxValueSpinBoxValueChanged);
connect(m_Controls.doubleSpinBoxMinValue, &QSpinBox::editingFinished, this, &QmitkHistogramVisualizationWidget::OnMinValueSpinBoxValueChanged);
}
void QmitkHistogramVisualizationWidget::SetGUIElementsEnabled(bool enabled)
{
this->setEnabled(enabled);
m_Controls.tabWidgetPlot->setEnabled(enabled);
m_Controls.checkBoxShowSubchart->setEnabled(enabled);
m_Controls.checkBoxUseDefaultNBins->setEnabled(enabled);
m_Controls.spinBoxNBins->setEnabled(!m_Controls.checkBoxUseDefaultNBins->isChecked());
m_Controls.buttonCopyHistogramToClipboard->setEnabled(enabled);
m_Controls.checkBoxViewMinMax->setEnabled(enabled);
m_Controls.doubleSpinBoxMaxValue->setEnabled(m_Controls.checkBoxViewMinMax->isChecked());
m_Controls.doubleSpinBoxMinValue->setEnabled(m_Controls.checkBoxViewMinMax->isChecked());
}
std::map<double, double> QmitkHistogramVisualizationWidget::ConvertHistogramToMap(itk::Statistics::Histogram<double>::ConstPointer histogram) const
{
std::map<double, double> histogramMap;
if (histogram)
{
auto endIt = histogram->End();
auto it = histogram->Begin();
// generating Lists of measurement and frequencies
for (; it != endIt; ++it)
{
double frequency = it.GetFrequency();
double measurement = it.GetMeasurementVector()[0];
histogramMap.emplace(measurement, frequency);
}
}
return histogramMap;
}
void QmitkHistogramVisualizationWidget::OnClipboardButtonClicked()
{
if (m_Histogram)
{
QApplication::clipboard()->clear();
QString clipboard("Measurement \t Frequency\n");
auto iter = m_Histogram->Begin();
auto iterEnd = m_Histogram->End();
for (; iter != iterEnd; ++iter)
{
clipboard = clipboard.append("%L1 \t %L2\n")
.arg(iter.GetMeasurementVector()[0], 0, 'f', 2)
.arg(iter.GetFrequency());
}
QApplication::clipboard()->setText(clipboard, QClipboard::Clipboard);
}
}
void QmitkHistogramVisualizationWidget::OnDefaultNBinsCheckBoxChanged()
{
if (m_Controls.checkBoxUseDefaultNBins->isChecked())
{
m_Controls.spinBoxNBins->setEnabled(false);
if (m_Controls.spinBoxNBins->value() != static_cast<int>(m_DefaultNBins) ) {
m_Controls.spinBoxNBins->setValue(m_DefaultNBins);
OnNBinsSpinBoxValueChanged();
}
}
else
{
m_Controls.spinBoxNBins->setEnabled(true);
}
}
void QmitkHistogramVisualizationWidget::OnNBinsSpinBoxValueChanged()
{
emit RequestHistogramUpdate(m_Controls.spinBoxNBins->value());
}
void QmitkHistogramVisualizationWidget::OnShowSubchartCheckBoxChanged()
{
m_Controls.chartWidget->Show(m_Controls.checkBoxShowSubchart->isChecked());
}
void QmitkHistogramVisualizationWidget::OnViewMinMaxCheckBoxChanged()
{
double min = m_Histogram->GetBinMin(0, 0);
auto maxVector = m_Histogram->GetDimensionMaxs(0);
double max;
if (m_Controls.checkBoxUseDefaultNBins->isChecked())
max = maxVector[m_DefaultNBins - 1];
else
max = maxVector[m_Controls.spinBoxNBins->value() - 1];
if (!m_Controls.checkBoxViewMinMax->isChecked())
{
m_Controls.doubleSpinBoxMaxValue->setEnabled(false);
m_Controls.doubleSpinBoxMinValue->setEnabled(false);
m_Controls.chartWidget->Reload();
}
else
{
m_Controls.doubleSpinBoxMinValue->setMinimum(min);
m_Controls.doubleSpinBoxMaxValue->setMaximum(max);
m_Controls.doubleSpinBoxMaxValue->setEnabled(true);
m_Controls.doubleSpinBoxMinValue->setEnabled(true);
}
}
void QmitkHistogramVisualizationWidget::OnMinValueSpinBoxValueChanged()
{
m_Controls.doubleSpinBoxMaxValue->setMinimum(m_Controls.doubleSpinBoxMinValue->value()+1);
m_Controls.chartWidget->UpdateMinMaxValueXView(m_Controls.doubleSpinBoxMinValue->value(),m_Controls.doubleSpinBoxMaxValue->value());
}
void QmitkHistogramVisualizationWidget::OnMaxValueSpinBoxValueChanged()
{
m_Controls.doubleSpinBoxMinValue->setMaximum(m_Controls.doubleSpinBoxMaxValue->value()-1);
m_Controls.chartWidget->UpdateMinMaxValueXView(m_Controls.doubleSpinBoxMinValue->value(),m_Controls.doubleSpinBoxMaxValue->value());
}<commit_msg>Setting min/max values directly on start<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkHistogramVisualizationWidget.h"
#include <QClipboard>
QmitkHistogramVisualizationWidget::QmitkHistogramVisualizationWidget(QWidget* parent) : QWidget(parent)
{
m_Controls.setupUi(this);
m_Controls.checkBoxShowSubchart->setChecked(false);
m_Controls.spinBoxNBins->setValue(m_DefaultNBins);
m_Controls.spinBoxNBins->setMinimum(m_MinNBins);
m_Controls.spinBoxNBins->setMaximum(m_MaxNBins);
CreateConnections();
}
void QmitkHistogramVisualizationWidget::SetHistogram(itk::Statistics::Histogram<double>::ConstPointer histogram, const std::string& dataLabel)
{
if (histogram == nullptr)
return;
m_Histogram = histogram;
m_Controls.chartWidget->AddData2D(ConvertHistogramToMap(m_Histogram), dataLabel);
m_Controls.chartWidget->SetChartType(dataLabel, QmitkChartWidget::ChartType::bar);
m_Controls.chartWidget->SetXAxisLabel("Gray value");
m_Controls.chartWidget->SetYAxisLabel("Frequency");
m_Controls.chartWidget->Show(m_Controls.checkBoxShowSubchart->isChecked());
SetGUIElementsEnabled(true);
}
void QmitkHistogramVisualizationWidget::Reset()
{
m_Controls.chartWidget->Clear();
SetGUIElementsEnabled(false);
}
void QmitkHistogramVisualizationWidget::SetTheme(QmitkChartWidget::ColorTheme style)
{
m_Controls.chartWidget->SetTheme(style);
}
void QmitkHistogramVisualizationWidget::CreateConnections()
{
connect(m_Controls.buttonCopyHistogramToClipboard, &QPushButton::clicked, this, &QmitkHistogramVisualizationWidget::OnClipboardButtonClicked);
connect(m_Controls.checkBoxUseDefaultNBins, &QCheckBox::clicked, this, &QmitkHistogramVisualizationWidget::OnDefaultNBinsCheckBoxChanged);
connect(m_Controls.spinBoxNBins, &QSpinBox::editingFinished, this, &QmitkHistogramVisualizationWidget::OnNBinsSpinBoxValueChanged);
connect(m_Controls.checkBoxShowSubchart, &QCheckBox::clicked, this, &QmitkHistogramVisualizationWidget::OnShowSubchartCheckBoxChanged);
connect(m_Controls.checkBoxViewMinMax, &QCheckBox::clicked, this, &QmitkHistogramVisualizationWidget::OnViewMinMaxCheckBoxChanged);
connect(m_Controls.doubleSpinBoxMaxValue, &QSpinBox::editingFinished, this, &QmitkHistogramVisualizationWidget::OnMaxValueSpinBoxValueChanged);
connect(m_Controls.doubleSpinBoxMinValue, &QSpinBox::editingFinished, this, &QmitkHistogramVisualizationWidget::OnMinValueSpinBoxValueChanged);
}
void QmitkHistogramVisualizationWidget::SetGUIElementsEnabled(bool enabled)
{
this->setEnabled(enabled);
m_Controls.tabWidgetPlot->setEnabled(enabled);
m_Controls.checkBoxShowSubchart->setEnabled(enabled);
m_Controls.checkBoxUseDefaultNBins->setEnabled(enabled);
m_Controls.spinBoxNBins->setEnabled(!m_Controls.checkBoxUseDefaultNBins->isChecked());
m_Controls.buttonCopyHistogramToClipboard->setEnabled(enabled);
m_Controls.checkBoxViewMinMax->setEnabled(enabled);
m_Controls.doubleSpinBoxMaxValue->setEnabled(m_Controls.checkBoxViewMinMax->isChecked());
m_Controls.doubleSpinBoxMinValue->setEnabled(m_Controls.checkBoxViewMinMax->isChecked());
}
std::map<double, double> QmitkHistogramVisualizationWidget::ConvertHistogramToMap(itk::Statistics::Histogram<double>::ConstPointer histogram) const
{
std::map<double, double> histogramMap;
if (histogram)
{
auto endIt = histogram->End();
auto it = histogram->Begin();
// generating Lists of measurement and frequencies
for (; it != endIt; ++it)
{
double frequency = it.GetFrequency();
double measurement = it.GetMeasurementVector()[0];
histogramMap.emplace(measurement, frequency);
}
}
return histogramMap;
}
void QmitkHistogramVisualizationWidget::OnClipboardButtonClicked()
{
if (m_Histogram)
{
QApplication::clipboard()->clear();
QString clipboard("Measurement \t Frequency\n");
auto iter = m_Histogram->Begin();
auto iterEnd = m_Histogram->End();
for (; iter != iterEnd; ++iter)
{
clipboard = clipboard.append("%L1 \t %L2\n")
.arg(iter.GetMeasurementVector()[0], 0, 'f', 2)
.arg(iter.GetFrequency());
}
QApplication::clipboard()->setText(clipboard, QClipboard::Clipboard);
}
}
void QmitkHistogramVisualizationWidget::OnDefaultNBinsCheckBoxChanged()
{
if (m_Controls.checkBoxUseDefaultNBins->isChecked())
{
m_Controls.spinBoxNBins->setEnabled(false);
if (m_Controls.spinBoxNBins->value() != static_cast<int>(m_DefaultNBins) ) {
m_Controls.spinBoxNBins->setValue(m_DefaultNBins);
OnNBinsSpinBoxValueChanged();
}
}
else
{
m_Controls.spinBoxNBins->setEnabled(true);
}
}
void QmitkHistogramVisualizationWidget::OnNBinsSpinBoxValueChanged()
{
emit RequestHistogramUpdate(m_Controls.spinBoxNBins->value());
}
void QmitkHistogramVisualizationWidget::OnShowSubchartCheckBoxChanged()
{
m_Controls.chartWidget->Show(m_Controls.checkBoxShowSubchart->isChecked());
}
void QmitkHistogramVisualizationWidget::OnViewMinMaxCheckBoxChanged()
{
double min = m_Histogram->GetBinMin(0, 0);
auto maxVector = m_Histogram->GetDimensionMaxs(0);
double max;
if (m_Controls.checkBoxUseDefaultNBins->isChecked())
max = maxVector[m_DefaultNBins - 1];
else
max = maxVector[m_Controls.spinBoxNBins->value() - 1];
if (!m_Controls.checkBoxViewMinMax->isChecked())
{
m_Controls.doubleSpinBoxMaxValue->setEnabled(false);
m_Controls.doubleSpinBoxMinValue->setEnabled(false);
m_Controls.chartWidget->Reload();
}
else
{
m_Controls.doubleSpinBoxMinValue->setMinimum(min);
m_Controls.doubleSpinBoxMinValue->setValue(min);
m_Controls.doubleSpinBoxMaxValue->setMaximum(max);
m_Controls.doubleSpinBoxMaxValue->setValue(max);
m_Controls.doubleSpinBoxMaxValue->setEnabled(true);
m_Controls.doubleSpinBoxMinValue->setEnabled(true);
}
}
void QmitkHistogramVisualizationWidget::OnMinValueSpinBoxValueChanged()
{
m_Controls.doubleSpinBoxMaxValue->setMinimum(m_Controls.doubleSpinBoxMinValue->value()+1);
m_Controls.chartWidget->UpdateMinMaxValueXView(m_Controls.doubleSpinBoxMinValue->value(),m_Controls.doubleSpinBoxMaxValue->value());
}
void QmitkHistogramVisualizationWidget::OnMaxValueSpinBoxValueChanged()
{
m_Controls.doubleSpinBoxMinValue->setMaximum(m_Controls.doubleSpinBoxMaxValue->value()-1);
m_Controls.chartWidget->UpdateMinMaxValueXView(m_Controls.doubleSpinBoxMinValue->value(),m_Controls.doubleSpinBoxMaxValue->value());
}<|endoftext|> |
<commit_before><commit_msg>Refactor the graphics example for common material loading<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2010 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 "net/http/http_auth_handler_ntlm.h"
#if !defined(NTLM_SSPI)
#include "base/base64.h"
#endif
#include "base/logging.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
namespace net {
int HttpAuthHandlerNTLM::GenerateAuthTokenImpl(
const string16* username,
const string16* password,
const HttpRequestInfo* request,
CompletionCallback* callback,
std::string* auth_token) {
#if defined(NTLM_SSPI)
return auth_sspi_.GenerateAuthToken(
username,
password,
CreateSPN(origin_),
auth_token);
#else // !defined(NTLM_SSPI)
// TODO(wtc): See if we can use char* instead of void* for in_buf and
// out_buf. This change will need to propagate to GetNextToken,
// GenerateType1Msg, and GenerateType3Msg, and perhaps further.
const void* in_buf;
void* out_buf;
uint32 in_buf_len, out_buf_len;
std::string decoded_auth_data;
// |username| may be in the form "DOMAIN\user". Parse it into the two
// components.
string16 domain;
string16 user;
const char16 backslash_character = '\\';
size_t backslash_idx = username->find(backslash_character);
if (backslash_idx == string16::npos) {
user = *username;
} else {
domain = username->substr(0, backslash_idx);
user = username->substr(backslash_idx + 1);
}
domain_ = domain;
username_ = user;
password_ = *password;
// Initial challenge.
if (auth_data_.empty()) {
in_buf_len = 0;
in_buf = NULL;
int rv = InitializeBeforeFirstChallenge();
if (rv != OK)
return rv;
} else {
if (!base::Base64Decode(auth_data_, &decoded_auth_data)) {
LOG(ERROR) << "Unexpected problem Base64 decoding.";
return ERR_UNEXPECTED;
}
in_buf_len = decoded_auth_data.length();
in_buf = decoded_auth_data.data();
}
int rv = GetNextToken(in_buf, in_buf_len, &out_buf, &out_buf_len);
if (rv != OK)
return rv;
// Base64 encode data in output buffer and prepend "NTLM ".
std::string encode_input(static_cast<char*>(out_buf), out_buf_len);
std::string encode_output;
bool base64_rv = base::Base64Encode(encode_input, &encode_output);
// OK, we are done with |out_buf|
free(out_buf);
if (!base64_rv) {
LOG(ERROR) << "Unexpected problem Base64 encoding.";
return ERR_UNEXPECTED;
}
*auth_token = std::string("NTLM ") + encode_output;
return OK;
#endif
}
// The NTLM challenge header looks like:
// WWW-Authenticate: NTLM auth-data
bool HttpAuthHandlerNTLM::ParseChallenge(
HttpAuth::ChallengeTokenizer* tok) {
scheme_ = "ntlm";
score_ = 3;
properties_ = ENCRYPTS_IDENTITY | IS_CONNECTION_BASED;
#if defined(NTLM_SSPI)
return auth_sspi_.ParseChallenge(tok);
#else
auth_data_.clear();
// Verify the challenge's auth-scheme.
if (!tok->valid() || !LowerCaseEqualsASCII(tok->scheme(), "ntlm"))
return false;
tok->set_expect_base64_token(true);
if (tok->GetNext())
auth_data_.assign(tok->value_begin(), tok->value_end());
return true;
#endif // defined(NTLM_SSPI)
}
// static
std::wstring HttpAuthHandlerNTLM::CreateSPN(const GURL& origin) {
// The service principal name of the destination server. See
// http://msdn.microsoft.com/en-us/library/ms677949%28VS.85%29.aspx
std::wstring target(L"HTTP/");
target.append(ASCIIToWide(GetHostAndPort(origin)));
return target;
}
} // namespace net
<commit_msg>Fail rather than crash if username+password are unspecified for NTLM on Linux+OSX.<commit_after>// Copyright (c) 2010 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 "net/http/http_auth_handler_ntlm.h"
#if !defined(NTLM_SSPI)
#include "base/base64.h"
#endif
#include "base/logging.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
namespace net {
int HttpAuthHandlerNTLM::GenerateAuthTokenImpl(
const string16* username,
const string16* password,
const HttpRequestInfo* request,
CompletionCallback* callback,
std::string* auth_token) {
#if defined(NTLM_SSPI)
return auth_sspi_.GenerateAuthToken(
username,
password,
CreateSPN(origin_),
auth_token);
#else // !defined(NTLM_SSPI)
// TODO(cbentzel): Shouldn't be hitting this case.
if (!username || !password) {
LOG(ERROR) << "Username and password are expected to be non-NULL.";
return ERR_MISSING_AUTH_CREDENTIALS;
}
// TODO(wtc): See if we can use char* instead of void* for in_buf and
// out_buf. This change will need to propagate to GetNextToken,
// GenerateType1Msg, and GenerateType3Msg, and perhaps further.
const void* in_buf;
void* out_buf;
uint32 in_buf_len, out_buf_len;
std::string decoded_auth_data;
// |username| may be in the form "DOMAIN\user". Parse it into the two
// components.
string16 domain;
string16 user;
const char16 backslash_character = '\\';
size_t backslash_idx = username->find(backslash_character);
if (backslash_idx == string16::npos) {
user = *username;
} else {
domain = username->substr(0, backslash_idx);
user = username->substr(backslash_idx + 1);
}
domain_ = domain;
username_ = user;
password_ = *password;
// Initial challenge.
if (auth_data_.empty()) {
in_buf_len = 0;
in_buf = NULL;
int rv = InitializeBeforeFirstChallenge();
if (rv != OK)
return rv;
} else {
if (!base::Base64Decode(auth_data_, &decoded_auth_data)) {
LOG(ERROR) << "Unexpected problem Base64 decoding.";
return ERR_UNEXPECTED;
}
in_buf_len = decoded_auth_data.length();
in_buf = decoded_auth_data.data();
}
int rv = GetNextToken(in_buf, in_buf_len, &out_buf, &out_buf_len);
if (rv != OK)
return rv;
// Base64 encode data in output buffer and prepend "NTLM ".
std::string encode_input(static_cast<char*>(out_buf), out_buf_len);
std::string encode_output;
bool base64_rv = base::Base64Encode(encode_input, &encode_output);
// OK, we are done with |out_buf|
free(out_buf);
if (!base64_rv) {
LOG(ERROR) << "Unexpected problem Base64 encoding.";
return ERR_UNEXPECTED;
}
*auth_token = std::string("NTLM ") + encode_output;
return OK;
#endif
}
// The NTLM challenge header looks like:
// WWW-Authenticate: NTLM auth-data
bool HttpAuthHandlerNTLM::ParseChallenge(
HttpAuth::ChallengeTokenizer* tok) {
scheme_ = "ntlm";
score_ = 3;
properties_ = ENCRYPTS_IDENTITY | IS_CONNECTION_BASED;
#if defined(NTLM_SSPI)
return auth_sspi_.ParseChallenge(tok);
#else
auth_data_.clear();
// Verify the challenge's auth-scheme.
if (!tok->valid() || !LowerCaseEqualsASCII(tok->scheme(), "ntlm"))
return false;
tok->set_expect_base64_token(true);
if (tok->GetNext())
auth_data_.assign(tok->value_begin(), tok->value_end());
return true;
#endif // defined(NTLM_SSPI)
}
// static
std::wstring HttpAuthHandlerNTLM::CreateSPN(const GURL& origin) {
// The service principal name of the destination server. See
// http://msdn.microsoft.com/en-us/library/ms677949%28VS.85%29.aspx
std::wstring target(L"HTTP/");
target.append(ASCIIToWide(GetHostAndPort(origin)));
return target;
}
} // namespace net
<|endoftext|> |
<commit_before>/******************************************************************************//**
* @copyright (c) RDO-Team, 2011
* @file choice_from.cpp
* @authors , ,
* @date unknown
* @brief RDOCalc
* @indent 4T
*********************************************************************************/
// **************************************************************************** PCH
#include "rdo_lib/rdo_runtime/pch.h"
// *********************************************************************** INCLUDES
#include <limits>
// *********************************************************************** SYNOPSIS
#include "rdo_lib/rdo_runtime/calc/choice_from.h"
#include "rdo_lib/rdo_runtime/rdo_runtime.h"
#include "rdo_lib/rdo_runtime/rdo_activity.h"
#include "rdo_lib/rdo_runtime/rdoprocess.h"
// ********************************************************************************
OPEN_RDO_RUNTIME_NAMESPACE
// ********************************************************************************
// ******************** RDOSelectResourceNonExistCalc
// ********************************************************************************
REF(RDOValue) RDOSelectResourceNonExistCalc::doCalc(CREF(LPRDORuntime) pRuntime)
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
return m_value;
}
// ********************************************************************************
// ******************** RDOCalcCreateNumberedResource
// ********************************************************************************
RDOCalcCreateNumberedResource::RDOCalcCreateNumberedResource(int _type, rbool _traceFlag, CREF(std::vector<RDOValue>) _paramsCalcs, int _number, rbool _isPermanent)
: m_pType (_type )
, traceFlag (_traceFlag )
, number (_number )
, isPermanent(_isPermanent)
{}
REF(RDOValue) RDOCalcCreateNumberedResource::doCalc(CREF(LPRDORuntime) pRuntime)
{
NEVER_REACH_HERE;
return m_value;
}
// ********************************************************************************
// ******************** RDOCalcCreateProcessResource
// ********************************************************************************
RDOCalcCreateProcessResource::RDOCalcCreateProcessResource(int _type, rbool _traceFlag, CREF(std::vector<RDOValue>) _paramsCalcs, int _number, rbool _isPermanent)
: m_pType (_type )
, traceFlag (_traceFlag )
, number (_number )
, isPermanent(_isPermanent)
{}
REF(RDOValue) RDOCalcCreateProcessResource::doCalc(CREF(LPRDORuntime) pRuntime)
{
NEVER_REACH_HERE;
return m_value;
}
// ********************************************************************************
// ******************** RDOCalcCreateResource
// ********************************************************************************
RDOCalcCreateResource::RDOCalcCreateResource(CREF(LPIResourceType) pType, CREF(std::vector<RDOValue>) rParamsCalcs, rbool traceFlag, rbool permanentFlag, ruint relResID)
: m_pResType (pType )
, m_traceFlag (traceFlag )
, m_permanentFlag(permanentFlag)
, m_relResID (relResID )
{
m_paramsCalcs.insert(m_paramsCalcs.begin(), rParamsCalcs.begin(), rParamsCalcs.end());
/// @todo ASSERT
if (m_permanentFlag && m_relResID > 0) NEVER_REACH_HERE; //
}
REF(RDOValue) RDOCalcCreateResource::doCalc(CREF(LPRDORuntime) pRuntime)
{
LPRDOResource pResource = m_pResType->createRes(pRuntime, m_paramsCalcs, m_traceFlag, m_permanentFlag);
if (m_relResID)
pRuntime->getCurrentActivity()->setRelRes(m_relResID, pResource->getTraceID());
return m_value; // just to return something
}
// ********************************************************************************
// ******************** RDOSelectResourceCalc
// ********************************************************************************
RDOSelectResourceCalc::RDOSelectResourceCalc(int _rel_res_id, CREF(LPRDOCalc) _choice_calc, CREF(LPRDOCalc) _order_calc, Type _order_type)
: rel_res_id (_rel_res_id )
, choice_calc(_choice_calc)
, order_calc (_order_calc )
, order_type (_order_type )
{}
REF(RDOValue) RDOSelectResourceDirectCalc::doCalc(CREF(LPRDORuntime) pRuntime)
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_id);
if (choice_calc && !choice_calc->calcValue(pRuntime).getAsBool())
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
m_value = 0;
return m_value;
}
m_value = 1;
return m_value;
}
REF(RDOValue) RDOSelectResourceByTypeCalc::doCalc(CREF(LPRDORuntime) pRuntime)
{
RDOValue maxVal = -DBL_MAX;
RDOValue minVal = DBL_MAX;
int res_minmax_id = -1;
RDORuntime::ResCIterator end = pRuntime->res_end();
for (RDORuntime::ResCIterator it = pRuntime->res_begin(); it != end; it++)
{
if (*it && (*it)->checkType(resType))
{
int res_id = (*it)->getTraceID();
switch (order_type)
{
case order_empty:
case order_first:
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_id);
if (choice_calc && !choice_calc->calcValue(pRuntime).getAsBool())
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
continue;
}
m_value = 1;
return m_value;
}
case order_with_min:
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_id);
if (choice_calc && !choice_calc->calcValue(pRuntime).getAsBool())
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
continue;
}
RDOValue tmp = order_calc->calcValue(pRuntime);
if (tmp < minVal)
{
minVal = tmp;
res_minmax_id = res_id;
}
break;
}
case order_with_max:
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_id);
if (choice_calc && !choice_calc->calcValue(pRuntime).getAsBool())
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
continue;
}
RDOValue tmp = order_calc->calcValue(pRuntime);
if (tmp > maxVal)
{
maxVal = tmp;
res_minmax_id = res_id;
}
break;
}
}
}
}
if (res_minmax_id != -1)
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_minmax_id);
m_value = 1;
return m_value;
}
m_value = 0;
return m_value;
}
void RDOSelectResourceCommonCalc::getBest(REF(std::vector< std::vector<int> >) allNumbs, ruint level, REF(std::vector<int>) res, REF(RDOValue) bestVal, CREF(LPRDORuntime) pRuntime, REF(rbool) hasBest) const
{
if (level >= allNumbs.size())
{
for (ruint i = 0; i < resSelectors.size(); i++)
{
if (!resSelectors.at(i)->callChoice(pRuntime))
{
return; // state not valid
}
}
RDOValue newVal = const_cast<PTR(RDOSelectResourceCommonCalc)>(this)->choice_calc->calcValue(pRuntime);
if (!hasBest || (useCommonWithMax && (newVal > bestVal)) ||
(!useCommonWithMax && (newVal < bestVal))) // found better value
{
for (ruint i = 0; i < resSelectors.size(); i++)
{
res.at(i) = pRuntime->getCurrentActivity()->getResByRelRes(i);
}
bestVal = newVal;
hasBest = true;
}
return;
}
REF(std::vector<int>) ourLevel = allNumbs.at(level);
for (ruint i = 0; i < ourLevel.size(); i++)
{
pRuntime->getCurrentActivity()->setRelRes(level, ourLevel.at(i));
getBest(allNumbs, level+1, res, bestVal, pRuntime, hasBest);
}
}
rbool RDOSelectResourceCommonCalc::getFirst(REF(std::vector< std::vector<int> >) allNumbs, ruint level, CREF(LPRDORuntime) pRuntime) const
{
if (level >= allNumbs.size())
{
for (ruint i = 0; i < resSelectors.size(); i++)
{
if (!resSelectors.at(i)->callChoice(pRuntime))
{
return false;
}
}
return true;
}
REF(std::vector<int>) ourLevel = allNumbs.at(level);
for (ruint i = 0; i < ourLevel.size(); i++)
{
pRuntime->getCurrentActivity()->setRelRes(level, ourLevel.at(i));
if (getFirst(allNumbs, level+1, pRuntime)) return true;
}
return false;
}
//rbool RDOSelectResourceCommonCalc::getFirst(REF(std::vector< std::vector<int> >) allNumbs, int level,CREF(LPRDORuntime) pRuntime) const
//{
// if (level <= 0) {
// for (int i = 0; i < resSelectors.size(); i++) {
// if (!resSelectors.at(i)->callChoice(pRuntime)) {
// return false;
// }
// }
// return true;
// } else {
// level--;
// REF(std::vector<int>) ourLevel = allNumbs.at(level);
// for (int i = 0; i < ourLevel.size(); i++) {
// pRuntime->setRelRes(level, ourLevel.at(i));
// if (getFirst(allNumbs, level, pRuntime)) return true;
// }
// }
// return false;
//}
REF(RDOValue) RDOSelectResourceCommonCalc::doCalc(CREF(LPRDORuntime) pRuntime)
{
std::vector< std::vector<int> > allNumbs;
std::vector<int> res;
for (ruint i = 0; i < resSelectors.size(); i++)
{
allNumbs.push_back(resSelectors.at(i)->getPossibleNumbers(pRuntime));
res.push_back(pRuntime->getCurrentActivity()->getResByRelRes(i));
}
if (!choice_calc)
{
// first
// if (getFirst(allNumbs, allNumbs.size(), pRuntime)) {
// return true;
// }
if (getFirst(allNumbs, 0, pRuntime))
{
m_value = 1;
return m_value;
}
}
else
{
// with_min / with_max
RDOValue bestVal = 0;
rbool found = false;
getBest(allNumbs, 0, res, bestVal, pRuntime, found);
if (found)
{
for (ruint i = 0; i < res.size(); i++)
{
pRuntime->getCurrentActivity()->setRelRes(i, res.at(i));
}
m_value = 1;
return m_value;
}
}
m_value = 0;
return m_value;
}
std::vector<int> RDOSelectResourceDirectCommonCalc::getPossibleNumbers(CREF(LPRDORuntime) pRuntime) const
{
std::vector<int> res;
res.push_back(res_id);
return res;
}
std::vector<int> RDOSelectResourceByTypeCommonCalc::getPossibleNumbers(CREF(LPRDORuntime) pRuntime) const
{
std::vector<int> res;
RDORuntime::ResCIterator end = pRuntime->res_end();
for (RDORuntime::ResCIterator it = pRuntime->res_begin(); it != end; it++)
{
if (*it == NULL)
continue;
if (!(*it)->checkType(resType))
continue;
res.push_back((*it)->getTraceID());
}
return res;
}
rbool RDOSelectResourceDirectCommonCalc::callChoice(CREF(LPRDORuntime) pRuntime) const
{
return (choice_calc && !const_cast<PTR(RDOSelectResourceDirectCommonCalc)>(this)->choice_calc->calcValue(pRuntime).getAsBool()) ? false : true;
}
rbool RDOSelectResourceByTypeCommonCalc::callChoice(CREF(LPRDORuntime) pRuntime) const
{
return (choice_calc && !const_cast<PTR(RDOSelectResourceByTypeCommonCalc)>(this)->choice_calc->calcValue(pRuntime).getAsBool()) ? false : true;
}
IRDOSelectResourceCommon::IRDOSelectResourceCommon()
{}
IRDOSelectResourceCommon::~IRDOSelectResourceCommon()
{}
RDOSelectResourceDirectCommonCalc::~RDOSelectResourceDirectCommonCalc()
{}
RDOSelectResourceByTypeCommonCalc::~RDOSelectResourceByTypeCommonCalc()
{}
CLOSE_RDO_RUNTIME_NAMESPACE
<commit_msg> - форматирование - перекомпоновка по классам<commit_after>/******************************************************************************//**
* @copyright (c) RDO-Team, 2011
* @file choice_from.cpp
* @authors , ,
* @date unknown
* @brief RDOCalc
* @indent 4T
*********************************************************************************/
// **************************************************************************** PCH
#include "rdo_lib/rdo_runtime/pch.h"
// *********************************************************************** INCLUDES
#include <limits>
// *********************************************************************** SYNOPSIS
#include "rdo_lib/rdo_runtime/calc/choice_from.h"
#include "rdo_lib/rdo_runtime/rdo_runtime.h"
#include "rdo_lib/rdo_runtime/rdo_activity.h"
#include "rdo_lib/rdo_runtime/rdoprocess.h"
// ********************************************************************************
OPEN_RDO_RUNTIME_NAMESPACE
// ********************************************************************************
// ******************** RDOSelectResourceNonExistCalc
// ********************************************************************************
REF(RDOValue) RDOSelectResourceNonExistCalc::doCalc(CREF(LPRDORuntime) pRuntime)
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
return m_value;
}
// ********************************************************************************
// ******************** RDOCalcCreateNumberedResource
// ********************************************************************************
RDOCalcCreateNumberedResource::RDOCalcCreateNumberedResource(int _type, rbool _traceFlag, CREF(std::vector<RDOValue>) _paramsCalcs, int _number, rbool _isPermanent)
: m_pType (_type )
, traceFlag (_traceFlag )
, number (_number )
, isPermanent(_isPermanent)
{}
REF(RDOValue) RDOCalcCreateNumberedResource::doCalc(CREF(LPRDORuntime) pRuntime)
{
NEVER_REACH_HERE;
return m_value;
}
// ********************************************************************************
// ******************** RDOCalcCreateProcessResource
// ********************************************************************************
RDOCalcCreateProcessResource::RDOCalcCreateProcessResource(int _type, rbool _traceFlag, CREF(std::vector<RDOValue>) _paramsCalcs, int _number, rbool _isPermanent)
: m_pType (_type )
, traceFlag (_traceFlag )
, number (_number )
, isPermanent(_isPermanent)
{}
REF(RDOValue) RDOCalcCreateProcessResource::doCalc(CREF(LPRDORuntime) pRuntime)
{
NEVER_REACH_HERE;
return m_value;
}
// ********************************************************************************
// ******************** RDOCalcCreateResource
// ********************************************************************************
RDOCalcCreateResource::RDOCalcCreateResource(CREF(LPIResourceType) pType, CREF(std::vector<RDOValue>) rParamsCalcs, rbool traceFlag, rbool permanentFlag, ruint relResID)
: m_pResType (pType )
, m_traceFlag (traceFlag )
, m_permanentFlag(permanentFlag)
, m_relResID (relResID )
{
m_paramsCalcs.insert(m_paramsCalcs.begin(), rParamsCalcs.begin(), rParamsCalcs.end());
/// @todo ASSERT
if (m_permanentFlag && m_relResID > 0) NEVER_REACH_HERE; //
}
REF(RDOValue) RDOCalcCreateResource::doCalc(CREF(LPRDORuntime) pRuntime)
{
LPRDOResource pResource = m_pResType->createRes(pRuntime, m_paramsCalcs, m_traceFlag, m_permanentFlag);
if (m_relResID)
pRuntime->getCurrentActivity()->setRelRes(m_relResID, pResource->getTraceID());
return m_value; // just to return something
}
// ********************************************************************************
// ******************** RDOSelectResourceCalc
// ********************************************************************************
RDOSelectResourceCalc::RDOSelectResourceCalc(int _rel_res_id, CREF(LPRDOCalc) _choice_calc, CREF(LPRDOCalc) _order_calc, Type _order_type)
: rel_res_id (_rel_res_id )
, choice_calc(_choice_calc)
, order_calc (_order_calc )
, order_type (_order_type )
{}
// ********************************************************************************
// ******************** RDOSelectResourceDirectCalc
// ********************************************************************************
REF(RDOValue) RDOSelectResourceDirectCalc::doCalc(CREF(LPRDORuntime) pRuntime)
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_id);
if (choice_calc && !choice_calc->calcValue(pRuntime).getAsBool())
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
m_value = 0;
return m_value;
}
m_value = 1;
return m_value;
}
// ********************************************************************************
// ******************** RDOSelectResourceByTypeCalc
// ********************************************************************************
REF(RDOValue) RDOSelectResourceByTypeCalc::doCalc(CREF(LPRDORuntime) pRuntime)
{
RDOValue maxVal = -DBL_MAX;
RDOValue minVal = DBL_MAX;
int res_minmax_id = -1;
RDORuntime::ResCIterator end = pRuntime->res_end();
for (RDORuntime::ResCIterator it = pRuntime->res_begin(); it != end; it++)
{
if (*it && (*it)->checkType(resType))
{
int res_id = (*it)->getTraceID();
switch (order_type)
{
case order_empty:
case order_first:
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_id);
if (choice_calc && !choice_calc->calcValue(pRuntime).getAsBool())
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
continue;
}
m_value = 1;
return m_value;
}
case order_with_min:
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_id);
if (choice_calc && !choice_calc->calcValue(pRuntime).getAsBool())
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
continue;
}
RDOValue tmp = order_calc->calcValue(pRuntime);
if (tmp < minVal)
{
minVal = tmp;
res_minmax_id = res_id;
}
break;
}
case order_with_max:
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_id);
if (choice_calc && !choice_calc->calcValue(pRuntime).getAsBool())
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, -1);
continue;
}
RDOValue tmp = order_calc->calcValue(pRuntime);
if (tmp > maxVal)
{
maxVal = tmp;
res_minmax_id = res_id;
}
break;
}
}
}
}
if (res_minmax_id != -1)
{
pRuntime->getCurrentActivity()->setRelRes(rel_res_id, res_minmax_id);
m_value = 1;
return m_value;
}
m_value = 0;
return m_value;
}
// ********************************************************************************
// ******************** RDOSelectResourceCommonCalc
// ********************************************************************************
void RDOSelectResourceCommonCalc::getBest(REF(std::vector< std::vector<int> >) allNumbs, ruint level, REF(std::vector<int>) res, REF(RDOValue) bestVal, CREF(LPRDORuntime) pRuntime, REF(rbool) hasBest) const
{
if (level >= allNumbs.size())
{
for (ruint i = 0; i < resSelectors.size(); i++)
{
if (!resSelectors.at(i)->callChoice(pRuntime))
{
return; // state not valid
}
}
RDOValue newVal = const_cast<PTR(RDOSelectResourceCommonCalc)>(this)->choice_calc->calcValue(pRuntime);
if (!hasBest || (useCommonWithMax && (newVal > bestVal)) ||
(!useCommonWithMax && (newVal < bestVal))) // found better value
{
for (ruint i = 0; i < resSelectors.size(); i++)
{
res.at(i) = pRuntime->getCurrentActivity()->getResByRelRes(i);
}
bestVal = newVal;
hasBest = true;
}
return;
}
REF(std::vector<int>) ourLevel = allNumbs.at(level);
for (ruint i = 0; i < ourLevel.size(); i++)
{
pRuntime->getCurrentActivity()->setRelRes(level, ourLevel.at(i));
getBest(allNumbs, level+1, res, bestVal, pRuntime, hasBest);
}
}
rbool RDOSelectResourceCommonCalc::getFirst(REF(std::vector< std::vector<int> >) allNumbs, ruint level, CREF(LPRDORuntime) pRuntime) const
{
if (level >= allNumbs.size())
{
for (ruint i = 0; i < resSelectors.size(); i++)
{
if (!resSelectors.at(i)->callChoice(pRuntime))
{
return false;
}
}
return true;
}
REF(std::vector<int>) ourLevel = allNumbs.at(level);
for (ruint i = 0; i < ourLevel.size(); i++)
{
pRuntime->getCurrentActivity()->setRelRes(level, ourLevel.at(i));
if (getFirst(allNumbs, level+1, pRuntime)) return true;
}
return false;
}
//rbool RDOSelectResourceCommonCalc::getFirst(REF(std::vector< std::vector<int> >) allNumbs, int level,CREF(LPRDORuntime) pRuntime) const
//{
// if (level <= 0) {
// for (int i = 0; i < resSelectors.size(); i++) {
// if (!resSelectors.at(i)->callChoice(pRuntime)) {
// return false;
// }
// }
// return true;
// } else {
// level--;
// REF(std::vector<int>) ourLevel = allNumbs.at(level);
// for (int i = 0; i < ourLevel.size(); i++) {
// pRuntime->setRelRes(level, ourLevel.at(i));
// if (getFirst(allNumbs, level, pRuntime)) return true;
// }
// }
// return false;
//}
REF(RDOValue) RDOSelectResourceCommonCalc::doCalc(CREF(LPRDORuntime) pRuntime)
{
std::vector< std::vector<int> > allNumbs;
std::vector<int> res;
for (ruint i = 0; i < resSelectors.size(); i++)
{
allNumbs.push_back(resSelectors.at(i)->getPossibleNumbers(pRuntime));
res.push_back(pRuntime->getCurrentActivity()->getResByRelRes(i));
}
if (!choice_calc)
{
// first
// if (getFirst(allNumbs, allNumbs.size(), pRuntime)) {
// return true;
// }
if (getFirst(allNumbs, 0, pRuntime))
{
m_value = 1;
return m_value;
}
}
else
{
// with_min / with_max
RDOValue bestVal = 0;
rbool found = false;
getBest(allNumbs, 0, res, bestVal, pRuntime, found);
if (found)
{
for (ruint i = 0; i < res.size(); i++)
{
pRuntime->getCurrentActivity()->setRelRes(i, res.at(i));
}
m_value = 1;
return m_value;
}
}
m_value = 0;
return m_value;
}
// ********************************************************************************
// ******************** RDOSelectResourceDirectCommonCalc
// ********************************************************************************
std::vector<int> RDOSelectResourceDirectCommonCalc::getPossibleNumbers(CREF(LPRDORuntime) pRuntime) const
{
std::vector<int> res;
res.push_back(res_id);
return res;
}
rbool RDOSelectResourceDirectCommonCalc::callChoice(CREF(LPRDORuntime) pRuntime) const
{
return (choice_calc && !const_cast<PTR(RDOSelectResourceDirectCommonCalc)>(this)->choice_calc->calcValue(pRuntime).getAsBool()) ? false : true;
}
RDOSelectResourceDirectCommonCalc::~RDOSelectResourceDirectCommonCalc()
{}
// ********************************************************************************
// ******************** RDOSelectResourceByTypeCommonCalc
// ********************************************************************************
std::vector<int> RDOSelectResourceByTypeCommonCalc::getPossibleNumbers(CREF(LPRDORuntime) pRuntime) const
{
std::vector<int> res;
RDORuntime::ResCIterator end = pRuntime->res_end();
for (RDORuntime::ResCIterator it = pRuntime->res_begin(); it != end; it++)
{
if (*it == NULL)
continue;
if (!(*it)->checkType(resType))
continue;
res.push_back((*it)->getTraceID());
}
return res;
}
rbool RDOSelectResourceByTypeCommonCalc::callChoice(CREF(LPRDORuntime) pRuntime) const
{
return (choice_calc && !const_cast<PTR(RDOSelectResourceByTypeCommonCalc)>(this)->choice_calc->calcValue(pRuntime).getAsBool()) ? false : true;
}
RDOSelectResourceByTypeCommonCalc::~RDOSelectResourceByTypeCommonCalc()
{}
// ********************************************************************************
// ******************** IRDOSelectResourceCommon
// ********************************************************************************
IRDOSelectResourceCommon::IRDOSelectResourceCommon()
{}
IRDOSelectResourceCommon::~IRDOSelectResourceCommon()
{}
CLOSE_RDO_RUNTIME_NAMESPACE
<|endoftext|> |
<commit_before>/**
* Implementation of the wayfire-shell-unstable-v2 protocol
*/
#include "wayfire/output.hpp"
#include "wayfire/core.hpp"
#include "wayfire/debug.hpp"
#include "wayfire/output-layout.hpp"
#include "wayfire/render-manager.hpp"
#include "wayfire-shell.hpp"
#include "wayfire-shell-unstable-v2-protocol.h"
#include "wayfire/signal-definitions.hpp"
#include "../view/view-impl.hpp"
#include <wayfire/util/log.hpp>
/* ----------------------------- wfs_hotspot -------------------------------- */
static void handle_hotspot_destroy(wl_resource *resource);
/**
* Represents a zwf_shell_hotspot_v2.
* Lifetime is managed by the resource.
*/
class wfs_hotspot : public noncopyable_t
{
private:
wf::geometry_t hotspot_geometry;
bool hotspot_triggered = false;
wf::wl_idle_call idle_check_input;
wf::wl_timer timer;
uint32_t timeout_ms;
wl_resource *hotspot_resource;
wf::signal_callback_t on_motion_event = [=] (wf::signal_data_t *data)
{
idle_check_input.run_once([=] () {
auto gcf = wf::get_core().get_cursor_position();
wf::point_t gc{(int)gcf.x, (int)gcf.y};
process_input_motion(gc);
});
};
wf::signal_callback_t on_touch_motion_event = [=] (wf::signal_data_t *data)
{
idle_check_input.run_once([=] () {
auto gcf = wf::get_core().get_touch_position(0);
wf::point_t gc{(int)gcf.x, (int)gcf.y};
process_input_motion(gc);
});
};
wf::signal_callback_t on_output_removed;
void process_input_motion(wf::point_t gc)
{
if (!(hotspot_geometry & gc))
{
if (hotspot_triggered)
zwf_hotspot_v2_send_leave(hotspot_resource);
/* Cursor outside of the hotspot */
hotspot_triggered = false;
timer.disconnect();
return;
}
if (hotspot_triggered)
{
/* Hotspot was already triggered, wait for the next time the cursor
* enters the hotspot area to trigger again */
return;
}
if (!timer.is_connected())
{
timer.set_timeout(timeout_ms, [=] () {
hotspot_triggered = true;
zwf_hotspot_v2_send_enter(hotspot_resource);
});
}
}
wf::geometry_t calculate_hotspot_geometry(wf::output_t *output,
uint32_t edge_mask, uint32_t distance) const
{
wf::geometry_t slot = output->get_layout_geometry();
if (edge_mask & ZWF_OUTPUT_V2_HOTSPOT_EDGE_TOP)
{
slot.height = distance;
} else if (edge_mask & ZWF_OUTPUT_V2_HOTSPOT_EDGE_BOTTOM)
{
slot.y += slot.height - distance;
slot.height = distance;
}
if (edge_mask & ZWF_OUTPUT_V2_HOTSPOT_EDGE_LEFT)
{
slot.width = distance;
} else if (edge_mask & ZWF_OUTPUT_V2_HOTSPOT_EDGE_RIGHT)
{
slot.x += slot.width - distance;
slot.width = distance;
}
return slot;
}
public:
/**
* Create a new hotspot.
* It is guaranteedd that edge_mask contains at most 2 non-opposing edges.
*/
wfs_hotspot(wf::output_t *output, uint32_t edge_mask,
uint32_t distance, uint32_t timeout, wl_client *client, uint32_t id)
{
this->timeout_ms = timeout;
this->hotspot_geometry =
calculate_hotspot_geometry(output, edge_mask, distance);
hotspot_resource =
wl_resource_create(client, &zwf_hotspot_v2_interface, 1, id);
wl_resource_set_implementation(hotspot_resource, NULL, this,
handle_hotspot_destroy);
// setup output destroy listener
on_output_removed = [this, output] (wf::signal_data_t* data)
{
auto ev = static_cast<output_removed_signal*> (data);
if (ev->output == output)
{
/* Make hotspot inactive by setting the region to empty */
hotspot_geometry = {0, 0, 0, 0};
process_input_motion({0, 0});
}
};
wf::get_core().connect_signal("pointer_motion", &on_motion_event);
wf::get_core().connect_signal("tablet_axis", &on_motion_event);
wf::get_core().connect_signal("touch_motion", &on_touch_motion_event);
wf::get_core().output_layout->connect_signal("output-removed",
&on_output_removed);
}
~wfs_hotspot()
{
wf::get_core().disconnect_signal("pointer_motion", &on_motion_event);
wf::get_core().disconnect_signal("tablet_axis", &on_motion_event);
wf::get_core().disconnect_signal("touch_motion", &on_touch_motion_event);
wf::get_core().output_layout->disconnect_signal("output-removed",
&on_output_removed);
}
};
static void handle_hotspot_destroy(wl_resource *resource)
{
auto *hotspot = (wfs_hotspot*)wl_resource_get_user_data(resource);
delete hotspot;
wl_resource_set_user_data(resource, nullptr);
}
/* ------------------------------ wfs_output -------------------------------- */
static void handle_output_destroy(wl_resource *resource);
static void handle_zwf_output_inhibit_output(wl_client*, wl_resource *resource);
static void handle_zwf_output_inhibit_output_done(wl_client*,
wl_resource *resource);
static void handle_zwf_output_create_hotspot(wl_client*, wl_resource *resource,
uint32_t hotspot, uint32_t threshold, uint32_t timeout, uint32_t id);
static struct zwf_output_v2_interface zwf_output_impl = {
.inhibit_output = handle_zwf_output_inhibit_output,
.inhibit_output_done = handle_zwf_output_inhibit_output_done,
.create_hotspot = handle_zwf_output_create_hotspot,
};
/**
* Represents a zwf_output_v2.
* Lifetime is managed by the wl_resource
*/
class wfs_output : public noncopyable_t
{
uint32_t num_inhibits = 0;
wl_resource *resource;
wf::output_t *output;
void disconnect_from_output()
{
wf::get_core().output_layout->disconnect_signal("output-removed",
&on_output_removed);
output->disconnect_signal("fullscreen-layer-focused", &on_fullscreen_layer_focused);
this->output = nullptr;
}
wf::signal_callback_t on_output_removed = [=] (wf::signal_data_t *data)
{
auto ev = static_cast<output_removed_signal*> (data);
if (ev->output == this->output)
disconnect_from_output();
};
wf::signal_callback_t on_fullscreen_layer_focused = [=] (wf::signal_data_t *data)
{
if (data != nullptr) {
zwf_output_v2_send_enter_fullscreen(resource);
} else {
zwf_output_v2_send_leave_fullscreen(resource);
}
};
public:
wfs_output(wf::output_t *output, wl_client *client, int id)
{
this->output = output;
resource = wl_resource_create(client, &zwf_output_v2_interface, 1, id);
wl_resource_set_implementation(resource, &zwf_output_impl,
this, handle_output_destroy);
output->connect_signal("fullscreen-layer-focused", &on_fullscreen_layer_focused);
wf::get_core().output_layout->connect_signal("output-removed",
&on_output_removed);
}
~wfs_output()
{
if (!this->output)
{
/* The wayfire output was destroyed. Gracefully do nothing */
return;
}
disconnect_from_output();
/* Remove any remaining inhibits, otherwise the compositor will never
* be "unlocked" */
while (num_inhibits > 0)
{
this->output->render->add_inhibit(false);
--num_inhibits;
}
}
void inhibit_output()
{
++this->num_inhibits;
this->output->render->add_inhibit(true);
}
void inhibit_output_done()
{
if (this->num_inhibits == 0)
{
wl_resource_post_no_memory(resource);
return;
}
--this->num_inhibits;
this->output->render->add_inhibit(false);
}
void create_hotspot(uint32_t hotspot, uint32_t threshold, uint32_t timeout,
uint32_t id)
{
// will be auto-deleted when the resource is destroyed by the client
new wfs_hotspot(this->output, hotspot, threshold, timeout,
wl_resource_get_client(this->resource), id);
}
};
static void handle_zwf_output_inhibit_output(wl_client*, wl_resource *resource)
{
auto output = (wfs_output*)wl_resource_get_user_data(resource);
output->inhibit_output();
}
static void handle_zwf_output_inhibit_output_done(
wl_client*, wl_resource *resource)
{
auto output = (wfs_output*)wl_resource_get_user_data(resource);
output->inhibit_output_done();
}
static void handle_zwf_output_create_hotspot(wl_client*, wl_resource *resource,
uint32_t hotspot, uint32_t threshold, uint32_t timeout, uint32_t id)
{
auto output = (wfs_output*)wl_resource_get_user_data(resource);
output->create_hotspot(hotspot, threshold, timeout, id);
}
static void handle_output_destroy(wl_resource *resource)
{
auto *output = (wfs_output*)wl_resource_get_user_data(resource);
delete output;
wl_resource_set_user_data(resource, nullptr);
}
/* ------------------------------ wfs_surface ------------------------------- */
static void handle_surface_destroy(wl_resource *resource);
static void handle_zwf_surface_interactive_move(wl_client*,
wl_resource *resource);
static struct zwf_surface_v2_interface zwf_surface_impl = {
.interactive_move = handle_zwf_surface_interactive_move,
};
/**
* Represents a zwf_surface_v2.
* Lifetime is managed by the wl_resource
*/
class wfs_surface : public noncopyable_t
{
wl_resource *resource;
wayfire_view view;
wf::signal_callback_t on_unmap = [=] (wf::signal_data_t *data)
{
view = nullptr;
};
public:
wfs_surface(wayfire_view view, wl_client *client, int id)
{
this->view = view;
resource = wl_resource_create(client, &zwf_surface_v2_interface, 1, id);
wl_resource_set_implementation(resource, &zwf_surface_impl,
this, handle_surface_destroy);
view->connect_signal("unmap", &on_unmap);
}
~wfs_surface()
{
if (this->view)
view->disconnect_signal("unmap", &on_unmap);
}
void interactive_move()
{
if (view) view->move_request();
}
};
static void handle_zwf_surface_interactive_move(wl_client*, wl_resource *resource)
{
auto surface = (wfs_surface*)wl_resource_get_user_data(resource);
surface->interactive_move();
}
static void handle_surface_destroy(wl_resource *resource)
{
auto surface = (wfs_surface*)wl_resource_get_user_data(resource);
delete surface;
wl_resource_set_user_data(resource, nullptr);
}
static void zwf_shell_manager_get_wf_output(wl_client *client,
wl_resource *resource, wl_resource *output, uint32_t id)
{
auto wlr_out = (wlr_output*) wl_resource_get_user_data(output);
auto wo = wf::get_core().output_layout->find_output(wlr_out);
if (wo)
{
// will be deleted when the resource is destroyed
new wfs_output(wo, client, id);
}
}
static void zwf_shell_manager_get_wf_surface(wl_client *client,
wl_resource *resource, wl_resource *surface, uint32_t id)
{
auto view = wf::wl_surface_to_wayfire_view(surface);
if (view)
{
/* Will be freed when the resource is destroyed */
new wfs_surface(view, client, id);
}
}
const struct zwf_shell_manager_v2_interface zwf_shell_manager_v2_impl =
{
zwf_shell_manager_get_wf_output,
zwf_shell_manager_get_wf_surface,
};
void bind_zwf_shell_manager(wl_client *client, void *data,
uint32_t version, uint32_t id)
{
auto resource =
wl_resource_create(client, &zwf_shell_manager_v2_interface, 1, id);
wl_resource_set_implementation(resource,
&zwf_shell_manager_v2_impl, NULL, NULL);
}
struct wayfire_shell
{
wl_global *shell_manager;
};
wayfire_shell* wayfire_shell_create(wl_display *display)
{
wayfire_shell *ws = new wayfire_shell;
ws->shell_manager = wl_global_create(display,
&zwf_shell_manager_v2_interface, 1, NULL, bind_zwf_shell_manager);
if (ws->shell_manager == NULL)
{
LOGE("Failed to create wayfire_shell interface");
return NULL;
}
return ws;
}
<commit_msg>wayfire-shell: fix crash when a client disconnects<commit_after>/**
* Implementation of the wayfire-shell-unstable-v2 protocol
*/
#include "wayfire/output.hpp"
#include "wayfire/core.hpp"
#include "wayfire/debug.hpp"
#include "wayfire/output-layout.hpp"
#include "wayfire/render-manager.hpp"
#include "wayfire-shell.hpp"
#include "wayfire-shell-unstable-v2-protocol.h"
#include "wayfire/signal-definitions.hpp"
#include "../view/view-impl.hpp"
#include <wayfire/util/log.hpp>
/* ----------------------------- wfs_hotspot -------------------------------- */
static void handle_hotspot_destroy(wl_resource *resource);
/**
* Represents a zwf_shell_hotspot_v2.
* Lifetime is managed by the resource.
*/
class wfs_hotspot : public noncopyable_t
{
private:
wf::geometry_t hotspot_geometry;
bool hotspot_triggered = false;
wf::wl_idle_call idle_check_input;
wf::wl_timer timer;
uint32_t timeout_ms;
wl_resource *hotspot_resource;
wf::signal_callback_t on_motion_event = [=] (wf::signal_data_t *data)
{
idle_check_input.run_once([=] () {
auto gcf = wf::get_core().get_cursor_position();
wf::point_t gc{(int)gcf.x, (int)gcf.y};
process_input_motion(gc);
});
};
wf::signal_callback_t on_touch_motion_event = [=] (wf::signal_data_t *data)
{
idle_check_input.run_once([=] () {
auto gcf = wf::get_core().get_touch_position(0);
wf::point_t gc{(int)gcf.x, (int)gcf.y};
process_input_motion(gc);
});
};
wf::signal_callback_t on_output_removed;
void process_input_motion(wf::point_t gc)
{
if (!(hotspot_geometry & gc))
{
if (hotspot_triggered)
zwf_hotspot_v2_send_leave(hotspot_resource);
/* Cursor outside of the hotspot */
hotspot_triggered = false;
timer.disconnect();
return;
}
if (hotspot_triggered)
{
/* Hotspot was already triggered, wait for the next time the cursor
* enters the hotspot area to trigger again */
return;
}
if (!timer.is_connected())
{
timer.set_timeout(timeout_ms, [=] () {
hotspot_triggered = true;
zwf_hotspot_v2_send_enter(hotspot_resource);
});
}
}
wf::geometry_t calculate_hotspot_geometry(wf::output_t *output,
uint32_t edge_mask, uint32_t distance) const
{
wf::geometry_t slot = output->get_layout_geometry();
if (edge_mask & ZWF_OUTPUT_V2_HOTSPOT_EDGE_TOP)
{
slot.height = distance;
} else if (edge_mask & ZWF_OUTPUT_V2_HOTSPOT_EDGE_BOTTOM)
{
slot.y += slot.height - distance;
slot.height = distance;
}
if (edge_mask & ZWF_OUTPUT_V2_HOTSPOT_EDGE_LEFT)
{
slot.width = distance;
} else if (edge_mask & ZWF_OUTPUT_V2_HOTSPOT_EDGE_RIGHT)
{
slot.x += slot.width - distance;
slot.width = distance;
}
return slot;
}
public:
/**
* Create a new hotspot.
* It is guaranteedd that edge_mask contains at most 2 non-opposing edges.
*/
wfs_hotspot(wf::output_t *output, uint32_t edge_mask,
uint32_t distance, uint32_t timeout, wl_client *client, uint32_t id)
{
this->timeout_ms = timeout;
this->hotspot_geometry =
calculate_hotspot_geometry(output, edge_mask, distance);
hotspot_resource =
wl_resource_create(client, &zwf_hotspot_v2_interface, 1, id);
wl_resource_set_implementation(hotspot_resource, NULL, this,
handle_hotspot_destroy);
// setup output destroy listener
on_output_removed = [this, output] (wf::signal_data_t* data)
{
auto ev = static_cast<output_removed_signal*> (data);
if (ev->output == output)
{
/* Make hotspot inactive by setting the region to empty */
hotspot_geometry = {0, 0, 0, 0};
process_input_motion({0, 0});
}
};
wf::get_core().connect_signal("pointer_motion", &on_motion_event);
wf::get_core().connect_signal("tablet_axis", &on_motion_event);
wf::get_core().connect_signal("touch_motion", &on_touch_motion_event);
wf::get_core().output_layout->connect_signal("output-removed",
&on_output_removed);
}
~wfs_hotspot()
{
wf::get_core().disconnect_signal("pointer_motion", &on_motion_event);
wf::get_core().disconnect_signal("tablet_axis", &on_motion_event);
wf::get_core().disconnect_signal("touch_motion", &on_touch_motion_event);
wf::get_core().output_layout->disconnect_signal("output-removed",
&on_output_removed);
}
};
static void handle_hotspot_destroy(wl_resource *resource)
{
auto *hotspot = (wfs_hotspot*)wl_resource_get_user_data(resource);
delete hotspot;
wl_resource_set_user_data(resource, nullptr);
}
/* ------------------------------ wfs_output -------------------------------- */
static void handle_output_destroy(wl_resource *resource);
static void handle_zwf_output_inhibit_output(wl_client*, wl_resource *resource);
static void handle_zwf_output_inhibit_output_done(wl_client*,
wl_resource *resource);
static void handle_zwf_output_create_hotspot(wl_client*, wl_resource *resource,
uint32_t hotspot, uint32_t threshold, uint32_t timeout, uint32_t id);
static struct zwf_output_v2_interface zwf_output_impl = {
.inhibit_output = handle_zwf_output_inhibit_output,
.inhibit_output_done = handle_zwf_output_inhibit_output_done,
.create_hotspot = handle_zwf_output_create_hotspot,
};
/**
* Represents a zwf_output_v2.
* Lifetime is managed by the wl_resource
*/
class wfs_output : public noncopyable_t
{
uint32_t num_inhibits = 0;
wl_resource *resource;
wf::output_t *output;
void disconnect_from_output()
{
wf::get_core().output_layout->disconnect_signal("output-removed",
&on_output_removed);
output->disconnect_signal("fullscreen-layer-focused", &on_fullscreen_layer_focused);
}
wf::signal_callback_t on_output_removed = [=] (wf::signal_data_t *data)
{
auto ev = static_cast<output_removed_signal*> (data);
if (ev->output == this->output)
{
disconnect_from_output();
this->output = nullptr;
}
};
wf::signal_callback_t on_fullscreen_layer_focused = [=] (wf::signal_data_t *data)
{
if (data != nullptr) {
zwf_output_v2_send_enter_fullscreen(resource);
} else {
zwf_output_v2_send_leave_fullscreen(resource);
}
};
public:
wfs_output(wf::output_t *output, wl_client *client, int id)
{
this->output = output;
resource = wl_resource_create(client, &zwf_output_v2_interface, 1, id);
wl_resource_set_implementation(resource, &zwf_output_impl,
this, handle_output_destroy);
output->connect_signal("fullscreen-layer-focused", &on_fullscreen_layer_focused);
wf::get_core().output_layout->connect_signal("output-removed",
&on_output_removed);
}
~wfs_output()
{
if (!this->output)
{
/* The wayfire output was destroyed. Gracefully do nothing */
return;
}
disconnect_from_output();
/* Remove any remaining inhibits, otherwise the compositor will never
* be "unlocked" */
while (num_inhibits > 0)
{
this->output->render->add_inhibit(false);
--num_inhibits;
}
}
void inhibit_output()
{
++this->num_inhibits;
if (this->output)
this->output->render->add_inhibit(true);
}
void inhibit_output_done()
{
if (this->num_inhibits == 0)
{
wl_resource_post_no_memory(resource);
return;
}
--this->num_inhibits;
if (this->output)
this->output->render->add_inhibit(false);
}
void create_hotspot(uint32_t hotspot, uint32_t threshold, uint32_t timeout,
uint32_t id)
{
// will be auto-deleted when the resource is destroyed by the client
new wfs_hotspot(this->output, hotspot, threshold, timeout,
wl_resource_get_client(this->resource), id);
}
};
static void handle_zwf_output_inhibit_output(wl_client*, wl_resource *resource)
{
auto output = (wfs_output*)wl_resource_get_user_data(resource);
output->inhibit_output();
}
static void handle_zwf_output_inhibit_output_done(
wl_client*, wl_resource *resource)
{
auto output = (wfs_output*)wl_resource_get_user_data(resource);
output->inhibit_output_done();
}
static void handle_zwf_output_create_hotspot(wl_client*, wl_resource *resource,
uint32_t hotspot, uint32_t threshold, uint32_t timeout, uint32_t id)
{
auto output = (wfs_output*)wl_resource_get_user_data(resource);
output->create_hotspot(hotspot, threshold, timeout, id);
}
static void handle_output_destroy(wl_resource *resource)
{
auto *output = (wfs_output*)wl_resource_get_user_data(resource);
delete output;
wl_resource_set_user_data(resource, nullptr);
}
/* ------------------------------ wfs_surface ------------------------------- */
static void handle_surface_destroy(wl_resource *resource);
static void handle_zwf_surface_interactive_move(wl_client*,
wl_resource *resource);
static struct zwf_surface_v2_interface zwf_surface_impl = {
.interactive_move = handle_zwf_surface_interactive_move,
};
/**
* Represents a zwf_surface_v2.
* Lifetime is managed by the wl_resource
*/
class wfs_surface : public noncopyable_t
{
wl_resource *resource;
wayfire_view view;
wf::signal_callback_t on_unmap = [=] (wf::signal_data_t *data)
{
view = nullptr;
};
public:
wfs_surface(wayfire_view view, wl_client *client, int id)
{
this->view = view;
resource = wl_resource_create(client, &zwf_surface_v2_interface, 1, id);
wl_resource_set_implementation(resource, &zwf_surface_impl,
this, handle_surface_destroy);
view->connect_signal("unmap", &on_unmap);
}
~wfs_surface()
{
if (this->view)
view->disconnect_signal("unmap", &on_unmap);
}
void interactive_move()
{
if (view) view->move_request();
}
};
static void handle_zwf_surface_interactive_move(wl_client*, wl_resource *resource)
{
auto surface = (wfs_surface*)wl_resource_get_user_data(resource);
surface->interactive_move();
}
static void handle_surface_destroy(wl_resource *resource)
{
auto surface = (wfs_surface*)wl_resource_get_user_data(resource);
delete surface;
wl_resource_set_user_data(resource, nullptr);
}
static void zwf_shell_manager_get_wf_output(wl_client *client,
wl_resource *resource, wl_resource *output, uint32_t id)
{
auto wlr_out = (wlr_output*) wl_resource_get_user_data(output);
auto wo = wf::get_core().output_layout->find_output(wlr_out);
if (wo)
{
// will be deleted when the resource is destroyed
new wfs_output(wo, client, id);
}
}
static void zwf_shell_manager_get_wf_surface(wl_client *client,
wl_resource *resource, wl_resource *surface, uint32_t id)
{
auto view = wf::wl_surface_to_wayfire_view(surface);
if (view)
{
/* Will be freed when the resource is destroyed */
new wfs_surface(view, client, id);
}
}
const struct zwf_shell_manager_v2_interface zwf_shell_manager_v2_impl =
{
zwf_shell_manager_get_wf_output,
zwf_shell_manager_get_wf_surface,
};
void bind_zwf_shell_manager(wl_client *client, void *data,
uint32_t version, uint32_t id)
{
auto resource =
wl_resource_create(client, &zwf_shell_manager_v2_interface, 1, id);
wl_resource_set_implementation(resource,
&zwf_shell_manager_v2_impl, NULL, NULL);
}
struct wayfire_shell
{
wl_global *shell_manager;
};
wayfire_shell* wayfire_shell_create(wl_display *display)
{
wayfire_shell *ws = new wayfire_shell;
ws->shell_manager = wl_global_create(display,
&zwf_shell_manager_v2_interface, 1, NULL, bind_zwf_shell_manager);
if (ws->shell_manager == NULL)
{
LOGE("Failed to create wayfire_shell interface");
delete ws;
return NULL;
}
return ws;
}
<|endoftext|> |
<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id$
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2002 MandrakeSoft S.A.
//
// MandrakeSoft S.A.
// 43, rue d'Aboukir
// 75002 Paris - France
// http://www.linux-mandrake.com/
// http://www.mandrakesoft.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 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 "iodev.h"
#if BX_SUPPORT_APIC
#include "cpu/apic.h"
class bx_ioapic_c bx_ioapic;
#define LOG_THIS bx_ioapic.
static bx_bool ioapic_read(bx_phy_address a20addr, unsigned len, void *data, void *param)
{
bx_ioapic.read(a20addr, data, len);
return 1;
}
static bx_bool ioapic_write(bx_phy_address a20addr, unsigned len, void *data, void *param)
{
if (len != 4) {
BX_PANIC (("I/O apic write with len=%d (should be 4)", len));
}
bx_ioapic.write(a20addr, (Bit32u*) data, len);
return 1;
}
void bx_io_redirect_entry_t::sprintf_self(char *buf)
{
sprintf(buf, "dest=%02x, masked=%d, trig_mode=%d, remote_irr=%d, polarity=%d, delivery_status=%d, dest_mode=%d, delivery_mode=%d, vector=%02x",
(unsigned) destination(),
(unsigned) is_masked(),
(unsigned) trigger_mode(),
(unsigned) remote_irr(),
(unsigned) pin_polarity(),
(unsigned) delivery_status(),
(unsigned) destination_mode(),
(unsigned) delivery_mode(),
(unsigned) vector());
}
void bx_io_redirect_entry_t::register_state(bx_param_c *parent)
{
BXRS_HEX_PARAM_SIMPLE(parent, lo);
BXRS_HEX_PARAM_SIMPLE(parent, hi);
}
#define BX_IOAPIC_BASE_ADDR (0xfec00000)
bx_ioapic_c::bx_ioapic_c()
: bx_generic_apic_c(BX_IOAPIC_BASE_ADDR)
{
put("IOAP");
}
#define BX_IOAPIC_DEFAULT_ID (BX_SMP_PROCESSORS)
void bx_ioapic_c::init(void)
{
bx_generic_apic_c::init();
BX_INFO(("initializing I/O APIC"));
base_addr = BX_IOAPIC_BASE_ADDR;
set_id(BX_IOAPIC_DEFAULT_ID);
DEV_register_memory_handlers(&bx_ioapic,
ioapic_read, ioapic_write, base_addr, base_addr + 0xfff);
reset(BX_RESET_HARDWARE);
}
void bx_ioapic_c::reset(unsigned type)
{
// all interrupts masked
for (int i=0; i<BX_IOAPIC_NUM_PINS; i++) {
ioredtbl[i].set_lo_part(0x00010000);
ioredtbl[i].set_hi_part(0x00000000);
}
intin = 0;
irr = 0;
ioregsel = 0;
}
void bx_ioapic_c::read_aligned(bx_phy_address address, Bit32u *data)
{
BX_DEBUG(("IOAPIC: read aligned addr=%08x", address));
address &= 0xff;
if (address == 0x00) {
// select register
*data = ioregsel;
return;
} else {
if (address != 0x10)
BX_PANIC(("IOAPIC: read from unsupported address"));
}
// only reached when reading data register
switch (ioregsel) {
case 0x00: // APIC ID, note this is 4bits, the upper 4 are reserved
*data = ((id & APIC_ID_MASK) << 24);
return;
case 0x01: // version
*data = BX_IOAPIC_VERSION_ID;
return;
case 0x02:
BX_INFO(("IOAPIC: arbitration ID unsupported, returned 0"));
*data = 0;
return;
default:
int index = (ioregsel - 0x10) >> 1;
if (index >= 0 && index < BX_IOAPIC_NUM_PINS) {
bx_io_redirect_entry_t *entry = ioredtbl + index;
*data = (ioregsel&1) ? entry->get_hi_part() : entry->get_lo_part();
return;
}
BX_PANIC(("IOAPIC: IOREGSEL points to undefined register %02x", ioregsel));
}
}
void bx_ioapic_c::write_aligned(bx_phy_address address, Bit32u *value)
{
BX_DEBUG(("IOAPIC: write aligned addr=%08x, data=%08x", address, *value));
address &= 0xff;
if (address == 0x00) {
ioregsel = *value;
return;
} else {
if (address != 0x10)
BX_PANIC(("IOAPIC: write to unsupported address"));
}
// only reached when writing data register
switch (ioregsel) {
case 0x00: // set APIC ID
{
Bit8u newid = (*value >> 24) & APIC_ID_MASK;
BX_INFO(("IOAPIC: setting id to 0x%x", newid));
set_id (newid);
return;
}
case 0x01: // version
case 0x02: // arbitration id
BX_INFO(("IOAPIC: could not write, IOREGSEL=0x%02x", ioregsel));
return;
default:
int index = (ioregsel - 0x10) >> 1;
if (index >= 0 && index < BX_IOAPIC_NUM_PINS) {
bx_io_redirect_entry_t *entry = ioredtbl + index;
if (ioregsel&1)
entry->set_hi_part(*value);
else
entry->set_lo_part(*value);
char buf[1024];
entry->sprintf_self(buf);
BX_DEBUG(("IOAPIC: now entry[%d] is %s", index, buf));
service_ioapic();
return;
}
BX_PANIC(("IOAPIC: IOREGSEL points to undefined register %02x", ioregsel));
}
}
void bx_ioapic_c::set_irq_level(Bit8u int_in, bx_bool level)
{
BX_DEBUG(("set_irq_level(): INTIN%d: level=%d", int_in, level));
if (int_in < BX_IOAPIC_NUM_PINS) {
Bit32u bit = 1<<int_in;
if ((level<<int_in) != (intin & bit)) {
bx_io_redirect_entry_t *entry = ioredtbl + int_in;
if (entry->trigger_mode()) {
// level triggered
if (level) {
intin |= bit;
irr |= bit;
service_ioapic();
} else {
intin &= ~bit;
irr &= ~bit;
}
} else {
// edge triggered
if (level) {
intin |= bit;
irr |= bit;
service_ioapic();
} else {
intin &= ~bit;
}
}
}
}
}
void bx_ioapic_c::receive_eoi(Bit8u vector)
{
BX_DEBUG(("IOAPIC: received EOI for vector %d", vector));
}
void bx_ioapic_c::service_ioapic()
{
static unsigned int stuck = 0;
Bit8u vector = 0;
// look in IRR and deliver any interrupts that are not masked.
BX_DEBUG(("IOAPIC: servicing"));
for (unsigned bit=0; bit < BX_IOAPIC_NUM_PINS; bit++) {
Bit32u mask = 1<<bit;
if (irr & mask) {
bx_io_redirect_entry_t *entry = ioredtbl + bit;
if (! entry->is_masked()) {
// clear irr bit and deliver
if (entry->delivery_mode() == 7) {
vector = DEV_pic_iac();
} else {
vector = entry->vector();
}
bx_bool done = apic_bus_deliver_interrupt(vector, entry->destination(), entry->delivery_mode(), entry->destination_mode(), entry->pin_polarity(), entry->trigger_mode());
if (done) {
if (! entry->trigger_mode())
irr &= ~mask;
entry->clear_delivery_status();
stuck = 0;
} else {
entry->set_delivery_status();
stuck++;
if (stuck > 5)
BX_INFO(("vector %#x stuck?", vector));
}
}
else {
BX_DEBUG(("service_ioapic(): INTIN%d is masked", bit));
}
}
}
}
void bx_ioapic_c::register_state(void)
{
bx_list_c *list = new bx_list_c(SIM->get_bochs_root(), "ioapic", "IOAPIC State", 4);
BXRS_HEX_PARAM_SIMPLE(list, ioregsel);
BXRS_HEX_PARAM_SIMPLE(list, intin);
BXRS_HEX_PARAM_SIMPLE(list, irr);
bx_list_c *table = new bx_list_c(list, "ioredtbl", BX_IOAPIC_NUM_PINS);
for (unsigned i=0; i<BX_IOAPIC_NUM_PINS; i++) {
char name[6];
sprintf(name, "0x%02x", i);
bx_list_c *entry = new bx_list_c(table, name, 2);
ioredtbl[i].register_state(entry);
}
}
#endif /* if BX_SUPPORT_APIC */
<commit_msg>faster i/o apic write access<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id$
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2002 MandrakeSoft S.A.
//
// MandrakeSoft S.A.
// 43, rue d'Aboukir
// 75002 Paris - France
// http://www.linux-mandrake.com/
// http://www.mandrakesoft.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 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 "iodev.h"
#if BX_SUPPORT_APIC
#include "cpu/apic.h"
class bx_ioapic_c bx_ioapic;
#define LOG_THIS bx_ioapic.
static bx_bool ioapic_read(bx_phy_address a20addr, unsigned len, void *data, void *param)
{
bx_ioapic.read(a20addr, data, len);
return 1;
}
static bx_bool ioapic_write(bx_phy_address a20addr, unsigned len, void *data, void *param)
{
if (len != 4) {
BX_PANIC (("I/O apic write with len=%d (should be 4)", len));
return 1;
}
if(a20addr & 3) {
BX_PANIC(("I/O apic write at unaligned address 0x" FMT_PHY_ADDRX, a20addr));
return 1;
}
bx_ioapic.write_aligned(a20addr, (Bit32u*) data);
return 1;
}
void bx_io_redirect_entry_t::sprintf_self(char *buf)
{
sprintf(buf, "dest=%02x, masked=%d, trig_mode=%d, remote_irr=%d, polarity=%d, delivery_status=%d, dest_mode=%d, delivery_mode=%d, vector=%02x",
(unsigned) destination(),
(unsigned) is_masked(),
(unsigned) trigger_mode(),
(unsigned) remote_irr(),
(unsigned) pin_polarity(),
(unsigned) delivery_status(),
(unsigned) destination_mode(),
(unsigned) delivery_mode(),
(unsigned) vector());
}
void bx_io_redirect_entry_t::register_state(bx_param_c *parent)
{
BXRS_HEX_PARAM_SIMPLE(parent, lo);
BXRS_HEX_PARAM_SIMPLE(parent, hi);
}
#define BX_IOAPIC_BASE_ADDR (0xfec00000)
bx_ioapic_c::bx_ioapic_c()
: bx_generic_apic_c(BX_IOAPIC_BASE_ADDR)
{
put("IOAP");
}
#define BX_IOAPIC_DEFAULT_ID (BX_SMP_PROCESSORS)
void bx_ioapic_c::init(void)
{
bx_generic_apic_c::init();
BX_INFO(("initializing I/O APIC"));
base_addr = BX_IOAPIC_BASE_ADDR;
set_id(BX_IOAPIC_DEFAULT_ID);
DEV_register_memory_handlers(&bx_ioapic,
ioapic_read, ioapic_write, base_addr, base_addr + 0xfff);
reset(BX_RESET_HARDWARE);
}
void bx_ioapic_c::reset(unsigned type)
{
// all interrupts masked
for (int i=0; i<BX_IOAPIC_NUM_PINS; i++) {
ioredtbl[i].set_lo_part(0x00010000);
ioredtbl[i].set_hi_part(0x00000000);
}
intin = 0;
irr = 0;
ioregsel = 0;
}
void bx_ioapic_c::read_aligned(bx_phy_address address, Bit32u *data)
{
BX_DEBUG(("IOAPIC: read aligned addr=%08x", address));
address &= 0xff;
if (address == 0x00) {
// select register
*data = ioregsel;
return;
} else {
if (address != 0x10)
BX_PANIC(("IOAPIC: read from unsupported address"));
}
// only reached when reading data register
switch (ioregsel) {
case 0x00: // APIC ID, note this is 4bits, the upper 4 are reserved
*data = ((id & APIC_ID_MASK) << 24);
return;
case 0x01: // version
*data = BX_IOAPIC_VERSION_ID;
return;
case 0x02:
BX_INFO(("IOAPIC: arbitration ID unsupported, returned 0"));
*data = 0;
return;
default:
int index = (ioregsel - 0x10) >> 1;
if (index >= 0 && index < BX_IOAPIC_NUM_PINS) {
bx_io_redirect_entry_t *entry = ioredtbl + index;
*data = (ioregsel&1) ? entry->get_hi_part() : entry->get_lo_part();
return;
}
BX_PANIC(("IOAPIC: IOREGSEL points to undefined register %02x", ioregsel));
}
}
void bx_ioapic_c::write_aligned(bx_phy_address address, Bit32u *value)
{
BX_DEBUG(("IOAPIC: write aligned addr=%08x, data=%08x", address, *value));
address &= 0xff;
if (address == 0x00) {
ioregsel = *value;
return;
} else {
if (address != 0x10)
BX_PANIC(("IOAPIC: write to unsupported address"));
}
// only reached when writing data register
switch (ioregsel) {
case 0x00: // set APIC ID
{
Bit8u newid = (*value >> 24) & APIC_ID_MASK;
BX_INFO(("IOAPIC: setting id to 0x%x", newid));
set_id (newid);
return;
}
case 0x01: // version
case 0x02: // arbitration id
BX_INFO(("IOAPIC: could not write, IOREGSEL=0x%02x", ioregsel));
return;
default:
int index = (ioregsel - 0x10) >> 1;
if (index >= 0 && index < BX_IOAPIC_NUM_PINS) {
bx_io_redirect_entry_t *entry = ioredtbl + index;
if (ioregsel&1)
entry->set_hi_part(*value);
else
entry->set_lo_part(*value);
char buf[1024];
entry->sprintf_self(buf);
BX_DEBUG(("IOAPIC: now entry[%d] is %s", index, buf));
service_ioapic();
return;
}
BX_PANIC(("IOAPIC: IOREGSEL points to undefined register %02x", ioregsel));
}
}
void bx_ioapic_c::set_irq_level(Bit8u int_in, bx_bool level)
{
BX_DEBUG(("set_irq_level(): INTIN%d: level=%d", int_in, level));
if (int_in < BX_IOAPIC_NUM_PINS) {
Bit32u bit = 1<<int_in;
if ((level<<int_in) != (intin & bit)) {
bx_io_redirect_entry_t *entry = ioredtbl + int_in;
if (entry->trigger_mode()) {
// level triggered
if (level) {
intin |= bit;
irr |= bit;
service_ioapic();
} else {
intin &= ~bit;
irr &= ~bit;
}
} else {
// edge triggered
if (level) {
intin |= bit;
irr |= bit;
service_ioapic();
} else {
intin &= ~bit;
}
}
}
}
}
void bx_ioapic_c::receive_eoi(Bit8u vector)
{
BX_DEBUG(("IOAPIC: received EOI for vector %d", vector));
}
void bx_ioapic_c::service_ioapic()
{
static unsigned int stuck = 0;
Bit8u vector = 0;
// look in IRR and deliver any interrupts that are not masked.
BX_DEBUG(("IOAPIC: servicing"));
for (unsigned bit=0; bit < BX_IOAPIC_NUM_PINS; bit++) {
Bit32u mask = 1<<bit;
if (irr & mask) {
bx_io_redirect_entry_t *entry = ioredtbl + bit;
if (! entry->is_masked()) {
// clear irr bit and deliver
if (entry->delivery_mode() == 7) {
vector = DEV_pic_iac();
} else {
vector = entry->vector();
}
bx_bool done = apic_bus_deliver_interrupt(vector, entry->destination(), entry->delivery_mode(), entry->destination_mode(), entry->pin_polarity(), entry->trigger_mode());
if (done) {
if (! entry->trigger_mode())
irr &= ~mask;
entry->clear_delivery_status();
stuck = 0;
} else {
entry->set_delivery_status();
stuck++;
if (stuck > 5)
BX_INFO(("vector %#x stuck?", vector));
}
}
else {
BX_DEBUG(("service_ioapic(): INTIN%d is masked", bit));
}
}
}
}
void bx_ioapic_c::register_state(void)
{
bx_list_c *list = new bx_list_c(SIM->get_bochs_root(), "ioapic", "IOAPIC State", 4);
BXRS_HEX_PARAM_SIMPLE(list, ioregsel);
BXRS_HEX_PARAM_SIMPLE(list, intin);
BXRS_HEX_PARAM_SIMPLE(list, irr);
bx_list_c *table = new bx_list_c(list, "ioredtbl", BX_IOAPIC_NUM_PINS);
for (unsigned i=0; i<BX_IOAPIC_NUM_PINS; i++) {
char name[6];
sprintf(name, "0x%02x", i);
bx_list_c *entry = new bx_list_c(table, name, 2);
ioredtbl[i].register_state(entry);
}
}
#endif /* if BX_SUPPORT_APIC */
<|endoftext|> |
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#ifndef MFEM_FORALL_HPP
#define MFEM_FORALL_HPP
#include "../config/config.hpp"
#include "error.hpp"
#include "backends.hpp"
#include "device.hpp"
#include "mem_manager.hpp"
#include "../linalg/dtensor.hpp"
namespace mfem
{
// Maximum size of dofs and quads in 1D.
const int MAX_D1D = 14;
const int MAX_Q1D = 14;
// MFEM pragma macros that can be used inside MFEM_FORALL macros.
#define MFEM_PRAGMA(X) _Pragma(#X)
// MFEM_UNROLL pragma macro that can be used inside MFEM_FORALL macros.
#if defined(MFEM_USE_CUDA)
#define MFEM_UNROLL(N) MFEM_PRAGMA(unroll N)
#else
#define MFEM_UNROLL(N)
#endif
// Implementation of MFEM's "parallel for" (forall) device/host kernel
// interfaces supporting RAJA, CUDA, OpenMP, and sequential backends.
// The MFEM_FORALL wrapper
#define MFEM_FORALL(i,N,...) \
ForallWrap<1>(true,N, \
[=] MFEM_DEVICE (int i) {__VA_ARGS__}, \
[&] MFEM_LAMBDA (int i) {__VA_ARGS__})
// MFEM_FORALL with a 2D CUDA block
#define MFEM_FORALL_2D(i,N,X,Y,BZ,...) \
ForallWrap<2>(true,N, \
[=] MFEM_DEVICE (int i) {__VA_ARGS__}, \
[&] MFEM_LAMBDA (int i) {__VA_ARGS__},\
X,Y,BZ)
// MFEM_FORALL with a 3D CUDA block
#define MFEM_FORALL_3D(i,N,X,Y,Z,...) \
ForallWrap<3>(true,N, \
[=] MFEM_DEVICE (int i) {__VA_ARGS__}, \
[&] MFEM_LAMBDA (int i) {__VA_ARGS__},\
X,Y,Z)
// MFEM_FORALL that uses the basic CPU backend when use_dev is false. See for
// example the functions in vector.cpp, where we don't want to use the mfem
// device for operations on small vectors.
#define MFEM_FORALL_SWITCH(use_dev,i,N,...) \
ForallWrap<1>(use_dev,N, \
[=] MFEM_DEVICE (int i) {__VA_ARGS__}, \
[&] MFEM_LAMBDA (int i) {__VA_ARGS__})
/// OpenMP backend
template <typename HBODY>
void OmpWrap(const int N, HBODY &&h_body)
{
#ifdef MFEM_USE_OPENMP
#pragma omp parallel for
for (int k = 0; k < N; k++)
{
h_body(k);
}
#else
MFEM_CONTRACT_VAR(N);
MFEM_CONTRACT_VAR(h_body);
MFEM_ABORT("OpenMP requested for MFEM but OpenMP is not enabled!");
#endif
}
/// RAJA Cuda backend
#if defined(MFEM_USE_RAJA) && defined(RAJA_ENABLE_CUDA)
using RAJA::statement::Segs;
template <const int BLOCKS = MFEM_CUDA_BLOCKS, typename DBODY>
void RajaCudaWrap1D(const int N, DBODY &&d_body)
{
//true denotes asynchronous kernel
RAJA::forall<RAJA::cuda_exec<BLOCKS,true>>(RAJA::RangeSegment(0,N),d_body);
}
template <typename DBODY>
void RajaCudaWrap2D(const int N, DBODY &&d_body,
const int X, const int Y, const int BZ)
{
MFEM_VERIFY(N>0, "");
MFEM_VERIFY(BZ>0, "");
const int G = (N+BZ-1)/BZ;
RAJA::kernel<RAJA::KernelPolicy<
RAJA::statement::CudaKernelAsync<
RAJA::statement::For<0, RAJA::cuda_block_x_direct,
RAJA::statement::For<1, RAJA::cuda_thread_x_direct,
RAJA::statement::For<2, RAJA::cuda_thread_y_direct,
RAJA::statement::For<3, RAJA::cuda_thread_z_direct,
RAJA::statement::Lambda<0, Segs<0>>>>>>>>>
(RAJA::make_tuple(RAJA::RangeSegment(0,G), RAJA::RangeSegment(0,X),
RAJA::RangeSegment(0,Y), RAJA::RangeSegment(0,BZ)),
[=] RAJA_DEVICE (const int n)
{
const int k = n*BZ + threadIdx.z;
if (k >= N) { return; }
d_body(k);
});
MFEM_GPU_CHECK(cudaGetLastError());
}
template <typename DBODY>
void RajaCudaWrap3D(const int N, DBODY &&d_body,
const int X, const int Y, const int Z)
{
MFEM_VERIFY(N>0, "");
RAJA::kernel<RAJA::KernelPolicy<
RAJA::statement::CudaKernelAsync<
RAJA::statement::For<0, RAJA::cuda_block_x_direct,
RAJA::statement::For<1, RAJA::cuda_thread_x_direct,
RAJA::statement::For<2, RAJA::cuda_thread_y_direct,
RAJA::statement::For<3, RAJA::cuda_thread_z_direct,
RAJA::statement::Lambda<0, Segs<0>>>>>>>>>
(RAJA::make_tuple(RAJA::RangeSegment(0,N), RAJA::RangeSegment(0,X),
RAJA::RangeSegment(0,Y), RAJA::RangeSegment(0,Z)),
[=] RAJA_DEVICE (const int k) { d_body(k); });
MFEM_GPU_CHECK(cudaGetLastError());
}
#endif
/// RAJA OpenMP backend
#if defined(MFEM_USE_RAJA) && defined(RAJA_ENABLE_OPENMP)
using RAJA::statement::Segs;
template <typename HBODY>
void RajaOmpWrap(const int N, HBODY &&h_body)
{
RAJA::forall<RAJA::omp_parallel_for_exec>(RAJA::RangeSegment(0,N), h_body);
}
#endif
/// RAJA sequential loop backend
template <typename HBODY>
void RajaSeqWrap(const int N, HBODY &&h_body)
{
#ifdef MFEM_USE_RAJA
RAJA::forall<RAJA::loop_exec>(RAJA::RangeSegment(0,N), h_body);
#else
MFEM_CONTRACT_VAR(N);
MFEM_CONTRACT_VAR(h_body);
MFEM_ABORT("RAJA requested but RAJA is not enabled!");
#endif
}
/// CUDA backend
#ifdef MFEM_USE_CUDA
template <typename BODY> __global__ static
void CuKernel1D(const int N, BODY body)
{
const int k = blockDim.x*blockIdx.x + threadIdx.x;
if (k >= N) { return; }
body(k);
}
template <typename BODY> __global__ static
void CuKernel2D(const int N, BODY body, const int BZ)
{
const int k = blockIdx.x*BZ + threadIdx.z;
if (k >= N) { return; }
body(k);
}
template <typename BODY> __global__ static
void CuKernel3D(const int N, BODY body)
{
const int k = blockIdx.x;
if (k >= N) { return; }
body(k);
}
template <const int BLCK = MFEM_CUDA_BLOCKS, typename DBODY>
void CuWrap1D(const int N, DBODY &&d_body)
{
if (N==0) { return; }
const int GRID = (N+BLCK-1)/BLCK;
CuKernel1D<<<GRID,BLCK>>>(N, d_body);
MFEM_GPU_CHECK(cudaGetLastError());
}
template <typename DBODY>
void CuWrap2D(const int N, DBODY &&d_body,
const int X, const int Y, const int BZ)
{
if (N==0) { return; }
MFEM_VERIFY(BZ>0, "");
const int GRID = (N+BZ-1)/BZ;
const dim3 BLCK(X,Y,BZ);
CuKernel2D<<<GRID,BLCK>>>(N,d_body,BZ);
MFEM_GPU_CHECK(cudaGetLastError());
}
template <typename DBODY>
void CuWrap3D(const int N, DBODY &&d_body,
const int X, const int Y, const int Z)
{
if (N==0) { return; }
const int GRID = N;
const dim3 BLCK(X,Y,Z);
CuKernel3D<<<GRID,BLCK>>>(N,d_body);
MFEM_GPU_CHECK(cudaGetLastError());
}
#endif // MFEM_USE_CUDA
/// HIP backend
#ifdef MFEM_USE_HIP
template <typename BODY> __global__ static
void HipKernel1D(const int N, BODY body)
{
const int k = hipBlockDim_x*hipBlockIdx_x + hipThreadIdx_x;
if (k >= N) { return; }
body(k);
}
template <typename BODY> __global__ static
void HipKernel2D(const int N, BODY body, const int BZ)
{
const int k = hipBlockIdx_x*BZ + hipThreadIdx_z;
if (k >= N) { return; }
body(k);
}
template <typename BODY> __global__ static
void HipKernel3D(const int N, BODY body)
{
const int k = hipBlockIdx_x;
if (k >= N) { return; }
body(k);
}
template <const int BLCK = MFEM_HIP_BLOCKS, typename DBODY>
void HipWrap1D(const int N, DBODY &&d_body)
{
if (N==0) { return; }
const int GRID = (N+BLCK-1)/BLCK;
hipLaunchKernelGGL(HipKernel1D,GRID,BLCK,0,0,N,d_body);
MFEM_GPU_CHECK(hipGetLastError());
}
template <typename DBODY>
void HipWrap2D(const int N, DBODY &&d_body,
const int X, const int Y, const int BZ)
{
if (N==0) { return; }
const int GRID = (N+BZ-1)/BZ;
const dim3 BLCK(X,Y,BZ);
hipLaunchKernelGGL(HipKernel2D,GRID,BLCK,0,0,N,d_body,BZ);
MFEM_GPU_CHECK(hipGetLastError());
}
template <typename DBODY>
void HipWrap3D(const int N, DBODY &&d_body,
const int X, const int Y, const int Z)
{
if (N==0) { return; }
const int GRID = N;
const dim3 BLCK(X,Y,Z);
hipLaunchKernelGGL(HipKernel3D,GRID,BLCK,0,0,N,d_body);
MFEM_GPU_CHECK(hipGetLastError());
}
#endif // MFEM_USE_HIP
/// The forall kernel body wrapper
template <const int DIM, typename DBODY, typename HBODY>
inline void ForallWrap(const bool use_dev, const int N,
DBODY &&d_body, HBODY &&h_body,
const int X=0, const int Y=0, const int Z=0)
{
MFEM_CONTRACT_VAR(X);
MFEM_CONTRACT_VAR(Y);
MFEM_CONTRACT_VAR(Z);
MFEM_CONTRACT_VAR(d_body);
if (!use_dev) { goto backend_cpu; }
#if defined(MFEM_USE_RAJA) && defined(RAJA_ENABLE_CUDA)
// Handle all allowed CUDA backends except Backend::CUDA
if (DIM == 1 && Device::Allows(Backend::CUDA_MASK & ~Backend::CUDA))
{ return RajaCudaWrap1D(N, d_body); }
if (DIM == 2 && Device::Allows(Backend::CUDA_MASK & ~Backend::CUDA))
{ return RajaCudaWrap2D(N, d_body, X, Y, Z); }
if (DIM == 3 && Device::Allows(Backend::CUDA_MASK & ~Backend::CUDA))
{ return RajaCudaWrap3D(N, d_body, X, Y, Z); }
#endif
#ifdef MFEM_USE_CUDA
// Handle all allowed CUDA backends
if (DIM == 1 && Device::Allows(Backend::CUDA_MASK))
{ return CuWrap1D(N, d_body); }
if (DIM == 2 && Device::Allows(Backend::CUDA_MASK))
{ return CuWrap2D(N, d_body, X, Y, Z); }
if (DIM == 3 && Device::Allows(Backend::CUDA_MASK))
{ return CuWrap3D(N, d_body, X, Y, Z); }
#endif
#ifdef MFEM_USE_HIP
// Handle all allowed HIP backends
if (DIM == 1 && Device::Allows(Backend::HIP_MASK))
{ return HipWrap1D(N, d_body); }
if (DIM == 2 && Device::Allows(Backend::HIP_MASK))
{ return HipWrap2D(N, d_body, X, Y, Z); }
if (DIM == 3 && Device::Allows(Backend::HIP_MASK))
{ return HipWrap3D(N, d_body, X, Y, Z); }
#endif
if (Device::Allows(Backend::DEBUG_DEVICE)) { goto backend_cpu; }
#if defined(MFEM_USE_RAJA) && defined(RAJA_ENABLE_OPENMP)
// Handle all allowed OpenMP backends except Backend::OMP
if (Device::Allows(Backend::OMP_MASK & ~Backend::OMP))
{ return RajaOmpWrap(N, h_body); }
#endif
#ifdef MFEM_USE_OPENMP
// Handle all allowed OpenMP backends
if (Device::Allows(Backend::OMP_MASK)) { return OmpWrap(N, h_body); }
#endif
#ifdef MFEM_USE_RAJA
// Handle all allowed CPU backends except Backend::CPU
if (Device::Allows(Backend::CPU_MASK & ~Backend::CPU))
{ return RajaSeqWrap(N, h_body); }
#endif
backend_cpu:
// Handle Backend::CPU. This is also a fallback for any allowed backends not
// handled above, e.g. OCCA_CPU with configuration 'occa-cpu,cpu', or
// OCCA_OMP with configuration 'occa-omp,cpu'.
for (int k = 0; k < N; k++) { h_body(k); }
}
} // namespace mfem
#endif // MFEM_FORALL_HPP
<commit_msg>RAJA::Kernel->RAJA::Teams<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#ifndef MFEM_FORALL_HPP
#define MFEM_FORALL_HPP
#include "../config/config.hpp"
#include "error.hpp"
#include "backends.hpp"
#include "device.hpp"
#include "mem_manager.hpp"
#include "../linalg/dtensor.hpp"
namespace mfem
{
// Maximum size of dofs and quads in 1D.
const int MAX_D1D = 14;
const int MAX_Q1D = 14;
// MFEM pragma macros that can be used inside MFEM_FORALL macros.
#define MFEM_PRAGMA(X) _Pragma(#X)
// MFEM_UNROLL pragma macro that can be used inside MFEM_FORALL macros.
#if defined(MFEM_USE_CUDA)
#define MFEM_UNROLL(N) MFEM_PRAGMA(unroll N)
#else
#define MFEM_UNROLL(N)
#endif
// Implementation of MFEM's "parallel for" (forall) device/host kernel
// interfaces supporting RAJA, CUDA, OpenMP, and sequential backends.
// The MFEM_FORALL wrapper
#define MFEM_FORALL(i,N,...) \
ForallWrap<1>(true,N, \
[=] MFEM_DEVICE (int i) {__VA_ARGS__}, \
[&] MFEM_LAMBDA (int i) {__VA_ARGS__})
// MFEM_FORALL with a 2D CUDA block
#define MFEM_FORALL_2D(i,N,X,Y,BZ,...) \
ForallWrap<2>(true,N, \
[=] MFEM_DEVICE (int i) {__VA_ARGS__}, \
[&] MFEM_LAMBDA (int i) {__VA_ARGS__},\
X,Y,BZ)
// MFEM_FORALL with a 3D CUDA block
#define MFEM_FORALL_3D(i,N,X,Y,Z,...) \
ForallWrap<3>(true,N, \
[=] MFEM_DEVICE (int i) {__VA_ARGS__}, \
[&] MFEM_LAMBDA (int i) {__VA_ARGS__},\
X,Y,Z)
// MFEM_FORALL that uses the basic CPU backend when use_dev is false. See for
// example the functions in vector.cpp, where we don't want to use the mfem
// device for operations on small vectors.
#define MFEM_FORALL_SWITCH(use_dev,i,N,...) \
ForallWrap<1>(use_dev,N, \
[=] MFEM_DEVICE (int i) {__VA_ARGS__}, \
[&] MFEM_LAMBDA (int i) {__VA_ARGS__})
/// OpenMP backend
template <typename HBODY>
void OmpWrap(const int N, HBODY &&h_body)
{
#ifdef MFEM_USE_OPENMP
#pragma omp parallel for
for (int k = 0; k < N; k++)
{
h_body(k);
}
#else
MFEM_CONTRACT_VAR(N);
MFEM_CONTRACT_VAR(h_body);
MFEM_ABORT("OpenMP requested for MFEM but OpenMP is not enabled!");
#endif
}
/// RAJA Cuda backend
#if defined(MFEM_USE_RAJA) && defined(RAJA_ENABLE_CUDA)
using launch_policy =
RAJA::expt::LaunchPolicy<RAJA::expt::null_launch_t, RAJA::expt::cuda_launch_t<false>>;
using teams_x = RAJA::expt::LoopPolicy<RAJA::loop_exec,RAJA::cuda_block_x_direct>;
using threads_z = RAJA::expt::LoopPolicy<RAJA::loop_exec,RAJA::cuda_thread_z_direct>;
template <const int BLOCKS = MFEM_CUDA_BLOCKS, typename DBODY>
void RajaCudaWrap1D(const int N, DBODY &&d_body)
{
//true denotes asynchronous kernel
RAJA::forall<RAJA::cuda_exec<BLOCKS,true>>(RAJA::RangeSegment(0,N),d_body);
}
template <typename DBODY>
void RajaCudaWrap2D(const int N, DBODY &&d_body,
const int X, const int Y, const int BZ)
{
MFEM_VERIFY(N>0, "");
MFEM_VERIFY(BZ>0, "");
const int G = (N+BZ-1)/BZ;
RAJA::expt::launch<launch_policy>(RAJA::expt::DEVICE,
RAJA::expt::Resources(RAJA::expt::Teams(G), RAJA::expt::Threads(X, Y, BZ)),
[=] RAJA_DEVICE (RAJA::expt::LaunchContext ctx) {
RAJA::expt::loop<teams_x>(ctx, RAJA::RangeSegment(0, G), [&] (const int n) {
RAJA::expt::loop<threads_z>(ctx, RAJA::RangeSegment(0, BZ), [&] (const int tz) {
const int k = n*BZ + tz;
if (k >= N) { return; }
d_body(k);
});
});
});
MFEM_GPU_CHECK(cudaGetLastError());
}
template <typename DBODY>
void RajaCudaWrap3D(const int N, DBODY &&d_body,
const int X, const int Y, const int Z)
{
MFEM_VERIFY(N>0, "");
RAJA::expt::launch<launch_policy>(RAJA::expt::DEVICE,
RAJA::expt::Resources(RAJA::expt::Teams(N), RAJA::expt::Threads(X, Y, Z)),
[=] RAJA_DEVICE (RAJA::expt::LaunchContext ctx) {
RAJA::expt::loop<teams_x>(ctx, RAJA::RangeSegment(0, N), d_body);
});
MFEM_GPU_CHECK(cudaGetLastError());
}
#endif
/// RAJA OpenMP backend
#if defined(MFEM_USE_RAJA) && defined(RAJA_ENABLE_OPENMP)
using RAJA::Segs;
template <typename HBODY>
void RajaOmpWrap(const int N, HBODY &&h_body)
{
RAJA::forall<RAJA::omp_parallel_for_exec>(RAJA::RangeSegment(0,N), h_body);
}
#endif
/// RAJA sequential loop backend
template <typename HBODY>
void RajaSeqWrap(const int N, HBODY &&h_body)
{
#ifdef MFEM_USE_RAJA
RAJA::forall<RAJA::loop_exec>(RAJA::RangeSegment(0,N), h_body);
#else
MFEM_CONTRACT_VAR(N);
MFEM_CONTRACT_VAR(h_body);
MFEM_ABORT("RAJA requested but RAJA is not enabled!");
#endif
}
/// CUDA backend
#ifdef MFEM_USE_CUDA
template <typename BODY> __global__ static
void CuKernel1D(const int N, BODY body)
{
const int k = blockDim.x*blockIdx.x + threadIdx.x;
if (k >= N) { return; }
body(k);
}
template <typename BODY> __global__ static
void CuKernel2D(const int N, BODY body, const int BZ)
{
const int k = blockIdx.x*BZ + threadIdx.z;
if (k >= N) { return; }
body(k);
}
template <typename BODY> __global__ static
void CuKernel3D(const int N, BODY body)
{
const int k = blockIdx.x;
if (k >= N) { return; }
body(k);
}
template <const int BLCK = MFEM_CUDA_BLOCKS, typename DBODY>
void CuWrap1D(const int N, DBODY &&d_body)
{
if (N==0) { return; }
const int GRID = (N+BLCK-1)/BLCK;
CuKernel1D<<<GRID,BLCK>>>(N, d_body);
MFEM_GPU_CHECK(cudaGetLastError());
}
template <typename DBODY>
void CuWrap2D(const int N, DBODY &&d_body,
const int X, const int Y, const int BZ)
{
if (N==0) { return; }
MFEM_VERIFY(BZ>0, "");
const int GRID = (N+BZ-1)/BZ;
const dim3 BLCK(X,Y,BZ);
CuKernel2D<<<GRID,BLCK>>>(N,d_body,BZ);
MFEM_GPU_CHECK(cudaGetLastError());
}
template <typename DBODY>
void CuWrap3D(const int N, DBODY &&d_body,
const int X, const int Y, const int Z)
{
if (N==0) { return; }
const int GRID = N;
const dim3 BLCK(X,Y,Z);
CuKernel3D<<<GRID,BLCK>>>(N,d_body);
MFEM_GPU_CHECK(cudaGetLastError());
}
#endif // MFEM_USE_CUDA
/// HIP backend
#ifdef MFEM_USE_HIP
template <typename BODY> __global__ static
void HipKernel1D(const int N, BODY body)
{
const int k = hipBlockDim_x*hipBlockIdx_x + hipThreadIdx_x;
if (k >= N) { return; }
body(k);
}
template <typename BODY> __global__ static
void HipKernel2D(const int N, BODY body, const int BZ)
{
const int k = hipBlockIdx_x*BZ + hipThreadIdx_z;
if (k >= N) { return; }
body(k);
}
template <typename BODY> __global__ static
void HipKernel3D(const int N, BODY body)
{
const int k = hipBlockIdx_x;
if (k >= N) { return; }
body(k);
}
template <const int BLCK = MFEM_HIP_BLOCKS, typename DBODY>
void HipWrap1D(const int N, DBODY &&d_body)
{
if (N==0) { return; }
const int GRID = (N+BLCK-1)/BLCK;
hipLaunchKernelGGL(HipKernel1D,GRID,BLCK,0,0,N,d_body);
MFEM_GPU_CHECK(hipGetLastError());
}
template <typename DBODY>
void HipWrap2D(const int N, DBODY &&d_body,
const int X, const int Y, const int BZ)
{
if (N==0) { return; }
const int GRID = (N+BZ-1)/BZ;
const dim3 BLCK(X,Y,BZ);
hipLaunchKernelGGL(HipKernel2D,GRID,BLCK,0,0,N,d_body,BZ);
MFEM_GPU_CHECK(hipGetLastError());
}
template <typename DBODY>
void HipWrap3D(const int N, DBODY &&d_body,
const int X, const int Y, const int Z)
{
if (N==0) { return; }
const int GRID = N;
const dim3 BLCK(X,Y,Z);
hipLaunchKernelGGL(HipKernel3D,GRID,BLCK,0,0,N,d_body);
MFEM_GPU_CHECK(hipGetLastError());
}
#endif // MFEM_USE_HIP
/// The forall kernel body wrapper
template <const int DIM, typename DBODY, typename HBODY>
inline void ForallWrap(const bool use_dev, const int N,
DBODY &&d_body, HBODY &&h_body,
const int X=0, const int Y=0, const int Z=0)
{
MFEM_CONTRACT_VAR(X);
MFEM_CONTRACT_VAR(Y);
MFEM_CONTRACT_VAR(Z);
MFEM_CONTRACT_VAR(d_body);
if (!use_dev) { goto backend_cpu; }
#if defined(MFEM_USE_RAJA) && defined(RAJA_ENABLE_CUDA)
// Handle all allowed CUDA backends except Backend::CUDA
if (DIM == 1 && Device::Allows(Backend::CUDA_MASK & ~Backend::CUDA))
{ return RajaCudaWrap1D(N, d_body); }
if (DIM == 2 && Device::Allows(Backend::CUDA_MASK & ~Backend::CUDA))
{ return RajaCudaWrap2D(N, d_body, X, Y, Z); }
if (DIM == 3 && Device::Allows(Backend::CUDA_MASK & ~Backend::CUDA))
{ return RajaCudaWrap3D(N, d_body, X, Y, Z); }
#endif
#ifdef MFEM_USE_CUDA
// Handle all allowed CUDA backends
if (DIM == 1 && Device::Allows(Backend::CUDA_MASK))
{ return CuWrap1D(N, d_body); }
if (DIM == 2 && Device::Allows(Backend::CUDA_MASK))
{ return CuWrap2D(N, d_body, X, Y, Z); }
if (DIM == 3 && Device::Allows(Backend::CUDA_MASK))
{ return CuWrap3D(N, d_body, X, Y, Z); }
#endif
#ifdef MFEM_USE_HIP
// Handle all allowed HIP backends
if (DIM == 1 && Device::Allows(Backend::HIP_MASK))
{ return HipWrap1D(N, d_body); }
if (DIM == 2 && Device::Allows(Backend::HIP_MASK))
{ return HipWrap2D(N, d_body, X, Y, Z); }
if (DIM == 3 && Device::Allows(Backend::HIP_MASK))
{ return HipWrap3D(N, d_body, X, Y, Z); }
#endif
if (Device::Allows(Backend::DEBUG_DEVICE)) { goto backend_cpu; }
#if defined(MFEM_USE_RAJA) && defined(RAJA_ENABLE_OPENMP)
// Handle all allowed OpenMP backends except Backend::OMP
if (Device::Allows(Backend::OMP_MASK & ~Backend::OMP))
{ return RajaOmpWrap(N, h_body); }
#endif
#ifdef MFEM_USE_OPENMP
// Handle all allowed OpenMP backends
if (Device::Allows(Backend::OMP_MASK)) { return OmpWrap(N, h_body); }
#endif
#ifdef MFEM_USE_RAJA
// Handle all allowed CPU backends except Backend::CPU
if (Device::Allows(Backend::CPU_MASK & ~Backend::CPU))
{ return RajaSeqWrap(N, h_body); }
#endif
backend_cpu:
// Handle Backend::CPU. This is also a fallback for any allowed backends not
// handled above, e.g. OCCA_CPU with configuration 'occa-cpu,cpu', or
// OCCA_OMP with configuration 'occa-omp,cpu'.
for (int k = 0; k < N; k++) { h_body(k); }
}
} // namespace mfem
#endif // MFEM_FORALL_HPP
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 Rene Herthel
* Copyright (C) 2017 Jonas Fuhrmann
*
* This file is subject to the terms and conditions of the MIT License.
* See the file LICENSE in the top level directory for more details.
*/
/**
* @ingroup height_measurement
* @{
*
* @brief Service function declaration of the HeightMeasurement component
*
* @author Rene Herthel <[email protected]>
* @author Jonas Fuhrmann <[email protected]>
*/
#include "HeightMeasurementService.h"
#include "HeightMeasurementHal.h"
#include "Logger.h"
#include "LogScope.h"
#include <chrono>
#include <algorithm>
/*
* @brief Macros to check if the measured data is in range of the corresponding state.
*
* @param [DATA] The measured data.
* @param [CAL] The reference value of the calibrated data.
*/
#define RANGE(DATA, CAL) (((DATA - DELTA_VAL) < CAL) && ((DATA + DELTA_VAL) > CAL))
/*
* @brief
*/
#define AMOUNT_OF_SIGNALS (6)
/*
* @brief
*/
#define AMOUNT_OF_SAMPLES (50)
HeightMeasurementService::HeightMeasurementService(int receive_chid, int send_chid, CalibrationData *calibrationDataPtr)
: stateMachine(new HeightContext(send_chid, this))
, calibrationDataPtr(calibrationDataPtr)
, receive_chid(receive_chid)
{
// Set this to true, so the statemachine thread will run his superloop.
statemachineIsRunning = true;
// Creates the thread for the statemachine with the receive channel to listen on it.
stateMachineThread = std::thread(&HeightMeasurementService::stateMachineTask, this, receive_chid);
}
HeightMeasurementService::~HeightMeasurementService() {
delete stateMachine;
}
void HeightMeasurementService::startMeasuring() {
// Set this true, so the measurement thread will run his suoperloop.
measurementIsRunning = true;
// Creates the thread for the measurement with the receive channel to send on it.
measurementThread = std::thread(&HeightMeasurementService::measuringTask, this, receive_chid);
}
void HeightMeasurementService::stopMeasuring() {
measurementIsRunning = false;
}
void HeightMeasurementService::measuringTask(int receive_chid) {
LOG_SCOPE;
LOG_SET_LEVEL(DEBUG);
LOG_DEBUG << "[HeightMeasurementService] measuringTask() Thread started\n";
int16_t data = 0; /*< The current measured data.*/
Signal state = START; /*< The current state of the statemachine.*/
Signal oldState = state; /*< The old state of the statemachine.*/
HeightMeasurementHal hal; /*< The hal object to access the HW.*/
int err = 0; /*< Return value of msgSend.*/
// Connect to the receive channel for sending pulse-messages on it.
int coid = ConnectAttach_r(ND_LOCAL_NODE, 0, receive_chid, 0, 0);
// Do error handling, if there is no channel available.
if (coid < 0) {
// TODO: Error handling.
LOG_DEBUG << "[HeightMeasurementService] measuringTask() ConnectAttach_r failed\n";
}
/* Check if the current measured data is in a valid range of the
* corresponding calibrated data. If it is so, send a signal to the receive-
* channel, where the statemachine is listening and will do the next
* transition.
*/
int counters[AMOUNT_OF_SIGNALS] = {0};
while (measurementIsRunning) {
int inRow = 0;
int heighestCount = 0;
int heighestCountIndex = 0;
Signal newSample = state;
Signal oldSample = START;
for (int i = 0; i < 64; i++) {
hal.read(data);
dataInRange(&newSample, data);
if (oldSample != START && newSample == oldSample) {
inRow++;
if (inRow >= 8) {
counters[newSample]++;
if (counters[newSample] > heighestCount) {
heighestCount = counters[newSample];
heighestCountIndex = newSample;
}
inRow = 0;
}
}
else {
inRow = 0;
}
oldSample = newSample;
}
state = Signal(heighestCountIndex);
/*
int currentCount = 0;
Signal tmpState = state;
for (int i = 0; i < AMOUNT_OF_SAMPLES; i++) {
hal.read(data);
dataInRange(&tmpState, data);
if(tmpState != oldState) {
if (++counters[tmpState] > currentCount) {
currentCount = counters[tmpState];
state = tmpState;
}
}
//std::this_thread::sleep_for(std::chrono::microseconds(50));
}
*/
// But send only a message if there is a new state.
if (state != oldState) {
err = MsgSendPulse_r(coid, sched_get_priority_min(0), 0, state);
if (err < 0) {
// TODO Error handling.
LOG_DEBUG << "[HeightMeasurementService] measuringTask() MsgSendPulse_r failed.\n";
}
LOG_DEBUG << "[HeightMeasurementService] send measuring signal: " << state << "\n";
}
// Remember the current state as old state for the next loop.
oldState = state;
// Reset the counters
std::fill(counters, counters + AMOUNT_OF_SIGNALS, 0);
}
LOG_DEBUG << "[HeightMeasurementService] measuringTask() Leaves superloop\n";
}
void HeightMeasurementService::dataInRange(Signal *state, int16_t data) {
if (RANGE(data, REF_HEIGHT_VAL)) {
*state = REF_HEIGHT;
}
else if (RANGE(data, HOLE_HEIGHT_VAL)) {
*state = HOLE_HEIGHT;
}
else if (RANGE(data, SURFACE_HEIGHT_VAL)) {
*state = SURFACE_HEIGHT;
}
else if (RANGE(data, LOW_HEIGHT_VAL)) {
*state = LOW_HEIGHT;
}
else if (RANGE(data, HIGH_HEIGHT_VAL)) {
*state = HIGH_HEIGHT;
}
else if (RANGE(data, INVALID_HEIGHT_VAL)){
*state = INVALID;
}
}
void HeightMeasurementService::stateMachineTask(int receive_chid) {
LOG_SCOPE;
LOG_SET_LEVEL(DEBUG);
LOG_DEBUG << "[HeightMeasurementService] stateMachineTask() Thread started\n";
struct _pulse pulse; /*< Structure that describes a pulse.*/
// Wait for a new incoming pulse-message to do the next transition.
while (statemachineIsRunning) {
// Returns 0 on success and a negative value on error.
int err = MsgReceivePulse_r(receive_chid, &pulse, sizeof(_pulse), NULL);
// Do error handling, if there occurs an error.
if (err < 0) {
// TODO: Error handling.
// EFAULT, EINTR, ESRCH, ETIMEDOUT -> see qnx-manual.
LOG_DEBUG << "[HeightMeasurementService] stateMachineTask() Error on MsgReceivePulse_r\n";
}
LOG_DEBUG << "[HeightMeasurementService] stateMachineTask() Received pulse: " << pulse.value.sival_int << "\n";
// Signalize the statemachine for the next transition.
stateMachine->process((Signal) pulse.value.sival_int);
}
LOG_DEBUG << "[HeightMeasurementService] stateMachineTask() Leaves superloop\n";
}
/** @} */
<commit_msg>First implementation of median of three<commit_after>/*
* Copyright (C) 2017 Rene Herthel
* Copyright (C) 2017 Jonas Fuhrmann
*
* This file is subject to the terms and conditions of the MIT License.
* See the file LICENSE in the top level directory for more details.
*/
/**
* @ingroup height_measurement
* @{
*
* @brief Service function declaration of the HeightMeasurement component
*
* @author Rene Herthel <[email protected]>
* @author Jonas Fuhrmann <[email protected]>
*/
#include "HeightMeasurementService.h"
#include "HeightMeasurementHal.h"
#include "Logger.h"
#include "LogScope.h"
#include <chrono>
#include <algorithm>
/*
* @brief Macros to check if the measured data is in range of the corresponding state.
*
* @param [DATA] The measured data.
* @param [CAL] The reference value of the calibrated data.
*/
#define RANGE(DATA, CAL) (((DATA - DELTA_VAL) < CAL) && ((DATA + DELTA_VAL) > CAL))
/*
* @brief
*/
#define AMOUNT_OF_SIGNALS (6)
/*
* @brief
*/
#define SAMPLES_AMOUNT (30)
/*
* @brief
*/
#define SAMPLES_WINDOW_SIZE (3)
#define SAMPLES_WINDOW_END (SAMPLES_WINDOW_SIZE - 1)
#define SAMPLES_WINDOW_MID (SAMPLES_WINDOW_SIZE / 2) // 1 in array on size of 3
/*
* @brief Returns the maximum of two arguments.
*/
#define MAX(x, y) ((x > y) ? (x) : (y))
/*
* @brief Returns the minimum of two arguments.
*/
#define MIN(x, y) ((x < y) ? (x) : (y))
/*
* @brief
*/
#define MEDIAN_OF_THREE(x, y, z) ( MAX( MIN( MAX( x, y), z), MIN(x, y)) )
HeightMeasurementService::HeightMeasurementService(int receive_chid, int send_chid, CalibrationData *calibrationDataPtr)
: stateMachine(new HeightContext(send_chid, this))
, calibrationDataPtr(calibrationDataPtr)
, receive_chid(receive_chid)
{
// Set this to true, so the statemachine thread will run his superloop.
statemachineIsRunning = true;
// Creates the thread for the statemachine with the receive channel to listen on it.
stateMachineThread = std::thread(&HeightMeasurementService::stateMachineTask, this, receive_chid);
}
HeightMeasurementService::~HeightMeasurementService() {
delete stateMachine;
}
void HeightMeasurementService::startMeasuring() {
// Set this true, so the measurement thread will run his suoperloop.
measurementIsRunning = true;
// Creates the thread for the measurement with the receive channel to send on it.
measurementThread = std::thread(&HeightMeasurementService::measuringTask, this, receive_chid);
}
void HeightMeasurementService::stopMeasuring() {
measurementIsRunning = false;
}
void HeightMeasurementService::measuringTask(int receive_chid) {
LOG_SCOPE;
LOG_SET_LEVEL(DEBUG);
LOG_DEBUG << "[HeightMeasurementService] measuringTask() Thread started\n";
int16_t data = 0; /*< The current measured data.*/
Signal state = START; /*< The current state of the statemachine.*/
Signal oldState = state; /*< The old state of the statemachine.*/
HeightMeasurementHal hal; /*< The hal object to access the HW.*/
int err = 0; /*< Return value of msgSend.*/
// Connect to the receive channel for sending pulse-messages on it.
int coid = ConnectAttach_r(ND_LOCAL_NODE, 0, receive_chid, 0, 0);
// Do error handling, if there is no channel available.
if (coid < 0) {
// TODO: Error handling.
LOG_DEBUG << "[HeightMeasurementService] measuringTask() ConnectAttach_r failed\n";
}
/* Check if the current measured data is in a valid range of the
* corresponding calibrated data. If it is so, send a signal to the receive-
* channel, where the statemachine is listening and will do the next
* transition.
*/
int counters[AMOUNT_OF_SIGNALS] = {0};
int window[SAMPLES_WINDOW_SIZE]
while (measurementIsRunning) {
for (int i = 0; i < AMOUNT_OF_SAMPLES; i++) {
hal.read(data);
// Shift the data to the left by one.
memmove(window, window + 1, sizeof(window) - sizeof(*window));
/* Put the new data at the end of the window.
*
* +----+----+----+ ... +----+
* OUT << | 0 | 1 | 2 | ... | N | << IN
* +----+----+----+ ... +----+
*/
window[SAMPLES_WINDOW_END] = data;
/* Calculate the median of three from the window.
* example:
* MAX( MIN ( MAX (3, 5), 4), MIN(3, 5))
* MAX( MIN (5 , 4), 3)
* MAX( 4, 3)
* 4 <- median
*/
int median = MEDIAN_OF_THREE(window[0], window[1], window[2]);
dataInRange(&state, median);
counters[state]++;
}
// TODO: get highest state?
/*
int inRow = 0;
int heighestCount = 0;
int heighestCountIndex = 0;
Signal newSample = state;
Signal oldSample = START;
for (int i = 0; i < 64; i++) {
hal.read(data);
dataInRange(&newSample, data);
if (oldSample != START && newSample == oldSample) {
inRow++;
if (inRow >= 8) {
counters[newSample]++;
if (counters[newSample] > heighestCount) {
heighestCount = counters[newSample];
heighestCountIndex = newSample;
}
inRow = 0;
}
}
else {
inRow = 0;
}
oldSample = newSample;
}
state = Signal(heighestCountIndex);
*/
/*
int currentCount = 0;
Signal tmpState = state;
for (int i = 0; i < AMOUNT_OF_SAMPLES; i++) {
hal.read(data);
dataInRange(&tmpState, data);
if(tmpState != oldState) {
if (++counters[tmpState] > currentCount) {
currentCount = counters[tmpState];
state = tmpState;
}
}
//std::this_thread::sleep_for(std::chrono::microseconds(50));
}
*/
// But send only a message if there is a new state.
if (state != oldState) {
err = MsgSendPulse_r(coid, sched_get_priority_min(0), 0, state);
if (err < 0) {
// TODO Error handling.
LOG_DEBUG << "[HeightMeasurementService] measuringTask() MsgSendPulse_r failed.\n";
}
LOG_DEBUG << "[HeightMeasurementService] send measuring signal: " << state << "\n";
}
// Remember the current state as old state for the next loop.
oldState = state;
// Reset the counters
std::fill(counters, counters + AMOUNT_OF_SIGNALS, 0);
std::fill(samples, samples + SAMPLES_AMOUNT, 0);
}
LOG_DEBUG << "[HeightMeasurementService] measuringTask() Leaves superloop\n";
}
void HeightMeasurementService::dataInRange(Signal *state, int16_t data) {
if (RANGE(data, REF_HEIGHT_VAL)) {
*state = REF_HEIGHT;
}
else if (RANGE(data, HOLE_HEIGHT_VAL)) {
*state = HOLE_HEIGHT;
}
else if (RANGE(data, SURFACE_HEIGHT_VAL)) {
*state = SURFACE_HEIGHT;
}
else if (RANGE(data, LOW_HEIGHT_VAL)) {
*state = LOW_HEIGHT;
}
else if (RANGE(data, HIGH_HEIGHT_VAL)) {
*state = HIGH_HEIGHT;
}
else if (RANGE(data, INVALID_HEIGHT_VAL)){
*state = INVALID;
}
}
void HeightMeasurementService::stateMachineTask(int receive_chid) {
LOG_SCOPE;
LOG_SET_LEVEL(DEBUG);
LOG_DEBUG << "[HeightMeasurementService] stateMachineTask() Thread started\n";
struct _pulse pulse; /*< Structure that describes a pulse.*/
// Wait for a new incoming pulse-message to do the next transition.
while (statemachineIsRunning) {
// Returns 0 on success and a negative value on error.
int err = MsgReceivePulse_r(receive_chid, &pulse, sizeof(_pulse), NULL);
// Do error handling, if there occurs an error.
if (err < 0) {
// TODO: Error handling.
// EFAULT, EINTR, ESRCH, ETIMEDOUT -> see qnx-manual.
LOG_DEBUG << "[HeightMeasurementService] stateMachineTask() Error on MsgReceivePulse_r\n";
}
LOG_DEBUG << "[HeightMeasurementService] stateMachineTask() Received pulse: " << pulse.value.sival_int << "\n";
// Signalize the statemachine for the next transition.
stateMachine->process((Signal) pulse.value.sival_int);
}
LOG_DEBUG << "[HeightMeasurementService] stateMachineTask() Leaves superloop\n";
}
/** @} */
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2016 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 <ospray/ospray_cpp/Device.h>
#include "common/commandline/Utility.h"
#include "common/sg/SceneGraph.h"
#include "common/sg/Renderer.h"
#include "common/sg/importer/Importer.h"
#include "ospcommon/FileName.h"
#include "sg/geometry/TriangleMesh.h"
#include "widgets/imguiViewer.h"
#include <sstream>
using namespace ospray;
ospcommon::vec3f translate;
ospcommon::vec3f scale;
bool lockFirstFrame = false;
std::vector<std::string> files;
bool showGui = false;
void parseExtraParametersFromComandLine(int ac, const char **&av)
{
for (int i = 1; i < ac; i++) {
const std::string arg = av[i];
if (arg == "--translate") {
translate.x = atof(av[++i]);
translate.y = atof(av[++i]);
translate.z = atof(av[++i]);
} else if (arg == "--scale") {
scale.x = atof(av[++i]);
scale.y = atof(av[++i]);
scale.z = atof(av[++i]);
} else if (arg == "--lockFirstFrame") {
lockFirstFrame = true;
} else if (arg == "--nogui") {
showGui = false;
}
else //look for valid models
{
ospcommon::FileName fileName = std::string(av[i]);
if (fileName.ext() == "obj" ||
fileName.ext() == "osg" ||
fileName.ext() == "ply"
)
{
files.push_back(av[i]);
}
}
}
}
int main(int ac, const char **av)
{
ospInit(&ac,av);
ospray::imgui3D::init(&ac,av);
auto ospObjs = parseWithDefaultParsers(ac, av);
std::deque<ospcommon::box3f> bbox;
std::deque<ospray::cpp::Model> model;
ospray::cpp::Renderer renderer;
ospray::cpp::Camera camera;
std::tie(bbox, model, renderer, camera) = ospObjs;
parseExtraParametersFromComandLine(ac, av);
ospray::imgui3D::ImGui3DWidget::showGui = showGui;
sg::RenderContext ctx;
sg::NodeH root = sg::createNode("ospray");
std::cout << root->getName() << std::endl;
sg::NodeH rendererN = sg::createNode("renderer", "Renderer");
root->add(rendererN);
sg::NodeH sun = sg::createNode("sun", "DirectionalLight");
root["renderer"]["lights"] += sun;
root["renderer"]["lights"]["sun"]["color"]->setValue(ospcommon::vec3f(1.f,232.f/255.f,166.f/255.f));
root["renderer"]["lights"]["sun"]["direction"]->setValue(ospcommon::vec3f(0.462f,-1.f,-.1f));
root["renderer"]["lights"]["sun"]["intensity"]->setValue(1.5f);
root["renderer"]["lights"] += sg::createNode("bounce", "DirectionalLight");
root["renderer"]["lights"]["bounce"]["color"]->setValue(ospcommon::vec3f(127.f/255.f,178.f/255.f,255.f/255.f));
root["renderer"]["lights"]["bounce"]["direction"]->setValue(ospcommon::vec3f(-.93,-.54f,-.605f));
root["renderer"]["lights"]["bounce"]["intensity"]->setValue(0.25f);
root["renderer"]["lights"] += sg::createNode("ambient", "AmbientLight");
root["renderer"]["lights"]["ambient"]["intensity"]->setValue(0.9f);
root["renderer"]["lights"]["ambient"]["color"]->setValue(ospcommon::vec3f(174.f/255.f,218.f/255.f,255.f/255.f));
root["renderer"]["shadowsEnabled"]->setValue(true);
root["renderer"]["aoSamples"]->setValue(1);
root["renderer"]["camera"]["fovy"]->setValue(60.f);
std::shared_ptr<sg::World> world = std::static_pointer_cast<sg::World>(root["renderer"]["world"].get());
for (auto file : files)
{
ospcommon::FileName fn = file;
if (fn.ext() == "obj")
{
// sg::importOBJ(world, file);
root["renderer"]["world"] += sg::createNode(fn.name(), "Importer");
root["renderer"]["world"][fn.name()]["fileName"]->setValue(fn.str());
}
if (fn.ext() == "osg")
{
// root["renderer"]["world"] += createNode(file, "TriangleMesh");
// root["renderer"]["world"][file]["fileName"]->setValue(file.str());
// sg::NodeH osgH;
// std::shared_ptr<sg::World> osg = sg::loadOSG(file);
// osg->setName("world");
// root["renderer"]["world"] = sg::NodeH(osg);
root["renderer"]["world"] += sg::createNode(fn.name(), "VolumeImporter");
root["renderer"]["world"][fn.name()]["fileName"]->setValue(fn.str());
}
if (fn.ext() == "ply")
{
root["renderer"]["world"] += sg::createNode(fn.name(), "Importer");
root["renderer"]["world"][fn.name()]["fileName"]->setValue(fn.str());
// sg::NodeH osgH;
// sg::NodeH osg(root["renderer"]["world"]);
// std::shared_ptr<sg::World> wsg(std::dynamic_pointer_cast<sg::World>(osg.get()));
// sg::importPLY(wsg, file);
// osg->setName("world");
// osg->setType("world");
// root["renderer"]["world"] = sg::NodeH(osg.get());
}
}
bbox.push_back(std::static_pointer_cast<sg::World>(root["renderer"]["world"].get())->getBounds());
//add plane
osp::vec3f *vertices = new osp::vec3f[4];
float ps = bbox[0].upper.x*5.f;
float py = bbox[0].lower.z-0.01f;
// vertices[0] = osp::vec3f{-ps, -ps, py};
// vertices[1] = osp::vec3f{-ps, ps, py};
// vertices[2] = osp::vec3f{ ps, -ps, py};
// vertices[3] = osp::vec3f{ ps, ps, py};
py = bbox[0].lower.y-0.01f;
vertices[0] = osp::vec3f{-ps, py, -ps};
vertices[1] = osp::vec3f{-ps, py, ps};
vertices[2] = osp::vec3f{ps, py, -ps};
vertices[3] = osp::vec3f{ps, py, ps};
auto position = std::shared_ptr<sg::DataBuffer>(new sg::DataArray3f((ospcommon::vec3f*)&vertices[0],size_t(4),false));
osp::vec3i *triangles = new osp::vec3i[2];
triangles[0] = osp::vec3i{0,1,2};
triangles[1] = osp::vec3i{1,2,3};
auto index = std::shared_ptr<sg::DataBuffer>(new sg::DataArray3i((ospcommon::vec3i*)&triangles[0],size_t(2),false));
root["renderer"]["world"] += sg::createNode("plane", "InstanceGroup");
root["renderer"]["world"]["plane"] += sg::createNode("mesh", "TriangleMesh");
std::shared_ptr<sg::TriangleMesh> plane =
std::static_pointer_cast<sg::TriangleMesh>(root["renderer"]["world"]["plane"]["mesh"].get());
plane->vertex = position;
plane->index = index;
root["renderer"]["world"]["plane"]["mesh"]["material"]["Kd"]->setValue(ospcommon::vec3f(0.8f));
root["renderer"]["world"]["plane"]["mesh"]["material"]["Ks"]->setValue(ospcommon::vec3f(0.6f));
root["renderer"]["world"]["plane"]["mesh"]["material"]["Ns"]->setValue(2.f);
for(int i=1;i < ac; i++)
{
std::string arg(av[i]);
size_t f;
std::string value("");
std::cout << "parsing cl arg: \"" << arg <<"\"" << std::endl;
while ( (f = arg.find(":")) != std::string::npos || (f = arg.find(",")) != std::string::npos)
arg[f]=' ';
f = arg.find("=");
if (f != std::string::npos)
{
value = arg.substr(f+1,arg.size());
std::cout << "found value: " << value << std::endl;
}
if (value != "")
{
std::stringstream ss;
ss << arg.substr(0,f);
std::string child;
sg::NodeH node = root;
while (ss >> child)
{
std::cout << "searching for node: " << child << std::endl;
node = node->getChildRecursive(child);
std::cout << "found node: " << node->getName() << std::endl;
}
try
{
node->getValue<std::string>();
node->setValue(value);
} catch(...) {};
try
{
std::stringstream vals(value);
float x;
vals >> x;
node->getValue<float>();
node->setValue(x);
} catch(...) {}
try
{
std::stringstream vals(value);
int x;
vals >> x;
node->getValue<int>();
node->setValue(x);
} catch(...) {}
try
{
std::stringstream vals(value);
bool x;
vals >> x;
node->getValue<bool>();
node->setValue(x);
} catch(...) {}
try
{
std::stringstream vals(value);
float x,y,z;
vals >> x >> y >> z;
node->getValue<ospcommon::vec3f>();
node->setValue(ospcommon::vec3f(x,y,z));
} catch(...) {}
try
{
std::stringstream vals(value);
int x,y,z;
vals >> x >> y;
node->getValue<ospcommon::vec2i>();
node->setValue(ospcommon::vec2i(x,y));
} catch(...) {}
}
}
root->traverse(ctx, "verify");
root->traverse(ctx,"print");
rendererN->traverse(ctx, "commit");
rendererN->traverse(ctx, "render");
ospray::ImGuiViewer window(bbox, model, renderer, camera, root["renderer"]);
window.setScale(scale);
window.setLockFirstAnimationFrame(lockFirstFrame);
window.setTranslation(translate);
window.create("ospImGui: OSPRay ImGui Viewer App");
ospray::imgui3D::run();
}
<commit_msg>Windows doesn't seem to load/find the ospray_sg symbols?<commit_after>// ======================================================================== //
// Copyright 2009-2016 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 <ospray/ospray_cpp/Device.h>
#include "common/commandline/Utility.h"
#include "common/sg/SceneGraph.h"
#include "common/sg/Renderer.h"
#include "common/sg/importer/Importer.h"
#include "ospcommon/FileName.h"
#include "sg/geometry/TriangleMesh.h"
#include "widgets/imguiViewer.h"
#include <sstream>
using namespace ospray;
ospcommon::vec3f translate;
ospcommon::vec3f scale;
bool lockFirstFrame = false;
std::vector<std::string> files;
bool showGui = false;
void parseExtraParametersFromComandLine(int ac, const char **&av)
{
for (int i = 1; i < ac; i++) {
const std::string arg = av[i];
if (arg == "--translate") {
translate.x = atof(av[++i]);
translate.y = atof(av[++i]);
translate.z = atof(av[++i]);
} else if (arg == "--scale") {
scale.x = atof(av[++i]);
scale.y = atof(av[++i]);
scale.z = atof(av[++i]);
} else if (arg == "--lockFirstFrame") {
lockFirstFrame = true;
} else if (arg == "--nogui") {
showGui = false;
}
else //look for valid models
{
ospcommon::FileName fileName = std::string(av[i]);
if (fileName.ext() == "obj" ||
fileName.ext() == "osg" ||
fileName.ext() == "ply"
)
{
files.push_back(av[i]);
}
}
}
}
int main(int ac, const char **av)
{
ospInit(&ac,av);
#ifdef _WIN32
// TODO: Why do we not have the sg symbols already available for us
// since we link against it?
loadLibrary("ospray_sg");
#endif
ospray::imgui3D::init(&ac,av);
auto ospObjs = parseWithDefaultParsers(ac, av);
std::deque<ospcommon::box3f> bbox;
std::deque<ospray::cpp::Model> model;
ospray::cpp::Renderer renderer;
ospray::cpp::Camera camera;
std::tie(bbox, model, renderer, camera) = ospObjs;
parseExtraParametersFromComandLine(ac, av);
ospray::imgui3D::ImGui3DWidget::showGui = showGui;
sg::RenderContext ctx;
sg::NodeH root = sg::createNode("ospray");
std::cout << root->getName() << std::endl;
sg::NodeH rendererN = sg::createNode("renderer", "Renderer");
root->add(rendererN);
sg::NodeH sun = sg::createNode("sun", "DirectionalLight");
root["renderer"]["lights"] += sun;
root["renderer"]["lights"]["sun"]["color"]->setValue(ospcommon::vec3f(1.f,232.f/255.f,166.f/255.f));
root["renderer"]["lights"]["sun"]["direction"]->setValue(ospcommon::vec3f(0.462f,-1.f,-.1f));
root["renderer"]["lights"]["sun"]["intensity"]->setValue(1.5f);
root["renderer"]["lights"] += sg::createNode("bounce", "DirectionalLight");
root["renderer"]["lights"]["bounce"]["color"]->setValue(ospcommon::vec3f(127.f/255.f,178.f/255.f,255.f/255.f));
root["renderer"]["lights"]["bounce"]["direction"]->setValue(ospcommon::vec3f(-.93,-.54f,-.605f));
root["renderer"]["lights"]["bounce"]["intensity"]->setValue(0.25f);
root["renderer"]["lights"] += sg::createNode("ambient", "AmbientLight");
root["renderer"]["lights"]["ambient"]["intensity"]->setValue(0.9f);
root["renderer"]["lights"]["ambient"]["color"]->setValue(ospcommon::vec3f(174.f/255.f,218.f/255.f,255.f/255.f));
root["renderer"]["shadowsEnabled"]->setValue(true);
root["renderer"]["aoSamples"]->setValue(1);
root["renderer"]["camera"]["fovy"]->setValue(60.f);
std::shared_ptr<sg::World> world = std::static_pointer_cast<sg::World>(root["renderer"]["world"].get());
for (auto file : files)
{
ospcommon::FileName fn = file;
if (fn.ext() == "obj")
{
// sg::importOBJ(world, file);
root["renderer"]["world"] += sg::createNode(fn.name(), "Importer");
root["renderer"]["world"][fn.name()]["fileName"]->setValue(fn.str());
}
if (fn.ext() == "osg")
{
// root["renderer"]["world"] += createNode(file, "TriangleMesh");
// root["renderer"]["world"][file]["fileName"]->setValue(file.str());
// sg::NodeH osgH;
// std::shared_ptr<sg::World> osg = sg::loadOSG(file);
// osg->setName("world");
// root["renderer"]["world"] = sg::NodeH(osg);
root["renderer"]["world"] += sg::createNode(fn.name(), "VolumeImporter");
root["renderer"]["world"][fn.name()]["fileName"]->setValue(fn.str());
}
if (fn.ext() == "ply")
{
root["renderer"]["world"] += sg::createNode(fn.name(), "Importer");
root["renderer"]["world"][fn.name()]["fileName"]->setValue(fn.str());
// sg::NodeH osgH;
// sg::NodeH osg(root["renderer"]["world"]);
// std::shared_ptr<sg::World> wsg(std::dynamic_pointer_cast<sg::World>(osg.get()));
// sg::importPLY(wsg, file);
// osg->setName("world");
// osg->setType("world");
// root["renderer"]["world"] = sg::NodeH(osg.get());
}
}
bbox.push_back(std::static_pointer_cast<sg::World>(root["renderer"]["world"].get())->getBounds());
//add plane
osp::vec3f *vertices = new osp::vec3f[4];
float ps = bbox[0].upper.x*5.f;
float py = bbox[0].lower.z-0.01f;
// vertices[0] = osp::vec3f{-ps, -ps, py};
// vertices[1] = osp::vec3f{-ps, ps, py};
// vertices[2] = osp::vec3f{ ps, -ps, py};
// vertices[3] = osp::vec3f{ ps, ps, py};
py = bbox[0].lower.y-0.01f;
vertices[0] = osp::vec3f{-ps, py, -ps};
vertices[1] = osp::vec3f{-ps, py, ps};
vertices[2] = osp::vec3f{ps, py, -ps};
vertices[3] = osp::vec3f{ps, py, ps};
auto position = std::shared_ptr<sg::DataBuffer>(new sg::DataArray3f((ospcommon::vec3f*)&vertices[0],size_t(4),false));
osp::vec3i *triangles = new osp::vec3i[2];
triangles[0] = osp::vec3i{0,1,2};
triangles[1] = osp::vec3i{1,2,3};
auto index = std::shared_ptr<sg::DataBuffer>(new sg::DataArray3i((ospcommon::vec3i*)&triangles[0],size_t(2),false));
root["renderer"]["world"] += sg::createNode("plane", "InstanceGroup");
root["renderer"]["world"]["plane"] += sg::createNode("mesh", "TriangleMesh");
std::shared_ptr<sg::TriangleMesh> plane =
std::static_pointer_cast<sg::TriangleMesh>(root["renderer"]["world"]["plane"]["mesh"].get());
plane->vertex = position;
plane->index = index;
root["renderer"]["world"]["plane"]["mesh"]["material"]["Kd"]->setValue(ospcommon::vec3f(0.8f));
root["renderer"]["world"]["plane"]["mesh"]["material"]["Ks"]->setValue(ospcommon::vec3f(0.6f));
root["renderer"]["world"]["plane"]["mesh"]["material"]["Ns"]->setValue(2.f);
for(int i=1;i < ac; i++)
{
std::string arg(av[i]);
size_t f;
std::string value("");
std::cout << "parsing cl arg: \"" << arg <<"\"" << std::endl;
while ( (f = arg.find(":")) != std::string::npos || (f = arg.find(",")) != std::string::npos)
arg[f]=' ';
f = arg.find("=");
if (f != std::string::npos)
{
value = arg.substr(f+1,arg.size());
std::cout << "found value: " << value << std::endl;
}
if (value != "")
{
std::stringstream ss;
ss << arg.substr(0,f);
std::string child;
sg::NodeH node = root;
while (ss >> child)
{
std::cout << "searching for node: " << child << std::endl;
node = node->getChildRecursive(child);
std::cout << "found node: " << node->getName() << std::endl;
}
try
{
node->getValue<std::string>();
node->setValue(value);
} catch(...) {};
try
{
std::stringstream vals(value);
float x;
vals >> x;
node->getValue<float>();
node->setValue(x);
} catch(...) {}
try
{
std::stringstream vals(value);
int x;
vals >> x;
node->getValue<int>();
node->setValue(x);
} catch(...) {}
try
{
std::stringstream vals(value);
bool x;
vals >> x;
node->getValue<bool>();
node->setValue(x);
} catch(...) {}
try
{
std::stringstream vals(value);
float x,y,z;
vals >> x >> y >> z;
node->getValue<ospcommon::vec3f>();
node->setValue(ospcommon::vec3f(x,y,z));
} catch(...) {}
try
{
std::stringstream vals(value);
int x,y,z;
vals >> x >> y;
node->getValue<ospcommon::vec2i>();
node->setValue(ospcommon::vec2i(x,y));
} catch(...) {}
}
}
root->traverse(ctx, "verify");
root->traverse(ctx,"print");
rendererN->traverse(ctx, "commit");
rendererN->traverse(ctx, "render");
ospray::ImGuiViewer window(bbox, model, renderer, camera, root["renderer"]);
window.setScale(scale);
window.setLockFirstAnimationFrame(lockFirstFrame);
window.setTranslation(translate);
window.create("ospImGui: OSPRay ImGui Viewer App");
ospray::imgui3D::run();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "bin/vmstats_impl.h"
#include <sstream>
#include "bin/fdutils.h"
#include "bin/file.h"
#include "bin/log.h"
#include "bin/platform.h"
#include "bin/socket.h"
#include "bin/thread.h"
#include "bin/utils.h"
#include "include/dart_debugger_api.h"
#include "platform/json.h"
#define BUFSIZE 8192
#define RETRY_PAUSE 100 // milliseconds
static const char* INDEX_HTML = "index.html";
static const char* VMSTATS_HTML = "vmstats.html";
static const char* DEFAULT_HOST = "localhost";
// Global static pointer used to ensure a single instance of the class.
VmStats* VmStats::instance_ = NULL;
dart::Monitor VmStats::instance_monitor_;
dart::Mutex VmStatusService::mutex_;
void VmStats::Start(int port, const char* root_dir) {
if (instance_ != NULL) {
FATAL("VmStats already started.");
}
MonitorLocker ml(&instance_monitor_);
instance_ = new VmStats();
VmStatusService::InitOnce();
Socket::Initialize();
if (root_dir != NULL) {
instance_->root_directory_ = root_dir;
}
// TODO(tball): allow host to be specified.
char* host = const_cast<char*>(DEFAULT_HOST);
OSError* os_error;
const char* host_ip = Socket::LookupIPv4Address(host, &os_error);
if (host_ip == NULL) {
Log::PrintErr("Failed IP lookup of VmStats host %s: %s\n",
host, os_error->message());
return;
}
const intptr_t BACKLOG = 128; // Default value from HttpServer.dart
int64_t address = ServerSocket::CreateBindListen(host_ip, port, BACKLOG);
if (address < 0) {
Log::PrintErr("Failed binding VmStats socket: %s:%d\n", host, port);
return;
}
instance_->bind_address_ = address;
Log::Print(
#if defined(TARGET_ARCH_X64)
"VmStats URL: http://%s:%ld/\n",
#else
"VmStats URL: http://%s:%d/\n",
#endif
host,
Socket::GetPort(address));
instance_->running_ = true;
int errno = dart::Thread::Start(WebServer, address);
if (errno != 0) {
Log::PrintErr("Failed starting VmStats thread: %d\n", errno);
Shutdown();
}
}
void VmStats::Stop() {
MonitorLocker ml(&instance_monitor_);
if (instance_ != NULL) {
instance_->running_ = false;
}
}
void VmStats::Shutdown() {
MonitorLocker ml(&instance_monitor_);
Socket::Close(instance_->bind_address_);
delete instance_;
instance_ = NULL;
}
void VmStats::AddIsolate(IsolateData* isolate_data,
Dart_Isolate isolate) {
MonitorLocker ml(&instance_monitor_);
if (instance_ != NULL) {
instance_->isolate_table_[isolate_data] = isolate;
}
}
void VmStats::RemoveIsolate(IsolateData* isolate_data) {
MonitorLocker ml(&instance_monitor_);
if (instance_ != NULL) {
instance_->isolate_table_.erase(isolate_data);
}
}
static const char* ContentType(const char* url) {
const char* suffix = strrchr(url, '.');
if (suffix != NULL) {
if (!strcmp(suffix, ".html")) {
return "text/html; charset=UTF-8";
}
if (!strcmp(suffix, ".dart")) {
return "application/dart; charset=UTF-8";
}
if (!strcmp(suffix, ".js")) {
return "application/javascript; charset=UTF-8";
}
if (!strcmp(suffix, ".css")) {
return "text/css; charset=UTF-8";
}
if (!strcmp(suffix, ".gif")) {
return "image/gif";
}
if (!strcmp(suffix, ".png")) {
return "image/png";
}
if (!strcmp(suffix, ".jpg") || !strcmp(suffix, ".jpeg")) {
return "image/jpeg";
}
}
return "text/plain";
}
void VmStats::WebServer(uword bind_address) {
while (true) {
intptr_t socket = ServerSocket::Accept(bind_address);
if (socket == ServerSocket::kTemporaryFailure) {
// Not a real failure, woke up but no connection available.
// Use MonitorLocker.Wait(), since it has finer granularity than sleep().
dart::Monitor m;
MonitorLocker ml(&m);
ml.Wait(RETRY_PAUSE);
continue;
}
if (socket < 0) {
// Stop() closed the socket.
return;
}
FDUtils::SetBlocking(socket);
// TODO(tball): rewrite this to use STL, so as to eliminate the static
// buffer and support resource URLs that are longer than BUFSIZE.
// Read request.
// TODO(tball): support partial reads, possibly needed for POST uploads.
char buffer[BUFSIZE + 1];
int len = read(socket, buffer, BUFSIZE);
if (len <= 0) {
// Invalid HTTP request, ignore.
continue;
}
buffer[len] = '\0';
// Verify it's a GET request.
// TODO(tball): support POST requests.
if (strncmp("GET ", buffer, 4) != 0 && strncmp("get ", buffer, 4) != 0) {
Log::PrintErr("Unsupported HTTP request type");
const char* response = "HTTP/1.1 403 Forbidden\n"
"Content-Length: 120\n"
"Connection: close\n"
"Content-Type: text/html\n\n"
"<html><head>\n<title>403 Forbidden</title>\n</head>"
"<body>\n<h1>Forbidden</h1>\nUnsupported HTTP request type\n</body>"
"</html>\n";
Socket::Write(socket, response, strlen(response));
Socket::Close(socket);
continue;
}
// Extract GET URL, and null-terminate URL in case request line has
// HTTP version.
for (int i = 4; i < len; i++) {
if (buffer[i] == ' ') {
buffer[i] = '\0';
}
}
char* url = &buffer[4];
Log::Print("vmstats: %s requested\n", url);
char* content = NULL;
// Check for VmStats-specific URLs.
if (strcmp(url, "/isolates") == 0) {
content = instance_->IsolatesStatus();
} else {
// Check plug-ins.
content = VmStatusService::GetVmStatus(url);
}
if (content != NULL) {
size_t content_len = strlen(content);
len = snprintf(buffer, BUFSIZE,
#if defined(TARGET_ARCH_X64)
"HTTP/1.1 200 OK\nContent-Type: application/json; charset=UTF-8\n"
"Content-Length: %lx\n\n",
#else
"HTTP/1.1 200 OK\nContent-Type: application/json; charset=UTF-8\n"
"Content-Length: %d\n\n",
#endif
content_len);
Socket::Write(socket, buffer, strlen(buffer));
Socket::Write(socket, content, content_len);
Socket::Write(socket, "\n", 1);
Socket::Write(socket, buffer, strlen(buffer));
free(content);
} else {
// No status content with this URL, return file or resource content.
std::string path(instance_->root_directory_);
path.append(url);
// Expand directory URLs.
if (strcmp(url, "/") == 0) {
path.append(VMSTATS_HTML);
} else if (url[strlen(url) - 1] == '/') {
path.append(INDEX_HTML);
}
bool success = false;
if (File::Exists(path.c_str())) {
File* f = File::Open(path.c_str(), File::kRead);
if (f != NULL) {
intptr_t len = f->Length();
char* text_buffer = reinterpret_cast<char*>(malloc(len));
if (f->ReadFully(text_buffer, len)) {
const char* content_type = ContentType(path.c_str());
snprintf(buffer, BUFSIZE,
#if defined(TARGET_ARCH_X64)
"HTTP/1.1 200 OK\nContent-Type: %s\n"
"Content-Length: %ld\n\n",
#else
"HTTP/1.1 200 OK\nContent-Type: %s\n"
"Content-Length: %d\n\n",
#endif
content_type, len);
Socket::Write(socket, buffer, strlen(buffer));
Socket::Write(socket, text_buffer, len);
Socket::Write(socket, "\n", 1);
success = true;
}
free(text_buffer);
delete f;
}
} else {
// TODO(tball): look up linked in resource.
}
if (!success) {
const char* response = "HTTP/1.1 404 Not Found\n\n";
Socket::Write(socket, response, strlen(response));
}
}
Socket::Close(socket);
}
Shutdown();
}
char* VmStats::IsolatesStatus() {
std::ostringstream stream;
stream << '{' << std::endl;
stream << "\"isolates\": [" << std::endl;
IsolateTable::iterator itr;
bool first = true;
for (itr = isolate_table_.begin(); itr != isolate_table_.end(); ++itr) {
Dart_Isolate isolate = itr->second;
static char request[512];
snprintf(request, sizeof(request),
#if defined(TARGET_ARCH_X64)
"/isolate/0x%lx",
#else
"/isolate/0x%llx",
#endif
reinterpret_cast<int64_t>(isolate));
char* status = VmStatusService::GetVmStatus(request);
if (status != NULL) {
stream << status;
if (!first) {
stream << "," << std::endl;
}
first = false;
}
free(status);
}
stream << std::endl << "]";
stream << std::endl << '}' << std::endl;
return strdup(stream.str().c_str());
}
// Global static pointer used to ensure a single instance of the class.
VmStatusService* VmStatusService::instance_ = NULL;
void VmStatusService::InitOnce() {
ASSERT(VmStatusService::instance_ == NULL);
VmStatusService::instance_ = new VmStatusService();
// Register built-in status plug-ins. RegisterPlugin is not used because
// this isn't called within an isolate, and because parameter checking
// isn't necessary.
instance_->RegisterPlugin(&Dart_GetVmStatus);
// TODO(tball): dynamically load any additional plug-ins.
}
int VmStatusService::RegisterPlugin(Dart_VmStatusCallback callback) {
MutexLocker ml(&mutex_);
if (callback == NULL) {
return -1;
}
VmStatusPlugin* plugin = new VmStatusPlugin(callback);
VmStatusPlugin* list = instance_->registered_plugin_list_;
if (list == NULL) {
instance_->registered_plugin_list_ = plugin;
} else {
list->Append(plugin);
}
return 0;
}
char* VmStatusService::GetVmStatus(const char* request) {
VmStatusPlugin* plugin = instance_->registered_plugin_list_;
while (plugin != NULL) {
char* result = (plugin->callback())(request);
if (result != NULL) {
return result;
}
plugin = plugin->next();
}
return NULL;
}
<commit_msg>- Fix string formatting. Review URL: https://codereview.chromium.org//12340088<commit_after>// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "bin/vmstats_impl.h"
#include <sstream>
#include "bin/fdutils.h"
#include "bin/file.h"
#include "bin/log.h"
#include "bin/platform.h"
#include "bin/socket.h"
#include "bin/thread.h"
#include "bin/utils.h"
#include "include/dart_debugger_api.h"
#include "platform/json.h"
#define BUFSIZE 8192
#define RETRY_PAUSE 100 // milliseconds
static const char* INDEX_HTML = "index.html";
static const char* VMSTATS_HTML = "vmstats.html";
static const char* DEFAULT_HOST = "localhost";
// Global static pointer used to ensure a single instance of the class.
VmStats* VmStats::instance_ = NULL;
dart::Monitor VmStats::instance_monitor_;
dart::Mutex VmStatusService::mutex_;
void VmStats::Start(int port, const char* root_dir) {
if (instance_ != NULL) {
FATAL("VmStats already started.");
}
MonitorLocker ml(&instance_monitor_);
instance_ = new VmStats();
VmStatusService::InitOnce();
Socket::Initialize();
if (root_dir != NULL) {
instance_->root_directory_ = root_dir;
}
// TODO(tball): allow host to be specified.
char* host = const_cast<char*>(DEFAULT_HOST);
OSError* os_error;
const char* host_ip = Socket::LookupIPv4Address(host, &os_error);
if (host_ip == NULL) {
Log::PrintErr("Failed IP lookup of VmStats host %s: %s\n",
host, os_error->message());
return;
}
const intptr_t BACKLOG = 128; // Default value from HttpServer.dart
int64_t address = ServerSocket::CreateBindListen(host_ip, port, BACKLOG);
if (address < 0) {
Log::PrintErr("Failed binding VmStats socket: %s:%d\n", host, port);
return;
}
instance_->bind_address_ = address;
Log::Print("VmStats URL: http://%s:%"Pd"/\n", host, Socket::GetPort(address));
instance_->running_ = true;
int err = dart::Thread::Start(WebServer, address);
if (err != 0) {
Log::PrintErr("Failed starting VmStats thread: %d\n", err);
Shutdown();
}
}
void VmStats::Stop() {
MonitorLocker ml(&instance_monitor_);
if (instance_ != NULL) {
instance_->running_ = false;
}
}
void VmStats::Shutdown() {
MonitorLocker ml(&instance_monitor_);
Socket::Close(instance_->bind_address_);
delete instance_;
instance_ = NULL;
}
void VmStats::AddIsolate(IsolateData* isolate_data,
Dart_Isolate isolate) {
MonitorLocker ml(&instance_monitor_);
if (instance_ != NULL) {
instance_->isolate_table_[isolate_data] = isolate;
}
}
void VmStats::RemoveIsolate(IsolateData* isolate_data) {
MonitorLocker ml(&instance_monitor_);
if (instance_ != NULL) {
instance_->isolate_table_.erase(isolate_data);
}
}
static const char* ContentType(const char* url) {
const char* suffix = strrchr(url, '.');
if (suffix != NULL) {
if (!strcmp(suffix, ".html")) {
return "text/html; charset=UTF-8";
}
if (!strcmp(suffix, ".dart")) {
return "application/dart; charset=UTF-8";
}
if (!strcmp(suffix, ".js")) {
return "application/javascript; charset=UTF-8";
}
if (!strcmp(suffix, ".css")) {
return "text/css; charset=UTF-8";
}
if (!strcmp(suffix, ".gif")) {
return "image/gif";
}
if (!strcmp(suffix, ".png")) {
return "image/png";
}
if (!strcmp(suffix, ".jpg") || !strcmp(suffix, ".jpeg")) {
return "image/jpeg";
}
}
return "text/plain";
}
void VmStats::WebServer(uword bind_address) {
while (true) {
intptr_t socket = ServerSocket::Accept(bind_address);
if (socket == ServerSocket::kTemporaryFailure) {
// Not a real failure, woke up but no connection available.
// Use MonitorLocker.Wait(), since it has finer granularity than sleep().
dart::Monitor m;
MonitorLocker ml(&m);
ml.Wait(RETRY_PAUSE);
continue;
}
if (socket < 0) {
// Stop() closed the socket.
return;
}
FDUtils::SetBlocking(socket);
// TODO(tball): rewrite this to use STL, so as to eliminate the static
// buffer and support resource URLs that are longer than BUFSIZE.
// Read request.
// TODO(tball): support partial reads, possibly needed for POST uploads.
char buffer[BUFSIZE + 1];
int len = read(socket, buffer, BUFSIZE);
if (len <= 0) {
// Invalid HTTP request, ignore.
continue;
}
buffer[len] = '\0';
// Verify it's a GET request.
// TODO(tball): support POST requests.
if (strncmp("GET ", buffer, 4) != 0 && strncmp("get ", buffer, 4) != 0) {
Log::PrintErr("Unsupported HTTP request type");
const char* response = "HTTP/1.1 403 Forbidden\n"
"Content-Length: 120\n"
"Connection: close\n"
"Content-Type: text/html\n\n"
"<html><head>\n<title>403 Forbidden</title>\n</head>"
"<body>\n<h1>Forbidden</h1>\nUnsupported HTTP request type\n</body>"
"</html>\n";
Socket::Write(socket, response, strlen(response));
Socket::Close(socket);
continue;
}
// Extract GET URL, and null-terminate URL in case request line has
// HTTP version.
for (int i = 4; i < len; i++) {
if (buffer[i] == ' ') {
buffer[i] = '\0';
}
}
char* url = &buffer[4];
Log::Print("vmstats: %s requested\n", url);
char* content = NULL;
// Check for VmStats-specific URLs.
if (strcmp(url, "/isolates") == 0) {
content = instance_->IsolatesStatus();
} else {
// Check plug-ins.
content = VmStatusService::GetVmStatus(url);
}
if (content != NULL) {
size_t content_len = strlen(content);
len = snprintf(buffer, BUFSIZE,
"HTTP/1.1 200 OK\nContent-Type: application/json; charset=UTF-8\n"
"Content-Length: %"Pu"\n\n",
content_len);
Socket::Write(socket, buffer, strlen(buffer));
Socket::Write(socket, content, content_len);
Socket::Write(socket, "\n", 1);
Socket::Write(socket, buffer, strlen(buffer));
free(content);
} else {
// No status content with this URL, return file or resource content.
std::string path(instance_->root_directory_);
path.append(url);
// Expand directory URLs.
if (strcmp(url, "/") == 0) {
path.append(VMSTATS_HTML);
} else if (url[strlen(url) - 1] == '/') {
path.append(INDEX_HTML);
}
bool success = false;
if (File::Exists(path.c_str())) {
File* f = File::Open(path.c_str(), File::kRead);
if (f != NULL) {
intptr_t len = f->Length();
char* text_buffer = reinterpret_cast<char*>(malloc(len));
if (f->ReadFully(text_buffer, len)) {
const char* content_type = ContentType(path.c_str());
snprintf(buffer, BUFSIZE,
"HTTP/1.1 200 OK\nContent-Type: %s\n"
"Content-Length: %"Pu"\n\n",
content_type, len);
Socket::Write(socket, buffer, strlen(buffer));
Socket::Write(socket, text_buffer, len);
Socket::Write(socket, "\n", 1);
success = true;
}
free(text_buffer);
delete f;
}
} else {
// TODO(tball): look up linked in resource.
}
if (!success) {
const char* response = "HTTP/1.1 404 Not Found\n\n";
Socket::Write(socket, response, strlen(response));
}
}
Socket::Close(socket);
}
Shutdown();
}
char* VmStats::IsolatesStatus() {
std::ostringstream stream;
stream << '{' << std::endl;
stream << "\"isolates\": [" << std::endl;
IsolateTable::iterator itr;
bool first = true;
for (itr = isolate_table_.begin(); itr != isolate_table_.end(); ++itr) {
Dart_Isolate isolate = itr->second;
static char request[512];
snprintf(request, sizeof(request),
"/isolate/0x%"Px,
reinterpret_cast<intptr_t>(isolate));
char* status = VmStatusService::GetVmStatus(request);
if (status != NULL) {
stream << status;
if (!first) {
stream << "," << std::endl;
}
first = false;
}
free(status);
}
stream << std::endl << "]";
stream << std::endl << '}' << std::endl;
return strdup(stream.str().c_str());
}
// Global static pointer used to ensure a single instance of the class.
VmStatusService* VmStatusService::instance_ = NULL;
void VmStatusService::InitOnce() {
ASSERT(VmStatusService::instance_ == NULL);
VmStatusService::instance_ = new VmStatusService();
// Register built-in status plug-ins. RegisterPlugin is not used because
// this isn't called within an isolate, and because parameter checking
// isn't necessary.
instance_->RegisterPlugin(&Dart_GetVmStatus);
// TODO(tball): dynamically load any additional plug-ins.
}
int VmStatusService::RegisterPlugin(Dart_VmStatusCallback callback) {
MutexLocker ml(&mutex_);
if (callback == NULL) {
return -1;
}
VmStatusPlugin* plugin = new VmStatusPlugin(callback);
VmStatusPlugin* list = instance_->registered_plugin_list_;
if (list == NULL) {
instance_->registered_plugin_list_ = plugin;
} else {
list->Append(plugin);
}
return 0;
}
char* VmStatusService::GetVmStatus(const char* request) {
VmStatusPlugin* plugin = instance_->registered_plugin_list_;
while (plugin != NULL) {
char* result = (plugin->callback())(request);
if (result != NULL) {
return result;
}
plugin = plugin->next();
}
return NULL;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <thread>
#include <mutex>
// Suppose we have a class:
struct A {
// That has a variable,
int m_count;
// that is accessed simulateously by two threads.
// Then we need to protect that variable using a mutex, say this one:
std::mutex m_count_mutex;
// Because, when we don't use locking, then things go wrong.
};
// For convenience, lets instantiate an object of type A globally,
// even though that is normally evil.
A a;
// Consider this thread that accesses m_count without locking!
void thr_no_lock()
{
// Loop 100000 times, each loop incrementing m_count by one.
for (int i = 0; i < 100000; ++i)
{
// Read m_count.
int read = a.m_count;
// Add 1 and write it back.
a.m_count = read + 1;
}
// If the reading and writing was atomic then
// this loop will have added precisely 100000.
}
// Also have a thread that does the same but with locking:
void thr_with_lock()
{
for (int i = 0; i < 100000; ++i)
{
std::unique_lock<std::mutex> lk(a.m_count_mutex);
int read = a.m_count;
a.m_count = read + 1;
}
}
int main()
{
// Do the test without locking first.
a.m_count = 0;
{
std::thread t1(thr_no_lock);
std::thread t2(thr_with_lock);
// Wait for t1 and t2 to be finished.
t1.join();
t2.join();
}
// This result will be LESS THAN 200000!
std::cout << "Afterwards the value of m_count, without locking, is: " << a.m_count << std::endl;
// And again, but now both threads use locking.
a.m_count = 0;
{
std::thread t1(thr_with_lock);
std::thread t2(thr_with_lock);
t1.join();
t2.join();
}
// This result will be precisely 200000!
std::cout << "Afterwards the value of m_count, with locking, is: " << a.m_count << std::endl;
// Can you understand why?
}
<commit_msg>Increase loop count.<commit_after>#include <iostream>
#include <thread>
#include <mutex>
// Suppose we have a class:
struct A {
// That has a variable,
int m_count;
// that is accessed simulateously by two threads.
// Then we need to protect that variable using a mutex, say this one:
std::mutex m_count_mutex;
// Because, when we don't use locking, then things go wrong.
};
// For convenience, lets instantiate an object of type A globally,
// even though that is normally evil.
A a;
// Consider this thread that accesses m_count without locking!
void thr_no_lock()
{
// Loop 100000 times, each loop incrementing m_count by one.
for (int i = 0; i < 1000000; ++i)
{
// Read m_count.
int read = a.m_count;
// Add 1 and write it back.
a.m_count = read + 1;
}
// If the reading and writing was atomic then
// this loop will have added precisely 100000.
}
// Also have a thread that does the same but with locking:
void thr_with_lock()
{
for (int i = 0; i < 1000000; ++i)
{
std::unique_lock<std::mutex> lk(a.m_count_mutex);
int read = a.m_count;
a.m_count = read + 1;
}
}
int main()
{
// Do the test without locking first.
a.m_count = 0;
{
std::thread t1(thr_no_lock);
std::thread t2(thr_with_lock);
// Wait for t1 and t2 to be finished.
t1.join();
t2.join();
}
// This result will be LESS THAN 200000!
std::cout << "Afterwards the value of m_count, without locking, is: " << a.m_count << std::endl;
// And again, but now both threads use locking.
a.m_count = 0;
{
std::thread t1(thr_with_lock);
std::thread t2(thr_with_lock);
t1.join();
t2.join();
}
// This result will be precisely 200000!
std::cout << "Afterwards the value of m_count, with locking, is: " << a.m_count << std::endl;
// Can you understand why?
}
<|endoftext|> |
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
/**
* Example 12: Physics Based Preconditioning
* This example shows how to enable the use of more advanced preconditioning
* with the optional Kernel::computeQpOffDiagJacobian method and input PBP block
*/
//Moose Includes
#include "MooseInit.h"
#include "Moose.h"
#include "MooseApp.h"
PerfLog Moose::perf_log("Example12: Physics Based Preconditioning");
int main (int argc, char** argv)
{
MooseInit init (argc, argv);
MooseApp app(argc, argv);
app.run();
return 0;
}
<commit_msg>Examples use ExampleApp now, not MooseApp!<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
/**
* Example 12: Physics Based Preconditioning
* This example shows how to enable the use of more advanced preconditioning
* with the optional Kernel::computeQpOffDiagJacobian method and input PBP block
*/
//Moose Includes
#include "MooseInit.h"
#include "Moose.h"
#include "ExampleApp.h"
PerfLog Moose::perf_log("Example12: Physics Based Preconditioning");
int main (int argc, char** argv)
{
MooseInit init (argc, argv);
ExampleApp app(argc, argv);
app.run();
return 0;
}
<|endoftext|> |
<commit_before>/***************************************************************************
*
* Project: libLAS -- C/C++ read/write library for LAS LIDAR data
* Purpose: LAS translation with optional configuration
* Author: Howard Butler, hobu.inc at gmail.com
***************************************************************************
* Copyright (c) 2010, Howard Butler, hobu.inc at gmail.com
*
* See LICENSE.txt in this source distribution for more information.
**************************************************************************/
#include <iostream>
#include <pdal/exceptions.hpp>
//#include <pdal/pdal_config.hpp>
//#include <pdal/Bounds.hpp>
//#include <pdal/Color.hpp>
//#include <pdal/Dimension.hpp>
//#include <pdal/Schema.hpp>
#include <pdal/filters/Chipper.hpp>
#include <pdal/filters/ReprojectionFilter.hpp>
#include <pdal/filters/ScalingFilter.hpp>
//#include <pdal/ColorFilter.hpp>
//#include <pdal/MosaicFilter.hpp>
//#include <pdal/FauxReader.hpp>
//#include <pdal/FauxWriter.hpp>
#include <pdal/drivers/las/Reader.hpp>
//#include <pdal/LasHeader.hpp>
#include <pdal/drivers/las/Writer.hpp>
#include <pdal/filters/CacheFilter.hpp>
#include <pdal/filters/ByteSwapFilter.hpp>
#include <pdal/drivers/liblas/Writer.hpp>
#include <pdal/drivers/liblas/Reader.hpp>
#ifdef PDAL_HAVE_ORACLE
#include <pdal/drivers/oci/Writer.hpp>
#include <pdal/drivers/oci/Reader.hpp>
#endif
#include <boost/property_tree/xml_parser.hpp>
#include "Application.hpp"
using namespace pdal;
namespace po = boost::program_options;
class Application_pc2pc : public Application
{
public:
Application_pc2pc(int argc, char* argv[]);
int execute();
private:
void addOptions();
bool validateOptions();
std::string m_inputFile;
std::string m_outputFile;
std::string m_xml;
std::string m_srs;
bool m_bCompress;
};
Application_pc2pc::Application_pc2pc(int argc, char* argv[])
: Application(argc, argv, "pc2pc")
{
}
bool Application_pc2pc::validateOptions()
{
if (!hasOption("input"))
{
usageError("--input/-i required");
return false;
}
if (!hasOption("output"))
{
usageError("--output/-o required");
return false;
}
return true;
}
void Application_pc2pc::addOptions()
{
po::options_description* file_options = new po::options_description("file options");
file_options->add_options()
("input,i", po::value<std::string>(&m_inputFile), "input file name")
("output,o", po::value<std::string>(&m_outputFile), "output file name")
("native", "use native LAS classes (not liblas)")
("oracle-writer", "Read data from LAS file and write to Oracle")
("oracle-reader", "Read data from Oracle and write to LAS")
("a_srs", po::value<std::string>(&m_srs)->default_value(""), "Assign output coordinate system")
("compress", po::value<bool>(&m_bCompress)->zero_tokens()->implicit_value(true),"Compress output data if available")
("xml", po::value<std::string>(&m_xml)->default_value("log.xml"), "XML file to load process (OCI only right now)")
;
addOptionSet(file_options);
}
int Application_pc2pc::execute()
{
if (!Utils::fileExists(m_inputFile))
{
runtimeError("file not found: " + m_inputFile);
return 1;
}
std::ostream* ofs = Utils::createFile(m_outputFile);
if (hasOption("native"))
{
pdal::drivers::las::LasReader reader(m_inputFile);
const boost::uint64_t numPoints = reader.getNumPoints();
pdal::drivers::las::LasWriter writer(reader, ofs);
//BUG: handle laz writer.setCompressed(false);
//writer.setPointFormat( reader.getPointFormatNumber() );
writer.initialize();
writer.write(numPoints);
}
else if (hasOption("oracle-writer"))
{
#ifdef PDAL_HAVE_ORACLE
try{
pdal::drivers::las::LasReader reader(m_inputFile);
reader.initialize();
const boost::uint64_t numPoints = reader.getNumPoints();
boost::property_tree::ptree load_tree;
boost::property_tree::read_xml(m_xml, load_tree);
boost::property_tree::ptree oracle_options = load_tree.get_child("pdal.drivers.oci.writer");
boost::property_tree::ptree las_options = load_tree.get_child("pdal.drivers.las");
pdal::OptionsOld options(oracle_options);
boost::property_tree::ptree in_srs_options = las_options.get_child("spatialreference");
std::string in_wkt = in_srs_options.get<std::string>("userinput");
boost::property_tree::ptree out_srs_options = oracle_options.get_child("spatialreference");
std::string out_wkt = out_srs_options.get<std::string>("userinput");
pdal::SpatialReference in_ref(in_wkt);
pdal::SpatialReference out_ref(out_wkt);
boost::property_tree::ptree& tree = options.GetPTree();
boost::uint32_t capacity = tree.get<boost::uint32_t>("capacity");
double scalex = oracle_options.get<double>("scale.x");
double scaley = oracle_options.get<double>("scale.y");
double scalez = oracle_options.get<double>("scale.z");
double offsetx = oracle_options.get<double>("offset.x");
double offsety = oracle_options.get<double>("offset.y");
double offsetz = oracle_options.get<double>("offset.z");
pdal::filters::CacheFilter cache(reader, 1, capacity);
pdal::filters::Chipper chipper(cache, capacity);
pdal::filters::ScalingFilter scalingFilter(chipper);
pdal::filters::ReprojectionFilter reprojectionFilter(scalingFilter, in_ref, out_ref);
pdal::filters::DescalingFilter descalingFilter(reprojectionFilter,
scalex, offsetx,
scaley, offsety,
scalez, offsetz);
// pdal::filters::ByteSwapFilter swapper(descalingFilter);
pdal::drivers::oci::Writer writer(descalingFilter, options);
writer.initialize();
writer.write(numPoints);
boost::property_tree::ptree output_tree;
// output_tree.put_child(writer.getName(), options.GetPTree());
// boost::property_tree::write_xml(m_xml, output_tree);
} catch (pdal::pdal_error& e)
{
std::cerr << "Error writing oracle: " << e.what() << std::endl;
}
#else
throw configuration_error("PDAL not compiled with Oracle support");
#endif
}
else if (hasOption("oracle-reader"))
{
#ifdef PDAL_HAVE_ORACLE
try{
boost::property_tree::ptree load_tree;
boost::property_tree::read_xml(m_xml, load_tree);
boost::property_tree::ptree oracle_options = load_tree.get_child("pdal.drivers.oci.reader");
boost::property_tree::ptree las_options = load_tree.get_child("pdal.drivers.las");
boost::property_tree::ptree srs_options = las_options.get_child("spatialreference");
double scalex = las_options.get<double>("scale.x");
double scaley = las_options.get<double>("scale.y");
double scalez = las_options.get<double>("scale.z");
double offsetx = las_options.get<double>("offset.x");
double offsety = las_options.get<double>("offset.y");
double offsetz = las_options.get<double>("offset.z");
bool compress = las_options.get<bool>("compress");
std::string out_wkt = srs_options.get<std::string>("userinput");
pdal::OptionsOld options(oracle_options);
pdal::drivers::oci::Reader reader(options);
reader.initialize();
pdal::drivers::las::LasWriter* writer;
pdal::SpatialReference out_ref(out_wkt);
pdal::SpatialReference in_ref(reader.getSpatialReference());
if (!(in_ref == out_ref))
{
// pdal::filters::ByteSwapFilter swapper(reader);
pdal::filters::ScalingFilter scalingFilter(reader);
pdal::filters::ReprojectionFilter reprojectionFilter(scalingFilter, in_ref, out_ref);
pdal::filters::DescalingFilter descalingFilter(reprojectionFilter,
scalex, offsetx,
scaley, offsety,
scalez, offsetz);
writer = new pdal::drivers::las::LasWriter(descalingFilter, ofs);
if (compress)
writer->setCompressed(true);
writer->setChunkSize(oracle_options.get<boost::uint32_t>("capacity"));
writer->setPointFormat(pdal::drivers::las::PointFormat3);
writer->initialize();
writer->write(0);
delete writer;
}
else
{
writer = new pdal::drivers::las::LasWriter(reader, ofs);
if (compress)
writer->setCompressed(true);
writer->setChunkSize(oracle_options.get<boost::uint32_t>("capacity"));
writer->setPointFormat(pdal::drivers::las::PointFormat3);
writer->initialize();
writer->write(0);
delete writer;
}
} catch (pdal::pdal_error& e)
{
std::cerr << "Error reading oracle: " << e.what() << std::endl;
return 1;
}
#else
throw configuration_error("PDAL not compiled with Oracle support");
#endif
}
else
{
pdal::drivers::liblas::LiblasReader reader(m_inputFile);
const boost::uint64_t numPoints = reader.getNumPoints();
pdal::drivers::liblas::LiblasWriter writer(reader, ofs);
//BUG: handle laz writer.setCompressed(false);
writer.setPointFormat( reader.getPointFormat() );
writer.initialize();
writer.write(numPoints);
}
Utils::closeFile(ofs);
return 0;
}
int main(int argc, char* argv[])
{
Application_pc2pc app(argc, argv);
return app.run();
}
<commit_msg>remove reader.initialize(), we shouldn't do that<commit_after>/***************************************************************************
*
* Project: libLAS -- C/C++ read/write library for LAS LIDAR data
* Purpose: LAS translation with optional configuration
* Author: Howard Butler, hobu.inc at gmail.com
***************************************************************************
* Copyright (c) 2010, Howard Butler, hobu.inc at gmail.com
*
* See LICENSE.txt in this source distribution for more information.
**************************************************************************/
#include <iostream>
#include <pdal/exceptions.hpp>
//#include <pdal/pdal_config.hpp>
//#include <pdal/Bounds.hpp>
//#include <pdal/Color.hpp>
//#include <pdal/Dimension.hpp>
//#include <pdal/Schema.hpp>
#include <pdal/filters/Chipper.hpp>
#include <pdal/filters/ReprojectionFilter.hpp>
#include <pdal/filters/ScalingFilter.hpp>
//#include <pdal/ColorFilter.hpp>
//#include <pdal/MosaicFilter.hpp>
//#include <pdal/FauxReader.hpp>
//#include <pdal/FauxWriter.hpp>
#include <pdal/drivers/las/Reader.hpp>
//#include <pdal/LasHeader.hpp>
#include <pdal/drivers/las/Writer.hpp>
#include <pdal/filters/CacheFilter.hpp>
#include <pdal/filters/ByteSwapFilter.hpp>
#include <pdal/drivers/liblas/Writer.hpp>
#include <pdal/drivers/liblas/Reader.hpp>
#ifdef PDAL_HAVE_ORACLE
#include <pdal/drivers/oci/Writer.hpp>
#include <pdal/drivers/oci/Reader.hpp>
#endif
#include <boost/property_tree/xml_parser.hpp>
#include "Application.hpp"
using namespace pdal;
namespace po = boost::program_options;
class Application_pc2pc : public Application
{
public:
Application_pc2pc(int argc, char* argv[]);
int execute();
private:
void addOptions();
bool validateOptions();
std::string m_inputFile;
std::string m_outputFile;
std::string m_xml;
std::string m_srs;
bool m_bCompress;
};
Application_pc2pc::Application_pc2pc(int argc, char* argv[])
: Application(argc, argv, "pc2pc")
{
}
bool Application_pc2pc::validateOptions()
{
if (!hasOption("input"))
{
usageError("--input/-i required");
return false;
}
if (!hasOption("output"))
{
usageError("--output/-o required");
return false;
}
return true;
}
void Application_pc2pc::addOptions()
{
po::options_description* file_options = new po::options_description("file options");
file_options->add_options()
("input,i", po::value<std::string>(&m_inputFile), "input file name")
("output,o", po::value<std::string>(&m_outputFile), "output file name")
("native", "use native LAS classes (not liblas)")
("oracle-writer", "Read data from LAS file and write to Oracle")
("oracle-reader", "Read data from Oracle and write to LAS")
("a_srs", po::value<std::string>(&m_srs)->default_value(""), "Assign output coordinate system")
("compress", po::value<bool>(&m_bCompress)->zero_tokens()->implicit_value(true),"Compress output data if available")
("xml", po::value<std::string>(&m_xml)->default_value("log.xml"), "XML file to load process (OCI only right now)")
;
addOptionSet(file_options);
}
int Application_pc2pc::execute()
{
if (!Utils::fileExists(m_inputFile))
{
runtimeError("file not found: " + m_inputFile);
return 1;
}
std::ostream* ofs = Utils::createFile(m_outputFile);
if (hasOption("native"))
{
pdal::drivers::las::LasReader reader(m_inputFile);
const boost::uint64_t numPoints = reader.getNumPoints();
pdal::drivers::las::LasWriter writer(reader, ofs);
//BUG: handle laz writer.setCompressed(false);
//writer.setPointFormat( reader.getPointFormatNumber() );
writer.initialize();
writer.write(numPoints);
}
else if (hasOption("oracle-writer"))
{
#ifdef PDAL_HAVE_ORACLE
try{
pdal::drivers::las::LasReader reader(m_inputFile);
const boost::uint64_t numPoints = reader.getNumPoints();
boost::property_tree::ptree load_tree;
boost::property_tree::read_xml(m_xml, load_tree);
boost::property_tree::ptree oracle_options = load_tree.get_child("pdal.drivers.oci.writer");
boost::property_tree::ptree las_options = load_tree.get_child("pdal.drivers.las");
pdal::OptionsOld options(oracle_options);
boost::property_tree::ptree in_srs_options = las_options.get_child("spatialreference");
std::string in_wkt = in_srs_options.get<std::string>("userinput");
boost::property_tree::ptree out_srs_options = oracle_options.get_child("spatialreference");
std::string out_wkt = out_srs_options.get<std::string>("userinput");
pdal::SpatialReference in_ref(in_wkt);
pdal::SpatialReference out_ref(out_wkt);
boost::property_tree::ptree& tree = options.GetPTree();
boost::uint32_t capacity = tree.get<boost::uint32_t>("capacity");
double scalex = oracle_options.get<double>("scale.x");
double scaley = oracle_options.get<double>("scale.y");
double scalez = oracle_options.get<double>("scale.z");
double offsetx = oracle_options.get<double>("offset.x");
double offsety = oracle_options.get<double>("offset.y");
double offsetz = oracle_options.get<double>("offset.z");
pdal::filters::CacheFilter cache(reader, 1, capacity);
pdal::filters::Chipper chipper(cache, capacity);
pdal::filters::ScalingFilter scalingFilter(chipper);
pdal::filters::ReprojectionFilter reprojectionFilter(scalingFilter, in_ref, out_ref);
pdal::filters::DescalingFilter descalingFilter(reprojectionFilter,
scalex, offsetx,
scaley, offsety,
scalez, offsetz);
// pdal::filters::ByteSwapFilter swapper(descalingFilter);
pdal::drivers::oci::Writer writer(descalingFilter, options);
writer.initialize();
writer.write(numPoints);
boost::property_tree::ptree output_tree;
// output_tree.put_child(writer.getName(), options.GetPTree());
// boost::property_tree::write_xml(m_xml, output_tree);
} catch (pdal::pdal_error& e)
{
std::cerr << "Error writing oracle: " << e.what() << std::endl;
}
#else
throw configuration_error("PDAL not compiled with Oracle support");
#endif
}
else if (hasOption("oracle-reader"))
{
#ifdef PDAL_HAVE_ORACLE
try{
boost::property_tree::ptree load_tree;
boost::property_tree::read_xml(m_xml, load_tree);
boost::property_tree::ptree oracle_options = load_tree.get_child("pdal.drivers.oci.reader");
boost::property_tree::ptree las_options = load_tree.get_child("pdal.drivers.las");
boost::property_tree::ptree srs_options = las_options.get_child("spatialreference");
double scalex = las_options.get<double>("scale.x");
double scaley = las_options.get<double>("scale.y");
double scalez = las_options.get<double>("scale.z");
double offsetx = las_options.get<double>("offset.x");
double offsety = las_options.get<double>("offset.y");
double offsetz = las_options.get<double>("offset.z");
bool compress = las_options.get<bool>("compress");
std::string out_wkt = srs_options.get<std::string>("userinput");
pdal::OptionsOld options(oracle_options);
pdal::drivers::oci::Reader reader(options);
pdal::drivers::las::LasWriter* writer;
pdal::SpatialReference out_ref(out_wkt);
pdal::SpatialReference in_ref(reader.getSpatialReference());
if (!(in_ref == out_ref))
{
// pdal::filters::ByteSwapFilter swapper(reader);
pdal::filters::ScalingFilter scalingFilter(reader);
pdal::filters::ReprojectionFilter reprojectionFilter(scalingFilter, in_ref, out_ref);
pdal::filters::DescalingFilter descalingFilter(reprojectionFilter,
scalex, offsetx,
scaley, offsety,
scalez, offsetz);
writer = new pdal::drivers::las::LasWriter(descalingFilter, ofs);
if (compress)
writer->setCompressed(true);
writer->setChunkSize(oracle_options.get<boost::uint32_t>("capacity"));
writer->setPointFormat(pdal::drivers::las::PointFormat3);
writer->initialize();
writer->write(0);
delete writer;
}
else
{
writer = new pdal::drivers::las::LasWriter(reader, ofs);
if (compress)
writer->setCompressed(true);
writer->setChunkSize(oracle_options.get<boost::uint32_t>("capacity"));
writer->setPointFormat(pdal::drivers::las::PointFormat3);
writer->initialize();
writer->write(0);
delete writer;
}
} catch (pdal::pdal_error& e)
{
std::cerr << "Error reading oracle: " << e.what() << std::endl;
return 1;
}
#else
throw configuration_error("PDAL not compiled with Oracle support");
#endif
}
else
{
pdal::drivers::liblas::LiblasReader reader(m_inputFile);
const boost::uint64_t numPoints = reader.getNumPoints();
pdal::drivers::liblas::LiblasWriter writer(reader, ofs);
//BUG: handle laz writer.setCompressed(false);
writer.setPointFormat( reader.getPointFormat() );
writer.initialize();
writer.write(numPoints);
}
Utils::closeFile(ofs);
return 0;
}
int main(int argc, char* argv[])
{
Application_pc2pc app(argc, argv);
return app.run();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include <fatal/lesson/driver.h>
namespace lesson {
/**
* @author: Marcelo Juchem <[email protected]>
*/
LESSON(
"representing values, part 1/4",
"This lesson gives an overview on how values are represented. Subsequent "
"tutorials will elaborate on proper ways of achieving such representation."
"\n\n"
"The goal, for now, is to come up with the intuition behind it without "
"drowing in syntax and correctness.",
template <int Value>
struct int_constant {
static int value;
};
template <int Value>
int int_constant<Value>::value = Value;
) {
COMMENT(
"A previous lesson mentioned that values can be emulated using types to "
"represent them. Here's an overview on the intuition of how this can be "
"achieved."
);
CODE(
using x = int_constant<15>;
);
PRINT("x = ", type_str<x>());
PRINT("x::value = ", x::value);
COMMENT(
"Note, however, that `int_constant::value` is a regular runtime variable "
"as opposed to a compile time constant. It is possible, for instance, to "
"change the value associated with it:"
);
CODE(
x::value = 30;
);
PRINT("x::value = ", x::value);
COMMENT(
"This makes it illegal to use such variable as an argument to a template. "
"Template parameters must be immutable and available at compile time. This "
"includes, for instance, type and integer constants."
);
ILLEGAL(
"`int_constant::value` is not a constant",
using y = int_constant<x::value>;
);
}
/**
* @author: Marcelo Juchem <[email protected]>
*/
LESSON(
"representing values, part 2/4",
"This lesson demonstrates proper ways to represent values that can be used "
"at compile time."
"\n\n"
"Let's modify the `int_constant` template to properly represent compile time "
"constants.",
template <int Value>
struct int_constant_proper {
static constexpr int const value = Value;
};
template <int Value>
constexpr int const int_constant_proper<Value>::value;
) {
COMMENT(
"C++11 introduced the `constexpr` keyword which roughly allows us to tell "
"the compiler that a given variable holds the result of a constant "
"expression."
"\n\n"
"Once we have such guarantee, the compiler can evaluate the contents of "
"such variable at compile time, effectivelly making it a compile time "
"constant."
);
CODE(
using x = int_constant_proper<15>;
);
PRINT("x = ", type_str<x>());
PRINT("x::value = ", x::value);
COMMENT(
"As noted before, constants can be used as template parameters."
);
CODE(
using y = int_constant_proper<x::value>;
);
PRINT("y = ", type_str<y>());
PRINT("y::value = ", y::value);
COMMENT(
"In fact, any expression that can be evaluated at compile time can be used "
"as a compile time constant:"
);
CODE(
using z = int_constant_proper<x::value * 2>;
);
PRINT("z = ", type_str<z>());
PRINT("z::value = ", z::value);
CODE(
using w = int_constant_proper<x::value + z::value - 3>;
);
PRINT("w = ", type_str<w>());
PRINT("w::value = ", w::value);
}
/**
* @author: Marcelo Juchem <[email protected]>
*/
LESSON(
"representing values, part 3/4",
"This lesson gives an overview on the implementation of "
"`std::integral_constant`."
"\n\n"
"So far we've been limited to `int` constants. One could be interested in "
"employing other types for a constant, like `char` or `unsigned long`."
"\n\n"
"Let's modify the `int_constant_proper` template to represent arbitrary "
"integral types.",
template <typename T, T Value>
struct constant {
static constexpr T const value = Value;
};
template <typename T, T Value>
constexpr T const constant<T, Value>::value;
) {
COMMENT(
"Now we can specify the type of the constant, as well as its value."
);
using x = constant<int, -15>;
PRINT("x = ", type_str<x>());
PRINT("x::value = ", x::value);
using y = constant<bool, true>;
PRINT("y = ", type_str<y>());
PRINT("y::value = ", std::boolalpha, y::value);
COMMENT(
"Again, any expression that can be evaluated at compile time will do:"
);
using z = constant<unsigned, (x::value > 0) ? x::value : -x::value>;
PRINT("z = ", type_str<z>());
PRINT("z::value = ", z::value);
}
/**
* @author: Marcelo Juchem <[email protected]>
*/
LESSON(
"representing values, part 4/4",
"This lesson gives an overview of some basic features that "
"`std::integral_constant` offers."
"\n\n"
"The implementation and library features built around "
"`std::integral_constant` are a bit more involved than what we've seen so "
"far, but for the purposes of a lesson, we don't need to dig too deep."
"\n\n"
"For now, let's look at a few more things that `std::integral_constant` "
"offers."
) {
COMMENT(
"We already covered how to represent a compile time constant with a type, "
"and how to access the constant's value."
);
using x = std::integral_constant<int, -15>;
PRINT("x = ", type_str<x>());
PRINT("x::value = ", x::value);
COMMENT(
"For convenience purposes, `std::integral_constant` also provides an "
"identity alias in the form of a member called `type`:"
);
PRINT("x::type = ", type_str<x::type>());
COMMENT(
"It also exposes the type of the constant it represents:"
);
PRINT("x::value_type = ", type_str<x::value_type>());
COMMENT(
"Shortcuts to boolean constants are also provided:"
);
using t = std::true_type;
PRINT("t = ", type_str<t>());
PRINT("t::value = ", std::boolalpha, t::value);
PRINT("t::value_type = ", type_str<t::value_type>());
using f = std::false_type;
PRINT("f = ", type_str<f>());
PRINT("f::value = ", std::boolalpha, f::value);
PRINT("f::value_type = ", type_str<f::value_type>());
}
/**
* @author: Marcelo Juchem <[email protected]>
*/
LESSON(
"convenience aliases",
"This lesson gives an overview on how to reduce verbosity through the use of "
"convenience aliases."
"\n\n"
"Some types will be extensively used throughout the examples in this lesson. "
"For instance, `std::integral_constant` for `int` values."
"\n\n"
"For this reason, let's see how we can shorten the code we write when "
"declaring an integral constant through the use of aliases.",
template <int Value>
using int_value = std::integral_constant<int, Value>;
) {
COMMENT(
"Let's start by going the verbose route and fully specifying `x` as an "
"`std::integral_constant`."
);
using x = std::integral_constant<int, 10>;
PRINT("x = ", type_str<x>());
PRINT("x::value = ", x::value);
COMMENT(
"Now let's use the convenient alias `int_value` to declare the same thing."
);
using y = int_value<10>;
PRINT("y = ", type_str<y>());
PRINT("y::value = ", y::value);
COMMENT(
"The beauty of aliases is that they don't create new types. Instead, "
"they're just shortcuts to existing types. For instance, by checking the "
"output of this lesson, it's easy to see that both `x` and `y` reference "
"exactly the same type: `std::integral_constant<int, 10>`."
"\n\n"
"The code below will be further explained in a later lesson. For now, it "
"suffices to know that it will prevent the program from compiling "
"correctly if both `x` and `y` do not represent the same type."
"\n\n"
"This means that, if the line below doesn't result in a compilation error, "
"then both `x` and `y` are guaranteed to reference the same type."
);
static_assert(std::is_same<x, y>::value, "type mismatch");
}
} // namespace lesson {
<commit_msg>- wrapping code blocks in CODE() for lesson 1.1<commit_after>/*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include <fatal/lesson/driver.h>
namespace lesson {
/**
* @author: Marcelo Juchem <[email protected]>
*/
LESSON(
"representing values, part 1/4",
"This lesson gives an overview on how values are represented. Subsequent "
"tutorials will elaborate on proper ways of achieving such representation."
"\n\n"
"The goal, for now, is to come up with the intuition behind it without "
"drowing in syntax and correctness.",
template <int Value>
struct int_constant {
static int value;
};
template <int Value>
int int_constant<Value>::value = Value;
) {
COMMENT(
"A previous lesson mentioned that values can be emulated using types to "
"represent them. Here's an overview on the intuition of how this can be "
"achieved."
);
CODE(
using x = int_constant<15>;
);
PRINT("x = ", type_str<x>());
PRINT("x::value = ", x::value);
COMMENT(
"Note, however, that `int_constant::value` is a regular runtime variable "
"as opposed to a compile time constant. It is possible, for instance, to "
"change the value associated with it:"
);
CODE(
x::value = 30;
);
PRINT("x::value = ", x::value);
COMMENT(
"This makes it illegal to use such variable as an argument to a template. "
"Template parameters must be immutable and available at compile time. This "
"includes, for instance, type and integer constants."
);
ILLEGAL(
"`int_constant::value` is not a constant",
using y = int_constant<x::value>;
);
}
/**
* @author: Marcelo Juchem <[email protected]>
*/
LESSON(
"representing values, part 2/4",
"This lesson demonstrates proper ways to represent values that can be used "
"at compile time."
"\n\n"
"Let's modify the `int_constant` template to properly represent compile time "
"constants.",
template <int Value>
struct int_constant_proper {
static constexpr int const value = Value;
};
template <int Value>
constexpr int const int_constant_proper<Value>::value;
) {
COMMENT(
"C++11 introduced the `constexpr` keyword which roughly allows us to tell "
"the compiler that a given variable holds the result of a constant "
"expression."
"\n\n"
"Once we have such guarantee, the compiler can evaluate the contents of "
"such variable at compile time, effectivelly making it a compile time "
"constant."
);
CODE(
using x = int_constant_proper<15>;
);
PRINT("x = ", type_str<x>());
PRINT("x::value = ", x::value);
COMMENT(
"As noted before, constants can be used as template parameters."
);
CODE(
using y = int_constant_proper<x::value>;
);
PRINT("y = ", type_str<y>());
PRINT("y::value = ", y::value);
COMMENT(
"In fact, any expression that can be evaluated at compile time can be used "
"as a compile time constant:"
);
CODE(
using z = int_constant_proper<x::value * 2>;
);
PRINT("z = ", type_str<z>());
PRINT("z::value = ", z::value);
CODE(
using w = int_constant_proper<x::value + z::value - 3>;
);
PRINT("w = ", type_str<w>());
PRINT("w::value = ", w::value);
}
/**
* @author: Marcelo Juchem <[email protected]>
*/
LESSON(
"representing values, part 3/4",
"This lesson gives an overview on the implementation of "
"`std::integral_constant`."
"\n\n"
"So far we've been limited to `int` constants. One could be interested in "
"employing other types for a constant, like `char` or `unsigned long`."
"\n\n"
"Let's modify the `int_constant_proper` template to represent arbitrary "
"integral types.",
template <typename T, T Value>
struct constant {
static constexpr T const value = Value;
};
template <typename T, T Value>
constexpr T const constant<T, Value>::value;
) {
COMMENT(
"Now we can specify the type of the constant, as well as its value."
);
CODE(
using x = constant<int, -15>;
);
PRINT("x = ", type_str<x>());
PRINT("x::value = ", x::value);
CODE(
using y = constant<bool, true>;
);
PRINT("y = ", type_str<y>());
PRINT("y::value = ", std::boolalpha, y::value);
COMMENT(
"Again, any expression that can be evaluated at compile time will do:"
);
CODE(
using z = constant<unsigned, (x::value > 0) ? x::value : -x::value>;
);
PRINT("z = ", type_str<z>());
PRINT("z::value = ", z::value);
}
/**
* @author: Marcelo Juchem <[email protected]>
*/
LESSON(
"representing values, part 4/4",
"This lesson gives an overview of some basic features that "
"`std::integral_constant` offers."
"\n\n"
"The implementation and library features built around "
"`std::integral_constant` are a bit more involved than what we've seen so "
"far, but for the purposes of a lesson, we don't need to dig too deep."
"\n\n"
"For now, let's look at a few more things that `std::integral_constant` "
"offers."
) {
COMMENT(
"We already covered how to represent a compile time constant with a type, "
"and how to access the constant's value."
);
CODE(
using x = std::integral_constant<int, -15>;
);
PRINT("x = ", type_str<x>());
PRINT("x::value = ", x::value);
COMMENT(
"For convenience purposes, `std::integral_constant` also provides an "
"identity alias in the form of a member called `type`:"
);
PRINT("x::type = ", type_str<x::type>());
COMMENT(
"It also exposes the type of the constant it represents:"
);
PRINT("x::value_type = ", type_str<x::value_type>());
COMMENT(
"Shortcuts to boolean constants are also provided:"
);
CODE(
using t = std::true_type;
);
PRINT("t = ", type_str<t>());
PRINT("t::value = ", std::boolalpha, t::value);
PRINT("t::value_type = ", type_str<t::value_type>());
CODE(
using f = std::false_type;
);
PRINT("f = ", type_str<f>());
PRINT("f::value = ", std::boolalpha, f::value);
PRINT("f::value_type = ", type_str<f::value_type>());
}
/**
* @author: Marcelo Juchem <[email protected]>
*/
LESSON(
"convenience aliases",
"This lesson gives an overview on how to reduce verbosity through the use of "
"convenience aliases."
"\n\n"
"Some types will be extensively used throughout the examples in this lesson. "
"For instance, `std::integral_constant` for `int` values."
"\n\n"
"For this reason, let's see how we can shorten the code we write when "
"declaring an integral constant through the use of aliases.",
template <int Value>
using int_value = std::integral_constant<int, Value>;
) {
COMMENT(
"Let's start by going the verbose route and fully specifying `x` as an "
"`std::integral_constant`."
);
CODE(
using x = std::integral_constant<int, 10>;
);
PRINT("x = ", type_str<x>());
PRINT("x::value = ", x::value);
COMMENT(
"Now let's use the convenient alias `int_value` to declare the same thing."
);
CODE(
using y = int_value<10>;
);
PRINT("y = ", type_str<y>());
PRINT("y::value = ", y::value);
COMMENT(
"The beauty of aliases is that they don't create new types. Instead, "
"they're just shortcuts to existing types. For instance, by checking the "
"output of this lesson, it's easy to see that both `x` and `y` reference "
"exactly the same type: `std::integral_constant<int, 10>`."
"\n\n"
"The code below will be further explained in a later lesson. For now, it "
"suffices to know that it will prevent the program from compiling "
"correctly if both `x` and `y` do not represent the same type."
"\n\n"
"This means that, if the line below doesn't result in a compilation error, "
"then both `x` and `y` are guaranteed to reference the same type."
);
CODE(
static_assert(std::is_same<x, y>::value, "type mismatch");
);
}
} // namespace lesson {
<|endoftext|> |
<commit_before>#include "bamliquidator.h"
#include <cmath>
#include <fstream>
#include <future>
#include <iostream>
#include <map>
#include <stdexcept>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <hdf5.h>
#include <hdf5_hl.h>
struct CountH5Record
{
uint32_t bin_number;
char cell_type[16];
char chromosome[16];
uint64_t count;
char file_name[64];
};
std::vector<CountH5Record> count(const std::string chr,
const std::string cell_type,
const unsigned int bin_size,
const size_t length,
const std::string bam_file)
{
const std::string bam_file_name = file_name_from_path(bam_file);
int bins = std::ceil(length / (double) bin_size);
int max_base_pair = bins * bin_size;
const std::vector<double> bin_counts = liquidate(bam_file, chr, 0, max_base_pair, '.', bins, 0);
CountH5Record record;
record.bin_number = 0;
strncpy(record.cell_type, cell_type.c_str(), sizeof(CountH5Record::cell_type));
strncpy(record.chromosome, chr.c_str(), sizeof(CountH5Record::chromosome));
strncpy(record.file_name, bam_file_name.c_str(), sizeof(CountH5Record::file_name));
std::vector<CountH5Record> records(bin_counts.size(), record);
for (size_t bin=0; bin < bin_counts.size(); ++bin)
{
records[bin].bin_number = bin;
records[bin].count = bin_counts[bin];
}
return records;
}
void batch(hid_t& file,
const std::string& cell_type,
const unsigned int bin_size,
std::map<std::string, size_t> chromosomeLengths,
const std::string& bam_file)
{
std::deque<std::future<std::vector<CountH5Record>>> future_counts;
for (const auto& chromosomeLength : chromosomeLengths)
{
future_counts.push_back(std::async(count,
chromosomeLength.first,
cell_type,
bin_size,
chromosomeLength.second,
bam_file));
}
const size_t record_size = sizeof(CountH5Record);
size_t record_offset[] = { HOFFSET(CountH5Record, bin_number),
HOFFSET(CountH5Record, cell_type),
HOFFSET(CountH5Record, chromosome),
HOFFSET(CountH5Record, count),
HOFFSET(CountH5Record, file_name) };
size_t field_sizes[] = { sizeof(CountH5Record::bin_number),
sizeof(CountH5Record::cell_type),
sizeof(CountH5Record::chromosome),
sizeof(CountH5Record::count),
sizeof(CountH5Record::file_name) };
for (auto& future_count : future_counts)
{
std::vector<CountH5Record> records = future_count.get();
herr_t status = H5TBappend_records(file, "bin_counts", records.size(), record_size,
record_offset, field_sizes, records.data());
if (status != 0)
{
std::cerr << "Error appending record, status = " << status << std::endl;
}
}
}
int main(int argc, char* argv[])
{
try
{
if (argc <= 5 || argc % 2 != 1)
{
std::cerr << "usage: " << argv[0] << " cell_type bin_size bam_file hdf5_file chr1 lenght1 ... \n"
<< "\ne.g. " << argv[0] << " mm1s 100000 /ifs/hg18/mm1s/04032013_D1L57ACXX_4.TTAGGC.hg18.bwt.sorted.bam "
<< "chr1 247249719 chr2 242951149 chr3 199501827"
<< "\nnote that this application is intended to be run from bamliquidator_batch.py -- see"
<< "\nhttps://github.com/BradnerLab/pipeline/wiki for more information"
<< std::endl;
return 1;
}
std::map<std::string, size_t> chromosomeLengths;
for (int arg = 5; arg < argc && arg + 1 < argc; arg += 2)
{
chromosomeLengths[argv[arg]] = boost::lexical_cast<size_t>(argv[arg+1]);
}
const std::string cell_type = argv[1];
const unsigned int bin_size = boost::lexical_cast<unsigned int>(argv[2]);
const std::string bam_file_path = argv[3];
const std::string hdf5_file_path = argv[4];
if (bin_size == 0)
{
std::cerr << "bin size cannot be zero" << std::endl;
return 2;
}
hid_t h5file = H5Fopen(hdf5_file_path.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
if (h5file < 0)
{
std::cerr << "Failed to open H5 file " << hdf5_file_path << std::endl;
return 3;
}
batch(h5file, cell_type, bin_size, chromosomeLengths, bam_file_path);
H5Fclose(h5file);
return 0;
}
catch(const std::exception& e)
{
std::cerr << "Unhandled exception: " << e.what() << std::endl;
return 4;
}
}
/* The MIT License (MIT)
Copyright (c) 2013 John DiMatteo ([email protected])
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.
*/
<commit_msg>Fixed chromosome order (e.g. so chr2 is before chr10)<commit_after>#include "bamliquidator.h"
#include <cmath>
#include <fstream>
#include <future>
#include <iostream>
#include <stdexcept>
#include <sstream>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <hdf5.h>
#include <hdf5_hl.h>
struct CountH5Record
{
uint32_t bin_number;
char cell_type[16];
char chromosome[16];
uint64_t count;
char file_name[64];
};
std::vector<CountH5Record> count(const std::string chr,
const std::string cell_type,
const unsigned int bin_size,
const size_t length,
const std::string bam_file)
{
const std::string bam_file_name = file_name_from_path(bam_file);
int bins = std::ceil(length / (double) bin_size);
int max_base_pair = bins * bin_size;
const std::vector<double> bin_counts = liquidate(bam_file, chr, 0, max_base_pair, '.', bins, 0);
CountH5Record record;
record.bin_number = 0;
strncpy(record.cell_type, cell_type.c_str(), sizeof(CountH5Record::cell_type));
strncpy(record.chromosome, chr.c_str(), sizeof(CountH5Record::chromosome));
strncpy(record.file_name, bam_file_name.c_str(), sizeof(CountH5Record::file_name));
std::vector<CountH5Record> records(bin_counts.size(), record);
for (size_t bin=0; bin < bin_counts.size(); ++bin)
{
records[bin].bin_number = bin;
records[bin].count = bin_counts[bin];
}
return records;
}
void batch(hid_t& file,
const std::string& cell_type,
const unsigned int bin_size,
const std::vector<std::pair<std::string, size_t>>& chromosomeLengths,
const std::string& bam_file)
{
std::deque<std::future<std::vector<CountH5Record>>> future_counts;
for (const auto& chromosomeLength : chromosomeLengths)
{
future_counts.push_back(std::async(count,
chromosomeLength.first,
cell_type,
bin_size,
chromosomeLength.second,
bam_file));
}
const size_t record_size = sizeof(CountH5Record);
size_t record_offset[] = { HOFFSET(CountH5Record, bin_number),
HOFFSET(CountH5Record, cell_type),
HOFFSET(CountH5Record, chromosome),
HOFFSET(CountH5Record, count),
HOFFSET(CountH5Record, file_name) };
size_t field_sizes[] = { sizeof(CountH5Record::bin_number),
sizeof(CountH5Record::cell_type),
sizeof(CountH5Record::chromosome),
sizeof(CountH5Record::count),
sizeof(CountH5Record::file_name) };
for (auto& future_count : future_counts)
{
std::vector<CountH5Record> records = future_count.get();
herr_t status = H5TBappend_records(file, "bin_counts", records.size(), record_size,
record_offset, field_sizes, records.data());
if (status != 0)
{
std::cerr << "Error appending record, status = " << status << std::endl;
}
}
}
int main(int argc, char* argv[])
{
try
{
if (argc <= 5 || argc % 2 != 1)
{
std::cerr << "usage: " << argv[0] << " cell_type bin_size bam_file hdf5_file chr1 lenght1 ... \n"
<< "\ne.g. " << argv[0] << " mm1s 100000 /ifs/hg18/mm1s/04032013_D1L57ACXX_4.TTAGGC.hg18.bwt.sorted.bam "
<< "chr1 247249719 chr2 242951149 chr3 199501827"
<< "\nnote that this application is intended to be run from bamliquidator_batch.py -- see"
<< "\nhttps://github.com/BradnerLab/pipeline/wiki for more information"
<< std::endl;
return 1;
}
std::vector<std::pair<std::string, size_t>> chromosomeLengths;
for (int arg = 5; arg < argc && arg + 1 < argc; arg += 2)
{
chromosomeLengths.push_back(
std::make_pair(argv[arg], boost::lexical_cast<size_t>(argv[arg+1])));
}
const std::string cell_type = argv[1];
const unsigned int bin_size = boost::lexical_cast<unsigned int>(argv[2]);
const std::string bam_file_path = argv[3];
const std::string hdf5_file_path = argv[4];
if (bin_size == 0)
{
std::cerr << "bin size cannot be zero" << std::endl;
return 2;
}
hid_t h5file = H5Fopen(hdf5_file_path.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
if (h5file < 0)
{
std::cerr << "Failed to open H5 file " << hdf5_file_path << std::endl;
return 3;
}
batch(h5file, cell_type, bin_size, chromosomeLengths, bam_file_path);
H5Fclose(h5file);
return 0;
}
catch(const std::exception& e)
{
std::cerr << "Unhandled exception: " << e.what() << std::endl;
return 4;
}
}
/* The MIT License (MIT)
Copyright (c) 2013 John DiMatteo ([email protected])
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.
*/
<|endoftext|> |
<commit_before>// Copyright (c) 2022 PaddlePaddle 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 "paddle/phi/kernels/split_kernel.h"
#include "paddle/phi/backends/onednn/onednn_reuse.h"
#include "paddle/phi/core/kernel_registry.h"
namespace phi {
template <typename T, typename Context>
void SplitKernel(const Context& dev_ctx,
const DenseTensor& x,
const IntArray& sections,
const Scalar& split_axis,
std::vector<DenseTensor*> out) {
const auto& onednn_engine = dev_ctx.GetEngine();
int axis = split_axis.to<int>();
auto outs_number = out.size();
const auto x_dims = x.dims();
auto x_vec_dims = vectorize(x_dims);
dnnl::memory::data_type x_type = funcs::ToOneDNNDataType(x.dtype());
auto& astream = OneDNNContext::tls().get_stream();
std::vector<int64_t> offset(x_vec_dims.size(), 0);
funcs::ReorderOneDNNHandler reorder_handler(
x_vec_dims, x.dtype(), x_type, onednn_engine);
auto reorder_src_memory_p = reorder_handler.AcquireSrcMemory(
x.mem_desc(), funcs::to_void_cast(x.data<T>()));
for (size_t i = 0; i < outs_number; ++i) {
auto out_vec_dims = vectorize(out[i]->dims());
auto slice_mem_p = reorder_handler.AcquireSubmemory(
out_vec_dims, offset, reorder_src_memory_p);
auto reorder_dst_memory_p = reorder_handler.AcquireDstMemory(
out[i], out_vec_dims, x.format(), dev_ctx.GetPlace());
auto reorder_p =
reorder_handler.AcquireReorder(reorder_dst_memory_p, slice_mem_p);
reorder_p->execute(astream, *slice_mem_p, *reorder_dst_memory_p);
offset[axis] += sections.GetData()[i];
out[i]->set_mem_desc(reorder_dst_memory_p->get_desc());
}
astream.wait();
}
template <typename T, typename Context>
void SplitWithNumKernel(const Context& dev_ctx,
const DenseTensor& x,
int num,
const Scalar& axis_scalar,
std::vector<DenseTensor*> outs) {
int axis_value = axis_scalar.to<int>();
auto input_axis_dim = x.dims().at(axis_value);
std::vector<int64_t> sections_vec;
for (int i = 0; i < num; ++i) {
sections_vec.push_back(input_axis_dim / num);
}
IntArray sections(sections_vec);
SplitKernel<T, Context>(dev_ctx, x, sections, axis_scalar, outs);
}
} // namespace phi
PD_REGISTER_KERNEL(
split, OneDNN, ONEDNN, phi::SplitKernel, float, phi::dtype::bfloat16) {}
PD_REGISTER_KERNEL(split_with_num,
OneDNN,
ONEDNN,
phi::SplitWithNumKernel,
float,
phi::dtype::bfloat16) {}
<commit_msg>minor split optimization (#47314)<commit_after>// Copyright (c) 2022 PaddlePaddle 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 "paddle/phi/kernels/split_kernel.h"
#include "paddle/phi/backends/onednn/onednn_reuse.h"
#include "paddle/phi/core/kernel_registry.h"
namespace phi {
template <typename T, typename Context>
void SplitKernel(const Context& dev_ctx,
const DenseTensor& x,
const IntArray& sections,
const Scalar& split_axis,
std::vector<DenseTensor*> out) {
const auto& onednn_engine = dev_ctx.GetEngine();
int axis = split_axis.to<int>();
auto outs_number = out.size();
const auto x_dims = x.dims();
auto x_vec_dims = vectorize(x_dims);
dnnl::memory::data_type x_type = funcs::ToOneDNNDataType(x.dtype());
auto& astream = OneDNNContext::tls().get_stream();
std::vector<int64_t> offset(x_vec_dims.size(), 0);
funcs::ReorderOneDNNHandler reorder_handler(
x_vec_dims, x.dtype(), x_type, onednn_engine);
auto reorder_src_memory_p = reorder_handler.AcquireSrcMemory(
x.mem_desc(), funcs::to_void_cast(x.data<T>()));
for (size_t i = 0; i < outs_number; ++i) {
auto out_vec_dims = vectorize(out[i]->dims());
auto slice_mem_p = reorder_handler.AcquireSubmemory(
out_vec_dims, offset, reorder_src_memory_p);
auto reorder_dst_memory_p = reorder_handler.AcquireDstMemory(
out[i], out_vec_dims, x.format(), dev_ctx.GetPlace());
auto reorder_p =
reorder_handler.AcquireReorder(reorder_dst_memory_p, slice_mem_p);
reorder_p->execute(astream, *slice_mem_p, *reorder_dst_memory_p);
offset[axis] += sections.GetData()[i];
out[i]->set_mem_desc(reorder_dst_memory_p->get_desc());
}
astream.wait();
}
template <typename T, typename Context>
void SplitWithNumKernel(const Context& dev_ctx,
const DenseTensor& x,
int num,
const Scalar& axis_scalar,
std::vector<DenseTensor*> outs) {
int axis_value = axis_scalar.to<int>();
auto input_axis_dim = x.dims().at(axis_value);
const std::vector<int64_t> sections_vec(num, input_axis_dim / num);
IntArray sections(sections_vec);
SplitKernel<T, Context>(dev_ctx, x, sections, axis_scalar, outs);
}
} // namespace phi
PD_REGISTER_KERNEL(
split, OneDNN, ONEDNN, phi::SplitKernel, float, phi::dtype::bfloat16) {}
PD_REGISTER_KERNEL(split_with_num,
OneDNN,
ONEDNN,
phi::SplitWithNumKernel,
float,
phi::dtype::bfloat16) {}
<|endoftext|> |
<commit_before>/*
************************************************************************
* HardwareSerial.cpp
*
* Arduino core files for MSP430
* Copyright (c) 2012 Robert Wessels. All right reserved.
*
*
***********************************************************************
Derived from:
HardwareSerial.cpp - Hardware serial library for Wiring
Copyright (c) 2006 Nicholas Zambetti. All right reserved.
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
Modified 23 November 2006 by David A. Mellis
Modified 28 September 2010 by Mark Sproul
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "Energia.h"
#include "wiring_private.h"
#include "usci_isr_handler.h"
#if defined(__MSP430_HAS_USCI__) || defined(__MSP430_HAS_USCI_A0__) || defined(__MSP430_HAS_USCI_A1__) || defined(__MSP430_HAS_EUSCI_A0__)
#include "HardwareSerial.h"
#define UCAxCTLW0 UCA0CTLW0
#define UCAxCTL0 UCA0CTL0
#define UCAxCTL1 UCA0CTL1
#define UCAxBRW UCA0BRW
#define UCAxBR0 UCA0BR0
#define UCAxBR1 UCA0BR1
#define UCAxMCTL UCA0MCTL
#define UCAxMCTLW UCA0MCTLW
#define UCAxSTAT UCA0STAT
#define UCAxRXBUF UCA0RXBUF
#define UCAxTXBUF UCA0TXBUF
#define UCAxABCTL UCA0ABCTL
#define UCAxIRCTL UCA0IRCTL
#define UCAxIRTCTL UCA0IRTCTL
#define UCAxIRRCTL UCA0IRRCTL
#define UCAxICTL UCA0ICTL
#define UCAxIE UCA0IE
#define UCAxIFG UCA0IFG
#define UCAxIV UCA0IV
#define SERIAL_BUFFER_SIZE 16
struct ring_buffer
{
unsigned char buffer[SERIAL_BUFFER_SIZE];
volatile unsigned int head;
volatile unsigned int tail;
};
ring_buffer rx_buffer = { { 0 }, 0, 0 };
ring_buffer tx_buffer = { { 0 }, 0, 0 };
#ifdef SERIAL1_AVAILABLE
ring_buffer rx_buffer1 = { { 0 }, 0, 0 };
ring_buffer tx_buffer1 = { { 0 }, 0, 0 };
#endif
inline void store_char(unsigned char c, ring_buffer *buffer)
{
unsigned int i = (unsigned int)(buffer->head + 1) % SERIAL_BUFFER_SIZE;
// if we should be storing the received character into the location
// just before the tail (meaning that the head would advance to the
// current location of the tail), we're about to overflow the buffer
// and so we don't write the character or advance the head.
if (i != buffer->tail) {
buffer->buffer[buffer->head] = c;
buffer->head = i;
}
}
void serialEvent() __attribute__((weak));
void serialEvent() {}
#ifdef SERIAL1_AVAILABLE
void serialEvent1() __attribute__((weak));
void serialEvent1() {}
#endif
void serialEventRun(void)
{
if (Serial.available()) serialEvent();
#ifdef SERIAL1_AVAILABLE
if (Serial1.available()) serialEvent1();
#endif
}
// Public Methods //////////////////////////////////////////////////////////////
#define SMCLK F_CPU //SMCLK = F_CPU for now
void HardwareSerial::begin(unsigned long baud)
{
unsigned int mod, divider;
unsigned char oversampling;
/* Calling this dummy function prevents the linker
* from stripping the USCI interupt vectors.*/
usci_isr_install();
if (SMCLK/baud>=48) { // requires SMCLK for oversampling
oversampling = 1;
}
else {
oversampling= 0;
}
divider=(SMCLK<<4)/baud;
pinMode_int(rxPin, rxPinMode);
pinMode_int(txPin, txPinMode);
*(&(UCAxCTL1) + uartOffset) = UCSWRST;
*(&(UCAxCTL1) + uartOffset) = UCSSEL_2; // SMCLK
*(&(UCAxCTL0) + uartOffset) = 0;
*(&(UCAxABCTL) + uartOffset) = 0;
#if defined(__MSP430_HAS_EUSCI_A0__)
if(!oversampling) {
mod = ((divider&0xF)+1)&0xE; // UCBRSx (bit 1-3)
divider >>=4;
} else {
mod = divider&0xFFF0; // UCBRFx = INT([(N/16) INT(N/16)] 16)
divider>>=8;
}
*(&(UCAxBR0) + uartOffset) = divider;
*(&(UCAxBR1) + uartOffset) = divider>>8;
*(&(UCAxMCTLW) + uartOffset)= (oversampling ? UCOS16:0) | mod;
#else
if(!oversampling) {
mod = ((divider&0xF)+1)&0xE; // UCBRSx (bit 1-3)
divider >>=4;
} else {
mod = ((divider&0xf8)+0x8)&0xf0; // UCBRFx (bit 4-7)
divider>>=8;
}
*(&(UCAxBR0) + uartOffset)= divider;
*(&(UCAxBR1) + uartOffset) = divider>>8;
*(&(UCAxMCTL) + uartOffset) = (unsigned char)(oversampling ? UCOS16:0) | mod;
#endif
*(&(UCAxCTL1) + uartOffset) &= ~UCSWRST;
#if defined(__MSP430_HAS_USCI_A0__) || defined(__MSP430_HAS_USCI_A1__) || defined(__MSP430_HAS_EUSCI_A0__)
*(&(UCAxIE) + uartOffset) |= UCRXIE;
#else
*(&(UC0IE) + uartOffset) |= UCA0RXIE;
#endif
}
void HardwareSerial::end()
{
// wait for transmission of outgoing data
while (_tx_buffer->head != _tx_buffer->tail);
_rx_buffer->head = _rx_buffer->tail;
}
int HardwareSerial::available(void)
{
return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % SERIAL_BUFFER_SIZE;
}
int HardwareSerial::peek(void)
{
if (_rx_buffer->head == _rx_buffer->tail) {
return -1;
} else {
return _rx_buffer->buffer[_rx_buffer->tail];
}
}
int HardwareSerial::read(void)
{
// if the head isn't ahead of the tail, we don't have any characters
if (_rx_buffer->head == _rx_buffer->tail) {
return -1;
} else {
unsigned char c = _rx_buffer->buffer[_rx_buffer->tail];
_rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % SERIAL_BUFFER_SIZE;
return c;
}
}
void HardwareSerial::flush()
{
while (_tx_buffer->head != _tx_buffer->tail);
}
size_t HardwareSerial::write(uint8_t c)
{
unsigned int i = (_tx_buffer->head + 1) % SERIAL_BUFFER_SIZE;
// If the output buffer is full, there's nothing for it other than to
// wait for the interrupt handler to empty it a bit
// ???: return 0 here instead?
while (i == _tx_buffer->tail);
_tx_buffer->buffer[_tx_buffer->head] = c;
_tx_buffer->head = i;
#if defined(__MSP430_HAS_USCI_A0__) || defined(__MSP430_HAS_USCI_A1__) || defined(__MSP430_HAS_EUSCI_A0__)
*(&(UCAxIE) + uartOffset) |= UCTXIE;
#else
*(&(UC0IE) + uartOffset) |= UCA0TXIE;
#endif
return 1;
}
void uart_rx_isr(uint8_t offset)
{
#ifdef SERIAL1_AVAILABLE
/* Debug uart aka Serial always gets rx_buffer and aux aka Serial1 gets rx_buffer1 */
ring_buffer *rx_buffer_ptr = (offset == DEBUG_UART_MODULE_OFFSET) ? &rx_buffer:&rx_buffer1;
#else
ring_buffer *rx_buffer_ptr = &rx_buffer;
#endif
unsigned char c = *(&(UCAxRXBUF) + offset);
store_char(c, rx_buffer_ptr);
}
void uart_tx_isr(uint8_t offset)
{
#ifdef SERIAL1_AVAILABLE
/* Debug uart aka Serial always gets rx_buffer and aux aka Serial1 gets rx_buffer1 */
ring_buffer *tx_buffer_ptr = (offset == DEBUG_UART_MODULE_OFFSET) ? &tx_buffer : &tx_buffer;
#else
ring_buffer *tx_buffer_ptr = &tx_buffer;
#endif
if (tx_buffer_ptr->head == tx_buffer_ptr->tail) {
// Buffer empty, so disable interrupts
#if defined(__MSP430_HAS_USCI_A0__) || defined(__MSP430_HAS_USCI_A1__) || defined(__MSP430_HAS_EUSCI_A0__)
*(&(UCAxIE) + offset) &= ~UCTXIE;
*(&(UCAxIFG) + offset) |= UCTXIFG; // Set Flag again
#else
*(&(UC0IE) + offset) &= ~UCA0TXIE;
#endif
return;
}
unsigned char c = tx_buffer_ptr->buffer[tx_buffer_ptr->tail];
tx_buffer_ptr->tail = (tx_buffer_ptr->tail + 1) % SERIAL_BUFFER_SIZE;
*(&(UCAxTXBUF) + offset) = c;
}
// Preinstantiate Objects //////////////////////////////////////////////////////
HardwareSerial Serial(&rx_buffer, &tx_buffer, DEBUG_UART_MODULE_OFFSET, DEBUG_UARTRXD_SET_MODE, DEBUG_UARTTXD_SET_MODE, DEBUG_UARTRXD, DEBUG_UARTTXD);
#ifdef SERIAL1_AVAILABLE
HardwareSerial Serial1(&rx_buffer1, &tx_buffer1, AUX_UART_MODULE_OFFSET, AUX_UARTRXD_SET_MODE, DEBUG_UARTTXD_SET_MODE, AUX_UARTRXD, AUX_UARTTXD);
#endif
#endif
<commit_msg>Fix auxiliary UART tx buffer assignment<commit_after>/*
************************************************************************
* HardwareSerial.cpp
*
* Arduino core files for MSP430
* Copyright (c) 2012 Robert Wessels. All right reserved.
*
*
***********************************************************************
Derived from:
HardwareSerial.cpp - Hardware serial library for Wiring
Copyright (c) 2006 Nicholas Zambetti. All right reserved.
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
Modified 23 November 2006 by David A. Mellis
Modified 28 September 2010 by Mark Sproul
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "Energia.h"
#include "wiring_private.h"
#include "usci_isr_handler.h"
#if defined(__MSP430_HAS_USCI__) || defined(__MSP430_HAS_USCI_A0__) || defined(__MSP430_HAS_USCI_A1__) || defined(__MSP430_HAS_EUSCI_A0__)
#include "HardwareSerial.h"
#define UCAxCTLW0 UCA0CTLW0
#define UCAxCTL0 UCA0CTL0
#define UCAxCTL1 UCA0CTL1
#define UCAxBRW UCA0BRW
#define UCAxBR0 UCA0BR0
#define UCAxBR1 UCA0BR1
#define UCAxMCTL UCA0MCTL
#define UCAxMCTLW UCA0MCTLW
#define UCAxSTAT UCA0STAT
#define UCAxRXBUF UCA0RXBUF
#define UCAxTXBUF UCA0TXBUF
#define UCAxABCTL UCA0ABCTL
#define UCAxIRCTL UCA0IRCTL
#define UCAxIRTCTL UCA0IRTCTL
#define UCAxIRRCTL UCA0IRRCTL
#define UCAxICTL UCA0ICTL
#define UCAxIE UCA0IE
#define UCAxIFG UCA0IFG
#define UCAxIV UCA0IV
#define SERIAL_BUFFER_SIZE 16
struct ring_buffer
{
unsigned char buffer[SERIAL_BUFFER_SIZE];
volatile unsigned int head;
volatile unsigned int tail;
};
ring_buffer rx_buffer = { { 0 }, 0, 0 };
ring_buffer tx_buffer = { { 0 }, 0, 0 };
#ifdef SERIAL1_AVAILABLE
ring_buffer rx_buffer1 = { { 0 }, 0, 0 };
ring_buffer tx_buffer1 = { { 0 }, 0, 0 };
#endif
inline void store_char(unsigned char c, ring_buffer *buffer)
{
unsigned int i = (unsigned int)(buffer->head + 1) % SERIAL_BUFFER_SIZE;
// if we should be storing the received character into the location
// just before the tail (meaning that the head would advance to the
// current location of the tail), we're about to overflow the buffer
// and so we don't write the character or advance the head.
if (i != buffer->tail) {
buffer->buffer[buffer->head] = c;
buffer->head = i;
}
}
void serialEvent() __attribute__((weak));
void serialEvent() {}
#ifdef SERIAL1_AVAILABLE
void serialEvent1() __attribute__((weak));
void serialEvent1() {}
#endif
void serialEventRun(void)
{
if (Serial.available()) serialEvent();
#ifdef SERIAL1_AVAILABLE
if (Serial1.available()) serialEvent1();
#endif
}
// Public Methods //////////////////////////////////////////////////////////////
#define SMCLK F_CPU //SMCLK = F_CPU for now
void HardwareSerial::begin(unsigned long baud)
{
unsigned int mod, divider;
unsigned char oversampling;
/* Calling this dummy function prevents the linker
* from stripping the USCI interupt vectors.*/
usci_isr_install();
if (SMCLK/baud>=48) { // requires SMCLK for oversampling
oversampling = 1;
}
else {
oversampling= 0;
}
divider=(SMCLK<<4)/baud;
pinMode_int(rxPin, rxPinMode);
pinMode_int(txPin, txPinMode);
*(&(UCAxCTL1) + uartOffset) = UCSWRST;
*(&(UCAxCTL1) + uartOffset) = UCSSEL_2; // SMCLK
*(&(UCAxCTL0) + uartOffset) = 0;
*(&(UCAxABCTL) + uartOffset) = 0;
#if defined(__MSP430_HAS_EUSCI_A0__)
if(!oversampling) {
mod = ((divider&0xF)+1)&0xE; // UCBRSx (bit 1-3)
divider >>=4;
} else {
mod = divider&0xFFF0; // UCBRFx = INT([(N/16) INT(N/16)] 16)
divider>>=8;
}
*(&(UCAxBR0) + uartOffset) = divider;
*(&(UCAxBR1) + uartOffset) = divider>>8;
*(&(UCAxMCTLW) + uartOffset)= (oversampling ? UCOS16:0) | mod;
#else
if(!oversampling) {
mod = ((divider&0xF)+1)&0xE; // UCBRSx (bit 1-3)
divider >>=4;
} else {
mod = ((divider&0xf8)+0x8)&0xf0; // UCBRFx (bit 4-7)
divider>>=8;
}
*(&(UCAxBR0) + uartOffset)= divider;
*(&(UCAxBR1) + uartOffset) = divider>>8;
*(&(UCAxMCTL) + uartOffset) = (unsigned char)(oversampling ? UCOS16:0) | mod;
#endif
*(&(UCAxCTL1) + uartOffset) &= ~UCSWRST;
#if defined(__MSP430_HAS_USCI_A0__) || defined(__MSP430_HAS_USCI_A1__) || defined(__MSP430_HAS_EUSCI_A0__)
*(&(UCAxIE) + uartOffset) |= UCRXIE;
#else
*(&(UC0IE) + uartOffset) |= UCA0RXIE;
#endif
}
void HardwareSerial::end()
{
// wait for transmission of outgoing data
while (_tx_buffer->head != _tx_buffer->tail);
_rx_buffer->head = _rx_buffer->tail;
}
int HardwareSerial::available(void)
{
return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % SERIAL_BUFFER_SIZE;
}
int HardwareSerial::peek(void)
{
if (_rx_buffer->head == _rx_buffer->tail) {
return -1;
} else {
return _rx_buffer->buffer[_rx_buffer->tail];
}
}
int HardwareSerial::read(void)
{
// if the head isn't ahead of the tail, we don't have any characters
if (_rx_buffer->head == _rx_buffer->tail) {
return -1;
} else {
unsigned char c = _rx_buffer->buffer[_rx_buffer->tail];
_rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % SERIAL_BUFFER_SIZE;
return c;
}
}
void HardwareSerial::flush()
{
while (_tx_buffer->head != _tx_buffer->tail);
}
size_t HardwareSerial::write(uint8_t c)
{
unsigned int i = (_tx_buffer->head + 1) % SERIAL_BUFFER_SIZE;
// If the output buffer is full, there's nothing for it other than to
// wait for the interrupt handler to empty it a bit
// ???: return 0 here instead?
while (i == _tx_buffer->tail);
_tx_buffer->buffer[_tx_buffer->head] = c;
_tx_buffer->head = i;
#if defined(__MSP430_HAS_USCI_A0__) || defined(__MSP430_HAS_USCI_A1__) || defined(__MSP430_HAS_EUSCI_A0__)
*(&(UCAxIE) + uartOffset) |= UCTXIE;
#else
*(&(UC0IE) + uartOffset) |= UCA0TXIE;
#endif
return 1;
}
void uart_rx_isr(uint8_t offset)
{
#ifdef SERIAL1_AVAILABLE
/* Debug uart aka Serial always gets rx_buffer and aux aka Serial1 gets rx_buffer1 */
ring_buffer *rx_buffer_ptr = (offset == DEBUG_UART_MODULE_OFFSET) ? &rx_buffer:&rx_buffer1;
#else
ring_buffer *rx_buffer_ptr = &rx_buffer;
#endif
unsigned char c = *(&(UCAxRXBUF) + offset);
store_char(c, rx_buffer_ptr);
}
void uart_tx_isr(uint8_t offset)
{
#ifdef SERIAL1_AVAILABLE
/* Debug uart aka Serial always gets rx_buffer and aux aka Serial1 gets rx_buffer1 */
ring_buffer *tx_buffer_ptr = (offset == DEBUG_UART_MODULE_OFFSET) ? &tx_buffer : &tx_buffer1;
#else
ring_buffer *tx_buffer_ptr = &tx_buffer;
#endif
if (tx_buffer_ptr->head == tx_buffer_ptr->tail) {
// Buffer empty, so disable interrupts
#if defined(__MSP430_HAS_USCI_A0__) || defined(__MSP430_HAS_USCI_A1__) || defined(__MSP430_HAS_EUSCI_A0__)
*(&(UCAxIE) + offset) &= ~UCTXIE;
*(&(UCAxIFG) + offset) |= UCTXIFG; // Set Flag again
#else
*(&(UC0IE) + offset) &= ~UCA0TXIE;
#endif
return;
}
unsigned char c = tx_buffer_ptr->buffer[tx_buffer_ptr->tail];
tx_buffer_ptr->tail = (tx_buffer_ptr->tail + 1) % SERIAL_BUFFER_SIZE;
*(&(UCAxTXBUF) + offset) = c;
}
// Preinstantiate Objects //////////////////////////////////////////////////////
HardwareSerial Serial(&rx_buffer, &tx_buffer, DEBUG_UART_MODULE_OFFSET, DEBUG_UARTRXD_SET_MODE, DEBUG_UARTTXD_SET_MODE, DEBUG_UARTRXD, DEBUG_UARTTXD);
#ifdef SERIAL1_AVAILABLE
HardwareSerial Serial1(&rx_buffer1, &tx_buffer1, AUX_UART_MODULE_OFFSET, AUX_UARTRXD_SET_MODE, DEBUG_UARTTXD_SET_MODE, AUX_UARTRXD, AUX_UARTTXD);
#endif
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <[email protected]>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtTest/QtTest>
#include <QtCore>
#include "nanoxml.h"
#include "fileutils.h"
#include "contexttypeinfo.h"
#include "contexttyperegistryinfo.h"
ContextTypeRegistryInfo* ContextTypeRegistryInfo::registryInstance = new ContextTypeRegistryInfo();
/* Mocked ContextTypeRegistryInfo */
ContextTypeRegistryInfo::ContextTypeRegistryInfo()
{
}
ContextTypeRegistryInfo* ContextTypeRegistryInfo::instance()
{
return registryInstance;
}
NanoTree ContextTypeRegistryInfo::typeDefinitionForName(QString name)
{
if (name == "double") {
QVariantList tree;
QVariantList doc;
QVariantList name;
name << QVariant("name");
name << QVariant("double");
doc << QVariant("doc");
doc << QVariant("double doc");
tree << QVariant("type");
tree << QVariant(name);
tree << QVariant(doc);
return ContextTypeInfo(QVariant(tree));
} else if (name == "complex") {
QVariantList tree;
QVariantList doc;
QVariantList base;
QVariantList name;
name << QVariant("name");
name << QVariant("complex");
doc << QVariant("doc");
doc << QVariant("complex doc");
base << QVariant("base");
base << QVariant("double");
tree << QVariant("type");
tree << QVariant(name);
tree << QVariant(doc);
tree << QVariant(base);
return ContextTypeInfo(QVariant(tree));
} else
return ContextTypeInfo();
}
class ContextTypeInfoUnitTest : public QObject
{
Q_OBJECT
private slots:
void name();
void doc();
void base();
void definition();
void parseDoubleType();
void parseCustomDoubleType();
void parseUniformList();
void parseMap();
};
void ContextTypeInfoUnitTest::name()
{
QCOMPARE(ContextTypeInfo(QString("bool")).name(), QString("bool"));
QCOMPARE(ContextTypeInfo(QString("string")).name(), QString("string"));
QVariantList lst;
lst << QVariant("int32");
QCOMPARE(ContextTypeInfo(QVariant(lst)).name(), QString("int32"));
}
void ContextTypeInfoUnitTest::doc()
{
QCOMPARE(ContextTypeInfo(QString("double")).doc(), QString("double doc"));
}
void ContextTypeInfoUnitTest::definition()
{
NanoTree def = ContextTypeInfo(QString("double")).definition();
QCOMPARE(def.keyValue("name").toString(), QString("double"));
QCOMPARE(def.keyValue("doc").toString(), QString("double doc"));
}
void ContextTypeInfoUnitTest::base()
{
ContextTypeInfo base = ContextTypeInfo(QString("complex")).base();
QCOMPARE(base.name(), QString("double"));
QCOMPARE(base.doc(), QString("double doc"));
}
void ContextTypeInfoUnitTest::parseDoubleType()
{
/*
NanoXml parser(LOCAL_FILE("double.xml"));
QCOMPARE(parser.didFail(), false);
ContextTypeInfo typeInfo(parser.result());
QCOMPARE(typeInfo.name(), QString("double"));
QCOMPARE(typeInfo.parameterDoc("min"), QString("Minimum value"));
QCOMPARE(typeInfo.parameterDoc("max"), QString("Maximum value"));
QCOMPARE(typeInfo.doc(), QString("A double value within the given limits."));
*/
//QStringList params = typeInfo.parameters();
//QCOMPARE(params.size(), 2);
//QVERIFY(params.contains(QString("min")));
//QVERIFY(params.contains(QString("max")));
}
void ContextTypeInfoUnitTest::parseCustomDoubleType()
{
/*
NanoXml parser(LOCAL_FILE("custom-double.xml"));
QCOMPARE(parser.didFail(), false);
ContextTypeInfo typeInfo(parser.result());
QCOMPARE(typeInfo.name(), QString("custom-double"));
QCOMPARE(typeInfo.parameterValue("min"), QString("1"));
QCOMPARE(typeInfo.parameterValue("max"), QString("666"));
QCOMPARE(typeInfo.parameterDoc("min"), QString("Minimum value"));
QCOMPARE(typeInfo.parameterDoc("max"), QString("Maximum value"));
QCOMPARE(typeInfo.doc(), QString("A double value that represents the level of hell in you."));
*/
}
void ContextTypeInfoUnitTest::parseUniformList()
{
/*
NanoXml parser(LOCAL_FILE("uniform-list.xml"));
QCOMPARE(parser.didFail(), false);
ContextUniformListTypeInfo listInfo(parser.result());
QCOMPARE(listInfo.base().name(), QString("list"));
QCOMPARE(listInfo.name(), QString("uniform-list"));
ContextTypeInfo elementTypeInfo = listInfo.elementType();
QCOMPARE(elementTypeInfo.name(), QString("double"));
*/
}
void ContextTypeInfoUnitTest::parseMap()
{
/*
NanoXml parser(LOCAL_FILE("person.xml"));
QCOMPARE(parser.didFail(), false);
ContextMapTypeInfo personInfo(parser.result());
QCOMPARE(personInfo.name(), QString("person"));
QCOMPARE(personInfo.base().name(), QString("map"));
QCOMPARE(personInfo.keyDoc("name"), QString("Name of the person"));
QCOMPARE(personInfo.keyDoc("surname"), QString("Surname of the person"));
QCOMPARE(personInfo.keyDoc("age"), QString("Age of the person"));
QCOMPARE(personInfo.keyType("name").name(), QString("string"));
QCOMPARE(personInfo.keyType("surname").name(), QString("string"));
QCOMPARE(personInfo.keyType("age").name(), QString("int32"));
*/
}
#include "contexttypeinfounittest.moc"
QTEST_MAIN(ContextTypeInfoUnitTest);
<commit_msg>Test ContextTypeInfo::parameterDoc.<commit_after>/*
* Copyright (C) 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <[email protected]>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtTest/QtTest>
#include <QtCore>
#include "nanoxml.h"
#include "fileutils.h"
#include "contexttypeinfo.h"
#include "contexttyperegistryinfo.h"
ContextTypeRegistryInfo* ContextTypeRegistryInfo::registryInstance = new ContextTypeRegistryInfo();
/* Mocked ContextTypeRegistryInfo */
ContextTypeRegistryInfo::ContextTypeRegistryInfo()
{
}
ContextTypeRegistryInfo* ContextTypeRegistryInfo::instance()
{
return registryInstance;
}
NanoTree ContextTypeRegistryInfo::typeDefinitionForName(QString name)
{
if (name == "double") {
QVariantList tree;
QVariantList doc;
QVariantList name;
name << QVariant("name");
name << QVariant("double");
doc << QVariant("doc");
doc << QVariant("double doc");
tree << QVariant("type");
tree << QVariant(name);
tree << QVariant(doc);
return ContextTypeInfo(QVariant(tree));
} else if (name == "complex") {
QVariantList tree;
QVariantList doc;
QVariantList base;
QVariantList name;
QVariantList params;
QVariantList p1;
QVariantList p1Doc;
name << QVariant("name");
name << QVariant("complex");
doc << QVariant("doc");
doc << QVariant("complex doc");
base << QVariant("base");
base << QVariant("double");
p1 << QVariant("p1");
p1Doc << QVariant("doc");
p1Doc << QVariant("p1 doc");
p1 << QVariant(p1Doc);
params << QVariant("params");
params << QVariant(p1);
tree << QVariant("type");
tree << QVariant(name);
tree << QVariant(params);
tree << QVariant(doc);
tree << QVariant(base);
return ContextTypeInfo(QVariant(tree));
} else
return ContextTypeInfo();
}
class ContextTypeInfoUnitTest : public QObject
{
Q_OBJECT
private slots:
void name();
void doc();
void base();
void definition();
void parameterDoc();
void parseDoubleType();
void parseCustomDoubleType();
void parseUniformList();
void parseMap();
};
void ContextTypeInfoUnitTest::name()
{
QCOMPARE(ContextTypeInfo(QString("bool")).name(), QString("bool"));
QCOMPARE(ContextTypeInfo(QString("string")).name(), QString("string"));
QVariantList lst;
lst << QVariant("int32");
QCOMPARE(ContextTypeInfo(QVariant(lst)).name(), QString("int32"));
}
void ContextTypeInfoUnitTest::doc()
{
QCOMPARE(ContextTypeInfo(QString("double")).doc(), QString("double doc"));
}
void ContextTypeInfoUnitTest::definition()
{
NanoTree def = ContextTypeInfo(QString("double")).definition();
QCOMPARE(def.keyValue("name").toString(), QString("double"));
QCOMPARE(def.keyValue("doc").toString(), QString("double doc"));
}
void ContextTypeInfoUnitTest::base()
{
ContextTypeInfo base = ContextTypeInfo(QString("complex")).base();
QCOMPARE(base.name(), QString("double"));
QCOMPARE(base.doc(), QString("double doc"));
}
void ContextTypeInfoUnitTest::parameterDoc()
{
ContextTypeInfo typeInfo = ContextTypeInfo(QString("complex"));
QCOMPARE(typeInfo.parameterDoc("p1"), QString("p1 doc"));
}
void ContextTypeInfoUnitTest::parseDoubleType()
{
/*
NanoXml parser(LOCAL_FILE("double.xml"));
QCOMPARE(parser.didFail(), false);
ContextTypeInfo typeInfo(parser.result());
QCOMPARE(typeInfo.name(), QString("double"));
QCOMPARE(typeInfo.parameterDoc("min"), QString("Minimum value"));
QCOMPARE(typeInfo.parameterDoc("max"), QString("Maximum value"));
QCOMPARE(typeInfo.doc(), QString("A double value within the given limits."));
*/
//QStringList params = typeInfo.parameters();
//QCOMPARE(params.size(), 2);
//QVERIFY(params.contains(QString("min")));
//QVERIFY(params.contains(QString("max")));
}
void ContextTypeInfoUnitTest::parseCustomDoubleType()
{
/*
NanoXml parser(LOCAL_FILE("custom-double.xml"));
QCOMPARE(parser.didFail(), false);
ContextTypeInfo typeInfo(parser.result());
QCOMPARE(typeInfo.name(), QString("custom-double"));
QCOMPARE(typeInfo.parameterValue("min"), QString("1"));
QCOMPARE(typeInfo.parameterValue("max"), QString("666"));
QCOMPARE(typeInfo.parameterDoc("min"), QString("Minimum value"));
QCOMPARE(typeInfo.parameterDoc("max"), QString("Maximum value"));
QCOMPARE(typeInfo.doc(), QString("A double value that represents the level of hell in you."));
*/
}
void ContextTypeInfoUnitTest::parseUniformList()
{
/*
NanoXml parser(LOCAL_FILE("uniform-list.xml"));
QCOMPARE(parser.didFail(), false);
ContextUniformListTypeInfo listInfo(parser.result());
QCOMPARE(listInfo.base().name(), QString("list"));
QCOMPARE(listInfo.name(), QString("uniform-list"));
ContextTypeInfo elementTypeInfo = listInfo.elementType();
QCOMPARE(elementTypeInfo.name(), QString("double"));
*/
}
void ContextTypeInfoUnitTest::parseMap()
{
/*
NanoXml parser(LOCAL_FILE("person.xml"));
QCOMPARE(parser.didFail(), false);
ContextMapTypeInfo personInfo(parser.result());
QCOMPARE(personInfo.name(), QString("person"));
QCOMPARE(personInfo.base().name(), QString("map"));
QCOMPARE(personInfo.keyDoc("name"), QString("Name of the person"));
QCOMPARE(personInfo.keyDoc("surname"), QString("Surname of the person"));
QCOMPARE(personInfo.keyDoc("age"), QString("Age of the person"));
QCOMPARE(personInfo.keyType("name").name(), QString("string"));
QCOMPARE(personInfo.keyType("surname").name(), QString("string"));
QCOMPARE(personInfo.keyType("age").name(), QString("int32"));
*/
}
#include "contexttypeinfounittest.moc"
QTEST_MAIN(ContextTypeInfoUnitTest);
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: Mesh2.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginLatex
//
// A Mesh can contain a variety of cells types. Typical cells are the
// LineCell, TriangleCell, QuadrilateralCell and TetrahedronCell. A large
// flexibility is provided for managing cells at the price of a bit more of
// complexity than in the case of point management.
//
// The following code creates a polygonal line in order to illustrate the
// simplest case of cell management in a Mesh. The only cell type used here is
// the \code{itk::LineCell}. The header file of this class has to be included.
//
// \index{itk::LineCell!Header}
//
// Software Guide : EndLatex
#include "itkMesh.h"
// Software Guide : BeginCodeSnippet
#include "itkLineCell.h"
// Software Guide : EndCodeSnippet
int main()
{
typedef float PixelType;
typedef itk::Mesh< PixelType, 3 > MeshType;
// Software Guide : BeginLatex
//
// In order to be consitent with the Mesh, cell types have to be configured
// with a number of custom types taken from the mesh traits. The set of
// traits relevant to cells are packaged by the Mesh class into the
// \code{CellType} trait. This trait needs to be passed to the actual cell
// types at the moment of their instantiation. The following line shows how
// to extract the Cell traits from the Mesh type.
//
// \index{itk::Mesh!CellType}
// \index{itk::Mesh!traits}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef MeshType::CellType CellType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The \code{itk::LineCell} type can now be instantiated using the traits
// taken from the Mesh. \index{itk::LineCell!Instantiation}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::LineCell< CellType > LineType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The main difference in the way cells and points are managed by the Mesh
// is that points are stored by copy on the PointsContainer while cells are
// stored in the CellsContainer using pointers. The reason for using
// pointers is that cells use C++ polymorphism on the mesh. This means that
// the mesh is only aware of having pointers to a generic cell which is the
// base class of all the specific cell types. This architecture makes
// possible to combine different cell types in the same mesh. Points, on the
// other hand, are of a single type and have a small memory footprint, which
// facilitates to copy them directly inside the container.
//
// \index{itk::Cell!CellAutoPointer}
// \index{itk::Mesh!CellAutoPointer}
// \index{CellAutoPointer}
// \index{itk::AutoPointer}
//
// Managing cells by pointers add another level of complexity to the Mesh
// since it is now necessary to stablish a protocol to make clear who is
// responsible for allocating and releasing the cells' memory. This protocol
// is implemented in the form of a specific type of pointer called the
// \code{CellAutoPointer}. This pointer differ in many senses from the
// SmartPointer. The CellAutoPointer has a internal pointer to the actual
// object and a boolean flag that indicates if the CellAutoPointer is
// responsible for releasing the cell memory whenever the time comes for its
// own destruction. It is said that a \code{CellAutoPointer} \emph{owns} the
// cell when it is responsible for its destruction. Many CellAutoPointer can
// point to the same cell but at any given time, only \textbf{one}
// CellAutoPointer can own the cell.
//
// The \code{CellAutoPointer} trait is defined in the MeshType and can be
// extracted as illustrated in the following line.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef CellType::CellAutoPointer CellAutoPointer;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Note that the CellAutoPointer is pointing to a generic cell type. It is
// not aware of the actual type of the cell, which can be for example
// LineCell, TriangleCell or TetrahedronCell. This fact will influence the
// way in which we access cells later on.
//
// At this point we can actually create a mesh and insert some points on it.
//
// \index{itk::Mesh!New()}
// \index{itk::Mesh!SetPoint()}
// \index{itk::Mesh!PointType}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
MeshType::Pointer mesh = MeshType::New();
MeshType::PointType p0;
MeshType::PointType p1;
MeshType::PointType p2;
p0[0] = -1.0; p0[1] = 0.0; p0[2] = 0.0;
p1[0] = 1.0; p1[1] = 0.0; p1[2] = 0.0;
p2[0] = 1.0; p2[1] = 1.0; p2[2] = 0.0;
mesh->SetPoint( 0, p0 );
mesh->SetPoint( 1, p1 );
mesh->SetPoint( 2, p2 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The following code creates two CellAutoPointers and initialize them with
// newly created cell objects. The actual cell type created in this case is
// \code{itk::LineCell}. Note that cells are created with the normal
// \code{new} C++ operator. The CellAutoPointer takes ownership of the
// received pointer by using the method \code{TakeOwnership()}. Even though
// this may seem verbose on the code, it results to be necessary to make
// more explicity from the code that the responsibility of memory release is
// assumed by the AutoPointer.
//
// \index{itk::AutoPointer!TakeOwnership()}
// \index{CellAutoPointer!TakeOwnership()}
// \index{CellType!creation}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
CellAutoPointer line0;
CellAutoPointer line1;
line0.TakeOwnership( new LineType );
line1.TakeOwnership( new LineType );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The LineCells should now be associated with points in the mesh. This is
// done using the identifiers assigned to points when they were inserted in
// the mesh. Every cell type has a specific number of points to be
// associated with. For example a \code{LineCell} requires two points, a
// \code{TriangleCell} requires three and a \code{TetrahedronCell} requires
// four. Cells use an internal numbering system for points. It is simple an
// index in the range $\{0,NumberOfPoints-1\}$. The association of points
// and cells is done by the \code{SetPointId()} method which requires the
// user to provide the internal index of the point in the cell and the
// corresponding pointIdentifier in the Mesh. The internal cell index is the
// first parameter of \code{SetPointId()} while the mesh point-identifier is
// the second.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
line0->SetPointId( 0, 0 ); // line between points 0 and 1
line0->SetPointId( 1, 1 );
line1->SetPointId( 0, 1 ); // line between points 1 and 2
line1->SetPointId( 1, 2 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Cells are inserted in the mesh using the \code{SetCell()} method. It
// requires an identifier and the AutoPointer to the cell. The Mesh will
// take ownership of the cell to which the AutoPointer is pointing. This is
// done internally by the \code{SetCell()} method. In this way, the
// destruction of the CellAutoPointer will not induce the destruction of the
// associated cell.
//
// \index{itk::Mesh!SetCell()}
// \index{SetCell()!itk::Mesh}
// \index{itk::Mesh!Inserting cells}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
mesh->SetCell( 0, line0 );
mesh->SetCell( 1, line1 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// After being argument of a \code{SetCell()} method, a CellAutoPointer no
// longer holds ownership of the cells. It is important not to use this same
// CellAutoPointer again as argument to \code{SetCell()} without first
// securing ownership of another cell.
//
// Software Guide : EndLatex
std::cout << "Points = " << mesh->GetNumberOfPoints() << std::endl;
// Software Guide : BeginLatex
//
// The number of Cells currently inserted in the mesh can be queried with
// the \code{GetNumberOfCells()} method.
//
// \index{itk::Mesh!GetNumberOfCells()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
std::cout << "Cells = " << mesh->GetNumberOfCells() << std::endl;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// In a way analogous to points, cells can be accessed using Iterators to
// the CellsContainer in the mesh. The trait for the cell iterator can be
// extracted from the mesh and used to define a local type.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef MeshType::CellsContainer::Iterator CellIterator;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Then the iterators to the first and past-end cell in the mesh can be
// obtained respectively with the \code{Begin()} and \code{End()} methods of
// the CellsContainer. The CellsContainer of the mesh is returned by the
// \code{GetCells()} method.
//
// \index{itk::Mesh!Iterating cells}
// \index{itk::Mesh!GetCells()}
// \index{CellsContainer!Begin()}
// \index{CellsContainer!End()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
CellIterator cellIterator = mesh->GetCells()->Begin();
CellIterator end = mesh->GetCells()->End();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally a standard loop is used to iterate over all the cells. Note the
// use of the \code{Value()} method used to get the actual pointer to the
// cell from the CellIterator. Note also that the values returned are
// pointers to the generic CellType. These pointers have to be down-casted
// in order to be used as actual LineCell types. Safe down-casting is
// performed with the \code{dynamic\_cast} operator which will throw an
// exception if the convertion cannot be safely performed.
//
// \index{down casting}
// \index{CellIterator!Value()}
// \index{CellIterator!increment}
// \index{itk::Mesh!CellType casting}
// \index{Print()}
// \index{CellType!Print()}
// \index{CellType!GetNumberOfPoints()}
// \index{LineCell!Print()}
// \index{LineCell!GetNumberOfPoints()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
while( cellIterator != end ) {
MeshType::CellType * cellptr = cellIterator->Value();
LineType * line = dynamic_cast<LineType *>( cellptr );
std::cout << line->GetNumberOfPoints() << std::cout;
++cellIterator;
}
// Software Guide : EndCodeSnippet
return 0;
}
<commit_msg>FIX: Value() called with ->. and typo in cout.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: Mesh2.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginLatex
//
// A Mesh can contain a variety of cells types. Typical cells are the
// LineCell, TriangleCell, QuadrilateralCell and TetrahedronCell. A large
// flexibility is provided for managing cells at the price of a bit more of
// complexity than in the case of point management.
//
// The following code creates a polygonal line in order to illustrate the
// simplest case of cell management in a Mesh. The only cell type used here is
// the \code{itk::LineCell}. The header file of this class has to be included.
//
// \index{itk::LineCell!Header}
//
// Software Guide : EndLatex
#include "itkMesh.h"
// Software Guide : BeginCodeSnippet
#include "itkLineCell.h"
// Software Guide : EndCodeSnippet
int main()
{
typedef float PixelType;
typedef itk::Mesh< PixelType, 3 > MeshType;
// Software Guide : BeginLatex
//
// In order to be consitent with the Mesh, cell types have to be configured
// with a number of custom types taken from the mesh traits. The set of
// traits relevant to cells are packaged by the Mesh class into the
// \code{CellType} trait. This trait needs to be passed to the actual cell
// types at the moment of their instantiation. The following line shows how
// to extract the Cell traits from the Mesh type.
//
// \index{itk::Mesh!CellType}
// \index{itk::Mesh!traits}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef MeshType::CellType CellType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The \code{itk::LineCell} type can now be instantiated using the traits
// taken from the Mesh. \index{itk::LineCell!Instantiation}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::LineCell< CellType > LineType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The main difference in the way cells and points are managed by the Mesh
// is that points are stored by copy on the PointsContainer while cells are
// stored in the CellsContainer using pointers. The reason for using
// pointers is that cells use C++ polymorphism on the mesh. This means that
// the mesh is only aware of having pointers to a generic cell which is the
// base class of all the specific cell types. This architecture makes
// possible to combine different cell types in the same mesh. Points, on the
// other hand, are of a single type and have a small memory footprint, which
// facilitates to copy them directly inside the container.
//
// \index{itk::Cell!CellAutoPointer}
// \index{itk::Mesh!CellAutoPointer}
// \index{CellAutoPointer}
// \index{itk::AutoPointer}
//
// Managing cells by pointers add another level of complexity to the Mesh
// since it is now necessary to stablish a protocol to make clear who is
// responsible for allocating and releasing the cells' memory. This protocol
// is implemented in the form of a specific type of pointer called the
// \code{CellAutoPointer}. This pointer differ in many senses from the
// SmartPointer. The CellAutoPointer has a internal pointer to the actual
// object and a boolean flag that indicates if the CellAutoPointer is
// responsible for releasing the cell memory whenever the time comes for its
// own destruction. It is said that a \code{CellAutoPointer} \emph{owns} the
// cell when it is responsible for its destruction. Many CellAutoPointer can
// point to the same cell but at any given time, only \textbf{one}
// CellAutoPointer can own the cell.
//
// The \code{CellAutoPointer} trait is defined in the MeshType and can be
// extracted as illustrated in the following line.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef CellType::CellAutoPointer CellAutoPointer;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Note that the CellAutoPointer is pointing to a generic cell type. It is
// not aware of the actual type of the cell, which can be for example
// LineCell, TriangleCell or TetrahedronCell. This fact will influence the
// way in which we access cells later on.
//
// At this point we can actually create a mesh and insert some points on it.
//
// \index{itk::Mesh!New()}
// \index{itk::Mesh!SetPoint()}
// \index{itk::Mesh!PointType}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
MeshType::Pointer mesh = MeshType::New();
MeshType::PointType p0;
MeshType::PointType p1;
MeshType::PointType p2;
p0[0] = -1.0; p0[1] = 0.0; p0[2] = 0.0;
p1[0] = 1.0; p1[1] = 0.0; p1[2] = 0.0;
p2[0] = 1.0; p2[1] = 1.0; p2[2] = 0.0;
mesh->SetPoint( 0, p0 );
mesh->SetPoint( 1, p1 );
mesh->SetPoint( 2, p2 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The following code creates two CellAutoPointers and initialize them with
// newly created cell objects. The actual cell type created in this case is
// \code{itk::LineCell}. Note that cells are created with the normal
// \code{new} C++ operator. The CellAutoPointer takes ownership of the
// received pointer by using the method \code{TakeOwnership()}. Even though
// this may seem verbose on the code, it results to be necessary to make
// more explicity from the code that the responsibility of memory release is
// assumed by the AutoPointer.
//
// \index{itk::AutoPointer!TakeOwnership()}
// \index{CellAutoPointer!TakeOwnership()}
// \index{CellType!creation}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
CellAutoPointer line0;
CellAutoPointer line1;
line0.TakeOwnership( new LineType );
line1.TakeOwnership( new LineType );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The LineCells should now be associated with points in the mesh. This is
// done using the identifiers assigned to points when they were inserted in
// the mesh. Every cell type has a specific number of points to be
// associated with. For example a \code{LineCell} requires two points, a
// \code{TriangleCell} requires three and a \code{TetrahedronCell} requires
// four. Cells use an internal numbering system for points. It is simple an
// index in the range $\{0,NumberOfPoints-1\}$. The association of points
// and cells is done by the \code{SetPointId()} method which requires the
// user to provide the internal index of the point in the cell and the
// corresponding pointIdentifier in the Mesh. The internal cell index is the
// first parameter of \code{SetPointId()} while the mesh point-identifier is
// the second.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
line0->SetPointId( 0, 0 ); // line between points 0 and 1
line0->SetPointId( 1, 1 );
line1->SetPointId( 0, 1 ); // line between points 1 and 2
line1->SetPointId( 1, 2 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Cells are inserted in the mesh using the \code{SetCell()} method. It
// requires an identifier and the AutoPointer to the cell. The Mesh will
// take ownership of the cell to which the AutoPointer is pointing. This is
// done internally by the \code{SetCell()} method. In this way, the
// destruction of the CellAutoPointer will not induce the destruction of the
// associated cell.
//
// \index{itk::Mesh!SetCell()}
// \index{SetCell()!itk::Mesh}
// \index{itk::Mesh!Inserting cells}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
mesh->SetCell( 0, line0 );
mesh->SetCell( 1, line1 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// After being argument of a \code{SetCell()} method, a CellAutoPointer no
// longer holds ownership of the cells. It is important not to use this same
// CellAutoPointer again as argument to \code{SetCell()} without first
// securing ownership of another cell.
//
// Software Guide : EndLatex
std::cout << "Points = " << mesh->GetNumberOfPoints() << std::endl;
// Software Guide : BeginLatex
//
// The number of Cells currently inserted in the mesh can be queried with
// the \code{GetNumberOfCells()} method.
//
// \index{itk::Mesh!GetNumberOfCells()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
std::cout << "Cells = " << mesh->GetNumberOfCells() << std::endl;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// In a way analogous to points, cells can be accessed using Iterators to
// the CellsContainer in the mesh. The trait for the cell iterator can be
// extracted from the mesh and used to define a local type.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef MeshType::CellsContainer::Iterator CellIterator;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Then the iterators to the first and past-end cell in the mesh can be
// obtained respectively with the \code{Begin()} and \code{End()} methods of
// the CellsContainer. The CellsContainer of the mesh is returned by the
// \code{GetCells()} method.
//
// \index{itk::Mesh!Iterating cells}
// \index{itk::Mesh!GetCells()}
// \index{CellsContainer!Begin()}
// \index{CellsContainer!End()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
CellIterator cellIterator = mesh->GetCells()->Begin();
CellIterator end = mesh->GetCells()->End();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally a standard loop is used to iterate over all the cells. Note the
// use of the \code{Value()} method used to get the actual pointer to the
// cell from the CellIterator. Note also that the values returned are
// pointers to the generic CellType. These pointers have to be down-casted
// in order to be used as actual LineCell types. Safe down-casting is
// performed with the \code{dynamic\_cast} operator which will throw an
// exception if the convertion cannot be safely performed.
//
// \index{down casting}
// \index{CellIterator!Value()}
// \index{CellIterator!increment}
// \index{itk::Mesh!CellType casting}
// \index{Print()}
// \index{CellType!Print()}
// \index{CellType!GetNumberOfPoints()}
// \index{LineCell!Print()}
// \index{LineCell!GetNumberOfPoints()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
while( cellIterator != end ) {
MeshType::CellType * cellptr = cellIterator.Value();
LineType * line = dynamic_cast<LineType *>( cellptr );
std::cout << line->GetNumberOfPoints() << std::endl;
++cellIterator;
}
// Software Guide : EndCodeSnippet
return 0;
}
<|endoftext|> |
<commit_before>//******************************************************************************
// FILE : function_variable_value_specific.cpp
//
// LAST MODIFIED : 15 July 2004
//
// DESCRIPTION :
//==============================================================================
// global classes
// ==============
// template class Function_variable_value_specific
// ===============================================
EXPORT template<typename Value_type>
Function_variable_value_specific<Value_type>::
Function_variable_value_specific<Value_type>(
bool (*set_function)(Value_type&,const Function_variable_handle)):
set_function(set_function){};
EXPORT template<typename Value_type>
Function_variable_value_specific<Value_type>::
~Function_variable_value_specific<Value_type>(){}
EXPORT template<typename Value_type>
const std::string Function_variable_value_specific<Value_type>::type()
{
return (type_string);
}
EXPORT template<typename Value_type>
bool Function_variable_value_specific<Value_type>::set(Value_type& value,
const Function_variable_handle variable)
{
bool result;
result=false;
if (set_function)
{
result=(*set_function)(value,variable);
}
return (result);
}
<commit_msg>Sorting out templates<commit_after>//******************************************************************************
// FILE : function_variable_value_specific.cpp
//
// LAST MODIFIED : 15 July 2004
//
// DESCRIPTION :
//==============================================================================
// global classes
// ==============
// template class Function_variable_value_specific
// ===============================================
EXPORT template<typename Value_type>
Function_variable_value_specific<Value_type>::
Function_variable_value_specific(
bool (*set_function)(Value_type&,const Function_variable_handle)):
set_function(set_function){};
EXPORT template<typename Value_type>
Function_variable_value_specific<Value_type>::
~Function_variable_value_specific<Value_type>(){}
EXPORT template<typename Value_type>
const std::string Function_variable_value_specific<Value_type>::type()
{
return (type_string);
}
EXPORT template<typename Value_type>
bool Function_variable_value_specific<Value_type>::set(Value_type& value,
const Function_variable_handle variable)
{
bool result;
result=false;
if (set_function)
{
result=(*set_function)(value,variable);
}
return (result);
}
<|endoftext|> |
<commit_before><commit_msg>Fixed bug preventing gallery apps from being autoupdated/synced.<commit_after><|endoftext|> |
<commit_before>// tag::C++11check[]
#define STRING2(x) #x
#define STRING(x) STRING2(x)
#if __cplusplus < 201103L
#pragma message("WARNING: the compiler may not be C++11 compliant. __cplusplus version is : " STRING(__cplusplus))
#endif
// end::C++11check[]
// tag::includes[]
#include <iostream>
#include <vector>
#include <algorithm>
#include <GL/glew.h>
#include <SDL.h>
// end::includes[]
// tag::namespace[]
using namespace std;
// end::namespace[]
// tag::globalVariables[]
std::string exeName;
SDL_Window *win; //pointer to the SDL_Window
SDL_GLContext context; //the SDL_GLContext
int frameCount = 0;
std::string frameLine = "";
// end::globalVariables[]
// tag::vertexShader[]
//string holding the **source** of our vertex shader, to save loading from a file
const std::string strVertexShader = R"(
#version 330
in vec2 position;
uniform vec2 offset;
void main()
{
vec2 tmpPosition = position + offset;
gl_Position = vec4(tmpPosition, 0.0, 1.0);
}
)";
// end::vertexShader[]
// tag::fragmentShader[]
//string holding the **source** of our fragment shader, to save loading from a file
const std::string strFragmentShader = R"(
#version 330
out vec4 outputColor;
void main()
{
outputColor = vec4(1.0f, 1.0f, 1.0f, 1.0f);
}
)";
// end::fragmentShader[]
//our variables
bool done = false;
//the data about our geometry
const GLfloat vertexData[] = {
0.000f, 0.500f,
-0.433f, -0.250f,
0.433f, -0.250f,
};
//the offset we'll pass to the GLSL
GLfloat offset[] = { -0.5, -0.5 }; //using different values from CPU and static GLSL examples, to make it clear this is working
GLfloat offsetVelocity[] = { 0.2, 0.2 }; //rate of change of offset in units per second
//our GL and GLSL variables
GLuint theProgram; //GLuint that we'll fill in to refer to the GLSL program (only have 1 at this point)
GLint positionLocation; //GLuint that we'll fill in with the location of the `offset` variable in the GLSL
GLint offsetLocation; //GLuint that we'll fill in with the location of the `offset` variable in the GLSL
GLuint vertexDataBufferObject;
GLuint vertexArrayObject;
// end Global Variables
/////////////////////////
void initialise()
{
if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
exit(1);
}
cout << "SDL initialised OK!\n";
}
void createWindow()
{
//get executable name, and use as window title
int beginIdxWindows = exeName.rfind("\\"); //find last occurrence of a backslash
int beginIdxLinux = exeName.rfind("/"); //find last occurrence of a forward slash
int beginIdx = max(beginIdxWindows, beginIdxLinux);
std::string exeNameEnd = exeName.substr(beginIdx + 1);
const char *exeNameCStr = exeNameEnd.c_str();
//create window
win = SDL_CreateWindow(exeNameCStr, 100, 100, 600, 600, SDL_WINDOW_OPENGL); //same height and width makes the window square ...
//error handling
if (win == nullptr)
{
std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
SDL_Quit();
exit(1);
}
cout << "SDL CreatedWindow OK!\n";
}
void setGLAttributes()
{
int major = 3;
int minor = 3;
cout << "Built for OpenGL Version " << major << "." << minor << endl; //ahttps://en.wikipedia.org/wiki/OpenGL_Shading_Language#Versions
// set the opengl context version
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, major);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minor);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); //core profile
cout << "Set OpenGL context to versicreate remote branchon " << major << "." << minor << " OK!\n";
}
void createContext()
{
setGLAttributes();
context = SDL_GL_CreateContext(win);
if (context == nullptr){
SDL_DestroyWindow(win);
std::cout << "SDL_GL_CreateContext Error: " << SDL_GetError() << std::endl;
SDL_Quit();
exit(1);
}
cout << "Created OpenGL context OK!\n";
}
void initGlew()
{
GLenum rev;
glewExperimental = GL_TRUE; //GLEW isn't perfect - see https://www.opengl.org/wiki/OpenGL_Loading_Library#GLEW
rev = glewInit();
if (GLEW_OK != rev){
std::cout << "GLEW Error: " << glewGetErrorString(rev) << std::endl;
SDL_Quit();
exit(1);
}
else {
cout << "GLEW Init OK!\n";
}
}
GLuint createShader(GLenum eShaderType, const std::string &strShaderFile)
{
GLuint shader = glCreateShader(eShaderType);
//error check
const char *strFileData = strShaderFile.c_str();
glShaderSource(shader, 1, &strFileData, NULL);
glCompileShader(shader);
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE)
{
GLint infoLogLength;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar *strInfoLog = new GLchar[infoLogLength + 1];
glGetShaderInfoLog(shader, infoLogLength, NULL, strInfoLog);
const char *strShaderType = NULL;
switch (eShaderType)
{
case GL_VERTEX_SHADER: strShaderType = "vertex"; break;
case GL_GEOMETRY_SHADER: strShaderType = "geometry"; break;
case GL_FRAGMENT_SHADER: strShaderType = "fragment"; break;
}
fprintf(stderr, "Compile failure in %s shader:\n%s\n", strShaderType, strInfoLog);
delete[] strInfoLog;
}
return shader;
}
GLuint createProgram(const std::vector<GLuint> &shaderList)
{
GLuint program = glCreateProgram();
for (size_t iLoop = 0; iLoop < shaderList.size(); iLoop++)
glAttachShader(program, shaderList[iLoop]);
glLinkProgram(program);
GLint status;
glGetProgramiv(program, GL_LINK_STATUS, &status);
if (status == GL_FALSE)
{
GLint infoLogLength;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar *strInfoLog = new GLchar[infoLogLength + 1];
glGetProgramInfoLog(program, infoLogLength, NULL, strInfoLog);
fprintf(stderr, "Linker failure: %s\n", strInfoLog);
delete[] strInfoLog;
}
for (size_t iLoop = 0; iLoop < shaderList.size(); iLoop++)
glDetachShader(program, shaderList[iLoop]);
return program;
}
void initializeProgram()
{
std::vector<GLuint> shaderList;
shaderList.push_back(createShader(GL_VERTEX_SHADER, strVertexShader));
shaderList.push_back(createShader(GL_FRAGMENT_SHADER, strFragmentShader));
theProgram = createProgram(shaderList);
if (theProgram == 0)
{
cout << "GLSL program creation error." << std::endl;
SDL_Quit();
exit(1);
}
else {
cout << "GLSL program creation OK! GLUint is: " << theProgram << std::endl;
}
positionLocation = glGetAttribLocation(theProgram, "position");
offsetLocation = glGetUniformLocation(theProgram, "offset");
//clean up shaders (we don't need them anymore as they are no in theProgram
for_each(shaderList.begin(), shaderList.end(), glDeleteShader);
}
void initializeVertexBuffer()
{
glGenBuffers(1, &vertexDataBufferObject);
glBindBuffer(GL_ARRAY_BUFFER, vertexDataBufferObject);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
cout << "vertexDataBufferObject created OK! GLUint is: " << vertexDataBufferObject << std::endl;
}
void loadAssets()
{
initializeProgram(); //create GLSL Shaders, link into a GLSL program, and get IDs of attributes and variables
initializeVertexBuffer(); //load data into a vertex buffer
cout << "Loaded Assets OK!\n";
}
void setupvertexArrayObject()
{
glGenVertexArrays(1, &vertexArrayObject); //create a Vertex Array Object
cout << "Vertex Array Object created OK! GLUint is: " << vertexArrayObject << std::endl;
glBindVertexArray(vertexArrayObject); //make the just created vertexArrayObject the active one
glBindBuffer(GL_ARRAY_BUFFER, vertexDataBufferObject); //bind vertexDataBufferObject
glEnableVertexAttribArray(positionLocation); //enable attribute at index positionLocation
glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, 0); //specify that position data contains four floats per vertex, and goes into attribute index positionLocation
glBindVertexArray(0); //unbind the vertexArrayObject so we can't change it
//cleanup
glDisableVertexAttribArray(positionLocation); //disable vertex attribute at index positionLocation
glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind array buffer
}
void handleInput()
{
//Event-based input handling
//The underlying OS is event-based, so **each** key-up or key-down (for example)
//generates an event.
// - https://wiki.libsdl.org/SDL_PollEvent
//In some scenarios we want to catch **ALL** the events, not just to present state
// - for instance, if taking keyboard input the user might key-down two keys during a frame
// - we want to catch based, and know the order
// - or the user might key-down and key-up the same within a frame, and we still want something to happen (e.g. jump)
// - the alternative is to Poll the current state with SDL_GetKeyboardState
SDL_Event event; //somewhere to store an event
//NOTE: there may be multiple events per frame
while (SDL_PollEvent(&event)) //loop until SDL_PollEvent returns 0 (meaning no more events)
{
switch (event.type)
{
case SDL_QUIT:
done = true; //set donecreate remote branch flag if SDL wants to quit (i.e. if the OS has triggered a close event,
// - such as window close, or SIGINT
break;
//keydown handling - we should to the opposite on key-up for direction controls (generally)
case SDL_KEYDOWN:
//Keydown can fire repeatable if key-repeat is on.
// - the repeat flag is set on the keyboard event, if this is a repeat event
// - in our case, we're going to ignore repeat events
// - https://wiki.libsdl.org/SDL_KeyboardEvent
if (!event.key.repeat)
switch (event.key.keysym.sym)
{
//hit escape to exit
case SDLK_ESCAPE: done = true;
}
break;
}
}
}
void updateSimulation(double simLength) //update simulation with an amount of time to simulate for (in seconds)
{
//CHANGE ME
}
void preRender()
{
glViewport(0, 0, 600, 600); //set viewpoint
glClearColor(1.0f, 0.0f, 0.0f, 1.0f); //set clear colour
glClear(GL_COLOR_BUFFER_BIT); //clear the window (technical the scissor box bounds)
}
void render()
{
glUseProgram(theProgram); //installs the program object specified by program as part of current rendering state
//load data to GLSL that **may** have changed
glUniform2f(offsetLocation, offset[0], offset[1]);
//alternatively, use glUnivform2fv
//glUniform2fv(offsetLocation, 1, offset); //Note: the count is 1, because we are setting a single uniform vec2 - https://www.opengl.org/wiki/GLSL_:_common_mistakes#How_to_use_glUniform
glBindVertexArray(vertexArrayObject);
glDrawArrays(GL_TRIANGLES, 0, 3); //Draw something, using Triangles, and 3 vertices - i.e. one lonely triangle
glBindVertexArray(0);
glUseProgram(0); //clean up
}
void postRender()
{
SDL_GL_SwapWindow(win);; //present the frame buffer to the display (swapBuffers)
frameLine += "Frame: " + std::to_string(frameCount++);
cout << "\r" << frameLine << std::flush;
frameLine = "";
}
void cleanUp()
{
SDL_GL_DeleteContext(context);
SDL_DestroyWindow(win);
cout << "Cleaning up OK!\n";
}
int main( int argc, char* args[] )
{
exeName = args[0];
//setup
//- do just once
initialise();
createWindow();
createContext();
initGlew();
glViewport(0,0,600,600); //should check what the actual window res is?
SDL_GL_SwapWindow(win); //force a swap, to make the trace clearer
//do stuff that only needs to happen once
//- create shaders
//- load vertex data
loadAssets();
//setup a GL object (a VertexArrayObject) that stores how to access data and from where
setupvertexArrayObject();
while (!done) //loop until done flag is set)
{
handleInput();
updateSimulation(0.02); //call update simulation with an amount of time to simulate for (in seconds)
//WARNING - we are always updating by a constant amount of time. This should be tied to how long has elapsed
// see, for example, http://headerphile.blogspot.co.uk/2014/07/part-9-no-more-delays.html
preRender();
render(); //RENDER HERE - PLACEHOLDER
postRender();
}
//cleanup and exit
cleanUp();
SDL_Quit();
return 0;
}
<commit_msg>include string - needed on windows<commit_after>// tag::C++11check[]
#define STRING2(x) #x
#define STRING(x) STRING2(x)
#if __cplusplus < 201103L
#pragma message("WARNING: the compiler may not be C++11 compliant. __cplusplus version is : " STRING(__cplusplus))
#endif
// end::C++11check[]
// tag::includes[]
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <GL/glew.h>
#include <SDL.h>
// end::includes[]
// tag::namespace[]
using namespace std;
// end::namespace[]
// tag::globalVariables[]
std::string exeName;
SDL_Window *win; //pointer to the SDL_Window
SDL_GLContext context; //the SDL_GLContext
int frameCount = 0;
std::string frameLine = "";
// end::globalVariables[]
// tag::vertexShader[]
//string holding the **source** of our vertex shader, to save loading from a file
const std::string strVertexShader = R"(
#version 330
in vec2 position;
uniform vec2 offset;
void main()
{
vec2 tmpPosition = position + offset;
gl_Position = vec4(tmpPosition, 0.0, 1.0);
}
)";
// end::vertexShader[]
// tag::fragmentShader[]
//string holding the **source** of our fragment shader, to save loading from a file
const std::string strFragmentShader = R"(
#version 330
out vec4 outputColor;
void main()
{
outputColor = vec4(1.0f, 1.0f, 1.0f, 1.0f);
}
)";
// end::fragmentShader[]
//our variables
bool done = false;
//the data about our geometry
const GLfloat vertexData[] = {
0.000f, 0.500f,
-0.433f, -0.250f,
0.433f, -0.250f,
};
//the offset we'll pass to the GLSL
GLfloat offset[] = { -0.5, -0.5 }; //using different values from CPU and static GLSL examples, to make it clear this is working
GLfloat offsetVelocity[] = { 0.2, 0.2 }; //rate of change of offset in units per second
//our GL and GLSL variables
GLuint theProgram; //GLuint that we'll fill in to refer to the GLSL program (only have 1 at this point)
GLint positionLocation; //GLuint that we'll fill in with the location of the `offset` variable in the GLSL
GLint offsetLocation; //GLuint that we'll fill in with the location of the `offset` variable in the GLSL
GLuint vertexDataBufferObject;
GLuint vertexArrayObject;
// end Global Variables
/////////////////////////
void initialise()
{
if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
exit(1);
}
cout << "SDL initialised OK!\n";
}
void createWindow()
{
//get executable name, and use as window title
int beginIdxWindows = exeName.rfind("\\"); //find last occurrence of a backslash
int beginIdxLinux = exeName.rfind("/"); //find last occurrence of a forward slash
int beginIdx = max(beginIdxWindows, beginIdxLinux);
std::string exeNameEnd = exeName.substr(beginIdx + 1);
const char *exeNameCStr = exeNameEnd.c_str();
//create window
win = SDL_CreateWindow(exeNameCStr, 100, 100, 600, 600, SDL_WINDOW_OPENGL); //same height and width makes the window square ...
//error handling
if (win == nullptr)
{
std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
SDL_Quit();
exit(1);
}
cout << "SDL CreatedWindow OK!\n";
}
void setGLAttributes()
{
int major = 3;
int minor = 3;
cout << "Built for OpenGL Version " << major << "." << minor << endl; //ahttps://en.wikipedia.org/wiki/OpenGL_Shading_Language#Versions
// set the opengl context version
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, major);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minor);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); //core profile
cout << "Set OpenGL context to versicreate remote branchon " << major << "." << minor << " OK!\n";
}
void createContext()
{
setGLAttributes();
context = SDL_GL_CreateContext(win);
if (context == nullptr){
SDL_DestroyWindow(win);
std::cout << "SDL_GL_CreateContext Error: " << SDL_GetError() << std::endl;
SDL_Quit();
exit(1);
}
cout << "Created OpenGL context OK!\n";
}
void initGlew()
{
GLenum rev;
glewExperimental = GL_TRUE; //GLEW isn't perfect - see https://www.opengl.org/wiki/OpenGL_Loading_Library#GLEW
rev = glewInit();
if (GLEW_OK != rev){
std::cout << "GLEW Error: " << glewGetErrorString(rev) << std::endl;
SDL_Quit();
exit(1);
}
else {
cout << "GLEW Init OK!\n";
}
}
GLuint createShader(GLenum eShaderType, const std::string &strShaderFile)
{
GLuint shader = glCreateShader(eShaderType);
//error check
const char *strFileData = strShaderFile.c_str();
glShaderSource(shader, 1, &strFileData, NULL);
glCompileShader(shader);
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE)
{
GLint infoLogLength;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar *strInfoLog = new GLchar[infoLogLength + 1];
glGetShaderInfoLog(shader, infoLogLength, NULL, strInfoLog);
const char *strShaderType = NULL;
switch (eShaderType)
{
case GL_VERTEX_SHADER: strShaderType = "vertex"; break;
case GL_GEOMETRY_SHADER: strShaderType = "geometry"; break;
case GL_FRAGMENT_SHADER: strShaderType = "fragment"; break;
}
fprintf(stderr, "Compile failure in %s shader:\n%s\n", strShaderType, strInfoLog);
delete[] strInfoLog;
}
return shader;
}
GLuint createProgram(const std::vector<GLuint> &shaderList)
{
GLuint program = glCreateProgram();
for (size_t iLoop = 0; iLoop < shaderList.size(); iLoop++)
glAttachShader(program, shaderList[iLoop]);
glLinkProgram(program);
GLint status;
glGetProgramiv(program, GL_LINK_STATUS, &status);
if (status == GL_FALSE)
{
GLint infoLogLength;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar *strInfoLog = new GLchar[infoLogLength + 1];
glGetProgramInfoLog(program, infoLogLength, NULL, strInfoLog);
fprintf(stderr, "Linker failure: %s\n", strInfoLog);
delete[] strInfoLog;
}
for (size_t iLoop = 0; iLoop < shaderList.size(); iLoop++)
glDetachShader(program, shaderList[iLoop]);
return program;
}
void initializeProgram()
{
std::vector<GLuint> shaderList;
shaderList.push_back(createShader(GL_VERTEX_SHADER, strVertexShader));
shaderList.push_back(createShader(GL_FRAGMENT_SHADER, strFragmentShader));
theProgram = createProgram(shaderList);
if (theProgram == 0)
{
cout << "GLSL program creation error." << std::endl;
SDL_Quit();
exit(1);
}
else {
cout << "GLSL program creation OK! GLUint is: " << theProgram << std::endl;
}
positionLocation = glGetAttribLocation(theProgram, "position");
offsetLocation = glGetUniformLocation(theProgram, "offset");
//clean up shaders (we don't need them anymore as they are no in theProgram
for_each(shaderList.begin(), shaderList.end(), glDeleteShader);
}
void initializeVertexBuffer()
{
glGenBuffers(1, &vertexDataBufferObject);
glBindBuffer(GL_ARRAY_BUFFER, vertexDataBufferObject);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
cout << "vertexDataBufferObject created OK! GLUint is: " << vertexDataBufferObject << std::endl;
}
void loadAssets()
{
initializeProgram(); //create GLSL Shaders, link into a GLSL program, and get IDs of attributes and variables
initializeVertexBuffer(); //load data into a vertex buffer
cout << "Loaded Assets OK!\n";
}
void setupvertexArrayObject()
{
glGenVertexArrays(1, &vertexArrayObject); //create a Vertex Array Object
cout << "Vertex Array Object created OK! GLUint is: " << vertexArrayObject << std::endl;
glBindVertexArray(vertexArrayObject); //make the just created vertexArrayObject the active one
glBindBuffer(GL_ARRAY_BUFFER, vertexDataBufferObject); //bind vertexDataBufferObject
glEnableVertexAttribArray(positionLocation); //enable attribute at index positionLocation
glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, 0); //specify that position data contains four floats per vertex, and goes into attribute index positionLocation
glBindVertexArray(0); //unbind the vertexArrayObject so we can't change it
//cleanup
glDisableVertexAttribArray(positionLocation); //disable vertex attribute at index positionLocation
glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind array buffer
}
void handleInput()
{
//Event-based input handling
//The underlying OS is event-based, so **each** key-up or key-down (for example)
//generates an event.
// - https://wiki.libsdl.org/SDL_PollEvent
//In some scenarios we want to catch **ALL** the events, not just to present state
// - for instance, if taking keyboard input the user might key-down two keys during a frame
// - we want to catch based, and know the order
// - or the user might key-down and key-up the same within a frame, and we still want something to happen (e.g. jump)
// - the alternative is to Poll the current state with SDL_GetKeyboardState
SDL_Event event; //somewhere to store an event
//NOTE: there may be multiple events per frame
while (SDL_PollEvent(&event)) //loop until SDL_PollEvent returns 0 (meaning no more events)
{
switch (event.type)
{
case SDL_QUIT:
done = true; //set donecreate remote branch flag if SDL wants to quit (i.e. if the OS has triggered a close event,
// - such as window close, or SIGINT
break;
//keydown handling - we should to the opposite on key-up for direction controls (generally)
case SDL_KEYDOWN:
//Keydown can fire repeatable if key-repeat is on.
// - the repeat flag is set on the keyboard event, if this is a repeat event
// - in our case, we're going to ignore repeat events
// - https://wiki.libsdl.org/SDL_KeyboardEvent
if (!event.key.repeat)
switch (event.key.keysym.sym)
{
//hit escape to exit
case SDLK_ESCAPE: done = true;
}
break;
}
}
}
void updateSimulation(double simLength) //update simulation with an amount of time to simulate for (in seconds)
{
//CHANGE ME
}
void preRender()
{
glViewport(0, 0, 600, 600); //set viewpoint
glClearColor(1.0f, 0.0f, 0.0f, 1.0f); //set clear colour
glClear(GL_COLOR_BUFFER_BIT); //clear the window (technical the scissor box bounds)
}
void render()
{
glUseProgram(theProgram); //installs the program object specified by program as part of current rendering state
//load data to GLSL that **may** have changed
glUniform2f(offsetLocation, offset[0], offset[1]);
//alternatively, use glUnivform2fv
//glUniform2fv(offsetLocation, 1, offset); //Note: the count is 1, because we are setting a single uniform vec2 - https://www.opengl.org/wiki/GLSL_:_common_mistakes#How_to_use_glUniform
glBindVertexArray(vertexArrayObject);
glDrawArrays(GL_TRIANGLES, 0, 3); //Draw something, using Triangles, and 3 vertices - i.e. one lonely triangle
glBindVertexArray(0);
glUseProgram(0); //clean up
}
void postRender()
{
SDL_GL_SwapWindow(win);; //present the frame buffer to the display (swapBuffers)
frameLine += "Frame: " + std::to_string(frameCount++);
cout << "\r" << frameLine << std::flush;
frameLine = "";
}
void cleanUp()
{
SDL_GL_DeleteContext(context);
SDL_DestroyWindow(win);
cout << "Cleaning up OK!\n";
}
int main( int argc, char* args[] )
{
exeName = args[0];
//setup
//- do just once
initialise();
createWindow();
createContext();
initGlew();
glViewport(0,0,600,600); //should check what the actual window res is?
SDL_GL_SwapWindow(win); //force a swap, to make the trace clearer
//do stuff that only needs to happen once
//- create shaders
//- load vertex data
loadAssets();
//setup a GL object (a VertexArrayObject) that stores how to access data and from where
setupvertexArrayObject();
while (!done) //loop until done flag is set)
{
handleInput();
updateSimulation(0.02); //call update simulation with an amount of time to simulate for (in seconds)
//WARNING - we are always updating by a constant amount of time. This should be tied to how long has elapsed
// see, for example, http://headerphile.blogspot.co.uk/2014/07/part-9-no-more-delays.html
preRender();
render(); //RENDER HERE - PLACEHOLDER
postRender();
}
//cleanup and exit
cleanUp();
SDL_Quit();
return 0;
}
<|endoftext|> |
<commit_before>//---------------------------------------------------------------------------
//
// kPPP: A pppd front end for the KDE project
//
//---------------------------------------------------------------------------
//
// (c) 1997-1998 Bernd Johannes Wuebben <[email protected]>
// (c) 1997-1999 Mario Weilguni <[email protected]>
// (c) 1998-1999 Harri Porten <[email protected]>
//
// derived from Jay Painters "ezppp"
//
//---------------------------------------------------------------------------
//
// $Id$
//
//---------------------------------------------------------------------------
//
// This program is free software; you can redistribute it and-or
// modify it under the terms of the GNU Library 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 Library 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.
//
//---------------------------------------------------------------------------
#include <qcombobox.h>
#include <qlabel.h>
#include <kurllabel.h>
#include <qlayout.h>
#include <qlistview.h>
#include <qdir.h>
#include <qregexp.h>
#include <qwmatrix.h>
#include <qcheckbox.h>
#include <kdialog.h>
#include <kstandarddirs.h>
#include <klocale.h>
#include <kiconloader.h>
#include <krun.h>
#include "acctselect.h"
#include "pppdata.h"
AccountingSelector::AccountingSelector(QWidget *parent, bool _isnewaccount, const char *name)
: QWidget(parent, name),
isnewaccount(_isnewaccount)
{
QVBoxLayout *l1 = new QVBoxLayout(parent, 0, KDialog::spacingHint());
enable_accounting = new QCheckBox(i18n("&Enable accounting"), parent);
l1->addWidget(enable_accounting, 1);
connect(enable_accounting, SIGNAL(toggled(bool)), this, SLOT(enableItems(bool)));
// insert the tree widget
tl = new QListView(parent, "treewidget");
connect(tl, SIGNAL(selectionChanged(QListViewItem*)), this,
SLOT(slotSelectionChanged(QListViewItem*)));
tl->setMinimumSize(220, 200);
l1->addWidget(tl, 1);
KURLLabel *up = new KURLLabel(parent);
up->setText(i18n("Check for rule updates"));
up->setURL("http://devel-home.kde.org/~kppp/rules.html");
connect(up, SIGNAL(leftClickedURL(const QString&)), SLOT(openURL(const QString&)));
l1->addWidget(up, 1);
// label to display the currently selected ruleset
QHBoxLayout *l11 = new QHBoxLayout;
l1->addSpacing(10);
l1->addLayout(l11);
QLabel *lsel = new QLabel(i18n("Selected:"), parent);
selected = new QLabel(parent);
selected->setFrameStyle(QFrame::Sunken | QFrame::WinPanel);
selected->setLineWidth(1);
selected->setFixedHeight(selected->sizeHint().height() + 16);
l11->addWidget(lsel, 0);
l11->addSpacing(10);
l11->addWidget(selected, 1);
// volume accounting
l1->addStretch(1);
QHBoxLayout *l12 = new QHBoxLayout;
l1->addLayout(l12);
QLabel *usevol_l = new QLabel(i18n("Volume accounting:"), parent);
use_vol = new QComboBox(parent);
use_vol->insertItem(i18n("No Accounting"), 0);
use_vol->insertItem(i18n("Bytes In"), 1);
use_vol->insertItem(i18n("Bytes Out"), 2);
use_vol->insertItem(i18n("Bytes In & Out"), 3);
use_vol->setCurrentItem(gpppdata.VolAcctEnabled());
l12->addWidget(usevol_l);
l12->addWidget(use_vol);
// load the pmfolder pixmap from KDEdir
pmfolder = UserIcon("folder");
// scale the pixmap
if(pmfolder.width() > 0) {
QWMatrix wm;
wm.scale(16.0/pmfolder.width(), 16.0/pmfolder.width());
pmfolder = pmfolder.xForm(wm);
}
// load the pmfolder pixmap from KDEdir
pmfile = UserIcon("phone");
// scale the pixmap
if(pmfile.width() > 0) {
QWMatrix wm;
wm.scale(16.0/pmfile.width(), 16.0/pmfile.width());
pmfile = pmfile.xForm(wm);
}
enable_accounting->setChecked(gpppdata.AcctEnabled());
setupTreeWidget();
l1->activate();
}
QString AccountingSelector::fileNameToName(QString s) {
s.replace('_', " ");
return KURL::decode_string(s);
}
QString AccountingSelector::nameToFileName(QString s) {
s.replace(' ', "_");
return s;
}
QListViewItem *AccountingSelector::findByName(QString name)
{
QListViewItem *ch = tl->firstChild();
while(ch) {
if(ch->text(0) == name)
return ch;
ch = ch->nextSibling();
}
return 0;
}
void AccountingSelector::insertDir(QDir d, QListViewItem *root) {
QListViewItem* tli = 0;
// sanity check
if(!d.exists() || !d.isReadable())
return;
// set up filter
d.setNameFilter("*.rst");
d.setFilter(QDir::Files);
d.setSorting(QDir::Name);
// read the list of files
const QFileInfoList *list = d.entryInfoList();
QFileInfoListIterator it( *list );
QFileInfo *fi;
// traverse the list and insert into the widget
while((fi = it.current())) {
++it;
QString samename = fi->fileName();
QListViewItem *i = findByName(samename);
// skip this file if already in tree
if(i)
continue;
// check if this is the file we should mark
QString name = fileNameToName(fi->baseName(true));
if(root)
tli = new QListViewItem(root, name);
else
tli = new QListViewItem(tl, name);
tli->setPixmap(0, pmfile);
// check if this is the item we are searching for
// (only in "Edit"-mode, not in "New"-mode
if(!isnewaccount && !edit_s.isEmpty() &&
(edit_s == QString(fi->filePath()).right(edit_s.length()))) {
edit_item = tli;
}
}
// set up a filter for the directories
d.setFilter(QDir::Dirs);
d.setNameFilter("*");
const QFileInfoList *dlist = d.entryInfoList();
QFileInfoListIterator dit(*dlist);
while((fi = dit.current())) {
// skip "." and ".." directories
if(fi->fileName().left(1) != ".") {
// convert to human-readable name
QString name = fileNameToName(fi->fileName());
// if the tree already has an item with this name,
// skip creation and use this one, otherwise
// create a new entry
QListViewItem *i = findByName(name);
if(!i) {
QListViewItem* item;
if(root)
item = new QListViewItem(root, name);
else
item = new QListViewItem(tl, name);
item->setPixmap(0, pmfolder);
insertDir(QDir(fi->filePath()), item);
} else
insertDir(QDir(fi->filePath()), i);
}
++dit;
}
}
void AccountingSelector::setupTreeWidget() {
// search the item
edit_item = 0;
if(!isnewaccount) {
edit_s = gpppdata.accountingFile();
}
else
edit_s = "";
tl->addColumn( i18n("Available Rules") );
tl->setColumnWidth(0, 205);
tl->setRootIsDecorated(true);
// look in ~/.kde/share/apps/kppp/Rules and $KDEDIR/share/apps/kppp/Rules
QStringList dirs = KGlobal::dirs()->resourceDirs("appdata");
for (QStringList::ConstIterator it = dirs.begin();
it != dirs.end(); it++) {
insertDir(QDir((*it) + "Rules"), 0);
}
// when mode is "Edit", then hightlight the
// appropriate item
if(!isnewaccount && edit_item) {
tl->setSelected(edit_item, true);
tl->setOpen(edit_item->parent(), true);
tl->ensureItemVisible(edit_item);
}
enableItems(enable_accounting->isChecked());
}
void AccountingSelector::enableItems(bool enabled) {
tl->setEnabled(enabled);
if(!enabled || (!tl->currentItem()))
selected->setText(i18n("(none)"));
else {
QListViewItem* i = tl->currentItem();
QString s;
while(i) {
s = "/" + i->text(0) + s;
i = i->parent();
}
selected->setText(s.mid(1));
s += ".rst";
edit_s = nameToFileName(s);
}
}
void AccountingSelector::slotSelectionChanged(QListViewItem* i) {
if(!i || i->childCount())
return;
if(!enable_accounting->isChecked())
return;
enableItems(true);
}
bool AccountingSelector::save() {
if(enable_accounting->isChecked()) {
gpppdata.setAccountingFile(edit_s);
gpppdata.setAcctEnabled(true);
} else {
gpppdata.setAccountingFile("");
gpppdata.setAcctEnabled(false);
}
gpppdata.setVolAcctEnabled(use_vol->currentItem());
return true;
}
void AccountingSelector::openURL(const QString &url) {
new KRun( url );
}
#include "acctselect.moc"
<commit_msg>KURL(const QString&) fixes<commit_after>//---------------------------------------------------------------------------
//
// kPPP: A pppd front end for the KDE project
//
//---------------------------------------------------------------------------
//
// (c) 1997-1998 Bernd Johannes Wuebben <[email protected]>
// (c) 1997-1999 Mario Weilguni <[email protected]>
// (c) 1998-1999 Harri Porten <[email protected]>
//
// derived from Jay Painters "ezppp"
//
//---------------------------------------------------------------------------
//
// $Id$
//
//---------------------------------------------------------------------------
//
// This program is free software; you can redistribute it and-or
// modify it under the terms of the GNU Library 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 Library 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.
//
//---------------------------------------------------------------------------
#include <qcombobox.h>
#include <qlabel.h>
#include <kurllabel.h>
#include <qlayout.h>
#include <qlistview.h>
#include <qdir.h>
#include <qregexp.h>
#include <qwmatrix.h>
#include <qcheckbox.h>
#include <kdialog.h>
#include <kstandarddirs.h>
#include <klocale.h>
#include <kiconloader.h>
#include <krun.h>
#include "acctselect.h"
#include "pppdata.h"
AccountingSelector::AccountingSelector(QWidget *parent, bool _isnewaccount, const char *name)
: QWidget(parent, name),
isnewaccount(_isnewaccount)
{
QVBoxLayout *l1 = new QVBoxLayout(parent, 0, KDialog::spacingHint());
enable_accounting = new QCheckBox(i18n("&Enable accounting"), parent);
l1->addWidget(enable_accounting, 1);
connect(enable_accounting, SIGNAL(toggled(bool)), this, SLOT(enableItems(bool)));
// insert the tree widget
tl = new QListView(parent, "treewidget");
connect(tl, SIGNAL(selectionChanged(QListViewItem*)), this,
SLOT(slotSelectionChanged(QListViewItem*)));
tl->setMinimumSize(220, 200);
l1->addWidget(tl, 1);
KURLLabel *up = new KURLLabel(parent);
up->setText(i18n("Check for rule updates"));
up->setURL("http://devel-home.kde.org/~kppp/rules.html");
connect(up, SIGNAL(leftClickedURL(const QString&)), SLOT(openURL(const QString&)));
l1->addWidget(up, 1);
// label to display the currently selected ruleset
QHBoxLayout *l11 = new QHBoxLayout;
l1->addSpacing(10);
l1->addLayout(l11);
QLabel *lsel = new QLabel(i18n("Selected:"), parent);
selected = new QLabel(parent);
selected->setFrameStyle(QFrame::Sunken | QFrame::WinPanel);
selected->setLineWidth(1);
selected->setFixedHeight(selected->sizeHint().height() + 16);
l11->addWidget(lsel, 0);
l11->addSpacing(10);
l11->addWidget(selected, 1);
// volume accounting
l1->addStretch(1);
QHBoxLayout *l12 = new QHBoxLayout;
l1->addLayout(l12);
QLabel *usevol_l = new QLabel(i18n("Volume accounting:"), parent);
use_vol = new QComboBox(parent);
use_vol->insertItem(i18n("No Accounting"), 0);
use_vol->insertItem(i18n("Bytes In"), 1);
use_vol->insertItem(i18n("Bytes Out"), 2);
use_vol->insertItem(i18n("Bytes In & Out"), 3);
use_vol->setCurrentItem(gpppdata.VolAcctEnabled());
l12->addWidget(usevol_l);
l12->addWidget(use_vol);
// load the pmfolder pixmap from KDEdir
pmfolder = UserIcon("folder");
// scale the pixmap
if(pmfolder.width() > 0) {
QWMatrix wm;
wm.scale(16.0/pmfolder.width(), 16.0/pmfolder.width());
pmfolder = pmfolder.xForm(wm);
}
// load the pmfolder pixmap from KDEdir
pmfile = UserIcon("phone");
// scale the pixmap
if(pmfile.width() > 0) {
QWMatrix wm;
wm.scale(16.0/pmfile.width(), 16.0/pmfile.width());
pmfile = pmfile.xForm(wm);
}
enable_accounting->setChecked(gpppdata.AcctEnabled());
setupTreeWidget();
l1->activate();
}
QString AccountingSelector::fileNameToName(QString s) {
s.replace('_', " ");
return KURL::decode_string(s);
}
QString AccountingSelector::nameToFileName(QString s) {
s.replace(' ', "_");
return s;
}
QListViewItem *AccountingSelector::findByName(QString name)
{
QListViewItem *ch = tl->firstChild();
while(ch) {
if(ch->text(0) == name)
return ch;
ch = ch->nextSibling();
}
return 0;
}
void AccountingSelector::insertDir(QDir d, QListViewItem *root) {
QListViewItem* tli = 0;
// sanity check
if(!d.exists() || !d.isReadable())
return;
// set up filter
d.setNameFilter("*.rst");
d.setFilter(QDir::Files);
d.setSorting(QDir::Name);
// read the list of files
const QFileInfoList *list = d.entryInfoList();
QFileInfoListIterator it( *list );
QFileInfo *fi;
// traverse the list and insert into the widget
while((fi = it.current())) {
++it;
QString samename = fi->fileName();
QListViewItem *i = findByName(samename);
// skip this file if already in tree
if(i)
continue;
// check if this is the file we should mark
QString name = fileNameToName(fi->baseName(true));
if(root)
tli = new QListViewItem(root, name);
else
tli = new QListViewItem(tl, name);
tli->setPixmap(0, pmfile);
// check if this is the item we are searching for
// (only in "Edit"-mode, not in "New"-mode
if(!isnewaccount && !edit_s.isEmpty() &&
(edit_s == QString(fi->filePath()).right(edit_s.length()))) {
edit_item = tli;
}
}
// set up a filter for the directories
d.setFilter(QDir::Dirs);
d.setNameFilter("*");
const QFileInfoList *dlist = d.entryInfoList();
QFileInfoListIterator dit(*dlist);
while((fi = dit.current())) {
// skip "." and ".." directories
if(fi->fileName().left(1) != ".") {
// convert to human-readable name
QString name = fileNameToName(fi->fileName());
// if the tree already has an item with this name,
// skip creation and use this one, otherwise
// create a new entry
QListViewItem *i = findByName(name);
if(!i) {
QListViewItem* item;
if(root)
item = new QListViewItem(root, name);
else
item = new QListViewItem(tl, name);
item->setPixmap(0, pmfolder);
insertDir(QDir(fi->filePath()), item);
} else
insertDir(QDir(fi->filePath()), i);
}
++dit;
}
}
void AccountingSelector::setupTreeWidget() {
// search the item
edit_item = 0;
if(!isnewaccount) {
edit_s = gpppdata.accountingFile();
}
else
edit_s = "";
tl->addColumn( i18n("Available Rules") );
tl->setColumnWidth(0, 205);
tl->setRootIsDecorated(true);
// look in ~/.kde/share/apps/kppp/Rules and $KDEDIR/share/apps/kppp/Rules
QStringList dirs = KGlobal::dirs()->resourceDirs("appdata");
for (QStringList::ConstIterator it = dirs.begin();
it != dirs.end(); it++) {
insertDir(QDir((*it) + "Rules"), 0);
}
// when mode is "Edit", then hightlight the
// appropriate item
if(!isnewaccount && edit_item) {
tl->setSelected(edit_item, true);
tl->setOpen(edit_item->parent(), true);
tl->ensureItemVisible(edit_item);
}
enableItems(enable_accounting->isChecked());
}
void AccountingSelector::enableItems(bool enabled) {
tl->setEnabled(enabled);
if(!enabled || (!tl->currentItem()))
selected->setText(i18n("(none)"));
else {
QListViewItem* i = tl->currentItem();
QString s;
while(i) {
s = "/" + i->text(0) + s;
i = i->parent();
}
selected->setText(s.mid(1));
s += ".rst";
edit_s = nameToFileName(s);
}
}
void AccountingSelector::slotSelectionChanged(QListViewItem* i) {
if(!i || i->childCount())
return;
if(!enable_accounting->isChecked())
return;
enableItems(true);
}
bool AccountingSelector::save() {
if(enable_accounting->isChecked()) {
gpppdata.setAccountingFile(edit_s);
gpppdata.setAcctEnabled(true);
} else {
gpppdata.setAccountingFile("");
gpppdata.setAcctEnabled(false);
}
gpppdata.setVolAcctEnabled(use_vol->currentItem());
return true;
}
void AccountingSelector::openURL(const QString &url) {
new KRun( KURL( url ) );
}
#include "acctselect.moc"
<|endoftext|> |
<commit_before>#include <CompositeTransformation.h>
#include <EventTypeHelpers.h>
#include <MetaEvent.h>
#include <IO.h>
#include <boost/graph/depth_first_search.hpp>
#include <boost/graph/copy.hpp>
#include <boost/graph/transpose_graph.hpp>
#include <boost/graph/graphviz.hpp>
#include <algorithm>
#include <iterator>
using namespace std;
using namespace boost;
struct CompositeTransformer : public Transformer {
using TransPtr = Transformation::TransPtr;
using Graph = adjacency_list<vecS, vecS, bidirectionalS, TransPtr>;
using Vertex= Graph::vertex_descriptor;
using Edge= Graph::edge_descriptor;
Graph graph;
/** \brief Generate CompositeTransformer from CompositeTransformation
* \param out output EventType of the created MetaEvents
* \param in input EventTypes of the consumed MetaEvents
* \param g CompositeTransformation graph to generate Transformers from
**/
CompositeTransformer(const EventType& out, const EventTypes& in, const CompositeTransformation::Graph& g)
: Transformer(Transformation::invalid, out, in) {
auto vertexCopy = [&g, this](CompositeTransformation::Vertex in, Vertex out) {
graph[out] = g[in].create();
};
auto edgeCopy = [&g, this](CompositeTransformation::Graph::edge_descriptor in, Edge out) {};
Graph temp;
transpose_graph(g, graph, boost::vertex_copy(vertexCopy).edge_copy(edgeCopy));
}
/** \brief check for applicability of Transformer
* \param events input events to check
* \return true if transformer can be applied, false otherwise
* \todo implement **/
bool check(const Events& events) const {
return false;
}
/** \brief execute transformer on input events
* \param events input events
* \return result of the transformer graph
* \todo implement
**/
MetaEvent operator()(const Events& events) {
return MetaEvent();
}
/** \brief print composite transformer
* \param o output stream to print to
**/
void print(std::ostream& o) const {
auto writeVertex = [this](ostream& o, Vertex v){
TransPtr t = graph[v];
if(t)
o << " [label=\"" << *t << "\"]";
else
o << " [label=\"nullptr\"]";
};
write_graphviz(o, graph, writeVertex);
}
};
using Graph = CompositeTransformation::Graph;
using Vertex = CompositeTransformation::Vertex;
using VertexResult = CompositeTransformation::VertexResult;
using VertexList = CompositeTransformation::VertexList;
using Edge = Graph::edge_descriptor;
using EventTypes = CompositeTransformation::EventTypes;
using EventIDs = CompositeTransformation::EventIDs;
using TransPtr = CompositeTransformation::TransPtr;
using TransList = CompositeTransformation::TransList;
struct InputEventTypeExtractor : public boost::default_dfs_visitor {
Vertex temp;
EventTypes& in;
InputEventTypeExtractor(EventTypes& in)
: in(in)
{}
void discover_vertex(Vertex v, const Graph& g) {
temp = v;
}
void finish_vertex(Vertex v, const Graph& g) {
if(temp == v) {
const EventTypes& tempIn = g[v].in();
copy(tempIn.begin(), tempIn.end(), back_inserter(in));
}
}
};
struct FindEventType : public boost::default_dfs_visitor {
VertexList& result;
const EventType& eT;
FindEventType(const EventType& eT, VertexList& result)
: result(result), eT(eT)
{}
void discover_vertex(Vertex v, const Graph& g) {
if(count(g[v].in().begin(), g[v].in().end(), eT))
result.push_back(v);
}
};
;
CompositeTransformation::CompositeTransformation(TransformationPtr tPtr, const EventType& goal,
const EventType& provided) {
VertexResult res = addRootTransformation(tPtr, goal, provided);
if(res.second)
mRoot = res.first;
}
TransPtr CompositeTransformation::create() const {
if(boost::num_vertices(mGraph)==1) {
return mGraph[mRoot].create();
}
return TransPtr(new CompositeTransformer(mOut, mIn, mGraph));
}
bool CompositeTransformation::check() const {
return boost::num_vertices(mGraph);
}
VertexResult CompositeTransformation::addRootTransformation(TransformationPtr tPtr, const EventType& tempGoal,
const EventType& provided) {
if(num_vertices(mGraph)==0) {
Vertex root = boost::add_vertex(mGraph);
ConfiguredTransformation& cT = mGraph[root];
cT.trans(tPtr);
cT.out(tempGoal);
if(provided==EventType())
cT.in(tPtr->in(tempGoal));
else
cT.in(tPtr->in(tempGoal, provided));
in(cT.in());
out(cT.out());
return make_pair(root, true);
}else
return make_pair(Vertex(), false);
}
VertexResult CompositeTransformation::addTransformation(TransformationPtr tPtr, Vertex v,
const EventType& intermediate,
const EventType& provided) {
const EventTypes& tempIn = mGraph[v].in();
if(!count(tempIn.begin(), tempIn.end(), intermediate))
return make_pair(Vertex(), false);
Vertex newV = boost::add_vertex(mGraph);
ConfiguredTransformation& cT = mGraph[newV];
cT.trans(tPtr);
cT.out(intermediate);
if(provided==EventType())
cT.in(tPtr->in(intermediate));
else
cT.in(tPtr->in(intermediate, provided));
auto e = boost::add_edge(v, newV, mGraph);
mGraph[e.first]=cT.out();
mIn.clear();
boost::depth_first_search(mGraph, boost::visitor(InputEventTypeExtractor(mIn)));
//sort(mIn.begin(), mIn.end());
//mIn.erase(unique(mIn.begin(). mIn.end()), mIn.end());
return make_pair(newV, true);
}
EventIDs CompositeTransformation::inIDs() const {
EventIDs ids(mIn.size());
copy(mIn.begin(), mIn.end(), ids.begin());
return ids;
}
TransList CompositeTransformation::path(Vertex v) const {
TransList result;
bool done=false;
do {
result.push_back(mGraph[v].trans());
auto in=in_edges(v, mGraph);
if(in.first!=in.second)
v=source(*in.first, mGraph);
else
done=true;
}while(!done);
return result;
}
VertexResult CompositeTransformation::find(TransformationPtr tPtr) const {
auto pred = [this, tPtr](Vertex v){ return mGraph[v].trans()==tPtr; };
auto it = find_if(vertices(mGraph).first, vertices(mGraph).second, pred);
if(it==vertices(mGraph).second)
return make_pair(Vertex(), false);
else
return make_pair(*it, true);
}
VertexList CompositeTransformation::find(const EventType& eT) const {
VertexList result;
boost::depth_first_search(mGraph, boost::visitor(FindEventType(eT, result)));
return result;
}
/** \todo implement **/
ostream& operator<<(ostream& o, const CompositeTransformation& t) {
const Graph& g=t.graph();
auto writeVertex = [&g](ostream& o, Vertex v){
if(g[v].trans())
o << " [label=\"" << *g[v].trans() << "\"]";
else
o << " [label=\"nullptr\"]";
};
auto writeEdge = [&g](ostream& o, Edge e){
o << " [label=\"" << g[e] << "\"]";
};
write_graphviz(o, g, writeVertex, writeEdge);
return o;
}
<commit_msg>CompositeTransformer: implement execution<commit_after>#include <CompositeTransformation.h>
#include <EventTypeHelpers.h>
#include <MetaEvent.h>
#include <IO.h>
#include <boost/graph/depth_first_search.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <boost/graph/copy.hpp>
#include <boost/graph/transpose_graph.hpp>
#include <boost/graph/graphviz.hpp>
#include <algorithm>
#include <iterator>
#include <iostream>
using namespace std;
using namespace boost;
struct CompositeTransformer : public Transformer {
using TransPtr = Transformation::TransPtr;
using Graph = adjacency_list<vecS, vecS, bidirectionalS, TransPtr, EventType>;
using Vertex= Graph::vertex_descriptor;
using Edge= Graph::edge_descriptor;
struct CallVisitor : public default_dfs_visitor {
MetaEvent& e;
map<Vertex, MetaEvent> buffer;
const Events& input;
CallVisitor(MetaEvent& e, const Events& input) : e(e), input(input) {}
void finish_vertex(Vertex v, const Graph& g) {
Events localIn;
TransPtr currTrans = g[v];
auto edges = out_edges(v, g);
for(const EventType& eT : currTrans->in()) {
bool found = false;
for(auto it=edges.first; it!=edges.second; it++)
if(g[*it]==eT) {
localIn.push_back(&buffer[target(*it, g)]);
found=true;
break;
}
if(!found)
for(const MetaEvent* eIn : input)
if(eT == (EventType)*eIn) {
localIn.push_back(eIn);
break;
}
}
buffer[v] = (*g[v])(localIn);
e=buffer[v];
}
};
Graph graph;
Vertex root;
/** \brief Generate CompositeTransformer from CompositeTransformation
* \param out output EventType of the created MetaEvents
* \param in input EventTypes of the consumed MetaEvents
* \param g CompositeTransformation graph to generate Transformers from
**/
CompositeTransformer(const EventType& out, const EventTypes& in, const CompositeTransformation::Graph& g)
: Transformer(Transformation::invalid, out, in) {
auto vertexCopy = [&g, this](CompositeTransformation::Vertex in, Vertex out) {
graph[out] = g[in].create();
};
Graph temp;
copy_graph(g, graph, boost::vertex_copy(vertexCopy));
auto it = find_if(vertices(graph).first, vertices(graph).second,
[this](Vertex v){ return !in_degree(v, graph);});
root = *it;
}
/** \brief check for applicability of Transformer
* \param events input events to check
* \return true if transformer can be applied, false otherwise
**/
bool check(const Events& events) const {
for(const EventType& eT : in())
if(!any_of(events.begin(), events.end(), [&eT](const MetaEvent* e){ return EventType(*e)<=eT; }))
return false;
return true;
}
/** \brief execute transformer on input events
* \param events input events
* \return result of the transformer graph
**/
MetaEvent operator()(const Events& events) {
MetaEvent e;
vector<default_color_type> colors(num_vertices(graph));
depth_first_visit(graph, root, CallVisitor(e, events),
make_iterator_property_map(colors.begin(), get(vertex_index, graph)));
return e;
}
/** \brief print composite transformer
* \param o output stream to print to
**/
void print(std::ostream& o) const {
auto writeVertex = [this](ostream& o, Vertex v){
TransPtr t = graph[v];
if(t)
o << " [label=\"" << *t << "\"]";
else
o << " [label=\"nullptr\"]";
};
auto writeEdge = [this](ostream& o, Edge e) {
o << " [label=\"" << graph[e] << "\"]";
};
write_graphviz(o, graph, writeVertex, writeEdge);
}
};
using Graph = CompositeTransformation::Graph;
using Vertex = CompositeTransformation::Vertex;
using VertexResult = CompositeTransformation::VertexResult;
using VertexList = CompositeTransformation::VertexList;
using Edge = Graph::edge_descriptor;
using EventTypes = CompositeTransformation::EventTypes;
using EventIDs = CompositeTransformation::EventIDs;
using TransPtr = CompositeTransformation::TransPtr;
using TransList = CompositeTransformation::TransList;
struct InputEventTypeExtractor : public boost::default_dfs_visitor {
Vertex temp;
EventTypes& in;
InputEventTypeExtractor(EventTypes& in)
: in(in)
{}
void discover_vertex(Vertex v, const Graph& g) {
temp = v;
}
void finish_vertex(Vertex v, const Graph& g) {
if(temp == v) {
const EventTypes& tempIn = g[v].in();
copy(tempIn.begin(), tempIn.end(), back_inserter(in));
}
}
};
struct FindEventType : public boost::default_dfs_visitor {
VertexList& result;
const EventType& eT;
FindEventType(const EventType& eT, VertexList& result)
: result(result), eT(eT)
{}
void discover_vertex(Vertex v, const Graph& g) {
if(count(g[v].in().begin(), g[v].in().end(), eT))
result.push_back(v);
}
};
;
CompositeTransformation::CompositeTransformation(TransformationPtr tPtr, const EventType& goal,
const EventType& provided) {
VertexResult res = addRootTransformation(tPtr, goal, provided);
if(res.second)
mRoot = res.first;
}
TransPtr CompositeTransformation::create() const {
if(boost::num_vertices(mGraph)==1) {
return mGraph[mRoot].create();
}
return TransPtr(new CompositeTransformer(mOut, mIn, mGraph));
}
bool CompositeTransformation::check() const {
return boost::num_vertices(mGraph);
}
VertexResult CompositeTransformation::addRootTransformation(TransformationPtr tPtr, const EventType& tempGoal,
const EventType& provided) {
if(num_vertices(mGraph)==0) {
Vertex root = boost::add_vertex(mGraph);
ConfiguredTransformation& cT = mGraph[root];
cT.trans(tPtr);
cT.out(tempGoal);
if(provided==EventType())
cT.in(tPtr->in(tempGoal));
else
cT.in(tPtr->in(tempGoal, provided));
in(cT.in());
out(cT.out());
return make_pair(root, true);
}else
return make_pair(Vertex(), false);
}
VertexResult CompositeTransformation::addTransformation(TransformationPtr tPtr, Vertex v,
const EventType& intermediate,
const EventType& provided) {
const EventTypes& tempIn = mGraph[v].in();
if(!count(tempIn.begin(), tempIn.end(), intermediate))
return make_pair(Vertex(), false);
Vertex newV = boost::add_vertex(mGraph);
ConfiguredTransformation& cT = mGraph[newV];
cT.trans(tPtr);
cT.out(intermediate);
if(provided==EventType())
cT.in(tPtr->in(intermediate));
else
cT.in(tPtr->in(intermediate, provided));
auto e = boost::add_edge(v, newV, mGraph);
mGraph[e.first]=cT.out();
mIn.clear();
boost::depth_first_search(mGraph, boost::visitor(InputEventTypeExtractor(mIn)));
return make_pair(newV, true);
}
EventIDs CompositeTransformation::inIDs() const {
EventIDs ids(mIn.size());
copy(mIn.begin(), mIn.end(), ids.begin());
return ids;
}
TransList CompositeTransformation::path(Vertex v) const {
TransList result;
bool done=false;
do {
result.push_back(mGraph[v].trans());
auto in=in_edges(v, mGraph);
if(in.first!=in.second)
v=source(*in.first, mGraph);
else
done=true;
}while(!done);
return result;
}
VertexResult CompositeTransformation::find(TransformationPtr tPtr) const {
auto pred = [this, tPtr](Vertex v){ return mGraph[v].trans()==tPtr; };
auto it = find_if(vertices(mGraph).first, vertices(mGraph).second, pred);
if(it==vertices(mGraph).second)
return make_pair(Vertex(), false);
else
return make_pair(*it, true);
}
VertexList CompositeTransformation::find(const EventType& eT) const {
VertexList result;
boost::depth_first_search(mGraph, boost::visitor(FindEventType(eT, result)));
return result;
}
/** \todo implement **/
ostream& operator<<(ostream& o, const CompositeTransformation& t) {
const Graph& g=t.graph();
auto writeVertex = [&g](ostream& o, Vertex v){
if(g[v].trans())
o << " [label=\"" << *g[v].trans() << "\"]";
else
o << " [label=\"nullptr\"]";
};
auto writeEdge = [&g](ostream& o, Edge e){
o << " [label=\"" << g[e] << "\"]";
};
write_graphviz(o, g, writeVertex, writeEdge);
return o;
}
<|endoftext|> |
<commit_before>#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#ifdef __APPLE__
#if TARGET_IOS
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>
#else
#import <OpenGL/OpenGL.h>
#import <OpenGL/gl3.h>
#endif
#else
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <EGL/egl.h>
#endif
#include <functional>
#include <memory>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <unordered_set>
#include <map>
#include <cstdint>
#include <string>
#include <tuple>
#include <utility>
#include <array>
#include <stdio.h>
#include <cmath>
#include "NativeBitmap.h"
#include "Texture.h"
#include "Material.h"
#include "Trig.h"
#include "TrigBatch.h"
#include "MeshObject.h"
#include "MaterialList.h"
#include "Scene.h"
#include "WavefrontOBJReader.h"
#include "Logger.h"
#include "AudioSink.h"
#include "SoundClip.h"
#include "SoundUtils.h"
#include "SoundListener.h"
#include "SoundEmitter.h"
#include "Vec2i.h"
#include "IMapElement.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "VBORenderingJob.h"
#include "DungeonGLES2Renderer.h"
#include "LightningStrategy.h"
#include "GameNativeAPI.h"
#include "IRenderer.h"
#include "NativeBitmap.h"
#include "CKnight.h"
#include "CGame.h"
#include "Common.h"
#include "NoudarGLES2Bridge.h"
#include "SplatAnimation.h"
#include "NoudarDungeonSnapshot.h"
std::shared_ptr<odb::DungeonGLES2Renderer> gles2Renderer = nullptr;
std::map<int, glm::vec2> mPositions;
bool hasActiveSplats;
odb::LightMap lightMap;
odb::AnimationList animationList;
long animationTime = 0;
bool hasCache = false;
odb::LightMap lightMapCache;
std::vector<std::shared_ptr<odb::NativeBitmap>> textures;
std::shared_ptr<Knights::CGame> game;
std::shared_ptr<odb::NoudarGLES2Bridge> render;
std::vector<std::shared_ptr<odb::SoundEmitter>> soundEmitters;
std::vector<std::shared_ptr<odb::SplatAnimation>> splatAnimation;
std::shared_ptr<odb::SoundListener> mainListener;
odb::NoudarDungeonSnapshot snapshot;
bool setupGraphics(int w, int h, std::string vertexShader, std::string fragmentShader, std::vector<std::shared_ptr<odb::NativeBitmap>> textureList ) {
textures = textureList;
gles2Renderer = std::make_shared<odb::DungeonGLES2Renderer>();
gles2Renderer->setTexture(textures);
animationTime = 0;
hasCache = false;
for (int y = 0; y < 20; ++y) {
for (int x = 0; x < 20; ++x) {
lightMapCache[ y ][ x ] = 0;
}
}
return gles2Renderer->init(w, h, vertexShader.c_str(), fragmentShader.c_str());
}
void renderFrame(long delta) {
if (gles2Renderer != nullptr && game != nullptr && textures.size() > 0) {
gles2Renderer->updateFadeState(delta);
auto cursor = game->getCursorPosition();
gles2Renderer->setCursorPosition( cursor.x, cursor.y );
gles2Renderer->setPlayerHealth( game->getMap()->getAvatar()->getHP() );
gles2Renderer->render(snapshot.map, snapshot.snapshot, snapshot.splat, lightMap, snapshot.ids, animationList, animationTime);
gles2Renderer->updateCamera(delta);
}
}
void shutdown() {
gles2Renderer->shutdown();
animationList.clear();
mPositions.clear();
animationTime = 0;
textures.clear();
hasCache = false;
for (int y = 0; y < 20; ++y) {
for (int x = 0; x < 20; ++x) {
lightMapCache[y][x] = 0;
}
}
gles2Renderer = nullptr;
}
void updateAnimations( long delta ) {
auto it = animationList.begin();
while (it != animationList.end()) {
if (animationTime - (std::get<2>(it->second)) >= odb::kAnimationLength) {
it = animationList.erase(it);
} else {
it = next(it);
}
}
hasActiveSplats = splatAnimation.size() > 0;
for ( auto splat : splatAnimation ) {
odb::Logger::log( "updating animatings" );
splat->update( delta );
}
splatAnimation.erase( std::remove_if( splatAnimation.begin(), splatAnimation.end(),
[](std::shared_ptr<odb::SplatAnimation> splat){ return splat->isFinished();}
), splatAnimation.end() );
if ( hasActiveSplats ) {
game->tick();
}
animationTime += delta;
}
void addCharacterMovement(int id, glm::vec2 previousPosition, glm::vec2 newPosition) {
auto movement = std::make_tuple<>(previousPosition, newPosition, animationTime);
if (animationList.count(id) > 0) {
auto animation = animationList[id];
auto prevPosition = std::get<0>(animation);
animation = std::make_tuple<>(prevPosition, newPosition, animationTime);
}
animationList[id] = movement;
char floorType = snapshot.map[ newPosition.y ][ newPosition.x ];
if ( floorType == '.' || floorType == '-' ) {
soundEmitters[0]->play(mainListener);
} else if ( floorType == '_' || floorType == '=') {
soundEmitters[1]->play(mainListener);
} else {
if ( floorType == '{' || floorType == '(' || floorType == ')' || floorType == '}' || floorType == '2' || floorType == '7' || '~' ) {
soundEmitters[1]->play(mainListener);
}
}
}
void updateCharacterMovements(const int *idsLocal) {
int position;
for (int y = 0; y < Knights::kMapSize; ++y) {
for (int x = 0; x < Knights::kMapSize; ++x) {
position = (y * Knights::kMapSize) + x;
int id = idsLocal[position];
snapshot.ids[y][x] = id;
if (id != 0) {
auto previousPosition = mPositions[id];
if (previousPosition != glm::vec2(x, y) ) {
mPositions[id] = glm::vec2(x, y);
if ( game->getTurn() > 0 ) {
addCharacterMovement(id, previousPosition, mPositions[id]);
}
}
}
}
}
}
void setCameraPosition( int x, int y ) {
if (gles2Renderer != nullptr) {
gles2Renderer->setCameraPosition(x, y);
}
}
void updateLevelSnapshot(const int *level, const int *actors, const int *splats) {
hasActiveSplats = false;
int position;
for (int y = 0; y < Knights::kMapSize; ++y) {
for (int x = 0; x < Knights::kMapSize; ++x) {
position = ( Knights::kMapSize * y ) + x;
snapshot.map[y][x] = (odb::ETextures) level[position];
snapshot.snapshot[y][x] = (odb::ETextures) actors[position];
snapshot.splat[y][x] = -1;
lightMap[y][x] = lightMapCache[y][x];
}
}
for ( auto& splatAnim : splatAnimation ) {
auto pos = splatAnim->getPosition();
snapshot.splat[pos.y][pos.x] = static_cast<odb::ETextures >( splatAnim->getSplatFrame());
}
// for (int y = 0; y < 20; ++y) {
// for (int x = 0; x < 20; ++x) {
//
// if (map[y][x] == '|') {
//
// if (!hasCache) {
// odb::LightningStrategy::castLightInAllDirections(lightMapCache, 255, map, x, y);
// odb::LightningStrategy::castLightInAllDirections(lightMap, 255, map, x, y);
// }
// }
// }
// }
hasCache = true;
}
void startFadingIn() {
if (gles2Renderer != nullptr) {
gles2Renderer->startFadingIn();
}
}
void startFadingOut() {
if (gles2Renderer != nullptr) {
gles2Renderer->startFadingOut();
}
}
bool isAnimating() {
if (gles2Renderer != nullptr) {
return gles2Renderer->isAnimating() && !hasActiveSplats;
}
return false;
}
void rotateCameraLeft() {
if (gles2Renderer != nullptr&& !isAnimating() ) {
gles2Renderer->rotateLeft();
render->setNextCommand('i');
game->tick();
render->setNextCommand('.');
}
}
void rotateCameraRight() {
if (gles2Renderer != nullptr&& !isAnimating() ) {
gles2Renderer->rotateRight();
render->setNextCommand('p');
game->tick();
render->setNextCommand('.');
}
}
void onReleasedLongPressingMove() {
if (gles2Renderer != nullptr) {
gles2Renderer->onReleasedLongPressingMove();
}
}
void onLongPressingMove() {
if (gles2Renderer != nullptr) {
gles2Renderer->onLongPressingMove();
}
}
void setEyeViewMatrix( float* eyeView ) {
if (gles2Renderer != nullptr) {
gles2Renderer->setEyeView(eyeView);
}
}
void setPerspectiveMatrix( float* perspectiveMatrix ) {
if (gles2Renderer != nullptr) {
gles2Renderer->setPerspectiveMatrix(perspectiveMatrix);
}
}
void setAngleXZ( float XZAngle ) {
if (gles2Renderer != nullptr) {
gles2Renderer->setAngleXZ(XZAngle);
}
}
void setAngleYZ( float YZAngle ) {
if (gles2Renderer != nullptr) {
gles2Renderer->setAngleYZ(YZAngle);
}
}
void loadMapData( std::string geoFile, std::string petFile ) {
}
void readMap( std::string data ) {
render = std::make_shared<odb::NoudarGLES2Bridge>();
std::string::size_type n = 0;
while ( ( n = data.find( "\n", n ) ) != std::string::npos )
{
data.replace( n, 1, "" );
++n;
}
auto onMonsterDead = [&]( Knights::Vec2i pos ) {
soundEmitters[ 4 ]->play( mainListener );
};
auto onPlayerDead = [&](Knights::Vec2i pos) {
soundEmitters[ 6 ]->play( mainListener );
};
auto onPlayerAttack = [&](Knights::Vec2i pos) {
soundEmitters[ 7 ]->play( mainListener );
};
auto onMonsterAttack = [&](Knights::Vec2i pos) {
};
auto onMonsterDamaged = [&](Knights::Vec2i pos) {
auto splat = std::make_shared<odb::SplatAnimation>( pos );
splatAnimation.push_back( splat );
splat->startSplatAnimation();
soundEmitters[ 3 ]->play( mainListener );
};
auto onPlayerDamaged = [&](Knights::Vec2i pos) {
soundEmitters[ 5 ]->play( mainListener );
};
auto gameDelegate = std::make_shared<Knights::CGameDelegate>();
gameDelegate->setMonsterAttackedCallback( onMonsterAttack );
gameDelegate->setMonsterDiedCallback( onMonsterDead );
gameDelegate->setMonsterDamagedCallback(onMonsterDamaged);
gameDelegate->setPlayerAttackedCallback( onPlayerAttack );
gameDelegate->setPlayerDiedCallback( onPlayerDead );
gameDelegate->setPlayerDamagedCallback( onPlayerDamaged );
game = std::make_shared<Knights::CGame>( data, render, gameDelegate );
if ( game != nullptr ) {
game->tick();
}
}
void moveUp() {
if ( game != nullptr && !isAnimating() ) {
render->setNextCommand('o');
game->tick();
render->setNextCommand('.');
}
}
void moveDown() {
if ( game != nullptr && !isAnimating() ) {
render->setNextCommand('p');
game->tick();
render->setNextCommand('p');
game->tick();
render->setNextCommand('o');
game->tick();
render->setNextCommand('i');
game->tick();
render->setNextCommand('i');
game->tick();
render->setNextCommand('.');
}
}
void moveLeft() {
if ( game != nullptr && !isAnimating() ) {
render->setNextCommand('i');
game->tick();
render->setNextCommand('o');
game->tick();
render->setNextCommand('p');
game->tick();
render->setNextCommand('.');
}
}
void moveRight() {
if ( game != nullptr && !isAnimating() ) {
render->setNextCommand('p');
game->tick();
render->setNextCommand('o');
game->tick();
render->setNextCommand('i');
game->tick();
render->setNextCommand('.');
}
}
void gameLoopTick( long ms ) {
updateAnimations( ms );
}
void setSoundEmitters( std::vector<std::shared_ptr<odb::SoundEmitter>> emitters, std::shared_ptr<odb::SoundListener> listener ) {
soundEmitters = emitters;
mainListener = listener;
}
void forceDirection( int direction ) {
char directions[] = { 'r', 'f', 'c', 'd'};
render->setNextCommand( directions[ direction ] );
game->tick();
render->setNextCommand('.');
}
<commit_msg>Enable back the lightning<commit_after>#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#ifdef __APPLE__
#if TARGET_IOS
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>
#else
#import <OpenGL/OpenGL.h>
#import <OpenGL/gl3.h>
#endif
#else
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <EGL/egl.h>
#endif
#include <functional>
#include <memory>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <unordered_set>
#include <map>
#include <cstdint>
#include <string>
#include <tuple>
#include <utility>
#include <array>
#include <stdio.h>
#include <cmath>
#include "NativeBitmap.h"
#include "Texture.h"
#include "Material.h"
#include "Trig.h"
#include "TrigBatch.h"
#include "MeshObject.h"
#include "MaterialList.h"
#include "Scene.h"
#include "WavefrontOBJReader.h"
#include "Logger.h"
#include "AudioSink.h"
#include "SoundClip.h"
#include "SoundUtils.h"
#include "SoundListener.h"
#include "SoundEmitter.h"
#include "Vec2i.h"
#include "IMapElement.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "VBORenderingJob.h"
#include "DungeonGLES2Renderer.h"
#include "LightningStrategy.h"
#include "GameNativeAPI.h"
#include "IRenderer.h"
#include "NativeBitmap.h"
#include "CKnight.h"
#include "CGame.h"
#include "Common.h"
#include "NoudarGLES2Bridge.h"
#include "SplatAnimation.h"
#include "NoudarDungeonSnapshot.h"
std::shared_ptr<odb::DungeonGLES2Renderer> gles2Renderer = nullptr;
std::map<int, glm::vec2> mPositions;
bool hasActiveSplats;
odb::LightMap lightMap;
odb::AnimationList animationList;
long animationTime = 0;
bool hasCache = false;
odb::LightMap lightMapCache;
std::vector<std::shared_ptr<odb::NativeBitmap>> textures;
std::shared_ptr<Knights::CGame> game;
std::shared_ptr<odb::NoudarGLES2Bridge> render;
std::vector<std::shared_ptr<odb::SoundEmitter>> soundEmitters;
std::vector<std::shared_ptr<odb::SplatAnimation>> splatAnimation;
std::shared_ptr<odb::SoundListener> mainListener;
odb::NoudarDungeonSnapshot snapshot;
bool setupGraphics(int w, int h, std::string vertexShader, std::string fragmentShader, std::vector<std::shared_ptr<odb::NativeBitmap>> textureList ) {
textures = textureList;
gles2Renderer = std::make_shared<odb::DungeonGLES2Renderer>();
gles2Renderer->setTexture(textures);
animationTime = 0;
hasCache = false;
for (int y = 0; y < 20; ++y) {
for (int x = 0; x < 20; ++x) {
lightMapCache[ y ][ x ] = 0;
}
}
return gles2Renderer->init(w, h, vertexShader.c_str(), fragmentShader.c_str());
}
void renderFrame(long delta) {
if (gles2Renderer != nullptr && game != nullptr && textures.size() > 0) {
gles2Renderer->updateFadeState(delta);
auto cursor = game->getCursorPosition();
gles2Renderer->setCursorPosition( cursor.x, cursor.y );
gles2Renderer->setPlayerHealth( game->getMap()->getAvatar()->getHP() );
gles2Renderer->render(snapshot.map, snapshot.snapshot, snapshot.splat, lightMap, snapshot.ids, animationList, animationTime);
gles2Renderer->updateCamera(delta);
}
}
void shutdown() {
gles2Renderer->shutdown();
animationList.clear();
mPositions.clear();
animationTime = 0;
textures.clear();
hasCache = false;
for (int y = 0; y < 20; ++y) {
for (int x = 0; x < 20; ++x) {
lightMapCache[y][x] = 0;
}
}
gles2Renderer = nullptr;
}
void updateAnimations( long delta ) {
auto it = animationList.begin();
while (it != animationList.end()) {
if (animationTime - (std::get<2>(it->second)) >= odb::kAnimationLength) {
it = animationList.erase(it);
} else {
it = next(it);
}
}
hasActiveSplats = splatAnimation.size() > 0;
for ( auto splat : splatAnimation ) {
odb::Logger::log( "updating animatings" );
splat->update( delta );
}
splatAnimation.erase( std::remove_if( splatAnimation.begin(), splatAnimation.end(),
[](std::shared_ptr<odb::SplatAnimation> splat){ return splat->isFinished();}
), splatAnimation.end() );
if ( hasActiveSplats ) {
game->tick();
}
animationTime += delta;
}
void addCharacterMovement(int id, glm::vec2 previousPosition, glm::vec2 newPosition) {
auto movement = std::make_tuple<>(previousPosition, newPosition, animationTime);
if (animationList.count(id) > 0) {
auto animation = animationList[id];
auto prevPosition = std::get<0>(animation);
animation = std::make_tuple<>(prevPosition, newPosition, animationTime);
}
animationList[id] = movement;
char floorType = snapshot.map[ newPosition.y ][ newPosition.x ];
if ( floorType == '.' || floorType == '-' ) {
soundEmitters[0]->play(mainListener);
} else if ( floorType == '_' || floorType == '=') {
soundEmitters[1]->play(mainListener);
} else {
if ( floorType == '{' || floorType == '(' || floorType == ')' || floorType == '}' || floorType == '2' || floorType == '7' || '~' ) {
soundEmitters[1]->play(mainListener);
}
}
}
void updateCharacterMovements(const int *idsLocal) {
int position;
for (int y = 0; y < Knights::kMapSize; ++y) {
for (int x = 0; x < Knights::kMapSize; ++x) {
position = (y * Knights::kMapSize) + x;
int id = idsLocal[position];
snapshot.ids[y][x] = id;
if (id != 0) {
auto previousPosition = mPositions[id];
if (previousPosition != glm::vec2(x, y) ) {
mPositions[id] = glm::vec2(x, y);
if ( game->getTurn() > 0 ) {
addCharacterMovement(id, previousPosition, mPositions[id]);
}
}
}
}
}
}
void setCameraPosition( int x, int y ) {
if (gles2Renderer != nullptr) {
gles2Renderer->setCameraPosition(x, y);
}
}
void updateLevelSnapshot(const int *level, const int *actors, const int *splats) {
hasActiveSplats = false;
int position;
for (int y = 0; y < Knights::kMapSize; ++y) {
for (int x = 0; x < Knights::kMapSize; ++x) {
position = ( Knights::kMapSize * y ) + x;
snapshot.map[y][x] = (odb::ETextures) level[position];
snapshot.snapshot[y][x] = (odb::ETextures) actors[position];
snapshot.splat[y][x] = -1;
lightMap[y][x] = lightMapCache[y][x];
}
}
for ( auto& splatAnim : splatAnimation ) {
auto pos = splatAnim->getPosition();
snapshot.splat[pos.y][pos.x] = static_cast<odb::ETextures >( splatAnim->getSplatFrame());
}
for (int y = 0; y < 20; ++y) {
for (int x = 0; x < 20; ++x) {
if (snapshot.map[y][x] == '|') {
if (!hasCache) {
odb::LightningStrategy::castLightInAllDirections(lightMapCache, 255, snapshot.map, x, y);
odb::LightningStrategy::castLightInAllDirections(lightMap, 255, snapshot.map, x, y);
}
}
}
}
hasCache = true;
}
void startFadingIn() {
if (gles2Renderer != nullptr) {
gles2Renderer->startFadingIn();
}
}
void startFadingOut() {
if (gles2Renderer != nullptr) {
gles2Renderer->startFadingOut();
}
}
bool isAnimating() {
if (gles2Renderer != nullptr) {
return gles2Renderer->isAnimating() && !hasActiveSplats;
}
return false;
}
void rotateCameraLeft() {
if (gles2Renderer != nullptr&& !isAnimating() ) {
gles2Renderer->rotateLeft();
render->setNextCommand('i');
game->tick();
render->setNextCommand('.');
}
}
void rotateCameraRight() {
if (gles2Renderer != nullptr&& !isAnimating() ) {
gles2Renderer->rotateRight();
render->setNextCommand('p');
game->tick();
render->setNextCommand('.');
}
}
void onReleasedLongPressingMove() {
if (gles2Renderer != nullptr) {
gles2Renderer->onReleasedLongPressingMove();
}
}
void onLongPressingMove() {
if (gles2Renderer != nullptr) {
gles2Renderer->onLongPressingMove();
}
}
void setEyeViewMatrix( float* eyeView ) {
if (gles2Renderer != nullptr) {
gles2Renderer->setEyeView(eyeView);
}
}
void setPerspectiveMatrix( float* perspectiveMatrix ) {
if (gles2Renderer != nullptr) {
gles2Renderer->setPerspectiveMatrix(perspectiveMatrix);
}
}
void setAngleXZ( float XZAngle ) {
if (gles2Renderer != nullptr) {
gles2Renderer->setAngleXZ(XZAngle);
}
}
void setAngleYZ( float YZAngle ) {
if (gles2Renderer != nullptr) {
gles2Renderer->setAngleYZ(YZAngle);
}
}
void loadMapData( std::string geoFile, std::string petFile ) {
}
void readMap( std::string data ) {
render = std::make_shared<odb::NoudarGLES2Bridge>();
std::string::size_type n = 0;
while ( ( n = data.find( "\n", n ) ) != std::string::npos )
{
data.replace( n, 1, "" );
++n;
}
auto onMonsterDead = [&]( Knights::Vec2i pos ) {
soundEmitters[ 4 ]->play( mainListener );
};
auto onPlayerDead = [&](Knights::Vec2i pos) {
soundEmitters[ 6 ]->play( mainListener );
};
auto onPlayerAttack = [&](Knights::Vec2i pos) {
soundEmitters[ 7 ]->play( mainListener );
};
auto onMonsterAttack = [&](Knights::Vec2i pos) {
};
auto onMonsterDamaged = [&](Knights::Vec2i pos) {
auto splat = std::make_shared<odb::SplatAnimation>( pos );
splatAnimation.push_back( splat );
splat->startSplatAnimation();
soundEmitters[ 3 ]->play( mainListener );
};
auto onPlayerDamaged = [&](Knights::Vec2i pos) {
soundEmitters[ 5 ]->play( mainListener );
};
auto gameDelegate = std::make_shared<Knights::CGameDelegate>();
gameDelegate->setMonsterAttackedCallback( onMonsterAttack );
gameDelegate->setMonsterDiedCallback( onMonsterDead );
gameDelegate->setMonsterDamagedCallback(onMonsterDamaged);
gameDelegate->setPlayerAttackedCallback( onPlayerAttack );
gameDelegate->setPlayerDiedCallback( onPlayerDead );
gameDelegate->setPlayerDamagedCallback( onPlayerDamaged );
game = std::make_shared<Knights::CGame>( data, render, gameDelegate );
if ( game != nullptr ) {
game->tick();
}
}
void moveUp() {
if ( game != nullptr && !isAnimating() ) {
render->setNextCommand('o');
game->tick();
render->setNextCommand('.');
}
}
void moveDown() {
if ( game != nullptr && !isAnimating() ) {
render->setNextCommand('p');
game->tick();
render->setNextCommand('p');
game->tick();
render->setNextCommand('o');
game->tick();
render->setNextCommand('i');
game->tick();
render->setNextCommand('i');
game->tick();
render->setNextCommand('.');
}
}
void moveLeft() {
if ( game != nullptr && !isAnimating() ) {
render->setNextCommand('i');
game->tick();
render->setNextCommand('o');
game->tick();
render->setNextCommand('p');
game->tick();
render->setNextCommand('.');
}
}
void moveRight() {
if ( game != nullptr && !isAnimating() ) {
render->setNextCommand('p');
game->tick();
render->setNextCommand('o');
game->tick();
render->setNextCommand('i');
game->tick();
render->setNextCommand('.');
}
}
void gameLoopTick( long ms ) {
updateAnimations( ms );
}
void setSoundEmitters( std::vector<std::shared_ptr<odb::SoundEmitter>> emitters, std::shared_ptr<odb::SoundListener> listener ) {
soundEmitters = emitters;
mainListener = listener;
}
void forceDirection( int direction ) {
char directions[] = { 'r', 'f', 'c', 'd'};
render->setNextCommand( directions[ direction ] );
game->tick();
render->setNextCommand('.');
}
<|endoftext|> |
<commit_before>//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 "ApplicationMain.h"
#include "StringHelpers.h"
#include "winobjc\winobjc.h"
#include <assert.h>
#include <string>
using namespace Windows::Foundation;
using namespace Windows::UI::Core;
using namespace Windows::System::Threading;
void EbrSetWritableFolder(const char* folder);
void IWSetTemporaryFolder(const char* folder);
typedef void* EbrEvent;
int EbrEventTimedMultipleWait(EbrEvent* events, int numEvents, double timeout, SocketWait* sockets);
void* g_XamlUIFiber = nullptr;
void* g_WinObjcUIFiber = nullptr;
int XamlTimedMultipleWait(EbrEvent* events, int numEvents, double timeout, SocketWait* sockets) {
// If our current fiber is the main winobjc UI thread,
// we perform the wait on a separate worker thread, then
// yield to the Xaml Dispatcher fiber. Once the worker thread wakes
// up, it will queue the result on the Xaml dispatcher, then
// have it switch back to the winobjc fiber with the result
if (::GetCurrentFiber() == g_WinObjcUIFiber) {
int retval = 0;
bool signaled = false;
auto dispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;
ThreadPool::RunAsync(
ref new WorkItemHandler([&retval, &signaled, events, numEvents, timeout, sockets, dispatcher](IAsyncAction ^ action) {
// Wait for an event
retval = EbrEventTimedMultipleWait(events, numEvents, timeout, sockets);
signaled = true;
// Dispatch it on the UI thread
dispatcher->RunAsync(CoreDispatcherPriority::High, ref new DispatchedHandler([]()
{
::SwitchToFiber(g_WinObjcUIFiber);
}));
}));
// ** WARNING ** The "local" retval is passed by ref to the lamba - never wake up this
// fiber from somewhere else!
::SwitchToFiber(g_XamlUIFiber);
assert(signaled);
return retval;
}
else {
return EbrEventTimedMultipleWait(events, numEvents, timeout, sockets);
}
}
extern "C" unsigned int XamlWaitHandle(uintptr_t hEvent, unsigned int timeout) {
int retval = 0;
bool signaled = false;
auto dispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;
ThreadPool::RunAsync(
ref new WorkItemHandler([&retval, &signaled, hEvent, timeout, dispatcher](IAsyncAction ^ action) {
// Wait for an event
retval = WaitForSingleObjectEx((HANDLE)hEvent, timeout, TRUE);
signaled = true;
// Dispatch it on the UI thread
dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([]()
{
::SwitchToFiber(g_WinObjcUIFiber);
}));
}));
// ** WARNING ** The "local" retval is passed by ref to the lamba - never wake up this
// fiber from somewhere else!
::SwitchToFiber(g_XamlUIFiber);
assert(signaled);
return retval;
}
struct StartParameters {
int argc;
char** argv;
std::string principalClassName;
std::string delegateClassName;
float windowWidth, windowHeight;
};
StartParameters g_startParams = { 0, nullptr, std::string(), std::string(), 0.0f, 0.0f };
static VOID CALLBACK WinObjcMainLoop(LPVOID param) {
ApplicationMainStart(g_startParams.argc,
g_startParams.argv,
g_startParams.principalClassName.c_str(),
g_startParams.delegateClassName.c_str(),
g_startParams.windowWidth,
g_startParams.windowHeight);
}
void SetXamlUIWaiter();
static void StartCompositedRunLoop() {
// Switch this xaml/winrt thread to a fiber, and store it
::ConvertThreadToFiberEx(nullptr, FIBER_FLAG_FLOAT_SWITCH);
g_XamlUIFiber = ::GetCurrentFiber();
// Create our WinObjC fiber
const size_t stackCommitSize = 4096 * 4; // 4 pages
const size_t stackReserveSize = 1024 * 1024; // 1MB
g_WinObjcUIFiber = ::CreateFiberEx(stackCommitSize, stackReserveSize, FIBER_FLAG_FLOAT_SWITCH, WinObjcMainLoop, nullptr);
// Switch to the WinObjC fiber to kick off the IOS launch sequence
::SwitchToFiber(g_WinObjcUIFiber);
}
void InitializeApp() {
// Only init once.
// No lock needed as this is only called from the UI thread.
static bool initialized = false;
if (initialized) {
return;
}
initialized = true;
// Set our writable and temp folders
char writableFolder[2048];
size_t outLen;
auto pathData = Windows::Storage::ApplicationData::Current->LocalFolder->Path->Data();
wcstombs_s(&outLen, writableFolder, pathData, sizeof(writableFolder));
EbrSetWritableFolder(writableFolder);
auto tempPathData = Windows::Storage::ApplicationData::Current->TemporaryFolder->Path->Data();
wcstombs_s(&outLen, writableFolder, tempPathData, sizeof(writableFolder));
IWSetTemporaryFolder(writableFolder);
// Set the waiter routine for yielding waits to the XAML/UI thread
SetXamlUIWaiter();
}
extern "C" void IWRunApplicationMain(Platform::String^ principalClassName,
Platform::String^ delegateClassName,
float windowWidth,
float windowHeight) {
// Perform initialization
InitializeApp();
// Store the start parameters to hand off to the run loop
g_startParams.argc = 0;
g_startParams.argv = nullptr;
g_startParams.principalClassName = Strings::WideToNarrow(principalClassName->Data());
g_startParams.delegateClassName = Strings::WideToNarrow(delegateClassName->Data());
g_startParams.windowWidth = windowWidth;
g_startParams.windowHeight = windowHeight;
// Kick off the run loop
StartCompositedRunLoop();
}
<commit_msg>Don't pass bogus string pointer to wcstomb_s<commit_after>//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 "ApplicationMain.h"
#include "StringHelpers.h"
#include "winobjc\winobjc.h"
#include <assert.h>
#include <string>
using namespace Windows::Foundation;
using namespace Windows::UI::Core;
using namespace Windows::System::Threading;
void EbrSetWritableFolder(const char* folder);
void IWSetTemporaryFolder(const char* folder);
typedef void* EbrEvent;
int EbrEventTimedMultipleWait(EbrEvent* events, int numEvents, double timeout, SocketWait* sockets);
void* g_XamlUIFiber = nullptr;
void* g_WinObjcUIFiber = nullptr;
int XamlTimedMultipleWait(EbrEvent* events, int numEvents, double timeout, SocketWait* sockets) {
// If our current fiber is the main winobjc UI thread,
// we perform the wait on a separate worker thread, then
// yield to the Xaml Dispatcher fiber. Once the worker thread wakes
// up, it will queue the result on the Xaml dispatcher, then
// have it switch back to the winobjc fiber with the result
if (::GetCurrentFiber() == g_WinObjcUIFiber) {
int retval = 0;
bool signaled = false;
auto dispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;
ThreadPool::RunAsync(
ref new WorkItemHandler([&retval, &signaled, events, numEvents, timeout, sockets, dispatcher](IAsyncAction ^ action) {
// Wait for an event
retval = EbrEventTimedMultipleWait(events, numEvents, timeout, sockets);
signaled = true;
// Dispatch it on the UI thread
dispatcher->RunAsync(CoreDispatcherPriority::High, ref new DispatchedHandler([]()
{
::SwitchToFiber(g_WinObjcUIFiber);
}));
}));
// ** WARNING ** The "local" retval is passed by ref to the lamba - never wake up this
// fiber from somewhere else!
::SwitchToFiber(g_XamlUIFiber);
assert(signaled);
return retval;
}
else {
return EbrEventTimedMultipleWait(events, numEvents, timeout, sockets);
}
}
extern "C" unsigned int XamlWaitHandle(uintptr_t hEvent, unsigned int timeout) {
int retval = 0;
bool signaled = false;
auto dispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;
ThreadPool::RunAsync(
ref new WorkItemHandler([&retval, &signaled, hEvent, timeout, dispatcher](IAsyncAction ^ action) {
// Wait for an event
retval = WaitForSingleObjectEx((HANDLE)hEvent, timeout, TRUE);
signaled = true;
// Dispatch it on the UI thread
dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([]()
{
::SwitchToFiber(g_WinObjcUIFiber);
}));
}));
// ** WARNING ** The "local" retval is passed by ref to the lamba - never wake up this
// fiber from somewhere else!
::SwitchToFiber(g_XamlUIFiber);
assert(signaled);
return retval;
}
struct StartParameters {
int argc;
char** argv;
std::string principalClassName;
std::string delegateClassName;
float windowWidth, windowHeight;
};
StartParameters g_startParams = { 0, nullptr, std::string(), std::string(), 0.0f, 0.0f };
static VOID CALLBACK WinObjcMainLoop(LPVOID param) {
ApplicationMainStart(g_startParams.argc,
g_startParams.argv,
g_startParams.principalClassName.c_str(),
g_startParams.delegateClassName.c_str(),
g_startParams.windowWidth,
g_startParams.windowHeight);
}
void SetXamlUIWaiter();
static void StartCompositedRunLoop() {
// Switch this xaml/winrt thread to a fiber, and store it
::ConvertThreadToFiberEx(nullptr, FIBER_FLAG_FLOAT_SWITCH);
g_XamlUIFiber = ::GetCurrentFiber();
// Create our WinObjC fiber
const size_t stackCommitSize = 4096 * 4; // 4 pages
const size_t stackReserveSize = 1024 * 1024; // 1MB
g_WinObjcUIFiber = ::CreateFiberEx(stackCommitSize, stackReserveSize, FIBER_FLAG_FLOAT_SWITCH, WinObjcMainLoop, nullptr);
// Switch to the WinObjC fiber to kick off the IOS launch sequence
::SwitchToFiber(g_WinObjcUIFiber);
}
void InitializeApp() {
// Only init once.
// No lock needed as this is only called from the UI thread.
static bool initialized = false;
if (initialized) {
return;
}
initialized = true;
// Set our writable and temp folders
char writableFolder[2048];
size_t outLen;
auto pathData = Windows::Storage::ApplicationData::Current->LocalFolder->Path;
wcstombs_s(&outLen, writableFolder, pathData->Data(), sizeof(writableFolder) - 1);
EbrSetWritableFolder(writableFolder);
auto tempPathData = Windows::Storage::ApplicationData::Current->TemporaryFolder->Path;
wcstombs_s(&outLen, writableFolder, tempPathData->Data(), sizeof(writableFolder) - 1);
IWSetTemporaryFolder(writableFolder);
// Set the waiter routine for yielding waits to the XAML/UI thread
SetXamlUIWaiter();
}
extern "C" void IWRunApplicationMain(Platform::String^ principalClassName,
Platform::String^ delegateClassName,
float windowWidth,
float windowHeight) {
// Perform initialization
InitializeApp();
// Store the start parameters to hand off to the run loop
g_startParams.argc = 0;
g_startParams.argv = nullptr;
g_startParams.principalClassName = Strings::WideToNarrow(principalClassName->Data());
g_startParams.delegateClassName = Strings::WideToNarrow(delegateClassName->Data());
g_startParams.windowWidth = windowWidth;
g_startParams.windowHeight = windowHeight;
// Kick off the run loop
StartCompositedRunLoop();
}
<|endoftext|> |
<commit_before>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
//! @file
#ifndef DO_IMAGEPROCESSING_WARP_HPP
#define DO_IMAGEPROCESSING_WARP_HPP
#include <DO/ImageProcessing/Interpolation.hpp>
namespace DO {
template <typename T, typename S>
void warp(const Image<T>& src, Image<T>& dst,
const Matrix<S, 3, 3>& homography,
const T& default_fill_color = PixelTraits<T>::min())
{
typedef typename PixelTraits<T>::template Cast<double>::pixel_type
DoublePixel;
typedef typename PixelTraits<T>::channel_type ChannelType;
typedef Matrix<S, 3, 3> Matrix3;
typedef Matrix<S, 3, 1> Vector3;
typedef Matrix<S, 2, 1> Vector2;
const Matrix3& H = homography;
typename Image<T>::array_iterator it = dst.begin_array();
for ( ; !it.end(); ++it)
{
// Get the corresponding coordinates in the source src.
Vector3 H_p;
H_p = H * (Vector3() << it.position().template cast<S>(), 1).finished();
H_p /= H_p(2);
// Check if the position is not in the src domain [0,w[ x [0,h[.
bool position_is_in_src_domain =
H_p.x() >= 0 || H_p.x() < S(src.width()) ||
H_p.y() >= 0 || H_p.y() < S(src.height());
// Fill with either the default value or the interpolated value.
if (position_is_in_src_domain)
{
Vector2 H_p_2(H_p.template head<2>());
DoublePixel pixel_value( interpolate(src, H_p_2) );
*it = PixelTraits<DoublePixel>::template Cast<ChannelType>::apply(
pixel_value);
}
else
*it = default_fill_color;
}
}
}
#endif /* DO_IMAGEPROCESSING_WARP_HPP */<commit_msg>Change variable name.<commit_after>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
//! @file
#ifndef DO_IMAGEPROCESSING_WARP_HPP
#define DO_IMAGEPROCESSING_WARP_HPP
#include <DO/ImageProcessing/Interpolation.hpp>
namespace DO {
template <typename T, typename S>
void warp(const Image<T>& src, Image<T>& dst,
const Matrix<S, 3, 3>& homography_from_dst_to_src,
const T& default_fill_color = PixelTraits<T>::min())
{
typedef typename PixelTraits<T>::template Cast<double>::pixel_type
DoublePixel;
typedef typename PixelTraits<T>::channel_type ChannelType;
typedef Matrix<S, 3, 3> Matrix3;
typedef Matrix<S, 3, 1> Vector3;
typedef Matrix<S, 2, 1> Vector2;
const Matrix3& H = homography_from_dst_to_src;
typename Image<T>::array_iterator it = dst.begin_array();
for ( ; !it.end(); ++it)
{
// Get the corresponding coordinates in the source src.
Vector3 H_p;
H_p = H * (Vector3() << it.position().template cast<S>(), 1).finished();
H_p /= H_p(2);
// Check if the position is not in the src domain [0,w[ x [0,h[.
bool position_is_in_src_domain =
H_p.x() >= 0 || H_p.x() < S(src.width()) ||
H_p.y() >= 0 || H_p.y() < S(src.height());
// Fill with either the default value or the interpolated value.
if (position_is_in_src_domain)
{
Vector2 H_p_2(H_p.template head<2>());
DoublePixel pixel_value( interpolate(src, H_p_2) );
*it = PixelTraits<DoublePixel>::template Cast<ChannelType>::apply(
pixel_value);
}
else
*it = default_fill_color;
}
}
}
#endif /* DO_IMAGEPROCESSING_WARP_HPP */<|endoftext|> |
<commit_before>#include <glm/gtc/matrix_transform.hpp>
#include "Core/Engine.hh"
#include "Core/Renderer.hh"
#include "DemoScene.hh"
#include "ResourceManager/SharedMesh.hh"
#include "ResourceManager/Texture.hh"
#include "ResourceManager/CubeMap.hh"
#include "Components/RotationForce.hh"
#include "Components/MaterialComponent.h"
#include <Components/CameraComponent.hh>
#include <Components/TrackBallComponent.hpp>
#include <OpenGL/ComputeShader.hh>
#include <Systems/RotationForceSystem.hpp>
#include <Systems/MeshRenderSystem.h>
#include <Systems/GraphNodeSystem.hpp>
#include <Systems/CameraSystem.hpp>
#include <Systems/TrackBallSystem.hpp>
#include "ResourceManager/ResourceManager.hh"
#include <Core/Engine.hh>
#include <Entities/EntityManager.h>
#include <SDL\SDL.h>
DemoScene::DemoScene(Engine &engine) : AScene(engine)
{
}
DemoScene::~DemoScene(void)
{
}
Handle DemoScene::createPlanet(float rotSpeed, float orbitSpeed,
glm::vec3 &pos, glm::vec3 &scale,
std::string const &shader,
std::string const &tex1, std::string const &tex2, std::string const &tex3,
std::string const &tex4)
{
auto &m = _engine.getInstance<EntityManager>();
auto p = m.createEntity();
auto e = m.createEntity();
p->addComponent<Component::GraphNode>();
e->addComponent<Component::GraphNode>();
e->setLocalTransform() = glm::translate(e->getLocalTransform(), pos);
e->setLocalTransform() = glm::scale(e->getLocalTransform(), scale);
SmartPointer<Component::MeshRenderer> r = e->addComponent<Component::MeshRenderer>("model:ball");
SmartPointer<Material> materialPlanet = _engine.getInstance<Renderer>().getMaterialManager().createMaterial("material:planet_" + shader);
materialPlanet->pushShader(shader);
e->addComponent<Component::MaterialComponent>(std::string("material:planet_" + shader));
//r->addMaterial(materialPlanet);
r->addTexture(tex1, 0);
if (!tex2.empty())
r->addTexture(tex2, 1);
if (!tex3.empty())
r->addTexture(tex3, 2);
if (!tex4.empty())
r->addTexture(tex4, 3);
e->addComponent<Component::RotationForce>(glm::vec3(0, orbitSpeed, 0));
p->getComponent<Component::GraphNode>()->addSon(e);
p->addComponent<Component::RotationForce>(glm::vec3(0, rotSpeed, 0));
return (p);
}
bool DemoScene::userStart()
{
// System Tests
//
//
addSystem<RotationForceSystem>(0);
addSystem<MeshRendererSystem>(0);
addSystem<GraphNodeSystem>(100);
addSystem<TrackBallSystem>(150);
addSystem<CameraSystem>(200);
//
//
// end System Test
std::string perModelVars[] =
{
"model"
};
std::string perFrameVars[] =
{
"projection",
"view",
"light",
"time"
};
OpenGLTools::Shader &s = _engine.getInstance<Renderer>().addShader("earth",
"./Shaders/earth.vp",
"./Shaders/earth.fp");
//.bindActiveTexture("fDayTexture", 0)
//.bindActiveTexture("fNightTexture", 1)
//.bindActiveTexture("fClouds", 2)
//.bindActiveTexture("fBump", 3);
_engine.getInstance<Renderer>().addUniform("PerFrame")
.init(&s, "PerFrame", perFrameVars);
_engine.getInstance<Renderer>().addUniform("PerModel")
.init(&s, "PerModel", perModelVars);
_engine.getInstance<Renderer>().addShader("basic", "Shaders/basic.vp", "Shaders/basic.fp", "Shaders/tesselation.gp");
_engine.getInstance<Renderer>().addShader("basicLight", "Shaders/light.vp", "Shaders/light.fp");
_engine.getInstance<Renderer>().addShader("bump", "Shaders/bump.vp", "Shaders/bump.fp");
//.bindActiveTexture("fTexture", 0)
//.bindActiveTexture("fBump", 1);
_engine.getInstance<Renderer>().addShader("fboToScreen", "Shaders/fboToScreen.vp", "Shaders/fboToScreen.fp");
_engine.getInstance<Renderer>().addShader("brightnessFilter", "Shaders/brightnessFilter.vp", "Shaders/brightnessFilter.fp");
_engine.getInstance<Renderer>().addShader("blurY", "Shaders/brightnessFilter.vp", "Shaders/blur1.fp");
_engine.getInstance<Renderer>().getShader("basic")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();
_engine.getInstance<Renderer>().getShader("basicLight")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();
_engine.getInstance<Renderer>().getShader("bump")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(2).build();
_engine.getInstance<Renderer>().getShader("fboToScreen")->addTarget(GL_COLOR_ATTACHMENT0)
.addLayer(GL_COLOR_ATTACHMENT0).build();
_engine.getInstance<Renderer>().getShader("earth")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(4).build();
_engine.getInstance<Renderer>().getShader("brightnessFilter")->addTarget(GL_COLOR_ATTACHMENT1)
.addLayer(GL_COLOR_ATTACHMENT0).build();
_engine.getInstance<Renderer>().getShader("blurY")->addTarget(GL_COLOR_ATTACHMENT2)
.addLayer(GL_COLOR_ATTACHMENT0).addLayer(GL_COLOR_ATTACHMENT1).build();
_engine.getInstance<Renderer>().getUniform("PerFrame")->setUniform("light", glm::vec4(0, 0, 0, 1));
_engine.getInstance<Renderer>().bindShaderToUniform("basicLight", "PerFrame", "PerFrame");
_engine.getInstance<Renderer>().bindShaderToUniform("basicLight", "PerModel", "PerModel");
_engine.getInstance<Renderer>().bindShaderToUniform("basic", "PerFrame", "PerFrame");
_engine.getInstance<Renderer>().bindShaderToUniform("basic", "PerModel", "PerModel");
_engine.getInstance<Renderer>().bindShaderToUniform("earth", "PerFrame", "PerFrame");
_engine.getInstance<Renderer>().bindShaderToUniform("earth", "PerModel", "PerModel");
_engine.getInstance<Renderer>().bindShaderToUniform("bump", "PerFrame", "PerFrame");
_engine.getInstance<Renderer>().bindShaderToUniform("bump", "PerModel", "PerModel");
_engine.getInstance<Resources::ResourceManager>().addResource("model:ball", new Resources::SharedMesh(), "./Assets/ball.obj");
SmartPointer<Resources::Texture> toRepeat = new Resources::Texture();
toRepeat->setWrapMode(GL_REPEAT);
_engine.getInstance<Resources::ResourceManager>().addResource("texture:sun", new Resources::Texture(), "./Assets/SunTexture.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:earth", new Resources::Texture(), "./Assets/EarthTexture.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:earthBump", new Resources::Texture(), "./Assets/EarthTextureBump.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:earthNight", new Resources::Texture(), "./Assets/EarthNightTexture.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:earthClouds", toRepeat, "./Assets/EarthClouds.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:sun", new Resources::Texture(), "./Assets/SunTexture.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:moon", new Resources::Texture(), "./Assets/MoonTexture.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:moonBump", new Resources::Texture(), "./Assets/MoonNormalMap.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("cubemap:space", new Resources::CubeMap(), "./Assets/skyboxSpace");
auto sun = createPlanet(0, 0, glm::vec3(0), glm::vec3(100), "basic", "texture:sun");
auto earth = createPlanet(7, 20, glm::vec3(300, 0, 0), glm::vec3(20), "earth", "texture:earth", "texture:earthNight", "texture:earthClouds", "texture:earthBump");
auto moon = createPlanet(0, 10, glm::vec3(5, 0, 0), glm::vec3(0.5), "bump", "texture:moon", "texture:moonBump");
earth->getComponent<Component::GraphNode>()->getSonsBegin()->get()->getComponent<Component::GraphNode>()->addSon(moon);
// Generating a lot of planet for performance test
//
//
{
unsigned int nbPlanet = 500;
Handle planets[500];
for (unsigned int i = 0; i < nbPlanet; ++i)
{
planets[i] = createPlanet((std::rand() % 200) / 100.0f
, (std::rand() % 200) / 100.0f,
glm::vec3(std::rand() % 300 - 150, std::rand() % 300 - 150, std::rand() % 300 - 150),
glm::vec3(std::rand() % 10 + 10), "basic", "texture:sun");
if (i == 0)
sun->getComponent<Component::GraphNode>()->addSon(planets[i]);
else
planets[i - 1]->getComponent<Component::GraphNode>()->addSon(planets[i]);
}
}
//
//
// END : Generating a lot of planet for performance test
// --
// Setting camera with skybox
// --
auto camera = _engine.getInstance<EntityManager>().createEntity();
camera->addComponent<Component::GraphNode>();
auto cameraComponent = camera->addComponent<Component::CameraComponent>();
auto trackBall = camera->addComponent<Component::TrackBall>( *(earth->getComponent<Component::GraphNode>()->getSonsBegin()), 50.0f, 3.0f, 1.0f);
std::string vars[] =
{
"projection",
"view"
};
OpenGLTools::Shader &sky = _engine.getInstance<Renderer>().addShader("cubemapShader", "Shaders/cubemap.vp", "Shaders/cubemap.fp");
_engine.getInstance<Renderer>().getShader("cubemapShader")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();
_engine.getInstance<Renderer>().addUniform("cameraUniform").
init(&sky, "cameraUniform", vars);
_engine.getInstance<Renderer>().bindShaderToUniform("cubemapShader", "cameraUniform", "cameraUniform");
cameraComponent->attachSkybox("cubemap:space", "cubemapShader");
// Compute shader Tests
//
//
//OpenGLTools::ComputeShader *cs = new OpenGLTools::ComputeShader();
//cs->init(File("../GameEngine/Shaders/test.cp"));
//cs->use();
//glDispatchCompute(512/16, 512/16, 1);
//
//
// End compute shader test
return (true);
}
bool DemoScene::userUpdate(double time)
{
if (_engine.getInstance<Input>().getInput(SDLK_ESCAPE) ||
_engine.getInstance<Input>().getInput(SDL_QUIT))
return (false);
return (true);
}
<commit_msg>last benshmark before merge<commit_after>#include <glm/gtc/matrix_transform.hpp>
#include "Core/Engine.hh"
#include "Core/Renderer.hh"
#include "DemoScene.hh"
#include "ResourceManager/SharedMesh.hh"
#include "ResourceManager/Texture.hh"
#include "ResourceManager/CubeMap.hh"
#include "Components/RotationForce.hh"
#include "Components/MaterialComponent.h"
#include <Components/CameraComponent.hh>
#include <Components/TrackBallComponent.hpp>
#include <OpenGL/ComputeShader.hh>
#include <Systems/RotationForceSystem.hpp>
#include <Systems/MeshRenderSystem.h>
#include <Systems/GraphNodeSystem.hpp>
#include <Systems/CameraSystem.hpp>
#include <Systems/TrackBallSystem.hpp>
#include "ResourceManager/ResourceManager.hh"
#include <Core/Engine.hh>
#include <Entities/EntityManager.h>
#include <SDL\SDL.h>
DemoScene::DemoScene(Engine &engine) : AScene(engine)
{
}
DemoScene::~DemoScene(void)
{
}
Handle DemoScene::createPlanet(float rotSpeed, float orbitSpeed,
glm::vec3 &pos, glm::vec3 &scale,
std::string const &shader,
std::string const &tex1, std::string const &tex2, std::string const &tex3,
std::string const &tex4)
{
auto &m = _engine.getInstance<EntityManager>();
auto p = m.createEntity();
auto e = m.createEntity();
p->addComponent<Component::GraphNode>();
e->addComponent<Component::GraphNode>();
e->setLocalTransform() = glm::translate(e->getLocalTransform(), pos);
e->setLocalTransform() = glm::scale(e->getLocalTransform(), scale);
SmartPointer<Component::MeshRenderer> r = e->addComponent<Component::MeshRenderer>("model:ball");
SmartPointer<Material> materialPlanet = _engine.getInstance<Renderer>().getMaterialManager().createMaterial("material:planet_" + shader);
materialPlanet->pushShader(shader);
e->addComponent<Component::MaterialComponent>(std::string("material:planet_" + shader));
//r->addMaterial(materialPlanet);
r->addTexture(tex1, 0);
if (!tex2.empty())
r->addTexture(tex2, 1);
if (!tex3.empty())
r->addTexture(tex3, 2);
if (!tex4.empty())
r->addTexture(tex4, 3);
e->addComponent<Component::RotationForce>(glm::vec3(0, orbitSpeed, 0));
p->getComponent<Component::GraphNode>()->addSon(e);
p->addComponent<Component::RotationForce>(glm::vec3(0, rotSpeed, 0));
return (p);
}
bool DemoScene::userStart()
{
// System Tests
//
//
addSystem<RotationForceSystem>(0);
addSystem<MeshRendererSystem>(0);
addSystem<GraphNodeSystem>(100);
addSystem<TrackBallSystem>(150);
addSystem<CameraSystem>(200);
//
//
// end System Test
std::string perModelVars[] =
{
"model"
};
std::string perFrameVars[] =
{
"projection",
"view",
"light",
"time"
};
OpenGLTools::Shader &s = _engine.getInstance<Renderer>().addShader("earth",
"./Shaders/earth.vp",
"./Shaders/earth.fp");
//.bindActiveTexture("fDayTexture", 0)
//.bindActiveTexture("fNightTexture", 1)
//.bindActiveTexture("fClouds", 2)
//.bindActiveTexture("fBump", 3);
_engine.getInstance<Renderer>().addUniform("PerFrame")
.init(&s, "PerFrame", perFrameVars);
_engine.getInstance<Renderer>().addUniform("PerModel")
.init(&s, "PerModel", perModelVars);
_engine.getInstance<Renderer>().addShader("basic", "Shaders/basic.vp", "Shaders/basic.fp", "Shaders/tesselation.gp");
_engine.getInstance<Renderer>().addShader("basicLight", "Shaders/light.vp", "Shaders/light.fp");
_engine.getInstance<Renderer>().addShader("bump", "Shaders/bump.vp", "Shaders/bump.fp");
//.bindActiveTexture("fTexture", 0)
//.bindActiveTexture("fBump", 1);
_engine.getInstance<Renderer>().addShader("fboToScreen", "Shaders/fboToScreen.vp", "Shaders/fboToScreen.fp");
_engine.getInstance<Renderer>().addShader("brightnessFilter", "Shaders/brightnessFilter.vp", "Shaders/brightnessFilter.fp");
_engine.getInstance<Renderer>().addShader("blurY", "Shaders/brightnessFilter.vp", "Shaders/blur1.fp");
_engine.getInstance<Renderer>().getShader("basic")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();
_engine.getInstance<Renderer>().getShader("basicLight")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();
_engine.getInstance<Renderer>().getShader("bump")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(2).build();
_engine.getInstance<Renderer>().getShader("fboToScreen")->addTarget(GL_COLOR_ATTACHMENT0)
.addLayer(GL_COLOR_ATTACHMENT0).build();
_engine.getInstance<Renderer>().getShader("earth")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(4).build();
_engine.getInstance<Renderer>().getShader("brightnessFilter")->addTarget(GL_COLOR_ATTACHMENT1)
.addLayer(GL_COLOR_ATTACHMENT0).build();
_engine.getInstance<Renderer>().getShader("blurY")->addTarget(GL_COLOR_ATTACHMENT2)
.addLayer(GL_COLOR_ATTACHMENT0).addLayer(GL_COLOR_ATTACHMENT1).build();
_engine.getInstance<Renderer>().getUniform("PerFrame")->setUniform("light", glm::vec4(0, 0, 0, 1));
_engine.getInstance<Renderer>().bindShaderToUniform("basicLight", "PerFrame", "PerFrame");
_engine.getInstance<Renderer>().bindShaderToUniform("basicLight", "PerModel", "PerModel");
_engine.getInstance<Renderer>().bindShaderToUniform("basic", "PerFrame", "PerFrame");
_engine.getInstance<Renderer>().bindShaderToUniform("basic", "PerModel", "PerModel");
_engine.getInstance<Renderer>().bindShaderToUniform("earth", "PerFrame", "PerFrame");
_engine.getInstance<Renderer>().bindShaderToUniform("earth", "PerModel", "PerModel");
_engine.getInstance<Renderer>().bindShaderToUniform("bump", "PerFrame", "PerFrame");
_engine.getInstance<Renderer>().bindShaderToUniform("bump", "PerModel", "PerModel");
_engine.getInstance<Resources::ResourceManager>().addResource("model:ball", new Resources::SharedMesh(), "./Assets/ball.obj");
SmartPointer<Resources::Texture> toRepeat = new Resources::Texture();
toRepeat->setWrapMode(GL_REPEAT);
_engine.getInstance<Resources::ResourceManager>().addResource("texture:sun", new Resources::Texture(), "./Assets/SunTexture.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:earth", new Resources::Texture(), "./Assets/EarthTexture.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:earthBump", new Resources::Texture(), "./Assets/EarthTextureBump.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:earthNight", new Resources::Texture(), "./Assets/EarthNightTexture.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:earthClouds", toRepeat, "./Assets/EarthClouds.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:sun", new Resources::Texture(), "./Assets/SunTexture.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:moon", new Resources::Texture(), "./Assets/MoonTexture.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("texture:moonBump", new Resources::Texture(), "./Assets/MoonNormalMap.tga");
_engine.getInstance<Resources::ResourceManager>().addResource("cubemap:space", new Resources::CubeMap(), "./Assets/skyboxSpace");
auto sun = createPlanet(0, 0, glm::vec3(0), glm::vec3(100), "basic", "texture:sun");
auto earth = createPlanet(7, 20, glm::vec3(300, 0, 0), glm::vec3(20), "earth", "texture:earth", "texture:earthNight", "texture:earthClouds", "texture:earthBump");
auto moon = createPlanet(0, 10, glm::vec3(5, 0, 0), glm::vec3(0.5), "bump", "texture:moon", "texture:moonBump");
earth->getComponent<Component::GraphNode>()->getSonsBegin()->get()->getComponent<Component::GraphNode>()->addSon(moon);
// Generating a lot of planet for performance test
//
//
{
unsigned int nbPlanet = 10000;
Handle planets[10000];
for (unsigned int i = 0; i < nbPlanet; ++i)
{
planets[i] = createPlanet((std::rand() % 200) / 100.0f
, (std::rand() % 200) / 100.0f,
glm::vec3(std::rand() % 300 - 150, std::rand() % 300 - 150, std::rand() % 300 - 150),
glm::vec3(std::rand() % 10 + 10), "basic", "texture:sun");
if (i == 0)
sun->getComponent<Component::GraphNode>()->addSon(planets[i]);
else
planets[i - 1]->getComponent<Component::GraphNode>()->addSon(planets[i]);
}
}
//
//
// END : Generating a lot of planet for performance test
// --
// Setting camera with skybox
// --
auto camera = _engine.getInstance<EntityManager>().createEntity();
camera->addComponent<Component::GraphNode>();
auto cameraComponent = camera->addComponent<Component::CameraComponent>();
auto trackBall = camera->addComponent<Component::TrackBall>( *(earth->getComponent<Component::GraphNode>()->getSonsBegin()), 50.0f, 3.0f, 1.0f);
std::string vars[] =
{
"projection",
"view"
};
OpenGLTools::Shader &sky = _engine.getInstance<Renderer>().addShader("cubemapShader", "Shaders/cubemap.vp", "Shaders/cubemap.fp");
_engine.getInstance<Renderer>().getShader("cubemapShader")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();
_engine.getInstance<Renderer>().addUniform("cameraUniform").
init(&sky, "cameraUniform", vars);
_engine.getInstance<Renderer>().bindShaderToUniform("cubemapShader", "cameraUniform", "cameraUniform");
cameraComponent->attachSkybox("cubemap:space", "cubemapShader");
// Compute shader Tests
//
//
//OpenGLTools::ComputeShader *cs = new OpenGLTools::ComputeShader();
//cs->init(File("../GameEngine/Shaders/test.cp"));
//cs->use();
//glDispatchCompute(512/16, 512/16, 1);
//
//
// End compute shader test
return (true);
}
bool DemoScene::userUpdate(double time)
{
if (_engine.getInstance<Input>().getInput(SDLK_ESCAPE) ||
_engine.getInstance<Input>().getInput(SDL_QUIT))
return (false);
return (true);
}
<|endoftext|> |
<commit_before>#include "opencl_utils.h"
namespace ocl {
int global_variable = 66;
const void Init() {}
const std::string DeviceTypeString(cl_device_type type) {
int ss = type;
std::string s = "";
if (type & CL_DEVICE_TYPE_CPU) {
s += "CL_DEVICE_TYPE_CPU ";
}
if (type & CL_DEVICE_TYPE_GPU) {
s += "CL_DEVICE_TYPE_GPU ";
}
if (type & CL_DEVICE_TYPE_ACCELERATOR) {
s += "CL_DEVICE_TYPE_ACCELERATOR ";
}
if (type & CL_DEVICE_TYPE_DEFAULT) {
s += "CL_DEVICE_TYPE_DEFAULT ";
}
return s;
}
}
std::string readable_fs(unsigned int sz /*in bytes*/) {
float size = (float)sz;
unsigned int kb = 1024;
unsigned int mb = kb * 1024;
unsigned int gb = mb * 1024;
std::string s = "";
float minus = 0;
if (size > gb) {
float a = floor(size / gb);
minus += a * gb;
s += std::to_string((int)a);
s += "GB, ";
}
if (size > mb) {
float a = floor((size - minus) / mb);
minus += a * mb;
s += std::to_string((int)a);
s += "MB, ";
}
if (size > kb) {
float a = floor((size - minus) / kb);
minus += a * kb;
s += std::to_string((int)a);
s += "KB, ";
}
s += std::to_string((int)(size - minus));
s += "B (";
s += std::to_string(sz);
s += ")";
return s;
}<commit_msg>Linux needs maths<commit_after>#include "opencl_utils.h"
#include <math.h>
namespace ocl {
int global_variable = 66;
const void Init() {}
const std::string DeviceTypeString(cl_device_type type) {
int ss = type;
std::string s = "";
if (type & CL_DEVICE_TYPE_CPU) {
s += "CL_DEVICE_TYPE_CPU ";
}
if (type & CL_DEVICE_TYPE_GPU) {
s += "CL_DEVICE_TYPE_GPU ";
}
if (type & CL_DEVICE_TYPE_ACCELERATOR) {
s += "CL_DEVICE_TYPE_ACCELERATOR ";
}
if (type & CL_DEVICE_TYPE_DEFAULT) {
s += "CL_DEVICE_TYPE_DEFAULT ";
}
return s;
}
}
std::string readable_fs(unsigned int sz /*in bytes*/) {
float size = (float)sz;
unsigned int kb = 1024;
unsigned int mb = kb * 1024;
unsigned int gb = mb * 1024;
std::string s = "";
float minus = 0;
if (size > gb) {
float a = floor(size / gb);
minus += a * gb;
s += std::to_string((int)a);
s += "GB, ";
}
if (size > mb) {
float a = floor((size - minus) / mb);
minus += a * mb;
s += std::to_string((int)a);
s += "MB, ";
}
if (size > kb) {
float a = floor((size - minus) / kb);
minus += a * kb;
s += std::to_string((int)a);
s += "KB, ";
}
s += std::to_string((int)(size - minus));
s += "B (";
s += std::to_string(sz);
s += ")";
return s;
}<|endoftext|> |
<commit_before>/*
Crystal Space 3ds2lev xml writer
Copyright (C) 2001,2002 by Luca Pancallo and Matze Braun
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
// includes for lib3ds
#include <lib3ds/camera.h>
#include <lib3ds/file.h>
#include <lib3ds/io.h>
#include <lib3ds/light.h>
#include <lib3ds/material.h>
#include <lib3ds/matrix.h>
#include <lib3ds/mesh.h>
#include <lib3ds/node.h>
#include <lib3ds/vector.h>
#include <csutil/scfstr.h>
#include "levelwriter.h"
CS_IMPLEMENT_APPLICATION
enum
{
FLAG_VERBOSE = 0x0001,
FLAG_LIST = 0x0002, /* List all objects in this 3ds */
};
enum xyzmode
{
MODE_XYZ = 0,
MODE_XZY = 1,
MODE_YXZ = 2,
MODE_YZX = 3,
MODE_ZXY = 4,
MODE_ZYX = 5
};
/**
* Simply switch x,y,z coord depending on the selected MODE_XYZ
*/
void ConvertXYZ (xyzmode mode_xyz, float& x, float& y, float& z)
{
float sw;
switch (mode_xyz)
{
case MODE_XYZ: return;
case MODE_XZY: sw = y; y = z; z = sw; return;
case MODE_YXZ: sw = x; x = y; y = sw; return;
case MODE_YZX: sw = x; x = y; y = z; z = sw; return;
case MODE_ZXY: sw = x; x = z; z = y; y = sw; return;
case MODE_ZYX: sw = x; x = z; z = sw; return;
}
}
/**
* Swap x,y,z coord depending on the selected MODE_XYZ
* All vertexes and triangles are affected.
* All lights are affected.
*/
void Lib3dsConvertXYZ (Lib3dsFile* p3dsFile, xyzmode mode)
{
// TODO: should be done for -center option. actually not supported.
//ConvertXYZ (scene->centre.x, scene->centre.y, scene->centre.z);
// a vertex
Lib3dsPoint *pCurPoint;
// used for coords of vertex
float *xyz;
// set the current mesh to the first in the file
Lib3dsMesh *p3dsMesh = p3dsFile->meshes;
// as long as we have a valid mesh...
while( p3dsMesh )
{
// get the number of vertices in the current mesh
int numVertices = p3dsMesh->points;
int i;
// vertexes pointer
pCurPoint = p3dsMesh->pointL;
for ( i = 0 ; i < numVertices ; i++ )
{
// index to the position on the list using index
xyz = pCurPoint->pos;
// Convert the vertex coords
ConvertXYZ (mode, xyz[0], xyz[1], xyz[2]);
// go to next vertex
pCurPoint++;
}
// we must convert also triangles or the texture will be flipped
// get the triangle count and go to the first triangle
int numTriangles = p3dsMesh->faces;
Lib3dsFace *pCurFace = p3dsMesh->faceL;
// convert each triangle
for ( i = 0 ; i < numTriangles ; i++ ) {
float v1 = pCurFace->points[0];
float v2 = pCurFace->points[1];
float v3 = pCurFace->points[2];
ConvertXYZ (mode, v1, v2, v3);
pCurFace->points[0] = (short unsigned int)v1;
pCurFace->points[1] = (short unsigned int)v2;
pCurFace->points[2] = (short unsigned int)v3;
// go to next triangle
pCurFace++;
}
// go to next mesh
p3dsMesh = p3dsMesh->next;
}
// swap coords of lights
Lib3dsLight* light;
for (light = p3dsFile->lights; light; light = light->next)
{
ConvertXYZ (mode, light->position[0],
light->position[1],
light->position[2]);
}
// swap coords of cameras
Lib3dsCamera *camera;
for (camera = p3dsFile->cameras; camera; camera = camera->next)
{
ConvertXYZ (mode, camera->position[0],
camera->position[1],
camera->position[2]);
ConvertXYZ (mode, camera->target[0],
camera->target[1],
camera->target[2]);
}
}
/**
* Main function
*/
int main (int argc, char * argv[])
{
char * infn=0, * outfn=0;
float xscale = 1, yscale = 1, zscale = 1;
float xrelocate = 0, yrelocate = 0, zrelocate = 0;
xyzmode mode_xyz = MODE_XZY;
int flags = 0;
LevelWriter writer;
flags = 0;
// default to lower left texture origin
writer.SetFlags (LevelWriter::FLAG_SWAP_V);
argc--;
argv++;
if(!argc)
{
fprintf (stderr,
"3D Studio native objectfile converter v2.0\n"
"originally by Mats Byggmastar 1996 Espoo, Finland.\n"
"This version is for Crystal Space and heavily modified by\n"
"Jorrit Tyberghein, Luca Pancallo and Matze Braun.\n"
"Use: %s [params...] inputfile.3ds\n"
"params:\n"
" -o file Name of the output file\n"
" -v Verbose mode on\n"
" -l Don't convert but list objects in 3ds file\n"
" -c optimize (combine every two triangles into polys)\n"
" -r x y z Relocate objects (x,y,z = floats)\n"
" -pl Make polygons lit\n"
" -3 Output 3D sprite instead of level\n"
" -tl Make texture origin lower left (default)\n"
" -b Use clearzbuf and clearscreen settings\n"
" -xyz Convert model xyz -> CS xyz\n"
" -xzy Convert model xyz -> CS xzy (default)\n"
" -yxz Convert model xyz -> CS yxz\n"
" -yzx Convert model xyz -> CS yzx\n"
" -zxy Convert model xyz -> CS zxy\n"
" -zyx Convert model xyz -> CS zyx\n",
argv[-1]);
return 1;
}
// Get the parameters and filenames
for (int n=0; n<argc; n++)
{
if (argv[n][0] == '-' || argv[n][0] == '/')
{
switch (toupper(argv[n][1]))
{
case 'O':
if (n+1<argc)
outfn=argv[++n];
else
{
fprintf (stderr, "Missing outputfile name!\n");
return 1;
}
break;
case 'R':
if (n+3<argc)
{
xrelocate = atof(argv[++n]);
yrelocate = atof(argv[++n]);
zrelocate = atof(argv[++n]);
}
else
{
fprintf(stderr, "Missing relocate value!\n");
return 1;
}
break;
case 'S':
if (n+3<argc)
{
xscale = atof(argv[++n]);
yscale = atof(argv[++n]);
zscale = atof(argv[++n]);
}
else
{
fprintf(stderr, "Missing scale value!\n");
return 1;
}
break;
case 'P':
if (toupper (argv[n][2]) == 'L')
{
writer.SetFlags (LevelWriter::FLAG_LIGHTING);
}
break;
case 'V':
writer.SetFlags(LevelWriter::FLAG_VERBOSE);
flags |= FLAG_VERBOSE;
break;
case 'T':
if (toupper (argv[n][2]) == 'L')
writer.SetFlags (LevelWriter::FLAG_SWAP_V);
break;
case '3':
writer.SetFlags (LevelWriter::FLAG_SPRITE);
break;
case 'L':
flags |= FLAG_LIST;
break;
case 'B':
writer.SetFlags (LevelWriter::FLAG_CLEARZBUFCLEARSCREEN);
break;
case 'X':
if (toupper (argv[n][2]) == 'Y')
mode_xyz = MODE_XYZ;
else
mode_xyz = MODE_XZY;
break;
case 'Y':
if (toupper (argv[n][2]) == 'X')
mode_xyz = MODE_YXZ;
else
mode_xyz = MODE_YZX;
break;
case 'Z':
if (toupper (argv[n][2]) == 'X')
mode_xyz = MODE_ZXY;
else
mode_xyz = MODE_ZYX;
break;
case 'C':
writer.SetFlags(LevelWriter::FLAG_COMBINEFACES);
writer.SetFlags(LevelWriter::FLAG_REMOVEDOUBLEVERTICES);
break;
default:
fprintf (stderr, "Bad parameter: %s\n",argv[n]);
return 1;
}
}
else
{
if (!infn)
infn = argv[n];
else
{
fprintf (stderr, "Too many filenames (can only convert 1 file at once!\n");
return 1;
}
}
}
if (!infn)
{
fprintf (stderr, "No inputfile specified!\n");
return 1;
}
// <--------- finished parsing parameters ----------->
// Read inputfile
Lib3dsFile* file3ds = lib3ds_file_load(infn);
if (!file3ds ) {
fprintf (stderr, "Failed to open %s\n", infn);
return 1;
}
// swap xyz if requested
if (mode_xyz != MODE_XYZ)
Lib3dsConvertXYZ (file3ds, mode_xyz);
// Print some interesting information about what we have
if (flags & FLAG_LIST || flags & FLAG_VERBOSE)
{
// fprintf (stderr, "3DS data size: %ld byte\n", size);
fprintf (stderr, "3DS name: %s\n", file3ds->name);
fprintf (stderr, "lights: %s\n", file3ds->lights ? "yes" : "no");
fprintf (stderr, "object-name faces vertices maps matrix\n");
// set the current mesh to the first in the file
Lib3dsMesh* mesh;
for (mesh = file3ds->meshes; mesh; mesh = mesh->next)
{
// get the numbers in the current mesh
fprintf(stderr, "===================================================\n");
fprintf(stderr, "%-14s %5ld %5ld %5d %s\n",
mesh->name, mesh->faces, mesh->points, -1, " ");
}
}
// setup writer
writer.Set3dsFile (file3ds);
writer.SetScale (xscale, yscale, zscale);
writer.SetTranslate (xrelocate, yrelocate, zrelocate);
if (flags & FLAG_VERBOSE)
fprintf (stderr, "Writing output in CS format...");
csRef<iDocument> document = writer.WriteDocument ();
iString* str = new scfString;
document->Write (str);
if (outfn)
{
// Write file to disk
FILE* outfile = fopen (outfn, "w");
if (!outfile)
{
fprintf (stderr, "Couldn't open output file '%s'!\n", outfn);
return 1;
}
fwrite (str->GetData(), 1, str->Length(), outfile);
fclose (outfile);
}
else
{
// Write file to stdout
printf ("%s", str->GetData());
}
if (flags & FLAG_VERBOSE)
fprintf (stderr, "done! \n");
return 0;
}
<commit_msg>missed a line<commit_after>/*
Crystal Space 3ds2lev xml writer
Copyright (C) 2001,2002 by Luca Pancallo and Matze Braun
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
// includes for lib3ds
#include <lib3ds/camera.h>
#include <lib3ds/file.h>
#include <lib3ds/io.h>
#include <lib3ds/light.h>
#include <lib3ds/material.h>
#include <lib3ds/matrix.h>
#include <lib3ds/mesh.h>
#include <lib3ds/node.h>
#include <lib3ds/vector.h>
#include <csutil/scfstr.h>
#include "levelwriter.h"
CS_IMPLEMENT_APPLICATION
enum
{
FLAG_VERBOSE = 0x0001,
FLAG_LIST = 0x0002, /* List all objects in this 3ds */
};
enum xyzmode
{
MODE_XYZ = 0,
MODE_XZY = 1,
MODE_YXZ = 2,
MODE_YZX = 3,
MODE_ZXY = 4,
MODE_ZYX = 5
};
/**
* Simply switch x,y,z coord depending on the selected MODE_XYZ
*/
void ConvertXYZ (xyzmode mode_xyz, float& x, float& y, float& z)
{
float sw;
switch (mode_xyz)
{
case MODE_XYZ: return;
case MODE_XZY: sw = y; y = z; z = sw; return;
case MODE_YXZ: sw = x; x = y; y = sw; return;
case MODE_YZX: sw = x; x = y; y = z; z = sw; return;
case MODE_ZXY: sw = x; x = z; z = y; y = sw; return;
case MODE_ZYX: sw = x; x = z; z = sw; return;
}
}
/**
* Swap x,y,z coord depending on the selected MODE_XYZ
* All vertexes and triangles are affected.
* All lights are affected.
*/
void Lib3dsConvertXYZ (Lib3dsFile* p3dsFile, xyzmode mode)
{
// TODO: should be done for -center option. actually not supported.
//ConvertXYZ (scene->centre.x, scene->centre.y, scene->centre.z);
// a vertex
Lib3dsPoint *pCurPoint;
// used for coords of vertex
float *xyz;
// set the current mesh to the first in the file
Lib3dsMesh *p3dsMesh = p3dsFile->meshes;
// as long as we have a valid mesh...
while( p3dsMesh )
{
// get the number of vertices in the current mesh
int numVertices = p3dsMesh->points;
int i;
// vertexes pointer
pCurPoint = p3dsMesh->pointL;
for ( i = 0 ; i < numVertices ; i++ )
{
// index to the position on the list using index
xyz = pCurPoint->pos;
// Convert the vertex coords
ConvertXYZ (mode, xyz[0], xyz[1], xyz[2]);
// go to next vertex
pCurPoint++;
}
// we must convert also triangles or the texture will be flipped
// get the triangle count and go to the first triangle
int numTriangles = p3dsMesh->faces;
Lib3dsFace *pCurFace = p3dsMesh->faceL;
// convert each triangle
for ( i = 0 ; i < numTriangles ; i++ ) {
float v1 = pCurFace->points[0];
float v2 = pCurFace->points[1];
float v3 = pCurFace->points[2];
ConvertXYZ (mode, v1, v2, v3);
pCurFace->points[0] = (short unsigned int)v1;
pCurFace->points[1] = (short unsigned int)v2;
pCurFace->points[2] = (short unsigned int)v3;
// go to next triangle
pCurFace++;
}
// go to next mesh
p3dsMesh = p3dsMesh->next;
}
// swap coords of lights
Lib3dsLight* light;
for (light = p3dsFile->lights; light; light = light->next)
{
ConvertXYZ (mode, light->position[0],
light->position[1],
light->position[2]);
}
// swap coords of cameras
Lib3dsCamera *camera;
for (camera = p3dsFile->cameras; camera; camera = camera->next)
{
ConvertXYZ (mode, camera->position[0],
camera->position[1],
camera->position[2]);
ConvertXYZ (mode, camera->target[0],
camera->target[1],
camera->target[2]);
}
}
/**
* Main function
*/
int main (int argc, char * argv[])
{
char * infn=0, * outfn=0;
float xscale = 1, yscale = 1, zscale = 1;
float xrelocate = 0, yrelocate = 0, zrelocate = 0;
xyzmode mode_xyz = MODE_XZY;
int flags = 0;
LevelWriter writer;
flags = 0;
// default to lower left texture origin
writer.SetFlags (LevelWriter::FLAG_SWAP_V);
argc--;
argv++;
if(!argc)
{
fprintf (stderr,
"3D Studio native objectfile converter v2.0\n"
"originally by Mats Byggmastar 1996 Espoo, Finland.\n"
"This version is for Crystal Space and heavily modified by\n"
"Jorrit Tyberghein, Luca Pancallo and Matze Braun.\n"
"Use: %s [params...] inputfile.3ds\n"
"params:\n"
" -o file Name of the output file\n"
" -v Verbose mode on\n"
" -l Don't convert but list objects in 3ds file\n"
" -c optimize (combine every two triangles into polys)\n"
" -r x y z Relocate objects (x,y,z = floats)\n"
" -s x y t Scale objects (x,y,z = floats)\n"
" -pl Make polygons lit\n"
" -3 Output 3D sprite instead of level\n"
" -tl Make texture origin lower left (default)\n"
" -b Use clearzbuf and clearscreen settings\n"
" -xyz Convert model xyz -> CS xyz\n"
" -xzy Convert model xyz -> CS xzy (default)\n"
" -yxz Convert model xyz -> CS yxz\n"
" -yzx Convert model xyz -> CS yzx\n"
" -zxy Convert model xyz -> CS zxy\n"
" -zyx Convert model xyz -> CS zyx\n",
argv[-1]);
return 1;
}
// Get the parameters and filenames
for (int n=0; n<argc; n++)
{
if (argv[n][0] == '-' || argv[n][0] == '/')
{
switch (toupper(argv[n][1]))
{
case 'O':
if (n+1<argc)
outfn=argv[++n];
else
{
fprintf (stderr, "Missing outputfile name!\n");
return 1;
}
break;
case 'R':
if (n+3<argc)
{
xrelocate = atof(argv[++n]);
yrelocate = atof(argv[++n]);
zrelocate = atof(argv[++n]);
}
else
{
fprintf(stderr, "Missing relocate value!\n");
return 1;
}
break;
case 'S':
if (n+3<argc)
{
xscale = atof(argv[++n]);
yscale = atof(argv[++n]);
zscale = atof(argv[++n]);
}
else
{
fprintf(stderr, "Missing scale value!\n");
return 1;
}
break;
case 'P':
if (toupper (argv[n][2]) == 'L')
{
writer.SetFlags (LevelWriter::FLAG_LIGHTING);
}
break;
case 'V':
writer.SetFlags(LevelWriter::FLAG_VERBOSE);
flags |= FLAG_VERBOSE;
break;
case 'T':
if (toupper (argv[n][2]) == 'L')
writer.SetFlags (LevelWriter::FLAG_SWAP_V);
break;
case '3':
writer.SetFlags (LevelWriter::FLAG_SPRITE);
break;
case 'L':
flags |= FLAG_LIST;
break;
case 'B':
writer.SetFlags (LevelWriter::FLAG_CLEARZBUFCLEARSCREEN);
break;
case 'X':
if (toupper (argv[n][2]) == 'Y')
mode_xyz = MODE_XYZ;
else
mode_xyz = MODE_XZY;
break;
case 'Y':
if (toupper (argv[n][2]) == 'X')
mode_xyz = MODE_YXZ;
else
mode_xyz = MODE_YZX;
break;
case 'Z':
if (toupper (argv[n][2]) == 'X')
mode_xyz = MODE_ZXY;
else
mode_xyz = MODE_ZYX;
break;
case 'C':
writer.SetFlags(LevelWriter::FLAG_COMBINEFACES);
writer.SetFlags(LevelWriter::FLAG_REMOVEDOUBLEVERTICES);
break;
default:
fprintf (stderr, "Bad parameter: %s\n",argv[n]);
return 1;
}
}
else
{
if (!infn)
infn = argv[n];
else
{
fprintf (stderr, "Too many filenames (can only convert 1 file at once!\n");
return 1;
}
}
}
if (!infn)
{
fprintf (stderr, "No inputfile specified!\n");
return 1;
}
// <--------- finished parsing parameters ----------->
// Read inputfile
Lib3dsFile* file3ds = lib3ds_file_load(infn);
if (!file3ds ) {
fprintf (stderr, "Failed to open %s\n", infn);
return 1;
}
// swap xyz if requested
if (mode_xyz != MODE_XYZ)
Lib3dsConvertXYZ (file3ds, mode_xyz);
// Print some interesting information about what we have
if (flags & FLAG_LIST || flags & FLAG_VERBOSE)
{
// fprintf (stderr, "3DS data size: %ld byte\n", size);
fprintf (stderr, "3DS name: %s\n", file3ds->name);
fprintf (stderr, "lights: %s\n", file3ds->lights ? "yes" : "no");
fprintf (stderr, "object-name faces vertices maps matrix\n");
// set the current mesh to the first in the file
Lib3dsMesh* mesh;
for (mesh = file3ds->meshes; mesh; mesh = mesh->next)
{
// get the numbers in the current mesh
fprintf(stderr, "===================================================\n");
fprintf(stderr, "%-14s %5ld %5ld %5d %s\n",
mesh->name, mesh->faces, mesh->points, -1, " ");
}
}
// setup writer
writer.Set3dsFile (file3ds);
writer.SetScale (xscale, yscale, zscale);
writer.SetTranslate (xrelocate, yrelocate, zrelocate);
if (flags & FLAG_VERBOSE)
fprintf (stderr, "Writing output in CS format...");
csRef<iDocument> document = writer.WriteDocument ();
iString* str = new scfString;
document->Write (str);
if (outfn)
{
// Write file to disk
FILE* outfile = fopen (outfn, "w");
if (!outfile)
{
fprintf (stderr, "Couldn't open output file '%s'!\n", outfn);
return 1;
}
fwrite (str->GetData(), 1, str->Length(), outfile);
fclose (outfile);
}
else
{
// Write file to stdout
printf ("%s", str->GetData());
}
if (flags & FLAG_VERBOSE)
fprintf (stderr, "done! \n");
return 0;
}
<|endoftext|> |
<commit_before>//===- Version.cpp - Clang Version Number -----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines several version-related utility functions for Clang.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/Version.h"
#include "llvm/Support/raw_ostream.h"
#include <cstring>
#include <cstdlib>
using namespace std;
namespace clang {
llvm::StringRef getClangRepositoryPath() {
static const char URL[] = "$URL$";
const char *URLEnd = URL + strlen(URL);
const char *End = strstr(URL, "/lib/Basic");
if (End)
URLEnd = End;
End = strstr(URL, "/clang/tools/clang");
if (End)
URLEnd = End;
const char *Begin = strstr(URL, "cfe/");
if (Begin)
return llvm::StringRef(Begin + 4, URLEnd - Begin - 4);
return llvm::StringRef(URL, URLEnd - URL);
}
std::string getClangRevision() {
#ifndef SVN_REVISION
// Subversion was not available at build time?
return "";
#else
std::string revision;
llvm::raw_string_ostream OS(revision);
OS << strtol(SVN_REVISION, 0, 10);
return revision;
#endif
}
std::string getClangFullRepositoryVersion() {
std::string buf;
llvm::raw_string_ostream OS(buf);
OS << getClangRepositoryPath();
const std::string &Revision = getClangRevision();
if (!Revision.empty())
OS << ' ' << Revision;
return buf;
}
std::string getClangFullVersion() {
std::string buf;
llvm::raw_string_ostream OS(buf);
#ifdef CLANG_VENDOR
OS << CLANG_VENDOR;
#endif
OS << "clang version " CLANG_VERSION_STRING " ("
<< getClangFullRepositoryVersion() << ')';
return buf;
}
} // end namespace clang
<commit_msg>Make getClangRevision() check that SVN_VERSION is an empty string (even if it is defined). This fixes the issue of this function returning '0' when SVN_VERSION is defined to be "".<commit_after>//===- Version.cpp - Clang Version Number -----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines several version-related utility functions for Clang.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/Version.h"
#include "llvm/Support/raw_ostream.h"
#include <cstring>
#include <cstdlib>
using namespace std;
namespace clang {
llvm::StringRef getClangRepositoryPath() {
static const char URL[] = "$URL$";
const char *URLEnd = URL + strlen(URL);
const char *End = strstr(URL, "/lib/Basic");
if (End)
URLEnd = End;
End = strstr(URL, "/clang/tools/clang");
if (End)
URLEnd = End;
const char *Begin = strstr(URL, "cfe/");
if (Begin)
return llvm::StringRef(Begin + 4, URLEnd - Begin - 4);
return llvm::StringRef(URL, URLEnd - URL);
}
std::string getClangRevision() {
#ifdef SVN_REVISION
if (SVN_VERSION[0] != '\0') {
std::string revision;
llvm::raw_string_ostream OS(revision);
OS << strtol(SVN_REVISION, 0, 10);
return revision;
}
#endif
return "";
}
std::string getClangFullRepositoryVersion() {
std::string buf;
llvm::raw_string_ostream OS(buf);
OS << getClangRepositoryPath();
const std::string &Revision = getClangRevision();
if (!Revision.empty())
OS << ' ' << Revision;
return buf;
}
std::string getClangFullVersion() {
std::string buf;
llvm::raw_string_ostream OS(buf);
#ifdef CLANG_VENDOR
OS << CLANG_VENDOR;
#endif
OS << "clang version " CLANG_VERSION_STRING " ("
<< getClangFullRepositoryVersion() << ')';
return buf;
}
} // end namespace clang
<|endoftext|> |
<commit_before>/* FLAC input plugin for Winamp3
* Copyright (C) 2000,2001,2002 Josh Coalson
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* NOTE: this code is derived from the 'rawpcm' example by
* Nullsoft; the original license for the 'rawpcm' example follows.
*/
/*
Nullsoft WASABI Source File License
Copyright 1999-2001 Nullsoft, Inc.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Brennan Underwood
[email protected]
*/
#include "cnv_flacpcm.h"
#include "flacpcm.h"
static WACNAME wac;
WAComponentClient *the = &wac;
#include "studio/services/servicei.h"
// {683FA153-4055-467c-ABEE-5E35FA03C51E}
static const GUID guid =
{ 0x683fa153, 0x4055, 0x467c, { 0xab, 0xee, 0x5e, 0x35, 0xfa, 0x3, 0xc5, 0x1e } };
_int nch("# of channels", 2);
_int samplerate("Sample rate", 44100);
_int bps("Bits per second", 16);
WACNAME::WACNAME() : WAComponentClient("RAW files support") {
registerService(new waServiceT<svc_mediaConverter, FlacPcm>);
}
WACNAME::~WACNAME() {
}
GUID WACNAME::getGUID() {
return guid;
}
void WACNAME::onRegisterServices() {
api->core_registerExtension("*.flac","FLAC Files");
registerAttribute(&nch);
registerAttribute(&samplerate);
registerAttribute(&bps);
}
<commit_msg>fix WACNAME<commit_after>/* FLAC input plugin for Winamp3
* Copyright (C) 2000,2001,2002 Josh Coalson
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* NOTE: this code is derived from the 'rawpcm' example by
* Nullsoft; the original license for the 'rawpcm' example follows.
*/
/*
Nullsoft WASABI Source File License
Copyright 1999-2001 Nullsoft, Inc.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Brennan Underwood
[email protected]
*/
#include "cnv_flacpcm.h"
#include "flacpcm.h"
static WACNAME wac;
WAComponentClient *the = &wac;
#include "studio/services/servicei.h"
// {683FA153-4055-467c-ABEE-5E35FA03C51E}
static const GUID guid =
{ 0x683fa153, 0x4055, 0x467c, { 0xab, 0xee, 0x5e, 0x35, 0xfa, 0x3, 0xc5, 0x1e } };
_int nch("# of channels", 2);
_int samplerate("Sample rate", 44100);
_int bps("Bits per second", 16);
WACNAME::WACNAME() : WAComponentClient("FLAC file support") {
registerService(new waServiceT<svc_mediaConverter, FlacPcm>);
}
WACNAME::~WACNAME() {
}
GUID WACNAME::getGUID() {
return guid;
}
void WACNAME::onRegisterServices() {
api->core_registerExtension("*.flac","FLAC Files");
registerAttribute(&nch);
registerAttribute(&samplerate);
registerAttribute(&bps);
}
<|endoftext|> |
<commit_before>/*
Crystal Space Quake Milk Shape ASCII convertor
Copyright (C) 2002 by Steven Geens <[email protected]>
Based upon:
Crystal Space Quake MDL/MD2 convertor
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cssysdef.h"
#include "msmodel.h"
CS_IMPLEMENT_APPLICATION
static void usage(FILE* s, int rc)
{
fprintf(s, "Usage: milk2spr <option> [model-file] [sprite-name]\n[sprite-name] without the trailing .lib\n");
fprintf(s, "Options:\n");
fprintf(s, " -h : help (this page)\n");
fprintf(s, " -d <float> : duration of a frame in seconds (default %f)\n",FRAME_DURATION_DEFAULT);
printCode(s,rc);
exit(rc);
}
static void fatal_usage() { usage(stderr, -1); }
static void okay_usage() { usage(stdout, 0); }
static void printCode(FILE* s, int rc)
{
fprintf(s, "The code example is replaced by a program.\n");
fprintf(s, "Look in /apps/tests/mottest\n");
exit(rc);
}
int main(int argc,char *argv[])
{
printf("milk2spr version 0.9\n"
"A Milk Shape ASCII model convertor for Crystal Space.\n"
"By Steven Geens <[email protected]>\n\n");
float frameDuration = FRAME_DURATION_DEFAULT;
if (argc < 2)
{
fatal_usage();
}
if (argc < 3)
{
switch (argv[1][1])
{
case 'c':
printCode(stdout, 0);
default:
fatal_usage();
}
}
else
{
int i;
for (i = 1; i < argc - 2; i++)
{
if (argv[i][0] != '-' && argv[i][0] != '/')
{
fprintf(stderr, "'%s' unreconized option\n", argv[i]);
fatal_usage();
}
switch (argv[i][1])
{
case 'h':
case '?':
okay_usage();break;
case 'c':
printCode(stdout, 0);break;
case 'd':
sscanf (argv[++i], "%f", &frameDuration);
printf("The duration of a frame set to %g seconds.\n", frameDuration);
break;
default:
fprintf(stderr, "'%s' unreconized option.\n", argv[i]);
fatal_usage();
}
}
}
const char* msfile = argv[argc - 2];
MsModel* ms = NULL;
if (MsModel::IsFileMsModel(msfile))
ms = new MsModel(msfile,frameDuration);
else
{
fprintf(stderr, "Not a recognized model file: %s\n", msfile);
exit(-1);
}
if (ms->getError())
{
fprintf(stderr, "\nError: %s\n", ms->getErrorString());
delete ms;
exit(-1);
}
ms->dumpstats(stdout);
putchar('\n');
ms->WriteSPR(argv[argc - 1]);
delete ms;
return 0;
}
<commit_msg>Allways test first before you commit.<commit_after>/*
Crystal Space Quake Milk Shape ASCII convertor
Copyright (C) 2002 by Steven Geens <[email protected]>
Based upon:
Crystal Space Quake MDL/MD2 convertor
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cssysdef.h"
#include "msmodel.h"
CS_IMPLEMENT_APPLICATION
static void printCode(FILE* s, int rc)
{
fprintf(s, "The code example is replaced by a program.\n");
fprintf(s, "Look in /apps/tests/mottest\n");
exit(rc);
}
static void usage(FILE* s, int rc)
{
fprintf(s, "Usage: milk2spr <option> [model-file] [sprite-name]\n[sprite-name] without the trailing .lib\n");
fprintf(s, "Options:\n");
fprintf(s, " -h : help (this page)\n");
fprintf(s, " -d <float> : duration of a frame in seconds (default %f)\n",FRAME_DURATION_DEFAULT);
printCode(s,rc);
}
static void fatal_usage() { usage(stderr, -1); }
static void okay_usage() { usage(stdout, 0); }
int main(int argc,char *argv[])
{
printf("milk2spr version 0.9\n"
"A Milk Shape ASCII model convertor for Crystal Space.\n"
"By Steven Geens <[email protected]>\n\n");
float frameDuration = FRAME_DURATION_DEFAULT;
if (argc < 2)
{
fatal_usage();
}
if (argc < 3)
{
switch (argv[1][1])
{
case 'c':
printCode(stdout, 0);
default:
fatal_usage();
}
}
else
{
int i;
for (i = 1; i < argc - 2; i++)
{
if (argv[i][0] != '-' && argv[i][0] != '/')
{
fprintf(stderr, "'%s' unreconized option\n", argv[i]);
fatal_usage();
}
switch (argv[i][1])
{
case 'h':
case '?':
okay_usage();break;
case 'c':
printCode(stdout, 0);break;
case 'd':
sscanf (argv[++i], "%f", &frameDuration);
printf("The duration of a frame set to %g seconds.\n", frameDuration);
break;
default:
fprintf(stderr, "'%s' unreconized option.\n", argv[i]);
fatal_usage();
}
}
}
const char* msfile = argv[argc - 2];
MsModel* ms = NULL;
if (MsModel::IsFileMsModel(msfile))
ms = new MsModel(msfile,frameDuration);
else
{
fprintf(stderr, "Not a recognized model file: %s\n", msfile);
exit(-1);
}
if (ms->getError())
{
fprintf(stderr, "\nError: %s\n", ms->getErrorString());
delete ms;
exit(-1);
}
ms->dumpstats(stdout);
putchar('\n');
ms->WriteSPR(argv[argc - 1]);
delete ms;
return 0;
}
<|endoftext|> |
<commit_before>/**
* KeybdInput 1.0.1
*
* @author Roger Lima ([email protected])
* @date 31/aug/2014
* @update 02/feb/2016
* @desc Reads the keyboard input them according to the format specified (only works on Windows)
* @example
int day, month, year;
KeybdInput< int > userin;
userin.solicit(
"Type a date (btw 01/01/1900 and 31/12/2009): ",
std::regex( "([0-2]?[0-9]|3[0-1])/(0?[1-9]|1[012])/(19[0-9]{2}|200[0-9])" ),
{ &day, &month, &year },
false,
false,
false,
'/'
);
*/
#pragma once
#include <conio.h>
#include <iostream>
#include <regex>
#include <sstream>
#include <vector>
#include <Windows.h>
template< typename T >
class KeybdInput {
private:
// Stores the values to be used in KeybdInput::reset()
bool _instverify, _reset, _ispw;
char _sep;
size_t _inmaxsize;
std::regex _restriction;
std::string _rmsg;
std::vector< T * > _references = {};
// Stores the user input
std::string input;
// Receives the current X and Y cursor position from get_cursor_position()
std::vector< size_t > cursor_position = { 0, 0 };
// Erase the input of user
// @param {size_t=input.size()} Erase range
void erase_input( size_t = 0 );
// Get the console cursor position and pass to the cursor_position
void get_cursor_position();
// Set the console cursor position
// @param {short} X position of cursor
// @param {short} Y position of cursor
void set_cursor_position( short, short );
// Split a string
// @param {std::string} Target string
// @param {char} Delimiter
std::vector< std::string > split( std::string str, char delim );
// Set the reference with input value
// @param {const std::string&} Input value
// @param {T*} Target place
void set_reference( const std::string&, T * );
// Clear all values of references
// @param {T*} Target place
void clear_references( std::vector< T * > );
public:
// Clipboard (arrow up or down to show the last inputs)
std::vector< std::string > clipboard;
// Requires the user input again
// @param [{std::string=_rmsg}] Request message
void reset( std::string = "" );
// Requires the keyboard input
// @param {string} Request message
// @param {regex} The regex
// @param {vector< T * >} The place(s) where it will be stored the input
// @param {bool=false} Instant verify
// @param {bool=false} Reset possibility
// @param {bool=false} Is password
// @param {char=' '} Separator
// @param {size_t=1000} Input size
void solicit( std::string, std::regex, std::vector< T * >, bool = false, bool = false, bool = false, char = ' ', size_t = 1000 );
};
template< typename T >
void KeybdInput< T >::erase_input( size_t erase_range = 0 ) {
// Default erase range
if ( !erase_range )
erase_range = input.size();
for ( size_t i = 0; i < erase_range; i++ )
std::cout << "\b \b";
input = "";
};
template < typename T >
void KeybdInput< T >::set_reference( const std::string& value, T *target ) {
std::stringstream convert;
convert << value;
convert >> *target;
};
void KeybdInput< std::string >::set_reference( const std::string& value, std::string *target ) {
*target = value;
};
template < typename T >
void KeybdInput< T >::clear_references( std::vector< T * > target ) {
for ( size_t i = 0; i < _references.size(); *target[ i++ ] = 0 );
};
void KeybdInput< std::string >::clear_references( std::vector< std::string * > target ) {
for ( size_t i = 0; i < _references.size(); *target[ i++ ] = "" );
};
template< typename T >
void KeybdInput< T >::get_cursor_position() {
CONSOLE_SCREEN_BUFFER_INFO screen_buffer_info;
HANDLE hStd = GetStdHandle( STD_OUTPUT_HANDLE );
if ( !GetConsoleScreenBufferInfo( hStd, &screen_buffer_info ) )
MessageBox( NULL, L"An error occurred getting the console cursor position.", L"KeybdInput ERROR", NULL );
cursor_position[ 0 ] = screen_buffer_info.dwCursorPosition.X;
cursor_position[ 1 ] = screen_buffer_info.dwCursorPosition.Y;
};
template< typename T >
void KeybdInput< T >::set_cursor_position( short x, short y ) {
if ( !SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), { x, y } ) )
MessageBox( NULL, L"An error occurred setting the console cursor position.", L"KeybdInput ERROR", NULL );
};
template< typename T >
std::vector< std::string > KeybdInput< T >::split( std::string str, char delim ) {
std::vector< std::string > elems;
std::stringstream stream( str );
std::string item;
for ( ; getline( stream, item, delim ); elems.push_back( item ) );
return elems;
};
template< typename T >
void KeybdInput< T >::reset( std::string msg = "" ) {
// Default request message
if ( msg == "" && _rmsg != "" )
msg = _rmsg;
if ( !_reset ) {
MessageBox( NULL, L"Can't possible execute KeybdInput::reset() without set reset_possibility=true in KeybdInput::solicit().", L"KeybdInput ERROR", NULL );
return;
}
// Clear previously set values
clear_references( _references );
// Sets the cursor in the previous line, erase all and requires input again
get_cursor_position();
set_cursor_position( short ( msg.size() + input.size() ), cursor_position[ 1 ] - 1 );
erase_input( msg.size() + input.size() );
solicit( msg, std::regex( _restriction ), _references, _instverify, _reset, _ispw, _sep, _inmaxsize );
};
template< typename T >
void KeybdInput< T >::solicit( std::string request_msg, std::regex restriction, std::vector< T * > references, bool instant_verify, bool reset_possibility, bool is_password, char separator, size_t input_max_size ) {
static size_t clipboard_index = 0;
size_t i, cursor_pos_x,
inputLength = 0;
char key = 0;
bool is_function_key = false,
arrow = false,
waiting_input = true;
std::string input_subtr;
std::vector< std::string > inputParts;
if ( references.size() == 0 ) {
MessageBox( NULL, L"\"refereces\" param need be set with at least one member.", L"KeybdInput ERROR", NULL );
return;
}
input = "";
std::cout << request_msg;
// Retrieves the values to be used in KeybdInput::reset()
if ( reset_possibility ) {
_rmsg = request_msg;
_restriction = restriction;
_references = references;
_instverify = instant_verify;
_reset = reset_possibility;
_ispw = is_password;
_sep = separator;
_inmaxsize = input_max_size;
}
// Clears previous data
else if ( _reset ) {
_rmsg = "";
_restriction = "";
_references = {};
_instverify = false;
_reset = false;
_ispw = false;
_sep = ' ';
_inmaxsize = 0;
}
while ( waiting_input ) {
key = _getch();
// Arrow keys prefix
if ( key == -32 ) {
arrow = true;
continue;
}
// Prevents function keys
if ( key == 0 ) {
is_function_key = true;
continue;
} else if ( is_function_key ) {
is_function_key = false;
continue;
}
// Arrows
if ( arrow ) {
get_cursor_position();
// LEFT
if ( key == 75 && cursor_position[ 0 ] > request_msg.size() )
set_cursor_position( cursor_position[ 0 ] - 1, cursor_position[ 1 ] );
// RIGHT
else if ( key == 77 && cursor_position[ 0 ] < input.size() + request_msg.size() )
set_cursor_position( cursor_position[ 0 ] + 1, cursor_position[ 1 ] );
// UP
else if ( key == 72 && !is_password && clipboard.size() > 0 && clipboard_index > 0 ) {
erase_input();
std::cout << clipboard[ --clipboard_index ];
input = clipboard[ clipboard_index ];
inputLength = clipboard[ clipboard_index ].size();
}
// DOWN
else if ( key == 80 && !is_password && clipboard.size() > 0 && clipboard_index < clipboard.size() - 1 ) {
erase_input();
std::cout << clipboard[ ++clipboard_index ];
input = clipboard[ clipboard_index ];
inputLength = clipboard[ clipboard_index ].size();
if ( clipboard_index >= clipboard.size() )
clipboard_index = clipboard.size() - 1;
}
}
// Valid character
else if ( key != 8 && key != 13 ) {
// Inserts the character in current cursor position
get_cursor_position();
input.insert( cursor_position[ 0 ] - request_msg.size(), std::string( 1, key ) );
// If the user input satisfy the restrictions, removes the character
if ( instant_verify && ( input.size() > input_max_size || !std::regex_match( input, restriction ) ) ) {
input.erase( cursor_position[ 0 ] - request_msg.size(), 1 );
} else {
// Appends the character if cursor is at the end, otherwise, interleaves
if ( cursor_position[ 0 ] == ( request_msg.size() + input.size() - 1 ) ) {
std::cout << ( ( is_password ) ? '*' : key );
} else {
input_subtr = input.substr( input.size() - ( ( request_msg.size() + input.size() ) - cursor_position[ 0 ] - 1 ), input.size() );
std::cout << ( ( is_password ) ? '*' : key )
<< ( ( is_password ) ? std::string( input_subtr.size(), '*' ) : input_subtr );
set_cursor_position( cursor_position[ 0 ] + 1, cursor_position[ 1 ] );
}
inputLength++;
}
}
// ENTER
else if ( key == 13 && inputLength ) {
// If the user input satisfy the restrictions, clear input
if ( input.size() > input_max_size || !std::regex_match( input, restriction ) ) {
erase_input();
inputLength = 0;
} else {
// Trim left and right
input.erase( 0, input.find_first_not_of( ' ' ) );
input.erase( input.find_last_not_of( ' ' ) + 1 );
if ( references.size() == 1 )
set_reference( input, references[ 0 ] );
else
for ( i = 0, inputParts = split( input, separator ); i < references.size(); i++ )
if ( i < inputParts.size() )
set_reference( inputParts[ i ], references[ i ] );
std::cout << std::endl;
// Prevents repetition on clipboard and don't save if it's a password
if ( !is_password && ( clipboard.size() == 0 || input != clipboard[ clipboard.size() - 1 ] ) ) {
clipboard.push_back( input );
clipboard_index = clipboard.size();
}
waiting_input = false;
}
}
// BACKSPACE
else if ( key == 8 && inputLength ) {
get_cursor_position();
cursor_pos_x = cursor_position[ 0 ];
if ( cursor_pos_x == ( request_msg.size() + input.size() - 1 ) && inputLength == 1 )
continue;
std::cout << "\b \b";
input.erase( cursor_pos_x - request_msg.size() - 1, 1 );
inputLength--;
// If the cursor isn't at the end
if ( cursor_pos_x <= ( request_msg.size() + input.size() ) ) {
// Put the cursor at the start and rewrites the input
set_cursor_position( short ( request_msg.size() ), cursor_position[ 1 ] );
std::cout << ( ( is_password ) ? std::string( input.size(), '*' ) : input );
// Put the cursor at the end and erase the last char
set_cursor_position( short ( request_msg.size() + input.size() + 1 ), cursor_position[ 1 ] );
std::cout << "\b \b";
// Put the cursor at the original position
set_cursor_position( short ( cursor_pos_x - 1 ), cursor_position[ 1 ] );
}
}
arrow = false;
}
};
<commit_msg>Change on split method<commit_after>/**
* KeybdInput 1.0.1
*
* @author Roger Lima ([email protected])
* @date 31/aug/2014
* @update 11/feb/2016
* @desc Reads the keyboard input them according to the format specified (only works on Windows)
* @example
int day, month, year;
KeybdInput< int > userin;
userin.solicit(
"Type a date (btw 01/01/1900 and 31/12/2009): ",
std::regex( "([0-2]?[0-9]|3[0-1])/(0?[1-9]|1[012])/(19[0-9]{2}|200[0-9])" ),
{ &day, &month, &year },
false,
false,
false,
'/'
);
*/
#pragma once
#include <conio.h>
#include <iostream>
#include <regex>
#include <sstream>
#include <vector>
#include <Windows.h>
template< typename T >
class KeybdInput {
private:
// Stores the values to be used in KeybdInput::reset()
bool _instverify, _reset, _ispw;
size_t _inmaxsize;
std::regex _restriction;
std::string _rmsg, _sep;
std::vector< T * > _references = {};
// Stores the user input
std::string input;
// Receives the current X and Y cursor position from get_cursor_position()
std::vector< size_t > cursor_position = { 0, 0 };
// Erase the input of user
// @param {size_t=input.size()} Erase range
void erase_input( size_t = 0 );
// Get the console cursor position and pass to the cursor_position
void get_cursor_position();
// Set the console cursor position
// @param {short} X position of cursor
// @param {short} Y position of cursor
void set_cursor_position( short, short );
// Split a string
// @param {std::string} Target string
// @param {std::string} Separator
std::vector< std::string > splitstr( std::string str, std::string separator );
// Set the reference with input value
// @param {const std::string&} Input value
// @param {T*} Target place
void set_reference( const std::string&, T * );
// Clear all values of references
// @param {T*} Target place
void clear_references( std::vector< T * > );
public:
// Clipboard (arrow up or down to show the last inputs)
std::vector< std::string > clipboard;
// Requires the user input again
// @param [{std::string=_rmsg}] Request message
void reset( std::string = "" );
// Requires the keyboard input
// @param {string} Request message
// @param {regex} The regex
// @param {vector< T * >} The place(s) where it will be stored the input
// @param {bool=false} Instant verify
// @param {bool=false} Reset possibility
// @param {bool=false} Is password
// @param {char=' '} Separator
// @param {size_t=1000} Input size
void solicit( std::string, std::regex, std::vector< T * >, bool = false, bool = false, bool = false, std::string = " ", size_t = 1000 );
};
template< typename T >
void KeybdInput< T >::erase_input( size_t erase_range = 0 ) {
// Default erase range
if ( !erase_range )
erase_range = input.size();
for ( size_t i = 0; i < erase_range; i++ )
std::cout << "\b \b";
input = "";
};
template < typename T >
void KeybdInput< T >::set_reference( const std::string& value, T *target ) {
std::stringstream convert;
convert << value;
convert >> *target;
};
void KeybdInput< std::string >::set_reference( const std::string& value, std::string *target ) {
*target = value;
};
template < typename T >
void KeybdInput< T >::clear_references( std::vector< T * > target ) {
for ( size_t i = 0; i < _references.size(); *target[ i++ ] = 0 );
};
void KeybdInput< std::string >::clear_references( std::vector< std::string * > target ) {
for ( size_t i = 0; i < _references.size(); *target[ i++ ] = "" );
};
template< typename T >
void KeybdInput< T >::get_cursor_position() {
CONSOLE_SCREEN_BUFFER_INFO screen_buffer_info;
HANDLE hStd = GetStdHandle( STD_OUTPUT_HANDLE );
if ( !GetConsoleScreenBufferInfo( hStd, &screen_buffer_info ) )
MessageBox( NULL, L"An error occurred getting the console cursor position.", L"KeybdInput ERROR", NULL );
cursor_position[ 0 ] = screen_buffer_info.dwCursorPosition.X;
cursor_position[ 1 ] = screen_buffer_info.dwCursorPosition.Y;
};
template< typename T >
void KeybdInput< T >::set_cursor_position( short x, short y ) {
if ( !SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), { x, y } ) )
MessageBox( NULL, L"An error occurred setting the console cursor position.", L"KeybdInput ERROR", NULL );
};
template< typename T >
std::vector< std::string > KeybdInput< T >::splitstr( std::string str, std::string separator = "" ) {
size_t index;
std::vector< std::string > elems;
while ( ( index = str.find( separator ) ) != std::string::npos && str.size() > 1 ) {
elems.push_back( str.substr( 0, index ? index : 1 ) );
str.erase( 0, index + ( !separator.size() ? 1 : separator.size() ) );
}
elems.push_back( str );
return elems;
};
template< typename T >
void KeybdInput< T >::reset( std::string msg = "" ) {
// Default request message
if ( msg == "" && _rmsg != "" )
msg = _rmsg;
if ( !_reset ) {
MessageBox( NULL, L"Can't possible execute KeybdInput::reset() without set reset_possibility=true in KeybdInput::solicit().", L"KeybdInput ERROR", NULL );
return;
}
// Clear previously set values
clear_references( _references );
// Sets the cursor in the previous line, erase all and requires input again
get_cursor_position();
set_cursor_position( short ( msg.size() + input.size() ), cursor_position[ 1 ] - 1 );
erase_input( msg.size() + input.size() );
solicit( msg, std::regex( _restriction ), _references, _instverify, _reset, _ispw, _sep, _inmaxsize );
};
template< typename T >
void KeybdInput< T >::solicit( std::string request_msg, std::regex restriction, std::vector< T * > references, bool instant_verify, bool reset_possibility, bool is_password, std::string separator, size_t input_max_size ) {
static size_t clipboard_index = 0;
size_t i, cursor_pos_x,
inputLength = 0;
char key = 0;
bool is_function_key = false,
arrow = false,
waiting_input = true;
std::string input_subtr;
std::vector< std::string > inputParts;
if ( references.size() == 0 ) {
MessageBox( NULL, L"\"refereces\" param need be set with at least one member.", L"KeybdInput ERROR", NULL );
return;
}
input = "";
std::cout << request_msg;
// Retrieves the values to be used in KeybdInput::reset()
if ( reset_possibility ) {
_rmsg = request_msg;
_restriction = restriction;
_references = references;
_instverify = instant_verify;
_reset = reset_possibility;
_ispw = is_password;
_sep = separator;
_inmaxsize = input_max_size;
}
// Clears previous data
else if ( _reset ) {
_rmsg = "";
_restriction = "";
_references = {};
_instverify = false;
_reset = false;
_ispw = false;
_sep = ' ';
_inmaxsize = 0;
}
while ( waiting_input ) {
key = _getch();
// Arrow keys prefix
if ( key == -32 ) {
arrow = true;
continue;
}
// Prevents function keys
if ( key == 0 ) {
is_function_key = true;
continue;
} else if ( is_function_key ) {
is_function_key = false;
continue;
}
// Arrows
if ( arrow ) {
get_cursor_position();
// LEFT
if ( key == 75 && cursor_position[ 0 ] > request_msg.size() )
set_cursor_position( cursor_position[ 0 ] - 1, cursor_position[ 1 ] );
// RIGHT
else if ( key == 77 && cursor_position[ 0 ] < input.size() + request_msg.size() )
set_cursor_position( cursor_position[ 0 ] + 1, cursor_position[ 1 ] );
// UP
else if ( key == 72 && !is_password && clipboard.size() > 0 && clipboard_index > 0 ) {
erase_input();
std::cout << clipboard[ --clipboard_index ];
input = clipboard[ clipboard_index ];
inputLength = clipboard[ clipboard_index ].size();
}
// DOWN
else if ( key == 80 && !is_password && clipboard.size() > 0 && clipboard_index < clipboard.size() - 1 ) {
erase_input();
std::cout << clipboard[ ++clipboard_index ];
input = clipboard[ clipboard_index ];
inputLength = clipboard[ clipboard_index ].size();
if ( clipboard_index >= clipboard.size() )
clipboard_index = clipboard.size() - 1;
}
}
// Valid character
else if ( key != 8 && key != 13 ) {
// Inserts the character in current cursor position
get_cursor_position();
input.insert( cursor_position[ 0 ] - request_msg.size(), std::string( 1, key ) );
// If the user input satisfy the restrictions, removes the character
if ( instant_verify && ( input.size() > input_max_size || !std::regex_match( input, restriction ) ) ) {
input.erase( cursor_position[ 0 ] - request_msg.size(), 1 );
} else {
// Appends the character if cursor is at the end, otherwise, interleaves
if ( cursor_position[ 0 ] == ( request_msg.size() + input.size() - 1 ) ) {
std::cout << ( ( is_password ) ? '*' : key );
} else {
input_subtr = input.substr( input.size() - ( ( request_msg.size() + input.size() ) - cursor_position[ 0 ] - 1 ), input.size() );
std::cout << ( ( is_password ) ? '*' : key )
<< ( ( is_password ) ? std::string( input_subtr.size(), '*' ) : input_subtr );
set_cursor_position( cursor_position[ 0 ] + 1, cursor_position[ 1 ] );
}
inputLength++;
}
}
// ENTER
else if ( key == 13 && inputLength ) {
// If the user input satisfy the restrictions, clear input
if ( input.size() > input_max_size || !std::regex_match( input, restriction ) ) {
erase_input();
inputLength = 0;
} else {
// Trim left and right
input.erase( 0, input.find_first_not_of( ' ' ) );
input.erase( input.find_last_not_of( ' ' ) + 1 );
if ( references.size() == 1 )
set_reference( input, references[ 0 ] );
else
for ( i = 0, inputParts = splitstr( input, separator ); i < references.size(); i++ )
if ( i < inputParts.size() )
set_reference( inputParts[ i ], references[ i ] );
std::cout << std::endl;
// Prevents repetition on clipboard and don't save if it's a password
if ( !is_password && ( clipboard.size() == 0 || input != clipboard[ clipboard.size() - 1 ] ) ) {
clipboard.push_back( input );
clipboard_index = clipboard.size();
}
waiting_input = false;
}
}
// BACKSPACE
else if ( key == 8 && inputLength ) {
get_cursor_position();
cursor_pos_x = cursor_position[ 0 ];
if ( cursor_pos_x == ( request_msg.size() + input.size() - 1 ) && inputLength == 1 )
continue;
std::cout << "\b \b";
input.erase( cursor_pos_x - request_msg.size() - 1, 1 );
inputLength--;
// If the cursor isn't at the end
if ( cursor_pos_x <= ( request_msg.size() + input.size() ) ) {
// Put the cursor at the start and rewrites the input
set_cursor_position( short ( request_msg.size() ), cursor_position[ 1 ] );
std::cout << ( ( is_password ) ? std::string( input.size(), '*' ) : input );
// Put the cursor at the end and erase the last char
set_cursor_position( short ( request_msg.size() + input.size() + 1 ), cursor_position[ 1 ] );
std::cout << "\b \b";
// Put the cursor at the original position
set_cursor_position( short ( cursor_pos_x - 1 ), cursor_position[ 1 ] );
}
}
arrow = false;
}
};
<|endoftext|> |
<commit_before>efaa7ad2-2e4e-11e5-9284-b827eb9e62be<commit_msg>efaf6dd0-2e4e-11e5-9284-b827eb9e62be<commit_after>efaf6dd0-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>//===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code dealing with C++ code generation.
//
//===----------------------------------------------------------------------===//
// We might split this into multiple files if it gets too unwieldy
#include "CodeGenModule.h"
#include "CGCXXABI.h"
#include "CodeGenFunction.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/StmtCXX.h"
#include "clang/Frontend/CodeGenOptions.h"
#include "llvm/ADT/StringExtras.h"
using namespace clang;
using namespace CodeGen;
/// Try to emit a base destructor as an alias to its primary
/// base-class destructor.
bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
if (!getCodeGenOpts().CXXCtorDtorAliases)
return true;
// Producing an alias to a base class ctor/dtor can degrade debug quality
// as the debugger cannot tell them apart.
if (getCodeGenOpts().OptimizationLevel == 0)
return true;
// If the destructor doesn't have a trivial body, we have to emit it
// separately.
if (!D->hasTrivialBody())
return true;
const CXXRecordDecl *Class = D->getParent();
// We are going to instrument this destructor, so give up even if it is
// currently empty.
if (Class->mayInsertExtraPadding())
return true;
// If we need to manipulate a VTT parameter, give up.
if (Class->getNumVBases()) {
// Extra Credit: passing extra parameters is perfectly safe
// in many calling conventions, so only bail out if the ctor's
// calling convention is nonstandard.
return true;
}
// If any field has a non-trivial destructor, we have to emit the
// destructor separately.
for (const auto *I : Class->fields())
if (I->getType().isDestructedType())
return true;
// Try to find a unique base class with a non-trivial destructor.
const CXXRecordDecl *UniqueBase = nullptr;
for (const auto &I : Class->bases()) {
// We're in the base destructor, so skip virtual bases.
if (I.isVirtual()) continue;
// Skip base classes with trivial destructors.
const auto *Base =
cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
if (Base->hasTrivialDestructor()) continue;
// If we've already found a base class with a non-trivial
// destructor, give up.
if (UniqueBase) return true;
UniqueBase = Base;
}
// If we didn't find any bases with a non-trivial destructor, then
// the base destructor is actually effectively trivial, which can
// happen if it was needlessly user-defined or if there are virtual
// bases with non-trivial destructors.
if (!UniqueBase)
return true;
// If the base is at a non-zero offset, give up.
const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
return true;
// Give up if the calling conventions don't match. We could update the call,
// but it is probably not worth it.
const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
D->getType()->getAs<FunctionType>()->getCallConv())
return true;
return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
GlobalDecl(BaseD, Dtor_Base),
false);
}
/// Try to emit a definition as a global alias for another definition.
/// If \p InEveryTU is true, we know that an equivalent alias can be produced
/// in every translation unit.
bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
GlobalDecl TargetDecl,
bool InEveryTU) {
if (!getCodeGenOpts().CXXCtorDtorAliases)
return true;
// The alias will use the linkage of the referent. If we can't
// support aliases with that linkage, fail.
llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
// We can't use an alias if the linkage is not valid for one.
if (!llvm::GlobalAlias::isValidLinkage(Linkage))
return true;
// Don't create a weak alias for a dllexport'd symbol.
if (AliasDecl.getDecl()->hasAttr<DLLExportAttr>() &&
llvm::GlobalValue::isWeakForLinker(Linkage))
return true;
llvm::GlobalValue::LinkageTypes TargetLinkage =
getFunctionLinkage(TargetDecl);
// Check if we have it already.
StringRef MangledName = getMangledName(AliasDecl);
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
if (Entry && !Entry->isDeclaration())
return false;
if (Replacements.count(MangledName))
return false;
// Derive the type for the alias.
llvm::PointerType *AliasType
= getTypes().GetFunctionType(AliasDecl)->getPointerTo();
// Find the referent. Some aliases might require a bitcast, in
// which case the caller is responsible for ensuring the soundness
// of these semantics.
auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
llvm::Constant *Aliasee = Ref;
if (Ref->getType() != AliasType)
Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
// Instead of creating as alias to a linkonce_odr, replace all of the uses
// of the aliasee.
if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
(TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage ||
!TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
// FIXME: An extern template instantiation will create functions with
// linkage "AvailableExternally". In libc++, some classes also define
// members with attribute "AlwaysInline" and expect no reference to
// be generated. It is desirable to reenable this optimisation after
// corresponding LLVM changes.
Replacements[MangledName] = Aliasee;
return false;
}
if (!InEveryTU) {
// If we don't have a definition for the destructor yet, don't
// emit. We can't emit aliases to declarations; that's just not
// how aliases work.
if (Ref->isDeclaration())
return true;
}
// Don't create an alias to a linker weak symbol. This avoids producing
// different COMDATs in different TUs. Another option would be to
// output the alias both for weak_odr and linkonce_odr, but that
// requires explicit comdat support in the IL.
if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
return true;
// Create the alias with no name.
auto *Alias =
llvm::GlobalAlias::create(AliasType, Linkage, "", Aliasee, &getModule());
// Switch any previous uses to the alias.
if (Entry) {
assert(Entry->getType() == AliasType &&
"declaration exists with different type");
Alias->takeName(Entry);
Entry->replaceAllUsesWith(Alias);
Entry->eraseFromParent();
} else {
Alias->setName(MangledName);
}
// Finally, set up the alias with its proper name and attributes.
setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
return false;
}
llvm::Function *CodeGenModule::codegenCXXStructor(const CXXMethodDecl *MD,
StructorType Type) {
const CGFunctionInfo &FnInfo =
getTypes().arrangeCXXStructorDeclaration(MD, Type);
auto *Fn = cast<llvm::Function>(
getAddrOfCXXStructor(MD, Type, &FnInfo, nullptr, true));
GlobalDecl GD;
if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
GD = GlobalDecl(DD, toCXXDtorType(Type));
} else {
const auto *CD = cast<CXXConstructorDecl>(MD);
GD = GlobalDecl(CD, toCXXCtorType(Type));
}
setFunctionLinkage(GD, Fn);
CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
setFunctionDefinitionAttributes(MD, Fn);
SetLLVMFunctionAttributesForDefinition(MD, Fn);
return Fn;
}
llvm::GlobalValue *CodeGenModule::getAddrOfCXXStructor(
const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo,
llvm::FunctionType *FnType, bool DontDefer) {
GlobalDecl GD;
if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
GD = GlobalDecl(CD, toCXXCtorType(Type));
} else {
auto *DD = dyn_cast<CXXDestructorDecl>(MD);
GD = GlobalDecl(DD, toCXXDtorType(Type));
}
StringRef Name = getMangledName(GD);
if (llvm::GlobalValue *Existing = GetGlobalValue(Name))
return Existing;
if (!FnType) {
if (!FnInfo)
FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type);
FnType = getTypes().GetFunctionType(*FnInfo);
}
return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FnType, GD,
/*ForVTable=*/false,
DontDefer));
}
static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
GlobalDecl GD,
llvm::Type *Ty,
const CXXRecordDecl *RD) {
assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
"No kext in Microsoft ABI");
GD = GD.getCanonicalDecl();
CodeGenModule &CGM = CGF.CGM;
llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
Ty = Ty->getPointerTo()->getPointerTo();
VTable = CGF.Builder.CreateBitCast(VTable, Ty);
assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
uint64_t AddressPoint =
CGM.getItaniumVTableContext().getVTableLayout(RD)
.getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
VTableIndex += AddressPoint;
llvm::Value *VFuncPtr =
CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
return CGF.Builder.CreateLoad(VFuncPtr);
}
/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
/// indirect call to virtual functions. It makes the call through indexing
/// into the vtable.
llvm::Value *
CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
NestedNameSpecifier *Qual,
llvm::Type *Ty) {
assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
"BuildAppleKextVirtualCall - bad Qual kind");
const Type *QTy = Qual->getAsType();
QualType T = QualType(QTy, 0);
const RecordType *RT = T->getAs<RecordType>();
assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
}
/// BuildVirtualCall - This routine makes indirect vtable call for
/// call to virtual destructors. It returns 0 if it could not do it.
llvm::Value *
CodeGenFunction::BuildAppleKextVirtualDestructorCall(
const CXXDestructorDecl *DD,
CXXDtorType Type,
const CXXRecordDecl *RD) {
const auto *MD = cast<CXXMethodDecl>(DD);
// FIXME. Dtor_Base dtor is always direct!!
// It need be somehow inline expanded into the caller.
// -O does that. But need to support -O0 as well.
if (MD->isVirtual() && Type != Dtor_Base) {
// Compute the function type we're calling.
const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
DD, StructorType::Complete);
llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
}
return nullptr;
}
<commit_msg>CGCXX: Use cast in getAddrOfCXXStructor()<commit_after>//===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code dealing with C++ code generation.
//
//===----------------------------------------------------------------------===//
// We might split this into multiple files if it gets too unwieldy
#include "CodeGenModule.h"
#include "CGCXXABI.h"
#include "CodeGenFunction.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/StmtCXX.h"
#include "clang/Frontend/CodeGenOptions.h"
#include "llvm/ADT/StringExtras.h"
using namespace clang;
using namespace CodeGen;
/// Try to emit a base destructor as an alias to its primary
/// base-class destructor.
bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
if (!getCodeGenOpts().CXXCtorDtorAliases)
return true;
// Producing an alias to a base class ctor/dtor can degrade debug quality
// as the debugger cannot tell them apart.
if (getCodeGenOpts().OptimizationLevel == 0)
return true;
// If the destructor doesn't have a trivial body, we have to emit it
// separately.
if (!D->hasTrivialBody())
return true;
const CXXRecordDecl *Class = D->getParent();
// We are going to instrument this destructor, so give up even if it is
// currently empty.
if (Class->mayInsertExtraPadding())
return true;
// If we need to manipulate a VTT parameter, give up.
if (Class->getNumVBases()) {
// Extra Credit: passing extra parameters is perfectly safe
// in many calling conventions, so only bail out if the ctor's
// calling convention is nonstandard.
return true;
}
// If any field has a non-trivial destructor, we have to emit the
// destructor separately.
for (const auto *I : Class->fields())
if (I->getType().isDestructedType())
return true;
// Try to find a unique base class with a non-trivial destructor.
const CXXRecordDecl *UniqueBase = nullptr;
for (const auto &I : Class->bases()) {
// We're in the base destructor, so skip virtual bases.
if (I.isVirtual()) continue;
// Skip base classes with trivial destructors.
const auto *Base =
cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
if (Base->hasTrivialDestructor()) continue;
// If we've already found a base class with a non-trivial
// destructor, give up.
if (UniqueBase) return true;
UniqueBase = Base;
}
// If we didn't find any bases with a non-trivial destructor, then
// the base destructor is actually effectively trivial, which can
// happen if it was needlessly user-defined or if there are virtual
// bases with non-trivial destructors.
if (!UniqueBase)
return true;
// If the base is at a non-zero offset, give up.
const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
return true;
// Give up if the calling conventions don't match. We could update the call,
// but it is probably not worth it.
const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
D->getType()->getAs<FunctionType>()->getCallConv())
return true;
return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
GlobalDecl(BaseD, Dtor_Base),
false);
}
/// Try to emit a definition as a global alias for another definition.
/// If \p InEveryTU is true, we know that an equivalent alias can be produced
/// in every translation unit.
bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
GlobalDecl TargetDecl,
bool InEveryTU) {
if (!getCodeGenOpts().CXXCtorDtorAliases)
return true;
// The alias will use the linkage of the referent. If we can't
// support aliases with that linkage, fail.
llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
// We can't use an alias if the linkage is not valid for one.
if (!llvm::GlobalAlias::isValidLinkage(Linkage))
return true;
// Don't create a weak alias for a dllexport'd symbol.
if (AliasDecl.getDecl()->hasAttr<DLLExportAttr>() &&
llvm::GlobalValue::isWeakForLinker(Linkage))
return true;
llvm::GlobalValue::LinkageTypes TargetLinkage =
getFunctionLinkage(TargetDecl);
// Check if we have it already.
StringRef MangledName = getMangledName(AliasDecl);
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
if (Entry && !Entry->isDeclaration())
return false;
if (Replacements.count(MangledName))
return false;
// Derive the type for the alias.
llvm::PointerType *AliasType
= getTypes().GetFunctionType(AliasDecl)->getPointerTo();
// Find the referent. Some aliases might require a bitcast, in
// which case the caller is responsible for ensuring the soundness
// of these semantics.
auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
llvm::Constant *Aliasee = Ref;
if (Ref->getType() != AliasType)
Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
// Instead of creating as alias to a linkonce_odr, replace all of the uses
// of the aliasee.
if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
(TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage ||
!TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
// FIXME: An extern template instantiation will create functions with
// linkage "AvailableExternally". In libc++, some classes also define
// members with attribute "AlwaysInline" and expect no reference to
// be generated. It is desirable to reenable this optimisation after
// corresponding LLVM changes.
Replacements[MangledName] = Aliasee;
return false;
}
if (!InEveryTU) {
// If we don't have a definition for the destructor yet, don't
// emit. We can't emit aliases to declarations; that's just not
// how aliases work.
if (Ref->isDeclaration())
return true;
}
// Don't create an alias to a linker weak symbol. This avoids producing
// different COMDATs in different TUs. Another option would be to
// output the alias both for weak_odr and linkonce_odr, but that
// requires explicit comdat support in the IL.
if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
return true;
// Create the alias with no name.
auto *Alias =
llvm::GlobalAlias::create(AliasType, Linkage, "", Aliasee, &getModule());
// Switch any previous uses to the alias.
if (Entry) {
assert(Entry->getType() == AliasType &&
"declaration exists with different type");
Alias->takeName(Entry);
Entry->replaceAllUsesWith(Alias);
Entry->eraseFromParent();
} else {
Alias->setName(MangledName);
}
// Finally, set up the alias with its proper name and attributes.
setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
return false;
}
llvm::Function *CodeGenModule::codegenCXXStructor(const CXXMethodDecl *MD,
StructorType Type) {
const CGFunctionInfo &FnInfo =
getTypes().arrangeCXXStructorDeclaration(MD, Type);
auto *Fn = cast<llvm::Function>(
getAddrOfCXXStructor(MD, Type, &FnInfo, nullptr, true));
GlobalDecl GD;
if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
GD = GlobalDecl(DD, toCXXDtorType(Type));
} else {
const auto *CD = cast<CXXConstructorDecl>(MD);
GD = GlobalDecl(CD, toCXXCtorType(Type));
}
setFunctionLinkage(GD, Fn);
CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
setFunctionDefinitionAttributes(MD, Fn);
SetLLVMFunctionAttributesForDefinition(MD, Fn);
return Fn;
}
llvm::GlobalValue *CodeGenModule::getAddrOfCXXStructor(
const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo,
llvm::FunctionType *FnType, bool DontDefer) {
GlobalDecl GD;
if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
GD = GlobalDecl(CD, toCXXCtorType(Type));
} else {
GD = GlobalDecl(cast<CXXDestructorDecl>(MD), toCXXDtorType(Type));
}
StringRef Name = getMangledName(GD);
if (llvm::GlobalValue *Existing = GetGlobalValue(Name))
return Existing;
if (!FnType) {
if (!FnInfo)
FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type);
FnType = getTypes().GetFunctionType(*FnInfo);
}
return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FnType, GD,
/*ForVTable=*/false,
DontDefer));
}
static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
GlobalDecl GD,
llvm::Type *Ty,
const CXXRecordDecl *RD) {
assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
"No kext in Microsoft ABI");
GD = GD.getCanonicalDecl();
CodeGenModule &CGM = CGF.CGM;
llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
Ty = Ty->getPointerTo()->getPointerTo();
VTable = CGF.Builder.CreateBitCast(VTable, Ty);
assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
uint64_t AddressPoint =
CGM.getItaniumVTableContext().getVTableLayout(RD)
.getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
VTableIndex += AddressPoint;
llvm::Value *VFuncPtr =
CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
return CGF.Builder.CreateLoad(VFuncPtr);
}
/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
/// indirect call to virtual functions. It makes the call through indexing
/// into the vtable.
llvm::Value *
CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
NestedNameSpecifier *Qual,
llvm::Type *Ty) {
assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
"BuildAppleKextVirtualCall - bad Qual kind");
const Type *QTy = Qual->getAsType();
QualType T = QualType(QTy, 0);
const RecordType *RT = T->getAs<RecordType>();
assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
}
/// BuildVirtualCall - This routine makes indirect vtable call for
/// call to virtual destructors. It returns 0 if it could not do it.
llvm::Value *
CodeGenFunction::BuildAppleKextVirtualDestructorCall(
const CXXDestructorDecl *DD,
CXXDtorType Type,
const CXXRecordDecl *RD) {
const auto *MD = cast<CXXMethodDecl>(DD);
// FIXME. Dtor_Base dtor is always direct!!
// It need be somehow inline expanded into the caller.
// -O does that. But need to support -O0 as well.
if (MD->isVirtual() && Type != Dtor_Base) {
// Compute the function type we're calling.
const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
DD, StructorType::Complete);
llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
}
return nullptr;
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBBITCOIN_MISC_IPP
#define LIBBITCOIN_MISC_IPP
#include <bitcoin/bitcoin/constants.hpp>
#include <bitcoin/bitcoin/math/checksum.hpp>
#include <bitcoin/bitcoin/primitives.hpp>
#include <bitcoin/bitcoin/utility/assert.hpp>
#include <bitcoin/bitcoin/utility/data.hpp>
#include <bitcoin/bitcoin/utility/serializer.hpp>
namespace libbitcoin {
// message headers
template <typename Iterator>
Iterator satoshi_save(const header_type& head, Iterator result)
{
auto serial = make_serializer(result);
serial.write_4_bytes(head.magic);
serial.write_fixed_string(head.command, command_size);
serial.write_4_bytes(head.payload_length);
if (head.checksum != 0)
serial.write_4_bytes(head.checksum);
return serial.iterator();
}
template <typename Iterator>
void satoshi_load(const Iterator first, const Iterator last,
header_type& head)
{
auto deserial = make_deserializer(first, last);
head.magic = deserial.read_4_bytes();
head.command = deserial.read_fixed_string(command_size);
head.payload_length = deserial.read_4_bytes();
head.checksum = 0;
}
// version messages
template <typename Iterator>
Iterator satoshi_save(const version_type& packet, Iterator result)
{
auto serial = make_serializer(result);
serial.write_4_bytes(packet.version);
serial.write_8_bytes(packet.services);
serial.write_8_bytes(packet.timestamp);
serial.write_network_address(packet.address_me);
serial.write_network_address(packet.address_you);
serial.write_8_bytes(packet.nonce);
serial.write_string(packet.user_agent);
serial.write_4_bytes(packet.start_height);
const uint8_t relay = packet.relay ? 1 : 0;
serial.write_byte(relay);
return serial.iterator();
}
template <typename Iterator>
void satoshi_load(const Iterator first, const Iterator last,
version_type& packet)
{
// Address timestamps are not used in the version message.
// read_network_address skips timestamp but it is read load address_type.
auto deserial = make_deserializer(first, last);
packet.version = deserial.read_4_bytes();
packet.services = deserial.read_8_bytes();
packet.timestamp = deserial.read_8_bytes();
packet.address_me = deserial.read_network_address();
packet.address_me.timestamp = 0;
if (packet.version < 106)
{
BITCOIN_ASSERT(std::distance(first, last) >= 46);
return;
}
packet.address_you = deserial.read_network_address();
packet.address_you.timestamp = 0;
packet.nonce = deserial.read_8_bytes();
packet.user_agent = deserial.read_string();
if (packet.version < 209)
{
BITCOIN_ASSERT(std::distance(first, last) >= 46 + 26 + 8 + 1);
return;
}
// The satoshi client treats 209 as the "initial protocol version"
// and disconnects peers below 31800 (for getheaders support).
packet.start_height = deserial.read_4_bytes();
if (packet.version < 70001)
{
BITCOIN_ASSERT(std::distance(first, last) >= 81 + 4);
return;
}
packet.relay = deserial.read_byte() != 0;
BITCOIN_ASSERT(std::distance(first, last) >= 85 + 1);
}
// verack messages
template <typename Iterator>
Iterator satoshi_save(const verack_type& DEBUG_ONLY(packet), Iterator result)
{
BITCOIN_ASSERT(satoshi_raw_size(packet) == 0);
return result;
}
template <typename Iterator>
void satoshi_load(const Iterator, const Iterator,
verack_type& DEBUG_ONLY(packet))
{
BITCOIN_ASSERT(satoshi_raw_size(packet) == 0);
}
// addr messages
template <typename Iterator>
Iterator satoshi_save(const address_type& packet, Iterator result)
{
auto serial = make_serializer(result);
serial.write_variable_uint(packet.addresses.size());
for (const auto& net_address: packet.addresses)
{
serial.write_4_bytes(net_address.timestamp);
serial.write_network_address(net_address);
}
return serial.iterator();
}
template <typename Iterator>
void satoshi_load(const Iterator first, const Iterator last,
address_type& packet)
{
auto deserial = make_deserializer(first, last);
uint64_t count = deserial.read_variable_uint();
for (size_t i = 0; i < count; ++i)
{
uint32_t timestamp = deserial.read_4_bytes();
network_address_type addr = deserial.read_network_address();
addr.timestamp = timestamp;
packet.addresses.push_back(addr);
}
BITCOIN_ASSERT(deserial.iterator() == first + satoshi_raw_size(packet));
BITCOIN_ASSERT(deserial.iterator() == last);
}
// getaddr messages
template <typename Iterator>
Iterator satoshi_save(const get_address_type& DEBUG_ONLY(packet),
Iterator result)
{
BITCOIN_ASSERT(satoshi_raw_size(packet) == 0);
return result;
}
template <typename Iterator>
void satoshi_load(const Iterator, const Iterator,
get_address_type& DEBUG_ONLY(packet))
{
BITCOIN_ASSERT(satoshi_raw_size(packet) == 0);
}
// inventory related stuff
BC_API uint32_t inventory_type_to_number(inventory_type_id inv_type);
BC_API inventory_type_id inventory_type_from_number(uint32_t raw_type);
template <typename Message>
size_t raw_size_inventory_impl(const Message& packet)
{
return variable_uint_size(packet.inventories.size()) +
36 * packet.inventories.size();
}
template <typename Message, typename Iterator>
Iterator save_inventory_impl(const Message& packet, Iterator result)
{
auto serial = make_serializer(result);
serial.write_variable_uint(packet.inventories.size());
for (const auto& inv: packet.inventories)
{
uint32_t raw_type = inventory_type_to_number(inv.type);
serial.write_4_bytes(raw_type);
serial.write_hash(inv.hash);
}
return serial.iterator();
}
template <typename Message, typename Iterator>
void load_inventory_impl(const Iterator first, const Iterator last,
Message& packet)
{
auto deserial = make_deserializer(first, last);
uint64_t count = deserial.read_variable_uint();
for (size_t i = 0; i < count; ++i)
{
inventory_vector_type inv;
uint32_t raw_type = deserial.read_4_bytes();
inv.type = inventory_type_from_number(raw_type);
inv.hash = deserial.read_hash();
packet.inventories.push_back(inv);
}
BITCOIN_ASSERT(deserial.iterator() == first + satoshi_raw_size(packet));
}
// inv messages
template <typename Iterator>
Iterator satoshi_save(const inventory_type& packet, Iterator result)
{
return save_inventory_impl(packet, result);
}
template <typename Iterator>
void satoshi_load(const Iterator first, const Iterator last,
inventory_type& packet)
{
load_inventory_impl(first, last, packet);
}
// getdata messages
template <typename Iterator>
Iterator satoshi_save(const get_data_type& packet, Iterator result)
{
return save_inventory_impl(packet, result);
}
template <typename Iterator>
void satoshi_load(const Iterator first, const Iterator last,
get_data_type& packet)
{
load_inventory_impl(first, last, packet);
}
// getblocks messages
template <typename Iterator>
Iterator satoshi_save(const get_blocks_type& packet, Iterator result)
{
auto serial = make_serializer(result);
serial.write_4_bytes(protocol_version);
serial.write_variable_uint(packet.start_hashes.size());
for (const auto& start_hash: packet.start_hashes)
serial.write_hash(start_hash);
serial.write_hash(packet.hash_stop);
return serial.iterator();
}
template <typename Iterator>
void satoshi_load(const Iterator first, const Iterator last,
get_blocks_type& packet)
{
auto deserial = make_deserializer(first, last);
// Discard protocol version because it is stupid
deserial.read_4_bytes();
// Note: changed to uint64_t to preclude possible loss of data.
uint64_t count = deserial.read_variable_uint();
for (uint64_t i = 0; i < count; ++i)
{
hash_digest start_hash = deserial.read_hash();
packet.start_hashes.push_back(start_hash);
}
packet.hash_stop = deserial.read_hash();
BITCOIN_ASSERT(deserial.iterator() == first + satoshi_raw_size(packet));
BITCOIN_ASSERT(deserial.iterator() == last);
}
// ping messages
template <typename Iterator>
Iterator satoshi_save(const ping_type& packet, Iterator result)
{
// We always send value, which implies our protocol version > 60000.
auto serial = make_serializer(result);
serial.write_8_bytes(packet.nonce);
return serial.iterator();
}
template <typename Iterator>
void satoshi_load(const Iterator first, const Iterator last,
ping_type& packet)
{
// We require a value, implying a peer protocol version > 60000 (BIP31).
// We are currently setting protocol_version to 60001.
auto deserial = make_deserializer(first, last);
packet.nonce = deserial.read_8_bytes();
BITCOIN_ASSERT(deserial.iterator() == first + satoshi_raw_size(packet));
BITCOIN_ASSERT(deserial.iterator() == last);
}
// pong messages
template <typename Iterator>
Iterator satoshi_save(const pong_type& packet, Iterator result)
{
auto serial = make_serializer(result);
serial.write_8_bytes(packet.nonce);
return serial.iterator();
}
template <typename Iterator>
void satoshi_load(const Iterator first, const Iterator last,
pong_type& packet)
{
auto deserial = make_deserializer(first, last);
packet.nonce = deserial.read_8_bytes();
BITCOIN_ASSERT(deserial.iterator() == first + satoshi_raw_size(packet));
BITCOIN_ASSERT(deserial.iterator() == last);
}
template <typename Message>
data_chunk create_raw_message(const Message& packet)
{
const auto payload_size = static_cast<uint32_t>(satoshi_raw_size(packet));
// Serialize the payload (required for header size).
data_chunk payload(payload_size);
satoshi_save(packet, payload.begin());
// Construct the header.
header_type header;
header.magic = bc::magic_value;
header.command = satoshi_command(packet);
header.payload_length = payload_size;
header.checksum = bitcoin_checksum(payload);
// Serialize header and copy the payload into a single message buffer.
data_chunk message(satoshi_raw_size(header));
satoshi_save(header, message.begin());
extend_data(message, payload);
return message;
}
} // libbitcoin
#endif
<commit_msg>Remove dead code.<commit_after><|endoftext|> |
<commit_before>cc973f44-2e4e-11e5-9284-b827eb9e62be<commit_msg>cc9c3bf2-2e4e-11e5-9284-b827eb9e62be<commit_after>cc9c3bf2-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>9a0602ea-2e4e-11e5-9284-b827eb9e62be<commit_msg>9a0b351c-2e4e-11e5-9284-b827eb9e62be<commit_after>9a0b351c-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>497b22f6-2e4e-11e5-9284-b827eb9e62be<commit_msg>49802044-2e4e-11e5-9284-b827eb9e62be<commit_after>49802044-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>#include "ResourceView.hpp"
#include <Engine/Geometry/Model.hpp>
#include <Engine/Texture/TextureAsset.hpp>
#include <Engine/Audio/SoundBuffer.hpp>
#include <Engine/Script/ScriptFile.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <Editor/Util/EditorSettings.hpp>
#include <Engine/Hymn.hpp>
#include <Engine/Entity/Entity.hpp>
#include <Engine/MainWindow.hpp>
#include <imgui.h>
#include <limits>
#include "../ImGui/Splitter.hpp"
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ResourceManager.hpp>
#include <cstdio>
#include <Utility/Log.hpp>
using namespace GUI;
using namespace std;
ResourceView::ResourceView() {
}
void ResourceView::Show() {
ImVec2 size(MainWindow::GetInstance()->GetSize().x, MainWindow::GetInstance()->GetSize().y);
// Splitter.
ImGui::VerticalSplitter(ImVec2(sceneWidth, size.y - resourceHeight), size.x - sceneWidth - editorWidth, splitterSize, resourceHeight, resourceResize, 20, size.y - 20);
if (resourceResize)
resourceHeight = size.y - resourceHeight;
ImGui::SetNextWindowPos(ImVec2(sceneWidth, size.y - resourceHeight));
ImGui::SetNextWindowSize(ImVec2(size.x - sceneWidth - editorWidth, resourceHeight));
ImGui::Begin("Resources", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders);
/// @todo Add resources.
// Show resources.
scriptPressed = false;
texturePressed = false;
modelPressed = false;
soundPressed = false;
ShowResourceFolder(Resources().resourceFolder, Resources().resourceFolder.name);
// Change scene.
if (changeScene) {
if (Hymn().GetPath() != "") {
savePromptWindow.SetVisible(true);
savePromptWindow.Show();
switch (savePromptWindow.GetDecision()) {
case 0:
sceneEditor.Save();
sceneEditor.SetVisible(true);
sceneEditor.SetScene(scene);
Resources().activeScene = resourcePath + "/" + *scene;
sceneEditor.entityEditor.SetVisible(false);
Hymn().world.Clear();
Hymn().world.Load(Hymn().GetPath() + "/" + Resources().activeScene + ".json");
changeScene = false;
savePromptWindow.SetVisible(false);
savePromptWindow.ResetDecision();
break;
case 1:
sceneEditor.SetVisible(true);
sceneEditor.SetScene(scene);
Resources().activeScene = resourcePath + "/" + *scene;
sceneEditor.entityEditor.SetVisible(false);
Hymn().world.Clear();
Hymn().world.Load(Hymn().GetPath() + "/" + Resources().activeScene + ".json");
changeScene = false;
savePromptWindow.SetVisible(false);
savePromptWindow.ResetDecision();
break;
default:
break;
}
}
}
if (sceneEditor.entityPressed || scriptPressed || texturePressed || modelPressed || soundPressed) {
sceneEditor.entityEditor.SetVisible(sceneEditor.entityPressed);
scriptEditor.SetVisible(scriptPressed);
textureEditor.SetVisible(texturePressed);
modelEditor.SetVisible(modelPressed);
soundEditor.SetVisible(soundPressed);
}
if (sceneEditor.IsVisible()) {
ImGui::HorizontalSplitter(ImVec2(sceneWidth, 20), size.y - 20, splitterSize, sceneWidth, sceneResize, 20, size.x - editorWidth - 20);
ImGui::SetNextWindowPos(ImVec2(0, 20));
ImGui::SetNextWindowSize(ImVec2(sceneWidth, size.y - 20));
sceneEditor.Show();
}
if (sceneEditor.entityEditor.IsVisible() || scriptEditor.IsVisible() || textureEditor.IsVisible() || modelEditor.IsVisible() || soundEditor.IsVisible()) {
editorWidth = size.x - editorWidth;
ImGui::HorizontalSplitter(ImVec2(editorWidth, 20), size.y - 20, splitterSize, editorWidth, editorResize, sceneWidth + 20, size.x - 20);
editorWidth = size.x - editorWidth;
ImGui::SetNextWindowPos(ImVec2(size.x - editorWidth, 20));
ImGui::SetNextWindowSize(ImVec2(editorWidth, size.y - 20));
}
if (sceneEditor.entityEditor.IsVisible())
sceneEditor.entityEditor.Show();
if (scriptEditor.IsVisible())
scriptEditor.Show();
if (textureEditor.IsVisible())
textureEditor.Show();
if (modelEditor.IsVisible())
modelEditor.Show();
if (soundEditor.IsVisible())
soundEditor.Show();
ImGui::End();
}
bool ResourceView::IsVisible() const {
return visible;
}
void ResourceView::SetVisible(bool visible) {
this->visible = visible;
}
void ResourceView::HideEditors() {
sceneEditor.SetVisible(false);
sceneEditor.entityEditor.SetVisible(false);
scriptEditor.SetVisible(false);
modelEditor.SetVisible(false);
textureEditor.SetVisible(false);
soundEditor.SetVisible(false);
}
void ResourceView::SaveScene() const {
sceneEditor.Save();
}
#undef max
void ResourceView::ResetScene() {
sceneEditor.SetScene(nullptr);
sceneEditor.SetVisible(false);
}
SceneEditor& ResourceView::GetScene() {
return sceneEditor;
}
void ResourceView::ShowResourceFolder(ResourceList::ResourceFolder& folder, const std::string& path) {
bool opened = ImGui::TreeNode(folder.name.c_str());
/// @todo Remove folder.
if (opened) {
// Show subfolders.
for (ResourceList::ResourceFolder& subfolder : folder.subfolders) {
ShowResourceFolder(subfolder, path + "/" + subfolder.name);
}
// Show resources.
for (auto it = folder.resources.begin(); it != folder.resources.end(); ++it) {
if (ShowResource(*it, path)) {
folder.resources.erase(it);
return;
}
}
ImGui::TreePop();
}
}
bool ResourceView::ShowResource(ResourceList::Resource& resource, const std::string& path) {
// Scene.
if (resource.type == ResourceList::Resource::SCENE) {
if (ImGui::Selectable(resource.scene.c_str())) {
// Sets to don't save when opening first scene.
if (scene == nullptr) {
changeScene = true;
resourcePath = path;
scene = &resource.scene;
savePromptWindow.SetVisible(false);
savePromptWindow.SetDecision(1);
} else {
// Does so that the prompt window won't show if you select active scene.
if (resource.scene != Resources().activeScene) {
changeScene = true;
resourcePath = path;
scene = &resource.scene;
savePromptWindow.SetTitle("Save before you switch scene?");
}
}
}
// Delete scene.
if (ImGui::BeginPopupContextItem(resource.scene.c_str())) {
if (ImGui::Selectable("Delete")) {
if (Resources().activeScene == resource.scene) {
Resources().activeScene = "";
sceneEditor.SetScene(nullptr);
}
ImGui::EndPopup();
return true;
}
ImGui::EndPopup();
}
}
/*
// Models.
bool modelPressed = false;
if (ImGui::TreeNode("Models")) {
if (ImGui::Button("Add model")) {
Geometry::Model* model = new Geometry::Model();
model->name = "Model #" + std::to_string(Resources().modelNumber++);
Resources().models.push_back(model);
}
for (auto it = Resources().models.begin(); it != Resources().models.end(); ++it) {
Geometry::Model* model = *it;
if (ImGui::Selectable(model->name.c_str())) {
modelPressed = true;
modelEditor.SetModel(model);
}
if (ImGui::BeginPopupContextItem(model->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (modelEditor.GetModel() == model)
modelEditor.SetVisible(false);
delete model;
Resources().models.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Textures.
bool texturePressed = false;
if (ImGui::TreeNode("Textures")) {
if (ImGui::Button("Add texture")) {
TextureAsset* texture = new TextureAsset();
texture->name = "Texture #" + std::to_string(Resources().textureNumber++);
Resources().textures.push_back(texture);
}
for (auto it = Resources().textures.begin(); it != Resources().textures.end(); ++it) {
TextureAsset* texture = *it;
if (ImGui::Selectable(texture->name.c_str())) {
texturePressed = true;
textureEditor.SetTexture(texture);
}
if (ImGui::BeginPopupContextItem(texture->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (Managers().resourceManager->GetTextureAssetInstanceCount(texture) > 1) {
Log() << "This texture is in use. Remove all references to the texture first.\n";
} else {
if (textureEditor.GetTexture() == texture)
textureEditor.SetVisible(false);
// Remove files.
remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".png").c_str());
remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".json").c_str());
Managers().resourceManager->FreeTextureAsset(texture);
Resources().textures.erase(it);
}
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Scripts.
bool scriptPressed = false;
if (ImGui::TreeNode("Scripts")) {
if (ImGui::Button("Add script")) {
ScriptFile* scriptFile = new ScriptFile();
scriptFile->name = "Script #" + std::to_string(Hymn().scriptNumber++);
Hymn().scripts.push_back(scriptFile);
}
for (auto it = Hymn().scripts.begin(); it != Hymn().scripts.end(); ++it) {
ScriptFile* script = *it;
std::string name = script->name;
if (ImGui::Selectable(name.c_str())) {
scriptPressed = true;
scriptEditor.SetScript(script);
}
if (ImGui::BeginPopupContextItem(name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (scriptEditor.GetScript() == script)
scriptEditor.SetVisible(false);
delete script;
Hymn().scripts.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Sounds.
bool soundPressed = false;
if (ImGui::TreeNode("Sounds")) {
if (ImGui::Button("Add sound")) {
Audio::SoundBuffer* sound = new Audio::SoundBuffer();
sound->name = "Sound #" + std::to_string(Resources().soundNumber++);
Resources().sounds.push_back(sound);
}
for (auto it = Resources().sounds.begin(); it != Resources().sounds.end(); ++it) {
Audio::SoundBuffer* sound = *it;
if (ImGui::Selectable(sound->name.c_str())) {
soundPressed = true;
soundEditor.SetSound(sound);
}
if (ImGui::BeginPopupContextItem(sound->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (soundEditor.GetSound() == sound)
soundEditor.SetVisible(false);
delete sound;
Resources().sounds.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}*/
return false;
}
<commit_msg>Add resource menu<commit_after>#include "ResourceView.hpp"
#include <Engine/Geometry/Model.hpp>
#include <Engine/Texture/TextureAsset.hpp>
#include <Engine/Audio/SoundBuffer.hpp>
#include <Engine/Script/ScriptFile.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <Editor/Util/EditorSettings.hpp>
#include <Engine/Hymn.hpp>
#include <Engine/Entity/Entity.hpp>
#include <Engine/MainWindow.hpp>
#include <imgui.h>
#include <limits>
#include "../ImGui/Splitter.hpp"
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ResourceManager.hpp>
#include <cstdio>
#include <Utility/Log.hpp>
using namespace GUI;
using namespace std;
ResourceView::ResourceView() {
}
void ResourceView::Show() {
ImVec2 size(MainWindow::GetInstance()->GetSize().x, MainWindow::GetInstance()->GetSize().y);
// Splitter.
ImGui::VerticalSplitter(ImVec2(sceneWidth, size.y - resourceHeight), size.x - sceneWidth - editorWidth, splitterSize, resourceHeight, resourceResize, 20, size.y - 20);
if (resourceResize)
resourceHeight = size.y - resourceHeight;
ImGui::SetNextWindowPos(ImVec2(sceneWidth, size.y - resourceHeight));
ImGui::SetNextWindowSize(ImVec2(size.x - sceneWidth - editorWidth, resourceHeight));
ImGui::Begin("Resources", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders);
// Show resources.
scriptPressed = false;
texturePressed = false;
modelPressed = false;
soundPressed = false;
ShowResourceFolder(Resources().resourceFolder, Resources().resourceFolder.name);
// Change scene.
if (changeScene) {
if (Hymn().GetPath() != "") {
savePromptWindow.SetVisible(true);
savePromptWindow.Show();
switch (savePromptWindow.GetDecision()) {
case 0:
sceneEditor.Save();
sceneEditor.SetVisible(true);
sceneEditor.SetScene(scene);
Resources().activeScene = resourcePath + "/" + *scene;
sceneEditor.entityEditor.SetVisible(false);
Hymn().world.Clear();
Hymn().world.Load(Hymn().GetPath() + "/" + Resources().activeScene + ".json");
changeScene = false;
savePromptWindow.SetVisible(false);
savePromptWindow.ResetDecision();
break;
case 1:
sceneEditor.SetVisible(true);
sceneEditor.SetScene(scene);
Resources().activeScene = resourcePath + "/" + *scene;
sceneEditor.entityEditor.SetVisible(false);
Hymn().world.Clear();
Hymn().world.Load(Hymn().GetPath() + "/" + Resources().activeScene + ".json");
changeScene = false;
savePromptWindow.SetVisible(false);
savePromptWindow.ResetDecision();
break;
default:
break;
}
}
}
if (sceneEditor.entityPressed || scriptPressed || texturePressed || modelPressed || soundPressed) {
sceneEditor.entityEditor.SetVisible(sceneEditor.entityPressed);
scriptEditor.SetVisible(scriptPressed);
textureEditor.SetVisible(texturePressed);
modelEditor.SetVisible(modelPressed);
soundEditor.SetVisible(soundPressed);
}
if (sceneEditor.IsVisible()) {
ImGui::HorizontalSplitter(ImVec2(sceneWidth, 20), size.y - 20, splitterSize, sceneWidth, sceneResize, 20, size.x - editorWidth - 20);
ImGui::SetNextWindowPos(ImVec2(0, 20));
ImGui::SetNextWindowSize(ImVec2(sceneWidth, size.y - 20));
sceneEditor.Show();
}
if (sceneEditor.entityEditor.IsVisible() || scriptEditor.IsVisible() || textureEditor.IsVisible() || modelEditor.IsVisible() || soundEditor.IsVisible()) {
editorWidth = size.x - editorWidth;
ImGui::HorizontalSplitter(ImVec2(editorWidth, 20), size.y - 20, splitterSize, editorWidth, editorResize, sceneWidth + 20, size.x - 20);
editorWidth = size.x - editorWidth;
ImGui::SetNextWindowPos(ImVec2(size.x - editorWidth, 20));
ImGui::SetNextWindowSize(ImVec2(editorWidth, size.y - 20));
}
if (sceneEditor.entityEditor.IsVisible())
sceneEditor.entityEditor.Show();
if (scriptEditor.IsVisible())
scriptEditor.Show();
if (textureEditor.IsVisible())
textureEditor.Show();
if (modelEditor.IsVisible())
modelEditor.Show();
if (soundEditor.IsVisible())
soundEditor.Show();
ImGui::End();
}
bool ResourceView::IsVisible() const {
return visible;
}
void ResourceView::SetVisible(bool visible) {
this->visible = visible;
}
void ResourceView::HideEditors() {
sceneEditor.SetVisible(false);
sceneEditor.entityEditor.SetVisible(false);
scriptEditor.SetVisible(false);
modelEditor.SetVisible(false);
textureEditor.SetVisible(false);
soundEditor.SetVisible(false);
}
void ResourceView::SaveScene() const {
sceneEditor.Save();
}
#undef max
void ResourceView::ResetScene() {
sceneEditor.SetScene(nullptr);
sceneEditor.SetVisible(false);
}
SceneEditor& ResourceView::GetScene() {
return sceneEditor;
}
void ResourceView::ShowResourceFolder(ResourceList::ResourceFolder& folder, const std::string& path) {
bool opened = ImGui::TreeNode(folder.name.c_str());
if (ImGui::BeginPopupContextItem(folder.name.c_str())) {
/// @todo Add subfolder.
if (ImGui::Selectable("Add folder")) {
}
/// @todo Add scene.
if (ImGui::Selectable("Add scene")) {
}
/// @todo Add model.
if (ImGui::Selectable("Add model")) {
}
/// @todo Add texture.
if (ImGui::Selectable("Add texture")) {
}
/// @todo Add script.
if (ImGui::Selectable("Add script")) {
}
/// @todo Add sound.
if (ImGui::Selectable("Add sound")) {
}
/// @todo Remove folder.
ImGui::EndPopup();
}
if (opened) {
// Show subfolders.
for (ResourceList::ResourceFolder& subfolder : folder.subfolders) {
ShowResourceFolder(subfolder, path + "/" + subfolder.name);
}
// Show resources.
for (auto it = folder.resources.begin(); it != folder.resources.end(); ++it) {
if (ShowResource(*it, path)) {
folder.resources.erase(it);
return;
}
}
ImGui::TreePop();
}
}
bool ResourceView::ShowResource(ResourceList::Resource& resource, const std::string& path) {
// Scene.
if (resource.type == ResourceList::Resource::SCENE) {
if (ImGui::Selectable(resource.scene.c_str())) {
// Sets to don't save when opening first scene.
if (scene == nullptr) {
changeScene = true;
resourcePath = path;
scene = &resource.scene;
savePromptWindow.SetVisible(false);
savePromptWindow.SetDecision(1);
} else {
// Does so that the prompt window won't show if you select active scene.
if (resource.scene != Resources().activeScene) {
changeScene = true;
resourcePath = path;
scene = &resource.scene;
savePromptWindow.SetTitle("Save before you switch scene?");
}
}
}
// Delete scene.
if (ImGui::BeginPopupContextItem(resource.scene.c_str())) {
if (ImGui::Selectable("Delete")) {
if (Resources().activeScene == resource.scene) {
Resources().activeScene = "";
sceneEditor.SetScene(nullptr);
}
ImGui::EndPopup();
return true;
}
ImGui::EndPopup();
}
}
/*
// Models.
bool modelPressed = false;
if (ImGui::TreeNode("Models")) {
if (ImGui::Button("Add model")) {
Geometry::Model* model = new Geometry::Model();
model->name = "Model #" + std::to_string(Resources().modelNumber++);
Resources().models.push_back(model);
}
for (auto it = Resources().models.begin(); it != Resources().models.end(); ++it) {
Geometry::Model* model = *it;
if (ImGui::Selectable(model->name.c_str())) {
modelPressed = true;
modelEditor.SetModel(model);
}
if (ImGui::BeginPopupContextItem(model->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (modelEditor.GetModel() == model)
modelEditor.SetVisible(false);
delete model;
Resources().models.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Textures.
bool texturePressed = false;
if (ImGui::TreeNode("Textures")) {
if (ImGui::Button("Add texture")) {
TextureAsset* texture = new TextureAsset();
texture->name = "Texture #" + std::to_string(Resources().textureNumber++);
Resources().textures.push_back(texture);
}
for (auto it = Resources().textures.begin(); it != Resources().textures.end(); ++it) {
TextureAsset* texture = *it;
if (ImGui::Selectable(texture->name.c_str())) {
texturePressed = true;
textureEditor.SetTexture(texture);
}
if (ImGui::BeginPopupContextItem(texture->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (Managers().resourceManager->GetTextureAssetInstanceCount(texture) > 1) {
Log() << "This texture is in use. Remove all references to the texture first.\n";
} else {
if (textureEditor.GetTexture() == texture)
textureEditor.SetVisible(false);
// Remove files.
remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".png").c_str());
remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".json").c_str());
Managers().resourceManager->FreeTextureAsset(texture);
Resources().textures.erase(it);
}
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Scripts.
bool scriptPressed = false;
if (ImGui::TreeNode("Scripts")) {
if (ImGui::Button("Add script")) {
ScriptFile* scriptFile = new ScriptFile();
scriptFile->name = "Script #" + std::to_string(Hymn().scriptNumber++);
Hymn().scripts.push_back(scriptFile);
}
for (auto it = Hymn().scripts.begin(); it != Hymn().scripts.end(); ++it) {
ScriptFile* script = *it;
std::string name = script->name;
if (ImGui::Selectable(name.c_str())) {
scriptPressed = true;
scriptEditor.SetScript(script);
}
if (ImGui::BeginPopupContextItem(name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (scriptEditor.GetScript() == script)
scriptEditor.SetVisible(false);
delete script;
Hymn().scripts.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Sounds.
bool soundPressed = false;
if (ImGui::TreeNode("Sounds")) {
if (ImGui::Button("Add sound")) {
Audio::SoundBuffer* sound = new Audio::SoundBuffer();
sound->name = "Sound #" + std::to_string(Resources().soundNumber++);
Resources().sounds.push_back(sound);
}
for (auto it = Resources().sounds.begin(); it != Resources().sounds.end(); ++it) {
Audio::SoundBuffer* sound = *it;
if (ImGui::Selectable(sound->name.c_str())) {
soundPressed = true;
soundEditor.SetSound(sound);
}
if (ImGui::BeginPopupContextItem(sound->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (soundEditor.GetSound() == sound)
soundEditor.SetVisible(false);
delete sound;
Resources().sounds.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}*/
return false;
}
<|endoftext|> |
<commit_before>#include "ResourceView.hpp"
#include <Engine/Geometry/Model.hpp>
#include <Engine/Texture/TextureAsset.hpp>
#include <Engine/Audio/SoundBuffer.hpp>
#include <Engine/Script/ScriptFile.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <Engine/Hymn.hpp>
#include <DefaultAlbedo.png.hpp>
#include <Engine/MainWindow.hpp>
#include <imgui.h>
#include <limits>
#include "../ImGui/Splitter.hpp"
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ResourceManager.hpp>
#include <cstdio>
#include <Utility/Log.hpp>
using namespace GUI;
using namespace std;
ResourceView::ResourceView() {
folderNameWindow.SetClosedCallback(std::bind(&ResourceView::FileNameWindowClosed, this, placeholders::_1));
}
void ResourceView::Show() {
ImVec2 size(MainWindow::GetInstance()->GetSize().x, MainWindow::GetInstance()->GetSize().y);
// Splitter.
ImGui::VerticalSplitter(ImVec2(sceneWidth, size.y - resourceHeight), size.x - sceneWidth - editorWidth, splitterSize, resourceHeight, resourceResize, 20, size.y - 20);
if (resourceResize)
resourceHeight = size.y - resourceHeight;
ImGui::SetNextWindowPos(ImVec2(sceneWidth, size.y - resourceHeight));
ImGui::SetNextWindowSize(ImVec2(size.x - sceneWidth - editorWidth, resourceHeight));
ImGui::Begin("Resources", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders);
// Show resources.
scriptPressed = false;
texturePressed = false;
modelPressed = false;
soundPressed = false;
ShowResourceFolder(Resources().resourceFolder, Resources().resourceFolder.name);
// Change scene.
if (changeScene) {
if (Hymn().GetPath() != "") {
savePromptWindow.SetVisible(true);
savePromptWindow.Show();
switch (savePromptWindow.GetDecision()) {
case 0:
sceneEditor.Save();
sceneEditor.SetVisible(true);
sceneEditor.SetScene(resourcePath, scene);
Resources().activeScene = resourcePath + "/" + *scene;
sceneEditor.entityEditor.SetVisible(false);
Hymn().world.Clear();
Hymn().world.Load(Hymn().GetPath() + "/" + Resources().activeScene + ".json");
changeScene = false;
savePromptWindow.SetVisible(false);
savePromptWindow.ResetDecision();
break;
case 1:
sceneEditor.SetVisible(true);
sceneEditor.SetScene(resourcePath, scene);
Resources().activeScene = resourcePath + "/" + *scene;
sceneEditor.entityEditor.SetVisible(false);
Hymn().world.Clear();
Hymn().world.Load(Hymn().GetPath() + "/" + Resources().activeScene + ".json");
changeScene = false;
savePromptWindow.SetVisible(false);
savePromptWindow.ResetDecision();
break;
case 2:
changeScene = false;
savePromptWindow.ResetDecision();
savePromptWindow.SetVisible(false);
break;
default:
break;
}
}
}
// Create folder.
if (folderNameWindow.IsVisible())
folderNameWindow.Show();
if (sceneEditor.entityPressed || scriptPressed || texturePressed || modelPressed || soundPressed) {
sceneEditor.entityEditor.SetVisible(sceneEditor.entityPressed);
scriptEditor.SetVisible(scriptPressed);
textureEditor.SetVisible(texturePressed);
modelEditor.SetVisible(modelPressed);
soundEditor.SetVisible(soundPressed);
}
if (sceneEditor.IsVisible()) {
ImGui::HorizontalSplitter(ImVec2(sceneWidth, 20), size.y - 20, splitterSize, sceneWidth, sceneResize, 20, size.x - editorWidth - 20);
ImGui::SetNextWindowPos(ImVec2(0, 20));
ImGui::SetNextWindowSize(ImVec2(sceneWidth, size.y - 20));
sceneEditor.Show();
}
if (sceneEditor.entityEditor.IsVisible() || scriptEditor.IsVisible() || textureEditor.IsVisible() || modelEditor.IsVisible() || soundEditor.IsVisible()) {
editorWidth = size.x - editorWidth;
ImGui::HorizontalSplitter(ImVec2(editorWidth, 20), size.y - 20, splitterSize, editorWidth, editorResize, sceneWidth + 20, size.x - 20);
editorWidth = size.x - editorWidth;
ImGui::SetNextWindowPos(ImVec2(size.x - editorWidth, 20));
ImGui::SetNextWindowSize(ImVec2(editorWidth, size.y - 20));
}
if (sceneEditor.entityEditor.IsVisible())
sceneEditor.entityEditor.Show();
if (scriptEditor.IsVisible())
scriptEditor.Show();
if (textureEditor.IsVisible())
textureEditor.Show();
if (modelEditor.IsVisible())
modelEditor.Show();
if (soundEditor.IsVisible())
soundEditor.Show();
ImGui::End();
}
bool ResourceView::IsVisible() const {
return visible;
}
void ResourceView::SetVisible(bool visible) {
this->visible = visible;
}
void ResourceView::HideEditors() {
sceneEditor.SetVisible(false);
sceneEditor.entityEditor.SetVisible(false);
scriptEditor.SetVisible(false);
modelEditor.SetVisible(false);
textureEditor.SetVisible(false);
soundEditor.SetVisible(false);
}
void ResourceView::SaveScene() const {
sceneEditor.Save();
}
#undef max
void ResourceView::ResetScene() {
sceneEditor.SetScene("", nullptr);
sceneEditor.SetVisible(false);
}
SceneEditor& ResourceView::GetScene() {
return sceneEditor;
}
void ResourceView::ShowResourceFolder(ResourceList::ResourceFolder& folder, const std::string& path) {
bool opened = ImGui::TreeNode(folder.name.c_str());
if (ImGui::BeginPopupContextItem(folder.name.c_str())) {
// Add subfolder.
if (ImGui::Selectable("Add folder")) {
resourcePath = path;
parentFolder = &folder;
folderNameWindow.SetVisible(true);
return;
}
// Add scene.
if (ImGui::Selectable("Add scene")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::SCENE;
resource.scene = "Scene #" + std::to_string(Resources().sceneNumber++);
folder.resources.push_back(resource);
return;
}
// Add model.
if (ImGui::Selectable("Add model")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::MODEL;
resource.model = new Geometry::Model();
resource.model->name = "Model #" + std::to_string(Resources().modelNumber++);
folder.resources.push_back(resource);
return;
}
// Add texture.
if (ImGui::Selectable("Add texture")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::TEXTURE;
string name = path + "/Texture #" + std::to_string(Resources().textureNumber++);
resource.texture = Managers().resourceManager->CreateTextureAsset(name, Managers().resourceManager->CreateTexture2D(DEFAULTALBEDO_PNG, DEFAULTALBEDO_PNG_LENGTH));
folder.resources.push_back(resource);
return;
}
// Add script.
if (ImGui::Selectable("Add script")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::SCRIPT;
resource.script = new ScriptFile();
resource.script->path = path + "/";
resource.script->name = "Script #" + std::to_string(Hymn().scriptNumber++);
Hymn().scripts.push_back(resource.script);
folder.resources.push_back(resource);
return;
}
/// @todo Add sound.
if (ImGui::Selectable("Add sound")) {
}
/// @todo Remove folder.
ImGui::EndPopup();
}
if (opened) {
// Show subfolders.
for (ResourceList::ResourceFolder& subfolder : folder.subfolders) {
ShowResourceFolder(subfolder, path + "/" + subfolder.name);
}
// Show resources.
for (auto it = folder.resources.begin(); it != folder.resources.end(); ++it) {
if (ShowResource(*it, path)) {
folder.resources.erase(it);
return;
}
}
ImGui::TreePop();
}
}
bool ResourceView::ShowResource(ResourceList::Resource& resource, const std::string& path) {
// Scene.
if (resource.type == ResourceList::Resource::SCENE) {
if (ImGui::Selectable(resource.scene.c_str())) {
// Sets to don't save when opening first scene.
if (scene == nullptr) {
changeScene = true;
resourcePath = path;
scene = &resource.scene;
savePromptWindow.SetVisible(false);
savePromptWindow.SetDecision(1);
} else {
// Does so that the prompt window won't show if you select active scene.
if (resource.scene != Resources().activeScene) {
changeScene = true;
resourcePath = path;
scene = &resource.scene;
savePromptWindow.SetTitle("Save before you switch scene?");
}
}
}
// Delete scene.
if (ImGui::BeginPopupContextItem(resource.scene.c_str())) {
if (ImGui::Selectable("Delete")) {
if (Resources().activeScene == resource.scene) {
Resources().activeScene = "";
sceneEditor.SetScene("", nullptr);
}
ImGui::EndPopup();
return true;
}
ImGui::EndPopup();
}
}
/*
// Models.
bool modelPressed = false;
if (ImGui::TreeNode("Models")) {
for (auto it = Resources().models.begin(); it != Resources().models.end(); ++it) {
Geometry::Model* model = *it;
if (ImGui::Selectable(model->name.c_str())) {
modelPressed = true;
modelEditor.SetModel(model);
}
if (ImGui::BeginPopupContextItem(model->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (modelEditor.GetModel() == model)
modelEditor.SetVisible(false);
delete model;
Resources().models.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Textures.
bool texturePressed = false;
if (ImGui::TreeNode("Textures")) {
for (auto it = Resources().textures.begin(); it != Resources().textures.end(); ++it) {
TextureAsset* texture = *it;
if (ImGui::Selectable(texture->name.c_str())) {
texturePressed = true;
textureEditor.SetTexture(texture);
}
if (ImGui::BeginPopupContextItem(texture->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (Managers().resourceManager->GetTextureAssetInstanceCount(texture) > 1) {
Log() << "This texture is in use. Remove all references to the texture first.\n";
} else {
if (textureEditor.GetTexture() == texture)
textureEditor.SetVisible(false);
// Remove files.
remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".png").c_str());
remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".json").c_str());
Managers().resourceManager->FreeTextureAsset(texture);
Resources().textures.erase(it);
}
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Scripts.
bool scriptPressed = false;
if (ImGui::TreeNode("Scripts")) {
for (auto it = Hymn().scripts.begin(); it != Hymn().scripts.end(); ++it) {
ScriptFile* script = *it;
std::string name = script->name;
if (ImGui::Selectable(name.c_str())) {
scriptPressed = true;
scriptEditor.SetScript(script);
}
if (ImGui::BeginPopupContextItem(name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (scriptEditor.GetScript() == script)
scriptEditor.SetVisible(false);
delete script;
Hymn().scripts.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Sounds.
bool soundPressed = false;
if (ImGui::TreeNode("Sounds")) {
if (ImGui::Button("Add sound")) {
Audio::SoundBuffer* sound = new Audio::SoundBuffer();
sound->name = "Sound #" + std::to_string(Resources().soundNumber++);
Resources().sounds.push_back(sound);
}
for (auto it = Resources().sounds.begin(); it != Resources().sounds.end(); ++it) {
Audio::SoundBuffer* sound = *it;
if (ImGui::Selectable(sound->name.c_str())) {
soundPressed = true;
soundEditor.SetSound(sound);
}
if (ImGui::BeginPopupContextItem(sound->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (soundEditor.GetSound() == sound)
soundEditor.SetVisible(false);
delete sound;
Resources().sounds.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}*/
return false;
}
void ResourceView::FileNameWindowClosed(const std::string& name) {
if (!name.empty()) {
ResourceList::ResourceFolder folder;
folder.name = name;
parentFolder->subfolders.push_back(folder);
FileSystem::CreateDirectory((Hymn().GetPath() + "/" + resourcePath + "/" + name).c_str());
}
}
<commit_msg>Add sound<commit_after>#include "ResourceView.hpp"
#include <Engine/Geometry/Model.hpp>
#include <Engine/Texture/TextureAsset.hpp>
#include <Engine/Audio/SoundBuffer.hpp>
#include <Engine/Script/ScriptFile.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <Engine/Hymn.hpp>
#include <DefaultAlbedo.png.hpp>
#include <Engine/MainWindow.hpp>
#include <imgui.h>
#include <limits>
#include "../ImGui/Splitter.hpp"
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ResourceManager.hpp>
#include <cstdio>
#include <Utility/Log.hpp>
using namespace GUI;
using namespace std;
ResourceView::ResourceView() {
folderNameWindow.SetClosedCallback(std::bind(&ResourceView::FileNameWindowClosed, this, placeholders::_1));
}
void ResourceView::Show() {
ImVec2 size(MainWindow::GetInstance()->GetSize().x, MainWindow::GetInstance()->GetSize().y);
// Splitter.
ImGui::VerticalSplitter(ImVec2(sceneWidth, size.y - resourceHeight), size.x - sceneWidth - editorWidth, splitterSize, resourceHeight, resourceResize, 20, size.y - 20);
if (resourceResize)
resourceHeight = size.y - resourceHeight;
ImGui::SetNextWindowPos(ImVec2(sceneWidth, size.y - resourceHeight));
ImGui::SetNextWindowSize(ImVec2(size.x - sceneWidth - editorWidth, resourceHeight));
ImGui::Begin("Resources", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders);
// Show resources.
scriptPressed = false;
texturePressed = false;
modelPressed = false;
soundPressed = false;
ShowResourceFolder(Resources().resourceFolder, Resources().resourceFolder.name);
// Change scene.
if (changeScene) {
if (Hymn().GetPath() != "") {
savePromptWindow.SetVisible(true);
savePromptWindow.Show();
switch (savePromptWindow.GetDecision()) {
case 0:
sceneEditor.Save();
sceneEditor.SetVisible(true);
sceneEditor.SetScene(resourcePath, scene);
Resources().activeScene = resourcePath + "/" + *scene;
sceneEditor.entityEditor.SetVisible(false);
Hymn().world.Clear();
Hymn().world.Load(Hymn().GetPath() + "/" + Resources().activeScene + ".json");
changeScene = false;
savePromptWindow.SetVisible(false);
savePromptWindow.ResetDecision();
break;
case 1:
sceneEditor.SetVisible(true);
sceneEditor.SetScene(resourcePath, scene);
Resources().activeScene = resourcePath + "/" + *scene;
sceneEditor.entityEditor.SetVisible(false);
Hymn().world.Clear();
Hymn().world.Load(Hymn().GetPath() + "/" + Resources().activeScene + ".json");
changeScene = false;
savePromptWindow.SetVisible(false);
savePromptWindow.ResetDecision();
break;
case 2:
changeScene = false;
savePromptWindow.ResetDecision();
savePromptWindow.SetVisible(false);
break;
default:
break;
}
}
}
// Create folder.
if (folderNameWindow.IsVisible())
folderNameWindow.Show();
if (sceneEditor.entityPressed || scriptPressed || texturePressed || modelPressed || soundPressed) {
sceneEditor.entityEditor.SetVisible(sceneEditor.entityPressed);
scriptEditor.SetVisible(scriptPressed);
textureEditor.SetVisible(texturePressed);
modelEditor.SetVisible(modelPressed);
soundEditor.SetVisible(soundPressed);
}
if (sceneEditor.IsVisible()) {
ImGui::HorizontalSplitter(ImVec2(sceneWidth, 20), size.y - 20, splitterSize, sceneWidth, sceneResize, 20, size.x - editorWidth - 20);
ImGui::SetNextWindowPos(ImVec2(0, 20));
ImGui::SetNextWindowSize(ImVec2(sceneWidth, size.y - 20));
sceneEditor.Show();
}
if (sceneEditor.entityEditor.IsVisible() || scriptEditor.IsVisible() || textureEditor.IsVisible() || modelEditor.IsVisible() || soundEditor.IsVisible()) {
editorWidth = size.x - editorWidth;
ImGui::HorizontalSplitter(ImVec2(editorWidth, 20), size.y - 20, splitterSize, editorWidth, editorResize, sceneWidth + 20, size.x - 20);
editorWidth = size.x - editorWidth;
ImGui::SetNextWindowPos(ImVec2(size.x - editorWidth, 20));
ImGui::SetNextWindowSize(ImVec2(editorWidth, size.y - 20));
}
if (sceneEditor.entityEditor.IsVisible())
sceneEditor.entityEditor.Show();
if (scriptEditor.IsVisible())
scriptEditor.Show();
if (textureEditor.IsVisible())
textureEditor.Show();
if (modelEditor.IsVisible())
modelEditor.Show();
if (soundEditor.IsVisible())
soundEditor.Show();
ImGui::End();
}
bool ResourceView::IsVisible() const {
return visible;
}
void ResourceView::SetVisible(bool visible) {
this->visible = visible;
}
void ResourceView::HideEditors() {
sceneEditor.SetVisible(false);
sceneEditor.entityEditor.SetVisible(false);
scriptEditor.SetVisible(false);
modelEditor.SetVisible(false);
textureEditor.SetVisible(false);
soundEditor.SetVisible(false);
}
void ResourceView::SaveScene() const {
sceneEditor.Save();
}
#undef max
void ResourceView::ResetScene() {
sceneEditor.SetScene("", nullptr);
sceneEditor.SetVisible(false);
}
SceneEditor& ResourceView::GetScene() {
return sceneEditor;
}
void ResourceView::ShowResourceFolder(ResourceList::ResourceFolder& folder, const std::string& path) {
bool opened = ImGui::TreeNode(folder.name.c_str());
if (ImGui::BeginPopupContextItem(folder.name.c_str())) {
// Add subfolder.
if (ImGui::Selectable("Add folder")) {
resourcePath = path;
parentFolder = &folder;
folderNameWindow.SetVisible(true);
return;
}
// Add scene.
if (ImGui::Selectable("Add scene")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::SCENE;
resource.scene = "Scene #" + std::to_string(Resources().sceneNumber++);
folder.resources.push_back(resource);
return;
}
// Add model.
if (ImGui::Selectable("Add model")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::MODEL;
resource.model = new Geometry::Model();
resource.model->path = path + "/";
resource.model->name = "Model #" + std::to_string(Resources().modelNumber++);
folder.resources.push_back(resource);
return;
}
// Add texture.
if (ImGui::Selectable("Add texture")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::TEXTURE;
string name = path + "/Texture #" + std::to_string(Resources().textureNumber++);
resource.texture = Managers().resourceManager->CreateTextureAsset(name, Managers().resourceManager->CreateTexture2D(DEFAULTALBEDO_PNG, DEFAULTALBEDO_PNG_LENGTH));
folder.resources.push_back(resource);
return;
}
// Add script.
if (ImGui::Selectable("Add script")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::SCRIPT;
resource.script = new ScriptFile();
resource.script->path = path + "/";
resource.script->name = "Script #" + std::to_string(Hymn().scriptNumber++);
Hymn().scripts.push_back(resource.script);
folder.resources.push_back(resource);
return;
}
// Add sound.
if (ImGui::Selectable("Add sound")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::SOUND;
resource.sound = new Audio::SoundBuffer();
resource.sound->path = path + "/";
resource.sound->name = "Sound #" + std::to_string(Resources().soundNumber++);
folder.resources.push_back(resource);
return;
}
/// @todo Remove folder.
ImGui::EndPopup();
}
if (opened) {
// Show subfolders.
for (ResourceList::ResourceFolder& subfolder : folder.subfolders) {
ShowResourceFolder(subfolder, path + "/" + subfolder.name);
}
// Show resources.
for (auto it = folder.resources.begin(); it != folder.resources.end(); ++it) {
if (ShowResource(*it, path)) {
folder.resources.erase(it);
return;
}
}
ImGui::TreePop();
}
}
bool ResourceView::ShowResource(ResourceList::Resource& resource, const std::string& path) {
// Scene.
if (resource.type == ResourceList::Resource::SCENE) {
if (ImGui::Selectable(resource.scene.c_str())) {
// Sets to don't save when opening first scene.
if (scene == nullptr) {
changeScene = true;
resourcePath = path;
scene = &resource.scene;
savePromptWindow.SetVisible(false);
savePromptWindow.SetDecision(1);
} else {
// Does so that the prompt window won't show if you select active scene.
if (resource.scene != Resources().activeScene) {
changeScene = true;
resourcePath = path;
scene = &resource.scene;
savePromptWindow.SetTitle("Save before you switch scene?");
}
}
}
// Delete scene.
if (ImGui::BeginPopupContextItem(resource.scene.c_str())) {
if (ImGui::Selectable("Delete")) {
if (Resources().activeScene == resource.scene) {
Resources().activeScene = "";
sceneEditor.SetScene("", nullptr);
}
ImGui::EndPopup();
return true;
}
ImGui::EndPopup();
}
}
/*
// Models.
bool modelPressed = false;
if (ImGui::TreeNode("Models")) {
for (auto it = Resources().models.begin(); it != Resources().models.end(); ++it) {
Geometry::Model* model = *it;
if (ImGui::Selectable(model->name.c_str())) {
modelPressed = true;
modelEditor.SetModel(model);
}
if (ImGui::BeginPopupContextItem(model->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (modelEditor.GetModel() == model)
modelEditor.SetVisible(false);
delete model;
Resources().models.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Textures.
bool texturePressed = false;
if (ImGui::TreeNode("Textures")) {
for (auto it = Resources().textures.begin(); it != Resources().textures.end(); ++it) {
TextureAsset* texture = *it;
if (ImGui::Selectable(texture->name.c_str())) {
texturePressed = true;
textureEditor.SetTexture(texture);
}
if (ImGui::BeginPopupContextItem(texture->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (Managers().resourceManager->GetTextureAssetInstanceCount(texture) > 1) {
Log() << "This texture is in use. Remove all references to the texture first.\n";
} else {
if (textureEditor.GetTexture() == texture)
textureEditor.SetVisible(false);
// Remove files.
remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".png").c_str());
remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".json").c_str());
Managers().resourceManager->FreeTextureAsset(texture);
Resources().textures.erase(it);
}
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Scripts.
bool scriptPressed = false;
if (ImGui::TreeNode("Scripts")) {
for (auto it = Hymn().scripts.begin(); it != Hymn().scripts.end(); ++it) {
ScriptFile* script = *it;
std::string name = script->name;
if (ImGui::Selectable(name.c_str())) {
scriptPressed = true;
scriptEditor.SetScript(script);
}
if (ImGui::BeginPopupContextItem(name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (scriptEditor.GetScript() == script)
scriptEditor.SetVisible(false);
delete script;
Hymn().scripts.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Sounds.
bool soundPressed = false;
if (ImGui::TreeNode("Sounds")) {
for (auto it = Resources().sounds.begin(); it != Resources().sounds.end(); ++it) {
Audio::SoundBuffer* sound = *it;
if (ImGui::Selectable(sound->name.c_str())) {
soundPressed = true;
soundEditor.SetSound(sound);
}
if (ImGui::BeginPopupContextItem(sound->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (soundEditor.GetSound() == sound)
soundEditor.SetVisible(false);
delete sound;
Resources().sounds.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}*/
return false;
}
void ResourceView::FileNameWindowClosed(const std::string& name) {
if (!name.empty()) {
ResourceList::ResourceFolder folder;
folder.name = name;
parentFolder->subfolders.push_back(folder);
FileSystem::CreateDirectory((Hymn().GetPath() + "/" + resourcePath + "/" + name).c_str());
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkColorPriv.h"
#include "SkShader.h"
/*
* Want to ensure that our bitmap sampler (in bitmap shader) keeps plenty of
* precision when scaling very large images (where the dx might get very small.
*/
#define W 256
#define H 160
class GiantBitmapGM : public skiagm::GM {
SkBitmap* fBM;
SkShader::TileMode fMode;
bool fDoFilter;
bool fDoRotate;
const SkBitmap& getBitmap() {
if (NULL == fBM) {
fBM = new SkBitmap;
fBM->setConfig(SkBitmap::kARGB_8888_Config, W, H);
fBM->allocPixels();
fBM->eraseColor(SK_ColorWHITE);
const SkColor colors[] = {
SK_ColorBLUE, SK_ColorRED, SK_ColorBLACK, SK_ColorGREEN
};
SkCanvas canvas(*fBM);
SkPaint paint;
paint.setAntiAlias(true);
paint.setStrokeWidth(SkIntToScalar(30));
for (int y = -H*2; y < H; y += 80) {
SkScalar yy = SkIntToScalar(y);
paint.setColor(colors[y/80 & 0x3]);
canvas.drawLine(0, yy, SkIntToScalar(W), yy + SkIntToScalar(W),
paint);
}
}
return *fBM;
}
public:
GiantBitmapGM(SkShader::TileMode mode, bool doFilter, bool doRotate) : fBM(NULL) {
fMode = mode;
fDoFilter = doFilter;
fDoRotate = doRotate;
}
virtual ~GiantBitmapGM() {
SkDELETE(fBM);
}
protected:
virtual SkString onShortName() {
SkString str("giantbitmap_");
switch (fMode) {
case SkShader::kClamp_TileMode:
str.append("clamp");
break;
case SkShader::kRepeat_TileMode:
str.append("repeat");
break;
case SkShader::kMirror_TileMode:
str.append("mirror");
break;
default:
break;
}
str.append(fDoFilter ? "_bilerp" : "_point");
str.append(fDoRotate ? "_rotate" : "_scale");
return str;
}
virtual SkISize onISize() { return SkISize::Make(640, 480); }
virtual void onDraw(SkCanvas* canvas) {
SkPaint paint;
SkShader* s = SkShader::CreateBitmapShader(getBitmap(), fMode, fMode);
SkMatrix m;
if (fDoRotate) {
// m.setRotate(SkIntToScalar(30), 0, 0);
m.setSkew(SK_Scalar1, 0, 0, 0);
m.postScale(2*SK_Scalar1/3, 2*SK_Scalar1/3);
} else {
m.setScale(2*SK_Scalar1/3, 2*SK_Scalar1/3);
}
s->setLocalMatrix(m);
paint.setShader(s)->unref();
paint.setFilterBitmap(fDoFilter);
canvas->translate(SkIntToScalar(50), SkIntToScalar(50));
canvas->drawPaint(paint);
}
private:
typedef GM INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
static skiagm::GM* G000(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, false, false); }
static skiagm::GM* G100(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, false, false); }
static skiagm::GM* G200(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, false, false); }
static skiagm::GM* G010(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, true, false); }
static skiagm::GM* G110(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, true, false); }
static skiagm::GM* G210(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, true, false); }
static skiagm::GM* G001(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, false, true); }
static skiagm::GM* G101(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, false, true); }
static skiagm::GM* G201(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, false, true); }
static skiagm::GM* G011(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, true, true); }
static skiagm::GM* G111(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, true, true); }
static skiagm::GM* G211(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, true, true); }
static skiagm::GMRegistry reg000(G000);
static skiagm::GMRegistry reg100(G100);
static skiagm::GMRegistry reg200(G200);
static skiagm::GMRegistry reg010(G010);
static skiagm::GMRegistry reg110(G110);
static skiagm::GMRegistry reg210(G210);
static skiagm::GMRegistry reg001(G001);
static skiagm::GMRegistry reg101(G101);
static skiagm::GMRegistry reg201(G201);
static skiagm::GMRegistry reg011(G011);
static skiagm::GMRegistry reg111(G111);
static skiagm::GMRegistry reg211(G211);
<commit_msg>update test<commit_after>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkColorPriv.h"
#include "SkShader.h"
/*
* Want to ensure that our bitmap sampler (in bitmap shader) keeps plenty of
* precision when scaling very large images (where the dx might get very small.
*/
#define W 257
#define H 161
class GiantBitmapGM : public skiagm::GM {
SkBitmap* fBM;
SkShader::TileMode fMode;
bool fDoFilter;
bool fDoRotate;
const SkBitmap& getBitmap() {
if (NULL == fBM) {
fBM = new SkBitmap;
fBM->setConfig(SkBitmap::kARGB_8888_Config, W, H);
fBM->allocPixels();
fBM->eraseColor(SK_ColorWHITE);
const SkColor colors[] = {
SK_ColorBLUE, SK_ColorRED, SK_ColorBLACK, SK_ColorGREEN
};
SkCanvas canvas(*fBM);
SkPaint paint;
paint.setAntiAlias(true);
paint.setStrokeWidth(SkIntToScalar(20));
#if 0
for (int y = -H*2; y < H; y += 50) {
SkScalar yy = SkIntToScalar(y);
paint.setColor(colors[y/50 & 0x3]);
canvas.drawLine(0, yy, SkIntToScalar(W), yy + SkIntToScalar(W),
paint);
}
#else
for (int x = -W; x < W; x += 60) {
paint.setColor(colors[x/60 & 0x3]);
SkScalar xx = SkIntToScalar(x);
canvas.drawLine(xx, 0, xx, SkIntToScalar(H),
paint);
}
#endif
}
return *fBM;
}
public:
GiantBitmapGM(SkShader::TileMode mode, bool doFilter, bool doRotate) : fBM(NULL) {
fMode = mode;
fDoFilter = doFilter;
fDoRotate = doRotate;
}
virtual ~GiantBitmapGM() {
SkDELETE(fBM);
}
protected:
virtual SkString onShortName() {
SkString str("giantbitmap_");
switch (fMode) {
case SkShader::kClamp_TileMode:
str.append("clamp");
break;
case SkShader::kRepeat_TileMode:
str.append("repeat");
break;
case SkShader::kMirror_TileMode:
str.append("mirror");
break;
default:
break;
}
str.append(fDoFilter ? "_bilerp" : "_point");
str.append(fDoRotate ? "_rotate" : "_scale");
return str;
}
virtual SkISize onISize() { return SkISize::Make(640, 480); }
virtual void onDraw(SkCanvas* canvas) {
SkPaint paint;
SkShader* s = SkShader::CreateBitmapShader(getBitmap(), fMode, fMode);
SkMatrix m;
if (fDoRotate) {
// m.setRotate(SkIntToScalar(30), 0, 0);
m.setSkew(SK_Scalar1, 0, 0, 0);
// m.postScale(2*SK_Scalar1/3, 2*SK_Scalar1/3);
} else {
SkScalar scale = 11*SK_Scalar1/12;
m.setScale(scale, scale);
}
s->setLocalMatrix(m);
paint.setShader(s)->unref();
paint.setFilterBitmap(fDoFilter);
canvas->translate(SkIntToScalar(50), SkIntToScalar(50));
SkRect r = SkRect::MakeXYWH(-50, -50, 32, 16);
// canvas->drawRect(r, paint); return;
canvas->drawPaint(paint);
}
private:
typedef GM INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
static skiagm::GM* G000(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, false, false); }
static skiagm::GM* G100(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, false, false); }
static skiagm::GM* G200(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, false, false); }
static skiagm::GM* G010(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, true, false); }
static skiagm::GM* G110(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, true, false); }
static skiagm::GM* G210(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, true, false); }
static skiagm::GM* G001(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, false, true); }
static skiagm::GM* G101(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, false, true); }
static skiagm::GM* G201(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, false, true); }
static skiagm::GM* G011(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, true, true); }
static skiagm::GM* G111(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, true, true); }
static skiagm::GM* G211(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, true, true); }
static skiagm::GMRegistry reg000(G000);
static skiagm::GMRegistry reg100(G100);
static skiagm::GMRegistry reg200(G200);
static skiagm::GMRegistry reg010(G010);
static skiagm::GMRegistry reg110(G110);
static skiagm::GMRegistry reg210(G210);
static skiagm::GMRegistry reg001(G001);
static skiagm::GMRegistry reg101(G101);
static skiagm::GMRegistry reg201(G201);
static skiagm::GMRegistry reg011(G011);
static skiagm::GMRegistry reg111(G111);
static skiagm::GMRegistry reg211(G211);
<|endoftext|> |
<commit_before>//
// File: PBody.cpp
// Class: PBody
// Author: Jesper Persson
// All code is my own except where credited to others.
//
// Copyright (c) 2012 by Catch22. All Rights Reserved.
// Date: 29/09-2012
//
#include "PBody.hpp"
#include "../../Helper/Logger.hpp"
#include "../../Math/Math.hpp"
PBody::PBody(Vector2dArray* vectorArray, Vector2d* centerOfMassOffset, bool affectedByGravity, bool stationaryObject, bool rotatableObject, PBodyType tag)
{
m_vectorArray = vectorArray;
m_centerOfMassOffset = centerOfMassOffset;
m_affectedByGravity = affectedByGravity;
m_stationaryObject = stationaryObject;
m_rotatableObject = rotatableObject;
m_movementVector = new Vector2d(0,0);
m_tag = tag;
}
PBody::PBody(Vector2dArray* vectorArray, bool affectedByGravity, bool stationaryObject, bool rotatableObject, PBodyType tag)
{
m_vectorArray = vectorArray;
m_centerOfMassOffset = new Vector2d(0,0);
m_affectedByGravity = affectedByGravity;
m_stationaryObject = stationaryObject;
m_rotatableObject = rotatableObject;
m_movementVector = new Vector2d(0,0);
m_tag = tag;
}
PBody::PBody(Vector2dArray* vectorArray, bool stationaryObject, PBodyType tag)
{
m_vectorArray = vectorArray;
m_centerOfMassOffset = new Vector2d(0,0);
m_affectedByGravity = !stationaryObject;
m_stationaryObject = stationaryObject;
m_rotatableObject = !stationaryObject;
m_movementVector = new Vector2d(0,0);
m_tag = tag;
}
PBody::PBody(Vector2d* position, Vector2d* size, bool affectedByGravity, bool stationaryObject, bool rotatableObject, PBodyType tag)
{
Vector2d** vArr = new Vector2d*[4];
vArr[0] = new Vector2d(position->m_x, position->m_y);
vArr[1] = new Vector2d(position->m_x, position->m_y + size->m_y);
vArr[2] = new Vector2d(position->m_x + size->m_x, position->m_y + size->m_y);
vArr[3] = new Vector2d(position->m_x + size->m_x, position->m_y);
m_vectorArray = new Vector2dArray(vArr, 4);
m_centerOfMassOffset = new Vector2d(0,0);
m_affectedByGravity = affectedByGravity;
m_stationaryObject = stationaryObject;
m_rotatableObject = rotatableObject;
m_movementVector = new Vector2d(0,0);
m_tag = tag;
}
PBody::~PBody()
{
delete m_centerOfMassOffset;
delete m_movementVector;
delete m_vectorArray;
}
void PBody::applyForce(float dt)
{
for (int i = 0; i < m_vectorArray->m_size; i++) {
m_vectorArray->m_vectors[i]->m_x += (m_movementVector->m_x * dt);
m_vectorArray->m_vectors[i]->m_y += (m_movementVector->m_y * dt);
}
}
void PBody::revertForce(float dt)
{
for (int i = 0; i < m_vectorArray->m_size; i++) {
m_vectorArray->m_vectors[i]->m_x -= (m_movementVector->m_x * dt);
m_vectorArray->m_vectors[i]->m_y -= (m_movementVector->m_y * dt);
}
}
void PBody::applyForceWithMask(Vector2d* mask, float dt)
{
for (int i = 0; i < m_vectorArray->m_size; i++) {
m_vectorArray->m_vectors[i]->m_x += ((m_movementVector->m_x * mask->m_x) * dt);
m_vectorArray->m_vectors[i]->m_y += ((m_movementVector->m_y * mask->m_y) * dt);
}
}
void PBody::revertForceWithMask(Vector2d* mask, float dt)
{
for (int i = 0; i < m_vectorArray->m_size; i++) {
m_vectorArray->m_vectors[i]->m_x -= ((m_movementVector->m_x * mask->m_x) * dt);
m_vectorArray->m_vectors[i]->m_y -= ((m_movementVector->m_y * mask->m_y) * dt);
}
}
void PBody::addVector(Vector2d* vector)
{
*m_movementVector += *vector;
}
void PBody::removeVector(Vector2d* vector)
{
*m_movementVector -= vector;
}
void PBody::resetMovementVector()
{
m_movementVector = new Vector2d(0,0);
}
void PBody::maskMovementVector(float x, float y)
{
this->m_movementVector->m_x *= x;
this->m_movementVector->m_y *= y;
}
void PBody::rotateAround(Vector2d* pivotPoint, float degrees)
{
// Implement me plxzz
}
void PBody::translateBy(Vector2d* vector)
{
// Implement me plxzz
}
Vector2dArray* PBody::getVectorArray()
{
return m_vectorArray;
}
bool PBody::isAffectedByGravity()
{
return m_affectedByGravity;
}
bool PBody::isStationary()
{
return m_stationaryObject;
}
bool PBody::isCollidingWithBody(PBody* otherBody)
{
Vector2d** axes1 = this->getAxes();
Vector2d** axes2 = otherBody->getAxes();
for (int a = 0; a < this->m_vectorArray->m_size; a++) {
Vector2d* axis = axes1[a];
Vector2d* proj1 = this->projectionOnVector(axis);
Vector2d* proj2 = otherBody->projectionOnVector(axis);
if (proj1->m_x < proj2->m_x && proj1->m_y < proj2->m_x)
return false;
if (proj2->m_x < proj1->m_x && proj2->m_y < proj1->m_x)
return false;
}
for (int a = 0; a < otherBody->m_vectorArray->m_size; a++) {
Vector2d* axis = axes2[a];
Vector2d* proj1 = this->projectionOnVector(axis);
Vector2d* proj2 = otherBody->projectionOnVector(axis);
if (proj1->m_x < proj2->m_x && proj1->m_y < proj2->m_x)
return false;
if (proj2->m_x < proj1->m_x && proj2->m_y < proj1->m_x)
return false;
}
return true;
}
PBodyType PBody::getTag()
{
return m_tag;
}
Vector2d* PBody::getSize()
{
double xmin = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_x : 0;
double xmax = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_x : 0;
double ymin = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_y : 0;
double ymax = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_y : 0;
for (int i = 0; i < this->m_vectorArray->m_size; i++) {
xmin = this->m_vectorArray->m_vectors[i]->m_x < xmin ? this->m_vectorArray->m_vectors[i]->m_x : xmin;
ymin = this->m_vectorArray->m_vectors[i]->m_y < ymin ? this->m_vectorArray->m_vectors[i]->m_y : ymin;
xmax = this->m_vectorArray->m_vectors[i]->m_x > xmax ? this->m_vectorArray->m_vectors[i]->m_x : xmax;
ymax = this->m_vectorArray->m_vectors[i]->m_y > ymax ? this->m_vectorArray->m_vectors[i]->m_y : ymax;
}
return new Vector2d(xmax - xmin, ymax - ymin);
}
Vector2d* PBody::getPosition()
{
double x = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_x : 0;
double y = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_y : 0;
for (int i = 0; i < this->m_vectorArray->m_size; i++) {
x = this->m_vectorArray->m_vectors[i]->m_x < x ? this->m_vectorArray->m_vectors[i]->m_x : x;
y = this->m_vectorArray->m_vectors[i]->m_y < y ? this->m_vectorArray->m_vectors[i]->m_y : y;
}
return new Vector2d(x, y);
}
Vector2d** PBody::getAxes()
{
Vector2d** edges = this->getEdges();
Vector2d** axes = new Vector2d*[this->m_vectorArray->m_size];
for (int i = 0; i < this->m_vectorArray->m_size; i++) {
axes[i] = new Vector2d(edges[i]->m_y, -edges[i]->m_x);
}
delete [] edges;
return axes;
}
Vector2d** PBody::getEdges()
{
Vector2d** edges = new Vector2d*[this->m_vectorArray->m_size];
for (int a = 0; a < this->m_vectorArray->m_size; a++) {
Vector2d* p1 = this->m_vectorArray->m_vectors[a];
Vector2d* p2 = this->m_vectorArray->m_vectors[a + 1 == this->m_vectorArray->m_size ? 0 : a + 1];
edges[a] = new Vector2d(p1->m_x - p2->m_x, p1->m_y - p2->m_y);
}
return edges;
}
Vector2d* PBody::projectionOnVector(Vector2d* axis)
{
double min = this->m_vectorArray->m_vectors[0]->m_x*axis->m_x + this->m_vectorArray->m_vectors[0]->m_y*axis->m_y;
double max = min;
for (int i = 0; i < this->m_vectorArray->m_size; i++) {
double dot = this->m_vectorArray->m_vectors[i]->m_x*axis->m_x + this->m_vectorArray->m_vectors[i]->m_y*axis->m_y;
min = min < dot ? min : dot;
max = max < dot ? dot : max;
}
return new Vector2d(min, max);
}
<commit_msg>Expanded how the collision detection works.<commit_after>//
// File: PBody.cpp
// Class: PBody
// Author: Jesper Persson
// All code is my own except where credited to others.
//
// Copyright (c) 2012 by Catch22. All Rights Reserved.
// Date: 29/09-2012
//
#include "PBody.hpp"
#include "../../Helper/Logger.hpp"
#include "../../Math/Math.hpp"
PBody::PBody(Vector2dArray* vectorArray, Vector2d* centerOfMassOffset, bool affectedByGravity, bool stationaryObject, bool rotatableObject, PBodyType tag)
{
m_vectorArray = vectorArray;
m_centerOfMassOffset = centerOfMassOffset;
m_affectedByGravity = affectedByGravity;
m_stationaryObject = stationaryObject;
m_rotatableObject = rotatableObject;
m_movementVector = new Vector2d(0.0,0.0);
m_tag = tag;
}
PBody::PBody(Vector2dArray* vectorArray, bool affectedByGravity, bool stationaryObject, bool rotatableObject, PBodyType tag)
{
m_vectorArray = vectorArray;
m_centerOfMassOffset = new Vector2d(0.0,0.0);
m_affectedByGravity = affectedByGravity;
m_stationaryObject = stationaryObject;
m_rotatableObject = rotatableObject;
m_movementVector = new Vector2d(0.0,0.0);
m_tag = tag;
}
PBody::PBody(Vector2dArray* vectorArray, bool stationaryObject, PBodyType tag)
{
m_vectorArray = vectorArray;
m_centerOfMassOffset = new Vector2d(0.0,0.0);
m_affectedByGravity = !stationaryObject;
m_stationaryObject = stationaryObject;
m_rotatableObject = !stationaryObject;
m_movementVector = new Vector2d(0.0,0.0);
m_tag = tag;
}
PBody::PBody(Vector2d* position, Vector2d* size, bool affectedByGravity, bool stationaryObject, bool rotatableObject, PBodyType tag)
{
Vector2d** vArr = new Vector2d*[4];
vArr[0] = new Vector2d(position->m_x, position->m_y);
vArr[1] = new Vector2d(position->m_x, position->m_y + size->m_y);
vArr[2] = new Vector2d(position->m_x + size->m_x, position->m_y + size->m_y);
vArr[3] = new Vector2d(position->m_x + size->m_x, position->m_y);
m_vectorArray = new Vector2dArray(vArr, 4);
m_centerOfMassOffset = new Vector2d(0.0,0.0);
m_affectedByGravity = affectedByGravity;
m_stationaryObject = stationaryObject;
m_rotatableObject = rotatableObject;
m_movementVector = new Vector2d(0.0,0.0);
m_tag = tag;
}
PBody::~PBody()
{
delete m_centerOfMassOffset;
delete m_movementVector;
delete m_vectorArray;
}
void PBody::applyForce(float dt)
{
for (int i = 0; i < m_vectorArray->m_size; i++) {
m_vectorArray->m_vectors[i]->m_x += (m_movementVector->m_x * dt);
m_vectorArray->m_vectors[i]->m_y += (m_movementVector->m_y * dt);
}
Log(LOG_INFO, "PBody", generateCString("Applying force: %d,%d", this->m_movementVector->m_x, this->m_movementVector->m_y));
}
void PBody::revertForce(float dt)
{
for (int i = 0; i < m_vectorArray->m_size; i++) {
m_vectorArray->m_vectors[i]->m_x -= (m_movementVector->m_x * dt);
m_vectorArray->m_vectors[i]->m_y -= (m_movementVector->m_y * dt);
}
}
void PBody::applyForceWithMask(Vector2d* mask, float dt)
{
for (int i = 0; i < m_vectorArray->m_size; i++) {
m_vectorArray->m_vectors[i]->m_x += ((m_movementVector->m_x * mask->m_x) * dt);
m_vectorArray->m_vectors[i]->m_y += ((m_movementVector->m_y * mask->m_y) * dt);
}
}
void PBody::revertForceWithMask(Vector2d* mask, float dt)
{
for (int i = 0; i < m_vectorArray->m_size; i++) {
m_vectorArray->m_vectors[i]->m_x -= ((m_movementVector->m_x * mask->m_x) * dt);
m_vectorArray->m_vectors[i]->m_y -= ((m_movementVector->m_y * mask->m_y) * dt);
}
}
void PBody::addVector(Vector2d* vector)
{
*m_movementVector += *vector;
}
void PBody::removeVector(Vector2d* vector)
{
*m_movementVector -= vector;
}
void PBody::resetMovementVector()
{
m_movementVector = new Vector2d(0.0,0.0);
}
void PBody::maskMovementVector(float x, float y)
{
this->m_movementVector->m_x *= x;
this->m_movementVector->m_y *= y;
}
void PBody::rotateAround(Vector2d* pivotPoint, float degrees)
{
// Implement me plxzz
}
void PBody::translateBy(Vector2d* vector)
{
for (int i = 0; i < this->m_vectorArray->m_size; i++) {
*this->m_vectorArray->m_vectors[i] += *vector;
}
}
Vector2dArray* PBody::getVectorArray()
{
return m_vectorArray;
}
bool PBody::isAffectedByGravity()
{
return m_affectedByGravity;
}
bool PBody::isStationary()
{
return m_stationaryObject;
}
Vector2d* PBody::isCollidingWithBody(PBody* otherBody)
{
Vector2d** axes1 = this->getAxes();
Vector2d** axes2 = otherBody->getAxes();
double overlap = -1;
Vector2d* smallestAxis = 0;
Vector2d* axis;
Vector2d* proj1;
Vector2d* proj2;
double tmpOver;
for (int a = 0; a < this->m_vectorArray->m_size; a++) {
axis = axes1[a];
proj1 = this->projectionOnVector(axis);
proj2 = otherBody->projectionOnVector(axis);
if ((proj1->m_x < proj2->m_x && proj1->m_y < proj2->m_x) || (
proj2->m_x < proj1->m_x && proj2->m_y < proj1->m_x)) {
delete proj1;
delete proj2;
for (int i = 0; i < this->m_vectorArray->m_size; i++)
delete [] axes1[i];
delete [] axes1;
for (int i = 0; i < otherBody->m_vectorArray->m_size; i++)
delete [] axes2[i];
delete [] axes2;
return 0;
} else {
if (proj1->m_y > proj2->m_x && proj2->m_y > proj1->m_y) {
tmpOver = proj1->m_y - proj2->m_x;
}
else if (proj2->m_y > proj1->m_x && proj1->m_y > proj2->m_y) {
tmpOver = proj2->m_y - proj1->m_x;
}
else if (proj1->m_x > proj2->m_x && proj1->m_y < proj2->m_y) {
tmpOver = proj1->m_y-proj1->m_x;
}
else if (proj2->m_x > proj1->m_x && proj2->m_y < proj1->m_y) {
tmpOver = proj2->m_y-proj2->m_x;
}
if (overlap == -1 || tmpOver < overlap) {
overlap = tmpOver;
smallestAxis = axis;
}
}
delete proj1;
delete proj2;
}
for (int a = 0; a < otherBody->m_vectorArray->m_size; a++) {
axis = axes2[a];
proj1 = this->projectionOnVector(axis);
proj2 = otherBody->projectionOnVector(axis);
if ((proj1->m_x < proj2->m_x && proj1->m_y < proj2->m_x) ||
(proj2->m_x < proj1->m_x && proj2->m_y < proj1->m_x)) {
delete proj1;
delete proj2;
for (int i = 0; i < this->m_vectorArray->m_size; i++)
delete [] axes1[i];
delete [] axes1;
for (int i = 0; i < otherBody->m_vectorArray->m_size; i++)
delete [] axes2[i];
delete [] axes2;
return 0;
} else {
if (proj1->m_y > proj2->m_x && proj2->m_y > proj1->m_y) {
tmpOver = proj1->m_y - proj2->m_x;
}
else if (proj2->m_y > proj1->m_x && proj1->m_y > proj2->m_y) {
tmpOver = proj2->m_y - proj1->m_x;
}
else if (proj1->m_x > proj2->m_x && proj1->m_y < proj2->m_y) {
tmpOver = proj1->m_y-proj1->m_x;
}
else if (proj2->m_x > proj1->m_x && proj2->m_y < proj1->m_y) {
tmpOver = proj2->m_y-proj2->m_x;
}
if (overlap == -1 || tmpOver < overlap) {
overlap = tmpOver;
smallestAxis = axis;
}
}
delete proj1;
delete proj2;
}
Vector2d* returnVector = new Vector2d(smallestAxis, overlap);
for (int i = 0; i < this->m_vectorArray->m_size; i++)
delete [] axes1[i];
delete [] axes1;
for (int i = 0; i < otherBody->m_vectorArray->m_size; i++)
delete [] axes2[i];
delete [] axes2;
return returnVector;
}
PBodyType PBody::getTag()
{
return m_tag;
}
Vector2d* PBody::getSize()
{
double xmin = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_x : 0;
double xmax = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_x : 0;
double ymin = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_y : 0;
double ymax = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_y : 0;
for (int i = 0; i < this->m_vectorArray->m_size; i++) {
xmin = this->m_vectorArray->m_vectors[i]->m_x < xmin ? this->m_vectorArray->m_vectors[i]->m_x : xmin;
ymin = this->m_vectorArray->m_vectors[i]->m_y < ymin ? this->m_vectorArray->m_vectors[i]->m_y : ymin;
xmax = this->m_vectorArray->m_vectors[i]->m_x > xmax ? this->m_vectorArray->m_vectors[i]->m_x : xmax;
ymax = this->m_vectorArray->m_vectors[i]->m_y > ymax ? this->m_vectorArray->m_vectors[i]->m_y : ymax;
}
return new Vector2d(xmax - xmin, ymax - ymin);
}
Vector2d* PBody::getPosition()
{
double x = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_x : 0;
double y = this->m_vectorArray->m_size > 0 ? this->m_vectorArray->m_vectors[0]->m_y : 0;
for (int i = 0; i < this->m_vectorArray->m_size; i++) {
x = this->m_vectorArray->m_vectors[i]->m_x < x ? this->m_vectorArray->m_vectors[i]->m_x : x;
y = this->m_vectorArray->m_vectors[i]->m_y < y ? this->m_vectorArray->m_vectors[i]->m_y : y;
}
return new Vector2d(x, y);
}
Vector2d** PBody::getAxes()
{
Vector2d** edges = this->getEdges();
Vector2d** axes = new Vector2d*[this->m_vectorArray->m_size];
for (int i = 0; i < this->m_vectorArray->m_size; i++) {
Vector2d* v = new Vector2d(edges[i]->m_y, -edges[i]->m_x);
axes[i] = Math::generateUnitVectorOf(v);
delete v;
delete [] edges[i];
}
delete [] edges;
return axes;
}
Vector2d** PBody::getEdges()
{
Vector2d** edges = new Vector2d*[this->m_vectorArray->m_size];
for (int a = 0; a < this->m_vectorArray->m_size; a++) {
Vector2d* p1 = this->m_vectorArray->m_vectors[a];
Vector2d* p2 = this->m_vectorArray->m_vectors[a + 1 == this->m_vectorArray->m_size ? 0 : a + 1];
edges[a] = new Vector2d(p1->m_x - p2->m_x, p1->m_y - p2->m_y);
}
return edges;
}
Vector2d* PBody::projectionOnVector(Vector2d* axis)
{
double min = this->m_vectorArray->m_vectors[0]->m_x*axis->m_x + this->m_vectorArray->m_vectors[0]->m_y*axis->m_y;
double max = min;
for (int i = 0; i < this->m_vectorArray->m_size; i++) {
double dot = this->m_vectorArray->m_vectors[i]->m_x*axis->m_x + this->m_vectorArray->m_vectors[i]->m_y*axis->m_y;
min = min < dot ? min : dot;
max = max < dot ? dot : max;
}
return new Vector2d(min, max);
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "WiimoteFactory.h"
WiimoteFactory::WiimoteFactory()
:DeviceIndex(0), DeviceInfoSet(NULL), OpenDevice(INVALID_HANDLE_VALUE)
{
HidD_GetHidGuid(&HidGuid);
ZeroMemory(&DeviceInfoData, sizeof(SP_DEVINFO_DATA));
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
DeviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
}
WiimoteFactory::~WiimoteFactory()
{
if (DeviceInfoSet)
{
SetupDiDestroyDeviceInfoList(DeviceInfoSet);
DeviceInfoSet = NULL;
}
}
WiimoteDeviceVector WiimoteFactory::GetWiimoteDevices()
{
DeviceInfoSet = SetupDiGetClassDevs(&HidGuid, NULL, NULL, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
if (!DeviceInfoSet)
{
std::cout << "No HID Devices Found!" << std::endl;
return WiimoteDevices;
}
while (SetupDiEnumDeviceInterfaces(DeviceInfoSet, NULL, &HidGuid, DeviceIndex, &DeviceInterfaceData))
{
std::cout << "New Device" << std::endl;
CheckEnumeratedDeviceInterface();
DeviceIndex++;
}
if (DeviceIndex == 0)
{
std::cout << "No Device Enumerated!" << std::endl;
}
return WiimoteDevices;
}
void WiimoteFactory::CheckEnumeratedDeviceInterface()
{
BOOL Result;
DWORD RequiredSize;
Result = SetupDiGetDeviceInterfaceDetail(DeviceInfoSet, &DeviceInterfaceData, NULL, 0, &RequiredSize, NULL);
PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(RequiredSize);
DeviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
Result = SetupDiGetDeviceInterfaceDetail(DeviceInfoSet, &DeviceInterfaceData, DeviceInterfaceDetailData, RequiredSize, NULL, NULL);
BOOL IsWiimote = CheckDevice(DeviceInterfaceDetailData->DevicePath);
if (IsWiimote)
{
WiimoteDevices.push_back(WiimoteDevice(OpenDevice));
}
else
{
CloseHandle(OpenDevice);
}
OpenDevice = INVALID_HANDLE_VALUE;
free(DeviceInterfaceDetailData);
}
BOOL WiimoteFactory::CheckDevice(LPCTSTR DevicePath)
{
OpenDevice = CreateFile(DevicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
if (OpenDevice == INVALID_HANDLE_VALUE)
{
std::cout << "Failed to open Device." << std::endl;
return FALSE;
}
std::cout << "0x" << std::hex << OpenDevice << std::endl;
HIDD_ATTRIBUTES HidAttributes;
HidAttributes.Size = sizeof(HidAttributes);
BOOL Result = HidD_GetAttributes(OpenDevice, &HidAttributes);
if (!Result)
{
std::cout << "Failed to get hid attributes" << std::endl;
return FALSE;
}
std::cout << HidAttributes.VendorID << " - " << HidAttributes.ProductID << std::endl;
TCHAR ProductName[255];
if (HidD_GetProductString(OpenDevice, ProductName, 255))
{
std::wcout << ProductName << std::endl;
}
return (HidAttributes.VendorID == 0x057e) && ((HidAttributes.ProductID == 0x0306) || (HidAttributes.ProductID == 0x0330));
}<commit_msg>Adjust print outs<commit_after>#include "stdafx.h"
#include "WiimoteFactory.h"
WiimoteFactory::WiimoteFactory()
:DeviceIndex(0), DeviceInfoSet(NULL), OpenDevice(INVALID_HANDLE_VALUE)
{
HidD_GetHidGuid(&HidGuid);
ZeroMemory(&DeviceInfoData, sizeof(SP_DEVINFO_DATA));
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
DeviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
}
WiimoteFactory::~WiimoteFactory()
{
if (DeviceInfoSet)
{
SetupDiDestroyDeviceInfoList(DeviceInfoSet);
DeviceInfoSet = NULL;
}
}
WiimoteDeviceVector WiimoteFactory::GetWiimoteDevices()
{
DeviceInfoSet = SetupDiGetClassDevs(&HidGuid, NULL, NULL, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
if (!DeviceInfoSet)
{
std::cout << "No HID Devices Found!" << std::endl;
return WiimoteDevices;
}
while (SetupDiEnumDeviceInterfaces(DeviceInfoSet, NULL, &HidGuid, DeviceIndex, &DeviceInterfaceData))
{
std::cout << "--- New Device ---" << std::endl;
CheckEnumeratedDeviceInterface();
DeviceIndex++;
std::cout << "------------------" << std::endl;
}
if (DeviceIndex == 0)
{
std::cout << "No Device Enumerated!" << std::endl;
}
return WiimoteDevices;
}
void WiimoteFactory::CheckEnumeratedDeviceInterface()
{
BOOL Result;
DWORD RequiredSize;
Result = SetupDiGetDeviceInterfaceDetail(DeviceInfoSet, &DeviceInterfaceData, NULL, 0, &RequiredSize, NULL);
PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(RequiredSize);
DeviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
Result = SetupDiGetDeviceInterfaceDetail(DeviceInfoSet, &DeviceInterfaceData, DeviceInterfaceDetailData, RequiredSize, NULL, NULL);
BOOL IsWiimote = CheckDevice(DeviceInterfaceDetailData->DevicePath);
if (IsWiimote)
{
WiimoteDevices.push_back(WiimoteDevice(OpenDevice));
}
else
{
CloseHandle(OpenDevice);
}
OpenDevice = INVALID_HANDLE_VALUE;
free(DeviceInterfaceDetailData);
}
BOOL WiimoteFactory::CheckDevice(LPCTSTR DevicePath)
{
OpenDevice = CreateFile(DevicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
if (OpenDevice == INVALID_HANDLE_VALUE)
{
std::cout << "Failed to open Device." << std::endl;
return FALSE;
}
std::cout << "DevicePath: \t0x" << std::hex << OpenDevice << std::endl;
HIDD_ATTRIBUTES HidAttributes;
HidAttributes.Size = sizeof(HidAttributes);
BOOL Result = HidD_GetAttributes(OpenDevice, &HidAttributes);
if (!Result)
{
std::cout << "Failed to get hid attributes" << std::endl;
return FALSE;
}
std::cout << "VID&PID: \t" << HidAttributes.VendorID << " - " << HidAttributes.ProductID << std::endl;
TCHAR ProductName[255];
if (HidD_GetProductString(OpenDevice, ProductName, 255))
{
std::wcout << "HID Name: \t" << ProductName << std::endl;
}
return (HidAttributes.VendorID == 0x057e) && ((HidAttributes.ProductID == 0x0306) || (HidAttributes.ProductID == 0x0330));
}<|endoftext|> |
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkColorPriv.h"
#include "SkShader.h"
/*
* Want to ensure that our bitmap sampler (in bitmap shader) keeps plenty of
* precision when scaling very large images (where the dx might get very small.
*/
#define W 256
#define H 160
class GiantBitmapGM : public skiagm::GM {
SkBitmap* fBM;
SkShader::TileMode fMode;
bool fDoFilter;
bool fDoRotate;
const SkBitmap& getBitmap() {
if (NULL == fBM) {
fBM = new SkBitmap;
fBM->setConfig(SkBitmap::kARGB_8888_Config, W, H);
fBM->allocPixels();
fBM->eraseColor(SK_ColorWHITE);
const SkColor colors[] = {
SK_ColorBLUE, SK_ColorRED, SK_ColorBLACK, SK_ColorGREEN
};
SkCanvas canvas(*fBM);
SkPaint paint;
paint.setAntiAlias(true);
paint.setStrokeWidth(SkIntToScalar(30));
for (int y = -H*2; y < H; y += 80) {
SkScalar yy = SkIntToScalar(y);
paint.setColor(colors[y/80 & 0x3]);
canvas.drawLine(0, yy, SkIntToScalar(W), yy + SkIntToScalar(W),
paint);
}
}
return *fBM;
}
public:
GiantBitmapGM(SkShader::TileMode mode, bool doFilter, bool doRotate) : fBM(NULL) {
fMode = mode;
fDoFilter = doFilter;
fDoRotate = doRotate;
}
virtual ~GiantBitmapGM() {
SkDELETE(fBM);
}
protected:
virtual SkString onShortName() {
SkString str("giantbitmap_");
switch (fMode) {
case SkShader::kClamp_TileMode:
str.append("clamp");
break;
case SkShader::kRepeat_TileMode:
str.append("repeat");
break;
case SkShader::kMirror_TileMode:
str.append("mirror");
break;
default:
break;
}
str.append(fDoFilter ? "_bilerp" : "_point");
str.append(fDoRotate ? "_rotate" : "_scale");
return str;
}
virtual SkISize onISize() { return SkISize::Make(640, 480); }
virtual void onDraw(SkCanvas* canvas) {
SkPaint paint;
SkShader* s = SkShader::CreateBitmapShader(getBitmap(), fMode, fMode);
SkMatrix m;
if (fDoRotate) {
// m.setRotate(SkIntToScalar(30), 0, 0);
m.setSkew(SK_Scalar1, 0, 0, 0);
m.postScale(2*SK_Scalar1/3, 2*SK_Scalar1/3);
} else {
m.setScale(2*SK_Scalar1/3, 2*SK_Scalar1/3);
}
s->setLocalMatrix(m);
paint.setShader(s)->unref();
paint.setFilterBitmap(fDoFilter);
canvas->translate(SkIntToScalar(50), SkIntToScalar(50));
canvas->drawPaint(paint);
}
private:
typedef GM INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
static skiagm::GM* G000(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, false, false); }
static skiagm::GM* G100(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, false, false); }
static skiagm::GM* G200(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, false, false); }
static skiagm::GM* G010(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, true, false); }
static skiagm::GM* G110(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, true, false); }
static skiagm::GM* G210(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, true, false); }
static skiagm::GM* G001(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, false, true); }
static skiagm::GM* G101(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, false, true); }
static skiagm::GM* G201(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, false, true); }
static skiagm::GM* G011(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, true, true); }
static skiagm::GM* G111(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, true, true); }
static skiagm::GM* G211(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, true, true); }
static skiagm::GMRegistry reg000(G000);
static skiagm::GMRegistry reg100(G100);
static skiagm::GMRegistry reg200(G200);
static skiagm::GMRegistry reg010(G010);
static skiagm::GMRegistry reg110(G110);
static skiagm::GMRegistry reg210(G210);
static skiagm::GMRegistry reg001(G001);
static skiagm::GMRegistry reg101(G101);
static skiagm::GMRegistry reg201(G201);
static skiagm::GMRegistry reg011(G011);
static skiagm::GMRegistry reg111(G111);
static skiagm::GMRegistry reg211(G211);
<commit_msg>update test<commit_after>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkColorPriv.h"
#include "SkShader.h"
/*
* Want to ensure that our bitmap sampler (in bitmap shader) keeps plenty of
* precision when scaling very large images (where the dx might get very small.
*/
#define W 257
#define H 161
class GiantBitmapGM : public skiagm::GM {
SkBitmap* fBM;
SkShader::TileMode fMode;
bool fDoFilter;
bool fDoRotate;
const SkBitmap& getBitmap() {
if (NULL == fBM) {
fBM = new SkBitmap;
fBM->setConfig(SkBitmap::kARGB_8888_Config, W, H);
fBM->allocPixels();
fBM->eraseColor(SK_ColorWHITE);
const SkColor colors[] = {
SK_ColorBLUE, SK_ColorRED, SK_ColorBLACK, SK_ColorGREEN
};
SkCanvas canvas(*fBM);
SkPaint paint;
paint.setAntiAlias(true);
paint.setStrokeWidth(SkIntToScalar(20));
#if 0
for (int y = -H*2; y < H; y += 50) {
SkScalar yy = SkIntToScalar(y);
paint.setColor(colors[y/50 & 0x3]);
canvas.drawLine(0, yy, SkIntToScalar(W), yy + SkIntToScalar(W),
paint);
}
#else
for (int x = -W; x < W; x += 60) {
paint.setColor(colors[x/60 & 0x3]);
SkScalar xx = SkIntToScalar(x);
canvas.drawLine(xx, 0, xx, SkIntToScalar(H),
paint);
}
#endif
}
return *fBM;
}
public:
GiantBitmapGM(SkShader::TileMode mode, bool doFilter, bool doRotate) : fBM(NULL) {
fMode = mode;
fDoFilter = doFilter;
fDoRotate = doRotate;
}
virtual ~GiantBitmapGM() {
SkDELETE(fBM);
}
protected:
virtual SkString onShortName() {
SkString str("giantbitmap_");
switch (fMode) {
case SkShader::kClamp_TileMode:
str.append("clamp");
break;
case SkShader::kRepeat_TileMode:
str.append("repeat");
break;
case SkShader::kMirror_TileMode:
str.append("mirror");
break;
default:
break;
}
str.append(fDoFilter ? "_bilerp" : "_point");
str.append(fDoRotate ? "_rotate" : "_scale");
return str;
}
virtual SkISize onISize() { return SkISize::Make(640, 480); }
virtual void onDraw(SkCanvas* canvas) {
SkPaint paint;
SkShader* s = SkShader::CreateBitmapShader(getBitmap(), fMode, fMode);
SkMatrix m;
if (fDoRotate) {
// m.setRotate(SkIntToScalar(30), 0, 0);
m.setSkew(SK_Scalar1, 0, 0, 0);
// m.postScale(2*SK_Scalar1/3, 2*SK_Scalar1/3);
} else {
SkScalar scale = 11*SK_Scalar1/12;
m.setScale(scale, scale);
}
s->setLocalMatrix(m);
paint.setShader(s)->unref();
paint.setFilterBitmap(fDoFilter);
canvas->translate(SkIntToScalar(50), SkIntToScalar(50));
SkRect r = SkRect::MakeXYWH(-50, -50, 32, 16);
// canvas->drawRect(r, paint); return;
canvas->drawPaint(paint);
}
private:
typedef GM INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
static skiagm::GM* G000(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, false, false); }
static skiagm::GM* G100(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, false, false); }
static skiagm::GM* G200(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, false, false); }
static skiagm::GM* G010(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, true, false); }
static skiagm::GM* G110(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, true, false); }
static skiagm::GM* G210(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, true, false); }
static skiagm::GM* G001(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, false, true); }
static skiagm::GM* G101(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, false, true); }
static skiagm::GM* G201(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, false, true); }
static skiagm::GM* G011(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, true, true); }
static skiagm::GM* G111(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, true, true); }
static skiagm::GM* G211(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, true, true); }
static skiagm::GMRegistry reg000(G000);
static skiagm::GMRegistry reg100(G100);
static skiagm::GMRegistry reg200(G200);
static skiagm::GMRegistry reg010(G010);
static skiagm::GMRegistry reg110(G110);
static skiagm::GMRegistry reg210(G210);
static skiagm::GMRegistry reg001(G001);
static skiagm::GMRegistry reg101(G101);
static skiagm::GMRegistry reg201(G201);
static skiagm::GMRegistry reg011(G011);
static skiagm::GMRegistry reg111(G111);
static skiagm::GMRegistry reg211(G211);
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 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 "Xalan" 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 [email protected].
*
* 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/>.
*/
#if !defined(VCPPDEFINITIONS_HEADER_GUARD_1357924680)
#define VCPPDEFINITIONS_HEADER_GUARD_1357924680
#pragma warning(disable: 4127 4251 4511 4512 4514 4702 4710 4711 4786 4097; error: 4150 4172 4238 4239 4715)
// ---------------------------------------------------------------------------
// A define in the build for each project is also used to control whether
// the export keyword is from the project's viewpoint or the client's.
// These defines provide the platform specific keywords that they need
// to do this.
// ---------------------------------------------------------------------------
#define XALAN_PLATFORM_EXPORT __declspec(dllexport)
#define XALAN_PLATFORM_IMPORT __declspec(dllimport)
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT
#define XALAN_NO_COVARIANT_RETURN_TYPE
#define XALAN_LSTRSUPPORT
#define XALAN_FULL_WCHAR_SUPPORT
#define XALAN_USE_WCHAR_SUPPORT
#define XALAN_RTTI_AVAILABLE
#define XALAN_LITLE_ENDIAN
#define XALAN_NEWLINE_IS_CRLF
#endif // VCPPDEFINITIONS_HEADER_GUARD_1357924680
<commit_msg>New #define to compensate for Microsoft's old std::string implementation.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 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 "Xalan" 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 [email protected].
*
* 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/>.
*/
#if !defined(VCPPDEFINITIONS_HEADER_GUARD_1357924680)
#define VCPPDEFINITIONS_HEADER_GUARD_1357924680
#pragma warning(disable: 4127 4251 4511 4512 4514 4702 4710 4711 4786 4097; error: 4150 4172 4238 4239 4715)
// ---------------------------------------------------------------------------
// A define in the build for each project is also used to control whether
// the export keyword is from the project's viewpoint or the client's.
// These defines provide the platform specific keywords that they need
// to do this.
// ---------------------------------------------------------------------------
#define XALAN_PLATFORM_EXPORT __declspec(dllexport)
#define XALAN_PLATFORM_IMPORT __declspec(dllimport)
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT
#define XALAN_NO_COVARIANT_RETURN_TYPE
#define XALAN_LSTRSUPPORT
#define XALAN_FULL_WCHAR_SUPPORT
#define XALAN_USE_WCHAR_SUPPORT
#define XALAN_RTTI_AVAILABLE
#define XALAN_LITLE_ENDIAN
#define XALAN_NEWLINE_IS_CRLF
// This is defined because Microsoft's basic_string is old, and
// does not have some of the things that it ought, like push_back().
// Eventually, they will get with it.
#define XALAN_OLD_STD_STRING
#endif // VCPPDEFINITIONS_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>#include "ArduinoInterface.h"
#include "ArduinoCmds.hpp"
#include "OSMC_driver.hpp"
class OSMC_4wd_driver
{
public:
OSMC_4wd_driver(const byte FORosmc, const byte FORcoder, const byte AFTosmc, const byte AFTcoder);
//~OSMC_4wd_driver();
//set motor
bool setMotorPWM(const int FR, const int FL, const int BR, const int BL);//must be -255 <-> 255, larger input trucated to 255, sign is pos / rev, true on failure
bool setMotorPWM(const byte FRdir, const byte FRmag, const byte FLdir, const byte FLmag, const byte BRdir, const byte BRmag, const byte BLdir, const byte BLmag);//must be 0 - 255, dir is pos / rev, true on failure
void setMotorVel_pd(const double FR, const double FL, const double BR, const double BL);
//update pd
bool update_pd();
//interog
bool getEncoderVel(double& FL, double& FR, double& BL, double& BR);
bool getLastPWMSent();
private:
volatile bool m_connected;
OSMC_driver FOR;
OSMC_driver AFT;
};
<commit_msg>spelling<commit_after>#include "ArduinoInterface.h"
#include "ArduinoCmds.hpp"
#include "OSMC_driver.hpp"
class OSMC_4wd_driver
{
public:
OSMC_4wd_driver(const byte FORosmc, const byte FORcoder, const byte AFTosmc, const byte AFTcoder);
//~OSMC_4wd_driver();
//set motor
bool setMotorPWM(const int FR, const int FL, const int BR, const int BL);//must be -255 <-> 255, larger input mag truncated to 255, sign is pos / rev, true on failure
bool setMotorPWM(const byte FRdir, const byte FRmag, const byte FLdir, const byte FLmag, const byte BRdir, const byte BRmag, const byte BLdir, const byte BLmag);//must be 0 - 255, dir is pos / rev, true on failure
void setMotorVel_pd(const double FR, const double FL, const double BR, const double BL);
//update pd
bool update_pd();
//interog
bool getEncoderVel(double& FL, double& FR, double& BL, double& BR);
bool getLastPWMSent();
private:
volatile bool m_connected;
OSMC_driver FOR;
OSMC_driver AFT;
};
<|endoftext|> |
<commit_before>//===- lib/Driver/Driver.cpp - Linker Driver Emulator ---------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lld/Driver/Driver.h"
#include "lld/Core/LLVM.h"
#include "lld/Core/InputFiles.h"
#include "lld/Core/Instrumentation.h"
#include "lld/Core/PassManager.h"
#include "lld/Core/Parallel.h"
#include "lld/Core/Resolver.h"
#include "lld/ReaderWriter/Reader.h"
#include "lld/ReaderWriter/Writer.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Option/Arg.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
namespace lld {
/// This is where the link is actually performed.
bool Driver::link(const LinkingContext &context, raw_ostream &diagnostics) {
// Honor -mllvm
if (!context.llvmOptions().empty()) {
unsigned numArgs = context.llvmOptions().size();
const char **args = new const char *[numArgs + 2];
args[0] = "lld (LLVM option parsing)";
for (unsigned i = 0; i != numArgs; ++i)
args[i + 1] = context.llvmOptions()[i];
args[numArgs + 1] = 0;
llvm::cl::ParseCommandLineOptions(numArgs + 1, args);
}
InputGraph &inputGraph = context.inputGraph();
if (!inputGraph.numFiles())
return true;
// Read inputs
ScopedTask readTask(getDefaultDomain(), "Read Args");
std::vector<std::vector<std::unique_ptr<File> > > files(
inputGraph.numFiles());
size_t index = 0;
std::atomic<bool> fail(false);
TaskGroup tg;
std::vector<std::unique_ptr<LinkerInput> > linkerInputs;
for (auto &ie : inputGraph.inputElements()) {
if (ie->kind() == InputElement::Kind::File) {
FileNode *fileNode = (llvm::dyn_cast<FileNode>)(ie.get());
auto linkerInput = fileNode->createLinkerInput(context);
if (!linkerInput) {
llvm::outs() << fileNode->errStr(error_code(linkerInput)) << "\n";
return true;
}
linkerInputs.push_back(std::move(*linkerInput));
}
else {
llvm_unreachable("Not handling other types of InputElements");
return true;
}
}
for (const auto &input : linkerInputs) {
if (context.logInputFiles())
llvm::outs() << input->getPath() << "\n";
tg.spawn([ &, index]{
if (error_code ec = context.readFile(input->getPath(), files[index])) {
diagnostics << "Failed to read file: " << input->getPath() << ": "
<< ec.message() << "\n";
fail = true;
return;
}
});
++index;
}
tg.sync();
readTask.end();
if (fail)
return true;
InputFiles inputs;
for (auto &f : inputGraph.internalFiles())
inputs.appendFile(*f.get());
for (auto &f : files)
inputs.appendFiles(f);
// Give target a chance to add files.
context.addImplicitFiles(inputs);
// assign an ordinal to each file so sort() can preserve command line order
inputs.assignFileOrdinals();
// Do core linking.
ScopedTask resolveTask(getDefaultDomain(), "Resolve");
Resolver resolver(context, inputs);
if (resolver.resolve()) {
if (!context.allowRemainingUndefines())
return true;
}
MutableFile &merged = resolver.resultFile();
resolveTask.end();
// Run passes on linked atoms.
ScopedTask passTask(getDefaultDomain(), "Passes");
PassManager pm;
context.addPasses(pm);
pm.runOnFile(merged);
passTask.end();
// Give linked atoms to Writer to generate output file.
ScopedTask writeTask(getDefaultDomain(), "Write");
if (error_code ec = context.writeFile(merged)) {
diagnostics << "Failed to write file '" << context.outputPath()
<< "': " << ec.message() << "\n";
return true;
}
return false;
}
} // namespace
<commit_msg>[lld][Driver] remove return after llvm_unreachable<commit_after>//===- lib/Driver/Driver.cpp - Linker Driver Emulator ---------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lld/Driver/Driver.h"
#include "lld/Core/LLVM.h"
#include "lld/Core/InputFiles.h"
#include "lld/Core/Instrumentation.h"
#include "lld/Core/PassManager.h"
#include "lld/Core/Parallel.h"
#include "lld/Core/Resolver.h"
#include "lld/ReaderWriter/Reader.h"
#include "lld/ReaderWriter/Writer.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Option/Arg.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
namespace lld {
/// This is where the link is actually performed.
bool Driver::link(const LinkingContext &context, raw_ostream &diagnostics) {
// Honor -mllvm
if (!context.llvmOptions().empty()) {
unsigned numArgs = context.llvmOptions().size();
const char **args = new const char *[numArgs + 2];
args[0] = "lld (LLVM option parsing)";
for (unsigned i = 0; i != numArgs; ++i)
args[i + 1] = context.llvmOptions()[i];
args[numArgs + 1] = 0;
llvm::cl::ParseCommandLineOptions(numArgs + 1, args);
}
InputGraph &inputGraph = context.inputGraph();
if (!inputGraph.numFiles())
return true;
// Read inputs
ScopedTask readTask(getDefaultDomain(), "Read Args");
std::vector<std::vector<std::unique_ptr<File> > > files(
inputGraph.numFiles());
size_t index = 0;
std::atomic<bool> fail(false);
TaskGroup tg;
std::vector<std::unique_ptr<LinkerInput> > linkerInputs;
for (auto &ie : inputGraph.inputElements()) {
if (ie->kind() == InputElement::Kind::File) {
FileNode *fileNode = (llvm::dyn_cast<FileNode>)(ie.get());
auto linkerInput = fileNode->createLinkerInput(context);
if (!linkerInput) {
llvm::outs() << fileNode->errStr(error_code(linkerInput)) << "\n";
return true;
}
linkerInputs.push_back(std::move(*linkerInput));
}
else {
llvm_unreachable("Not handling other types of InputElements");
}
}
for (const auto &input : linkerInputs) {
if (context.logInputFiles())
llvm::outs() << input->getPath() << "\n";
tg.spawn([ &, index]{
if (error_code ec = context.readFile(input->getPath(), files[index])) {
diagnostics << "Failed to read file: " << input->getPath() << ": "
<< ec.message() << "\n";
fail = true;
return;
}
});
++index;
}
tg.sync();
readTask.end();
if (fail)
return true;
InputFiles inputs;
for (auto &f : inputGraph.internalFiles())
inputs.appendFile(*f.get());
for (auto &f : files)
inputs.appendFiles(f);
// Give target a chance to add files.
context.addImplicitFiles(inputs);
// assign an ordinal to each file so sort() can preserve command line order
inputs.assignFileOrdinals();
// Do core linking.
ScopedTask resolveTask(getDefaultDomain(), "Resolve");
Resolver resolver(context, inputs);
if (resolver.resolve()) {
if (!context.allowRemainingUndefines())
return true;
}
MutableFile &merged = resolver.resultFile();
resolveTask.end();
// Run passes on linked atoms.
ScopedTask passTask(getDefaultDomain(), "Passes");
PassManager pm;
context.addPasses(pm);
pm.runOnFile(merged);
passTask.end();
// Give linked atoms to Writer to generate output file.
ScopedTask writeTask(getDefaultDomain(), "Write");
if (error_code ec = context.writeFile(merged)) {
diagnostics << "Failed to write file '" << context.outputPath()
<< "': " << ec.message() << "\n";
return true;
}
return false;
}
} // namespace
<|endoftext|> |
<commit_before>/* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include "handshake.h"
#include <mysql.h> // for MYSQL structure
/// Client-side context for authentication handshake
class Handshake_client: public Handshake
{
/**
Name of the server's service for which we authenticate.
The service name is sent by server in the initial packet. If no
service name is used, this member is @c NULL.
*/
SEC_WCHAR *m_service_name;
/// Buffer for storing service name obtained from server.
SEC_WCHAR m_service_name_buf[MAX_SERVICE_NAME_LENGTH];
Connection &m_con;
public:
Handshake_client(Connection &con, const char *target, size_t len);
~Handshake_client();
Blob first_packet();
Blob process_data(const Blob&);
Blob read_packet();
int write_packet(Blob &data);
};
/**
Create authentication handshake context for client.
@param con connection for communication with the peer
@param target name of the target service with which we will authenticate
(can be NULL if not used)
Some security packages (like Kerberos) require providing explicit name
of the service with which a client wants to authenticate. The server-side
authentication plugin sends this name in the greeting packet
(see @c win_auth_handshake_{server,client}() functions).
*/
Handshake_client::Handshake_client(Connection &con,
const char *target, size_t len)
: Handshake(SSP_NAME, CLIENT), m_service_name(NULL), m_con(con)
{
if (!target || 0 == len)
return;
// Convert received UPN to internal WCHAR representation.
m_service_name= utf8_to_wchar(target, &len);
if (m_service_name)
DBUG_PRINT("info", ("Using target service: %S\n", m_service_name));
else
{
/*
Note: we ignore errors here - m_target will be NULL, the target name
will not be used and system will fall-back to NTLM authentication. But
we leave trace in error log.
*/
ERROR_LOG(WARNING, ("Could not decode UPN sent by the server"
"; target service name will not be used"
" and Kerberos authentication will not work"));
}
}
Handshake_client::~Handshake_client()
{
if (m_service_name)
free(m_service_name);
}
Blob Handshake_client::read_packet()
{
/*
We do a fake read in the first round because first
packet from the server containing UPN must be read
before the handshake context is created and the packet
processing loop starts. We return an empty blob here
and process_data() function will ignore it.
*/
if (m_round == 1)
return Blob();
// Otherwise we read packet from the connection.
Blob packet= m_con.read();
m_error= m_con.error();
if (!m_error && packet.is_null())
m_error= true; // (no specific error code assigned)
if (m_error)
return Blob();
DBUG_PRINT("dump", ("Got the following bytes"));
DBUG_DUMP("dump", packet.ptr(), packet.len());
return packet;
}
int Handshake_client::write_packet(Blob &data)
{
/*
Length of the first data payload send by client authentication plugin is
limited to 255 bytes (because it is wrapped inside client authentication
packet and is length-encoded with 1 byte for the length).
If the data payload is longer than 254 bytes, then it is sent in two parts:
first part of length 255 will be embedded in the authentication packet,
second part will be sent in the following packet. Byte 255 of the first
part contains information about the total length of the payload. It is a
number of blocks of size 512 bytes which is sufficient to store the
combined packets.
Server's logic for reading first client's payload is as follows
(see Handshake_server::read_packet()):
1. Read data from the authentication packet, if it is shorter than 255 bytes
then that is all data sent by client.
2. If there is 255 bytes of data in the authentication packet, read another
packet and append it to the data, skipping byte 255 of the first packet
which can be used to allocate buffer of appropriate size.
*/
size_t len2= 0; // length of the second part of first data payload
byte saved_byte; // for saving byte 255 in which data length is stored
if (m_round == 1 && data.len() > 254)
{
len2= data.len() - 254;
DBUG_PRINT("info", ("Splitting first packet of length %lu"
", %lu bytes will be sent in a second part",
data.len(), len2));
/*
Store in byte 255 the number of 512b blocks that are needed to
keep all the data.
*/
unsigned block_count= data.len()/512 + ((data.len() % 512) ? 1 : 0);
DBUG_ASSERT(block_count < (unsigned)0x100);
saved_byte= data[254];
data[254] = block_count;
data.trim(255);
}
DBUG_PRINT("dump", ("Sending the following data"));
DBUG_DUMP("dump", data.ptr(), data.len());
int ret= m_con.write(data);
if (ret)
return ret;
// Write second part if it is present.
if (len2)
{
data[254]= saved_byte;
Blob data2(data.ptr() + 254, len2);
DBUG_PRINT("info", ("Sending second part of data"));
DBUG_DUMP("info", data2.ptr(), data2.len());
ret= m_con.write(data2);
}
return ret;
}
/**
Process data sent by server.
@param[in] data blob with data from server
This method analyses data sent by server during authentication handshake.
If client should continue packet exchange, this method returns data to
be sent to the server next. If no more data needs to be exchanged, an
empty blob is returned and @c is_complete() is @c true. In case of error
an empty blob is returned and @c error() gives non-zero error code.
When invoked for the first time (in the first round of the handshake)
there is no data from the server (data blob is null) and the intial
packet is generated without an input.
@return Data to be sent to the server next or null blob if no more data
needs to be exchanged or in case of error.
*/
Blob Handshake_client::process_data(const Blob &data)
{
#if !defined(DBUG_OFF) && defined(WINAUTH_USE_DBUG_LIB)
/*
Code for testing the logic for sending the first client payload.
A fake data of length given by environment variable TEST_PACKET_LENGTH
(or default 255 bytes) is sent to the server. First 2 bytes of the
payload contain its total length (LSB first). The length of test data
is limited to 2048 bytes.
Upon receiving test data, server will check that data is correct and
refuse connection. If server detects data errors it will crash on
assertion.
This code is executed if debug flag "winauth_first_packet_test" is
set, e.g. using client option:
--debug="d,winauth_first_packet_test"
The same debug flag must be enabled in the server, e.g. using
statement:
SET GLOBAL debug= '+d,winauth_first_packet_test';
*/
static byte test_buf[2048];
if (m_round == 1
&& DBUG_EVALUATE_IF("winauth_first_packet_test", true, false))
{
const char *env= getenv("TEST_PACKET_LENGTH");
size_t len= env ? atoi(env) : 0;
if (!len)
len= 255;
if (len > sizeof(test_buf))
len= sizeof(test_buf);
// Store data length in first 2 bytes.
byte *ptr= test_buf;
*ptr++= len & 0xFF;
*ptr++= len >> 8;
// Fill remaining bytes with known values.
for (byte b= 0; ptr < test_buf + len; ++ptr, ++b)
*ptr= b;
return Blob(test_buf, len);
};
#endif
Security_buffer input(data);
SECURITY_STATUS ret;
m_output.free();
ret= InitializeSecurityContextW(
&m_cred,
m_round == 1 ? NULL : &m_sctx, // partial context
m_service_name, // service name
ASC_REQ_ALLOCATE_MEMORY, // requested attributes
0, // reserved
SECURITY_NETWORK_DREP, // data representation
m_round == 1 ? NULL : &input, // input data
0, // reserved
&m_sctx, // context
&m_output, // output data
&m_atts, // attributes
&m_expire); // expire date
if (process_result(ret))
{
DBUG_PRINT("error",
("InitializeSecurityContext() failed with error %X", ret));
return Blob();
}
return m_output.as_blob();
}
/**********************************************************************/
/**
Perform authentication handshake from client side.
@param[in] vio pointer to @c MYSQL_PLUGIN_VIO instance to be used
for communication with the server
@param[in] mysql pointer to a MySQL connection for which we authenticate
After reading the initial packet from server, containing its UPN to be
used as service name, client starts packet exchange by sending the first
packet in this exchange. While handshake is not yet completed, client
reads packets sent by the server and process them, possibly generating new
data to be sent to the server.
This function reports errors.
@return 0 on success.
*/
int win_auth_handshake_client(MYSQL_PLUGIN_VIO *vio, MYSQL *mysql)
{
DBUG_ENTER("win_auth_handshake_client");
/*
Check if we should enable logging.
*/
{
const char *opt= getenv("AUTHENTICATION_WIN_LOG");
int opt_val= opt ? atoi(opt) : 0;
if (opt && !opt_val)
{
if (!strncasecmp("on", opt, 2)) opt_val= 2;
if (!strncasecmp("yes", opt, 3)) opt_val= 2;
if (!strncasecmp("true", opt, 4)) opt_val= 2;
if (!strncasecmp("debug", opt, 5)) opt_val= 4;
if (!strncasecmp("dbug", opt, 4)) opt_val= 4;
}
set_log_level(opt_val);
}
ERROR_LOG(INFO, ("Authentication handshake for account %s", mysql->user));
// Create connection object.
Connection con(vio);
DBUG_ASSERT(!con.error());
// Read initial packet from server containing service name.
Blob service_name= con.read();
if (con.error() || service_name.is_null())
{
ERROR_LOG(ERROR, ("Error reading initial packet"));
DBUG_RETURN(CR_ERROR);
}
DBUG_PRINT("info", ("Got initial packet of length %d", service_name.len()));
// Create authentication handshake context using the given service name.
Handshake_client hndshk(con,
service_name[0] ? (char *)service_name.ptr() : NULL,
service_name.len());
if (hndshk.error())
{
ERROR_LOG(ERROR, ("Could not create authentication handshake context"));
DBUG_RETURN(CR_ERROR);
}
DBUG_ASSERT(!hndshk.error());
/*
Read and process packets from server until handshake is complete.
Note that the first read from server is dummy
(see Handshake_client::read_packet()) as we already have read the
first packet to establish service name.
*/
if (hndshk.packet_processing_loop())
DBUG_RETURN(CR_ERROR);
DBUG_ASSERT(!hndshk.error() && hndshk.is_complete());
DBUG_RETURN(CR_OK);
}
<commit_msg>Bug#12982926 CLIENT CAN OVERRIDE ZERO-LENGTH-ALLOCATE BUFFER<commit_after>/* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include "handshake.h"
#include <mysql.h> // for MYSQL structure
/// Client-side context for authentication handshake
class Handshake_client: public Handshake
{
/**
Name of the server's service for which we authenticate.
The service name is sent by server in the initial packet. If no
service name is used, this member is @c NULL.
*/
SEC_WCHAR *m_service_name;
/// Buffer for storing service name obtained from server.
SEC_WCHAR m_service_name_buf[MAX_SERVICE_NAME_LENGTH];
Connection &m_con;
public:
Handshake_client(Connection &con, const char *target, size_t len);
~Handshake_client();
Blob first_packet();
Blob process_data(const Blob&);
Blob read_packet();
int write_packet(Blob &data);
};
/**
Create authentication handshake context for client.
@param con connection for communication with the peer
@param target name of the target service with which we will authenticate
(can be NULL if not used)
Some security packages (like Kerberos) require providing explicit name
of the service with which a client wants to authenticate. The server-side
authentication plugin sends this name in the greeting packet
(see @c win_auth_handshake_{server,client}() functions).
*/
Handshake_client::Handshake_client(Connection &con,
const char *target, size_t len)
: Handshake(SSP_NAME, CLIENT), m_service_name(NULL), m_con(con)
{
if (!target || 0 == len)
return;
// Convert received UPN to internal WCHAR representation.
m_service_name= utf8_to_wchar(target, &len);
if (m_service_name)
DBUG_PRINT("info", ("Using target service: %S\n", m_service_name));
else
{
/*
Note: we ignore errors here - m_target will be NULL, the target name
will not be used and system will fall-back to NTLM authentication. But
we leave trace in error log.
*/
ERROR_LOG(WARNING, ("Could not decode UPN sent by the server"
"; target service name will not be used"
" and Kerberos authentication will not work"));
}
}
Handshake_client::~Handshake_client()
{
if (m_service_name)
free(m_service_name);
}
Blob Handshake_client::read_packet()
{
/*
We do a fake read in the first round because first
packet from the server containing UPN must be read
before the handshake context is created and the packet
processing loop starts. We return an empty blob here
and process_data() function will ignore it.
*/
if (m_round == 1)
return Blob();
// Otherwise we read packet from the connection.
Blob packet= m_con.read();
m_error= m_con.error();
if (!m_error && packet.is_null())
m_error= true; // (no specific error code assigned)
if (m_error)
return Blob();
DBUG_PRINT("dump", ("Got the following bytes"));
DBUG_DUMP("dump", packet.ptr(), packet.len());
return packet;
}
int Handshake_client::write_packet(Blob &data)
{
/*
Length of the first data payload send by client authentication plugin is
limited to 255 bytes (because it is wrapped inside client authentication
packet and is length-encoded with 1 byte for the length).
If the data payload is longer than 254 bytes, then it is sent in two parts:
first part of length 255 will be embedded in the authentication packet,
second part will be sent in the following packet. Byte 255 of the first
part contains information about the total length of the payload. It is a
number of blocks of size 512 bytes which is sufficient to store the
combined packets.
Server's logic for reading first client's payload is as follows
(see Handshake_server::read_packet()):
1. Read data from the authentication packet, if it is shorter than 255 bytes
then that is all data sent by client.
2. If there is 255 bytes of data in the authentication packet, read another
packet and append it to the data, skipping byte 255 of the first packet
which can be used to allocate buffer of appropriate size.
*/
size_t len2= 0; // length of the second part of first data payload
byte saved_byte; // for saving byte 255 in which data length is stored
if (m_round == 1 && data.len() > 254)
{
len2= data.len() - 254;
DBUG_PRINT("info", ("Splitting first packet of length %lu"
", %lu bytes will be sent in a second part",
data.len(), len2));
/*
Store in byte 255 the number of 512b blocks that are needed to
keep all the data.
*/
unsigned block_count= data.len()/512 + ((data.len() % 512) ? 1 : 0);
#if !defined(DBUG_OFF) && defined(WINAUTH_USE_DBUG_LIB)
/*
For testing purposes, use wrong block count to see how server
handles this.
*/
DBUG_EXECUTE_IF("winauth_first_packet_test",{
block_count= data.len() == 601 ? 0 :
data.len() == 602 ? 1 :
block_count;
});
#endif
DBUG_ASSERT(block_count < (unsigned)0x100);
saved_byte= data[254];
data[254] = block_count;
data.trim(255);
}
DBUG_PRINT("dump", ("Sending the following data"));
DBUG_DUMP("dump", data.ptr(), data.len());
int ret= m_con.write(data);
if (ret)
return ret;
// Write second part if it is present.
if (len2)
{
data[254]= saved_byte;
Blob data2(data.ptr() + 254, len2);
DBUG_PRINT("info", ("Sending second part of data"));
DBUG_DUMP("info", data2.ptr(), data2.len());
ret= m_con.write(data2);
}
return ret;
}
/**
Process data sent by server.
@param[in] data blob with data from server
This method analyses data sent by server during authentication handshake.
If client should continue packet exchange, this method returns data to
be sent to the server next. If no more data needs to be exchanged, an
empty blob is returned and @c is_complete() is @c true. In case of error
an empty blob is returned and @c error() gives non-zero error code.
When invoked for the first time (in the first round of the handshake)
there is no data from the server (data blob is null) and the intial
packet is generated without an input.
@return Data to be sent to the server next or null blob if no more data
needs to be exchanged or in case of error.
*/
Blob Handshake_client::process_data(const Blob &data)
{
#if !defined(DBUG_OFF) && defined(WINAUTH_USE_DBUG_LIB)
/*
Code for testing the logic for sending the first client payload.
A fake data of length given by environment variable TEST_PACKET_LENGTH
(or default 255 bytes) is sent to the server. First 2 bytes of the
payload contain its total length (LSB first). The length of test data
is limited to 2048 bytes.
Upon receiving test data, server will check that data is correct and
refuse connection. If server detects data errors it will crash on
assertion.
This code is executed if debug flag "winauth_first_packet_test" is
set, e.g. using client option:
--debug="d,winauth_first_packet_test"
The same debug flag must be enabled in the server, e.g. using
statement:
SET GLOBAL debug= '+d,winauth_first_packet_test';
*/
static byte test_buf[2048];
if (m_round == 1
&& DBUG_EVALUATE_IF("winauth_first_packet_test", true, false))
{
const char *env= getenv("TEST_PACKET_LENGTH");
size_t len= env ? atoi(env) : 0;
if (!len)
len= 255;
if (len > sizeof(test_buf))
len= sizeof(test_buf);
// Store data length in first 2 bytes.
byte *ptr= test_buf;
*ptr++= len & 0xFF;
*ptr++= len >> 8;
// Fill remaining bytes with known values.
for (byte b= 0; ptr < test_buf + len; ++ptr, ++b)
*ptr= b;
return Blob(test_buf, len);
};
#endif
Security_buffer input(data);
SECURITY_STATUS ret;
m_output.free();
ret= InitializeSecurityContextW(
&m_cred,
m_round == 1 ? NULL : &m_sctx, // partial context
m_service_name, // service name
ASC_REQ_ALLOCATE_MEMORY, // requested attributes
0, // reserved
SECURITY_NETWORK_DREP, // data representation
m_round == 1 ? NULL : &input, // input data
0, // reserved
&m_sctx, // context
&m_output, // output data
&m_atts, // attributes
&m_expire); // expire date
if (process_result(ret))
{
DBUG_PRINT("error",
("InitializeSecurityContext() failed with error %X", ret));
return Blob();
}
return m_output.as_blob();
}
/**********************************************************************/
/**
Perform authentication handshake from client side.
@param[in] vio pointer to @c MYSQL_PLUGIN_VIO instance to be used
for communication with the server
@param[in] mysql pointer to a MySQL connection for which we authenticate
After reading the initial packet from server, containing its UPN to be
used as service name, client starts packet exchange by sending the first
packet in this exchange. While handshake is not yet completed, client
reads packets sent by the server and process them, possibly generating new
data to be sent to the server.
This function reports errors.
@return 0 on success.
*/
int win_auth_handshake_client(MYSQL_PLUGIN_VIO *vio, MYSQL *mysql)
{
DBUG_ENTER("win_auth_handshake_client");
/*
Check if we should enable logging.
*/
{
const char *opt= getenv("AUTHENTICATION_WIN_LOG");
int opt_val= opt ? atoi(opt) : 0;
if (opt && !opt_val)
{
if (!strncasecmp("on", opt, 2)) opt_val= 2;
if (!strncasecmp("yes", opt, 3)) opt_val= 2;
if (!strncasecmp("true", opt, 4)) opt_val= 2;
if (!strncasecmp("debug", opt, 5)) opt_val= 4;
if (!strncasecmp("dbug", opt, 4)) opt_val= 4;
}
set_log_level(opt_val);
}
ERROR_LOG(INFO, ("Authentication handshake for account %s", mysql->user));
// Create connection object.
Connection con(vio);
DBUG_ASSERT(!con.error());
// Read initial packet from server containing service name.
Blob service_name= con.read();
if (con.error() || service_name.is_null())
{
ERROR_LOG(ERROR, ("Error reading initial packet"));
DBUG_RETURN(CR_ERROR);
}
DBUG_PRINT("info", ("Got initial packet of length %d", service_name.len()));
// Create authentication handshake context using the given service name.
Handshake_client hndshk(con,
service_name[0] ? (char *)service_name.ptr() : NULL,
service_name.len());
if (hndshk.error())
{
ERROR_LOG(ERROR, ("Could not create authentication handshake context"));
DBUG_RETURN(CR_ERROR);
}
DBUG_ASSERT(!hndshk.error());
/*
Read and process packets from server until handshake is complete.
Note that the first read from server is dummy
(see Handshake_client::read_packet()) as we already have read the
first packet to establish service name.
*/
if (hndshk.packet_processing_loop())
DBUG_RETURN(CR_ERROR);
DBUG_ASSERT(!hndshk.error() && hndshk.is_complete());
DBUG_RETURN(CR_OK);
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** This file is a modified version of part of an example program for Qt.
** This file may be used, distributed and modified without limitation.
**
** Don Sanders <[email protected]>
**
*****************************************************************************/
#include "smtp.h"
#include <qtextstream.h>
#include <qsocket.h>
#include <qtimer.h>
#include <kapp.h>
#include <kmessagebox.h>
#include <klocale.h>
Smtp::Smtp( const QString &from, const QStringList &to,
const QString &aMessage,
const QString &server,
unsigned short int port )
{
skipReadResponse = false;
mSocket = new QSocket( this );
connect ( mSocket, SIGNAL( readyRead() ),
this, SLOT( readyRead() ) );
connect ( mSocket, SIGNAL( connected() ),
this, SLOT( connected() ) );
connect ( mSocket, SIGNAL( error(int) ),
this, SLOT( socketError(int) ) );
message = aMessage;
this->from = from;
rcpt = to;
state = smtpInit;
command = "";
emit status( i18n( "Connecting to %1" ).arg( server ) );
mSocket->connectToHost( server, port );
t = new QTextStream( mSocket );
}
Smtp::~Smtp()
{
if (t)
delete t;
if (mSocket)
delete mSocket;
}
void Smtp::send( const QString &from, const QStringList &to,
const QString &aMessage )
{
skipReadResponse = true;
message = aMessage;
this->from = from;
rcpt = to;
state = smtpMail;
command = "";
readyRead();
}
void Smtp::quit()
{
skipReadResponse = true;
state = smtpQuit;
command = "";
readyRead();
}
void Smtp::connected()
{
emit status( i18n( "Connected to %1" ).arg( mSocket->peerName() ) );
}
void Smtp::socketError(int errorCode)
{
command = "CONNECT";
switch ( errorCode ) {
case QSocket::ErrConnectionRefused:
responseLine = i18n( "Connection refused." );
break;
case QSocket::ErrHostNotFound:
responseLine = i18n( "Host Not Found." );
break;
case QSocket::ErrSocketRead:
responseLine = i18n( "Error reading socket." );
break;
default:
responseLine = i18n( "Internal error, unrecognized error." );
}
QTimer::singleShot( 0, this, SLOT(emitError()) );
}
void Smtp::emitError() {
error( command, responseLine );
}
void Smtp::readyRead()
{
if (!skipReadResponse) {
// SMTP is line-oriented
if ( !mSocket->canReadLine() )
return;
do {
responseLine = mSocket->readLine();
response += responseLine;
} while( mSocket->canReadLine() && responseLine[3] != ' ' );
responseLine.truncate( 3 );
}
skipReadResponse = false;
if ( state == smtpInit && responseLine[0] == '2' ) {
// banner was okay, let's go on
command = "HELO there";
*t << "HELO there\r\n";
state = smtpMail;
} else if ( state == smtpMail && responseLine[0] == '2' ) {
// HELO response was okay (well, it has to be)
command = "MAIL";
*t << "MAIL FROM: <" << from << ">\r\n";
state = smtpRcpt;
} else if ( state == smtpRcpt && responseLine[0] == '2' && (rcpt.begin() != rcpt.end())) {
command = "RCPT";
*t << "RCPT TO: <" << *(rcpt.begin()) << ">\r\n";
rcpt.remove( rcpt.begin() );
if (rcpt.begin() == rcpt.end())
state = smtpData;
} else if ( state == smtpData && responseLine[0] == '2' ) {
command = "DATA";
*t << "DATA\r\n";
state = smtpBody;
} else if ( state == smtpBody && responseLine[0] == '3' ) {
command = "DATA";
QString seperator = "";
if (message[message.length() - 1] != '\n')
seperator = "\n";
*t << message << seperator << ".\r\n";
state = smtpSuccess;
} else if ( state == smtpSuccess && responseLine[0] == '2' ) {
QTimer::singleShot( 0, this, SIGNAL(success()) );
} else if ( state == smtpQuit && responseLine[0] == '2' ) {
command = "QUIT";
*t << "QUIT\r\n";
// here, we just close.
state = smtpClose;
emit status( tr( "Message sent" ) );
} else if ( state == smtpClose ) {
// we ignore it
} else { // error occurred
QTimer::singleShot( 0, this, SLOT(emitError()) );
state = smtpClose;
}
response = "";
if ( state == smtpClose ) {
delete t;
t = 0;
delete mSocket;
mSocket = 0;
QTimer::singleShot( 0, this, SLOT(deleteMe()) );
}
}
void Smtp::deleteMe()
{
delete this;
}
<commit_msg>Fixed <CR><LF>.<CR><LF> issue which make qMail unhappy<commit_after>/****************************************************************************
**
** This file is a modified version of part of an example program for Qt.
** This file may be used, distributed and modified without limitation.
**
** Don Sanders <[email protected]>
**
*****************************************************************************/
#include "smtp.h"
#include <qtextstream.h>
#include <qsocket.h>
#include <qtimer.h>
#include <kapp.h>
#include <kmessagebox.h>
#include <klocale.h>
Smtp::Smtp( const QString &from, const QStringList &to,
const QString &aMessage,
const QString &server,
unsigned short int port )
{
skipReadResponse = false;
mSocket = new QSocket( this );
connect ( mSocket, SIGNAL( readyRead() ),
this, SLOT( readyRead() ) );
connect ( mSocket, SIGNAL( connected() ),
this, SLOT( connected() ) );
connect ( mSocket, SIGNAL( error(int) ),
this, SLOT( socketError(int) ) );
message = aMessage;
this->from = from;
rcpt = to;
state = smtpInit;
command = "";
emit status( i18n( "Connecting to %1" ).arg( server ) );
mSocket->connectToHost( server, port );
t = new QTextStream( mSocket );
}
Smtp::~Smtp()
{
if (t)
delete t;
if (mSocket)
delete mSocket;
}
void Smtp::send( const QString &from, const QStringList &to,
const QString &aMessage )
{
skipReadResponse = true;
message = aMessage;
this->from = from;
rcpt = to;
state = smtpMail;
command = "";
readyRead();
}
void Smtp::quit()
{
skipReadResponse = true;
state = smtpQuit;
command = "";
readyRead();
}
void Smtp::connected()
{
emit status( i18n( "Connected to %1" ).arg( mSocket->peerName() ) );
}
void Smtp::socketError(int errorCode)
{
command = "CONNECT";
switch ( errorCode ) {
case QSocket::ErrConnectionRefused:
responseLine = i18n( "Connection refused." );
break;
case QSocket::ErrHostNotFound:
responseLine = i18n( "Host Not Found." );
break;
case QSocket::ErrSocketRead:
responseLine = i18n( "Error reading socket." );
break;
default:
responseLine = i18n( "Internal error, unrecognized error." );
}
QTimer::singleShot( 0, this, SLOT(emitError()) );
}
void Smtp::emitError() {
error( command, responseLine );
}
void Smtp::readyRead()
{
if (!skipReadResponse) {
// SMTP is line-oriented
if ( !mSocket->canReadLine() )
return;
do {
responseLine = mSocket->readLine();
response += responseLine;
} while( mSocket->canReadLine() && responseLine[3] != ' ' );
responseLine.truncate( 3 );
}
skipReadResponse = false;
if ( state == smtpInit && responseLine[0] == '2' ) {
// banner was okay, let's go on
command = "HELO there";
*t << "HELO there\r\n";
state = smtpMail;
} else if ( state == smtpMail && responseLine[0] == '2' ) {
// HELO response was okay (well, it has to be)
command = "MAIL";
*t << "MAIL FROM: <" << from << ">\r\n";
state = smtpRcpt;
} else if ( state == smtpRcpt && responseLine[0] == '2' && (rcpt.begin() != rcpt.end())) {
command = "RCPT";
*t << "RCPT TO: <" << *(rcpt.begin()) << ">\r\n";
rcpt.remove( rcpt.begin() );
if (rcpt.begin() == rcpt.end())
state = smtpData;
} else if ( state == smtpData && responseLine[0] == '2' ) {
command = "DATA";
*t << "DATA\r\n";
state = smtpBody;
} else if ( state == smtpBody && responseLine[0] == '3' ) {
command = "DATA";
QString seperator = "";
if (message[message.length() - 1] != '\n')
seperator = "\r\n";
*t << message << seperator << ".\r\n";
state = smtpSuccess;
} else if ( state == smtpSuccess && responseLine[0] == '2' ) {
QTimer::singleShot( 0, this, SIGNAL(success()) );
} else if ( state == smtpQuit && responseLine[0] == '2' ) {
command = "QUIT";
*t << "QUIT\r\n";
// here, we just close.
state = smtpClose;
emit status( tr( "Message sent" ) );
} else if ( state == smtpClose ) {
// we ignore it
} else { // error occurred
QTimer::singleShot( 0, this, SLOT(emitError()) );
state = smtpClose;
}
response = "";
if ( state == smtpClose ) {
delete t;
t = 0;
delete mSocket;
mSocket = 0;
QTimer::singleShot( 0, this, SLOT(deleteMe()) );
}
}
void Smtp::deleteMe()
{
delete this;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 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 "chrome/browser/extensions/external_registry_extension_provider_win.h"
#include "base/file_path.h"
#include "base/registry.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/version.h"
// The Registry hive where to look for external extensions.
const HKEY kRegRoot = HKEY_LOCAL_MACHINE;
// The Registry subkey that contains information about external extensions.
const char kRegistryExtensions[] = "Software\\Google\\Chrome\\Extensions";
// Registry value of of that key that defines the path to the .crx file.
const wchar_t kRegistryExtensionPath[] = L"path";
// Registry value of that key that defines the current version of the .crx file.
const wchar_t kRegistryExtensionVersion[] = L"version";
ExternalRegistryExtensionProvider::ExternalRegistryExtensionProvider() {
}
ExternalRegistryExtensionProvider::~ExternalRegistryExtensionProvider() {
}
void ExternalRegistryExtensionProvider::VisitRegisteredExtension(
Visitor* visitor, const std::set<std::string>& ids_to_ignore) const {
RegistryKeyIterator iterator(kRegRoot,
ASCIIToWide(kRegistryExtensions).c_str());
while (iterator.Valid()) {
RegKey key;
std::wstring key_path = ASCIIToWide(kRegistryExtensions);
key_path.append(L"\\");
key_path.append(iterator.Name());
if (key.Open(kRegRoot, key_path.c_str(), KEY_READ)) {
std::wstring extension_path;
if (key.ReadValue(kRegistryExtensionPath, &extension_path)) {
std::wstring extension_version;
if (key.ReadValue(kRegistryExtensionVersion, &extension_version)) {
std::string id = WideToASCII(iterator.Name());
StringToLowerASCII(&id);
if (ids_to_ignore.find(id) != ids_to_ignore.end()) {
++iterator;
continue;
}
scoped_ptr<Version> version;
version.reset(Version::GetVersionFromString(extension_version));
FilePath path = FilePath::FromWStringHack(extension_path);
visitor->OnExternalExtensionFileFound(id, version.get(), path,
Extension::EXTERNAL_REGISTRY);
} else {
// TODO(erikkay): find a way to get this into about:extensions
LOG(WARNING) << "Missing value " << kRegistryExtensionVersion <<
" for key " << key_path;
}
} else {
// TODO(erikkay): find a way to get this into about:extensions
LOG(WARNING) << "Missing value " << kRegistryExtensionPath <<
" for key " << key_path;
}
}
++iterator;
}
}
Version* ExternalRegistryExtensionProvider::RegisteredVersion(
const std::string& id,
Extension::Location* location) const {
RegKey key;
std::wstring key_path = ASCIIToWide(kRegistryExtensions);
key_path.append(L"\\");
key_path.append(ASCIIToWide(id));
if (!key.Open(kRegRoot, key_path.c_str(), KEY_READ))
return NULL;
std::wstring extension_version;
if (!key.ReadValue(kRegistryExtensionVersion, &extension_version))
return NULL;
if (location)
*location = Extension::EXTERNAL_REGISTRY;
return Version::GetVersionFromString(extension_version);
}
<commit_msg>In windows registry external extensions provider, error out on invalid version.<commit_after>// Copyright (c) 2009 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 "chrome/browser/extensions/external_registry_extension_provider_win.h"
#include "base/file_path.h"
#include "base/registry.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/version.h"
// The Registry hive where to look for external extensions.
const HKEY kRegRoot = HKEY_LOCAL_MACHINE;
// The Registry subkey that contains information about external extensions.
const char kRegistryExtensions[] = "Software\\Google\\Chrome\\Extensions";
// Registry value of of that key that defines the path to the .crx file.
const wchar_t kRegistryExtensionPath[] = L"path";
// Registry value of that key that defines the current version of the .crx file.
const wchar_t kRegistryExtensionVersion[] = L"version";
ExternalRegistryExtensionProvider::ExternalRegistryExtensionProvider() {
}
ExternalRegistryExtensionProvider::~ExternalRegistryExtensionProvider() {
}
void ExternalRegistryExtensionProvider::VisitRegisteredExtension(
Visitor* visitor, const std::set<std::string>& ids_to_ignore) const {
RegistryKeyIterator iterator(kRegRoot,
ASCIIToWide(kRegistryExtensions).c_str());
while (iterator.Valid()) {
RegKey key;
std::wstring key_path = ASCIIToWide(kRegistryExtensions);
key_path.append(L"\\");
key_path.append(iterator.Name());
if (key.Open(kRegRoot, key_path.c_str(), KEY_READ)) {
std::wstring extension_path;
if (key.ReadValue(kRegistryExtensionPath, &extension_path)) {
std::wstring extension_version;
if (key.ReadValue(kRegistryExtensionVersion, &extension_version)) {
std::string id = WideToASCII(iterator.Name());
StringToLowerASCII(&id);
if (ids_to_ignore.find(id) != ids_to_ignore.end()) {
++iterator;
continue;
}
scoped_ptr<Version> version;
version.reset(Version::GetVersionFromString(extension_version));
if (!version.get()) {
LOG(ERROR) << "Invalid version value " << extension_version
<< " for key " << key_path;
continue;
}
FilePath path = FilePath::FromWStringHack(extension_path);
visitor->OnExternalExtensionFileFound(id, version.get(), path,
Extension::EXTERNAL_REGISTRY);
} else {
// TODO(erikkay): find a way to get this into about:extensions
LOG(ERROR) << "Missing value " << kRegistryExtensionVersion
<< " for key " << key_path;
}
} else {
// TODO(erikkay): find a way to get this into about:extensions
LOG(ERROR) << "Missing value " << kRegistryExtensionPath
<< " for key " << key_path;
}
}
++iterator;
}
}
Version* ExternalRegistryExtensionProvider::RegisteredVersion(
const std::string& id,
Extension::Location* location) const {
RegKey key;
std::wstring key_path = ASCIIToWide(kRegistryExtensions);
key_path.append(L"\\");
key_path.append(ASCIIToWide(id));
if (!key.Open(kRegRoot, key_path.c_str(), KEY_READ))
return NULL;
std::wstring extension_version;
if (!key.ReadValue(kRegistryExtensionVersion, &extension_version))
return NULL;
if (location)
*location = Extension::EXTERNAL_REGISTRY;
return Version::GetVersionFromString(extension_version);
}
<|endoftext|> |
<commit_before>#ifndef ALEPH_PERSISTENT_HOMOLOGY_CONNECTED_COMPONENTS_HH__
#define ALEPH_PERSISTENT_HOMOLOGY_CONNECTED_COMPONENTS_HH__
#include "persistenceDiagrams/PersistenceDiagram.hh"
#include "topology/SimplicialComplex.hh"
#include "topology/UnionFind.hh"
#include <algorithm>
#include <vector>
namespace aleph
{
/**
Calculates zero-dimensional persistent homology, i.e. tracking of connected
components, for a given simplicial complex. This is highly-efficient, as it
only requires a suitable 'Union--Find' data structure.
As usual, the function assumes that the simplicial complex is in filtration
order, meaning that faces are preceded by their cofaces. The function won't
check this, though!
*/
template <class Simplex> PersistenceDiagram<typename Simplex::DataType> calculateZeroDimensionalPersistenceDiagram( const topology::SimplicialComplex<Simplex>& K )
{
using DataType = typename Simplex::DataType;
using VertexType = typename Simplex::VertexType;
using namespace topology;
// Extract {0,1}-simplices -----------------------------------------
//
// Note that there is a range predicate for the simplicial complex class that
// does essentially the same thing. However, the results of the query must be
// consistent with respect to the filtration order.
std::vector<Simplex> simplices;
std::copy_if( K.begin(), K.end(),
std::back_inserter( simplices ),
[] ( const Simplex& s ) { return s.dimension() <= 1; } );
SimplicialComplex<Simplex> S
= SimplicialComplex<Simplex>( simplices.begin(), simplices.end() );
std::vector<Simplex> vertices;
std::copy_if( simplices.begin(), simplices.end() ,
std::back_inserter( vertices ),
[] ( const Simplex& s ) { return s.dimension() == 0; } );
UnionFind<Simplex> uf( vertices.begin(), vertices.end() );
PersistenceDiagram<DataType> pd;
for( auto&& simplex : S )
{
// Only edges can destroy a component
if( simplex.dimension() == 1 )
{
// Prepare component destruction -------------------------------
VertexType u = *( simplex.begin() );
VertexType v = *( simplex.begin() + 1 );
auto youngerComponent = uf.find( u );
auto olderComponent = uf.find( v );
// If the component has already been merged by some other edge, we are
// not interested in it any longer.
if( youngerComponent == olderComponent )
continue;
// Ensures that the younger component is always the first component. A
// component is younger if it its parent vertex precedes the other one
// in the current filtration.
{
auto uIndex = S.index( youngerComponent );
auto vIndex = S.index( olderComponent );
// The younger component must have the _larger_ index as it is born
// _later_ in the filtration.
if( uIndex < vIndex )
std::swap( youngerComponent, olderComponent );
}
auto creation = youngerComponent.data();
auto destruction = simplex.data();
uf.merge( youngerComponent, olderComponent );
pd.add( creation, destruction );
}
}
// Store information about unpaired simplices ----------------------
//
// All components in the Union--Find data structure now correspond to
// essential 0-dimensional homology classes of the input complex.
std::vector<Simplex> roots;
uf.roots( std::back_inserter( roots ) );
for( auto&& root : roots )
pd.add( root.data() );
// TODO: Return Union--Find data structure as well?
return pd;
}
} // namespace aleph
#endif
<commit_msg>Rewrote calculation of connected components<commit_after>#ifndef ALEPH_PERSISTENT_HOMOLOGY_CONNECTED_COMPONENTS_HH__
#define ALEPH_PERSISTENT_HOMOLOGY_CONNECTED_COMPONENTS_HH__
#include "persistenceDiagrams/PersistenceDiagram.hh"
#include "topology/SimplicialComplex.hh"
#include "topology/UnionFind.hh"
#include <algorithm>
#include <vector>
namespace aleph
{
/**
Calculates zero-dimensional persistent homology, i.e. tracking of connected
components, for a given simplicial complex. This is highly-efficient, as it
only requires a suitable 'Union--Find' data structure.
As usual, the function assumes that the simplicial complex is in filtration
order, meaning that faces are preceded by their cofaces. The function won't
check this, though!
*/
template <class Simplex> PersistenceDiagram<typename Simplex::DataType> calculateZeroDimensionalPersistenceDiagram( const topology::SimplicialComplex<Simplex>& K )
{
using DataType = typename Simplex::DataType;
using VertexType = typename Simplex::VertexType;
using namespace topology;
// Extract {0,1}-simplices -----------------------------------------
//
// Note that there is a range predicate for the simplicial complex class that
// does essentially the same thing. However, the results of the query must be
// consistent with respect to the filtration order.
std::vector<Simplex> simplices;
std::copy_if( K.begin(), K.end(),
std::back_inserter( simplices ),
[] ( const Simplex& s ) { return s.dimension() <= 1; } );
SimplicialComplex<Simplex> S
= SimplicialComplex<Simplex>( simplices.begin(), simplices.end() );
std::vector<VertexType> vertices;
for( auto&& s : simplices )
{
if( s.dimension() == 0 )
vertices.push_back( *s.begin() );
}
UnionFind<VertexType> uf( vertices.begin(), vertices.end() );
PersistenceDiagram<DataType> pd;
for( auto&& simplex : S )
{
// Only edges can destroy a component
if( simplex.dimension() == 1 )
{
// Prepare component destruction -------------------------------
VertexType u = *( simplex.begin() );
VertexType v = *( simplex.begin() + 1 );
auto youngerComponent = uf.find( u );
auto olderComponent = uf.find( v );
// If the component has already been merged by some other edge, we are
// not interested in it any longer.
if( youngerComponent == olderComponent )
continue;
// Ensures that the younger component is always the first component. A
// component is younger if it its parent vertex precedes the other one
// in the current filtration.
auto uIndex = S.index( Simplex( youngerComponent ) );
auto vIndex = S.index( Simplex( olderComponent ) );
// The younger component must have the _larger_ index as it is born
// _later_ in the filtration.
if( uIndex < vIndex )
std::swap( youngerComponent, olderComponent );
auto creation = S[uIndex].data();
auto destruction = simplex.data();
uf.merge( youngerComponent, olderComponent );
pd.add( creation, destruction );
}
}
// Store information about unpaired simplices ----------------------
//
// All components in the Union--Find data structure now correspond to
// essential 0-dimensional homology classes of the input complex.
std::vector<VertexType> roots;
uf.roots( std::back_inserter( roots ) );
for( auto&& root : roots )
{
auto creator = *S.find( Simplex( root ) );
pd.add( creator.data() );
}
// TODO: Return Union--Find data structure as well?
return pd;
}
} // namespace aleph
#endif
<|endoftext|> |
<commit_before>#include "utils.hpp"
#include <cstring>
#include <boost/filesystem.hpp>
namespace bf = boost::filesystem;
static std::string makepath(bf::path, RdbAttrs);
// Get the key for the given path.
static bool getkey(const bf::path&, std::string&);
static bf::path keyfile(const std::string&);
static void touch(const bf::path&);
std::string pathfor(const char *root, RdbAttrs keys) {
bool used[keys.size()];
memset(used, 0, sizeof(*used) * keys.size());
bf::path path(root);
std::string curkey;
while (keys.size() > 0) {
if (bf::exists(path)) {
if (!bf::is_directory(path))
fatal("%s is not a directory\n", path.string().c_str());
if (!getkey(path, curkey))
return makepath(path.string().c_str(), keys);
path /= keys[curkey];
keys.erase(curkey);
} else {
return makepath(path.string().c_str(), keys);
}
}
return path.string();
}
static std::string makepath(bf::path root, RdbAttrs keys) {
if (!bf::exists(root) && keys.size() > 1)
bf::create_directory(root);
while (keys.size() > 0) {
const std::string &key = keys.begin()->first;
const std::string &vl = keys.begin()->second;
touch(root / keyfile(key));
keys.erase(key);
root /= vl;
if (keys.size() > 0)
bf::create_directory(vl);
}
return root.string();
}
static bool getkey(const bf::path &p, std::string &key) {
for (bf::directory_iterator it(p); it != bf::directory_iterator(); it++) {
const char *fname = it->string().c_str();
if (strstr(fname, "KEY=") == fname) {
key = fname + strlen("KEY=");
return true;
}
}
return false;
}
static bf::path keyfile(const std::string &key) {
return bf::path(std::string("KEY=") + key);
}
static void touch(const bf::path &p) {
FILE *touch = fopen(p.string().c_str(), "w");
if (!touch)
fatalx(errno, "Failed to touch keyfile %s\n", p.string().c_str());
fclose(touch);
}<commit_msg>rdb: handle unspecified keys.<commit_after>#include "utils.hpp"
#include <cstring>
#include <boost/filesystem.hpp>
namespace bf = boost::filesystem;
static std::string makepath(bf::path, RdbAttrs);
// Get the key for the given path.
static bool getkey(const bf::path&, std::string&);
static bf::path keyfile(const std::string&);
static void touch(const bf::path&);
std::string pathfor(const char *root, RdbAttrs keys) {
bf::path path(root);
std::string curkey;
while (keys.size() > 0) {
if (bf::exists(path)) {
if (!bf::is_directory(path) && keys.size() > 0)
fatal("%s is not a directory\n", path.string().c_str());
if (!getkey(path, curkey))
return makepath(path.string().c_str(), keys);
RdbAttrs::iterator it = keys.find(curkey);
if (it == keys.end()) {
path /= "UNSPECIFIED";
} else {
path /= it->second;
keys.erase(it);
}
} else {
return makepath(path.string().c_str(), keys);
}
}
return path.string();
}
static std::string makepath(bf::path root, RdbAttrs keys) {
if (!bf::exists(root) && keys.size() > 1)
bf::create_directory(root);
while (keys.size() > 0) {
const std::string &key = keys.begin()->first;
const std::string &vl = keys.begin()->second;
touch(root / keyfile(key));
keys.erase(key);
root /= vl;
if (keys.size() > 0)
bf::create_directory(vl);
}
return root.string();
}
static bool getkey(const bf::path &p, std::string &key) {
for (bf::directory_iterator it(p); it != bf::directory_iterator(); it++) {
const char *fname = it->string().c_str();
if (strstr(fname, "KEY=") == fname) {
key = fname + strlen("KEY=");
return true;
}
}
return false;
}
static bf::path keyfile(const std::string &key) {
return bf::path(std::string("KEY=") + key);
}
static void touch(const bf::path &p) {
FILE *touch = fopen(p.string().c_str(), "w");
if (!touch)
fatalx(errno, "Failed to touch keyfile %s\n", p.string().c_str());
fclose(touch);
}<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <stdint.h>
#include <math.h>
#include <cv_bridge/cv_bridge.h>
#include <nav_msgs/GetMap.h>
#include <nav_msgs/OccupancyGrid.h>
#include <quirkd/Alert.h>
#include <sensor_msgs/LaserScan.h>
#include <tf/transform_listener.h>
#include <tf/transform_datatypes.h>
class DataController {
public:
DataController() {
alert_pub_ = n_.advertise<quirkd::Alert>("/quirkd/alert/notification", 1);
laser_sub_ = n_.subscribe("/base_scan", 1, &DataController::laserScanCB, this);
// ros::service::waitForService("static_map");
static_map_client_ = n_.serviceClient<nav_msgs::GetMap>("static_map");
// ros::service::waitForService("dynamic_map");
dynamic_map_client_ = n_.serviceClient<nav_msgs::GetMap>("dynamic_map");
}
void laserScanCB(const sensor_msgs::LaserScan msg) {
ROS_INFO("Laser Scan Callback");
updated = true;
last_data = msg;
try {
tf_.lookupTransform("/map", "/base_laser_link", ros::Time(0), last_tf);
ROS_INFO("tf success for /map to /base_laser_link");
} catch (tf::TransformException &ex) {
ROS_WARN("tf fetch failed. %s", ex.what());
}
}
void update() {
ROS_INFO("Update Data Processor");
nav_msgs::GetMap srv;
cv_bridge::CvImagePtr static_image;
cv_bridge::CvImagePtr dynamic_image;
if (static_map_client_.call(srv)) {
ROS_INFO("Successfull call static map");
nav_msgs::OccupancyGrid og = srv.response.map;
static_image = this -> gridToCvImage(&og);
} else {
ROS_WARN("Failed to get static map");
}
if (dynamic_map_client_.call(srv)) {
ROS_INFO("Successfull call dynamic map");
nav_msgs::OccupancyGrid og = srv.response.map;
dynamic_image = this -> gridToCvImage(&og);
} else {
ROS_WARN("Failed to get dynamic map");
}
updated = false;
}
void pub_alert_status() {
quirkd::Alert alert;
alert.level = 0;
alert.min_x = 0;
alert.max_x = 1;
alert.min_y = 0;
alert.max_y = 1;
updateAlertPerimeter(&alert, last_data, last_tf);
alert_pub_.publish(alert);
}
bool updated;
sensor_msgs::LaserScan last_data;
tf::StampedTransform last_tf;
private:
ros::NodeHandle n_;
ros::Publisher alert_pub_;
ros::Subscriber laser_sub_;
ros::ServiceClient dynamic_map_client_;
ros::ServiceClient static_map_client_;
tf::TransformListener tf_;
void updateAlertPerimeter(quirkd::Alert* alert, const sensor_msgs::LaserScan scan, const tf::StampedTransform tf) {
double base_x = tf.getOrigin().x();
double base_y = tf.getOrigin().y();
double r, p, base_heading;
tf::Matrix3x3 m(tf.getRotation());
m.getRPY(r, p, base_heading);
double scan_min = base_heading + scan.angle_min;
double scan_inc = scan.angle_increment;
double heading = scan_min;
alert->min_x = base_x;
alert->max_x = base_x;
alert->min_y = base_y;
alert->max_y = base_y;
double live_x, live_y;
for (int i = 0; i < scan.ranges.size(); i++) {
double dist = scan.ranges[i];
live_x = dist * sin(heading);
live_y = dist * cos(heading);
alert->min_x = std::min(live_x, double(alert->min_x));
alert->max_x = std::max(live_x, double(alert->max_x));
alert->min_y = std::min(live_y, double(alert->min_y));
alert->max_y = std::max(live_y, double(alert->max_y));
heading += scan_inc;
}
}
cv_bridge::CvImagePtr gridToCvImage(nav_msgs::OccupancyGrid* grid) {
// Unpack the Occupancy Grid
nav_msgs::MapMetaData info = grid -> info;
float resolution = info.resolution;
int cell_width = info.width;
float map_width = cell_width * resolution;
int cell_height = info.height;
float map_height = cell_height * resolution;
// I'm assuming the map isn't rotated right now because that could be really complex
float origin_x = info.origin.position.x;
float origin_y = info.origin.position.x;
/*
* From documentation:
* The map data in row major order, starting at 0,0.
* Valid values are in the range [0, 100]
*/
std::vector<int8_t> data = grid -> data;
std::vector<uint8_t> unsigned_data;
unsigned_data.resize(data.size()); // allocate and fill vector to match num elements of data
for (std::vector<int8_t>::size_type i = 0; i < data.size(); i++) {
int8_t old_int = data[i];
// assume unknown values (signed -1) are just 0
// assumption is that unseen parts of the map have no obstacles until proven otherwise
uint8_t new_int = (uint8_t)((old_int == -1) ? 0 : old_int);
unsigned_data[(std::vector<uint8_t>::size_type) i] = new_int;
}
// Create the ROS Image Message
sensor_msgs::Image converted_image;
converted_image.width = cell_width;
converted_image.height = cell_height;
converted_image.encoding = sensor_msgs::image_encodings::MONO8;
converted_image.step = cell_width;
converted_image.data = unsigned_data;
// TODO use CV Bridge to get the CvImagePtr
cv_bridge::CvImagePtr cv_ptr;
try {
cv_ptr = cv_bridge::toCvCopy(converted_image, sensor_msgs::image_encodings::MONO8);
} catch (cv_bridge::Exception& e) {
ROS_ERROR("cv_bridge exception: %s", e.what());
}
return cv_ptr;
}
};
int main(int argc, char** argv) {
ros::init(argc, argv, "DataController");
ROS_INFO("1");
DataController dp;
ROS_INFO("2");
dp.updated = false;
ROS_INFO("3");
ros::Rate r(30);
ROS_INFO("4");
dp.update();
while(ros::ok()) {
ros::spinOnce();
if (dp.updated) {
dp.update();
ROS_INFO("Processed message data in loop");
}
dp.pub_alert_status();
r.sleep();
}
ROS_INFO("Data Processor Exited.");
return 0;
}
<commit_msg>The conversion to an image is working<commit_after>#include <ros/ros.h>
#include <math.h>
#include <stdint.h>
#include <stdbool.h>
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <nav_msgs/GetMap.h>
#include <nav_msgs/OccupancyGrid.h>
#include <opencv2/highgui/highgui.hpp>
#include <quirkd/Alert.h>
#include <sensor_msgs/LaserScan.h>
#include <sensor_msgs/image_encodings.h>
#include <tf/transform_listener.h>
#include <tf/transform_datatypes.h>
class DataController {
public:
DataController()
: it_(n_)
{
alert_pub_ = n_.advertise<quirkd::Alert>("/quirkd/alert/notification", 1);
laser_sub_ = n_.subscribe("/base_scan", 1, &DataController::laserScanCB, this);
// ros::service::waitForService("static_map");
static_map_client_ = n_.serviceClient<nav_msgs::GetMap>("static_map");
// ros::service::waitForService("dynamic_map");
dynamic_map_client_ = n_.serviceClient<nav_msgs::GetMap>("dynamic_map");
image_pub_ = it_.advertise("/quirkd/test/static_image", 1);
}
void laserScanCB(const sensor_msgs::LaserScan msg) {
ROS_INFO("Laser Scan Callback");
updated = true;
last_data = msg;
try {
tf_.lookupTransform("/map", "/base_laser_link", ros::Time(0), last_tf);
ROS_INFO("tf success for /map to /base_laser_link");
} catch (tf::TransformException &ex) {
ROS_WARN("tf fetch failed. %s", ex.what());
}
}
void update() {
ROS_INFO("Update Data Processor");
nav_msgs::GetMap srv;
cv_bridge::CvImagePtr static_image;
cv_bridge::CvImagePtr dynamic_image;
if (static_map_client_.call(srv)) {
ROS_INFO("Successfull call static map");
nav_msgs::OccupancyGrid og = srv.response.map;
static_image = this -> gridToCvImage(&og);
// For testing
if (static_image -> image.rows > 60 && static_image -> image.cols>60) {
cv::circle(static_image -> image, cv::Point(50,50), 10, CV_RGB(100,100,100), -1);
}
ROS_INFO("Publish static image window");
image_pub_.publish(static_image->toImageMsg());
} else {
ROS_WARN("Failed to get static map");
}
if (dynamic_map_client_.call(srv)) {
ROS_INFO("Successfull call dynamic map");
nav_msgs::OccupancyGrid og = srv.response.map;
dynamic_image = this -> gridToCvImage(&og);
} else {
ROS_WARN("Failed to get dynamic map");
}
updated = false;
}
void pub_alert_status() {
quirkd::Alert alert;
alert.level = 0;
alert.min_x = 0;
alert.max_x = 1;
alert.min_y = 0;
alert.max_y = 1;
updateAlertPerimeter(&alert, last_data, last_tf);
alert_pub_.publish(alert);
}
bool updated;
sensor_msgs::LaserScan last_data;
tf::StampedTransform last_tf;
private:
ros::NodeHandle n_;
image_transport::ImageTransport it_;
image_transport::Publisher image_pub_;
ros::Publisher alert_pub_;
ros::Subscriber laser_sub_;
ros::ServiceClient dynamic_map_client_;
ros::ServiceClient static_map_client_;
tf::TransformListener tf_;
void updateAlertPerimeter(quirkd::Alert* alert, const sensor_msgs::LaserScan scan, const tf::StampedTransform tf) {
double base_x = tf.getOrigin().x();
double base_y = tf.getOrigin().y();
double r, p, base_heading;
tf::Matrix3x3 m(tf.getRotation());
m.getRPY(r, p, base_heading);
double scan_min = base_heading + scan.angle_min;
double scan_inc = scan.angle_increment;
double heading = scan_min;
alert->min_x = base_x;
alert->max_x = base_x;
alert->min_y = base_y;
alert->max_y = base_y;
double live_x, live_y;
for (int i = 0; i < scan.ranges.size(); i++) {
double dist = scan.ranges[i];
live_x = dist * sin(heading);
live_y = dist * cos(heading);
alert->min_x = std::min(live_x, double(alert->min_x));
alert->max_x = std::max(live_x, double(alert->max_x));
alert->min_y = std::min(live_y, double(alert->min_y));
alert->max_y = std::max(live_y, double(alert->max_y));
heading += scan_inc;
}
}
cv_bridge::CvImagePtr gridToCvImage(nav_msgs::OccupancyGrid* grid) {
// Unpack the Occupancy Grid
nav_msgs::MapMetaData info = grid -> info;
float resolution = info.resolution;
int cell_width = info.width;
float map_width = cell_width * resolution;
int cell_height = info.height;
float map_height = cell_height * resolution;
// I'm assuming the map isn't rotated right now because that could be really complex
float origin_x = info.origin.position.x;
float origin_y = info.origin.position.x;
/*
* From documentation:
* The map data in row major order, starting at 0,0.
* Valid values are in the range [0, 100]
*/
std::vector<int8_t> data = grid -> data;
std::vector<uint8_t> unsigned_data;
unsigned_data.resize(data.size()); // allocate and fill vector to match num elements of data
for (std::vector<int8_t>::size_type i = 0; i < data.size(); i++) {
int8_t old_int = data[i];
// assume unknown values (signed -1) are just 0
// assumption is that unseen parts of the map have no obstacles until proven otherwise
uint8_t new_int = (uint8_t)((old_int == -1) ? 0 : old_int);
unsigned_data[(std::vector<uint8_t>::size_type) i] = new_int;
}
// Create the ROS Image Message
sensor_msgs::Image converted_image;
converted_image.width = cell_width;
converted_image.height = cell_height;
converted_image.encoding = sensor_msgs::image_encodings::MONO8;
converted_image.step = cell_width;
converted_image.data = unsigned_data;
// TODO use CV Bridge to get the CvImagePtr
cv_bridge::CvImagePtr cv_ptr;
try {
cv_ptr = cv_bridge::toCvCopy(converted_image, sensor_msgs::image_encodings::MONO8);
} catch (cv_bridge::Exception& e) {
ROS_ERROR("cv_bridge exception: %s", e.what());
}
return cv_ptr;
}
};
int main(int argc, char** argv) {
ros::init(argc, argv, "DataController");
ROS_INFO("1");
DataController dp;
ROS_INFO("2");
dp.updated = false;
ROS_INFO("3");
ros::Rate r(30);
ROS_INFO("4");
dp.update();
while(ros::ok()) {
ros::spinOnce();
if (dp.updated || true) {
dp.update();
ROS_INFO("Processed message data in loop");
}
dp.pub_alert_status();
r.sleep();
}
ROS_INFO("Data Processor Exited.");
return 0;
}
<|endoftext|> |
<commit_before>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2014--2016
John Harvey 2014 (DS18B20 code)
Deniz Erbilgin 2015--2016
*/
/*
* Header for common on-board and external sensors and actuators for V0p2 variants.
*/
#include <stdint.h>
#include <limits.h>
#include <util/atomic.h>
#include <Wire.h> // Arduino I2C library.
#include <OTV0p2Base.h>
#include "V0p2_Main.h"
#include "V0p2_Board_IO_Config.h" // I/O pin allocation: include ahead of I/O module headers.
#include "V0p2_Sensors.h" // I/O code access.
#include "Control.h"
#include "UI_Minimal.h"
// Sensor for supply (eg battery) voltage in millivolts.
// Singleton implementation/instance.
OTV0P2BASE::SupplyVoltageCentiVolts Supply_cV;
#ifdef TEMP_POT_AVAILABLE
// Singleton implementation/instance.
#if defined(TEMP_POT_REVERSE)
OTV0P2BASE::SensorTemperaturePot TempPot(OTV0P2BASE::SensorTemperaturePot::TEMP_POT_RAW_MAX, 0);
#else
OTV0P2BASE::SensorTemperaturePot TempPot(0, OTV0P2BASE::SensorTemperaturePot::TEMP_POT_RAW_MAX);
#endif // defined(TEMP_POT_REVERSE)
#endif
#ifdef ENABLE_AMBLIGHT_SENSOR
// Normal 2 bit shift between raw and externally-presented values.
static const uint8_t shiftRawScaleTo8Bit = 2;
#ifdef AMBIENT_LIGHT_SENSOR_PHOTOTRANS_TEPT4400
// This implementation expects a phototransitor TEPT4400 (50nA dark current, nominal 200uA@100lx@Vce=50V) from IO_POWER_UP to LDR_SENSOR_AIN and 220k to ground.
// Measurement should be taken wrt to internal fixed 1.1V bandgap reference, since light indication is current flow across a fixed resistor.
// Aiming for maximum reading at or above 100--300lx, ie decent domestic internal lighting.
// Note that phototransistor is likely far more directionally-sensitive than LDR and its response nearly linear.
// This extends the dynamic range and switches to measurement vs supply when full-scale against bandgap ref, then scales by Vss/Vbandgap and compresses to fit.
// http://home.wlv.ac.uk/~in6840/Lightinglevels.htm
// http://www.engineeringtoolbox.com/light-level-rooms-d_708.html
// http://www.pocklington-trust.org.uk/Resources/Thomas%20Pocklington/Documents/PDF/Research%20Publications/GPG5.pdf
// http://www.vishay.com/docs/84154/appnotesensors.pdf
#if (7 == V0p2_REV) // REV7 initial board run especially uses different phototransistor (not TEPT4400).
// Note that some REV7s from initial batch were fitted with wrong device entirely,
// an IR device, with very low effective sensitivity (FSD ~ 20 rather than 1023).
static const int LDR_THR_LOW = 180U;
static const int LDR_THR_HIGH = 250U;
#else // REV4 default values.
static const int LDR_THR_LOW = 270U;
static const int LDR_THR_HIGH = 400U;
#endif
#else // LDR (!defined(AMBIENT_LIGHT_SENSOR_PHOTOTRANS_TEPT4400))
// This implementation expects an LDR (1M dark resistance) from IO_POWER_UP to LDR_SENSOR_AIN and 100k to ground.
// Measurement should be taken wrt to supply voltage, since light indication is a fraction of that.
// Values below from PICAXE V0.09 impl approx multiplied by 4+ to allow for scale change.
#ifdef ENABLE_AMBLIGHT_EXTRA_SENSITIVE // Define if LDR not exposed to much light, eg for REV2 cut4 sideways-pointing LDR (TODO-209).
static const int LDR_THR_LOW = 50U;
static const int LDR_THR_HIGH = 70U;
#else // Normal settings.
static const int LDR_THR_LOW = 160U; // Was 30.
static const int LDR_THR_HIGH = 200U; // Was 35.
#endif // ENABLE_AMBLIGHT_EXTRA_SENSITIVE
#endif // AMBIENT_LIGHT_SENSOR_PHOTOTRANS_TEPT4400
// Singleton implementation/instance.
AmbientLight AmbLight(LDR_THR_HIGH >> shiftRawScaleTo8Bit);
#endif // ENABLE_AMBLIGHT_SENSOR
#if defined(ENABLE_MINIMAL_ONEWIRE_SUPPORT)
OTV0P2BASE::MinimalOneWire<> MinOW_DEFAULT;
#endif
#if defined(SENSOR_EXTERNAL_DS18B20_ENABLE_0) // Enable sensor zero.
OTV0P2BASE::TemperatureC16_DS18B20 extDS18B20_0(MinOW_DEFAULT, 0);
#endif
#if defined(ENABLE_PRIMARY_TEMP_SENSOR_SHT21)
// Singleton implementation/instance.
OTV0P2BASE::HumiditySensorSHT21 RelHumidity;
#else
OTV0P2BASE::DummyHumiditySensorSHT21 RelHumidity;
#endif
// Ambient/room temperature sensor, usually on main board.
#if defined(ENABLE_PRIMARY_TEMP_SENSOR_SHT21)
OTV0P2BASE::RoomTemperatureC16_SHT21 TemperatureC16; // SHT21 impl.
#elif defined(ENABLE_PRIMARY_TEMP_SENSOR_DS18B20)
#if defined(ENABLE_MINIMAL_ONEWIRE_SUPPORT)
// DSB18B20 temperature impl, with slightly reduced precision to improve speed.
OTV0P2BASE::TemperatureC16_DS18B20 TemperatureC16(MinOW_DEFAULT, 0, OTV0P2BASE::TemperatureC16_DS18B20::MAX_PRECISION - 1);
#endif
#else // Don't use TMP112 if SHT21 or DS18B20 are selected.
OTV0P2BASE::RoomTemperatureC16_TMP112 TemperatureC16;
#endif
#ifdef ENABLE_VOICE_SENSOR
// If count meets or exceeds this threshold in one poll period then
// the room is deemed to be occupied.
// Strictly positive.
// DHD20151119: even now it seems a threshold of >= 2 is needed to avoid false positives.
#define VOICE_DETECTION_THRESHOLD 4
// Force a read/poll of the voice level and return the value sensed.
// Thread-safe and ISR-safe.
uint8_t VoiceDetection::read()
{
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
isDetected = ((value = count) >= VOICE_DETECTION_THRESHOLD);
// clear count and detection flag
// isTriggered = false;
count = 0;
}
return(value);
}
// Handle simple interrupt.
// Fast and ISR (Interrupt Service Routines) safe.
// Returns true if interrupt was successfully handled and cleared
// else another interrupt handler in the chain may be called
// to attempt to clear the interrupt.
bool VoiceDetection::handleInterruptSimple()
{
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
// Count of voice activations since last poll, avoiding overflow.
if ((count < 255) && (++count >= VOICE_DETECTION_THRESHOLD))
{
// Act as soon as voice is detected.
isDetected = true;
// Don't regard this as a very strong indication,
// as it could be a TV or radio on in the room.
Occupancy.markAsPossiblyOccupied();
}
}
// // Flag that interrupt has occurred
// endOfLocking = OTV0P2BASE::getMinutesSinceMidnightLT() + lockingPeriod;
// isTriggered = true;
// No further work to be done to 'clear' interrupt.
return (true);
}
// Singleton implementation/instance.
VoiceDetection Voice;
#endif
////////////////////////// Actuators
// DORM1/REV7 direct drive actuator.
#ifdef HAS_DORM1_VALVE_DRIVE
//#ifdef DIRECT_MOTOR_DRIVE_V1
// Singleton implementation/instance.
#ifdef ENABLE_DORM1_MOTOR_REVERSED // Reversed vs sample 2015/12
OTRadValve::ValveMotorDirectV1<MOTOR_DRIVE_ML, MOTOR_DRIVE_MR, MOTOR_DRIVE_MI_AIN, MOTOR_DRIVE_MC_AIN> ValveDirect;
#else
OTRadValve::ValveMotorDirectV1<MOTOR_DRIVE_MR, MOTOR_DRIVE_ML, MOTOR_DRIVE_MI_AIN, MOTOR_DRIVE_MC_AIN> ValveDirect;
#endif // HAS_DORM1_MOTOR_REVERSED
#endif
// FHT8V radio-controlled actuator.
#ifdef ENABLE_FHT8VSIMPLE
// Function to append stats trailer (and 0xff) to FHT8V/FS20 TX buffer.
// Assume enough space in buffer for largest possible stats message.
#if defined(ALLOW_STATS_TX)
uint8_t *appendStatsToTXBufferWithFF(uint8_t *bptr, const uint8_t bufSize)
{
OTV0P2BASE::FullStatsMessageCore_t trailer;
populateCoreStats(&trailer);
// Ensure that no ID is encoded in the message sent on the air since it would be a repeat from the FHT8V frame.
trailer.containsID = false;
#if defined(ENABLE_MINIMAL_STATS_TXRX)
// As bandwidth optimisation just write minimal trailer if only temp&power available.
if (trailer.containsTempAndPower &&
!trailer.containsID && !trailer.containsAmbL)
{
writeTrailingMinimalStatsPayload(bptr, &(trailer.tempAndPower));
bptr += 3;
*bptr = (uint8_t)0xff; // Terminate TX bytes.
}
else
#endif
{
// Assume enough space in buffer for largest possible stats message.
bptr = encodeFullStatsMessageCore(bptr, bufSize, OTV0P2BASE::getStatsTXLevel(), false, &trailer);
}
return (bptr);
}
#else
#define appendStatsToTXBufferWithFF NULL // Do not append stats.
#endif
#endif // ENABLE_FHT8VSIMPLE
#ifdef ENABLE_FHT8VSIMPLE
OTRadValve::FHT8VRadValve<_FHT8V_MAX_EXTRA_TRAILER_BYTES, OTRadValve::FHT8VRadValveBase::RFM23_PREAMBLE_BYTES, OTRadValve::FHT8VRadValveBase::RFM23_PREAMBLE_BYTE> FHT8V(appendStatsToTXBufferWithFF);
#endif
// Clear both housecode parts (and thus disable local valve).
// Does nothing if FHT8V not in use.
#ifdef ENABLE_FHT8VSIMPLE
void FHT8VClearHC()
{
FHT8V.clearHC();
OTV0P2BASE::eeprom_smart_erase_byte((uint8_t*)V0P2BASE_EE_START_FHT8V_HC1);
OTV0P2BASE::eeprom_smart_erase_byte((uint8_t*)V0P2BASE_EE_START_FHT8V_HC2);
}
#endif
// Set (non-volatile) HC1 and HC2 for single/primary FHT8V wireless valve under control.
// Also set value in FHT8V rad valve model.
// Does nothing if FHT8V not in use.
#ifdef ENABLE_FHT8VSIMPLE
void FHT8VSetHC1(uint8_t hc)
{
FHT8V.setHC1(hc);
OTV0P2BASE::eeprom_smart_update_byte((uint8_t*)V0P2BASE_EE_START_FHT8V_HC1, hc);
}
void FHT8VSetHC2(uint8_t hc)
{
FHT8V.setHC2(hc);
OTV0P2BASE::eeprom_smart_update_byte((uint8_t*)V0P2BASE_EE_START_FHT8V_HC2, hc);
}
#endif
// Get (non-volatile) HC1 and HC2 for single/primary FHT8V wireless valve under control (will be 0xff until set).
// FHT8V instance values are used as a cache.
// Does nothing if FHT8V not in use.
#ifdef ENABLE_FHT8VSIMPLE
uint8_t FHT8VGetHC1()
{
const uint8_t vv = FHT8V.getHC1();
// If cached value in FHT8V instance is valid, return it.
if (OTRadValve::FHT8VRadValveBase::isValidFHTV8HouseCode(vv))
{
return (vv);
}
// Else if EEPROM value is valid, then cache it in the FHT8V instance and return it.
const uint8_t ev = eeprom_read_byte((uint8_t*)V0P2BASE_EE_START_FHT8V_HC1);
if (OTRadValve::FHT8VRadValveBase::isValidFHTV8HouseCode(ev))
{
FHT8V.setHC1(ev);
}
return (ev);
}
uint8_t FHT8VGetHC2()
{
const uint8_t vv = FHT8V.getHC2();
// If cached value in FHT8V instance is valid, return it.
if (OTRadValve::FHT8VRadValveBase::isValidFHTV8HouseCode(vv))
{
return (vv);
}
// Else if EEPROM value is valid, then cache it in the FHT8V instance and return it.
const uint8_t ev = eeprom_read_byte((uint8_t*)V0P2BASE_EE_START_FHT8V_HC2);
if (OTRadValve::FHT8VRadValveBase::isValidFHTV8HouseCode(ev))
{
FHT8V.setHC2(ev);
}
return (ev);
}
#endif // ENABLE_FHT8VSIMPLE
#ifdef ENABLE_FHT8VSIMPLE
// Load EEPROM house codes into primary FHT8V instance at start-up or once cleared in FHT8V instance.
void FHT8VLoadHCFromEEPROM()
{
// Uses side-effect to cache/save in FHT8V instance.
FHT8VGetHC1();
FHT8VGetHC2();
}
#endif // ENABLE_FHT8VSIMPLE
<commit_msg>lowered threshold to get something out of new QM-1s<commit_after>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2014--2016
John Harvey 2014 (DS18B20 code)
Deniz Erbilgin 2015--2016
*/
/*
* Header for common on-board and external sensors and actuators for V0p2 variants.
*/
#include <stdint.h>
#include <limits.h>
#include <util/atomic.h>
#include <Wire.h> // Arduino I2C library.
#include <OTV0p2Base.h>
#include "V0p2_Main.h"
#include "V0p2_Board_IO_Config.h" // I/O pin allocation: include ahead of I/O module headers.
#include "V0p2_Sensors.h" // I/O code access.
#include "Control.h"
#include "UI_Minimal.h"
// Sensor for supply (eg battery) voltage in millivolts.
// Singleton implementation/instance.
OTV0P2BASE::SupplyVoltageCentiVolts Supply_cV;
#ifdef TEMP_POT_AVAILABLE
// Singleton implementation/instance.
#if defined(TEMP_POT_REVERSE)
OTV0P2BASE::SensorTemperaturePot TempPot(OTV0P2BASE::SensorTemperaturePot::TEMP_POT_RAW_MAX, 0);
#else
OTV0P2BASE::SensorTemperaturePot TempPot(0, OTV0P2BASE::SensorTemperaturePot::TEMP_POT_RAW_MAX);
#endif // defined(TEMP_POT_REVERSE)
#endif
#ifdef ENABLE_AMBLIGHT_SENSOR
// Normal 2 bit shift between raw and externally-presented values.
static const uint8_t shiftRawScaleTo8Bit = 2;
#ifdef AMBIENT_LIGHT_SENSOR_PHOTOTRANS_TEPT4400
// This implementation expects a phototransitor TEPT4400 (50nA dark current, nominal 200uA@100lx@Vce=50V) from IO_POWER_UP to LDR_SENSOR_AIN and 220k to ground.
// Measurement should be taken wrt to internal fixed 1.1V bandgap reference, since light indication is current flow across a fixed resistor.
// Aiming for maximum reading at or above 100--300lx, ie decent domestic internal lighting.
// Note that phototransistor is likely far more directionally-sensitive than LDR and its response nearly linear.
// This extends the dynamic range and switches to measurement vs supply when full-scale against bandgap ref, then scales by Vss/Vbandgap and compresses to fit.
// http://home.wlv.ac.uk/~in6840/Lightinglevels.htm
// http://www.engineeringtoolbox.com/light-level-rooms-d_708.html
// http://www.pocklington-trust.org.uk/Resources/Thomas%20Pocklington/Documents/PDF/Research%20Publications/GPG5.pdf
// http://www.vishay.com/docs/84154/appnotesensors.pdf
#if (7 == V0p2_REV) // REV7 initial board run especially uses different phototransistor (not TEPT4400).
// Note that some REV7s from initial batch were fitted with wrong device entirely,
// an IR device, with very low effective sensitivity (FSD ~ 20 rather than 1023).
static const int LDR_THR_LOW = 180U;
static const int LDR_THR_HIGH = 250U;
#else // REV4 default values.
static const int LDR_THR_LOW = 270U;
static const int LDR_THR_HIGH = 400U;
#endif
#else // LDR (!defined(AMBIENT_LIGHT_SENSOR_PHOTOTRANS_TEPT4400))
// This implementation expects an LDR (1M dark resistance) from IO_POWER_UP to LDR_SENSOR_AIN and 100k to ground.
// Measurement should be taken wrt to supply voltage, since light indication is a fraction of that.
// Values below from PICAXE V0.09 impl approx multiplied by 4+ to allow for scale change.
#ifdef ENABLE_AMBLIGHT_EXTRA_SENSITIVE // Define if LDR not exposed to much light, eg for REV2 cut4 sideways-pointing LDR (TODO-209).
static const int LDR_THR_LOW = 50U;
static const int LDR_THR_HIGH = 70U;
#else // Normal settings.
static const int LDR_THR_LOW = 160U; // Was 30.
static const int LDR_THR_HIGH = 200U; // Was 35.
#endif // ENABLE_AMBLIGHT_EXTRA_SENSITIVE
#endif // AMBIENT_LIGHT_SENSOR_PHOTOTRANS_TEPT4400
// Singleton implementation/instance.
AmbientLight AmbLight(LDR_THR_HIGH >> shiftRawScaleTo8Bit);
#endif // ENABLE_AMBLIGHT_SENSOR
#if defined(ENABLE_MINIMAL_ONEWIRE_SUPPORT)
OTV0P2BASE::MinimalOneWire<> MinOW_DEFAULT;
#endif
#if defined(SENSOR_EXTERNAL_DS18B20_ENABLE_0) // Enable sensor zero.
OTV0P2BASE::TemperatureC16_DS18B20 extDS18B20_0(MinOW_DEFAULT, 0);
#endif
#if defined(ENABLE_PRIMARY_TEMP_SENSOR_SHT21)
// Singleton implementation/instance.
OTV0P2BASE::HumiditySensorSHT21 RelHumidity;
#else
OTV0P2BASE::DummyHumiditySensorSHT21 RelHumidity;
#endif
// Ambient/room temperature sensor, usually on main board.
#if defined(ENABLE_PRIMARY_TEMP_SENSOR_SHT21)
OTV0P2BASE::RoomTemperatureC16_SHT21 TemperatureC16; // SHT21 impl.
#elif defined(ENABLE_PRIMARY_TEMP_SENSOR_DS18B20)
#if defined(ENABLE_MINIMAL_ONEWIRE_SUPPORT)
// DSB18B20 temperature impl, with slightly reduced precision to improve speed.
OTV0P2BASE::TemperatureC16_DS18B20 TemperatureC16(MinOW_DEFAULT, 0, OTV0P2BASE::TemperatureC16_DS18B20::MAX_PRECISION - 1);
#endif
#else // Don't use TMP112 if SHT21 or DS18B20 are selected.
OTV0P2BASE::RoomTemperatureC16_TMP112 TemperatureC16;
#endif
#ifdef ENABLE_VOICE_SENSOR
// If count meets or exceeds this threshold in one poll period then
// the room is deemed to be occupied.
// Strictly positive.
// DHD20151119: even now it seems a threshold of >= 2 is needed to avoid false positives.
// DE20160101: Lowered detection threshold as new boards have lower sensitivity
#define VOICE_DETECTION_THRESHOLD 2
// Force a read/poll of the voice level and return the value sensed.
// Thread-safe and ISR-safe.
uint8_t VoiceDetection::read()
{
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
isDetected = ((value = count) >= VOICE_DETECTION_THRESHOLD);
// clear count and detection flag
// isTriggered = false;
count = 0;
}
return(value);
}
// Handle simple interrupt.
// Fast and ISR (Interrupt Service Routines) safe.
// Returns true if interrupt was successfully handled and cleared
// else another interrupt handler in the chain may be called
// to attempt to clear the interrupt.
bool VoiceDetection::handleInterruptSimple()
{
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
// Count of voice activations since last poll, avoiding overflow.
if ((count < 255) && (++count >= VOICE_DETECTION_THRESHOLD))
{
// Act as soon as voice is detected.
isDetected = true;
// Don't regard this as a very strong indication,
// as it could be a TV or radio on in the room.
Occupancy.markAsPossiblyOccupied();
}
}
// // Flag that interrupt has occurred
// endOfLocking = OTV0P2BASE::getMinutesSinceMidnightLT() + lockingPeriod;
// isTriggered = true;
// No further work to be done to 'clear' interrupt.
return (true);
}
// Singleton implementation/instance.
VoiceDetection Voice;
#endif
////////////////////////// Actuators
// DORM1/REV7 direct drive actuator.
#ifdef HAS_DORM1_VALVE_DRIVE
//#ifdef DIRECT_MOTOR_DRIVE_V1
// Singleton implementation/instance.
#ifdef ENABLE_DORM1_MOTOR_REVERSED // Reversed vs sample 2015/12
OTRadValve::ValveMotorDirectV1<MOTOR_DRIVE_ML, MOTOR_DRIVE_MR, MOTOR_DRIVE_MI_AIN, MOTOR_DRIVE_MC_AIN> ValveDirect;
#else
OTRadValve::ValveMotorDirectV1<MOTOR_DRIVE_MR, MOTOR_DRIVE_ML, MOTOR_DRIVE_MI_AIN, MOTOR_DRIVE_MC_AIN> ValveDirect;
#endif // HAS_DORM1_MOTOR_REVERSED
#endif
// FHT8V radio-controlled actuator.
#ifdef ENABLE_FHT8VSIMPLE
// Function to append stats trailer (and 0xff) to FHT8V/FS20 TX buffer.
// Assume enough space in buffer for largest possible stats message.
#if defined(ALLOW_STATS_TX)
uint8_t *appendStatsToTXBufferWithFF(uint8_t *bptr, const uint8_t bufSize)
{
OTV0P2BASE::FullStatsMessageCore_t trailer;
populateCoreStats(&trailer);
// Ensure that no ID is encoded in the message sent on the air since it would be a repeat from the FHT8V frame.
trailer.containsID = false;
#if defined(ENABLE_MINIMAL_STATS_TXRX)
// As bandwidth optimisation just write minimal trailer if only temp&power available.
if (trailer.containsTempAndPower &&
!trailer.containsID && !trailer.containsAmbL)
{
writeTrailingMinimalStatsPayload(bptr, &(trailer.tempAndPower));
bptr += 3;
*bptr = (uint8_t)0xff; // Terminate TX bytes.
}
else
#endif
{
// Assume enough space in buffer for largest possible stats message.
bptr = encodeFullStatsMessageCore(bptr, bufSize, OTV0P2BASE::getStatsTXLevel(), false, &trailer);
}
return (bptr);
}
#else
#define appendStatsToTXBufferWithFF NULL // Do not append stats.
#endif
#endif // ENABLE_FHT8VSIMPLE
#ifdef ENABLE_FHT8VSIMPLE
OTRadValve::FHT8VRadValve<_FHT8V_MAX_EXTRA_TRAILER_BYTES, OTRadValve::FHT8VRadValveBase::RFM23_PREAMBLE_BYTES, OTRadValve::FHT8VRadValveBase::RFM23_PREAMBLE_BYTE> FHT8V(appendStatsToTXBufferWithFF);
#endif
// Clear both housecode parts (and thus disable local valve).
// Does nothing if FHT8V not in use.
#ifdef ENABLE_FHT8VSIMPLE
void FHT8VClearHC()
{
FHT8V.clearHC();
OTV0P2BASE::eeprom_smart_erase_byte((uint8_t*)V0P2BASE_EE_START_FHT8V_HC1);
OTV0P2BASE::eeprom_smart_erase_byte((uint8_t*)V0P2BASE_EE_START_FHT8V_HC2);
}
#endif
// Set (non-volatile) HC1 and HC2 for single/primary FHT8V wireless valve under control.
// Also set value in FHT8V rad valve model.
// Does nothing if FHT8V not in use.
#ifdef ENABLE_FHT8VSIMPLE
void FHT8VSetHC1(uint8_t hc)
{
FHT8V.setHC1(hc);
OTV0P2BASE::eeprom_smart_update_byte((uint8_t*)V0P2BASE_EE_START_FHT8V_HC1, hc);
}
void FHT8VSetHC2(uint8_t hc)
{
FHT8V.setHC2(hc);
OTV0P2BASE::eeprom_smart_update_byte((uint8_t*)V0P2BASE_EE_START_FHT8V_HC2, hc);
}
#endif
// Get (non-volatile) HC1 and HC2 for single/primary FHT8V wireless valve under control (will be 0xff until set).
// FHT8V instance values are used as a cache.
// Does nothing if FHT8V not in use.
#ifdef ENABLE_FHT8VSIMPLE
uint8_t FHT8VGetHC1()
{
const uint8_t vv = FHT8V.getHC1();
// If cached value in FHT8V instance is valid, return it.
if (OTRadValve::FHT8VRadValveBase::isValidFHTV8HouseCode(vv))
{
return (vv);
}
// Else if EEPROM value is valid, then cache it in the FHT8V instance and return it.
const uint8_t ev = eeprom_read_byte((uint8_t*)V0P2BASE_EE_START_FHT8V_HC1);
if (OTRadValve::FHT8VRadValveBase::isValidFHTV8HouseCode(ev))
{
FHT8V.setHC1(ev);
}
return (ev);
}
uint8_t FHT8VGetHC2()
{
const uint8_t vv = FHT8V.getHC2();
// If cached value in FHT8V instance is valid, return it.
if (OTRadValve::FHT8VRadValveBase::isValidFHTV8HouseCode(vv))
{
return (vv);
}
// Else if EEPROM value is valid, then cache it in the FHT8V instance and return it.
const uint8_t ev = eeprom_read_byte((uint8_t*)V0P2BASE_EE_START_FHT8V_HC2);
if (OTRadValve::FHT8VRadValveBase::isValidFHTV8HouseCode(ev))
{
FHT8V.setHC2(ev);
}
return (ev);
}
#endif // ENABLE_FHT8VSIMPLE
#ifdef ENABLE_FHT8VSIMPLE
// Load EEPROM house codes into primary FHT8V instance at start-up or once cleared in FHT8V instance.
void FHT8VLoadHCFromEEPROM()
{
// Uses side-effect to cache/save in FHT8V instance.
FHT8VGetHC1();
FHT8VGetHC2();
}
#endif // ENABLE_FHT8VSIMPLE
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** 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 [email protected].
**
**************************************************************************/
#include "watchdata.h"
#include <QtCore/QTextStream>
#include <QtCore/QDebug>
////////////////////////////////////////////////////////////////////
//
// WatchData
//
////////////////////////////////////////////////////////////////////
namespace Debugger {
namespace Internal {
enum GuessChildrenResult
{
HasChildren,
HasNoChildren,
HasPossiblyChildren
};
static QString htmlEscape(const QString &plain)
{
QString rich;
rich.reserve(int(plain.length() * 1.1));
for (int i = 0; i < plain.length(); ++i) {
if (plain.at(i) == QLatin1Char('<'))
rich += QLatin1String("<");
else if (plain.at(i) == QLatin1Char('>'))
rich += QLatin1String(">");
else if (plain.at(i) == QLatin1Char('&'))
rich += QLatin1String("&");
else if (plain.at(i) == QLatin1Char('"'))
rich += QLatin1String(""");
else
rich += plain.at(i);
}
return rich;
}
bool isPointerType(const QByteArray &type)
{
return type.endsWith('*') || type.endsWith("* const");
}
bool isCharPointerType(const QByteArray &type)
{
return type == "char *" || type == "const char *" || type == "char const *";
}
bool isIntType(const QByteArray &type)
{
if (type.isEmpty())
return false;
switch (type.at(0)) {
case 'b':
return type == "bool";
case 'c':
return type == "char";
case 'i':
return type == "int" || type == "int64";
case 'l':
return type == "long"
|| type == "long long";
case 'p':
return type == "ptrdiff_t";
case 'q':
return type == "qint16" || type == "quint16"
|| type == "qint32" || type == "quint32"
|| type == "qint64" || type == "quint64";
case 's':
return type == "short"
|| type == "signed"
|| type == "size_t"
|| type == "std::size_t"
|| type == "std::ptrdiff_t"
|| type.startsWith("signed ");
case 'u':
return type == "unsigned"
|| type.startsWith("unsigned ");
default:
return false;
}
}
bool isFloatType(const QByteArray &type)
{
return type == "float" || type == "double" || type == "qreal";
}
bool isIntOrFloatType(const QByteArray &type)
{
return isIntType(type) || isFloatType(type);
}
GuessChildrenResult guessChildren(const QByteArray &type)
{
if (isIntOrFloatType(type))
return HasNoChildren;
if (isCharPointerType(type))
return HasNoChildren;
if (isPointerType(type))
return HasChildren;
if (type.endsWith("QString"))
return HasNoChildren;
return HasPossiblyChildren;
}
WatchData::WatchData() :
id(0),
state(InitialState),
editformat(0),
address(0),
bitpos(0),
bitsize(0),
generation(-1),
hasChildren(false),
valueEnabled(true),
valueEditable(true),
error(false),
changed(false),
sortId(0),
source(0)
{
}
bool WatchData::isEqual(const WatchData &other) const
{
return iname == other.iname
&& exp == other.exp
&& name == other.name
&& value == other.value
&& editvalue == other.editvalue
&& valuetooltip == other.valuetooltip
&& type == other.type
&& displayedType == other.displayedType
&& variable == other.variable
&& address == other.address
&& hasChildren == other.hasChildren
&& valueEnabled == other.valueEnabled
&& valueEditable == other.valueEditable
&& error == other.error;
}
void WatchData::setError(const QString &msg)
{
setAllUnneeded();
value = msg;
setHasChildren(false);
valueEnabled = false;
valueEditable = false;
error = true;
}
void WatchData::setValue(const QString &value0)
{
value = value0;
if (value == "{...}") {
value.clear();
hasChildren = true; // at least one...
}
// strip off quoted characters for chars.
if (value.endsWith(QLatin1Char('\'')) && type.endsWith("char")) {
const int blankPos = value.indexOf(QLatin1Char(' '));
if (blankPos != -1)
value.truncate(blankPos);
}
// avoid duplicated information
if (value.startsWith(QLatin1Char('(')) && value.contains(") 0x"))
value = value.mid(value.lastIndexOf(") 0x") + 2);
// doubles are sometimes displayed as "@0x6141378: 1.2".
// I don't want that.
if (/*isIntOrFloatType(type) && */ value.startsWith("@0x")
&& value.contains(':')) {
value = value.mid(value.indexOf(':') + 2);
setHasChildren(false);
}
// "numchild" is sometimes lying
//MODEL_DEBUG("\n\n\nPOINTER: " << type << value);
if (isPointerType(type))
setHasChildren(value != "0x0" && value != "<null>"
&& !isCharPointerType(type));
// pointer type information is available in the 'type'
// column. No need to duplicate it here.
if (value.startsWith(QLatin1Char('(') + type + ") 0x"))
value = value.section(QLatin1Char(' '), -1, -1);
setValueUnneeded();
}
void WatchData::setValueToolTip(const QString &tooltip)
{
valuetooltip = tooltip;
}
void WatchData::setType(const QByteArray &str, bool guessChildrenFromType)
{
type = str.trimmed();
bool changed = true;
while (changed) {
if (type.endsWith("const"))
type.chop(5);
else if (type.endsWith(' '))
type.chop(1);
else if (type.endsWith('&'))
type.chop(1);
else if (type.startsWith("const "))
type = type.mid(6);
else if (type.startsWith("volatile "))
type = type.mid(9);
else if (type.startsWith("class "))
type = type.mid(6);
else if (type.startsWith("struct "))
type = type.mid(6);
else if (type.startsWith(' '))
type = type.mid(1);
else
changed = false;
}
setTypeUnneeded();
if (guessChildrenFromType) {
switch (guessChildren(type)) {
case HasChildren:
setHasChildren(true);
break;
case HasNoChildren:
setHasChildren(false);
break;
case HasPossiblyChildren:
setHasChildren(true); // FIXME: bold assumption
break;
}
}
}
void WatchData::setAddress(const quint64 &a)
{
address = a;
}
void WatchData::setHexAddress(const QByteArray &a)
{
bool ok;
const qint64 av = a.toULongLong(&ok, 16);
if (ok) {
address = av;
} else {
qWarning("WatchData::setHexAddress(): Failed to parse address value '%s' for '%s', '%s'",
a.constData(), iname.constData(), type.constData());
address = 0;
}
}
QString WatchData::toString() const
{
const char *doubleQuoteComma = "\",";
QString res;
QTextStream str(&res);
str << QLatin1Char('{');
if (!iname.isEmpty())
str << "iname=\"" << iname << doubleQuoteComma;
str << "sortId=\"" << sortId << doubleQuoteComma;
if (!name.isEmpty() && name != iname)
str << "name=\"" << name << doubleQuoteComma;
if (error)
str << "error,";
if (address) {
str.setIntegerBase(16);
str << "addr=\"0x" << address << doubleQuoteComma;
str.setIntegerBase(10);
}
if (!exp.isEmpty())
str << "exp=\"" << exp << doubleQuoteComma;
if (!variable.isEmpty())
str << "variable=\"" << variable << doubleQuoteComma;
if (isValueNeeded())
str << "value=<needed>,";
if (isValueKnown() && !value.isEmpty())
str << "value=\"" << value << doubleQuoteComma;
if (!editvalue.isEmpty())
str << "editvalue=\"<...>\",";
// str << "editvalue=\"" << editvalue << doubleQuoteComma;
if (!dumperFlags.isEmpty())
str << "dumperFlags=\"" << dumperFlags << doubleQuoteComma;
if (isTypeNeeded())
str << "type=<needed>,";
if (isTypeKnown() && !type.isEmpty())
str << "type=\"" << type << doubleQuoteComma;
if (isHasChildrenNeeded())
str << "hasChildren=<needed>,";
if (isHasChildrenKnown())
str << "hasChildren=\"" << (hasChildren ? "true" : "false") << doubleQuoteComma;
if (isChildrenNeeded())
str << "children=<needed>,";
str.flush();
if (res.endsWith(QLatin1Char(',')))
res.truncate(res.size() - 1);
return res + QLatin1Char('}');
}
// Format a tooltip fow with aligned colon.
static void formatToolTipRow(QTextStream &str,
const QString &category, const QString &value)
{
str << "<tr><td>" << category << "</td><td> : </td><td>"
<< htmlEscape(value) << "</td></tr>";
}
QString WatchData::toToolTip() const
{
if (!valuetooltip.isEmpty())
return QString::number(valuetooltip.size());
QString res;
QTextStream str(&res);
str << "<html><body><table>";
formatToolTipRow(str, tr("Name"), name);
formatToolTipRow(str, tr("Expression"), exp);
formatToolTipRow(str, tr("Internal Type"), type);
formatToolTipRow(str, tr("Displayed Type"), displayedType);
QString val = value;
if (value.size() > 1000) {
val.truncate(1000);
val += tr(" ... <cut off>");
}
formatToolTipRow(str, tr("Value"), val);
formatToolTipRow(str, tr("Object Address"),
QString::fromAscii(hexAddress()));
formatToolTipRow(str, tr("Internal ID"), iname);
formatToolTipRow(str, tr("Generation"),
QString::number(generation));
str << "</table></body></html>";
return res;
}
QString WatchData::msgNotInScope()
{
//: Value of variable in Debugger Locals display for variables out of scope (stopped above initialization).
static const QString rc = QCoreApplication::translate("Debugger::Internal::WatchData", "<not in scope>");
return rc;
}
const QString &WatchData::shadowedNameFormat()
{
//: Display of variables shadowed by variables of the same name
//: in nested scopes: Variable %1 is the variable name, %2 is a
//: simple count.
static const QString format = QCoreApplication::translate("Debugger::Internal::WatchData", "%1 <shadowed %2>");
return format;
}
QString WatchData::shadowedName(const QString &name, int seen)
{
if (seen <= 0)
return name;
return shadowedNameFormat().arg(name, seen);
}
quint64 WatchData::coreAddress() const
{
return address;
}
QByteArray WatchData::hexAddress() const
{
return address ? (QByteArray("0x") + QByteArray::number(address, 16)) : QByteArray();
}
} // namespace Internal
} // namespace Debugger
<commit_msg>debugger: recognize more types as integral<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** 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 [email protected].
**
**************************************************************************/
#include "watchdata.h"
#include <QtCore/QTextStream>
#include <QtCore/QDebug>
////////////////////////////////////////////////////////////////////
//
// WatchData
//
////////////////////////////////////////////////////////////////////
namespace Debugger {
namespace Internal {
enum GuessChildrenResult
{
HasChildren,
HasNoChildren,
HasPossiblyChildren
};
static QString htmlEscape(const QString &plain)
{
QString rich;
rich.reserve(int(plain.length() * 1.1));
for (int i = 0; i < plain.length(); ++i) {
if (plain.at(i) == QLatin1Char('<'))
rich += QLatin1String("<");
else if (plain.at(i) == QLatin1Char('>'))
rich += QLatin1String(">");
else if (plain.at(i) == QLatin1Char('&'))
rich += QLatin1String("&");
else if (plain.at(i) == QLatin1Char('"'))
rich += QLatin1String(""");
else
rich += plain.at(i);
}
return rich;
}
bool isPointerType(const QByteArray &type)
{
return type.endsWith('*') || type.endsWith("* const");
}
bool isCharPointerType(const QByteArray &type)
{
return type == "char *" || type == "const char *" || type == "char const *";
}
bool isIntType(const QByteArray &type)
{
if (type.isEmpty())
return false;
switch (type.at(0)) {
case 'b':
return type == "bool";
case 'c':
return type == "char";
case 'i':
return type == "int" || type == "int64";
case 'l':
return type == "long"
|| type.startsWith("long ");
case 'p':
return type == "ptrdiff_t";
case 'q':
return type == "qint16" || type == "quint16"
|| type == "qint32" || type == "quint32"
|| type == "qint64" || type == "quint64"
|| type == "qlonglong" || type == "qulonglong";
case 's':
return type == "short"
|| type == "signed"
|| type == "size_t"
|| type == "std::size_t"
|| type == "std::ptrdiff_t"
|| type.startsWith("signed ");
case 'u':
return type == "unsigned"
|| type.startsWith("unsigned ");
default:
return false;
}
}
bool isFloatType(const QByteArray &type)
{
return type == "float" || type == "double" || type == "qreal";
}
bool isIntOrFloatType(const QByteArray &type)
{
return isIntType(type) || isFloatType(type);
}
GuessChildrenResult guessChildren(const QByteArray &type)
{
if (isIntOrFloatType(type))
return HasNoChildren;
if (isCharPointerType(type))
return HasNoChildren;
if (isPointerType(type))
return HasChildren;
if (type.endsWith("QString"))
return HasNoChildren;
return HasPossiblyChildren;
}
WatchData::WatchData() :
id(0),
state(InitialState),
editformat(0),
address(0),
bitpos(0),
bitsize(0),
generation(-1),
hasChildren(false),
valueEnabled(true),
valueEditable(true),
error(false),
changed(false),
sortId(0),
source(0)
{
}
bool WatchData::isEqual(const WatchData &other) const
{
return iname == other.iname
&& exp == other.exp
&& name == other.name
&& value == other.value
&& editvalue == other.editvalue
&& valuetooltip == other.valuetooltip
&& type == other.type
&& displayedType == other.displayedType
&& variable == other.variable
&& address == other.address
&& hasChildren == other.hasChildren
&& valueEnabled == other.valueEnabled
&& valueEditable == other.valueEditable
&& error == other.error;
}
void WatchData::setError(const QString &msg)
{
setAllUnneeded();
value = msg;
setHasChildren(false);
valueEnabled = false;
valueEditable = false;
error = true;
}
void WatchData::setValue(const QString &value0)
{
value = value0;
if (value == "{...}") {
value.clear();
hasChildren = true; // at least one...
}
// strip off quoted characters for chars.
if (value.endsWith(QLatin1Char('\'')) && type.endsWith("char")) {
const int blankPos = value.indexOf(QLatin1Char(' '));
if (blankPos != -1)
value.truncate(blankPos);
}
// avoid duplicated information
if (value.startsWith(QLatin1Char('(')) && value.contains(") 0x"))
value = value.mid(value.lastIndexOf(") 0x") + 2);
// doubles are sometimes displayed as "@0x6141378: 1.2".
// I don't want that.
if (/*isIntOrFloatType(type) && */ value.startsWith("@0x")
&& value.contains(':')) {
value = value.mid(value.indexOf(':') + 2);
setHasChildren(false);
}
// "numchild" is sometimes lying
//MODEL_DEBUG("\n\n\nPOINTER: " << type << value);
if (isPointerType(type))
setHasChildren(value != "0x0" && value != "<null>"
&& !isCharPointerType(type));
// pointer type information is available in the 'type'
// column. No need to duplicate it here.
if (value.startsWith(QLatin1Char('(') + type + ") 0x"))
value = value.section(QLatin1Char(' '), -1, -1);
setValueUnneeded();
}
void WatchData::setValueToolTip(const QString &tooltip)
{
valuetooltip = tooltip;
}
void WatchData::setType(const QByteArray &str, bool guessChildrenFromType)
{
type = str.trimmed();
bool changed = true;
while (changed) {
if (type.endsWith("const"))
type.chop(5);
else if (type.endsWith(' '))
type.chop(1);
else if (type.endsWith('&'))
type.chop(1);
else if (type.startsWith("const "))
type = type.mid(6);
else if (type.startsWith("volatile "))
type = type.mid(9);
else if (type.startsWith("class "))
type = type.mid(6);
else if (type.startsWith("struct "))
type = type.mid(6);
else if (type.startsWith(' '))
type = type.mid(1);
else
changed = false;
}
setTypeUnneeded();
if (guessChildrenFromType) {
switch (guessChildren(type)) {
case HasChildren:
setHasChildren(true);
break;
case HasNoChildren:
setHasChildren(false);
break;
case HasPossiblyChildren:
setHasChildren(true); // FIXME: bold assumption
break;
}
}
}
void WatchData::setAddress(const quint64 &a)
{
address = a;
}
void WatchData::setHexAddress(const QByteArray &a)
{
bool ok;
const qint64 av = a.toULongLong(&ok, 16);
if (ok) {
address = av;
} else {
qWarning("WatchData::setHexAddress(): Failed to parse address value '%s' for '%s', '%s'",
a.constData(), iname.constData(), type.constData());
address = 0;
}
}
QString WatchData::toString() const
{
const char *doubleQuoteComma = "\",";
QString res;
QTextStream str(&res);
str << QLatin1Char('{');
if (!iname.isEmpty())
str << "iname=\"" << iname << doubleQuoteComma;
str << "sortId=\"" << sortId << doubleQuoteComma;
if (!name.isEmpty() && name != iname)
str << "name=\"" << name << doubleQuoteComma;
if (error)
str << "error,";
if (address) {
str.setIntegerBase(16);
str << "addr=\"0x" << address << doubleQuoteComma;
str.setIntegerBase(10);
}
if (!exp.isEmpty())
str << "exp=\"" << exp << doubleQuoteComma;
if (!variable.isEmpty())
str << "variable=\"" << variable << doubleQuoteComma;
if (isValueNeeded())
str << "value=<needed>,";
if (isValueKnown() && !value.isEmpty())
str << "value=\"" << value << doubleQuoteComma;
if (!editvalue.isEmpty())
str << "editvalue=\"<...>\",";
// str << "editvalue=\"" << editvalue << doubleQuoteComma;
if (!dumperFlags.isEmpty())
str << "dumperFlags=\"" << dumperFlags << doubleQuoteComma;
if (isTypeNeeded())
str << "type=<needed>,";
if (isTypeKnown() && !type.isEmpty())
str << "type=\"" << type << doubleQuoteComma;
if (isHasChildrenNeeded())
str << "hasChildren=<needed>,";
if (isHasChildrenKnown())
str << "hasChildren=\"" << (hasChildren ? "true" : "false") << doubleQuoteComma;
if (isChildrenNeeded())
str << "children=<needed>,";
str.flush();
if (res.endsWith(QLatin1Char(',')))
res.truncate(res.size() - 1);
return res + QLatin1Char('}');
}
// Format a tooltip fow with aligned colon.
static void formatToolTipRow(QTextStream &str,
const QString &category, const QString &value)
{
str << "<tr><td>" << category << "</td><td> : </td><td>"
<< htmlEscape(value) << "</td></tr>";
}
QString WatchData::toToolTip() const
{
if (!valuetooltip.isEmpty())
return QString::number(valuetooltip.size());
QString res;
QTextStream str(&res);
str << "<html><body><table>";
formatToolTipRow(str, tr("Name"), name);
formatToolTipRow(str, tr("Expression"), exp);
formatToolTipRow(str, tr("Internal Type"), type);
formatToolTipRow(str, tr("Displayed Type"), displayedType);
QString val = value;
if (value.size() > 1000) {
val.truncate(1000);
val += tr(" ... <cut off>");
}
formatToolTipRow(str, tr("Value"), val);
formatToolTipRow(str, tr("Object Address"),
QString::fromAscii(hexAddress()));
formatToolTipRow(str, tr("Internal ID"), iname);
formatToolTipRow(str, tr("Generation"),
QString::number(generation));
str << "</table></body></html>";
return res;
}
QString WatchData::msgNotInScope()
{
//: Value of variable in Debugger Locals display for variables out of scope (stopped above initialization).
static const QString rc = QCoreApplication::translate("Debugger::Internal::WatchData", "<not in scope>");
return rc;
}
const QString &WatchData::shadowedNameFormat()
{
//: Display of variables shadowed by variables of the same name
//: in nested scopes: Variable %1 is the variable name, %2 is a
//: simple count.
static const QString format = QCoreApplication::translate("Debugger::Internal::WatchData", "%1 <shadowed %2>");
return format;
}
QString WatchData::shadowedName(const QString &name, int seen)
{
if (seen <= 0)
return name;
return shadowedNameFormat().arg(name, seen);
}
quint64 WatchData::coreAddress() const
{
return address;
}
QByteArray WatchData::hexAddress() const
{
return address ? (QByteArray("0x") + QByteArray::number(address, 16)) : QByteArray();
}
} // namespace Internal
} // namespace Debugger
<|endoftext|> |
<commit_before>/* Copyright 2007-2015 QReal Research Group, Dmitry Mordvinov
*
* 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 "interpreterCore/managers/actionsManager.h"
#include <QtCore/QSignalMapper>
#include <qrkernel/settingsManager.h>
#include <kitBase/robotModel/robotModelUtils.h>
using namespace interpreterCore;
static const qReal::Id robotDiagramType = qReal::Id("RobotsMetamodel", "RobotsDiagram", "RobotsDiagramNode");
static const qReal::Id subprogramDiagramType = qReal::Id("RobotsMetamodel", "RobotsDiagram", "SubprogramDiagram");
ActionsManager::ActionsManager(KitPluginManager &kitPluginManager, RobotModelManager &robotModelManager)
: mKitPluginManager(kitPluginManager)
, mRobotModelManager(robotModelManager)
, mRunAction(QIcon(":/icons/robots_run.png"), QObject::tr("Run"), nullptr)
, mStopRobotAction(QIcon(":/icons/robots_stop.png"), QObject::tr("Stop robot"), nullptr)
, mConnectToRobotAction(QIcon(":/icons/robots_connect.png"), QObject::tr("Connect to robot"), nullptr)
, mRobotSettingsAction(QIcon(":/icons/robots_settings.png"), QObject::tr("Robot settings"), nullptr)
, mExportExerciseAction(QIcon(), QObject::tr("Save as task..."), nullptr)
, mDebugModeAction(QObject::tr("Switch to debug mode"), nullptr)
, mEditModeAction(QObject::tr("Switch to edit mode"), nullptr)
, mSeparator1(nullptr)
, mSeparator2(nullptr)
{
initKitPluginActions();
mConnectToRobotAction.setCheckable(true);
mSeparator1.setSeparator(true);
mSeparator2.setSeparator(true);
mActions
<< &mConnectToRobotAction
<< &mRunAction
<< &mStopRobotAction
<< &mRobotSettingsAction
<< &mExportExerciseAction
;
mEditModeAction.setShortcut(QKeySequence(Qt::CTRL + Qt::Key_1));
mDebugModeAction.setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2));
mStopRobotAction.setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_F5));
mRunAction.setShortcut(QKeySequence(Qt::Key_F5));
}
QList<qReal::ActionInfo> ActionsManager::actions()
{
QList<qReal::ActionInfo> result;
result << mPluginActionInfos;
result
<< qReal::ActionInfo(&mConnectToRobotAction, "interpreters", "tools")
<< qReal::ActionInfo(&mRunAction, "interpreters", "tools")
<< qReal::ActionInfo(&mStopRobotAction, "interpreters", "tools")
<< qReal::ActionInfo(&mSeparator1, "interpreters", "tools");
result << mRobotModelActions.values();
result << qReal::ActionInfo(&mSeparator2, "interpreters", "tools")
<< qReal::ActionInfo(&mRobotSettingsAction, "interpreters", "tools")
<< qReal::ActionInfo(&mExportExerciseAction, "", "tools")
;
return result;
}
QList<qReal::HotKeyActionInfo> ActionsManager::hotKeyActionInfos()
{
QList<qReal::HotKeyActionInfo> result;
result += mPluginHotKeyActionInfos;
result
<< qReal::HotKeyActionInfo("Editor.EditMode", mEditModeAction.text(), &mEditModeAction)
<< qReal::HotKeyActionInfo("Editor.DebugMode", mDebugModeAction.text(), &mDebugModeAction)
<< qReal::HotKeyActionInfo("Interpreter.Run", QObject::tr("Run interpreter"), &mRunAction)
<< qReal::HotKeyActionInfo("Interpreter.Stop", QObject::tr("Stop interpreter"), &mStopRobotAction)
;
return result;
}
QAction &ActionsManager::runAction()
{
return mRunAction;
}
QAction &ActionsManager::stopRobotAction()
{
return mStopRobotAction;
}
QAction &ActionsManager::connectToRobotAction()
{
return mConnectToRobotAction;
}
void ActionsManager::init(qReal::gui::MainWindowInterpretersInterface *mainWindowInterpretersInterface)
{
mMainWindowInterpretersInterface = mainWindowInterpretersInterface;
updateEnabledActions();
}
QAction &ActionsManager::robotSettingsAction()
{
return mRobotSettingsAction;
}
QAction &ActionsManager::exportExerciseAction()
{
return mExportExerciseAction;
}
QAction &ActionsManager::debugModeAction()
{
return mDebugModeAction;
}
QAction &ActionsManager::editModeAction()
{
return mEditModeAction;
}
void ActionsManager::onRobotModelChanged(kitBase::robotModel::RobotModelInterface &model)
{
mConnectToRobotAction.setVisible(model.needsConnection());
mRunAction.setVisible(model.interpretedModel());
mStopRobotAction.setVisible(false);
const QString currentKitId = kitIdOf(model);
const QString switchActionName = "switchTo" + currentKitId + model.name();
/// @todo: this stupid visibility management may show actions with custom avalability logic.
for (const QString &kitId : mKitPluginManager.kitIds()) {
for (const qReal::ActionInfo &actionInfo : mRobotModelActions.values(kitId)) {
if (actionInfo.isAction()) {
actionInfo.action()->setVisible(currentKitId == kitId);
actionInfo.action()->setChecked(actionInfo.action()->objectName() == switchActionName);
} else {
actionInfo.menu()->setVisible(currentKitId == kitId);
}
}
}
}
void ActionsManager::onActiveTabChanged(const qReal::TabInfo &info)
{
updateEnabledActions();
const bool isDiagramTab = info.type() == qReal::TabInfo::TabType::editor;
mRunAction.setEnabled(isDiagramTab);
mStopRobotAction.setEnabled(isDiagramTab);
}
void ActionsManager::onRobotModelActionChecked(QObject *robotModelObject)
{
const auto robotModel = dynamic_cast<kitBase::robotModel::RobotModelInterface *>(robotModelObject);
mRobotModelManager.setModel(robotModel);
onRobotModelChanged(*robotModel);
}
QString ActionsManager::kitIdOf(kitBase::robotModel::RobotModelInterface &model) const
{
for (const QString &kitId : mKitPluginManager.kitIds()) {
for (kitBase::KitPluginInterface * const kit : mKitPluginManager.kitsById(kitId)) {
if (kit->robotModels().contains(&model)) {
return kitId;
}
}
}
/// @todo: Impossible scenario, something wrong if we get here.
return QString();
}
void ActionsManager::updateEnabledActions()
{
const qReal::Id &rootElementId = mMainWindowInterpretersInterface->activeDiagram();
const bool enabled = rootElementId.type() == robotDiagramType || rootElementId.type() == subprogramDiagramType;
for (QAction * const action : mActions) {
if (action != &mRobotSettingsAction) {
action->setEnabled(enabled);
}
}
}
void ActionsManager::initKitPluginActions()
{
QSignalMapper * const robotModelMapper = new QSignalMapper(this);
connect(robotModelMapper, SIGNAL(mapped(QObject*)), this, SLOT(onRobotModelActionChecked(QObject*)));
for (const QString &kitId : mKitPluginManager.kitIds()) {
const QList<kitBase::KitPluginInterface *> kits = mKitPluginManager.kitsById(kitId);
QActionGroup * const group = new QActionGroup(this);
QList<kitBase::robotModel::RobotModelInterface *> robotModels;
QMap<kitBase::robotModel::RobotModelInterface *, QIcon> fastSelectorIcons;
int topRecommendedModels = 0;
for (kitBase::KitPluginInterface * const kitPlugin : kits) {
topRecommendedModels = qMax(topRecommendedModels, kitPlugin->topRecommendedRobotModels());
mPluginActionInfos << kitPlugin->customActions();
mPluginHotKeyActionInfos << kitPlugin->hotKeyActions();
for (kitBase::robotModel::RobotModelInterface * const robotModel : kitPlugin->robotModels()) {
const QIcon &icon = kitPlugin->iconForFastSelector(*robotModel);
if (icon.isNull()) {
continue;
}
fastSelectorIcons[robotModel] = icon;
robotModels << robotModel;
}
}
QList<QAction *> twoDModelActions;
QList<QAction *> realRobotActions;
kitBase::robotModel::RobotModelUtils::sortRobotModels(robotModels);
for (kitBase::robotModel::RobotModelInterface * const robotModel : robotModels) {
const QString &text = robotModel->friendlyName();
QAction * const fastSelectionAction = new QAction(fastSelectorIcons[robotModel], text, nullptr);
robotModelMapper->setMapping(fastSelectionAction, robotModel);
connect(fastSelectionAction, SIGNAL(triggered()), robotModelMapper, SLOT(map()));
fastSelectionAction->setObjectName("switchTo" + kitId + robotModel->name());
fastSelectionAction->setCheckable(true);
group->addAction(fastSelectionAction);
if (text.contains("2D")) {
twoDModelActions << fastSelectionAction;
} else {
realRobotActions << fastSelectionAction;
}
}
if (!kits.isEmpty()) {
QAction * const twoDModelSwitcher = produceMenuAction(kitId, tr("2D model"), twoDModelActions);
QAction * const realRobotSwitcher = produceMenuAction(kitId, tr("Real robot"), realRobotActions);
// if (robotModels.count() > topRecommendedModels) {
// QAction * const separator = new QAction(nullptr);
// separator->setSeparator(true);
// action->menu()->insertAction(action->menu()->actions()[topRecommendedModels], separator);
// }
QMap<QString, qReal::ActionInfo>::iterator twoDModelPosition;
if (twoDModelSwitcher) {
twoDModelPosition = mRobotModelActions.insertMulti(kitId
, qReal::ActionInfo(twoDModelSwitcher, "interpreters", "tools"));
}
if (realRobotSwitcher) {
mRobotModelActions.insertMulti(twoDModelPosition, kitId
, qReal::ActionInfo(realRobotSwitcher, "interpreters", "tools"));
}
}
}
}
QAction *ActionsManager::produceMenuAction(const QString &kitId, const QString &name
, const QList<QAction *> &subActions) const
{
if (subActions.isEmpty()) {
return nullptr;
}
if (subActions.count() == 1) {
return subActions.first();
}
QAction * const menuAction = new QAction(QIcon(), name, nullptr);
menuAction->setCheckable(true);
menuAction->setIcon(subActions.first()->icon());
menuAction->setMenu(new QMenu);
menuAction->menu()->addActions(subActions);
connect(&mRobotModelManager, &RobotModelManager::robotModelChanged
, [this, menuAction, kitId](kitBase::robotModel::RobotModelInterface &model) {
const QString actionName = "switchTo" + kitId + model.name();
for (QAction * const action : menuAction->menu()->actions()) {
if (action->objectName() == actionName) {
menuAction->setIcon(action->icon());
menuAction->setChecked(true);
action->setChecked(true);
return;
}
}
menuAction->setChecked(false);
});
connect(menuAction, &QAction::triggered, [=]() { menuAction->menu()->exec(QCursor::pos()); });
return menuAction;
}
<commit_msg>Made new fast selection actions working<commit_after>/* Copyright 2007-2015 QReal Research Group, Dmitry Mordvinov
*
* 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 "interpreterCore/managers/actionsManager.h"
#include <QtCore/QSignalMapper>
#include <qrkernel/settingsManager.h>
#include <kitBase/robotModel/robotModelUtils.h>
using namespace interpreterCore;
static const qReal::Id robotDiagramType = qReal::Id("RobotsMetamodel", "RobotsDiagram", "RobotsDiagramNode");
static const qReal::Id subprogramDiagramType = qReal::Id("RobotsMetamodel", "RobotsDiagram", "SubprogramDiagram");
ActionsManager::ActionsManager(KitPluginManager &kitPluginManager, RobotModelManager &robotModelManager)
: mKitPluginManager(kitPluginManager)
, mRobotModelManager(robotModelManager)
, mRunAction(QIcon(":/icons/robots_run.png"), QObject::tr("Run"), nullptr)
, mStopRobotAction(QIcon(":/icons/robots_stop.png"), QObject::tr("Stop robot"), nullptr)
, mConnectToRobotAction(QIcon(":/icons/robots_connect.png"), QObject::tr("Connect to robot"), nullptr)
, mRobotSettingsAction(QIcon(":/icons/robots_settings.png"), QObject::tr("Robot settings"), nullptr)
, mExportExerciseAction(QIcon(), QObject::tr("Save as task..."), nullptr)
, mDebugModeAction(QObject::tr("Switch to debug mode"), nullptr)
, mEditModeAction(QObject::tr("Switch to edit mode"), nullptr)
, mSeparator1(nullptr)
, mSeparator2(nullptr)
{
initKitPluginActions();
mConnectToRobotAction.setCheckable(true);
mSeparator1.setSeparator(true);
mSeparator2.setSeparator(true);
mActions
<< &mConnectToRobotAction
<< &mRunAction
<< &mStopRobotAction
<< &mRobotSettingsAction
<< &mExportExerciseAction
;
mEditModeAction.setShortcut(QKeySequence(Qt::CTRL + Qt::Key_1));
mDebugModeAction.setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2));
mStopRobotAction.setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_F5));
mRunAction.setShortcut(QKeySequence(Qt::Key_F5));
}
QList<qReal::ActionInfo> ActionsManager::actions()
{
QList<qReal::ActionInfo> result;
result << mPluginActionInfos;
result
<< qReal::ActionInfo(&mConnectToRobotAction, "interpreters", "tools")
<< qReal::ActionInfo(&mRunAction, "interpreters", "tools")
<< qReal::ActionInfo(&mStopRobotAction, "interpreters", "tools")
<< qReal::ActionInfo(&mSeparator1, "interpreters", "tools");
result << mRobotModelActions.values();
result << qReal::ActionInfo(&mSeparator2, "interpreters", "tools")
<< qReal::ActionInfo(&mRobotSettingsAction, "interpreters", "tools")
<< qReal::ActionInfo(&mExportExerciseAction, "", "tools")
;
return result;
}
QList<qReal::HotKeyActionInfo> ActionsManager::hotKeyActionInfos()
{
QList<qReal::HotKeyActionInfo> result;
result += mPluginHotKeyActionInfos;
result
<< qReal::HotKeyActionInfo("Editor.EditMode", mEditModeAction.text(), &mEditModeAction)
<< qReal::HotKeyActionInfo("Editor.DebugMode", mDebugModeAction.text(), &mDebugModeAction)
<< qReal::HotKeyActionInfo("Interpreter.Run", QObject::tr("Run interpreter"), &mRunAction)
<< qReal::HotKeyActionInfo("Interpreter.Stop", QObject::tr("Stop interpreter"), &mStopRobotAction)
;
return result;
}
QAction &ActionsManager::runAction()
{
return mRunAction;
}
QAction &ActionsManager::stopRobotAction()
{
return mStopRobotAction;
}
QAction &ActionsManager::connectToRobotAction()
{
return mConnectToRobotAction;
}
void ActionsManager::init(qReal::gui::MainWindowInterpretersInterface *mainWindowInterpretersInterface)
{
mMainWindowInterpretersInterface = mainWindowInterpretersInterface;
updateEnabledActions();
}
QAction &ActionsManager::robotSettingsAction()
{
return mRobotSettingsAction;
}
QAction &ActionsManager::exportExerciseAction()
{
return mExportExerciseAction;
}
QAction &ActionsManager::debugModeAction()
{
return mDebugModeAction;
}
QAction &ActionsManager::editModeAction()
{
return mEditModeAction;
}
void ActionsManager::onRobotModelChanged(kitBase::robotModel::RobotModelInterface &model)
{
mConnectToRobotAction.setVisible(model.needsConnection());
mRunAction.setVisible(model.interpretedModel());
mStopRobotAction.setVisible(false);
const QString currentKitId = kitIdOf(model);
/// @todo: this stupid visibility management may show actions with custom avalability logic.
for (const QString &kitId : mKitPluginManager.kitIds()) {
for (const qReal::ActionInfo &actionInfo : mRobotModelActions.values(kitId)) {
if (actionInfo.isAction()) {
actionInfo.action()->setVisible(currentKitId == kitId);
} else {
actionInfo.menu()->setVisible(currentKitId == kitId);
}
}
}
}
void ActionsManager::onActiveTabChanged(const qReal::TabInfo &info)
{
updateEnabledActions();
const bool isDiagramTab = info.type() == qReal::TabInfo::TabType::editor;
mRunAction.setEnabled(isDiagramTab);
mStopRobotAction.setEnabled(isDiagramTab);
}
void ActionsManager::onRobotModelActionChecked(QObject *robotModelObject)
{
const auto robotModel = dynamic_cast<kitBase::robotModel::RobotModelInterface *>(robotModelObject);
mRobotModelManager.setModel(robotModel);
onRobotModelChanged(*robotModel);
}
QString ActionsManager::kitIdOf(kitBase::robotModel::RobotModelInterface &model) const
{
for (const QString &kitId : mKitPluginManager.kitIds()) {
for (kitBase::KitPluginInterface * const kit : mKitPluginManager.kitsById(kitId)) {
if (kit->robotModels().contains(&model)) {
return kitId;
}
}
}
/// @todo: Impossible scenario, something wrong if we get here.
return QString();
}
void ActionsManager::updateEnabledActions()
{
const qReal::Id &rootElementId = mMainWindowInterpretersInterface->activeDiagram();
const bool enabled = rootElementId.type() == robotDiagramType || rootElementId.type() == subprogramDiagramType;
for (QAction * const action : mActions) {
if (action != &mRobotSettingsAction) {
action->setEnabled(enabled);
}
}
}
void ActionsManager::initKitPluginActions()
{
QSignalMapper * const robotModelMapper = new QSignalMapper(this);
connect(robotModelMapper, SIGNAL(mapped(QObject*)), this, SLOT(onRobotModelActionChecked(QObject*)));
for (const QString &kitId : mKitPluginManager.kitIds()) {
const QList<kitBase::KitPluginInterface *> kits = mKitPluginManager.kitsById(kitId);
QActionGroup * const group = new QActionGroup(this);
QList<kitBase::robotModel::RobotModelInterface *> robotModels;
QMap<kitBase::robotModel::RobotModelInterface *, QIcon> fastSelectorIcons;
int topRecommendedModels = 0;
for (kitBase::KitPluginInterface * const kitPlugin : kits) {
topRecommendedModels = qMax(topRecommendedModels, kitPlugin->topRecommendedRobotModels());
mPluginActionInfos << kitPlugin->customActions();
mPluginHotKeyActionInfos << kitPlugin->hotKeyActions();
for (kitBase::robotModel::RobotModelInterface * const robotModel : kitPlugin->robotModels()) {
const QIcon &icon = kitPlugin->iconForFastSelector(*robotModel);
if (icon.isNull()) {
continue;
}
fastSelectorIcons[robotModel] = icon;
robotModels << robotModel;
}
}
QList<QAction *> twoDModelActions;
QList<QAction *> realRobotActions;
kitBase::robotModel::RobotModelUtils::sortRobotModels(robotModels);
for (kitBase::robotModel::RobotModelInterface * const robotModel : robotModels) {
const QString &text = robotModel->friendlyName();
QAction * const fastSelectionAction = new QAction(fastSelectorIcons[robotModel], text, nullptr);
robotModelMapper->setMapping(fastSelectionAction, robotModel);
connect(fastSelectionAction, SIGNAL(triggered()), robotModelMapper, SLOT(map()));
fastSelectionAction->setObjectName("switchTo" + kitId + robotModel->name());
fastSelectionAction->setCheckable(true);
group->addAction(fastSelectionAction);
if (text.contains("2D")) {
twoDModelActions << fastSelectionAction;
} else {
realRobotActions << fastSelectionAction;
}
}
if (!kits.isEmpty()) {
QAction * const twoDModelSwitcher = produceMenuAction(kitId, tr("2D model"), twoDModelActions);
QAction * const realRobotSwitcher = produceMenuAction(kitId, tr("Real robot"), realRobotActions);
// if (robotModels.count() > topRecommendedModels) {
// QAction * const separator = new QAction(nullptr);
// separator->setSeparator(true);
// action->menu()->insertAction(action->menu()->actions()[topRecommendedModels], separator);
// }
QMap<QString, qReal::ActionInfo>::iterator twoDModelPosition;
if (twoDModelSwitcher) {
twoDModelPosition = mRobotModelActions.insertMulti(kitId
, qReal::ActionInfo(twoDModelSwitcher, "interpreters", "tools"));
}
if (realRobotSwitcher) {
mRobotModelActions.insertMulti(twoDModelPosition, kitId
, qReal::ActionInfo(realRobotSwitcher, "interpreters", "tools"));
}
}
}
}
QAction *ActionsManager::produceMenuAction(const QString &kitId, const QString &name
, const QList<QAction *> &subActions) const
{
if (subActions.isEmpty()) {
return nullptr;
}
if (subActions.count() == 1) {
QAction * const result = subActions.first();
connect(&mRobotModelManager, &RobotModelManager::robotModelChanged
, [this, kitId, result](kitBase::robotModel::RobotModelInterface &model) {
result->setChecked("switchTo" + kitId + model.name() == result->objectName());
});
return result;
}
QAction * const menuAction = new QAction(subActions.first()->icon(), name, nullptr);
menuAction->setCheckable(true);
menuAction->setMenu(new QMenu);
menuAction->menu()->addActions(subActions);
auto checkAction = [this, menuAction, kitId](const QString &name) {
const QString actionName = name;
for (QAction * const action : menuAction->menu()->actions()) {
if (action->objectName() == actionName) {
action->setChecked(true);
qReal::SettingsManager::setValue("lastFastSelectorActionFor" + kitId, actionName);
menuAction->setIcon(action->icon());
menuAction->setChecked(true);
return action;
}
}
menuAction->setChecked(false);
return static_cast<QAction *>(nullptr);
};
connect(&mRobotModelManager, &RobotModelManager::robotModelChanged
, [this, kitId, checkAction](kitBase::robotModel::RobotModelInterface &model) {
checkAction("switchTo" + kitId + model.name());
});
connect(menuAction, &QAction::triggered, [this, kitId, checkAction]() {
const QString key = qReal::SettingsManager::value("lastFastSelectorActionFor" + kitId).toString();
if (QAction * const action = checkAction(key)) {
action->trigger();
}
});
return menuAction;
}
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief グラフィックス・カラー定義
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>
namespace graphics {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 基本カラー定数
@param[in] T ピクセル型(uint16_t、uint32_t)
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <typename T>
class base_color {
static constexpr uint32_t rgb888_(uint8_t r, uint8_t g, uint8_t b)
{
return
(static_cast<uint32_t>(r) << 16)
| (static_cast<uint32_t>(g) << 8)
| static_cast<uint32_t>(b);
}
static constexpr uint16_t rgb565_(uint8_t r, uint8_t g, uint8_t b)
{
return
(static_cast<uint16_t>(r & 0xf8) << 8)
| (static_cast<uint16_t>(g & 0xfc) << 3)
| (static_cast<uint16_t>(b & 0xf8) >> 3);
}
static constexpr T rgb_(uint8_t r, uint8_t g, uint8_t b)
{
if(sizeof(T) == 1) {
return (r & 0b11100000) | ((g & 0b11100000) >> 3) | ((b & 0b11000000) >> 6);
} else if(sizeof(T) == 2) return rgb565_(r, g, b);
else if(sizeof(T) == 4) return rgb888_(r, g, b);
else return 0;
}
public:
//-----------------------------------------------------------------//
/*!
@brief RGB 値から、パックされた RGB 値に変換
@param[in] r R 値
@param[in] g G 値
@param[in] b B 値
@return パックされた RGB 値
*/
//-----------------------------------------------------------------//
static T rgb(uint8_t r, uint8_t g, uint8_t b) { return rgb_(r, g, b); }
// https://jonasjacek.github.io/colors/
static constexpr T Black = rgb_( 0, 0, 0);
static constexpr T Maroon = rgb_(128, 0, 0);
static constexpr T Green = rgb_( 0, 128, 0);
static constexpr T Olive = rgb_(128, 128, 0);
static constexpr T Navy = rgb_( 0, 0, 128);
static constexpr T Purple = rgb_(128, 0, 128);
static constexpr T Teal = rgb_( 0, 128, 128);
static constexpr T Silver = rgb_(192, 192, 192);
static constexpr T Gray = rgb_(128, 128, 128); // 米国
static constexpr T Grey = rgb_(128, 128, 128); // 英国
static constexpr T Red = rgb_(255, 0, 0);
static constexpr T Lime = rgb_( 0, 255, 0);
static constexpr T Yellow = rgb_(255, 255, 0);
static constexpr T Blue = rgb_( 0, 0, 255);
static constexpr T Fuchsi = rgb_(255, 0, 255);
static constexpr T Aqua = rgb_( 0, 255, 255);
static constexpr T White = rgb_(255, 255, 255);
};
}
<commit_msg>update: optimize rgb565 conversion<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief グラフィックス・カラー定義
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>
namespace graphics {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 基本カラー定数
@param[in] T ピクセル型(uint16_t、uint32_t)
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <typename T>
class base_color {
static constexpr uint32_t rgb888_(uint8_t r, uint8_t g, uint8_t b)
{
return
(static_cast<uint32_t>(r) << 16)
| (static_cast<uint32_t>(g) << 8)
| static_cast<uint32_t>(b);
}
static constexpr uint16_t rgb565_(uint8_t r, uint8_t g, uint8_t b)
{
return
(static_cast<uint16_t>(r & 0xf8) << 8)
| (static_cast<uint16_t>(g & 0xfc) << 3)
| (static_cast<uint16_t>(b) >> 3);
}
static constexpr T rgb_(uint8_t r, uint8_t g, uint8_t b)
{
if(sizeof(T) == 1) {
return (r & 0b11100000) | ((g & 0b11100000) >> 3) | ((b & 0b11000000) >> 6);
} else if(sizeof(T) == 2) return rgb565_(r, g, b);
else if(sizeof(T) == 4) return rgb888_(r, g, b);
else return 0;
}
public:
//-----------------------------------------------------------------//
/*!
@brief RGB 値から、パックされた RGB 値に変換
@param[in] r R 値
@param[in] g G 値
@param[in] b B 値
@return パックされた RGB 値
*/
//-----------------------------------------------------------------//
static T rgb(uint8_t r, uint8_t g, uint8_t b) { return rgb_(r, g, b); }
// https://jonasjacek.github.io/colors/
static constexpr T Black = rgb_( 0, 0, 0);
static constexpr T Maroon = rgb_(128, 0, 0);
static constexpr T Green = rgb_( 0, 128, 0);
static constexpr T Olive = rgb_(128, 128, 0);
static constexpr T Navy = rgb_( 0, 0, 128);
static constexpr T Purple = rgb_(128, 0, 128);
static constexpr T Teal = rgb_( 0, 128, 128);
static constexpr T Silver = rgb_(192, 192, 192);
static constexpr T Gray = rgb_(128, 128, 128); // 米国
static constexpr T Grey = rgb_(128, 128, 128); // 英国
static constexpr T Red = rgb_(255, 0, 0);
static constexpr T Lime = rgb_( 0, 255, 0);
static constexpr T Yellow = rgb_(255, 255, 0);
static constexpr T Blue = rgb_( 0, 0, 255);
static constexpr T Fuchsi = rgb_(255, 0, 255);
static constexpr T Aqua = rgb_( 0, 255, 255);
static constexpr T White = rgb_(255, 255, 255);
};
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (C) 2015 Mark Charlebois. 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 PX4 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 main.cpp
* Basic shell to execute builtin "apps"
*
* @author Mark Charlebois <[email protected]>
*/
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
namespace px4 {
void init_once(void);
}
using namespace std;
typedef int (*px4_main_t)(int argc, char *argv[]);
#include "apps.h"
#include "px4_middleware.h"
static void run_cmd(const vector<string> &appargs) {
// command is appargs[0]
string command = appargs[0];
cout << "----------------------------------\n";
if (apps.find(command) != apps.end()) {
const char *arg[appargs.size()+2];
unsigned int i = 0;
while (i < appargs.size() && appargs[i] != "") {
arg[i] = (char *)appargs[i].c_str();
++i;
}
arg[i] = (char *)0;
cout << "Running: " << command << "\n";
apps[command](i,(char **)arg);
}
else
{
cout << "Invalid command: " << command << endl;
list_builtins();
}
}
static void process_line(string &line)
{
vector<string> appargs(5);
stringstream(line) >> appargs[0] >> appargs[1] >> appargs[2] >> appargs[3] >> appargs[4];
run_cmd(appargs);
}
int main(int argc, char **argv)
{
px4::init_once();
px4::init(argc, argv, "mainapp");
// Execute a command list of provided
if (argc == 2) {
ifstream infile(argv[1]);
for (string line; getline(infile, line, '\n'); ) {
process_line(line);
}
}
string mystr;
while(1) {
cout << "Enter a command and its args:" << endl;
getline (cin,mystr);
process_line(mystr);
mystr = "";
}
}
<commit_msg>increase number of arguments passable to apps<commit_after>/****************************************************************************
*
* Copyright (C) 2015 Mark Charlebois. 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 PX4 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 main.cpp
* Basic shell to execute builtin "apps"
*
* @author Mark Charlebois <[email protected]>
*/
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
namespace px4 {
void init_once(void);
}
using namespace std;
typedef int (*px4_main_t)(int argc, char *argv[]);
#include "apps.h"
#include "px4_middleware.h"
static void run_cmd(const vector<string> &appargs) {
// command is appargs[0]
string command = appargs[0];
cout << "----------------------------------\n";
if (apps.find(command) != apps.end()) {
const char *arg[appargs.size()+2];
unsigned int i = 0;
while (i < appargs.size() && appargs[i] != "") {
arg[i] = (char *)appargs[i].c_str();
++i;
}
arg[i] = (char *)0;
cout << "Running: " << command << "\n";
apps[command](i,(char **)arg);
}
else
{
cout << "Invalid command: " << command << endl;
list_builtins();
}
}
static void process_line(string &line)
{
vector<string> appargs(8);
stringstream(line) >> appargs[0] >> appargs[1] >> appargs[2] >> appargs[3] >> appargs[4] >> appargs[5] >> appargs[6] >> appargs[7];
run_cmd(appargs);
}
int main(int argc, char **argv)
{
px4::init_once();
px4::init(argc, argv, "mainapp");
// Execute a command list of provided
if (argc == 2) {
ifstream infile(argv[1]);
for (string line; getline(infile, line, '\n'); ) {
process_line(line);
}
}
string mystr;
while(1) {
cout << "Enter a command and its args:" << endl;
getline (cin,mystr);
process_line(mystr);
mystr = "";
}
}
<|endoftext|> |
<commit_before>#include <ros/ros.h> //For ROS itself
#include <image_transport/image_transport.h> //For the image transport class. Still needs the vc bridge though.
#include <opencv2/highgui/highgui.hpp> //FIXME Not exactly sure why this one is here; maybe it's for displaying the images that come in?
#include <cv_bridge/cv_bridge.h> //The openCV bridge that image_transport needs
#include <ros/console.h> //This is for ROS_ERROR and stuff.
#include <boost/filesystem.hpp> //For creating directtories if needed
#include <obe_toolset/ImageAndPose.h> //Needed for the custom Image and Pose message type
int main(int argc, char** argv)
{
ros::init(argc, argv, "image_publisher_node");
ros::NodeHandle n;
image_transport::ImageTransport it(n);
ros::Publisher impose_pub = n.advertise<obe_toolset::ImageAndPose>("obe/imagePipe1", 100);
// image_transport::Publisher impose_pub = it.advertise("obe/image", 255); //Buffers up to 255 pictures in case connection is lost
// ^^That used to be the old publisher.
// cv::Mat image = cv::imread("/home/kennon/images/BrentRambo.jpg", CV_LOAD_IMAGE_COLOR);
// cv::waitKey(30); //No idea what this line does...
// cv::imshow("view", image); //This can be used to see the image as it's published
//This block makes sure that the needed directories are set up (I'm pretty sure they should be, since this node might end up running from one of them).
namespace fs = boost::filesystem;
fs::create_directories("~/images/new");
fs::create_directories("~/images/processed");
fs::create_directories("~/images/unsuccessful");
//NOTE:: IF THERE IS AN ISSUE WITH PERMISSIONS FOR SOME REASON, IT MIGHT BE THAT THE LINES OF CODE ABOVE ARE REMOVING EXECUTE PERMISSIONS. JUST SOMETHING TO CONSIDER
fs::path im_fetch_path("~/images/new"); //Will be used to get images
if (!(fs::exists(im_fetch_path)))
{
ROS_ERROR("Oh no. ~/images/new isn't a directory =(");
return(-1);
}
else if (fs::is_regular_file(im_fetch_path))
{
ROS_ERROR("Oh no. ~/images/new is a regular file =(");
return(-1);
}
ros::Rate loop_rate(.1); //rate is the number of outer loop iterations per second
//Also, we need the loop rate to be relatively quick becuase we don't want delay in dispatching images. Delay in dispatching images could lead to wasted execution time and potential incorrect location stamps.
while(n.ok())
{
//We need to dispatch each of the images in the new directory
for(fs::directory_iterator cur_path_itr(im_fetch_path); cur_path_itr != fs::directory_iterator(); ++cur_path_itr)
{
if(fs::is_directory(cur_path_itr->path()))
{
ROS_INFO_STREAM_ONCE("There's a directory in the ~/images/new path; this is currently unhandled.");
}
else
{
cv::Mat newImage = cv::imread(cur_path_itr->path().string(), CV_LOAD_IMAGE_COLOR);
if(newImage.data == NULL)//The image was read improperly if this fails...
{
ROS_ERROR("I was unable to read the file image file.");
}
else
{
obe_toolset::ImageAndPose impose_msg; //This is the custom message type that has a sensor_msgs::Image msg and a std_msgs::Pose message.
impose_msg.image = *(cv_bridge::CvImage(std_msgs::Header(), "bgr8", newImage).toImageMsg()); //The meat of this line is from the image_transport tutorial; I just de-reference their piece to get a sensor_msgs::Image. Note: There's probably a better way to do this, but it will work for now.
//This is where we need to assign the position pieces. (Use UTM values.
impose_msg.position.x = ; //fakes an x UTM value
impose_msg.position.y = ; //etc...
impose_msg.position.z = ;
//These values should be collected from one of the MAVROS pieces.
impose_pub.publish(impose_msg); //send the impose message.
}
}
} //Ends the for loop
ros::spinOnce();
loop_rate.sleep();
}
//It shouldn't get here until you hit ctrl-C, but we still need to specify a return value:
return 0;
}
<commit_msg>BS Commit - Switching to a different PC<commit_after>#include <ros/ros.h> //For ROS itself
//#include <image_transport/image_transport.h> //For the image transport class. Still needs the vc bridge though.
#include <opencv2/highgui/highgui.hpp> //FIXME Not exactly sure why this one is here; maybe it's for displaying the images that come in?
#include <cv_bridge/cv_bridge.h> //The openCV bridge that image_transport needs
#include <ros/console.h> //This is for ROS_ERROR and stuff.
#include <boost/filesystem.hpp> //For creating directtories if needed
#include <obe_toolset/ImageAndPose.h> //Needed for the custom Image and Pose message type
#include <string>
#include <vector>
//#include "std_msgs/String.h"
//#define ONEATATIME //if this is defined, it will do one file at a time and pause in between files.
int main(int argc, char** argv)
{
ros::init(argc, argv, "image_publisher_node");
ros::NodeHandle n;
int numOfPipes;
int currentPipeMinusOne = 0;
if(!(n.hasParam("numPipes")))
ROS_INFO("the parameter 'numPipes' for the dispatcher node hasn't been specified; assuming 1 to ensure that no images are lost. This may cause severe back-up issues in a long mission.");
n.param<int>("numPipes", numOfPipes, 1); //gets the numPipes param (so that we know where to publish), defaulting to 1 if it can't be read.
std::vector<ros::Publisher> impose_pub_vector(numOfPipes); //vector of publishers
for(int i = 1; i <= numOfPipes; ++i)
{
std::string topic("obe/imagePipe");
topic += std::to_string(i);
impose_pub_vector[i-1] = n.advertise<obe_toolset::ImageAndPose>(topic.c_str(), 512); //publishes to the obe/imagePipe<i> and buffers up to 512 images per pipe in case it can't send them all that quickly.
}
// image_transport::ImageTransport it(n);
// ros::Publisher pub = n.advertise<std_msgs::String>("obe/test", 100);
// image_transport::Publisher impose_pub = it.advertise("obe/image", 255); //Buffers up to 255 pictures in case connection is lost
// ^^That used to be the old publisher.
// cv::Mat image = cv::imread("/home/kennon/images/BrentRambo.jpg", CV_LOAD_IMAGE_COLOR);
// cv::waitKey(30); //No idea what this line does...
// cv::imshow("view", image); //This can be used to see the image as it's published
//This block makes sure that the needed directories are set up (I'm pretty sure they should be, since this node might end up running from one of them).
namespace fs = boost::filesystem;
fs::path new_path("../images/new/"); //Will be used to get images.
fs::path processed_path("../images/processed/");
fs::path roi_path("../images/rois/");
fs::path error_path("../images/unsuccessful/");
fs::path im_fetch_path(new_path);
fs::create_directories(im_fetch_path);
fs::create_directories(processed_path);
fs::create_directories(roi_path);
fs::create_directories(error_path);
//NOTE:: IF THERE IS AN ISSUE WITH PERMISSIONS FOR SOME REASON, IT MIGHT BE THAT THE LINES OF CODE ABOVE ARE REMOVING EXECUTE PERMISSIONS. JUST SOMETHING TO CONSIDER
if (!(fs::exists(im_fetch_path)))
{
//If it doesn't exist, something went horribly wrong =/
ROS_ERROR("Oh no. '%s' isn't a directory =(", im_fetch_path.string().c_str());
return(-1);
}
else if (fs::is_regular_file(im_fetch_path))
{
ROS_ERROR("Oh no. '%s' is a regular file =(", im_fetch_path.string().c_str());
return(-1);
}
#ifdef ONEATATIME
ros::Rate loop_rate(.25);
#else
ros::Rate loop_rate(25); //rate is the number of outer loop iterations per second
//Also, we need the loop rate to be relatively quick becuase we don't want delay in dispatching images. Delay in dispatching images could lead to wasted execution time and potential incorrect location stamps.
#endif //ONEATATIME
while(n.ok())
{
//We need to dispatch each of the images in the new directory
ROS_INFO("Looking at path %s", im_fetch_path.string().c_str());
fs::directory_iterator end_itr;
for(fs::directory_iterator cur_path_itr(im_fetch_path); cur_path_itr != end_itr; cur_path_itr++)
{
ROS_INFO("I'm looking at this file: %s", cur_path_itr->path().string().c_str());
if(fs::is_directory(cur_path_itr->path()))
{
ROS_INFO_STREAM_ONCE("There's a directory in the ~/images/new path; this is currently unhandled.");
fs::rename(cur_path_itr->path(), error_path / cur_path_itr->path().filename());
//FIXME Don't forget to move this file to the folder for files with errors.
}
else
{
cv::Mat newImage = cv::imread(cur_path_itr->path().string(), CV_LOAD_IMAGE_COLOR);
if(newImage.data == NULL)//The image was read improperly if this fails...
{
ROS_ERROR("I was unable to read the file image file.");
fs::rename(cur_path_itr->path(), error_path / cur_path_itr->path().filename());
}
else
{
obe_toolset::ImageAndPose impose_msg; //This is the custom message type that has a sensor_msgs::Image msg and a std_msgs::Pose message.
impose_msg.image = *(cv_bridge::CvImage(std_msgs::Header(), "bgr8", newImage).toImageMsg()); //The meat of this line is from the image_transport tutorial; I just de-reference their piece to get a sensor_msgs::Image. Note: There's probably a better way to do this, but it will work for now.
//This is the point where the fakeing things comes in.
impose_msg.x = 0; //fakes an x UTM value
impose_msg.y = 0; //etc...
impose_msg.z = 60.96; //This is actually a decent guess (~200 ft)
impose_msg.roll = 0.0;
impose_msg.pitch = 0.0;
impose_msg.yaw = 0.0; //this is the only one that's used as of 4.26.17
//End the faking it stuff.
//publish to the current pipe that's due for another message. NOTE: In the future, this could have a system that keeps track of busy nodes so that no particular node gets bogged down. I'm kind of assuming that we have enough nodes and a fast enough ROI algorithm and randomness is on our side so that this doesn't get out of hand.
impose_pub_vector[currentPipeMinusOne].publish(impose_msg); //send the impose message.
//set up the current pipe for the next time we publish something.
currentPipeMinusOne++;
currentPipeMinusOne %= numOfPipes; //we want to wrap around
//Now that we've published it, we can move the file to the processed folder
fs::rename(cur_path_itr->path(), processed_path / cur_path_itr->path().filename());
#ifdef ONEATATIME
break;
#endif
}
}
} //Ends the for loop
ros::spinOnce();
loop_rate.sleep();
ROS_INFO("I'm done sleeping");
}
//It shouldn't get here until you hit ctrl-C, but we still need to specify a return value:
return 0;
}
<|endoftext|> |
<commit_before>#include "../../IRCBot/include/command-interface.hpp"
#include "../../IRCBot/include/bot.hpp"
#include "./random-line-stream.hpp" /* for use in BabblerCommand */
#include "./iplookup.hpp"
#include "./googler.hpp"
#include "./stocks.hpp"
#include "./quotes.hpp"
#include "./http.hpp"
#include "./hash.hpp"
#include "./urban.hpp"
#include <algorithm>
#include <string>
#include <vector>
#include <random>
#include <cctype>
#include <unistd.h> /* getpid() */
namespace Plugins {
class GoogleCommand : protected IRC::CommandInterface {
unsigned long long times_executed;
public:
GoogleCommand() /* pointer to owning bot not needed. */
: CommandInterface("@google ", "Performs google search and returns shortened links.", nullptr, true), times_executed(0) {}
void run(const IRC::Packet& p) {
std::vector<std::string> res_vec;
Googler::do_google_search(p.content.substr(this->trigger().length()), 2, res_vec);
for (auto& res : res_vec) {
p.reply(res);
}
this->times_executed++;
}
std::string get_stats(void) const {
return "GoogleCommand -> Times Executed: " + std::to_string(this->times_executed);
}
};
class LMGTFYCommand : protected IRC::CommandInterface {
public:
LMGTFYCommand()
: CommandInterface("@lmgtfy ", "mean way to tell ppl to google things.") {}
void run(const IRC::Packet& p) {
p.reply("http://lmgtfy.com/?q=" + MyHTTP::uri_encode( p.content.substr(this->trigger().length()) ) );
}
};
class UrbanCommand : protected IRC::CommandInterface {
public:
UrbanCommand()
: CommandInterface("@urban ", "checks urban dictionary for a definition.") {}
void run(const IRC::Packet& p) {
std::string def = "";
Urban::get_first_result(p.content.substr(this->trigger_string.length()) , def);
if (!def.empty()) {
p.reply(def);
}
}
};
class IPLookupCommand : protected IRC::CommandInterface {
public:
IPLookupCommand() : IRC::CommandInterface("@iplookup ", "looks up IP address.", nullptr, true) {}
void run(const IRC::Packet& p) {
p.reply(IPLookup::do_lookup(p.content.substr(this->trigger().length())));
}
};
class SayHiCommand : protected IRC::CommandInterface {
public:
SayHiCommand() : IRC::CommandInterface("@sayhi", "says hi.") {}
void run(const IRC::Packet& p) {
p.reply("Hello!");
}
};
class SlapCommand : protected IRC::CommandInterface {
public:
SlapCommand() : IRC::CommandInterface("@slap ", "slaps arguments.") {}
void run(const IRC::Packet& p) {
p.reply("\001ACTION slapped the hell outta " + p.content.substr(this->trigger().length()) + "\001");
}
};
class SpeakCommand : protected IRC::CommandInterface {
public:
SpeakCommand() : IRC::CommandInterface("@speak ", "says a message to channel: @speak <chan> <msg...>", nullptr, true) {}
void run(const IRC::Packet& p) {
std::string arguments = p.content.substr(this->trigger().length()); // everything after "@speak "
size_t first_space_idx = arguments.find(" ");
if (first_space_idx == std::string::npos)
return;
std::string chan = arguments.substr(0, first_space_idx);
std::string msg = arguments.substr(first_space_idx + 1);
p.owner->privmsg( chan , msg );
}
};
class BabblerCommand : protected IRC::CommandInterface {
RandomLineStream rls;
public:
BabblerCommand(const std::string& babbles_filepath)
: CommandInterface("@babble", "does a babble."), rls(babbles_filepath) {}
void run(const IRC::Packet& p) {
p.reply(rls.sample());
}
};
class StocksCommand : protected IRC::CommandInterface {
unsigned long long queries_done;
public:
StocksCommand() : CommandInterface("@stock ", "checks a stock ticker price."), queries_done(0) {}
void run(const IRC::Packet& p) {
p.reply(Stocks::get_stock_summary( p.content.substr(this->trigger().length()) ));
this->queries_done++;
}
std::string get_stats(void) const {
return "Stock Queries Done: " + std::to_string(queries_done);
}
};
class QuoteCommand : protected IRC::CommandInterface {
public:
QuoteCommand() : CommandInterface("@quote", "delivers the quote of the day.") {}
void run(const IRC::Packet& p) {
p.reply(Quotes::get_random_quote());
}
};
class EliteCommand : protected IRC::CommandInterface {
const std::string reglr = "abeiolgsqtz";
const std::string elite = "48310195972";
public:
EliteCommand() : CommandInterface("@1337 ", "translates to and from 13375p34k.") {}
void run(const IRC::Packet& p) {
std::string sub = p.content.substr(this->trigger_string.length());
std::string msg = "";
try {
msg = sub.substr(sub.find(" "));
} catch (std::exception& e) {
std::cerr << "EliteCommand::run() error: " << e.what() << '\n';
p.reply("Error. Usage: @1337 [to1337 | from1337] [message...]");
}
sub = sub.substr(0, sub.find(" "));
if (sub == "from1337") {
for (auto& e : msg) {
for (size_t i = 0; i < elite.length(); ++i) {
if (std::tolower(e) == elite[i])
e = reglr[i];
}
}
} else {
for (auto& e : msg) {
for (size_t i = 0; i < reglr.length(); ++i) {
if (std::tolower(e) == reglr[i])
e = elite[i];
}
}
}
p.reply(msg);
}
};
class ChooseCommand : protected IRC::CommandInterface {
std::minstd_rand random_gen;
public:
ChooseCommand() : CommandInterface("@choose ", "chooses a thing of comma-separated list.") {
random_gen.seed(getpid());
}
bool triggered(const IRC::Packet& p) {
if (p.content.length() < this->trigger_string.length())
return false;
std::string s = p.content.substr(0, this->trigger_string.length()-1);
return p.type == IRC::Packet::PacketType::PRIVMSG && !std::isalpha(s[0]) && !std::isdigit(s[0]) && s.substr(1) == this->trigger_string.substr(1, s.length()-1);
}
void run(const IRC::Packet& p) {
std::string choices_str = p.content.substr(this->trigger_string.length());
std::vector<std::string> choices_vec;
size_t last = 0, next = 0;
while (last < choices_str.length() && (next = choices_str.find(",", last)) != std::string::npos) {
choices_vec.push_back(choices_str.substr( last, next - last ) );
last = next+1;
while (last < choices_str.length() && choices_str[last] == ',')
++last;
}
choices_vec.push_back(choices_str.substr(last));
std::cout << "choices_vec.size() = " << choices_vec.size() << '\n';
if ( !choices_vec.empty() )
p.reply(choices_vec.at( random_gen() % choices_vec.size() ) );
}
};
class UtilityCommands : protected IRC::CommandInterface {
public:
UtilityCommands(IRC::Bot *b = nullptr) : IRC::CommandInterface("@kick,@join,@part,@quit,@nick,@adda", "does utility actions", b, true) {
if (b == nullptr) {
throw std::logic_error("In UtilityCommands, Bot *b cannot be nullptr!");
}
}
bool triggered(const IRC::Packet& p) {
std::string cmd = p.content.substr(0,5);
return p.type == IRC::Packet::PacketType::PRIVMSG
&& ( cmd == "@kick" || cmd == "@join" || cmd == "@part" || cmd == "@quit" || cmd == "@nick" || cmd == "@adda");
}
void run(const IRC::Packet& p) {
std::string cmd = p.content.substr(0,5);
if (p.content.length() > 5) {
if ( cmd == "@kick" ) {
p.owner->kick(p.channel, p.content.substr(6));
} else if ( cmd == "@join" ) {
p.owner->join_channel( p.content.substr(6 , p.content.find(" ", 6) - 6) );
} else if ( cmd == "@part" ) {
p.owner->part_channel( p.content.substr(6) );
} else if ( cmd == "@nick" ) {
p.owner->set_nick( p.content.substr(6) );
} else if ( cmd == "@adda" ) {
std::vector<std::string> args;
p.get_args(args);
if (args.size() < 3) {
p.owner->privmsg(p.sender, "Error. Usage: @adda TYPE name");
return;
}
try {
std::transform(args[1].begin(), args[1].end(), args[1].begin(), ::tolower);
} catch (...) {
std::cerr << "failed in UtilityCommands @adda to transform to lowercase : " << args[1] << '\n';
return;
}
IRC::Bot::RELATIONSHIP r = IRC::Bot::RELATIONSHIP::IGNORED;
if (args[1] == "admin") {
r = IRC::Bot::RELATIONSHIP::ADMIN;
} else if (args[1] != "ignore") { // all else except "admin" and "ignore" (case insensitive)
p.owner->privmsg(p.sender, "Error. Invalid argument: " + args[1]);
return;
}
bot_ptr->add_a(r , args[2]);
p.reply("Added " + args[2] + " to " + args[1] + " list.");
}
}
if (cmd == "@quit") { // quit
p.owner->disconnect( p.content.length() > 6 ? p.content.substr(6) : "Quitting..." );
}
}
};
class RecoveryCommand : public IRC::CommandInterface {
public:
RecoveryCommand(IRC::Bot *b = nullptr) : CommandInterface("@recover ", "recover the bot with a password.", b) {}
void run(const IRC::Packet& p) {
std::string password = p.content.substr(this->trigger().length());
if ( bot_ptr->reauthenticate(p.sender, Hash::sha256(password)) ) {
p.owner->privmsg(p.sender, "Password accepted! You now have admin rights.");
} else {
p.owner->privmsg(p.sender, "Denied. Password invalid.");
}
}
};
};
<commit_msg>cleanup a utility plugin<commit_after>#include "../../IRCBot/include/command-interface.hpp"
#include "../../IRCBot/include/bot.hpp"
#include "./random-line-stream.hpp" /* for use in BabblerCommand */
#include "./iplookup.hpp"
#include "./googler.hpp"
#include "./stocks.hpp"
#include "./quotes.hpp"
#include "./http.hpp"
#include "./hash.hpp"
#include "./urban.hpp"
#include <algorithm>
#include <string>
#include <vector>
#include <random>
#include <cctype>
#include <unistd.h> /* getpid() */
namespace Plugins {
class GoogleCommand : protected IRC::CommandInterface {
unsigned long long times_executed;
public:
GoogleCommand() /* pointer to owning bot not needed. */
: CommandInterface("@google ", "Performs google search and returns shortened links.", nullptr, true), times_executed(0) {}
void run(const IRC::Packet& p) {
std::vector<std::string> res_vec;
Googler::do_google_search(p.content.substr(this->trigger().length()), 2, res_vec);
for (auto& res : res_vec) {
p.reply(res);
}
this->times_executed++;
}
std::string get_stats(void) const {
return "GoogleCommand -> Times Executed: " + std::to_string(this->times_executed);
}
};
class LMGTFYCommand : protected IRC::CommandInterface {
public:
LMGTFYCommand()
: CommandInterface("@lmgtfy ", "mean way to tell ppl to google things.") {}
void run(const IRC::Packet& p) {
p.reply("http://lmgtfy.com/?q=" + MyHTTP::uri_encode( p.content.substr(this->trigger().length()) ) );
}
};
class UrbanCommand : protected IRC::CommandInterface {
public:
UrbanCommand()
: CommandInterface("@urban ", "checks urban dictionary for a definition.") {}
void run(const IRC::Packet& p) {
std::string def = "";
Urban::get_first_result(p.content.substr(this->trigger_string.length()) , def);
if (!def.empty()) {
p.reply(def);
}
}
};
class IPLookupCommand : protected IRC::CommandInterface {
public:
IPLookupCommand() : IRC::CommandInterface("@iplookup ", "looks up IP address.", nullptr, true) {}
void run(const IRC::Packet& p) {
p.reply(IPLookup::do_lookup(p.content.substr(this->trigger().length())));
}
};
class SayHiCommand : protected IRC::CommandInterface {
public:
SayHiCommand() : IRC::CommandInterface("@sayhi", "says hi.") {}
void run(const IRC::Packet& p) {
p.reply("Hello!");
}
};
class SlapCommand : protected IRC::CommandInterface {
public:
SlapCommand() : IRC::CommandInterface("@slap ", "slaps arguments.") {}
void run(const IRC::Packet& p) {
p.reply("\001ACTION slapped the hell outta " + p.content.substr(this->trigger().length()) + "\001");
}
};
class SpeakCommand : protected IRC::CommandInterface {
public:
SpeakCommand() : IRC::CommandInterface("@speak ", "says a message to channel: @speak <chan> <msg...>", nullptr, true) {}
void run(const IRC::Packet& p) {
std::string arguments = p.content.substr(this->trigger().length()); // everything after "@speak "
size_t first_space_idx = arguments.find(" ");
if (first_space_idx == std::string::npos)
return;
std::string chan = arguments.substr(0, first_space_idx);
std::string msg = arguments.substr(first_space_idx + 1);
p.owner->privmsg( chan , msg );
}
};
class BabblerCommand : protected IRC::CommandInterface {
RandomLineStream rls;
public:
BabblerCommand(const std::string& babbles_filepath)
: CommandInterface("@babble", "does a babble."), rls(babbles_filepath) {}
void run(const IRC::Packet& p) {
p.reply(rls.sample());
}
};
class StocksCommand : protected IRC::CommandInterface {
unsigned long long queries_done;
public:
StocksCommand() : CommandInterface("@stock ", "checks a stock ticker price."), queries_done(0) {}
void run(const IRC::Packet& p) {
p.reply(Stocks::get_stock_summary( p.content.substr(this->trigger().length()) ));
this->queries_done++;
}
std::string get_stats(void) const {
return "Stock Queries Done: " + std::to_string(queries_done);
}
};
class QuoteCommand : protected IRC::CommandInterface {
public:
QuoteCommand() : CommandInterface("@quote", "delivers the quote of the day.") {}
void run(const IRC::Packet& p) {
p.reply(Quotes::get_random_quote());
}
};
class EliteCommand : protected IRC::CommandInterface {
const std::string reglr = "abeiolgsqtz";
const std::string elite = "48310195972";
public:
EliteCommand() : CommandInterface("@1337 ", "translates to and from 13375p34k.") {}
void run(const IRC::Packet& p) {
std::string sub = p.content.substr(this->trigger_string.length());
std::string msg = "";
try {
msg = sub.substr(sub.find(" "));
} catch (std::exception& e) {
std::cerr << "EliteCommand::run() error: " << e.what() << '\n';
p.reply("Error. Usage: @1337 [to1337 | from1337] [message...]");
}
sub = sub.substr(0, sub.find(" "));
if (sub == "from1337") {
for (auto& e : msg) {
for (size_t i = 0; i < elite.length(); ++i) {
if (std::tolower(e) == elite[i])
e = reglr[i];
}
}
} else {
for (auto& e : msg) {
for (size_t i = 0; i < reglr.length(); ++i) {
if (std::tolower(e) == reglr[i])
e = elite[i];
}
}
}
p.reply(msg);
}
};
class ChooseCommand : protected IRC::CommandInterface {
std::minstd_rand random_gen;
public:
ChooseCommand() : CommandInterface("@choose ", "chooses a thing of comma-separated list.") {
random_gen.seed(getpid());
}
bool triggered(const IRC::Packet& p) {
if (p.content.length() < this->trigger_string.length())
return false;
std::string s = p.content.substr(0, this->trigger_string.length()-1);
return p.type == IRC::Packet::PacketType::PRIVMSG && !std::isalpha(s[0]) && !std::isdigit(s[0]) && s.substr(1) == this->trigger_string.substr(1, s.length()-1);
}
void run(const IRC::Packet& p) {
std::string choices_str = p.content.substr(this->trigger_string.length());
std::vector<std::string> choices_vec;
size_t last = 0, next = 0;
while (last < choices_str.length() && (next = choices_str.find(",", last)) != std::string::npos) {
choices_vec.push_back(choices_str.substr( last, next - last ) );
last = next+1;
while (last < choices_str.length() && choices_str[last] == ',')
++last;
}
choices_vec.push_back(choices_str.substr(last));
std::cout << "choices_vec.size() = " << choices_vec.size() << '\n';
if ( !choices_vec.empty() )
p.reply(choices_vec.at( random_gen() % choices_vec.size() ) );
}
};
class UtilityCommands : protected IRC::CommandInterface {
public:
UtilityCommands(IRC::Bot *b = nullptr) : IRC::CommandInterface("@kick, @join, @part, @quit, @nick, @adda", "does utility actions", b, true) {
if (b == nullptr) {
throw std::logic_error("In UtilityCommands, Bot *b cannot be nullptr!");
}
}
bool triggered(const IRC::Packet& p) {
std::string cmd = p.content.substr(0,5);
return p.type == IRC::Packet::PacketType::PRIVMSG
&& ( cmd == "@kick" || cmd == "@join" || cmd == "@part" || cmd == "@quit" || cmd == "@nick" || cmd == "@adda");
}
void run(const IRC::Packet& p) {
std::string cmd = p.content.substr(0,5);
if (p.content.length() > 5) {
if ( cmd == "@kick" ) {
p.owner->kick(p.channel, p.content.substr(6));
} else if ( cmd == "@join" ) {
p.owner->join_channel( p.content.substr(6 , p.content.find(" ", 6) - 6) );
} else if ( cmd == "@part" ) {
p.owner->part_channel( p.content.substr(6) );
} else if ( cmd == "@nick" ) {
p.owner->set_nick( p.content.substr(6) );
} else if ( cmd == "@adda" ) {
std::vector<std::string> args;
p.get_args(args);
if (args.size() < 3) {
p.owner->privmsg(p.sender, "Error. Usage: @adda TYPE name");
return;
}
try {
std::transform(args[1].begin(), args[1].end(), args[1].begin(), ::tolower);
} catch (...) {
std::cerr << "failed in UtilityCommands @adda to transform to lowercase : " << args[1] << '\n';
return;
}
IRC::Bot::RELATIONSHIP r = IRC::Bot::RELATIONSHIP::IGNORED;
if (args[1] == "admin") {
r = IRC::Bot::RELATIONSHIP::ADMIN;
} else if (args[1] != "ignore") { // all else except "admin" and "ignore" (case insensitive)
p.owner->privmsg(p.sender, "Error. Invalid argument: " + args[1]);
return;
}
bot_ptr->add_a(r , args[2]);
p.reply("Added " + args[2] + " to " + args[1] + " list.");
}
}
if (cmd == "@quit") { // quit
p.owner->disconnect( p.content.length() > 6 ? p.content.substr(6) : "Quitting..." );
}
}
};
class RecoveryCommand : public IRC::CommandInterface {
public:
RecoveryCommand(IRC::Bot *b = nullptr) : CommandInterface("@recover ", "recover the bot with a password.", b) {}
void run(const IRC::Packet& p) {
std::string password = p.content.substr(this->trigger().length());
if ( bot_ptr->reauthenticate(p.sender, Hash::sha256(password)) ) {
p.owner->privmsg(p.sender, "Password accepted! You now have admin rights.");
} else {
p.owner->privmsg(p.sender, "Denied. Password invalid.");
}
}
};
};
<|endoftext|> |
<commit_before>#include "AliAODExtension.h"
//-------------------------------------------------------------------------
// Support class for AOD extensions. This is created by the user analysis
// that requires a separate file for some AOD branches. The name of the
// AliAODExtension object is the file name where the AOD branches will be
// stored.
//-------------------------------------------------------------------------
#include "AliAODBranchReplicator.h"
#include "AliAODEvent.h"
#include "AliCodeTimer.h"
#include "AliLog.h"
#include "Riostream.h"
#include "TDirectory.h"
#include "TFile.h"
#include "TList.h"
#include "TMap.h"
#include "TMap.h"
#include "TObjString.h"
#include "TROOT.h"
#include "TString.h"
#include "TTree.h"
using std::endl;
using std::cout;
ClassImp(AliAODExtension)
//______________________________________________________________________________
AliAODExtension::AliAODExtension() : TNamed(),
fAODEvent(0), fTreeE(0), fFileE(0), fNtotal(0), fNpassed(0),
fSelected(kFALSE), fTreeBuffSize(30000000), fMemCountAOD(0),
fRepFiMap(0x0), fRepFiList(0x0), fEnableReferences(kTRUE)
{
// default ctor
}
//______________________________________________________________________________
AliAODExtension::AliAODExtension(const char* name, const char* title, Bool_t isfilter)
:TNamed(name,title),
fAODEvent(0),
fTreeE(0),
fFileE(0),
fNtotal(0),
fNpassed(0),
fSelected(kFALSE),
fTreeBuffSize(30000000),
fMemCountAOD(0),
fRepFiMap(0x0),
fRepFiList(0x0),
fEnableReferences(kTRUE),
fObjectList(0x0)
{
// Constructor.
if (isfilter) {
TObject::SetBit(kFilteredAOD);
printf("####### Added AOD filter %s\n", name);
} else printf("####### Added AOD extension %s\n", name);
KeepUnspecifiedBranches();
}
//______________________________________________________________________________
AliAODExtension::~AliAODExtension()
{
// Destructor.
if(fFileE){
// is already handled in TerminateIO
fFileE->Close();
delete fFileE;
fTreeE = 0;
fAODEvent = 0;
}
if (fTreeE) delete fTreeE;
if (fRepFiMap) fRepFiMap->DeleteAll();
delete fRepFiMap; // the map is owner
delete fRepFiList; // the list is not
delete fObjectList; // not owner
}
//______________________________________________________________________________
void AliAODExtension::AddBranch(const char* cname, void* addobj)
{
// Add a new branch to the aod
if (!fAODEvent) {
char type[20];
gROOT->ProcessLine(Form("TString s_tmp; AliAnalysisManager::GetAnalysisManager()->GetAnalysisTypeString(s_tmp); sprintf((char*)%p, \"%%s\", s_tmp.Data());", type));
Init(type);
}
TDirectory *owd = gDirectory;
if (fFileE) {
fFileE->cd();
}
char** apointer = (char**) addobj;
TObject* obj = (TObject*) *apointer;
fAODEvent->AddObject(obj);
TString bname(obj->GetName());
if (!fTreeE->FindBranch(bname.Data()))
{
Bool_t acceptAdd(kTRUE);
if ( TestBit(kDropUnspecifiedBranches) )
{
// check that this branch is in our list of specified ones...
// otherwise do not add it !
TIter next(fRepFiMap);
TObjString* p;
acceptAdd=kFALSE;
while ( ( p = static_cast<TObjString*>(next()) ) && !acceptAdd )
{
if ( p->String() == bname ) acceptAdd=kTRUE;
}
}
if ( acceptAdd )
{
// Do the same as if we book via
// TTree::Branch(TCollection*)
fObjectList->Add(obj);
const Int_t kSplitlevel = 99; // default value in TTree::Branch()
const Int_t kBufsize = 32000; // default value in TTree::Branch()
fTreeE->Bronch(bname.Data(), cname,
fAODEvent->GetList()->GetObjectRef(obj),
kBufsize, kSplitlevel - 1);
}
}
owd->cd();
}
//______________________________________________________________________________
Bool_t AliAODExtension::FinishEvent()
{
// Fill current event.
fNtotal++;
if (!IsFilteredAOD()) {
fAODEvent->MakeEntriesReferencable();
FillTree();
return kTRUE;
}
// Filtered AOD. Fill only if event is selected.
if (!fSelected) return kTRUE;
TIter next(fRepFiList);
AliAODBranchReplicator* repfi;
while ( ( repfi = static_cast<AliAODBranchReplicator*>(next()) ) )
{
repfi->ReplicateAndFilter(*fAODEvent);
}
fNpassed++;
FillTree();
fSelected = kFALSE; // so that next event will not be selected unless demanded
return kTRUE;
}
//______________________________________________________________________________
void AliAODExtension::FillTree()
{
//
// Fill AOD extension tree and check AutoFlush settings
//
Long64_t nbf = fTreeE->Fill();
// Check buffer size and set autoflush if fTreeBuffSize is reached
if (fTreeBuffSize>0 && fTreeE->GetAutoFlush()<0 &&
(fMemCountAOD += nbf)>fTreeBuffSize ) { // default limit is still not reached
nbf = fTreeE->GetZipBytes();
if (nbf>0) nbf = -nbf;
else nbf = fTreeE->GetEntries();
fTreeE->SetAutoFlush(nbf);
AliInfo(Form("Calling fTreeE->SetAutoFlush(%lld) | W:%lld T:%lld Z:%lld",
nbf,fMemCountAOD,fTreeE->GetTotBytes(),fTreeE->GetZipBytes()));
}
}
//______________________________________________________________________________
Bool_t AliAODExtension::Init(Option_t *option)
{
// Initialize IO.
AliCodeTimerAuto(GetName(),0);
if(!fAODEvent)
{
fAODEvent = new AliAODEvent();
}
TDirectory *owd = gDirectory;
TString opt(option);
opt.ToLower();
if (opt.Contains("proof"))
{
// proof
// Merging via files. Need to access analysis manager via interpreter.
gROOT->ProcessLine(Form("AliAnalysisDataContainer *c_common_out = AliAnalysisManager::GetAnalysisManager()->GetCommonOutputContainer();"));
gROOT->ProcessLine(Form("AliAnalysisManager::GetAnalysisManager()->OpenProofFile(c_common_out, \"RECREATE\", \"%s\");", fName.Data()));
fFileE = gFile;
}
else
{
fFileE = new TFile(GetName(), "RECREATE");
}
fTreeE = new TTree("aodTree", "AliAOD tree");
delete fObjectList;
fObjectList = new TList;
fObjectList->SetOwner(kFALSE); // be explicit we're not the owner...
TList* inputList = fAODEvent->GetList();
TIter next(inputList);
TObject* o;
while ( ( o = next() ) )
{
// Loop on the objects that are within the main AOD, and see what to do with them :
// - transmit them to our AOD as they are
// - filter them (by means of an AliAODBranchReplicator)
// - drop them completely
Bool_t mustKeep(kFALSE);
TString test(o->ClassName());
test.ToUpper();
// check if there is a replicator for the header
Bool_t headerHasReplicator = fRepFiMap && (fRepFiMap->FindObject(o->GetName())!=0x0);
if (test.BeginsWith("ALIAODHEADER") && !headerHasReplicator)
{
// do not allow to drop header branch
mustKeep=kTRUE;
}
if ( fRepFiMap && !mustKeep )
{
// we have some replicators, so let's see what the relevant one decides about this object
TObject* specified = fRepFiMap->FindObject(o->GetName()); // FindObject finds key=o->GetName() in the map
if (specified)
{
AliAODBranchReplicator* repfi = dynamic_cast<AliAODBranchReplicator*>(fRepFiMap->GetValue(o->GetName())); // GetValue gets the replicator corresponding to key=o->GetName()
if ( repfi )
{
TList* replicatedList = repfi->GetList();
if (replicatedList)
{
AliAODEvent::AssignIDtoCollection(replicatedList);
TIter nextRep(replicatedList);
TObject* objRep;
while ( ( objRep = nextRep() ) )
{
if ( !fObjectList->FindObject(objRep) ) // insure we're not adding several times the same object
{
fObjectList->Add(objRep);
}
}
}
else
{
AliError(Form("replicatedList from %s is null !",repfi->GetName()));
}
}
}
else
{
if ( !TestBit(kDropUnspecifiedBranches) )
{
// object o will be transmitted to the output AOD, unchanged
fObjectList->Add(o);
}
}
}
else
{
// no replicator, so decide based on the policy about dropping unspecified branches
if ( mustKeep || !TestBit(kDropUnspecifiedBranches) )
{
// object o will be transmitted to the output AOD, unchanged
fObjectList->Add(o);
}
}
}
if (fEnableReferences)
{
fTreeE->BranchRef();
}
fTreeE->Branch(fObjectList);
owd->cd();
return kTRUE;
}
//______________________________________________________________________________
void AliAODExtension::Print(Option_t* opt) const
{
// Print info about this extension
cout << opt << Form("%s - %s - %s - aod %p",IsFilteredAOD() ? "FilteredAOD" : "Extension",
GetName(),GetTitle(),GetAOD()) << endl;
if ( !fEnableReferences )
{
cout << opt << opt << "References are disabled ! Hope you know what you are doing !" << endl;
}
if ( TestBit(kDropUnspecifiedBranches) )
{
cout << opt << opt << "All branches not explicitely specified will be dropped" << endl;
}
TIter next(fRepFiMap);
TObjString* s;
while ( ( s = static_cast<TObjString*>(next()) ) )
{
AliAODBranchReplicator* br = static_cast<AliAODBranchReplicator*>(fRepFiMap->GetValue(s->String().Data()));
cout << opt << opt << "Branch " << s->String();
if (br)
{
cout << " will be filtered by class " << br->ClassName();
}
else
{
cout << " will be transmitted as is";
}
cout << endl;
}
}
//______________________________________________________________________________
void AliAODExtension::SetEvent(AliAODEvent* event)
{
// Connects to an external event
if (!IsFilteredAOD()) {
Error("SetEvent", "Not allowed to set external event for non filtered AOD's");
return;
}
fAODEvent = event;
}
//______________________________________________________________________________
void AliAODExtension::AddAODtoTreeUserInfo()
{
// Add aod event to tree user info
if (!fTreeE) return;
AliAODEvent* aodEvent(fAODEvent);
if ( IsFilteredAOD() )
{
// cannot attach fAODEvent (which is shared with our AliAODHandler mother)
// so we create a custom (empty) AliAODEvent
// Has also the advantage we can specify only the list of objects
// that are actually there in this filtered aod
//
aodEvent = new AliAODEvent;
TIter nextObj(fObjectList);
TObject* o;
while ( ( o = nextObj() ) )
{
aodEvent->AddObject(o);
}
}
fTreeE->GetUserInfo()->Add(aodEvent);
}
//______________________________________________________________________________
Bool_t AliAODExtension::TerminateIO()
{
// Terminate IO
if (TObject::TestBit(kFilteredAOD))
printf("AOD Filter %s: events processed: %d passed: %d\n", GetName(), fNtotal, fNpassed);
else
printf("AOD extension %s: events processed: %d\n", GetName(), fNtotal);
if (fFileE)
{
fFileE->Write();
fFileE->Close();
delete fFileE;
fFileE = 0;
fTreeE = 0;
fAODEvent = 0;
}
return kTRUE;
}
//______________________________________________________________________________
void AliAODExtension::FilterBranch(const char* branchName, AliAODBranchReplicator* repfi)
{
// Specify a filter/replicator for a given branch
//
// If repfi=0x0, this will disable the branch (in the output) completely.
//
// repfi is adopted by this class, i.e. user should not delete it.
//
// WARNING : branch name must be exact.
//
// See also the documentation for AliAODBranchReplicator class.
//
if (!fRepFiMap)
{
fRepFiMap = new TMap;
fRepFiMap->SetOwnerKeyValue(kTRUE,kTRUE);
fRepFiList = new TList;
fRepFiList->SetOwner(kFALSE);
}
fRepFiMap->Add(new TObjString(branchName),repfi);
if (repfi && !fRepFiList->FindObject(repfi))
{
// insure we get unique and non-null replicators in this list
fRepFiList->Add(repfi);
}
}
<commit_msg>Fixed Coverity defect<commit_after>#include "AliAODExtension.h"
//-------------------------------------------------------------------------
// Support class for AOD extensions. This is created by the user analysis
// that requires a separate file for some AOD branches. The name of the
// AliAODExtension object is the file name where the AOD branches will be
// stored.
//-------------------------------------------------------------------------
#include "AliAODBranchReplicator.h"
#include "AliAODEvent.h"
#include "AliCodeTimer.h"
#include "AliLog.h"
#include "Riostream.h"
#include "TDirectory.h"
#include "TFile.h"
#include "TList.h"
#include "TMap.h"
#include "TMap.h"
#include "TObjString.h"
#include "TROOT.h"
#include "TString.h"
#include "TTree.h"
using std::endl;
using std::cout;
ClassImp(AliAODExtension)
//______________________________________________________________________________
AliAODExtension::AliAODExtension() : TNamed(),
fAODEvent(0), fTreeE(0), fFileE(0), fNtotal(0), fNpassed(0),
fSelected(kFALSE), fTreeBuffSize(30000000), fMemCountAOD(0),
fRepFiMap(0x0), fRepFiList(0x0), fEnableReferences(kTRUE), fObjectList(0)
{
// default ctor
}
//______________________________________________________________________________
AliAODExtension::AliAODExtension(const char* name, const char* title, Bool_t isfilter)
:TNamed(name,title),
fAODEvent(0),
fTreeE(0),
fFileE(0),
fNtotal(0),
fNpassed(0),
fSelected(kFALSE),
fTreeBuffSize(30000000),
fMemCountAOD(0),
fRepFiMap(0x0),
fRepFiList(0x0),
fEnableReferences(kTRUE),
fObjectList(0x0)
{
// Constructor.
if (isfilter) {
TObject::SetBit(kFilteredAOD);
printf("####### Added AOD filter %s\n", name);
} else printf("####### Added AOD extension %s\n", name);
KeepUnspecifiedBranches();
}
//______________________________________________________________________________
AliAODExtension::~AliAODExtension()
{
// Destructor.
if(fFileE){
// is already handled in TerminateIO
fFileE->Close();
delete fFileE;
fTreeE = 0;
fAODEvent = 0;
}
if (fTreeE) delete fTreeE;
if (fRepFiMap) fRepFiMap->DeleteAll();
delete fRepFiMap; // the map is owner
delete fRepFiList; // the list is not
delete fObjectList; // not owner
}
//______________________________________________________________________________
void AliAODExtension::AddBranch(const char* cname, void* addobj)
{
// Add a new branch to the aod
if (!fAODEvent) {
char type[20];
gROOT->ProcessLine(Form("TString s_tmp; AliAnalysisManager::GetAnalysisManager()->GetAnalysisTypeString(s_tmp); sprintf((char*)%p, \"%%s\", s_tmp.Data());", type));
Init(type);
}
TDirectory *owd = gDirectory;
if (fFileE) {
fFileE->cd();
}
char** apointer = (char**) addobj;
TObject* obj = (TObject*) *apointer;
fAODEvent->AddObject(obj);
TString bname(obj->GetName());
if (!fTreeE->FindBranch(bname.Data()))
{
Bool_t acceptAdd(kTRUE);
if ( TestBit(kDropUnspecifiedBranches) )
{
// check that this branch is in our list of specified ones...
// otherwise do not add it !
TIter next(fRepFiMap);
TObjString* p;
acceptAdd=kFALSE;
while ( ( p = static_cast<TObjString*>(next()) ) && !acceptAdd )
{
if ( p->String() == bname ) acceptAdd=kTRUE;
}
}
if ( acceptAdd )
{
// Do the same as if we book via
// TTree::Branch(TCollection*)
fObjectList->Add(obj);
const Int_t kSplitlevel = 99; // default value in TTree::Branch()
const Int_t kBufsize = 32000; // default value in TTree::Branch()
fTreeE->Bronch(bname.Data(), cname,
fAODEvent->GetList()->GetObjectRef(obj),
kBufsize, kSplitlevel - 1);
}
}
owd->cd();
}
//______________________________________________________________________________
Bool_t AliAODExtension::FinishEvent()
{
// Fill current event.
fNtotal++;
if (!IsFilteredAOD()) {
fAODEvent->MakeEntriesReferencable();
FillTree();
return kTRUE;
}
// Filtered AOD. Fill only if event is selected.
if (!fSelected) return kTRUE;
TIter next(fRepFiList);
AliAODBranchReplicator* repfi;
while ( ( repfi = static_cast<AliAODBranchReplicator*>(next()) ) )
{
repfi->ReplicateAndFilter(*fAODEvent);
}
fNpassed++;
FillTree();
fSelected = kFALSE; // so that next event will not be selected unless demanded
return kTRUE;
}
//______________________________________________________________________________
void AliAODExtension::FillTree()
{
//
// Fill AOD extension tree and check AutoFlush settings
//
Long64_t nbf = fTreeE->Fill();
// Check buffer size and set autoflush if fTreeBuffSize is reached
if (fTreeBuffSize>0 && fTreeE->GetAutoFlush()<0 &&
(fMemCountAOD += nbf)>fTreeBuffSize ) { // default limit is still not reached
nbf = fTreeE->GetZipBytes();
if (nbf>0) nbf = -nbf;
else nbf = fTreeE->GetEntries();
fTreeE->SetAutoFlush(nbf);
AliInfo(Form("Calling fTreeE->SetAutoFlush(%lld) | W:%lld T:%lld Z:%lld",
nbf,fMemCountAOD,fTreeE->GetTotBytes(),fTreeE->GetZipBytes()));
}
}
//______________________________________________________________________________
Bool_t AliAODExtension::Init(Option_t *option)
{
// Initialize IO.
AliCodeTimerAuto(GetName(),0);
if(!fAODEvent)
{
fAODEvent = new AliAODEvent();
}
TDirectory *owd = gDirectory;
TString opt(option);
opt.ToLower();
if (opt.Contains("proof"))
{
// proof
// Merging via files. Need to access analysis manager via interpreter.
gROOT->ProcessLine(Form("AliAnalysisDataContainer *c_common_out = AliAnalysisManager::GetAnalysisManager()->GetCommonOutputContainer();"));
gROOT->ProcessLine(Form("AliAnalysisManager::GetAnalysisManager()->OpenProofFile(c_common_out, \"RECREATE\", \"%s\");", fName.Data()));
fFileE = gFile;
}
else
{
fFileE = new TFile(GetName(), "RECREATE");
}
fTreeE = new TTree("aodTree", "AliAOD tree");
delete fObjectList;
fObjectList = new TList;
fObjectList->SetOwner(kFALSE); // be explicit we're not the owner...
TList* inputList = fAODEvent->GetList();
TIter next(inputList);
TObject* o;
while ( ( o = next() ) )
{
// Loop on the objects that are within the main AOD, and see what to do with them :
// - transmit them to our AOD as they are
// - filter them (by means of an AliAODBranchReplicator)
// - drop them completely
Bool_t mustKeep(kFALSE);
TString test(o->ClassName());
test.ToUpper();
// check if there is a replicator for the header
Bool_t headerHasReplicator = fRepFiMap && (fRepFiMap->FindObject(o->GetName())!=0x0);
if (test.BeginsWith("ALIAODHEADER") && !headerHasReplicator)
{
// do not allow to drop header branch
mustKeep=kTRUE;
}
if ( fRepFiMap && !mustKeep )
{
// we have some replicators, so let's see what the relevant one decides about this object
TObject* specified = fRepFiMap->FindObject(o->GetName()); // FindObject finds key=o->GetName() in the map
if (specified)
{
AliAODBranchReplicator* repfi = dynamic_cast<AliAODBranchReplicator*>(fRepFiMap->GetValue(o->GetName())); // GetValue gets the replicator corresponding to key=o->GetName()
if ( repfi )
{
TList* replicatedList = repfi->GetList();
if (replicatedList)
{
AliAODEvent::AssignIDtoCollection(replicatedList);
TIter nextRep(replicatedList);
TObject* objRep;
while ( ( objRep = nextRep() ) )
{
if ( !fObjectList->FindObject(objRep) ) // insure we're not adding several times the same object
{
fObjectList->Add(objRep);
}
}
}
else
{
AliError(Form("replicatedList from %s is null !",repfi->GetName()));
}
}
}
else
{
if ( !TestBit(kDropUnspecifiedBranches) )
{
// object o will be transmitted to the output AOD, unchanged
fObjectList->Add(o);
}
}
}
else
{
// no replicator, so decide based on the policy about dropping unspecified branches
if ( mustKeep || !TestBit(kDropUnspecifiedBranches) )
{
// object o will be transmitted to the output AOD, unchanged
fObjectList->Add(o);
}
}
}
if (fEnableReferences)
{
fTreeE->BranchRef();
}
fTreeE->Branch(fObjectList);
owd->cd();
return kTRUE;
}
//______________________________________________________________________________
void AliAODExtension::Print(Option_t* opt) const
{
// Print info about this extension
cout << opt << Form("%s - %s - %s - aod %p",IsFilteredAOD() ? "FilteredAOD" : "Extension",
GetName(),GetTitle(),GetAOD()) << endl;
if ( !fEnableReferences )
{
cout << opt << opt << "References are disabled ! Hope you know what you are doing !" << endl;
}
if ( TestBit(kDropUnspecifiedBranches) )
{
cout << opt << opt << "All branches not explicitely specified will be dropped" << endl;
}
TIter next(fRepFiMap);
TObjString* s;
while ( ( s = static_cast<TObjString*>(next()) ) )
{
AliAODBranchReplicator* br = static_cast<AliAODBranchReplicator*>(fRepFiMap->GetValue(s->String().Data()));
cout << opt << opt << "Branch " << s->String();
if (br)
{
cout << " will be filtered by class " << br->ClassName();
}
else
{
cout << " will be transmitted as is";
}
cout << endl;
}
}
//______________________________________________________________________________
void AliAODExtension::SetEvent(AliAODEvent* event)
{
// Connects to an external event
if (!IsFilteredAOD()) {
Error("SetEvent", "Not allowed to set external event for non filtered AOD's");
return;
}
fAODEvent = event;
}
//______________________________________________________________________________
void AliAODExtension::AddAODtoTreeUserInfo()
{
// Add aod event to tree user info
if (!fTreeE) return;
AliAODEvent* aodEvent(fAODEvent);
if ( IsFilteredAOD() )
{
// cannot attach fAODEvent (which is shared with our AliAODHandler mother)
// so we create a custom (empty) AliAODEvent
// Has also the advantage we can specify only the list of objects
// that are actually there in this filtered aod
//
aodEvent = new AliAODEvent;
TIter nextObj(fObjectList);
TObject* o;
while ( ( o = nextObj() ) )
{
aodEvent->AddObject(o);
}
}
fTreeE->GetUserInfo()->Add(aodEvent);
}
//______________________________________________________________________________
Bool_t AliAODExtension::TerminateIO()
{
// Terminate IO
if (TObject::TestBit(kFilteredAOD))
printf("AOD Filter %s: events processed: %d passed: %d\n", GetName(), fNtotal, fNpassed);
else
printf("AOD extension %s: events processed: %d\n", GetName(), fNtotal);
if (fFileE)
{
fFileE->Write();
fFileE->Close();
delete fFileE;
fFileE = 0;
fTreeE = 0;
fAODEvent = 0;
}
return kTRUE;
}
//______________________________________________________________________________
void AliAODExtension::FilterBranch(const char* branchName, AliAODBranchReplicator* repfi)
{
// Specify a filter/replicator for a given branch
//
// If repfi=0x0, this will disable the branch (in the output) completely.
//
// repfi is adopted by this class, i.e. user should not delete it.
//
// WARNING : branch name must be exact.
//
// See also the documentation for AliAODBranchReplicator class.
//
if (!fRepFiMap)
{
fRepFiMap = new TMap;
fRepFiMap->SetOwnerKeyValue(kTRUE,kTRUE);
fRepFiList = new TList;
fRepFiList->SetOwner(kFALSE);
}
fRepFiMap->Add(new TObjString(branchName),repfi);
if (repfi && !fRepFiList->FindObject(repfi))
{
// insure we get unique and non-null replicators in this list
fRepFiList->Add(repfi);
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (C) 2015 Mark Charlebois. 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 PX4 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 main.cpp
* Basic shell to execute builtin "apps"
*
* @author Mark Charlebois <[email protected]>
* @author Roman Bapst <[email protected]>
*/
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include "apps.h"
#include "px4_middleware.h"
#include "DriverFramework.hpp"
#include <termios.h>
namespace px4
{
void init_once(void);
}
using namespace std;
typedef int (*px4_main_t)(int argc, char *argv[]);
#define CMD_BUFF_SIZE 100
static bool _ExitFlag = false;
static struct termios orig_term;
extern "C" {
void _SigIntHandler(int sig_num);
void _SigIntHandler(int sig_num)
{
cout.flush();
cout << endl << "Exiting..." << endl;
cout.flush();
_ExitFlag = true;
}
void _SigFpeHandler(int sig_num);
void _SigFpeHandler(int sig_num)
{
cout.flush();
cout << endl << "floating point exception" << endl;
PX4_BACKTRACE();
cout.flush();
}
}
static void print_prompt()
{
cout.flush();
cout << "pxh> ";
cout.flush();
}
static void run_cmd(const vector<string> &appargs, bool exit_on_fail)
{
// command is appargs[0]
string command = appargs[0];
if (apps.find(command) != apps.end()) {
const char *arg[appargs.size() + 2];
unsigned int i = 0;
while (i < appargs.size() && appargs[i] != "") {
arg[i] = (char *)appargs[i].c_str();
++i;
}
arg[i] = (char *)0;
cout << endl;
int retval = apps[command](i, (char **)arg);
if (retval) {
cout << "Command '" << command << "' failed, returned " << retval << endl;
if (exit_on_fail && retval) {
exit(retval);
}
}
} else if (command.compare("help") == 0) {
list_builtins();
} else if (command.length() == 0) {
// Do nothing
} else {
cout << endl << "Invalid command: " << command << "\ntype 'help' for a list of commands" << endl;
}
}
static void usage()
{
cout << "./mainapp [-d] [startup_config] -h" << std::endl;
cout << " -d - Optional flag to run the app in daemon mode and does not listen for user input." <<
std::endl;
cout << " This is needed if mainapp is intended to be run as a upstart job on linux" << std::endl;
cout << "<startup_config> - config file for starting/stopping px4 modules" << std::endl;
cout << " -h - help/usage information" << std::endl;
}
static void process_line(string &line, bool exit_on_fail)
{
if (line.length() == 0) {
printf("\n");
}
vector<string> appargs(10);
stringstream(line) >> appargs[0] >> appargs[1] >> appargs[2] >> appargs[3] >> appargs[4] >> appargs[5] >> appargs[6] >>
appargs[7] >> appargs[8] >> appargs[9];
run_cmd(appargs, exit_on_fail);
}
static void restore_term(void)
{
cout << "Restoring terminal\n";
tcsetattr(0, TCSANOW, &orig_term);
}
bool px4_exit_requested(void) {
return _ExitFlag;
}
int main(int argc, char **argv)
{
bool daemon_mode = false;
bool chroot_on = false;
tcgetattr(0, &orig_term);
atexit(restore_term);
struct sigaction sig_int;
memset(&sig_int, 0, sizeof(struct sigaction));
sig_int.sa_handler = _SigIntHandler;
sig_int.sa_flags = 0;// not SA_RESTART!;
struct sigaction sig_fpe;
memset(&sig_fpe, 0, sizeof(struct sigaction));
sig_fpe.sa_handler = _SigFpeHandler;
sig_fpe.sa_flags = 0;// not SA_RESTART!;
sigaction(SIGINT, &sig_int, NULL);
//sigaction(SIGTERM, &sig_int, NULL);
sigaction(SIGFPE, &sig_fpe, NULL);
int index = 1;
char *commands_file = nullptr;
while (index < argc) {
if (argv[index][0] == '-') {
// the arg starts with -
if (strcmp(argv[index], "-d") == 0) {
daemon_mode = true;
} else if (strcmp(argv[index], "-h") == 0) {
usage();
return 0;
} else if (strcmp(argv[index], "-c") == 0) {
chroot_on = true;
} else {
PX4_WARN("Unknown/unhandled parameter: %s", argv[index]);
return 1;
}
} else {
// this is an argument that does not have '-' prefix; treat it like a file name
ifstream infile(argv[index]);
if (infile.good()) {
infile.close();
commands_file = argv[index];
} else {
PX4_WARN("Error opening file: %s", argv[index]);
return -1;
}
}
++index;
}
DriverFramework::Framework::initialize();
px4::init_once();
px4::init(argc, argv, "mainapp");
// if commandfile is present, process the commands from the file
if (commands_file != nullptr) {
ifstream infile(commands_file);
if (infile.is_open()) {
for (string line; getline(infile, line, '\n');) {
if (px4_exit_requested()) {
break;
}
// TODO: this should be true but for that we have to check all startup files
process_line(line, false);
}
} else {
PX4_WARN("Error opening file: %s", commands_file);
}
}
if (chroot_on) {
// Lock this application in the current working dir
// this is not an attempt to secure the environment,
// rather, to replicate a deployed file system.
#ifdef PATH_MAX
const unsigned path_max_len = PATH_MAX;
#else
const unsigned path_max_len = 1024;
#endif
char pwd_path[path_max_len];
const char *folderpath = "/rootfs/";
if (nullptr == getcwd(pwd_path, sizeof(pwd_path))) {
PX4_ERR("Failed acquiring working dir, abort.");
exit(1);
}
if (nullptr == strcat(pwd_path, folderpath)) {
PX4_ERR("Failed completing path, abort.");
exit(1);
}
if (chroot(pwd_path)) {
PX4_ERR("Failed chrooting application, path: %s, error: %s.", pwd_path, strerror(errno));
exit(1);
}
if (chdir("/")) {
PX4_ERR("Failed changing to root dir, path: %s, error: %s.", pwd_path, strerror(errno));
exit(1);
}
}
if (!daemon_mode) {
string mystr = "";
string string_buffer[CMD_BUFF_SIZE];
int buf_ptr_write = 0;
int buf_ptr_read = 0;
print_prompt();
// change input mode so that we can manage shell
struct termios term;
tcgetattr(0, &term);
term.c_lflag &= ~ICANON;
term.c_lflag &= ~ECHO;
tcsetattr(0, TCSANOW, &term);
setbuf(stdin, NULL);
while (!_ExitFlag) {
char c = getchar();
switch (c) {
case 127: // backslash
if (mystr.length() > 0) {
mystr.pop_back();
printf("%c[2K", 27); // clear line
cout << (char)13;
print_prompt();
cout << mystr;
}
break;
case'\n': // user hit enter
if (buf_ptr_write == CMD_BUFF_SIZE) {
buf_ptr_write = 0;
}
if (buf_ptr_write > 0) {
if (mystr != string_buffer[buf_ptr_write - 1]) {
string_buffer[buf_ptr_write] = mystr;
buf_ptr_write++;
}
} else {
if (mystr != string_buffer[CMD_BUFF_SIZE - 1]) {
string_buffer[buf_ptr_write] = mystr;
buf_ptr_write++;
}
}
process_line(mystr, false);
mystr = "";
buf_ptr_read = buf_ptr_write;
print_prompt();
break;
case '\033': { // arrow keys
c = getchar(); // skip first one, does not have the info
c = getchar();
// arrow up
if (c == 'A') {
buf_ptr_read--;
// arrow down
} else if (c == 'B') {
if (buf_ptr_read < buf_ptr_write) {
buf_ptr_read++;
}
} else {
// TODO: Support editing current line
}
if (buf_ptr_read < 0) {
buf_ptr_read = 0;
}
string saved_cmd = string_buffer[buf_ptr_read];
printf("%c[2K", 27);
cout << (char)13;
mystr = saved_cmd;
print_prompt();
cout << mystr;
break;
}
default: // any other input
cout << c;
mystr += c;
break;
}
}
} else {
while (!_ExitFlag) {
usleep(100000);
}
}
// TODO: Always try to stop muorb for QURT because px4_task_is_running doesn't seem to work.
if (true) {
//if (px4_task_is_running("muorb")) {
// sending muorb stop is needed if it is running to exit cleanly
vector<string> muorb_stop_cmd = { "muorb", "stop" };
run_cmd(muorb_stop_cmd, !daemon_mode);
}
vector<string> shutdown_cmd = { "shutdown" };
run_cmd(shutdown_cmd, true);
DriverFramework::Framework::shutdown();
return OK;
}
<commit_msg>POSIX: Fix code style of main app<commit_after>/****************************************************************************
*
* Copyright (C) 2015 Mark Charlebois. 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 PX4 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 main.cpp
* Basic shell to execute builtin "apps"
*
* @author Mark Charlebois <[email protected]>
* @author Roman Bapst <[email protected]>
*/
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include "apps.h"
#include "px4_middleware.h"
#include "DriverFramework.hpp"
#include <termios.h>
namespace px4
{
void init_once(void);
}
using namespace std;
typedef int (*px4_main_t)(int argc, char *argv[]);
#define CMD_BUFF_SIZE 100
static bool _ExitFlag = false;
static struct termios orig_term;
extern "C" {
void _SigIntHandler(int sig_num);
void _SigIntHandler(int sig_num)
{
cout.flush();
cout << endl << "Exiting..." << endl;
cout.flush();
_ExitFlag = true;
}
void _SigFpeHandler(int sig_num);
void _SigFpeHandler(int sig_num)
{
cout.flush();
cout << endl << "floating point exception" << endl;
PX4_BACKTRACE();
cout.flush();
}
}
static void print_prompt()
{
cout.flush();
cout << "pxh> ";
cout.flush();
}
static void run_cmd(const vector<string> &appargs, bool exit_on_fail)
{
// command is appargs[0]
string command = appargs[0];
if (apps.find(command) != apps.end()) {
const char *arg[appargs.size() + 2];
unsigned int i = 0;
while (i < appargs.size() && appargs[i] != "") {
arg[i] = (char *)appargs[i].c_str();
++i;
}
arg[i] = (char *)0;
cout << endl;
int retval = apps[command](i, (char **)arg);
if (retval) {
cout << "Command '" << command << "' failed, returned " << retval << endl;
if (exit_on_fail && retval) {
exit(retval);
}
}
} else if (command.compare("help") == 0) {
list_builtins();
} else if (command.length() == 0) {
// Do nothing
} else {
cout << endl << "Invalid command: " << command << "\ntype 'help' for a list of commands" << endl;
}
}
static void usage()
{
cout << "./mainapp [-d] [startup_config] -h" << std::endl;
cout << " -d - Optional flag to run the app in daemon mode and does not listen for user input." <<
std::endl;
cout << " This is needed if mainapp is intended to be run as a upstart job on linux" << std::endl;
cout << "<startup_config> - config file for starting/stopping px4 modules" << std::endl;
cout << " -h - help/usage information" << std::endl;
}
static void process_line(string &line, bool exit_on_fail)
{
if (line.length() == 0) {
printf("\n");
}
vector<string> appargs(10);
stringstream(line) >> appargs[0] >> appargs[1] >> appargs[2] >> appargs[3] >> appargs[4] >> appargs[5] >> appargs[6] >>
appargs[7] >> appargs[8] >> appargs[9];
run_cmd(appargs, exit_on_fail);
}
static void restore_term(void)
{
cout << "Restoring terminal\n";
tcsetattr(0, TCSANOW, &orig_term);
}
bool px4_exit_requested(void)
{
return _ExitFlag;
}
int main(int argc, char **argv)
{
bool daemon_mode = false;
bool chroot_on = false;
tcgetattr(0, &orig_term);
atexit(restore_term);
struct sigaction sig_int;
memset(&sig_int, 0, sizeof(struct sigaction));
sig_int.sa_handler = _SigIntHandler;
sig_int.sa_flags = 0;// not SA_RESTART!;
struct sigaction sig_fpe;
memset(&sig_fpe, 0, sizeof(struct sigaction));
sig_fpe.sa_handler = _SigFpeHandler;
sig_fpe.sa_flags = 0;// not SA_RESTART!;
sigaction(SIGINT, &sig_int, NULL);
//sigaction(SIGTERM, &sig_int, NULL);
sigaction(SIGFPE, &sig_fpe, NULL);
int index = 1;
char *commands_file = nullptr;
while (index < argc) {
if (argv[index][0] == '-') {
// the arg starts with -
if (strcmp(argv[index], "-d") == 0) {
daemon_mode = true;
} else if (strcmp(argv[index], "-h") == 0) {
usage();
return 0;
} else if (strcmp(argv[index], "-c") == 0) {
chroot_on = true;
} else {
PX4_WARN("Unknown/unhandled parameter: %s", argv[index]);
return 1;
}
} else {
// this is an argument that does not have '-' prefix; treat it like a file name
ifstream infile(argv[index]);
if (infile.good()) {
infile.close();
commands_file = argv[index];
} else {
PX4_WARN("Error opening file: %s", argv[index]);
return -1;
}
}
++index;
}
DriverFramework::Framework::initialize();
px4::init_once();
px4::init(argc, argv, "mainapp");
// if commandfile is present, process the commands from the file
if (commands_file != nullptr) {
ifstream infile(commands_file);
if (infile.is_open()) {
for (string line; getline(infile, line, '\n');) {
if (px4_exit_requested()) {
break;
}
// TODO: this should be true but for that we have to check all startup files
process_line(line, false);
}
} else {
PX4_WARN("Error opening file: %s", commands_file);
}
}
if (chroot_on) {
// Lock this application in the current working dir
// this is not an attempt to secure the environment,
// rather, to replicate a deployed file system.
#ifdef PATH_MAX
const unsigned path_max_len = PATH_MAX;
#else
const unsigned path_max_len = 1024;
#endif
char pwd_path[path_max_len];
const char *folderpath = "/rootfs/";
if (nullptr == getcwd(pwd_path, sizeof(pwd_path))) {
PX4_ERR("Failed acquiring working dir, abort.");
exit(1);
}
if (nullptr == strcat(pwd_path, folderpath)) {
PX4_ERR("Failed completing path, abort.");
exit(1);
}
if (chroot(pwd_path)) {
PX4_ERR("Failed chrooting application, path: %s, error: %s.", pwd_path, strerror(errno));
exit(1);
}
if (chdir("/")) {
PX4_ERR("Failed changing to root dir, path: %s, error: %s.", pwd_path, strerror(errno));
exit(1);
}
}
if (!daemon_mode) {
string mystr = "";
string string_buffer[CMD_BUFF_SIZE];
int buf_ptr_write = 0;
int buf_ptr_read = 0;
print_prompt();
// change input mode so that we can manage shell
struct termios term;
tcgetattr(0, &term);
term.c_lflag &= ~ICANON;
term.c_lflag &= ~ECHO;
tcsetattr(0, TCSANOW, &term);
setbuf(stdin, NULL);
while (!_ExitFlag) {
char c = getchar();
switch (c) {
case 127: // backslash
if (mystr.length() > 0) {
mystr.pop_back();
printf("%c[2K", 27); // clear line
cout << (char)13;
print_prompt();
cout << mystr;
}
break;
case'\n': // user hit enter
if (buf_ptr_write == CMD_BUFF_SIZE) {
buf_ptr_write = 0;
}
if (buf_ptr_write > 0) {
if (mystr != string_buffer[buf_ptr_write - 1]) {
string_buffer[buf_ptr_write] = mystr;
buf_ptr_write++;
}
} else {
if (mystr != string_buffer[CMD_BUFF_SIZE - 1]) {
string_buffer[buf_ptr_write] = mystr;
buf_ptr_write++;
}
}
process_line(mystr, false);
mystr = "";
buf_ptr_read = buf_ptr_write;
print_prompt();
break;
case '\033': { // arrow keys
c = getchar(); // skip first one, does not have the info
c = getchar();
// arrow up
if (c == 'A') {
buf_ptr_read--;
// arrow down
} else if (c == 'B') {
if (buf_ptr_read < buf_ptr_write) {
buf_ptr_read++;
}
} else {
// TODO: Support editing current line
}
if (buf_ptr_read < 0) {
buf_ptr_read = 0;
}
string saved_cmd = string_buffer[buf_ptr_read];
printf("%c[2K", 27);
cout << (char)13;
mystr = saved_cmd;
print_prompt();
cout << mystr;
break;
}
default: // any other input
cout << c;
mystr += c;
break;
}
}
} else {
while (!_ExitFlag) {
usleep(100000);
}
}
// TODO: Always try to stop muorb for QURT because px4_task_is_running doesn't seem to work.
if (true) {
//if (px4_task_is_running("muorb")) {
// sending muorb stop is needed if it is running to exit cleanly
vector<string> muorb_stop_cmd = { "muorb", "stop" };
run_cmd(muorb_stop_cmd, !daemon_mode);
}
vector<string> shutdown_cmd = { "shutdown" };
run_cmd(shutdown_cmd, true);
DriverFramework::Framework::shutdown();
return OK;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013-2016 Anton Kozhevnikov, Thomas Schulthess
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/** \file xc_functional.hpp
*
* \brief Contains implementation of sirius::XC_functional class.
*/
#ifndef __XC_FUNCTIONAL_HPP__
#define __XC_FUNCTIONAL_HPP__
#include <xc.h>
#include <string.h>
#include "xc_functional_base.hpp"
#include "SDDK/fft3d.hpp"
#ifdef USE_VDWXC
#include <vdwxc.h>
#include <vdwxc_mpi.h>
#endif
namespace sirius {
/// Interface class to Libxc.
class XC_functional : public XC_functional_base
{
private:
// I can not use a generic void pointer because xc_func_type is a structure
// while wdv_functional_ is a pointer over structure.
#ifdef USE_VDWXC
vdwxc_data handler_vdw_{nullptr};
bool vdw_functional_{false};
#endif
/* forbid copy constructor */
XC_functional(const XC_functional& src) = delete;
/* forbid assigment operator */
XC_functional& operator=(const XC_functional& src) = delete;
public:
/* we need the context because libvdwxc asks for lattice vectors and fft parameters */
XC_functional(const FFT3D& fft, const matrix3d<double>& lattice_vectors_, const std::string libxc_name__, int num_spins__)
: XC_functional_base(libxc_name__, num_spins__)
{
#ifdef USE_VDWXC
/* return immediately if the functional_base class is initialized */
if (this->libxc_initialized_) {
return;
}
/* test if have van der walls functionals types */
bool test = (libxc_name_ == "XC_FUNC_VDWDF");
test = test || (libxc_name_ == "XC_FUNC_VDWDF2");
test = test || (libxc_name_ == "XC_FUNC_VDWDFCX");
int func_ = -1;
if (libxc_name__ == "XC_FUNC_VDWDF") {
func_ = FUNC_VDWDF;
}
if (libxc_name__ == "XC_FUNC_VDWDF2") {
func_ = FUNC_VDWDF2;
}
if (libxc_name__ == "XC_FUNC_VDWDFCX") {
func_ = FUNC_VDWDFCX;
}
if (test) {
if (num_spins__ == 1) {
// non magnetic case
handler_vdw_ = vdwxc_new(func_);
} else {
// magnetic case
handler_vdw_ = vdwxc_new_spin(func_);
}
if (!handler_vdw_) {
std::stringstream s;
s << "VDW functional lib could not be initialized";
TERMINATE(s);
}
double v1[3] = { lattice_vectors_(0, 0), lattice_vectors_(1, 0), lattice_vectors_(2, 0) };
double v2[3] = { lattice_vectors_(0, 1), lattice_vectors_(1, 1), lattice_vectors_(2, 1) };
double v3[3] = { lattice_vectors_(0, 2), lattice_vectors_(1, 2), lattice_vectors_(2, 2) };
vdwxc_set_unit_cell(handler_vdw_,
fft.size(0),
fft.size(1),
fft.size(2),
v1[0], v1[1], v1[2],
v2[0], v2[1], v2[2],
v3[0], v3[1], v3[2]);
if (fft.comm().size() == 1) {
vdwxc_init_serial(handler_vdw_);
} else {
vdwxc_init_mpi(handler_vdw_, fft.comm().mpi_comm());
}
vdw_functional_ = true;
return;
} else {
/* it means that the functional does not exist either in vdw or xc libraries */
std::stringstream s;
s << "XC functional " << libxc_name__ << " is unknown";
TERMINATE(s);
}
#else
if (this->libxc_initialized_) {
return;
} else {
/* it means that the functional does not exist either in vdw or xc libraries */
std::stringstream s;
s << "XC functional " << libxc_name__ << " is unknown";
TERMINATE(s);
}
#endif /* USE_VDWXC */
}
XC_functional(XC_functional&& src__)
:XC_functional_base(std::move(src__))
{
#ifdef USE_VDWXC
this->handler_vdw_ = src__.handler_vdw_;
this->vdw_functional_ = src__.vdw_functional_;
src__.vdw_functional_ = false;
#endif
}
~XC_functional()
{
#ifdef USE_VDWXC
if (this->vdw_functional_) {
vdwxc_finalize(&this->handler_vdw_);
this->vdw_functional_ = false;
return;
}
#endif
}
const std::string refs() const
{
#ifdef USE_VDWXC
std::stringstream s;
if (vdw_functional_) {
s << "==============================================================================\n";
s << " \n";
s << "Warning : these functionals should be used in combination with GGA functionals\n";
s << " \n";
s << "==============================================================================\n";
s << "\n";
s << "A. H. Larsen, M. Kuisma, J. Löfgren, Y. Pouillon, P. Erhart, and P. Hyldgaard, ";
s << "Modelling Simul. Mater. Sci. Eng. 25, 065004 (2017) (10.1088/1361-651X/aa7320)\n";
return s.str();
}
#endif
return XC_functional_base::refs();
}
int family() const
{
#ifdef USE_VDWXC
if (this->vdw_functional_ == true) {
return XC_FAMILY_UNKNOWN;
}
#endif
return XC_functional_base::family();
}
bool is_vdw() const
{
#ifdef USE_VDWXC
return this->vdw_functional_;
#else
return false;
#endif
}
int kind() const
{
#ifdef USE_VDWXC
if (this->vdw_functional_ == true) {
return -1;
}
#endif
return XC_functional_base::kind();
}
#ifdef USE_VDWXC
/// get van der walls contribution for the exchange term
void get_vdw(double* rho,
double* sigma,
double* vrho,
double* vsigma,
double* energy__)
{
if (!is_vdw()) {
TERMINATE("Error wrong vdw XC");
}
energy__[0] = vdwxc_calculate(handler_vdw_, rho, sigma, vrho, vsigma);
}
/// get van der walls contribution to the exchange term magnetic case
void get_vdw(double *rho_up, double *rho_down,
double *sigma_up, double *sigma_down,
double *vrho_up, double *vrho_down,
double *vsigma_up, double *vsigma_down,
double *energy__)
{
if (!is_vdw()) {
TERMINATE("Error wrong XC");
}
energy__[0] = vdwxc_calculate_spin(handler_vdw_, rho_up, rho_down,
sigma_up , sigma_down,
vrho_up, vrho_down,
vsigma_up, vsigma_down);
}
#endif
};
}
#endif // __XC_FUNCTIONAL_H__
<commit_msg>fallback to serial if libvdwxc has not been compiled with MPI<commit_after>// Copyright (c) 2013-2016 Anton Kozhevnikov, Thomas Schulthess
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/** \file xc_functional.hpp
*
* \brief Contains implementation of sirius::XC_functional class.
*/
#ifndef __XC_FUNCTIONAL_HPP__
#define __XC_FUNCTIONAL_HPP__
#include <xc.h>
#include <string.h>
#include "xc_functional_base.hpp"
#include "SDDK/fft3d.hpp"
#ifdef USE_VDWXC
#include <vdwxc.h>
#if VDWXC_FFTW_MPI == 1
#include <vdwxc_mpi.h>
#endif
#endif
namespace sirius {
/// Interface class to Libxc.
class XC_functional : public XC_functional_base
{
private:
// I can not use a generic void pointer because xc_func_type is a structure
// while wdv_functional_ is a pointer over structure.
#ifdef USE_VDWXC
vdwxc_data handler_vdw_{nullptr};
bool vdw_functional_{false};
#endif
/* forbid copy constructor */
XC_functional(const XC_functional& src) = delete;
/* forbid assigment operator */
XC_functional& operator=(const XC_functional& src) = delete;
public:
/* we need the context because libvdwxc asks for lattice vectors and fft parameters */
XC_functional(const FFT3D& fft, const matrix3d<double>& lattice_vectors_, const std::string libxc_name__, int num_spins__)
: XC_functional_base(libxc_name__, num_spins__)
{
#ifdef USE_VDWXC
/* return immediately if the functional_base class is initialized */
if (this->libxc_initialized_) {
return;
}
/* test if have van der walls functionals types */
bool test = (libxc_name_ == "XC_FUNC_VDWDF");
test = test || (libxc_name_ == "XC_FUNC_VDWDF2");
test = test || (libxc_name_ == "XC_FUNC_VDWDFCX");
int func_ = -1;
if (libxc_name__ == "XC_FUNC_VDWDF") {
func_ = FUNC_VDWDF;
}
if (libxc_name__ == "XC_FUNC_VDWDF2") {
func_ = FUNC_VDWDF2;
}
if (libxc_name__ == "XC_FUNC_VDWDFCX") {
func_ = FUNC_VDWDFCX;
}
if (test) {
if (num_spins__ == 1) {
// non magnetic case
handler_vdw_ = vdwxc_new(func_);
} else {
// magnetic case
handler_vdw_ = vdwxc_new_spin(func_);
}
if (!handler_vdw_) {
std::stringstream s;
s << "VDW functional lib could not be initialized";
TERMINATE(s);
}
double v1[3] = { lattice_vectors_(0, 0), lattice_vectors_(1, 0), lattice_vectors_(2, 0) };
double v2[3] = { lattice_vectors_(0, 1), lattice_vectors_(1, 1), lattice_vectors_(2, 1) };
double v3[3] = { lattice_vectors_(0, 2), lattice_vectors_(1, 2), lattice_vectors_(2, 2) };
vdwxc_set_unit_cell(handler_vdw_,
fft.size(0),
fft.size(1),
fft.size(2),
v1[0], v1[1], v1[2],
v2[0], v2[1], v2[2],
v3[0], v3[1], v3[2]);
if (fft.comm().size() == 1) {
vdwxc_init_serial(handler_vdw_);
} else {
#if VDWXC_FFTW_MPI == 1
vdwxc_init_mpi(handler_vdw_, fft.comm().mpi_comm());
#else
vdwxc_init_serial(handler_vdw_);
#endif
}
vdw_functional_ = true;
return;
} else {
/* it means that the functional does not exist either in vdw or xc libraries */
std::stringstream s;
s << "XC functional " << libxc_name__ << " is unknown";
TERMINATE(s);
}
#else
if (this->libxc_initialized_) {
return;
} else {
/* it means that the functional does not exist either in vdw or xc libraries */
std::stringstream s;
s << "XC functional " << libxc_name__ << " is unknown";
TERMINATE(s);
}
#endif /* USE_VDWXC */
}
XC_functional(XC_functional&& src__)
:XC_functional_base(std::move(src__))
{
#ifdef USE_VDWXC
this->handler_vdw_ = src__.handler_vdw_;
this->vdw_functional_ = src__.vdw_functional_;
src__.vdw_functional_ = false;
#endif
}
~XC_functional()
{
#ifdef USE_VDWXC
if (this->vdw_functional_) {
vdwxc_finalize(&this->handler_vdw_);
this->vdw_functional_ = false;
return;
}
#endif
}
const std::string refs() const
{
#ifdef USE_VDWXC
std::stringstream s;
if (vdw_functional_) {
s << "==============================================================================\n";
s << " \n";
s << "Warning : these functionals should be used in combination with GGA functionals\n";
s << " \n";
s << "==============================================================================\n";
s << "\n";
s << "A. H. Larsen, M. Kuisma, J. Löfgren, Y. Pouillon, P. Erhart, and P. Hyldgaard, ";
s << "Modelling Simul. Mater. Sci. Eng. 25, 065004 (2017) (10.1088/1361-651X/aa7320)\n";
return s.str();
}
#endif
return XC_functional_base::refs();
}
int family() const
{
#ifdef USE_VDWXC
if (this->vdw_functional_ == true) {
return XC_FAMILY_UNKNOWN;
}
#endif
return XC_functional_base::family();
}
bool is_vdw() const
{
#ifdef USE_VDWXC
return this->vdw_functional_;
#else
return false;
#endif
}
int kind() const
{
#ifdef USE_VDWXC
if (this->vdw_functional_ == true) {
return -1;
}
#endif
return XC_functional_base::kind();
}
#ifdef USE_VDWXC
/// get van der walls contribution for the exchange term
void get_vdw(double* rho,
double* sigma,
double* vrho,
double* vsigma,
double* energy__)
{
if (!is_vdw()) {
TERMINATE("Error wrong vdw XC");
}
energy__[0] = vdwxc_calculate(handler_vdw_, rho, sigma, vrho, vsigma);
}
/// get van der walls contribution to the exchange term magnetic case
void get_vdw(double *rho_up, double *rho_down,
double *sigma_up, double *sigma_down,
double *vrho_up, double *vrho_down,
double *vsigma_up, double *vsigma_down,
double *energy__)
{
if (!is_vdw()) {
TERMINATE("Error wrong XC");
}
energy__[0] = vdwxc_calculate_spin(handler_vdw_, rho_up, rho_down,
sigma_up , sigma_down,
vrho_up, vrho_down,
vsigma_up, vsigma_down);
}
#endif
};
}
#endif // __XC_FUNCTIONAL_H__
<|endoftext|> |
<commit_before>/* Copyright (c) 2013 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any purpose
* with or without fee is hereby granted, provided that the above copyright
* notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
* RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
* CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "Common.h"
#include "ExternalStorage.h"
namespace RAMCloud {
/**
* Constructor for ExternalStorage objects.
*/
ExternalStorage::ExternalStorage()
: workspace("/")
, fullName(workspace)
, testName(NULL)
{}
// See header file for documentation.
const char*
ExternalStorage::getWorkspace()
{
return workspace.c_str();
}
// See header file for documentation.
void
ExternalStorage::setWorkspace(const char* pathPrefix)
{
workspace = pathPrefix;
fullName = pathPrefix;
assert(pathPrefix[0] == '/');
assert(pathPrefix[workspace.size()-1] == '/');
}
/**
* Return the absolute node name (i.e., one that begins with "/") that
* corresponds to the \c name argument. It is provided as a convenience for
* subclasses.
*
* \param name
* Name of a node; may be either relative or absolute.
*
* \return
* If \c name starts with "/", then it is returned. Otherwise, an
* absolute node name is formed by concatenating the workspace name
* with \c name, and this is returned. Note: the return value is stored
* in a string in the ExternalStorage object, and will be overwritten
* the next time this method is invoked. If you need the result to
* last a long time, you better copy it. This method is not thread-safe:
* it assumes the caller has acquired a lock, so that no one else can
* invoke this method concurrently.
*/
const char*
ExternalStorage::getFullName(const char* name)
{
if (testName != NULL) {
return testName;
}
if (name[0] == '/') {
return name;
}
fullName.resize(workspace.size());
fullName.append(name);
return fullName.c_str();
}
/**
* Construct an Object.
*
* \param name
* Name of the object; NULL-terminated string. A local copy will
* be made in this Object.
* \param value
* Value of the object, or NULL if none. A local copy will
* be made in this Object.
* \param length
* Length of value, in bytes.
*/
ExternalStorage::Object::Object(const char* name, const char* value, int length)
: name(NULL)
, value(NULL)
, length(0)
{
size_t nameLength = strlen(name) + 1;
this->name = static_cast<char*>(malloc(nameLength));
memcpy(this->name, name, nameLength);
if ((value != NULL) && (length > 0)) {
this->value = static_cast<char*>(malloc(length));
memcpy(this->value, value, length);
this->length = length;
}
}
/**
* Destructor for Objects (must free storage).
*/
ExternalStorage::Object::~Object()
{
free(name);
free(value);
}
} // namespace RAMCloud
<commit_msg>Fixed lint from "make check".<commit_after>/* Copyright (c) 2013 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any purpose
* with or without fee is hereby granted, provided that the above copyright
* notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
* RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
* CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "Common.h"
#include "ExternalStorage.h"
namespace RAMCloud {
/**
* Constructor for ExternalStorage objects.
*/
ExternalStorage::ExternalStorage()
: workspace("/")
, fullName(workspace)
, testName(NULL)
{}
// See header file for documentation.
const char*
ExternalStorage::getWorkspace()
{
return workspace.c_str();
}
// See header file for documentation.
void
ExternalStorage::setWorkspace(const char* pathPrefix)
{
workspace = pathPrefix;
fullName = pathPrefix;
assert(pathPrefix[0] == '/');
assert(pathPrefix[workspace.size()-1] == '/');
}
/**
* Return the absolute node name (i.e., one that begins with "/") that
* corresponds to the \c name argument. It is provided as a convenience for
* subclasses.
*
* \param name
* Name of a node; may be either relative or absolute.
*
* \return
* If \c name starts with "/", then it is returned. Otherwise, an
* absolute node name is formed by concatenating the workspace name
* with \c name, and this is returned. Note: the return value is stored
* in a string in the ExternalStorage object, and will be overwritten
* the next time this method is invoked. If you need the result to
* last a long time, you better copy it. This method is not thread-safe:
* it assumes the caller has acquired a lock, so that no one else can
* invoke this method concurrently.
*/
const char*
ExternalStorage::getFullName(const char* name)
{
if (testName != NULL) {
return testName;
}
if (name[0] == '/') {
return name;
}
fullName.resize(workspace.size());
fullName.append(name);
return fullName.c_str();
}
/**
* Construct an Object.
*
* \param name
* Name of the object; NULL-terminated string. A local copy will
* be made in this Object.
* \param value
* Value of the object, or NULL if none. A local copy will
* be made in this Object.
* \param length
* Length of value, in bytes.
*/
ExternalStorage::Object::Object(const char* name, const char* value, int length)
: name(NULL)
, value(NULL)
, length(0)
{
size_t nameLength = strlen(name) + 1;
this->name = static_cast<char*>(malloc(nameLength));
memcpy(this->name, name, nameLength);
if ((value != NULL) && (length > 0)) {
this->value = static_cast<char*>(malloc(length));
memcpy(this->value, value, length);
this->length = length;
}
}
/**
* Destructor for Objects (must free storage).
*/
ExternalStorage::Object::~Object()
{
free(name);
free(value);
}
} // namespace RAMCloud
<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Rüdiger Sonderfeld
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.
*/
#ifndef FLUSSPFERD_PLUGINS_GMP_RATIONAL_HPP
#define FLUSSPFERD_PLUGINS_GMP_RATIONAL_HPP
#include "flusspferd/class.hpp"
#include "flusspferd/create.hpp"
#include <gmpxx.h>
//#include "Integer.hpp"
namespace multi_precission {
class Integer;
struct Rational : public flusspferd::native_object_base {
struct class_info : flusspferd::class_info {
static char const *constructor_name() {
return "Rational";
}
static char const *full_name() {
return "Rational";
}
static object create_prototype() {
flusspferd::object proto = flusspferd::create_object();
create_native_method(proto, "get_double", &Rational::get_double);
create_native_method(proto, "get_string", &Rational::get_string);
create_native_method(proto, "get_string_base", &Rational::get_string_base);
create_native_method(proto, "sgn", &Rational::sgn);
create_native_method(proto, "abs", &Rational::abs);
create_native_method(proto, "canonicalize", &Rational::canonicalize);
create_native_method(proto, "get_num", &Rational::get_num);
create_native_method(proto, "get_den", &Rational::get_den);
create_native_method(proto, "cmp", &Rational::cmp);
create_native_method(proto, "add", &Rational::add);
create_native_method(proto, "sub", &Rational::sub);
create_native_method(proto, "mul", &Rational::mul);
create_native_method(proto, "div", &Rational::div);
return proto;
}
};
mpq_class mp;
Rational(flusspferd::object const &self, mpq_class const &mp);
Rational(flusspferd::object const &self, flusspferd::call_context &x);
double get_double() /*const*/;
std::string get_string() /*const*/;
std::string get_string_base(int base) /*const*/;
template<typename T>
static Rational &create_rational(T mp) {
return flusspferd::create_native_object<Rational>(object(), mpq_class(mp));
}
int sgn() /*const*/;
Rational &abs() /*const*/;
void canonicalize();
Integer &get_num() /*const*/;
Integer &get_den() /*const*/;
// operators
void cmp(flusspferd::call_context &x) /*const*/;
void add(flusspferd::call_context &x) /*const*/;
void sub(flusspferd::call_context &x) /*const*/;
void mul(flusspferd::call_context &x) /*const*/;
void div(flusspferd::call_context &x) /*const*/;
};
}
#endif
<commit_msg>plugins.gmp: minor cleanup<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Rüdiger Sonderfeld
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.
*/
#ifndef FLUSSPFERD_PLUGINS_GMP_RATIONAL_HPP
#define FLUSSPFERD_PLUGINS_GMP_RATIONAL_HPP
#include "flusspferd/class.hpp"
#include "flusspferd/create.hpp"
#include <gmpxx.h>
namespace multi_precission {
class Integer;
struct Rational : public flusspferd::native_object_base {
struct class_info : flusspferd::class_info {
static char const *constructor_name() {
return "Rational";
}
static char const *full_name() {
return "Rational";
}
static object create_prototype() {
flusspferd::object proto = flusspferd::create_object();
create_native_method(proto, "get_double", &Rational::get_double);
create_native_method(proto, "get_string", &Rational::get_string);
create_native_method(proto, "get_string_base", &Rational::get_string_base);
create_native_method(proto, "sgn", &Rational::sgn);
create_native_method(proto, "abs", &Rational::abs);
create_native_method(proto, "canonicalize", &Rational::canonicalize);
create_native_method(proto, "get_num", &Rational::get_num);
create_native_method(proto, "get_den", &Rational::get_den);
create_native_method(proto, "cmp", &Rational::cmp);
create_native_method(proto, "add", &Rational::add);
create_native_method(proto, "sub", &Rational::sub);
create_native_method(proto, "mul", &Rational::mul);
create_native_method(proto, "div", &Rational::div);
return proto;
}
};
mpq_class mp;
Rational(flusspferd::object const &self, mpq_class const &mp);
Rational(flusspferd::object const &self, flusspferd::call_context &x);
double get_double() /*const*/;
std::string get_string() /*const*/;
std::string get_string_base(int base) /*const*/;
template<typename T>
static Rational &create_rational(T mp) {
return flusspferd::create_native_object<Rational>(object(), mpq_class(mp));
}
int sgn() /*const*/;
Rational &abs() /*const*/;
void canonicalize();
Integer &get_num() /*const*/;
Integer &get_den() /*const*/;
// operators
void cmp(flusspferd::call_context &x) /*const*/;
void add(flusspferd::call_context &x) /*const*/;
void sub(flusspferd::call_context &x) /*const*/;
void mul(flusspferd::call_context &x) /*const*/;
void div(flusspferd::call_context &x) /*const*/;
};
}
#endif
<|endoftext|> |
<commit_before>//===--- GenTypes.cpp - Swift IR Generation For Types ---------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements IR generation for types in Swift.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/Decl.h"
#include "swift/AST/Types.h"
#include "llvm/DerivedTypes.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Target/TargetData.h"
#include "GenType.h"
#include "IRGenFunction.h"
#include "IRGenModule.h"
#include "Address.h"
#include "Explosion.h"
#include "Linking.h"
using namespace swift;
using namespace irgen;
bool TypeInfo::isSingleRetainablePointer(ResilienceScope scope) const {
return false;
}
ExplosionSchema TypeInfo::getSchema(ExplosionKind kind) const {
ExplosionSchema schema(kind);
getSchema(schema);
return schema;
}
/// Copy a value from one object to a new object, directly taking
/// responsibility for anything it might have. This is like C++
/// move-initialization, except the old object will not be destroyed.
void TypeInfo::initializeWithTake(IRGenFunction &IGF,
Address destAddr, Address srcAddr) const {
// Prefer loads and stores if we won't make a million of them.
// Maybe this should also require the scalars to have a fixed offset.
ExplosionSchema schema = getSchema(ExplosionKind::Maximal);
if (!schema.containsAggregate() && schema.size() <= 2) {
Explosion copy(ExplosionKind::Maximal);
load(IGF, srcAddr, copy);
initialize(IGF, copy, destAddr);
return;
}
// Otherwise, use a memcpy.
IGF.emitMemCpy(destAddr.getAddress(), srcAddr.getAddress(),
StorageSize, std::min(destAddr.getAlignment(),
srcAddr.getAlignment()));
}
static TypeInfo *invalidTypeInfo() { return (TypeInfo*) 1; }
namespace {
/// Basic IR generation for primitive types, which are always
/// represented as a single scalar.
class PrimitiveTypeInfo : public TypeInfo {
public:
PrimitiveTypeInfo(llvm::Type *Type, Size S, Alignment A)
: TypeInfo(Type, S, A) {}
unsigned getExplosionSize(ExplosionKind kind) const {
return 1;
}
void getSchema(ExplosionSchema &schema) const {
schema.add(ExplosionSchema::Element::forScalar(getStorageType()));
}
void load(IRGenFunction &IGF, Address addr, Explosion &e) const {
e.addUnmanaged(IGF.Builder.CreateLoad(addr));
}
void assign(IRGenFunction &IGF, Explosion &e, Address addr) const {
IGF.Builder.CreateStore(e.claimUnmanagedNext(), addr);
}
void initialize(IRGenFunction &IGF, Explosion &e, Address addr) const {
IGF.Builder.CreateStore(e.claimUnmanagedNext(), addr);
}
void reexplode(IRGenFunction &IGF, Explosion &src, Explosion &dest) const {
src.transferInto(dest, 1);
}
void manage(IRGenFunction &IGF, Explosion &src, Explosion &dest) const {
src.transferInto(dest, 1);
}
};
}
/// Constructs a type info which performs simple loads and stores of
/// the given IR type.
const TypeInfo *TypeConverter::createPrimitive(llvm::Type *type,
Size size, Alignment align) {
return new PrimitiveTypeInfo(type, size, align);
}
TypeConverter::TypeConverter() : FirstConverted(invalidTypeInfo()) {}
TypeConverter::~TypeConverter() {
// Delete all the converted type infos.
for (const TypeInfo *I = FirstConverted; I != invalidTypeInfo(); ) {
const TypeInfo *Cur = I;
I = Cur->NextConverted;
delete Cur;
}
}
/// Get the fragile type information for the given type.
const TypeInfo &IRGenFunction::getFragileTypeInfo(Type T) {
return IGM.getFragileTypeInfo(T);
}
/// Get the fragile IR type for the given type.
llvm::Type *IRGenModule::getFragileType(Type T) {
return getFragileTypeInfo(T).StorageType;
}
/// Get the fragile type information for the given type.
const TypeInfo &IRGenModule::getFragileTypeInfo(Type T) {
return TypeConverter::getFragileTypeInfo(*this, T);
}
const TypeInfo &TypeConverter::getFragileTypeInfo(IRGenModule &IGM, Type T) {
assert(!T.isNull());
auto Entry = IGM.Types.Converted.find(T.getPointer());
if (Entry != IGM.Types.Converted.end())
return *Entry->second;
const TypeInfo *Result = convertType(IGM, T);
IGM.Types.Converted[T.getPointer()] = Result;
// If the type info hasn't been added to the list of types, do so.
if (!Result->NextConverted) {
Result->NextConverted = IGM.Types.FirstConverted;
IGM.Types.FirstConverted = Result;
}
return *Result;
}
const TypeInfo *TypeConverter::convertType(IRGenModule &IGM, Type T) {
llvm::LLVMContext &Ctx = IGM.getLLVMContext();
TypeBase *TB = T.getPointer();
switch (TB->getKind()) {
#define UNCHECKED_TYPE(id, parent) \
case TypeKind::id: \
llvm_unreachable("generating an " #id "Type");
#define SUGARED_TYPE(id, parent) \
case TypeKind::id: \
return &getFragileTypeInfo(IGM, cast<id##Type>(TB)->getDesugaredType());
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
case TypeKind::MetaType:
return convertMetaTypeType(IGM, cast<MetaTypeType>(T));
case TypeKind::Module:
return convertModuleType(IGM, cast<ModuleType>(T));
case TypeKind::BuiltinRawPointer:
return createPrimitive(llvm::Type::getInt8PtrTy(Ctx), IGM.getPointerSize(),
IGM.getPointerAlignment());
case TypeKind::BuiltinObjectPointer:
return convertBuiltinObjectPointer(IGM);
case TypeKind::BuiltinFloat:
switch (cast<BuiltinFloatType>(T)->getFPKind()) {
case BuiltinFloatType::IEEE16:
return createPrimitive(llvm::Type::getHalfTy(Ctx),
Size(2), Alignment(2));
case BuiltinFloatType::IEEE32:
return createPrimitive(llvm::Type::getFloatTy(Ctx),
Size(4), Alignment(4));
case BuiltinFloatType::IEEE64:
return createPrimitive(llvm::Type::getDoubleTy(Ctx),
Size(8), Alignment(8));
case BuiltinFloatType::IEEE80:
return createPrimitive(llvm::Type::getX86_FP80Ty(Ctx),
Size(10), Alignment(16));
case BuiltinFloatType::IEEE128:
return createPrimitive(llvm::Type::getFP128Ty(Ctx),
Size(16), Alignment(16));
case BuiltinFloatType::PPC128:
return createPrimitive(llvm::Type::getPPC_FP128Ty(Ctx),
Size(16), Alignment(16));
}
llvm_unreachable("bad builtin floating-point type kind");
case TypeKind::BuiltinInteger: {
unsigned BitWidth = cast<BuiltinIntegerType>(T)->getBitWidth();
unsigned ByteSize = (BitWidth+7U)/8U;
// Round up the memory size and alignment to a power of 2.
if (!llvm::isPowerOf2_32(ByteSize))
ByteSize = llvm::NextPowerOf2(ByteSize);
return createPrimitive(llvm::IntegerType::get(Ctx, BitWidth),
Size(ByteSize), Alignment(ByteSize));
}
case TypeKind::LValue:
return convertLValueType(IGM, cast<LValueType>(TB));
case TypeKind::Tuple:
return convertTupleType(IGM, cast<TupleType>(TB));
case TypeKind::OneOf:
return convertOneOfType(IGM, cast<OneOfType>(TB));
case TypeKind::Function:
return convertFunctionType(IGM, cast<FunctionType>(TB));
case TypeKind::Array:
return convertArrayType(IGM, cast<ArrayType>(TB));
case TypeKind::Protocol:
llvm_unreachable("protocol not handled in IRGen yet");
}
llvm_unreachable("bad type kind");
}
/// emitTypeAlias - Emit a type alias. You wouldn't think that these
/// would need IR support, but we apparently want to emit struct and
/// oneof declarations as these instead of as their own declarations.
void IRGenModule::emitTypeAlias(Type underlyingType) {
if (OneOfType *oneof = dyn_cast<OneOfType>(underlyingType))
return emitOneOfType(oneof);
}
/// createNominalType - Create a new nominal type.
llvm::StructType *IRGenModule::createNominalType(TypeAliasDecl *alias) {
llvm::SmallString<32> typeName;
llvm::raw_svector_ostream nameStream(typeName);
LinkEntity::forNonFunction(alias).mangle(nameStream);
return llvm::StructType::create(getLLVMContext(), nameStream.str());
}
/// Compute the explosion schema for the given type.
void IRGenModule::getSchema(Type type, ExplosionSchema &schema) {
// As an optimization, avoid actually building a TypeInfo for any
// obvious TupleTypes. This assumes that a TupleType's explosion
// schema is always the concatenation of its components schemata.
if (TupleType *tuple = dyn_cast<TupleType>(type)) {
for (const TupleTypeElt &field : tuple->getFields())
getSchema(field.getType(), schema);
return;
}
// Okay, that didn't work; just do the general thing.
getFragileTypeInfo(type).getSchema(schema);
}
<commit_msg>use cached type, thanks John<commit_after>//===--- GenTypes.cpp - Swift IR Generation For Types ---------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements IR generation for types in Swift.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/Decl.h"
#include "swift/AST/Types.h"
#include "llvm/DerivedTypes.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Target/TargetData.h"
#include "GenType.h"
#include "IRGenFunction.h"
#include "IRGenModule.h"
#include "Address.h"
#include "Explosion.h"
#include "Linking.h"
using namespace swift;
using namespace irgen;
bool TypeInfo::isSingleRetainablePointer(ResilienceScope scope) const {
return false;
}
ExplosionSchema TypeInfo::getSchema(ExplosionKind kind) const {
ExplosionSchema schema(kind);
getSchema(schema);
return schema;
}
/// Copy a value from one object to a new object, directly taking
/// responsibility for anything it might have. This is like C++
/// move-initialization, except the old object will not be destroyed.
void TypeInfo::initializeWithTake(IRGenFunction &IGF,
Address destAddr, Address srcAddr) const {
// Prefer loads and stores if we won't make a million of them.
// Maybe this should also require the scalars to have a fixed offset.
ExplosionSchema schema = getSchema(ExplosionKind::Maximal);
if (!schema.containsAggregate() && schema.size() <= 2) {
Explosion copy(ExplosionKind::Maximal);
load(IGF, srcAddr, copy);
initialize(IGF, copy, destAddr);
return;
}
// Otherwise, use a memcpy.
IGF.emitMemCpy(destAddr.getAddress(), srcAddr.getAddress(),
StorageSize, std::min(destAddr.getAlignment(),
srcAddr.getAlignment()));
}
static TypeInfo *invalidTypeInfo() { return (TypeInfo*) 1; }
namespace {
/// Basic IR generation for primitive types, which are always
/// represented as a single scalar.
class PrimitiveTypeInfo : public TypeInfo {
public:
PrimitiveTypeInfo(llvm::Type *Type, Size S, Alignment A)
: TypeInfo(Type, S, A) {}
unsigned getExplosionSize(ExplosionKind kind) const {
return 1;
}
void getSchema(ExplosionSchema &schema) const {
schema.add(ExplosionSchema::Element::forScalar(getStorageType()));
}
void load(IRGenFunction &IGF, Address addr, Explosion &e) const {
e.addUnmanaged(IGF.Builder.CreateLoad(addr));
}
void assign(IRGenFunction &IGF, Explosion &e, Address addr) const {
IGF.Builder.CreateStore(e.claimUnmanagedNext(), addr);
}
void initialize(IRGenFunction &IGF, Explosion &e, Address addr) const {
IGF.Builder.CreateStore(e.claimUnmanagedNext(), addr);
}
void reexplode(IRGenFunction &IGF, Explosion &src, Explosion &dest) const {
src.transferInto(dest, 1);
}
void manage(IRGenFunction &IGF, Explosion &src, Explosion &dest) const {
src.transferInto(dest, 1);
}
};
}
/// Constructs a type info which performs simple loads and stores of
/// the given IR type.
const TypeInfo *TypeConverter::createPrimitive(llvm::Type *type,
Size size, Alignment align) {
return new PrimitiveTypeInfo(type, size, align);
}
TypeConverter::TypeConverter() : FirstConverted(invalidTypeInfo()) {}
TypeConverter::~TypeConverter() {
// Delete all the converted type infos.
for (const TypeInfo *I = FirstConverted; I != invalidTypeInfo(); ) {
const TypeInfo *Cur = I;
I = Cur->NextConverted;
delete Cur;
}
}
/// Get the fragile type information for the given type.
const TypeInfo &IRGenFunction::getFragileTypeInfo(Type T) {
return IGM.getFragileTypeInfo(T);
}
/// Get the fragile IR type for the given type.
llvm::Type *IRGenModule::getFragileType(Type T) {
return getFragileTypeInfo(T).StorageType;
}
/// Get the fragile type information for the given type.
const TypeInfo &IRGenModule::getFragileTypeInfo(Type T) {
return TypeConverter::getFragileTypeInfo(*this, T);
}
const TypeInfo &TypeConverter::getFragileTypeInfo(IRGenModule &IGM, Type T) {
assert(!T.isNull());
auto Entry = IGM.Types.Converted.find(T.getPointer());
if (Entry != IGM.Types.Converted.end())
return *Entry->second;
const TypeInfo *Result = convertType(IGM, T);
IGM.Types.Converted[T.getPointer()] = Result;
// If the type info hasn't been added to the list of types, do so.
if (!Result->NextConverted) {
Result->NextConverted = IGM.Types.FirstConverted;
IGM.Types.FirstConverted = Result;
}
return *Result;
}
const TypeInfo *TypeConverter::convertType(IRGenModule &IGM, Type T) {
llvm::LLVMContext &Ctx = IGM.getLLVMContext();
TypeBase *TB = T.getPointer();
switch (TB->getKind()) {
#define UNCHECKED_TYPE(id, parent) \
case TypeKind::id: \
llvm_unreachable("generating an " #id "Type");
#define SUGARED_TYPE(id, parent) \
case TypeKind::id: \
return &getFragileTypeInfo(IGM, cast<id##Type>(TB)->getDesugaredType());
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
case TypeKind::MetaType:
return convertMetaTypeType(IGM, cast<MetaTypeType>(T));
case TypeKind::Module:
return convertModuleType(IGM, cast<ModuleType>(T));
case TypeKind::BuiltinRawPointer:
return createPrimitive(IGM.Int8PtrTy, IGM.getPointerSize(),
IGM.getPointerAlignment());
case TypeKind::BuiltinObjectPointer:
return convertBuiltinObjectPointer(IGM);
case TypeKind::BuiltinFloat:
switch (cast<BuiltinFloatType>(T)->getFPKind()) {
case BuiltinFloatType::IEEE16:
return createPrimitive(llvm::Type::getHalfTy(Ctx),
Size(2), Alignment(2));
case BuiltinFloatType::IEEE32:
return createPrimitive(llvm::Type::getFloatTy(Ctx),
Size(4), Alignment(4));
case BuiltinFloatType::IEEE64:
return createPrimitive(llvm::Type::getDoubleTy(Ctx),
Size(8), Alignment(8));
case BuiltinFloatType::IEEE80:
return createPrimitive(llvm::Type::getX86_FP80Ty(Ctx),
Size(10), Alignment(16));
case BuiltinFloatType::IEEE128:
return createPrimitive(llvm::Type::getFP128Ty(Ctx),
Size(16), Alignment(16));
case BuiltinFloatType::PPC128:
return createPrimitive(llvm::Type::getPPC_FP128Ty(Ctx),
Size(16), Alignment(16));
}
llvm_unreachable("bad builtin floating-point type kind");
case TypeKind::BuiltinInteger: {
unsigned BitWidth = cast<BuiltinIntegerType>(T)->getBitWidth();
unsigned ByteSize = (BitWidth+7U)/8U;
// Round up the memory size and alignment to a power of 2.
if (!llvm::isPowerOf2_32(ByteSize))
ByteSize = llvm::NextPowerOf2(ByteSize);
return createPrimitive(llvm::IntegerType::get(Ctx, BitWidth),
Size(ByteSize), Alignment(ByteSize));
}
case TypeKind::LValue:
return convertLValueType(IGM, cast<LValueType>(TB));
case TypeKind::Tuple:
return convertTupleType(IGM, cast<TupleType>(TB));
case TypeKind::OneOf:
return convertOneOfType(IGM, cast<OneOfType>(TB));
case TypeKind::Function:
return convertFunctionType(IGM, cast<FunctionType>(TB));
case TypeKind::Array:
return convertArrayType(IGM, cast<ArrayType>(TB));
case TypeKind::Protocol:
llvm_unreachable("protocol not handled in IRGen yet");
}
llvm_unreachable("bad type kind");
}
/// emitTypeAlias - Emit a type alias. You wouldn't think that these
/// would need IR support, but we apparently want to emit struct and
/// oneof declarations as these instead of as their own declarations.
void IRGenModule::emitTypeAlias(Type underlyingType) {
if (OneOfType *oneof = dyn_cast<OneOfType>(underlyingType))
return emitOneOfType(oneof);
}
/// createNominalType - Create a new nominal type.
llvm::StructType *IRGenModule::createNominalType(TypeAliasDecl *alias) {
llvm::SmallString<32> typeName;
llvm::raw_svector_ostream nameStream(typeName);
LinkEntity::forNonFunction(alias).mangle(nameStream);
return llvm::StructType::create(getLLVMContext(), nameStream.str());
}
/// Compute the explosion schema for the given type.
void IRGenModule::getSchema(Type type, ExplosionSchema &schema) {
// As an optimization, avoid actually building a TypeInfo for any
// obvious TupleTypes. This assumes that a TupleType's explosion
// schema is always the concatenation of its components schemata.
if (TupleType *tuple = dyn_cast<TupleType>(type)) {
for (const TupleTypeElt &field : tuple->getFields())
getSchema(field.getType(), schema);
return;
}
// Okay, that didn't work; just do the general thing.
getFragileTypeInfo(type).getSchema(schema);
}
<|endoftext|> |
<commit_before>/*
* ScreenSpaceEdgeRenderer.cpp
*
* Copyright (C) 2016 by MegaMol Team
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "ScreenSpaceEdgeRenderer.h"
#include "mmcore/CoreInstance.h"
#include "vislib/graphics/gl/IncludeAllGL.h"
#include "vislib/graphics/gl/ShaderSource.h"
#include "mmcore/param/StringParam.h"
#include "mmcore/utility/ColourParser.h"
using namespace megamol;
using namespace megamol::trisoup;
using namespace megamol::core;
/*
* ScreenSpaceEdgeRenderer::ScreenSpaceEdgeRenderer
*/
ScreenSpaceEdgeRenderer::ScreenSpaceEdgeRenderer(void) : Renderer3DModule(),
rendererSlot("renderer", "Connects to the renderer actually rendering the image"),
colorSlot("color", "The triangle color (if not colors are read from file)") {
this->rendererSlot.SetCompatibleCall<view::CallRender3DDescription>();
this->MakeSlotAvailable(&this->rendererSlot);
this->colorSlot.SetParameter(new param::StringParam("silver"));
this->MakeSlotAvailable(&this->colorSlot);
}
/*
* ScreenSpaceEdgeRenderer::~ScreenSpaceEdgeRenderer
*/
ScreenSpaceEdgeRenderer::~ScreenSpaceEdgeRenderer(void) {
this->Release();
}
/*
* ScreenSpaceEdgeRenderer::create
*/
bool ScreenSpaceEdgeRenderer::create(void) {
ASSERT(IsAvailable());
vislib::graphics::gl::ShaderSource vert, frag;
if (!instance()->ShaderSourceFactory().MakeShaderSource("ScreenSpaceEdge::vertex", vert)) {
return false;
}
if (!instance()->ShaderSourceFactory().MakeShaderSource("ScreenSpaceEdge::fragment", frag)) {
return false;
}
//printf("\nVertex Shader:\n%s\n\nFragment Shader:\n%s\n",
// vert.WholeCode().PeekBuffer(),
// frag.WholeCode().PeekBuffer());
try {
if (!this->shader.Create(vert.Code(), vert.Count(), frag.Code(), frag.Count())) {
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR,
"Unable to compile ScreenSpaceEdge shader: Unknown error\n");
return false;
}
} catch (vislib::graphics::gl::AbstractOpenGLShader::CompileException ce) {
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR,
"Unable to compile ScreenSpaceEdge shader (@%s): %s\n",
vislib::graphics::gl::AbstractOpenGLShader::CompileException::CompileActionName(
ce.FailedAction()), ce.GetMsgA());
return false;
} catch (vislib::Exception e) {
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR,
"Unable to compile ScreenSpaceEdge shader: %s\n", e.GetMsgA());
return false;
} catch (...) {
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR,
"Unable to compile ScreenSpaceEdge shader: Unknown exception\n");
return false;
}
return true;
}
/*
* ScreenSpaceEdgeRenderer::GetCapabilities
*/
bool ScreenSpaceEdgeRenderer::GetCapabilities(Call& call) {
view::CallRender3D *inCall = dynamic_cast<view::CallRender3D*>(&call);
if (inCall == NULL) return false;
view::CallRender3D *outCall = this->rendererSlot.CallAs<view::CallRender3D>();
if (outCall == NULL) return false;
*outCall = *inCall;
if (!(*outCall)(2)) return false;
*inCall = *outCall;
return true;
}
/*
* ScreenSpaceEdgeRenderer::GetExtents
*/
bool ScreenSpaceEdgeRenderer::GetExtents(Call& call) {
view::CallRender3D *inCall = dynamic_cast<view::CallRender3D*>(&call);
if (inCall == NULL) return false;
view::CallRender3D *outCall = this->rendererSlot.CallAs<view::CallRender3D>();
if (outCall == NULL) return false;
*outCall = *inCall;
if (!(*outCall)(1)) return false;
*inCall = *outCall;
return true;
}
/*
* ScreenSpaceEdgeRenderer::release
*/
void ScreenSpaceEdgeRenderer::release(void) {
if (vislib::graphics::gl::GLSLShader::IsValidHandle(this->shader.ProgramHandle())) this->shader.Release();
if (this->fbo.IsValid()) this->fbo.Release();
}
/*
* ScreenSpaceEdgeRenderer::Render
*/
bool ScreenSpaceEdgeRenderer::Render(Call& call) {
view::CallRender3D *inCall = dynamic_cast<view::CallRender3D*>(&call);
if (inCall == NULL) return false;
view::CallRender3D *outCall = this->rendererSlot.CallAs<view::CallRender3D>();
if (outCall == NULL) return false;
inCall->DisableOutputBuffer();
const vislib::math::Rectangle<int>& vp = inCall->GetViewport();
if (!this->fbo.IsValid()
|| (this->fbo.GetWidth() != static_cast<unsigned int>(vp.Width()))
|| (this->fbo.GetHeight() != static_cast<unsigned int>(vp.Height()))) {
if (this->fbo.IsValid()) this->fbo.Release();
this->fbo.Create(
static_cast<unsigned int>(vp.Width()), static_cast<unsigned int>(vp.Height()),
GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE,
vislib::graphics::gl::FramebufferObject::ATTACHMENT_TEXTURE);
}
fbo.Enable();
::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
*outCall = *inCall;
outCall->SetOutputBuffer(&fbo);
bool renderValid = (*outCall)(0);
fbo.Disable();
inCall->EnableOutputBuffer();
::glPushAttrib(GL_TEXTURE_BIT | GL_TRANSFORM_BIT);
float r, g, b;
this->colorSlot.ResetDirty();
utility::ColourParser::FromString(this->colorSlot.Param<param::StringParam>()->Value(), r, g, b);
::glDisable(GL_BLEND);
::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
shader.Enable();
glActiveTexture(GL_TEXTURE0 + 0);
fbo.BindColourTexture(0);
glActiveTexture(GL_TEXTURE0 + 1);
fbo.BindDepthTexture();
shader.SetParameter("inColorTex", 0);
shader.SetParameter("inDepthTex", 1);
shader.SetParameter("viewportMax", vp.Width() - 1, vp.Height() - 1);
shader.SetParameter("color", r, g, b);
::glMatrixMode(GL_PROJECTION);
::glPushMatrix();
::glLoadIdentity();
::glMatrixMode(GL_MODELVIEW);
::glPushMatrix();
::glLoadIdentity();
::glBegin(GL_QUADS);
::glVertex3d(-1.0, -1.0, 0.5);
::glVertex3d(1.0, -1.0, 0.5);
::glVertex3d(1.0, 1.0, 0.5);
::glVertex3d(-1.0, 1.0, 0.5);
::glEnd();
// GL_MODELVIEW
::glPopMatrix();
::glMatrixMode(GL_PROJECTION);
::glPopMatrix();
shader.Disable();
::glPopAttrib();
return true;
}
<commit_msg>Change in bounding box rendering stuff<commit_after>/*
* ScreenSpaceEdgeRenderer.cpp
*
* Copyright (C) 2016 by MegaMol Team
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "ScreenSpaceEdgeRenderer.h"
#include "mmcore/CoreInstance.h"
#include "vislib/graphics/gl/IncludeAllGL.h"
#include "vislib/graphics/gl/ShaderSource.h"
#include "mmcore/param/StringParam.h"
#include "mmcore/utility/ColourParser.h"
using namespace megamol;
using namespace megamol::trisoup;
using namespace megamol::core;
/*
* ScreenSpaceEdgeRenderer::ScreenSpaceEdgeRenderer
*/
ScreenSpaceEdgeRenderer::ScreenSpaceEdgeRenderer(void) : Renderer3DModule(),
rendererSlot("renderer", "Connects to the renderer actually rendering the image"),
colorSlot("color", "The triangle color (if not colors are read from file)") {
this->rendererSlot.SetCompatibleCall<view::CallRender3DDescription>();
this->MakeSlotAvailable(&this->rendererSlot);
this->colorSlot.SetParameter(new param::StringParam("silver"));
this->MakeSlotAvailable(&this->colorSlot);
}
/*
* ScreenSpaceEdgeRenderer::~ScreenSpaceEdgeRenderer
*/
ScreenSpaceEdgeRenderer::~ScreenSpaceEdgeRenderer(void) {
this->Release();
}
/*
* ScreenSpaceEdgeRenderer::create
*/
bool ScreenSpaceEdgeRenderer::create(void) {
ASSERT(IsAvailable());
vislib::graphics::gl::ShaderSource vert, frag;
if (!instance()->ShaderSourceFactory().MakeShaderSource("ScreenSpaceEdge::vertex", vert)) {
return false;
}
if (!instance()->ShaderSourceFactory().MakeShaderSource("ScreenSpaceEdge::fragment", frag)) {
return false;
}
//printf("\nVertex Shader:\n%s\n\nFragment Shader:\n%s\n",
// vert.WholeCode().PeekBuffer(),
// frag.WholeCode().PeekBuffer());
try {
if (!this->shader.Create(vert.Code(), vert.Count(), frag.Code(), frag.Count())) {
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR,
"Unable to compile ScreenSpaceEdge shader: Unknown error\n");
return false;
}
} catch (vislib::graphics::gl::AbstractOpenGLShader::CompileException ce) {
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR,
"Unable to compile ScreenSpaceEdge shader (@%s): %s\n",
vislib::graphics::gl::AbstractOpenGLShader::CompileException::CompileActionName(
ce.FailedAction()), ce.GetMsgA());
return false;
} catch (vislib::Exception e) {
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR,
"Unable to compile ScreenSpaceEdge shader: %s\n", e.GetMsgA());
return false;
} catch (...) {
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR,
"Unable to compile ScreenSpaceEdge shader: Unknown exception\n");
return false;
}
return true;
}
/*
* ScreenSpaceEdgeRenderer::GetCapabilities
*/
bool ScreenSpaceEdgeRenderer::GetCapabilities(Call& call) {
view::CallRender3D *inCall = dynamic_cast<view::CallRender3D*>(&call);
if (inCall == NULL) return false;
view::CallRender3D *outCall = this->rendererSlot.CallAs<view::CallRender3D>();
if (outCall == NULL) return false;
*outCall = *inCall;
if (!(*outCall)(2)) return false;
*inCall = *outCall;
return true;
}
/*
* ScreenSpaceEdgeRenderer::GetExtents
*/
bool ScreenSpaceEdgeRenderer::GetExtents(Call& call) {
view::CallRender3D *inCall = dynamic_cast<view::CallRender3D*>(&call);
if (inCall == NULL) return false;
view::CallRender3D *outCall = this->rendererSlot.CallAs<view::CallRender3D>();
if (outCall == NULL) return false;
*outCall = *inCall;
if (!(*outCall)(1)) return false;
*inCall = *outCall;
return true;
}
/*
* ScreenSpaceEdgeRenderer::release
*/
void ScreenSpaceEdgeRenderer::release(void) {
if (vislib::graphics::gl::GLSLShader::IsValidHandle(this->shader.ProgramHandle())) this->shader.Release();
if (this->fbo.IsValid()) this->fbo.Release();
}
/*
* ScreenSpaceEdgeRenderer::Render
*/
bool ScreenSpaceEdgeRenderer::Render(Call& call) {
view::CallRender3D *inCall = dynamic_cast<view::CallRender3D*>(&call);
if (inCall == NULL) return false;
view::CallRender3D *outCall = this->rendererSlot.CallAs<view::CallRender3D>();
if (outCall == NULL) return false;
//const vislib::math::Rectangle<int>& vp = inCall->GetViewport();
inCall->DisableOutputBuffer();
const vislib::math::Rectangle<int>& vp = inCall->GetCameraParameters()->TileRect();
if (!this->fbo.IsValid()
|| (this->fbo.GetWidth() != static_cast<unsigned int>(vp.Width()))
|| (this->fbo.GetHeight() != static_cast<unsigned int>(vp.Height()))) {
if (this->fbo.IsValid()) this->fbo.Release();
this->fbo.Create(
static_cast<unsigned int>(vp.Width()), static_cast<unsigned int>(vp.Height()),
GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE,
vislib::graphics::gl::FramebufferObject::ATTACHMENT_TEXTURE);
}
fbo.Enable();
::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
*outCall = *inCall;
outCall->SetOutputBuffer(&fbo);
bool renderValid = (*outCall)(0);
fbo.Disable();
inCall->EnableOutputBuffer();
::glPushAttrib(GL_TEXTURE_BIT | GL_TRANSFORM_BIT);
float r, g, b;
this->colorSlot.ResetDirty();
utility::ColourParser::FromString(this->colorSlot.Param<param::StringParam>()->Value(), r, g, b);
::glDisable(GL_BLEND);
::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
shader.Enable();
glActiveTexture(GL_TEXTURE0 + 0);
fbo.BindColourTexture(0);
glActiveTexture(GL_TEXTURE0 + 1);
fbo.BindDepthTexture();
shader.SetParameter("inColorTex", 0);
shader.SetParameter("inDepthTex", 1);
shader.SetParameter("viewportMax", vp.Width() - 1, vp.Height() - 1);
shader.SetParameter("color", r, g, b);
::glMatrixMode(GL_PROJECTION);
::glPushMatrix();
::glLoadIdentity();
::glMatrixMode(GL_MODELVIEW);
::glPushMatrix();
::glLoadIdentity();
::glBegin(GL_QUADS);
::glVertex3d(-1.0, -1.0, 0.5);
::glVertex3d(1.0, -1.0, 0.5);
::glVertex3d(1.0, 1.0, 0.5);
::glVertex3d(-1.0, 1.0, 0.5);
::glEnd();
// GL_MODELVIEW
::glPopMatrix();
::glMatrixMode(GL_PROJECTION);
::glPopMatrix();
shader.Disable();
::glPopAttrib();
return true;
}
<|endoftext|> |
<commit_before>// ViterbiSTL.cpp : is an C++ and STL implementatiton of the Wikipedia example
// Wikipedia: http://en.wikipedia.org/wiki/Viterbi_algorithm#A_concrete_example
// It as accurate implementation as it was possible
#include "string"
#include "vector"
#include "map"
#include "iostream"
using namespace std;
//states = ('Rainy', 'Sunny')
//
//observations = ('walk', 'shop', 'clean')
//
//start_probability = {'Rainy': 0.6, 'Sunny': 0.4}
//
//transition_probability = {
// 'Rainy' : {'Rainy': 0.7, 'Sunny': 0.3},
// 'Sunny' : {'Rainy': 0.4, 'Sunny': 0.6},
// }
//
//emission_probability = {
// 'Rainy' : {'walk': 0.1, 'shop': 0.4, 'clean': 0.5},
// 'Sunny' : {'walk': 0.6, 'shop': 0.3, 'clean': 0.1},
// }
vector<string> states;
vector<string> observations;
map<string,double> start_probability;
map<string,map<string, double> > transition_probability;
map<string,map<string, double> > emission_probability;
class Tracking {
public:
double prob;
vector<string> v_path;
double v_prob;
Tracking() {
prob = 0.0;
v_prob = 0.0;
}
Tracking(double p, vector<string> & v_pth, double v_p) {
prob = p;
v_path = v_pth;
v_prob = v_p;
}
};
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
void init_variables(void) {
states.push_back("Rainy");
states.push_back("Sunny");
observations.push_back("walk");
observations.push_back("shop");
observations.push_back("clean");
start_probability["Rainy"] = 0.6;
start_probability["Sunny"] = 0.4;
transition_probability["Rainy"]["Rainy"] = 0.7;
transition_probability["Rainy"]["Sunny"] = 0.3;
transition_probability["Sunny"]["Rainy"] = 0.4;
transition_probability["Sunny"]["Sunny"] = 0.6;
emission_probability["Rainy"]["walk"] = 0.1;
emission_probability["Rainy"]["shop"] = 0.4;
emission_probability["Rainy"]["clean"] = 0.5;
emission_probability["Sunny"]["walk"] = 0.6;
emission_probability["Sunny"]["shop"] = 0.3;
emission_probability["Sunny"]["clean"] = 0.1;
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
void print_variables(void) {
// print states
cout << "States:" << endl;
for(vector<string>::iterator i=states.begin();i!=states.end();i++) {
cout << "S: " << (*i) << endl;
}
// print observations
cout << "Observations:" << endl;
for(vector<string>::iterator i=observations.begin();i!=observations.end();i++) {
cout << "O: " << (*i) << endl;
}
// print start probabilities
cout << "Start probabilities:" << endl;
for(map<string, double>::iterator i=start_probability.begin();i!=start_probability.end();i++) {
cout << "S: " << (*i).first << " P: " << (*i).second << endl;
}
// print transition_probability
cout << "Transition probabilities:" << endl;
for(map<string,map<string, double> >::iterator i=transition_probability.begin();i!=transition_probability.end();i++) {
for(map<string, double>::iterator j=(*i).second.begin();j!=(*i).second.end();j++) {
cout << "FS: " << (*i).first << " TS: " << (*j).first << " P: " << (*j).second << endl;
}
}
// print emission probabilities
cout << "Emission probabilities:" << endl;
for(int i=0; i<states.size(); i++) {
for(int j=0; j<observations.size(); j++) {
cout << "FS: " << states[i] << " TO: " << observations[j] <<
" P: " << emission_probability[states[i]][observations[j]] << endl;
}
}
}
//this method compute total probability for observation, most likely viterbi path
//and probability of such path
void forward_viterbi(vector<string> obs, vector<string> states, map<string, double> start_p, map<string, map<string, double> > trans_p, map<string, map<string, double> > emit_p) {
map<string, Tracking> T;
for(vector<string>::iterator state=states.begin(); state!=states.end();state++) {
vector<string> v_pth;
v_pth.push_back(*state);
T[*state] = Tracking(start_p[*state], v_pth, start_p[*state]);
}
for(vector<string>::iterator output=obs.begin(); output!=obs.end();output++) {
map<string, Tracking> U;
for(vector<string>::iterator next_state=states.begin(); next_state!=states.end(); next_state++) {
Tracking next_tracker;
for(vector<string>::iterator source_state=states.begin(); source_state!=states.end(); source_state++) {
Tracking source_tracker = T[*source_state];
double p = emit_p[*source_state][*output]*trans_p[*source_state][*next_state];
source_tracker.prob *= p;
source_tracker.v_prob *= p;
next_tracker.prob += source_tracker.prob;
if(source_tracker.v_prob > next_tracker.v_prob) {
next_tracker.v_path = source_tracker.v_path;
next_tracker.v_path.push_back(*next_state);
next_tracker.v_prob = source_tracker.v_prob;
}
}
U[*next_state] = next_tracker;
}
T = U;
}
// apply sum/max to the final states
Tracking final_tracker;
for(vector<string>::iterator state=states.begin(); state!=states.end(); state++) {
Tracking tracker = T[*state];
final_tracker.prob += tracker.prob;
if(tracker.v_prob > final_tracker.v_prob) {
final_tracker.v_path = tracker.v_path;
final_tracker.v_prob = tracker.v_prob;
}
}
cout << "Total probability of the observation sequence: " << final_tracker.prob << endl;
cout << "Probability of the Viterbi path: " << final_tracker.v_prob << endl;
cout << "The Viterbi path: " << endl;
for(vector<string>::iterator state=final_tracker.v_path.begin(); state!=final_tracker.v_path.end(); state++) {
cout << "VState: " << *state << endl;
}
}
int main(int argc, char* argv[])
{
cout << "Viterbi STL example" << endl;
init_variables();
print_variables();
forward_viterbi(observations, states, start_probability, transition_probability, emission_probability);
cout << "End" << endl;
string end;
cin >> end;
return 0;
}
<commit_msg>Reformat verterbi source.<commit_after>// ViterbiSTL.cpp : is an C++ and STL implementatiton of the Wikipedia example
// Wikipedia: http://en.wikipedia.org/wiki/Viterbi_algorithm#A_concrete_example
// It as accurate implementation as it was possible
#include "string"
#include "vector"
#include "map"
#include "iostream"
using namespace std;
//states = ('Rainy', 'Sunny')
//
//observations = ('walk', 'shop', 'clean')
//
//start_probability = {'Rainy': 0.6, 'Sunny': 0.4}
//
//transition_probability = {
// 'Rainy' : {'Rainy': 0.7, 'Sunny': 0.3},
// 'Sunny' : {'Rainy': 0.4, 'Sunny': 0.6},
// }
//
//emission_probability = {
// 'Rainy' : {'walk': 0.1, 'shop': 0.4, 'clean': 0.5},
// 'Sunny' : {'walk': 0.6, 'shop': 0.3, 'clean': 0.1},
// }
vector<string> states;
vector<string> observations;
map<string,double> start_probability;
map<string,map<string, double> > transition_probability;
map<string,map<string, double> > emission_probability;
class Tracking {
public:
double prob;
vector<string> v_path;
double v_prob;
Tracking() {
prob = 0.0;
v_prob = 0.0;
}
Tracking(double p, vector<string> & v_pth, double v_p) {
prob = p;
v_path = v_pth;
v_prob = v_p;
}
};
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
void init_variables(void) {
states.push_back("Rainy");
states.push_back("Sunny");
observations.push_back("walk");
observations.push_back("shop");
observations.push_back("clean");
start_probability["Rainy"] = 0.6;
start_probability["Sunny"] = 0.4;
transition_probability["Rainy"]["Rainy"] = 0.7;
transition_probability["Rainy"]["Sunny"] = 0.3;
transition_probability["Sunny"]["Rainy"] = 0.4;
transition_probability["Sunny"]["Sunny"] = 0.6;
emission_probability["Rainy"]["walk"] = 0.1;
emission_probability["Rainy"]["shop"] = 0.4;
emission_probability["Rainy"]["clean"] = 0.5;
emission_probability["Sunny"]["walk"] = 0.6;
emission_probability["Sunny"]["shop"] = 0.3;
emission_probability["Sunny"]["clean"] = 0.1;
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
void print_variables(void) {
// print states
cout << "States:" << endl;
for(vector<string>::iterator i=states.begin();i!=states.end();i++) {
cout << "S: " << (*i) << endl;
}
// print observations
cout << "Observations:" << endl;
for(vector<string>::iterator i=observations.begin();i!=observations.end();i++) {
cout << "O: " << (*i) << endl;
}
// print start probabilities
cout << "Start probabilities:" << endl;
for(map<string, double>::iterator i=start_probability.begin();i!=start_probability.end();i++) {
cout << "S: " << (*i).first << " P: " << (*i).second << endl;
}
// print transition_probability
cout << "Transition probabilities:" << endl;
for(map<string,map<string, double> >::iterator i=transition_probability.begin();i!=transition_probability.end();i++) {
for(map<string, double>::iterator j=(*i).second.begin();j!=(*i).second.end();j++) {
cout << "FS: " << (*i).first << " TS: " << (*j).first << " P: " << (*j).second << endl;
}
}
// print emission probabilities
cout << "Emission probabilities:" << endl;
for(int i=0; i<states.size(); i++) {
for(int j=0; j<observations.size(); j++) {
cout << "FS: " << states[i] << " TO: " << observations[j] <<
" P: " << emission_probability[states[i]][observations[j]] << endl;
}
}
}
//this method compute total probability for observation, most likely viterbi path
//and probability of such path
void forward_viterbi(vector<string> obs, vector<string> states, map<string, double> start_p, map<string, map<string, double> > trans_p, map<string, map<string, double> > emit_p) {
map<string, Tracking> T;
for(vector<string>::iterator state=states.begin(); state!=states.end();state++) {
vector<string> v_pth;
v_pth.push_back(*state);
T[*state] = Tracking(start_p[*state], v_pth, start_p[*state]);
}
for(vector<string>::iterator output=obs.begin(); output!=obs.end();output++) {
map<string, Tracking> U;
for(vector<string>::iterator next_state=states.begin(); next_state!=states.end(); next_state++) {
Tracking next_tracker;
for(vector<string>::iterator source_state=states.begin(); source_state!=states.end(); source_state++) {
Tracking source_tracker = T[*source_state];
double p = emit_p[*source_state][*output]*trans_p[*source_state][*next_state];
source_tracker.prob *= p;
source_tracker.v_prob *= p;
next_tracker.prob += source_tracker.prob;
if(source_tracker.v_prob > next_tracker.v_prob) {
next_tracker.v_path = source_tracker.v_path;
next_tracker.v_path.push_back(*next_state);
next_tracker.v_prob = source_tracker.v_prob;
}
}
U[*next_state] = next_tracker;
}
T = U;
}
// apply sum/max to the final states
Tracking final_tracker;
for(vector<string>::iterator state=states.begin(); state!=states.end(); state++) {
Tracking tracker = T[*state];
final_tracker.prob += tracker.prob;
if(tracker.v_prob > final_tracker.v_prob) {
final_tracker.v_path = tracker.v_path;
final_tracker.v_prob = tracker.v_prob;
}
}
cout << "Total probability of the observation sequence: " << final_tracker.prob << endl;
cout << "Probability of the Viterbi path: " << final_tracker.v_prob << endl;
cout << "The Viterbi path: " << endl;
for(vector<string>::iterator state=final_tracker.v_path.begin(); state!=final_tracker.v_path.end(); state++) {
cout << "VState: " << *state << endl;
}
}
int main(int argc, char* argv[])
{
cout << "Viterbi STL example" << endl;
init_variables();
print_variables();
forward_viterbi(observations, states, start_probability, transition_probability, emission_probability);
cout << "End" << endl;
string end;
cin >> end;
return 0;
}
<|endoftext|> |
<commit_before>#include "HeatFlowProject.h"
namespace HeatFlow {
HeatFlowProject::HeatFlowProject()
{
this->title_ = "New Sim Project";
this->notes_ = "";
this->initial_temps_matrix_path_ = "Temps.floatfield";
this->materials_matrix_path_ = "Materials.intfield";
this->field_gap_distance_ = 0.00001; // the distance between nodes in the X direction
this->time_step_ = 1; // number of milliseconds between calculation iterations
}
HeatFlowProject::~HeatFlowProject()
{
}
int HeatFlowProject::load_from_file(const std::string& path) {
tinyxml2::XMLDocument doc;
tinyxml2::XMLError load_success = doc.LoadFile(path.c_str());
if (load_success != tinyxml2::XMLError::XML_SUCCESS) {
return 0;
}
tinyxml2::XMLElement *root = doc.FirstChildElement("HeatProject");
// Load the single-value elements
this->title_ = root->FirstChildElement("Title")->GetText();
this->notes_ = root->FirstChildElement("Notes")->GetText();
this->time_step_ = std::strtod(root->FirstChildElement("TimeStep")->GetText(), NULL);
this->field_gap_distance_ = std::strtod(root->FirstChildElement("FieldGapDistance")->GetText(), NULL);
// Get the absolute paths to the data files.
// In the project file, they are specified relative to the config file's directory.
boost::filesystem::path temps_matrix_path(root->FirstChildElement("InitialTemperaturesField")->FirstChildElement("path")->GetText());
boost::filesystem::path config_path(path);
boost::filesystem::path real_temps_path = config_path.parent_path() / temps_matrix_path;
//this->initial_temps_matrix_path_ = root->FirstChildElement("InitialTemperaturesField")->FirstChildElement("path")->GetText();
this->initial_temps_matrix_path_ = real_temps_path.native();
boost::filesystem::path materials_matrix_path(root->FirstChildElement("MaterialsField")->FirstChildElement("path")->GetText());
this->materials_matrix_path_ = (config_path.parent_path() / materials_matrix_path).native();
// Load the Bill of Materials
tinyxml2::XMLElement *bom = root->FirstChildElement("Materials");
tinyxml2::XMLElement *material = bom->FirstChildElement();
Material tmp_material;
int new_id = 0;
while (material != NULL) {
tmp_material.set_name(material->FirstChildElement("name")->GetText());
tmp_material.set_density(std::strtod(material->FirstChildElement("density")->GetText(), NULL));
tmp_material.set_conductivity(std::strtod(material->FirstChildElement("conductivity")->GetText(), NULL));
new_id = material->IntAttribute("id");
this->bom_[new_id] = tmp_material;
material = material->NextSiblingElement();
}
// load initial temperatures
if (boost::filesystem::exists(this->initial_temps_matrix_path_)) {
if (!this->initial_temperatures_.read_file_ascii(this->initial_temps_matrix_path_)) return -2;
}
else {
return -1;
}
// load materials configuration
if (boost::filesystem::exists(this->materials_matrix_path_)) {
if (!this->materials_.read_file_ascii(this->materials_matrix_path_)) return -4;
}
else {
return -3;
}
// Check whether the temperature and materials matrices are the same size.
if (this->initial_temperatures_.get_data()->size1() != this->materials_.get_data()->size1()
|| this->initial_temperatures_.get_data()->size2() != this->materials_.get_data()->size2())
{
return -5;
}
// If we got here, life must be good
return 1;
}
int HeatFlowProject::add_material(const Material& new_material) {
// Find the largest currently-used index
int max_index = 0;
for (std::map<int, Material>::iterator it = this->bom_.begin(); it != this->bom_.end(); ++it) {
if (it->first > max_index) {
max_index = it->first;
}
}
// Increment that index to create a new, unused one
int new_index = max_index + 1;
// Assign the new material to the BoM at the computed index
this->bom_[new_index] = new_material;
// Then return it
return new_index;
}
int HeatFlowProject::delete_material(const std::string& name) {
// Find the index in the BoM of a Material named 'name'
for (std::map<int, Material>::iterator it = this->bom_.begin(); it != this->bom_.end(); ++it) {
if (name == it->second.get_name()) {
this->bom_.erase(it);
return 1;
}
}
// If we get here, no materials matched the given name
return 0;
}
int HeatFlowProject::delete_material(int index) {
std::map<int, Material>::iterator it = this->bom_.find(index);
if (it == this->bom_.end()) {
return 0;
}
this->bom_.erase(index);
return 1;
}
} // namespace HeatFlow
<commit_msg>Clean up the path computation code<commit_after>#include "HeatFlowProject.h"
namespace HeatFlow {
HeatFlowProject::HeatFlowProject()
{
this->title_ = "New Sim Project";
this->notes_ = "";
this->initial_temps_matrix_path_ = "Temps.floatfield";
this->materials_matrix_path_ = "Materials.intfield";
this->field_gap_distance_ = 0.00001; // the distance between nodes in the X direction
this->time_step_ = 1; // number of milliseconds between calculation iterations
}
HeatFlowProject::~HeatFlowProject()
{
}
int HeatFlowProject::load_from_file(const std::string& path) {
tinyxml2::XMLDocument doc;
tinyxml2::XMLError load_success = doc.LoadFile(path.c_str());
if (load_success != tinyxml2::XMLError::XML_SUCCESS) {
return 0;
}
tinyxml2::XMLElement *root = doc.FirstChildElement("HeatProject");
// Load the single-value elements
this->title_ = root->FirstChildElement("Title")->GetText();
this->notes_ = root->FirstChildElement("Notes")->GetText();
this->time_step_ = std::strtod(root->FirstChildElement("TimeStep")->GetText(), NULL);
this->field_gap_distance_ = std::strtod(root->FirstChildElement("FieldGapDistance")->GetText(), NULL);
// Get the absolute paths to the data files.
// In the project file, they are specified relative to the config file's directory.
boost::filesystem::path config_path(path);
boost::filesystem::path initial_temps_path(root->FirstChildElement("InitialTemperaturesField")->FirstChildElement("path")->GetText());
this->initial_temps_matrix_path_ = (config_path.parent_path() / initial_temps_path).native();
boost::filesystem::path materials_matrix_path(root->FirstChildElement("MaterialsField")->FirstChildElement("path")->GetText());
this->materials_matrix_path_ = (config_path.parent_path() / materials_matrix_path).native();
// Load the Bill of Materials
tinyxml2::XMLElement *bom = root->FirstChildElement("Materials");
tinyxml2::XMLElement *material = bom->FirstChildElement();
Material tmp_material;
int new_id = 0;
while (material != NULL) {
tmp_material.set_name(material->FirstChildElement("name")->GetText());
tmp_material.set_density(std::strtod(material->FirstChildElement("density")->GetText(), NULL));
tmp_material.set_conductivity(std::strtod(material->FirstChildElement("conductivity")->GetText(), NULL));
new_id = material->IntAttribute("id");
this->bom_[new_id] = tmp_material;
material = material->NextSiblingElement();
}
// load initial temperatures
if (boost::filesystem::exists(this->initial_temps_matrix_path_)) {
if (!this->initial_temperatures_.read_file_ascii(this->initial_temps_matrix_path_)) return -2;
}
else {
return -1;
}
// load materials configuration
if (boost::filesystem::exists(this->materials_matrix_path_)) {
if (!this->materials_.read_file_ascii(this->materials_matrix_path_)) return -4;
}
else {
return -3;
}
// Check whether the temperature and materials matrices are the same size.
if (this->initial_temperatures_.get_data()->size1() != this->materials_.get_data()->size1()
|| this->initial_temperatures_.get_data()->size2() != this->materials_.get_data()->size2())
{
return -5;
}
// If we got here, life must be good
return 1;
}
int HeatFlowProject::add_material(const Material& new_material) {
// Find the largest currently-used index
int max_index = 0;
for (std::map<int, Material>::iterator it = this->bom_.begin(); it != this->bom_.end(); ++it) {
if (it->first > max_index) {
max_index = it->first;
}
}
// Increment that index to create a new, unused one
int new_index = max_index + 1;
// Assign the new material to the BoM at the computed index
this->bom_[new_index] = new_material;
// Then return it
return new_index;
}
int HeatFlowProject::delete_material(const std::string& name) {
// Find the index in the BoM of a Material named 'name'
for (std::map<int, Material>::iterator it = this->bom_.begin(); it != this->bom_.end(); ++it) {
if (name == it->second.get_name()) {
this->bom_.erase(it);
return 1;
}
}
// If we get here, no materials matched the given name
return 0;
}
int HeatFlowProject::delete_material(int index) {
std::map<int, Material>::iterator it = this->bom_.find(index);
if (it == this->bom_.end()) {
return 0;
}
this->bom_.erase(index);
return 1;
}
} // namespace HeatFlow
<|endoftext|> |
<commit_before>#include "SIO/SIOWriter.h"
// -- lcio headers
#include "EVENT/LCEvent.h"
#include "EVENT/LCRunHeader.h"
#include "EVENT/LCIO.h"
#include "EVENT/LCCollection.h"
#include "SIO/LCSIO.h"
// -- sio headers
#include <sio/exception.h>
#include <sio/api.h>
#include <sio/compression/zlib.h>
// -- std headers
#include <sys/stat.h>
namespace SIO {
void SIOWriter::open(const std::string & filename) {
std::string sioFilename ;
getSIOFileName( filename, sioFilename ) ;
struct stat fileinfo ;
// if the file exists we throw an exception
if ( ::stat( sioFilename.c_str(), &fileinfo ) == 0 ) {
throw IO::IOException( std::string( "[SIOWriter::open()] File already exists: "
+ sioFilename
+ " \n open it in append or new mode !\n"
)) ;
}
// open new file for writing
open( filename, EVENT::LCIO::WRITE_NEW ) ;
}
//----------------------------------------------------------------------------
void SIOWriter::getSIOFileName(const std::string& filename, std::string& sioFilename ) {
if( filename.rfind( LCSIO::FileExtension ) == std::string::npos || // .slcio not found at all
!( filename.rfind(LCSIO::FileExtension) + strlen( LCSIO::FileExtension ) == filename.length() ) ) { // found, but not at end
sioFilename = filename + LCSIO::FileExtension ;
}
else {
sioFilename = filename ;
}
}
//----------------------------------------------------------------------------
void SIOWriter::open(const std::string& filename, int writeMode) {
// make sure filename has the proper extension (.slcio)
std::string sioFilename ;
getSIOFileName( filename, sioFilename ) ;
switch( writeMode ) {
case EVENT::LCIO::WRITE_NEW :
_stream.open( sioFilename , std::ios::binary ) ;
break ;
case EVENT::LCIO::WRITE_APPEND :
// try to read the last LCIORandomAccess record at the end --------------------
SIO_DEBUG( "SIOWriter::open: Opening in write append mode" );
sio::ifstream istr ;
istr.open( sioFilename, std::ios::binary ) ;
// status = _stream->open( sioFilename.c_str() , SIO_MODE_READ ) ;
if( not istr.is_open() ) {
throw IO::IOException( std::string( "[SIOWriter::open()] Can't open stream for reading TOC: " + sioFilename ) ) ;
}
SIO_DEBUG( "SIOWriter::open: Opening in write append mode 1" );
bool hasRandomAccess = _raMgr.initAppend(istr ) ;
istr.close() ;
SIO_DEBUG( "SIOWriter::open: Opening in write append mode 2" );
if( hasRandomAccess ) {
_stream.open( sioFilename.c_str() , std::ios::binary | std::ios::out | std::ios::in ) ;
// position at the beginnning of the file record which will then be overwritten with the next record ...
_stream.seekp( 0 , std::ios_base::end ) ;
auto endg = _stream.tellp() ;
if( endg < LCSIO::RandomAccessSize ) {
std::stringstream s ; s << "[SIOWriter::open()] Can't seek stream to " << LCSIO::RandomAccessSize ;
throw IO::IOException( s.str() ) ;
}
sio::ifstream::streampos tpos = LCSIO::RandomAccessSize ;
_stream.seekp( endg - tpos , std::ios_base::beg ) ;
}
else {
_stream.open( sioFilename.c_str() , std::ios::binary | std::ios::out | std::ios::ate ) ;
}
SIO_DEBUG( "SIOWriter::open: Opening in write append mode ... OK" );
break ;
}
if( not _stream.good() or not _stream.is_open() ) {
SIO_THROW( sio::error_code::not_open, "[SIOWriter::open()] Couldn't open file: '" + sioFilename + "'" ) ;
}
}
//----------------------------------------------------------------------------
void SIOWriter::setCompressionLevel(int level) {
_compressor.set_level( level ) ;
}
//----------------------------------------------------------------------------
void SIOWriter::writeRunHeader(const EVENT::LCRunHeader * hdr) {
if( not _stream.is_open() ) {
throw IO::IOException( "[SIOWriter::writeRunHeader] stream not opened") ;
}
sio::record_info recinfo {} ;
SIORunHeaderRecord::writeRecord( _rawBuffer, const_cast<EVENT::LCRunHeader*>(hdr), recinfo, 0 ) ;
// deal with zlib compression here
if( _compressor.level() != 0 ) {
sio::api::compress_record( recinfo, _rawBuffer, _compBuffer, _compressor ) ;
sio::api::write_record( _stream, _rawBuffer.span(0, recinfo._header_length), _compBuffer.span(), recinfo ) ;
}
else {
sio::api::write_record( _stream, _rawBuffer.span(), recinfo ) ;
}
// random access treatment
_raMgr.add( RunEvent( hdr->getRunNumber(), -1 ) , recinfo._file_end ) ;
}
//----------------------------------------------------------------------------
void SIOWriter::writeEvent(const EVENT::LCEvent* evt) {
if( not _stream.is_open() ) {
throw IO::IOException( "[SIOWriter::writeEvent] stream not opened") ;
}
// 1) write the event header record
sio::record_info rechdrinfo {} ;
SIOEventHeaderRecord::writeRecord( _rawBuffer, const_cast<EVENT::LCEvent*>(evt), rechdrinfo, 0 ) ;
// deal with zlib compression here
if( _compressor.level() != 0 ) {
sio::api::compress_record( rechdrinfo, _rawBuffer, _compBuffer, _compressor ) ;
sio::api::write_record( _stream, _rawBuffer.span(0, rechdrinfo._header_length), _compBuffer.span(), rechdrinfo ) ;
}
else {
sio::api::write_record( _stream, _rawBuffer.span(), rechdrinfo ) ;
}
// random access treatment
_raMgr.add( RunEvent( evt->getRunNumber(), evt->getEventNumber() ) , rechdrinfo._file_start ) ;
// 2) write the event record
sio::record_info recinfo {} ;
SIOEventRecord::writeRecord( _rawBuffer, const_cast<EVENT::LCEvent*>(evt), _eventHandlerMgr, recinfo, 0 ) ;
// deal with zlib compression here
if( _compressor.level() != 0 ) {
sio::api::compress_record( recinfo, _rawBuffer, _compBuffer, _compressor ) ;
sio::api::write_record( _stream, _rawBuffer.span(0, recinfo._header_length), _compBuffer.span(), recinfo ) ;
}
else {
sio::api::write_record( _stream, _rawBuffer.span(), recinfo ) ;
}
}
//----------------------------------------------------------------------------
void SIOWriter::close() {
_raMgr.writeRandomAccessRecords( _stream ) ;
_raMgr.clear() ;
_stream.close();
}
//----------------------------------------------------------------------------
void SIOWriter::flush() {
_stream.flush() ;
}
} // namespace
<commit_msg>Fixed random access mapping on run header writing<commit_after>#include "SIO/SIOWriter.h"
// -- lcio headers
#include "EVENT/LCEvent.h"
#include "EVENT/LCRunHeader.h"
#include "EVENT/LCIO.h"
#include "EVENT/LCCollection.h"
#include "SIO/LCSIO.h"
// -- sio headers
#include <sio/exception.h>
#include <sio/api.h>
#include <sio/compression/zlib.h>
// -- std headers
#include <sys/stat.h>
namespace SIO {
void SIOWriter::open(const std::string & filename) {
std::string sioFilename ;
getSIOFileName( filename, sioFilename ) ;
struct stat fileinfo ;
// if the file exists we throw an exception
if ( ::stat( sioFilename.c_str(), &fileinfo ) == 0 ) {
throw IO::IOException( std::string( "[SIOWriter::open()] File already exists: "
+ sioFilename
+ " \n open it in append or new mode !\n"
)) ;
}
// open new file for writing
open( filename, EVENT::LCIO::WRITE_NEW ) ;
}
//----------------------------------------------------------------------------
void SIOWriter::getSIOFileName(const std::string& filename, std::string& sioFilename ) {
if( filename.rfind( LCSIO::FileExtension ) == std::string::npos || // .slcio not found at all
!( filename.rfind(LCSIO::FileExtension) + strlen( LCSIO::FileExtension ) == filename.length() ) ) { // found, but not at end
sioFilename = filename + LCSIO::FileExtension ;
}
else {
sioFilename = filename ;
}
}
//----------------------------------------------------------------------------
void SIOWriter::open(const std::string& filename, int writeMode) {
// make sure filename has the proper extension (.slcio)
std::string sioFilename ;
getSIOFileName( filename, sioFilename ) ;
switch( writeMode ) {
case EVENT::LCIO::WRITE_NEW :
_stream.open( sioFilename , std::ios::binary ) ;
break ;
case EVENT::LCIO::WRITE_APPEND :
// try to read the last LCIORandomAccess record at the end --------------------
SIO_DEBUG( "SIOWriter::open: Opening in write append mode" );
sio::ifstream istr ;
istr.open( sioFilename, std::ios::binary ) ;
// status = _stream->open( sioFilename.c_str() , SIO_MODE_READ ) ;
if( not istr.is_open() ) {
throw IO::IOException( std::string( "[SIOWriter::open()] Can't open stream for reading TOC: " + sioFilename ) ) ;
}
SIO_DEBUG( "SIOWriter::open: Opening in write append mode 1" );
bool hasRandomAccess = _raMgr.initAppend(istr ) ;
istr.close() ;
SIO_DEBUG( "SIOWriter::open: Opening in write append mode 2" );
if( hasRandomAccess ) {
_stream.open( sioFilename.c_str() , std::ios::binary | std::ios::out | std::ios::in ) ;
// position at the beginnning of the file record which will then be overwritten with the next record ...
_stream.seekp( 0 , std::ios_base::end ) ;
auto endg = _stream.tellp() ;
if( endg < LCSIO::RandomAccessSize ) {
std::stringstream s ; s << "[SIOWriter::open()] Can't seek stream to " << LCSIO::RandomAccessSize ;
throw IO::IOException( s.str() ) ;
}
sio::ifstream::streampos tpos = LCSIO::RandomAccessSize ;
_stream.seekp( endg - tpos , std::ios_base::beg ) ;
}
else {
_stream.open( sioFilename.c_str() , std::ios::binary | std::ios::out | std::ios::ate ) ;
}
SIO_DEBUG( "SIOWriter::open: Opening in write append mode ... OK" );
break ;
}
if( not _stream.good() or not _stream.is_open() ) {
SIO_THROW( sio::error_code::not_open, "[SIOWriter::open()] Couldn't open file: '" + sioFilename + "'" ) ;
}
}
//----------------------------------------------------------------------------
void SIOWriter::setCompressionLevel(int level) {
_compressor.set_level( level ) ;
}
//----------------------------------------------------------------------------
void SIOWriter::writeRunHeader(const EVENT::LCRunHeader * hdr) {
if( not _stream.is_open() ) {
throw IO::IOException( "[SIOWriter::writeRunHeader] stream not opened") ;
}
sio::record_info recinfo {} ;
SIORunHeaderRecord::writeRecord( _rawBuffer, const_cast<EVENT::LCRunHeader*>(hdr), recinfo, 0 ) ;
// deal with zlib compression here
if( _compressor.level() != 0 ) {
sio::api::compress_record( recinfo, _rawBuffer, _compBuffer, _compressor ) ;
sio::api::write_record( _stream, _rawBuffer.span(0, recinfo._header_length), _compBuffer.span(), recinfo ) ;
}
else {
sio::api::write_record( _stream, _rawBuffer.span(), recinfo ) ;
}
// random access treatment
_raMgr.add( RunEvent( hdr->getRunNumber(), -1 ) , recinfo._file_start ) ;
}
//----------------------------------------------------------------------------
void SIOWriter::writeEvent(const EVENT::LCEvent* evt) {
if( not _stream.is_open() ) {
throw IO::IOException( "[SIOWriter::writeEvent] stream not opened") ;
}
// 1) write the event header record
sio::record_info rechdrinfo {} ;
SIOEventHeaderRecord::writeRecord( _rawBuffer, const_cast<EVENT::LCEvent*>(evt), rechdrinfo, 0 ) ;
// deal with zlib compression here
if( _compressor.level() != 0 ) {
sio::api::compress_record( rechdrinfo, _rawBuffer, _compBuffer, _compressor ) ;
sio::api::write_record( _stream, _rawBuffer.span(0, rechdrinfo._header_length), _compBuffer.span(), rechdrinfo ) ;
}
else {
sio::api::write_record( _stream, _rawBuffer.span(), rechdrinfo ) ;
}
// random access treatment
_raMgr.add( RunEvent( evt->getRunNumber(), evt->getEventNumber() ) , rechdrinfo._file_start ) ;
// 2) write the event record
sio::record_info recinfo {} ;
SIOEventRecord::writeRecord( _rawBuffer, const_cast<EVENT::LCEvent*>(evt), _eventHandlerMgr, recinfo, 0 ) ;
// deal with zlib compression here
if( _compressor.level() != 0 ) {
sio::api::compress_record( recinfo, _rawBuffer, _compBuffer, _compressor ) ;
sio::api::write_record( _stream, _rawBuffer.span(0, recinfo._header_length), _compBuffer.span(), recinfo ) ;
}
else {
sio::api::write_record( _stream, _rawBuffer.span(), recinfo ) ;
}
}
//----------------------------------------------------------------------------
void SIOWriter::close() {
_raMgr.writeRandomAccessRecords( _stream ) ;
_raMgr.clear() ;
_stream.close();
}
//----------------------------------------------------------------------------
void SIOWriter::flush() {
_stream.flush() ;
}
} // namespace
<|endoftext|> |
<commit_before>#include "testing/testing.hpp"
#include "platform/mwm_version.hpp"
#include "platform/platform.hpp"
#include "defines.hpp"
#include "coding/file_name_utils.hpp"
#include "coding/file_writer.hpp"
#include "coding/internal/file_data.hpp"
#include "base/logging.hpp"
#include "base/scope_guard.hpp"
#include "std/bind.hpp"
#include "std/initializer_list.hpp"
#include "std/set.hpp"
namespace
{
char const * TEST_FILE_NAME = "some_temporary_unit_test_file.tmp";
void CheckFilesPresence(string const & baseDir, unsigned typeMask,
initializer_list<pair<string, size_t>> const & files)
{
Platform::TFilesWithType fwts;
Platform::GetFilesByType(baseDir, typeMask, fwts);
multiset<string> filesSet;
for (auto const & fwt : fwts)
filesSet.insert(fwt.first);
for (auto const & file : files)
TEST_EQUAL(filesSet.count(file.first), file.second, (file.first, file.second));
}
} // namespace
UNIT_TEST(WritableDir)
{
string const path = GetPlatform().WritableDir() + TEST_FILE_NAME;
try
{
my::FileData f(path, my::FileData::OP_WRITE_TRUNCATE);
}
catch (Writer::OpenException const &)
{
LOG(LCRITICAL, ("Can't create file"));
return;
}
my::DeleteFileX(path);
}
UNIT_TEST(WritablePathForFile)
{
Platform & pl = GetPlatform();
string const p1 = pl.WritableDir() + TEST_FILE_NAME;
string const p2 = pl.WritablePathForFile(TEST_FILE_NAME);
TEST_EQUAL(p1, p2, ());
}
UNIT_TEST(GetReader)
{
char const * NON_EXISTING_FILE = "mgbwuerhsnmbui45efhdbn34.tmp";
char const * arr[] = {
"resources-ldpi_legacy/symbols.sdf",
"classificator.txt",
"minsk-pass.mwm"
};
Platform & p = GetPlatform();
for (size_t i = 0; i < ARRAY_SIZE(arr); ++i)
{
ReaderPtr<Reader> r = p.GetReader(arr[i]);
TEST_GREATER(r.Size(), 0, ("File should exist!"));
}
bool wasException = false;
try
{
ReaderPtr<Reader> r = p.GetReader(NON_EXISTING_FILE);
}
catch (FileAbsentException const &)
{
wasException = true;
}
TEST_EQUAL(wasException, true, ());
}
UNIT_TEST(GetFilesInDir_Smoke)
{
Platform & pl = GetPlatform();
Platform::FilesList files1, files2;
string const dir = pl.WritableDir();
pl.GetFilesByExt(dir, DATA_FILE_EXTENSION, files1);
TEST_GREATER(files1.size(), 0, ("/data/ folder should contain some data files"));
pl.GetFilesByRegExp(dir, ".*\\" DATA_FILE_EXTENSION "$", files2);
TEST_EQUAL(files1, files2, ());
files1.clear();
pl.GetFilesByExt(dir, ".dsa", files1);
TEST_EQUAL(files1.size(), 0, ());
}
UNIT_TEST(DirsRoutines)
{
Platform & platform = GetPlatform();
string const baseDir = platform.WritableDir();
string const testDir = my::JoinFoldersToPath(baseDir, "test-dir");
string const testFile = my::JoinFoldersToPath(testDir, "test-file");
TEST(!Platform::IsFileExistsByFullPath(testDir), ());
TEST_EQUAL(platform.MkDir(testDir), Platform::ERR_OK, ());
TEST(Platform::IsFileExistsByFullPath(testDir), ());
TEST(Platform::IsDirectoryEmpty(testDir), ());
{
FileWriter writer(testFile);
}
TEST(!Platform::IsDirectoryEmpty(testDir), ());
FileWriter::DeleteFileX(testFile);
TEST_EQUAL(Platform::RmDir(testDir), Platform::ERR_OK, ());
TEST(!Platform::IsFileExistsByFullPath(testDir), ());
}
UNIT_TEST(GetFilesByType)
{
string const kTestDirBaseName = "test-dir";
string const kTestFileBaseName = "test-file";
Platform & platform = GetPlatform();
string const baseDir = platform.WritableDir();
string const testDir = my::JoinFoldersToPath(baseDir, kTestDirBaseName);
TEST_EQUAL(platform.MkDir(testDir), Platform::ERR_OK, ());
MY_SCOPE_GUARD(removeTestDir, bind(&Platform::RmDir, testDir));
string const testFile = my::JoinFoldersToPath(baseDir, kTestFileBaseName);
TEST(!Platform::IsFileExistsByFullPath(testFile), ());
{
FileWriter writer(testFile);
}
TEST(Platform::IsFileExistsByFullPath(testFile), ());
MY_SCOPE_GUARD(removeTestFile, bind(FileWriter::DeleteFileX, testFile));
CheckFilesPresence(baseDir, Platform::FILE_TYPE_DIRECTORY,
{{
kTestDirBaseName, 1 /* present */
},
{
kTestFileBaseName, 0 /* not present */
}});
CheckFilesPresence(baseDir, Platform::FILE_TYPE_REGULAR,
{{
kTestDirBaseName, 0 /* not present */
},
{
kTestFileBaseName, 1 /* present */
}});
CheckFilesPresence(baseDir, Platform::FILE_TYPE_DIRECTORY | Platform::FILE_TYPE_REGULAR,
{{
kTestDirBaseName, 1 /* present */
},
{
kTestFileBaseName, 1 /* present */
}});
}
UNIT_TEST(GetFileSize)
{
Platform & pl = GetPlatform();
uint64_t size = 123141;
TEST(!pl.GetFileSizeByName("adsmngfuwrbfyfwe", size), ());
TEST(!pl.IsFileExistsByFullPath("adsmngfuwrbfyfwe"), ());
{
FileWriter testFile(TEST_FILE_NAME);
testFile.Write("HOHOHO", 6);
}
size = 0;
TEST(Platform::GetFileSizeByFullPath(TEST_FILE_NAME, size), ());
TEST_EQUAL(size, 6, ());
FileWriter::DeleteFileX(TEST_FILE_NAME);
{
FileWriter testFile(pl.WritablePathForFile(TEST_FILE_NAME));
testFile.Write("HOHOHO", 6);
}
size = 0;
TEST(pl.GetFileSizeByName(TEST_FILE_NAME, size), ());
TEST_EQUAL(size, 6, ());
FileWriter::DeleteFileX(pl.WritablePathForFile(TEST_FILE_NAME));
}
UNIT_TEST(CpuCores)
{
int const coresNum = GetPlatform().CpuCores();
TEST_GREATER(coresNum, 0, ());
TEST_LESS_OR_EQUAL(coresNum, 128, ());
}
UNIT_TEST(GetWritableStorageStatus)
{
TEST_EQUAL(Platform::STORAGE_OK, GetPlatform().GetWritableStorageStatus(100000), ());
TEST_EQUAL(Platform::NOT_ENOUGH_SPACE, GetPlatform().GetWritableStorageStatus(uint64_t(-1)), ());
}
UNIT_TEST(RmDirRecursively)
{
Platform & platform = GetPlatform();
string const testDir1 = my::JoinFoldersToPath(platform.WritableDir(), "test_dir1");
TEST_EQUAL(platform.MkDir(testDir1), Platform::ERR_OK, ());
MY_SCOPE_GUARD(removeTestDir1, bind(&Platform::RmDir, testDir1));
string const testDir2 = my::JoinFoldersToPath(testDir1, "test_dir2");
TEST_EQUAL(platform.MkDir(testDir2), Platform::ERR_OK, ());
MY_SCOPE_GUARD(removeTestDir2, bind(&Platform::RmDir, testDir2));
string const filePath = my::JoinFoldersToPath(testDir2, "test_file");
{
FileWriter testFile(filePath);
testFile.Write("HOHOHO", 6);
}
MY_SCOPE_GUARD(removeTestFile, bind(&my::DeleteFileX, filePath));
TEST(Platform::IsFileExistsByFullPath(filePath), ());
TEST(Platform::IsFileExistsByFullPath(testDir1), ());
TEST(Platform::IsFileExistsByFullPath(testDir2), ());
TEST_EQUAL(Platform::ERR_DIRECTORY_NOT_EMPTY, Platform::RmDir(testDir1), ());
TEST(Platform::IsFileExistsByFullPath(filePath), ());
TEST(Platform::IsFileExistsByFullPath(testDir1), ());
TEST(Platform::IsFileExistsByFullPath(testDir2), ());
TEST(Platform::RmDirRecursively(testDir1), ());
TEST(!Platform::IsFileExistsByFullPath(filePath), ());
TEST(!Platform::IsFileExistsByFullPath(testDir1), ());
TEST(!Platform::IsFileExistsByFullPath(testDir2), ());
}
UNIT_TEST(IsSingleMwm)
{
TEST(version::IsSingleMwm(version::FOR_TESTING_SINGLE_MWM1), ());
TEST(version::IsSingleMwm(version::FOR_TESTING_SINGLE_MWM_LATEST), ());
TEST(!version::IsSingleMwm(version::FOR_TESTING_TWO_COMPONENT_MWM1), ());
TEST(!version::IsSingleMwm(version::FOR_TESTING_TWO_COMPONENT_MWM2), ());
}
<commit_msg>Add path to log output in WritableDir test<commit_after>#include "testing/testing.hpp"
#include "platform/mwm_version.hpp"
#include "platform/platform.hpp"
#include "defines.hpp"
#include "coding/file_name_utils.hpp"
#include "coding/file_writer.hpp"
#include "coding/internal/file_data.hpp"
#include "base/logging.hpp"
#include "base/scope_guard.hpp"
#include "std/bind.hpp"
#include "std/initializer_list.hpp"
#include "std/set.hpp"
namespace
{
char const * TEST_FILE_NAME = "some_temporary_unit_test_file.tmp";
void CheckFilesPresence(string const & baseDir, unsigned typeMask,
initializer_list<pair<string, size_t>> const & files)
{
Platform::TFilesWithType fwts;
Platform::GetFilesByType(baseDir, typeMask, fwts);
multiset<string> filesSet;
for (auto const & fwt : fwts)
filesSet.insert(fwt.first);
for (auto const & file : files)
TEST_EQUAL(filesSet.count(file.first), file.second, (file.first, file.second));
}
} // namespace
UNIT_TEST(WritableDir)
{
string const path = GetPlatform().WritableDir() + TEST_FILE_NAME;
try
{
my::FileData f(path, my::FileData::OP_WRITE_TRUNCATE);
}
catch (Writer::OpenException const &)
{
LOG(LCRITICAL, ("Can't create file", path));
return;
}
my::DeleteFileX(path);
}
UNIT_TEST(WritablePathForFile)
{
Platform & pl = GetPlatform();
string const p1 = pl.WritableDir() + TEST_FILE_NAME;
string const p2 = pl.WritablePathForFile(TEST_FILE_NAME);
TEST_EQUAL(p1, p2, ());
}
UNIT_TEST(GetReader)
{
char const * NON_EXISTING_FILE = "mgbwuerhsnmbui45efhdbn34.tmp";
char const * arr[] = {
"resources-ldpi_legacy/symbols.sdf",
"classificator.txt",
"minsk-pass.mwm"
};
Platform & p = GetPlatform();
for (size_t i = 0; i < ARRAY_SIZE(arr); ++i)
{
ReaderPtr<Reader> r = p.GetReader(arr[i]);
TEST_GREATER(r.Size(), 0, ("File should exist!"));
}
bool wasException = false;
try
{
ReaderPtr<Reader> r = p.GetReader(NON_EXISTING_FILE);
}
catch (FileAbsentException const &)
{
wasException = true;
}
TEST_EQUAL(wasException, true, ());
}
UNIT_TEST(GetFilesInDir_Smoke)
{
Platform & pl = GetPlatform();
Platform::FilesList files1, files2;
string const dir = pl.WritableDir();
pl.GetFilesByExt(dir, DATA_FILE_EXTENSION, files1);
TEST_GREATER(files1.size(), 0, ("/data/ folder should contain some data files"));
pl.GetFilesByRegExp(dir, ".*\\" DATA_FILE_EXTENSION "$", files2);
TEST_EQUAL(files1, files2, ());
files1.clear();
pl.GetFilesByExt(dir, ".dsa", files1);
TEST_EQUAL(files1.size(), 0, ());
}
UNIT_TEST(DirsRoutines)
{
Platform & platform = GetPlatform();
string const baseDir = platform.WritableDir();
string const testDir = my::JoinFoldersToPath(baseDir, "test-dir");
string const testFile = my::JoinFoldersToPath(testDir, "test-file");
TEST(!Platform::IsFileExistsByFullPath(testDir), ());
TEST_EQUAL(platform.MkDir(testDir), Platform::ERR_OK, ());
TEST(Platform::IsFileExistsByFullPath(testDir), ());
TEST(Platform::IsDirectoryEmpty(testDir), ());
{
FileWriter writer(testFile);
}
TEST(!Platform::IsDirectoryEmpty(testDir), ());
FileWriter::DeleteFileX(testFile);
TEST_EQUAL(Platform::RmDir(testDir), Platform::ERR_OK, ());
TEST(!Platform::IsFileExistsByFullPath(testDir), ());
}
UNIT_TEST(GetFilesByType)
{
string const kTestDirBaseName = "test-dir";
string const kTestFileBaseName = "test-file";
Platform & platform = GetPlatform();
string const baseDir = platform.WritableDir();
string const testDir = my::JoinFoldersToPath(baseDir, kTestDirBaseName);
TEST_EQUAL(platform.MkDir(testDir), Platform::ERR_OK, ());
MY_SCOPE_GUARD(removeTestDir, bind(&Platform::RmDir, testDir));
string const testFile = my::JoinFoldersToPath(baseDir, kTestFileBaseName);
TEST(!Platform::IsFileExistsByFullPath(testFile), ());
{
FileWriter writer(testFile);
}
TEST(Platform::IsFileExistsByFullPath(testFile), ());
MY_SCOPE_GUARD(removeTestFile, bind(FileWriter::DeleteFileX, testFile));
CheckFilesPresence(baseDir, Platform::FILE_TYPE_DIRECTORY,
{{
kTestDirBaseName, 1 /* present */
},
{
kTestFileBaseName, 0 /* not present */
}});
CheckFilesPresence(baseDir, Platform::FILE_TYPE_REGULAR,
{{
kTestDirBaseName, 0 /* not present */
},
{
kTestFileBaseName, 1 /* present */
}});
CheckFilesPresence(baseDir, Platform::FILE_TYPE_DIRECTORY | Platform::FILE_TYPE_REGULAR,
{{
kTestDirBaseName, 1 /* present */
},
{
kTestFileBaseName, 1 /* present */
}});
}
UNIT_TEST(GetFileSize)
{
Platform & pl = GetPlatform();
uint64_t size = 123141;
TEST(!pl.GetFileSizeByName("adsmngfuwrbfyfwe", size), ());
TEST(!pl.IsFileExistsByFullPath("adsmngfuwrbfyfwe"), ());
{
FileWriter testFile(TEST_FILE_NAME);
testFile.Write("HOHOHO", 6);
}
size = 0;
TEST(Platform::GetFileSizeByFullPath(TEST_FILE_NAME, size), ());
TEST_EQUAL(size, 6, ());
FileWriter::DeleteFileX(TEST_FILE_NAME);
{
FileWriter testFile(pl.WritablePathForFile(TEST_FILE_NAME));
testFile.Write("HOHOHO", 6);
}
size = 0;
TEST(pl.GetFileSizeByName(TEST_FILE_NAME, size), ());
TEST_EQUAL(size, 6, ());
FileWriter::DeleteFileX(pl.WritablePathForFile(TEST_FILE_NAME));
}
UNIT_TEST(CpuCores)
{
int const coresNum = GetPlatform().CpuCores();
TEST_GREATER(coresNum, 0, ());
TEST_LESS_OR_EQUAL(coresNum, 128, ());
}
UNIT_TEST(GetWritableStorageStatus)
{
TEST_EQUAL(Platform::STORAGE_OK, GetPlatform().GetWritableStorageStatus(100000), ());
TEST_EQUAL(Platform::NOT_ENOUGH_SPACE, GetPlatform().GetWritableStorageStatus(uint64_t(-1)), ());
}
UNIT_TEST(RmDirRecursively)
{
Platform & platform = GetPlatform();
string const testDir1 = my::JoinFoldersToPath(platform.WritableDir(), "test_dir1");
TEST_EQUAL(platform.MkDir(testDir1), Platform::ERR_OK, ());
MY_SCOPE_GUARD(removeTestDir1, bind(&Platform::RmDir, testDir1));
string const testDir2 = my::JoinFoldersToPath(testDir1, "test_dir2");
TEST_EQUAL(platform.MkDir(testDir2), Platform::ERR_OK, ());
MY_SCOPE_GUARD(removeTestDir2, bind(&Platform::RmDir, testDir2));
string const filePath = my::JoinFoldersToPath(testDir2, "test_file");
{
FileWriter testFile(filePath);
testFile.Write("HOHOHO", 6);
}
MY_SCOPE_GUARD(removeTestFile, bind(&my::DeleteFileX, filePath));
TEST(Platform::IsFileExistsByFullPath(filePath), ());
TEST(Platform::IsFileExistsByFullPath(testDir1), ());
TEST(Platform::IsFileExistsByFullPath(testDir2), ());
TEST_EQUAL(Platform::ERR_DIRECTORY_NOT_EMPTY, Platform::RmDir(testDir1), ());
TEST(Platform::IsFileExistsByFullPath(filePath), ());
TEST(Platform::IsFileExistsByFullPath(testDir1), ());
TEST(Platform::IsFileExistsByFullPath(testDir2), ());
TEST(Platform::RmDirRecursively(testDir1), ());
TEST(!Platform::IsFileExistsByFullPath(filePath), ());
TEST(!Platform::IsFileExistsByFullPath(testDir1), ());
TEST(!Platform::IsFileExistsByFullPath(testDir2), ());
}
UNIT_TEST(IsSingleMwm)
{
TEST(version::IsSingleMwm(version::FOR_TESTING_SINGLE_MWM1), ());
TEST(version::IsSingleMwm(version::FOR_TESTING_SINGLE_MWM_LATEST), ());
TEST(!version::IsSingleMwm(version::FOR_TESTING_TWO_COMPONENT_MWM1), ());
TEST(!version::IsSingleMwm(version::FOR_TESTING_TWO_COMPONENT_MWM2), ());
}
<|endoftext|> |
<commit_before>#pragma once
#include <vector>
namespace KickStartAlarm {
template <typename IntType>
static IntType quickPowerWithModulo(IntType base, IntType exp, IntType modulo) {
auto mod = [modulo](const auto value) { return value % modulo; };
IntType t{1u};
while (exp != 0) {
if (exp % 2 == 1)
t = mod(t * base);
base = mod(base * base);
exp /= 2;
}
return t;
};
template <typename IntType>
static IntType calculatePOWER_K(IntType N, IntType K, IntType x1, IntType y1, IntType C, IntType D, IntType E1,
IntType E2, IntType F, IntType resultModulo) {
x1 %= F;
y1 %= F;
C %= F;
D %= F;
E1 %= F;
E2 %= F;
std::vector<IntType> A;
A.reserve(N);
{
auto modF = [&F](const auto val) { return val % F; };
A.push_back(modF(x1 + y1));
IntType prevX{x1};
IntType prevY{y1};
for (auto i{1u}; i < N; ++i) {
const auto currentX = modF(C * prevX + D * prevY + E1);
const auto currentY = modF(D * prevX + C * prevY + E2);
A.push_back(modF(currentX + currentY));
prevX = currentX;
prevY = currentY;
}
}
auto modResult = [&resultModulo](const auto val) { return val % resultModulo; };
auto quickPowerWithResultModulo = [&resultModulo](auto base, auto exp) {
return quickPowerWithModulo(base, exp, resultModulo);
};
auto moduloInverse = [&resultModulo, &quickPowerWithResultModulo](const auto val) {
return quickPowerWithResultModulo(val, resultModulo - 2u);
};
IntType POWER_K{0u};
IntType totalSumOfGeometricProgressions{K};
// POWER_K(A) = power_1(A) + power_2(A) + ... + power_K(A) =
// = (N + 1 - 1)(1^1)A_1 + (N + 1 - 2)(1^1 + 2^1)A_2 + ... (N + 1 - N)(1^1 + 2^1 + ... + N^1)A_N +
// + (N + 1 - 1)(1^2)A_1 + (N + 1 - 2)(1^2 + 2^2)A_2 + ... (N + 1 - N)(1^2 + 2^2 + ... + N^2)A_N +
// + ... +
// + (N + 1 - 1)(1^K)A_1 + (N + 1 - 2)(1^K + 2^K)A_2 + ... (N + 1 - N)(1^K + 2^K + ... + N^K)A_N =
// = (N + 1 - 1)(1^1 + 1^2 + ... + 1^K)A_1 +
// + (N + 1 - 2)(1^1 + 1^2 + ... + 1^K + 2^1 + 2^2 + ... + 2^K)A_2 +
// + ... +
// + (N + 1 - N)(1^1 + 1^2 + ... + 1^K + 2^1 + 2^2 + ... + 2^K + ... + N^1 + N^2 + ... + N^K)A_N
for (IntType x{1u}; x <= N; ++x) {
if (x != 1u) {
// Sum of geometric progression
// x^1 + x^2 + ... + x^K =
// = x(1 - x^K)/(1 - x) =
// = (x - x^(K + 1))/(1 - x) =
// = (x^(K+1) - x)/(x - 1) =
// = (x^(K+1) - x)(x - 1)^(-1)
// | t1 || t2 |
const auto t1 = resultModulo + quickPowerWithResultModulo(x, K + 1u) - x;
// Calculate modular inverse using Euler-theorem
// (x - 1)^(-1) mod M = (x - 1)^(M - 2) mod M
const auto t2 = moduloInverse(x - 1u);
const auto sumOfSingleGeometricProgression = modResult(t1 * t2);
totalSumOfGeometricProgressions = modResult(totalSumOfGeometricProgressions + sumOfSingleGeometricProgression);
}
POWER_K = modResult(POWER_K + modResult(modResult(totalSumOfGeometricProgressions * A[x - 1u]) * (N + 1u - x)));
}
return POWER_K;
}
}; // namespace KickStartAlarm<commit_msg>Fix with modulo 67<commit_after>#pragma once
#include <vector>
namespace KickStartAlarm {
template <typename IntType>
static IntType quickPowerWithModulo(IntType base, IntType exp, IntType modulo) {
auto mod = [modulo](const auto value) { return value % modulo; };
IntType t{1u};
while (exp != 0) {
if (exp % 2 == 1)
t = mod(t * base);
base = mod(base * base);
exp /= 2;
}
return t;
};
template <typename IntType>
static IntType calculatePOWER_K(IntType N, IntType K, IntType x1, IntType y1, IntType C, IntType D, IntType E1,
IntType E2, IntType F, IntType resultModulo) {
x1 %= F;
y1 %= F;
C %= F;
D %= F;
E1 %= F;
E2 %= F;
std::vector<IntType> A;
A.reserve(N);
{
auto modF = [&F](const auto val) { return val % F; };
A.push_back(modF(x1 + y1));
IntType prevX{x1};
IntType prevY{y1};
for (auto i{1u}; i < N; ++i) {
const auto currentX = modF(C * prevX + D * prevY + E1);
const auto currentY = modF(D * prevX + C * prevY + E2);
A.push_back(modF(currentX + currentY));
prevX = currentX;
prevY = currentY;
}
}
auto modResult = [&resultModulo](const auto val) { return val % resultModulo; };
auto quickPowerWithResultModulo = [&resultModulo](auto base, auto exp) {
return quickPowerWithModulo(base, exp, resultModulo);
};
auto moduloInverse = [&resultModulo, &quickPowerWithResultModulo](const auto val) {
return quickPowerWithResultModulo(val, resultModulo - 2u);
};
IntType POWER_K{0u};
IntType totalSumOfGeometricProgressions{K};
// POWER_K(A) = power_1(A) + power_2(A) + ... + power_K(A) =
// = (N + 1 - 1)(1^1)A_1 + (N + 1 - 2)(1^1 + 2^1)A_2 + ... (N + 1 - N)(1^1 + 2^1 + ... + N^1)A_N +
// + (N + 1 - 1)(1^2)A_1 + (N + 1 - 2)(1^2 + 2^2)A_2 + ... (N + 1 - N)(1^2 + 2^2 + ... + N^2)A_N +
// + ... +
// + (N + 1 - 1)(1^K)A_1 + (N + 1 - 2)(1^K + 2^K)A_2 + ... (N + 1 - N)(1^K + 2^K + ... + N^K)A_N =
// = (N + 1 - 1)(1^1 + 1^2 + ... + 1^K)A_1 +
// + (N + 1 - 2)(1^1 + 1^2 + ... + 1^K + 2^1 + 2^2 + ... + 2^K)A_2 +
// + ... +
// + (N + 1 - N)(1^1 + 1^2 + ... + 1^K + 2^1 + 2^2 + ... + 2^K + ... + N^1 + N^2 + ... + N^K)A_N
for (IntType x{1u}; x <= N; ++x) {
if (x != 1u) {
// Sum of geometric progression
// x^1 + x^2 + ... + x^K =
// = (1 - x^(K+1))/(1 - x) =
// = (x^(K+1) - 1)/(x - 1) =
// = (x^(K+1) - 1)(x - 1)^(-1)
// | t1 || t2 |
const auto t1 = modResult(quickPowerWithResultModulo(x, K + 1u) + resultModulo - 1);
// Calculate modular inverse using Euler-theorem
// (x - 1)^(-1) mod M = (x - 1)^(M - 2) mod M
const auto t2 = moduloInverse(x - 1u);
const auto sumOfSingleGeometricProgression = modResult(modResult(t1 * t2) + resultModulo - 1);
totalSumOfGeometricProgressions = modResult(totalSumOfGeometricProgressions + sumOfSingleGeometricProgression);
}
POWER_K = modResult(POWER_K + modResult(modResult(totalSumOfGeometricProgressions * A[x - 1u]) * (N + 1u - x)));
}
return POWER_K;
}
}; // namespace KickStartAlarm<|endoftext|> |
<commit_before>#include "MapController.h"
#include "fakeit.hpp"
class MapControllerStub: public tsg::map::MapController {
virtual void loadMapFromFile(const std::string &) {}
// virtual void initTouchEvents() {}
public:
MapControllerStub() : MapController(nullptr) {}
};
using namespace fakeit;
TEST_CASE("That map listener will be notified on map load", "[MapController]") {
Mock<tsg::map::IMapEventListener> listenerMock;
MapControllerStub mapControllerStub;
When(Method(listenerMock, onMapLoad)).Return();
mapControllerStub.registerListener(&listenerMock.get());
Verify(Method(listenerMock, onMapLoad)).Exactly(0);
mapControllerStub.loadMap("test/map");
Verify(Method(listenerMock, onMapLoad)).Exactly(1);
}
<commit_msg>disable broken tests<commit_after>#include "MapController.h"
#include "fakeit.hpp"
class MapControllerStub: public tsg::map::MapController {
virtual void loadMapFromFile(const std::string &) {}
// virtual void initTouchEvents() {}
public:
MapControllerStub() : MapController(nullptr) {}
};
using namespace fakeit;
TEST_CASE("That map listener will be notified on map load", "[MapController]") {
Mock<tsg::map::IMapEventListener> listenerMock;
MapControllerStub mapControllerStub;
When(Method(listenerMock, onMapLoad)).Return();
mapControllerStub.registerListener(&listenerMock.get());
Verify(Method(listenerMock, onMapLoad)).Exactly(0);
// mapControllerStub.loadMap("test/map");
// Verify(Method(listenerMock, onMapLoad)).Exactly(1);
}
<|endoftext|> |
<commit_before>//===-- ValueObjectChild.cpp ------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Core/ValueObjectChild.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ValueObjectList.h"
#include "lldb/Symbol/CompilerType.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/SymbolContext.h"
#include "lldb/Symbol/Type.h"
#include "lldb/Symbol/Variable.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"
using namespace lldb_private;
ValueObjectChild::ValueObjectChild
(
ValueObject &parent,
const CompilerType &compiler_type,
const ConstString &name,
uint64_t byte_size,
int32_t byte_offset,
uint32_t bitfield_bit_size,
uint32_t bitfield_bit_offset,
bool is_base_class,
bool is_deref_of_parent,
AddressType child_ptr_or_ref_addr_type,
uint64_t language_flags
) :
ValueObject (parent),
m_compiler_type (compiler_type),
m_byte_size (byte_size),
m_byte_offset (byte_offset),
m_bitfield_bit_size (bitfield_bit_size),
m_bitfield_bit_offset (bitfield_bit_offset),
m_is_base_class (is_base_class),
m_is_deref_of_parent (is_deref_of_parent),
m_can_update_with_invalid_exe_ctx()
{
m_name = name;
SetAddressTypeOfChildren(child_ptr_or_ref_addr_type);
SetLanguageFlags(language_flags);
}
ValueObjectChild::~ValueObjectChild()
{
}
lldb::ValueType
ValueObjectChild::GetValueType() const
{
return m_parent->GetValueType();
}
size_t
ValueObjectChild::CalculateNumChildren(uint32_t max)
{
auto children_count = GetCompilerType().GetNumChildren (true);
return children_count <= max ? children_count : max;
}
static void
AdjustForBitfieldness(ConstString& name,
uint8_t bitfield_bit_size)
{
if (name && bitfield_bit_size)
{
const char *compiler_type_name = name.AsCString();
if (compiler_type_name)
{
std::vector<char> bitfield_type_name (strlen(compiler_type_name) + 32, 0);
::snprintf (&bitfield_type_name.front(), bitfield_type_name.size(), "%s:%u", compiler_type_name, bitfield_bit_size);
name.SetCString(&bitfield_type_name.front());
}
}
}
ConstString
ValueObjectChild::GetTypeName()
{
if (m_type_name.IsEmpty())
{
m_type_name = GetCompilerType().GetConstTypeName ();
AdjustForBitfieldness(m_type_name, m_bitfield_bit_size);
}
return m_type_name;
}
ConstString
ValueObjectChild::GetQualifiedTypeName()
{
ConstString qualified_name = GetCompilerType().GetConstTypeName();
AdjustForBitfieldness(qualified_name, m_bitfield_bit_size);
return qualified_name;
}
ConstString
ValueObjectChild::GetDisplayTypeName()
{
ConstString display_name = GetCompilerType().GetDisplayTypeName();
AdjustForBitfieldness(display_name, m_bitfield_bit_size);
return display_name;
}
LazyBool
ValueObjectChild::CanUpdateWithInvalidExecutionContext ()
{
if (m_can_update_with_invalid_exe_ctx.hasValue())
return m_can_update_with_invalid_exe_ctx.getValue();
if (m_parent)
{
ValueObject *opinionated_parent = m_parent->FollowParentChain([] (ValueObject* valobj) -> bool {
return (valobj->CanUpdateWithInvalidExecutionContext() == eLazyBoolCalculate);
});
if (opinionated_parent)
return (m_can_update_with_invalid_exe_ctx = opinionated_parent->CanUpdateWithInvalidExecutionContext()).getValue();
}
return (m_can_update_with_invalid_exe_ctx = this->ValueObject::CanUpdateWithInvalidExecutionContext()).getValue();
}
bool
ValueObjectChild::UpdateValue ()
{
m_error.Clear();
SetValueIsValid (false);
ValueObject* parent = m_parent;
if (parent)
{
if (parent->UpdateValueIfNeeded(false))
{
m_value.SetCompilerType(GetCompilerType());
CompilerType parent_type(parent->GetCompilerType());
// Copy the parent scalar value and the scalar value type
m_value.GetScalar() = parent->GetValue().GetScalar();
Value::ValueType value_type = parent->GetValue().GetValueType();
m_value.SetValueType (value_type);
Flags parent_type_flags(parent_type.GetTypeInfo());
bool is_instance_ptr_base = ((m_is_base_class == true) && (parent_type_flags.AnySet(lldb::eTypeInstanceIsPointer)));
bool treat_scalar_as_address = parent_type_flags.AnySet(lldb::eTypeIsPointer | lldb::eTypeIsReference);
treat_scalar_as_address |= ((m_is_base_class == false) && (parent_type_flags.AnySet(lldb::eTypeInstanceIsPointer)));
treat_scalar_as_address |= is_instance_ptr_base;
AddressType addr_type = parent->GetAddressTypeOfChildren();
if (treat_scalar_as_address)
{
lldb::addr_t addr = parent->GetPointerValue ();
m_value.GetScalar() = addr;
if (addr == LLDB_INVALID_ADDRESS)
{
m_error.SetErrorString ("parent address is invalid.");
}
else if (addr == 0)
{
m_error.SetErrorString ("parent is NULL");
}
else
{
m_value.GetScalar() += m_byte_offset;
switch (addr_type)
{
case eAddressTypeFile:
{
lldb::ProcessSP process_sp (GetProcessSP());
if (process_sp && process_sp->IsAlive() == true)
m_value.SetValueType (Value::eValueTypeLoadAddress);
else
m_value.SetValueType(Value::eValueTypeFileAddress);
}
break;
case eAddressTypeLoad:
m_value.SetValueType (is_instance_ptr_base ? Value::eValueTypeScalar: Value::eValueTypeLoadAddress);
break;
case eAddressTypeHost:
m_value.SetValueType(Value::eValueTypeHostAddress);
break;
case eAddressTypeInvalid:
// TODO: does this make sense?
m_value.SetValueType(Value::eValueTypeScalar);
break;
}
}
}
else
{
switch (value_type)
{
case Value::eValueTypeLoadAddress:
case Value::eValueTypeFileAddress:
case Value::eValueTypeHostAddress:
{
lldb::addr_t addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
if (addr == LLDB_INVALID_ADDRESS)
{
m_error.SetErrorString ("parent address is invalid.");
}
else if (addr == 0)
{
m_error.SetErrorString ("parent is NULL");
}
else
{
// Set this object's scalar value to the address of its
// value by adding its byte offset to the parent address
m_value.GetScalar() += GetByteOffset();
}
}
break;
case Value::eValueTypeScalar:
// try to extract the child value from the parent's scalar value
{
Scalar scalar(m_value.GetScalar());
if (m_bitfield_bit_size)
scalar.ExtractBitfield(m_bitfield_bit_size, m_bitfield_bit_offset);
else
scalar.ExtractBitfield(8*m_byte_size, 8*m_byte_offset);
m_value.GetScalar() = scalar;
}
break;
default:
m_error.SetErrorString ("parent has invalid value.");
break;
}
}
if (m_error.Success())
{
const bool thread_and_frame_only_if_stopped = true;
ExecutionContext exe_ctx (GetExecutionContextRef().Lock(thread_and_frame_only_if_stopped));
if (GetCompilerType().GetTypeInfo() & lldb::eTypeHasValue)
{
if (!is_instance_ptr_base)
m_error = m_value.GetValueAsData (&exe_ctx, m_data, 0, GetModule().get());
else
m_error = m_parent->GetValue().GetValueAsData (&exe_ctx, m_data, 0, GetModule().get());
}
else
{
m_error.Clear(); // No value so nothing to read...
}
}
}
else
{
m_error.SetErrorStringWithFormat("parent failed to evaluate: %s", parent->GetError().AsCString());
}
}
else
{
m_error.SetErrorString("ValueObjectChild has a NULL parent ValueObject.");
}
return m_error.Success();
}
bool
ValueObjectChild::IsInScope ()
{
ValueObject* root(GetRoot());
if (root)
return root->IsInScope ();
return false;
}
<commit_msg>Minor reshuffle of the code here to better fit with the cleanup plan I have in mind<commit_after>//===-- ValueObjectChild.cpp ------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Core/ValueObjectChild.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ValueObjectList.h"
#include "lldb/Symbol/CompilerType.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/SymbolContext.h"
#include "lldb/Symbol/Type.h"
#include "lldb/Symbol/Variable.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"
using namespace lldb_private;
ValueObjectChild::ValueObjectChild
(
ValueObject &parent,
const CompilerType &compiler_type,
const ConstString &name,
uint64_t byte_size,
int32_t byte_offset,
uint32_t bitfield_bit_size,
uint32_t bitfield_bit_offset,
bool is_base_class,
bool is_deref_of_parent,
AddressType child_ptr_or_ref_addr_type,
uint64_t language_flags
) :
ValueObject (parent),
m_compiler_type (compiler_type),
m_byte_size (byte_size),
m_byte_offset (byte_offset),
m_bitfield_bit_size (bitfield_bit_size),
m_bitfield_bit_offset (bitfield_bit_offset),
m_is_base_class (is_base_class),
m_is_deref_of_parent (is_deref_of_parent),
m_can_update_with_invalid_exe_ctx()
{
m_name = name;
SetAddressTypeOfChildren(child_ptr_or_ref_addr_type);
SetLanguageFlags(language_flags);
}
ValueObjectChild::~ValueObjectChild()
{
}
lldb::ValueType
ValueObjectChild::GetValueType() const
{
return m_parent->GetValueType();
}
size_t
ValueObjectChild::CalculateNumChildren(uint32_t max)
{
auto children_count = GetCompilerType().GetNumChildren (true);
return children_count <= max ? children_count : max;
}
static void
AdjustForBitfieldness(ConstString& name,
uint8_t bitfield_bit_size)
{
if (name && bitfield_bit_size)
{
const char *compiler_type_name = name.AsCString();
if (compiler_type_name)
{
std::vector<char> bitfield_type_name (strlen(compiler_type_name) + 32, 0);
::snprintf (&bitfield_type_name.front(), bitfield_type_name.size(), "%s:%u", compiler_type_name, bitfield_bit_size);
name.SetCString(&bitfield_type_name.front());
}
}
}
ConstString
ValueObjectChild::GetTypeName()
{
if (m_type_name.IsEmpty())
{
m_type_name = GetCompilerType().GetConstTypeName ();
AdjustForBitfieldness(m_type_name, m_bitfield_bit_size);
}
return m_type_name;
}
ConstString
ValueObjectChild::GetQualifiedTypeName()
{
ConstString qualified_name = GetCompilerType().GetConstTypeName();
AdjustForBitfieldness(qualified_name, m_bitfield_bit_size);
return qualified_name;
}
ConstString
ValueObjectChild::GetDisplayTypeName()
{
ConstString display_name = GetCompilerType().GetDisplayTypeName();
AdjustForBitfieldness(display_name, m_bitfield_bit_size);
return display_name;
}
LazyBool
ValueObjectChild::CanUpdateWithInvalidExecutionContext ()
{
if (m_can_update_with_invalid_exe_ctx.hasValue())
return m_can_update_with_invalid_exe_ctx.getValue();
if (m_parent)
{
ValueObject *opinionated_parent = m_parent->FollowParentChain([] (ValueObject* valobj) -> bool {
return (valobj->CanUpdateWithInvalidExecutionContext() == eLazyBoolCalculate);
});
if (opinionated_parent)
return (m_can_update_with_invalid_exe_ctx = opinionated_parent->CanUpdateWithInvalidExecutionContext()).getValue();
}
return (m_can_update_with_invalid_exe_ctx = this->ValueObject::CanUpdateWithInvalidExecutionContext()).getValue();
}
bool
ValueObjectChild::UpdateValue ()
{
m_error.Clear();
SetValueIsValid (false);
ValueObject* parent = m_parent;
if (parent)
{
if (parent->UpdateValueIfNeeded(false))
{
m_value.SetCompilerType(GetCompilerType());
CompilerType parent_type(parent->GetCompilerType());
// Copy the parent scalar value and the scalar value type
m_value.GetScalar() = parent->GetValue().GetScalar();
Value::ValueType value_type = parent->GetValue().GetValueType();
m_value.SetValueType (value_type);
Flags parent_type_flags(parent_type.GetTypeInfo());
const bool is_instance_ptr_base = ((m_is_base_class == true) && (parent_type_flags.AnySet(lldb::eTypeInstanceIsPointer)));
const bool treat_scalar_as_address = parent_type_flags.AnySet(lldb::eTypeIsPointer | lldb::eTypeIsReference | lldb::eTypeInstanceIsPointer);
if (treat_scalar_as_address)
{
lldb::addr_t addr = parent->GetPointerValue ();
m_value.GetScalar() = addr;
if (addr == LLDB_INVALID_ADDRESS)
{
m_error.SetErrorString ("parent address is invalid.");
}
else if (addr == 0)
{
m_error.SetErrorString ("parent is NULL");
}
else
{
m_value.GetScalar() += m_byte_offset;
AddressType addr_type = parent->GetAddressTypeOfChildren();
switch (addr_type)
{
case eAddressTypeFile:
{
lldb::ProcessSP process_sp (GetProcessSP());
if (process_sp && process_sp->IsAlive() == true)
m_value.SetValueType (Value::eValueTypeLoadAddress);
else
m_value.SetValueType(Value::eValueTypeFileAddress);
}
break;
case eAddressTypeLoad:
m_value.SetValueType (is_instance_ptr_base ? Value::eValueTypeScalar: Value::eValueTypeLoadAddress);
break;
case eAddressTypeHost:
m_value.SetValueType(Value::eValueTypeHostAddress);
break;
case eAddressTypeInvalid:
// TODO: does this make sense?
m_value.SetValueType(Value::eValueTypeScalar);
break;
}
}
}
else
{
switch (value_type)
{
case Value::eValueTypeLoadAddress:
case Value::eValueTypeFileAddress:
case Value::eValueTypeHostAddress:
{
lldb::addr_t addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
if (addr == LLDB_INVALID_ADDRESS)
{
m_error.SetErrorString ("parent address is invalid.");
}
else if (addr == 0)
{
m_error.SetErrorString ("parent is NULL");
}
else
{
// Set this object's scalar value to the address of its
// value by adding its byte offset to the parent address
m_value.GetScalar() += GetByteOffset();
}
}
break;
case Value::eValueTypeScalar:
// try to extract the child value from the parent's scalar value
{
Scalar scalar(m_value.GetScalar());
if (m_bitfield_bit_size)
scalar.ExtractBitfield(m_bitfield_bit_size, m_bitfield_bit_offset);
else
scalar.ExtractBitfield(8*m_byte_size, 8*m_byte_offset);
m_value.GetScalar() = scalar;
}
break;
default:
m_error.SetErrorString ("parent has invalid value.");
break;
}
}
if (m_error.Success())
{
const bool thread_and_frame_only_if_stopped = true;
ExecutionContext exe_ctx (GetExecutionContextRef().Lock(thread_and_frame_only_if_stopped));
if (GetCompilerType().GetTypeInfo() & lldb::eTypeHasValue)
{
if (!is_instance_ptr_base)
m_error = m_value.GetValueAsData (&exe_ctx, m_data, 0, GetModule().get());
else
m_error = m_parent->GetValue().GetValueAsData (&exe_ctx, m_data, 0, GetModule().get());
}
else
{
m_error.Clear(); // No value so nothing to read...
}
}
}
else
{
m_error.SetErrorStringWithFormat("parent failed to evaluate: %s", parent->GetError().AsCString());
}
}
else
{
m_error.SetErrorString("ValueObjectChild has a NULL parent ValueObject.");
}
return m_error.Success();
}
bool
ValueObjectChild::IsInScope ()
{
ValueObject* root(GetRoot());
if (root)
return root->IsInScope ();
return false;
}
<|endoftext|> |
<commit_before>/**
* L I N E A R A L G E B R A O P C O D E S F O R C S O U N D
* Michael Gogins
*
* These opcodes implement many linear algebra operations,
* from scalar, vector, and matrix arithmetic up to
* and including eigenvalue decompositions.
* The opcodes are designed to facilitate signal processing,
* and of course other mathematical operations,
* in the Csound orchestra language.
*
* Linear Algebra Data Types
*
* Mathematical Code Corresponding Csound Type or Types
* -------------- ----- --------------------------------------------------------
* real scalar r Native i-rate or k-rate variable
* complex scalar c Pair of native i-rate or k-rate variables, e.g. "kr, ki"
* real vector rv Pointer to array used as native i-rate or k-rate variable
* a Native a-rate variable
* t Native function table number
* complex vector cv Pointer to array used as native i-rate or k-rate variable
* f Native fsig variable
* real matrix rm Pointer to array used as native i-rate or k-rate variable
* complex matrix cm Pointer to array used as native i-rate or k-rate variable
*
* All arrays are 0-based.
*
* All arrays are considered to be column-major
* (x or i goes along columnns, y or j goes along rows).
*
* All arrays are general and dense; banded, Hermitian, symmetric
* and sparse routines are not implemented.
*
* All operands must be pre-allocated; no operation allocates any arrays.
* However, some operations may reshape arrays to hold results.
*
* Data is stored in i-rate and k-rate "array" objects,
* which can be of type code vr, vc, mr, or mc, and
* which internally store type code and shape.
* In orchestra code the "array" variable is passed in the same way
* as a MYFLT i-rate or i-rate variable, but it is in reality
* a pointer to the creator opcode instance.
*
* The processing rate and operation name
* are deterministically and exhaustively encoded into the opcode name as follows.
* Each part below is separated by an underscore.
* 1. Opcode family: "la" for "linear algebra".
* 2. Processing rate: "i" for i-rate or "k" for k-rate.
* 3. For creators only: type code of the created array.
* 4. Operation: the common mathematical term or abbreviation, e.g.
* "plus", "minus", "prod", "div", "dot", "abs", "conj", "norm1", "det", "hermite", and so on.
* 5. Where the array type(s) are not implicit: type code of parameter(s).
*
* Array Creators
* --------------
*
* iarray la_i_vr_create irows
* iarray la_i_vc_create irows
* iarray la_i_mr_create irows, icolumns [, jdiagonal]
* iarray la_i_mc_create irows, icolumns [, jdiagonal]
* iarray la_i_copy iarray
* iarray la_i_copy_a asig
* iarray la_i_copy_f fsig
* iarray la_i_copy_t itable
*
* Array Introspection
* -------------------
*
* itype, irows, icolumns la_i_info iarray
*
* Array Element Access
* --------------------
*
* la_i_vr_set iarray, icolumn, ivalue
* la_i_vc_set iarray, icolumn, irvalue, iivalue
* la_i mr_set iarray, icolumn, irow, ivalue
* la_i_mc_set iarray, icolumn, irow, irvalue, iivalue
* ivalue la_i_vr_get iarray, icolumn
* irvalue, iivalue la_i_vc_get iarray, icolumn, irow
* ivalue la_i_mr_get iarray, icolumn
* irvalue, iivalue la_i_mc_get iarray, icolumn, irow
*
* Single Array Operations
* -----------------------
*
* iarray la_i_conjugate iarray
* iarray la_i_transpose iarray
*
* Scalar Operations
* -----------------
*
* ir la_i_norm1 iarray
* ir la_i_norm2 iarray
* ir la_i_norm_inf iarray
* ir la_i_trace iarray
* ir la_i_lu_det imatrix
* iarray la_i_scale_r iarray, ir
* iarray la_i_scale_c iarray, ireal, iimaginary
*
* Elementwise Array-Array Operations
* ----------------------------------
*
* iarray la_i_add iarray_a, iarray_b
* iarray la_i_subtract iarray_a, iarray_b
* iarray la_i_multiply iarray_a, iarray_b
* iarray la_i_divide iarray_a, iarray-b
*
* Inner Products
* --------------
*
* iarray la_i_dot iarray_a, iarray_b
* iarray la_i_lu_invert imatrix
*
* Array Decompositions
* --------------------
*
* iarray la_i_upper_solve imatrix [, j_1_diagonal]
* iarray la_i_lower_solve imatrix [, j_1_diagonal]
* iarray la_i_lu_factor imatrix, ivector_pivot
* iarray la_i_lu_solve imatrix, ivector, ivector_pivot
* imatrix_q, imatrix_r la_i_qr_factor imatrix
* ivector_eigenvalues la_i_qr_eigen imatrix, ia_tolerance
* ivec_eval, imat_evec la_i_qr_sym_eigen imatrix, ia_tolerance
*
*/
extern "C"
{
// a-rate, k-rate, FUNC, SPECDAT
#include <csoundCore.h>
// PVSDAT
#include <pstream.h>
}
#include <OpcodeBase.hpp>
#include <gmm/gmm.h>
#include <vector>
struct Array
{
char code[4];
size_t rows;
size_t columns;
MYFLT *storage;
};
extern "C"
{
PUBLIC int csoundModuleCreate(CSOUND *csound)
{
return 0;
}
PUBLIC int csoundModuleInit(CSOUND *csound)
{
int status = 0;
return status;
}
PUBLIC int csoundModuleDestroy(CSOUND *csound)
{
return 0;
}
}
<commit_msg>no message<commit_after>/**
* L I N E A R A L G E B R A O P C O D E S F O R C S O U N D
* Michael Gogins
*
* These opcodes implement many linear algebra operations,
* from scalar, vector, and matrix arithmetic up to
* and including eigenvalue decompositions.
* The opcodes are designed to facilitate signal processing,
* and of course other mathematical operations,
* in the Csound orchestra language.
*
* Linear Algebra Data Types
* -------------------------
*
* Mathematical Code Corresponding Csound Type or Types
* -------------- ----- --------------------------------------------------------
* real scalar r Native i-rate or k-rate variable
* complex scalar c Pair of native i-rate or k-rate variables, e.g. "kr, ki"
* real vector rv Pointer to array used as native i-rate or k-rate variable
* a Native a-rate variable
* t Native function table number
* complex vector cv Pointer to array used as native i-rate or k-rate variable
* f Native fsig variable
* real matrix rm Pointer to array used as native i-rate or k-rate variable
* complex matrix cm Pointer to array used as native i-rate or k-rate variable
*
* All arrays are 0-based.
*
* All arrays are considered to be column-major
* (x or i goes along columnns, y or j goes along rows).
*
* All arrays are general and dense; banded, Hermitian, symmetric
* and sparse routines are not implemented.
*
* All operands must be pre-allocated; no operation allocates any arrays.
* However, some operations may reshape arrays to hold results.
*
* Data is stored in i-rate and k-rate "array" objects,
* which can be of type code vr, vc, mr, or mc, and
* which internally store type code and shape.
* In orchestra code the "array" variable is passed in the same way
* as a MYFLT i-rate or i-rate variable, but it is in reality
* a pointer to the creator opcode instance.
*
* The processing rate and operation name
* are deterministically and exhaustively encoded into the opcode name as follows.
* Each part below is separated by an underscore.
* 1. Opcode family: "la" for "linear algebra".
* 2. Processing rate: "i" for i-rate or "k" for k-rate.
* 3. For creators only: type code of the created array.
* 4. Operation: the common mathematical term or abbreviation, e.g.
* "plus", "minus", "prod", "div", "dot", "abs", "conj", "norm1", "det", "hermite", and so on.
* 5. Where the array type(s) are not implicit: type code of parameter(s).
*
* Array Creators
* --------------
*
* iarray la_i_vr_create irows
* iarray la_i_vc_create irows
* iarray la_i_mr_create irows, icolumns [, jdiagonal]
* iarray la_i_mc_create irows, icolumns [, jdiagonal]
* iarray la_i_copy iarray
* iarray la_i_copy_a asig
* iarray la_i_copy_f fsig
* iarray la_i_copy_t itable
* iarray la_i_a_copy ivr
* iarray la_i_f_copy ivc
* iarray la_i_t_copy ivr
*
* Array Introspection
* -------------------
*
* itype, irows, icolumns la_i_info iarray
*
* Array Element Access
* --------------------
*
* la_i_vr_set iarray, icolumn, ivalue
* la_i_vc_set iarray, icolumn, irvalue, iivalue
* la_i mr_set iarray, icolumn, irow, ivalue
* la_i_mc_set iarray, icolumn, irow, irvalue, iivalue
* ivalue la_i_vr_get iarray, icolumn
* irvalue, iivalue la_i_vc_get iarray, icolumn, irow
* ivalue la_i_mr_get iarray, icolumn
* irvalue, iivalue la_i_mc_get iarray, icolumn, irow
*
* Single Array Operations
* -----------------------
*
* iarray la_i_conjugate iarray
* iarray la_i_transpose iarray
*
* Scalar Operations
* -----------------
*
* ir la_i_norm1 iarray
* ir la_i_norm2 iarray
* ir la_i_norm_inf iarray
* ir la_i_trace iarray
* ir la_i_lu_det imatrix
* iarray la_i_scale_r iarray, ir
* iarray la_i_scale_c iarray, ireal, iimaginary
*
* Elementwise Array-Array Operations
* ----------------------------------
*
* iarray la_i_add iarray_a, iarray_b
* iarray la_i_subtract iarray_a, iarray_b
* iarray la_i_multiply iarray_a, iarray_b
* iarray la_i_divide iarray_a, iarray-b
*
* Inner Products
* --------------
*
* iarray la_i_dot iarray_a, iarray_b
* iarray la_i_lu_invert imatrix
*
* Array Decompositions
* --------------------
*
* iarray la_i_upper_solve imatrix [, j_1_diagonal]
* iarray la_i_lower_solve imatrix [, j_1_diagonal]
* iarray la_i_lu_factor imatrix, ivector_pivot
* iarray la_i_lu_solve imatrix, ivector, ivector_pivot
* imatrix_q, imatrix_r la_i_qr_factor imatrix
* ivector_eigenvalues la_i_qr_eigen imatrix, ia_tolerance
* ivec_eval, imat_evec la_i_qr_sym_eigen imatrix, ia_tolerance
*
*/
extern "C"
{
// a-rate, k-rate, FUNC, SPECDAT
#include <csoundCore.h>
// PVSDAT
#include <pstream.h>
}
#include <OpcodeBase.hpp>
#include <gmm/gmm.h>
#include <vector>
struct Array
{
OPDS h;
MYFLT *array;
MYFLT *rows;
MYFLT *columns;
MYFLT *code;
};
int noteoff(CSOUND *csound, Array *array)
{
}
extern "C"
{
PUBLIC int csoundModuleCreate(CSOUND *csound)
{
return 0;
}
PUBLIC int csoundModuleInit(CSOUND *csound)
{
int status = 0;
return status;
}
PUBLIC int csoundModuleDestroy(CSOUND *csound)
{
return 0;
}
}
<|endoftext|> |
<commit_before>#include <set>
#include <string>
#include <vector>
#include "InferArguments.h"
#include "IRVisitor.h"
namespace Halide {
namespace Internal {
using std::set;
using std::string;
using std::vector;
namespace {
class InferArguments : public IRGraphVisitor {
public:
vector<InferredArgument> &args;
InferArguments(vector<InferredArgument> &a, const vector<Function> &o, Stmt body)
: args(a), outputs(o) {
args.clear();
for (const Function &f : outputs) {
visit_function(f);
}
if (body.defined()) {
body.accept(this);
}
}
private:
vector<Function> outputs;
set<string> visited_functions;
using IRGraphVisitor::visit;
bool already_have(const string &name) {
// Ignore dependencies on the output buffers
for (const Function &output : outputs) {
if (name == output.name() || starts_with(name, output.name() + ".")) {
return true;
}
}
for (const InferredArgument &arg : args) {
if (arg.arg.name == name) {
return true;
}
}
return false;
}
void visit_exprs(const vector<Expr>& v) {
for (Expr i : v) {
visit_expr(i);
}
}
void visit_expr(Expr e) {
if (!e.defined()) return;
e.accept(this);
}
void visit_function(const Function& func) {
if (visited_functions.count(func.name())) return;
visited_functions.insert(func.name());
func.accept(this);
// Function::accept hits all the Expr children of the
// Function, but misses the buffers and images that might be
// extern arguments.
if (func.has_extern_definition()) {
for (const ExternFuncArgument &extern_arg : func.extern_arguments()) {
if (extern_arg.is_func()) {
visit_function(Function(extern_arg.func));
} else if (extern_arg.is_buffer()) {
include_buffer(extern_arg.buffer);
} else if (extern_arg.is_image_param()) {
include_parameter(extern_arg.image_param);
}
}
}
}
void include_parameter(Parameter p) {
if (!p.defined()) return;
if (already_have(p.name())) return;
Expr def, min, max;
if (!p.is_buffer()) {
def = p.get_scalar_expr();
min = p.get_min_value();
max = p.get_max_value();
}
InferredArgument a = {
Argument(p.name(),
p.is_buffer() ? Argument::InputBuffer : Argument::InputScalar,
p.type(), p.dimensions(), def, min, max),
p,
Buffer<>()};
args.push_back(a);
// Visit child expressions
if (!p.is_buffer()) {
visit_expr(def);
visit_expr(min);
visit_expr(max);
} else {
for (int i = 0; i < p.dimensions(); i++) {
visit_expr(p.min_constraint(i));
visit_expr(p.extent_constraint(i));
visit_expr(p.stride_constraint(i));
}
}
}
void include_buffer(Buffer<> b) {
if (!b.defined()) return;
if (already_have(b.name())) return;
InferredArgument a = {
Argument(b.name(), Argument::InputBuffer, b.type(), b.dimensions()),
Parameter(),
b};
args.push_back(a);
}
void visit(const Load *op) {
IRGraphVisitor::visit(op);
include_parameter(op->param);
include_buffer(op->image);
}
void visit(const Variable *op) {
IRGraphVisitor::visit(op);
include_parameter(op->param);
include_buffer(op->image);
}
void visit(const Call *op) {
IRGraphVisitor::visit(op);
if (op->func.defined()) {
Function fn(op->func);
visit_function(fn);
}
include_buffer(op->image);
include_parameter(op->param);
}
};
}
vector<InferredArgument> infer_arguments(Stmt body, const vector<Function> &outputs) {
vector<InferredArgument> inferred_args;
// Infer an arguments vector by walking the IR
InferArguments infer_args(inferred_args,
outputs,
body);
// Sort the Arguments with all buffers first (alphabetical by name),
// followed by all non-buffers (alphabetical by name).
std::sort(inferred_args.begin(), inferred_args.end());
#if 0
// Add the user context argument.
inferred_args.push_back(user_context_arg);
// Return the inferred argument types, minus any constant images
// (we'll embed those in the binary by default), and minus the user_context arg.
vector<Argument> result;
for (const InferredArgument &arg : inferred_args) {
debug(1) << "Inferred argument: " << arg.arg.type << " " << arg.arg.name << "\n";
if (!arg.buffer.defined() &&
arg.arg.name != user_context_arg.arg.name) {
result.push_back(arg.arg);
}
}
#endif
return inferred_args;
}
}
}
<commit_msg>Remove dead code.<commit_after>#include <set>
#include <string>
#include <vector>
#include "InferArguments.h"
#include "IRVisitor.h"
namespace Halide {
namespace Internal {
using std::set;
using std::string;
using std::vector;
namespace {
class InferArguments : public IRGraphVisitor {
public:
vector<InferredArgument> &args;
InferArguments(vector<InferredArgument> &a, const vector<Function> &o, Stmt body)
: args(a), outputs(o) {
args.clear();
for (const Function &f : outputs) {
visit_function(f);
}
if (body.defined()) {
body.accept(this);
}
}
private:
vector<Function> outputs;
set<string> visited_functions;
using IRGraphVisitor::visit;
bool already_have(const string &name) {
// Ignore dependencies on the output buffers
for (const Function &output : outputs) {
if (name == output.name() || starts_with(name, output.name() + ".")) {
return true;
}
}
for (const InferredArgument &arg : args) {
if (arg.arg.name == name) {
return true;
}
}
return false;
}
void visit_exprs(const vector<Expr>& v) {
for (Expr i : v) {
visit_expr(i);
}
}
void visit_expr(Expr e) {
if (!e.defined()) return;
e.accept(this);
}
void visit_function(const Function& func) {
if (visited_functions.count(func.name())) return;
visited_functions.insert(func.name());
func.accept(this);
// Function::accept hits all the Expr children of the
// Function, but misses the buffers and images that might be
// extern arguments.
if (func.has_extern_definition()) {
for (const ExternFuncArgument &extern_arg : func.extern_arguments()) {
if (extern_arg.is_func()) {
visit_function(Function(extern_arg.func));
} else if (extern_arg.is_buffer()) {
include_buffer(extern_arg.buffer);
} else if (extern_arg.is_image_param()) {
include_parameter(extern_arg.image_param);
}
}
}
}
void include_parameter(Parameter p) {
if (!p.defined()) return;
if (already_have(p.name())) return;
Expr def, min, max;
if (!p.is_buffer()) {
def = p.get_scalar_expr();
min = p.get_min_value();
max = p.get_max_value();
}
InferredArgument a = {
Argument(p.name(),
p.is_buffer() ? Argument::InputBuffer : Argument::InputScalar,
p.type(), p.dimensions(), def, min, max),
p,
Buffer<>()};
args.push_back(a);
// Visit child expressions
if (!p.is_buffer()) {
visit_expr(def);
visit_expr(min);
visit_expr(max);
} else {
for (int i = 0; i < p.dimensions(); i++) {
visit_expr(p.min_constraint(i));
visit_expr(p.extent_constraint(i));
visit_expr(p.stride_constraint(i));
}
}
}
void include_buffer(Buffer<> b) {
if (!b.defined()) return;
if (already_have(b.name())) return;
InferredArgument a = {
Argument(b.name(), Argument::InputBuffer, b.type(), b.dimensions()),
Parameter(),
b};
args.push_back(a);
}
void visit(const Load *op) {
IRGraphVisitor::visit(op);
include_parameter(op->param);
include_buffer(op->image);
}
void visit(const Variable *op) {
IRGraphVisitor::visit(op);
include_parameter(op->param);
include_buffer(op->image);
}
void visit(const Call *op) {
IRGraphVisitor::visit(op);
if (op->func.defined()) {
Function fn(op->func);
visit_function(fn);
}
include_buffer(op->image);
include_parameter(op->param);
}
};
}
vector<InferredArgument> infer_arguments(Stmt body, const vector<Function> &outputs) {
vector<InferredArgument> inferred_args;
// Infer an arguments vector by walking the IR
InferArguments infer_args(inferred_args,
outputs,
body);
// Sort the Arguments with all buffers first (alphabetical by name),
// followed by all non-buffers (alphabetical by name).
std::sort(inferred_args.begin(), inferred_args.end());
return inferred_args;
}
}
}
<|endoftext|> |
<commit_before><commit_msg>`ChunkMaster::render`: render only if `this->should_be_rendered`.<commit_after><|endoftext|> |
<commit_before>/*=========================================================================
Program: Monteverdi2
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mvdMainWindow.h"
#include "ui_mvdMainWindow.h"
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
#include <QtGui>
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdAboutDialog.h"
#include "mvdApplication.h"
#include "mvdColorDynamicsController.h"
#include "mvdColorDynamicsWidget.h"
#include "mvdColorSetupController.h"
#include "mvdDatasetModel.h"
#include "mvdGLImageWidget.h"
#include "mvdImageModelRenderer.h"
#include "mvdImageViewManipulator.h"
#include "mvdQuicklookModel.h"
#include "mvdQuicklookViewManipulator.h"
#include "mvdVectorImageModel.h"
namespace mvd
{
/*
TRANSLATOR mvd::MainWindow
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
MainWindow
::MainWindow( QWidget* parent, Qt::WindowFlags flags ) :
QMainWindow( parent, flags ),
m_UI( new mvd::Ui::MainWindow() )
{
m_UI->setupUi( this );
Initialize();
}
/*****************************************************************************/
MainWindow
::~MainWindow()
{
}
/*****************************************************************************/
void
MainWindow
::Initialize()
{
setObjectName( "mvd::MainWindow" );
setWindowTitle( PROJECT_NAME );
// instanciate the manipulator and the renderer relative to this widget
m_ImageViewManipulator = new ImageViewManipulator();
m_ImageModelRenderer = new ImageModelRenderer();
// set the GLImageWidget as the centralWidget in MainWindow.
setCentralWidget(
new GLImageWidget(
m_ImageViewManipulator,
m_ImageModelRenderer,
this
)
);
// instanciate the Ql manipulator/renderer
m_QLModelRenderer = new ImageModelRenderer();
m_QLViewManipulator = new QuicklookViewManipulator();
// Connect centralWidget manipulator to Ql renderer when viewportRegionChanged
QObject::connect(
m_ImageViewManipulator, SIGNAL( ViewportRegionRepresentationChanged(const PointType&, const PointType&) ),
m_QLModelRenderer, SLOT( OnViewportRegionRepresentationChanged(const PointType&, const PointType&) )
);
// Connect ql mousePressEventpressed to centralWidget manipulator
QObject::connect(
m_QLViewManipulator, SIGNAL( ViewportRegionChanged(double, double) ),
m_ImageViewManipulator, SLOT( OnViewportRegionChanged(double, double) )
);
// add the needed docks
InitializeDockWidgets();
// add needed widget to the status bar
InitializeStatusBarWidgets();
// Connect Quit action of main menu to QApplication's quit() slot.
QObject::connect(
m_UI->action_Quit, SIGNAL( activated() ),
qApp, SLOT( quit() )
);
// Connect Appllication and MainWindow when selected model is about
// to change.
QObject::connect(
qApp, SIGNAL( AboutToChangeSelectedModel( const AbstractModel* ) ),
this, SLOT( OnAboutToChangeSelectedModel( const AbstractModel* ) )
);
// Connect Appllication and MainWindow when selected model has been
// changed.
QObject::connect(
qApp, SIGNAL( SelectedModelChanged( AbstractModel* ) ),
this, SLOT( OnSelectedModelChanged( AbstractModel* ) )
);
// Change to NULL model to force emitting GUI signals when GUI is
// instanciated. So, GUI will be initialized and controller-widgets
// disabled.
Application::Instance()->SetModel( NULL );
}
/*****************************************************************************/
void
MainWindow
::InitializeStatusBarWidgets()
{
// Add a QLabel to the status bar to show pixel coordinates
QLabel * currentPixelLabel = new QLabel(statusBar());
currentPixelLabel->setAlignment(Qt::AlignCenter);
// connect this widget to receive notification from
// ImageViewManipulator
QObject::connect(
m_ImageViewManipulator,
SIGNAL( CurrentCoordinatesUpdated(const QString& ) ),
currentPixelLabel,
SLOT( setText(const QString &) )
);
statusBar()->addWidget(currentPixelLabel);
}
/*****************************************************************************/
void
MainWindow
::InitializeDockWidgets()
{
//
// EXPERIMENTAL QUICKLOOK Widget.
assert( qobject_cast< GLImageWidget* >( centralWidget() )!=NULL );
GLImageWidget* qlWidget = new GLImageWidget(
m_QLViewManipulator,
m_QLModelRenderer,
this,
qobject_cast< GLImageWidget* >( centralWidget() )
);
// TODO: Set better minimum size for quicklook GL widget.
qlWidget->setMinimumSize(100,100);
AddWidgetToDock(
qlWidget,
QUICKLOOK_DOCK,
tr( "Quicklook" ),
Qt::LeftDockWidgetArea
);
//
// COLOR SETUP.
ColorSetupWidget* colorSetupWgt = new ColorSetupWidget( this );
ColorSetupController* colorSetupCtrl = new ColorSetupController(
// wraps:
colorSetupWgt,
// as child of:
AddWidgetToDock(
colorSetupWgt,
VIDEO_COLOR_SETUP_DOCK,
tr( "Video color setup" ),
Qt::LeftDockWidgetArea
)
);
//
// COLOR DYNAMICS.
ColorDynamicsWidget* colorDynWgt = new ColorDynamicsWidget( this );
// Controller is childed to dock.
ColorDynamicsController* colorDynamicsCtrl = new ColorDynamicsController(
// wraps:
colorDynWgt,
// as child of:
AddWidgetToDock(
colorDynWgt,
VIDEO_COLOR_DYNAMICS_DOCK,
tr( "Video color dynamics" ),
Qt::LeftDockWidgetArea
)
);
//
// CHAIN CONTROLLERS.
// Forward model update signals of color-setup controller...
QObject::connect(
colorSetupCtrl,
SIGNAL( RgbChannelIndexChanged( RgbaChannel, int ) ),
// to: ...color-dynamics controller model update signal.
colorDynamicsCtrl,
SLOT( OnRgbChannelIndexChanged( RgbaChannel, int ) )
);
//
// EXPERIMENTAL TOOLBOX.
#if 0
QToolBox* toolBox = new QToolBox( this );
toolBox->setObjectName( "mvd::VideoColorToolBox" );
toolBox->addItem( new ColorSetupWidget( toolBox ), tr( "Video color setup" ) );
toolBox->addItem( new ColorDynamicsWidget( toolBox ), tr( "Video color dynamics" ) );
AddWidgetToDock(
toolBox,
"videoColorSettingsDock",
tr( "Video color dynamics" ),
Qt::LeftDockWidgetArea
);
#endif
}
/*****************************************************************************/
QDockWidget*
MainWindow
::AddWidgetToDock( QWidget* widget,
const QString& dockName,
const QString& dockTitle,
Qt::DockWidgetArea dockArea )
{
// New dock.
QDockWidget* dockWidget = new QDockWidget( dockTitle, this );
// You can use findChild( dockName ) to get dock-widget.
dockWidget->setObjectName( dockName );
dockWidget->setWidget( widget );
// Features.
dockWidget->setFloating( false );
dockWidget->setFeatures(
QDockWidget::DockWidgetMovable |
QDockWidget::DockWidgetFloatable
);
// Add dock.
addDockWidget( dockArea, dockWidget );
return dockWidget;
}
/*****************************************************************************/
/* SLOTS */
/*****************************************************************************/
void
MainWindow
::on_action_Open_activated()
{
QString filename(
QFileDialog::getOpenFileName( this, tr( "Open file..." ) )
);
if( filename.isNull() )
{
return;
}
try
{
// TODO: Replace with complex model (list of DatasetModel) when implemented.
DatasetModel* model = Application::LoadDatasetModel(
filename,
// TODO: Remove width and height from dataset model loading.
centralWidget()->width(), centralWidget()->height()
);
Application::Instance()->SetModel( model );
}
catch( std::exception& exc )
{
QMessageBox::warning( this, tr("Exception!"), exc.what() );
return;
}
}
/*****************************************************************************/
void
MainWindow
::on_action_About_activated()
{
AboutDialog aboutDialog( this );
aboutDialog.exec();
}
/*****************************************************************************/
void
MainWindow
::OnAboutToChangeSelectedModel( const AbstractModel* )
{
//
// COLOR SETUP.
SetControllerModel( GetColorSetupDock(), NULL );
//
// COLOR DYNAMICS.
SetControllerModel( GetColorDynamicsDock(), NULL );
// De-assign models to view after controllers (LIFO disconnect).
qobject_cast< GLImageWidget *>( centralWidget() )->SetImageModel( NULL );
qobject_cast< GLImageWidget * >( GetQuicklookDock()->widget() )->SetImageModel(
NULL
);
//
//
const Application* app = Application::ConstInstance();
assert( app!=NULL );
const DatasetModel* datasetModel =
qobject_cast< const DatasetModel* >( app->GetModel() );
// It is Ok there is no previously selected model (e.g. at
// application startup.
if( datasetModel==NULL )
{
return;
}
assert( datasetModel->HasSelectedImageModel() );
const VectorImageModel* vectorImageModel =
qobject_cast< const VectorImageModel* >(
datasetModel->GetSelectedImageModel()
);
assert( vectorImageModel!=NULL );
//
// MAIN VIEW.
// Disconnect previously selected model from view.
QObject::disconnect(
vectorImageModel,
SIGNAL( SettingsUpdated() ),
// to:
centralWidget(),
SLOT( updateGL() )
);
// TODO : where to do this
QObject::disconnect(
// vectorImageModel->GetQuicklookModel(),
// TODO: Remove temporary hack by better design.
vectorImageModel,
SIGNAL( SettingsUpdated() ),
// to:
GetQuicklookDock()->widget(),
SLOT( updateGL() )
);
//
// disconnect the vectorimage model spacing change (when zooming)
QObject::disconnect(
vectorImageModel,
SIGNAL( SpacingChanged(const SpacingType&) ),
// to:
centralWidget(),
SLOT( OnSpacingChanged(const SpacingType&) )
);
// disconnect signal used to update the ql widget
QObject::disconnect(
centralWidget(),
SIGNAL( CentralWidgetUpdated() ),
// to:
GetQuicklookDock()->widget(),
SLOT( updateGL() )
);
}
/*****************************************************************************/
void
MainWindow
::OnSelectedModelChanged( AbstractModel* model )
{
if( model==NULL )
return;
DatasetModel* datasetModel = qobject_cast< DatasetModel* >( model );
assert( datasetModel!=NULL );
assert( datasetModel->HasSelectedImageModel() );
VectorImageModel* vectorImageModel =
qobject_cast< VectorImageModel* >(
datasetModel->GetSelectedImageModel()
);
assert( vectorImageModel!=NULL );
//
// COLOR SETUP.
SetControllerModel( GetColorSetupDock(), vectorImageModel );
//
// COLOR DYNAMICS.
SetControllerModel( GetColorDynamicsDock(), vectorImageModel );
//
// MAIN VIEW.
// Assign newly selected model to view.
qobject_cast< GLImageWidget *>( centralWidget() )->SetImageModel(
vectorImageModel
);
// Connect newly selected model to view (after all other widgets are
// connected to prevent signals/slots to produce multiple view
// refreshes).
QObject::connect(
vectorImageModel,
SIGNAL( SettingsUpdated() ),
// to:
centralWidget(),
SLOT( updateGL() )
);
//
// QUICKLOOK VIEW.
// Assign newly selected model to view.
qobject_cast< GLImageWidget * >( GetQuicklookDock()->widget() )->SetImageModel(
vectorImageModel->GetQuicklookModel()
);
// Connect newly selected model to view (after all other widgets are
// connected to prevent signals/slots to produce multiple view
// refreshes).
// TODO : find where to do this
QObject::connect(
// vectorImageModel->GetQuicklookModel(),
// TODO: Remove temporary hack by better design.
vectorImageModel,
SIGNAL( SettingsUpdated() ),
// to:
GetQuicklookDock()->widget(),
SLOT( updateGL() )
);
//
// connect the vectorimage model spacing change (when zooming)
QObject::connect(
vectorImageModel,
SIGNAL( SpacingChanged(const SpacingType&) ),
// to:
centralWidget(),
SLOT( OnSpacingChanged(const SpacingType&) )
);
// signal used to update the ql widget
QObject::connect(
centralWidget(),
SIGNAL( CentralWidgetUpdated() ),
// to:
GetQuicklookDock()->widget(),
SLOT( updateGL() )
);
}
/*****************************************************************************/
} // end namespace 'mvd'
<commit_msg>ENH: More informative window title<commit_after>/*=========================================================================
Program: Monteverdi2
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mvdMainWindow.h"
#include "ui_mvdMainWindow.h"
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
#include <QtGui>
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdAboutDialog.h"
#include "mvdApplication.h"
#include "mvdColorDynamicsController.h"
#include "mvdColorDynamicsWidget.h"
#include "mvdColorSetupController.h"
#include "mvdDatasetModel.h"
#include "mvdGLImageWidget.h"
#include "mvdImageModelRenderer.h"
#include "mvdImageViewManipulator.h"
#include "mvdQuicklookModel.h"
#include "mvdQuicklookViewManipulator.h"
#include "mvdVectorImageModel.h"
namespace mvd
{
/*
TRANSLATOR mvd::MainWindow
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
MainWindow
::MainWindow( QWidget* parent, Qt::WindowFlags flags ) :
QMainWindow( parent, flags ),
m_UI( new mvd::Ui::MainWindow() )
{
m_UI->setupUi( this );
Initialize();
}
/*****************************************************************************/
MainWindow
::~MainWindow()
{
}
/*****************************************************************************/
void
MainWindow
::Initialize()
{
setObjectName( "mvd::MainWindow" );
setWindowTitle( PROJECT_NAME );
// instanciate the manipulator and the renderer relative to this widget
m_ImageViewManipulator = new ImageViewManipulator();
m_ImageModelRenderer = new ImageModelRenderer();
// set the GLImageWidget as the centralWidget in MainWindow.
setCentralWidget(
new GLImageWidget(
m_ImageViewManipulator,
m_ImageModelRenderer,
this
)
);
// instanciate the Ql manipulator/renderer
m_QLModelRenderer = new ImageModelRenderer();
m_QLViewManipulator = new QuicklookViewManipulator();
// Connect centralWidget manipulator to Ql renderer when viewportRegionChanged
QObject::connect(
m_ImageViewManipulator, SIGNAL( ViewportRegionRepresentationChanged(const PointType&, const PointType&) ),
m_QLModelRenderer, SLOT( OnViewportRegionRepresentationChanged(const PointType&, const PointType&) )
);
// Connect ql mousePressEventpressed to centralWidget manipulator
QObject::connect(
m_QLViewManipulator, SIGNAL( ViewportRegionChanged(double, double) ),
m_ImageViewManipulator, SLOT( OnViewportRegionChanged(double, double) )
);
// add the needed docks
InitializeDockWidgets();
// add needed widget to the status bar
InitializeStatusBarWidgets();
// Connect Quit action of main menu to QApplication's quit() slot.
QObject::connect(
m_UI->action_Quit, SIGNAL( activated() ),
qApp, SLOT( quit() )
);
// Connect Appllication and MainWindow when selected model is about
// to change.
QObject::connect(
qApp, SIGNAL( AboutToChangeSelectedModel( const AbstractModel* ) ),
this, SLOT( OnAboutToChangeSelectedModel( const AbstractModel* ) )
);
// Connect Appllication and MainWindow when selected model has been
// changed.
QObject::connect(
qApp, SIGNAL( SelectedModelChanged( AbstractModel* ) ),
this, SLOT( OnSelectedModelChanged( AbstractModel* ) )
);
// Change to NULL model to force emitting GUI signals when GUI is
// instanciated. So, GUI will be initialized and controller-widgets
// disabled.
Application::Instance()->SetModel( NULL );
}
/*****************************************************************************/
void
MainWindow
::InitializeStatusBarWidgets()
{
// Add a QLabel to the status bar to show pixel coordinates
QLabel * currentPixelLabel = new QLabel(statusBar());
currentPixelLabel->setAlignment(Qt::AlignCenter);
// connect this widget to receive notification from
// ImageViewManipulator
QObject::connect(
m_ImageViewManipulator,
SIGNAL( CurrentCoordinatesUpdated(const QString& ) ),
currentPixelLabel,
SLOT( setText(const QString &) )
);
statusBar()->addWidget(currentPixelLabel);
}
/*****************************************************************************/
void
MainWindow
::InitializeDockWidgets()
{
//
// EXPERIMENTAL QUICKLOOK Widget.
assert( qobject_cast< GLImageWidget* >( centralWidget() )!=NULL );
GLImageWidget* qlWidget = new GLImageWidget(
m_QLViewManipulator,
m_QLModelRenderer,
this,
qobject_cast< GLImageWidget* >( centralWidget() )
);
// TODO: Set better minimum size for quicklook GL widget.
qlWidget->setMinimumSize(100,100);
AddWidgetToDock(
qlWidget,
QUICKLOOK_DOCK,
tr( "Quicklook" ),
Qt::LeftDockWidgetArea
);
//
// COLOR SETUP.
ColorSetupWidget* colorSetupWgt = new ColorSetupWidget( this );
ColorSetupController* colorSetupCtrl = new ColorSetupController(
// wraps:
colorSetupWgt,
// as child of:
AddWidgetToDock(
colorSetupWgt,
VIDEO_COLOR_SETUP_DOCK,
tr( "Video color setup" ),
Qt::LeftDockWidgetArea
)
);
//
// COLOR DYNAMICS.
ColorDynamicsWidget* colorDynWgt = new ColorDynamicsWidget( this );
// Controller is childed to dock.
ColorDynamicsController* colorDynamicsCtrl = new ColorDynamicsController(
// wraps:
colorDynWgt,
// as child of:
AddWidgetToDock(
colorDynWgt,
VIDEO_COLOR_DYNAMICS_DOCK,
tr( "Video color dynamics" ),
Qt::LeftDockWidgetArea
)
);
//
// CHAIN CONTROLLERS.
// Forward model update signals of color-setup controller...
QObject::connect(
colorSetupCtrl,
SIGNAL( RgbChannelIndexChanged( RgbaChannel, int ) ),
// to: ...color-dynamics controller model update signal.
colorDynamicsCtrl,
SLOT( OnRgbChannelIndexChanged( RgbaChannel, int ) )
);
//
// EXPERIMENTAL TOOLBOX.
#if 0
QToolBox* toolBox = new QToolBox( this );
toolBox->setObjectName( "mvd::VideoColorToolBox" );
toolBox->addItem( new ColorSetupWidget( toolBox ), tr( "Video color setup" ) );
toolBox->addItem( new ColorDynamicsWidget( toolBox ), tr( "Video color dynamics" ) );
AddWidgetToDock(
toolBox,
"videoColorSettingsDock",
tr( "Video color dynamics" ),
Qt::LeftDockWidgetArea
);
#endif
}
/*****************************************************************************/
QDockWidget*
MainWindow
::AddWidgetToDock( QWidget* widget,
const QString& dockName,
const QString& dockTitle,
Qt::DockWidgetArea dockArea )
{
// New dock.
QDockWidget* dockWidget = new QDockWidget( dockTitle, this );
// You can use findChild( dockName ) to get dock-widget.
dockWidget->setObjectName( dockName );
dockWidget->setWidget( widget );
// Features.
dockWidget->setFloating( false );
dockWidget->setFeatures(
QDockWidget::DockWidgetMovable |
QDockWidget::DockWidgetFloatable
);
// Add dock.
addDockWidget( dockArea, dockWidget );
return dockWidget;
}
/*****************************************************************************/
/* SLOTS */
/*****************************************************************************/
void
MainWindow
::on_action_Open_activated()
{
QString filename(
QFileDialog::getOpenFileName( this, tr( "Open file..." ) )
);
if( filename.isNull() )
{
return;
}
try
{
// TODO: Replace with complex model (list of DatasetModel) when implemented.
DatasetModel* model = Application::LoadDatasetModel(
filename,
// TODO: Remove width and height from dataset model loading.
centralWidget()->width(), centralWidget()->height()
);
Application::Instance()->SetModel( model );
}
catch( std::exception& exc )
{
QMessageBox::warning( this, tr("Exception!"), exc.what() );
return;
}
}
/*****************************************************************************/
void
MainWindow
::on_action_About_activated()
{
AboutDialog aboutDialog( this );
aboutDialog.exec();
}
/*****************************************************************************/
void
MainWindow
::OnAboutToChangeSelectedModel( const AbstractModel* )
{
//
// COLOR SETUP.
SetControllerModel( GetColorSetupDock(), NULL );
//
// COLOR DYNAMICS.
SetControllerModel( GetColorDynamicsDock(), NULL );
// De-assign models to view after controllers (LIFO disconnect).
qobject_cast< GLImageWidget *>( centralWidget() )->SetImageModel( NULL );
qobject_cast< GLImageWidget * >( GetQuicklookDock()->widget() )->SetImageModel(
NULL
);
//
//
const Application* app = Application::ConstInstance();
assert( app!=NULL );
const DatasetModel* datasetModel =
qobject_cast< const DatasetModel* >( app->GetModel() );
// It is Ok there is no previously selected model (e.g. at
// application startup.
if( datasetModel==NULL )
{
return;
}
assert( datasetModel->HasSelectedImageModel() );
const VectorImageModel* vectorImageModel =
qobject_cast< const VectorImageModel* >(
datasetModel->GetSelectedImageModel()
);
assert( vectorImageModel!=NULL );
//
// MAIN VIEW.
// Disconnect previously selected model from view.
QObject::disconnect(
vectorImageModel,
SIGNAL( SettingsUpdated() ),
// to:
centralWidget(),
SLOT( updateGL() )
);
// TODO : where to do this
QObject::disconnect(
// vectorImageModel->GetQuicklookModel(),
// TODO: Remove temporary hack by better design.
vectorImageModel,
SIGNAL( SettingsUpdated() ),
// to:
GetQuicklookDock()->widget(),
SLOT( updateGL() )
);
//
// disconnect the vectorimage model spacing change (when zooming)
QObject::disconnect(
vectorImageModel,
SIGNAL( SpacingChanged(const SpacingType&) ),
// to:
centralWidget(),
SLOT( OnSpacingChanged(const SpacingType&) )
);
// disconnect signal used to update the ql widget
QObject::disconnect(
centralWidget(),
SIGNAL( CentralWidgetUpdated() ),
// to:
GetQuicklookDock()->widget(),
SLOT( updateGL() )
);
}
/*****************************************************************************/
void
MainWindow
::OnSelectedModelChanged( AbstractModel* model )
{
if( model==NULL )
return;
DatasetModel* datasetModel = qobject_cast< DatasetModel* >( model );
assert( datasetModel!=NULL );
assert( datasetModel->HasSelectedImageModel() );
VectorImageModel* vectorImageModel =
qobject_cast< VectorImageModel* >(
datasetModel->GetSelectedImageModel()
);
assert( vectorImageModel!=NULL );
itk::OStringStream oss;
oss<<PROJECT_NAME<<" - "<<ToStdString(vectorImageModel->GetFilename());
//<<" ("<<vectorImageModel->ToImageBase()->GetNumberOfComponentsPerPixel()<<tr(" bands, ")<<vectorImageModel->ToImageBase()->GetLargestPossibleRegion().GetSize()[0]<<"x"<<vectorImageModel->ToImageBase()->GetLargestPossibleRegion().GetSize()[1]<<tr(" pixels)");
setWindowTitle( FromStdString(oss.str()) );
//
// COLOR SETUP.
SetControllerModel( GetColorSetupDock(), vectorImageModel );
//
// COLOR DYNAMICS.
SetControllerModel( GetColorDynamicsDock(), vectorImageModel );
//
// MAIN VIEW.
// Assign newly selected model to view.
qobject_cast< GLImageWidget *>( centralWidget() )->SetImageModel(
vectorImageModel
);
// Connect newly selected model to view (after all other widgets are
// connected to prevent signals/slots to produce multiple view
// refreshes).
QObject::connect(
vectorImageModel,
SIGNAL( SettingsUpdated() ),
// to:
centralWidget(),
SLOT( updateGL() )
);
//
// QUICKLOOK VIEW.
// Assign newly selected model to view.
qobject_cast< GLImageWidget * >( GetQuicklookDock()->widget() )->SetImageModel(
vectorImageModel->GetQuicklookModel()
);
// Connect newly selected model to view (after all other widgets are
// connected to prevent signals/slots to produce multiple view
// refreshes).
// TODO : find where to do this
QObject::connect(
// vectorImageModel->GetQuicklookModel(),
// TODO: Remove temporary hack by better design.
vectorImageModel,
SIGNAL( SettingsUpdated() ),
// to:
GetQuicklookDock()->widget(),
SLOT( updateGL() )
);
//
// connect the vectorimage model spacing change (when zooming)
QObject::connect(
vectorImageModel,
SIGNAL( SpacingChanged(const SpacingType&) ),
// to:
centralWidget(),
SLOT( OnSpacingChanged(const SpacingType&) )
);
// signal used to update the ql widget
QObject::connect(
centralWidget(),
SIGNAL( CentralWidgetUpdated() ),
// to:
GetQuicklookDock()->widget(),
SLOT( updateGL() )
);
}
/*****************************************************************************/
} // end namespace 'mvd'
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.