hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
51dce849eac84709b62a567aaa4f24712f72a234 | 2,156 | hpp | C++ | Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/buffer/buflimit.hpp | TiagoPedroByterev/openvpnclient-ios | a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76 | [
"MIT"
] | 10 | 2021-03-29T13:52:06.000Z | 2022-03-10T02:24:25.000Z | Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/buffer/buflimit.hpp | TiagoPedroByterev/openvpnclient-ios | a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76 | [
"MIT"
] | 1 | 2018-07-13T06:45:25.000Z | 2018-07-13T06:45:25.000Z | Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/buffer/buflimit.hpp | TiagoPedroByterev/openvpnclient-ios | a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76 | [
"MIT"
] | 7 | 2018-07-11T10:37:02.000Z | 2019-08-03T10:34:08.000Z | // OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2017 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// 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 in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
#ifndef OPENVPN_BUFFER_BUFLIMIT_H
#define OPENVPN_BUFFER_BUFLIMIT_H
#include <openvpn/buffer/buffer.hpp>
namespace openvpn {
template <typename T>
class BufferLimit
{
public:
BufferLimit()
{
set_max(0, 0);
reset();
}
BufferLimit(const T max_lines_arg,
const T max_bytes_arg)
{
set_max(max_lines_arg, max_bytes_arg);
reset();
}
void set_max(const T max_lines_arg,
const T max_bytes_arg)
{
max_lines = max_lines_arg;
max_bytes = max_bytes_arg;
}
void reset()
{
n_bytes = n_lines = 0;
}
void add(const Buffer& buf)
{
T size = (T)buf.size();
n_bytes += size;
if (max_bytes && n_bytes > max_bytes)
bytes_exceeded();
if (max_lines)
{
const unsigned char *p = buf.c_data();
while (size--)
{
const unsigned char c = *p++;
if (c == '\n')
{
++n_lines;
if (n_lines > max_lines)
lines_exceeded();
}
}
}
}
virtual void bytes_exceeded() = 0;
virtual void lines_exceeded() = 0;
protected:
T max_lines;
T max_bytes;
T n_bytes;
T n_lines;
};
}
#endif
| 23.182796 | 78 | 0.62616 | TiagoPedroByterev |
51df0512a39f1f1081ef22b241df43d76ca83074 | 8,908 | cpp | C++ | src/qt/blocknettoolbar.cpp | CircuitBreaker88/blocknet | da08717b612c582367d2a00a79c90a8db2330773 | [
"MIT"
] | 1 | 2020-09-26T15:45:32.000Z | 2020-09-26T15:45:32.000Z | src/qt/blocknettoolbar.cpp | CircuitBreaker88/blocknet | da08717b612c582367d2a00a79c90a8db2330773 | [
"MIT"
] | null | null | null | src/qt/blocknettoolbar.cpp | CircuitBreaker88/blocknet | da08717b612c582367d2a00a79c90a8db2330773 | [
"MIT"
] | null | null | null | // Copyright (c) 2018-2019 The Blocknet developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/blocknettoolbar.h>
#include <qt/blocknetguiutil.h>
#include <QApplication>
#include <QProgressBar>
#include <QTimer>
BlocknetToolBar::BlocknetToolBar(QWidget *popup, QFrame *parent) : QFrame(parent), popupWidget(popup),
layout(new QHBoxLayout) {
layout->setAlignment(Qt::AlignRight);
layout->setSpacing(BGU::spi(18));
this->setLayout(layout);
peersIndicator = new BlocknetPeersIndicator;
peersIndicator->setPeers(BGU::spi(10));
stakingIndicator = new BlocknetStakingIndicator;
stakingIndicator->setObjectName("staking");
progressIndicator = new QFrame;
progressIndicator->setObjectName("progress");
progressIndicator->setFixedSize(BGU::spi(220), BGU::spi(28));
progressIndicator->setLayout(new QHBoxLayout);
progressIndicator->layout()->setContentsMargins(QMargins());
progressBar = new QProgressBar;
#if defined(Q_OS_WIN)
progressBar->setProperty("os", "win"); // work-around bug in Qt windows QProgressBar background
#endif
progressBar->setAlignment(Qt::AlignVCenter);
progressIndicator->layout()->addWidget(progressBar);
lockIndicator = new BlocknetLockIndicator;
lockIndicator->setObjectName("lock");
layout->addStretch(1);
layout->addWidget(peersIndicator);
layout->addWidget(stakingIndicator);
layout->addWidget(progressIndicator);
layout->addWidget(lockIndicator);
lockMenu = new BlocknetLockMenu;
lockMenu->setDisplayWidget(popupWidget);
lockMenu->hOnLockWallet = [&]() { Q_EMIT lock(true); };
lockMenu->hOnChangePw = [&]() { Q_EMIT passphrase(); };
lockMenu->hOnUnlockWallet = [&]() { Q_EMIT lock(false); };
lockMenu->hOnUnlockForStaking = [&]() { Q_EMIT lock(false, true); };
lockMenu->hOnTimedUnlock = [&]() { /*lockIndicator->setTime();*/ }; // TODO Blocknet Qt setTime
lockMenu->hide();
connect(lockIndicator, &BlocknetLockIndicator::lockRequest, this, &BlocknetToolBar::onLockClicked);
}
QLabel* BlocknetToolBar::getIcon(QString path, QString description, QSize size) {
QPixmap pm(path);
pm.setDevicePixelRatio(BGU::dpr());
auto *icon = new QLabel(description);
icon->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
icon->setFixedSize(size);
icon->setPixmap(pm.scaled(icon->width()*pm.devicePixelRatio(), icon->height()*pm.devicePixelRatio(),
Qt::KeepAspectRatio, Qt::SmoothTransformation));
return icon;
}
void BlocknetToolBar::setPeers(const int peers) {
peersIndicator->setPeers(peers);
}
void BlocknetToolBar::setStaking(const bool on, const QString &msg) {
stakingIndicator->setOn(on);
stakingIndicator->setToolTip(msg);
}
void BlocknetToolBar::setLock(const bool lock, const bool stakingOnly) {
lockIndicator->setLock(lock, stakingOnly);
}
void BlocknetToolBar::setProgress(const int progress, const QString &msg, const int maximum) {
progressBar->setMaximum(maximum);
progressBar->setValue(progress);
progressBar->setStatusTip(msg);
progressBar->setToolTip(msg);
progressBar->setFormat(QString(" %1").arg(msg));
}
void BlocknetToolBar::onLockClicked(bool lock) {
if (lockMenu->isHidden()) {
QPoint li = lockIndicator->mapToGlobal(QPoint());
QPoint npos = popupWidget->mapFromGlobal(QPoint(li.x() - lockMenu->width() + 10, li.y() + lockIndicator->height() + 12));
lockMenu->move(npos);
lockMenu->show();
}
}
BlocknetPeersIndicator::BlocknetPeersIndicator(QFrame *parent) : QFrame(parent), layout(new QHBoxLayout) {
layout->setContentsMargins(QMargins());
layout->setSpacing(BGU::spi(4));
this->setLayout(layout);
auto *peersIcon = BlocknetToolBar::getIcon(QString(":/redesign/UtilityBar/Peers.png"), QString("Peers"), QSize(BGU::spi(21), BGU::spi(20)));
peersLbl = new QLabel;
peersLbl->setObjectName("peersLbl");
layout->addWidget(peersIcon);
layout->addWidget(peersLbl);
}
void BlocknetPeersIndicator::setPeers(const int peers) {
peersLbl->setText(QString::number(peers));
this->setToolTip(QString("%1: %2").arg(tr("Connected peers"), QString::number(peers)));
}
BlocknetStakingIndicator::BlocknetStakingIndicator(QFrame *parent) : QFrame(parent), layout(new QHBoxLayout) {
layout->setContentsMargins(QMargins());
layout->setSpacing(0);
this->setLayout(layout);
this->setOn(false);
}
void BlocknetStakingIndicator::setOn(const bool on) {
if (stakingIcon != nullptr) {
layout->removeWidget(stakingIcon);
stakingIcon->deleteLater();
}
QString icon = on ? ":/redesign/UtilityBar/StakingNodeIconActive.png" :
":/redesign/UtilityBar/StakingNodeIconInactive.png";
stakingIcon = BlocknetToolBar::getIcon(icon, tr("Staking"), QSize(BGU::spi(20), BGU::spi(20)));
layout->addWidget(stakingIcon);
}
/**
* Manages the lock indicator. If the datetime is set, this icon will set a QTimer to check the time once per second.
* @param parent
*/
BlocknetLockIndicator::BlocknetLockIndicator(QPushButton *parent) : QPushButton(parent), layout(new QHBoxLayout) {
layout->setContentsMargins(QMargins());
layout->setSpacing(0);
layout->setAlignment(Qt::AlignVCenter | Qt::AlignHCenter);
this->setLayout(layout);
this->setFixedSize(BGU::spi(26), BGU::spi(24));
this->setCursor(Qt::PointingHandCursor);
this->setCheckable(true);
this->setLock(false);
connect(this, &BlocknetLockIndicator::clicked, this, &BlocknetLockIndicator::onClick);
}
/**
* Sets the time. A timer is fired every 1 second. If the time is set to 0 epoch the timer is cleared.
* @param time
*/
void BlocknetLockIndicator::setTime(const QDateTime time) {
this->lockTime = time;
// lock if time is in the future
// TODO Blocknet Qt needs work for older qt 5 versions
// if (time.toSecsSinceEpoch() > QDateTime::currentSecsSinceEpoch())
// this->setLock(true);
//
// if (time.toSecsSinceEpoch() == 0) {
// timer->stop();
// } else {
// this->lockTime = time;
// if (timer == nullptr) {
// timer = new QTimer;
// timer->setInterval(1000);
// timer->setTimerType(Qt::CoarseTimer);
// connect(timer, &QTimer::timeout, this, &BlocknettToolBar::tick);
// }
// timer->start();
// }
}
void BlocknetLockIndicator::setLock(const bool locked, const bool stakingOnly) {
this->locked = locked;
this->stakingOnly = stakingOnly;
removeLockIcon();
QString icon = locked ? ":/redesign/UtilityBar/LockedIcon.png" :
":/redesign/UtilityBar/UnlockedIcon.png";
lockIcon = BlocknetToolBar::getIcon(icon, tr("Wallet lock state"), QSize(BGU::spi(20), BGU::spi(16)));
layout->addWidget(lockIcon);
if (this->locked)
this->setToolTip(tr("Wallet is locked"));
else
this->setToolTip(this->stakingOnly ? tr("Wallet is unlocked for staking only") : tr("Wallet is unlocked"));
}
void BlocknetLockIndicator::tick() {
// TODO Blocknet Qt support older qt versions
// QDateTime current = QDateTime::currentDateTime();
// qint64 diff = lockTime.toSecsSinceEpoch() - current.toSecsSinceEpoch();
// if (diff < 3600 && diff >= 0) { // 1 hr
// if (lockIcon != nullptr)
// lockIcon->hide();
// if (elapsedLbl == nullptr) {
// elapsedLbl = new QLabel;
// elapsedLbl->setObjectName("timeLbl");
// layout->addWidget(elapsedLbl);
// }
// qint64 t = lockTime.toSecsSinceEpoch() - current.toSecsSinceEpoch();
// if (diff < 60) { // seconds
// elapsedLbl->setText(QString::number(t) + "s");
// } else { // minutes
// elapsedLbl->setText(QString::number(ceil((double)t/60)) + "m");
// }
// } else if (elapsedLbl != nullptr) {
// clearTimer();
// }
}
void BlocknetLockIndicator::onClick(bool) {
if (timer && timer->isActive()) {
clearTimer();
}
// If locked send lock request
Q_EMIT lockRequest(!this->locked);
}
void BlocknetLockIndicator::removeLockIcon() {
if (lockIcon == nullptr)
return;
layout->removeWidget(lockIcon);
lockIcon->deleteLater();
lockIcon = nullptr;
}
void BlocknetLockIndicator::clearTimer() {
// TODO Blocknet Qt support older qt versions
// this->lockTime = QDateTime::fromSecsSinceEpoch(0);
// if (elapsedLbl != nullptr) {
// if (lockIcon != nullptr)
// lockIcon->show();
// layout->removeWidget(elapsedLbl);
// elapsedLbl->deleteLater();
// elapsedLbl = nullptr;
// // now clear the timer
// timer->stop();
// }
}
| 36.211382 | 144 | 0.661989 | CircuitBreaker88 |
51e09353a31188075a4acc8e30d6e98201c5345d | 27,424 | cpp | C++ | WMap.cpp | HSHL/OSM | 89772fc5c89dbad08b8426de1772e49e5022005a | [
"MIT"
] | 5 | 2019-04-08T12:24:31.000Z | 2022-01-13T02:04:16.000Z | WMap.cpp | CBause/OSM | ef458a3b2787905f223180e01b79e7899e398fb6 | [
"MIT"
] | null | null | null | WMap.cpp | CBause/OSM | ef458a3b2787905f223180e01b79e7899e398fb6 | [
"MIT"
] | 2 | 2016-10-09T14:33:48.000Z | 2019-08-30T03:42:13.000Z | #include "WMap.hpp"
//-------------------------------------------------------------------------------------------------------------------------------------------------
WMap::WMap(MainController* pC, Data* pR) {
c = pC;
r = pR;
timer = new QTimer;
QObject::connect(timer,SIGNAL(timeout()),this,SLOT(zoom()));
QObject::connect(this,SIGNAL(zoomFinished()),this,SLOT(stopTimer()));
tunnel = new bool;
*tunnel = false;
scaleControl = new double;
*scaleControl = 1.0;
stepCounter = new int;
*stepCounter = 0;
moveMouse = new bool;
*moveMouse = false;
mousePos = new QPointF();
mousePos->setX(0);
mousePos->setY(0);
pen = new QPen;
pen->setCapStyle(Qt::RoundCap);
brush = new QBrush;
brush->setStyle(Qt::SolidPattern);
brush->setColor(QColor::fromRgb(128,255,128,255));
scene = new QGraphicsScene;
setBoundingRect();
scene->setSceneRect(*boundingRect);
setScene(scene);
setBackgroundBrush(*brush);
transformation = new QTransform();
transformation->rotate(180,Qt::XAxis);
this->setTransform(*transformation);
drawOuterRect();
drawRelations();
drawAreas();
drawWays();
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::setBoundingRect() {
double x,y,w,h;
borderWidth = new int;
*borderWidth = 1;
x= (r->getMinLon() / 1E2) - *borderWidth;
y = (r->getMinLat() / 1E2) - *borderWidth;
w = (r->getMaxLon() / 1E2) - (r->getMinLon() / 1E2) + 2* (*borderWidth);
h = (r->getMaxLat() / 1E2) - (r->getMinLat() / 1E2) + 2* (*borderWidth);
boundingRect = new QRectF(x,y,w,h);
}
//DRAW MAP---------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::drawOuterRect() {
pen->setWidth(*borderWidth);
pen->setColor(Qt::black);
pen->setWidth(10);
brush->setColor(QColor::fromRgb(128,255,128,255));
QRectF borderRect = *boundingRect;
borderRect.setX(borderRect.x()-5);
borderRect.setY(borderRect.y()-5);
borderRect.setWidth(borderRect.width()+10);
borderRect.setHeight(borderRect.height()+10);
scene->addRect(borderRect,*pen,*brush);
bool b = true;
QRect rect;
QPolygonF visibleScene;
QPolygonF::iterator polyIt;
while (b) {
polyIt = visibleScene.begin();
rect = this->viewport()->rect();
visibleScene = this->mapToScene(rect);
for (int i = 0; i < visibleScene.count(); i++) {
b = false;
if (outOfBounds(*polyIt)) {
b = true;
break;
}
polyIt++;
}
if (b)
scale(1.01,1.01);
}
while (!b) {
polyIt = visibleScene.begin();
rect = this->viewport()->rect();
visibleScene = this->mapToScene(rect);
for (int i = 0; i < visibleScene.count(); i++) {
b = false;
if (outOfBounds(*polyIt)) {
b = true;
break;
}
polyIt++;
}
if (!b)
scale(0.99,0.99);
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::drawAreas() {
QHash<QString,Way*>::iterator wayIt = r->getWays()->begin();
for (int i = 0; i < r->getWays()->count(); i++) {
Way *w = *wayIt;
QList<Node*>::iterator nodeListIt = w->getNodeList()->begin();
QHash<QString,QString>::iterator tagIt = w->getTags()->begin();
bool area = false;
for (int j = 0; j < w->getTags()->count(); j++) {
if(tagIt.key() == "area")
area = true;
tagIt++;
}
if((area == true) && (w->getTags()->count()>1)) {
QPolygonF poly;
for (int k = 0; k < w->getNodeList()->count()-1; k++) {
double x,y;
Node *n = *nodeListIt;
x = n->getLon() / 1E2;
y = n->getLat() / 1E2;
QPointF point;
point.setX(x);
point.setY(y);
poly << point;
nodeListIt++;
}
if (changeBrush(w->getTags())) {
scene->addPolygon(poly,*pen,*brush);
}
}
wayIt++;
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::drawWays() {
QHash<QString,Way*>::iterator wayIt = r->getWays()->begin();
for (int i = 0; i < r->getWays()->count(); i++) {
*tunnel = false;
Way *w = *wayIt;
QList<Node*>::iterator nodeListIt = w->getNodeList()->begin();
QHash<QString,QString>::iterator tagIt = w->getTags()->begin();
bool area = false;
for (int j = 0; j < w->getTags()->count(); j++) {
if(tagIt.key() == "area")
area = true;
if(tagIt.key() == "tunnel")
*tunnel = true;
tagIt++;
}
if (!area) {
for (int k = 0; k < w->getNodeList()->count()-1; k++) {
double x1, x2, y1, y2;
Node *n = *nodeListIt;
y1 = n->getLat() / 1E2;
x1 = n->getLon() / 1E2;
nodeListIt++;
n = *nodeListIt;
y2 = n->getLat() / 1E2;
x2 = n->getLon() / 1E2;
if (changePen(w->getTags()))
scene->addLine(x1,y1,x2,y2,*pen);
}
}
wayIt++;
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::drawRelations() {
QHash<QString,Relation*>::Iterator relationIt = r->getRelations()->begin();
for(int i = 0; i < r->getRelations()->count(); i++) {
Relation *re = *relationIt;
QHash<QString,QString>::iterator tagIt = re->getTags()->begin();
QList<Member*>::iterator memberIt = re->getMemberList()->begin();
QList<Node*>::iterator nodeIt;
QHash<QString,Way*>::iterator wayIt;
for(int j = 0; j < re->getTags()->count(); j++) {
if (tagIt.value() == "multipolygon") {
currentPoly = new QPolygonF;
bool openPoly = false;
QList<QPolygonF> polyList;
QList<QString> roleList;
for (int l=0;l<re->getMemberList()->count();l++) {
Member *member = *memberIt;
if (member->getType() == "way" && member->getRole() != "") {
if (r->getWays()->contains(member->getRef()) ) {
wayIt = r->getWays()->find(member->getRef());
Way *w = *wayIt;
QHash<QString,QString>::iterator wayTagIt = w->getTags()->begin();
bool area = false;
for (int v = 0; v < w->getTags()->count(); v++) {
if(wayTagIt.key() == "area")
area = true;
wayTagIt++;
}
nodeIt = w->getNodeList()->begin();
if(!openPoly)
currentFirstNode = *nodeIt;
for(int k=0;k<w->getNodeList()->count();k++) {
currentLastNode = *nodeIt;
Node *n = *nodeIt;
QPointF point;
point.setX(n->getLon() / 1E2);
point.setY(n->getLat() / 1E2);
*currentPoly << point;
nodeIt++;
}
if( (area == true )) {
polyList.append(*currentPoly);
roleList.append(member->getRole());
currentPoly = new QPolygonF;
openPoly = false;
} else {
if (!openPoly) {
} else {
if (currentLastNode == currentFirstNode) {
polyList.append(*currentPoly);
roleList.append(member->getRole());
currentPoly = new QPolygonF;
openPoly = false;
}
}
}
} else {
delete currentPoly;
break;
}
}
}
memberIt++;
if (!polyList.isEmpty()) {
QList<QPolygonF>::iterator polyIt = polyList.begin();
QList<QString>::iterator roleIt = roleList.begin();
for (int u = 0; u < polyList.count(); u++) {
re->addTag("role",*roleIt);
if (changeBrush(re->getTags()))
scene->addPolygon(*polyIt,*pen,*brush);
re->getTags()->erase(re->getTags()->find("role"));
polyIt++;
roleIt++;
}
}
} // END MULTIPOLYGON
if (tagIt.value() == "associatedStreet") {
for (int k = 0; k<re->getMemberList()->count(); k++) {
Member *member = *memberIt;
if (r->getWays()->contains( member->getRef() )) {
Way *w = *r->getWays()->find(member->getRef());
if(member->getRole() == "house") {
QPolygonF poly;
nodeIt = w->getNodeList()->begin();
for(int f = 0; f < w->getNodeList()->count(); f++) {
Node *n = *nodeIt;
QPointF point;
point.setX(n->getLon() / 1E2);
point.setY(n->getLat() / 1E2);
poly << point;
nodeIt++;
}
if (changeBrush(w->getTags()))
scene->addPolygon(poly,*pen,*brush);
} else {
nodeIt = w->getNodeList()->begin();
for (int f = 0; f< w->getNodeList()->count() - 1; f++) {
Node *n = *nodeIt;
nodeIt++;
Node *m = *nodeIt;
QPointF a,b;
a.setX(n->getLon() / 1E2);
a.setY(n->getLat() / 1E2);
b.setX(m->getLon() / 1E2);
b.setY(m->getLat() / 1E2);
if (changePen(w->getTags()))
scene->addLine(a.x(),a.y(),b.x(),b.y(),*pen);
}
}
}
memberIt++;
}
} //END ASSOCIATEDSTREET
tagIt++;
}
relationIt++;
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
bool WMap::changePen(QHash<QString,QString>* pTags) {
QHash<QString,QString>::iterator tagIt = pTags->begin();
bool set = false;
for(int i = 0; i < pTags->count(); i++) {
pen->setStyle(Qt::SolidLine);
if(*tunnel == true)
pen->setStyle(Qt::DashDotLine);
if(tagIt.key() == "highway") {
if(tagIt.value() == "primary" || tagIt.value() == "primary_link" || tagIt.value() == "trunk" || tagIt.value() == "trunk_link") {
pen->setColor(QColor::fromRgb(255,160,128,255)); pen->setWidth(10); set=true; break;}
if(tagIt.value() == "secondary" || tagIt.value() == "secondary_link") {
pen->setColor(QColor::fromRgb(255,224,128,255)); pen->setWidth(8); set=true; break;}
if (tagIt.value() == "tertiary" || tagIt.value() == "tertiary_link") {
pen->setColor(QColor::fromRgb(128,128,208,255)); pen->setWidth(8); set=true; break;}
if(tagIt.value() == "residential" || tagIt.value() == "living_street") {
pen->setColor(QColor::fromRgb(64,64,64,255)); pen->setWidth(5); set=true; break;}
if(tagIt.value() == "service") {
pen->setColor(QColor::fromRgb(208,208,208,255)); pen->setWidth(4); set=true; break;}
if(tagIt.value() == "track") {
pen->setColor(QColor::fromRgb(96,32,0,255)); pen->setWidth(1); pen->setStyle(Qt::DashLine); set=true; break;}
if(tagIt.value() == "path") {
pen->setColor(QColor::fromRgb(128,64,0,255)); pen->setWidth(1); pen->setStyle(Qt::DashLine); set=true; break;}
if(tagIt.value() == "footway") {
pen->setColor(QColor::fromRgb(192,192,192,255)); pen->setWidth(2); pen->setStyle(Qt::DashLine); set=true; break;}
if(tagIt.value() == "road") {
pen->setColor(QColor::fromRgb(32,32,32,255)); pen->setWidth(5); set=true; break;}
if((tagIt.value() == "motorway") || (tagIt.value() == "motorway_link")) {
pen->setColor(QColor::fromRgb(160,80,112,255)); pen->setWidth(10); set=true; break;}
}
if(tagIt.key() == "waterway") {
if(tagIt.value() == "river") {
pen->setColor(Qt::blue); pen->setWidth(20); set=true; break;}
if(tagIt.value() == "stream") {
pen->setColor(Qt::blue); pen->setWidth(5); set=true; break;}
}
if(tagIt.value() == "water") {
pen->setColor(Qt::blue); set=true; break;
}
if(tagIt.key() == "railway") {
pen->setWidth(2);
pen->setColor(Qt::black);
pen->setStyle(Qt::DotLine);
set = true;
break;
}
tagIt++;
}
return(set);
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
bool WMap::changeBrush(QHash<QString,QString>* pTags) {
QHash<QString,QString>::iterator tagIt = pTags->begin();
bool set = false;
brush->setStyle(Qt::SolidPattern);
pen->setStyle(Qt::NoPen);
for(int i = 0; i < pTags->count(); i++) {
if((tagIt.value() == "reservoir") || (tagIt.value() == "basin") || (tagIt.value() == "water")) {
brush->setColor(Qt::blue); pen->setColor(Qt::blue); set=true; break;
}
if(tagIt.key() == "building" || tagIt.value() == "building") {
brush->setColor(QColor::fromRgb(128,128,128,255)); pen->setStyle(Qt::SolidLine); pen->setColor(QColor::fromRgb(16,16,16,255)); pen->setWidth(1); set=true; break;
}
if (tagIt.key() == "landuse") {
if (tagIt.value() == "forest") {
brush->setColor(QColor::fromRgb(0,160,0,125)); set=true; break;}
if(tagIt.value() == "industrial" || tagIt.value() == "retail" || tagIt.value() == "commercial") {
brush->setColor(QColor::fromRgb(160,160,255,125)); set=true; break;}
if(tagIt.value() == "railway") {
brush->setColor(QColor::fromRgb(208,208,255,125)); set=true; break;}
if(tagIt.value() == "residential") {
brush->setColor(QColor::fromRgb(220,220,220,125)); set=true; break;}
if(tagIt.value() == "cemetery") {
brush->setStyle(Qt::DiagCrossPattern); brush->setColor(QColor::fromRgb(128,255,128,125)); set=true; break;}
if(tagIt.value() == "recreation_ground" || tagIt.value() == "village_green" || tagIt.value() == "meadow" || tagIt.value() == "grass" || tagIt.value() == "greenfield") {
brush->setColor(QColor::fromRgb(80,255,80,125)); set=true; break;}
}
tagIt++;
}
return(set);
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
bool WMap::outOfBounds(QPointF pPoint) {
if ((pPoint.x() < boundingRect->left()) || (pPoint.x() > boundingRect->right()) ||
(pPoint.y() < boundingRect->top()) || (pPoint.y() > boundingRect->bottom()) )
return(true);
return(false);
}
//KEYEVENTS-------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::keyPressEvent(QKeyEvent* event) {
if(event->key() == 16777275)
takeScreenshot();
}
//MOUSEEVENTS--------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::mousePressEvent(QMouseEvent *event) {
if(event->button() == Qt::LeftButton) {
setCursor(Qt::ClosedHandCursor);
mousePos->setX(event->x());
mousePos->setY(event->y());
*moveMouse = true;
event->accept();
}
event->ignore();
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::mouseReleaseEvent(QMouseEvent *event) {
if(event->button() == Qt::LeftButton) {
setCursor(Qt::ArrowCursor);
*moveMouse = false;
event->accept();
}
event->ignore();
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::mouseMoveEvent(QMouseEvent* event) {
if (*moveMouse == true) {
this->horizontalScrollBar()->setValue(this->horizontalScrollBar()->value() - (event->x() - mousePos->x()));
this->verticalScrollBar()->setValue(this->verticalScrollBar()->value() - (event->y() - mousePos->y()));
mousePos->setX(event->x());
mousePos->setY(event->y());
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::wheelEvent(QWheelEvent* event) {
int degrees = event->delta() / 15;
int steps = degrees / 8;
if(*stepCounter * steps < 0)
*stepCounter = steps;
else
*stepCounter += steps;
if (!timer->isActive()) {;
timer->start(20);
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::stopTimer() {
timer->stop();
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::zoom() {
if (*stepCounter != 0) {
qreal viewScale = 1.0;
qreal factor = 0.2;
qreal max = 3;
if(*stepCounter < 0) {
if ( (this->horizontalScrollBar()->value() != 0) && (this->verticalScrollBar()->value() != 0) ) {
viewScale -= factor;
*scaleControl -= factor;
}
*stepCounter += 1;
} else {
if((*scaleControl+factor)<max) {
viewScale += factor;
*scaleControl += factor;
}
*stepCounter -= 1;
}
scale(viewScale,viewScale);
bool b = true;
QRect rect;
QPolygonF poly;
QPolygonF::iterator polyIt;
while(b) {
rect = this->viewport()->visibleRegion().boundingRect();
poly = this->mapToScene(rect);
polyIt = poly.begin();
for (int i=0;i < poly.count(); i++) {
if (!this->outOfBounds(*polyIt)) {
b = false;
} else {
b = true;
break;
}
polyIt++;
}
*scaleControl -= factor;
*stepCounter = 0;
scale(1.01,1.01);
}
} else {
emit zoomFinished();
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::takeScreenshot() {
QString fileName = QFileDialog::getSaveFileName(this,"Screenshot speichern", "", "(*.png)");
QPixmap pic = QPixmap::grabWidget(this,this->viewport()->rect());
pic.save(fileName,"" ,100);
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
| 46.481356 | 190 | 0.310968 | HSHL |
51e332b99e5a59fcb7502c85f78dfd908289b5cd | 7,888 | cpp | C++ | ext/libigl/external/cgal/src/CGAL_Project/demo/Polyhedron/Scene_plane_item.cpp | liminchen/OptCuts | cb85b06ece3a6d1279863e26b5fd17a5abb0834d | [
"MIT"
] | 187 | 2019-01-23T04:07:11.000Z | 2022-03-27T03:44:58.000Z | ext/libigl/external/cgal/src/CGAL_Project/demo/Polyhedron/Scene_plane_item.cpp | xiaoxie5002/OptCuts | 1f4168fc867f47face85fcfa3a572be98232786f | [
"MIT"
] | 8 | 2019-03-22T13:27:38.000Z | 2020-06-18T13:23:23.000Z | ext/libigl/external/cgal/src/CGAL_Project/demo/Polyhedron/Scene_plane_item.cpp | xiaoxie5002/OptCuts | 1f4168fc867f47face85fcfa3a572be98232786f | [
"MIT"
] | 34 | 2019-02-13T01:11:12.000Z | 2022-02-28T03:29:40.000Z | #include "Scene_plane_item.h"
#include <QApplication>
using namespace CGAL::Three;
Scene_plane_item::Scene_plane_item(const CGAL::Three::Scene_interface* scene_interface)
:CGAL::Three::Scene_item(NbOfVbos,NbOfVaos),
scene(scene_interface),
manipulable(false),
can_clone(true),
frame(new ManipulatedFrame())
{
setNormal(0., 0., 1.);
//Generates an integer which will be used as ID for each buffer
invalidateOpenGLBuffers();
}
Scene_plane_item::~Scene_plane_item() {
delete frame;
}
void Scene_plane_item::initializeBuffers(Viewer_interface *viewer) const
{
program = getShaderProgram(PROGRAM_WITHOUT_LIGHT, viewer);
program->bind();
vaos[Facets]->bind();
buffers[Facets_vertices].bind();
buffers[Facets_vertices].allocate(positions_quad.data(),
static_cast<int>(positions_quad.size()*sizeof(float)));
program->enableAttributeArray("vertex");
program->setAttributeBuffer("vertex",GL_FLOAT,0,3);
buffers[Facets_vertices].release();
vaos[Facets]->release();
vaos[Edges]->bind();
buffers[Edges_vertices].bind();
buffers[Edges_vertices].allocate(positions_lines.data(),
static_cast<int>(positions_lines.size()*sizeof(float)));
program->enableAttributeArray("vertex");
program->setAttributeBuffer("vertex",GL_FLOAT,0,3);
buffers[Edges_vertices].release();
vaos[Edges]->release();
program->release();
are_buffers_filled = true;
}
void Scene_plane_item::compute_normals_and_vertices(void) const
{
QApplication::setOverrideCursor(Qt::WaitCursor);
positions_quad.resize(0);
positions_lines.resize(0);
const double diag = scene_diag();
//The quad
{
positions_quad.push_back(-diag);
positions_quad.push_back(-diag);
positions_quad.push_back(0.0 );
positions_quad.push_back(-diag);
positions_quad.push_back(diag );
positions_quad.push_back(0.0 );
positions_quad.push_back(diag );
positions_quad.push_back(-diag);
positions_quad.push_back(0.0 );
positions_quad.push_back(diag );
positions_quad.push_back(-diag);
positions_quad.push_back(0.0 );
positions_quad.push_back(-diag);
positions_quad.push_back(diag );
positions_quad.push_back(0.0 );
positions_quad.push_back(diag );
positions_quad.push_back(diag );
positions_quad.push_back(0.0 );
}
//The grid
float x = (2*diag)/10.0;
float y = (2*diag)/10.0;
{
for(int u = 0; u < 11; u++)
{
positions_lines.push_back(-diag + x* u);
positions_lines.push_back(-diag );
positions_lines.push_back(0.0 );
positions_lines.push_back(-diag + x* u);
positions_lines.push_back(diag );
positions_lines.push_back(0.0 );
}
for(int v=0; v<11; v++)
{
positions_lines.push_back(-diag );
positions_lines.push_back(-diag + v * y);
positions_lines.push_back(0.0 );
positions_lines.push_back(diag );
positions_lines.push_back(-diag + v * y);
positions_lines.push_back(0.0 );
}
}
QApplication::restoreOverrideCursor();
}
void Scene_plane_item::draw(Viewer_interface* viewer)const
{
if(!are_buffers_filled)
initializeBuffers(viewer);
vaos[Facets]->bind();
program = getShaderProgram(PROGRAM_WITHOUT_LIGHT);
attribBuffers(viewer, PROGRAM_WITHOUT_LIGHT);
QMatrix4x4 f_matrix;
for(int i=0; i<16; i++)
f_matrix.data()[i] = (float)frame->matrix()[i];
program->bind();
program->setUniformValue("f_matrix", f_matrix);
program->setAttributeValue("colors",this->color());
program->setUniformValue("is_selected", false);
viewer->glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(positions_quad.size()/3));
program->release();
vaos[Facets]->release();
}
void Scene_plane_item::drawEdges(CGAL::Three::Viewer_interface* viewer)const
{
if(!are_buffers_filled)
initializeBuffers(viewer);
vaos[Edges]->bind();
program = getShaderProgram(PROGRAM_WITHOUT_LIGHT);
attribBuffers(viewer, PROGRAM_WITHOUT_LIGHT);
QMatrix4x4 f_matrix;
for(int i=0; i<16; i++)
f_matrix.data()[i] = (float)frame->matrix()[i];
program->bind();
program->setUniformValue("f_matrix", f_matrix);
program->setAttributeValue("colors",QVector3D(0,0,0));
viewer->glDrawArrays(GL_LINES, 0, static_cast<GLsizei>(positions_lines.size()/3));
program->release();
vaos[Edges]->release();
}
void Scene_plane_item::flipPlane()
{
qglviewer::Quaternion q;
qglviewer::Vec axis(0,1,0);
if(frame->orientation().axis() == axis)
q.setAxisAngle(qglviewer::Vec(1,0,0), M_PI);
else
q.setAxisAngle(axis, M_PI);
frame->rotate(q.normalized());
invalidateOpenGLBuffers();
Q_EMIT itemChanged();
}
bool Scene_plane_item::manipulatable() const {
return manipulable;
}
Scene_item::ManipulatedFrame* Scene_plane_item::manipulatedFrame() {
return frame;
}
Scene_plane_item* Scene_plane_item::clone() const {
if(can_clone)
{
Scene_plane_item* item = new Scene_plane_item(scene);
item->manipulable = manipulable;
item->can_clone = true;
item->frame = new ManipulatedFrame;
item->frame->setPosition(frame->position());
item->frame->setOrientation(frame->orientation());
return item;
}
else
return 0;
}
QString Scene_plane_item::toolTip() const {
const qglviewer::Vec& pos = frame->position();
const qglviewer::Vec& n = frame->inverseTransformOf(qglviewer::Vec(0.f, 0.f, 1.f));
return
tr("<p><b>%1</b> (mode: %2, color: %3)<br />")
.arg(this->name())
.arg(this->renderingModeName())
.arg(this->color().name())
+
tr("<i>Plane</i></p>"
"<p>Equation: %1*x + %2*y + %3*z + %4 = 0<br />"
"Normal vector: (%1, %2, %3)<br />"
"Point: (%5, %6, %7)</p>")
.arg(n[0]).arg(n[1]).arg(n[2])
.arg( - pos * n)
.arg(pos[0]).arg(pos[1]).arg(pos[2])
+
tr("<p>Can clone: %1<br />"
"Manipulatable: %2</p>")
.arg(can_clone?tr("true"):tr("false"))
.arg(manipulable?tr("true"):tr("false"));
}
Plane_3 Scene_plane_item::plane(qglviewer::Vec offset) const {
const qglviewer::Vec& pos = frame->position() - offset;
const qglviewer::Vec& n =
frame->inverseTransformOf(qglviewer::Vec(0.f, 0.f, 1.f));
return Plane_3(n[0], n[1], n[2], - n * pos);
}
void Scene_plane_item::invalidateOpenGLBuffers()
{
compute_normals_and_vertices();
are_buffers_filled = false;
compute_bbox();
}
void Scene_plane_item::setPosition(float x, float y, float z) {
frame->setPosition(x, y, z);
}
void Scene_plane_item::setPosition(double x, double y, double z) {
const qglviewer::Vec offset = static_cast<CGAL::Three::Viewer_interface*>(QGLViewer::QGLViewerPool().first())->offset();
frame->setPosition((float)x+offset.x, (float)y+offset.y, (float)z+offset.z);
}
void Scene_plane_item::setNormal(float x, float y, float z) {
QVector3D normal(x,y,z);
if(normal == QVector3D(0,0,0))
return;
QVector3D origin(0,0,1);
qglviewer::Quaternion q;
if(origin == normal)
{
return;
}
if(origin == -normal)
{
q.setAxisAngle(qglviewer::Vec(0,1,0),M_PI);
frame->setOrientation(q);
return;
}
QVector3D cp = QVector3D::crossProduct(origin, normal);
cp.normalize();
q.setAxisAngle(qglviewer::Vec(cp.x(),cp.y(), cp.z()),acos(QVector3D::dotProduct(origin, normal)/(normal.length()*origin.length())));
frame->setOrientation(q.normalized());
}
void Scene_plane_item::setNormal(double x, double y, double z) {
setNormal((float)x, (float)y, (float)z);
}
void Scene_plane_item::setClonable(bool b) {
can_clone = b;
}
void Scene_plane_item::setManipulatable(bool b) {
manipulable = b;
}
| 29.214815 | 134 | 0.651749 | liminchen |
51e4be76c4bf77fc17279e8e7b8acfb626ce6280 | 38,962 | cpp | C++ | sceneloader.cpp | nlguillemot/fictional-doodle | d340f4e6983f77ea38b94f8ba30f7f1f5ebb532f | [
"MIT"
] | 14 | 2016-11-20T02:36:24.000Z | 2022-02-18T07:08:25.000Z | sceneloader.cpp | nlguillemot/fictional-doodle | d340f4e6983f77ea38b94f8ba30f7f1f5ebb532f | [
"MIT"
] | 1 | 2020-07-16T14:33:19.000Z | 2020-07-26T01:49:18.000Z | sceneloader.cpp | nlguillemot/fictional-doodle | d340f4e6983f77ea38b94f8ba30f7f1f5ebb532f | [
"MIT"
] | 1 | 2016-11-21T09:50:45.000Z | 2016-11-21T09:50:45.000Z | #include "sceneloader.h"
#include "scene.h"
// assimp includes
#include <cimport.h>
// assimp also has a scene.h. weird.
#include <scene.h>
#include <postprocess.h>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_inverse.hpp>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#include <vector>
#include <string>
#include <functional>
#include <array>
static void LoadMD5Materials(
Scene* scene,
const char* assetFolder, const char* modelFolder,
aiMaterial** materials, int numMaterials,
int* materialIDMapping)
{
// Only the texture types we care about
std::array<aiTextureType,3> textureTypes = {
aiTextureType_DIFFUSE,
aiTextureType_SPECULAR,
aiTextureType_NORMALS
};
static const int numTextureTypes = (int)textureTypes.size();
// find all textures that need to be loaded
std::vector<std::vector<std::string>> texturesToLoad(numTextureTypes);
for (int materialIdx = 0; materialIdx < numMaterials; materialIdx++)
{
aiMaterial* material = materials[materialIdx];
for (int textureTypeIdx = 0; textureTypeIdx < (int)textureTypes.size(); textureTypeIdx++)
{
int textureCount = (int)aiGetMaterialTextureCount(material, textureTypes[textureTypeIdx]);
for (int textureIdxInStack = 0; textureIdxInStack < (int)textureCount; textureIdxInStack++)
{
aiString path;
aiReturn result = aiGetMaterialTexture(material, textureTypes[textureTypeIdx], textureIdxInStack, &path, NULL, NULL, NULL, NULL, NULL, NULL);
if (result != AI_SUCCESS)
{
fprintf(stderr, "aiGetMaterialTexture failed: %s\n", aiGetErrorString());
exit(1);
}
texturesToLoad[textureTypeIdx].push_back(std::string(modelFolder) + path.C_Str());
}
}
}
std::vector<std::unordered_map<std::string, int>*> textureNameToIDs
{
&scene->DiffuseTextureNameToID,
&scene->SpecularTextureNameToID,
&scene->NormalTextureNameToID,
};
assert(textureNameToIDs.size() == numTextureTypes);
// keep only the unique textures
for (int textureTypeIdx = 0; textureTypeIdx < numTextureTypes; textureTypeIdx++)
{
// remove textures that appear more than once in this list
std::sort(begin(texturesToLoad[textureTypeIdx]), end(texturesToLoad[textureTypeIdx]));
texturesToLoad[textureTypeIdx].erase(
std::unique(begin(texturesToLoad[textureTypeIdx]), end(texturesToLoad[textureTypeIdx])),
end(texturesToLoad[textureTypeIdx]));
// remove textures that were loaded by previous meshes
texturesToLoad[textureTypeIdx].erase(
std::remove_if(begin(texturesToLoad[textureTypeIdx]), end(texturesToLoad[textureTypeIdx]),
[&textureNameToIDs, textureTypeIdx](const std::string& s) {
return textureNameToIDs[textureTypeIdx]->find(s) != textureNameToIDs[textureTypeIdx]->end();
}), end(texturesToLoad[textureTypeIdx]));
}
// load all the unique textures
for (int textureTypeIdx = 0; textureTypeIdx < numTextureTypes; textureTypeIdx++)
{
for (int textureToLoadIdx = 0; textureToLoadIdx < (int)texturesToLoad[textureTypeIdx].size(); textureToLoadIdx++)
{
const std::string& fullpath = assetFolder + texturesToLoad[textureTypeIdx][textureToLoadIdx];
int width, height, comp;
int req_comp = 4;
stbi_set_flip_vertically_on_load(1); // because GL
stbi_uc* img = stbi_load(fullpath.c_str(), &width, &height, &comp, req_comp);
if (!img)
{
fprintf(stderr, "stbi_load (%s): %s\n", fullpath.c_str(), stbi_failure_reason());
}
else
{
bool hasTransparency = false;
for (int i = 0; i < width * height; i++)
{
if (img[i * 4 + 3] != 255)
{
hasTransparency = true;
break;
}
}
bool isSRGB = false;
if (textureTypes[textureTypeIdx] == aiTextureType_DIFFUSE)
{
isSRGB = true;
}
else if (textureTypes[textureTypeIdx] == aiTextureType_SPECULAR)
{
isSRGB = false;
}
else if (textureTypes[textureTypeIdx] == aiTextureType_NORMALS)
{
isSRGB = false;
}
else
{
fprintf(stderr, "%s: Unhandled texture type %d\n", fullpath.c_str(), textureTypes[textureTypeIdx]);
exit(1);
}
// premultiply teh alphas
if (hasTransparency)
{
for (int i = 0; i < width * height; i++)
{
float alpha = glm::clamp(img[i * 4 + 3] / 255.0f, 0.0f, 1.0f);
if (isSRGB)
{
alpha = glm::clamp(std::pow(alpha, 1.0f / 2.2f), 0.0f, 1.0f);
}
img[i * 4 + 0] = stbi_uc(img[i * 4 + 0] * alpha);
img[i * 4 + 1] = stbi_uc(img[i * 4 + 1] * alpha);
img[i * 4 + 2] = stbi_uc(img[i * 4 + 2] * alpha);
}
}
if (req_comp != 0)
{
comp = req_comp;
}
GLenum srcDataFormat[4] = {
GL_RED, GL_RG, GL_RGB, GL_RGBA
};
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
if (textureTypes[textureTypeIdx] == aiTextureType_DIFFUSE)
{
float anisotropy;
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &anisotropy);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, anisotropy);
glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, width, height, 0, srcDataFormat[comp - 1], GL_UNSIGNED_BYTE, img);
}
else if (textureTypes[textureTypeIdx] == aiTextureType_SPECULAR)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, srcDataFormat[comp - 1], GL_UNSIGNED_BYTE, img);
}
else if (textureTypes[textureTypeIdx] == aiTextureType_NORMALS)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8_SNORM, width, height, 0, srcDataFormat[comp - 1], GL_UNSIGNED_BYTE, img);
}
else
{
fprintf(stderr, "%s: Unhandled texture type %d\n", fullpath.c_str(), textureTypes[textureTypeIdx]);
exit(1);
}
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
int id = -1;
if (textureTypes[textureTypeIdx] == aiTextureType_DIFFUSE)
{
DiffuseTexture d;
d.HasTransparency = hasTransparency;
d.TO = texture;
scene->DiffuseTextures.push_back(std::move(d));
id = (int)scene->DiffuseTextures.size() - 1;
}
else if (textureTypes[textureTypeIdx] == aiTextureType_SPECULAR)
{
SpecularTexture s;
s.TO = texture;
scene->SpecularTextures.push_back(std::move(s));
id = (int)scene->SpecularTextures.size() - 1;
}
else if (textureTypes[textureTypeIdx] == aiTextureType_NORMALS)
{
NormalTexture n;
n.TO = texture;
scene->NormalTextures.push_back(std::move(n));
id = (int)scene->NormalTextures.size() - 1;
}
else
{
fprintf(stderr, "%s: Unhandled texture type %d\n", fullpath.c_str(), textureTypes[textureTypeIdx]);
exit(1);
}
textureNameToIDs[textureTypeIdx]->emplace(texturesToLoad[textureTypeIdx][textureToLoadIdx], id);
stbi_image_free(img);
}
stbi_set_flip_vertically_on_load(0);
}
}
// hook up list of materials
for (int materialIdx = 0; materialIdx < numMaterials; materialIdx++)
{
aiMaterial* material = materials[materialIdx];
// Potential improvement:
// Look for an existing material with the same properties,
// instead of creating a new one.
Material newMat;
for (int textureTypeIdx = 0; textureTypeIdx < (int)textureTypes.size(); textureTypeIdx++)
{
int textureCount = (int)aiGetMaterialTextureCount(material, textureTypes[textureTypeIdx]);
for (int textureIdxInStack = 0; textureIdxInStack < (int)textureCount; textureIdxInStack++)
{
aiString path;
aiReturn result = aiGetMaterialTexture(material, textureTypes[textureTypeIdx], textureIdxInStack, &path, NULL, NULL, NULL, NULL, NULL, NULL);
if (result != AI_SUCCESS)
{
fprintf(stderr, "aiGetMaterialTexture failed: %s\n", aiGetErrorString());
exit(1);
}
std::string modelpath = std::string(modelFolder) + path.C_Str();
auto foundNameToID = textureNameToIDs[textureTypeIdx]->find(modelpath);
if (foundNameToID != textureNameToIDs[textureTypeIdx]->end())
{
int textureID = foundNameToID->second;
if (textureTypes[textureTypeIdx] == aiTextureType_DIFFUSE)
{
newMat.DiffuseTextureIDs.push_back(textureID);
}
else if (textureTypes[textureTypeIdx] == aiTextureType_SPECULAR)
{
newMat.SpecularTextureIDs.push_back(textureID);
}
else if (textureTypes[textureTypeIdx] == aiTextureType_NORMALS)
{
newMat.NormalTextureIDs.push_back(textureID);
}
else
{
fprintf(stderr, "%s: Unhandled texture type %d\n", modelpath.c_str(), textureTypes[textureTypeIdx]);
exit(1);
}
}
}
}
if (materialIDMapping)
{
materialIDMapping[materialIdx] = (int)scene->Materials.size();
}
scene->Materials.push_back(std::move(newMat));
}
}
static int LoadMD5SkeletonNode(
Scene* scene,
const aiNode* ainode,
const std::unordered_map<std::string, glm::mat4>& invBindPoseTransforms)
{
if (strcmp(ainode->mName.C_Str(), "<MD5_Hierarchy>") != 0)
{
fprintf(stderr, "Expected <MD5_Hierarchy>, got %s\n", ainode->mName.C_Str());
exit(1);
}
// traverse skeleton and flatten it
std::vector<aiNode*> boneNodes;
std::vector<int> boneParentIDs;
std::vector<std::pair<aiNode*, int>> skeletonDFSStack;
// Initialize stack with parentless bones
for (int childIdx = (int)ainode->mNumChildren - 1; childIdx >= 0; childIdx--)
{
skeletonDFSStack.emplace_back(ainode->mChildren[childIdx], -1);
}
while (!skeletonDFSStack.empty())
{
aiNode* node = skeletonDFSStack.back().first;
int parentID = skeletonDFSStack.back().second;
skeletonDFSStack.pop_back();
int myBoneID = (int)boneNodes.size();
boneNodes.push_back(node);
boneParentIDs.push_back(parentID);
for (int childIdx = (int)node->mNumChildren - 1; childIdx >= 0; childIdx--)
{
skeletonDFSStack.emplace_back(node->mChildren[childIdx], myBoneID);
}
}
int boneCount = (int)boneNodes.size();
// Generate bone indices for rendering
std::vector<glm::uvec2> boneIndices(boneCount - 1);
for (int boneIdx = 1, indexIdx = 0; boneIdx < boneCount; boneIdx++, indexIdx++)
{
boneIndices[indexIdx] = glm::uvec2(boneParentIDs[boneIdx], boneIdx);
}
Skeleton skeleton;
skeleton.BoneNames.resize(boneCount);
skeleton.BoneInverseBindPoseTransforms.resize(boneCount);
skeleton.BoneLengths.resize(boneCount);
skeleton.BoneParents = std::move(boneParentIDs);
skeleton.NumBones = boneCount;
skeleton.NumBoneIndices = 2 * (int)boneIndices.size();
for (int boneID = 0; boneID < boneCount; boneID++)
{
skeleton.BoneNames[boneID] = boneNodes[boneID]->mName.C_Str();
skeleton.BoneNameToID.emplace(skeleton.BoneNames[boneID], boneID);
int parentBoneID = skeleton.BoneParents[boneID];
// Unused bones won't have an inverse bind pose transform to use
auto it = invBindPoseTransforms.find(skeleton.BoneNames[boneID]);
if (it != invBindPoseTransforms.end())
{
skeleton.BoneInverseBindPoseTransforms[boneID] = it->second;
}
else
{
// Missing inverse bind pose implies no local transformation
printf("Bone %s has no inverse bind pose transform, assigning from ", skeleton.BoneNames[boneID].c_str());
if (parentBoneID >= 0)
{
// Same absolute transform as parent
printf("%s\n", skeleton.BoneNames[parentBoneID].c_str());
skeleton.BoneInverseBindPoseTransforms[boneID] = skeleton.BoneInverseBindPoseTransforms[parentBoneID];
}
else
{
// No absolute transform
printf("identity\n");
skeleton.BoneInverseBindPoseTransforms[boneID] = glm::mat4(1.0);
}
}
if (parentBoneID != -1)
{
glm::mat4 childInvBindPose = skeleton.BoneInverseBindPoseTransforms[boneID];
glm::mat4 childBindPose = inverse(childInvBindPose);
glm::vec3 childPosition = glm::vec3(childBindPose[3]);
glm::mat4 parentInvBindPose = skeleton.BoneInverseBindPoseTransforms[parentBoneID];
glm::mat4 parentBindPose = inverse(parentInvBindPose);
glm::vec3 parentPosition = glm::vec3(parentBindPose[3]);
skeleton.BoneLengths[boneID] = length(childPosition - parentPosition);
}
}
// Upload bone indices
glGenBuffers(1, &skeleton.BoneEBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skeleton.BoneEBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, boneIndices.size() * sizeof(boneIndices[0]), boneIndices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
scene->Skeletons.push_back(std::move(skeleton));
return (int)scene->Skeletons.size() - 1;
}
static int LoadMD5Skeleton(
Scene* scene,
const aiScene* aiscene)
{
aiNode* root = aiscene->mRootNode;
if (strcmp(root->mName.C_Str(), "<MD5_Root>") != 0)
{
fprintf(stderr, "Expected <MD5_Root>, got %s\n", root->mName.C_Str());
exit(1);
}
// Global skeleton transformation
glm::mat4 skeletonTransform = glm::transpose(glm::make_mat4(&root->mTransformation.a1));
// Retrieve inverse bind pose transformation for each mesh's bones
std::unordered_map<std::string, glm::mat4> invBindPoseTransforms;
for (int meshIdx = 0; meshIdx < (int)aiscene->mNumMeshes; meshIdx++)
{
for (int boneIdx = 0; boneIdx < (int)aiscene->mMeshes[meshIdx]->mNumBones; boneIdx++)
{
const aiBone* bone = aiscene->mMeshes[meshIdx]->mBones[boneIdx];
std::string boneName = bone->mName.C_Str();
invBindPoseTransforms[boneName] = glm::transpose(glm::make_mat4(&bone->mOffsetMatrix.a1));
}
}
// traverse all children
for (int childIdx = 0; childIdx < (int)root->mNumChildren; childIdx++)
{
aiNode* child = root->mChildren[childIdx];
if (strcmp(child->mName.C_Str(), "<MD5_Hierarchy>") == 0)
{
// Found skeleton
int skeletonID = LoadMD5SkeletonNode(scene, child, invBindPoseTransforms);
scene->Skeletons[skeletonID].Transform = skeletonTransform;
return skeletonID;
}
}
fprintf(stderr, "Failed to find skeleton in scene\n");
exit(1);
return -1;
}
static void LoadMD5Meshes(
Scene* scene,
int skeletonID,
const char* modelFolder, const char* meshFile,
aiMesh** meshes, int numMeshes,
const int* materialIDMapping, // 1-1 mapping with assimp scene materials
int* bindPoseMeshIDMapping)
{
for (int meshIdx = 0; meshIdx < numMeshes; meshIdx++)
{
aiMesh* mesh = meshes[meshIdx];
if (mesh->mPrimitiveTypes != aiPrimitiveType_TRIANGLE)
{
fprintf(stderr, "Mesh %s was not made out of triangles\n", mesh->mName.C_Str());
exit(1);
}
if (!mesh->mTextureCoords[0])
{
fprintf(stderr, "Mesh %s didn't have TexCoord\n", mesh->mName.C_Str());
exit(1);
}
if (!mesh->mNormals)
{
fprintf(stderr, "Mesh %s didn't have normals\n", mesh->mName.C_Str());
exit(1);
}
if (!mesh->mTangents)
{
fprintf(stderr, "Mesh %s didn't have tangents\n", mesh->mName.C_Str());
exit(1);
}
if (!mesh->mBitangents)
{
fprintf(stderr, "Mesh %s didn't have bitangents\n", mesh->mName.C_Str());
exit(1);
}
if (!mesh->mBones)
{
fprintf(stderr, "Mesh %s didn't have bones\n", mesh->mName.C_Str());
exit(1);
}
int vertexCount = (int)mesh->mNumVertices;
std::vector<PositionVertex> positions(vertexCount);
std::vector<TexCoordVertex> texCoords(vertexCount);
std::vector<DifferentialVertex> differentials(vertexCount);
for (int vertexIdx = 0; vertexIdx < vertexCount; vertexIdx++)
{
positions[vertexIdx].Position = glm::make_vec3(&mesh->mVertices[vertexIdx][0]);
texCoords[vertexIdx].TexCoord = glm::make_vec2(&mesh->mTextureCoords[0][vertexIdx][0]);
differentials[vertexIdx].Normal = glm::make_vec3(&mesh->mNormals[vertexIdx][0]);
differentials[vertexIdx].Tangent = glm::make_vec3(&mesh->mTangents[vertexIdx][0]);
differentials[vertexIdx].Bitangent = glm::make_vec3(&mesh->mBitangents[vertexIdx][0]);
}
const Skeleton& skeleton = scene->Skeletons[skeletonID];
int boneCount = (int)mesh->mNumBones;
std::vector<BoneWeightVertex> boneWeights(vertexCount);
std::vector<int> vertexNumBones(vertexCount);
for (int boneIdx = 0; boneIdx < boneCount; boneIdx++)
{
aiBone* bone = mesh->mBones[boneIdx];
int boneWeightCount = (int)bone->mNumWeights;
auto foundBone = skeleton.BoneNameToID.find(bone->mName.C_Str());
if (foundBone == end(skeleton.BoneNameToID))
{
fprintf(stderr, "Couldn't find bone %s in skeleton\n", bone->mName.C_Str());
exit(1);
}
int boneID = foundBone->second;
for (int weightIdx = 0; weightIdx < boneWeightCount; weightIdx++)
{
aiVertexWeight vertexWeight = bone->mWeights[weightIdx];
int vertexID = vertexWeight.mVertexId;
float weight = vertexWeight.mWeight;
if (vertexNumBones[vertexID] < 4)
{
boneWeights[vertexID].BoneIDs[vertexNumBones[vertexID]] = boneID;
boneWeights[vertexID].Weights[vertexNumBones[vertexID]] = weight;
vertexNumBones[vertexID]++;
}
else if (boneWeights[vertexID].Weights[3] < weight)
{
// Keep the top 4 influencing weights in sorted order. bubble down.
boneWeights[vertexID].Weights[3] = weight;
for (int nextWeight = 2; nextWeight >= 0; nextWeight--)
{
if (boneWeights[vertexID].Weights[nextWeight] >= boneWeights[vertexID].Weights[nextWeight + 1])
{
break;
}
std::swap(boneWeights[vertexID].Weights[nextWeight], boneWeights[vertexID].Weights[nextWeight + 1]);
}
}
}
}
int faceCount = (int)mesh->mNumFaces;
std::vector<glm::uvec3> indices(faceCount);
for (int faceIdx = 0; faceIdx < faceCount; faceIdx++)
{
indices[faceIdx] = glm::make_vec3(&mesh->mFaces[faceIdx].mIndices[0]);
}
BindPoseMesh bindPoseMesh;
bindPoseMesh.NumVertices = vertexCount;
bindPoseMesh.NumIndices = faceCount * 3;
bindPoseMesh.SkeletonID = skeletonID;
bindPoseMesh.MaterialID = materialIDMapping[mesh->mMaterialIndex];
glGenBuffers(1, &bindPoseMesh.PositionVBO);
glBindBuffer(GL_ARRAY_BUFFER, bindPoseMesh.PositionVBO);
glBufferData(GL_ARRAY_BUFFER, positions.size() * sizeof(positions[0]), positions.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &bindPoseMesh.TexCoordVBO);
glBindBuffer(GL_ARRAY_BUFFER, bindPoseMesh.TexCoordVBO);
glBufferData(GL_ARRAY_BUFFER, texCoords.size() * sizeof(texCoords[0]), texCoords.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &bindPoseMesh.DifferentialVBO);
glBindBuffer(GL_ARRAY_BUFFER, bindPoseMesh.DifferentialVBO);
glBufferData(GL_ARRAY_BUFFER, differentials.size() * sizeof(differentials[0]), differentials.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &bindPoseMesh.BoneVBO);
glBindBuffer(GL_ARRAY_BUFFER, bindPoseMesh.BoneVBO);
glBufferData(GL_ARRAY_BUFFER, boneWeights.size() * sizeof(boneWeights[0]), boneWeights.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &bindPoseMesh.EBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bindPoseMesh.EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(indices[0]), indices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glGenVertexArrays(1, &bindPoseMesh.SkinningVAO);
glBindVertexArray(bindPoseMesh.SkinningVAO);
glBindBuffer(GL_ARRAY_BUFFER, bindPoseMesh.PositionVBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(PositionVertex), (GLvoid*)offsetof(PositionVertex, Position));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, bindPoseMesh.TexCoordVBO);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(TexCoordVertex), (GLvoid*)offsetof(TexCoordVertex, TexCoord));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, bindPoseMesh.DifferentialVBO);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(DifferentialVertex), (GLvoid*)offsetof(DifferentialVertex, Normal));
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(DifferentialVertex), (GLvoid*)offsetof(DifferentialVertex, Tangent));
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(DifferentialVertex), (GLvoid*)offsetof(DifferentialVertex, Bitangent));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glEnableVertexAttribArray(4);
glBindBuffer(GL_ARRAY_BUFFER, bindPoseMesh.BoneVBO);
glVertexAttribIPointer(5, 4, GL_UNSIGNED_BYTE, sizeof(BoneWeightVertex), (GLvoid*)offsetof(BoneWeightVertex, BoneIDs));
glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, sizeof(BoneWeightVertex), (GLvoid*)offsetof(BoneWeightVertex, Weights));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(5);
glEnableVertexAttribArray(6);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bindPoseMesh.EBO);
glBindVertexArray(0);
if (bindPoseMeshIDMapping)
{
bindPoseMeshIDMapping[meshIdx] = (int)scene->BindPoseMeshes.size();
}
scene->BindPoseMeshes.push_back(std::move(bindPoseMesh));
}
}
void LoadMD5Mesh(
Scene* scene,
const char* assetFolder, const char* modelFolder,
const char* meshFile,
std::vector<int>* loadedMaterialIDs,
int* loadedSkeletonID,
std::vector<int>* loadedBindPoseMeshIDs)
{
std::string meshpath = std::string(assetFolder) + modelFolder + meshFile;
const aiScene* aiscene = aiImportFile(meshpath.c_str(), aiProcessPreset_TargetRealtime_MaxQuality);
if (!aiscene)
{
fprintf(stderr, "aiImportFile: %s\n", aiGetErrorString());
exit(1);
}
std::vector<int> materialIDMapping(aiscene->mNumMaterials);
LoadMD5Materials(
scene,
assetFolder, modelFolder,
aiscene->mMaterials, (int)aiscene->mNumMaterials,
materialIDMapping.data());
int skeletonID = LoadMD5Skeleton(scene, aiscene);
if (loadedSkeletonID) *loadedSkeletonID = skeletonID;
if (loadedBindPoseMeshIDs)
{
loadedBindPoseMeshIDs->resize(aiscene->mNumMeshes);
}
LoadMD5Meshes(
scene,
skeletonID,
modelFolder, meshFile,
&aiscene->mMeshes[0], (int)aiscene->mNumMeshes,
materialIDMapping.data(),
loadedBindPoseMeshIDs ? loadedBindPoseMeshIDs->data() : NULL);
if (loadedMaterialIDs)
{
*loadedMaterialIDs = std::move(materialIDMapping);
}
aiReleaseImport(aiscene);
}
void LoadMD5Anim(
Scene* scene,
int skeletonID,
const char* assetFolder, const char* modelFolder,
const char* animFile,
int* loadedAnimSequenceID)
{
std::string fullpath = std::string(assetFolder) + modelFolder + animFile;
const aiScene* animScene = aiImportFile(fullpath.c_str(), aiProcessPreset_TargetRealtime_MaxQuality);
// Check if file exists and was successfully parsed
if (!animScene)
{
fprintf(stderr, "aiImportFile: %s\n", aiGetErrorString());
return;
}
// Check if file contains an animation
if (animScene->mNumAnimations != 1)
{
fprintf(stderr, "Expected 1 animation in %s, got %d\n", fullpath.c_str(), (int)animScene->mNumAnimations);
return;
}
// TODO: Check if animation is valid for the skeleton
// One animation per file
const aiAnimation* animation = animScene->mAnimations[0];
AnimSequence animSequence;
animSequence.Name = std::string(modelFolder) + animFile;
animSequence.SkeletonID = skeletonID;
animSequence.FramesPerSecond = (int)animation->mTicksPerSecond;
animSequence.NumFrames = (int)animation->mDuration;
// Allocate storage for each bone
animSequence.BoneBaseFrame.resize(animation->mNumChannels);
animSequence.BoneChannelBits.resize(animation->mNumChannels);
animSequence.BoneFrameDataOffsets.resize(animation->mNumChannels);
int numFrameComponents = 0;
// For each bone
for (int bone = 0; bone < (int)animation->mNumChannels; bone++)
{
aiNodeAnim* boneAnim = animation->mChannels[bone];
// Base frame bone position
aiVector3D baseT = boneAnim->mPositionKeys[0].mValue;
animSequence.BoneBaseFrame[bone].T = glm::vec3(baseT.x, baseT.y, baseT.z);
// Base frame bone orientation
aiQuaternion baseQ = boneAnim->mRotationKeys[0].mValue;
animSequence.BoneBaseFrame[bone].Q = glm::quat(baseQ.w, baseQ.x, baseQ.y, baseQ.z);
// Find which position components of this bone are animated
glm::bvec3 isAnimatedT(false);
for (int i = 1; i < (int)boneAnim->mNumPositionKeys; i++)
{
aiVector3D v0 = boneAnim->mPositionKeys[i - 1].mValue;
aiVector3D v1 = boneAnim->mPositionKeys[i].mValue;
if (v0.x != v1.x) { isAnimatedT.x = true; }
if (v0.y != v1.y) { isAnimatedT.y = true; }
if (v0.z != v1.z) { isAnimatedT.z = true; }
if (all(isAnimatedT))
{
break;
}
}
// Find which orientation components of this bone are animated
glm::bvec3 isAnimatedQ(false);
for (int i = 1; i < (int)boneAnim->mNumRotationKeys; i++)
{
aiQuaternion q0 = boneAnim->mRotationKeys[i - 1].mValue;
aiQuaternion q1 = boneAnim->mRotationKeys[i].mValue;
if (q0.x != q1.x) { isAnimatedQ.x = true; }
if (q0.y != q1.y) { isAnimatedQ.y = true; }
if (q0.z != q1.z) { isAnimatedQ.z = true; }
if (all(isAnimatedQ))
{
break;
}
}
// Encode which position and orientation components are animated
animSequence.BoneChannelBits[bone] |= isAnimatedT.x ? ANIMCHANNEL_TX_BIT : 0;
animSequence.BoneChannelBits[bone] |= isAnimatedT.y ? ANIMCHANNEL_TY_BIT : 0;
animSequence.BoneChannelBits[bone] |= isAnimatedT.z ? ANIMCHANNEL_TZ_BIT : 0;
animSequence.BoneChannelBits[bone] |= isAnimatedQ.x ? ANIMCHANNEL_QX_BIT : 0;
animSequence.BoneChannelBits[bone] |= isAnimatedQ.y ? ANIMCHANNEL_QY_BIT : 0;
animSequence.BoneChannelBits[bone] |= isAnimatedQ.z ? ANIMCHANNEL_QZ_BIT : 0;
animSequence.BoneFrameDataOffsets[bone] = numFrameComponents;
// Update offset for the next bone
for (uint8_t bits = animSequence.BoneChannelBits[bone]; bits != 0; bits &= (bits - 1))
{
numFrameComponents++;
}
}
// Create storage for frame data
animSequence.BoneFrameData.resize(animSequence.NumFrames * numFrameComponents);
animSequence.NumFrameComponents = numFrameComponents;
// Generate encoded frame data
for (int bone = 0; bone < (int)animation->mNumChannels; bone++)
{
for (int frame = 0; frame < animSequence.NumFrames; frame++)
{
int off = animSequence.BoneFrameDataOffsets[bone];
uint8_t bits = animSequence.BoneChannelBits[bone];
if (bits & ANIMCHANNEL_TX_BIT)
{
int index = frame * numFrameComponents + off++;
animSequence.BoneFrameData[index] = animation->mChannels[bone]->mPositionKeys[frame].mValue.x;
}
if (bits & ANIMCHANNEL_TY_BIT)
{
int index = frame * numFrameComponents + off++;
animSequence.BoneFrameData[index] = animation->mChannels[bone]->mPositionKeys[frame].mValue.y;
}
if (bits & ANIMCHANNEL_TZ_BIT)
{
int index = frame * numFrameComponents + off++;
animSequence.BoneFrameData[index] = animation->mChannels[bone]->mPositionKeys[frame].mValue.z;
}
if (bits & ANIMCHANNEL_QX_BIT)
{
int index = frame * numFrameComponents + off++;
animSequence.BoneFrameData[index] = animation->mChannels[bone]->mRotationKeys[frame].mValue.x;
}
if (bits & ANIMCHANNEL_QY_BIT)
{
int index = frame * numFrameComponents + off++;
animSequence.BoneFrameData[index] = animation->mChannels[bone]->mRotationKeys[frame].mValue.y;
}
if (bits & ANIMCHANNEL_QZ_BIT)
{
int index = frame * numFrameComponents + off++;
animSequence.BoneFrameData[index] = animation->mChannels[bone]->mRotationKeys[frame].mValue.z;
}
}
}
scene->AnimSequences.push_back(std::move(animSequence));
int animSequenceID = (int)scene->AnimSequences.size() - 1;
if (loadedAnimSequenceID)
{
*loadedAnimSequenceID = animSequenceID;
}
aiReleaseImport(animScene);
}
static void LoadOBJMeshes(
Scene* scene,
const char* modelFolder, const char* meshFile,
aiMesh** meshes, int numMeshes,
const int* materialIDMapping, // 1-1 mapping with assimp scene materials
int* staticMeshIDMapping)
{
for (int meshIdx = 0; meshIdx < numMeshes; meshIdx++)
{
aiMesh* mesh = meshes[meshIdx];
if (mesh->mPrimitiveTypes != aiPrimitiveType_TRIANGLE)
{
fprintf(stderr, "Mesh %s was not made out of triangles\n", mesh->mName.C_Str());
exit(1);
}
if (!mesh->mTextureCoords[0])
{
fprintf(stderr, "Mesh %s didn't have TexCoord\n", mesh->mName.C_Str());
exit(1);
}
if (!mesh->mNormals)
{
fprintf(stderr, "Mesh %s didn't have normals\n", mesh->mName.C_Str());
exit(1);
}
if (!mesh->mTangents)
{
fprintf(stderr, "Mesh %s didn't have tangents\n", mesh->mName.C_Str());
exit(1);
}
if (!mesh->mBitangents)
{
fprintf(stderr, "Mesh %s didn't have bitangents\n", mesh->mName.C_Str());
exit(1);
}
int vertexCount = (int)mesh->mNumVertices;
std::vector<PositionVertex> positions(vertexCount);
std::vector<TexCoordVertex> texCoords(vertexCount);
std::vector<DifferentialVertex> differentials(vertexCount);
for (int vertexIdx = 0; vertexIdx < vertexCount; vertexIdx++)
{
positions[vertexIdx].Position = glm::make_vec3(&mesh->mVertices[vertexIdx][0]);
texCoords[vertexIdx].TexCoord = glm::make_vec2(&mesh->mTextureCoords[0][vertexIdx][0]);
differentials[vertexIdx].Normal = glm::make_vec3(&mesh->mNormals[vertexIdx][0]);
differentials[vertexIdx].Tangent = glm::make_vec3(&mesh->mTangents[vertexIdx][0]);
differentials[vertexIdx].Bitangent = glm::make_vec3(&mesh->mBitangents[vertexIdx][0]);
}
int faceCount = (int)mesh->mNumFaces;
std::vector<glm::uvec3> indices(faceCount);
for (int faceIdx = 0; faceIdx < faceCount; faceIdx++)
{
indices[faceIdx] = glm::make_vec3(&mesh->mFaces[faceIdx].mIndices[0]);
}
StaticMesh staticMesh;
staticMesh.NumVertices = vertexCount;
staticMesh.NumIndices = faceCount * 3;
staticMesh.MaterialID = materialIDMapping[mesh->mMaterialIndex];
glGenBuffers(1, &staticMesh.PositionVBO);
glBindBuffer(GL_ARRAY_BUFFER, staticMesh.PositionVBO);
glBufferData(GL_ARRAY_BUFFER, positions.size() * sizeof(positions[0]), positions.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &staticMesh.TexCoordVBO);
glBindBuffer(GL_ARRAY_BUFFER, staticMesh.TexCoordVBO);
glBufferData(GL_ARRAY_BUFFER, texCoords.size() * sizeof(texCoords[0]), texCoords.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &staticMesh.DifferentialVBO);
glBindBuffer(GL_ARRAY_BUFFER, staticMesh.DifferentialVBO);
glBufferData(GL_ARRAY_BUFFER, differentials.size() * sizeof(differentials[0]), differentials.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &staticMesh.MeshEBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, staticMesh.MeshEBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(indices[0]), indices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glGenVertexArrays(1, &staticMesh.MeshVAO);
glBindVertexArray(staticMesh.MeshVAO);
glBindBuffer(GL_ARRAY_BUFFER, staticMesh.PositionVBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(PositionVertex), (GLvoid*)offsetof(PositionVertex, Position));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, staticMesh.TexCoordVBO);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(TexCoordVertex), (GLvoid*)offsetof(TexCoordVertex, TexCoord));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, staticMesh.DifferentialVBO);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(DifferentialVertex), (GLvoid*)offsetof(DifferentialVertex, Normal));
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(DifferentialVertex), (GLvoid*)offsetof(DifferentialVertex, Tangent));
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(DifferentialVertex), (GLvoid*)offsetof(DifferentialVertex, Bitangent));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glEnableVertexAttribArray(4);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, staticMesh.MeshEBO);
glBindVertexArray(0);
if (staticMeshIDMapping)
{
staticMeshIDMapping[meshIdx] = (int)scene->StaticMeshes.size();
}
scene->StaticMeshes.push_back(std::move(staticMesh));
}
}
void LoadOBJMesh(
Scene* scene,
const char* assetFolder, const char* modelFolder,
const char* objFile,
std::vector<int>* loadedMaterialIDs,
std::vector<int>* loadedStaticMeshIDs)
{
std::string meshpath = std::string(assetFolder) + modelFolder + objFile;
const aiScene* aiscene = aiImportFile(meshpath.c_str(), aiProcessPreset_TargetRealtime_MaxQuality);
if (!aiscene)
{
fprintf(stderr, "aiImportFile: %s\n", aiGetErrorString());
exit(1);
}
std::vector<int> materialIDMapping(aiscene->mNumMaterials);
LoadMD5Materials(
scene,
assetFolder, modelFolder,
aiscene->mMaterials, (int)aiscene->mNumMaterials,
materialIDMapping.data());
std::vector<int> staticMeshIDMapping(aiscene->mNumMeshes);
LoadOBJMeshes(
scene,
modelFolder, objFile,
aiscene->mMeshes, (int)aiscene->mNumMeshes,
materialIDMapping.data(),
staticMeshIDMapping.data());
if (loadedMaterialIDs)
{
*loadedMaterialIDs = std::move(materialIDMapping);
}
if (loadedStaticMeshIDs)
{
*loadedStaticMeshIDs = std::move(staticMeshIDMapping);
}
aiReleaseImport(aiscene);
}
| 38.729622 | 157 | 0.603768 | nlguillemot |
51e7098934b5e0e3d3c1be331921771523063552 | 1,613 | hpp | C++ | src/test/_test.hpp | BigDataAnalyticsGroup/RewiredCracking | b12bf39b54672d28175f4608d266c505e3611459 | [
"Apache-2.0"
] | 3 | 2019-04-21T07:23:03.000Z | 2019-12-04T02:10:04.000Z | src/test/_test.hpp | BigDataAnalyticsGroup/RewiredCracking | b12bf39b54672d28175f4608d266c505e3611459 | [
"Apache-2.0"
] | null | null | null | src/test/_test.hpp | BigDataAnalyticsGroup/RewiredCracking | b12bf39b54672d28175f4608d266c505e3611459 | [
"Apache-2.0"
] | null | null | null | #ifndef TABLE
#error "#define TABLE to some hash table"
#endif
#ifndef HASH
#error "#define HASH to some hash function"
#endif
#include "test/catch.hpp"
#include <cstdint>
#define STRINGIFY(X) #X
#define STR(X) STRINGIFY(X)
#define PREFIX STR(TABLE) "/" STR(HASH)
using table_type = TABLE<uint64_t, uint64_t, HASH<uint64_t>>;
TEST_CASE( PREFIX )
{
table_type table(-1, 32);
REQUIRE(table.find(42) == table.end());
REQUIRE(table.end() == table.end());
}
TEST_CASE( PREFIX "/insert" )
{
table_type table(-1, 1024);
for (uint64_t i = 0; i != 42; ++i)
table.insert(i, i);
for (uint64_t i = 0; i != 42; ++i) {
auto it = table.find(i);
REQUIRE(it != table.end());
REQUIRE((*it).key == i);
REQUIRE((*it).value == i);
}
for (uint64_t i = 42; i != 1024; ++i)
REQUIRE(table.find(i) == table.end());
}
TEST_CASE( PREFIX "/rehash" )
{
table_type table(-1, 32);
/* initial fill */
for (uint64_t i = 0; i != 10; ++i)
table.insert(i, i);
for (uint64_t i = 0; i != 10; ++i) {
auto it = table.find(i);
REQUIRE(it != table.end());
REQUIRE((*it).key == i);
}
/* fill to trigger rehash(es) */
for (uint64_t i = 10; i != 1000; ++i)
table.insert(i, i);
/* verify state */
REQUIRE(table.size() == 1000);
REQUIRE(table.capacity() >= 1000);
for (uint64_t i = 0; i != 1000; ++i) {
auto it = table.find(i);
REQUIRE(it != table.end());
REQUIRE((*it).key == i);
}
}
#undef TABLE
#undef HASH
#undef STRINGIFY
#undef STR
#undef PREFIX
| 21.223684 | 61 | 0.548667 | BigDataAnalyticsGroup |
51eae19c8254bc366da7b0247539de283d54f016 | 4,494 | cpp | C++ | qttools/tests/auto/qhelpcontentmodel/tst_qhelpcontentmodel.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qttools/tests/auto/qhelpcontentmodel/tst_qhelpcontentmodel.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qttools/tests/auto/qhelpcontentmodel/tst_qhelpcontentmodel.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** 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 The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtCore/QThread>
#include <QtCore/QUrl>
#include <QtCore/QFileInfo>
#include <QtHelp/QHelpEngine>
#include <QtHelp/QHelpContentWidget>
class SignalWaiter : public QThread
{
Q_OBJECT
public:
SignalWaiter();
void run();
public slots:
void stopWaiting();
private:
bool stop;
};
SignalWaiter::SignalWaiter()
{
stop = false;
}
void SignalWaiter::run()
{
while (!stop)
msleep(500);
stop = false;
}
void SignalWaiter::stopWaiting()
{
stop = true;
}
class tst_QHelpContentModel : public QObject
{
Q_OBJECT
private slots:
void init();
void setupContents();
void contentItemAt();
private:
QString m_colFile;
};
void tst_QHelpContentModel::init()
{
// defined in profile
QString path = QLatin1String(SRCDIR);
m_colFile = path + QLatin1String("/data/col.qhc");
if (QFile::exists(m_colFile))
QDir::current().remove(m_colFile);
if (!QFile::copy(path + "/data/collection.qhc", m_colFile))
QFAIL("Cannot copy file!");
QFile f(m_colFile);
f.setPermissions(QFile::WriteUser|QFile::ReadUser);
}
void tst_QHelpContentModel::setupContents()
{
QHelpEngine h(m_colFile, 0);
QHelpContentModel *m = h.contentModel();
SignalWaiter w;
connect(m, SIGNAL(contentsCreated()),
&w, SLOT(stopWaiting()));
w.start();
h.setupData();
int i = 0;
while (w.isRunning() && i++ < 10)
QTest::qWait(500);
QCOMPARE(h.currentFilter(), QString("unfiltered"));
QCOMPARE(m->rowCount(), 4);
w.start();
h.setCurrentFilter("Custom Filter 1");
i = 0;
while (w.isRunning() && i++ < 10)
QTest::qWait(500);
QCOMPARE(m->rowCount(), 1);
}
void tst_QHelpContentModel::contentItemAt()
{
QHelpEngine h(m_colFile, 0);
QHelpContentModel *m = h.contentModel();
SignalWaiter w;
connect(m, SIGNAL(contentsCreated()),
&w, SLOT(stopWaiting()));
w.start();
h.setupData();
int i = 0;
while (w.isRunning() && i++ < 10)
QTest::qWait(500);
QCOMPARE(h.currentFilter(), QString("unfiltered"));
QModelIndex root = m->index(0, 0);
if (!root.isValid())
QFAIL("Cannot retrieve root item!");
QHelpContentItem *item = m->contentItemAt(root);
if (!item)
QFAIL("Cannot retrieve content item!");
QCOMPARE(item->title(), QString("qmake Manual"));
item = m->contentItemAt(m->index(4, 0, root));
QCOMPARE(item->title(), QString("qmake Concepts"));
item = m->contentItemAt(m->index(3, 0));
QCOMPARE(item->title(), QString("Fancy Manual"));
w.start();
h.setCurrentFilter("Custom Filter 1");
i = 0;
while (w.isRunning() && i++ < 10)
QTest::qWait(500);
item = m->contentItemAt(m->index(0, 0));
QCOMPARE(item->title(), QString("Test Manual"));
}
QTEST_MAIN(tst_QHelpContentModel)
#include "tst_qhelpcontentmodel.moc"
| 26.591716 | 77 | 0.646862 | wgnet |
51edb584ab6ed521376076b7cf871d1235b04a63 | 43,538 | cpp | C++ | src/modules/GenericPropagation/GenericPropagationModule.cpp | bencline1/Allpix_GaAs | c4922dc9d981aca265e076eb5bfe4cefe51913a2 | [
"MIT"
] | 3 | 2019-03-04T22:31:32.000Z | 2021-04-20T11:19:17.000Z | src/modules/GenericPropagation/GenericPropagationModule.cpp | bencline1/Allpix_GaAs | c4922dc9d981aca265e076eb5bfe4cefe51913a2 | [
"MIT"
] | 27 | 2019-04-01T12:25:46.000Z | 2021-09-03T12:20:19.000Z | src/modules/GenericPropagation/GenericPropagationModule.cpp | bencline1/Allpix_GaAs | c4922dc9d981aca265e076eb5bfe4cefe51913a2 | [
"MIT"
] | 15 | 2017-08-08T14:57:51.000Z | 2021-06-26T17:16:21.000Z | /**
* @file
* @brief Implementation of generic charge propagation module
* @remarks Based on code from Paul Schuetze
* @copyright Copyright (c) 2017-2020 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "GenericPropagationModule.hpp"
#include <cmath>
#include <limits>
#include <map>
#include <memory>
#include <random>
#include <sstream>
#include <string>
#include <utility>
#include <Eigen/Core>
#include <Math/Point3D.h>
#include <Math/Vector3D.h>
#include <TCanvas.h>
#include <TFile.h>
#include <TH2F.h>
#include <TH3F.h>
#include <TPaveText.h>
#include <TPolyLine3D.h>
#include <TPolyMarker3D.h>
#include <TStyle.h>
#include "core/config/Configuration.hpp"
#include "core/messenger/Messenger.hpp"
#include "core/utils/distributions.h"
#include "core/utils/log.h"
#include "core/utils/unit.h"
#include "tools/ROOT.h"
#include "tools/runge_kutta.h"
#include "objects/DepositedCharge.hpp"
#include "objects/PropagatedCharge.hpp"
using namespace allpix;
/**
* Besides binding the message and setting defaults for the configuration, the module copies some configuration variables to
* local copies to speed up computation.
*/
GenericPropagationModule::GenericPropagationModule(Configuration& config,
Messenger* messenger,
std::shared_ptr<Detector> detector)
: Module(config, detector), messenger_(messenger), detector_(std::move(detector)) {
// Save detector model
model_ = detector_->getModel();
// Require deposits message for single detector
messenger_->bindSingle<DepositedChargeMessage>(this, MsgFlags::REQUIRED);
// Set default value for config variables
config_.setDefault<double>("spatial_precision", Units::get(0.25, "nm"));
config_.setDefault<double>("timestep_start", Units::get(0.01, "ns"));
config_.setDefault<double>("timestep_min", Units::get(0.001, "ns"));
config_.setDefault<double>("timestep_max", Units::get(0.5, "ns"));
config_.setDefault<double>("integration_time", Units::get(25, "ns"));
config_.setDefault<unsigned int>("charge_per_step", 10);
config_.setDefault<double>("temperature", 293.15);
// Models:
config_.setDefault<std::string>("mobility_model", "jacoboni");
config_.setDefault<std::string>("recombination_model", "none");
config_.setDefault<bool>("output_linegraphs", false);
config_.setDefault<bool>("output_animations", false);
config_.setDefault<bool>("output_plots",
config_.get<bool>("output_linegraphs") || config_.get<bool>("output_animations"));
config_.setDefault<bool>("output_animations_color_markers", false);
config_.setDefault<double>("output_plots_step", config_.get<double>("timestep_max"));
config_.setDefault<bool>("output_plots_use_pixel_units", false);
config_.setDefault<bool>("output_plots_align_pixels", false);
config_.setDefault<double>("output_plots_theta", 0.0f);
config_.setDefault<double>("output_plots_phi", 0.0f);
config_.setDefault<bool>("output_plots_lines_at_implants", false);
// Set defaults for charge carrier propagation:
config_.setDefault<bool>("propagate_electrons", true);
config_.setDefault<bool>("propagate_holes", false);
if(!config_.get<bool>("propagate_electrons") && !config_.get<bool>("propagate_holes")) {
throw InvalidValueError(
config_,
"propagate_electrons",
"No charge carriers selected for propagation, enable 'propagate_electrons' or 'propagate_holes'.");
}
config_.setDefault<bool>("ignore_magnetic_field", false);
// Copy some variables from configuration to avoid lookups:
temperature_ = config_.get<double>("temperature");
timestep_min_ = config_.get<double>("timestep_min");
timestep_max_ = config_.get<double>("timestep_max");
timestep_start_ = config_.get<double>("timestep_start");
integration_time_ = config_.get<double>("integration_time");
target_spatial_precision_ = config_.get<double>("spatial_precision");
output_plots_ = config_.get<bool>("output_plots");
output_linegraphs_ = config_.get<bool>("output_linegraphs");
output_animations_ = config_.get<bool>("output_animations");
output_plots_step_ = config_.get<double>("output_plots_step");
output_plots_lines_at_implants_ = config_.get<bool>("output_plots_lines_at_implants");
propagate_electrons_ = config_.get<bool>("propagate_electrons");
propagate_holes_ = config_.get<bool>("propagate_holes");
charge_per_step_ = config_.get<unsigned int>("charge_per_step");
// Enable multithreading of this module if multithreading is enabled and no per-event output plots are requested:
// FIXME: Review if this is really the case or we can still use multithreading
if(!(output_animations_ || output_linegraphs_)) {
allow_multithreading();
} else {
LOG(WARNING) << "Per-event line graphs or animations requested, disabling parallel event processing";
}
boltzmann_kT_ = Units::get(8.6173e-5, "eV/K") * temperature_;
// Parameter for charge transport in magnetic field (approximated from graphs:
// http://www.ioffe.ru/SVA/NSM/Semicond/Si/electric.html) FIXME
electron_Hall_ = 1.15;
hole_Hall_ = 0.9;
}
void GenericPropagationModule::create_output_plots(uint64_t event_num, OutputPlotPoints& output_plot_points) {
LOG(TRACE) << "Writing output plots";
// Convert to pixel units if necessary
if(config_.get<bool>("output_plots_use_pixel_units")) {
for(auto& deposit_points : output_plot_points) {
for(auto& point : deposit_points.second) {
point.SetX(point.x() / model_->getPixelSize().x());
point.SetY(point.y() / model_->getPixelSize().y());
}
}
}
// Calculate the axis limits
double minX = FLT_MAX, maxX = FLT_MIN;
double minY = FLT_MAX, maxY = FLT_MIN;
unsigned long tot_point_cnt = 0;
double start_time = std::numeric_limits<double>::max();
unsigned int total_charge = 0;
unsigned int max_charge = 0;
for(auto& [deposit, points] : output_plot_points) {
for(auto& point : points) {
minX = std::min(minX, point.x());
maxX = std::max(maxX, point.x());
minY = std::min(minY, point.y());
maxY = std::max(maxY, point.y());
}
start_time = std::min(start_time, deposit.getGlobalTime());
total_charge += deposit.getCharge();
max_charge = std::max(max_charge, deposit.getCharge());
tot_point_cnt += points.size();
}
// Compute frame axis sizes if equal scaling is requested
if(config_.get<bool>("output_plots_use_equal_scaling", true)) {
double centerX = (minX + maxX) / 2.0;
double centerY = (minY + maxY) / 2.0;
if(config_.get<bool>("output_plots_use_pixel_units")) {
minX = centerX - model_->getSensorSize().z() / model_->getPixelSize().x() / 2.0;
maxX = centerX + model_->getSensorSize().z() / model_->getPixelSize().x() / 2.0;
minY = centerY - model_->getSensorSize().z() / model_->getPixelSize().y() / 2.0;
maxY = centerY + model_->getSensorSize().z() / model_->getPixelSize().y() / 2.0;
} else {
minX = centerX - model_->getSensorSize().z() / 2.0;
maxX = centerX + model_->getSensorSize().z() / 2.0;
minY = centerY - model_->getSensorSize().z() / 2.0;
maxY = centerY + model_->getSensorSize().z() / 2.0;
}
}
// Align on pixels if requested
if(config_.get<bool>("output_plots_align_pixels")) {
if(config_.get<bool>("output_plots_use_pixel_units")) {
minX = std::floor(minX - 0.5) + 0.5;
minY = std::floor(minY + 0.5) - 0.5;
maxX = std::ceil(maxX - 0.5) + 0.5;
maxY = std::ceil(maxY + 0.5) - 0.5;
} else {
double div = minX / model_->getPixelSize().x();
minX = (std::floor(div - 0.5) + 0.5) * model_->getPixelSize().x();
div = minY / model_->getPixelSize().y();
minY = (std::floor(div - 0.5) + 0.5) * model_->getPixelSize().y();
div = maxX / model_->getPixelSize().x();
maxX = (std::ceil(div + 0.5) - 0.5) * model_->getPixelSize().x();
div = maxY / model_->getPixelSize().y();
maxY = (std::ceil(div + 0.5) - 0.5) * model_->getPixelSize().y();
}
}
// Use a histogram to create the underlying frame
auto* histogram_frame = new TH3F(("frame_" + getUniqueName() + "_" + std::to_string(event_num)).c_str(),
"",
10,
minX,
maxX,
10,
minY,
maxY,
10,
model_->getSensorCenter().z() - model_->getSensorSize().z() / 2.0,
model_->getSensorCenter().z() + model_->getSensorSize().z() / 2.0);
histogram_frame->SetDirectory(getROOTDirectory());
// Create the canvas for the line plot and set orientation
auto canvas = std::make_unique<TCanvas>(("line_plot_" + std::to_string(event_num)).c_str(),
("Propagation of charge for event " + std::to_string(event_num)).c_str(),
1280,
1024);
canvas->cd();
canvas->SetTheta(config_.get<float>("output_plots_theta") * 180.0f / ROOT::Math::Pi());
canvas->SetPhi(config_.get<float>("output_plots_phi") * 180.0f / ROOT::Math::Pi());
// Draw the frame on the canvas
histogram_frame->GetXaxis()->SetTitle(
(std::string("x ") + (config_.get<bool>("output_plots_use_pixel_units") ? "(pixels)" : "(mm)")).c_str());
histogram_frame->GetYaxis()->SetTitle(
(std::string("y ") + (config_.get<bool>("output_plots_use_pixel_units") ? "(pixels)" : "(mm)")).c_str());
histogram_frame->GetZaxis()->SetTitle("z (mm)");
histogram_frame->Draw();
// Loop over all point sets created during propagation
// The vector of unique_pointers is required in order not to delete the objects before the canvas is drawn.
std::vector<std::unique_ptr<TPolyLine3D>> lines;
short current_color = 1;
for(auto& [deposit, points] : output_plot_points) {
auto line = std::make_unique<TPolyLine3D>();
for(auto& point : points) {
line->SetNextPoint(point.x(), point.y(), point.z());
}
// Plot all lines with at least three points with different color
if(line->GetN() >= 3) {
EColor plot_color = (deposit.getType() == CarrierType::ELECTRON ? EColor::kAzure : EColor::kOrange);
current_color = static_cast<short int>(plot_color - 9 + (static_cast<int>(current_color) + 1) % 19);
line->SetLineColor(current_color);
line->Draw("same");
}
lines.push_back(std::move(line));
}
// Draw and write canvas to module output file, then clear the stored lines
canvas->Draw();
getROOTDirectory()->WriteTObject(canvas.get());
lines.clear();
// Create canvas for GIF animition of process
canvas = std::make_unique<TCanvas>(("animation_" + std::to_string(event_num)).c_str(),
("Propagation of charge for event " + std::to_string(event_num)).c_str(),
1280,
1024);
canvas->cd();
// Change axis labels if close to zero or PI as they behave different here
if(std::fabs(config_.get<double>("output_plots_theta") / (ROOT::Math::Pi() / 2.0) -
std::round(config_.get<double>("output_plots_theta") / (ROOT::Math::Pi() / 2.0))) < 1e-6 ||
std::fabs(config_.get<double>("output_plots_phi") / (ROOT::Math::Pi() / 2.0) -
std::round(config_.get<double>("output_plots_phi") / (ROOT::Math::Pi() / 2.0))) < 1e-6) {
histogram_frame->GetXaxis()->SetLabelOffset(-0.1f);
histogram_frame->GetYaxis()->SetLabelOffset(-0.075f);
} else {
histogram_frame->GetXaxis()->SetTitleOffset(2.0f);
histogram_frame->GetYaxis()->SetTitleOffset(2.0f);
}
// Draw frame on canvas
histogram_frame->Draw();
if(output_animations_) {
// Create the contour histogram
std::vector<std::string> file_name_contour;
std::vector<TH2F*> histogram_contour;
file_name_contour.push_back(createOutputFile("contourX" + std::to_string(event_num) + ".gif"));
histogram_contour.push_back(new TH2F(("contourX_" + getUniqueName() + "_" + std::to_string(event_num)).c_str(),
"",
100,
minY,
maxY,
100,
model_->getSensorCenter().z() - model_->getSensorSize().z() / 2.0,
model_->getSensorCenter().z() + model_->getSensorSize().z() / 2.0));
histogram_contour.back()->SetDirectory(getROOTDirectory());
file_name_contour.push_back(createOutputFile("contourY" + std::to_string(event_num) + ".gif"));
histogram_contour.push_back(new TH2F(("contourY_" + getUniqueName() + "_" + std::to_string(event_num)).c_str(),
"",
100,
minX,
maxX,
100,
model_->getSensorCenter().z() - model_->getSensorSize().z() / 2.0,
model_->getSensorCenter().z() + model_->getSensorSize().z() / 2.0));
histogram_contour.back()->SetDirectory(getROOTDirectory());
file_name_contour.push_back(createOutputFile("contourZ" + std::to_string(event_num) + ".gif"));
histogram_contour.push_back(new TH2F(("contourZ_" + getUniqueName() + "_" + std::to_string(event_num)).c_str(),
"",
100,
minX,
maxX,
100,
minY,
maxY));
histogram_contour.back()->SetDirectory(getROOTDirectory());
// Create file and disable statistics for histogram
std::string file_name_anim = createOutputFile("animation" + std::to_string(event_num) + ".gif");
for(size_t i = 0; i < 3; ++i) {
histogram_contour[i]->SetStats(false);
}
// Remove temporary created files
auto ret = remove(file_name_anim.c_str());
for(size_t i = 0; i < 3; ++i) {
ret |= remove(file_name_contour[i].c_str());
}
if(ret != 0) {
throw ModuleError("Could not delete temporary animation files.");
}
// Create color table
TColor* colors[80]; // NOLINT
for(int i = 20; i < 100; ++i) {
auto color_idx = TColor::GetFreeColorIndex();
colors[i - 20] = new TColor(color_idx,
static_cast<float>(i) / 100.0f - 0.2f,
static_cast<float>(i) / 100.0f - 0.2f,
static_cast<float>(i) / 100.0f - 0.2f);
}
// Create animation of moving charges
auto animation_time = static_cast<unsigned int>(
std::round((Units::convert(config_.get<long double>("output_plots_step"), "ms") / 10.0) *
config_.get<long double>("output_animations_time_scaling", 1e9)));
unsigned long plot_idx = 0;
unsigned int point_cnt = 0;
LOG_PROGRESS(INFO, getUniqueName() + "_OUTPUT_PLOTS") << "Written 0 of " << tot_point_cnt << " points for animation";
while(point_cnt < tot_point_cnt) {
std::vector<std::unique_ptr<TPolyMarker3D>> markers;
unsigned long min_idx_diff = std::numeric_limits<unsigned long>::max();
// Reset the canvas
canvas->Clear();
canvas->SetTheta(config_.get<float>("output_plots_theta") * 180.0f / ROOT::Math::Pi());
canvas->SetPhi(config_.get<float>("output_plots_phi") * 180.0f / ROOT::Math::Pi());
canvas->Draw();
// Reset the histogram frame
histogram_frame->SetTitle("Charge propagation in sensor");
histogram_frame->GetXaxis()->SetTitle(
(std::string("x ") + (config_.get<bool>("output_plots_use_pixel_units") ? "(pixels)" : "(mm)")).c_str());
histogram_frame->GetYaxis()->SetTitle(
(std::string("y ") + (config_.get<bool>("output_plots_use_pixel_units") ? "(pixels)" : "(mm)")).c_str());
histogram_frame->GetZaxis()->SetTitle("z (mm)");
histogram_frame->Draw();
auto text = std::make_unique<TPaveText>(-0.75, -0.75, -0.60, -0.65);
auto time_ns = Units::convert(plot_idx * config_.get<long double>("output_plots_step"), "ns");
std::stringstream sstr;
sstr << std::fixed << std::setprecision(2) << time_ns << "ns";
auto time_str = std::string(8 - sstr.str().size(), ' ');
time_str += sstr.str();
text->AddText(time_str.c_str());
text->Draw();
// Plot all the required points
for(auto& [deposit, points] : output_plot_points) {
auto diff = static_cast<unsigned long>(
std::round((deposit.getGlobalTime() - start_time) / config_.get<long double>("output_plots_step")));
if(plot_idx < diff) {
min_idx_diff = std::min(min_idx_diff, diff - plot_idx);
continue;
}
auto idx = plot_idx - diff;
if(idx >= points.size()) {
continue;
}
min_idx_diff = 0;
auto marker = std::make_unique<TPolyMarker3D>();
marker->SetMarkerStyle(kFullCircle);
marker->SetMarkerSize(
static_cast<float>(deposit.getCharge() * config_.get<double>("output_animations_marker_size", 1)) /
static_cast<float>(max_charge));
auto initial_z_perc = static_cast<int>(
((points[0].z() + model_->getSensorSize().z() / 2.0) / model_->getSensorSize().z()) * 80);
initial_z_perc = std::max(std::min(79, initial_z_perc), 0);
if(config_.get<bool>("output_animations_color_markers")) {
marker->SetMarkerColor(static_cast<Color_t>(colors[initial_z_perc]->GetNumber()));
}
marker->SetNextPoint(points[idx].x(), points[idx].y(), points[idx].z());
marker->Draw();
markers.push_back(std::move(marker));
histogram_contour[0]->Fill(points[idx].y(), points[idx].z(), deposit.getCharge());
histogram_contour[1]->Fill(points[idx].x(), points[idx].z(), deposit.getCharge());
histogram_contour[2]->Fill(points[idx].x(), points[idx].y(), deposit.getCharge());
++point_cnt;
}
// Create a step in the animation
if(min_idx_diff != 0) {
canvas->Print((file_name_anim + "+100").c_str());
plot_idx += min_idx_diff;
} else {
// print animation
if(point_cnt < tot_point_cnt - 1) {
canvas->Print((file_name_anim + "+" + std::to_string(animation_time)).c_str());
} else {
canvas->Print((file_name_anim + "++100").c_str());
}
// Draw and print contour histograms
for(size_t i = 0; i < 3; ++i) {
canvas->Clear();
canvas->SetTitle((std::string("Contour of charge propagation projected on the ") +
static_cast<char>('X' + i) + "-axis")
.c_str());
switch(i) {
case 0 /* x */:
histogram_contour[i]->GetXaxis()->SetTitle(
(std::string("y ") + (config_.get<bool>("output_plots_use_pixel_units") ? "(pixels)" : "(mm)"))
.c_str());
histogram_contour[i]->GetYaxis()->SetTitle("z (mm)");
break;
case 1 /* y */:
histogram_contour[i]->GetXaxis()->SetTitle(
(std::string("x ") + (config_.get<bool>("output_plots_use_pixel_units") ? "(pixels)" : "(mm)"))
.c_str());
histogram_contour[i]->GetYaxis()->SetTitle("z (mm)");
break;
case 2 /* z */:
histogram_contour[i]->GetXaxis()->SetTitle(
(std::string("x ") + (config_.get<bool>("output_plots_use_pixel_units") ? "(pixels)" : "(mm)"))
.c_str());
histogram_contour[i]->GetYaxis()->SetTitle(
(std::string("y ") + (config_.get<bool>("output_plots_use_pixel_units") ? "(pixels)" : "(mm)"))
.c_str());
break;
default:;
}
histogram_contour[i]->SetMinimum(1);
histogram_contour[i]->SetMaximum(total_charge /
config_.get<double>("output_animations_contour_max_scaling", 10));
histogram_contour[i]->Draw("CONTZ 0");
if(point_cnt < tot_point_cnt - 1) {
canvas->Print((file_name_contour[i] + "+" + std::to_string(animation_time)).c_str());
} else {
canvas->Print((file_name_contour[i] + "++100").c_str());
}
histogram_contour[i]->Reset();
}
++plot_idx;
}
markers.clear();
LOG_PROGRESS(INFO, getUniqueName() + "_OUTPUT_PLOTS")
<< "Written " << point_cnt << " of " << tot_point_cnt << " points for animation";
}
}
}
void GenericPropagationModule::initialize() {
auto detector = getDetector();
// Check for electric field and output warning for slow propagation if not defined
if(!detector->hasElectricField()) {
LOG(WARNING) << "This detector does not have an electric field.";
}
// For linear fields we can in addition check if the correct carriers are propagated
if(detector->getElectricFieldType() == FieldType::LINEAR) {
auto model = detector_->getModel();
auto probe_point = ROOT::Math::XYZPoint(model->getSensorCenter().x(),
model->getSensorCenter().y(),
model->getSensorCenter().z() + model->getSensorSize().z() / 2.01);
// Get the field close to the implants and check its sign:
auto efield = detector->getElectricField(probe_point);
auto direction = std::signbit(efield.z());
// Compare with propagated carrier type:
if(direction && !propagate_electrons_) {
LOG(WARNING) << "Electric field indicates electron collection at implants, but electrons are not propagated!";
}
if(!direction && !propagate_holes_) {
LOG(WARNING) << "Electric field indicates hole collection at implants, but holes are not propagated!";
}
}
// Check for magnetic field
has_magnetic_field_ = detector->hasMagneticField();
if(has_magnetic_field_) {
if(config_.get<bool>("ignore_magnetic_field")) {
has_magnetic_field_ = false;
LOG(WARNING) << "A magnetic field is switched on, but is set to be ignored for this module.";
} else {
LOG(DEBUG) << "This detector sees a magnetic field.";
magnetic_field_ = detector_->getMagneticField();
}
}
if(output_plots_) {
step_length_histo_ =
CreateHistogram<TH1D>("step_length_histo",
"Step length;length [#mum];integration steps",
100,
0,
static_cast<double>(Units::convert(0.25 * model_->getSensorSize().z(), "um")));
drift_time_histo_ = CreateHistogram<TH1D>("drift_time_histo",
"Drift time;Drift time [ns];charge carriers",
static_cast<int>(Units::convert(integration_time_, "ns") * 5),
0,
static_cast<double>(Units::convert(integration_time_, "ns")));
uncertainty_histo_ =
CreateHistogram<TH1D>("uncertainty_histo",
"Position uncertainty;uncertainty [nm];integration steps",
100,
0,
static_cast<double>(4 * Units::convert(config_.get<double>("spatial_precision"), "nm")));
group_size_histo_ = CreateHistogram<TH1D>("group_size_histo",
"Charge carrier group size;group size;number of groups transported",
static_cast<int>(charge_per_step_ - 1),
1,
static_cast<double>(charge_per_step_));
recombine_histo_ =
CreateHistogram<TH1D>("recombination_histo",
"Fraction of recombined charge carriers;recombination [N / N_{total}] ;number of events",
100,
0,
1);
}
// Prepare mobility model
try {
mobility_ = Mobility(config_.get<std::string>("mobility_model"), temperature_, detector->hasDopingProfile());
} catch(ModelError& e) {
throw InvalidValueError(config_, "mobility_model", e.what());
}
// Prepare recombination model
try {
recombination_ = Recombination(config_.get<std::string>("recombination_model"), detector->hasDopingProfile());
} catch(ModelError& e) {
throw InvalidValueError(config_, "recombination_model", e.what());
}
}
void GenericPropagationModule::run(Event* event) {
auto deposits_message = messenger_->fetchMessage<DepositedChargeMessage>(this, event);
// Create vector of propagated charges to output
std::vector<PropagatedCharge> propagated_charges;
// List of points to plot to plot for output plots
OutputPlotPoints output_plot_points;
// Loop over all deposits for propagation
LOG(TRACE) << "Propagating charges in sensor";
unsigned int propagated_charges_count = 0;
unsigned int recombined_charges_count = 0;
unsigned int step_count = 0;
long double total_time = 0;
for(const auto& deposit : deposits_message->getData()) {
if((deposit.getType() == CarrierType::ELECTRON && !propagate_electrons_) ||
(deposit.getType() == CarrierType::HOLE && !propagate_holes_)) {
LOG(DEBUG) << "Skipping charge carriers (" << deposit.getType() << ") on "
<< Units::display(deposit.getLocalPosition(), {"mm", "um"});
continue;
}
// Only process if within requested integration time:
if(deposit.getLocalTime() > integration_time_) {
LOG(DEBUG) << "Skipping charge carriers deposited beyond integration time: "
<< Units::display(deposit.getGlobalTime(), "ns") << " global / "
<< Units::display(deposit.getLocalTime(), {"ns", "ps"}) << " local";
continue;
}
// Loop over all charges in the deposit
unsigned int charges_remaining = deposit.getCharge();
LOG(DEBUG) << "Set of charge carriers (" << deposit.getType() << ") on "
<< Units::display(deposit.getLocalPosition(), {"mm", "um"});
auto charge_per_step = charge_per_step_;
while(charges_remaining > 0) {
// Define number of charges to be propagated and remove charges of this step from the total
if(charge_per_step > charges_remaining) {
charge_per_step = charges_remaining;
}
charges_remaining -= charge_per_step;
// Get position and propagate through sensor
auto initial_position = deposit.getLocalPosition();
// Add point of deposition to the output plots if requested
if(output_linegraphs_) {
auto global_position = detector_->getGlobalPosition(initial_position);
std::lock_guard<std::mutex> lock{stats_mutex_};
output_plot_points.emplace_back(PropagatedCharge(initial_position,
global_position,
deposit.getType(),
charge_per_step,
deposit.getLocalTime(),
deposit.getGlobalTime()),
std::vector<ROOT::Math::XYZPoint>());
}
// Propagate a single charge deposit
auto [final_position, time, alive] = propagate(
initial_position, deposit.getType(), deposit.getLocalTime(), event->getRandomEngine(), output_plot_points);
if(!alive) {
LOG(DEBUG) << " Recombined " << charge_per_step << " at " << Units::display(final_position, {"mm", "um"})
<< " in " << Units::display(time, "ns") << " time, removing";
recombined_charges_count += charge_per_step;
continue;
}
LOG(DEBUG) << " Propagated " << charge_per_step << " to " << Units::display(final_position, {"mm", "um"})
<< " in " << Units::display(time, "ns") << " time";
// Create a new propagated charge and add it to the list
auto global_position = detector_->getGlobalPosition(final_position);
PropagatedCharge propagated_charge(final_position,
global_position,
deposit.getType(),
charge_per_step,
deposit.getLocalTime() + time,
deposit.getGlobalTime() + time,
&deposit);
propagated_charges.push_back(std::move(propagated_charge));
// Update statistical information
++step_count;
propagated_charges_count += charge_per_step;
total_time += charge_per_step * time;
if(output_plots_) {
drift_time_histo_->Fill(static_cast<double>(Units::convert(time, "ns")), charge_per_step);
group_size_histo_->Fill(charge_per_step);
}
}
}
// Output plots if required
if(output_linegraphs_) {
create_output_plots(event->number, output_plot_points);
}
// Write summary and update statistics
long double average_time = total_time / std::max(1u, propagated_charges_count);
LOG(INFO) << "Propagated " << propagated_charges_count << " charges in " << step_count << " steps in average time of "
<< Units::display(average_time, "ns") << std::endl
<< "Recombined " << recombined_charges_count << " charges during transport";
total_propagated_charges_ += propagated_charges_count;
total_steps_ += step_count;
total_time_picoseconds_ += static_cast<long unsigned int>(total_time * 1e3);
if(output_plots_) {
recombine_histo_->Fill(static_cast<double>(recombined_charges_count) /
(propagated_charges_count + recombined_charges_count));
}
// Create a new message with propagated charges
auto propagated_charge_message = std::make_shared<PropagatedChargeMessage>(std::move(propagated_charges), detector_);
// Dispatch the message with propagated charges
messenger_->dispatchMessage(this, propagated_charge_message, event);
}
/**
* Propagation is simulated using a parameterization for the electron mobility. This is used to calculate the electron
* velocity at every point with help of the electric field map of the detector. An Runge-Kutta integration is applied in
* multiple steps, adding a random diffusion to the propagating charge every step.
*/
std::tuple<ROOT::Math::XYZPoint, double, bool>
GenericPropagationModule::propagate(const ROOT::Math::XYZPoint& pos,
const CarrierType& type,
const double initial_time,
RandomNumberGenerator& random_generator,
OutputPlotPoints& output_plot_points) const {
// Create a runge kutta solver using the electric field as step function
Eigen::Vector3d position(pos.x(), pos.y(), pos.z());
// Define a function to compute the diffusion
auto carrier_diffusion = [&](double efield_mag, double doping_concentration, double timestep) -> Eigen::Vector3d {
double diffusion_constant = boltzmann_kT_ * mobility_(type, efield_mag, doping_concentration);
double diffusion_std_dev = std::sqrt(2. * diffusion_constant * timestep);
// Compute the independent diffusion in three
allpix::normal_distribution<double> gauss_distribution(0, diffusion_std_dev);
Eigen::Vector3d diffusion;
for(int i = 0; i < 3; ++i) {
diffusion[i] = gauss_distribution(random_generator);
}
return diffusion;
};
// Survival probability of this charge carrier package, evaluated at every step
std::uniform_real_distribution<double> survival(0, 1);
// Define lambda functions to compute the charge carrier velocity with or without magnetic field
std::function<Eigen::Vector3d(double, const Eigen::Vector3d&)> carrier_velocity_noB =
[&](double, const Eigen::Vector3d& cur_pos) -> Eigen::Vector3d {
auto raw_field = detector_->getElectricField(static_cast<ROOT::Math::XYZPoint>(cur_pos));
Eigen::Vector3d efield(raw_field.x(), raw_field.y(), raw_field.z());
auto doping = detector_->getDopingConcentration(static_cast<ROOT::Math::XYZPoint>(cur_pos));
return static_cast<int>(type) * mobility_(type, efield.norm(), doping) * efield;
};
std::function<Eigen::Vector3d(double, const Eigen::Vector3d&)> carrier_velocity_withB =
[&](double, const Eigen::Vector3d& cur_pos) -> Eigen::Vector3d {
auto raw_field = detector_->getElectricField(static_cast<ROOT::Math::XYZPoint>(cur_pos));
Eigen::Vector3d efield(raw_field.x(), raw_field.y(), raw_field.z());
Eigen::Vector3d velocity;
Eigen::Vector3d bfield(magnetic_field_.x(), magnetic_field_.y(), magnetic_field_.z());
auto doping = detector_->getDopingConcentration(static_cast<ROOT::Math::XYZPoint>(cur_pos));
auto mob = mobility_(type, efield.norm(), doping);
auto exb = efield.cross(bfield);
Eigen::Vector3d term1;
double hallFactor = (type == CarrierType::ELECTRON ? electron_Hall_ : hole_Hall_);
term1 = static_cast<int>(type) * mob * hallFactor * exb;
Eigen::Vector3d term2 = mob * mob * hallFactor * hallFactor * efield.dot(bfield) * bfield;
auto rnorm = 1 + mob * mob * hallFactor * hallFactor * bfield.dot(bfield);
return static_cast<int>(type) * mob * (efield + term1 + term2) / rnorm;
};
// Create the runge kutta solver with an RKF5 tableau, using different velocity calculators depending on the magnetic
// field
auto runge_kutta = make_runge_kutta(
tableau::RK5, (has_magnetic_field_ ? carrier_velocity_withB : carrier_velocity_noB), timestep_start_, position);
// Continue propagation until the deposit is outside the sensor
Eigen::Vector3d last_position = position;
double last_time = 0;
size_t next_idx = 0;
bool is_alive = true;
while(detector_->getModel()->isWithinSensor(static_cast<ROOT::Math::XYZPoint>(position)) &&
(initial_time + runge_kutta.getTime()) < integration_time_ && is_alive) {
// Update output plots if necessary (depending on the plot step)
if(output_linegraphs_) {
auto time_idx = static_cast<size_t>(runge_kutta.getTime() / output_plots_step_);
while(next_idx <= time_idx) {
output_plot_points.back().second.push_back(static_cast<ROOT::Math::XYZPoint>(position));
next_idx = output_plot_points.back().second.size();
}
}
// Save previous position and time
last_position = position;
last_time = runge_kutta.getTime();
// Execute a Runge Kutta step
auto step = runge_kutta.step();
// Get the current result and timestep
auto timestep = runge_kutta.getTimeStep();
position = runge_kutta.getValue();
// Get electric field at current position and fall back to empty field if it does not exist
auto efield = detector_->getElectricField(static_cast<ROOT::Math::XYZPoint>(position));
auto doping = detector_->getDopingConcentration(static_cast<ROOT::Math::XYZPoint>(position));
// Apply diffusion step
auto diffusion = carrier_diffusion(std::sqrt(efield.Mag2()), doping, timestep);
position += diffusion;
runge_kutta.setValue(position);
// Check if charge carrier is still alive:
is_alive = !recombination_(type,
detector_->getDopingConcentration(static_cast<ROOT::Math::XYZPoint>(position)),
survival(random_generator),
timestep);
LOG(TRACE) << "Step from " << Units::display(static_cast<ROOT::Math::XYZPoint>(last_position), {"um", "mm"})
<< " to " << Units::display(static_cast<ROOT::Math::XYZPoint>(position), {"um", "mm"}) << " at "
<< Units::display(initial_time + runge_kutta.getTime(), {"ps", "ns", "us"})
<< (is_alive ? "" : ", recombined");
// Adapt step size to match target precision
double uncertainty = step.error.norm();
// Update step length histogram
if(output_plots_) {
step_length_histo_->Fill(static_cast<double>(Units::convert(step.value.norm(), "um")));
uncertainty_histo_->Fill(static_cast<double>(Units::convert(step.error.norm(), "nm")));
}
// Lower timestep when reaching the sensor edge
if(std::fabs(model_->getSensorSize().z() / 2.0 - position.z()) < 2 * step.value.z()) {
timestep *= 0.75;
} else {
if(uncertainty > target_spatial_precision_) {
timestep *= 0.75;
} else if(2 * uncertainty < target_spatial_precision_) {
timestep *= 1.5;
}
}
// Limit the timestep to certain minimum and maximum step sizes
if(timestep > timestep_max_) {
timestep = timestep_max_;
} else if(timestep < timestep_min_) {
timestep = timestep_min_;
}
runge_kutta.setTimeStep(timestep);
}
// Find proper final position in the sensor
auto time = runge_kutta.getTime();
if(!detector_->getModel()->isWithinSensor(static_cast<ROOT::Math::XYZPoint>(position))) {
auto check_position = position;
check_position.z() = last_position.z();
if(position.z() > 0 && detector_->getModel()->isWithinSensor(static_cast<ROOT::Math::XYZPoint>(check_position))) {
// Carrier left sensor on the side of the pixel grid, interpolate end point on surface
auto z_cur_border = std::fabs(position.z() - model_->getSensorSize().z() / 2.0);
auto z_last_border = std::fabs(model_->getSensorSize().z() / 2.0 - last_position.z());
auto z_total = z_cur_border + z_last_border;
position = (z_last_border / z_total) * position + (z_cur_border / z_total) * last_position;
time = (z_last_border / z_total) * time + (z_cur_border / z_total) * last_time;
} else {
// Carrier left sensor on any order border, use last position inside instead
position = last_position;
time = last_time;
}
}
// If requested, remove charge drift lines from plots if they did not reach the implant side within the integration time:
if(output_linegraphs_ && output_plots_lines_at_implants_) {
// If drift time is larger than integration time or the charge carriers have been collected at the backside, remove
if(time >= integration_time_ || last_position.z() < -model_->getSensorSize().z() * 0.45) {
output_plot_points.pop_back();
}
}
if(!is_alive) {
LOG(DEBUG) << "Charge carrier recombined after " << Units::display(last_time, {"ns"});
}
// Return the final position of the propagated charge
return std::make_tuple(static_cast<ROOT::Math::XYZPoint>(position), initial_time + time, is_alive);
}
void GenericPropagationModule::finalize() {
if(output_plots_) {
step_length_histo_->Write();
drift_time_histo_->Write();
uncertainty_histo_->Write();
group_size_histo_->Write();
recombine_histo_->Write();
}
long double average_time = static_cast<long double>(total_time_picoseconds_) / 1e3 /
std::max(1u, static_cast<unsigned int>(total_propagated_charges_));
LOG(INFO) << "Propagated total of " << total_propagated_charges_ << " charges in " << total_steps_
<< " steps in average time of " << Units::display(average_time, "ns");
}
| 49.475 | 125 | 0.571593 | bencline1 |
51edfece79314dc7d87e1282ddbda109954e4ae2 | 2,601 | cpp | C++ | example_bar_plot/src/ofApp.cpp | nickgillian/ofxGrt | 689c068b76af9e614f7124dbd4f38c8640c3a06d | [
"MIT"
] | 127 | 2016-01-04T20:33:15.000Z | 2021-11-30T07:18:48.000Z | example_bar_plot/src/ofApp.cpp | nickgillian/ofxGrt | 689c068b76af9e614f7124dbd4f38c8640c3a06d | [
"MIT"
] | 29 | 2016-01-05T20:39:14.000Z | 2021-01-04T04:07:37.000Z | example_bar_plot/src/ofApp.cpp | nickgillian/ofxGrt | 689c068b76af9e614f7124dbd4f38c8640c3a06d | [
"MIT"
] | 33 | 2016-01-05T18:44:57.000Z | 2020-08-09T00:13:47.000Z |
#include "ofApp.h"
#define NUM_DIMENSIONS 20
//--------------------------------------------------------------
void ofApp::setup(){
ofSetBackgroundColor(255);
//Load the font for the graph
font.load("verdana.ttf", 12, true, true);
font.setLineHeight(14.0f);
//Setup the plot
plot1.setup( NUM_DIMENSIONS, "sine data");
plot1.setRanges( -1.0, 1.0, true );
}
//--------------------------------------------------------------
void ofApp::update(){
//Update the data
vector< float > data( NUM_DIMENSIONS );
for(unsigned int i=0; i<NUM_DIMENSIONS; i++){
data[i] = sin( ofMap(i,0,NUM_DIMENSIONS-1,0.0,TWO_PI) );
}
plot1.update( data );
}
//--------------------------------------------------------------
void ofApp::draw(){
int plotX = 10;
int plotY = 10;
int plotW = ofGetWidth() - plotX*2;
int plotH = ofGetHeight() - 20;
ofSetColor(255,255,255);
ofFill();
plot1.draw( plotX, plotY, plotW, plotH );
ofSetColor(255,0,0);
ofNoFill();
ofDrawRectangle( plotX, plotY, plotW, plotH );
plotX += 25 + plotW;
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch(key){
case 'q':
{
ofImage img;
img.grabScreen(0, 0 , ofGetWidth(), ofGetHeight());
img.save( ofToDataPath( "screenshot_" + Util::timeAsString() + ".png") );
}
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 23.017699 | 89 | 0.38985 | nickgillian |
51ef9a043c754240e5c35ab326db8e2a7dee9b42 | 4,009 | cpp | C++ | fileformats/GOB_Reader.cpp | kcat/XLEngine | 0e735ad67fa40632add3872e0cbe5a244689cbe5 | [
"MIT"
] | 1 | 2021-07-25T15:10:39.000Z | 2021-07-25T15:10:39.000Z | fileformats/GOB_Reader.cpp | kcat/XLEngine | 0e735ad67fa40632add3872e0cbe5a244689cbe5 | [
"MIT"
] | null | null | null | fileformats/GOB_Reader.cpp | kcat/XLEngine | 0e735ad67fa40632add3872e0cbe5a244689cbe5 | [
"MIT"
] | null | null | null | #include "GOB_Reader.h"
#include "../EngineSettings.h"
#include "../ui/XL_Console.h"
#include <string.h>
#include <stdio.h>
#include <cstdint>
GOB_Reader::GOB_Reader() : Archive()
{
m_CurFile = -1;
m_pFile = NULL;
m_FileList.pEntries = NULL;
}
bool GOB_Reader::Open(const char *pszName)
{
sprintf(m_szFileName, "%s%s", EngineSettings::get().GetGameDataDir(), pszName);
m_bGOB = true;
size_t l = strlen(pszName);
if ( (pszName[l-3] == 'l' && pszName[l-2] == 'a' && pszName[l-1] == 'b') ||
(pszName[l-3] == 'L' && pszName[l-2] == 'A' && pszName[l-1] == 'B') )
{
//this is a LAB file - very similar to a gob though.
m_bGOB = false;
}
FILE *f = fopen(m_szFileName, "rb");
if ( f )
{
fread(&m_Header, sizeof(GOB_Header_t), 1, f);
if ( m_bGOB )
{
fseek(f, m_Header.MASTERX, SEEK_SET);
fread(&m_FileList.MASTERN, sizeof(int32_t), 1, f);
m_FileList.pEntries = xlNew GOB_Entry_t[m_FileList.MASTERN];
fread(m_FileList.pEntries, sizeof(GOB_Entry_t), m_FileList.MASTERN, f);
}
else
{
int32_t stringTableSize;
fread(&m_FileList.MASTERN, sizeof(int32_t), 1, f);
fread(&stringTableSize, sizeof(int32_t), 1, f);
m_FileList.pEntries = xlNew GOB_Entry_t[m_FileList.MASTERN];
//now read string table.
fseek(f, 16*(m_FileList.MASTERN+1), SEEK_SET);
char *pStringTable = xlNew char[stringTableSize+1];
fread(pStringTable, 1, stringTableSize, f);
//now read the entries.
fseek(f, 16, SEEK_SET);
for (int32_t e=0; e<m_FileList.MASTERN; e++)
{
uint32_t fname_offs;
uint32_t start, size, dummy;
fread(&fname_offs, sizeof(uint32_t), 1, f);
fread(&start, sizeof(uint32_t), 1, f);
fread(&size, sizeof(uint32_t), 1, f);
fread(&dummy, sizeof(uint32_t), 1, f);
m_FileList.pEntries[e].IX = start;
m_FileList.pEntries[e].LEN = size;
strcpy(m_FileList.pEntries[e].NAME, &pStringTable[fname_offs]);
}
xlDelete [] pStringTable;
pStringTable = NULL;
}
fclose(f);
m_bOpen = true;
return true;
}
XL_Console::PrintF("^1Error: Failed to load %s", m_szFileName);
return false;
}
void GOB_Reader::Close()
{
CloseFile();
if ( m_FileList.pEntries )
{
xlDelete [] m_FileList.pEntries;
m_FileList.pEntries = NULL;
}
m_bOpen = false;
}
bool GOB_Reader::OpenFile(const char *pszFile)
{
m_pFile = fopen(m_szFileName, "rb");
m_CurFile = -1;
if ( m_pFile )
{
//search for this file.
for (int32_t i=0; i<m_FileList.MASTERN; i++)
{
if ( stricmp(pszFile, m_FileList.pEntries[i].NAME) == 0 )
{
m_CurFile = i;
break;
}
}
if ( m_CurFile == -1 )
{
XL_Console::PrintF("^1Error: Failed to load %s from \"%s\"", pszFile, m_szFileName);
}
}
return m_CurFile > -1 ? true : false;
}
void GOB_Reader::CloseFile()
{
if ( m_pFile )
{
fclose(m_pFile);
m_pFile = NULL;
}
m_CurFile = -1;
}
uint32_t GOB_Reader::GetFileLen()
{
return (uint32_t)m_FileList.pEntries[ m_CurFile ].LEN;
}
bool GOB_Reader::ReadFile(void *pData, uint32_t uLength)
{
if ( !m_pFile ) { return false; }
fseek(m_pFile, m_FileList.pEntries[ m_CurFile ].IX, SEEK_SET);
if ( uLength == 0 )
uLength = (uint32_t)m_FileList.pEntries[ m_CurFile ].LEN;
fread(pData, uLength, 1, m_pFile);
return true;
}
int32_t GOB_Reader::GetFileCount()
{
return m_FileList.MASTERN;
}
const char *GOB_Reader::GetFileName(int32_t nFileIdx)
{
return m_FileList.pEntries[nFileIdx].NAME;
}
| 25.864516 | 96 | 0.555251 | kcat |
51f35f32ac3fdc6b9538c40aa78866d4458fb31b | 7,903 | cpp | C++ | src/cpp/DeviceState.cpp | pongasoft/re-ab12-audio-out-switch | 525e0074250244646f57c7346e89559f99dbd0ab | [
"Apache-2.0"
] | 1 | 2021-10-12T17:45:43.000Z | 2021-10-12T17:45:43.000Z | src/cpp/DeviceState.cpp | pongasoft/re-ab12-audio-out-switch | 525e0074250244646f57c7346e89559f99dbd0ab | [
"Apache-2.0"
] | null | null | null | src/cpp/DeviceState.cpp | pongasoft/re-ab12-audio-out-switch | 525e0074250244646f57c7346e89559f99dbd0ab | [
"Apache-2.0"
] | null | null | null | //
// Created by Yan Pujante on 5/23/15.
//
#include "DeviceState.h"
DeviceState::DeviceState() : fSingleStateKeySwitch(kNone)
{
for (int i = static_cast<int>(kA1); i < static_cast<int>(kEnd); ++i)
{
fSwitchedOutputStates[i] = new SwitchedOutputState(fMotherboard.fSwitchedOutputs[i]);
}
for (int i = static_cast<int>(kA1); i < static_cast<int>(kEnd); ++i)
{
fSelectedSwitches[i] = false;
fSelectedAndConnectedSwitches[i] = false;
}
}
void DeviceState::init()
{
fSingleStateKeySwitch = kNone;
}
void DeviceState::update(const DeviceState &rhs)
{
fMotherboard.update(rhs.fMotherboard);
for (int i = static_cast<int>(kA1); i < static_cast<int>(kEnd); ++i)
{
fSwitchedOutputStates[i]->update(*rhs.fSwitchedOutputStates[i]);
fSelectedSwitches[i] = rhs.fSelectedSwitches[i];
fSelectedAndConnectedSwitches[i] = rhs.fSelectedAndConnectedSwitches[i];
}
fSingleStateKeySwitch = rhs.fSingleStateKeySwitch;
}
bool DeviceState::onNoteReceived(const TJBox_PropertyDiff &iPropertyDiff)
{
TJBox_Tag noteIndex = iPropertyDiff.fPropertyTag;
int outputIndex = (noteIndex % 12) + static_cast<int>(kA1);
JBOX_ASSERT(outputIndex >= kA1 && outputIndex < kEnd);
SwitchedOutputState *output = fSwitchedOutputStates[outputIndex];
bool cur = JBox::toJBoxFloat64(iPropertyDiff.fCurrentValue) != 0;
bool prev = JBox::toJBoxFloat64(iPropertyDiff.fPreviousValue) != 0;
if(cur != prev)
{
if(cur && isSingleMode() && isKeyboardEnabled())
fSingleStateKeySwitch = output->getId();
output->setNoteSelection(cur);
return true;
}
return false;
}
bool DeviceState::afterMotherboardUpdate(bool motherboardStateChanged,
DeviceState const &previousState)
{
bool res = motherboardStateChanged;
// adjust midi and volume
for (int i = static_cast<int>(kA1); i < static_cast<int>(kEnd); ++i)
{
SwitchedOutputState *output = fSwitchedOutputStates[i];
res |= output->afterMotherboardUpdate(motherboardStateChanged,
fMotherboard.fPropVolumeChangeFilter.getValue());
}
if(motherboardStateChanged)
{
if(previousState.isKeyboardEnabled() && !isKeyboardEnabled())
fSingleStateKeySwitch = kNone;
// handle CV (single state)
TJBox_Float64 stateSingleCV = previousState.fMotherboard.fPropStateSingleCV.getValue();
// if there is UI override, it trumps everything
if(fMotherboard.fPropStateSingle.isNotSameValue(previousState.fMotherboard.fPropStateSingle) ||
fMotherboard.fPropStateSingleOverrideCV.isNotSameValue(previousState.fMotherboard.fPropStateSingleOverrideCV))
{
fSingleStateKeySwitch = kNone;
stateSingleCV = 0;
}
else
{
// keyboard trumps cv (if enabled)
if(previousState.fSingleStateKeySwitch != fSingleStateKeySwitch && isKeyboardEnabled())
{
stateSingleCV = fSingleStateKeySwitch;
}
else
{
// no longer connected => no state from CV
if(!fMotherboard.fCVInStateSingle.isConnected() && previousState.fMotherboard.fCVInStateSingle.isConnected())
stateSingleCV = fSingleStateKeySwitch;
else
{
if(fMotherboard.fCVInStateSingle.isNotSameValue(previousState.fMotherboard.fCVInStateSingle)) // only when CV changes
{
TJBox_Int32 noteValue = fMotherboard.fCVInStateSingle.getValue();
if(noteValue >= kMidiC0)
{
stateSingleCV = (noteValue % 12) + 1; // Cx maps to A1
}
}
}
}
}
res |= fMotherboard.fPropStateSingleCV.storeValueToMotherboardOnUpdate(stateSingleCV);
// handle CV (bank)
TJBox_Float64 bankCV = previousState.fMotherboard.fPropBankCV.getValue();
if(!fMotherboard.fCVInBank.isConnected() ||
fMotherboard.fPropBankOverrideCV.isNotSameValue(previousState.fMotherboard.fPropBankOverrideCV))
{
// not connected or UI forced change => revert to no CV
bankCV = 0;
}
else
if(fMotherboard.fCVInBank.isNotSameValue(previousState.fMotherboard.fCVInBank)) // only when CV changes
{
TJBox_Float64 value = fMotherboard.fCVInBank.getValue();
switch(fMotherboard.fPropBankCVMapping.getValue())
{
case kBankCVMappingBipolar:
if(value <= -1.0)
bankCV = 1;
else
if(value < 0)
bankCV = 2;
else
if(value < 1.0)
bankCV = 3;
else
bankCV = 4;
break;
case kBankCVMappingUnipolar:
if(value < 0.25)
bankCV = 1;
else
if(value < 0.5)
bankCV = 2;
else
if(value < 0.75)
bankCV = 3;
else
bankCV = 4;
break;
case kBankCVMappingNote:
{
TJBox_Int32 note = JBox::toNote(value) % 12; // to bring back to 1 octave
if(note < 3) // Cx - Dx
bankCV = 1;
else
if(note < 6) // D#x - Fx
bankCV = 2;
else
if(note < 9) // F#x - G#x
bankCV = 3;
else
bankCV = 4; // Ax - Bx
}
break;
default:
JBOX_ASSERT_MESSAGE(true, "not reached");
}
}
res |=
fMotherboard.fPropBankCV.storeValueToMotherboardOnUpdate(bankCV);
}
if(res)
{
// compute state of switches
for (int i = static_cast<int>(kA1); i < static_cast<int>(kEnd); ++i)
{
SwitchedOutputState *output = fSwitchedOutputStates[i];
bool selected = isSelected(output);
fSelectedSwitches[i] = selected;
fSelectedAndConnectedSwitches[i] = selected && output->isConnected();
output->adjustGateOut(selected);
}
}
return res;
}
bool DeviceState::haveOutputsChanged(DeviceState const &previousState)
{
for (int i = static_cast<int>(kA1); i < static_cast<int>(kEnd); ++i)
{
if(fSelectedAndConnectedSwitches[i] != previousState.fSelectedAndConnectedSwitches[i])
return true;
}
return false;
}
//------------------------------------------------------------------------
// DeviceState::writeAudio
//------------------------------------------------------------------------
void DeviceState::writeAudio(StereoAudioBuffer &iAudioInputBuffer)
{
for(int i = static_cast<int>(kA1); i < static_cast<int>(kEnd); ++i)
{
SwitchedOutputState *output = fSwitchedOutputStates[i];
if(fSelectedAndConnectedSwitches[i])
output->writeAudio(iAudioInputBuffer);
}
}
//------------------------------------------------------------------------
// DeviceState::writeAudio
//------------------------------------------------------------------------
void DeviceState::writeAudio(StereoAudioBuffer &iAudioInputBuffer,
DeviceState const &previousState,
XFade<kBatchSize> const &iXFade)
{
for(int i = static_cast<int>(kA1); i < static_cast<int>(kEnd); ++i)
{
SwitchedOutputState *output = fSwitchedOutputStates[i];
if(fSelectedAndConnectedSwitches[i])
{
// no cross-fading (switch was on and remained on)
if(previousState.fSelectedAndConnectedSwitches[i])
output->writeAudio(iAudioInputBuffer);
else
{
// cross-fading from 0 to iAudioInputBuffer
StereoAudioBuffer buf;
buf.clear();
buf.xFade(iXFade, iAudioInputBuffer, buf);
output->writeAudio(buf);
}
}
else
{
if(previousState.fSelectedAndConnectedSwitches[i])
{
// cross-fading from iAudioInputBuffer to 0
StereoAudioBuffer buf;
buf.clear();
buf.xFade(iXFade, buf, iAudioInputBuffer);
output->writeAudio(buf);
}
else
{
// nothing to do: switch was off and remained off
}
}
}
}
| 29.27037 | 127 | 0.60863 | pongasoft |
51f3e9c16b4dc8c64a4cd66aa775132370159315 | 1,149 | cpp | C++ | cpp/functionoverloading.cpp | chathu1996/hacktoberfest2020 | eaf64ac051709984cde916259e90cb24213b5c2f | [
"MIT"
] | 71 | 2020-10-06T05:53:59.000Z | 2021-11-27T03:14:42.000Z | cpp/functionoverloading.cpp | chathu1996/hacktoberfest2020 | eaf64ac051709984cde916259e90cb24213b5c2f | [
"MIT"
] | 92 | 2020-10-05T19:18:14.000Z | 2021-10-09T04:35:16.000Z | cpp/functionoverloading.cpp | chathu1996/hacktoberfest2020 | eaf64ac051709984cde916259e90cb24213b5c2f | [
"MIT"
] | 572 | 2020-10-05T20:11:28.000Z | 2021-10-10T16:28:29.000Z | #include<iostream.h>
#include<conio.h>
void area(int,int);
void area(float);
void area(int);
void area(float,float);
void main()
{ clrscr();
int ch=0,s,b,l;
float h,ba,r;
do
{
cout<<"Enter your choice\n";
cout<<"1.Rectangle \n2.Circle \n3.Square \n4.Triangle";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\nEnter Length and Breadth of Rectangle "<<endl;
cin>>l>>b;
area(l,b);
break;
case 2:
cout<<"\nEnter Radius of Circle "<<endl;
cin>>r;
area(r);
break;
case 3:
cout<<"\nEnter Side of Square "<<endl;
cin>>s;
area(s);
break;
case 4:
cout<<"\nEnter Base and Hieght of Triangle "<<endl;
cin>>ba>>h;
area(ba,h);
break;
default:cout<<"\nWrong choice";
}
}while(ch>0&&ch<5);
getch();
}
void area(int l,int b)
{int a;
a=l*b;
cout<<"\nArea of Rectangle =>"<<a<<endl;
}
void area(float r)
{float a;
a=3.14*r*r;
cout<<"\nArea of Circle =>"<<a<<endl;
}
void area(int s)
{int a;
a=s*s;
cout<<"\nArea of Square =>"<<a<<endl;
}
void area(float b,float h)
{float a;
a=(b*h)/2;
cout<<"\nArea of Triangle =>"<<a<<endl;
}
| 16.897059 | 60 | 0.553525 | chathu1996 |
51f5e616d09849a78be384d0b82a56cbceaef6c3 | 3,769 | hpp | C++ | crit_crauser.hpp | kaini/sssp-simulation | 0ee9cefb9b5d3a79c59eedd44092cd0401e99581 | [
"MIT"
] | null | null | null | crit_crauser.hpp | kaini/sssp-simulation | 0ee9cefb9b5d3a79c59eedd44092cd0401e99581 | [
"MIT"
] | null | null | null | crit_crauser.hpp | kaini/sssp-simulation | 0ee9cefb9b5d3a79c59eedd44092cd0401e99581 | [
"MIT"
] | null | null | null | #pragma once
#include "criteria.hpp"
#include "dijkstra.hpp"
#include "graph.hpp"
#include "stringy_enum.hpp"
#include <boost/heap/pairing_heap.hpp>
#include <unordered_set>
namespace sssp {
// Implements Crauser's IN criteria. Additionally instead of using the minimal edges,
// with dynamic=true, one can use the minimal non-settled edge.
class crauser_in : public criteria {
public:
crauser_in(const sssp::graph* graph, size_t start_node, bool dynamic);
virtual void relaxable_nodes(todo_output& output) const override;
virtual void changed_predecessor(size_t node, size_t predecessor, double distance) override;
virtual void relaxed_node(size_t node) override;
virtual bool is_complete() const override { return true; }
bool dynamic() const { return m_dynamic; }
private:
struct node_info;
struct node_info_compare_distance {
bool operator()(const node_info* a, const node_info* b) const;
};
// threshold(n) = tentative(n) - min{ cost of incmoing edges (not settled if dynamic) }
// Called "i" in the paper.
struct node_info_compare_threshold {
bool operator()(const node_info* a, const node_info* b) const;
};
using distance_queue = boost::heap::pairing_heap<node_info*, boost::heap::compare<node_info_compare_distance>>;
using threshold_queue = boost::heap::pairing_heap<node_info*, boost::heap::compare<node_info_compare_threshold>>;
struct node_info {
node_info(const sssp::graph& g, size_t index);
size_t index;
std::vector<edge_info> incoming;
double tentative_distance = INFINITY;
bool settled = false;
distance_queue::handle_type distance_queue_handle;
threshold_queue::handle_type threshold_queue_handle;
double threshold() const;
};
bool m_dynamic;
node_map<node_info> m_node_info;
distance_queue m_distance_queue;
threshold_queue m_threshold_queue;
};
// Implements Crauser's OUT criteria. Additionally instead of using the minimal edges,
// with dynamic=true, one can use the minimal non-settled edge.
class crauser_out : public criteria {
public:
crauser_out(const sssp::graph* graph, size_t start_node, bool dynamic);
virtual void relaxable_nodes(todo_output& output) const override;
virtual void changed_predecessor(size_t node, size_t predecessor, double distance) override;
virtual void relaxed_node(size_t node) override;
virtual bool is_complete() const override { return true; }
bool dynamic() const { return m_dynamic; }
private:
struct node_info;
struct node_info_compare_distance {
bool operator()(const node_info* a, const node_info* b) const;
};
// threshold(n) = tentative(n) + min{ outgoing edge (not settled if dynamic) }
// Called "L" in the paper (to be exact this are the values of all nodes, not the final L)
struct node_info_compare_threshold {
bool operator()(const node_info* a, const node_info* b) const;
};
using distance_queue = boost::heap::pairing_heap<node_info*, boost::heap::compare<node_info_compare_distance>>;
using threshold_queue = boost::heap::pairing_heap<node_info*, boost::heap::compare<node_info_compare_threshold>>;
struct node_info {
node_info(const sssp::graph& g, size_t index);
size_t index;
std::vector<edge_info> outgoing;
double tentative_distance = INFINITY;
bool settled = false;
distance_queue::handle_type distance_queue_handle;
threshold_queue::handle_type threshold_queue_handle;
double threshold() const;
};
bool m_dynamic;
node_map<node_info> m_node_info;
distance_queue m_distance_queue;
threshold_queue m_threshold_queue;
};
} // namespace sssp | 38.85567 | 117 | 0.71982 | kaini |
51f619232167475c8482b0576d4880740bbb23b6 | 25,377 | cxx | C++ | admin/netui/common/src/reg/reg/regval.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/netui/common/src/reg/reg/regval.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/netui/common/src/reg/reg/regval.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /**********************************************************************/
/** Microsoft Windows/NT **/
/** Copyright(c) Microsoft Corp., 1991 **/
/**********************************************************************/
/*
REGVAL.CXX
Win32 Registry class implementation
Value handline member functions.
FILE HISTORY:
DavidHov 4/25/92 Created
DavidHov 6/1/92 Reworked for UNICODE and
title removal; incomplete.
terryk 11/4/92 Added QueryValue for Binary data
*/
#define INCL_NETERRORS
#define INCL_DOSERRORS
#define INCL_NETLIB
#include "lmui.hxx"
#include "base.hxx"
#include "string.hxx"
#include "uiassert.hxx"
#include "uitrace.hxx"
#include "uatom.hxx" // Atom Management defs
#include "regkey.hxx" // Registry defs
const int RM_MAXVALUENUM = 10 ; // Default numeric value length
const int RM_MAXVALUESTR = 300 ; // Default string value length
const int RM_MAXVALUEBIN = 300 ; // Default Binary value length
const int cchPad = 2 ; // Length to pad strings
/*******************************************************************
NAME: REG_KEY::QueryKeyValueString
SYNOPSIS: Worker function for all string query functions
ENTRY:
EXIT:
RETURNS:
NOTES: If the incoming type is REG_EXPAND_SZ and the
underlying queried type is also, the value is expanded.
A REG_SZ is also accepted in this case.
Otherwise, it's a type mismatch.
HISTORY: DavidHov 5/1/92 Created
DavidHov 5/17/92 Added REG_EXPAND_SZ support.
********************************************************************/
APIERR REG_KEY :: QueryKeyValueString
( const TCHAR * pszValueName, // Name of value
TCHAR * * ppszResult, // Location to store result
NLS_STR * pnlsResult, // or, NLS_STR to update
DWORD * pdwTitle, // location to receive title index
LONG cchMaxSize, // Maximum size allowed
LONG * pcchSize, // Size of result (no terminator)
DWORD dwType ) // Value type expected
{
APIERR err = 0 ;
TCHAR achValueData[ RM_MAXVALUESTR ] ;
REG_VALUE_INFO_STRUCT rviStruct ;
INT cchLen = 0,
cchBufferSize = 0 ;
TCHAR * pszResult = NULL,
* pszBuffer = NULL,
* pszEos = NULL,
* pszSource = NULL ;
rviStruct.nlsValueName = pszValueName ;
rviStruct.ulTitle = 0 ;
rviStruct.ulType = 0 ;
if ( pnlsResult != NULL && ppszResult != NULL )
{
err = ERROR_INVALID_PARAMETER ;
}
else
if ( rviStruct.nlsValueName.QueryError() )
{
err = rviStruct.nlsValueName.QueryError() ;
}
else
if ( cchMaxSize == 0 ) // Unknown size?
{
// Query the key to determine the largest possible length necessary
REG_KEY_INFO_STRUCT rkiStruct ;
if ( rkiStruct.nlsName.QueryError()
|| rkiStruct.nlsClass.QueryError() )
{
err = ERROR_NOT_ENOUGH_MEMORY ;
}
else
if ( (err = QueryInfo( & rkiStruct )) == 0 )
{
cchBufferSize = rkiStruct.ulMaxValueLen / sizeof (TCHAR) ;
}
}
else
if ( cchMaxSize > sizeof achValueData )
{
// Known size, but it's larger than the automatic array
cchBufferSize = cchMaxSize ;
} // else, value will fit into automatic array
if ( err )
return err ;
if ( cchBufferSize )
{
// We need to allocate a buffer
pszBuffer = new TCHAR [cchBufferSize + cchPad] ;
if ( pszBuffer == NULL )
{
return ERROR_NOT_ENOUGH_MEMORY ;
}
// Store the BYTE pointer and BYTE count of the buffer
rviStruct.pwcData = (BYTE *) pszBuffer ;
rviStruct.ulDataLength = cchBufferSize * sizeof (TCHAR) ;
}
else // Use the automatic array for temporary storage.
{
rviStruct.pwcData = (BYTE *) achValueData ;
rviStruct.ulDataLength = ((sizeof achValueData) - cchPad) * sizeof (TCHAR) ;
}
if ( (err = QueryValue( & rviStruct )) == 0 )
{
// Zero-terminate the value data.
pszSource = (TCHAR *) rviStruct.pwcData ;
pszEos = (TCHAR *) (rviStruct.pwcData+rviStruct.ulDataLengthOut) ;
*pszEos = 0 ;
cchLen = (INT)(pszEos - pszSource) ;
if ( pcchSize )
*pcchSize = cchLen ;
// If it wasn't the requested type, give an error. Handle
// the special case of a request for a REG_EXPAND_SZ but
// a REG_SZ result.
if ( (rviStruct.ulType != dwType)
&& ( !(rviStruct.ulType == REG_SZ && dwType == REG_EXPAND_SZ) ) )
{
err = ERROR_INVALID_PARAMETER ;
}
}
// Expand REG_MULTI_SZ if necessary.
if ( err == 0 && rviStruct.ulType == REG_EXPAND_SZ )
{
DWORD cchExpand,
cchExpanded = cchLen * 2 ;
TCHAR * pszExpanded = NULL ;
do
{
// NTRAID#NTBUG9-577099-2002/03/08-artm Prefast: need to use delete [].
// Allocated with new [] (see next line of code); use
// delete [] to avoid memory leak.
// This function is a little convoluted; it probably warrants
// a scan to see if there are any subtle memory leaks not
// detected by prefast.
delete pszExpanded ;
pszExpanded = new TCHAR [cchExpand = cchExpanded] ;
if ( pszExpanded == NULL )
{
err = ERROR_NOT_ENOUGH_MEMORY ;
break ;
}
cchExpanded = ::ExpandEnvironmentStrings( pszSource,
pszExpanded,
cchExpand ) ;
}
while ( cchExpanded > cchExpand ) ;
// Replace the older buffer, if any, with the new one, if any.
delete pszBuffer ;
pszBuffer = pszSource = pszExpanded ;
}
if ( err == 0 )
{
if ( ppszResult )
{
// They want TCHAR output. See if we've already allocated
// a buffer; if so, use it, otherwise make one.
if ( pszBuffer )
{
*ppszResult = pszBuffer ;
pszBuffer = NULL ; // Suppress deletion of buffer
}
else
if ( (pszResult = new TCHAR [cchLen + cchPad]) != NULL )
{
::strcpyf( pszResult, pszSource ) ;
*ppszResult = pszResult ;
}
else
{
err = ERROR_NOT_ENOUGH_MEMORY ;
}
}
else
{
// They want NLS_STR output
*pnlsResult = pszSource ;
err = pnlsResult->QueryError() ;
}
}
// NTRAID#NTBUG9-577099-2002/03/08-artm Prefast: use delete [].
// Allocated with new [], use delete [].
delete pszBuffer ;
return err ;
}
/*******************************************************************
NAME: REG_KEY::SetKeyValueString
SYNOPSIS: Worker function for value string handling
ENTRY:
EXIT:
RETURNS:
NOTES: If lcbSize == 0, compute the length of the string
using ::strlenf().
HISTORY:
********************************************************************/
APIERR REG_KEY :: SetKeyValueString
( const TCHAR * pszValueName, // Name of value
const TCHAR * pszValue, // Data to be applied
DWORD dwTitle, // Title index (optional)
LONG lcbSize, // Size of string
DWORD dwType ) // Type
{
REG_VALUE_INFO_STRUCT rviStruct ;
rviStruct.pwcData = (BYTE *) pszValue ;
rviStruct.ulDataLength = lcbSize == 0
? (::strlenf( pszValue ) + 1)
: lcbSize ;
rviStruct.ulDataLength *= sizeof (TCHAR) ;
rviStruct.nlsValueName = pszValueName ;
rviStruct.ulTitle = 0 ;
rviStruct.ulType = dwType ;
return rviStruct.nlsValueName.QueryError()
? rviStruct.nlsValueName.QueryError()
: SetValue( & rviStruct ) ;
}
/*******************************************************************
NAME: REG_KEY::QueryKeyValueBinary
SYNOPSIS: Worker function for all binary query functions
If "*ppbResult" is non-NULL, this value is used
for the result buffer; its size is assumed to be
"cbMaxSize".
If "cbMaxSize" is zero, key is queried to find
largest value.
ENTRY:
EXIT:
RETURNS: APIERR
HISTORY: DavidHov 5/1/92 Created
DavidHov 5/17/92 Added REG_EXPAND_SZ support.
terryk 11/4/92 Changed it to QueryKeyValueBinary
********************************************************************/
APIERR REG_KEY :: QueryKeyValueBinary
( const TCHAR * pszValueName, // Name of value
BYTE * * ppbResult, // Location to store result
LONG * pcbSize, // Size of result (no terminator)
LONG cbMaxSize, // Maximum size allowed
DWORD * pdwTitle, // location to receive title index
DWORD dwType ) // Value type expected
{
APIERR err = 0 ;
REG_VALUE_INFO_STRUCT rviStruct ;
INT cbBufferSize = 0 ;
BYTE * pbBuffer = NULL;
rviStruct.nlsValueName = pszValueName ;
rviStruct.ulTitle = 0 ;
rviStruct.ulType = 0 ;
do
{
if ( ppbResult == NULL )
{
err = ERROR_INVALID_PARAMETER ;
break ;
}
if ( err = rviStruct.nlsValueName.QueryError() )
{
break;
}
if ( (cbBufferSize = cbMaxSize) == 0 ) // Unknown size?
{
// Query the key to determine the largest possible length necessary
REG_KEY_INFO_STRUCT rkiStruct ;
if ( rkiStruct.nlsName.QueryError()
|| rkiStruct.nlsClass.QueryError() )
{
err = ERROR_NOT_ENOUGH_MEMORY ;
}
else
if ( (err = QueryInfo( & rkiStruct )) == 0 )
{
cbBufferSize = rkiStruct.ulMaxValueLen ;
}
if ( err )
break ;
}
// See if we need to allocate a buffer. Use the size given by the user
// if present.
if ( *ppbResult ) // Does the pointer point somewhere?
{
pbBuffer = *ppbResult ; // Pick up user's pointer.
}
else // We have to allocate a buffer
if ( (pbBuffer = new BYTE [cbBufferSize]) == NULL )
{
err = ERROR_NOT_ENOUGH_MEMORY ;
break ;
}
// Store the BYTE pointer and BYTE count of the buffer
rviStruct.pwcData = pbBuffer ;
rviStruct.ulDataLength = cbBufferSize * sizeof (BYTE) ;
if ( err = QueryValue( & rviStruct ) )
{
break ;
}
if ( rviStruct.ulType != dwType )
{
err = ERROR_INVALID_PARAMETER ;
break ;
}
if ( *ppbResult == NULL )
{
// Give the caller the allocated buffer.
*ppbResult = pbBuffer ;
}
// Report eh size read.
*pcbSize = rviStruct.ulDataLengthOut ;
}
while ( FALSE ) ;
if ( err && pbBuffer != *ppbResult )
{
// NTRAID#NTBUG9-577099-2002/03/08-artm Prefast: use delete []
// allocated with []; use delete [] to avoid memory leak
delete pbBuffer ;
}
return err ;
}
/*******************************************************************
NAME: REG_KEY::SetKeyValueBinary
SYNOPSIS: Worker function for value binary handling
ENTRY:
EXIT:
RETURNS:
HISTORY:
********************************************************************/
APIERR REG_KEY :: SetKeyValueBinary
( const TCHAR * pszValueName, // Name of value
const BYTE * pbValue, // Data to be applied
LONG lcbSize, // Size of binary
DWORD dwTitle, // Title index (optional)
DWORD dwType ) // Type
{
REG_VALUE_INFO_STRUCT rviStruct ;
rviStruct.pwcData = (BYTE *) pbValue ;
rviStruct.ulDataLength = lcbSize ;
rviStruct.nlsValueName = pszValueName ;
rviStruct.ulTitle = 0 ;
rviStruct.ulType = dwType ;
return rviStruct.nlsValueName.QueryError()
? rviStruct.nlsValueName.QueryError()
: SetValue( & rviStruct ) ;
}
/*******************************************************************
NAME: REG_KEY::QueryKeyValueLong
SYNOPSIS: Worker function for REG_DWORD handling
ENTRY:
EXIT:
RETURNS:
NOTES:
HISTORY:
********************************************************************/
APIERR REG_KEY :: QueryKeyValueLong
( const TCHAR * pszValueName, // Name of value
LONG * pnResult, // Location to store result
DWORD * pdwTitle ) // location to receive title index
{
APIERR err ;
BYTE abValueData[ RM_MAXVALUENUM ] ;
REG_VALUE_INFO_STRUCT rviStruct ;
TCHAR * pszResult = NULL ;
rviStruct.pwcData = abValueData ;
rviStruct.ulDataLength = sizeof abValueData ;
rviStruct.nlsValueName = pszValueName ;
rviStruct.ulTitle = 0 ;
rviStruct.ulType = 0 ;
if ( rviStruct.nlsValueName.QueryError() )
{
err = rviStruct.nlsValueName.QueryError() ;
}
else
if ( (err = QueryValue( & rviStruct )) == 0 )
{
if ( rviStruct.ulType != REG_DWORD )
{
err = ERROR_INVALID_PARAMETER ;
}
else
{
*pnResult = *( (LONG *) abValueData ) ;
}
}
return err ;
}
/*******************************************************************
NAME: REG_KEY::SetKeyValueLong
SYNOPSIS: Worker function for REG_DWORD value setting
ENTRY:
EXIT:
RETURNS:
NOTES:
HISTORY:
********************************************************************/
APIERR REG_KEY :: SetKeyValueLong
( const TCHAR * pszValueName, // Name of value
LONG nNewValue, // Data to be applied
DWORD dwTitle ) // Title index (optional)
{
REG_VALUE_INFO_STRUCT rviStruct ;
rviStruct.pwcData = (BYTE *) & nNewValue ;
rviStruct.ulDataLength = sizeof nNewValue ;
rviStruct.nlsValueName = pszValueName ;
rviStruct.ulTitle = 0 ;
rviStruct.ulType = REG_DWORD ;
return rviStruct.nlsValueName.QueryError()
? rviStruct.nlsValueName.QueryError()
: SetValue( & rviStruct ) ;
}
/*******************************************************************
NAME: REG_KEY::QueryValue
SYNOPSIS: Query a single string value from the
Registry.
ENTRY:
EXIT:
RETURNS:
NOTES: If "fExpandSz" is TRUE, then a REG_EXPAND_SZ is
is allowed, and if found, expanded; REG_SZ will
also suffice.
HISTORY:
********************************************************************/
APIERR REG_KEY :: QueryValue (
const TCHAR * pszValueName,
NLS_STR * pnlsValue,
ULONG cchMax,
DWORD * pdwTitle,
BOOL fExpandSz )
{
LONG cchSize ;
return QueryKeyValueString( pszValueName,
NULL,
pnlsValue,
NULL,
cchMax ? cchMax : RM_MAXVALUESTR,
& cchSize,
fExpandSz ? REG_EXPAND_SZ : REG_SZ );
}
/*******************************************************************
NAME: REG_KEY::
SYNOPSIS:
ENTRY:
EXIT:
RETURNS:
NOTES:
HISTORY:
********************************************************************/
APIERR REG_KEY :: SetValue (
const TCHAR * pszValueName,
const NLS_STR * pnlsValue,
const DWORD * pdwTitle,
BOOL fExpandSz )
{
return SetKeyValueString( pszValueName,
pnlsValue->QueryPch(),
NULL,
0,
fExpandSz ? REG_EXPAND_SZ
: REG_SZ ) ;
}
/*******************************************************************
NAME: REG_KEY::QueryValue
SYNOPSIS: Query Binary value from the
Registry.
ENTRY:
EXIT:
RETURNS:
HISTORY:
********************************************************************/
APIERR REG_KEY :: QueryValue (
const TCHAR * pszValueName,
BYTE ** ppbByte,
LONG *pcbSize,
LONG cbMax,
DWORD * pdwTitle )
{
return QueryKeyValueBinary( pszValueName,
ppbByte,
pcbSize,
cbMax,
pdwTitle,
REG_BINARY );
}
/*******************************************************************
NAME: REG_KEY::
SYNOPSIS:
ENTRY:
EXIT:
RETURNS:
NOTES:
HISTORY:
********************************************************************/
APIERR REG_KEY :: SetValue (
const TCHAR * pszValueName,
const BYTE * pByte,
const LONG cbByte,
const DWORD * pdwTitle )
{
return SetKeyValueBinary( pszValueName,
pByte,
cbByte,
NULL,
REG_BINARY ) ;
}
/*******************************************************************
NAME: REG_KEY::
SYNOPSIS:
ENTRY:
EXIT:
RETURNS:
NOTES:
HISTORY:
********************************************************************/
APIERR REG_KEY :: QueryValue (
const TCHAR * pszValueName,
TCHAR * * ppchValue,
ULONG cchMax,
DWORD * pdwTitle,
BOOL fExpandSz )
{
LONG cchSize ;
return QueryKeyValueString( pszValueName,
ppchValue,
NULL,
NULL,
cchMax ? cchMax : RM_MAXVALUESTR,
& cchSize,
fExpandSz ? REG_EXPAND_SZ
: REG_SZ );
}
/*******************************************************************
NAME: REG_KEY::
SYNOPSIS:
ENTRY:
EXIT:
RETURNS:
NOTES:
HISTORY:
********************************************************************/
APIERR REG_KEY :: SetValue (
const TCHAR * pszValueName,
const TCHAR * pchValue,
ULONG cchLen, // BUGBUG: this parameter should be removed
const DWORD * pdwTitle,
BOOL fExpandSz )
{
return SetKeyValueString( pszValueName,
pchValue,
NULL,
0,
fExpandSz ? REG_EXPAND_SZ
: REG_SZ ) ;
}
/*******************************************************************
NAME: REG_KEY::
SYNOPSIS:
ENTRY:
EXIT:
RETURNS:
NOTES:
HISTORY:
********************************************************************/
// Query/Set numeric values
APIERR REG_KEY :: QueryValue (
const TCHAR * pszValueName,
DWORD * pdwValue,
DWORD * pdwTitle )
{
return QueryKeyValueLong( pszValueName,
(LONG *) pdwValue,
NULL ) ;
}
/*******************************************************************
NAME: REG_KEY::
SYNOPSIS:
ENTRY:
EXIT:
RETURNS:
NOTES:
HISTORY:
********************************************************************/
APIERR REG_KEY :: SetValue (
const TCHAR * pszValueName,
DWORD dwValue,
const DWORD * pdwTitle )
{
return SetKeyValueLong( pszValueName,
dwValue,
NULL ) ;
}
/*******************************************************************
NAME: REG_KEY::
SYNOPSIS:
ENTRY:
EXIT:
RETURNS:
NOTES:
HISTORY:
********************************************************************/
APIERR REG_KEY :: QueryValue (
const TCHAR * pszValueName,
STRLIST * * ppStrList,
DWORD * pdwTitle )
{
APIERR err = 0 ;
TCHAR * pszResult = NULL,
* pszNext = NULL,
* pszLast = NULL ;
LONG cchLen, cchNext ;
STRLIST * pStrList = NULL ;
do
{
pStrList = new STRLIST ;
if ( pStrList == NULL )
{
err = ERROR_NOT_ENOUGH_MEMORY ;
break ;
}
err = QueryKeyValueString( pszValueName,
& pszResult,
NULL,
NULL,
0, // Ask key for size of largest item
& cchLen,
REG_MULTI_SZ ) ;
if ( err )
break ;
for ( pszLast = pszNext = pszResult, cchNext = 0 ;
err == 0 && cchNext < cchLen ;
cchNext++, pszNext++ )
{
// BUGBUG: It appears that there's an extra delimiter
// on the returned data, resulting in a bogus final
// zero-length string. For now, skip it...
if ( *pszNext == 0 && pszLast < pszNext )
{
NLS_STR * pnlsNext = new NLS_STR( pszLast ) ;
if ( pnlsNext == NULL )
{
err = ERROR_NOT_ENOUGH_MEMORY ;
}
else
if ( (err = pnlsNext->QueryError()) == 0 )
{
err = pStrList->Append( pnlsNext ) ;
}
}
if ( *pszNext == 0 )
{
pszLast = pszNext + 1 ;
}
}
}
while ( FALSE ) ;
if ( err == 0 )
{
*ppStrList = pStrList ;
}
else
{
delete pStrList ;
}
delete pszResult ;
return err ;
}
#ifndef UNICODE
extern "C"
{
LONG emptyMultiSz ( HKEY hKey, const CHAR * pszValueName )
{
BYTE bData [2] ;
return ::RegSetValueExA( hKey,
pszValueName,
0,
REG_MULTI_SZ,
bData,
0 );
}
}
#endif
/*******************************************************************
NAME: REG_KEY::
SYNOPSIS:
ENTRY:
EXIT:
RETURNS:
NOTES:
HISTORY:
********************************************************************/
APIERR REG_KEY :: SetValue (
const TCHAR * pszValueName,
const STRLIST * pStrList,
const DWORD * pdwTitle )
{
LONG cchLen ;
INT cStrs ;
NLS_STR * pnlsNext ;
TCHAR * pchBuffer = NULL ;
APIERR err ;
{
ITER_STRLIST istrList( *((STRLIST *) pStrList) ) ;
for ( cStrs = 0, cchLen = 0 ; pnlsNext = istrList.Next() ; cStrs++ )
{
cchLen += pnlsNext->QueryTextLength() + 1 ;
}
}
#ifndef UNICODE
if ( cStrs == 0 )
{
return emptyMultiSz( _hKey, pszValueName ) ;
}
#endif
pchBuffer = new TCHAR [cchLen+cchPad] ;
if ( pchBuffer == NULL )
{
err = ERROR_NOT_ENOUGH_MEMORY ;
}
else
{
ITER_STRLIST istrList( *((STRLIST *) pStrList) ) ;
TCHAR * pchNext = pchBuffer ;
for ( ; pnlsNext = istrList.Next() ; )
{
::strcpyf( pchNext, pnlsNext->QueryPch() ) ;
pchNext += pnlsNext->QueryTextLength() ;
*pchNext++ = 0 ;
}
*pchNext++ = 0 ;
*pchNext = 0 ;
err = SetKeyValueString( pszValueName,
pchBuffer,
0,
cchLen+1,
REG_MULTI_SZ ) ;
}
// NTRAID#NTBUG9-577099-2002/03/08-artm Prefast: use delete [].
// Allocated with new []; use delete [] to avoid memory leak.
delete pchBuffer ;
return err ;
}
// End of REGVAL.CXX
| 25.842159 | 85 | 0.447571 | npocmaka |
51f675ab28f07d980f2f0c9d3af113cc9ce3ce67 | 451 | cpp | C++ | solutions/1010.cpp | tdakhran/leetcode | ed680059661faae32857eaa791ca29c1d9c16120 | [
"MIT"
] | null | null | null | solutions/1010.cpp | tdakhran/leetcode | ed680059661faae32857eaa791ca29c1d9c16120 | [
"MIT"
] | null | null | null | solutions/1010.cpp | tdakhran/leetcode | ed680059661faae32857eaa791ca29c1d9c16120 | [
"MIT"
] | null | null | null | #include <array>
#include <vector>
class Solution {
public:
int numPairsDivisibleBy60(std::vector<int>& time) {
std::array<int, 60> durations = {0};
for (auto t : time) {
++durations[t % 60];
}
int result = (durations[0] - 1) * durations[0] / 2 +
(durations[30] - 1) * durations[30] / 2;
for (size_t t = 1; t < 30; ++t) {
result += durations[t] * durations[60 - t];
}
return result;
}
};
| 23.736842 | 57 | 0.534368 | tdakhran |
51fa9dbde53d3c04cf97e87eca10e5da112e306c | 2,857 | cpp | C++ | source/src/multilanguage/qrlanguager.cpp | Qters/QrCommon | 0e90365c1ad58c63ff17c259bb298f27c78d7d91 | [
"Apache-2.0"
] | null | null | null | source/src/multilanguage/qrlanguager.cpp | Qters/QrCommon | 0e90365c1ad58c63ff17c259bb298f27c78d7d91 | [
"Apache-2.0"
] | null | null | null | source/src/multilanguage/qrlanguager.cpp | Qters/QrCommon | 0e90365c1ad58c63ff17c259bb298f27c78d7d91 | [
"Apache-2.0"
] | null | null | null | #include "qrlanguager.h"
#include <algorithm>
#include <QTranslator>
#include <qapplication.h>
#include <QtCore/qdebug.h>
#include "qrutf8.h"
NS_QRCOMMON_BEGIN
class QrLanguagerPrivate
{
QR_DECLARE_PUBLIC(QrLanguager)
public:
int curLanaugeIndex = -1;
QVector<QrLanguagData> languageDatas;
QTranslator translator;
public:
QrLanguagerPrivate(QrLanguager *q) : q_ptr(q) {}
bool loadLanguage(const QString &qmFileName);
};
bool QrLanguagerPrivate::loadLanguage(const QString& qmFileName)
{
qApp->removeTranslator(&translator);
auto absFileName = QApplication::applicationDirPath() + "/translations/" + qmFileName;
if(translator.load(absFileName)){
return qApp->installTranslator(&translator);
} else {
qDebug() << "load language fail, " << absFileName;
}
return false;
}
NS_QRCOMMON_END
///////////////////////////////////////////////////////
USING_NS_QRCOMMON;
QR_SINGLETON_IMPLEMENT(QrLanguager)
QrLanguager::QrLanguager()
: QrSingleton<QrLanguager>("qrlanguager"),
d_ptr(new QrLanguagerPrivate(this))
{
}
void QrLanguager::initLanguages(const QVector<QrLanguagData> &languageDatas)
{
Q_D(QrLanguager);
d->languageDatas = languageDatas;
if(d->languageDatas.isEmpty()) {
d->curLanaugeIndex = -1;
} else {
d->curLanaugeIndex = 0;
}
}
bool QrLanguager::setLanguageByName(const QString& display)
{
Q_D(QrLanguager);
auto find = std::find_if(d->languageDatas.begin(), d->languageDatas.end(),
[display](QrLanguagData languageData){
return languageData.display == display;
});
if(d->languageDatas.end() == find) {
qDebug() << "fail to set language, could'nt find by " << display;
return false;
}
return d->loadLanguage(find->qmFileName);
}
bool QrLanguager::setLanaugeByIndex(int index)
{
Q_D(QrLanguager);
auto find = std::find_if(d->languageDatas.begin(), d->languageDatas.end(),
[index](QrLanguagData languageData){
return languageData.index == index;
});
if(d->languageDatas.end() == find) {
qDebug() << "fail to set language, could'nt find by " << index;
return false;
}
return d->loadLanguage(find->qmFileName);
}
QrLanguagData QrLanguager::curLanguage() const
{
Q_D(const QrLanguager);
if(d->curLanaugeIndex >= d->languageDatas.count()) {
qDebug() << "language index is unvalid.";
return QrLanguagData();
}
return d->languageDatas.at(d->curLanaugeIndex);
}
QStringList QrLanguager::getDisplayNames() const
{
QStringList names;
Q_D(const QrLanguager);
std::for_each(d->languageDatas.begin(),
d->languageDatas.end(),
[&names](QrLanguagData languageData){
names.push_back(languageData.display);
});
return names;
}
| 23.808333 | 90 | 0.652083 | Qters |
51fb4572055fdce043c3f3d02f02452838b0656e | 2,592 | cpp | C++ | src/scene.cpp | martin-pr/embree_viewer | 4e382f0352a8b76ff5d955024b5f56f1855d20c1 | [
"MIT"
] | 23 | 2018-03-15T00:02:53.000Z | 2022-03-19T17:44:40.000Z | src/scene.cpp | martin-pr/embree_viewer | 4e382f0352a8b76ff5d955024b5f56f1855d20c1 | [
"MIT"
] | null | null | null | src/scene.cpp | martin-pr/embree_viewer | 4e382f0352a8b76ff5d955024b5f56f1855d20c1 | [
"MIT"
] | 5 | 2019-03-06T06:48:44.000Z | 2021-03-21T16:56:30.000Z | #include "scene.h"
#include <cmath>
#include <iostream>
#include <limits>
#include <embree3/rtcore_ray.h>
#include "mesh.h"
Scene::SceneHandle::SceneHandle(Device& device) {
m_scene = rtcNewScene(device);
rtcSetSceneFlags(m_scene, RTC_SCENE_FLAG_COMPACT);
}
Scene::SceneHandle::~SceneHandle() {
rtcReleaseScene(m_scene);
}
Scene::SceneHandle::operator RTCScene& () {
return m_scene;
}
Scene::SceneHandle::operator const RTCScene& () const {
return m_scene;
}
////////////
Scene::Scene() : m_scene(new SceneHandle(m_device)) {
}
Scene::~Scene() {
}
Scene::Scene(Scene&& s) : m_device(s.m_device), m_scene(std::move(s.m_scene)) {
}
Scene& Scene::operator = (Scene&& s) {
if(&s != this) {
m_device = s.m_device;
m_scene = std::move(s.m_scene);
}
return *this;
}
unsigned Scene::addMesh(Mesh&& geom) {
unsigned int geomID = rtcAttachGeometry(*m_scene, geom.geom());
rtcCommitGeometry(geom.geom());
return geomID;
}
unsigned Scene::addInstance(const Scene& s, const Mat4& _tr) {
RTCGeometry instance = rtcNewGeometry(m_device, RTC_GEOMETRY_TYPE_INSTANCE);
rtcSetGeometryInstancedScene(instance, *s.m_scene);
unsigned int geomID = rtcAttachGeometry(*m_scene, instance);
rtcReleaseGeometry(instance);
Mat4 tr = _tr;
// tr.transpose();
rtcSetGeometryTransform(instance, 0, RTC_FORMAT_FLOAT4X4_COLUMN_MAJOR, tr.m);
rtcCommitGeometry(instance);
return geomID;
}
void Scene::commit() {
rtcCommitScene(*m_scene);
}
Vec3 Scene::renderPixel(const Ray& r) const {
RTCRayHit rayhit = trace(r);
Vec3 color{0, 0, 0};
if(rayhit.hit.geomID != RTC_INVALID_GEOMETRY_ID) {
//color = Vec3{(float)(rayhit.hit.geomID & 1), (float)((rayhit.hit.geomID >> 1) & 1), (float)((rayhit.hit.geomID >> 2) & 1)};
color = Vec3(1, 1, 1);
Vec3 norm(rayhit.hit.Ng_x, rayhit.hit.Ng_y, rayhit.hit.Ng_z);
norm.normalize();
const float d = std::abs(r.direction.dot(norm));
color.x *= d;
color.y *= d;
color.z *= d;
}
return color;
}
RTCRayHit Scene::trace(const Ray& r) const {
RTCIntersectContext context;
rtcInitIntersectContext(&context);
RTCRayHit rayhit;
rayhit.ray.org_x = r.origin.x;
rayhit.ray.org_y = r.origin.y;
rayhit.ray.org_z = r.origin.z;
rayhit.ray.tnear = 0;
rayhit.ray.tfar = std::numeric_limits<float>::infinity();
rayhit.ray.dir_x = r.direction.x;
rayhit.ray.dir_y = r.direction.y;
rayhit.ray.dir_z = r.direction.z;
rayhit.ray.time = 0;
rayhit.ray.mask = 0xFFFFFFFF;
rayhit.ray.id = 0;
rayhit.ray.flags = 0;
rayhit.hit.geomID = RTC_INVALID_GEOMETRY_ID;
rtcIntersect1(*m_scene, &context, &rayhit);
return rayhit;
}
| 20.25 | 127 | 0.697145 | martin-pr |
51fc876792446d7d9bed7541049214da83741401 | 2,777 | cpp | C++ | ConsoleEditor/libeditor/HtmlDocumentFormatter.cpp | AlK2x/OOD | 7ce78cfa7708978483f67642d93a8bc2873c2285 | [
"MIT"
] | null | null | null | ConsoleEditor/libeditor/HtmlDocumentFormatter.cpp | AlK2x/OOD | 7ce78cfa7708978483f67642d93a8bc2873c2285 | [
"MIT"
] | 5 | 2016-03-20T20:28:52.000Z | 2016-06-30T18:17:42.000Z | ConsoleEditor/libeditor/HtmlDocumentFormatter.cpp | AlK2x/OOD | 7ce78cfa7708978483f67642d93a8bc2873c2285 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "HtmlDocumentFormatter.h"
namespace fs = boost::filesystem;
CHtmlDocumentFormatter::CHtmlDocumentFormatter(CTempFolder const & tempFolder)
:m_tempFolder(tempFolder)
{
m_htmlEntities.push_back({ '&', "&" });
m_htmlEntities.push_back({ '<', "<" });
m_htmlEntities.push_back({ '>', ">" });
m_htmlEntities.push_back({ '"', """ });
}
std::string CHtmlDocumentFormatter::EscapeHtmlEntities(const std::string & str)
{
std::string escaped = str;
for (auto const & htmlEntity : m_htmlEntities)
{
std::string::size_type pos = escaped.find_first_of(htmlEntity.first);
while (pos != std::string::npos)
{
escaped.replace(pos, 1, htmlEntity.second);
pos = escaped.find_first_of(htmlEntity.first, pos + htmlEntity.second.size());
}
}
return escaped;
}
void CHtmlDocumentFormatter::CreateDocumentFilesImpl(IDocument const & document, std::string const & path)
{
fs::path p{ path };
fs::path parentPath(p.parent_path());
fs::file_status s = fs::status(p);
if (!fs::exists(s) && !fs::is_directory(p))
{
fs::create_directory(parentPath);
}
fs::path imagePath(parentPath);
imagePath /= m_tempFolder.GetImagePath();
if (!fs::is_directory(imagePath))
{
fs::create_directory(imagePath);
}
else
{
fs::remove_all(imagePath);
fs::create_directory(imagePath);
}
for (size_t i = 0; i < document.GetItemsCount(); ++i)
{
CConstDocumentItem item = document.GetItem(i);
std::shared_ptr<const IImage> m_image = item.GetImage();
if (m_image != nullptr)
{
fs::path from = m_tempFolder.GetPath();
from /= m_image->GetPath();
fs::path absoluteImagePath(parentPath);
absoluteImagePath /= m_image->GetPath();
fs::copy_file(from, absoluteImagePath, fs::copy_option::overwrite_if_exists);
}
}
}
void CHtmlDocumentFormatter::FormatHeader(IDocument const & document, std::ostream & out)
{
std::string escapedTitle = EscapeHtmlEntities(document.GetTitle());
out << boost::format{ R"(
<!DOCTYPE html>
<html>
<head>
<title>%1%</title>
</head>
<body>)" } % escapedTitle;
}
void CHtmlDocumentFormatter::FormatDocumentItem(CConstDocumentItem const & item, size_t position, std::ostream & out)
{
(void)position;
std::shared_ptr<const IImage> imagePtr = item.GetImage();
std::shared_ptr<const IParagraph> paragraphPtr = item.GetParagraph();
if (paragraphPtr != nullptr)
{
out << boost::format(R"(<p>%1%</p>)") % EscapeHtmlEntities(paragraphPtr->GetText()) << std::endl;
}
if (imagePtr != nullptr)
{
out << boost::format(R"(<img height="%1%" width="%2%" src="%3%" />)")
% imagePtr->GetWidth()
% imagePtr->GetHeight()
% imagePtr->GetPath().string()
<< std::endl;
}
}
void CHtmlDocumentFormatter::FormatFooter(std::ostream & out)
{
out << R"(
</body>
</html>)";
}
| 25.245455 | 117 | 0.685992 | AlK2x |
a4027077b1090bed4e9ed4dee30eea27e3795b1c | 1,419 | cpp | C++ | test/language/choice_types/cpp/ExpressionSelectorChoiceTest.cpp | dkBrazz/zserio | 29dd8145b7d851fac682d3afe991185ea2eac318 | [
"BSD-3-Clause"
] | 86 | 2018-09-06T09:30:53.000Z | 2022-03-27T01:12:36.000Z | test/language/choice_types/cpp/ExpressionSelectorChoiceTest.cpp | dkBrazz/zserio | 29dd8145b7d851fac682d3afe991185ea2eac318 | [
"BSD-3-Clause"
] | 362 | 2018-09-04T20:21:24.000Z | 2022-03-30T15:14:38.000Z | test/language/choice_types/cpp/ExpressionSelectorChoiceTest.cpp | dkBrazz/zserio | 29dd8145b7d851fac682d3afe991185ea2eac318 | [
"BSD-3-Clause"
] | 20 | 2018-09-10T15:59:02.000Z | 2021-12-01T15:38:22.000Z | #include "gtest/gtest.h"
#include "choice_types/expression_selector_choice/ExpressionSelectorChoice.h"
namespace choice_types
{
namespace expression_selector_choice
{
TEST(ExpressionSelectorChoiceTest, field8)
{
const uint16_t selector = 0;
ExpressionSelectorChoice expressionSelectorChoice;
expressionSelectorChoice.initialize(selector);
const uint8_t value8 = 0x7F;
expressionSelectorChoice.setField8(value8);
ASSERT_EQ(value8, expressionSelectorChoice.getField8());
ASSERT_EQ(8, expressionSelectorChoice.bitSizeOf());
}
TEST(ExpressionSelectorChoiceTest, field16)
{
const uint16_t selector = 1;
ExpressionSelectorChoice expressionSelectorChoice;
expressionSelectorChoice.initialize(selector);
const uint16_t value16 = 0x7F7F;
expressionSelectorChoice.setField16(value16);
ASSERT_EQ(value16, expressionSelectorChoice.getField16());
ASSERT_EQ(16, expressionSelectorChoice.bitSizeOf());
}
TEST(ExpressionSelectorChoiceTest, field32)
{
const uint16_t selector = 2;
ExpressionSelectorChoice expressionSelectorChoice;
expressionSelectorChoice.initialize(selector);
const uint32_t value32 = 0x7F7F7F7F;
expressionSelectorChoice.setField32(value32);
ASSERT_EQ(value32, expressionSelectorChoice.getField32());
ASSERT_EQ(32, expressionSelectorChoice.bitSizeOf());
}
} // namespace expression_selector_choice
} // namespace choice_types
| 31.533333 | 77 | 0.796335 | dkBrazz |
a405242adb8b4bae23c4536be95dcb6af5cbe697 | 5,004 | cc | C++ | media/cast/test/encode_decode_test.cc | iplo/Chain | 8bc8943d66285d5258fffc41bed7c840516c4422 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 231 | 2015-01-08T09:04:44.000Z | 2021-12-30T03:03:10.000Z | media/cast/test/encode_decode_test.cc | JasonEric/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2017-02-14T21:55:58.000Z | 2017-02-14T21:55:58.000Z | media/cast/test/encode_decode_test.cc | JasonEric/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 268 | 2015-01-21T05:53:28.000Z | 2022-03-25T22:09:01.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Joint encoder and decoder testing.
// These tests operate directly on the VP8 encoder and decoder, not the
// transport layer, and are targeted at validating the bit stream.
#include <gtest/gtest.h>
#include "base/bind.h"
#include "base/memory/scoped_ptr.h"
#include "media/base/video_frame.h"
#include "media/cast/cast_environment.h"
#include "media/cast/test/fake_single_thread_task_runner.h"
#include "media/cast/test/utility/video_utility.h"
#include "media/cast/video_receiver/codecs/vp8/vp8_decoder.h"
#include "media/cast/video_sender/codecs/vp8/vp8_encoder.h"
namespace media {
namespace cast {
static const int64 kStartMillisecond = GG_INT64_C(1245);
static const int kWidth = 1280;
static const int kHeight = 720;
static const int kStartbitrate = 4000000;
static const int kMaxQp = 54;
static const int kMinQp = 4;
static const int kMaxFrameRate = 30;
namespace {
class EncodeDecodeTestFrameCallback
: public base::RefCountedThreadSafe<EncodeDecodeTestFrameCallback> {
public:
EncodeDecodeTestFrameCallback() : num_called_(0) {
gfx::Size size(kWidth, kHeight);
original_frame_ = media::VideoFrame::CreateFrame(
VideoFrame::I420, size, gfx::Rect(size), size, base::TimeDelta());
}
void SetFrameStartValue(int start_value) {
PopulateVideoFrame(original_frame_.get(), start_value);
}
void DecodeComplete(const scoped_refptr<media::VideoFrame>& decoded_frame,
const base::TimeTicks& render_time) {
++num_called_;
// Compare resolution.
EXPECT_EQ(original_frame_->coded_size().width(),
decoded_frame->coded_size().width());
EXPECT_EQ(original_frame_->coded_size().height(),
decoded_frame->coded_size().height());
// Compare data.
EXPECT_GT(I420PSNR(original_frame_, decoded_frame), 40.0);
}
int num_called() const { return num_called_; }
protected:
virtual ~EncodeDecodeTestFrameCallback() {}
private:
friend class base::RefCountedThreadSafe<EncodeDecodeTestFrameCallback>;
int num_called_;
scoped_refptr<media::VideoFrame> original_frame_;
};
} // namespace
class EncodeDecodeTest : public ::testing::Test {
protected:
EncodeDecodeTest()
: testing_clock_(new base::SimpleTestTickClock()),
task_runner_(new test::FakeSingleThreadTaskRunner(testing_clock_)),
// CastEnvironment will only be used by the vp8 decoder; Enable only the
// video decoder and main threads.
cast_environment_(new CastEnvironment(
scoped_ptr<base::TickClock>(testing_clock_).Pass(),
task_runner_,
NULL,
NULL,
NULL,
task_runner_,
NULL,
GetDefaultCastReceiverLoggingConfig())),
test_callback_(new EncodeDecodeTestFrameCallback()) {
testing_clock_->Advance(
base::TimeDelta::FromMilliseconds(kStartMillisecond));
encoder_config_.max_number_of_video_buffers_used = 1;
encoder_config_.number_of_cores = 1;
encoder_config_.width = kWidth;
encoder_config_.height = kHeight;
encoder_config_.start_bitrate = kStartbitrate;
encoder_config_.min_qp = kMaxQp;
encoder_config_.min_qp = kMinQp;
encoder_config_.max_frame_rate = kMaxFrameRate;
int max_unacked_frames = 1;
encoder_.reset(new Vp8Encoder(encoder_config_, max_unacked_frames));
// Initialize to use one core.
decoder_.reset(new Vp8Decoder(cast_environment_));
}
virtual ~EncodeDecodeTest() {}
virtual void SetUp() OVERRIDE {
// Create test frame.
int start_value = 10; // Random value to start from.
gfx::Size size(encoder_config_.width, encoder_config_.height);
video_frame_ = media::VideoFrame::CreateFrame(
VideoFrame::I420, size, gfx::Rect(size), size, base::TimeDelta());
PopulateVideoFrame(video_frame_, start_value);
test_callback_->SetFrameStartValue(start_value);
}
VideoSenderConfig encoder_config_;
scoped_ptr<Vp8Encoder> encoder_;
scoped_ptr<Vp8Decoder> decoder_;
scoped_refptr<media::VideoFrame> video_frame_;
base::SimpleTestTickClock* testing_clock_; // Owned by CastEnvironment.
scoped_refptr<test::FakeSingleThreadTaskRunner> task_runner_;
scoped_refptr<CastEnvironment> cast_environment_;
scoped_refptr<EncodeDecodeTestFrameCallback> test_callback_;
};
TEST_F(EncodeDecodeTest, BasicEncodeDecode) {
transport::EncodedVideoFrame encoded_frame;
encoder_->Initialize();
// Encode frame.
encoder_->Encode(video_frame_, &encoded_frame);
EXPECT_GT(encoded_frame.data.size(), GG_UINT64_C(0));
// Decode frame.
decoder_->Decode(&encoded_frame,
base::TimeTicks(),
base::Bind(&EncodeDecodeTestFrameCallback::DecodeComplete,
test_callback_));
task_runner_->RunTasks();
}
} // namespace cast
} // namespace media
| 35.489362 | 80 | 0.723421 | iplo |
a40539eac21efc3396418b8a29a244e8b694467c | 677 | cpp | C++ | friendship_inheritance/inheritance1.cpp | Sinchiguano/Algorithmic-Toolbox | 7e9dda588a72356fc43fa276016fc3486be47556 | [
"BSD-2-Clause"
] | null | null | null | friendship_inheritance/inheritance1.cpp | Sinchiguano/Algorithmic-Toolbox | 7e9dda588a72356fc43fa276016fc3486be47556 | [
"BSD-2-Clause"
] | null | null | null | friendship_inheritance/inheritance1.cpp | Sinchiguano/Algorithmic-Toolbox | 7e9dda588a72356fc43fa276016fc3486be47556 | [
"BSD-2-Clause"
] | null | null | null | /*
* inheritance1.cpp
* Copyright (C) 2018 CESAR SINCHIGUANO <cesarsinchiguano@hotmail.es>
*
* Distributed under terms of the BSD license.
*/
#include <iostream>
using namespace std;
//g++ -std=c++14 -o temp sort.cpp
class Mother
{
public:
Mother ()
{ cout << "Mother: no parameters\n"; }
Mother (int a)
{ cout << "Mother: int parameter\n"; }
};
class Daughter : public Mother
{
public:
Daughter (int a)
{ cout << "Daughter: int parameter\n\n"; }
};
class Son : public Mother
{
public:
Son (int a) : Mother (a)
{ cout << "Son: int parameter\n\n"; }
};
int main ()
{
Daughter kelly(3);
Son casch(3);
return 0;
}
| 15.044444 | 69 | 0.595273 | Sinchiguano |
a406b386fceea856d3a50693083c7c58718ee026 | 1,013 | cpp | C++ | AP325/P-6-20.cpp | Superdanby/YEE | 49a6349dc5644579246623b480777afbf8031fcd | [
"MIT"
] | 1 | 2019-09-07T15:56:05.000Z | 2019-09-07T15:56:05.000Z | AP325/P-6-20.cpp | Superdanby/YEE | 49a6349dc5644579246623b480777afbf8031fcd | [
"MIT"
] | null | null | null | AP325/P-6-20.cpp | Superdanby/YEE | 49a6349dc5644579246623b480777afbf8031fcd | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
constexpr const ll INF = 1L << 60;
constexpr const ll MOD = 1e9 + 9;
ll solve(vector<ll> &values) {
vector<ll> dp(values.size());
vector<bool> pushed(values.size());
queue<ll> que;
que.push(0);
while (!que.empty()) {
ll node = que.front();
que.pop();
ll flip = 1, next;
while (flip < values.size()) {
next = node | flip;
if (next > node)
dp[next] = dp[node] + values[node] > dp[next] ? dp[node] + values[node]
: dp[next];
if (!pushed[next]) {
pushed[next] = true;
que.push(next);
}
flip <<= 1;
}
}
return dp.back() + values.back();
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
ll power;
cin >> power;
ll size = 1;
for (int i = 0; i < power; ++i) size <<= 1;
vector<ll> values(size);
for (auto &x : values) cin >> x;
cout << solve(values) << "\n";
return 0;
}
| 20.673469 | 79 | 0.516288 | Superdanby |
a406edcd4ce0aeba244cc0200b1a5ddee2bc3d26 | 970 | hpp | C++ | lightkit/software/src/tools/tools.hpp | Devdevdavid/Domoticz | d692d5f38706bcf45edb8a75794d64451cc4a72e | [
"MIT"
] | null | null | null | lightkit/software/src/tools/tools.hpp | Devdevdavid/Domoticz | d692d5f38706bcf45edb8a75794d64451cc4a72e | [
"MIT"
] | 26 | 2020-06-15T14:05:54.000Z | 2021-12-15T16:48:47.000Z | lightkit/software/src/tools/tools.hpp | Devdevdavid/Domoticz | d692d5f38706bcf45edb8a75794d64451cc4a72e | [
"MIT"
] | 1 | 2021-12-23T13:44:26.000Z | 2021-12-23T13:44:26.000Z | /**
* @file tools.hpp
* @brief Store useful functions and macros
* @author David DEVANT
* @date 03/07/2018
*/
#ifndef SRC_TOOLS_HPP_
#define SRC_TOOLS_HPP_
#include <cstdint>
#include <cstdlib>
#define OK 0
#define TIME_SECOND (1000)
#define TIME_MINUTE (60 * TIME_SECOND)
#define TIME_HOUR (60 * TIME_MINUTE)
#define TIME_DAY (24 * TIME_HOUR)
#define POW_2(x) (x * x)
#define POW_3(x) (x * x * x)
#define POW_4(x) (POW_2(x) * POW_2(x))
#define _set(base, flag) (base) |= (flag);
#define _unset(base, flag) (base) &= ~(flag);
#define _isset(base, flag) (((base) & (flag)) != 0)
#define _isunset(base, flag) (((base) & (flag)) == 0)
#define _strncmp(str1, strCst) strncmp(argv[0], strCst, sizeof(strCst))
#define CHECK_CALL(call) \
if (call) { \
log_error(#call " failed()"); \
return -1; \
}
uint16_t sToU16(const char * str, uint16_t length);
#endif /* SRC_TOOLS_HPP_ */
| 23.658537 | 71 | 0.606186 | Devdevdavid |
a40b558cec5fb88f3b6895e11f595b7c0cca599e | 2,109 | cpp | C++ | qsdlrectangle.cpp | CrimsonAS/qtsdl | a0c2487c175393d54d27574f9f02bfa436c34e79 | [
"Unlicense"
] | 2 | 2018-06-23T17:06:27.000Z | 2019-01-29T21:31:53.000Z | qsdlrectangle.cpp | CrimsonAS/qtsdl | a0c2487c175393d54d27574f9f02bfa436c34e79 | [
"Unlicense"
] | null | null | null | qsdlrectangle.cpp | CrimsonAS/qtsdl | a0c2487c175393d54d27574f9f02bfa436c34e79 | [
"Unlicense"
] | null | null | null | /*
* Copyright (c) 2014 Robin Burchell <robin+git@viroteck.net>
* 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.
*/
#include <QQmlInfo>
#include <QFile>
#include <SDL.h>
#include "qsdlwindow.h"
#include "qsdlrectangle.h"
QSdlRectangle::QSdlRectangle(QObject *parent)
: QSdlItem(parent)
{
}
QSdlRectangle::~QSdlRectangle()
{
}
QColor QSdlRectangle::color() const
{
return m_color;
}
void QSdlRectangle::setColor(const QColor &color)
{
m_color = color;
emit colorChanged();
}
void QSdlRectangle::render()
{
SDL_Rect rect;
rect.x = x();
rect.y = y();
rect.w = width();
rect.h = height();
SDL_SetRenderDrawColor(window()->renderer(), color().red(), color().green(), color().blue(), color().alpha());
SDL_RenderFillRect(window()->renderer(), &rect);
QSdlItem::render();
}
| 30.128571 | 114 | 0.726885 | CrimsonAS |
a40e335b4ce8500b2c918978da410d0785ce5428 | 1,224 | cpp | C++ | tests/test_http/main.cpp | thorrak/esp32FOTA | 270da987f228c3cbd9dc1ef60a45af81a24d11d6 | [
"Unlicense"
] | 178 | 2018-12-21T08:10:57.000Z | 2022-03-30T02:57:10.000Z | tests/test_http/main.cpp | thorrak/esp32FOTA | 270da987f228c3cbd9dc1ef60a45af81a24d11d6 | [
"Unlicense"
] | 60 | 2019-03-27T10:01:31.000Z | 2022-03-23T05:31:03.000Z | tests/test_http/main.cpp | thorrak/esp32FOTA | 270da987f228c3cbd9dc1ef60a45af81a24d11d6 | [
"Unlicense"
] | 72 | 2019-03-27T16:05:53.000Z | 2022-03-23T19:21:25.000Z | /**
esp32 firmware OTA
Purpose: Perform an OTA update from a bin located on a webserver (HTTP Only)
Setup:
Step 1 : Set your WiFi (ssid & password)
Step 2 : set esp32fota()
Upload:
Step 1 : Menu > Sketch > Export Compiled Library. The bin file will be saved in the sketch folder (Menu > Sketch > Show Sketch folder)
Step 2 : Upload it to your webserver
Step 3 : Update your firmware JSON file ( see firwmareupdate )
*/
#include <esp32fota.h>
#include <WiFi.h>
// Change to your WiFi credentials
const char *ssid = "";
const char *password = "";
// esp32fota esp32fota("<Type of Firme for this device>", <this version>);
esp32FOTA esp32FOTA("esp32-fota-http", 1);
void setup_wifi()
{
delay(10);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println(WiFi.localIP());
}
void setup()
{
esp32FOTA.checkURL = "http://server/fota/fota.json";
Serial.begin(115200);
setup_wifi();
}
void loop()
{
bool updatedNeeded = esp32FOTA.execHTTPcheck();
if (updatedNeeded)
{
esp32FOTA.execOTA();
}
delay(2000);
}
| 19.428571 | 137 | 0.658497 | thorrak |
a40f8b7b85852101ddbc2c946cdb585a06270f80 | 406 | hpp | C++ | external-memory/Common/Timer.hpp | Why1221/iDEC | a6f0064bf4f6c0b199dc0753a7f14ce4dad357cb | [
"MIT"
] | 2 | 2021-06-15T14:58:59.000Z | 2022-01-06T17:17:57.000Z | in-memory/Common/Timer.hpp | Why1221/iDEC | a6f0064bf4f6c0b199dc0753a7f14ce4dad357cb | [
"MIT"
] | null | null | null | in-memory/Common/Timer.hpp | Why1221/iDEC | a6f0064bf4f6c0b199dc0753a7f14ce4dad357cb | [
"MIT"
] | null | null | null | #ifndef __TIMER_HPP_
#define __TIMER_HPP_
#include <chrono>
using namespace std::chrono;
struct HighResolutionTimer {
void restart() {
_start = high_resolution_clock::now();
}
double elapsed() const {
auto cur = high_resolution_clock::now();
return duration<double, std::micro>(cur - _start).count();
}
private:
high_resolution_clock::time_point _start;
};
#endif // __TIMER_HPP_ | 19.333333 | 62 | 0.714286 | Why1221 |
a4100d249dea357782c9a9a22ef3a8a883c06f2e | 11,173 | cpp | C++ | tests/types/tests_fundamental_int.cpp | YuriyLisovskiy/xalwart.base | edf7e43128305c0401ff208d8065e6576c8d783b | [
"Apache-2.0"
] | null | null | null | tests/types/tests_fundamental_int.cpp | YuriyLisovskiy/xalwart.base | edf7e43128305c0401ff208d8065e6576c8d783b | [
"Apache-2.0"
] | null | null | null | tests/types/tests_fundamental_int.cpp | YuriyLisovskiy/xalwart.base | edf7e43128305c0401ff208d8065e6576c8d783b | [
"Apache-2.0"
] | null | null | null | /**
* types/tests_fundamental_int.cpp
*
* Copyright (c) 2021 Yuriy Lisovskiy
*/
#include <gtest/gtest.h>
#include "../../src/types/fundamental.h"
using namespace xw;
TEST(TestCase_Fundamental_Int, Test_Get)
{
auto int_obj = types::Fundamental<int>(10);
ASSERT_EQ(*int_obj, 10);
}
TEST(TestCase_Fundamental_Int, Test_HoldsType_True)
{
auto int_obj = types::Fundamental<int>(10);
ASSERT_TRUE(int_obj.holds_type<int>());
}
TEST(TestCase_Fundamental_Int, Test_HoldsType_False)
{
auto int_obj = types::Fundamental<int>(10);
ASSERT_FALSE(int_obj.holds_type<long>());
}
TEST(TestCase_Fundamental_Int, Test_FitTo)
{
auto value = types::Fundamental<float>(10.5f);
ASSERT_EQ(*value, 10.5f);
auto fitted_value = value.fit_to<unsigned long>();
ASSERT_EQ(*fitted_value, 10);
}
TEST(TestCase_Fundamental_Int, Test_OperatorBool_True)
{
auto int_obj = types::Fundamental<int>(10);
ASSERT_TRUE(int_obj.operator bool());
}
TEST(TestCase_Fundamental_Int, Test_OperatorBool_False)
{
auto int_obj = types::Fundamental<int>(0);
ASSERT_FALSE(int_obj.operator bool());
}
TEST(TestCase_Fundamental_Int, Test___str__)
{
auto int_obj = types::Fundamental<int>(10);
ASSERT_EQ(int_obj.__str__(), "10");
}
TEST(TestCase_Fundamental_Int, Test___repr__)
{
auto int_obj = types::Fundamental<int>(10);
ASSERT_EQ(int_obj.__repr__(), "10");
}
TEST(TestCase_Fundamental_Int, Test_AssignmentOperator)
{
auto int_obj = types::Fundamental<int>(10);
auto int_obj_copy = int_obj;
ASSERT_EQ(*int_obj, *int_obj_copy);
}
TEST(TestCase_Fundamental_Int, Test_OperatorPlus)
{
auto left = types::Fundamental<int>(10);
auto right = types::Fundamental<int>(35);
ASSERT_EQ(*(left + right), 10 + 35);
}
TEST(TestCase_Fundamental_Int, Test_OperatorMinus)
{
auto left = types::Fundamental<int>(10);
auto right = types::Fundamental<int>(35);
ASSERT_EQ(*(left - right), 10 - 35);
}
TEST(TestCase_Fundamental_Int, Test_OperatorUnaryPlus)
{
auto value = types::Fundamental<int>(-10);
ASSERT_EQ(*(+value), -10);
}
TEST(TestCase_Fundamental_Int, Test_OperatorUnaryMinus)
{
auto value = types::Fundamental<int>(10);
ASSERT_EQ(*-value, -10);
}
TEST(TestCase_Fundamental_Int, Test_OperatorMultiply)
{
auto left = types::Fundamental<int>(7);
auto right = types::Fundamental<int>(35);
ASSERT_EQ(*(left * right), 7 * 35);
}
TEST(TestCase_Fundamental_Int, Test_OperatorDivision)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(35);
ASSERT_EQ(*(left / right), 11 / 35);
}
TEST(TestCase_Fundamental_Int, Test_OperatorMod)
{
auto left = types::Fundamental<int>(35);
auto right = types::Fundamental<int>(11);
ASSERT_EQ(*(left % right), 35 % 11);
}
TEST(TestCase_Fundamental_Int, Test_OperatorEquals_True)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(11);
ASSERT_TRUE(left == right);
}
TEST(TestCase_Fundamental_Int, Test_OperatorEquals_False)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(35);
ASSERT_FALSE(left == right);
}
TEST(TestCase_Fundamental_Int, Test_OperatorNotEquals_False)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(11);
ASSERT_FALSE(left != right);
}
TEST(TestCase_Fundamental_Int, Test_OperatorNotEquals_True)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(35);
ASSERT_TRUE(left != right);
}
TEST(TestCase_Fundamental_Int, Test_OperatorLess_True)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(12);
ASSERT_TRUE(left < right);
}
TEST(TestCase_Fundamental_Int, Test_OperatorLess_False)
{
auto left = types::Fundamental<int>(37);
auto right = types::Fundamental<int>(35);
ASSERT_FALSE(left < right);
}
TEST(TestCase_Fundamental_Int, Test_OperatorLessEq_True)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(11);
ASSERT_TRUE(left <= right);
}
TEST(TestCase_Fundamental_Int, Test_OperatorLessEq_False)
{
auto left = types::Fundamental<int>(37);
auto right = types::Fundamental<int>(35);
ASSERT_FALSE(left <= right);
}
TEST(TestCase_Fundamental_Int, Test_OperatorGreater_True)
{
auto left = types::Fundamental<int>(12);
auto right = types::Fundamental<int>(11);
ASSERT_TRUE(left > right);
}
TEST(TestCase_Fundamental_Int, Test_OperatorGreater_False)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(35);
ASSERT_FALSE(left > right);
}
TEST(TestCase_Fundamental_Int, Test_OperatorGreaterEq_True)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(11);
ASSERT_TRUE(left >= right);
}
TEST(TestCase_Fundamental_Int, Test_OperatorGreaterEq_False)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(35);
ASSERT_FALSE(left >= right);
}
TEST(TestCase_Fundamental_Int, Test_OperatorBitwiseAnd)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(35);
ASSERT_EQ(*(left & right), 11 & 35);
}
TEST(TestCase_Fundamental_Int, Test_OperatorNot_True)
{
auto value = types::Fundamental<int>(0);
ASSERT_TRUE(!value);
}
TEST(TestCase_Fundamental_Int, Test_OperatorNot_False)
{
auto value = types::Fundamental<int>(11);
ASSERT_FALSE(!value);
}
TEST(TestCase_Fundamental_Int, Test_OperatorBitwiseOr)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(35);
ASSERT_EQ(*(left | right), 11 | 35);
}
TEST(TestCase_Fundamental_Int, Test_OperatorBitwiseNot)
{
auto value = types::Fundamental<int>(35);
ASSERT_EQ(*~value, ~35);
}
TEST(TestCase_Fundamental_Int, Test_OperatorBitwiseXor)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(35);
ASSERT_EQ(*(left ^ right), 11 ^ 35);
}
TEST(TestCase_Fundamental_Int, Test_OperatorLeftShiftIntegral)
{
auto value = types::Fundamental<int>(11);
auto ic = 5;
ASSERT_EQ(*(value << ic), 11 << 5);
}
TEST(TestCase_Fundamental_Int, Test_OperatorLeftShift)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(5);
ASSERT_EQ(*(left << right), 11 << 5);
}
TEST(TestCase_Fundamental_Int, Test_OperatorRightShiftIntegral)
{
auto value = types::Fundamental<int>(11);
auto ic = 5;
ASSERT_EQ(*(value >> ic), 11 >> 5);
}
TEST(TestCase_Fundamental_Int, Test_OperatorRightShift)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(5);
ASSERT_EQ(*(left >> right), 11 >> 5);
}
TEST(TestCase_Fundamental_Int, Test_OperatorOstream)
{
auto value = types::Fundamental<int>(11);
std::stringstream ss;
ss << value;
ASSERT_EQ(ss.str(), "11");
}
TEST(TestCase_Fundamental_Int, Test_OperatorAddEq)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(35);
ASSERT_EQ(*left, 11);
left += right;
ASSERT_EQ(*left, 11 + 35);
}
TEST(TestCase_Fundamental_Int, Test_OperatorAddEqFundamental)
{
auto left = types::Fundamental<int>(11);
float right = 35.4f;
ASSERT_EQ(*left, 11);
left += right;
int expected = 11;
expected += right;
ASSERT_EQ(*left, expected);
}
TEST(TestCase_Fundamental_Int, Test_OperatorSubEq)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(35);
ASSERT_EQ(*left, 11);
left -= right;
ASSERT_EQ(*left, 11 - 35);
}
TEST(TestCase_Fundamental_Int, Test_OperatorSubEqFundamental)
{
auto left = types::Fundamental<int>(11);
float right = 35.4f;
ASSERT_EQ(*left, 11);
left -= right;
int expected = 11;
expected -= right;
ASSERT_EQ(*left, expected);
}
TEST(TestCase_Fundamental_Int, Test_OperatorMulEq)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(35);
ASSERT_EQ(*left, 11);
left *= right;
ASSERT_EQ(*left, 11 * 35);
}
TEST(TestCase_Fundamental_Int, Test_OperatorMulEqFundamental)
{
auto left = types::Fundamental<int>(11);
float right = 35.4f;
ASSERT_EQ(*left, 11);
left *= right;
int expected = 11;
expected *= right;
ASSERT_EQ(*left, expected);
}
TEST(TestCase_Fundamental_Int, Test_OperatorDivEq)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(35);
ASSERT_EQ(*left, 11);
left /= right;
ASSERT_EQ(*left, 11 / 35);
}
TEST(TestCase_Fundamental_Int, Test_OperatorDivEqFundamental)
{
auto left = types::Fundamental<int>(11);
float right = 35.4f;
ASSERT_EQ(*left, 11);
left /= right;
int expected = 11;
expected /= right;
ASSERT_EQ(*left, expected);
}
TEST(TestCase_Fundamental_Int, Test_OperatorModEq)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(35);
ASSERT_EQ(*left, 11);
left %= right;
ASSERT_EQ(*left, 11 % 35);
}
TEST(TestCase_Fundamental_Int, Test_OperatorModEqFundamental)
{
auto left = types::Fundamental<int>(11);
long long right = 7;
ASSERT_EQ(*left, 11);
left %= right;
int expected = 11;
expected %= right;
ASSERT_EQ(*left, expected);
}
TEST(TestCase_Fundamental_Int, Test_OperatorBitwiseAndEq)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(35);
ASSERT_EQ(*left, 11);
left &= right;
ASSERT_EQ(*left, 11 & 35);
}
TEST(TestCase_Fundamental_Int, Test_OperatorBitwiseAndEqFundamental)
{
auto left = types::Fundamental<int>(11);
signed right = 35;
ASSERT_EQ(*left, 11);
left &= right;
int expected = 11;
expected &= right;
ASSERT_EQ(*left, expected);
}
TEST(TestCase_Fundamental_Int, Test_OperatorBitwiseOrEq)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(35);
ASSERT_EQ(*left, 11);
left |= right;
ASSERT_EQ(*left, 11 | 35);
}
TEST(TestCase_Fundamental_Int, Test_OperatorBitwiseOrEqFundamental)
{
auto left = types::Fundamental<int>(11);
unsigned right = 35;
ASSERT_EQ(*left, 11);
left |= right;
int expected = 11;
expected |= right;
ASSERT_EQ(*left, expected);
}
TEST(TestCase_Fundamental_Int, Test_OperatorBitwiseXorEq)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(4);
ASSERT_EQ(*left, 11);
left ^= right;
ASSERT_EQ(*left, 11 ^ 4);
}
TEST(TestCase_Fundamental_Int, Test_OperatorBitwiseXorEqFundamental)
{
auto left = types::Fundamental<int>(11);
short right = 4;
ASSERT_EQ(*left, 11);
left ^= right;
int expected = 11;
expected ^= right;
ASSERT_EQ(*left, expected);
}
TEST(TestCase_Fundamental_Int, Test_OperatorBitwiseLeftShiftEq)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(3);
ASSERT_EQ(*left, 11);
left <<= right;
ASSERT_EQ(*left, 11 << 3);
}
TEST(TestCase_Fundamental_Int, Test_OperatorBitwiseLeftShiftEqFundamental)
{
auto left = types::Fundamental<int>(11);
char right = 'c';
ASSERT_EQ(*left, 11);
left <<= right;
int expected = 11;
expected <<= right;
ASSERT_EQ(*left, expected);
}
TEST(TestCase_Fundamental_Int, Test_OperatorBitwiseRightShiftEq)
{
auto left = types::Fundamental<int>(11);
auto right = types::Fundamental<int>(2);
ASSERT_EQ(*left, 11);
left >>= right;
ASSERT_EQ(*left, 11 >> 2);
}
TEST(TestCase_Fundamental_Int, Test_OperatorBitwiseRightShiftEqFundamental)
{
auto left = types::Fundamental<int>(11);
long right = 2;
ASSERT_EQ(*left, 11);
left >>= right;
int expected = 11;
expected >>= right;
ASSERT_EQ(*left, expected);
}
| 22.037475 | 75 | 0.724335 | YuriyLisovskiy |
a4120120a01c49eeeaeef05a13642baf8feffadb | 18,459 | cpp | C++ | third-party/llvm/llvm-src/tools/clang/lib/APINotes/APINotesYAMLCompiler.cpp | jhh67/chapel | f041470e9b88b5fc4914c75aa5a37efcb46aa08f | [
"ECL-2.0",
"Apache-2.0"
] | 250 | 2019-05-07T12:56:44.000Z | 2022-03-10T15:52:06.000Z | third-party/llvm/llvm-src/tools/clang/lib/APINotes/APINotesYAMLCompiler.cpp | jhh67/chapel | f041470e9b88b5fc4914c75aa5a37efcb46aa08f | [
"ECL-2.0",
"Apache-2.0"
] | 410 | 2019-06-06T20:52:32.000Z | 2022-01-18T14:21:48.000Z | third-party/llvm/llvm-src/tools/clang/lib/APINotes/APINotesYAMLCompiler.cpp | jhh67/chapel | f041470e9b88b5fc4914c75aa5a37efcb46aa08f | [
"ECL-2.0",
"Apache-2.0"
] | 50 | 2019-05-10T21:12:24.000Z | 2022-01-21T06:39:47.000Z | //===-- APINotesYAMLCompiler.cpp - API Notes YAML Format Reader -*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// The types defined locally are designed to represent the YAML state, which
// adds an additional bit of state: e.g. a tri-state boolean attribute (yes, no,
// not applied) becomes a tri-state boolean + present. As a result, while these
// enumerations appear to be redefining constants from the attributes table
// data, they are distinct.
//
#include "clang/APINotes/APINotesYAMLCompiler.h"
#include "clang/APINotes/Types.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/Specifiers.h"
#include "llvm/ADT/Optional.h"
#include "llvm/Support/VersionTuple.h"
#include "llvm/Support/YAMLParser.h"
#include "llvm/Support/YAMLTraits.h"
#include <vector>
using namespace clang;
using namespace api_notes;
namespace {
enum class APIAvailability {
Available = 0,
OSX,
IOS,
None,
NonSwift,
};
} // namespace
namespace llvm {
namespace yaml {
template <> struct ScalarEnumerationTraits<APIAvailability> {
static void enumeration(IO &IO, APIAvailability &AA) {
IO.enumCase(AA, "OSX", APIAvailability::OSX);
IO.enumCase(AA, "iOS", APIAvailability::IOS);
IO.enumCase(AA, "none", APIAvailability::None);
IO.enumCase(AA, "nonswift", APIAvailability::NonSwift);
IO.enumCase(AA, "available", APIAvailability::Available);
}
};
} // namespace yaml
} // namespace llvm
namespace {
enum class MethodKind {
Class,
Instance,
};
} // namespace
namespace llvm {
namespace yaml {
template <> struct ScalarEnumerationTraits<MethodKind> {
static void enumeration(IO &IO, MethodKind &MK) {
IO.enumCase(MK, "Class", MethodKind::Class);
IO.enumCase(MK, "Instance", MethodKind::Instance);
}
};
} // namespace yaml
} // namespace llvm
namespace {
struct Param {
unsigned Position;
Optional<bool> NoEscape = false;
Optional<NullabilityKind> Nullability;
Optional<RetainCountConventionKind> RetainCountConvention;
StringRef Type;
};
typedef std::vector<Param> ParamsSeq;
} // namespace
LLVM_YAML_IS_SEQUENCE_VECTOR(Param)
LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(NullabilityKind)
namespace llvm {
namespace yaml {
template <> struct ScalarEnumerationTraits<NullabilityKind> {
static void enumeration(IO &IO, NullabilityKind &NK) {
IO.enumCase(NK, "Nonnull", NullabilityKind::NonNull);
IO.enumCase(NK, "Optional", NullabilityKind::Nullable);
IO.enumCase(NK, "Unspecified", NullabilityKind::Unspecified);
IO.enumCase(NK, "NullableResult", NullabilityKind::NullableResult);
// TODO: Mapping this to it's own value would allow for better cross
// checking. Also the default should be Unknown.
IO.enumCase(NK, "Scalar", NullabilityKind::Unspecified);
// Aliases for compatibility with existing APINotes.
IO.enumCase(NK, "N", NullabilityKind::NonNull);
IO.enumCase(NK, "O", NullabilityKind::Nullable);
IO.enumCase(NK, "U", NullabilityKind::Unspecified);
IO.enumCase(NK, "S", NullabilityKind::Unspecified);
}
};
template <> struct ScalarEnumerationTraits<RetainCountConventionKind> {
static void enumeration(IO &IO, RetainCountConventionKind &RCCK) {
IO.enumCase(RCCK, "none", RetainCountConventionKind::None);
IO.enumCase(RCCK, "CFReturnsRetained",
RetainCountConventionKind::CFReturnsRetained);
IO.enumCase(RCCK, "CFReturnsNotRetained",
RetainCountConventionKind::CFReturnsNotRetained);
IO.enumCase(RCCK, "NSReturnsRetained",
RetainCountConventionKind::NSReturnsRetained);
IO.enumCase(RCCK, "NSReturnsNotRetained",
RetainCountConventionKind::NSReturnsNotRetained);
}
};
template <> struct MappingTraits<Param> {
static void mapping(IO &IO, Param &P) {
IO.mapRequired("Position", P.Position);
IO.mapOptional("Nullability", P.Nullability, llvm::None);
IO.mapOptional("RetainCountConvention", P.RetainCountConvention);
IO.mapOptional("NoEscape", P.NoEscape);
IO.mapOptional("Type", P.Type, StringRef(""));
}
};
} // namespace yaml
} // namespace llvm
namespace {
typedef std::vector<NullabilityKind> NullabilitySeq;
struct AvailabilityItem {
APIAvailability Mode = APIAvailability::Available;
StringRef Msg;
};
/// Old attribute deprecated in favor of SwiftName.
enum class FactoryAsInitKind {
/// Infer based on name and type (the default).
Infer,
/// Treat as a class method.
AsClassMethod,
/// Treat as an initializer.
AsInitializer,
};
struct Method {
StringRef Selector;
MethodKind Kind;
ParamsSeq Params;
NullabilitySeq Nullability;
Optional<NullabilityKind> NullabilityOfRet;
Optional<RetainCountConventionKind> RetainCountConvention;
AvailabilityItem Availability;
Optional<bool> SwiftPrivate;
StringRef SwiftName;
FactoryAsInitKind FactoryAsInit = FactoryAsInitKind::Infer;
bool DesignatedInit = false;
bool Required = false;
StringRef ResultType;
};
typedef std::vector<Method> MethodsSeq;
} // namespace
LLVM_YAML_IS_SEQUENCE_VECTOR(Method)
namespace llvm {
namespace yaml {
template <> struct ScalarEnumerationTraits<FactoryAsInitKind> {
static void enumeration(IO &IO, FactoryAsInitKind &FIK) {
IO.enumCase(FIK, "A", FactoryAsInitKind::Infer);
IO.enumCase(FIK, "C", FactoryAsInitKind::AsClassMethod);
IO.enumCase(FIK, "I", FactoryAsInitKind::AsInitializer);
}
};
template <> struct MappingTraits<Method> {
static void mapping(IO &IO, Method &M) {
IO.mapRequired("Selector", M.Selector);
IO.mapRequired("MethodKind", M.Kind);
IO.mapOptional("Parameters", M.Params);
IO.mapOptional("Nullability", M.Nullability);
IO.mapOptional("NullabilityOfRet", M.NullabilityOfRet, llvm::None);
IO.mapOptional("RetainCountConvention", M.RetainCountConvention);
IO.mapOptional("Availability", M.Availability.Mode,
APIAvailability::Available);
IO.mapOptional("AvailabilityMsg", M.Availability.Msg, StringRef(""));
IO.mapOptional("SwiftPrivate", M.SwiftPrivate);
IO.mapOptional("SwiftName", M.SwiftName, StringRef(""));
IO.mapOptional("FactoryAsInit", M.FactoryAsInit, FactoryAsInitKind::Infer);
IO.mapOptional("DesignatedInit", M.DesignatedInit, false);
IO.mapOptional("Required", M.Required, false);
IO.mapOptional("ResultType", M.ResultType, StringRef(""));
}
};
} // namespace yaml
} // namespace llvm
namespace {
struct Property {
StringRef Name;
llvm::Optional<MethodKind> Kind;
llvm::Optional<NullabilityKind> Nullability;
AvailabilityItem Availability;
Optional<bool> SwiftPrivate;
StringRef SwiftName;
Optional<bool> SwiftImportAsAccessors;
StringRef Type;
};
typedef std::vector<Property> PropertiesSeq;
} // namespace
LLVM_YAML_IS_SEQUENCE_VECTOR(Property)
namespace llvm {
namespace yaml {
template <> struct MappingTraits<Property> {
static void mapping(IO &IO, Property &P) {
IO.mapRequired("Name", P.Name);
IO.mapOptional("PropertyKind", P.Kind);
IO.mapOptional("Nullability", P.Nullability, llvm::None);
IO.mapOptional("Availability", P.Availability.Mode,
APIAvailability::Available);
IO.mapOptional("AvailabilityMsg", P.Availability.Msg, StringRef(""));
IO.mapOptional("SwiftPrivate", P.SwiftPrivate);
IO.mapOptional("SwiftName", P.SwiftName, StringRef(""));
IO.mapOptional("SwiftImportAsAccessors", P.SwiftImportAsAccessors);
IO.mapOptional("Type", P.Type, StringRef(""));
}
};
} // namespace yaml
} // namespace llvm
namespace {
struct Class {
StringRef Name;
bool AuditedForNullability = false;
AvailabilityItem Availability;
Optional<bool> SwiftPrivate;
StringRef SwiftName;
Optional<StringRef> SwiftBridge;
Optional<StringRef> NSErrorDomain;
Optional<bool> SwiftImportAsNonGeneric;
Optional<bool> SwiftObjCMembers;
MethodsSeq Methods;
PropertiesSeq Properties;
};
typedef std::vector<Class> ClassesSeq;
} // namespace
LLVM_YAML_IS_SEQUENCE_VECTOR(Class)
namespace llvm {
namespace yaml {
template <> struct MappingTraits<Class> {
static void mapping(IO &IO, Class &C) {
IO.mapRequired("Name", C.Name);
IO.mapOptional("AuditedForNullability", C.AuditedForNullability, false);
IO.mapOptional("Availability", C.Availability.Mode,
APIAvailability::Available);
IO.mapOptional("AvailabilityMsg", C.Availability.Msg, StringRef(""));
IO.mapOptional("SwiftPrivate", C.SwiftPrivate);
IO.mapOptional("SwiftName", C.SwiftName, StringRef(""));
IO.mapOptional("SwiftBridge", C.SwiftBridge);
IO.mapOptional("NSErrorDomain", C.NSErrorDomain);
IO.mapOptional("SwiftImportAsNonGeneric", C.SwiftImportAsNonGeneric);
IO.mapOptional("SwiftObjCMembers", C.SwiftObjCMembers);
IO.mapOptional("Methods", C.Methods);
IO.mapOptional("Properties", C.Properties);
}
};
} // namespace yaml
} // namespace llvm
namespace {
struct Function {
StringRef Name;
ParamsSeq Params;
NullabilitySeq Nullability;
Optional<NullabilityKind> NullabilityOfRet;
Optional<api_notes::RetainCountConventionKind> RetainCountConvention;
AvailabilityItem Availability;
Optional<bool> SwiftPrivate;
StringRef SwiftName;
StringRef Type;
StringRef ResultType;
};
typedef std::vector<Function> FunctionsSeq;
} // namespace
LLVM_YAML_IS_SEQUENCE_VECTOR(Function)
namespace llvm {
namespace yaml {
template <> struct MappingTraits<Function> {
static void mapping(IO &IO, Function &F) {
IO.mapRequired("Name", F.Name);
IO.mapOptional("Parameters", F.Params);
IO.mapOptional("Nullability", F.Nullability);
IO.mapOptional("NullabilityOfRet", F.NullabilityOfRet, llvm::None);
IO.mapOptional("RetainCountConvention", F.RetainCountConvention);
IO.mapOptional("Availability", F.Availability.Mode,
APIAvailability::Available);
IO.mapOptional("AvailabilityMsg", F.Availability.Msg, StringRef(""));
IO.mapOptional("SwiftPrivate", F.SwiftPrivate);
IO.mapOptional("SwiftName", F.SwiftName, StringRef(""));
IO.mapOptional("ResultType", F.ResultType, StringRef(""));
}
};
} // namespace yaml
} // namespace llvm
namespace {
struct GlobalVariable {
StringRef Name;
llvm::Optional<NullabilityKind> Nullability;
AvailabilityItem Availability;
Optional<bool> SwiftPrivate;
StringRef SwiftName;
StringRef Type;
};
typedef std::vector<GlobalVariable> GlobalVariablesSeq;
} // namespace
LLVM_YAML_IS_SEQUENCE_VECTOR(GlobalVariable)
namespace llvm {
namespace yaml {
template <> struct MappingTraits<GlobalVariable> {
static void mapping(IO &IO, GlobalVariable &GV) {
IO.mapRequired("Name", GV.Name);
IO.mapOptional("Nullability", GV.Nullability, llvm::None);
IO.mapOptional("Availability", GV.Availability.Mode,
APIAvailability::Available);
IO.mapOptional("AvailabilityMsg", GV.Availability.Msg, StringRef(""));
IO.mapOptional("SwiftPrivate", GV.SwiftPrivate);
IO.mapOptional("SwiftName", GV.SwiftName, StringRef(""));
IO.mapOptional("Type", GV.Type, StringRef(""));
}
};
} // namespace yaml
} // namespace llvm
namespace {
struct EnumConstant {
StringRef Name;
AvailabilityItem Availability;
Optional<bool> SwiftPrivate;
StringRef SwiftName;
};
typedef std::vector<EnumConstant> EnumConstantsSeq;
} // namespace
LLVM_YAML_IS_SEQUENCE_VECTOR(EnumConstant)
namespace llvm {
namespace yaml {
template <> struct MappingTraits<EnumConstant> {
static void mapping(IO &IO, EnumConstant &EC) {
IO.mapRequired("Name", EC.Name);
IO.mapOptional("Availability", EC.Availability.Mode,
APIAvailability::Available);
IO.mapOptional("AvailabilityMsg", EC.Availability.Msg, StringRef(""));
IO.mapOptional("SwiftPrivate", EC.SwiftPrivate);
IO.mapOptional("SwiftName", EC.SwiftName, StringRef(""));
}
};
} // namespace yaml
} // namespace llvm
namespace {
/// Syntactic sugar for EnumExtensibility and FlagEnum
enum class EnumConvenienceAliasKind {
/// EnumExtensibility: none, FlagEnum: false
None,
/// EnumExtensibility: open, FlagEnum: false
CFEnum,
/// EnumExtensibility: open, FlagEnum: true
CFOptions,
/// EnumExtensibility: closed, FlagEnum: false
CFClosedEnum
};
} // namespace
namespace llvm {
namespace yaml {
template <> struct ScalarEnumerationTraits<EnumConvenienceAliasKind> {
static void enumeration(IO &IO, EnumConvenienceAliasKind &ECAK) {
IO.enumCase(ECAK, "none", EnumConvenienceAliasKind::None);
IO.enumCase(ECAK, "CFEnum", EnumConvenienceAliasKind::CFEnum);
IO.enumCase(ECAK, "NSEnum", EnumConvenienceAliasKind::CFEnum);
IO.enumCase(ECAK, "CFOptions", EnumConvenienceAliasKind::CFOptions);
IO.enumCase(ECAK, "NSOptions", EnumConvenienceAliasKind::CFOptions);
IO.enumCase(ECAK, "CFClosedEnum", EnumConvenienceAliasKind::CFClosedEnum);
IO.enumCase(ECAK, "NSClosedEnum", EnumConvenienceAliasKind::CFClosedEnum);
}
};
} // namespace yaml
} // namespace llvm
namespace {
struct Tag {
StringRef Name;
AvailabilityItem Availability;
StringRef SwiftName;
Optional<bool> SwiftPrivate;
Optional<StringRef> SwiftBridge;
Optional<StringRef> NSErrorDomain;
Optional<EnumExtensibilityKind> EnumExtensibility;
Optional<bool> FlagEnum;
Optional<EnumConvenienceAliasKind> EnumConvenienceKind;
};
typedef std::vector<Tag> TagsSeq;
} // namespace
LLVM_YAML_IS_SEQUENCE_VECTOR(Tag)
namespace llvm {
namespace yaml {
template <> struct ScalarEnumerationTraits<EnumExtensibilityKind> {
static void enumeration(IO &IO, EnumExtensibilityKind &EEK) {
IO.enumCase(EEK, "none", EnumExtensibilityKind::None);
IO.enumCase(EEK, "open", EnumExtensibilityKind::Open);
IO.enumCase(EEK, "closed", EnumExtensibilityKind::Closed);
}
};
template <> struct MappingTraits<Tag> {
static void mapping(IO &IO, Tag &T) {
IO.mapRequired("Name", T.Name);
IO.mapOptional("Availability", T.Availability.Mode,
APIAvailability::Available);
IO.mapOptional("AvailabilityMsg", T.Availability.Msg, StringRef(""));
IO.mapOptional("SwiftPrivate", T.SwiftPrivate);
IO.mapOptional("SwiftName", T.SwiftName, StringRef(""));
IO.mapOptional("SwiftBridge", T.SwiftBridge);
IO.mapOptional("NSErrorDomain", T.NSErrorDomain);
IO.mapOptional("EnumExtensibility", T.EnumExtensibility);
IO.mapOptional("FlagEnum", T.FlagEnum);
IO.mapOptional("EnumKind", T.EnumConvenienceKind);
}
};
} // namespace yaml
} // namespace llvm
namespace {
struct Typedef {
StringRef Name;
AvailabilityItem Availability;
StringRef SwiftName;
Optional<bool> SwiftPrivate;
Optional<StringRef> SwiftBridge;
Optional<StringRef> NSErrorDomain;
Optional<SwiftNewTypeKind> SwiftType;
};
typedef std::vector<Typedef> TypedefsSeq;
} // namespace
LLVM_YAML_IS_SEQUENCE_VECTOR(Typedef)
namespace llvm {
namespace yaml {
template <> struct ScalarEnumerationTraits<SwiftNewTypeKind> {
static void enumeration(IO &IO, SwiftNewTypeKind &SWK) {
IO.enumCase(SWK, "none", SwiftNewTypeKind::None);
IO.enumCase(SWK, "struct", SwiftNewTypeKind::Struct);
IO.enumCase(SWK, "enum", SwiftNewTypeKind::Enum);
}
};
template <> struct MappingTraits<Typedef> {
static void mapping(IO &IO, Typedef &T) {
IO.mapRequired("Name", T.Name);
IO.mapOptional("Availability", T.Availability.Mode,
APIAvailability::Available);
IO.mapOptional("AvailabilityMsg", T.Availability.Msg, StringRef(""));
IO.mapOptional("SwiftPrivate", T.SwiftPrivate);
IO.mapOptional("SwiftName", T.SwiftName, StringRef(""));
IO.mapOptional("SwiftBridge", T.SwiftBridge);
IO.mapOptional("NSErrorDomain", T.NSErrorDomain);
IO.mapOptional("SwiftWrapper", T.SwiftType);
}
};
} // namespace yaml
} // namespace llvm
namespace {
struct TopLevelItems {
ClassesSeq Classes;
ClassesSeq Protocols;
FunctionsSeq Functions;
GlobalVariablesSeq Globals;
EnumConstantsSeq EnumConstants;
TagsSeq Tags;
TypedefsSeq Typedefs;
};
} // namespace
namespace llvm {
namespace yaml {
static void mapTopLevelItems(IO &IO, TopLevelItems &TLI) {
IO.mapOptional("Classes", TLI.Classes);
IO.mapOptional("Protocols", TLI.Protocols);
IO.mapOptional("Functions", TLI.Functions);
IO.mapOptional("Globals", TLI.Globals);
IO.mapOptional("Enumerators", TLI.EnumConstants);
IO.mapOptional("Tags", TLI.Tags);
IO.mapOptional("Typedefs", TLI.Typedefs);
}
} // namespace yaml
} // namespace llvm
namespace {
struct Versioned {
VersionTuple Version;
TopLevelItems Items;
};
typedef std::vector<Versioned> VersionedSeq;
} // namespace
LLVM_YAML_IS_SEQUENCE_VECTOR(Versioned)
namespace llvm {
namespace yaml {
template <> struct MappingTraits<Versioned> {
static void mapping(IO &IO, Versioned &V) {
IO.mapRequired("Version", V.Version);
mapTopLevelItems(IO, V.Items);
}
};
} // namespace yaml
} // namespace llvm
namespace {
struct Module {
StringRef Name;
AvailabilityItem Availability;
TopLevelItems TopLevel;
VersionedSeq SwiftVersions;
llvm::Optional<bool> SwiftInferImportAsMember = {llvm::None};
LLVM_DUMP_METHOD void dump() /*const*/;
};
} // namespace
namespace llvm {
namespace yaml {
template <> struct MappingTraits<Module> {
static void mapping(IO &IO, Module &M) {
IO.mapRequired("Name", M.Name);
IO.mapOptional("Availability", M.Availability.Mode,
APIAvailability::Available);
IO.mapOptional("AvailabilityMsg", M.Availability.Msg, StringRef(""));
IO.mapOptional("SwiftInferImportAsMember", M.SwiftInferImportAsMember);
mapTopLevelItems(IO, M.TopLevel);
IO.mapOptional("SwiftVersions", M.SwiftVersions);
}
};
} // namespace yaml
} // namespace llvm
void Module::dump() {
llvm::yaml::Output OS(llvm::errs());
OS << *this;
}
namespace {
bool parseAPINotes(StringRef YI, Module &M, llvm::SourceMgr::DiagHandlerTy Diag,
void *DiagContext) {
llvm::yaml::Input IS(YI, nullptr, Diag, DiagContext);
IS >> M;
return static_cast<bool>(IS.error());
}
} // namespace
bool clang::api_notes::parseAndDumpAPINotes(StringRef YI,
llvm::raw_ostream &OS) {
Module M;
if (parseAPINotes(YI, M, nullptr, nullptr))
return true;
llvm::yaml::Output YOS(OS);
YOS << M;
return false;
}
| 30.816361 | 80 | 0.721437 | jhh67 |
a416992d74323ce478fd892fdfda3f79a2e49ba5 | 6,131 | cpp | C++ | SOURCE/allProjects/car_data/car_dataBase_tree/carBinaryTree.cpp | llanesjuan/AllMyProjects | 5944b248ae8f4f84cfea9fcf379f877909372551 | [
"MIT"
] | null | null | null | SOURCE/allProjects/car_data/car_dataBase_tree/carBinaryTree.cpp | llanesjuan/AllMyProjects | 5944b248ae8f4f84cfea9fcf379f877909372551 | [
"MIT"
] | null | null | null | SOURCE/allProjects/car_data/car_dataBase_tree/carBinaryTree.cpp | llanesjuan/AllMyProjects | 5944b248ae8f4f84cfea9fcf379f877909372551 | [
"MIT"
] | null | null | null | #include"carBinaryTree.h"
#include"binarySearchTree.h"
#include"binaryTreeType.h"
#include"carType.h"
#include<string>
#include<fstream>
#include<vector>
using namespace std;
void carBinaryTree::genSearch() {
int count = 0;
string make;
string id;
string model;
string year;
string engine;
string door;
string drive;
string fuelType;
string trim;
string trans;
string condition;
string price;
//int inStock;
cout << "Enter Make\n";
getline(cin, make);
cout << "enter id\n";
getline(cin, id);
cout << "Enter Model\n";
getline(cin, model);
cout << "enter Year\n";
getline(cin, year);
cout << "Enter engine\n";
getline(cin, engine);
cout << "Enter number of doors\n";
getline(cin, door);
cout << "Enter type of Drive\n";
getline(cin, drive);
cout << "Enter Fuel type\n";
getline(cin, fuelType);
cout << "enter Trim\n";
getline(cin, trim);
cout << "Enter type of Transmission\n";
getline(cin, trans);
cout << "Enter condition\n";
getline(cin, condition);
int countCar = 0;
binaryTreeNode<carType>* current = root;
if (current == NULL) {
cout << " No cars in archive\n";
return ;
}
genSearchRec(current, count, make, model, year, engine, door, drive, fuelType, trim, trans, condition, price);
cout << "Number of car encounterd; " << count << endl;
}
void carBinaryTree::genSearchRec(binaryTreeNode<carType>* current,int& count,string make, string model, string year, string engine,
string door, string drive, string fuelType, string trim, string trans, string condition, string price) {
if(current){
if ((current->info.getMake() == make || make == "") && (current->info.getModel() == model || model == "") &&
(current->info.getYear() == year || year == "") &&(current->info.getEngine()==engine||engine=="") &&
(current->info.getDoor()==door||door=="")&&(current->info.getDrive()==drive||drive=="")&&(current->info.getFuel()==fuelType||fuelType=="")&&
(current->info.getTrim() == trim || trim == "") && (current->info.getTrans() == trans || trans == "") &&
(current->info.getCond() == condition || condition == "") && (current->info.getPrice() == price || price == "")) {
count+=current->info.getInStock();
cout << current->info;
}
genSearchRec(current->llink,count, make, model, year, engine, door, drive, fuelType, trim, trans, condition, price);
genSearchRec(current->rlink,count, make, model, year, engine, door, drive, fuelType, trim, trans, condition, price);
}
}
void carBinaryTree::searchCarList(string make, bool& found, binaryTreeNode<carType>* ¤t)const
{
found = false;
current = root;
if (current == NULL) //the tree is empty
cout << "Cannot search an empty tree. " << endl;
else
{
found = false; //set found to false
while (!found && current != NULL) //search the tree
if(current->info.getMake()==make)
found = true;
else if (current->info.getMake() > make)
current = current->llink;
else
current = current->rlink;
} //end else
}
void carBinaryTree::searchCarListId(string make,string id, bool& found, binaryTreeNode<carType>* ¤t)const
{
found = false;
current = root;
if (current == NULL) //the tree is empty
cout << "Cannot search an empty tree. " << endl;
else
{
found = false; //set found to false
while (!found && current != NULL) //search the tree
if (current->info.getId() == id)
found = true;
else if (current->info.getMake() > make)
current = current->llink;
else
current = current->rlink;
} //end else
}
void carBinaryTree::inorderMake(binaryTreeNode<carType> *p)
{
if (p != NULL)
{
inorderMake(p->llink);
p->info.printMake();
inorderMake(p->rlink);
}
}
void carBinaryTree::carPrintMake()
{
inorderMake(root);
}
bool carBinaryTree::isCarAvailable(string title) const
{
bool found;
binaryTreeNode<carType> *location;
searchCarList(title, found, location);
if (found)
found = (location->info.getInStock() > 0);
else
found = false;
return found;
}
void carBinaryTree::carCheckIn(string make,string id)
{
bool found = false;
binaryTreeNode<carType> *location;
searchCarListId(make,id, found, location);
if (found)
location->info.checkIn();
else
cout << "The store does not carry " << make
<< endl;
}
void carBinaryTree::carCheckOut(string make,string id)
{
bool found = false;
binaryTreeNode<carType> *location;
searchCarListId(make,id, found, location);
if (found)
location->info.checkOut();
else
cout << "The store does not carry " << make
<< endl;
}
bool carBinaryTree::carCheckMake(string make) const
{
bool found = false;
binaryTreeNode<carType> *location;
searchCarList(make, found, location); //search the list
return found;
}
void carBinaryTree::carUpdateInStock(string make, int num)
{
bool found = false;
binaryTreeNode<carType> *location;
searchCarList(make, found, location); //search the list
if (found)
location->info.updateInStock(num);
else
cout << "The store does not carry " << make
<< endl;
}
void carBinaryTree::carSetCarInStock(string make, int num)
{
bool found = false;
binaryTreeNode<carType> *location;
searchCarList(make, found, location);
if (found)
location->info.setCopiesInStock(num);
else
cout << "The store does not carry " << make
<< endl;
}
bool carBinaryTree::carSearch(string make) const
{
bool found = false;
binaryTreeNode<carType> *location;
searchCarList(make, found, location);
return found;
}
void carBinaryTree::saveCarTree() {
binaryTreeNode<carType>* current = root;
ofstream outfile;
outfile.open(saveAddress);
savePreorder(current,outfile);
outfile.close();
}
void carBinaryTree::saveCarTreeTest() {
binaryTreeNode<carType>* current = root;
ofstream outfile;
outfile.open(saveAddressTest);
savePreorder(current, outfile);
outfile.close();
}
void carBinaryTree::savePreorder( binaryTreeNode<carType>* p,ofstream& outfile)
{
if (p != NULL) {
outfile << p->info << endl;
savePreorder(p->llink,outfile);
savePreorder(p->rlink,outfile);
}
}
void carBinaryTree::setSaveAddress(string addInput) {
saveAddress = addInput;
}
void carBinaryTree::setSaveAddressTest(string addInput) {
saveAddressTest = addInput;
}
| 27.493274 | 143 | 0.686185 | llanesjuan |
a41b27829873d759cadc2158f6c017d2024d36da | 568 | cpp | C++ | Typhoon/Src/Typhoon/Timestep.cpp | Stangui/TyphoonEngine | 20dfdac4ded598ebbc26a48acc5d0d1adc97c833 | [
"Apache-2.0"
] | null | null | null | Typhoon/Src/Typhoon/Timestep.cpp | Stangui/TyphoonEngine | 20dfdac4ded598ebbc26a48acc5d0d1adc97c833 | [
"Apache-2.0"
] | null | null | null | Typhoon/Src/Typhoon/Timestep.cpp | Stangui/TyphoonEngine | 20dfdac4ded598ebbc26a48acc5d0d1adc97c833 | [
"Apache-2.0"
] | null | null | null | #include "TyphoonPCH.h"
#include "Timestep.h"
#include "Typhoon/Core.h"
#if TE_PLATFORM_WINDOWS
#include "Platform/Windows/WindowsTimestep.h"
#endif ////TE_PLATFORM_WINDOWS
namespace TyphoonEngine
{
Timestep* Timestep::Create()
{
#if TE_PLATFORM_WINDOWS
return new WindowsTimestep();
#endif ////TE_PLATFORM_WINDOWS
#if TE_PLATFORM_LINUX
return new LinuxTimestep();
#endif ////TE_PLATFORM_WINDOWS
#if TE_PLATFORM_MACOS
return new MacOSTimestep();
#endif ////TE_PLATFORM_WINDOWS
TE_ASSERT( false, "Unsupported timestep platform!" );
return nullptr;
}
}
| 20.285714 | 55 | 0.762324 | Stangui |
a41ff93d55a486a613bbe6fe4887358d42122ae3 | 411 | cpp | C++ | Practice Programs/small_factorials.cpp | C-Nikks/CPP_Language_Programs | e3ed1990aedd6b41f2746cdab7661c40f24d5588 | [
"MIT"
] | 3 | 2021-02-04T17:59:00.000Z | 2022-01-29T17:21:42.000Z | Practice Programs/small_factorials.cpp | C-Nikks/CPP_Language_Programs | e3ed1990aedd6b41f2746cdab7661c40f24d5588 | [
"MIT"
] | null | null | null | Practice Programs/small_factorials.cpp | C-Nikks/CPP_Language_Programs | e3ed1990aedd6b41f2746cdab7661c40f24d5588 | [
"MIT"
] | 3 | 2021-10-02T14:38:21.000Z | 2021-10-05T06:19:22.000Z | #include <iostream>
using namespace std;
int fact(int n)
{
int f = n;
while (f != 1)
{
n = n * (f - 1);
f--;
}
return n;
}
int main()
{
int t, n;
cin >> t;
int arr[t];
for (int i = 1; i <= t; i++)
{
cin >> n;
arr[i] = fact(n);
}
for (int i = 1; i <= t; i++)
{
cout << endl
<< arr[i];
}
return 0;
} | 13.7 | 32 | 0.350365 | C-Nikks |
a4202259b3eb2128d67232881e1f8772fb155cb3 | 5,365 | cpp | C++ | src/cell-simulation/core/engine.cpp | firestack/cell-simulation | 11eacc685afe7c283c1fc2ed6f8b312785f45f98 | [
"MIT"
] | null | null | null | src/cell-simulation/core/engine.cpp | firestack/cell-simulation | 11eacc685afe7c283c1fc2ed6f8b312785f45f98 | [
"MIT"
] | null | null | null | src/cell-simulation/core/engine.cpp | firestack/cell-simulation | 11eacc685afe7c283c1fc2ed6f8b312785f45f98 | [
"MIT"
] | null | null | null | #include "engine.h"
// Standard includes.
#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>
// SFML includes.
#include <SFML/OpenGL.hpp>
#include <SFML/Window/Keyboard.hpp>
// Project includes.
#include "content.h"
#include "console.h"
Engine::Engine() :
m_avgRenderTime(0.0f),
m_avgRenderAcc(0.0f),
m_avgRenderCounter(1.0f),
m_avgUpdateTime(0.0f),
m_avgUpdateAcc(0.0f),
m_avgUpdateCounter(1.0f),
m_fps(0),
m_fpsTicks(0),
m_maxDeltaTime(0.0f),
m_entityTrackingIndex(0)
{ }
Engine::~Engine()
{ }
bool Engine::initialize()
{
time_t t;
time(&t);
srand(t);
// Initialize and load the content before we create the rest of the objects
// Since they may need to use them.
if(!Content::initialize()) {
return false;
}
m_debugText = new sf::Text();
m_debugText->setPosition(1.0f, 1.0f);
m_debugText->setCharacterSize(16);
m_debugText->setStyle(sf::Text::Bold);
m_debugText->setFont(*Content::font);
m_shader = Content::shader;
if (!m_world.initialize()) {
return false;
}
m_camera.trackEntity(m_world.getEntities()[0]);
return m_ircBot.initialize();
}
void Engine::destroy()
{
m_ircBot.destroy();
if (m_debugText)
delete m_debugText;
Console::destroy();
m_world.destroy();
Content::destroy();
}
void Engine::resize(const uint32 width, const uint32 height)
{
m_textView = sf::View(sf::FloatRect(sf::Vector2f(), sf::Vector2f(width, height)));
m_camera.resize(width, height);
}
void Engine::keyPress(sf::Event::KeyEvent e)
{
bool nowTracking = false;
if (e.code == sf::Keyboard::R) {
// Make sure the index is valid after adding.
m_entityTrackingIndex = (m_entityTrackingIndex + 1) % m_world.getEntityCount();
nowTracking = true;
}
else if (e.code == sf::Keyboard::T) {
// Make sure the index is valid after subtracting.
m_entityTrackingIndex = (m_entityTrackingIndex - 1) % m_world.getEntityCount();
nowTracking = true;
}
else if (e.code == sf::Keyboard::Space) {
// Make sure the index is valid.
m_entityTrackingIndex = (m_entityTrackingIndex) % m_world.getEntityCount();
nowTracking = true;
}
else if (e.code == sf::Keyboard::I) {
// Swap the debug flag.
m_world.setDebug(!m_world.getDebug());
}
if (nowTracking) {
Entity* entity = m_world.getEntity(m_entityTrackingIndex);
uint32 counter = 0;
while(entity->getType() != type::Cell && counter < m_world.getEntityCount()) {
m_entityTrackingIndex = (m_entityTrackingIndex + 1) % m_world.getEntityCount();
entity = m_world.getEntity(m_entityTrackingIndex);
counter++;
}
if (entity)
m_camera.trackEntity(entity);
}
}
void Engine::update(const float dt)
{
// Begin the measuring the time for this update cycle.
m_updateTimer.restart();
m_camera.applyKeyboardControls(dt);
m_world.update(dt);
m_camera.update(dt);
// Update the average update time.
m_avgUpdateAcc += m_updateTimer.getElapsedTime().asSeconds();
m_avgUpdateCounter++;
m_avgUpdateTime = m_avgUpdateAcc / m_avgUpdateCounter;
// Reset the average update counter after so many.
/*if (m_avgUpdateCounter > 2500) {
m_avgUpdateCounter = 1.0f;
m_avgUpdateAcc = 0.0f;
}*/
Console::update();
if (dt > m_maxDeltaTime) {
m_maxDeltaTime = dt;
}
}
void Engine::updateDebugInfo()
{
if (m_debugTextTimer.getElapsedTime().asSeconds() >= 0.2) {
m_debugTextTimer.restart();
std::stringstream str;
str << std::fixed << std::setprecision(8);
str << "avg rtime: " << m_avgRenderTime << std::endl;
str << "avg utime: " << m_avgUpdateTime << std::endl;
str << std::setprecision(2);
str << "fps: " << m_fps << std::endl;
str << "max dt: " << m_maxDeltaTime << std::endl;
//str << "scale: " << m_worldScale << std::endl;
vec2f cameraLocation = m_camera.getLocation();
str << "cam offset: (x: " << cameraLocation.x << ", y: " << cameraLocation.y << ")" << std::endl;
m_debugText->setString(str.str());
}
}
void Engine::render(sf::RenderTarget& target)
{
// Being the measuring the time for this render cycle.
m_renderTimer.restart();
// Make sure we have updated d
updateDebugInfo();
// Draw stuff here in the world view.
m_world.render(target, m_camera, m_textView);
// Update the view so we see text properly.
target.setView(m_textView);
target.draw(*m_debugText);
Console::render(target);
// Reset the average render counter after so many.
/*if (m_avgRenderCounter > 2500) {
m_avgRenderCounter = 1.0f;
m_avgRenderAcc = 0.0f;
}*/
// Average the render time measured with the render time.
m_avgRenderAcc += m_renderTimer.getElapsedTime().asSeconds();
m_avgRenderCounter++;
m_avgRenderTime = m_avgRenderAcc / m_avgRenderCounter;
// Update the frame counter too. we don't really need it but why not.
m_fpsTicks++;
if (m_fpsTimer.getElapsedTime().asSeconds() >= 1.0f) {
m_fpsTimer.restart();
m_fps = m_fpsTicks;
m_fpsTicks = 0;
}
}
| 25.306604 | 105 | 0.627213 | firestack |
a424e61811f8df783ec4a974ca1cc6f0f4378a57 | 4,576 | hpp | C++ | slope/slope/math/vector3.hpp | muleax/slope | 254138703163705b57332fc7490dd2eea0082b57 | [
"MIT"
] | 6 | 2022-02-05T23:28:12.000Z | 2022-02-24T11:08:04.000Z | slope/slope/math/vector3.hpp | muleax/slope | 254138703163705b57332fc7490dd2eea0082b57 | [
"MIT"
] | null | null | null | slope/slope/math/vector3.hpp | muleax/slope | 254138703163705b57332fc7490dd2eea0082b57 | [
"MIT"
] | null | null | null | #pragma once
#include "slope/math/math_utils.hpp"
namespace slope {
class vec3 {
public:
static constexpr vec3 zero() { return {}; }
constexpr vec3() : x(0.f), y(0.f), z(0.f) {}
explicit constexpr vec3(float all) : x(all), y(all), z(all) {}
constexpr vec3(float x, float y, float z) : x(x), y(y), z(z) {}
constexpr vec3 operator+(const vec3& rhs) const { return {x + rhs.x, y + rhs.y, z + rhs.z }; }
constexpr vec3 operator-(const vec3& rhs) const { return {x - rhs.x, y - rhs.y, z - rhs.z }; }
constexpr vec3& operator+=(const vec3& value);
constexpr vec3& operator-=(const vec3& value);
friend constexpr vec3 operator*(float lhs, const vec3& rhs) { return {lhs * rhs.x, lhs * rhs.y, lhs * rhs.z }; }
constexpr vec3 operator*(float rhs) const { return rhs * *this; }
constexpr vec3 operator/(float rhs) const { return {x / rhs, y / rhs, z / rhs }; }
constexpr vec3& operator*=(float value);
constexpr vec3& operator/=(float value);
constexpr vec3 operator-() const { return {-x, -y, -z }; }
constexpr bool operator==(const vec3& value) const { return x == value.x && y == value.y && z == value.z; }
constexpr bool operator!=(const vec3& value) const { return x != value.x || y != value.y || z != value.z; }
constexpr float& operator[](size_t index) { return data[index]; }
constexpr const float& operator[](size_t index) const { return data[index]; }
void set_zero();
constexpr float dot(const vec3& rhs) const { return x * rhs.x + y * rhs.y + z * rhs.z; }
constexpr vec3 cross(const vec3& rhs) const;
constexpr float length_squared() const { return sqr(x) + sqr(y) + sqr(z); }
float length() const { return std::sqrt(length_squared()); }
constexpr float square_distance(const vec3& rhs) const;
float distance(const vec3& rhs) const { return std::sqrt(square_distance(rhs)); }
vec3 normalized() const;
bool is_zero() const { return x == 0.f && y == 0.f && z == 0.f; }
bool is_finite() const { return std::isfinite(x) && std::isfinite(y) && std::isfinite(z); }
constexpr bool equal(const vec3& rhs, float epsilon = EQUALITY_EPSILON) const;
constexpr bool equal(float rhs, float epsilon = EQUALITY_EPSILON) const;
union {
struct {
float x, y, z;
};
float data[3]{};
};
};
constexpr vec3 lerp(const vec3& from, const vec3& to, float factor)
{
return from + (to - from) * factor;
}
inline vec3 min(const vec3& lhs, const vec3& rhs)
{
return {std::fmin(lhs.x, rhs.x), std::fmin(lhs.y, rhs.y), std::fmin(lhs.z, rhs.z)};
}
inline vec3 max(const vec3& lhs, const vec3& rhs)
{
return {std::fmax(lhs.x, rhs.x), std::fmax(lhs.y, rhs.y), std::fmax(lhs.z, rhs.z)};
}
inline vec3 vec3::normalized() const
{
float multiplier = 1.f / length();
return {x * multiplier, y * multiplier, z * multiplier};
}
constexpr vec3& vec3::operator+=(const vec3& value)
{
x += value.x;
y += value.y;
z += value.z;
return *this;
}
constexpr vec3& vec3::operator-=(const vec3& value)
{
x -= value.x;
y -= value.y;
z -= value.z;
return *this;
}
constexpr vec3& vec3::operator*=(float value)
{
x *= value;
y *= value;
z *= value;
return *this;
}
constexpr vec3& vec3::operator/=(float value)
{
float rcp = 1.f / value;
x *= rcp;
y *= rcp;
z *= rcp;
return *this;
}
inline void vec3::set_zero()
{
x = 0.f;
y = 0.f;
z = 0.f;
}
constexpr vec3 vec3::cross(const vec3& rhs) const
{
return {y * rhs.z - z * rhs.y,
z * rhs.x - x * rhs.z,
x * rhs.y - y * rhs.x};
}
constexpr float vec3::square_distance(const vec3& rhs) const
{
return sqr(x - rhs.x) + sqr(y - rhs.y) + sqr(z - rhs.z);
}
constexpr bool vec3::equal(const vec3& rhs, float epsilon) const
{
return slope::equal(x, rhs.x, epsilon) && slope::equal(y, rhs.y, epsilon) && slope::equal(z, rhs.z, epsilon);
}
constexpr bool vec3::equal(float rhs, float epsilon) const
{
return slope::equal(x, rhs, epsilon) && slope::equal(y, rhs, epsilon) && slope::equal(z, rhs, epsilon);
}
} // slope
| 32.453901 | 121 | 0.547421 | muleax |
a42765efaa4612abd78e0a55bd3947086cce6c8f | 503 | hpp | C++ | include/axl.util/Protocol.hpp | Defalt8/axl.util | 71375e37d7df5d91d813d6e0fe99416220ce4dca | [
"MIT"
] | 1 | 2021-02-12T12:48:28.000Z | 2021-02-12T12:48:28.000Z | include/axl.util/Protocol.hpp | Defalt8/axl.util | 71375e37d7df5d91d813d6e0fe99416220ce4dca | [
"MIT"
] | null | null | null | include/axl.util/Protocol.hpp | Defalt8/axl.util | 71375e37d7df5d91d813d6e0fe99416220ce4dca | [
"MIT"
] | null | null | null | #pragma once
#include "lib.hpp"
#include "types.hpp"
#include "ds/Array.hpp"
#include "ds/List.hpp"
#include "Serial.hpp"
namespace axl {
namespace util {
class AXLUTILCXXAPI Protocol
{
public:
Protocol();
virtual ~Protocol();
virtual ds::Array<byte, axl::util::ds::Allocators::Malloc<byte>> serialize(const Serial& serial) const = 0;
virtual bool deserialize(Serial& serial, const ds::Array<byte, axl::util::ds::Allocators::Malloc<byte>>& serial_data) const = 0;
};
} // axl.util
} // axl
| 21.869565 | 130 | 0.699801 | Defalt8 |
a4291633209df533c172ee350b015c3434babc47 | 9,038 | cpp | C++ | src/gtest/test-utils-basic.cpp | w5292c/mcode | bb5d09c09b54d870bcc4e6a220176168d6618f60 | [
"MIT"
] | null | null | null | src/gtest/test-utils-basic.cpp | w5292c/mcode | bb5d09c09b54d870bcc4e6a220176168d6618f60 | [
"MIT"
] | null | null | null | src/gtest/test-utils-basic.cpp | w5292c/mcode | bb5d09c09b54d870bcc4e6a220176168d6618f60 | [
"MIT"
] | 1 | 2017-04-15T09:14:33.000Z | 2017-04-15T09:14:33.000Z | /*
* The MIT License (MIT)
*
* Copyright (c) 2020 Alexander Chumakov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "utils.h"
#include <gtest/gtest.h>
using namespace testing;
class UtilsBasic : public Test
{
protected:
void SetUp() override {
}
void TearDown() override {
}
bool is_whitespace(char ch) {
return isspace(ch) || !ch;
}
bool is_numeric(char ch) {
return ch >= '0' && ch <= '9';
}
bool is_hex(char ch) {
return (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f') || is_numeric(ch);
}
};
TEST_F(UtilsBasic, MCharIsWhitespace)
{
int ch;
for (ch = 0; ch < 256; ++ch) {
const bool whitespace = char_is_whitespace(ch);
ASSERT_EQ(whitespace, is_whitespace(ch)) << "Character: [" << (char)ch << "], code: " << ch;
}
}
TEST_F(UtilsBasic, MCharIsNumeric)
{
int ch;
for (ch = 0; ch < 256; ++ch) {
ASSERT_EQ(char_is_digit(ch), is_numeric(ch)) << "Character: [" << (char)ch << "], code: " << ch;
}
}
TEST_F(UtilsBasic, MCharIsHex)
{
int ch;
for (ch = 0; ch < 256; ++ch) {
ASSERT_EQ(char_is_hex(ch), is_hex(ch)) << "Character: [" << (char)ch << "], code: " << ch;
}
}
TEST_F(UtilsBasic, GlobChToVal)
{
char ch;
uint8_t value;
for (ch = '0'; ch <= '9'; ++ch) {
value = glob_ch_to_val(ch);
ASSERT_EQ(value, ch - '0') << "Character: [" << (char)ch << "], code: " << ch;
}
for (ch = 'a'; ch <= 'f'; ++ch) {
value = glob_ch_to_val(ch);
ASSERT_EQ(value, ch - 'a' + 10) << "Character: [" << (char)ch << "], code: " << ch;
}
for (ch = 'A'; ch <= 'F'; ++ch) {
value = glob_ch_to_val(ch);
ASSERT_EQ(value, ch - 'A' + 10) << "Character: [" << (char)ch << "], code: " << ch;
}
}
TEST_F(UtilsBasic, GlobGetByte)
{
uint8_t value = glob_get_byte("9F");
ASSERT_EQ(value, 0x9fu);
value = glob_get_byte("00");
ASSERT_EQ(value, 0x00u);
value = glob_get_byte("FF");
ASSERT_EQ(value, 0xffu);
}
TEST_F(UtilsBasic, GlobStrToUint16)
{
uint16_t value = glob_str_to_uint16("0000");
ASSERT_EQ(value, 0x0000u);
value = glob_str_to_uint16("ffff");
ASSERT_EQ(value, 0xffffu);
value = glob_str_to_uint16("FFFF");
ASSERT_EQ(value, 0xffffu);
value = glob_str_to_uint16("80DE");
ASSERT_EQ(value, 0x80deu);
value = glob_str_to_uint16("1234");
ASSERT_EQ(value, 0x1234u);
value = glob_str_to_uint16("4567");
ASSERT_EQ(value, 0x4567u);
value = glob_str_to_uint16("89ab");
ASSERT_EQ(value, 0x89abu);
value = glob_str_to_uint16("cdef");
ASSERT_EQ(value, 0xcdefu);
value = glob_str_to_uint16("98BA");
ASSERT_EQ(value, 0x98bau);
value = glob_str_to_uint16("DCFE");
ASSERT_EQ(value, 0xdcfeu);
}
TEST_F(UtilsBasic, StringSkipWhitespace)
{
const char *const input1 = "abcdef qwerty";
const char *const input2 = " poiuyt asdfg";
const char *result = string_skip_whitespace(input1);
ASSERT_EQ(result, input1);
result = string_skip_whitespace(result);
ASSERT_EQ(result, input1);
result = string_skip_whitespace(input2);
ASSERT_EQ(result, input2 + 4);
result = string_skip_whitespace(result);
ASSERT_EQ(result, input2 + 4);
result = string_skip_whitespace(NULL);
ASSERT_EQ(result, (const char *)NULL);
result = string_skip_whitespace("");
ASSERT_EQ(result, (const char *)NULL);
result = string_skip_whitespace(" ");
ASSERT_EQ(result, (const char *)NULL);
result = string_skip_whitespace(" \r\n\r\f\t\v ");
ASSERT_EQ(result, (const char *)NULL);
}
TEST_F(UtilsBasic, StringNextDecimalNumber)
{
uint16_t value = 0;
const char *result = string_next_number("12345, new", &value);
ASSERT_EQ(value, 12345);
ASSERT_STREQ(result, ", new");
result = string_next_number("12345", &value);
ASSERT_EQ(value, 12345);
ASSERT_EQ(result, (const char *)NULL);
result = string_next_number("26143hello", &value);
ASSERT_EQ(value, 26143);
ASSERT_STREQ(result, "hello");
result = string_next_number("1234567890 ", &value);
ASSERT_EQ(value, 722);
ASSERT_STREQ(result, " ");
value = 0;
result = string_next_number(NULL, &value);
ASSERT_EQ(value, 0);
ASSERT_EQ(result, (const char *)NULL);
result = string_next_number("", &value);
ASSERT_EQ(value, 0);
ASSERT_EQ(result, (const char *)NULL);
}
TEST_F(UtilsBasic, StringNextHexNumber)
{
uint16_t value = 0;
const char *result = string_next_number("0x2345, old", &value);
ASSERT_EQ(value, 0x2345u);
ASSERT_STREQ(result, ", old");
result = string_next_number("0xfe10", &value);
ASSERT_EQ(value, 0xfe10u);
ASSERT_EQ(result, (const char *)NULL);
result = string_next_number("0x261fhello", &value);
ASSERT_EQ(value, 0x261fu);
ASSERT_STREQ(result, "hello");
result = string_next_number("0x1234567890abcdef ", &value);
ASSERT_EQ(value, 0xcdefu);
ASSERT_STREQ(result, " ");
}
TEST_F(UtilsBasic, StringNextToken)
{
int length = 0;
const char *result = string_next_token("word 12345678", &length);
ASSERT_EQ(length, 4);
ASSERT_STREQ(result, " 12345678");
result = string_next_token("token", &length);
ASSERT_EQ(length, 5);
ASSERT_STREQ(result, (const char *)NULL);
}
TEST_F(UtilsBasic, StringToBuffer)
{
uint8_t length = 0;
uint8_t buffer[128];
memset(buffer, 0, sizeof (buffer));
const char *result = string_to_buffer("00012ef677ff00aa", sizeof (buffer), buffer, &length);
ASSERT_EQ(buffer[0], 0x00u);
ASSERT_EQ(buffer[1], 0x01u);
ASSERT_EQ(buffer[2], 0x2eu);
ASSERT_EQ(buffer[3], 0xf6u);
ASSERT_EQ(buffer[4], 0x77u);
ASSERT_EQ(buffer[5], 0xffu);
ASSERT_EQ(buffer[6], 0x00u);
ASSERT_EQ(buffer[7], 0xaau);
ASSERT_EQ(length, 8);
ASSERT_EQ(result, (const char *)NULL);
length = 0;
memset(buffer, 0, sizeof (buffer));
result = string_to_buffer("55X", sizeof (buffer), buffer, &length);
ASSERT_EQ(buffer[0], 0x55u);
ASSERT_EQ(length, 1);
ASSERT_STREQ(result, "X");
length = 0;
memset(buffer, 0, sizeof (buffer));
result = string_to_buffer("", sizeof (buffer), buffer, &length);
ASSERT_EQ(length, 0);
ASSERT_STREQ(result, (const char *)NULL);
length = 0;
memset(buffer, 0, sizeof (buffer));
result = string_to_buffer(NULL, sizeof (buffer), buffer, &length);
ASSERT_EQ(length, 0);
ASSERT_STREQ(result, (const char *)NULL);
length = 0;
memset(buffer, 0, sizeof (buffer));
result = string_to_buffer("1234567890abcdef", 2, buffer, &length);
ASSERT_EQ(length, 2);
ASSERT_EQ(buffer[0], 0x12u);
ASSERT_EQ(buffer[1], 0x34u);
ASSERT_STREQ(result, "567890abcdef");
}
TEST_F(UtilsBasic, DISABLED_StringToBuffer)
{
/* This case is disabled, as it gives an error, needs to be fixed or removed */
uint8_t length = 0;
uint8_t buffer[128];
memset(buffer, 0, sizeof (buffer));
const char *result = string_to_buffer("123", sizeof (buffer), buffer, &length);
ASSERT_EQ(length, 1);
ASSERT_EQ(buffer[0], 0x12u);
ASSERT_STREQ(result, "3");
}
TEST_F(UtilsBasic, FromPdu7bit)
{
char buffer[256] = { 0 };
size_t length = 0;
bool res = from_pdu_7bit("F4F29C0E", -1, buffer, sizeof (buffer), &length);
ASSERT_EQ(res, true);
ASSERT_STREQ(buffer, "test");
memset(buffer, 0, sizeof (buffer));
res = from_pdu_7bit("F4F29C0EX", -1, buffer, sizeof (buffer), &length);
/* Failure is reported, as the 'X' char is illigal in this context */
ASSERT_EQ(res, false);
ASSERT_STREQ(buffer, "test");
memset(buffer, 0, sizeof (buffer));
res = from_pdu_7bit(NULL, -1, buffer, sizeof (buffer), &length);
/* Failure is reported, as the 'X' char is illigal in this context */
ASSERT_EQ(res, false);
length = 0;
memset(buffer, 0, sizeof (buffer));
res = from_pdu_7bit("F3B29BDC4ABBCD6F50AC3693B14022F2DB5D16B140381A", -1, buffer, sizeof (buffer), &length);
ASSERT_EQ(res, true);
ASSERT_STREQ(buffer, "send-info 1532, \"done\", 84");
}
TEST_F(UtilsBasic, DISABLED_FromPdu7bit)
{
char buffer[256] = { 0 };
size_t length = 0;
bool res = from_pdu_7bit("F4F29C0E", -1, buffer, 2, &length);
/* Failure is reported, as the 'X' char is illigal in this context */
ASSERT_EQ(res, true);
ASSERT_EQ(length, 2);
ASSERT_STREQ(buffer, "te");
}
| 30.430976 | 110 | 0.67526 | w5292c |
a4299f7cc284f50e31f330a24b68cce3e24b8bf5 | 889 | hpp | C++ | code/deps/osrm/include/extractor/extraction_turn.hpp | mbeckem/msc | 93e71ba163a7ffef4eec3e83934fa793f3f50ff6 | [
"MIT"
] | null | null | null | code/deps/osrm/include/extractor/extraction_turn.hpp | mbeckem/msc | 93e71ba163a7ffef4eec3e83934fa793f3f50ff6 | [
"MIT"
] | null | null | null | code/deps/osrm/include/extractor/extraction_turn.hpp | mbeckem/msc | 93e71ba163a7ffef4eec3e83934fa793f3f50ff6 | [
"MIT"
] | null | null | null | #ifndef OSRM_EXTRACTION_TURN_HPP
#define OSRM_EXTRACTION_TURN_HPP
#include <boost/numeric/conversion/cast.hpp>
#include <extractor/guidance/intersection.hpp>
#include <cstdint>
namespace osrm
{
namespace extractor
{
struct ExtractionTurn
{
ExtractionTurn(const guidance::ConnectedRoad &turn, bool has_traffic_light)
: angle(180. - turn.angle), turn_type(turn.instruction.type),
direction_modifier(turn.instruction.direction_modifier),
has_traffic_light(has_traffic_light), weight(0.), duration(0.), source_restricted(false),
target_restricted(false)
{
}
const double angle;
const guidance::TurnType::Enum turn_type;
const guidance::DirectionModifier::Enum direction_modifier;
const bool has_traffic_light;
double weight;
double duration;
bool source_restricted;
bool target_restricted;
};
}
}
#endif
| 23.394737 | 99 | 0.737908 | mbeckem |
a42f011786e6fbea57b932c544335d2d7ef78035 | 7,375 | cpp | C++ | system/apps_experiments/76_cc1101send/source/main.cpp | tomwei7/LA104 | fdf04061f37693d37e2812ed6074348e65d7e5f9 | [
"MIT"
] | 336 | 2018-11-23T23:54:15.000Z | 2022-03-21T03:47:05.000Z | system/apps_experiments/76_cc1101send/source/main.cpp | 203Null/LA104 | b8ae9413d01ea24eafb9fdb420c97511287cbd99 | [
"MIT"
] | 56 | 2019-02-01T05:01:07.000Z | 2022-03-26T16:00:24.000Z | system/apps_experiments/76_cc1101send/source/main.cpp | 203Null/LA104 | b8ae9413d01ea24eafb9fdb420c97511287cbd99 | [
"MIT"
] | 52 | 2019-02-06T17:05:04.000Z | 2022-03-04T12:30:53.000Z | #include <library.h>
#include "../../os_host/source/framework/Console.h"
#include "assert.h"
#include "device/cc1101.h"
//#include <iostream>
#include "protocol/protocol.h"
#include "protocol/weather.h"
#include "streamer/streamer.h"
#include "streamer/stm32f10x.h"
#include "graph.h"
CDeviceCC1101 gModem;
#include "send.h"
#include "thermo.h"
// 10ms -> 493 pulses
// 10 000 us = 500 pulses
// 40 pulses per ms
extern int totalSamples;
using namespace BIOS;
bool setup()
{
// srand(BIOS::SYS::GetTick());
while (1)
{
CONSOLE::Print("Init... ");
if (gModem.Init())
{
CONSOLE::Print("Ok!\n");
break;
} else
{
CONSOLE::Print("Failed!\n");
if (KEY::GetKey() == KEY::EKey::Escape)
return false;
}
}
// 433.91, 135khz, 0dB
gModem.SetFrequency(433876000UL);
gModem.DeltaGain(-100);
// gModem.DeltaGain(2); // 0..7
gModem.DeltaBandwidth(-100);
gModem.DeltaBandwidth(9); // 8:203khz, 10: 135khz, 12 -> 101khz
gModem.DeltaGain(+5); // 5:-12db
gModem.SetDataRate(4000);
// BIOS::GPIO::PinMode(BIOS::GPIO::EPin::P4, BIOS::GPIO::EMode::Input);
gModem.SetRxState();
streamerBufferMaxCounter = 4000;
streamerBegin();
return true;
}
void finish()
{
streamerEnd();
gModem.SetIdleState();
}
void Noise()
{
uint8_t buffer[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
if (!sendPacket(433876000UL, 4000, buffer, COUNT(buffer)))
{
BIOS::SYS::Beep(1000);
BIOS::SYS::DelayMs(1000);
} else
{
BIOS::SYS::Beep(50);
}
// gModem.SetRxState();
// gModem.SetDataRate(4000);
}
int signal_[100];
CArray<int> arrsignal(signal_, COUNT(signal_));
CWeather weather;
void _graphPush(int v)
{
if (v==-1)
{
arrsignal.RemoveAll();
}
else
{
if (arrsignal.GetSize() < arrsignal.GetMaxSize())
arrsignal.Add(v*25);
/*
#define Ticks(d) ((d+10)/20)
#define IsPulse(l) (Ticks(l) == 1)
#define IsSpacer(l) (Ticks(l) >= 16 && Ticks(l) < 25)
#define IsShort(l) (Ticks(l) >= 4 && Ticks(l) <= 5)
#define IsLong(l) (Ticks(l) >= 8 && Ticks(l) <= 10)
#define IsLongOrShort(l) (IsLong(l) || IsShort(l))
*/
if (arrsignal.GetSize() >= weather.MinIndentifyCount())
{
/*
if (IsPulse(signal[0]) &&
IsSpacer(signal[1]) &&
IsPulse(signal[2]) &&
IsLongOrShort(signal[3]) &&
IsPulse(signal[4]))
*/
if (weather.Identify(arrsignal))
{
BIOS::LCD::Printf(0, BIOS::LCD::Height-16-16-20, RGB565(ff0000), RGB565(0000d0), "!!!");
arrsignal.RemoveAll();
Noise();
}
}
}
graphPush(v);
}
void pulseMachinePush(int interval)
{
static int buffer = -1;
static bool bufferSet = false;
static bool transmit = false;
static int index = 0;
if (!transmit)
{
if (!bufferSet)
{
buffer = interval;
if (interval != -1)
{
bufferSet = true;
transmit = true;
}
return;
}
}
else
{
if (interval == -1)
{
if (!bufferSet)
_graphPush(-1);
bufferSet = false;
transmit = false;
return;
}
if (bufferSet)
{
index = 0;
_graphPush(buffer);
BIOS::LCD::Printf(index*32, BIOS::LCD::Height-16-16-20, RGB565(ffffff), RGB565(0000d0), "%4d", buffer);
buffer = -1;
bufferSet = false;
}
index++;
if (index < 9)
BIOS::LCD::Printf(index*32, BIOS::LCD::Height-16-16-20, RGB565(ffffff), RGB565(0000d0), "%4d", interval);
_graphPush(interval);
}
}
void pulseMachine(int interval)
{
// L:1000, H:0, L:1000, H:0, L:300, H:1000, L:0, H:1000, L:0, H:100, L:500, H:500, L:500, H:500
// -> L:2300, H:2100, L:500, H:500, L:500, H:500
// 1000,0;
static int interval1 = 0;
static int interval2 = 0;
static bool leading = true;
static bool terminated = false;
if (interval == -1)
{
// dolozit?
interval1 = 0;
interval2 = 0;
leading = true;
pulseMachinePush(-1);
return;
}
if (interval1 == 0)
{
interval += interval2;
}
if (interval > 400)
{
// if (!leading)
// pulseMachinePush(500);
if (!terminated)
{
terminated = true;
pulseMachinePush(-1);
}
leading = true; // aj tak ho potom pretlaci cez interval2!!
// interval2 = 0;
// interval1 = 0;
// return;
}
if (interval1 != 0 && interval2 != 0)
{
if (leading)
leading = false;
else
{
pulseMachinePush(interval2);
terminated = false;
}
}
interval2 = interval1;
interval1 = interval;
}
void StreamerPreview()
{
if (streamerOverrun)
{
BIOS::DBG::Print("Overflow!");
streamerOverrun = 0;
}
#ifdef __APPLE__
EVERY(100)
{
static int pulse[] = { 1000, 0, 1000, 0, 300, // leading 1300
/*1000, 0, 1000, 0,*/ 100, 500, 500, 500, 500, // data
1000, 0, 1000, 0, 1000, 0, 1000, 0, 1000, 0, 1000, 0, 300, // leading 6300
//1000, 0, 1000, 0, 100, 500, 500, 500, 500, // data
0,
1000, 0, 1000, 0, 1000, 0, 1000, 0, // trailing 4000
1000, 0, 1000, 0, 1000, 0, 1000, 0, // trailing 4000
1000, 0, 1000, 0, 1000, 0, 1000, 0, // trailing 4000
};
static int pos = 0;
streamerBuffer.push(pulse[pos++]);
if (pos >= COUNT(pulse))
pos = 0;
}
#endif
static int p = 0;
static int x=0;
int n = streamerBuffer.size();
static int lx = 0;
int by = BIOS::LCD::Height-16-20;
int c = BIOS::GPIO::DigitalRead(BIOS::GPIO::EPin::P4) ? RGB565(ffffff) : RGB565(000000);
int k = 80;
BIOS::LCD::Bar(x/k, by+2, x/k+2, by+18, c);
for (int i=0; i<n; i++, p++)
{
int v = streamerBuffer.pull();
pulseMachine(v);
/*
static bool lastLong = false;
if (v!=0)
{
if (v == 4000)
{
if (!lastLong)
{
lastLong = true;
BIOS::DBG::Print("-, ");
}
} else
{
lastLong = false;
BIOS::DBG::Print("%d, ", v);
}
}
*/
if (v > 0 && v<k) v = k;
BIOS::LCD::Bar(lx/k, by+2, (lx)/k+2, by+18, RGB565(0000b0));
BIOS::LCD::Bar(x/k, by+2, x/k+2, by+18, c);
lx = x;
int x1 = min((x+v)/k, BIOS::LCD::Width);
BIOS::LCD::Bar(x/k, by, x1, by+2, (p & 1) ? RGB565(ff0000) : RGB565(0000b0));
BIOS::LCD::Bar(x/k, by+18, x1, by+20, (p & 1) ? RGB565(0000b0) : RGB565(00ff00));
x += v;
if (x/k >= BIOS::LCD::Width)
x -= BIOS::LCD::Width * k;
}
}
void drop()
{
int n = streamerBuffer.size();
for (int i=0; i<n - (n&1); i++)
{
int v = streamerBuffer.pull();
}
}
void loop()
{
StreamerPreview();
// {EVERY(1000){ sendThermo(); CONSOLE::Print("."); }}
}
#ifdef _ARM
__attribute__((__section__(".entry")))
#endif
int _main(void)
{
CRect rcClient(0, 0, LCD::Width, LCD::Height);
LCD::Bar(rcClient, RGB565(0000b0));
CRect rc1(rcClient);
rc1.bottom = 14;
GUI::Background(rc1, RGB565(4040b0), RGB565(404040));
LCD::Print(8, rc1.top, RGB565(ffffff), RGBTRANS, "CC1101 test signal generator");
if (!setup())
return 1;
CRect rc2(rcClient);
rc2.top = rc2.bottom-14;
GUI::Background(rc2, RGB565(404040), RGB565(202020));
LCD::Printf(8, rc2.top, RGB565(808080), RGBTRANS, "F: %.1f MHz, BW: %d kHz, G: %d dB", gModem.GetFrequency() / 1e6f, gModem.GetBandwidth() / 1000, gModem.GetGain());
KEY::EKey key;
while ((key = KEY::GetKey()) != KEY::EKey::Escape)
{
static bool run = true;
if (key == KEY::EKey::F1)
run = !run;
if (run)
loop();
else
drop();
}
finish();
return 0;
}
| 20.600559 | 169 | 0.572068 | tomwei7 |
a43036417a0914982d39e989c28dae5882427f12 | 253 | cc | C++ | 13/31/31.cc | williamgherman/cpp-solutions | cf947b3b8f49fa3071fbee96f522a4228e4207b8 | [
"BSD-Source-Code"
] | 5 | 2019-08-01T07:52:27.000Z | 2022-03-27T08:09:35.000Z | 13/31/31.cc | williamgherman/cpp-solutions | cf947b3b8f49fa3071fbee96f522a4228e4207b8 | [
"BSD-Source-Code"
] | 1 | 2020-10-03T17:29:59.000Z | 2020-11-17T10:03:10.000Z | 13/31/31.cc | williamgherman/cpp-solutions | cf947b3b8f49fa3071fbee96f522a4228e4207b8 | [
"BSD-Source-Code"
] | 6 | 2019-08-24T08:55:56.000Z | 2022-02-09T08:41:44.000Z | #include <iostream>
#include <vector>
#include <algorithm>
#include "HasPtr.h"
using std::swap;
int main()
{
HasPtr a("Hello"), b("World!"), c("Goodbye");
std::vector<HasPtr> hps{a,b,c};
std::sort(hps.begin(), hps.end());
return 0;
}
| 15.8125 | 49 | 0.600791 | williamgherman |
a43437f7efe43aff64f046b3c1a2dc6df2f197ec | 10,405 | cpp | C++ | drivers/ksfilter/ks/kslog.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | drivers/ksfilter/ks/kslog.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | drivers/ksfilter/ks/kslog.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (C) Microsoft Corporation, 1998 - 1999
Module Name:
kslog.cpp
Abstract:
This module contains the KS logging implementation.
Author:
Dale Sather (DaleSat) 10-May-1999
--*/
#include "ksp.h"
#include "stdarg.h"
#ifdef ALLOC_DATA_PRAGMA
#pragma const_seg("PAGECONST")
#endif // ALLOC_DATA_PRAGMA
#ifdef ALLOC_PRAGMA
#pragma code_seg("PAGE")
#endif // ALLOC_PRAGMA
#if DBG
extern "C" PVOID KsLog = NULL;
extern "C" ULONG KsLogSize = (1024*64);
extern "C" ULONG KsLogPosition = 0;
extern "C" ULONGLONG KsLogTicksPerSecond = 0;
#define STRW_DEVICENAME TEXT("\\Device\\KsLog")
#define STRW_LINKNAME TEXT("\\DosDevices\\KsLog")
extern "C"
NTKERNELAPI
NTSTATUS
IoCreateDriver (
IN PUNICODE_STRING DriverName OPTIONAL,
IN PDRIVER_INITIALIZE InitializationFunction
);
NTSTATUS
KsLogDispatchCreate(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp
)
{
PAGED_CODE();
ASSERT(DeviceObject);
ASSERT(Irp);
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(Irp);
irpSp->FileObject->FsContext = ULongToPtr(0);
Irp->IoStatus.Status = STATUS_SUCCESS;
IoCompleteRequest(Irp,IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
NTSTATUS
KsLogDispatchClose(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp
)
{
Irp->IoStatus.Status = STATUS_SUCCESS;
IoCompleteRequest(Irp,IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
//
// mmGetSystemAddressForMdl() is defined as a macro in wdm.h which
// calls mmMapLockedPages() which is treated as an evil by verifier.
// mmMapLockedPages is reimplemented by mm via
// mmMapLockedPagesSpecifyCache(MDL,Mode,mmCaches,NULL,TRUE,HighPriority)
// where TRUE is to indicate a bug check, should the call fails.
// I don't need the bug check, therefore, I specify FALSE below.
//
#define KsGetSystemAddressForMdl(MDL) \
(((MDL)->MdlFlags & (MDL_MAPPED_TO_SYSTEM_VA | \
MDL_SOURCE_IS_NONPAGED_POOL)) ? \
((MDL)->MappedSystemVa) : \
(MmMapLockedPagesSpecifyCache((MDL), \
KernelMode, \
MmCached, \
NULL, \
FALSE, \
HighPagePriority)))
NTSTATUS
KsLogDispatchRead(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp
)
{
PAGED_CODE();
ASSERT(DeviceObject);
ASSERT(Irp);
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(Irp);
ULONG prevPosition = PtrToUlong(irpSp->FileObject->FsContext);
ULONG position = (ULONG)
InterlockedExchange(
PLONG(&KsLogPosition),
LONG(KsLogPosition));
//
// Either kind of wrapping results in the position getting reset.
//
if ((prevPosition > position) || (prevPosition + KsLogSize < position)) {
prevPosition = position;
}
ULONG remaining = irpSp->Parameters.Read.Length;
ULONG copied = 0;
PUCHAR dest;
if ( NULL != Irp->MdlAddress &&
NULL != (dest = PUCHAR(KsGetSystemAddressForMdl(Irp->MdlAddress)))) {
//
// When remaining is 0, we have a null MdlAddress. Check before leap.
// MmGetSystemAddressForMdl requires allocation of resources, i.e.
// it could fail. Might be even better to use
// MmMapLockedPagesSpecifyCache() instead to avoid possible bugcheck.
//
while (1) {
position = (ULONG)
InterlockedExchange(
PLONG(&KsLogPosition),
LONG(KsLogPosition));
ULONG modPosition = prevPosition % KsLogSize;
ULONG toCopy = position - prevPosition;
if (toCopy > remaining) {
toCopy = remaining;
}
if (toCopy > KsLogSize - modPosition) {
toCopy = KsLogSize - modPosition;
}
if (! toCopy) {
break;
}
RtlCopyMemory(dest,PUCHAR(KsLog) + modPosition,toCopy);
remaining -= toCopy;
copied += toCopy;
dest += toCopy;
prevPosition += toCopy;
}
}
irpSp->FileObject->FsContext = ULongToPtr(prevPosition);
Irp->IoStatus.Information = copied;
Irp->IoStatus.Status = STATUS_SUCCESS;
IoCompleteRequest(Irp,IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
NTSTATUS
_KsLogDriverEntry(
IN PDRIVER_OBJECT DriverObject,
IN PUNICODE_STRING RegistryPath
)
{
ASSERT(DriverObject);
DriverObject->DriverUnload = KsNullDriverUnload;
DriverObject->MajorFunction[IRP_MJ_CREATE] = KsLogDispatchCreate;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = KsLogDispatchClose;
DriverObject->MajorFunction[IRP_MJ_READ] = KsLogDispatchRead;
UNICODE_STRING deviceName;
RtlInitUnicodeString(&deviceName,STRW_DEVICENAME);
PDEVICE_OBJECT deviceObject;
NTSTATUS status =
IoCreateDevice(
DriverObject,
0,
&deviceName,
FILE_DEVICE_KS,
FILE_DEVICE_SECURE_OPEN,
FALSE,
&deviceObject);
if (! NT_SUCCESS(status)) {
_DbgPrintF(DEBUGLVL_TERSE,("Failed to create KS log device (%p)",status));
return status;
}
UNICODE_STRING linkName;
RtlInitUnicodeString(&linkName,STRW_LINKNAME);
status = IoCreateSymbolicLink(&linkName,&deviceName);
if (NT_SUCCESS(status)) {
deviceObject->Flags |= DO_DIRECT_IO;
deviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
} else {
_DbgPrintF(DEBUGLVL_TERSE,("Failed to create KS log symbolic link (%p)",status));
return status;
}
return STATUS_SUCCESS;
}
void
_KsLogInit(
void
)
{
KsLog = ExAllocatePoolWithTag(NonPagedPool,KsLogSize,'gLsK');
if (KsLog) {
RtlZeroMemory(KsLog,KsLogSize);
}
LARGE_INTEGER tps;
KeQueryPerformanceCounter(&tps);
KsLogTicksPerSecond = tps.QuadPart;
NTSTATUS status = IoCreateDriver(NULL,_KsLogDriverEntry);
if (! NT_SUCCESS(status)) {
_DbgPrintF(DEBUGLVL_TERSE,("Failed to create KS log driver (%p)",status));
}
}
void
_KsLogInitContext(
OUT PKSLOG_ENTRY_CONTEXT Context,
IN PKSPIN Pin OPTIONAL,
IN PVOID Component OPTIONAL
)
{
ASSERT(Context);
if (Pin) {
Context->Graph = NULL;
Context->Filter = ULONG_PTR(KspFilterInterface(KsPinGetParentFilter(Pin)));
Context->Pin = ULONG_PTR(KspPinInterface(Pin));
} else {
Context->Graph = NULL;
Context->Filter = NULL;
Context->Pin = NULL;
}
Context->Component = ULONG_PTR(Component);
}
#ifdef ALLOC_PRAGMA
#pragma code_seg()
#endif // ALLOC_PRAGMA
void
_KsLog(
IN PKSLOG_ENTRY_CONTEXT Context OPTIONAL,
IN ULONG Code,
IN ULONG_PTR Irp,
IN ULONG_PTR Frame,
IN PKSLOG_ENTRY Entry
)
{
if (! Entry) {
return;
}
if (Context) {
RtlCopyMemory(&Entry->Context,Context,sizeof(Entry->Context));
} else {
RtlZeroMemory(&Entry->Context,sizeof(Entry->Context));
}
Entry->Code = Code;
Entry->Irp = Irp;
Entry->Frame = Frame;
}
PKSLOG_ENTRY
_KsLogEntry(
IN ULONG ExtSize,
IN PVOID Ext OPTIONAL
)
{
ASSERT((ExtSize != 0) || (Ext == NULL));
if (! KsLog) {
return NULL;
}
ULONGLONG time = KeQueryPerformanceCounter(NULL).QuadPart;
//
// Size must be aligned and must include an appended size field.
//
ULONG size = (sizeof(KSLOG_ENTRY) + ExtSize + sizeof(ULONG) + FILE_QUAD_ALIGNMENT) & ~FILE_QUAD_ALIGNMENT;
while (1) {
//
// Determine the current position. This may change because we have no
// lock on it.
//
ULONG position = (ULONG)
InterlockedExchange(
PLONG(&KsLogPosition),
LONG(KsLogPosition));
ULONG modPosition = position % KsLogSize;
//
// See if there is enough room for this entry.
//
if (modPosition + size > KsLogSize) {
//
// No. Try to fill up the remaining space.
//
if (InterlockedCompareExchange(
PLONG(&KsLogPosition),
0,
LONG(position)) == LONG(position)) {
//
// Captured the space we want to fill. Fill it.
//
PULONG p = PULONG(PUCHAR(KsLog) + modPosition);
for (ULONG count = (KsLogSize - modPosition) / sizeof(ULONG); count--; p++) {
*p = FILE_QUAD_ALIGNMENT + 1;
}
}
continue;
}
//
// Try to capture space for the entry.
//
if (InterlockedCompareExchange(
PLONG(&KsLogPosition),
LONG(position + size),
LONG(position)) == LONG(position)) {
//
// Captured the space. Store what we can.
//
PKSLOG_ENTRY entry = PKSLOG_ENTRY(PUCHAR(KsLog) + modPosition);
entry->Size = size;
entry->Time = (time * 1000000) / KsLogTicksPerSecond;
*PULONG(PUCHAR(entry) + size - sizeof(ULONG)) = size;
if (Ext) {
RtlCopyMemory(entry + 1,Ext,ExtSize);
}
return entry;
}
}
return NULL;
}
PKSLOG_ENTRY
_KsLogEntryF(
IN PCHAR Format OPTIONAL,
...
)
{
if (! KsLog) {
return NULL;
}
CHAR buffer[512];
ULONG stringSize;
//
// Determine the size of the entry.
//
if (Format) {
va_list arglist;
va_start(arglist,Format);
stringSize = _vsnprintf(buffer,sizeof(buffer),Format,arglist);
va_end(arglist);
} else {
stringSize = 0;
}
return _KsLogEntry(stringSize,buffer);
}
#endif // DBG
| 26.0125 | 111 | 0.568477 | npocmaka |
bf9b104472bcefe28c992610950f81700cce588a | 13,674 | cpp | C++ | fboss/agent/hw/test/ConfigFactory.cpp | midopooler/fboss | c8d08dd4255e97e5977f53712e7c91a7d045a0cb | [
"BSD-3-Clause"
] | null | null | null | fboss/agent/hw/test/ConfigFactory.cpp | midopooler/fboss | c8d08dd4255e97e5977f53712e7c91a7d045a0cb | [
"BSD-3-Clause"
] | null | null | null | fboss/agent/hw/test/ConfigFactory.cpp | midopooler/fboss | c8d08dd4255e97e5977f53712e7c91a7d045a0cb | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2004-present, 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 "fboss/agent/hw/test/ConfigFactory.h"
#include "fboss/agent/FbossError.h"
#include <folly/Format.h>
#include <folly/logging/xlog.h>
#include <thrift/lib/cpp/util/EnumUtils.h>
using namespace facebook::fboss;
using namespace facebook::fboss::utility;
namespace {
// TODO(ccpowers): remove this once we've made platformPortEntry a required
// field
cfg::PortSpeed maxPortSpeed(const HwSwitch* hwSwitch, PortID port) {
// If Hardware can't decide the max speed, we use Platform(PlatformMapping) to
// decide the max speed.
if (auto maxSpeed = hwSwitch->getPortMaxSpeed(port);
maxSpeed != cfg::PortSpeed::DEFAULT) {
return maxSpeed;
}
return hwSwitch->getPlatform()->getPortMaxSpeed(port);
}
cfg::SwitchConfig genPortVlanCfg(
const HwSwitch* hwSwitch,
const std::vector<PortID>& ports,
const std::map<PortID, VlanID>& port2vlan,
const std::vector<VlanID>& vlans,
cfg::PortLoopbackMode lbMode = cfg::PortLoopbackMode::NONE) {
cfg::SwitchConfig config;
// Port config
config.ports_ref()->resize(ports.size());
auto portItr = ports.begin();
int portIndex = 0;
for (; portItr != ports.end(); portItr++, portIndex++) {
*config.ports[portIndex].logicalID_ref() = *portItr;
*config.ports[portIndex].speed_ref() = maxPortSpeed(hwSwitch, *portItr);
auto platformPort = hwSwitch->getPlatform()->getPlatformPort(*portItr);
if (auto entry = platformPort->getPlatformPortEntry()) {
config.ports_ref()[portIndex].name_ref() =
*entry->mapping_ref()->name_ref();
*config.ports[portIndex].profileID_ref() =
platformPort->getProfileIDBySpeed(
*config.ports[portIndex].speed_ref());
if (*config.ports[portIndex].profileID_ref() ==
cfg::PortProfileID::PROFILE_DEFAULT) {
throw FbossError(
*entry->mapping_ref()->name_ref(),
" has speed: ",
apache::thrift::util::enumNameSafe(
*config.ports[portIndex].speed_ref()),
" which has profile: ",
apache::thrift::util::enumNameSafe(
*config.ports[portIndex].profileID_ref()));
}
} else {
config.ports_ref()[portIndex].name_ref() =
"eth1/" + std::to_string(*portItr) + "/1";
}
*config.ports[portIndex].maxFrameSize_ref() = 9412;
*config.ports[portIndex].state_ref() = cfg::PortState::ENABLED;
*config.ports[portIndex].loopbackMode_ref() = lbMode;
*config.ports[portIndex].ingressVlan_ref() =
port2vlan.find(*portItr)->second;
*config.ports[portIndex].routable_ref() = true;
*config.ports[portIndex].parserType_ref() = cfg::ParserType::L3;
}
// Vlan config
config.vlans_ref()->resize(vlans.size() + 1);
auto vlanCfgItr = vlans.begin();
int vlanIndex = 0;
for (; vlanCfgItr != vlans.end(); vlanCfgItr++, vlanIndex++) {
*config.vlans[vlanIndex].id_ref() = *vlanCfgItr;
*config.vlans[vlanIndex].name_ref() = "vlan" + std::to_string(*vlanCfgItr);
*config.vlans[vlanIndex].routable_ref() = true;
}
*config.vlans[vlanIndex].id_ref() = kDefaultVlanId;
*config.vlans[vlanIndex].name_ref() =
folly::sformat("vlan{}", kDefaultVlanId);
*config.vlans[vlanIndex].routable_ref() = true;
*config.defaultVlan_ref() = kDefaultVlanId;
// Vlan port config
config.vlanPorts_ref()->resize(port2vlan.size());
auto vlanItr = port2vlan.begin();
portIndex = 0;
for (; vlanItr != port2vlan.end(); vlanItr++, portIndex++) {
*config.vlanPorts[portIndex].logicalPort_ref() = vlanItr->first;
*config.vlanPorts[portIndex].vlanID_ref() = vlanItr->second;
*config.vlanPorts[portIndex].spanningTreeState_ref() =
cfg::SpanningTreeState::FORWARDING;
*config.vlanPorts[portIndex].emitTags_ref() = false;
}
return config;
}
std::string getLocalCpuMacStr() {
return kLocalCpuMac().toString();
}
void removePort(
cfg::SwitchConfig& config,
PortID port,
bool supportsAddRemovePort) {
auto cfgPort = findCfgPortIf(config, port);
if (cfgPort == config.ports.end()) {
return;
}
if (supportsAddRemovePort) {
config.ports.erase(cfgPort);
auto removed = std::remove_if(
config.vlanPorts.begin(),
config.vlanPorts.end(),
[port](auto vlanPort) { return PortID(vlanPort.logicalPort) == port; });
config.vlanPorts.erase(removed, config.vlanPorts.end());
} else {
cfgPort->state_ref() = cfg::PortState::DISABLED;
}
}
void removeSubsumedPorts(
cfg::SwitchConfig& config,
const cfg::PlatformPortConfig& profile,
bool supportsAddRemovePort) {
if (auto subsumedPorts = profile.subsumedPorts_ref()) {
for (auto& subsumedPortID : subsumedPorts.value()) {
removePort(config, PortID(subsumedPortID), supportsAddRemovePort);
}
}
}
} // unnamed namespace
namespace facebook::fboss::utility {
folly::MacAddress kLocalCpuMac() {
static const folly::MacAddress kLocalMac("02:00:00:00:00:01");
return kLocalMac;
}
cfg::SwitchConfig oneL3IntfConfig(
const HwSwitch* hwSwitch,
PortID port,
cfg::PortLoopbackMode lbMode) {
std::vector<PortID> ports{port};
return oneL3IntfNPortConfig(hwSwitch, ports, lbMode);
}
cfg::SwitchConfig oneL3IntfNoIPAddrConfig(
const HwSwitch* hwSwitch,
PortID port,
cfg::PortLoopbackMode lbMode) {
std::vector<PortID> ports{port};
return oneL3IntfNPortConfig(
hwSwitch, ports, lbMode, false /*interfaceHasSubnet*/);
}
cfg::SwitchConfig oneL3IntfTwoPortConfig(
const HwSwitch* hwSwitch,
PortID port1,
PortID port2,
cfg::PortLoopbackMode lbMode) {
std::vector<PortID> ports{port1, port2};
return oneL3IntfNPortConfig(hwSwitch, ports, lbMode);
}
cfg::SwitchConfig oneL3IntfNPortConfig(
const HwSwitch* hwSwitch,
const std::vector<PortID>& ports,
cfg::PortLoopbackMode lbMode,
bool interfaceHasSubnet) {
std::map<PortID, VlanID> port2vlan;
std::vector<VlanID> vlans{VlanID(kBaseVlanId)};
std::vector<PortID> vlanPorts;
for (auto port : ports) {
port2vlan[port] = VlanID(kBaseVlanId);
vlanPorts.push_back(port);
}
auto config = genPortVlanCfg(hwSwitch, vlanPorts, port2vlan, vlans, lbMode);
config.interfaces_ref()->resize(1);
*config.interfaces[0].intfID_ref() = kBaseVlanId;
*config.interfaces[0].vlanID_ref() = kBaseVlanId;
*config.interfaces[0].routerID_ref() = 0;
config.interfaces_ref()[0].mac_ref() = getLocalCpuMacStr();
config.interfaces_ref()[0].mtu_ref() = 9000;
if (interfaceHasSubnet) {
config.interfaces_ref()[0].ipAddresses_ref()->resize(2);
config.interfaces[0].ipAddresses_ref()[0] = "1.1.1.1/24";
config.interfaces[0].ipAddresses_ref()[1] = "1::/64";
}
return config;
}
cfg::SwitchConfig onePortPerVlanConfig(
const HwSwitch* hwSwitch,
const std::vector<PortID>& ports,
cfg::PortLoopbackMode lbMode,
bool interfaceHasSubnet) {
std::map<PortID, VlanID> port2vlan;
std::vector<VlanID> vlans;
std::vector<PortID> vlanPorts;
auto idx = 0;
for (auto port : ports) {
auto vlan = kBaseVlanId + idx++;
port2vlan[port] = VlanID(vlan);
vlans.push_back(VlanID(vlan));
vlanPorts.push_back(port);
}
auto config = genPortVlanCfg(hwSwitch, vlanPorts, port2vlan, vlans, lbMode);
config.interfaces_ref()->resize(vlans.size());
for (auto i = 0; i < vlans.size(); ++i) {
*config.interfaces[i].intfID_ref() = kBaseVlanId + i;
*config.interfaces[i].vlanID_ref() = kBaseVlanId + i;
*config.interfaces[i].routerID_ref() = 0;
config.interfaces_ref()[i].mac_ref() = getLocalCpuMacStr();
config.interfaces_ref()[i].mtu_ref() = 9000;
if (interfaceHasSubnet) {
config.interfaces_ref()[i].ipAddresses_ref()->resize(2);
auto ipDecimal = folly::sformat("{}", i + 1);
config.interfaces[i].ipAddresses_ref()[0] =
folly::sformat("{}.0.0.0/24", ipDecimal);
config.interfaces[i].ipAddresses_ref()[1] =
folly::sformat("{}::/64", ipDecimal);
}
}
return config;
}
cfg::SwitchConfig twoL3IntfConfig(
const HwSwitch* hwSwitch,
PortID port1,
PortID port2,
cfg::PortLoopbackMode lbMode) {
std::map<PortID, VlanID> port2vlan;
std::vector<PortID> ports;
port2vlan[port1] = VlanID(kBaseVlanId);
port2vlan[port2] = VlanID(kBaseVlanId);
ports.push_back(port1);
ports.push_back(port2);
std::vector<VlanID> vlans = {VlanID(kBaseVlanId), VlanID(kBaseVlanId + 1)};
auto config = genPortVlanCfg(hwSwitch, ports, port2vlan, vlans, lbMode);
config.interfaces_ref()->resize(2);
*config.interfaces[0].intfID_ref() = kBaseVlanId;
*config.interfaces[0].vlanID_ref() = kBaseVlanId;
*config.interfaces[0].routerID_ref() = 0;
config.interfaces_ref()[0].ipAddresses_ref()->resize(2);
config.interfaces[0].ipAddresses_ref()[0] = "1.1.1.1/24";
config.interfaces[0].ipAddresses_ref()[1] = "1::1/64";
*config.interfaces[1].intfID_ref() = kBaseVlanId + 1;
*config.interfaces[1].vlanID_ref() = kBaseVlanId + 1;
*config.interfaces[1].routerID_ref() = 0;
config.interfaces_ref()[1].ipAddresses_ref()->resize(2);
config.interfaces[1].ipAddresses_ref()[0] = "2.2.2.2/24";
config.interfaces[1].ipAddresses_ref()[1] = "2::1/64";
for (auto& interface : *config.interfaces_ref()) {
interface.mac_ref() = getLocalCpuMacStr();
interface.mtu_ref() = 9000;
}
return config;
}
void addMatcher(
cfg::SwitchConfig* config,
const std::string& matcherName,
const cfg::MatchAction& matchAction) {
cfg::MatchToAction action = cfg::MatchToAction();
*action.matcher_ref() = matcherName;
*action.action_ref() = matchAction;
cfg::TrafficPolicyConfig egressTrafficPolicy;
if (auto dataPlaneTrafficPolicy = config->dataPlaneTrafficPolicy_ref()) {
egressTrafficPolicy = *dataPlaneTrafficPolicy;
}
auto curNumMatchActions = egressTrafficPolicy.matchToAction_ref()->size();
egressTrafficPolicy.matchToAction_ref()->resize(curNumMatchActions + 1);
egressTrafficPolicy.matchToAction_ref()[curNumMatchActions] = action;
config->dataPlaneTrafficPolicy_ref() = egressTrafficPolicy;
}
void updatePortSpeed(
const HwSwitch& hwSwitch,
cfg::SwitchConfig& cfg,
PortID portID,
cfg::PortSpeed speed) {
auto cfgPort = findCfgPort(cfg, portID);
auto platform = hwSwitch.getPlatform();
auto supportsAddRemovePort = platform->supportsAddRemovePort();
auto platformPort = platform->getPlatformPort(portID);
if (auto platPortEntry = platformPort->getPlatformPortEntry()) {
auto profileID = platformPort->getProfileIDBySpeed(speed);
const auto& supportedProfiles = platPortEntry->supportedProfiles;
auto profile = supportedProfiles.find(profileID);
if (profile == supportedProfiles.end()) {
throw FbossError("No profile ", profileID, " found for port ", portID);
}
cfgPort->profileID_ref() = profileID;
removeSubsumedPorts(cfg, profile->second, supportsAddRemovePort);
}
cfgPort->speed_ref() = speed;
}
std::vector<cfg::Port>::iterator findCfgPort(
cfg::SwitchConfig& cfg,
PortID portID) {
auto port = findCfgPortIf(cfg, portID);
if (port == cfg.ports.end()) {
throw FbossError("No cfg found for port ", portID);
}
return port;
}
std::vector<cfg::Port>::iterator findCfgPortIf(
cfg::SwitchConfig& cfg,
PortID portID) {
return std::find_if(
cfg.ports.begin(), cfg.ports.end(), [&portID](auto& port) {
return PortID(port.logicalID) == portID;
});
}
// Set any ports in this port group to use the specified speed,
// and disables any ports that don't support this speed.
void configurePortGroup(
const HwSwitch& hwSwitch,
cfg::SwitchConfig& config,
cfg::PortSpeed speed,
std::vector<PortID> allPortsInGroup) {
auto platform = hwSwitch.getPlatform();
auto supportsAddRemovePort = platform->supportsAddRemovePort();
for (auto portID : allPortsInGroup) {
// We might have removed a subsumed port already in a previous
// iteration of the loop.
auto cfgPort = findCfgPortIf(config, portID);
if (cfgPort == config.ports.end()) {
return;
}
auto platformPort = platform->getPlatformPort(portID);
auto platPortEntry = platformPort->getPlatformPortEntry();
if (platPortEntry == std::nullopt) {
throw std::runtime_error(folly::to<std::string>(
"No platform port entry found for port ", portID));
}
auto profileID = platformPort->getProfileIDBySpeedIf(speed);
if (!profileID.has_value()) {
XLOG(WARNING) << "Port " << static_cast<int>(portID)
<< "Doesn't support speed " << static_cast<int>(speed)
<< ", disabling it instead";
// Port doesn't support this speed, just disable it.
cfgPort->speed_ref() = cfg::PortSpeed::DEFAULT;
cfgPort->state_ref() = cfg::PortState::DISABLED;
continue;
}
auto supportedProfiles = platPortEntry->supportedProfiles;
auto profile = supportedProfiles.find(profileID.value());
if (profile == supportedProfiles.end()) {
throw std::runtime_error(folly::to<std::string>(
"No profile ", profileID.value(), " found for port ", portID));
}
cfgPort->profileID_ref() = profileID.value();
cfgPort->speed_ref() = speed;
cfgPort->state_ref() = cfg::PortState::ENABLED;
removeSubsumedPorts(config, profile->second, supportsAddRemovePort);
}
}
} // namespace facebook::fboss::utility
| 35.516883 | 80 | 0.684657 | midopooler |
bf9bc13732089d87feed946edf4cbdcf759af657 | 7,555 | cpp | C++ | src/fuml/src_gen/fUML/impl/ValueImpl.cpp | MichaelBranz/MDE4CPP | 5b918850a37e9cee54f6c3b92f381b0458451724 | [
"MIT"
] | null | null | null | src/fuml/src_gen/fUML/impl/ValueImpl.cpp | MichaelBranz/MDE4CPP | 5b918850a37e9cee54f6c3b92f381b0458451724 | [
"MIT"
] | 1 | 2019-03-01T00:54:13.000Z | 2019-03-04T02:15:50.000Z | src/fuml/src_gen/fUML/impl/ValueImpl.cpp | vallesch/MDE4CPP | 7f8a01dd6642820913b2214d255bef2ea76be309 | [
"MIT"
] | null | null | null | #include "fUML/impl/ValueImpl.hpp"
#ifdef NDEBUG
#define DEBUG_MESSAGE(a) /**/
#else
#define DEBUG_MESSAGE(a) a
#endif
#ifdef ACTIVITY_DEBUG_ON
#define ACT_DEBUG(a) a
#else
#define ACT_DEBUG(a) /**/
#endif
//#include "util/ProfileCallCount.hpp"
#include <cassert>
#include <iostream>
#include <sstream>
#include "abstractDataTypes/SubsetUnion.hpp"
#include "ecore/EAnnotation.hpp"
#include "ecore/EClass.hpp"
#include "fUML/impl/FUMLPackageImpl.hpp"
#include "abstractDataTypes/Subset.hpp"
#include "uml/Classifier.hpp"
//Forward declaration includes
#include "persistence/interfaces/XLoadHandler.hpp" // used for Persistence
#include "persistence/interfaces/XSaveHandler.hpp" // used for Persistence
#include "fUML/FUMLFactory.hpp"
#include "fUML/FUMLPackage.hpp"
#include <exception> // used in Persistence
#include "uml/Classifier.hpp"
#include "fUML/SemanticVisitor.hpp"
#include "fUML/Value.hpp"
#include "uml/ValueSpecification.hpp"
#include "ecore/EcorePackage.hpp"
#include "ecore/EcoreFactory.hpp"
#include "fUML/FUMLPackage.hpp"
#include "fUML/FUMLFactory.hpp"
#include "ecore/EAttribute.hpp"
#include "ecore/EStructuralFeature.hpp"
using namespace fUML;
//*********************************
// Constructor / Destructor
//*********************************
ValueImpl::ValueImpl()
{
//*********************************
// Attribute Members
//*********************************
//*********************************
// Reference Members
//*********************************
//References
//Init references
}
ValueImpl::~ValueImpl()
{
#ifdef SHOW_DELETION
std::cout << "-------------------------------------------------------------------------------------------------\r\ndelete Value "<< this << "\r\n------------------------------------------------------------------------ " << std::endl;
#endif
}
ValueImpl::ValueImpl(const ValueImpl & obj):ValueImpl()
{
//create copy of all Attributes
#ifdef SHOW_COPIES
std::cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\ncopy Value "<< this << "\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ " << std::endl;
#endif
//copy references with no containment (soft copy)
//Clone references with containment (deep copy)
}
std::shared_ptr<ecore::EObject> ValueImpl::copy() const
{
std::shared_ptr<ValueImpl> element(new ValueImpl(*this));
element->setThisValuePtr(element);
return element;
}
std::shared_ptr<ecore::EClass> ValueImpl::eStaticClass() const
{
return FUMLPackageImpl::eInstance()->getValue_EClass();
}
//*********************************
// Attribute Setter Getter
//*********************************
//*********************************
// Operations
//*********************************
bool ValueImpl::equals(std::shared_ptr<fUML::Value> otherValue)
{
//ADD_COUNT(__PRETTY_FUNCTION__)
//generated from body annotation
std::shared_ptr<Bag<uml::Classifier> > myTypes = this->getTypes();
std::shared_ptr<Bag<uml::Classifier> > otherTypes = otherValue->getTypes();
DEBUG_MESSAGE(std::cout<<"in Value"<<std::endl;)
bool isEqual = true;
if(myTypes->size() != otherTypes->size())
{
isEqual = false;
}
else
{
unsigned int i = 0;
while(isEqual && i < myTypes->size())
{
bool matched = false;
unsigned int j = 0;
while(!matched && j < otherTypes->size())
{
matched = (otherTypes->at(j) == myTypes->at(i));
j = j + 1;
}
isEqual = matched;
i = i + 1;
}
}
return isEqual;
//end of body
}
std::shared_ptr<Bag<uml::Classifier> > ValueImpl::getTypes() const
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
throw "UnsupportedOperationException";
}
bool ValueImpl::hasTypes(std::shared_ptr<uml::Classifier> type)
{
//ADD_COUNT(__PRETTY_FUNCTION__)
//generated from body annotation
std::shared_ptr<Bag<uml::Classifier> > types = this->getTypes();
bool found = false;
unsigned int i = 0;
while(!found && i < types->size())
{
found = (types->at(i) == type);
i = i + 1;
}
return found;
//end of body
}
std::string ValueImpl::objectId()
{
//ADD_COUNT(__PRETTY_FUNCTION__)
//generated from body annotation
return "SemanticVisitor";//typename(SemanticVisitor); //return super.toString();
//end of body
}
std::shared_ptr<uml::ValueSpecification> ValueImpl::specify()
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
throw "UnsupportedOperationException";
}
std::string ValueImpl::toString()
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
throw "UnsupportedOperationException";
}
//*********************************
// References
//*********************************
//*********************************
// Union Getter
//*********************************
std::shared_ptr<Value> ValueImpl::getThisValuePtr() const
{
return m_thisValuePtr.lock();
}
void ValueImpl::setThisValuePtr(std::weak_ptr<Value> thisValuePtr)
{
m_thisValuePtr = thisValuePtr;
setThisSemanticVisitorPtr(thisValuePtr);
}
std::shared_ptr<ecore::EObject> ValueImpl::eContainer() const
{
return nullptr;
}
//*********************************
// Structural Feature Getter/Setter
//*********************************
Any ValueImpl::eGet(int featureID, bool resolve, bool coreType) const
{
switch(featureID)
{
}
return SemanticVisitorImpl::eGet(featureID, resolve, coreType);
}
bool ValueImpl::internalEIsSet(int featureID) const
{
switch(featureID)
{
}
return SemanticVisitorImpl::internalEIsSet(featureID);
}
bool ValueImpl::eSet(int featureID, Any newValue)
{
switch(featureID)
{
}
return SemanticVisitorImpl::eSet(featureID, newValue);
}
//*********************************
// Persistence Functions
//*********************************
void ValueImpl::load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler)
{
std::map<std::string, std::string> attr_list = loadHandler->getAttributeList();
loadAttributes(loadHandler, attr_list);
//
// Create new objects (from references (containment == true))
//
// get FUMLFactory
std::shared_ptr<fUML::FUMLFactory> modelFactory = fUML::FUMLFactory::eInstance();
int numNodes = loadHandler->getNumOfChildNodes();
for(int ii = 0; ii < numNodes; ii++)
{
loadNode(loadHandler->getNextNodeName(), loadHandler, modelFactory);
}
}
void ValueImpl::loadAttributes(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler, std::map<std::string, std::string> attr_list)
{
SemanticVisitorImpl::loadAttributes(loadHandler, attr_list);
}
void ValueImpl::loadNode(std::string nodeName, std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler, std::shared_ptr<fUML::FUMLFactory> modelFactory)
{
SemanticVisitorImpl::loadNode(nodeName, loadHandler, modelFactory);
}
void ValueImpl::resolveReferences(const int featureID, std::list<std::shared_ptr<ecore::EObject> > references)
{
SemanticVisitorImpl::resolveReferences(featureID, references);
}
void ValueImpl::save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const
{
saveContent(saveHandler);
SemanticVisitorImpl::saveContent(saveHandler);
ecore::EObjectImpl::saveContent(saveHandler);
}
void ValueImpl::saveContent(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const
{
try
{
std::shared_ptr<fUML::FUMLPackage> package = fUML::FUMLPackage::eInstance();
}
catch (std::exception& e)
{
std::cout << "| ERROR | " << e.what() << std::endl;
}
}
| 24.609121 | 234 | 0.617207 | MichaelBranz |
bf9c3244794c75dce20a9630a31ab3cdb0c460c0 | 1,978 | cpp | C++ | tests/test_Reflection_Spectrum.cpp | temken/DaMaSCUS-SUN | 6dc10d7e707c20bb1d5aea58249515b00e225b58 | [
"MIT"
] | 4 | 2021-02-26T10:30:36.000Z | 2021-03-17T01:49:18.000Z | tests/test_Reflection_Spectrum.cpp | temken/DaMaSCUS-SUN | 6dc10d7e707c20bb1d5aea58249515b00e225b58 | [
"MIT"
] | 7 | 2021-02-09T16:32:05.000Z | 2022-02-03T09:20:08.000Z | tests/test_Reflection_Spectrum.cpp | temken/DaMaSCUS-SUN | 6dc10d7e707c20bb1d5aea58249515b00e225b58 | [
"MIT"
] | 1 | 2022-01-03T03:54:24.000Z | 2022-01-03T03:54:24.000Z | #include "Reflection_Spectrum.hpp"
#include "gtest/gtest.h"
#include <mpi.h>
#include "libphysica/Integration.hpp"
#include "libphysica/Natural_Units.hpp"
#include "obscura/DM_Halo_Models.hpp"
#include "obscura/DM_Particle_Standard.hpp"
using namespace DaMaSCUS_SUN;
using namespace libphysica::natural_units;
int main(int argc, char* argv[])
{
int result = 0;
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
result = RUN_ALL_TESTS();
MPI_Finalize();
return result;
}
TEST(TestReflectionSpectrum, TestSpectrum)
{
// ARRANGE
Solar_Model solar_model;
obscura::Standard_Halo_Model SHM;
double mDM = 0.1;
obscura::DM_Particle_SI DM(mDM);
DM.Set_Low_Mass_Mode(true);
DM.Set_Sigma_Proton(1e-1 * pb);
solar_model.Interpolate_Total_DM_Scattering_Rate(DM, 100, 50);
Simulation_Data data_set(10, 0, 1);
int fixed_seed = 13;
data_set.Generate_Data(DM, solar_model, SHM, fixed_seed);
double v = 1e-3;
// ACT & ASSERT
Reflection_Spectrum spectrum(data_set, solar_model, SHM, mDM);
EXPECT_DOUBLE_EQ(spectrum.Differential_Spectrum(v), 4.0 * M_PI * AU * AU * spectrum.Differential_DM_Flux(v));
EXPECT_GT(spectrum.PDF_Speed(v), 0.0);
std::function<double(double)> pdf = [&spectrum](double v) {
return spectrum.PDF_Speed(v);
};
double norm = libphysica::Integrate(pdf, spectrum.Minimum_DM_Speed(), spectrum.Maximum_DM_Speed());
EXPECT_NEAR(norm, 1.0, 1e-3);
double flux_1 = spectrum.Differential_DM_Flux(v);
spectrum.Set_Distance(2.0 * AU);
double flux_2 = spectrum.Differential_DM_Flux(v);
EXPECT_DOUBLE_EQ(flux_1, 4.0 * flux_2);
}
TEST(TestReflectionSpectrum, TestDMEnteringRate)
{
// ARRANGE
Solar_Model solar_model;
obscura::Standard_Halo_Model SHM;
double mDM_1 = 1.0;
double mDM_2 = 2.0;
// ACT
double rate_1 = DM_Entering_Rate(solar_model, SHM, mDM_1);
double rate_2 = DM_Entering_Rate(solar_model, SHM, mDM_2);
// ASSERT
ASSERT_DOUBLE_EQ(rate_1, 2.0 * rate_2);
ASSERT_NEAR(rate_1, 1.06689e+30 / sec, 1.0e27 / sec);
} | 27.09589 | 110 | 0.747725 | temken |
bf9ebce3a48163c0b6c517e39a9b67d59e11fe6c | 4,913 | cpp | C++ | Components/Camera.cpp | raulgonzalezupc/FirstAssigment | 9193de31049922787da966695340253d84439bf3 | [
"MIT"
] | null | null | null | Components/Camera.cpp | raulgonzalezupc/FirstAssigment | 9193de31049922787da966695340253d84439bf3 | [
"MIT"
] | null | null | null | Components/Camera.cpp | raulgonzalezupc/FirstAssigment | 9193de31049922787da966695340253d84439bf3 | [
"MIT"
] | null | null | null | #include "Camera.h"
#include "../GameObject.h"
#include "Component.h"
#include "../Application.h"
#include "../ModuleRender.h"
#include "../ModuleWindow.h"
#include "../ModuleCamera.h"
#include "../ModuleScene.h"
#include "../ModuleProgram.h"
#include "../ModuleModelLoader.h"
#include <math.h>
#include "../imgui/imgui.h"
#include "../Utils/DebugDraw.h"
Camera::Camera(GameObject* owner, int number) : Component(owner, ComponentType::Camera)
{
aspect = App->window->width / App->window->height;
frustum.type = FrustumType::PerspectiveFrustum;
if (number == 1) {
frustum.pos = float3::unitX;
}
else {
frustum.pos = float3{ 6.0F, 0.0F, -10.0F };
}
//skybox = new Skybox();
frustum.front = float3::unitZ;
frustum.up = float3::unitY;
frustum.nearPlaneDistance = 1.0F;
frustum.farPlaneDistance = 100.0F;
frustum.verticalFov = PI / 4.0F;
frustum.horizontalFov = 2.0F*atanf(tanf(frustum.verticalFov*0.5F)*aspect);
//setting up our proj
proj = frustum.ProjectionMatrix();
model = float4x4::FromTRS(float3(0.0F, -5.0F, 20.0F), float3x3::RotateY(0.0F), float3(1.0F, 1.0F, 1.0F));
view = frustum.ViewMatrix();
float4x4 transform = proj * view * float4x4(model);
glGenFramebuffers(1, &fbo);
}
Camera::~Camera()
{
glDeleteFramebuffers(1, &fbo);
glDeleteFramebuffers(1, &fb_depth);
}
void Camera::CreateRay(const float2& normalizedPos, LineSegment &value) const
{
value = frustum.UnProjectLineSegment(normalizedPos.x, normalizedPos.y);
}
void Camera::DrawFrustumPlanes()
{
float4x4 clipMatrix = proj * view;
dd::frustum(clipMatrix.Inverted(), float3(0, 0, 1));
}
int Camera::isCollidingFrustum(const AABB& aabb) const
{
float3 edges[8];
int totalPointsIn = 6;
aabb.GetCornerPoints(edges);
Plane viewportPlanes[6];
frustum.GetPlanes(viewportPlanes);
for (int pl = 0; pl < 6; pl++)
{
int isInPlane = 1;
for (int p = 0; p < 8; p++)
{
if (viewportPlanes[pl].IsOnPositiveSide(edges[p]))
{
isInPlane = 0;
--totalPointsIn;
}
}
}
if (totalPointsIn == 6)
{
return IS_IN;
}
if (totalPointsIn == 0)
{
return IS_OUT;
}
return INTERSECT;
}
void Camera::Draw(const char* name)
{
ImGui::Begin(name);
if (ImGui::IsWindowHovered())
{
isHovered = true;
}
else
{
isHovered = false;
}
width = ImGui::GetWindowContentRegionWidth();
height = ImGui::GetContentRegionAvail().y;
ImGui::SetNextWindowPos(ImVec2(256.0f, 0.0f), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(800.0f, 600.0f), ImGuiCond_FirstUseEver);
BindBuffers(width, height);
App->camera->SetAspectRatio(width/height, this);
ImGui::GetWindowDrawList()->AddImage(
(void*)fb_tex,
ImVec2(ImGui::GetCursorScreenPos()),
ImVec2(ImGui::GetCursorScreenPos().x + fb_width,
ImGui::GetCursorScreenPos().y + fb_height),
ImVec2(0, 1), ImVec2(1, 0));
//ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::End();
}
void Camera::BindBuffers(unsigned w, unsigned h)
{
if (fb_tex)
{
glDeleteTextures(1, &fb_tex);
}
else {
glGenTextures(1, &fb_tex);
}
if (fb_depth)
{
glDeleteRenderbuffers(1, &fb_depth);
}
else {
glGenRenderbuffers(1, &fb_depth);
}
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glBindRenderbuffer(GL_RENDERBUFFER, fb_depth);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, w, h);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
glBindTexture(GL_TEXTURE_2D, fb_tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fb_tex, 0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fb_depth);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
fb_width = w;
fb_height = h;
//glDrawBuffer(GL_COLOR_ATTACHMENT0);
}
void Camera::GenerateFBOTexture(unsigned w, unsigned h)
{
BindBuffers(w, h);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
unsigned int program = App->program->defaultProgram;
glUseProgram(program);
glUniformMatrix4fv(glGetUniformLocation(program, "model"), 1, GL_TRUE, &(model[0][0]));
glUniformMatrix4fv(glGetUniformLocation(program, "view"), 1, GL_TRUE, &(view[0][0]));
glUniformMatrix4fv(glGetUniformLocation(program, "proj"), 1, GL_TRUE, &(proj[0][0]));
glViewport(0, 0, width, height);
glClearColor(0.2f, 0.2f, 0.2f, 1.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
App->renderer->ShowAxis();
DrawFrustumPlanes();
App->renderer->ShowGrid();
App->scene->DrawAllBoundingBoxes();
App->modelLoader->Draw(program);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
| 24.688442 | 125 | 0.718095 | raulgonzalezupc |
bf9f398f8966a85086a2095312c25886bb8197a2 | 59,794 | hh | C++ | src/Mesh.hh | nmaxwell/OpenMesh-Python | daa461069decb459f990bfcc1131c55a2db7b5e5 | [
"BSD-3-Clause"
] | 9 | 2019-09-16T10:03:37.000Z | 2022-02-03T17:56:24.000Z | src/Mesh.hh | Jiawei1996/OpenMesh-Python | daa461069decb459f990bfcc1131c55a2db7b5e5 | [
"BSD-3-Clause"
] | null | null | null | src/Mesh.hh | Jiawei1996/OpenMesh-Python | daa461069decb459f990bfcc1131c55a2db7b5e5 | [
"BSD-3-Clause"
] | 1 | 2020-04-13T15:23:59.000Z | 2020-04-13T15:23:59.000Z | #ifndef OPENMESH_PYTHON_MESH_HH
#define OPENMESH_PYTHON_MESH_HH
#include "Utilities.hh"
#include "MeshTypes.hh"
#include "Iterator.hh"
#include "Circulator.hh"
#include <algorithm>
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
namespace py = pybind11;
namespace OM = OpenMesh;
/**
* Thin wrapper for assign_connectivity.
*
* @tparam Mesh A mesh type.
* @tparam OtherMesh A mesh type.
*
* @param _self The mesh instance that is to be used.
* @param _other The mesh from which the connectivity is to be copied.
*/
template <class Mesh, class OtherMesh>
void assign_connectivity(Mesh& _self, const OtherMesh& _other) {
_self.assign_connectivity(_other);
}
/**
* Get an iterator.
*/
template <class Mesh, class Iterator, size_t (OM::ArrayKernel::*n_items)() const>
IteratorWrapperT<Iterator, n_items> get_iterator(Mesh& _self) {
return IteratorWrapperT<Iterator, n_items>(_self, typename Iterator::value_type(0));
}
/**
* Get a skipping iterator.
*/
template <class Mesh, class Iterator, size_t (OM::ArrayKernel::*n_items)() const>
IteratorWrapperT<Iterator, n_items> get_skipping_iterator(Mesh& _self) {
return IteratorWrapperT<Iterator, n_items>(_self, typename Iterator::value_type(0), true);
}
/**
* Get a circulator.
*
* @tparam Mesh A Mesh type.
* @tparam Circulator A circulator type.
* @tparam CenterEntityHandle The appropriate handle type.
*
* @param _self The mesh instance that is to be used.
* @param _handle The handle of the item to circulate around.
*/
template <class Mesh, class Circulator, class CenterEntityHandle>
CirculatorWrapperT<Circulator, CenterEntityHandle> get_circulator(Mesh& _self, CenterEntityHandle _handle) {
return CirculatorWrapperT<Circulator, CenterEntityHandle>(_self, _handle);
}
/**
* Garbage collection using lists instead of vectors to keep track of a set of
* handles.
*
* @tparam Mesh A Mesh type.
*
* @param _self The mesh instance that is to be used.
* @param _vh_to_update The list of vertex handles to be updated.
* @param _hh_to_update The list of halfedge handles to be updated.
* @param _fh_to_update The list of face handles to be updated.
* @param _v Remove deleted vertices?
* @param _e Remove deleted edges?
* @param _f Remove deleted faces?
*/
template <class Mesh>
void garbage_collection(Mesh& _self, py::list& _vh_to_update, py::list& _hh_to_update, py::list& _fh_to_update, bool _v = true, bool _e = true, bool _f = true) {
// Convert list of handles to vector of pointers
std::vector<OM::VertexHandle*> vh_vector;
for (auto item : _vh_to_update) {
if (py::isinstance<OM::VertexHandle>(item)) {
vh_vector.push_back(item.cast<OM::VertexHandle*>());
}
}
// Convert list of handles to vector of pointers
std::vector<OM::HalfedgeHandle*> hh_vector;
for (auto item : _hh_to_update) {
if (py::isinstance<OM::HalfedgeHandle>(item)) {
hh_vector.push_back(item.cast<OM::HalfedgeHandle*>());
}
}
// Convert list of handles to vector of pointers
std::vector<OM::FaceHandle*> fh_vector;
for (auto item : _fh_to_update) {
if (py::isinstance<OM::FaceHandle>(item)) {
fh_vector.push_back(item.cast<OM::FaceHandle*>());
}
}
// Call garbage collection
_self.garbage_collection(vh_vector, hh_vector, fh_vector, _v, _e, _f);
}
/**
* Converts OpenMesh vectors to numpy arrays.
*
* @tparam vector A Vector type.
* @param _vec The vector to be converted.
*/
template<class Vector>
py::array_t<typename Vector::value_type> vec2numpy(const Vector& _vec) {
typedef typename Vector::value_type dtype;
dtype *data = new dtype[_vec.size()];
std::copy_n(_vec.data(), _vec.size(), data);
py::capsule base = free_when_done(data);
return py::array_t<dtype>({_vec.size()}, {sizeof(dtype)}, data, base);
}
/**
* Converts OpenMesh vectors to numpy arrays.
*
* The returned array references the vector's underlying data, i.e. changes
* made to the returned array affect the original mesh.
*
* @tparam Mesh A Mesh type.
* @tparam vector A Vector type.
*
* @param _mesh The mesh that owns the vector's underlying memory. In order
* to avaoid dangling pointers, the lifetime of this mesh is tied to the
* lifetime of the returned numpy array.
* @param _vec The vector to be converted.
*/
template<class Mesh, class Vector>
py::array_t<typename Vector::value_type> vec2numpy(Mesh& _mesh, Vector& _vec, size_t _n = 1) {
typedef typename Vector::value_type dtype;
std::vector<size_t> shape;
std::vector<size_t> strides;
if (_n == 1) {
shape = {_vec.size()};
strides = {sizeof(dtype)};
}
else {
shape = {_n, _vec.size()};
strides = {_vec.size() * sizeof(dtype), sizeof(dtype)};
}
return py::array_t<dtype>(shape, strides, _vec.data(), py::cast(_mesh));
}
template<class Mesh>
py::array_t<float> flt2numpy(Mesh& _mesh, const float& _flt, size_t _n = 1) {
return py::array_t<float>({_n}, {sizeof(float)}, &_flt, py::cast(_mesh));
}
template<class Mesh>
py::array_t<double> flt2numpy(Mesh& _mesh, const double& _flt, size_t _n = 1) {
return py::array_t<double>({_n}, {sizeof(double)}, &_flt, py::cast(_mesh));
}
py::array_t<int> face_vertex_indices_trimesh(TriMesh& _self) {
if (_self.n_faces() == 0) {
return py::array_t<int>();
}
const bool has_status = _self.has_face_status();
int *indices = new int[_self.n_faces() * 3];
py::capsule base = free_when_done(indices);
for (auto fh : _self.all_faces()) {
if (has_status && _self.status(fh).deleted()) {
PyErr_SetString(PyExc_RuntimeError, "Mesh has deleted items. Please call garbage_collection() first.");
throw py::error_already_set();
}
auto fv_it = _self.fv_iter(fh);
indices[fh.idx() * 3 + 0] = fv_it->idx(); ++fv_it;
indices[fh.idx() * 3 + 1] = fv_it->idx(); ++fv_it;
indices[fh.idx() * 3 + 2] = fv_it->idx();
}
const auto shape = {_self.n_faces(), size_t(3)};
const auto strides = {3 * sizeof(int), sizeof(int)};
return py::array_t<int>(shape, strides, indices, base);
}
struct FuncEdgeVertex {
static void call(const OM::ArrayKernel& _mesh, OM::EdgeHandle _eh, int *_ptr) {
const auto heh = _mesh.halfedge_handle(_eh, 0);
_ptr[0] = _mesh.from_vertex_handle(heh).idx();
_ptr[1] = _mesh.to_vertex_handle(heh).idx();
}
};
struct FuncEdgeFace {
static void call(const OM::ArrayKernel& _mesh, OM::EdgeHandle _eh, int *_ptr) {
const auto heh1 = _mesh.halfedge_handle(_eh, 0);
const auto heh2 = _mesh.halfedge_handle(_eh, 1);
_ptr[0] = _mesh.face_handle(heh1).idx();
_ptr[1] = _mesh.face_handle(heh2).idx();
}
};
struct FuncEdgeHalfedge {
static void call(const OM::ArrayKernel& _mesh, OM::EdgeHandle _eh, int *_ptr) {
_ptr[0] = _mesh.halfedge_handle(_eh, 0).idx();
_ptr[1] = _mesh.halfedge_handle(_eh, 1).idx();
}
};
struct FuncHalfedgeToVertex {
static void call(const OM::ArrayKernel& _mesh, OM::HalfedgeHandle _heh, int *_ptr) {
*_ptr = _mesh.to_vertex_handle(_heh).idx();
}
static size_t dim() { return 1; }
};
struct FuncHalfedgeFromVertex {
static void call(const OM::ArrayKernel& _mesh, OM::HalfedgeHandle _heh, int *_ptr) {
*_ptr = _mesh.from_vertex_handle(_heh).idx();
}
static size_t dim() { return 1; }
};
struct FuncHalfedgeFace {
static void call(const OM::ArrayKernel& _mesh, OM::HalfedgeHandle _heh, int *_ptr) {
*_ptr = _mesh.face_handle(_heh).idx();
}
static size_t dim() { return 1; }
};
struct FuncHalfedgeEdge {
static void call(const OM::ArrayKernel& _mesh, OM::HalfedgeHandle _heh, int *_ptr) {
*_ptr = _mesh.edge_handle(_heh).idx();
}
static size_t dim() { return 1; }
};
struct FuncHalfedgeVertex {
static void call(const OM::ArrayKernel& _mesh, OM::HalfedgeHandle _heh, int *_ptr) {
_ptr[0] = _mesh.from_vertex_handle(_heh).idx();
_ptr[1] = _mesh.to_vertex_handle(_heh).idx();
}
static size_t dim() { return 2; }
};
template <class Mesh, class CopyFunc>
py::array_t<int> edge_other_indices(Mesh& _self) {
if (_self.n_edges() == 0) {
return py::array_t<int>();
}
const bool has_status = _self.has_edge_status();
int *indices = new int[_self.n_edges() * 2];
py::capsule base = free_when_done(indices);
for (auto eh : _self.all_edges()) {
if (has_status && _self.status(eh).deleted()) {
PyErr_SetString(PyExc_RuntimeError, "Mesh has deleted items. Please call garbage_collection() first.");
throw py::error_already_set();
}
CopyFunc::call(_self, eh, &indices[eh.idx() * 2]);
}
const auto shape = {_self.n_edges(), size_t(2)};
const auto strides = {2 * sizeof(int), sizeof(int)};
return py::array_t<int>(shape, strides, indices, base);
}
template <class Mesh, class CopyFunc>
py::array_t<int> halfedge_other_indices(Mesh& _self) {
if (_self.n_halfedges() == 0) {
return py::array_t<int>();
}
const bool has_status = _self.has_halfedge_status();
const size_t dim = CopyFunc::dim();
int *indices = new int[_self.n_halfedges() * dim];
py::capsule base = free_when_done(indices);
for (auto heh : _self.all_halfedges()) {
if (has_status && _self.status(heh).deleted()) {
PyErr_SetString(PyExc_RuntimeError, "Mesh has deleted items. Please call garbage_collection() first.");
throw py::error_already_set();
}
CopyFunc::call(_self, heh, &indices[heh.idx() * dim]);
}
std::vector<size_t> shape;
std::vector<size_t> strides;
if (dim == 1) {
shape = {_self.n_halfedges()};
strides = {sizeof(int)};
}
else {
shape = {_self.n_halfedges(), dim};
strides = {dim * sizeof(int), sizeof(int)};
}
return py::array_t<int>(shape, strides, indices, base);
}
template <class Mesh, class Handle, class Circulator>
py::array_t<int> indices(Mesh& _self) {
const size_t n = _self.py_n_items(Handle());
if (n == 0) return py::array_t<int>();
const bool has_status = _self.py_has_status(Handle());
// find max valence and check status
int max_valence = 0;
for (size_t i = 0; i < n; ++i) {
Handle hnd(i);
if (has_status && _self.status(hnd).deleted()) {
PyErr_SetString(PyExc_RuntimeError, "Mesh has deleted items. Please call garbage_collection() first.");
throw py::error_already_set();
}
int valence = 0;
for (auto it = Circulator(_self, hnd); it.is_valid(); ++it) {
valence++;
}
max_valence = std::max(max_valence, valence);
}
// allocate memory
int *indices = new int[n * max_valence];
// copy indices
for (size_t i = 0; i < n; ++i) {
int valence = 0;
for (auto it = Circulator(_self, Handle(i)); it.is_valid(); ++it) {
indices[i * max_valence + valence] = it->idx();
valence++;
}
for (size_t j = valence; j < max_valence; ++j) {
indices[i * max_valence + j] = -1;
}
}
// make numpy array
const auto shape = {n, size_t(max_valence)};
const auto strides = {max_valence * sizeof(int), sizeof(int)};
py::capsule base = free_when_done(indices);
return py::array_t<int>(shape, strides, indices, base);
}
/**
* This function template is used to expose mesh member functions that are only
* available for a specific type of mesh (i.e. they are available for polygon
* meshes or triangle meshes, but not both).
*
* @tparam Class A pybind11::class type.
*
* @param _class The pybind11::class instance for which the member
* functions are to be defined.
*/
template <class Class>
void expose_type_specific_functions(Class& _class) {
// See the template specializations below
}
/**
* Function template specialization for polygon meshes.
*/
template <>
void expose_type_specific_functions(py::class_<PolyMesh>& _class) {
typedef PolyMesh::Scalar Scalar;
typedef PolyMesh::Point Point;
typedef PolyMesh::Normal Normal;
typedef PolyMesh::Color Color;
typedef py::array_t<typename Point::value_type> np_point_t;
OM::FaceHandle (PolyMesh::*add_face_4_vh)(OM::VertexHandle, OM::VertexHandle, OM::VertexHandle, OM::VertexHandle) = &PolyMesh::add_face;
_class
.def("add_face", add_face_4_vh)
.def("split", [](PolyMesh& _self, OM::EdgeHandle _eh, np_point_t _arr) {
_self.split(_eh, Point(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("split", [](PolyMesh& _self, OM::FaceHandle _fh, np_point_t _arr) {
_self.split(_fh, Point(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("insert_edge", &PolyMesh::insert_edge)
.def("face_vertex_indices", &indices<PolyMesh, OM::FaceHandle, PolyMesh::FaceVertexIter>)
.def("fv_indices", &indices<PolyMesh, OM::FaceHandle, PolyMesh::FaceVertexIter>)
.def("calc_face_normal", [](PolyMesh& _self, np_point_t _p0, np_point_t _p1, np_point_t _p2) {
const Point p0(_p0.at(0), _p0.at(1), _p0.at(2));
const Point p1(_p1.at(0), _p1.at(1), _p1.at(2));
const Point p2(_p2.at(0), _p2.at(1), _p2.at(2));
return vec2numpy(_self.calc_face_normal(p0, p1, p2));
})
;
}
/**
* Function template specialization for triangle meshes.
*/
template <>
void expose_type_specific_functions(py::class_<TriMesh>& _class) {
typedef TriMesh::Scalar Scalar;
typedef TriMesh::Point Point;
typedef TriMesh::Normal Normal;
typedef TriMesh::Color Color;
typedef py::array_t<typename Point::value_type> np_point_t;
void (TriMesh::*split_copy_eh_vh)(OM::EdgeHandle, OM::VertexHandle) = &TriMesh::split_copy;
OM::HalfedgeHandle (TriMesh::*vertex_split_vh)(OM::VertexHandle, OM::VertexHandle, OM::VertexHandle, OM::VertexHandle) = &TriMesh::vertex_split;
_class
.def("split", [](TriMesh& _self, OM::EdgeHandle _eh, np_point_t _arr) {
return _self.split(_eh, Point(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("split", [](TriMesh& _self, OM::FaceHandle _fh, np_point_t _arr) {
return _self.split(_fh, Point(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("split_copy", split_copy_eh_vh)
.def("split_copy", [](TriMesh& _self, OM::EdgeHandle _eh, np_point_t _arr) {
return _self.split_copy(_eh, Point(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("split_copy", [](TriMesh& _self, OM::FaceHandle _fh, np_point_t _arr) {
return _self.split_copy(_fh, Point(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("opposite_vh", &TriMesh::opposite_vh)
.def("opposite_he_opposite_vh", &TriMesh::opposite_he_opposite_vh)
.def("vertex_split", vertex_split_vh)
.def("vertex_split", [](TriMesh& _self, np_point_t _arr, OM::VertexHandle _v1, OM::VertexHandle _vl, OM::VertexHandle _vr) {
return _self.vertex_split(Point(_arr.at(0), _arr.at(1), _arr.at(2)), _v1, _vl, _vr);
})
.def("is_flip_ok", &TriMesh::is_flip_ok)
.def("flip", &TriMesh::flip)
.def("face_vertex_indices", &face_vertex_indices_trimesh)
.def("fv_indices", &face_vertex_indices_trimesh)
;
}
/**
* Expose a mesh type to %Python.
*
* @tparam Mesh A mesh type.
*
* @param _name The name of the mesh type to be exposed.
*/
template <class Mesh>
void expose_mesh(py::module& m, const char *_name) {
typedef typename Mesh::Scalar Scalar;
typedef typename Mesh::Point Point;
typedef typename Mesh::Normal Normal;
typedef typename Mesh::Color Color;
typedef typename Mesh::TexCoord1D TexCoord1D;
typedef typename Mesh::TexCoord2D TexCoord2D;
typedef typename Mesh::TexCoord3D TexCoord3D;
typedef typename Mesh::TextureIndex TextureIndex;
//======================================================================
// KernelT Function Pointers
//======================================================================
// Get the i'th item
OM::VertexHandle (Mesh::*vertex_handle_uint )(unsigned int) const = &Mesh::vertex_handle;
OM::HalfedgeHandle (Mesh::*halfedge_handle_uint)(unsigned int) const = &Mesh::halfedge_handle;
OM::EdgeHandle (Mesh::*edge_handle_uint )(unsigned int) const = &Mesh::edge_handle;
OM::FaceHandle (Mesh::*face_handle_uint )(unsigned int) const = &Mesh::face_handle;
// Delete items
void (Mesh::*garbage_collection_bools)(bool, bool, bool) = &Mesh::garbage_collection;
void (*garbage_collection_lists_bools)(Mesh&, py::list&, py::list&, py::list&, bool, bool, bool) = &garbage_collection;
// Vertex connectivity
OM::HalfedgeHandle (Mesh::*halfedge_handle_vh)(OM::VertexHandle) const = &Mesh::halfedge_handle;
OM::HalfedgeHandle (Mesh::*halfedge_handle_fh)(OM::FaceHandle ) const = &Mesh::halfedge_handle;
// Halfedge connectivity
OM::FaceHandle (Mesh::*face_handle_hh )(OM::HalfedgeHandle) const = &Mesh::face_handle;
OM::HalfedgeHandle (Mesh::*prev_halfedge_handle_hh)(OM::HalfedgeHandle) const = &Mesh::prev_halfedge_handle;
OM::EdgeHandle (Mesh::*edge_handle_hh )(OM::HalfedgeHandle) const = &Mesh::edge_handle;
// Edge connectivity
OM::HalfedgeHandle (Mesh::*halfedge_handle_eh_uint)(OM::EdgeHandle, unsigned int) const = &Mesh::halfedge_handle;
// Set halfedge
void (Mesh::*set_halfedge_handle_vh_hh)(OM::VertexHandle, OM::HalfedgeHandle) = &Mesh::set_halfedge_handle;
void (Mesh::*set_halfedge_handle_fh_hh)(OM::FaceHandle, OM::HalfedgeHandle) = &Mesh::set_halfedge_handle;
// Low-level adding new items
OM::VertexHandle (Mesh::*new_vertex_void )(void ) = &Mesh::new_vertex;
OM::FaceHandle (Mesh::*new_face_void )(void ) = &Mesh::new_face;
OM::FaceHandle (Mesh::*new_face_face )(const typename Mesh::Face& ) = &Mesh::new_face;
// Kernel item iterators
IteratorWrapperT<typename Mesh::VertexIter, &Mesh::n_vertices > (*vertices )(Mesh&) = &get_iterator;
IteratorWrapperT<typename Mesh::HalfedgeIter, &Mesh::n_halfedges> (*halfedges)(Mesh&) = &get_iterator;
IteratorWrapperT<typename Mesh::EdgeIter, &Mesh::n_edges > (*edges )(Mesh&) = &get_iterator;
IteratorWrapperT<typename Mesh::FaceIter, &Mesh::n_faces > (*faces )(Mesh&) = &get_iterator;
IteratorWrapperT<typename Mesh::VertexIter, &Mesh::n_vertices > (*svertices )(Mesh&) = &get_skipping_iterator;
IteratorWrapperT<typename Mesh::HalfedgeIter, &Mesh::n_halfedges> (*shalfedges)(Mesh&) = &get_skipping_iterator;
IteratorWrapperT<typename Mesh::EdgeIter, &Mesh::n_edges > (*sedges )(Mesh&) = &get_skipping_iterator;
IteratorWrapperT<typename Mesh::FaceIter, &Mesh::n_faces > (*sfaces )(Mesh&) = &get_skipping_iterator;
//======================================================================
// BaseKernel Function Pointers
//======================================================================
// Copy all properties
void (Mesh::*copy_all_properties_vh_vh_bool)(OM::VertexHandle, OM::VertexHandle, bool) = &Mesh::copy_all_properties;
void (Mesh::*copy_all_properties_hh_hh_bool)(OM::HalfedgeHandle, OM::HalfedgeHandle, bool) = &Mesh::copy_all_properties;
void (Mesh::*copy_all_properties_eh_eh_bool)(OM::EdgeHandle, OM::EdgeHandle, bool) = &Mesh::copy_all_properties;
void (Mesh::*copy_all_properties_fh_fh_bool)(OM::FaceHandle, OM::FaceHandle, bool) = &Mesh::copy_all_properties;
//======================================================================
// PolyConnectivity Function Pointers
//======================================================================
// Assign connectivity
void (*assign_connectivity_poly)(Mesh&, const PolyMesh&) = &assign_connectivity;
void (*assign_connectivity_tri )(Mesh&, const TriMesh& ) = &assign_connectivity;
// Adding items to a mesh
OM::FaceHandle (Mesh::*add_face_3_vh)(OM::VertexHandle, OM::VertexHandle, OM::VertexHandle) = &Mesh::add_face;
OM::FaceHandle (Mesh::*add_face_list)(const std::vector<OM::VertexHandle>&) = &Mesh::add_face;
// Vertex and face valence
unsigned int (Mesh::*valence_vh)(OM::VertexHandle) const = &Mesh::valence;
unsigned int (Mesh::*valence_fh)(OM::FaceHandle ) const = &Mesh::valence;
// Triangulate face or mesh
void (Mesh::*triangulate_fh )(OM::FaceHandle) = &Mesh::triangulate;
void (Mesh::*triangulate_void)( ) = &Mesh::triangulate;
// Vertex and Face circulators
CirculatorWrapperT<typename Mesh::VertexVertexIter, OM::VertexHandle > (*vv )(Mesh&, OM::VertexHandle ) = &get_circulator;
CirculatorWrapperT<typename Mesh::VertexIHalfedgeIter, OM::VertexHandle > (*vih)(Mesh&, OM::VertexHandle ) = &get_circulator;
CirculatorWrapperT<typename Mesh::VertexOHalfedgeIter, OM::VertexHandle > (*voh)(Mesh&, OM::VertexHandle ) = &get_circulator;
CirculatorWrapperT<typename Mesh::VertexEdgeIter, OM::VertexHandle > (*ve )(Mesh&, OM::VertexHandle ) = &get_circulator;
CirculatorWrapperT<typename Mesh::VertexFaceIter, OM::VertexHandle > (*vf )(Mesh&, OM::VertexHandle ) = &get_circulator;
CirculatorWrapperT<typename Mesh::FaceVertexIter, OM::FaceHandle > (*fv )(Mesh&, OM::FaceHandle ) = &get_circulator;
CirculatorWrapperT<typename Mesh::FaceHalfedgeIter, OM::FaceHandle > (*fh )(Mesh&, OM::FaceHandle ) = &get_circulator;
CirculatorWrapperT<typename Mesh::FaceEdgeIter, OM::FaceHandle > (*fe )(Mesh&, OM::FaceHandle ) = &get_circulator;
CirculatorWrapperT<typename Mesh::FaceFaceIter, OM::FaceHandle > (*ff )(Mesh&, OM::FaceHandle ) = &get_circulator;
CirculatorWrapperT<typename Mesh::HalfedgeLoopIter, OM::HalfedgeHandle> (*hl )(Mesh&, OM::HalfedgeHandle) = &get_circulator;
// Boundary and manifold tests
bool (Mesh::*is_boundary_hh)(OM::HalfedgeHandle ) const = &Mesh::is_boundary;
bool (Mesh::*is_boundary_eh)(OM::EdgeHandle ) const = &Mesh::is_boundary;
bool (Mesh::*is_boundary_vh)(OM::VertexHandle ) const = &Mesh::is_boundary;
bool (Mesh::*is_boundary_fh)(OM::FaceHandle, bool) const = &Mesh::is_boundary;
//======================================================================
// PolyMeshT Function Pointers
//======================================================================
Scalar (Mesh::*calc_edge_length_eh)(OM::EdgeHandle ) const = &Mesh::calc_edge_length;
Scalar (Mesh::*calc_edge_length_hh)(OM::HalfedgeHandle) const = &Mesh::calc_edge_length;
Scalar (Mesh::*calc_edge_sqr_length_eh)(OM::EdgeHandle ) const = &Mesh::calc_edge_sqr_length;
Scalar (Mesh::*calc_edge_sqr_length_hh)(OM::HalfedgeHandle) const = &Mesh::calc_edge_sqr_length;
Scalar (Mesh::*calc_dihedral_angle_fast_hh)(OM::HalfedgeHandle) const = &Mesh::calc_dihedral_angle_fast;
Scalar (Mesh::*calc_dihedral_angle_fast_eh)(OM::EdgeHandle ) const = &Mesh::calc_dihedral_angle_fast;
Scalar (Mesh::*calc_dihedral_angle_hh)(OM::HalfedgeHandle) const = &Mesh::calc_dihedral_angle;
Scalar (Mesh::*calc_dihedral_angle_eh)(OM::EdgeHandle ) const = &Mesh::calc_dihedral_angle;
unsigned int (Mesh::*find_feature_edges)(Scalar) = &Mesh::find_feature_edges;
void (Mesh::*split_fh_vh)(OM::FaceHandle, OM::VertexHandle) = &Mesh::split;
void (Mesh::*split_eh_vh)(OM::EdgeHandle, OM::VertexHandle) = &Mesh::split;
void (Mesh::*split_copy_fh_vh)(OM::FaceHandle, OM::VertexHandle) = &Mesh::split_copy;
//======================================================================
// Mesh Type
//======================================================================
py::class_<Mesh> class_mesh(m, _name);
class_mesh
.def(py::init<>())
.def(py::init([](py::array_t<typename Point::value_type> _points, py::array_t<int> _faces) {
Mesh mesh;
// return if _points is empty
if (_points.size() == 0) {
return mesh;
}
// _points is not empty, throw if _points has wrong shape
if (_points.ndim() != 2 || _points.shape(1) != 3) {
PyErr_SetString(PyExc_RuntimeError, "Array 'points' must have shape (n, 3)");
throw py::error_already_set();
}
for (ssize_t i = 0; i < _points.shape(0); ++i) {
mesh.add_vertex(Point(_points.at(i, 0), _points.at(i, 1), _points.at(i, 2)));
}
// return if _faces is empty
if (_faces.size() == 0) {
return mesh;
}
// _faces is not empty, throw if _faces has wrong shape
if (_faces.ndim() != 2 || _faces.shape(1) < 3) {
PyErr_SetString(PyExc_RuntimeError, "Array 'face_vertex_indices' must have shape (n, m) with m > 2");
throw py::error_already_set();
}
for (ssize_t i = 0; i < _faces.shape(0); ++i) {
std::vector<OM::VertexHandle> vhandles;
for (ssize_t j = 0; j < _faces.shape(1); ++j) {
if (_faces.at(i, j) >= 0 && _faces.at(i, j) < _points.shape(0)) {
vhandles.push_back(OM::VertexHandle(_faces.at(i, j)));
}
}
if (vhandles.size() >= 3) {
mesh.add_face(vhandles);
}
}
return mesh;
}), py::arg("points"), py::arg("face_vertex_indices")=py::array_t<int>())
//======================================================================
// Copy interface
//======================================================================
.def("__copy__", &Mesh::py_copy)
.def("__deepcopy__", &Mesh::py_deepcopy)
//======================================================================
// KernelT
//======================================================================
.def("reserve", &Mesh::reserve)
.def("vertex_handle", vertex_handle_uint)
.def("halfedge_handle", halfedge_handle_uint)
.def("edge_handle", edge_handle_uint)
.def("face_handle", face_handle_uint)
.def("clear", &Mesh::clear)
.def("clean", &Mesh::clean)
.def("garbage_collection", garbage_collection_bools,
py::arg("v")=true, py::arg("e")=true, py::arg("f")=true)
.def("garbage_collection", garbage_collection_lists_bools,
py::arg("vh_to_update"), py::arg("hh_to_update"), py::arg("fh_to_update"),
py::arg("v")=true, py::arg("e")=true, py::arg("f")=true)
.def("n_vertices", &Mesh::n_vertices)
.def("n_halfedges", &Mesh::n_halfedges)
.def("n_edges", &Mesh::n_edges)
.def("n_faces", &Mesh::n_faces)
.def("vertices_empty", &Mesh::vertices_empty)
.def("halfedges_empty", &Mesh::halfedges_empty)
.def("edges_empty", &Mesh::edges_empty)
.def("faces_empty", &Mesh::faces_empty)
.def("halfedge_handle", halfedge_handle_vh)
.def("set_halfedge_handle", set_halfedge_handle_vh_hh)
.def("to_vertex_handle", &Mesh::to_vertex_handle)
.def("from_vertex_handle", &Mesh::from_vertex_handle)
.def("set_vertex_handle", &Mesh::set_vertex_handle)
.def("face_handle", face_handle_hh)
.def("set_face_handle", &Mesh::set_face_handle)
.def("next_halfedge_handle", &Mesh::next_halfedge_handle)
.def("set_next_halfedge_handle", &Mesh::set_next_halfedge_handle)
.def("prev_halfedge_handle", prev_halfedge_handle_hh)
.def("opposite_halfedge_handle", &Mesh::opposite_halfedge_handle)
.def("ccw_rotated_halfedge_handle", &Mesh::ccw_rotated_halfedge_handle)
.def("cw_rotated_halfedge_handle", &Mesh::cw_rotated_halfedge_handle)
.def("edge_handle", edge_handle_hh)
.def("halfedge_handle", halfedge_handle_eh_uint)
.def("halfedge_handle", halfedge_handle_fh)
.def("set_halfedge_handle", set_halfedge_handle_fh_hh)
.def("is_deleted", [](Mesh& _self, OM::VertexHandle _h) {
if (!_self.has_vertex_status()) return false;
return _self.status(_h).deleted();
})
.def("set_deleted", [](Mesh& _self, OM::VertexHandle _h, bool _val) {
if (!_self.has_vertex_status()) _self.request_vertex_status();
_self.status(_h).set_deleted(_val);
})
.def("is_deleted", [](Mesh& _self, OM::HalfedgeHandle _h) {
if (!_self.has_halfedge_status()) return false;
return _self.status(_h).deleted();
})
.def("set_deleted", [](Mesh& _self, OM::HalfedgeHandle _h, bool _val) {
if (!_self.has_halfedge_status()) _self.request_halfedge_status();
_self.status(_h).set_deleted(_val);
})
.def("is_deleted", [](Mesh& _self, OM::EdgeHandle _h) {
if (!_self.has_edge_status()) return false;
return _self.status(_h).deleted();
})
.def("set_deleted", [](Mesh& _self, OM::EdgeHandle _h, bool _val) {
if (!_self.has_edge_status()) _self.request_edge_status();
_self.status(_h).set_deleted(_val);
})
.def("is_deleted", [](Mesh& _self, OM::FaceHandle _h) {
if (!_self.has_face_status()) return false;
return _self.status(_h).deleted();
})
.def("set_deleted", [](Mesh& _self, OM::FaceHandle _h, bool _val) {
if (!_self.has_face_status()) _self.request_face_status();
_self.status(_h).set_deleted(_val);
})
.def("request_vertex_normals", &Mesh::request_vertex_normals)
.def("request_vertex_colors", &Mesh::request_vertex_colors)
.def("request_vertex_texcoords1D", &Mesh::request_vertex_texcoords1D)
.def("request_vertex_texcoords2D", &Mesh::request_vertex_texcoords2D)
.def("request_vertex_texcoords3D", &Mesh::request_vertex_texcoords3D)
.def("request_halfedge_normals", &Mesh::request_halfedge_normals)
.def("request_halfedge_colors", &Mesh::request_halfedge_colors)
.def("request_halfedge_texcoords1D", &Mesh::request_halfedge_texcoords1D)
.def("request_halfedge_texcoords2D", &Mesh::request_halfedge_texcoords2D)
.def("request_halfedge_texcoords3D", &Mesh::request_halfedge_texcoords3D)
.def("request_edge_colors", &Mesh::request_edge_colors)
.def("request_face_normals", &Mesh::request_face_normals)
.def("request_face_colors", &Mesh::request_face_colors)
.def("request_face_texture_index", &Mesh::request_face_texture_index)
.def("release_vertex_normals", &Mesh::release_vertex_normals)
.def("release_vertex_colors", &Mesh::release_vertex_colors)
.def("release_vertex_texcoords1D", &Mesh::release_vertex_texcoords1D)
.def("release_vertex_texcoords2D", &Mesh::release_vertex_texcoords2D)
.def("release_vertex_texcoords3D", &Mesh::release_vertex_texcoords3D)
.def("release_halfedge_normals", &Mesh::release_halfedge_normals)
.def("release_halfedge_colors", &Mesh::release_halfedge_colors)
.def("release_halfedge_texcoords1D", &Mesh::release_halfedge_texcoords1D)
.def("release_halfedge_texcoords2D", &Mesh::release_halfedge_texcoords2D)
.def("release_halfedge_texcoords3D", &Mesh::release_halfedge_texcoords3D)
.def("release_edge_colors", &Mesh::release_edge_colors)
.def("release_face_normals", &Mesh::release_face_normals)
.def("release_face_colors", &Mesh::release_face_colors)
.def("release_face_texture_index", &Mesh::release_face_texture_index)
.def("has_vertex_normals", &Mesh::has_vertex_normals)
.def("has_vertex_colors", &Mesh::has_vertex_colors)
.def("has_vertex_texcoords1D", &Mesh::has_vertex_texcoords1D)
.def("has_vertex_texcoords2D", &Mesh::has_vertex_texcoords2D)
.def("has_vertex_texcoords3D", &Mesh::has_vertex_texcoords3D)
.def("has_halfedge_normals", &Mesh::has_halfedge_normals)
.def("has_halfedge_colors", &Mesh::has_halfedge_colors)
.def("has_halfedge_texcoords1D", &Mesh::has_halfedge_texcoords1D)
.def("has_halfedge_texcoords2D", &Mesh::has_halfedge_texcoords2D)
.def("has_halfedge_texcoords3D", &Mesh::has_halfedge_texcoords3D)
.def("has_edge_colors", &Mesh::has_edge_colors)
.def("has_face_normals", &Mesh::has_face_normals)
.def("has_face_colors", &Mesh::has_face_colors)
.def("has_face_texture_index", &Mesh::has_face_texture_index)
.def("new_vertex", new_vertex_void)
.def("new_vertex", [](Mesh& _self, py::array_t<typename Point::value_type> _arr) {
return _self.new_vertex(Point(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("new_edge", &Mesh::new_edge)
.def("new_face", new_face_void)
.def("new_face", new_face_face)
.def("vertices", vertices)
.def("halfedges", halfedges)
.def("edges", edges)
.def("faces", faces)
.def("svertices", svertices)
.def("shalfedges", shalfedges)
.def("sedges", sedges)
.def("sfaces", sfaces)
.def("texture_index", [](Mesh& _self, OM::FaceHandle _h) {
if (!_self.has_face_texture_index()) _self.request_face_texture_index();
return _self.texture_index(_h);
})
.def("set_texture_index", [](Mesh& _self, OM::FaceHandle _h, TextureIndex _idx) {
if (!_self.has_face_texture_index()) _self.request_face_texture_index();
_self.set_texture_index(_h, _idx);
})
.def("texture_name", [](Mesh& _self, TextureIndex _idx) {
OM::MPropHandleT<std::map<TextureIndex, std::string> > prop;
if (_self.get_property_handle(prop, "TextureMapping")) {
const auto map = _self.property(prop);
if (map.count(_idx) == 0) {
throw py::index_error();
}
else {
return map.at(_idx);
}
}
else {
PyErr_SetString(PyExc_RuntimeError, "Mesh has no textures.");
throw py::error_already_set();
}
})
//======================================================================
// BaseKernel
//======================================================================
.def("copy_all_properties", copy_all_properties_vh_vh_bool,
py::arg("vh_from"), py::arg("vh_to"), py::arg("copy_build_in")=false)
.def("copy_all_properties", copy_all_properties_hh_hh_bool,
py::arg("hh_from"), py::arg("hh_to"), py::arg("copy_build_in")=false)
.def("copy_all_properties", copy_all_properties_eh_eh_bool,
py::arg("eh_from"), py::arg("eh_to"), py::arg("copy_build_in")=false)
.def("copy_all_properties", copy_all_properties_fh_fh_bool,
py::arg("fh_from"), py::arg("fh_to"), py::arg("copy_build_in")=false)
//======================================================================
// ArrayKernel
//======================================================================
.def("is_valid_handle", (bool (Mesh::*)(OM::VertexHandle) const) &Mesh::is_valid_handle)
.def("is_valid_handle", (bool (Mesh::*)(OM::HalfedgeHandle) const) &Mesh::is_valid_handle)
.def("is_valid_handle", (bool (Mesh::*)(OM::EdgeHandle) const) &Mesh::is_valid_handle)
.def("is_valid_handle", (bool (Mesh::*)(OM::FaceHandle) const) &Mesh::is_valid_handle)
.def("delete_isolated_vertices", [](Mesh& _self) {
if (!_self.has_vertex_status()) _self.request_vertex_status();
_self.delete_isolated_vertices();
})
//======================================================================
// PolyConnectivity
//======================================================================
.def("assign_connectivity", assign_connectivity_poly)
.def("assign_connectivity", assign_connectivity_tri)
.def("add_face", add_face_3_vh)
.def("add_face", add_face_list)
.def("opposite_face_handle", &Mesh::opposite_face_handle)
.def("adjust_outgoing_halfedge", &Mesh::adjust_outgoing_halfedge)
.def("find_halfedge", &Mesh::find_halfedge)
.def("valence", valence_vh)
.def("valence", valence_fh)
.def("is_simple_link", &Mesh::is_simple_link)
.def("is_simply_connected", &Mesh::is_simply_connected)
.def("remove_edge", &Mesh::remove_edge)
.def("reinsert_edge", &Mesh::reinsert_edge)
.def("triangulate", triangulate_fh)
.def("triangulate", triangulate_void)
.def("split_edge", &Mesh::split_edge)
.def("split_edge_copy", &Mesh::split_edge_copy)
.def("is_collapse_ok", [](Mesh& _self, OM::HalfedgeHandle _heh) {
if (!_self.has_vertex_status()) _self.request_vertex_status();
if (!_self.has_halfedge_status()) _self.request_halfedge_status();
if (!_self.has_edge_status()) _self.request_edge_status();
if (!_self.has_face_status()) _self.request_face_status();
return _self.is_collapse_ok(_heh);
})
.def("collapse", [](Mesh& _self, OM::HalfedgeHandle _heh) {
if (!_self.has_vertex_status()) _self.request_vertex_status();
if (!_self.has_halfedge_status()) _self.request_halfedge_status();
if (!_self.has_edge_status()) _self.request_edge_status();
if (!_self.has_face_status()) _self.request_face_status();
_self.collapse(_heh);
})
.def("add_vertex", [](Mesh& _self, py::array_t<typename Point::value_type> _arr) {
return _self.add_vertex(Point(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("delete_vertex", [](Mesh& _self, OM::VertexHandle _vh, bool _delete_isolated) {
if (!_self.has_vertex_status()) _self.request_vertex_status();
if (!_self.has_halfedge_status()) _self.request_halfedge_status();
if (!_self.has_edge_status()) _self.request_edge_status();
if (!_self.has_face_status()) _self.request_face_status();
_self.delete_vertex(_vh, _delete_isolated);
}, py::arg("vh"), py::arg("delete_isolated_vertices")=true)
.def("delete_edge", [](Mesh& _self, OM::EdgeHandle _eh, bool _delete_isolated) {
if (!_self.has_vertex_status() && _delete_isolated) _self.request_vertex_status();
if (!_self.has_halfedge_status()) _self.request_halfedge_status();
if (!_self.has_edge_status()) _self.request_edge_status();
if (!_self.has_face_status()) _self.request_face_status();
_self.delete_edge(_eh, _delete_isolated);
}, py::arg("eh"), py::arg("delete_isolated_vertices")=true)
.def("delete_face", [](Mesh& _self, OM::FaceHandle _fh, bool _delete_isolated) {
if (!_self.has_vertex_status() && _delete_isolated) _self.request_vertex_status();
if (!_self.has_halfedge_status()) _self.request_halfedge_status();
if (!_self.has_edge_status()) _self.request_edge_status();
if (!_self.has_face_status()) _self.request_face_status();
_self.delete_face(_fh, _delete_isolated);
}, py::arg("fh"), py::arg("delete_isolated_vertices")=true)
.def("vv", vv)
.def("vih", vih)
.def("voh", voh)
.def("ve", ve)
.def("vf", vf)
.def("fv", fv)
.def("fh", fh)
.def("fe", fe)
.def("ff", ff)
.def("hl", hl)
.def("is_boundary", is_boundary_hh)
.def("is_boundary", is_boundary_eh)
.def("is_boundary", is_boundary_vh)
.def("is_boundary", is_boundary_fh, py::arg("fh"), py::arg("check_vertex")=false)
.def("is_manifold", &Mesh::is_manifold)
.def_static("is_triangles", &Mesh::is_triangles)
.def_readonly_static("InvalidVertexHandle", &Mesh::InvalidVertexHandle)
.def_readonly_static("InvalidHalfedgeHandle", &Mesh::InvalidHalfedgeHandle)
.def_readonly_static("InvalidEdgeHandle", &Mesh::InvalidEdgeHandle)
.def_readonly_static("InvalidFaceHandle", &Mesh::InvalidFaceHandle)
//======================================================================
// PolyMeshT
//======================================================================
.def("calc_edge_length", calc_edge_length_eh)
.def("calc_edge_length", calc_edge_length_hh)
.def("calc_edge_sqr_length", calc_edge_sqr_length_eh)
.def("calc_edge_sqr_length", calc_edge_sqr_length_hh)
.def("calc_sector_angle", &Mesh::calc_sector_angle)
.def("calc_sector_area", &Mesh::calc_sector_area)
.def("calc_dihedral_angle_fast", calc_dihedral_angle_fast_hh)
.def("calc_dihedral_angle_fast", calc_dihedral_angle_fast_eh)
.def("calc_dihedral_angle", calc_dihedral_angle_hh)
.def("calc_dihedral_angle", calc_dihedral_angle_eh)
.def("find_feature_edges", find_feature_edges, py::arg("angle_tresh")=OM::deg_to_rad(44.0))
.def("split", split_fh_vh)
.def("split", split_eh_vh)
.def("split_copy", split_copy_fh_vh)
.def("update_normals", [](Mesh& _self) {
if (!_self.has_face_normals()) {
_self.request_face_normals();
}
if (!_self.has_halfedge_normals()) {
_self.request_halfedge_normals();
}
if (!_self.has_vertex_normals()) {
_self.request_vertex_normals();
}
_self.update_normals();
})
.def("update_normal", [](Mesh& _self, OM::FaceHandle _fh) {
if (!_self.has_face_normals()) _self.request_face_normals();
_self.update_normal(_fh);
})
.def("update_face_normals", [](Mesh& _self) {
if (!_self.has_face_normals()) _self.request_face_normals();
_self.update_face_normals();
})
.def("update_normal", [](Mesh& _self, OM::HalfedgeHandle _hh, double _feature_angle) {
if (!_self.has_face_normals()) {
_self.request_face_normals();
_self.update_face_normals();
}
if (!_self.has_halfedge_normals()) {
_self.request_halfedge_normals();
}
_self.update_normal(_hh, _feature_angle);
}, py::arg("heh"), py::arg("feature_angle")=0.8)
.def("update_halfedge_normals", [](Mesh& _self, double _feature_angle) {
if (!_self.has_face_normals()) {
_self.request_face_normals();
_self.update_face_normals();
}
if (!_self.has_halfedge_normals()) {
_self.request_halfedge_normals();
}
_self.update_halfedge_normals(_feature_angle);
}, py::arg("feature_angle")=0.8)
.def("update_normal", [](Mesh& _self, OM::VertexHandle _vh) {
if (!_self.has_face_normals()) {
_self.request_face_normals();
_self.update_face_normals();
}
if (!_self.has_vertex_normals()) {
_self.request_vertex_normals();
}
_self.update_normal(_vh);
})
.def("update_vertex_normals", [](Mesh& _self) {
if (!_self.has_face_normals()) {
_self.request_face_normals();
_self.update_face_normals();
}
if (!_self.has_vertex_normals()) {
_self.request_vertex_normals();
}
_self.update_vertex_normals();
})
.def("is_estimated_feature_edge", &Mesh::is_estimated_feature_edge)
.def_static("is_polymesh", &Mesh::is_polymesh)
.def("is_trimesh", &Mesh::is_trimesh)
//======================================================================
// numpy calc_*
//======================================================================
.def("calc_face_normal", [](Mesh& _self, OM::FaceHandle _fh) {
return vec2numpy(_self.calc_face_normal(_fh));
})
.def("calc_halfedge_normal", [](Mesh& _self, OM::HalfedgeHandle _heh, double _feature_angle) {
if (!_self.has_face_normals()) {
_self.request_face_normals();
_self.update_face_normals();
}
return vec2numpy(_self.calc_halfedge_normal(_heh, _feature_angle));
}, py::arg("heh"), py::arg("feature_angle")=0.8)
.def("calc_vertex_normal", [](Mesh& _self, OM::VertexHandle _vh) {
if (!_self.has_face_normals()) {
_self.request_face_normals();
_self.update_face_normals();
}
return vec2numpy(_self.calc_vertex_normal(_vh));
})
.def("calc_vertex_normal_fast", [](Mesh& _self, OM::VertexHandle _vh) {
if (!_self.has_face_normals()) {
_self.request_face_normals();
_self.update_face_normals();
}
typename Mesh::Normal n;
_self.calc_vertex_normal_fast(_vh, n);
return vec2numpy(n);
})
.def("calc_vertex_normal_correct", [](Mesh& _self, OM::VertexHandle _vh) {
typename Mesh::Normal n;
_self.calc_vertex_normal_correct(_vh, n);
return vec2numpy(n);
})
.def("calc_vertex_normal_loop", [](Mesh& _self, OM::VertexHandle _vh) {
typename Mesh::Normal n;
_self.calc_vertex_normal_loop(_vh, n);
return vec2numpy(n);
})
.def("calc_face_centroid", [](Mesh& _self, OM::FaceHandle _fh) {
return vec2numpy(_self.calc_face_centroid(_fh));
})
.def("calc_edge_vector", [](Mesh& _self, OM::EdgeHandle _eh) {
return vec2numpy(_self.calc_edge_vector(_eh));
})
.def("calc_edge_vector", [](Mesh& _self, OM::HalfedgeHandle _heh) {
return vec2numpy(_self.calc_edge_vector(_heh));
})
.def("calc_sector_vectors", [](Mesh& _self, OM::HalfedgeHandle _heh) {
typename Mesh::Normal vec0;
typename Mesh::Normal vec1;
_self.calc_sector_vectors(_heh, vec0, vec1);
return std::make_tuple(vec2numpy(vec0), vec2numpy(vec1));
})
.def("calc_sector_normal", [](Mesh& _self, OM::HalfedgeHandle _heh) {
typename Mesh::Normal n;
_self.calc_sector_normal(_heh, n);
return vec2numpy(n);
})
//======================================================================
// numpy vector getter
//======================================================================
.def("point", [](Mesh& _self, OM::VertexHandle _h) {
return vec2numpy(_self, _self.point(_h));
})
.def("normal", [](Mesh& _self, OM::VertexHandle _h) {
if (!_self.has_vertex_normals()) _self.request_vertex_normals();
return vec2numpy(_self, _self.normal(_h));
})
.def("normal", [](Mesh& _self, OM::HalfedgeHandle _h) {
if (!_self.has_halfedge_normals()) _self.request_halfedge_normals();
return vec2numpy(_self, _self.normal(_h));
})
.def("normal", [](Mesh& _self, OM::FaceHandle _h) {
if (!_self.has_face_normals()) _self.request_face_normals();
return vec2numpy(_self, _self.normal(_h));
})
.def("color", [](Mesh& _self, OM::VertexHandle _h) {
if (!_self.has_vertex_colors()) _self.request_vertex_colors();
return vec2numpy(_self, _self.color(_h));
})
.def("color", [](Mesh& _self, OM::HalfedgeHandle _h) {
if (!_self.has_halfedge_colors()) _self.request_halfedge_colors();
return vec2numpy(_self, _self.color(_h));
})
.def("color", [](Mesh& _self, OM::EdgeHandle _h) {
if (!_self.has_edge_colors()) _self.request_edge_colors();
return vec2numpy(_self, _self.color(_h));
})
.def("color", [](Mesh& _self, OM::FaceHandle _h) {
if (!_self.has_face_colors()) _self.request_face_colors();
return vec2numpy(_self, _self.color(_h));
})
.def("texcoord1D", [](Mesh& _self, OM::VertexHandle _h) {
if (!_self.has_vertex_texcoords1D()) _self.request_vertex_texcoords1D();
return flt2numpy(_self, _self.texcoord1D(_h));
})
.def("texcoord1D", [](Mesh& _self, OM::HalfedgeHandle _h) {
if (!_self.has_halfedge_texcoords1D()) _self.request_halfedge_texcoords1D();
return flt2numpy(_self, _self.texcoord1D(_h));
})
.def("texcoord2D", [](Mesh& _self, OM::VertexHandle _h) {
if (!_self.has_vertex_texcoords2D()) _self.request_vertex_texcoords2D();
return vec2numpy(_self, _self.texcoord2D(_h));
})
.def("texcoord2D", [](Mesh& _self, OM::HalfedgeHandle _h) {
if (!_self.has_halfedge_texcoords2D()) _self.request_halfedge_texcoords2D();
return vec2numpy(_self, _self.texcoord2D(_h));
})
.def("texcoord3D", [](Mesh& _self, OM::VertexHandle _h) {
if (!_self.has_vertex_texcoords3D()) _self.request_vertex_texcoords3D();
return vec2numpy(_self, _self.texcoord3D(_h));
})
.def("texcoord3D", [](Mesh& _self, OM::HalfedgeHandle _h) {
if (!_self.has_halfedge_texcoords3D()) _self.request_halfedge_texcoords3D();
return vec2numpy(_self, _self.texcoord3D(_h));
})
//======================================================================
// numpy vector setter
//======================================================================
.def("set_point", [](Mesh& _self, OM::VertexHandle _h, py::array_t<typename Point::value_type> _arr) {
_self.point(_h) = Point(_arr.at(0), _arr.at(1), _arr.at(2));
})
.def("set_normal", [](Mesh& _self, OM::VertexHandle _h, py::array_t<typename Normal::value_type> _arr) {
if (!_self.has_vertex_normals()) _self.request_vertex_normals();
_self.set_normal(_h, typename Mesh::Normal(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("set_normal", [](Mesh& _self, OM::HalfedgeHandle _h, py::array_t<typename Normal::value_type> _arr) {
if (!_self.has_halfedge_normals()) _self.request_halfedge_normals();
_self.set_normal(_h, typename Mesh::Normal(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("set_normal", [](Mesh& _self, OM::FaceHandle _h, py::array_t<typename Normal::value_type> _arr) {
if (!_self.has_face_normals()) _self.request_face_normals();
_self.set_normal(_h, typename Mesh::Normal(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("set_color", [](Mesh& _self, OM::VertexHandle _h, py::array_t<typename Color::value_type> _arr) {
if(!_self.has_vertex_colors()) _self.request_vertex_colors();
_self.set_color(_h, typename Mesh::Color(_arr.at(0), _arr.at(1), _arr.at(2), _arr.at(3)));
})
.def("set_color", [](Mesh& _self, OM::HalfedgeHandle _h, py::array_t<typename Color::value_type> _arr) {
if(!_self.has_halfedge_colors()) _self.request_halfedge_colors();
_self.set_color(_h, typename Mesh::Color(_arr.at(0), _arr.at(1), _arr.at(2), _arr.at(3)));
})
.def("set_color", [](Mesh& _self, OM::EdgeHandle _h, py::array_t<typename Color::value_type> _arr) {
if(!_self.has_edge_colors()) _self.request_edge_colors();
_self.set_color(_h, typename Mesh::Color(_arr.at(0), _arr.at(1), _arr.at(2), _arr.at(3)));
})
.def("set_color", [](Mesh& _self, OM::FaceHandle _h, py::array_t<typename Color::value_type> _arr) {
if(!_self.has_face_colors()) _self.request_face_colors();
_self.set_color(_h, typename Mesh::Color(_arr.at(0), _arr.at(1), _arr.at(2), _arr.at(3)));
})
.def("set_texcoord1D", [](Mesh& _self, OM::VertexHandle _h, py::array_t<TexCoord1D> _arr) {
if (!_self.has_vertex_texcoords1D()) _self.request_vertex_texcoords1D();
_self.set_texcoord1D(_h, _arr.at(0));
})
.def("set_texcoord1D", [](Mesh& _self, OM::HalfedgeHandle _h, py::array_t<TexCoord1D> _arr) {
if (!_self.has_halfedge_texcoords1D()) _self.request_halfedge_texcoords1D();
_self.set_texcoord1D(_h, _arr.at(0));
})
.def("set_texcoord2D", [](Mesh& _self, OM::VertexHandle _h, py::array_t<typename TexCoord2D::value_type> _arr) {
if (!_self.has_vertex_texcoords2D()) _self.request_vertex_texcoords2D();
_self.set_texcoord2D(_h, typename Mesh::TexCoord2D(_arr.at(0), _arr.at(1)));
})
.def("set_texcoord2D", [](Mesh& _self, OM::HalfedgeHandle _h, py::array_t<typename TexCoord2D::value_type> _arr) {
if (!_self.has_halfedge_texcoords2D()) _self.request_halfedge_texcoords2D();
_self.set_texcoord2D(_h, typename Mesh::TexCoord2D(_arr.at(0), _arr.at(1)));
})
.def("set_texcoord3D", [](Mesh& _self, OM::VertexHandle _h, py::array_t<typename TexCoord3D::value_type> _arr) {
if (!_self.has_vertex_texcoords3D()) _self.request_vertex_texcoords3D();
_self.set_texcoord3D(_h, typename Mesh::TexCoord3D(_arr.at(0), _arr.at(1), _arr.at(2)));
})
.def("set_texcoord3D", [](Mesh& _self, OM::HalfedgeHandle _h, py::array_t<typename TexCoord3D::value_type> _arr) {
if (!_self.has_halfedge_texcoords3D()) _self.request_halfedge_texcoords3D();
_self.set_texcoord3D(_h, typename Mesh::TexCoord3D(_arr.at(0), _arr.at(1), _arr.at(2)));
})
//======================================================================
// numpy matrix getter
//======================================================================
.def("points", [](Mesh& _self) {
return vec2numpy(_self, _self.point(OM::VertexHandle(0)), _self.n_vertices());
})
.def("vertex_normals", [](Mesh& _self) {
if (!_self.has_vertex_normals()) _self.request_vertex_normals();
return vec2numpy(_self, _self.normal(OM::VertexHandle(0)), _self.n_vertices());
})
.def("vertex_colors", [](Mesh& _self) {
if (!_self.has_vertex_colors()) _self.request_vertex_colors();
return vec2numpy(_self, _self.color(OM::VertexHandle(0)), _self.n_vertices());
})
.def("vertex_texcoords1D", [](Mesh& _self) {
if (!_self.has_vertex_texcoords1D()) _self.request_vertex_texcoords1D();
return flt2numpy(_self, _self.texcoord1D(OM::VertexHandle(0)), _self.n_vertices());
})
.def("vertex_texcoords2D", [](Mesh& _self) {
if (!_self.has_vertex_texcoords2D()) _self.request_vertex_texcoords2D();
return vec2numpy(_self, _self.texcoord2D(OM::VertexHandle(0)), _self.n_vertices());
})
.def("vertex_texcoords3D", [](Mesh& _self) {
if (!_self.has_vertex_texcoords3D()) _self.request_vertex_texcoords3D();
return vec2numpy(_self, _self.texcoord3D(OM::VertexHandle(0)), _self.n_vertices());
})
.def("halfedge_normals", [](Mesh& _self) {
if (!_self.has_halfedge_normals()) _self.request_halfedge_normals();
return vec2numpy(_self, _self.normal(OM::HalfedgeHandle(0)), _self.n_halfedges());
})
.def("halfedge_colors", [](Mesh& _self) {
if (!_self.has_halfedge_colors()) _self.request_halfedge_colors();
return vec2numpy(_self, _self.color(OM::HalfedgeHandle(0)), _self.n_halfedges());
})
.def("halfedge_texcoords1D", [](Mesh& _self) {
if (!_self.has_halfedge_texcoords1D()) _self.request_halfedge_texcoords1D();
return flt2numpy(_self, _self.texcoord1D(OM::HalfedgeHandle(0)), _self.n_halfedges());
})
.def("halfedge_texcoords2D", [](Mesh& _self) {
if (!_self.has_halfedge_texcoords2D()) _self.request_halfedge_texcoords2D();
return vec2numpy(_self, _self.texcoord2D(OM::HalfedgeHandle(0)), _self.n_halfedges());
})
.def("halfedge_texcoords3D", [](Mesh& _self) {
if (!_self.has_halfedge_texcoords3D()) _self.request_halfedge_texcoords3D();
return vec2numpy(_self, _self.texcoord3D(OM::HalfedgeHandle(0)), _self.n_halfedges());
})
.def("edge_colors", [](Mesh& _self) {
if (!_self.has_edge_colors()) _self.request_edge_colors();
return vec2numpy(_self, _self.color(OM::EdgeHandle(0)), _self.n_edges());
})
.def("face_normals", [](Mesh& _self) {
if (!_self.has_face_normals()) _self.request_face_normals();
return vec2numpy(_self, _self.normal(OM::FaceHandle(0)), _self.n_faces());
})
.def("face_colors", [](Mesh& _self) {
if (!_self.has_face_colors()) _self.request_face_colors();
return vec2numpy(_self, _self.color (OM::FaceHandle(0)), _self.n_faces());
})
//======================================================================
// numpy indices
//======================================================================
.def("vertex_vertex_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexVertexIter>)
.def("vv_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexVertexIter>)
.def("vertex_face_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexFaceIter>)
.def("vf_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexFaceIter>)
.def("vertex_edge_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexEdgeIter>)
.def("ve_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexEdgeIter>)
.def("vertex_outgoing_halfedge_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexOHalfedgeIter>)
.def("voh_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexOHalfedgeIter>)
.def("vertex_incoming_halfedge_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexIHalfedgeIter>)
.def("vih_indices", &indices<Mesh, OM::VertexHandle, typename Mesh::VertexIHalfedgeIter>)
.def("face_face_indices", &indices<Mesh, OM::FaceHandle, typename Mesh::FaceFaceIter>)
.def("ff_indices", &indices<Mesh, OM::FaceHandle, typename Mesh::FaceFaceIter>)
.def("face_edge_indices", &indices<Mesh, OM::FaceHandle, typename Mesh::FaceEdgeIter>)
.def("fe_indices", &indices<Mesh, OM::FaceHandle, typename Mesh::FaceEdgeIter>)
.def("face_halfedge_indices", &indices<Mesh, OM::FaceHandle, typename Mesh::FaceHalfedgeIter>)
.def("fh_indices", &indices<Mesh, OM::FaceHandle, typename Mesh::FaceHalfedgeIter>)
.def("edge_vertex_indices", &edge_other_indices<Mesh, FuncEdgeVertex>)
.def("ev_indices", &edge_other_indices<Mesh, FuncEdgeVertex>)
.def("edge_face_indices", &edge_other_indices<Mesh, FuncEdgeFace>)
.def("ef_indices", &edge_other_indices<Mesh, FuncEdgeFace>)
.def("edge_halfedge_indices", &edge_other_indices<Mesh, FuncEdgeHalfedge>)
.def("eh_indices", &edge_other_indices<Mesh, FuncEdgeHalfedge>)
.def("halfedge_vertex_indices", &halfedge_other_indices<Mesh, FuncHalfedgeVertex>)
.def("hv_indices", &halfedge_other_indices<Mesh, FuncHalfedgeVertex>)
.def("halfedge_to_vertex_indices", &halfedge_other_indices<Mesh, FuncHalfedgeToVertex>)
.def("htv_indices", &halfedge_other_indices<Mesh, FuncHalfedgeToVertex>)
.def("halfedge_from_vertex_indices", &halfedge_other_indices<Mesh, FuncHalfedgeFromVertex>)
.def("hfv_indices", &halfedge_other_indices<Mesh, FuncHalfedgeFromVertex>)
.def("halfedge_face_indices", &halfedge_other_indices<Mesh, FuncHalfedgeFace>)
.def("hf_indices", &halfedge_other_indices<Mesh, FuncHalfedgeFace>)
.def("halfedge_edge_indices", &halfedge_other_indices<Mesh, FuncHalfedgeEdge>)
.def("he_indices", &halfedge_other_indices<Mesh, FuncHalfedgeEdge>)
//======================================================================
// new property interface: single item
//======================================================================
.def("vertex_property", &Mesh::template py_property<OM::VertexHandle, typename Mesh::VPropHandle>)
.def("halfedge_property", &Mesh::template py_property<OM::HalfedgeHandle, typename Mesh::HPropHandle>)
.def("edge_property", &Mesh::template py_property<OM::EdgeHandle, typename Mesh::EPropHandle>)
.def("face_property", &Mesh::template py_property<OM::FaceHandle, typename Mesh::FPropHandle>)
.def("set_vertex_property", &Mesh::template py_set_property<OM::VertexHandle, typename Mesh::VPropHandle>)
.def("set_halfedge_property", &Mesh::template py_set_property<OM::HalfedgeHandle, typename Mesh::HPropHandle>)
.def("set_edge_property", &Mesh::template py_set_property<OM::EdgeHandle, typename Mesh::EPropHandle>)
.def("set_face_property", &Mesh::template py_set_property<OM::FaceHandle, typename Mesh::FPropHandle>)
.def("has_vertex_property", &Mesh::template py_has_property<OM::VertexHandle>)
.def("has_halfedge_property", &Mesh::template py_has_property<OM::HalfedgeHandle>)
.def("has_edge_property", &Mesh::template py_has_property<OM::EdgeHandle>)
.def("has_face_property", &Mesh::template py_has_property<OM::FaceHandle>)
.def("remove_vertex_property", &Mesh::template py_remove_property<OM::VertexHandle>)
.def("remove_halfedge_property", &Mesh::template py_remove_property<OM::HalfedgeHandle>)
.def("remove_edge_property", &Mesh::template py_remove_property<OM::EdgeHandle>)
.def("remove_face_property", &Mesh::template py_remove_property<OM::FaceHandle>)
//======================================================================
// new property interface: generic
//======================================================================
.def("vertex_property", &Mesh::template py_property_generic<OM::VertexHandle, typename Mesh::VPropHandle>)
.def("halfedge_property", &Mesh::template py_property_generic<OM::HalfedgeHandle, typename Mesh::HPropHandle>)
.def("edge_property", &Mesh::template py_property_generic<OM::EdgeHandle, typename Mesh::EPropHandle>)
.def("face_property", &Mesh::template py_property_generic<OM::FaceHandle, typename Mesh::FPropHandle>)
.def("set_vertex_property", &Mesh::template py_set_property_generic<OM::VertexHandle, typename Mesh::VPropHandle>)
.def("set_halfedge_property", &Mesh::template py_set_property_generic<OM::HalfedgeHandle, typename Mesh::HPropHandle>)
.def("set_edge_property", &Mesh::template py_set_property_generic<OM::EdgeHandle, typename Mesh::EPropHandle>)
.def("set_face_property", &Mesh::template py_set_property_generic<OM::FaceHandle, typename Mesh::FPropHandle>)
//======================================================================
// new property interface: array
//======================================================================
.def("vertex_property_array", &Mesh::template py_property_array<OM::VertexHandle, typename Mesh::VPropHandle>)
.def("halfedge_property_array", &Mesh::template py_property_array<OM::HalfedgeHandle, typename Mesh::HPropHandle>)
.def("edge_property_array", &Mesh::template py_property_array<OM::EdgeHandle, typename Mesh::EPropHandle>)
.def("face_property_array", &Mesh::template py_property_array<OM::FaceHandle, typename Mesh::FPropHandle>)
.def("set_vertex_property_array", &Mesh::template py_set_property_array<OM::VertexHandle, typename Mesh::VPropHandle>)
.def("set_halfedge_property_array", &Mesh::template py_set_property_array<OM::HalfedgeHandle, typename Mesh::HPropHandle>)
.def("set_edge_property_array", &Mesh::template py_set_property_array<OM::EdgeHandle, typename Mesh::EPropHandle>)
.def("set_face_property_array", &Mesh::template py_set_property_array<OM::FaceHandle, typename Mesh::FPropHandle>)
//======================================================================
// new property interface: copy
//======================================================================
.def("copy_property", &Mesh::template py_copy_property<OM::VertexHandle, typename Mesh::VPropHandle>)
.def("copy_property", &Mesh::template py_copy_property<OM::HalfedgeHandle, typename Mesh::HPropHandle>)
.def("copy_property", &Mesh::template py_copy_property<OM::EdgeHandle, typename Mesh::EPropHandle>)
.def("copy_property", &Mesh::template py_copy_property<OM::FaceHandle, typename Mesh::FPropHandle>)
;
expose_type_specific_functions(class_mesh);
}
#endif
| 42.108451 | 161 | 0.674014 | nmaxwell |
bfa1e8340a88e16c329ca86b20a67fd6a41bd1d0 | 845 | hpp | C++ | libs/utils/include/suil/utils/uuid.hpp | suilteam/spark-xy | d07dc98c12c8842af0f11bf27d59161cb80f99b0 | [
"MIT"
] | null | null | null | libs/utils/include/suil/utils/uuid.hpp | suilteam/spark-xy | d07dc98c12c8842af0f11bf27d59161cb80f99b0 | [
"MIT"
] | null | null | null | libs/utils/include/suil/utils/uuid.hpp | suilteam/spark-xy | d07dc98c12c8842af0f11bf27d59161cb80f99b0 | [
"MIT"
] | null | null | null | /**
* Copyright (c) 2022 Suilteam, Carter Mbotho
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MIT license. See LICENSE for details.
*
* @author Carter
* @date 2022-03-12
*/
#pragma once
#include <cstdint>
#include <string>
namespace suil {
struct Uuid {
Uuid(unsigned char val[16]);
Uuid(const std::string_view& str = {});
std::string toString(bool lower = true) const;
bool operator==(const Uuid& other) const;
bool operator!=(const Uuid& other) const;
bool empty() const;
const unsigned char* raw() const { return &_bin[0]; }
private:
union {
struct {
uint64_t _hi;
uint64_t _lo;
};
unsigned char _bin[16] = {0};
};
};
} | 23.472222 | 74 | 0.564497 | suilteam |
bfa5cf0febca4df39ca6f4f7a29f86bd440c2c80 | 42,743 | cpp | C++ | utils/license_to_header.cpp | ZopharShinta/SegsEngine | 86d52c5b805e05e107594efd3358cabd694365f0 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | utils/license_to_header.cpp | ZopharShinta/SegsEngine | 86d52c5b805e05e107594efd3358cabd694365f0 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | utils/license_to_header.cpp | ZopharShinta/SegsEngine | 86d52c5b805e05e107594efd3358cabd694365f0 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | #include <QtCore/QFile>
#include <QtCore/QString>
#include <QFileInfo>
#include <QStringList>
#include <QHash>
#include <QCryptographicHash>
#include <QTextStream>
#include <QDebug>
#include <QSet>
#include <QJsonDocument>
#include <QMap>
#include <QDirIterator>
#include <QRegularExpression>
#include <QtCore/QCoreApplication>
#include <QtCore/QJsonArray>
#include <QJsonObject>
#include <cassert>
#ifdef _MSC_VER
#include <iso646.h>
#endif
#include <QDateTime>
#include <cstdio>
struct TpEntry
{
QString comment;
struct Entry {
QString tp_file, tp_copyright, tp_license;
};
QVector<Entry> entries;
};
QString escape_string(const QString &input)
{
QString result;
for(QChar c : input)
if (!c.isPrint() || c == '\\' || c=='"')
result += QString("\\%1").arg(uint8_t(c.toLatin1()),3,8,QChar('0'));
else
result += c;
return result;
}
class LicenseReader
{
public:
QString current;
QFile &_license_file;
int line_num = 0;
LicenseReader(QFile &license_file) : _license_file(license_file)
{
current = next_line();
}
QString next_line()
{
QString line = _license_file.readLine();
line_num += 1;
while(line.startsWith("#"))
{
line = _license_file.readLine();
line_num += 1;
}
current = line;
return line;
}
std::pair<QString,QStringList> next_tag()
{
if (not this->current.contains(':'))
return {"",{}};
QStringList parts = current.split(":");
assert(parts.size()>1);
QString tag = parts.takeFirst();
QStringList lines = { parts.join(':').trimmed() };
while((!next_line().isEmpty()) && current.startsWith(" "))
lines.append(current.trimmed());
return {tag, lines};
}
};
bool make_license_header(const QStringList &source)
{
QString src_copyright = QFileInfo(source[0]).absoluteFilePath();
QString src_license = QFileInfo(source[1]).absoluteFilePath();
QString dst = QFileInfo(source[2]).absoluteFilePath();
QFile license_file(src_license);
QFile copyright_file(src_copyright);
QFile g(dst);
if(!license_file.open(QFile::ReadOnly) || !copyright_file.open(QFile::ReadOnly) || !g.open(QFile::WriteOnly))
return false;
QTextStream out(&g);
out.setGenerateByteOrderMark(true);
out.setCodec("UTF-8");
QMap<QString,QVector<QHash<QString,QStringList>>> projects;
QVector<QStringList> license_list;
LicenseReader reader(copyright_file);
QHash<QString,QStringList> part = {};
QHash<QString,QStringList> *tgt_part = ∂
QStringList file_license_copyright_tags= {"Files", "Copyright", "License"};
while(!reader.current.isEmpty())
{
std::pair<QString,QStringList> tag_content = reader.next_tag();
if(file_license_copyright_tags.contains(tag_content.first))
{
(*tgt_part)[tag_content.first] = tag_content.second;
}
else if (tag_content.first == "Comment")
{
// attach part to named project
projects[tag_content.second[0]].append(part);
tgt_part = &projects[tag_content.second[0]].back();
}
if (tag_content.first.isEmpty() or reader.current.isEmpty())
{
// end of a paragraph start a new part
if (tgt_part->contains("License") and not tgt_part->contains("Files"))
{
// no Files tag in this one, so assume standalone license
license_list.append(part["License"]);
}
tgt_part = ∂
part.clear();
reader.next_line();
}
}
QStringList data_list;
for(auto &project : projects)
{
for(auto &part : project)
{
part["file_index"].append(QString::number(data_list.size()));
data_list.append(part["Files"]);
part["copyright_index"].append(QString::number(data_list.size()));
data_list.append(part["Copyright"]);
}
}
out << "/* THIS FILE IS GENERATED DO NOT EDIT */\n";
out << "#ifndef _EDITOR_LICENSE_H\n";
out << "#define _EDITOR_LICENSE_H\n";
out << "const char *const GODOT_LICENSE_TEXT =";
QString license_line;
QTextStream license_stream(&license_file);
while(license_stream.readLineInto(&license_line))
{
out << "\n\t\t\"" << escape_string(license_line.trimmed()) + "\\n\"";
}
out <<";\n\n";
out << "struct ComponentCopyrightPart {\n"
"\tconst char *license;\n"
"\tconst char *const *files;\n"
"\tconst char *const *copyright_statements;\n"
"\tint file_count;\n"
"\tint copyright_count;\n"
"};\n\n";
out << "struct ComponentCopyright {\n"
"\tconst char *name;\n"
"\tconst ComponentCopyrightPart *parts;\n"
"\tint part_count;\n"
"};\n\n";
out << "const char *const COPYRIGHT_INFO_DATA[] = {\n";
for (auto line : data_list)
out << "\t\"" << escape_string(line) << "\",\n";
out << "};\n\n";
out << "const ComponentCopyrightPart COPYRIGHT_PROJECT_PARTS[] = {\n";
int part_index = 0;
QMap<QString,int> part_indexes = {};
for(auto iter=projects.begin(),fin = projects.end(); iter!=fin; ++iter)
{
QString project_name = iter.key();
auto &project(iter.value());
part_indexes[project_name] = part_index;
for(const auto &part : project)
{
out << "\t{ \"" << escape_string(part["License"].front()) << "\", "
<< "©RIGHT_INFO_DATA[" << part["file_index"].join("") << "], "
<< "©RIGHT_INFO_DATA[" << part["copyright_index"].join("") << "], "
<< part["Files"].size() << ", "
<< part["Copyright"].size()<< " },\n";
part_index++;
}
}
out << "};\n\n";
out << "const int COPYRIGHT_INFO_COUNT = " << projects.size() << ";\n";
out << "const ComponentCopyright COPYRIGHT_INFO[] = {\n";
for(auto iter=projects.begin(),fin = projects.end(); iter!=fin; ++iter)
{
QString project_name = iter.key();
auto &project(iter.value());
out << "\t{ \"" << escape_string(project_name) << "\", "
<< "©RIGHT_PROJECT_PARTS[" << QString::number(part_indexes[project_name]) << "], "
<< QString::number(project.size()) << " },\n";
}
out << "};\n\n";
out << "const int LICENSE_COUNT = " << license_list.size() << ";\n";
out << "const char *const LICENSE_NAMES[] = {\n";
for (const auto &l : license_list)
out << "\t\"" << escape_string(l[0]) << "\",\n";
out << "};\n\n";
out << "const char *const LICENSE_BODIES[] = {\n\n";
for(auto & l : license_list)
{
for (const auto &line : l.mid(1))
{
if(line == ".")
out << "\t\"\\n\"\n";
else
out << "\t\"" << escape_string(line) << "\\n\"\n";
}
out << "\t\"\",\n\n";
}
out << "};\n\n";
out << "#endif\n";
return true;
}
bool make_license_header2(QStringList source)
{
QString src_copyright = QFileInfo(source[0]).absoluteFilePath();
QString src_license = QFileInfo(source[1]).absoluteFilePath();
QString dst = QFileInfo(source[2]).absoluteFilePath();
QFile f(src_license);
QFile fc(src_copyright);
QFile g(dst);
if(!f.open(QFile::ReadOnly) || !fc.open(QFile::ReadOnly) || !g.open(QFile::WriteOnly))
return false;
g.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n");
g.write("#ifndef _EDITOR_LICENSE_H\n");
g.write("#define _EDITOR_LICENSE_H\n");
g.write("static const char *GODOT_LICENSE_TEXT =");
QTextStream lic_stream(&f);
QString line;
while(lic_stream.readLineInto(&line))
{
QString escaped_string = escape_string(line.trimmed());
g.write(qUtf8Printable("\n\t\"" + escaped_string + "\\n\""));
}
g.write(";\n");
int tp_current = 0;
QString tp_file = "";
QString tp_comment = "";
QString tp_copyright = "";
QString tp_license = "";
QString tp_licensename = "";
QString tp_licensebody = "";
QVector<TpEntry> tp;
QVector<QPair<QString,QString>> tp_licensetext;
QTextStream copyright_stream(&fc);
while(copyright_stream.readLineInto(&line))
{
if(line.startsWith("#"))
continue;
if(line.startsWith("Files:"))
{
tp_file = line.mid(6).trimmed();
tp_current = 1;
}
else if (line.startsWith("Comment:"))
{
tp_comment = line.mid(8).trimmed();
tp_current = 2;
}
else if (line.startsWith("Copyright:"))
{
tp_copyright = line.mid(10).trimmed();
tp_current = 3;
}
else if (line.startsWith("License:"))
{
if (tp_current != 0)
{
tp_license = line.mid(8).trimmed();
tp_current = 4;
}
else
{
tp_licensename = line.mid(8).trimmed();
tp_current = 5;
}
}
else if (line.startsWith(" "))
{
if (tp_current == 1)
tp_file += "\n" + line.trimmed();
else if (tp_current == 3)
tp_copyright += "\n" + line.trimmed();
else if (tp_current == 5)
{
if (line.trimmed() == ".")
tp_licensebody += "\n";
else
tp_licensebody += line.midRef(1);
}
}
else
{
if (tp_current != 0)
{
if (tp_current == 5)
{
tp_licensetext.append({tp_licensename, tp_licensebody});
tp_licensename = "";
tp_licensebody = "";
}
else
{
bool added = false;
for(auto &i : tp)
{
if(i.comment == tp_comment)
{
i.entries.append(TpEntry::Entry {tp_file, tp_copyright, tp_license});
added = true;
break;
}
}
if(!added)
tp.append({tp_comment,{{tp_file, tp_copyright, tp_license}}});
tp_file.clear();
tp_comment.clear();
tp_copyright.clear();
tp_license.clear();
}
tp_current = 0;
}
}
}
tp_licensetext.push_back({ tp_licensename, tp_licensebody });
QString about_thirdparty = "";
QString about_tp_copyright_count = "";
QString about_tp_license = "";
QString about_tp_copyright = "";
QString about_tp_file = "";
for(auto i : tp)
{
about_thirdparty += "\t\"" + i.comment + "\",\n";
about_tp_copyright_count += QString::number(i.entries.size()) + ", ";
for(const auto &j : i.entries)
{
QString file_body = "";
QString copyright_body = "";
for(auto k : j.tp_file.split("\n"))
{
if(!file_body.isEmpty())
file_body += "\\n\"\n";
QString escaped_string = escape_string(k.trimmed());
file_body += "\t\"" + escaped_string;
}
for(auto k : j.tp_copyright.split("\n"))
{
if(!copyright_body.isEmpty())
copyright_body += "\\n\"\n";
QString escaped_string = escape_string(k.trimmed());
copyright_body += "\t\"" + escaped_string;
}
about_tp_file += "\t" + file_body + "\",\n";
about_tp_copyright += "\t" + copyright_body + "\",\n";
about_tp_license += "\t\"" + j.tp_license + "\",\n";
}
}
QString about_license_name = "";
QString about_license_body = "";
for(const QPair<QString,QString> &i : tp_licensetext)
{
QString body = "";
for (auto j : i.second.split("\n"))
{
if(!body.isEmpty())
body += "\\n\"\n";
QString escaped_string = escape_string(j.trimmed());
body += "\t\"" + escaped_string;
}
about_license_name += "\t\"" + i.first + "\",\n";
about_license_body += "\t" + body + "\",\n";
}
g.write("static const char *about_thirdparty[] = {\n");
g.write(about_thirdparty.toUtf8());
g.write("\t0\n");
g.write("};\n");
g.write(qPrintable("#define THIRDPARTY_COUNT " + QString::number(tp.size()) + "\n"));
g.write("static const int about_tp_copyright_count[] = {\n\t");
g.write(about_tp_copyright_count.toUtf8());
g.write("0\n};\n");
g.write("static const char *about_tp_file[] = {\n");
g.write(about_tp_file.toUtf8());
g.write("\t0\n");
g.write("};\n");
g.write("static const char *about_tp_copyright[] = {\n");
g.write(about_tp_copyright.toUtf8());
g.write("\tnullptr\n");
g.write("};\n");
g.write("static const char *about_tp_license[] = {\n");
g.write(about_tp_license.toUtf8());
g.write("\tnullptr\n");
g.write("};\n");
g.write("static const char *LICENSE_NAMES[] = {\n");
g.write(about_license_name.toUtf8());
g.write("\tnullptr\n");
g.write("};\n");
g.write(qPrintable("#define LICENSE_COUNT " + QString::number(tp_licensetext.size()) + "\n"));
g.write("static const char *LICENSE_BODIES[] = {\n");
g.write(about_license_body.toUtf8());
g.write("\tnullptr\n");
g.write("};\n");
g.write("#endif\n");
g.close();
fc.close();
f.close();
return true;
}
static void close_section(QTextStream &g)
{
g << "\tnullptr\n";
g << "};\n";
}
bool make_authors_header(const QStringList &source)
{
QStringList sections = {"Project Founders", "Lead Developer", "Project Manager", "Developers"};
QStringList sections_id = { "AUTHORS_FOUNDERS", "AUTHORS_LEAD_DEVELOPERS",
"AUTHORS_PROJECT_MANAGERS", "AUTHORS_DEVELOPERS" };
QString src_authors = QFileInfo(source[0]).absoluteFilePath();
QString dst = QFileInfo(source[1]).absoluteFilePath();
QFile f(src_authors);
QFile g(dst);
if(!f.open(QFile::ReadOnly|QFile::Text) || !g.open(QFile::WriteOnly))
return false;
QTextStream out(&g);
out.setGenerateByteOrderMark(true);
out.setCodec("UTF-8");
out << "/* THIS FILE IS GENERATED DO NOT EDIT */\n";
out << "#ifndef _EDITOR_AUTHORS_H\n";
out << "#define _EDITOR_AUTHORS_H\n";
QString current_section = "";
bool reading = false;
QString line;
QTextStream authors_stream(&f);
authors_stream.setCodec("UTF-8");
authors_stream.setGenerateByteOrderMark(true);
while(authors_stream.readLineInto(&line))
{
if (reading)
{
if(line.startsWith(" "))
{
out << "\t\"" << escape_string(line.trimmed()) << "\",\n";
continue;
}
}
if (line.startsWith("## "))
{
if (reading)
{
close_section(out);
reading = false;
}
for(int i=0; i<sections.size(); ++i)
{
QString section = sections[i];
if (line.trimmed().endsWith(section))
{
current_section = escape_string(sections_id[i]);
reading = true;
out<< "static const char *" << current_section << "[] = {\n";
break;
}
}
}
}
if(reading)
close_section(out);
out << "#endif\n";
return true;
}
bool make_donors_header(QStringList source)
{
QStringList sections = { "Platinum sponsors", "Gold sponsors", "Silver sponsors", "Bronze sponsors", "Mini sponsors",
"Gold donors", "Silver donors", "Bronze donors" };
QStringList sections_id = { "DONORS_SPONSOR_PLATINUM", "DONORS_SPONSOR_GOLD", "DONORS_SPONSOR_SILVER",
"DONORS_SPONSOR_BRONZE", "DONORS_SPONSOR_MINI", "DONORS_GOLD", "DONORS_SILVER", "DONORS_BRONZE" };
QString src_donors = QFileInfo(source[0]).absoluteFilePath();
QString dst = QFileInfo(source[1]).absoluteFilePath();
QFile f(src_donors);
QFile g(dst);
if(!f.open(QFile::ReadOnly) || !g.open(QFile::WriteOnly))
return false;
QTextStream out(&g);
out.setGenerateByteOrderMark(true);
out.setCodec("UTF-8");
out << "/* THIS FILE IS GENERATED DO NOT EDIT */\n";
out << "#ifndef _EDITOR_DONORS_H\n";
out << "#define _EDITOR_DONORS_H\n";
QString current_section = "";
bool reading = false;
QString line;
QTextStream donors_stream(&f);
while(donors_stream.readLineInto(&line))
{
if(reading)
{
if (line.startsWith(" "))
{
out << "\t\"" << escape_string(line.trimmed()) << "\",\n";
continue;
}
}
if (line.startsWith("## "))
{
if (reading)
{
close_section(out);
reading = false;
}
for(int i=0; i < sections.size(); ++i)
{
if (line.trimmed().endsWith(sections[i]))
{
current_section = escape_string(sections_id[i]);
reading = true;
out << "static const char *" << current_section << "[] = {\n";
break;
}
}
}
}
if (reading)
close_section(out);
out << "#endif\n";
return true;
}
static bool _make_doc_data_class_path(const QStringList &paths,const QString &to_path)
{
QFile g(to_path+"/doc_data_class_path.gen.h");
if(!g.open(QFile::WriteOnly))
return false;
QStringList sorted;
sorted.reserve(100);
for(const QString &path : paths)
{
if(path.contains("doc/classes")) // skip engine docs
continue;
sorted.push_back(path);
}
std::sort(sorted.begin(),sorted.end());
g.write(qPrintable("static const int _doc_data_class_path_count = " + QString::number(sorted.size()) + ";\n"));
g.write("struct _DocDataClassPath { const char* name; const char* path; };\n");
g.write(qPrintable("static const _DocDataClassPath _doc_data_class_paths[" + QString::number(sorted.size()+1) + "] = {\n"));
for(auto c : sorted)
{
QFileInfo fi(c);
QString module_path = fi.path();
module_path = module_path.mid(module_path.indexOf("modules"));
g.write(qUtf8Printable(QString("\t{\"%1\", \"%2\"},\n").arg(fi.baseName(), module_path)));
}
g.write("\t{nullptr, nullptr}\n");
g.write("};\n");
g.close();
return true;
}
QStringList collect_docs(const QString &src_path,const QString &tgt_doc_path)
{
QFile list_fl(src_path);
if(!list_fl.open(QFile::ReadOnly))
return {};
QStringList all_paths = QString(list_fl.readAll()).split(';');
QStringList docs;
for(const auto &path : all_paths)
{
if(path.isEmpty())
continue;
QDirIterator dir_iter(path.trimmed(),QDir::Files,QDirIterator::Subdirectories);
while(dir_iter.hasNext())
{
docs.push_back(dir_iter.next());
}
}
_make_doc_data_class_path(docs,tgt_doc_path);
// docs = sorted(docs)
return docs;
}
static void byteArrayToHexInFile(const QByteArray &src,QFile &g)
{
int column_count=0;
for(char b : src)
{
if(column_count==0)
g.write("\t");
g.write(qPrintable(QString("0x%1,").arg(uint16_t(uint8_t(b)),2,16,QChar('0'))));
column_count++;
if(column_count==20)
{
g.write("\n");
column_count=0;
}
}
}
bool collect_and_pack_docs(QStringList args)
{
QString doc_paths=args.takeFirst();
QString tgt_path= args.takeFirst();
QString dst = tgt_path+"/doc_data_compressed.gen.h";
QStringList all_doc_paths=collect_docs(doc_paths,tgt_path);
QFile g(dst);
if(!g.open(QFile::WriteOnly))
return false;
QByteArray buf = "";
for (const QString &s : all_doc_paths)
{
if(!s.endsWith(".xml"))
continue;
QString src = QFileInfo(s).absoluteFilePath();
QFile f(src);
QByteArray content;
if(f.open(QFile::ReadOnly))
content = f.readAll();
buf.append(content);
}
int decomp_size = buf.size();
QByteArray compressed = qCompress(buf);
compressed.remove(0,4); // remove the decomp size that is added by qCompress
g.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n");
g.write("#ifndef _DOC_DATA_RAW_H\n");
g.write("#define _DOC_DATA_RAW_H\n");
g.write(qPrintable("static const int _doc_data_compressed_size = " + QString::number(compressed.size()) + ";\n"));
g.write(qPrintable("static const int _doc_data_uncompressed_size = " + QString::number(decomp_size) + ";\n"));
g.write("static const unsigned char _doc_data_compressed[] = {\n");
byteArrayToHexInFile(compressed,g);
g.write("};\n");
g.write("#endif");
g.close();
return true;
}
bool make_translations_header(QStringList args)
{
QString translations_path=args.takeFirst();
QString tgt_path = args.takeFirst();
QString dst = tgt_path+"/translations.gen.h";
QFile g(dst);
if(!g.open(QFile::WriteOnly))
return false;
g.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n");
g.write("#ifndef _EDITOR_TRANSLATIONS_H\n");
g.write("#define _EDITOR_TRANSLATIONS_H\n");
QDirIterator translation_files_iter(translations_path,{"*.po"},QDir::Files);
QStringList all_translation_paths;
while(translation_files_iter.hasNext())
{
all_translation_paths.push_back(translation_files_iter.next());
}
std::sort(all_translation_paths.begin(),all_translation_paths.end());
// paths = [node.srcnode().abspath for node in source]
// sorted_paths = sorted(paths, key=lambda path: os.path.splitext(os.path.basename(path))[0])
struct TranslationEntry {
QString name;
int comp_len;
int decomp_len;
};
QVector<TranslationEntry> xl_names;
for(auto path : all_translation_paths)
{
QFile fl(path);
fl.open(QFile::ReadOnly);
QByteArray buf = fl.readAll();
auto decomp_size = buf.size();
buf = qCompress(buf);
buf.remove(0,4); // remove the decomp size that is added by qCompress
QString name = QFileInfo(path).baseName();
g.write(qUtf8Printable("static const unsigned char _translation_" + name + "_compressed[] = {\n"));
byteArrayToHexInFile(buf,g);
g.write("};\n");
xl_names.append({name, buf.size(), decomp_size});
}
g.write("struct EditorTranslationList {\n");
g.write("\tconst char* lang;\n");
g.write("\tint comp_size;\n");
g.write("\tint uncomp_size;\n");
g.write("\tconst unsigned char* data;\n");
g.write("};\n\n");
g.write("static EditorTranslationList _editor_translations[] = {\n");
for (TranslationEntry &x : xl_names)
{
g.write(qUtf8Printable(QString("\t{ \"%1\", %2, %3, _translation_%1_compressed},\n")
.arg(x.name).arg(x.comp_len).arg(x.decomp_len)));
}
g.write("\t{nullptr, 0, 0, nullptr}\n");
g.write("};\n");
g.write("#endif");
g.close();
return true;
}
bool make_default_controller_mappings(QStringList args)
{
QString dst = args.takeFirst();
QFile g(dst);
QDir d;
d.mkpath(QFileInfo(dst).path());
if(!g.open(QFile::WriteOnly))
return false;
g.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n");
g.write("#include \"core/input/default_controller_mappings.h\"\n");
// ensure mappings have a consistent order
QMap<QString,QMap<QString,QString>> platform_mappings;
for(const QString &src : args)
{
QString src_path = QFileInfo(src).absoluteFilePath();
QFile f(src_path);
QStringList mapping_file_lines;
if(f.open(QFile::ReadOnly))
{
QTextStream inp_text_stream(&f);
//# read mapping file and skip header
QString z;
while(inp_text_stream.readLineInto(&z))
mapping_file_lines.push_back(z);
mapping_file_lines = mapping_file_lines.mid(2);
}
QString current_platform;
for(QString line : mapping_file_lines)
{
if(line.isEmpty())
continue;
line = line.trimmed();
if(line.isEmpty())
continue;
if (line[0] == "#")
{
current_platform = line.mid(1).trimmed();
}
else if (!current_platform.isEmpty())
{
QStringList line_parts = line.split(',');
QString guid = line_parts[0];
if(platform_mappings[current_platform].contains(guid))
g.write(qPrintable(
QString("// WARNING - DATABASE %1 OVERWROTE PRIOR MAPPING: %2 %3\n").arg(src_path, current_platform, platform_mappings[current_platform][guid])));
bool valid_mapping = true;
for(const auto &input_map : line_parts.mid(2))
{
if(input_map.contains("+") or input_map.contains("-") or input_map.contains("~") )
{
g.write(qPrintable(
QString("// WARNING - DISCARDED UNSUPPORTED MAPPING TYPE FROM DATABASE %1: %2 %3\n").arg(src_path, current_platform, line)));
valid_mapping = false;
break;
}
}
if (valid_mapping)
platform_mappings[current_platform][guid] = line;
}
}
}
QMap<QString,QString> platform_variables = {
{"Linux", "#if X11_ENABLED"},
{"Windows", "#ifdef WINDOWS_ENABLED"},
{"Mac OS X", "#ifdef OSX_ENABLED"},
{"Android", "#if defined(__ANDROID__)"},
{"iOS", "#ifdef IPHONE_ENABLED"},
{"Javascript", "#ifdef JAVASCRIPT_ENABLED"},
{"UWP", "#ifdef UWP_ENABLED"},
};
g.write("const char* DefaultControllerMappings::mappings[] = {\n");
for(auto iter=platform_mappings.begin(),fin=platform_mappings.end(); iter!=fin; ++iter)
{
QString variable = platform_variables[iter.key()];
g.write(qPrintable(variable+"\n"));
for(auto plat_iter=iter.value().constKeyValueBegin(),plat_fin=iter.value().constKeyValueEnd(); plat_iter!=plat_fin; ++plat_iter)
{
g.write(qPrintable(QString("\t\"%1\",\n").arg((*plat_iter).second)));
}
g.write("#endif\n");
}
g.write("\tnullptr\n};\n");
g.close();
return true;
}
bool gen_script_encryption(QStringList args)
{
QString txt = "0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0";
QString e = qgetenv("SCRIPT_AES256_ENCRYPTION_KEY");
if (!e.isEmpty())
{
txt = "";
bool ec_valid = true;
if (e.size() != 64)
ec_valid = false;
else
{
for(int i=0; i<e.size()/2; ++i)
{
if (i > 0)
txt += ",";
bool parse_ok;
e.midRef(i*2,2).toInt(&parse_ok,16);
ec_valid &= parse_ok;
txt += QString("0x%1").arg(e.midRef(i*2,2));
}
}
if (not ec_valid)
{
txt = "0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0";
qCritical()<<"Invalid AES256 encryption key, not 64 bits hex:" << e;
return false;
}
}
QString target_path = args.takeFirst() + "/script_encryption_key.gen.cpp";
QFile fl(target_path);
if(fl.open(QFile::WriteOnly))
{
fl.write(qPrintable("#include \"core/project_settings.h\"\nuint8_t script_encryption_key[32]={" + txt + "};\n"));
return true;
}
return false;
}
QString _spaced(QString e)
{
if(e.endsWith('*'))
return e;
return e + " ";
}
QStringList generate_extension_struct(QString name,const QJsonObject &ext,bool include_version=true)
{
QStringList ret_val;
if(ext.contains("next") && ext["next"].isObject())
{
ret_val.append(generate_extension_struct(name, ext["next"].toObject()));
}
ret_val.append({
QString("typedef struct godot_gdnative_ext_") + name + (
(not include_version) ? "" :
QString("_%1_%2").arg(ext["version"]["major"].toInt()).arg(
ext["version"]["minor"].toInt())) + "_api_struct {",
"\tunsigned int type;",
"\tgodot_gdnative_api_version version;",
"\tconst godot_gdnative_api_struct *next;"
});
for(const QJsonValue &funcdef : ext["api"].toArray())
{
QStringList args;
for(const QJsonValue &arg_elem : funcdef["arguments"].toArray())
{
QJsonArray arg_elems = arg_elem.toArray();
args.append(QString("%1%2").arg(_spaced(arg_elems.at(0).toString()),arg_elems.at(1).toString()));
}
ret_val.append(QString("\t%1(*%2)(%3);").arg(_spaced(funcdef["return_type"].toString()),
funcdef["name"].toString(), args.join(",")));
}
ret_val += {
"} godot_gdnative_ext_" + name + ((not include_version) ? QString("") : QString("_%1_%2").arg(ext["version"]["major"].toInt()).arg(ext["version"]["minor"].toInt())) + "_api_struct;",
""
};
return ret_val;
}
QString _build_gdnative_api_struct_header(QJsonDocument &api)
{
QStringList gdnative_api_init_macro = {
"\textern const godot_gdnative_core_api_struct *_gdnative_wrapper_api_struct;"
};
QJsonValue extensions = api["extensions"];
assert(extensions.isArray());
if(extensions.isArray())
{
for(QJsonValue ext : extensions.toArray())
{
QString name = ext["name"].toString();
gdnative_api_init_macro.append(
QString("\textern const godot_gdnative_ext_%1_api_struct *_gdnative_wrapper_%1_api_struct;").arg(name));
}
}
gdnative_api_init_macro.append("\t_gdnative_wrapper_api_struct = options->api_struct;");
gdnative_api_init_macro.append("\tfor (unsigned int i = 0; i < _gdnative_wrapper_api_struct->num_extensions; i++) { ");
gdnative_api_init_macro.append("\t\tswitch (_gdnative_wrapper_api_struct->extensions[i]->type) {");
for(QJsonValue ext : extensions.toArray())
{
QString name = ext["name"].toString();
QString type = ext["type"].toString();
gdnative_api_init_macro.append(
QString("\t\t\tcase GDNATIVE_EXT_%1:").arg(type));
gdnative_api_init_macro.append(
QString("\t\t\t\t_gdnative_wrapper_%1_api_struct = (godot_gdnative_ext_%1_api_struct *)"
" _gdnative_wrapper_api_struct->extensions[i];").arg(name));
gdnative_api_init_macro.append("\t\t\t\tbreak;");
}
gdnative_api_init_macro.append("\t\t}");
gdnative_api_init_macro.append("\t}");
QStringList out = {
"/* THIS FILE IS GENERATED DO NOT EDIT */",
"#ifndef GODOT_GDNATIVE_API_STRUCT_H",
"#define GODOT_GDNATIVE_API_STRUCT_H",
"",
"#include <gdnative/gdnative.h>",
"#include <android/godot_android.h>",
"#include <arvr/godot_arvr.h>",
"#include <nativescript/godot_nativescript.h>",
"#include <net/godot_net.h>",
"#include <pluginscript/godot_pluginscript.h>",
"#include <videodecoder/godot_videodecoder.h>",
"",
"#define GDNATIVE_API_INIT(options) do { \\\n" + gdnative_api_init_macro.join(" \\\n") + " \\\n } while (0)",
"",
"#ifdef __cplusplus",
"extern \"C\" {",
"#endif",
"",
"enum GDNATIVE_API_TYPES {",
"\tGDNATIVE_" + api["core"]["type"].toString() + ','
};
for(QJsonValue ext : extensions.toArray())
out.push_back(QString("\tGDNATIVE_EXT_") + ext["type"].toString() + ',');
out.push_back("};");
out.push_back("");
for(QJsonValue ext : extensions.toArray())
{
QString name = ext["name"].toString();
out.append(generate_extension_struct(name, ext.toObject(), false));
}
out.append({
"typedef struct godot_gdnative_core_api_struct {",
"\tunsigned int type;",
"\tgodot_gdnative_api_version version;",
"\tconst godot_gdnative_api_struct *next;",
"\tunsigned int num_extensions;",
"\tconst godot_gdnative_api_struct **extensions;",
});
assert(api["core"]["api"].isArray());
for(const QJsonValue &funcdef : api["core"]["api"].toArray())
{
QStringList args;
for(const QJsonValue &arg_elem : funcdef["arguments"].toArray())
{
QJsonArray arg_elems = arg_elem.toArray();
args.append(QString("%1%2").arg(_spaced(arg_elems.at(0).toString()),arg_elems.at(1).toString()));
}
out.append(QString("\t%1(*%2)(%3);").arg(_spaced(funcdef["return_type"].toString()), funcdef["name"].toString(), args.join(',')));
}
out.append({
"} godot_gdnative_core_api_struct;",
"",
"#ifdef __cplusplus",
"}",
"#endif",
"",
"#endif // GODOT_GDNATIVE_API_STRUCT_H",
""
});
return out.join('\n');
}
static QString get_extension_struct_name(QString name,const QJsonObject &ext, bool include_version=true)
{
return "godot_gdnative_ext_" + name + ((not include_version)? QString("") :QString("_%1_%2").arg(ext["version"]["major"].toInt()).arg(ext["version"]["minor"].toInt())) + "_api_struct";
};
static QString get_extension_struct_instance_name(QString name,const QJsonObject &ext, bool include_version=true)
{
return "api_extension_" + name + ((not include_version)? QString("") :QString("_%1_%2").arg(ext["version"]["major"].toInt()).arg(ext["version"]["minor"].toInt())) + "_struct";
}
static QStringList get_extension_struct_definition(QString name,const QJsonObject &ext, bool include_version=true)
{
QStringList ret_val;
if(ext.contains("next") && ext["next"].isObject())
{
ret_val += get_extension_struct_definition(name, ext["next"].toObject());
}
ret_val.append({
QString("extern const ") + get_extension_struct_name(name, ext, include_version) + ' ' + get_extension_struct_instance_name(name, ext, include_version) + " = {",
QString("\tGDNATIVE_EXT_") + ext["type"].toString() + ',',
QString("\t{%1, %2},").arg(ext["version"]["major"].toInt()).arg(ext["version"]["minor"].toInt()),
QString("\t") + (not ext["next"].isObject() ? "nullptr" :("(const godot_gdnative_api_struct *)&" + get_extension_struct_instance_name(name, ext["next"].toObject()))) + ','
});
for(const QJsonValue &funcdef : ext["api"].toArray())
ret_val.append(QString("\t%1,").arg(funcdef["name"].toString()));
ret_val.append("};\n");
return ret_val;
}
QString _build_gdnative_api_struct_source(QJsonDocument &api)
{
QStringList out = {
"/* THIS FILE IS GENERATED DO NOT EDIT */",
"",
"#include <gdnative_api_struct.gen.h>",
""
};
for(QJsonValue ext : api["extensions"].toArray())
{
QString name = ext["name"].toString();
out.append(get_extension_struct_definition(name, ext.toObject(), false));
}
out.append({"", "const godot_gdnative_api_struct *gdnative_extensions_pointers[] = {"});
for(QJsonValue ext : api["extensions"].toArray())
{
QString name = ext["name"].toString();
out.append({QString("\t(godot_gdnative_api_struct *)&api_extension_") + name + "_struct,"});
}
out.append("};\n");
out.append({
QStringLiteral("extern const godot_gdnative_core_api_struct api_struct = {"),
QString("\tGDNATIVE_") + api["core"]["type"].toString() + ',',
QString("\t{%1, %2},").arg(api["core"]["version"]["major"].toInt()).arg(api["core"]["version"]["minor"].toInt()),
QStringLiteral("\tnullptr,"),
QString("\t%1,").arg(api["extensions"].toArray().size()),
"\tgdnative_extensions_pointers,",
});
for(const QJsonValue &funcdef : api["core"]["api"].toArray())
out.append(QString("\t%1,").arg(funcdef["name"].toString()));
out.append("};\n");
return out.join("\n");
}
bool build_gdnative_api_struct(QStringList args)
{
// gensource = gdn_env.Command(['include/gdnative_api_struct.gen.h', 'gdnative_api_struct.gen.cpp'],
// 'gdnative_api.json', build_gdnative_api_struct)
QString src_json = args.takeFirst();
QFile json_doc(src_json);
if(!json_doc.open(QFile::ReadOnly))
return false;
QJsonDocument api = QJsonDocument::fromJson(json_doc.readAll());
QString tgt_dir = args.takeFirst();
QString header = tgt_dir+"/gdnative_api_struct.gen.h";
QString source = tgt_dir+"/gdnative_api_struct.gen.cpp";
QFile header_file(header);
if(!header_file.open(QFile::WriteOnly))
return false;
header_file.write(_build_gdnative_api_struct_header(api).toUtf8());
QFile src_file(source);
if(!src_file.open(QFile::WriteOnly))
return false;
src_file.write(_build_gdnative_api_struct_source(api).toUtf8());
return true;
}
bool generate_mono_glue(QStringList args) {
QString src = args.takeFirst();
QString dst = args.takeFirst();
QString version_dst = args.takeFirst();
QFile header(dst);
QDir d(".");
qDebug()<<QFileInfo(dst).path();
d.mkpath(QFileInfo(dst).path());
if(!header.open(QFile::WriteOnly)) {
qCritical("Failed to open destination file");
return false;
}
QStringList lines = {
"/* THIS FILE IS GENERATED DO NOT EDIT */",
"#ifndef CS_COMPRESSED_H",
"#define CS_COMPRESSED_H\n",
"#ifdef TOOLS_ENABLED\n",
"#include \"core/map.h\"",
"#include \"core/string.h\"",
};
QStringList inserted_files;
int cs_file_count = 0;
QDirIterator visitor(src,QDirIterator::Subdirectories);
QCryptographicHash hash(QCryptographicHash::Sha256);
QStringList files;
while(visitor.hasNext()) {
QString fname = visitor.next();
if(fname.contains("Generated") || fname.contains("obj/"))
continue;
if(!fname.endsWith(".cs"))
continue;
files.push_back(fname);
}
files.sort();
for(const QString & fname : files) {
QFileInfo fi(fname);
QFile file(fname);
file.open(QFile::ReadOnly);
QCryptographicHash hash2(QCryptographicHash::Sha256);
QByteArray contents = file.readAll();
// remove end of line chars to normalize hash between windows/linux files.
contents.replace('\n',"");
contents.replace('\r',"");
hash.addData(contents);
hash2.addData(contents);
qDebug() << "Hashing"<<fname<<QString::number(qHash(hash.result()),16);
cs_file_count += 1;
}
auto hashed = hash.result();
auto glue_version = qHash(hashed); // simply hash the array containing sha256
d.mkpath(QFileInfo(version_dst).path());
QFile version_header(version_dst);
if(!version_header.open(QFile::WriteOnly)) {
qCritical("Failed to open destination file");
return false;
}
version_header.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n");
version_header.write("#pragma once\n");
version_header.write(("#define CS_GLUE_VERSION UINT32_C(" + QString::number(glue_version) + ")\n").toLatin1());
return true;
}
void report_arg_error(const char *mode,int required_args)
{
qWarning("Not enough arguments for editor_to_header %s mode",mode);
}
int main(int argc, char **argv)
{
QCoreApplication app(argc,argv);
if(argc<3)
{
qWarning("Not enough arguments for editor_to_header");
return -1;
}
QString mode = app.arguments()[1];
if(mode=="license")
{
if(argc<5)
{
report_arg_error("license",argc);
return -1;
}
return make_license_header(app.arguments().mid(2)) ? 0 : -1;
}
if(mode=="authors")
{
if(argc<4)
{
report_arg_error("authors",argc);
return -1;
}
return make_authors_header(app.arguments().mid(2)) ? 0 : -1;
}
else if(mode=="donors")
{
if(argc<4)
{
report_arg_error("donors",argc);
return -1;
}
return make_donors_header(app.arguments().mid(2)) ? 0 : -1;
}
else if(mode=="docs")
{
if(argc!=4)
{
report_arg_error("docs",argc);
return -1;
}
return collect_and_pack_docs(app.arguments().mid(2)) ? 0 : -1;
}
else if(mode=="translations")
{
if(argc!=4)
{
report_arg_error("translations",argc);
return -1;
}
return make_translations_header(app.arguments().mid(2)) ? 0 : -1;
}
else if(mode=="controllers")
{
if(argc<4)
{
report_arg_error("controllers",argc);
return -1;
}
return make_default_controller_mappings(app.arguments().mid(2)) ? 0 : -1;
}
else if(mode=="encryption")
{
if(argc<3)
{
report_arg_error("encryption",argc);
return -1;
}
return gen_script_encryption(app.arguments().mid(2)) ? 0 : -1;
}
else if(mode=="gdnative") // exe gdnative json_file target_path
{
if(argc!=4)
{
report_arg_error("gdnative",argc);
return -1;
}
return build_gdnative_api_struct(app.arguments().mid(2)) ? 0 : -1;
}
else if(mode=="mono") {
if(argc!=5)
{
report_arg_error("mono",argc);
return -1;
}
return generate_mono_glue(app.arguments().mid(2)) ? 0 : -1;
}
}
| 33.735596 | 194 | 0.564092 | ZopharShinta |
bfa608787d343981f7d6a12fc8df082967007d13 | 22,024 | cc | C++ | Algorithms/MatchedFilter/MatchedFilter2.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | Algorithms/MatchedFilter/MatchedFilter2.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | Algorithms/MatchedFilter/MatchedFilter2.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | #include "boost/bind.hpp"
#include <fftw3.h>
#include <algorithm> // for std::transform
#include <functional> // for std::bind* and std::mem_fun*
#include "Algorithms/Controller.h"
#include "Algorithms/Utils.h"
#include "Logger/Log.h"
#include "MatchedFilter2.h"
#include "MatchedFilter_defaults.h"
#include "WorkRequestQueue.h"
#include "WorkerThreads.h"
#include "QtCore/QString"
#include "QtCore/QVariant"
using namespace SideCar;
using namespace SideCar::Algorithms;
using namespace SideCar::Algorithms::MatchedFilterUtils;
static const char* kDomainNames[] = {"Frequency", "Time"};
const char* const*
MatchedFilter::DomainEnumTraits::GetEnumNames()
{
return kDomainNames;
}
// Constructor. Do minimal initialization here. Registration of processors and runtime parameters should occur
// in the startup() method. NOTE: it is WRONG to call any virtual functions here...
//
MatchedFilter::MatchedFilter(Controller& controller, Logger::Log& logger) :
Super(controller, logger, kDefaultEnabled, kDefaultMaxBufferSize),
numWorkers_(
Parameter::PositiveIntValue::Make("numWorkers", "Number of worker threads for processing", kDefaultNumWorkers)),
numFFTThreads_(Parameter::PositiveIntValue::Make("numFFTThreads", "Number of FFT threads for processing",
kDefaultNumFFTThreads)),
txPulseStartBin_(Parameter::IntValue::Make("txPulseStartBin",
"First complex bin of reference pulse in Tx<br>"
"(-1 for last, etc.)",
kDefaultTxPulseStartBin)),
txPulseSpan_(Parameter::IntValue::Make("txPulseSpan",
"Number of complex bins for reference pulse in Tx<br>"
"(< 1 = msgSize + value)",
kDefaultTxPulseSpan)),
rxFilterStartBin_(Parameter::IntValue::Make("rxFilterStartBin",
"First complex bin to filter in Rx<br>"
"(-1 for last, etc.)",
kDefaultRxFilterStartBin)),
rxFilterSpan_(Parameter::IntValue::Make("rxFilterSpan",
"Number of complex bins to filter in Rx<br>"
"(< 1 = msgSize + value)",
kDefaultRxFilterSpan)),
fftSize_(Parameter::PositiveIntValue::Make("fftSize",
"Size of FFT for filtering in frequency domain<br>"
"(best if power of 2)",
kDefaultFftSize)),
scaleWithSumMag_(Parameter::BoolValue::Make("scaleWithSumMag",
"Scale Tx pulse using sum of magnitudes instead of "
"just max value",
kDefaultScaleWithSumMag)),
domain_(DomainParameter::Make("domain_", "Domain", Domain(kDefaultDomain))),
txThreshold_(Parameter::IntValue::Make("txThreshold",
"If no Tx pulse values pass threshold,<br>"
"pass unfiltered Rx",
kDefaultTxThreshold)),
txThresholdStartBin_(Parameter::IntValue::Make("txThresholdStartBin", "First complex bin for Tx pulse search",
kDefaultTxThresholdStartBin)),
txThresholdSpan_(Parameter::IntValue::Make("txThresholdSpan", "Number of complex bins to search for Tx pulse",
kDefaultTxThresholdSpan)),
fwdFFT_(), txPulseVec_(), workerThreads_(0), idleWorkRequests_(new WorkRequestQueue("idle")),
pendingWorkRequests_(new WorkRequestQueue("pending")), finishedWorkRequests_(new WorkRequestQueue("finished")),
noPulseDetected_(false), restartWorkerThreads_(true)
{
Logger::ProcLog log("MatchedFilter", logger);
if (!fftw_init_threads()) LOGERROR << "failed fftw_init_threads" << std::endl;
numWorkers_->connectChangedSignalTo(boost::bind(&MatchedFilter::numWorkersChanged, this, _1));
fftSize_->connectChangedSignalTo(boost::bind(&MatchedFilter::fftSizeChanged, this, _1));
rxFilterSpan_->connectChangedSignalTo(boost::bind(&MatchedFilter::rxFilterSpanChanged, this, _1));
}
// Startup routine. This is called right after the Controller loads our DLL and creates an instance of the
// MatchedFilter class. Place registerProcessor and registerParameter calls here. Also, be sure to invoke
// Algorithm::startup() as shown below.
//
bool
MatchedFilter::startup()
{
return registerParameter(txPulseStartBin_) && registerParameter(txPulseSpan_) &&
registerParameter(rxFilterStartBin_) && registerParameter(rxFilterSpan_) && registerParameter(domain_) &&
registerParameter(fftSize_) && registerParameter(scaleWithSumMag_) && registerParameter(numWorkers_) &&
registerParameter(numFFTThreads_) && registerParameter(txThreshold_) &&
registerParameter(txThresholdStartBin_) && registerParameter(txThresholdSpan_) && Super::startup();
}
bool
MatchedFilter::shutdown()
{
// Note: at this point there is no algorithm thread running, so this is safe to do here.
//
stopThreads();
// When stopThreads() returns, no worker threads will be running so we can safely delete all WorkRequest
// objects.
//
while (!idleWorkRequests_->is_empty()) {
ACE_Message_Block* data;
idleWorkRequests_->dequeue_head(data);
WorkRequest::Destroy(data);
}
return Super::shutdown();
}
bool
MatchedFilter::reset()
{
Logger::ProcLog log("reset", getLog());
LOGINFO << std::endl;
// First, signal the process() method to restart our worker threads.
//
setRestartWorkerThreads();
return Super::reset();
}
ACE_Message_Block*
MatchedFilter::getWorkRequest()
{
// Fetch from the idleQueue_ if possible. Otherwise, create a new WorkRequest.
//
ACE_Message_Block* data = 0;
if (idleWorkRequests_->message_count() && idleWorkRequests_->dequeue_head(data) != -1) return data;
return WorkRequest::Make(txPulseVec_.get(), numFFTThreads_->getValue(), fftSize_->getValue());
}
bool
MatchedFilter::getRestartWorkerThreads()
{
// Safely acquire the restart signal, and reset it.
//
pendingWorkRequests_->lock().acquire();
bool value = restartWorkerThreads_;
restartWorkerThreads_ = false;
pendingWorkRequests_->lock().release();
return value;
}
void
MatchedFilter::setRestartWorkerThreads()
{
// Safely set the restart signal.
//
pendingWorkRequests_->lock().acquire();
restartWorkerThreads_ = true;
pendingWorkRequests_->lock().release();
}
void
MatchedFilter::startThreads()
{
Logger::ProcLog log("startThreads", getLog());
LOGINFO << std::endl;
size_t numWorkers = numWorkers_->getValue();
// Visit existing WorkRequest objects, updating them with new parameter values.
//
for (size_t index = 0; index < idleWorkRequests_->message_count(); ++index) {
// Remove top item from queue, update with new values, and push to back of queue. This should visit all
// of the item in the idle queue.
//
ACE_Message_Block* data;
idleWorkRequests_->dequeue_head(data);
WorkRequest::FromMessageBlock(data)->reconfigure(txPulseVec_.get(), numFFTThreads_->getValue(),
fftSize_->getValue());
idleWorkRequests_->enqueue_tail(data);
}
// Create new thread pool object.
//
workerThreads_.reset(new WorkerThreads(*this, *pendingWorkRequests_, *finishedWorkRequests_));
LOGDEBUG << "attempting to start " << numWorkers << " worker threads" << std::endl;
int rc = workerThreads_->activate(THR_NEW_LWP | THR_JOINABLE | THR_INHERIT_SCHED, numWorkers);
if (rc == -1) { LOGERROR << "failed to activate worker threads" << std::endl; }
}
void
MatchedFilter::stopThreads()
{
Logger::ProcLog log("stopThreads", getLog());
LOGINFO << std::endl;
// Signal all threads to stop. Processing threads will also stop once they become idle.
//
pendingWorkRequests_->deactivate();
if (workerThreads_) {
// Wait until all threads have stopped.
//
workerThreads_->wait();
LOGDEBUG << "threads stopped" << std::endl;
workerThreads_.reset();
}
// Now that there are no worker threads around, reactivate the queue and move any pending requests back onto
// the idle queue.
//
pendingWorkRequests_->activate();
while (!pendingWorkRequests_->is_empty()) {
ACE_Message_Block* data;
pendingWorkRequests_->dequeue_head(data);
idleWorkRequests_->enqueue_tail(data);
}
// Move any finished requests back onto the idle queue.
//
while (!finishedWorkRequests_->is_empty()) {
ACE_Message_Block* data;
finishedWorkRequests_->dequeue_head(data);
idleWorkRequests_->enqueue_tail(data);
}
}
void
MatchedFilter::numWorkersChanged(const Parameter::PositiveIntValue& parameter)
{
setRestartWorkerThreads();
}
void
MatchedFilter::fftSizeChanged(const Parameter::PositiveIntValue& parameter)
{
Logger::ProcLog log("fftSizeChanged", getLog());
LOGINFO << "fftSize: " << parameter.getValue() << std::endl;
setRestartWorkerThreads();
}
void
MatchedFilter::rxFilterSpanChanged(const Parameter::IntValue& parameter)
{
Logger::ProcLog log("rxFilterSpanChanged", getLog());
LOGINFO << "rxFilterSpan: " << parameter.getValue() << std::endl;
setRestartWorkerThreads();
}
void
MatchedFilter::buildFFTs()
{
Logger::ProcLog log("buildFFTs", getLog());
int fftSize = fftSize_->getValue();
LOGINFO << "rebuilding FFTW with size " << fftSize << std::endl;
fftw_plan_with_nthreads(numFFTThreads_->getValue());
fwdFFT_.reset(new FwdFFT(vsip::Domain<1>(fftSize), 1.0));
fftw_plan_with_nthreads(1);
txPulseVec_.reset(new VsipComplexVector(fftSize));
}
ChannelBuffer*
MatchedFilter::makeChannelBuffer(int index, const std::string& name, size_t maxBufferSize)
{
static Logger::ProcLog log("makeChannelBuffer", getLog());
LOGINFO << std::endl;
if (name == "transmit") {
tx_ = new TChannelBuffer<Messages::Video>(*this, index, maxBufferSize);
return tx_;
} else if (name == "receive") {
rx_ = new TChannelBuffer<Messages::Video>(*this, index, maxBufferSize);
return rx_;
} else {
LOGFATAL << "invalid channel name - " << name << std::endl;
}
return 0;
}
bool
MatchedFilter::processChannels()
{
static Logger::ProcLog log("processChannels", getLog());
LOGINFO << std::endl;
Messages::Video::Ref rxMsg(rx_->popFront());
Messages::Video::Ref txMsg(tx_->popFront());
if (!isEnabled()) {
LOGDEBUG << "not enabled" << std::endl;
return send(rxMsg);
}
// Since samples in the main and auxillary channels contain I,Q sample pairs, divide the message sizes by 2
// to get the number of complex samples.
//
int txSize = txMsg->size() / 2;
int rxSize = rxMsg->size() / 2;
// Check Tx for a pulse above a given threshold.
//
int txThreshold = txThreshold_->getValue();
int txThresholdStart = txThresholdStartBin_->getValue();
int txThresholdSpan = txThresholdSpan_->getValue();
LOGDEBUG << "txThreshold: " << txThreshold << " txThresholdStart: " << txThresholdStart
<< " txThresholdSpan: " << txThresholdSpan << " txSize: " << txSize << std::endl;
if (!Utils::normalizeSampleRanges(txThresholdStart, txThresholdSpan, txSize)) {
getController().setError("txThresholdStart is too large.");
return true;
}
bool txPulseDetected = false;
Messages::Video::const_iterator pos(txMsg->begin());
pos += txThresholdStartBin_->getValue() * 2;
for (int index = 0; index < txThresholdSpan_->getValue(); ++index) {
float i = *pos++;
float q = *pos++;
if (abs(i) > txThreshold || abs(q) > txThreshold) {
txPulseDetected = true;
break;
}
}
if (!txPulseDetected) {
LOGWARNING << "no pulse detected" << std::endl;
noPulseDetected_ = true;
return send(rxMsg);
}
noPulseDetected_ = false;
// Check if we need to (re)start our worker threads. Done here to remove any chance of a race condition with
// our message processing thread that runs this method.
//
if (getRestartWorkerThreads()) {
if (workerThreads_) stopThreads();
buildFFTs();
startThreads();
}
// Fetch the parameters that define the slice of the transmit message containing the transmit pulse.
//
int txPulseStart = txPulseStartBin_->getValue();
int txPulseSpan = txPulseSpan_->getValue();
LOGDEBUG << "txPulseStart : " << txPulseStart << " txPulseSpan : " << txPulseSpan << " txSize: " << txSize
<< std::endl;
// Make sure txPulseStart and txPulseSpan have reasonable values given the number of samples in the message.
// This will change txPulseStart and txPulseSpan if they are <= 0 so that they are valid sample indices and
// lengths.
//
if (!Utils::normalizeSampleRanges(txPulseStart, txPulseSpan, txSize)) {
getController().setError("txPulseStart is too large.");
return true;
}
LOGDEBUG << "txPulseStart : " << txPulseStart << " txPulseSpan : " << txPulseSpan << " txSize: " << txSize
<< std::endl;
int rxFilterStart = rxFilterStartBin_->getValue();
int rxFilterSpan = rxFilterSpan_->getValue();
LOGDEBUG << "rxFilterStart : " << rxFilterStart << " rxFilterSpan : " << rxFilterSpan << " rxSize: " << rxSize
<< std::endl;
// Make sure rxFilterStart and rxFilterSpan have reasonable values given the number of samples in the
// message.
//
if (!Utils::normalizeSampleRanges(rxFilterStart, rxFilterSpan, rxSize)) {
getController().setError("rxFilterStart is too large.");
return true;
}
LOGDEBUG << "rxFilterStart : " << rxFilterStart << " rxFilterSpan : " << rxFilterSpan << " rxSize: " << rxSize
<< std::endl;
// Create our output message now that we are done validating inputs.
//
Messages::Video::Ref out(Messages::Video::Make(getName(), rxMsg));
Messages::Video::Container& outputData(out->getData());
// Copy over samples before rxFilterStart.
//
std::copy(rxMsg->begin(), rxMsg->begin() + rxFilterStart * 2, std::back_inserter<>(outputData));
if (domain_->getValue() == kFrequencyDomain) {
LOGDEBUG << "processing in frequency domain" << std::endl;
// Since different threads will muck with their own part of the output buffer, we need it to be its full
// size.
//
outputData.resize(rxMsg->size());
// Copy over samples after rxFilterStart + rxFilterSpan
//
size_t offset = (rxFilterStart + rxFilterSpan) * 2;
std::copy(rxMsg->begin() + offset, rxMsg->end(), outputData.begin() + offset);
// Fetch the FFT parameters. The number of windows is the number of FFTs we must execute in order to
// process the filter span. Using ::ceil to sure that numWindows covers the entire message.
//
const int fftSize = fftSize_->getValue();
int numWindows = static_cast<int>(::ceil(static_cast<float>(rxFilterSpan) / fftSize));
const int totalFFTSize = fftSize * numWindows;
const int padding = totalFFTSize - rxFilterSpan;
// Get slice of the tx channel representing the transmit pulse.
//
Messages::Video::const_iterator pos(txMsg->begin());
pos += 2 * txPulseStart;
for (int index = 0; index < txPulseSpan; ++index) {
float i = *pos++;
float q = *pos++;
txPulseVec_->put(index, ComplexType(i, q));
}
// Pad the txPulseVec with zeroes so that it represents a length equal to fftSize
//
for (int index = txPulseSpan; index < fftSize; ++index) txPulseVec_->put(index, ComplexType(0.0, 0.0));
// Fetch the average magnitude found within the pulse. Since this value is always non-negative (sum of
// squares), we don't need to use a complex type to represent it.
//
float scale;
if (scaleWithSumMag_->getValue()) {
scale = vsip::sqrt(vsip::sumval(vsip::magsq(*txPulseVec_)));
} else {
vsip::Index<1> maxIndex;
scale = vsip::sqrt(vsip::maxmgsqval(*txPulseVec_, maxIndex));
}
// Convert xmit pulse into frequence domain.
//
*txPulseVec_ /= scale;
*txPulseVec_ = (*fwdFFT_)(*txPulseVec_);
*txPulseVec_ = vsip::conj(*txPulseVec_);
// Process the rx buffer as windows of fftSize, each window processed by a separate thread.
//
offset = 2 * rxFilterStart;
for (int windowIndex = 0; windowIndex < numWindows; ++windowIndex) {
// Fetch a new/existing WorkRequest object and fill it with the window values.
//
ACE_Message_Block* data = getWorkRequest();
WorkRequest* wr = WorkRequest::FromMessageBlock(data);
wr->beginRequest(rxMsg, out, offset);
offset += fftSize * 2;
// Add to the pending queue for the next available WorkerThread to process.
//
pendingWorkRequests_->enqueue_tail(data);
}
// Now that we've scheduled all of the work, we need to essentially perform a barrier wait until all of
// the threads have finished performing their calculations.
//
ACE_Message_Block* data = 0;
while (finishedWorkRequests_->dequeue_head(data) != -1) {
idleWorkRequests_->enqueue_tail(data);
--numWindows;
if (numWindows == 0) break;
}
} else {
LOGDEBUG << "processing in time domain" << std::endl;
// Get slice of the tx channel representing the transmit pulse
//
VsipComplexVector txPulseVec(txPulseSpan);
// Get slice of the tx channel representing the transmit pulse.
//
Messages::Video::const_iterator pos(txMsg->begin());
pos += 2 * txPulseStart;
for (int index = 0; index < txPulseSpan; ++index) {
float i = *pos++;
float q = *pos++;
txPulseVec.put(index, ComplexType(i, q));
}
// Get portion of receive channel to filter
//
VsipComplexVector rxVec(rxFilterSpan);
pos = rxMsg->begin() + 2 * rxFilterStart;
for (int index = 0; index < rxFilterSpan; ++index) {
float i = *pos++;
float q = *pos++;
rxVec.put(index, ComplexType(i, q));
}
txPulseVec = conj(txPulseVec);
float scale;
if (scaleWithSumMag_->getValue()) {
scale = vsip::sqrt(vsip::sumval(vsip::magsq(txPulseVec)));
} else {
vsip::Index<1> maxIndex;
scale = vsip::sqrt(vsip::maxmgsqval(txPulseVec, maxIndex));
}
// Normalize the values of the transmit pulse
//
txPulseVec /= scale;
int limit = rxFilterSpan - txPulseSpan;
for (int index = 0; index < limit; ++index) {
vsip::Domain<1> range(index, 1, txPulseSpan);
VsipComplexVector rxOp = rxVec.get(range);
rxVec(index) = vsip::sumval(txPulseVec * rxOp);
}
// Copy over the filtered data to output msg
//
for (int index = 0; index < rxFilterSpan - txPulseSpan; ++index) {
outputData.push_back(Messages::Video::DatumType(::rint(rxVec.get(index).real())));
outputData.push_back(Messages::Video::DatumType(::rint(rxVec.get(index).imag())));
}
// Copy any remaining unfiltered data to the output msg
//
for (size_t index = (rxFilterStart + rxFilterSpan - txPulseSpan) * 2; index < rxMsg->size(); ++index) {
outputData.push_back(rxMsg[index]);
}
} // end if processing in time domain
if (outputData.size() > 30 * 1024) LOGERROR << "abnormally large size: " << outputData.size() << std::endl;
bool rc = send(out);
LOGDEBUG << "rc: " << rc << std::endl;
return rc;
}
void
MatchedFilter::setInfoSlots(IO::StatusBase& status)
{
Super::setInfoSlots(status);
status.setSlot(kFFTSize, fftSize_->getValue());
status.setSlot(kWorkerCount, numWorkers_->getValue());
status.setSlot(kFFTThreadCount, numFFTThreads_->getValue());
status.setSlot(kDomain, domain_->getValue());
status.setSlot(kNoPulseDetected, noPulseDetected_);
}
extern "C" ACE_Svc_Export QVariant
FormatInfo(const IO::StatusBase& status, int role)
{
if (role != Qt::DisplayRole) return QVariant();
if (!status[ManyInAlgorithm::kEnabled] || status[MatchedFilter::kNoPulseDetected]) return "Rx Passthrough";
return QString("Threads: %1/%2 FFT: %3 Domain: %4 ")
.arg(int(status[MatchedFilter::kWorkerCount]))
.arg(int(status[MatchedFilter::kFFTThreadCount]))
.arg(int(status[MatchedFilter::kFFTSize]))
.arg(kDomainNames[int(status[MatchedFilter::kDomain])]) +
ManyInAlgorithm::GetFormattedStats(status);
}
// Factory function for the DLL that will create a new instance of the MatchedFilter class. DO NOT CHANGE!
//
extern "C" ACE_Svc_Export Algorithm*
MatchedFilterMake(Controller& controller, Logger::Log& log)
{
return new MatchedFilter(controller, log);
}
| 38.4363 | 120 | 0.624909 | jwillemsen |
bfa6e8d9093c3196f4da3168a70e6307077600ba | 7,226 | cpp | C++ | smart-ptrs/unique_advanced/test.cpp | DenisOstashov/cpp-advanced-hse | 6e4317763c0a9c510d639ae1e5793a8e9549d953 | [
"MIT"
] | null | null | null | smart-ptrs/unique_advanced/test.cpp | DenisOstashov/cpp-advanced-hse | 6e4317763c0a9c510d639ae1e5793a8e9549d953 | [
"MIT"
] | null | null | null | smart-ptrs/unique_advanced/test.cpp | DenisOstashov/cpp-advanced-hse | 6e4317763c0a9c510d639ae1e5793a8e9549d953 | [
"MIT"
] | null | null | null | #include "../unique.h"
#include "deleters.h"
#include "../my_int.h"
#include <catch.hpp>
#include <tuple>
TEST_CASE("Construction with deleters") {
SECTION("From copyable deleter") {
const CopyableDeleter<MyInt> cd;
UniquePtr<MyInt, CopyableDeleter<MyInt>> s(new MyInt, cd);
}
SECTION("From move-only deleter") {
Deleter<MyInt> d;
UniquePtr<MyInt, Deleter<MyInt>> s(new MyInt, std::move(d));
}
SECTION("From temporary") {
UniquePtr<MyInt, Deleter<MyInt>> s(new MyInt, Deleter<MyInt>{});
}
SECTION("Deleter type is non-const reference") {
Deleter<MyInt> d;
UniquePtr<MyInt, Deleter<MyInt>&> s(new MyInt, d);
}
SECTION("Deleter type is const reference") {
Deleter<MyInt> d;
UniquePtr<MyInt, const Deleter<MyInt>&> s1(new MyInt, d);
const Deleter<MyInt>& cr = d;
UniquePtr<MyInt, const Deleter<MyInt>&> s2(new MyInt, cr);
}
}
TEST_CASE("Swap with deleters") {
SECTION("If storing deleter by value") {
MyInt* p1 = new MyInt(1);
UniquePtr<MyInt, Deleter<MyInt>> s1(p1, Deleter<MyInt>(1));
MyInt* p2 = new MyInt(2);
UniquePtr<MyInt, Deleter<MyInt>> s2(p2, Deleter<MyInt>(2));
s1.Swap(s2);
REQUIRE(s1.Get() == p2);
REQUIRE(*s1 == 2);
REQUIRE(s2.Get() == p1);
REQUIRE(*s2 == 1);
REQUIRE(s1.GetDeleter().GetTag() == 2);
REQUIRE(s2.GetDeleter().GetTag() == 1);
REQUIRE(MyInt::AliveCount() == 2);
std::swap(s1, s2);
REQUIRE(s1.Get() == p1);
REQUIRE(*s1 == 1);
REQUIRE(s2.Get() == p2);
REQUIRE(*s2 == 2);
REQUIRE(s1.GetDeleter().GetTag() == 1);
REQUIRE(s2.GetDeleter().GetTag() == 2);
}
/*
* SECTION("If storing reference to deleter") {
*
* }
*
* well, me think it's enough for you this time...
*/
}
TEST_CASE("Moving deleters") {
SECTION("Move with custom deleter") {
UniquePtr<MyInt, Deleter<MyInt>> s1(new MyInt, Deleter<MyInt>(5));
MyInt* p = s1.Get();
UniquePtr<MyInt, Deleter<MyInt>> s2(new MyInt);
REQUIRE(MyInt::AliveCount() == 2);
REQUIRE(s1.GetDeleter().GetTag() == 5);
REQUIRE(s2.GetDeleter().GetTag() == 0);
s2 = std::move(s1);
REQUIRE(s2.Get() == p);
REQUIRE(s1.Get() == nullptr);
REQUIRE(MyInt::AliveCount() == 1);
REQUIRE(s2.GetDeleter().GetTag() == 5);
REQUIRE(s1.GetDeleter().GetTag() == 0);
}
SECTION("Move with reference deleter type") {
CopyableDeleter<MyInt> d1(5);
UniquePtr<MyInt, CopyableDeleter<MyInt>&> s1(new MyInt, d1);
MyInt* p1 = s1.Get();
CopyableDeleter<MyInt> d2(6);
UniquePtr<MyInt, CopyableDeleter<MyInt>&> s2(new MyInt, d2);
REQUIRE(MyInt::AliveCount() == 2);
s2 = std::move(s1);
REQUIRE(s2.Get() == p1);
REQUIRE(s1.Get() == nullptr);
REQUIRE(MyInt::AliveCount() == 1);
REQUIRE(d1.GetTag() == 5);
REQUIRE(d2.GetTag() == 5);
}
}
TEST_CASE("GetDeleter") {
SECTION("Get deleter") {
UniquePtr<MyInt, Deleter<MyInt>> p;
REQUIRE(!p.GetDeleter().IsConst());
}
SECTION("Get deleter const") {
const UniquePtr<MyInt, Deleter<MyInt>> p;
REQUIRE(p.GetDeleter().IsConst());
}
SECTION("Get deleter reference") {
using UDRef = UniquePtr<MyInt, Deleter<MyInt>&>;
Deleter<MyInt> d;
UDRef p(nullptr, d);
const UDRef& cp = p;
REQUIRE(!p.GetDeleter().IsConst());
REQUIRE(!cp.GetDeleter().IsConst());
}
SECTION("Get deleter const reference") {
using UDConstRef = UniquePtr<MyInt, const Deleter<MyInt>&>;
const Deleter<MyInt> d;
UDConstRef p(nullptr, d);
const UDConstRef& cp = p;
REQUIRE(p.GetDeleter().IsConst());
REQUIRE(cp.GetDeleter().IsConst());
}
}
struct VoidPtrDeleter {
void operator()(void* ptr) {
free(ptr);
}
};
TEST_CASE("UniquePtr<void, VoidPtrDeleter>") {
SECTION("It compiles!") {
UniquePtr<void, VoidPtrDeleter> p(malloc(100));
}
}
TEST_CASE("Array specialization") {
SECTION("delete[] is called") {
UniquePtr<MyInt[]> u(new MyInt[100]);
REQUIRE(MyInt::AliveCount() == 100);
u.Reset();
REQUIRE(MyInt::AliveCount() == 0);
}
SECTION("Able to use custom deleters") {
UniquePtr<MyInt[], Deleter<MyInt[]>> u(new MyInt[100]);
REQUIRE(MyInt::AliveCount() == 100);
u.Reset();
REQUIRE(MyInt::AliveCount() == 0);
}
SECTION("Operator []") {
int* arr = new int[5];
for (size_t i = 0; i < 5; ++i) {
arr[i] = i;
}
UniquePtr<int[]> u(arr);
for (int i = 0; i < 5; ++i) {
REQUIRE(u[i] == i);
u[i] = -i;
REQUIRE(u[i] == -i);
}
}
}
template <typename T>
void DeleteFunction(T* ptr) {
delete ptr;
}
template <typename T>
struct StatefulDeleter {
int some_useless_field = 0;
void operator()(T* ptr) {
delete ptr;
++some_useless_field;
}
};
TEST_CASE("Compressed pair usage") {
SECTION("Stateless struct deleter") {
static_assert(sizeof(UniquePtr<int>) == sizeof(void*));
static_assert(sizeof(UniquePtr<int, std::default_delete<int>>) == sizeof(int*));
}
SECTION("Stateful struct deleter") {
static_assert(sizeof(UniquePtr<int, StatefulDeleter<int>>) ==
sizeof(std::pair<int*, StatefulDeleter<int>>));
}
SECTION("Stateless lambda deleter") {
auto lambda_deleter = [](int* ptr) { delete ptr; };
static_assert(sizeof(UniquePtr<int, decltype(lambda_deleter)>) == sizeof(int*));
}
SECTION("Stateful lambda deleter") {
int some_useless_counter = 0;
auto lambda_deleter = [&some_useless_counter](int* ptr) {
delete ptr;
++some_useless_counter;
};
static_assert(sizeof(UniquePtr<int, decltype(lambda_deleter)>) ==
sizeof(std::pair<int*, decltype(lambda_deleter)>));
}
SECTION("Function pointer deleter") {
static_assert(sizeof(UniquePtr<int, decltype(&DeleteFunction<int>)>) ==
sizeof(std::pair<int*, decltype(&DeleteFunction<int>)>));
}
}
template <typename T>
class DerivedDeleter : public Deleter<T> {};
TEST_CASE("Upcasts") {
SECTION("Upcast in move constructor") {
UniquePtr<MyInt, DerivedDeleter<MyInt>> s(new MyInt);
UniquePtr<MyInt, Deleter<MyInt>> s2(std::move(s));
}
SECTION("Upcast in move assignment") {
UniquePtr<MyInt, DerivedDeleter<MyInt>> s(new MyInt);
UniquePtr<MyInt, Deleter<MyInt>> s2(new MyInt);
s2 = std::move(s);
}
}
TEST_CASE("Deleter call check") {
SECTION("Was called") {
Deleter<int> d;
{ UniquePtr<int, Deleter<int>&> up(new int, d); }
REQUIRE(d.WasCalled());
}
SECTION("Was not called") {
Deleter<int> d;
{ UniquePtr<int, Deleter<int>&> up(nullptr, d); }
REQUIRE(!d.WasCalled());
}
}
| 26.962687 | 88 | 0.562137 | DenisOstashov |
bfa7c88d6925c84e92512e3ec1d5a8b26219bd6c | 6,945 | cpp | C++ | src/microscopy/blocks/ai/CellDatabaseComparison.cpp | luminosuslight/pathology-ml-model-training | 00849ba00006c0e855d10a7a2a4e0d41fece1aab | [
"MIT"
] | null | null | null | src/microscopy/blocks/ai/CellDatabaseComparison.cpp | luminosuslight/pathology-ml-model-training | 00849ba00006c0e855d10a7a2a4e0d41fece1aab | [
"MIT"
] | null | null | null | src/microscopy/blocks/ai/CellDatabaseComparison.cpp | luminosuslight/pathology-ml-model-training | 00849ba00006c0e855d10a7a2a4e0d41fece1aab | [
"MIT"
] | 1 | 2020-05-20T08:17:33.000Z | 2020-05-20T08:17:33.000Z | #include "CellDatabaseComparison.h"
#include "core/CoreController.h"
#include "core/manager/BlockList.h"
#include "core/manager/StatusManager.h"
#include "core/connections/Nodes.h"
#include "microscopy/blocks/basic/CellDatabaseBlock.h"
#include <QtConcurrent>
bool CellDatabaseComparison::s_registered = BlockList::getInstance().addBlock(CellDatabaseComparison::info());
CellDatabaseComparison::CellDatabaseComparison(CoreController* controller, QString uid)
: OneInputBlock(controller, uid)
, m_instanceCountDifference(this, "instanceCountDifference", 0, std::numeric_limits<int>::min(), std::numeric_limits<int>::max())
, m_truePositives(this, "truePositives", 0, 0, std::numeric_limits<int>::max())
, m_falsePositives(this, "falsePositives", 0, 0, std::numeric_limits<int>::max())
, m_falseNegatives(this, "falseNegatives", 0, 0, std::numeric_limits<int>::max())
, m_accuracy(this, "accuracy", 0.0)
, m_precision(this, "precision", 0.0)
, m_recall(this, "recall", 0.0)
, m_f1(this, "f1", 0.0)
, m_meanSquarePositionError(this, "meanSquarePositionError", 0.0, 0.0, std::numeric_limits<double>::max())
, m_meanSquareRadiusError(this, "meanSquareRadiusError", 0.0, 0.0, std::numeric_limits<double>::max())
, m_meanSquareShapeError(this, "meanSquareShapeError", 0.0, 0.0, std::numeric_limits<double>::max())
{
m_groundTruthNode = createInputNode("groundTruth");
m_truePositivesNode = createOutputNode("truePositives");
m_falseNegativesNode = createOutputNode("falseNegatives");
m_falsePositivesNode = createOutputNode("falsePositives");
m_updateTimer.setSingleShot(true);
m_updateTimer.setInterval(200);
connect(&m_updateTimer, &QTimer::timeout, this, [this]() {
const bool locked = m_updateMutex.tryLock();
if (!locked) return;
QtConcurrent::run([this](){
update();
m_updateMutex.unlock();
});
});
connect(m_inputNode, &NodeBase::connectionChanged, this, [this]() { m_updateTimer.start(); });
connect(m_groundTruthNode, &NodeBase::connectionChanged, this, [this]() { m_updateTimer.start(); });
connect(m_inputNode, &NodeBase::dataChanged, this, [this]() { m_updateTimer.start(); });
connect(m_groundTruthNode, &NodeBase::dataChanged, this, [this]() { m_updateTimer.start(); });
}
void CellDatabaseComparison::update() {
if (!m_groundTruthNode->isConnected() || !m_inputNode->isConnected()) return;
const QVector<int> gtCells = m_groundTruthNode->constData().ids();
CellDatabaseBlock* gtDb = m_groundTruthNode->constData().referenceObject<CellDatabaseBlock>();
if (!gtDb) return;
const QVector<int> candidateCells = m_inputNode->constData().ids();
CellDatabaseBlock* candidateDb = m_inputNode->constData().referenceObject<CellDatabaseBlock>();
if (!candidateDb) return;
Status* status = m_controller->manager<StatusManager>("statusManager")->getStatus(getUid());
status->m_title = "Comparing Datasets...";
status->m_running = true;
m_instanceCountDifference = candidateCells.size() - gtCells.size();
QVector<int> truePositives;
QVector<int> falseNegatives;
QVector<bool> alreadyUsed(candidateCells.size());
double positionSquareErrorSum = 0.0;
double radiusSquareErrorSum = 0.0;
double shapeSquareErrorSum = 0.0;
for (int gtCellId: gtCells) {
const double gtX = gtDb->getFeature(CellDatabaseConstants::X_POS, gtCellId);
const double gtY = gtDb->getFeature(CellDatabaseConstants::Y_POS, gtCellId);
const double gtRadius = gtDb->getFeature(CellDatabaseConstants::RADIUS, gtCellId);
QVector<QPair<int, double>> similarNuclei;
for (int i = 0; i < candidateCells.size(); ++i) {
if (alreadyUsed.at(i)) continue;
const int cnCellId = candidateCells.at(i);
const double cnX = candidateDb->getFeature(CellDatabaseConstants::X_POS, cnCellId);
const double cnY = candidateDb->getFeature(CellDatabaseConstants::Y_POS, cnCellId);
const double distance = std::sqrt(std::pow(gtX - cnX, 2) + std::pow(gtY - cnY, 2));
if (distance <= gtRadius) {
similarNuclei.append({i, distance});
}
}
if (!similarNuclei.isEmpty()) {
const auto [i, distance] = *std::min_element(similarNuclei.begin(), similarNuclei.end(),
[](const auto& lhs, const auto& rhs) {
return lhs.second < rhs.second;
});
const int cnCellId = candidateCells.at(i);
const double cnRadius = candidateDb->getFeature(CellDatabaseConstants::RADIUS, cnCellId);
truePositives.append(cnCellId);
alreadyUsed[i] = true;
positionSquareErrorSum += std::pow(distance, 2);
radiusSquareErrorSum += std::pow(gtRadius - cnRadius, 2);
const CellShape& gtShape = gtDb->getShape(gtCellId);
const CellShape& cnShape = candidateDb->getShape(cnCellId);
double cellShapeSquareErrorSum = 0.0;
for (std::size_t j = 0; j < gtShape.size(); ++j) {
cellShapeSquareErrorSum += std::pow(gtShape.at(j) - cnShape.at(j), 2);
}
shapeSquareErrorSum += cellShapeSquareErrorSum / gtShape.size();
} else {
falseNegatives.append(gtCellId);
}
}
QVector<int> falsePositives;
for (int i = 0; i < candidateCells.size(); ++i) {
if (!alreadyUsed.at(i)) {
falsePositives.append(candidateCells.at(i));
}
}
m_truePositives = truePositives.size();
m_falseNegatives = falseNegatives.size();
m_falsePositives = falsePositives.size();
const int trueNegatives = 0;
m_accuracy = double(m_truePositives + trueNegatives) / (m_truePositives + trueNegatives + m_falsePositives + m_falseNegatives);
m_precision = double(m_truePositives) / (m_truePositives + m_falsePositives);
m_recall = double(m_truePositives) / (m_truePositives + m_falseNegatives);
m_f1 = 2.0 * ((m_precision * m_recall) / (m_precision + m_recall));
m_meanSquarePositionError = positionSquareErrorSum / m_truePositives;
m_meanSquareRadiusError = radiusSquareErrorSum / m_truePositives;
m_meanSquareShapeError = shapeSquareErrorSum / m_truePositives;
m_truePositivesNode->data().setReferenceObject(candidateDb);
m_truePositivesNode->data().setIds(truePositives);
m_truePositivesNode->dataWasModifiedByBlock();
m_falseNegativesNode->data().setReferenceObject(gtDb);
m_falseNegativesNode->data().setIds(falseNegatives);
m_falseNegativesNode->dataWasModifiedByBlock();
m_falsePositivesNode->data().setReferenceObject(candidateDb);
m_falsePositivesNode->data().setIds(falsePositives);
m_falsePositivesNode->dataWasModifiedByBlock();
m_controller->manager<StatusManager>("statusManager")->removeStatus(getUid());
}
| 45.392157 | 133 | 0.683225 | luminosuslight |
bfa92077cc14ec83225cb95b353196d81c49d6ad | 20,655 | cpp | C++ | source/GTest/FX/Fx.cpp | paradoxnj/Genesis3D | 272fc6aa2580de4ee223274ea04a101199c535a1 | [
"Condor-1.1",
"Unlicense"
] | 3 | 2020-04-29T03:17:50.000Z | 2021-05-26T19:53:46.000Z | source/GTest/FX/Fx.cpp | paradoxnj/Genesis3D | 272fc6aa2580de4ee223274ea04a101199c535a1 | [
"Condor-1.1",
"Unlicense"
] | 1 | 2020-04-29T03:12:47.000Z | 2020-04-29T03:12:47.000Z | source/GTest/FX/Fx.cpp | paradoxnj/Genesis3D | 272fc6aa2580de4ee223274ea04a101199c535a1 | [
"Condor-1.1",
"Unlicense"
] | null | null | null | /****************************************************************************************/
/* Fx.c */
/* */
/* Author: John Pollard */
/* Description: */
/* */
/* Copyright (c) 1999 WildTangent, Inc.; All rights reserved. */
/* */
/* See the accompanying file LICENSE.TXT for terms on the use of this library. */
/* This library is distributed in the hope that it will be useful but WITHOUT */
/* ANY WARRANTY OF ANY KIND and without any implied warranty of MERCHANTABILITY */
/* or FITNESS FOR ANY PURPOSE. Refer to LICENSE.TXT for more details. */
/* */
/****************************************************************************************/
#include <Windows.h>
#include <Assert.h>
#include "Genesis.h"
#include "Errorlog.h"
#include "Ram.h"
#include "Fx.h"
#include "..\\Procedurals\gebmutil.h"
static geBoolean ControlParticleAnim(Fx_System *Fx, Fx_TempPlayer *Player, float Time);
#define POLY_FLAGS (GE_RENDER_DEPTH_SORT_BF)
//#define POLY_FLAGS (GE_RENDER_DO_NOT_OCCLUDE_OTHERS)
extern geFloat EffectScale;
static char SmokeBitmapNames[NUM_SMOKE_TEXTURES][32] = {
"Bmp\\Fx\\Smoke_01.Bmp",
"Bmp\\Fx\\Smoke_02.Bmp",
"Bmp\\Fx\\Smoke_03.Bmp",
"Bmp\\Fx\\Smoke_04.Bmp",
"Bmp\\Fx\\Smoke_05.Bmp",
"Bmp\\Fx\\Smoke_06.Bmp",
"Bmp\\Fx\\Smoke_07.Bmp",
"Bmp\\Fx\\Smoke_08.Bmp",
"Bmp\\Fx\\Smoke_09.Bmp",
"Bmp\\Fx\\Smoke_10.Bmp"
};
static char SmokeBitmapANames[NUM_SMOKE_TEXTURES][32] = {
"Bmp\\Fx\\A_Smk01.Bmp",
"Bmp\\Fx\\A_Smk02.Bmp",
"Bmp\\Fx\\A_Smk03.Bmp",
"Bmp\\Fx\\A_Smk04.Bmp",
"Bmp\\Fx\\A_Smk05.Bmp",
"Bmp\\Fx\\A_Smk06.Bmp",
"Bmp\\Fx\\A_Smk07.Bmp",
"Bmp\\Fx\\A_Smk08.Bmp",
"Bmp\\Fx\\A_Smk09.Bmp",
"Bmp\\Fx\\A_Smk10.Bmp",
};
static char ExplodeBitmapNames[NUM_EXPLODE_TEXTURES][32] = {
"Bmp\\Explode\\1EXP01.Bmp",
"Bmp\\Explode\\1EXP02.Bmp",
"Bmp\\Explode\\1EXP03.Bmp",
"Bmp\\Explode\\1EXP04.Bmp",
"Bmp\\Explode\\1EXP05.Bmp",
"Bmp\\Explode\\1EXP06.Bmp"
};
static char ExplodeBitmapANames[NUM_EXPLODE_TEXTURES][32] = {
"Bmp\\Explode\\A_1EXP01.Bmp",
"Bmp\\Explode\\A_1EXP02.Bmp",
"Bmp\\Explode\\A_1EXP03.Bmp",
"Bmp\\Explode\\A_1EXP04.Bmp",
"Bmp\\Explode\\A_1EXP05.Bmp",
"Bmp\\Explode\\A_1EXP06.Bmp"
};
static char ParticleBitmapNames[NUM_PARTICLE_TEXTURES][32] = {
"Bmp\\Fx\\Parti1.Bmp",
"Bmp\\Fx\\Parti2.Bmp",
"Bmp\\Fx\\Parti3.Bmp",
"Bmp\\Fx\\Parti4.Bmp",
"Bmp\\Fx\\Parti5.Bmp",
"Bmp\\Fx\\Parti6.Bmp",
"Bmp\\Fx\\Parti7.Bmp",
"Bmp\\Fx\\Parti8.Bmp",
};
static char ParticleBitmapANames[NUM_PARTICLE_TEXTURES][32] = {
"Bmp\\Fx\\Parti1.Bmp",
"Bmp\\Fx\\Parti2.Bmp",
"Bmp\\Fx\\Parti3.Bmp",
"Bmp\\Fx\\Parti4.Bmp",
"Bmp\\Fx\\Parti5.Bmp",
"Bmp\\Fx\\Parti6.Bmp",
"Bmp\\Fx\\Parti7.Bmp",
"Bmp\\Fx\\Parti8.Bmp",
};
//=====================================================================================
// Private local static functions
//=====================================================================================
static geBoolean StartupSmokeTrail(Fx_System *Fx, Fx_Player *Player);
static geBoolean ShutdownSmokeTrail(Fx_System *Fx, Fx_Player *Player);
static geBoolean LoadFxTextures(Fx_System *Fx);
static geBoolean FreeFxTextures(Fx_System *Fx);
static geBoolean ControlExplode1Anim(Fx_System *Fx, Fx_TempPlayer *Player, float Time);
static geBoolean ControlExplode2Anim(Fx_System *Fx, Fx_TempPlayer *Player, float Time);
static geBoolean ControlParticleTrail(Fx_System *Fx, Fx_Player *Player, float Time);
static geBoolean ControlSmokeTrail(Fx_System *Fx, Fx_Player *Player, float Time);
static geBoolean ControlShredderFx(Fx_System *Fx, Fx_Player *Player, float Time);
//=====================================================================================
// Fx_SystemCreate
//=====================================================================================
Fx_System *Fx_SystemCreate(geWorld *World, Console_Console *Console)
{
Fx_System *Fx;
assert(World);
//assert(Console);
Fx = GE_RAM_ALLOCATE_STRUCT(Fx_System);
if (!Fx)
return NULL;
memset(Fx, 0, sizeof(Fx_System));
Fx->World = World;
Fx->Console = Console;
if (!LoadFxTextures(Fx))
{
Fx_SystemDestroy(Fx);
return NULL;
}
return Fx;
}
//=====================================================================================
// Fx_SystemDestroy
//=====================================================================================
void Fx_SystemDestroy(Fx_System *Fx)
{
geBoolean Ret;
assert(Fx);
Ret = FreeFxTextures(Fx);
assert(Ret == GE_TRUE);
geRam_Free(Fx);
}
//=====================================================================================
// Fx_SystemFrame
//=====================================================================================
geBoolean Fx_SystemFrame(Fx_System *Fx, float Time)
{
Fx_TempPlayer *Player;
int32 i;
// Control the temp players
Player = Fx->TempPlayers;
for (i=0; i< FX_MAX_TEMP_PLAYERS; i++, Player++)
{
if (!Player->Active)
continue;
if (!Player->Control)
continue;
// Call the players control routine...
if (!Player->Control(Fx, Player, Time))
return GE_FALSE;
}
return GE_TRUE;
}
//=====================================================================================
// Fx_SpawnFx
//=====================================================================================
geBoolean Fx_SpawnFx(Fx_System *Fx, geVec3d *Pos, uint8 Type)
{
Fx_TempPlayer *TempPlayer;
TempPlayer = Fx_SystemAddTempPlayer(Fx);
if (!TempPlayer)
return GE_TRUE; // Oh well, they just won't see any smoke...
TempPlayer->Pos = *Pos;
TempPlayer->Time = 0.0f;
switch(Type)
{
case FX_EXPLODE1:
TempPlayer->Control = ControlExplode1Anim;
break;
case FX_EXPLODE2:
TempPlayer->Control = ControlExplode2Anim;
break;
default:
return GE_FALSE;
}
return GE_TRUE;
}
//=====================================================================================
// Fx_SystemAddTempPlayer
//=====================================================================================
Fx_TempPlayer *Fx_SystemAddTempPlayer(Fx_System *Fx)
{
Fx_TempPlayer *Player, *End;
int32 i;
Player = Fx->CurrentTempPlayer;
if (!Player)
Player = Fx->TempPlayers;
End = &Fx->TempPlayers[FX_MAX_TEMP_PLAYERS-1];
for (i=0; i< FX_MAX_TEMP_PLAYERS; i++)
{
if (!Player->Active) // Look for a non active player
{
Fx->CurrentTempPlayer = Player;
memset(Player, 0, sizeof(Fx_TempPlayer));
Player->Active = GE_TRUE;
return Player;
}
Player++;
if (Player >= End) // Wrap player at end of structure to beginning
Player = Fx->TempPlayers;
}
return NULL;
}
//=====================================================================================
// Fx_SystemRemoveTempPlayer
//=====================================================================================
void Fx_SystemRemoveTempPlayer(Fx_System *Fx, Fx_TempPlayer *Player)
{
Player->Active = GE_FALSE;
Fx->CurrentTempPlayer = Player; // Easy steal for any one who wants to create a temp player
}
//=====================================================================================
// Fx_PlayerSetFxFlags
//=====================================================================================
geBoolean Fx_PlayerSetFxFlags(Fx_System *Fx, Fx_Player *Player, uint16 FxFlags)
{
if (FxFlags == Player->FxFlags)
return GE_TRUE; // Nothing to change...
//Console_Printf(Fx->Console, "Flags changed.\n");
if ((Player->FxFlags & FX_SMOKE_TRAIL) && !(FxFlags & FX_SMOKE_TRAIL))
ShutdownSmokeTrail(Fx, Player);
else if (!(Player->FxFlags & FX_SMOKE_TRAIL) && (FxFlags & FX_SMOKE_TRAIL))
StartupSmokeTrail(Fx, Player);
Player->FxFlags = FxFlags; // The flags are now current
return GE_TRUE;
}
//=====================================================================================
// Fx_PlayerFrame
//=====================================================================================
geBoolean Fx_PlayerFrame(Fx_System *Fx, Fx_Player *Player, const geXForm3d *XForm, float Time)
{
Player->XForm = *XForm;
if (Player->FxFlags & FX_SMOKE_TRAIL)
ControlSmokeTrail(Fx, Player, Time);
if (Player->FxFlags & FX_PARTICLE_TRAIL)
ControlParticleTrail(Fx, Player, Time);
if (Player->FxFlags & FX_SHREDDER)
ControlShredderFx(Fx, Player, Time);
return GE_TRUE;
}
//=====================================================================================
// StartupSmokeTrail
//=====================================================================================
static geBoolean StartupSmokeTrail(Fx_System *Fx, Fx_Player *Player)
{
//Console_Printf(Fx->Console, "Smoke trail started.\n");
return GE_TRUE;
}
//=====================================================================================
// ShutdownSmokeTrail
//=====================================================================================
static geBoolean ShutdownSmokeTrail(Fx_System *Fx, Fx_Player *Player)
{
//Console_Printf(Fx->Console, "Smoke trail stopped.\n");
return GE_TRUE;
}
//=====================================================================================
// ControlExplode1Anim
//=====================================================================================
static geBoolean ControlExplode1Anim(Fx_System *Fx, Fx_TempPlayer *Player, float Time)
{
GE_LVertex Vert;
int32 Frame;
Player->Time += Time;
Vert.X = Player->Pos.X;
Vert.Y = Player->Pos.Y;
Vert.Z = Player->Pos.Z;
Vert.r = Vert.g = Vert.b = Vert.a = 255.0f;
Vert.u = Vert.v = 0.0f;
Frame = (int32)(Player->Time*20.0f);
if (Frame >= NUM_EXPLODE_TEXTURES)
{
// Make sure we draw the last frame...
Frame = NUM_EXPLODE_TEXTURES-1;
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->ExplodeBitmaps[Frame], GE_TEXTURED_POINT, GE_RENDER_DEPTH_SORT_BF, 10.0f * EffectScale);
Fx_SystemRemoveTempPlayer(Fx, Player); // Smoke is done...
}
else
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->ExplodeBitmaps[Frame], GE_TEXTURED_POINT, POLY_FLAGS, 10.0f * EffectScale);
return GE_TRUE;
}
//=====================================================================================
// ControlExplode2Anim
//=====================================================================================
static geBoolean ControlExplode2Anim(Fx_System *Fx, Fx_TempPlayer *Player, float Time)
{
GE_LVertex Vert;
int32 Frame;
Player->Time += Time;
Vert.X = Player->Pos.X;
Vert.Y = Player->Pos.Y;
Vert.Z = Player->Pos.Z;
Vert.r = Vert.g = 255.0f;
Vert.b = 100.0f;
Vert.a = 255.0f;
Vert.u = Vert.v = 0.0f;
Frame = (int32)(Player->Time*20.0f);
if (Frame >= NUM_PARTICLE_TEXTURES)
{
// Make sure we draw the last frame...
Frame = NUM_PARTICLE_TEXTURES-1;
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->ParticleBitmaps[Frame], GE_TEXTURED_POINT, POLY_FLAGS, 8.0f * EffectScale);
Fx_SystemRemoveTempPlayer(Fx, Player); // Smoke is done...
}
else
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->ParticleBitmaps[Frame], GE_TEXTURED_POINT, POLY_FLAGS, 8.0f * EffectScale);
return GE_TRUE;
}
//=====================================================================================
// LoadFxTextures
//=====================================================================================
extern geVFile *MainFS;
static geBoolean LoadFxTextures(Fx_System *Fx)
{
int32 i;
assert(Fx);
assert(Fx->World);
for (i=0; i< NUM_SMOKE_TEXTURES; i++)
{
Fx->SmokeBitmaps[i] = geBitmapUtil_CreateFromFileAndAlphaNames(MainFS, SmokeBitmapNames[i], SmokeBitmapANames[i]);
if (!Fx->SmokeBitmaps[i])
{
char Str[1024];
sprintf(Str, "%s, %s", SmokeBitmapNames[i], SmokeBitmapANames[i]);
geErrorLog_AddString(-1, "Fx_LoadFxTextures: geBitmapUtil_CreateFromFileAndAlphaNames failed:", Str);
goto ExitWithError;
}
if (!geWorld_AddBitmap(Fx->World, Fx->SmokeBitmaps[i]))
{
geErrorLog_AddString(-1, "Fx_LoadFxTextures: geWorld_AddBItmap failed.", NULL);
goto ExitWithError;
}
}
for (i=0; i< NUM_PARTICLE_TEXTURES; i++)
{
Fx->ParticleBitmaps[i] = geBitmapUtil_CreateFromFileAndAlphaNames(MainFS, ParticleBitmapNames[i], ParticleBitmapANames[i]);
if (!Fx->ParticleBitmaps[i])
{
char Str[1024];
sprintf(Str, "%s, %s", ParticleBitmapNames[i], ParticleBitmapANames[i]);
geErrorLog_AddString(-1, "Fx_LoadFxTextures: geBitmapUtil_CreateFromFileAndAlphaNames failed:", Str);
goto ExitWithError;
}
if (!geWorld_AddBitmap(Fx->World, Fx->ParticleBitmaps[i]))
{
geErrorLog_AddString(-1, "Fx_LoadFxTextures: geWorld_AddBItmap failed.", NULL);
goto ExitWithError;
}
}
for (i=0; i< NUM_EXPLODE_TEXTURES; i++)
{
Fx->ExplodeBitmaps[i] = geBitmapUtil_CreateFromFileAndAlphaNames(MainFS, ExplodeBitmapNames[i], ExplodeBitmapANames[i]);
if (!Fx->ExplodeBitmaps[i])
{
char Str[1024];
sprintf(Str, "%s, %s", ExplodeBitmapNames[i], ExplodeBitmapANames[i]);
geErrorLog_AddString(-1, "Fx_LoadFxTextures: geBitmapUtil_CreateFromFileAndAlphaNames failed:", Str);
goto ExitWithError;
}
if (!geWorld_AddBitmap(Fx->World, Fx->ExplodeBitmaps[i]))
{
geErrorLog_AddString(-1, "Fx_LoadFxTextures: geWorld_AddBItmap failed.", NULL);
goto ExitWithError;
}
}
return GE_TRUE;
ExitWithError:
{
FreeFxTextures(Fx);
return GE_FALSE;
}
}
//=====================================================================================
// LoadFxTextures
//=====================================================================================
static geBoolean FreeFxTextures(Fx_System *Fx)
{
int32 i;
assert(Fx);
assert(Fx->World);
for (i=0; i< NUM_SMOKE_TEXTURES; i++)
{
if (Fx->SmokeBitmaps[i])
{
geWorld_RemoveBitmap(Fx->World, Fx->SmokeBitmaps[i]);
geBitmap_Destroy(&Fx->SmokeBitmaps[i]);
Fx->SmokeBitmaps[i] = NULL;
}
}
for (i=0; i< NUM_PARTICLE_TEXTURES; i++)
{
if (Fx->ParticleBitmaps[i])
{
geWorld_RemoveBitmap(Fx->World, Fx->ParticleBitmaps[i]);
geBitmap_Destroy(&Fx->ParticleBitmaps[i]);
Fx->ParticleBitmaps[i] = NULL;
}
}
for (i=0; i< NUM_EXPLODE_TEXTURES; i++)
{
if (Fx->ExplodeBitmaps[i])
{
geWorld_RemoveBitmap(Fx->World, Fx->ExplodeBitmaps[i]);
geBitmap_Destroy(&Fx->ExplodeBitmaps[i]);
Fx->ExplodeBitmaps[i] = NULL;
}
}
return GE_TRUE;
}
//=====================================================================================
// FxPlayer controls
//=====================================================================================
//=====================================================================================
// ControlParticleAnim
//=====================================================================================
static geBoolean ControlParticleAnim(Fx_System *Fx, Fx_TempPlayer *Player, float Time)
{
GE_LVertex Vert;
int32 Frame;
Player->Time += Time;
Vert.X = Player->Pos.X;
Vert.Y = Player->Pos.Y;
Vert.Z = Player->Pos.Z;
Vert.r = Vert.g = Vert.b = Vert.a = 255.0f;
Vert.u = Vert.v = 0.0f;
Frame = (int32)(Player->Time*20.0f);
if (Frame >= NUM_PARTICLE_TEXTURES)
{
// Make sure we draw the last frame...
Frame = NUM_PARTICLE_TEXTURES-1;
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->ParticleBitmaps[Frame], GE_TEXTURED_POINT, POLY_FLAGS, 2.3f * EffectScale);
Fx_SystemRemoveTempPlayer(Fx, Player); // Smoke is done...
}
else
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->ParticleBitmaps[Frame], GE_TEXTURED_POINT, POLY_FLAGS, 2.3f * EffectScale);
return GE_TRUE;
}
//=====================================================================================
// ControlParticleTrail
//=====================================================================================
static geBoolean ControlParticleTrail(Fx_System *Fx, Fx_Player *Player, float Time)
{
Fx_TempPlayer *TempPlayer;
Player->Time += Time;
if (Player->Time >= 0.04f)
{
TempPlayer = Fx_SystemAddTempPlayer(Fx);
if (!TempPlayer)
return GE_TRUE; // Oh well, they just won't see any smoke...
TempPlayer->Control = ControlParticleAnim;
TempPlayer->Pos = Player->XForm.Translation;
TempPlayer->Time = 0.0f;
Player->Time = 0.0f;
}
return GE_TRUE;
}
//=====================================================================================
// ControlSmokeAnim
//=====================================================================================
static geBoolean ControlSmokeAnim(Fx_System *Fx, Fx_TempPlayer *Player, float Time)
{
GE_LVertex Vert;
int32 Frame;
Player->Time += Time + ((float)(rand()%1000) * (1.0f/1000.0f)* 0.1f);
Vert.X = Player->Pos.X;
Vert.Y = Player->Pos.Y;
Vert.Z = Player->Pos.Z;
Vert.r = Vert.g = Vert.b = Vert.a = 255.0f;
Vert.u = Vert.v = 0.0f;
Frame = (int32)(Player->Time*15.0f);
if (Frame >= NUM_SMOKE_TEXTURES)
{
// Make sure we draw the last frame...
Frame = NUM_SMOKE_TEXTURES-1;
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->SmokeBitmaps[Frame], GE_TEXTURED_POINT, POLY_FLAGS, 2.6f * EffectScale); // 2,6
Fx_SystemRemoveTempPlayer(Fx, Player); // Smoke is done...
}
else
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->SmokeBitmaps[Frame], GE_TEXTURED_POINT, POLY_FLAGS, 2.6f * EffectScale);
return GE_TRUE;
}
//=====================================================================================
// ControlSmokeTrail
//=====================================================================================
static geBoolean ControlSmokeTrail(Fx_System *Fx, Fx_Player *Player, float Time)
{
Fx_TempPlayer *TempPlayer;
Player->Time += Time;
if (Player->Time >= 0.04f)
{
TempPlayer = Fx_SystemAddTempPlayer(Fx);
if (!TempPlayer)
return GE_TRUE; // Oh well, they just won't see any smoke...
TempPlayer->Control = ControlSmokeAnim;
TempPlayer->Pos = Player->XForm.Translation;
TempPlayer->Time = 0.0f;
Player->Time = 0.0f;
}
return GE_TRUE;
}
//=====================================================================================
// ControlSmokeAnim
//=====================================================================================
static geBoolean ControlShredderAnim(Fx_System *Fx, Fx_TempPlayer *Player, float Time)
{
GE_LVertex Vert;
int32 Frame;
Player->Time += Time;
Vert.X = Player->Pos.X;
Vert.Y = Player->Pos.Y;
Vert.Z = Player->Pos.Z;
Vert.r = Vert.g = Vert.b = Vert.a = 255.0f;
Vert.u = Vert.v = 0.0f;
Frame = (int32)(Player->Time*20.0f);
if (Frame >= NUM_SMOKE_TEXTURES)
{
// Make sure we draw the last frame...
Frame = NUM_SMOKE_TEXTURES-1;
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->SmokeBitmaps[Frame], GE_TEXTURED_POINT, POLY_FLAGS, 0.6f * EffectScale); // 2,6
Fx_SystemRemoveTempPlayer(Fx, Player); // Smoke is done...
}
else
geWorld_AddPolyOnce(Fx->World, &Vert, 1, Fx->SmokeBitmaps[Frame], GE_TEXTURED_POINT, POLY_FLAGS, 0.6f * EffectScale);
return GE_TRUE;
}
//=====================================================================================
// ControlShredderFx
//=====================================================================================
static geBoolean ControlShredderFx(Fx_System *Fx, Fx_Player *Player, float Time)
{
assert(Fx);
assert(Player);
Player->Time += Time;
if (Player->Time >= 0.03f)
{
Fx_TempPlayer *TempPlayer;
GE_Collision Collision;
geVec3d Front, Back, In;
geVec3d Mins = {-1.0f, -1.0f, -1.0f};
geVec3d Maxs = { 1.0f, 1.0f, 1.0f};
TempPlayer = Fx_SystemAddTempPlayer(Fx);
if (!TempPlayer)
return GE_TRUE; // Oh well...
TempPlayer->Control = ControlShredderAnim;
TempPlayer->Time = 0.0f;
Front = Player->XForm.Translation;
geXForm3d_GetIn(&Player->XForm, &In);
geVec3d_AddScaled(&Front, &In, 10000.0f, &Back);
if (geWorld_Collision(Fx->World, NULL, NULL, &Front, &Back, GE_CONTENTS_CANNOT_OCCUPY, GE_COLLIDE_ACTORS | GE_COLLIDE_MODELS, 0xffffffff, NULL, NULL, &Collision))
{
// Move it back a little from the wall
geVec3d_AddScaled(&Collision.Impact, &In, -50.0f, &Collision.Impact);
// Randomize the impact point
Collision.Impact.X += (float)(rand()%15);
Collision.Impact.Y += (float)(rand()%15);
Collision.Impact.Z += (float)(rand()%15);
TempPlayer->Pos = Collision.Impact;
}
else
TempPlayer->Pos = Player->XForm.Translation;
Player->Time = 0.0f;
}
return GE_TRUE;
}
| 29.173729 | 164 | 0.541515 | paradoxnj |
bfaa5f23f74561eb7de709daa7bf488c303f5e3b | 9,319 | cc | C++ | android_webview/browser/surfaces_instance.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | android_webview/browser/surfaces_instance.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | android_webview/browser/surfaces_instance.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2016 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 "android_webview/browser/surfaces_instance.h"
#include <algorithm>
#include <memory>
#include <utility>
#include "android_webview/browser/aw_gl_surface.h"
#include "android_webview/browser/aw_render_thread_context_provider.h"
#include "android_webview/browser/deferred_gpu_command_service.h"
#include "android_webview/browser/parent_output_surface.h"
#include "base/stl_util.h"
#include "components/viz/common/display/renderer_settings.h"
#include "components/viz/common/frame_sinks/begin_frame_source.h"
#include "components/viz/common/quads/solid_color_draw_quad.h"
#include "components/viz/common/quads/surface_draw_quad.h"
#include "components/viz/common/surfaces/parent_local_surface_id_allocator.h"
#include "components/viz/service/display/display.h"
#include "components/viz/service/display/display_scheduler.h"
#include "components/viz/service/frame_sinks/compositor_frame_sink_support.h"
#include "components/viz/service/frame_sinks/frame_sink_manager_impl.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/transform.h"
namespace android_webview {
namespace {
// The client_id used here should not conflict with the client_id generated
// from RenderWidgetHostImpl.
constexpr uint32_t kDefaultClientId = 0u;
SurfacesInstance* g_surfaces_instance = nullptr;
} // namespace
// static
scoped_refptr<SurfacesInstance> SurfacesInstance::GetOrCreateInstance() {
if (g_surfaces_instance)
return base::WrapRefCounted(g_surfaces_instance);
return base::WrapRefCounted(new SurfacesInstance);
}
SurfacesInstance::SurfacesInstance()
: frame_sink_id_allocator_(kDefaultClientId),
frame_sink_id_(AllocateFrameSinkId()) {
viz::RendererSettings settings;
// Should be kept in sync with compositor_impl_android.cc.
settings.allow_antialiasing = false;
settings.highp_threshold_min = 2048;
// Webview does not own the surface so should not clear it.
settings.should_clear_root_render_pass = false;
frame_sink_manager_ = std::make_unique<viz::FrameSinkManagerImpl>();
parent_local_surface_id_allocator_.reset(
new viz::ParentLocalSurfaceIdAllocator());
constexpr bool is_root = true;
constexpr bool needs_sync_points = true;
support_ = std::make_unique<viz::CompositorFrameSinkSupport>(
this, frame_sink_manager_.get(), frame_sink_id_, is_root,
needs_sync_points);
begin_frame_source_.reset(new viz::StubBeginFrameSource);
std::unique_ptr<ParentOutputSurface> output_surface_holder(
new ParentOutputSurface(AwRenderThreadContextProvider::Create(
base::WrapRefCounted(new AwGLSurface),
DeferredGpuCommandService::GetInstance())));
output_surface_ = output_surface_holder.get();
auto scheduler = std::make_unique<viz::DisplayScheduler>(
begin_frame_source_.get(), nullptr /* current_task_runner */,
output_surface_holder->capabilities().max_frames_pending);
display_ = std::make_unique<viz::Display>(
nullptr /* shared_bitmap_manager */, settings, frame_sink_id_,
std::move(output_surface_holder), std::move(scheduler),
nullptr /* current_task_runner */);
display_->Initialize(this, frame_sink_manager_->surface_manager());
// TODO(ccameron): WebViews that are embedded in WCG windows will want to
// specify gfx::ColorSpace::CreateExtendedSRGB(). This situation is not yet
// detected.
// https://crbug.com/735658
gfx::ColorSpace display_color_space = gfx::ColorSpace::CreateSRGB();
display_->SetColorSpace(display_color_space, display_color_space);
frame_sink_manager_->RegisterBeginFrameSource(begin_frame_source_.get(),
frame_sink_id_);
display_->SetVisible(true);
DCHECK(!g_surfaces_instance);
g_surfaces_instance = this;
}
SurfacesInstance::~SurfacesInstance() {
DCHECK_EQ(g_surfaces_instance, this);
frame_sink_manager_->UnregisterBeginFrameSource(begin_frame_source_.get());
g_surfaces_instance = nullptr;
DCHECK(child_ids_.empty());
}
void SurfacesInstance::DisplayOutputSurfaceLost() {
// Android WebView does not handle context loss.
LOG(FATAL) << "Render thread context loss";
}
viz::FrameSinkId SurfacesInstance::AllocateFrameSinkId() {
return frame_sink_id_allocator_.NextFrameSinkId();
}
viz::FrameSinkManagerImpl* SurfacesInstance::GetFrameSinkManager() {
return frame_sink_manager_.get();
}
void SurfacesInstance::DrawAndSwap(const gfx::Size& viewport,
const gfx::Rect& clip,
const gfx::Transform& transform,
const gfx::Size& frame_size,
const viz::SurfaceId& child_id,
float device_scale_factor) {
DCHECK(base::ContainsValue(child_ids_, child_id));
// Create a frame with a single SurfaceDrawQuad referencing the child
// Surface and transformed using the given transform.
std::unique_ptr<viz::RenderPass> render_pass = viz::RenderPass::Create();
render_pass->SetNew(1, gfx::Rect(viewport), clip, gfx::Transform());
render_pass->has_transparent_background = false;
viz::SharedQuadState* quad_state =
render_pass->CreateAndAppendSharedQuadState();
quad_state->quad_to_target_transform = transform;
quad_state->quad_layer_rect = gfx::Rect(frame_size);
quad_state->visible_quad_layer_rect = gfx::Rect(frame_size);
quad_state->clip_rect = clip;
quad_state->is_clipped = true;
quad_state->opacity = 1.f;
viz::SurfaceDrawQuad* surface_quad =
render_pass->CreateAndAppendDrawQuad<viz::SurfaceDrawQuad>();
surface_quad->SetNew(quad_state, gfx::Rect(quad_state->quad_layer_rect),
gfx::Rect(quad_state->quad_layer_rect), child_id,
base::nullopt, SK_ColorWHITE, false);
viz::CompositorFrame frame;
// We draw synchronously, so acknowledge a manual BeginFrame.
frame.metadata.begin_frame_ack =
viz::BeginFrameAck::CreateManualAckWithDamage();
frame.render_pass_list.push_back(std::move(render_pass));
frame.metadata.device_scale_factor = device_scale_factor;
frame.metadata.referenced_surfaces = child_ids_;
if (!root_id_.is_valid() || viewport != surface_size_ ||
device_scale_factor != device_scale_factor_) {
root_id_ = parent_local_surface_id_allocator_->GenerateId();
surface_size_ = viewport;
device_scale_factor_ = device_scale_factor;
display_->SetLocalSurfaceId(root_id_, device_scale_factor);
}
support_->SubmitCompositorFrame(root_id_, std::move(frame));
display_->Resize(viewport);
display_->DrawAndSwap();
display_->DidReceiveSwapBuffersAck();
}
void SurfacesInstance::AddChildId(const viz::SurfaceId& child_id) {
DCHECK(!base::ContainsValue(child_ids_, child_id));
child_ids_.push_back(child_id);
if (root_id_.is_valid())
SetSolidColorRootFrame();
}
void SurfacesInstance::RemoveChildId(const viz::SurfaceId& child_id) {
auto itr = std::find(child_ids_.begin(), child_ids_.end(), child_id);
DCHECK(itr != child_ids_.end());
child_ids_.erase(itr);
if (root_id_.is_valid())
SetSolidColorRootFrame();
}
void SurfacesInstance::SetSolidColorRootFrame() {
DCHECK(!surface_size_.IsEmpty());
gfx::Rect rect(surface_size_);
bool is_clipped = false;
bool are_contents_opaque = true;
std::unique_ptr<viz::RenderPass> render_pass = viz::RenderPass::Create();
render_pass->SetNew(1, rect, rect, gfx::Transform());
viz::SharedQuadState* quad_state =
render_pass->CreateAndAppendSharedQuadState();
quad_state->SetAll(gfx::Transform(), rect, rect, rect, is_clipped,
are_contents_opaque, 1.f, SkBlendMode::kSrcOver, 0);
viz::SolidColorDrawQuad* solid_quad =
render_pass->CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>();
solid_quad->SetNew(quad_state, rect, rect, SK_ColorBLACK, false);
viz::CompositorFrame frame;
frame.render_pass_list.push_back(std::move(render_pass));
// We draw synchronously, so acknowledge a manual BeginFrame.
frame.metadata.begin_frame_ack =
viz::BeginFrameAck::CreateManualAckWithDamage();
frame.metadata.referenced_surfaces = child_ids_;
frame.metadata.device_scale_factor = device_scale_factor_;
support_->SubmitCompositorFrame(root_id_, std::move(frame));
}
void SurfacesInstance::DidReceiveCompositorFrameAck(
const std::vector<viz::ReturnedResource>& resources) {
ReclaimResources(resources);
}
void SurfacesInstance::DidPresentCompositorFrame(uint32_t presentation_token,
base::TimeTicks time,
base::TimeDelta refresh,
uint32_t flags) {}
void SurfacesInstance::DidDiscardCompositorFrame(uint32_t presentation_token) {}
void SurfacesInstance::OnBeginFrame(const viz::BeginFrameArgs& args) {}
void SurfacesInstance::ReclaimResources(
const std::vector<viz::ReturnedResource>& resources) {
// Root surface should have no resources to return.
CHECK(resources.empty());
}
void SurfacesInstance::OnBeginFramePausedChanged(bool paused) {}
} // namespace android_webview
| 40.694323 | 80 | 0.741067 | zipated |
bfaae1bbde6de98b6131ebed61b9324dc20b3d91 | 52 | cpp | C++ | Graph/Common Graph Templates/cycleDetect.cpp | aminPial/Competitive-Programming-Library | c77373bf9f0dd212369a383ec3165d345f2a0cc7 | [
"MIT"
] | 4 | 2020-03-21T04:32:09.000Z | 2021-07-14T13:49:00.000Z | Graph/Common Graph Templates/cycleDetect.cpp | aminPial/Competitive-Programming-Library | c77373bf9f0dd212369a383ec3165d345f2a0cc7 | [
"MIT"
] | null | null | null | Graph/Common Graph Templates/cycleDetect.cpp | aminPial/Competitive-Programming-Library | c77373bf9f0dd212369a383ec3165d345f2a0cc7 | [
"MIT"
] | 1 | 2020-12-11T06:06:06.000Z | 2020-12-11T06:06:06.000Z | // cycle detection for directed and undirected graph | 52 | 52 | 0.826923 | aminPial |
bfac1857cac402b861fa6a09633de259ddfc12f2 | 13,324 | inl | C++ | Engine/Include/Sapphire/Maths/Space/Quaternion.inl | SapphireSuite/Sapphire | f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47 | [
"MIT"
] | 2 | 2020-03-18T09:06:21.000Z | 2020-04-09T00:07:56.000Z | Engine/Include/Sapphire/Maths/Space/Quaternion.inl | SapphireSuite/Sapphire | f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47 | [
"MIT"
] | null | null | null | Engine/Include/Sapphire/Maths/Space/Quaternion.inl | SapphireSuite/Sapphire | f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47 | [
"MIT"
] | null | null | null | // Copyright 2020 Sapphire development team. All Rights Reserved.
namespace Sa
{
template <typename T>
const Quat<T> Quat<T>::Zero{ T(0), T(0), T(0), T(0) };
template <typename T>
const Quat<T> Quat<T>::Identity{ T(1), T(0), T(0), T(0) };
template <typename T>
constexpr Quat<T>::Quat(T _w, T _x, T _y, T _z) noexcept :
w{ _w },
x{ _x },
y{ _y },
z{ _z }
{
}
template <typename T>
Quat<T>::Quat(Deg<T> _angle, const Vec3<T>& _axis) noexcept
{
const Rad<T> halfAngle = _angle / 2.0f;
w = Maths::Cos(halfAngle);
Vec3<T>& inAxis = reinterpret_cast<Vec3<T>&>(x);
#if SA_DEBUG
if (!_axis.IsNormalized())
{
SA_LOG("Axis should be normalized!", Warning, Maths);
inAxis = _axis.GetNormalized() * Maths::Sin(halfAngle);
return;
}
#endif
inAxis = _axis * Maths::Sin(halfAngle);
}
template <typename T>
template <typename TIn>
constexpr Quat<T>::Quat(const Quat<TIn>& _other) noexcept :
w{ static_cast<T>(_other.w) },
x{ static_cast<T>(_other.x) },
y{ static_cast<T>(_other.y) },
z{ static_cast<T>(_other.z) }
{
}
template <typename T>
constexpr bool Quat<T>::IsZero() const noexcept
{
return Maths::Equals0(w) && Maths::Equals0(x) && Maths::Equals0(y) && Maths::Equals0(z);
}
template <typename T>
constexpr bool Quat<T>::IsIdentity() const noexcept
{
return Maths::Equals1(w) && Maths::Equals0(x) && Maths::Equals0(y) && Maths::Equals0(z);
}
template <typename T>
constexpr bool Quat<T>::Equals(const Quat& _other, T _threshold) const noexcept
{
return Maths::Equals(w, _other.w, _threshold) &&
Maths::Equals(x, _other.x, _threshold) &&
Maths::Equals(y, _other.y, _threshold) &&
Maths::Equals(z, _other.z, _threshold);
}
template <typename T>
constexpr T Quat<T>::Length() const noexcept
{
return Maths::Sqrt(SqrLength());
}
template <typename T>
constexpr T Quat<T>::SqrLength() const noexcept
{
return w * w + x * x + y * y + z * z;
}
template <typename T>
T* Quat<T>::Data() noexcept
{
return &w;
}
template <typename T>
const T* Quat<T>::Data() const noexcept
{
return &w;
}
template <typename T>
Quat<T>& Quat<T>::Normalize()
{
SA_ASSERT(!IsZero(), DivisionBy0, Maths, L"Normalize null quaternion!");
const T norm = Length();
w /= norm;
x /= norm;
y /= norm;
z /= norm;
return *this;
}
template <typename T>
constexpr Quat<T> Quat<T>::GetNormalized() const
{
SA_ASSERT(!IsZero(), DivisionBy0, Maths, L"Normalize null quaternion!");
const T norm = Length();
return Quat(w / norm, x / norm, y / norm, z / norm);
}
template <typename T>
constexpr bool Quat<T>::IsNormalized() const noexcept
{
/// Handle Maths::Sqrt() miss precision.
return Maths::Equals1(SqrLength(), 3.0f * Limits<T>::epsilon);
}
template <typename T>
constexpr Quat<T>& Quat<T>::Inverse()
{
SA_ASSERT(IsNormalized(), NonNormalized, Maths, L"Quaternion must be normalized!");
// Inverse of normalized quaternion is conjugate.
x = -x;
y = -y;
z = -z;
return *this;
}
template <typename T>
constexpr Quat<T> Quat<T>::GetInversed() const
{
SA_ASSERT(IsNormalized(), NonNormalized, Maths, L"Quaternion must be normalized!");
// Inverse of normalized quaternion is conjugate.
return Quat(w, -x, -y, -z);
}
template <typename T>
constexpr Deg<T> Quat<T>::GetAngle() const noexcept
{
return Maths::ACos(w) * 2.0f;
}
template <typename T>
constexpr Vec3<T> Quat<T>::GetAxis() const noexcept
{
#if SA_DEBUG
if (Maths::Equals1(w))
{
SA_LOG("Get axis of an idendity quaternion.", Warning, Maths);
return Vec3<T>::Zero;
}
#endif
const Vec3<T>& axis = reinterpret_cast<const Vec3<T>&>(x);
const Rad<T> halfAngle = Maths::ACos(w);
return (axis / Maths::Sin(halfAngle)).GetNormalized();
}
template <typename T>
Quat<T>& Quat<T>::Scale(T _scale) noexcept
{
w *= _scale;
x *= _scale;
y *= _scale;
z *= _scale;
return *this;
}
template <typename T>
constexpr Quat<T> Quat<T>::GetScaled(T _scale) const noexcept
{
return Quat(w - _scale, x * _scale, y * _scale, z * _scale);
}
template <typename T>
Quat<T>& Quat<T>::UnScale(T _scale)
{
SA_ASSERT(!Maths::Equals0(_scale), DivisionBy0, Maths, L"Inverse scale quaternion by 0!");
w /= _scale;
x /= _scale;
y /= _scale;
z /= _scale;
return *this;
}
template <typename T>
constexpr Quat<T> Quat<T>::GetUnScaled(T _scale) const
{
SA_ASSERT(!Maths::Equals0(_scale), DivisionBy0, Maths, L"Inverse scale quaternion by 0!");
return Quat(w / _scale, x / _scale, y / _scale, z / _scale);
}
template <typename T>
constexpr Quat<T> Quat<T>::Rotate(const Quat<T>& _other) const
{
SA_ASSERT(IsNormalized(), NonNormalized, Maths, L"Quaternion multiplication must be normalized. This quaternion is not normalized!");
SA_ASSERT(_other.IsNormalized(), NonNormalized, Maths, L"Quaternion multiplication must be normalized. Other quaternion is not normalized!");
T resW = w * _other.w - x * _other.x - y * _other.y - z * _other.z;
T resX = w * _other.x + x * _other.w + y * _other.z - z * _other.y;
T resY = w * _other.y - x * _other.z + y * _other.w + z * _other.x;
T resZ = w * _other.z + x * _other.y - y * _other.x + z * _other.w;
return Quat(resW, resX, resY, resZ);
}
template <typename T>
constexpr Vec3<T> Quat<T>::Rotate(const Vec3<T>& _vec) const
{
SA_ASSERT(IsNormalized(), NonNormalized, Maths, L"Quaternion multiplication must be normalized. This quaternion is not normalized!");
// Quaternion-vector multiplication optimization:
// http://people.csail.mit.edu/bkph/articles/Quaternions.pdf
// v' = q * p * q-1
// Pure imaginary optimization:
// v' = v + q * 2.0f * (q X v) + q * 2.0f * (q X v).
// v' = v + q * ( A ) + q * ( A ).
// Vector component from quaternion.
const Vec3<T> qVec(x, y, z);
// Compute A = 2.0f * (q X v).
const Vec3<T> A = 2.0f * Vec3<T>::Cross(qVec, _vec);
return _vec + (w * A) + Vec3<T>::Cross(qVec, A);
}
template <typename T>
constexpr Quat<T> Quat<T>::UnRotate(const Quat<T>& _other) const
{
return GetInversed().Rotate(_other);
}
template <typename T>
constexpr Vec3<T> Quat<T>::UnRotate(const Vec3<T>& _vec) const
{
return GetInversed().Rotate(_vec);
}
template <typename T>
constexpr Vec3<T> Quat<T>::RightVector() const
{
return Rotate(Vec3<T>::Right);
}
template <typename T>
constexpr Vec3<T> Quat<T>::UpVector() const
{
return Rotate(Vec3<T>::Up);
}
template <typename T>
constexpr Vec3<T> Quat<T>::ForwardVector() const
{
return Rotate(Vec3<T>::Forward);
}
template <typename T>
constexpr Vec3<Deg<T>> Quat<T>::ToEuler() const noexcept
{
// Source: https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
Vec3<Deg<T>> result;
// Pitch - X axis
{
const T cosPitch = 1.0f - 2.0f * (x * x + y * y);
const T sinPitch = 2.0f * (w * x + y * z);
result.x = Maths::ATan2(sinPitch, cosPitch);
}
// Yaw - Y axis
{
const T sinYaw = 2.0f * (w * y - z * x);
result.y = Maths::Abs(sinYaw) < 1.0f ? Maths::ASin(sinYaw) : Rad<T>(Maths::PiOv4 * Maths::Sign(sinYaw)); // 90 degrees if out of range.
}
// Roll - Z axis
{
const T cosRoll = 1.0f - 2.0f * (y * y + z * z);
const T sinRoll = 2.0f * (w * z + x * y);
result.z = Maths::ATan2(sinRoll, cosRoll);
}
return result;
}
template <typename T>
constexpr Quat<T> Quat<T>::FromEuler(const Vec3<Deg<T>>& _angles) noexcept
{
// Source: https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
Vec3<Rad<T>> halfRadAngles = _angles * 0.5f;
const T cosPitch = Maths::Cos(halfRadAngles.x);
const T sinPitch = Maths::Sin(halfRadAngles.x);
const T cosYaw = Maths::Cos(halfRadAngles.y);
const T sinYaw = Maths::Sin(halfRadAngles.y);
const T cosRoll = Maths::Cos(halfRadAngles.z);
const T sinRoll = Maths::Sin(halfRadAngles.z);
Quat result;
result.w = cosPitch * cosYaw * cosRoll + sinPitch * sinYaw * sinRoll;
result.x = sinPitch * cosYaw * cosRoll - cosPitch * sinYaw * sinRoll;
result.y = cosPitch * sinYaw * cosRoll + sinPitch * cosYaw * sinRoll;
result.z = cosPitch * cosYaw * sinRoll - sinPitch * sinYaw * cosRoll;
return result;
}
template <typename T>
constexpr T Quat<T>::Dot(const Quat<T>& _lhs, const Quat& _rhs) noexcept
{
return _lhs.w * _rhs.w +
_lhs.x * _rhs.x +
_lhs.y * _rhs.y +
_lhs.z * _rhs.z;
}
template <typename T>
Quat<T> Quat<T>::Lerp(const Quat& _start, const Quat& _end, float _alpha) noexcept
{
#if SA_DEBUG
if (!_start.IsNormalized())
SA_LOG("_start should be normalized!", Warning, Maths);
if (!_end.IsNormalized())
SA_LOG("_end should be normalized!", Warning, Maths);
#endif
return Maths::Lerp(_start, _end, _alpha).GetNormalized();
}
template <typename T>
Quat<T> Quat<T>::LerpUnclamped(const Quat& _start, const Quat& _end, float _alpha) noexcept
{
#if SA_DEBUG
if (!_start.IsNormalized())
SA_LOG("_start should be normalized!", Warning, Maths);
if (!_end.IsNormalized())
SA_LOG("_end should be normalized!", Warning, Maths);
#endif
return Maths::LerpUnclamped(_start, _end, _alpha).GetNormalized();
}
template <typename T>
Quat<T> Quat<T>::SLerp(const Quat& _start, const Quat& _end, float _alpha) noexcept
{
#if SA_DEBUG
if (!_start.IsNormalized())
SA_LOG("_start should be normalized!", Warning, Maths);
if (!_end.IsNormalized())
SA_LOG("_end should be normalized!", Warning, Maths);
#endif
return Maths::SLerp(_start, _end, _alpha).GetNormalized();
}
template <typename T>
Quat<T> Quat<T>::SLerpUnclamped(const Quat& _start, const Quat& _end, float _alpha) noexcept
{
#if SA_DEBUG
if (!_start.IsNormalized())
SA_LOG("_start should be normalized!", Warning, Maths);
if (!_end.IsNormalized())
SA_LOG("_end should be normalized!", Warning, Maths);
#endif
return Maths::SLerpUnclamped(_start, _end, _alpha).GetNormalized();
}
template <typename T>
constexpr Quat<T> Quat<T>::operator-() const noexcept
{
return Quat(-w, -x, -y, -z);
}
template <typename T>
constexpr Quat<T> Quat<T>::operator*(T _scale) const noexcept
{
return GetScaled(_scale);
}
template <typename T>
constexpr Quat<T> Quat<T>::operator/(T _scale) const
{
return GetUnScaled(_scale);
}
template <typename T>
constexpr Quat<T> Quat<T>::operator+(const Quat<T>& _rhs) const noexcept
{
return Quat(
w + _rhs.w,
x + _rhs.x,
y + _rhs.y,
z + _rhs.z
);
}
template <typename T>
constexpr Quat<T> Quat<T>::operator-(const Quat<T>& _rhs) const noexcept
{
return Quat(
w - _rhs.w,
x - _rhs.x,
y - _rhs.y,
z - _rhs.z
);
}
template <typename T>
constexpr Quat<T> Quat<T>::operator*(const Quat& _rhs) const
{
return Rotate(_rhs);
}
template <typename T>
constexpr Vec3<T> Quat<T>::operator*(const Vec3<T>& _rhs) const
{
return Rotate(_rhs);
}
template <typename T>
constexpr Quat<T> Quat<T>::operator/(const Quat& _rhs) const
{
return UnRotate(_rhs);
}
template <typename T>
constexpr Vec3<T> Quat<T>::operator/(const Vec3<T>& _rhs) const
{
return UnRotate(_rhs);
}
template <typename T>
constexpr T Quat<T>::operator|(const Quat& _rhs) const noexcept
{
return Dot(*this, _rhs);
}
template <typename T>
Quat<T>& Quat<T>::operator*=(T _scale) const noexcept
{
Scale(_scale);
return *this;
}
template <typename T>
Quat<T>& Quat<T>::operator/=(T _scale) const
{
UnScale(_scale);
return *this;
}
template <typename T>
Quat<T>& Quat<T>::operator+=(const Quat<T>& _rhs) noexcept
{
w += _rhs.w;
x += _rhs.x;
y += _rhs.y;
z += _rhs.z;
return *this;
}
template <typename T>
Quat<T>& Quat<T>::operator-=(const Quat<T>& _rhs) noexcept
{
w -= _rhs.w;
x -= _rhs.x;
y -= _rhs.y;
z -= _rhs.z;
return *this;
}
template <typename T>
Quat<T>& Quat<T>::operator*=(const Quat& _rhs) noexcept
{
return *this = (*this) * _rhs;
}
template <typename T>
Quat<T>& Quat<T>::operator/=(const Quat& _rhs) noexcept
{
return *this = (*this) / _rhs;
}
template <typename T>
constexpr bool Quat<T>::operator==(const Quat<T>& _rhs) noexcept
{
return Equals(_rhs);
}
template <typename T>
constexpr bool Quat<T>::operator!=(const Quat<T>& _rhs) noexcept
{
return !(*this == _rhs);
}
template <typename T>
T& Quat<T>::operator[](uint32 _index)
{
SA_ASSERT(_index <= 3u, OutOfRange, Maths, _index, 0u, 3u);
return Data()[_index];
}
template <typename T>
T Quat<T>::operator[](uint32 _index) const
{
SA_ASSERT(_index <= 3u, OutOfRange, Maths, _index, 0u, 3u);
return Data()[_index];
}
template <typename T>
constexpr Quat<T> operator*(T _lhs, const Quat<T>& _rhs) noexcept
{
return _rhs * _lhs;
}
template <typename T>
constexpr Quat<T> operator/(T _lhs, const Quat<T>& _rhs)
{
return Quat(
_lhs / _rhs.w,
_lhs / _rhs.x,
_lhs / _rhs.y,
_lhs / _rhs.z
);
}
template <typename T>
constexpr Vec3<T> operator*(const Vec3<T>& _lhs, const Quat<T>& _rhs) noexcept
{
return _rhs * _lhs;
}
template <typename T>
constexpr Vec3<T> operator/(const Vec3<T>& _lhs, const Quat<T>& _rhs)
{
return _rhs / _lhs;
}
template <typename T>
template <typename TIn>
constexpr Quat<T>::operator Quat<TIn>() const noexcept
{
return Quat<TIn>(*this);
}
}
| 21.878489 | 143 | 0.645827 | SapphireSuite |
bfac974de42b3e3c1f3b5bc90349d2f648f20f69 | 28,880 | cpp | C++ | NULL Engine/Source/C_Animator.cpp | BarcinoLechiguino/NULL_Engine | f2abecb44bee45b7cbf2d5b53609d79d38ecc5a3 | [
"MIT"
] | 4 | 2020-11-29T12:28:31.000Z | 2021-06-08T17:32:56.000Z | NULL Engine/Source/C_Animator.cpp | BarcinoLechiguino/NULL_Engine | f2abecb44bee45b7cbf2d5b53609d79d38ecc5a3 | [
"MIT"
] | null | null | null | NULL Engine/Source/C_Animator.cpp | BarcinoLechiguino/NULL_Engine | f2abecb44bee45b7cbf2d5b53609d79d38ecc5a3 | [
"MIT"
] | 4 | 2020-11-01T17:06:32.000Z | 2021-01-09T16:58:50.000Z | #include "MathGeoLib/include/Geometry/LineSegment.h"
#include "Profiler.h"
#include "JSONParser.h"
#include "Time.h"
#include "Channel.h"
#include "AnimatorClip.h"
#include "Application.h"
#include "M_ResourceManager.h"
#include "R_Animation.h"
#include "GameObject.h"
#include "C_Transform.h"
#include "C_Animator.h"
typedef std::map<double, float3>::const_iterator PositionKeyframe;
typedef std::map<double, Quat>::const_iterator RotationKeyframe;
typedef std::map<double, float3>::const_iterator ScaleKeyframe;
C_Animator::C_Animator(GameObject* owner) : Component(owner, COMPONENT_TYPE::ANIMATOR),
current_clip (nullptr),
blending_clip (nullptr),
current_root_bone (nullptr)
{
blend_frames = 0;
play = false;
pause = false;
step = false;
stop = true;
playback_speed = 1.0f;
interpolate = true;
loop_animation = false;
play_on_start = true;
camera_culling = true;
show_bones = false;
}
C_Animator::~C_Animator()
{
current_clip = nullptr;
blending_clip = nullptr;
current_root_bone = nullptr;
}
bool C_Animator::Update()
{
BROFILER_CATEGORY("Animation Component Update", Profiler::Color::DarkSlateBlue);
bool ret = true;
AddAnimationsToAdd();
if (play || step)
{
if (current_clip != nullptr)
{
StepAnimation();
}
step = false;
}
return ret;
}
bool C_Animator::CleanUp()
{
bool ret = true;
for (uint i = 0; i < animations.size(); ++i)
{
App->resource_manager->FreeResource(animations[i]->GetUID());
}
animations.clear();
animation_bones.clear();
clips.clear();
current_bones.clear();
blending_bones.clear();
display_bones.clear();
animations_to_add.clear();
return ret;
}
bool C_Animator::SaveState(ParsonNode& root) const
{
bool ret = true;
root.SetNumber("Type", (double)GetType());
// Animations
ParsonArray animations_array = root.SetArray("Animations");
for (auto animation = animations.cbegin(); animation != animations.cend(); ++animation)
{
ParsonNode animation_node = animations_array.SetNode((*animation)->GetName());
animation_node.SetNumber("UID", (*animation)->GetUID());
animation_node.SetString("Name", (*animation)->GetAssetsFile());
animation_node.SetString("Path", (*animation)->GetLibraryPath());
animation_node.SetString("File", (*animation)->GetLibraryFile());
}
// Clips
ParsonArray clips_array = root.SetArray("Clips");
for (auto clip = clips.cbegin(); clip != clips.cend(); ++clip)
{
if (strstr(clip->first.c_str(), "Default") != nullptr)
{
continue;
}
ParsonNode clip_node = clips_array.SetNode(clip->second.GetName());
clip->second.SaveState(clip_node);
}
// Current Clip
if (current_clip != nullptr)
{
ParsonNode current_clip_node = root.SetNode("CurrentClip");
current_clip_node.SetString("AnimationName", current_clip->GetAnimationName());
current_clip_node.SetString("Name", current_clip->GetName());
}
return ret;
}
bool C_Animator::LoadState(ParsonNode& root)
{
bool ret = true;
ParsonArray animations_array = root.GetArray("Animations");
for (uint i = 0; i < animations_array.size; ++i)
{
ParsonNode animation_node = animations_array.GetNode(i);
if (!animation_node.NodeIsValid())
{
continue;
}
std::string assets_path = ASSETS_MODELS_PATH + std::string(animation_node.GetString("Name"));
App->resource_manager->AllocateResource((uint32)animation_node.GetNumber("UID"), assets_path.c_str());
R_Animation* r_animation = (R_Animation*)App->resource_manager->RequestResource((uint32)animation_node.GetNumber("UID"));
if (r_animation != nullptr)
{
animations_to_add.push_back(r_animation);
//AddAnimation(r_animation);
}
}
ParsonArray clips_array = root.GetArray("Clips");
for (uint i = 0; i < clips_array.size; ++i)
{
ParsonNode clip_node = clips_array.GetNode(i);
AnimatorClip clip = AnimatorClip();
clip.LoadState(clip_node);
clips.emplace(clip.GetName(), clip);
}
ParsonNode current_clip_node = root.GetNode("CurrentClip");
auto item = clips.find(current_clip_node.GetString("Name"));
if (item != clips.end())
{
SetCurrentClip(&item->second);
}
return ret;
}
// --- C_ANIMATION METHODS ---
bool C_Animator::StepAnimation()
{
bool ret = true;
bool success = ValidateCurrentClip();
if (!success)
{
return false;
}
success = StepClips();
if (!success)
{
return false;
}
for (uint i = 0; i < current_bones.size(); ++i)
{
const BoneLink& bone = current_bones[i];
C_Transform* c_transform = bone.game_object->GetComponent<C_Transform>();
if (c_transform == nullptr)
{
LOG("[WARNING] Animation Component: GameObject { %s } did not have a Transform Component!", bone.game_object->GetName());
continue;
}
const Transform& original_transform = Transform(c_transform->GetLocalTransform());
if (interpolate)
{
Transform& interpolated_transform = GetInterpolatedTransform(current_clip->GetAnimationFrame(), bone.channel, original_transform);
if (BlendingClipExists())
{
interpolated_transform = GetBlendedTransform(blending_clip->GetAnimationFrame(), blending_bones[i].channel, interpolated_transform);
}
c_transform->ImportTransform(interpolated_transform);
}
else
{
if (current_clip->in_new_tick)
{
Transform& pose_to_pose_transform = GetPoseToPoseTransform(current_clip->GetAnimationTick(), bone.channel, original_transform);
if (BlendingClipExists())
{
pose_to_pose_transform = GetBlendedTransform(blending_clip->GetAnimationTick(), blending_bones[i].channel, pose_to_pose_transform);
}
c_transform->ImportTransform(pose_to_pose_transform);
}
}
}
UpdateDisplayBones();
return ret;
}
bool C_Animator::StepClips()
{
bool ret = true;
bool current_exists = CurrentClipExists();
bool blending_exists = BlendingClipExists();
if (!current_exists && !blending_exists)
{
LOG("[ERROR] Animator Component: Could not Step Clips! Error: There were no Current or Blending Clips set.");
return false;
}
if (!current_exists && blending_exists)
{
SwitchBlendingToCurrent();
}
if (BlendingClipExists())
{
if (blending_clip->GetAnimationFrame() > (float)(blending_clip->GetStart() + blend_frames))
{
SwitchBlendingToCurrent();
}
}
float dt = (App->play) ? Time::Game::GetDT() : Time::Real::GetDT(); // In case a clip preview is needed outside Game Mode.
float step_value = dt * playback_speed;
if (CurrentClipExists())
{
bool success = current_clip->StepClip(step_value);
if (!success)
{
if (BlendingClipExists())
{
blending_clip->StepClip(step_value);
SwitchBlendingToCurrent();
return true;
}
else
{
if (!current_clip->IsLooped())
{
Stop();
ResetBones();
return false;
}
}
}
if (BlendingClipExists())
{
blending_clip->StepClip(step_value);
}
}
return ret;
}
bool C_Animator::BlendAnimation()
{
bool ret = true;
return ret;
}
bool C_Animator::ValidateCurrentClip()
{
bool ret = true;
if (current_clip == nullptr)
{
if (blending_clip != nullptr)
{
SwitchBlendingToCurrent();
ret = true;
}
else
{
ret = false;
}
}
return ret;
}
void C_Animator::SwitchBlendingToCurrent()
{
if (current_clip != nullptr)
{
current_clip->playing = false;
current_clip->ClearClip();
ClearCurrentClip();
}
SetCurrentClip(blending_clip);
ClearBlendingClip();
}
void C_Animator::ResetBones()
{
if (current_clip == nullptr)
{
LOG("[ERROR] Animator Component: Could not Reset Bones! Error: Current Clip was nullptr.");
return;
}
for (auto bone = current_bones.cbegin(); bone != current_bones.cend(); ++bone)
{
const Transform& transform = Transform(bone->game_object->GetComponent<C_Transform>()->GetLocalTransform());
const Transform& interpolated_transform = GetInterpolatedTransform((double)current_clip->GetStart(), bone->channel, transform);
bone->game_object->GetComponent<C_Transform>()->ImportTransform(interpolated_transform);
}
UpdateDisplayBones();
}
void C_Animator::AddAnimationsToAdd()
{
if (!animations_to_add.empty())
{
for (uint i = 0; i < animations_to_add.size(); ++i)
{
AddAnimation(animations_to_add[i]);
}
animations_to_add.clear();
}
}
Transform C_Animator::GetInterpolatedTransform(const double& keyframe, const Channel& channel, const Transform& original_transform) const
{
float3 interpolated_position = GetInterpolatedPosition(keyframe, channel, original_transform.position);
Quat interpolated_rotation = GetInterpolatedRotation(keyframe, channel, original_transform.rotation);
float3 interpolated_scale = GetInterpolatedScale(keyframe, channel, original_transform.scale);
return Transform(interpolated_position, interpolated_rotation, interpolated_scale);
}
const float3 C_Animator::GetInterpolatedPosition(const double& keyframe, const Channel& channel, const float3& original_position) const
{
if (!channel.HasPositionKeyframes())
{
return original_position;
}
PositionKeyframe prev_keyframe = channel.GetClosestPrevPositionKeyframe(keyframe);
PositionKeyframe next_keyframe = channel.GetClosestNextPositionKeyframe(keyframe);
float rate = (float)(keyframe / next_keyframe->first);
float3 ret = (prev_keyframe == next_keyframe) ? prev_keyframe->second : prev_keyframe->second.Lerp(next_keyframe->second, rate);
return ret;
}
const Quat C_Animator::GetInterpolatedRotation(const double& keyframe, const Channel& channel, const Quat& original_rotation) const
{
if (!channel.HasRotationKeyframes())
{
return original_rotation;
}
RotationKeyframe prev_keyframe = channel.GetClosestPrevRotationKeyframe(keyframe);
RotationKeyframe next_keyframe = channel.GetClosestNextRotationKeyframe(keyframe);
float rate = (float)(keyframe / next_keyframe->first);
Quat ret = (prev_keyframe == next_keyframe) ? prev_keyframe->second : prev_keyframe->second.Slerp(next_keyframe->second, rate);
return ret;
}
const float3 C_Animator::GetInterpolatedScale(const double& keyframe, const Channel& channel, const float3& original_scale) const
{
if (!channel.HasScaleKeyframes())
{
return original_scale;
}
ScaleKeyframe prev_keyframe = channel.GetClosestPrevScaleKeyframe(keyframe);
ScaleKeyframe next_keyframe = channel.GetClosestNextScaleKeyframe(keyframe);
float rate = (float)(keyframe / next_keyframe->first);
float3 ret = (prev_keyframe == next_keyframe) ? prev_keyframe->second : prev_keyframe->second.Lerp(next_keyframe->second, rate);
return ret;
}
Transform C_Animator::GetPoseToPoseTransform(const uint& tick, const Channel& channel, const Transform& original_transform) const
{
const float3& position = GetPoseToPosePosition(tick, channel, original_transform.position);
const Quat& rotation = GetPoseToPoseRotation(tick, channel, original_transform.rotation);
const float3& scale = GetPoseToPoseScale(tick, channel, original_transform.scale);
return Transform(position, rotation, scale);
}
const float3 C_Animator::GetPoseToPosePosition(const uint& tick, const Channel& channel, const float3& original_position) const
{
if (!channel.HasPositionKeyframes())
{
return original_position;
}
return channel.GetPositionKeyframe(tick)->second;
}
const Quat C_Animator::GetPoseToPoseRotation(const uint& tick, const Channel& channel, const Quat& original_rotation) const
{
if (!channel.HasRotationKeyframes())
{
return original_rotation;
}
return channel.GetRotationKeyframe(tick)->second;
}
const float3 C_Animator::GetPoseToPoseScale(const uint& tick, const Channel& channel, const float3& original_scale) const
{
if (!channel.HasScaleKeyframes())
{
return original_scale;
}
return channel.GetScaleKeyframe(tick)->second;
}
Transform C_Animator::GetBlendedTransform(const double& blended_keyframe, const Channel& blended_channel, const Transform& original_transform) const
{
const float3& position = GetBlendedPosition(blended_keyframe, blended_channel, original_transform.position);
const Quat& rotation = GetBlendedRotation(blended_keyframe, blended_channel, original_transform.rotation);
const float3& scale = GetBlendedScale(blended_keyframe, blended_channel, original_transform.scale);
return Transform(position, rotation, scale);
}
const float3 C_Animator::GetBlendedPosition(const double& blending_keyframe, const Channel& blending_channel, const float3& original_position) const
{
if (!blending_channel.HasPositionKeyframes())
{
return original_position;
}
float3 position = GetInterpolatedPosition(blending_keyframe, blending_channel, original_position);
double blend_frame = blending_keyframe - blending_clip->GetStart();
float blend_rate = (float)(blend_frame / blend_frames);
float3 blended_position = original_position.Lerp(position, blend_rate);
return blended_position;
}
const Quat C_Animator::GetBlendedRotation(const double& blending_keyframe, const Channel& blending_channel, const Quat& original_rotation) const
{
if (!blending_channel.HasRotationKeyframes())
{
return original_rotation;
}
Quat rotation = GetInterpolatedRotation(blending_keyframe, blending_channel, original_rotation);
double blend_frame = blending_keyframe - blending_clip->GetStart();
float blend_rate = (float)(blend_frame / blend_frames);
Quat blended_rotation = original_rotation.Slerp(rotation, blend_rate);
return blended_rotation;
}
const float3 C_Animator::GetBlendedScale(const double& blending_keyframe, const Channel& blending_channel, const float3& original_scale) const
{
if (!blending_channel.HasScaleKeyframes())
{
return original_scale;
}
float3 scale = GetInterpolatedScale(blending_keyframe, blending_channel, original_scale);
double blend_frame = blending_keyframe - blending_clip->GetStart();
float blend_rate = (float)(blend_frame / blend_frames);
float3 blended_scale = original_scale.Lerp(scale, blend_rate);
return blended_scale;
}
void C_Animator::FindAnimationBones(const R_Animation* r_animation)
{
if (r_animation == nullptr)
{
return;
}
if (r_animation->channels.empty())
{
return;
}
std::vector<BoneLink> links;
bool success = FindBoneLinks(r_animation, links);
if (success)
{
animation_bones.emplace(r_animation->GetUID(), links);
GameObject* root_bone = FindRootBone(links);
if (root_bone != nullptr)
{
SetRootBone(root_bone);
UpdateDisplayBones();
}
}
}
bool C_Animator::FindBoneLinks(const R_Animation* r_animation, std::vector<BoneLink>& links)
{
if (r_animation == nullptr)
{
LOG("[ERROR] Animator Component: Could not find Bone Links! Error: Given R_Animation* was nullptr.");
return false;
}
if (r_animation->channels.empty())
{
LOG("[ERROR] Animator Component: Could not find { %s }'s Bone Links! Error: R_Animation* had no channels.");
return false;
}
if (this->GetOwner()->childs.empty())
{
LOG("[ERROR] Animator Component: Could not find { %s }'s Bone Links! Error: Component Owner { %s } had no Childs.", this->GetOwner()->GetName());
return false;
}
std::map<std::string, GameObject*> childs;
this->GetOwner()->GetAllChilds(childs);
for (auto channel = r_animation->channels.cbegin(); channel != r_animation->channels.cend(); ++channel) // Trying out the auto keyword
{
auto go_item = childs.find(channel->name);
if (go_item != childs.end())
{
go_item->second->is_bone = true;
links.push_back(BoneLink((*channel), go_item->second));
}
}
childs.clear();
return true;
}
GameObject* C_Animator::FindRootBone(const std::vector<BoneLink>& links)
{
for (auto link = links.cbegin(); link != links.cend(); ++link) // Trying out the auto keyword
{
if (link->game_object->parent == nullptr)
{
continue;
}
if (!link->game_object->parent->is_bone)
{
return link->game_object;
}
}
return nullptr;
}
void C_Animator::SetRootBone(const GameObject* root_bone)
{
if (root_bone == nullptr)
{
LOG("[ERROR] Animator Component: Could not Set Root Bone! Error: Given GameObject* was nullptr.");
return;
}
if (current_root_bone == nullptr)
{
current_root_bone = root_bone;
}
else
{
if (current_root_bone != root_bone)
{
LOG("[WARNING] Animator Component: Disparity between root bones detected! A: [%s], B: [%s]", current_root_bone->GetName(), root_bone->GetName());
}
}
}
void C_Animator::UpdateDisplayBones()
{
display_bones.clear();
if (current_root_bone != nullptr)
{
GenerateBoneSegments(current_root_bone);
}
return;
}
void C_Animator::GenerateBoneSegments(const GameObject* bone)
{
if (bone == nullptr)
{
LOG("[ERROR] Animation Component: Could not Generate Bone Segments! Error: Given GameObject* was nullptr.");
return;
}
if (bone->childs.empty() || !bone->is_bone)
{
return;
}
C_Transform* bone_transform = bone->GetComponent<C_Transform>();
for (uint i = 0; i < bone->childs.size(); ++i)
{
LineSegment display_bone = { float3::zero, float3::zero };
display_bone.a = bone_transform->GetWorldPosition();
display_bone.b = bone->childs[i]->GetComponent<C_Transform>()->GetWorldPosition();
display_bones.push_back(display_bone);
GenerateBoneSegments(bone->childs[i]);
}
}
bool C_Animator::GenerateDefaultClip(const R_Animation* r_animation, AnimatorClip& default_clip)
{
if (r_animation == nullptr)
{
LOG("[ERROR] Animator Component: Could not Generate Default Clip! Error: Given R_Animation* was nullptr.");
return false;
}
std::string default_name = r_animation->GetName() + std::string(" Default");
default_clip = AnimatorClip(r_animation, default_name, 0, (uint)r_animation->GetDuration(), false);
return true;
}
void C_Animator::SortBoneLinksByHierarchy(const std::vector<BoneLink>& bone_links, const GameObject* root_bone, std::vector<BoneLink>& sorted)
{
if (root_bone == nullptr)
{
return;
}
if (root_bone == current_root_bone)
{
for (uint j = 0; j < bone_links.size(); ++j)
{
if (bone_links[j].channel.name == root_bone->GetName())
{
sorted.push_back(bone_links[j]);
}
}
}
for (uint i = 0; i < root_bone->childs.size(); ++i)
{
for (uint j = 0; j < bone_links.size(); ++j)
{
if (bone_links[j].channel.name == root_bone->childs[i]->GetName())
{
sorted.push_back(bone_links[j]);
}
}
}
for (uint i = 0; i < root_bone->childs.size(); ++i)
{
SortBoneLinksByHierarchy(bone_links, root_bone->childs[i], sorted);
}
}
void C_Animator::AddAnimation(R_Animation* r_animation)
{
if (r_animation == nullptr)
{
LOG("[ERROR] Animator Component: Could not Add Animation to %s's Animation Component! Error: Argument R_Animation* was nullptr.", this->GetOwner()->GetName());
return;
}
animations.push_back(r_animation);
FindAnimationBones(r_animation);
AnimatorClip default_clip = AnimatorClip();
bool success = GenerateDefaultClip(r_animation, default_clip);
if (success)
{
clips.emplace(default_clip.GetName(), default_clip);
if (current_clip == nullptr)
{
SetCurrentClip(&clips.find(default_clip.GetName())->second);
}
}
}
bool C_Animator::AddClip(const AnimatorClip& clip)
{
if (clip.GetAnimation() == nullptr)
{
LOG("[ERROR] Animator Component: Could not Add Clip { %s }! Error: Clip's R_Animation* was nullptr.", clip.GetName());
return false;
}
if (clips.find(clip.GetName()) != clips.end())
{
LOG("[ERROR] Animator Component: Could not Add Clip { %s }! Error: A clip with the same name already exists.", clip.GetName());
return false;
}
clips.emplace(clip.GetName(), clip);
if (current_clip == nullptr)
{
current_clip = (AnimatorClip*)&clip;
}
return true;
}
void C_Animator::PlayClip(const std::string& clip_name, const uint& blend_frames)
{
auto item = clips.find(clip_name);
if (item == clips.end())
{
LOG("[ERROR] Animator Component: Could not Play Clip! Error: Could not find any clip with the given name!");
return;
}
if (current_clip != nullptr && current_clip->GetName() == clip_name)
{
return;
}
if (current_clip == nullptr || blend_frames == 0 || blend_frames > item->second.GetDuration())
{
Stop();
SetCurrentClip(&item->second);
}
else
{
SetBlendingClip(&item->second, blend_frames);
}
Play();
}
bool C_Animator::Play()
{
if (current_clip == nullptr)
{
return false;
}
play = true;
pause = false;
step = false;
stop = false;
current_clip->playing = true;
if (BlendingClipExists())
{
blending_clip->playing = true;
};
return play;
}
bool C_Animator::Pause()
{
if (play)
{
pause = true;
play = false;
step = false;
}
else
{
LOG("[WARNING] Animation Component: Cannot Pause a Stopped Animation!");
}
return pause;
}
bool C_Animator::Step()
{
if (pause)
{
step = true;
}
else
{
LOG("[WARNING] Animation Component: Only Paused Animations can be Stepped!");
}
return step;
}
bool C_Animator::Stop()
{
stop = true;
play = false;
pause = false;
step = false;
current_clip->playing = false;
current_clip->ClearClip();
if (BlendingClipExists())
{
blending_clip->playing = false;
blending_clip->ClearClip();
}
return stop;
}
// --- DEBUG METHODS
bool C_Animator::StepToPrevKeyframe()
{
if (play)
{
LOG("[ERROR] Animator Component: Could not Step Animation to Prev Keyframe! Error: Cannot step an animation that is being currently Played.");
return false;
}
if (current_clip == nullptr)
{
LOG("[ERROR] Animator Component: Could not Step Animation to Prev Keyframe! Error: Current Clip (AnimatorClip*) was nullptr.");
return false;
}
current_clip->StepClipToPrevKeyframe();
for (uint i = 0; i < current_bones.size(); ++i)
{
const Transform& transform = Transform(current_bones[i].game_object->GetComponent<C_Transform>()->GetLocalTransform());
const Transform& interpolated_transform = GetInterpolatedTransform((double)current_clip->GetClipTick(), current_bones[i].channel, transform);
current_bones[i].game_object->GetComponent<C_Transform>()->ImportTransform(interpolated_transform);
}
UpdateDisplayBones();
return true;
}
bool C_Animator::StepToNextKeyframe()
{
if (play)
{
LOG("[ERROR] Animator Component: Could not Step Animation to Next Keyframe! Error: Cannot step an animation that is being currently Played.");
return false;
}
if (current_clip == nullptr)
{
LOG("[ERROR] Animator Component: Could not Step Animation to Next Keyframe! Error: Current Clip (AnimatorClip*) was nullptr.");
return false;
}
current_clip->StepClipToNextKeyframe();
for (uint i = 0; i < current_bones.size(); ++i)
{
const Transform& transform = Transform(current_bones[i].game_object->GetComponent<C_Transform>()->GetLocalTransform());
const Transform& interpolated_transform = GetInterpolatedTransform((double)current_clip->GetClipTick(), current_bones[i].channel, transform);
current_bones[i].game_object->GetComponent<C_Transform>()->ImportTransform(interpolated_transform);
}
UpdateDisplayBones();
return false;
}
bool C_Animator::RefreshBoneDisplay()
{
UpdateDisplayBones();
return true;
}
// --- CURRENT/BLENDING ANIMATION METHODS
AnimatorClip* C_Animator::GetCurrentClip() const
{
return current_clip;
}
AnimatorClip* C_Animator::GetBlendingClip() const
{
return blending_clip;
}
void C_Animator::SetCurrentClip(AnimatorClip* clip)
{
std::string error_string = "[ERROR] Animator Component: Could not Set Current Clip to { " + std::string(this->GetOwner()->GetName()) + " }'s Animator Component";
if (clip == nullptr)
{
LOG("%s! Error: Given AnimatorClip* was nullptr.", error_string.c_str());
return;
}
if (clips.find(clip->GetName()) == clips.end())
{
LOG("%s! Error: Could not find the given AnimatorClip* in the clips map.", error_string.c_str());
return;
}
if (clip->GetAnimation() == nullptr)
{
LOG("%s! Error: Given AnimatorClip* had no R_Animation* assigned to it.", error_string.c_str());
return;
}
auto bones = animation_bones.find(clip->GetAnimation()->GetUID());
if (bones == animation_bones.end())
{
LOG("%s! Error: Could not find the Bones of the Clip's animation (R_Animation*).");
return;
}
current_clip = clip;
current_bones = bones->second;
//current_clip->ClearClip();
}
void C_Animator::SetBlendingClip(AnimatorClip* clip, uint blend_frames)
{
std::string error_string = "[ERROR] Animator Component: Could not Set Blending Clip in { " + std::string(this->GetOwner()->GetName()) + " }'s Animator Component";
if (clip == nullptr)
{
LOG("%s! Error: Given AnimatorClip* was nullptr.", error_string.c_str());
return;
}
if (clips.find(clip->GetName()) == clips.end())
{
LOG("%s! Error: Could not find the given AnimatorClip* in the clips map.", error_string.c_str());
return;
}
if (clip->GetAnimation() == nullptr)
{
LOG("%s! Error: Given AnimatorClip* had no R_Animation* assigned to it.", error_string.c_str());
return;
}
auto bones = animation_bones.find(clip->GetAnimation()->GetUID());
if (bones == animation_bones.end())
{
LOG("%s! Error: Could not find the Bones of the Clip's animation (R_Animation*).");
return;
}
blending_clip = clip;
blending_bones = bones->second;
this->blend_frames = blend_frames;
blending_clip->ClearClip(); // Resetting the clip just in case.
}
void C_Animator::SetCurrentClipByIndex(const uint& index)
{
if (index >= clips.size())
{
LOG("[ERROR] Animator Component: Could not Set Current Clip By Index! Error: Given Index was out of bounds.");
return;
}
std::string error_string = "[ERROR] Animator Component: Could not Set Current Clip in { " + std::string(this->GetOwner()->GetName()) + " }'s Animator Component";
uint i = 0;
for (auto item = clips.cbegin(); item != clips.cend(); ++item)
{
if (i == index) // Dirty way of finding items in a map by index.
{
const AnimatorClip& clip = item->second;
if (animation_bones.find(clip.GetAnimation()->GetUID()) == animation_bones.end())
{
LOG("%s! Error: Could not find the Bones of the Clip's animation (R_Animation*).");
return;
}
current_clip = (AnimatorClip*)&clip;
current_bones = animation_bones.find(clip.GetAnimation()->GetUID())->second;
current_clip->ClearClip();
return;
}
++i;
}
}
/*void C_Animator::SetBlendingClipByIndex(const uint& index, const uint& blend_frames)
{
}*/
bool C_Animator::CurrentClipExists() const
{
return (current_clip != nullptr) ? true : false;
}
bool C_Animator::BlendingClipExists() const
{
return (blending_clip != nullptr) ? true : false;
}
void C_Animator::ClearCurrentClip()
{
current_clip = nullptr;
current_bones.clear();
}
void C_Animator::ClearBlendingClip()
{
blending_clip = nullptr;
blend_frames = 0;
blending_bones.clear();
}
// --- GET/SET METHODS
std::vector<LineSegment> C_Animator::GetDisplayBones() const
{
return display_bones;
}
std::vector<std::string> C_Animator::GetClipNamesAsVector() const
{
std::vector<std::string> clip_names;
for (auto clip = clips.cbegin(); clip != clips.cend(); ++clip)
{
clip_names.push_back(clip->first);
}
return clip_names;
}
std::string C_Animator::GetClipNamesAsString() const
{
std::string clip_names = "";
for (auto clip = clips.cbegin(); clip != clips.cend(); ++clip)
{
clip_names += clip->first.c_str();
clip_names += '\0';
}
return clip_names;
}
std::string C_Animator::GetAnimationNamesAsString() const
{
std::string animation_names = "";
for (auto animation = animations.cbegin(); animation != animations.cend(); ++animation)
{
animation_names += (*animation)->GetName();
animation_names += '\0';
}
return animation_names;
}
R_Animation* C_Animator::GetAnimationByIndex(const uint& index) const
{
if (index >= animations.size())
{
LOG("[ERROR] Animator Component: Could not get Animation by Index! Error: Given index was out of bounds.");
return nullptr;
}
return animations[index];
}
float C_Animator::GetPlaybackSpeed() const
{
return playback_speed;
}
bool C_Animator::GetInterpolate() const
{
return interpolate;
}
bool C_Animator::GetLoopAnimation() const
{
return loop_animation;
}
bool C_Animator::GetPlayOnStart() const
{
return play_on_start;
}
bool C_Animator::GetCameraCulling() const
{
return camera_culling;
}
bool C_Animator::GetShowBones() const
{
return show_bones;
}
void C_Animator::SetPlaybackSpeed(const float& playback_speed)
{
this->playback_speed = playback_speed;
}
void C_Animator::SetInterpolate(const bool& set_to)
{
interpolate = set_to;
}
void C_Animator::SetLoopAnimation(const bool& set_to)
{
loop_animation = set_to;
}
void C_Animator::SetPlayOnStart(const bool& set_to)
{
play_on_start = set_to;
}
void C_Animator::SetCameraCulling(const bool& set_to)
{
camera_culling = set_to;
}
void C_Animator::SetShowBones(const bool& set_to)
{
show_bones = set_to;
}
// --- BONE LINK METHODS
BoneLink::BoneLink() :
channel(Channel()),
game_object(nullptr)
{
}
BoneLink::BoneLink(const Channel& channel, GameObject* game_object) :
channel(channel),
game_object(game_object)
{
} | 24.066667 | 163 | 0.717209 | BarcinoLechiguino |
bfaf1a64947d58d5337963ecadaf3c1423b6ce1b | 1,336 | cpp | C++ | src/human_aware_navigation/src/KeyboardManager.cpp | CodeToPoem/HumanAwareRobotNavigation | d44eb7e5acd73a5a7bf8bf1cd88c23d6a4a3c330 | [
"BSD-3-Clause"
] | 20 | 2017-10-26T05:58:24.000Z | 2021-06-13T11:18:54.000Z | src/human_aware_navigation/src/KeyboardManager.cpp | dmr-goncalves/HumanAwareRobotNavigation | d44eb7e5acd73a5a7bf8bf1cd88c23d6a4a3c330 | [
"BSD-3-Clause"
] | null | null | null | src/human_aware_navigation/src/KeyboardManager.cpp | dmr-goncalves/HumanAwareRobotNavigation | d44eb7e5acd73a5a7bf8bf1cd88c23d6a4a3c330 | [
"BSD-3-Clause"
] | 6 | 2018-02-05T09:31:42.000Z | 2022-02-07T22:05:57.000Z | /***************************** Made by Duarte Gonçalves *********************************/
#include "human_aware_navigation/KeyboardManager.hpp"
KeyboardManager::KeyboardManager(){
m_pub_TaskFinished = m_nd.advertise<human_aware_navigation::TaskFinished>("/task_finished", 1, true);
}
void KeyboardManager::run(){
Rate loop_rate(1);
while(ok()){
enable_raw_mode();
if (kbhit()){
char key = getchar();
switch(key){
case '1':
//printer::printGreen("Key 1 pressed");
tf.task_id = 1;
break;
case '2':
//printer::printGreen("Key 2 pressed");
tf.task_id = 2;
break;
case '3':
//printer::printGreen("Key 3 pressed");
tf.task_id = 3;
break;
}
m_pub_TaskFinished.publish(tf);
}
disable_raw_mode();
tcflush(0, TCIFLUSH); // Clear stdin to prevent characters appearing on prompt
spinOnce();
loop_rate.sleep();
}
}
void KeyboardManager::enable_raw_mode(){
termios term;
tcgetattr(0, &term);
term.c_lflag &= ~(ICANON | ECHO); // Disable echo as well
tcsetattr(0, TCSANOW, &term);
}
void KeyboardManager::disable_raw_mode(){
termios term;
tcgetattr(0, &term);
term.c_lflag |= ICANON | ECHO;
tcsetattr(0, TCSANOW, &term);
}
bool KeyboardManager::kbhit(){
int byteswaiting;
ioctl(0, FIONREAD, &byteswaiting);
return byteswaiting > 0;
}
| 18.816901 | 102 | 0.631737 | CodeToPoem |
bfafbb740d1b97a15171e88e1bf704e24efc80c4 | 23,056 | cc | C++ | src/mojo/edk/system/message_pipe_unittest.cc | bopopescu/MQUIC | 703e944ec981366cfd2528943b1def2c72b7e49d | [
"MIT"
] | 1 | 2018-01-02T15:42:08.000Z | 2018-01-02T15:42:08.000Z | src/mojo/edk/system/message_pipe_unittest.cc | bopopescu/MQUIC | 703e944ec981366cfd2528943b1def2c72b7e49d | [
"MIT"
] | null | null | null | src/mojo/edk/system/message_pipe_unittest.cc | bopopescu/MQUIC | 703e944ec981366cfd2528943b1def2c72b7e49d | [
"MIT"
] | 1 | 2020-07-25T02:05:49.000Z | 2020-07-25T02:05:49.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stdint.h>
#include "base/memory/ref_counted.h"
#include "mojo/edk/system/test_utils.h"
#include "mojo/edk/test/mojo_test_base.h"
#include "mojo/public/c/system/core.h"
#include "mojo/public/c/system/types.h"
namespace mojo {
namespace edk {
namespace {
const MojoHandleSignals kAllSignals = MOJO_HANDLE_SIGNAL_READABLE |
MOJO_HANDLE_SIGNAL_WRITABLE |
MOJO_HANDLE_SIGNAL_PEER_CLOSED;
static const char kHelloWorld[] = "hello world";
class MessagePipeTest : public test::MojoTestBase {
public:
MessagePipeTest() {
CHECK_EQ(MOJO_RESULT_OK, MojoCreateMessagePipe(nullptr, &pipe0_, &pipe1_));
}
~MessagePipeTest() override {
if (pipe0_ != MOJO_HANDLE_INVALID)
CHECK_EQ(MOJO_RESULT_OK, MojoClose(pipe0_));
if (pipe1_ != MOJO_HANDLE_INVALID)
CHECK_EQ(MOJO_RESULT_OK, MojoClose(pipe1_));
}
MojoResult WriteMessage(MojoHandle message_pipe_handle,
const void* bytes,
uint32_t num_bytes) {
return MojoWriteMessage(message_pipe_handle, bytes, num_bytes, nullptr, 0,
MOJO_WRITE_MESSAGE_FLAG_NONE);
}
MojoResult ReadMessage(MojoHandle message_pipe_handle,
void* bytes,
uint32_t* num_bytes,
bool may_discard = false) {
return MojoReadMessage(message_pipe_handle, bytes, num_bytes, nullptr, 0,
may_discard ? MOJO_READ_MESSAGE_FLAG_MAY_DISCARD :
MOJO_READ_MESSAGE_FLAG_NONE);
}
MojoHandle pipe0_, pipe1_;
private:
DISALLOW_COPY_AND_ASSIGN(MessagePipeTest);
};
using FuseMessagePipeTest = test::MojoTestBase;
TEST_F(MessagePipeTest, WriteData) {
ASSERT_EQ(MOJO_RESULT_OK,
WriteMessage(pipe0_, kHelloWorld, sizeof(kHelloWorld)));
}
// Tests:
// - only default flags
// - reading messages from a port
// - when there are no/one/two messages available for that port
// - with buffer size 0 (and null buffer) -- should get size
// - with too-small buffer -- should get size
// - also verify that buffers aren't modified when/where they shouldn't be
// - writing messages to a port
// - in the obvious scenarios (as above)
// - to a port that's been closed
// - writing a message to a port, closing the other (would be the source) port,
// and reading it
TEST_F(MessagePipeTest, Basic) {
int32_t buffer[2];
const uint32_t kBufferSize = static_cast<uint32_t>(sizeof(buffer));
uint32_t buffer_size;
// Nothing to read yet on port 0.
buffer[0] = 123;
buffer[1] = 456;
buffer_size = kBufferSize;
ASSERT_EQ(MOJO_RESULT_SHOULD_WAIT, ReadMessage(pipe0_, buffer, &buffer_size));
ASSERT_EQ(kBufferSize, buffer_size);
ASSERT_EQ(123, buffer[0]);
ASSERT_EQ(456, buffer[1]);
// Ditto for port 1.
buffer[0] = 123;
buffer[1] = 456;
buffer_size = kBufferSize;
ASSERT_EQ(MOJO_RESULT_SHOULD_WAIT, ReadMessage(pipe1_, buffer, &buffer_size));
// Write from port 1 (to port 0).
buffer[0] = 789012345;
buffer[1] = 0;
ASSERT_EQ(MOJO_RESULT_OK, WriteMessage(pipe1_, buffer, sizeof(buffer[0])));
MojoHandleSignalsState state;
ASSERT_EQ(MOJO_RESULT_OK, MojoWait(pipe0_, MOJO_HANDLE_SIGNAL_READABLE,
MOJO_DEADLINE_INDEFINITE, &state));
// Read from port 0.
buffer[0] = 123;
buffer[1] = 456;
buffer_size = kBufferSize;
ASSERT_EQ(MOJO_RESULT_OK, ReadMessage(pipe0_, buffer, &buffer_size));
ASSERT_EQ(static_cast<uint32_t>(sizeof(buffer[0])), buffer_size);
ASSERT_EQ(789012345, buffer[0]);
ASSERT_EQ(456, buffer[1]);
// Read again from port 0 -- it should be empty.
buffer_size = kBufferSize;
ASSERT_EQ(MOJO_RESULT_SHOULD_WAIT, ReadMessage(pipe0_, buffer, &buffer_size));
// Write two messages from port 0 (to port 1).
buffer[0] = 123456789;
buffer[1] = 0;
ASSERT_EQ(MOJO_RESULT_OK, WriteMessage(pipe0_, buffer, sizeof(buffer[0])));
buffer[0] = 234567890;
buffer[1] = 0;
ASSERT_EQ(MOJO_RESULT_OK, WriteMessage(pipe0_, buffer, sizeof(buffer[0])));
ASSERT_EQ(MOJO_RESULT_OK, MojoWait(pipe1_, MOJO_HANDLE_SIGNAL_READABLE,
MOJO_DEADLINE_INDEFINITE, &state));
// Read from port 1 with buffer size 0 (should get the size of next message).
// Also test that giving a null buffer is okay when the buffer size is 0.
buffer_size = 0;
ASSERT_EQ(MOJO_RESULT_RESOURCE_EXHAUSTED,
ReadMessage(pipe1_, nullptr, &buffer_size));
ASSERT_EQ(static_cast<uint32_t>(sizeof(buffer[0])), buffer_size);
// Read from port 1 with buffer size 1 (too small; should get the size of next
// message).
buffer[0] = 123;
buffer[1] = 456;
buffer_size = 1;
ASSERT_EQ(MOJO_RESULT_RESOURCE_EXHAUSTED,
ReadMessage(pipe1_, buffer, &buffer_size));
ASSERT_EQ(static_cast<uint32_t>(sizeof(buffer[0])), buffer_size);
ASSERT_EQ(123, buffer[0]);
ASSERT_EQ(456, buffer[1]);
// Read from port 1.
buffer[0] = 123;
buffer[1] = 456;
buffer_size = kBufferSize;
ASSERT_EQ(MOJO_RESULT_OK, ReadMessage(pipe1_, buffer, &buffer_size));
ASSERT_EQ(static_cast<uint32_t>(sizeof(buffer[0])), buffer_size);
ASSERT_EQ(123456789, buffer[0]);
ASSERT_EQ(456, buffer[1]);
ASSERT_EQ(MOJO_RESULT_OK, MojoWait(pipe1_, MOJO_HANDLE_SIGNAL_READABLE,
MOJO_DEADLINE_INDEFINITE, &state));
// Read again from port 1.
buffer[0] = 123;
buffer[1] = 456;
buffer_size = kBufferSize;
ASSERT_EQ(MOJO_RESULT_OK, ReadMessage(pipe1_, buffer, &buffer_size));
ASSERT_EQ(static_cast<uint32_t>(sizeof(buffer[0])), buffer_size);
ASSERT_EQ(234567890, buffer[0]);
ASSERT_EQ(456, buffer[1]);
// Read again from port 1 -- it should be empty.
buffer_size = kBufferSize;
ASSERT_EQ(MOJO_RESULT_SHOULD_WAIT, ReadMessage(pipe1_, buffer, &buffer_size));
// Write from port 0 (to port 1).
buffer[0] = 345678901;
buffer[1] = 0;
ASSERT_EQ(MOJO_RESULT_OK, WriteMessage(pipe0_, buffer, sizeof(buffer[0])));
// Close port 0.
MojoClose(pipe0_);
pipe0_ = MOJO_HANDLE_INVALID;
ASSERT_EQ(MOJO_RESULT_OK, MojoWait(pipe1_, MOJO_HANDLE_SIGNAL_PEER_CLOSED,
MOJO_DEADLINE_INDEFINITE, &state));
// Try to write from port 1 (to port 0).
buffer[0] = 456789012;
buffer[1] = 0;
ASSERT_EQ(MOJO_RESULT_FAILED_PRECONDITION,
WriteMessage(pipe1_, buffer, sizeof(buffer[0])));
// Read from port 1; should still get message (even though port 0 was closed).
buffer[0] = 123;
buffer[1] = 456;
buffer_size = kBufferSize;
ASSERT_EQ(MOJO_RESULT_OK, ReadMessage(pipe1_, buffer, &buffer_size));
ASSERT_EQ(static_cast<uint32_t>(sizeof(buffer[0])), buffer_size);
ASSERT_EQ(345678901, buffer[0]);
ASSERT_EQ(456, buffer[1]);
// Read again from port 1 -- it should be empty (and port 0 is closed).
buffer_size = kBufferSize;
ASSERT_EQ(MOJO_RESULT_FAILED_PRECONDITION,
ReadMessage(pipe1_, buffer, &buffer_size));
}
TEST_F(MessagePipeTest, CloseWithQueuedIncomingMessages) {
int32_t buffer[1];
const uint32_t kBufferSize = static_cast<uint32_t>(sizeof(buffer));
uint32_t buffer_size;
// Write some messages from port 1 (to port 0).
for (int32_t i = 0; i < 5; i++) {
buffer[0] = i;
ASSERT_EQ(MOJO_RESULT_OK, WriteMessage(pipe1_, buffer, kBufferSize));
}
MojoHandleSignalsState state;
ASSERT_EQ(MOJO_RESULT_OK, MojoWait(pipe0_, MOJO_HANDLE_SIGNAL_READABLE,
MOJO_DEADLINE_INDEFINITE, &state));
// Port 0 shouldn't be empty.
buffer_size = 0;
ASSERT_EQ(MOJO_RESULT_RESOURCE_EXHAUSTED,
ReadMessage(pipe0_, nullptr, &buffer_size));
ASSERT_EQ(kBufferSize, buffer_size);
// Close port 0 first, which should have outstanding (incoming) messages.
MojoClose(pipe0_);
MojoClose(pipe1_);
pipe0_ = pipe1_ = MOJO_HANDLE_INVALID;
}
TEST_F(MessagePipeTest, DiscardMode) {
int32_t buffer[2];
const uint32_t kBufferSize = static_cast<uint32_t>(sizeof(buffer));
uint32_t buffer_size;
// Write from port 1 (to port 0).
buffer[0] = 789012345;
buffer[1] = 0;
ASSERT_EQ(MOJO_RESULT_OK, WriteMessage(pipe1_, buffer, sizeof(buffer[0])));
MojoHandleSignalsState state;
ASSERT_EQ(MOJO_RESULT_OK, MojoWait(pipe0_, MOJO_HANDLE_SIGNAL_READABLE,
MOJO_DEADLINE_INDEFINITE, &state));
// Read/discard from port 0 (no buffer); get size.
buffer_size = 0;
ASSERT_EQ(MOJO_RESULT_RESOURCE_EXHAUSTED,
ReadMessage(pipe0_, nullptr, &buffer_size, true));
ASSERT_EQ(static_cast<uint32_t>(sizeof(buffer[0])), buffer_size);
// Read again from port 0 -- it should be empty.
buffer_size = kBufferSize;
ASSERT_EQ(MOJO_RESULT_SHOULD_WAIT,
ReadMessage(pipe0_, buffer, &buffer_size, true));
// Write from port 1 (to port 0).
buffer[0] = 890123456;
buffer[1] = 0;
ASSERT_EQ(MOJO_RESULT_OK,
WriteMessage(pipe1_, buffer, sizeof(buffer[0])));
ASSERT_EQ(MOJO_RESULT_OK, MojoWait(pipe0_, MOJO_HANDLE_SIGNAL_READABLE,
MOJO_DEADLINE_INDEFINITE, &state));
// Read from port 0 (buffer big enough).
buffer[0] = 123;
buffer[1] = 456;
buffer_size = kBufferSize;
ASSERT_EQ(MOJO_RESULT_OK, ReadMessage(pipe0_, buffer, &buffer_size, true));
ASSERT_EQ(static_cast<uint32_t>(sizeof(buffer[0])), buffer_size);
ASSERT_EQ(890123456, buffer[0]);
ASSERT_EQ(456, buffer[1]);
// Read again from port 0 -- it should be empty.
buffer_size = kBufferSize;
ASSERT_EQ(MOJO_RESULT_SHOULD_WAIT,
ReadMessage(pipe0_, buffer, &buffer_size, true));
// Write from port 1 (to port 0).
buffer[0] = 901234567;
buffer[1] = 0;
ASSERT_EQ(MOJO_RESULT_OK, WriteMessage(pipe1_, buffer, sizeof(buffer[0])));
ASSERT_EQ(MOJO_RESULT_OK, MojoWait(pipe0_, MOJO_HANDLE_SIGNAL_READABLE,
MOJO_DEADLINE_INDEFINITE, &state));
// Read/discard from port 0 (buffer too small); get size.
buffer_size = 1;
ASSERT_EQ(MOJO_RESULT_RESOURCE_EXHAUSTED,
ReadMessage(pipe0_, buffer, &buffer_size, true));
ASSERT_EQ(static_cast<uint32_t>(sizeof(buffer[0])), buffer_size);
// Read again from port 0 -- it should be empty.
buffer_size = kBufferSize;
ASSERT_EQ(MOJO_RESULT_SHOULD_WAIT,
ReadMessage(pipe0_, buffer, &buffer_size, true));
// Write from port 1 (to port 0).
buffer[0] = 123456789;
buffer[1] = 0;
ASSERT_EQ(MOJO_RESULT_OK, WriteMessage(pipe1_, buffer, sizeof(buffer[0])));
ASSERT_EQ(MOJO_RESULT_OK, MojoWait(pipe0_, MOJO_HANDLE_SIGNAL_READABLE,
MOJO_DEADLINE_INDEFINITE, &state));
// Discard from port 0.
buffer_size = 1;
ASSERT_EQ(MOJO_RESULT_RESOURCE_EXHAUSTED,
ReadMessage(pipe0_, nullptr, 0, true));
// Read again from port 0 -- it should be empty.
buffer_size = kBufferSize;
ASSERT_EQ(MOJO_RESULT_SHOULD_WAIT,
ReadMessage(pipe0_, buffer, &buffer_size, true));
}
TEST_F(MessagePipeTest, BasicWaiting) {
MojoHandleSignalsState hss;
int32_t buffer[1];
const uint32_t kBufferSize = static_cast<uint32_t>(sizeof(buffer));
uint32_t buffer_size;
// Always writable (until the other port is closed).
hss = MojoHandleSignalsState();
ASSERT_EQ(MOJO_RESULT_OK, MojoWait(pipe0_, MOJO_HANDLE_SIGNAL_WRITABLE, 0,
&hss));
ASSERT_EQ(MOJO_HANDLE_SIGNAL_WRITABLE, hss.satisfied_signals);
ASSERT_EQ(kAllSignals, hss.satisfiable_signals);
hss = MojoHandleSignalsState();
// Not yet readable.
ASSERT_EQ(MOJO_RESULT_DEADLINE_EXCEEDED,
MojoWait(pipe0_, MOJO_HANDLE_SIGNAL_READABLE, 0, &hss));
ASSERT_EQ(MOJO_HANDLE_SIGNAL_WRITABLE, hss.satisfied_signals);
ASSERT_EQ(kAllSignals, hss.satisfiable_signals);
// The peer is not closed.
hss = MojoHandleSignalsState();
ASSERT_EQ(MOJO_RESULT_DEADLINE_EXCEEDED,
MojoWait(pipe0_, MOJO_HANDLE_SIGNAL_PEER_CLOSED, 0, &hss));
ASSERT_EQ(MOJO_HANDLE_SIGNAL_WRITABLE, hss.satisfied_signals);
ASSERT_EQ(kAllSignals, hss.satisfiable_signals);
// Write from port 0 (to port 1), to make port 1 readable.
buffer[0] = 123456789;
ASSERT_EQ(MOJO_RESULT_OK, WriteMessage(pipe0_, buffer, kBufferSize));
// Port 1 should already be readable now.
ASSERT_EQ(MOJO_RESULT_OK, MojoWait(pipe1_, MOJO_HANDLE_SIGNAL_READABLE,
MOJO_DEADLINE_INDEFINITE, &hss));
ASSERT_EQ(MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_WRITABLE,
hss.satisfied_signals);
ASSERT_EQ(kAllSignals, hss.satisfiable_signals);
// ... and still writable.
hss = MojoHandleSignalsState();
ASSERT_EQ(MOJO_RESULT_OK, MojoWait(pipe1_, MOJO_HANDLE_SIGNAL_WRITABLE,
MOJO_DEADLINE_INDEFINITE, &hss));
ASSERT_EQ(MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_WRITABLE,
hss.satisfied_signals);
ASSERT_EQ(kAllSignals, hss.satisfiable_signals);
// Close port 0.
MojoClose(pipe0_);
pipe0_ = MOJO_HANDLE_INVALID;
// Port 1 should be signaled with peer closed.
hss = MojoHandleSignalsState();
ASSERT_EQ(MOJO_RESULT_OK, MojoWait(pipe1_, MOJO_HANDLE_SIGNAL_PEER_CLOSED,
MOJO_DEADLINE_INDEFINITE, &hss));
ASSERT_EQ(MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
hss.satisfied_signals);
ASSERT_EQ(MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
hss.satisfiable_signals);
// Port 1 should not be writable.
hss = MojoHandleSignalsState();
ASSERT_EQ(MOJO_RESULT_FAILED_PRECONDITION,
MojoWait(pipe1_, MOJO_HANDLE_SIGNAL_WRITABLE,
MOJO_DEADLINE_INDEFINITE, &hss));
ASSERT_EQ(MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
hss.satisfied_signals);
ASSERT_EQ(MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
hss.satisfiable_signals);
// But it should still be readable.
hss = MojoHandleSignalsState();
ASSERT_EQ(MOJO_RESULT_OK, MojoWait(pipe1_, MOJO_HANDLE_SIGNAL_READABLE,
MOJO_DEADLINE_INDEFINITE, &hss));
ASSERT_EQ(MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
hss.satisfied_signals);
ASSERT_EQ(MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
hss.satisfiable_signals);
// Read from port 1.
buffer[0] = 0;
buffer_size = kBufferSize;
ASSERT_EQ(MOJO_RESULT_OK, ReadMessage(pipe1_, buffer, &buffer_size));
ASSERT_EQ(123456789, buffer[0]);
// Now port 1 should no longer be readable.
hss = MojoHandleSignalsState();
ASSERT_EQ(MOJO_RESULT_FAILED_PRECONDITION,
MojoWait(pipe1_, MOJO_HANDLE_SIGNAL_READABLE,
MOJO_DEADLINE_INDEFINITE, &hss));
ASSERT_EQ(MOJO_HANDLE_SIGNAL_PEER_CLOSED, hss.satisfied_signals);
ASSERT_EQ(MOJO_HANDLE_SIGNAL_PEER_CLOSED, hss.satisfiable_signals);
}
#if !defined(OS_IOS)
const size_t kPingPongHandlesPerIteration = 50;
const size_t kPingPongIterations = 500;
DEFINE_TEST_CLIENT_TEST_WITH_PIPE(HandlePingPong, MessagePipeTest, h) {
// Waits for a handle to become readable and writes it back to the sender.
for (size_t i = 0; i < kPingPongIterations; i++) {
MojoHandle handles[kPingPongHandlesPerIteration];
ReadMessageWithHandles(h, handles, kPingPongHandlesPerIteration);
WriteMessageWithHandles(h, "", handles, kPingPongHandlesPerIteration);
}
EXPECT_EQ(MOJO_RESULT_OK, MojoWait(h, MOJO_HANDLE_SIGNAL_READABLE,
MOJO_DEADLINE_INDEFINITE, nullptr));
char msg[4];
uint32_t num_bytes = 4;
EXPECT_EQ(MOJO_RESULT_OK, ReadMessage(h, msg, &num_bytes));
}
// This test is flaky: http://crbug.com/585784
TEST_F(MessagePipeTest, DISABLED_DataPipeConsumerHandlePingPong) {
MojoHandle p, c[kPingPongHandlesPerIteration];
for (size_t i = 0; i < kPingPongHandlesPerIteration; ++i) {
EXPECT_EQ(MOJO_RESULT_OK, MojoCreateDataPipe(nullptr, &p, &c[i]));
MojoClose(p);
}
RUN_CHILD_ON_PIPE(HandlePingPong, h)
for (size_t i = 0; i < kPingPongIterations; i++) {
WriteMessageWithHandles(h, "", c, kPingPongHandlesPerIteration);
ReadMessageWithHandles(h, c, kPingPongHandlesPerIteration);
}
WriteMessage(h, "quit", 4);
END_CHILD()
for (size_t i = 0; i < kPingPongHandlesPerIteration; ++i)
MojoClose(c[i]);
}
// This test is flaky: http://crbug.com/585784
TEST_F(MessagePipeTest, DISABLED_DataPipeProducerHandlePingPong) {
MojoHandle p[kPingPongHandlesPerIteration], c;
for (size_t i = 0; i < kPingPongHandlesPerIteration; ++i) {
EXPECT_EQ(MOJO_RESULT_OK, MojoCreateDataPipe(nullptr, &p[i], &c));
MojoClose(c);
}
RUN_CHILD_ON_PIPE(HandlePingPong, h)
for (size_t i = 0; i < kPingPongIterations; i++) {
WriteMessageWithHandles(h, "", p, kPingPongHandlesPerIteration);
ReadMessageWithHandles(h, p, kPingPongHandlesPerIteration);
}
WriteMessage(h, "quit", 4);
END_CHILD()
for (size_t i = 0; i < kPingPongHandlesPerIteration; ++i)
MojoClose(p[i]);
}
#if defined(OS_ANDROID)
// Android multi-process tests are not executing the new process. This is flaky.
#define MAYBE_SharedBufferHandlePingPong DISABLED_SharedBufferHandlePingPong
#else
#define MAYBE_SharedBufferHandlePingPong SharedBufferHandlePingPong
#endif
TEST_F(MessagePipeTest, MAYBE_SharedBufferHandlePingPong) {
MojoHandle buffers[kPingPongHandlesPerIteration];
for (size_t i = 0; i <kPingPongHandlesPerIteration; ++i)
EXPECT_EQ(MOJO_RESULT_OK, MojoCreateSharedBuffer(nullptr, 1, &buffers[i]));
RUN_CHILD_ON_PIPE(HandlePingPong, h)
for (size_t i = 0; i < kPingPongIterations; i++) {
WriteMessageWithHandles(h, "", buffers, kPingPongHandlesPerIteration);
ReadMessageWithHandles(h, buffers, kPingPongHandlesPerIteration);
}
WriteMessage(h, "quit", 4);
END_CHILD()
for (size_t i = 0; i < kPingPongHandlesPerIteration; ++i)
MojoClose(buffers[i]);
}
#endif // !defined(OS_IOS)
TEST_F(FuseMessagePipeTest, Basic) {
// Test that we can fuse pipes and they still work.
MojoHandle a, b, c, d;
CreateMessagePipe(&a, &b);
CreateMessagePipe(&c, &d);
EXPECT_EQ(MOJO_RESULT_OK, MojoFuseMessagePipes(b, c));
// Handles b and c should be closed.
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(b));
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(c));
const std::string kTestMessage1 = "Hello, world!";
const std::string kTestMessage2 = "Goodbye, world!";
WriteMessage(a, kTestMessage1);
EXPECT_EQ(kTestMessage1, ReadMessage(d));
WriteMessage(d, kTestMessage2);
EXPECT_EQ(kTestMessage2, ReadMessage(a));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(a));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(d));
}
TEST_F(FuseMessagePipeTest, FuseAfterPeerWrite) {
// Test that messages written before fusion are eventually delivered.
MojoHandle a, b, c, d;
CreateMessagePipe(&a, &b);
CreateMessagePipe(&c, &d);
const std::string kTestMessage1 = "Hello, world!";
const std::string kTestMessage2 = "Goodbye, world!";
WriteMessage(a, kTestMessage1);
WriteMessage(d, kTestMessage2);
EXPECT_EQ(MOJO_RESULT_OK, MojoFuseMessagePipes(b, c));
// Handles b and c should be closed.
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(b));
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(c));
EXPECT_EQ(kTestMessage1, ReadMessage(d));
EXPECT_EQ(kTestMessage2, ReadMessage(a));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(a));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(d));
}
TEST_F(FuseMessagePipeTest, NoFuseAfterWrite) {
// Test that a pipe endpoint which has been written to cannot be fused.
MojoHandle a, b, c, d;
CreateMessagePipe(&a, &b);
CreateMessagePipe(&c, &d);
WriteMessage(b, "shouldn't have done that!");
EXPECT_EQ(MOJO_RESULT_FAILED_PRECONDITION, MojoFuseMessagePipes(b, c));
// Handles b and c should be closed.
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(b));
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(c));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(a));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(d));
}
TEST_F(FuseMessagePipeTest, NoFuseSelf) {
// Test that a pipe's own endpoints can't be fused together.
MojoHandle a, b;
CreateMessagePipe(&a, &b);
EXPECT_EQ(MOJO_RESULT_FAILED_PRECONDITION, MojoFuseMessagePipes(a, b));
// Handles a and b should be closed.
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(a));
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(b));
}
TEST_F(FuseMessagePipeTest, FuseInvalidArguments) {
MojoHandle a, b, c, d;
CreateMessagePipe(&a, &b);
CreateMessagePipe(&c, &d);
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(b));
// Can't fuse an invalid handle.
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoFuseMessagePipes(b, c));
// Handle c should be closed.
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(c));
// Can't fuse a non-message pipe handle.
MojoHandle e, f;
CreateDataPipe(&e, &f, 16);
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoFuseMessagePipes(e, d));
// Handles d and e should be closed.
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(d));
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(e));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(a));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(f));
}
TEST_F(FuseMessagePipeTest, FuseAfterPeerClosure) {
// Test that peer closure prior to fusion can still be detected after fusion.
MojoHandle a, b, c, d;
CreateMessagePipe(&a, &b);
CreateMessagePipe(&c, &d);
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(a));
EXPECT_EQ(MOJO_RESULT_OK, MojoFuseMessagePipes(b, c));
// Handles b and c should be closed.
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(b));
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(c));
EXPECT_EQ(MOJO_RESULT_OK, MojoWait(d, MOJO_HANDLE_SIGNAL_PEER_CLOSED,
MOJO_DEADLINE_INDEFINITE, nullptr));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(d));
}
TEST_F(FuseMessagePipeTest, FuseAfterPeerWriteAndClosure) {
// Test that peer write and closure prior to fusion still results in the
// both message arrival and awareness of peer closure.
MojoHandle a, b, c, d;
CreateMessagePipe(&a, &b);
CreateMessagePipe(&c, &d);
const std::string kTestMessage = "ayyy lmao";
WriteMessage(a, kTestMessage);
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(a));
EXPECT_EQ(MOJO_RESULT_OK, MojoFuseMessagePipes(b, c));
// Handles b and c should be closed.
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(b));
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoClose(c));
EXPECT_EQ(kTestMessage, ReadMessage(d));
EXPECT_EQ(MOJO_RESULT_OK, MojoWait(d, MOJO_HANDLE_SIGNAL_PEER_CLOSED,
MOJO_DEADLINE_INDEFINITE, nullptr));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(d));
}
} // namespace
} // namespace edk
} // namespace mojo
| 35.416283 | 80 | 0.709967 | bopopescu |
bfb06db7d0f418cfdec185e4f34d0a8a87200aeb | 8,935 | cpp | C++ | CapabilityAgents/PlaybackController/src/PlaybackCommand.cpp | AndersSpringborg/avs-device-sdk | 8e77a64c5be5a0b7b19c53549d91b0c45c37df3a | [
"Apache-2.0"
] | 1,272 | 2017-08-17T04:58:05.000Z | 2022-03-27T03:28:29.000Z | CapabilityAgents/PlaybackController/src/PlaybackCommand.cpp | AndersSpringborg/avs-device-sdk | 8e77a64c5be5a0b7b19c53549d91b0c45c37df3a | [
"Apache-2.0"
] | 1,948 | 2017-08-17T03:39:24.000Z | 2022-03-30T15:52:41.000Z | CapabilityAgents/PlaybackController/src/PlaybackCommand.cpp | AndersSpringborg/avs-device-sdk | 8e77a64c5be5a0b7b19c53549d91b0c45c37df3a | [
"Apache-2.0"
] | 630 | 2017-08-17T06:35:59.000Z | 2022-03-29T04:04:44.000Z | /*
* Copyright Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include <rapidjson/error/en.h>
#include "PlaybackController/PlaybackCommand.h"
namespace alexaClientSDK {
namespace capabilityAgents {
namespace playbackController {
using namespace avsCommon::avs;
using namespace rapidjson;
/// String to identify log entries originating from this file.
static const std::string TAG("PlaybackCommand");
/**
* Create a LogEntry using this file's TAG and the specified event string.
*
* @param The event string for this @c LogEntry.
*/
#define LX(event) utils::logger::LogEntry(TAG, event)
// PlaybackController interface 1.1 buttons event name.
static const std::string BUTTON_COMMAND_EVENT_NAME = "ButtonCommandIssued";
// PlaybackController interface 1.1 toggles event name.
static const std::string TOGGLE_COMMAND_EVENT_NAME = "ToggleCommandIssued";
// String to identify the AVS action SELECT string in @c ToggleCommandIssued event.
static const std::string PLAYBACK_TOGGLE_ACTION_SELECT = "SELECT";
// String to identify the AVS action DESELECT string in @c ToggleCommandIssued event.
static const std::string PLAYBACK_TOGGLE_ACTION_DESELECT = "DESELECT";
// String to identify the AVS name SHUFFLE string in @c ToggleCommandIssued event.
static const std::string PLAYBACK_TOGGLE_NAME_SHUFFLE = "SHUFFLE";
// String to identify the AVS name LOOP string in @c ToggleCommandIssued event.
static const std::string PLAYBACK_TOGGLE_NAME_LOOP = "LOOP";
// String to identify the AVS name REPEAT string in @c ToggleCommandIssued event.
static const std::string PLAYBACK_TOGGLE_NAME_REPEAT = "REPEAT";
// String to identify the AVS name THUMBS_UP string in @c ToggleCommandIssued event.
static const std::string PLAYBACK_TOGGLE_NAME_THUMBSUP = "THUMBSUP";
// String to identify the AVS name THUMBS_DOWN string in @c ToggleCommandIssued event.
static const std::string PLAYBACK_TOGGLE_NAME_THUMBSDOWN = "THUMBSDOWN";
// String to identify the AVS name UNKNOWN string in any event
static const std::string PLAYBACK_NAME_UNKNOWN = "UNKNOWN";
// event payload key for playback controller 1.1 buttons and toggles
static const std::string PLAYBACK_CONTROLLER_EVENT_NAME_KEY = "name";
// event payload key for playback controller 1.1 toggles
static const std::string PLAYBACK_CONTROLLER_EVENT_ACTION_KEY = "action";
// json empty object
static const std::string JSON_EMPTY_PAYLOAD = "{}";
// json open bracket
static const std::string JSON_BEGIN = "{\"";
// json colon sepeartor
static const std::string JSON_COLON = "\": \"";
// json comma seperator
static const std::string JSON_COMMA = "\", \"";
// json end bracket
static const std::string JSON_END = "\"}";
// In Playback Controller 1.0 -> 1.1, different button commands have different event payloads
/// @c PlayCommandIssued event.
static const ButtonCommand_v1_0 g_playButton_v1_0 = ButtonCommand_v1_0("PlayCommandIssued");
/// @c PauseCommandIssued event.
static const ButtonCommand_v1_0 g_pauseButton_v1_0 = ButtonCommand_v1_0("PauseCommandIssued");
/// @c NextCommandIssued event.
static const ButtonCommand_v1_0 g_nextButton_v1_0 = ButtonCommand_v1_0("NextCommandIssued");
/// @c PreviousCommandIssued event.
static const ButtonCommand_v1_0 g_previousButton_v1_0 = ButtonCommand_v1_0("PreviousCommandIssued");
/// @c SKIPFORWARD command.
static const ButtonCommand_v1_1 g_skipForwardButton_v1_0 = ButtonCommand_v1_1("SKIPFORWARD");
/// @c SKIPBACKWARD command.
static const ButtonCommand_v1_1 g_skipBackwardButton_v1_0 = ButtonCommand_v1_1("SKIPBACKWARD");
/// Unknown command
static const ButtonCommand_v1_1 g_unknownButton_v1_0 = ButtonCommand_v1_1(PLAYBACK_NAME_UNKNOWN);
/// @c SHUFFLE command with action = @c SELECT
static const ToggleCommand g_shuffleSelectToggle = ToggleCommand(PLAYBACK_TOGGLE_NAME_SHUFFLE, true);
/// @c SHUFFLE command with action = @c DESELECT
static const ToggleCommand g_shuffleDeselectToggle = ToggleCommand(PLAYBACK_TOGGLE_NAME_SHUFFLE, false);
/// @c LOOP command with action = @c SELECT
static const ToggleCommand g_loopSelectToggle = ToggleCommand(PLAYBACK_TOGGLE_NAME_LOOP, true);
/// @c LOOP command with action = @c DESELECT
static const ToggleCommand g_loopDeselectToggle = ToggleCommand(PLAYBACK_TOGGLE_NAME_LOOP, false);
/// @c REPEAT command with action = @c SELECT
static const ToggleCommand g_repeatSelectToggle = ToggleCommand(PLAYBACK_TOGGLE_NAME_REPEAT, true);
/// @c REPEAT command with action = @c DESELECT
static const ToggleCommand g_repeatDeselectToggle = ToggleCommand(PLAYBACK_TOGGLE_NAME_REPEAT, false);
/// @c THUMBSUP command with action = @c SELECT
static const ToggleCommand g_thumbsUpSelectToggle = ToggleCommand(PLAYBACK_TOGGLE_NAME_THUMBSUP, true);
/// @c THUMBSUP command with action = @c DESELECT
static const ToggleCommand g_thumbsUpDeselectToggle = ToggleCommand(PLAYBACK_TOGGLE_NAME_THUMBSUP, false);
/// @c THUMBSDOWN command with action = @c SELECT
static const ToggleCommand g_thumbsDownSelectToggle = ToggleCommand(PLAYBACK_TOGGLE_NAME_THUMBSDOWN, true);
/// @c THUMBSDOWN command with action = @c DESELECT
static const ToggleCommand g_thumbsDownDeselectToggle = ToggleCommand(PLAYBACK_TOGGLE_NAME_THUMBSDOWN, false);
/// Unknown toggle
static const ToggleCommand g_unknownToggle = ToggleCommand(PLAYBACK_NAME_UNKNOWN, false);
PlaybackCommand::PlaybackCommand(const std::string& name) : m_name(name) {
}
const PlaybackCommand& PlaybackCommand::buttonToCommand(PlaybackButton button) {
switch (button) {
case PlaybackButton::PLAY:
return g_playButton_v1_0;
case PlaybackButton::PAUSE:
return g_pauseButton_v1_0;
case PlaybackButton::NEXT:
return g_nextButton_v1_0;
case PlaybackButton::PREVIOUS:
return g_previousButton_v1_0;
case PlaybackButton::SKIP_FORWARD:
return g_skipForwardButton_v1_0;
case PlaybackButton::SKIP_BACKWARD:
return g_skipBackwardButton_v1_0;
}
return g_unknownButton_v1_0;
}
const PlaybackCommand& PlaybackCommand::toggleToCommand(PlaybackToggle toggle, bool state) {
switch (toggle) {
case PlaybackToggle::LOOP:
return (state ? g_loopSelectToggle : g_loopDeselectToggle);
case PlaybackToggle::REPEAT:
return (state ? g_repeatSelectToggle : g_repeatDeselectToggle);
case PlaybackToggle ::SHUFFLE:
return (state ? g_shuffleSelectToggle : g_shuffleDeselectToggle);
case PlaybackToggle::THUMBS_DOWN:
return (state ? g_thumbsDownSelectToggle : g_thumbsDownDeselectToggle);
case PlaybackToggle::THUMBS_UP:
return (state ? g_thumbsUpSelectToggle : g_thumbsUpDeselectToggle);
}
return g_unknownToggle;
}
std::string PlaybackCommand::toString() const {
return m_name;
}
std::string ToggleCommand::toString() const {
return m_name + "_" + getActionString();
}
std::ostream& operator<<(std::ostream& stream, const PlaybackCommand& command) {
return stream << command.toString();
}
ButtonCommand_v1_0::ButtonCommand_v1_0(const std::string& name) : PlaybackCommand(name) {
}
std::string ButtonCommand_v1_0::getEventName() const {
return m_name;
}
std::string ButtonCommand_v1_0::getEventPayload() const {
return JSON_EMPTY_PAYLOAD;
}
ButtonCommand_v1_1::ButtonCommand_v1_1(const std::string& name) : PlaybackCommand(name) {
}
std::string ButtonCommand_v1_1::getEventName() const {
return BUTTON_COMMAND_EVENT_NAME;
}
std::string ButtonCommand_v1_1::getEventPayload() const {
return JSON_BEGIN + PLAYBACK_CONTROLLER_EVENT_NAME_KEY + JSON_COLON + m_name + JSON_END;
}
ToggleCommand::ToggleCommand(const std::string& name, bool action) : PlaybackCommand(name), m_action(action) {
}
std::string ToggleCommand::getEventName() const {
return TOGGLE_COMMAND_EVENT_NAME;
}
std::string ToggleCommand::getEventPayload() const {
return JSON_BEGIN + PLAYBACK_CONTROLLER_EVENT_NAME_KEY + JSON_COLON + m_name + JSON_COMMA +
PLAYBACK_CONTROLLER_EVENT_ACTION_KEY + JSON_COLON + getActionString() + JSON_END;
}
std::string ToggleCommand::getActionString() const {
return (m_action ? PLAYBACK_TOGGLE_ACTION_SELECT : PLAYBACK_TOGGLE_ACTION_DESELECT);
}
} // namespace playbackController
} // namespace capabilityAgents
} // namespace alexaClientSDK
| 37.542017 | 110 | 0.769782 | AndersSpringborg |
bfb0c309a82246f243c3b88be364e76a9130da04 | 1,547 | cpp | C++ | 72.cpp | machinecc/leetcode | 32bbf6c1f9124049c046a235c85b14ca9168daa8 | [
"MIT"
] | null | null | null | 72.cpp | machinecc/leetcode | 32bbf6c1f9124049c046a235c85b14ca9168daa8 | [
"MIT"
] | null | null | null | 72.cpp | machinecc/leetcode | 32bbf6c1f9124049c046a235c85b14ca9168daa8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <string>
#include <unordered_set>
#include <vector>
#include <algorithm>
#include <climits>
#include <stack>
#include <sstream>
#include <numeric>
#include <unordered_map>
using namespace std;
class Solution {
public:
int minDistance(string word1, string word2) {
if (word1.size() > word2.size())
swap(word1, word2);
int n = word1.size();
int m = word2.size();
//cout << word1 << " " << word2 << endl;
//cout << n << " " << m << endl;
if (m == 0)
return 0;
int** f = new int*[n+1];
for (int i = 0; i <= n; ++ i)
f[i] = new int[m+1];
for (int j = 0; j <= m; ++ j)
f[0][j] = j;
for (int i = 0; i <= n; ++ i)
f[i][0] = i;
for (int i = 1; i <= n; ++ i) {
for (int j = 1; j <= m; ++ j) {
if (word1[i-1] == word2[j-1]) {
f[i][j] = f[i-1][j-1];
}
else {
f[i][j] = min( min(f[i-1][j-1], f[i-1][j]), f[i][j-1] ) + 1;
//cout << " i = " << i << " j = " << j << " f[i][j] = " << f[i][j] << endl;
}
}
}
int mindist = INT_MAX;
for (int j = 0; j <= m; ++ j) {
mindist = min(mindist, f[n][j] + m - j);
}
for (int i = 0; i <= n; ++ i)
delete [] f[i];
delete [] f;
return mindist;
}
};
int main() {
cout << Solution().minDistance("aihfk","hk") << endl;
return 0;
} | 19.3375 | 93 | 0.405301 | machinecc |
bfb142a1dd1886deb273bc875837356c2354d332 | 1,132 | cpp | C++ | uva/11747.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | 3 | 2018-01-08T02:52:51.000Z | 2021-03-03T01:08:44.000Z | uva/11747.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | null | null | null | uva/11747.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | 1 | 2020-08-13T18:07:35.000Z | 2020-08-13T18:07:35.000Z | #include <bits/stdc++.h>
#define le 10004
using namespace std;
int p[le];
struct edge{
int u, v, w;
};
bool comp(edge a, edge b){
return a.w < b.w;
}
int fnc(int a){
if(p[a] == a) return a;
p[a] = fnc(p[a]);
return p[a];
}
vector<edge> v;
vector<int> ve;
void mst(){
sort(v.begin(), v.end(), comp);
for(int i = 0; i < (int)v.size(); i++){
int a = fnc(v[i].u);
int b = fnc(v[i].v);
if(a != b) p[b] = a;
else ve.push_back(v[i].w);
}
}
int main(){
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int n, m, a, b, c;
while(scanf("%d %d", &n, &m) != EOF && n){
ve.clear();
for(int i = 0; i < n; p[i] = i, i++);
edge eg;
for(int i = 0; i < m; i++){
scanf("%d %d %d", &a, &b, &c);
eg.u = a;
eg.v = b;
eg.w = c;
v.push_back(eg);
}
mst();
if(ve.size() == 0) printf("forest\n");
else{
sort(ve.begin(), ve.end());
for(int i = 0; i < ve.size() - 1; printf("%d ", ve[i]), i++);
printf("%d\n", ve[ve.size() - 1]);
}
v.clear();
}
return 0;
}
| 21.358491 | 68 | 0.437279 | cosmicray001 |
bfb245ebe64e3492f568d038fde248756b0c25f6 | 62 | cpp | C++ | libboost-proto/tests/basics/driver.cpp | build2-packaging/boost | 203d505dd3ba04ea50785bc8b247a295db5fc718 | [
"BSL-1.0"
] | 4 | 2021-02-23T11:24:33.000Z | 2021-09-11T20:10:46.000Z | libboost-proto/tests/basics/driver.cpp | build2-packaging/boost | 203d505dd3ba04ea50785bc8b247a295db5fc718 | [
"BSL-1.0"
] | null | null | null | libboost-proto/tests/basics/driver.cpp | build2-packaging/boost | 203d505dd3ba04ea50785bc8b247a295db5fc718 | [
"BSL-1.0"
] | null | null | null | #include <boost/proto/proto.hpp>
int
main ()
{
return 0;
}
| 7.75 | 32 | 0.629032 | build2-packaging |
bfb8c6398e002eb181771ab525fa372dd4129c84 | 1,322 | cpp | C++ | Scripting/Source/ScriptManager.cpp | jordanlittlefair/Foundation | ab737b933ea5bbe2be76133ed78c8e882f072fd0 | [
"BSL-1.0"
] | null | null | null | Scripting/Source/ScriptManager.cpp | jordanlittlefair/Foundation | ab737b933ea5bbe2be76133ed78c8e882f072fd0 | [
"BSL-1.0"
] | null | null | null | Scripting/Source/ScriptManager.cpp | jordanlittlefair/Foundation | ab737b933ea5bbe2be76133ed78c8e882f072fd0 | [
"BSL-1.0"
] | null | null | null | #include "../Include/ScriptManager.hpp"
#include "../Include/Script.hpp"
using namespace Fnd::Scripting;
ScriptManager::ScriptManager():
_entity_system(nullptr),
_input_handler(nullptr)
{
}
void ScriptManager::AddScript( unsigned int entity_id, Script* script )
{
_entities[entity_id].entity_id = entity_id;
_entities[entity_id].scripts.push_back(std::shared_ptr<Script>(script));
}
void ScriptManager::SetEntitySystem( Fnd::EntitySystem::EntitySystem* entity_system )
{
_entity_system = entity_system;
}
void ScriptManager::SetInputHandler( Fnd::Input::IInput* input_handler )
{
_input_handler = input_handler;
}
void ScriptManager::Update( const Fnd::CommonResources::FrameData& frame_data )
{
for ( auto entity_iter = _entities.begin(); entity_iter != _entities.end(); ++entity_iter )
{
for ( auto script_iter = entity_iter->second.scripts.begin(); script_iter != entity_iter->second.scripts.end(); ++script_iter )
{
// Doesn't yet handle adding/removing entities/components.
script_iter->get()->OnUpdate( frame_data );
}
}
}
Fnd::EntitySystem::EntitySystem* ScriptManager::GetEntitySystem()
{
return _entity_system;
}
Fnd::Input::IInput* ScriptManager::GetInputHandler()
{
return _input_handler;
}
ScriptManager::~ScriptManager()
{
} | 24.943396 | 130 | 0.721634 | jordanlittlefair |
bfba0c83f795186379ebfa623bfc563b934b1d63 | 388 | cpp | C++ | 2020-12-01/area.cpp | pufe/programa | 7f79566597446e9e39222e6c15fa636c3dd472bb | [
"MIT"
] | 2 | 2020-12-12T00:02:40.000Z | 2021-04-21T19:49:59.000Z | 2020-12-01/area.cpp | pufe/programa | 7f79566597446e9e39222e6c15fa636c3dd472bb | [
"MIT"
] | null | null | null | 2020-12-01/area.cpp | pufe/programa | 7f79566597446e9e39222e6c15fa636c3dd472bb | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cmath>
const double pi = 4*atan(1);
int main() {
double d = sqrt(3) - 1;
double cc = pi/12 - sin(pi/12)*cos(pi/12);
double a1 = d*d/2.0 + 4*cc;
double a3 = 8*(1/2.0 - sqrt(3)/8.0 - pi/12);
double a2 = 1-a1-a3;
double f;
while(scanf(" %lf", &f)==1) {
printf("%.3lf %.3lf %.3lf\n", a1*f*f, a2*f*f, a3*f*f);
}
return 0;
}
| 21.555556 | 59 | 0.507732 | pufe |
bfbb5f214d1edbff97c28d8afab524374a29ea32 | 2,577 | cpp | C++ | tools/utmostcp/src/utmostcp.cpp | denis-ryzhkov/antiques | 6a67bf606c1b49cc413df26bfdf00d392b605f88 | [
"MIT"
] | null | null | null | tools/utmostcp/src/utmostcp.cpp | denis-ryzhkov/antiques | 6a67bf606c1b49cc413df26bfdf00d392b605f88 | [
"MIT"
] | null | null | null | tools/utmostcp/src/utmostcp.cpp | denis-ryzhkov/antiques | 6a67bf606c1b49cc413df26bfdf00d392b605f88 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <stdio.h>
#include <io.h>
#include <string.h>
#define IN_FN argv[ 1 ]
#define OUT_FN argv[ 2 ]
#define SKIP_K argv[ 3 ]
#define INT64 __int64
int percents_c = 0;
INT64 in_size, byte_i, bads_c = 0, skip_k = 0, skip_c = 1;
int calc_percents_c() { return percents_c = ( byte_i * 100 ) / in_size; }
void print_status() {
printf( "%i%% - %iB", calc_percents_c(), bads_c );
if ( skip_c > 1 ) printf( " >>> %iB", skip_c );
else printf( "\t\t\t" );
printf( "\015" );
fflush( stdout );
}
int main( int argc, char** argv ) {
if ( ( argc != 3 ) && ( argc != 4 ) ) puts( "utmostcp 1.1 2002-01-07\nCopyright (C) 2003 Denis Ryzhkov ( Creon ) mail@creon.cjb.net\ndoes: utmost copy of source file to destination file or folder\nneed when: for example MPEG from bad CD\ncomment: almost as slow as effective\nusage: utmostcp <source> <destination> [<skip-coefficient>]" );
else {
FILE* in_f = fopen( IN_FN, "rb" );
if ( !in_f ) printf( "can't read file \"%s\"\n", IN_FN );
else {
char out_fn[ _MAX_PATH ];
strcpy( out_fn, OUT_FN );
if ( out_fn[ strlen( out_fn ) - 1 ] == '\\' ) strcat( out_fn, IN_FN );
FILE* out_f = fopen( out_fn, "wb" );
if ( !out_f ) printf( "can't write file \"%s\"\n", out_fn );
else {
if ( argc == 4 ) skip_k = atoi( SKIP_K );
if ( skip_k < 0 ) skip_k = 0;
bool ok;
in_size = _filelengthi64( _fileno( in_f ) );
int percents_old_c = 0;
print_status();
for ( byte_i = 0; byte_i < in_size; byte_i++ ) {
int buf = fgetc( in_f );
if ( buf != EOF ) {
if ( !ok ) { // get out of bads
ok = true;
skip_c = 1;
print_status();
} // eo get out of bads
fputc( buf, out_f );
} else { // skip bads
if ( !ok && skip_k ) { // use skip_k
skip_c *= skip_k;
for ( INT64 skip_i = 0; ( skip_i < skip_c ) && ( byte_i < in_size ); skip_i++, byte_i++, bads_c++ )
fputc( 0, out_f );
} else { // no skip_k
ok = false;
fputc( 0, out_f );
bads_c++;
} // eo no skip_k
print_status();
fseek( in_f, byte_i + 1, SEEK_SET );
} // eo skip bads
if ( calc_percents_c() != percents_old_c ) {
percents_old_c = percents_c;
print_status();
} // eo calc_percents_c() != percents_old_c
fflush( out_f );
} // eo for byte_i
fclose( out_f );
print_status();
puts( "\n" );
} // eo ok out_f
fclose( in_f );
} // eo ok in_f
} // eo argc != 1
return 0;
} // eo main
| 32.620253 | 341 | 0.54676 | denis-ryzhkov |
bfbccac119a001b8a798ed189e936ad82ee7c40d | 3,329 | cpp | C++ | thirdparty/graph-tools-master/src/graphalign/KmerIndexOperations.cpp | AlesMaver/ExpansionHunter | 274903d26a33cfbc546aac98c85bbfe51701fd3b | [
"BSL-1.0",
"Apache-2.0"
] | 122 | 2017-01-06T16:19:31.000Z | 2022-03-08T00:05:50.000Z | thirdparty/graph-tools-master/src/graphalign/KmerIndexOperations.cpp | AlesMaver/ExpansionHunter | 274903d26a33cfbc546aac98c85bbfe51701fd3b | [
"BSL-1.0",
"Apache-2.0"
] | 90 | 2017-01-04T00:23:34.000Z | 2022-02-27T12:55:52.000Z | thirdparty/graph-tools-master/src/graphalign/KmerIndexOperations.cpp | AlesMaver/ExpansionHunter | 274903d26a33cfbc546aac98c85bbfe51701fd3b | [
"BSL-1.0",
"Apache-2.0"
] | 35 | 2017-03-02T13:39:58.000Z | 2022-03-30T17:34:11.000Z | //
// GraphTools library
// Copyright 2017-2019 Illumina, Inc.
// All rights reserved.
//
// Author: Egor Dolzhenko <edolzhenko@illumina.com>,
// Peter Krusche <pkrusche@illumina.com>
//
// 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 "graphalign/KmerIndexOperations.hh"
#include <list>
#include <boost/algorithm/string.hpp>
#include "graphutils/SequenceOperations.hh"
using std::list;
using std::string;
namespace graphtools
{
list<string> extractKmersFromAllPositions(const string& sequence, int32_t kmer_len)
{
list<string> kmers;
for (size_t pos = 0; pos + kmer_len <= sequence.length(); ++pos)
{
string kmer = sequence.substr(pos, static_cast<std::size_t>(kmer_len));
boost::to_upper(kmer);
kmers.push_back(kmer);
}
return kmers;
}
int32_t countKmerMatches(const KmerIndex& kmer_index, const std::string& seq)
{
const list<string> kmers = extractKmersFromAllPositions(seq, kmer_index.kmerLength());
int32_t num_kmer_matches = 0;
for (const string& kmer : kmers)
{
if (kmer_index.numPaths(kmer) != 0)
{
++num_kmer_matches;
}
}
return num_kmer_matches;
}
bool checkIfForwardOriented(const KmerIndex& kmer_index, const std::string& sequence)
{
const int32_t num_forward_matches = countKmerMatches(kmer_index, sequence);
const int32_t num_revcomp_matches = countKmerMatches(kmer_index, reverseComplement(sequence));
return num_forward_matches >= num_revcomp_matches;
}
/**
* Find minimum kmer length that covers each node with a unique kmer
* @param graph a graph
* @param min_unique_kmers_per_edge min number of unique kmers to cover each edge
* @param min_unique_kmers_per_node min number of unique kmers to cover each node
* @return
*/
int findMinCoveringKmerLength(Graph const* graph, size_t min_unique_kmers_per_edge, size_t min_unique_kmers_per_node)
{
for (int32_t k = 10; k < 64; ++k)
{
KmerIndex index(*graph, k);
bool any_below = false;
for (NodeId node_id = 0; node_id != graph->numNodes(); ++node_id)
{
if (index.numUniqueKmersOverlappingNode(node_id) < min_unique_kmers_per_node)
{
any_below = true;
break;
}
// this will enumerate all edges
for (const auto succ : graph->successors(node_id))
{
if (index.numUniqueKmersOverlappingEdge(node_id, succ) < min_unique_kmers_per_edge)
{
any_below = true;
break;
}
}
if (any_below)
{
break;
}
}
if (any_below)
{
continue;
}
return k;
}
return -1;
}
}
| 29.201754 | 117 | 0.645539 | AlesMaver |
bfbe5bbdba6aea439903878b04d4f033b58c9ac6 | 1,395 | cpp | C++ | beringei/lib/tests/CaseUtilsTest.cpp | pidb/Gorilla | 75c3002b179d99c8709323d605e7d4b53484035c | [
"BSD-3-Clause"
] | 2,780 | 2016-12-22T19:25:26.000Z | 2018-05-21T11:29:42.000Z | beringei/lib/tests/CaseUtilsTest.cpp | pidb/Gorilla | 75c3002b179d99c8709323d605e7d4b53484035c | [
"BSD-3-Clause"
] | 57 | 2016-12-23T09:22:18.000Z | 2018-05-04T06:26:48.000Z | beringei/lib/tests/CaseUtilsTest.cpp | pidb/Gorilla | 75c3002b179d99c8709323d605e7d4b53484035c | [
"BSD-3-Clause"
] | 254 | 2016-12-22T20:53:12.000Z | 2018-05-16T06:14:10.000Z | /**
* Copyright (c) 2016-present, 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 <gtest/gtest.h>
#include <unordered_map>
#include <folly/String.h>
#include "TestKeyList.h"
#include "beringei/lib/CaseUtils.h"
using namespace ::testing;
using namespace facebook::gorilla;
TEST(CaseUtilsTest, CaseEq) {
CaseEq eq;
EXPECT_TRUE(eq("foo", "FoO"));
EXPECT_TRUE(eq("foo", "foo"));
EXPECT_TRUE(eq("FOO", "foO"));
EXPECT_FALSE(eq("foo", "bar"));
EXPECT_FALSE(eq("foo", "b"));
}
TEST(CaseUtilsTest, CaseHash) {
CaseHash hash;
EXPECT_EQ(hash("foo"), hash("FoO"));
EXPECT_EQ(hash("BaR"), hash("bAr"));
EXPECT_NE(hash("foo"), hash("bar"));
}
const static int kNumHashes = 10000000;
const static int kKeyListSize = 400000;
TEST(CaseUtilsTest, Perf) {
CaseHash hsh;
TestKeyList keyList(kKeyListSize, 10);
size_t x = 0;
for (int i = 0; i < kNumHashes; i++) {
x ^= hsh(keyList.testStr(i));
}
LOG(INFO) << x;
}
TEST(CaseUtilsTest, PerfComparison) {
std::hash<std::string> hsh;
TestKeyList keyList(kKeyListSize);
size_t x = 0;
for (int i = 0; i < kNumHashes; i++) {
x ^= hsh(keyList.testStr(i));
}
LOG(INFO) << x;
}
| 23.644068 | 78 | 0.666667 | pidb |
bfbf6581565cfade6c043509c1ae65d3e9c0233b | 32,185 | cpp | C++ | Engine/source/renderInstance/renderProbeMgr.cpp | DraconicEnt/Torque3D | b351ad38f8df8c297980941f610d72a8794633ea | [
"MIT"
] | 417 | 2020-06-01T15:55:15.000Z | 2022-03-31T12:50:51.000Z | Engine/source/renderInstance/renderProbeMgr.cpp | Ashry00/Torque3D | 33e3e41c8b7eb41c743a589558bc21302207ef97 | [
"MIT"
] | 186 | 2020-06-02T19:12:39.000Z | 2022-02-15T02:22:27.000Z | Engine/source/renderInstance/renderProbeMgr.cpp | Ashry00/Torque3D | 33e3e41c8b7eb41c743a589558bc21302207ef97 | [
"MIT"
] | 84 | 2020-06-01T15:54:44.000Z | 2022-03-24T13:52:59.000Z | //-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "renderProbeMgr.h"
#include "console/consoleTypes.h"
#include "scene/sceneObject.h"
#include "materials/materialManager.h"
#include "scene/sceneRenderState.h"
#include "math/util/sphereMesh.h"
#include "math/util/matrixSet.h"
#include "materials/processedMaterial.h"
#include "renderInstance/renderDeferredMgr.h"
#include "math/mPolyhedron.impl.h"
#include "gfx/gfxTransformSaver.h"
#include "lighting/advanced/advancedLightBinManager.h" //for ssao
#include "gfx/gfxDebugEvent.h"
#include "shaderGen/shaderGenVars.h"
#include "materials/shaderData.h"
#include "gfx/gfxTextureManager.h"
#include "scene/reflectionManager.h"
#include "postFx/postEffect.h"
#include "T3D/lighting/reflectionProbe.h"
#include "T3D/lighting/IBLUtilities.h"
//For our cameraQuery setup
#include "T3D/gameTSCtrl.h"
#include "T3D/Scene.h"
#define TORQUE_GFX_VISUAL_DEBUG //renderdoc debugging
IMPLEMENT_CONOBJECT(RenderProbeMgr);
ConsoleDocClass( RenderProbeMgr,
"@brief A render bin which uses object callbacks for rendering.\n\n"
"This render bin gathers object render instances and calls its delegate "
"method to perform rendering. It is used infrequently for specialized "
"scene objects which perform custom rendering.\n\n"
"@ingroup RenderBin\n" );
RenderProbeMgr *RenderProbeMgr::smProbeManager = NULL;
bool RenderProbeMgr::smRenderReflectionProbes = true;
F32 RenderProbeMgr::smMaxProbeDrawDistance = 100;
S32 RenderProbeMgr::smMaxProbesPerFrame = 8;
S32 QSORT_CALLBACK AscendingReflectProbeInfluence(const void* a, const void* b)
{
// Debug Profiling.
PROFILE_SCOPE(AdvancedLightBinManager_AscendingReflectProbeInfluence);
// Fetch asset definitions.
const ProbeRenderInst* pReflectProbeA = (*(ProbeRenderInst**)a);
const ProbeRenderInst* pReflectProbeB = (*(ProbeRenderInst**)b);
//sort by score
return pReflectProbeA->mScore - pReflectProbeB->mScore;
}
//
//
ProbeRenderInst::ProbeRenderInst() :
mIsEnabled(true),
mTransform(true),
mDirty(false),
mPriority(1.0f),
mScore(0.0f),
mPrefilterCubemap(NULL),
mIrradianceCubemap(NULL),
mRadius(1.0f),
mProbeRefOffset(0, 0, 0),
mProbeRefScale(1,1,1),
mAtten(0.0),
mCubemapIndex(0),
mProbeIdx(0),
mProbeShapeType(Box)
{
}
ProbeRenderInst::~ProbeRenderInst()
{
if (mPrefilterCubemap && mPrefilterCubemap.isValid())
{
mPrefilterCubemap.free();
}
if (mIrradianceCubemap && mIrradianceCubemap.isValid())
{
mIrradianceCubemap.free();
}
}
void ProbeRenderInst::set(const ProbeRenderInst *probeInfo)
{
mTransform = probeInfo->mTransform;
mPrefilterCubemap = probeInfo->mPrefilterCubemap;
mIrradianceCubemap = probeInfo->mIrradianceCubemap;
mRadius = probeInfo->mRadius;
mProbeShapeType = probeInfo->mProbeShapeType;
mBounds = probeInfo->mBounds;
mScore = probeInfo->mScore;
mAtten = probeInfo->mAtten;
}
//
//
ProbeShaderConstants::ProbeShaderConstants()
: mInit(false),
mShader(NULL),
mProbePositionSC(NULL),
mProbeRefPosSC(NULL),
mRefScaleSC(NULL),
mProbeConfigDataSC(NULL),
mProbeSpecularCubemapSC(NULL),
mProbeIrradianceCubemapSC(NULL),
mProbeCountSC(NULL),
mBRDFTextureMap(NULL),
mSkylightCubemapIdxSC(NULL),
mWorldToObjArraySC(NULL)
{
}
ProbeShaderConstants::~ProbeShaderConstants()
{
if (mShader.isValid())
{
mShader->getReloadSignal().remove(this, &ProbeShaderConstants::_onShaderReload);
mShader = NULL;
}
}
void ProbeShaderConstants::init(GFXShader* shader)
{
if (mShader.getPointer() != shader)
{
if (mShader.isValid())
mShader->getReloadSignal().remove(this, &ProbeShaderConstants::_onShaderReload);
mShader = shader;
mShader->getReloadSignal().notify(this, &ProbeShaderConstants::_onShaderReload);
}
//Reflection Probes
mProbePositionSC = shader->getShaderConstHandle(ShaderGenVars::probePosition);
mProbeRefPosSC = shader->getShaderConstHandle(ShaderGenVars::probeRefPos);
mRefScaleSC = shader->getShaderConstHandle(ShaderGenVars::refScale);
mWorldToObjArraySC = shader->getShaderConstHandle(ShaderGenVars::worldToObjArray);
mProbeConfigDataSC = shader->getShaderConstHandle(ShaderGenVars::probeConfigData);
mProbeSpecularCubemapSC = shader->getShaderConstHandle(ShaderGenVars::specularCubemapAR);
mProbeIrradianceCubemapSC = shader->getShaderConstHandle(ShaderGenVars::irradianceCubemapAR);
mProbeCountSC = shader->getShaderConstHandle(ShaderGenVars::probeCount);
mBRDFTextureMap = shader->getShaderConstHandle(ShaderGenVars::BRDFTextureMap);
mSkylightCubemapIdxSC = shader->getShaderConstHandle(ShaderGenVars::skylightCubemapIdx);
mInit = true;
}
bool ProbeShaderConstants::isValid()
{
if (mProbePositionSC->isValid() ||
mProbeConfigDataSC->isValid() ||
mRefScaleSC->isValid() ||
mProbeSpecularCubemapSC->isValid() ||
mProbeIrradianceCubemapSC->isValid())
return true;
return false;
}
void ProbeShaderConstants::_onShaderReload()
{
if (mShader.isValid())
init(mShader);
}
//
//
RenderProbeMgr::RenderProbeMgr()
: RenderBinManager(RenderPassManager::RIT_Probes, 1.0f, 1.0f),
mLastShader(nullptr),
mLastConstants(nullptr),
mProbesDirty(false),
mHasSkylight(false),
mSkylightCubemapIdx(-1),
mCubeMapCount(0),
mDefaultSkyLight(nullptr),
mUseHDRCaptures(true)
{
mEffectiveProbeCount = 0;
mMipCount = 0;
mProbeArrayEffect = nullptr;
smProbeManager = this;
mCubeMapCount = 0;
mCubeSlotCount = PROBE_ARRAY_SLOT_BUFFER_SIZE;
for (U32 i = 0; i < PROBE_MAX_COUNT; i++)
{
mCubeMapSlots[i] = false;
}
mPrefilterSize = 64;
mPrefilterMipLevels = mLog2(F32(mPrefilterSize)) + 1;
}
RenderProbeMgr::RenderProbeMgr(RenderInstType riType, F32 renderOrder, F32 processAddOrder)
: RenderBinManager(riType, renderOrder, processAddOrder)
{
mCubeMapCount = 0;
dMemset(mCubeMapSlots, false, sizeof(mCubeMapSlots));
mCubeSlotCount = PROBE_ARRAY_SLOT_BUFFER_SIZE;
mDefaultSkyLight = nullptr;
mEffectiveProbeCount = 0;
mHasSkylight = false;
mSkylightCubemapIdx = -1;
mLastConstants = nullptr;
mMipCount = 0;
mProbesDirty = false;
mUseHDRCaptures = true;
mPrefilterSize = 64;
mPrefilterMipLevels = mLog2(F32(mPrefilterSize)) + 1;
}
RenderProbeMgr::~RenderProbeMgr()
{
mLastShader = NULL;
mLastConstants = NULL;
for (ProbeConstantMap::Iterator i = mConstantLookup.begin(); i != mConstantLookup.end(); i++)
{
if (i->value)
SAFE_DELETE(i->value);
}
mConstantLookup.clear();
}
bool RenderProbeMgr::onAdd()
{
if (!Parent::onAdd())
return false;
mIrradianceArray = GFXCubemapArrayHandle(GFX->createCubemapArray());
mPrefilterArray = GFXCubemapArrayHandle(GFX->createCubemapArray());
//pre-allocate a few slots
mIrradianceArray->init(PROBE_ARRAY_SLOT_BUFFER_SIZE, PROBE_IRRAD_SIZE, PROBE_FORMAT);
mPrefilterArray->init(PROBE_ARRAY_SLOT_BUFFER_SIZE, PROBE_PREFILTER_SIZE, PROBE_FORMAT);
mCubeSlotCount = PROBE_ARRAY_SLOT_BUFFER_SIZE;
//create our own default default skylight
mDefaultSkyLight = new ProbeRenderInst;
mDefaultSkyLight->mProbeShapeType = ProbeRenderInst::Skylight;
mDefaultSkyLight->mIsEnabled = false;
String defaultIrradMapPath = GFXTextureManager::getDefaultIrradianceCubemapPath();
if (!mDefaultSkyLight->mIrradianceCubemap.set(defaultIrradMapPath))
{
Con::errorf("RenderProbeMgr::onAdd: Failed to load default irradiance cubemap");
return false;
}
String defaultPrefilterPath = GFXTextureManager::getDefaultPrefilterCubemapPath();
if (!mDefaultSkyLight->mPrefilterCubemap.set(defaultPrefilterPath))
{
Con::errorf("RenderProbeMgr::onAdd: Failed to load default prefilter cubemap");
return false;
}
String brdfTexturePath = GFXTextureManager::getBRDFTexturePath();
if (!mBRDFTexture.set(brdfTexturePath, &GFXTexturePersistentProfile, "BRDFTexture"))
{
Con::errorf("RenderProbeMgr::onAdd: Failed to load BRDF Texture");
return false;
}
return true;
}
void RenderProbeMgr::onRemove()
{
Parent::onRemove();
}
void RenderProbeMgr::initPersistFields()
{
Parent::initPersistFields();
}
void RenderProbeMgr::consoleInit()
{
Parent::consoleInit();
// Vars for debug rendering while the RoadEditor is open, only used if smEditorOpen is true.
Con::addVariable("$pref::maxProbeDrawDistance", TypeF32, &RenderProbeMgr::smMaxProbeDrawDistance, "Max distance for reflection probes to render.\n");
Con::addVariable("$pref::MaxProbesPerFrame", TypeS32, &RenderProbeMgr::smMaxProbesPerFrame, "Max number of Environment Probes that can be rendered per-frame.\n");
}
void RenderProbeMgr::registerProbe(ProbeRenderInst* newProbe)
{
//Can't have over the probe limit
if (mRegisteredProbes.size() + 1 >= PROBE_MAX_COUNT)
return;
mRegisteredProbes.push_back(newProbe);
newProbe->mProbeIdx = mRegisteredProbes.size() - 1;
const U32 cubeIndex = _findNextEmptyCubeSlot();
if (cubeIndex == INVALID_CUBE_SLOT)
{
Con::warnf("RenderProbeMgr::addProbe: Invalid cubemap slot.");
return;
}
//check if we need to resize the cubemap array
if (cubeIndex >= mCubeSlotCount)
{
//alloc temp array handles
GFXCubemapArrayHandle irr = GFXCubemapArrayHandle(GFX->createCubemapArray());
GFXCubemapArrayHandle prefilter = GFXCubemapArrayHandle(GFX->createCubemapArray());
irr->init(mCubeSlotCount + PROBE_ARRAY_SLOT_BUFFER_SIZE, PROBE_IRRAD_SIZE, PROBE_FORMAT);
prefilter->init(mCubeSlotCount + PROBE_ARRAY_SLOT_BUFFER_SIZE, PROBE_PREFILTER_SIZE, PROBE_FORMAT);
mIrradianceArray->copyTo(irr);
mPrefilterArray->copyTo(prefilter);
//assign the temp handles to the new ones, this will destroy the old ones as well
mIrradianceArray = irr;
mPrefilterArray = prefilter;
mCubeSlotCount += PROBE_ARRAY_SLOT_BUFFER_SIZE;
}
newProbe->mCubemapIndex = cubeIndex;
//mark cubemap slot as taken
mCubeMapSlots[cubeIndex] = true;
mCubeMapCount++;
#ifdef TORQUE_DEBUG
Con::warnf("RenderProbeMgr::registerProbe: Registered probe %u to cubeIndex %u", newProbe->mProbeIdx, cubeIndex);
#endif
mProbesDirty = true;
}
void RenderProbeMgr::unregisterProbe(U32 probeIdx)
{
//Mostly for consolidation, but also lets us sanity check or prep any other data we need for rendering this in one place at time of flagging for render
if (probeIdx >= mRegisteredProbes.size())
return;
if (mRegisteredProbes[probeIdx]->mCubemapIndex == INVALID_CUBE_SLOT)
return;
//mark cubemap slot as available now
mCubeMapSlots[mRegisteredProbes[probeIdx]->mCubemapIndex] = false;
mCubeMapCount--;
mRegisteredProbes.erase(probeIdx);
//recalculate all the probe's indicies just to be sure
for (U32 i = 0; i < mRegisteredProbes.size(); i++)
{
mRegisteredProbes[i]->mProbeIdx = i;
}
//rebuild our probe data
mProbesDirty = true;
}
void RenderProbeMgr::submitProbe(const ProbeRenderInst& newProbe)
{
mActiveProbes.push_back(newProbe);
}
//
//
PostEffect* RenderProbeMgr::getProbeArrayEffect()
{
if (!mProbeArrayEffect)
{
mProbeArrayEffect = dynamic_cast<PostEffect*>(Sim::findObject("reflectionProbeArrayPostFX"));
if (!mProbeArrayEffect)
return nullptr;
}
return mProbeArrayEffect;
}
//remove
//Con::setIntVariable("lightMetrics::activeReflectionProbes", mReflectProbeBin.size());
//Con::setIntVariable("lightMetrics::culledReflectProbes", 0/*mNumLightsCulled*/);
//
void RenderProbeMgr::updateProbes()
{
mProbesDirty = true;
}
void RenderProbeMgr::updateProbeTexture(ProbeRenderInst* probeInfo)
{
if (probeInfo->mIrradianceCubemap.isNull() || !probeInfo->mIrradianceCubemap->isInitialized())
{
Con::errorf("RenderProbeMgr::updateProbeTexture() - tried to update a probe's texture with an invalid or uninitialized irradiance map!");
return;
}
if (probeInfo->mPrefilterCubemap.isNull() || !probeInfo->mPrefilterCubemap->isInitialized())
{
Con::errorf("RenderProbeMgr::updateProbeTexture() - tried to update a probe's texture with an invalid or uninitialized specular map!");
return;
}
const U32 cubeIndex = probeInfo->mCubemapIndex;
mIrradianceArray->updateTexture(probeInfo->mIrradianceCubemap, cubeIndex);
mPrefilterArray->updateTexture(probeInfo->mPrefilterCubemap, cubeIndex);
#ifdef TORQUE_DEBUG
Con::warnf("UpdatedProbeTexture - probeIdx: %u on cubeIndex %u, Irrad validity: %d, Prefilter validity: %d", probeInfo->mProbeIdx, cubeIndex,
probeInfo->mIrradianceCubemap->isInitialized(), probeInfo->mPrefilterCubemap->isInitialized());
#endif
}
void RenderProbeMgr::reloadTextures()
{
U32 probeCount = mRegisteredProbes.size();
for (U32 i = 0; i < probeCount; i++)
{
updateProbeTexture(mRegisteredProbes[i]);
}
mProbesDirty = true;
}
void RenderProbeMgr::_setupPerFrameParameters(const SceneRenderState *state)
{
PROFILE_SCOPE(RenderProbeMgr_SetupPerFrameParameters);
mProbeData = ProbeDataSet(smMaxProbesPerFrame);
getBestProbes(state->getCameraPosition(), &mProbeData);
}
ProbeShaderConstants* RenderProbeMgr::getProbeShaderConstants(GFXShaderConstBuffer* buffer)
{
if (!buffer)
return NULL;
PROFILE_SCOPE(ProbeManager_GetProbeShaderConstants);
GFXShader* shader = buffer->getShader();
// Check to see if this is the same shader, we'll get hit repeatedly by
// the same one due to the render bin loops.
if (mLastShader.getPointer() != shader)
{
ProbeConstantMap::Iterator iter = mConstantLookup.find(shader);
if (iter != mConstantLookup.end())
{
mLastConstants = iter->value;
}
else
{
ProbeShaderConstants* psc = new ProbeShaderConstants();
mConstantLookup[shader] = psc;
mLastConstants = psc;
}
// Set our new shader
mLastShader = shader;
}
/*if (mLastConstants == nullptr)
{
ProbeShaderConstants* psc = new ProbeShaderConstants();
mConstantLookup[shader] = psc;
mLastConstants = psc;
}*/
// Make sure that our current lighting constants are initialized
if (mLastConstants && !mLastConstants->mInit)
mLastConstants->init(shader);
return mLastConstants;
}
void RenderProbeMgr::setupSGData(SceneData& data, const SceneRenderState* state, LightInfo* light)
{
//ensure they're sorted for forward rendering
mActiveProbes.sort(_probeScoreCmp);
}
void RenderProbeMgr::_update4ProbeConsts(const SceneData &sgData,
MatrixSet &matSet,
ProbeShaderConstants *probeShaderConsts,
GFXShaderConstBuffer *shaderConsts)
{
PROFILE_SCOPE(ProbeManager_Update4ProbeConsts);
// Skip over gathering lights if we don't have to!
if (probeShaderConsts->isValid())
{
PROFILE_SCOPE(ProbeManager_Update4ProbeConsts_setProbes);
const U32 MAX_FORWARD_PROBES = 4;
ProbeDataSet probeSet(MAX_FORWARD_PROBES);
matSet.restoreSceneViewProjection();
getBestProbes(sgData.objTrans->getPosition(), &probeSet);
static AlignedArray<Point4F> probePositionAlignedArray(probeSet.maxProbeCount, sizeof(Point4F));
static AlignedArray<Point4F> refScaleAlignedArray(probeSet.maxProbeCount, sizeof(Point4F));
static AlignedArray<Point4F> probeRefPositionAlignedArray(probeSet.maxProbeCount, sizeof(Point4F));
static AlignedArray<Point4F> probeConfigAlignedArray(probeSet.maxProbeCount, sizeof(Point4F));
for (U32 i = 0; i < probeSet.maxProbeCount; i++)
{
probePositionAlignedArray[i] = probeSet.probePositionArray[i];
probeRefPositionAlignedArray[i] = probeSet.probeRefPositionArray[i];
refScaleAlignedArray[i] = probeSet.refScaleArray[i];
probeConfigAlignedArray[i] = probeSet.probeConfigArray[i];
}
shaderConsts->setSafe(probeShaderConsts->mProbeCountSC, (S32)probeSet.effectiveProbeCount);
shaderConsts->setSafe(probeShaderConsts->mProbePositionSC, probePositionAlignedArray);
shaderConsts->setSafe(probeShaderConsts->mProbeRefPosSC, probeRefPositionAlignedArray);
if(probeShaderConsts->isValid())
shaderConsts->set(probeShaderConsts->mWorldToObjArraySC, probeSet.probeWorldToObjArray.address(), probeSet.effectiveProbeCount, GFXSCT_Float4x4);
shaderConsts->setSafe(probeShaderConsts->mRefScaleSC, refScaleAlignedArray);
shaderConsts->setSafe(probeShaderConsts->mProbeConfigDataSC, probeConfigAlignedArray);
shaderConsts->setSafe(probeShaderConsts->mSkylightCubemapIdxSC, (float)probeSet.skyLightIdx);
if(probeShaderConsts->mBRDFTextureMap->getSamplerRegister() != -1 && mBRDFTexture.isValid())
GFX->setTexture(probeShaderConsts->mBRDFTextureMap->getSamplerRegister(), mBRDFTexture);
if(probeShaderConsts->mProbeSpecularCubemapSC->getSamplerRegister() != -1)
GFX->setCubeArrayTexture(probeShaderConsts->mProbeSpecularCubemapSC->getSamplerRegister(), mPrefilterArray);
if(probeShaderConsts->mProbeIrradianceCubemapSC->getSamplerRegister() != -1)
GFX->setCubeArrayTexture(probeShaderConsts->mProbeIrradianceCubemapSC->getSamplerRegister(), mIrradianceArray);
}
}
S32 QSORT_CALLBACK RenderProbeMgr::_probeScoreCmp(const ProbeRenderInst* a, const ProbeRenderInst* b)
{
F32 diff = a->getScore() - b->getScore();
return diff > 0 ? 1 : diff < 0 ? -1 : 0;
}
void RenderProbeMgr::getBestProbes(const Point3F& objPosition, ProbeDataSet* probeDataSet)
{
PROFILE_SCOPE(ProbeManager_getBestProbes);
//Array rendering
U32 probeCount = mActiveProbes.size();
Vector<S8> bestPickProbes;
bestPickProbes.setSize(probeDataSet->maxProbeCount);
bestPickProbes.fill(-1);
probeDataSet->effectiveProbeCount = 0;
for (U32 i = 0; i < probeCount; i++)
{
if (probeDataSet->skyLightIdx != -1 && probeDataSet->effectiveProbeCount >= probeDataSet->maxProbeCount)
break;
const ProbeRenderInst& curEntry = mActiveProbes[i];
if (!curEntry.mIsEnabled)
continue;
if (curEntry.mProbeShapeType != ProbeRenderInst::Skylight)
{
if (probeDataSet->effectiveProbeCount < probeDataSet->maxProbeCount)
{
bestPickProbes[probeDataSet->effectiveProbeCount] = i;
probeDataSet->effectiveProbeCount++;
}
}
else
{
probeDataSet->skyLightIdx = curEntry.mCubemapIndex;
}
}
//Grab our best probe picks
for (U32 i = 0; i < bestPickProbes.size(); i++)
{
if (bestPickProbes[i] == -1)
continue;
const ProbeRenderInst& curEntry = mActiveProbes[bestPickProbes[i]];
MatrixF p2A = curEntry.getTransform();
p2A.inverse();
probeDataSet->refScaleArray[i] = curEntry.mProbeRefScale / p2A.getScale();
Point3F probePos = curEntry.getPosition();
Point3F refPos = probePos + curEntry.mProbeRefOffset * probeDataSet->refScaleArray[i].asPoint3F();
probeDataSet->probeWorldToObjArray[i] = curEntry.getTransform();
probeDataSet->probePositionArray[i] = Point4F(probePos.x, probePos.y, probePos.z, 0);
probeDataSet->probeRefPositionArray[i] = Point4F(refPos.x, refPos.y, refPos.z, 0);
probeDataSet->probeConfigArray[i] = Point4F(curEntry.mProbeShapeType,
curEntry.mRadius,
curEntry.mAtten,
curEntry.mCubemapIndex);
}
}
void RenderProbeMgr::getProbeTextureData(ProbeTextureArrayData* probeTextureSet)
{
probeTextureSet->BRDFTexture = mBRDFTexture;
probeTextureSet->prefilterArray = mPrefilterArray;
probeTextureSet->irradianceArray = mIrradianceArray;
}
void RenderProbeMgr::setProbeInfo(ProcessedMaterial *pmat,
const Material *mat,
const SceneData &sgData,
const SceneRenderState *state,
U32 pass,
GFXShaderConstBuffer *shaderConsts)
{
// Skip this if we're rendering from the deferred bin.
if (sgData.binType == SceneData::DeferredBin)
return;
PROFILE_SCOPE(ProbeManager_setProbeInfo);
ProbeShaderConstants *psc = getProbeShaderConstants(shaderConsts);
// NOTE: If you encounter a crash from this point forward
// while setting a shader constant its probably because the
// mConstantLookup has bad shaders/constants in it.
//
// This is a known crash bug that can occur if materials/shaders
// are reloaded and the light manager is not reset.
//
// We should look to fix this by clearing the table.
MatrixSet matSet = state->getRenderPass()->getMatrixSet();
// Update the forward shading light constants.
_update4ProbeConsts(sgData, matSet, psc, shaderConsts);
}
//-----------------------------------------------------------------------------
// render objects
//-----------------------------------------------------------------------------
void RenderProbeMgr::render( SceneRenderState *state )
{
if (getProbeArrayEffect() == nullptr)
{
mActiveProbes.clear();
return;
}
GFXDEBUGEVENT_SCOPE(RenderProbeMgr_render, ColorI::WHITE);
//Sort the active probes
mActiveProbes.sort(_probeScoreCmp);
// Initialize and set the per-frame data
_setupPerFrameParameters(state);
// Early out if nothing to draw.
if (!RenderProbeMgr::smRenderReflectionProbes || (!state->isDiffusePass() && !state->isReflectPass()) || (mProbeData.effectiveProbeCount == 0 && mProbeData.skyLightIdx == -1))
{
getProbeArrayEffect()->setSkip(true);
mActiveProbes.clear();
return;
}
GFXTransformSaver saver;
//Visualization
String useDebugAtten = Con::getVariable("$Probes::showAttenuation", "0");
mProbeArrayEffect->setShaderMacro("DEBUGVIZ_ATTENUATION", useDebugAtten);
String useDebugSpecCubemap = Con::getVariable("$Probes::showSpecularCubemaps", "0");
mProbeArrayEffect->setShaderMacro("DEBUGVIZ_SPECCUBEMAP", useDebugSpecCubemap);
String useDebugDiffuseCubemap = Con::getVariable("$Probes::showDiffuseCubemaps", "0");
mProbeArrayEffect->setShaderMacro("DEBUGVIZ_DIFFCUBEMAP", useDebugDiffuseCubemap);
String useDebugContrib = Con::getVariable("$Probes::showProbeContrib", "0");
mProbeArrayEffect->setShaderMacro("DEBUGVIZ_CONTRIB", useDebugContrib);
if(mProbeData.skyLightIdx != -1 && mProbeData.effectiveProbeCount == 0)
mProbeArrayEffect->setShaderMacro("SKYLIGHT_ONLY", "1");
else
mProbeArrayEffect->setShaderMacro("SKYLIGHT_ONLY", "0");
String probePerFrame = Con::getVariable("$pref::MaxProbesPerFrame", "8");
mProbeArrayEffect->setShaderMacro("MAX_PROBES", probePerFrame);
//ssao mask
if (AdvancedLightBinManager::smUseSSAOMask)
{
//find ssaoMask
NamedTexTargetRef ssaoTarget = NamedTexTarget::find("ssaoMask");
GFXTextureObject* pTexObj = ssaoTarget->getTexture();
if (pTexObj)
{
mProbeArrayEffect->setShaderMacro("USE_SSAO_MASK");
mProbeArrayEffect->setTexture(6, pTexObj);
}
}
else
{
mProbeArrayEffect->setTexture(6, GFXTexHandle(NULL));
}
mProbeArrayEffect->setTexture(3, mBRDFTexture);
mProbeArrayEffect->setCubemapArrayTexture(4, mPrefilterArray);
mProbeArrayEffect->setCubemapArrayTexture(5, mIrradianceArray);
mProbeArrayEffect->setShaderConst("$numProbes", (S32)mProbeData.effectiveProbeCount);
mProbeArrayEffect->setShaderConst("$skylightCubemapIdx", (S32)mProbeData.skyLightIdx);
mProbeArrayEffect->setShaderConst("$cubeMips", (float)mPrefilterArray->getMipMapLevels());
//also set up some colors
Vector<Point4F> contribColors;
contribColors.setSize(mProbeData.effectiveProbeCount);
if (mProbeData.effectiveProbeCount != 0)
{
if (useDebugContrib == String("1"))
{
MRandomLCG RandomGen;
RandomGen.setSeed(mProbeData.effectiveProbeCount);
for (U32 i = 0; i < mProbeData.effectiveProbeCount; i++)
{
//we're going to cheat here a little for consistent debugging behavior. The first 3 probes will always have R G and then B for their colors, every other will be random
if (i == 0)
contribColors[i] = Point4F(1, 0, 0, 1);
else if (i == 1)
contribColors[i] = Point4F(0, 1, 0, 1);
else if (i == 2)
contribColors[i] = Point4F(0, 0, 1, 1);
else
contribColors[i] = Point4F(RandomGen.randF(0, 1), RandomGen.randF(0, 1), RandomGen.randF(0, 1), 1);
}
}
}
mProbeArrayEffect->setShaderConst("$probeContribColors", contribColors);
mProbeArrayEffect->setShaderConst("$probePosArray", mProbeData.probePositionArray);
mProbeArrayEffect->setShaderConst("$refPosArray", mProbeData.probeRefPositionArray);
mProbeArrayEffect->setShaderConst("$worldToObjArray", mProbeData.probeWorldToObjArray);
mProbeArrayEffect->setShaderConst("$refScaleArray", mProbeData.refScaleArray);
mProbeArrayEffect->setShaderConst("$probeConfigData", mProbeData.probeConfigArray);
// Make sure the effect is gonna render.
getProbeArrayEffect()->setSkip(false);
mActiveProbes.clear();
}
void RenderProbeMgr::bakeProbe(ReflectionProbe *probe)
{
GFXDEBUGEVENT_SCOPE(RenderProbeMgr_Bake, ColorI::WHITE);
Con::warnf("RenderProbeMgr::bakeProbe() - Beginning bake!");
U32 startMSTime = Platform::getRealMilliseconds();
String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
U32 resolution = Con::getIntVariable("$pref::ReflectionProbes::BakeResolution", 64);
U32 prefilterMipLevels = mLog2(F32(resolution)) + 1;
bool renderWithProbes = Con::getIntVariable("$pref::ReflectionProbes::RenderWithProbes", false);
ReflectionProbe* clientProbe = nullptr;
if (probe->isServerObject())
clientProbe = static_cast<ReflectionProbe*>(probe->getClientObject());
else
return;
if (clientProbe == nullptr)
return;
String probePrefilterPath = clientProbe->getPrefilterMapPath();
String probeIrradPath = clientProbe->getIrradianceMapPath();
if (clientProbe->mReflectionModeType != ReflectionProbe::DynamicCubemap)
{
//Prep our bake path
if (probePrefilterPath.isEmpty() || probeIrradPath.isEmpty())
{
Con::errorf("RenderProbeMgr::bake() - Unable to bake our captures because probe doesn't have a path set");
return;
}
}
// Save the current transforms so we can restore
// it for child control rendering below.
GFXTransformSaver saver;
bool probeRenderState = RenderProbeMgr::smRenderReflectionProbes;
F32 farPlane = 1000.0f;
ReflectorDesc reflDesc;
reflDesc.texSize = resolution;
reflDesc.farDist = farPlane;
reflDesc.detailAdjust = 1;
reflDesc.objectTypeMask = probe->mProbeShapeType == ProbeRenderInst::ProbeShapeType::Skylight ? SKYLIGHT_CAPTURE_TYPEMASK : REFLECTION_PROBE_CAPTURE_TYPEMASK;
CubeReflector cubeRefl;
cubeRefl.registerReflector(probe, &reflDesc);
ReflectParams reflParams;
//need to get the query somehow. Likely do some sort of get function to fetch from the guiTSControl that's active
CameraQuery query; //need to get the last cameraQuery
query.fov = 90; //90 degree slices for each of the 6 sides
query.nearPlane = 0.1f;
query.farPlane = farPlane;
query.headMatrix = MatrixF();
query.cameraMatrix = clientProbe->getTransform();
Frustum culler;
culler.set(false,
query.fov,
1.0f,
query.nearPlane,
query.farPlane,
query.cameraMatrix);
S32 stereoTarget = GFX->getCurrentStereoTarget();
Point2I maxRes(2048, 2048); //basically a boundary so we don't go over this and break stuff
reflParams.culler = culler;
reflParams.eyeId = stereoTarget;
reflParams.query = &query;
reflParams.startOfUpdateMs = startMSTime;
reflParams.viewportExtent = maxRes;
if (!renderWithProbes)
RenderProbeMgr::smRenderReflectionProbes = false;
GFXFormat reflectFormat;
if (mUseHDRCaptures)
reflectFormat = GFXFormatR16G16B16A16F;
else
reflectFormat = GFXFormatR8G8B8A8;
const GFXFormat oldRefFmt = REFLECTMGR->getReflectFormat();
REFLECTMGR->setReflectFormat(reflectFormat);
mProbeArrayEffect->setShaderConst("$CAPTURING", true);
cubeRefl.updateReflection(reflParams, clientProbe->getTransform().getPosition()+clientProbe->mProbeRefOffset);
mProbeArrayEffect->setShaderConst("$CAPTURING", false);
//Now, save out the maps
//create irridiance cubemap
if (cubeRefl.getCubemap())
{
//Just to ensure we're prepped for the generation
clientProbe->createClientResources();
//Prep it with whatever resolution we've dictated for our bake
clientProbe->mIrridianceMap->mCubemap->initDynamic(resolution, reflectFormat);
clientProbe->mPrefilterMap->mCubemap->initDynamic(resolution, reflectFormat);
GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
IBLUtilities::GenerateIrradianceMap(renderTarget, cubeRefl.getCubemap(), clientProbe->mIrridianceMap->mCubemap);
IBLUtilities::GeneratePrefilterMap(renderTarget, cubeRefl.getCubemap(), prefilterMipLevels, clientProbe->mPrefilterMap->mCubemap);
U32 endMSTime = Platform::getRealMilliseconds();
F32 diffTime = F32(endMSTime - startMSTime);
Con::warnf("RenderProbeMgr::bake() - Finished Capture! Took %g milliseconds", diffTime);
Con::warnf("RenderProbeMgr::bake() - Beginning save now!");
IBLUtilities::SaveCubeMap(clientProbe->getIrradianceMapPath(), clientProbe->mIrridianceMap->mCubemap);
IBLUtilities::SaveCubeMap(clientProbe->getPrefilterMapPath(), clientProbe->mPrefilterMap->mCubemap);
}
else
{
Con::errorf("RenderProbeMgr::bake() - Didn't generate a valid scene capture cubemap, unable to generate prefilter and irradiance maps!");
}
if (!renderWithProbes)
RenderProbeMgr::smRenderReflectionProbes = probeRenderState;
cubeRefl.unregisterReflector();
U32 endMSTime = Platform::getRealMilliseconds();
F32 diffTime = F32(endMSTime - startMSTime);
probe->setMaskBits(-1);
Con::warnf("RenderProbeMgr::bake() - Finished bake! Took %g milliseconds", diffTime);
REFLECTMGR->setReflectFormat(oldRefFmt);
}
void RenderProbeMgr::bakeProbes()
{
Vector<ReflectionProbe*> probes;
Scene::getRootScene()->findObjectByType<ReflectionProbe>(probes);
for (U32 i = 0; i < probes.size(); i++)
{
if (probes[i]->isClientObject())
continue;
bakeProbe(probes[i]);
}
}
DefineEngineMethod(RenderProbeMgr, bakeProbe, void, (ReflectionProbe* probe), (nullAsType< ReflectionProbe*>()),
"@brief Bakes the cubemaps for a reflection probe\n\n.")
{
if(probe != nullptr)
object->bakeProbe(probe);
}
DefineEngineMethod(RenderProbeMgr, bakeProbes, void, (),, "@brief Iterates over all reflection probes in the scene and bakes their cubemaps\n\n.")
{
object->bakeProbes();
}
| 33.526042 | 179 | 0.720304 | DraconicEnt |
bfc2aa0b08832e245a58f51eddd70586279ab2e4 | 63 | cpp | C++ | DeviceCode/Drivers/TouchPanel/ADS7843/ads7843_fastcompile.cpp | Sirokujira/MicroFrameworkPK_v4_3 | a0d80b4fd8eeda6dbdb58f6f7beb4f07f7ef563e | [
"Apache-2.0"
] | 4 | 2019-01-21T11:47:53.000Z | 2020-06-09T02:14:15.000Z | DeviceCode/Drivers/TouchPanel/ADS7843/ads7843_fastcompile.cpp | yisea123/NetmfSTM32 | 62ddb8aa0362b83d2e73f3621a56593988e3620f | [
"Apache-2.0"
] | null | null | null | DeviceCode/Drivers/TouchPanel/ADS7843/ads7843_fastcompile.cpp | yisea123/NetmfSTM32 | 62ddb8aa0362b83d2e73f3621a56593988e3620f | [
"Apache-2.0"
] | 6 | 2017-11-09T11:48:10.000Z | 2020-05-24T09:43:07.000Z | #include "ADS7843_functions.cpp"
#include "ADS7843_driver.cpp"
| 21 | 32 | 0.809524 | Sirokujira |
bfc53adfe174a3848f2af9b97dabc6a328ffb171 | 935 | inl | C++ | extra_files/vector.inl | Majrusz/AdventOfCode2020 | cb01ebb735bdbc27b1fef8f3513bc340cfb2bd25 | [
"MIT"
] | 1 | 2020-12-19T17:06:58.000Z | 2020-12-19T17:06:58.000Z | extra_files/vector.inl | Majrusz/AdventOfCode2020 | cb01ebb735bdbc27b1fef8f3513bc340cfb2bd25 | [
"MIT"
] | null | null | null | extra_files/vector.inl | Majrusz/AdventOfCode2020 | cb01ebb735bdbc27b1fef8f3513bc340cfb2bd25 | [
"MIT"
] | null | null | null | // Created by Majrusz on 20/12/2020. All rights reserved.
#include "vector.h"
template< size_t N >
double aoc::Vector< N >::calculateDistance( const Vector< N > &origin ) const {
double distance{};
for( size_t index{}; index < N; index++ )
distance += std::pow( this->coordinates[ index ] - origin.coordinates[ index ], 2 );
return std::sqrt( distance );
}
template< size_t N >
double aoc::Vector< N >::dotProduct( const Vector< N > &vector ) const {
double product{};
for( size_t index{}; index < N; index++ )
product += this->coordinates[ index ] * vector.coordinates[ index ];
return product;
}
template< size_t N >
aoc::Angle aoc::Vector< N >::calculateAngle( const Vector< N > &vector ) const {
Radians radians{ std::acos( dotProduct( vector ) / ( calculateDistance() * vector.calculateDistance() ) ) };
if( this->coordinates[ N-1 ] < 0.0 )
radians = Radians{ 2 * Angle::pi - radians };
return radians;
}
| 27.5 | 109 | 0.662032 | Majrusz |
bfca0cd1e2499fba04c73af165f404fe8e68b4b5 | 529 | cpp | C++ | ThirdParty/BCGControlBar/BCGControlBar/bcginit.cpp | BlackYoup/gamecq | 85d7ca2a84125e48a439c185a249e06c7bd3e3e9 | [
"MIT"
] | 12 | 2016-05-22T22:37:36.000Z | 2021-02-02T16:47:42.000Z | ThirdParty/BCGControlBar/BCGControlBar/bcginit.cpp | BlackYoup/gamecq | 85d7ca2a84125e48a439c185a249e06c7bd3e3e9 | [
"MIT"
] | 2 | 2017-06-16T13:30:34.000Z | 2018-01-28T21:04:24.000Z | ThirdParty/BCGControlBar/BCGControlBar/bcginit.cpp | BlackYoup/gamecq | 85d7ca2a84125e48a439c185a249e06c7bd3e3e9 | [
"MIT"
] | 11 | 2016-05-28T04:43:55.000Z | 2020-09-26T03:48:13.000Z | //*******************************************************************************
// COPYRIGHT NOTES
// ---------------
// This is a part of the BCGControlBar Library
// Copyright (C) 1998-2006 BCGSoft Ltd.
// All rights reserved.
//
// This source code can be used, distributed or modified
// only under terms and conditions
// of the accompanying license agreement.
//*******************************************************************************
#include "stdafx.h"
#include "bcginit.h"
BOOL BCGInit ()
{
return TRUE;
}
| 26.45 | 82 | 0.470699 | BlackYoup |
bfcb46d5d707ff73291e19f9db65cb9f5c45ff6f | 3,702 | cpp | C++ | image-localization/community-code/roboauto/ros/src/utils/src/SignDetection.cpp | vaibhav-s/self-driving-car | eb5865d50499f90b3eeace869c1f8a65cf9e2c46 | [
"MIT"
] | null | null | null | image-localization/community-code/roboauto/ros/src/utils/src/SignDetection.cpp | vaibhav-s/self-driving-car | eb5865d50499f90b3eeace869c1f8a65cf9e2c46 | [
"MIT"
] | null | null | null | image-localization/community-code/roboauto/ros/src/utils/src/SignDetection.cpp | vaibhav-s/self-driving-car | eb5865d50499f90b3eeace869c1f8a65cf9e2c46 | [
"MIT"
] | null | null | null | /*
* Copyright 2016 RoboAuto team, Artin
* All rights reserved.
*
* This file is part of RoboAuto HorizonSlam.
*
* RoboAuto HorizonSlam is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* RoboAuto HorizonSlam 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 RoboAuto HorizonSlam. If not, see <http://www.gnu.org/licenses/>.
*/
#include <utils/SignDetection.h>
std::vector<utils::SignDetection::Sign> utils::SignDetection::FindSigns(cv::Mat &marks, int minRadius) {
std::vector<std::vector<cv::Point>> contours,goodContours;
cv::findContours(marks, contours, cv::RetrievalModes::RETR_LIST, cv::ContourApproximationModes::CHAIN_APPROX_NONE, cv::Point(0, 0));
cv::Mat goodMarks = cv::Mat::zeros(marks.rows,marks.cols,marks.type());
for (size_t i = 0; i < contours.size(); ++i)
{
if(contours[i].size() > 100 && contours[i].size() < 6000)
{
goodContours.push_back(contours[i]);
}
}
cv::fillPoly(goodMarks,goodContours,cv::Scalar(255));
contours.clear();
cv::morphologyEx(goodMarks,goodMarks,cv::MORPH_CLOSE,cv::getStructuringElement(cv::MORPH_ELLIPSE,cv::Size(7,7)));
cv::morphologyEx(goodMarks,goodMarks,cv::MORPH_OPEN,cv::getStructuringElement(cv::MORPH_ELLIPSE,cv::Size(3,3)));
cv::findContours(goodMarks, contours, cv::RetrievalModes::RETR_LIST, cv::ContourApproximationModes::CHAIN_APPROX_NONE, cv::Point(0, 0));
std::vector<Sign> detectedMarks;
for (size_t i = 0; i < contours.size(); i++) {
float radius;
cv::Point2f center;
std::vector<cv::Point> contours_poly;
cv::approxPolyDP(cv::Mat(contours[i]), contours_poly, 3, true);
cv::minEnclosingCircle((cv::Mat) contours_poly, center, radius);
if (radius > minRadius) {
detectedMarks.push_back({center, radius});
}
}
return detectedMarks;
}
void utils::SignDetection::DrawSignToImg(cv::Mat &img, const std::vector<std::pair<cv::Point2f, float>> &marks,
const std::string &type) {
cv::Scalar color;
if (type == "yellow") {
color = cv::Scalar(21, 178, 0);
} else if (type == "dark yellow") {
color = cv::Scalar(219, 198, 41);
} else if (type == "dark green") {
color = cv::Scalar(40, 131, 22);
} else {
color = cv::Scalar(255, 0, 0);
}
for (std::size_t i = 0; i < marks.size(); i++) {
cv::circle(img, marks[i].first, marks[i].second, color, 2, 8, 0);
}
}
std::vector<utils::SignDetection::Sign> utils::SignDetection::DetectYellowMarks(const cv::Mat &hsvImage) {
cv::Mat marks;
cv::inRange(hsvImage, cv::Scalar(20, 107, 53), cv::Scalar(56, 182, 255), marks);
return FindSigns(marks);
}
std::vector<utils::SignDetection::Sign> utils::SignDetection::DetectDarkYellowMarks(const cv::Mat &hsvImage) {
cv::Mat marks;
cv::inRange(hsvImage, cv::Scalar(9, 115, 64), cv::Scalar(38, 200, 200), marks);
return FindSigns(marks);
}
std::vector<utils::SignDetection::Sign> utils::SignDetection::DetectDarkGreen(const cv::Mat &hsvImage) {
cv::Mat marks;
cv::inRange(hsvImage, cv::Scalar(91, 113, 32), cv::Scalar(103, 213, 208), marks);
return FindSigns(marks, 20);
} | 39.806452 | 140 | 0.655051 | vaibhav-s |
bfcc3c02ed1648435fe862c9662a3dddf3d13db6 | 10,678 | cpp | C++ | src/NGM.cpp | monsanto-pinheiro/ngmlr | 8d7677929001d1d13c6b4593c409a52044180dca | [
"MIT"
] | 239 | 2017-01-18T15:14:34.000Z | 2022-03-09T10:44:08.000Z | src/NGM.cpp | monsanto-pinheiro/ngmlr | 8d7677929001d1d13c6b4593c409a52044180dca | [
"MIT"
] | 96 | 2017-01-13T15:03:29.000Z | 2022-02-07T14:27:18.000Z | src/NGM.cpp | monsanto-pinheiro/ngmlr | 8d7677929001d1d13c6b4593c409a52044180dca | [
"MIT"
] | 44 | 2017-03-17T20:31:08.000Z | 2021-12-02T07:27:09.000Z | /**
* Contact: philipp.rescheneder@gmail.com
*/
#include "NGM.h"
#include <memory.h>
#include <stdlib.h>
#include <limits.h>
#include "CS.h"
#include "PrefixTable.h"
#include "ReadProvider.h"
#include "PlainFileWriter.h"
#include "SAMWriter.h"
#include "Timing.h"
#include "StrippedSW.h"
#undef module_name
#define module_name "NGM"
_NGM * _NGM::pInstance = 0;
NGMOnceControl _NGM::once_control = NGM_ONCE_INIT;
char const * _NGM::AppName = 0;
namespace __NGM {
inline int min(int a, int b) {
return (a < b) ? a : b;
}
}
void _NGM::Init() {
pInstance = new _NGM();
}
_NGM & _NGM::Instance() {
NGMOnce(&_NGM::once_control, Init);
return *pInstance;
}
_NGM::_NGM() : Stats(new NGMStats()), m_ActiveThreads(0), m_NextThread(0), m_CurStart(0), m_CurCount(0), m_SchedulerMutex(), m_SchedulerWait(), m_TrackUnmappedReads(false), m_UnmappedReads(0), m_MappedReads(0), m_WrittenReads(0), m_ReadReads(0), m_RefProvider(0), m_ReadProvider(0) {
char const * const output_name = Config.getOutputFile();
// if (!Config.getBAM()) {
if (output_name != 0) {
Log.Message("Opening for output (SAM): %s", output_name);
} else {
Log.Message("Writing output (SAM) to stdout");
}
m_Output = new PlainFileWriter(output_name);
// } else {
// if (output_name != 0) {
// Log.Message("Opening for output (BAM): %s", output_name);
// } else {
// Log.Message("Wrinting output (BAM) to stdout");
// }
// m_Output = new FileWriterBam(output_name);
// }
Log.Verbose("NGM Core initialization");
NGMInitMutex(&m_Mutex);
NGMInitMutex(&m_OutputMutex);
NGMInitMutex(&m_UMRMutex);
NGMInitWait(&m_CSWait);
NGMInitMutex(&m_SchedulerMutex);
NGMInitWait(&m_SchedulerWait);
writer = 0;
memset(m_StageThreadCount, 0, cMaxStage * sizeof(int));
memset(m_BlockedThreads, 0, cMaxStage * sizeof(int));
memset(m_ToBlock, 0, cMaxStage * sizeof(int));
}
void _NGM::InitProviders() {
CS::Init();
SequenceProvider.Init(); // Prepares input data
m_RefProvider = new CompactPrefixTable();
m_ReadProvider = new ReadProvider();
uint readCount = m_ReadProvider->init();
}
_NGM::~_NGM() {
delete Stats;
Stats = 0;
if (m_RefProvider != 0)
delete m_RefProvider;
if (m_ReadProvider != 0)
delete m_ReadProvider;
}
void _NGM::StartThread(NGMTask * task, int cpu) {
Log.Verbose("Starting thread %i <%s> on cpu %i", m_NextThread, task->GetName(), cpu);
NGMLock(&m_Mutex);
task->m_TID = m_NextThread;
m_Tasks[m_NextThread] = task;
m_Threads[m_NextThread] = NGMCreateThread(&_NGM::ThreadFunc, task, false);
++m_StageThreadCount[task->GetStage()];
++m_NextThread;
++m_ActiveThreads;
NGMUnlock(&m_Mutex);
}
void * _NGM::getWriter() {
return m_Output;
}
void _NGM::ReleaseWriter() {
if (m_Output != 0) {
// if (!Config.getBAM()) {
delete (FileWriter*) m_Output;
// } else {
// delete (FileWriterBam*) m_Output;
// }
m_Output = 0;
}
}
void _NGM::AddUnmappedRead(MappedRead const * const read, int reason) {
AtomicInc(&m_UnmappedReads);
Log.Debug(LOG_OUTPUT_DETAILS, "Read %s (%i) not mapped (%i)", read->name, read->ReadId, reason);
}
int _NGM::GetUnmappedReadCount() const {
return m_UnmappedReads;
}
void _NGM::AddMappedRead(int readid) {
AtomicInc(&m_MappedReads);
}
int _NGM::GetMappedReadCount() const {
return m_MappedReads;
}
void _NGM::AddWrittenRead(int readid) {
AtomicInc(&m_WrittenReads);
}
int _NGM::GetWrittenReadCount() const {
return m_WrittenReads;
}
void _NGM::AddReadRead(int readid) {
AtomicInc(&m_ReadReads);
}
int _NGM::GetReadReadCount() const {
return m_ReadReads;
}
int _NGM::GetStageThreadCount(int stage) {
NGMLock(&m_Mutex);
int cnt = 0;
for (int i = 0; i <= stage; ++i) {
cnt += m_StageThreadCount[i];
}
NGMUnlock(&m_Mutex);
return cnt;
}
void _NGM::FinishStage(int tid) {
NGMLock(&m_Mutex);
int stage = m_Tasks[tid]->GetStage();
--m_StageThreadCount[stage];
NGMUnlock(&m_Mutex);
Log.Verbose("Thread %i finished its stage (Stage %i, now %i active)", tid, stage, m_StageThreadCount[stage]);
}
void _NGM::FinishThread(int tid) {
AtomicDec(&m_ActiveThreads);
Log.Verbose("Thread %i finished (%i worker threads remaining)", tid, m_ActiveThreads);
m_Tasks[tid]->FinishStage();
delete m_Tasks[tid];
m_Tasks[tid] = 0;
}
bool eof = false;
std::vector<MappedRead*> _NGM::GetNextReadBatch(int desBatchSize) {
NGMLock(&m_Mutex);
std::vector<MappedRead*> list;
desBatchSize &= ~1;
if (m_CurCount == 0) {
m_CurStart = 0;
NGMSignal(&m_CSWait);
}
list.reserve(desBatchSize);
int count = 0;
//Long PacBio reads are split into smaller parts.
//Each part should have its own id.
int idJump = 2000;
int i = 0;
while (count < desBatchSize && !eof) {
MappedRead * read1 = 0;
eof = !NGM.GetReadProvider()->GenerateRead(m_CurStart + i * idJump, read1, 0, read1);
i += 1;
if (!eof) {
if (read1 != 0) {
count += 1;
Stats->readLengthSum += read1->length;
if (read1->group == 0) {
// Short read found: not split into read group
list.push_back(read1);
} else {
// Long read found: push subreads
for (int j = 0; j < read1->group->readNumber; ++j) {
list.push_back(read1->group->reads[j]);
}
}
}
}
}
m_CurStart += count;
m_CurCount -= desBatchSize;
NGMUnlock(&m_Mutex);
#ifdef _DEBUGCS
if(m_CurStart > 100000) {
Log.Warning("Debug CS mode: quitting after 100000 reads!");
list.clear();
}
#endif
return list;
}
NGMTHREADFUNC _NGM::ThreadFunc(void* data) {
NGMTask * task = (NGMTask*) data;
int tid = task->m_TID;
try {
Log.Verbose("Running thread %i", tid);
task->Run();
Log.Verbose("Thread %i run return, finishing", tid);
NGM.FinishThread(tid);
Log.Verbose("Thread %i finished", tid);
} catch (...) {
Log.Error("Unhandled exception in thread %i", tid);
NGM.FinishThread(tid);
}
Log.Verbose("ThreadFunc on thread %i returning", tid);
return 0;
}
void _NGM::InitQuit() {
static int quitState = 0;
++quitState;
if (quitState == 1) {
Log.Warning("Hit 'Q' two more times to quit program.");
} else if (quitState >= 3) {
CleanupPlatform();
Log.Error("Terminate by user request");
Log.Message("%i Threads still active", m_ActiveThreads);
for (int i = 0; i < cMaxStage; ++i) {
if (m_StageThreadCount[i] > 0)
Log.Message("Stage %i got %i threads still running", i, m_StageThreadCount[i]);
}
exit(-1);
}
}
void _NGM::AquireOutputLock() {
NGMLock(&m_OutputMutex);
}
void _NGM::ReleaseOutputLock() {
NGMUnlock(&m_OutputMutex);
}
IRefProvider const * _NGM::GetRefProvider(int const tid) {
return m_RefProvider;
}
IReadProvider * _NGM::GetReadProvider() {
return m_ReadProvider;
}
bool _NGM::ThreadActive(int tid, int stage) {
if (m_ToBlock[stage] > 0) {
NGMLock(&m_SchedulerMutex);
bool blocked = false;
if (m_ToBlock[stage] > 0) {
--m_ToBlock[stage];
blocked = true;
m_BlockedThreads[stage]++;
while (blocked) {
Log.Green("Block %i @ %i", tid, stage);
NGMWait(&m_SchedulerMutex, &m_SchedulerWait);
if (m_ToBlock[stage] < 0) {
++m_ToBlock[stage];
blocked = false;
m_BlockedThreads[stage]--;
Log.Green("Unblock %i @ %i", tid, stage);
}
}
}
NGMUnlock(&m_SchedulerMutex);
}
return true;
}
void _NGM::StopThreads() {
}
void _NGM::StartThreads() {
StartCS(Config.getThreads());
}
void _NGM::StartCS(int cs_threadcount) {
for (int i = 0; i < cs_threadcount; ++i) {
NGMTask * cs = 0;
cs = new CS();
StartThread(cs, -1);
}
}
IAlignment * _NGM::CreateAlignment(int const mode) {
IAlignment * instance = 0;
switch (Config.getSubreadAligner()) {
case 2:
instance = new StrippedSW();
break;
default:
Log.Error("Invalid subread alignerd: %d", Config.getSubreadAligner());
throw "";
}
return instance;
}
void _NGM::DeleteAlignment(IAlignment* instance) {
Log.Verbose("Delete alignment called");
if (instance != 0) {
delete instance;
instance = 0;
}
}
void _NGM::MainLoop() {
Timer tmr;
tmr.ST();
bool const progress = Config.getProgress();
int processed = 0;
float runTime = 0.0f;
float readsPerSecond = 0.0f;
float alignSuccessRatio = 0.0f;
int avgCorridor = 0;
while (Running()) {
Sleep(2000);
if (progress) {
processed = std::max(1, NGM.GetMappedReadCount() + NGM.GetUnmappedReadCount());
runTime = tmr.ET();
readsPerSecond = processed / runTime;
if((NGM.Stats->alignmentCount + NGM.Stats->invalidAligmentCount) > 0) {
avgCorridor = NGM.Stats->corridorLen / (NGM.Stats->alignmentCount + NGM.Stats->invalidAligmentCount);
alignSuccessRatio = NGM.Stats->alignmentCount * 1.0f / (NGM.Stats->alignmentCount + NGM.Stats->invalidAligmentCount);
}
float avgAlignPerc = 0.0f;
int avgReadLenght = 0;
float alignRate = 0.0f;
if(processed > 0) {
avgAlignPerc = NGM.Stats->avgAlignPerc / std::max(1, NGM.GetMappedReadCount());
avgReadLenght = (int)(NGM.Stats->readLengthSum / processed);
alignRate = NGM.GetMappedReadCount() * 1.0f / processed;
}
Log.Progress("Processed: %d (%.2f), R/S: %.2f, RL: %d, Time: %.2f %.2f %.2f, Align: %.2f, %d, %.2f", processed, alignRate, readsPerSecond, avgReadLenght, NGM.Stats->csTime, NGM.Stats->scoreTime, NGM.Stats->alignTime, alignSuccessRatio, avgCorridor, avgAlignPerc);
}
}
if (progress) {
processed = std::max(1, NGM.GetMappedReadCount() + NGM.GetUnmappedReadCount());
runTime = tmr.ET();
readsPerSecond = processed / runTime;
if((NGM.Stats->alignmentCount + NGM.Stats->invalidAligmentCount) > 0) {
alignSuccessRatio = NGM.Stats->alignmentCount * 1.0f / (NGM.Stats->alignmentCount + NGM.Stats->invalidAligmentCount);
avgCorridor = NGM.Stats->corridorLen / (NGM.Stats->alignmentCount + NGM.Stats->invalidAligmentCount);
}
float avgAlignPerc = 0.0f;
int avgReadLenght = 0;
float alignRate = 0.0f;
if(processed > 0) {
avgAlignPerc = NGM.Stats->avgAlignPerc / std::max(1, NGM.GetMappedReadCount());
avgReadLenght = (int)(NGM.Stats->readLengthSum / processed);
alignRate = NGM.GetMappedReadCount() * 1.0f / processed;
}
Log.Message("Processed: %d (%.2f), R/S: %.2f, RL: %d, Time: %.2f %.2f %.2f, Align: %.2f, %d, %.2f", processed, alignRate, readsPerSecond, avgReadLenght, NGM.Stats->csTime, NGM.Stats->scoreTime, NGM.Stats->alignTime, alignSuccessRatio, avgCorridor, avgAlignPerc);
}
}
| 24.832558 | 284 | 0.648342 | monsanto-pinheiro |
bfcd50b60d6e0c74def2ebbf04a98a32b10807bf | 4,903 | cpp | C++ | src/managers/framebuffer_manager.cpp | Romop5/holoinjector | db11922e6c57b4664beeec31199385a4877e1619 | [
"MIT"
] | 2 | 2021-04-12T06:09:57.000Z | 2021-05-20T11:56:01.000Z | src/managers/framebuffer_manager.cpp | Romop5/holoinjector | db11922e6c57b4664beeec31199385a4877e1619 | [
"MIT"
] | null | null | null | src/managers/framebuffer_manager.cpp | Romop5/holoinjector | db11922e6c57b4664beeec31199385a4877e1619 | [
"MIT"
] | null | null | null | /*****************************************************************************
*
* PROJECT: HoloInjector - https://github.com/Romop5/holoinjector
* LICENSE: See LICENSE in the top level directory
* FILE: managers/framebuffer_manager.cpp
*
*****************************************************************************/
#define GL_GLEXT_PROTOTYPES 1
#include <GL/gl.h>
#include "context.hpp"
#include "framebuffer_manager.hpp"
#include "pipeline/output_fbo.hpp"
#include "pipeline/viewport_area.hpp"
#include "trackers/framebuffer_tracker.hpp"
#include "utils/opengl_debug.hpp"
#include "utils/opengl_state.hpp"
#include "utils/opengl_utils.hpp"
using namespace hi;
using namespace hi::managers;
void FramebufferManager::clear(Context& context, GLbitfield mask)
{
if (context.m_IsMultiviewActivated && context.getFBOTracker().isFBODefault() && context.getOutputFBO().hasImage())
{
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(context.getCurrentViewport().getX(), context.getCurrentViewport().getY(),
context.getCurrentViewport().getWidth(), context.getCurrentViewport().getHeight());
context.getOutputFBO().renderToBackbuffer(context.getCameraParameters());
context.getOutputFBO().clearBuffers();
}
glClear(mask);
}
void FramebufferManager::bindFramebuffer(Context& context, GLenum target, GLuint framebuffer)
{
CLEAR_GL_ERROR();
context.getFBOTracker().bind(framebuffer);
if (framebuffer == 0)
{
if (context.m_IsMultiviewActivated)
{
glBindFramebuffer(target, context.getOutputFBO().getFBOId());
glViewport(0, 0, context.getOutputFBO().getParams().getTextureWidth(), context.getOutputFBO().getParams().getTextureHeight());
}
else
{
glBindFramebuffer(target, 0);
glViewport(context.getCurrentViewport().getX(), context.getCurrentViewport().getY(),
context.getCurrentViewport().getWidth(), context.getCurrentViewport().getHeight());
ASSERT_GL_ERROR();
}
}
else
{
if (context.m_IsMultiviewActivated)
{
auto id = framebuffer;
auto fbo = context.getFBOTracker().getBound();
/*
* Only create & bind shadow FBO when original FBO is complete (thus has any attachment)
*/
if (fbo->hasAnyAttachment())
{
if (!fbo->hasShadowFBO() && context.getFBOTracker().isSuitableForRepeating())
{
fbo->createShadowedFBO(context.getOutputFBO().getParams().getLayers());
if (!fbo->hasShadowFBO())
{
Logger::logError("Failed to create shadow FBO for FBO: ", id, HI_POS);
}
}
// Creation of shadow FBO should never fail
id = (fbo->hasShadowFBO() ? fbo->getShadowFBO() : id);
}
else
{
Logger::logDebug("Missing any attachment for FBOTracker::bind()");
}
glBindFramebuffer(target, id);
glViewport(context.getCurrentViewport().getX(), context.getCurrentViewport().getY(),
context.getCurrentViewport().getWidth(), context.getCurrentViewport().getHeight());
// TODO: shadowed textures are the same size as OutputFBO
/* if(context.m_IsMultiviewActivated) */
/* { */
/* glViewport(0,0,context.getOutputFBO().getParams().getTextureWidth(), context.getOutputFBO().getParams().getTextureHeight()); */
/* } */
}
else
{
glBindFramebuffer(target, framebuffer);
}
}
}
void FramebufferManager::swapBuffers(Context& context, std::function<void(void)> swapit)
{
swapit();
}
void FramebufferManager::renderFromOutputFBO(Context& context)
{
hi::utils::restoreStateFunctor({ GL_CULL_FACE, GL_DEPTH_TEST, GL_SCISSOR_TEST }, [this, &context]() {
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_SCISSOR_TEST);
glDisable(GL_STENCIL_TEST);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
if (context.m_IsMultiviewActivated && context.getOutputFBO().hasImage())
{
debug::logTrace("Dumping OutputFBO to backbuffer");
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glViewport(context.getCurrentViewport().getX(), context.getCurrentViewport().getY(),
context.getCurrentViewport().getWidth(), context.getCurrentViewport().getHeight());
context.getOutputFBO().renderToBackbuffer(context.getCameraParameters());
context.getOutputFBO().clearBuffers();
}
});
}
| 38.606299 | 146 | 0.607995 | Romop5 |
bfcda35f798d306b4537f7d1f1b501ff1af5a884 | 433 | cpp | C++ | test/Vec3Tests.cpp | craft-coder/Softwareentwicklung-2021 | 6c9cf6201b333796a058394c017c8b3e72a3f631 | [
"MIT"
] | null | null | null | test/Vec3Tests.cpp | craft-coder/Softwareentwicklung-2021 | 6c9cf6201b333796a058394c017c8b3e72a3f631 | [
"MIT"
] | null | null | null | test/Vec3Tests.cpp | craft-coder/Softwareentwicklung-2021 | 6c9cf6201b333796a058394c017c8b3e72a3f631 | [
"MIT"
] | 4 | 2021-04-21T13:19:13.000Z | 2021-12-18T20:19:16.000Z | #include "gtest/gtest.h"
#include "Vec3.h"
TEST(Vec3, DefaultConstructor_XisZero) {
raytracer::Vec3 vec{};
double x = vec.x();
EXPECT_NEAR(x, 0.0, 0.00001);
}
TEST(Vec3, DefaultConstructor_YisZero) {
raytracer::Vec3 vec{};
double y = vec.y();
EXPECT_NEAR(y, 0.0, 0.00001);
}
TEST(Vec3, DefaultConstructor_ZisZero) {
raytracer::Vec3 vec{};
double z = vec.z();
EXPECT_NEAR(z, 0.0, 0.00001);
}
| 18.041667 | 40 | 0.630485 | craft-coder |
bfcfdd6082eef7ca753e401c931bbfe6ba4b0adc | 492 | cpp | C++ | basic/09_multidimensional_array/multidimensional_array.cpp | khairanabila/CPP | 48b18b6bf835d8075fc96bbf183adf28a71ba819 | [
"MIT"
] | 23 | 2021-09-10T00:08:48.000Z | 2022-03-24T16:09:30.000Z | basic/09_multidimensional_array/multidimensional_array.cpp | khairanabila/CPP | 48b18b6bf835d8075fc96bbf183adf28a71ba819 | [
"MIT"
] | 20 | 2021-09-21T15:34:21.000Z | 2021-11-28T18:52:10.000Z | basic/09_multidimensional_array/multidimensional_array.cpp | khairanabila/CPP | 48b18b6bf835d8075fc96bbf183adf28a71ba819 | [
"MIT"
] | 27 | 2021-09-10T02:35:56.000Z | 2022-01-24T10:46:06.000Z | #include <iostream>
int main(){
// arr[baris][kolom]
int arr[3][2] = {
{0,1},
{2,3},
{4,5}
};
for(int baris = 0; baris < 3; baris++){
for(int kolom = 0; kolom < 2; kolom++){
std::cout << "arr[" << baris << "][" << kolom << "]: " << arr[baris][kolom] << std::endl;
}
}
/*
Expected Output:
arr[0][0]: 0
arr[0][1]: 1
arr[1][0]: 2
arr[1][1]: 3
arr[2][0]: 4
arr[2][1]: 5
*/
} | 16.965517 | 101 | 0.376016 | khairanabila |
bfd0133a1aaf2601faa26d94b1f7a79c3f4146ff | 72 | cpp | C++ | Algorithmns/gcd.cpp | waba359/VAULT | 5680882f76848f3df19a2f86b55eece5ae9df20f | [
"CC0-1.0"
] | 1 | 2019-12-27T04:06:31.000Z | 2019-12-27T04:06:31.000Z | Algorithmns/gcd.cpp | waba359/VAULT | 5680882f76848f3df19a2f86b55eece5ae9df20f | [
"CC0-1.0"
] | null | null | null | Algorithmns/gcd.cpp | waba359/VAULT | 5680882f76848f3df19a2f86b55eece5ae9df20f | [
"CC0-1.0"
] | null | null | null | ll gcd(ll m, ll n){
if(n == 0) return m;
return gcd(n, m%n);
}
| 14.4 | 25 | 0.472222 | waba359 |
bfd5b33b318b4966638c44135a5aa058c92d3199 | 2,586 | cpp | C++ | writesinglecoildialog.cpp | tonylin0826/ModbusMasterTool | d751126ac4937838660f2684e16c7c04d66481d8 | [
"MIT"
] | null | null | null | writesinglecoildialog.cpp | tonylin0826/ModbusMasterTool | d751126ac4937838660f2684e16c7c04d66481d8 | [
"MIT"
] | null | null | null | writesinglecoildialog.cpp | tonylin0826/ModbusMasterTool | d751126ac4937838660f2684e16c7c04d66481d8 | [
"MIT"
] | null | null | null | #include "writesinglecoildialog.hpp"
#include <QIntValidator>
#include "mainwindow.hpp"
#include "ui_writesinglecoildialog.h"
WriteSingleCoilDialog::WriteSingleCoilDialog(QWidget *parent, quint16 startingAddress)
: QDialog(parent), _ui(new Ui::WriteSingleCoilDialog), _onOffGroup(new QButtonGroup(this)) {
_setupUI(startingAddress);
}
WriteSingleCoilDialog::~WriteSingleCoilDialog() { delete _ui; }
void WriteSingleCoilDialog::on_btnCancel_clicked() { close(); }
void WriteSingleCoilDialog::on_btnSend_clicked() {
if (_ui->inputAddress->text().isEmpty() || _ui->inputSlaveId->text().isEmpty()) {
return;
}
const auto address = _ui->inputAddress->text().toUShort();
const auto slaveId = _ui->inputSlaveId->text().toUShort();
const auto on = _onOffGroup->checkedId() == 1;
const auto modbus = qobject_cast<MainWindow *>(parentWidget())->modbus();
if (!modbus) {
_ui->labelStatus->setText("Failed - Modbus not connected");
_ui->labelStatus->setStyleSheet("QLabel { color : Crimson; }");
return;
}
const auto reply = modbus->sendWriteRequest(
QModbusDataUnit(QModbusDataUnit::RegisterType::Coils, address, QVector<quint16>({on})), slaveId);
if (!reply) {
_ui->labelStatus->setText("Failed - No reply");
_ui->labelStatus->setStyleSheet("QLabel { color : Crimson; }");
return;
}
if (reply->isFinished()) {
delete reply;
return;
}
_ui->labelStatus->setText("Sending");
_ui->labelStatus->setStyleSheet("QLabel { color : DodgerBlue; }");
QObject::connect(reply, &QModbusReply::finished, [=]() {
if (reply->error() != QModbusDevice::NoError) {
_ui->labelStatus->setText(QString("Failed - %1(code: %2)")
.arg(reply->errorString(), QString::number(reply->rawResult().exceptionCode())));
_ui->labelStatus->setStyleSheet("QLabel { color : Crimson; }");
delete reply;
return;
}
_ui->labelStatus->setText("Success");
_ui->labelStatus->setStyleSheet("QLabel { color : Chartreuse; }");
delete reply;
});
}
void WriteSingleCoilDialog::_setupUI(quint16 startingAddress) {
setAttribute(Qt::WA_DeleteOnClose);
_ui->setupUi(this);
setWindowTitle("Write Single Coil");
_ui->inputAddress->setValidator(new QIntValidator(0, 65535, this));
_ui->inputAddress->setText(QString::number(startingAddress));
_ui->inputSlaveId->setText("1");
_ui->inputSlaveId->setValidator(new QIntValidator(0, 255, this));
_onOffGroup->addButton(_ui->btnOff, 0);
_onOffGroup->addButton(_ui->btnOn, 1);
_ui->btnOn->setChecked(true);
}
| 31.925926 | 117 | 0.686775 | tonylin0826 |
bfd926d2b7a35f79596908918ede8b2ed358e86c | 10,174 | cpp | C++ | extension/tpcds/dsdgen/dsdgen-c/w_web_sales.cpp | AldoMyrtaj/duckdb | 3aa4978a2ceab8df25e4b20c388bcd7629de73ed | [
"MIT"
] | 2,816 | 2018-06-26T18:52:52.000Z | 2021-04-06T10:39:15.000Z | extension/tpcds/dsdgen/dsdgen-c/w_web_sales.cpp | AldoMyrtaj/duckdb | 3aa4978a2ceab8df25e4b20c388bcd7629de73ed | [
"MIT"
] | 1,310 | 2021-04-06T16:04:52.000Z | 2022-03-31T13:52:53.000Z | extension/tpcds/dsdgen/dsdgen-c/w_web_sales.cpp | AldoMyrtaj/duckdb | 3aa4978a2ceab8df25e4b20c388bcd7629de73ed | [
"MIT"
] | 270 | 2021-04-09T06:18:28.000Z | 2022-03-31T11:55:37.000Z | /*
* Legal Notice
*
* This document and associated source code (the "Work") is a part of a
* benchmark specification maintained by the TPC.
*
* The TPC reserves all right, title, and interest to the Work as provided
* under U.S. and international laws, including without limitation all patent
* and trademark rights therein.
*
* No Warranty
*
* 1.1 TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE INFORMATION
* CONTAINED HEREIN IS PROVIDED "AS IS" AND WITH ALL FAULTS, AND THE
* AUTHORS AND DEVELOPERS OF THE WORK HEREBY DISCLAIM ALL OTHER
* WARRANTIES AND CONDITIONS, EITHER EXPRESS, IMPLIED OR STATUTORY,
* INCLUDING, BUT NOT LIMITED TO, ANY (IF ANY) IMPLIED WARRANTIES,
* DUTIES OR CONDITIONS OF MERCHANTABILITY, OF FITNESS FOR A PARTICULAR
* PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OF
* WORKMANLIKE EFFORT, OF LACK OF VIRUSES, AND OF LACK OF NEGLIGENCE.
* ALSO, THERE IS NO WARRANTY OR CONDITION OF TITLE, QUIET ENJOYMENT,
* QUIET POSSESSION, CORRESPONDENCE TO DESCRIPTION OR NON-INFRINGEMENT
* WITH REGARD TO THE WORK.
* 1.2 IN NO EVENT WILL ANY AUTHOR OR DEVELOPER OF THE WORK BE LIABLE TO
* ANY OTHER PARTY FOR ANY DAMAGES, INCLUDING BUT NOT LIMITED TO THE
* COST OF PROCURING SUBSTITUTE GOODS OR SERVICES, LOST PROFITS, LOSS
* OF USE, LOSS OF DATA, OR ANY INCIDENTAL, CONSEQUENTIAL, DIRECT,
* INDIRECT, OR SPECIAL DAMAGES WHETHER UNDER CONTRACT, TORT, WARRANTY,
* OR OTHERWISE, ARISING IN ANY WAY OUT OF THIS OR ANY OTHER AGREEMENT
* RELATING TO THE WORK, WHETHER OR NOT SUCH AUTHOR OR DEVELOPER HAD
* ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.
*
* Contributors:
* Gradient Systems
*/
#include "w_web_sales.h"
#include "append_info.h"
#include "build_support.h"
#include "config.h"
#include "constants.h"
#include "date.h"
#include "decimal.h"
#include "genrand.h"
#include "misc.h"
#include "nulls.h"
#include "parallel.h"
#include "permute.h"
#include "porting.h"
#include "pricing.h"
#include "scaling.h"
#include "scd.h"
#include "tables.h"
#include "tdefs.h"
#include "w_web_returns.h"
#include <stdio.h>
struct W_WEB_SALES_TBL g_w_web_sales;
ds_key_t skipDays(int nTable, ds_key_t *pRemainder);
static ds_key_t kNewDateIndex = 0;
static ds_key_t jDate;
static int nItemIndex = 0;
/*
* the validation process requires generating a single lineitem
* so the main mk_xxx routine has been split into a master record portion
* and a detail/lineitem portion.
*/
static void mk_master(void *info_arr, ds_key_t index) {
static decimal_t dMin, dMax;
int nGiftPct;
struct W_WEB_SALES_TBL *r;
static int nItemCount;
r = &g_w_web_sales;
if (!InitConstants::mk_master_init) {
strtodec(&dMin, "1.00");
strtodec(&dMax, "100000.00");
jDate = skipDays(WEB_SALES, &kNewDateIndex);
nItemCount = (int)getIDCount(ITEM);
InitConstants::mk_master_init = 1;
}
/***
* some attributes reamin the same for each lineitem in an order; others are
* different for each lineitem. Since the number of lineitems per order is
* static, we can use a modulo to determine when to change the semi-static
* values
*/
while (index > kNewDateIndex) /* need to move to a new date */
{
jDate += 1;
kNewDateIndex += dateScaling(WEB_SALES, jDate);
}
r->ws_sold_date_sk = mk_join(WS_SOLD_DATE_SK, DATET, 1);
r->ws_sold_time_sk = mk_join(WS_SOLD_TIME_SK, TIME, 1);
r->ws_bill_customer_sk = mk_join(WS_BILL_CUSTOMER_SK, CUSTOMER, 1);
r->ws_bill_cdemo_sk = mk_join(WS_BILL_CDEMO_SK, CUSTOMER_DEMOGRAPHICS, 1);
r->ws_bill_hdemo_sk = mk_join(WS_BILL_HDEMO_SK, HOUSEHOLD_DEMOGRAPHICS, 1);
r->ws_bill_addr_sk = mk_join(WS_BILL_ADDR_SK, CUSTOMER_ADDRESS, 1);
/* most orders are for the ordering customers, some are not */
genrand_integer(&nGiftPct, DIST_UNIFORM, 0, 99, 0, WS_SHIP_CUSTOMER_SK);
if (nGiftPct > WS_GIFT_PCT) {
r->ws_ship_customer_sk = mk_join(WS_SHIP_CUSTOMER_SK, CUSTOMER, 2);
r->ws_ship_cdemo_sk = mk_join(WS_SHIP_CDEMO_SK, CUSTOMER_DEMOGRAPHICS, 2);
r->ws_ship_hdemo_sk = mk_join(WS_SHIP_HDEMO_SK, HOUSEHOLD_DEMOGRAPHICS, 2);
r->ws_ship_addr_sk = mk_join(WS_SHIP_ADDR_SK, CUSTOMER_ADDRESS, 2);
} else {
r->ws_ship_customer_sk = r->ws_bill_customer_sk;
r->ws_ship_cdemo_sk = r->ws_bill_cdemo_sk;
r->ws_ship_hdemo_sk = r->ws_bill_hdemo_sk;
r->ws_ship_addr_sk = r->ws_bill_addr_sk;
}
r->ws_order_number = index;
genrand_integer(&nItemIndex, DIST_UNIFORM, 1, nItemCount, 0, WS_ITEM_SK);
return;
}
static void mk_detail(void *info_arr, int bPrint) {
static int *pItemPermutation, nItemCount;
struct W_WEB_SALES_TBL *r;
int nShipLag, nTemp;
struct W_WEB_RETURNS_TBL w_web_returns;
tdef *pT = getSimpleTdefsByNumber(WEB_SALES);
if (!InitConstants::mk_detail_init) {
jDate = skipDays(WEB_SALES, &kNewDateIndex);
pItemPermutation = makePermutation(NULL, nItemCount = (int)getIDCount(ITEM), WS_PERMUTATION);
InitConstants::mk_detail_init = 1;
}
r = &g_w_web_sales;
nullSet(&pT->kNullBitMap, WS_NULLS);
/* orders are shipped some number of days after they are ordered,
* and not all lineitems ship at the same time
*/
genrand_integer(&nShipLag, DIST_UNIFORM, WS_MIN_SHIP_DELAY, WS_MAX_SHIP_DELAY, 0, WS_SHIP_DATE_SK);
r->ws_ship_date_sk = r->ws_sold_date_sk + nShipLag;
if (++nItemIndex > nItemCount)
nItemIndex = 1;
r->ws_item_sk = matchSCDSK(getPermutationEntry(pItemPermutation, nItemIndex), r->ws_sold_date_sk, ITEM);
/* the web page needs to be valid for the sale date */
r->ws_web_page_sk = mk_join(WS_WEB_PAGE_SK, WEB_PAGE, r->ws_sold_date_sk);
r->ws_web_site_sk = mk_join(WS_WEB_SITE_SK, WEB_SITE, r->ws_sold_date_sk);
r->ws_ship_mode_sk = mk_join(WS_SHIP_MODE_SK, SHIP_MODE, 1);
r->ws_warehouse_sk = mk_join(WS_WAREHOUSE_SK, WAREHOUSE, 1);
r->ws_promo_sk = mk_join(WS_PROMO_SK, PROMOTION, 1);
set_pricing(WS_PRICING, &r->ws_pricing);
/**
* having gone to the trouble to make the sale, now let's see if it gets
* returned
*/
genrand_integer(&nTemp, DIST_UNIFORM, 0, 99, 0, WR_IS_RETURNED);
if (nTemp < WR_RETURN_PCT) {
mk_w_web_returns(&w_web_returns, 1);
struct W_WEB_RETURNS_TBL *rr = &w_web_returns;
void *info = append_info_get(info_arr, WEB_RETURNS);
append_row_start(info);
append_key(info, rr->wr_returned_date_sk);
append_key(info, rr->wr_returned_time_sk);
append_key(info, rr->wr_item_sk);
append_key(info, rr->wr_refunded_customer_sk);
append_key(info, rr->wr_refunded_cdemo_sk);
append_key(info, rr->wr_refunded_hdemo_sk);
append_key(info, rr->wr_refunded_addr_sk);
append_key(info, rr->wr_returning_customer_sk);
append_key(info, rr->wr_returning_cdemo_sk);
append_key(info, rr->wr_returning_hdemo_sk);
append_key(info, rr->wr_returning_addr_sk);
append_key(info, rr->wr_web_page_sk);
append_key(info, rr->wr_reason_sk);
append_key(info, rr->wr_order_number);
append_integer(info, rr->wr_pricing.quantity);
append_decimal(info, &rr->wr_pricing.net_paid);
append_decimal(info, &rr->wr_pricing.ext_tax);
append_decimal(info, &rr->wr_pricing.net_paid_inc_tax);
append_decimal(info, &rr->wr_pricing.fee);
append_decimal(info, &rr->wr_pricing.ext_ship_cost);
append_decimal(info, &rr->wr_pricing.refunded_cash);
append_decimal(info, &rr->wr_pricing.reversed_charge);
append_decimal(info, &rr->wr_pricing.store_credit);
append_decimal(info, &rr->wr_pricing.net_loss);
append_row_end(info);
}
void *info = append_info_get(info_arr, WEB_SALES);
append_row_start(info);
append_key(info, r->ws_sold_date_sk);
append_key(info, r->ws_sold_time_sk);
append_key(info, r->ws_ship_date_sk);
append_key(info, r->ws_item_sk);
append_key(info, r->ws_bill_customer_sk);
append_key(info, r->ws_bill_cdemo_sk);
append_key(info, r->ws_bill_hdemo_sk);
append_key(info, r->ws_bill_addr_sk);
append_key(info, r->ws_ship_customer_sk);
append_key(info, r->ws_ship_cdemo_sk);
append_key(info, r->ws_ship_hdemo_sk);
append_key(info, r->ws_ship_addr_sk);
append_key(info, r->ws_web_page_sk);
append_key(info, r->ws_web_site_sk);
append_key(info, r->ws_ship_mode_sk);
append_key(info, r->ws_warehouse_sk);
append_key(info, r->ws_promo_sk);
append_key(info, r->ws_order_number);
append_integer(info, r->ws_pricing.quantity);
append_decimal(info, &r->ws_pricing.wholesale_cost);
append_decimal(info, &r->ws_pricing.list_price);
append_decimal(info, &r->ws_pricing.sales_price);
append_decimal(info, &r->ws_pricing.ext_discount_amt);
append_decimal(info, &r->ws_pricing.ext_sales_price);
append_decimal(info, &r->ws_pricing.ext_wholesale_cost);
append_decimal(info, &r->ws_pricing.ext_list_price);
append_decimal(info, &r->ws_pricing.ext_tax);
append_decimal(info, &r->ws_pricing.coupon_amt);
append_decimal(info, &r->ws_pricing.ext_ship_cost);
append_decimal(info, &r->ws_pricing.net_paid);
append_decimal(info, &r->ws_pricing.net_paid_inc_tax);
append_decimal(info, &r->ws_pricing.net_paid_inc_ship);
append_decimal(info, &r->ws_pricing.net_paid_inc_ship_tax);
append_decimal(info, &r->ws_pricing.net_profit);
append_row_end(info);
return;
}
/*
* mk_web_sales
*/
int mk_w_web_sales(void *info_arr, ds_key_t index) {
int nLineitems, i;
/* build the static portion of an order */
mk_master(info_arr, index);
/* set the number of lineitems and build them */
genrand_integer(&nLineitems, DIST_UNIFORM, 8, 16, 9, WS_ORDER_NUMBER);
for (i = 1; i <= nLineitems; i++) {
mk_detail(info_arr, 1);
}
/**
* and finally return 1 since we have already printed the rows
*/
return 0;
}
/*
* Routine:
* Purpose:
* Algorithm:
* Data Structures:
*
* Params:
* Returns:
* Called By:
* Calls:
* Assumptions:
* Side Effects:
* TODO: None
*/
int vld_web_sales(int nTable, ds_key_t kRow, int *Permutation) {
int nLineitem, nMaxLineitem, i;
row_skip(nTable, kRow - 1);
row_skip(WEB_RETURNS, (kRow - 1));
jDate = skipDays(WEB_SALES, &kNewDateIndex);
mk_master(NULL, kRow);
genrand_integer(&nMaxLineitem, DIST_UNIFORM, 8, 16, 9, WS_ORDER_NUMBER);
genrand_integer(&nLineitem, DIST_UNIFORM, 1, nMaxLineitem, 0, WS_PRICING_QUANTITY);
for (i = 1; i < nLineitem; i++) {
mk_detail(NULL, 0);
}
mk_detail(NULL, 1);
return (0);
}
| 34.14094 | 105 | 0.743759 | AldoMyrtaj |
bfdd440d5a33f15bffd244b332ee184245e3573f | 1,884 | cpp | C++ | node_modules/nodeimu/RTIMULib2/RTHost/RTIMULibGL/QtGLLib/QtGLPlaneComponent.cpp | RGUCode/pi-sensor | c5219abc3a7557c44bce4f7f8f909fffa00ef071 | [
"MIT"
] | null | null | null | node_modules/nodeimu/RTIMULib2/RTHost/RTIMULibGL/QtGLLib/QtGLPlaneComponent.cpp | RGUCode/pi-sensor | c5219abc3a7557c44bce4f7f8f909fffa00ef071 | [
"MIT"
] | 1 | 2020-07-16T19:00:53.000Z | 2020-07-16T19:00:53.000Z | node_modules/nodeimu/RTIMULib2/RTHost/RTIMULibGL/QtGLLib/QtGLPlaneComponent.cpp | RGUCode/pi-sensor | c5219abc3a7557c44bce4f7f8f909fffa00ef071 | [
"MIT"
] | 1 | 2019-03-23T10:00:55.000Z | 2019-03-23T10:00:55.000Z | ////////////////////////////////////////////////////////////////////////////
//
// This file is part of RTIMULib
//
// Copyright (c) 2014, richards-tech
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
// Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "QtGL.h"
QtGLPlaneComponent::QtGLPlaneComponent()
{
}
QtGLPlaneComponent::~QtGLPlaneComponent()
{
}
void QtGLPlaneComponent::generate(float width, float height)
{
static const float coords[4][2] = {{+0.5f, +0.5f}, {-0.5f, +0.5f}, {-0.5f, -0.5f}, {+0.5f, -0.5f}};
reset();
for (int vert = 0; vert < 4; vert++) {
addTextureCoord(QVector2D(vert == 0 || vert == 3, vert == 0 || vert == 1));
addVertex(QVector3D(width * coords[vert][0], height * coords[vert][1], 0));
}
}
void QtGLPlaneComponent::draw()
{
QtGLComponent::draw(GL_TRIANGLE_FAN);
}
| 36.941176 | 104 | 0.657113 | RGUCode |
bfde6ea67dba61936ee0963ed6f96a32c9adbf84 | 1,241 | cpp | C++ | CPP, C++ Solutions/64. Minimum Path Sum.cpp | arpitkekri/My-Leetcode-Solution-In-CPP | 345f1c53c627fce33ee84672c5d3661863367040 | [
"MIT"
] | 4 | 2021-06-21T04:32:12.000Z | 2021-11-02T04:20:36.000Z | CPP, C++ Solutions/64. Minimum Path Sum.cpp | arpitkekri/My-Leetcode-Solution-In-CPP | 345f1c53c627fce33ee84672c5d3661863367040 | [
"MIT"
] | null | null | null | CPP, C++ Solutions/64. Minimum Path Sum.cpp | arpitkekri/My-Leetcode-Solution-In-CPP | 345f1c53c627fce33ee84672c5d3661863367040 | [
"MIT"
] | 2 | 2021-08-19T11:27:18.000Z | 2021-09-26T14:51:30.000Z | /*********** Method-1(TC - O(NM), SC - O(NM)) **************************************
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> dp(m+1, vector<int>(n+1, INT_MAX));
for(int i = m-1; i >= 0; i--) {
for(int j = n-1; j >= 0; j--) {
if(min(dp[i+1][j], dp[i][j+1]) == INT_MAX)
dp[i][j] = grid[i][j];
else
dp[i][j] = grid[i][j] + min(dp[i+1][j], dp[i][j+1]);
}
}
return dp[0][0];
}
};
***********************************************************************************/
/**********************Method-2 (TC-O(NM), SC-O(N))**************************************/
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
vector<int> dp(n+1, INT_MAX);
// Base case
dp[n-1] = 0;
// Bottom to Top, R to L
for(int i = m-1; i >= 0; i--)
for(int j = n-1; j >= 0; j--)
dp[j] = grid[i][j] + min(dp[j], dp[j+1]);
return dp[0];
}
}; | 30.268293 | 90 | 0.33199 | arpitkekri |
bfe2b3d261d774c1516d7d9ec47526702c9af7c2 | 4,530 | cc | C++ | systems/sensors/test/image_to_lcm_image_array_t_test.cc | RobotLocomotion/drake-python3.7 | ae397a4c6985262d23e9675b9bf3927c08d027f5 | [
"BSD-3-Clause"
] | 2 | 2021-02-25T02:01:02.000Z | 2021-03-17T04:52:04.000Z | systems/sensors/test/image_to_lcm_image_array_t_test.cc | RobotLocomotion/drake-python3.7 | ae397a4c6985262d23e9675b9bf3927c08d027f5 | [
"BSD-3-Clause"
] | null | null | null | systems/sensors/test/image_to_lcm_image_array_t_test.cc | RobotLocomotion/drake-python3.7 | ae397a4c6985262d23e9675b9bf3927c08d027f5 | [
"BSD-3-Clause"
] | 1 | 2021-06-13T12:05:39.000Z | 2021-06-13T12:05:39.000Z | #include "drake/systems/sensors/image_to_lcm_image_array_t.h"
#include <gtest/gtest.h>
#include "drake/lcmt_image_array.hpp"
#include "drake/systems/sensors/image.h"
namespace drake {
namespace systems {
namespace sensors {
namespace {
const char* kColorFrameName = "color_frame_name";
const char* kDepthFrameName = "depth_frame_name";
const char* kLabelFrameName = "label_frame_name";
// Using very tiny image.
const int kImageWidth = 8;
const int kImageHeight = 6;
lcmt_image_array SetUpInputAndOutput(
ImageToLcmImageArrayT* dut, const ImageRgba8U& color_image,
const ImageDepth32F& depth_image, const ImageLabel16I& label_image) {
const InputPort<double>& color_image_input_port =
dut->color_image_input_port();
const InputPort<double>& depth_image_input_port =
dut->depth_image_input_port();
const InputPort<double>& label_image_input_port =
dut->label_image_input_port();
std::unique_ptr<Context<double>> context = dut->CreateDefaultContext();
color_image_input_port.FixValue(context.get(), color_image);
depth_image_input_port.FixValue(context.get(), depth_image);
label_image_input_port.FixValue(context.get(), label_image);
return dut->image_array_t_msg_output_port().
Eval<lcmt_image_array>(*context);
}
GTEST_TEST(ImageToLcmImageArrayT, ValidTest) {
ImageRgba8U color_image(kImageWidth, kImageHeight);
ImageDepth32F depth_image(kImageWidth, kImageHeight);
ImageLabel16I label_image(kImageWidth, kImageHeight);
auto Verify = [color_image, depth_image, label_image](
const ImageToLcmImageArrayT& dut,
const lcmt_image_array& output_image_array,
uint8_t compression_method) {
// Verifyies lcmt_image_array
EXPECT_EQ(output_image_array.header.seq, 0);
EXPECT_EQ(output_image_array.header.utime, 0);
EXPECT_EQ(output_image_array.header.frame_name, "");
EXPECT_EQ(output_image_array.num_images, 3);
EXPECT_EQ(output_image_array.images.size(), 3);
// Verifyies each lcmt_image.
for (auto const& image : output_image_array.images) {
EXPECT_EQ(image.header.seq, 0);
EXPECT_EQ(image.header.utime, 0);
EXPECT_EQ(image.width, kImageWidth);
EXPECT_EQ(image.height, kImageHeight);
EXPECT_EQ(image.data.size(), image.size);
EXPECT_FALSE(image.bigendian);
EXPECT_EQ(image.compression_method, compression_method);
std::string frame_name;
int row_stride;
int8_t pixel_format;
int8_t channel_type;
if (image.pixel_format == lcmt_image::PIXEL_FORMAT_RGBA) {
frame_name = kColorFrameName;
row_stride = color_image.width() * color_image.kNumChannels *
sizeof(*color_image.at(0, 0));
pixel_format = lcmt_image::PIXEL_FORMAT_RGBA;
channel_type = lcmt_image::CHANNEL_TYPE_UINT8;
} else if (image.pixel_format == lcmt_image::PIXEL_FORMAT_DEPTH) {
frame_name = kDepthFrameName;
row_stride = depth_image.width() * depth_image.kNumChannels *
sizeof(*depth_image.at(0, 0));
pixel_format = lcmt_image::PIXEL_FORMAT_DEPTH;
channel_type = lcmt_image::CHANNEL_TYPE_FLOAT32;
} else if (image.pixel_format == lcmt_image::PIXEL_FORMAT_LABEL) {
frame_name = kLabelFrameName;
row_stride = label_image.width() * label_image.kNumChannels *
sizeof(*label_image.at(0, 0));
pixel_format = lcmt_image::PIXEL_FORMAT_LABEL;
channel_type = lcmt_image::CHANNEL_TYPE_INT16;
} else {
EXPECT_FALSE(true);
}
EXPECT_EQ(image.header.frame_name, frame_name);
EXPECT_EQ(image.row_stride, row_stride);
EXPECT_EQ(image.pixel_format, pixel_format);
EXPECT_EQ(image.channel_type, channel_type);
}
};
ImageToLcmImageArrayT dut_compressed(
kColorFrameName, kDepthFrameName, kLabelFrameName, true);
auto image_array_t_compressed = SetUpInputAndOutput(
&dut_compressed, color_image, depth_image, label_image);
Verify(dut_compressed, image_array_t_compressed,
lcmt_image::COMPRESSION_METHOD_ZLIB);
ImageToLcmImageArrayT dut_uncompressed(
kColorFrameName, kDepthFrameName, kLabelFrameName, false);
auto image_array_t_uncompressed = SetUpInputAndOutput(
&dut_uncompressed, color_image, depth_image, label_image);
Verify(dut_uncompressed, image_array_t_uncompressed,
lcmt_image::COMPRESSION_METHOD_NOT_COMPRESSED);
}
} // namespace
} // namespace sensors
} // namespace systems
} // namespace drake
| 38.389831 | 73 | 0.729139 | RobotLocomotion |
bfe3422c9f0d9f28a4a0468c73ae125920403fe9 | 4,273 | cpp | C++ | Samples/Unicode/cppwinrt/Scenario1_FindId.cpp | dujianxin/Windows-universal-samples | d4e95ff0ac408c5d4d980bb18d53fb2c6556a273 | [
"MIT"
] | 2,504 | 2019-05-07T06:56:42.000Z | 2022-03-31T19:37:59.000Z | Samples/Unicode/cppwinrt/Scenario1_FindId.cpp | dujianxin/Windows-universal-samples | d4e95ff0ac408c5d4d980bb18d53fb2c6556a273 | [
"MIT"
] | 314 | 2019-05-08T16:56:30.000Z | 2022-03-21T07:13:45.000Z | Samples/Unicode/cppwinrt/Scenario1_FindId.cpp | dujianxin/Windows-universal-samples | d4e95ff0ac408c5d4d980bb18d53fb2c6556a273 | [
"MIT"
] | 2,219 | 2019-05-07T00:47:26.000Z | 2022-03-30T21:12:31.000Z | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "Scenario1_FindId.h"
#include "Scenario1_FindId.g.cpp"
#include <sstream>
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Data::Text;
using namespace Windows::UI::Xaml;
namespace
{
// This is a helper method that an app could create to find one or all available
// ids within a string. An id begins with a character for which IsIdStart,
// and continues with characters that are IsIdContinue. Invalid sequences are ignored.
std::vector<std::wstring> FindIdsInString(std::wstring_view const& inputString)
{
// Vector where we maintain the ids found in the input string
std::vector<std::wstring> idList;
// Maintains the beginning index of the id found in the input string
size_t indexIdStart = std::wstring_view::npos;
// Iterate through each of the characters in the string
size_t i = 0;
while (i < inputString.size())
{
size_t nextIndex;
uint32_t codepoint = inputString[i];
if (UnicodeCharacters::IsHighSurrogate(codepoint))
{
// If the character is a high surrogate, then the next characters must be a low surrogate.
if ((i < inputString.size()) && (UnicodeCharacters::IsLowSurrogate(inputString[i + 1])))
{
// Update the code point with the surrogate pair.
codepoint = UnicodeCharacters::GetCodepointFromSurrogatePair(codepoint, inputString[i + 1]);
nextIndex = i + 2;
}
else
{
// Warning: High surrogate not followed by low surrogate.
codepoint = 0;
nextIndex = i + 1;
}
}
else
{
// Not a surrogate pair.
nextIndex = i + 1;
}
if (indexIdStart == std::wstring_view::npos)
{
// Not in an id. Have we found an id start?
if (UnicodeCharacters::IsIdStart(codepoint))
{
indexIdStart = i;
}
}
else if (!UnicodeCharacters::IsIdContinue(codepoint))
{
// We have not found an id continue, so the id is complete. We need to
// create the identifier string
idList.emplace_back(inputString.substr(indexIdStart, i - indexIdStart));
// Reset back the index start and re-examine the current code point
// in next iteration
indexIdStart = std::wstring::npos;
nextIndex = i;
}
i = nextIndex;
}
// Do we have a pending id at the end of the string?
if (indexIdStart != std::wstring_view::npos)
{
// We need to create the identifier string
idList.emplace_back(inputString.substr(indexIdStart, i - indexIdStart));
}
// Return the list of identifiers found in the string
return idList;
}
}
namespace winrt::SDKTemplate::implementation
{
Scenario1_FindId::Scenario1_FindId()
{
InitializeComponent();
}
void Scenario1_FindId::Default_Click(IInspectable const&, RoutedEventArgs const&)
{
std::wstringstream result;
bool first = true;
for (auto id : FindIdsInString(TextInput().Text()))
{
if (!first)
{
result << L", ";
}
first = false;
result << id;
}
TextOutput().Text(result.str());
}
}
| 34.739837 | 113 | 0.532179 | dujianxin |
bfe5f2ebfb7e41ccb671ceb9f220e5057f2f4f31 | 9,487 | cc | C++ | src/sst/elements/memHierarchy/cacheArray.cc | zhangyjBU/sst-elements | d2c6725ea5fbb4dd493bf7d1a8c321aea4ff556c | [
"BSD-3-Clause"
] | 2 | 2021-12-24T03:24:33.000Z | 2022-01-11T23:03:39.000Z | src/sst/elements/memHierarchy/cacheArray.cc | zhangyjBU/sst-elements | d2c6725ea5fbb4dd493bf7d1a8c321aea4ff556c | [
"BSD-3-Clause"
] | null | null | null | src/sst/elements/memHierarchy/cacheArray.cc | zhangyjBU/sst-elements | d2c6725ea5fbb4dd493bf7d1a8c321aea4ff556c | [
"BSD-3-Clause"
] | 2 | 2021-05-23T02:28:02.000Z | 2021-09-08T13:38:46.000Z | // Copyright 2009-2018 NTESS. Under the terms
// of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
//
// Copyright (c) 2009-2018, NTESS
// All rights reserved.
//
// Portions are copyright of other developers:
// See the file CONTRIBUTORS.TXT in the top level directory
// the distribution for more information.
//
// This file is part of the SST software package. For license
// information, see the LICENSE file in the top level directory of the
// distribution.
/*
* File: cacheArray.cc
* Author: Caesar De la Paz III
* Email: caesar.sst@gmail.com
*/
#include <sst_config.h>
#include "cacheArray.h"
#include <vector>
namespace SST { namespace MemHierarchy {
/* Set Associative Array Class */
SetAssociativeArray::SetAssociativeArray(Output* dbg, unsigned int numLines, unsigned int lineSize, unsigned int associativity, ReplacementMgr* rm, HashFunction* hf, bool sharersAware) :
CacheArray(dbg, numLines, associativity, lineSize, rm, hf, sharersAware, true)
{
setStates = new State[associativity];
setSharers = new unsigned int[associativity];
setOwned = new bool[associativity];
}
SetAssociativeArray::~SetAssociativeArray() {
delete [] setStates;
delete [] setSharers;
delete [] setOwned;
}
CacheArray::CacheLine* SetAssociativeArray::lookup(const Addr baseAddr, bool update) {
Addr lineAddr = toLineAddr(baseAddr);
int set = hash_->hash(0, lineAddr) % numSets_;
int setBegin = set * associativity_;
int setEnd = setBegin + associativity_;
for (int i = setBegin; i < setEnd; i++) {
if (lines_[i]->getBaseAddr() == baseAddr) {
if (update) replacementMgr_->update(i);
return lines_[i];
}
}
return nullptr;
}
CacheArray::CacheLine* SetAssociativeArray::findReplacementCandidate(const Addr baseAddr, bool cache) {
int index = preReplace(baseAddr);
return lines_[index];
}
unsigned int SetAssociativeArray::preReplace(const Addr baseAddr) {
Addr lineAddr = toLineAddr(baseAddr);
int set = hash_->hash(0, lineAddr) % numSets_;
int setBegin = set * associativity_;
for (unsigned int id = 0; id < associativity_; id++) {
setStates[id] = lines_[id+setBegin]->getState();
setSharers[id] = lines_[id+setBegin]->numSharers();
setOwned[id] = lines_[id+setBegin]->ownerExists();
}
return replacementMgr_->findBestCandidate(setBegin, setStates, setSharers, setOwned, sharersAware_? true: false);
}
void SetAssociativeArray::replace(const Addr baseAddr, CacheArray::CacheLine * candidate, CacheArray::DataLine * dataCandidate) {
unsigned int index = candidate->getIndex();
replacementMgr_->replaced(index);
candidate->reset();
candidate->setBaseAddr(baseAddr);
replacementMgr_->update(index);
}
void SetAssociativeArray::deallocate(unsigned int index) {
replacementMgr_->replaced(index);
lines_[index]->reset();
}
/* Dual Set Associative Array Class */
DualSetAssociativeArray::DualSetAssociativeArray(Output* dbg, unsigned int lineSize, HashFunction * hf, bool sharersAware, unsigned int dirNumLines,
unsigned int dirAssociativity, ReplacementMgr * dirRp, unsigned int cacheNumLines, unsigned int cacheAssociativity, ReplacementMgr * cacheRp) :
CacheArray(dbg, dirNumLines, dirAssociativity, lineSize, dirRp, hf, sharersAware, false)
{
// Set up data cache
cacheNumLines_ = cacheNumLines;
cacheAssociativity_ = cacheAssociativity;
cacheReplacementMgr_ = cacheRp;
cacheNumSets_ = cacheNumLines_ / cacheAssociativity_;
dataLines_.resize(cacheNumLines_);
for (unsigned int i = 0; i < cacheNumLines_; i++) {
dataLines_[i] = new DataLine(lineSize_, i, dbg_);
}
dirSetStates = new State[dirAssociativity];
dirSetSharers = new unsigned int[dirAssociativity];
dirSetOwned = new bool[dirAssociativity];
cacheSetStates = new State[cacheAssociativity];
cacheSetSharers = new unsigned int[cacheAssociativity];
cacheSetOwned = new bool[cacheAssociativity];
}
CacheArray::CacheLine* DualSetAssociativeArray::lookup(const Addr baseAddr, bool update) {
Addr lineAddr = toLineAddr(baseAddr);
int set = hash_->hash(0, lineAddr) % numSets_;
int setBegin = set * associativity_;
int setEnd = setBegin + associativity_;
for (int i = setBegin; i < setEnd; i++) {
if (lines_[i]->getBaseAddr() == baseAddr) {
if (update) {
replacementMgr_->update(i);
if (lines_[i]->getDataLine() != NULL) {
cacheReplacementMgr_->update(lines_[i]->getDataLine()->getIndex());
}
}
return lines_[i];
}
}
return nullptr;
}
CacheArray::CacheLine * DualSetAssociativeArray::findReplacementCandidate(const Addr baseAddr, bool cache) {
int index = cache ? preReplaceDir(baseAddr) : preReplaceCache(baseAddr);
// Handle invalid case for cache allocations -> then dataLines_[index]->getDirLine() == nullptr
// and we can just link that cache entry to the dir entry for baseAddr
if (!cache && dataLines_[index]->getDirLine() == nullptr) {
CacheLine * currentDirEntry = lookup(baseAddr, false);
if (currentDirEntry->getDataLine() != NULL) {
dbg_->fatal(CALL_INFO, -1, "Error: Attempting to allocate a data line for a directory entry that already has an associated data line. Addr = 0x%" PRIx64 "\n", baseAddr);
}
currentDirEntry->setDataLine(dataLines_[index]); // Don't need to set dirLine, "replace" will do that
return currentDirEntry;
}
return cache ? lines_[index] : dataLines_[index]->getDirLine();
}
unsigned int DualSetAssociativeArray::preReplaceDir(const Addr baseAddr) {
Addr lineAddr = toLineAddr(baseAddr);
int set = hash_->hash(0, lineAddr) % numSets_;
int setBegin = set * associativity_;
for (unsigned int id = 0; id < associativity_; id++) {
dirSetStates[id] = lines_[id+setBegin]->getState();
dirSetSharers[id] = lines_[id+setBegin]->numSharers();
dirSetOwned[id] = lines_[id+setBegin]->ownerExists();
}
return replacementMgr_->findBestCandidate(setBegin, dirSetStates, dirSetSharers, dirSetOwned, sharersAware_);
}
void DualSetAssociativeArray::replace(const Addr baseAddr, CacheArray::CacheLine * candidate, CacheArray::DataLine * dataCandidate) {
unsigned int index = candidate->getIndex();
if (dataCandidate == nullptr) {
replacementMgr_->replaced(index);
if (lines_[index]->getDataLine() != NULL) {
deallocateCache(candidate->getDataLine()->getIndex());
}
candidate->reset();
candidate->setBaseAddr(baseAddr);
replacementMgr_->update(index);
} else {
unsigned int dIndex = dataCandidate->getIndex();
cacheReplacementMgr_->replaced(dIndex);
if (dataCandidate->getDirLine() != nullptr) { // break existing dir->data link
dataCandidate->getDirLine()->setDataLine(nullptr);
}
dataCandidate->setDirLine(candidate); // set new dir->data link
candidate->setDataLine(dataCandidate);
cacheReplacementMgr_->update(dIndex);
}
}
unsigned int DualSetAssociativeArray::preReplaceCache(const Addr baseAddr) {
Addr lineAddr = toLineAddr(baseAddr);
int set = hash_->hash(0, lineAddr) % cacheNumSets_;
int setBegin = set * cacheAssociativity_;
for (unsigned int id = 0; id < cacheAssociativity_; id++) {
int dirIndex = dataLines_[id+setBegin]->getDirLine() ? dataLines_[id+setBegin]->getDirLine()->getIndex() : -1;
if (dirIndex == -1) {
cacheSetStates[id] = I;
cacheSetSharers[id] = 0;
cacheSetOwned[id] = false;
} else {
cacheSetStates[id] = lines_[dirIndex]->getState();
cacheSetSharers[id] = lines_[dirIndex]->numSharers();
cacheSetOwned[id] = lines_[dirIndex]->ownerExists();
}
}
return cacheReplacementMgr_->findBestCandidate(setBegin, cacheSetStates, cacheSetSharers, cacheSetOwned, sharersAware_);
}
void DualSetAssociativeArray::deallocateCache(unsigned int index) {
cacheReplacementMgr_->replaced(index);
dataLines_[index]->setDirLine(nullptr);
}
/* Cache Array Class */
void CacheArray::printConfiguration() {
dbg_->debug(_INFO_, "Sets: %d \n", numSets_);
dbg_->debug(_INFO_, "Lines: %d \n", numLines_);
dbg_->debug(_INFO_, "Line size: %d \n", lineSize_);
dbg_->debug(_INFO_, "Associativity: %i \n\n", associativity_);
}
void CacheArray::errorChecking() {
if(0 == numLines_ || 0 == numSets_) dbg_->fatal(CALL_INFO, -1, "Cache size and/or number of sets not greater than zero. Number of lines = %d, Number of sets = %d.\n", numLines_, numSets_);
// TODO relax this, use mod instead of setmask_
if((numSets_ * associativity_) != numLines_) dbg_->fatal(CALL_INFO, -1, "Wrong configuration. Make sure numSets * associativity = Size/cacheLineSize. Number of sets = %d, Associtaivity = %d, Number of lines = %d.\n", numSets_, associativity_, numLines_);
if(associativity_ < 1) dbg_->fatal(CALL_INFO, -1, "Associativity has to be greater than zero. Associativity = %d\n", associativity_);
}
}}
| 41.427948 | 259 | 0.669969 | zhangyjBU |
bfe8092373db4769d07f6d063b60453bcc14305a | 3,886 | cpp | C++ | QuoteGeneration/qpl/linux/x509.cpp | LeoneChen/SGXDataCenterAttestationPrimitives | 5a94eb0085f05ed5e8738fcbce59a2d42ee6b9e6 | [
"BSD-3-Clause"
] | 156 | 2018-09-06T07:19:23.000Z | 2022-03-30T19:01:40.000Z | QuoteGeneration/qpl/linux/x509.cpp | LeoneChen/SGXDataCenterAttestationPrimitives | 5a94eb0085f05ed5e8738fcbce59a2d42ee6b9e6 | [
"BSD-3-Clause"
] | 136 | 2018-10-02T00:58:26.000Z | 2022-03-21T08:45:25.000Z | QuoteGeneration/qpl/linux/x509.cpp | LeoneChen/SGXDataCenterAttestationPrimitives | 5a94eb0085f05ed5e8738fcbce59a2d42ee6b9e6 | [
"BSD-3-Clause"
] | 109 | 2018-10-01T19:09:58.000Z | 2022-03-29T13:33:51.000Z | /*
* Copyright (C) 2011-2021 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation 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: x509.cpp
*
* Description: X.509 parser
*
*/
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <iostream>
#include <sstream>
#include <vector>
#include <map>
#include <string>
#include <string.h>
using std::cout;
using std::endl;
using std::map;
using std::string;
using std::stringstream;
using std::vector;
//----------------------------------------------------------------------
static vector<string> crl_urls(X509 *x509)
{
vector<string> list;
int nid = NID_crl_distribution_points;
STACK_OF(DIST_POINT) *dist_points = (STACK_OF(DIST_POINT) *)X509_get_ext_d2i(x509, nid, NULL, NULL);
for (int j = 0; j < sk_DIST_POINT_num(dist_points); j++)
{
DIST_POINT *dp = sk_DIST_POINT_value(dist_points, j);
DIST_POINT_NAME *distpoint = dp->distpoint;
if (distpoint->type == 0)
{
for (int k = 0; k < sk_GENERAL_NAME_num(distpoint->name.fullname); k++)
{
GENERAL_NAME *gen = sk_GENERAL_NAME_value(distpoint->name.fullname, k);
ASN1_IA5STRING *asn1_str = gen->d.uniformResourceIdentifier;
list.push_back(string((char *)ASN1_STRING_get0_data(asn1_str), ASN1_STRING_length(asn1_str)));
}
}
else if (distpoint->type == 1)
{
STACK_OF(X509_NAME_ENTRY) *sk_relname = distpoint->name.relativename;
for (int k = 0; k < sk_X509_NAME_ENTRY_num(sk_relname); k++)
{
X509_NAME_ENTRY *e = sk_X509_NAME_ENTRY_value(sk_relname, k);
ASN1_STRING *d = X509_NAME_ENTRY_get_data(e);
list.push_back(string((char *)ASN1_STRING_get0_data(d), ASN1_STRING_length(d)));
}
}
}
CRL_DIST_POINTS_free(dist_points);
return list;
}
std::string get_cdp_url_from_pem_cert(const char *p_cert)
{
std::string cdp_url = "";
// To use X509 function group
OpenSSL_add_all_algorithms();
BIO *bio_mem = BIO_new(BIO_s_mem());
BIO_puts(bio_mem, p_cert);
X509 *x509 = PEM_read_bio_X509(bio_mem, NULL, NULL, NULL);
vector<string> crls = crl_urls(x509);
if (crls.size() > 0)
cdp_url = crls[0];
BIO_free(bio_mem);
X509_free(x509);
return cdp_url;
}
| 35.651376 | 110 | 0.670612 | LeoneChen |
bfead6a5f4cdcf2f1fa8f643c0339f40e3bb7655 | 3,146 | cc | C++ | uncores/lmac/src/core2/lmac_core_top.cc | tinochinamora/iw_imdb | 89964024bee7f8eaaa25530a8d40155251345be0 | [
"MIT"
] | 3 | 2021-09-10T08:14:45.000Z | 2022-02-25T04:53:12.000Z | uncores/lmac/src/core2/lmac_core_top.cc | PrincetonUniversity/ILA-Modeling-Verification | 88964aad8c465c9da82f1ec66425da9f16fc8d29 | [
"MIT"
] | 1 | 2019-06-12T07:02:31.000Z | 2019-06-12T07:02:31.000Z | uncores/lmac/src/core2/lmac_core_top.cc | PrincetonUniversity/ILA-Modeling-Verification | 88964aad8c465c9da82f1ec66425da9f16fc8d29 | [
"MIT"
] | 2 | 2021-09-21T22:15:26.000Z | 2021-10-31T11:24:43.000Z | // ============================================================================
// Instruction-Level Abstraction of LeWiz Communications Ethernet MAC
//
// This Instruction-Level Abstraction (ILA) description is derived based on the
// LeWiz Communications Ethernet MAC (LMAC), which is licensed under GNU LGPL.
// Check "LICENSE" which comes with this distribution for more information.
// ============================================================================
//
// File Name: lmac_core_top.cc
// LmacCore2 top level entry points
// - TX FIFO
// - RX FIFO
// - Register interface and configuration
// - PHY
#include <lmac/core2/lmac_core_top.h>
#include <ilang/util/log.h>
#include <lmac/core2/configs.h>
namespace ilang {
LmacCore2::LmacCore2() {}
LmacCore2::~LmacCore2() {}
Ila LmacCore2::New(const std::string& name) {
ILA_DLOG("LMAC") << "Create ILA with name " << name;
auto m = Ila(name);
// state vars
SetArchStateVar(m);
SetImplStateVar(m);
// model hierarchy
SetChild(m);
// instruction decode & updates
SetInstr(m);
// initial condition
SetInit(m);
{ // valid
// TX FIFO
auto tx_valid = (m.input(TX_WE) == TX_WE_V_VALID) &
(m.state(TXFIFO_FULL) != TXFIFO_FULL_V_FULL);
// RX FIFO
auto rx_valid = true;
// Reg interface
auto reg_itf_valid = (m.input(REG_RD_START) == REG_RD_START_V_BUSY) &
(m.input(HOST_ADDR) >= FMAC_TX_PKT_CNT_ADDR) &
(m.input(HOST_ADDR) <= FMAC_RX_PKT_CNT1518_HI_ADDR);
// PHY
auto phy_valid = true;
auto valid = tx_valid | rx_valid | reg_itf_valid | phy_valid;
m.SetValid(valid);
}
{ // fetch
// TX FIFO
auto tx_fetch = (m.input(TX_WE));
// RX FIFO
auto rx_fetch = BoolConst(true);
// Reg interface
auto reg_fetch = BoolConst(true);
// PHY
auto phy_fetch = BoolConst(true);
auto fetch =
Concat(tx_fetch, Concat(rx_fetch, Concat(reg_fetch, phy_fetch)));
m.SetFetch(fetch);
}
ILA_DLOG("LMAC") << "Done";
return m;
}
void LmacCore2::SetArchStateVar(Ila& m) {
ILA_DLOG("LMAC") << "Setup state variables from spec.";
// TX interface signals
SetupTxInterface(m);
// RX interface signals
SetupRxInterface(m);
// Register interface and configuration
SetupRegInterface(m);
SetupMmioRegs(m);
// PHY interface signals
return;
}
void LmacCore2::SetImplStateVar(Ila& m) {
ILA_DLOG("LMAC") << "Setup state variables (impl. specific)";
// TX FIFO internal states
#if 0 // TODO
SetupTxInternal(m);
#endif
// RX FIFO internal states
// Register and configuration
// PHY internal states
return;
}
void LmacCore2::SetChild(Ila& m) {
ILA_DLOG("LMAC") << "Setup child ILAs";
return;
}
void LmacCore2::SetInstr(Ila& m) {
ILA_DLOG("LMAC") << "Setup instructions";
// TX FIFO instructions
SetupTxInstr(m);
// RX FIFO instructions
// Register and configuration instructions
SetupRegInstr(m);
// PHY instructions
return;
}
void LmacCore2::SetInit(Ila& m) {
ILA_DLOG("LMAC") << "Setup initial condition";
return;
}
}; // namespace ilang
| 20.973333 | 79 | 0.620788 | tinochinamora |
bfefb2d820718c89ee8b6674b9b43b9655a2308c | 12,264 | hpp | C++ | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/svl/detail/graphics_impl.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/svl/detail/graphics_impl.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/svl/detail/graphics_impl.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null |
namespace svl {
namespace graphics
{
pen::pen(color colour)
: pen_( win32::create_pen(PS_SOLID, 1, win32::rgb_from_color(colour) ))
{}
pen::pen(color colour, unsigned width)
: pen_( win32::create_pen(PS_SOLID, static_cast<int>(width), win32::rgb_from_color(colour) ))
{}
pen::pen(pen const& other)
: pen_( other.pen_ )
{}
pen& pen::operator = (pen const& other)
{
pen_ = other.pen_;
return *this;
}
pen::~pen()
{}
HPEN pen::win32_handle() const
{
return pen_;
}
pen::pen(HPEN hpen, win32::system_object_t)
: pen_( hpen, win32::system_object )
{}
/*----------------------------------------------------------------------*/
brush::brush(color colour)
: brush_( win32::create_solid_brush( win32::rgb_from_color(colour) ))
{}
brush::brush(brush const& other)
: brush_( other.brush_ )
{}
brush& brush::operator = (brush const& other)
{
brush_ = other.brush_;
return *this;
}
HBRUSH brush::win32_handle() const
{
return brush_;
}
brush::~brush()
{}
brush::brush(HBRUSH hbrush, win32::system_object_t)
: brush_( hbrush, win32::system_object )
{}
brush const brush::transparent = brush( win32::get_stock_object<HBRUSH>(HOLLOW_BRUSH), win32::system_object );
/*----------------------------------------------------------------------*/
font::font(str_ref name, int height, unsigned styles)
: font_( create_font( name, height, styles ))
{}
font::font(font const& other)
: font_( other.font_ )
{}
font& font::operator = (font const& other)
{
font_ = other.font_;
return *this;
}
HFONT font::create_font(str_ref name, int height, unsigned styles)
{
HFONT hfont = SVL_MS(CreateFont)(
/* nHeight */ height,
/* nWidth */ 0,
/* nEscapement */ 0,
/* nOrientation */ 0,
/* fnWeight */ (styles & font::bold) ? FW_BOLD : FW_NORMAL,
/* fdwItalic */ (styles & font::italic) ? TRUE : FALSE,
/* fdwUnderline */ (styles & font::underline) ? TRUE : FALSE,
/* fdwStrikeOut */ FALSE,
/* fdwCharSet */ ANSI_CHARSET,
/* fdwOutputPrecision */ OUT_DEFAULT_PRECIS,
/* fdwClipPrecision */ CLIP_DEFAULT_PRECIS,
/* fdwQuality */ DEFAULT_QUALITY,
/* fdwPitchAndFamily */ DEFAULT_PITCH,
/* lpszFace */ name.data());
if (hfont == 0)
throw win32_error( "CreateFont" );
return hfont;
}
HFONT font::win32_handle() const
{
return font_;
}
font::~font()
{}
font::font(HFONT hfont, win32::system_object_t)
: font_( hfont, win32::system_object )
{}
font const font::def = font( win32::get_stock_object<HFONT>(DEFAULT_GUI_FONT), win32::system_object );
/*----------------------------------------------------------------------*/
edge::edge(border::type outer, border::type inner, unsigned lines)
: borders_( outer | +inner << 2 )
, lines_( lines )
{}
edge::border::type edge::outer() const
{
return static_cast<border::type>( borders_ & 0x03 );
}
edge::border::type edge::inner() const
{
return static_cast<border::type>( borders_ >> 2 );
}
unsigned edge::lines() const
{
return lines_;
}
unsigned edge::borders() const
{
return borders_;
}
edge edge::none = edge( edge::border::none );
edge edge::bump = edge( edge::border::raised, edge::border::sunken );
edge edge::etched = edge( edge::border::sunken, edge::border::raised );
edge edge::raised = edge( edge::border::raised, edge::border::raised );
edge edge::sunken = edge( edge::border::sunken, edge::border::sunken );
/*----------------------------------------------------------------------*/
painting::painting()
: def_pen_ ( 0 )
, cur_pen_ ( 0 )
, def_brush_( 0 )
, cur_brush_( 0 )
, def_font_ ( 0 )
, cur_font_ ( 0 )
{
SVL_IN_DEBUG_2( hdc_ = 0; )
}
painting::~painting()
{
SVL_ASSERT_2( hdc_ == 0 );
}
void painting::open( HDC hdc ) // throw()
{
SVL_ASSERT_2( hdc_ == 0 );
hdc_ = hdc;
}
void painting::close() // throw()
{
if (def_pen_ != 0)
win32::select_object<std::nothrow_t>( hdc_, def_pen_ );
if (def_brush_ != 0)
win32::select_object<std::nothrow_t>( hdc_, def_brush_ );
if (def_font_ != 0)
win32::select_object<std::nothrow_t>( hdc_, def_font_ );
SVL_IN_DEBUG_2( hdc_ = 0; )
}
void painting::select(pen const& p)
{
HPEN hpen = p.win32_handle();
if (hpen != cur_pen_)
{
HGDIOBJ prev = win32::select_object( hdc_, hpen );
cur_pen_ = hpen;
if (def_pen_ == 0)
def_pen_ = prev;
}
}
void painting::select(brush const& b)
{
HBRUSH hbrush = b.win32_handle();
if (hbrush != cur_brush_)
{
HGDIOBJ prev = win32::select_object( hdc_, hbrush );
cur_brush_ = hbrush;
if (def_brush_ == 0)
def_brush_ = prev;
}
}
void painting::select(font const& f)
{
HFONT hfont = f.win32_handle();
if (hfont != cur_font_)
{
HGDIOBJ prev = win32::select_object( hdc_, hfont );
cur_font_ = hfont;
if (def_font_ == 0)
def_font_ = prev;
}
}
HDC painting::win32_handle() const
{
return hdc_;
}
void painting::draw_pixel(point const& p, color c)
{
::SetPixel( hdc_, p.x, p.y, win32::rgb_from_color(c) );
}
void painting::move_to(point const& pos)
{
SVL_VERIFY( ::MoveToEx( hdc_, pos.x, pos.y, 0 ), != 0 );
}
void painting::draw_line_to(point const& pos, pen const& p)
{
select( p );
SVL_VERIFY( ::LineTo( hdc_, pos.x, pos.y ), != 0 );
}
void painting::draw_line(point const& from, point const& to, pen const& p)
{
move_to( from );
draw_line_to( to, p );
}
void painting::draw_rectangle(rect2 const& r, brush const& b)
{
RECT R = win32::from_rect2( r );
SVL_VERIFY( ::FillRect( hdc_, &R, b.win32_handle() ), != 0 );
}
void painting::draw_rectangle(rect2 const& r, pen const& p, brush const& b)
{
select( p );
select( b );
SVL_VERIFY( ::Rectangle( hdc_, r.x0, r.y0, r.x1, r.y1 ), != 0 );
}
void painting::draw_round_rect(rect2 const& r, size const& ell_sz, pen const& p, brush const& b)
{
select( p );
select( b );
SVL_VERIFY( ::RoundRect( hdc_, r.x0, r.y0, r.x1, r.y1, ell_sz.dx, ell_sz.dy ), != 0 );
}
void painting::draw_ellipse(rect2 const& r, pen const& p, brush const& b)
{
select( p );
select( b );
SVL_VERIFY( ::Ellipse( hdc_, r.x0, r.y0, r.x1, r.y1 ), != 0 );
}
void painting::draw_pie( rect2 const& r, point const& p0, point const& p1, pen const& p, brush const& b )
{
select( p );
select( b );
SVL_VERIFY( ::Pie( hdc_, r.x0, r.y0, r.x1, r.y1, p0.x, p0.y, p1.x, p1.y ), != 0 );
}
point painting::draw_text(str_ref str, point const& p, font const& f, color text_color, color back_color)
{
select( f );
SVL_VERIFY( ::SetTextAlign( hdc_, TA_LEFT | TA_TOP | TA_UPDATECP ), != GDI_ERROR );
SVL_VERIFY( ::SetTextColor( hdc_, win32::rgb_from_color(text_color)), != CLR_INVALID );
if (back_color.argb() == color::transparent)
{
SVL_VERIFY( ::SetBkMode( hdc_, TRANSPARENT ), != 0 );
}
else
{
SVL_VERIFY( ::SetBkColor( hdc_, win32::rgb_from_color(back_color) ), != CLR_INVALID );
SVL_VERIFY( ::SetBkMode( hdc_, OPAQUE ), != 0 );
}
SVL_VERIFY( ::MoveToEx( hdc_, p.x, p.y, 0 ), != 0 );
SVL_VERIFY( SVL_MS(TextOut)( hdc_, 0, 0, str.data(), static_cast<int>(str.size()) ), != 0 );
POINT P;
SVL_VERIFY( ::MoveToEx( hdc_, 0, 0, &P ), != 0 );
return win32::to_point( P );
}
void painting::draw_text(str_ref str, rect2 const& r, text::format frmt, font const& f, color text_color, color back_color)
{
select( f );
SVL_VERIFY( ::SetTextAlign( hdc_, TA_LEFT | TA_TOP | TA_NOUPDATECP ), != GDI_ERROR );
SVL_VERIFY( ::SetTextColor( hdc_, win32::rgb_from_color(text_color)), != CLR_INVALID );
if (back_color.argb() == color::transparent)
{
SVL_VERIFY( ::SetBkMode( hdc_, TRANSPARENT ), != 0 );
}
else
{
SVL_VERIFY( ::SetBkColor( hdc_, win32::rgb_from_color(back_color) ), != CLR_INVALID );
SVL_VERIFY( ::SetBkMode( hdc_, OPAQUE ), != 0 );
}
RECT R = win32::from_rect2( r );
SVL_MS(DrawText)( hdc_, str.data(), static_cast<int>( str.size() ), &R, frmt );
}
void painting::draw(edge e, rect2 const& r)
{
RECT R = win32::from_rect2( r );
SVL_VERIFY( ::DrawEdge( hdc_, &R, e.borders(), e.lines() ), != 0 );
}
void painting::draw(image const& img, point const& p)
{
draw( img, p, rect(point(0,0), img.size()) );
}
void painting::draw(image const& img, point const& p, rect const& r)
{
win32::compatible_dc mem_dc( win32_handle() );
HGDIOBJ def_bitmap = win32::select_object( mem_dc.handle(), img.win32_handle() );
SVL_VERIFY( ::BitBlt( win32_handle(), p.x, p.y, r.dx, r.dy, mem_dc.handle(), r.x, r.y, SRCCOPY ), != 0 );
win32::select_object<std::nothrow_t>( mem_dc.handle(), def_bitmap );
}
/*----------------------------------------------------------------------*/
canvas::canvas(window& wnd)
{
hwnd_ = wnd.win32_handle();
HDC hdc = wnd.get_env().device_contexts.find( wnd );
own_ = hdc == 0;
if (own_)
hdc = win32::dc::get( hwnd_ );
open( hdc );
}
canvas::~canvas()
{
HDC hdc = win32_handle();
close();
if (own_)
win32::dc::release( hwnd_, hdc );
}
/*----------------------------------------------------------------------*/
image::image( svl::size const& sz)
: bitmap_( 0, win32::system_object )
, size_ ( sz )
{
resize( sz );
}
image::~image()
{}
size image::size() const
{
return size_;
}
void image::resize(svl::size const& sz)
{
if ( 0 < sz.dx && 0 < sz.dy )
{
win32::dc dc( svl::detail::env::shared_instance()->sys_window );
win32::gdi_object<HBITMAP> new_bitmap(
win32::create_compatible_bitmap(dc.handle(), sz.dx, sz.dy )
);
bitmap_.swap( new_bitmap );
size_ = sz;
}
else
{
win32::gdi_object<HBITMAP> empty_bitmap( 0, win32::system_object );
bitmap_.swap( empty_bitmap );
size_ = svl::size( 0, 0 );
}
}
HBITMAP image::win32_handle() const
{
return bitmap_;
}
/*----------------------------------------------------------------------*/
image_canvas::image_canvas(image& img)
: bitmap_( img.bitmap_ )
{
win32::dc dc( svl::detail::env::shared_instance()->sys_window );
win32::compatible_dc mem_dc( dc.handle() );
open( mem_dc.handle() );
def_bitmap_ = win32::select_object( mem_dc.handle(), bitmap_ );
mem_dc.detach();
}
image_canvas::~image_canvas()
{
HDC hdc = win32_handle();
close();
win32::select_object<std::nothrow_t>( hdc, def_bitmap_ );
win32::compatible_dc::delete_dc( hdc );
}
/*----------------------------------------------------------------------*/
image& buffered_canvas::shared_image()
{
return svl::detail::env::shared_instance()->shared_image;
}
image& buffered_canvas::widen(image& img, size const& sz)
{
size img_size = img.size();
if (img_size.dx < sz.dx || img_size.dy < sz.dy)
{
img_size = size(
(std::max)(img_size.dx, sz.dx),
(std::max)(img_size.dy, sz.dy)
);
img.resize( img_size );
}
return img;
}
buffered_canvas::buffered_canvas(window& w, image& img)
: size_( w.size() )
, bitmap_( widen( img, size_ ).bitmap_ )
, hwnd_( w.win32_handle() )
{
wnd_hdc_ = w.get_env().device_contexts.find( w );
own_ = wnd_hdc_ == 0;
if (own_)
wnd_hdc_ = win32::dc::get( hwnd_ );
try
{
win32::compatible_dc mem_dc( wnd_hdc_ );
open( mem_dc.handle() );
def_bitmap_ = win32::select_object( mem_dc.handle(), bitmap_ );
mem_dc.detach();
}
catch (...)
{
if (own_)
win32::dc::release( hwnd_, wnd_hdc_ );
throw;
}
}
buffered_canvas::~buffered_canvas()
{
try
{
flush();
}
catch (...)
{
SVL_ASSERT_FALSE();
}
HDC mem_hdc = win32_handle();
close();
win32::select_object<std::nothrow_t>( mem_hdc, def_bitmap_ );
win32::compatible_dc::delete_dc( mem_hdc );
if (own_)
win32::dc::release( hwnd_, wnd_hdc_ );
}
void buffered_canvas::flush()
{
SVL_VERIFY( ::BitBlt( wnd_hdc_, 0, 0, size_.dx, size_.dy, win32_handle(), 0, 0, SRCCOPY ), != 0 );
}
void buffered_canvas::fill_window_area(brush const& b)
{
draw_rectangle( rect2(0, 0, size_.dx, size_.dy), b );
}
void buffered_canvas::fill_window_area()
{
HBRUSH hbrush = reinterpret_cast<HBRUSH>(
SVL_MS(GetClassLongPtr)( hwnd_, GCLP_HBRBACKGROUND )
);
if (hbrush != 0)
fill_window_area( brush(hbrush, win32::system_object) );
}
}}
| 23.584615 | 124 | 0.595401 | yklishevich |
bff0487727502bcf7237bc13320e3f364972bf26 | 23,065 | cpp | C++ | sources/libcpp83gts_callback_and_action/cb_trace_files.cpp | Savraska2/GTS | 78c8b4d634f1379eb3e33642716717f53bf7e1ad | [
"BSD-3-Clause"
] | 61 | 2016-03-26T03:04:43.000Z | 2021-09-17T02:11:18.000Z | sources/libcpp83gts_callback_and_action/cb_trace_files.cpp | sahwar/GTS | b25734116ea81eb0d7e2eabc8ce16cdd1c8b22dd | [
"BSD-3-Clause"
] | 92 | 2016-04-10T23:40:22.000Z | 2022-03-11T21:49:12.000Z | sources/libcpp83gts_callback_and_action/cb_trace_files.cpp | sahwar/GTS | b25734116ea81eb0d7e2eabc8ce16cdd1c8b22dd | [
"BSD-3-Clause"
] | 18 | 2016-03-26T11:19:14.000Z | 2021-08-07T00:26:02.000Z | #include <cstdio> // std::rename(-)
#include <iostream> // std::cout
#include <sstream> // std::ostringstream
#include <iomanip> // std::setfill(-) ,std::setw(-)
#include <FL/fl_ask.H> // fl_alert(-) fl_input(-)
#include "pri.h"
#include "ptbl_returncode.h"
#include "osapi_exist.h"
#ifdef _WIN32
#include "osapi_mbs_wcs.h" // osapi::cp932_from_utf8(-)
#endif
#include "ids_path_fltk_native_browse.h"
#ifdef _WIN32
#include "wincom_native_browse_directory.h"
#endif
#include "ids_path_level_from_files.h"
#include "cb_trace_files.h"
#include "gts_gui.h"
#include "gts_master.h"
//----------------------------------------------------------------------
/* 2値化処理実行 */
int cb_trace_files::read_and_save_crnt_(
const int file_num
,const int list_num
)
{
/* 表示:リストを対象項目が見える場所にスクロール */
cl_gts_gui.selbro_number_list->middleline(list_num);
/* 読込:番号に対するファイルパスを得る */
std::string fpath_open( this->get_open_path(file_num) );
if (fpath_open.empty()) {
pri_funct_err_bttvr(
"Error : this->get_open_path(%d) returns nullptr"
, file_num
);
return NG;
}
/* 読込:ファイルがあるかチェック */
if ( osapi::exist_utf8_mbs( fpath_open ) == false ) {
pri_funct_msg_ttvr(
"Error : Not exist \"%s\"",fpath_open.c_str());
return NG;
}
/* 読込:ファイルパスを設定 */
if (cl_gts_master.cl_iip_read.cl_name.set_name(fpath_open.c_str())
!= OK) {
pri_funct_err_bttvr(
"Error : cl_gts_master.cl_iip_read.cl_name.set_name(%s) returns NG",
fpath_open.c_str());
return NG;
}
/* 読込 */
if (cl_gts_master.cl_iip_read.file() != OK) {
pri_funct_err_bttvr(
"Error : cl_gts_master.cl_iip_read.file() returns NG" );
return NG;
}
/* 読込:画像はフルカラーであること */
if (cl_gts_master.cl_iip_read.get_l_channels() < 3) {
pri_funct_err_bttvr(
"Error : cl_gts_master.cl_iip_read.get_l_channels() is less than 3" );
return NG;
}
/* Crop以外の画像表示をした場合 */
cl_gts_master.cl_area_and_rot90.reset_dpi_to_zero_by_scan_or_preview();
/* 処理:Rot90 and Effects(color Trace and Erase color dot noise) */
if (cl_gts_master.rot_and_trace_and_enoise(
&(cl_gts_master.cl_iip_read)
,0 /* 画像コンバート処理のみで、回転はしない */
) != OK) {
return NG;
}
/* 保存:番号に対するファイルパスを得る */
std::string fpath_save( this->get_save_path(file_num) );
if (fpath_save.empty()) {
pri_funct_err_bttvr(
"Error : this->get_save_path(%d) returns empty"
, file_num
);
return NG;
}
/* 保存 */
if (OK != cl_gts_master.iipg_save(
&(cl_gts_master.cl_iip_trac)
, const_cast<char *>(fpath_save.c_str())
, cl_gts_master.cl_iip_read.get_d_tif_dpi_x()
/* rot90実行後なので(デフォルト)0度とする */
/* (デフォルト)なしとする、
&(cl_gts_master.cl_iip_read)は参照しない */
)) {
pri_funct_err_bttvr(
"Error : cl_gts_master.iipg_save(-) returns NG" );
return NG;
}
/* 表示:リストにマーク付いていなければ付ける */
cl_gts_master.cl_number.add_S( list_num );
/* 表示:リストの選択解除 */
cl_gts_master.cl_number.unselect(list_num);
/* 表示:画像の再表示 */
if (cl_gts_master.redraw_image(
&(cl_gts_master.cl_iip_read)
, false /* crop sw */
, false /* force view scanimage sw */
)) {
return NG;
}
/* 表示:保存するタイプで画像を表示する */
if ( cl_gts_gui.chkbtn_trace_filter_trace_sw->value() ) {
/* TracenImage画像のみ表示 */
cl_gts_master.cb_change_wview_sub();
/* 画像表示状態をメニューに設定 */
cl_gts_gui.menite_wview_sub->setonly();
}
else {
/* ScanImage(メイン)画像のみ表示 */
cl_gts_master.cb_change_wview_main();
/* 画像表示状態をメニューに設定 */
cl_gts_gui.menite_wview_main->setonly();
}
return OK;
}
int cb_trace_files::cb_start( const bool interactive_sw )
{
if ( !cl_gts_master.cl_number.is_trace() ) {
fl_alert("Set Number for Trace");
return OK;
}
/* チェック:開くファイルのLevel名がない */
{
std::string name(cl_gts_gui.strinp_trace_open_file_head->value());
if ( name.empty() ) {
fl_alert("Need Trace Open Name!");
return NG;
}
}
/* チェック:保存ファイルのLevel名がない */
{
std::string name(cl_gts_gui.strinp_trace_save_file_head->value());
if ( name.empty() ) {
fl_alert("Need Trace Save Name!");
return NG;
}
}
/* チェック:開くファイル名がない */
if (this->get_open_path(0).empty()) {
fl_alert("Check Open Folder and File name!");
return NG;
}
/* チェック:保存ファイル名がない */
if (this->get_save_path(0).empty()) {
fl_alert("Check Save Folder and File name!");
return NG;
}
/* 順送り(start <= end)の初期位置 */
cb_number &cl_num = cl_gts_master.cl_number;
int list_num = cl_num.next_selected_list_num(1);
/* チェック:番号選択がない */
if (list_num < 1) {
fl_alert("Select Number!");
return NG;
}
/* 順送り(start <= end)の初期番号 */
int file_num = cl_num.file_num_from_list_num(list_num);
/* 実行確認 */
if (interactive_sw) {
const bool tsw =
cl_gts_gui.chkbtn_trace_filter_trace_sw->value() != 0;
const bool esw =
cl_gts_gui.chkbtn_trace_filter_erase_dot_noise_sw->value() != 0;
if (fl_ask(
"%s%s\n%s\n-->\n%s\n..."
,tsw ?"Trace" :"Not trace"
,esw ?" and Erase Dot Noise" :""
,this->get_open_path(file_num).c_str()
,this->get_save_path(file_num).c_str()
) != 1) {
return OK; // Cancel
}
}
while (1 <= list_num) {
/* カレントの読み込みと処理と保存をして */
if (OK != this->read_and_save_crnt_( file_num ,list_num )) {
pri_funct_err_bttvr(
"Error : this->read_and_save_crnt_() returns NG" );
return NG;
}
/* 次を得る */
list_num = cl_num.next_selected_list_num( list_num + 1 );
file_num = cl_num.file_num_from_list_num( list_num );
Fl::check();
const int ekey = Fl::event_key();
/* FL_Escapeと'q'と't'は効かない */
//if (FL_Escape == ekey) {
//if ('q' == ekey) {
//if ('t' == ekey) { /* Tで開始し、tで終る */
if ('e' == ekey) {
break;
}
}
return OK;
}
//----------------------------------------------------------------------
/* rename/renumber処理実行 */
void cb_trace_files::cb_rename(void)
{
/* Openファイルのフルパスを得る */
const std::string filepath = this->get_open_path( 1 );
if (filepath.empty()) {
fl_alert( "Not set Open Folder or File name" );
return;
}
/* 連番ファイルの存在チェックして必要な情報に変える */
std::string dpath , head , num , ext;
int number=-1;
std::vector<int> nums;
ids::path::level_from_files(
filepath ,dpath ,head ,num ,number ,ext ,nums
);
if (head.empty() || nums.size() <= 0) {
fl_alert( "Not exist files" );
return;
}
std::ostringstream numost;
for (auto nu : nums) {
numost << nu;
numost << " ";
}
/* ユーザーから新しい名前を得る */
const char* new_head_ptr = fl_input(
"Enter New Level Name" ,head.c_str()
);
if (new_head_ptr == nullptr || head == new_head_ptr ) {
return; /* Cancel or 同じ名前なら何もしない */
}
const std::string new_head(new_head_ptr);
/* ファイル毎名前を変更する */
for (size_t ii=0; ii<nums.size() ; ++ii) {
std::string opa( this->get_open_path( nums.at(ii) ) );
std::string npa( this->get_open_path_from_head_and_number_(
new_head.c_str() ,nums.at(ii)
));
/* 最初にこれでいいかユーザーに確認する */
if (ii==0) {
if (fl_ask(
"Rename\nFrom\n %s\nTo\n %s\nNumber List\n %s\nOK?"
,opa.c_str()
,npa.c_str()
,numost.str().c_str()
) != 1) {
return; // Cancel
}
}
#ifdef _WIN32
std::string opa2( osapi::cp932_from_utf8( opa ) );
std::string npa2( osapi::cp932_from_utf8( npa ) );
if (opa2.empty() || npa2.empty()) {
fl_alert("Error:rename \"%s\" \"%s\""
,opa.c_str() ,npa.c_str() );
return;
}
std::rename( opa2.c_str() ,npa2.c_str() );
#else
std::rename( opa.c_str() ,npa.c_str() );
#endif
}
/* rename成功したら、新しい名前に表示変更 */
cl_gts_gui.strinp_trace_open_file_head->value( new_head.c_str() );
}
void cb_trace_files::cb_renumber(void)
{
/* Openファイルのフルパスを得る */
const std::string filepath = this->get_open_path( 1 );
if (filepath.empty()) {
fl_alert( "Not set Open Folder or File name" );
return;
}
/* 連番ファイルの存在チェックして必要な情報に変える */
std::string dpath , head , num , ext;
int number=-1;
std::vector<int> nums;
ids::path::level_from_files(
filepath ,dpath ,head ,num ,number ,ext ,nums
);
if (head.empty() || nums.size() <= 0) {
fl_alert( "Not exist files" );
return;
}
/* ユーザーから新しいStart番号を得る */
const char* new_start_num_ptr = fl_input(
"Enter New Start Number" ,std::to_string(nums.at(0)).c_str()
);
if (new_start_num_ptr == nullptr
|| std::stoi(std::string(new_start_num_ptr))==nums.at(0)) {
return; /* Cancel or 同じ名前なら何もしない */
}
const std::string new_start_num( new_start_num_ptr );
/* 新しいStart番号との差 */
const int diff_num = std::stoi(new_start_num) - nums.at(0);
/* エラー数値をチェックしつつ番号を文字列に入れる */
std::ostringstream numost;
bool error_sw = false;
for (auto nu : nums) {
numost << nu + diff_num;
numost << " ";
if ( nu + diff_num < 0 || 9999 < nu + diff_num ) {
error_sw = true;
}
}
/* ゼロ以下数値があるとエラーメッセージダイオローグを出して終わる */
if (error_sw) {
std::string opa( this->get_open_path( nums.at(0) ) );
std::string npa( this->get_open_path(
nums.at(0) + diff_num ) );
fl_alert(
"Error : Number need 0...9999 range\nFrom\n %s\nTo\n %s\nNumber List\n %s\n"
,opa.c_str()
,npa.c_str()
,numost.str().c_str()
);
return;
}
/* ファイル毎名前を変更する */
for (size_t ii=0; ii<nums.size() ; ++ii) {
std::string opa( this->get_open_path( nums.at(ii) ) );
std::string npa( this->get_open_path(
nums.at(ii) + diff_num ) );
/* 最初にこれでいいかユーザーに確認する */
if (ii==0) {
if (fl_ask(
"Renumber\nFrom\n %s\nTo\n %s\nNumber List\n %s\nOK?"
,opa.c_str()
,npa.c_str()
,numost.str().c_str()
) != 1) {
return; // Cancel
}
}
#ifdef _WIN32
std::string opa2( osapi::cp932_from_utf8( opa ) );
std::string npa2( osapi::cp932_from_utf8( npa ) );
if (opa2.empty() || npa2.empty()) {
fl_alert("Error:rename \"%s\" \"%s\""
,opa.c_str() ,npa.c_str() );
return;
}
std::rename( opa2.c_str() ,npa2.c_str() );
#else
std::rename( opa.c_str() ,npa.c_str() );
#endif
}
/* renumber成功したら、新しいStart,End,Numberに表示変更 */
this->cb_set_number();
this->cb_check_existing_saved_file();
}
//----------------------------------------------------------------------
/* 連番画像ファイルブラウズ */
void cb_trace_files::cb_browse_open_file( void )
{
/* NativeブラウザーOpenで開く */
int filter_current=
cl_gts_gui.choice_trace_open_image_format->value();
const std::string filepath = ids::path::fltk_native_browse_open(
"Open Images"
,cl_gts_gui.filinp_trace_open_dir_path->value()
,this->get_open_name_from_number_(
static_cast<int>(cl_gts_gui.valout_trace_num_start->value())
)
,this->ext_open.get_native_filters()
,filter_current
).at(0);
/* Cancel */
if (filepath.empty()) {
return;
}
/* 必要な情報に変える */
std::string dpath , head , num , ext;
int number=-1;
std::vector<int> nums;
ids::path::level_from_files(
filepath ,dpath ,head ,num ,number ,ext ,nums
);
/* チェック:ファイルヘッド(file head名)が空だとなにもしない */
if (head.empty()) {
fl_alert("No Head in File");
return;
}
/* チェック:拡張子が対応した種類でないと何もしない */
const int ext_num = this->ext_open.num_from_str( ext );
if ( ext_num < 0 ) {
fl_alert("Bad Extension\"%s\" in File",ext.c_str());
return;
}
/* チェック:連番でないならなにもしない */
if (num.empty() || number == -1) {
fl_alert("No Number in File");
return;
}
/* Traceの番号であることを表示して示す */
cl_gts_master.cl_number.set_type_to_trace();
/* ファイルパスから生成した部品を、GUI、その他セット */
this->set_gui_for_open( dpath ,head ,num ,ext ,nums );
/* 連番画像読込表示 */
cl_gts_master.cb_number_read_and_trace_and_preview();
/* 画像を開いたときの初期表示を元画像の表示にする */
cl_gts_master.cb_change_wview_main();
cl_gts_gui.menite_wview_main->setonly();
}
void cb_trace_files::set_gui_for_open(
const std::string& dpath
,const std::string& head
,const std::string& num
,const std::string& ext
,const std::vector<int>& nums
)
{
/* Trace Filesウインドウ Open設定 */
cl_gts_gui.filinp_trace_open_dir_path->value(dpath.c_str());
cl_gts_gui.strinp_trace_open_file_head->value(head.c_str());
cl_gts_gui.strinp_trace_open_number_format->value(num.c_str());
int ext_num = this->ext_open.num_from_str(ext);
if (ext_num < 0) { ext_num = 0; }
cl_gts_gui.choice_trace_open_image_format->value(ext_num);
/* Trace Filesウインドウ Number設定 */
if (nums.empty()) {
cl_gts_gui.valout_trace_num_start->value( 0 );
cl_gts_gui.valout_trace_num_end->value( 0 );
}
else {
cl_gts_gui.valout_trace_num_start->value( nums.front() );
cl_gts_gui.valout_trace_num_end->value( nums.back() );
}
/* Trace Filesウインドウ 即表示 */
cl_gts_gui.window_trace_files->flush();
/* Numberウインドウ Listを操作可能にする */
cl_gts_gui.selbro_number_list->activate();
/* Numberウインドウ再構築 */
cl_gts_master.cl_number.reset_by_number_list( nums );
}
/* 保存フォルダーブラウズ */
void cb_trace_files::cb_browse_save_folder( void )
{
/* Nativeフォルダーブラウザー開く */
#ifdef _WIN32
const std::string filepath =wincom::native_browse_directory_m(
"Select Saving Folder for Trace"
,cl_gts_gui.filinp_trace_save_dir_path->value()
,::fl_xid( cl_gts_gui.window_trace_files )
);
#else
const std::string filepath =ids::path::fltk_native_browse_directory(
"Set Saving Folder for Trace"
,cl_gts_gui.filinp_trace_save_dir_path->value()
).at(0);
#endif
/* Cancel */
if (filepath.empty()) {
return;
}
cl_gts_gui.filinp_trace_save_dir_path->value( filepath.c_str() );
}
//----------------------------------------------------------------------
/* numberセット表示/file存在確認表示 */
void cb_trace_files::cb_set_number( void )
{
/* Traceの番号であることを表示して示す */
cl_gts_master.cl_number.set_type_to_trace();
/* 必要な情報に変える */
std::string filepath( this->get_open_path( 0 ) );
std::string dpath , head , num , ext;
int number=-1;
std::vector<int> nums;
ids::path::level_from_files(
filepath ,dpath ,head ,num ,number ,ext ,nums
);
if (head.empty() || nums.empty() || nums.size() <= 0) {
fl_alert( "Not exist file about \'%s\'" ,filepath.c_str() );
return;
}
/* Trace Filesウインドウ Number設定 */
cl_gts_gui.valout_trace_num_start->value( nums.front() );
cl_gts_gui.valout_trace_num_end->value( nums.back() );
/* Trace Filesウインドウ 即表示 */
cl_gts_gui.window_trace_files->flush();
/* Numberウインドウ Listを操作可能にする */
cl_gts_gui.selbro_number_list->activate();
/* Numberウインドウ再構築 */
cl_gts_master.cl_number.reset_by_number_list( nums );
}
//----------------------------------------------------------------------
/* 保存する連番ファイルが存在するならファイル名の背景を黄色表示 */
void cb_trace_files::cb_check_existing_saved_file(void)
{
if ( !cl_gts_master.cl_number.is_trace() ) {
return;
}
this->check_existing_saved_file();
}
void cb_trace_files::check_existing_saved_file(void)
{
Fl_Color col = 0;
if ( this->is_exist_save_files_() ) { /* 上書き */
col = FL_YELLOW;
} else { /* 新規ファイル */
col = FL_WHITE;
}
cl_gts_gui.filinp_trace_save_dir_path->color(col);
cl_gts_gui.filinp_trace_save_dir_path->redraw();
cl_gts_gui.strinp_trace_save_file_head->color(col);
cl_gts_gui.strinp_trace_save_file_head->redraw();
//cl_gts_gui.strinp_trace_save_number_format->color(col);
//cl_gts_gui.strinp_trace_save_number_format->redraw();
cl_gts_gui.output_trace_save_number_format->color(col);
cl_gts_gui.output_trace_save_number_format->redraw();
cl_gts_gui.choice_trace_save_image_format->color(col);
cl_gts_gui.choice_trace_save_image_format->redraw();
}
bool cb_trace_files::is_exist_save_files_(void)
{
/* Numberの非選択含めた番号ファイルで一つでも存在するならtrueを返す */
bool sw=false;
for (int ii = 1; ii <= cl_gts_gui.selbro_number_list->size(); ++ii) {
/* リストの項目に表示した番号 */
const int file_num = std::stoi(
cl_gts_gui.selbro_number_list->text(ii)
);
/* 番号によるファイルパス */
std::string filepath( this->get_save_path( file_num ) );
/* ファイルの存在の表示チェック */
if (!filepath.empty() && osapi::exist_utf8_mbs(filepath)) {
sw = true;
cl_gts_master.cl_number.replace_with_S( file_num ,ii );
}
else {
cl_gts_master.cl_number.replace_without_S( file_num ,ii );
}
}
return sw;
}
//----------------------------------------------------------------------
/* open file/path */
const std::string cb_trace_files::get_open_path( const int number )
{
/* Folder & File名が設定していないと空を返す */
if (cl_gts_gui.filinp_trace_open_dir_path->value() == nullptr
|| this->get_open_name_from_number_( number ).empty()) {
return std::string();
}
std::string filepath;
filepath += cl_gts_gui.filinp_trace_open_dir_path->value();
filepath += '/';
filepath += this->get_open_name_from_number_( number );
return filepath;
}
const std::string cb_trace_files::get_open_name_from_number_( const int number )
{
return this->get_open_name_from_head_and_number_(
cl_gts_gui.strinp_trace_open_file_head->value() ,number );
}
const std::string cb_trace_files::get_open_name_from_head_and_number_(
const std::string& file_head
,const int number
)
{
/* 名(head,num_form,ext)が設定していないと空を返す */
if (file_head.empty()
|| (0 <= number
&& cl_gts_gui.strinp_trace_open_number_format->value() == nullptr)
|| cl_gts_gui.choice_trace_open_image_format->text() == nullptr) {
return std::string();
}
std::string filename(file_head);
if (0 <= number) {
filename += ids::path::str_from_number(
number , cl_gts_gui.strinp_trace_open_number_format->value()
);
}
filename += cl_gts_gui.choice_trace_open_image_format->text();
return filename;
}
const std::string cb_trace_files::get_open_path_from_head_and_number_(
const std::string& file_head
,const int number
)
{
/* Folder & File名が設定していないと空を返す */
if (cl_gts_gui.filinp_trace_open_dir_path->value() == nullptr
|| this->get_open_name_from_head_and_number_(
file_head,number).empty()) {
return std::string();
}
std::string filepath;
filepath += cl_gts_gui.filinp_trace_open_dir_path->value();
filepath += '/';
filepath += this->get_open_name_from_head_and_number_(
file_head ,number
);
return filepath;
}
//----------------------------------------------------------------------
/* save file/path */
const std::string cb_trace_files::get_save_path( const int number )
{
/* Folder & File名が設定していないと空を返す */
if (cl_gts_gui.filinp_trace_save_dir_path->value() == nullptr
|| this->get_save_name_( number ).empty()) {
return std::string();
}
std::string filepath;
filepath += cl_gts_gui.filinp_trace_save_dir_path->value();
filepath += '/';
filepath += this->get_save_name_( number );
return filepath;
}
const std::string cb_trace_files::get_save_name_( const int number )
{
/* 名(head,num_form,ext)が設定していないと空を返す */
if (cl_gts_gui.strinp_trace_save_file_head->value() == nullptr
|| (0 <= number
&& cl_gts_gui.output_trace_save_number_format->value() == nullptr)
|| cl_gts_gui.choice_trace_save_image_format->text() == nullptr) {
return std::string();
}
std::string filename;
filename += cl_gts_gui.strinp_trace_save_file_head->value();
if (0 <= number) {
filename += ids::path::str_from_number(
number
, cl_gts_gui.output_trace_save_number_format->value()
);
}
filename += cl_gts_gui.choice_trace_save_image_format->text();
return filename;
}
//----------------------------------------------------------------------
std::string cb_trace_files::get_open_ext_for_legacy_(const std::string& type)
{
if (type.size() == 4) { return type; }
for (int ii=0;ii<this->ext_open.size() ;++ii) {
if ( this->ext_open.get_fltk_filter( ii ) == type) {
return this->ext_open.str_from_num( ii );
}
}
return type;
}
std::string cb_trace_files::get_save_ext_for_legacy_(const std::string& type)
{
if (type.size() == 4) { return type; }
for (int ii=0;ii<this->ext_save.size() ;++ii) {
if ( this->ext_save.get_fltk_filter( ii ) == type) {
return this->ext_save.str_from_num( ii );
}
}
return type;
}
void cb_trace_files::cb_choice_open_image_format( const std::string& type )
{
std::string typestr( this->get_open_ext_for_legacy_(type) );
const Fl_Menu_Item *crnt =
cl_gts_gui.choice_trace_open_image_format->find_item(
typestr.c_str() );
if (crnt == nullptr) { return; }
cl_gts_gui.choice_trace_open_image_format->value(crnt);
}
void cb_trace_files::cb_choice_save_image_format( const std::string& type )
{
std::string typestr( this->get_save_ext_for_legacy_(type) );
const Fl_Menu_Item *crnt =
cl_gts_gui.choice_trace_save_image_format->find_item(
typestr.c_str() );
if (crnt == nullptr) { return; }
cl_gts_gui.choice_trace_save_image_format->value(crnt);
}
//----------------------------------------------------------------------
void cb_trace_files::cb_switch_trace_filter_erase_dot_noise( const bool sw )
{
if (sw) {
cl_gts_gui.chkbtn_trace_filter_erase_dot_noise_sw->box(FL_SHADOW_BOX);
cl_gts_gui.chkbtn_trace_filter_erase_dot_noise_sw->value(1);//ON
}
else {
cl_gts_gui.chkbtn_trace_filter_erase_dot_noise_sw->box(FL_FLAT_BOX);
cl_gts_gui.chkbtn_trace_filter_erase_dot_noise_sw->value(0);//OFF
}
}
//----------------------------------------------------------------------
void cb_trace_files::cb_browse_save_file( void )
{
/* Crop中は保存できない */
if (cl_gts_master.cl_ogl_view.get_crop_disp_sw()) {
fl_alert("Finish Cropping, Please Scan.");
return;
}
/* ScanもReadもまだしていない */
if (cl_gts_master.cl_iip_ro90.get_clp_parent() == nullptr ) {
fl_alert("Please Any Scan or Open.");
return;
}
/* parameter */
iip_canvas* parent = nullptr;
int rot90=0;
double dpi = 0;
iip_read* read_attr = nullptr;
/* ファイル読込後 */
if ( &(cl_gts_master.cl_iip_read)
== cl_gts_master.cl_iip_ro90.get_clp_parent() ) {
parent = &(cl_gts_master.cl_iip_read);
rot90 = 0; /* 画像コンバート処理のみで、回転はしない */
dpi = cl_gts_master.cl_iip_read.get_d_tif_dpi_x();
read_attr = &(cl_gts_master.cl_iip_read);
}
else
/* スキャン後 */
if ( cl_gts_master.cl_iip_scan.get_clp_canvas()
== cl_gts_master.cl_iip_ro90.get_clp_parent() ) {
parent = cl_gts_master.cl_iip_scan.get_clp_canvas();
rot90 = cl_gts_gui.choice_rot90->value();
dpi = cl_gts_gui.valinp_area_reso->value();
} else {
fl_alert("No Image");
return;
}
/* parameter */
std::string save_dpath;
std::string save_fname;
std::string save_filter;
int save_filter_num = 0;
/* ファイルトレスモード */
if (cl_gts_master.cl_number.is_trace()) {
save_dpath = cl_gts_gui.filinp_trace_save_dir_path->value();
save_fname = this->get_save_name_( -1 );
save_filter = this->ext_save.get_native_filters();
save_filter_num = cl_gts_gui.choice_trace_save_image_format->value();
} else
/* スキャンモード */
if (cl_gts_master.cl_number.is_scan()) {
save_dpath = cl_gts_gui.filinp_scan_save_dir_path->value();
save_fname = cl_gts_master.cl_scan_and_save.get_save_path( -1 );
save_filter = cl_gts_master.cl_scan_and_save.ext_save.get_native_filters();
save_filter_num = cl_gts_gui.choice_scan_save_image_format->value();
} else {
fl_alert("Not Scan/Trace");
return;
}
/* NativeブラウザーSaveで開く */
//std::cout << __FILE__ << " " << "save_dpath=" << save_dpath << " save_fname=" << save_fname << std::endl;
const std::string fpath_save = ids::path::fltk_native_browse_save(
"Save Image"
,save_dpath
,save_fname
,save_filter
,save_filter_num
).at(0);
/* Cancel */
if (fpath_save.empty()) {
return;
}
/* 処理:Rot90 and Effects(color Trace and Erase color dot noise) */
if (cl_gts_master.rot_and_trace_and_enoise( parent ,rot90 ) != OK) {
return;
}
/* 保存 */
if (OK != cl_gts_master.iipg_save(
&(cl_gts_master.cl_iip_edot)
, const_cast<char *>(fpath_save.c_str())
,dpi
,rot90
,read_attr
)) {
pri_funct_err_bttvr(
"Error : cl_gts_master.iipg_save(-) returns NG" );
return;
}
/* 表示:画像の再表示 */
if (cl_gts_master.redraw_image(
&(cl_gts_master.cl_iip_edot)
, false /* crop sw */
, false /* force view scanimage sw */
)) {
return;
}
}
| 26.481056 | 107 | 0.672491 | Savraska2 |
bff0b638a70ed3f6bb03a3738ba01db2d1f2880f | 997 | hpp | C++ | SFND_Camera/SFND_3D_Object_Tracking/src/lidarData.hpp | KU-AIRS-SPARK/Udacity_Sensor_Fusion_Nanodegree | 2c6d26bee670abe2c63034d26556f99f6d77925b | [
"MIT"
] | 18 | 2020-11-12T07:13:57.000Z | 2022-03-12T18:42:13.000Z | SFND_Camera/SFND_3D_Object_Tracking/src/lidarData.hpp | KU-AIRS-SPARK/Udacity_Sensor_Fusion_Nanodegree | 2c6d26bee670abe2c63034d26556f99f6d77925b | [
"MIT"
] | null | null | null | SFND_Camera/SFND_3D_Object_Tracking/src/lidarData.hpp | KU-AIRS-SPARK/Udacity_Sensor_Fusion_Nanodegree | 2c6d26bee670abe2c63034d26556f99f6d77925b | [
"MIT"
] | 16 | 2020-09-29T05:27:32.000Z | 2021-11-02T18:26:53.000Z |
#ifndef lidarData_hpp
#define lidarData_hpp
#include <stdio.h>
#include <fstream>
#include <string>
#include "dataStructures.h"
void cropLidarPoints(std::vector<LidarPoint>& lidarPoints,
float minX,
float maxX,
float maxY,
float minZ,
float maxZ,
float minR);
void loadLidarFromFile(std::vector<LidarPoint>& lidarPoints,
std::string filename);
void showLidarTopview(std::vector<LidarPoint>& lidarPoints,
cv::Size worldSize,
cv::Size imageSize,
bool bWait = true);
void showLidarImgOverlay(cv::Mat& img,
std::vector<LidarPoint>& lidarPoints,
cv::Mat& P_rect_xx,
cv::Mat& R_rect_xx,
cv::Mat& RT,
cv::Mat* extVisImg = nullptr);
#endif /* lidarData_hpp */
| 31.15625 | 62 | 0.500502 | KU-AIRS-SPARK |
bff1433bcbaea411c0a0ba8d2c76fdf18190237d | 4,005 | hpp | C++ | auxil/broker/caf/libcaf_core/caf/exec_main.hpp | hugolin615/zeek-4.0.0-ele420520-spring2021 | 258e9b2ee1f2a4bd45c6332a75304793b7d44d40 | [
"Apache-2.0"
] | null | null | null | auxil/broker/caf/libcaf_core/caf/exec_main.hpp | hugolin615/zeek-4.0.0-ele420520-spring2021 | 258e9b2ee1f2a4bd45c6332a75304793b7d44d40 | [
"Apache-2.0"
] | null | null | null | auxil/broker/caf/libcaf_core/caf/exec_main.hpp | hugolin615/zeek-4.0.0-ele420520-spring2021 | 258e9b2ee1f2a4bd45c6332a75304793b7d44d40 | [
"Apache-2.0"
] | null | null | null | // This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#pragma once
#include "caf/actor_system.hpp"
#include "caf/actor_system_config.hpp"
#include "caf/detail/type_list.hpp"
#include "caf/detail/type_traits.hpp"
#include "caf/init_global_meta_objects.hpp"
namespace caf {
template <class>
struct exec_main_helper;
template <>
struct exec_main_helper<detail::type_list<actor_system&>> {
using config = actor_system_config;
template <class F>
auto operator()(F& fun, actor_system& sys, const config&) {
return fun(sys);
}
};
template <class T>
struct exec_main_helper<detail::type_list<actor_system&, const T&>> {
using config = T;
template <class F>
auto operator()(F& fun, actor_system& sys, const config& cfg) {
return fun(sys, cfg);
}
};
template <class T>
void exec_main_init_meta_objects_single() {
if constexpr (std::is_base_of<actor_system::module, T>::value)
T::init_global_meta_objects();
else
init_global_meta_objects<T>();
}
template <class... Ts>
void exec_main_init_meta_objects() {
(exec_main_init_meta_objects_single<Ts>(), ...);
}
template <class T>
void exec_main_load_module(actor_system_config& cfg) {
if constexpr (std::is_base_of<actor_system::module, T>::value)
cfg.template load<T>();
}
template <class... Ts, class F = void (*)(actor_system&)>
int exec_main(F fun, int argc, char** argv,
const char* config_file_name = "caf-application.conf") {
using trait = typename detail::get_callable_trait<F>::type;
using arg_types = typename trait::arg_types;
static_assert(detail::tl_size<arg_types>::value == 1
|| detail::tl_size<arg_types>::value == 2,
"main function must have one or two arguments");
static_assert(std::is_same<
typename detail::tl_head<arg_types>::type,
actor_system&
>::value,
"main function must take actor_system& as first parameter");
using arg2 = typename detail::tl_at<arg_types, 1>::type;
using decayed_arg2 = typename std::decay<arg2>::type;
static_assert(std::is_same<arg2, unit_t>::value
|| (std::is_base_of<actor_system_config, decayed_arg2>::value
&& std::is_same<arg2, const decayed_arg2&>::value),
"second parameter of main function must take a subtype of "
"actor_system_config as const reference");
using helper = exec_main_helper<typename trait::arg_types>;
// Pass CLI options to config.
typename helper::config cfg;
if (auto err = cfg.parse(argc, argv, config_file_name)) {
std::cerr << "error while parsing CLI and file options: " << to_string(err)
<< std::endl;
return EXIT_FAILURE;
}
// Return immediately if a help text was printed.
if (cfg.cli_helptext_printed)
return EXIT_SUCCESS;
// Load modules.
(exec_main_load_module<Ts>(cfg), ...);
// Initialize the actor system.
actor_system system{cfg};
if (cfg.slave_mode) {
if (!cfg.slave_mode_fun) {
std::cerr << "cannot run slave mode, I/O module not loaded" << std::endl;
return EXIT_FAILURE;
}
return cfg.slave_mode_fun(system, cfg);
}
helper f;
using result_type = decltype(f(fun, system, cfg));
if constexpr (std::is_convertible<result_type, int>::value) {
return f(fun, system, cfg);
} else {
f(fun, system, cfg);
return EXIT_SUCCESS;
}
}
} // namespace caf
#define CAF_MAIN(...) \
int main(int argc, char** argv) { \
caf::exec_main_init_meta_objects<__VA_ARGS__>(); \
caf::core::init_global_meta_objects(); \
return caf::exec_main<__VA_ARGS__>(caf_main, argc, argv); \
}
| 34.230769 | 80 | 0.645693 | hugolin615 |
bff2cef641dd87c9db80e8b44993ebaf81d4b10b | 1,134 | cc | C++ | components/subresource_filter/content/browser/content_activation_list_utils.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/subresource_filter/content/browser/content_activation_list_utils.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/subresource_filter/content/browser/content_activation_list_utils.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 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 "components/subresource_filter/content/browser/content_activation_list_utils.h"
namespace subresource_filter {
ActivationList GetListForThreatTypeAndMetadata(
safe_browsing::SBThreatType threat_type,
safe_browsing::ThreatPatternType threat_type_metadata) {
bool is_phishing_interstitial =
(threat_type == safe_browsing::SB_THREAT_TYPE_URL_PHISHING);
bool is_soc_engineering_ads_interstitial =
threat_type_metadata ==
safe_browsing::ThreatPatternType::SOCIAL_ENGINEERING_ADS;
bool subresource_filter =
(threat_type == safe_browsing::SB_THREAT_TYPE_SUBRESOURCE_FILTER);
if (is_phishing_interstitial) {
if (is_soc_engineering_ads_interstitial) {
return ActivationList::SOCIAL_ENG_ADS_INTERSTITIAL;
}
return ActivationList::PHISHING_INTERSTITIAL;
} else if (subresource_filter) {
return ActivationList::SUBRESOURCE_FILTER;
}
return ActivationList::NONE;
}
} // namespace subresource_filter
| 35.4375 | 88 | 0.789242 | metux |
bff6da18a7255440fb3e7e0f1640ff19936cbfc5 | 2,261 | cpp | C++ | src/termui/terminal_mode.cpp | numerodix/bmon-cpp | fae0613776b879a33e327f9ccf1d3819383634dd | [
"MIT"
] | 1 | 2020-07-31T01:34:47.000Z | 2020-07-31T01:34:47.000Z | src/termui/terminal_mode.cpp | numerodix/bmon-cpp | fae0613776b879a33e327f9ccf1d3819383634dd | [
"MIT"
] | null | null | null | src/termui/terminal_mode.cpp | numerodix/bmon-cpp | fae0613776b879a33e327f9ccf1d3819383634dd | [
"MIT"
] | null | null | null | #include <stdexcept>
#include <unistd.h>
#include "except.hpp"
#include "signals.hpp"
#include "terminal_mode.hpp"
namespace bandwit {
namespace termui {
void TerminalModeSetter::set() {
SignalGuard guard{signal_suspender_};
struct termios tm {};
if (tcgetattr(STDIN_FILENO, &tm) < 0) {
THROW_CERROR(std::runtime_error,
"TerminalModeSetter.set failed in tcgetattr()");
}
// save the unmodified state so we can restore it
orig_termios_ = tm;
tm.c_lflag &= ~local_off_;
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &tm) < 0) {
THROW_CERROR(std::runtime_error,
"TerminalModeSetter.set failed in tcsetattr()");
}
// Now check that the set actually set all of our flags
struct termios tm_after {};
if (tcgetattr(STDIN_FILENO, &tm_after) < 0) {
THROW_CERROR(std::runtime_error,
"TerminalModeSetter.set failed in #2 tcgetattr()");
}
if ((tm_after.c_lflag & local_off_) > 0) {
THROW_MSG(std::runtime_error,
"TerminalModeSetter.set failed to actually set the flags!");
}
}
void TerminalModeSetter::reset() {
SignalGuard guard{signal_suspender_};
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios_) < 0) {
THROW_CERROR(std::runtime_error,
"TerminalModeSetter.unset failed in tcsetattr()");
}
// Now check that the set actually unset all of our flags
struct termios tm_after {};
if (tcgetattr(STDIN_FILENO, &tm_after) < 0) {
THROW_CERROR(std::runtime_error,
"TerminalModeSetter.unset failed in tcgetattr()");
}
if ((tm_after.c_lflag & local_off_) != local_off_) {
THROW_MSG(
std::runtime_error,
"TerminalModeSetter.unset failed to actually unset the flags!");
}
}
TerminalModeSet &TerminalModeSet::local_off(tcflag_t flag) {
flags_local_off_ |= flag;
return *this;
}
std::unique_ptr<TerminalModeSetter>
TerminalModeSet::build_setter(SignalSuspender *signal_suspender) {
return std::make_unique<TerminalModeSetter>(flags_local_off_,
signal_suspender);
}
} // namespace termui
} // namespace bandwit | 28.2625 | 78 | 0.637771 | numerodix |
bffaab10eb745e8831e5ff7e1563d01e08fe9cb4 | 621 | cpp | C++ | test/structure_size.cpp | vhapiak/meta_info_lib | 677984960028c6ef0f2b462c2f6ae8ac7fc714ea | [
"MIT"
] | null | null | null | test/structure_size.cpp | vhapiak/meta_info_lib | 677984960028c6ef0f2b462c2f6ae8ac7fc714ea | [
"MIT"
] | null | null | null | test/structure_size.cpp | vhapiak/meta_info_lib | 677984960028c6ef0f2b462c2f6ae8ac7fc714ea | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include "mil/mil.hpp"
struct normal {
int i;
double d;
};
struct extended {
MIL_BEGIN(extended);
MIL_DEFINE_FIELD(int, i);
MIL_DEFINE_FIELD(double, d);
MIL_END;
};
TEST(structure_size, size) {
EXPECT_EQ(sizeof(normal), sizeof(extended));
}
struct inheritance : normal {
float f;
};
struct inheritance_extended : MIL_INHERITANCE(inheritance_extended, extended) {
MIL_BEGIN(inheritance_extended);
MIL_DEFINE_FIELD(float, f);
MIL_END;
};
TEST(structure_size, inheritance_size) {
EXPECT_EQ(sizeof(inheritance), sizeof(inheritance_extended));
}
| 18.264706 | 79 | 0.703704 | vhapiak |
bffacdaf4dea29404257dc0634564d66f6bdef6a | 7,011 | cpp | C++ | src/thunder/plugins/ctrlm_thunder_plugin_cec_sink.cpp | rdkcmf/rdk-control | 8aec8a571abb7eb104c3ac8f788af16cda57aea8 | [
"Apache-2.0"
] | null | null | null | src/thunder/plugins/ctrlm_thunder_plugin_cec_sink.cpp | rdkcmf/rdk-control | 8aec8a571abb7eb104c3ac8f788af16cda57aea8 | [
"Apache-2.0"
] | null | null | null | src/thunder/plugins/ctrlm_thunder_plugin_cec_sink.cpp | rdkcmf/rdk-control | 8aec8a571abb7eb104c3ac8f788af16cda57aea8 | [
"Apache-2.0"
] | 1 | 2021-04-27T11:11:30.000Z | 2021-04-27T11:11:30.000Z | /*
* If not stated otherwise in this file or this component's license file the
* following copyright and licenses apply:
*
* Copyright 2015 RDK Management
*
* 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 "ctrlm_thunder_plugin_cec_sink.h"
#include "ctrlm_thunder_log.h"
#include <WPEFramework/core/core.h>
#include <WPEFramework/websocket/websocket.h>
#include <WPEFramework/plugins/plugins.h>
#include <glib.h>
#include <sstream>
using namespace Thunder;
using namespace CECSink;
using namespace WPEFramework;
static int _on_device_changed_thread(void *data) {
ctrlm_thunder_plugin_cec_sink_t *plugin = (ctrlm_thunder_plugin_cec_sink_t *)data;
if(plugin) {
plugin->device_add_timer = 0;
plugin->on_device_updated();
} else {
THUNDER_LOG_ERROR("%s: Plugin NULL\n", __FUNCTION__);
}
return(0);
}
static void _on_device_added(ctrlm_thunder_plugin_cec_sink_t *plugin, JsonObject params) {
if(plugin) {
if(plugin->device_add_timer > 0) {
g_source_remove(plugin->device_add_timer);
plugin->device_add_timer = 0;
}
plugin->device_add_timer = g_timeout_add_seconds(3, &_on_device_changed_thread, (void *)plugin);
} else {
THUNDER_LOG_ERROR("%s: Plugin NULL\n", __FUNCTION__);
}
}
static void _on_device_removed(ctrlm_thunder_plugin_cec_sink_t *plugin, JsonObject params) {
if(plugin) {
if(plugin->device_add_timer > 0) {
g_source_remove(plugin->device_add_timer);
plugin->device_add_timer = 0;
}
g_idle_add(&_on_device_changed_thread, (void *)plugin);
} else {
THUNDER_LOG_ERROR("%s: Plugin NULL\n", __FUNCTION__);
}
}
static void _on_device_info_changed(ctrlm_thunder_plugin_cec_sink_t *plugin, JsonObject params) {
if(plugin) {
if(plugin->device_add_timer > 0) {
g_source_remove(plugin->device_add_timer);
plugin->device_add_timer = 0;
}
plugin->device_add_timer = g_timeout_add_seconds(3, &_on_device_changed_thread, (void *)plugin);
} else {
THUNDER_LOG_ERROR("%s: Plugin NULL\n", __FUNCTION__);
}
}
ctrlm_thunder_plugin_cec_sink_t::ctrlm_thunder_plugin_cec_sink_t() : ctrlm_thunder_plugin_t("HdmiCecSink", "org.rdk.HdmiCecSink", 1) {
sem_init(&this->semaphore, 0, 1);
this->registered_events = false;
this->device_add_timer = 0;
}
ctrlm_thunder_plugin_cec_sink_t::~ctrlm_thunder_plugin_cec_sink_t() {
}
void ctrlm_thunder_plugin_cec_sink_t::get_cec_devices(std::vector<Thunder::CEC::cec_device_t> &cec_devices) {
// Lock sempahore as we are touching CEC cache
sem_wait(&this->semaphore);
cec_devices = this->devices;
// Unlock semaphore as we are done touching the CEC cache
sem_post(&this->semaphore);
}
bool ctrlm_thunder_plugin_cec_sink_t::_update_cec_devices() {
bool ret = false;
JsonObject params, response;
THUNDER_LOG_INFO("%s: Calling CECSink for device data\n", __FUNCTION__);
// Lock sempahore as we are touching CEC cache
sem_wait(&this->semaphore);
this->devices.clear();
if(this->call_plugin("getDeviceList", (void *)¶ms, (void *)&response)) {
if(response.HasLabel("deviceList")) {
JsonArray device_list = response["deviceList"].Array();
for(int i = 0; i < device_list.Length(); i++) {
if(device_list[i].Object().HasLabel("logicalAddress") &&
device_list[i].Object().HasLabel("osdName") &&
device_list[i].Object().HasLabel("vendorID") &&
device_list[i].Object().HasLabel("portNumber")) {
std::stringstream vendor_parse;
Thunder::CEC::cec_device_t device;
device.logical_address = device_list[i].Object()["logicalAddress"].Number();
device.osd = device_list[i].Object()["osdName"].String();
device.port = device_list[i].Object()["portNumber"].Number();
vendor_parse << std::hex << device_list[i].Object()["vendorID"].String();
vendor_parse >> device.vendor_id;
this->devices.push_back(device);
}
}
} else {
std::string response_str;
response.ToString(response_str);
THUNDER_LOG_ERROR("%s: CECSink getDeviceList response malformed: <%s>\n", __FUNCTION__, response_str.c_str());
}
} else {
THUNDER_LOG_ERROR("%s: CECSink getDeviceList call failed!\n", __FUNCTION__);
}
// Unlock semaphore as we are done touching the CEC cache
sem_post(&this->semaphore);
return(ret);
}
bool ctrlm_thunder_plugin_cec_sink_t::register_events() {
bool ret = this->registered_events;
if(ret == false) {
auto clientObject = (JSONRPC::LinkType<Core::JSON::IElement>*)this->plugin_client;
if(clientObject) {
ret = true;
uint32_t thunderRet = clientObject->Subscribe<JsonObject>(CALL_TIMEOUT, _T("onDeviceAdded"), &_on_device_added, this);
if(thunderRet != Core::ERROR_NONE) {
THUNDER_LOG_ERROR("%s: Thunder subscribe failed <onDeviceAdded>\n", __FUNCTION__);
ret = false;
}
thunderRet = clientObject->Subscribe<JsonObject>(CALL_TIMEOUT, _T("onDeviceRemoved"), &_on_device_removed, this);
if(thunderRet != Core::ERROR_NONE) {
THUNDER_LOG_ERROR("%s: Thunder subscribe failed <onDeviceRemoved>\n", __FUNCTION__);
ret = false;
}
thunderRet = clientObject->Subscribe<JsonObject>(CALL_TIMEOUT, _T("onDeviceInfoUpdated"), &_on_device_info_changed, this);
if(thunderRet != Core::ERROR_NONE) {
THUNDER_LOG_ERROR("%s: Thunder subscribe failed <onDeviceInfoUpdated>\n", __FUNCTION__);
ret = false;
}
if(ret) {
this->registered_events = true;
}
}
}
Thunder::Plugin::ctrlm_thunder_plugin_t::register_events();
return(ret);
}
void ctrlm_thunder_plugin_cec_sink_t::on_initial_activation() {
this->_update_cec_devices();
Thunder::Plugin::ctrlm_thunder_plugin_t::on_initial_activation();
}
void ctrlm_thunder_plugin_cec_sink_t::on_device_updated() {
THUNDER_LOG_INFO("%s: CEC Device changed\n", __FUNCTION__);
this->_update_cec_devices();
} | 39.610169 | 134 | 0.651405 | rdkcmf |
bffbe676ba7bd90706842145f2446d111a05d93e | 1,631 | cpp | C++ | leetcode/331_Verify_Preorder_Serialization_of_a_Binary_Tree.cpp | longztian/cpp | 59203f41162f40a46badf69093d287250e5cbab6 | [
"MIT"
] | null | null | null | leetcode/331_Verify_Preorder_Serialization_of_a_Binary_Tree.cpp | longztian/cpp | 59203f41162f40a46badf69093d287250e5cbab6 | [
"MIT"
] | null | null | null | leetcode/331_Verify_Preorder_Serialization_of_a_Binary_Tree.cpp | longztian/cpp | 59203f41162f40a46badf69093d287250e5cbab6 | [
"MIT"
] | null | null | null | class Solution {
public:
bool isValidSerialization(string preorder) {
if (preorder.size() < 5) return preorder == "#";
stack<pair<bool, bool>> validNodes;
validNodes.push({true, false}); // dummy root with a dummy left child
auto pb = preorder.data(), pe = pb;
const auto PE = pb + preorder.size();
while (pb < PE && !validNodes.empty()) {
if (*pb != '#') { // live node
pe = find(pb, PE, ',');
validNodes.push({false, false});
} else {
pe = pb + 1; // null node
while (!validNodes.empty() && validNodes.top().first == true) validNodes.pop();
if (!validNodes.empty()) validNodes.top().first = true;
}
pb = pe + 1;
}
return pe == PE && validNodes.empty();
}
};
class Solution {
public:
bool isValidSerialization(string preorder) {
if (preorder.size() < 5) return preorder == "#";
stack<bool> leftValidated;
leftValidated.push(true);
auto pb = preorder.data();
const auto PE = pb + preorder.size();
while (pb < PE && !leftValidated.empty()) {
if (*pb != '#') {
leftValidated.push(false);
pb = find(pb, PE, ',') + 1;
} else {
while (!leftValidated.empty() && leftValidated.top() == true) leftValidated.pop();
if (!leftValidated.empty()) leftValidated.top() = true;
pb += 2;
}
}
return pb == PE + 1 && leftValidated.empty();
}
};
| 28.12069 | 98 | 0.486205 | longztian |
bffc306886feb649c5b00d30488295f23445dbd8 | 124 | cpp | C++ | epyks.cpp | whyamiroot/epyks | 45d5cde06f60110a3b3b78c189d5aeb634345593 | [
"MIT"
] | null | null | null | epyks.cpp | whyamiroot/epyks | 45d5cde06f60110a3b3b78c189d5aeb634345593 | [
"MIT"
] | null | null | null | epyks.cpp | whyamiroot/epyks | 45d5cde06f60110a3b3b78c189d5aeb634345593 | [
"MIT"
] | null | null | null | #include "epyks.h"
void encode(unsigned char* data, size_t size)
{
}
void decode(unsigned char* data, size_t size)
{
}
| 9.538462 | 45 | 0.685484 | whyamiroot |
bffcd0200f3dac5ae40993af272d51ab7cf0e285 | 1,312 | cc | C++ | video-player/src/log.cc | deets/brombeerquark | 9314bc6adaf19ee3868612c8aafdce0f1ebbabb9 | [
"MIT"
] | null | null | null | video-player/src/log.cc | deets/brombeerquark | 9314bc6adaf19ee3868612c8aafdce0f1ebbabb9 | [
"MIT"
] | null | null | null | video-player/src/log.cc | deets/brombeerquark | 9314bc6adaf19ee3868612c8aafdce0f1ebbabb9 | [
"MIT"
] | null | null | null | #include "log.hh"
#include <boost/core/null_deleter.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/sinks.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <iostream>
namespace logging = boost::log;
namespace sinks = boost::log::sinks;
namespace expr = boost::log::expressions;
void setupLogging() //boost::log::trivial::severity_level level)
{
logging::core::get()->set_filter
(
logging::trivial::severity >= logging::trivial::info
);
logging::add_common_attributes();
using text_sink = sinks::synchronous_sink< sinks::text_ostream_backend >;
boost::shared_ptr<text_sink> sink = boost::make_shared< text_sink >();
boost::shared_ptr< std::ostream > stream(&std::clog, boost::null_deleter());
sink->locked_backend()->add_stream(stream);
sink->set_formatter
(
expr::stream << \
expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S.%f") \
<< " "
<< expr::smessage
);
logging::core::get()->add_sink(sink);
}
void LOG(const char* message) {
BOOST_LOG_TRIVIAL(error) << message;
}
| 28.521739 | 90 | 0.698933 | deets |
8702c58828fa6e51c4e597bc73fe69ad9ef46af8 | 3,593 | hpp | C++ | external_libraries/amgcl/solver/eigen.hpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 778 | 2017-01-27T16:29:17.000Z | 2022-03-30T03:01:51.000Z | external_libraries/amgcl/solver/eigen.hpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 6,634 | 2017-01-15T22:56:13.000Z | 2022-03-31T15:03:36.000Z | external_libraries/amgcl/solver/eigen.hpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 224 | 2017-02-07T14:12:49.000Z | 2022-03-06T23:09:34.000Z | #ifndef AMGCL_SOLVER_EIGEN_HPP
#define AMGCL_SOLVER_EIGEN_HPP
/*
The MIT License
Copyright (c) 2012-2020 Denis Demidov <dennis.demidov@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
\file amgcl/solver/eigen.hpp
\author Denis Demidov <dennis.demidov@gmail.com>
\brief Wrapper around eigen direct solvers.
*/
#include <Eigen/Dense>
#include <Eigen/SparseCore>
#include <type_traits>
#include <amgcl/backend/builtin.hpp>
#include <amgcl/util.hpp>
namespace amgcl {
namespace solver {
template < class Solver >
class EigenSolver {
public:
typedef typename Solver::MatrixType MatrixType;
typedef typename Solver::Scalar value_type;
typedef amgcl::detail::empty_params params;
static size_t coarse_enough() {
return 3000 / math::static_rows<value_type>::value;
}
template <class Matrix>
EigenSolver(const Matrix &A, const params& = params())
: n( backend::rows(A) )
{
typedef
typename std::remove_const<
typename std::remove_pointer<
typename backend::col_data_impl<Matrix>::type
>::type
>::type
col_type;
typedef
typename std::remove_const<
typename std::remove_pointer<
typename backend::ptr_data_impl<Matrix>::type
>::type
>::type
ptr_type;
S.compute(
MatrixType(
Eigen::MappedSparseMatrix<value_type, Eigen::RowMajor, ptrdiff_t>(
backend::rows(A), backend::cols(A), backend::nonzeros(A),
const_cast<ptr_type*>(backend::ptr_data(A)),
const_cast<col_type*>(backend::col_data(A)),
const_cast<value_type*>(backend::val_data(A))
)
)
);
}
template <class Vec1, class Vec2>
void operator()(const Vec1 &rhs, Vec2 &x) const {
Eigen::Map< Eigen::Matrix<value_type, Eigen::Dynamic, 1> >
RHS(const_cast<value_type*>(&rhs[0]), n), X(&x[0], n);
X = S.solve(RHS);
}
friend std::ostream& operator<<(std::ostream &os, const EigenSolver &s) {
return os << "eigen: " << s.n << " unknowns";
}
private:
ptrdiff_t n;
Solver S;
};
} // namespace solver
} // namespace amgcl
#endif
| 32.963303 | 90 | 0.60757 | lkusch |
87052cacedf3f9923dfa0202beb08fdb352c21ba | 598 | cpp | C++ | BorisEngine2/DigitSprite.cpp | Rariolu/BorisEngine2 | d98d348a85a91ed09a8e1e48dc06b26f20b6f8f7 | [
"MIT"
] | 1 | 2019-11-16T13:23:03.000Z | 2019-11-16T13:23:03.000Z | BorisEngine2/DigitSprite.cpp | chocorho/BorisEngine2 | d98d348a85a91ed09a8e1e48dc06b26f20b6f8f7 | [
"MIT"
] | 2 | 2021-05-24T23:21:49.000Z | 2021-05-26T20:41:03.000Z | BorisEngine2/DigitSprite.cpp | chocorho/BorisEngine2 | d98d348a85a91ed09a8e1e48dc06b26f20b6f8f7 | [
"MIT"
] | 1 | 2021-05-24T22:52:31.000Z | 2021-05-24T22:52:31.000Z | #include "DigitSprite.h"
DigitSprite::DigitSprite(Font* font) : Sprite(texturemanager->AddTexture("digitSprite_0",font->CreateTextTexture("0",SOLID)))
{
digitFont = font;
}
DigitSprite::~DigitSprite()
{
}
int DigitSprite::GetDisplayNumber()
{
return displayNumber;
}
void DigitSprite::SetDisplayNumber(int num)
{
displayNumber = num;
if (digitFont)
{
String str = "digitSprite_" + std::to_string(num);
Texture* t = texturemanager->GetTexture(str);
if (!t)
{
t = texturemanager->AddTexture(str,digitFont->CreateTextTexture(std::to_string(num), SOLID));
}
SetTexture(t);
}
} | 19.290323 | 125 | 0.712375 | Rariolu |
87061140c4d88ae47bd8c416a8209f37492bb54e | 4,000 | hpp | C++ | components/scream/src/share/field/field_header.hpp | ashlynrlee/scream | 3d58c32340058368bee0cb2b02457c4723fb18db | [
"FTL",
"zlib-acknowledgement",
"RSA-MD"
] | null | null | null | components/scream/src/share/field/field_header.hpp | ashlynrlee/scream | 3d58c32340058368bee0cb2b02457c4723fb18db | [
"FTL",
"zlib-acknowledgement",
"RSA-MD"
] | null | null | null | components/scream/src/share/field/field_header.hpp | ashlynrlee/scream | 3d58c32340058368bee0cb2b02457c4723fb18db | [
"FTL",
"zlib-acknowledgement",
"RSA-MD"
] | null | null | null | #ifndef SCREAM_FIELD_HEADER_HPP
#define SCREAM_FIELD_HEADER_HPP
#include "share/field/field_identifier.hpp"
#include "share/field/field_tracking.hpp"
#include "share/field/field_alloc_prop.hpp"
#include "share/scream_types.hpp"
#include "share/util/scream_time_stamp.hpp"
#include "ekat/std_meta/ekat_std_any.hpp"
#include "ekat/std_meta/ekat_std_enable_shared_from_this.hpp"
#include <vector>
#include <map>
#include <memory> // For std::shared_ptr and std::weak_ptr
namespace scream
{
class AtmosphereProcess;
/*
* A small class to contain meta-data about a field
*
* The FieldHeader class is itself a container of other
* more speicific classes, such as FieldIdentifier
* (which contains information used to uniquely identify
* the field) or FieldTracking (which contains info used
* to track access to the field).
* There is also 'extra_data', which is a sort of fall-back
* option, for the meta-data that does not follow under
* any pre-defined category, and that is not general enough
* to warrant a new sub-object or a specific named member/method.
*/
class FieldHeader : public ekat::enable_shared_from_this<FieldHeader> {
public:
using identifier_type = FieldIdentifier;
using tracking_type = FieldTracking;
using extra_data_type = std::map<std::string,ekat::any>;
// Constructor(s)
FieldHeader (const FieldHeader&) = default;
explicit FieldHeader (const identifier_type& id);
FieldHeader (const identifier_type& id,
std::shared_ptr<FieldHeader> parent,
const int idim, const int k);
// Assignment deleted, to prevent sneaky overwrites.
FieldHeader& operator= (const FieldHeader&) = delete;
// Set extra data
void set_extra_data (const std::string& key,
const ekat::any& data,
const bool throw_if_existing = false);
template<typename T>
void set_extra_data (const std::string& key,
const T& data,
const bool throw_if_existing = false) {
ekat::any data_any;
data_any.reset<T>(data);
set_extra_data(key,data_any,throw_if_existing);
}
// ----- Getters ----- //
// Get the basic information from the identifier
const identifier_type& get_identifier () const { return m_identifier; }
// Get the tracking
const tracking_type& get_tracking () const { return *m_tracking; }
tracking_type& get_tracking () { return *m_tracking; }
const std::shared_ptr<tracking_type>& get_tracking_ptr () const { return m_tracking; }
// Get the allocation properties
const FieldAllocProp& get_alloc_properties () const { return m_alloc_prop; }
FieldAllocProp& get_alloc_properties () { return m_alloc_prop; }
// Get parent (if any)
std::weak_ptr<FieldHeader> get_parent () const { return m_parent; }
// Get children list (if any)
std::list<std::weak_ptr<FieldHeader>> get_children () const { return m_children; }
// Get the extra data
const extra_data_type& get_extra_data () const { return m_extra_data; }
protected:
// Static information about the field: name, rank, tags
identifier_type m_identifier;
// Tracking of the field
std::shared_ptr<tracking_type> m_tracking;
// Allocation properties
FieldAllocProp m_alloc_prop;
// If this field is a sub-view of another field, we keep a pointer to the parent
// OTOH, if other fields are sub-view of this field, we keep a pointer to them
std::weak_ptr<FieldHeader> m_parent;
std::list<std::weak_ptr<FieldHeader>> m_children;
// Extra data associated with this field
extra_data_type m_extra_data;
};
// Use this free function to exploit features of enable_from_this
template<typename... Args>
inline std::shared_ptr<FieldHeader>
create_header(const Args&... args) {
auto ptr = std::make_shared<FieldHeader>(args...);
ptr->setSelfPointer(ptr);
return ptr;
}
} // namespace scream
#endif // SCREAM_FIELD_HEADER_HPP
| 32.786885 | 88 | 0.706 | ashlynrlee |
87078da0692935a4d1f393f17499b89674a80efb | 29,477 | cpp | C++ | gmm-dpct/gaussian_kernel.dp.cpp | jchlanda/oneAPI-DirectProgramming | 82a1be635f89b4b2a83e36965a60b19fd71e46b2 | [
"BSD-3-Clause"
] | null | null | null | gmm-dpct/gaussian_kernel.dp.cpp | jchlanda/oneAPI-DirectProgramming | 82a1be635f89b4b2a83e36965a60b19fd71e46b2 | [
"BSD-3-Clause"
] | null | null | null | gmm-dpct/gaussian_kernel.dp.cpp | jchlanda/oneAPI-DirectProgramming | 82a1be635f89b4b2a83e36965a60b19fd71e46b2 | [
"BSD-3-Clause"
] | null | null | null | /*
* CUDA Kernels for Expectation Maximization with Gaussian Mixture Models
*
* Author: Andrew Pangborn
*
* Department of Computer Engineering
* Rochester Institute of Technology
*/
#ifndef _TEMPLATE_KERNEL_H_
#define _TEMPLATE_KERNEL_H_
#include <CL/sycl.hpp>
#include <dpct/dpct.hpp>
#include "gaussian.h"
/*
* Compute the multivariate mean of the FCS data
*/
void mvtmeans(float* fcs_data, int num_dimensions, int num_events, float* means,
sycl::nd_item<3> item_ct1) {
int tid = item_ct1.get_local_id(2);
if(tid < num_dimensions) {
means[tid] = 0.0;
// Sum up all the values for each dimension
for(int i = 0; i < num_events; i++) {
means[tid] += fcs_data[i*num_dimensions+tid];
}
// Divide by the # of elements to get the average
means[tid] /= (float) num_events;
}
}
void averageVariance(float* fcs_data, float* means, int num_dimensions, int num_events, float* avgvar,
sycl::nd_item<3> item_ct1, float *variances,
float *total_variance) {
int tid = item_ct1.get_local_id(2);
// Compute average variance for each dimension
if(tid < num_dimensions) {
variances[tid] = 0.0;
// Sum up all the variance
for(int i = 0; i < num_events; i++) {
// variance = (data - mean)^2
variances[tid] += (fcs_data[i*num_dimensions + tid])*(fcs_data[i*num_dimensions + tid]);
}
variances[tid] /= (float) num_events;
variances[tid] -= means[tid]*means[tid];
}
item_ct1.barrier();
if(tid == 0) {
*total_variance = 0.0;
for(int i=0; i<num_dimensions;i++) {
*total_variance += variances[i];
}
*avgvar = *total_variance / (float)num_dimensions;
}
}
// Inverts an NxN matrix 'data' stored as a 1D array in-place
// 'actualsize' is N
// Computes the log of the determinant of the origianl matrix in the process
void invert(float* data, int actualsize, float* log_determinant,
sycl::nd_item<3> item_ct1) {
int maxsize = actualsize;
int n = actualsize;
if (item_ct1.get_local_id(2) == 0) {
*log_determinant = 0.0;
// sanity check
if (actualsize == 1) {
*log_determinant = sycl::log(data[0]);
data[0] = 1.0 / data[0];
} else {
for (int i=1; i < actualsize; i++) data[i] /= data[0]; // normalize row 0
for (int i=1; i < actualsize; i++) {
for (int j=i; j < actualsize; j++) { // do a column of L
float sum = 0.0;
for (int k = 0; k < i; k++)
sum += data[j*maxsize+k] * data[k*maxsize+i];
data[j*maxsize+i] -= sum;
}
if (i == actualsize-1) continue;
for (int j=i+1; j < actualsize; j++) { // do a row of U
float sum = 0.0;
for (int k = 0; k < i; k++)
sum += data[i*maxsize+k]*data[k*maxsize+j];
data[i*maxsize+j] =
(data[i*maxsize+j]-sum) / data[i*maxsize+i];
}
}
for(int i=0; i<actualsize; i++) {
*log_determinant += sycl::log(sycl::fabs(data[i * n + i]));
}
for ( int i = 0; i < actualsize; i++ ) // invert L
for ( int j = i; j < actualsize; j++ ) {
float x = 1.0;
if ( i != j ) {
x = 0.0;
for ( int k = i; k < j; k++ )
x -= data[j*maxsize+k]*data[k*maxsize+i];
}
data[j*maxsize+i] = x / data[j*maxsize+j];
}
for ( int i = 0; i < actualsize; i++ ) // invert U
for ( int j = i; j < actualsize; j++ ) {
if ( i == j ) continue;
float sum = 0.0;
for ( int k = i; k < j; k++ )
sum += data[k*maxsize+j]*( (i==k) ? 1.0 : data[i*maxsize+k] );
data[i*maxsize+j] = -sum;
}
for ( int i = 0; i < actualsize; i++ ) // final inversion
for ( int j = 0; j < actualsize; j++ ) {
float sum = 0.0;
for ( int k = ((i>j)?i:j); k < actualsize; k++ )
sum += ((j==k)?1.0:data[j*maxsize+k])*data[k*maxsize+i];
data[j*maxsize+i] = sum;
}
}
}
}
void compute_pi(clusters_t* clusters, int num_clusters,
sycl::nd_item<3> item_ct1, float *sum) {
if (item_ct1.get_local_id(2) == 0) {
*sum = 0.0;
for(int i=0; i<num_clusters; i++) {
*sum += clusters->N[i];
}
}
item_ct1.barrier();
for (int c = item_ct1.get_local_id(2); c < num_clusters;
c += item_ct1.get_local_range().get(2)) {
if(clusters->N[c] < 0.5f) {
clusters->pi[item_ct1.get_local_id(2)] = 1e-10;
} else {
clusters->pi[item_ct1.get_local_id(2)] = clusters->N[c] / *sum;
}
}
item_ct1.barrier();
}
void compute_constants(clusters_t* clusters, int num_clusters, int num_dimensions,
sycl::nd_item<3> item_ct1, float *determinant_arg,
float *matrix) {
int tid = item_ct1.get_local_id(2);
int num_threads = item_ct1.get_local_range().get(2);
int num_elements = num_dimensions*num_dimensions;
// only one thread computes the inverse so we need a shared argument
float log_determinant;
// Invert the matrix for every cluster
int c = item_ct1.get_group(2);
// Copy the R matrix into shared memory for doing the matrix inversion
for(int i=tid; i<num_elements; i+= num_threads ) {
matrix[i] = clusters->R[c*num_dimensions*num_dimensions+i];
}
item_ct1.barrier();
#if DIAG_ONLY
if(tid == 0) {
determinant_arg = 1.0f;
for(int i=0; i < num_dimensions; i++) {
determinant_arg *= matrix[i*num_dimensions+i];
matrix[i*num_dimensions+i] = 1.0f / matrix[i*num_dimensions+i];
}
determinant_arg = logf(determinant_arg);
}
#else
invert(matrix, num_dimensions, determinant_arg, item_ct1);
#endif
item_ct1.barrier();
log_determinant = *determinant_arg;
// Copy the matrx from shared memory back into the cluster memory
for(int i=tid; i<num_elements; i+= num_threads) {
clusters->Rinv[c*num_dimensions*num_dimensions+i] = matrix[i];
}
item_ct1.barrier();
// Compute the constant
// Equivilent to: log(1/((2*PI)^(M/2)*det(R)^(1/2)))
// This constant is used in all E-step likelihood calculations
if(tid == 0) {
clusters->constant[c] =
-num_dimensions * 0.5f * sycl::log((float)(2.0f * PI)) -
0.5f * log_determinant;
}
}
/*
* Computes the constant, pi, Rinv for each cluster
*
* Needs to be launched with the number of blocks = number of clusters
*/
SYCL_EXTERNAL void constants_kernel(clusters_t *clusters, int num_clusters,
int num_dimensions,
sycl::nd_item<3> item_ct1,
float *determinant_arg, float *sum,
float *matrix) {
// compute_constants(clusters,num_clusters,num_dimensions);
int tid = item_ct1.get_local_id(2);
int bid = item_ct1.get_group(2);
int num_threads = item_ct1.get_local_range().get(2);
int num_elements = num_dimensions*num_dimensions;
// only one thread computes the inverse so we need a shared argument
float log_determinant;
// Invert the matrix for every cluster
// Copy the R matrix into shared memory for doing the matrix inversion
for(int i=tid; i<num_elements; i+= num_threads ) {
matrix[i] = clusters->R[bid*num_dimensions*num_dimensions+i];
}
item_ct1.barrier();
#if DIAG_ONLY
if(tid == 0) {
determinant_arg = 1.0f;
for(int i=0; i < num_dimensions; i++) {
determinant_arg *= matrix[i*num_dimensions+i];
matrix[i*num_dimensions+i] = 1.0f / matrix[i*num_dimensions+i];
}
determinant_arg = logf(determinant_arg);
}
#else
invert(matrix, num_dimensions, determinant_arg, item_ct1);
#endif
item_ct1.barrier();
log_determinant = *determinant_arg;
// Copy the matrx from shared memory back into the cluster memory
for(int i=tid; i<num_elements; i+= num_threads) {
clusters->Rinv[bid*num_dimensions*num_dimensions+i] = matrix[i];
}
item_ct1.barrier();
// Compute the constant
// Equivilent to: log(1/((2*PI)^(M/2)*det(R)^(1/2)))
// This constant is used in all E-step likelihood calculations
if(tid == 0) {
clusters->constant[bid] =
-num_dimensions * 0.5f * sycl::log((float)(2.0f * PI)) -
0.5f * log_determinant;
}
item_ct1.barrier();
if(bid == 0) {
// compute_pi(clusters,num_clusters);
if(tid == 0) {
*sum = 0.0;
for(int i=0; i<num_clusters; i++) {
*sum += clusters->N[i];
}
}
item_ct1.barrier();
for(int i = tid; i < num_clusters; i += num_threads) {
if(clusters->N[i] < 0.5f) {
clusters->pi[tid] = 1e-10;
} else {
clusters->pi[tid] = clusters->N[i] / *sum;
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
//! @param fcs_data FCS data: [num_events]
//! @param clusters Clusters: [num_clusters]
//! @param num_dimensions number of dimensions in an FCS event
//! @param num_events number of FCS events
////////////////////////////////////////////////////////////////////////////////
SYCL_EXTERNAL void seed_clusters_kernel(
const float *fcs_data, clusters_t *clusters, const int num_dimensions,
const int num_clusters, const int num_events, sycl::nd_item<3> item_ct1,
float *means, float *avgvar, float *variances, float *total_variance)
{
int tid = item_ct1.get_local_id(2);
int num_threads = item_ct1.get_local_range().get(2);
int row, col;
float seed;
// Number of elements in the covariance matrix
int num_elements = num_dimensions*num_dimensions;
// shared memory
// Compute the means
// mvtmeans(fcs_data, num_dimensions, num_events, means);
if(tid < num_dimensions) {
means[tid] = 0.0;
// Sum up all the values for each dimension
for(int i = 0; i < num_events; i++) {
means[tid] += fcs_data[i*num_dimensions+tid];
}
// Divide by the # of elements to get the average
means[tid] /= (float) num_events;
}
item_ct1.barrier();
// Compute the average variance
// averageVariance(fcs_data, means, num_dimensions, num_events, &avgvar);
// Compute average variance for each dimension
if(tid < num_dimensions) {
variances[tid] = 0.0;
// Sum up all the variance
for(int i = 0; i < num_events; i++) {
// variance = (data - mean)^2
variances[tid] += (fcs_data[i*num_dimensions + tid])*(fcs_data[i*num_dimensions + tid]);
}
variances[tid] /= (float) num_events;
variances[tid] -= means[tid]*means[tid];
}
item_ct1.barrier();
if(tid == 0) {
*total_variance = 0.0;
for(int i=0; i<num_dimensions;i++) {
*total_variance += variances[i];
}
*avgvar = *total_variance / (float)num_dimensions;
}
item_ct1.barrier();
if(num_clusters > 1) {
seed = (num_events-1.0f)/(num_clusters-1.0f);
} else {
seed = 0.0;
}
// Seed the pi, means, and covariances for every cluster
for(int c=0; c < num_clusters; c++) {
if(tid < num_dimensions) {
clusters->means[c*num_dimensions+tid] = fcs_data[((int)(c*seed))*num_dimensions+tid];
}
for(int i=tid; i < num_elements; i+= num_threads) {
// Add the average variance divided by a constant, this keeps the cov matrix from becoming singular
row = (i) / num_dimensions;
col = (i) % num_dimensions;
if(row == col) {
clusters->R[c*num_dimensions*num_dimensions+i] = 1.0f;
} else {
clusters->R[c*num_dimensions*num_dimensions+i] = 0.0f;
}
}
if(tid == 0) {
clusters->pi[c] = 1.0f/((float)num_clusters);
clusters->N[c] = ((float) num_events) / ((float)num_clusters);
clusters->avgvar[c] = *avgvar / COVARIANCE_DYNAMIC_RANGE;
}
}
}
float parallelSum(float* data, const unsigned int ndata,
sycl::nd_item<3> item_ct1) {
const unsigned int tid = item_ct1.get_local_id(2);
float t;
item_ct1.barrier();
// Butterfly sum. ndata MUST be a power of 2.
for(unsigned int bit = ndata >> 1; bit > 0; bit >>= 1) {
t = data[tid] + data[tid ^ bit]; item_ct1.barrier();
data[tid] = t; item_ct1.barrier();
}
return data[tid];
}
void compute_indices(int num_events, int* start, int* stop,
sycl::nd_item<3> item_ct1) {
// Break up the events evenly between the blocks
int num_pixels_per_block = num_events / NUM_BLOCKS;
// Make sure the events being accessed by the block are aligned to a multiple of 16
num_pixels_per_block = num_pixels_per_block - (num_pixels_per_block % 16);
*start =
item_ct1.get_group(1) * num_pixels_per_block + item_ct1.get_local_id(2);
// Last block will handle the leftover events
if (item_ct1.get_group(1) == item_ct1.get_group_range(1) - 1) {
*stop = num_events;
} else {
*stop = (item_ct1.get_group(1) + 1) * num_pixels_per_block;
}
}
SYCL_EXTERNAL void estep1(float *data, clusters_t *clusters, int num_dimensions,
int num_events, sycl::nd_item<3> item_ct1,
float *means, float *Rinv) {
// Cached cluster parameters
float cluster_pi;
float constant;
const unsigned int tid = item_ct1.get_local_id(2);
int start_index;
int end_index;
int c = item_ct1.get_group(2);
compute_indices(num_events, &start_index, &end_index, item_ct1);
float like;
// This loop computes the expectation of every event into every cluster
//
// P(k|n) = L(x_n|mu_k,R_k)*P(k) / P(x_n)
//
// Compute log-likelihood for every cluster for each event
// L = constant*exp(-0.5*(x-mu)*Rinv*(x-mu))
// log_L = log_constant - 0.5*(x-u)*Rinv*(x-mu)
// the constant stored in clusters[c].constant is already the log of the constant
// copy the means for this cluster into shared memory
if(tid < num_dimensions) {
means[tid] = clusters->means[c*num_dimensions+tid];
}
// copy the covariance inverse into shared memory
for(int i=tid; i < num_dimensions*num_dimensions; i+= NUM_THREADS_ESTEP) {
Rinv[i] = clusters->Rinv[c*num_dimensions*num_dimensions+i];
}
cluster_pi = clusters->pi[c];
constant = clusters->constant[c];
// Sync to wait for all params to be loaded to shared memory
item_ct1.barrier();
for(int event=start_index; event<end_index; event += NUM_THREADS_ESTEP) {
like = 0.0f;
// this does the loglikelihood calculation
#if DIAG_ONLY
for(int j=0; j<num_dimensions; j++) {
like += (data[j*num_events+event]-means[j]) * (data[j*num_events+event]-means[j]) * Rinv[j*num_dimensions+j];
}
#else
for(int i=0; i<num_dimensions; i++) {
for(int j=0; j<num_dimensions; j++) {
like += (data[i*num_events+event]-means[i]) * (data[j*num_events+event]-means[j]) * Rinv[i*num_dimensions+j];
}
}
#endif
// numerator of the E-step probability computation
clusters->memberships[c * num_events + event] =
-0.5f * like + constant + sycl::log(cluster_pi);
}
}
SYCL_EXTERNAL void estep2(float *fcs_data, clusters_t *clusters,
int num_dimensions, int num_clusters, int num_events,
float *likelihood, sycl::nd_item<3> item_ct1,
float *total_likelihoods) {
float temp;
float thread_likelihood = 0.0f;
float max_likelihood;
float denominator_sum;
// Break up the events evenly between the blocks
int num_pixels_per_block = num_events / item_ct1.get_group_range(2);
// Make sure the events being accessed by the block are aligned to a multiple of 16
num_pixels_per_block = num_pixels_per_block - (num_pixels_per_block % 16);
int tid = item_ct1.get_local_id(2);
int start_index;
int end_index;
start_index = item_ct1.get_group(2) * num_pixels_per_block + tid;
// Last block will handle the leftover events
if (item_ct1.get_group(2) == item_ct1.get_group_range(2) - 1) {
end_index = num_events;
} else {
end_index = (item_ct1.get_group(2) + 1) * num_pixels_per_block;
}
total_likelihoods[tid] = 0.0;
// P(x_n) = sum of likelihoods weighted by P(k) (their probability, cluster[c].pi)
// log(a+b) != log(a) + log(b) so we need to do the log of the sum of the exponentials
// For the sake of numerical stability, we first find the max and scale the values
// That way, the maximum value ever going into the exp function is 0 and we avoid overflow
// log-sum-exp formula:
// log(sum(exp(x_i)) = max(z) + log(sum(exp(z_i-max(z))))
for(int pixel=start_index; pixel<end_index; pixel += NUM_THREADS_ESTEP) {
// find the maximum likelihood for this event
max_likelihood = clusters->memberships[pixel];
for(int c=1; c<num_clusters; c++) {
max_likelihood = sycl::fmax(
max_likelihood, clusters->memberships[c * num_events + pixel]);
}
// Compute P(x_n), the denominator of the probability (sum of weighted likelihoods)
denominator_sum = 0.0;
for(int c=0; c<num_clusters; c++) {
temp = sycl::exp(clusters->memberships[c * num_events + pixel] -
max_likelihood);
denominator_sum += temp;
}
denominator_sum = max_likelihood + sycl::log(denominator_sum);
thread_likelihood += denominator_sum;
// Divide by denominator, also effectively normalize probabilities
// exp(log(p) - log(denom)) == p / denom
for(int c=0; c<num_clusters; c++) {
clusters->memberships[c * num_events + pixel] =
sycl::exp(clusters->memberships[c * num_events + pixel] -
denominator_sum);
//printf("Probability that pixel #%d is in cluster #%d: %f\n",pixel,c,clusters->memberships[c*num_events+pixel]);
}
}
total_likelihoods[tid] = thread_likelihood;
item_ct1.barrier();
temp = parallelSum(total_likelihoods, NUM_THREADS_ESTEP, item_ct1);
if(tid == 0) {
likelihood[item_ct1.get_group(2)] = temp;
}
}
/*
* Means kernel
* MultiGPU version, sums up all of the elements, but does not divide by N.
* This task is left for the host after combing results from multiple GPUs
*
* Should be launched with [M x D] grid
*/
SYCL_EXTERNAL void mstep_means(float *fcs_data, clusters_t *clusters,
int num_dimensions, int num_clusters,
int num_events, sycl::nd_item<3> item_ct1,
float *temp_sum) {
// One block per cluster, per dimension: (M x D) grid of blocks
int tid = item_ct1.get_local_id(2);
int num_threads = item_ct1.get_local_range().get(2);
int c = item_ct1.get_group(2); // cluster number
int d = item_ct1.get_group(1); // dimension number
float sum = 0.0f;
for(int event=tid; event < num_events; event+= num_threads) {
sum += fcs_data[d*num_events+event]*clusters->memberships[c*num_events+event];
}
temp_sum[tid] = sum;
item_ct1.barrier();
// Reduce partial sums
sum = parallelSum(temp_sum, NUM_THREADS_MSTEP, item_ct1);
if(tid == 0) {
clusters->means[c*num_dimensions+d] = sum;
}
/*if(tid == 0) {
for(int i=1; i < num_threads; i++) {
temp_sum[0] += temp_sum[i];
}
clusters->means[c*num_dimensions+d] = temp_sum[0];
//clusters->means[c*num_dimensions+d] = temp_sum[0] / clusters->N[c];
}*/
}
/*
* Computes the size of each cluster, N
* Should be launched with M blocks (where M = number of clusters)
*/
SYCL_EXTERNAL void mstep_N(clusters_t *clusters, int num_dimensions,
int num_clusters, int num_events,
sycl::nd_item<3> item_ct1, float *temp_sums) {
int tid = item_ct1.get_local_id(2);
int num_threads = item_ct1.get_local_range().get(2);
int c = item_ct1.get_group(2);
// Need to store the sum computed by each thread so in the end
// a single thread can reduce to get the final sum
// Compute new N
float sum = 0.0f;
// Break all the events accross the threads, add up probabilities
for(int event=tid; event < num_events; event += num_threads) {
sum += clusters->memberships[c*num_events+event];
}
temp_sums[tid] = sum;
item_ct1.barrier();
sum = parallelSum(temp_sums, NUM_THREADS_MSTEP, item_ct1);
if(tid == 0) {
clusters->N[c] = sum;
clusters->pi[c] = sum;
}
// Let the first thread add up all the intermediate sums
// Could do a parallel reduction...doubt it's really worth it for so few elements though
/*if(tid == 0) {
clusters->N[c] = 0.0;
for(int j=0; j<num_threads; j++) {
clusters->N[c] += temp_sums[j];
}
//printf("clusters[%d].N = %f\n",c,clusters[c].N);
// Set PI to the # of expected items, and then normalize it later
clusters->pi[c] = clusters->N[c];
}*/
}
/*
* Computes the row and col of a square matrix based on the index into
* a lower triangular (with diagonal) matrix
*
* Used to determine what row/col should be computed for covariance
* based on a block index.
*/
void compute_row_col(int n, int* row, int* col, sycl::nd_item<3> item_ct1) {
int i = 0;
for(int r=0; r < n; r++) {
for(int c=0; c <= r; c++) {
if (i == item_ct1.get_group(1)) {
*row = r;
*col = c;
return;
}
i++;
}
}
}
/*
* Computes the covariance matrices of the data (R matrix)
* Must be launched with a M x D*D grid of blocks:
* i.e. dim3 gridDim(num_clusters,num_dimensions*num_dimensions)
*/
void
mstep_covariance1(float* fcs_data, clusters_t* clusters, int num_dimensions, int num_clusters, int num_events,
sycl::nd_item<3> item_ct1, float *means, float *temp_sums) {
int tid =
item_ct1.get_local_id(2); // easier variable name for our thread ID
// Determine what row,col this matrix is handling, also handles the symmetric element
int row,col,c;
compute_row_col(num_dimensions, &row, &col, item_ct1);
//row = blockIdx.y / num_dimensions;
//col = blockIdx.y % num_dimensions;
item_ct1.barrier();
c = item_ct1.get_group(2); // Determines what cluster this block is handling
int matrix_index = row * num_dimensions + col;
#if DIAG_ONLY
if(row != col) {
clusters->R[c*num_dimensions*num_dimensions+matrix_index] = 0.0;
matrix_index = col*num_dimensions+row;
clusters->R[c*num_dimensions*num_dimensions+matrix_index] = 0.0;
return;
}
#endif
// Store the means in shared memory to speed up the covariance computations
// copy the means for this cluster into shared memory
if(tid < num_dimensions) {
means[tid] = clusters->means[c*num_dimensions+tid];
}
// Sync to wait for all params to be loaded to shared memory
item_ct1.barrier();
float cov_sum = 0.0;
for(int event=tid; event < num_events; event+=NUM_THREADS_MSTEP) {
cov_sum += (fcs_data[row*num_events+event]-means[row])*
(fcs_data[col*num_events+event]-means[col])*clusters->memberships[c*num_events+event];
}
temp_sums[tid] = cov_sum;
item_ct1.barrier();
cov_sum = parallelSum(temp_sums, NUM_THREADS_MSTEP, item_ct1);
if(tid == 0) {
clusters->R[c*num_dimensions*num_dimensions+matrix_index] = cov_sum;
// Set the symmetric value
matrix_index = col*num_dimensions+row;
clusters->R[c*num_dimensions*num_dimensions+matrix_index] = cov_sum;
// Regularize matrix - adds some variance to the diagonal elements
// Helps keep covariance matrix non-singular (so it can be inverted)
// The amount added is scaled down based on COVARIANCE_DYNAMIC_RANGE constant defined at top of this file
if(row == col) {
clusters->R[c*num_dimensions*num_dimensions+matrix_index] += clusters->avgvar[c];
}
}
}
SYCL_EXTERNAL void mstep_covariance2(float *fcs_data, clusters_t *clusters,
int num_dimensions, int num_clusters,
int num_events, sycl::nd_item<3> item_ct1,
float *means_row, float *means_col,
float *temp_sums) {
int tid =
item_ct1.get_local_id(2); // easier variable name for our thread ID
// Determine what row,col this matrix is handling, also handles the symmetric element
int row,col,c1;
compute_row_col(num_dimensions, &row, &col, item_ct1);
item_ct1.barrier();
c1 = item_ct1.get_group(2) *
NUM_CLUSTERS_PER_BLOCK; // Determines what cluster this block is
// handling
#if DIAG_ONLY
if(row != col) {
clusters->R[c*num_dimensions*num_dimensions+row*num_dimensions+col] = 0.0f;
clusters->R[c*num_dimensions*num_dimensions+col*num_dimensions+row] = 0.0f;
return;
}
#endif
// Store the means in shared memory to speed up the covariance computations
//if(tid < NUM_CLUSTERS_PER_BLOCK) {
if ((tid < sycl::min(num_clusters, NUM_CLUSTERS_PER_BLOCK)) // c1 = 0
&& (c1 + tid < num_clusters)) {
means_row[tid] = clusters->means[(c1+tid)*num_dimensions+row];
means_col[tid] = clusters->means[(c1+tid)*num_dimensions+col];
}
// Sync to wait for all params to be loaded to shared memory
item_ct1.barrier();
// 256 * 6
float cov_sum1 = 0.0f;
float cov_sum2 = 0.0f;
float cov_sum3 = 0.0f;
float cov_sum4 = 0.0f;
float cov_sum5 = 0.0f;
float cov_sum6 = 0.0f;
float val1,val2;
for(int c=0; c < NUM_CLUSTERS_PER_BLOCK; c++) {
temp_sums[c*NUM_THREADS_MSTEP+tid] = 0.0;
}
for(int event=tid; event < num_events; event+=NUM_THREADS_MSTEP) {
val1 = fcs_data[row*num_events+event];
val2 = fcs_data[col*num_events+event];
cov_sum1 += (val1-means_row[0])*(val2-means_col[0])*clusters->memberships[c1*num_events+event];
cov_sum2 += (val1-means_row[1])*(val2-means_col[1])*clusters->memberships[(c1+1)*num_events+event];
cov_sum3 += (val1-means_row[2])*(val2-means_col[2])*clusters->memberships[(c1+2)*num_events+event];
cov_sum4 += (val1-means_row[3])*(val2-means_col[3])*clusters->memberships[(c1+3)*num_events+event];
cov_sum5 += (val1-means_row[4])*(val2-means_col[4])*clusters->memberships[(c1+4)*num_events+event];
cov_sum6 += (val1-means_row[5])*(val2-means_col[5])*clusters->memberships[(c1+5)*num_events+event];
}
temp_sums[0*NUM_THREADS_MSTEP+tid] = cov_sum1;
temp_sums[1*NUM_THREADS_MSTEP+tid] = cov_sum2;
temp_sums[2*NUM_THREADS_MSTEP+tid] = cov_sum3;
temp_sums[3*NUM_THREADS_MSTEP+tid] = cov_sum4;
temp_sums[4*NUM_THREADS_MSTEP+tid] = cov_sum5;
temp_sums[5*NUM_THREADS_MSTEP+tid] = cov_sum6;
item_ct1.barrier();
for(int c=0; c < NUM_CLUSTERS_PER_BLOCK; c++) {
temp_sums[c * NUM_THREADS_MSTEP + tid] = parallelSum(
&temp_sums[c * NUM_THREADS_MSTEP], NUM_THREADS_MSTEP, item_ct1);
item_ct1.barrier();
}
if(tid == 0) {
for(int c=0; c < NUM_CLUSTERS_PER_BLOCK && (c+c1) < num_clusters; c++) {
int offset = (c+c1)*num_dimensions*num_dimensions;
cov_sum1 = temp_sums[c*NUM_THREADS_MSTEP];
clusters->R[offset+row*num_dimensions+col] = cov_sum1;
// Set the symmetric value
clusters->R[offset+col*num_dimensions+row] = cov_sum1;
// Regularize matrix - adds some variance to the diagonal elements
// Helps keep covariance matrix non-singular (so it can be inverted)
// The amount added is scaled down based on COVARIANCE_DYNAMIC_RANGE constant defined in gaussian.h
if(row == col) {
clusters->R[offset+row*num_dimensions+col] += clusters->avgvar[c+c1];
}
}
}
}
#endif // #ifndef _TEMPLATE_KERNEL_H_
| 35.217443 | 129 | 0.585982 | jchlanda |
87081461e53cd42fa90373d68e2886e31cb176fb | 1,964 | cpp | C++ | ddynamic_reconfigure/test/dd_param/test_dd_double.cpp | manomitbal/realsense-ros | 35a6f59fdfef460bc1e9f225e1a15547e2934175 | [
"Apache-2.0"
] | 45 | 2020-03-13T00:00:36.000Z | 2021-12-14T14:12:12.000Z | ddynamic_reconfigure/test/dd_param/test_dd_double.cpp | manomitbal/realsense-ros | 35a6f59fdfef460bc1e9f225e1a15547e2934175 | [
"Apache-2.0"
] | 4 | 2021-06-08T22:12:54.000Z | 2022-03-12T00:44:32.000Z | ddynamic_reconfigure/test/dd_param/test_dd_double.cpp | manomitbal/realsense-ros | 35a6f59fdfef460bc1e9f225e1a15547e2934175 | [
"Apache-2.0"
] | 7 | 2020-03-06T05:10:41.000Z | 2021-12-14T04:38:00.000Z | #include <ros/ros.h>
#include <gtest/gtest.h>
#include <ddynamic_reconfigure/param/dd_double_param.h>
namespace ddynamic_reconfigure {
/**
* @brief preliminary test which makes sure we can use the object.
*/
TEST(DDDoubleTest, constructorTest) { // NOLINT(cert-err58-cpp,modernize-use-equals-delete)
DDDouble param1("param1",0,"param1",0.5);
DDDouble param2("",0,"",1,10);
DDDouble param3("\000",0,"\000", -0, -3.4e100, 43.5e20); // NOLINT(bugprone-string-literal-with-embedded-nul)
}
/**
* @brief a test making sure we can handle all API for handling the values of the param
*/
TEST(DDDoubleTest, valueTest) { // NOLINT(cert-err58-cpp,modernize-use-equals-delete)
DDDouble param("dd_param",0,"dd_param",1);
// we won't do any tests on getLevel or getName, as those are implicit.
Value v(1.0);
ASSERT_TRUE(param.sameType(v));
ASSERT_TRUE(param.sameValue(v));
v = Value(1);
ASSERT_FALSE(param.sameType(v));
ASSERT_TRUE(param.sameValue(v));
v = Value(2.0);
ASSERT_TRUE(param.sameType(v));
ASSERT_FALSE(param.sameValue(v));
v = Value(2);
ASSERT_FALSE(param.sameType(v));
ASSERT_FALSE(param.sameValue(v));
param.setValue(v);
v = Value(3);
ASSERT_FALSE(param.sameValue(v)); // makes sure anti-aliasing happens
ASSERT_TRUE(param.getValue().getType() == "double");
ASSERT_TRUE(param.sameValue(Value(2)));
}
TEST(DDDoubleTest, streamTest) { // NOLINT(cert-err58-cpp,modernize-use-equals-delete)
DDDouble param1("param1",0,"param1",1.0);
stringstream stream;
stream << param1;
ASSERT_EQ(param1.getName() + ":" + param1.getValue().toString(),stream.str());
}
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
srand((unsigned int)random());
return RUN_ALL_TESTS();
} | 32.196721 | 117 | 0.625255 | manomitbal |