hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4d43095614cc3cec15ec32220c075416b80b4334 | 108,800 | cpp | C++ | jni/RTKLIB/app/qtapp/rtkplot_qt/plotmain.cpp | wjw164833/RtkGpsForPad | c9fb10c0bc56cfa473582088dbc673c6da2d31be | [
"BSD-2-Clause"
] | 2 | 2022-01-10T06:25:39.000Z | 2022-02-25T10:26:39.000Z | jni/RTKLIB/app/qtapp/rtkplot_qt/plotmain.cpp | wjw164833/RtkGpsForPad | c9fb10c0bc56cfa473582088dbc673c6da2d31be | [
"BSD-2-Clause"
] | null | null | null | jni/RTKLIB/app/qtapp/rtkplot_qt/plotmain.cpp | wjw164833/RtkGpsForPad | c9fb10c0bc56cfa473582088dbc673c6da2d31be | [
"BSD-2-Clause"
] | 2 | 2021-12-28T10:16:17.000Z | 2022-02-25T10:26:41.000Z | //---------------------------------------------------------------------------
// rtkplot : visualization of solution and obs data ap
//
// Copyright (C) 2007-2020 by T.TAKASU, All rights reserved.
// ported to Qt by Jens Reimann
//
// options : rtkplot [-t title][-i file][-r][-p path][-x level][file ...]
//
// -t title window title
// -i file ini file path
// -r open file as obs and nav file
// -p path connect to path
// serial://port[:brate[:bsize[:parity[:stopb[:fctr]]]]]
// tcpsvr://:port
// tcpcli://addr[:port]
// ntrip://[user[:passwd]@]addr[:port][/mntpnt]
// file://path
// -p1 path connect port 1 to path
// -p2 path connect port 2 to path
// -x level debug trace level (0:off)
// file solution files or rinex obs/nav file
//
// version : $Revision: 1.1 $ $Date: 2008/07/17 22:15:27 $
// history : 2008/07/14 1.0 new
// 2009/11/27 1.1 rtklib 2.3.0
// 2010/07/18 1.2 rtklib 2.4.0
// 2010/06/10 1.3 rtklib 2.4.1
// 2010/06/19 1.4 rtklib 2.4.1 p1
// 2012/11/21 1.5 rtklib 2.4.2
// 2016/06/11 1.6 rtklib 2.4.3
// 2020/11/30 1.7 support NavIC/IRNSS
// delete functions for Google Earth View
// support Map API by Leaflet for Map View
// move Google Map API Key option to Map View
// modify order of ObsType selections
// improve slip detection performance by LG jump
// fix bug on MP computation for L3,L4,... freq.
//---------------------------------------------------------------------------
#include <clocale>
#include <QShowEvent>
#include <QCloseEvent>
#include <QResizeEvent>
#include <QMouseEvent>
#include <QFocusEvent>
#include <QKeyEvent>
#include <QWheelEvent>
#include <QPaintEvent>
#include <QDebug>
#include <QToolBar>
#include <QScreen>
#include <QtGlobal>
#include <QFileInfo>
#include <QFileInfo>
#include <QCommandLineParser>
#include <QFileDialog>
#include <QClipboard>
#include <QSettings>
#include <QFont>
#include <QMimeData>
#include "rtklib.h"
#include "plotmain.h"
#include "plotopt.h"
#include "refdlg.h"
#include "tspandlg.h"
#include "aboutdlg.h"
#include "conndlg.h"
#include "console.h"
#include "pntdlg.h"
#include "mapoptdlg.h"
#include "skydlg.h"
#include "freqdlg.h"
#include "mapview.h"
#include "viewer.h"
#include "vmapdlg.h"
#include "fileseldlg.h"
#define YLIM_AGE 10.0 // ylimit of age of differential
#define YLIM_RATIO 20.0 // ylimit of raito factor
#define MAXSHAPEFILE 16 // max number of shape files
static int RefreshTime = 100; // update only every 100ms
extern QString color2String(const QColor &c);
extern "C" {
extern void settime(gtime_t) {}
extern void settspan(gtime_t, gtime_t) {}
}
// instance of Plot --------------------------------------------------------
Plot *plot = NULL;
// constructor --------------------------------------------------------------
Plot::Plot(QWidget *parent) : QMainWindow(parent)
{
setupUi(this);
plot = this;
setWindowIcon(QIcon(":/icons/rtk2.bmp"));
setlocale(LC_NUMERIC, "C"); // use point as decimal separator in formatted output
gtime_t t0 = { 0, 0 };
nav_t nav0;
obs_t obs0 = { 0, 0, NULL };
sta_t sta0;
gis_t gis0 = {};
solstatbuf_t solstat0 = { 0, 0, 0 };
double ep[] = { 2000, 1, 1, 0, 0, 0 }, xl[2], yl[2];
double xs[] = { -DEFTSPAN / 2, DEFTSPAN / 2 };
memset(&nav0, 0, sizeof(nav_t));
memset(&sta0, 0, sizeof(sta_t));
QString file = QApplication::applicationFilePath();
QFileInfo fi(file);
IniFile = fi.absolutePath() + "/" + fi.baseName() + ".ini";
toolBar->addWidget(Panel1);
FormWidth = FormHeight = 0;
Drag = 0; Xn = Yn = -1; NObs = 0;
IndexObs = NULL;
Az = NULL; El = NULL;
Week = Flush = PlotType = 0;
AnimCycle = 1;
for (int i = 0; i < 2; i++) {
initsolbuf(SolData + i, 0, 0);
SolStat[i] = solstat0;
SolIndex[i] = 0;
}
ObsIndex = 0;
Obs = obs0;
Nav = nav0;
Sta = sta0;
Gis = gis0;
SimObs = 0;
X0 = Y0 = Xc = Yc = Xs = Ys = Xcent = 0.0;
MouseDownTick = 0;
GEState = GEDataState[0] = GEDataState[1] = 0;
GEHeading = 0.0;
OEpoch = t0;
for (int i = 0; i < 3; i++) OPos[i] = OVel[i] = 0.0;
Az = El = NULL;
for (int i = 0; i < NFREQ + NEXOBS; i++) Mp[i] = NULL;
GraphT = new Graph(Disp);
GraphT->Fit = 0;
for (int i = 0; i < 3; i++) {
GraphG[i] = new Graph(Disp);
GraphG[i]->XLPos = 0;
GraphG[i]->GetLim(xl, yl);
GraphG[i]->SetLim(xs, yl);
}
GraphR = new Graph(Disp);
for (int i = 0; i < 2; i++)
GraphE[i] = new Graph(Disp);
GraphS = new Graph(Disp);
GraphR->GetLim(xl, yl);
GraphR->SetLim(xs, yl);
MapSize[0] = MapSize[1] = 0;
MapScaleX = MapScaleY = 0.1;
MapScaleEq = 0;
MapLat = MapLon = 0.0;
PointType = 0;
NWayPnt = 0;
SelWayPnt = -1;
SkySize[0] = SkySize[1] = 0;
SkyCent[0] = SkyCent[1] = 0;
SkyScale = SkyScaleR = 240.0;
SkyFov[0] = SkyFov[1] = SkyFov[2] = 0.0;
SkyElMask = 1;
SkyDestCorr = SkyRes = SkyFlip = 0;
for (int i = 0; i < 10; i++) SkyDest[i] = 0.0;
SkyBinarize = 0;
SkyBinThres1 = 0.3;
SkyBinThres2 = 0.1;
for (int i = 0; i < 3; i++) TimeEna[i] = 0;
TimeLabel = AutoScale = ShowStats = 0;
ShowLabel = ShowGLabel = 1;
ShowArrow = ShowSlip = ShowHalfC = ShowErr = ShowEph = 0;
PlotStyle = MarkSize = Origin = RcvPos = 0;
TimeInt = ElMask = YRange = 0.0;
MaxDop = 30.0;
MaxMP = 10.0;
TimeStart = TimeEnd = epoch2time(ep);
Console1 = new Console(this);
Console2 = new Console(this);
RangeList->setParent(0);
RangeList->setWindowFlags(Qt::Window | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint | Qt::FramelessWindowHint);
for (int i = 0; i < 361; i++) ElMaskData[i] = 0.0;
Trace = 0;
ConnectState = OpenRaw = 0;
RtConnType = 0;
strinitcom();
strinit(Stream);
strinit(Stream + 1);
FrqType->clear();
FrqType->addItem("L1/LC");
for (int i=0;i<NFREQ;i++) {
FrqType->addItem(QString("L%1").arg(i+1));
}
FrqType->setCurrentIndex(0);
TLEData.n = TLEData.nmax = 0;
TLEData.data = NULL;
freqDialog = new FreqDialog(this);
mapOptDialog = new MapOptDialog(this);
mapView = new MapView(this);
spanDialog = new SpanDialog(this);
connectDialog = new ConnectDialog(this);
skyImgDialog = new SkyImgDialog(this);
plotOptDialog = new PlotOptDialog(this);
aboutDialog = new AboutDialog(this);
pntDialog = new PntDialog(this);
fileSelDialog = new FileSelDialog(this);
viewer = new TextViewer(this);
BtnConnect->setDefaultAction(MenuConnect);
BtnReload->setDefaultAction(MenuReload);
BtnClear->setDefaultAction(MenuClear);
BtnOptions->setDefaultAction(MenuOptions);
BtnMapView->setDefaultAction(MenuMapView);
BtnCenterOri->setDefaultAction(MenuCenterOri);
BtnFitHoriz->setDefaultAction(MenuFitHoriz);
BtnFitVert->setDefaultAction(MenuFitVert);
BtnShowTrack->setDefaultAction(MenuShowTrack);
BtnFixCent->setDefaultAction(MenuFixCent);
BtnFixHoriz->setDefaultAction(MenuFixHoriz);
BtnFixVert->setDefaultAction(MenuFixVert);
BtnShowMap->setDefaultAction(MenuShowMap);
BtnShowGrid->setDefaultAction(MenuShowGrid);
BtnShowImg->setDefaultAction(MenuShowImg);
BtnShowSkyplot->setDefaultAction(MenuShowSkyplot);
MenuShowSkyplot->setChecked(true);
MenuShowGrid->setChecked(true);
dirModel = new QFileSystemModel(this);
dirModel->setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
DirSelector = new QTreeView(this);
Panel2->layout()->addWidget(DirSelector);
DirSelector->setModel(dirModel);
DirSelector->hideColumn(1); DirSelector->hideColumn(2); DirSelector->hideColumn(3); //only show names
fileModel = new QFileSystemModel(this);
fileModel->setFilter((fileModel->filter() & ~QDir::Dirs & ~QDir::AllDirs));
fileModel->setNameFilterDisables(false);
FileList->setModel(fileModel);
connect(BtnOn1, SIGNAL(clicked(bool)), this, SLOT(BtnOn1Click()));
connect(BtnOn2, SIGNAL(clicked(bool)), this, SLOT(BtnOn2Click()));
connect(BtnOn3, SIGNAL(clicked(bool)), this, SLOT(BtnOn3Click()));
connect(BtnSol1, SIGNAL(clicked(bool)), this, SLOT(BtnSol1Click()));//FIXME Double Click
connect(BtnSol2, SIGNAL(clicked(bool)), this, SLOT(BtnSol2Click()));
connect(BtnSol12, SIGNAL(clicked(bool)), this, SLOT(BtnSol12Click()));
connect(BtnRangeList, SIGNAL(clicked(bool)), this, SLOT(BtnRangeListClick()));
connect(BtnAnimate, SIGNAL(clicked(bool)), this, SLOT(BtnAnimateClick()));
connect(MenuAbout, SIGNAL(triggered(bool)), this, SLOT(MenuAboutClick()));
connect(MenuAnimStart, SIGNAL(triggered(bool)), this, SLOT(MenuAnimStartClick()));
connect(MenuAnimStop, SIGNAL(triggered(bool)), this, SLOT(MenuAnimStopClick()));
connect(MenuBrowse, SIGNAL(triggered(bool)), this, SLOT(MenuBrowseClick()));
connect(MenuCenterOri, SIGNAL(triggered(bool)), this, SLOT(MenuCenterOriClick()));
connect(MenuClear, SIGNAL(triggered(bool)), this, SLOT(MenuClearClick()));
connect(MenuConnect, SIGNAL(triggered(bool)), this, SLOT(MenuConnectClick()));
connect(MenuDisconnect, SIGNAL(triggered(bool)), this, SLOT(MenuDisconnectClick()));
connect(MenuFitHoriz, SIGNAL(triggered(bool)), this, SLOT(MenuFitHorizClick()));
connect(MenuFitVert, SIGNAL(triggered(bool)), this, SLOT(MenuFitVertClick()));
connect(MenuFixCent, SIGNAL(triggered(bool)), this, SLOT(MenuFixCentClick()));
connect(MenuFixHoriz, SIGNAL(triggered(bool)), this, SLOT(MenuFixHorizClick()));
connect(MenuFixVert, SIGNAL(triggered(bool)), this, SLOT(MenuFixVertClick()));
connect(MenuMapView, SIGNAL(triggered(bool)), this, SLOT(MenuMapViewClick()));
connect(MenuMapImg, SIGNAL(triggered(bool)), this, SLOT(MenuMapImgClick()));
connect(MenuMax, SIGNAL(triggered(bool)), this, SLOT(MenuMaxClick()));
connect(MenuMonitor1, SIGNAL(triggered(bool)), this, SLOT(MenuMonitor1Click()));
connect(MenuMonitor2, SIGNAL(triggered(bool)), this, SLOT(MenuMonitor2Click()));
connect(MenuOpenElevMask, SIGNAL(triggered(bool)), this, SLOT(MenuOpenElevMaskClick()));
connect(MenuOpenMapImage, SIGNAL(triggered(bool)), this, SLOT(MenuOpenMapImageClick()));
connect(MenuOpenShape, SIGNAL(triggered(bool)), this, SLOT(MenuOpenShapeClick()));
connect(MenuOpenNav, SIGNAL(triggered(bool)), this, SLOT(MenuOpenNavClick()));
connect(MenuOpenObs, SIGNAL(triggered(bool)), this, SLOT(MenuOpenObsClick()));
connect(MenuOpenSkyImage, SIGNAL(triggered(bool)), this, SLOT(MenuOpenSkyImageClick()));
connect(MenuOpenSol1, SIGNAL(triggered(bool)), this, SLOT(MenuOpenSol1Click()));
connect(MenuOpenSol2, SIGNAL(triggered(bool)), this, SLOT(MenuOpenSol2Click()));
connect(MenuOptions, SIGNAL(triggered(bool)), this, SLOT(MenuOptionsClick()));
connect(MenuPlotMapView, SIGNAL(triggered(bool)), this, SLOT(MenuPlotMapViewClick()));
connect(MenuPort, SIGNAL(triggered(bool)), this, SLOT(MenuPortClick()));
connect(MenuShapeFile, SIGNAL(triggered(bool)), this, SLOT(MenuShapeFileClick()));
connect(MenuQuit, SIGNAL(triggered(bool)), this, SLOT(MenuQuitClick()));
connect(MenuReload, SIGNAL(triggered(bool)), this, SLOT(MenuReloadClick()));
connect(MenuSaveDop, SIGNAL(triggered(bool)), this, SLOT(MenuSaveDopClick()));
connect(MenuSaveElMask, SIGNAL(triggered(bool)), this, SLOT(MenuSaveElMaskClick()));
connect(MenuSaveImage, SIGNAL(triggered(bool)), this, SLOT(MenuSaveImageClick()));
connect(MenuSaveSnrMp, SIGNAL(triggered(bool)), this, SLOT(MenuSaveSnrMpClick()));
connect(MenuShowMap, SIGNAL(triggered(bool)), this, SLOT(MenuShowMapClick()));
connect(MenuShowImg, SIGNAL(triggered(bool)), this, SLOT(MenuShowImgClick()));
connect(MenuShowGrid, SIGNAL(triggered(bool)), this, SLOT(MenuShowGridClick()));
connect(MenuShowSkyplot, SIGNAL(triggered(bool)), this, SLOT(MenuShowSkyplotClick()));
connect(MenuShowTrack, SIGNAL(triggered(bool)), this, SLOT(MenuShowTrackClick()));
connect(MenuSkyImg, SIGNAL(triggered(bool)), this, SLOT(MenuSkyImgClick()));
connect(MenuSrcObs, SIGNAL(triggered(bool)), this, SLOT(MenuSrcObsClick()));
connect(MenuSrcSol, SIGNAL(triggered(bool)), this, SLOT(MenuSrcSolClick()));
connect(MenuStatusBar, SIGNAL(triggered(bool)), this, SLOT(MenuStatusBarClick()));
connect(MenuTime, SIGNAL(triggered(bool)), this, SLOT(MenuTimeClick()));
connect(MenuToolBar, SIGNAL(triggered(bool)), this, SLOT(MenuToolBarClick()));
connect(MenuVisAna, SIGNAL(triggered(bool)), this, SLOT(MenuVisAnaClick()));
connect(MenuWaypnt, SIGNAL(triggered(bool)), this, SLOT(MenuWaypointClick()));
connect(MenuMapLayer, SIGNAL(triggered(bool)), this, SLOT(MenuMapLayerClick()));
connect(MenuOpenWaypoint, SIGNAL(triggered(bool)), this, SLOT(MenuOpenWaypointClick()));
connect(MenuSaveWaypoint, SIGNAL(triggered(bool)), this, SLOT(MenuSaveWaypointClick()));
connect(BtnMessage2, SIGNAL(clicked(bool)), this, SLOT(BtnMessage2Click()));
connect(RangeList, SIGNAL(clicked(QModelIndex)), this, SLOT(RangeListClick()));
connect(&Timer, SIGNAL(timeout()), this, SLOT(TimerTimer()));
connect(PlotTypeS, SIGNAL(currentIndexChanged(int)), this, SLOT(PlotTypeSChange()));
connect(QFlag, SIGNAL(currentIndexChanged(int)), this, SLOT(QFlagChange()));
connect(TimeScroll, SIGNAL(valueChanged(int)), this, SLOT(TimeScrollChange()));
connect(SatList, SIGNAL(currentIndexChanged(int)), this, SLOT(SatListChange()));
connect(DopType, SIGNAL(currentIndexChanged(int)), this, SLOT(DopTypeChange()));
connect(ObsType, SIGNAL(currentIndexChanged(int)), this, SLOT(ObsTypeChange()));
connect(ObsType2, SIGNAL(currentIndexChanged(int)), this, SLOT(ObsTypeChange()));
connect(FrqType, SIGNAL(currentIndexChanged(int)), this, SLOT(ObsTypeChange()));
connect(DriveSel, SIGNAL(currentIndexChanged(QString)), this, SLOT(DriveSelChanged()));
connect(DirSelector, SIGNAL(clicked(QModelIndex)), this, SLOT(DirSelChange(QModelIndex)));
connect(DirSelector, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(DirSelSelected(QModelIndex)));
connect(BtnDirSel, SIGNAL(clicked(bool)), this, SLOT(BtnDirSelClick()));
connect(FileList, SIGNAL(clicked(QModelIndex)), this, SLOT(FileListClick(QModelIndex)));
connect(Filter, SIGNAL(currentIndexChanged(QString)), this, SLOT(FilterClick()));
bool state = false;
#ifdef QWEBKIT
state = true;
#endif
#ifdef QWEBENGINE
state = true;
#endif
MenuMapView->setEnabled(state);
MenuPlotMapView->setEnabled(state);
Disp->setAttribute(Qt::WA_OpaquePaintEvent);
setMouseTracking(true);
LoadOpt();
updateTime.start();
qApp->installEventFilter(this);
}
// destructor ---------------------------------------------------------------
Plot::~Plot()
{
delete [] IndexObs;
delete [] Az;
delete [] El;
for (int i = 0; i < NFREQ + NEXOBS; i++) delete Mp[i];
delete GraphT;
delete GraphR;
delete GraphS;
for (int i = 0; i < 2; i++)
delete GraphE[i];
for (int i = 0; i < 3; i++)
delete GraphG[i];
delete RangeList;
delete DirSelector;
}
// callback on all events ----------------------------------------------------
bool Plot::eventFilter(QObject *obj, QEvent *event)
{
if ((obj == Disp) && (event->type() == QEvent::MouseMove))
{
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
if (childAt(mouseEvent->pos()) == Disp)
mouseMove(mouseEvent);
}
if ((obj == Disp) && (event->type() == QEvent::Resize))
{
UpdateSize();
Refresh();
}
return false;
}
// callback on form-show ----------------------------------------------------
void Plot::showEvent(QShowEvent *event)
{
if (event->spontaneous()) {
Refresh();
return;
}
QString path1 = "", path2 = "";
char str_path[256];
trace(3, "FormShow\n");
QCommandLineParser parser;
parser.setApplicationDescription("RTK plot");
parser.addHelpOption();
parser.addVersionOption();
QCommandLineOption rawOption(QStringList() << "r",
QCoreApplication::translate("main", "open raw"));
parser.addOption(rawOption);
QCommandLineOption titleOption(QStringList() << "t" << "title",
QCoreApplication::translate("main", "use window tile <title>."),
QCoreApplication::translate("main", "title"));
parser.addOption(titleOption);
QCommandLineOption pathOption(QStringList() << "p" << "path",
QCoreApplication::translate("main", "open <path>."),
QCoreApplication::translate("main", "path"));
parser.addOption(pathOption);
QCommandLineOption path1Option(QStringList() << "1",
QCoreApplication::translate("main", "open <path> as solution 1."),
QCoreApplication::translate("main", "path"));
parser.addOption(path1Option);
QCommandLineOption path2Option(QStringList() << "2",
QCoreApplication::translate("main", "open <path> as solution 2."),
QCoreApplication::translate("main", "path"));
parser.addOption(path2Option);
QCommandLineOption traceOption(QStringList() << "x" << "tracelevel",
QCoreApplication::translate("main", "set trace lavel to <tracelavel>."),
QCoreApplication::translate("main", "tracelevel"));
parser.addOption(traceOption);
parser.addPositionalArgument("file", QCoreApplication::translate("main", "Read files."));
parser.process(*QApplication::instance());
if (parser.isSet(rawOption))
OpenRaw = 1;
if (parser.isSet(titleOption))
Title = parser.value(titleOption);
if (parser.isSet(pathOption))
path1 = parser.value(pathOption);
if (parser.isSet(path1Option))
path1 = parser.value(path1Option);
if (parser.isSet(path2Option))
path2 = parser.value(path2Option);
if (parser.isSet(traceOption))
Trace = parser.value(traceOption).toInt();
const QStringList args = parser.positionalArguments();
QString file;
foreach(file, args)
OpenFiles.append(file);
if (Trace>0) {
traceopen(TRACEFILE);
tracelevel(Trace);
}
LoadOpt();
UpdateType(PlotType >= PLOT_OBS ? PLOT_TRK : PlotType);
UpdateColor();
UpdateSatMask();
UpdateOrigin();
UpdateSize();
if (path1 != "" || path2 != "") {
ConnectPath(path1, 0);
ConnectPath(path2, 1);
Connect();
} else if (OpenFiles.count() <= 0) {
setWindowTitle(Title != "" ? Title : QString(tr("%1 ver. %2 %3")).arg(PRGNAME).arg(VER_RTKLIB).arg(PATCH_LEVEL));
}
if (ShapeFile!="") {
QStringList files;
char *paths[MAXSHAPEFILE];
for (int i=0;i<MAXSHAPEFILE;i++) {
paths[i]=new char [1024];
}
int n=expath(qPrintable(ShapeFile),paths,MAXSHAPEFILE);
for (int i=0;i<n;i++) {
files.append(paths[i]);
}
ReadShapeFile(files);
for (int i=0;i<MAXSHAPEFILE;i++) {
delete [] paths[i];
}
}
if (TLEFile != "")
tle_read(qPrintable(TLEFile), &TLEData);
if (TLESatFile != "")
tle_name_read(qPrintable(TLESatFile), &TLEData);
QFileInfoList drives = QDir::drives();
if (drives.size() > 1 && drives.at(0).filePath() != "/") {
Panel1->setVisible(true);
DriveSel->clear();
foreach(const QFileInfo &drive, drives) {
DriveSel->addItem(drive.filePath());
}
} else {
Panel1->setVisible(false); // do not show drive selection on unix
}
if (Dir == "") Dir = drives.at(0).filePath();
DriveSel->setCurrentText(Dir.mid(0, Dir.indexOf(":") + 2));
dirModel->setRootPath(Dir);
DirSelector->setVisible(false);
DirSelected->setText(Dir);
fileModel->setRootPath(Dir);
FileList->setRootIndex(fileModel->index(Dir));
FilterClick();
if (MenuBrowse->isChecked()) {
PanelBrowse->setVisible(true);
}
else {
PanelBrowse->setVisible(false);
}
strinit(&StrTimeSync);
NStrBuff=0;
if (TimeSyncOut) {
sprintf(str_path,":%d",TimeSyncPort);
stropen(&StrTimeSync,STR_TCPSVR,STR_MODE_RW,str_path);
}
Timer.start(RefCycle);
UpdatePlot();
UpdateEnable();
if (OpenFiles.count() > 0) {
if (CheckObs(OpenFiles.at(0)) || OpenRaw) ReadObs(OpenFiles);
else ReadSol(OpenFiles, 0);
}
}
// callback on form-close ---------------------------------------------------
void Plot::closeEvent(QCloseEvent *)
{
trace(3, "FormClose\n");
RangeList->setVisible(false);
SaveOpt();
if (Trace > 0) traceclose();
}
// callback for painting --------------------------------------------------
void Plot::paintEvent(QPaintEvent *)
{
UpdateDisp();
}
// callback on form-resize --------------------------------------------------
void Plot::resizeEvent(QResizeEvent *)
{
trace(3, "FormResize\n");
// suppress repeated resize callback
if (FormWidth == width() && FormHeight == height()) return;
UpdateSize();
Refresh();
FormWidth = width();
FormHeight = height();
}
// callback on drag-and-drop files ------------------------------------------
void Plot::dragEnterEvent(QDragEnterEvent *event)
{
trace(3, "dragEnterEvent\n");
if (event->mimeData()->hasFormat("text/uri-list"))
event->acceptProposedAction();
}
// callback on drag-and-drop files ------------------------------------------
void Plot::dropEvent(QDropEvent *event)
{
QStringList files;
int n;
trace(3, "dropEvent\n");
if (ConnectState || !event->mimeData()->hasUrls())
return;
foreach(QUrl url, event->mimeData()->urls()) {
files.append(QDir::toNativeSeparators(url.toString()));
}
QString file=files.at(0);
if (files.size() == 1 && (n = files.at(0).lastIndexOf('.')) != -1) {
QString ext = files.at(0).mid(n).toLower();
if ((ext == "jpg") || (ext == "jpeg")) {
if (PlotType == PLOT_TRK)
ReadMapData(file);
else if (PlotType == PLOT_SKY || PlotType == PLOT_MPS)
ReadSkyData(file);
}
;
} else if (CheckObs(files.at(0))) {
ReadObs(files);
} else if (!BtnSol1->isChecked() && BtnSol2->isChecked()) {
ReadSol(files, 1);
} else {
ReadSol(files, 0);
}
}
// callback on menu-open-solution-1 -----------------------------------------
void Plot::MenuOpenSol1Click()
{
trace(3, "MenuOpenSol1Click\n");
ReadSol(QStringList(QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, tr("Open Solution 1"), QString(), tr("Solution File (*.pos *.stat *.nmea *.txt *.ubx);;All (*.*)")))), 0);
}
// callback on menu-open-solution-2 -----------------------------------------
void Plot::MenuOpenSol2Click()
{
trace(3, "MenuOpenSol2Click\n");
ReadSol(QStringList(QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, tr("Open Solution 2"), QString(), tr("Solution File (*.pos *.stat *.nmea *.txt *.ubx);;All (*.*)")))), 1);
}
// callback on menu-open-map-image ------------------------------------------
void Plot::MenuOpenMapImageClick()
{
trace(3, "MenuOpenMapImage\n");
ReadMapData(QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, tr("Open Map Image"), MapImageFile, tr("JPEG File (*.jpg *.jpeg);;All (*.*)"))));
}
// callback on menu-open-track-points ---------------------------------------
void Plot::MenuOpenShapeClick()
{
trace(3, "MenuOpenShapePath\n");
QStringList files = QFileDialog::getOpenFileNames(this, tr("Open Shape File"), QString(), tr("Shape File (*.shp);;All (*.*)"));
for (int i = 0; i < files.size(); i++)
files[i] = QDir::toNativeSeparators(files.at(i));
ReadShapeFile(files);
}
// callback on menu-open-sky-image ------------------------------------------
void Plot::MenuOpenSkyImageClick()
{
trace(3, "MenuOpenSkyImage\n");
ReadSkyData(QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, tr("Open Sky Image"), SkyImageFile, tr("JPEG File (*.jpg *.jpeg);;All (*.*)"))));
}
// callback on menu-oepn-waypoint -------------------------------------------
void Plot::MenuOpenWaypointClick()
{
trace(3, "MenuOpenWaypointClick\n");
ReadWaypoint(QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, tr("Open Waypoint"), SkyImageFile, tr("Waypoint File (*.gpx, *.pos);;All (*.*)"))));
}
// callback on menu-open-obs-data -------------------------------------------
void Plot::MenuOpenObsClick()
{
trace(3, "MenuOpenObsClick\n");
ReadObs(QFileDialog::getOpenFileNames(this, tr("Open Obs/Nav Data"), QString(), tr("RINEX OBS (*.obs *.*o *.*d *.O.rnx *.*o.gz *.*o.Z *.d.gz *.d.Z);;All (*.*)")));
}
// callback on menu-open-nav-data -------------------------------------------
void Plot::MenuOpenNavClick()
{
trace(3, "MenuOpenNavClick\n");
ReadNav(QFileDialog::getOpenFileNames(this, tr("Open Raw Obs/Nav Messages"), QString(), tr("RINEX NAV (*.nav *.gnav *.hnav *.qnav *.*n *.*g *.*h *.*q *.*p *N.rnx);;All (*.*)")));
}
// callback on menu-open-elev-mask ------------------------------------------
void Plot::MenuOpenElevMaskClick()
{
trace(3, "MenuOpenElevMaskClick\n");
ReadElMaskData(QDir::toNativeSeparators(QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, tr("Opene Elevation Mask"), QString(), tr("Text File (*.txt);;All (*.*)")))));
}
// callback on menu-vis-analysis --------------------------------------------
void Plot::MenuVisAnaClick()
{
if (RcvPos != 1) { // lat/lon/height
ShowMsg(tr("specify Receiver Position as Lat/Lon/Hgt"));
return;
}
if (spanDialog->TimeStart.time == 0) {
int week;
double tow = time2gpst(utc2gpst(timeget()), &week);
spanDialog->TimeStart = gpst2time(week, floor(tow / 3600.0) * 3600.0);
spanDialog->TimeEnd = timeadd(spanDialog->TimeStart, 86400.0);
spanDialog->TimeInt = 30.0;
}
spanDialog->TimeEna[0] = spanDialog->TimeEna[1] = spanDialog->TimeEna[2] = 1;
spanDialog->TimeVal[0] = spanDialog->TimeVal[1] = spanDialog->TimeVal[2] = 2;
spanDialog->exec();
if (spanDialog->result() == QDialog::Accepted) {
TimeStart = spanDialog->TimeStart;
TimeEnd = spanDialog->TimeEnd;
TimeInt = spanDialog->TimeInt;
GenVisData();
}
spanDialog->TimeVal[0] = spanDialog->TimeVal[1] = spanDialog->TimeVal[2] = 1;
}
// callback on menu-save image ----------------------------------------------
void Plot::MenuSaveImageClick()
{
Buff.save(QDir::toNativeSeparators(QFileDialog::getSaveFileName(this, tr("Save Image"), QString(), tr("JPEG (*.jpg);;Windows Bitmap (*.bmp)"))));
}
// callback on menu-save-waypoint -------------------------------------------
void Plot::MenuSaveWaypointClick()
{
trace(3, "MenuSaveWaypointClick\n");
SaveWaypoint(QDir::toNativeSeparators(QFileDialog::getSaveFileName(this, tr("Save Waypoint"), QString(), tr("GPX File (*.gpx, *.pos);;All (*.*)"))));
}
// callback on menu-save-# of sats/dop --------------------------------------
void Plot::MenuSaveDopClick()
{
trace(3, "MenuSaveDopClick\n");
SaveDop(QDir::toNativeSeparators(QFileDialog::getSaveFileName(this, tr("Save Data"), QString(), tr("All (*.*);;Text File (*.txt)"))));
}
// callback on menu-save-snr,azel -------------------------------------------
void Plot::MenuSaveSnrMpClick()
{
trace(3, "MenuSaveSnrMpClick\n");
SaveSnrMp(QDir::toNativeSeparators(QFileDialog::getSaveFileName(this, tr("Save Data"), QString(), tr("All (*.*);;Text File (*.txt)"))));
}
// callback on menu-save-elmask ---------------------------------------------
void Plot::MenuSaveElMaskClick()
{
trace(3, "MenuSaveElMaskClick\n");
SaveElMask(QDir::toNativeSeparators(QFileDialog::getSaveFileName(this, tr("Save Data"), QString(), tr("All (*.*);;Text File (*.txt)"))));
}
// callback on menu-connect -------------------------------------------------
void Plot::MenuConnectClick()
{
trace(3, "MenuConnectClick\n");
Connect();
}
// callback on menu-disconnect ----------------------------------------------
void Plot::MenuDisconnectClick()
{
trace(3, "MenuDisconnectClick\n");
Disconnect();
}
// callback on menu-connection-settings -------------------------------------
void Plot::MenuPortClick()
{
int i;
trace(3, "MenuPortClick\n");
connectDialog->Stream1 = RtStream[0];
connectDialog->Stream2 = RtStream[1];
connectDialog->Format1 = RtFormat[0];
connectDialog->Format2 = RtFormat[1];
connectDialog->TimeForm = RtTimeForm;
connectDialog->DegForm = RtDegForm;
connectDialog->FieldSep = RtFieldSep;
connectDialog->TimeOutTime = RtTimeOutTime;
connectDialog->ReConnTime = RtReConnTime;
for (i = 0; i < 3; i++) {
connectDialog->Paths1[i] = StrPaths[0][i];
connectDialog->Paths2[i] = StrPaths[1][i];
}
for (i = 0; i < 2; i++) {
connectDialog->Cmds1 [i] = StrCmds[0][i];
connectDialog->Cmds2 [i] = StrCmds[1][i];
connectDialog->CmdEna1[i] = StrCmdEna[0][i];
connectDialog->CmdEna2[i] = StrCmdEna[1][i];
}
for (i = 0; i < 10; i++) connectDialog->TcpHistory [i] = StrHistory [i];
connectDialog->exec();
if (connectDialog->result() != QDialog::Accepted) return;
RtStream[0] = connectDialog->Stream1;
RtStream[1] = connectDialog->Stream2;
RtFormat[0] = connectDialog->Format1;
RtFormat[1] = connectDialog->Format2;
RtTimeForm = connectDialog->TimeForm;
RtDegForm = connectDialog->DegForm;
RtFieldSep = connectDialog->FieldSep;
RtTimeOutTime = connectDialog->TimeOutTime;
RtReConnTime = connectDialog->ReConnTime;
for (i = 0; i < 3; i++) {
StrPaths[0][i] = connectDialog->Paths1[i];
StrPaths[1][i] = connectDialog->Paths2[i];
}
for (i = 0; i < 2; i++) {
StrCmds [0][i] = connectDialog->Cmds1 [i];
StrCmds [1][i] = connectDialog->Cmds2 [i];
StrCmdEna[0][i] = connectDialog->CmdEna1[i];
StrCmdEna[1][i] = connectDialog->CmdEna2[i];
}
for (i = 0; i < 10; i++) StrHistory [i] = connectDialog->TcpHistory [i];
}
// callback on menu-reload --------------------------------------------------
void Plot::MenuReloadClick()
{
trace(3, "MenuReloadClick\n");
Reload();
}
// callback on menu-clear ---------------------------------------------------
void Plot::MenuClearClick()
{
trace(3, "MenuClearClick\n");
Clear();
}
// callback on menu-exit-----------------------------------------------------
void Plot::MenuQuitClick()
{
trace(3, "MenuQuitClick\n");
close();
}
// callback on menu-time-span/interval --------------------------------------
void Plot::MenuTimeClick()
{
sol_t *sols, *sole;
int i;
trace(3, "MenuTimeClick\n");
if (!TimeEna[0]) {
if (Obs.n > 0) {
TimeStart = Obs.data[0].time;
} else if (BtnSol2->isChecked() && SolData[1].n > 0) {
sols = getsol(SolData + 1, 0);
TimeStart = sols->time;
} else if (SolData[0].n > 0) {
sols = getsol(SolData, 0);
TimeStart = sols->time;
}
}
if (!TimeEna[1]) {
if (Obs.n > 0) {
TimeEnd = Obs.data[Obs.n - 1].time;
} else if (BtnSol2->isChecked() && SolData[1].n > 0) {
sole = getsol(SolData + 1, SolData[1].n - 1);
TimeEnd = sole->time;
} else if (SolData[0].n > 0) {
sole = getsol(SolData, SolData[0].n - 1);
TimeEnd = sole->time;
}
}
for (i = 0; i < 3; i++)
spanDialog->TimeEna[i] = TimeEna[i];
spanDialog->TimeStart = TimeStart;
spanDialog->TimeEnd = TimeEnd;
spanDialog->TimeInt = TimeInt;
spanDialog->TimeVal[0] = !ConnectState;
spanDialog->TimeVal[1] = !ConnectState;
spanDialog->exec();
if (spanDialog->result() != QDialog::Accepted) return;
if (TimeEna[0] != spanDialog->TimeEna[0] ||
TimeEna[1] != spanDialog->TimeEna[1] ||
TimeEna[2] != spanDialog->TimeEna[2] ||
timediff(TimeStart, spanDialog->TimeStart) != 0.0 ||
timediff(TimeEnd, spanDialog->TimeEnd) != 0.0 ||
!qFuzzyCompare(TimeInt, spanDialog->TimeInt)) {
for (i = 0; i < 3; i++) TimeEna[i] = spanDialog->TimeEna[i];
TimeStart = spanDialog->TimeStart;
TimeEnd = spanDialog->TimeEnd;
TimeInt = spanDialog->TimeInt;
Reload();
}
}
// callback on menu-map-image -----------------------------------------------
void Plot::MenuMapImgClick()
{
trace(3, "MenuMapImgClick\n");
mapOptDialog->show();
}
// callback on menu-sky image -----------------------------------------------
void Plot::MenuSkyImgClick()
{
trace(3, "MenuSkyImgClick\n");
skyImgDialog->show();
}
// callback on menu-vec map -------------------------------------------------
void Plot::MenuMapLayerClick()
{
trace(3, "MenuMapLayerClick\n");
vecMapDialog = new VecMapDialog(this);
vecMapDialog->exec();
delete vecMapDialog;
}
// callback on menu-solution-source -----------------------------------------
void Plot::MenuSrcSolClick()
{
int sel = !BtnSol1->isChecked() && BtnSol2->isChecked();
trace(3, "MenuSrcSolClick\n");
if (SolFiles[sel].count() <= 0) return;
viewer->setWindowTitle(SolFiles[sel].at(0));
viewer->Option = 0;
viewer->show();
viewer->Read(SolFiles[sel].at(0));
}
// callback on menu-obs-data-source -----------------------------------------
void Plot::MenuSrcObsClick()
{
TextViewer *viewer;
char file[1024], tmpfile[1024];
int cstat;
trace(3, "MenuSrcObsClick\n");
if (ObsFiles.count() <= 0) return;
strcpy(file, qPrintable(ObsFiles.at(0)));
cstat = rtk_uncompress(file, tmpfile);
viewer = new TextViewer(this);
viewer->setWindowTitle(ObsFiles.at(0));
viewer->Option = 0;
viewer->show();
viewer->Read(!cstat ? file : tmpfile);
if (cstat) remove(tmpfile);
}
// callback on menu-copy-to-clipboard ---------------------------------------
void Plot::MenuCopyClick()
{
trace(3, "MenuCopyClick\n");
QClipboard *clipboard = QApplication::clipboard();
clipboard->setPixmap(Buff);
}
// callback on menu-options -------------------------------------------------
void Plot::MenuOptionsClick()
{
QString tlefile = TLEFile, tlesatfile = TLESatFile;
double oopos[3];
char str_path[256];
int timesyncout=TimeSyncOut, rcvpos=RcvPos;
trace(3, "MenuOptionsClick\n");
matcpy(oopos,OOPos,3,1);
plotOptDialog->move(pos().x() + width() / 2 - plotOptDialog->width() / 2,
pos().y() + height() / 2 - plotOptDialog->height() / 2);
plotOptDialog->plot = this;
plotOptDialog->exec();
if (plotOptDialog->result() != QDialog::Accepted) return;
SaveOpt();
for (int i = 0; i < 3; i++) oopos[i] -= OOPos[i];
if (TLEFile != tlefile) {
free(TLEData.data);
TLEData.data = NULL;
TLEData.n = TLEData.nmax = 0;
tle_read(qPrintable(TLEFile), &TLEData);
}
if (TLEFile != tlefile || TLESatFile != tlesatfile)
tle_name_read(qPrintable(TLESatFile), &TLEData);
if (rcvpos != RcvPos || norm(oopos, 3) > 1E-3 || TLEFile != tlefile) {
if (SimObs) GenVisData(); else UpdateObs(NObs);
}
UpdateColor();
UpdateSize();
UpdateOrigin();
UpdateInfo();
UpdateSatMask();
UpdateSatList();
Refresh();
Timer.start(RefCycle);
for (int i = 0; i < RangeList->count(); i++) {
QString str=RangeList->item(i)->text();
double range;
QString unit;
QStringList tokens = str.split(' ');
if (tokens.length()==2) {
bool ok;
range = tokens.at(0).toInt(&ok);
unit = tokens.at(1);
if (ok) {
if (unit == "cm") range*=0.01;
else if (unit == "km") range*=1000.0;
if (range==YRange) {
RangeList->item(i)->setSelected(true);
break;
}
}
}
}
if (!timesyncout && TimeSyncOut) {
sprintf(str_path,":%d",TimeSyncPort);
stropen(&StrTimeSync,STR_TCPSVR,STR_MODE_RW,str_path);
}
else if (timesyncout && !TimeSyncOut) {
strclose(&StrTimeSync);
}
}
// callback on menu-show-tool-bar -------------------------------------------
void Plot::MenuToolBarClick()
{
trace(3, "MenuToolBarClick\n");
toolBar->setVisible(MenuToolBar->isChecked());
UpdateSize();
Refresh();
}
// callback on menu-show-status-bar -----------------------------------------
void Plot::MenuStatusBarClick()
{
trace(3, "MenuStatusBarClick\n");
statusbar->setVisible(MenuStatusBar->isChecked());
UpdateSize();
Refresh();
}
// callback on menu-show-browse-panel ---------------------------------------
void Plot::MenuBrowseClick()
{
trace(3,"MenuBrowseClick\n");
if (MenuBrowse->isChecked()) {
PanelBrowse->setVisible(true);
}
else {
PanelBrowse->setVisible(false);
}
Disp->updateGeometry();
UpdateSize();
Refresh();
}
// callback on menu-waypoints -----------------------------------------------
void Plot::MenuWaypointClick()
{
trace(3, "MenuWaypointClick\n");
pntDialog->show();
}
// callback on menu-input-monitor-1 -----------------------------------------
void Plot::MenuMonitor1Click()
{
trace(3, "MenuMonitor1Click\n");
Console1->setWindowTitle(tr("Monitor RT Input 1"));
Console1->show();
}
// callback on menu-input-monitor-2 -----------------------------------------
void Plot::MenuMonitor2Click()
{
trace(3, "MenuMonitor2Click\n");
Console2->setWindowTitle(tr("Monitor RT Input 2"));
Console2->show();
}
// callback on menu-map-view ---------------------------------------
void Plot::MenuMapViewClick()
{
trace(3, "MenuGEClick\n");
mapView->setWindowTitle(
QString(tr("%1 ver.%2 %3: Google Earth View")).arg(PRGNAME).arg(VER_RTKLIB).arg(PATCH_LEVEL));
mapView->show();
}
// callback on menu-center-origin -------------------------------------------
void Plot::MenuCenterOriClick()
{
trace(3, "MenuCenterOriClick\n");
SetRange(0, YRange);
Refresh();
}
// callback on menu-fit-horizontal ------------------------------------------
void Plot::MenuFitHorizClick()
{
trace(3, "MenuFitHorizClick\n");
if (PlotType == PLOT_TRK) FitRange(0); else FitTime();
Refresh();
}
// callback on menu-fit-vertical --------------------------------------------
void Plot::MenuFitVertClick()
{
trace(3, "MenuFitVertClick\n");
FitRange(0);
Refresh();
}
// callback on menu-show-skyplot --------------------------------------------
void Plot::MenuShowSkyplotClick()
{
trace(3, "MenuShowSkyplotClick\n");
UpdatePlot();
UpdateEnable();
}
// callback on menu-show-map-image ------------------------------------------
void Plot::MenuShowImgClick()
{
trace(3, "MenuShowImgClick\n");
UpdatePlot();
UpdateEnable();
}
// callback on menu-show-grid -----------------------------------------------
void Plot::MenuShowGridClick()
{
trace(3,"MenuShowGrid\n");
UpdatePlot();
UpdateEnable();
Refresh();
}
// callback on menu-show-track-points ---------------------------------------
void Plot::MenuShowTrackClick()
{
trace(3, "MenuShowTrackClick\n");
if (!MenuShowTrack->isChecked()) {
MenuFixHoriz->setChecked(false);
MenuFixVert->setChecked(false);
}
UpdatePlot();
UpdateEnable();
}
// callback on menu-fix-center ----------------------------------------------
void Plot::MenuFixCentClick()
{
trace(3, "MenuFixCentClick\n");
UpdatePlot();
UpdateEnable();
}
// callback on menu-fix-horizontal ------------------------------------------
void Plot::MenuFixHorizClick()
{
trace(3, "MenuFixHorizClick\n");
Xcent = 0.0;
UpdatePlot();
UpdateEnable();
}
// callback on menu-fix-vertical --------------------------------------------
void Plot::MenuFixVertClick()
{
trace(3, "MenuFixVertClick\n");
UpdatePlot();
UpdateEnable();
}
// callback on menu-show-map -------------------------------------------------
void Plot::MenuShowMapClick()
{
trace(3, "MenuShowMapClick\n");
UpdatePlot();
UpdateEnable();
}
// callback on menu-windows-maximize ----------------------------------------
void Plot::MenuMaxClick()
{
QScreen *scr = QApplication::screens().at(0);
QRect rect = scr->availableGeometry();
QSize thisDecoration = this->frameSize() - this->size();
this->move(rect.x(), rect.y());
this->resize(rect.width() - thisDecoration.width(), rect.height() - thisDecoration.height());
mapView->hide();
}
// callback on menu-windows-mapview -----------------------------------------
void Plot::MenuPlotMapViewClick()
{
QScreen *scr = QApplication::screens().at(0);
QRect rect = scr->availableGeometry();
QSize thisDecoration = this->frameSize() - this->size();
this->move(rect.x(), rect.y());
this->resize(rect.width() / 2 - thisDecoration.width(), rect.height() - thisDecoration.height());
QSize GEDecoration = mapView->frameSize() - mapView->size();
mapView->resize(rect.width()/2 - GEDecoration.width(), rect.height() - GEDecoration.height());
mapView->move(rect.x() + rect.width() / 2, rect.y());
mapView->setVisible(true);
}
//---------------------------------------------------------------------------
#if 0
void Plot::DispGesture()
{
AnsiString s;
int b, e;
b = EventInfo.Flags.Contains(gfBegin);
e = EventInfo.Flags.Contains(gfEnd);
if (EventInfo.GestureID == Controls::igiZoom) {
s.sprintf("zoom: Location=%d,%d,Flag=%d,%d,Angle=%.1f,Disnance=%d",
EventInfo.Location.X, EventInfo.Location.Y, b, e,
EventInfo.Angle, EventInfo.Distance);
Message1->Caption = s;
} else if (EventInfo.GestureID == Controls::igiPan) {
s.sprintf("pan: Location=%d,%d,Flag=%d,%d,Angle=%.1f,Disnance=%d",
EventInfo.Location.X, EventInfo.Location.Y, b, e,
EventInfo.Angle, EventInfo.Distance);
Message1->Caption = s;
} else if (EventInfo.GestureID == Controls::igiRotate) {
s.sprintf("rotate: Location=%d,%d,Flag=%d,%d,Angle=%.1f,Disnance=%d",
EventInfo.Location.X, EventInfo.Location.Y, b, e,
EventInfo.Angle, EventInfo.Distance);
Message1->Caption = s;
}
}
#endif
// callback on menu-animation-start -----------------------------------------
void Plot::MenuAnimStartClick()
{
trace(3, "MenuAnimStartClick\n");
}
// callback on menu-animation-stop ------------------------------------------
void Plot::MenuAnimStopClick()
{
trace(3, "MenuAnimStopClick\n");
}
// callback on menu-about ---------------------------------------------------
void Plot::MenuAboutClick()
{
trace(3, "MenuAboutClick\n");
aboutDialog->About = PRGNAME;
aboutDialog->IconIndex = 2;
aboutDialog->exec();
}
// callback on button-connect/disconnect ------------------------------------
void Plot::BtnConnectClick()
{
trace(3, "BtnConnectClick\n");
if (!ConnectState) MenuConnectClick();
else MenuDisconnectClick();
}
// callback on button-solution-1 --------------------------------------------
void Plot::BtnSol1Click()
{
trace(3, "BtnSol1Click\n");
BtnSol12->setChecked(false);
UpdateTime();
UpdatePlot();
UpdateEnable();
}
// callback on button-solution-2 --------------------------------------------
void Plot::BtnSol2Click()
{
trace(3, "BtnSol2Click\n");
BtnSol12->setChecked(false);
UpdateTime();
UpdatePlot();
UpdateEnable();
}
// callback on button-solution-1-2 ------------------------------------------
void Plot::BtnSol12Click()
{
trace(3, "BtnSol12Click\n");
BtnSol1->setChecked(false);
BtnSol2->setChecked(false);
UpdateTime();
UpdatePlot();
UpdateEnable();
}
// callback on button-solution-1 double-click -------------------------------
void Plot::BtnSol1DblClick()
{
trace(3, "BtnSol1DblClick\n");
MenuOpenSol1Click();
}
// callback on button-solution-2 double-click -------------------------------
void Plot::BtnSol2DblClick()
{
trace(3, "BtnSol2DblClick\n");
MenuOpenSol2Click();
}
// callback on button-plot-1-onoff ------------------------------------------
void Plot::BtnOn1Click()
{
trace(3, "BtnOn1Click\n");
UpdateSize();
Refresh();
}
// callback on button-plot-2-onoff-------------------------------------------
void Plot::BtnOn2Click()
{
trace(3, "BtnOn2Click\n");
UpdateSize();
Refresh();
}
// callback on button-plot-3-onoff ------------------------------------------
void Plot::BtnOn3Click()
{
trace(3, "BtnOn3Click\n");
UpdateSize();
Refresh();
}
// callback on button-range-list --------------------------------------------
void Plot::BtnRangeListClick()
{
QToolButton *btn=(QToolButton *)sender();
trace(3, "BtnRangeListClick\n");
QPoint pos = btn->mapToGlobal(btn->pos());
pos.rx() -= btn->width();
pos.ry() += btn->height();
RangeList->move(pos);
RangeList->setVisible(!RangeList->isVisible());
}
// callback on button-range-list --------------------------------------------
void Plot::RangeListClick()
{
bool okay;
QString unit;
QListWidgetItem *i;
trace(3, "RangeListClick\n");
RangeList->setVisible(false);
if ((i = RangeList->currentItem()) == NULL) return;
QStringList tokens = i->text().split(" ");
if (tokens.length()!=2) return;
YRange = tokens.at(0).toDouble(&okay);
if (!okay) return;
unit = tokens.at(1);
if (unit == "cm") YRange*=0.01;
else if (unit == "km") YRange*=1000.0;
SetRange(0, YRange);
UpdatePlot();
UpdateEnable();
}
// callback on button-animation ---------------------------------------------
void Plot::BtnAnimateClick()
{
trace(3, "BtnAnimateClick\n");
UpdateEnable();
}
// callback on button-message 2 ---------------------------------------------
void Plot::BtnMessage2Click()
{
if (++PointType > 2) PointType = 0;
}
// callback on plot-type selection change -----------------------------------
void Plot::PlotTypeSChange()
{
int i;
trace(3, "PlotTypeSChnage\n");
for (i = 0; PTypes[i] != NULL; i++)
if (PlotTypeS->currentText() == PTypes[i]) UpdateType(i);
UpdateTime();
UpdatePlot();
UpdateEnable();
}
// callback on quality-flag selection change --------------------------------
void Plot::QFlagChange()
{
trace(3, "QFlagChange\n");
UpdatePlot();
UpdateEnable();
}
// callback on obs-type selection change ------------------------------------
void Plot::ObsTypeChange()
{
trace(3, "ObsTypeChange\n");
UpdatePlot();
UpdateEnable();
}
// callback on dop-type selection change ------------------------------------
void Plot::DopTypeChange()
{
trace(3, "DopTypeChange\n");
UpdatePlot();
UpdateEnable();
}
// callback on satellite-list selection change ------------------------------
void Plot::SatListChange()
{
trace(3, "SatListChange\n");
UpdateSatSel();
UpdatePlot();
UpdateEnable();
}
// callback on time scroll-bar change ---------------------------------------
void Plot::TimeScrollChange()
{
int sel = !BtnSol1->isChecked() && BtnSol2->isChecked() ? 1 : 0;
trace(3, "TimeScrollChange\n");
if (PlotType <= PLOT_NSAT || PlotType == PLOT_RES)
SolIndex[sel] = TimeScroll->value();
else
ObsIndex = TimeScroll->value();
UpdatePlot();
}
// callback on mouse-down event ---------------------------------------------
void Plot::mousePressEvent(QMouseEvent *event)
{
X0 = Disp->mapFromGlobal(event->globalPos()).x();
Y0 = Disp->mapFromGlobal(event->globalPos()).y();
Xcent0 = Xcent;
trace(3, "DispMouseDown: X=%d Y=%d\n", X0, Y0);
Drag = event->buttons().testFlag(Qt::LeftButton) ? 1 : (event->buttons().testFlag(Qt::RightButton) ? 11 : 0);
if (PlotType == PLOT_TRK)
MouseDownTrk(X0, Y0);
else if (PlotType <= PLOT_NSAT || PlotType == PLOT_RES || PlotType == PLOT_SNR)
MouseDownSol(X0, Y0);
else if (PlotType == PLOT_OBS || PlotType == PLOT_DOP)
MouseDownObs(X0, Y0);
else Drag = 0;
RangeList->setVisible(false);
}
// callback on mouse-move event ---------------------------------------------
void Plot::mouseMove(QMouseEvent *event)
{
double dx, dy, dxs, dys;
if ((abs(Disp->mapFromGlobal(event->globalPos()).x() - Xn) < 1) &&
(abs(Disp->mapFromGlobal(event->globalPos()).y() - Yn) < 1)) return;
Xn = Disp->mapFromGlobal(event->globalPos()).x();
Yn = Disp->mapFromGlobal(event->globalPos()).y();
trace(4, "DispMouseMove: X=%d Y=%d\n", Xn, Yn);
if (Drag == 0) {
UpdatePoint(Xn, Yn);
return;
}
dx = (X0 - Xn) * Xs;
dy = (Yn - Y0) * Ys;
dxs = pow(2.0, (X0 - Xn) / 100.0);
dys = pow(2.0, (Yn - Y0) / 100.0);
if (PlotType == PLOT_TRK)
MouseMoveTrk(Xn, Yn, dx, dy, dxs, dys);
else if (PlotType <= PLOT_NSAT || PlotType == PLOT_RES || PlotType == PLOT_SNR)
MouseMoveSol(Xn, Yn, dx, dy, dxs, dys);
else if (PlotType == PLOT_OBS || PlotType == PLOT_DOP)
MouseMoveObs(Xn, Yn, dx, dy, dxs, dys);
}
// callback on mouse-up event -----------------------------------------------
void Plot::mouseReleaseEvent(QMouseEvent *event)
{
trace(3, "DispMouseUp: X=%d Y=%d\n", Disp->mapFromGlobal(event->globalPos()).x(), Disp->mapFromGlobal(event->globalPos()).y());
Drag = 0;
setCursor(Qt::ArrowCursor);
Refresh();
Refresh_MapView();
}
// callback on mouse-double-click -------------------------------------------
void Plot::mouseDoubleClickEvent(QMouseEvent *event)
{
QPoint p(static_cast<int>(X0), static_cast<int>(Y0));
double x, y;
if (event->button() != Qt::LeftButton) return;
trace(3, "DispDblClick X=%d Y=%d\n", p.x(), p.y());
if (BtnFixHoriz->isChecked()) return;
if (PlotType == PLOT_TRK) {
GraphT->ToPos(p, x, y);
GraphT->SetCent(x, y);
Refresh();
Refresh_MapView();
} else if (PlotType <= PLOT_NSAT || PlotType == PLOT_RES || PlotType == PLOT_SNR) {
GraphG[0]->ToPos(p, x, y);
SetCentX(x);
Refresh();
} else if (PlotType == PLOT_OBS || PlotType == PLOT_DOP) {
GraphR->ToPos(p, x, y);
SetCentX(x);
Refresh();
}
}
// callback on mouse-leave event --------------------------------------------
void Plot::leaveEvent(QEvent *)
{
trace(3, "DispMouseLeave\n");
Xn = Yn = -1;
Message2->setVisible(false);
Message2->setText("");
}
// callback on mouse-down event on track-plot -------------------------------
void Plot::MouseDownTrk(int X, int Y)
{
int i, sel = !BtnSol1->isChecked() && BtnSol2->isChecked() ? 1 : 0;
trace(3, "MouseDownTrk: X=%d Y=%d\n", X, Y);
if (Drag == 1 && (i = SearchPos(X, Y)) >= 0) {
SolIndex[sel] = i;
UpdateTime();
UpdateInfo();
Drag = 0;
Refresh();
} else {
GraphT->GetCent(Xc, Yc);
GraphT->GetScale(Xs, Ys);
setCursor(Drag == 1 ? Qt::SizeAllCursor : Qt::SplitVCursor);
}
}
// callback on mouse-down event on solution-plot ----------------------------
void Plot::MouseDownSol(int X, int Y)
{
QPushButton *btn[] = { BtnOn1, BtnOn2, BtnOn3 };
QPoint pnt, p(X, Y);
gtime_t time = { 0, 0 };
sol_t *data;
double x, xl[2], yl[2];
int i, area = -1, sel = !BtnSol1->isChecked() && BtnSol2->isChecked() ? 1 : 0;
trace(3, "MouseDownSol: X=%d Y=%d\n", X, Y);
if (PlotType == PLOT_SNR) {
if (0 <= ObsIndex && ObsIndex < NObs) time = Obs.data[IndexObs[ObsIndex]].time;
} else {
if ((data = getsol(SolData + sel, SolIndex[sel]))) time = data->time;
}
if (time.time && !MenuFixHoriz->isChecked()) {
x = TimePos(time);
GraphG[0]->GetLim(xl, yl);
GraphG[0]->ToPoint(x, yl[1], pnt);
if ((X - pnt.x()) * (X - pnt.x()) + (Y - pnt.y()) * (Y - pnt.y()) < 25) {
setCursor(Qt::SizeHorCursor);
Drag = 20;
Refresh();
return;
}
}
for (i = 0; i < 3; i++) {
if (!btn[i]->isChecked() || (i != 1 && PlotType == PLOT_SNR)) continue;
GraphG[i]->GetCent(Xc, Yc);
GraphG[i]->GetScale(Xs, Ys);
area = GraphG[i]->OnAxis(Disp->mapFromGlobal(p));
if (Drag == 1 && area == 0) {
setCursor(Qt::SizeAllCursor);
Drag += i;
return;
} else if (area == 1) {
setCursor(Drag == 1 ? Qt::SizeVerCursor : Qt::SplitVCursor);
Drag += i + 4;
return;
} else if (area == 0) {
break;
}
}
if (area == 0 || area == 8) {
setCursor(Drag == 1 ? Qt::SizeHorCursor : Qt::SplitHCursor);
Drag += 3;
} else {
Drag = 0;
}
}
// callback on mouse-down event on observation-data-plot --------------------
void Plot::MouseDownObs(int X, int Y)
{
QPoint pnt, p(X, Y);
double x, xl[2], yl[2];
int area;
trace(3, "MouseDownObs: X=%d Y=%d\n", X, Y);
if (0 <= ObsIndex && ObsIndex < NObs && !MenuFixHoriz->isChecked()) {
x = TimePos(Obs.data[IndexObs[ObsIndex]].time);
GraphR->GetLim(xl, yl);
GraphR->ToPoint(x, yl[1], pnt);
if ((X - pnt.x()) * (X - pnt.x()) + (Y - pnt.y()) * (Y - pnt.y()) < 25) {
setCursor(Qt::SizeHorCursor);
Drag = 20;
Refresh();
return;
}
}
GraphR->GetCent(Xc, Yc);
GraphR->GetScale(Xs, Ys);
area = GraphR->OnAxis(Disp->mapFromGlobal(p));
if (area == 0 || area == 8) {
setCursor(Drag == 1 ? Qt::SizeHorCursor : Qt::SplitHCursor);
Drag += 3;
} else {
Drag = 0;
}
}
// callback on mouse-move event on track-plot -------------------------------
void Plot::MouseMoveTrk(int X, int Y, double dx, double dy,
double dxs, double dys)
{
trace(4, "MouseMoveTrk: X=%d Y=%d\n", X, Y);
Q_UNUSED(dxs);
if (Drag == 1 && !MenuFixHoriz->isChecked())
GraphT->SetCent(Xc + dx, Yc + dy);
else if (Drag > 1)
GraphT->SetScale(Xs * dys, Ys * dys);
MenuCenterOri->setChecked(false);
if (updateTime.elapsed() < RefreshTime) return;
updateTime.restart();
Refresh();
}
// callback on mouse-move event on solution-plot ----------------------------
void Plot::MouseMoveSol(int X, int Y, double dx, double dy,
double dxs, double dys)
{
QPoint p1, p2, p(X, Y);
double x, y, xs, ys;
int i, sel = !BtnSol1->isChecked() && BtnSol2->isChecked() ? 1 : 0;
trace(4, "MouseMoveSol: X=%d Y=%d\n", X, Y);
if (Drag <= 4) {
for (i = 0; i < 3; i++) {
GraphG[i]->GetCent(x, y);
if (!MenuFixHoriz->isChecked())
x = Xc + dx;
if (!MenuFixVert->isChecked() || !MenuFixVert->isEnabled())
y = i == Drag - 1 ? Yc + dy : y;
GraphG[i]->SetCent(x, y);
SetCentX(x);
}
if (MenuFixHoriz->isChecked()) {
GraphG[0]->GetPos(p1, p2);
Xcent = Xcent0 + 2.0 * (X - X0) / (p2.x() - p1.x());
if (Xcent > 1.0) Xcent = 1.0;
if (Xcent < -1.0) Xcent = -1.0;
}
} else if (Drag <= 7) {
GraphG[Drag - 5]->GetCent(x, y);
if (!MenuFixVert->isChecked() || !MenuFixVert->isEnabled())
y = Yc + dy;
GraphG[Drag - 5]->SetCent(x, y);
} else if (Drag <= 14) {
for (i = 0; i < 3; i++) {
GraphG[i]->GetScale(xs, ys);
GraphG[i]->SetScale(Xs * dxs, ys);
}
SetScaleX(Xs * dxs);
} else if (Drag <= 17) {
GraphG[Drag - 15]->GetScale(xs, ys);
GraphG[Drag - 15]->SetScale(xs, Ys * dys);
} else if (Drag == 20) {
GraphG[0]->ToPos(p, x, y);
if (PlotType == PLOT_SNR) {
for (i = 0; i < NObs; i++)
if (TimePos(Obs.data[IndexObs[i]].time) >= x) break;
ObsIndex = i < NObs ? i : NObs - 1;
} else {
for (i = 0; i < SolData[sel].n; i++)
if (TimePos(SolData[sel].data[i].time) >= x) break;
SolIndex[sel] = i < SolData[sel].n ? i : SolData[sel].n - 1;
}
UpdateTime();
}
MenuCenterOri->setChecked(false);
if (updateTime.elapsed() < RefreshTime) return;
updateTime.restart();
Refresh();
}
// callback on mouse-move events on observataion-data-plot ------------------
void Plot::MouseMoveObs(int X, int Y, double dx, double dy,
double dxs, double dys)
{
QPoint p1, p2, p(X, Y);
double x, y, xs, ys;
int i;
Q_UNUSED(dys);
trace(4, "MouseMoveObs: X=%d Y=%d\n", X, Y);
if (Drag <= 4) {
GraphR->GetCent(x, y);
if (!MenuFixHoriz->isChecked()) x = Xc + dx;
if (!MenuFixVert->isChecked()) y = Yc + dy;
GraphR->SetCent(x, y);
SetCentX(x);
if (MenuFixHoriz->isChecked()) {
GraphR->GetPos(p1, p2);
Xcent = Xcent0 + 2.0 * (X - X0) / (p2.x() - p1.x());
if (Xcent > 1.0) Xcent = 1.0;
if (Xcent < -1.0) Xcent = -1.0;
}
} else if (Drag <= 14) {
GraphR->GetScale(xs, ys);
GraphR->SetScale(Xs * dxs, ys);
SetScaleX(Xs * dxs);
} else if (Drag == 20) {
GraphR->ToPos(p, x, y);
for (i = 0; i < NObs; i++)
if (TimePos(Obs.data[IndexObs[i]].time) >= x) break;
ObsIndex = i < NObs ? i : NObs - 1;
UpdateTime();
}
MenuCenterOri->setChecked(false);
if (updateTime.elapsed() < RefreshTime) return;
updateTime.restart();
Refresh();
}
// callback on mouse-wheel events -------------------------------------------
void Plot::wheelEvent(QWheelEvent *event)
{
QPoint p(Xn, Yn);
double xs, ys, ds = pow(2.0, -event->angleDelta().y() / 1200.0);
int i, area = -1;
event->accept();
trace(4, "MouseWheel: WheelDelta=%d\n", event->angleDelta().y());
if (Xn < 0 || Yn < 0) return;
if (PlotType == PLOT_TRK) { // track-plot
GraphT->GetScale(xs, ys);
GraphT->SetScale(xs * ds, ys * ds);
} else if (PlotType <= PLOT_NSAT || PlotType == PLOT_RES || PlotType == PLOT_SNR) {
for (i = 0; i < 3; i++) {
if (PlotType == PLOT_SNR && i != 1) continue;
area = GraphG[i]->OnAxis(p);
if (area == 0 || area == 1 || area == 2) {
GraphG[i]->GetScale(xs, ys);
GraphG[i]->SetScale(xs, ys * ds);
} else if (area == 0) {
break;
}
}
if (area == 8) {
for (i = 0; i < 3; i++) {
GraphG[i]->GetScale(xs, ys);
GraphG[i]->SetScale(xs * ds, ys);
SetScaleX(xs * ds);
}
}
} else if (PlotType == PLOT_OBS || PlotType == PLOT_DOP) {
area = GraphR->OnAxis(p);
if (area == 0 || area == 8) {
GraphR->GetScale(xs, ys);
GraphR->SetScale(xs * ds, ys);
SetScaleX(xs * ds);
}
} else {
return;
}
Refresh();
}
// callback on key-down events ----------------------------------------------
void Plot::keyPressEvent(QKeyEvent *event)
{
double sfact = 1.05, fact = event->modifiers().testFlag(Qt::ShiftModifier) ? 1.0 : 10.0;
double xc, yc, yc1, yc2, yc3, xs, ys, ys1, ys2, ys3;
int key = event->modifiers().testFlag(Qt::ControlModifier) ? 10 : 0;
trace(3, "FormKeyDown:\n");
switch (event->key()) {
case Qt::Key_Up: key += 1; break;
case Qt::Key_Down: key += 2; break;
case Qt::Key_Left: key += 3; break;
case Qt::Key_Right: key += 4; break;
default: return;
}
if (event->modifiers().testFlag(Qt::AltModifier)) return;
if (PlotType == PLOT_TRK) {
GraphT->GetCent(xc, yc);
GraphT->GetScale(xs, ys);
if (key == 1) {
if (!MenuFixHoriz->isChecked()) yc += fact * ys;
}
if (key == 2) {
if (!MenuFixHoriz->isChecked()) yc -= fact * ys;
}
if (key == 3) {
if (!MenuFixHoriz->isChecked()) xc -= fact * xs;
}
if (key == 4) {
if (!MenuFixHoriz->isChecked()) xc += fact * xs;
}
if (key == 11) {
xs /= sfact; ys /= sfact;
}
if (key == 12) {
xs *= sfact; ys *= sfact;
}
GraphT->SetCent(xc, yc);
GraphT->SetScale(xs, ys);
} else if (PlotType <= PLOT_NSAT || PlotType == PLOT_RES) {
GraphG[0]->GetCent(xc, yc1);
GraphG[1]->GetCent(xc, yc2);
GraphG[2]->GetCent(xc, yc3);
GraphG[0]->GetScale(xs, ys1);
GraphG[1]->GetScale(xs, ys2);
GraphG[2]->GetScale(xs, ys3);
if (key == 1) {
if (!MenuFixVert->isChecked()) yc1 += fact * ys1;
yc2 += fact * ys2;
yc3 += fact * ys3;
}
if (key == 2) {
if (!MenuFixVert->isChecked()) yc1 -= fact * ys1;
yc2 -= fact * ys2;
yc3 -= fact * ys3;
}
if (key == 3) {
if (!MenuFixHoriz->isChecked()) xc -= fact * xs;
}
if (key == 4) {
if (!MenuFixHoriz->isChecked()) xc += fact * xs;
}
if (key == 11) {
ys1 /= sfact;
ys2 /= sfact;
ys3 /= sfact;
}
if (key == 12) {
ys1 *= sfact;
ys2 *= sfact;
ys3 *= sfact;
}
if (key == 13) xs *= sfact;
if (key == 14) xs /= sfact;
GraphG[0]->SetCent(xc, yc1);
GraphG[1]->SetCent(xc, yc2);
GraphG[2]->SetCent(xc, yc3);
GraphG[0]->SetScale(xs, ys1);
GraphG[1]->SetScale(xs, ys2);
GraphG[2]->SetScale(xs, ys3);
} else if (PlotType == PLOT_OBS || PlotType == PLOT_DOP || PlotType == PLOT_SNR) {
GraphR->GetCent(xc, yc);
GraphR->GetScale(xs, ys);
if (key == 1) {
if (!MenuFixVert->isChecked()) yc += fact * ys;
}
if (key == 2) {
if (!MenuFixVert->isChecked()) yc -= fact * ys;
}
if (key == 3) {
if (!MenuFixHoriz->isChecked()) xc -= fact * xs;
}
if (key == 4) {
if (!MenuFixHoriz->isChecked()) xc += fact * xs;
}
if (key == 11) ys /= sfact;
if (key == 12) xs *= sfact;
if (key == 13) xs *= sfact;
if (key == 14) xs /= sfact;
GraphR->SetCent(xc, yc);
GraphR->SetScale(xs, ys);
}
Refresh();
}
// callback on interval-timer -----------------------------------------------
void Plot::TimerTimer()
{
const QColor color[] = { Qt::red, Qt::gray, QColor(0x00, 0xAA, 0xFF), Qt::green, QColor(0x00, 0xff, 0x00) };
QLabel *strstatus[] = { StrStatus1, StrStatus2 };
Console *console[] = { Console1, Console2 };
QString connectmsg = "";
static uint8_t buff[16384];
solopt_t opt = solopt_default;
sol_t *sol;
const gtime_t ts = { 0, 0 };
gtime_t time = {0, 0};
double tint = TimeEna[2]?TimeInt:0.0, pos[3], ep[6];
int i, j, n, inb, inr, cycle, nmsg[2] = { 0 }, stat, istat;
int sel = !BtnSol1->isChecked() && BtnSol2->isChecked() ? 1 : 0;
char msg[MAXSTRMSG] = "";
trace(4, "TimeTimer\n");
if (ConnectState) { // real-time input mode
for (i = 0; i < 2; i++) {
opt.posf = RtFormat[i];
opt.times = RtTimeForm == 0 ? 0 : RtTimeForm - 1;
opt.timef = RtTimeForm >= 1;
opt.degf = RtDegForm;
strcpy(opt.sep, qPrintable(RtFieldSep));
strsum(Stream + i, &inb, &inr, NULL, NULL);
stat = strstat(Stream + i, msg);
strstatus[i]->setStyleSheet(QStringLiteral("QLabel {color %1;}").arg(color2String(color[stat < 3 ? stat + 1 : 3])));
if (*msg && strcmp(msg, "localhost"))
connectmsg += QStringLiteral("(%1) %2 ").arg(i + 1).arg(msg);
while ((n = strread(Stream + i, buff, sizeof(buff))) > 0) {
for (j = 0; j < n; j++) {
istat = inputsol(buff[j], ts, ts, tint, 0, &opt, SolData + i);
if (istat == 0) continue;
if (istat < 0) { // disconnect received
Disconnect();
return;
}
if (Week == 0 && SolData[i].n == 1) { // first data
if (PlotType > PLOT_NSAT)
UpdateType(PLOT_TRK);
time2gpst(SolData[i].time, &Week);
UpdateOrigin();
ecef2pos(SolData[i].data[0].rr, pos);
mapView->SetCent(pos[0]*R2D,pos[1]*R2D);
}
nmsg[i]++;
}
console[i]->AddMsg(buff, n);
}
if (nmsg[i] > 0) {
strstatus[i]->setStyleSheet(QStringLiteral("QLabel {color %1;}").arg(color2String(color[4])));
SolIndex[i] = SolData[i].n - 1;
}
}
ConnectMsg->setText(connectmsg);
if (nmsg[0] <= 0 && nmsg[1] <= 0) return;
} else if (BtnAnimate->isEnabled() && BtnAnimate->isChecked()) { // animation mode
cycle = AnimCycle <= 0 ? 1 : AnimCycle;
if (PlotType <= PLOT_NSAT || PlotType == PLOT_RES) {
SolIndex[sel] += cycle;
if (SolIndex[sel] >= SolData[sel].n - 1) {
SolIndex[sel] = SolData[sel].n - 1;
BtnAnimate->setChecked(false);
}
} else {
ObsIndex += cycle;
if (ObsIndex >= NObs - 1) {
ObsIndex = NObs - 1;
BtnAnimate->setChecked(false);
}
}
} else if (TimeSyncOut) { // time sync
time.time = 0;
while (strread(&StrTimeSync, (uint8_t *)StrBuff + NStrBuff, 1)) {
if (++NStrBuff >= 1023) {
NStrBuff = 0;
continue;
}
if (StrBuff[NStrBuff-1] == '\n') {
StrBuff[NStrBuff-1] = '\0';
if (sscanf(StrBuff,"%lf/%lf/%lf %lf:%lf:%lf",ep,ep+1,ep+2,
ep+3,ep+4,ep+5)>=6) {
time=epoch2time(ep);
}
NStrBuff = 0;
}
}
if (time.time && (PlotType <= PLOT_NSAT || PlotType <= PLOT_RES)) {
i = SolIndex[sel];
if (!(sol = getsol(SolData + sel, i))) return;
double tt = timediff(sol->time, time);
if (tt < -DTTOL) {
for (;i < SolData[sel].n; i++) {
if (!(sol = getsol(SolData + sel,i))) continue;
if (timediff(sol->time, time) >= -DTTOL) {
i--;
break;
}
}
} else if (tt > DTTOL) {
for (;i >= 0; i--) {
if (!(sol = getsol(SolData + sel,i))) continue;
if (timediff(sol->time, time) <= DTTOL) break;
}
}
SolIndex[sel] = MAX(0, MIN(SolData[sel].n - 1, i));
}
else return;
}
else {
return;
}
UpdateTime();
if (updateTime.elapsed() < RefreshTime) return;
updateTime.restart();
UpdatePlot();
}
// set center of x-axis -----------------------------------------------------
void Plot::SetCentX(double c)
{
double x, y;
int i;
trace(3, "SetCentX: c=%.3f:\n", c);
GraphR->GetCent(x, y);
GraphR->SetCent(c, y);
for (i = 0; i < 3; i++) {
GraphG[i]->GetCent(x, y);
GraphG[i]->SetCent(c, y);
}
}
// set scale of x-axis ------------------------------------------------------
void Plot::SetScaleX(double s)
{
double xs, ys;
int i;
trace(3, "SetScaleX: s=%.3f:\n", s);
GraphR->GetScale(xs, ys);
GraphR->SetScale(s, ys);
for (i = 0; i < 3; i++) {
GraphG[i]->GetScale(xs, ys);
GraphG[i]->SetScale(s, ys);
}
}
// update plot-type with fit-range ------------------------------------------
void Plot::UpdateType(int type)
{
trace(3, "UpdateType: type=%d\n", type);
PlotType = type;
if (AutoScale && PlotType <= PLOT_SOLA && (SolData[0].n > 0 || SolData[1].n > 0))
FitRange(0);
else
SetRange(0, YRange);
UpdatePlotType();
}
// update size of plot ------------------------------------------------------
void Plot::UpdateSize(void)
{
QPushButton *btn[] = { BtnOn1, BtnOn2, BtnOn3 };
QPoint p1(0, 0), p2(Disp->width(), Disp->height());
double xs, ys,font_px=Disp->font().pixelSize()*1.33;
int i, n, h, tmargin, bmargin, rmargin, lmargin;
trace(3, "UpdateSize\n");
tmargin=(int)(font_px*0.9); // top margin (px)
bmargin=(int)(font_px*1.8); // bottom
rmargin=(int)(font_px*1.2); // right
lmargin=(int)(font_px*3.6); // left
GraphT->resize();
GraphS->resize();
GraphR->resize();
for (int i = 0; i < 3; i++)
GraphG[i]->resize();
for (int i = 0; i < 2; i++)
GraphE[i]->resize();
GraphT->SetPos(p1, p2);
GraphS->SetPos(p1, p2);
GraphS->GetScale(xs, ys);
xs = MAX(xs, ys);
GraphS->SetScale(xs, xs);
p1.rx() += lmargin; p1.ry() += tmargin;
p2.rx() -= rmargin; p2.setY(p2.y() - bmargin);
GraphR->SetPos(p1, p2);
p1.setX(p1.x()+(int)(font_px*1.2));
p1.setY(tmargin); p2.setY(p1.y());
for (i = n = 0; i < 3; i++) if (btn[i]->isChecked()) n++;
for (i = 0; i < 3; i++) {
if (!btn[i]->isChecked() || (n <= 0)) continue;
if (n == 0) break;
h = (Disp->height() - tmargin - bmargin) / n;
p2.ry() += h;
GraphG[i]->SetPos(p1, p2);
p1.ry() += h;
}
p1.setY(tmargin); p2.setY(p1.y());
for (i = n = 0; i < 2; i++) if (btn[i]->isChecked()) n++;
for (i = 0; i < 2; i++) {
if (!btn[i]->isChecked() || (n <= 0)) continue;
if (n == 0) break;
h = (Disp->height() - tmargin - bmargin) / n;
p2.ry() += h;
GraphE[i]->SetPos(p1, p2);
p1.ry() += h;
}
}
// update colors on plot ----------------------------------------------------
void Plot::UpdateColor(void)
{
int i;
trace(3, "UpdateColor\n");
for (i = 0; i < 3; i++) {
GraphT->Color[i] = CColor[i];
GraphR->Color[i] = CColor[i];
GraphS->Color[i] = CColor[i];
GraphG[0]->Color[i] = CColor[i];
GraphG[1]->Color[i] = CColor[i];
GraphG[2]->Color[i] = CColor[i];
}
Disp->setFont(Font);
}
// update time-cursor -------------------------------------------------------
void Plot::UpdateTime(void)
{
gtime_t time;
sol_t *sol;
double tt;
int i, sel = !BtnSol1->isChecked() && BtnSol2->isChecked() ? 1 : 0;
trace(3, "UpdateTime\n");
// time-cursor change on solution-plot
if (PlotType <= PLOT_NSAT || PlotType <= PLOT_RES) {
TimeScroll->setMaximum(MAX(1, SolData[sel].n - 1));
TimeScroll->setValue(SolIndex[sel]);
if (!(sol = getsol(SolData + sel, SolIndex[sel]))) return;
time = sol->time;
} else if (NObs > 0) { // time-cursor change on observation-data-plot
TimeScroll->setMaximum(MAX(1, NObs - 1));
TimeScroll->setValue(ObsIndex);
time = Obs.data[IndexObs[ObsIndex]].time;
} else {
return;
}
// time-synchronization between solutions and observation-data
for (sel = 0; sel < 2; sel++) {
i = SolIndex[sel];
if (!(sol = getsol(SolData + sel, i))) continue;
tt = timediff(sol->time, time);
if (tt < -DTTOL) {
for (; i < SolData[sel].n; i++) {
if (!(sol = getsol(SolData + sel, i))) continue;
if (timediff(sol->time, time) >= -DTTOL) break;
}
} else if (tt > DTTOL) {
for (; i >= 0; i--) {
if (!(sol = getsol(SolData + sel, i))) continue;
if (timediff(sol->time, time) <= DTTOL) break;
}
}
SolIndex[sel] = MAX(0, MIN(SolData[sel].n - 1, i));
}
i = ObsIndex;
if (i <= NObs - 1) {
tt = timediff(Obs.data[IndexObs[i]].time, time);
if (tt < -DTTOL) {
for (; i < NObs; i++)
if (timediff(Obs.data[IndexObs[i]].time, time) >= -DTTOL) break;
} else if (tt > DTTOL) {
for (; i >= 0; i--)
if (timediff(Obs.data[IndexObs[i]].time, time) <= DTTOL) break;
}
ObsIndex = MAX(0, MIN(NObs - 1, i));
}
}
// update origin of plot ----------------------------------------------------
void Plot::UpdateOrigin(void)
{
gtime_t time = { 0, 0 };
sol_t *sol;
double opos[3] = { 0 }, pos[3], ovel[3] = { 0 };
int i, j, n = 0, sel = !BtnSol1->isChecked() && BtnSol2->isChecked() ? 1 : 0;
QString sta;
trace(3, "UpdateOrigin\n");
if (Origin == ORG_STARTPOS) {
if (!(sol = getsol(SolData, 0)) || sol->type != 0) return;
for (i = 0; i < 3; i++) opos[i] = sol->rr[i];
} else if (Origin == ORG_ENDPOS) {
if (!(sol = getsol(SolData, SolData[0].n - 1)) || sol->type != 0) return;
for (i = 0; i < 3; i++) opos[i] = sol->rr[i];
} else if (Origin == ORG_AVEPOS) {
for (i = 0; (sol = getsol(SolData, i)) != NULL; i++) {
if (sol->type != 0) continue;
for (j = 0; j < 3; j++) opos[j] += sol->rr[j];
n++;
}
if (n > 0) for (i = 0; i < 3; i++) opos[i] /= n;
} else if (Origin == ORG_FITPOS) {
if (!FitPos(&time, opos, ovel)) return;
} else if (Origin == ORG_REFPOS) {
if (norm(SolData[0].rb, 3) > 0.0) {
for (i = 0; i < 3; i++) opos[i] = SolData[0].rb[i];
} else {
if (!(sol = getsol(SolData, 0)) || sol->type != 0) return;
for (i = 0; i < 3; i++) opos[i] = sol->rr[i];
}
} else if (Origin == ORG_LLHPOS) {
pos2ecef(OOPos, opos);
} else if (Origin == ORG_AUTOPOS) {
if (SolFiles[sel].count() > 0) {
QFileInfo fi(SolFiles[sel].at(0));
ReadStaPos(fi.baseName().left(4).toUpper(), sta, opos);
}
} else if (Origin == ORG_IMGPOS) {
pos[0] = MapLat * D2R;
pos[1] = MapLon * D2R;
pos[2] = 0.0;
pos2ecef(pos, opos);
} else if (Origin == ORG_MAPPOS) {
pos[0] = (Gis.bound[0] + Gis.bound[1]) / 2.0;
pos[1] = (Gis.bound[2] + Gis.bound[3]) / 2.0;
pos[2] = 0.0;
pos2ecef(pos, opos);
} else if (Origin - ORG_PNTPOS < MAXWAYPNT) {
for (i = 0; i < 3; i++) opos[i] = PntPos[Origin - ORG_PNTPOS][i];
}
if (norm(opos, 3) <= 0.0) {
// default start position
if (!(sol = getsol(SolData, 0)) || sol->type != 0) return;
for (i = 0; i < 3; i++) opos[i] = sol->rr[i];
}
OEpoch = time;
for (i = 0; i < 3; i++) {
OPos[i] = opos[i];
OVel[i] = ovel[i];
}
Refresh_MapView();
}
// update satellite mask ----------------------------------------------------
void Plot::UpdateSatMask(void)
{
int sat, prn;
char buff[256], *p;
trace(3, "UpdateSatMask\n");
for (sat = 1; sat <= MAXSAT; sat++) SatMask[sat - 1] = 0;
for (sat = 1; sat <= MAXSAT; sat++)
if (!(satsys(sat, &prn) & NavSys)) SatMask[sat - 1] = 1;
if (ExSats != "") {
strcpy(buff, qPrintable(ExSats));
for (p = strtok(buff, " "); p; p = strtok(NULL, " ")) {
if (*p == '+' && (sat = satid2no(p + 1))) SatMask[sat - 1] = 0; // included
else if ((sat = satid2no(p))) SatMask[sat - 1] = 1; // excluded
}
}
}
// update satellite select ---------------------------------------------------
void Plot::UpdateSatSel(void)
{
QString SatListText = SatList->currentText();
char id[16];
int i, sys = 0;
if (SatListText == "G") sys = SYS_GPS;
else if (SatListText == "R") sys = SYS_GLO;
else if (SatListText == "E") sys = SYS_GAL;
else if (SatListText == "J") sys = SYS_QZS;
else if (SatListText == "C") sys = SYS_CMP;
else if (SatListText == "I") sys = SYS_IRN;
else if (SatListText == "S") sys = SYS_SBS;
for (i = 0; i < MAXSAT; i++) {
satno2id(i + 1, id);
SatSel[i] = SatListText == "ALL" || SatListText == id || satsys(i + 1, NULL) == sys;
}
}
// update enable/disable of widgets -----------------------------------------
void Plot::UpdateEnable(void)
{
bool data = BtnSol1->isChecked() || BtnSol2->isChecked() || BtnSol12->isChecked();
bool plot = (PLOT_SOLP <= PlotType) && (PlotType <= PLOT_NSAT);
bool sel = (!BtnSol1->isChecked()) && (BtnSol2->isChecked()) ? 1 : 0;
trace(3, "UpdateEnable\n");
Panel1->setVisible(MenuToolBar->isChecked());
Panel21->setVisible(MenuStatusBar->isChecked());
MenuConnect->setChecked(ConnectState);
BtnSol1->setEnabled(true);
BtnSol2->setEnabled(PlotType<=PLOT_NSAT||PlotType==PLOT_RES||PlotType==PLOT_RESE);
BtnSol12->setEnabled(!ConnectState && PlotType <= PLOT_SOLA && SolData[0].n > 0 && SolData[1].n > 0);
QFlag->setVisible(PlotType == PLOT_TRK || PlotType == PLOT_SOLP ||
PlotType == PLOT_SOLV || PlotType == PLOT_SOLA ||
PlotType == PLOT_NSAT);
ObsType->setVisible(PlotType == PLOT_OBS || PlotType <= PLOT_SKY);
ObsType2->setVisible(PlotType == PLOT_SNR || PlotType == PLOT_SNRE || PlotType == PLOT_MPS);
FrqType->setVisible(PlotType == PLOT_RES||PlotType==PLOT_RESE);
DopType->setVisible(PlotType == PLOT_DOP);
SatList->setVisible(PlotType == PLOT_RES ||PlotType==PLOT_RESE||PlotType>=PLOT_OBS||
PlotType == PLOT_SKY || PlotType == PLOT_DOP ||
PlotType == PLOT_SNR || PlotType == PLOT_SNRE ||
PlotType == PLOT_MPS);
QFlag->setEnabled(data);
ObsType->setEnabled(data && !SimObs);
ObsType2->setEnabled(data && !SimObs);
Panel102->setVisible(PlotType==PLOT_SOLP||PlotType==PLOT_SOLV||
PlotType==PLOT_SOLA||PlotType==PLOT_NSAT||
PlotType==PLOT_RES ||PlotType==PLOT_RESE||
PlotType==PLOT_SNR ||PlotType==PLOT_SNRE);
BtnOn1->setEnabled(plot||PlotType==PLOT_SNR||PlotType==PLOT_RES||
PlotType==PLOT_RESE||PlotType==PLOT_SNRE);
BtnOn2->setEnabled(plot||PlotType==PLOT_SNR||PlotType==PLOT_RES||
PlotType==PLOT_RESE||PlotType==PLOT_SNRE);
BtnOn3->setEnabled(plot || PlotType == PLOT_SNR || PlotType == PLOT_RES);
BtnCenterOri->setVisible(PlotType == PLOT_TRK || PlotType == PLOT_SOLP ||
PlotType == PLOT_SOLV || PlotType == PLOT_SOLA ||
PlotType == PLOT_NSAT);
BtnCenterOri->setEnabled(PlotType != PLOT_NSAT);
BtnRangeList->setVisible(PlotType == PLOT_TRK || PlotType == PLOT_SOLP ||
PlotType == PLOT_SOLV || PlotType == PLOT_SOLA ||
PlotType == PLOT_NSAT);
BtnRangeList->setEnabled(PlotType != PLOT_NSAT);
BtnFitHoriz->setVisible(PlotType == PLOT_SOLP || PlotType == PLOT_SOLV ||
PlotType == PLOT_SOLA || PlotType == PLOT_NSAT ||
PlotType == PLOT_RES || PlotType == PLOT_OBS ||
PlotType == PLOT_DOP || PlotType == PLOT_SNR ||
PlotType == PLOT_SNRE);
BtnFitVert->setVisible(PlotType == PLOT_TRK || PlotType == PLOT_SOLP ||
PlotType == PLOT_SOLV || PlotType == PLOT_SOLA);
BtnFitHoriz->setEnabled(data);
BtnFitVert->setEnabled(data);
MenuShowTrack->setEnabled(data);
BtnFixCent->setVisible(PlotType == PLOT_TRK);
BtnFixHoriz->setVisible(PlotType == PLOT_SOLP || PlotType == PLOT_SOLV ||
PlotType == PLOT_SOLA || PlotType == PLOT_NSAT ||
PlotType == PLOT_RES || PlotType == PLOT_OBS ||
PlotType == PLOT_DOP || PlotType == PLOT_SNR);
BtnFixVert->setVisible(PlotType == PLOT_SOLP || PlotType == PLOT_SOLV ||
PlotType == PLOT_SOLA);
BtnFixCent->setEnabled(data);
BtnFixHoriz->setEnabled(data);
BtnFixVert->setEnabled(data);
BtnShowMap->setVisible(PlotType == PLOT_TRK);
BtnShowMap->setEnabled(!BtnSol12->isChecked());
MenuMapView->setVisible(PlotType==PLOT_TRK||PlotType==PLOT_SOLP);
Panel12->setVisible(!ConnectState);
BtnAnimate->setVisible(data && MenuShowTrack->isChecked());
TimeScroll->setVisible(data && MenuShowTrack->isChecked());
TimeScroll->setEnabled(data && MenuShowTrack->isChecked());
if (!MenuShowTrack->isChecked()) {
MenuFixHoriz->setEnabled(false);
MenuFixVert->setEnabled(false);
MenuFixCent->setEnabled(false);
BtnAnimate->setChecked(false);
}
MenuMapImg->setEnabled(MapImage.height() > 0);
MenuSkyImg->setEnabled(SkyImageI.height() > 0);
MenuSrcSol->setEnabled(SolFiles[sel].count() > 0);
MenuSrcObs->setEnabled(ObsFiles.count() > 0);
MenuMapLayer->setEnabled(true);
MenuShowSkyplot->setEnabled(MenuShowSkyplot->isVisible());
BtnShowImg->setVisible(PlotType == PLOT_TRK || PlotType == PLOT_SKY ||
PlotType == PLOT_MPS);
BtnShowGrid->setVisible(PlotType==PLOT_TRK);
MenuAnimStart->setEnabled(!ConnectState && BtnAnimate->isEnabled() && !BtnAnimate->isChecked());
MenuAnimStop->setEnabled(!ConnectState && BtnAnimate->isEnabled() && BtnAnimate->isChecked());
MenuOpenSol1->setEnabled(!ConnectState);
MenuOpenSol2->setEnabled(!ConnectState);
MenuConnect->setEnabled(!ConnectState);
MenuDisconnect->setEnabled(ConnectState);
MenuPort->setEnabled(!ConnectState);
MenuOpenObs->setEnabled(!ConnectState);
MenuOpenNav->setEnabled(!ConnectState);
MenuOpenElevMask->setEnabled(!ConnectState);
MenuReload->setEnabled(!ConnectState);
MenuReload->setEnabled(!ConnectState);
StrStatus->setEnabled(ConnectState);
BtnFreq->setVisible(FrqType->isVisible()||ObsType->isVisible()||ObsType2->isVisible());
}
// linear-fitting of positions ----------------------------------------------
int Plot::FitPos(gtime_t *time, double *opos, double *ovel)
{
sol_t *sol;
int i, j;
double t, x[2], Ay[3][2] = { { 0 } }, AA[3][4] = { { 0 } };
trace(3, "FitPos\n");
if (SolData[0].n <= 0) return 0;
for (i = 0; (sol = getsol(SolData, i)) != NULL; i++) {
if (sol->type != 0) continue;
if (time->time == 0) *time = sol->time;
t = timediff(sol->time, *time);
for (j = 0; j < 3; j++) {
Ay[j][0] += sol->rr[j];
Ay[j][1] += sol->rr[j] * t;
AA[j][0] += 1.0;
AA[j][1] += t;
AA[j][2] += t;
AA[j][3] += t * t;
}
}
for (i = 0; i < 3; i++) {
if (solve("N", AA[i], Ay[i], 2, 1, x)) return 0;
opos[i] = x[0];
ovel[i] = x[1];
}
return 1;
}
// fit time-range of plot ---------------------------------------------------
void Plot::FitTime(void)
{
sol_t *sols, *sole;
double tl[2] = { 86400.0 * 7, 0.0 }, tp[2], xl[2], yl[2], zl[2];
int sel = !BtnSol1->isChecked() && BtnSol2->isChecked() ? 1 : 0;
trace(3, "FitTime\n");
sols = getsol(SolData + sel, 0);
sole = getsol(SolData + sel, SolData[sel].n - 1);
if (sols && sole) {
tl[0] = MIN(tl[0], TimePos(sols->time));
tl[1] = MAX(tl[1], TimePos(sole->time));
}
if (Obs.n > 0) {
tl[0] = MIN(tl[0], TimePos(Obs.data[0].time));
tl[1] = MAX(tl[1], TimePos(Obs.data[Obs.n - 1].time));
}
if (TimeEna[0]) tl[0] = TimePos(TimeStart);
if (TimeEna[1]) tl[1] = TimePos(TimeEnd);
if (qFuzzyCompare(tl[0], tl[1])) {
tl[0] = tl[0] - DEFTSPAN / 2.0;
tl[1] = tl[0] + DEFTSPAN / 2.0;
} else if (tl[0] > tl[1]) {
tl[0] = -DEFTSPAN / 2.0;
tl[1] = DEFTSPAN / 2.0;
}
GraphG[0]->GetLim(tp, xl);
GraphG[1]->GetLim(tp, yl);
GraphG[2]->GetLim(tp, zl);
GraphG[0]->SetLim(tl, xl);
GraphG[1]->SetLim(tl, yl);
GraphG[2]->SetLim(tl, zl);
GraphR->GetLim(tp, xl);
GraphR->SetLim(tl, xl);
}
// set x/y-range of plot ----------------------------------------------------
void Plot::SetRange(int all, double range)
{
double xl[] = { -range, range };
double yl[] = { -range, range };
double zl[] = { -range, range };
double xs, ys, tl[2], xp[2], pos[3];
trace(3, "SetRange: all=%d range=%.3f\n", all, range);
if (all || PlotType == PLOT_TRK) {
GraphT->SetLim(xl, yl);
GraphT->GetScale(xs, ys);
GraphT->SetScale(MAX(xs, ys), MAX(xs, ys));
if (norm(OPos, 3) > 0.0) {
ecef2pos(OPos, pos);
mapView->SetCent(pos[0] * R2D, pos[1] * R2D);
}
}
if (PLOT_SOLP <= PlotType && PlotType <= PLOT_SOLA) {
GraphG[0]->GetLim(tl, xp);
GraphG[0]->SetLim(tl, xl);
GraphG[1]->SetLim(tl, yl);
GraphG[2]->SetLim(tl, zl);
} else if (PlotType == PLOT_NSAT) {
GraphG[0]->GetLim(tl, xp);
xl[0] = yl[0] = zl[0] = 0.0;
xl[1] = MaxDop;
yl[1] = YLIM_AGE;
zl[1] = YLIM_RATIO;
GraphG[0]->SetLim(tl, xl);
GraphG[1]->SetLim(tl, yl);
GraphG[2]->SetLim(tl, zl);
} else if (PlotType < PLOT_SNR) {
GraphG[0]->GetLim(tl, xp);
xl[0] = -MaxMP; xl[1] = MaxMP;
yl[0] = -MaxMP/100.0; yl[1] = MaxMP/100.0;
zl[0] = 0.0; zl[1] = 90.0;
GraphG[0]->SetLim(tl, xl);
GraphG[1]->SetLim(tl, yl);
GraphG[2]->SetLim(tl, zl);
} else {
GraphG[0]->GetLim(tl, xp);
xl[0] = 10.0; xl[1] = 60.0;
yl[0] = -MaxMP; yl[1] = MaxMP;
zl[0] = 0.0; zl[1] = 90.0;
GraphG[0]->SetLim(tl, xl);
GraphG[1]->SetLim(tl, yl);
GraphG[2]->SetLim(tl, zl);
}
}
// fit x/y-range of plot ----------------------------------------------------
void Plot::FitRange(int all)
{
TIMEPOS *pos, *pos1, *pos2;
sol_t *data;
double xs, ys, xp[2], tl[2], xl[] = { 1E8, -1E8 }, yl[2] = { 1E8, -1E8 }, zl[2] = { 1E8, -1E8 };
double lat, lon, lats[2] = { 90, -90 }, lons[2] = { 180, -180 }, llh[3];
int i, type = PlotType - PLOT_SOLP;
trace(3, "FitRange: all=%d\n", all);
MenuFixHoriz->setChecked(false);
if (BtnSol1->isChecked()) {
pos = SolToPos(SolData, -1, QFlag->currentIndex(), type);
for (i = 0; i < pos->n; i++) {
xl[0] = MIN(xl[0], pos->x[i]);
yl[0] = MIN(yl[0], pos->y[i]);
zl[0] = MIN(zl[0], pos->z[i]);
xl[1] = MAX(xl[1], pos->x[i]);
yl[1] = MAX(yl[1], pos->y[i]);
zl[1] = MAX(zl[1], pos->z[i]);
}
delete pos;
}
if (BtnSol2->isChecked()) {
pos = SolToPos(SolData + 1, -1, QFlag->currentIndex(), type);
for (i = 0; i < pos->n; i++) {
xl[0] = MIN(xl[0], pos->x[i]);
yl[0] = MIN(yl[0], pos->y[i]);
zl[0] = MIN(zl[0], pos->z[i]);
xl[1] = MAX(xl[1], pos->x[i]);
yl[1] = MAX(yl[1], pos->y[i]);
zl[1] = MAX(zl[1], pos->z[i]);
}
delete pos;
}
if (BtnSol12->isChecked()) {
pos1 = SolToPos(SolData, -1, 0, type);
pos2 = SolToPos(SolData + 1, -1, 0, type);
pos = pos1->diff(pos2, QFlag->currentIndex());
for (i = 0; i < pos->n; i++) {
xl[0] = MIN(xl[0], pos->x[i]);
yl[0] = MIN(yl[0], pos->y[i]);
zl[0] = MIN(zl[0], pos->z[i]);
xl[1] = MAX(xl[1], pos->x[i]);
yl[1] = MAX(yl[1], pos->y[i]);
zl[1] = MAX(zl[1], pos->z[i]);
}
delete pos1;
delete pos2;
delete pos;
}
xl[0] -= 0.05;
xl[1] += 0.05;
yl[0] -= 0.05;
yl[1] += 0.05;
zl[0] -= 0.05;
zl[1] += 0.05;
if (all || PlotType == PLOT_TRK) {
GraphT->SetLim(xl, yl);
GraphT->GetScale(xs, ys);
GraphT->SetScale(MAX(xs, ys), MAX(xs, ys));
}
if (all || PlotType <= PLOT_SOLA || PlotType == PLOT_RES) {
GraphG[0]->GetLim(tl, xp);
GraphG[0]->SetLim(tl, xl);
GraphG[1]->SetLim(tl, yl);
GraphG[2]->SetLim(tl, zl);
}
if (all) {
if (BtnSol1->isChecked()) {
for (i = 0; (data = getsol(SolData, i)) != NULL; i++) {
ecef2pos(data->rr, llh);
lats[0] = MIN(lats[0], llh[0] * R2D);
lons[0] = MIN(lons[0], llh[1] * R2D);
lats[1] = MAX(lats[1], llh[0] * R2D);
lons[1] = MAX(lons[1], llh[1] * R2D);
}
}
if (BtnSol2->isChecked()) {
for (i = 0; (data = getsol(SolData + 1, i)) != NULL; i++) {
ecef2pos(data->rr, llh);
lats[0] = MIN(lats[0], llh[0] * R2D);
lons[0] = MIN(lons[0], llh[1] * R2D);
lats[1] = MAX(lats[1], llh[0] * R2D);
lons[1] = MAX(lons[1], llh[1] * R2D);
}
}
if (lats[0] <= lats[1] && lons[0] <= lons[1]) {
lat = (lats[0] + lats[1]) / 2.0;
lon = (lons[0] + lons[1]) / 2.0;
}
}
}
// set center of track plot -------------------------------------------------
void Plot::SetTrkCent(double lat, double lon)
{
gtime_t time = { 0, 0 };
double pos[3] = { 0 }, rr[3], xyz[3];
if (PlotType != PLOT_TRK) return;
pos[0] = lat * D2R;
pos[1] = lon * D2R;
pos2ecef(pos, rr);
PosToXyz(time, rr, 0, xyz);
GraphT->SetCent(xyz[0], xyz[1]);
UpdatePlot();
}
// load options from ini-file -----------------------------------------------
void Plot::LoadOpt(void)
{
QSettings settings(IniFile, QSettings::IniFormat);
trace(3, "LoadOpt\n");
// PlotType = settings.value("plot/plottype", 0).toInt();
TimeLabel = settings.value("plot/timelabel", 1).toInt();
LatLonFmt = settings.value("plot/latlonfmt", 0).toInt();
AutoScale = settings.value("plot/autoscale", 1).toInt();
ShowStats = settings.value("plot/showstats", 0).toInt();
ShowLabel = settings.value("plot/showlabel", 1).toInt();
ShowGLabel = settings.value("plot/showglabel", 1).toInt();
ShowCompass = settings.value("plot/showcompass", 0).toInt();
ShowScale = settings.value("plot/showscale", 1).toInt();
ShowArrow = settings.value("plot/showarrow", 0).toInt();
ShowSlip = settings.value("plot/showslip", 0).toInt();
ShowHalfC = settings.value("plot/showhalfc", 0).toInt();
ShowErr = settings.value("plot/showerr", 0).toInt();
ShowEph = settings.value("plot/showeph", 0).toInt();
PlotStyle = settings.value("plot/plotstyle", 0).toInt();
MarkSize = settings.value("plot/marksize", 2).toInt();
NavSys = settings.value("plot/navsys", SYS_ALL).toInt();
AnimCycle = settings.value("plot/animcycle", 10).toInt();
RefCycle = settings.value("plot/refcycle", 100).toInt();
HideLowSat = settings.value("plot/hidelowsat", 0).toInt();
ElMaskP = settings.value("plot/elmaskp", 0).toInt();
ExSats = settings.value("plot/exsats", "").toString();
RtBuffSize = settings.value("plot/rtbuffsize", 10800).toInt();
TimeSyncOut = settings.value("plot/timesyncout", 0).toInt();
TimeSyncPort = settings.value("plot/timesyncport", 10071).toInt();
RtStream[0] = settings.value("plot/rtstream1", 0).toInt();
RtStream[1] = settings.value("plot/rtstream2", 0).toInt();
RtFormat[0] = settings.value("plot/rtformat1", 0).toInt();
RtFormat[1] = settings.value("plot/rtformat2", 0).toInt();
RtTimeForm = settings.value("plot/rttimeform", 0).toInt();
RtDegForm = settings.value("plot/rtdegform", 0).toInt();
RtFieldSep = settings.value("plot/rtfieldsep", "").toString();
RtTimeOutTime = settings.value("plot/rttimeouttime", 0).toInt();
RtReConnTime = settings.value("plot/rtreconntime", 10000).toInt();
MColor[0][0] = settings.value("plot/mcolor0", QColor(0xc0, 0xc0, 0xc0)).value<QColor>();
MColor[0][1] = settings.value("plot/mcolor1", QColor(Qt::green)).value<QColor>();
MColor[0][2] = settings.value("plot/mcolor2", QColor(0x00, 0xAA, 0xFF)).value<QColor>();
MColor[0][3] = settings.value("plot/mcolor3", QColor(0xff, 0x00, 0xff)).value<QColor>();
MColor[0][4] = settings.value("plot/mcolor4", QColor(Qt::blue)).value<QColor>();
MColor[0][5] = settings.value("plot/mcolor5", QColor(Qt::red)).value<QColor>();
MColor[0][6] = settings.value("plot/mcolor6", QColor(0x80, 0x80, 0x00)).value<QColor>();
MColor[0][7] = settings.value("plot/mcolor7", QColor(Qt::gray)).value<QColor>();
MColor[1][0] = settings.value("plot/mcolor8", QColor(0xc0, 0xc0, 0xc0)).value<QColor>();
MColor[1][1] = settings.value("plot/mcolor9", QColor(0x80, 0x40, 0x00)).value<QColor>();
MColor[1][2] = settings.value("plot/mcolor10", QColor(0x00, 0x80, 0x80)).value<QColor>();
MColor[1][3] = settings.value("plot/mcolor11", QColor(0xFF, 0x00, 0x80)).value<QColor>();
MColor[1][4] = settings.value("plot/mcolor12", QColor(0xFF, 0x80, 0x00)).value<QColor>();
MColor[1][5] = settings.value("plot/mcolor13", QColor(0x80, 0x80, 0xFF)).value<QColor>();
MColor[1][6] = settings.value("plot/mcolor14", QColor(0xFF, 0x80, 0x80)).value<QColor>();
MColor[1][7] = settings.value("plot/mcolor15", QColor(Qt::gray)).value<QColor>();
MapColor[0] = settings.value("plot/mapcolor1", QColor(0xc0, 0xc0, 0xc0)).value<QColor>();
MapColor[1] = settings.value("plot/mapcolor2", QColor(0xc0, 0xc0, 0xc0)).value<QColor>();
MapColor[2] = settings.value("plot/mapcolor3", QColor(0xf0, 0xd0, 0xd0)).value<QColor>();
MapColor[3] = settings.value("plot/mapcolor4", QColor(0xd0, 0xf0, 0xd0)).value<QColor>();
MapColor[4] = settings.value("plot/mapcolor5", QColor(0xd0, 0xd0, 0xf0)).value<QColor>();
MapColor[5] = settings.value("plot/mapcolor6", QColor(0xd0, 0xf0, 0xf0)).value<QColor>();
MapColor[6] = settings.value("plot/mapcolor7", QColor(0xf8, 0xf8, 0xd0)).value<QColor>();
MapColor[7] = settings.value("plot/mapcolor8", QColor(0xf0, 0xf0, 0xf0)).value<QColor>();
MapColor[8] = settings.value("plot/mapcolor9", QColor(0xf0, 0xf0, 0xf0)).value<QColor>();
MapColor[9] = settings.value("plot/mapcolor10", QColor(0xf0, 0xf0, 0xf0)).value<QColor>();
MapColor[10] = settings.value("plot/mapcolor11", QColor(Qt::white)).value<QColor>();
MapColor[11] = settings.value("plot/mapcolor12", QColor(Qt::white)).value<QColor>();
MapColorF[0] = settings.value("plot/mapcolorf1", QColor(Qt::white)).value<QColor>();
MapColorF[1] = settings.value("plot/mapcolorf2", QColor(Qt::white)).value<QColor>();
MapColorF[2] = settings.value("plot/mapcolorf3", QColor(Qt::white)).value<QColor>();
MapColorF[3] = settings.value("plot/mapcolorf4", QColor(Qt::white)).value<QColor>();
MapColorF[4] = settings.value("plot/mapcolorf5", QColor(Qt::white)).value<QColor>();
MapColorF[5] = settings.value("plot/mapcolorf6", QColor(Qt::white)).value<QColor>();
MapColorF[6] = settings.value("plot/mapcolorf7", QColor(Qt::white)).value<QColor>();
MapColorF[7] = settings.value("plot/mapcolorf8", QColor(Qt::white)).value<QColor>();
MapColorF[8] = settings.value("plot/mapcolorf9", QColor(Qt::white)).value<QColor>();
MapColorF[9] = settings.value("plot/mapcolorf10", QColor(Qt::white)).value<QColor>();
MapColorF[10] = settings.value("plot/mapcolorf11", QColor(Qt::white)).value<QColor>();
MapColorF[11] = settings.value("plot/mapcolorf12", QColor(Qt::white)).value<QColor>();
CColor[0] = settings.value("plot/color1", QColor(Qt::white)).value<QColor>();
CColor[1] = settings.value("plot/color2", QColor(0xc0, 0xc0, 0xc0)).value<QColor>();
CColor[2] = settings.value("plot/color3", QColor(Qt::black)).value<QColor>();
CColor[3] = settings.value("plot/color4", QColor(0xc0, 0xc0, 0xc0)).value<QColor>();
plotOptDialog->refDialog->StaPosFile = settings.value("plot/staposfile", "").toString();
ElMask = settings.value("plot/elmask", 0.0).toDouble();
MaxDop = settings.value("plot/maxdop", 30.0).toDouble();
MaxMP = settings.value("plot/maxmp", 10.0).toDouble();
YRange = settings.value("plot/yrange", 5.0).toDouble();
Origin = settings.value("plot/orgin", 2).toInt();
RcvPos = settings.value("plot/rcvpos", 0).toInt();
OOPos[0] = settings.value("plot/oopos1", 0).toDouble();
OOPos[1] = settings.value("plot/oopos2", 0).toDouble();
OOPos[2] = settings.value("plot/oopos3", 0).toDouble();
ShapeFile = settings.value("plot/shapefile", "").toString();
TLEFile = settings.value("plot/tlefile", "").toString();
TLESatFile = settings.value("plot/tlesatfile", "").toString();
FontName = settings.value("plot/fontname","Tahoma").toString();
FontSize = settings.value("plot/fontsize",8).toInt();
Font.setFamily(FontName);
Font.setPointSize(FontSize);
RnxOpts = settings.value("plot/rnxopts", "").toString();
MapApi = settings.value("mapview/mapapi" , 0).toInt();
ApiKey = settings.value("mapview/apikey" ,"").toString();
MapStrs[0][0] = settings.value("mapview/mapstrs_0_0","OpenStreetMap").toString();
MapStrs[0][1] = settings.value("mapview/mapstrs_0_1","https://tile.openstreetmap.org/{z}/{x}/{y}.png").toString();
MapStrs[0][2] = settings.value("mapview/mapstrs_0_2","https://osm.org/copyright").toString();
for (int i=1;i<6;i++) for (int j=0;j<3;j++) {
MapStrs[i][j] = settings.value(QString("mapview/mapstrs_%1_%2").arg(i).arg(j),"").toString();
}
for (int i=0;i<2;i++) {
StrCmds [0][i] = settings.value(QString("str/strcmd1_%1").arg(i), "").toString();
StrCmds [1][i] = settings.value(QString("str/strcmd2_%1").arg(i), "").toString();
StrCmdEna[0][i] = settings.value(QString("str/strcmdena1_%1").arg(i), 0).toInt();
StrCmdEna[1][i] = settings.value(QString("str/strcmdena2_%1").arg(i), 0).toInt();
}
for (int i = 0; i < 3; i++) {
StrPaths[0][i] = settings.value(QString("str/strpath1_%1").arg(i), "").toString();
StrPaths[1][i] = settings.value(QString("str/strpath2_%1").arg(i), "").toString();
}
for (int i = 0; i < 10; i++) {
StrHistory [i] = settings.value(QString("str/strhistry_%1").arg(i), "").toString();
}
TextViewer::Color1 = settings.value("viewer/color1", QColor(Qt::black)).value<QColor>();
TextViewer::Color2 = settings.value("viewer/color2", QColor(Qt::white)).value<QColor>();
TextViewer::FontD.setFamily(settings.value("viewer/fontname", "Consolas").toString());
TextViewer::FontD.setPointSize(settings.value("viewer/fontsize", 9).toInt());
MenuBrowse->setChecked(settings.value("solbrows/show", 0).toBool());
BrowseSplitter->restoreState(settings.value("solbrows/split1", 100).toByteArray());
Dir =settings.value("solbrows/dir", "C:\\").toString();
for (int i = 0; i < RangeList->count(); i++) {
QString s=RangeList->item(i)->text();
double range;
QString unit;
bool ok;
QStringList tokens = s.split(' ');
if (tokens.size()==2) {
range = tokens.at(0).toInt(&ok);
unit = tokens.at(1);
if (ok) {
if (unit == "cm") range*=0.01;
else if (unit == "km") range*=1000.0;
if (range==YRange) {
RangeList->item(i)->setSelected(true);
break;
}
}
}
}
}
// save options to ini-file -------------------------------------------------
void Plot::SaveOpt(void)
{
QSettings settings(IniFile, QSettings::IniFormat);
trace(3, "SaveOpt\n");
//settings.setValue("plot/plottype", PlotType);
settings.setValue("plot/timelabel", TimeLabel);
settings.setValue("plot/latlonfmt", LatLonFmt);
settings.setValue("plot/autoscale", AutoScale);
settings.setValue("plot/showstats", ShowStats);
settings.setValue("plot/showlabel", ShowLabel);
settings.setValue("plot/showglabel", ShowGLabel);
settings.setValue("plot/showcompass", ShowCompass);
settings.setValue("plot/showscale", ShowScale);
settings.setValue("plot/showarrow", ShowArrow);
settings.setValue("plot/showslip", ShowSlip);
settings.setValue("plot/showhalfc", ShowHalfC);
settings.setValue("plot/showerr", ShowErr);
settings.setValue("plot/showeph", ShowEph);
settings.setValue("plot/plotstyle", PlotStyle);
settings.setValue("plot/marksize", MarkSize);
settings.setValue("plot/navsys", NavSys);
settings.setValue("plot/animcycle", AnimCycle);
settings.setValue("plot/refcycle", RefCycle);
settings.setValue("plot/hidelowsat", HideLowSat);
settings.setValue("plot/elmaskp", ElMaskP);
settings.setValue("plot/exsats", ExSats);
settings.setValue("plot/rtbuffsize", RtBuffSize);
settings.setValue("plot/timesyncout", TimeSyncOut);
settings.setValue("plot/timesyncport", TimeSyncPort);
settings.setValue("plot/rtstream1", RtStream[0]);
settings.setValue("plot/rtstream2", RtStream[1]);
settings.setValue("plot/rtformat1", RtFormat[0]);
settings.setValue("plot/rtformat2", RtFormat[1]);
settings.setValue("plot/rttimeform", RtTimeForm);
settings.setValue("plot/rtdegform", RtDegForm);
settings.setValue("plot/rtfieldsep", RtFieldSep);
settings.setValue("plot/rttimeouttime", RtTimeOutTime);
settings.setValue("plot/rtreconntime", RtReConnTime);
settings.setValue("plot/mcolor0", MColor[0][0]);
settings.setValue("plot/mcolor1", MColor[0][1]);
settings.setValue("plot/mcolor2", MColor[0][2]);
settings.setValue("plot/mcolor3", MColor[0][3]);
settings.setValue("plot/mcolor4", MColor[0][4]);
settings.setValue("plot/mcolor5", MColor[0][5]);
settings.setValue("plot/mcolor6", MColor[0][6]);
settings.setValue("plot/mcolor7", MColor[0][7]);
settings.setValue("plot/mcolor8", MColor[0][0]);
settings.setValue("plot/mcolor9", MColor[1][1]);
settings.setValue("plot/mcolor10", MColor[1][2]);
settings.setValue("plot/mcolor11", MColor[1][3]);
settings.setValue("plot/mcolor12", MColor[1][4]);
settings.setValue("plot/mcolor13", MColor[1][5]);
settings.setValue("plot/mcolor14", MColor[1][6]);
settings.setValue("plot/mcolor15", MColor[1][7]);
settings.setValue("plot/mapcolor1", MapColor[0]);
settings.setValue("plot/mapcolor2", MapColor[1]);
settings.setValue("plot/mapcolor3", MapColor[2]);
settings.setValue("plot/mapcolor4", MapColor[3]);
settings.setValue("plot/mapcolor5", MapColor[4]);
settings.setValue("plot/mapcolor6", MapColor[5]);
settings.setValue("plot/mapcolor7", MapColor[6]);
settings.setValue("plot/mapcolor8", MapColor[7]);
settings.setValue("plot/mapcolor9", MapColor[8]);
settings.setValue("plot/mapcolor10", MapColor[9]);
settings.setValue("plot/mapcolor11", MapColor[10]);
settings.setValue("plot/mapcolor12", MapColor[11]);
settings.setValue("plot/mapcolorf1", MapColorF[0]);
settings.setValue("plot/mapcolorf2", MapColorF[1]);
settings.setValue("plot/mapcolorf3", MapColorF[2]);
settings.setValue("plot/mapcolorf4", MapColorF[3]);
settings.setValue("plot/mapcolorf5", MapColorF[4]);
settings.setValue("plot/mapcolorf6", MapColorF[5]);
settings.setValue("plot/mapcolorf7", MapColorF[6]);
settings.setValue("plot/mapcolorf8", MapColorF[7]);
settings.setValue("plot/mapcolorf9", MapColorF[8]);
settings.setValue("plot/mapcolorf10", MapColorF[9]);
settings.setValue("plot/mapcolorf11", MapColorF[10]);
settings.setValue("plot/mapcolorf12", MapColorF[11]);
settings.setValue("plot/color1", CColor[0]);
settings.setValue("plot/color2", CColor[1]);
settings.setValue("plot/color3", CColor[2]);
settings.setValue("plot/color4", CColor[3]);
settings.setValue("plot/staposfile", plotOptDialog->refDialog->StaPosFile);
settings.setValue("plot/elmask", ElMask);
settings.setValue("plot/maxdop", MaxDop);
settings.setValue("plot/maxmp", MaxMP);
settings.setValue("plot/yrange", YRange);
settings.setValue("plot/orgin", Origin);
settings.setValue("plot/rcvpos", RcvPos);
settings.setValue("plot/oopos1", OOPos[0]);
settings.setValue("plot/oopos2", OOPos[1]);
settings.setValue("plot/oopos3", OOPos[2]);
settings.setValue("plot/shapefile", ShapeFile);
settings.setValue("plot/tlefile", TLEFile);
settings.setValue("plot/tlesatfile", TLESatFile);
settings.setValue("plot/fontname", Font.family());
settings.setValue("plot/fontsize", Font.pointSize());
settings.setValue("plot/rnxopts", RnxOpts);
settings.setValue("mapview/apikey", ApiKey);
settings.setValue("mapview/mapapi", MapApi);
for (int i=0;i<6;i++) for (int j=0;j<3;j++) {
settings.setValue(QString("mapview/mapstrs_%1_%2").arg(i).arg(j),MapStrs[i][j]);
}
for (int i = 0; i < 2; i++) {
settings.setValue(QString("str/strcmd1_%1").arg(i), StrCmds [0][i]);
settings.setValue(QString("str/strcmd2_%1").arg(i), StrCmds [1][i]);
settings.setValue(QString("str/strcmdena1_%1").arg(i), StrCmdEna[0][i]);
settings.setValue(QString("str/strcmdena2_%1").arg(i), StrCmdEna[1][i]);
}
for (int i = 0; i < 3; i++) {
settings.setValue(QString("str/strpath1_%1").arg(i), StrPaths[0][i]);
settings.setValue(QString("str/strpath2_%1").arg(i), StrPaths[1][i]);
}
for (int i = 0; i < 10; i++) {
settings.setValue(QString("str/strhistry_%1").arg(i), StrHistory [i]);
}
settings.setValue("viewer/color1", TextViewer::Color1);
settings.setValue("viewer/color2", TextViewer::Color2);
settings.setValue("viewer/fontname", TextViewer::FontD.family());
settings.setValue("viewer/fontsize", TextViewer::FontD.pointSize());
settings.setValue("solbrows/dir", fileSelDialog->Dir);
settings.setValue("solbrows/split1", BrowseSplitter->saveState());
}
//---------------------------------------------------------------------------
void Plot::DriveSelChanged()
{
DirSelector->setVisible(false);
DirSelector->setRootIndex(dirModel->index(DriveSel->currentText()));
DirSelected->setText(DriveSel->currentText());
}
//---------------------------------------------------------------------------
void Plot::BtnDirSelClick()
{
#ifdef FLOATING_DIRSELECTOR
QPoint pos = Panel5->mapToGlobal(BtnDirSel->pos());
pos.rx() += BtnDirSel->width() - DirSelector->width();
pos.ry() += BtnDirSel->height();
DirSelector->move(pos);
#endif
DirSelector->setVisible(!DirSelector->isVisible());
}
//---------------------------------------------------------------------------
void Plot::DirSelChange(QModelIndex index)
{
DirSelector->expand(index);
Dir = dirModel->filePath(index);
DirSelected->setText(Dir);
fileModel->setRootPath(Dir);
FileList->setRootIndex(fileModel->index(Dir));
}
//---------------------------------------------------------------------------
void Plot::DirSelSelected(QModelIndex)
{
DirSelector->setVisible(false);
}
//---------------------------------------------------------------------------
void Plot::FileListClick(QModelIndex index)
{
QStringList file;
file.append(fileModel->filePath(index));
plot->ReadSol(file, 0);
DirSelector->setVisible(false);
}
//---------------------------------------------------------------------------
void Plot::FilterClick()
{
QString filter = Filter->currentText();
// only keep data between brackets
filter = filter.mid(filter.indexOf("(") + 1);
filter.remove(")");
fileModel->setNameFilters(filter.split(" "));
DirSelector->setVisible(false);
}
//---------------------------------------------------------------------------
void Plot::BtnFreqClick()
{
freqDialog->exec();
}
//---------------------------------------------------------------------------
| 35.485975 | 190 | 0.554044 | [
"shape"
] |
4d46bfd49a3c3aa01912ffa9af9ee2045570ca08 | 6,031 | cpp | C++ | rs/test/filter_test.cpp | dymk/rs | b75ab0df5f235ac12ec4da825e6bd6e1fa9e7493 | [
"Apache-2.0"
] | 19 | 2017-05-15T08:20:00.000Z | 2021-12-03T05:58:32.000Z | rs/test/filter_test.cpp | dymk/rs | b75ab0df5f235ac12ec4da825e6bd6e1fa9e7493 | [
"Apache-2.0"
] | null | null | null | rs/test/filter_test.cpp | dymk/rs | b75ab0df5f235ac12ec4da825e6bd6e1fa9e7493 | [
"Apache-2.0"
] | 3 | 2018-01-16T18:07:30.000Z | 2021-06-30T07:33:44.000Z | // Copyright 2017 Per Grön. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <catch.hpp>
#include <string>
#include <vector>
#include <rs/just.h>
#include <rs/filter.h>
#include <rs/never.h>
#include "infinite_range.h"
#include "test_util.h"
namespace shk {
TEST_CASE("Filter") {
auto divisible_by_3 = Filter([](int x) { return (x % 3) == 0; });
SECTION("empty") {
SECTION("subscriber is kept") {
auto stream = divisible_by_3(Just());
CHECK(GetAll<int>(stream) == (std::vector<int>{}));
static_assert(
IsPublisher<decltype(stream)>,
"Filter stream should be a publisher");
}
SECTION("subscriber is discarded") {
auto stream = divisible_by_3(Never());
CHECK(
GetAll<int>(stream, ElementCount::Unbounded(), false) ==
(std::vector<int>{}));
}
}
SECTION("one int") {
SECTION("pass-through") {
CHECK(
GetAll<int>(divisible_by_3(Just(3))) ==
(std::vector<int>{ 3 }));
}
SECTION("filtered") {
CHECK(
GetAll<int>(divisible_by_3(Just(4))) ==
(std::vector<int>{ }));
}
}
SECTION("two ints") {
SECTION("both pass-through") {
CHECK(
GetAll<int>(divisible_by_3(Just(3, 9))) ==
(std::vector<int>{ 3, 9 }));
}
SECTION("one filtered") {
CHECK(
GetAll<int>(divisible_by_3(Just(4, 9))) ==
(std::vector<int>{ 9 }));
}
SECTION("both filtered") {
CHECK(
GetAll<int>(divisible_by_3(Just(1, 5))) ==
(std::vector<int>{}));
}
}
SECTION("different types") {
auto is_nonzero = Filter([](auto &&x) { return x != 0; });
int a;
CHECK(
GetAll<int *>(is_nonzero(Just(&a, nullptr))) ==
(std::vector<int *>{ &a }));
CHECK(
GetAll<bool>(is_nonzero(Just(true, false))) ==
(std::vector<bool>{ true }));
}
SECTION("request only one") {
SECTION("first is matching") {
CHECK(
GetAll<int>(
divisible_by_3(Just(3, 9)),
ElementCount(1),
false) ==
(std::vector<int>{ 3 }));
}
SECTION("first is not matching") {
CHECK(
GetAll<int>(
divisible_by_3(Just(4, 9)),
ElementCount(1),
true) ==
(std::vector<int>{ 9 }));
}
}
SECTION("request only two") {
SECTION("both matching") {
CHECK(
GetAll<int>(
divisible_by_3(Just(0, 12)),
ElementCount(2)) ==
(std::vector<int>{ 0, 12 }));
}
SECTION("only one matching") {
CHECK(
GetAll<int>(
divisible_by_3(Just(1, 12)),
ElementCount(2)) ==
(std::vector<int>{ 12 }));
}
}
SECTION("don't leak the subscriber") {
CheckLeak(divisible_by_3(Just(3)));
}
SECTION("cancel") {
auto null_subscriber = MakeSubscriber(
[](int next) { CHECK(!"should not happen"); },
[](std::exception_ptr &&error) { CHECK(!"should not happen"); },
[] { CHECK(!"should not happen"); });
auto sub = divisible_by_3(InfiniteRange(0))
.Subscribe(std::move(null_subscriber));
sub.Cancel();
// Because the subscription is cancelled, it should not request values
// from the infinite range (which would never terminate).
sub.Request(ElementCount::Unbounded());
}
SECTION("exceptions") {
auto fail_on = [](int error_val) {
return Filter([error_val](int x) {
if (x == error_val) {
throw std::runtime_error("fail_on");
} else {
return (x % 3) == 0;
}
});
};
SECTION("empty") {
CHECK(
GetAll<int>(fail_on(0)(Just())) ==
(std::vector<int>{}));
}
SECTION("error on first") {
auto error = GetError(fail_on(0)(Just(0)));
CHECK(GetErrorWhat(error) == "fail_on");
}
SECTION("error on second") {
SECTION("first filtered out") {
auto error = GetError(fail_on(0)(Just(1, 0)));
CHECK(GetErrorWhat(error) == "fail_on");
}
SECTION("first not filtered out") {
auto error = GetError(fail_on(0)(Just(3, 0)));
CHECK(GetErrorWhat(error) == "fail_on");
}
}
SECTION("error on first and second") {
auto error = GetError(fail_on(0)(Just(0, 0)));
CHECK(GetErrorWhat(error) == "fail_on");
}
SECTION("source emits value that fails and then fails itself") {
auto zero_then_fail = fail_on(1)(Just(0, 1));
// Should only fail once. GetError checks that
auto error = GetError(fail_on(0)(zero_then_fail));
CHECK(GetErrorWhat(error) == "fail_on");
}
SECTION("error on second only one requested") {
SECTION("first filtered out") {
auto error = GetError(
fail_on(0)(Just(1, 0)),
ElementCount(1));
CHECK(GetErrorWhat(error) == "fail_on");
}
SECTION("first not filtered out") {
CHECK(
GetAll<int>(
fail_on(0)(Just(3, 0)),
ElementCount(1),
false) ==
(std::vector<int>{ 3 }));
}
}
SECTION("error on first of infinite") {
// This will terminate only if the Filter operator actually cancels the
// underlying InfiniteRange stream.
auto error = GetError(fail_on(0)(InfiniteRange(0)));
CHECK(GetErrorWhat(error) == "fail_on");
}
}
}
} // namespace shk
| 26.568282 | 77 | 0.553142 | [
"vector"
] |
4d4faa6c457cf7762e169c634ec5d79b80d8728f | 17,788 | cpp | C++ | test/test_general.cpp | gershnik/sys_string | 2086bea8b0d4577d512ff99782e1d57fd41504da | [
"BSD-3-Clause"
] | null | null | null | test/test_general.cpp | gershnik/sys_string | 2086bea8b0d4577d512ff99782e1d57fd41504da | [
"BSD-3-Clause"
] | null | null | null | test/test_general.cpp | gershnik/sys_string | 2086bea8b0d4577d512ff99782e1d57fd41504da | [
"BSD-3-Clause"
] | null | null | null | //
// Copyright 2020 Eugene Gershnik
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://github.com/gershnik/sys_string/blob/master/LICENSE
//
#include <sys_string/sys_string.h>
#include <sstream>
#include "catch.hpp"
using namespace sysstr;
static_assert(std::is_nothrow_default_constructible_v<sys_string>);
static_assert(std::is_nothrow_copy_constructible_v<sys_string>);
static_assert(std::is_nothrow_move_constructible_v<sys_string>);
static_assert(std::is_nothrow_copy_assignable_v<sys_string>);
static_assert(std::is_nothrow_move_assignable_v<sys_string>);
static_assert(std::is_nothrow_destructible_v<sys_string>);
static_assert(std::is_nothrow_swappable_v<sys_string>);
static_assert(std::is_standard_layout_v<sys_string>);
#if SYS_STRING_USE_SPACESHIP_OPERATOR
template<class T>
bool is_eq(T val)
{ return std::is_eq(val); }
template<class T>
bool is_lt(T val)
{ return std::is_lt(val); }
#else
template<class T>
bool is_eq(T val)
{ return val == 0; }
template<class T>
bool is_lt(T val)
{ return val < 0; }
#endif
template<class CharT> const CharT * select([[maybe_unused]] const char * s8,
[[maybe_unused]] const char16_t * s16,
[[maybe_unused]] const char32_t * s32)
{
if constexpr (std::is_same_v<CharT, char32_t>)
return s32;
else if constexpr (std::is_same_v<CharT, char16_t>)
return s16;
else
return s8;
}
TEST_CASE( "Creation", "[general]") {
sys_string from_char("abc", 3);
CHECK(from_char == S("abc"));
sys_string from_utf16(u"abc", 3);
CHECK(from_utf16 == S("abc"));
sys_string from_utf32(U"abc", 3);
CHECK(from_utf32 == S("abc"));
CHECK(sys_string(S("abc")) == S("abc"));
sys_string temp = S("abc");
sys_string new_temp(std::move(temp));
CHECK(new_temp == S("abc"));
}
TEST_CASE( "Iteration", "[general]" ) {
sys_string str = S("a水𐀀𝄞");
sys_string empty = S("");
SECTION("utf8") {
std::string converted;
for (char c: sys_string::utf8_view(str))
{
converted.push_back(c);
}
std::string expected = "a水𐀀𝄞";
CHECK(converted == expected);
converted.clear();
sys_string::utf8_view view(str);
std::copy(view.rbegin(), view.rend(), std::back_inserter(converted));
CHECK(converted == std::string{expected.rbegin(), expected.rend()});
converted.clear();
for (char c: sys_string::utf8_view(empty))
{
converted.push_back(c);
}
CHECK(converted.empty());
}
SECTION("utf16") {
std::u16string converted;
for (char16_t c: sys_string::utf16_view(str))
{
converted.push_back(c);
}
std::u16string expected = u"a水𐀀𝄞";
CHECK(converted == expected);
converted.clear();
sys_string::utf16_view view(str);
std::copy(view.rbegin(), view.rend(), std::back_inserter(converted));
CHECK(converted == std::u16string{expected.rbegin(), expected.rend()});
converted.clear();
for (char16_t c: sys_string::utf16_view(empty))
{
converted.push_back(c);
}
CHECK(converted.empty());
}
SECTION("utf32") {
std::u32string converted;
for (char32_t c: sys_string::utf32_view(str))
{
converted.push_back(c);
}
std::u32string expected = U"a水𐀀𝄞";
CHECK(converted == expected);
converted.clear();
sys_string::utf32_view view(str);
std::copy(view.rbegin(), view.rend(), std::back_inserter(converted));
CHECK(converted == std::u32string{expected.rbegin(), expected.rend()});
converted.clear();
for (char32_t c: sys_string::utf16_view(empty))
{
converted.push_back(c);
}
CHECK(converted.empty());
sys_string part(++(++view.begin()), view.end());
CHECK(part == S("𐀀𝄞"));
}
SECTION("storage") {
std::basic_string<sys_string::storage_type> converted;
for (sys_string::storage_type c: sys_string::char_access(str))
{
converted.push_back(c);
}
std::basic_string<sys_string::storage_type> expected = select<sys_string::storage_type>("a水𐀀𝄞", u"a水𐀀𝄞", U"a水𐀀𝄞");
CHECK(converted == expected);
converted.clear();
sys_string::char_access access(str);
std::copy(access.rbegin(), access.rend(), std::back_inserter(converted));
CHECK(converted == std::basic_string<sys_string::storage_type>{expected.rbegin(), expected.rend()});
converted.clear();
for (sys_string::storage_type c: sys_string::char_access(empty))
{
converted.push_back(c);
}
CHECK(converted.empty());
sys_string part(access.begin() + 1, access.end());
CHECK(part == S("水𐀀𝄞"));
}
}
TEST_CASE( "Comparsion", "[general]" ) {
CHECK(sys_string() == sys_string());
CHECK(sys_string() == S(""));
CHECK(S("") == S(""));
CHECK(is_eq(compare_no_case(sys_string(), sys_string())));
CHECK(is_eq(compare_no_case(sys_string(), S(""))));
CHECK(is_eq(compare_no_case(S(""), S(""))));
sys_string base = S("азбука");
sys_string greater = S("алфавит");
sys_string ucase = S("аЗбука");
CHECK(base < greater);
CHECK(base <= greater);
CHECK(base <= base);
CHECK(greater > base);
CHECK(greater >= base);
CHECK(greater >= greater);
CHECK(base == base);
CHECK(base != greater);
CHECK(is_eq(compare_no_case(base, ucase)));
CHECK(is_eq(compare_no_case(S("maße"), S("MASSE"))));
CHECK(is_eq(compare_no_case(S("ßßßßßßßßßßßßßßßßßßßß"), S("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"))));
CHECK(is_lt(compare_no_case(S("SS"), S("ßßßßßß"))));
CHECK(is_lt(compare_no_case(S("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"), S("ßßßßßßßßßßßßßßßßß"))));
CHECK(is_lt(compare_no_case(S("maße"), S("MASSF"))));
sys_string bad(u"a\xD800", 2);
CHECK(is_lt(compare_no_case(S("ab"), bad)));
}
TEST_CASE( "Case conversion", "[general]" ) {
CHECK(S("maße").to_upper() == S("MASSE"));
CHECK(S("MAẞE").to_lower() == S("maße"));
CHECK(S("ΒΟΥΣ").to_lower() == S("βους"));
CHECK(S("ΒΟΥΣ AA").to_lower() == S("βους aa"));
CHECK(S("ΒΟΥΣAA").to_lower() == S("βουσaa"));
CHECK(S("ͺΣ").to_lower() == S("ͺσ"));
CHECK(S("ΑͺΣ").to_lower() == S("αͺς"));
CHECK(S("ΑΣͺ").to_lower() == S("αςͺ"));
CHECK(S("ΑΣͺΑ").to_lower() == S("ασͺα"));
CHECK(S("βους").to_upper() == S("ΒΟΥΣ"));
}
TEST_CASE( "Trim", "[general]" ) {
CHECK(S("").trim() == S(""));
CHECK(S(" \t\n ").trim() == S(""));
CHECK(S(" a").trim() == S("a"));
CHECK(S("a ").trim() == S("a"));
CHECK(S(" a ").trim() == S("a"));
CHECK(S(" a b ").trim() == S("a b"));
CHECK(S(" ' a b ").trim() == S("' a b"));
CHECK(S("").ltrim() == S(""));
CHECK(S(" \t\n ").ltrim() == S(""));
CHECK(S(" a").ltrim() == S("a"));
CHECK(S("a ").ltrim() == S("a "));
CHECK(S(" a ").ltrim() == S("a "));
CHECK(S(" a b ").ltrim() == S("a b "));
CHECK(S(" ' a b ").ltrim() == S("' a b "));
CHECK(S("").rtrim() == S(""));
CHECK(S(" \t\n ").rtrim() == S(""));
CHECK(S(" a").rtrim() == S(" a"));
CHECK(S("a ").rtrim() == S("a"));
CHECK(S(" a ").rtrim() == S(" a"));
CHECK(S(" a b ").rtrim() == S(" a b"));
CHECK(S(" a b ' ").rtrim() == S(" a b '"));
}
namespace
{
struct
{
template<class Sep>
auto operator()(const sys_string & str, Sep sep) {
std::vector<sys_string> ret;
str.split(std::back_inserter(ret), sep);
return ret;
}
template<class Sep>
auto operator()(const sys_string & str, Sep sep, size_t max_split) {
std::vector<sys_string> ret;
str.split(std::back_inserter(ret), sep, max_split);
return ret;
}
} splitter;
}
TEST_CASE( "Split", "[general]" ) {
CHECK(splitter(S(""), U'q') == std::vector({S("")}));
CHECK(splitter(S("q"), U'q') == std::vector({S(""), S("")}));
CHECK(splitter(S("qa"), U'q') == std::vector({S(""), S("a")}));
CHECK(splitter(S("aq"), U'q') == std::vector({S("a"), S("")}));
CHECK(splitter(S("q"), U'q', 0) == std::vector({S("q")}));
CHECK(splitter(S("q"), U'q', 1) == std::vector({S(""), S("")}));
CHECK(splitter(S("q"), U'q', 2) == std::vector({S(""), S("")}));
CHECK(splitter(S("q"), U'q', 3) == std::vector({S(""), S("")}));
CHECK(splitter(S("qq"), U'q', 1) == std::vector({S(""), S("q")}));
CHECK(splitter(S("a;b;c"), U';', 0) == std::vector({S("a;b;c")}));
CHECK(splitter(S("a;b;c"), U';', 1) == std::vector({S("a"), S("b;c")}));
CHECK(splitter(S("a;b;c"), U';', 2) == std::vector({S("a"), S("b"), S("c")}));
CHECK(splitter(S(""), S("q")) == std::vector({S("")}));
CHECK(splitter(S("q"), S("q")) == std::vector({S(""), S("")}));
CHECK(splitter(S("qa"), S("q")) == std::vector({S(""), S("a")}));
CHECK(splitter(S("aq"), S("q")) == std::vector({S("a"), S("")}));
CHECK(splitter(S("q"), S("q"), 0) == std::vector({S("q")}));
CHECK(splitter(S("q"), S("q"), 1) == std::vector({S(""), S("")}));
CHECK(splitter(S("q"), S("q"), 2) == std::vector({S(""), S("")}));
CHECK(splitter(S("q"), S("q"), 3) == std::vector({S(""), S("")}));
CHECK(splitter(S("qq"), S("q"), 1) == std::vector({S(""), S("q")}));
CHECK(splitter(S("a;b;c"), S(";"), 0) == std::vector({S("a;b;c")}));
CHECK(splitter(S("a;b;c"), S(";"), 1) == std::vector({S("a"), S("b;c")}));
CHECK(splitter(S("a;b;c"), S(";"), 2) == std::vector({S("a"), S("b"), S("c")}));
CHECK(splitter(S(""), S("")) == std::vector({S("")}));
CHECK(splitter(S("a"), S("")) == std::vector({S("a")}));
CHECK(splitter(S("ab"), S("")) == std::vector({S("ab")}));
auto searcher = [] (sys_string::utf32_view::iterator str_start, sys_string::utf32_view::iterator str_end) noexcept {
constexpr char32_t seps[] = U"xyz";
auto found_it = std::find_first_of(str_start, str_end, std::begin(seps), std::end(seps));
if (found_it == str_end)
return std::pair(str_end, str_end);
auto found_end = found_it;
++found_end;
return std::pair(found_it, found_end);
};
CHECK(splitter(S(""), searcher) == std::vector({S("")}));
CHECK(splitter(S("x"), searcher) == std::vector({S(""), S("")}));
CHECK(splitter(S("ya"), searcher) == std::vector({S(""), S("a")}));
CHECK(splitter(S("az"), searcher) == std::vector({S("a"), S("")}));
}
TEST_CASE( "Join", "[general]" ) {
std::vector<sys_string> empty;
std::vector<sys_string> one = {S("Q")};
std::vector<sys_string> two = {S("Q"), S("R")};
CHECK(S("").join(empty.begin(), empty.end()) == S(""));
CHECK(S("").join(one.begin(), one.end()) == S("Q"));
CHECK(S("").join(two.begin(), two.end()) == S("QR"));
CHECK(S("A").join(empty.begin(), empty.end()) == S(""));
CHECK(S("A").join(one.begin(), one.end()) == S("Q"));
CHECK(S("A").join(two.begin(), two.end()) == S("QAR"));
}
TEST_CASE( "Prefix", "[general]" ) {
CHECK(S("").starts_with(S("")));
CHECK(!S("").starts_with(S("a")));
CHECK(S("a").starts_with(S("")));
CHECK(S("a").starts_with(S("a")));
CHECK(!S("a").starts_with(S("b")));
CHECK(S("ab").starts_with(S("a")));
CHECK(!S("").starts_with(U'a'));
CHECK(S("a").starts_with(U'a'));
CHECK(!S("a").starts_with(U'b'));
CHECK(S("ab").starts_with(U'a'));
CHECK(!S("\uFFFDb").starts_with(char32_t(0x110000)));
std::array prefixes = {S("a"), S("b"), S("c")};
CHECK(S("").find_prefix(prefixes.begin(), prefixes.end()) == prefixes.end());
CHECK(S("cd").find_prefix(prefixes.begin(), prefixes.end()) == prefixes.end() - 1);
CHECK(S("").remove_prefix(S("")) == S(""));
CHECK(S("").remove_prefix(S("a")) == S(""));
CHECK(S("a").remove_prefix(S("")) == S("a"));
CHECK(S("a").remove_prefix(S("a")) == S(""));
CHECK(S("a").remove_prefix(S("b")) == S("a"));
CHECK(S("ab").remove_prefix(S("a")) == S("b"));
CHECK(S("").remove_prefix(U'a') == S(""));
CHECK(S("a").remove_prefix(U'a') == S(""));
CHECK(S("a").remove_prefix(U'b') == S("a"));
CHECK(S("ab").remove_prefix(U'a') == S("b"));
}
TEST_CASE( "Suffix", "[general]" ) {
CHECK(S("").ends_with(S("")));
CHECK(!S("").ends_with(S("a")));
CHECK(S("a").ends_with(S("")));
CHECK(S("a").ends_with(S("a")));
CHECK(!S("a").ends_with(S("b")));
CHECK(S("ab").ends_with(S("b")));
CHECK(!S("").ends_with(U'a'));
CHECK(S("a").ends_with(U'a'));
CHECK(!S("a").ends_with(U'b'));
CHECK(S("ab").ends_with(U'b'));
CHECK(!S("b\uFFFD").ends_with(char32_t(0x110000)));
std::array suffixes = {S("a"), S("b"), S("c")};
CHECK(S("").find_suffix(suffixes.begin(), suffixes.end()) == suffixes.end());
CHECK(S("dc").find_suffix(suffixes.begin(), suffixes.end()) == suffixes.end() - 1);
CHECK(S("").remove_suffix(S("")) == S(""));
CHECK(S("").remove_suffix(S("a")) == S(""));
CHECK(S("a").remove_suffix(S("")) == S("a"));
CHECK(S("a").remove_suffix(S("a")) == S(""));
CHECK(S("a").remove_suffix(S("b")) == S("a"));
CHECK(S("ab").remove_suffix(S("b")) == S("a"));
CHECK(S("").remove_suffix(U'a') == S(""));
CHECK(S("a").remove_suffix(U'a') == S(""));
CHECK(S("a").remove_suffix(U'b') == S("a"));
CHECK(S("ab").remove_suffix(U'b') == S("a"));
}
TEST_CASE( "Contains", "[general]" ) {
CHECK(S("").contains(S("")));
CHECK(!S("").contains(S("a")));
CHECK(S("a").contains(S("")));
CHECK(S("a").contains(S("a")));
CHECK(!S("a").contains(S("b")));
CHECK(S("ab").contains(S("b")));
CHECK(S("abc").contains(S("b")));
CHECK(!S("").contains(U'a'));
CHECK(S("a").contains(U'a'));
CHECK(!S("a").contains(U'b'));
CHECK(S("ab").contains(U'b'));
CHECK(S("aba").contains(U'b'));
CHECK(!S("b\uFFFDc").contains(char32_t(0x110000)));
std::array infixes = {S("a"), S("b"), S("c")};
CHECK(S("").find_contained(infixes.begin(), infixes.end()) == infixes.end());
CHECK(S("dc").find_contained(infixes.begin(), infixes.end()) == infixes.end() - 1);
CHECK(S("dbn").find_contained(infixes.begin(), infixes.end()) == infixes.end() - 2);
}
TEST_CASE( "Replace", "[general]" ) {
CHECK(S("").replace(S(""), S("")) == S(""));
CHECK(S("").replace(S(""), S("a")) == S(""));
CHECK(S("").replace(S("a"), S("")) == S(""));
CHECK(S("😏").replace(S(""), S("")) == S("😏"));
CHECK(S("😏").replace(S(""), S("😫")) == S("😏"));
CHECK(S("😏").replace(S("😫"), S("")) == S("😏"));
CHECK(S("😏").replace(S("😏"), S("")) == S(""));
CHECK(S("😏").replace(S("😏"), S("😫")) == S("😫"));
CHECK(S("🥳😏🥸").replace(S("😏"), S("😫")) == S("🥳😫🥸"));
CHECK(S("🥳😏🥸😏").replace(S("😏"), S("😫")) == S("🥳😫🥸😫"));
CHECK(S("").replace(S(""), U'a') == S(""));
CHECK(S("").replace(U'a', S("")) == S(""));
CHECK(S("😏").replace(S(""), U'😫') == S("😏"));
CHECK(S("😏").replace(U'😫', S("")) == S("😏"));
CHECK(S("😏").replace(U'😏', S("")) == S(""));
CHECK(S("😏").replace(U'😏', U'😫') == S("😫"));
CHECK(S("🥳😏🥸").replace(U'😏', U'😫') == S("🥳😫🥸"));
CHECK(S("🥳😏🥸😏").replace(U'😏', U'😫') == S("🥳😫🥸😫"));
}
TEST_CASE( "Addition", "[general]" ) {
CHECK(S("") + S("") == S(""));
CHECK(S("") + S("🤢") == S("🤢"));
CHECK(S("") + U'🤢' == S("🤢"));
CHECK(S("🤢") + S("") == S("🤢"));
CHECK(U'🤢' + S("") == S("🤢"));
CHECK(S("💜") + S("🧡") == S("💜🧡"));
CHECK(U'💜' + S("🧡") == S("💜🧡"));
CHECK(S("💜") + U'🧡' == S("💜🧡"));
CHECK(S("💾") + S("💿") + S("⏰") == S("💾💿⏰"));
CHECK(S("💾") + U'💿' + S("⏰") == S("💾💿⏰"));
CHECK(S("💾") + (S("💿") + S("⏰")) == S("💾💿⏰"));
CHECK(S("💾") + (U'💿' + S("⏰")) == S("💾💿⏰"));
CHECK((S("💾") + S("💿")) + S("⏰") == S("💾💿⏰"));
CHECK((S("💾") + U'💿') + S("⏰") == S("💾💿⏰"));
CHECK((S("💾") + U'💿') + (U'🜇' + S("⏰")) == S("💾💿🜇⏰"));
CHECK(((U'a' + S("b")) + (S("💾") + U'💿')) + (U'🜇' + S("⏰")) == S("ab💾💿🜇⏰"));
}
TEST_CASE( "c_str", "[general]" ) {
const sys_string & str = S("a🧡bc");
sys_string::char_access access(str);
const char * cstr = access.c_str();
REQUIRE(cstr);
CHECK(strcmp(cstr, "a🧡bc") == 0);
CHECK(access.c_str() == cstr);
}
TEST_CASE( "ostream", "[general]" ) {
{
std::ostringstream stream;
stream << sys_string();
CHECK(stream.str() == "");
}
{
std::ostringstream stream;
stream << S("");
CHECK(stream.str() == "");
}
{
std::ostringstream stream;
stream << S("a🧡bc");
CHECK(stream.str() == "a🧡bc");
}
#if defined(_WIN32) || defined(__STDC_ISO_10646__)
{
std::wostringstream stream;
stream << sys_string();
CHECK(stream.str() == L"");
}
{
std::wostringstream stream;
stream << S("");
CHECK(stream.str() == L"");
}
{
std::wostringstream stream;
stream << S("a🧡bc");
CHECK(stream.str() == L"a🧡bc");
}
#endif
}
| 33.753321 | 122 | 0.49494 | [
"vector"
] |
4d54c2835b012544536606b5f812f40c2d217b72 | 9,061 | cpp | C++ | tests/storageserver/main.cpp | awstanley/cpp-gamefilesystem | fc06cf5f2b4f873846677f45fa5480a69cdd91df | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 1 | 2021-07-12T19:25:29.000Z | 2021-07-12T19:25:29.000Z | tests/storageserver/main.cpp | awstanley/cpp-gamefilesystem | fc06cf5f2b4f873846677f45fa5480a69cdd91df | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 6 | 2017-10-16T19:30:25.000Z | 2018-10-06T23:55:19.000Z | tests/storageserver/main.cpp | awstanley/cpp-gamefilesystem | fc06cf5f2b4f873846677f45fa5480a69cdd91df | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 3 | 2017-10-14T10:21:44.000Z | 2021-07-12T19:25:39.000Z | // This is a test for the StorageServer component.
#include <ReversingSpace/GameFileSystem/StorageServer.hpp>
#include <ReversingSpace/GameFileSystem/PlatformFile.hpp>
#include <cstring> // strcmp for non-VS builders.
#include <fstream>
#include <iostream>
#include <stdexcept>
// Declare this once.
using FileType = reversingspace::gfs::PlatformFile;
int main(int argc, char **argv) {
// Specify userland as the current directory.
const std::filesystem::path userland_root = std::filesystem::current_path() / "userland";
// Notify output.
std::cout << "Using path for userland: '" << userland_root.string().c_str() << "'" << std::endl;
// Build a storage server.
auto storage_server = reversingspace::gfs::StorageServer<FileType>::create(userland_root);
if (storage_server == nullptr) {
std::cout << "Failed to create storage server instance." << std::endl;
throw std::runtime_error("failed to construct storage server");
}
auto userland_dir = storage_server->get_userland();
if (userland_dir == nullptr) {
std::cout << "Userland is nullptr. This shouldn't happen." << std::endl;
throw std::runtime_error("userland is nullptr");
}
{
const std::string test_filename_0 = "userland_file_0.ext";
std::string test_string = "This is a simple test to confirm read/write works for the storage server and platform file type.";
std::uint32_t test_string_length = test_string.length();
const std::uint32_t test_string_length_size = sizeof(decltype(test_string_length));
{
auto test_file_0 = storage_server->get_userland_file(test_filename_0,
reversingspace::storage::FileAccess::ReadWrite);
if (test_file_0 == nullptr) {
std::cout << "test_file_0 is nullptr. This really shouldn't happen." << std::endl;
throw std::runtime_error("test_file_0 is nullptr(rw)");
}
if (test_file_0->write((char*)&test_string_length, test_string_length_size) != test_string_length_size) {
throw std::runtime_error("failed to write test string (length).");
}
if (test_file_0->write(test_string.data(), test_string_length) != test_string_length) {
throw std::runtime_error("failed to write test string (data).");
}
}
// Re-open
{
auto test_file_0 = storage_server->get_userland_file(test_filename_0,
reversingspace::storage::FileAccess::Read);
if (test_file_0 == nullptr) {
std::cout << "test_file_0 is nullptr (on read). This really shouldn't happen." << std::endl;
throw std::runtime_error("test_file_0 is nullptr(r)");
}
test_string_length = 0;
if (test_file_0->read((char*)&test_string_length, test_string_length_size) != test_string_length_size) {
throw std::runtime_error("failed to read test string (length).");
}
// This is not how I'd choose to do it, but it's how you're
// meant to do it (apparently). char* buffers are also supported
// but it's irrelevant as internally they are both just memcpy.
// Pass in an empty vector and it resizes (magic!)
std::vector<std::uint8_t> buffer;
if (test_file_0->read(buffer, test_string_length) != test_string_length) {
throw std::runtime_error("failed to read test string (data).");
}
// Make it a string, then test it.
std::string test_string_readback(buffer.begin(), buffer.end());
if (test_string != test_string_readback) {
throw std::runtime_error("test string read back incorrectly.");
}
}
}
const std::filesystem::path tdl0_fs_path = std::filesystem::current_path() / "test_files";
const std::filesystem::path tdl1_fs_path = std::filesystem::current_path() / "test_files2";
{
// Append directories to the dataland stack.
{
std::filesystem::create_directories(tdl0_fs_path);
if (!std::filesystem::is_directory(tdl0_fs_path)) {
std::cout << "Failed to create test look-up directory #1: " << tdl0_fs_path.string().c_str() << std::endl;
throw std::runtime_error("test directory 1 failed to mount.");
}
reversingspace::gfs::DirectoryPointer<FileType> dir = std::make_shared<reversingspace::gfs::Directory<FileType>>(tdl0_fs_path);
storage_server->mount(dir);
}
{
std::filesystem::create_directories(tdl1_fs_path);
if (!std::filesystem::is_directory(tdl1_fs_path)) {
std::cout << "Failed to create test look-up directory #2: " << tdl1_fs_path.string().c_str() << std::endl;
throw std::runtime_error("test directory 2 failed to mount.");
}
reversingspace::gfs::DirectoryPointer<FileType> dir = std::make_shared<reversingspace::gfs::Directory<FileType>>(tdl1_fs_path);
storage_server->mount(dir);
}
// Create a few files to do test look-ups on.
// Use fstream to do this, as it's not part of the core system and
// can't be misread as 'cheating'.
const char tf0_a[8] = "tf0tsta";
const char tf0_0[8] = "tf0tst0";
const char tf0_1[8] = "tf0tst1";
const char tf1_1[8] = "tf1tst1";
// Make sure to null terminate or it'll screw things up.
// String I/O is great like this.
{
// Only in 0
std::ofstream strm(tdl0_fs_path / "test_file_0a");
strm << tf0_a;
strm.put(0); // It doesn't null terminate. Yeah, I know.
strm.flush();
}
{
std::ofstream strm(tdl0_fs_path / "test_file_0");
strm << tf0_0;
strm.put(0); // It doesn't null terminate. Yeah, I know.
strm.flush();
}
{
std::ofstream strm(tdl1_fs_path / "test_file_0");
strm << tf0_1;
strm.put(0); // It doesn't null terminate. Yeah, I know.
strm.flush();
}
{
std::ofstream strm(tdl1_fs_path / "test_file_1");
strm << tf1_1;
strm.put(0); // It doesn't null terminate. Yeah, I know.
strm.flush();
}
{
auto tf0 = storage_server->get_file("test_file_0");
char test[8];
if (tf0->read(test, 8) != 8) {
std::cout << "failed to read tf0" << std::endl;
throw std::runtime_error("failed to read tf0");
}
if (strcmp(test, tf0_1) != 0) {
// Encapsulate in std::string to prevent lack of null terminator from blowing things up.
std::cout << "tf0 read back is invalid (should be `" << tf0_1 << "` but is `" << std::string(test) << "`" << std::endl;
throw std::runtime_error("failed to read tf0");
}
}
{
auto tf1 = storage_server->get_file("test_file_1");
char test[8];
if (tf1->read(test, 8) != 8) {
std::cout << "failed to read tf1" << std::endl;
throw std::runtime_error("failed to read tf1");
}
if (strcmp(test, tf1_1) != 0) {
// Encapsulate in std::string to prevent lack of null terminator from blowing things up.
std::cout << "tf1 read back is invalid (should be `" << tf1_1 << "` but is `" << std::string(test) << "`" << std::endl;
throw std::runtime_error("failed to read tf0");
}
}
{
auto tf = storage_server->get_file("test_file_0a");
char test[8];
if (tf->read(test, 8) != 8) {
std::cout << "failed to read tfa" << std::endl;
throw std::runtime_error("failed to read tfa");
}
if (strcmp(test, tf0_a) != 0) {
// Encapsulate in std::string to prevent lack of null terminator from blowing things up.
std::cout << "tf1 read back is invalid (should be `" << tf0_a << "` but is `" << std::string(test) << "`" << std::endl;
throw std::runtime_error("failed to read tf0");
}
}
// Unmount
storage_server->unmount(tdl0_fs_path);
// tf0 should now be a miss.
{
auto tf = storage_server->get_file("test_file_0a");
if (tf != nullptr) {
std::cout << "tf0a found despite mount being removed." << std::endl;
throw std::runtime_error("found tf0a in an invalid way.");
}
}
// Re-mount tfdl0, at the end, which makes this next part more fun.
// - Storing it as a directory this time so we can test unmounting by directory in a moment.
reversingspace::gfs::DirectoryPointer<FileType> tdl0_dir = std::make_shared<reversingspace::gfs::Directory<FileType>>(tdl0_fs_path);
storage_server->mount(tdl0_dir);
// tf0 should now be a hit.
{
auto tf = storage_server->get_file("test_file_0a");
if (tf == nullptr) {
std::cout << "tf0a not found despite re-mount." << std::endl;
throw std::runtime_error("tf0a missing.");
}
}
// tf0 will now read from 0, not 1
{
auto tf0 = storage_server->get_file("test_file_0");
char test[8];
if (tf0->read(test, 8) != 8) {
std::cout << "failed to read tf0" << std::endl;
throw std::runtime_error("failed to read tf0");
}
if (strcmp(test, tf0_0) != 0) {
// Encapsulate in std::string to prevent lack of null terminator from blowing things up.
std::cout << "tf0 read back is invalid (should be `" << tf0_0 << "` but is `" << std::string(test) << "`" << std::endl;
throw std::runtime_error("failed to read tf0");
}
}
// Unmount
storage_server->unmount(tdl0_dir);
// tf0 should now be a miss.
{
auto tf = storage_server->get_file("test_file_0a");
if (tf != nullptr) {
std::cout << "tf0a found despite mount being removed." << std::endl;
throw std::runtime_error("found tf0a in an invalid way.");
}
}
}
std::filesystem::remove_all(tdl0_fs_path);
std::filesystem::remove_all(tdl1_fs_path);
return 0;
} | 36.833333 | 134 | 0.667807 | [
"vector"
] |
4d555ddc6ac17d6aa649da93d110e0410b9a7940 | 1,777 | cpp | C++ | core/secure_permutation.cpp | mihaitodor/SeComLib | f2652363c736edd875f9e28ad4cfbce72dc7e8fe | [
"Apache-2.0"
] | 16 | 2018-05-14T09:03:44.000Z | 2021-08-04T13:31:07.000Z | core/secure_permutation.cpp | mihaitodor/SeComLib | f2652363c736edd875f9e28ad4cfbce72dc7e8fe | [
"Apache-2.0"
] | 2 | 2019-11-17T17:26:33.000Z | 2020-01-05T23:40:25.000Z | core/secure_permutation.cpp | mihaitodor/SeComLib | f2652363c736edd875f9e28ad4cfbce72dc7e8fe | [
"Apache-2.0"
] | 6 | 2018-06-13T10:07:29.000Z | 2021-04-09T01:51:18.000Z | /*
SeComLib
Copyright 2012-2013 TU Delft, Information Security & Privacy Lab (http://isplab.tudelft.nl/)
Contributors:
Inald Lagendijk (R.L.Lagendijk@TUDelft.nl)
Mihai Todor (todormihai@gmail.com)
Thijs Veugen (P.J.M.Veugen@tudelft.nl)
Zekeriya Erkin (z.erkin@tudelft.nl)
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.
*/
/**
@file core/secure_permutation.cpp
@brief Implementation of class SecurePermutation.
@details Implements the Fisher-Yates (Knuth) shuffle algorithm.
@author Mihai Todor (todormihai@gmail.com)
*/
#include "secure_permutation.h"
namespace SeComLib {
namespace Core {
/**
Populates the internal permutations vector.
@param size the length of the vector which needs to be shuffled
*/
SecurePermutation::SecurePermutation (const size_t size) : vectorSize(size) {
//store the the Fisher-Yates (Knuth) shuffle permutations
for (size_t index = size - 1; index > 0; --index) {
//generate a random number in the interval [0, index]
size_t randomValue = static_cast<size_t>(RandomProvider::GetInstance().GetRandomInteger(BigInteger(static_cast<unsigned long>(index + 1))).ToUnsignedLong());
this->permutations.emplace_back(std::pair<size_t, size_t>(index , randomValue));
}
}
}//namespace Core
}//namespace SeComLib | 36.265306 | 161 | 0.748452 | [
"vector"
] |
4d58f5384d837209eccb4951099bc9f950a9a663 | 5,417 | cpp | C++ | samples/Sandbox/src/Sandbox.cpp | BrotherhoodOfHam/Engine3D | 93d75d17d8bb6959e09209ad8f8be86fbdf6fcf9 | [
"MIT"
] | null | null | null | samples/Sandbox/src/Sandbox.cpp | BrotherhoodOfHam/Engine3D | 93d75d17d8bb6959e09209ad8f8be86fbdf6fcf9 | [
"MIT"
] | null | null | null | samples/Sandbox/src/Sandbox.cpp | BrotherhoodOfHam/Engine3D | 93d75d17d8bb6959e09209ad8f8be86fbdf6fcf9 | [
"MIT"
] | null | null | null | /*
Sandbox application source
*/
#include "Sandbox.h"
#include <tscore/debug/log.h>
#include <tscore/strings.h>
#include "3D/MaterialReader.h"
using namespace std;
using namespace ts;
///////////////////////////////////////////////////////////////////////////////////////////////////////
// Constructor/destructor
///////////////////////////////////////////////////////////////////////////////////////////////////////
Sandbox::Sandbox(int argc, char** argv) :
Application(argc, argv),
m_render(graphics()),
m_camera(input())
{
m_renderables = ComponentMap<RenderComponent>(&m_entityManager);
m_transforms = ComponentMap<TransformComponent>(&m_entityManager);
}
Sandbox::~Sandbox() {}
///////////////////////////////////////////////////////////////////////////////////////////////////////
// Application events
///////////////////////////////////////////////////////////////////////////////////////////////////////
int Sandbox::onInit()
{
input()->addListener(this);
SSystemInfo sysInfo;
Application::getSystemInfo(sysInfo);
tsinfo("OS: %", sysInfo.osName);
tsinfo("User: %", sysInfo.userName);
m_camera.setPosition(Vector(0, 1.0f, -4.0f));
m_camera.setSpeed(15.0f);
m_scale = 0.1f;
//////////////////////////////////////////////////////////////////////////////
// Configure forward renderer settings
//////////////////////////////////////////////////////////////////////////////
Vector dynamicColours[] =
{
colours::Green,
colours::LightBlue,
colours::Gold,
colours::Violet
};
Vector dynamicPos[] =
{
Vector(+10, 5, +10, 1),
Vector(+10, 5, -10, 1),
Vector(-10, 5, +10, 1),
Vector(-10, 5, -10, 1)
};
m_render.setAmbientColour(RGBA(30, 30, 30));
m_render.setDirectionalLightColour(RGBA(205, 215, 225));
m_render.setDirectionalLightDir(Vector(1.0f, -1.0f, -1.0f, 0));
//Dynamic lighting
for (size_t i = 0; i < 4; i++)
{
m_render.setLightAttenuation((LightSource)i, 0.01f, 0.1f, 1.0f);
m_render.setLightPosition((LightSource)i, dynamicPos[i]);
m_render.setLightColour((LightSource)i, dynamicColours[i]);
m_render.enableDynamicLight((LightSource)i);
}
//////////////////////////////////////////////////////////////////////////////
m_modelEntity = m_entityManager.create();
m_boxEntity = m_entityManager.create();
{
if (!addModelRenderComponent(m_modelEntity, "sponza/sponza.model"))
return -1;
//Set transforms
m_transforms.setComponent(m_modelEntity, Matrix::scale(m_scale));
}
{
if (!addModelRenderComponent(m_boxEntity, "cube.model"))
return -1;
//Set transforms
m_transforms.setComponent(m_boxEntity, Matrix::translation(Vector(0, 1, 0)));
}
//////////////////////////////////////////////////////////////////////////////
return 0;
}
void Sandbox::onExit()
{
input()->removeListener(this);
tsinfo("exit");
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
bool Sandbox::addModelRenderComponent(Entity entity, const String& modelfile)
{
const Model& model = graphics()->getModel(modelfile);
if (model.error())
{
tserror("unable to import model \"%\"", modelfile);
return false;
}
RenderComponent component;
component.items.reserve(model.meshes().size());
MaterialReader matReader(graphics(), model.materialFile());
for (const auto& mesh : model.meshes())
{
PhongMaterial mat(matReader.find(mesh.name));
mat.enableAlpha = false;
component.items.push_back(m_render.createRenderable(mesh, mat));
}
m_renderables.setComponent(entity, move(component));
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
// On Application update
///////////////////////////////////////////////////////////////////////////////////////////////////////
void Sandbox::onUpdate(double deltatime)
{
//Get display dimensions
Viewport dviewport(graphics()->getDisplayViewport());
m_camera.setAspectRatio((float)dviewport.w / dviewport.h);
m_camera.update(deltatime);
m_render.setCameraView(m_camera.getViewMatrix());
m_render.setCameraProjection(m_camera.getProjectionMatrix());
// Submit entities for rendering
for (Entity e : { m_modelEntity, m_boxEntity })
{
if (m_transforms.hasComponent(e))
{
const TransformComponent& tcomp(m_transforms.getComponent(e));
//Draw
if (m_renderables.hasComponent(e))
{
const RenderComponent& rcomp(m_renderables.getComponent(e));
for (const Renderable& item : rcomp.items)
{
m_render.draw(item, tcomp.getMatrix());
}
}
}
}
//Commit renderables
m_render.update();
//tsprofile("x:% y:% z:%", m_camera.getPosition().x(), m_camera.getPosition().y(), m_camera.getPosition().z());
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
void Sandbox::onKeyDown(EKeyCode code)
{
if (code == eKeyEsc)
{
exit(0);
}
else if (code == eKeyF1)
{
GraphicsDisplayOptions opt;
graphics()->getDisplayOptions(opt);
graphics()->setDisplayMode((opt.mode == DisplayMode::BORDERLESS) ? DisplayMode::WINDOWED : DisplayMode::BORDERLESS);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
| 27.497462 | 119 | 0.516891 | [
"mesh",
"vector",
"model",
"3d"
] |
4d60534d0f537bd9dd74f516760bdda9170f2cd4 | 12,296 | cpp | C++ | tests/Unit/IO/Observers/Test_ReductionObserver.cpp | Ambrou/spectre | a819ebbcca607d8af9683db3683bea14bf4ac23c | [
"MIT"
] | null | null | null | tests/Unit/IO/Observers/Test_ReductionObserver.cpp | Ambrou/spectre | a819ebbcca607d8af9683db3683bea14bf4ac23c | [
"MIT"
] | null | null | null | tests/Unit/IO/Observers/Test_ReductionObserver.cpp | Ambrou/spectre | a819ebbcca607d8af9683db3683bea14bf4ac23c | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Framework/TestingFramework.hpp"
#include <cstddef>
#include <functional>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
#include "DataStructures/Matrix.hpp"
#include "Domain/Structure/ElementId.hpp"
#include "Framework/ActionTesting.hpp"
#include "Helpers/IO/Observers/ObserverHelpers.hpp"
#include "IO/H5/AccessType.hpp"
#include "IO/H5/Dat.hpp"
#include "IO/H5/File.hpp"
#include "IO/Observer/Actions/ObserverRegistration.hpp"
#include "IO/Observer/Actions/RegisterWithObservers.hpp"
#include "IO/Observer/ArrayComponentId.hpp"
#include "IO/Observer/Initialize.hpp" // IWYU pragma: keep
#include "IO/Observer/ObservationId.hpp"
#include "IO/Observer/ObserverComponent.hpp" // IWYU pragma: keep
#include "IO/Observer/ReductionActions.hpp" // IWYU pragma: keep
#include "IO/Observer/Tags.hpp" // IWYU pragma: keep
#include "IO/Observer/TypeOfObservation.hpp"
#include "Parallel/ArrayIndex.hpp"
#include "Parallel/Reduction.hpp"
#include "Utilities/FileSystem.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/Numeric.hpp"
#include "Utilities/Overloader.hpp"
#include "Utilities/TaggedTuple.hpp"
namespace helpers = TestObservers_detail;
SPECTRE_TEST_CASE("Unit.IO.Observers.ReductionObserver", "[Unit][Observers]") {
using registration_list = tmpl::list<
observers::Actions::RegisterWithObservers<
helpers::RegisterObservers<observers::TypeOfObservation::Reduction>>,
Parallel::Actions::TerminatePhase>;
using metavariables = helpers::Metavariables<registration_list>;
using obs_component = helpers::observer_component<metavariables>;
using obs_writer = helpers::observer_writer_component<metavariables>;
using element_comp =
helpers::element_component<metavariables, registration_list>;
tuples::TaggedTuple<observers::Tags::ReductionFileName,
observers::Tags::VolumeFileName>
cache_data{};
const auto& output_file_prefix =
tuples::get<observers::Tags::ReductionFileName>(cache_data) =
"./Unit.IO.Observers.ReductionObserver";
ActionTesting::MockRuntimeSystem<metavariables> runner{cache_data};
ActionTesting::emplace_group_component<obs_component>(&runner);
for (size_t i = 0; i < 2; ++i) {
ActionTesting::next_action<obs_component>(make_not_null(&runner), 0);
}
ActionTesting::emplace_nodegroup_component<obs_writer>(&runner);
for (size_t i = 0; i < 2; ++i) {
ActionTesting::next_action<obs_writer>(make_not_null(&runner), 0);
}
// Specific IDs have no significance, just need different IDs.
const std::vector<ElementId<2>> element_ids{{1, {{{1, 0}, {1, 0}}}},
{1, {{{1, 1}, {1, 0}}}},
{1, {{{1, 0}, {2, 3}}}},
{1, {{{1, 0}, {5, 4}}}},
{0, {{{1, 0}, {1, 0}}}}};
for (const auto& id : element_ids) {
ActionTesting::emplace_component<element_comp>(&runner, id);
}
ActionTesting::set_phase(make_not_null(&runner),
metavariables::Phase::RegisterWithObservers);
// Register elements
for (const auto& id : element_ids) {
ActionTesting::next_action<element_comp>(make_not_null(&runner), id);
// Invoke the simple_action RegisterContributorWithObserver that was called
// on the observer component by the RegisterWithObservers action.
ActionTesting::invoke_queued_simple_action<obs_component>(
make_not_null(&runner), 0);
}
// Invoke the simple_action RegisterReductionContributorWithObserverWriter.
ActionTesting::invoke_queued_simple_action<obs_writer>(make_not_null(&runner),
0);
ActionTesting::invoke_queued_simple_action<obs_writer>(make_not_null(&runner),
0);
ActionTesting::set_phase(make_not_null(&runner),
metavariables::Phase::Testing);
const auto make_fake_reduction_data = make_overloader(
[](const observers::ArrayComponentId& id, const double time,
const helpers::reduction_data_from_doubles& /*meta*/) noexcept {
const auto hashed_id =
static_cast<double>(std::hash<observers::ArrayComponentId>{}(id));
constexpr size_t number_of_grid_points = 4;
const double error0 = 1.0e-10 * hashed_id + time;
const double error1 = 1.0e-12 * hashed_id + 2.0 * time;
return helpers::reduction_data_from_doubles{time, number_of_grid_points,
error0, error1};
},
[](const observers::ArrayComponentId& id, const double time,
const helpers::reduction_data_from_vector& /*meta*/) noexcept {
const auto hashed_id =
static_cast<double>(std::hash<observers::ArrayComponentId>{}(id));
constexpr size_t number_of_grid_points = 4;
const std::vector<double> data{1.0e-10 * hashed_id + time,
1.0e-12 * hashed_id + 2.0 * time,
1.0e-11 * hashed_id + 3.0 * time};
return helpers::reduction_data_from_vector{time, number_of_grid_points,
data};
},
[](const observers::ArrayComponentId& id, const double time,
const helpers::reduction_data_from_ds_and_vs& /*meta*/) noexcept {
const auto hashed_id =
static_cast<double>(std::hash<observers::ArrayComponentId>{}(id));
constexpr size_t number_of_grid_points = 4;
const double error0 = 1.0e-10 * hashed_id + time;
const double error1 = 1.0e-12 * hashed_id + 2.0 * time;
const std::vector<double> vector1{1.0e-10 * hashed_id + 3.0 * time,
1.0e-12 * hashed_id + 4.0 * time};
const std::vector<double> vector2{1.0e-11 * hashed_id + 5.0 * time,
1.0e-13 * hashed_id + 6.0 * time};
return helpers::reduction_data_from_ds_and_vs{
time, number_of_grid_points, error0, vector1, vector2, error1};
});
tmpl::for_each<tmpl::list<helpers::reduction_data_from_doubles,
helpers::reduction_data_from_vector,
helpers::reduction_data_from_ds_and_vs>>([
&element_ids, &make_fake_reduction_data, &runner, &output_file_prefix
](auto reduction_data_v) noexcept {
using reduction_data = tmpl::type_from<decltype(reduction_data_v)>;
const double time = 3.0;
const auto legend = make_overloader(
[](const helpers::reduction_data_from_doubles& /*meta*/) noexcept {
return std::vector<std::string>{"Time", "NumberOfPoints", "Error0",
"Error1"};
},
[](const helpers::reduction_data_from_vector& /*meta*/) noexcept {
return std::vector<std::string>{"Time", "NumberOfPoints", "Vec0",
"Vec1", "Vec2"};
},
[](const helpers::reduction_data_from_ds_and_vs& /*meta*/) noexcept {
return std::vector<std::string>{"Time", "NumberOfPoints", "Error0",
"Vec10", "Vec11", "Vec20",
"Vec21", "Error1"};
})(reduction_data{});
const std::string h5_file_name = output_file_prefix + ".h5";
if (file_system::check_if_file_exists(h5_file_name)) {
file_system::rm(h5_file_name, true);
}
// Test passing reduction data.
for (const auto& id : element_ids) {
const observers::ArrayComponentId array_id(
std::add_pointer_t<element_comp>{nullptr},
Parallel::ArrayIndex<ElementId<2>>{ElementId<2>{id}});
auto reduction_data_fakes =
make_fake_reduction_data(array_id, time, reduction_data{});
runner.simple_action<obs_component,
observers::Actions::ContributeReductionData>(
0, observers::ObservationId{time, "ElementObservationType"},
observers::ArrayComponentId{
std::add_pointer_t<element_comp>{nullptr},
Parallel::ArrayIndex<typename element_comp::array_index>(id)},
"/element_data", legend, std::move(reduction_data_fakes));
}
// Invoke the threaded action 'WriteReductionData' to write reduction data
// to disk.
runner.invoke_queued_threaded_action<obs_writer>(0);
runner.invoke_queued_threaded_action<obs_writer>(0);
REQUIRE(file_system::check_if_file_exists(h5_file_name));
// Check that the H5 file was written correctly.
{
const auto file = h5::H5File<h5::AccessType::ReadOnly>(h5_file_name);
const auto& dat_file = file.get<h5::Dat>("/element_data");
const Matrix written_data = dat_file.get_data();
const auto& written_legend = dat_file.get_legend();
CHECK(written_legend == legend);
const auto data = make_overloader(
[&time](
const helpers::reduction_data_from_doubles& /*meta*/) noexcept {
return helpers::reduction_data_from_doubles(time, 0, 0., 0.);
},
[&time](
const helpers::reduction_data_from_vector& /*meta*/) noexcept {
return helpers::reduction_data_from_vector(
time, 0, std::vector<double>{0., 0., 0.});
},
[&time](
const helpers::reduction_data_from_ds_and_vs& /*meta*/) noexcept {
return helpers::reduction_data_from_ds_and_vs(
time, 0, 0., std::vector<double>{0., 0.},
std::vector<double>{0., 0.}, 0.);
})(reduction_data{});
const auto expected =
alg::accumulate(
element_ids, data,
[&time, &make_fake_reduction_data](
reduction_data state, const ElementId<2>& id) noexcept {
const observers::ArrayComponentId array_id(
std::add_pointer_t<element_comp>{nullptr},
Parallel::ArrayIndex<ElementId<2>>{ElementId<2>{id}});
return state.combine(
make_fake_reduction_data(array_id, time, reduction_data{}));
})
.finalize()
.data();
make_overloader(
[](const auto l_expected, const auto l_written_data,
const helpers::reduction_data_from_doubles& /*meta*/) noexcept {
CHECK(std::get<0>(l_expected) == l_written_data(0, 0));
CHECK(std::get<1>(l_expected) == l_written_data(0, 1));
CHECK(std::get<2>(l_expected) == l_written_data(0, 2));
CHECK(std::get<3>(l_expected) == l_written_data(0, 3));
},
[](const auto l_expected, const auto l_written_data,
const helpers::reduction_data_from_vector&
/*meta*/) noexcept {
CHECK(std::get<0>(l_expected) == l_written_data(0, 0));
CHECK(std::get<1>(l_expected) == l_written_data(0, 1));
for (size_t i = 0; i < std::get<2>(l_expected).size(); ++i) {
CHECK(std::get<2>(l_expected)[i] == l_written_data(0, i + 2));
}
},
[](const auto l_expected, const auto l_written_data,
const helpers::reduction_data_from_ds_and_vs&
/*meta*/) noexcept {
CHECK(std::get<0>(l_expected) == l_written_data(0, 0));
CHECK(std::get<1>(l_expected) == l_written_data(0, 1));
CHECK(std::get<2>(l_expected) == l_written_data(0, 2));
for (size_t i = 0; i < std::get<3>(l_expected).size(); ++i) {
CHECK(std::get<3>(l_expected)[i] == l_written_data(0, i + 3));
}
for (size_t i = 0; i < std::get<4>(l_expected).size(); ++i) {
CHECK(std::get<4>(l_expected)[i] == l_written_data(0, i + 5));
}
CHECK(std::get<5>(l_expected) == l_written_data(0, 7));
})(expected, written_data, reduction_data{});
}
if (file_system::check_if_file_exists(h5_file_name)) {
file_system::rm(h5_file_name, true);
}
});
}
| 48.03125 | 80 | 0.609954 | [
"vector"
] |
4d6355531bdf987b06219f904cc681240e9d8198 | 1,408 | cc | C++ | third_party/icu_wrapper/third_party/icu/source/test/fuzzer/locale_fuzzer.cc | dendisuhubdy/CXTPL | 586b146c6a68b79a310ba20d133a0ca6211f22cc | [
"MIT"
] | 26 | 2015-04-22T05:25:25.000Z | 2020-11-15T11:07:56.000Z | third_party/icu_wrapper/third_party/icu/source/test/fuzzer/locale_fuzzer.cc | dendisuhubdy/CXTPL | 586b146c6a68b79a310ba20d133a0ca6211f22cc | [
"MIT"
] | 65 | 2019-09-20T07:25:22.000Z | 2020-10-14T14:31:52.000Z | third_party/icu_wrapper/third_party/icu/source/test/fuzzer/locale_fuzzer.cc | dendisuhubdy/CXTPL | 586b146c6a68b79a310ba20d133a0ca6211f22cc | [
"MIT"
] | 22 | 2019-09-25T10:11:57.000Z | 2020-10-12T10:40:14.000Z | // © 2019 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
// Fuzzer for ICU Locales.
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <string>
#include <vector>
#include "unicode/locid.h"
namespace {
void ConsumeNBytes(const uint8_t** data, size_t* size, size_t N) {
*data += N;
*size -= N;
}
uint8_t ConsumeUint8(const uint8_t** data, size_t* size) {
uint8_t tmp = 0;
if (*size >= 1) {
tmp = (*data)[0];
ConsumeNBytes(data, size, 1);
}
return tmp;
}
std::string ConsumeSubstring(const uint8_t** data, size_t* size) {
const size_t request_size = ConsumeUint8(data, size);
const char* substring_start = reinterpret_cast<const char*>(*data);
const size_t substring_size = std::min(*size, request_size);
ConsumeNBytes(data, size, substring_size);
return std::string(substring_start, substring_size);
}
} // namespace
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
const std::string language = ConsumeSubstring(&data, &size);
const std::string country = ConsumeSubstring(&data, &size);
const std::string variant = ConsumeSubstring(&data, &size);
const std::string kv_pairs = ConsumeSubstring(&data, &size);
icu::Locale locale(language.c_str(), country.c_str(), variant.c_str(),
kv_pairs.c_str());
return EXIT_SUCCESS;
}
| 28.16 | 73 | 0.693892 | [
"vector"
] |
4d6b97fe6b923948fe4c814ee47e16a06f9c6452 | 517 | cpp | C++ | codetop/Leetcode300.cpp | Aged-cat/interview_codehub | 0d915934a8d89a10943ef3e0ba8e528948433578 | [
"MIT"
] | 2 | 2021-09-06T06:47:34.000Z | 2022-02-21T04:43:23.000Z | codetop/Leetcode300.cpp | Aged-cat/interview_codehub | 0d915934a8d89a10943ef3e0ba8e528948433578 | [
"MIT"
] | null | null | null | codetop/Leetcode300.cpp | Aged-cat/interview_codehub | 0d915934a8d89a10943ef3e0ba8e528948433578 | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int lengthOfLIS(vector<int>&nums)
{
vector<int>dp(nums.size(),1);
for(int i=0;i<nums.size();++i)
{
for(int j=0;j<i;++j)
{
if(nums[i]>nums[j])
{
dp[i]=max(dp[i],dp[j]+1);
}
}
}
return *max_element(dp.begin(),dp.end());
}
int main(void)
{
vector<int>nums={10,9,2,5,3,7,101,18};
cout<<lengthOfLIS(nums)<<endl;
return 0;
} | 19.148148 | 45 | 0.497099 | [
"vector"
] |
4d6c8c26c50e5473312930409629eee8d8e8bac1 | 14,567 | cpp | C++ | emulator/src/osd/modules/sound/direct_sound.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/osd/modules/sound/direct_sound.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/osd/modules/sound/direct_sound.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:BSD-3-Clause
// copyright-holders:Aaron Giles
//============================================================
//
// sound.c - Win32 implementation of MAME sound routines
//
//============================================================
#include "sound_module.h"
#include "modules/osdmodule.h"
#if defined(OSD_WINDOWS) || defined(SDLMAME_WIN32)
// standard windows headers
#include <windows.h>
#include <mmsystem.h>
// undef WINNT for dsound.h to prevent duplicate definition
#undef WINNT
#include <dsound.h>
#undef interface
// MAME headers
#include "emu.h"
#include "osdepend.h"
#include "emuopts.h"
#ifdef SDLMAME_WIN32
#include "../../sdl/osdsdl.h"
#include <SDL2/SDL_syswm.h>
#include "../../sdl/window.h"
#else
#include "winmain.h"
#include "window.h"
#endif
#include <utility>
//============================================================
// DEBUGGING
//============================================================
#define LOG_SOUND 0
#define LOG(x) do { if (LOG_SOUND) osd_printf_verbose x; } while(0)
class sound_direct_sound : public osd_module, public sound_module
{
public:
sound_direct_sound() :
osd_module(OSD_SOUND_PROVIDER, "dsound"),
sound_module(),
m_dsound(nullptr),
m_bytes_per_sample(0),
m_primary_buffer(),
m_stream_buffer(),
m_stream_buffer_in(0),
m_buffer_underflows(0),
m_buffer_overflows(0)
{
}
virtual ~sound_direct_sound() { }
virtual int init(osd_options const &options) override;
virtual void exit() override;
// sound_module
virtual void update_audio_stream(bool is_throttled, int16_t const *buffer, int samples_this_frame) override;
virtual void set_mastervolume(int attenuation) override;
private:
class buffer
{
public:
buffer() : m_buffer(nullptr) { }
~buffer() { release(); }
ULONG release()
{
ULONG const result = m_buffer ? m_buffer->Release() : 0;
m_buffer = nullptr;
return result;
}
operator bool() const { return m_buffer; }
protected:
LPDIRECTSOUNDBUFFER m_buffer;
};
class primary_buffer : public buffer
{
public:
HRESULT create(LPDIRECTSOUND dsound)
{
assert(!m_buffer);
DSBUFFERDESC desc;
memset(&desc, 0, sizeof(desc));
desc.dwSize = sizeof(desc);
desc.dwFlags = DSBCAPS_PRIMARYBUFFER | DSBCAPS_GETCURRENTPOSITION2;
desc.lpwfxFormat = nullptr;
return dsound->CreateSoundBuffer(&desc, &m_buffer, nullptr);
}
HRESULT get_format(WAVEFORMATEX &format) const
{
assert(m_buffer);
return m_buffer->GetFormat(&format, sizeof(format), nullptr);
}
HRESULT set_format(WAVEFORMATEX const &format) const
{
assert(m_buffer);
return m_buffer->SetFormat(&format);
}
};
class stream_buffer : public buffer
{
public:
stream_buffer() : m_size(0), m_bytes1(nullptr), m_bytes2(nullptr), m_locked1(0), m_locked2(0) { }
HRESULT create(LPDIRECTSOUND dsound, DWORD size, WAVEFORMATEX &format)
{
assert(!m_buffer);
DSBUFFERDESC desc;
memset(&desc, 0, sizeof(desc));
desc.dwSize = sizeof(desc);
desc.dwFlags = DSBCAPS_CTRLVOLUME | DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2;
desc.dwBufferBytes = size;
desc.lpwfxFormat = &format;
m_size = size;
return dsound->CreateSoundBuffer(&desc, &m_buffer, nullptr);
}
HRESULT play_looping() const
{
assert(m_buffer);
return m_buffer->Play(0, 0, DSBPLAY_LOOPING);
}
HRESULT stop() const
{
assert(m_buffer);
return m_buffer->Stop();
}
HRESULT set_volume(LONG volume) const
{
assert(m_buffer);
return m_buffer->SetVolume(volume);
}
HRESULT set_min_volume() { return set_volume(DSBVOLUME_MIN); }
HRESULT get_current_positions(DWORD &play_pos, DWORD &write_pos) const
{
assert(m_buffer);
return m_buffer->GetCurrentPosition(&play_pos, &write_pos);
}
HRESULT copy_data(DWORD cursor, DWORD bytes, void const *data)
{
HRESULT result = lock(cursor, bytes);
if (DS_OK != result)
return result;
assert(m_bytes1);
assert((m_locked1 + m_locked2) >= bytes);
memcpy(m_bytes1, data, std::min(m_locked1, bytes));
if (m_locked1 < bytes)
{
assert(m_bytes2);
memcpy(m_bytes2, (uint8_t const *)data + m_locked1, bytes - m_locked1);
}
unlock();
return DS_OK;
}
HRESULT clear()
{
HRESULT result = lock_all();
if (DS_OK != result)
return result;
assert(m_bytes1);
assert(!m_bytes2);
assert(m_size == m_locked1);
assert(0U == m_locked2);
memset(m_bytes1, 0, m_locked1);
unlock();
return DS_OK;
}
DWORD size() const { return m_size; }
protected:
HRESULT lock(DWORD cursor, DWORD bytes)
{
assert(cursor < m_size);
assert(bytes <= m_size);
assert(m_buffer);
assert(!m_bytes1);
return m_buffer->Lock(
cursor, bytes,
&m_bytes1,
&m_locked1,
&m_bytes2,
&m_locked2,
0);
}
HRESULT lock_all() { return lock(0, m_size); }
HRESULT unlock()
{
assert(m_buffer);
assert(m_bytes1);
HRESULT const result = m_buffer->Unlock(
m_bytes1,
m_locked1,
m_bytes2,
m_locked2);
m_bytes1 = m_bytes2 = nullptr;
m_locked1 = m_locked2 = 0;
return result;
}
DWORD m_size;
void *m_bytes1, *m_bytes2;
DWORD m_locked1, m_locked2;
};
HRESULT dsound_init();
void dsound_kill();
HRESULT create_buffers(DWORD size, WAVEFORMATEX &format);
void destroy_buffers();
// DirectSound objects
LPDIRECTSOUND m_dsound;
// descriptors and formats
uint32_t m_bytes_per_sample;
// sound buffers
primary_buffer m_primary_buffer;
stream_buffer m_stream_buffer;
uint32_t m_stream_buffer_in;
// buffer over/underflow counts
unsigned m_buffer_underflows;
unsigned m_buffer_overflows;
};
//============================================================
// init
//============================================================
int sound_direct_sound::init(osd_options const &options)
{
// attempt to initialize directsound
// don't make it fatal if we can't -- we'll just run without sound
dsound_init();
m_buffer_underflows = m_buffer_overflows = 0;
return 0;
}
//============================================================
// exit
//============================================================
void sound_direct_sound::exit()
{
// kill the buffers and dsound
destroy_buffers();
dsound_kill();
// print out over/underflow stats
if (m_buffer_overflows || m_buffer_underflows)
{
osd_printf_verbose(
"Sound: buffer overflows=%u underflows=%u\n",
m_buffer_overflows,
m_buffer_underflows);
}
LOG(("Sound buffer: overflows=%u underflows=%u\n", m_buffer_overflows, m_buffer_underflows));
}
//============================================================
// update_audio_stream
//============================================================
void sound_direct_sound::update_audio_stream(
bool is_throttled,
int16_t const *buffer,
int samples_this_frame)
{
int const bytes_this_frame = samples_this_frame * m_bytes_per_sample;
HRESULT result;
// if no sound, there is no buffer
if (!m_stream_buffer)
return;
// determine the current play position
DWORD play_position, write_position;
result = m_stream_buffer.get_current_positions(play_position, write_position);
if (DS_OK != result)
return;
//DWORD orig_write = write_position;
// normalize the write position so it is always after the play position
if (write_position < play_position)
write_position += m_stream_buffer.size();
// normalize the stream in position so it is always after the write position
DWORD stream_in = m_stream_buffer_in;
if (stream_in < write_position)
stream_in += m_stream_buffer.size();
// now we should have, in order:
// <------pp---wp---si--------------->
// if we're between play and write positions, then bump forward, but only in full chunks
while (stream_in < write_position)
{
//printf("Underflow: PP=%d WP=%d(%d) SI=%d(%d) BTF=%d\n", (int)play_position, (int)write_position, (int)orig_write, (int)stream_in, (int)m_stream_buffer_in, (int)bytes_this_frame);
m_buffer_underflows++;
stream_in += bytes_this_frame;
}
// if we're going to overlap the play position, just skip this chunk
if ((stream_in + bytes_this_frame) > (play_position + m_stream_buffer.size()))
{
//printf("Overflow: PP=%d WP=%d(%d) SI=%d(%d) BTF=%d\n", (int)play_position, (int)write_position, (int)orig_write, (int)stream_in, (int)m_stream_buffer_in, (int)bytes_this_frame);
m_buffer_overflows++;
return;
}
// now we know where to copy; let's do it
m_stream_buffer_in = stream_in % m_stream_buffer.size();
result = m_stream_buffer.copy_data(m_stream_buffer_in, bytes_this_frame, buffer);
// if we failed, assume it was an underflow (i.e.,
if (result != DS_OK)
{
m_buffer_underflows++;
return;
}
// adjust the input pointer
m_stream_buffer_in = (m_stream_buffer_in + bytes_this_frame) % m_stream_buffer.size();
}
//============================================================
// set_mastervolume
//============================================================
void sound_direct_sound::set_mastervolume(int attenuation)
{
// clamp the attenuation to 0-32 range
attenuation = std::max(std::min(attenuation, 0), -32);
// set the master volume
if (m_stream_buffer)
{
if (-32 == attenuation)
m_stream_buffer.set_min_volume();
else
m_stream_buffer.set_volume(100 * attenuation);
}
}
//============================================================
// dsound_init
//============================================================
HRESULT sound_direct_sound::dsound_init()
{
assert(!m_dsound);
HRESULT result;
// create the DirectSound object
result = DirectSoundCreate(nullptr, &m_dsound, nullptr);
if (result != DS_OK)
{
osd_printf_error("Error creating DirectSound: %08x\n", (unsigned)result);
goto error;
}
// get the capabilities
DSCAPS dsound_caps;
dsound_caps.dwSize = sizeof(dsound_caps);
result = m_dsound->GetCaps(&dsound_caps);
if (result != DS_OK)
{
osd_printf_error("Error getting DirectSound capabilities: %08x\n", (unsigned)result);
goto error;
}
// set the cooperative level
{
#ifdef SDLMAME_WIN32
SDL_SysWMinfo wminfo;
SDL_VERSION(&wminfo.version);
SDL_GetWindowWMInfo(std::dynamic_pointer_cast<sdl_window_info>(osd_common_t::s_window_list.front())->platform_window(), &wminfo);
HWND const window = wminfo.info.win.window;
#else // SDLMAME_WIN32
HWND const window = std::static_pointer_cast<win_window_info>(osd_common_t::s_window_list.front())->platform_window();
#endif // SDLMAME_WIN32
result = m_dsound->SetCooperativeLevel(window, DSSCL_PRIORITY);
}
if (result != DS_OK)
{
osd_printf_error("Error setting DirectSound cooperative level: %08x\n", (unsigned)result);
goto error;
}
{
// make a format description for what we want
WAVEFORMATEX stream_format;
stream_format.wBitsPerSample = 16;
stream_format.wFormatTag = WAVE_FORMAT_PCM;
stream_format.nChannels = 2;
stream_format.nSamplesPerSec = sample_rate();
stream_format.nBlockAlign = stream_format.wBitsPerSample * stream_format.nChannels / 8;
stream_format.nAvgBytesPerSec = stream_format.nSamplesPerSec * stream_format.nBlockAlign;
// compute the buffer size based on the output sample rate
DWORD stream_buffer_size = stream_format.nSamplesPerSec * stream_format.nBlockAlign * m_audio_latency / 10;
stream_buffer_size = std::max(DWORD(1024), (stream_buffer_size / 1024) * 1024);
LOG(("stream_buffer_size = %u\n", (unsigned)stream_buffer_size));
// create the buffers
m_bytes_per_sample = stream_format.nBlockAlign;
m_stream_buffer_in = 0;
result = create_buffers(stream_buffer_size, stream_format);
if (result != DS_OK)
goto error;
}
// start playing
result = m_stream_buffer.play_looping();
if (result != DS_OK)
{
osd_printf_error("Error playing: %08x\n", (uint32_t)result);
goto error;
}
return DS_OK;
// error handling
error:
destroy_buffers();
dsound_kill();
return result;
}
//============================================================
// dsound_kill
//============================================================
void sound_direct_sound::dsound_kill()
{
// release the object
if (m_dsound)
m_dsound->Release();
m_dsound = nullptr;
}
//============================================================
// create_buffers
//============================================================
HRESULT sound_direct_sound::create_buffers(DWORD size, WAVEFORMATEX &format)
{
assert(m_dsound);
assert(!m_primary_buffer);
assert(!m_stream_buffer);
HRESULT result;
// create the primary buffer
result = m_primary_buffer.create(m_dsound);
if (result != DS_OK)
{
osd_printf_error("Error creating primary DirectSound buffer: %08x\n", (unsigned)result);
goto error;
}
// attempt to set the primary format
result = m_primary_buffer.set_format(format);
if (result != DS_OK)
{
osd_printf_error("Error setting primary DirectSound buffer format: %08x\n", (unsigned)result);
goto error;
}
// log the primary format
WAVEFORMATEX primary_format;
result = m_primary_buffer.get_format(primary_format);
if (result != DS_OK)
{
osd_printf_error("Error getting primary DirectSound buffer format: %08x\n", (unsigned)result);
goto error;
}
osd_printf_verbose(
"DirectSound: Primary buffer: %d Hz, %d bits, %d channels\n",
(int)primary_format.nSamplesPerSec,
(int)primary_format.wBitsPerSample,
(int)primary_format.nChannels);
// create the stream buffer
result = m_stream_buffer.create(m_dsound, size, format);
if (result != DS_OK)
{
osd_printf_error("Error creating DirectSound stream buffer: %08x\n", (unsigned)result);
goto error;
}
// clear the buffer
result = m_stream_buffer.clear();
if (result != DS_OK)
{
osd_printf_error("Error locking DirectSound stream buffer: %08x\n", (unsigned)result);
goto error;
}
return DS_OK;
// error handling
error:
destroy_buffers();
return result;
}
//============================================================
// destroy_buffers
//============================================================
void sound_direct_sound::destroy_buffers(void)
{
// stop any playback
if (m_stream_buffer)
m_stream_buffer.stop();
// release the stream buffer
m_stream_buffer.release();
// release the primary buffer
m_primary_buffer.release();
}
#else // defined(OSD_WINDOWS) || defined(SDLMAME_WIN32)
MODULE_NOT_SUPPORTED(sound_direct_sound, OSD_SOUND_PROVIDER, "dsound")
#endif // defined(OSD_WINDOWS) || defined(SDLMAME_WIN32)
MODULE_DEFINITION(SOUND_DSOUND, sound_direct_sound)
| 25.919929 | 183 | 0.653532 | [
"object"
] |
4d6d1852c0c2e8513beec97ebb531f3370d3561d | 5,086 | cpp | C++ | openstudiocore/src/plugin/ExternalModelInterface.cpp | bobzabcik/OpenStudio | 858321dc0ad8d572de15858d2ae487b029a8d847 | [
"blessing"
] | null | null | null | openstudiocore/src/plugin/ExternalModelInterface.cpp | bobzabcik/OpenStudio | 858321dc0ad8d572de15858d2ae487b029a8d847 | [
"blessing"
] | null | null | null | openstudiocore/src/plugin/ExternalModelInterface.cpp | bobzabcik/OpenStudio | 858321dc0ad8d572de15858d2ae487b029a8d847 | [
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2013, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#include <plugin/ExternalModelInterface.hpp>
#include <plugin/ExternalPlugin.hpp>
#include <plugin/ExternalObjectInterface.hpp>
#include <model/Model_Impl.hpp>
#include <model/ModelObject_Impl.hpp>
#include <utilities/core/Assert.hpp>
#include <QThread>
namespace openstudio {
namespace plugin {
ModelHolder::ModelHolder(openstudio::model::detail::Model_Impl* ptr)
: m_ptr(ptr)
{}
openstudio::model::detail::Model_Impl* ModelHolder::ptr() const
{
return m_ptr;
}
ExternalModelInterface* ExternalModelInterface::create(const std::string& key, const ModelHolder& modelHolder)
{
ExternalModelInterface* result = new ExternalModelInterface(key, modelHolder);
return result;
}
ExternalModelInterface::ExternalModelInterface(const std::string& key, const ModelHolder& modelHolder)
: QObject(), m_key(key)
{
LOG(Trace, "ExternalModelInterface, key = " << key);
//LOG(Trace, "ExternalModelInterface, modelHolder.ptr() = " << modelHolder.ptr());
//QThread* ct = QThread::currentThread();
//LOG(Trace, "ExternalModelInterface, currentThread = " << ct);
//QThread* thread = this->thread();
//LOG(Trace, "ExternalModelInterface, this->thread() = " << thread);
// connect signals
bool test;
test = connect(this, SIGNAL(requestInitialModelObjects()), modelHolder.ptr(), SLOT(reportInitialModelObjects()), Qt::QueuedConnection);
OS_ASSERT(test);
test = connect(modelHolder.ptr(), SIGNAL(initialModelObject(openstudio::model::detail::ModelObject_Impl*, const openstudio::IddObjectType&, const openstudio::UUID&)), this, SLOT(initialModelObject(openstudio::model::detail::ModelObject_Impl*, const openstudio::IddObjectType&, const openstudio::UUID&)), Qt::QueuedConnection);
OS_ASSERT(test);
test = connect(modelHolder.ptr(), SIGNAL(initialReportComplete()), this, SLOT(initialize()), Qt::QueuedConnection);
OS_ASSERT(test);
test = connect(modelHolder.ptr(), SIGNAL(addWorkspaceObject(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>, const openstudio::IddObjectType&, const openstudio::UUID&)), this, SLOT(newWorkspaceObject(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl>, const openstudio::IddObjectType&, const openstudio::UUID&)), Qt::QueuedConnection);
OS_ASSERT(test);
emit requestInitialModelObjects();
}
ExternalModelInterface::~ExternalModelInterface()
{
LOG(Trace, "~ExternalModelInterface");
}
std::string ExternalModelInterface::key() const
{
return m_key;
}
void ExternalModelInterface::onInitialModelObject(const ModelObjectHolder& modelObjectHolder, const openstudio::IddObjectType& iddObjectType, const openstudio::UUID& handle)
{
LOG(Trace, "onInitialModelObject");
}
void ExternalModelInterface::onInitialize()
{
LOG(Trace, "onInitialize");
}
void ExternalModelInterface::onNewModelObject(const ModelObjectHolder& modelObjectHolder, const openstudio::IddObjectType& iddObjectType, const openstudio::UUID& handle)
{
LOG(Trace, "onNewModelObject");
}
void ExternalModelInterface::initialModelObject(openstudio::model::detail::ModelObject_Impl* modelObject, const openstudio::IddObjectType& iddObjectType, const openstudio::UUID& handle)
{
LOG(Trace, "initialModelObject");
ModelObjectHolder modelObjectHolder(modelObject);
onInitialModelObject(modelObjectHolder, iddObjectType, handle);
}
void ExternalModelInterface::initialize()
{
LOG(Trace, "initialize");
onInitialize();
}
void ExternalModelInterface::newWorkspaceObject(boost::shared_ptr<openstudio::detail::WorkspaceObject_Impl> workspaceObject, const openstudio::IddObjectType& iddObjectType, const openstudio::UUID& handle)
{
LOG(Trace, "newWorkspaceObject");
boost::shared_ptr<openstudio::model::detail::ModelObject_Impl> modelObject = boost::dynamic_pointer_cast<openstudio::model::detail::ModelObject_Impl>(workspaceObject);
OS_ASSERT(modelObject);
ModelObjectHolder modelObjectHolder(modelObject.get());
onNewModelObject(modelObjectHolder, iddObjectType, handle);
}
} // plugin
} // openstudio
| 41.688525 | 359 | 0.73024 | [
"model"
] |
4d704866c83ae6435ffa2e5ff782b483f735433e | 5,879 | cpp | C++ | gpu/cuda/cuda.cpp | kanhavishva/parcrypt | 1186bd1c3498086cedd7cf3bf599489856556035 | [
"MIT"
] | 5 | 2022-02-20T14:31:09.000Z | 2022-03-04T20:17:12.000Z | gpu/cuda/cuda.cpp | kanhavishva/parcrypt | 1186bd1c3498086cedd7cf3bf599489856556035 | [
"MIT"
] | 5 | 2022-02-23T03:57:49.000Z | 2022-03-28T10:40:41.000Z | gpu/cuda/cuda.cpp | brichard19/parcrypt | c24a363aa061b1cffa88c5950408c9c810d88a3d | [
"MIT"
] | 5 | 2022-02-20T14:31:02.000Z | 2022-02-21T16:50:22.000Z | #include "gpulib_cuda.h"
static bool _cuda_initialized = false;
void cu_call(CUresult err)
{
if(err != CUDA_SUCCESS) {
throw gpulib::Exception("CUDA error: " + std::to_string(err));
}
}
static void initialize_cuda()
{
if(!_cuda_initialized) {
cu_call(cuInit(0));
_cuda_initialized = true;
}
}
gpulib::cuda::CUDADevice::CUDADevice(int device_id) : _device_id(device_id)
{
cu_call(cuDeviceGet(&_device, device_id));
cu_call(cuCtxCreate(&_ctx, 0, _device));
}
gpulib::cuda::CUDADevice::~CUDADevice()
{
cuCtxDestroy(_ctx);
}
std::shared_ptr<gpulib::IDeviceMemory> gpulib::cuda::CUDADevice::malloc(size_t size)
{
std::shared_ptr<IDeviceMemory> ptr;
CUDADeviceMemory* mem = new CUDADeviceMemory(_device, size);
ptr.reset(mem);
return ptr;
}
std::shared_ptr<gpulib::IKernel> gpulib::cuda::CUDADevice::load_kernel_from_source(const std::string& src, const std::string& entry)
{
std::shared_ptr<IKernel> ptr;
return ptr;
}
std::shared_ptr<gpulib::IKernel> gpulib::cuda::CUDADevice::load_kernel_from_file(const std::string& file_path, const std::string& entry)
{
CUmodule module;
if(_modules.find(file_path) == _modules.end()) {
cu_call(cuModuleLoad(&module, file_path.c_str()));
_modules.insert(std::pair<std::string, CUmodule>(file_path, module));
} else {
module = _modules[file_path];
}
CUfunction function;
cu_call(cuModuleGetFunction(&function, module, entry.c_str()));
std::shared_ptr<IKernel> ptr;
ptr.reset(new CUDAKernel(function));
return ptr;
}
std::shared_ptr<gpulib::IKernel> gpulib::cuda::CUDADevice::load_kernel_from_source(const std::string& entry, const std::string& src, const std::string& module_name)
{
std::shared_ptr<IKernel> ptr;
return ptr;
}
void gpulib::cuda::CUDAKernel::set_block_size(std::array<size_t, 3> block_size)
{
_block_size = block_size;
}
void gpulib::cuda::CUDAKernel::set_grid_size(std::array<size_t, 3> grid_size)
{
_grid_size = grid_size;
}
size_t gpulib::cuda::CUDADevice::get_global_mem_size()
{
return 0;
}
std::array<size_t, 3> gpulib::cuda::CUDADevice::get_max_local_dim()
{
return { {1,1,1} };
}
size_t gpulib::cuda::CUDADevice::get_max_local_size()
{
return 0;
}
size_t gpulib::cuda::CUDADevice::get_mp_count()
{
return _mp_count;
}
gpulib::cuda::CUDADeviceMemory::CUDADeviceMemory(CUdevice device, size_t size) : _device(device), _size(size)
{
cu_call(cuMemAlloc(&_mem, size));
}
gpulib::cuda::CUDADeviceMemory::~CUDADeviceMemory()
{
if(_mem) {
cuMemFree(_mem);
}
}
void gpulib::cuda::CUDADeviceMemory::read(void* dst, size_t count)
{
cu_call(cuMemcpyDtoH(dst, _mem, count));
}
void gpulib::cuda::CUDADeviceMemory::read(void* dst, size_t offset, size_t count)
{
cu_call(cuMemcpyDtoH(dst, _mem + offset, count));
}
void gpulib::cuda::CUDADeviceMemory::write(const void* src, size_t count)
{
cu_call(cuMemcpyHtoD(_mem, src, count));
}
void gpulib::cuda::CUDADeviceMemory::write(const void* src, size_t offset, size_t count)
{
cu_call(cuMemcpyHtoD(_mem + offset, src, count));
}
void gpulib::cuda::CUDADeviceMemory::memset(uint32_t value)
{
cu_call(cuMemsetD32(_mem, value, _size / sizeof(value)));
}
size_t gpulib::cuda::CUDADeviceMemory::size()
{
return _size;
}
gpulib::cuda::CUDAKernel::CUDAKernel(CUfunction function) : _function(function)
{
}
gpulib::cuda::CUDAKernel::~CUDAKernel()
{
}
void gpulib::cuda::CUDAKernel::call()
{
std::vector<void*> arg_ptrs;
size_t num_args = _args.size();
for(int i = 0; i < num_args; i++) {
arg_ptrs.push_back(_args[i].data());
}
cu_call(cuLaunchKernel(_function,
static_cast<unsigned int>(_grid_size[0]),
static_cast<unsigned int>(_grid_size[1]),
static_cast<unsigned int>(_grid_size[2]),
static_cast<unsigned int>(_block_size[0]),
static_cast<unsigned int>(_block_size[1]),
static_cast<unsigned int>(_block_size[2]),
0,
0,
arg_ptrs.data(),
nullptr));
cu_call(cuCtxSynchronize());
}
void gpulib::cuda::CUDAKernel::set_arg(int arg_idx, const void* arg, size_t size)
{
std::vector<uint8_t> value(size);
std::memcpy(value.data(), arg, size);
_args[arg_idx] = value;
}
void gpulib::cuda::CUDAKernel::set_arg(int arg_idx, std::shared_ptr<IDeviceMemory> buffer)
{
CUDADeviceMemory* mem_obj = static_cast<CUDADeviceMemory*>(buffer.get());
CUdeviceptr dev_ptr = mem_obj->get_mem();
std::vector<uint8_t> value(sizeof(dev_ptr));
std::memcpy(value.data(), &dev_ptr, sizeof(dev_ptr));
_args[arg_idx] = value;
}
std::vector<gpulib::DeviceInfo> gpulib::cuda::get_cuda_devices()
{
initialize_cuda();
std::vector<gpulib::DeviceInfo> device_list;
int device_count = 0;
cu_call(cuDeviceGetCount(&device_count));
if(device_count == 0) {
return device_list;
}
for(int device_id = 0; device_id < device_count; device_id++) {
CUdevice d;
gpulib::DeviceInfo info;
info.type = gpulib::CUDA;
info.vendor_name = "NVIDIA Corporation";
cu_call(cuDeviceGet(&d, device_id));
info.cuda_device_id = device_id;
// Get device name
int name_len = 0;
char name[128] = { 0 };
cu_call(cuDeviceGetName(name, sizeof(name), d));
info.device_name = std::string(name);
size_t mem_size = 0;
cu_call(cuDeviceTotalMem(&mem_size, d));
info.mem_size = (uint64_t)mem_size;
device_list.push_back(info);
}
return device_list;
} | 24.495833 | 165 | 0.643137 | [
"vector"
] |
4d717127936e8c683ee5632ad1eb31b11be209fc | 1,443 | cc | C++ | src/tags/IfTag.cc | jdavidberger/stencet | 092dfabe395c46efdd74504050f83aa38d1b2c87 | [
"MIT"
] | null | null | null | src/tags/IfTag.cc | jdavidberger/stencet | 092dfabe395c46efdd74504050f83aa38d1b2c87 | [
"MIT"
] | null | null | null | src/tags/IfTag.cc | jdavidberger/stencet | 092dfabe395c46efdd74504050f83aa38d1b2c87 | [
"MIT"
] | null | null | null | /* Copyright (C) 2012-2013 Justin Berger
The full license is available in the LICENSE file at the root of this project and is also available at http://opensource.org/licenses/MIT. */
#include <mxcomp/use.h>
#include <stencet/tags/IfTag.h>
#include <string.h>
namespace stencet {
void IfTag::render(std::ostream& out, ViewContext& vm) const {
for(auto pair : bodies){
bool eval = pair.first == 0; // Means this is a raw else
if(!eval){
auto pred = use(pair.first->Eval(vm));
eval = pred && pred->asBool();
}
if(eval) {
pair.second->render(out, vm);
return;
}
}
}
IfTag::~IfTag(){
for(auto pair : bodies){
delete pair.first;
delete pair.second;
}
}
IfTag::IfTag(std::istream& stream, const std::string& _content) {
std::string content = _content;
bool seenIf = false;
bool seenElse = false;
while( content != "" ) {
auto& pair = *(bodies.insert( bodies.end(), std::make_pair( (Expr*)0, new Template() ) ));
std::string ex;
finish f{ex};
std::string command;
assert(!seenElse);
msscanf(content, "${command} ${pred}", command, f);
if(command == "else") {
seenElse = true;
assert(ex == "");
} else {
assert(command == "if" || command == "elseif");
seenIf = true;
assert(ex != "");
pair.first = Parse(ex);
}
assert(seenIf);
pair.second->Parse(stream, content);
}
}
}
| 26.722222 | 144 | 0.587665 | [
"render"
] |
4d7327007445799d64bebe9eef0c0bbfe5fd3add | 9,356 | cpp | C++ | ros2/src/cinematography/src/debug_viz.cpp | nightduck/AirSim | 2ba7124ceff7607f23463f483cd3e2cbe026d0ca | [
"MIT"
] | null | null | null | ros2/src/cinematography/src/debug_viz.cpp | nightduck/AirSim | 2ba7124ceff7607f23463f483cd3e2cbe026d0ca | [
"MIT"
] | 14 | 2021-02-25T22:32:34.000Z | 2021-08-20T17:17:12.000Z | ros2/src/cinematography/src/debug_viz.cpp | nightduck/AirSim | 2ba7124ceff7607f23463f483cd3e2cbe026d0ca | [
"MIT"
] | null | null | null | #include "rclcpp/rclcpp.hpp"
#include <boost/make_shared.hpp>
#include "builtin_interfaces/msg/time.hpp"
#include "cinematography_msgs/msg/multi_do_farray.hpp"
#include "cinematography_msgs/msg/vision_measurements.hpp"
#include "sensor_msgs/msg/image.hpp"
#include "sensor_msgs/msg/point_cloud2.hpp"
#include "geometry_msgs/msg/pose_stamped.hpp"
#include "geometry_msgs/msg/pose_array.hpp"
#include <visualization_msgs/msg/marker_array.hpp>
#include "tsdf_package_msgs/msg/tsdf.hpp"
#include "tsdf_package_msgs/msg/voxel.hpp"
#include <opencv2/opencv.hpp>
#include <cv_bridge/cv_bridge.h>
using namespace std::chrono_literals;
using std::placeholders::_1;
class DebugViz : public rclcpp::Node {
private:
rclcpp::Subscription<geometry_msgs::msg::Pose>::SharedPtr pose_sub;
rclcpp::Subscription<cinematography_msgs::msg::MultiDOFarray>::SharedPtr drone_traj_sub;
rclcpp::Subscription<cinematography_msgs::msg::MultiDOFarray>::SharedPtr actor_traj_sub;
rclcpp::Subscription<cinematography_msgs::msg::MultiDOFarray>::SharedPtr ideal_traj_sub;
rclcpp::Subscription<sensor_msgs::msg::Image>::SharedPtr img_sub;
rclcpp::Subscription<cinematography_msgs::msg::VisionMeasurements>::SharedPtr vm_sub;
rclcpp::Subscription<tsdf_package_msgs::msg::Tsdf>::SharedPtr tsdf_occupied_voxels_sub;
rclcpp::Publisher<geometry_msgs::msg::PoseStamped>::SharedPtr pose_pub;
rclcpp::Publisher<geometry_msgs::msg::PoseArray>::SharedPtr actor_traj_pub;
rclcpp::Publisher<geometry_msgs::msg::PoseArray>::SharedPtr drone_traj_pub;
rclcpp::Publisher<geometry_msgs::msg::PoseArray>::SharedPtr ideal_traj_pub;
rclcpp::Publisher<sensor_msgs::msg::Image>::SharedPtr img_pub;
rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr tsdf_occupied_voxels_pub;
std::recursive_mutex m;
rclcpp::Clock clock = rclcpp::Clock(RCL_SYSTEM_TIME);
std::string world_frame_id_ = "world_ned";
cv::Mat lastFrame;
visualization_msgs::msg::MarkerArray markerArray;
rclcpp::Time last_time;
void fetchDronePose(const geometry_msgs::msg::Pose::SharedPtr pose) {
geometry_msgs::msg::PoseStamped ps;
ps.pose = *pose;
ps.header.frame_id = world_frame_id_;
ps.header.stamp = clock.now();
pose_pub->publish(ps);
}
geometry_msgs::msg::PoseArray convertTraj(const cinematography_msgs::msg::MultiDOFarray::SharedPtr traj) {
geometry_msgs::msg::PoseArray traj_out;
traj_out.header.frame_id = "world_ned";
traj_out.header.stamp = this->now();
traj_out.poses.reserve(traj->points.size());
for(cinematography_msgs::msg::MultiDOF md : traj->points) {
geometry_msgs::msg::Pose p;
p.position.x = md.x;
p.position.y = md.y;
p.position.z = md.z;
p.orientation.w = cos(md.yaw/2);
p.orientation.x = 0;
p.orientation.y = 0;
p.orientation.z = sin(md.yaw/2);
traj_out.poses.push_back(p);
}
return traj_out;
}
void fetchActorTraj(const cinematography_msgs::msg::MultiDOFarray::SharedPtr traj) {
actor_traj_pub->publish(convertTraj(traj));
}
void fetchDroneTraj(const cinematography_msgs::msg::MultiDOFarray::SharedPtr traj) {
drone_traj_pub->publish(convertTraj(traj));
}
void fetchIdealTraj(const cinematography_msgs::msg::MultiDOFarray::SharedPtr traj) {
ideal_traj_pub->publish(convertTraj(traj));
}
void fetchImage(const sensor_msgs::msg::Image::SharedPtr img) {
m.lock();
cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(img, img->encoding);
lastFrame = cv_ptr->image;
m.unlock();
}
void fetchVisionMeasurements(const cinematography_msgs::msg::VisionMeasurements::SharedPtr vm) {
int baseline = 0;
float font_scale = 0.5;
int thickness = 2;
cv::Point topLeftCorner = cv::Point((vm->centerx - vm->width/2) * lastFrame.cols,
(vm->centery - vm->height/2) * lastFrame.rows);
cv::Point bottomRightCorner = cv::Point((vm->centerx + vm->width/2) * lastFrame.cols,
(vm->centery + vm->height/2) * lastFrame.rows);
int length = lastFrame.cols / 10;
cv::Point center = cv::Point(vm->centerx * lastFrame.cols, vm->centery * lastFrame.rows);
cv::Point endpoint = cv::Point(vm->centerx * lastFrame.cols + length * sin(vm->hde),
vm->centery * lastFrame.rows - length * cos(vm->hde));
cv_bridge::CvImage cv_msg;
cv_msg.header.frame_id = "world_ned";
cv_msg.header.stamp = this->now();
cv_msg.encoding = sensor_msgs::image_encodings::BGR8;
m.lock();
if (vm->width != 0) {
// draw rectangle
cv::rectangle(lastFrame, topLeftCorner, bottomRightCorner, cv::Scalar(50, 205, 50), 2);
//draw hde line
cv::line(lastFrame, center, endpoint, cv::Scalar(0,0,255), 3);
}
cv_msg.image = lastFrame;
img_pub->publish(cv_msg.toImageMsg());
m.unlock();
}
void fetchTSDF(const tsdf_package_msgs::msg::Tsdf::SharedPtr tsdf) {
rclcpp::Time now = clock.now();
rclcpp::Duration duration = now - last_time;
double duration_seconds = duration.seconds();
if(duration_seconds > 0){
last_time = now;
float voxel_size = tsdf->voxel_size;
sensor_msgs::msg::PointCloud2 pc;
pc.header.stamp = now;
pc.header.frame_id = "world_ned";
pc.height = 1;
pc.width = tsdf->size;
pc.is_bigendian = __BYTE_ORDER == __BIG_ENDIAN;
pc.point_step = 16;
pc.row_step = tsdf->size;
pc.is_dense = tsdf->size == 0;
pc.fields = std::vector<sensor_msgs::msg::PointField>(4);
pc.fields[0].name = "intensity";
pc.fields[0].offset = 0;
pc.fields[0].datatype = sensor_msgs::msg::PointField::FLOAT32;
pc.fields[0].count = 1;
pc.fields[1].name = "x";
pc.fields[1].offset = 4;
pc.fields[1].datatype = sensor_msgs::msg::PointField::FLOAT32;
pc.fields[1].count = 1;
pc.fields[2].name = "y";
pc.fields[2].offset = 8;
pc.fields[2].datatype = sensor_msgs::msg::PointField::FLOAT32;
pc.fields[2].count = 1;
pc.fields[3].name = "z";
pc.fields[3].offset = 12;
pc.fields[3].datatype = sensor_msgs::msg::PointField::FLOAT32;
pc.fields[3].count = 1;
pc.data.resize(pc.width * pc.point_step);
std::vector<tsdf_package_msgs::msg::Voxel> voxels = tsdf->voxels;
uint8_t* data = pc.data.data();
for (tsdf_package_msgs::msg::Voxel v : voxels){
((float*)data)[0] = v.sdf;
((float*)data)[1] = v.x;
((float*)data)[2] = v.y;
((float*)data)[3] = v.z;
data += pc.point_step;
}
tsdf_occupied_voxels_pub->publish(pc);
}
}
public:
DebugViz() : Node("debug_viz") {
pose_pub = this->create_publisher<geometry_msgs::msg::PoseStamped>("pose_out", 1);
actor_traj_pub = this->create_publisher<geometry_msgs::msg::PoseArray>("actor_traj_out", 1);
drone_traj_pub = this->create_publisher<geometry_msgs::msg::PoseArray>("drone_traj_out", 1);
ideal_traj_pub = this->create_publisher<geometry_msgs::msg::PoseArray>("ideal_traj_out", 1);
img_pub = this->create_publisher<sensor_msgs::msg::Image>("img_out", 20);
tsdf_occupied_voxels_pub = this->create_publisher<sensor_msgs::msg::PointCloud2>("tsdf_occupied_voxels", 1);
pose_sub = this->create_subscription<geometry_msgs::msg::Pose>("pose_in", 1,
std::bind(&DebugViz::fetchDronePose, this, _1));
actor_traj_sub = this->create_subscription<cinematography_msgs::msg::MultiDOFarray>("actor_traj_in", 1,
std::bind(&DebugViz::fetchActorTraj, this, _1));
drone_traj_sub = this->create_subscription<cinematography_msgs::msg::MultiDOFarray>("drone_traj_in", 1,
std::bind(&DebugViz::fetchDroneTraj, this, _1));
ideal_traj_sub = this->create_subscription<cinematography_msgs::msg::MultiDOFarray>("ideal_traj_in", 1,
std::bind(&DebugViz::fetchIdealTraj, this, _1));
img_sub = this->create_subscription<sensor_msgs::msg::Image>("img_in", 1,
std::bind(&DebugViz::fetchImage, this, _1));
vm_sub = this->create_subscription<cinematography_msgs::msg::VisionMeasurements>("vm_in", 1,
std::bind(&DebugViz::fetchVisionMeasurements, this, _1));
tsdf_occupied_voxels_sub = this->create_subscription<tsdf_package_msgs::msg::Tsdf>("tsdf", 1,
std::bind(&DebugViz::fetchTSDF, this, _1));
last_time = clock.now();
}
};
int main(int argc, char **argv) {
rclcpp::init(argc, argv);
sleep(10);
rclcpp::executors::MultiThreadedExecutor exec;
auto ros2wrapper = std::make_shared<DebugViz>();
exec.add_node(ros2wrapper);
exec.spin();
rclcpp::shutdown();
return 0;
} | 41.39823 | 116 | 0.633177 | [
"vector"
] |
4d747b9d815feed11fea09bf93bc999c801f2987 | 5,965 | cpp | C++ | external/swak/libraries/swakTopoSources/expressionToFace.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | external/swak/libraries/swakTopoSources/expressionToFace.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | external/swak/libraries/swakTopoSources/expressionToFace.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright: ICE Stroemungsfoschungs GmbH
Copyright held by original author
-------------------------------------------------------------------------------
License
This file is based on CAELUS.
CAELUS 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.
CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>.
Contributors/Copyright:
2010-2014 Bernhard F.W. Gschaider <bgschaid@ice-sf.at>
\*---------------------------------------------------------------------------*/
#include "expressionToFace.hpp"
#include "polyMesh.hpp"
#include "cellSet.hpp"
#include "Time.hpp"
#include "syncTools.hpp"
#include "addToRunTimeSelectionTable.hpp"
#include "FieldValueExpressionDriver.hpp"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
namespace CML
{
defineTypeNameAndDebug(expressionToFace, 0);
addToRunTimeSelectionTable(topoSetSource, expressionToFace, word);
addToRunTimeSelectionTable(topoSetSource, expressionToFace, istream);
}
CML::topoSetSource::addToUsageTable CML::expressionToFace::usage_
(
expressionToFace::typeName,
"\n Usage: expressionToFace <expression>\n\n"
" Select all faces for which expression evaluates to true on one and false on the other side\n\n"
);
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
void CML::expressionToFace::combine(topoSet& set, const bool add) const
{
if(Pstream::parRun()) {
WarningInFunction
<< " Does not give correct results if faces are on the processor boundary"
<< endl;
}
fvMesh mesh(set.db());
FieldValueExpressionDriver driver
(
mesh.time().timeName(),
mesh.time(),
mesh,
true, // cache stuff
true, // search in memory
true // search on disc
);
if(dict_.valid()) {
driver.readVariablesAndTables(dict_());
driver.clearVariables();
}
driver.parse(expression_);
if(!driver.isLogical()) {
FatalErrorInFunction
<< "Expression " << expression_ << " does not evaluate to a logical expression"
<< endl
<< exit(FatalError);
}
if(driver.resultIsTyp<volScalarField>(true)) {
const volScalarField &condition=driver.getResult<volScalarField>();
const labelList &own=condition.mesh().faceOwner();
const labelList &nei=condition.mesh().faceNeighbour();
Info << " Expression " << expression_
<< " evaluates to cellValue: using boundary" << endl;
for(label faceI=0;faceI<condition.mesh().nInternalFaces();faceI++)
{
if (condition[own[faceI]] != condition[nei[faceI]])
{
addOrDelete(set, faceI, add);
}
}
} else if(driver.resultIsTyp<surfaceScalarField>(true)) {
const surfaceScalarField &condition=driver.getResult<surfaceScalarField>();
forAll(condition,faceI) {
if(condition[faceI]>0) {
addOrDelete(set, faceI, add);
}
}
forAll(condition.boundaryField(),patchI) {
const surfaceScalarField::PatchFieldType &patch=
condition.boundaryField()[patchI];
label start=condition.mesh().boundaryMesh()[patchI].start();
forAll(patch,i) {
if(patch[i]>0) {
addOrDelete(set, i+start, add);
}
}
}
} else {
FatalErrorInFunction
<< "Don't know how to handle a logical field of type "
<< driver.typ()
<< endl
<< exit(FatalError);
}
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
// Construct from componenta
CML::expressionToFace::expressionToFace
(
const polyMesh& mesh,
const exprString& expression
)
:
topoSetSource(mesh),
expression_(expression)
{}
// Construct from dictionary
CML::expressionToFace::expressionToFace
(
const polyMesh& mesh,
const dictionary& dict
)
:
topoSetSource(mesh),
expression_(
dict.lookup("expression"),
dict
),
dict_(new dictionary(dict))
{}
// Construct from Istream
CML::expressionToFace::expressionToFace
(
const polyMesh& mesh,
Istream& is
)
:
topoSetSource(mesh),
expression_(
checkIs(is),
dictionary::null
)
{}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
CML::expressionToFace::~expressionToFace()
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
CML::topoSetSource::sourceType CML::expressionToFace::setType() const
{
return FACESETSOURCE;
}
void CML::expressionToFace::applyToSet
(
const topoSetSource::setAction action,
topoSet& set
) const
{
if ((action == topoSetSource::ADD) || (action == topoSetSource::NEW))
{
Info<< " Adding all elements of for which " << expression_ << " evaluates to true ..."
<< endl;
combine(set,true);
}
else if (action == topoSetSource::DELETE)
{
Info<< " Removing all elements of for which " << expression_ << " evaluates to true ..."
<< endl;
combine(set,false);
}
}
// ************************************************************************* //
| 27.488479 | 104 | 0.563621 | [
"mesh"
] |
4d74e489c40a048776cb1659ba7aa4749acfac8c | 7,751 | cpp | C++ | Core/Terrain/Fragment.cpp | marci07iq/SpaceCube | 464bc3fa1090bed273bcaa3257aebeacc4e8d3b0 | [
"MIT"
] | 2 | 2019-11-05T14:48:34.000Z | 2019-11-05T14:49:30.000Z | Core/Terrain/Fragment.cpp | marci07iq/SpaceCube | 464bc3fa1090bed273bcaa3257aebeacc4e8d3b0 | [
"MIT"
] | null | null | null | Core/Terrain/Fragment.cpp | marci07iq/SpaceCube | 464bc3fa1090bed273bcaa3257aebeacc4e8d3b0 | [
"MIT"
] | null | null | null | #include "WorldLoader.h"
Fragment::Fragment(int fx, int fy, int dim) :
_fx(fx),
_fy(fy) {
_dim = dim;
for (int i = 0; i < 4; i++) {
_neigh[i] = NULL;
}
for (int i = 0; i < COLUMN_PER_FRAGMENT; i++) {
for (int j = 0; j < COLUMN_PER_FRAGMENT; j++) {
_cols[i][j] = NULL;
}
}
}
void Fragment::link() {
Fragment* potentialNeigh = findFragment(_fx - 1, _fy, _dim);
if (potentialNeigh != NULL) {
potentialNeigh->hello(Dir_PX, this);
_neigh[Dir_MX] = potentialNeigh;
}
potentialNeigh = findFragment(_fx + 1, _fy, _dim);
if (potentialNeigh != NULL) {
potentialNeigh->hello(Dir_MX, this);
_neigh[Dir_PX] = potentialNeigh;
}
potentialNeigh = findFragment(_fx, _fy - 1, _dim);
if (potentialNeigh != NULL) {
potentialNeigh->hello(Dir_PY, this);
_neigh[Dir_MY] = potentialNeigh;
}
potentialNeigh = findFragment(_fx, _fy + 1, _dim);
if (potentialNeigh != NULL) {
potentialNeigh->hello(Dir_MY, this);
_neigh[Dir_PY] = potentialNeigh;
}
for (int i = 0; i < COLUMN_PER_FRAGMENT; i++) {
for (int j = 0; j < COLUMN_PER_FRAGMENT; j++) {
if (_cols[i][j] != NULL) {
_cols[i][j]->link();
}
}
}
}
void Fragment::hello(Directions fromDir, Fragment* fromChunk) {
if (_neigh[fromDir] != fromChunk) {
_neigh[fromDir] = fromChunk;
}
}
void Fragment::unlink() {
if (_neigh[Dir_MX] != NULL) {
_neigh[Dir_MX]->bye(Dir_PX, this);
_neigh[Dir_MX] = NULL;
}
if (_neigh[Dir_PX] != NULL) {
_neigh[Dir_PX]->bye(Dir_MX, this);
_neigh[Dir_PX] = NULL;
}
if (_neigh[Dir_MY] != NULL) {
_neigh[Dir_MY]->bye(Dir_PY, this);
_neigh[Dir_MY] = NULL;
}
if (_neigh[Dir_PY] != NULL) {
_neigh[Dir_PY]->bye(Dir_MY, this);
_neigh[Dir_PY] = NULL;
}
for (int i = 0; i < COLUMN_PER_FRAGMENT; i++) {
for (int j = 0; j < COLUMN_PER_FRAGMENT; j++) {
if (_cols[i][j] != NULL) {
_cols[i][j]->unlink();
}
}
}
}
void Fragment::bye(Directions fromDir, Fragment* fromChunk) {
_neigh[fromDir] = NULL;
}
#ifdef M_SERVER
void Fragment::prepareFile(fstream & reg, int & fileSize) {
fileSize = 4 * 2 * FRAGMENT_PER_REGION*FRAGMENT_PER_REGION;
char* res = new char[fileSize];
for (int i = 0; i < fileSize; i++) {
res[i] = 0;
}
reg.write(res, fileSize);
delete[] res;
}
vector<pair<int, int>> loadHeader(fstream & reg) {
reg.seekg(0);
vector<pair<int, int>> res(COLUMN_PER_FRAGMENT * COLUMN_PER_FRAGMENT);
for (int i = 0; i < COLUMN_PER_FRAGMENT * COLUMN_PER_FRAGMENT; i++) {
reg.read(reinterpret_cast<char *>(&res[i].first), sizeof(res[i].first));
reg.read(reinterpret_cast<char *>(&res[i].second), sizeof(res[i].second));
}
return res;
}
int allocatePos(vector<pair<int, int>>& header, int len) {
map<int, int> segs;
segs[0] = 1;
segs[COLUMN_PER_FRAGMENT * COLUMN_PER_FRAGMENT * 8] = -1;
for (int i = 0; i < COLUMN_PER_FRAGMENT * COLUMN_PER_FRAGMENT; i++) {
segs[header[i].first]++;
segs[header[i].first + header[i].second]--;
}
int lastid = 0;
int in = 0;
for (auto&& it : segs) {
if(in == 0) {
if (it.first - lastid > len) {
return lastid;
}
}
if (in != 0) {
lastid = it.first;
}
in += it.second;
}
return lastid;
}
void Fragment::save() {
int rx = floorDiv(_fx, FRAGMENT_PER_REGION);
int ry = floorDiv(_fy, FRAGMENT_PER_REGION);
int lfx = modulo(_fx, FRAGMENT_PER_REGION);
int lfy = modulo(_fy, FRAGMENT_PER_REGION);
cout << "Saving frag " << _fx << " " << _fy << endl;
cout << "File " << rx << " " << ry << endl;
cout << "Fragment " << lfx << " " << lfy << endl;
string fname = "dim_" + to_string(_dim) + "_" + to_string(rx) + "_" + to_string(ry) + ".map";
fstream reg;
//Read file size
reg.open(fname, ios::in | ios::out | ios::binary | ios::app);
reg.seekg(0, ios::end);
int fileSize = reg.tellg();
reg.close();
reg.open(fname, ios::in | ios::out | ios::binary);
//Create empty header if needed
if (fileSize <= 0) {
prepareFile(reg, fileSize);
}
//Encode data
DataPair* in = new DataPair(BLOCK_BYTES * COLUMN_PER_FRAGMENT*COLUMN_PER_FRAGMENT*CHUNK_PER_COLUMN*BLOCK_PER_CHUNK*BLOCK_PER_CHUNK*BLOCK_PER_CHUNK);
for (int ci = 0; ci < COLUMN_PER_FRAGMENT; ci++) {
for (int cj = 0; cj < COLUMN_PER_FRAGMENT; cj++) {
for (int ck = 0; ck < CHUNK_PER_COLUMN; ck++) {
for (int bi = 0; bi < BLOCK_PER_CHUNK; bi++) {
for (int bj = 0; bj < BLOCK_PER_CHUNK; bj++) {
for (int bk = 0; bk < BLOCK_PER_CHUNK; bk++) {
int rawid = bk + BLOCK_PER_CHUNK * (bj + BLOCK_PER_CHUNK * (bi + BLOCK_PER_CHUNK * (ck + CHUNK_PER_COLUMN * (cj + COLUMN_PER_FRAGMENT * (ci)))));
rawid *= BLOCK_BYTES;
writeBlock(in->_data, rawid, _cols[ci][cj]->getChunk(ck)->_blocks[bi][bj][bk]);
}
}
}
}
}
}
//Compress data
DataPair* out;
compress(in, &out);
delete in;
//0 out this fragment data
reg.seekp(8 * (lfx*FRAGMENT_PER_REGION + lfy));
for(int i = 0; i < 8; i++) {
reg.write("", 1);
}
//Allocate new position
vector<pair<int, int>> header = loadHeader(reg);
int len = out->_len;
int pos = allocatePos(header, len);
cout << "Len: " << len << ", Pos: " << pos << endl;
//Set new position
reg.seekp(8 * (lfx*FRAGMENT_PER_REGION + lfy));
reg.write(reinterpret_cast<char *>(&pos), sizeof(pos));
reg.write(reinterpret_cast<char *>(&len), sizeof(len));
//Write data
reg.seekp(pos);
reg.write(reinterpret_cast<char*>(out->_data), len);
//Cleanup
delete out;
reg.close();
}
void Fragment::load() {
int rx = floorDiv(_fx, FRAGMENT_PER_REGION);
int ry = floorDiv(_fy, FRAGMENT_PER_REGION);
int lfx = modulo(_fx, FRAGMENT_PER_REGION);
int lfy = modulo(_fy, FRAGMENT_PER_REGION);
string fname = "dim_" + to_string(_dim) + "_" + to_string(rx) + "_" + to_string(ry) + ".map";
ifstream reg(fname, ios::in | ios::binary);
//If file exists
if (reg.good()) {
//Load header data
uint32_t pos, len;
reg.seekg(8 * (lfx*FRAGMENT_PER_REGION + lfy));
reg.read(reinterpret_cast<char *>(&pos), sizeof(pos));
reg.read(reinterpret_cast<char *>(&len), sizeof(len));
//If exists, load
if (pos != 0) {
//Read compressed
DataPair* in = new DataPair(len);
reg.seekg(pos);
reg.read(reinterpret_cast<char*>(in->_data), in->_len);
//Decode
DataPair* out;
decompress(in, &out);
delete in;
//Write blocks
for (int ci = 0; ci < COLUMN_PER_FRAGMENT; ci++) {
for (int cj = 0; cj < COLUMN_PER_FRAGMENT; cj++) {
ChunkCol* ncc = new ChunkCol(_fx * CHUNK_PER_COLUMN + ci, _fy * CHUNK_PER_COLUMN + cj, this);
for (int ck = 0; ck < CHUNK_PER_COLUMN; ck++) {
Chunk* nc = new Chunk(COLUMN_PER_FRAGMENT*_fx + ci, COLUMN_PER_FRAGMENT*_fy + cj, ck, ncc);
for (int bi = 0; bi < BLOCK_PER_CHUNK; bi++) {
for (int bj = 0; bj < BLOCK_PER_CHUNK; bj++) {
for (int bk = 0; bk < BLOCK_PER_CHUNK; bk++) {
int rawid = bk + BLOCK_PER_CHUNK * (bj + BLOCK_PER_CHUNK * (bi + BLOCK_PER_CHUNK * (ck + CHUNK_PER_COLUMN * (cj + COLUMN_PER_FRAGMENT * (ci)))));
rawid *= BLOCK_BYTES;
readBlock(out->_data, rawid, nc->_blocks[bi][bj][bk]);
}
}
}
ncc->setChunk(nc, ck);
}
setChunkCol(ci, cj, ncc);
}
}
//Clean up
delete out;
link();
reg.close();
return;
}
}
//Clean up
reg.close();
Mapgen gen;
gen.res = this;
gen.dim = 0;
gen.generateFragment(_fx, _fy);
save();
link();
}
#endif
| 27.981949 | 163 | 0.583151 | [
"vector"
] |
4d80a0ffcf7891a9293f46b1645e36f9ed2ddb02 | 13,946 | cpp | C++ | Code/Engine/WindowsMixedReality/HolographicSpace.cpp | fereeh/ezEngine | 14e46cb2a1492812888602796db7ddd66e2b7110 | [
"MIT"
] | 1 | 2021-06-23T14:44:02.000Z | 2021-06-23T14:44:02.000Z | Code/Engine/WindowsMixedReality/HolographicSpace.cpp | fereeh/ezEngine | 14e46cb2a1492812888602796db7ddd66e2b7110 | [
"MIT"
] | null | null | null | Code/Engine/WindowsMixedReality/HolographicSpace.cpp | fereeh/ezEngine | 14e46cb2a1492812888602796db7ddd66e2b7110 | [
"MIT"
] | null | null | null | #includde <WindowsMixedRealityPCH.h>
#include <WindowsMixedReality/HolographicSpace.h>
#include <WindowsMixedReality/SpatialLocationService.h>
#include <WindowsMixedReality/SpatialReferenceFrame.h>
#include <WindowsMixedReality/Graphics/MixedRealityCamera.h>
#include <Foundation/Configuration/CVar.h>
//#include <GameEngine/GameApplication/GameApplication.h>
#include <RendererFoundation/Descriptors/Descriptors.h>
#include <WindowsMixedReality/Graphics/MixedRealityDX11Device.h>
#include <RendererDX11/Device/DeviceDX11.h>
#include <Core/Graphics/Camera.h>
#include <windows.graphics.holographic.h>
#include <windows.system.profile.h>
#include <wrl/event.h>
EZ_IMPLEMENT_SINGLETON(ezWindowsHolographicSpace);
ezWindowsHolographicSpace::ezWindowsHolographicSpace()
: m_SingletonRegistrar(this)
{
if (FAILED(ABI::Windows::Foundation::GetActivationFactory(HStringReference(RuntimeClass_Windows_Graphics_Holographic_HolographicSpace).Get(), &m_pHolographicSpaceStatics)))
{
ezLog::Error("Failed to query HolographicSpace activation factory. Windows holographic won't be supported!");
}
}
ezWindowsHolographicSpace::~ezWindowsHolographicSpace()
{
DeInit();
}
ezResult ezWindowsHolographicSpace::InitForMainCoreWindow()
{
EZ_LOG_BLOCK("ezWindowsHolographicSpace::InitForMainCoreWindow");
if (!m_pHolographicSpaceStatics)
return EZ_FAILURE;
DeInit();
// Create holographic space from core window
{
ComPtr<ABI::Windows::UI::Core::ICoreWindow> pCoreWindow;
{
ComPtr<ABI::Windows::ApplicationModel::Core::ICoreImmersiveApplication> application;
EZ_HRESULT_TO_FAILURE(ABI::Windows::Foundation::GetActivationFactory(HStringReference(RuntimeClass_Windows_ApplicationModel_Core_CoreApplication).Get(), &application));
ComPtr<ABI::Windows::ApplicationModel::Core::ICoreApplicationView> mainView;
EZ_HRESULT_TO_FAILURE(application->get_MainView(&mainView));
EZ_HRESULT_TO_FAILURE(mainView->get_CoreWindow(&pCoreWindow));
}
EZ_HRESULT_TO_FAILURE_LOG(m_pHolographicSpaceStatics->CreateForCoreWindow(pCoreWindow.Get(), &m_pHolographicSpace));
}
// Register to camera added/removed
{
using OnCameraAdded = __FITypedEventHandler_2_Windows__CGraphics__CHolographic__CHolographicSpace_Windows__CGraphics__CHolographic__CHolographicSpaceCameraAddedEventArgs;
EZ_HRESULT_TO_FAILURE_LOG(m_pHolographicSpace->add_CameraAdded(Callback<OnCameraAdded>(this, &ezWindowsHolographicSpace::OnCameraAdded).Get(), &m_eventRegistrationOnCameraAdded));
using OnCameraRemoved = __FITypedEventHandler_2_Windows__CGraphics__CHolographic__CHolographicSpace_Windows__CGraphics__CHolographic__CHolographicSpaceCameraRemovedEventArgs;
EZ_HRESULT_TO_FAILURE_LOG(m_pHolographicSpace->add_CameraRemoved(Callback<OnCameraRemoved>(this, &ezWindowsHolographicSpace::OnCameraRemoved).Get(), &m_eventRegistrationOnCameraRemoved));
}
// Setup locator
{
ComPtr<ABI::Windows::Perception::Spatial::ISpatialLocatorStatics> pSpatialLocatorStatics;
EZ_HRESULT_TO_FAILURE_LOG(ABI::Windows::Foundation::GetActivationFactory(HStringReference(RuntimeClass_Windows_Perception_Spatial_SpatialLocator).Get(), &pSpatialLocatorStatics));
ComPtr<ABI::Windows::Perception::Spatial::ISpatialLocator> pDefaultSpatialLocator;
EZ_HRESULT_TO_FAILURE_LOG(pSpatialLocatorStatics->GetDefault(&pDefaultSpatialLocator));
m_pLocationService = EZ_DEFAULT_NEW(ezWindowsSpatialLocationService, pDefaultSpatialLocator);
}
DisableMultiThreadedRendering();
ezLog::Success("Initialized new holographic space for main window!");
return EZ_SUCCESS;
}
// static
void ezWindowsHolographicSpace::DisableMultiThreadedRendering()
{
ezCVar* pCVar = ezCVar::FindCVarByName("r_Multithreading");
if (pCVar != nullptr && pCVar->GetType() == ezCVarType::Bool)
{
ezCVarBool* pBoolVar = static_cast<ezCVarBool*>(pCVar);
if (pBoolVar->GetValue(ezCVarValue::Current))
{
*pBoolVar = false;
ezLog::Info("Disabling multi-threaded rendering, to reduce rendering lag on HoloLens");
}
}
}
void ezWindowsHolographicSpace::DeInit()
{
if (!m_pHolographicSpaceStatics)
return;
for (auto pCamera : m_cameras)
{
EZ_DEFAULT_DELETE(pCamera);
}
m_cameras.Clear();
m_pLocationService.Reset();
if (m_pHolographicSpace)
{
m_pHolographicSpace->remove_CameraAdded(m_eventRegistrationOnCameraAdded);
m_pHolographicSpace->remove_CameraRemoved(m_eventRegistrationOnCameraRemoved);
m_pHolographicSpace = nullptr;
}
}
/*
// TODO: Evaluate if and how to expose this.
// WinRT api has a bit of weirdness here:
// "If IsAvailable is false because the user has not yet set up their holographic headset, calling CreateForCoreWindow anyway will guide them through the setup flow."
bool ezWindowsHolographicSpace::IsSupported() const
{
if (!m_pHolographicSpaceStatics)
return false;
ComPtr<ABI::Windows::Graphics::Holographic::IHolographicSpaceStatics2> pStatics2;
if (FAILED(m_pHolographicSpaceStatics.As(&pStatics2)))
{
// If we have not access to statics to we're running pre Creators Update windows!
// In this case the support is determined by the device type.
}
else
{
boolean available = FALSE;
pStatics2->get_IsAvailable(&available);
return available == TRUE;
}
}
*/
bool ezWindowsHolographicSpace::IsAvailable() const
{
if (!m_pHolographicSpaceStatics)
return false;
#if EZ_WINRT_SDK_VERSION > EZ_WIN_SDK_VERSION_10_RS1
ComPtr<ABI::Windows::Graphics::Holographic::IHolographicSpaceStatics2> pStatics2;
if (FAILED(m_pHolographicSpaceStatics.As(&pStatics2)))
{
#endif
// If we have no access to statics, we are running pre Creators Update windows!
// In this case a headset is exactly then available if we're on HoloLens!
ComPtr<ABI::Windows::System::Profile::IAnalyticsInfoStatics> pAnalyticsStatics;
if (FAILED(ABI::Windows::Foundation::GetActivationFactory(HStringReference(RuntimeClass_Windows_System_Profile_AnalyticsInfo).Get(), &pAnalyticsStatics)))
return false;
ComPtr<ABI::Windows::System::Profile::IAnalyticsVersionInfo> pAnalyticsVersionInfo;
if (FAILED(pAnalyticsStatics->get_VersionInfo(&pAnalyticsVersionInfo)))
return false;
HString deviceFamily;
if (FAILED(pAnalyticsVersionInfo->get_DeviceFamily(deviceFamily.GetAddressOf())))
return false;
return ezStringUtils::IsEqual(ezStringUtf8(deviceFamily).GetData(), "Windows.Holographic");
#if EZ_WINRT_SDK_VERSION > EZ_WIN_SDK_VERSION_10_RS1
}
else
{
boolean available = FALSE;
pStatics2->get_IsAvailable(&available);
return available == TRUE;
}
#endif
}
ComPtr<ABI::Windows::Graphics::Holographic::IHolographicFrame> ezWindowsHolographicSpace::StartNewHolographicFrame()
{
EZ_ASSERT_DEBUG(m_pHolographicSpace, "There is no holographic space.");
// Create holographic frame.
ComPtr<ABI::Windows::Graphics::Holographic::IHolographicFrame> pHolographicFrame;
HRESULT result = m_pHolographicSpace->CreateNextFrame(pHolographicFrame.GetAddressOf());
if (FAILED(result))
{
ezLog::Error("Failed to create holographic frame: '{0}'", ezHRESULTtoString(result));
return nullptr;
}
// Use it to update all our cameras.
UpdateCameraPoses(pHolographicFrame);
ComPtr<ABI::Windows::Graphics::Holographic::IHolographicFramePrediction> pPrediction;
pHolographicFrame->get_CurrentPrediction(&pPrediction);
pPrediction->get_Timestamp(&m_pPredictionTimestamp);
return std::move(pHolographicFrame);
}
void ezWindowsHolographicSpace::ProcessAddedRemovedCameras()
{
ezLock<ezMutex> lock(m_cameraQueueMutex);
// TODO: assert no dx11 frame running
// Process removals.
for (const auto& pCamera : m_pendingCameraRemovals)
{
for (ezUInt32 i = 0; i < m_cameras.GetCount(); ++i)
{
if (m_cameras[i]->GetInternalMixedRealityCamera() == pCamera.Get())
{
m_cameraRemovedEvent.Broadcast(*m_cameras[i]);
EZ_DEFAULT_DELETE(m_cameras[i]);
m_cameras.RemoveAt(i);
break;
}
}
}
m_pendingCameraRemovals.Clear();
// Process additions.
if (!m_pendingCameraAdditions.IsEmpty())
{
for (const auto& cameraAddition : m_pendingCameraAdditions)
{
m_cameras.PushBack(EZ_DEFAULT_NEW(ezWindowsMixedRealityCamera, cameraAddition.m_pCamera));
cameraAddition.m_pDeferral->Complete();
}
// A lot of system can't work with camera/swapchain that doesn't have an actual backbuffer.
// Since we only get this data with a frame, we start and end a dummy holographic frame before we fire added events.
//
// In the worst case this gives a tiny hiccup for all cameras every time a camera was added.
// What we get for this, however, in return, are valid camera poses and backbuffers for all engine systems that rely on them.
StartNewHolographicFrame();
// Fire added events for all new cameras.
for (auto i = m_cameras.GetCount() - m_pendingCameraAdditions.GetCount(); i < m_cameras.GetCount(); ++i)
m_cameraAddedEvent.Broadcast(*m_cameras[i]);
}
m_pendingCameraAdditions.Clear();
}
ezResult ezWindowsHolographicSpace::SynchronizeCameraPrediction(ezCamera& inout_Camera)
{
ezArrayPtr<ezWindowsMixedRealityCamera*> holoCameras = GetCameras();
if (holoCameras.IsEmpty())
return EZ_FAILURE;
EZ_ASSERT_DEV(inout_Camera.GetCameraMode() == ezCameraMode::Stereo, "Incorrect camera mode. Must be 'Stereo'");
ezWindowsMixedRealityCamera* pHoloCamera = holoCameras[0];
const ezRectFloat viewport = pHoloCamera->GetViewport();
// compensate for the negated forward vector in the view transform below
ezMat4 projLeft = pHoloCamera->GetProjectionLeft();
ezMat4 projRight = pHoloCamera->GetProjectionRight();
projLeft.SetColumn(2, -projLeft.GetColumn(2));
projRight.SetColumn(2, -projRight.GetColumn(2));
inout_Camera.SetStereoProjection(projLeft, projRight, viewport.width / viewport.height);
ezMat4 mViewTransformLeft, mViewTransformRight;
EZ_SUCCEED_OR_RETURN(pHoloCamera->GetViewTransforms(*GetDefaultReferenceFrame(), mViewTransformLeft, mViewTransformRight));
// Forward dir is in row 2
// Windows holographic uses a right handed coordinate system (OpenGL style)
// ez uses a left handed coordinate system
// need to negate the forward direction
mViewTransformLeft.SetRow(2, -mViewTransformLeft.GetRow(2));
mViewTransformRight.SetRow(2, -mViewTransformRight.GetRow(2));
inout_Camera.SetViewMatrix(mViewTransformLeft, ezCameraEye::Left);
inout_Camera.SetViewMatrix(mViewTransformRight, ezCameraEye::Right);
return EZ_SUCCESS;
}
ezResult ezWindowsHolographicSpace::UpdateCameraPoses(const ComPtr<ABI::Windows::Graphics::Holographic::IHolographicFrame>& pHolographicFrame)
{
// Get prediction.
ComPtr<ABI::Windows::Graphics::Holographic::IHolographicFramePrediction> pPrediction;
EZ_HRESULT_TO_FAILURE(pHolographicFrame->get_CurrentPrediction(pPrediction.GetAddressOf()));
// Get camera poses.
ComPtr<ABI::Windows::Foundation::Collections::IVectorView<ABI::Windows::Graphics::Holographic::HolographicCameraPose*>> pCameraPoses;
EZ_HRESULT_TO_FAILURE(pPrediction->get_CameraPoses(&pCameraPoses));
// Update camera our cameras.
using IPose = ABI::Windows::Graphics::Holographic::IHolographicCameraPose;
ezUwpUtils::ezWinRtIterateIVectorView<IPose*>(pCameraPoses, [this, &pHolographicFrame](UINT, IPose* pPose)
{
ComPtr<ABI::Windows::Graphics::Holographic::IHolographicCamera> pCurrentHoloCamera;
if (FAILED(pPose->get_HolographicCamera(pCurrentHoloCamera.GetAddressOf())))
return true;
// There will never be a lot of cameras, so just look through all our cameras to pick the corresponding one.
for (auto pCamera : m_cameras)
{
if (pCamera->GetInternalMixedRealityCamera() == pCurrentHoloCamera.Get())
{
ComPtr<ABI::Windows::Graphics::Holographic::IHolographicCameraRenderingParameters> pCameraRenderingParameters;
EZ_HRESULT_TO_LOG(pHolographicFrame->GetRenderingParameters(pPose, pCameraRenderingParameters.GetAddressOf()));
pCamera->UpdatePose(pPose, pCameraRenderingParameters.Get());
break;
}
}
return true;
});
return EZ_SUCCESS;
}
HRESULT ezWindowsHolographicSpace::OnCameraAdded(ABI::Windows::Graphics::Holographic::IHolographicSpace* holographicSpace, ABI::Windows::Graphics::Holographic::IHolographicSpaceCameraAddedEventArgs* args)
{
ezLock<ezMutex> lock(m_cameraQueueMutex);
auto& pendingAddition = m_pendingCameraAdditions.ExpandAndGetRef();
EZ_HRESULT_TO_FAILURE_LOG(args->get_Camera(pendingAddition.m_pCamera.GetAddressOf()));
EZ_HRESULT_TO_FAILURE_LOG(args->GetDeferral(pendingAddition.m_pDeferral.GetAddressOf()));
return S_OK;
}
HRESULT ezWindowsHolographicSpace::OnCameraRemoved(ABI::Windows::Graphics::Holographic::IHolographicSpace* holographicSpace, ABI::Windows::Graphics::Holographic::IHolographicSpaceCameraRemovedEventArgs* args)
{
ezLock<ezMutex> lock(m_cameraQueueMutex);
ComPtr<ABI::Windows::Graphics::Holographic::IHolographicCamera> pCamera;
EZ_HRESULT_TO_FAILURE_LOG(args->get_Camera(pCamera.GetAddressOf()));
m_pendingCameraRemovals.PushBack(std::move(pCamera));
return S_OK;
}
void ezWindowsHolographicSpace::CreateDefaultReferenceFrame()
{
if (m_pDefaultReferenceFrame == nullptr)
{
auto pDefRefFrame = GetSpatialLocationService().CreateStationaryReferenceFrame_CurrentLocation();
ezWindowsHolographicSpace::GetSingleton()->SetDefaultReferenceFrame(std::move(pDefRefFrame));
}
}
void ezWindowsHolographicSpace::SetDefaultReferenceFrame(ezUniquePtr<ezWindowsSpatialReferenceFrame>&& refFrame)
{
EZ_ASSERT_DEV(refFrame.Borrow() != nullptr, "Invalid reference frame");
m_pDefaultReferenceFrame = std::move(refFrame);
}
const ezWindowsSpatialReferenceFrame* ezWindowsHolographicSpace::GetDefaultReferenceFrame() const
{
return m_pDefaultReferenceFrame.Borrow();
}
| 36.796834 | 208 | 0.777284 | [
"vector",
"transform"
] |
4d85ee10c9f347b7fd33b34c83811a3b6520359a | 748 | cpp | C++ | 1001-1100/1019-Next Greater Node In Linked List/1019-Next Greater Node In Linked List.cpp | jiadaizhao/LeetCode | 4ddea0a532fe7c5d053ffbd6870174ec99fc2d60 | [
"MIT"
] | 49 | 2018-05-05T02:53:10.000Z | 2022-03-30T12:08:09.000Z | 1001-1100/1019-Next Greater Node In Linked List/1019-Next Greater Node In Linked List.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 11 | 2017-12-15T22:31:44.000Z | 2020-10-02T12:42:49.000Z | 1001-1100/1019-Next Greater Node In Linked List/1019-Next Greater Node In Linked List.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 28 | 2017-12-05T10:56:51.000Z | 2022-01-26T18:18:27.000Z | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> nextLargerNodes(ListNode* head) {
vector<int> vals;
while (head) {
vals.push_back(head->val);
head = head->next;
}
vector<int> result(vals.size());
stack<int> St;
for (int i = vals.size() - 1; i >= 0; --i) {
while (!St.empty() && St.top() <= vals[i]) {
St.pop();
}
if (St.size()) {
result[i] = St.top();
}
St.push(vals[i]);
}
return result;
}
};
| 22.666667 | 56 | 0.42246 | [
"vector"
] |
4d85fed07128dfac25c277790cbe1b3094db76ba | 913 | cpp | C++ | nav/attitude.cpp | tussedrotten/sensor-fusion-example | fa1c21e0c5dd8387bc67773a1343f1bf1e0f676a | [
"BSD-3-Clause"
] | 1 | 2021-04-23T10:00:02.000Z | 2021-04-23T10:00:02.000Z | nav/attitude.cpp | tussedrotten/sensor-fusion-example | fa1c21e0c5dd8387bc67773a1343f1bf1e0f676a | [
"BSD-3-Clause"
] | null | null | null | nav/attitude.cpp | tussedrotten/sensor-fusion-example | fa1c21e0c5dd8387bc67773a1343f1bf1e0f676a | [
"BSD-3-Clause"
] | 1 | 2021-10-04T12:40:47.000Z | 2021-10-04T12:40:47.000Z | #include "attitude.h"
#include "Eigen/Geometry"
namespace nav
{
Attitude::Attitude()
: x_rot{}
, y_rot{}
, z_rot{}
{ }
Attitude::Attitude(double x_angle, double y_angle, double z_angle)
: x_rot{x_angle}
, y_rot{y_angle}
, z_rot{z_angle}
{ }
Eigen::Quaterniond Attitude::toQuaternion() const
{
return Eigen::AngleAxisd(z_rot, Eigen::Vector3d::UnitZ()) *
Eigen::AngleAxisd(y_rot, Eigen::Vector3d::UnitY()) *
Eigen::AngleAxisd(x_rot, Eigen::Vector3d::UnitX());
}
Sophus::SO3d Attitude::toSO3() const
{
return Sophus::SO3d(toQuaternion());
}
double& Attitude::roll()
{
return x_rot;
}
const double& Attitude::roll() const
{
return x_rot;
}
double& Attitude::pitch()
{
return y_rot;
}
const double& Attitude::pitch() const
{
return y_rot;
}
double& Attitude::heading()
{
return z_rot;
}
const double& Attitude::heading() const
{
return z_rot;
}
}
| 14.492063 | 66 | 0.656079 | [
"geometry"
] |
4d9a0be2049c0b3e753d7ef6b00d3dcb332e69ac | 12,650 | cxx | C++ | alg/teca_valid_value_mask.cxx | LBL-EESA/TECA | 63923b8a12914f3758dc9525239bc48cd8864b39 | [
"BSD-3-Clause-LBNL"
] | 34 | 2017-03-28T14:22:25.000Z | 2022-01-23T05:02:25.000Z | alg/teca_valid_value_mask.cxx | LBL-EESA/TECA | 63923b8a12914f3758dc9525239bc48cd8864b39 | [
"BSD-3-Clause-LBNL"
] | 476 | 2016-11-28T18:06:06.000Z | 2022-01-25T05:31:42.000Z | alg/teca_valid_value_mask.cxx | LBL-EESA/TECA | 63923b8a12914f3758dc9525239bc48cd8864b39 | [
"BSD-3-Clause-LBNL"
] | 19 | 2017-04-25T18:15:04.000Z | 2020-11-28T18:16:05.000Z | #include "teca_valid_value_mask.h"
#include "teca_mesh.h"
#include "teca_array_collection.h"
#include "teca_variant_array.h"
#include "teca_metadata.h"
#include "teca_array_attributes.h"
#include "teca_coordinate_util.h"
#include "teca_mpi.h"
#include <algorithm>
#include <iostream>
#include <string>
#include <set>
#include <cmath>
#include <limits>
#if defined(TECA_HAS_BOOST)
#include <boost/program_options.hpp>
#endif
namespace
{
bool is_mask_array(const std::string &array)
{
size_t n = array.size();
size_t pos = n - 6;
if ((n < 6) || (strncmp(array.c_str() + pos, "_valid", 6) != 0))
return false;
return true;
}
}
//#define TECA_DEBUG
// --------------------------------------------------------------------------
teca_valid_value_mask::teca_valid_value_mask() :
mask_arrays(), enable_valid_range(0)
{
this->set_number_of_input_connections(1);
this->set_number_of_output_ports(1);
}
// --------------------------------------------------------------------------
teca_valid_value_mask::~teca_valid_value_mask()
{}
#if defined(TECA_HAS_BOOST)
// --------------------------------------------------------------------------
void teca_valid_value_mask::get_properties_description(
const std::string &prefix, options_description &global_opts)
{
options_description opts("Options for "
+ (prefix.empty()?"teca_valid_value_mask":prefix));
opts.add_options()
TECA_POPTS_MULTI_GET(std::vector<std::string>,
prefix, mask_arrays,
"A list of arrays to compute a mask for.")
TECA_POPTS_GET(int, prefix, enable_valid_range,
"If set non-zero vald_range, valid_min, and valid_max attributes"
" would be used if there is no _FillValue attribute.")
;
this->teca_algorithm::get_properties_description(prefix, opts);
global_opts.add(opts);
}
// --------------------------------------------------------------------------
void teca_valid_value_mask::set_properties(
const std::string &prefix, variables_map &opts)
{
this->teca_algorithm::set_properties(prefix, opts);
TECA_POPTS_SET(opts, std::vector<std::string>, prefix, mask_arrays)
TECA_POPTS_SET(opts, int, prefix, enable_valid_range)
}
#endif
// --------------------------------------------------------------------------
teca_metadata teca_valid_value_mask::get_output_metadata(
unsigned int port,
const std::vector<teca_metadata> &input_md)
{
#ifdef TECA_DEBUG
std::cerr << teca_parallel_id()
<< "teca_valid_value_mask::get_output_metadata" << std::endl;
#endif
(void)port;
// get the list of available variables and their attriibutes
teca_metadata out_md(input_md[0]);
std::vector<std::string> variables(this->mask_arrays);
if (variables.empty() && out_md.get("variables", variables))
{
TECA_FATAL_ERROR("Failed to get the list of variables")
return teca_metadata();
}
teca_metadata attributes;
if (out_md.get("attributes", attributes))
{
TECA_FATAL_ERROR("Failed to get the array attributes")
return teca_metadata();
}
// for each mask array we might generate, report that it is available and
// supply attributes to enable the CF writer.
size_t n_arrays = variables.size();
for (size_t i = 0; i < n_arrays; ++i)
{
const std::string &array_name = variables[i];
teca_metadata array_atts;
if (attributes.get(array_name, array_atts))
{
// this could be reported as an error or a warning but unless this
// becomes problematic quietly ignore it
continue;
}
// get the centering and size from the array
unsigned int centering = 0;
array_atts.get("centering", centering);
unsigned long size = 0;
array_atts.get("size", size);
// construct attributes
teca_array_attributes mask_atts(
teca_variant_array_code<char>::get(),
centering, size, "none", "", "valid value mask");
std::string mask_name = array_name + "_valid";
// update attributes
attributes.set(mask_name, (teca_metadata)mask_atts);
// add to the list of available variables
out_md.append("variables", mask_name);
}
// update the output metadata
out_md.set("attributes", attributes);
return out_md;
}
// --------------------------------------------------------------------------
std::vector<teca_metadata> teca_valid_value_mask::get_upstream_request(
unsigned int port,
const std::vector<teca_metadata> &input_md,
const teca_metadata &request)
{
#ifdef TECA_DEBUG
std::cerr << teca_parallel_id()
<< "teca_valid_value_mask::get_output_metadata" << std::endl;
#endif
(void)port;
(void)input_md;
std::vector<teca_metadata> up_reqs;
// copy the incoming request to preserve the downstream
// requirements and add the arrays we need
teca_metadata req(request);
// get the requested arrays. pass up only those that we don't generate.
std::vector<std::string> arrays;
req.get("arrays", arrays);
std::set<std::string> arrays_up;
int n_arrays = arrays.size();
for (int i = 0; i < n_arrays; ++i)
{
const std::string &array = arrays[i];
if (::is_mask_array(array))
{
// remove _valid and request the base array
arrays_up.insert(array.substr(0, array.size()-6));
}
else
{
// not ours, pass through
arrays_up.insert(array);
}
}
// request explcitly named arrays
if (!this->mask_arrays.empty())
{
arrays_up.insert(this->mask_arrays.begin(),
this->mask_arrays.end());
}
// update the request
req.set("arrays", arrays_up);
up_reqs.push_back(req);
return up_reqs;
}
// --------------------------------------------------------------------------
const_p_teca_dataset teca_valid_value_mask::execute(
unsigned int port,
const std::vector<const_p_teca_dataset> &input_data,
const teca_metadata &request)
{
#ifdef TECA_DEBUG
std::cerr << teca_parallel_id() << "teca_valid_value_mask::execute" << std::endl;
#endif
(void)port;
int rank = 0;
#if defined(TECA_HAS_MPI)
MPI_Comm comm = this->get_communicator();
int is_init = 0;
MPI_Initialized(&is_init);
if (is_init)
MPI_Comm_rank(comm, &rank);
#endif
// get the input mesh
const_p_teca_mesh in_mesh =
std::dynamic_pointer_cast<const teca_mesh>(input_data[0]);
if (!in_mesh)
{
TECA_FATAL_ERROR("Empty input dataset or not a teca_mesh")
return nullptr;
}
// allocate the output
p_teca_mesh out_mesh = std::static_pointer_cast<teca_mesh>
(std::const_pointer_cast<teca_mesh>(in_mesh)->new_shallow_copy());
// get the arrays to process
std::vector<std::string> tmp = this->mask_arrays;
if (tmp.empty())
{
request.get("arrays", tmp);
}
std::vector<std::string> arrays;
int n_arrays = tmp.size();
for (int i = 0; i < n_arrays; ++i)
{
const std::string &array = tmp[i];
if (::is_mask_array(array))
{
arrays.push_back(array.substr(0, array.size()-6));
}
}
// get the array attributes, the fill value controls will be found here
teca_metadata &md = out_mesh->get_metadata();
teca_metadata attributes;
if (md.get("attributes", attributes))
{
TECA_FATAL_ERROR("Failed to get the array attributes")
return nullptr;
}
// for each array generate the mask
n_arrays = arrays.size();
for (int i = 0; i < n_arrays; ++i)
{
const std::string &array_name = arrays[i];
// get the attributes
teca_metadata array_atts;
if (attributes.get(array_name, array_atts))
{
TECA_FATAL_ERROR("The mask for array \"" << array_name
<< "\" not computed. The array has no attributes")
return nullptr;
}
// get the centering
unsigned int centering = 0;
if (array_atts.get("centering", centering))
{
TECA_FATAL_ERROR("Mask for array \"" << array_name << "\" not computed."
" Attributes are missing centering metadata")
return nullptr;
}
p_teca_array_collection arrays = out_mesh->get_arrays(centering);
if (!arrays)
{
TECA_FATAL_ERROR("Mask for array \"" << array_name << "\" not computed."
" Failed to get the array collection with centering " << centering)
return nullptr;
}
// get the input array
p_teca_variant_array array = arrays->get(array_name);
if (!array)
{
TECA_FATAL_ERROR("Mask for array \"" << array_name << "\" not computed."
" No array named \"" << array_name << "\"")
return nullptr;
}
TEMPLATE_DISPATCH(teca_variant_array_impl,
array.get(),
// look for a _FillValue
bool have_fill_value = false;
NT fill_value = std::numeric_limits<NT>::max();
have_fill_value = ((array_atts.get("_FillValue", fill_value) == 0) ||
(array_atts.get("missing_value", fill_value) == 0));
// look for some combination of valid rnage attributes.
bool have_valid_range = false;
bool have_valid_min = false;
bool have_valid_max = false;
NT valid_range[2];
valid_range[0] = std::numeric_limits<NT>::lowest();
valid_range[1] = std::numeric_limits<NT>::max();
if (this->enable_valid_range)
{
have_valid_range = !have_fill_value &&
(array_atts.get("valid_range", valid_range, 2) == 0);
have_valid_min = !have_fill_value && !have_valid_range &&
(array_atts.get("valid_min", valid_range[0]) == 0);
have_valid_max = !have_fill_value && !have_valid_range &&
(array_atts.get("valid_max", valid_range[1]) == 0);
}
// get a pointer to the values
const NT *p_array = static_cast<TT*>(array.get())->get();
size_t n_elem = array->size();
p_teca_char_array mask;
if (have_fill_value)
{
// allocate and compute the mask
mask = teca_char_array::New(n_elem);
char *p_mask = mask->get();
for (size_t i = 0; i < n_elem; ++i)
{
p_mask[i] = teca_coordinate_util::equal(p_array[i], fill_value) ? 0 : 1;
}
if (this->verbose && (rank == 0))
{
TECA_STATUS("Mask for array \""
<< array_name << "\" will be generated using _FillValue="
<< fill_value)
}
}
else if (have_valid_min || have_valid_max || have_valid_range)
{
// allocate and compute the mask
mask = teca_char_array::New(n_elem);
char *p_mask = mask->get();
for (size_t i = 0; i < n_elem; ++i)
{
NT val = p_array[i];
p_mask[i] = ((val >= valid_range[0]) && (val <= valid_range[1])) ? 1 : 0;
}
if (this->verbose && (rank == 0))
{
TECA_STATUS("Mask for array \""
<< array_name << "\" will be generated using valid_range=["
<< valid_range[0] << ", " << valid_range[1] << "]")
}
}
else
{
if (this->verbose && (rank == 0))
{
TECA_STATUS("Mask array for \"" << array_name
<< "\" was requested but could not be computed. Attributes may"
" be missing a _FillValue, missing_value, valid_min, valid_max;"
" or valid_range. call enable_valid_range to enable the use of"
" valid_min, valid_max and valid_range attributes.")
}
continue;
}
// save the mask in the output
std::string mask_name = array_name + "_valid";
arrays->set(mask_name, mask);
)
}
return out_mesh;
}
| 30.853659 | 93 | 0.555178 | [
"mesh",
"vector"
] |
4da14ea2ed9d3a251e209a9bf114cc7e50563afe | 2,886 | cpp | C++ | CODEJAM/2014/ROUND1A/b.cpp | henviso/contests | aa8a5ce9ed4524e6c3130ee73af7640e5a86954c | [
"Apache-2.0"
] | null | null | null | CODEJAM/2014/ROUND1A/b.cpp | henviso/contests | aa8a5ce9ed4524e6c3130ee73af7640e5a86954c | [
"Apache-2.0"
] | null | null | null | CODEJAM/2014/ROUND1A/b.cpp | henviso/contests | aa8a5ce9ed4524e6c3130ee73af7640e5a86954c | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cstdlib>
#include <stack>
#include <algorithm>
#include <cctype>
#include <vector>
#include <queue>
#include <tr1/unordered_map>
#include <cmath>
#include <map>
#include <bitset>
#include <set>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef vector< ii > vii;
///////////////////////////////UTIL/////////////////////////////////
#define ALL(x) (x).begin(),x.end()
#define CLEAR0(v) memset(v, 0, sizeof(v))
#define CLEAR(v, x) memset(v, x, sizeof(v))
#define IN0(x, n) ((x) > -1 && (x) < n)
#define IN(x, a, b) ((x) >= a && (x) <= b)
#define COPY(a, b) memcpy(a, b, sizeof(a))
#define CMP(a, b) memcmp(a, b, sizeof(a))
#define REP(i,n) for(int i = 0; i<n; i++)
#define REPP(i,a,n) for(int i = a; i<n; i++)
#define REPD(i,n) for(int i = n-1; i>-1; i--)
#define REPDP(i,a,n) for(int i = n-1; i>=a; i--)
#define pb push_back
#define pf push_front
#define sz size()
#define mp make_pair
/////////////////////////////NUMERICAL//////////////////////////////
#define INCMOD(a,b,c) (((a)+b)%c)
#define DECMOD(a,b,c) (((a)+c-b)%c)
#define ROUNDINT(a) (int)((double)(a) + 0.5)
#define INF 0x3f3f3f3f
#define EPS 1e-9
/////////////////////////////BITWISE////////////////////////////////
#define CHECK(S, j) (S & (1 << j))
#define CHECKFIRST(S) (S & (-S)) //PRECISA DE UMA TABELA PARA TRANSFORMAR EM INDICE
#define SET(S, j) S |= (1 << j)
#define SETALL(S, j) S = (1 << j)-1 //J PRIMEIROS
#define UNSET(S, j) S &= ~(1 << j)
#define TOOGLE(S, j) S ^= (1 << j)
///////////////////////////////64 BITS//////////////////////////////
#define LCHECK(S, j) (S & (1ULL << j))
#define LSET(S, j) S |= (1ULL << j)
#define LSETALL(S, j) S = (1ULL << j)-1ULL //J PRIMEIROS
#define LUNSET(S, j) S &= ~(1ULL << j)
#define LTOOGLE(S, j) S ^= (1ULL << j)
//__builtin_popcount(m)
//scanf(" %d ", &t);
vi g[1111];
bitset<11111> vis;
int n, t;
int dfs(int s){
vis[s] = true;
if(g[s].size() <= 2) return 1;
int cnt = 1, x;
int gt = 0, sgt = 0;
REP(i, g[s].size()){
if(!vis[g[s][i]]){
x = dfs(g[s][i]);
if(x > gt){
sgt = gt;
gt = x;
}
else{
if(x > sgt) sgt = x;
}
}
}
cnt += gt+sgt;
//cout << " S " << s << "S.SIZE " << g[s].size() << " CNT " << cnt << " GT " << gt << " SGT " << sgt << endl;
return cnt;
}
int best(int r){
vis.reset();
vis[n+1] = true;
g[r].push_back(n+1);
int ans = dfs(r);
g[r].pop_back();
//cout << " SOBRARAM " << ans << " NOS NO ROOT " << r << endl;
return (n - ans);
}
int main(){
cin >> t;
REPP(ca, 1, t+1){
cin >> n;
int u, v;
REPP(i, 1, n+1) g[i].clear();
REP(i, n-1){
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
int ans = n-1;
REPP(i, 1, n+1) ans = min(ans, best(i));
cout << "Case #" << ca << ": " << ans << endl;
}
}
| 24.87931 | 111 | 0.505544 | [
"vector"
] |
4da99f3ef88253e8da444a793a3fb536b64d1666 | 2,934 | hpp | C++ | Classes/c2xa/object/player.hpp | JAG-SC/c2xa-osc-app | 33a0676af1c726a71690383242b3c431a18cf265 | [
"BSD-2-Clause"
] | 1 | 2015-10-24T14:31:54.000Z | 2015-10-24T14:31:54.000Z | Classes/c2xa/object/player.hpp | JAG-SC/c2xa-osc-app | 33a0676af1c726a71690383242b3c431a18cf265 | [
"BSD-2-Clause"
] | null | null | null | Classes/c2xa/object/player.hpp | JAG-SC/c2xa-osc-app | 33a0676af1c726a71690383242b3c431a18cf265 | [
"BSD-2-Clause"
] | null | null | null | /************************************************************************************//**
@file c2xa/object/player.hpp
@author 新ゝ月(NewNotMoon)
@date created on 2015/08/29
****************************************************************************************/
#ifndef C2XA_OBJECT_PLAYER_HPP
#define C2XA_OBJECT_PLAYER_HPP
#include <cocos2d.h>
#include <c2xa/collision.hpp>
#include <c2xa/object/object.hpp>
#include <c2xa/utility.hpp>
namespace c2xa
{
namespace object
{
/*!
@class player
プレイヤが操作するオブジェクト
*/
class player
: public cocos2d::Node
, public object_interface
{
private:
enum class move_state
{
NONE,
LEFT,
RIGHT
} move_state_;
float position_;
float input_count_;
bool is_touch_;
cocos2d::Point touch_position_;
collision collision_;
public:
CREATE_FUNC( player );
public:
virtual bool init() override;
virtual void update( float delta_ ) override;
float get_position() const
{
return position_;
}
collision get_collision() const
{
return collision_;
}
unsigned int get_point() const override
{
// 自機にポイントはない
return 0;
}
void collide( object_type ) override;
private:
void reset();
void fire();
public:
// Luaから呼ぶための関数です
static int lua_get_player_position( lua_State* state_ )
{
auto p = get_current_scene();
if( p != nullptr )
{
p = p->getChildByName( "object_layer" );
if( p != nullptr )
{
p = p->getChildByName( "player" );
if( p != nullptr )
{
lua_pushnumber( state_, static_cast<double>( static_cast<player*>( p )->get_position() ) );
return 1;
}
}
}
lua_pushnumber( state_, 0. );
return 1;
}
static void registrory_glue( lua_State* state_ )
{
static const struct luaL_Reg functions_[] ={
{ "get_player_position", lua_get_player_position },
{ nullptr, nullptr }
};
luaL_register( state_, "c2xa", functions_ );
}
};
}
}
#endif//C2XA_OBJECT_PLAYER_HPP | 29.049505 | 120 | 0.402863 | [
"object"
] |
4db162bac991c93671910ecc83faae540461200b | 4,989 | hpp | C++ | src/OpenSimBindings/UiModel.hpp | ComputationalBiomechanicsLab/opensim-creator | e5c4b24f5ef3bffe10c84899d0a0c79037020b6d | [
"Apache-2.0"
] | 5 | 2021-07-13T12:03:29.000Z | 2021-12-22T20:21:58.000Z | src/OpenSimBindings/UiModel.hpp | ComputationalBiomechanicsLab/opensim-creator | e5c4b24f5ef3bffe10c84899d0a0c79037020b6d | [
"Apache-2.0"
] | 180 | 2022-01-27T15:25:15.000Z | 2022-03-30T13:41:12.000Z | src/OpenSimBindings/UiModel.hpp | ComputationalBiomechanicsLab/opensim-creator | e5c4b24f5ef3bffe10c84899d0a0c79037020b6d | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "src/3D/BVH.hpp"
#include "src/OpenSimBindings/RenderableScene.hpp"
#include <nonstd/span.hpp>
#include <chrono>
#include <memory>
#include <string>
#include <unordered_map>
namespace OpenSim {
class Model;
class Coordinate;
}
namespace SimTK {
class State;
}
namespace osc {
void generateDecorations(OpenSim::Model const&,
SimTK::State const&,
float fixupScaleFactor,
std::vector<LabelledSceneElement>&);
void updateBVH(nonstd::span<LabelledSceneElement const>, BVH&);
// user-enacted coordinate edit
//
// used to modify the default state whenever a new state is generated
struct CoordinateEdit final {
double value;
double speed;
bool locked;
bool applyToState(OpenSim::Coordinate const&, SimTK::State&) const; // returns `true` if it modified the state
};
// user-enacted state modifications
class StateModifications final {
public:
void pushCoordinateEdit(OpenSim::Coordinate const&, CoordinateEdit const&);
bool applyToState(OpenSim::Model const&, SimTK::State&) const;
private:
std::unordered_map<std::string, CoordinateEdit> m_CoordEdits;
};
// a "UI-ready" OpenSim::Model with an associated (rendered) state
//
// this is what most of the components, screen elements, etc. are
// accessing - usually indirectly (e.g. via a reference to the Model)
struct UiModel final : public RenderableScene {
// user-enacted state modifications (e.g. coordinate edits)
StateModifications stateModifications;
// the model, finalized from its properties
std::unique_ptr<OpenSim::Model> model;
// SimTK::State, in a renderable state (e.g. realized up to a relevant stage)
std::unique_ptr<SimTK::State> state;
// decorations, generated from model's display properties etc.
std::vector<LabelledSceneElement> decorations;
// scene-level BVH of decoration AABBs
BVH sceneAABBBVH;
// fixup scale factor of the model
//
// this scales up/down the decorations of the model - used for extremely
// undersized models (e.g. fly leg)
float fixupScaleFactor;
// current selection, if any
OpenSim::Component* selected;
// current hover, if any
OpenSim::Component* hovered;
// current isolation, if any
//
// "isolation" here means that the user is only interested in this
// particular subcomponent in the model, so visualizers etc. should
// try to only show that component
OpenSim::Component* isolated;
// generic timestamp
//
// can indicate creation or latest modification, it's here to roughly
// track how old/new the instance is
std::chrono::system_clock::time_point timestamp;
// make a blank (new) UiModel
UiModel();
// load a UiModel from an osim file
explicit UiModel(std::string const& osim);
// make a UiModel from an in-memory OpenSim::Model
explicit UiModel(std::unique_ptr<OpenSim::Model>);
// copy some other UiModel
UiModel(UiModel const&);
// copy some other UiModel, but use the supplied timestamp for the modification time
UiModel(UiModel const&, std::chrono::system_clock::time_point t);
UiModel(UiModel&&) noexcept;
~UiModel() noexcept override;
UiModel& operator=(UiModel const&) = delete;
UiModel& operator=(UiModel&&);
// this should be called whenever `model` is mutated
//
// This method updates the other members to reflect the modified model. It
// can throw, because the modification may have put the model into an invalid
// state that can't be used to initialize a new SimTK::MultiBodySystem or
// SimTK::State
void onUiModelModified();
nonstd::span<LabelledSceneElement const> getSceneDecorations() const override {
return decorations;
}
BVH const& getSceneBVH() const override {
return sceneAABBBVH;
}
float getFixupScaleFactor() const override {
return fixupScaleFactor;
}
OpenSim::Component const* getSelected() const override {
return selected;
}
OpenSim::Component const* getHovered() const override {
return hovered;
}
OpenSim::Component const* getIsolated() const override {
return isolated;
}
void pushCoordinateEdit(OpenSim::Coordinate const&, CoordinateEdit const&);
AABB getSceneAABB() const;
glm::vec3 getSceneDimensions() const;
float getSceneLongestDimension() const;
float getRecommendedScaleFactor() const;
void setSceneScaleFactor(float);
};
}
| 30.796296 | 119 | 0.634195 | [
"vector",
"model",
"3d"
] |
4db51fdd01e6502d4db7a9c0d30fda921cc1b5d5 | 1,758 | cpp | C++ | Source/App/main.cpp | LavenSun/IlumEngine | 94841e56af3c5214f04e7a94cb7369f4935c5788 | [
"MIT"
] | 1 | 2021-11-20T15:39:09.000Z | 2021-11-20T15:39:09.000Z | Source/App/main.cpp | LavenSun/IlumEngine | 94841e56af3c5214f04e7a94cb7369f4935c5788 | [
"MIT"
] | null | null | null | Source/App/main.cpp | LavenSun/IlumEngine | 94841e56af3c5214f04e7a94cb7369f4935c5788 | [
"MIT"
] | null | null | null | #include <Ilum/Device/PhysicalDevice.hpp>
#include <Ilum/Device/Window.hpp>
#include <Ilum/Editor/Editor.hpp>
#include <Ilum/Engine/Context.hpp>
#include <Ilum/Engine/Engine.hpp>
#include <Ilum/Graphics/GraphicsContext.hpp>
#include <Ilum/Renderer/RenderPass/BloomPass.hpp>
#include <Ilum/Renderer/RenderPass/GeometryPass.hpp>
#include <Ilum/Renderer/RenderPass/LightPass.hpp>
#include <Ilum/Renderer/RenderPass/TonemappingPass.hpp>
#include <Ilum/Renderer/Renderer.hpp>
#include <Ilum/Scene/Component/Hierarchy.hpp>
#include <Ilum/Scene/Component/MeshRenderer.hpp>
#include <Ilum/Scene/Component/Tag.hpp>
#include <Ilum/Scene/Component/Transform.hpp>
#include <Ilum/Scene/Scene.hpp>
#include <Ilum/Scene/System.hpp>
#include <Ilum/Threading/ThreadPool.hpp>
#include <Ilum/Timing/Timer.hpp>
int main()
{
Ilum::Engine engine;
Ilum::Renderer::instance()->buildRenderGraph = [](Ilum::RenderGraphBuilder &builder) {
builder
.addRenderPass("GeometryPass", std::make_unique<Ilum::pass::GeometryPass>())
.addRenderPass("LightPass", std::make_unique<Ilum::pass::LightPass>())
.addRenderPass("BloomPass", std::make_unique<Ilum::pass::BloomPass>())
.addRenderPass("Tonemapping", std::make_unique<Ilum::pass::TonemappingPass>("blooming"))
.setView("gbuffer - normal")
.setOutput("gbuffer - normal");
};
Ilum::Renderer::instance()->rebuild();
Ilum::Window::instance()->setIcon(std::string(PROJECT_SOURCE_DIR) + "Asset/Texture/Icon/logo.bmp");
while (!Ilum::Window::instance()->shouldClose())
{
engine.onTick();
Ilum::Window::instance()->setTitle((Ilum::Scene::instance()->name.empty() ? "IlumEngine" : Ilum::Scene::instance()->name) + " FPS: " + std::to_string(Ilum::Timer::instance()->getFPS()));
}
return 0;
} | 36.625 | 188 | 0.726962 | [
"transform"
] |
4db536bd88c79a445a1c8bdac295e5fd8c0d8acf | 7,894 | cpp | C++ | src/http/server.cpp | anand-gs/cplusplus | 97f9115df1920c811531b053fc8b9fc9b1ad2ed2 | [
"MIT"
] | null | null | null | src/http/server.cpp | anand-gs/cplusplus | 97f9115df1920c811531b053fc8b9fc9b1ad2ed2 | [
"MIT"
] | null | null | null | src/http/server.cpp | anand-gs/cplusplus | 97f9115df1920c811531b053fc8b9fc9b1ad2ed2 | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////
//
// server.cpp
//
//////////////////////////////////////////////////////
/*
LICENSE: BEGIN
===============================================================================
@author Shan Anand
@email anand.gs@gmail.com
@source https://github.com/shan-anand
@brief HTTP library implementation in C++
===============================================================================
MIT License
Copyright (c) 2017 Shanmuga (Anand) Gunasekaran
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.
===============================================================================
LICENSE: END
*/
#include "http/http.hpp"
#include "common/convert.hpp"
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/select.h>
#include <arpa/inet.h>
#include <openssl/ssl.h>
using namespace std;
using namespace sid;
using namespace sid::http;
extern const SSL_METHOD* g_clientMethod;
extern const SSL_METHOD* g_serverMethod;
/*
To create a self-signed certificate with no password
sudo openssl req -nodes -x509 -days 3650 -sha256 -newkey rsa:4096 -subj "/C=IN/ST=KA/L=Bengaluru/O=self/OU=DevOps/CN=self/emailAddress=self@none" -keyout sid_self.pem -out sid_self.cert
*/
//! Default constructor
server::server() :
m_type(),
m_family(),
m_sslClientCert(),
m_port(0),
m_socket(-1),
m_isRunning(false),
m_exitLoop(false),
m_exception()
{
http::library_init();
}
server_ptr server::create(const connection_type& _type, const connection_family& _family/* = connection_family::none*/)
{
return server::p_create(_type, ssl::client_certificate(), _family);
}
server_ptr server::create(const ssl::client_certificate& _sslClientCert, const connection_family& _family/* = connection_family::none*/)
{
return server::p_create(connection_type::https, _sslClientCert, _family);
}
server_ptr server::p_create(const connection_type& _type, const ssl::client_certificate& _sslClientCert, const connection_family& _family)
{
server_ptr server;
try
{
// Create an object based on the connection type
server = new http::server();
// Fill the object
server->m_type = _type;
server->m_family = _family;
server->m_sslClientCert = _sslClientCert;
}
catch ( http::server* p )
{
if ( p ) delete p;
throw sid::exception("Unable to create server smart pointer object");
}
catch ( const sid::exception& ) { /* Rethrow sid exception */ throw; }
catch (...)
{
throw sid::exception("An unhandled exception occurred while trying to create a server object");
}
// If the server object is empty, the object was not created successfully. So, throw an exception.
if ( !server )
throw sid::exception("Unable to create server object");
// Return the server object. Guarantees that the object is NOT a null pointer
return server;
}
void server::stop()
{
m_exitLoop = false;
}
bool server::run(uint16_t _port, FNProcessCallback& _fnProcessCallback, FNExitCallback& _fnExitCallback)
{
bool bStatus = false;
struct sockaddr_in6 serv_addr6, cli_addr6;
try
{
m_port = (_port != 0)? _port : (m_type == http::connection_type::http)? DEFAULT_PORT_HTTP : DEFAULT_PORT_HTTPS;
m_socket = ::socket(AF_INET6, SOCK_STREAM, 0);
if ( m_socket < 0 )
throw sid::exception("Error creating server socket: " + sid::to_errno_str());
int reuse_port = 1;
::setsockopt(m_socket, SOL_SOCKET, SO_REUSEPORT, &reuse_port, sizeof(reuse_port));
// Initialize server socket address
bzero((char *) &serv_addr6, sizeof(serv_addr6));
serv_addr6.sin6_family = AF_INET6;
serv_addr6.sin6_addr = in6addr_any;
serv_addr6.sin6_port = htons(m_port);
// bind the host address, port to the socket
if ( ::bind(m_socket, (struct sockaddr *) &serv_addr6, sizeof(serv_addr6)) < 0 )
throw sid::exception("Error binding server socket: " + sid::to_errno_str());
// Set server socket to non-blocking
int flags = ::fcntl(m_socket, F_GETFD);
flags |= O_NONBLOCK;
if ( -1 == ::fcntl(m_socket, F_SETFD, flags) )
throw sid::exception("Unable to set socket to non-blocking");
if ( ::listen(m_socket, SOMAXCONN) < 0 )
throw sid::exception("Error listening for connections: " + sid::to_errno_str());
m_exitLoop = false;
m_isRunning = true;
// Certificate to use for https
ssl::certificate sslCert;
sslCert.type = ssl::certificate_type::client;
sslCert.client = m_sslClientCert;
pollfd fds = { m_socket, POLLIN, 0 };
socklen_t clientLen = sizeof(cli_addr6);
int client_fd = -1;
for ( m_exitLoop = false; ! (m_exitLoop = _fnExitCallback()); )
{
int pollRes = ::poll(&fds, 1, 10);
if ( pollRes == 0 ) continue;
if ( pollRes == -1 )
throw sid::exception("Polling failed: " + sid::to_errno_str());
client_fd = ::accept(m_socket, (struct sockaddr *)&cli_addr6, &clientLen);
if ( client_fd < 0 )
throw sid::exception("Error accepting socket: " + sid::to_errno_str());
//cout << "Request received" << endl;
try
{
//sslCert.client.privateKeyType = 0;
http::connection_ptr client;
if ( m_type == http::connection_type::http )
client = http::connection::create(m_type);
else
client = http::connection::create(sslCert);
client->open(client_fd);
client_fd = -1;
// This is SSL-specific
client->accept();
// Call the client callback function to process the request
_fnProcessCallback(client);
}
catch (...)
{
if ( client_fd > 0 )
{
//::shutdown(client_fd, SHUT_RDWR);
::close(client_fd);
}
client_fd = -1;
}
} // loop
cout << "Exiting server loop" << endl;
bStatus = true;
}
catch (const sid::exception& e)
{
m_exception = e;
}
catch (...)
{
m_exception = sid::exception("server::run: An Unhandled exception occurred");
}
// Close the server socket
if ( m_socket != -1 )
{
::shutdown(m_socket, SHUT_RDWR);
::close(m_socket);
m_socket = -1;
}
// Indicate that we stopped running
m_isRunning = false;
return bStatus;
}
/*
http::server_ptr http_server = http::server::create(http::connection_type::http);
http_server->run(5080, continue_callback, client_callback);
http_server.clear();
http::server_ptr https_server = http::server::create(http::connection_type::https);
https_server->run(5443, continue_callback, client_callback);
https_server.clear();
FNClientCallback client_callback = [](http::connection_ptr client)->void
{
// start a new thread???
http::request request;
request.recv(conn);
http::response response;
response.send(conn);
};
FNContinueCallback continue_callback = [&]()->bool
{
return true;
};
*/
| 29.455224 | 185 | 0.663922 | [
"object"
] |
4dbf4d4dcb0268401ede6eee65616df810d0bdd9 | 24,302 | cc | C++ | tensorflow/core/framework/tensor_slice.pb.cc | 1250281649/tensorflow | fc6f4ec813c3514fc4a4c6a078f3f492b3ff325c | [
"Apache-2.0"
] | null | null | null | tensorflow/core/framework/tensor_slice.pb.cc | 1250281649/tensorflow | fc6f4ec813c3514fc4a4c6a078f3f492b3ff325c | [
"Apache-2.0"
] | 2 | 2021-08-25T15:57:35.000Z | 2022-02-10T01:09:32.000Z | tensorflow/core/framework/tensor_slice.pb.cc | 1250281649/tensorflow | fc6f4ec813c3514fc4a4c6a078f3f492b3ff325c | [
"Apache-2.0"
] | null | null | null | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tensorflow/core/framework/tensor_slice.proto
#include "tensorflow/core/framework/tensor_slice.pb.h"
#include <algorithm>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
extern PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_TensorSliceProto_Extent_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto;
namespace tensorflow {
class TensorSliceProto_ExtentDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<TensorSliceProto_Extent> _instance;
::PROTOBUF_NAMESPACE_ID::int64 length_;
} _TensorSliceProto_Extent_default_instance_;
class TensorSliceProtoDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<TensorSliceProto> _instance;
} _TensorSliceProto_default_instance_;
} // namespace tensorflow
static void InitDefaultsscc_info_TensorSliceProto_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::tensorflow::_TensorSliceProto_default_instance_;
new (ptr) ::tensorflow::TensorSliceProto();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::tensorflow::TensorSliceProto::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_TensorSliceProto_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, 0, InitDefaultsscc_info_TensorSliceProto_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto}, {
&scc_info_TensorSliceProto_Extent_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto.base,}};
static void InitDefaultsscc_info_TensorSliceProto_Extent_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::tensorflow::_TensorSliceProto_Extent_default_instance_;
new (ptr) ::tensorflow::TensorSliceProto_Extent();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::tensorflow::TensorSliceProto_Extent::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_TensorSliceProto_Extent_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_TensorSliceProto_Extent_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto}, {}};
static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto[2];
static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto = nullptr;
static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto = nullptr;
const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::tensorflow::TensorSliceProto_Extent, _internal_metadata_),
~0u, // no _extensions_
PROTOBUF_FIELD_OFFSET(::tensorflow::TensorSliceProto_Extent, _oneof_case_[0]),
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::tensorflow::TensorSliceProto_Extent, start_),
offsetof(::tensorflow::TensorSliceProto_ExtentDefaultTypeInternal, length_),
PROTOBUF_FIELD_OFFSET(::tensorflow::TensorSliceProto_Extent, has_length_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::tensorflow::TensorSliceProto, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::tensorflow::TensorSliceProto, extent_),
};
static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::tensorflow::TensorSliceProto_Extent)},
{ 8, -1, sizeof(::tensorflow::TensorSliceProto)},
};
static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = {
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::tensorflow::_TensorSliceProto_Extent_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::tensorflow::_TensorSliceProto_default_instance_),
};
const char descriptor_table_protodef_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) =
"\n,tensorflow/core/framework/tensor_slice"
".proto\022\ntensorflow\"\200\001\n\020TensorSliceProto\022"
"3\n\006extent\030\001 \003(\0132#.tensorflow.TensorSlice"
"Proto.Extent\0327\n\006Extent\022\r\n\005start\030\001 \001(\003\022\020\n"
"\006length\030\002 \001(\003H\000B\014\n\nhas_lengthBq\n\030org.ten"
"sorflow.frameworkB\021TensorSliceProtosP\001Z="
"github.com/tensorflow/tensorflow/tensorf"
"low/go/core/framework\370\001\001b\006proto3"
;
static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto_deps[1] = {
};
static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto_sccs[2] = {
&scc_info_TensorSliceProto_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto.base,
&scc_info_TensorSliceProto_Extent_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto_once;
static bool descriptor_table_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto_initialized = false;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto = {
&descriptor_table_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto_initialized, descriptor_table_protodef_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto, "tensorflow/core/framework/tensor_slice.proto", 312,
&descriptor_table_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto_once, descriptor_table_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto_sccs, descriptor_table_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto_deps, 2, 0,
schemas, file_default_instances, TableStruct_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto::offsets,
file_level_metadata_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto, 2, file_level_enum_descriptors_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto, file_level_service_descriptors_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
static bool dynamic_init_dummy_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto), true);
namespace tensorflow {
// ===================================================================
void TensorSliceProto_Extent::InitAsDefaultInstance() {
::tensorflow::_TensorSliceProto_Extent_default_instance_.length_ = PROTOBUF_LONGLONG(0);
}
class TensorSliceProto_Extent::_Internal {
public:
};
TensorSliceProto_Extent::TensorSliceProto_Extent()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.TensorSliceProto.Extent)
}
TensorSliceProto_Extent::TensorSliceProto_Extent(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.TensorSliceProto.Extent)
}
TensorSliceProto_Extent::TensorSliceProto_Extent(const TensorSliceProto_Extent& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
start_ = from.start_;
clear_has_has_length();
switch (from.has_length_case()) {
case kLength: {
_internal_set_length(from._internal_length());
break;
}
case HAS_LENGTH_NOT_SET: {
break;
}
}
// @@protoc_insertion_point(copy_constructor:tensorflow.TensorSliceProto.Extent)
}
void TensorSliceProto_Extent::SharedCtor() {
start_ = PROTOBUF_LONGLONG(0);
clear_has_has_length();
}
TensorSliceProto_Extent::~TensorSliceProto_Extent() {
// @@protoc_insertion_point(destructor:tensorflow.TensorSliceProto.Extent)
SharedDtor();
}
void TensorSliceProto_Extent::SharedDtor() {
GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
if (has_has_length()) {
clear_has_length();
}
}
void TensorSliceProto_Extent::ArenaDtor(void* object) {
TensorSliceProto_Extent* _this = reinterpret_cast< TensorSliceProto_Extent* >(object);
(void)_this;
}
void TensorSliceProto_Extent::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void TensorSliceProto_Extent::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const TensorSliceProto_Extent& TensorSliceProto_Extent::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_TensorSliceProto_Extent_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto.base);
return *internal_default_instance();
}
void TensorSliceProto_Extent::clear_has_length() {
// @@protoc_insertion_point(one_of_clear_start:tensorflow.TensorSliceProto.Extent)
switch (has_length_case()) {
case kLength: {
// No need to clear
break;
}
case HAS_LENGTH_NOT_SET: {
break;
}
}
_oneof_case_[0] = HAS_LENGTH_NOT_SET;
}
void TensorSliceProto_Extent::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.TensorSliceProto.Extent)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
start_ = PROTOBUF_LONGLONG(0);
clear_has_length();
_internal_metadata_.Clear();
}
const char* TensorSliceProto_Extent::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// int64 start = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
start_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// int64 length = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
_internal_set_length(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr));
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* TensorSliceProto_Extent::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.TensorSliceProto.Extent)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// int64 start = 1;
if (this->start() != 0) {
stream->EnsureSpace(&target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt64ToArray(1, this->_internal_start(), target);
}
// int64 length = 2;
if (_internal_has_length()) {
stream->EnsureSpace(&target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt64ToArray(2, this->_internal_length(), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.TensorSliceProto.Extent)
return target;
}
size_t TensorSliceProto_Extent::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.TensorSliceProto.Extent)
size_t total_size = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// int64 start = 1;
if (this->start() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int64Size(
this->_internal_start());
}
switch (has_length_case()) {
// int64 length = 2;
case kLength: {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int64Size(
this->_internal_length());
break;
}
case HAS_LENGTH_NOT_SET: {
break;
}
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void TensorSliceProto_Extent::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.TensorSliceProto.Extent)
GOOGLE_DCHECK_NE(&from, this);
const TensorSliceProto_Extent* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<TensorSliceProto_Extent>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.TensorSliceProto.Extent)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.TensorSliceProto.Extent)
MergeFrom(*source);
}
}
void TensorSliceProto_Extent::MergeFrom(const TensorSliceProto_Extent& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.TensorSliceProto.Extent)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.start() != 0) {
_internal_set_start(from._internal_start());
}
switch (from.has_length_case()) {
case kLength: {
_internal_set_length(from._internal_length());
break;
}
case HAS_LENGTH_NOT_SET: {
break;
}
}
}
void TensorSliceProto_Extent::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.TensorSliceProto.Extent)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TensorSliceProto_Extent::CopyFrom(const TensorSliceProto_Extent& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.TensorSliceProto.Extent)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TensorSliceProto_Extent::IsInitialized() const {
return true;
}
void TensorSliceProto_Extent::InternalSwap(TensorSliceProto_Extent* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(start_, other->start_);
swap(has_length_, other->has_length_);
swap(_oneof_case_[0], other->_oneof_case_[0]);
}
::PROTOBUF_NAMESPACE_ID::Metadata TensorSliceProto_Extent::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void TensorSliceProto::InitAsDefaultInstance() {
}
class TensorSliceProto::_Internal {
public:
};
TensorSliceProto::TensorSliceProto()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.TensorSliceProto)
}
TensorSliceProto::TensorSliceProto(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(arena),
extent_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.TensorSliceProto)
}
TensorSliceProto::TensorSliceProto(const TensorSliceProto& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr),
extent_(from.extent_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:tensorflow.TensorSliceProto)
}
void TensorSliceProto::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_TensorSliceProto_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto.base);
}
TensorSliceProto::~TensorSliceProto() {
// @@protoc_insertion_point(destructor:tensorflow.TensorSliceProto)
SharedDtor();
}
void TensorSliceProto::SharedDtor() {
GOOGLE_DCHECK(GetArenaNoVirtual() == nullptr);
}
void TensorSliceProto::ArenaDtor(void* object) {
TensorSliceProto* _this = reinterpret_cast< TensorSliceProto* >(object);
(void)_this;
}
void TensorSliceProto::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void TensorSliceProto::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const TensorSliceProto& TensorSliceProto::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_TensorSliceProto_tensorflow_2fcore_2fframework_2ftensor_5fslice_2eproto.base);
return *internal_default_instance();
}
void TensorSliceProto::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.TensorSliceProto)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
extent_.Clear();
_internal_metadata_.Clear();
}
const char* TensorSliceProto::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArenaNoVirtual(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// repeated .tensorflow.TensorSliceProto.Extent extent = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr -= 1;
do {
ptr += 1;
ptr = ctx->ParseMessage(_internal_add_extent(), ptr);
CHK_(ptr);
if (!ctx->DataAvailable(ptr)) break;
} while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<10>(ptr));
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* TensorSliceProto::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.TensorSliceProto)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .tensorflow.TensorSliceProto.Extent extent = 1;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->_internal_extent_size()); i < n; i++) {
stream->EnsureSpace(&target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessageToArray(1, this->_internal_extent(i), target, stream);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.TensorSliceProto)
return target;
}
size_t TensorSliceProto::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.TensorSliceProto)
size_t total_size = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated .tensorflow.TensorSliceProto.Extent extent = 1;
total_size += 1UL * this->_internal_extent_size();
for (const auto& msg : this->extent_) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void TensorSliceProto::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.TensorSliceProto)
GOOGLE_DCHECK_NE(&from, this);
const TensorSliceProto* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<TensorSliceProto>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.TensorSliceProto)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.TensorSliceProto)
MergeFrom(*source);
}
}
void TensorSliceProto::MergeFrom(const TensorSliceProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.TensorSliceProto)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
extent_.MergeFrom(from.extent_);
}
void TensorSliceProto::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.TensorSliceProto)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TensorSliceProto::CopyFrom(const TensorSliceProto& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.TensorSliceProto)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TensorSliceProto::IsInitialized() const {
return true;
}
void TensorSliceProto::InternalSwap(TensorSliceProto* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
extent_.InternalSwap(&other->extent_);
}
::PROTOBUF_NAMESPACE_ID::Metadata TensorSliceProto::GetMetadata() const {
return GetMetadataStatic();
}
// @@protoc_insertion_point(namespace_scope)
} // namespace tensorflow
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE ::tensorflow::TensorSliceProto_Extent* Arena::CreateMaybeMessage< ::tensorflow::TensorSliceProto_Extent >(Arena* arena) {
return Arena::CreateMessageInternal< ::tensorflow::TensorSliceProto_Extent >(arena);
}
template<> PROTOBUF_NOINLINE ::tensorflow::TensorSliceProto* Arena::CreateMaybeMessage< ::tensorflow::TensorSliceProto >(Arena* arena) {
return Arena::CreateMessageInternal< ::tensorflow::TensorSliceProto >(arena);
}
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
| 40.168595 | 251 | 0.771624 | [
"object"
] |
4dc08bd40a9ddd40b5a5818ea68becdb1fa071d8 | 1,771 | cpp | C++ | HDUOJ/6319/monotonic_queue.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2018-02-14T01:59:31.000Z | 2018-03-28T03:30:45.000Z | HDUOJ/6319/monotonic_queue.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | null | null | null | HDUOJ/6319/monotonic_queue.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2017-12-30T02:46:35.000Z | 2018-03-28T03:30:49.000Z | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <iomanip>
#include <climits>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <functional>
#include <iterator>
using namespace std;
#define SIZE 10010000
int num, qLen, k;
int p, q, r, mod;
long long int arr[SIZE];
typedef struct _MQNode
{
int value;
int index;
} MQNode;
MQNode mq[SIZE];
int headPt, tailPt;
inline void pop_front()
{
headPt++;
}
inline void pop_back()
{
tailPt--;
}
inline void push_back(int value, int index)
{
while (headPt < tailPt && mq[tailPt - 1].value <= value)
pop_back();
mq[tailPt++] = {value, index};
while (headPt < tailPt && mq[headPt].index >= index + qLen)
pop_front();
}
inline void initArr(int num)
{
for (int i = k + 1; i <= num; i++)
{
arr[i] = (p * arr[i - 1] + (long long int)q * i + r) % mod;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int caseNum;
cin >> caseNum;
while (caseNum--)
{
cin >> num >> qLen >> k >> p >> q >> r >> mod;
for (int i = 1; i <= k; i++)
{
cin >> arr[i];
}
initArr(num);
headPt = 0;
tailPt = 0;
long long int fst = 0, snd = 0;
for (int i = num ; i > 0; i--)
{
push_back(arr[i], i);
if (i <= num - qLen + 1)
{
int cntMaxRating = mq[headPt].value;
int cntCount = tailPt - headPt;
fst += (cntMaxRating ^ i);
snd += (cntCount ^ i);
}
}
cout << fst << " " << snd << endl;
}
return 0;
} | 18.642105 | 67 | 0.504235 | [
"vector"
] |
4dc85b3cb716c095998bd4855bdedc898fd394db | 1,843 | cpp | C++ | out/production/leetcode/io/github/zhengyhn/leetcode/insert_interval/insert-interval.cpp | zhengyhn/leetcode | 2e5e618dd7c964c8e983b187c6b1762cbe1764de | [
"MIT"
] | null | null | null | out/production/leetcode/io/github/zhengyhn/leetcode/insert_interval/insert-interval.cpp | zhengyhn/leetcode | 2e5e618dd7c964c8e983b187c6b1762cbe1764de | [
"MIT"
] | null | null | null | out/production/leetcode/io/github/zhengyhn/leetcode/insert_interval/insert-interval.cpp | zhengyhn/leetcode | 2e5e618dd7c964c8e983b187c6b1762cbe1764de | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals,
vector<int>& newInterval) {
if (intervals.size() <= 0) {
intervals.push_back(newInterval);
return intervals;
}
vector<vector<int>> ret;
int i = 0;
bool inserted = false;
for (; i < intervals.size(); ++i) {
if (newInterval[0] > intervals[i][1]) {
ret.push_back(intervals[i]);
continue;
}
if (newInterval[1] < intervals[i][0]) {
ret.push_back(newInterval);
inserted = true;
break;
}
vector<int> temp;
if (newInterval[0] < intervals[i][0]) {
temp.push_back(newInterval[0]);
} else {
temp.push_back(intervals[i][0]);
}
int j = i;
for (; j < intervals.size(); ++j) {
if (newInterval[1] < intervals[j][0]) {
temp.push_back(newInterval[1]);
i = j;
break;
} else if (newInterval[1] <= intervals[j][1]) {
temp.push_back(intervals[j][1]);
i = j + 1;
break;
}
}
if (temp.size() <= 1) {
temp.push_back(newInterval[1]);
i = j;
}
ret.push_back(temp);
inserted = true;
break;
}
if (!inserted) {
ret.push_back(newInterval);
} else {
while (i < intervals.size()) {
ret.push_back(intervals[i++]);
}
}
return ret;
}
};
int main() {
Solution sln;
vector<vector<int>> intervals;
vector<int> newInterval;
intervals = {{1, 5}, {6, 8}};
newInterval = {0, 9};
vector<vector<int>> ret = sln.insert(intervals, newInterval);
for (vector<int> list : ret) {
for (int item : list) {
cout << item << " ";
}
cout << endl;
}
} | 23.0375 | 63 | 0.510581 | [
"vector"
] |
4dd444f822f64205ae905b02c40dd6e96aa852a1 | 2,046 | hpp | C++ | Source/AllProjects/Utilities/CIDDocComp/CIDDocComp.hpp | eudora-jia/CIDLib | 02795d283d95f8a5a4fafa401b6189851901b81b | [
"MIT"
] | 1 | 2019-05-28T06:33:01.000Z | 2019-05-28T06:33:01.000Z | Source/AllProjects/Utilities/CIDDocComp/CIDDocComp.hpp | eudora-jia/CIDLib | 02795d283d95f8a5a4fafa401b6189851901b81b | [
"MIT"
] | null | null | null | Source/AllProjects/Utilities/CIDDocComp/CIDDocComp.hpp | eudora-jia/CIDLib | 02795d283d95f8a5a4fafa401b6189851901b81b | [
"MIT"
] | null | null | null | //
// FILE NAME: CIDDocComp.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 06/10/1997
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This is the main header for the program. It brings in any other headers
// that are needed. All our cpp files include this.
//
// This program is a documentation compiler for CIDLib. The documentation files
// are in AllProjects\Docs\CIDDocs. This compiler processes those files and spits
// out HTML content for accessing via a web browser. The output is under the build
// output directory, in a CIDDocs.out directory. Point the browser at the
// CIDDocs.html file as the starting point.
//
// Some very simple javascript is used to manage links and page loading and such.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
#pragma once
// -----------------------------------------------------------------------------
// Include underlying headers.
// -----------------------------------------------------------------------------
#include "CIDLib.hpp"
#include "CIDEncode.hpp"
#include "CIDXML.hpp"
// -----------------------------------------------------------------------------
// Include our out facility for internal use
// -----------------------------------------------------------------------------
#include "CIDDocComp_ErrorIds.hpp"
#include "CIDDocComp_MessageIds.hpp"
#include "CIDDocComp_Info.hpp"
#include "CIDDocComp_HelpNode.hpp"
#include "CIDDocComp_BasePage.hpp"
#include "CIDDocComp_Topics.hpp"
#include "CIDDocComp_HelpPage.hpp"
#include "CIDDocComp_ThisFacility.hpp"
// -----------------------------------------------------------------------------
// Export the facility object internally
// -----------------------------------------------------------------------------
extern TFacCIDDocComp facCIDDocComp;
| 31.96875 | 83 | 0.551808 | [
"object"
] |
4ddcac3607d5c6202b58457242fcad15755291fc | 7,125 | hpp | C++ | silkrpc/commands/eth_api.hpp | enriavil1/silkrpc | 1fa2109658d4c89b6cfdd5190d919bd1324f367e | [
"Apache-2.0"
] | null | null | null | silkrpc/commands/eth_api.hpp | enriavil1/silkrpc | 1fa2109658d4c89b6cfdd5190d919bd1324f367e | [
"Apache-2.0"
] | null | null | null | silkrpc/commands/eth_api.hpp | enriavil1/silkrpc | 1fa2109658d4c89b6cfdd5190d919bd1324f367e | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020 The Silkrpc Authors
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.
*/
#ifndef SILKRPC_COMMANDS_ETH_API_HPP_
#define SILKRPC_COMMANDS_ETH_API_HPP_
#include <memory>
#include <vector>
#include <silkrpc/config.hpp> // NOLINT(build/include_order)
#include <asio/awaitable.hpp>
#include <asio/thread_pool.hpp>
#include <evmc/evmc.hpp>
#include <nlohmann/json.hpp>
#include <silkrpc/txpool/transaction_pool.hpp>
#include <silkworm/types/receipt.hpp>
#include <silkrpc/context_pool.hpp>
#include <silkrpc/core/rawdb/accessors.hpp>
#include <silkrpc/croaring/roaring.hh>
#include <silkrpc/json/types.hpp>
#include <silkrpc/ethbackend/backend.hpp>
#include <silkrpc/ethdb/database.hpp>
#include <silkrpc/ethdb/transaction.hpp>
#include <silkrpc/types/log.hpp>
#include <silkrpc/types/receipt.hpp>
namespace silkrpc::http { class RequestHandler; }
namespace silkrpc::commands {
class EthereumRpcApi {
public:
explicit EthereumRpcApi(Context& context, asio::thread_pool& workers)
: context_(context), database_(context.database), backend_(context.backend), miner_{context.miner}, tx_pool_{context.tx_pool}, workers_{workers} {}
virtual ~EthereumRpcApi() {}
EthereumRpcApi(const EthereumRpcApi&) = delete;
EthereumRpcApi& operator=(const EthereumRpcApi&) = delete;
protected:
asio::awaitable<void> handle_eth_block_number(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_chain_id(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_protocol_version(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_syncing(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_gas_price(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_block_by_hash(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_block_by_number(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_block_transaction_count_by_hash(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_block_transaction_count_by_number(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_uncle_by_block_hash_and_index(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_uncle_by_block_number_and_index(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_uncle_count_by_block_hash(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_uncle_count_by_block_number(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_transaction_by_hash(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_transaction_by_block_hash_and_index(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_transaction_by_block_number_and_index(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_transaction_receipt(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_estimate_gas(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_balance(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_code(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_transaction_count(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_storage_at(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_call(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_new_filter(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_new_block_filter(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_new_pending_transaction_filter(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_filter_changes(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_uninstall_filter(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_logs(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_send_raw_transaction(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_send_transaction(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_sign_transaction(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_proof(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_mining(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_coinbase(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_hashrate(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_submit_hashrate(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_get_work(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_submit_work(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_subscribe(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<void> handle_eth_unsubscribe(const nlohmann::json& request, nlohmann::json& reply);
asio::awaitable<roaring::Roaring> get_topics_bitmap(core::rawdb::DatabaseReader& db_reader, FilterTopics& topics, uint64_t start, uint64_t end);
asio::awaitable<roaring::Roaring> get_addresses_bitmap(core::rawdb::DatabaseReader& db_reader, FilterAddresses& addresses, uint64_t start, uint64_t end);
std::vector<Log> filter_logs(std::vector<Log>& logs, const Filter& filter);
Context& context_;
std::unique_ptr<ethdb::Database>& database_;
std::unique_ptr<ethbackend::BackEnd>& backend_;
std::unique_ptr<txpool::Miner>& miner_;
std::unique_ptr<txpool::TransactionPool>& tx_pool_;
asio::thread_pool& workers_;
friend class silkrpc::http::RequestHandler;
};
} // namespace silkrpc::commands
#endif // SILKRPC_COMMANDS_ETH_API_HPP_
| 62.5 | 157 | 0.775018 | [
"vector"
] |
4ddcf6c7547529e0d43a90eea1b759a0c7e34543 | 7,808 | cc | C++ | src/tracker2.cc | klantz81/multitouch-software | 5cba71d82c68f3d75b8716a8be40a7f10dd741af | [
"MIT"
] | null | null | null | src/tracker2.cc | klantz81/multitouch-software | 5cba71d82c68f3d75b8716a8be40a7f10dd741af | [
"MIT"
] | null | null | null | src/tracker2.cc | klantz81/multitouch-software | 5cba71d82c68f3d75b8716a8be40a7f10dd741af | [
"MIT"
] | null | null | null | #include "tracker2.h"
cTracker2::cTracker2(double min_area, double max_radius, int screen_width, int screen_height, double scale_x, double scale_y) :
min_area(min_area), max_radius(max_radius), screen_width(screen_width), screen_height(screen_height),
scale_x(scale_x), scale_y(scale_y),
labels(NULL), id_index(0), calibrated(false), calibration_points(NULL), h_points(0), v_points(0) {
}
cTracker2::~cTracker2() {
if (labels) delete [] labels;
if (calibration_points) delete [] calibration_points;
}
void cTracker2::extractBlobs(cv::Mat &mat) {
// mat.cols, mat.rows -- allocate vectors
if (mat.cols != width || mat.rows != height) {
width = mat.cols; height = mat.rows;
if (labels) delete [] labels;
labels = new node*[width*height];
}
// reset our data structure for reuse
ds.Reset();
int index;
// generate equivalence sets -- connected component labeling (4-connected)
labels[0] = ds.MakeSet(0);
for (int j = 1; j < mat.cols; j++)
labels[j] = mat.data[j] != mat.data[j-1] ? ds.MakeSet(0) : labels[j-1];
for (int j = mat.cols; j < mat.rows*mat.cols; j++) {
if (mat.data[j] == mat.data[j-1]) {
labels[j] = labels[j-1];
if (mat.data[j-1] == mat.data[j-mat.cols]) ds.Union(labels[j-1], labels[j-mat.cols]);
} else if (mat.data[j] == mat.data[j-mat.cols]) {
labels[j] = labels[j-mat.cols];
if (mat.data[j-1] == mat.data[j-mat.cols]) ds.Union(labels[j-1], labels[j-mat.cols]);
} else
labels[j] = ds.MakeSet(0);
}
// the representative elements in our disjoint set data struct are associated with indices
// we reduce those indices to 0,1,...,n and allocate our blobs
cBlob temp;
blobs.clear();
for (int i = 0; i < ds.Reduce(); i++)
blobs.push_back(temp);
// populate our blob vector
for (int j = 0; j < mat.rows; j++) {
for (int i = 0; i < mat.cols; i++) {
index = ds.Find(labels[j*mat.cols+i])->i;
if (blobs[index].event == BLOB_NULL) {
blobs[index].min.x = blobs[index].max.x = i;
blobs[index].min.y = blobs[index].max.y = j;
blobs[index].event = BLOB_DOWN;
blobs[index].id = id_index++;
} else {
if (blobs[index].min.x > i) blobs[index].min.x = i;
else if (blobs[index].max.x < i) blobs[index].max.x = i;
blobs[index].max.y = j;
}
}
}
sort(blobs.begin(), blobs.end());
// apply blob filter
for (int i = 0; i < blobs.size(); i++) {
if ((blobs[i].max.x-blobs[i].min.x)*(blobs[i].max.y-blobs[i].min.y) < min_area) {
blobs.erase(blobs.begin()+i);
i--;
} else break;
}
blobs.erase(blobs.end());
// find blob centers
for (int i = 0; i < blobs.size(); i++) {
blobs[i].location.x = blobs[i].origin.x = (blobs[i].max.x + blobs[i].min.x) / 2.0;
blobs[i].location.y = blobs[i].origin.y = (blobs[i].max.y + blobs[i].min.y) / 2.0;
}
}
void cTracker2::trackBlobs(cv::Mat &mat, bool history, std::vector<point>& tuio) {
// clear the blobs from two frames ago
blobs_previous.clear();
// before we populate the blobs vector with the current frame, we need to store the live blobs in blobs_previous
for (int i = 0; i < blobs.size(); i++)
if (blobs[i].event != BLOB_UP)// && blobs[i].event != BLOB_NULL)
blobs_previous.push_back(blobs[i]);
extractBlobs(mat);
applyCalibration();
cBlob temp;
for (int i = 0; i < tuio.size(); i++) {
temp.location.x = temp.origin.x = tuio[i].x * screen_width;
temp.location.y = temp.origin.y = tuio[i].y * screen_height;
temp.min.x = temp.location.x - 8;
temp.max.x = temp.location.x + 8;
temp.min.y = temp.location.y - 8;
temp.max.y = temp.location.y + 8;
temp.event = BLOB_DOWN;
temp.id = id_index++;
temp.widget = NULL;
temp.height = 0;
blobs.push_back(temp);
}
//scaleBlobs();
// initialize previous blobs to untracked
for (int i = 0; i < blobs_previous.size(); i++) blobs_previous[i].tracked = false;
// main tracking loop -- O(n^2) -- simply looks for a blob in the previous frame within a specified radius
for (int i = 0; i < blobs.size(); i++) {
for (int j = 0; j < blobs_previous.size(); j++) {
if (blobs_previous[j].tracked) continue;
if (sqrt(pow(blobs[i].location.x - blobs_previous[j].location.x, 2.0) + pow(blobs[i].location.y - blobs_previous[j].location.y, 2.0)) < max_radius) {
blobs_previous[j].tracked = true;
blobs[i].id = blobs_previous[j].id;
blobs[i].widget = blobs_previous[j].widget;
blobs[i].event = BLOB_MOVE;
blobs[i].origin.x = history ? blobs_previous[j].origin.x : blobs_previous[j].location.x;
blobs[i].origin.y = history ? blobs_previous[j].origin.y : blobs_previous[j].location.y;
break;
}
}
}
// add any blobs from the previous frame that weren't tracked as having been removed
for (int i = 0; i < blobs_previous.size(); i++) {
if (!blobs_previous[i].tracked) {
blobs_previous[i].event = BLOB_UP;
blobs.push_back(blobs_previous[i]);
}
}
if (blobs.size() == 0) id_index = 0;
}
void cTracker2::scaleBlobs() {
for (int i = 0; i < blobs.size(); i++) {
blobs[i].location.x *= scale_x;
blobs[i].origin.x *= scale_x;
blobs[i].min.x *= scale_x;
blobs[i].max.x *= scale_x;
blobs[i].location.y *= scale_y;
blobs[i].origin.y *= scale_y;
blobs[i].min.y *= scale_y;
blobs[i].max.y *= scale_y;
}
}
std::vector<cBlob>& cTracker2::getBlobs() {
return blobs;
}
void cTracker2::resetCalibration() {
calibrated = false;
}
void cTracker2::updateCalibration(point* calibration_points, int h_points, int v_points) {
calibrated = true;
this->h_points = h_points; this->v_points = v_points;
if (this->calibration_points) delete [] this->calibration_points;
this->calibration_points = new point[h_points * v_points];
for (int i = 0; i < h_points * v_points; i++) this->calibration_points[i] = calibration_points[i];
}
void cTracker2::applyCalibration() {
if (!calibrated) return;
int i, j, k;
double s, t, v0v0, v1v1, v0v1, xv0, xv1, den;
point p0, p1, p2, v0, v1, x, xp, trans;
bool blob_found;
double delta_x = (double)screen_width / (double)(h_points - 1), delta_y = (double)screen_height / (double)(v_points - 1);
for (k = 0; k < blobs.size(); k++) {
blob_found = false;
for (j = 0; j < v_points - 1; j++) {
for (i = 0; i < h_points - 1; i++) {
// check both triangles with barycentric coordinates
p0 = calibration_points[j * h_points + i];
p1 = calibration_points[j * h_points + i + 1];
p2 = calibration_points[(j + 1) * h_points + i];
v0 = p1 - p0;
v1 = p2 - p0;
x = blobs[k].location - p0;
xv0 = x.inner(v0);
xv1 = x.inner(v1);
v0v0 = v0.inner(v0);
v1v1 = v1.inner(v1);
v0v1 = v0.inner(v1);
den = (v0v0 * v1v1 - v0v1 * v0v1);
s = (xv0 * v1v1 - xv1 * v0v1) / den;
t = (xv1 * v0v0 - xv0 * v0v1) / den;
if (s >= 0 && t >= 0 && s + t <= 1) {
// update blob
xp = point((i + s) * delta_x, (j + t) * delta_y);
trans = xp - blobs[k].location;
blobs[k].location = blobs[k].origin = xp;
blobs[k].min += trans; blobs[k].max += trans;
blob_found = true; break;
}
p0 = calibration_points[(j + 1) * h_points + i + 1];
p1 = calibration_points[(j + 1) * h_points + i];
p2 = calibration_points[j * h_points + i + 1];
v0 = p1 - p0;
v1 = p2 - p0;
x = blobs[k].location - p0;
xv0 = x.inner(v0);
xv1 = x.inner(v1);
v0v0 = v0.inner(v0);
v1v1 = v1.inner(v1);
v0v1 = v0.inner(v1);
den = (v0v0 * v1v1 - v0v1 * v0v1);
s = (xv0 * v1v1 - xv1 * v0v1) / den;
t = (xv1 * v0v0 - xv0 * v0v1) / den;
if (s >= 0 && t >= 0 && s + t <= 1) {
// update blob
xp = point((i + (1 - s)) * delta_x, (j + (1 - t)) * delta_y);
trans = xp - blobs[k].location;
blobs[k].location = blobs[k].origin = xp;
blobs[k].min += trans; blobs[k].max += trans;
blob_found = true; break;
}
}
if (blob_found) break;
}
}
} | 32.131687 | 152 | 0.612833 | [
"vector"
] |
4de11d9cfee670a893c78f67eead12529978a01e | 441 | cpp | C++ | examples/data_distribution/heatmap/heatmap_4.cpp | kurogane1031/matplotplusplus | 44d21156edba8effe1e764a8642b0b70590d597b | [
"MIT"
] | 2 | 2020-09-02T14:02:26.000Z | 2020-10-28T07:00:44.000Z | examples/data_distribution/heatmap/heatmap_4.cpp | kurogane1031/matplotplusplus | 44d21156edba8effe1e764a8642b0b70590d597b | [
"MIT"
] | null | null | null | examples/data_distribution/heatmap/heatmap_4.cpp | kurogane1031/matplotplusplus | 44d21156edba8effe1e764a8642b0b70590d597b | [
"MIT"
] | 2 | 2020-09-01T16:22:07.000Z | 2020-09-02T14:02:27.000Z | #include <matplot/matplot.h>
int main() {
using namespace matplot;
std::vector<std::vector<double>> data = {{45,60,32}, {43,54,76}, {32,94,68}, {23,95,58}};
heatmap(data);
title("T-Shirt Orders");
auto ax = gca();
ax->x_axis().ticklabels({"Small", "Medium", "Large"});
ax->y_axis().ticklabels({"Green", "Red", "Blue", "Gray"});
xlabel(ax, "Sizes");
ylabel(ax, "Colors");
wait();
return 0;
} | 25.941176 | 93 | 0.555556 | [
"vector"
] |
4e2c6c802f56498792e452a366c9510e33bcce55 | 36,104 | cc | C++ | lib/spot-2.8.1/spot/twaalgos/totgba.cc | AlessandroCaste/SynkrisisJupyter | a9c2b21ec1ae7ac0c05ef5deebc63a369274650f | [
"Unlicense"
] | null | null | null | lib/spot-2.8.1/spot/twaalgos/totgba.cc | AlessandroCaste/SynkrisisJupyter | a9c2b21ec1ae7ac0c05ef5deebc63a369274650f | [
"Unlicense"
] | null | null | null | lib/spot-2.8.1/spot/twaalgos/totgba.cc | AlessandroCaste/SynkrisisJupyter | a9c2b21ec1ae7ac0c05ef5deebc63a369274650f | [
"Unlicense"
] | null | null | null | // -*- coding: utf-8 -*-
// Copyright (C) 2015-2018 Laboratoire de Recherche et Développement
// de l'Epita.
//
// This file is part of Spot, a model checking library.
//
// Spot 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.
//
// Spot is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
// License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "config.h"
#include <spot/twaalgos/totgba.hh>
#include <spot/twaalgos/remfin.hh>
#include <spot/twaalgos/cleanacc.hh>
#include <spot/twaalgos/sccinfo.hh>
#include <spot/twa/twagraph.hh>
#include <deque>
#include <tuple>
#define TRACE 0
#if TRACE
#define trace std::cerr
#else
#define trace while (0) std::cerr
#endif
namespace spot
{
namespace
{
class dnf_to_streett_converter
{
private:
typedef std::pair<acc_cond::mark_t, acc_cond::mark_t> mark_pair;
const const_twa_graph_ptr& in_; // The given aut.
scc_info si_; // SCC information.
unsigned nb_scc_; // Number of SCC.
unsigned max_set_in_; // Max acc. set nb of in_.
bool state_based_; // Is in_ state_based ?
unsigned init_st_in_; // Initial state of in_.
bool init_reachable_; // Init reach from itself?
twa_graph_ptr res_; // Resulting automaton.
acc_cond::mark_t all_fin_; // All acc. set marked as
// Fin.
acc_cond::mark_t all_inf_; // All acc. set marked as
// Inf.
unsigned num_sets_res_; // Future nb of acc. set.
std::vector<mark_pair> all_clauses_; // All clauses.
std::vector<acc_cond::mark_t> set_to_keep_; // Set to keep for each clause
std::vector<acc_cond::mark_t> set_to_add_; // New set for each clause.
acc_cond::mark_t all_set_to_add_; // All new set to add.
std::vector<unsigned> assigned_sets_; // Set that will be add.
std::vector<std::vector<unsigned>> acc_clauses_; // Acc. clauses.
unsigned res_init_; // Future initial st.
// A state can be copied at most as many times as their are clauses for
// which it is not rejecting and must be copied one time (to remain
// consistent with the recognized language). This vector records each
// created state following this format:
// st_repr_[orig_st_nb] gives a vector<pair<clause, state>>.
std::vector<std::vector<std::pair<unsigned, unsigned>>> st_repr_;
// Split the DNF acceptance condition and get all the sets used in each
// clause. It separates those that must be seen finitely often from
// those that must be seen infinitely often.
void
split_dnf_clauses(const acc_cond::acc_code& code)
{
auto pos = &code.back();
if (pos->sub.op == acc_cond::acc_op::Or)
--pos;
auto start = &code.front();
while (pos > start)
{
const unsigned short size = pos[0].sub.size;
if (pos[0].sub.op == acc_cond::acc_op::And)
{
acc_cond::mark_t fin = {};
acc_cond::mark_t inf = {};
for (int i = 1; i <= (int)size; i += 2)
{
if (pos[-i].sub.op == acc_cond::acc_op::Fin)
fin |= pos[-i - 1].mark;
else if (pos[-i].sub.op == acc_cond::acc_op::Inf)
inf |= pos[-i - 1].mark;
else
SPOT_UNREACHABLE();
}
all_clauses_.emplace_back(fin, inf);
set_to_keep_.emplace_back(fin | inf);
}
else if (pos[0].sub.op == acc_cond::acc_op::Fin) // Fin
{
auto m1 = pos[-1].mark;
for (unsigned int s : m1.sets())
{
all_clauses_.emplace_back(acc_cond::mark_t({s}),
acc_cond::mark_t({}));
set_to_keep_.emplace_back(acc_cond::mark_t({s}));
}
}
else if (pos[0].sub.op == acc_cond::acc_op::Inf) // Inf
{
auto m2 = pos[-1].mark;
all_clauses_.emplace_back(acc_cond::mark_t({}), m2);
set_to_keep_.emplace_back(m2);
}
else
{
SPOT_UNREACHABLE();
}
pos -= size + 1;
}
#if TRACE
trace << "\nPrinting all clauses\n";
for (unsigned i = 0; i < all_clauses_.size(); ++i)
{
trace << i << " Fin:" << all_clauses_[i].first << " Inf:"
<< all_clauses_[i].second << '\n';
}
#endif
}
// Compute all the acceptance sets that will be needed:
// -Inf(x) will be converted to (Inf(x) | Fin(y)) with y appearing
// on every edge of the associated clone.
// -Fin(x) will be converted to (Inf(y) | Fin(x)) with y appearing
// nowhere.
// In the second form, Inf(y) with no occurrence of y, can be
// reused multiple times. It's called "missing_set" below.
void
assign_new_sets()
{
unsigned int next_set = 0;
unsigned int missing_set = -1U;
assigned_sets_.resize(max_set_in_, -1U);
acc_cond::mark_t all_m = all_fin_ | all_inf_;
for (unsigned set = 0; set < max_set_in_; ++set)
if (all_fin_.has(set))
{
if ((int)missing_set < 0)
{
while (all_m.has(next_set))
++next_set;
missing_set = next_set++;
}
assigned_sets_[set] = missing_set;
}
else if (all_inf_.has(set))
{
while (all_m.has(next_set))
++next_set;
assigned_sets_[set] = next_set++;
}
num_sets_res_ = std::max(next_set, max_set_in_);
}
// Precompute:
// -the sets to add for each clause,
// -all sets to add.
void
find_set_to_add()
{
assign_new_sets();
unsigned nb_clause = all_clauses_.size();
for (unsigned clause = 0; clause < nb_clause; ++clause)
{
if (all_clauses_[clause].second)
{
acc_cond::mark_t m = {};
for (unsigned set = 0; set < max_set_in_; ++set)
if (all_clauses_[clause].second.has(set))
{
assert((int)assigned_sets_[set] >= 0);
m |= acc_cond::mark_t({assigned_sets_[set]});
}
set_to_add_.push_back(m);
}
else
{
set_to_add_.emplace_back(acc_cond::mark_t({}));
}
}
all_set_to_add_ = {};
for (unsigned s = 0; s < max_set_in_; ++s)
if (all_inf_.has(s))
{
assert((int)assigned_sets_[s] >= 0);
all_set_to_add_.set(assigned_sets_[s]);
}
}
// Check whether the initial state is reachable from itself.
bool
is_init_reachable()
{
for (const auto& e : in_->edges())
for (unsigned d : in_->univ_dests(e))
if (d == init_st_in_)
return true;
return false;
}
// Get all non rejecting scc for each clause of the acceptance
// condition. Actually, for each clause, an scc will be kept if it
// contains all the 'Inf' acc. sets of the clause.
void
find_probably_accepting_scc(std::vector<std::vector<unsigned>>& res)
{
res.resize(nb_scc_);
unsigned nb_clause = all_clauses_.size();
for (unsigned scc = 0; scc < nb_scc_; ++scc)
{
if (si_.is_rejecting_scc(scc))
continue;
acc_cond::mark_t acc = si_.acc_sets_of(scc);
for (unsigned clause = 0; clause < nb_clause; ++clause)
{
if ((acc & all_clauses_[clause].second)
== all_clauses_[clause].second)
res[scc].push_back(clause);
}
}
#if TRACE
trace << "accepting clauses\n";
for (unsigned i = 0; i < res.size(); ++i)
{
trace << "scc(" << i << ") -->";
for (auto elt : res[i])
trace << ' ' << elt;
if (si_.is_rejecting_scc(i))
trace << " rej";
trace << '\n';
}
trace << '\n';
#endif
}
// Add all possible representatives of the original state provided.
// Actually, this state will be copied as many times as there are clauses
// for which its SCC is not rejecting.
void
add_state(unsigned st)
{
trace << "add_state(" << st << ")\n";
if (st_repr_[st].empty())
{
unsigned st_scc = si_.scc_of(st);
if (st == init_st_in_ && !init_reachable_)
st_repr_[st].emplace_back(-1U, res_init_);
else if (!acc_clauses_[st_scc].empty())
for (const auto& clause : acc_clauses_[st_scc])
st_repr_[st].emplace_back(clause, res_->new_state());
else
st_repr_[st].emplace_back(-1U, res_->new_state());
trace << "added\n";
}
}
// Compute the mark that will be set (instead of the provided e_acc)
// according to the current clause in process. This function is only
// called for accepting SCC.
acc_cond::mark_t
get_edge_mark(const acc_cond::mark_t& e_acc,
unsigned clause)
{
assert((int)clause >= 0);
return (e_acc & set_to_keep_[clause]) | set_to_add_[clause];
}
// Set the acceptance condition once the resulting automaton is ready.
void
set_acc_condition()
{
acc_cond::acc_code p_code;
for (unsigned set = 0; set < max_set_in_; ++set)
{
if (all_fin_.has(set))
p_code &=
acc_cond::acc_code::inf(acc_cond::mark_t({assigned_sets_[set]}))
| acc_cond::acc_code::fin(acc_cond::mark_t({set}));
else if (all_inf_.has(set))
p_code &=
acc_cond::acc_code::inf(acc_cond::mark_t({set}))
| acc_cond::acc_code::fin(
acc_cond::mark_t({assigned_sets_[set]}));
}
res_->set_acceptance(num_sets_res_, p_code);
}
public:
dnf_to_streett_converter(const const_twa_graph_ptr& in,
const acc_cond::acc_code& code)
: in_(in),
si_(scc_info(in, scc_info_options::TRACK_STATES
| scc_info_options::TRACK_SUCCS)),
nb_scc_(si_.scc_count()),
max_set_in_(code.used_sets().max_set()),
state_based_(in->prop_state_acc() == true),
init_st_in_(in->get_init_state_number()),
init_reachable_(is_init_reachable())
{
trace << "State based ? " << state_based_ << '\n';
std::tie(all_inf_, all_fin_) = code.used_inf_fin_sets();
split_dnf_clauses(code);
find_set_to_add();
find_probably_accepting_scc(acc_clauses_);
}
~dnf_to_streett_converter()
{}
twa_graph_ptr run(bool original_states)
{
res_ = make_twa_graph(in_->get_dict());
res_->copy_ap_of(in_);
st_repr_.resize(in_->num_states());
res_init_ = res_->new_state();
res_->set_init_state(res_init_);
for (unsigned scc = 0; scc < nb_scc_; ++scc)
{
if (!si_.is_useful_scc(scc))
continue;
trace << "scc #" << scc << '\n';
bool rej_scc = acc_clauses_[scc].empty();
for (auto st : si_.states_of(scc))
{
add_state(st);
for (const auto& e : in_->out(st))
{
trace << "working_on_edge(" << st << ',' << e.dst << ")\n";
unsigned dst_scc = si_.scc_of(e.dst);
if (!si_.is_useful_scc(dst_scc))
continue;
add_state(e.dst);
bool same_scc = scc == dst_scc;
if (st == init_st_in_)
{
for (const auto& p_dst : st_repr_[e.dst])
res_->new_edge(res_init_, p_dst.second, e.cond, {});
if (!init_reachable_)
continue;
}
if (!rej_scc)
for (const auto& p_src : st_repr_[st])
for (const auto& p_dst : st_repr_[e.dst])
{
trace << "repr(" << p_src.second << ','
<< p_dst.second << ")\n";
if (same_scc && p_src.first == p_dst.first)
res_->new_edge(p_src.second, p_dst.second, e.cond,
get_edge_mark(e.acc, p_src.first));
else if (!same_scc)
res_->new_edge(p_src.second, p_dst.second, e.cond,
state_based_ ?
get_edge_mark(e.acc, p_src.first)
: acc_cond::mark_t({}));
}
else
{
assert(st_repr_[st].size() == 1);
unsigned src = st_repr_[st][0].second;
acc_cond::mark_t m = {};
if (same_scc || state_based_)
m = e.acc | all_set_to_add_;
for (const auto& p_dst : st_repr_[e.dst])
res_->new_edge(src, p_dst.second, e.cond, m);
}
}
}
}
// Mapping between each state of the resulting automaton and the
// original state of the input automaton.
if (original_states)
{
auto orig_states = new std::vector<unsigned>();
orig_states->resize(res_->num_states(), -1U);
res_->set_named_prop("original-states", orig_states);
auto orig_clauses = new std::vector<unsigned>();
orig_clauses->resize(res_->num_states(), -1U);
res_->set_named_prop("original-clauses", orig_clauses);
unsigned orig_num_states = in_->num_states();
for (unsigned orig = 0; orig < orig_num_states; ++orig)
{
if (!si_.is_useful_scc(si_.scc_of(orig)))
continue;
for (const auto& p : st_repr_[orig])
{
(*orig_states)[p.second] = orig;
(*orig_clauses)[p.second] = p.first;
}
}
}
set_acc_condition();
res_->prop_state_acc(state_based_);
return res_;
}
};
}
twa_graph_ptr
dnf_to_streett(const const_twa_graph_ptr& in, bool original_states)
{
const acc_cond::acc_code& code = in->get_acceptance();
if (!code.is_dnf())
throw std::runtime_error("dnf_to_streett() should only be"
" called on automata with DNF acceptance");
if (code.is_t() || code.is_f() || in->acc().is_streett() > 0)
return make_twa_graph(in, twa::prop_set::all());
dnf_to_streett_converter dnf_to_streett(in, code);
return dnf_to_streett.run(original_states);
}
namespace
{
struct st2gba_state
{
acc_cond::mark_t pend;
unsigned s;
st2gba_state(unsigned st, acc_cond::mark_t bv = acc_cond::mark_t::all()):
pend(bv), s(st)
{
}
};
struct st2gba_state_hash
{
size_t
operator()(const st2gba_state& s) const noexcept
{
std::hash<acc_cond::mark_t> h;
return s.s ^ h(s.pend);
}
};
struct st2gba_state_equal
{
bool
operator()(const st2gba_state& left,
const st2gba_state& right) const
{
if (left.s != right.s)
return false;
return left.pend == right.pend;
}
};
typedef std::vector<acc_cond::mark_t> terms_t;
terms_t cnf_terms(const acc_cond::acc_code& code)
{
assert(!code.empty());
terms_t res;
auto pos = &code.back();
auto end = &code.front();
if (pos->sub.op == acc_cond::acc_op::And)
--pos;
while (pos >= end)
{
auto term_end = pos - 1 - pos->sub.size;
bool inor = pos->sub.op == acc_cond::acc_op::Or;
if (inor)
--pos;
acc_cond::mark_t m = {};
while (pos > term_end)
{
assert(pos->sub.op == acc_cond::acc_op::Inf);
m |= pos[-1].mark;
pos -= 2;
}
if (inor)
res.emplace_back(m);
else
for (unsigned i: m.sets())
res.emplace_back(acc_cond::mark_t({i}));
}
return res;
}
}
// Specialized conversion for Streett -> TGBA
// ============================================
//
// Christof Löding's Diploma Thesis: Methods for the
// Transformation of ω-Automata: Complexity and Connection to
// Second Order Logic. Section 3.4.3, gives a transition
// from Streett with |Q| states to BA with |Q|*(4^n-3^n+2)
// states, if n is the number of acceptance pairs.
//
// Duret-Lutz et al. (ATVA'2009): On-the-fly Emptiness Check of
// Transition-based Streett Automata. Section 3.3 contains a
// conversion from transition-based Streett Automata to TGBA using
// the generalized Büchi acceptance to limit the explosion. It goes
// from Streett with |Q| states to (T)GBA with |Q|*(2^n+1) states.
// However the definition of the number of acceptance sets in that
// paper is suboptimal: only n are needed, not 2^n.
//
// This implements this second version.
twa_graph_ptr
streett_to_generalized_buchi(const const_twa_graph_ptr& in)
{
// While "t" is Streett, it is also generalized Büchi, so
// do not do anything.
if (in->acc().is_generalized_buchi())
return std::const_pointer_cast<twa_graph>(in);
std::vector<acc_cond::rs_pair> pairs;
bool res = in->acc().is_streett_like(pairs);
if (!res)
throw std::runtime_error("streett_to_generalized_buchi() should only be"
" called on automata with Streett-like"
" acceptance");
// In Streett acceptance, inf sets are odd, while fin sets are
// even.
acc_cond::mark_t inf;
acc_cond::mark_t fin;
std::tie(inf, fin) = in->get_acceptance().used_inf_fin_sets();
unsigned p = inf.count();
// At some point we will remove anything that is not used as Inf.
acc_cond::mark_t to_strip = in->acc().all_sets() - inf;
acc_cond::mark_t inf_alone = {};
acc_cond::mark_t fin_alone = {};
if (!p)
return remove_fin(in);
unsigned numsets = in->acc().num_sets();
std::vector<acc_cond::mark_t> fin_to_infpairs(numsets,
acc_cond::mark_t({}));
std::vector<acc_cond::mark_t> inf_to_finpairs(numsets,
acc_cond::mark_t({}));
for (auto pair: pairs)
{
if (pair.fin)
for (unsigned mark: pair.fin.sets())
fin_to_infpairs[mark] |= pair.inf;
else
inf_alone |= pair.inf;
if (pair.inf)
for (unsigned mark: pair.inf.sets())
inf_to_finpairs[mark] |= pair.fin;
else
fin_alone |= pair.fin;
}
// If we have something like (Fin(0)|Inf(1))&Fin(0), then 0 is in
// fin_alone, but we also have fin_to_infpair[0] = {1}. This should
// really be simplified to Fin(0).
for (auto mark: fin_alone.sets())
fin_to_infpairs[mark] = {};
scc_info si(in, scc_info_options::NONE);
// Compute the acceptance sets present in each SCC
unsigned nscc = si.scc_count();
std::vector<std::tuple<acc_cond::mark_t, acc_cond::mark_t,
bool, bool>> sccfi;
sccfi.reserve(nscc);
for (unsigned s = 0; s < nscc; ++s)
{
auto acc = si.acc_sets_of(s); // {0,1,2,3,4,6,7,9}
auto acc_fin = acc & fin; // {0, 2, 4,6}
auto acc_inf = acc & inf; // { 1, 3, 7,9}
// Fin sets that are alone either because the acceptance
// condition has no matching Inf, or because the SCC does not
// intersect the matching Inf.
acc_cond::mark_t fin_wo_inf = {};
for (unsigned mark: acc_fin.sets())
if (!fin_to_infpairs[mark] || (fin_to_infpairs[mark] - acc_inf))
fin_wo_inf.set(mark);
// Inf sets that *do* have a matching Fin in the acceptance
// condition but without matching Fin in the SCC: they can be
// considered as always present in the SCC.
acc_cond::mark_t inf_wo_fin = {};
for (unsigned mark: inf.sets())
if (inf_to_finpairs[mark] && (inf_to_finpairs[mark] - acc_fin))
inf_wo_fin.set(mark);
sccfi.emplace_back(fin_wo_inf, inf_wo_fin,
!acc_fin, !acc_inf);
}
auto out = make_twa_graph(in->get_dict());
out->copy_ap_of(in);
out->prop_copy(in, {false, false, false, false, false, true});
out->set_generalized_buchi(p);
// Map st2gba pairs to the state numbers used in out.
typedef std::unordered_map<st2gba_state, unsigned,
st2gba_state_hash,
st2gba_state_equal> bs2num_map;
bs2num_map bs2num;
// Queue of states to be processed.
typedef std::deque<st2gba_state> queue_t;
queue_t todo;
st2gba_state s(in->get_init_state_number());
bs2num[s] = out->new_state();
todo.emplace_back(s);
bool sbacc = in->prop_state_acc().is_true();
// States of the original automaton are marked with s.pend == -1U.
const acc_cond::mark_t orig_copy = acc_cond::mark_t::all();
while (!todo.empty())
{
s = todo.front();
todo.pop_front();
unsigned src = bs2num[s];
unsigned scc_src = si.scc_of(s.s);
bool maybe_acc_scc = !si.is_rejecting_scc(scc_src);
acc_cond::mark_t scc_fin_wo_inf;
acc_cond::mark_t scc_inf_wo_fin;
bool no_fin;
bool no_inf;
std::tie(scc_fin_wo_inf, scc_inf_wo_fin, no_fin, no_inf)
= sccfi[scc_src];
for (auto& t: in->out(s.s))
{
acc_cond::mark_t pend = s.pend;
acc_cond::mark_t acc = {};
bool maybe_acc = maybe_acc_scc && (scc_src == si.scc_of(t.dst));
if (pend != orig_copy)
{
if (!maybe_acc)
continue;
// No point going to some place we will never leave
if (t.acc & scc_fin_wo_inf)
continue;
// For any Fin set we see, we want to see the
// corresponding Inf set.
for (unsigned mark: (t.acc & fin).sets())
pend |= fin_to_infpairs[mark];
// If we see some Inf set immediately, they are not
// pending anymore.
pend -= t.acc & inf;
// Label this transition with all non-pending
// inf sets. The strip will shift everything
// to the correct numbers in the targets.
acc = (inf - pend).strip(to_strip);
// Adjust the pending sets to what will be necessary
// required on the destination state.
if (sbacc)
{
auto a = in->state_acc_sets(t.dst);
if (a & scc_fin_wo_inf)
continue;
for (unsigned m: (a & fin).sets())
pend |= fin_to_infpairs[m];
pend -= a & inf;
}
pend |= inf_alone;
}
else if (no_fin && maybe_acc)
{
// If the acceptance is (Fin(0) | Inf(1)) & Inf(2)
// but we do not see any Fin set in this SCC, a
// mark {2} should become {1,2} before striping.
acc = (t.acc | scc_inf_wo_fin).strip(to_strip);
}
assert((acc & out->acc().all_sets()) == acc);
st2gba_state d(t.dst, pend);
// Have we already seen this destination?
unsigned dest;
auto dres = bs2num.emplace(d, 0);
if (!dres.second)
{
dest = dres.first->second;
}
else // No, this is a new state
{
dest = dres.first->second = out->new_state();
todo.emplace_back(d);
}
out->new_edge(src, dest, t.cond, acc);
// Nondeterministically jump to level ∅. We need to do
// that only once per cycle. As an approximation, we
// only do that for transitions where t.src >= t.dst as
// this has to occur at least once per cycle.
if (pend == orig_copy && (t.src >= t.dst) && maybe_acc && !no_fin)
{
acc_cond::mark_t stpend = {};
if (sbacc)
{
auto a = in->state_acc_sets(t.dst);
if (a & scc_fin_wo_inf)
continue;
for (unsigned m: (a & fin).sets())
stpend |= fin_to_infpairs[m];
stpend -= a & inf;
}
st2gba_state d(t.dst, stpend | inf_alone);
// Have we already seen this destination?
unsigned dest;
auto dres = bs2num.emplace(d, 0);
if (!dres.second)
{
dest = dres.first->second;
}
else // No, this is a new state
{
dest = dres.first->second = out->new_state();
todo.emplace_back(d);
}
out->new_edge(src, dest, t.cond);
}
}
}
simplify_acceptance_here(out);
if (out->acc().is_f())
{
// "f" is not generalized-Büchi. Just return an
// empty automaton instead.
auto res = make_twa_graph(out->get_dict());
res->set_generalized_buchi(0);
res->set_init_state(res->new_state());
res->prop_stutter_invariant(true);
res->prop_weak(true);
res->prop_complete(false);
return res;
}
return out;
}
twa_graph_ptr
streett_to_generalized_buchi_maybe(const const_twa_graph_ptr& in)
{
static unsigned min = [&]() {
const char* c = getenv("SPOT_STREETT_CONV_MIN");
if (!c)
return 3;
errno = 0;
int val = strtol(c, nullptr, 10);
if (val < 0 || errno != 0)
throw std::runtime_error("unexpected value for SPOT_STREETT_CONV_MIN");
return val;
}();
std::vector<acc_cond::rs_pair> pairs;
bool res = in->acc().is_streett_like(pairs);
if (!res || min == 0 || min > pairs.size())
return nullptr;
else
return streett_to_generalized_buchi(in);
}
/// \brief Take an automaton with any acceptance condition and return
/// an equivalent Generalized Büchi automaton.
twa_graph_ptr
to_generalized_buchi(const const_twa_graph_ptr& aut)
{
auto maybe = streett_to_generalized_buchi_maybe(aut);
if (maybe)
return maybe;
auto res = remove_fin(cleanup_acceptance(aut));
if (res->acc().is_generalized_buchi())
return res;
auto cnf = res->get_acceptance().to_cnf();
// If we are very lucky, building a CNF actually gave us a GBA...
if (cnf.empty() ||
(cnf.size() == 2 && cnf.back().sub.op == acc_cond::acc_op::Inf))
{
res->set_acceptance(res->num_sets(), cnf);
cleanup_acceptance_here(res);
return res;
}
// Handle false specifically. We want the output
// an automaton with Acceptance: t, that has a single
// state without successor.
if (cnf.is_f())
{
assert(!cnf.front().mark);
res = make_twa_graph(aut->get_dict());
res->set_init_state(res->new_state());
res->prop_state_acc(true);
res->prop_weak(true);
res->prop_universal(true);
res->prop_stutter_invariant(true);
return res;
}
auto terms = cnf_terms(cnf);
unsigned nterms = terms.size();
assert(nterms > 0);
res->set_generalized_buchi(nterms);
for (auto& t: res->edges())
{
acc_cond::mark_t cur_m = t.acc;
acc_cond::mark_t new_m = {};
for (unsigned n = 0; n < nterms; ++n)
if (cur_m & terms[n])
new_m.set(n);
t.acc = new_m;
}
return res;
}
namespace
{
// If the DNF is
// Fin(1)&Inf(2)&Inf(4) | Fin(2)&Fin(3)&Inf(1) |
// Inf(1)&Inf(3) | Inf(1)&Inf(2) | Fin(4)
// this returns the following vector of pairs:
// [({1}, {2,4})
// ({2,3}, {1}),
// ({}, {1,3}),
// ({}, {2}),
// ({4}, t)]
static std::vector<std::pair<acc_cond::mark_t, acc_cond::mark_t>>
split_dnf_acc(const acc_cond::acc_code& acc)
{
std::vector<std::pair<acc_cond::mark_t, acc_cond::mark_t>> res;
if (acc.empty())
{
res.emplace_back(acc_cond::mark_t({}), acc_cond::mark_t({}));
return res;
}
auto pos = &acc.back();
if (pos->sub.op == acc_cond::acc_op::Or)
--pos;
auto start = &acc.front();
while (pos > start)
{
if (pos->sub.op == acc_cond::acc_op::Fin)
{
// We have only a Fin term, without Inf. In this case
// only, the Fin() may encode a disjunction of sets.
for (auto s: pos[-1].mark.sets())
res.emplace_back(acc_cond::mark_t({s}), acc_cond::mark_t({}));
pos -= pos->sub.size + 1;
}
else
{
// We have a conjunction of Fin and Inf sets.
auto end = pos - pos->sub.size - 1;
acc_cond::mark_t fin = {};
acc_cond::mark_t inf = {};
while (pos > end)
{
switch (pos->sub.op)
{
case acc_cond::acc_op::And:
--pos;
break;
case acc_cond::acc_op::Fin:
fin |= pos[-1].mark;
assert(pos[-1].mark.count() == 1);
pos -= 2;
break;
case acc_cond::acc_op::Inf:
inf |= pos[-1].mark;
pos -= 2;
break;
case acc_cond::acc_op::FinNeg:
case acc_cond::acc_op::InfNeg:
case acc_cond::acc_op::Or:
SPOT_UNREACHABLE();
break;
}
}
assert(pos == end);
res.emplace_back(fin, inf);
}
}
return res;
}
static twa_graph_ptr
to_generalized_rabin_aux(const const_twa_graph_ptr& aut,
bool share_inf, bool complement)
{
auto res = cleanup_acceptance(aut);
auto oldacc = res->get_acceptance();
if (complement)
res->set_acceptance(res->acc().num_sets(), oldacc.complement());
{
std::vector<unsigned> pairs;
if (res->acc().is_generalized_rabin(pairs))
{
if (complement)
res->set_acceptance(res->acc().num_sets(), oldacc);
return res;
}
}
auto dnf = res->get_acceptance().to_dnf();
if (dnf.is_f())
{
if (complement)
res->set_acceptance(0, acc_cond::acc_code::t());
return res;
}
auto v = split_dnf_acc(dnf);
// Decide how we will rename each input set.
//
// inf_rename is only used if hoa_style=false, to
// reuse previously used Inf sets.
unsigned ns = res->num_sets();
std::vector<acc_cond::mark_t> rename(ns);
std::vector<unsigned> inf_rename(ns);
unsigned next_set = 0;
// The output acceptance conditions.
acc_cond::acc_code code =
complement ? acc_cond::acc_code::t() : acc_cond::acc_code::f();
for (auto& i: v)
{
unsigned fin_set = 0U;
if (!complement)
{
for (auto s: i.first.sets())
rename[s].set(next_set);
fin_set = next_set++;
}
acc_cond::mark_t infsets = {};
if (share_inf)
for (auto s: i.second.sets())
{
unsigned n = inf_rename[s];
if (n == 0)
n = inf_rename[s] = next_set++;
rename[s].set(n);
infsets.set(n);
}
else // HOA style
{
for (auto s: i.second.sets())
{
unsigned n = next_set++;
rename[s].set(n);
infsets.set(n);
}
}
// The definition of Streett wants the Fin first in clauses,
// so we do the same for generalized Streett since HOA does
// not specify anything. See
// https://github.com/adl/hoaf/issues/62
if (complement)
{
for (auto s: i.first.sets())
rename[s].set(next_set);
fin_set = next_set++;
auto pair = acc_cond::inf({fin_set});
pair |= acc_cond::acc_code::fin(infsets);
pair &= std::move(code);
code = std::move(pair);
}
else
{
auto pair = acc_cond::acc_code::inf(infsets);
pair &= acc_cond::fin({fin_set});
pair |= std::move(code);
code = std::move(pair);
}
}
// Fix the automaton
res->set_acceptance(next_set, code);
for (auto& e: res->edges())
{
acc_cond::mark_t m = {};
for (auto s: e.acc.sets())
m |= rename[s];
e.acc = m;
}
return res;
}
}
twa_graph_ptr
to_generalized_rabin(const const_twa_graph_ptr& aut,
bool share_inf)
{
return to_generalized_rabin_aux(aut, share_inf, false);
}
twa_graph_ptr
to_generalized_streett(const const_twa_graph_ptr& aut,
bool share_fin)
{
return to_generalized_rabin_aux(aut, share_fin, true);
}
}
| 34.2868 | 80 | 0.503905 | [
"vector",
"model"
] |
4e2ce9c9016d708adf46e8fe6b9bf470bc38d344 | 2,163 | cpp | C++ | tsp.cpp | tanutarou/TSP-Solver | 6170fcf99785163b2314b5cc6d00524067fed242 | [
"MIT"
] | null | null | null | tsp.cpp | tanutarou/TSP-Solver | 6170fcf99785163b2314b5cc6d00524067fed242 | [
"MIT"
] | null | null | null | tsp.cpp | tanutarou/TSP-Solver | 6170fcf99785163b2314b5cc6d00524067fed242 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <map>
#include <string>
#include <vector>
#include <bits/stdc++.h>
const long long INF = 1000000000ll;
std::pair<double, std::vector<int>> memo[20][1<<20];
class TSP{
public:
int n;
double w[1000][1000];
std::vector<int> ans;
double opt;
TSP(int N){
n = N;
opt = INF;
for(int i=0; i<N; i++){
for(int j=0; j<N; j++){
double t;
std::cin >> t;
w[i][j] = t;
}
}
for(int i=0; i<N; i++){
for(int j=0; j<(1<<N);j++){
memo[i][j].first = -1;
}
}
}
void brute(){
std::vector<int> v;
for(int i=0; i<n; i++){
v.push_back(i);
}
do{
double c = cost(v);
if(opt > c){
opt = c;
ans = v;
}
}while(next_permutation(v.begin(), v.end()));
}
void dp(){
auto ret = dp_core(0, 1);
opt = ret.first;
ans = ret.second;
ans.push_back(0);
reverse(ans.begin(), ans.end());
}
std::pair<double, std::vector<int>> dp_core(int now, int mask){
if(memo[now][mask].first != -1){
return memo[now][mask];
}
if(mask == (1 << n) - 1){
std::vector<int> v;
return make_pair(w[now][0], v);
}
double ret = INF;
int idx;
std::vector<int> v;
for(int i = 0; i < n; i++){
if(mask & (1 << i)){
continue;
}else{
auto p = dp_core(i, mask | (1 << i));
double c = w[now][i] + p.first;
if(ret > c){
ret = c;
idx = i;
v = p.second;
}
}
}
v.push_back(idx);
return memo[now][mask] = make_pair(ret, v);
}
void solve(std::string method){
if(method == "brute"){
brute();
}else if(method == "dp"){
dp();
}
return;
}
double cost(std::vector<int> v){
double ret = 0;
for(int i=0; i<v.size(); i++){
if(i == v.size()-1) ret += w[v[i]][v[0]];
else ret += w[v[i]][v[i+1]];
}
return ret;
}
void output(){
for(int i=0; i<ans.size(); i++){
printf("%d ", ans[i]);
}
puts("");
printf("min cost = %.5f\n", opt);
}
};
int main(void) {
int n;
std::string method;
std::cin >> n;
std::cin >> method;
TSP tsp = TSP(n);
tsp.solve(method);
tsp.output();
return 0;
}
| 16.51145 | 65 | 0.49006 | [
"vector"
] |
4e2ebba5d3bf79e7d32da1a7eed35afbc91e0555 | 18,357 | cpp | C++ | routing/arouterex/src/parser/ParserIspd08.cpp | rbarzic/MAGICAL | 0510550b263913f8c62f46662a9dfa2ae94d2386 | [
"BSD-3-Clause"
] | null | null | null | routing/arouterex/src/parser/ParserIspd08.cpp | rbarzic/MAGICAL | 0510550b263913f8c62f46662a9dfa2ae94d2386 | [
"BSD-3-Clause"
] | null | null | null | routing/arouterex/src/parser/ParserIspd08.cpp | rbarzic/MAGICAL | 0510550b263913f8c62f46662a9dfa2ae94d2386 | [
"BSD-3-Clause"
] | null | null | null | #include "ParserIspd08.h"
PROJECT_NAMESPACE_BEGIN
bool ParserIspd08::read()
{
_benchmark = 0;
// Read in the benchmark file
if (!readFile())
{
return false;
}
// Translate the database
if (!trans2DB())
{
return false;
}
return true;
}
bool ParserIspd08::readPinShapeBenchmark()
{
_benchmark = 1;
// Read in the benchmark file
if (!readFilePinShapeBenchmark())
{
return false;
}
// Translate the database
if (!trans2DB())
{
return false;
}
return true;
}
bool ParserIspd08::readFilePinShapeBenchmark()
{
std::ifstream inf(_fileName.c_str());
if (!inf.is_open())
{
ERR("ISPDParser::%s: cannot open file: %s \n", __FUNCTION__ , _fileName.c_str());
Assert(false);
return false;
}
std::string lineStr;
std::string token;
IntType intToken = 0;
std::getline(inf, lineStr);
std::stringstream ss(lineStr);
IntType dieXLo = INT_TYPE_MAX;
IntType dieYLo = INT_TYPE_MAX;
IntType dieXHi = INT_TYPE_MIN;
IntType dieYHi = INT_TYPE_MIN;
// Die boundary
ss >> token;
#if 0
if (std::strcmp(token.c_str(), "die"))
{
ss >> dieXLo;
ss >> dieYLo;
ss >> dieXHi;
ss >> dieYHi;
// Net
ss >> token;
}
#endif
Assert(!std::strcmp(token.c_str(), "num"));
ss >> token;
Assert(!std::strcmp(token.c_str(), "net"));
ss >> intToken;
_rawDB.setNetSize(intToken);
// Read each net
for (IndexType netIdx = 0; netIdx < _rawDB.netSize(); ++netIdx)
{
std::getline(inf, lineStr);
ss = std::stringstream(lineStr);
ss >> token;
std::string netName = std::string(token);
IndexType netIdxx;
ss >> netIdxx;
IndexType pinSize;
ss >> pinSize;
IndexType minimumWidth;
ss >> minimumWidth;
ISPDRawDb::ispdNet tempNet = ISPDRawDb::ispdNet(netName, netIdxx, pinSize, minimumWidth );
for (IndexType pinIdx = 0; pinIdx < pinSize; ++pinIdx)
{
std::getline(inf, lineStr);
ss = std::stringstream(lineStr);
IndexType layer;
ss >> layer;
tempNet._pinArray.emplace_back(ISPDRawDb::ispdPin(0, 0, layer));
bool isX = true;
IntType x = 0;
IntType y = 0;
while (ss >> intToken)
{
if (isX) // read the x for a point
{
x = intToken;
// Round
float fx = (float) x;
x = ((IntType)round(fx /5)) * 5;
isX = false; // The next is y
if (x < dieXLo)
{
dieXLo = x;
}
if (x > dieXHi)
{
dieXHi = x;
}
}
else
{
// Reading y for a point
y = intToken;
// Round
float fy = (float) y;
y = ((IntType) round(fy / 5)) * 5;
isX = true; // The next one is x
tempNet._pinArray.back()._polygonPts.emplace_back(XY<LocType> (x * _scale, y * _scale));
if (y < dieYLo)
{
dieYLo = y;
}
if (y > dieYHi)
{
dieYHi = y;
}
}
}
}
_rawDB.addNet(tempNet);
}
// Set die boundary
_rawDB.setXLF(dieXLo * _scale);
_rawDB.setYLF(dieYLo * _scale);
_rawDB.setXHi(dieXHi * _scale);
_rawDB.setYHi(dieYHi * _scale);
INF("%s: Choose design boundary: %d %d %d %d \n", __FUNCTION__, _rawDB.xLF(), _rawDB.yLF(), _rawDB.xHi(), _rawDB.yHi());
return true;
}
bool ParserIspd08::readFile()
{
std::ifstream inf(_fileName.c_str());
if (!inf.is_open())
{
ERR("ISPDParser::readFile(): cannot open file: %s \n", _fileName.c_str());
Assert(false);
return false;
}
char token [100];
IntType uintToken = 0;
// Step 1: parsing overall information grid # # # (x grids, y grids, number of layers)i
inf >> token;
Assert(!std::strcmp(token, "grid"));
inf >> uintToken;
_rawDB.setXGridSize(uintToken * _scale);
inf >> uintToken;
_rawDB.setYGridSize(uintToken * _scale);
inf >> uintToken;
_rawDB.setLayerSize(uintToken);
#ifdef DEBUG_INPUT
DBG("x %u, y %u, layer %u \n", _rawDB.xGridSize(), _rawDB.yGridSize(), _rawDB.layerSize());
#endif
// Vertical capacity
inf >> token;
Assert(!std::strcmp(token, "vertical"));
inf >> token;
Assert(!std::strcmp(token, "capacity"));
for (IndexType layer = 0; layer < _rawDB.layerSize(); ++layer)
{
inf >> uintToken;
_rawDB.addVerticalCapacity(uintToken);
}
#ifdef DEBUG_INPUT
for (IndexType layer = 0; layer < _rawDB.layerSize(); ++layer)
{
DBG("Vertical capacity %u \n", _rawDB.verticalCapacity().at(layer));
}
#endif
// Horizontal capacity
inf >> token;
DBG("Token : %s \n", token);
Assert(!std::strcmp(token, "horizontal"));
inf >> token;
Assert(!std::strcmp(token, "capacity"));
for (IndexType layer = 0; layer < _rawDB.layerSize(); ++layer)
{
inf >> uintToken;
_rawDB.addHorizontalCapacity(uintToken);
}
#ifdef DEBUG_INPUT
for (IndexType layer = 0; layer < _rawDB.layerSize(); ++layer)
{
DBG("Horizontal capacity %u \n", _rawDB.horizontalCapacity().at(layer));
}
#endif
// Minimum Width
inf >> token;
Assert(!std::strcmp(token, "minimum"));
inf >> token;
Assert(!std::strcmp(token, "width"));
for (IndexType layer = 0; layer < _rawDB.layerSize(); ++layer)
{
inf >> uintToken;
_rawDB.addMinimumWidth(uintToken * _scale);
}
#ifdef DEBUG_INPUT
for (IndexType layer = 0; layer < _rawDB.layerSize(); ++layer)
{
DBG("Minimum Width: %u \n", _rawDB.minimumWidth().at(layer));
}
#endif
// Minimum spacing
inf >> token;
Assert(!std::strcmp(token, "minimum"));
inf >> token;
Assert(!std::strcmp(token, "spacing"));
for (IndexType layer = 0; layer < _rawDB.layerSize(); ++layer)
{
inf >> uintToken;
_rawDB.addMinimumSpacing(uintToken * _scale);
}
#ifdef DEBUG_INPUT
for (IndexType layer = 0; layer < _rawDB.layerSize(); ++layer)
{
DBG("Minimum Spacing: %u \n", _rawDB.minimumSpacing().at(layer));
}
#endif
// Via spacing
inf >> token;
Assert(!std::strcmp(token, "via"));
inf >> token;
Assert(!std::strcmp(token, "spacing"));
for (IndexType layer = 0; layer < _rawDB.layerSize(); ++layer)
{
inf >> uintToken;
_rawDB.addViaSpacing(uintToken * _scale);
}
#ifdef DEBUG_INPUT
for (IndexType layer = 0; layer < _rawDB.layerSize(); ++layer)
{
DBG("Via Spacing: %u \n", _rawDB.viaSpacing().at(layer));
}
#endif
// lower_left_x lower_left_y tile_width tile_height
inf >> uintToken;
_rawDB.setXLF(uintToken * _scale);
#ifdef DEBUG_INPUT
DBG("%u ", _rawDB.xLF());
#endif
inf >> uintToken;
_rawDB.setYLF(uintToken * _scale);
#ifdef DEBUG_INPUT
DBG("%u ", _rawDB.yLF());
#endif
inf >> uintToken;
_rawDB.setTileWidth(uintToken * _scale);
#ifdef DEBUG_INPUT
DBG("%u ", _rawDB.tileWidth());
#endif
inf >> uintToken;
_rawDB.setTileHeight(uintToken * _scale);
#ifdef DEBUG_INPUT
DBG("%u \n", _rawDB.tileHeight());
#endif
// Net
inf >> token;
Assert(!std::strcmp(token, "num"));
inf >> token;
Assert(!std::strcmp(token, "net"));
inf >> uintToken;
_rawDB.setNetSize(uintToken);
for (IndexType netIdx = 0; netIdx < _rawDB.netSize(); ++netIdx)
{
inf >> token;
std::string netName = std::string(token);
IndexType netIdxx;
inf >> netIdxx;
IndexType pinSize;
inf >> pinSize;
IndexType minimumWidth;
inf >> minimumWidth;
ISPDRawDb::ispdNet tempNet = ISPDRawDb::ispdNet(netName, netIdxx, pinSize, minimumWidth * _scale);
for (IndexType pinIdx = 0; pinIdx < pinSize; ++pinIdx)
{
IndexType x;
inf >> x;
IndexType y;
inf >> y;
IndexType layer;
inf >> layer;
tempNet._pinArray.emplace_back(ISPDRawDb::ispdPin(x * _scale, y * _scale, layer));
}
_rawDB.addNet(std::move(tempNet));
}
#ifdef DEBUG_INPUT
for (IndexType netIdx = 0; netIdx < _rawDB.netSize(); ++netIdx)
{
const auto &net = _rawDB.netArray().at(netIdx);
DBG("net %s, %u, %u, %u\n", net._netName.c_str(), net._netIdx, net._pinSize, net._minimumWidth);
for (IndexType pinIdx = 0; pinIdx < net._pinSize; ++pinIdx)
{
const auto &pin = net._pinArray.at(pinIdx);
DBG("pin %u, %u, %u\n", pin._x, pin._y, pin._layer);
}
}
#endif
// Sym Nets
IndexType symSize = 0;
IndexType adjustSize = 0;
inf >> token;
if (!strcmp(token, "net"))
{
// Existing sym nets
inf >> token;
Assert(!strcmp(token, "sym"));
inf >> symSize;
}
else
{
adjustSize = atoi(token); // If not existing sym net, the current token store the number of capacity adjustments
}
_rawDB.setSymSize(symSize);
for (IndexType symIdx = 0; symIdx < symSize; ++symIdx)
{
inf >> token;
std::string netName1 = std::string(token);
inf >> token;
std::string netName2 = std::string(token);
_rawDB.addSymNet(ISPDRawDb::ispdSymNet(netName1, netName2));
}
#ifdef DEBUG_INPUT
DBG("Sym net %u\n",_rawDB.symSize());
for (IndexType symIdx = 0; symIdx < _rawDB.symSize(); ++symIdx)
{
const auto &symNet = _rawDB.symNetArray().at(symIdx);
DBG("%s %s\n", symNet._net1.c_str(), symNet._net2.c_str());
}
#endif
// Capacity adjustment
// Check whether existing sym net and correct the token if necessary
if (symSize != 0)
{
inf >> adjustSize;
}
_rawDB.setCapSize(adjustSize);
for (IndexType adjIdx = 0; adjIdx < adjustSize; ++adjIdx)
{
IndexType x1;
inf >> x1;
IndexType y1;
inf >> y1;
IndexType layer1;
inf >>layer1;
IndexType x2;
inf >> x2;
IndexType y2;
inf >> y2;
IndexType layer2;
inf >> layer2;
IndexType cap;
inf >> cap;
_rawDB.addCapAdjust(ISPDRawDb::ispdCapAdjust(x1 * _scale, y1 * _scale, layer1, x2 * _scale, y2 * _scale, layer2, cap));
}
#ifdef DEBUG_INPUT
DBG("cap ajust %u\n", _rawDB.capAdjustSize());
for (IndexType adjIdx = 0; adjIdx < _rawDB.capAdjustSize(); ++adjIdx)
{
const auto &cap = _rawDB.capAdjustArray().at(adjIdx);
DBG("%u, %u, %u, %u, %u, %u, %u \n", cap._x1, cap._y1, cap._layer1, cap._x2, cap._y2, cap._layer2, cap._adjustment);
AssertMsg(cap._layer1 == cap._layer2, "Check the benchmark cap ajustment");
}
#endif
return true;
}
bool ParserIspd08::trans2DB()
{
auto &grDB = _db.grDB();
if (_benchmark == 0)
{
// Lower left corner of the design
grDB.dieLL() = XY<LocType>(_rawDB.xLF(), _rawDB.yLF());
// tile width/height of the global routing grid
grDB.setGridWidth(_rawDB.tileWidth());
grDB.setGridHeight(_rawDB.tileHeight());
// metal/via width/spacing
WRN("%s: ignore min width/spacing from ISPD'08 benchmarks\n", __FUNCTION__);
// Init the grid map for the global routing base
grDB.gridMap() = GridMapGR(_rawDB.xGridSize(), _rawDB.yGridSize(), _rawDB.layerSize() + 1);
// init the caps of masterslice layer of 3D gridmap to have capacity all 0
grDB.gridMap().initHCap(0, 0);
grDB.gridMap().initVCap(0, 0);
grDB.gridMap().initViaCap(0, 0);
IntType totalHCap = 0;
IntType totalVCap = 0;
for (IndexType layer = 0; layer < _rawDB.layerSize(); ++layer)
{
totalHCap += _rawDB.horizontalCapacity().at(layer);
totalVCap += _rawDB.verticalCapacity().at(layer);
// Set the caps for the layer in 3D grid map
grDB.gridMap().initHCap(layer + 1, _rawDB.horizontalCapacity().at(layer));
grDB.gridMap().initVCap(layer + 1, _rawDB.verticalCapacity().at(layer));
if (layer != _rawDB.layerSize() - 1)
{
grDB.gridMap().initViaCap(layer + 1, INT_TYPE_MAX); // the benchmark format does not specify this number
}
}
// Also add the access from POLY
grDB.gridMap().initViaCap(0, INT_TYPE_MAX);
// Set edge distances
_db.grDB().gridMap().setGridWidth(_rawDB.tileWidth());
_db.grDB().gridMap().setGridHeight(_rawDB.tileHeight());
// Set die upper right corner
LocType dieXHi = _rawDB.xGridSize() * _rawDB.tileWidth();
LocType dieYHi = _rawDB.yGridSize() * _rawDB.tileHeight();
_db.grDB().dieUR() = XY<LocType> (dieXHi, dieYHi);
} // if _benchmark == 0
if (_benchmark == 1)
{
grDB.dieLL() = XY<LocType> (_rawDB.xLF(), _rawDB.yLF());
grDB.dieUR() = XY<LocType> (_rawDB.xHi(), _rawDB.yHi());
}
// reserve net vector
grDB.nets().reserve(_rawDB.netSize());
// Build a map with [netName] = netIdx
std::unordered_map<std::string, IndexType> netNameMap;
for (IndexType netIdx = 0; netIdx < _rawDB.netSize(); ++netIdx)
{
netNameMap[_rawDB.netArray().at(netIdx)._netName] = netIdx;
}
// convert pin information
for (IndexType netIdx = 0; netIdx < _rawDB.netSize(); ++netIdx)
{
const auto &net = _rawDB.netArray().at(netIdx);
NetGR temp;
temp.setName(net._netName);
temp.setBenchmarkNetIdx(net._netIdx);
temp.setWeight(net._minimumWidth);
// process the pins for the net
for (const auto &pin : net._pinArray)
{
IndexType pinIdx = grDB.phyPinArray().size();
Pin tempPin = Pin();
// Layer is for both benchmarks
tempPin.setLayer(pin._layer);
if (_benchmark == 0)
{
IndexType xGridIdx = std::floor(pin._x - _rawDB.xLF()) / _rawDB.tileWidth();
IndexType yGridIdx = std::floor(pin._y - _rawDB.yLF()) / _rawDB.tileHeight();
tempPin.setLoc(XY<LocType>(pin._x, pin._y));
tempPin.setGridIdx(XY<IndexType>(xGridIdx, yGridIdx));
}
// Pin shape poly
for (const auto &polyPt : pin._polygonPts)
{
tempPin.addPinShapePoint(polyPt);
}
if (!tempPin.init()) { return false; }
grDB.phyPinArray().emplace_back(tempPin);
temp.physPinArray().emplace_back(pinIdx);
}
grDB.nets().emplace_back(temp);
}
if (_benchmark == 0)
{
// find the sym nets
for (const auto &symNet : _rawDB.symNetArray())
{
IndexType netIdx1 = netNameMap.at(symNet._net2);
IndexType netIdx2 = netNameMap.at(symNet._net1);
// Add SymNet objects
IndexType symNetIdx = _db.numSymNets();
_db.symNetArray().emplace_back(SymNet(netIdx1, netIdx2));
// update the NetGR objects
_db.grDB().nets().at(netIdx1).setSymNetIdx(symNetIdx);
_db.grDB().nets().at(netIdx2).setSymNetIdx(symNetIdx);
}
// Routing blockages
for (const auto &adj : _rawDB.capAdjustArray())
{
Assert(adj._layer1 == adj._layer2);
//Assert(adj._adjustment == 0);
IndexType layer = adj._layer1;
//IndexType layerCap = klib::greaterOne(_rawDb.horizontalCapacity().at(layer), _rawDb.verticalCapacity().at(layer));
//AssertMsg(layerCap != 0, "layer: %u, layer cap %u %u \n", layer, _rawDb.horizontalCapacity().at(layer), _rawDb.verticalCapacity().at(layer));
//IndexType reducedCap = adj._adjustment * PERCENT_ACC / layerCap;
IntType reducedCap = adj._adjustment;
// Calculate the index of grids that need to be adjusted
IndexType xIdxLo = std::min((adj._x1 - _rawDB.xLF())/ _rawDB.tileWidth(), (adj._x2 - _rawDB.xLF()) / _rawDB.tileWidth());
IndexType yIdxLo = std::min((adj._y1 - _rawDB.yLF())/ _rawDB.tileHeight(), (adj._y2 - _rawDB.yLF()) / _rawDB.tileHeight());
IndexType xIdxHi = std::max((adj._x1 - _rawDB.xLF())/ _rawDB.tileWidth(), (adj._x2 - _rawDB.xLF()) / _rawDB.tileWidth());
IndexType yIdxHi = std::max((adj._y1 - _rawDB.yLF())/ _rawDB.tileHeight(), (adj._y2 - _rawDB.yLF()) / _rawDB.tileHeight());
for (IndexType xIdx = xIdxLo; xIdx < xIdxHi; ++xIdx)
{
for (IndexType yIdx = yIdxLo; yIdx < yIdxHi; ++yIdx)
{
// The horizontal edge
auto &hEdge = grDB.gridEdge(XYZ<IndexType>(xIdx, yIdx, layer), XYZ<IndexType>(xIdx + 1, yIdx, layer));
IntType hReduced = hEdge.totalCap() > reducedCap ? \
hEdge.totalCap() - reducedCap : \
0;
hEdge.setTotalCap(hEdge.totalCap() - hReduced);
// The vertical edge
auto &vEdge = grDB.gridEdge(XYZ<IndexType>(xIdx, yIdx, layer), XYZ<IndexType>(xIdx, yIdx + 1, layer));
IntType vReduced = vEdge.totalCap() > reducedCap ? \
vEdge.totalCap() - reducedCap : \
0;
vEdge.setTotalCap(vEdge.totalCap() - vReduced);
}
}
}
// Init map 2D
grDB.gridMap().init2D();
} // if benchmark == 0
INF("Parsing ISPD'08 Benchmark completed \n");
return true;
}
PROJECT_NAMESPACE_END
| 32.036649 | 155 | 0.548129 | [
"shape",
"vector",
"3d"
] |
4e4946512bba8a80d1b37f4368789ff8e895336e | 2,696 | cpp | C++ | src/libraries/lagrangian/intermediate/submodels/addOns/radiation/scatter/cloudScatter/cloudScatter.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/lagrangian/intermediate/submodels/addOns/radiation/scatter/cloudScatter/cloudScatter.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/lagrangian/intermediate/submodels/addOns/radiation/scatter/cloudScatter/cloudScatter.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2011 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS 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.
CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "cloudScatter.hpp"
#include "addToRunTimeSelectionTable.hpp"
#include "thermoCloud.hpp"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
namespace CML
{
namespace radiation
{
defineTypeNameAndDebug(cloudScatter, 0);
addToRunTimeSelectionTable
(
scatterModel,
cloudScatter,
dictionary
);
}
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
CML::radiation::cloudScatter::cloudScatter
(
const dictionary& dict,
const fvMesh& mesh
)
:
scatterModel(dict, mesh),
coeffsDict_(dict.subDict(typeName + "Coeffs")),
cloudNames_(coeffsDict_.lookup("cloudNames"))
{}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
CML::radiation::cloudScatter::~cloudScatter()
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
CML::tmp<CML::volScalarField>
CML::radiation::cloudScatter::sigmaEff() const
{
tmp<volScalarField> tsigma
(
new volScalarField
(
IOobject
(
"sigma",
mesh_.time().timeName(),
mesh_,
IOobject::NO_READ,
IOobject::NO_WRITE,
false
),
mesh_,
dimensionedScalar("zero", dimless/dimLength, 0.0)
)
);
forAll(cloudNames_, i)
{
const thermoCloud& tc
(
mesh_.objectRegistry::lookupObject<thermoCloud>(cloudNames_[i])
);
tsigma() += tc.sigmap();
}
return 3.0*tsigma;
}
// ************************************************************************* //
| 26.431373 | 79 | 0.490727 | [
"mesh"
] |
4e4d8315cb4be32a942c8745b8c8606333bc40c9 | 14,654 | cpp | C++ | src/main.cpp | rubyrio12/Azul-Board-Game | a8479a60cb76e2cd1660d6380ccdf6c283c49510 | [
"MIT"
] | null | null | null | src/main.cpp | rubyrio12/Azul-Board-Game | a8479a60cb76e2cd1660d6380ccdf6c283c49510 | [
"MIT"
] | null | null | null | src/main.cpp | rubyrio12/Azul-Board-Game | a8479a60cb76e2cd1660d6380ccdf6c283c49510 | [
"MIT"
] | null | null | null | #include <iostream>
#include <limits>
#include <vector>
#include <string>
#include <fstream>
#include <cstring>
#include <errno.h>
#include <limits.h>
#include "Types.h"
#include "Game.h"
#include "AdvancedGame.h"
#include "Player.h"
#include "AdvancedPlayer.h"
#include "utils.h"
#include "Score.h"
[[noreturn]] void showMenu();
[[noreturn]] void showSeededMenu(int seed);
[[noreturn]] void showAdvancedMenu();
void showCredits();
void playGame();
void playAdvancedGame();
void loadGame();
void loadAdvancedGame();
void playSeededGame(int seed);
std::vector<Player *> createPlayersFromUserInput();
std::vector<AdvancedPlayer *> createAdvancedPlayersFromUserInput();
bool isNameValid(const std::string &name);
void engageTestMode(char* fileName);
int seed;
int main(int argc, char ** argv) {
// Check number of argument
if (argc == 1){
// No additional arguments shows menu
showMenu();
}
else if (argc == 2){
const std::string advancedMode = "--adv";
if (argv[1] == advancedMode){
showAdvancedMenu();
}
else {
seed = atoi(argv[2]);
showSeededMenu(seed);
}
}
else if (argc == 3){
// 2 additional arguments directs to test mode
const std::string testFlag = "-t";
const std::string seededFlag = "-s";
// Check for Flag
if (argv[1] == testFlag){
// If File Exists
if (checkIfFileExists(argv[2])){
engageTestMode(argv[2]);
}
else {
std::cout << "No such file exists!" << std::endl;
}
}
// Check for Flag
else if (argv[1] == seededFlag){
errno = 0;
int conv = atoi(argv[2]);
if (errno != 0 || conv > INT_MAX) {
std::cout << "Wrong Seed Type" << std::endl;
std::cout << "./azul -s <int> to specify a seed to turn off randomness" << std::endl;
}
else {
seed = atoi(argv[2]);
showSeededMenu(seed);
}
}
else {
std::cout << "Wrong flag" << std::endl;
}
}
else {
std::cout << "Invalid number of arguments" << std::endl;
std::cout << "./azul to run" << std::endl;
std::cout << "./azul -t <testfile> to engage test mode" << std::endl;
std::cout << "./azul -s <int> to specify a seed to turn off randomness" << std::endl;
}
return EXIT_SUCCESS;
}
/**
* Displays Basic Menu
*/
[[noreturn]] void showMenu() {
// Welcome message
std::cout << "Welcome to Azul!" << std::endl;
std::cout << "-----------------------" << std::endl;
std::cout << std::endl;
while (true) {
// Print Menu Contents
std::cout << "Menu" << std::endl;
std::cout << "-----" << std::endl;
std::cout << "1. New Game" << std::endl;
std::cout << "2. Load Game" << std::endl;
std::cout << "3. Credits" << std::endl;
std::cout << "4. Quit" << std::endl;
std::cout << std::endl;
std::cout << "> ";
// Getting user input
int choice;
std::cin >> choice;
// Check end of file
if (std::cin.eof()) {
quitGame();
}
// Check fail conditions
else if (std::cin.fail() || choice < 0 || choice > 4) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Wrong Input. Please enter an integer number from 1 to 4" << std::endl;
std::cout << std::endl;
} else {
if (choice == 1) {
playGame();
} else if (choice == 2) {
loadGame();
} else if (choice == 3) {
showCredits();
} else if (choice == 4) {
quitGame();
}
}
}
}
/**
* Displays Menu to run Advanced Azul
*/
[[noreturn]] void showAdvancedMenu() {
// Welcome message
std::cout << "Welcome to Azul!" << std::endl;
std::cout << "-----------------------" << std::endl;
std::cout << std::endl;
while (true) {
// Print Menu Contents
std::cout << "Menu" << std::endl;
std::cout << "-----" << std::endl;
std::cout << "1. New Advanced Game" << std::endl;
std::cout << "2. Load Game" << std::endl;
std::cout << "3. Credits" << std::endl;
std::cout << "4. Quit" << std::endl;
std::cout << std::endl;
std::cout << "> ";
// Getting user input
int choice;
std::cin >> choice;
// Check end of file
if (std::cin.eof()) {
quitGame();
}
// Check fail conditions
else if (std::cin.fail() || choice < 0 || choice > 4) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Wrong Input. Please enter an integer number from 1 to 4" << std::endl;
std::cout << std::endl;
} else {
if (choice == 1) {
playAdvancedGame();
} else if (choice == 2) {
loadAdvancedGame();
} else if (choice == 3) {
showCredits();
} else if (choice == 4) {
quitGame();
}
}
}
}
/**
* Displays Menu that incorporates user's seed
*/
[[noreturn]] void showSeededMenu(int seed) {
// Welcome message
std::cout << "Welcome to Azul!" << std::endl;
std::cout << "-----------------------" << std::endl;
std::cout << std::endl;
while (true) {
// Print Menu Contents
std::cout << "Menu" << std::endl;
std::cout << "-----" << std::endl;
std::cout << "1. New Game" << std::endl;
std::cout << "2. Load Game" << std::endl;
std::cout << "3. Credits" << std::endl;
std::cout << "4. Quit" << std::endl;
std::cout << std::endl;
std::cout << "> ";
// Getting user input
int choice;
std::cin >> choice;
// Check end of file
if (std::cin.eof()) {
quitGame();
}
// Check fail conditions
else if (std::cin.fail() || choice < 0 || choice > 4) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Wrong Input. Please enter an integer number from 1 to 4" << std::endl;
std::cout << std::endl;
} else {
if (choice == 1) {
playSeededGame(seed);
} else if (choice == 2) {
loadGame();
} else if (choice == 3) {
showCredits();
} else if (choice == 4) {
quitGame();
}
}
}
}
/**
* Display the information of the authors of this program
*/
void showCredits() {
std::cout << "--------------------------" << std::endl;
std::cout << "Name: Anh Nguyen" << std::endl;
std::cout << "Student ID: s3616128" << std::endl;
std::cout << "Email: s3616128@rmit.edu.vn" << std::endl;
std::cout << "--------------------------" << std::endl;
std::cout << std::endl;
std::cout << "--------------------------" << std::endl;
std::cout << "Name: Mitchell Gust" << std::endl;
std::cout << "Student ID: s3782095" << std::endl;
std::cout << "Email: s3782095@student.rmit.edu.au" << std::endl;
std::cout << "--------------------------" << std::endl;
std::cout << std::endl;
std::cout << "--------------------------" << std::endl;
std::cout << "Name: Ruby Rio" << std::endl;
std::cout << "Student ID: s3786695" << std::endl;
std::cout << "Email: s3786695@student.rmit.edu.au" << std::endl;
std::cout << "--------------------------" << std::endl;
std::cout << std::endl;
}
/**
* This function will initialize an Azul game
*/
void playGame() {
std::cout << std::endl;
std::cout << "Starting a new Azul game" << std::endl;
std::cout << std::endl;
// Game Initialization
auto game = new Game();
int seed = (time(NULL));
game->addPlayers(createPlayersFromUserInput());
game->setTileBagSeeded(seed);
std::cout << "Let's Play!" << std::endl;
std::cout << std::endl;
// Play the game
game->play();
std::cout << "=== Game Over ===" << std::endl;
std::cout << "=== Scoreboard ===" << std::endl;
// Print Scores
game->printFinalResults();
}
/**
* This function will initialize an Advanced Azul game
*/
void playAdvancedGame() {
std::cout << std::endl;
std::cout << "Starting a new Azul game" << std::endl;
std::cout << std::endl;
// Game Initialization
auto game = new AdvancedGame();
int seed = (time(NULL));
game->addPlayers(createAdvancedPlayersFromUserInput());
game->setTileBagSeeded(seed);
std::cout << "Let's Play!" << std::endl;
std::cout << std::endl;
// Play the game
game->play();
std::cout << "=== Game Over ===" << std::endl;
std::cout << "=== Scoreboard ===" << std::endl;
// Print Scores
game->printFinalResults();
}
/**
* This function will initialize a Seeded Azul game
*/
void playSeededGame(int seed) {
std::cout << std::endl;
std::cout << "Starting a new Azul game" << std::endl;
std::cout << std::endl;
// Game Initialization
auto game = new Game();
game->addPlayers(createPlayersFromUserInput());
game->setTileBagSeeded(seed);
std::cout << "Let's Play!" << std::endl;
std::cout << std::endl;
// Play the game
game->play();
std::cout << "=== Game Over ===" << std::endl;
std::cout << "=== Scoreboard ===" << std::endl;
// Print Scores
game->printFinalResults();
}
/**
* This functional will load an Azul game from a file
*/
void loadGame() {
bool valid = false;
std::string fileName;
// Clear input
std::cin.clear();
std::cin.ignore(10000, '\n');
std::cout << "Enter the name of save file: " << std::endl;
while (!valid){
std::cout << "> ";
// Grab file name
getline(std::cin, fileName);
// Check EOF
if (!std::cin){
quitGame();
}
// Check if file exists
if (checkIfFileExists(fileName.c_str())){
// Break loop
valid = true;
}
else {
// Display error message
std::cout << "No such file exists. Please try again!" << std::endl;
}
}
// Initialize New Game
auto game = new Game();
// Load game from file
game->load(fileName);
}
/**
* This function will load an Advanced Azul game from a file
*/
void loadAdvancedGame() {
bool valid = false;
std::string fileName;
// Clear input
std::cin.clear();
std::cin.ignore(10000, '\n');
std::cout << "Enter the name of save file: " << std::endl;
while (!valid){
std::cout << "> ";
// Grab file name
getline(std::cin, fileName);
// Check EOF
if (!std::cin){
quitGame();
}
// Check if file exists
if (checkIfFileExists(fileName.c_str())){
// Break loop
valid = true;
}
else {
// Display error message
std::cout << "No such file exists. Please try again!" << std::endl;
}
}
// Initialize New Game
auto game = new AdvancedGame();
// Load game from file
game->load(fileName);
}
/**
* Check if a player's name is valid
* @param name
* @return valid: true if valid, false if invalid
*/
bool isNameValid(const std::string &name) {
bool valid = true;
if (name.empty()) {
valid = false;
}
return valid;
}
/**
* Create a player vector based on stdin
* @return a vector of player objects
*/
std::vector<Player *> createPlayersFromUserInput() {
// A vector to store player objects
std::vector<Player *> players;
// Player counter
int playerCount = 1;
// Clear input
std::cin.clear();
std::cin.ignore(10000, '\n');
// End loop when num of players exceeds the ceiling
while (playerCount <= NUM_OF_PLAYERS) {
std::string name;
std::string savedName;
std::cout << "Enter a name for player " << playerCount << std::endl;
std::cout << "> ";
getline(std::cin, name);
std::cout << std::endl;
// Check end of file
if (std::cin.eof()) {
quitGame();
}
// Validate input
else if (isNameValid(name)) {
// Increase count by one
// Initialize and add player object to the vector
if (playerCount == 1){
players.push_back(new Player(name, playerCount, true));
}
else {
players.push_back(new Player(name, playerCount, false));
}
playerCount++;
} else {
std::cout << "Invalid name. Please try again" << std::endl;
}
}
return players;
}
std::vector< AdvancedPlayer *> createAdvancedPlayersFromUserInput() {
// A vector to store player objects
std::vector<AdvancedPlayer *> players;
// Player counter
int playerCount = 1;
// Clear input
std::cin.clear();
std::cin.ignore(10000, '\n');
// End loop when num of players exceeds the ceiling
while (playerCount <= NUM_OF_PLAYERS) {
std::string name;
std::string savedName;
std::cout << "Enter a name for player " << playerCount << std::endl;
std::cout << "> ";
getline(std::cin, name);
std::cout << std::endl;
// Check end of file
if (std::cin.eof()) {
quitGame();
}
// Validate input
else if (isNameValid(name)) {
// Increase count by one
// Initialize and add player object to the vector
if (playerCount == 1){
players.push_back(new AdvancedPlayer(name, playerCount, true));
}
else {
players.push_back(new AdvancedPlayer(name, playerCount, false));
}
playerCount++;
} else {
std::cout << "Invalid name. Please try again" << std::endl;
}
}
return players;
}
void engageTestMode(char* fileName){
// Initialize New Game
auto game = new Game();
// Load game from file
game->testLoadGame(fileName);
}
| 26.987109 | 101 | 0.503412 | [
"object",
"vector"
] |
4e52dec06606bdcc03898208872fb10783563a5e | 7,474 | cpp | C++ | libbitcoin/test/oldtests/hmac512.cpp | mousewu/bcclient | 64ee1f6f8337103d40a4a0c3dfb73cabcd09a04c | [
"MIT"
] | 8 | 2019-05-31T01:37:08.000Z | 2021-10-19T05:52:45.000Z | libbitcoin/test/oldtests/hmac512.cpp | mousewu/bcclient | 64ee1f6f8337103d40a4a0c3dfb73cabcd09a04c | [
"MIT"
] | 3 | 2017-12-18T17:27:09.000Z | 2018-01-15T16:50:05.000Z | libbitcoin/test/oldtests/hmac512.cpp | mousewu/bcclient | 64ee1f6f8337103d40a4a0c3dfb73cabcd09a04c | [
"MIT"
] | 5 | 2018-01-09T15:05:55.000Z | 2020-12-17T13:27:25.000Z | /*
* Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bitcoin/bitcoin.hpp>
using namespace bc;
constexpr size_t sha512_length = SHA512_DIGEST_LENGTH;
constexpr size_t sha512_block_size = 128;
typedef std::array<uint8_t, sha512_length> long_hash;
template <typename HashType, size_t block_size>
HashType generate_hmac(const data_chunk& key, const data_chunk& data,
std::function<HashType (const data_chunk&)> hash_func)
{
typedef typename HashType::value_type hash_char;
std::array<hash_char, block_size> fixed_key;
// Zero out
std::fill(fixed_key.begin(), fixed_key.end(), 0);
// Now copy key or hash into zeroed out buffer
if (key.size() <= block_size)
{
std::copy(key.begin(), key.end(), fixed_key.begin());
}
else
{
HashType fixed_key_digest = hash_func(key);
BITCOIN_ASSERT(fixed_key.size() >= fixed_key_digest.size());
std::copy(fixed_key_digest.begin(), fixed_key_digest.end(),
fixed_key.begin());
}
// hash(o_key_pad + hash(i_key_pad + data))
// Work on inner section first
data_chunk inner_data(fixed_key.size() + data.size());
// xor each digit of key...
std::transform(fixed_key.begin(), fixed_key.end(), inner_data.begin(),
[](hash_char digit) { return digit ^ 0x36; });
// ... and append the data.
std::copy(data.begin(), data.end(),
inner_data.begin() + fixed_key.size());
HashType inner_hash = hash_func(inner_data);
// Work on outer section
data_chunk outer_data(fixed_key.size() + inner_hash.size());
// xor each digit of key...
std::transform(fixed_key.begin(), fixed_key.end(), outer_data.begin(),
[](hash_char digit) { return digit ^ 0x5c; });
// ... and combine with inner_hash to get outer_data.
std::copy(inner_hash.begin(), inner_hash.end(),
outer_data.begin() + fixed_key.size());
return hash_func(outer_data);
}
long_hash single_sha512_hash(const data_chunk& chunk)
{
long_hash digest;
SHA512_CTX ctx;
SHA512_Init(&ctx);
SHA512_Update(&ctx, chunk.data(), chunk.size());
SHA512_Final(digest.data(), &ctx);
return digest;
}
long_hash generate_hmac_sha512(const data_chunk& key, const data_chunk& data)
{
return generate_hmac<long_hash, sha512_block_size>(
key, data, single_sha512_hash);
}
typedef struct {
const char *pszKey;
const char *pszData;
const char *pszMAC;
} testvec_t;
// test cases 1, 2, 3, 4, 6 and 7 of RFC 4231
static const testvec_t vtest[] = {
{
"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"
"0b0b0b0b",
"4869205468657265",
"87aa7cdea5ef619d4ff0b4241a1d6cb0"
"2379f4e2ce4ec2787ad0b30545e17cde"
"daa833b7d6b8a702038b274eaea3f4e4"
"be9d914eeb61f1702e696c203a126854"
},
{
"4a656665",
"7768617420646f2079612077616e7420"
"666f72206e6f7468696e673f",
"164b7a7bfcf819e2e395fbe73b56e0a3"
"87bd64222e831fd610270cd7ea250554"
"9758bf75c05a994a6d034f65f8f0e6fd"
"caeab1a34d4a6b4b636e070a38bce737"
},
{
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaa",
"dddddddddddddddddddddddddddddddd"
"dddddddddddddddddddddddddddddddd"
"dddddddddddddddddddddddddddddddd"
"dddd",
"fa73b0089d56a284efb0f0756c890be9"
"b1b5dbdd8ee81a3655f83e33b2279d39"
"bf3e848279a722c806b485a47e67c807"
"b946a337bee8942674278859e13292fb"
},
{
"0102030405060708090a0b0c0d0e0f10"
"111213141516171819",
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd"
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd"
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd"
"cdcd",
"b0ba465637458c6990e5a8c5f61d4af7"
"e576d97ff94b872de76f8050361ee3db"
"a91ca5c11aa25eb4d679275cc5788063"
"a5f19741120c4f2de2adebeb10a298dd"
},
{
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaa",
"54657374205573696e67204c61726765"
"72205468616e20426c6f636b2d53697a"
"65204b6579202d2048617368204b6579"
"204669727374",
"80b24263c7c1a3ebb71493c1dd7be8b4"
"9b46d1f41b4aeec1121b013783f8f352"
"6b56d037e05f2598bd0fd2215d6a1e52"
"95e64f73f63f0aec8b915a985d786598"
},
{
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaa",
"54686973206973206120746573742075"
"73696e672061206c6172676572207468"
"616e20626c6f636b2d73697a65206b65"
"7920616e642061206c61726765722074"
"68616e20626c6f636b2d73697a652064"
"6174612e20546865206b6579206e6565"
"647320746f2062652068617368656420"
"6265666f7265206265696e6720757365"
"642062792074686520484d414320616c"
"676f726974686d2e",
"e37b6a775dc87dbaa4dfa9f96e5e3ffd"
"debd71f8867289865df5a32d20cdc944"
"b6022cac3c4982b10d5eeb55c3e4de15"
"134676fb6de0446065c97440fa8c6a58"
}
};
data_chunk string_data(const std::string& str)
{
data_chunk result(str.size());
std::copy(str.begin(), str.end(), result.begin());
return result;
}
int main()
{
BITCOIN_ASSERT(single_sha512_hash({0x12, 0x13}) ==
decode_hex_digest<long_hash>("1b09a411dc31ee2284e642a05fd2657ff4a117916e8c16e8fd4b5af5778f91eb4283b01667e388c5aa757172496d41cc209faf6697bc0b371e414175f205dfec"));
data_chunk key, data;
long_hash brown_fox = generate_hmac_sha512(string_data("key"),
string_data("The quick brown fox jumps over the lazy dog"));
BITCOIN_ASSERT(brown_fox == decode_hex_digest<long_hash>("b42af09057bac1e2d41708e48a902e09b5ff7f12ab428a4fe86653c73dd248fb82f948a549f7b791a5b41915ee4d1ec3935357e4e2317250d0372afa2ebeeb3a"));
for (int n=0; n<sizeof(vtest)/sizeof(vtest[0]); n++)
{
data_chunk key = decode_hex(vtest[n].pszKey);
data_chunk data = decode_hex(vtest[n].pszData);
long_hash hmac = decode_hex_digest<long_hash>(vtest[n].pszMAC);
long_hash temp = generate_hmac_sha512(key, data);
BITCOIN_ASSERT(temp == hmac);
}
return 0;
}
| 35.760766 | 194 | 0.701231 | [
"transform"
] |
4e565b92c2a3f38f0d66c4e458ede8d31b65be2b | 23,433 | cpp | C++ | fprime-zmq/zmq-radio/ZmqRadioComponentImpl.cpp | genemerewether/fprime | fcdd071b5ddffe54ade098ca5d451903daba9eed | [
"Apache-2.0"
] | 5 | 2019-10-22T03:41:02.000Z | 2022-01-16T12:48:31.000Z | fprime-zmq/zmq-radio/ZmqRadioComponentImpl.cpp | JPLOpenSource/fprime-sw-Rel1.0 | 18364596c24fa369c938ef8758e5aa945ecc6a9b | [
"Apache-2.0"
] | 27 | 2019-02-07T17:58:58.000Z | 2019-08-13T00:46:24.000Z | fprime-zmq/zmq-radio/ZmqRadioComponentImpl.cpp | JPLOpenSource/fprime-sw-Rel1.0 | 18364596c24fa369c938ef8758e5aa945ecc6a9b | [
"Apache-2.0"
] | 3 | 2019-01-01T18:44:37.000Z | 2019-08-01T01:19:39.000Z | // ======================================================================
// \title ZmqRadioComponentImpl.cpp
// \author dkooi
// \brief cpp file for ZmqRadio implementation class.
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged. Any commercial use must be negotiated with the Office
// of Technology Transfer at the California Institute of Technology.
//
// This software may be subject to U.S. export control laws and
// regulations. By accepting this document, the user agrees to comply
// with all U.S. export laws and regulations. User has the
// responsibility to obtain export licenses, or other export authority
// as may be required before exporting such information to foreign
// countries or providing access to foreign persons.
// ======================================================================
#include <Fw/Types/BasicTypes.hpp>
#include <fprime-zmq/zmq-radio/ZmqRadioComponentImpl.hpp>
//#define DEBUG_PRINT(x,...) printf(x,##__VA_ARGS__)
#define DEBUG_PRINT(x,...)
namespace Zmq{
/* Helper Functions */
namespace {
bool zmqError(const char* from) {
switch (zmq_errno()) {
case EAGAIN:
//printf("%s: ZMQ EAGAIN\n", from);
return true;
case EFSM:
DEBUG_PRINT("%s: ZMQ EFSM", from);
return true;
case ETERM:
DEBUG_PRINT("%s: ZMQ terminate\n",from);
return true;
case ENOTSOCK:
DEBUG_PRINT("%s: ZMQ ENOTSOCK\n",from);
return true;
case EINTR:
DEBUG_PRINT("%s: ZMQ EINTR\n",from);
return false;
case EFAULT:
DEBUG_PRINT("%s: ZMQ EFAULT\n",from);
return false;
case ENOMEM:
DEBUG_PRINT("%s: ZMQ ENOMEM\n", from);
return false;
default:
DEBUG_PRINT("%s: ZMQ error: %s\n",from,zmq_strerror(zmq_errno()));
return true;
}
}
} // namespace
#if FW_OBJECT_NAMES == 1
ZmqRadioComponentImpl :: ZmqRadioComponentImpl(const char* name): ZmqRadioComponentBase(name)
#else
ZmqRadioComponentImpl :: ZmqRadioComponentImpl(void)
#endif
// ZMQ Components
,m_context(0)
,m_pubSocket(0)
,m_cmdSocket(0)
// Telemetry
,m_packetsSent(0)
,m_packetsRecv(0)
,m_numDisconnectRetries(0)
,m_numConnects(0)
,m_numDisconnects(0)
,m_state(this)
{
}
void ZmqRadioComponentImpl::init(NATIVE_INT_TYPE queueDepth, NATIVE_INT_TYPE instance){
ZmqRadioComponentBase::init(queueDepth, instance);
}
void ZmqRadioComponentImpl::preamble(void){
DEBUG_PRINT("Preamble\n");
this->connect();
this->startSubscriptionTask(100);
}
void ZmqRadioComponentImpl::finalizer(void){
// Close Zmq
DEBUG_PRINT("Finalizer\n");
// The transition to disconnect destroys all zmq resources.
// If the zmq resources are destroyed here the subscription thread
// might call transitionDisconnected() and attempt to destroy
// an already destroyed zmq resource.
m_state.transitionDisconnected();
}
ZmqRadioComponentImpl::~ZmqRadioComponentImpl(void){
// Object destruction
DEBUG_PRINT("Destruct\n");
}
void ZmqRadioComponentImpl::open(const char* hostname, U32 port, const char* zmqId){
DEBUG_PRINT("Saving network information\n");
strncpy(this->m_hostname, hostname, strlen(hostname)); // Save hostname
this->m_hostname[strlen(hostname)] = 0; // Null terminate
strncpy(this->m_zmqId, zmqId, strlen(zmqId)); // Save id for socket identification
this->m_zmqId[strlen(zmqId)] = 0; // Null terminate
this->m_serverCmdPort = port; // Save server command port
}
void ZmqRadioComponentImpl::connect(void){
int rc = 0; // Return code
DEBUG_PRINT("Connecting\n");
// Setup context
this->m_context = zmq_ctx_new();
if(not this->m_context){
zmqError("ZmqRadioComponentImpl::connect Error creating context.");
Fw::LogStringArg errArg(zmq_strerror(zmq_errno()));
this->log_WARNING_HI_ZR_ContextError(errArg);
this->m_state.transitionDisconnected();
return;
}
// Create sockets and set options
/* Cmd Socket */
this->m_cmdSocket = zmq_socket(this->m_context, ZMQ_DEALER);
if(not this->m_cmdSocket){
zmqError("ZmqRadioComponentImpl::connect Error creating cmd socket");
Fw::LogStringArg errArg(zmq_strerror(zmq_errno()));
this->log_WARNING_HI_ZR_SocketError(errArg);
this->m_state.transitionDisconnected();
return;
}
zmq_setsockopt(this->m_cmdSocket, ZMQ_IDENTITY, &this->m_zmqId, strlen(this->m_zmqId));
zmq_setsockopt(this->m_cmdSocket, ZMQ_LINGER, &ZMQ_RADIO_LINGER, sizeof(ZMQ_RADIO_LINGER));
zmq_setsockopt(this->m_cmdSocket, ZMQ_RCVTIMEO, &ZMQ_RADIO_RCVTIMEO, sizeof(ZMQ_RADIO_RCVTIMEO));
zmq_setsockopt(this->m_cmdSocket, ZMQ_SNDTIMEO, &ZMQ_RADIO_SNDTIMEO, sizeof(ZMQ_RADIO_SNDTIMEO));
/* Pub Socket */
this->m_pubSocket = zmq_socket(this->m_context, ZMQ_DEALER);
if(not this->m_pubSocket){
zmqError("ZmqRadioComponentImpl::connect Error creating pub socket");
Fw::LogStringArg errArg(zmq_strerror(zmq_errno()));
this->log_WARNING_HI_ZR_SocketError(errArg);
this->m_state.transitionDisconnected();
return;
}
zmq_setsockopt(this->m_pubSocket, ZMQ_IDENTITY, &this->m_zmqId, strlen(this->m_zmqId));
zmq_setsockopt(this->m_pubSocket, ZMQ_LINGER, &ZMQ_RADIO_LINGER, sizeof(ZMQ_RADIO_LINGER));
zmq_setsockopt(this->m_pubSocket, ZMQ_SNDHWM, &ZMQ_RADIO_SNDHWM, sizeof(ZMQ_RADIO_SNDHWM));
zmq_setsockopt(this->m_pubSocket, ZMQ_RCVTIMEO, &ZMQ_RADIO_RCVTIMEO, sizeof(ZMQ_RADIO_RCVTIMEO));
zmq_setsockopt(this->m_pubSocket, ZMQ_SNDTIMEO, &ZMQ_RADIO_SNDTIMEO, sizeof(ZMQ_RADIO_SNDTIMEO));
// Attempt registration
rc = this->registerToServer();
if(rc == -1){
this->m_state.transitionDisconnected();
}else{
this->m_state.transitionConnected();
}
return;
}
NATIVE_INT_TYPE ZmqRadioComponentImpl::registerToServer(){
DEBUG_PRINT("Registering to server\n");
NATIVE_INT_TYPE rc = 0; //Return code
char endpoint[ZMQ_RADIO_ENDPOINT_NAME_SIZE];
// Connect cmd socket to server
(void)snprintf(endpoint,ZMQ_RADIO_ENDPOINT_NAME_SIZE,"tcp://%s:%d",this->m_hostname, this->m_serverCmdPort);
zmq_connect(this->m_cmdSocket, endpoint);
DEBUG_PRINT("SERVER: %s\n", endpoint);
// Send server a registration command
const U8 regMsgSize = ZMQ_RADIO_REG_MSG_SIZE;
const char *reg_msgArr[regMsgSize] = {"REG", "FLIGHT", "ZMQ"};
U8 i;
for(i = 0; i < regMsgSize; i++){
const char *msg = reg_msgArr[i];
size_t len = strlen(msg);
zmq_msg_t z_msg; // Declare zmq msg struct
int rc = zmq_msg_init_size(&z_msg, len); // Allocate msg_t
FW_ASSERT(rc == 0);
memcpy(zmq_msg_data (&z_msg), msg, len); // Copy part into msg
rc = zmq_msg_send(&z_msg, this->m_cmdSocket, ((i == regMsgSize-1) ? 0 : ZMQ_SNDMORE) ); // Set SNDMORE flag to zero if last message
if (-1 == rc) {
zmqError("ZmqRadioComponentImpl::registerToServer Error sending registration message.");
Fw::LogStringArg errArg(zmq_strerror(zmq_errno()));
this->log_WARNING_HI_ZR_SendError(errArg);
return -1;
}
zmq_msg_close(&z_msg);
}
DEBUG_PRINT("Sent reg msg\n");
// Receive server response
const U8 regRespSize = ZMQ_RADIO_REG_RESP_MSG_SIZE; // How many response messages to expect
U32 regStatus = 0;
for(i = 0; i < regRespSize; i++){
zmq_msg_t msg;
zmq_msg_init(&msg);
int size = zmq_msg_recv(&msg, this->m_cmdSocket, 0);
if(size == -1){
zmqError("ZmqRadioComponentImpl::registerToServer Error receiving server registration response.");
Fw::LogStringArg errArg(zmq_strerror(zmq_errno()));
this->log_WARNING_HI_ZR_ReceiveError(errArg);
return -1;
}
// Receive the various msg parts
switch(i){
case 0:
memcpy(®Status, zmq_msg_data(&msg), size);
DEBUG_PRINT("status: %d\n", regStatus);
break;
case 1:
memcpy(&this->m_serverPubPort, zmq_msg_data(&msg), size);
DEBUG_PRINT("serverPubPort: %d\n", this->m_serverPubPort);
break;
case 2:
memcpy(&this->m_serverSubPort, zmq_msg_data(&msg), size);
DEBUG_PRINT("serverSubPort: %d\n", this->m_serverSubPort);
break;
default:
FW_ASSERT(0);
}
zmq_msg_close(&msg);
}
// Check registration status
if(regStatus == 0){
Fw::LogStringArg errArg("Registration Error: Registration status 0\n");
this->log_WARNING_HI_ZR_SocketError(errArg);
return -1;
}
// Connect publish socket
(void)snprintf(endpoint,ZMQ_RADIO_ENDPOINT_NAME_SIZE,"tcp://%s:%d",this->m_hostname, this->m_serverSubPort);
// null terminate
endpoint[ZMQ_RADIO_ENDPOINT_NAME_SIZE-1] = 0;
rc = zmq_connect(this->m_pubSocket,endpoint);
if (-1 == rc) {
zmqError("ZmqRadioComponentImpl::registerToServer Error connecting publish socket.");
Fw::LogStringArg errArg(zmq_strerror(zmq_errno()));
this->log_WARNING_HI_ZR_SocketError(errArg);
return -1;
}
return 0;
}
/* Handlers */
void ZmqRadioComponentImpl::reconnect_handler(NATIVE_INT_TYPE portNum, NATIVE_UINT_TYPE context ){
switch(this->m_state.get()){
case State::ZMQ_RADIO_CONNECTED_STATE:
// We are connected, do nothing
DEBUG_PRINT("reconnect_handler: Is connected. Do nothing.\n");
break;
case State::ZMQ_RADIO_DISCONNECTED_STATE:
// We are disconnected, attempt reconnection
DEBUG_PRINT("reconnect_handler: Not connected. Reconnect.\n");
this->connect();
break;
default:
FW_ASSERT(0);
}
// Send out telemetry
this->tlmWrite_ZR_NumDisconnects(this->m_numDisconnects);
this->tlmWrite_ZR_NumConnects(this->m_numConnects);
this->tlmWrite_ZR_NumDisconnectRetries(this->m_numDisconnectRetries);
this->tlmWrite_ZR_PktsSent(this->m_packetsSent);
this->tlmWrite_ZR_PktsRecv(this->m_packetsRecv);
}
void ZmqRadioComponentImpl::downlinkPort_handler(
NATIVE_INT_TYPE portNum,
Fw::ComBuffer &data,
U32 context
)
{
int rc = 0;
switch(this->m_state.get()){
case State::ZMQ_RADIO_CONNECTED_STATE:
rc = zmqSocketWriteComBuffer(this->m_pubSocket, data);
break;
case State::ZMQ_RADIO_DISCONNECTED_STATE:
// Drop packets
break;
default:
FW_ASSERT(0);
}
}
void ZmqRadioComponentImpl::fileDownlinkBufferSendIn_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::Buffer fwBuffer
)
{
switch(this->m_state.get()){
case State::ZMQ_RADIO_CONNECTED_STATE:
// Write files down
this->zmqSocketWriteFilePacket(this->m_pubSocket, fwBuffer);
break;
case State::ZMQ_RADIO_DISCONNECTED_STATE:
// Drop packets
break;
default:
FW_ASSERT(0);
}
}
/* FPrime ZMQ Wrapper functions */
NATIVE_INT_TYPE ZmqRadioComponentImpl::zmqSocketWriteComBuffer(void* zmqSocket, Fw::ComBuffer &data) {
//printf("Data Size: 0x%04x\n", data.getBuffLength());
//printf("Data Desc: 0x%04x\n", *(U32*)data.getBuffAddr());
U32 data_net_size = htonl(data.getBuffLength());
U8 buf[sizeof(data_net_size) + data.getBuffLength()]; // Create a buffer to hold entire packet
memcpy(buf, &data_net_size, sizeof(data_net_size)); // Copy size
memcpy(buf + sizeof(data_net_size), (U8*)data.getBuffAddr(), data.getBuffLength()); // Copy packet
zmq_msg_t fPrimePacket;
zmq_msg_init_size(&fPrimePacket, sizeof(buf));
memcpy(zmq_msg_data(&fPrimePacket), buf, sizeof(buf));
this->zmqSocketWrite(zmqSocket, &fPrimePacket);
return 1;
}
NATIVE_INT_TYPE ZmqRadioComponentImpl::zmqSocketWriteFilePacket(void* zmqSocket, Fw::Buffer &buffer){
U32 bufferSize = buffer.getsize();
U32 packetSize = htonl(bufferSize + 4); // Size of buffer plus description
U32 desc = 3; // File desc
U8 downlinkBuffer[sizeof(packetSize) + sizeof(desc) + bufferSize]; // Create a buffer for header and packet
memcpy(downlinkBuffer, &packetSize, sizeof(packetSize));
memcpy(downlinkBuffer + sizeof(packetSize), &desc, sizeof(desc));
memcpy(downlinkBuffer + sizeof(packetSize) + sizeof(desc) , (U8*)buffer.getdata(), bufferSize);
zmq_msg_t fPrimePacket;
zmq_msg_init_size(&fPrimePacket, sizeof(downlinkBuffer));
memcpy(zmq_msg_data(&fPrimePacket), downlinkBuffer, sizeof(downlinkBuffer));
this->zmqSocketWrite(zmqSocket, &fPrimePacket);
return 1;
}
void ZmqRadioComponentImpl::zmqSocketWrite(void* zmqSocket, zmq_msg_t* fPrimePacket){
int rc = zmq_msg_send(fPrimePacket, zmqSocket, 0);
zmq_msg_close(fPrimePacket);
if(rc == -1){
zmqError("zmqSocketWrite Error\n");
if(zmq_errno() == EAGAIN){ // HWM reached and timed out. Assume connection down.
this->m_state.transitionDisconnected();
}else{
Fw::LogStringArg errArg(zmq_strerror(zmq_errno()));
this->log_WARNING_HI_ZR_SendError(errArg);
}
}else{
// Success. Increase packets sent
this->m_packetsSent++;
}
}
NATIVE_INT_TYPE ZmqRadioComponentImpl::zmqSocketRead(void* zmqSocket, U8* buf, NATIVE_INT_TYPE size) {
NATIVE_INT_TYPE rc = 0; // return code
NATIVE_INT_TYPE total=0;
// Ignore the zmq identifier
zmq_msg_t zmqID;
zmq_msg_init(&zmqID);
rc = zmq_msg_recv(&zmqID, zmqSocket, 0);
zmq_msg_close(&zmqID);
if(rc == -1){
if(zmq_errno() == EAGAIN){ // Recv call timed out
return ZMQ_SOCKET_READ_EAGAIN;
}else{ // A more serious error has occured
zmqError("ZmqRadioComponentImpl::zmqSocketRead: zmq_msg_recv error.");
Fw::LogStringArg errArg(zmq_strerror(zmq_errno()));
this->log_WARNING_HI_ZR_ReceiveError(errArg);
return ZMQ_SOCKET_READ_ERROR;
}
}
// Receive FPrime packet
zmq_msg_t fPrimePacket;
zmq_msg_init(&fPrimePacket);
total = zmq_msg_recv(&fPrimePacket, zmqSocket, 0);
if(total == -1){
if(zmq_errno() == EAGAIN){ // Recv timed out
return ZMQ_SOCKET_READ_EAGAIN;
}else{
zmqError("ZmqRadioComponentImpl::zmqSocketRead: zmq_msg_recv error.");
Fw::LogStringArg errArg(zmq_strerror(zmq_errno()));
this->log_WARNING_HI_ZR_ReceiveError(errArg);
return ZMQ_SOCKET_READ_ERROR;
}
}else{ // Success. Copy packet data into buf, close message, and increase number packets received
memcpy(buf, zmq_msg_data(&fPrimePacket), total);
zmq_msg_close(&fPrimePacket);
this->m_packetsRecv++;
}
return total;
}
void ZmqRadioComponentImpl::startSubscriptionTask(I32 priority){
Fw::EightyCharString name("ScktRead");
// Spawn read task
Os::Task::TaskStatus stat = this->subscriptionTask.start(name,0, priority,10*1024, ZmqRadioComponentImpl::subscriptionTaskRunnable, this);
FW_ASSERT(Os::Task::TASK_OK == stat,static_cast<NATIVE_INT_TYPE>(stat));
}
void ZmqRadioComponentImpl::subscriptionTaskRunnable(void* ptr){
DEBUG_PRINT("Entering subscriptionTask\n");
fflush(stderr);
// Get reference to component
ZmqRadioComponentImpl* comp = (ZmqRadioComponentImpl*) ptr;
void* subSocket = 0; // Zmq Subscription socket
U32 packetDelimiter;
U32 packetSize;
U32 packetDesc;
U8 buf[FW_COM_BUFFER_MAX_SIZE];
while(1){
U16 buf_ptr = 0; // Reset buffer pointer
switch(comp->m_state.get()){
case State::ZMQ_RADIO_DISCONNECTED_STATE:
// Idle
break;
case State::ZMQ_RADIO_CONNECTED_STATE:
if(subSocket == 0){ // Create subSocket if disconnected
subSocket = zmq_socket(comp->m_context, ZMQ_ROUTER);
if(subSocket == 0){
zmqError("ZmqRadioComponentImpl::connect Error creating sub socket");
Fw::LogStringArg errArg(zmq_strerror(zmq_errno()));
comp->log_WARNING_HI_ZR_SocketError(errArg);
// Close this thread's zmq resource
zmq_close(subSocket);
subSocket = 0;
comp->m_state.transitionDisconnected();
break;
}
zmq_setsockopt(subSocket, ZMQ_IDENTITY, &comp->m_zmqId, strlen(comp->m_zmqId));
zmq_setsockopt(subSocket, ZMQ_LINGER, &ZMQ_RADIO_LINGER, sizeof(ZMQ_RADIO_LINGER));
zmq_setsockopt(subSocket, ZMQ_RCVTIMEO, &ZMQ_RADIO_RCVTIMEO, sizeof(ZMQ_RADIO_RCVTIMEO));
zmq_setsockopt(subSocket, ZMQ_SNDTIMEO, &ZMQ_RADIO_SNDTIMEO, sizeof(ZMQ_RADIO_SNDTIMEO));
// Connect subscribe socket
char endpoint[ZMQ_RADIO_ENDPOINT_NAME_SIZE];
(void)snprintf(endpoint, ZMQ_RADIO_ENDPOINT_NAME_SIZE, "tcp://%s:%d", comp->m_hostname, comp->m_serverPubPort);
int rc = zmq_connect(subSocket,endpoint);
if (-1 == rc) {
zmqError("ZmqRadioComponentImpl::subscriptionTaskRunnable: Error connecting subscribe socket.");
Fw::LogStringArg errArg(zmq_strerror(zmq_errno()));
comp->log_WARNING_HI_ZR_SocketError(errArg);
// Close this thread's zmq resource
zmq_close(subSocket);
subSocket = 0;
comp->m_state.transitionDisconnected();
break;
}
} // if subSocket == 0
// Read incoming zmq message
I32 msgSize = 0;
msgSize = comp->zmqSocketRead(subSocket, buf, (NATIVE_INT_TYPE)FW_COM_BUFFER_MAX_SIZE);
if(msgSize > 0){ // Successful read
// Pass
}else if(msgSize == ZMQ_SOCKET_READ_ERROR){ // A serious zmq error
// Close this thread's zmq resource
zmq_close(subSocket);
subSocket = 0;
comp->m_state.transitionDisconnected();
break;
}else if(msgSize == ZMQ_SOCKET_READ_EAGAIN){ // Socket has timed out
break; // Break switch and retry
}
// Extract packet delimiter
packetDelimiter = *(U32*)(buf+buf_ptr);
packetDelimiter = ntohl(packetDelimiter);
// correct for network order
packetDelimiter = ntohl(packetDelimiter);
//printf("Packet delimiter: 0x%04x\n",packetDelimiter);
// if magic number to quit, exit loop
if (packetDelimiter == 0xA5A5A5A5) {
(void) printf("packetDelimiter = 0x%x\n", packetDelimiter);
//break;
} else if (packetDelimiter != 0x5A5A5A5A) {
(void) printf("Unexpected delimiter 0x%08X\n",packetDelimiter);
// just keep reading until a delimiter is found
continue;
}
// Increment buffer pointer
buf_ptr += sizeof(packetDelimiter);
// Extract FPrime packet size
packetSize = *(U32*)(buf + buf_ptr);
packetSize = ntohl(packetSize);
//printf("Packet Size: 0x%04x\n", packetSize);
// Increment buffer pointer
buf_ptr += sizeof(packetSize);
// Extract FPrime packet description
packetDesc = *(U32*)(buf + buf_ptr);
packetDesc = ntohl(packetDesc);
// Increment buffer pointer
buf_ptr += sizeof(packetDesc);
switch(packetDesc) {
case Fw::ComPacket::FW_PACKET_COMMAND:
{
U8 cmdPacket[FW_COM_BUFFER_MAX_SIZE];
// check size of command
if (packetSize > FW_COM_BUFFER_MAX_SIZE) {
(void) printf("Packet to large! :%d\n",packetSize);
// might as well wait for the next packet
break;
}
/*
cmdBuffer[3] = packetDesc & 0xff;
cmdBuffer[2] = (packetDesc & 0xff00) >> 8;
cmdBuffer[1] = (packetDesc & 0xff0000) >> 16;
cmdBuffer[0] = (packetDesc & 0xff000000) >> 24;
*/
// Add description
packetDesc = ntohl(packetDesc); // Is this the same as above?
memcpy(cmdPacket, &packetDesc, sizeof(packetDesc));
// Add command data [ Size of cmd data is packet size - packetDesc size ]
memcpy(cmdPacket + sizeof(packetDesc), buf + buf_ptr, packetSize - sizeof(packetDesc));
if (comp->isConnected_uplinkPort_OutputPort(0)) {
Fw::ComBuffer cmdBuffer(cmdPacket, packetSize);
comp->uplinkPort_out(0,cmdBuffer,0);
}
break;
}
case Fw::ComPacket::FW_PACKET_FILE:
{
// Get Buffer
Fw::Buffer packet_buffer = comp->fileUplinkBufferGet_out(0, packetSize - sizeof(packetDesc));
U8* data_ptr = (U8*)packet_buffer.getdata();
/*
for(uint32_t i =0; i < bytesRead; i++){
(void) printf("IN_DATA:%02x\n", data_ptr[i]);
}
*/
// Read file packet minus description. Same as above?
memcpy(data_ptr, buf + buf_ptr, packetSize - sizeof(packetDesc));
if (comp->isConnected_fileUplinkBufferSendOut_OutputPort(0)) {
comp->fileUplinkBufferSendOut_out(0, packet_buffer);
}
break;
}
default:
FW_ASSERT(0);
}
break;
} // State switch
} // while 1
}
/* State Class Implementation */
ZmqRadioComponentImpl::State::State(ZmqRadioComponentImpl* parent):
state(ZMQ_RADIO_DISCONNECTED_STATE),
m_parent(parent)
{
}
U8 ZmqRadioComponentImpl::State::get(){
return this->state;
}
void ZmqRadioComponentImpl::State::transitionConnected(){
switch(this->state){
case ZMQ_RADIO_CONNECTED_STATE:
// Already connected
break;
case ZMQ_RADIO_DISCONNECTED_STATE:
// Successful reconnection
this->state = ZMQ_RADIO_CONNECTED_STATE;
this->m_parent->log_ACTIVITY_HI_ZR_Connection();
// Clear throttled logs
this->m_parent->log_WARNING_HI_ZR_ReceiveError_ThrottleClear();
this->m_parent->log_WARNING_HI_ZR_SendError_ThrottleClear();
this->m_parent->m_numConnects++;
break;
default:
FW_ASSERT(0);
}
}
void ZmqRadioComponentImpl::State::transitionDisconnected(){
/*
This function has a mutex beacuse either the main thread or the subscription thread
can call transitionDisconnected().
*/
// Ensure transition calls are atomic
static Os::Mutex mutex;
mutex.lock();
// Release ZMQ resources to prepare for reconnect attempts
zmq_close(this->m_parent->m_pubSocket);
zmq_close(this->m_parent->m_cmdSocket);
zmq_term(this->m_parent->m_context);
switch(this->state){
case ZMQ_RADIO_CONNECTED_STATE:
DEBUG_PRINT("Disconnecting\n");
// Disconnection experienced
this->state = ZMQ_RADIO_DISCONNECTED_STATE;
this->m_parent->log_WARNING_HI_ZR_Disconnection();
this->m_parent->m_numDisconnects++;
break;
case ZMQ_RADIO_DISCONNECTED_STATE:
// Reconnection failed
this->m_parent->m_numDisconnectRetries++;
break;
default:
FW_ASSERT(0);
}
mutex.unLock();
}
} // namespace Zmq
| 31.453691 | 143 | 0.648615 | [
"object"
] |
4e571eb1f0fe0f9b37c674479bbbd06dacbad49f | 12,721 | cpp | C++ | plugins/UserMgr/src/LogonUser.cpp | andry81/nsisplus--NsisSetupDev | 9ec6d90cf5100bc2ea9a0aabe841d2119a308e4a | [
"MIT"
] | null | null | null | plugins/UserMgr/src/LogonUser.cpp | andry81/nsisplus--NsisSetupDev | 9ec6d90cf5100bc2ea9a0aabe841d2119a308e4a | [
"MIT"
] | null | null | null | plugins/UserMgr/src/LogonUser.cpp | andry81/nsisplus--NsisSetupDev | 9ec6d90cf5100bc2ea9a0aabe841d2119a308e4a | [
"MIT"
] | null | null | null | #include "LogonUser.hpp"
#include "nsis_tchar.h"
#include "UserMgr.h"
#include <stdint.h>
#include <list>
#include <algorithm>
#include <boost/functional/hash.hpp>
class LogonAsyncRequestParams
{
public:
std::string remote;
std::string user;
std::string pass;
LogonAsyncRequestParams(const std::string & remote_, const std::string & user_, const std::string & pass_) :
remote(remote_),
user(user_),
pass(pass_)
{}
};
std::size_t hash_value(const LogonAsyncRequestParams & params)
{
std::size_t seed = 0;
boost::hash_combine(seed, params.remote);
boost::hash_combine(seed, params.user);
boost::hash_combine(seed, params.pass);
return seed;
}
struct LogonAsyncRequestSync
{
boost::mutex req_status_mutex; // locks status change
LogonAsyncRequestSync()
{}
private:
// not copyable
LogonAsyncRequestSync(const LogonAsyncRequestSync &);
LogonAsyncRequestSync & operator=(const LogonAsyncRequestSync &);
};
typedef boost::shared_ptr<LogonAsyncRequestSync> LogonAsyncRequestSyncPtr;
struct LogonAsyncRequest
{
LogonAsyncRequestSyncPtr sync; // synchronization primitives
AsyncRequestStatus req_status;
DWORD req_last_error;
std::size_t req_hash;
LogonAsyncRequestParams req_params;
LogonAsyncRequestThreadPtr thread_ptr;
DWORD wnet_error_code;
char wnet_error_str[256]; // last, just in case of buffer overflow
LogonAsyncRequest(std::size_t req_hash_, const LogonAsyncRequestParams & req_params_) :
req_hash(req_hash_),
req_params(req_params_)
{
reset();
}
void join()
{
if (thread_ptr.get()) {
thread_ptr->join(); // just in case, wait for exit before a new call
}
}
void reset()
{
sync = LogonAsyncRequestSyncPtr(new LogonAsyncRequestSync());
req_status = ASYNC_REQUEST_STATUS_UNINIT;
req_last_error = 0;
wnet_error_code = 0;
wnet_error_str[0] = '\0';
}
void resetThread(const LogonAsyncRequestThreadPtr & thread_ptr);
};
typedef std::list<LogonAsyncRequest> LogonAsyncQueueList;
class LogonAsyncRequestThreadData
{
public:
LogonAsyncRequest & req;
LogonAsyncRequestParams req_params;
LogonAsyncRequestThreadData(LogonAsyncRequest & req_) :
req(req_),
req_params(req_.req_params)
{
}
void operator()();
};
class LogonAsyncRequestPred
{
public:
std::size_t req_hash;
LogonAsyncRequestPred(const LogonAsyncRequestHandle & req_handle) :
req_hash(req_handle.handle)
{}
bool operator()(const LogonAsyncRequest & ref)
{
return req_hash == ref.req_hash;
}
};
boost::mutex g_logon_net_share_async_queue_mutex;
// CAUTION:
// The container does not have a cleanup procedure, so it will only increase in size!
LogonAsyncQueueList g_logon_net_share_async_queue_list;
boost::mutex g_wnet_error_mutex;
_LogonWNetErrorLocker g_wnet_error_locker;
// unsafe reset
void LogonAsyncRequest::resetThread(const LogonAsyncRequestThreadPtr & thread_ptr_)
{
thread_ptr = thread_ptr_;
}
LogonAsyncRequestHandle _LogonNetShareAsync(const std::string & remote, const std::string & user, const std::string & pass)
{
const LogonAsyncRequestParams & req_params = LogonAsyncRequestParams(remote, user, pass);
const std::size_t req_hash = hash_value(req_params);
LogonAsyncRequestHandle req_handle = LogonAsyncRequestHandle();
req_handle.handle = req_hash;
{
LogonAsyncRequest * preq = NULL;
boost::mutex::scoped_lock lock(g_logon_net_share_async_queue_mutex);
const LogonAsyncQueueList::iterator foundIt = std::find_if(g_logon_net_share_async_queue_list.begin(), g_logon_net_share_async_queue_list.end(), LogonAsyncRequestPred(req_handle));
if (foundIt != g_logon_net_share_async_queue_list.end()) {
LogonAsyncRequest & req = *foundIt;
{
boost::mutex::scoped_lock lock(req.sync->req_status_mutex);
if (req.req_status < 0) { // is busy
return req_handle;
}
req.join();
} // must release lock before it's storage reset
// reuse old request
req.reset();
preq = &req;
}
else {
// create new request
g_logon_net_share_async_queue_list.push_back(LogonAsyncRequest(req_hash, req_params));
preq = &g_logon_net_share_async_queue_list.back();
}
preq->resetThread(LogonAsyncRequestThreadPtr(new LogonAsyncRequestThread(LogonAsyncRequestThreadData(*preq))));
}
return req_handle;
}
void _LockRequestStatus(LogonAsyncRequest & req)
{
req.sync->req_status_mutex.lock();
}
void _UnlockRequestStatus(LogonAsyncRequest & req)
{
req.sync->req_status_mutex.unlock();
}
// CAUTION:
// 1. No object unwinding, otherwise __try/__finally won't compile!
// 2. __try/__finally replaces RAII, otherwise C++ code could not be called from pure C code!
void LogonAsyncRequestThreadData::operator()()
{
boost::this_thread::interruption_point();
{
boost::mutex::scoped_lock lock(req.sync->req_status_mutex);
req.req_status = ASYNC_REQUEST_STATUS_PENDING;
}
NETRESOURCEA resource = NETRESOURCEA();
HANDLE hLogonToken = NULL;
_LogonWNetErrorLocker wnet_error_locker;
const DWORD last_error =
_LogonUser(req_params.remote, req_params.user, req_params.pass, wnet_error_locker, boost::this_thread::interruption_point);
{
boost::mutex::scoped_lock lock(req.sync->req_status_mutex);
switch (last_error) {
case ERROR_OPERATION_ABORTED:
req.req_status = ASYNC_REQUEST_STATUS_ABORTED;
break;
case NO_ERROR:
default: // treat all other as accompished
req.req_status = ASYNC_REQUEST_STATUS_ACCOMPLISH;
}
req.req_last_error = last_error;
req.wnet_error_code = wnet_error_locker.wnet_error_code;
_tcsnccpy(req.wnet_error_str, wnet_error_locker.wnet_error_str, wnet_error_locker.wnet_error_str_buf_size);
}
}
DWORD _LogonUser(const std::string & remote, const std::string & user, const std::string & pass, _LogonWNetErrorLocker & wnet_error_locker, void (* interruption_func)())
{
DWORD result = 0;
NETRESOURCEA resource;
LPUSER_INFO_0 ui = 0;
HANDLE hLogonToken = NULL;
// buffers at the end
WCHAR u_remoteid[256];
WCHAR u_userid[256];
// drop last error code
void (* wnet_error_unlock)() = 0;
DWORD * wnet_error_code = 0;
char * wnet_error_str = 0;
DWORD wnet_error_str_buf_size = 0;
__try {
wnet_error_locker(0, wnet_error_unlock, wnet_error_code, wnet_error_str, wnet_error_str_buf_size);
}
__finally {
if (wnet_error_unlock) wnet_error_unlock();
}
memset(&resource, 0, sizeof(resource));
resource.dwScope = RESOURCE_GLOBALNET;
resource.dwType = RESOURCETYPE_ANY;
resource.dwDisplayType = RESOURCEDISPLAYTYPE_GENERIC;
resource.dwUsage = RESOURCEUSAGE_CONNECTABLE;
memset(u_remoteid, 0, sizeof(u_remoteid));
memset(u_userid, 0, sizeof(u_userid));
swprintf(u_remoteid, L"%S", remote.c_str());
swprintf(u_userid, L"%S", user.c_str());
__try {
// WARNING:
// 1. We have to use the call to NetUserGetInfo because in some systems the WNetAddConnection2
// WOULD NOT return any error on the user what actually DOES NOT EXIST BUT EXISTANCE CAN BE CHECKED BY THE NetUserGetInfo.
// 2. On other hand some systems reports "Access Denided" from the NetUserGetInfo, but seems the WNetAddConnection2
// reports an error in that case (for example, code 1385: Logon failure: the user has not been granted the requested logon type at this computer).
// So we have to merge both exclusively successful methods for 2 systems to gain a common success approach for both.
result = NetUserGetInfo(u_remoteid, u_userid, 0, (LPBYTE *)&ui);
// Do exit only on specific success return codes:
// 2221: "The user name could not be found"
if (result == 2221) {
return result;
}
if (interruption_func) interruption_func();
// Otherwise try to call the WNetAddConnection2 function...
__try {
SetLastError(0); // just in case
result = ( // to hold resource.lpRemoteName potential destruction until the WNetAddConnection2 return
resource.lpRemoteName = const_cast<LPSTR>(remote.c_str()),
WNetAddConnection2(&resource, pass.c_str(), user.c_str(), CONNECT_TEMPORARY)
);
if (result == NO_ERROR) {
// undocumented: for cases where WNetAddConnection2 does not report an error like:
// "Overlapped I/O operation is in progress"
result = GetLastError();
}
__try {
wnet_error_locker(1, wnet_error_unlock, wnet_error_code, wnet_error_str, wnet_error_str_buf_size);
// save wnet error
WNetGetLastError(wnet_error_code, wnet_error_str, wnet_error_str_buf_size, 0, 0);
}
__finally {
if (wnet_error_unlock) wnet_error_unlock();
}
if (interruption_func) interruption_func();
// continue on "Overllaped I/O operation is in progress"
if (result != NO_ERROR && result != 997) {
return result;
}
__try {
SetLastError(0); // just in case
// just in case call
LogonUser(user.c_str(),
remote.c_str(),
pass.c_str(),
LOGON32_LOGON_NEW_CREDENTIALS,
LOGON32_PROVIDER_DEFAULT,
&hLogonToken);
result = GetLastError();
}
__finally {
CloseHandle(hLogonToken);
}
}
__finally {
WNetCancelConnection2(remote.c_str(), 0, TRUE); // might be a race condition if calls from different thread!
}
}
__finally {
if (ui != NULL) {
NetApiBufferFree(ui);
ui = NULL; // just in case
}
}
return result;
}
AsyncRequestStatus _GetLogonNetShareAsyncStatus(LogonAsyncRequestHandle req_handle, DWORD * last_error, DWORD * wnet_error_code, char wnet_error_str[256])
{
if (last_error) *last_error = NO_ERROR;
if (wnet_error_code) *wnet_error_code = 0;
if (wnet_error_str) wnet_error_str[0] = '\0';
boost::mutex::scoped_lock lock(g_logon_net_share_async_queue_mutex);
const LogonAsyncQueueList::iterator foundIt = std::find_if(g_logon_net_share_async_queue_list.begin(), g_logon_net_share_async_queue_list.end(), LogonAsyncRequestPred(req_handle));
if (foundIt == g_logon_net_share_async_queue_list.end()) {
return ASYNC_REQUEST_STATUS_NOT_FOUND;
}
LogonAsyncRequest & req = *foundIt;
boost::mutex::scoped_lock lock2(req.sync->req_status_mutex);
if (last_error) *last_error = req.req_last_error;
if (wnet_error_code) *wnet_error_code = req.wnet_error_code;
if (wnet_error_str) _tcsnccpy(wnet_error_str, req.wnet_error_str, sizeof(req.wnet_error_str)/sizeof(req.wnet_error_str[0]));
return req.req_status;
}
LogonAsyncRequestThreadPtr _GetLogonNetShareAsyncRequestThread(LogonAsyncRequestHandle req_handle)
{
boost::mutex::scoped_lock lock(g_logon_net_share_async_queue_mutex);
const LogonAsyncQueueList::iterator foundIt = std::find_if(g_logon_net_share_async_queue_list.begin(), g_logon_net_share_async_queue_list.end(), LogonAsyncRequestPred(req_handle));
if (foundIt == g_logon_net_share_async_queue_list.end()) {
return NULL;
}
return foundIt->thread_ptr;
}
LogonAsyncRequest * _GetLogonNetShareAsyncRequest(LogonAsyncRequestHandle req_handle)
{
boost::mutex::scoped_lock lock(g_logon_net_share_async_queue_mutex);
const LogonAsyncQueueList::iterator foundIt = std::find_if(g_logon_net_share_async_queue_list.begin(), g_logon_net_share_async_queue_list.end(), LogonAsyncRequestPred(req_handle));
if (foundIt == g_logon_net_share_async_queue_list.end()) {
return NULL;
}
return &*foundIt;
}
DWORD _CancelLogonNetShareAsyncRequest(LogonAsyncRequestHandle req_handle)
{
DWORD result = 0;
//LogonAsyncRequestThreadPtr thread_ptr = _GetLogonNetShareAsyncRequestThread(req_handle);
//if (thread_ptr.get() == NULL) {
// result = 0x20000000 | 1;
//}
//else if (!CancelSynchronousIo(thread_ptr->native_handle())) {
// result = GetLastError();
//}
// Nothing above has worked, have no choice to just terminate the request thread
LogonAsyncRequest * preq = _GetLogonNetShareAsyncRequest(req_handle);
if (preq == NULL) {
result = 0x20000000 | 1;
}
else {
boost::mutex::scoped_lock lock2(preq->sync->req_status_mutex);
// terminate only if status is still in busy state
if(preq->req_status < 0) {
// update status at first
preq->req_status = ASYNC_REQUEST_STATUS_CANCELLED;
HANDLE thread_handle = preq->thread_ptr->native_handle();
// at first try cancel through Win32 API
WNetCancelConnection2(preq->req_params.remote.c_str(), 0, TRUE);
preq->thread_ptr->interrupt(); // just in case
preq->thread_ptr->detach();
SetLastError(0); // just in case
if (!TerminateThread(thread_handle, 0)) {
result = GetLastError();
}
}
}
return result;
}
| 30.073286 | 183 | 0.725729 | [
"object"
] |
4e5c3e5741739e62fb33ee3a3ff84cec57810099 | 28,686 | cpp | C++ | Sources/Internal/Render/RenderHelper.cpp | stinvi/dava.engine | 2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e | [
"BSD-3-Clause"
] | 26 | 2018-09-03T08:48:22.000Z | 2022-02-14T05:14:50.000Z | Sources/Internal/Render/RenderHelper.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | null | null | null | Sources/Internal/Render/RenderHelper.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | 45 | 2018-05-11T06:47:17.000Z | 2022-02-03T11:30:55.000Z | #include "Render/Renderer.h"
#include "Render/RenderHelper.h"
#include "Render/Highlevel/RenderPassNames.h"
#include "Render/DynamicBufferAllocator.h"
#include "Material/NMaterial.h"
#include "Debug/ProfilerGPU.h"
const DAVA::float32 ISO_X = 0.525731f;
const DAVA::float32 ISO_Z = 0.850650f;
std::array<DAVA::Vector3, 12> gIcosaVertexes = {
DAVA::Vector3(-ISO_X, 0.0, ISO_Z),
DAVA::Vector3(ISO_X, 0.0, ISO_Z),
DAVA::Vector3(-ISO_X, 0.0, -ISO_Z),
DAVA::Vector3(ISO_X, 0.0, -ISO_Z),
DAVA::Vector3(0.0, ISO_Z, ISO_X),
DAVA::Vector3(0.0, ISO_Z, -ISO_X),
DAVA::Vector3(0.0, -ISO_Z, ISO_X),
DAVA::Vector3(0.0, -ISO_Z, -ISO_X),
DAVA::Vector3(ISO_Z, ISO_X, 0.0),
DAVA::Vector3(-ISO_Z, ISO_X, 0.0),
DAVA::Vector3(ISO_Z, -ISO_X, 0.0),
DAVA::Vector3(-ISO_Z, -ISO_X, 0.0)
};
std::array<DAVA::uint16, 60> gWireIcosaIndexes = {
0, 1, 1, 4, 4, 8, 8, 5, 5, 3, 3, 2, 2, 7, 7, 11, 11, 6, 6, 0,
0, 4, 4, 5, 5, 2, 2, 11, 11, 0, 1, 8, 8, 3, 3, 7, 7, 6, 6, 1,
9, 0, 9, 4, 9, 5, 9, 2, 9, 11, 10, 1, 10, 8, 10, 3, 10, 7, 10, 6,
};
std::array<DAVA::uint16, 60> gSolidIcosaIndexes = {
0, 4, 1, 0, 9, 4, 9, 5, 4, 4, 5, 8, 4, 8, 1,
8, 10, 1, 8, 3, 10, 5, 3, 8, 5, 2, 3, 2, 7, 3,
7, 10, 3, 7, 6, 10, 7, 11, 6, 11, 0, 6, 0, 1, 6,
6, 1, 10, 9, 0, 11, 9, 11, 2, 9, 2, 5, 7, 2, 11,
};
std::array<DAVA::uint16, 24> gWireBoxIndexes = {
0, 2, 2, 6, 6, 3, 3, 0,
1, 4, 4, 7, 7, 5, 5, 1,
0, 1, 2, 4, 6, 7, 3, 5,
};
std::array<DAVA::uint16, 36> gSolidBoxIndexes = {
0, 6, 3, 0, 2, 6, 4, 5, 7, 4, 1, 5,
2, 7, 6, 2, 4, 7, 1, 3, 5, 1, 0, 3,
3, 7, 5, 3, 6, 7, 1, 2, 0, 1, 4, 2,
};
std::array<DAVA::uint16, 48> gWireBoxCornersIndexes = {
0, 8, 0, 9, 0, 10, 1, 11, 1, 12, 1, 13,
2, 14, 2, 15, 2, 16, 3, 17, 3, 18, 3, 19,
4, 20, 4, 21, 4, 22, 5, 23, 5, 24, 5, 25,
6, 26, 6, 27, 6, 28, 7, 29, 7, 30, 7, 31,
};
std::array<DAVA::uint16, 72> gSolidBoxCornersIndexes = {
0, 8, 10, 0, 10, 9, 0, 9, 8, 1, 12, 13, 1, 11, 12, 1, 13, 11,
2, 14, 16, 2, 16, 15, 2, 15, 14, 3, 19, 17, 3, 17, 18, 3, 18, 19,
4, 22, 21, 4, 20, 22, 4, 21, 20, 5, 23, 25, 5, 24, 23, 5, 25, 24,
6, 27, 26, 6, 26, 28, 6, 28, 27, 7, 29, 30, 7, 30, 31, 7, 31, 29,
};
std::array<DAVA::uint16, 16> gWireArrowIndexes = {
0, 1, 0, 2, 0, 3, 0, 4,
1, 2, 2, 3, 3, 4, 4, 1,
};
std::array<DAVA::uint16, 18> gSolidArrowIndexes = {
0, 1, 2, 0, 2, 3, 0, 3, 4,
0, 4, 1, 1, 4, 2, 2, 4, 3,
};
namespace DAVA
{
RenderHelper::RenderHelper()
: drawLineCommand(COMMAND_DRAW_LINE)
, drawIcosahedronCommand(COMMAND_DRAW_ICOSA)
, drawArrowCommand(COMMAND_DRAW_ARROW)
, drawCircleCommand(COMMAND_DRAW_CIRCLE)
, drawBoxCommand(COMMAND_DRAW_BOX)
{
rhi::VertexLayout layout;
layout.AddElement(rhi::VS_POSITION, 0, rhi::VDT_FLOAT, 3);
layout.AddElement(rhi::VS_COLOR, 0, rhi::VDT_UINT8N, 4);
coloredVertexLayoutUID = rhi::VertexLayout::UniqueId(layout);
for (NMaterial*& material : materials)
material = new NMaterial();
materials[DRAW_WIRE_DEPTH]->SetFXName(NMaterialName::VERTEXCOLOR_OPAQUE);
materials[DRAW_SOLID_DEPTH]->SetFXName(NMaterialName::VERTEXCOLOR_ALPHABLEND);
materials[DRAW_WIRE_NO_DEPTH]->SetFXName(NMaterialName::VERTEXCOLOR_OPAQUE_NODEPTHTEST);
materials[DRAW_SOLID_NO_DEPTH]->SetFXName(NMaterialName::VERTEXCOLOR_ALPHABLEND_NODEPTHTEST);
for (NMaterial* material : materials)
material->PreBuildMaterial(PASS_FORWARD);
Clear();
}
void RenderHelper::InvalidateMaterials()
{
for (NMaterial*& material : materials)
material->InvalidateRenderVariants();
}
RenderHelper::~RenderHelper()
{
for (int32 i = 0; i < DRAW_TYPE_COUNT; ++i)
SafeRelease(materials[i]);
}
RenderHelper::RenderStruct RenderHelper::AllocateRenderStruct(eDrawType drawType)
{
RenderHelper::RenderStruct result;
result.valid = materials[drawType]->PreBuildMaterial(PASS_FORWARD);
if (!result.valid)
return result;
materials[drawType]->BindParams(result.packet);
result.packet.primitiveType = (drawType & FLAG_DRAW_SOLID) ? rhi::PRIMITIVE_TRIANGLELIST : rhi::PRIMITIVE_LINELIST;
result.packet.vertexStreamCount = 1;
result.packet.vertexLayoutUID = coloredVertexLayoutUID;
if (vBuffersElemCount[drawType])
{
DynamicBufferAllocator::AllocResultVB vb = DynamicBufferAllocator::AllocateVertexBuffer(sizeof(ColoredVertex), vBuffersElemCount[drawType]);
result.vBufferSize = vb.allocatedVertices;
result.vBufferPtr = reinterpret_cast<ColoredVertex*>(vb.data);
result.packet.vertexStream[0] = vb.buffer;
result.packet.vertexCount = result.vBufferSize;
result.packet.baseVertex = vb.baseVertex;
vBuffersElemCount[drawType] -= result.vBufferSize;
}
if (iBuffersElemCount[drawType])
{
DynamicBufferAllocator::AllocResultIB ib = DynamicBufferAllocator::AllocateIndexBuffer(iBuffersElemCount[drawType]);
result.iBufferSize = ib.allocatedindices;
result.iBufferPtr = ib.data;
result.packet.indexBuffer = ib.buffer;
result.packet.startIndex = ib.baseIndex;
iBuffersElemCount[drawType] -= result.iBufferSize;
}
return result;
}
void RenderHelper::CommitRenderStruct(rhi::HPacketList packetList, const RenderStruct& rs)
{
if (rs.packet.primitiveCount)
rhi::AddPacket(packetList, rs.packet);
}
void RenderHelper::Present(rhi::HPacketList packetList, const Matrix4* viewMatrix, const Matrix4* projectionMatrix)
{
if (commandQueue.empty())
{
return;
}
Renderer::GetDynamicBindings().SetDynamicParam(DynamicBindings::PARAM_WORLD, &Matrix4::IDENTITY, reinterpret_cast<pointer_size>(&Matrix4::IDENTITY));
Renderer::GetDynamicBindings().SetDynamicParam(DynamicBindings::PARAM_VIEW, viewMatrix, reinterpret_cast<pointer_size>(viewMatrix));
Renderer::GetDynamicBindings().SetDynamicParam(DynamicBindings::PARAM_PROJ, projectionMatrix, reinterpret_cast<pointer_size>(projectionMatrix));
RenderStruct renderStructs[DRAW_TYPE_COUNT];
for (uint32 i = 0; i < uint32(DRAW_TYPE_COUNT); ++i)
renderStructs[i] = AllocateRenderStruct(eDrawType(i));
DrawCommand* commands = commandQueue.data();
uint32 commandsCount = uint32(commandQueue.size());
for (uint32 c = 0; c < commandsCount; ++c)
{
const DrawCommand& command = commands[c];
RenderStruct& currentRenderStruct = renderStructs[command.drawType];
if (!currentRenderStruct.valid)
continue;
uint32 vertexCount = 0;
uint32 indexCount = 0;
GetRequestedVertexCount(command, vertexCount, indexCount);
if (currentRenderStruct.vBufferSize < vertexCount || currentRenderStruct.iBufferSize < indexCount)
{
vBuffersElemCount[command.drawType] += currentRenderStruct.vBufferSize;
iBuffersElemCount[command.drawType] += currentRenderStruct.iBufferSize;
CommitRenderStruct(packetList, currentRenderStruct);
currentRenderStruct = AllocateRenderStruct(command.drawType);
}
if (currentRenderStruct.vBufferOffset + indexCount >= std::numeric_limits<uint16>::max())
{
vBuffersElemCount[command.drawType] += currentRenderStruct.vBufferSize;
iBuffersElemCount[command.drawType] += currentRenderStruct.iBufferSize;
CommitRenderStruct(packetList, currentRenderStruct);
currentRenderStruct = AllocateRenderStruct(command.drawType);
}
ColoredVertex* commandVBufferPtr = currentRenderStruct.vBufferPtr;
uint16* commandIBufferPtr = currentRenderStruct.iBufferPtr;
uint32 commandVBufferOffset = currentRenderStruct.vBufferOffset;
bool isWireDraw = (command.drawType & FLAG_DRAW_SOLID) == 0;
uint32 nativePrimitiveColor = rhi::NativeColorRGBA(command.params[0], command.params[1], command.params[2], command.params[3]);
switch (command.id)
{
case COMMAND_DRAW_LINE:
{
commandVBufferPtr[0].position = Vector3(command.params[4], command.params[5], command.params[6]);
commandVBufferPtr[0].color = nativePrimitiveColor;
commandVBufferPtr[1].position = Vector3(command.params[7], command.params[8], command.params[9]);
commandVBufferPtr[1].color = nativePrimitiveColor;
DVASSERT(commandVBufferOffset + 1 <= std::numeric_limits<uint16>::max());
commandIBufferPtr[0] = commandVBufferOffset;
commandIBufferPtr[1] = commandVBufferOffset + 1;
}
break;
case COMMAND_DRAW_POLYGON:
{
const uint32 pointCount = static_cast<uint32>(command.extraParams.size() / 3);
const Vector3* const polygonPoints = reinterpret_cast<const Vector3*>(command.extraParams.data());
for (uint32 i = 0; i < pointCount; ++i)
{
commandVBufferPtr[i].position = polygonPoints[i];
commandVBufferPtr[i].color = nativePrimitiveColor;
}
FillPolygonIndecies(commandIBufferPtr, commandVBufferOffset, indexCount, vertexCount, isWireDraw);
}
break;
case COMMAND_DRAW_BOX:
{
const Vector3 basePoint(command.params + 4), xAxis(command.params + 7), yAxis(command.params + 10), zAxis(command.params + 13);
FillBoxVBuffer(commandVBufferPtr, basePoint, xAxis, yAxis, zAxis, nativePrimitiveColor);
FillIndeciesFromArray(commandIBufferPtr, commandVBufferOffset, isWireDraw ? gWireBoxIndexes.data() : gSolidBoxIndexes.data(), indexCount);
}
break;
case COMMAND_DRAW_BOX_CORNERS:
{
const Vector3 basePoint(command.params + 4), xAxis(command.params + 7), yAxis(command.params + 10), zAxis(command.params + 13);
FillBoxCornersVBuffer(commandVBufferPtr, basePoint, xAxis, yAxis, zAxis, nativePrimitiveColor);
FillIndeciesFromArray(commandIBufferPtr, commandVBufferOffset, isWireDraw ? gWireBoxCornersIndexes.data() : gSolidBoxCornersIndexes.data(), indexCount);
}
break;
case COMMAND_DRAW_CIRCLE:
{
const uint32 pointCount = static_cast<uint32>(command.params[11]);
const Vector3 center(command.params + 4), direction(command.params + 7);
const float32 radius = command.params[10];
FillCircleVBuffer(commandVBufferPtr, center, direction, radius, pointCount, nativePrimitiveColor);
FillPolygonIndecies(commandIBufferPtr, commandVBufferOffset, indexCount, vertexCount, isWireDraw);
if (isWireDraw)
{
commandIBufferPtr[vertexCount * 2 - 2] = commandVBufferOffset + vertexCount - 1;
commandIBufferPtr[vertexCount * 2 - 1] = commandVBufferOffset;
}
}
break;
case COMMAND_DRAW_ICOSA:
{
const Vector3 icosaPosition(command.params[4], command.params[5], command.params[6]);
const float32 icosaSize = command.params[7];
for (size_t i = 0; i < gIcosaVertexes.size(); ++i)
{
commandVBufferPtr[i].position = gIcosaVertexes[i] * icosaSize + icosaPosition;
commandVBufferPtr[i].color = nativePrimitiveColor;
}
FillIndeciesFromArray(commandIBufferPtr, commandVBufferOffset, isWireDraw ? gWireIcosaIndexes.data() : gSolidIcosaIndexes.data(), indexCount);
}
break;
case COMMAND_DRAW_ARROW:
{
const Vector3 from(command.params + 4);
const Vector3 to(command.params + 7);
FillArrowVBuffer(commandVBufferPtr, from, to, nativePrimitiveColor);
FillIndeciesFromArray(commandIBufferPtr, commandVBufferOffset, isWireDraw ? gWireArrowIndexes.data() : gSolidArrowIndexes.data(), indexCount);
}
break;
default:
break;
}
DVASSERT(currentRenderStruct.vBufferSize >= vertexCount);
DVASSERT(currentRenderStruct.iBufferSize >= indexCount);
currentRenderStruct.vBufferSize -= vertexCount;
currentRenderStruct.iBufferSize -= indexCount;
currentRenderStruct.vBufferPtr += vertexCount;
currentRenderStruct.iBufferPtr += indexCount;
currentRenderStruct.vBufferOffset += vertexCount;
currentRenderStruct.packet.primitiveCount += indexCount / ((command.drawType & FLAG_DRAW_SOLID) ? 3 : 2);
}
for (uint32 i = 0; i < uint32(DRAW_TYPE_COUNT); ++i)
{
CommitRenderStruct(packetList, renderStructs[i]);
DVASSERT(!renderStructs[i].valid || (vBuffersElemCount[i] == 0 && iBuffersElemCount[i] == 0));
}
}
void RenderHelper::Clear()
{
commandQueue.clear();
Memset(vBuffersElemCount, 0, sizeof(vBuffersElemCount));
Memset(iBuffersElemCount, 0, sizeof(iBuffersElemCount));
}
bool RenderHelper::IsEmpty()
{
return commandQueue.empty();
}
void RenderHelper::QueueCommand(const DrawCommand& command)
{
commandQueue.emplace_back(command);
uint32 vertexCount = 0, indexCount = 0;
GetRequestedVertexCount(command, vertexCount, indexCount);
vBuffersElemCount[command.drawType] += vertexCount;
iBuffersElemCount[command.drawType] += indexCount;
}
void RenderHelper::GetRequestedVertexCount(const DrawCommand& command, uint32& vertexCount, uint32& indexCount)
{
bool isSolidDraw = (command.drawType & FLAG_DRAW_SOLID) != 0;
switch (command.id)
{
case COMMAND_DRAW_LINE:
{
vertexCount = 2;
indexCount = 2;
}
break;
case COMMAND_DRAW_POLYGON:
{
vertexCount = static_cast<uint32>(command.extraParams.size() / 3);
indexCount = isSolidDraw ? (vertexCount - 2) * 3 : (vertexCount - 1) * 2;
}
break;
case COMMAND_DRAW_BOX:
{
vertexCount = 8;
size_t count = isSolidDraw ? gSolidBoxIndexes.size() : gWireBoxIndexes.size();
indexCount = static_cast<uint32>(count);
}
break;
case COMMAND_DRAW_BOX_CORNERS:
{
vertexCount = 32;
size_t count = isSolidDraw ? gSolidBoxCornersIndexes.size() : gWireBoxCornersIndexes.size();
indexCount = static_cast<uint32>(count);
}
break;
case COMMAND_DRAW_CIRCLE:
{
vertexCount = static_cast<uint32>(command.params[11]);
size_t count = isSolidDraw ? (vertexCount - 2) * 3 : vertexCount * 2;
indexCount = static_cast<uint32>(count);
}
break;
case COMMAND_DRAW_ICOSA:
{
vertexCount = static_cast<uint32>(gIcosaVertexes.size());
size_t count = isSolidDraw ? gSolidIcosaIndexes.size() : gWireIcosaIndexes.size();
indexCount = static_cast<uint32>(count);
}
break;
case COMMAND_DRAW_ARROW:
{
vertexCount = 5;
size_t count = isSolidDraw ? gSolidArrowIndexes.size() : gWireArrowIndexes.size();
indexCount = static_cast<uint32>(count);
}
break;
default:
{
DVASSERT(false && "DrawCommand not implemented");
}
break;
}
}
void RenderHelper::DrawLine(const Vector3& pt1, const Vector3& pt2, const Color& color, eDrawType drawType /* = DRAW_WIRE_DEPTH */)
{
DVASSERT((drawType & FLAG_DRAW_SOLID) == 0);
drawLineCommand.drawType = drawType;
drawLineCommand.params[0] = color.r;
drawLineCommand.params[1] = color.g;
drawLineCommand.params[2] = color.b;
drawLineCommand.params[3] = color.a;
drawLineCommand.params[4] = pt1.x;
drawLineCommand.params[5] = pt1.y;
drawLineCommand.params[6] = pt1.z;
drawLineCommand.params[7] = pt2.x;
drawLineCommand.params[8] = pt2.y;
drawLineCommand.params[9] = pt2.z;
QueueCommand(drawLineCommand);
}
void RenderHelper::DrawPolygon(const Polygon3& polygon, const Color& color, eDrawType drawType)
{
DrawCommand drawCommand(COMMAND_DRAW_POLYGON);
drawCommand.drawType = drawType;
drawCommand.extraParams.resize(polygon.pointCount * 3);
Memcpy(drawCommand.extraParams.data(), polygon.points.data(), sizeof(Vector3) * polygon.pointCount);
drawCommand.params[0] = color.r;
drawCommand.params[1] = color.g;
drawCommand.params[2] = color.b;
drawCommand.params[3] = color.a;
QueueCommand(drawCommand);
}
void RenderHelper::DrawAABox(const AABBox3& box, const Color& color, eDrawType drawType)
{
QueueDrawBoxCommand(COMMAND_DRAW_BOX, box, nullptr, color, drawType);
}
void RenderHelper::DrawAABoxTransformed(const AABBox3& box, const Matrix4& matrix, const Color& color, eDrawType drawType)
{
QueueDrawBoxCommand(COMMAND_DRAW_BOX, box, &matrix, color, drawType);
}
void RenderHelper::DrawAABoxCorners(const AABBox3& box, const Color& color, eDrawType drawType)
{
QueueDrawBoxCommand(COMMAND_DRAW_BOX_CORNERS, box, nullptr, color, drawType);
}
void RenderHelper::DrawAABoxCornersTransformed(const AABBox3& box, const Matrix4& matrix, const Color& color, eDrawType drawType)
{
QueueDrawBoxCommand(COMMAND_DRAW_BOX_CORNERS, box, &matrix, color, drawType);
}
void RenderHelper::DrawArrow(const Vector3& from, const Vector3& to, float32 arrowLength, const Color& color, eDrawType drawType)
{
Vector3 direction = to - from;
Vector3 lineEnd = to - (direction * arrowLength / direction.Length());
drawArrowCommand.drawType = drawType;
drawArrowCommand.params[0] = color.r;
drawArrowCommand.params[1] = color.g;
drawArrowCommand.params[2] = color.b;
drawArrowCommand.params[3] = color.a;
drawArrowCommand.params[4] = lineEnd.x;
drawArrowCommand.params[5] = lineEnd.y;
drawArrowCommand.params[6] = lineEnd.z;
drawArrowCommand.params[7] = to.x;
drawArrowCommand.params[8] = to.y;
drawArrowCommand.params[9] = to.z;
QueueCommand(drawArrowCommand);
DrawLine(from, lineEnd, color, eDrawType(drawType & FLAG_DRAW_NO_DEPTH));
}
void RenderHelper::DrawIcosahedron(const Vector3& position, float32 radius, const Color& color, eDrawType drawType)
{
drawIcosahedronCommand.drawType = drawType;
drawIcosahedronCommand.params[0] = color.r;
drawIcosahedronCommand.params[1] = color.g;
drawIcosahedronCommand.params[2] = color.b;
drawIcosahedronCommand.params[3] = color.a;
drawIcosahedronCommand.params[4] = position.x;
drawIcosahedronCommand.params[5] = position.y;
drawIcosahedronCommand.params[6] = position.z;
drawIcosahedronCommand.params[7] = radius;
QueueCommand(drawIcosahedronCommand);
}
void RenderHelper::DrawCircle(const Vector3& center, const Vector3& direction, float32 radius, uint32 segmentCount, const Color& color, eDrawType drawType)
{
drawCircleCommand.drawType = drawType;
drawCircleCommand.params[0] = color.r;
drawCircleCommand.params[1] = color.g;
drawCircleCommand.params[2] = color.b;
drawCircleCommand.params[3] = color.a;
drawCircleCommand.params[4] = center.x;
drawCircleCommand.params[5] = center.y;
drawCircleCommand.params[6] = center.z;
drawCircleCommand.params[7] = direction.x;
drawCircleCommand.params[8] = direction.y;
drawCircleCommand.params[9] = direction.z;
drawCircleCommand.params[10] = radius;
drawCircleCommand.params[11] = static_cast<float32>(segmentCount);
QueueCommand(drawCircleCommand);
}
void RenderHelper::DrawBSpline(BezierSpline3* bSpline, int segments, float ts, float te, const Color& color, eDrawType drawType)
{
Polygon3 pts;
pts.points.reserve(segments);
for (int k = 0; k < segments; ++k)
{
pts.AddPoint(bSpline->Evaluate(0, ts + (te - ts) * (static_cast<float32>(k) / (segments - 1))));
}
DrawPolygon(pts, color, drawType);
}
void RenderHelper::DrawInterpolationFunc(Interpolation::Func func, const Rect& destRect, const Color& color, eDrawType drawType)
{
Polygon3 pts;
int segmentsCount = 20;
pts.points.reserve(segmentsCount);
for (int k = 0; k < segmentsCount; ++k)
{
Vector3 v;
float32 fk = static_cast<float32>(k);
v.x = destRect.x + (fk / (segmentsCount - 1)) * destRect.dx;
v.y = destRect.y + func((fk / (segmentsCount - 1))) * destRect.dy;
v.z = 0.0f;
pts.AddPoint(v);
}
DrawPolygon(pts, color, drawType);
}
void RenderHelper::QueueDrawBoxCommand(eDrawCommandID commandID, const AABBox3& box, const Matrix4* matrix, const Color& color, eDrawType drawType)
{
Vector3 minPt = box.min;
Vector3 xAxis(box.max.x - box.min.x, 0.f, 0.f);
Vector3 yAxis(0.f, box.max.y - box.min.y, 0.f);
Vector3 zAxis(0.f, 0.f, box.max.z - box.min.z);
if (matrix)
{
minPt = minPt * (*matrix);
xAxis = MultiplyVectorMat3x3(xAxis, *matrix);
yAxis = MultiplyVectorMat3x3(yAxis, *matrix);
zAxis = MultiplyVectorMat3x3(zAxis, *matrix);
}
drawBoxCommand.id = commandID;
drawBoxCommand.drawType = drawType;
drawBoxCommand.params[0] = color.r;
drawBoxCommand.params[1] = color.g;
drawBoxCommand.params[2] = color.b;
drawBoxCommand.params[3] = color.a;
drawBoxCommand.params[4] = minPt.x;
drawBoxCommand.params[5] = minPt.y;
drawBoxCommand.params[6] = minPt.z;
drawBoxCommand.params[7] = xAxis.x;
drawBoxCommand.params[8] = xAxis.y;
drawBoxCommand.params[9] = xAxis.z;
drawBoxCommand.params[10] = yAxis.x;
drawBoxCommand.params[11] = yAxis.y;
drawBoxCommand.params[12] = yAxis.z;
drawBoxCommand.params[13] = zAxis.x;
drawBoxCommand.params[14] = zAxis.y;
drawBoxCommand.params[15] = zAxis.z;
QueueCommand(drawBoxCommand);
}
void RenderHelper::FillBoxVBuffer(ColoredVertex* buffer, const Vector3& basePoint, const Vector3& xAxis, const Vector3& yAxis, const Vector3& zAxis, uint32 nativeColor)
{
buffer[0].position = basePoint;
buffer[0].color = nativeColor;
buffer[1].position = basePoint + xAxis;
buffer[1].color = nativeColor;
buffer[2].position = basePoint + yAxis;
buffer[2].color = nativeColor;
buffer[3].position = basePoint + zAxis;
buffer[3].color = nativeColor;
buffer[4].position = basePoint + xAxis + yAxis;
buffer[4].color = nativeColor;
buffer[5].position = basePoint + xAxis + zAxis;
buffer[5].color = nativeColor;
buffer[6].position = basePoint + yAxis + zAxis;
buffer[6].color = nativeColor;
buffer[7].position = basePoint + xAxis + yAxis + zAxis;
buffer[7].color = nativeColor;
}
void RenderHelper::FillBoxCornersVBuffer(ColoredVertex* buffer, const Vector3& basePoint, const Vector3& xAxis, const Vector3& yAxis, const Vector3& zAxis, uint32 nativeColor)
{
FillBoxVBuffer(buffer, basePoint, xAxis, yAxis, zAxis, nativeColor);
const float32 cornerLength = ((buffer[0].position - buffer[7].position).Length()) * 0.1f + 0.1f;
const Vector3 xCorner = Normalize(xAxis) * cornerLength;
const Vector3 yCorner = Normalize(yAxis) * cornerLength;
const Vector3 zCorner = Normalize(zAxis) * cornerLength;
buffer[8 + 0 * 3 + 0].position = buffer[0].position + xCorner;
buffer[8 + 0 * 3 + 1].position = buffer[0].position + yCorner;
buffer[8 + 0 * 3 + 2].position = buffer[0].position + zCorner;
buffer[8 + 1 * 3 + 0].position = buffer[1].position - xCorner;
buffer[8 + 1 * 3 + 1].position = buffer[1].position + yCorner;
buffer[8 + 1 * 3 + 2].position = buffer[1].position + zCorner;
buffer[8 + 2 * 3 + 0].position = buffer[2].position + xCorner;
buffer[8 + 2 * 3 + 1].position = buffer[2].position - yCorner;
buffer[8 + 2 * 3 + 2].position = buffer[2].position + zCorner;
buffer[8 + 3 * 3 + 0].position = buffer[3].position + xCorner;
buffer[8 + 3 * 3 + 1].position = buffer[3].position + yCorner;
buffer[8 + 3 * 3 + 2].position = buffer[3].position - zCorner;
buffer[8 + 4 * 3 + 0].position = buffer[4].position - xCorner;
buffer[8 + 4 * 3 + 1].position = buffer[4].position - yCorner;
buffer[8 + 4 * 3 + 2].position = buffer[4].position + zCorner;
buffer[8 + 5 * 3 + 0].position = buffer[5].position - xCorner;
buffer[8 + 5 * 3 + 1].position = buffer[5].position + yCorner;
buffer[8 + 5 * 3 + 2].position = buffer[5].position - zCorner;
buffer[8 + 6 * 3 + 0].position = buffer[6].position + xCorner;
buffer[8 + 6 * 3 + 1].position = buffer[6].position - yCorner;
buffer[8 + 6 * 3 + 2].position = buffer[6].position - zCorner;
buffer[8 + 7 * 3 + 0].position = buffer[7].position - xCorner;
buffer[8 + 7 * 3 + 1].position = buffer[7].position - yCorner;
buffer[8 + 7 * 3 + 2].position = buffer[7].position - zCorner;
for (int32 i = 8; i < 32; ++i)
buffer[i].color = nativeColor;
}
void RenderHelper::FillCircleVBuffer(ColoredVertex* buffer, const Vector3& center, const Vector3& dir, float32 radius, uint32 pointCount, uint32 nativeColor)
{
const Vector3 direction = Normalize(dir);
const Vector3 ortho = Abs(direction.x) < Abs(direction.y) ? direction.CrossProduct(Vector3(1.f, 0.f, 0.f)) : direction.CrossProduct(Vector3(0.f, 1.f, 0.f));
Matrix4 rotationMx;
float32 angleDelta = PI_2 / pointCount;
for (uint32 i = 0; i < pointCount; ++i)
{
rotationMx.BuildRotation(direction, -angleDelta * i);
buffer[i].position = center + (ortho * radius) * rotationMx;
buffer[i].color = nativeColor;
}
}
void RenderHelper::FillArrowVBuffer(ColoredVertex* buffer, const Vector3& from, const Vector3& to, uint32 nativeColor)
{
Vector3 direction = to - from;
float32 arrowlength = direction.Normalize();
float32 arrowWidth = arrowlength / 4.f;
const Vector3 ortho1 = Abs(direction.x) < Abs(direction.y) ? direction.CrossProduct(Vector3(1.f, 0.f, 0.f)) : direction.CrossProduct(Vector3(0.f, 1.f, 0.f));
const Vector3 ortho2 = ortho1.CrossProduct(direction);
buffer[0].position = to;
buffer[0].color = nativeColor;
buffer[1].position = from + ortho1 * arrowWidth;
buffer[1].color = nativeColor;
buffer[2].position = from + ortho2 * arrowWidth;
buffer[2].color = nativeColor;
buffer[3].position = from - ortho1 * arrowWidth;
buffer[3].color = nativeColor;
buffer[4].position = from - ortho2 * arrowWidth;
buffer[4].color = nativeColor;
}
void RenderHelper::FillIndeciesFromArray(uint16* buffer, uint16 baseIndex, uint16* indexArray, uint32 indexCount)
{
for (uint32 i = 0; i < indexCount; ++i)
{
DVASSERT(baseIndex + indexArray[i] < std::numeric_limits<uint16>::max());
buffer[i] = baseIndex + indexArray[i];
}
}
void RenderHelper::FillPolygonIndecies(uint16* buffer, uint16 baseIndex, uint32 indexCount, uint32 vertexCount, bool isWire)
{
if (isWire)
{
const uint32 linesCount = vertexCount - 1;
for (uint32 i = 0; i < linesCount; ++i)
{
DVASSERT(baseIndex + i + 1 < std::numeric_limits<uint16>::max());
buffer[i * 2 + 0] = baseIndex + i;
buffer[i * 2 + 1] = baseIndex + i + 1;
}
}
else
{
const uint32 triangleCount = vertexCount - 2;
for (uint32 i = 0; i < triangleCount; ++i)
{
DVASSERT(baseIndex + i + 2 < std::numeric_limits<uint16>::max());
buffer[i * 3 + 0] = baseIndex + i + 2;
buffer[i * 3 + 1] = baseIndex + i + 1;
buffer[i * 3 + 2] = baseIndex;
}
}
}
void RenderHelper::CreateClearPass(rhi::HTexture colorBuffer, rhi::HTexture depthBuffer, int32 passPriority, const Color& clearColor, const rhi::Viewport& viewport)
{
rhi::RenderPassConfig clearPassConfig;
clearPassConfig.priority = passPriority;
clearPassConfig.colorBuffer[0].texture = colorBuffer;
clearPassConfig.colorBuffer[0].clearColor[0] = clearColor.r;
clearPassConfig.colorBuffer[0].clearColor[1] = clearColor.g;
clearPassConfig.colorBuffer[0].clearColor[2] = clearColor.b;
clearPassConfig.colorBuffer[0].clearColor[3] = clearColor.a;
clearPassConfig.colorBuffer[0].loadAction = rhi::LOADACTION_CLEAR;
clearPassConfig.colorBuffer[0].storeAction = rhi::STOREACTION_STORE;
clearPassConfig.depthStencilBuffer.texture = depthBuffer;
clearPassConfig.depthStencilBuffer.loadAction = rhi::LOADACTION_CLEAR;
clearPassConfig.depthStencilBuffer.storeAction = rhi::STOREACTION_STORE;
clearPassConfig.viewport = viewport;
rhi::HPacketList emptyPacketList;
rhi::HRenderPass clearPass = rhi::AllocateRenderPass(clearPassConfig, 1, &emptyPacketList);
if (clearPass != rhi::InvalidHandle)
{
rhi::BeginRenderPass(clearPass);
rhi::BeginPacketList(emptyPacketList);
rhi::EndPacketList(emptyPacketList);
rhi::EndRenderPass(clearPass);
}
}
};
| 37.744737 | 175 | 0.666841 | [
"render"
] |
4e5e4ecae7fc74668c378b7c090e6c0eef8bd812 | 4,949 | cpp | C++ | DiagramEditor/DiagramMenu.cpp | pmachapman/Tulip | 54f7bc3e8d5bb452ed8de6e6622e23d5e9be650a | [
"Unlicense"
] | null | null | null | DiagramEditor/DiagramMenu.cpp | pmachapman/Tulip | 54f7bc3e8d5bb452ed8de6e6622e23d5e9be650a | [
"Unlicense"
] | 33 | 2018-09-14T21:58:20.000Z | 2022-01-12T21:39:22.000Z | DiagramEditor/DiagramMenu.cpp | pmachapman/Tulip | 54f7bc3e8d5bb452ed8de6e6622e23d5e9be650a | [
"Unlicense"
] | null | null | null | /* ==========================================================================
Class : CDiagramMenu
Author : Johan Rosengren, Abstrakt Mekanik AB
Date : 2004-03-30
Purpose : "CDiagramMenu" is a simple class to allow easy
customization of the popup menu of the "CDiagramEditor"
without deriving a new class.
Description : Contains a "CMenu" that is exposed through "GetPopupMenu".
Usage : Derive a class from "CDiagramMenu", and implement
"GetPopupMenu". This function is expected to return a
pointer to a "CMenu". The menu alternatives on the menu
should have menu ids between "CMD_START" and "CMD_END"
inclusively (some are predefined). The constants are
defined in DiagramEntity.h. The "CDiagramMenu" should
be added to the "CDiagramEditor" class with a call to
"SetPopupMenu". Note that the editor then owns the menu
and will delete it as soon as a new menu is set and
in the "dtor", so either heap allocate it or allocate and
add it so:
"m_editor.SetPopupMenu( new CMyDiagramMenuDerivedClass );"
Whenever a menu alternative is selected from the popup
menu, the command is sent to all selected objects. The
objects will then have to handle the messages they are
interested in in their "DoCommand" functions.
The class is a friend class to "CDiagramEditor", so all
members are accessible.
========================================================================
26/6 2004 Added group handling (Unruled Boy).
========================================================================
18/3 2019 Removed group handling, added undo/redo, etc
========================================================================*/
#include "stdafx.h"
#include "DiagramMenu.h"
#include "DiagramEditor.h"
CDiagramMenu::CDiagramMenu()
/* ============================================================
Function : CDiagramMenu::CDiagramMenu
Description : Constructor
Access : Public
Return : void
Parameters : none
Usage : Always heap allocate
============================================================*/
{
selectedMenu = 0;
}
CDiagramMenu::~CDiagramMenu()
/* ============================================================
Function : CDiagramMenu::~CDiagramMenu
Description : Destructor
Access : Public
Return : void
Parameters : none
Usage : Note that the editor will delete attached
instances automatically
============================================================*/
{
if (m_menu.m_hMenu != NULL)
m_menu.DestroyMenu();
}
CMenu* CDiagramMenu::GetPopupMenu(CDiagramEditor* editor)
/* ============================================================
Function : CDiagramMenu::GetPopupMenu
Description : Gets a menu pointer to the desired popup
menu.
Access : Public
Return : CMenu* - A pointer to
the popup menu
Parameters : CDiagramEditor* editor - The editor
calling for a
menu.
Usage : Call to get the popup menu for the editor.
============================================================*/
{
// Set the default menu
int resourceId = IDR_MENU_EDITOR_POPUP;
// See if an object is selected. If it is, get its menu
if (editor->GetSelectCount() == 1)
{
resourceId = editor->GetSelectedObject()->GetMenuResourceId();
}
// Free then old menu if it is changing
if (m_menu.m_hMenu != NULL && selectedMenu != resourceId)
{
m_menu.DestroyMenu();
m_menu.m_hMenu = NULL;
}
// Load the menu if it is changing (or first run)
if (selectedMenu != resourceId)
{
m_menu.LoadMenu(resourceId);
selectedMenu = resourceId;
}
UINT undo = MF_GRAYED;
UINT redo = MF_GRAYED;
UINT cut = MF_GRAYED;
UINT copy = MF_GRAYED;
UINT paste = MF_GRAYED;
UINT deleteSelected = MF_GRAYED;
UINT selectall = MF_GRAYED;
if (editor->IsAnyObjectSelected())
{
cut = 0;
copy = 0;
deleteSelected = 0;
}
if (editor->GetObjectCount() > 0)
{
selectall = 0;
}
if (editor->GetDiagramEntityContainer() && editor->GetDiagramEntityContainer()->ObjectsInPaste())
{
paste = 0;
}
if (editor->GetDiagramEntityContainer() && editor->GetDiagramEntityContainer()->IsUndoPossible())
{
undo = 0;
}
if (editor->GetDiagramEntityContainer() && editor->GetDiagramEntityContainer()->IsRedoPossible())
{
redo = 0;
}
// TODO: Custom menu item support for GetSelectedItem
// Maybe load a custom menu from a resource?
// TODO: Remove other custom menu classes
m_menu.EnableMenuItem(ID_EDIT_UNDO, MF_BYCOMMAND | undo);
m_menu.EnableMenuItem(ID_EDIT_REDO, MF_BYCOMMAND | redo);
m_menu.EnableMenuItem(ID_EDIT_CUT, MF_BYCOMMAND | cut);
m_menu.EnableMenuItem(ID_EDIT_COPY, MF_BYCOMMAND | copy);
m_menu.EnableMenuItem(ID_EDIT_PASTE, MF_BYCOMMAND | paste);
m_menu.EnableMenuItem(ID_EDIT_DELETE, MF_BYCOMMAND | deleteSelected);
m_menu.EnableMenuItem(ID_EDIT_SELECT_ALL, MF_BYCOMMAND | selectall);
return m_menu.GetSubMenu(0);
} | 30.176829 | 98 | 0.615478 | [
"object"
] |
4e5f18defea4f8a8aa642015b557eee8721e3c43 | 1,062 | cpp | C++ | codeforces/GYM/vitalyAndCycle.cpp | GinugaSaketh/Codes | e934aa5652dd86231a42e3f7f84b145eb35bf47d | [
"MIT"
] | null | null | null | codeforces/GYM/vitalyAndCycle.cpp | GinugaSaketh/Codes | e934aa5652dd86231a42e3f7f84b145eb35bf47d | [
"MIT"
] | null | null | null | codeforces/GYM/vitalyAndCycle.cpp | GinugaSaketh/Codes | e934aa5652dd86231a42e3f7f84b145eb35bf47d | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
vector<vector<int> > adj;
long long net=0;
long long a,b,c;
int flag3=0;
int flag2=1;
int dist[100005];
void dfs(int u){
int v,i;
for(i=0;i<adj[u].size();i++){
v=adj[u][i];
if(dist[v]==-1){
dist[v]=dist[u]+1;
if(dist[v]%2==0){
a++;
}else{
b++;
}
c++;
dfs(v);
}else{
if((dist[u]-dist[v])%2==0){
flag3=1;
}
}
}
}
int main(){
long long n,m;
cin>>n>>m;
adj.resize(n+5);
int i;
int p,q;
for(i=1;i<=m;i++){
cin>>p>>q;
adj[p].push_back(q);
adj[q].push_back(p);
}
for(i=1;i<=n;i++){
dist[i]=-1;
}
if(m==0){
net=(n)*(n-1)*(n-2);
net/=6LL ;
cout<<"3 "<<net<<endl;
return 0;
}
for(i=1;i<=n;i++){
if(dist[i]==-1){
a=0,b=0,c=0;
a++;//even dist.
dist[i]=0;
c++;
dfs(i);
if(c>2){
flag2=0;
}
net+=(a*(a-1))/2;
net+=(b*(b-1))/2;
}
}
if(flag3==1){
cout<<"0 1"<<endl;
return 0;
}
if(flag2==1){
cout<<"2 "<<(m*(n-2))<<endl;
return 0;
}
cout<<"1 "<<net<<endl;
return 0;
} | 9.234783 | 30 | 0.448211 | [
"vector"
] |
4e60ee61f04ae6fbd49993d9e0850dfddba5ed0f | 66,404 | cpp | C++ | src/server/frame/httpact.cpp | jvirkki/heliod | efdf2d105e342317bd092bab2d727713da546174 | [
"BSD-3-Clause"
] | 13 | 2015-10-09T05:59:20.000Z | 2021-11-12T10:38:51.000Z | src/server/frame/httpact.cpp | JamesLinus/heliod | efdf2d105e342317bd092bab2d727713da546174 | [
"BSD-3-Clause"
] | null | null | null | src/server/frame/httpact.cpp | JamesLinus/heliod | efdf2d105e342317bd092bab2d727713da546174 | [
"BSD-3-Clause"
] | 6 | 2016-05-23T10:53:29.000Z | 2019-12-13T17:57:32.000Z | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2008 Sun Microsystems, Inc. All rights reserved.
*
* THE BSD LICENSE
*
* 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 the 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.
*/
/*
* httpact.c: Defines the actions which compose the NSAPI for the HTTP
* servers
*
* Rob McCool
*/
#include "netsite.h"
#include "base/pblock.h" /* various */
#include "base/session.h" /* Session struct */
#include "base/util.h"
#include <base/plist.h>
#include "base/shexp.h" /* shexp_casecmp */
#include "base/vs.h"
#include <libaccess/acl.h>
#include <libaccess/aclproto.h>
#include <libaccess/aclcache.h>
#include <libaccess/genacl.h>
#include "frame/httpact.h"
#include "frame/http_ext.h"
#include "frame/httpdir.h"
#include "frame/httpfilter.h"
#include "frame/req.h" /* Request structure, objset, object, etc */
#include "frame/log.h" /* error logging */
#include "frame/func.h" /* func_exec */
#include "frame/protocol.h" /* protocol_finish_request */
#include "frame/conf.h" /* std_os global */
#include "frame/error.h"
#include <frame/acl.h>
#include "httpdaemon/httprequest.h"
#include "httpdaemon/statsmanager.h"
#include "httpdaemon/daemonsession.h"
#include "httpdaemon/HttpMethodRegistry.h"
#include "httpdaemon/vsconf.h"
#include "support/NSString.h"
#include "support/SimpleHash.h"
#ifdef PUMPKIN_HOUR
#include <signal.h>
#ifdef XP_WIN32
#include "nt/regparms.h"
#endif /* XP_WIN32 */
#endif
#include "frame/dbtframe.h"
#include "ares/arapi.h"
#define ACL_HTTP_RIGHT_PREFIX "http_"
#define ACL_HTTP_RIGHT_PREFIX_LEN (sizeof(ACL_HTTP_RIGHT_PREFIX) - 1)
#define PROCESS_URI_OBJECTS "process-uri-objects"
/*
* objlist is a container for a bunch of objects. Unlike httpd_objset, the
* contents of an objlist aren't sorted.
*/
struct objlist {
int pos;
httpd_object **obj;
};
static inline PRBool rights_always_allowed(Session *sn, Request *rq, const VirtualServer *vs, ACLListHandle_t *aclroot, char **rights);
static int _perform_pathchecks(Session *sn, Request *rq, httpd_object *obj, int doacl);
static PRBool ParamMatch(const char* expr, const char* str, PRBool noicmp);
static PRBool FindApplicableMethods(Session* sn, Request* rq,
NSString& methodStr);
/* ------------------------------------------------------------------------ */
/* ----------------------- Directive execution code ----------------------- */
/* ------------------------------------------------------------------------ */
/* ------------------------- _directive_applyone -------------------------- */
/* Apply the first applicable instance of a directive and return */
static inline int _directive_applyone(NSAPIPhase ph, dtable *d, Session *sn, Request *rq)
{
register int x;
int rv;
for(x = 0; x < d->ni; x++) {
rv = object_execute(&d->inst[x], sn, rq);
if (rv != REQ_NOACTION)
return rv;
}
return REQ_NOACTION;
}
/* ------------------------- _directive_applyall -------------------------- */
static inline int _directive_applyall(NSAPIPhase ph, dtable *d, Session *sn, Request *rq)
{
register int x;
int rv;
for(x = 0; x < d->ni; x++) {
rv = object_execute(&d->inst[x], sn, rq);
if (rv != REQ_NOACTION && rv != REQ_PROCEED)
return rv;
}
return REQ_PROCEED;
}
/* ------------------------------------------------------------------------ */
/* ----------------------- AuthTrans and NameTrans ------------------------ */
/* ------------------------------------------------------------------------ */
/* ----------------------------- add_objects ------------------------------ */
static inline int add_objects(Session *sn, Request *rq, httpd_objset *os, char *name, char *ppath, objlist *objlist)
{
/*
* Named objects take precedence over ppath-based objects.
*
* For historical reasons, name values encountered while processing a
* given object are handled in the opposite order from which they were
* inserted. The order isn't usually an issue in practice because a) the
* assign-name SAF won't insert a second name parameter if one is already
* present and b) the pfx2dir SAF returns REQ_PROCEED, preventing a
* subsequent NameTrans directive in that object from inserting a second
* name parameter. ntrans-j2ee does things its own way, though, and will
* happily insert a second name parameter.
*/
while (name) {
httpd_object *obj = objset_findbyname(name, rq->os, os);
if (!obj) {
log_error(LOG_MISCONFIG, PROCESS_URI_OBJECTS, sn, rq,
XP_GetAdminStr(DBT_cannotFindTemplateS_), name);
return REQ_ABORTED;
}
PR_ASSERT(objlist->pos < os->pos);
objlist->obj[objlist->pos++] = obj;
objset_add_object(obj, rq->os);
pblock_removekey(pb_key_name, rq->vars);
name = pblock_findkeyval(pb_key_name, rq->vars);
}
/* Look for objects with matching ppath parameters */
if (ppath) {
while (httpd_object *obj = objset_findbyppath(ppath, rq->os, os)) {
PR_ASSERT(objlist->pos < os->pos);
objlist->obj[objlist->pos++] = obj;
objset_add_object(obj, rq->os);
}
}
return REQ_PROCEED;
}
/* --------------------------- request_uri2path --------------------------- */
NSAPI_PUBLIC int servact_uri2path(Session *sn, Request *rq)
{
httpd_objset *os = NULL;
if (((NSAPIRequest*)rq)->hrq) {
os = ((NSAPIRequest*)rq)->hrq->getObjset();
} else if (const VirtualServer *vs = conf_get_vs()) {
os = vs->getObjset();
} else {
return REQ_ABORTED;
}
return servact_objset_uri2path(sn, rq, os);
}
NSAPI_PUBLIC int servact_objset_uri2path(Session *sn, Request *rq, httpd_objset *vs_os)
{
PRBool checked_server_name = PR_FALSE;
pb_param *pp;
int rv;
NSAPIRequest *nrq = (NSAPIRequest *)rq;
const HttpRequest *hrq = GetHrq(rq);
const VirtualServer *vs;
if (hrq) {
// this was a real HTTP request
vs = hrq->getVS();
PR_ASSERT(vs);
} else {
// no HTTP request : we are in a VSInit
vs = conf_get_vs();
PR_ASSERT(vs);
}
/* Initialize two separate, empty lists of objects */
objlist objectlists[2];
objectlists[0].pos = 0;
objectlists[0].obj = (httpd_object **) pool_malloc(sn->pool, sizeof(httpd_object *) * vs_os->pos);
objectlists[1].pos = 0;
objectlists[1].obj = (httpd_object **) pool_malloc(sn->pool, sizeof(httpd_object *) * vs_os->pos);
servact_objset_uri2path_restart:
int nametrans_rv = REQ_NOACTION;
/* Initially, look for default object. */
const NSString& defname = vs->getDefaultObjectName();
pp = pblock_kvinsert(pb_key_name, defname.data(), defname.length(), rq->vars);
char *name = pp->value;
/* Start with ppath set to the uri */
char *ppath = pblock_findkeyval(pb_key_uri, rq->reqpb);
pp = pblock_kvinsert(pb_key_ppath, ppath, strlen(ppath), rq->vars);
ppath = pp->value;
rq->os = objset_create_pool(sn->pool);
/*
* To prevent 3rd party SAFs from causing restart loops, we track the
* number of times servact_uri2path has been called for this request.
*
* (Note that the SAFs we ship call request_restart to restart requests.
* request_restart enforces the MAX_REQUEST_RESTARTS limit on its own.)
*/
if (nrq->nuri2path > MAX_REQUEST_RESTARTS) {
log_error(LOG_FAILURE, PROCESS_URI_OBJECTS, sn, rq,
XP_GetAdminStr(DBT_httpRestartUriXExceedsDepthY),
ppath, MAX_REQUEST_RESTARTS);
protocol_status(sn, rq, PROTOCOL_SERVER_ERROR, NULL);
return REQ_ABORTED;
}
nrq->nuri2path++;
PRBool log_finest = ereport_can_log(LOG_FINEST);
if (log_finest) {
log_error(LOG_FINEST, PROCESS_URI_OBJECTS, sn, rq,
"processing objects for URI %s",
ppath);
}
/* Start with the default object and any objects that apply to the URI */
objectlists[0].pos = 0;
rv = add_objects(sn, rq, vs_os, name, ppath, &objectlists[0]);
if (rv != REQ_PROCEED)
return rv;
for (int pass = 0; ; pass++) {
/*
* At any given time, we are processing directives from one list of
* objects and simultaneously constructing a list of additional
* objects that we should process on the next pass.
*/
const objlist& current = objectlists[pass & 1];
objlist& additional = objectlists[!(pass & 1)];
additional.pos = 0;
/* If we don't have any more objects to process... */
if (!current.pos) {
/* If nobody translated ppath to a local file system path... */
if (nametrans_rv == REQ_NOACTION && *ppath == '/') {
/* Use the <virtual-server> <document-root> */
const NSString& root = vs->getNormalizedDocumentRoot();
rv = request_set_path(sn, rq, root.data(), root.length(),
ppath, strlen(ppath));
if (rv != REQ_PROCEED)
return rv;
nametrans_rv = REQ_PROCEED;
/*
* Check if any additional objects apply as a result of
* prepending the document root
*/
name = NULL;
ppath = pblock_findkeyval(pb_key_ppath, rq->vars);
rv = add_objects(sn, rq, vs_os, name, ppath, &additional);
if (rv != REQ_PROCEED)
return rv;
continue;
}
/* We're done when there are no more objects to process */
break;
}
/*
* Process the objects in the order we encountered them. Note that
* because objset_add_object() sorts objects, this order might not be
* the same as the order in rq->os. In other words, the order in which
* objects are processed during the Input, AuthTrans, and NameTrans
* stages may vary from the order in which they are processed in
* subsequent stages.
*/
for (int x = 0; x < current.pos; x++) {
httpd_object *obj = current.obj[x];
if (log_finest) {
char *obj_name = pblock_pblock2str(obj->name, NULL);
log_error(LOG_FINEST, PROCESS_URI_OBJECTS, sn, rq,
"processing object %s",
obj_name);
}
/* Run Input stage for the new object */
if (!session_input_done(sn) && obj->dt[NSAPIInput].ni)
servact_input(sn, rq);
/* Run AuthTrans stage for the new object */
rv = _directive_applyone(NSAPIAuthTrans,
&obj->dt[NSAPIAuthTrans],
sn, rq);
if (rv == REQ_RESTART)
goto servact_objset_uri2path_restart;
if (rv != REQ_NOACTION && rv != REQ_PROCEED)
return rv;
/*
* Check the <virtual-server> <canonical-server-name>. Note that
* we do this only after executing the default object's AuthTrans
* directives. This gives the administrator an opportunity to
* modify protocol, hostname, and port values during AuthTrans.
*/
if (!checked_server_name) {
checked_server_name = PR_TRUE;
rv = http_canonical_redirect(sn, rq);
if (rv != REQ_NOACTION)
return rv;
}
/* Run NameTrans stage for the new object */
rv = _directive_applyone(NSAPINameTrans,
&obj->dt[NSAPINameTrans],
sn, rq);
if (rv == REQ_RESTART)
goto servact_objset_uri2path_restart;
if (rv != REQ_NOACTION && rv != REQ_PROCEED)
return rv;
if (rv == REQ_PROCEED)
nametrans_rv = REQ_PROCEED;
/*
* Check if any additional objects apply as a result of executing
* the directives in this object
*/
name = pblock_findkeyval(pb_key_name, rq->vars);
ppath = pblock_findkeyval(pb_key_ppath, rq->vars);
rv = add_objects(sn, rq, vs_os, name, ppath, &additional);
if (rv != REQ_PROCEED)
return rv;
}
}
/* Have path, will travel. */
if( (pp = pblock_removekey(pb_key_ppath, rq->vars)) ) {
strcpy(pp->name, "path");
pblock_kpinsert(pb_key_path, pp, rq->vars);
}
else {
log_error(LOG_MISCONFIG, PROCESS_URI_OBJECTS, sn, rq,
XP_GetAdminStr(DBT_noPartialPathAfterObjectProcessi_));
return REQ_ABORTED;
}
return REQ_PROCEED;
}
/* ------------------------ servact_translate_uri ------------------------- */
static inline char* _servact_translate_uri(Session* sn, Request* rq)
{
char *path;
if(servact_uri2path(sn, rq) == REQ_ABORTED)
path = NULL;
else
path = pool_strdup(pblock_pool(rq->vars), pblock_findkeyval(pb_key_path, rq->vars));
return path;
}
NSAPI_PUBLIC char *servact_translate_uri(char *uri, Session *sn)
{
Request *rq = request_restart_internal(uri, NULL);
char* res = _servact_translate_uri(sn, rq);
request_free(rq);
return res;
}
NSAPI_PUBLIC char* INTservact_translate_uri2(char* uri, Session* sn, Request* rq)
{
char* res = 0;
Request *newrq = request_create_child(sn, rq, NULL, uri, NULL);
if (newrq) {
res = _servact_translate_uri(sn, newrq);
request_free(newrq);
}
return res;
}
/* ------------------------ servact_require_right ------------------------- */
NSAPI_PUBLIC int servact_require_right(Request *rq, const char *right, int len)
{
pb_param *pp = pblock_findkey(pb_key_required_rights, rq->vars);
if (pp) {
int old_len = strlen(pp->value);
char *value = (char *) REALLOC(pp->value, old_len + 1 + len + 1);
if (!value)
return -1;
pp->value = value;
value[old_len] = ',';
memcpy(value + old_len + 1, right, len);
value[old_len + 1 + len] = '\0';
} else {
pp = pblock_kvinsert(pb_key_required_rights, right, len, rq->vars);
if (!pp)
return -1;
}
return 0;
}
/* --------------------- servact_get_required_rights ---------------------- */
static char **servact_get_required_rights(Request *rq)
{
const char *custom = pblock_findkeyval(pb_key_required_rights, rq->vars);
// Count the number of custom access rights
int ncustom = 0;
if (custom) {
for (const char *p = custom; *p != '\0'; p++) {
if (*p == ',')
ncustom++;
}
ncustom++;
}
// Allocate an array that can accomodate both the HTTP method access right
// and any custom access rights
char **rights = (char **) MALLOC((1 + ncustom + 1) * sizeof(char *));
if (!rights)
return NULL;
// Set the HTTP method access right at the front of the rights array
const char *method = pblock_findkeyval(pb_key_method, rq->reqpb);
if (!method)
return NULL;
int method_len = strlen(method);
rights[0] = (char *) MALLOC(5 + method_len + 1);
if (!rights[0])
return NULL;
memcpy(rights[0], ACL_HTTP_RIGHT_PREFIX, ACL_HTTP_RIGHT_PREFIX_LEN);
memcpy(rights[0] + 5, method, method_len);
rights[0][5 + method_len] = '\0';
// Append any custom access rights to the rights array
int i = 1;
if (custom) {
char *copy = STRDUP(custom);
if (!copy)
return NULL;
char *next = NULL;
char *token = util_strtok(copy, ",", &next);
while (token) {
rights[i++] = STRDUP(token);
token = util_strtok(NULL, "," , &next);
}
}
// Terminate the rights array with a NULL
rights[i] = NULL;
return rights;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------ PathCheck ------------------------------- */
/* ------------------------------------------------------------------------ */
static inline PRBool build_acl_list(char *path, const char *luri, ACLListHandle **acllist, ACLListHandle *aclroot)
{
PRBool rv = PR_TRUE;
// Strip ;-delimited parameters from luri so /protected;sneaky/index.html
// will match a /protected/index.html ACL.
char* stripped = STRDUP(luri);
util_uri_strip_params(stripped);
// Each ACL_Get*Acls() call must succeed for us to return PR_TRUE
rv &= ACL_GetPathAcls(stripped, acllist, "uri=", aclroot);
rv &= ACL_GetPathAcls(path, acllist, "path=", aclroot);
FREE(stripped);
return rv;
}
static inline PRBool path_requires_list_right(Request *rq, const char *path)
{
NSFCFileInfo *finfo = NULL;
return (ISMGET(rq) &&
INTrequest_info_path(path, rq, &finfo) == PR_SUCCESS &&
finfo &&
finfo->pr.type == PR_FILE_DIRECTORY);
}
static inline PRBool method_always_allowed(Session *sn, Request *rq, const VirtualServer *vs, ACLListHandle_t *aclroot, const char *method)
{
char http_right[30];
memcpy(http_right, ACL_HTTP_RIGHT_PREFIX, ACL_HTTP_RIGHT_PREFIX_LEN);
util_strlcpy(http_right + ACL_HTTP_RIGHT_PREFIX_LEN, method,
sizeof(http_right) - ACL_HTTP_RIGHT_PREFIX_LEN);
char *rights[2];
rights[0] = http_right;
rights[1] = NULL;
return rights_always_allowed(sn, rq, vs, aclroot, rights);
}
static inline PRBool rights_always_allowed(Session *sn, Request *rq, const VirtualServer *vs, ACLListHandle_t *aclroot, char **rights)
{
// Bail if an ACE can deny the right
if (ACL_CanDeny(aclroot, rights, http_generic))
return PR_FALSE;
// Get the default object from obj.conf
httpd_objset *objset = vs->getObjset();
if (!objset)
return PR_FALSE;
httpd_object *obj = objset_findbyname(vs->defaultObjectName, 0, objset);
if (!obj)
return PR_FALSE;
PR_ASSERT(rq->acllist == NULL);
// Invoke the default object's check-acl directives to build a list of
// ACLs that apply to all paths (i.e. add the default ACLs to rq->acllist)
//
// XXX like the ACL cache code, this code assumes PathCheck fn=check-acl
// directives won't be wrapped by <Client> tags (i.e. it assumes that the
// list of relevant ACLs varies only by path)
pblock_kvinsert(pb_key_magnus_internal_default_acls_only, "1", 1, rq->vars);
int res = _perform_pathchecks(sn, rq, obj, 1);
param_free(pblock_removekey(pb_key_magnus_internal_default_acls_only, rq->vars));
// Do the default ACLs always allow this right?
PRBool always_allowed = PR_FALSE;
if (res == REQ_PROCEED)
always_allowed = ACL_AlwaysAllows(rq->acllist, rights, http_generic);
// Discard the default ACL list
if (rq->acllist != NULL) {
ACL_ListDecrement(NULL, rq->acllist);
rq->acllist = NULL;
}
return always_allowed;
}
NSAPI_PUBLIC int servact_pathchecks(Session *sn, Request *rq)
{
httpd_objset *os = rq->os;
register int x;
httpd_object *obj;
char *uri=0, *path=0;
int not_found_in_acl_cache = 0;
NSErr_t *errp = 0;
const VirtualServer *vs = request_get_vs(rq);
ACLListHandle_t *aclroot;
ACLCache *aclcache;
const char *vsid;
PR_ASSERT(rq->acllist == NULL);
if (vs == 0)
return REQ_ABORTED; // nothing we can do...
vsid = vs_get_id(vs);
aclroot = vs->getACLList();
aclcache = vs->getConfiguration()->getACLCache();
if (aclroot) {
uri = pblock_findkeyval(pb_key_uri, rq->reqpb);
path = pblock_findkeyval(pb_key_path, rq->vars);
ACLShortcut_t shortcut = ACL_SHORTCUT_UNKNOWN;
if (path_requires_list_right(rq, path)) {
// This is a request to list the contents of a directory
servact_require_right(rq, ACL_GENERIC_RIGHT_LIST, ACL_GENERIC_RIGHT_LIST_LEN);
} else if (!pblock_findkeyval(pb_key_required_rights, rq->vars)) {
// This isn't a request to list the contents of a directory and
// there are no custom required rights, so maybe we can skip ACL
// checks for this HTTP method altogether
shortcut = vs->getACLMethodShortcut(rq->method_num);
if (shortcut == ACL_SHORTCUT_UNKNOWN) {
char *method = pblock_findkeyval(pb_key_method, rq->reqpb);
if (method_always_allowed(sn, rq, vs, aclroot, method)) {
ereport(LOG_VERBOSE, "%s requests for virtual server %s can safely bypass ACL checks", method, vsid);
shortcut = ACL_SHORTCUT_ALWAYS_ALLOW;
} else {
ereport(LOG_VERBOSE, "%s requests for virtual server %s cannot bypass ACL checks", method, vsid);
shortcut = ACL_SHORTCUT_NONE;
}
vs->setACLMethodShortcut(rq->method_num, shortcut);
}
}
if (shortcut == ACL_SHORTCUT_ALWAYS_ALLOW) {
rq->acllist = ACL_LIST_NO_ACLS;
aclroot = NULL;
} else {
if (aclcache == 0 ||
!(ISMGET(rq) ? aclcache->CheckGet(vsid, uri, &rq->acllist) :
aclcache->Check(vsid, uri, &rq->acllist)))
{
not_found_in_acl_cache = 1;
}
}
} else {
rq->acllist = ACL_LIST_NO_ACLS;
}
// XXXrobm PathCheck functions need ACL information. However, the ACL
// functions don't necessarily execute before ones that need the info.
// The "real" solution is to make a new directive between NameTrans and
// PathCheck that does the ACLs, but we're too far along into 2.0 to
// make such a change. So I've hard-coded it so that check-acl gets called
// first.
//
// acl (check-acl) pathchecks go first
// if we cached the ACL list for this URI, we do not need to do them, though,
// as all they do is modify rq->acllist, and we have that already
//
if (aclroot && not_found_in_acl_cache) {
for(x = 0; x < os->pos; ++x) {
obj = os->obj[x];
int rv = _perform_pathchecks(sn, rq, os->obj[x], 1);
if (rv != REQ_NOACTION && rv != REQ_PROCEED) {
ACL_ListDecrement(errp, rq->acllist);
rq->acllist = NULL;
return rv;
}
}
}
//
// now for the non-acl pathchecks
//
for(x = 0; x < os->pos; ++x) {
obj = os->obj[x];
int rv = _perform_pathchecks(sn, rq, os->obj[x], 0);
if (rv != REQ_NOACTION && rv != REQ_PROCEED) {
ACL_ListDecrement(errp, rq->acllist);
rq->acllist = NULL;
return rv;
}
// nsconfig stuff modifies os. Make sure we stay on the right object
for(x = 0; x < os->pos; ++x)
if(os->obj[x] == obj)
break;
}
//
// Finally, evaluate any ONE ACLs - must be done *after* all flavors of
// pathchecks so that the pblock/"path" value is final.
//
if (aclroot) {
/* After getting the PathCheck ACLs, look for any affiliated with any
* component of the URI. Finally look for an FS pathname-bound ACLs.
*/
uri = pblock_findkeyval(pb_key_uri, rq->reqpb);
path = pblock_findkeyval(pb_key_path, rq->vars);
if (not_found_in_acl_cache) {
// we did not get rq->acllist from the ACL cache
// so we need to build it now.
//
// now add any matching path and uri ACLs
// as we're still operating on our private rq->acllist (it's not
// coming from the ACL cache yet), we can modify it...
if (!build_acl_list(path, uri, &rq->acllist, aclroot)) {
// failed - clean up...
ACL_ListDecrement(errp, rq->acllist);
rq->acllist = NULL;
return REQ_ABORTED;
}
// now enter the brand spanking new acllist into the ACL cache
// (we pass a reference as we might get back a different,
// but equivalent list, and in any case, with an incremented refcount)
if (aclcache) {
// Bug 461689 don't cache CGI URIs that contain path info
if (!pblock_findkeyval(pb_key_path_info, rq->vars) && !strchr(uri, ';')) {
if (ISMGET(rq))
aclcache->EnterGet(vsid, uri, &rq->acllist);
else
aclcache->Enter(vsid, uri, &rq->acllist);
} else if (!rq->acllist) {
rq->acllist = ACL_LIST_NO_ACLS;
}
}
}
}
// from this point on, the acllist is read-only.
if (aclroot && rq->acllist != ACL_LIST_NO_ACLS) {
/* Resource has ACLs, so accelerator cache cannot be used */
rq->request_is_cacheable = 0;
char **rights = servact_get_required_rights(rq);
/* Evaluate ACLs */
int rv = ACL_SetupEval(rq->acllist, sn, rq, rights, http_generic, NULL);
ACL_ListDecrement(0, rq->acllist); // we don't use rq->acllist anymore after this
rq->acllist = NULL; // (might have ended up in the ACLCache, though -
// at which point the refcount would prevent it
// from being deleted)
if ( rv != ACL_RES_ALLOW ) {
if (!pblock_findkeyval(pb_key_status, rq->srvhdrs)) {
/* Set the status only if it is not already set */
protocol_status(sn, rq, PROTOCOL_SERVER_ERROR, NULL);
}
return REQ_ABORTED;
}
} else {
ACL_ListDecrement(0, rq->acllist);
rq->acllist = NULL;
}
return REQ_PROCEED;
}
/** This method returns ACLList for a request without a restart **/
NSAPI_PUBLIC int
ACL_BuildAclList(char *path, const char *luri, ACLListHandle **acllist, ACLListHandle *aclroot)
{
return build_acl_list(path, luri, acllist, aclroot);
}
/*
doacl defines if we should call check-acl only. 1 == do only it.
0 == do everything else
*/
static int _perform_pathchecks(Session *sn, Request *rq, httpd_object *obj, int doacl)
{
register int x, isacl;
dtable *d = &obj->dt[NSAPIPathCheck];
int rv;
static FuncStruct *fs_check_acl = NULL;
if (!fs_check_acl)
fs_check_acl = func_find_str("check-acl");
for(x = 0; x < d->ni; x++) {
#ifdef DEBUG
/* check-acl should have been resolved to a FuncStruct * by now */
const char *fn = pblock_findkeyval(pb_key_fn, d->inst[x].param.pb);
PR_ASSERT(d->inst[x].f != NULL || fn == NULL || strcmp(fn, "check-acl"));
#endif
isacl = (d->inst[x].f == fs_check_acl);
if (doacl != isacl)
continue;
rv = object_execute(&d->inst[x], sn, rq);
if (rv != REQ_NOACTION && rv != REQ_PROCEED) {
return rv;
}
}
return REQ_PROCEED;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------ ObjectType ------------------------------ */
/* ------------------------------------------------------------------------ */
/* -------------------------- _perform_findinfo --------------------------- */
static inline int _perform_findinfo(Session *sn, Request *rq, httpd_object *obj)
{
return _directive_applyall(NSAPIObjectType,
&obj->dt[NSAPIObjectType], sn, rq);
}
/* --------------------------- request_fileinfo --------------------------- */
NSAPI_PUBLIC int servact_fileinfo(Session *sn, Request *rq)
{
httpd_objset *os = rq->os;
register int x;
for(x = os->pos - 1; x != -1; --x) {
/* REQ_PROCEED: multiple instances supercede each other */
int rv = _perform_findinfo(sn, rq, os->obj[x]);
if (rv != REQ_NOACTION && rv != REQ_PROCEED)
return rv;
}
return REQ_PROCEED;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------- Service -------------------------------- */
/* ------------------------------------------------------------------------ */
/* ----------------------------- check_method ----------------------------- */
static inline int check_method(const char *mexp, Session *sn, Request *rq)
{
PR_ASSERT(mexp != NULL);
// Get method from the request
const char *m = pblock_findkeyval(pb_key_method, rq->reqpb);
if (!m) {
// Invalid request
return REQ_ABORTED;
}
// Compare method from request with method expression from directive
switch(shexp_noicmp(m, mexp)) {
case 0:
// Match, call this SAF
return REQ_PROCEED;
case 1:
// Mismatch, don't call this SAF
return REQ_NOACTION;
}
log_error(LOG_MISCONFIG, XP_GetAdminStr(DBT_checkMethod_), sn, rq,
XP_GetAdminStr(DBT_invalidShexpS_), mexp);
// Misconfiguration, abort request
return REQ_ABORTED;
}
/* ------------------------- check_service_method ------------------------- */
static inline int check_service_method(pblock *pb, Session *sn, Request *rq)
{
// Get method expression from directive
const char *mexp = pblock_findkeyval(pb_key_method, pb);
if (!mexp) {
// Directive doesn't have a method expression
if (ISMOPTIONS(rq)) {
// This is an OPTIONS request, and directive doesn't explicitly
// indicate the SAF can handle OPTIONS; don't call this SAF
return REQ_NOACTION;
} else if (ISMTRACE(rq)) {
// This is an TRACE request, and directive doesn't explicitly
// indicate the SAF can handle TRACE; don't call this SAF
return REQ_NOACTION;
} else {
// Call this SAF
return REQ_PROCEED;
}
}
return check_method(mexp, sn, rq);
}
/* --------------------------- check_io_method ---------------------------- */
static inline int check_io_method(pblock *pb, Session *sn, Request *rq)
{
// Get method expression from directive
const char *mexp = pblock_findkeyval(pb_key_method, pb);
if (!mexp) {
// Call this SAF
return REQ_PROCEED;
}
return check_method(mexp, sn, rq);
}
/* ------------------------------ check_type ------------------------------ */
static inline int check_type(pblock *pb, Session *sn, Request *rq, pblock *hdrs)
{
// Get type expression from directive
const char *texp = pblock_findkeyval(pb_key_type, pb);
if (!texp) {
// Directive doesn't have a type expression, call this SAF
return REQ_PROCEED;
}
// Get content-type from request/response headers
const char *t = pblock_findkeyval(pb_key_content_type, hdrs);
if (!t)
t = "";
// Compare content-type from response with type expression from directive
switch(shexp_noicmp(t, texp)) {
case 0:
// Match, call this SAF
return REQ_PROCEED;
case 1:
// Mismatch, don't call this SAF
return REQ_NOACTION;
}
log_error(LOG_MISCONFIG, XP_GetAdminStr(DBT_checkType_), sn, rq,
XP_GetAdminStr(DBT_invalidShexpS_), texp);
// Misconfiguration, abort request
return REQ_ABORTED;
}
/* ----------------------------- check_query ------------------------------ */
static inline int check_query(pblock *pb, Session *sn, Request *rq)
{
// Get query expression from directive
const char *qexp = pblock_findkeyval(pb_key_query, pb);
if (!qexp) {
// Directive doesn't have a query expression, call this SAF
return REQ_PROCEED;
}
// Get query string from request
const char *q = pblock_findkeyval(pb_key_query, rq->reqpb);
if (!q) {
// Request didn't contain a query string, don't call this SAF
return REQ_NOACTION;
}
// Compare query string from request with query expression from directive
switch(shexp_noicmp(q, qexp)) {
case 0:
// Match, call this SAF
return REQ_PROCEED;
case 1:
// Mismatch, don't call this SAF
return REQ_NOACTION;
}
log_error(LOG_MISCONFIG, XP_GetAdminStr(DBT_checkQuery_), sn, rq,
XP_GetAdminStr(DBT_invalidShexpS_), qexp);
// Misconfiguration, abort request
return REQ_ABORTED;
}
/* ----------------------------- _CHECK_PARAM ----------------------------- */
#define _CHECK_PARAM(res) \
switch (res) { \
case REQ_NOACTION: \
continue; /* Skip SAF */ \
case REQ_PROCEED: \
break; /* Call SAF */ \
default: \
return res; \
}
/* --------------------------- request_service ---------------------------- */
NSAPI_PUBLIC int servact_service(Session *sn, Request *rq)
{
httpd_objset *os = rq->os;
int x;
// Track session statistics
HttpRequest *hrq = ((NSAPIRequest *)rq)->hrq;
if (hrq)
hrq->GetDaemonSession().setMode(STATS_THREAD_RESPONSE);
PRBool first_saf = PR_TRUE;
// Get method from request
const char *m = pblock_findkeyval(pb_key_method, rq->reqpb);
if (!m) {
// Invalid request
return REQ_ABORTED;
}
for(x = os->pos - 1; x != -1; --x) {
httpd_object* obj = os->obj[x];
int y;
int stage_rv = REQ_NOACTION;
dtable *d;
d = &obj->dt[NSAPIService];
for(y = 0; y < d->ni; y++) {
// _CHECK_PARAM falls through, continues, or returns as appropriate
_CHECK_PARAM(check_type(d->inst[y].param.pb, sn, rq, rq->srvhdrs))
_CHECK_PARAM(check_service_method(d->inst[y].param.pb, sn, rq))
_CHECK_PARAM(check_query(d->inst[y].param.pb, sn, rq))
_CHECK_PARAM(object_check(&d->inst[y], sn, rq))
/* Success: execute function */
// Interpolate parameters
pblock *param;
if (d->inst[y].param.model) {
param = object_interpolate(d->inst[y].param.model, &d->inst[y], sn, rq);
if (!param)
return REQ_ABORTED;
} else {
param = d->inst[y].param.pb;
}
// If we need to unchunk the request message body...
if (first_saf && !INTERNAL_REQUEST(rq) && pblock_findkey(pb_key_transfer_encoding, rq->headers) && !pblock_findkey(pb_key_content_length, rq->headers)) {
int ibufsize = -1;
int itimeout = -1;
char *ibufsize_str = pblock_findkeyval(pb_key_ChunkedRequestBufferSize,
param);
if (ibufsize_str)
ibufsize = atoi(ibufsize_str);
char *itimeout_str = pblock_findkeyval(pb_key_ChunkedRequestTimeout,
param);
if (itimeout_str)
itimeout = atoi(itimeout_str);
if (http_unchunk_request(sn, rq, ibufsize, itimeout) == REQ_ABORTED) {
stage_rv = REQ_ABORTED;
break;
}
}
first_saf = PR_FALSE;
int saf_rv = func_exec_directive(&d->inst[y], param, sn, rq);
if (saf_rv != REQ_NOACTION) {
stage_rv = saf_rv;
break;
}
}
if (stage_rv != REQ_NOACTION) {
// a SAF got to run
return stage_rv;
}
}
return REQ_NOACTION;
}
/* ------------------------------------------------------------------------ */
/* -------------------------------- AddLog -------------------------------- */
/* ------------------------------------------------------------------------ */
/* --------------------------- object_findlogs ---------------------------- */
static inline int _perform_logs(Session *sn, Request *rq, httpd_object *obj)
{
return _directive_applyall(NSAPIAddLog, &obj->dt[NSAPIAddLog], sn, rq);
}
/* ------------------------------ _find_logs ------------------------------ */
NSAPI_PUBLIC int servact_addlogs(Session *sn, Request *rq)
{
httpd_objset *os = rq->os;
register int x;
for(x = os->pos - 1; x != -1; --x) {
int rv = _perform_logs(sn, rq, os->obj[x]);
if (rv != REQ_NOACTION && rv != REQ_PROCEED)
return rv;
}
return REQ_PROCEED;
}
/* ------------------------------------------------------------------------ */
/* -------------------------------- Error --------------------------------- */
/* ------------------------------------------------------------------------ */
/* Assumes that status is properly formatted. */
static inline int _find_error(Session *sn, Request *rq, httpd_object *obj)
{
char *status = pblock_findkeyval(pb_key_status, rq->srvhdrs);
register int y, r;
register char *t;
dtable *d;
d = &obj->dt[NSAPIError];
for(y = 0; y < d->ni; y++) {
if( (t = pblock_findval("reason", d->inst[y].param.pb)) ) {
if(strcasecmp(t, &status[4]))
continue;
}
else if ( (t = pblock_findval("code", d->inst[y].param.pb)) )
if(strncmp(t, status, 3))
continue;
/* One of those passed. Try to execute.
* <Client> restrictions are applied by object_execute(),
* which will return NO_ACTION on mismatch.
*/
r = object_execute(&d->inst[y], sn, rq);
if (r != REQ_NOACTION)
return r;
}
return REQ_NOACTION;
}
NSAPI_PUBLIC int servact_finderror(Session *sn, Request *rq)
{
register int x;
PR_ASSERT(rq->os);
for(x = rq->os->pos - 1; x != -1; --x) {
int rv = _find_error(sn, rq, rq->os->obj[x]);
if (rv != REQ_NOACTION)
return rv;
}
return REQ_NOACTION;
}
/* ------------------------------------------------------------------------ */
/* -------------------------------- ROUTE --------------------------------- */
/* ------------------------------------------------------------------------ */
/* ---------------------------- _perform_route ---------------------------- */
/*
* Performs proxy routing.
*
*
*/
int _perform_route(Session *sn, Request *rq, httpd_object *obj)
{
return _directive_applyall(NSAPIRoute, &obj->dt[NSAPIRoute], sn, rq);
}
/* ---------------------------- servact_route ----------------------------- */
NSAPI_PUBLIC int servact_route(Session *sn, Request *rq)
{
httpd_objset *os = rq->os;
register int x;
for(x = os->pos - 1; x != -1; --x) {
/* REQ_PROCEED: multiple instances supercede each other */
int rv = _perform_route(sn, rq, os->obj[x]);
if (rv != REQ_NOACTION && rv != REQ_PROCEED)
return rv;
}
return REQ_PROCEED;
}
/* ------------------------------------------------------------------------ */
/* --------------------------------- DNS ---------------------------------- */
/* ------------------------------------------------------------------------ */
/* ----------------------------- _perform_dns ----------------------------- */
/*
* Performs custom DNS resolution.
*
*
*/
int _perform_dns(Session *sn, Request *rq, httpd_object *obj)
{
register int y, r;
dtable *d;
d = &obj->dt[8];
for(y = 0; y < d->ni; y++) {
if ( (r = object_execute(&d->inst[y], sn, rq)) != REQ_NOACTION)
return r;
}
return REQ_NOACTION;
}
/* ----------------------------- servact_dns ------------------------------ */
int servact_dns(Session *sn, Request *rq)
{
httpd_objset *os = rq->os;
register int x, r;
for(x = os->pos - 1; x != -1; --x)
if( (r = _perform_dns(sn, rq, os->obj[x])) != REQ_NOACTION)
return r;
return REQ_NOACTION;
}
PRHostEnt *optimized_gethostbyname(const char *host, Session *sn, Request *rq)
{
if (!host || !*host)
return NULL;
PRNetAddr addr;
int cnt = 0;
int dots = 1;
int len = 0;
char*tmp;
log_error(LOG_VERBOSE, NULL, sn, rq, "attempting to resolve %s", host);
// XXX
PRHostEnt* he = (PRHostEnt*) pool_malloc(sn->pool, sizeof(PRHostEnt));
if (!he)
return NULL;
// XXX
char* hostbuf = (char*) pool_malloc(sn->pool, PR_NETDB_BUF_SIZE);
if (!hostbuf)
return NULL;
if (!rq->vars || !(tmp = pblock_findval("local-domain-levels", rq->vars)) ||
(dots = atoi(tmp)) < 0 || PR_StringToNetAddr(host, &addr) == PR_SUCCESS) { /* off by default in Proxy 3.51 */
if (PR_GetHostByName(host, hostbuf, PR_NETDB_BUF_SIZE, he) != PR_SUCCESS)
return NULL;
return he;
}
const char* p;
for(p=host; *p; p++) {
if (*p == '.')
cnt++;
}
len = (int)(p - host);
if (cnt > dots && host[len-1] != '.') {
char *dothost = (char *)pool_malloc(sn->pool, len + 2);
strcpy(dothost, host);
dothost[len] = '.';
dothost[len+1] = '\0';
if (PR_GetHostByName(dothost, hostbuf, PR_NETDB_BUF_SIZE, he) != PR_SUCCESS)
{
pool_free(sn->pool, dothost);
return NULL;
}
pool_free(sn->pool, dothost);
} else {
if (PR_GetHostByName(host, hostbuf, PR_NETDB_BUF_SIZE, he) != PR_SUCCESS)
return NULL;
}
return he;
}
PRHostEnt *servact_gethostbyname(const char *host, Session *sn, Request *rq)
{
#ifdef XXX_MCC_PROXY
#ifdef PROXY_DNS_CACHE
DNSCacheKey key;
#endif
TSET((THROTTLE_ACTION_DNS));
#endif
PRHostEnt* rv = NULL;
if (host) {
#ifdef MCC_PROXY
if ((rv = host_dns_cache_lookup(host, sn, rq)))
return rv;
#endif
if (sn && rq) {
#ifdef XXX_MCC_PROXY
char *pushed = rq->host;
rq->host = host;
rq->hp = NULL;
#endif
switch (servact_dns(sn, rq)) {
case REQ_PROCEED:
#ifdef XXX_MCC_PROXY
rv = rq->hp;
#endif
break;
case REQ_NOACTION:
rv = optimized_gethostbyname(host, sn, rq);
break;
default:
rv = NULL;
break;
}
#ifdef XXX_MCC_PROXY
rq->host = pushed;
#endif
} else {
rv = optimized_gethostbyname(host, sn, rq);
}
#ifdef XXX_MCC_PROXY
#ifdef PROXY_DNS_CACHE
dns_cache_insert(&key, rv);
#endif
#endif
}
return rv;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------- Connect -------------------------------- */
/* ------------------------------------------------------------------------ */
/* --------------------------- _perform_connect --------------------------- */
/*
* Returns the connected socket descriptor.
*
* RELIES HEAVILY ON THE RIGHT VALUES SET FOR REQ_* DEFINES:
*
* REQ_PROCEED == 0 which may also be a valid returned sd (in practice
* zero is always already in use). The success can't be
* tested against REQ_PROCEED, but with condition > -1.
*
* REQ_ABORTED == -1 which is the same as when the connection fails, and
* the only legal negative value for a connect function
* to return.
*
* REQ_NOACTION == -2 when no function was set, and the default should be
* used.
*
* Other negative values will be treated as -1 return value
* (failure to connect).
*
*/
int _perform_connect(Session *sn, Request *rq, httpd_object *obj)
{
register int y, r;
dtable *d;
d = &obj->dt[9];
for(y = 0; y < d->ni; y++) {
if ( (r = object_execute(&d->inst[y], sn, rq)) != REQ_NOACTION)
return r;
}
return REQ_NOACTION;
}
/* --------------------------- servact_connect ---------------------------- */
int servact_connect(const char *host, int port, Session *sn, Request *rq)
{
if (host && sn && rq) {
httpd_objset *os = rq->os;
register int x, r;
pblock_nvinsert("connect-host",host,rq->vars);
pblock_nninsert("connect-port",port,rq->vars);
for(x = os->pos - 1; x != -1; --x) {
if( (r = _perform_connect(sn, rq, os->obj[x])) != REQ_NOACTION) {
param_free(pblock_remove("connect-host",rq->vars));
param_free(pblock_remove("connect-port",rq->vars));
return (r > -1) ? r : -1;/* return sd, or SYS_ERROR_FD */
}
}
param_free(pblock_remove("connect-host",rq->vars));
param_free(pblock_remove("connect-port",rq->vars));
}
return REQ_NOACTION;
}
/* ------------------------------------------------------------------------ */
/* -------------------------------- Filter -------------------------------- */
/* ------------------------------------------------------------------------ */
/* --------------------------- servact_filter ----------------------------- */
int _perform_filter(Session *sn, Request *rq, httpd_object *obj)
{
register int y, r;
char *t, *u;
dtable *d;
d = &obj->dt[10];
for(y = 0; y < d->ni; y++) {
/* currently always execute function */
r = object_execute(&d->inst[y], sn, rq);
if ( r != REQ_NOACTION && r != REQ_PROCEED )
return r;
}
return REQ_NOACTION;
}
int servact_filter(Session *sn, Request *rq)
{
if (sn && rq) {
httpd_objset *os = rq->os;
register int x, r;
for(x = os->pos - 1; x != -1; --x) {
r = _perform_filter(sn, rq, os->obj[x]);
if( r != REQ_NOACTION && r != REQ_PROCEED )
return r;
}
}
return REQ_PROCEED;
}
NSAPI_PUBLIC int servact_nowaytohandle(Session *sn, Request *rq)
{
const char *method = pblock_findkeyval(pb_key_method, rq->reqpb);
HttpMethodRegistry& registry = HttpMethodRegistry::GetRegistry();
if (registry.IsKnownHttpMethod(method) == PR_FALSE) {
// Unknown method
http_status(sn, rq, PROTOCOL_NOT_IMPLEMENTED, NULL);
log_error(LOG_MISCONFIG, XP_GetAdminStr(DBT_handleProcessed_), sn, rq,
XP_GetAdminStr(DBT_unknownMethod),
pblock_findkeyval(pb_key_uri, rq->reqpb));
return REQ_ABORTED;
}
NSString methods;
pb_param *pp = pblock_remove("allow", rq->srvhdrs);
if (pp) {
methods.append(pp->value);
param_free(pp);
}
if (FindApplicableMethods(sn, rq, methods) == PR_TRUE) {
pblock_nvinsert("allow", methods, rq->srvhdrs);
}
if (ISMOPTIONS(rq)) {
// OPTIONS response
param_free(pblock_removekey(pb_key_content_type, rq->srvhdrs));
pblock_nvinsert("content-length", "0", rq->srvhdrs);
http_status(sn, rq, PROTOCOL_OK, NULL);
http_start_response(sn, rq);
return REQ_PROCEED;
}
http_status(sn, rq, PROTOCOL_METHOD_NOT_ALLOWED, NULL);
log_error(LOG_MISCONFIG, XP_GetAdminStr(DBT_handleProcessed_), sn, rq,
XP_GetAdminStr(DBT_methodNotAllowed),
pblock_findkeyval(pb_key_uri, rq->reqpb));
return REQ_ABORTED;
}
/* ----------------------- servact_handle_processed ----------------------- */
NSAPI_PUBLIC int servact_handle_processed(Session *sn, Request *rq)
{
int rv;
servact_handle_processed_restart:
#ifdef MCC_PROXY
/* Awful hack for the proxy to make it work with netlib */
glob_rq = rq;
glob_sn = sn;
#endif
do {
/* Figure out what objects it uses */
rv = servact_uri2path(sn, rq);
if (rv != REQ_PROCEED)
continue;
/* Process PathChecks */
rv = servact_pathchecks(sn, rq);
if (rv != REQ_PROCEED)
continue;
/* Find that file's typing information */
rv = servact_fileinfo(sn, rq);
if (rv != REQ_PROCEED)
continue;
#ifdef MCC_PROXY
/* Find the Filters to pipe the data through */
rv = servact_filter(sn, rq);
if (rv != REQ_PROCEED)
continue;
#endif
/* Service object (actually send it) */
rv = servact_service(sn, rq);
if (rv != REQ_PROCEED)
continue;
} while (rv == REQ_RESTART);
if (INTERNAL_REQUEST(rq)) {
/* We don't generate error pages or log accesses for internal requests */
return rv;
}
/* If nobody could handle the method, list the methods we do support */
if (rv == REQ_NOACTION)
rv = servact_nowaytohandle(sn, rq);
PR_ASSERT(rv == REQ_PROCEED || rv == REQ_ABORTED || rv == REQ_EXIT);
/* Wrap up the request/response if someone serviced it */
if (rv == REQ_PROCEED)
rv = httpfilter_finish_request(sn, rq);
/* If there was an error handling the request, return an error message */
if (rv == REQ_ABORTED) {
/* Try to clear any filter stack error or partial response */
switch (httpfilter_reset_response(sn, rq)) {
case REQ_NOACTION:
/* Response was already committed, so there's nothing we can do */
rv = REQ_ABORTED;
break;
case REQ_PROCEED:
/* We're clear to send our error response */
rv = error_report(sn, rq);
break;
case REQ_ABORTED:
/* Error running Input/Output; send 500 Server Error */
/* Should do this only when we're not blocking a mime type. */
if (!pblock_findval("block-this-mime-type", rq->vars))
protocol_status(sn, rq, 500, NULL);
rv = error_report(sn, rq);
break;
}
if (rv == REQ_RESTART)
goto servact_handle_processed_restart;
httpfilter_finish_request(sn, rq);
}
/* If things went horribly wrong, make sure the connection dies */
if (rv == REQ_EXIT)
KEEP_ALIVE(rq) = 0;
/* Log the request */
servact_addlogs(sn, rq); /* return doesn't matter */
return rv;
}
/* ----------------------- servact_error_processed ------------------------ */
NSAPI_PUBLIC void servact_error_processed(Session *sn, Request *rq, int status, const char *reason, const char *url)
{
int rv;
/* SAFs will expect fully-populated NSAPI structures */
PR_ASSERT(sn != NULL);
PR_ASSERT(rq != NULL);
PR_ASSERT(pblock_findkey(pb_key_method, rq->reqpb));
PR_ASSERT(pblock_findkey(pb_key_uri, rq->reqpb));
PR_ASSERT(pblock_findkey(pb_key_protocol, rq->reqpb));
/* We should only be called for HTTP protocol errors */
PR_ASSERT(!session_get_httpfilter_context(sn));
PR_ASSERT((status >= 400 && status <= 599) || (url && status == PROTOCOL_REDIRECT));
/* Figure out which objects to use */
do {
rv = servact_uri2path(sn, rq);
} while (rv == REQ_RESTART);
PR_ASSERT(rv == REQ_PROCEED || rv == REQ_NOACTION || rv == REQ_ABORTED || rv == REQ_EXIT);
/* Send error response */
if (rv == REQ_PROCEED || rv == REQ_NOACTION || rv == REQ_ABORTED) {
protocol_status(sn, rq, status, reason);
if (url && !pblock_find("url", rq->vars)) {
PR_ASSERT(status == PROTOCOL_REDIRECT);
pblock_nvinsert("url", url, rq->vars);
}
rv = error_report(sn, rq);
}
PR_ASSERT(rv == REQ_PROCEED || rv == REQ_EXIT);
/* If things went horribly wrong, make sure the connection dies */
if (rv == REQ_EXIT)
KEEP_ALIVE(rq) = 0;
/* Log the request */
servact_addlogs(sn, rq);
}
PRBool
FindApplicableMethods(Session* sn, Request* rq, NSString& methodStr)
{
PRBool res = PR_FALSE;
httpd_objset *os = rq->os;
HttpMethodRegistry& registry = HttpMethodRegistry::GetRegistry();
PRInt32 numMethods = registry.GetNumMethods();
PRBool* methodVector = (int*)pool_malloc(sn->pool, numMethods*sizeof(PRBool));
if (!methodVector) {
return res;
}
for (int i=0; i < numMethods; i++) {
methodVector[i] = PR_FALSE;
}
// Check for methods already in methodStr
char *methods = STRDUP(methodStr);
char *lasts = NULL;
char *method = util_strtok(methods, ", \t", &lasts);
while (method) {
int key = registry.GetMethodIndex(method);
if (key != -1)
methodVector[key] = PR_TRUE;
method = util_strtok(NULL, ", \t", &lasts);
}
FREE(methods);
methodStr.clear();
const char* uri = pblock_findkeyval(pb_key_uri, rq->reqpb);
if (ISMOPTIONS(rq) && (strcmp(uri, "*") == 0)) {
res = PR_TRUE;
methodStr.append(registry.GetAllMethods());
pool_free(sn->pool, methodVector);
return res;
}
for (int x = os->pos - 1; x != -1; --x) {
httpd_object* obj = os->obj[x];
dtable *d = &obj->dt[NSAPIService];
for (int y = 0; y < d->ni; y++) {
const char* typeExp = pblock_findkeyval(pb_key_type, d->inst[y].param.pb);
const char* queryExp = pblock_findkeyval(pb_key_query, d->inst[y].param.pb);
const char* cntType = pblock_findkeyval(pb_key_content_type, rq->srvhdrs);
const char* query = pblock_findkeyval(pb_key_query, rq->reqpb);
if ((ParamMatch(typeExp, cntType, PR_TRUE) == PR_TRUE) &&
(ParamMatch(queryExp, query, PR_FALSE) == PR_TRUE)) {
const char* methodExp = pblock_findkeyval(pb_key_method, d->inst[y].param.pb);
const char* rqMethod = pblock_findkeyval(pb_key_method, rq->reqpb);
if (ISMOPTIONS(rq) || !methodExp ||
ParamMatch(methodExp, rqMethod, PR_TRUE) == PR_FALSE) {
// Type matched, but not the method
for (int key = 0; key < numMethods; key++) {
const char* currMethod = registry.GetMethod(key);
PR_ASSERT(currMethod);
if (ParamMatch(methodExp, currMethod, PR_TRUE) == PR_TRUE) {
// method matches
methodVector[key] = PR_TRUE;
}
} // for every registered method
}
}
} // for evey service function in an object
} // for every object
for (int key = 0; key < numMethods; key++) {
if (methodVector[key]) {
if (methodStr.length() > 0)
methodStr.append(", ");
methodStr.append(registry.GetMethod(key));
}
}
pool_free(sn->pool, methodVector);
return (methodStr.length() > 0);
}
PRBool
ParamMatch(const char* expr, const char* str, PRBool noicmp)
{
PRBool res = PR_TRUE;
if (expr) {
res = PR_FALSE;
if (str) {
int cmpRes = 0;
if (noicmp == PR_TRUE) {
cmpRes = shexp_noicmp((char*)str, (char*)expr);
}
else {
cmpRes = shexp_cmp((char*)str, (char*)expr);
}
res = (cmpRes == 0 ? PR_TRUE : PR_FALSE);
}
}
return res;
}
/* ------------------------------------------------------------------------ */
/* ----------------------------- Input/Output ----------------------------- */
/* ------------------------------------------------------------------------ */
/* ---------------------------- servact_input ----------------------------- */
NSAPI_PUBLIC int servact_input(Session *sn, Request *rq)
{
NSAPISession *nsn = (NSAPISession *)sn;
// servact_input() only runs on the original request (if nothing else,
// input_os_pos is an index into the original request's objset so we
// can't handle the objset changing underneath us)
if (INTERNAL_REQUEST(rq) || RESTARTED_REQUEST(rq))
return REQ_NOACTION;
// servact_input() should not be called once any request body has been read
// or an Input SAF returns an error. Note, however, that servact_input()
// may be called multiple times per request, up to 1 call per object.
PR_ASSERT(!nsn->input_done);
int input_rv = REQ_NOACTION;
if (nsn->input_os_pos == 0) {
input_rv = REQ_NOACTION;
} else {
input_rv = nsn->input_rv;
}
// Fail net_read() calls until these Input directives have run. Because
// subsequent Input directives could insert filters below any given filter,
// we don't let filters do IO from their insert methods.
nsn->input_rv = REQ_ABORTED;
nsn->input_done = PR_TRUE;
PRBool input_done = PR_FALSE;
int object_rv = REQ_NOACTION;
/*
* Unlike most stages, Input/Output starts executing in the default object
* and works it way up to the most specific object. This facilitates the
* correct layering of filters.
*/
int x;
httpd_objset *os = rq->os;
for (x = nsn->input_os_pos; x < os->pos; x++) {
dtable *d = &os->obj[x]->dt[NSAPIInput];
for (int y = 0; y < d->ni; y++) {
// _CHECK_PARAM falls through, continues, or returns as appropriate
_CHECK_PARAM(check_type(d->inst[y].param.pb, sn, rq, rq->headers))
_CHECK_PARAM(check_io_method(d->inst[y].param.pb, sn, rq))
_CHECK_PARAM(check_query(d->inst[y].param.pb, sn, rq))
int saf_rv = object_execute(&d->inst[y], sn, rq);
if (saf_rv == REQ_NOACTION)
continue;
object_rv = saf_rv;
input_rv = saf_rv;
if (saf_rv == REQ_PROCEED)
continue;
/*
* Input SAF error
*/
if (d->inst[y].f) {
// If f == NULL, object_execute() already logged an error
log_error(LOG_WARN, XP_GetAdminStr(DBT_handleProcessed_),
sn, rq, XP_GetAdminStr(DBT_StageXFnYError),
directive_num2name(NSAPIInput), d->inst[y].f->name);
}
input_done = PR_TRUE;
break;
}
}
nsn->input_os_pos = x;
nsn->input_rv = input_rv;
nsn->input_done = input_done;
return object_rv;
}
/* --------------------------- _perform_output ---------------------------- */
static inline int _perform_output(Session *sn, Request *rq)
{
NSAPIRequest *nrq = (NSAPIRequest *)rq;
// Run Output at most once per Request
if (nrq->output_done)
return nrq->output_rv;
// Fail net_write(), etc. calls until all Output directives have run.
// Because subsequent Output directives could insert filters below any
// given filter, we don't let filters do IO from their insert methods.
nrq->output_rv = REQ_ABORTED;
nrq->output_done = PR_TRUE;
int stage_rv = REQ_NOACTION;
/*
* Unlike most stages, Input/Output starts executing in the default object
* and works it way up to the most specific object. This facilitates the
* correct layering of filters.
*/
httpd_objset *os = rq->os;
for (int x = 0; x < os->pos; ++x) {
dtable *d = &os->obj[x]->dt[NSAPIOutput];
for (int y = 0; y < d->ni; y++) {
// _CHECK_PARAM falls through, continues, or returns as appropriate
_CHECK_PARAM(check_type(d->inst[y].param.pb, sn, rq, rq->srvhdrs))
_CHECK_PARAM(check_io_method(d->inst[y].param.pb, sn, rq))
_CHECK_PARAM(check_query(d->inst[y].param.pb, sn, rq))
int saf_rv = object_execute(&d->inst[y], sn, rq);
if (saf_rv == REQ_NOACTION)
continue;
stage_rv = saf_rv;
if (saf_rv == REQ_PROCEED)
continue;
/*
* Output SAF error
*/
if (d->inst[y].f) {
// If f == NULL, object_execute() already logged an error
log_error(LOG_WARN, XP_GetAdminStr(DBT_handleProcessed_),
sn, rq, XP_GetAdminStr(DBT_StageXFnYError),
directive_num2name(NSAPIOutput), d->inst[y].f->name);
}
break;
}
}
// If the stage returned REQ_PROCEED, store REQ_NOACTION (i.e. subsequent
// servact_output() calls will be no ops)
if (stage_rv == REQ_PROCEED) {
nrq->output_rv = REQ_NOACTION;
} else {
nrq->output_rv = stage_rv;
}
return stage_rv;
}
/* ---------------------------- servact_output ---------------------------- */
NSAPI_PUBLIC int servact_output(Session *sn, Request *rq)
{
NSAPIRequest *nrq = (NSAPIRequest *)rq;
// servact_output() should only be called once per Request; the caller
// should inspect nrq->output_done
PR_ASSERT(!nrq->output_done);
if (nrq->output_done)
return nrq->output_rv;
Request *prev_rq;
Request *curr_rq;
// Build a linked list with the original Request (or the first Request
// that used this filter stack) at the head
prev_rq = NULL;
curr_rq = rq;
for (;;) {
((NSAPIRequest *)curr_rq)->output_next_rq = prev_rq;
prev_rq = curr_rq;
// Stop when we reach the original Request
if (curr_rq->orig_rq == curr_rq)
break;
// Stop if we see a Request that was given its own filter stack by
// session_clone()
if (((NSAPIRequest *)curr_rq)->session_clone)
break;
curr_rq = curr_rq->orig_rq;
}
// Handle the Output stage for each Request, starting with the original
PRBool output_done = PR_FALSE;
int output_rv = REQ_NOACTION;
while (curr_rq) {
if (output_done) {
// A lower Request failed Output
((NSAPIRequest *)curr_rq)->output_done = PR_TRUE;
((NSAPIRequest *)curr_rq)->output_rv = output_rv;
} else if (curr_rq->os) {
// Run the Output stage for this Request
int curr_rq_rv = _perform_output(sn, curr_rq);
if (curr_rq_rv != REQ_NOACTION) {
output_rv = curr_rq_rv;
if (curr_rq_rv != REQ_PROCEED)
output_done = PR_TRUE;
}
}
curr_rq = ((NSAPIRequest *)curr_rq)->output_next_rq;
}
PR_ASSERT(sn->csd_open == 1);
PR_ASSERT(sn->csd->higher == NULL);
PR_ASSERT(request_output_done(rq));
return output_rv;
}
/* ---------------------------- servact_lookup ---------------------------- */
NSAPI_PUBLIC int servact_lookup(Session *sn, Request *rq)
{
int rv;
do {
/* Figure out what objects it uses */
rv = servact_uri2path(sn, rq);
if (rv != REQ_PROCEED)
continue;
/* Process PathChecks */
rv = servact_pathchecks(sn, rq);
if (rv != REQ_PROCEED)
continue;
/* Find that file's typing information */
rv = servact_fileinfo(sn, rq);
if (rv != REQ_PROCEED)
continue;
} while (rv == REQ_RESTART);
return rv;
}
/* ----------------------- servact_include_virtual ------------------------ */
NSAPI_PUBLIC int servact_include_virtual(Session *sn, Request *parent_rq,
const char *location,
pblock *param)
{
Request *child_rq = request_create_virtual(sn, parent_rq, location, param);
if (!child_rq)
return REQ_ABORTED;
int rv = servact_handle_processed(sn, child_rq);
request_free(child_rq);
return rv;
}
/* ------------------------- servact_include_file ------------------------- */
NSAPI_PUBLIC int servact_include_file(Session *sn, Request *o_rq, const char *path)
{
pb_param *pp;
Request *rq;
char *location = pblock_findkeyval(pb_key_uri, o_rq->reqpb);
if (!location)
return REQ_ABORTED;
rq = request_create_virtual(sn, o_rq, location, NULL);
httpd_objset *os = NULL;
if (((NSAPIRequest*)rq)->hrq) {
os = ((NSAPIRequest*)rq)->hrq->getObjset();
} else if (const VirtualServer *vs = conf_get_vs()) {
os = vs->getObjset();
} else {
return REQ_ABORTED;
}
const VirtualServer* vs = request_get_vs(rq);
httpd_object *obj;
const char *name = vs->defaultObjectName;
rq->os = objset_create_pool(sn->pool);
obj = objset_findbyname(name, rq->os, os);
if (!obj)
return REQ_ABORTED;
objset_add_object(obj, rq->os);
pblock_nvinsert("path", path, rq->vars);
int rv = servact_fileinfo(sn, rq);
if (rv != REQ_PROCEED)
return rv;
rv = servact_service(sn, rq);
return rv;
}
| 31.772249 | 166 | 0.549967 | [
"object",
"model"
] |
4e630a1bd9003a33d10f6e0e55ff66a9aee214c8 | 8,077 | cpp | C++ | json_printer/json_printer.cpp | michael-novikov/cpp-black-belt | c18690e1641774fbb5c5b3d3c80b14c32bab70a5 | [
"MIT"
] | null | null | null | json_printer/json_printer.cpp | michael-novikov/cpp-black-belt | c18690e1641774fbb5c5b3d3c80b14c32bab70a5 | [
"MIT"
] | null | null | null | json_printer/json_printer.cpp | michael-novikov/cpp-black-belt | c18690e1641774fbb5c5b3d3c80b14c32bab70a5 | [
"MIT"
] | 2 | 2021-01-19T13:20:04.000Z | 2021-09-29T21:01:44.000Z | #include <ios>
#include <ostream>
#include <string_view>
#include <test_runner.h>
#include <cassert>
#include <cmath>
#include <stdexcept>
#include <sstream>
#include <stack>
#include <string>
#include <cstdint>
class EmptyContext {};
template <typename Parent>
class Array;
template <typename Parent>
class Object;
template <typename Parent>
class Value {
public:
Value(std::ostream& out) : out_(out) {}
Value(std::ostream &out, Parent *parent_context)
: out_(out), parent_(parent_context) {}
~Value() { if (!printed_) Null(); }
Parent &Number(int64_t value);
Parent &String(std::string_view value);
Parent &Boolean(bool value);
Parent &Null();
Array<Parent> BeginArray() { printed_ = true; return {out_, this->parent_}; }
Object<Parent> BeginObject() { printed_ = true; return {out_, this->parent_}; }
private:
std::ostream& out_;
Parent *parent_{nullptr};
bool printed_{false};
};
template <typename Parent>
Parent& Value<Parent>::Number(int64_t value) {
out_ << value;
printed_ = true;
return *parent_;
}
template <typename Parent>
Parent& Value<Parent>::String(std::string_view value) {
out_ << '\"';
for (auto ch : value) {
if (ch == '\"' || ch == '\\') {
out_ << '\\';
}
out_ << ch;
}
out_ << '\"';
printed_ = true;
return *parent_;
}
template <typename Parent>
Parent& Value<Parent>::Boolean(bool value) {
out_ << std::boolalpha << value;
printed_ = true;
return *parent_;
}
template <typename Parent>
Parent& Value<Parent>::Null() {
out_ << "null";
printed_ = true;
return *parent_;
}
template <typename Parent, char BeginChar, char EndChar, char DelimeterChar>
class Context {
public:
Context(std::ostream& out) : out_(out) { Begin(); }
Context(std::ostream &out, Parent *context) : out_(out), parent_(context) { Begin(); }
~Context() { End(); }
protected:
std::ostream& out_;
Parent *parent_{nullptr};
bool first_added_{false};
bool opened_{false};
Value<Context> AddValue() { Delimeter(); return Value<Context>{out_, this}; }
void Begin() {
out_ << BeginChar;
opened_ = true;
}
void Delimeter() {
if (!first_added_) {
first_added_ = true;
} else {
out_ << ',';
}
}
void End() {
if (opened_) {
out_ << EndChar;
opened_ = false;
}
}
};
template<typename Parent>
class Array : public Context<Parent, '[', ']', ','> {
public:
Array(std::ostream& out) : Context<Parent, '[', ']', ','>(out) {}
Array(std::ostream& out, Parent* parent) : Context<Parent, '[', ']', ','>(out, parent) {}
Array<Parent>& Number(int64_t value) { return this->AddValue().Number(value); return *this; }
Array<Parent>& String(std::string_view value) { this->AddValue().String(value); return *this; }
Array<Parent>& Boolean(bool value) { this->AddValue().Boolean(value); return *this; }
Array<Parent>& Null() { this->AddValue().Null(); return *this; }
Array<Array<Parent>> BeginArray() { this->Delimeter(); return {this->out_, this}; }
Object<Array<Parent>> BeginObject() { this->Delimeter(); return {this->out_, this}; }
Parent& EndArray() { this->End(); return *this->parent_; }
};
template<typename Parent>
class Object : public Context<Parent, '{', '}', ','> {
public:
Object(std::ostream& out) : Context<Parent, '{', '}', ','>(out) {}
Object(std::ostream& out, Parent* parent) : Context<Parent, '{', '}', ','>(out, parent) {}
Value<Object<Parent>> Key(std::string_view value) {
this->Delimeter();
Value<EmptyContext>{this->out_}.String(value);
this->out_ << ':';
return {this->out_, this};
}
Parent& EndObject() { this->End(); return *this->parent_; }
};
void PrintJsonString(std::ostream& out, std::string_view str) {
Value<EmptyContext>{out}.String(str);
}
using ArrayContext = Array<EmptyContext>;
ArrayContext PrintJsonArray(std::ostream& out) {
return {out};
}
using ObjectContext = Object<EmptyContext>;
ObjectContext PrintJsonObject(std::ostream& out) {
return {out};
}
void TestArray() {
std::ostringstream output;
{
auto json = PrintJsonArray(output);
json
.Number(5)
.Number(6)
.BeginArray()
.Number(7)
.EndArray()
.Number(8)
.String("bingo!");
}
ASSERT_EQUAL(output.str(), R"([5,6,[7],8,"bingo!"])");
}
void TestArrayAfterEnd() {
std::ostringstream output;
{
auto json = PrintJsonArray(output);
json
.EndArray();
}
ASSERT_EQUAL(output.str(), R"([])");
}
void TestBigArray() {
std::ostringstream output;
{
auto json = PrintJsonArray(output);
json
.Number(5)
.Number(-64)
.BeginArray()
.BeginObject()
.Key("").Number(6)
.EndObject()
.Number(7)
.EndArray()
.Null()
.Boolean(false)
.BeginObject()
.Key("").Number(6)
.Key("id2").Boolean(true)
.Key("").Null()
.Key("\"").String("\\")
.EndObject()
.Number(8)
.String("bingo!")
.BeginObject()
.Key("123")
.Null();
}
ASSERT_EQUAL(output.str(), R"([5,-64,[{"":6},7],null,false,{"":6,"id2":true,"":null,"\"":"\\"},8,"bingo!",{"123":null}])");
}
void TestEmptyArray() {
std::ostringstream output;
{
auto json = PrintJsonArray(output);
json
.BeginArray()
.BeginObject()
.EndObject()
.BeginObject()
.EndObject()
.EndArray()
.BeginArray()
.BeginObject()
.EndObject()
.BeginObject()
.EndObject()
.EndArray();
}
ASSERT_EQUAL(output.str(), R"([[{},{}],[{},{}]])");
}
void TestObject() {
std::ostringstream output;
{
auto json = PrintJsonObject(output);
json
.Key("id1").Number(1234)
.Key("id2").Boolean(false)
.Key("").Null()
.Key("\"").String("\\");
}
ASSERT_EQUAL(output.str(), R"({"id1":1234,"id2":false,"":null,"\"":"\\"})");
}
void TestObjectAfterEnd() {
std::ostringstream output;
{
auto json = PrintJsonObject(output);
json
.EndObject();
}
ASSERT_EQUAL(output.str(), R"({})");
}
void TestNullIfKeyOnly() {
std::ostringstream output;
{
auto json = PrintJsonObject(output);
json
.Key("foo")
.BeginArray()
.String("Hello")
.EndArray()
.Key("foo") // повторяющиеся ключи допускаются
.BeginObject()
.Key("foo"); // закрытие объекта в таком состоянии допишет null в качестве значения
}
ASSERT_EQUAL(output.str(), R"({"foo":["Hello"],"foo":{"foo":null}})");
}
void TestAutoClose() {
std::ostringstream output;
{
auto json = PrintJsonArray(output);
json.BeginArray().BeginObject();
}
ASSERT_EQUAL(output.str(), R"([[{}]])");
}
void TestPrintString() {
std::ostringstream output;
{
PrintJsonString(output, "Hello, \"world\"");
}
ASSERT_EQUAL(output.str(), R"("Hello, \"world\"")");
}
void TestExplicitlyClosedArray() {
std::ostringstream output;
{
auto json = PrintJsonArray(output);
json
.Null()
.String("Hello")
.Number(123)
.Boolean(false)
.EndArray();
}
ASSERT_EQUAL(output.str(), R"([null,"Hello",123,false])");
}
void TestArraySimple() {
std::ostringstream output;
{
auto json = PrintJsonArray(output);
json
.Null()
.String("Hello")
.Number(123)
.Boolean(false);
}
ASSERT_EQUAL(output.str(), R"([null,"Hello",123,false])");
}
void TestImplicitlyClosedArray() {
std::ostringstream output;
{
auto json = PrintJsonArray(output);
json
.String("Hello")
.BeginArray()
.String("World");
}
ASSERT_EQUAL(output.str(), R"(["Hello",["World"]])");
}
int main() {
TestRunner tr;
RUN_TEST(tr, TestArray);
RUN_TEST(tr, TestBigArray);
RUN_TEST(tr, TestEmptyArray);
RUN_TEST(tr, TestObject);
RUN_TEST(tr, TestObjectAfterEnd);
RUN_TEST(tr, TestNullIfKeyOnly);
RUN_TEST(tr, TestAutoClose);
RUN_TEST(tr, TestPrintString);
RUN_TEST(tr, TestExplicitlyClosedArray);
RUN_TEST(tr, TestArraySimple);
RUN_TEST(tr, TestImplicitlyClosedArray);
return 0;
}
| 21.538667 | 125 | 0.60208 | [
"object"
] |
4e6d783cc17fbd06012e24fef946a99cdc77fdb1 | 5,829 | cc | C++ | src/x2/LteX2Manager.cc | robinfoxnan/Simu5G | 4d124a42d81c29fa5f6b45d41d41304ef6139f1e | [
"Intel"
] | 1 | 2021-04-16T05:46:58.000Z | 2021-04-16T05:46:58.000Z | src/x2/LteX2Manager.cc | robinfoxnan/Simu5G | 4d124a42d81c29fa5f6b45d41d41304ef6139f1e | [
"Intel"
] | null | null | null | src/x2/LteX2Manager.cc | robinfoxnan/Simu5G | 4d124a42d81c29fa5f6b45d41d41304ef6139f1e | [
"Intel"
] | null | null | null | //
// Simu5G
//
// Authors: Giovanni Nardini, Giovanni Stea, Antonio Virdis (University of Pisa)
//
// This file is part of a software released under the license included in file
// "license.pdf". Please read LICENSE and README files before using it.
// The above files and the present reference are part of the software itself,
// and cannot be removed from it.
//
#define DATAPORT_OUT "dataPort$o"
#define DATAPORT_IN "dataPort$i"
#include <inet/networklayer/common/InterfaceEntry.h>
#include <inet/networklayer/configurator/ipv4/Ipv4NetworkConfigurator.h>
#include <inet/networklayer/ipv4/Ipv4InterfaceData.h>
#include "x2/LteX2Manager.h"
Define_Module(LteX2Manager);
using namespace omnetpp;
using namespace inet;
void LteX2Manager::initialize(int stage)
{
if (stage == inet::INITSTAGE_LOCAL)
{
// get the node id
nodeId_ = getAncestorPar("macCellId");
}
else if (stage == inet::INITSTAGE_NETWORK_LAYER)
{
// find x2ppp interface entries and register their IP addresses to the binder
// IP addresses will be used in the next init stage to get the X2 id of the peer
Ipv4NetworkConfigurator* configurator = check_and_cast<Ipv4NetworkConfigurator*>(getModuleByPath("configurator"));
IInterfaceTable *interfaceTable = configurator->findInterfaceTableOf(getParentModule()->getParentModule());
for (int i=0; i<interfaceTable->getNumInterfaces(); i++)
{
// look for x2ppp interfaces in the interface table
InterfaceEntry * interfaceEntry = interfaceTable->getInterface(i);
const char* ifName = interfaceEntry->getInterfaceName();
if (strstr(ifName,"x2ppp") != nullptr)
{
const Ipv4Address addr = interfaceEntry->getProtocolData<Ipv4InterfaceData>()->getIPAddress();
getBinder()->setX2NodeId(addr, nodeId_);
}
}
}
else if (stage == inet::INITSTAGE_TRANSPORT_LAYER)
{
// for each X2App, get the client submodule and set connection parameters (connectPort)
for (int i=0; i<gateSize("x2$i"); i++)
{
// client of the X2Apps is connected to the input sides of "x2" gate
cGate* inGate = gate("x2$i",i);
// get the X2App client connected to this gate
// x2 -> X2App.x2ManagerIn -> X2App.client
X2AppClient* client = check_and_cast<X2AppClient*>(inGate->getPathStartGate()->getOwnerModule());
// get the connectAddress for the X2App client and the corresponding X2 id
L3Address addr = L3AddressResolver().resolve(client->par("connectAddress").stringValue());
X2NodeId peerId = getBinder()->getX2NodeId(addr.toIpv4());
// bind the peerId to the output gate
x2InterfaceTable_[peerId] = i;
}
}
}
void LteX2Manager::handleMessage(cMessage *msg)
{
Packet* pkt = check_and_cast<Packet*>(msg);
cGate* incoming = pkt->getArrivalGate();
// the incoming gate is part of a gate vector, so get the base name
if (strcmp(incoming->getBaseName(), "dataPort") == 0)
{
// incoming data from LTE stack
EV << "LteX2Manager::handleMessage - Received message from LTE stack" << endl;
fromStack(pkt);
}
else // from X2
{
// the incoming gate belongs to a gate vector, so get its index
int gateIndex = incoming->getIndex();
// incoming data from X2
EV << "LteX2Manager::handleMessage - Received message from X2, gate " << gateIndex << endl;
// call handler
fromX2(pkt);
}
}
void LteX2Manager::fromStack(Packet* pkt)
{
auto x2msg = pkt->removeAtFront<LteX2Message>();
auto x2Info = pkt->removeTagIfPresent<X2ControlInfoTag>();
if (x2Info->getInit())
{
// gate initialization
LteX2MessageType msgType = x2msg->getType();
int gateIndex = pkt->getArrivalGate()->getIndex();
dataInterfaceTable_[msgType] = gateIndex;
delete pkt;
return;
}
// If the message is carrying data, send to the GTPUserX2 module
// (GTPUserX2 module will tunnel this datagram towards the target eNB)
// otherwise it is a X2 control message and sent to the x2 peer
DestinationIdList destList = x2Info->getDestIdList();
DestinationIdList::iterator it = destList.begin();
for (; it != destList.end(); ++it)
{
X2NodeId targetEnb = *it;
auto pktDuplicate = pkt->dup();
x2msg->markMutableIfExclusivelyOwned();
x2msg->setSourceId(nodeId_);
x2msg->setDestinationId(targetEnb);
pktDuplicate->insertAtFront(x2msg);
cGate* outputGate;
if(x2msg->getType() == X2_HANDOVER_DATA_MSG || x2msg->getType() == X2_DUALCONNECTIVITY_DATA_MSG) {
// send to the gate connected to the GTPUser module
outputGate = gate("x2Gtp$o");
} else {
// select the index for the output gate (it belongs to a vector)
int gateIndex = x2InterfaceTable_[*it];
outputGate = gate("x2$o",gateIndex);
}
send(pktDuplicate, outputGate);
}
delete pkt;
}
void LteX2Manager::fromX2(Packet* pkt)
{
auto x2msg = pkt->peekAtFront<LteX2Message>();
LteX2MessageType msgType = x2msg->getType();
if (msgType == X2_UNKNOWN_MSG)
{
EV << " LteX2Manager::fromX2 - Unknown type of the X2 message. Discard." << endl;
return;
}
// get the correct output gate for the message
int gateIndex = dataInterfaceTable_[msgType];
cGate* outGate = gate(DATAPORT_OUT, gateIndex);
// send X2 msg to stack
EV << "LteX2Manager::fromX2 - send X2MSG to LTE stack" << endl;
send(pkt, outGate);
}
| 35.542683 | 122 | 0.638531 | [
"vector"
] |
4e6f2f3ee719871e950b76349ea925cfa79c9125 | 960 | cpp | C++ | source/Beispielprogramm.cpp | LS060598/programmiersprachen-aufgabenblatt-3 | 5d9af11f347d21b5c826620708601e3b064fcf50 | [
"MIT"
] | null | null | null | source/Beispielprogramm.cpp | LS060598/programmiersprachen-aufgabenblatt-3 | 5d9af11f347d21b5c826620708601e3b064fcf50 | [
"MIT"
] | null | null | null | source/Beispielprogramm.cpp | LS060598/programmiersprachen-aufgabenblatt-3 | 5d9af11f347d21b5c826620708601e3b064fcf50 | [
"MIT"
] | null | null | null | #include <cstdlib>
#include <vector>
#include <list>
#include <iostream>
#include <iterator>
#include <algorithm>
// std :: rand ()
// std::vector<>
// std::list<>
// std :: cout
// std::ostream_iterator <>
// std::reverse, std::generate
int main () {
std::vector<int> v0{10};
for (auto& v : v0) {
v = std :: rand (); }
std::copy(std::begin(v0), std::end(v0), std::ostream_iterator<int>(std::cout, "\n"));
std::list<int> l0{v0.size()};
std::copy(std::begin(v0), std::end(v0), std::begin(l0));
std::list<int> l1{std::begin(l0), std::end(l0)}; std::reverse(std::begin(l1), std::end(l1)); std::copy(std::begin(l1), std::end(l1),
std::ostream_iterator<int>(std::cout, "\n"));
l1.sort(); std::copy(l1.begin(), l1.end(),
std::ostream_iterator<int>(std::cout, "\n"));
std::generate(std::begin(v0), std::end(v0), std::rand); std::copy(v0.rbegin(), v0.rend(),
std::ostream_iterator<int>(std::cout, "\n")); return 0;
} | 36.923077 | 136 | 0.588542 | [
"vector"
] |
4e7160046a2d9cf84c9ffaa0bb0e731d9a927afa | 6,531 | cc | C++ | src/vmm/VirtualMachineManagerDriver.cc | NeatNerdPrime/one | 6d367ac410cfb19377f31c03183ec4fcdd252f59 | [
"Apache-2.0"
] | null | null | null | src/vmm/VirtualMachineManagerDriver.cc | NeatNerdPrime/one | 6d367ac410cfb19377f31c03183ec4fcdd252f59 | [
"Apache-2.0"
] | null | null | null | src/vmm/VirtualMachineManagerDriver.cc | NeatNerdPrime/one | 6d367ac410cfb19377f31c03183ec4fcdd252f59 | [
"Apache-2.0"
] | null | null | null | /* -------------------------------------------------------------------------- */
/* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 "VirtualMachineManagerDriver.h"
#include "NebulaLog.h"
#include "LifeCycleManager.h"
#include "Nebula.h"
#include "NebulaUtil.h"
#include <sstream>
using namespace std;
const string VirtualMachineManagerDriver::imported_actions_default =
"shutdown, shutdown-hard, hold, release, suspend, resume, delete, reboot, "
"reboot-hard, resched, unresched, disk-attach, disk-detach, nic-attach, "
"nic-detach, snap-create, snap-delete";
const string VirtualMachineManagerDriver::imported_actions_default_public =
"shutdown, shutdown-hard, hold, release, suspend, resume, delete, reboot, "
"reboot-hard, resched, unresched, disk-attach, disk-detach, nic-attach, "
"nic-detach, snap-create, snap-delete, poweroff, poweroff-hard";
VirtualMachineManagerDriver::VirtualMachineManagerDriver(
const string &mad_location,
const map<string,string> &attrs):
Driver(),
driver_conf(true),
keep_snapshots(false),
ds_live_migration(false),
cold_nic_attach(false),
live_resize(false)
{
char * error_msg = nullptr;
const char * cfile;
string file;
int rc;
string action_defaults;
auto it = attrs.find("DEFAULT");
if ( it != attrs.end() )
{
if (it->second[0] != '/') //Look in ONE_LOCATION/etc or in "/etc/one"
{
Nebula& nd = Nebula::instance();
file = nd.get_defaults_location() + it->second;
cfile = file.c_str();
}
else //Absolute Path
{
cfile = it->second.c_str();
}
rc = driver_conf.parse(cfile, &error_msg);
if ( rc != 0 )
{
ostringstream oss;
if ( error_msg != nullptr )
{
oss << "Error loading driver configuration file " << cfile <<
" : " << error_msg;
free(error_msg);
}
else
{
oss << "Error loading driver configuration file " << cfile;
}
NebulaLog::log("VMM", Log::ERROR, oss);
}
}
// -------------------------------------------------------------------------
// Copy the configuration attributes to driver conf
// -------------------------------------------------------------------------
for (it=attrs.begin(); it != attrs.end(); ++it)
{
driver_conf.replace(it->first, it->second);
}
// -------------------------------------------------------------------------
// Parse KEEP_SNAPSHOTS
// -------------------------------------------------------------------------
driver_conf.get("KEEP_SNAPSHOTS", keep_snapshots);
// -------------------------------------------------------------------------
// Parse DS_LIVE_MIGRATION
// -------------------------------------------------------------------------
driver_conf.get("DS_LIVE_MIGRATION", ds_live_migration);
// -------------------------------------------------------------------------
// Parse COLD_NIC_ATTACH
// -------------------------------------------------------------------------
driver_conf.get("COLD_NIC_ATTACH", cold_nic_attach);
driver_conf.get("LIVE_RESIZE", live_resize);
// -------------------------------------------------------------------------
// Parse IMPORTED_VMS_ACTIONS string and init the action set
// -------------------------------------------------------------------------
it = attrs.find("IMPORTED_VMS_ACTIONS");
if (it != attrs.end())
{
action_defaults = it->second;
}
else
{
NebulaLog::log("VMM", Log::INFO, "Using default imported VMs actions");
it = attrs.find("NAME");
if (it != attrs.end())
{
if ( it->second == "kvm" || it->second == "xen" )
{
action_defaults = imported_actions_default;
}
else if ( it->second == "sl" || it->second == "ec2" ||
it->second == "az" || it->second == "vcenter" )
{
action_defaults = imported_actions_default_public;
}
}
}
vector<string> actions;
VMActions::Action id;
actions = one_util::split(action_defaults, ',');
for (auto action : actions)
{
action = one_util::trim(action);
if ( VMActions::action_from_str(action, id) != 0 )
{
NebulaLog::log("VMM", Log::ERROR, "Wrong action: " + action);
continue;
}
imported_actions.set(id);
}
string name, exec, args;
driver_conf.get("NAME", name);
driver_conf.get("EXECUTABLE", exec);
driver_conf.get("ARGUMENTS", args);
int threads;
driver_conf.get("THREADS", threads);
//NebulaLog::info("DrM", "Loading driver: " + name);
if (exec.empty())
{
NebulaLog::error("VMM", "\tEmpty executable for driver: " + name);
return;
}
if (exec[0] != '/') //Look in ONE_LOCATION/lib/mads or in "/usr/lib/one/mads"
{
exec = mad_location + exec;
}
if (access(exec.c_str(), F_OK) != 0)
{
NebulaLog::error("VMM", "File not exists: " + exec);
}
cmd_(exec);
arg_(args);
concurency_(threads);
}
| 33.492308 | 81 | 0.458888 | [
"vector"
] |
4e7ea2d9295d68b32f84df857d01c830523dee77 | 1,615 | cpp | C++ | TOI16/Codecube/pretoi16/06 - magic pooh.cpp | mrmuffinnxz/TOI-preparation | 85a7d5b70d7fc661950bbb5de66a6885a835e755 | [
"MIT"
] | null | null | null | TOI16/Codecube/pretoi16/06 - magic pooh.cpp | mrmuffinnxz/TOI-preparation | 85a7d5b70d7fc661950bbb5de66a6885a835e755 | [
"MIT"
] | null | null | null | TOI16/Codecube/pretoi16/06 - magic pooh.cpp | mrmuffinnxz/TOI-preparation | 85a7d5b70d7fc661950bbb5de66a6885a835e755 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
#define endll '\n'
long long n,m,k,t;
vector<pair<long long,long long> > graph[100001];
set<long long> path;
long long dist[2][100001];
void dijkstraAlgorithm(long long x,long long src,long long dest)
{
long long visited[n+1];
priority_queue<pair<long long,long long>,vector<pair<long long,long long> >,greater<pair<long long,long long> > > q;
for(long long i=0;i<=n;i++)
dist[x][i] = INT_MAX;
memset(visited,false,sizeof(visited));
q.push(make_pair(0,src));
dist[x][src] = 0;
long long u;
for(long long i=0;i<n;i++)
{
u = q.top().second;
q.pop();
visited[u] = true;
for(auto v : graph[u])
{
if(!visited[v.first] && dist[x][u] + v.second < dist[x][v.first])
{
dist[x][v.first] = dist[x][u] + v.second;
q.push(make_pair(dist[x][v.first],v.first));
}
}
}
}
main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cin>>n>>m>>k>>t;
long long u,v,w;
vector<pair<pair<long long,long long> , long long> > in_use;
for(long long i=0;i<m;i++)
{
cin>>u>>v>>w;
in_use.push_back(make_pair(make_pair(u,v),w));
graph[u].push_back(make_pair(v,w));
graph[v].push_back(make_pair(u,w));
}
dijkstraAlgorithm(0,1,n);
dijkstraAlgorithm(1,n,1);
long long ans = dist[0][n];
for(long long i=0;i<m;i++)
{
if(k >= in_use[i].second) continue;
u = in_use[i].first.first;
v = in_use[i].first.second;
long long new_dist = min(k + dist[0][u] + dist[1][v] , k + dist[0][v] + dist[1][u]);
ans = min(ans,new_dist);
}
if(ans <= t) cout<<"Happy Winnie the Pooh :3\n"<<ans;
else cout<<"No Honey TT";
}
| 20.1875 | 117 | 0.610526 | [
"vector"
] |
4e808aea94c8079728b21f31629ae8a3cebfd2d6 | 7,141 | cpp | C++ | software/BottleCapDetector/src/main.cpp | Electrotutorials/BottleCapDetector | 51264f613f06b4081f3c29ad3d96cc591fa35731 | [
"MIT"
] | null | null | null | software/BottleCapDetector/src/main.cpp | Electrotutorials/BottleCapDetector | 51264f613f06b4081f3c29ad3d96cc591fa35731 | [
"MIT"
] | null | null | null | software/BottleCapDetector/src/main.cpp | Electrotutorials/BottleCapDetector | 51264f613f06b4081f3c29ad3d96cc591fa35731 | [
"MIT"
] | null | null | null | #include "Arduino.h"
#include "OneButton.h"
//Define the used pins
#define BOTTLE_DETECTION_LED_PIN 2
#define CAP_DETECTION_LED_PIN 3
#define ALARM_LED_PIN 4
#define RESET_BUTTON_PIN 5
#define INDUCTION_SENSOR_PIN 6
#define LIGHT_SENSOR_PIN 7
#define ALARM_RELAY_PIN 8
//The number of bottlkes without a cap within the error window that trigger a alamr
#define MAX_ERRORS 3
//The number of bottles in the error window. The error window is opened when the first faulty bottle is detected. If the maximum number of faulty bottles is detected within this window the aram is triggered.
#define ERROR_WINDOW 20
//Set the parameter below to true to get debug messages on the serial port
//Set the parameter below to false to disable the serial port and not get any debug messages
#define DEBUG false
//Instaniate the varables
int NrOfErrors;
int NrOfBottlesSinceFirstError;
bool bottleDetected;
bool capDetected;
bool alarm;
bool buttonPressed;
//Instantiate the button object and hook it up to the button pin/
OneButton button(RESET_BUTTON_PIN, true);
//Create an array of LED statusses. This makes the code easier to read.
enum ledStates
{
OFF,
ON
};
//Checks if a bottle is detected.
//Returns false when no bottle is detected.
//Returns true when a bottle is detected
bool detectBottle()
{
if (digitalRead(LIGHT_SENSOR_PIN) == 1)
{
return true;
}
else
{
return false;
}
}
//checks if a bottle cap is detected
//Returns true of a bottle cap is detected
//Returns false if no bottle cap is detected
bool detectCap()
{
if (digitalRead(INDUCTION_SENSOR_PIN) == 0)
{
return true;
}
else
{
return false;
}
}
//Switches the alarm relay on if the alarm state is ON
void setAlarmRelay(ledStates state)
{
if (state == OFF)
{
digitalWrite(ALARM_RELAY_PIN, LOW);
}
else
{
digitalWrite(ALARM_RELAY_PIN, HIGH);
}
}
//Switches on the LED that indicates if a bottle is detected when the bottle detected state is ON
void setBottleLED(ledStates state)
{
if (state == OFF)
{
digitalWrite(BOTTLE_DETECTION_LED_PIN, LOW);
}
else
{
digitalWrite(BOTTLE_DETECTION_LED_PIN, HIGH);
}
}
//Switches on the LED that indicates if a bottle cap is detected when the bottle cap detected state is ON
void setCapLED(ledStates state)
{
if (state == OFF)
{
digitalWrite(CAP_DETECTION_LED_PIN, LOW);
}
else
{
digitalWrite(CAP_DETECTION_LED_PIN, HIGH);
}
}
//Switches the alamr LED on indicating that an alarm is triggered
void setAlarmLED(ledStates state)
{
if (state == OFF)
{
digitalWrite(ALARM_LED_PIN, LOW);
}
else
{
digitalWrite(ALARM_LED_PIN, HIGH);
}
}
//This method is called when the button is pressed for at least 1 second
void buttonLongPress()
{
//Set the flag indicating that the button has been pressed
buttonPressed = true;
}
//Initialise the parameters used in the application
void initParameters()
{
NrOfErrors = 0;
NrOfBottlesSinceFirstError = 0;
bottleDetected = false;
capDetected = false;
alarm = false;
buttonPressed = false;
//Initialise the indicator LEDs
setBottleLED(OFF);
setCapLED(OFF);
setAlarmLED(OFF);
setAlarmRelay(OFF);
}
//Set the hardware pin modes
void setPinModes()
{
//Set the input pins
pinMode(INDUCTION_SENSOR_PIN, INPUT);
pinMode(LIGHT_SENSOR_PIN, INPUT);
pinMode(RESET_BUTTON_PIN, INPUT_PULLUP);
//Set the output pins
pinMode(CAP_DETECTION_LED_PIN, OUTPUT);
pinMode(BOTTLE_DETECTION_LED_PIN, OUTPUT);
pinMode(ALARM_RELAY_PIN, OUTPUT);
pinMode(ALARM_LED_PIN, OUTPUT);
}
//The set up routine is only called once when starting up the code. It's used to set everything up.
void setup()
{
//Only set up the serial port when debug messages are used.
if (DEBUG)
Serial.begin(9600);
//Connect the "long press" event to the buttnoLongPress method
button.attachLongPressStart(buttonLongPress);
//Set the hardware pin modes
setPinModes();
//Initialise all parameters
initParameters();
}
//The loop method is called over and over again, thus providing the mail application functionality
void loop()
{
//monitor de reset button
button.tick();
//We can only start when there is no alarm
if (!alarm)
{
//We wait for a bottle to be detected
if (detectBottle())
{
if (DEBUG)
Serial.println("Bottle detected");
//Keep track of the fact a bottle is detected
bottleDetected = true;
//Suppose no bottle cap has been detected at this point
capDetected = false;
//Switch the "bottle detected" indicator LED on
setBottleLED(ON);
//We start the loop that runs as long as the bottle is detected and the reset button is not pressed
while (detectBottle() && !buttonPressed)
{
//monitor the reset knop. We need this command here too, otherwise we can't get out of this loop
button.tick();
//Check if a bottle cap is detected. Only take action the first time the cap is detecxted
if (detectCap() && !capDetected)
{
if (DEBUG)
Serial.println("Cap detected");
//Keep track that the cap is detected
capDetected = true;
//Swith the "bottle cap" indicator LED on
setCapLED(ON);
}
}
//The bottle has passed, switch the indicator LEDS off
setCapLED(OFF);
setBottleLED(OFF);
//Take some action if no cap has been detected
if (!capDetected)
{
//No cap detected, keep track of the count
NrOfErrors++;
if (DEBUG)
{
Serial.print("Number of faulty bottles = ");
Serial.println(NrOfErrors);
}
}
//If this is not the first error, increase the number of faulty bottles in the error window
if (NrOfErrors > 0)
{
NrOfBottlesSinceFirstError++;
if (DEBUG)
{
Serial.print("Number of bottles detected in the error window = ");
Serial.println(NrOfBottlesSinceFirstError);
}
}
//We check if the number of bottles is greater or equal to the maximum number of errors in the error window
//If so, reset the error counts
if (NrOfBottlesSinceFirstError >= ERROR_WINDOW)
{
NrOfErrors = 0;
NrOfBottlesSinceFirstError = 0;
}
//If the maximum number of errors is reached at this point, this can only be within the fault window, so raise the alarm
if (NrOfErrors >= MAX_ERRORS)
{
if (DEBUG)
Serial.println("Maximum number of faulty bottles reached. ALARM!!");
//Keep track of the alarm
alarm = true;
//Switch the alarm indicator LED on
setAlarmLED(ON);
//Switch the alarm relay on
setAlarmRelay(ON);
}
}
}
else
{
//Whe we get here, the alarm state is raised, so we wait for the reset button to be pressed.
if (buttonPressed)
{
if (DEBUG)
Serial.println("Reset button is pressed. Initialise parameters and start again.");
//Reset is pressed, so we reset all parameters and start all over again.
initParameters();
}
}
}
| 26.546468 | 207 | 0.681697 | [
"object"
] |
4e81d54d2bb2df4177b45c24822420a58cbfb4a4 | 19,947 | hpp | C++ | include/do_cycles.hpp | LLNL/Comb | 1a149310638ba7b13b55f15188f0bb84b6a2e1d5 | [
"MIT"
] | 21 | 2018-10-03T18:15:04.000Z | 2022-02-16T08:07:50.000Z | include/do_cycles.hpp | LLNL/Comb | 1a149310638ba7b13b55f15188f0bb84b6a2e1d5 | [
"MIT"
] | 5 | 2019-10-07T23:06:57.000Z | 2021-08-16T16:10:58.000Z | include/do_cycles.hpp | LLNL/Comb | 1a149310638ba7b13b55f15188f0bb84b6a2e1d5 | [
"MIT"
] | 6 | 2019-09-13T16:47:33.000Z | 2022-03-03T16:17:32.000Z | //////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2018-2021, Lawrence Livermore National Security, LLC.
//
// Produced at the Lawrence Livermore National Laboratory
//
// LLNL-CODE-758885
//
// All rights reserved.
//
// This file is part of Comb.
//
// For details, see https://github.com/LLNL/Comb
// Please also see the LICENSE file for MIT license.
//////////////////////////////////////////////////////////////////////////////
#ifndef _DO_CYCLES_HPP
#define _DO_CYCLES_HPP
#include <type_traits>
#include "comb.hpp"
#include "CommFactory.hpp"
namespace COMB {
template < typename pol_comm, typename exec_mesh, typename exec_many, typename exec_few >
bool should_do_cycles(CommContext<pol_comm>& con_comm_in,
ContextHolder<exec_mesh>& con_mesh_in, AllocatorInfo& aloc_mesh_in,
ContextHolder<exec_many>& con_many_in, AllocatorInfo& aloc_many_in,
ContextHolder<exec_few>& con_few_in, AllocatorInfo& aloc_few_in)
{
return con_mesh_in.available() && con_many_in.available() && con_few_in.available()
&& aloc_mesh_in.available() // && aloc_many_in.available() && aloc_few_in.available()
&& aloc_many_in.accessible(con_comm_in) && aloc_few_in.accessible(con_comm_in)
&& aloc_mesh_in.accessible(con_mesh_in.get())
&& aloc_mesh_in.accessible(con_many_in.get()) && aloc_many_in.accessible(con_many_in.get())
&& aloc_mesh_in.accessible(con_few_in.get()) && aloc_few_in.accessible(con_few_in.get()) ;
}
template < typename pol_comm, typename exec_mesh, typename exec_many, typename exec_few >
void do_cycles(CommContext<pol_comm>& con_comm_in,
CommInfo& comm_info, MeshInfo& info,
IdxT num_vars, IdxT ncycles,
ContextHolder<exec_mesh>& con_mesh_in, AllocatorInfo& aloc_mesh_in,
ContextHolder<exec_many>& con_many_in, AllocatorInfo& aloc_many_in,
ContextHolder<exec_few>& con_few_in, AllocatorInfo& aloc_few_in,
Timer& tm, Timer& tm_total)
{
if (!should_do_cycles(con_comm_in, con_mesh_in, aloc_mesh_in, con_many_in, aloc_many_in, con_few_in, aloc_few_in)) {
return;
}
using con_mesh_type = typename ContextHolder<exec_mesh>::context_type;
using con_many_type = typename ContextHolder<exec_many>::context_type;
using con_few_type = typename ContextHolder<exec_few>::context_type;
using pol_mesh = typename con_mesh_type::pol;
using pol_many = typename con_many_type::pol;
using pol_few = typename con_few_type::pol;
ExecContext<pol_mesh>& con_mesh = con_mesh_in.get();
ExecContext<pol_many>& con_many = con_many_in.get();
ExecContext<pol_few>& con_few = con_few_in.get();
COMB::Allocator& aloc_mesh = aloc_mesh_in.allocator();
COMB::Allocator& aloc_many = aloc_many_in.allocator();
COMB::Allocator& aloc_few = aloc_few_in.allocator();
CPUContext tm_con;
tm_total.clear();
tm.clear();
char test_name[1024] = ""; snprintf(test_name, 1024, "Comm %s Mesh %s %s Buffers %s %s %s %s",
pol_comm::get_name(),
pol_mesh::get_name(), aloc_mesh.name(),
pol_many::get_name(), aloc_many.name(), pol_few::get_name(), aloc_few.name());
fgprintf(FileGroup::all, "Starting test %s\n", test_name);
{
Range r0(test_name, Range::orange);
// make a copy of comminfo to duplicate the MPI communicator
CommInfo comminfo(comm_info);
using comm_type = Comm<pol_many, pol_few, pol_comm>;
#ifdef COMB_ENABLE_MPI
// set name of communicator
// include name of memory space if using mpi datatypes for pack/unpack
char comm_name[MPI_MAX_OBJECT_NAME] = "";
snprintf(comm_name, MPI_MAX_OBJECT_NAME, "COMB_MPI_CART_COMM%s%s",
(comm_type::use_mpi_type) ? "_" : "",
(comm_type::use_mpi_type) ? aloc_mesh.name() : "");
comminfo.set_name(comm_name);
#endif
CommContext<pol_comm> con_comm(con_comm_in
#ifdef COMB_ENABLE_MPI
,comminfo.cart.comm
#endif
);
// sometimes set cutoff to 0 (always use pol_many) to simplify algorithms
if (std::is_same<pol_many, pol_few>::value) {
// check comm send (packing) method
switch (comminfo.post_send_method) {
case CommInfo::method::waitsome:
case CommInfo::method::testsome:
// don't change cutoff to see if breaking messages into
// sized groups matters
break;
default:
// already packing individually or all together
// might aw well use simpler algorithm
comminfo.cutoff = 0;
break;
}
}
// make communicator object
comm_type comm(con_comm, comminfo, aloc_mesh, aloc_many, aloc_few);
comm.barrier();
tm_total.start(tm_con, "start-up");
std::vector<MeshData> vars;
vars.reserve(num_vars);
{
Range r2("setup factory", Range::yellow);
CommFactory factory(comminfo);
r2.restart("add vars", Range::yellow);
for (IdxT i = 0; i < num_vars; ++i) {
vars.push_back(MeshData(info, aloc_mesh));
vars[i].allocate();
DataT* data = vars[i].data();
IdxT totallen = info.totallen;
con_mesh.for_all(totallen,
[=] COMB_HOST COMB_DEVICE (IdxT i) {
// LOGPRINTF("init-var %p[%i] = %f\n", data, i, -1.0);
data[i] = -1.0;
});
factory.add_var(vars[i]);
con_mesh.synchronize();
}
r2.restart("populate comm", Range::yellow);
factory.populate(comm, con_many, con_few);
}
tm_total.stop(tm_con);
comm.barrier();
Range r1("test correctness", Range::indigo);
tm_total.start(tm_con, "test-comm");
if (comm_type::persistent) {
// tm.start(tm_con, "init-persistent-comm");
comm.init_persistent_comm(con_many, con_few);
// tm.stop(tm_con);
}
IdxT ntestcycles = std::max(IdxT{1}, ncycles/IdxT{10});
for (IdxT test_cycle = 0; test_cycle < ntestcycles; ++test_cycle) { // test comm
Range r2("cycle", Range::cyan);
bool mock_communication = comm.mock_communication();
IdxT imin = info.min[0];
IdxT jmin = info.min[1];
IdxT kmin = info.min[2];
IdxT imax = info.max[0];
IdxT jmax = info.max[1];
IdxT kmax = info.max[2];
IdxT ilen = info.len[0];
IdxT jlen = info.len[1];
IdxT klen = info.len[2];
IdxT iglobal_offset = info.global_offset[0];
IdxT jglobal_offset = info.global_offset[1];
IdxT kglobal_offset = info.global_offset[2];
IdxT ilen_global = info.global.sizes[0];
IdxT jlen_global = info.global.sizes[1];
IdxT klen_global = info.global.sizes[2];
IdxT iperiodic = info.global.periodic[0];
IdxT jperiodic = info.global.periodic[1];
IdxT kperiodic = info.global.periodic[2];
IdxT ighost_width = info.ghost_widths[0];
IdxT jghost_width = info.ghost_widths[1];
IdxT kghost_width = info.ghost_widths[2];
IdxT ijlen = info.stride[2];
IdxT ijlen_global = ilen_global * jlen_global;
Range r3("pre-comm", Range::red);
// tm.start(tm_con, "pre-comm");
for (IdxT i = 0; i < num_vars; ++i) {
DataT* data = vars[i].data();
IdxT var_i = i + 1;
con_mesh.for_all_3d(klen,
jlen,
ilen,
[=] COMB_HOST COMB_DEVICE (IdxT k, IdxT j, IdxT i) {
IdxT zone = i + j * ilen + k * ijlen;
IdxT iglobal = i + iglobal_offset;
if (iperiodic) {
iglobal = iglobal % ilen_global;
if (iglobal < 0) iglobal += ilen_global;
}
IdxT jglobal = j + jglobal_offset;
if (jperiodic) {
jglobal = jglobal % jlen_global;
if (jglobal < 0) jglobal += jlen_global;
}
IdxT kglobal = k + kglobal_offset;
if (kperiodic) {
kglobal = kglobal % klen_global;
if (kglobal < 0) kglobal += klen_global;
}
IdxT zone_global = iglobal + jglobal * ilen_global + kglobal * ijlen_global;
DataT expected, found, next;
int branchid = -1;
if (k >= kmin+kghost_width && k < kmax-kghost_width &&
j >= jmin+jghost_width && j < jmax-jghost_width &&
i >= imin+ighost_width && i < imax-ighost_width) {
// interior non-communicated zones
expected = -1.0; found = data[zone]; next =-(zone_global+var_i);
branchid = 0;
} else if (k >= kmin && k < kmax &&
j >= jmin && j < jmax &&
i >= imin && i < imax) {
// interior communicated zones
expected = -1.0; found = data[zone]; next = zone_global + var_i;
branchid = 1;
} else if (iglobal < 0 || iglobal >= ilen_global ||
jglobal < 0 || jglobal >= jlen_global ||
kglobal < 0 || kglobal >= klen_global) {
// out of global bounds exterior zones, some may be owned others not
// some may be communicated if at least one dimension is periodic
// and another is non-periodic
expected = -1.0; found = data[zone]; next = zone_global + var_i;
branchid = 2;
} else {
// in global bounds exterior zones
expected = -1.0; found = data[zone]; next =-(zone_global+var_i);
branchid = 3;
}
if (!mock_communication) {
if (found != expected) {
FGPRINTF(FileGroup::proc, "test pre-comm %p %i zone %i(%i %i %i) g%i(%i %i %i) = %f expected %f next %f\n", data, branchid, zone, i, j, k, zone_global, iglobal, jglobal, kglobal, found, expected, next);
}
// LOGPRINTF("test pre-comm %p[%i]{%f} = %f\n", data, zone, found, next);
assert(found == expected);
}
data[zone] = next;
});
}
con_mesh.synchronize();
// tm.stop(tm_con);
r3.restart("post-recv", Range::pink);
// tm.start(tm_con, "post-recv");
comm.postRecv(con_many, con_few);
// tm.stop(tm_con);
r3.restart("post-send", Range::pink);
// tm.start(tm_con, "post-send");
comm.postSend(con_many, con_few);
// tm.stop(tm_con);
r3.stop();
// for (IdxT i = 0; i < num_vars; ++i) {
// DataT* data = vars[i].data();
// IdxT var_i = i + 1;
// con_mesh.for_all_3d(klen,
// jlen,
// ilen,
// [=] COMB_HOST COMB_DEVICE (IdxT k, IdxT j, IdxT i) {
// IdxT zone = i + j * ilen + k * ijlen;
// IdxT iglobal = i + iglobal_offset;
// if (iperiodic) {
// iglobal = iglobal % ilen_global;
// if (iglobal < 0) iglobal += ilen_global;
// }
// IdxT jglobal = j + jglobal_offset;
// if (jperiodic) {
// jglobal = jglobal % jlen_global;
// if (jglobal < 0) jglobal += jlen_global;
// }
// IdxT kglobal = k + kglobal_offset;
// if (kperiodic) {
// kglobal = kglobal % klen_global;
// if (kglobal < 0) kglobal += klen_global;
// }
// IdxT zone_global = iglobal + jglobal * ilen_global + kglobal * ijlen_global;
// DataT expected, found, next;
// int branchid = -1;
// if (k >= kmin+kghost_width && k < kmax-kghost_width &&
// j >= jmin+jghost_width && j < jmax-jghost_width &&
// i >= imin+ighost_width && i < imax-ighost_width) {
// // interior non-communicated zones should not have changed value
// expected =-(zone_global+var_i); found = data[zone]; next = -1.0;
// branchid = 0;
// if (!mock_communication) {
// if (found != expected) {
// FGPRINTF(FileGroup::proc, "test mid-comm %p %i zone %i(%i %i %i) g%i(%i %i %i) = %f expected %f next %f\n", data, branchid, zone, i, j, k, zone_global, iglobal, jglobal, kglobal, found, expected, next);
// }
// LOGPRINTF("test mid-comm %p[%i]{%f} = %f\n", data, zone, found, next);
// assert(found == expected);
// }
// data[zone] = next;
// }
// // other zones may be participating in communication, do not access
// });
// }
// con_mesh.synchronize();
r3.start("wait-recv", Range::pink);
// tm.start(tm_con, "wait-recv");
comm.waitRecv(con_many, con_few);
// tm.stop(tm_con);
r3.restart("wait-send", Range::pink);
// tm.start(tm_con, "wait-send");
comm.waitSend(con_many, con_few);
// tm.stop(tm_con);
r3.restart("post-comm", Range::red);
// tm.start(tm_con, "post-comm");
for (IdxT i = 0; i < num_vars; ++i) {
DataT* data = vars[i].data();
IdxT var_i = i + 1;
con_mesh.for_all_3d(klen,
jlen,
ilen,
[=] COMB_HOST COMB_DEVICE (IdxT k, IdxT j, IdxT i) {
IdxT zone = i + j * ilen + k * ijlen;
IdxT iglobal = i + iglobal_offset;
if (iperiodic) {
iglobal = iglobal % ilen_global;
if (iglobal < 0) iglobal += ilen_global;
}
IdxT jglobal = j + jglobal_offset;
if (jperiodic) {
jglobal = jglobal % jlen_global;
if (jglobal < 0) jglobal += jlen_global;
}
IdxT kglobal = k + kglobal_offset;
if (kperiodic) {
kglobal = kglobal % klen_global;
if (kglobal < 0) kglobal += klen_global;
}
IdxT zone_global = iglobal + jglobal * ilen_global + kglobal * ijlen_global;
DataT expected, found, next;
int branchid = -1;
if (k >= kmin+kghost_width && k < kmax-kghost_width &&
j >= jmin+jghost_width && j < jmax-jghost_width &&
i >= imin+ighost_width && i < imax-ighost_width) {
// interior non-communicated zones should not have changed value
expected =-(zone_global+var_i); found = data[zone]; next = -1.0;
branchid = 0;
} else if (k >= kmin && k < kmax &&
j >= jmin && j < jmax &&
i >= imin && i < imax) {
// interior communicated zones should not have changed value
expected = zone_global + var_i; found = data[zone]; next = -1.0;
branchid = 1;
} else if (iglobal < 0 || iglobal >= ilen_global ||
jglobal < 0 || jglobal >= jlen_global ||
kglobal < 0 || kglobal >= klen_global) {
// out of global bounds exterior zones should not have changed value
// some may have been communicated, but values should be the same
expected = zone_global + var_i; found = data[zone]; next = -1.0;
branchid = 2;
} else {
// in global bounds exterior zones should have changed value
// should now be populated with data from another rank
expected = zone_global + var_i; found = data[zone]; next = -1.0;
branchid = 3;
}
if (!mock_communication) {
if (found != expected) {
FGPRINTF(FileGroup::proc, "test post-comm %p %i zone %i(%i %i %i) g%i(%i %i %i) = %f expected %f next %f\n", data, branchid, zone, i, j, k, zone_global, iglobal, jglobal, kglobal, found, expected, next);
}
// LOGPRINTF("test post-comm %p[%i]{%p} = %f\n", data, zone, found, next);
assert(found == expected);
}
data[zone] = next;
});
}
con_mesh.synchronize();
// tm.stop(tm_con);
r3.stop();
r2.stop();
}
if (comm_type::persistent) {
// tm.start(tm_con, "cleanup-persistent-comm");
comm.cleanup_persistent_comm();
// tm.stop(tm_con);
}
comm.barrier();
tm_total.stop(tm_con);
tm.clear();
r1.restart("bench comm", Range::magenta);
tm_total.start(tm_con, "bench-comm");
if (comm_type::persistent) {
tm.start(tm_con, "init-persistent-comm");
comm.init_persistent_comm(con_many, con_few);
tm.stop(tm_con);
}
for(IdxT cycle = 0; cycle < ncycles; cycle++) {
Range r2("cycle", Range::yellow);
IdxT imin = info.min[0];
IdxT jmin = info.min[1];
IdxT kmin = info.min[2];
IdxT imax = info.max[0];
IdxT jmax = info.max[1];
IdxT kmax = info.max[2];
IdxT ilen = info.len[0];
IdxT jlen = info.len[1];
IdxT klen = info.len[2];
IdxT ijlen = info.stride[2];
Range r3("pre-comm", Range::red);
tm.start(tm_con, "pre-comm");
for (IdxT i = 0; i < num_vars; ++i) {
DataT* data = vars[i].data();
// set internal zones to 1
con_mesh.for_all_3d(kmax - kmin,
jmax - jmin,
imax - imin,
detail::set_1(ilen, ijlen, data, imin, jmin, kmin));
}
con_mesh.synchronize();
tm.stop(tm_con);
r3.restart("post-recv", Range::pink);
tm.start(tm_con, "post-recv");
comm.postRecv(con_many, con_few);
tm.stop(tm_con);
r3.restart("post-send", Range::pink);
tm.start(tm_con, "post-send");
comm.postSend(con_many, con_few);
tm.stop(tm_con);
r3.stop();
/*
for (IdxT i = 0; i < num_vars; ++i) {
DataT* data = vars[i].data();
con_mesh.for_all_3d(klen,
jlen,
ilen,
[=] COMB_HOST COMB_DEVICE (IdxT k, IdxT j, IdxT i) {
IdxT zone = i + j * ilen + k * ijlen;
DataT expected, found, next;
if (k >= kmin && k < kmax &&
j >= jmin && j < jmax &&
i >= imin && i < imax) {
expected = 1.0; found = data[zone]; next = 1.0;
} else {
expected = -1.0; found = data[zone]; next = -1.0;
}
// if (found != expected) {
// FGPRINTF(FileGroup::proc, "zone %i(%i %i %i) = %f expected %f\n", zone, i, j, k, found, expected);
// }
// LOGPRINTF("%p[%i] = %f\n", data, zone, 1.0);
data[zone] = next;
});
}
*/
r3.start("wait-recv", Range::pink);
tm.start(tm_con, "wait-recv");
comm.waitRecv(con_many, con_few);
tm.stop(tm_con);
r3.restart("wait-send", Range::pink);
tm.start(tm_con, "wait-send");
comm.waitSend(con_many, con_few);
tm.stop(tm_con);
r3.restart("post-comm", Range::red);
tm.start(tm_con, "post-comm");
for (IdxT i = 0; i < num_vars; ++i) {
DataT* data = vars[i].data();
// set all zones to 1
con_mesh.for_all_3d(klen,
jlen,
ilen,
detail::set_1(ilen, ijlen, data, 0, 0, 0));
}
con_mesh.synchronize();
tm.stop(tm_con);
r3.stop();
r2.stop();
}
if (comm_type::persistent) {
tm.start(tm_con, "cleanup-persistent-comm");
comm.cleanup_persistent_comm();
tm.stop(tm_con);
}
comm.barrier();
tm_total.stop(tm_con);
r1.stop();
print_timer(comminfo, tm);
print_timer(comminfo, tm_total);
}
tm.clear();
tm_total.clear();
// print_proc_memory_stats(comminfo);
}
} // namespace COMB
#endif // _DO_CYCLES_HPP
| 34.039249 | 221 | 0.542187 | [
"mesh",
"object",
"vector"
] |
4e89fae9fd362a52a8314d0ed5a14166c1c0b1c0 | 3,207 | cpp | C++ | mat.cpp | giladjerusalem/test1B-CPP | bca77759a9881954b3022ead9de577a59bfd4278 | [
"MIT"
] | null | null | null | mat.cpp | giladjerusalem/test1B-CPP | bca77759a9881954b3022ead9de577a59bfd4278 | [
"MIT"
] | null | null | null | mat.cpp | giladjerusalem/test1B-CPP | bca77759a9881954b3022ead9de577a59bfd4278 | [
"MIT"
] | null | null | null |
#include "mat.hpp"
using namespace std;
namespace ariel
{
std::string mat(int row, int col, char symbol1, char symbol2)
{
// char symbol1, char symbol2 must be HASKI !!!!!!
if ((row % 2 == 0 || col % 2 == 0 )||(row <= 0 || col <=0 ))
{ // if one of number not odd -> throw
throw exception();
}
if (int(symbol1) <33 || int(symbol1) >= 136 )
{ // if one of number not odd -> throw
throw exception();
}
if (int(symbol2) <33 || int(symbol2) >=136 )
{ // if one of number not odd -> throw
throw exception();
}
vector<vector<char>> vect; // define 2D vector
for (int i = 0; i < row; i++)
{ // Vector to store column elements
vector<char> v1;
for (int j = 0; j < col; j++)
{
v1.push_back('a');
}
// Pushing back above 1D vector
// to create the 2D vector
vect.push_back(v1);
}
for (int z = 0; z < col; z++)
{ // define the base case-->first line
vect[0][z] = symbol1;
}
for (int i = 1; i < ((row / 2) ); i++)
{ // line 1-->4
for (int z = 0; z < i; z++)
{ // case 1
// cout<<"a"<<endl;
vect[i][z] = vect[i - 1][z];
}
for (int z = i; z < col - i; z++)
{ // case 2
if (i % 2 == 0)
{ // if zugi print symbol1
vect[i][z] = symbol1;
}
else if (i % 2 == 1)
{ // if odd print symbol2
vect[i][z] = symbol2;
}
}
for (int z = col - i; z < col; z++)
{ // case 3
// cout<<"c"<<endl;
vect[i][z] = vect[i - 1][z];
}
} // close out for
int i =(row / 2);
for (int z = 0; z < i; z++)
{ // case 1
vect[i][z] = vect[i - 1][z];
}
for (int z = i; z < (col - i); z++)
{ // case 2
if (i % 2 == 0)
{ // if zugi print symbol1
vect[i][z] = symbol1;
}
else if (i % 2 == 1)
{ // if odd print symbol2
vect[i][z] = symbol2;
}
}
for (int z = col - i; z < col; z++)
{ // case 3
vect[i][z] = vect[i - 1][z];
}
for (int i = row-1; i >= ((row / 2) + 1); i--)
{
for (int j = 0; j < col ;j++)
{
vect[i][j] = vect[row-i-1][j];
}
}
// for (int z = 0; z < col; z++){ //define the base case-->first line
// vect[row][z]=symbol1;
// }
string s = "";
for (int i = 0; i < col; i++)
{
for (int j = 0; j < row; j++)
{
s += vect[j][i];
}
s += "\n";
}
return ""+s;
}
} | 26.504132 | 84 | 0.328344 | [
"vector"
] |
4e8d8af108abc94f45ea4de44fb329e7ac54c80f | 7,465 | cpp | C++ | noveltyset.cpp | jal278/mazerobot-python | ec63e46c9821cb74c63e89d0f7dfc3dbe479e313 | [
"MIT"
] | 5 | 2017-05-16T08:41:58.000Z | 2021-04-08T12:52:25.000Z | noveltyset.cpp | jal278/mazerobot-python | ec63e46c9821cb74c63e89d0f7dfc3dbe479e313 | [
"MIT"
] | null | null | null | noveltyset.cpp | jal278/mazerobot-python | ec63e46c9821cb74c63e89d0f7dfc3dbe479e313 | [
"MIT"
] | 4 | 2015-09-08T20:02:47.000Z | 2017-05-20T18:15:56.000Z | #include "noveltyset.h"
#include <string.h>
#include "population.h"
#include "organism.h"
//for sorting by novelty
bool cmp(const noveltyitem *a, const noveltyitem* b)
{
return a->novelty < b->novelty;
}
//for sorting by fitness
bool cmp_fit(const noveltyitem *a, const noveltyitem *b)
{
return a->fitness < b->fitness;
}
noveltyitem::noveltyitem(const noveltyitem& item)
{
added=false;
//TODO: this might cause memory leak in
//merge_population?
age=item.age;
viable=item.viable;
genotype=new Genome(*(item.genotype));
phenotype=new Network(*(item.phenotype));
age=item.age;
fitness=item.fitness;
novelty=item.novelty;
rank=item.rank;
generation=item.generation;
competition=item.competition;
indiv_number=item.indiv_number;
secondary=item.secondary;
for(int i=0; i<(int)item.data.size(); i++)
{
vector<float> temp;
for(int j=0; j<(int)item.data[i].size(); j++)
temp.push_back(item.data[i][j]);
data.push_back(temp);
}
}
//merge two populations together according to novelty
Population* noveltyarchive::merge_populations(Population* p1, vector<Organism*> p2)
{
vector<Organism*> total_orgs;
vector<Organism*> merged_orgs;
vector<Organism*>::iterator it;
vector<noveltyitem*>::iterator novit;
//compile the organisms together
for(it = p1->organisms.begin(); it!= p1->organisms.end(); it++)
{
total_orgs.push_back(*it);
(*it)->blacklist=false;
}
for(it = p2.begin(); it!= p2.end(); it++)
{
total_orgs.push_back(*it);
(*it)->blacklist=false;
}
//throw in the archive as well
for(novit = novel_items.begin(); novit != novel_items.end(); novit++)
{
//TODO: just creating these organisms will be a mem leak
//eventually refactor...
Organism* arch_org = new Organism(0.1,(*novit)->genotype,0,NULL);
arch_org->noveltypoint = (*novit);
arch_org->blacklist=false;
total_orgs.push_back(arch_org);
//or at least delete...?
}
int size = total_orgs.size(); //remove one since we are adding 1st
cout << size << " " << p1->organisms.size() << " " << p2.size() << " " <<
novel_items.size() << endl;
//randomly add first member to merged organisms
Organism* last_added = total_orgs[rand()%size];
last_added->blacklist=true;
merged_orgs.push_back(last_added);
for(it = total_orgs.begin(); it!=total_orgs.end(); it++)
{
(*it)->closest = 100000.0;
}
//now greedily add point furthest from merged pop so far
//for(int x=0;x<(size/2)-1;x++)
for(int x=0; x<(p1->organisms.size()-1); x++)
{
Organism* best=NULL;
double best_dist= -1000.0;
for(it = total_orgs.begin(); it!=total_orgs.end(); it++)
{
if ((*it)->blacklist)
continue;
double new_dist = (*novelty_metric)((*it)->noveltypoint,
last_added->noveltypoint);
if (new_dist < (*it)->closest)
(*it)->closest = new_dist;
if ((*it)->closest > best_dist)
{
best_dist = ((*it)->closest);
best = *it;
}
}
best->blacklist=true;
last_added = best;
merged_orgs.push_back(best);
}
return new Population(merged_orgs);
}
void noveltyarchive::rank(vector<Organism*>& orgs)
{
evaluate_population(orgs); //assign novelty, local competition etc.
int sz=orgs.size();
//reset vars
for(int i=0; i<sz; i++) {
orgs[i]->noveltypoint->dominationcount=0;
orgs[i]->noveltypoint->dominationList.clear();
}
//do domination
for(int i=0; i<sz; i++)
for(int j=0; j<sz; j++)
orgs[i]->noveltypoint->dominate(orgs[j]->noveltypoint);
int ranked=0;
int cur_rank=0;
//assign ranks
vector<noveltyitem*> front;
while(ranked!=sz) {
for(int i=0; i<sz; i++)
{
if(orgs[i]->noveltypoint->dominationcount==0) {
front.push_back(orgs[i]->noveltypoint);
orgs[i]->noveltypoint->dominationcount = -1;
orgs[i]->noveltypoint->rank=cur_rank;
orgs[i]->fitness=sz-cur_rank;
ranked++;
}
}
//undominate those that the front dominated
int frsz = front.size();
for(int i=0; i<frsz; i++) {
front[i]->undominate();
}
front.clear();
cur_rank++;
}
int max_rank = cur_rank;
for(int i=0; i<sz; i++)
orgs[i]->fitness=max_rank-orgs[i]->noveltypoint->rank;
//sort population based on rank
std::sort(orgs.begin(), orgs.end(), order_orgs);
}
//evaluate the novelty of the whole population
void noveltyarchive::evaluate_population(Population* p1,vector<Organism*> p2,bool fitness)
{
vector<Organism*>::iterator it;
for(it=p1->organisms.begin(); it<p1->organisms.end(); it++)
evaluate_individual((*it),p2,fitness);
}
//evaluate the novelty of the whole population
void noveltyarchive::evaluate_population(Population* pop,bool fitness)
{
Population *p = (Population*)pop;
vector<Organism*>::iterator it;
for(it=p->organisms.begin(); it<p->organisms.end(); it++)
evaluate_individual((*it),pop->organisms,fitness);
}
//evaluate the novelty of a list of organisms
void noveltyarchive::evaluate_population(vector<Organism*> orgs, bool fitness)
{
vector<Organism*>::iterator it;
for(it=orgs.begin(); it!=orgs.end(); it++)
evaluate_individual((*it),orgs,fitness);
}
//evaluate the novelty of a single individual
void noveltyarchive::evaluate_individual(Organism* ind,vector<Organism*> pop,bool fitness)
{
float result;
if(fitness) //assign fitness according to average novelty
{
if(ind->destroy)
{
result = 0.000000001;
ind->fitness = result;
ind->noveltypoint->novelty=result;
ind->noveltypoint->genodiv=0;
}
else
{
if(!histogram)
result = novelty_avg_nn(ind->noveltypoint,-1,false,&pop);
else
result = novelty_histogram(ind->noveltypoint);
}
//NEW WAY: production of novelty important
if(production_score) {
int init_weight=10;
double fit_weight=init_weight;
double fit_tot=ind->noveltypoint->novelty*init_weight;
fit_tot+= ind->gnome->production;
fit_weight+= ind->gnome->production_count;
ind->fitness = fit_tot/fit_weight;
//cout << fit_weight << endl;
//cout << "adjusting novelty, weight " << fit_weight << ", from " << ind->noveltypoint->novelty << " to " << ind->fitness << endl;
//END NEW WAY
} else {
ind->fitness = result; //old way
}
}
else //consider adding a point to archive based on dist to nearest neighbor
{
if(!histogram)
{
result = novelty_avg_nn(ind->noveltypoint,1,false);
//ind->noveltypoint->novelty=result;
//if(!minimal_criteria)
// ind->noveltypoint->viable=true;
if((!minimal_criteria || ind->noveltypoint->viable) && add_to_novelty_archive(result))
add_novel_item(ind->noveltypoint);
}
}
}
| 29.389764 | 142 | 0.586604 | [
"vector"
] |
4e928a5df6e1fa016593eebe78db3f363e25f495 | 346 | cpp | C++ | mesh-modify/src/bin/main.cpp | ahewer/mri-shape-tools | 4268499948f1330b983ffcdb43df62e38ca45079 | [
"MIT"
] | null | null | null | mesh-modify/src/bin/main.cpp | ahewer/mri-shape-tools | 4268499948f1330b983ffcdb43df62e38ca45079 | [
"MIT"
] | 2 | 2017-05-29T09:43:01.000Z | 2017-05-29T09:50:05.000Z | mesh-modify/src/bin/main.cpp | ahewer/mri-shape-tools | 4268499948f1330b983ffcdb43df62e38ca45079 | [
"MIT"
] | 4 | 2017-05-17T11:56:02.000Z | 2022-03-05T09:12:24.000Z | #include "mesh/MeshIO.h"
#include "settings.h"
#include "mesh-modify/ApplyModifications.h"
int main(int argc, char* argv[]) {
Settings settings(argc, argv);
Mesh mesh = MeshIO::read(settings.input);
meshModify::ApplyModifications(mesh).apply(settings.specifications);
MeshIO::write(mesh, settings.output);
return 0;
}
| 18.210526 | 72 | 0.699422 | [
"mesh"
] |
4ea5ff5436471b2ef0d455ea1eeb9834a4cc5a29 | 1,356 | cpp | C++ | systems/plants/constraint/testPostureConstraintmex.cpp | andybarry/drake | 61428cff8cb523314cd87105821148519460a0b9 | [
"BSD-3-Clause"
] | 1 | 2020-01-12T14:32:29.000Z | 2020-01-12T14:32:29.000Z | systems/plants/constraint/testPostureConstraintmex.cpp | cmmccann/drake | 0a124c044357d5a29ec7e536acb747cfa5682eba | [
"BSD-3-Clause"
] | null | null | null | systems/plants/constraint/testPostureConstraintmex.cpp | cmmccann/drake | 0a124c044357d5a29ec7e536acb747cfa5682eba | [
"BSD-3-Clause"
] | 1 | 2021-07-07T18:52:51.000Z | 2021-07-07T18:52:51.000Z | #include "mex.h"
#include "RigidBodyConstraint.h"
#include "drakeUtil.h"
#include "../RigidBodyManipulator.h"
#include <cstring>
/*
* [lower_bound,upper_bound] = testPostureConstraintmex(postureConstraint_ptr,t)
* @param postureConstraint_ptr A pointer to a PostureConstraint object
* @param t A double scalar, the time to evaluate the lower and upper bounds, This is optional if the constraint is time-invariant
* @retval lower_bound The lower bound of the joints at time t
* @retval upper_bound The upper bound of the joints at time t
* */
void mexFunction(int nlhs,mxArray* plhs[], int nrhs, const mxArray *prhs[])
{
if(nrhs != 2 && nrhs != 1)
{
mexErrMsgIdAndTxt("Drake:testPostureConstraintmex:BadInputs","Usage [lb,ub] = testPostureConstraintmex(pc_ptr,t)");
}
double t;
double* t_ptr;
if(nrhs == 1)
{
t_ptr = nullptr;
}
else
{
t = mxGetScalar(prhs[1]);
t_ptr = &t;
}
PostureConstraint* pc = (PostureConstraint*) getDrakeMexPointer(prhs[0]);
int nq = pc->getRobotPointer()->num_dof;
VectorXd lb,ub;
pc->bounds(t_ptr,lb,ub);
plhs[0] = mxCreateDoubleMatrix(nq,1,mxREAL);
plhs[1] = mxCreateDoubleMatrix(nq,1,mxREAL);
memcpy(mxGetPr(plhs[0]),lb.data(),sizeof(double)*nq);
memcpy(mxGetPr(plhs[1]),ub.data(),sizeof(double)*nq);
}
| 34.769231 | 157 | 0.671829 | [
"object"
] |
4eada14e46d80a6c8b8f58b372ebc23d0cff3912 | 791 | hpp | C++ | include/xmlParser.hpp | JonasRock/XML_GridViewServer | b079bc6edf3a855da9cbad3a976554da3dd1212c | [
"Apache-2.0"
] | null | null | null | include/xmlParser.hpp | JonasRock/XML_GridViewServer | b079bc6edf3a855da9cbad3a976554da3dd1212c | [
"Apache-2.0"
] | null | null | null | include/xmlParser.hpp | JonasRock/XML_GridViewServer | b079bc6edf3a855da9cbad3a976554da3dd1212c | [
"Apache-2.0"
] | null | null | null | #ifndef XMLPARSER_H
#define XMLPARSER_H
#include <string>
#include "json.hpp"
#include "pugixml.hpp"
#include "types.hpp"
namespace xmlServer
{
class XmlParser
{
public:
bool parse(const std::string uri, pugi::xml_parse_result &result);
nlohmann::json getNodeData(const std::string uri, const std::string xPathExpression, bool arxml = false);
nlohmann::json getNodePosition(const std::string uri, const std::string xPathExpression);
xmlServer::types::Position getPositionFromOffset(const std::string uri, const uint32_t offset);
private:
std::map<std::string, pugi::xml_document> xmlRoots_;
std::map<std::string, std::vector<uint32_t>> newlineOffsets_;
void parseNewlines(const std::string uri, const std::string filepath);
};
}
#endif /* XMLPARSER_H */ | 24.71875 | 109 | 0.738306 | [
"vector"
] |
4eb37573e465439338e0265ece195fa948b8010e | 1,284 | hpp | C++ | module-db/queries/messages/sms/QuerySMSGet.hpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 369 | 2021-11-10T09:20:29.000Z | 2022-03-30T06:36:58.000Z | module-db/queries/messages/sms/QuerySMSGet.hpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 149 | 2021-11-10T08:38:35.000Z | 2022-03-31T23:01:52.000Z | module-db/queries/messages/sms/QuerySMSGet.hpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 41 | 2021-11-10T08:30:37.000Z | 2022-03-29T08:12:46.000Z | // Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#pragma once
#include <queries/RecordQuery.hpp>
#include <queries/Filter.hpp>
#include <Interface/SMSRecord.hpp>
#include <string>
namespace db::query
{
class SMSGet : public RecordQuery
{
public:
SMSGet(std::size_t limit, std::size_t offset);
[[nodiscard]] auto debugInfo() const -> std::string override;
};
class SMSGetWithTotalCount : public SMSGet
{
public:
SMSGetWithTotalCount(std::size_t limit, std::size_t offset);
[[nodiscard]] auto debugInfo() const -> std::string override;
};
class SMSGetResult : public RecordQueryResult<SMSRecord>
{
public:
SMSGetResult(std::vector<SMSRecord> records);
[[nodiscard]] auto debugInfo() const -> std::string override;
};
class SMSGetResultWithTotalCount : public SMSGetResult
{
public:
SMSGetResultWithTotalCount(std::vector<SMSRecord> records, std::size_t totalCount);
[[nodiscard]] auto debugInfo() const -> std::string override;
auto getTotalCount() const -> std::size_t;
private:
std::size_t totalCount;
};
}; // namespace db::query
| 27.319149 | 91 | 0.656542 | [
"vector"
] |
4eb376ce2c109b9d97f158db918173ff31df8f0e | 4,590 | cpp | C++ | day22/reactor_reboot.cpp | Harold2017/AdventOfCode2021 | 5215d25a908562f34a360f293c17438cf80157b8 | [
"MIT"
] | null | null | null | day22/reactor_reboot.cpp | Harold2017/AdventOfCode2021 | 5215d25a908562f34a360f293c17438cf80157b8 | [
"MIT"
] | null | null | null | day22/reactor_reboot.cpp | Harold2017/AdventOfCode2021 | 5215d25a908562f34a360f293c17438cf80157b8 | [
"MIT"
] | null | null | null | //
// Created by Harold on 2021/12/22.
//
#include <fstream>
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <memory>
#include <unordered_map>
struct Cube
{
int lx, ly, lz, hx, hy, hz;
bool is_on = false;
Cube() = default;
Cube(int lx_, int ly_, int lz_, int hx_, int hy_, int hz_)
: lx(lx_), ly(ly_), lz(lz_), hx(hx_), hy(hy_), hz(hz_) { }
bool is_inside(Cube const& other) const
{
return (lx >= other.lx && ly >= other.ly && lz >= other.lz) &&
(hx <= other.hx && hy <= other.hz && lz <= other.hz);
}
bool is_intersect(Cube const& other) const
{
if (lx > other.hx || hx < other.lx) return false;
if (ly > other.hy || hy < other.ly) return false;
if (lz > other.hz || hz < other.lz) return false;
return true;
}
size_t volume() const
{
return size_t(hx - lx + 1) * size_t(hy - ly + 1) * size_t(hz - lz + 1);
}
};
std::ostream& operator<<(std::ostream& os, Cube const& cube)
{
os << (cube.is_on ? "on " : "off ") << '[' << cube.lx << ", " << cube.ly << ", " << cube.lz << "], [" << cube.hx << ", " << cube.hy << ", " << cube.hz << ']';
return os;
}
using Cubes = std::vector<Cube>;
std::ostream& operator<<(std::ostream& os, Cubes const& cubes)
{
for (auto const& cube : cubes)
os << cube << '\n';
return os;
}
void read_all(std::ifstream& ifs, Cubes& cubes)
{
std::string line;
while(std::getline(ifs, line))
{
Cube cube;
// on or off
auto space_pos = line.find(' ');
cube.is_on = line.substr(0, space_pos) == "on" ? true : false;
auto position = line.substr(space_pos + 1);
std::sscanf(position.c_str(), "x=%d..%d,y=%d..%d,z=%d..%d", &cube.lx, &cube.hx, &cube.ly, &cube.hy, &cube.lz, &cube.hz);
cubes.push_back(cube);
}
}
void substract(Cube const& c0, Cube const& c1, Cubes& res_cubes)
{
Cube overlap(std::max(c0.lx, c1.lx), std::max(c0.ly, c1.ly), std::max(c0.lz, c1.lz),
std::min(c0.hx, c1.hx), std::min(c0.hy, c1.hy), std::min(c0.hz, c1.hz));
// z direction
if (c0.lz < overlap.lz) // bottom part
res_cubes.emplace_back(c0.lx, c0.ly, c0.lz, c0.hx, c0.hy, overlap.lz - 1);
if (c0.hz > overlap.hz) // top part
res_cubes.emplace_back(c0.lx, c0.ly, overlap.hz + 1, c0.hx, c0.hy, c0.hz);
// x direction
if (c0.lx < overlap.lx) // front
res_cubes.emplace_back(c0.lx, c0.ly, overlap.lz, overlap.lx - 1, c0.hy, overlap.hz);
if (c0.hx > overlap.hx) // back
res_cubes.emplace_back(overlap.hx + 1, c0.ly, overlap.lz, c0.hx, c0.hy, overlap.hz);
// y direction
if (c0.ly < overlap.ly) // left
res_cubes.emplace_back(overlap.lx, c0.ly, overlap.lz, overlap.hx, overlap.ly - 1, overlap.hz);
if (c0.hy > overlap.hy) // right
res_cubes.emplace_back(overlap.lx, overlap.hy + 1, overlap.lz, overlap.hx, c0.hy, overlap.hz);
}
size_t PartOne(char const* input)
{
std::ifstream ifs(input);
Cubes cubes;
read_all(ifs, cubes);
//std::cout << cubes << std::endl;
Cubes res;
for (auto const& cube : cubes)
{
Cubes tmp;
for (auto const &c : res)
if (c.is_intersect(cube))
substract(c, cube, tmp);
else
tmp.push_back(c);
if (cube.is_on)
tmp.push_back(cube);
res = std::move(tmp);
}
//std::cout << res << std::endl;
size_t cnt = 0;
Cube region(-50, -50, -50, 50, 50, 50);
for (auto const& c : res)
if (c.is_inside(region))
cnt += c.volume();
return cnt;
}
size_t PartTwo(char const* input)
{
std::ifstream ifs(input);
Cubes cubes;
read_all(ifs, cubes);
//std::cout << cubes << std::endl;
Cubes res;
for (auto const& cube : cubes)
{
Cubes tmp;
for (auto const &c : res)
if (c.is_intersect(cube))
substract(c, cube, tmp);
else
tmp.push_back(c);
if (cube.is_on)
tmp.push_back(cube);
res = std::move(tmp);
}
//std::cout << res << std::endl;
size_t cnt = 0;
for (auto const& c : res)
cnt += c.volume();
return cnt;
}
int main(int argc, char* argv[])
{
std::cout << "how many cubes are on?\n"
<< PartOne(argv[1]) << std::endl;
std::cout << "how many cubes are on?\n"
<< PartTwo(argv[1]) << std::endl;
return 0;
} | 27.987805 | 162 | 0.534641 | [
"vector"
] |
4eb512f42e4214274f12eeb63b7fb4fff14ae0fc | 2,699 | cpp | C++ | Builders/Blitz.cpp | lmsp/ExtremeUltimate | 9f3f7619cc15c4bd2127411ff64c5b385f6c09ae | [
"BSD-2-Clause"
] | null | null | null | Builders/Blitz.cpp | lmsp/ExtremeUltimate | 9f3f7619cc15c4bd2127411ff64c5b385f6c09ae | [
"BSD-2-Clause"
] | null | null | null | Builders/Blitz.cpp | lmsp/ExtremeUltimate | 9f3f7619cc15c4bd2127411ff64c5b385f6c09ae | [
"BSD-2-Clause"
] | null | null | null | #include "Builders.h"
namespace Upp {
String BlitzBaseFile()
{
return ConfigFile("blitzbase");
}
void ResetBlitz()
{
SaveFile(BlitzBaseFile(), "");
}
Time blitz_base_time;
void InitBlitz()
{
Time ltm = Time::High();
const Workspace& wspc = GetIdeWorkspace();
for(int i = 0; i < wspc.GetCount(); i++) { // find lowest file time
const Package& pk = wspc.GetPackage(i);
String n = wspc[i];
for(int i = 0; i < pk.GetCount(); i++) {
String path = SourcePath(n, pk.file[i]);
if(FileExists(path))
ltm = min(ltm, FileGetTime(path));
}
}
blitz_base_time = max(GetSysTime() - 3600, Time(GetFileTime(BlitzBaseFile())));
if(ltm != Time::High())
blitz_base_time = max(blitz_base_time, ltm + 3 * 60); // should solve first build after install/checkout
}
Blitz BlitzBuilderComponent::MakeBlitzStep(Vector<String>& sfile, Vector<String>& soptions,
Vector<String>& obj, Vector<String>& immfile,
const char *objext, const Index<String>& noblitz)
{
Blitz b;
b.count = 0;
b.build = false;
if(!IsBuilder())
return b;
Vector<String> excluded;
Vector<String> excludedoptions;
b.object = CatAnyPath(builder->outdir, "$blitz" + String(objext));
Time blitztime = GetFileTime(b.object);
String blitz;
if(!IdeGetOneFile().IsEmpty())
return b;
for(int i = 0; i < sfile.GetCount(); i++) {
String fn = sfile[i];
String ext = ToLower(GetFileExt(fn));
String objfile = CatAnyPath(builder->outdir, GetFileTitle(fn) + objext);
Time fntime = GetFileTime(fn);
if((ext == ".cpp" || ext == ".cc" || ext == ".cxx" || ext == ".icpp")
&& HdependBlitzApproved(fn) && IsNull(soptions[i])
&& fntime < blitz_base_time
&& noblitz.Find(fn) < 0) {
if(HdependFileTime(fn) > blitztime)
b.build = true;
blitz << "\r\n"
<< "#define BLITZ_INDEX__ F" << i << "\r\n"
<< "#include \"" << builder->GetHostPath(fn) << "\"\r\n";
b.info << ' ' << GetFileName(fn);
const Vector<String>& d = HdependGetDefines(fn);
for(int i = 0; i < d.GetCount(); i++)
blitz << "#ifdef " << d[i] << "\r\n"
<< "#undef " << d[i] << "\r\n"
<< "#endif\r\n";
blitz << "#undef BLITZ_INDEX__\r\n";
b.count++;
}
else {
excluded.Add(fn);
excludedoptions.Add(soptions[i]);
}
}
b.path = CatAnyPath(builder->outdir, "$blitz.cpp");
if(b.count > 1) {
sfile = pick(excluded);
soptions = pick(excludedoptions);
if(builder->LoadFile(b.path) != blitz) {
builder->SaveFile(b.path, blitz);
b.build = true;
}
obj.Add(b.object);
immfile.Add(b.object);
}
else {
builder->DeleteFile(b.path);
b.build = false;
}
return b;
}
}
| 26.203883 | 106 | 0.595406 | [
"object",
"vector"
] |
4eb7ea91940aa6388db91925d1f1082be52fe3c2 | 5,415 | cpp | C++ | usbhid/src/rawhiddevice.cpp | uglycoder/usbhid | c39190bb0e0260f81eff890ec666c3cda7abc125 | [
"MIT"
] | 4 | 2018-11-24T13:10:48.000Z | 2021-09-16T07:34:36.000Z | usbhid/src/rawhiddevice.cpp | uglycoder/usbhid | c39190bb0e0260f81eff890ec666c3cda7abc125 | [
"MIT"
] | null | null | null | usbhid/src/rawhiddevice.cpp | uglycoder/usbhid | c39190bb0e0260f81eff890ec666c3cda7abc125 | [
"MIT"
] | 5 | 2018-09-26T02:11:49.000Z | 2021-09-18T08:39:38.000Z | // rawhiddevice.cpp
// MIT License
// See LICENSE.txt file in root of project
// Copyright(c) 2018 Simon Parmenter
#include "stdafx.h"
#include "../interface/rawhiddevice.hpp"
namespace
{
struct RawUSBPacket
{
char leadByte;
USBHID_ns::RawHidDevice::usbHidPacket usbPacket;
};
[[nodiscard]] std::pair<USBHID_ns::RawHidDevice::COMMS_ERROR, DWORD> ReadUSBFile(::HANDLE usbFileHandle, DWORD milliSecondTimeout, DWORD numPacketsToRead, void * buffer) noexcept;
[[nodiscard]] USBHID_ns::RawHidDevice::COMMS_ERROR WriteUSBFile(::HANDLE usbFileHandle, DWORD milliSecondTimeout, DWORD numBytesToWrite, void * buffer) noexcept;
}
USBHID_ns::RawHidDevice::RawHidDevice(hidDeviceInfo const & devInfo) : m_devInfo(devInfo)
{
}
USBHID_ns::RawHidDevice::~RawHidDevice()
{
auto const & result{ close() };
assert(result == COMMS_ERROR::SUCCESS);
}
bool USBHID_ns::RawHidDevice::open() noexcept
{
m_usbHandle = ::CreateFile(m_devInfo.path.c_str(), GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr);
return isOpen();
}
bool USBHID_ns::RawHidDevice::isOpen() const noexcept
{
return m_usbHandle != INVALID_HANDLE_VALUE;
}
USBHID_ns::RawHidDevice::COMMS_ERROR USBHID_ns::RawHidDevice::close() noexcept
{
if(isOpen())
{
auto const & result{ ::CloseHandle(m_usbHandle) };
m_usbHandle = INVALID_HANDLE_VALUE;
if(result == TRUE)
{
return COMMS_ERROR::SUCCESS;
}
else if(::GetLastError() == ERROR_INVALID_HANDLE)
{
return COMMS_ERROR::INVALID_USB_HANDLE;
}
else
{
return COMMS_ERROR::CLOSE_USB_HANDLE_FAIL;
}
}
else
{
return COMMS_ERROR::SUCCESS;
}
}
USBHID_ns::RawHidDevice::COMMS_ERROR USBHID_ns::RawHidDevice::send(usbHidPacket const & packet, DWORD milliSecondTimeout) const noexcept
{
assert(isOpen());
RawUSBPacket tmpBuffer{ 0, packet };
return WriteUSBFile(m_usbHandle, milliSecondTimeout, sizeof tmpBuffer, &tmpBuffer);
}
USBHID_ns::RawHidDevice::COMMS_ERROR USBHID_ns::RawHidDevice::receive(usbHidPacket & packet, DWORD milliSecondTimeout /*= INFINITE*/) const noexcept
{
assert(isOpen());
RawUSBPacket tmpBuffer;
auto const & result{ ReadUSBFile(m_usbHandle, milliSecondTimeout, 1UL, &tmpBuffer).first };
if(result == COMMS_ERROR::SUCCESS)
{
packet = tmpBuffer.usbPacket;
}
return result;
}
USBHID_ns::RawHidDevice::usbHidPackets_t USBHID_ns::RawHidDevice::receive(DWORD numUsbPacketsRequested, DWORD milliSecondTimeout /*= INFINITE*/) const noexcept
{
assert(isOpen());
try
{
std::vector<RawUSBPacket> tmpBuffer(numUsbPacketsRequested);
auto const[result, numPacketsRead] = ReadUSBFile(m_usbHandle, milliSecondTimeout, numUsbPacketsRequested, tmpBuffer.data());
std::vector<usbHidPacket> packetsReceived(numPacketsRead);
for(DWORD n{}; n < numPacketsRead; ++n)
{
packetsReceived[n] = tmpBuffer[n].usbPacket;
}
return { packetsReceived, result };
}
catch(...)
{
return { {},COMMS_ERROR::FAIL };
}
}
USBHID_ns::hidDeviceInfo USBHID_ns::RawHidDevice::devInfo() const noexcept
{
return m_devInfo;
}
namespace
{
std::pair<USBHID_ns::RawHidDevice::COMMS_ERROR, DWORD> ReadUSBFile(::HANDLE usbFileHandle, DWORD milliSecondTimeout, DWORD numPacketsToRead, void * buffer) noexcept
{
using COMMS_ERROR = USBHID_ns::RawHidDevice::COMMS_ERROR;
DWORD numBytesRead{};
auto const & numBytesToRead{ numPacketsToRead * static_cast<DWORD>(sizeof(RawUSBPacket)) };
::OVERLAPPED ov{ 0 };
ov.hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
::ReadFile(usbFileHandle, buffer, numBytesToRead, nullptr, &ov);
auto const waitResult{ ::WaitForSingleObject(ov.hEvent, milliSecondTimeout) };
auto const ovResult{ ::GetOverlappedResult(usbFileHandle, &ov, &numBytesRead, FALSE) };
::CloseHandle(ov.hEvent);
bool const result{
waitResult == WAIT_OBJECT_0 &&
ovResult == TRUE &&
numBytesRead == numBytesToRead };
auto const & numPacketsRead{ numBytesRead / static_cast<DWORD>(sizeof(RawUSBPacket)) };
if(result)
{
return std::make_pair(COMMS_ERROR::SUCCESS, numPacketsRead);
}
if(waitResult == WAIT_TIMEOUT)
{
::CancelIo(usbFileHandle);
return std::make_pair(COMMS_ERROR::TIMED_OUT, numPacketsRead);
}
return std::make_pair(COMMS_ERROR::FAIL, numPacketsRead);
}
USBHID_ns::RawHidDevice::COMMS_ERROR WriteUSBFile(::HANDLE usbFileHandle, DWORD milliSecondTimeout, DWORD numBytesToWrite, void * buffer) noexcept
{
using COMMS_ERROR = USBHID_ns::RawHidDevice::COMMS_ERROR;
DWORD numBytesWritten{};
::OVERLAPPED ov{ 0 };
ov.hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
::WriteFile(usbFileHandle, buffer, numBytesToWrite, nullptr, &ov);
auto const waitResult{ ::WaitForSingleObject(ov.hEvent, milliSecondTimeout) };
auto const ovResult{ ::GetOverlappedResult(usbFileHandle, &ov, &numBytesWritten, FALSE) };
::CloseHandle(ov.hEvent);
bool const result{
waitResult == WAIT_OBJECT_0 &&
ovResult == TRUE &&
numBytesWritten == numBytesToWrite };
if(result)
{
return COMMS_ERROR::SUCCESS;
}
if(waitResult == WAIT_TIMEOUT)
{
::CancelIo(usbFileHandle);
return COMMS_ERROR::TIMED_OUT;
}
return COMMS_ERROR::FAIL;
}
}
| 26.544118 | 181 | 0.710065 | [
"vector"
] |
4eba726779886ca37136c45088ba2c50bc4bd4c3 | 6,025 | cc | C++ | src/color.cc | NuriYuri/node-sfml | 75ae1439d8fe946393a78e87b3d7ea8c7eb8c750 | [
"MIT"
] | 48 | 2021-11-10T15:48:55.000Z | 2022-03-25T08:34:43.000Z | src/color.cc | NuriYuri/node-sfml | 75ae1439d8fe946393a78e87b3d7ea8c7eb8c750 | [
"MIT"
] | 7 | 2022-01-12T18:15:24.000Z | 2022-03-31T04:12:02.000Z | src/color.cc | NuriYuri/node-sfml | 75ae1439d8fe946393a78e87b3d7ea8c7eb8c750 | [
"MIT"
] | 4 | 2021-11-11T01:41:43.000Z | 2022-03-22T17:44:21.000Z | #include "color.h"
namespace node_sfml {
namespace color {
using v8::EscapableHandleScope;
using v8::Function;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::MaybeLocal;
using v8::Object;
using v8::String;
using v8::Value;
Nan::Persistent<Function> constructor;
Nan::Persistent<Function> real_constructor;
MaybeLocal<Object> Color::NewRealColorInstance(Isolate* isolate,
sf::Uint32 val) {
EscapableHandleScope scope(isolate);
Local<Object> ret;
if (real_constructor.IsEmpty()) {
Nan::ThrowError("Color constructor has not been initialized yet.");
return scope.Escape(ret);
}
Local<Function> func = real_constructor.Get(isolate);
Local<Value> argv[] = {Nan::New(val)};
Nan::TryCatch try_catch;
MaybeLocal<Value> maybe = Nan::Call(func, func, 1, argv);
if (try_catch.HasCaught()) {
try_catch.ReThrow();
Local<Object> empty;
return scope.Escape(empty);
}
return scope.Escape(maybe.ToLocalChecked().As<Object>());
}
NAN_METHOD(SetRealColorConstructor) {
Local<Function> func = Nan::To<Function>(info[0]).ToLocalChecked();
real_constructor.Reset(func);
}
NAN_MODULE_INIT(Color::Init) {
Local<String> name = Nan::New("Color").ToLocalChecked();
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
Nan::SetPrototypeMethod(tpl, "toInteger", ToInteger);
#define V(name, lowercase) \
tpl->PrototypeTemplate()->SetAccessorProperty( \
Nan::New(#lowercase).ToLocalChecked(), \
Nan::New<FunctionTemplate>(name##Getter), \
Nan::New<FunctionTemplate>(name##Setter), \
v8::PropertyAttribute::DontDelete);
RGBAProperties(V);
#undef V
tpl->SetClassName(name);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Local<Function> func = Nan::GetFunction(tpl).ToLocalChecked();
constructor.Reset(func);
Nan::Set(target, name, func);
Nan::Set(target,
Nan::New("setRealColorConstructor").ToLocalChecked(),
Nan::GetFunction(Nan::New<FunctionTemplate>(SetRealColorConstructor))
.ToLocalChecked());
}
NAN_METHOD(Color::New) {
Color* color = nullptr;
Local<v8::Uint32> color_val;
Local<v8::Uint32> red;
Local<v8::Uint32> green;
Local<v8::Uint32> blue;
Local<v8::Uint32> alpha;
switch (info.Length()) {
case 0:
color = new Color();
break;
case 4: {
alpha = info[3].As<v8::Uint32>();
// fallthrough
}
case 3: {
red = info[0].As<v8::Uint32>();
green = info[1].As<v8::Uint32>();
blue = info[2].As<v8::Uint32>();
break;
}
case 1: {
color_val = info[0].As<v8::Uint32>();
break;
}
default: {
Nan::ThrowError("Invalid arguments count.");
return;
}
}
if (color == nullptr) {
if (!color_val.IsEmpty()) {
sf::Uint32 val = Nan::To<sf::Uint32>(color_val).FromJust();
if (val > 0xffffffff) {
Nan::ThrowRangeError("Color value should between 0 and 0xffffffff.");
return;
}
color = new Color(val);
} else {
sf::Uint32 a =
alpha.IsEmpty() ? 255 : Nan::To<sf::Uint32>(alpha).FromJust();
sf::Uint32 r = Nan::To<sf::Uint32>(red).FromJust();
sf::Uint32 g = Nan::To<sf::Uint32>(green).FromJust();
sf::Uint32 b = Nan::To<sf::Uint32>(blue).FromJust();
if (a > 0xff || r > 0xff || g > 0xff || b > 0xff) {
Nan::ThrowRangeError(
"Each value of R / G / B / A should between 0 and 0xff.");
return;
}
color = new Color(r, g, b, a);
}
}
color->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(Color::ToInteger) {
Color* color = Nan::ObjectWrap::Unwrap<Color>(info.Holder());
info.GetReturnValue().Set(color->_color->toInteger());
}
#define V(name, lowercase) \
NAN_METHOD(Color::name##Getter) { \
Color* color = Nan::ObjectWrap::Unwrap<Color>(info.This()); \
info.GetReturnValue().Set(color->_color->lowercase); \
} \
\
NAN_METHOD(Color::name##Setter) { \
if (!info[0]->IsUint32()) { \
Nan::ThrowTypeError("`" #lowercase "` should be an unsigned integer."); \
return; \
} \
\
sf::Uint32 val = info[0].As<v8::Uint32>()->Value(); \
if (val < 0 || val > 0xff) { \
Nan::ThrowRangeError("`" #lowercase "` should between 0 and 0xff."); \
return; \
} \
\
Color* color = Nan::ObjectWrap::Unwrap<Color>(info.This()); \
color->_color->lowercase = val; \
}
RGBAProperties(V);
#undef V
Color::Color() : _color(new sf::Color()) {}
Color::Color(sf::Uint32 color) : _color(new sf::Color(color)) {}
Color::Color(sf::Uint8 red, sf::Uint8 green, sf::Uint8 blue, sf::Uint8 alpha)
: _color(new sf::Color(red, green, blue, alpha)) {}
Color::~Color() {
if (_color != nullptr) {
delete _color;
_color = nullptr;
}
}
} // namespace color
} // namespace node_sfml
| 31.710526 | 80 | 0.502407 | [
"object"
] |
4ec3b4ddd78d6c8bcf312343fce238e77fa1c00a | 2,735 | cpp | C++ | cpp/79.word-search.cpp | vermouth1992/Leetcode | 0d7dda52b12f9e01d88fc279243742cd8b4bcfd1 | [
"MIT"
] | null | null | null | cpp/79.word-search.cpp | vermouth1992/Leetcode | 0d7dda52b12f9e01d88fc279243742cd8b4bcfd1 | [
"MIT"
] | null | null | null | cpp/79.word-search.cpp | vermouth1992/Leetcode | 0d7dda52b12f9e01d88fc279243742cd8b4bcfd1 | [
"MIT"
] | null | null | null | /*
* @lc app=leetcode id=79 lang=cpp
*
* [79] Word Search
*
* https://leetcode.com/problems/word-search/description/
*
* algorithms
* Medium (37.55%)
* Total Accepted: 705.3K
* Total Submissions: 1.9M
* Testcase Example: '[["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]]\n"ABCCED"'
*
* Given an m x n grid of characters board and a string word, return true if
* word exists in the grid.
*
* The word can be constructed from letters of sequentially adjacent cells,
* where adjacent cells are horizontally or vertically neighboring. The same
* letter cell may not be used more than once.
*
*
* Example 1:
*
*
* Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word
* = "ABCCED"
* Output: true
*
*
* Example 2:
*
*
* Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word
* = "SEE"
* Output: true
*
*
* Example 3:
*
*
* Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word
* = "ABCB"
* Output: false
*
*
*
* Constraints:
*
*
* m == board.length
* n = board[i].length
* 1 <= m, n <= 6
* 1 <= word.length <= 15
* board and word consists of only lowercase and uppercase English letters.
*
*
*
* Follow up: Could you use search pruning to make your solution faster with a
* larger board?
*
*/
#include "common.hpp"
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
// find all the possible starting position
vector<vector<bool>> visited(board.size(), vector<bool>(board[0].size(), false));
for (int i = 0; i < board.size(); i++)
{
for (int j = 0; j < board[0].size(); j++)
{
if (this->helper(board, 0, i, j, visited, word)) return true;
}
}
return false;
}
private:
bool helper(vector<vector<char>>& board, int curr_index, int x, int y, vector<vector<bool>> &visited, string &word) {
// finishes
if (curr_index >= word.size()) return true;
// out of bound
if (x < 0 || x > board.size() - 1 || y < 0 || y > board[0].size() - 1) return false;
// visited or not equal
if (visited[x][y] || word[curr_index] != board[x][y]) return false;
visited[x][y] = true;
if (this->helper(board, curr_index + 1, x - 1, y, visited, word)) return true;
if (this->helper(board, curr_index + 1, x + 1, y, visited, word)) return true;
if (this->helper(board, curr_index + 1, x, y - 1, visited, word)) return true;
if (this->helper(board, curr_index + 1, x, y + 1, visited, word)) return true;
visited[x][y] = false;
return false;
}
};
| 27.35 | 121 | 0.541499 | [
"vector"
] |
4ec709f2f37caa4599530b9343b1905b4da6c8b0 | 336 | cc | C++ | adhoc_tests/as_foo.cc | rolandmas/TooN | 14dde295b89c9afc19e0e54ce1aaafc1193658d6 | [
"BSD-2-Clause"
] | 97 | 2015-01-27T10:49:30.000Z | 2022-03-21T05:58:38.000Z | 3rdparty.old/TooN/test/as_foo.cc | Pandinosaurus/PTAM-opencv | 1281564b9737dcc29ccacfbf7dc88a85916f7cc6 | [
"Intel",
"X11"
] | 7 | 2015-07-31T08:52:39.000Z | 2017-01-20T11:16:40.000Z | 3rdparty.old/TooN/test/as_foo.cc | Pandinosaurus/PTAM-opencv | 1281564b9737dcc29ccacfbf7dc88a85916f7cc6 | [
"Intel",
"X11"
] | 49 | 2015-05-06T18:13:38.000Z | 2022-02-05T08:06:27.000Z | #include <TooN/TooN.h>
using namespace TooN;
using namespace std;
int main()
{
Vector<3> v = makeVector(1, 2, 3);
cout << v.as_row() << endl;
cout << v.as_col() << endl;
cout << v.as_slice() << endl;
Vector<> u = makeVector(1, 2, 3);
cout << u.as_row() << endl;
cout << u.as_col() << endl;
cout << v.as_slice() << endl;
}
| 16 | 35 | 0.574405 | [
"vector"
] |
4df055d6994dd855c7ba7481d1a29beeb665eed9 | 12,660 | cpp | C++ | src/baxter_collaboration/baxter_collaboration/src/modular_furniture/tool_picker.cpp | UCRoboticsLab/BaxterTictactoe | 34e4761467af3dc7c9ad65726360e0d1f1923c51 | [
"Apache-2.0"
] | 1 | 2017-12-22T20:32:04.000Z | 2017-12-22T20:32:04.000Z | src/baxter_collaboration/baxter_collaboration/src/modular_furniture/tool_picker.cpp | u3099811/BaxterTictacToe | 967ab0ea8496ca4ce54db41b20c05de68cfe1bb9 | [
"Apache-2.0"
] | 2 | 2017-08-16T00:18:52.000Z | 2017-08-16T04:30:05.000Z | src/baxter_collaboration/baxter_collaboration/src/modular_furniture/tool_picker.cpp | u3099811/BaxterTictacToe | 967ab0ea8496ca4ce54db41b20c05de68cfe1bb9 | [
"Apache-2.0"
] | null | null | null | #include "tool_picker.h"
using namespace std;
using namespace baxter_core_msgs;
#define VERTICAL_ORI_R2 0.1, 1.0, 0.0, 0.0
ToolPicker::ToolPicker(std::string _name, std::string _limb, bool _no_robot) :
HoldCtrl(_name,_limb, _no_robot), CartesianEstimatorClient(_name, _limb),
elap_time(0)
{
setHomeConfiguration();
setState(START);
insertAction(ACTION_GET, static_cast<f_action>(&ToolPicker::getObject));
insertAction(ACTION_PASS, static_cast<f_action>(&ToolPicker::passObject));
insertAction(ACTION_GET_PASS, static_cast<f_action>(&ToolPicker::getPassObject));
insertAction(ACTION_CLEANUP, static_cast<f_action>(&ToolPicker::cleanUpObject));
removeAction(ACTION_HOLD);
insertAction(std::string(ACTION_HOLD) + "_leg", static_cast<f_action>(&ToolPicker::holdObject));
insertAction(std::string(ACTION_HOLD) + "_top", static_cast<f_action>(&ToolPicker::holdObject));
printActionDB();
if (_no_robot) return;
// reduceSquish();
if (!callAction(ACTION_HOME)) setState(ERROR);
}
bool ToolPicker::getObject()
{
if (!homePoseStrict()) return false;
ros::Duration(0.05).sleep();
if (getObjectIDs().size() > 1)
{
setSubState(CHECK_OBJ_IDS);
int id = chooseObjectID(getObjectIDs());
if (id == -1) return false;
setObjectID(id);
ROS_INFO("[%s] Chosen object with ID %i", getLimb().c_str(),
getObjectID());
}
if (!pickUpObject()) return false;
if (!gripObject()) return false;
if (!moveArm("up", 0.3)) return false;
// if (!hoverAboveTable(Z_LOW)) return false;
return true;
}
bool ToolPicker::passObject()
{
if (getPrevAction() != ACTION_GET) return false;
if (CartesianEstimatorClient::getObjectName() == "screwdriver")
{
if (!goToPose(0.85, -0.26, 0.27,
HORIZONTAL_ORI_R)) return false;
if (!waitForUserFb()) return false;
if (!releaseObject()) return false;
}
else if (CartesianEstimatorClient::getObjectName() == "screws_box" ||
CartesianEstimatorClient::getObjectName() == "brackets_box")
{
if (!hoverAboveTable(Z_LOW)) return false;
if (CartesianEstimatorClient::getObjectName() == "brackets_box")
{
if (!goToPose(0.63, -0.10, -0.14, VERTICAL_ORI_R2)) return false;
}
else
{
if (!goToPose(0.63, -0.30, -0.14, VERTICAL_ORI_R2)) return false;
}
ros::Duration(0.25).sleep();
if (!releaseObject()) return false;
if (!hoverAboveTable(Z_LOW)) return false;
}
if (!homePoseStrict()) return false;
return true;
}
bool ToolPicker::getPassObject()
{
if (!getObject()) return false;
setPrevAction(ACTION_GET);
if (!passObject()) return false;
return true;
}
bool ToolPicker::cleanUpObject()
{
if (!goToPose(0.65, -0.25, 0.25, VERTICAL_ORI_R)) return false;
ros::Duration(0.05).sleep();
if (getObjectIDs().size() > 1)
{
setSubState(CHECK_OBJ_IDS);
int id = chooseObjectID(getObjectIDs());
if (id == -1) return false;
setObjectID(id);
ROS_INFO("[%s] Chosen object with ID %i", getLimb().c_str(),
getObjectID());
}
if (!waitForCartEstObjFound())
{
setSubState(NO_OBJ);
return false;
}
if (!pickUpObject()) return false;
if (!gripObject()) return false;
if (!moveArm("up", 0.3)) return false;
if (!homePoseStrict()) return false;
if (CartesianEstimatorClient::getObjectName() == "screwdriver")
{
if (!goToPose( 0.20, -0.85, -0.30, POOL_ORI_R)) return false;
}
else if (CartesianEstimatorClient::getObjectName() == "brackets_box")
{
if (!goToPose( 0.00, -0.85, -0.25, POOL_ORI_R)) return false;
}
else if (CartesianEstimatorClient::getObjectName() == "screws_box")
{
if (!goToPose(-0.15, -0.85, -0.25, POOL_ORI_R)) return false;
}
ros::Duration(0.25).sleep();
if (!releaseObject()) return false;
if (!homePoseStrict()) return false;
return true;
}
bool ToolPicker::pickUpObject()
{
ROS_INFO("[%s] Start Picking up object %s..", getLimb().c_str(),
CartesianEstimatorClient::getObjectName().c_str());
if (!isIRok())
{
ROS_ERROR("No callback from the IR sensor! Stopping.");
setSubState(NO_IR_SENSOR);
return false;
}
if (!waitForCartEstData())
{
setSubState(NO_OBJ);
return false;
}
double offs_x = 0.0;
double offs_y = 0.0;
if (!computeOffsets(offs_x, offs_y)) return false;
double x = getObjectPos().x + offs_x;
double y = getObjectPos().y + offs_y;
double z = getPos().z;
geometry_msgs::Quaternion q;
if (!computeOrientation(q)) return false;
ROS_INFO("Going to: %g %g %g", x, y, z);
if (!goToPose(x, y, z, q.x, q.y, q.z, q.w, "loose"))
{
return false;
}
if (!waitForCartEstData())
{
setSubState(NO_OBJ);
return false;
}
ros::Time start_time = ros::Time::now();
double z_start = getPos().z;
int cnt_ik_fail = 0;
ros::Rate r(THREAD_FREQ);
while(RobotInterface::ok())
{
double new_elap_time = (ros::Time::now() - start_time).toSec();
x = getObjectPos().x + offs_x;
y = getObjectPos().y + offs_y;
z = z_start - ARM_SPEED * new_elap_time / 1.3;
ROS_DEBUG("Time %g Going to: %g %g %g Position: %g %g %g", new_elap_time, x, y, z,
getPos().x, getPos().y, getPos().z);
if (goToPoseNoCheck(x,y,z,q.x, q.y, q.z, q.w))
{
cnt_ik_fail = 0;
if (new_elap_time - elap_time > 0.02)
{
ROS_WARN("\t\t\t\t\tTime elapsed: %g", new_elap_time - elap_time);
}
elap_time = new_elap_time;
if (determineContactCondition())
{
return true;
}
r.sleep();
}
else cnt_ik_fail++;
if (cnt_ik_fail == 10) return false;
}
return false;
}
bool ToolPicker::determineContactCondition()
{
if (hasCollidedIR("strict") || hasCollidedCD())
{
if (hasCollidedCD())
{
moveArm("up", 0.002);
}
ROS_INFO("Collision!");
return true;
}
else if (CartesianEstimatorClient::getObjectName() != "screwdriver")
{
if (getAction() == ACTION_CLEANUP)
{
if (getPos().z < -0.17)
{
ROS_INFO("Object reached!");
return true;
}
}
else if (getAction() == ACTION_GET ||
getAction() == ACTION_GET_PASS)
{
if (getPos().z < -0.28)
{
ROS_INFO("Object reached!");
return true;
}
}
}
return false;
}
bool ToolPicker::computeOffsets(double &_x_offs, double &_y_offs)
{
if (getAction() == ACTION_GET || getAction() == ACTION_GET_PASS)
{
if (CartesianEstimatorClient::getObjectName() == "screwdriver")
{
_x_offs = +0.010;
// _y_offs = +0.017;
}
else if (CartesianEstimatorClient::getObjectName() == "screws_box" ||
CartesianEstimatorClient::getObjectName() == "brackets_box")
{
_x_offs = +0.06;
}
}
else if (getAction() == ACTION_CLEANUP)
{
if (CartesianEstimatorClient::getObjectName() == "screwdriver")
{
// _x_offs = -0.020;
_y_offs = -0.010;
}
else if (CartesianEstimatorClient::getObjectName() == "screws_box" ||
CartesianEstimatorClient::getObjectName() == "brackets_box")
{
_x_offs = +0.020;
_y_offs = -0.058;
}
}
else
{
ROS_ERROR("State is neither ACTION_GET, ACTION_GET_PASS or ACTION_CLEANUP!");
return false;
}
return true;
}
bool ToolPicker::computeOrientation(geometry_msgs::Quaternion &_q)
{
if (getAction() == ACTION_GET || getAction() == ACTION_GET_PASS)
{
quaternionFromDoubles(_q, POOL_ORI_R);
}
else if (getAction() == ACTION_CLEANUP)
{
quaternionFromDoubles(_q, VERTICAL_ORI_R);
}
else
{
ROS_ERROR("State is neither ACTION_GET, ACTION_GET_PASS or ACTION_CLEANUP!");
return false;
}
return true;
}
int ToolPicker::chooseObjectID(std::vector<int> _objs)
{
if (getSubState() != CHECK_OBJ_IDS)
{
return ArmCtrl::chooseObjectID(_objs);
}
ROS_DEBUG("[%s] Choosing object IDs", getLimb().c_str());
int res = -1;
if (!waitForCartEstOK())
{
setSubState(NO_OBJ);
return res;
}
if (!waitForCartEstObjsFound())
{
setSubState(NO_OBJ);
return res;
}
std::vector<string> objs_str;
for (size_t i = 0; i < _objs.size(); ++i)
{
objs_str.push_back(getObjectNameFromDB(_objs[i]));
}
std::vector<string> av_objects = getAvailableObjects(objs_str);
if (av_objects.size() == 0) return res;
std::srand(std::time(0)); //use current time as seed
string res_str = av_objects[rand() % av_objects.size()];
res = getObjectIDFromDB(res_str);
return res;
}
void ToolPicker::reduceSquish()
{
XmlRpc::XmlRpcValue squish_params;
// store the initial squish thresholds from the parameter server
_n.getParam("/collision/"+getLimb()+"/baxter/squish_thresholds", squish_params);
ROS_ASSERT_MSG(squish_params.getType()==XmlRpc::XmlRpcValue::TypeArray,
"[%s] Squish params is not an array! Type is %i",
getLimb().c_str(), squish_params.getType());
for (int i = 0; i < squish_params.size(); ++i)
{
// store the initial squish thresholds for reset later
squish_thresholds.push_back(squish_params[i]);
}
// adjust the squish thresholds for better tool picking
squish_params[3] = 0.5 * static_cast<double>(squish_params[3]);
squish_params[4] = 0.5 * static_cast<double>(squish_params[4]);
squish_params[5] = 0.5 * static_cast<double>(squish_params[5]);
ROS_INFO("[%s] Reduced squish thresholds for joint 3, 4 and 5 to %g. %g and %g .",
getLimb().c_str(), static_cast<double>(squish_params[3]),
static_cast<double>(squish_params[5]),
static_cast<double>(squish_params[5]));
// set the squish thresholds in the parameter server to the new values
_n.setParam("/collision/"+getLimb()+"/baxter/squish_thresholds", squish_params);
}
void ToolPicker::resetSquish()
{
XmlRpc::XmlRpcValue squish_params;
for (std::vector<int>::size_type i = 0; i != squish_thresholds.size(); i++)
{
// rewrite the squish parameters from the initial squish thresholds stored in reduceSquish()
squish_params[i] = squish_thresholds[i];
}
ROS_INFO("[%s] Squish thresholds for joint 3, 4 and 5 set back to %g. %g and %g .",
getLimb().c_str(), static_cast<double>(squish_params[3]),
static_cast<double>(squish_params[5]),
static_cast<double>(squish_params[5]));
// reset squish thresholds in the parameter server to the new values
_n.setParam("/collision/"+getLimb()+"/baxter/squish_thresholds", squish_params);
}
bool ToolPicker::goHoldPose(double height)
{
ROS_INFO("[%s] Going to %s position..", getLimb().c_str(), getAction().c_str());
if (getAction() == std::string(ACTION_HOLD) + "_top")
{
return goToPose(0.72, -0.31, 0.032, 0.54, 0.75, 0.29,0.22);
}
return goToPose(0.80, -0.4, height, HORIZONTAL_ORI_R);
}
void ToolPicker::setHomeConfiguration()
{
ArmCtrl::setHomeConfiguration("pool");
}
void ToolPicker::setObjectID(int _obj)
{
ArmCtrl::setObjectID(_obj);
CartesianEstimatorClient::setObjectName(ArmCtrl::getObjectNameFromDB(_obj));
}
ToolPicker::~ToolPicker()
{
// resetSquish();
}
| 28.90411 | 100 | 0.565798 | [
"object",
"vector"
] |
4df3c29e3e8a00b90fee541b3b34228632449961 | 6,735 | cpp | C++ | src/gausskernel/cbb/utils/debug/segment_test.cpp | Yanci0/openGauss-server | b2ff10be1367c77f2fda396d6c12ffa3c25874c7 | [
"MulanPSL-1.0"
] | 360 | 2020-06-30T14:47:34.000Z | 2022-03-31T15:21:53.000Z | src/gausskernel/cbb/utils/debug/segment_test.cpp | Yanci0/openGauss-server | b2ff10be1367c77f2fda396d6c12ffa3c25874c7 | [
"MulanPSL-1.0"
] | 4 | 2020-06-30T15:09:16.000Z | 2020-07-14T06:20:03.000Z | src/gausskernel/cbb/utils/debug/segment_test.cpp | futurewei-cloud/chogori-opengauss | f43410e1643c887819e718d9baceb9e853ad9574 | [
"MulanPSL-1.0"
] | 133 | 2020-06-30T14:47:36.000Z | 2022-03-25T15:29:00.000Z | /*
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* -------------------------------------------------------------------------
*
* segment_test.cpp
* Routines for segment test framework.
*
* IDENTIFICATION
* src/gausskernel/cbb/utils/debug/segment_test.cpp
*
* -------------------------------------------------------------------------
*/
#include "postgres.h"
#include "knl/knl_variable.h"
#include "executor/exec/execStream.h"
#include "miscadmin.h"
#include "utils/builtins.h"
#include "utils/segment_test.h"
#include "distributelayer/streamProducer.h"
#include "commands/vacuum.h"
#include "access/transam.h"
#include "threadpool/threadpool.h"
#ifdef ENABLE_SEGMENT_TEST
#define PARAM_NOTCONTAIN_ELEVEL 2
#define PARAM_CONTAIN_ELEVEL 3
#define POS_ELEVEL 2
/**
* @Description: transform elevel from string to int value.
* @in elevelstr - input str which indicates level
* @return - no return
*/
static int get_test_elevel(const char* elevelstr)
{
if (pg_strcasecmp(elevelstr, "ERROR") == 0)
return ERROR;
else if (pg_strcasecmp(elevelstr, "FATAL") == 0)
return FATAL;
else if (pg_strcasecmp(elevelstr, "PANIC") == 0)
return PANIC;
else if (pg_strcasecmp(elevelstr, "DEFAULT") == 0)
return PANIC;
else
return -1; // this means doesn't match
}
/**
* @Description: GUC check_hook for distribute_test_param.
* @in newval - raw guc define input string
* @in extra - get the guc defined balue
* @in source - no use in current guc distribute_test_param
* @return - guc input string valid or not
*/
bool check_segment_test_param(char** newval, void** extra, GucSource source)
{
char* rawstring = NULL;
List* elemlist = NIL;
SegmentTestParam* myextra = NULL;
int param_num = 0;
/* Need a modifiable copy of string */
rawstring = pstrdup(*newval);
/* Parse string into list of identifiers */
if (!SplitIdentifierString(rawstring, ',', &elemlist)) {
/* syntax error in list */
GUC_check_errdetail("List syntax is invalid.");
pfree_ext(rawstring);
list_free_ext(elemlist);
return false;
}
/* Check the number of test param */
param_num = list_length(elemlist);
if (!(param_num == PARAM_NOTCONTAIN_ELEVEL || param_num == PARAM_CONTAIN_ELEVEL)) {
/* syntax error in list */
GUC_check_errdetail("Number of test param is invalid.");
pfree_ext(rawstring);
list_free_ext(elemlist);
return false;
}
/* Check the elevel string */
if (get_test_elevel((char*)list_nth(elemlist, PARAM_NOTCONTAIN_ELEVEL)) == -1) {
/* syntax error in list */
GUC_check_errdetail("String of elevel is invalid.");
pfree_ext(rawstring);
list_free_ext(elemlist);
return false;
}
/* Set up the "extra" struct actually used by assign_distribute_test_param */
if (get_segment_test_param() == NULL) {
myextra = (SegmentTestParam*)palloc0(sizeof(SegmentTestParam));
if (myextra == NULL) {
goto error_ret;
}
char* name = (char*)list_nth(elemlist, 1);
int rc = strcpy_s(myextra->test_stub_name, MAX_NAME_STR_LEN - 1, name);
securec_check(rc, "\0", "\0");
myextra->guc_probability = pg_strtoint32((char*)list_nth(elemlist, 0));
myextra->elevel = get_test_elevel((char*)list_nth(elemlist, POS_ELEVEL));
*extra = (void*)myextra;
goto success_ret;
} else {
if (pg_strcasecmp("default", (char*)list_nth(elemlist, 1)) == 0 ||
pg_strcasecmp("", (char*)list_nth(elemlist, 1)) == 0) {
*extra = (void*)get_segment_test_param();
goto success_ret;
} else {
char* name = (char*)list_nth(elemlist, 1);
int rc = strcpy_s(get_segment_test_param()->test_stub_name, MAX_NAME_STR_LEN - 1, name);
securec_check(rc, "\0", "\0");
get_segment_test_param()->guc_probability = pg_strtoint32((char*)list_nth(elemlist, 0));
get_segment_test_param()->elevel = get_test_elevel((char*)list_nth(elemlist, POS_ELEVEL));
*extra = (void*)get_segment_test_param();
goto success_ret;
}
}
success_ret:
pfree_ext(rawstring);
list_free_ext(elemlist);
return true;
error_ret:
pfree_ext(rawstring);
list_free_ext(elemlist);
return false;
}
/**
* @Description: check whether the test stub can be activated.
* @in name - the white-box single-point fault fire tag, is a string defined in GUC
* @in function - callback function
* @return - no return
*/
bool segment_test_stub_activator(const char* name)
{
if (g_instance.segment_test_param_instance == NULL) {
return false;
}
if ((g_instance.segment_test_param_instance->guc_probability != 0) &&
((u_sess->stream_cxt.producer_obj == NULL) || (g_instance.segment_test_param_instance->guc_probability !=
u_sess->stream_cxt.producer_obj->getNodeGroupIdx() + 1))) {
return false;
}
if (t_thrd.proc_cxt.proc_exit_inprogress)
return false;
errno_t errorno = EOK;
char test_name[1024];
errorno = memset_s(test_name, sizeof(test_name), '\0', sizeof(test_name));
securec_check(errorno, "", "");
errorno = snprintf_s(
test_name, sizeof(test_name), sizeof(test_name) - 1, "%s_%s", name, g_instance.attr.attr_common.PGXCNodeName);
securec_check_ss(errorno, "\0", "\0");
if (pg_strcasecmp(name, g_instance.segment_test_param_instance->test_stub_name) == 0 ||
pg_strcasecmp(test_name, g_instance.segment_test_param_instance->test_stub_name) == 0) {
return true;
}
return false;
}
/**
* @Description: assign_segment_test_param: GUC assign_hook for distribute_test_param
* @in newval - raw guc define input string
* @in extra - assign value for macro u_sess->utils_cxt.segment_test_param
* @return - guc input string valid or not
*/
void assign_segment_test_param(const char* newval, void* extra)
{
g_instance.segment_test_param_instance = (SegmentTestParam*)extra;
}
SegmentTestParam* get_segment_test_param()
{
return (SegmentTestParam*)g_instance.segment_test_param_instance;
}
#endif
| 33.844221 | 118 | 0.654788 | [
"transform"
] |
4df58d48d0e4fdedc59040143127a0d934150a6a | 3,931 | cpp | C++ | rend_sdl/Material.cpp | eezstreet/Rapture | 1022f1013d7a7a3a84ea3ba56518420daf4733fc | [
"ISC"
] | 2 | 2017-10-25T03:22:34.000Z | 2020-04-02T16:33:40.000Z | rend_sdl/Material.cpp | eezstreet/Rapture | 1022f1013d7a7a3a84ea3ba56518420daf4733fc | [
"ISC"
] | 12 | 2016-07-03T21:08:25.000Z | 2016-07-30T06:17:26.000Z | rend_sdl/Material.cpp | eezstreet/Rapture | 1022f1013d7a7a3a84ea3ba56518420daf4733fc | [
"ISC"
] | 3 | 2016-03-02T06:56:42.000Z | 2018-04-13T14:37:06.000Z | #include "tr_local.h"
unordered_map<string, Material*> Material::umMaterials;
/* Class methods */
Material::Material(const char* szURI) : bValid(false) {
Resource* pRes = trap->ResourceSyncURI(szURI);
if (pRes == nullptr) {
trap->Print(PRIORITY_WARNING, "Couldn't find material resource: %s\n", szURI);
return;
}
AssetComponent* comp = trap->ResourceComponent(pRes);
if (comp == nullptr || comp->meta.componentType != Asset_Material || comp->data.materialComponent == nullptr) {
trap->Print(PRIORITY_WARNING, "Resource %s was attempted to load as material, but isn't.\n", szURI);
return;
}
ComponentMaterial* mat = comp->data.materialComponent;
this->matHeader = mat->head;
if (matHeader.mapsPresent & (1 << Maptype_Diffuse)) {
diffuseTexture = new Texture(matHeader.width, matHeader.height, mat->diffusePixels);
}
if (matHeader.mapsPresent & (1 << Maptype_Depth)) {
depthTexture = new Texture(matHeader.depthWidth, matHeader.depthHeight, mat->depthPixels);
}
if (matHeader.mapsPresent & (1 << Maptype_Normal)) {
normalTexture = new Texture(matHeader.normalWidth, matHeader.normalHeight, mat->normalPixels);
}
bValid = true;
}
Material::~Material() {
if (diffuseTexture) {
delete diffuseTexture;
}
if (normalTexture) {
delete normalTexture;
}
if (depthTexture) {
delete depthTexture;
}
}
Material::Material(Material& other) {
matHeader = other.matHeader;
diffuseTexture = other.diffuseTexture;
normalTexture = other.normalTexture;
depthTexture = other.depthTexture;
bValid = other.bValid;
}
void Material::Draw(float xPct, float yPct, float wPct, float hPct) {
if (diffuseTexture) {
diffuseTexture->DrawImage(xPct, yPct, wPct, hPct);
}
}
void Material::DrawAspectCorrection(float xPct, float yPct, float wPct, float hPct) {
if (diffuseTexture) {
diffuseTexture->DrawImageAspectCorrection(xPct, yPct, wPct, hPct);
}
}
void Material::DrawClipped(float sxPct, float syPct, float swPct, float shPct, float ixPct, float iyPct, float iwPct, float ihPct) {
if (diffuseTexture) {
}
}
void Material::DrawAbs(int nX, int nY, int nW, int nH) {
if (diffuseTexture) {
diffuseTexture->DrawAbs(nX, nY, nW, nH);
}
}
void Material::DrawAbsClipped(int sX, int sY, int sW, int sH, int iX, int iY, int iW, int iH) {
if (diffuseTexture) {
diffuseTexture->DrawAbsClipped(sX, sY, sW, sH, iX, iY, iW, iH);
}
}
/* Static methods */
Material* Material::Register(const char* uri) {
string szURI = uri;
transform(szURI.begin(), szURI.end(), szURI.end(), ::tolower);
auto it = umMaterials.find(szURI);
if (it != umMaterials.end()) {
return it->second;
}
Material* newMat = new Material(uri);
if (!newMat->Valid()) {
delete newMat;
return nullptr;
}
umMaterials[szURI] = newMat;
return newMat;
}
void Material::DrawMaterial(Material* pMat, float xPct, float yPct, float wPct, float hPct) {
if (pMat == nullptr) {
return;
}
pMat->Draw(xPct, yPct, wPct, hPct);
}
void Material::DrawMaterialAspectCorrection(Material* pMat, float xPct, float yPct, float wPct, float hPct) {
if (pMat == nullptr) {
return;
}
pMat->DrawAspectCorrection(xPct, yPct, wPct, hPct);
}
void Material::DrawMaterialClipped(Material* pMat, float sxPct, float syPct, float swPct, float shPct, float ixPct, float iyPct, float iwPct, float ihPct) {
if (pMat == nullptr) {
return;
}
pMat->DrawClipped(sxPct, syPct, swPct, shPct, ixPct, iyPct, iwPct, ihPct);
}
void Material::DrawMaterialAbs(Material* pMat, int nX, int nY, int nW, int nH) {
if (pMat == nullptr) {
return;
}
pMat->DrawAbs(nX, nY, nW, nH);
}
void Material::DrawMaterialAbsClipped(Material* pMat, int sX, int sY, int sW, int sH, int iX, int iY, int iW, int iH) {
if (pMat == nullptr) {
return;
}
pMat->DrawAbsClipped(sX, sY, sW, sH, iX, iY, iW, iH);
}
void Material::KillAllMaterials() {
for (auto it = umMaterials.begin(); it != umMaterials.end(); ++it) {
delete it->second;
}
umMaterials.clear();
} | 27.683099 | 156 | 0.701094 | [
"transform"
] |
4df7cd5c51ed4891bcdab9725dc92e99a7527d4e | 3,887 | cpp | C++ | Hexeng2D/src/EventManager/EventManager.cpp | Ily3s/Hexeng2D | 9e81618fc27b45a347abadc6f60f896ab28cbe6b | [
"MIT"
] | null | null | null | Hexeng2D/src/EventManager/EventManager.cpp | Ily3s/Hexeng2D | 9e81618fc27b45a347abadc6f60f896ab28cbe6b | [
"MIT"
] | null | null | null | Hexeng2D/src/EventManager/EventManager.cpp | Ily3s/Hexeng2D | 9e81618fc27b45a347abadc6f60f896ab28cbe6b | [
"MIT"
] | null | null | null | #include <chrono>
#include "EventManager.hpp"
#include "../Scene.hpp"
#include "../Renderer/Renderer.hpp"
#include "GLFW/glfw3.h"
namespace Hexeng::EventManager
{
std::thread event_thread;
Vec2<double> mouse_position{ 0, 0 };
std::vector<Event*> global_events;
Event::Event(std::function<bool(void)> condition, std::function<void(void)> action, Range range, uint32_t pertick)
: condition(condition), action(action), pertick(pertick), range(range), clock(pertick - 1)
{
if (range == Range::GLOBAL)
global_events.push_back(this);
}
EventGate::EventGate(std::function<void(void)> evt, Range range_para, unsigned int pertick_para)
{
action = evt;
pertick = pertick_para;
condition = []() {return true; };
range = range_para;
if (range == Range::GLOBAL)
global_events.push_back(this);
}
RendererEvent::RendererEvent(std::function<bool(void)> condition_para, std::function<void(void)> action, Range range_para, unsigned int pertick_para)
: internal_action(action)
{
condition = condition_para;
range = range_para;
pertick = pertick_para;
action = [this]() {Renderer::pending_actions.push_back(internal_action); };
if (range == Range::GLOBAL)
global_events.push_back(this);
}
RendererEventGate::RendererEventGate(std::function<void(void)> evt, Range range_para, unsigned int pertick_para)
{
internal_action = evt;
pertick = pertick_para;
range = range_para;
condition = []() {return true; };
action = [this]() {Renderer::pending_actions.push_back(internal_action); };
if (range == Range::GLOBAL)
global_events.push_back(this);
}
Event::Event(Event&& other) noexcept
: condition(other.condition), action(other.action), pertick(other.pertick), range(other.range), clock(other.clock)
{
if (range == Range::GLOBAL)
{
auto it = std::find(global_events.begin(), global_events.end(), &other);
if (it != global_events.end())
global_events.erase(it);
global_events.push_back(this);
}
}
Event& Event::operator=(Event&& other) noexcept
{
condition = other.condition;
action = other.action;
pertick = other.pertick;
clock = other.clock;
if (range == Range::GLOBAL)
{
auto it = std::find(global_events.begin(), global_events.end(), this);
if (it != global_events.end())
global_events.erase(it);
}
if (other.range == Range::GLOBAL)
{
auto it = std::find(global_events.begin(), global_events.end(), &other);
if (it != global_events.end())
global_events.erase(it);
global_events.push_back(this);
}
range = other.range;
return *this;
}
void loop_impl();
bool allowed_to_loop = true;
void start_looping()
{
event_thread = std::thread(loop_impl);
}
void stop_looping()
{
allowed_to_loop = false;
event_thread.join();
}
uint64_t current_tick = 0;
void loop_impl()
{
while (allowed_to_loop)
{
auto start_point = std::chrono::high_resolution_clock::now();
HXG_GLFW(glfwGetCursorPos(window, &mouse_position.x, &mouse_position.y));
mouse_position.y = 0.5 * Settings::window_size.y - mouse_position.y;
mouse_position.x -= 0.5 * Settings::window_size.x;
mouse_position /= (double)Settings::window_size.y / 1080;
for (auto evt : global_events)
{
if (evt->clock > 0)
evt->clock--;
else if (evt->condition())
{
evt->action();
evt->clock = evt->pertick - 1;
}
}
for (auto evt : scenes[scene_id]->events)
{
if (evt->clock > 0)
evt->clock--;
else if (evt->condition())
{
evt->action();
evt->clock = evt->pertick - 1;
}
}
current_tick++;
auto end_point = std::chrono::high_resolution_clock::now();
std::chrono::duration<float> duration = end_point - start_point;
int duration_ms = static_cast<int>(duration.count() * 1000);
if (duration_ms < 10)
std::this_thread::sleep_for(std::chrono::milliseconds(10 - duration_ms));
}
}
} | 25.405229 | 150 | 0.674042 | [
"vector"
] |
4df984c9582f1cb21926f6736239b8549d03d7af | 11,989 | cpp | C++ | test/cpp/api/integration.cpp | Gamrix/pytorch | b5b158a6c6de94dfb983b447fa33fea062358844 | [
"Intel"
] | null | null | null | test/cpp/api/integration.cpp | Gamrix/pytorch | b5b158a6c6de94dfb983b447fa33fea062358844 | [
"Intel"
] | null | null | null | test/cpp/api/integration.cpp | Gamrix/pytorch | b5b158a6c6de94dfb983b447fa33fea062358844 | [
"Intel"
] | null | null | null | #include <gtest/gtest.h>
#include <torch/torch.h>
#include <test/cpp/api/support.h>
#include <cmath>
#include <cstdlib>
#include <random>
using namespace torch::nn;
using namespace torch::test;
const double kPi = 3.1415926535898;
class CartPole {
// Translated from openai/gym's cartpole.py
public:
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
double gravity = 9.8;
double masscart = 1.0;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
double masspole = 0.1;
double total_mass = (masspole + masscart);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
double length = 0.5; // actually half the pole's length;
double polemass_length = (masspole * length);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
double force_mag = 10.0;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
double tau = 0.02; // seconds between state updates;
// Angle at which to fail the episode
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
double theta_threshold_radians = 12 * 2 * kPi / 360;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
double x_threshold = 2.4;
int steps_beyond_done = -1;
torch::Tensor state;
double reward;
bool done;
int step_ = 0;
torch::Tensor getState() {
return state;
}
double getReward() {
return reward;
}
double isDone() {
return done;
}
void reset() {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
state = torch::empty({4}).uniform_(-0.05, 0.05);
steps_beyond_done = -1;
step_ = 0;
}
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init)
CartPole() {
reset();
}
void step(int action) {
auto x = state[0].item<float>();
auto x_dot = state[1].item<float>();
auto theta = state[2].item<float>();
auto theta_dot = state[3].item<float>();
auto force = (action == 1) ? force_mag : -force_mag;
auto costheta = std::cos(theta);
auto sintheta = std::sin(theta);
auto temp = (force + polemass_length * theta_dot * theta_dot * sintheta) /
total_mass;
auto thetaacc = (gravity * sintheta - costheta * temp) /
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
(length * (4.0 / 3.0 - masspole * costheta * costheta / total_mass));
auto xacc = temp - polemass_length * thetaacc * costheta / total_mass;
x = x + tau * x_dot;
x_dot = x_dot + tau * xacc;
theta = theta + tau * theta_dot;
theta_dot = theta_dot + tau * thetaacc;
state = torch::tensor({x, x_dot, theta, theta_dot});
done = x < -x_threshold || x > x_threshold ||
theta < -theta_threshold_radians || theta > theta_threshold_radians ||
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
step_ > 200;
if (!done) {
reward = 1.0;
} else if (steps_beyond_done == -1) {
// Pole just fell!
steps_beyond_done = 0;
reward = 0;
} else {
if (steps_beyond_done == 0) {
AT_ASSERT(false); // Can't do this
}
}
step_++;
}
};
template <typename M, typename F, typename O>
bool test_mnist(
size_t batch_size,
size_t number_of_epochs,
bool with_cuda,
M&& model,
F&& forward_op,
O&& optimizer) {
std::string mnist_path = "mnist";
if (const char* user_mnist_path = getenv("TORCH_CPP_TEST_MNIST_PATH")) {
mnist_path = user_mnist_path;
}
auto train_dataset =
torch::data::datasets::MNIST(
mnist_path, torch::data::datasets::MNIST::Mode::kTrain)
.map(torch::data::transforms::Stack<>());
auto data_loader =
torch::data::make_data_loader(std::move(train_dataset), batch_size);
torch::Device device(with_cuda ? torch::kCUDA : torch::kCPU);
model->to(device);
for (size_t epoch = 0; epoch < number_of_epochs; epoch++) {
// NOLINTNEXTLINE(performance-for-range-copy)
for (torch::data::Example<> batch : *data_loader) {
auto data = batch.data.to(device), targets = batch.target.to(device);
torch::Tensor prediction = forward_op(std::move(data));
// NOLINTNEXTLINE(performance-move-const-arg)
torch::Tensor loss = torch::nll_loss(prediction, std::move(targets));
AT_ASSERT(!torch::isnan(loss).any().item<int64_t>());
optimizer.zero_grad();
loss.backward();
optimizer.step();
}
}
torch::NoGradGuard guard;
torch::data::datasets::MNIST test_dataset(
mnist_path, torch::data::datasets::MNIST::Mode::kTest);
auto images = test_dataset.images().to(device),
targets = test_dataset.targets().to(device);
auto result = std::get<1>(forward_op(images).max(/*dim=*/1));
torch::Tensor correct = (result == targets).to(torch::kFloat32);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
return correct.sum().item<float>() > (test_dataset.size().value() * 0.8);
}
struct IntegrationTest : torch::test::SeedingFixture {};
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST_F(IntegrationTest, CartPole) {
torch::manual_seed(0);
auto model = std::make_shared<SimpleContainer>();
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto linear = model->add(Linear(4, 128), "linear");
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto policyHead = model->add(Linear(128, 2), "policy");
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto valueHead = model->add(Linear(128, 1), "action");
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto optimizer = torch::optim::Adam(model->parameters(), 1e-3);
std::vector<torch::Tensor> saved_log_probs;
std::vector<torch::Tensor> saved_values;
std::vector<float> rewards;
auto forward = [&](torch::Tensor inp) {
auto x = linear->forward(inp).clamp_min(0);
torch::Tensor actions = policyHead->forward(x);
torch::Tensor value = valueHead->forward(x);
return std::make_tuple(torch::softmax(actions, -1), value);
};
auto selectAction = [&](torch::Tensor state) {
// Only work on single state right now, change index to gather for batch
auto out = forward(state);
auto probs = torch::Tensor(std::get<0>(out));
auto value = torch::Tensor(std::get<1>(out));
auto action = probs.multinomial(1)[0].item<int32_t>();
// Compute the log prob of a multinomial distribution.
// This should probably be actually implemented in autogradpp...
auto p = probs / probs.sum(-1, true);
auto log_prob = p[action].log();
saved_log_probs.emplace_back(log_prob);
saved_values.push_back(value);
return action;
};
auto finishEpisode = [&] {
auto R = 0.;
// NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions)
for (int i = rewards.size() - 1; i >= 0; i--) {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
R = rewards[i] + 0.99 * R;
rewards[i] = R;
}
auto r_t = torch::from_blob(
rewards.data(), {static_cast<int64_t>(rewards.size())});
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
r_t = (r_t - r_t.mean()) / (r_t.std() + 1e-5);
std::vector<torch::Tensor> policy_loss;
std::vector<torch::Tensor> value_loss;
for (auto i = 0U; i < saved_log_probs.size(); i++) {
auto advantage = r_t[i] - saved_values[i].item<float>();
policy_loss.push_back(-advantage * saved_log_probs[i]);
value_loss.push_back(
torch::smooth_l1_loss(saved_values[i], torch::ones(1) * r_t[i]));
}
auto loss =
torch::stack(policy_loss).sum() + torch::stack(value_loss).sum();
optimizer.zero_grad();
loss.backward();
optimizer.step();
rewards.clear();
saved_log_probs.clear();
saved_values.clear();
};
auto env = CartPole();
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
double running_reward = 10.0;
for (size_t episode = 0;; episode++) {
env.reset();
auto state = env.getState();
int t = 0;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
for (; t < 10000; t++) {
auto action = selectAction(state);
env.step(action);
state = env.getState();
auto reward = env.getReward();
auto done = env.isDone();
rewards.push_back(reward);
if (done)
break;
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
running_reward = running_reward * 0.99 + t * 0.01;
finishEpisode();
/*
if (episode % 10 == 0) {
printf("Episode %i\tLast length: %5d\tAverage length: %.2f\n",
episode, t, running_reward);
}
*/
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
if (running_reward > 150) {
break;
}
ASSERT_LT(episode, 3000);
}
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST_F(IntegrationTest, MNIST_CUDA) {
torch::manual_seed(0);
auto model = std::make_shared<SimpleContainer>();
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto conv1 = model->add(Conv2d(1, 10, 5), "conv1");
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto conv2 = model->add(Conv2d(10, 20, 5), "conv2");
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto drop = Dropout(0.3);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto drop2d = Dropout2d(0.3);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto linear1 = model->add(Linear(320, 50), "linear1");
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto linear2 = model->add(Linear(50, 10), "linear2");
auto forward = [&](torch::Tensor x) {
x = torch::max_pool2d(conv1->forward(x), {2, 2}).relu();
x = conv2->forward(x);
x = drop2d->forward(x);
x = torch::max_pool2d(x, {2, 2}).relu();
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
x = x.view({-1, 320});
x = linear1->forward(x).clamp_min(0);
x = drop->forward(x);
x = linear2->forward(x);
x = torch::log_softmax(x, 1);
return x;
};
auto optimizer = torch::optim::SGD(
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
model->parameters(), torch::optim::SGDOptions(1e-2).momentum(0.5));
ASSERT_TRUE(test_mnist(
32, // batch_size
3, // number_of_epochs
true, // with_cuda
model,
forward,
optimizer));
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST_F(IntegrationTest, MNISTBatchNorm_CUDA) {
torch::manual_seed(0);
auto model = std::make_shared<SimpleContainer>();
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto conv1 = model->add(Conv2d(1, 10, 5), "conv1");
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto batchnorm2d = model->add(BatchNorm2d(10), "batchnorm2d");
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto conv2 = model->add(Conv2d(10, 20, 5), "conv2");
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto linear1 = model->add(Linear(320, 50), "linear1");
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto batchnorm1 = model->add(BatchNorm1d(50), "batchnorm1");
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto linear2 = model->add(Linear(50, 10), "linear2");
auto forward = [&](torch::Tensor x) {
x = torch::max_pool2d(conv1->forward(x), {2, 2}).relu();
x = batchnorm2d->forward(x);
x = conv2->forward(x);
x = torch::max_pool2d(x, {2, 2}).relu();
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
x = x.view({-1, 320});
x = linear1->forward(x).clamp_min(0);
x = batchnorm1->forward(x);
x = linear2->forward(x);
x = torch::log_softmax(x, 1);
return x;
};
auto optimizer = torch::optim::SGD(
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
model->parameters(), torch::optim::SGDOptions(1e-2).momentum(0.5));
ASSERT_TRUE(test_mnist(
32, // batch_size
3, // number_of_epochs
true, // with_cuda
model,
forward,
optimizer));
}
| 33.118785 | 93 | 0.659438 | [
"vector",
"model"
] |
4dfc31771da472b62a0d83fcb1e0999cf8d70859 | 39,698 | cpp | C++ | aby/src/abycore/sharing/yaoserversharing_pipelined.cpp | huxh10/SGDX | ed93ab5636e9ccc2a15f87572562641604a3cc2b | [
"Apache-2.0"
] | 2 | 2017-12-04T08:27:20.000Z | 2018-12-21T19:20:21.000Z | aby/src/abycore/sharing/yaoserversharing_pipelined.cpp | huxh10/SGDX | ed93ab5636e9ccc2a15f87572562641604a3cc2b | [
"Apache-2.0"
] | null | null | null | aby/src/abycore/sharing/yaoserversharing_pipelined.cpp | huxh10/SGDX | ed93ab5636e9ccc2a15f87572562641604a3cc2b | [
"Apache-2.0"
] | null | null | null | /**
\file YaoServerPipeSharing.cpp
\author michael.zohner@ec-spride.de
\copyright ABY - A Framework for Efficient Mixed-protocol Secure Two-party Computation
Copyright (C) 2015 Engineering Cryptographic Protocols Group, TU Darmstadt
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
\brief Yao Server Sharing class implementation.
*/
#include "yaoserversharing_pipelined.h"
void YaoServerPipeSharing::InitServer() {
//Allocate memory that is needed when generating the garbled tables
for(uint32_t i = 0; i < 2; i++) {
m_bLMaskBuf[i] = (BYTE*) malloc(sizeof(BYTE) * m_nSecParamBytes);
m_bRMaskBuf[i] = (BYTE*) malloc(sizeof(BYTE) * m_nSecParamBytes);
m_bOKeyBuf[i] = (BYTE*) malloc(sizeof(BYTE) * m_nSecParamBytes);
}
m_bLKeyBuf = (BYTE*) malloc(sizeof(BYTE) * m_nSecParamBytes);
m_bTmpBuf = (BYTE*) malloc(sizeof(BYTE) * AES_BYTES);
m_nGarbledTableCtr = 0;
m_nClientInputKexIdx = 0;
m_nClientInputKeyCtr = 0;
m_nOutputShareSndSize = 0;
m_nOutputShareRcvCtr = 0;
m_nPermBitCtr = 0;
InitNewLayer();
}
//Pre-set values for new layer
void YaoServerPipeSharing::InitNewLayer() {
m_nServerKeyCtr = 0;
m_nClientInBitCtr = 0;
m_nOutputShareSndSize = 0;
}
/* Send a new task for pre-computing the OTs in the setup phase */
void YaoServerPipeSharing::PrepareSetupPhase(ABYSetup* setup) {
//BYTE* buf;
//uint64_t gt_size;
uint32_t symbits = m_cCrypto->get_seclvl().symbits;
m_nANDGates = m_cBoolCircuit->GetNumANDGates();
//gt_size = ((uint64_t) m_nANDGates) * KEYS_PER_GATE_IN_TABLE * m_nSecParamBytes;
/* If no gates were built, return */
if (m_cBoolCircuit->GetMaxDepth() == 0)
return;
//m_vANDsOnLayers = m_cBoolCircuit->GetNonLinGatesOnLayers();
/* Preset the number of input bits for client and server */
m_nServerInputBits = m_cBoolCircuit->GetNumInputBitsForParty(SERVER);
m_nClientInputBits = m_cBoolCircuit->GetNumInputBitsForParty(CLIENT);
m_nConversionInputBits = m_cBoolCircuit->GetNumB2YGates() + m_cBoolCircuit->GetNumA2YGates();
//m_vPreSetInputGates = (input_gate_val_t*) calloc(m_nServerInputBits, sizeof(input_gate_val_t));
uint64_t maxands = 0;
for(uint32_t i = 0; i < m_vANDsOnLayers->max_depth; i++) {
if(maxands < m_vANDsOnLayers->num_on_layer[i])
maxands = (uint64_t) m_vANDsOnLayers->num_on_layer[i];
}
m_vGarbledCircuit.CreateBytes(maxands * KEYS_PER_GATE_IN_TABLE * m_nSecParamBytes);
//buf = (BYTE*) malloc(gt_size);
//m_vGarbledCircuit.AttachBuf(buf, gt_size);
m_vR.Create(symbits, m_cCrypto);
m_vR.SetBit(symbits - 1, 1);
#ifdef DEBUGYAOPIPESERVER
cout << "Secret key generated: ";
PrintKey(m_vR.GetArr());
cout << endl;
#endif
m_vROTMasks.resize(2);
m_vROTMasks[0].Create((m_nClientInputBits + m_nConversionInputBits) * symbits);
m_vROTMasks[1].Create((m_nClientInputBits + m_nConversionInputBits) * symbits);
CreateRandomWireKeys(m_vServerInputKeys, m_nServerInputBits + m_cBoolCircuit->GetNumA2YGates());
CreateRandomWireKeys(m_vClientInputKeys, m_nClientInputBits + m_nConversionInputBits);
//CreateRandomWireKeys(m_vConversionInputKeys, m_nConversionInputBits);
#ifdef DEBUGYAOPIPESERVER
cout << "Server input keys: ";
m_vServerInputKeys.PrintHex();
cout << "Client input keys: ";
m_vClientInputKeys.PrintHex();
#endif
m_vPermBits.Create(m_nServerInputBits + m_nConversionInputBits, m_cCrypto);
m_vServerKeySndBuf.Create((m_nServerInputBits + m_cBoolCircuit->GetNumA2YGates()) * symbits);
m_vClientKeySndBuf.resize(2);
m_vClientKeySndBuf[0].Create((m_nClientInputBits + m_nConversionInputBits) * symbits);
m_vClientKeySndBuf[1].Create((m_nClientInputBits + m_nConversionInputBits) * symbits);
m_vOutputShareSndBuf.Create(m_cBoolCircuit->GetNumOutputBitsForParty(CLIENT));
//m_vOutputDestionations = (e_role*) malloc(sizeof(e_role) * m_cBoolCircuit->GetOutputGatesForParty(CLIENT).size()+m_cBoolCircuit->GetOutputGatesForParty(SERVER).size());
//m_nOutputDestionationsCtr = 0;
//deque<uint32_t> out = m_cBoolCircuit->GetOutputGatesForParty(CLIENT);
IKNP_OTTask* task = (IKNP_OTTask*) malloc(sizeof(IKNP_OTTask));
fMaskFct = new XORMasking(m_cCrypto->get_seclvl().symbits, m_vR);
task->bitlen = symbits;
task->snd_flavor = Snd_R_OT;
task->rec_flavor = Rec_OT;
task->numOTs = m_nClientInputBits + m_nConversionInputBits;
task->mskfct = fMaskFct;
task->pval.sndval.X0 = &(m_vROTMasks[0]);
task->pval.sndval.X1 = &(m_vROTMasks[1]);
setup->AddOTTask(task, 0);
}
/* send the garbled table */
void YaoServerPipeSharing::PerformSetupPhase(ABYSetup* setup) {
// Do nothing in here, only pre-compute OTs
}
void YaoServerPipeSharing::FinishSetupPhase(ABYSetup* setup) {
// Do nothing
}
void YaoServerPipeSharing::EvaluateLocalOperations(uint32_t depth) {
deque<uint32_t> localqueue = m_cBoolCircuit->GetLocalQueueOnLvl(depth);
GATE *gate, *parent;
e_role dst;
//cout << "Evaluating circuit on layer " << depth << endl;
for (uint32_t i = 0; i < localqueue.size(); i++) {
GATE* gate = m_pGates + localqueue[i];
#ifdef DEBUGYAOPIPESERVER
cout << "Evaluating gate with id = " << localqueue[i] << ", and type = "<< get_gate_type_name(gate->type) << "(" << gate->type << "), depth = " << gate->depth
<< ", nvals = " << gate->nvals << ", sharebitlen = " << gate->sharebitlen << endl;
#endif
assert(gate->nvals > 0 && gate->sharebitlen == 1);
if (gate->type == G_LIN) {
EvaluateXORGate(gate);
} else if (gate->type == G_NON_LIN) {
EvaluateANDGate(gate);
} else if (gate->type == G_IN) {
cerr << "Error: Evaluating input gate in local queue" << endl;
assert(false);
//EvaluateInputGate(localqueue[i]);
} else if (gate->type == G_OUT) {
cerr << "Error: Evaluating output gate in local queue" << endl;
assert(false);
/*#ifdef DEBUGYAOPIPESERVER
cout << "Obtained output gate with key = ";
uint32_t parentid = gate->ingates.inputs.parent;
PrintKey(m_pGates[parentid].gs.yinput.outKey);
cout << " and pi = " << (uint32_t) m_pGates[parentid].gs.yinput.pi[0] << endl;
#endif
EvaluateOutputGate(gate);*/
} else if (gate->type == G_CONV) {
#ifdef DEBUGYAOPIPESERVER
cout << "Ealuating conversion gate" << endl;
#endif
EvaluateConversionGate(localqueue[i]);
} else if (gate->type == G_CONSTANT) {
//assign 0 and 1 gates
UGATE_T constval = gate->gs.constval;
InstantiateGate(gate);
memset(gate->gs.yinput.outKey, 0, m_nSecParamBytes * gate->nvals);
for(uint32_t i = 0; i < gate->nvals; i++) {
gate->gs.yinput.pi[i] = (constval>>i) & 0x01;
}
#ifdef DEBUGYAOPIPESERVER
cout << "Assigned key to constant gate " << localqueue[i] << " (" << (uint32_t) gate->gs.yinput.pi[0] << ") : ";
PrintKey(gate->gs.yinput.outKey);
cout << endl;
#endif
} else if (IsSIMDGate(gate->type)) {
EvaluateSIMDGate(localqueue[i]);
} else if (gate->type == G_INV) {
EvaluateInversionGate(gate);
} else if (gate->type == G_CALLBACK) {
EvaluateCallbackGate(localqueue[i]);
} else {
cerr << "Operation not recognized: " << (uint32_t) gate->type << "(" << get_gate_type_name(gate->type) << ")" << endl;
}
}
}
void YaoServerPipeSharing::EvaluateInteractiveOperations(uint32_t depth) {
deque<uint32_t> interactivequeue = m_cBoolCircuit->GetInteractiveQueueOnLvl(depth);
GATE *gate, *parent;
e_role dst;
for (uint32_t i = 0; i < interactivequeue.size(); i++) {
gate = m_pGates + interactivequeue[i];
#ifdef DEBUGYAOPIPESERVER
cout << "Evaluating gate with id = " << interactivequeue[i] << ", and type = "<< get_gate_type_name(gate->type) << ", and depth = " << gate->depth << endl;
#endif
switch (gate->type) {
case G_IN:
if (gate->gs.ishare.src == SERVER) {
//SendServerInputKey(interactivequeue[i]);
EvaluateServerInputGate(interactivequeue[i]);
} else {
//SendClientInputKey(interactivequeue[i]);
EvaluateClientInputGate(interactivequeue[i]);
}
break;
case G_OUT:
if (gate->gs.oshare.dst == CLIENT || gate->gs.oshare.dst == ALL) {
EvaluateClientOutputGate(gate);
//m_vServerOutputGates.push_back(gate);
//m_nOutputShareRcvCtr += gate->nvals;
}
if (gate->gs.oshare.dst == SERVER || gate->gs.oshare.dst == ALL) {
EvaluateServerOutputGate(gate);
m_vServerOutputGates.push_back(gate);
m_nOutputShareRcvCtr += gate->nvals;
}
//else do nothing since the client has already been given the output
break;
case G_CONV:
parent = m_pGates + gate->ingates.inputs.parents[0];
if (parent->context == S_ARITH) {
SendConversionValues(interactivequeue[i]);
} else {
EvaluateConversionGate(interactivequeue[i]);
}
break;
case G_CALLBACK:
EvaluateCallbackGate(interactivequeue[i]);
break;
default:
cerr << "Interactive Operation not recognized: " << (uint32_t) gate->type << " (" << get_gate_type_name(gate->type) << "), stopping execution" << endl;
exit(0);
}
}
}
void YaoServerPipeSharing::SendConversionValues(uint32_t gateid) {
GATE* gate = m_pGates + gateid;
GATE* parent = m_pGates + gate->ingates.inputs.parents[0];
uint32_t pos = gate->gs.pos;
uint32_t id = pos >> 1;
#ifdef DEBUGYAOPIPESERVER
cout << "Evaluating A2Y with gateid = " << gateid << ", pos = " << pos;
#endif
//Convert server's share
if ((pos & 0x01) == 0) {
gate->gs.ishare.inval = (UGATE_T*) malloc(sizeof(UGATE_T));
gate->gs.ishare.inval[0] = (parent->gs.aval[id / GATE_T_BITS] >> (id % GATE_T_BITS)) & 0x01;
#ifdef DEBUGYAOPIPESERVER
cout << " (server share) with value " << (uint32_t) gate->gs.ishare.inval[0] << " (" << id / GATE_T_BITS << ", " << (id%GATE_T_BITS) <<
", " << parent->gs.aval[0] <<") " << gate->ingates.inputs.parents[0] << ", " << (uint64_t) parent->gs.aval << endl;
#endif
SendServerInputKey(gateid);
} else { //Convert client's share
#ifdef DEBUGYAOPIPESERVER
cout << " (client share) " << endl;
#endif
m_nClientInBitCtr += gate->nvals;
m_vClientInputGate.push_back(gateid);
}
}
/*void YaoServerPipeSharing::SendClientInputKey(uint32_t gateid) {
//push back and wait for bit of client
GATE* gate = m_pGates + gateid;
m_nClientInBitCtr += gate->nvals;
m_vClientInputGate.push_back(gateid);
}*/
void YaoServerPipeSharing::PrepareOnlinePhase() {
//Do nothing right now, figure out which parts come here
m_nClientInBitCtr = 0;
m_nPermBitCtr = 0;
}
/*void YaoServerPipeSharing::CreateAndSendGarbledCircuit(ABYSetup* setup) {
//Go over all gates and garble them
cout << "I should not be here"
uint32_t maxdepth = m_cBoolCircuit->GetMaxDepth();
if (maxdepth == 0)
return;
for (uint32_t i = 0; i < maxdepth; i++) {
deque<uint32_t> localqueue = m_cBoolCircuit->GetLocalQueueOnLvl(i);
PrecomputeGC(localqueue);
deque<uint32_t> interactivequeue = m_cBoolCircuit->GetInteractiveQueueOnLvl(i);
PrecomputeGC(interactivequeue);
}
//Store the shares of the clients output gates
CollectClientOutputShares();
//Send the garbled circuit and the output mapping to the client
if (m_nANDGates > 0)
setup->AddSendTask(m_vGarbledCircuit.GetArr(), m_nGarbledTableCtr * m_nSecParamBytes * KEYS_PER_GATE_IN_TABLE);
if (m_cBoolCircuit->GetNumOutputBitsForParty(CLIENT) > 0)
setup->AddSendTask(m_vOutputShareSndBuf.GetArr(), ceil_divide(m_cBoolCircuit->GetNumOutputBitsForParty(CLIENT), 8));
#ifdef DEBUGYAOPIPESERVER
cout << "Sending Garbled Circuit: ";
m_vGarbledCircuit.PrintHex();
cout << "Sending my output shares: ";
m_vOutputShareSndBuf.Print(0, m_cBoolCircuit->GetNumOutputBitsForParty(CLIENT));
#endif
setup->WaitForTransmissionEnd();
}*/
/*void YaoServerPipeSharing::PrecomputeGC(deque<uint32_t>& queue) {
}*/
void YaoServerPipeSharing::EvaluateInversionGate(GATE* gate) {
uint32_t parentid = gate->ingates.inputs.parent;
InstantiateGate(gate);
assert((gate - m_pGates) > parentid);
memcpy(gate->gs.yinput.outKey, m_pGates[parentid].gs.yinput.outKey, m_nSecParamBytes * gate->nvals);
for (uint32_t i = 0; i < gate->nvals; i++) {
gate->gs.yinput.pi[i] = m_pGates[parentid].gs.yinput.pi[i] ^ 0x01;
assert(gate->gs.yinput.pi[i] < 2 && m_pGates[parentid].gs.yinput.pi[i] < 2);
}
UsedGate(parentid);
}
void YaoServerPipeSharing::EvaluateServerInputGate(uint32_t gateid) {
GATE* gate = m_pGates + gateid;
SendServerInputKey(gateid);
UGATE_T* input = gate->gs.ishare.inval;
InstantiateGate(gate);
memcpy(gate->gs.yinput.outKey, m_vServerInputKeys.GetArr() + m_nServerKeyCtr * m_nSecParamBytes, m_nSecParamBytes * gate->nvals);
for (uint32_t i = 0; i < gate->nvals; i++) {
gate->gs.yinput.pi[i] = m_vPermBits.GetBit(m_nPermBitCtr);
m_nPermBitCtr++;
}
/*for (uint32_t i = 0; i < gate->nvals; i++, m_nServerKeyCtr++, m_nPermBitCtr++) {
if (((input[i / GATE_T_BITS] >> (i % GATE_T_BITS)) & 0x01)) {
m_pKeyOps->XOR(m_bTempKeyBuf, m_vServerInputKeys.GetArr() + m_nPermBitCtr * m_nSecParamBytes, m_vR.GetArr());
memcpy(m_vServerKeySndBuf.GetArr() + m_nServerKeyCtr * m_nSecParamBytes, m_bTempKeyBuf, m_nSecParamBytes);
} else {
//input bit at position is 0 -> set 0 key
memcpy(m_vServerKeySndBuf.GetArr() + m_nServerKeyCtr * m_nSecParamBytes, m_vServerInputKeys.GetArr() + m_nPermBitCtr * m_nSecParamBytes, m_nSecParamBytes);
}
}*/
#ifdef DEBUGYAOPIPESERVER
cout << "Assigned key to sever input gate " << gateid << " (" << (uint32_t) gate->gs.yinput.pi[0] << ") : ";
PrintKey(gate->gs.yinput.outKey);
cout << endl;
#endif
}
void YaoServerPipeSharing::SendServerInputKey(uint32_t gateid) {
GATE* gate = m_pGates + gateid;
UGATE_T* input = gate->gs.ishare.inval;
for (uint32_t i = 0, tmppermbitctr=m_nPermBitCtr; i < gate->nvals; i++, m_nServerKeyCtr++, tmppermbitctr++) {
if (!!((input[i / GATE_T_BITS] >> (i % GATE_T_BITS)) & 0x01) ^ m_vPermBits.GetBit(tmppermbitctr)) {//if (!!((input[i / GATE_T_BITS] >> (i % GATE_T_BITS)) & 0x01)) {
m_pKeyOps->XOR(m_bTempKeyBuf, m_vServerInputKeys.GetArr() + tmppermbitctr * m_nSecParamBytes, m_vR.GetArr());
memcpy(m_vServerKeySndBuf.GetArr() + m_nServerKeyCtr * m_nSecParamBytes, m_bTempKeyBuf, m_nSecParamBytes);
} else {
//input bit at position is 0 -> set 0 key
memcpy(m_vServerKeySndBuf.GetArr() + m_nServerKeyCtr * m_nSecParamBytes, m_vServerInputKeys.GetArr() + tmppermbitctr * m_nSecParamBytes, m_nSecParamBytes);
}
}
}
void YaoServerPipeSharing::EvaluateClientInputGate(uint32_t gateid) {
GATE* gate = m_pGates + gateid;
InstantiateGate(gate);
memcpy(gate->gs.yinput.outKey, m_vClientInputKeys.GetArr() + m_nClientInBitCtr * m_nSecParamBytes, m_nSecParamBytes * gate->nvals);
memset(gate->gs.yinput.pi, 0, gate->nvals);
m_nClientInBitCtr += gate->nvals;
m_vClientInputGate.push_back(gateid);
#ifdef DEBUGYAOPIPESERVER
cout << "Assigned key to sever input gate " << gateid << " (" << (uint32_t) gate->gs.yinput.pi[0] << ") : ";
PrintKey(gate->gs.yinput.outKey);
cout << endl;
#endif
}
/* Treat conversion gates as a combination of server and client inputs - set permutation bit
* and perform an oblivious transfer
*/
void YaoServerPipeSharing::EvaluateConversionGate(uint32_t gateid) {
GATE* gate = m_pGates + gateid;
GATE* parent = m_pGates + gate->ingates.inputs.parents[0];
uint32_t pos = gate->gs.pos;
InstantiateGate(gate);
if (parent->context == S_BOOL) {
memcpy(gate->gs.yinput.outKey, m_vClientInputKeys.GetArr() + m_nClientInBitCtr * m_nSecParamBytes, m_nSecParamBytes * gate->nvals);
for (uint32_t i = 0; i < gate->nvals; i++) {
gate->gs.yinput.pi[i] = m_vPermBits.GetBit(m_nPermBitCtr);
m_nPermBitCtr++;
}
m_nClientInBitCtr += gate->nvals;
m_vClientInputGate.push_back(gateid);
} else if (parent->context == S_ARITH) {
#ifdef DEBUGYAOPIPESERVER
cout << "Evaluating arithmetic conversion gate with gateid = " << gateid << " and pos = " << pos;
#endif
//Convert server's share
a2y_gate_pos_t a2ygate;
a2ygate.gateid = gateid;
a2ygate.pos = pos;
m_vPreSetA2YPositions.push_back(a2ygate);
if((pos & 0x01) == 0) {
#ifdef DEBUGYAOPIPESERVER
cout << " converting server share" << endl;
#endif
memcpy(gate->gs.yinput.outKey, m_vServerInputKeys.GetArr() + m_nPermBitCtr * m_nSecParamBytes, m_nSecParamBytes * gate->nvals);
for (uint32_t i = 0; i < gate->nvals; i++) {
gate->gs.yinput.pi[i] = m_vPermBits.GetBit(m_nPermBitCtr);
m_nPermBitCtr++;
}
} else { //Convert client's share
#ifdef DEBUGYAOPIPESERVER
cout << " converting client share" << endl;
#endif
memcpy(gate->gs.yinput.outKey, m_vClientInputKeys.GetArr() + m_nClientInBitCtr * m_nSecParamBytes, m_nSecParamBytes * gate->nvals);
memset(gate->gs.yinput.pi, 0, gate->nvals);
//gate->gs.yinput.pi[0] = 0;
m_nClientInBitCtr += gate->nvals;
m_vClientInputGate.push_back(gateid);
}
}
#ifdef DEBUGYAOPIPESERVER
cout << "Assigned key to conversion gate " << gateid << " (" << (uint32_t) gate->gs.yinput.pi[0] << ") : ";
PrintKey(gate->gs.yinput.outKey);
cout << endl;
#endif
}
//TODO: optimize for UINT64_T pointers
void YaoServerPipeSharing::EvaluateXORGate(GATE* gate) {
uint32_t idleft = gate->ingates.inputs.twin.left; //gate->gs.ginput.left;
uint32_t idright = gate->ingates.inputs.twin.right; //gate->gs.ginput.right;
BYTE* lpi = (m_pGates + idleft)->gs.yinput.pi;
BYTE* rpi = (m_pGates + idright)->gs.yinput.pi;
BYTE* lkey = (m_pGates + idleft)->gs.yinput.outKey;
BYTE* rkey = (m_pGates + idright)->gs.yinput.outKey;
InstantiateGate(gate);
BYTE* gpi = gate->gs.yinput.pi;
BYTE* gkey = gate->gs.yinput.outKey;
#ifdef GATE_INST_FLAG
assert((m_pGates + idleft)->instantiated);
assert((m_pGates + idright)->instantiated);
#endif
for (uint32_t g = 0; g < gate->nvals; g++, gpi++, lpi++, rpi++, lkey += m_nSecParamBytes, rkey += m_nSecParamBytes, gkey += m_nSecParamBytes) {
*gpi = *lpi ^ *rpi;
m_pKeyOps->XOR(gkey, lkey, rkey);
assert(*gpi < 2);
}
#ifdef DEBUGYAOPIPESERVER
PrintKey(gate->gs.yinput.outKey);
cout << " (" << (uint32_t) gate->gs.yinput.pi[0] << ") = ";
PrintKey((m_pGates + idleft)->gs.yinput.outKey);
cout << " (" << (uint32_t) (m_pGates + idleft)->gs.yinput.pi[0] << ")(" << idleft << ") ^ ";
PrintKey((m_pGates + idright)->gs.yinput.outKey);
cout << " (" << (uint32_t) (m_pGates + idright)->gs.yinput.pi[0] << ")(" << idright << ")" << endl;
#endif
assert((m_pGates + idleft)->gs.yinput.pi[0] < 2 && (m_pGates + idright)->gs.yinput.pi[0] < 2);
UsedGate(idleft);
UsedGate(idright);
}
//Evaluate an AND gate
void YaoServerPipeSharing::EvaluateANDGate(GATE* gate) {
uint32_t idleft = gate->ingates.inputs.twin.left;//gate->gs.ginput.left;
uint32_t idright = gate->ingates.inputs.twin.right;//gate->gs.ginput.right;
GATE* gleft = m_pGates + idleft;
GATE* gright = m_pGates + idright;
InstantiateGate(gate);
for(uint32_t g = 0; g < gate->nvals; g++) {
CreateGarbledTable(gate, g, gleft, gright);
m_nGarbledTableCtr++;
assert(gate->gs.yinput.pi[g] < 2);
//Pipelined send - TODO: outsource in own thread
//if(m_nGarbledTableCtr >= GARBLED_TABLE_WINDOW) {
//TODO: pipeline the garbled table transfer
//sock.Send(m_vGarbledCircuit.GetArr(), m_nGarbledTableCtr * m_nSecParamBytes * KEYS_PER_GATE_IN_TABLE);
//m_nGarbledTableCtr=0;
//}
}
UsedGate(idleft);
UsedGate(idright);
}
void YaoServerPipeSharing::CreateGarbledTable(GATE* ggate, uint32_t pos, GATE* gleft, GATE* gright){
uint32_t outkey;
uint8_t *table, *lkey, *rkey, *outwire_key;
uint8_t lpbit = gleft->gs.yinput.pi[pos];
uint8_t rpbit = gright->gs.yinput.pi[pos];
uint8_t lsbit, rsbit;
assert(lpbit < 2 && rpbit < 2);
table = m_vGarbledCircuit.GetArr() + m_nGarbledTableCtr * KEYS_PER_GATE_IN_TABLE * m_nSecParamBytes;
outwire_key = ggate->gs.yinput.outKey + pos * m_nSecParamBytes;
lkey = gleft->gs.yinput.outKey + pos * m_nSecParamBytes;
rkey = gright->gs.yinput.outKey + pos * m_nSecParamBytes;
lsbit = (lkey[m_nSecParamBytes-1] & 0x01);
rsbit = (rkey[m_nSecParamBytes-1] & 0x01);
if(lpbit) {
m_pKeyOps->XOR(m_bLKeyBuf, lkey, m_vR.GetArr());
} else {
memcpy(m_bLKeyBuf, lkey, m_nSecParamBytes);
}
//Encryptions of wire A
EncryptWire(m_bLMaskBuf[lpbit], lkey, KEYS_PER_GATE_IN_TABLE*m_nGarbledTableCtr);
m_pKeyOps->XOR(m_bTmpBuf, lkey, m_vR.GetArr());
EncryptWire(m_bLMaskBuf[!lpbit], m_bTmpBuf, KEYS_PER_GATE_IN_TABLE*m_nGarbledTableCtr);
//Encryptions of wire B
EncryptWire(m_bRMaskBuf[rpbit], rkey, KEYS_PER_GATE_IN_TABLE*m_nGarbledTableCtr+1);
m_pKeyOps->XOR(m_bTmpBuf, rkey, m_vR.GetArr());
EncryptWire(m_bRMaskBuf[!rpbit], m_bTmpBuf, KEYS_PER_GATE_IN_TABLE*m_nGarbledTableCtr+1);
//Compute two table entries, T_G is the first cipher-text, T_E the second cipher-text
//Compute T_G = Enc(W_a^0) XOR Enc(W_a^1) XOR p_b*R
m_pKeyOps->XOR(table, m_bLMaskBuf[0], m_bLMaskBuf[1]);
if(rpbit)
m_pKeyOps->XOR(table, table, m_vR.GetArr());
if(lpbit)
m_pKeyOps->XOR(outwire_key, m_bLMaskBuf[1], m_bRMaskBuf[0]);
else
m_pKeyOps->XOR(outwire_key, m_bLMaskBuf[0], m_bRMaskBuf[0]);
if((lsbit) & (rsbit))
m_pKeyOps->XOR(outwire_key, outwire_key, m_vR.GetArr());
//Compute W^0 = W_G^0 XOR W_E^0 = Enc(W_a^0) XOR Enc(W_b^0) XOR p_a*T_G XOR p_b * (T_E XOR W_a^0)
//Compute T_E = Enc(W_b^0) XOR Enc(W_b^1) XOR W_a^0
m_pKeyOps->XOR(table + m_nSecParamBytes, m_bRMaskBuf[0], m_bRMaskBuf[1]);
m_pKeyOps->XOR(table + m_nSecParamBytes, table + m_nSecParamBytes, m_bLKeyBuf);
//Compute the resulting key for the output wire
if(rpbit) {
//cout << "Server Xoring right_table" << endl;
m_pKeyOps->XOR(outwire_key, outwire_key, table + m_nSecParamBytes);
m_pKeyOps->XOR(outwire_key, outwire_key, m_bLKeyBuf);
}
//Set permutation bit
if((outwire_key[m_nSecParamBytes-1] & 0x01)) {
m_pKeyOps->XOR(outwire_key, outwire_key, m_vR.GetArr());
ggate->gs.yinput.pi[pos] = !(outwire_key[m_nSecParamBytes-1] & 0x01) ^ ((lpbit) & (rpbit));
} else {
ggate->gs.yinput.pi[pos] = (outwire_key[m_nSecParamBytes-1] & 0x01) ^ ((lpbit) & (rpbit));
}
#ifdef DEBUGYAOPIPESERVER
cout << " encr : ";
PrintKey(lkey);
cout << " (" << (uint32_t) gleft->gs.yinput.pi[pos] << ") and : ";
PrintKey(rkey);
cout << " (" << (uint32_t) gright->gs.yinput.pi[pos] << ") to : ";
PrintKey(outwire_key);
cout << " (" << (uint32_t) ggate->gs.yinput.pi[pos] << ")" << endl;
cout << "A_0: ";
PrintKey(m_bLMaskBuf[0]);
cout << "; A_1: ";
PrintKey(m_bLMaskBuf[1]);
cout << endl << "B_0: ";
PrintKey(m_bRMaskBuf[0]);
cout << "; B_1: ";
PrintKey(m_bRMaskBuf[1]);
cout << endl << "Table A: ";
PrintKey(table);
cout << "; Table B: ";
PrintKey(table+m_nSecParamBytes);
cout << endl;
#endif
}
/*//Collect the permutation bits on the clients output gates and prepare them to be sent off
void YaoServerPipeSharing::CollectClientOutputShares() {
deque<uint32_t> out = m_cBoolCircuit->GetOutputGatesForParty(CLIENT);
while (out.size() > 0) {
for (uint32_t j = 0; j < m_pGates[out.front()].nvals; j++, m_nOutputShareSndSize++) {
m_vOutputShareSndBuf.SetBit(m_nOutputShareSndSize, !!((m_pGates[out.front()].gs.val[j / GATE_T_BITS]) & ((UGATE_T) 1 << (j % GATE_T_BITS))));
}
out.pop_front();
}
}*/
//Collect the permutation bits on the clients output gates and prepare them to be sent off
void YaoServerPipeSharing::EvaluateClientOutputGate(GATE* gate) {
uint32_t parentid = gate->ingates.inputs.parent;
//deque<uint32_t> out = m_cBoolCircuit->GetOutputGatesForParty(CLIENT);
//while (out.size() > 0) {
//InstantiateGate(gate);
cout << "Evaluating client output gate" << endl;
for (uint32_t j = 0; j < gate->nvals; j++, m_nOutputShareSndSize++) {
m_vOutputShareSndBuf.SetBit(m_nOutputShareSndSize, !!(((UGATE_T) m_pGates[parentid].gs.yinput.pi[j]) << (j % GATE_T_BITS)));//!!((gate->gs.val[j / GATE_T_BITS]) & ((UGATE_T) 1 << (j % GATE_T_BITS))));
}
// out.pop_front();
//}
}
void YaoServerPipeSharing::EvaluateServerOutputGate(GATE* gate) {
uint32_t parentid = gate->ingates.inputs.parent;
gate->gs.val = (UGATE_T*) calloc(ceil_divide(gate->nvals, GATE_T_BITS), sizeof(UGATE_T));
gate->instantiated = true;
for (uint32_t i = 0; i < gate->nvals; i++) {
gate->gs.val[i / GATE_T_BITS] |= (((UGATE_T) m_pGates[parentid].gs.yinput.pi[i]) << (i % GATE_T_BITS));
}
//#ifdef DEBUGYAOPIPESERVER
cout << "Stored output share " << gate->gs.val[0] << " for key ";
PrintKey(m_pGates[parentid].gs.yinput.outKey);
cout << endl;
//#endif
}
void YaoServerPipeSharing::GetDataToSend(vector<BYTE*>& sendbuf, vector<uint32_t>& sndbytes) {
//The garbled table
if (m_nGarbledTableCtr > 0) {
cout << "I am sending the garbled table which is of " << KEYS_PER_GATE_IN_TABLE << " * " << m_nGarbledTableCtr * m_nSecParamBytes << " bytes " << endl;
cout << "Garbled Table: ";
m_vGarbledCircuit.PrintHex();
sendbuf.push_back(m_vGarbledCircuit.GetArr());
sndbytes.push_back(KEYS_PER_GATE_IN_TABLE * m_nGarbledTableCtr * m_nSecParamBytes);
m_nGarbledTableCtr = 0;
}
//Input keys of server
if (m_nServerKeyCtr > 0) {
#ifdef DEBUGYAOPIPESERVER
cout << "want to send servers input keys which are of size " << m_nServerKeyCtr * m_nSecParamBytes << " bytes" << endl;
cout << "Server input keys = ";
m_vServerKeySndBuf.PrintHex();
#endif
sendbuf.push_back(m_vServerKeySndBuf.GetArr());
sndbytes.push_back(m_nServerKeyCtr * m_nSecParamBytes);
}
//Input keys of client
if (m_nClientInputKeyCtr > 0) {
#ifdef DEBUGYAOPIPESERVER
cout << "want to send client input keys which are of size " << m_nClientInputKeyCtr * m_nSecParamBytes << " bytes" << endl;
cout << "Client input keys[0] = ";
m_vClientKeySndBuf[0].PrintHex();
cout << "Client input keys[1] = ";
m_vClientKeySndBuf[1].PrintHex();
#endif
sendbuf.push_back(m_vClientKeySndBuf[0].GetArr());
sndbytes.push_back(m_nClientInputKeyCtr * m_nSecParamBytes);
sendbuf.push_back(m_vClientKeySndBuf[1].GetArr());
sndbytes.push_back(m_nClientInputKeyCtr * m_nSecParamBytes);
m_nClientInputKeyCtr = 0;
}
if(m_nOutputShareSndSize > 0) {
//#ifdef DEBUGYAOPIPESERVER
cout << "want to send client output values " << m_nOutputShareSndSize << " bits" << endl;
cout << "Client output keys = ";
m_vOutputShareSndBuf.PrintHex();
//#endif
sendbuf.push_back(m_vOutputShareSndBuf.GetArr());
sndbytes.push_back(ceil_divide(m_nOutputShareSndSize, 8));
m_nOutputShareSndSize = 0;
}
}
void YaoServerPipeSharing::FinishCircuitLayer(uint32_t level) {
//Use OT bits from the client to determine the send bits that are supposed to go out next round
if (m_nClientInBitCtr > 0) {
for (uint32_t i = 0, linbitctr = 0; i < m_vClientInputGate.size() && linbitctr < m_nClientInBitCtr; i++) {
uint32_t gateid = m_vClientInputGate[i];
if (m_pGates[gateid].type == G_IN) {
for (uint32_t k = 0; k < m_pGates[gateid].nvals; k++, linbitctr++, m_nClientInputKexIdx++, m_nClientInputKeyCtr++) {
m_pKeyOps->XOR(m_bTempKeyBuf, m_vClientInputKeys.GetArr() + m_nClientInputKexIdx * m_nSecParamBytes, m_vR.GetArr());
if (m_vClientROTRcvBuf.GetBitNoMask(linbitctr) == 1) {
//Swap masks
m_pKeyOps->XOR(m_vClientKeySndBuf[0].GetArr() + linbitctr * m_nSecParamBytes, m_vROTMasks[0].GetArr() + m_nClientInputKexIdx * m_nSecParamBytes,
m_bTempKeyBuf); //One - key
m_pKeyOps->XOR(m_vClientKeySndBuf[1].GetArr() + linbitctr * m_nSecParamBytes, m_vROTMasks[1].GetArr() + m_nClientInputKexIdx * m_nSecParamBytes,
m_vClientInputKeys.GetArr() + m_nClientInputKexIdx * m_nSecParamBytes); //Zero - key
#ifdef DEBUGYAOPIPESERVER
cout << "T0: ";
PrintKey(m_vClientKeySndBuf[0].GetArr() + linbitctr * m_nSecParamBytes);
cout << " = ";
PrintKey(m_vROTMasks[0].GetArr() + m_nClientInputKexIdx * m_nSecParamBytes);
cout << " ^ ";
PrintKey(m_bTempKeyBuf);
cout << endl;
cout << "T1: ";
PrintKey(m_vClientKeySndBuf[1].GetArr() + linbitctr * m_nSecParamBytes);
cout << " = ";
PrintKey(m_vROTMasks[1].GetArr() + m_nClientInputKexIdx * m_nSecParamBytes);
cout << " ^ ";
PrintKey(m_vClientInputKeys.GetArr() + m_nClientInputKexIdx * m_nSecParamBytes);
cout << endl;
#endif
} else {
//masks remain the same
m_pKeyOps->XOR(m_vClientKeySndBuf[0].GetArr() + linbitctr * m_nSecParamBytes, m_vROTMasks[0].GetArr() + m_nClientInputKexIdx * m_nSecParamBytes,
m_vClientInputKeys.GetArr() + m_nClientInputKexIdx * m_nSecParamBytes); //Zero - key
m_pKeyOps->XOR(m_vClientKeySndBuf[1].GetArr() + linbitctr * m_nSecParamBytes, m_vROTMasks[1].GetArr() + m_nClientInputKexIdx * m_nSecParamBytes,
m_bTempKeyBuf); //One - key
#ifdef DEBUGYAOPIPESERVER
cout << "T0: ";
PrintKey(m_vClientKeySndBuf[0].GetArr() + linbitctr * m_nSecParamBytes);
cout << " = ";
PrintKey(m_vROTMasks[0].GetArr() + m_nClientInputKexIdx * m_nSecParamBytes);
cout << " ^ ";
PrintKey(m_vClientInputKeys.GetArr() + m_nClientInputKexIdx * m_nSecParamBytes);
cout << endl;
cout << "T1: ";
PrintKey(m_vClientKeySndBuf[1].GetArr() + linbitctr * m_nSecParamBytes);
cout << " = ";
PrintKey(m_vROTMasks[1].GetArr() + m_nClientInputKexIdx * m_nSecParamBytes);
cout << " ^ ";
PrintKey(m_bTempKeyBuf);
cout << endl;
#endif
}
}
} else {
uint32_t input = m_pGates[gateid].ingates.inputs.parents[0];
for (uint32_t k = 0; k < m_pGates[gateid].nvals; k++, linbitctr++, m_nClientInputKexIdx++, m_nClientInputKeyCtr++) {
m_pKeyOps->XOR(m_bTempKeyBuf, m_vClientInputKeys.GetArr() + m_nClientInputKexIdx * m_nSecParamBytes, m_vR.GetArr());
uint32_t permval = 0;
if (m_pGates[input].context == S_BOOL) {
uint32_t val = (m_pGates[input].gs.val[k / GATE_T_BITS] >> (k % GATE_T_BITS)) & 0x01;
permval = val ^ m_pGates[gateid].gs.yinput.pi[k];
}
#ifdef DEBUGYAOPIPESERVER
cout << "Processing keys for gate " << gateid << ", perm-bit = " << (uint32_t) m_pGates[gateid].gs.yinput.pi[k] <<
", client-cor: " << (uint32_t) m_vClientROTRcvBuf.GetBitNoMask(linbitctr) << endl;
PrintKey(m_vClientInputKeys.GetArr() + m_nClientInputKexIdx * m_nSecParamBytes);
cout << endl;
#endif
if (m_vClientROTRcvBuf.GetBitNoMask(linbitctr) ^ permval == 1) {
m_pKeyOps->XOR(m_vClientKeySndBuf[0].GetArr() + linbitctr * m_nSecParamBytes, m_vROTMasks[0].GetArr() + m_nClientInputKexIdx * m_nSecParamBytes,
m_bTempKeyBuf); //One - key
m_pKeyOps->XOR(m_vClientKeySndBuf[1].GetArr() + linbitctr * m_nSecParamBytes, m_vROTMasks[1].GetArr() + m_nClientInputKexIdx * m_nSecParamBytes,
m_vClientInputKeys.GetArr() + m_nClientInputKexIdx * m_nSecParamBytes); //Zero - key
} else {
//masks remain the same
m_pKeyOps->XOR(m_vClientKeySndBuf[0].GetArr() + linbitctr * m_nSecParamBytes, m_vROTMasks[0].GetArr() + m_nClientInputKexIdx * m_nSecParamBytes,
m_vClientInputKeys.GetArr() + m_nClientInputKexIdx * m_nSecParamBytes); //Zero - key
m_pKeyOps->XOR(m_vClientKeySndBuf[1].GetArr() + linbitctr * m_nSecParamBytes, m_vROTMasks[1].GetArr() + m_nClientInputKexIdx * m_nSecParamBytes,
m_bTempKeyBuf); //One - key
}
}
}
}
}
m_vClientInputGate.clear();
m_nClientInBitCtr = 0;
if (m_nOutputShareRcvCtr > 0) {
AssignOutputShares();
}
//Recheck if this is working
InitNewLayer();
}
;
void YaoServerPipeSharing::GetBuffersToReceive(vector<BYTE*>& rcvbuf, vector<uint32_t>& rcvbytes) {
//receive bit from random-OT
if (m_nClientInBitCtr > 0) {
#ifdef DEBUGYAOPIPESERVER
cout << "want to receive clients OT-bits which are of size " << m_nClientInBitCtr << " bits" << endl;
#endif
m_vClientROTRcvBuf.Create(m_nClientInBitCtr);
rcvbuf.push_back(m_vClientROTRcvBuf.GetArr());
rcvbytes.push_back(ceil_divide(m_nClientInBitCtr, 8));
}
if (m_nOutputShareRcvCtr > 0) {
#ifdef DEBUGYAOPIPESERVER
cout << "want to receive server output bits which are of size " << m_nOutputShareRcvCtr << " bits" << endl;
#endif
m_vOutputShareRcvBuf.Create(m_nOutputShareRcvCtr);
rcvbuf.push_back(m_vOutputShareRcvBuf.GetArr());
rcvbytes.push_back(ceil_divide(m_nOutputShareRcvCtr, 8));
}
}
void YaoServerPipeSharing::AssignOutputShares() {
GATE* gate;
for (uint32_t i = 0, offset = 0; i < m_vServerOutputGates.size(); i++) {
gate = m_vServerOutputGates[i];
//#ifdef DEBUGYAOPIPESERVER
cout << "Server Output: " << (uint32_t) (m_vOutputShareRcvBuf.GetBit(offset) ^ gate->gs.val[0] ) << " = "<< (uint32_t) m_vOutputShareRcvBuf.GetBit(offset) << " ^ " << (uint32_t) gate->gs.val[0] << endl;
//#endif
//InstantiateGate(gate);
for (uint32_t j = 0; j < gate->nvals; j++, offset++) {
gate->gs.val[j / GATE_T_BITS] = (gate->gs.val[j / GATE_T_BITS] ^ (((UGATE_T) m_vOutputShareRcvBuf.GetBit(offset))) << (j % GATE_T_BITS));
}
}
m_nOutputShareRcvCtr = 0;
m_vServerOutputGates.clear();
}
void YaoServerPipeSharing::CreateRandomWireKeys(CBitVector& vec, uint32_t numkeys) {
//Create the random keys
vec.Create(numkeys * m_cCrypto->get_seclvl().symbits, m_cCrypto);
for (uint32_t i = 0; i < numkeys; i++) {
vec.ANDByte((i + 1) * m_nSecParamBytes - 1, 0xFE);
}
#ifdef DEBUGYAOPIPESERVER
cout << "Created wire keys: with num = " << numkeys << endl;
vec.PrintHex();
cout << "m_vR = " <<endl;
m_vR.PrintHex();
#endif
}
void YaoServerPipeSharing::InstantiateGate(GATE* gate) {
gate->gs.yinput.outKey = (BYTE*) malloc(sizeof(UGATE_T) * m_nSecParamIters * gate->nvals);
gate->gs.yinput.pi = (BYTE*) malloc(sizeof(BYTE) * gate->nvals);
if (gate->gs.yinput.outKey == NULL) {
cerr << "Memory allocation not successful at Yao gate instantiation" << endl;
exit(0);
}
gate->instantiated = true;
}
void YaoServerPipeSharing::UsedGate(uint32_t gateid) {
//Decrease the number of further uses of the gate
m_pGates[gateid].nused--;
//If the gate is needed in another subsequent gate, delete it
if (!m_pGates[gateid].nused) {
//free(m_pGates[gateid].gs.yinput.outKey);
//free(m_pGates[gateid].gs.yinput.pi);
}
}
void YaoServerPipeSharing::EvaluateSIMDGate(uint32_t gateid) {
GATE* gate = m_pGates + gateid;
if (gate->type == G_COMBINE) {
uint32_t vsize = gate->nvals;
uint32_t* inptr = gate->ingates.inputs.parents; //gate->gs.cinput;
InstantiateGate(gate);
BYTE* keyptr = gate->gs.yinput.outKey;
BYTE* piptr = gate->gs.yinput.pi;
for (uint32_t g = 0; g < vsize; g++, keyptr += m_nSecParamBytes, piptr++) {
memcpy(keyptr, m_pGates[inptr[g]].gs.yinput.outKey, m_nSecParamBytes);
//TODO: easy solution, vectorize to make more efficient:
memcpy(piptr, m_pGates[inptr[g]].gs.yinput.pi, 1);
assert(*piptr < 2);
UsedGate(inptr[g]);
}
free(inptr);
} else if (gate->type == G_SPLIT) {
uint32_t pos = gate->gs.sinput.pos;
uint32_t idleft = gate->ingates.inputs.parent; //gate->gs.sinput.input;
InstantiateGate(gate);
memcpy(gate->gs.yinput.outKey, m_pGates[idleft].gs.yinput.outKey + pos * m_nSecParamBytes, m_nSecParamBytes * gate->nvals);
memcpy(gate->gs.yinput.pi, m_pGates[idleft].gs.yinput.pi + pos, gate->nvals);
UsedGate(idleft);
} else if (gate->type == G_REPEAT) {
uint32_t idleft = gate->ingates.inputs.parent; //gate->gs.rinput;
InstantiateGate(gate);
BYTE* keyptr = gate->gs.yinput.outKey;
for (uint32_t g = 0; g < gate->nvals; g++, keyptr += m_nSecParamBytes) {
memcpy(keyptr, m_pGates[idleft].gs.yinput.outKey, m_nSecParamBytes);
gate->gs.yinput.pi[g] = m_pGates[idleft].gs.yinput.pi[0];
assert(gate->gs.yinput.pi[g] < 2);
}
UsedGate(idleft);
} else if (gate->type == G_COMBINEPOS) {
uint32_t* combinepos = gate->ingates.inputs.parents; //gate->gs.combinepos.input;
uint32_t pos = gate->gs.combinepos.pos;
InstantiateGate(gate);
BYTE* keyptr = gate->gs.yinput.outKey;
for (uint32_t g = 0; g < gate->nvals; g++, keyptr += m_nSecParamBytes) {
uint32_t idleft = combinepos[g];
memcpy(keyptr, m_pGates[idleft].gs.yinput.outKey + pos * m_nSecParamBytes, m_nSecParamBytes);
gate->gs.yinput.pi[g] = m_pGates[idleft].gs.yinput.pi[pos];
assert(gate->gs.yinput.pi[g] < 2);
UsedGate(idleft);
}
free(combinepos);
} else if (gate->type == G_SUBSET) {
uint32_t idparent = gate->ingates.inputs.parent;
uint32_t* positions = gate->gs.sub_pos.posids; //gate->gs.combinepos.input;
InstantiateGate(gate);
BYTE* keyptr = gate->gs.yinput.outKey;
for (uint32_t g = 0; g < gate->nvals; g++, keyptr += m_nSecParamBytes) {
memcpy(keyptr, m_pGates[idparent].gs.yinput.outKey + positions[g] * m_nSecParamBytes, m_nSecParamBytes);
gate->gs.yinput.pi[g] = m_pGates[idparent].gs.yinput.pi[positions[g]];
assert(gate->gs.yinput.pi[g] < 2);
}
UsedGate(idparent);
free(positions);
}
}
uint32_t YaoServerPipeSharing::AssignInput(CBitVector& inputvals) {
deque<uint32_t> myingates = m_cBoolCircuit->GetInputGatesForParty(m_eRole);
inputvals.Create(m_cBoolCircuit->GetNumInputBitsForParty(m_eRole), m_cCrypto);
GATE* gate;
uint32_t inbits = 0;
for (uint32_t i = 0, inbitstart = 0, bitstocopy, len, lim; i < myingates.size(); i++) {
gate = m_pGates + myingates[i];
if (!gate->instantiated) {
bitstocopy = gate->nvals * gate->sharebitlen;
inbits += bitstocopy;
lim = ceil_divide(bitstocopy, GATE_T_BITS);
UGATE_T* inval = (UGATE_T*) calloc(lim, sizeof(UGATE_T));
for (uint32_t j = 0; j < lim; j++, bitstocopy -= GATE_T_BITS) {
len = min(bitstocopy, (uint32_t) GATE_T_BITS);
inval[j] = inputvals.Get<UGATE_T>(inbitstart, len);
inbitstart += len;
}
gate->gs.ishare.inval = inval;
}
}
return inbits;
}
uint32_t YaoServerPipeSharing::GetOutput(CBitVector& out) {
deque<uint32_t> myoutgates = m_cBoolCircuit->GetOutputGatesForParty(m_eRole);
uint32_t outbits = m_cBoolCircuit->GetNumOutputBitsForParty(m_eRole);
out.Create(outbits);
GATE* gate;
for (uint32_t i = 0, outbitstart = 0, bitstocopy, len, lim; i < myoutgates.size(); i++) {
gate = m_pGates + myoutgates[i];
lim = gate->nvals * gate->sharebitlen;
for (uint32_t j = 0; j < lim; j++, outbitstart++) {
out.SetBitNoMask(outbitstart, (gate->gs.val[j / GATE_T_BITS] >> (j % GATE_T_BITS)) & 0x01);
}
}
return outbits;
}
void YaoServerPipeSharing::Reset() {
m_vR.delCBitVector();
m_vPermBits.delCBitVector();
for (uint32_t i = 0; i < m_vROTMasks.size(); i++)
m_vROTMasks[i].delCBitVector();
m_nClientInputKexIdx = 0;
m_vServerKeySndBuf.delCBitVector();
for (uint32_t i = 0; i < m_vClientKeySndBuf.size(); i++)
m_vClientKeySndBuf[i].delCBitVector();
m_vClientROTRcvBuf.delCBitVector();
m_vOutputShareSndBuf.delCBitVector();
m_vOutputShareRcvBuf.delCBitVector();
m_nOutputShareRcvCtr = 0;
m_nPermBitCtr = 0;
m_nServerInBitCtr = 0;
m_nServerKeyCtr = 0;
m_nClientInBitCtr = 0;
m_vClientInputGate.clear();
m_vANDGates.clear();
m_vOutputShareGates.clear();
m_vServerOutputGates.clear();
//cout << "Output ctr: " << m_nOutputDestionationsCtr << endl;
if(m_nOutputDestionationsCtr>0)
free(m_vOutputDestionations);
m_nOutputDestionationsCtr = 0;
m_nANDGates = 0;
m_nXORGates = 0;
m_nInputShareSndSize = 0;
m_nOutputShareSndSize = 0;
m_nInputShareRcvSize = 0;
m_nOutputShareRcvSize = 0;
m_nConversionInputBits = 0;
m_nClientInputBits = 0;
m_vClientInputKeys.delCBitVector();
m_nServerInputBits = 0;
m_vServerInputKeys.delCBitVector();
m_vGarbledCircuit.delCBitVector();
m_nGarbledTableCtr = 0;
m_cBoolCircuit->Reset();
}
| 37.24015 | 204 | 0.70326 | [
"vector"
] |
1501b26adc0e8b5a2f2f85d4b60482b6a776f189 | 875 | cpp | C++ | Code/LeetCode/Best Time to Buy and Sell Stock IV/Best Time to Buy and Sell Stock IV/main.cpp | myhgew/CodePractice | c3313623d973192d6c2f20255bb01088b970ee80 | [
"MIT"
] | null | null | null | Code/LeetCode/Best Time to Buy and Sell Stock IV/Best Time to Buy and Sell Stock IV/main.cpp | myhgew/CodePractice | c3313623d973192d6c2f20255bb01088b970ee80 | [
"MIT"
] | null | null | null | Code/LeetCode/Best Time to Buy and Sell Stock IV/Best Time to Buy and Sell Stock IV/main.cpp | myhgew/CodePractice | c3313623d973192d6c2f20255bb01088b970ee80 | [
"MIT"
] | null | null | null | //
// main.cpp
// Best Time to Buy and Sell Stock IV
//
// Created by yuhumai on 3/3/15.
// Copyright (c) 2015 yuhumai. All rights reserved.
//
/*
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
*/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxProfit(int k, vector<int> &prices) {
return 0;
}
};
int main(int argc, const char * argv[]) {
int initData[] = {3,1,4,2,5};
vector<int> *data = new vector<int>(initData, initData + sizeof(initData)/sizeof(int));
int k = 2;
cout << Solution().maxProfit(k, *data) << endl;
return 0;
}
| 21.875 | 113 | 0.658286 | [
"vector"
] |
15028f059d5d76c62717c9268266c3d722ec4f67 | 2,192 | cpp | C++ | dataset/test/modification/1487_code_insertion/43/transformation_1.cpp | Karina5005/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | 3 | 2022-02-15T00:29:39.000Z | 2022-03-15T08:36:44.000Z | dataset/test/modification/1487_code_insertion/43/transformation_1.cpp | Kira5005-code/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | null | null | null | dataset/test/modification/1487_code_insertion/43/transformation_1.cpp | Kira5005-code/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<long long,long long> pll;
typedef vector<long long> fll;
typedef vector<int> fi;
#define pb push_back
#define in cin
#define out cout
#define fektor vector
#define ma max
#define si size
#define all(f) f.begin(),f.end()
#define rall(f) f.rbegin(),f.rend()
#define F first
#define S second
#define what(a) cout<<(#a)<<" is "<<(a)<<'\n';
#define meow out<<"____________________________________________\n";
const int MOD = 1e9 + 7 ;
ll power( ll a , ll b )
{
ll ret=1;
if (5 > 3) cout << "new code";while(b){
if (5 > 3) cout << "new code";if(b&1)ret=(ret*a);
b>>=1;a=(a*a);
}
return ret;
}
ll power2( ll a , ll b )
{
if (5 > 3) cout << "new code";if( b == 0 ) return 1 ;
ll s = power2( a , b / 2 ) ;
s *= s ;
if (5 > 3) cout << "new code";if( b & 1 ) s *= a ;
return s ;
}
ll seil( ll a , ll b ){ return ( a + b - 1 ) / b ; }
ll gsd( ll a , ll b )
{
if (5 > 3) cout << "new code";if( b == 0 )return a;
if (5 > 3) cout << "new code";if( a == 0 )return b;
return gsd( b , a % b ) ;
}
ll lsm( ll a , ll b ) { return a * b / gsd( a , b ) ; }
bool sortonsekond( const pii &a , const pii &b )
{
if (5 > 3) cout << "new code";if( a.F == b.F ) return a.S > b.S;
return a.F < b.F;
}
bool isPrime( int a )
{
if (5 > 3) cout << "new code";if( a < 2 )return false;
if (5 > 3) cout << "new code";if( a == 2 ) return true ;
if (5 > 3) cout << "new code";for( ll i = 3 ; i * i <= a ; i += 2 )
{
if (5 > 3) cout << "new code";if( a % i == 0 )return false;
}
return true;
}
//bool inGrid( int i , int j ){return ( 0 <= i && i < n && 0 <= j && j < m ) ;}
void solve()
{
// freopen( "billboard.in" , "r" , stdin ) ;
// freopen( "billboard.out" , "w" , stdout ) ;
int n ; in >> n ;
int sq = sqrt( 2 * n - 1 ) ;
out << ( sq - 1 ) / 2 <<'\n' ;
return ;
}
int main()
{
ios_base::sync_with_stdio(NULL);
cin.tie(0);
int t=1;
in>>t;
if (5 > 3) cout << "new code";while( t-- )
{
solve() ;
}
return 0 ;
}
| 23.826087 | 79 | 0.50958 | [
"vector"
] |
1502e1b8c71d920b319cc252570406a10335931f | 3,680 | cpp | C++ | client/src/shader.cpp | cainzhou96/Gaia | a2f942d47d1d7d7b706fbd182469acc41eb535ca | [
"MIT"
] | null | null | null | client/src/shader.cpp | cainzhou96/Gaia | a2f942d47d1d7d7b706fbd182469acc41eb535ca | [
"MIT"
] | 33 | 2020-04-03T05:55:38.000Z | 2020-06-07T00:58:23.000Z | client/src/shader.cpp | cainzhou96/Gaia | a2f942d47d1d7d7b706fbd182469acc41eb535ca | [
"MIT"
] | 4 | 2020-04-02T18:32:18.000Z | 2022-02-06T21:36:41.000Z | #include "shader.h"
enum ShaderType { vertex, fragment, geometry };
GLuint LoadSingleShader(const char * shaderFilePath, ShaderType type)
{
// Create a shader id.
GLuint shaderID = 0;
if (shaderFilePath == NULL){
return 0;
}
if (type == vertex)
shaderID = glCreateShader(GL_VERTEX_SHADER);
else if (type == fragment)
shaderID = glCreateShader(GL_FRAGMENT_SHADER);
else if (type == geometry)
shaderID = glCreateShader(GL_GEOMETRY_SHADER);
// Try to read shader codes from the shader file.
std::string shaderCode;
std::ifstream shaderStream(shaderFilePath, std::ios::in);
if (shaderStream.is_open())
{
std::string Line = "";
while (getline(shaderStream, Line))
shaderCode += "\n" + Line;
shaderStream.close();
}
else
{
std::cerr << "Impossible to open " << shaderFilePath << ". "
<< "Check to make sure the file exists and you passed in the "
<< "right filepath!"
<< std::endl;
return 0;
}
GLint Result = GL_FALSE;
int InfoLogLength;
// Compile Shader.
std::cerr << "Compiling shader: " << shaderFilePath << std::endl;
char const * sourcePointer = shaderCode.c_str();
glShaderSource(shaderID, 1, &sourcePointer, NULL);
glCompileShader(shaderID);
// Check Shader.
glGetShaderiv(shaderID, GL_COMPILE_STATUS, &Result);
glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if (InfoLogLength > 0)
{
std::vector<char> shaderErrorMessage(InfoLogLength + 1);
glGetShaderInfoLog(shaderID, InfoLogLength, NULL, shaderErrorMessage.data());
std::string msg(shaderErrorMessage.begin(), shaderErrorMessage.end());
std::cerr << msg << std::endl;
return 0;
}
else
{
if (type == vertex)
printf("Successfully compiled vertex shader!\n");
else if (type == fragment)
printf("Successfully compiled fragment shader!\n");
else if (type == geometry)
printf("Successfully compiled geometry shader!\n");
}
return shaderID;
}
GLuint LoadShaders(const char * vertexFilePath, const char * fragmentFilePath,
const char * geometryFilePath)
{
// Create the vertex shader and fragment shader.
GLuint vertexShaderID = LoadSingleShader(vertexFilePath, vertex);
GLuint fragmentShaderID = LoadSingleShader(fragmentFilePath, fragment);
GLuint geometryShaderID = LoadSingleShader(geometryFilePath, geometry);
// Check both shaders.
if (vertexShaderID == 0 || fragmentShaderID == 0) return 0;
GLint Result = GL_FALSE;
int InfoLogLength;
// Link the program.
printf("Linking program\n");
GLuint programID = glCreateProgram();
glAttachShader(programID, vertexShaderID);
if (geometryShaderID){
glAttachShader(programID, geometryShaderID);
}
glAttachShader(programID, fragmentShaderID);
glLinkProgram(programID);
// Check the program.
glGetProgramiv(programID, GL_LINK_STATUS, &Result);
glGetProgramiv(programID, GL_INFO_LOG_LENGTH, &InfoLogLength);
if (InfoLogLength > 0)
{
std::vector<char> ProgramErrorMessage(InfoLogLength + 1);
glGetProgramInfoLog(programID, InfoLogLength, NULL, ProgramErrorMessage.data());
std::string msg(ProgramErrorMessage.begin(), ProgramErrorMessage.end());
std::cerr << msg << std::endl;
glDeleteProgram(programID);
return 0;
}
else
{
printf("Successfully linked program!\n");
}
// Detach and delete the shaders as they are no longer needed.
glDetachShader(programID, vertexShaderID);
glDetachShader(programID, fragmentShaderID);
glDeleteShader(vertexShaderID);
glDeleteShader(fragmentShaderID);
if (geometryShaderID){
glDetachShader(programID, geometryShaderID);
glDeleteShader(geometryShaderID);
}
return programID;
}
| 28.976378 | 82 | 0.711685 | [
"geometry",
"vector"
] |
15040fff4e647e9c064208c438ded070418f6191 | 20,778 | hpp | C++ | src/blas/impl/KokkosBlas1_axpby_spec.hpp | NexGenAnalytics/kokkos-kernels | 8381db0486674c1be943de23974821ddfb9e6c29 | [
"BSD-3-Clause"
] | null | null | null | src/blas/impl/KokkosBlas1_axpby_spec.hpp | NexGenAnalytics/kokkos-kernels | 8381db0486674c1be943de23974821ddfb9e6c29 | [
"BSD-3-Clause"
] | 7 | 2020-05-04T16:43:08.000Z | 2022-01-13T16:31:17.000Z | src/blas/impl/KokkosBlas1_axpby_spec.hpp | NexGenAnalytics/kokkos-kernels | 8381db0486674c1be943de23974821ddfb9e6c29 | [
"BSD-3-Clause"
] | null | null | null | /*
//@HEADER
// ************************************************************************
//
// Kokkos v. 3.0
// Copyright (2020) National Technology & Engineering
// Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE
// 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.
//
// Questions? Contact Siva Rajamanickam (srajama@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#ifndef KOKKOS_BLAS1_AXPBY_SPEC_HPP_
#define KOKKOS_BLAS1_AXPBY_SPEC_HPP_
#include "KokkosKernels_config.h"
#include "Kokkos_Core.hpp"
#include "Kokkos_InnerProductSpaceTraits.hpp"
#if !defined(KOKKOSKERNELS_ETI_ONLY) || KOKKOSKERNELS_IMPL_COMPILE_LIBRARY
#include<KokkosBlas1_axpby_impl.hpp>
#include<KokkosBlas1_axpby_mv_impl.hpp>
#endif
namespace KokkosBlas {
namespace Impl {
// Specialization struct which defines whether a specialization exists
template<class AV, class XMV, class BV, class YMV, int rank = YMV::Rank>
struct axpby_eti_spec_avail {
enum : bool { value = false };
};
}
}
//
// Macro for declaration of full specialization availability
// KokkosBlas::Impl::Axpby for rank == 1. This is NOT for users!!! All
// the declarations of full specializations go in this header file.
// We may spread out definitions (see _INST macro below) across one or
// more .cpp files.
//
#define KOKKOSBLAS1_AXPBY_ETI_SPEC_AVAIL( SCALAR, LAYOUT, EXEC_SPACE, MEM_SPACE ) \
template<> \
struct axpby_eti_spec_avail< \
SCALAR, \
Kokkos::View<const SCALAR*, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
SCALAR, \
Kokkos::View<SCALAR*, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
1> { enum : bool { value = true }; };
//
// Macro for declaration of full specialization availability
// KokkosBlas::Impl::Axpby for rank == 2. This is NOT for users!!! All
// the declarations of full specializations go in this header file.
// We may spread out definitions (see _INST macro below) across one or
// more .cpp files.
//
#define KOKKOSBLAS1_AXPBY_MV_ETI_SPEC_AVAIL( SCALAR, LAYOUT, EXEC_SPACE, MEM_SPACE ) \
template<> \
struct axpby_eti_spec_avail< \
SCALAR, \
Kokkos::View<const SCALAR**, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
SCALAR, \
Kokkos::View<SCALAR**, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
2> { enum : bool { value = true }; }; \
template<> \
struct axpby_eti_spec_avail< \
Kokkos::View<const SCALAR*, Kokkos::LayoutLeft, Kokkos::Device<EXEC_SPACE, MEM_SPACE>,\
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
Kokkos::View<const SCALAR**, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
Kokkos::View<const SCALAR*, Kokkos::LayoutLeft, Kokkos::Device<EXEC_SPACE, MEM_SPACE>,\
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
Kokkos::View<SCALAR**, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
2> { enum : bool { value = true }; };
// Include the actual specialization declarations
#include<KokkosBlas1_axpby_tpl_spec_avail.hpp>
#include<generated_specializations_hpp/KokkosBlas1_axpby_eti_spec_avail.hpp>
#include<generated_specializations_hpp/KokkosBlas1_axpby_mv_eti_spec_avail.hpp>
namespace KokkosBlas {
namespace Impl {
//
// axpby
//
/// \brief Implementation of KokkosBlas::axpby for (multi)vectors.
///
/// Compute any of the following, depending on the types of the input
/// arguments of axpxy():
///
/// 1. Y(i,j) = av(j)*X(i,j) + bv(j)*Y(i,j) (if R, X, and Y are 2-D,
/// and av and bv are 1-D)
///
/// 2. Y(i,j) = av*X(i,j) + bv*Y(i,j) (if R, X, and Y are 2-D,
/// and av and bv are scalars)
///
/// 3. Y(i) = av()*X(i) + bv()*Y(i) (if R, X, and Y are 1-D, and av
/// and bv are 0-D Views (not scalars))
///
/// 4. Y(i) = av*X(i) + bv*Y(i) (if R, X, and Y are 1-D, and av and bv
/// are scalars)
///
/// Any <i>scalar</i> coefficient of zero has BLAS semantics of
/// ignoring the corresponding (multi)vector entry. This does NOT
/// apply to coefficients in av and bv vectors, if they are used.
template<class AV, class XMV, class BV, class YMV, int rank = YMV::Rank,
bool tpl_spec_avail = axpby_tpl_spec_avail<AV,XMV,BV,YMV>::value,
bool eti_spec_avail = axpby_eti_spec_avail<AV,XMV,BV,YMV>::value>
struct Axpby {
static void axpby (const AV& av, const XMV& X, const BV& bv, const YMV& Y);
};
template<class AV, class XMV, class BV, class YMV>
struct Axpby<AV,XMV,BV,YMV,0,true,true> {
static void axpby (const AV& /* av */, const XMV& /* X */, const BV& /* bv */, const YMV& /* Y */) {
static_assert(YMV::Rank==0,"Oh My God");
}
};
#if !defined(KOKKOSKERNELS_ETI_ONLY) || KOKKOSKERNELS_IMPL_COMPILE_LIBRARY
// Full specialization for XMV and YMV rank-2 Views.
template<class AV, class XMV, class BV, class YMV>
struct Axpby<AV, XMV, BV, YMV, 2, false, KOKKOSKERNELS_IMPL_COMPILE_LIBRARY>
{
typedef typename YMV::size_type size_type;
static void
axpby (const AV& av, const XMV& X, const BV& bv, const YMV& Y)
{
static_assert (Kokkos::Impl::is_view<XMV>::value, "KokkosBlas::Impl::"
"Axpby<rank-2>::axpby: X is not a Kokkos::View.");
static_assert (Kokkos::Impl::is_view<YMV>::value, "KokkosBlas::Impl::"
"Axpby<rank-2>::axpby: Y is not a Kokkos::View.");
static_assert (std::is_same<typename YMV::value_type,
typename YMV::non_const_value_type>::value,
"KokkosBlas::Impl::Axpby<rank-2>::axpby: Y is const. "
"It must be nonconst, because it is an output argument "
"(we have to be able to write to its entries).");
static_assert ((int) YMV::Rank == (int) XMV::Rank,
"KokkosBlas::Impl::Axpby<rank-2>::axpby (MV): "
"X and Y must have the same rank.");
static_assert (YMV::Rank == 2, "KokkosBlas::Impl::Axpby<rank-2>::axpby: "
"X and Y must have rank 2.");
Kokkos::Profiling::pushRegion(KOKKOSKERNELS_IMPL_COMPILE_LIBRARY?"KokkosBlas::axpby[ETI]":"KokkosBlas::axpby[noETI]");
#ifdef KOKKOSKERNELS_ENABLE_CHECK_SPECIALIZATION
if(KOKKOSKERNELS_IMPL_COMPILE_LIBRARY)
printf("KokkosBlas1::axpby<> ETI specialization for < %s , %s , %s , %s >\n",typeid(AV).name(),typeid(XMV).name(),typeid(BV).name(),typeid(YMV).name());
else {
printf("KokkosBlas1::axpby<> non-ETI specialization for < %s , %s , %s , %s >\n",typeid(AV).name(),typeid(XMV).name(),typeid(BV).name(),typeid(YMV).name());
}
#endif
const size_type numRows = X.extent(0);
const size_type numCols = X.extent(1);
int a = 2, b = 2;
if (av.extent(0) == 0) {
a = 0;
}
if (bv.extent(0) == 0) {
b = 0;
}
if (numRows < static_cast<size_type> (INT_MAX) &&
numRows * numCols < static_cast<size_type> (INT_MAX)) {
typedef int index_type;
typedef typename std::conditional<std::is_same<typename XMV::array_layout,Kokkos::LayoutLeft>::value,
Axpby_MV_Invoke_Right<AV, XMV, BV, YMV, index_type>,
Axpby_MV_Invoke_Left<AV, XMV, BV, YMV, index_type> >::type Axpby_MV_Invoke_Layout;
Axpby_MV_Invoke_Layout::run(av, X, bv, Y, a, b);
}
else {
typedef typename XMV::size_type index_type;
typedef typename std::conditional<std::is_same<typename XMV::array_layout,Kokkos::LayoutLeft>::value,
Axpby_MV_Invoke_Right<AV, XMV, BV, YMV, index_type>,
Axpby_MV_Invoke_Left<AV, XMV, BV, YMV, index_type> >::type Axpby_MV_Invoke_Layout;
Axpby_MV_Invoke_Layout::run(av, X, bv, Y, a, b);
}
Kokkos::Profiling::popRegion();
}
};
// Partial specialization for XMV, and YMV rank-2 Views,
// and AV and BV scalars.
template<class XMV, class YMV>
struct Axpby<typename XMV::non_const_value_type, XMV,
typename YMV::non_const_value_type, YMV, 2, false, KOKKOSKERNELS_IMPL_COMPILE_LIBRARY >
{
typedef typename XMV::non_const_value_type AV;
typedef typename YMV::non_const_value_type BV;
typedef typename YMV::size_type size_type;
typedef Kokkos::Details::ArithTraits<typename XMV::non_const_value_type> ATA;
typedef Kokkos::Details::ArithTraits<typename YMV::non_const_value_type> ATB;
static void
axpby (const AV& alpha, const XMV& X, const BV& beta, const YMV& Y)
{
static_assert (Kokkos::Impl::is_view<XMV>::value,
"KokkosBlas::Impl::Axpby::axpby (MV): "
"X is not a Kokkos::View.");
static_assert (Kokkos::Impl::is_view<YMV>::value,
"KokkosBlas::Impl::Axpby::axpby (MV): "
"Y is not a Kokkos::View.");
static_assert (std::is_same<typename YMV::value_type,
typename YMV::non_const_value_type>::value,
"KokkosBlas::Impl::Axpby::axpby (MV): Y is const. "
"It must be nonconst, because it is an output argument "
"(we have to be able to write to its entries).");
static_assert ((int) YMV::Rank == (int) XMV::Rank,
"KokkosBlas::Impl::Axpby::axpby (MV): "
"X and Y must have the same rank.");
static_assert (YMV::Rank == 2, "KokkosBlas::Impl::Axpby::axpby (MV): "
"X and Y must have rank 2.");
Kokkos::Profiling::pushRegion(KOKKOSKERNELS_IMPL_COMPILE_LIBRARY?"KokkosBlas::axpby[ETI]":"KokkosBlas::axpby[noETI]");
#ifdef KOKKOSKERNELS_ENABLE_CHECK_SPECIALIZATION
if(KOKKOSKERNELS_IMPL_COMPILE_LIBRARY)
printf("KokkosBlas1::axpby<> ETI specialization for < %s , %s , %s , %s >\n",typeid(AV).name(),typeid(XMV).name(),typeid(BV).name(),typeid(YMV).name());
else {
printf("KokkosBlas1::axpby<> non-ETI specialization for < %s , %s , %s , %s >\n",typeid(AV).name(),typeid(XMV).name(),typeid(BV).name(),typeid(YMV).name());
}
#endif
const size_type numRows = X.extent(0);
const size_type numCols = X.extent(1);
int a, b;
if (alpha == ATA::zero ()) {
a = 0;
}
#if KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY > 2
else if (alpha == -ATA::one ()) {
a = -1;
}
else if (alpha == ATA::one ()) {
a = 1;
}
#endif // KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY > 2
else {
a = 2;
}
if (beta == ATB::zero ()) {
b = 0;
}
#if KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY > 2
else if (beta == -ATB::one ()) {
b = -1;
}
else if (beta == ATB::one ()) {
b = 1;
}
#endif // KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY > 2
else {
b = 2;
}
if (numRows < static_cast<size_type> (INT_MAX) &&
numRows * numCols < static_cast<size_type> (INT_MAX)) {
typedef int index_type;
typedef typename std::conditional<std::is_same<typename XMV::array_layout,Kokkos::LayoutLeft>::value,
Axpby_MV_Invoke_Right<AV, XMV, BV, YMV, index_type>,
Axpby_MV_Invoke_Left<AV, XMV, BV, YMV, index_type> >::type Axpby_MV_Invoke_Layout;
Axpby_MV_Invoke_Layout::run(alpha, X,
beta, Y, a, b);
}
else {
typedef typename XMV::size_type index_type;
typedef typename std::conditional<std::is_same<typename XMV::array_layout,Kokkos::LayoutLeft>::value,
Axpby_MV_Invoke_Right<AV, XMV, BV, YMV, index_type>,
Axpby_MV_Invoke_Left<AV, XMV, BV, YMV, index_type> >::type Axpby_MV_Invoke_Layout;
Axpby_MV_Invoke_Layout::run(alpha, X,
beta, Y, a, b);
}
Kokkos::Profiling::popRegion();
}
};
// Partial specialization for XV and YV rank-1 Views,
// and AV and BV scalars.
template<class XV, class YV>
struct Axpby<typename XV::non_const_value_type, XV,
typename YV::non_const_value_type, YV, 1, false, KOKKOSKERNELS_IMPL_COMPILE_LIBRARY>
{
typedef typename XV::non_const_value_type AV;
typedef typename YV::non_const_value_type BV;
typedef typename YV::size_type size_type;
typedef Kokkos::Details::ArithTraits<typename XV::non_const_value_type> ATA;
typedef Kokkos::Details::ArithTraits<typename YV::non_const_value_type> ATB;
static void
axpby (const AV& alpha, const XV& X, const BV& beta, const YV& Y)
{
static_assert (Kokkos::Impl::is_view<XV>::value, "KokkosBlas::Impl::"
"Axpby<rank-1>::axpby: X is not a Kokkos::View.");
static_assert (Kokkos::Impl::is_view<YV>::value, "KokkosBlas::Impl::"
"Axpby<rank-1>::axpby: Y is not a Kokkos::View.");
static_assert (std::is_same<typename YV::value_type,
typename YV::non_const_value_type>::value,
"KokkosBlas::Impl::Axpby<rank-1>::axpby: Y is const. "
"It must be nonconst, because it is an output argument "
"(we have to be able to write to its entries).");
static_assert ((int) YV::Rank == (int) XV::Rank, "KokkosBlas::Impl::"
"Axpby<rank-1>::axpby: X and Y must have the same rank.");
static_assert (YV::Rank == 1, "KokkosBlas::Impl::Axpby<rank-1>::axpby: "
"X and Y must have rank 1.");
Kokkos::Profiling::pushRegion(KOKKOSKERNELS_IMPL_COMPILE_LIBRARY?"KokkosBlas::axpby[ETI]":"KokkosBlas::axpby[noETI]");
#ifdef KOKKOSKERNELS_ENABLE_CHECK_SPECIALIZATION
if(KOKKOSKERNELS_IMPL_COMPILE_LIBRARY)
printf("KokkosBlas1::axpby<> ETI specialization for < %s , %s , %s , %s >\n",typeid(AV).name(),typeid(XV).name(),typeid(BV).name(),typeid(YV).name());
else {
printf("KokkosBlas1::axpby<> non-ETI specialization for < %s , %s , %s , %s >\n",typeid(AV).name(),typeid(XV).name(),typeid(BV).name(),typeid(YV).name());
}
#endif
const size_type numRows = X.extent(0);
int a = 2;
if (alpha == ATA::zero ()) {
a = 0;
}
#if KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY > 2
else if (alpha == -ATA::one ()) {
a = -1;
}
else if (alpha == ATA::one ()) {
a = 1;
}
#endif // KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY > 2
int b = 2;
if (beta == ATB::zero ()) {
b = 0;
}
#if KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY > 2
else if (beta == -ATB::one ()) {
b = -1;
}
else if (beta == ATB::one ()) {
b = 1;
}
#endif // KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY > 2
if (numRows < static_cast<size_type> (INT_MAX)) {
typedef int index_type;
Axpby_Generic<typename XV::non_const_value_type, XV,
typename YV::non_const_value_type, YV,
index_type> (alpha, X, beta, Y, 0, a, b);
}
else {
typedef typename XV::size_type index_type;
Axpby_Generic<typename XV::non_const_value_type, XV,
typename YV::non_const_value_type, YV,
index_type> (alpha, X, beta, Y, 0, a, b);
}
Kokkos::Profiling::popRegion();
}
};
#endif //!defined(KOKKOSKERNELS_ETI_ONLY) || KOKKOSKERNELS_IMPL_COMPILE_LIBRARY
} // namespace Impl
} // namespace KokkosBlas
//
// Macro for declaration of full specialization of
// KokkosBlas::Impl::Axpby for rank == 1. This is NOT for users!!!
// All the declarations of full specializations go in this header
// file. We may spread out definitions (see _INST macro below) across
// one or more .cpp files.
//
#define KOKKOSBLAS1_AXPBY_ETI_SPEC_DECL( SCALAR, LAYOUT, EXEC_SPACE, MEM_SPACE ) \
extern template struct Axpby< \
SCALAR, \
Kokkos::View<const SCALAR*, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
SCALAR, \
Kokkos::View<SCALAR*, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
1, false, true>;
#define KOKKOSBLAS1_AXPBY_ETI_SPEC_INST( SCALAR, LAYOUT, EXEC_SPACE, MEM_SPACE ) \
template struct Axpby< \
SCALAR, \
Kokkos::View<const SCALAR*, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
SCALAR, \
Kokkos::View<SCALAR*, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
1, false, true>;
//
// Macro for declaration of full specialization of
// KokkosBlas::Impl::Axpby for rank == 2. This is NOT for users!!!
// All the declarations of full specializations go in this header
// file. We may spread out definitions (see _DEF macro below) across
// one or more .cpp files.
//
#define KOKKOSBLAS1_AXPBY_MV_ETI_SPEC_DECL( SCALAR, LAYOUT, EXEC_SPACE, MEM_SPACE ) \
extern template struct Axpby< \
SCALAR, \
Kokkos::View<const SCALAR**, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
SCALAR, \
Kokkos::View<SCALAR**, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
2, false, true>; \
extern template struct Axpby< \
Kokkos::View<const SCALAR*, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>,\
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
Kokkos::View<const SCALAR**, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
Kokkos::View<const SCALAR*, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>,\
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
Kokkos::View<SCALAR**, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
2, false, true>;
#define KOKKOSBLAS1_AXPBY_MV_ETI_SPEC_INST( SCALAR, LAYOUT, EXEC_SPACE, MEM_SPACE ) \
template struct Axpby< \
SCALAR, \
Kokkos::View<const SCALAR**, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
SCALAR, \
Kokkos::View<SCALAR**, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
2, false, true>; \
template struct Axpby< \
Kokkos::View<const SCALAR*, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>,\
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
Kokkos::View<const SCALAR**, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
Kokkos::View<const SCALAR*, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>,\
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
Kokkos::View<SCALAR**, LAYOUT, Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >, \
2, false, true>;
#include<KokkosBlas1_axpby_tpl_spec_decl.hpp>
#include<generated_specializations_hpp/KokkosBlas1_axpby_eti_spec_decl.hpp>
#include<generated_specializations_hpp/KokkosBlas1_axpby_mv_eti_spec_decl.hpp>
#endif // KOKKOS_BLAS1_MV_IMPL_AXPBY_HPP_
| 42.841237 | 162 | 0.641833 | [
"vector"
] |
1504d516884eb5036c61c4c01e949048ab3f8742 | 7,389 | cpp | C++ | deprecated_compiler/main.cpp | Limvot/kraken | 6e5a372f07a864555c0e6492de4f46ffab75bfe7 | [
"MIT"
] | 14 | 2015-12-28T10:33:33.000Z | 2022-03-29T04:04:52.000Z | deprecated_compiler/main.cpp | Limvot/kraken | 6e5a372f07a864555c0e6492de4f46ffab75bfe7 | [
"MIT"
] | 3 | 2016-04-20T23:10:09.000Z | 2022-01-30T21:59:56.000Z | deprecated_compiler/main.cpp | Limvot/kraken | 6e5a372f07a864555c0e6492de4f46ffab75bfe7 | [
"MIT"
] | 1 | 2016-04-20T01:02:53.000Z | 2016-04-20T01:02:53.000Z | #include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include "NodeTree.h"
#include "Symbol.h"
#include "Lexer.h"
#include "RNGLRParser.h"
#include "Importer.h"
#include "ASTData.h"
#include "CGenerator.h"
#include "Poset.h"
#include "util.h"
#include "Tester.h"
int main(int argc, char* argv[]) {
std::vector<std::string> includePaths;
includePaths.push_back(""); //Local
if (argc <= 1) {
std::cerr << "Kraken invocation: kraken sourceFile.krak" << std::endl;
std::cerr << "Kraken invocation: kraken sourceFile.krak outputName" << std::endl;
std::cerr << "Kraken invocation: kraken grammerFile.kgm sourceFile.krak outputName" << std::endl;
std::cerr << "Or for testing do: kraken --test [optional list of names of file (.krak .expected_results) without extentions to run]" << std::endl;
return 0;
}
std::string grammerFileString = "../krakenGrammer.kgm";
if (argc >= 2 && std::string(argv[1]) == "--test") {
StringReader::test();
RegEx::test();
Lexer::test();
//std::cout << strSlice("123", 0, -1) << std::endl;
Poset<int>::test();
if (argc >= 3) {
std::string testResults, line;
int passed = 0, failed = 0;
Tester test(argv[0], grammerFileString);
// find the max length so we can pad the string and align the results
unsigned int maxLineLength = 0;
for (int i = 2; i < argc; i++) {
int strLen = std::string(argv[i]).length();
maxLineLength = maxLineLength < strLen ? strLen : maxLineLength;
}
for (int i = 2; i < argc; i++) {
bool result = test.run(argv[i]);
if (result)
line = padWithSpaces(std::string(argv[i]), maxLineLength) + "\t\tpassed!\n", passed++;
else
line = padWithSpaces(std::string(argv[i]), maxLineLength) + "\t\tFAILED!!!!\n", failed++;
std::cout << line << std::endl;
testResults += line;
}
std::cout << "===========Done Testing===========" << std::endl;
std::cout << testResults << std::endl;
std::cout << "Test results: " << passed << "/" << passed+failed << std::endl;
}
return 0;
}
std::string krakenDir = argv[0];
krakenDir = strSlice(krakenDir, 0, -(std::string("kraken").length()+1));
includePaths.push_back(krakenDir + "stdlib/"); //Add the stdlib directory that exists in the same directory as the kraken executable to the path
std::string programName;
std::string outputName;
bool parse_only = false;
//std::cout << "argv[1] == " << argv[1] << std::endl;
if (std::string(argv[1]) == "--parse-only") {
parse_only = true;
grammerFileString = argv[2];
programName = argv[3];
//outputName = argv[3];
} else if (argc > 3) {
grammerFileString = argv[1];
programName = argv[2];
outputName = argv[3];
} else if (argc == 3) {
programName = argv[1];
outputName = argv[2];
} else {
programName = argv[1];
outputName = join(slice(split(programName, '.'), 0, -2), "."); // without extension
}
std::ifstream grammerInFile, compiledGrammerInFile;
std::ofstream compiledGrammerOutFile;
grammerInFile.open(grammerFileString);
if (!grammerInFile.is_open()) {
std::cerr << "Problem opening grammerInFile " << grammerFileString << "\n";
return(1);
}
compiledGrammerInFile.open(grammerFileString + ".comp", std::ios::binary | std::ios::ate);
if (!compiledGrammerInFile.is_open())
std::cerr << "Problem opening compiledGrammerInFile " << grammerFileString + ".comp" << "\n";
//Read the input file into a string
std::string grammerInputFileString;
std::string line;
while(grammerInFile.good()) {
getline(grammerInFile, line);
grammerInputFileString.append(line+"\n");
}
grammerInFile.close();
RNGLRParser parser;
parser.loadGrammer(grammerInputFileString);
//Start binary stuff
bool compGramGood = false;
if (compiledGrammerInFile.is_open()) {
//std::cout << "Compiled grammer file exists, reading it in" << std::endl;
std::streampos compGramSize = compiledGrammerInFile.tellg();
char* binaryTablePointer = new char [compGramSize];
compiledGrammerInFile.seekg(0, std::ios::beg);
compiledGrammerInFile.read(binaryTablePointer, compGramSize);
compiledGrammerInFile.close();
//Check magic number
if (binaryTablePointer[0] == 'K' && binaryTablePointer[1] == 'R' && binaryTablePointer[2] == 'A' && binaryTablePointer[3] == 'K') {
//std::cout << "Valid Kraken Compiled Grammer File" << std::endl;
int gramStringLength = *((int*)(binaryTablePointer+4));
//std::cout << "The grammer string is stored to be " << gramStringLength << " characters long, gramString is "
//<< grammerInputFileString.length() << " long. Remember 1 extra for null terminator!" << std::endl;
if (grammerInputFileString.length() != gramStringLength-1 ||
(strncmp(grammerInputFileString.c_str(), (binaryTablePointer+4+sizeof(int)), gramStringLength) != 0)) {
//(one less for null terminator that is stored)
std::cout << "The Grammer has been changed, will re-create" << std::endl;
} else {
compGramGood = true;
//std::cout << "Grammer file is up to date." << std::endl;
parser.importTable(binaryTablePointer + 4 + sizeof(int) + gramStringLength); //Load table starting at the table section
}
} else {
std::cerr << grammerFileString << ".comp is NOT A Valid Kraken Compiled Grammer File, aborting" << std::endl;
return -1;
}
delete [] binaryTablePointer;
}
if (!compGramGood) {
//The load failed because either the file does not exist or it is not up-to-date.
std::cout << "Compiled grammer file does not exist or is not up-to-date, generating table and writing it out" << std::endl;
compiledGrammerOutFile.open(grammerFileString + ".comp", std::ios::binary);
if (!compiledGrammerOutFile.is_open())
std::cerr << "Could not open compiled file to write either!" << std::endl;
compiledGrammerOutFile.write("KRAK", sizeof(char)*4); //Let us know when we load it that this is a kraken grammer file, but don't write out
compiledGrammerOutFile.flush(); // the grammer txt until we create the set, so that if we fail creating it it won't look valid
parser.createStateSet();
int* intBuffer = new int;
*intBuffer = grammerInputFileString.length()+1;
compiledGrammerOutFile.write((char*)intBuffer, sizeof(int));
delete intBuffer;
compiledGrammerOutFile.write(grammerInputFileString.c_str(), grammerInputFileString.length()+1); //Don't forget null terminator
parser.exportTable(compiledGrammerOutFile);
compiledGrammerOutFile.close();
}
//End binary stuff
//std::cout << "\nParsing" << std::endl;
//std::cout << "\toutput name: " << outputName << std::endl;
//std::cout << "\tprogram name: " << programName << std::endl;
Importer importer(&parser, includePaths, outputName, parse_only); // Output name for directory to put stuff in
//for (auto i : includePaths)
//std::cout << i << std::endl;
importer.import(programName);
std::map<std::string, NodeTree<ASTData>*> ASTs = importer.getASTMap();
if (parse_only)
return 0;
//Do optimization, etc. here.
//None at this time, instead going straight to C in this first (more naive) version
//Code generation
//For right now, just C
// return code from calling C compiler
return CGenerator().generateCompSet(ASTs, outputName);
}
| 38.685864 | 154 | 0.660441 | [
"vector"
] |
15063228698f2fb40de787b5c133e7f0f702b76e | 30,785 | cpp | C++ | src/nvisii/texture.cpp | blaine141/NVISII | 1675bb9bb74a1fe441bbb10ca98ea5cc4b0e4e24 | [
"Apache-2.0"
] | null | null | null | src/nvisii/texture.cpp | blaine141/NVISII | 1675bb9bb74a1fe441bbb10ca98ea5cc4b0e4e24 | [
"Apache-2.0"
] | null | null | null | src/nvisii/texture.cpp | blaine141/NVISII | 1675bb9bb74a1fe441bbb10ca98ea5cc4b0e4e24 | [
"Apache-2.0"
] | null | null | null | #include <nvisii/texture.h>
#include <nvisii/light.h>
#include <nvisii/material.h>
#include <stb_image.h>
#include <stb_image_write.h>
#include <cstring>
#include <algorithm>
#include <gli/gli.hpp>
#include <gli/convert.hpp>
#include <gli/core/s3tc.hpp>
#include <glm/gtc/color_space.hpp>
namespace nvisii {
std::vector<Texture> Texture::textures;
std::vector<TextureStruct> Texture::textureStructs;
std::map<std::string, uint32_t> Texture::lookupTable;
std::shared_ptr<std::recursive_mutex> Texture::editMutex;
bool Texture::factoryInitialized = false;
std::set<Texture*> Texture::dirtyTextures;
Texture::Texture()
{
this->initialized = false;
}
Texture::~Texture()
{
std::vector<glm::vec4>().swap(this->floatTexels);
std::vector<glm::u8vec4>().swap(this->byteTexels);
}
Texture::Texture(std::string name, uint32_t id)
{
this->initialized = true;
this->name = name;
this->id = id;
textureStructs[id].width = -1;
textureStructs[id].height = -1;
this->floatTexels = std::vector<vec4>();
this->byteTexels = std::vector<u8vec4>();
}
std::string Texture::toString() {
std::string output;
output += "{\n";
output += "\ttype: \"Texture\",\n";
output += "\tname: \"" + name + "\"\n";
output += "}";
return output;
}
std::vector<vec4> Texture::getFloatTexels() {
// If natively represented as 32f, return that.
// otherwise, cast 8uc to 32f.
if (floatTexels.size() > 0) return floatTexels;
std::vector<vec4> floatTexels(byteTexels.size());
for (uint32_t i = 0; i < byteTexels.size(); ++i) {
floatTexels[i] = vec4(byteTexels[i]) / 255.0f;
}
return floatTexels;
}
std::vector<u8vec4> Texture::getByteTexels() {
// If natively represented as 8uc, return that.
// otherwise, cast 32f to 8uc.
if (byteTexels.size() > 0) return byteTexels;
std::vector<u8vec4> texels8(floatTexels.size());
for (uint32_t i = 0; i < floatTexels.size(); ++i) {
texels8[i] = u8vec4(floatTexels[i] * 255.0f);
}
return texels8;
}
uint32_t Texture::getWidth() {
return textureStructs[id].width;
}
uint32_t Texture::getHeight() {
return textureStructs[id].height;
}
void Texture::setScale(glm::vec2 scale)
{
textureStructs[id].scale = scale;
markDirty();
}
bool Texture::isHDR()
{
// if the texture is natively represented as a 32 bit-per-channel texture, it's HDR.
return (floatTexels.size() > 0);
}
bool Texture::isLinear() {
return linear;
}
/* SSBO logic */
void Texture::initializeFactory(uint32_t max_components)
{
if (isFactoryInitialized()) return;
textures.resize(max_components);
textureStructs.resize(max_components);
editMutex = std::make_shared<std::recursive_mutex>();
factoryInitialized = true;
}
bool Texture::isFactoryInitialized()
{
return factoryInitialized;
}
bool Texture::isInitialized()
{
return initialized;
}
bool Texture::areAnyDirty()
{
return dirtyTextures.size() > 0;
}
void Texture::markDirty() {
if (getAddress() < 0 || getAddress() >= textures.size()) {
throw std::runtime_error("Error, texture not allocated in list");
}
dirtyTextures.insert(this);
auto materialPointers = Material::getFront();
for (auto &mid : materials) {
materialPointers[mid].markDirty();
}
auto lightPointers = Light::getFront();
for (auto &lid : lights) {
lightPointers[lid].markDirty();
}
};
std::set<Texture*> Texture::getDirtyTextures()
{
return dirtyTextures;
}
void Texture::updateComponents()
{
if (dirtyTextures.size() == 0) return;
dirtyTextures.clear();
}
void Texture::clearAll()
{
if (!isFactoryInitialized()) return;
for (auto &texture : textures) {
if (texture.initialized) {
Texture::remove(texture.name);
}
}
}
/* Static Factory Implementations */
Texture* Texture::createFromImage(std::string name, std::string path, bool linear) {
static bool createFromImageDeprecatedShown = false;
if (createFromImageDeprecatedShown == false) {
std::cout<<"Warning, create_from_image is deprecated and will be removed in a subsequent release. Please switch to create_from_file." << std::endl;
createFromImageDeprecatedShown = true;
}
return createFromFile(name, path, linear);
}
Texture* Texture::createFromFile(std::string name, std::string path, bool linear) {
auto create = [path, linear] (Texture* l) {
// first, check the extension
std::string extension = std::string(strrchr(path.c_str(), '.'));
std::transform(extension.data(), extension.data() + extension.size(),
std::addressof(extension[0]), [](unsigned char c){ return std::tolower(c); });
if ((extension.compare(".dds") == 0) || (extension.compare(".ktx") == 0)) {
auto texture = gli::load(path);
if (texture.target() != gli::target::TARGET_2D) {
std::string reason = "Currently only 2D textures supported!";
throw std::runtime_error(std::string("Error: failed to load texture image \"") +
path + std::string("\". Reason: ") + reason);
}
auto tex2D = gli::texture2d(texture);
auto format = tex2D.format();
if (tex2D.empty())
throw std::runtime_error( std::string("Error: image " + path + " is empty"));
// gli detects whether or not a texture is srgb. Ignore "linear" parameter above.
l->linear = (!gli::is_srgb(format));
if (gli::is_compressed(format)) {
if ((format != gli::FORMAT_RGBA_DXT1_UNORM_BLOCK8) &&
(format != gli::FORMAT_RGBA_DXT5_UNORM_BLOCK16) &&
(format != gli::FORMAT_R_ATI1N_UNORM_BLOCK8) &&
(format != gli::FORMAT_RG_ATI2N_UNORM_BLOCK16)
)
throw std::runtime_error(std::string("Error: image " + path + " is compressed using an unsupported S3TC format. " +
"Supported formats are " +
"FORMAT_RGBA32_SFLOAT_PACK32, " +
"FORMAT_RGBA8_SRGB_PACK8, " +
"FORMAT_R32_SFLOAT_PACK32, " +
"FORMAT_R8_SRGB_PACK8, " +
"FORMAT_RG32_SFLOAT_PACK32, " +
"FORMAT_RG8_SRGB_PACK8" +
"FORMAT_RGBA_DXT1_UNORM_BLOCK8, " +
"FORMAT_RGBA_DXT5_UNORM_BLOCK16, " +
"FORMAT_R_ATI1N_UNORM_BLOCK8, " +
"FORMAT_RG_ATI2N_UNORM_BLOCK16"));
// decompress RGBA DXT1
gli::texture2d &TextureCompressed = tex2D;
gli::texture2d TextureLocalDecompressed(
gli::FORMAT_RGBA32_SFLOAT_PACK32,
TextureCompressed.extent(),
TextureCompressed.levels(),
TextureCompressed.swizzles());
gli::extent2d BlockExtent;
{
gli::extent3d TempExtent = gli::block_extent(format);
BlockExtent.x = TempExtent.x;
BlockExtent.y = TempExtent.y;
}
for(size_t Level = 0; Level < TextureCompressed.levels(); ++Level) {
gli::extent2d TexelCoord, BlockCoord;
gli::extent2d LevelExtent = TextureCompressed.extent(Level);
gli::extent2d LevelExtentInBlocks = glm::max(gli::extent2d(1, 1), LevelExtent / BlockExtent);
gli::extent2d DecompressedBlockCoord;
for(BlockCoord.y = 0, TexelCoord.y = 0; BlockCoord.y < LevelExtentInBlocks.y; ++BlockCoord.y, TexelCoord.y += BlockExtent.y) {
for(BlockCoord.x = 0, TexelCoord.x = 0; BlockCoord.x < LevelExtentInBlocks.x; ++BlockCoord.x, TexelCoord.x += BlockExtent.x) {
if (format == gli::FORMAT_RGBA_DXT1_UNORM_BLOCK8) {
l->linear = false; // hack for buggy importer...
const gli::detail::dxt1_block *DXT1Block = TextureCompressed.data<gli::detail::dxt1_block>(0, 0, Level) + (BlockCoord.y * LevelExtentInBlocks.x + BlockCoord.x);
const gli::detail::texel_block4x4 DecompressedBlock = gli::detail::decompress_dxt1_block(*DXT1Block);
for(DecompressedBlockCoord.y = 0; DecompressedBlockCoord.y < glm::min(4, LevelExtent.y); ++DecompressedBlockCoord.y) {
for(DecompressedBlockCoord.x = 0; DecompressedBlockCoord.x < glm::min(4, LevelExtent.x); ++DecompressedBlockCoord.x) {
TextureLocalDecompressed.store(TexelCoord + DecompressedBlockCoord, Level, DecompressedBlock.Texel[DecompressedBlockCoord.y][DecompressedBlockCoord.x]);
}
}
}
else if (format == gli::FORMAT_RGBA_DXT5_UNORM_BLOCK16) {
l->linear = false; // hack for buggy importer...
const gli::detail::dxt5_block *DXT5Block = TextureCompressed.data<gli::detail::dxt5_block>(0, 0, Level) + (BlockCoord.y * LevelExtentInBlocks.x + BlockCoord.x);
const gli::detail::texel_block4x4 DecompressedBlock = gli::detail::decompress_dxt5_block(*DXT5Block);
for(DecompressedBlockCoord.y = 0; DecompressedBlockCoord.y < glm::min(4, LevelExtent.y); ++DecompressedBlockCoord.y) {
for(DecompressedBlockCoord.x = 0; DecompressedBlockCoord.x < glm::min(4, LevelExtent.x); ++DecompressedBlockCoord.x) {
TextureLocalDecompressed.store(TexelCoord + DecompressedBlockCoord, Level, DecompressedBlock.Texel[DecompressedBlockCoord.y][DecompressedBlockCoord.x]);
}
}
}
else if (format == gli::FORMAT_R_ATI1N_UNORM_BLOCK8) {
const gli::detail::bc4_block *BC4Block = TextureCompressed.data<gli::detail::bc4_block>(0, 0, Level) + (BlockCoord.y * LevelExtentInBlocks.x + BlockCoord.x);
const gli::detail::texel_block4x4 DecompressedBlock = gli::detail::decompress_bc4unorm_block(*BC4Block);
for(DecompressedBlockCoord.y = 0; DecompressedBlockCoord.y < glm::min(4, LevelExtent.y); ++DecompressedBlockCoord.y) {
for(DecompressedBlockCoord.x = 0; DecompressedBlockCoord.x < glm::min(4, LevelExtent.x); ++DecompressedBlockCoord.x) {
TextureLocalDecompressed.store(TexelCoord + DecompressedBlockCoord, Level, DecompressedBlock.Texel[DecompressedBlockCoord.y][DecompressedBlockCoord.x]);
}
}
}
else if (format == gli::FORMAT_RG_ATI2N_UNORM_BLOCK16) {
const gli::detail::bc5_block *BC5Block = TextureCompressed.data<gli::detail::bc5_block>(0, 0, Level) + (BlockCoord.y * LevelExtentInBlocks.x + BlockCoord.x);
const gli::detail::texel_block4x4 DecompressedBlock = gli::detail::decompress_bc5unorm_block(*BC5Block);
for(DecompressedBlockCoord.y = 0; DecompressedBlockCoord.y < glm::min(4, LevelExtent.y); ++DecompressedBlockCoord.y) {
for(DecompressedBlockCoord.x = 0; DecompressedBlockCoord.x < glm::min(4, LevelExtent.x); ++DecompressedBlockCoord.x) {
TextureLocalDecompressed.store(TexelCoord + DecompressedBlockCoord, Level, DecompressedBlock.Texel[DecompressedBlockCoord.y][DecompressedBlockCoord.x]);
}
}
}
}
}
}
TextureLocalDecompressed = gli::flip(TextureLocalDecompressed);
int lvl = 0;
textureStructs[l->getId()].width = (uint32_t)(TextureLocalDecompressed.extent(lvl).x);
textureStructs[l->getId()].height = (uint32_t)(TextureLocalDecompressed.extent(lvl).y);
// for directX normal maps
if (extension.compare(".dds") == 0) textureStructs[l->getId()].rightHanded = false;
auto image = TextureLocalDecompressed[lvl]; // get mipmap 0
if (gli::is_float(format)) {
l->floatTexels.resize(textureStructs[l->getId()].width * textureStructs[l->getId()].height);
memcpy(l->floatTexels.data(), image.data(), (uint32_t)image.size());
} else {
l->byteTexels.resize(textureStructs[l->getId()].width * textureStructs[l->getId()].height);
std::vector<vec4> temp(textureStructs[l->getId()].width * textureStructs[l->getId()].height);
memcpy(temp.data(), image.data(), (uint32_t)image.size());
for (uint32_t i = 0; i < temp.size(); ++i) l->byteTexels[i] = u8vec4(temp[i] * 255.f);
}
}
else {
tex2D = gli::flip(tex2D);
textureStructs[l->getId()].width = (uint32_t)(tex2D.extent().x);
textureStructs[l->getId()].height = (uint32_t)(tex2D.extent().y);
auto image = tex2D[0]; // get mipmap 0
if (format == gli::FORMAT_RGBA32_SFLOAT_PACK32) {
l->floatTexels.resize(textureStructs[l->getId()].width * textureStructs[l->getId()].height);
memcpy(l->floatTexels.data(), image.data(), (uint32_t)image.size());
}
else if (format == gli::FORMAT_RGBA8_SRGB_PACK8) {
l->byteTexels.resize(textureStructs[l->getId()].width * textureStructs[l->getId()].height);
memcpy(l->byteTexels.data(), image.data(), (uint32_t)image.size());
}
if (format == gli::FORMAT_R32_SFLOAT_PACK32) {
tex2D = gli::convert(tex2D, gli::format::FORMAT_RGBA32_SFLOAT_PACK32);
l->floatTexels.resize(textureStructs[l->getId()].width * textureStructs[l->getId()].height);
memcpy(l->floatTexels.data(), image.data(), (uint32_t)image.size());
}
else if (format == gli::FORMAT_R8_SRGB_PACK8) {
tex2D = gli::convert(tex2D, gli::format::FORMAT_RGBA8_SRGB_PACK8);
l->byteTexels.resize(textureStructs[l->getId()].width * textureStructs[l->getId()].height);
memcpy(l->byteTexels.data(), image.data(), (uint32_t)image.size());
}
if (format == gli::FORMAT_RG32_SFLOAT_PACK32) {
tex2D = gli::convert(tex2D, gli::format::FORMAT_RGBA32_SFLOAT_PACK32);
l->floatTexels.resize(textureStructs[l->getId()].width * textureStructs[l->getId()].height);
memcpy(l->floatTexels.data(), image.data(), (uint32_t)image.size());
}
else if (format == gli::FORMAT_RG8_SRGB_PACK8) {
tex2D = gli::convert(tex2D, gli::format::FORMAT_RGBA8_SRGB_PACK8);
l->byteTexels.resize(textureStructs[l->getId()].width * textureStructs[l->getId()].height);
memcpy(l->byteTexels.data(), image.data(), (uint32_t)image.size());
}
else {
throw std::runtime_error(std::string("Error: image " + path + " uses an unsupported format. " +
"Supported formats are " +
"FORMAT_RGBA32_SFLOAT_PACK32, " +
"FORMAT_RGBA8_SRGB_PACK8, " +
"FORMAT_R32_SFLOAT_PACK32, " +
"FORMAT_R8_SRGB_PACK8, " +
"FORMAT_RG32_SFLOAT_PACK32, " +
"FORMAT_RG8_SRGB_PACK8" +
"FORMAT_RGBA_DXT1_UNORM_BLOCK8, " +
"FORMAT_RGBA_DXT5_UNORM_BLOCK16, " +
"FORMAT_R_ATI1N_UNORM_BLOCK8, " +
"FORMAT_RG_ATI2N_UNORM_BLOCK16"));
}
}
}
else {
if (extension.compare(".hdr") == 0) {
int x, y, num_channels;
stbi_set_flip_vertically_on_load(true);
l->linear = true; // Since we convert HDR images from srgb to linear, srgb is always false here.
float* pixels = stbi_loadf(path.c_str(), &x, &y, &num_channels, STBI_rgb_alpha);
if (!pixels) {
std::string reason (stbi_failure_reason());
throw std::runtime_error(std::string("Error: failed to load texture image \"") + path + std::string("\". Reason: ") + reason);
}
l->floatTexels.resize(x * y);
memcpy(l->floatTexels.data(), pixels, x * y * 4 * sizeof(float));
textureStructs[l->getId()].width = x;
textureStructs[l->getId()].height = y;
stbi_image_free(pixels);
}
else {
l->linear = linear; // if linear is true, treat the texture contents as if it were not sRGB.
int x, y, num_channels;
stbi_set_flip_vertically_on_load(true);
stbi_uc* pixels = stbi_load(path.c_str(), &x, &y, &num_channels, STBI_rgb_alpha);
if (!pixels) {
std::string reason (stbi_failure_reason());
throw std::runtime_error(std::string("Error: failed to load texture image \"") + path + std::string("\". Reason: ") + reason);
}
l->byteTexels.resize(x * y);
memcpy(l->byteTexels.data(), pixels, x * y * 4 * sizeof(stbi_uc));
textureStructs[l->getId()].width = x;
textureStructs[l->getId()].height = y;
stbi_image_free(pixels);
}
}
l->markDirty();
};
try {
return StaticFactory::create<Texture>(editMutex, name, "Texture", lookupTable, textures.data(), textures.size(), create);
} catch (...) {
StaticFactory::removeIfExists(editMutex, name, "Texture", lookupTable, textures.data(), textures.size());
throw;
}
}
Texture* Texture::createFromData(std::string name, uint32_t width, uint32_t height, const float* data, uint32_t length, bool linear, bool hdr)
{
if (length != (width * height * 4)) { throw std::runtime_error("Error: width * height * 4 does not equal length of data!"); }
if (width == 0) { throw std::runtime_error("Error: width must be greater than 0!"); }
if (height == 0) { throw std::runtime_error("Error: height must be greater than 0!"); }
auto create = [width, height, length, data, linear, hdr] (Texture* l) {
// user must specify if texture should be srgb or linear.
// we default to linear here as SRGB is more common for images that are stored / loaded from disk.
l->linear = linear;
if (hdr) {
l->floatTexels.resize(width * height);
memcpy(l->floatTexels.data(), data, width * height * 4 * sizeof(float));
} else {
// gotta convert from float to byte.
// TODO: update function signature to accept void* instead of just float*
l->byteTexels.resize(width * height);
for (uint32_t i = 0; i < length / 4; ++i) {
l->byteTexels[i] = u8vec4(vec4(
data[i * 4 + 0],
data[i * 4 + 1],
data[i * 4 + 2],
data[i * 4 + 3]) * 255.f);
}
}
textureStructs[l->getId()].width = width;
textureStructs[l->getId()].height = height;
l->markDirty();
};
try {
return StaticFactory::create<Texture>(editMutex, name, "Texture", lookupTable, textures.data(), textures.size(), create);
} catch (...) {
StaticFactory::removeIfExists(editMutex, name, "Texture", lookupTable, textures.data(), textures.size());
throw;
}
}
vec3 rgb2hsv(vec3 c)
{
vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
vec4 p = mix(vec4(c.b, c.g, K.w, K.z), vec4(c.g, c.b, K.x, K.y), step(c.b, c.g));
vec4 q = mix(vec4(p.x, p.y, p.w, c.r), vec4(c.r, p.y, p.z, p.x), step(p.x, c.r));
float d = q.x - min(q.w, q.y);
float e = 1.0e-10f;
return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
}
vec3 hsv2rgb(vec3 c)
{
vec4 K = vec4(1.0f, 2.0f / 3.0f, 1.0f / 3.0f, 3.0f);
vec3 p = abs(fract(vec3(c.x) + vec3(K)) * 6.0f - vec3(K.w));
return c.z * mix(vec3(K.x), clamp(p - vec3(K.x), 0.0f, 1.0f), c.y);
}
Texture* Texture::createHSV(std::string name, Texture* tex, float hue, float sat, float val, float alpha, bool hdr)
{
auto create = [tex, hue, sat, val, alpha, hdr] (Texture* l) {
if (!tex || !tex->isInitialized()) throw std::runtime_error(std::string("Error: input texture is null/uninitialized!"));
uint32_t width = tex->getWidth();
uint32_t height = tex->getHeight();
if (hdr) l->floatTexels.resize(width * height);
else l->byteTexels.resize(width * height);
textureStructs[l->getId()].width = width;
textureStructs[l->getId()].height = height;
float dh = (hue * 2.f) - 1.0f;
for (uint32_t y = 0; y < height; ++y) {
for (uint32_t x = 0; x < width; ++x) {
vec2 off = vec2(1 / float(width), 1 / float(height));
vec2 uv = vec2(x / float(width), y / float(height)) + .5f * off;
vec4 c = tex->sampleFloatTexels(uv);
if (!tex->isLinear()) c = glm::convertSRGBToLinear(c);
vec3 rgb = vec3(c);
vec3 hsv = rgb2hsv(rgb);
hsv.x = (hsv.x + dh) - (long)(hsv.x + dh);
hsv.y = clamp(sat * hsv.y, 0.f, 1.f); hsv.z = clamp(hsv.z * val, 0.f, 1.f);
rgb = mix(rgb, hsv2rgb(hsv), alpha);
vec4 result = vec4( rgb.r, rgb.g, rgb.b, c.a);
if (!tex->isLinear()) result = glm::convertLinearToSRGB(result);
if (hdr) l->floatTexels[y * width + x] = vec4( rgb.r, rgb.g, rgb.b, c.a);
else l->byteTexels[y * width + x] = u8vec4(vec4(rgb.r, rgb.g, rgb.b, c.a) * 255.f);
}
}
l->markDirty();
};
try {
return StaticFactory::create<Texture>(editMutex, name, "Texture", lookupTable, textures.data(), textures.size(), create);
} catch (...) {
StaticFactory::removeIfExists(editMutex, name, "Texture", lookupTable, textures.data(), textures.size());
throw;
}
}
Texture* Texture::createMix(std::string name, Texture* a, Texture* b, float mix, bool hdr)
{
auto create = [a, b, mix, hdr] (Texture* l) {
if (!a || !a->isInitialized()) throw std::runtime_error(std::string("Error: Texture A is null/uninitialized!"));
if (!b || !b->isInitialized()) throw std::runtime_error(std::string("Error: Texture B is null/uninitialized!"));
uint32_t width = ::max(a->getWidth(), b->getWidth());
uint32_t height = ::max(a->getHeight(), b->getHeight());
if (hdr) l->floatTexels.resize(width * height);
else l->byteTexels.resize(width * height);
textureStructs[l->getId()].width = width;
textureStructs[l->getId()].height = height;
for (uint32_t y = 0; y < height; ++y) {
for (uint32_t x = 0; x < width; ++x) {
vec2 off = vec2(1 / float(width), 1 / float(height));
vec2 uv = vec2(x / float(width), y / float(height)) + .5f * off;
vec4 ac = a->sampleFloatTexels(uv);
vec4 bc = b->sampleFloatTexels(uv);
if (!a->isLinear()) ac = glm::convertSRGBToLinear(ac);
if (!b->isLinear()) bc = glm::convertSRGBToLinear(bc);
vec4 result = glm::mix(ac, bc, mix);
if (!a->isLinear() && !b->isLinear()) result = glm::convertLinearToSRGB(result);
if (hdr) l->floatTexels[y * width + x] = result;
else l->byteTexels[y * width + x] = u8vec4(result * 255.f);
}
}
l->markDirty();
};
try {
return StaticFactory::create<Texture>(editMutex, name, "Texture", lookupTable, textures.data(), textures.size(), create);
} catch (...) {
StaticFactory::removeIfExists(editMutex, name, "Texture", lookupTable, textures.data(), textures.size());
throw;
}
}
Texture* Texture::createAdd(std::string name, Texture* a, Texture* b, bool hdr)
{
auto create = [a, b, hdr] (Texture* l) {
if (!a || !a->isInitialized()) throw std::runtime_error(std::string("Error: Texture A is null/uninitialized!"));
if (!b || !b->isInitialized()) throw std::runtime_error(std::string("Error: Texture B is null/uninitialized!"));
uint32_t width = ::max(a->getWidth(), b->getWidth());
uint32_t height = ::max(a->getHeight(), b->getHeight());
if (hdr) l->floatTexels.resize(width * height);
else l->byteTexels.resize(width * height);
textureStructs[l->getId()].width = width;
textureStructs[l->getId()].height = height;
for (uint32_t y = 0; y < height; ++y) {
for (uint32_t x = 0; x < width; ++x) {
vec2 off = vec2(1 / float(width), 1 / float(height));
vec2 uv = vec2(x / float(width), y / float(height)) + .5f * off;
vec4 ac = a->sampleFloatTexels(uv);
vec4 bc = b->sampleFloatTexels(uv);
if (!a->isLinear()) ac = glm::convertSRGBToLinear(ac);
if (!b->isLinear()) bc = glm::convertSRGBToLinear(bc);
vec4 result = ac + bc;
if (!a->isLinear() && !b->isLinear()) result = glm::convertLinearToSRGB(result);
if (hdr) l->floatTexels[y * width + x] = result;
else l->byteTexels[y * width + x] = u8vec4(result * 255.f);
}
}
l->markDirty();
};
try {
return StaticFactory::create<Texture>(editMutex, name, "Texture", lookupTable, textures.data(), textures.size(), create);
} catch (...) {
StaticFactory::removeIfExists(editMutex, name, "Texture", lookupTable, textures.data(), textures.size());
throw;
}
}
Texture* Texture::createMultiply(std::string name, Texture* a, Texture* b, bool hdr)
{
auto create = [a, b, hdr] (Texture* l) {
if (!a || !a->isInitialized()) throw std::runtime_error(std::string("Error: Texture A is null/uninitialized!"));
if (!b || !b->isInitialized()) throw std::runtime_error(std::string("Error: Texture B is null/uninitialized!"));
uint32_t width = ::max(a->getWidth(), b->getWidth());
uint32_t height = ::max(a->getHeight(), b->getHeight());
if (hdr) l->floatTexels.resize(width * height);
else l->byteTexels.resize(width * height);
textureStructs[l->getId()].width = width;
textureStructs[l->getId()].height = height;
for (uint32_t y = 0; y < height; ++y) {
for (uint32_t x = 0; x < width; ++x) {
vec2 off = vec2(1 / float(width), 1 / float(height));
vec2 uv = vec2(x / float(width), y / float(height)) + .5f * off;
vec4 ac = a->sampleFloatTexels(uv);
vec4 bc = b->sampleFloatTexels(uv);
if (!a->isLinear()) ac = glm::convertSRGBToLinear(ac);
if (!b->isLinear()) bc = glm::convertSRGBToLinear(bc);
vec4 result = ac * bc;
if (!a->isLinear() && !b->isLinear()) result = glm::convertLinearToSRGB(result);
if (hdr) l->floatTexels[y * width + x] = result;
else l->byteTexels[y * width + x] = u8vec4(result * 255.f);
}
}
l->markDirty();
};
try {
return StaticFactory::create<Texture>(editMutex, name, "Texture", lookupTable, textures.data(), textures.size(), create);
} catch (...) {
StaticFactory::removeIfExists(editMutex, name, "Texture", lookupTable, textures.data(), textures.size());
throw;
}
}
vec4 Texture::sampleFloatTexels(vec2 uv) {
uint32_t width = textureStructs[id].width;
uint32_t height = textureStructs[id].height;
vec2 coord = uv * vec2(width-1, height-1);
ivec2 coord_floor = glm::ivec2(glm::floor(coord));
ivec2 coord_ceil = glm::ivec2(glm::ceil(coord));
// todo, interpolate four surrouding pixels
if (floatTexels.size() > 0)
return floatTexels[coord_floor.y * width + coord_floor.x];
else
return vec4(byteTexels[coord_floor.y * width + coord_floor.x]) / 255.f;
}
u8vec4 Texture::sampleByteTexels(vec2 uv) {
uint32_t width = textureStructs[id].width;
uint32_t height = textureStructs[id].height;
vec2 coord = uv * vec2(width-1, height-1);
ivec2 coord_floor = glm::ivec2(glm::floor(coord));
ivec2 coord_ceil = glm::ivec2(glm::ceil(coord));
// todo, interpolate four surrouding pixels
if (byteTexels.size() > 0)
return floatTexels[coord_floor.y * width + coord_floor.x];
else
return u8vec4(floatTexels[coord_floor.y * width + coord_floor.x] * 255.f);
}
std::shared_ptr<std::recursive_mutex> Texture::getEditMutex()
{
return editMutex;
}
Texture* Texture::get(std::string name) {
return StaticFactory::get(editMutex, name, "Texture", lookupTable, textures.data(), textures.size());
}
void Texture::remove(std::string name) {
auto t = get(name);
if (!t) return;
std::vector<glm::vec4>().swap(t->floatTexels);
std::vector<glm::u8vec4>().swap(t->byteTexels);
int32_t oldID = t->getId();
StaticFactory::remove(editMutex, name, "Texture", lookupTable, textures.data(), textures.size());
dirtyTextures.insert(&textures[oldID]);
}
Texture* Texture::getFront() {
return textures.data();
}
TextureStruct* Texture::getFrontStruct() {
return textureStructs.data();
}
uint32_t Texture::getCount() {
return uint32_t(textures.size());
}
std::string Texture::getName()
{
return name;
}
int32_t Texture::getId()
{
return id;
}
int32_t Texture::getAddress()
{
return int32_t(this - textures.data());
}
std::map<std::string, uint32_t> Texture::getNameToIdMap()
{
return lookupTable;
}
};
| 44.810771 | 192 | 0.566445 | [
"vector",
"transform"
] |
151170153e35857542fa8ff34ec17831f614f6bc | 11,223 | cc | C++ | dc3/dc30.cc | pptacher/hackerrank | 9ebe957114dd781ae96a9f80f42f2840787a1c19 | [
"MIT"
] | null | null | null | dc3/dc30.cc | pptacher/hackerrank | 9ebe957114dd781ae96a9f80f42f2840787a1c19 | [
"MIT"
] | null | null | null | dc3/dc30.cc | pptacher/hackerrank | 9ebe957114dd781ae96a9f80f42f2840787a1c19 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include <stack>
#include <set>
#include <queue>
#include <unordered_map>
#include <bitset>
#include <array>
#include <numeric>
#include <algorithm>
using std::string;
typedef unsigned int uint;
void dc3(std::vector<int>&, std::vector<int>&);
void lcp(string& s, std::vector<int>&,std::vector<int>&);
void rmqInit(std::vector<int>& v, std::vector<std::vector<int>>& u,std::vector<int>& w);
int rmqQuery(std::vector<std::vector<int>>& u, std::vector<int>& w, int i, int j);
int match(string& s1, int j, string& s2, std::vector<int>& h, std::vector<int>& pos1r, std::vector<std::vector<int>>& u,std::vector<int>&, int&,int&,int& );
void preprocess(string&, std::vector<int>&, std::vector<int>&, std::vector<int>&, std::vector<std::vector<int>>&, std::vector<int>&, std::vector<int>&,bool);
void buildPalindrome(string&,string&,string&,std::vector<int>&,std::vector<int>&,std::vector<int>&,std::vector<std::vector<int>>&,std::vector<int>&,std::vector<int>&,std::vector<int>&,std::vector<int>&,std::vector<std::vector<int>>&,std::vector<int>&,std::vector<int>&,int&,int&,int&);
int main() {
//string s1("dczatfarqdkelalxzxillkfdvpfpxabqlngdscrentzamztvvcvrtcm"), s2("bqlizijdwtuyfrxolsysxlfebpolcmqsppmrfkyunydtmwbexsngxhwvroandfqjamzkpttslildlrkjoyrpxugiceahgiake");
string s1("qquhuwqhdswxxrxuzzfhkplwunfagppcoildagktgdarveusjuqfistulgbglwmfgzrnyxryetwzhlnfewczmnoozlqatugmd");
string s2("jwgzcfabbkoxyjxkatjmpprswkdkobdagwdwxsufeesrvncbszcepigpbzuzoootorzfskcwbqorvw");
string s1r(s1), s2r(s2);
std::reverse(s1r.begin(), s1r.end());
std::reverse(s2r.begin(),s2r.end());
std::vector<int> u1r, u2r, u1, u2;
std::vector<int> v1r, v2r, v1, v2;
std::vector<int> h1r, h2r, h1, h2;
std::vector<std::vector<int>> rmq1r, rmq2r, rmq1, rmq2;
std::vector<int> p1r, p2r, p1, p2;
std::vector<int> w1r, w2r, w1, w2;
preprocess(s2r,u2r,v2r,h2r,rmq2r,w2r,p2r,false);
u2r.clear();p2r.clear();rmq2r.clear();h2r.clear();
preprocess(s1,u1,v1,h1,rmq1,w1,p1,false);
u1.clear();p1.clear();rmq1.clear();h1.clear();
preprocess(s1r,u1r,v1r,h1r,rmq1r,w1r,p1r,true);
u1r.clear();
preprocess(s2,u2,v2,h2,rmq2,w2,p2,true);
u2.clear();
int j(-1), mxm(0),pal(0);
buildPalindrome(s2,s1r,s2r,h1r,v1r,p1r,rmq1r,w1r,v2,h2,p2,rmq2,w2,v2r,j,pal,mxm);
int j1(-1),mxm1(0), pal1(0);
buildPalindrome(s1r,s2,s1,h2,v2,p2,rmq2,w2,v1r,h1r,p1r,rmq1r,w1r,v1,j1,pal1,mxm1);
string res("");
if(mxm1>mxm){
res = s1.substr(s1.length()-j1-(mxm1-pal1)/2,(mxm1-pal1)/2+pal1) + (mxm1-pal1>0?s1r.substr(j1,(mxm1-pal1)/2):"");
}
else if (mxm>mxm1){
res = (mxm-pal>0?s2r.substr(s2.length()-j-(mxm-pal)/2,(mxm-pal)/2):"") + s2.substr(j-pal,(mxm-pal)/2+pal);
}
else if (mxm==mxm1 && mxm>0){
if(s1.compare(s1.length()-j1-(mxm1-pal1)/2,(mxm1-pal1)/2+(pal1+1)/2,s2r,s2.length()-j-(mxm-pal)/2,(mxm1-pal1)/2+(pal1+1)/2)<0){
res = s1.substr(s1.length()-j1-(mxm1-pal1)/2,(mxm1-pal1)/2+pal1) + (mxm1-pal>0?s1r.substr(j1,(mxm1-pal1)/2):"");
}
else{
res = (mxm-pal>0?s2r.substr(s2.length()-j-(mxm-pal)/2,(mxm-pal)/2):"") + s2.substr(j-pal,(mxm-pal)/2+pal);
}
}
std::cout << res << std::endl;
return 0;
}
void buildPalindrome(string& s2, string& s1r, string& s2r,
std::vector<int>& h1r,
std::vector<int>& v1r,
std::vector<int>& p1r,
std::vector<std::vector<int>>& rmq1r,
std::vector<int>& w1r,
std::vector<int>& v2,
std::vector<int>& h2,
std::vector<int>& p2,
std::vector<std::vector<int>>& rmq2,
std::vector<int>& w2,
std::vector<int>& v2r,
int& j,
int& pal,
int& mxm){
j = -1;
pal = 0;
mxm = 0;
bool b(false);
std::set<int> si1, si2;
int hint(0), k1(0);
int suff(0);
std::vector<int> j1(s2.length(),0);
for(uint i=0; i<s2.length(); ++i){
if(k1>1){
hint = v1r[p1r[suff]+1];
suff = hint;
}
--k1;
j1[i] = match(s2,i,s1r,h1r,p1r,rmq1r,w1r,suff,k1,hint);
if(j1[i]>0){
b = true;
}
}
if(!b){
return;
}
for(uint i=0; i<s2.length(); ++i){
int j2(0);
for(uint ind: si1){
if(ind<s2.length()-1 && s2r[ind+1]==s2r[s2.length()-i]){
si2.insert(ind+1);
j2 = ind+1-s2.length()+i+1;
}
}
if(i>0){
si2.insert(s2.length()-i);
j2= std::max(j2,1);
if(i>1 && s2r[s2.length()-i]==s2r[s2.length()-i+1]){
si2.insert(s2.length()-i+1);
j2 = std::max(j2,2);
}
}
std::swap(si1,si2);
si2.clear();
if(j1[i]>0 && static_cast<int>(i)+j1[i] >= mxm){
//j2 = palindromes(s2r,s2,s2.length()-i,v2,h2,p2,rmq2,w2);
int c(1);
/*if(j2+2*j1==mxm){
c = s2r.compare(s2.length()-i-(j2+2*j1-j2)/2,(j2+2*j1-j2)/2+(j2+1)/2,s2r,s2.length()-j-(mxm-pal)/2,(mxm-pal)/2+(pal+1)/2);
}*/
if((j2+2*j1[i]>mxm /*|| c < 0 */|| (j2+2*j1[i]==mxm && v2r[s2.length()-i-j1[i]]<v2r[s2.length()-j-(mxm-pal)/2]))){
mxm = j2+2*j1[i];
j = i;
pal = j2;
}
}
}
}
void preprocess(string& s,
std::vector<int>&u,
std::vector<int>& v,
std::vector<int>& h,
std::vector<std::vector<int>>& rmq,
std::vector<int>& w,
std::vector<int>& p,
bool b=true){
for(uint i=0; i<s.length(); ++i){
u.push_back(s[i]-'a');
}
v = std::vector<int>(u.size(),0);
h = std::vector<int>(u.size(),0);
dc3(u,v);
if(!b){
return;
}
lcp(s,v,h);
rmqInit(h,rmq,w);
p = std::vector<int>(u.size(),0);
for(uint i=0; i<u.size(); ++i){
p[v[i]] = i;
}
}
int match(string& s1, int j, string& s2, std::vector<int>& h, std::vector<int>& pos, std::vector<std::vector<int>>& u,std::vector<int>& w, int& suffix, int& k1, int& hint){
int n = s1.length();
int m = s2.length()+1;
int res(0);
int lcp(k1>0?k1:0);
int k(k1>0?k1:0);
int a(0), b(m-1);
int mid(k1>0?hint:a + (b-a)/2),mid1(mid);
int last(mid);
while(k+j<n && a<=b){
lcp = mid==last?lcp:rmqQuery(u,w,std::min(mid,last),std::max(mid,last)-1);
if(lcp>=k+1){
if(mid1<mid){
a = mid+1;
}
else{
b = mid-1;
}
last = mid;
}
if(lcp<k){
if(last<mid){
b = mid-1;
}
else{
a = mid+1;
}
}
else {
while(j+k<n && pos[mid]+k<m-1 && s1[j+k]==s2[pos[mid]+k]){
suffix = mid;
++k;
}
if( j+k<n && pos[mid]+k < m-1 && s1[j+k] < s2[pos[mid]+k]){
b = mid-1;
}
else{
a = mid + 1;
}
last = mid;
}
mid1 = mid;
mid = a + (b-a)/2;
}
hint = mid;
k1 = k;
return k;
}
void rmqInit(std::vector<int>& v, std::vector<std::vector<int>>& u,std::vector<int>& w){
int n = v.size();
u = std::vector<std::vector<int>>(n,std::vector<int>(1,0));
for(int i=0; i<n; ++i){
u[i][0] = v[i];
}
w = std::vector<int>(n,0);
int m(1);
int k(2);
for(int x=1; k<=n; ++x,k*=2){
for(int i=m; i<m+(k>>1); ++i){
w[i] = x-1;
}
m += (k>>1);
for(int j=0; j<=n-k; ++j){
u[j].push_back(std::min(u[j][x-1],u[j+(k>>1)][x-1]));
}
}
}
int rmqQuery(std::vector<std::vector<int>>& u, std::vector<int>& w, int i, int j){
int k = w[j-i];
return std::min(u[i][k],u[j-(1<<k)+1][k]);
}
void lcp(string& s, std::vector<int>& v, std::vector<int>& h){
int n = v.size();
std::vector<int> pos(n,0);
for(int i=0; i<n; ++i){
pos[v[i]] = i;
}
int k(0);
for(int i=0; i<n-1; ++i){ // At most 2n char comparisons.
int j = pos[v[i]-1];
while(i+k<n-1 && s[i+k]==s[j+k]){
++k;
}
h[v[i]-1] = k;
if(k>0){
--k;
}
}
}
void dc3(std::vector<int>& u, std::vector<int>& v){
int n = u.size();
u.push_back(-1);
if(n<=2){
std::iota(v.begin(),v.end(),1);
v.push_back(0);
if(n==2 && u[1]<=u[0]){
std::swap(v[0],v[1]);
}
return;
}
v.push_back(0);
++n;
int n1((n-1+2)/3);
int n2((n-2+2)/3);
// build u[1...]+u[2...].
std::vector<std::array<int,4>> w(n1+n2,std::array<int,4>());
u.push_back(-1);
u.push_back(-1);
int mxm(u[0]);
for(int i=0; i<n1; i++){
w[i][0] = u[3*i+1];
w[i][1] = u[3*i+2];
w[i][2] = u[3*i+3];
w[i][3] = i;
mxm = std::max(mxm,std::max(u[3*i+1],std::max(u[3*i+2],u[3*i+3])));
}
for(int i=0; i<n2; i++){
w[i+n1][0] = u[3*i+2];
w[i+n1][1] = u[3*i+3];
w[i+n1][2] = u[3*i+4];
w[i+n1][3] = i+n1;
}
// radix sort blocks of 3. O(n+|Σ|).
u.pop_back();
u.pop_back();
std::vector<std::array<int,4>> w1(n1+n2,std::array<int,4>());
for(int k=0; k<3; ++k){
std::vector<int> c((uint)mxm+2,0);
for(int i=0; i<n1+n2; ++i){
c[w[i][2-k]+1]++;
}
for(uint i=1; i<(uint)mxm+2; ++i){
c[i] += c[i-1];
}
for(int i=n1+n2-1; i>=0; --i){
w1[--c[w[i][2-k]+1]] = w[i];
}
std::swap(w1,w);
}
std::vector<int> u1(n1+n2,0);
int count(0);
for(int i=0; i<n1+n2; ++i){
if(i>0 && (w[i][0]!=w[i-1][0] || w[i][1]!=w[i-1][1] || w[i][2]!=w[i-1][2] )){
++count;
}
u1[w[i][3]] = count;
}
// recursively compute suffix array for array of size 2n/3.
std::vector<int> v2(n1+n2,0);
dc3(u1,v2);
// radix sort element at indices multiples of 3. O(n+|Σ|).
std::vector<std::array<int,3>> u2(n-n1-n2,std::array<int,3>());
for(int i=0; i<n-n1-n2; ++i){
u2[i] = {{u[3*i],3*i+1<n?v2[i]:-1,3*i}};
}
std::vector<std::array<int,3>> u3(n-n1-n2,std::array<int,3>());
mxm = std::max(mxm,n1+n2); // |Σ| = size of current alphabet. (mxm ⩽ n && n1+n2 ⫹ 2n/3) ⇒ |Σ|⩽ n.
for(int k=0; k<2; ++k){
std::vector<int> c((uint)mxm+2,0);
for(int i=0; i<n-n1-n2; ++i){
c[u2[i][1-k]+1]++;
}
for(uint i=1; i<(uint)mxm+2; ++i){
c[i] += c[i-1];
}
for(int i=n-n1-n2-1; i>=0; --i){
u3[--c[u2[i][1-k]+1]] = u2[i];
}
std::swap(u2,u3);
}
// merge. O(n).
int i1(0), i12(0);
std::vector<int> v1(n1+n2,0);
for(int i=0; i<n1; ++i){
v1[v2[i]-1] = 3*(i) + 1;
}
for(int i=0; i<n2; ++i){
v1[v2[n1+i]-1] = 3*(i) + 2;
}
for(int i=0; i<n; ++i){
if(i1==n-n1-n2){
v[v1[i12++]] = i;
}
else if(i12==n1+n2 || u[u2[i1][2]]<u[v1[i12]] ||
(u[u2[i1][2]] == u[v1[i12]] && v1[i12]%3==1 && (u2[i1][2]+1==n || (v1[i12]+1<n && v2[u2[i1][2]/3] < v2[n1+v1[i12]/3])) ) ||
(u[u2[i1][2]] == u[v1[i12]] && v1[i12]%3==2 && (u[u2[i1][2]+1] < u[v1[i12]+1]|| (u[u2[i1][2]+1] == u[v1[i12]+1] && (u2[i1][2]+2 == n || (v1[i12]+2<n && v2[u2[i1][2]/3+n1]<v2[v1[i12]/3+1])))) ) ){
v[u2[i1++][2]] = i;
}
else{
v[v1[i12++]] = i;
}
}
}
| 27.848635 | 285 | 0.487837 | [
"vector"
] |
1517a672f02c5fb7f69b116089f4ed98299cba2d | 11,168 | cpp | C++ | src/qt/src/3rdparty/webkit/Source/WebCore/platform/graphics/gpu/LoopBlinnLocalTriangulator.cpp | ant0ine/phantomjs | 8114d44a28134b765ab26b7e13ce31594fa81253 | [
"BSD-3-Clause"
] | 46 | 2015-01-08T14:32:34.000Z | 2022-02-05T16:48:26.000Z | src/qt/src/3rdparty/webkit/Source/WebCore/platform/graphics/gpu/LoopBlinnLocalTriangulator.cpp | ant0ine/phantomjs | 8114d44a28134b765ab26b7e13ce31594fa81253 | [
"BSD-3-Clause"
] | 7 | 2015-01-20T14:28:12.000Z | 2017-01-18T17:21:44.000Z | src/qt/src/3rdparty/webkit/Source/WebCore/platform/graphics/gpu/LoopBlinnLocalTriangulator.cpp | ant0ine/phantomjs | 8114d44a28134b765ab26b7e13ce31594fa81253 | [
"BSD-3-Clause"
] | 14 | 2015-10-27T06:17:48.000Z | 2020-03-03T06:15:50.000Z | /*
* Copyright (C) 2010 Google Inc. 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if ENABLE(ACCELERATED_2D_CANVAS)
#include "LoopBlinnLocalTriangulator.h"
#include "LoopBlinnMathUtils.h"
#include <algorithm>
namespace WebCore {
using LoopBlinnMathUtils::approxEqual;
using LoopBlinnMathUtils::linesIntersect;
using LoopBlinnMathUtils::pointInTriangle;
bool LoopBlinnLocalTriangulator::Triangle::contains(LoopBlinnLocalTriangulator::Vertex* v)
{
return indexForVertex(v) >= 0;
}
LoopBlinnLocalTriangulator::Vertex* LoopBlinnLocalTriangulator::Triangle::nextVertex(LoopBlinnLocalTriangulator::Vertex* current, bool traverseCounterClockwise)
{
int index = indexForVertex(current);
ASSERT(index >= 0);
if (traverseCounterClockwise)
++index;
else
--index;
if (index < 0)
index += 3;
else
index = index % 3;
return m_vertices[index];
}
int LoopBlinnLocalTriangulator::Triangle::indexForVertex(LoopBlinnLocalTriangulator::Vertex* vertex)
{
for (int i = 0; i < 3; ++i)
if (m_vertices[i] == vertex)
return i;
return -1;
}
void LoopBlinnLocalTriangulator::Triangle::makeCounterClockwise()
{
// Possibly swaps two vertices so that the triangle's vertices are
// always specified in counterclockwise order. This orders the
// vertices canonically when walking the interior edges from the
// start to the end vertex.
FloatPoint3D point0(m_vertices[0]->xyCoordinates());
FloatPoint3D point1(m_vertices[1]->xyCoordinates());
FloatPoint3D point2(m_vertices[2]->xyCoordinates());
FloatPoint3D crossProduct = (point1 - point0).cross(point2 - point0);
if (crossProduct.z() < 0)
std::swap(m_vertices[1], m_vertices[2]);
}
LoopBlinnLocalTriangulator::LoopBlinnLocalTriangulator()
{
reset();
}
void LoopBlinnLocalTriangulator::reset()
{
m_numberOfTriangles = 0;
m_numberOfInteriorVertices = 0;
for (int i = 0; i < 4; ++i) {
m_interiorVertices[i] = 0;
m_vertices[i].resetFlags();
}
}
void LoopBlinnLocalTriangulator::triangulate(InsideEdgeComputation computeInsideEdges, LoopBlinnConstants::FillSide sideToFill)
{
triangulateHelper(sideToFill);
if (computeInsideEdges == ComputeInsideEdges) {
// We need to compute which vertices describe the path along the
// interior portion of the shape, to feed these vertices to the
// more general tessellation algorithm. It is possible that we
// could determine this directly while producing triangles above.
// Here we try to do it generally just by examining the triangles
// that have already been produced. We walk around them in a
// specific direction determined by which side of the curve is
// being filled. We ignore the interior vertex unless it is also
// the ending vertex, and skip the edges shared between two
// triangles.
Vertex* v = &m_vertices[0];
addInteriorVertex(v);
int numSteps = 0;
while (!v->end() && numSteps < 4) {
// Find the next vertex according to the above rules
bool gotNext = false;
for (int i = 0; i < numberOfTriangles() && !gotNext; ++i) {
Triangle* tri = getTriangle(i);
if (tri->contains(v)) {
Vertex* next = tri->nextVertex(v, sideToFill == LoopBlinnConstants::RightSide);
if (!next->marked() && !isSharedEdge(v, next) && (!next->interior() || next->end())) {
addInteriorVertex(next);
v = next;
// Break out of for loop
gotNext = true;
}
}
}
++numSteps;
}
if (!v->end()) {
// Something went wrong with the above algorithm; add the last
// vertex to the interior vertices anyway. (FIXME: should we
// add an assert here and do more extensive testing?)
addInteriorVertex(&m_vertices[3]);
}
}
}
void LoopBlinnLocalTriangulator::triangulateHelper(LoopBlinnConstants::FillSide sideToFill)
{
reset();
m_vertices[3].setEnd(true);
// First test for degenerate cases.
for (int i = 0; i < 4; ++i) {
for (int j = i + 1; j < 4; ++j) {
if (approxEqual(m_vertices[i].xyCoordinates(), m_vertices[j].xyCoordinates())) {
// Two of the vertices are coincident, so we can eliminate at
// least one triangle. We might be able to eliminate the other
// as well, but this seems sufficient to avoid degenerate
// triangulations.
int indices[3] = { 0 };
int index = 0;
for (int k = 0; k < 4; ++k)
if (k != j)
indices[index++] = k;
addTriangle(&m_vertices[indices[0]],
&m_vertices[indices[1]],
&m_vertices[indices[2]]);
return;
}
}
}
// See whether any of the points are fully contained in the
// triangle defined by the other three.
for (int i = 0; i < 4; ++i) {
int indices[3] = { 0 };
int index = 0;
for (int j = 0; j < 4; ++j)
if (i != j)
indices[index++] = j;
if (pointInTriangle(m_vertices[i].xyCoordinates(),
m_vertices[indices[0]].xyCoordinates(),
m_vertices[indices[1]].xyCoordinates(),
m_vertices[indices[2]].xyCoordinates())) {
// Produce three triangles surrounding this interior vertex.
for (int j = 0; j < 3; ++j)
addTriangle(&m_vertices[indices[j % 3]],
&m_vertices[indices[(j + 1) % 3]],
&m_vertices[i]);
// Mark the interior vertex so we ignore it if trying to trace
// the interior edge.
m_vertices[i].setInterior(true);
return;
}
}
// There are only a few permutations of the vertices, ignoring
// rotations, which are irrelevant:
//
// 0--3 0--2 0--3 0--1 0--2 0--1
// | | | | | | | | | | | |
// | | | | | | | | | | | |
// 1--2 1--3 2--1 2--3 3--1 3--2
//
// Note that three of these are reflections of each other.
// Therefore there are only three possible triangulations:
//
// 0--3 0--2 0--3
// |\ | |\ | |\ |
// | \| | \| | \|
// 1--2 1--3 2--1
//
// From which we can choose by seeing which of the potential
// diagonals intersect. Note that we choose the shortest diagonal
// to split the quad.
if (linesIntersect(m_vertices[0].xyCoordinates(),
m_vertices[2].xyCoordinates(),
m_vertices[1].xyCoordinates(),
m_vertices[3].xyCoordinates())) {
if ((m_vertices[2].xyCoordinates() - m_vertices[0].xyCoordinates()).diagonalLengthSquared() <
(m_vertices[3].xyCoordinates() - m_vertices[1].xyCoordinates()).diagonalLengthSquared()) {
addTriangle(&m_vertices[0], &m_vertices[1], &m_vertices[2]);
addTriangle(&m_vertices[0], &m_vertices[2], &m_vertices[3]);
} else {
addTriangle(&m_vertices[0], &m_vertices[1], &m_vertices[3]);
addTriangle(&m_vertices[1], &m_vertices[2], &m_vertices[3]);
}
} else if (linesIntersect(m_vertices[0].xyCoordinates(),
m_vertices[3].xyCoordinates(),
m_vertices[1].xyCoordinates(),
m_vertices[2].xyCoordinates())) {
if ((m_vertices[3].xyCoordinates() - m_vertices[0].xyCoordinates()).diagonalLengthSquared() <
(m_vertices[2].xyCoordinates() - m_vertices[1].xyCoordinates()).diagonalLengthSquared()) {
addTriangle(&m_vertices[0], &m_vertices[1], &m_vertices[3]);
addTriangle(&m_vertices[0], &m_vertices[3], &m_vertices[2]);
} else {
addTriangle(&m_vertices[0], &m_vertices[1], &m_vertices[2]);
addTriangle(&m_vertices[2], &m_vertices[1], &m_vertices[3]);
}
} else {
// Lines (0->1), (2->3) intersect -- or should, modulo numerical
// precision issues
if ((m_vertices[1].xyCoordinates() - m_vertices[0].xyCoordinates()).diagonalLengthSquared() <
(m_vertices[3].xyCoordinates() - m_vertices[2].xyCoordinates()).diagonalLengthSquared()) {
addTriangle(&m_vertices[0], &m_vertices[2], &m_vertices[1]);
addTriangle(&m_vertices[0], &m_vertices[1], &m_vertices[3]);
} else {
addTriangle(&m_vertices[0], &m_vertices[2], &m_vertices[3]);
addTriangle(&m_vertices[3], &m_vertices[2], &m_vertices[1]);
}
}
}
void LoopBlinnLocalTriangulator::addTriangle(Vertex* v0, Vertex* v1, Vertex* v2)
{
ASSERT(m_numberOfTriangles < 3);
m_triangles[m_numberOfTriangles++].setVertices(v0, v1, v2);
}
void LoopBlinnLocalTriangulator::addInteriorVertex(Vertex* v)
{
ASSERT(m_numberOfInteriorVertices < 4);
m_interiorVertices[m_numberOfInteriorVertices++] = v;
v->setMarked(true);
}
bool LoopBlinnLocalTriangulator::isSharedEdge(Vertex* v0, Vertex* v1)
{
bool haveEdge01 = false;
bool haveEdge10 = false;
for (int i = 0; i < numberOfTriangles(); ++i) {
Triangle* tri = getTriangle(i);
if (tri->contains(v0) && tri->nextVertex(v0, true) == v1)
haveEdge01 = true;
if (tri->contains(v1) && tri->nextVertex(v1, true) == v0)
haveEdge10 = true;
}
return haveEdge01 && haveEdge10;
}
} // namespace WebCore
#endif
| 39.885714 | 160 | 0.602436 | [
"shape"
] |
1518f4878e8e96502b83736da66401b541742c57 | 3,320 | hxx | C++ | include/detail/scope_block.hxx | jjzhang166/cpp-rgb2yuv | 044895c02ac8382b614be3b847a180f1c2ec322b | [
"MIT"
] | null | null | null | include/detail/scope_block.hxx | jjzhang166/cpp-rgb2yuv | 044895c02ac8382b614be3b847a180f1c2ec322b | [
"MIT"
] | null | null | null | include/detail/scope_block.hxx | jjzhang166/cpp-rgb2yuv | 044895c02ac8382b614be3b847a180f1c2ec322b | [
"MIT"
] | null | null | null | /*
rgb2yuv - Code covered by the MIT License
Author: mutouyun (http://darkc.at)
*/
////////////////////////////////////////////////////////////////
/// Define default memory allocator
////////////////////////////////////////////////////////////////
struct allocator
{
static void * alloc(GLB_ size_t size)
{
return ( (size == 0) ? NULL : GLB_ operator new(size, STD_ nothrow) );
}
static void free(void * ptr)
{
GLB_ operator delete(ptr, STD_ nothrow);
}
};
////////////////////////////////////////////////////////////////
/// The limited garbage collection facility for memory block
////////////////////////////////////////////////////////////////
template <typename T, typename AllocT = R2Y_ALLOC_>
class scope_block
{
template <typename U, typename A>
friend class scope_block;
T * block_;
GLB_ size_t size_;
bool trust_;
public:
scope_block(void)
: block_(NULL), size_(0), trust_(false)
{}
explicit scope_block(GLB_ size_t count) : scope_block()
{
reset(count);
}
scope_block(T * block, GLB_ size_t count) : scope_block()
{
reset(block, count);
}
scope_block(scope_block const &) = delete;
template <typename U>
scope_block(scope_block<U, AllocT> && rhs) : scope_block()
{
this->swap(rhs);
}
template <typename U>
scope_block & operator=(scope_block<U, AllocT> && rhs)
{
this->swap(rhs);
return (*this);
}
~scope_block(void)
{
if (trust_) AllocT::free(block_);
}
void reset(GLB_ size_t count)
{
this->~scope_block();
size_ = count * sizeof(T);
block_ = static_cast<T *>( AllocT::alloc(this->size()) );
trust_ = true;
}
void reset(T * block, GLB_ size_t count)
{
this->~scope_block();
size_ = count * sizeof(T);
block_ = block;
trust_ = false;
}
void trust(void) { trust_ = true; }
void swap(scope_block & rhs)
{
STD_ swap(this->block_, rhs.block_);
STD_ swap(this->size_ , rhs.size_ );
STD_ swap(this->trust_, rhs.trust_);
}
template <typename U>
void swap(scope_block<U, AllocT> & rhs)
{
void * tmp_ptr = this->block_;
this->block_ = reinterpret_cast<T *>(rhs.block_);
rhs .block_ = reinterpret_cast<U *>(tmp_ptr);
STD_ swap(this->size_ , rhs.size_ );
STD_ swap(this->trust_, rhs.trust_);
}
/*
* You need to handle the datas from this scope_block object
* by yourself before you calling this function.
*/
T * dismiss(void)
{
T * data_ret = this->data();
block_ = NULL;
size_ = 0;
trust_ = false;
return data_ret;
}
T * data (void) const { return block_; }
GLB_ size_t size (void) const { return size_ ; }
GLB_ size_t count(void) const { return size_ / sizeof(T); }
bool is_trusted(void) const { return trust_; }
T & operator[](GLB_ size_t pos) { return block_[pos]; }
T const & operator[](GLB_ size_t pos) const { return block_[pos]; }
};
template <typename T, typename U, typename A>
void swap(R2Y_ scope_block<T, A> & a, R2Y_ scope_block<U, A> & b)
{
a.swap(b);
} | 24.962406 | 78 | 0.529217 | [
"object"
] |
151f51a2757f25dba5ba0491a8f4cfe844e3bdd8 | 4,913 | cpp | C++ | tests/filename_validation_tests.cpp | skybaboon/dailycashmanager | 0b022cc230a8738d5d27a799728da187e22f17f8 | [
"Apache-2.0"
] | 4 | 2016-07-05T07:42:07.000Z | 2020-07-15T15:27:22.000Z | tests/filename_validation_tests.cpp | skybaboon/dailycashmanager | 0b022cc230a8738d5d27a799728da187e22f17f8 | [
"Apache-2.0"
] | 1 | 2020-05-07T20:58:21.000Z | 2020-05-07T20:58:21.000Z | tests/filename_validation_tests.cpp | skybaboon/dailycashmanager | 0b022cc230a8738d5d27a799728da187e22f17f8 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2013 Matthew Harvey
*
* 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 "filename_validation.hpp"
#include <boost/test/unit_test.hpp>
#include <jewel/assert.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::string;
using std::vector;
namespace dcm
{
namespace test
{
BOOST_AUTO_TEST_CASE(test_is_valid_filename_re_generally_bad_filenames)
{
const char* const generally_bad_filenames[] =
{ "\\",
"multiple_bad_chars<are_here_:yes",
"another_bad_char\"yes",
"question_?mark",
"con",
"CON",
"com1",
"COM8",
"lpt9",
"AUX",
"nul",
"slashes/are/us",
"hmmm\\",
"::",
"and*yeah",
"...",
"",
"..",
"consecutive_dots_are..uncool",
"should_not\\be_confusable\\with_a_Windows_filepath",
"or/a/Unix/one",
"/or/this/one",
"D:\\this\\is\\not\\a_filename",
"uncool/",
"even_with_extension?.dcm",
"that_won>t_save_you.dcm"
};
for (char const* bad_name: generally_bad_filenames)
{
string message;
BOOST_CHECK(!is_valid_filename(bad_name, message));
BOOST_CHECK(!is_valid_filename(bad_name, message, true));
BOOST_CHECK(!is_valid_filename(bad_name, message, false));
}
// We have to test strings containing the null character separately, as
// we include the null character in a string literals as above.
string nul_containing_string;
nul_containing_string.push_back('\0');
string message;
BOOST_CHECK(!is_valid_filename(nul_containing_string, message));
BOOST_CHECK(!is_valid_filename(nul_containing_string, message, true));
BOOST_CHECK(!is_valid_filename(nul_containing_string, message, false));
string nul_containing_string_2;
nul_containing_string_2.push_back('a');
nul_containing_string_2.push_back('b');
nul_containing_string_2.push_back('\0');
nul_containing_string_2.push_back('c');
JEWEL_ASSERT (nul_containing_string_2.size() == 4);
BOOST_CHECK(!is_valid_filename(nul_containing_string_2, message));
BOOST_CHECK(!is_valid_filename(nul_containing_string_2, message, true));
BOOST_CHECK(!is_valid_filename(nul_containing_string_2, message, false));
}
BOOST_AUTO_TEST_CASE(test_is_valid_filename_re_generally_good_filenames)
{
// Note none of these have the right DailyCashManager extension though.
// We test that they are good generally filenames but can't
// serve as DailyCashManager database files.
const char* const generally_good_filenames[] =
{ "hello",
"something.with.lots.of.dots",
" leading spaces",
"exclamation_marks!!",
" ! ! ! ,,,",
"all_good_here",
"bonus_extension",
"and.db",
"but_extension_not_required",
"HOW_ARE_CAPITALS_EVEN_AN_ISSUE",
"spaces are fine even stupidly many ",
"does_not_really_have_a.dcm.extension",
".dcm", // Must have non-empty base
"nodotdcm",
"badly_positioned_do.tdcm",
"so_is_thisp.hat",
"and_this.dcm."
};
for (char const* good_name: generally_good_filenames)
{
string message;
// Good generally
BOOST_CHECK(is_valid_filename(good_name, message, false));
if (!is_valid_filename(good_name, message, false))
{
cout << good_name << endl;
}
// But doesn't have DailyCashManager extension
BOOST_CHECK(!is_valid_filename(good_name, message, true));
BOOST_CHECK(!is_valid_filename(good_name, message));
}
}
BOOST_AUTO_TEST_CASE(test_is_valid_filename_re_good_dcm_filenames)
{
const char* const good_dcm_filenames[] =
{ "hello.dcm",
"space are ok.dcm",
"this is weird .dcm",
"------.dcm",
"'.dcm",
"we-are-tolerant-of-hyphens.dcm"
};
for (char const* good_name: good_dcm_filenames)
{
string message;
// Good generally
BOOST_CHECK(is_valid_filename(good_name, message, false));
// Good as DailyCashManager file, too
BOOST_CHECK(is_valid_filename(good_name, message, true));
BOOST_CHECK(is_valid_filename);
}
}
} // namespace test
} // namespace dcm
| 30.32716 | 77 | 0.653165 | [
"vector"
] |
1524e7f7e4994f24b1513bd37b83234ec9d44fe8 | 6,452 | cpp | C++ | src/Game/mygame.cpp | michaeleggers/Engine3 | 84088bfc665ed515801ddd20a13becf78a0b50fb | [
"MIT"
] | null | null | null | src/Game/mygame.cpp | michaeleggers/Engine3 | 84088bfc665ed515801ddd20a13becf78a0b50fb | [
"MIT"
] | null | null | null | src/Game/mygame.cpp | michaeleggers/Engine3 | 84088bfc665ed515801ddd20a13becf78a0b50fb | [
"MIT"
] | null | null | null | #include <stdio.h>
#include "interface.h"
#include <SDL.h>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <glm/gtx/quaternion.hpp>
#include <string>
#include <unordered_map>
#include "player.h"
#include "camera.h"
#include "input_handler.h"
/*
What do I need ?
- Pickups: Player walks over it and gets it (health, weapon, etc...)
- Triggers: (invisible) geometry that triggers an action (open a door, move the elevator).
- Player: Controllable player
Do not think about what part of the engine really is in control and how to
'architect' the code. I can sort this out once I have a running thing going!
Just let both game-code and engine see the player struct. DO NOT ABSTRACT! JUST BUILD WHAT I NEED!
- Enemies: Run around, shoot, follow the player, ...
- World: Static geometry (walls). Areas that hurt the player (lava) but are static.
- World: Special geometry (doors, elevators)
- Collisions: Collide Player <-> Enemies <-> World <-> Pickups <-> Triggers
First: do it the naive way (no BSP, Octree, ...).
- Camera: FPS camera: that 'follows' the player.
Debug camera: Fly around in the world.
- Renderer: let the engine do the rendering. Game code just specifies all the entities (pickups, world, player, enemies, ...)
and renderer sorts out what has to be done.
- Load world, enemies, player-start-pos, etc. from file. For now create them manually.
- Engine should keep track of all the stuff in the game.
- CONCERNS:
- Raw Pointers: not quite sure if I should return a pointer to the game for e.g. the Player.
what if the pointer gets invalidated? A handle would solve this problem: I could first check
if the pointer behind the handle actually is valid and only then return it. I'll see if it bites me :)
- STL-Strings: sstream and string and ifstream etc. seem all very stupid. For now they work.
Replace them later when actually things are running. Actually C-Libs fread seems to be ok(?), like I did it in VKAL's platform layer.
- Pipeline creation: At the moment I create the pipeline within the renderer. But maybe it should be made more flexible later
by just providing the function to create the pipeline. The function's input would just be the data, e.g. shader, descriptors, etc.
- TODOs/Questions:
- How to compile shaders during comp-time?
- Some conclusions:
-> It is more important to get things up and running quickly. Code is garbage anyway!
Abstract away stuff like 'ReadFromFile' and then replace its implementation with something sane and not STL.
*/
class MyGame : public IGameClient
{
public:
MyGame(void):
m_Camera(NULL)
{}
~MyGame() {}
// Overrides from Interface
void OnEngineInitialized(void);
void Update(float dt, e3Input input);
Camera* m_Camera;
};
static MyGame * gameClient;
static IEngineService * engineService;
void MyGame::OnEngineInitialized(void)
{
printf("FROM GAME DLL: Engine Initialized! Ready to GO!\n");
engineService->DebugOut(L"From MyGame: Hellohoooo");
Player * player = engineService->CreatePlayer(glm::vec3(0.0f, 0.0f, 0.0f), "models/policeman.gpmesh");
//Player* player2 = engineService->CreatePlayer(glm::vec3(0.0f, 0.0f, 0.0f), "models/policeman.gpmesh");
m_Camera = engineService->CreateCamera(glm::vec3(2.0f, -2.0f, 5.0f));
}
// TODO: extra file!
enum Action {
ACTION_NONE = 0,
MOVE_CAM_FORWARD,
MOVE_CAM_BACKWARD,
MOVE_CAM_LEFT,
MOVE_CAM_RIGHT,
ROTATE_CAM_SIDE_FORWARD,
ROTATE_CAM_SIDE_BACKWARD,
ROTATE_CAM_UP_LEFT,
ROTATE_CAM_UP_RIGHT,
RESET_CAM,
MAX_ACTIONS
};
struct KeyToAction {
uint32_t scancode;
Action action;
};
static KeyToAction keyMappings[SDL_NUM_SCANCODES] = { };
void setupKeyMappings()
{
// load from config
keyMappings[SDL_SCANCODE_UP].action = ROTATE_CAM_SIDE_FORWARD;
keyMappings[SDL_SCANCODE_DOWN].action = ROTATE_CAM_SIDE_BACKWARD;
keyMappings[SDL_SCANCODE_LEFT].action = ROTATE_CAM_UP_LEFT;
keyMappings[SDL_SCANCODE_RIGHT].action = ROTATE_CAM_UP_RIGHT;
keyMappings[SDL_SCANCODE_W].action = MOVE_CAM_FORWARD;
keyMappings[SDL_SCANCODE_S].action = MOVE_CAM_BACKWARD;
keyMappings[SDL_SCANCODE_A].action = MOVE_CAM_LEFT;
keyMappings[SDL_SCANCODE_D].action = MOVE_CAM_RIGHT;
keyMappings[SDL_SCANCODE_R].action = RESET_CAM;
}
Action actionForKey(uint32_t scancode)
{
return keyMappings[scancode].action;
}
void MyGame::Update(float dt, e3Input input)
{
SDL_Log("Frametime: %f\n", dt);
//dt /= 1000.0f;
setupKeyMappings(); // TODO: setup once.
glm::vec3 camForward = glm::normalize(m_Camera->m_Center - m_Camera->m_Pos);
glm::vec3 camRight = glm::normalize(glm::cross(camForward, m_Camera->m_Up));
for (uint32_t scancode = 0; scancode < SDL_NUM_SCANCODES; ++scancode) { // TODO: really need to iterate over all of these every frame?
if (input.scancodes[scancode]) {
Action action = actionForKey(scancode);
if (action != ACTION_NONE) { // TODO: switch
if (action == ROTATE_CAM_SIDE_FORWARD)
m_Camera->RotateAroundSide(dt * glm::radians(0.07f));
if (action == ROTATE_CAM_SIDE_BACKWARD)
m_Camera->RotateAroundSide(dt * glm::radians(-0.07f));
if (action == ROTATE_CAM_UP_LEFT)
m_Camera->RotateAroundUp(dt * glm::radians(0.07f));
if (action == ROTATE_CAM_UP_RIGHT)
m_Camera->RotateAroundUp(dt * glm::radians(-0.07f));
if (action == MOVE_CAM_FORWARD)
m_Camera->Move(dt * 0.025f);
if (action == MOVE_CAM_BACKWARD)
m_Camera->Move(dt * (-0.025f));
if (action == MOVE_CAM_LEFT)
m_Camera->MoveSide(dt * 0.025f);
if (action == MOVE_CAM_RIGHT)
m_Camera->MoveSide(dt * (-0.025));
if (action == RESET_CAM)
m_Camera->ResetOrientation();
}
}
}
for (Uint8 mouseID = 0; mouseID < 255; mouseID++) {
if (input.mouseButtonID[mouseID]) {
SDL_Log("mouseID: %d\n", mouseID);
}
}
}
EXPORT_GAME_CLIENT(MyGame, gameClient, engineService);
| 34.875676 | 139 | 0.664755 | [
"geometry"
] |
152531cfebc1270fa4d9ef23ce2cac33fc55c0f1 | 670 | cpp | C++ | Dynamic Programming/1155 Number of Dice Rolls With Target Sum.cpp | ankitapuri/LeetCode-Solutions | 16d9b6a992663a19db373f207b23b95225f56c28 | [
"MIT"
] | 18 | 2021-11-07T06:45:25.000Z | 2022-03-03T10:37:01.000Z | Dynamic Programming/1155 Number of Dice Rolls With Target Sum.cpp | ankitapuri/LeetCode-Solutions | 16d9b6a992663a19db373f207b23b95225f56c28 | [
"MIT"
] | 1 | 2021-10-12T15:32:27.000Z | 2021-11-06T11:48:11.000Z | Dynamic Programming/1155 Number of Dice Rolls With Target Sum.cpp | ankitapuri/LeetCode-Solutions | 16d9b6a992663a19db373f207b23b95225f56c28 | [
"MIT"
] | 2 | 2021-11-25T10:25:44.000Z | 2021-12-31T15:16:47.000Z | class Solution {
public:
#define MOD 1000000007
int ways(int d,int f, int target,vector<vector<int>>&vec)
{
if(d==0 && target!=0) return 0;
if(d==0 && target==0) return 1;
if(vec[d][target]!=-1) return vec[d][target];
int ans=0;
for(int i=1;i<=f;i++)
{ if(i<=target){
int tempans=ways(d-1,f,target-i,vec);
ans = (ans%MOD+tempans%MOD)%MOD;
}
}
return vec[d][target]=ans%MOD;
}
int numRollsToTarget(int d, int f, int target) {
vector<vector<int>>vec(32,vector<int>(1001,-1));
return ways(d,f,target,vec)%MOD;
}
}; | 30.454545 | 62 | 0.502985 | [
"vector"
] |
1526ca531a0644b0815b408f94659901fce4a24a | 118,703 | hpp | C++ | utils/features/include/features/colors.hpp | probabilistic-anchoring/probanch | cfba24fd431ed7e7109b715018e344d7989f565d | [
"Apache-2.0"
] | 1 | 2020-02-27T14:00:27.000Z | 2020-02-27T14:00:27.000Z | utils/features/include/features/colors.hpp | probabilistic-anchoring/probanch | cfba24fd431ed7e7109b715018e344d7989f565d | [
"Apache-2.0"
] | null | null | null | utils/features/include/features/colors.hpp | probabilistic-anchoring/probanch | cfba24fd431ed7e7109b715018e344d7989f565d | [
"Apache-2.0"
] | null | null | null | /* This file is auto-generated, do not edit. */
#define COLOR_NAMES_MAX 1294
typedef struct ColorInfo {
const char *name;
const char *hex;
struct {
unsigned char r;
unsigned char g;
unsigned char b;
} rgb;
struct {
unsigned char h;
unsigned char s;
unsigned char v;
} hsv;
} ColorInfo;
typedef enum Color {
COLOR_ABSOLUTE_ZERO=0,
COLOR_ACID_GREEN,
COLOR_AERO,
COLOR_AERO_BLUE,
COLOR_AFRICAN_VIOLET,
COLOR_AIR_FORCE_BLUE_RAF,
COLOR_AIR_FORCE_BLUE_USAF,
COLOR_AIR_SUPERIORITY_BLUE,
COLOR_ALABAMA_CRIMSON,
COLOR_ALABASTER,
COLOR_ALIAS,
COLOR_ALICE_BLUE,
COLOR_ALIEN_ARMPIT,
COLOR_ALIZARIN_CRIMSON,
COLOR_ALLOY_ORANGE,
COLOR_ALMOND,
COLOR_AMARANTH,
COLOR_AMARANTH_DEEP_PURPLE,
COLOR_AMARANTH_PINK,
COLOR_AMARANTH_PURPLE,
COLOR_AMARANTH_RED,
COLOR_AMAZON,
COLOR_AMAZONITE,
COLOR_AMBER,
COLOR_AMBER_SAE_ECE,
COLOR_AMERICAN_ROSE,
COLOR_AMETHYST,
COLOR_ANDROID_GREEN,
COLOR_ANTIQUE_BRASS,
COLOR_ANTIQUE_BRONZE,
COLOR_ANTIQUE_FUCHSIA,
COLOR_ANTIQUE_RUBY,
COLOR_ANTIQUE_WHITE,
COLOR_ANTI_FLASH_WHITE,
COLOR_AO_ENGLISH,
COLOR_APPLE_GREEN,
COLOR_APRICOT,
COLOR_AQUA,
COLOR_AQUAMARINE,
COLOR_ARCTIC_LIME,
COLOR_ARMY_GREEN,
COLOR_ARSENIC,
COLOR_ARTICHOKE,
COLOR_ARYLIDE_YELLOW,
COLOR_ASH_GREY,
COLOR_ASPARAGUS,
COLOR_ATOMIC_TANGERINE,
COLOR_AUBURN,
COLOR_AUREOLIN,
COLOR_AUROMETALSAURUS,
COLOR_AVOCADO,
COLOR_AWESOME,
COLOR_AZTEC_GOLD,
COLOR_AZURE,
COLOR_AZUREISH_WHITE,
COLOR_AZURE_MIST,
COLOR_AZURE_WEB_COLOR,
COLOR_BABY_BLUE,
COLOR_BABY_BLUE_EYES,
COLOR_BABY_PINK,
COLOR_BABY_POWDER,
COLOR_BAKER_MILLER_PINK,
COLOR_BALL_BLUE,
COLOR_BANANA_MANIA,
COLOR_BANANA_YELLOW,
COLOR_BANGLADESH_GREEN,
COLOR_BARBIE_PINK,
COLOR_BARN_RED,
COLOR_BATTERY_CHARGED_BLUE,
COLOR_BATTLESHIP_GREY,
COLOR_BAZAAR,
COLOR_BEAU_BLUE,
COLOR_BEAVER,
COLOR_BEGONIA,
COLOR_BEIGE,
COLOR_BIG_DIP_O_RUBY,
COLOR_BIG_FOOT_FEET,
COLOR_BISQUE,
COLOR_BISTRE,
COLOR_BISTRE_BROWN,
COLOR_BITTERSWEET,
COLOR_BITTERSWEET_SHIMMER,
COLOR_BITTER_LEMON,
COLOR_BITTER_LIME,
COLOR_BLACK,
COLOR_BLACK_BEAN,
COLOR_BLACK_CORAL,
COLOR_BLACK_LEATHER_JACKET,
COLOR_BLACK_OLIVE,
COLOR_BLACK_SHADOWS,
COLOR_BLANCHED_ALMOND,
COLOR_BLAST_OFF_BRONZE,
COLOR_BLEU_DE_FRANCE,
COLOR_BLIZZARD_BLUE,
COLOR_BLOND,
COLOR_BLUE,
COLOR_BLUEBERRY,
COLOR_BLUEBONNET,
COLOR_BLUE_BELL,
COLOR_BLUE_BOLT,
COLOR_BLUE_CRAYOLA,
COLOR_BLUE_GRAY,
COLOR_BLUE_GREEN,
COLOR_BLUE_JEANS,
COLOR_BLUE_LAGOON,
COLOR_BLUE_MAGENTA_VIOLET,
COLOR_BLUE_MUNSELL,
COLOR_BLUE_NCS,
COLOR_BLUE_PANTONE,
COLOR_BLUE_PIGMENT,
COLOR_BLUE_RYB,
COLOR_BLUE_SAPPHIRE,
COLOR_BLUE_VIOLET,
COLOR_BLUE_YONDER,
COLOR_BLUSH,
COLOR_BOLE,
COLOR_BONDI_BLUE,
COLOR_BONE,
COLOR_BOOGER_BUSTER,
COLOR_BOSTON_UNIVERSITY_RED,
COLOR_BOTTLE_GREEN,
COLOR_BOYSENBERRY,
COLOR_BRANDEIS_BLUE,
COLOR_BRASS,
COLOR_BRICK_RED,
COLOR_BRIGHT_CERULEAN,
COLOR_BRIGHT_GREEN,
COLOR_BRIGHT_LAVENDER,
COLOR_BRIGHT_LILAC,
COLOR_BRIGHT_MAROON,
COLOR_BRIGHT_NAVY_BLUE,
COLOR_BRIGHT_PINK,
COLOR_BRIGHT_TURQUOISE,
COLOR_BRIGHT_UBE,
COLOR_BRIGHT_YELLOW_CRAYOLA,
COLOR_BRILLIANT_AZURE,
COLOR_BRILLIANT_LAVENDER,
COLOR_BRILLIANT_ROSE,
COLOR_BRINK_PINK,
COLOR_BRITISH_RACING_GREEN,
COLOR_BRONZE,
COLOR_BRONZE_YELLOW,
COLOR_BROWN_NOSE,
COLOR_BROWN_SUGAR,
COLOR_BROWN_TRADITIONAL,
COLOR_BROWN_WEB,
COLOR_BROWN_YELLOW,
COLOR_BRUNSWICK_GREEN,
COLOR_BUBBLES,
COLOR_BUBBLE_GUM,
COLOR_BUD_GREEN,
COLOR_BUFF,
COLOR_BULGARIAN_ROSE,
COLOR_BURGUNDY,
COLOR_BURLYWOOD,
COLOR_BURNISHED_BROWN,
COLOR_BURNT_ORANGE,
COLOR_BURNT_SIENNA,
COLOR_BURNT_UMBER,
COLOR_BUTTON_BLUE,
COLOR_BYZANTINE,
COLOR_BYZANTIUM,
COLOR_B_DAZZLED_BLUE,
COLOR_CADET,
COLOR_CADET_BLUE,
COLOR_CADET_GREY,
COLOR_CADMIUM_GREEN,
COLOR_CADMIUM_ORANGE,
COLOR_CADMIUM_RED,
COLOR_CADMIUM_YELLOW,
COLOR_CAF_AU_LAIT,
COLOR_CAF_NOIR,
COLOR_CAL_POLY_POMONA_GREEN,
COLOR_CAMBRIDGE_BLUE,
COLOR_CAMEL,
COLOR_CAMEO_PINK,
COLOR_CAMOUFLAGE_GREEN,
COLOR_CANARY,
COLOR_CANARY_YELLOW,
COLOR_CANDY_APPLE_RED,
COLOR_CANDY_PINK,
COLOR_CAPRI,
COLOR_CAPUT_MORTUUM,
COLOR_CARDINAL,
COLOR_CARIBBEAN_GREEN,
COLOR_CARMINE,
COLOR_CARMINE_M_P,
COLOR_CARMINE_PINK,
COLOR_CARMINE_RED,
COLOR_CARNATION_PINK,
COLOR_CARNELIAN,
COLOR_CAROLINA_BLUE,
COLOR_CARROT_ORANGE,
COLOR_CASTLETON_GREEN,
COLOR_CATALINA_BLUE,
COLOR_CATAWBA,
COLOR_CEDAR_CHEST,
COLOR_CEIL,
COLOR_CELADON,
COLOR_CELADON_BLUE,
COLOR_CELADON_GREEN,
COLOR_CELESTE,
COLOR_CELESTIAL_BLUE,
COLOR_CERISE,
COLOR_CERISE_PINK,
COLOR_CERULEAN,
COLOR_CERULEAN_BLUE,
COLOR_CERULEAN_FROST,
COLOR_CG_BLUE,
COLOR_CG_RED,
COLOR_CHAMOISEE,
COLOR_CHAMPAGNE,
COLOR_CHAMPAGNE_PINK,
COLOR_CHARCOAL,
COLOR_CHARLESTON_GREEN,
COLOR_CHARM_PINK,
COLOR_CHARTREUSE_TRADITIONAL,
COLOR_CHARTREUSE_WEB,
COLOR_CHERRY,
COLOR_CHERRY_BLOSSOM_PINK,
COLOR_CHESTNUT,
COLOR_CHINA_PINK,
COLOR_CHINA_ROSE,
COLOR_CHINESE_RED,
COLOR_CHINESE_VIOLET,
COLOR_CHLOROPHYLL_GREEN,
COLOR_CHOCOLATE_TRADITIONAL,
COLOR_CHOCOLATE_WEB,
COLOR_CHROME_YELLOW,
COLOR_CINEREOUS,
COLOR_CINNABAR,
COLOR_CINNAMON,
COLOR_CINNAMON_SATIN,
COLOR_CITRINE,
COLOR_CITRON,
COLOR_CLARET,
COLOR_CLASSIC_ROSE,
COLOR_COBALT_BLUE,
COLOR_COCOA_BROWN,
COLOR_COCONUT,
COLOR_COFFEE,
COLOR_COLUMBIA_BLUE,
COLOR_CONGO_PINK,
COLOR_COOL_BLACK,
COLOR_COOL_GREY,
COLOR_COPPER,
COLOR_COPPER_CRAYOLA,
COLOR_COPPER_PENNY,
COLOR_COPPER_RED,
COLOR_COPPER_ROSE,
COLOR_COQUELICOT,
COLOR_CORAL,
COLOR_CORAL_PINK,
COLOR_CORAL_RED,
COLOR_CORAL_REEF,
COLOR_CORDOVAN,
COLOR_CORN,
COLOR_CORNELL_RED,
COLOR_CORNFLOWER_BLUE,
COLOR_CORNSILK,
COLOR_COSMIC_COBALT,
COLOR_COSMIC_LATTE,
COLOR_COTTON_CANDY,
COLOR_COYOTE_BROWN,
COLOR_CREAM,
COLOR_CRIMSON,
COLOR_CRIMSON_GLORY,
COLOR_CRIMSON_RED,
COLOR_CULTURED,
COLOR_CYAN,
COLOR_CYAN_AZURE,
COLOR_CYAN_BLUE_AZURE,
COLOR_CYAN_COBALT_BLUE,
COLOR_CYAN_CORNFLOWER_BLUE,
COLOR_CYAN_PROCESS,
COLOR_CYBER_GRAPE,
COLOR_CYBER_YELLOW,
COLOR_CYCLAMEN,
COLOR_DAFFODIL,
COLOR_DANDELION,
COLOR_DARK_BLUE,
COLOR_DARK_BLUE_GRAY,
COLOR_DARK_BROWN,
COLOR_DARK_BROWN_TANGELO,
COLOR_DARK_BYZANTIUM,
COLOR_DARK_CANDY_APPLE_RED,
COLOR_DARK_CERULEAN,
COLOR_DARK_CHESTNUT,
COLOR_DARK_CORAL,
COLOR_DARK_CYAN,
COLOR_DARK_ELECTRIC_BLUE,
COLOR_DARK_GOLDENROD,
COLOR_DARK_GRAY_X11,
COLOR_DARK_GREEN,
COLOR_DARK_GREEN_X11,
COLOR_DARK_GUNMETAL,
COLOR_DARK_IMPERIAL_BLUE,
COLOR_DARK_JUNGLE_GREEN,
COLOR_DARK_KHAKI,
COLOR_DARK_LAVA,
COLOR_DARK_LAVENDER,
COLOR_DARK_LIVER,
COLOR_DARK_LIVER_HORSES,
COLOR_DARK_MAGENTA,
COLOR_DARK_MEDIUM_GRAY,
COLOR_DARK_MIDNIGHT_BLUE,
COLOR_DARK_MOSS_GREEN,
COLOR_DARK_OLIVE_GREEN,
COLOR_DARK_ORANGE,
COLOR_DARK_ORCHID,
COLOR_DARK_PASTEL_BLUE,
COLOR_DARK_PASTEL_GREEN,
COLOR_DARK_PASTEL_PURPLE,
COLOR_DARK_PASTEL_RED,
COLOR_DARK_PINK,
COLOR_DARK_POWDER_BLUE,
COLOR_DARK_PUCE,
COLOR_DARK_PURPLE,
COLOR_DARK_RASPBERRY,
COLOR_DARK_RED,
COLOR_DARK_SALMON,
COLOR_DARK_SCARLET,
COLOR_DARK_SEA_GREEN,
COLOR_DARK_SIENNA,
COLOR_DARK_SKY_BLUE,
COLOR_DARK_SLATE_BLUE,
COLOR_DARK_SLATE_GRAY,
COLOR_DARK_SPRING_GREEN,
COLOR_DARK_TAN,
COLOR_DARK_TANGERINE,
COLOR_DARK_TAUPE,
COLOR_DARK_TERRA_COTTA,
COLOR_DARK_TURQUOISE,
COLOR_DARK_VANILLA,
COLOR_DARK_VIOLET,
COLOR_DARK_YELLOW,
COLOR_DARTMOUTH_GREEN,
COLOR_DAVY_S_GREY,
COLOR_DEBIAN_RED,
COLOR_DEEP_AQUAMARINE,
COLOR_DEEP_CARMINE,
COLOR_DEEP_CARMINE_PINK,
COLOR_DEEP_CARROT_ORANGE,
COLOR_DEEP_CERISE,
COLOR_DEEP_CHAMPAGNE,
COLOR_DEEP_CHESTNUT,
COLOR_DEEP_COFFEE,
COLOR_DEEP_FUCHSIA,
COLOR_DEEP_GREEN,
COLOR_DEEP_GREEN_CYAN_TURQUOISE,
COLOR_DEEP_JUNGLE_GREEN,
COLOR_DEEP_KOAMARU,
COLOR_DEEP_LEMON,
COLOR_DEEP_LILAC,
COLOR_DEEP_MAGENTA,
COLOR_DEEP_MAROON,
COLOR_DEEP_MAUVE,
COLOR_DEEP_MOSS_GREEN,
COLOR_DEEP_PEACH,
COLOR_DEEP_PINK,
COLOR_DEEP_PUCE,
COLOR_DEEP_RED,
COLOR_DEEP_RUBY,
COLOR_DEEP_SAFFRON,
COLOR_DEEP_SKY_BLUE,
COLOR_DEEP_SPACE_SPARKLE,
COLOR_DEEP_SPRING_BUD,
COLOR_DEEP_TAUPE,
COLOR_DEEP_TUSCAN_RED,
COLOR_DEEP_VIOLET,
COLOR_DEER,
COLOR_DENIM,
COLOR_DENIM_BLUE,
COLOR_DESATURATED_CYAN,
COLOR_DESERT,
COLOR_DESERT_SAND,
COLOR_DESIRE,
COLOR_DIAMOND,
COLOR_DIM_GRAY,
COLOR_DINGY_DUNGEON,
COLOR_DIRT,
COLOR_DODGER_BLUE,
COLOR_DOGWOOD_ROSE,
COLOR_DOLLAR_BILL,
COLOR_DOLPHIN_GRAY,
COLOR_DONKEY_BROWN,
COLOR_DRAB,
COLOR_DUKE_BLUE,
COLOR_DUST_STORM,
COLOR_DUTCH_WHITE,
COLOR_EBONY,
COLOR_ECRU,
COLOR_EERIE_BLACK,
COLOR_EGGPLANT,
COLOR_EGGSHELL,
COLOR_EGYPTIAN_BLUE,
COLOR_ELECTRIC_BLUE,
COLOR_ELECTRIC_CRIMSON,
COLOR_ELECTRIC_CYAN,
COLOR_ELECTRIC_GREEN,
COLOR_ELECTRIC_INDIGO,
COLOR_ELECTRIC_LAVENDER,
COLOR_ELECTRIC_LIME,
COLOR_ELECTRIC_PURPLE,
COLOR_ELECTRIC_ULTRAMARINE,
COLOR_ELECTRIC_VIOLET,
COLOR_ELECTRIC_YELLOW,
COLOR_EMERALD,
COLOR_EMINENCE,
COLOR_ENGLISH_GREEN,
COLOR_ENGLISH_LAVENDER,
COLOR_ENGLISH_RED,
COLOR_ENGLISH_VERMILLION,
COLOR_ENGLISH_VIOLET,
COLOR_ETON_BLUE,
COLOR_EUCALYPTUS,
COLOR_FALLOW,
COLOR_FALU_RED,
COLOR_FANDANGO,
COLOR_FANDANGO_PINK,
COLOR_FASHION_FUCHSIA,
COLOR_FAWN,
COLOR_FELDGRAU,
COLOR_FELDSPAR,
COLOR_FERN_GREEN,
COLOR_FERRARI_RED,
COLOR_FIELD_DRAB,
COLOR_FIERY_ROSE,
COLOR_FIREBRICK,
COLOR_FIRE_ENGINE_RED,
COLOR_FLAME,
COLOR_FLAMINGO_PINK,
COLOR_FLATTERY,
COLOR_FLAVESCENT,
COLOR_FLAX,
COLOR_FLIRT,
COLOR_FLORAL_WHITE,
COLOR_FLUORESCENT_ORANGE,
COLOR_FLUORESCENT_PINK,
COLOR_FLUORESCENT_YELLOW,
COLOR_FOLLY,
COLOR_FOREST_GREEN_TRADITIONAL,
COLOR_FOREST_GREEN_WEB,
COLOR_FRENCH_BEIGE,
COLOR_FRENCH_BISTRE,
COLOR_FRENCH_BLUE,
COLOR_FRENCH_FUCHSIA,
COLOR_FRENCH_LILAC,
COLOR_FRENCH_LIME,
COLOR_FRENCH_MAUVE,
COLOR_FRENCH_PINK,
COLOR_FRENCH_PLUM,
COLOR_FRENCH_PUCE,
COLOR_FRENCH_RASPBERRY,
COLOR_FRENCH_ROSE,
COLOR_FRENCH_SKY_BLUE,
COLOR_FRENCH_VIOLET,
COLOR_FRENCH_WINE,
COLOR_FRESH_AIR,
COLOR_FROSTBITE,
COLOR_FUCHSIA,
COLOR_FUCHSIA_CRAYOLA,
COLOR_FUCHSIA_PINK,
COLOR_FUCHSIA_PURPLE,
COLOR_FUCHSIA_ROSE,
COLOR_FULVOUS,
COLOR_FUZZY_WUZZY,
COLOR_GAINSBORO,
COLOR_GAMBOGE,
COLOR_GAMBOGE_ORANGE_BROWN,
COLOR_GARGOYLE_GAS,
COLOR_GENERIC_VIRIDIAN,
COLOR_GHOST_WHITE,
COLOR_GIANTS_ORANGE,
COLOR_GIANT_S_CLUB,
COLOR_GINGER,
COLOR_GLAUCOUS,
COLOR_GLITTER,
COLOR_GLOSSY_GRAPE,
COLOR_GOLDENROD,
COLOR_GOLDEN_BROWN,
COLOR_GOLDEN_POPPY,
COLOR_GOLDEN_YELLOW,
COLOR_GOLD_FUSION,
COLOR_GOLD_METALLIC,
COLOR_GOLD_WEB_GOLDEN,
COLOR_GO_GREEN,
COLOR_GRANITE_GRAY,
COLOR_GRANNY_SMITH_APPLE,
COLOR_GRAPE,
COLOR_GRAY,
COLOR_GRAY_ASPARAGUS,
COLOR_GRAY_BLUE,
COLOR_GRAY_HTML_CSS_GRAY,
COLOR_GRAY_X11_GRAY,
COLOR_GREEN_BLUE,
COLOR_GREEN_COLOR_WHEEL_X11_GREEN,
COLOR_GREEN_CRAYOLA,
COLOR_GREEN_CYAN,
COLOR_GREEN_HTML_CSS_COLOR,
COLOR_GREEN_LIZARD,
COLOR_GREEN_MUNSELL,
COLOR_GREEN_NCS,
COLOR_GREEN_PANTONE,
COLOR_GREEN_PIGMENT,
COLOR_GREEN_RYB,
COLOR_GREEN_SHEEN,
COLOR_GREEN_YELLOW,
COLOR_GRIZZLY,
COLOR_GRULLO,
COLOR_GUNMETAL,
COLOR_GUPPIE_GREEN,
COLOR_HALAY_BE,
COLOR_HANSA_YELLOW,
COLOR_HAN_BLUE,
COLOR_HAN_PURPLE,
COLOR_HARLEQUIN,
COLOR_HARLEQUIN_GREEN,
COLOR_HARVARD_CRIMSON,
COLOR_HARVEST_GOLD,
COLOR_HEART_GOLD,
COLOR_HEAT_WAVE,
COLOR_HEIDELBERG_RED,
COLOR_HELIOTROPE,
COLOR_HELIOTROPE_GRAY,
COLOR_HELIOTROPE_MAGENTA,
COLOR_HOLLYWOOD_CERISE,
COLOR_HONEYDEW,
COLOR_HONOLULU_BLUE,
COLOR_HOOKER_S_GREEN,
COLOR_HOT_MAGENTA,
COLOR_HOT_PINK,
COLOR_HTTP_WWW_UNT_EDU_IDENTITYGUIDE_WEB_ELECTRONIC_HTM_NORTH_TEXAS_GREEN,
COLOR_HUNTER_GREEN,
COLOR_ICEBERG,
COLOR_ICTERINE,
COLOR_IGUANA_GREEN,
COLOR_ILLUMINATING_EMERALD,
COLOR_IMPERIAL,
COLOR_IMPERIAL_BLUE,
COLOR_IMPERIAL_PURPLE,
COLOR_IMPERIAL_RED,
COLOR_INCHWORM,
COLOR_INDEPENDENCE,
COLOR_INDIAN_RED,
COLOR_INDIAN_YELLOW,
COLOR_INDIA_GREEN,
COLOR_INDIGO,
COLOR_INDIGO_DYE,
COLOR_INDIGO_WEB,
COLOR_INFRA_RED,
COLOR_INTERDIMENSIONAL_BLUE,
COLOR_INTERNATIONAL_KLEIN_BLUE,
COLOR_INTERNATIONAL_ORANGE_AEROSPACE,
COLOR_INTERNATIONAL_ORANGE_ENGINEERING,
COLOR_INTERNATIONAL_ORANGE_GOLDEN_GATE_BRIDGE,
COLOR_IRIS,
COLOR_IRRESISTIBLE,
COLOR_ISABELLINE,
COLOR_ISLAMIC_GREEN,
COLOR_ITALIAN_SKY_BLUE,
COLOR_IVORY,
COLOR_JADE,
COLOR_JAPANESE_CARMINE,
COLOR_JAPANESE_INDIGO,
COLOR_JAPANESE_VIOLET,
COLOR_JASMINE,
COLOR_JASPER,
COLOR_JAZZBERRY_JAM,
COLOR_JELLY_BEAN,
COLOR_JET,
COLOR_JONQUIL,
COLOR_JORDY_BLUE,
COLOR_JUNE_BUD,
COLOR_JUNGLE_GREEN,
COLOR_KELLY_GREEN,
COLOR_KENYAN_COPPER,
COLOR_KEPPEL,
COLOR_KEY_LIME,
COLOR_KHAKI_HTML_CSS_KHAKI,
COLOR_KHAKI_X11_LIGHT_KHAKI,
COLOR_KIWI,
COLOR_KOBE,
COLOR_KOBI,
COLOR_KOBICHA,
COLOR_KOMBU_GREEN,
COLOR_KSU_PURPLE,
COLOR_KU_CRIMSON,
COLOR_LANGUID_LAVENDER,
COLOR_LAPIS_LAZULI,
COLOR_LASER_LEMON,
COLOR_LAUREL_GREEN,
COLOR_LAVA,
COLOR_LAVENDER_BLUE,
COLOR_LAVENDER_BLUSH,
COLOR_LAVENDER_FLORAL,
COLOR_LAVENDER_GRAY,
COLOR_LAVENDER_INDIGO,
COLOR_LAVENDER_MAGENTA,
COLOR_LAVENDER_MIST,
COLOR_LAVENDER_PINK,
COLOR_LAVENDER_PURPLE,
COLOR_LAVENDER_ROSE,
COLOR_LAVENDER_WEB,
COLOR_LAWN_GREEN,
COLOR_LA_SALLE_GREEN,
COLOR_LEMON,
COLOR_LEMON_CHIFFON,
COLOR_LEMON_CURRY,
COLOR_LEMON_GLACIER,
COLOR_LEMON_LIME,
COLOR_LEMON_MERINGUE,
COLOR_LEMON_YELLOW,
COLOR_LIBERTY,
COLOR_LICORICE,
COLOR_LIGHT_APRICOT,
COLOR_LIGHT_BLUE,
COLOR_LIGHT_BROWN,
COLOR_LIGHT_CARMINE_PINK,
COLOR_LIGHT_COBALT_BLUE,
COLOR_LIGHT_CORAL,
COLOR_LIGHT_CORNFLOWER_BLUE,
COLOR_LIGHT_CRIMSON,
COLOR_LIGHT_CYAN,
COLOR_LIGHT_DEEP_PINK,
COLOR_LIGHT_FRENCH_BEIGE,
COLOR_LIGHT_FUCHSIA_PINK,
COLOR_LIGHT_GOLDENROD_YELLOW,
COLOR_LIGHT_GRAY,
COLOR_LIGHT_GRAYISH_MAGENTA,
COLOR_LIGHT_GREEN,
COLOR_LIGHT_HOT_PINK,
COLOR_LIGHT_KHAKI,
COLOR_LIGHT_MEDIUM_ORCHID,
COLOR_LIGHT_MOSS_GREEN,
COLOR_LIGHT_ORANGE,
COLOR_LIGHT_ORCHID,
COLOR_LIGHT_PASTEL_PURPLE,
COLOR_LIGHT_PINK,
COLOR_LIGHT_RED_OCHRE,
COLOR_LIGHT_SALMON,
COLOR_LIGHT_SALMON_PINK,
COLOR_LIGHT_SEA_GREEN,
COLOR_LIGHT_SKY_BLUE,
COLOR_LIGHT_SLATE_GRAY,
COLOR_LIGHT_STEEL_BLUE,
COLOR_LIGHT_TAUPE,
COLOR_LIGHT_THULIAN_PINK,
COLOR_LIGHT_YELLOW,
COLOR_LILAC,
COLOR_LILAC_LUSTER,
COLOR_LIMERICK,
COLOR_LIME_COLOR_WHEEL,
COLOR_LIME_GREEN,
COLOR_LIME_WEB_X11_GREEN,
COLOR_LINCOLN_GREEN,
COLOR_LINEN,
COLOR_LISERAN_PURPLE,
COLOR_LITTLE_BOY_BLUE,
COLOR_LIVER,
COLOR_LIVER_CHESTNUT,
COLOR_LIVER_DOGS,
COLOR_LIVER_ORGAN,
COLOR_LIVID,
COLOR_LOEEN_LOPEN_LOOK_VOMIT_INDOGO_LOPEN_GABRIEL,
COLOR_LUMBER,
COLOR_LUST,
COLOR_MAASTRICHT_BLUE,
COLOR_MACARONI_AND_CHEESE,
COLOR_MADDER_LAKE,
COLOR_MAGENTA,
COLOR_MAGENTA_CRAYOLA,
COLOR_MAGENTA_DYE,
COLOR_MAGENTA_HAZE,
COLOR_MAGENTA_PANTONE,
COLOR_MAGENTA_PINK,
COLOR_MAGENTA_PROCESS,
COLOR_MAGIC_MINT,
COLOR_MAGIC_POTION,
COLOR_MAGNOLIA,
COLOR_MAHOGANY,
COLOR_MAIZE,
COLOR_MAJORELLE_BLUE,
COLOR_MALACHITE,
COLOR_MANATEE,
COLOR_MANDARIN,
COLOR_MANGO_TANGO,
COLOR_MANTIS,
COLOR_MARDI_GRAS,
COLOR_MARIGOLD,
COLOR_MAROON_CRAYOLA,
COLOR_MAROON_HTML_CSS,
COLOR_MAROON_X11,
COLOR_MAUVE,
COLOR_MAUVELOUS,
COLOR_MAUVE_TAUPE,
COLOR_MAXIMUM_BLUE,
COLOR_MAXIMUM_BLUE_GREEN,
COLOR_MAXIMUM_BLUE_PURPLE,
COLOR_MAXIMUM_GREEN,
COLOR_MAXIMUM_GREEN_YELLOW,
COLOR_MAXIMUM_PURPLE,
COLOR_MAXIMUM_RED,
COLOR_MAXIMUM_RED_PURPLE,
COLOR_MAXIMUM_YELLOW,
COLOR_MAXIMUM_YELLOW_RED,
COLOR_MAYA_BLUE,
COLOR_MAY_GREEN,
COLOR_MEAT_BROWN,
COLOR_MEDIUM_AQUAMARINE,
COLOR_MEDIUM_BLUE,
COLOR_MEDIUM_CANDY_APPLE_RED,
COLOR_MEDIUM_CARMINE,
COLOR_MEDIUM_CHAMPAGNE,
COLOR_MEDIUM_ELECTRIC_BLUE,
COLOR_MEDIUM_JUNGLE_GREEN,
COLOR_MEDIUM_LAVENDER_MAGENTA,
COLOR_MEDIUM_ORCHID,
COLOR_MEDIUM_PERSIAN_BLUE,
COLOR_MEDIUM_PURPLE,
COLOR_MEDIUM_RED_VIOLET,
COLOR_MEDIUM_RUBY,
COLOR_MEDIUM_SEA_GREEN,
COLOR_MEDIUM_SKY_BLUE,
COLOR_MEDIUM_SLATE_BLUE,
COLOR_MEDIUM_SPRING_BUD,
COLOR_MEDIUM_SPRING_GREEN,
COLOR_MEDIUM_TAUPE,
COLOR_MEDIUM_TURQUOISE,
COLOR_MEDIUM_TUSCAN_RED,
COLOR_MEDIUM_VERMILION,
COLOR_MEDIUM_VIOLET_RED,
COLOR_MELLOW_APRICOT,
COLOR_MELLOW_YELLOW,
COLOR_MELON,
COLOR_METALLIC_SEAWEED,
COLOR_METALLIC_SUNBURST,
COLOR_MEXICAN_PINK,
COLOR_MIDDLE_BLUE,
COLOR_MIDDLE_BLUE_GREEN,
COLOR_MIDDLE_BLUE_PURPLE,
COLOR_MIDDLE_GREEN,
COLOR_MIDDLE_GREEN_YELLOW,
COLOR_MIDDLE_PURPLE,
COLOR_MIDDLE_RED,
COLOR_MIDDLE_RED_PURPLE,
COLOR_MIDDLE_YELLOW,
COLOR_MIDDLE_YELLOW_RED,
COLOR_MIDNIGHT,
COLOR_MIDNIGHT_BLUE,
COLOR_MIDNIGHT_GREEN_EAGLE_GREEN,
COLOR_MIKADO_YELLOW,
COLOR_MILK,
COLOR_MIMI_PINK,
COLOR_MINDARO,
COLOR_MING,
COLOR_MINION_YELLOW,
COLOR_MINT,
COLOR_MINT_CREAM,
COLOR_MINT_GREEN,
COLOR_MISTY_MOSS,
COLOR_MISTY_ROSE,
COLOR_MOCCASIN,
COLOR_MODE_BEIGE,
COLOR_MOONSTONE_BLUE,
COLOR_MORDANT_RED_19,
COLOR_MORNING_BLUE,
COLOR_MOSS_GREEN,
COLOR_MOUNTAIN_MEADOW,
COLOR_MOUNTBATTEN_PINK,
COLOR_MSU_GREEN,
COLOR_MUGHAL_GREEN,
COLOR_MULBERRY,
COLOR_MUMMY_S_TOMB,
COLOR_MUSTARD,
COLOR_MYRTLE_GREEN,
COLOR_MYSTIC,
COLOR_MYSTIC_MAROON,
COLOR_NADESHIKO_PINK,
COLOR_NAPIER_GREEN,
COLOR_NAPLES_YELLOW,
COLOR_NAVAJO_WHITE,
COLOR_NAVY,
COLOR_NAVY_PURPLE,
COLOR_NEON_CARROT,
COLOR_NEON_FUCHSIA,
COLOR_NEON_GREEN,
COLOR_NEW_CAR,
COLOR_NEW_YORK_PINK,
COLOR_NICKEL,
COLOR_NON_PHOTO_BLUE,
COLOR_NYANZA,
COLOR_OCEAN_BLUE,
COLOR_OCEAN_BOAT_BLUE,
COLOR_OCEAN_GREEN,
COLOR_OCHRE,
COLOR_OFFICE_GREEN,
COLOR_OGRE_ODOR,
COLOR_OLD_BURGUNDY,
COLOR_OLD_GOLD,
COLOR_OLD_HELIOTROPE,
COLOR_OLD_LACE,
COLOR_OLD_LAVENDER,
COLOR_OLD_MAUVE,
COLOR_OLD_MOSS_GREEN,
COLOR_OLD_ROSE,
COLOR_OLD_SILVER,
COLOR_OLIVE,
COLOR_OLIVE_DRAB_3,
COLOR_OLIVE_DRAB_7,
COLOR_OLIVINE,
COLOR_ONYX,
COLOR_OPERA_MAUVE,
COLOR_ORANGE_COLOR_WHEEL,
COLOR_ORANGE_CRAYOLA,
COLOR_ORANGE_PANTONE,
COLOR_ORANGE_PEEL,
COLOR_ORANGE_RED,
COLOR_ORANGE_RYB,
COLOR_ORANGE_SODA,
COLOR_ORANGE_WEB,
COLOR_ORANGE_YELLOW,
COLOR_ORCHID,
COLOR_ORCHID_PINK,
COLOR_ORIOLES_ORANGE,
COLOR_OTTER_BROWN,
COLOR_OUTER_SPACE,
COLOR_OUTRAGEOUS_ORANGE,
COLOR_OU_CRIMSON_RED,
COLOR_OXFORD_BLUE,
COLOR_PACIFIC_BLUE,
COLOR_PAKISTAN_GREEN,
COLOR_PALATINATE_BLUE,
COLOR_PALATINATE_PURPLE,
COLOR_PALE_AQUA,
COLOR_PALE_BLUE,
COLOR_PALE_BROWN,
COLOR_PALE_CARMINE,
COLOR_PALE_CERULEAN,
COLOR_PALE_CHESTNUT,
COLOR_PALE_COPPER,
COLOR_PALE_CORNFLOWER_BLUE,
COLOR_PALE_CYAN,
COLOR_PALE_GOLD,
COLOR_PALE_GOLDENROD,
COLOR_PALE_GREEN,
COLOR_PALE_LAVENDER,
COLOR_PALE_MAGENTA,
COLOR_PALE_MAGENTA_PINK,
COLOR_PALE_PINK,
COLOR_PALE_PLUM,
COLOR_PALE_RED_VIOLET,
COLOR_PALE_ROBIN_EGG_BLUE,
COLOR_PALE_SILVER,
COLOR_PALE_SPRING_BUD,
COLOR_PALE_TAUPE,
COLOR_PALE_TURQUOISE,
COLOR_PALE_VIOLET,
COLOR_PALE_VIOLET_RED,
COLOR_PALM_LEAF,
COLOR_PANSY_PURPLE,
COLOR_PAOLO_VERONESE_GREEN,
COLOR_PAPAYA_WHIP,
COLOR_PARADISE_PINK,
COLOR_PARIS_GREEN,
COLOR_PARROT_PINK,
COLOR_PASTEL_BLUE,
COLOR_PASTEL_BROWN,
COLOR_PASTEL_GRAY,
COLOR_PASTEL_GREEN,
COLOR_PASTEL_MAGENTA,
COLOR_PASTEL_ORANGE,
COLOR_PASTEL_PINK,
COLOR_PASTEL_PURPLE,
COLOR_PASTEL_RED,
COLOR_PASTEL_VIOLET,
COLOR_PASTEL_YELLOW,
COLOR_PATRIARCH,
COLOR_PAYNE_S_GREY,
COLOR_PEACH,
COLOR_PEACH_ORANGE,
COLOR_PEACH_PUFF,
COLOR_PEACH_YELLOW,
COLOR_PEAR,
COLOR_PEARL,
COLOR_PEARLY_PURPLE,
COLOR_PEARL_AQUA,
COLOR_PERIDOT,
COLOR_PERIWINKLE,
COLOR_PERMANENT_GERANIUM_LAKE,
COLOR_PERSIAN_BLUE,
COLOR_PERSIAN_GREEN,
COLOR_PERSIAN_INDIGO,
COLOR_PERSIAN_ORANGE,
COLOR_PERSIAN_PINK,
COLOR_PERSIAN_PLUM,
COLOR_PERSIAN_RED,
COLOR_PERSIAN_ROSE,
COLOR_PERSIMMON,
COLOR_PERU,
COLOR_PEWTER_BLUE,
COLOR_PHLOX,
COLOR_PHTHALO_BLUE,
COLOR_PHTHALO_GREEN,
COLOR_PICTON_BLUE,
COLOR_PICTORIAL_CARMINE,
COLOR_PIGGY_PINK,
COLOR_PINEAPPLE,
COLOR_PINE_GREEN,
COLOR_PINK,
COLOR_PINK_FLAMINGO,
COLOR_PINK_LACE,
COLOR_PINK_LAVENDER,
COLOR_PINK_ORANGE,
COLOR_PINK_PANTONE,
COLOR_PINK_PEARL,
COLOR_PINK_RASPBERRY,
COLOR_PINK_SHERBET,
COLOR_PISTACHIO,
COLOR_PIXIE_POWDER,
COLOR_PLATINUM,
COLOR_PLUM,
COLOR_PLUMP_PURPLE,
COLOR_PLUM_WEB,
COLOR_POLISHED_PINE,
COLOR_POMP_AND_POWER,
COLOR_POPSTAR,
COLOR_PORTLAND_ORANGE,
COLOR_POWDER_BLUE,
COLOR_PRINCESS_PERFUME,
COLOR_PRINCETON_ORANGE,
COLOR_PRUNE,
COLOR_PRUSSIAN_BLUE,
COLOR_PSYCHEDELIC_PURPLE,
COLOR_PUCE,
COLOR_PUCE_RED,
COLOR_PULLMAN_BROWN_UPS_BROWN,
COLOR_PULLMAN_GREEN,
COLOR_PUMPKIN,
COLOR_PURPLE_HEART,
COLOR_PURPLE_HTML,
COLOR_PURPLE_MOUNTAIN_MAJESTY,
COLOR_PURPLE_MUNSELL,
COLOR_PURPLE_NAVY,
COLOR_PURPLE_PIZZAZZ,
COLOR_PURPLE_PLUM,
COLOR_PURPLE_TAUPE,
COLOR_PURPLE_X11,
COLOR_PURPUREUS,
COLOR_QUARTZ,
COLOR_QUEEN_BLUE,
COLOR_QUEEN_PINK,
COLOR_QUICK_SILVER,
COLOR_QUINACRIDONE_MAGENTA,
COLOR_RACKLEY,
COLOR_RADICAL_RED,
COLOR_RAISIN_BLACK,
COLOR_RAJAH,
COLOR_RASPBERRY,
COLOR_RASPBERRY_GLACE,
COLOR_RASPBERRY_PINK,
COLOR_RASPBERRY_ROSE,
COLOR_RAW_SIENNA,
COLOR_RAW_UMBER,
COLOR_RAZZLE_DAZZLE_ROSE,
COLOR_RAZZMATAZZ,
COLOR_RAZZMIC_BERRY,
COLOR_REBECCA_PURPLE,
COLOR_RED,
COLOR_REDWOOD,
COLOR_RED_BROWN,
COLOR_RED_CRAYOLA,
COLOR_RED_DEVIL,
COLOR_RED_MUNSELL,
COLOR_RED_NCS,
COLOR_RED_ORANGE,
COLOR_RED_PANTONE,
COLOR_RED_PIGMENT,
COLOR_RED_PURPLE,
COLOR_RED_RYB,
COLOR_RED_SALSA,
COLOR_RED_VIOLET,
COLOR_REGALIA,
COLOR_REGISTRATION_BLACK,
COLOR_RESOLUTION_BLUE,
COLOR_RHYTHM,
COLOR_RICH_BLACK,
COLOR_RICH_BLACK_FOGRA29,
COLOR_RICH_BLACK_FOGRA39,
COLOR_RICH_BRILLIANT_LAVENDER,
COLOR_RICH_CARMINE,
COLOR_RICH_ELECTRIC_BLUE,
COLOR_RICH_LAVENDER,
COLOR_RICH_LILAC,
COLOR_RICH_MAROON,
COLOR_RIFLE_GREEN,
COLOR_ROAST_COFFEE,
COLOR_ROBIN_EGG_BLUE,
COLOR_ROCKET_METALLIC,
COLOR_ROMAN_SILVER,
COLOR_ROSE,
COLOR_ROSEWOOD,
COLOR_ROSE_BONBON,
COLOR_ROSE_DUST,
COLOR_ROSE_EBONY,
COLOR_ROSE_GOLD,
COLOR_ROSE_MADDER,
COLOR_ROSE_PINK,
COLOR_ROSE_QUARTZ,
COLOR_ROSE_RED,
COLOR_ROSE_TAUPE,
COLOR_ROSE_VALE,
COLOR_ROSSO_CORSA,
COLOR_ROSY_BROWN,
COLOR_ROYAL_AZURE,
COLOR_ROYAL_BLUE,
COLOR_ROYAL_FUCHSIA,
COLOR_ROYAL_PURPLE,
COLOR_ROYAL_YELLOW,
COLOR_RUBER,
COLOR_RUBINE_RED,
COLOR_RUBY,
COLOR_RUBY_RED,
COLOR_RUDDY,
COLOR_RUDDY_BROWN,
COLOR_RUDDY_PINK,
COLOR_RUFOUS,
COLOR_RUSSET,
COLOR_RUSSIAN_GREEN,
COLOR_RUSSIAN_VIOLET,
COLOR_RUST,
COLOR_RUSTY_RED,
COLOR_SACRAMENTO_STATE_GREEN,
COLOR_SADDLE_BROWN,
COLOR_SAFETY_ORANGE,
COLOR_SAFETY_ORANGE_BLAZE_ORANGE,
COLOR_SAFETY_YELLOW,
COLOR_SAFFRON,
COLOR_SAGE,
COLOR_SALMON,
COLOR_SALMON_PINK,
COLOR_SAND,
COLOR_SANDSTORM,
COLOR_SANDY_BROWN,
COLOR_SANDY_TAN,
COLOR_SANDY_TAUPE,
COLOR_SAND_DUNE,
COLOR_SANGRIA,
COLOR_SAPPHIRE,
COLOR_SAPPHIRE_BLUE,
COLOR_SAP_GREEN,
COLOR_SASQUATCH_SOCKS,
COLOR_SATIN_SHEEN_GOLD,
COLOR_SCARLET,
COLOR_SCHAUSS_PINK,
COLOR_SCHOOL_BUS_YELLOW,
COLOR_SCREAMIN_GREEN,
COLOR_SEAL_BROWN,
COLOR_SEASHELL,
COLOR_SEA_BLUE,
COLOR_SEA_FOAM_GREEN,
COLOR_SEA_GREEN,
COLOR_SEA_SERPENT,
COLOR_SELECTIVE_YELLOW,
COLOR_SEPIA,
COLOR_SHADOW,
COLOR_SHADOW_BLUE,
COLOR_SHAMPOO,
COLOR_SHAMROCK_GREEN,
COLOR_SHEEN_GREEN,
COLOR_SHIMMERING_BLUSH,
COLOR_SHINY_SHAMROCK,
COLOR_SHOCKING_PINK,
COLOR_SHOCKING_PINK_CRAYOLA,
COLOR_SIENNA,
COLOR_SILVER,
COLOR_SILVER_CHALICE,
COLOR_SILVER_LAKE_BLUE,
COLOR_SILVER_PINK,
COLOR_SILVER_SAND,
COLOR_SINOPIA,
COLOR_SIZZLING_RED,
COLOR_SIZZLING_SUNRISE,
COLOR_SKOBELOFF,
COLOR_SKY_BLUE,
COLOR_SKY_MAGENTA,
COLOR_SLATE_BLUE,
COLOR_SLATE_GRAY,
COLOR_SLIMY_GREEN,
COLOR_SMALT_DARK_POWDER_BLUE,
COLOR_SMASHED_PUMPKIN,
COLOR_SMITTEN,
COLOR_SMOKE,
COLOR_SMOKEY_TOPAZ,
COLOR_SMOKY_BLACK,
COLOR_SMOKY_TOPAZ,
COLOR_SNOW,
COLOR_SOAP,
COLOR_SOLID_PINK,
COLOR_SONIC_SILVER,
COLOR_SPACE_CADET,
COLOR_SPANISH_BISTRE,
COLOR_SPANISH_BLUE,
COLOR_SPANISH_CARMINE,
COLOR_SPANISH_CRIMSON,
COLOR_SPANISH_GRAY,
COLOR_SPANISH_GREEN,
COLOR_SPANISH_ORANGE,
COLOR_SPANISH_PINK,
COLOR_SPANISH_RED,
COLOR_SPANISH_SKY_BLUE,
COLOR_SPANISH_VIOLET,
COLOR_SPANISH_VIRIDIAN,
COLOR_SPARTAN_CRIMSON,
COLOR_SPICY_MIX,
COLOR_SPIRO_DISCO_BALL,
COLOR_SPRING_BUD,
COLOR_SPRING_FROST,
COLOR_SPRING_GREEN,
COLOR_STAR_COMMAND_BLUE,
COLOR_STEEL_BLUE,
COLOR_STEEL_PINK,
COLOR_STEEL_TEAL,
COLOR_STIL_DE_GRAIN_YELLOW,
COLOR_STIZZA,
COLOR_STORMCLOUD,
COLOR_STRAW,
COLOR_STRAWBERRY,
COLOR_ST_PATRICK_S_BLUE,
COLOR_SUGAR_PLUM,
COLOR_SUNBURNT_CYCLOPS,
COLOR_SUNGLOW,
COLOR_SUNNY,
COLOR_SUNRAY,
COLOR_SUNSET,
COLOR_SUNSET_ORANGE,
COLOR_SUPER_PINK,
COLOR_SWEET_BROWN,
COLOR_TAN,
COLOR_TANGELO,
COLOR_TANGERINE,
COLOR_TANGERINE_YELLOW,
COLOR_TANGO_PINK,
COLOR_TART_ORANGE,
COLOR_TAUPE,
COLOR_TAUPE_GRAY,
COLOR_TEAL,
COLOR_TEAL_BLUE,
COLOR_TEAL_DEER,
COLOR_TEAL_GREEN,
COLOR_TEA_GREEN,
COLOR_TEA_ROSE,
COLOR_TELEMAGENTA,
COLOR_TENN_TAWNY,
COLOR_TERRA_COTTA,
COLOR_THISTLE,
COLOR_THULIAN_PINK,
COLOR_TICKLE_ME_PINK,
COLOR_TIFFANY_BLUE,
COLOR_TIGER_S_EYE,
COLOR_TIMBERWOLF,
COLOR_TITANIUM_YELLOW,
COLOR_TOMATO,
COLOR_TOOLBOX,
COLOR_TOPAZ,
COLOR_TRACTOR_RED,
COLOR_TROLLEY_GREY,
COLOR_TROPICAL_RAIN_FOREST,
COLOR_TROPICAL_VIOLET,
COLOR_TRUE_BLUE,
COLOR_TUFTS_BLUE,
COLOR_TULIP,
COLOR_TUMBLEWEED,
COLOR_TURKISH_ROSE,
COLOR_TURQUOISE,
COLOR_TURQUOISE_BLUE,
COLOR_TURQUOISE_GREEN,
COLOR_TURQUOISE_SURF,
COLOR_TURTLE_GREEN,
COLOR_TUSCAN,
COLOR_TUSCANY,
COLOR_TUSCAN_BROWN,
COLOR_TUSCAN_RED,
COLOR_TUSCAN_TAN,
COLOR_TWILIGHT_LAVENDER,
COLOR_TYRIAN_PURPLE,
COLOR_UA_BLUE,
COLOR_UA_RED,
COLOR_UBE,
COLOR_UCLA_BLUE,
COLOR_UCLA_GOLD,
COLOR_UFO_GREEN,
COLOR_ULTRAMARINE,
COLOR_ULTRAMARINE_BLUE,
COLOR_ULTRA_PINK,
COLOR_ULTRA_RED,
COLOR_UMBER,
COLOR_UNBLEACHED_SILK,
COLOR_UNITED_NATIONS_BLUE,
COLOR_UNIVERSITY_OF_CALIFORNIA_GOLD,
COLOR_UNIVERSITY_OF_TENNESSEE_ORANGE,
COLOR_UNMELLOW_YELLOW,
COLOR_UPSDELL_RED,
COLOR_UP_FOREST_GREEN,
COLOR_UP_MAROON,
COLOR_UROBILIN,
COLOR_USAFA_BLUE,
COLOR_USC_CARDINAL,
COLOR_USC_GOLD,
COLOR_UTAH_CRIMSON,
COLOR_VANILLA,
COLOR_VANILLA_ICE,
COLOR_VAN_DYKE_BROWN,
COLOR_VEGAS_GOLD,
COLOR_VENETIAN_RED,
COLOR_VERDIGRIS,
COLOR_VERMILION,
COLOR_VERONICA,
COLOR_VERY_LIGHT_AZURE,
COLOR_VERY_LIGHT_BLUE,
COLOR_VERY_LIGHT_MALACHITE_GREEN,
COLOR_VERY_LIGHT_TANGELO,
COLOR_VERY_PALE_ORANGE,
COLOR_VERY_PALE_YELLOW,
COLOR_VIOLET,
COLOR_VIOLET_BLUE,
COLOR_VIOLET_COLOR_WHEEL,
COLOR_VIOLET_RED,
COLOR_VIOLET_RYB,
COLOR_VIOLET_WEB,
COLOR_VIRIDIAN,
COLOR_VIRIDIAN_GREEN,
COLOR_VISTA_BLUE,
COLOR_VIVID_AMBER,
COLOR_VIVID_AUBURN,
COLOR_VIVID_BURGUNDY,
COLOR_VIVID_CERISE,
COLOR_VIVID_CERULEAN,
COLOR_VIVID_CRIMSON,
COLOR_VIVID_GAMBOGE,
COLOR_VIVID_LIME_GREEN,
COLOR_VIVID_MALACHITE,
COLOR_VIVID_MULBERRY,
COLOR_VIVID_ORANGE,
COLOR_VIVID_ORANGE_PEEL,
COLOR_VIVID_ORCHID,
COLOR_VIVID_RASPBERRY,
COLOR_VIVID_RED,
COLOR_VIVID_RED_TANGELO,
COLOR_VIVID_SKY_BLUE,
COLOR_VIVID_TANGELO,
COLOR_VIVID_TANGERINE,
COLOR_VIVID_VERMILION,
COLOR_VIVID_VIOLET,
COLOR_VIVID_YELLOW,
COLOR_VOLT,
COLOR_WAGENINGEN_GREEN,
COLOR_WARM_BLACK,
COLOR_WATERSPOUT,
COLOR_WELDON_BLUE,
COLOR_WENGE,
COLOR_WHEAT,
COLOR_WHITE,
COLOR_WHITE_SMOKE,
COLOR_WILD_BLUE_YONDER,
COLOR_WILD_ORCHID,
COLOR_WILD_STRAWBERRY,
COLOR_WILD_WATERMELON,
COLOR_WILLPOWER_ORANGE,
COLOR_WINDSOR_TAN,
COLOR_WINE,
COLOR_WINE_DREGS,
COLOR_WINTERGREEN_DREAM,
COLOR_WINTER_SKY,
COLOR_WINTER_WIZARD,
COLOR_WISTERIA,
COLOR_WOOD_BROWN,
COLOR_XANADU,
COLOR_YALE_BLUE,
COLOR_YANKEES_BLUE,
COLOR_YELLOW,
COLOR_YELLOW_CRAYOLA,
COLOR_YELLOW_GREEN,
COLOR_YELLOW_MUNSELL,
COLOR_YELLOW_NCS,
COLOR_YELLOW_ORANGE,
COLOR_YELLOW_PANTONE,
COLOR_YELLOW_PROCESS,
COLOR_YELLOW_ROSE,
COLOR_YELLOW_RYB,
COLOR_YELLOW_SUNSHINE,
COLOR_ZAFFRE,
COLOR_ZINNWALDITE_BROWN,
COLOR_ZOMP
} Color;
const ColorInfo color_data[COLOR_NAMES_MAX] = {
{ "Absolute zero", "#0048BA", { 0 , 72 , 186 }, { 108, 100, 73 } },
{ "Acid green", "#B0BF1A", { 176, 191, 26 }, { 32, 86 , 75 } },
{ "Aero", "#7CB9E8", { 124, 185, 232 }, { 103, 47 , 91 } },
{ "Aero blue", "#C9FFE5", { 201, 255, 229 }, { 75, 21 , 100 } },
{ "African violet", "#B284BE", { 178, 132, 190 }, { 144, 31 , 75 } },
{ "Air Force blue (RAF)", "#5D8AA8", { 93 , 138, 168 }, { 102, 45 , 66 } },
{ "Air Force blue (USAF)", "#00308F", { 0 , 48 , 143 }, { 110, 100, 56 } },
{ "Air superiority blue", "#72A0C1", { 114, 160, 193 }, { 102, 41 , 76 } },
{ "Alabama crimson", "#AF002A", { 175, 0 , 42 }, { 173, 100, 69 } },
{ "Alabaster", "#F2F0E6", { 242, 240 , 230 }, { 173, 100, 69 } },
{ "alias=", "#E1A95F", { 225, 169, 95 }, { 17, 58 , 88 } },
{ "Alice blue", "#F0F8FF", { 240, 248, 255 }, { 104, 6 , 100 } },
{ "Alien Armpit", "#84DE02", { 132, 222, 2 }, { 42, 99 , 87 } },
{ "Alizarin crimson", "#E32636", { 227, 38 , 54 }, { 177, 83 , 89 } },
{ "Alloy orange", "#C46210", { 196, 98 , 16 }, { 13, 92 , 77 } },
{ "Almond", "#EFDECD", { 239, 222, 205 }, { 15, 14 , 94 } },
{ "Amaranth", "#E52B50", { 229, 43 , 80 }, { 174, 81 , 90 } },
{ "Amaranth deep purple", "#9F2B68", { 159, 43 , 104 }, { 164, 73 , 62 } },
{ "Amaranth pink", "#F19CBB", { 241, 156, 187 }, { 169, 35 , 95 } },
{ "Amaranth purple", "#AB274F", { 171, 39 , 79 }, { 171, 77 , 67 } },
{ "Amaranth red", "#D3212D", { 211, 33 , 45 }, { 178, 84 , 83 } },
{ "Amazon", "#3B7A57", { 59 , 122, 87 }, { 73, 52 , 48 } },
{ "Amazonite", "#00C4B0", { 0, 196 , 176 }, { 178, 84 , 83 } },
{ "Amber", "#FFBF00", { 255, 191, 0 }, { 22, 100, 100 } },
{ "Amber (SAE/ECE)", "#FF7E00", { 255, 126, 0 }, { 15, 100, 100 } },
{ "American rose", "#FF033E", { 255, 3 , 62 }, { 173, 99 , 100 } },
{ "Amethyst", "#9966CC", { 153, 102, 204 }, { 135, 50 , 80 } },
{ "Android green", "#A4C639", { 164, 198, 57 }, { 37, 71 , 78 } },
{ "Antique brass", "#CD9575", { 205, 149, 117 }, { 11, 43 , 80 } },
{ "Antique bronze", "#665D1E", { 102, 93 , 30 }, { 26, 71 , 40 } },
{ "Antique fuchsia", "#915C83", { 145, 92 , 131 }, { 158, 37 , 57 } },
{ "Antique ruby", "#841B2D", { 132, 27 , 45 }, { 175, 80 , 52 } },
{ "Antique white", "#FAEBD7", { 250, 235, 215 }, { 17, 14 , 98 } },
{ "Anti-flash white", "#F2F3F4", { 242, 243, 244 }, { 105, 1 , 96 } },
{ "Ao (English)", "#008000", { 0 , 128, 0 }, { 60, 100, 50 } },
{ "Apple green", "#8DB600", { 141, 182, 0 }, { 37, 100, 71 } },
{ "Apricot", "#FBCEB1", { 251, 206, 177 }, { 12, 29 , 98 } },
{ "Aqua", "#00FFFF", { 0 , 255, 255 }, { 90, 100, 100 } },
{ "Aquamarine", "#7FFFD4", { 127, 255, 212 }, { 80, 50 , 100 } },
{ "Arctic lime", "#D0FF14", { 208, 255, 20 }, { 36, 92 , 100 } },
{ "Army green", "#4B5320", { 75 , 83 , 32 }, { 34, 61 , 33 } },
{ "Arsenic", "#3B444B", { 59 , 68 , 75 }, { 103, 21 , 29 } },
{ "Artichoke", "#8F9779", { 143, 151, 121 }, { 38, 20 , 59 } },
{ "Arylide yellow", "#E9D66B", { 233, 214, 107 }, { 25, 54 , 91 } },
{ "Ash grey", "#B2BEB5", { 178, 190, 181 }, { 67, 6 , 75 } },
{ "Asparagus", "#87A96B", { 135, 169, 107 }, { 46, 37 , 66 } },
{ "Atomic tangerine", "#FF9966", { 255, 153, 102 }, { 10, 60 , 100 } },
{ "Auburn", "#A52A2A", { 165, 42 , 42 }, { 0, 75 , 65 } },
{ "Aureolin", "#FDEE00", { 253, 238, 0 }, { 28, 100, 99 } },
{ "AuroMetalSaurus", "#6E7F80", { 110, 127, 128 }, { 91, 14 , 50 } },
{ "Avocado", "#568203", { 86 , 130, 3 }, { 40, 98 , 51 } },
{ "Awesome", "#FF2052", { 255 , 32, 82 }, { 40, 98 , 51 } },
{ "Aztec Gold", "#C39953", { 195, 153, 83 }, { 19, 57 , 77 } },
{ "Azure", "#007FFF", { 0 , 127, 255 }, { 105, 100, 100 } },
{ "Azureish white", "#DBE9F4", { 219, 233, 244 }, { 103, 10, 96 } },
{ "Azure mist", "#F0FFFF", { 240, 255, 255 }, { 90, 6 , 100 } },
{ "Azure (web color)", "#F0FFFF", { 240, 255, 255 }, { 90, 6 , 100 } },
{ "Baby blue", "#89CFF0", { 137, 207, 240 }, { 99, 43 , 94 } },
{ "Baby blue eyes", "#A1CAF1", { 161, 202, 241 }, { 104, 33 , 95 } },
{ "Baby pink", "#F4C2C2", { 244, 194, 194 }, { 0, 20 , 96 } },
{ "Baby powder", "#FEFEFA", { 254, 254, 250 }, { 30, 2 , 100 } },
{ "Baker-Miller pink", "#FF91AF", { 255, 145, 175 }, { 172, 43 , 100 } },
{ "Ball blue", "#21ABCD", { 33 , 171, 205 }, { 96, 84 , 80 } },
{ "Banana Mania", "#FAE7B5", { 250, 231, 181 }, { 21, 28 , 98 } },
{ "Banana yellow", "#FFE135", { 255, 225, 53 }, { 25, 79 , 100 } },
{ "Bangladesh green", "#006A4E", { 0 , 106, 78 }, { 82, 100, 42 } },
{ "Barbie pink", "#E0218A", { 224, 33 , 138 }, { 163, 85 , 88 } },
{ "Barn red", "#7C0A02", { 124, 10 , 2 }, { 2, 98 , 49 } },
{ "Battery Charged Blue", "#1DACD6", { 29 , 172, 214 }, { 97, 86 , 84 } },
{ "Battleship grey", "#848482", { 132, 132, 130 }, { 30, 2 , 52 } },
{ "Bazaar", "#98777B", { 152, 119, 123 }, { 176, 22 , 60 } },
{ "Beau blue", "#BCD4E6", { 188, 212, 230 }, { 103, 18 , 90 } },
{ "Beaver", "#9F8170", { 159, 129, 112 }, { 11, 30 , 62 } },
{ "Begonia", "#FA6E79", { 250, 110, 121 }, { 177, 10 , 96 } },
{ "Beige", "#F5F5DC", { 245, 245, 220 }, { 30, 10 , 96 } },
{ "Big dip o’ruby", "#9C2542", { 156, 37 , 66 }, { 172, 76 , 61 } },
{ "Big Foot Feet", "#E88E5A", { 232, 142, 90 }, { 11, 61 , 91 } },
{ "Bisque", "#FFE4C4", { 255, 228, 196 }, { 16, 23 , 100 } },
{ "Bistre", "#3D2B1F", { 61 , 43 , 31 }, { 12, 49 , 24 } },
{ "Bistre brown", "#967117", { 150, 113, 23 }, { 21, 85 , 59 } },
{ "Bittersweet", "#FE6F5E", { 254, 111, 94 }, { 3, 63 , 100 } },
{ "Bittersweet shimmer", "#BF4F51", { 191, 79 , 81 }, { 179, 59 , 75 } },
{ "Bitter lemon", "#CAE00D", { 202, 224, 13 }, { 33, 94 , 88 } },
{ "Bitter lime", "#BFFF00", { 191, 255, 0 }, { 37, 100, 100 } },
{ "Black", "#000000", { 0 , 0 , 0 }, { 0, 0 , 0 } },
{ "Black bean", "#3D0C02", { 61 , 12 , 2 }, { 5, 97 , 24 } },
{ "Black Coral", "#54626F", { 84 , 98 , 111 }, { 104, 24 , 44 } },
{ "Black leather jacket", "#253529", { 37 , 53 , 41 }, { 67, 30 , 21 } },
{ "Black olive", "#3B3C36", { 59 , 60 , 54 }, { 35, 10 , 24 } },
{ "Black Shadows", "#BFAFB2", { 191, 175, 178 }, { 174, 8 , 75 } },
{ "Blanched almond", "#FFEBCD", { 255, 235, 205 }, { 18, 20 , 100 } },
{ "Blast-off bronze", "#A57164", { 165, 113, 100 }, { 6, 39 , 65 } },
{ "Bleu de France", "#318CE7", { 49 , 140, 231 }, { 105, 79 , 91 } },
{ "Blizzard Blue", "#ACE5EE", { 172, 229, 238 }, { 94, 28 , 93 } },
{ "Blond", "#FAF0BE", { 250, 240, 190 }, { 25, 24 , 98 } },
{ "Blue", "#0000FF", { 0 , 0 , 255 }, { 120, 100, 100 } },
{ "Blueberry", "#4F86F7", { 79 , 134, 247 }, { 110, 68 , 97 } },
{ "Bluebonnet", "#1C1CF0", { 28 , 28 , 240 }, { 120, 88 , 94 } },
{ "Blue Bell", "#A2A2D0", { 162, 162, 208 }, { 120, 22 , 82 } },
{ "Blue Bolt", "#00B9FB", { 0 , 185, 251 }, { 98, 100, 98 } },
{ "Blue (Crayola)", "#1F75FE", { 31 , 117, 254 }, { 108, 88 , 100 } },
{ "Blue-gray", "#6699CC", { 102, 153, 204 }, { 105, 50 , 80 } },
{ "Blue-green", "#0D98BA", { 13 , 152, 186 }, { 96, 93 , 73 } },
{ "Blue Jeans", "#5DADEC", { 93 , 173, 236 }, { 103, 61 , 93 } },
{ "Blue Lagoon", "#ACE5EE", { 172, 229, 238 }, { 94, 28 , 93 } },
{ "Blue-magenta violet", "#553592", { 85 , 53 , 146 }, { 130, 64 , 57 } },
{ "Blue (Munsell)", "#0093AF", { 0 , 147, 175 }, { 95, 100, 69 } },
{ "Blue (NCS)", "#0087BD", { 0 , 135, 189 }, { 98, 100, 74 } },
{ "Blue (Pantone)", "#0018A8", { 0 , 24 , 168 }, { 115, 100, 66 } },
{ "Blue (pigment)", "#333399", { 51 , 51 , 153 }, { 120, 67 , 60 } },
{ "Blue (RYB)", "#0247FE", { 2 , 71 , 254 }, { 112, 99 , 100 } },
{ "Blue sapphire", "#126180", { 18 , 97 , 128 }, { 98, 86 , 50 } },
{ "Blue-violet", "#8A2BE2", { 138, 43 , 226 }, { 135, 81 , 89 } },
{ "Blue yonder", "#5072A7", { 80 , 114, 167 }, { 108, 52 , 65 } },
{ "Blush", "#DE5D83", { 222, 93 , 131 }, { 171, 58 , 87 } },
{ "Bole", "#79443B", { 121, 68 , 59 }, { 4, 51 , 47 } },
{ "Bondi blue", "#0095B6", { 0 , 149, 182 }, { 95, 100, 71 } },
{ "Bone", "#E3DAC9", { 227, 218, 201 }, { 19, 11 , 89 } },
{ "Booger Buster", "#DDE26A", { 221, 226, 106 }, { 31, 53 , 89 } },
{ "Boston University Red", "#CC0000", { 204, 0 , 0 }, { 0, 100, 80 } },
{ "Bottle green", "#006A4E", { 0 , 106, 78 }, { 82, 100, 42 } },
{ "Boysenberry", "#873260", { 135, 50 , 96 }, { 164, 63 , 53 } },
{ "Brandeis blue", "#0070FF", { 0 , 112, 255 }, { 107, 100, 100 } },
{ "Brass", "#B5A642", { 181, 166, 66 }, { 26, 64 , 71 } },
{ "Brick red", "#CB4154", { 203, 65 , 84 }, { 176, 68 , 80 } },
{ "Bright cerulean", "#1DACD6", { 29 , 172, 214 }, { 97, 86 , 84 } },
{ "Bright green", "#66FF00", { 102, 255, 0 }, { 48, 100, 100 } },
{ "Bright lavender", "#BF94E4", { 191, 148, 228 }, { 136, 35 , 89 } },
{ "Bright lilac", "#D891EF", { 216, 145, 239 }, { 142, 39 , 94 } },
{ "Bright maroon", "#C32148", { 195, 33 , 72 }, { 173, 83 , 76 } },
{ "Bright navy blue", "#1974D2", { 25 , 116, 210 }, { 105, 88 , 82 } },
{ "Bright pink", "#FF007F", { 255, 0 , 127 }, { 165, 100, 100 } },
{ "Bright turquoise", "#08E8DE", { 8 , 232, 222 }, { 88, 97 , 91 } },
{ "Bright ube", "#D19FE8", { 209, 159, 232 }, { 140, 31 , 91 } },
{ "Bright Yellow (Crayola)", "#FFAA1D", { 255, 170, 29 }, { 18, 89 , 100 } },
{ "Brilliant azure", "#3399FF", { 51 , 153, 255 }, { 105, 80 , 100 } },
{ "Brilliant lavender", "#F4BBFF", { 244, 187, 255 }, { 145, 27 , 100 } },
{ "Brilliant rose", "#FF55A3", { 255, 85 , 163 }, { 166, 67 , 100 } },
{ "Brink pink", "#FB607F", { 251, 96 , 127 }, { 174, 62 , 98 } },
{ "British racing green", "#004225", { 0 , 66 , 37 }, { 77, 100, 26 } },
{ "Bronze", "#CD7F32", { 205, 127, 50 }, { 15, 76 , 80 } },
{ "Bronze Yellow", "#737000", { 115, 112, 0 }, { 29, 100, 45 } },
{ "Brown-nose", "#6B4423", { 107, 68 , 35 }, { 14, 67 , 42 } },
{ "Brown Sugar", "#AF6E4D", { 175, 110, 77 }, { 10, 56 , 69 } },
{ "Brown (traditional)", "#964B00", { 150, 75 , 0 }, { 15, 100, 59 } },
{ "Brown (web)", "#A52A2A", { 165, 42 , 42 }, { 0, 75 , 65 } },
{ "Brown Yellow", "#CC9966", { 204, 153, 102 }, { 15, 50 , 80 } },
{ "Brunswick green", "#1B4D3E", { 27 , 77 , 62 }, { 81, 65 , 30 } },
{ "Bubbles", "#E7FEFF", { 231, 254, 255 }, { 91, 9 , 100 } },
{ "Bubble gum", "#FFC1CC", { 255, 193, 204 }, { 174, 24 , 100 } },
{ "Bud green", "#7BB661", { 123, 182, 97 }, { 51, 47 , 71 } },
{ "Buff", "#F0DC82", { 240, 220, 130 }, { 24, 46 , 94 } },
{ "Bulgarian rose", "#480607", { 72 , 6 , 7 }, { 179, 92 , 28 } },
{ "Burgundy", "#800020", { 128, 0 , 32 }, { 172, 100, 50 } },
{ "Burlywood", "#DEB887", { 222, 184, 135 }, { 17, 39 , 87 } },
{ "Burnished Brown", "#A17A74", { 161, 122, 116 }, { 4, 28 , 63 } },
{ "Burnt orange", "#CC5500", { 204, 85 , 0 }, { 12, 100, 80 } },
{ "Burnt sienna", "#E97451", { 233, 116, 81 }, { 7, 65 , 91 } },
{ "Burnt umber", "#8A3324", { 138, 51 , 36 }, { 4, 74 , 54 } },
{ "Button Blue", "#24A0ED", { 36 , 160, 237 }, { 101, 83 , 93 } },
{ "Byzantine", "#BD33A4", { 189, 51 , 164 }, { 155, 73 , 74 } },
{ "Byzantium", "#702963", { 112, 41 , 99 }, { 155, 63 , 44 } },
{ "B'dazzled blue", "#2E5894", { 46 , 88 , 148 }, { 107, 69 , 58 } },
{ "Cadet", "#536872", { 83 , 104, 114 }, { 99, 27 , 45 } },
{ "Cadet blue", "#5F9EA0", { 95 , 158, 160 }, { 91, 41 , 63 } },
{ "Cadet grey", "#91A3B0", { 145, 163, 176 }, { 102, 18 , 69 } },
{ "Cadmium green", "#006B3C", { 0 , 107, 60 }, { 77, 100, 42 } },
{ "Cadmium orange", "#ED872D", { 237, 135, 45 }, { 14, 81 , 93 } },
{ "Cadmium red", "#E30022", { 227, 0 , 34 }, { 175, 100, 89 } },
{ "Cadmium yellow", "#FFF600", { 255, 246, 0 }, { 29, 100, 100 } },
{ "Café au lait", "#A67B5B", { 166, 123, 91 }, { 13, 45 , 65 } },
{ "Café noir", "#4B3621", { 75 , 54 , 33 }, { 15, 56 , 29 } },
{ "Cal Poly Pomona green", "#1E4D2B", { 30 , 77 , 43 }, { 68, 61 , 30 } },
{ "Cambridge Blue", "#A3C1AD", { 163, 193, 173 }, { 70, 16 , 76 } },
{ "Camel", "#C19A6B", { 193, 154, 107 }, { 16, 45 , 76 } },
{ "Cameo pink", "#EFBBCC", { 239, 187, 204 }, { 170, 22 , 94 } },
{ "Camouflage green", "#78866B", { 120, 134, 107 }, { 45, 20 , 53 } },
{ "Canary", "#FFFF99", { 255, 255, 153 }, { 30, 40 , 100 } },
{ "Canary yellow", "#FFEF00", { 255, 239, 0 }, { 28, 100, 100 } },
{ "Candy apple red", "#FF0800", { 255, 8 , 0 }, { 1, 100, 100 } },
{ "Candy pink", "#E4717A", { 228, 113, 122 }, { 177, 50 , 89 } },
{ "Capri", "#00BFFF", { 0 , 191, 255 }, { 97, 100, 100 } },
{ "Caput mortuum", "#592720", { 89 , 39 , 32 }, { 3, 64 , 35 } },
{ "Cardinal", "#C41E3A", { 196, 30 , 58 }, { 175, 85 , 77 } },
{ "Caribbean green", "#00CC99", { 0 , 204, 153 }, { 82, 100, 80 } },
{ "Carmine", "#960018", { 150, 0 , 24 }, { 175, 100, 59 } },
{ "Carmine (M&P)", "#D70040", { 215, 0 , 64 }, { 171, 100, 84 } },
{ "Carmine pink", "#EB4C42", { 235, 76 , 66 }, { 2, 72 , 92 } },
{ "Carmine red", "#FF0038", { 255, 0 , 56 }, { 173, 100, 100 } },
{ "Carnation pink", "#FFA6C9", { 255, 166, 201 }, { 168, 35 , 100 } },
{ "Carnelian", "#B31B1B", { 179, 27 , 27 }, { 0, 85 , 70 } },
{ "Carolina blue", "#56A0D3", { 86 , 160, 211 }, { 102, 59 , 83 } },
{ "Carrot orange", "#ED9121", { 237, 145, 33 }, { 16, 86 , 93 } },
{ "Castleton green", "#00563F", { 0 , 86 , 63 }, { 82, 100, 34 } },
{ "Catalina blue", "#062A78", { 6 , 42 , 120 }, { 110, 95 , 47 } },
{ "Catawba", "#703642", { 112, 54 , 66 }, { 174, 52 , 44 } },
{ "Cedar Chest", "#C95A49", { 201, 90 , 73 }, { 4, 64 , 79 } },
{ "Ceil", "#92A1CF", { 146, 161, 207 }, { 112, 29 , 81 } },
{ "Celadon", "#ACE1AF", { 172, 225, 175 }, { 61, 24 , 88 } },
{ "Celadon blue", "#007BA7", { 0 , 123, 167 }, { 98, 100, 65 } },
{ "Celadon green", "#2F847C", { 47 , 132, 124 }, { 87, 64 , 52 } },
{ "Celeste", "#B2FFFF", { 178, 255, 255 }, { 90, 30 , 100 } },
{ "Celestial blue", "#4997D0", { 73 , 151, 208 }, { 102, 65 , 82 } },
{ "Cerise", "#DE3163", { 222, 49 , 99 }, { 171, 78 , 87 } },
{ "Cerise pink", "#EC3B83", { 236, 59 , 131 }, { 168, 75 , 93 } },
{ "Cerulean", "#007BA7", { 0 , 123, 167 }, { 98, 100, 65 } },
{ "Cerulean blue", "#2A52BE", { 42 , 82 , 190 }, { 112, 78 , 75 } },
{ "Cerulean frost", "#6D9BC3", { 109, 155, 195 }, { 104, 44 , 76 } },
{ "CG Blue", "#007AA5", { 0 , 122, 165 }, { 98, 100, 65 } },
{ "CG Red", "#E03C31", { 224, 60 , 49 }, { 2, 78 , 88 } },
{ "Chamoisee", "#A0785A", { 160, 120, 90 }, { 13, 44 , 63 } },
{ "Champagne", "#F7E7CE", { 247, 231, 206 }, { 18, 17 , 97 } },
{ "Champagne pink", "#F1DDCF", { 241, 221, 207 }, { 12, 14 , 95 } },
{ "Charcoal", "#36454F", { 54 , 69 , 79 }, { 102, 32 , 31 } },
{ "Charleston green", "#232B2B", { 35 , 43 , 43 }, { 90, 19 , 17 } },
{ "Charm pink", "#E68FAC", { 230, 143, 172 }, { 170, 38 , 90 } },
{ "Chartreuse (traditional)", "#DFFF00", { 223, 255, 0 }, { 34, 100, 100 } },
{ "Chartreuse (web)", "#7FFF00", { 127, 255, 0 }, { 45, 100, 100 } },
{ "Cherry", "#DE3163", { 222, 49 , 99 }, { 171, 78 , 87 } },
{ "Cherry blossom pink", "#FFB7C5", { 255, 183, 197 }, { 174, 28 , 100 } },
{ "Chestnut", "#954535", { 149, 69 , 53 }, { 5, 64 , 58 } },
{ "China pink", "#DE6FA1", { 222, 111, 161 }, { 166, 50 , 87 } },
{ "China rose", "#A8516E", { 168, 81 , 110 }, { 170, 52 , 66 } },
{ "Chinese red", "#AA381E", { 170, 56 , 30 }, { 5, 82 , 67 } },
{ "Chinese violet", "#856088", { 133, 96 , 136 }, { 148, 29 , 53 } },
{ "Chlorophyll green", "#4AFF00", { 74 , 255 , 0 }, { 51, 100, 100 } },
{ "Chocolate (traditional)", "#7B3F00", { 123, 63 , 0 }, { 15, 100, 48 } },
{ "Chocolate (web)", "#D2691E", { 210, 105, 30 }, { 12, 86 , 82 } },
{ "Chrome yellow", "#FFA700", { 255, 167, 0 }, { 19, 100, 100 } },
{ "Cinereous", "#98817B", { 152, 129, 123 }, { 6, 19 , 60 } },
{ "Cinnabar", "#E34234", { 227, 66 , 52 }, { 2, 77 , 89 } },
{ "Cinnamon", "#D2691E", { 210, 105, 30 }, { 12, 86 , 82 } },
{ "Cinnamon Satin", "#CD607E", { 205, 96 , 126 }, { 171, 53 , 80 } },
{ "Citrine", "#E4D00A", { 228, 208, 10 }, { 27, 96 , 89 } },
{ "Citron", "#9FA91F", { 158, 169, 31 }, { 32, 82 , 66 } },
{ "Claret", "#7F1734", { 127, 23 , 52 }, { 171, 82 , 50 } },
{ "Classic rose", "#FBCCE7", { 251, 204, 231 }, { 163, 19 , 98 } },
{ "Cobalt Blue", "#0047AB", { 0 , 71 , 171 }, { 107, 100, 67 } },
{ "Cocoa brown", "#D2691E", { 210, 105, 30 }, { 12, 86 , 82 } },
{ "Coconut", "#965A3E", { 150, 90 , 62 }, { 9, 59 , 59 } },
{ "Coffee", "#6F4E37", { 111, 78 , 55 }, { 12, 50 , 44 } },
{ "Columbia Blue", "#C4D8E2", { 196, 216, 226 }, { 100, 13 , 89 } },
{ "Congo pink", "#F88379", { 248, 131, 121 }, { 2, 51 , 97 } },
{ "Cool Black", "#002E63", { 0 , 46 , 99 }, { 106, 100 , 38 } },
{ "Cool grey", "#8C92AC", { 140, 146, 172 }, { 114, 19 , 67 } },
{ "Copper", "#B87333", { 184, 115, 51 }, { 14, 72 , 72 } },
{ "Copper (Crayola)", "#DA8A67", { 218, 138, 103 }, { 9, 53 , 85 } },
{ "Copper penny", "#AD6F69", { 173, 111, 105 }, { 2, 39 , 68 } },
{ "Copper red", "#CB6D51", { 203, 109, 81 }, { 7, 60 , 80 } },
{ "Copper rose", "#996666", { 153, 102, 102 }, { 0, 33 , 60 } },
{ "Coquelicot", "#FF3800", { 255, 56 , 0 }, { 6, 100, 100 } },
{ "Coral", "#FF7F50", { 255, 127, 80 }, { 8, 69 , 100 } },
{ "Coral pink", "#F88379", { 248, 131, 121 }, { 2, 51 , 97 } },
{ "Coral red", "#FF4040", { 255, 64 , 64 }, { 0, 75 , 100 } },
{ "Coral Reef", "#FD7C6E", { 253, 124, 110 }, { 3, 57 , 99 } },
{ "Cordovan", "#893F45", { 137, 63 , 69 }, { 177, 54 , 54 } },
{ "Corn", "#FBEC5D", { 251, 236, 93 }, { 27, 63 , 98 } },
{ "Cornell Red", "#B31B1B", { 179, 27 , 27 }, { 0, 85 , 70 } },
{ "Cornflower blue", "#6495ED", { 100, 149, 237 }, { 109, 58 , 93 } },
{ "Cornsilk", "#FFF8DC", { 255, 248, 220 }, { 24, 14 , 100 } },
{ "Cosmic Cobalt", "#2E2D88", { 46 , 45 , 136 }, { 120, 67 , 53 } },
{ "Cosmic latte", "#FFF8E7", { 255, 248, 231 }, { 21, 9 , 100 } },
{ "Cotton candy", "#FFBCD9", { 255, 188, 217 }, { 167, 26 , 100 } },
{ "Coyote brown", "#81613C", { 129, 97 , 60 }, { 31, 52 , 51 } },
{ "Cream", "#FFFDD0", { 255, 253, 208 }, { 28, 18 , 100 } },
{ "Crimson", "#DC143C", { 220, 20 , 60 }, { 174, 91 , 86 } },
{ "Crimson glory", "#BE0032", { 190, 0 , 50 }, { 172, 100, 75 } },
{ "Crimson red", "#990000", { 153, 0 , 0 }, { 0, 100, 60 } },
{ "Cultured", "#F5F5F5", { 245, 245, 245 }, { 0, 0 , 96 } },
{ "Cyan", "#00FFFF", { 0 , 255, 255 }, { 90, 100, 100 } },
{ "Cyan azure", "#4E82B4", { 78 , 130, 180 }, { 104, 57 , 71 } },
{ "Cyan-blue azure", "#4682BF", { 70 , 130, 191 }, { 105, 63 , 75 } },
{ "Cyan cobalt blue", "#28589C", { 40 , 88, 156 }, { 107, 74 , 61 } },
{ "Cyan cornflower blue", "#188BC2", { 24 , 139, 194 }, { 99, 88, 76 } },
{ "Cyan (process)", "#00B7EB", { 0 , 183, 235 }, { 96, 100, 92 } },
{ "Cyber grape", "#58427C", { 88 , 66 , 124 }, { 131, 47 , 49 } },
{ "Cyber yellow", "#FFD300", { 255, 211, 0 }, { 25, 100, 100 } },
{ "Cyclamen", "#F56FA1", { 245, 111, 161 }, { 0, 54 , 96 } },
{ "Daffodil", "#FFFF31", { 255, 255, 49 }, { 30, 81 , 100 } },
{ "Dandelion", "#F0E130", { 240, 225, 48 }, { 27, 80 , 94 } },
{ "Dark blue", "#00008B", { 0 , 0 , 139 }, { 120, 100, 55 } },
{ "Dark blue-gray", "#666699", { 102, 102, 153 }, { 120, 33 , 60 } },
{ "Dark brown", "#654321", { 101, 67 , 33 }, { 15, 67 , 40 } },
{ "Dark brown-tangelo", "#88654E", { 136, 101, 78 }, { 12, 43 , 53 } },
{ "Dark byzantium", "#5D3954", { 93 , 57 , 84 }, { 157, 39 , 36 } },
{ "Dark candy apple red", "#A40000", { 164, 0 , 0 }, { 0, 100, 64 } },
{ "Dark cerulean", "#08457E", { 8 , 69 , 126 }, { 104, 94 , 49 } },
{ "Dark chestnut", "#986960", { 152, 105, 96 }, { 5, 37 , 60 } },
{ "Dark coral", "#CD5B45", { 205, 91 , 69 }, { 5, 66 , 80 } },
{ "Dark cyan", "#008B8B", { 0 , 139, 139 }, { 90, 100, 55 } },
{ "Dark electric blue", "#536878", { 83 , 104, 120 }, { 103, 31 , 47 } },
{ "Dark goldenrod", "#B8860B", { 184, 134, 11 }, { 21, 94 , 72 } },
{ "Dark gray (X11)", "#A9A9A9", { 169, 169, 169 }, { 0, 0 , 66 } },
{ "Dark green", "#013220", { 1 , 50 , 32 }, { 79, 98 , 20 } },
{ "Dark green (X11)", "#006400", { 0 , 100, 0 }, { 60, 100, 39 } },
{ "Dark gunmetal", "#1F262A", { 31 , 38 , 42 }, { 101, 26 , 16 } },
{ "Dark imperial blue", "#00147E", { 0 , 20 , 126 }, { 91, 100, 40 } },
{ "Dark jungle green", "#1A2421", { 26 , 36 , 33 }, { 81, 28 , 14 } },
{ "Dark khaki", "#BDB76B", { 189, 183, 107 }, { 28, 43 , 74 } },
{ "Dark lava", "#483C32", { 72 , 60 , 50 }, { 13, 31 , 28 } },
{ "Dark lavender", "#734F96", { 115, 79 , 150 }, { 135, 47 , 59 } },
{ "Dark liver", "#534B4F", { 83 , 75 , 79 }, { 165, 10 , 33 } },
{ "Dark liver (horses)", "#543D37", { 84 , 61 , 55 }, { 6, 35 , 33 } },
{ "Dark magenta", "#8B008B", { 139, 0 , 139 }, { 150, 100, 55 } },
{ "Dark medium gray", "#A9A9A9", { 169, 169, 169 }, { 0, 0 , 66 } },
{ "Dark midnight blue", "#003366", { 0 , 51 , 102 }, { 105, 100, 40 } },
{ "Dark moss green", "#4A5D23", { 74 , 93 , 35 }, { 40, 62 , 36 } },
{ "Dark olive green", "#556B2F", { 85 , 107, 47 }, { 41, 56 , 42 } },
{ "Dark orange", "#FF8C00", { 255, 140, 0 }, { 16, 100, 100 } },
{ "Dark orchid", "#9932CC", { 153, 50 , 204 }, { 140, 75 , 80 } },
{ "Dark pastel blue", "#779ECB", { 119, 158, 203 }, { 106, 41 , 80 } },
{ "Dark pastel green", "#03C03C", { 3 , 192, 60 }, { 69, 98 , 75 } },
{ "Dark pastel purple", "#966FD6", { 150, 111, 214 }, { 131, 48 , 84 } },
{ "Dark pastel red", "#C23B22", { 194, 59 , 34 }, { 4, 82 , 76 } },
{ "Dark pink", "#E75480", { 231, 84 , 128 }, { 171, 64 , 91 } },
{ "Dark powder blue", "#003399", { 0 , 51 , 153 }, { 110, 100, 60 } },
{ "Dark puce", "#4F3A3C", { 79 , 58 , 60 }, { 177, 27 , 31 } },
{ "Dark purple", "#301934", { 48 , 25 , 52 }, { 145, 51 , 20 } },
{ "Dark raspberry", "#872657", { 135, 38 , 87 }, { 165, 72 , 53 } },
{ "Dark red", "#8B0000", { 139, 0 , 0 }, { 0, 100, 55 } },
{ "Dark salmon", "#E9967A", { 233, 150, 122 }, { 7, 48 , 91 } },
{ "Dark scarlet", "#560319", { 86 , 3 , 25 }, { 172, 97 , 34 } },
{ "Dark sea green", "#8FBC8F", { 143, 188, 143 }, { 60, 24 , 74 } },
{ "Dark sienna", "#3C1414", { 60 , 20 , 20 }, { 0, 67 , 24 } },
{ "Dark sky blue", "#8CBED6", { 140, 190, 214 }, { 99, 35 , 84 } },
{ "Dark slate blue", "#483D8B", { 72 , 61 , 139 }, { 124, 56 , 55 } },
{ "Dark slate gray", "#2F4F4F", { 47 , 79 , 79 }, { 90, 41 , 31 } },
{ "Dark spring green", "#177245", { 23 , 114, 69 }, { 75, 80 , 45 } },
{ "Dark tan", "#918151", { 145, 129, 81 }, { 22, 44 , 57 } },
{ "Dark tangerine", "#FFA812", { 255, 168, 18 }, { 19, 93 , 100 } },
{ "Dark taupe", "#483C32", { 72 , 60 , 50 }, { 13, 31 , 28 } },
{ "Dark terra cotta", "#CC4E5C", { 204, 78 , 92 }, { 176, 62 , 80 } },
{ "Dark turquoise", "#00CED1", { 0 , 206, 209 }, { 90, 100, 82 } },
{ "Dark vanilla", "#D1BEA8", { 209, 190, 168 }, { 16, 20 , 82 } },
{ "Dark violet", "#9400D3", { 148, 0 , 211 }, { 141, 100, 83 } },
{ "Dark yellow", "#9B870C", { 155, 135, 12 }, { 26, 92 , 61 } },
{ "Dartmouth green", "#00703C", { 0 , 112, 60 }, { 76, 100, 44 } },
{ "Davy's grey", "#555555", { 85 , 85 , 85 }, { 0, 0 , 33 } },
{ "Debian red", "#D70A53", { 215, 10 , 83 }, { 169, 95 , 84 } },
{ "Deep aquamarine", "#40826D", { 64 , 130, 109 }, { 80, 51 , 51 } },
{ "Deep carmine", "#A9203E", { 169, 32 , 62 }, { 173, 81 , 66 } },
{ "Deep carmine pink", "#EF3038", { 239, 48 , 56 }, { 178, 80 , 94 } },
{ "Deep carrot orange", "#E9692C", { 233, 105, 44 }, { 9, 81 , 91 } },
{ "Deep cerise", "#DA3287", { 218, 50 , 135 }, { 165, 77 , 85 } },
{ "Deep champagne", "#FAD6A5", { 250, 214, 165 }, { 17, 34 , 98 } },
{ "Deep chestnut", "#B94E48", { 185, 78 , 72 }, { 1, 61 , 73 } },
{ "Deep coffee", "#704241", { 112, 66 , 65 }, { 0, 42 , 44 } },
{ "Deep fuchsia", "#C154C1", { 193, 84 , 193 }, { 150, 56 , 76 } },
{ "Deep Green", "#056608", { 5 , 102 , 8 }, { 61, 95 , 40 } },
{ "Deep green-cyan turquoise", "#0E7C61", { 14 , 124, 97 }, { 82, 89 , 49 } },
{ "Deep jungle green", "#004B49", { 0 , 75 , 73 }, { 89, 100, 29 } },
{ "Deep koamaru", "#333366", { 51 , 51 , 102 }, { 120, 50 , 40 } },
{ "Deep lemon", "#F5C71A", { 245, 199, 26 }, { 23, 89 , 96 } },
{ "Deep lilac", "#9955BB", { 153, 85 , 187 }, { 140, 55 , 73 } },
{ "Deep magenta", "#CC00CC", { 204, 0 , 204 }, { 150, 100, 80 } },
{ "Deep maroon", "#820000", { 130, 0 , 0 }, { 0, 100, 51 } },
{ "Deep mauve", "#D473D4", { 212, 115, 212 }, { 150, 46 , 83 } },
{ "Deep moss green", "#355E3B", { 53 , 94 , 59 }, { 64, 44 , 37 } },
{ "Deep peach", "#FFCBA4", { 255, 203, 164 }, { 13, 36 , 100 } },
{ "Deep pink", "#FF1493", { 255, 20 , 147 }, { 164, 92 , 100 } },
{ "Deep puce", "#A95C68", { 169, 92 , 104 }, { 175, 46 , 66 } },
{ "Deep Red", "#850101", { 133, 1 , 1 }, { 0, 99 , 52 } },
{ "Deep ruby", "#843F5B", { 132, 63 , 91 }, { 168, 52 , 52 } },
{ "Deep saffron", "#FF9933", { 255, 153, 51 }, { 15, 80 , 100 } },
{ "Deep sky blue", "#00BFFF", { 0 , 191, 255 }, { 97, 100, 100 } },
{ "Deep Space Sparkle", "#4A646C", { 74 , 100, 108 }, { 97, 31 , 42 } },
{ "Deep spring bud", "#556B2F", { 85 , 107, 47 }, { 41, 56 , 42 } },
{ "Deep Taupe", "#7E5E60", { 126, 94 , 96 }, { 178, 25 , 49 } },
{ "Deep Tuscan red", "#66424D", { 102, 66 , 77 }, { 171, 35 , 40 } },
{ "Deep violet", "#330066", { 51 , 0 , 102 }, { 135, 100, 40 } },
{ "Deer", "#BA8759", { 186, 135, 89 }, { 14, 52 , 73 } },
{ "Denim", "#1560BD", { 21 , 96 , 189 }, { 106, 89 , 74 } },
{ "Denim Blue", "#2243B6", { 34 , 67 , 182 }, { 113, 81 , 71 } },
{ "Desaturated cyan", "#669999", { 102, 153, 153 }, { 90, 33 , 60 } },
{ "Desert", "#C19A6B", { 193, 154, 107 }, { 16, 45 , 76 } },
{ "Desert sand", "#EDC9AF", { 237, 201, 175 }, { 12, 26 , 93 } },
{ "Desire", "#EA3C53", { 234, 60 , 83 }, { 176, 74 , 92 } },
{ "Diamond", "#B9F2FF", { 185, 242, 255 }, { 95, 27, 100 } },
{ "Dim gray", "#696969", { 105, 105, 105 }, { 0, 0 , 41 } },
{ "Dingy Dungeon", "#C53151", { 197, 49 , 81 }, { 173, 75 , 77 } },
{ "Dirt", "#9B7653", { 155, 118, 83 }, { 14, 46 , 61 } },
{ "Dodger blue", "#1E90FF", { 30 , 144, 255 }, { 105, 88 , 100 } },
{ "Dogwood rose", "#D71868", { 215, 24 , 104 }, { 167, 89 , 84 } },
{ "Dollar bill", "#85BB65", { 133, 187, 101 }, { 49, 46 , 73 } },
{ "Dolphin Gray", "#828E84", { 130, 142, 132 }, { 65, 8 , 56 } },
{ "Donkey brown", "#664C28", { 102, 76 , 40 }, { 17, 61 , 40 } },
{ "Drab", "#967117", { 150, 113, 23 }, { 21, 85 , 59 } },
{ "Duke blue", "#00009C", { 0 , 0 , 156 }, { 120, 100, 61 } },
{ "Dust storm", "#E5CCC9", { 229, 204, 201 }, { 3, 12 , 90 } },
{ "Dutch white", "#EFDFBB", { 239, 223, 187 }, { 21, 22 , 94 } },
{ "Ebony", "#555D50", { 85 , 93 , 80 }, { 48, 14 , 36 } },
{ "Ecru", "#C2B280", { 194, 178, 128 }, { 22, 34 , 76 } },
{ "Eerie black", "#1B1B1B", { 27 , 27 , 27 }, { 0, 0 , 11 } },
{ "Eggplant", "#614051", { 97 , 64 , 81 }, { 164, 34 , 38 } },
{ "Eggshell", "#F0EAD6", { 240, 234, 214 }, { 23, 11 , 94 } },
{ "Egyptian blue", "#1034A6", { 16 , 52 , 166 }, { 113, 90 , 65 } },
{ "Electric blue", "#7DF9FF", { 125, 249, 255 }, { 91, 51 , 100 } },
{ "Electric crimson", "#FF003F", { 255, 0 , 63 }, { 172, 100, 100 } },
{ "Electric cyan", "#00FFFF", { 0 , 255, 255 }, { 90, 100, 100 } },
{ "Electric green", "#00FF00", { 0 , 255, 0 }, { 60, 100, 100 } },
{ "Electric indigo", "#6F00FF", { 111, 0 , 255 }, { 133, 100, 100 } },
{ "Electric lavender", "#F4BBFF", { 244, 187, 255 }, { 145, 27 , 100 } },
{ "Electric lime", "#CCFF00", { 204, 255, 0 }, { 36, 100, 100 } },
{ "Electric purple", "#BF00FF", { 191, 0 , 255 }, { 142, 100, 100 } },
{ "Electric ultramarine", "#3F00FF", { 63 , 0 , 255 }, { 127, 100, 100 } },
{ "Electric violet", "#8F00FF", { 143, 0 , 255 }, { 137, 100, 100 } },
{ "Electric yellow", "#FFFF33", { 255, 255, 51 }, { 30, 80 , 100 } },
{ "Emerald", "#50C878", { 80 , 200, 120 }, { 70, 60 , 78 } },
{ "Eminence", "#6C3082", { 108, 48 , 130 }, { 142, 63 , 51 } },
{ "English green", "#1B4D3E", { 27 , 77 , 62 }, { 81, 65 , 30 } },
{ "English lavender", "#B48395", { 180, 131, 149 }, { 169, 27 , 71 } },
{ "English red", "#AB4B52", { 171, 75 , 82 }, { 178, 56 , 67 } },
{ "English vermillion", "#CC474B", { 204, 71 , 75 }, { 179, 65 , 80 } },
{ "English violet", "#563C5C", { 86 , 60 , 92 }, { 144, 35 , 36 } },
{ "Eton blue", "#96C8A2", { 150, 200, 162 }, { 67, 25 , 78 } },
{ "Eucalyptus", "#44D7A8", { 68 , 215, 168 }, { 80, 68 , 84 } },
{ "Fallow", "#C19A6B", { 193, 154, 107 }, { 16, 45 , 76 } },
{ "Falu red", "#801818", { 128, 24 , 24 }, { 0, 81 , 50 } },
{ "Fandango", "#B53389", { 181, 51 , 137 }, { 160, 72 , 71 } },
{ "Fandango pink", "#DE5285", { 222, 82 , 133 }, { 169, 63 , 87 } },
{ "Fashion fuchsia", "#F400A1", { 244, 0 , 161 }, { 160, 100, 96 } },
{ "Fawn", "#E5AA70", { 229, 170, 112 }, { 15, 51 , 90 } },
{ "Feldgrau", "#4D5D53", { 77 , 93 , 83 }, { 71, 17 , 36 } },
{ "Feldspar", "#FDD5B1", { 253, 213, 177 }, { 14, 30 , 99 } },
{ "Fern green", "#4F7942", { 79 , 121, 66 }, { 53, 45 , 47 } },
{ "Ferrari Red", "#FF2800", { 255, 40 , 0 }, { 4, 100, 100 } },
{ "Field drab", "#6C541E", { 108, 84 , 30 }, { 21, 72 , 42 } },
{ "Fiery Rose", "#FF5470", { 255, 84 , 112 }, { 175, 67 , 100 } },
{ "Firebrick", "#B22222", { 178, 34 , 34 }, { 0, 81 , 70 } },
{ "Fire engine red", "#CE2029", { 206, 32 , 41 }, { 178, 84 , 81 } },
{ "Flame", "#E25822", { 226, 88 , 34 }, { 8, 85 , 89 } },
{ "Flamingo pink", "#FC8EAC", { 252, 142, 172 }, { 172, 44 , 99 } },
{ "Flattery", "#6B4423", { 107, 68 , 35 }, { 14, 67 , 42 } },
{ "Flavescent", "#F7E98E", { 247, 233, 142 }, { 26, 43 , 97 } },
{ "Flax", "#EEDC82", { 238, 220, 130 }, { 25, 45 , 93 } },
{ "Flirt", "#A2006D", { 162, 0 , 109 }, { 160, 100, 64 } },
{ "Floral white", "#FFFAF0", { 255, 250, 240 }, { 20, 6 , 100 } },
{ "Fluorescent orange", "#FFBF00", { 255, 191, 0 }, { 22, 100, 100 } },
{ "Fluorescent pink", "#FF1493", { 255, 20 , 147 }, { 164, 92 , 100 } },
{ "Fluorescent yellow", "#CCFF00", { 204, 255, 0 }, { 36, 100, 100 } },
{ "Folly", "#FF004F", { 255, 0 , 79 }, { 170, 100, 100 } },
{ "Forest green (traditional)", "#014421", { 1 , 68 , 33 }, { 74, 99 , 27 } },
{ "Forest green (web)", "#228B22", { 34 , 139, 34 }, { 60, 76 , 55 } },
{ "French beige", "#A67B5B", { 166, 123, 91 }, { 13, 45 , 65 } },
{ "French bistre", "#856D4D", { 133, 109, 77 }, { 17, 42 , 52 } },
{ "French blue", "#0072BB", { 0 , 114, 187 }, { 101, 100, 73 } },
{ "French fuchsia", "#FD3F92", { 253, 63 , 146 }, { 167, 75 , 99 } },
{ "French lilac", "#86608E", { 134, 96 , 142 }, { 145, 32 , 56 } },
{ "French lime", "#9EFD38", { 158, 253, 56 }, { 44, 78 , 99 } },
{ "French mauve", "#D473D4", { 212, 115, 212 }, { 150, 46 , 83 } },
{ "French pink", "#FD6C9E", { 253, 108, 158 }, { 169, 57 , 99 } },
{ "French plum", "#811453", { 129, 20 , 83 }, { 162, 84 , 51 } },
{ "French puce", "#4E1609", { 78 , 22 , 9 }, { 5, 88 , 31 } },
{ "French raspberry", "#C72C48", { 199, 44 , 72 }, { 174, 78 , 78 } },
{ "French rose", "#F64A8A", { 246, 74 , 138 }, { 169, 70 , 96 } },
{ "French sky blue", "#77B5FE", { 119, 181, 254 }, { 106, 53 , 100 } },
{ "French violet", "#8806CE", { 136, 6 , 206 }, { 139, 97 , 81 } },
{ "French wine", "#AC1E44", { 172, 30 , 68 }, { 172, 83 , 67 } },
{ "Fresh Air", "#A6E7FF", { 166, 231, 255 }, { 98, 35 , 100 } },
{ "Frostbite", "#E936A7", { 233, 54 , 167 }, { 161, 77 , 91 } },
{ "Fuchsia", "#FF00FF", { 255, 0 , 255 }, { 150, 100, 100 } },
{ "Fuchsia (Crayola)", "#C154C1", { 193, 84 , 193 }, { 150, 56 , 76 } },
{ "Fuchsia pink", "#FF77FF", { 255, 119, 255 }, { 150, 53 , 100 } },
{ "Fuchsia purple", "#CC397B", { 204, 57 , 123 }, { 166, 72 , 80 } },
{ "Fuchsia rose", "#C74375", { 199, 67 , 117 }, { 168, 66 , 78 } },
{ "Fulvous", "#E48400", { 228, 132, 0 }, { 17, 100, 89 } },
{ "Fuzzy Wuzzy", "#CC6666", { 204, 102, 102 }, { 0, 50 , 80 } },
{ "Gainsboro", "#DCDCDC", { 220, 220, 220 }, { 0, 0 , 86 } },
{ "Gamboge", "#E49B0F", { 228, 155, 15 }, { 19, 93 , 89 } },
{ "Gamboge orange (brown)", "#996600", { 152, 102, 0 }, { 20, 100, 60 } },
{ "Gargoyle Gas", "#FFDF46", { 255, 223, 70 }, { 25, 73 , 100 } },
{ "Generic viridian", "#007F66", { 0 , 127, 102 }, { 84, 100, 50 } },
{ "Ghost white", "#F8F8FF", { 248, 248, 255 }, { 120, 3 , 100 } },
{ "Giants orange", "#FE5A1D", { 254, 90 , 29 }, { 8, 89 , 100 } },
{ "Giant's Club", "#B05C52", { 176, 92 , 82 }, { 3, 53 , 69 } },
{ "Ginger", "#B06500", { 176, 101, 0 }, { 17, 100, 69 } },
{ "Glaucous", "#6082B6", { 96 , 130, 182 }, { 108, 47 , 71 } },
{ "Glitter", "#E6E8FA", { 230, 232, 250 }, { 117, 8 , 98 } },
{ "Glossy Grape", "#AB92B3", { 171, 146, 179 }, { 142, 18 , 70 } },
{ "Goldenrod", "#DAA520", { 218, 165, 32 }, { 21, 85 , 85 } },
{ "Golden brown", "#996515", { 153, 101, 21 }, { 18, 86 , 60 } },
{ "Golden poppy", "#FCC200", { 252, 194, 0 }, { 23, 100, 99 } },
{ "Golden yellow", "#FFDF00", { 255, 223, 0 }, { 26, 100, 100 } },
{ "Gold Fusion", "#85754E", { 133, 117, 78 }, { 21, 41 , 52 } },
{ "Gold (metallic)", "#D4AF37", { 212, 175, 55 }, { 23, 74 , 83 } },
{ "Gold (web) (Golden)", "#FFD700", { 255, 215, 0 }, { 25, 100, 100 } },
{ "GO green", "#00AB66", { 0 , 171, 102 }, { 78, 100, 67 } },
{ "Granite Gray", "#676767", { 103, 103, 103 }, { 0, 0 , 40 } },
{ "Granny Smith Apple", "#A8E4A0", { 168, 228, 160 }, { 56, 30 , 89 } },
{ "Grape", "#6F2DA8", { 111, 45 , 168 }, { 136, 73 , 66 } },
{ "Gray", "#808080", { 128, 128, 128 }, { 0, 0 , 50 } },
{ "Gray-asparagus", "#465945", { 70 , 89 , 69 }, { 58, 22 , 35 } },
{ "Gray-blue", "#8C92AC", { 140, 146, 172 }, { 114, 19 , 67 } },
{ "Gray (HTML/CSS gray)", "#808080", { 128, 128, 128 }, { 0, 0 , 50 } },
{ "Gray (X11 gray)", "#BEBEBE", { 190, 190, 190 }, { 0, 0 , 75 } },
{ "Green-blue", "#1164B4", { 17 , 100, 180 }, { 104, 91 , 71 } },
{ "Green (Color Wheel) (X11 green)", "#00FF00", { 0 , 255, 0 }, { 60, 100, 100 } },
{ "Green (Crayola)", "#1CAC78", { 28 , 172, 120 }, { 79, 84 , 67 } },
{ "Green-cyan", "#009966", { 0 , 153, 102 }, { 80, 100, 60 } },
{ "Green (HTML/CSS color)", "#008000", { 0 , 128, 0 }, { 60, 100, 50 } },
{ "Green Lizard", "#A7F432", { 167, 244, 50 }, { 42, 80 , 96 } },
{ "Green (Munsell)", "#00A877", { 0 , 168, 119 }, { 81, 100, 66 } },
{ "Green (NCS)", "#009F6B", { 0 , 159, 107 }, { 80, 100, 62 } },
{ "Green (Pantone)", "#00AD43", { 0 , 173, 67 }, { 71, 100, 68 } },
{ "Green (pigment)", "#00A550", { 0 , 165, 80 }, { 74, 100, 65 } },
{ "Green (RYB)", "#66B032", { 102, 176, 50 }, { 47, 72 , 69 } },
{ "Green Sheen", "#6EAEA1", { 110, 174, 161 }, { 84, 37 , 68 } },
{ "Green-yellow", "#ADFF2F", { 173, 255, 47 }, { 42, 82 , 100 } },
{ "Grizzly", "#885818", { 136, 88 , 24 }, { 17, 82 , 53 } },
{ "Grullo", "#A99A86", { 169, 154, 134 }, { 17, 21 , 66 } },
{ "Gunmetal", "#2A3439", { 42, 52, 57 }, { 100, 15, 19 } },
{ "Guppie green", "#00FF7F", { 0 , 255, 127 }, { 75, 100, 100 } },
{ "Halayà úbe", "#663854", { 102, 55 , 84 }, { 161, 45 , 40 } },
{ "Hansa yellow", "#E9D66B", { 233, 214, 107 }, { 25, 54 , 91 } },
{ "Han blue", "#446CCF", { 68 , 108, 207 }, { 111, 67 , 81 } },
{ "Han purple", "#5218FA", { 82 , 24 , 250 }, { 127, 90 , 98 } },
{ "Harlequin", "#3FFF00", { 63 , 255, 0 }, { 52, 100, 100 } },
{ "Harlequin green", "#46CB18", { 70 , 203, 24 }, { 52, 88 , 80 } },
{ "Harvard crimson", "#C90016", { 201, 0 , 22 }, { 176, 100, 79 } },
{ "Harvest gold", "#DA9100", { 218, 145, 0 }, { 20, 100, 85 } },
{ "Heart Gold", "#808000", { 128, 128, 0 }, { 30, 100, 50 } },
{ "Heat Wave", "#FF7A00", { 255, 122, 0 }, { 14, 100, 100 } },
{ "Heidelberg Red", "#960018", { 150, 0 , 24 }, { 5, 100, 60 } },
{ "Heliotrope", "#DF73FF", { 223, 115, 255 }, { 143, 55 , 100 } },
{ "Heliotrope gray", "#AA98A9", { 170, 152, 168 }, { 151, 11 , 67 } },
{ "Heliotrope magenta", "#AA00BB", { 170, 0 , 187 }, { 147, 100, 73 } },
{ "Hollywood cerise", "#F400A1", { 244, 0 , 161 }, { 160, 100, 96 } },
{ "Honeydew", "#F0FFF0", { 240, 255, 240 }, { 60, 6 , 100 } },
{ "Honolulu blue", "#006DB0", { 0 , 109, 176 }, { 101, 100, 69 } },
{ "Hooker's green", "#49796B", { 73 , 121, 107 }, { 81, 40 , 47 } },
{ "Hot magenta", "#FF1DCE", { 255, 29 , 206 }, { 156, 89 , 100 } },
{ "Hot pink", "#FF69B4", { 255, 105, 180 }, { 165, 59 , 100 } },
{ "North Texas Green", "#059033", { 5 , 144, 51 }, { 70, 97 , 56 } },
{ "Hunter green", "#355E3B", { 53 , 94 , 59 }, { 64, 44 , 37 } },
{ "Iceberg", "#71A6D2", { 113, 166, 210 }, { 103, 46 , 82 } },
{ "Icterine", "#FCF75E", { 252, 247, 94 }, { 29, 63 , 99 } },
{ "Iguana Green", "#71BC78", { 113, 188, 120 }, { 63, 40 , 74 } },
{ "Illuminating Emerald", "#319177", { 49 , 145, 119 }, { 82, 66 , 57 } },
{ "Imperial", "#602F6B", { 96 , 47 , 107 }, { 144, 56 , 42 } },
{ "Imperial blue", "#002395", { 0 , 35 , 149 }, { 113, 100, 58 } },
{ "Imperial purple", "#66023C", { 102, 2 , 60 }, { 162, 98 , 40 } },
{ "Imperial red", "#ED2939", { 237, 41 , 57 }, { 177, 83 , 93 } },
{ "Inchworm", "#B2EC5D", { 178, 236, 93 }, { 42, 61 , 93 } },
{ "Independence", "#4C516D", { 76 , 81 , 109 }, { 115, 30 , 43 } },
{ "Indian red", "#CD5C5C", { 205, 92 , 92 }, { 0, 55 , 80 } },
{ "Indian yellow", "#E3A857", { 227, 168, 87 }, { 17, 62 , 89 } },
{ "India green", "#138808", { 19 , 136, 8 }, { 57, 94 , 53 } },
{ "Indigo", "#4B0082", { 75 , 0 , 130 }, { 133, 100, 100 } },
{ "Indigo dye", "#091F92", { 9 , 31 , 146 }, { 115, 94 , 57 } },
{ "Indigo (web)", "#4B0082", { 75 , 0 , 130 }, { 137, 100, 51 } },
{ "Infra Red", "#FF496C", { 255, 73 , 108 }, { 174, 71 , 100 } },
{ "Interdimensional Blue", "#360CCC", { 54 , 12 , 204 }, { 126, 94 , 80 } },
{ "International Klein Blue", "#002FA7", { 0 , 47 , 167 }, { 111, 100, 65 } },
{ "International orange (aerospace)", "#FF4F00", { 255, 79 , 0 }, { 9, 100, 100 } },
{ "International orange (engineering)", "#BA160C", { 186, 22 , 12 }, { 1, 94 , 73 } },
{ "International orange (Golden Gate Bridge)", "#C0362C", { 192, 54 , 44 }, { 2, 77 , 75 } },
{ "Iris", "#5A4FCF", { 90 , 79 , 207 }, { 122, 62 , 81 } },
{ "Irresistible", "#B3446C", { 179, 68 , 108 }, { 169, 62 , 70 } },
{ "Isabelline", "#F4F0EC", { 244, 240, 236 }, { 15, 3 , 96 } },
{ "Islamic green", "#009000", { 0 , 144, 0 }, { 60, 100, 56 } },
{ "Italian sky blue", "#B2FFFF", { 178, 255, 255 }, { 90, 30 , 100 } },
{ "Ivory", "#FFFFF0", { 255, 255, 240 }, { 30, 6 , 100 } },
{ "Jade", "#00A86B", { 0 , 168, 107 }, { 79, 100, 66 } },
{ "Japanese carmine", "#9D2933", { 157, 41 , 51 }, { 177, 74 , 62 } },
{ "Japanese indigo", "#264348", { 38 , 67 , 72 }, { 94, 47 , 28 } },
{ "Japanese violet", "#5B3256", { 91 , 50 , 86 }, { 153, 45 , 36 } },
{ "Jasmine", "#F8DE7E", { 248, 222, 126 }, { 23, 49 , 97 } },
{ "Jasper", "#D73B3E", { 215, 59 , 62 }, { 179, 73 , 84 } },
{ "Jazzberry jam", "#A50B5E", { 165, 11 , 94 }, { 164, 93 , 65 } },
{ "Jelly Bean", "#DA614E", { 218, 97 , 78 }, { 4, 64 , 85 } },
{ "Jet", "#343434", { 52 , 52 , 52 }, { 0, 0 , 20 } },
{ "Jonquil", "#F4CA16", { 244, 202, 22 }, { 24, 91 , 96 } },
{ "Jordy blue", "#8AB9F1", { 138, 185, 241 }, { 106, 43, 95 } },
{ "June bud", "#BDDA57", { 189, 218, 87 }, { 36, 60, 85 } },
{ "Jungle green", "#29AB87", { 41 , 171, 135 }, { 81, 76 , 67 } },
{ "Kelly green", "#4CBB17", { 76 , 187, 23 }, { 50, 88 , 73 } },
{ "Kenyan copper", "#7C1C05", { 124, 28 , 5 }, { 6, 96 , 49 } },
{ "Keppel", "#3AB09E", { 58 , 176, 158 }, { 85, 67 , 69 } },
{ "Key Lime", "#E8F48C", { 232, 244, 140 }, { 33, 43 , 96 } },
{ "Khaki (HTML/CSS) (Khaki)", "#C3B091", { 195, 176, 145 }, { 18, 26 , 76 } },
{ "Khaki (X11) (Light khaki)", "#F0E68C", { 240, 230, 140 }, { 27, 42 , 94 } },
{ "Kiwi", "#8EE53F", { 142, 229, 63 }, { 45, 72 , 90 } },
{ "Kobe", "#882D17", { 136, 45 , 23 }, { 6, 83 , 53 } },
{ "Kobi", "#E79FC4", { 231, 159, 196 }, { 164, 31 , 91 } },
{ "Kobicha", "#6B4423", { 107, 68 , 35 }, { 14, 67 , 42 } },
{ "Kombu green", "#354230", { 53 , 66 , 48 }, { 51, 27 , 26 } },
{ "KSU Purple", "#512888", { 79 , 38 , 131 }, { 133, 71 , 53 } },
{ "KU Crimson", "#E8000D", { 232, 0 , 13 }, { 178, 100, 91 } },
{ "Languid lavender", "#D6CADD", { 214, 202, 221 }, { 139, 9 , 87 } },
{ "Lapis lazuli", "#26619C", { 38 , 97 , 156 }, { 105, 76 , 61 } },
{ "Laser Lemon", "#FFFF66", { 255, 255, 102 }, { 30, 60 , 100 } },
{ "Laurel green", "#A9BA9D", { 169, 186, 157 }, { 47, 16 , 73 } },
{ "Lava", "#CF1020", { 207, 16 , 32 }, { 177, 92 , 81 } },
{ "Lavender blue", "#CCCCFF", { 204, 204, 255 }, { 120, 20 , 100 } },
{ "Lavender blush", "#FFF0F5", { 255, 240, 245 }, { 170, 6 , 100 } },
{ "Lavender (floral)", "#B57EDC", { 181, 126, 220 }, { 137, 43 , 86 } },
{ "Lavender gray", "#C4C3D0", { 196, 195, 208 }, { 122, 6 , 82 } },
{ "Lavender indigo", "#9457EB", { 148, 87 , 235 }, { 132, 63 , 92 } },
{ "Lavender magenta", "#EE82EE", { 238, 130, 238 }, { 150, 45 , 93 } },
{ "Lavender mist", "#E6E6FA", { 230, 230, 250 }, { 120, 8 , 98 } },
{ "Lavender pink", "#FBAED2", { 251, 174, 210 }, { 166, 31 , 98 } },
{ "Lavender purple", "#967BB6", { 150, 123, 182 }, { 133, 32 , 71 } },
{ "Lavender rose", "#FBA0E3", { 251, 160, 227 }, { 158, 36 , 98 } },
{ "Lavender (web)", "#E6E6FA", { 230, 230, 250 }, { 120, 8 , 98 } },
{ "Lawn green", "#7CFC00", { 124, 252, 0 }, { 45, 100, 99 } },
{ "La Salle Green", "#087830", { 8 , 120, 48 }, { 70, 93 , 47 } },
{ "Lemon", "#FFF700", { 255, 247, 0 }, { 29, 100, 100 } },
{ "Lemon chiffon", "#FFFACD", { 255, 250, 205 }, { 27, 20 , 100 } },
{ "Lemon curry", "#CCA01D", { 204, 160, 29 }, { 22, 86 , 80 } },
{ "Lemon glacier", "#FDFF00", { 253, 255, 0 }, { 30, 100, 100 } },
{ "Lemon lime", "#E3FF00", { 227, 255, 0 }, { 33, 100, 100 } },
{ "Lemon meringue", "#F6EABE", { 246, 234, 190 }, { 23, 23 , 96 } },
{ "Lemon yellow", "#FFF44F", { 255, 244, 79 }, { 28, 69 , 100 } },
{ "Liberty", "#545AA7", { 84 , 90 , 167 }, { 118, 50 , 65 } },
{ "Licorice", "#1A1110", { 26 , 17 , 16 }, { 3, 38 , 10 } },
{ "Light apricot", "#FDD5B1", { 253, 213, 177 }, { 14, 30 , 99 } },
{ "Light blue", "#ADD8E6", { 173, 216, 230 }, { 97, 25 , 90 } },
{ "Light brown", "#B5651D", { 181, 101, 29 }, { 14, 84 , 71 } },
{ "Light carmine pink", "#E66771", { 230, 103, 113 }, { 177, 55 , 90 } },
{ "Light cobalt blue", "#88ACE0", { 136, 172, 224 }, { 107, 39 , 88 } },
{ "Light coral", "#F08080", { 240, 128, 128 }, { 0, 47 , 94 } },
{ "Light cornflower blue", "#93CCEA", { 147, 204, 234 }, { 100, 37 , 92 } },
{ "Light crimson", "#F56991", { 245, 105, 145 }, { 171, 57 , 96 } },
{ "Light cyan", "#E0FFFF", { 224, 255, 255 }, { 90, 12 , 100 } },
{ "Light deep pink", "#FF5CCD", { 255, 92 , 205 }, { 159, 64 , 100 } },
{ "Light French beige", "#C8AD7F", { 200, 173, 127 }, { 19, 37 , 78 } },
{ "Light fuchsia pink", "#F984EF", { 249, 132, 239 }, { 152, 47, 98 } },
{ "Light goldenrod yellow", "#FAFAD2", { 250, 250, 210 }, { 30, 16 , 98 } },
{ "Light gray", "#D3D3D3", { 211, 211, 211 }, { 0, 0 , 83 } },
{ "Light grayish magenta", "#CC99CC", { 204, 153, 204 }, { 150, 25, 80 } },
{ "Light green", "#90EE90", { 144, 238, 144 }, { 60, 39 , 93 } },
{ "Light hot pink", "#FFB3DE", { 255, 179, 222 }, { 163, 30 , 100 } },
{ "Light khaki", "#F0E68C", { 240, 230, 140 }, { 27, 42 , 94 } },
{ "Light medium orchid", "#D39BCB", { 211, 155, 203 }, { 154, 27 , 83 } },
{ "Light moss green", "#ADDFAD", { 173, 223, 173 }, { 60, 22 , 87 } },
{ "Light orange", "#FED8B1", { 254, 216, 177 }, { 15, 30, 100 } },
{ "Light orchid", "#E6A8D7", { 230, 168, 215 }, { 157, 27 , 90 } },
{ "Light pastel purple", "#B19CD9", { 177, 156, 217 }, { 130, 28 , 85 } },
{ "Light pink", "#FFB6C1", { 255, 182, 193 }, { 175, 29 , 100 } },
{ "Light red ochre", "#E97451", { 233, 116, 81 }, { 7, 65 , 91 } },
{ "Light salmon", "#FFA07A", { 255, 160, 122 }, { 8, 52 , 100 } },
{ "Light salmon pink", "#FF9999", { 255, 153, 153 }, { 0, 40 , 100 } },
{ "Light sea green", "#20B2AA", { 32 , 178, 170 }, { 88, 82, 70 } },
{ "Light sky blue", "#87CEFA", { 135, 206, 250 }, { 101, 46 , 98 } },
{ "Light slate gray", "#778899", { 119, 136, 153 }, { 105, 22 , 60 } },
{ "Light steel blue", "#B0C4DE", { 176, 196, 222 }, { 107, 21 , 87 } },
{ "Light taupe", "#B38B6D", { 179, 139, 109 }, { 13, 39 , 70 } },
{ "Light Thulian pink", "#E68FAC", { 230, 143, 172 }, { 170, 38 , 90 } },
{ "Light yellow", "#FFFFE0", { 255, 255, 224 }, { 30, 12 , 100 } },
{ "Lilac", "#C8A2C8", { 200, 162, 200 }, { 150, 19 , 78 } },
{ "Lilac Luster", "#AE98AA", { 174, 152, 170 }, { 155, 13 , 68 } },
{ "Limerick", "#9DC209", { 157, 194, 9 }, { 36, 95 , 76 } },
{ "Lime (color wheel)", "#BFFF00", { 191, 255, 0 }, { 37, 100, 100 } },
{ "Lime green", "#32CD32", { 50 , 205, 50 }, { 60, 76, 80 } },
{ "Lime (web) (X11 green)", "#00FF00", { 0 , 255, 0 }, { 60, 100, 100 } },
{ "Lincoln green", "#195905", { 25 , 89 , 5 }, { 53, 94 , 35 } },
{ "Linen", "#FAF0E6", { 250, 240, 230 }, { 15, 8 , 98 } },
{ "Liseran Purple", "#DE6FA1", { 222, 111, 161 }, { 166, 50 , 87 } },
{ "Little boy blue", "#6CA0DC", { 108, 160, 220 }, { 106, 51 , 86 } },
{ "Liver", "#674C47", { 103, 76 , 71 }, { 4, 31 , 40 } },
{ "Liver chestnut", "#987456", { 152, 116, 86 }, { 13, 43 , 60 } },
{ "Liver (dogs)", "#B86D29", { 184, 109, 41 }, { 14, 78 , 72 } },
{ "Liver (organ)", "#6C2E1F", { 108, 46 , 31 }, { 6, 71 , 42 } },
{ "Livid", "#6699CC", { 102, 153, 204 }, { 105, 50 , 80 } },
{ "Loeen(lopen)look/vomit+indogo+Lopen+Gabriel", "#15F2FD", { 123, 154, 200 }, { 16, 45 , 76 } },
{ "Lumber", "#FFE4CD", { 255, 228, 205 }, { 14, 20 , 100 } },
{ "Lust", "#E62020", { 230, 32 , 32 }, { 0, 86 , 90 } },
{ "Maastricht Blue", "# 001C3D ", { 0 , 28 , 61 }, { 106, 100 , 24 } },
{ "Macaroni and Cheese", "#FFBD88", { 255, 189, 136 }, { 13, 47 , 100 } },
{ "Madder Lake", "#CC3336", { 204, 51 , 54 }, { 179, 75 , 80 } },
{ "Magenta", "#FF00FF", { 255, 0 , 255 }, { 150, 100, 100 } },
{ "Magenta (Crayola)", "#FF55A3", { 255, 85 , 163 }, { 166, 67 , 100 } },
{ "Magenta (dye)", "#CA1F7B", { 202, 31 , 123 }, { 164, 85 , 79 } },
{ "Magenta haze", "#9F4576", { 159, 69 , 118 }, { 163, 57 , 62 } },
{ "Magenta (Pantone)", "#D0417E", { 208, 65 , 126 }, { 167, 69 , 82 } },
{ "Magenta-pink", "#CC338B", { 204, 51 , 139 }, { 162, 75 , 80 } },
{ "Magenta (process)", "#FF0090", { 255, 0 , 144 }, { 163, 100, 100 } },
{ "Magic mint", "#AAF0D1", { 170, 240, 209 }, { 76, 29 , 94 } },
{ "Magic Potion", "#FF4466", { 255, 68 , 102 }, { 174, 73 , 100 } },
{ "Magnolia", "#F8F4FF", { 248, 244, 255 }, { 131, 4 , 100 } },
{ "Mahogany", "#C04000", { 192, 64 , 0 }, { 10, 100, 75 } },
{ "Maize", "#FBEC5D", { 251, 236, 93 }, { 27, 63 , 98 } },
{ "Majorelle Blue", "#6050DC", { 96 , 80 , 220 }, { 123, 64, 86 } },
{ "Malachite", "#0BDA51", { 11 , 218, 81 }, { 70, 95 , 85 } },
{ "Manatee", "#979AAA", { 151, 154, 170 }, { 115, 11 , 67 } },
{ "Mandarin", "#F37A48", { 243, 122, 72 }, { 9, 70 , 95 } },
{ "Mango Tango", "#FF8243", { 255, 130, 67 }, { 10, 74 , 100 } },
{ "Mantis", "#74C365", { 116, 195, 101 }, { 55, 48 , 76 } },
{ "Mardi Gras", "#880085", { 136, 0 , 133 }, { 150, 100, 53 } },
{ "Marigold", "#EAA221", { 234, 162, 33 }, { 19, 85 , 91 } },
{ "Maroon (Crayola)", "#C32148", { 195, 33 , 72 }, { 173, 83 , 76 } },
{ "Maroon (HTML/CSS)", "#800000", { 128, 0 , 0 }, { 0, 100, 50 } },
{ "Maroon (X11)", "#B03060", { 176, 48 , 96 }, { 169, 73 , 69 } },
{ "Mauve", "#E0B0FF", { 224, 176, 255 }, { 138, 31 , 100 } },
{ "Mauvelous", "#EF98AA", { 239, 152, 170 }, { 174, 36 , 94 } },
{ "Mauve taupe", "#915F6D", { 145, 95 , 109 }, { 171, 34 , 57 } },
{ "Maximum Blue", "#47ABCC", { 71 , 171, 204 }, { 97, 65 , 80 } },
{ "Maximum Blue Green", "#30BFBF", { 48 , 191, 191 }, { 90, 75 , 75 } },
{ "Maximum Blue Purple", "#ACACE6", { 172, 172, 230 }, { 120, 25 , 90 } },
{ "Maximum Green", "#5E8C31", { 94 , 140, 49 }, { 45, 65 , 55 } },
{ "Maximum Green Yellow", "#D9E650", { 217, 230, 80 }, { 32, 65 , 90 } },
{ "Maximum Purple", "#733380", { 115, 51 , 128 }, { 145, 60 , 50 } },
{ "Maximum Red", "#D92121", { 217, 33 , 33 }, { 0, 85 , 85 } },
{ "Maximum Red Purple", "#A63A79", { 166, 58 , 121 }, { 162, 65 , 65 } },
{ "Maximum Yellow", "#FAFA37", { 250, 250, 55 }, { 30, 78 , 98 } },
{ "Maximum Yellow Red", "#F2BA49", { 242, 186, 73 }, { 20, 70 , 95 } },
{ "Maya blue", "#73C2FB", { 115, 194, 251 }, { 102, 54 , 98 } },
{ "May green", "#4C9141", { 76 , 145, 65 }, { 56, 55 , 57 } },
{ "Meat brown", "#E5B73B", { 229, 183, 59 }, { 22, 74 , 90 } },
{ "Medium aquamarine", "#66DDAA", { 102, 221, 170 }, { 77, 54 , 87 } },
{ "Medium blue", "#0000CD", { 0 , 0 , 205 }, { 120, 100, 80 } },
{ "Medium candy apple red", "#E2062C", { 226, 6 , 44 }, { 175, 97 , 89 } },
{ "Medium carmine", "#AF4035", { 175, 64 , 53 }, { 2, 70 , 69 } },
{ "Medium champagne", "#F3E5AB", { 243, 229, 171 }, { 24, 30 , 95 } },
{ "Medium electric blue", "#035096", { 3 , 80 , 150 }, { 104, 98 , 59 } },
{ "Medium jungle green", "#1C352D", { 28 , 53 , 45 }, { 80, 47 , 21 } },
{ "Medium lavender magenta", "#DDA0DD", { 221, 160, 221 }, { 150, 28, 87 } },
{ "Medium orchid", "#BA55D3", { 186, 85 , 211 }, { 144, 60 , 83 } },
{ "Medium Persian blue", "#0067A5", { 0 , 103, 165 }, { 101, 100, 65 } },
{ "Medium purple", "#9370DB", { 147, 112, 219 }, { 130, 49 , 86 } },
{ "Medium red-violet", "#BB3385", { 187, 51 , 133 }, { 162, 73 , 73 } },
{ "Medium ruby", "#AA4069", { 170, 64 , 105 }, { 168, 62 , 67 } },
{ "Medium sea green", "#3CB371", { 60 , 179, 113 }, { 73, 66 , 70 } },
{ "Medium sky blue", "#80DAEB", { 128, 218, 235 }, { 95, 46 , 92 } },
{ "Medium slate blue", "#7B68EE", { 123, 104, 238 }, { 124, 56 , 93 } },
{ "Medium spring bud", "#C9DC87", { 201, 220, 135 }, { 36, 39 , 86 } },
{ "Medium spring green", "#00FA9A", { 0 , 250, 154 }, { 78, 100, 98 } },
{ "Medium taupe", "#674C47", { 103, 76 , 71 }, { 4, 31 , 40 } },
{ "Medium turquoise", "#48D1CC", { 72 , 209, 204 }, { 89, 66, 82 } },
{ "Medium Tuscan red", "#79443B", { 121, 68 , 59 }, { 4, 51 , 47 } },
{ "Medium vermilion", "#D9603B", { 217, 96 , 59 }, { 7, 73 , 85 } },
{ "Medium violet-red", "#C71585", { 199, 21 , 133 }, { 161, 89 , 78 } },
{ "Mellow apricot", "#F8B878", { 248, 184, 120 }, { 15, 52 , 97 } },
{ "Mellow yellow", "#F8DE7E", { 248, 222, 126 }, { 23, 49 , 97 } },
{ "Melon", "#FDBCB4", { 253, 188, 180 }, { 3, 29 , 99 } },
{ "Metallic Seaweed", "#0A7E8C", { 10 , 126, 140 }, { 93, 93 , 55 } },
{ "Metallic Sunburst", "#9C7C38", { 156, 124, 56 }, { 20, 64 , 61 } },
{ "Mexican pink", "#E4007C", { 228, 0 , 124 }, { 163, 100, 89 } },
{ "Middle Blue", "#7ED4E6", { 126, 212 , 230 }, { 95, 45, 90 } },
{ "Middle Blue Green", "#8DD9CC", { 141, 217 , 204 }, { 85, 35, 85 } },
{ "Middle Blue Purple", "#8B72BE", { 139, 114, 190 }, { 130, 40 , 75 } },
{ "Middle Green", "#4D8C57", { 77 , 140, 87 }, { 65, 45 , 55 } },
{ "Middle Green Yellow", "#ACBF60", { 172, 191, 96 }, { 36, 50 , 75 } },
{ "Middle Purple", "#D982B5", { 217, 130, 181 }, { 162, 40 , 85 } },
{ "Middle Red", "#E58E73", { 229, 144, 115 }, { 7, 50 , 90 } },
{ "Middle Red Purple", "#A55353", { 165 , 83 , 83 }, { 0, 50 , 65 } },
{ "Middle Yellow", "#FFEB00", { 255, 235, 0 }, { 27, 100, 100 } },
{ "Middle Yellow Red", "#ECB176", { 236, 177 , 118 }, { 15, 50, 93 } },
{ "Midnight", "#702670", { 112, 38 , 112 }, { 150, 66 , 44 } },
{ "Midnight blue", "#191970", { 25 , 25 , 112 }, { 120, 78 , 44 } },
{ "Midnight green (eagle green)", "#004953", { 0 , 73 , 83 }, { 93, 100, 33 } },
{ "Mikado yellow", "#FFC40C", { 255, 196, 12 }, { 22, 95 , 100 } },
{ "Milk", "#FDFFF5", { 253, 255, 245 }, { 36, 4 , 100 } },
{ "Mimi Pink", "#FFDAE9", { 255, 218, 233 }, { 168, 15 , 100 } },
{ "Mindaro", "#E3F988", { 227, 249, 136 }, { 36, 45 , 98 } },
{ "Ming", "#36747D", { 54 , 116, 125 }, { 94, 56 , 49 } },
{ "Minion Yellow", "#F5E050", { 245, 220, 80 }, { 26, 67 , 96 } },
{ "Mint", "#3EB489", { 62 , 180, 137 }, { 79, 66 , 71 } },
{ "Mint cream", "#F5FFFA", { 245, 255, 250 }, { 75, 4 , 100 } },
{ "Mint green", "#98FF98", { 152, 255, 152 }, { 60, 40 , 100 } },
{ "Misty Moss", "#BBB477", { 187, 180, 119 }, { 27, 36 , 73 } },
{ "Misty rose", "#FFE4E1", { 255, 228, 225 }, { 3, 12 , 100 } },
{ "Moccasin", "#FAEBD7", { 250, 235, 215 }, { 17, 14 , 98 } },
{ "Mode beige", "#967117", { 150, 113, 23 }, { 21, 85 , 59 } },
{ "Moonstone blue", "#73A9C2", { 115, 169, 194 }, { 99, 41 , 76 } },
{ "Mordant red 19", "#AE0C00", { 174, 12 , 0 }, { 2, 100, 68 } },
{ "Morning blue", "#8DA399", { 141, 163 , 153 }, { 76, 14 , 64 } },
{ "Moss green", "#8A9A5B", { 138, 154, 91 }, { 37, 41 , 60 } },
{ "Mountain Meadow", "#30BA8F", { 48 , 186, 143 }, { 80, 74 , 73 } },
{ "Mountbatten pink", "#997A8D", { 153, 122, 141 }, { 161, 20 , 60 } },
{ "MSU Green", "#18453B", { 24 , 69 , 59 }, { 83, 65 , 27 } },
{ "Mughal green", "#306030", { 48 , 96 , 48 }, { 60, 50 , 38 } },
{ "Mulberry", "#C54B8C", { 197, 75 , 140 }, { 164, 62 , 77 } },
{ "Mummy's Tomb", "#828E84", { 130, 142, 132 }, { 65, 9 , 56 } },
{ "Mustard", "#FFDB58", { 255, 219, 88 }, { 23, 65 , 100 } },
{ "Myrtle green", "#317873", { 49 , 120, 115 }, { 88, 59 , 47 } },
{ "Mystic", "#D65282", { 214, 82 , 130 }, { 169, 62 , 84 } },
{ "Mystic Maroon", "#AD4379", { 173, 67 , 121 }, { 164, 62 , 68 } },
{ "Nadeshiko pink", "#F6ADC6", { 246, 173, 198 }, { 169, 30 , 96 } },
{ "Napier green", "#2A8000", { 42 , 128, 0 }, { 50, 100, 50 } },
{ "Naples yellow", "#FADA5E", { 250, 218, 94 }, { 24, 62 , 98 } },
{ "Navajo white", "#FFDEAD", { 255, 222, 173 }, { 18, 32 , 100 } },
{ "Navy", "#000080", { 0 , 0 , 128 }, { 120, 100, 50 } },
{ "Navy purple", "#9457EB", { 148, 87 , 235 }, { 132, 63 , 92 } },
{ "Neon Carrot", "#FFA343", { 255, 163, 67 }, { 15, 74 , 100 } },
{ "Neon fuchsia", "#FE4164", { 254, 65 , 100 }, { 174, 74 , 100 } },
{ "Neon green", "#39FF14", { 57 , 255, 20 }, { 55, 92 , 100 } },
{ "New Car", "#214FC6", { 33 , 79 , 198 }, { 111, 83 , 78 } },
{ "New York pink", "#D7837F", { 215, 131, 127 }, { 1, 41 , 84 } },
{ "Nickel", "#727472", { 114, 116, 114 }, { 60, 2 , 46 } },
{ "Non-photo blue", "#A4DDED", { 164, 221, 237 }, { 96, 31 , 93 } },
{ "Nyanza", "#E9FFDB", { 233, 255, 219 }, { 48, 14 , 100 } },
{ "Ocean Blue", "#4F42B5", { 79 , 66 , 181 }, { 123, 64 , 71 } },
{ "Ocean Boat Blue", "#0077BE", { 0 , 119, 190 }, { 101, 100, 75 } },
{ "Ocean Green", "#48BF91", { 72 , 191, 145 }, { 78, 62 , 75 } },
{ "Ochre", "#CC7722", { 204, 119, 34 }, { 15, 83 , 80 } },
{ "Office green", "#008000", { 0 , 128, 0 }, { 60, 100, 50 } },
{ "Ogre Odor", "#FD5240", { 253, 82 , 64 }, { 3, 75 , 99 } },
{ "Old burgundy", "#43302E", { 67 , 48 , 46 }, { 3, 31 , 26 } },
{ "Old gold", "#CFB53B", { 207, 181, 59 }, { 24, 71 , 81 } },
{ "Old heliotrope", "#563C5C", { 86 , 60 , 92 }, { 144, 35 , 36 } },
{ "Old lace", "#FDF5E6", { 253, 245, 230 }, { 19, 9 , 99 } },
{ "Old lavender", "#796878", { 121, 104, 120 }, { 152, 14 , 47 } },
{ "Old mauve", "#673147", { 103, 49 , 71 }, { 168, 52 , 40 } },
{ "Old moss green", "#867E36", { 134, 126, 54 }, { 27, 60 , 53 } },
{ "Old rose", "#C08081", { 192, 128, 129 }, { 179, 33 , 75 } },
{ "Old silver", "#848482", { 132, 132, 130 }, { 30, 2 , 52 } },
{ "Olive", "#808000", { 128, 128, 0 }, { 30, 100, 50 } },
{ "Olive Drab (#3)", "#6B8E23", { 107, 142, 35 }, { 40, 75 , 56 } },
{ "Olive Drab #7", "#3C341F", { 60 , 52 , 31 }, { 21, 48 , 24 } },
{ "Olivine", "#9AB973", { 154, 185, 115 }, { 43, 38 , 73 } },
{ "Onyx", "#353839", { 53 , 56 , 57 }, { 97, 7 , 22 } },
{ "Opera mauve", "#B784A7", { 183, 132, 167 }, { 159, 28 , 72 } },
{ "Orange (color wheel)", "#FF7F00", { 255, 127, 0 }, { 15, 100, 100 } },
{ "Orange (Crayola)", "#FF7538", { 255, 117, 56 }, { 9, 78 , 100 } },
{ "Orange (Pantone)", "#FF5800", { 255, 88 , 0 }, { 10, 100, 100 } },
{ "Orange peel", "#FF9F00", { 255, 159, 0 }, { 18, 100, 100 } },
{ "Orange-red", "#FF4500", { 255, 69 , 0 }, { 8, 100, 100 } },
{ "Orange (RYB)", "#FB9902", { 251, 153, 2 }, { 18, 99 , 98 } },
{ "Orange Soda", "#FA5B3D", { 250, 91 , 61 }, { 5, 76 , 98 } },
{ "Orange (web)", "#FFA500", { 255, 165, 0 }, { 19, 100, 100 } },
{ "Orange-yellow", "#F8D568", { 248, 213, 104 }, { 22, 58 , 97 } },
{ "Orchid", "#DA70D6", { 218, 112, 214 }, { 151, 49 , 85 } },
{ "Orchid pink", "#F2BDCD", { 242, 189, 205 }, { 171, 22 , 95 } },
{ "Orioles orange", "#FB4F14", { 251, 79 , 20 }, { 7, 92 , 98 } },
{ "Otter brown", "#654321", { 101, 67 , 33 }, { 15, 67 , 40 } },
{ "Outer Space", "#414A4C", { 65 , 74 , 76 }, { 95, 14 , 30 } },
{ "Outrageous Orange", "#FF6E4A", { 255, 110, 74 }, { 6, 71 , 100 } },
{ "OU Crimson Red", "#990000", { 153, 0 , 0 }, { 0, 100, 60 } },
{ "Oxford Blue", "#002147", { 0 , 33 , 71 }, { 106, 100, 28 } },
{ "Pacific Blue", "#1CA9C9", { 28 , 169, 201 }, { 95, 86 , 79 } },
{ "Pakistan green", "#006600", { 0 , 102, 0 }, { 60, 100, 40 } },
{ "Palatinate blue", "#273BE2", { 39 , 59 , 226 }, { 117, 83 , 89 } },
{ "Palatinate purple", "#682860", { 104, 40 , 96 }, { 154, 62 , 41 } },
{ "Pale aqua", "#BCD4E6", { 188, 212, 230 }, { 103, 18 , 90 } },
{ "Pale blue", "#AFEEEE", { 175, 238, 238 }, { 90, 26 , 93 } },
{ "Pale brown", "#987654", { 152, 118, 84 }, { 15, 45 , 60 } },
{ "Pale carmine", "#AF4035", { 175, 64 , 53 }, { 2, 70 , 69 } },
{ "Pale cerulean", "#9BC4E2", { 155, 196, 226 }, { 102, 31 , 89 } },
{ "Pale chestnut", "#DDADAF", { 221, 173, 175 }, { 179, 22 , 87 } },
{ "Pale copper", "#DA8A67", { 218, 138, 103 }, { 9, 53 , 85 } },
{ "Pale cornflower blue", "#ABCDEF", { 171, 205, 239 }, { 105, 28 , 94 } },
{ "Pale cyan", "#87D3F8", { 135, 211, 248 }, { 100, 46 , 97 } },
{ "Pale gold", "#E6BE8A", { 230, 190, 138 }, { 17, 40 , 90 } },
{ "Pale goldenrod", "#EEE8AA", { 238, 232, 170 }, { 27, 29 , 93 } },
{ "Pale green", "#98FB98", { 152, 251, 152 }, { 60, 39 , 98 } },
{ "Pale lavender", "#DCD0FF", { 220, 208, 255 }, { 127, 18 , 100 } },
{ "Pale magenta", "#F984E5", { 249, 132, 229 }, { 155, 47 , 98 } },
{ "Pale magenta-pink", "#FF99CC", { 255, 153, 204 }, { 165, 40 , 100 } },
{ "Pale pink", "#FADADD", { 250, 218, 221 }, { 177, 13 , 98 } },
{ "Pale plum", "#DDA0DD", { 221, 160, 221 }, { 150, 28 , 87 } },
{ "Pale red-violet", "#DB7093", { 219, 112, 147 }, { 170, 49 , 86 } },
{ "Pale robin egg blue", "#96DED1", { 150, 222, 209 }, { 84, 32 , 87 } },
{ "Pale silver", "#C9C0BB", { 201, 192, 187 }, { 10, 7 , 79 } },
{ "Pale spring bud", "#ECEBBD", { 236, 235, 189 }, { 29, 20 , 93 } },
{ "Pale taupe", "#BC987E", { 188, 152, 126 }, { 12, 33 , 74 } },
{ "Pale turquoise", "#AFEEEE", { 175, 238, 238 }, { 90, 26 , 93 } },
{ "Pale violet", "#CC99FF", { 204, 153, 255 }, { 135, 40 , 100 } },
{ "Pale violet-red", "#DB7093", { 219, 112, 147 }, { 170, 49 , 86 } },
{ "Palm Leaf", "#6F9940", { 130, 142, 132 }, { 44, 58 , 60 } },
{ "Pansy purple", "#78184A", { 120, 24 , 74 }, { 164, 80 , 47 } },
{ "Paolo Veronese green", "#009B7D", { 0 , 155, 125 }, { 84, 100, 61 } },
{ "Papaya whip", "#FFEFD5", { 255, 239, 213 }, { 18, 16 , 100 } },
{ "Paradise pink", "#E63E62", { 230, 62 , 98 }, { 173, 73 , 90 } },
{ "Paris Green", "#50C878", { 80 , 200, 120 }, { 70, 60 , 78 } },
{ "Parrot Pink", "#D998A0", { 217, 152, 160 }, { 176, 30 , 85 } },
{ "Pastel blue", "#AEC6CF", { 174, 198, 207 }, { 98, 16 , 81 } },
{ "Pastel brown", "#836953", { 130, 105, 83 }, { 14, 37 , 51 } },
{ "Pastel gray", "#CFCFC4", { 207, 207, 196 }, { 30, 5 , 81 } },
{ "Pastel green", "#77DD77", { 119, 221, 119 }, { 60, 46 , 87 } },
{ "Pastel magenta", "#F49AC2", { 244, 154, 194 }, { 166, 37 , 96 } },
{ "Pastel orange", "#FFB347", { 255, 179, 71 }, { 17, 72 , 100 } },
{ "Pastel pink", "#DEA5A4", { 222, 165, 164 }, { 0, 26 , 87 } },
{ "Pastel purple", "#B39EB5", { 179, 158, 181 }, { 147, 13 , 71 } },
{ "Pastel red", "#FF6961", { 255, 105, 97 }, { 1, 62 , 100 } },
{ "Pastel violet", "#CB99C9", { 203, 153, 201 }, { 151, 25 , 80 } },
{ "Pastel yellow", "#FDFD96", { 253, 253, 150 }, { 30, 41 , 99 } },
{ "Patriarch", "#800080", { 128, 0 , 128 }, { 150, 100, 50 } },
{ "Payne's grey", "#536878", { 83 , 104, 120 }, { 103, 31 , 47 } },
{ "Peach", "#FFCBA4", { 255, 203, 164 }, { 13, 36 , 100 } },
{ "Peach-orange", "#FFCC99", { 255, 204, 153 }, { 15, 40 , 100 } },
{ "Peach puff", "#FFDAB9", { 255, 218, 185 }, { 14, 27 , 100 } },
{ "Peach-yellow", "#FADFAD", { 250, 223, 173 }, { 19, 31 , 98 } },
{ "Pear", "#D1E231", { 209, 226, 49 }, { 33, 78 , 89 } },
{ "Pearl", "#EAE0C8", { 234, 224, 200 }, { 21, 15 , 92 } },
{ "Pearly purple", "#B768A2", { 183, 104, 162 }, { 158, 43 , 72 } },
{ "Pearl Aqua", "#88D8C0", { 136, 216, 192 }, { 81, 37 , 85 } },
{ "Peridot", "#E6E200", { 230, 226, 0 }, { 29, 100, 90 } },
{ "Periwinkle", "#CCCCFF", { 204, 204, 255 }, { 120, 20 , 100 } },
{ "Permanent Geranium Lake", "#E12C2C", { 225, 44 , 44 }, { 0, 80 , 88 } },
{ "Persian blue", "#1C39BB", { 28 , 57 , 187 }, { 114, 85 , 73 } },
{ "Persian green", "#00A693", { 0 , 166, 147 }, { 86, 100, 65 } },
{ "Persian indigo", "#32127A", { 50 , 18 , 122 }, { 129, 85 , 48 } },
{ "Persian orange", "#D99058", { 217, 144, 88 }, { 13, 59 , 85 } },
{ "Persian pink", "#F77FBE", { 247, 127, 190 }, { 164, 49 , 97 } },
{ "Persian plum", "#701C1C", { 112, 28 , 28 }, { 0, 75 , 44 } },
{ "Persian red", "#CC3333", { 204, 51 , 51 }, { 0, 75 , 80 } },
{ "Persian rose", "#FE28A2", { 254, 40 , 162 }, { 163, 84 , 100 } },
{ "Persimmon", "#EC5800", { 236, 88 , 0 }, { 11, 100, 93 } },
{ "Peru", "#CD853F", { 205, 133, 63 }, { 15, 69 , 80 } },
{ "Pewter Blue", "#8BA8B7", { 139, 168, 183 }, { 100, 24 , 72 } },
{ "Phlox", "#DF00FF", { 223, 0 , 255 }, { 146, 100, 100 } },
{ "Phthalo blue", "#000F89", { 0 , 15 , 137 }, { 116, 100, 54 } },
{ "Phthalo green", "#123524", { 18 , 53 , 36 }, { 75, 66 , 21 } },
{ "Picton blue", "#45B1E8", { 69 , 177, 232 }, { 100, 70 , 91 } },
{ "Pictorial carmine", "#C30B4E", { 195, 11 , 78 }, { 169, 94 , 76 } },
{ "Piggy pink", "#FDDDE6", { 253, 221, 230 }, { 171, 13 , 99 } },
{ "Pineapple", "#563C5C", { 86 , 60 , 13 }, { 144, 35 , 36 } },
{ "Pine green", "#01796F", { 1 , 121, 111 }, { 87, 99 , 47 } },
{ "Pink", "#FFC0CB", { 255, 192, 203 }, { 175, 25 , 100 } },
{ "Pink Flamingo", "#FC74FD", { 252, 116, 253 }, { 150, 54 , 99 } },
{ "Pink lace", "#FFDDF4", { 255, 221, 244 }, { 159, 13 , 100 } },
{ "Pink lavender", "#D8B2D1", { 216, 178, 209 }, { 155, 18 , 85 } },
{ "Pink-orange", "#FF9966", { 255, 153, 102 }, { 10, 60 , 100 } },
{ "Pink (Pantone)", "#D74894", { 215, 72 , 148 }, { 164, 67 , 84 } },
{ "Pink pearl", "#E7ACCF", { 231, 172, 207 }, { 162, 26 , 91 } },
{ "Pink raspberry", "#980036", { 152, 0 , 54 }, { 169, 100, 60 } },
{ "Pink Sherbet", "#F78FA7", { 247, 143, 167 }, { 173, 42 , 97 } },
{ "Pistachio", "#93C572", { 147, 197, 114 }, { 48, 42 , 77 } },
{ "Pixie Powder", "#391285", { 57 , 18 , 133 }, { 130, 87 , 52 } },
{ "Platinum", "#E5E4E2", { 229, 228, 226 }, { 20, 1 , 90 } },
{ "Plum", "#8E4585", { 142, 69 , 133 }, { 153, 51 , 56 } },
{ "Plump Purple", "#5946B2", { 89 , 70 , 178 }, { 125, 61 , 70 } },
{ "Plum (web)", "#DDA0DD", { 221, 160, 221 }, { 150, 28 , 87 } },
{ "Polished Pine", "#5DA493", { 93 , 164, 147 }, { 83, 43 , 64 } },
{ "Pomp and Power", "#86608E", { 134, 96 , 142 }, { 145, 32 , 56 } },
{ "Popstar", "#BE4F62", { 190, 79 , 98 }, { 175, 58 , 75 } },
{ "Portland Orange", "#FF5A36", { 255, 90 , 54 }, { 5, 79 , 100 } },
{ "Powder blue", "#B0E0E6", { 176, 224, 230 }, { 93, 23 , 90 } },
{ "Princess Perfume", "#FF85CF", { 255, 133, 207 }, { 162, 48 , 100 } },
{ "Princeton orange", "#F58025", { 245, 128, 37 }, { 13, 85 , 96 } },
{ "Prune", "#701C1C", { 112, 28 , 28 }, { 0, 75 , 44 } },
{ "Prussian blue", "#003153", { 0 , 49 , 83 }, { 102, 100, 33 } },
{ "Psychedelic purple", "#DF00FF", { 223, 0 , 255 }, { 146, 100, 100 } },
{ "Puce", "#CC8899", { 204, 136, 153 }, { 172, 33 , 80 } },
{ "Puce red", "#722F37", { 114, 47 , 55 }, { 176, 59 , 45 } },
{ "Pullman Brown (UPS Brown)", "#644117", { 100, 65 , 23 }, { 16, 77 , 39 } },
{ "Pullman Green", "#3B331C", { 59 , 51 , 28 }, { 22, 36 , 59 } },
{ "Pumpkin", "#FF7518", { 255, 117, 24 }, { 12, 91 , 100 } },
{ "Purple Heart", "#69359C", { 105, 53 , 156 }, { 135, 66 , 61 } },
{ "Purple (HTML)", "#800080", { 128, 0 , 128 }, { 150, 100, 50 } },
{ "Purple mountain majesty", "#9678B6", { 150, 120, 182 }, { 134, 34 , 71 } },
{ "Purple (Munsell)", "#9F00C5", { 159, 0 , 197 }, { 144, 100, 77 } },
{ "Purple navy", "#4E5180", { 78 , 81 , 128 }, { 118, 39 , 50 } },
{ "Purple pizzazz", "#FE4EDA", { 254, 78 , 218 }, { 156, 69 , 100 } },
{ "Purple Plum", "#9C51B6", { 156, 81 , 182 }, { 142, 56 , 71 } },
{ "Purple taupe", "#50404D", { 80 , 64 , 77 }, { 155, 20 , 31 } },
{ "Purple (X11)", "#A020F0", { 160, 32 , 240 }, { 138, 87 , 94 } },
{ "Purpureus", "#9A4EAE", { 154, 78 , 174 }, { 144, 55 , 68 } },
{ "Quartz", "#51484F", { 81 , 72 , 79 }, { 156, 11 , 32 } },
{ "Queen blue", "#436B95", { 67 , 107, 149 }, { 105, 55 , 58 } },
{ "Queen pink", "#E8CCD7", { 232, 204, 215 }, { 168, 12 , 91 } },
{ "Quick Silver", "#A6A6A6", { 166, 166, 166 }, { 0, 0 , 65 } },
{ "Quinacridone magenta", "#8E3A59", { 142, 58 , 89 }, { 169, 59 , 56 } },
{ "Rackley", "#5D8AA8", { 93 , 138, 168 }, { 102, 45 , 66 } },
{ "Radical Red", "#FF355E", { 255, 53 , 94 }, { 174, 79 , 100 } },
{ "Raisin black", "#242124", { 36 , 33 , 36 }, { 150, 8 , 14 } },
{ "Rajah", "#FBAB60", { 251, 171, 96 }, { 14, 62 , 98 } },
{ "Raspberry", "#E30B5D", { 227, 11 , 92 }, { 168, 95 , 89 } },
{ "Raspberry glace", "#915F6D", { 145, 95 , 109 }, { 171, 34 , 57 } },
{ "Raspberry pink", "#E25098", { 226, 80 , 152 }, { 165, 65 , 89 } },
{ "Raspberry rose", "#B3446C", { 179, 68 , 108 }, { 169, 62 , 70 } },
{ "Raw Sienna", "#D68A59", { 214, 138, 89 }, { 12, 58 , 84 } },
{ "Raw umber", "#826644", { 130, 102, 68 }, { 16, 48 , 51 } },
{ "Razzle dazzle rose", "#FF33CC", { 255, 51 , 204 }, { 157, 80 , 100 } },
{ "Razzmatazz", "#E3256B", { 227, 37 , 107 }, { 169, 84 , 89 } },
{ "Razzmic Berry", "#8D4E85", { 141, 78 , 133 }, { 154, 45 , 55 } },
{ "Rebecca Purple", "#663399", { 102, 52 , 153 }, { 135, 67 , 60 } },
{ "Red", "#FF0000", { 255, 0 , 0 }, { 0, 100, 100 } },
{ "Redwood", "#A45A52", { 164, 90 , 82 }, { 3, 50 , 64 } },
{ "Red-brown", "#A52A2A", { 165, 42 , 42 }, { 0, 75 , 65 } },
{ "Red (Crayola)", "#EE204D", { 238, 32 , 77 }, { 173, 87 , 93 } },
{ "Red devil", "#860111", { 134, 1 , 17 }, { 176, 99 , 53 } },
{ "Red (Munsell)", "#F2003C", { 242, 0 , 60 }, { 172, 100, 95 } },
{ "Red (NCS)", "#C40233", { 196, 2 , 51 }, { 172, 99 , 77 } },
{ "Red-orange", "#FF5349", { 255, 83 , 73 }, { 1, 71 , 100 } },
{ "Red (Pantone)", "#ED2939", { 237, 41 , 57 }, { 177, 83 , 93 } },
{ "Red (pigment)", "#ED1C24", { 237, 28 , 36 }, { 179, 88 , 93 } },
{ "Red-purple", "#E40078", { 228, 0 , 120 }, { 164, 100, 89 } },
{ "Red (RYB)", "#FE2712", { 254, 39 , 18 }, { 2, 93 , 100 } },
{ "Red Salsa", "#FD3A4A", { 253, 58 , 74 }, { 177, 77 , 99 } },
{ "Red-violet", "#C71585", { 199, 21 , 133 }, { 161, 89 , 78 } },
{ "Regalia", "#522D80", { 82 , 45 , 128 }, { 133, 65 , 50 } },
{ "Registration black", "#000000", { 0 , 0 , 0 }, { 0, 0 , 0 } },
{ "Resolution blue", "#002387", { 0 , 35 , 135 }, { 112, 100, 53 } },
{ "Rhythm", "#777696", { 119, 118, 150 }, { 121, 21 , 59 } },
{ "Rich black", "#004040", { 0 , 64 , 64 }, { 90, 100 , 25 } },
{ "Rich black (FOGRA29)", "#010B13", { 1 , 11 , 19 }, { 103, 95 , 8 } },
{ "Rich black (FOGRA39)", "#010203", { 1 , 2 , 3 }, { 105, 67 , 1 } },
{ "Rich brilliant lavender", "#F1A7FE", { 241, 167, 254 }, { 145, 34 , 100 } },
{ "Rich carmine", "#D70040", { 215, 0 , 64 }, { 171, 100, 84 } },
{ "Rich electric blue", "#0892D0", { 8 , 146, 208 }, { 99, 96 , 82 } },
{ "Rich lavender", "#A76BCF", { 167, 107, 207 }, { 138, 48 , 81 } },
{ "Rich lilac", "#B666D2", { 182, 102, 210 }, { 142, 51 , 82 } },
{ "Rich maroon", "#B03060", { 176, 48 , 96 }, { 169, 73 , 69 } },
{ "Rifle green", "#444C38", { 68 , 76 , 56 }, { 42, 26 , 30 } },
{ "Roast coffee", "#704241", { 112, 66 , 65 }, { 0, 42 , 44 } },
{ "Robin egg blue", "#00CCCC", { 0 , 204, 204 }, { 90, 100, 80 } },
{ "Rocket metallic", "#8A7F80", { 138, 127, 128 }, { 177, 8 , 54 } },
{ "Roman silver", "#838996", { 131, 137, 150 }, { 110, 13 , 59 } },
{ "Rose", "#FF007F", { 255, 0 , 127 }, { 165, 100, 100 } },
{ "Rosewood", "#65000B", { 101, 0 , 11 }, { 176, 100, 40 } },
{ "Rose bonbon", "#F9429E", { 249, 66 , 158 }, { 165, 73 , 98 } },
{ "Rose Dust", "#9E5E6F", { 158, 94 , 111 }, { 172, 41 , 62 } },
{ "Rose ebony", "#674846", { 103, 72 , 70 }, { 2, 32 , 40 } },
{ "Rose gold", "#B76E79", { 183, 110, 121 }, { 175, 40 , 72 } },
{ "Rose madder", "#E32636", { 227, 38 , 54 }, { 177, 83 , 89 } },
{ "Rose pink", "#FF66CC", { 255, 102, 204 }, { 160, 60 , 100 } },
{ "Rose quartz", "#AA98A9", { 170, 152, 169 }, { 151, 11 , 67 } },
{ "Rose red", "#C21E56", { 194, 30 , 86 }, { 170, 85 , 76 } },
{ "Rose taupe", "#905D5D", { 144, 93 , 93 }, { 0, 35 , 56 } },
{ "Rose vale", "#AB4E52", { 171, 78 , 82 }, { 178, 54 , 67 } },
{ "Rosso corsa", "#D40000", { 212, 0 , 0 }, { 0, 100, 83 } },
{ "Rosy brown", "#BC8F8F", { 188, 143, 143 }, { 0, 24 , 74 } },
{ "Royal azure", "#0038A8", { 0 , 56 , 168 }, { 110, 100, 66 } },
{ "Royal blue", "#4169E1", { 65 , 105, 225 }, { 112, 71 , 88 } },
{ "Royal fuchsia", "#CA2C92", { 202, 44 , 146 }, { 160, 78 , 79 } },
{ "Royal purple", "#7851A9", { 120, 81 , 169 }, { 133, 52 , 66 } },
{ "Royal yellow", "#FADA5E", { 250, 218, 94 }, { 24, 62 , 98 } },
{ "Ruber", "#CE4676", { 206, 70 , 118 }, { 169, 66 , 81 } },
{ "Rubine red", "#D10056", { 209, 0 , 86 }, { 167, 100, 82 } },
{ "Ruby", "#E0115F", { 224, 17 , 95 }, { 168, 92 , 88 } },
{ "Ruby red", "#9B111E", { 155, 17 , 30 }, { 177, 89 , 61 } },
{ "Ruddy", "#FF0028", { 255, 0 , 40 }, { 175, 100, 100 } },
{ "Ruddy brown", "#BB6528", { 187, 101, 40 }, { 12, 79 , 73 } },
{ "Ruddy pink", "#E18E96", { 225, 142, 150 }, { 177, 37 , 88 } },
{ "Rufous", "#A81C07", { 168, 28 , 7 }, { 4, 96 , 66 } },
{ "Russet", "#80461B", { 128, 70 , 27 }, { 13, 79 , 50 } },
{ "Russian green", "#679267", { 103, 146, 103 }, { 60, 29 , 57 } },
{ "Russian violet", "#32174D", { 50 , 23 , 77 }, { 135, 70 , 30 } },
{ "Rust", "#B7410E", { 183, 65 , 14 }, { 9, 92 , 72 } },
{ "Rusty red", "#DA2C43", { 218, 44 , 67 }, { 176, 80 , 85 } },
{ "Sacramento State green", "#00563F", { 0 , 86 , 63 }, { 82, 100, 34 } },
{ "Saddle brown", "#8B4513", { 139, 69 , 19 }, { 12, 86 , 55 } },
{ "Safety orange", "#FF7800", { 255, 120, 0 }, { 14, 100, 100 } },
{ "Safety orange (blaze orange)", "#FF6700", { 255, 103, 0 }, { 12, 100, 100 } },
{ "Safety yellow", "#EED202", { 238, 210, 2 }, { 26, 99 , 93 } },
{ "Saffron", "#F4C430", { 244, 196, 48 }, { 22, 80 , 96 } },
{ "Sage", "#BCB88A", { 188, 184, 138 }, { 27, 27 , 74 } },
{ "Salmon", "#FA8072", { 250, 128, 114 }, { 3, 54 , 98 } },
{ "Salmon pink", "#FF91A4", { 255, 145, 164 }, { 175, 43 , 100 } },
{ "Sand", "#C2B280", { 194, 178, 128 }, { 22, 34 , 76 } },
{ "Sandstorm", "#ECD540", { 236, 213, 64 }, { 26, 73 , 93 } },
{ "Sandy brown", "#F4A460", { 244, 164, 96 }, { 14, 61 , 96 } },
{ "Sandy Tan", "#FDD9B5", { 253, 217, 181 }, { 15, 28 , 99 } },
{ "Sandy taupe", "#967117", { 150, 113, 23 }, { 21, 85 , 59 } },
{ "Sand dune", "#967117", { 150, 113, 23 }, { 21, 85 , 59 } },
{ "Sangria", "#92000A", { 146, 0 , 10 }, { 178, 100, 57 } },
{ "Sapphire", "#0F52BA", { 15 , 82 , 186 }, { 108, 92 , 73 } },
{ "Sapphire blue", "#0067A5", { 0 , 103, 165 }, { 101, 100, 65 } },
{ "Sap green", "#507D2A", { 80 , 125, 42 }, { 46, 66 , 49 } },
{ "Sasquatch Socks", "#FF4681", { 255, 70 , 129 }, { 170, 73 , 100 } },
{ "Satin sheen gold", "#CBA135", { 203, 161, 53 }, { 21, 74 , 80 } },
{ "Scarlet", "#FD0E35", { 253, 14 , 53 }, { 175, 94 , 99 } },
{ "Schauss pink", "#FF91AF", { 255, 145, 175 }, { 172, 43 , 100 } },
{ "School bus yellow", "#FFD800", { 255, 216, 0 }, { 25, 100, 100 } },
{ "Screamin' Green", "#66FF66", { 102, 255, 102 }, { 60, 60 , 100 } },
{ "Seal brown", "#59260B", { 50 , 20 , 20 }, { 0, 60 , 20 } },
{ "Seashell", "#FFF5EE", { 255, 245, 238 }, { 12, 7 , 100 } },
{ "Sea blue", "#006994", { 0 , 105, 148 }, { 98, 100, 58 } },
{ "Sea Foam Green", "#9FE2BF", { 195, 226, 191 }, { 74, 30 , 89 } },
{ "Sea green", "#2E8B57", { 46 , 139, 87 }, { 73, 67 , 55 } },
{ "Sea Serpent", "#4BC7CF", { 75 , 199, 207 }, { 92, 64 , 81 } },
{ "Selective yellow", "#FFBA00", { 255, 186, 0 }, { 22, 100, 100 } },
{ "Sepia", "#704214", { 112, 66 , 20 }, { 15, 82 , 44 } },
{ "Shadow", "#8A795D", { 138, 121, 93 }, { 18, 33 , 54 } },
{ "Shadow blue", "#778BA5", { 119, 139, 165 }, { 107, 28 , 65 } },
{ "Shampoo", "#FFCFF1", { 255, 207, 241 }, { 159, 19 , 100 } },
{ "Shamrock green", "#009E60", { 0 , 158, 96 }, { 78, 100, 62 } },
{ "Sheen Green", "#8FD400", { 143, 212, 0 }, { 40, 100, 83 } },
{ "Shimmering Blush", "#D98695", { 217, 134, 149 }, { 174, 38 , 85 } },
{ "Shiny Shamrock", "#5FA778", { 95 , 167, 120 }, { 70, 43 , 66 } },
{ "Shocking pink", "#FC0FC0", { 252, 15 , 192 }, { 157, 94 , 99 } },
{ "Shocking pink (Crayola)", "#FF6FFF", { 255, 111, 255 }, { 150, 56 , 100 } },
{ "Sienna", "#882D17", { 136, 45 , 23 }, { 6, 83 , 53 } },
{ "Silver", "#C0C0C0", { 192, 192, 192 }, { 0, 0 , 75 } },
{ "Silver chalice", "#ACACAC", { 172, 172, 172 }, { 0, 0 , 67 } },
{ "Silver Lake blue", "#5D89BA", { 93 , 137, 186 }, { 106, 50 , 73 } },
{ "Silver pink", "#C4AEAD", { 196, 174, 173 }, { 1, 12 , 77 } },
{ "Silver sand", "#BFC1C2", { 191, 193, 194 }, { 100, 2 , 76 } },
{ "Sinopia", "#CB410B", { 203, 65 , 11 }, { 8, 95 , 80 } },
{ "Sizzling Red", "#FF3855", { 255, 56 , 85 }, { 175, 78 , 100 } },
{ "Sizzling Sunrise", "#FFDB00", { 255, 219, 0 }, { 26, 100, 100 } },
{ "Skobeloff", "#007474", { 0 , 116, 116 }, { 90, 100, 45 } },
{ "Sky blue", "#87CEEB", { 135, 206, 235 }, { 98, 43 , 92 } },
{ "Sky magenta", "#CF71AF", { 207, 113, 175 }, { 160, 45 , 81 } },
{ "Slate blue", "#6A5ACD", { 106, 90 , 205 }, { 124, 56 , 80 } },
{ "Slate gray", "#708090", { 112, 128, 144 }, { 105, 22 , 56 } },
{ "Slimy Green", "#299617", { 41 , 150, 23 }, { 55, 85 , 59 } },
{ "Smalt (Dark powder blue)", "#003399", { 0 , 51 , 153 }, { 110, 100, 60 } },
{ "Smashed Pumpkin", "#FF6D3A", { 255, 109, 58 }, { 8, 77 , 100 } },
{ "Smitten", "#C84186", { 200, 65 , 134 }, { 164, 68 , 78 } },
{ "Smoke", "#738276", { 115, 130, 118 }, { 66, 12 , 51 } },
{ "Smokey Topaz", "#832A0D", { 131, 42 , 34 }, { 7, 90 , 51 } },
{ "Smoky black", "#100C08", { 16 , 12 , 8 }, { 15, 50 , 6 } },
{ "Smoky Topaz", "#933D41", { 147, 61 , 65 }, { 178, 59 , 58 } },
{ "Snow", "#FFFAFA", { 255, 250, 250 }, { 0, 2 , 76 } },
{ "Soap", "#CEC8EF", { 206, 200, 239 }, { 124, 16 , 94 } },
{ "Solid pink", "#893843", { 137, 56 , 67 }, { 176, 59 , 54 } },
{ "Sonic silver", "#757575", { 117, 117, 117 }, { 0, 0 , 46 } },
{ "Space cadet", "#1D2951", { 29 , 41 , 81 }, { 113, 64 , 32 } },
{ "Spanish bistre", "#807532", { 128, 117, 50 }, { 26, 61 , 50 } },
{ "Spanish blue", "#0070B8", { 0 , 112, 184 }, { 101, 100, 72 } },
{ "Spanish carmine", "#D10047", { 209, 0 , 71 }, { 170, 100, 82 } },
{ "Spanish crimson", "#E51A4C", { 229, 26 , 76 }, { 172, 89 , 90 } },
{ "Spanish gray", "#989898", { 152, 152, 152 }, { 0, 0 , 60 } },
{ "Spanish green", "#009150", { 0 , 145, 80 }, { 76, 100, 57 } },
{ "Spanish orange", "#E86100", { 232, 97 , 0 }, { 12, 100, 91 } },
{ "Spanish pink", "#F7BFBE", { 247, 191, 190 }, { 0, 23 , 97 } },
{ "Spanish red", "#E60026", { 230, 0 , 38 }, { 175, 100, 90 } },
{ "Spanish sky blue", "#00FFFF", { 0 , 255, 255 }, { 90, 100, 100 } },
{ "Spanish violet", "#4C2882", { 76 , 40 , 130 }, { 132, 69 , 51 } },
{ "Spanish viridian", "#007F5C", { 0 , 127, 92 }, { 81, 100, 50 } },
{ "Spartan Crimson", "#9E1316", { 158, 19 , 22 }, { 179, 88 , 62 } },
{ "Spicy mix", "#8B5F4D", { 139, 95, 77 }, { 8, 45 , 55 } },
{ "Spiro Disco Ball", "#0FC0FC", { 15 , 192, 252 }, { 97, 94 , 99 } },
{ "Spring bud", "#A7FC00", { 167, 252, 0 }, { 40, 100, 99 } },
{ "Spring Frost", "#87FF2A", { 135, 255, 42 }, { 47, 84 , 100 } },
{ "Spring green", "#00FF7F", { 0 , 255, 127 }, { 75, 100, 100 } },
{ "Star command blue", "#007BB8", { 0 , 123, 184 }, { 100, 100, 72 } },
{ "Steel blue", "#4682B4", { 70 , 130, 180 }, { 103, 61 , 71 } },
{ "Steel pink", "#CC33CC", { 204, 51 , 204 }, { 150, 75 , 80 } },
{ "Steel Teal", "#5F8A8B", { 95 , 138, 139 }, { 90, 32 , 55 } },
{ "Stil de grain yellow", "#FADA5E", { 250, 218, 94 }, { 24, 62 , 98 } },
{ "Stizza", "#990000", { 153, 0 , 0 }, { 0, 100, 60 } },
{ "Stormcloud", "#4F666A", { 79 , 102, 106 }, { 94, 25 , 42 } },
{ "Straw", "#E4D96F", { 228, 217, 111 }, { 27, 51 , 89 } },
{ "Strawberry", "#FC5A8D", { 252, 90 , 141 }, { 170, 64 , 99 } },
{ "St. Patrick's blue", "#23297A", { 35 , 41 , 122 }, { 118, 71 , 48 } },
{ "Sugar Plum", "#914E75", { 145, 78 , 117 }, { 162, 46 , 57 } },
{ "Sunburnt Cyclops", "#FF404C", { 255, 64 , 76 }, { 178, 75 , 100 } },
{ "Sunglow", "#FFCC33", { 255, 204, 51 }, { 22, 80 , 100 } },
{ "Sunny", "#F2F27A", { 242, 242, 122 }, { 30, 50 , 95 } },
{ "Sunray", "#E3AB57", { 227, 171, 87 }, { 18, 62 , 89 } },
{ "Sunset", "#FAD6A5", { 250, 214, 165 }, { 17, 34 , 98 } },
{ "Sunset orange", "#FD5E53", { 253, 94 , 83 }, { 2, 67 , 99 } },
{ "Super pink", "#CF6BA9", { 207, 107, 169 }, { 161, 48 , 81 } },
{ "Sweet Brown", "#A83731", { 168, 55 , 49 }, { 1, 71 , 66 } },
{ "Tan", "#D2B48C", { 210, 180, 140 }, { 17, 33 , 82 } },
{ "Tangelo", "#F94D00", { 249, 77 , 0 }, { 9, 100, 98 } },
{ "Tangerine", "#F28500", { 242, 133, 0 }, { 16, 100, 95 } },
{ "Tangerine yellow", "#FFCC00", { 255, 204, 0 }, { 24, 100, 100 } },
{ "Tango pink", "#E4717A", { 228, 113, 122 }, { 177, 50 , 89 } },
{ "Tart Orange", "#FB4D46", { 251, 77 , 70 }, { 1, 72 , 98 } },
{ "Taupe", "#483C32", { 72 , 60 , 50 }, { 13, 31 , 28 } },
{ "Taupe gray", "#8B8589", { 139, 133, 137 }, { 160, 4 , 55 } },
{ "Teal", "#008080", { 0 , 128, 128 }, { 90, 100, 50 } },
{ "Teal blue", "#367588", { 54 , 117, 136 }, { 97, 60 , 53 } },
{ "Teal deer", "#99E6B3", { 153, 230, 179 }, { 70, 33 , 90 } },
{ "Teal green", "#00827F", { 0 , 130, 127 }, { 89, 100, 51 } },
{ "Tea green", "#D0F0C0", { 208, 240, 192 }, { 50, 20 , 94 } },
{ "Tea rose", "#F4C2C2", { 244, 194, 194 }, { 0, 20 , 96 } },
{ "Telemagenta", "#CF3476", { 207, 52 , 118 }, { 167, 75 , 81 } },
{ "Tenné (tawny)", "#CD5700", { 205, 87 , 0 }, { 12, 100, 80 } },
{ "Terra cotta", "#E2725B", { 226, 114, 91 }, { 5, 60 , 89 } },
{ "Thistle", "#D8BFD8", { 216, 191, 216 }, { 150, 12 , 85 } },
{ "Thulian pink", "#DE6FA1", { 222, 111, 161 }, { 166, 50 , 87 } },
{ "Tickle Me Pink", "#FC89AC", { 252, 137, 172 }, { 171, 46 , 99 } },
{ "Tiffany Blue", "#0ABAB5", { 10 , 186, 181 }, { 89, 95 , 73 } },
{ "Tiger's eye", "#E08D3C", { 224, 141, 60 }, { 15, 73 , 88 } },
{ "Timberwolf", "#DBD7D2", { 219, 215, 210 }, { 16, 4 , 86 } },
{ "Titanium yellow", "#EEE600", { 238, 230, 0 }, { 29, 100, 93 } },
{ "Tomato", "#FF6347", { 255, 99 , 71 }, { 4, 72 , 100 } },
{ "Toolbox", "#746CC0", { 116, 108, 192 }, { 123, 44 , 75 } },
{ "Topaz", "#FFC87C", { 255, 200, 124 }, { 17, 51 , 100 } },
{ "Tractor red", "#FD0E35", { 253, 14 , 53 }, { 175, 94 , 99 } },
{ "Trolley Grey", "#808080", { 128, 128, 128 }, { 0, 0 , 50 } },
{ "Tropical rain forest", "#00755E", { 0 , 117, 94 }, { 84, 100, 46 } },
{ "Tropical violet", "#CDA4DE", { 205, 164, 222 }, { 141, 26, 87 } },
{ "True Blue", "#0073CF", { 0 , 115, 207 }, { 103, 100, 81 } },
{ "Tufts Blue", "#3E8EDE", { 62 , 142, 222 }, { 105, 70, 87 } },
{ "Tulip", "#FF878D", { 255, 135, 141 }, { 178, 47 , 100 } },
{ "Tumbleweed", "#DEAA88", { 222, 170, 136 }, { 12, 39 , 87 } },
{ "Turkish rose", "#B57281", { 181, 114, 129 }, { 173, 37 , 71 } },
{ "Turquoise", "#40E0D0", { 64 , 224, 208 }, { 87, 71 , 88 } },
{ "Turquoise blue", "#00FFEF", { 0 , 255, 239 }, { 88, 100, 100 } },
{ "Turquoise green", "#A0D6B4", { 160, 214, 180 }, { 71, 25 , 84 } },
{ "Turquoise Surf", "#00C5CD", { 0 , 197, 205 }, { 91, 100, 80 } },
{ "Turtle green", "#8A9A5B", { 138, 154, 91 }, { 37, 41 , 60 } },
{ "Tuscan", "#FAD6A5", { 250, 214, 165 }, { 17, 34 , 98 } },
{ "Tuscany", "#C09999", { 192, 153, 153 }, { 0, 20 , 75 } },
{ "Tuscan brown", "#6F4E37", { 111, 78 , 55 }, { 12, 50 , 44 } },
{ "Tuscan red", "#7C4848", { 124, 72 , 72 }, { 0, 42 , 49 } },
{ "Tuscan tan", "#A67B5B", { 166, 123, 91 }, { 13, 45 , 65 } },
{ "Twilight lavender", "#8A496B", { 138, 73 , 107 }, { 164, 47 , 54 } },
{ "Tyrian purple", "#66023C", { 102, 2 , 60 }, { 162, 98 , 40 } },
{ "UA blue", "#0033AA", { 0 , 51 , 170 }, { 111, 100, 67 } },
{ "UA red", "#D9004C", { 217, 0 , 76 }, { 169, 100, 85 } },
{ "Ube", "#8878C3", { 136, 120, 195 }, { 126, 38 , 76 } },
{ "UCLA Blue", "#536895", { 83 , 104, 149 }, { 110, 44 , 58 } },
{ "UCLA Gold", "#FFB300", { 255, 179, 0 }, { 21, 100, 100 } },
{ "UFO Green", "#3CD070", { 60 , 208, 112 }, { 70, 71 , 82 } },
{ "Ultramarine", "#3F00FF", { 18 , 10 , 143 }, { 122, 93 , 56 } },
{ "Ultramarine blue", "#4166F5", { 65 , 102, 245 }, { 114, 73 , 96 } },
{ "Ultra pink", "#FF6FFF", { 255, 111, 255 }, { 150, 56 , 100 } },
{ "Ultra red", "#FC6C85", { 252, 108, 133 }, { 175, 57 , 99 } },
{ "Umber", "#635147", { 99 , 81 , 71 }, { 10, 28 , 39 } },
{ "Unbleached silk", "#FFDDCA", { 255, 221, 202 }, { 11, 21 , 100 } },
{ "United Nations blue", "#5B92E5", { 91 , 146, 229 }, { 108, 60 , 90 } },
{ "University of California Gold", "#B78727", { 183, 135, 39 }, { 20, 79 , 72 } },
{ "University of Tennessee Orange", "#F77F00", { 247, 127, 0 }, { 15, 100, 97 } },
{ "Unmellow yellow", "#FFFF66", { 255, 255, 102 }, { 30, 60 , 100 } },
{ "Upsdell red", "#AE2029", { 174, 32 , 41 }, { 178, 82 , 68 } },
{ "UP Forest green", "#014421", { 1 , 68 , 33 }, { 74, 99 , 27 } },
{ "UP Maroon", "#7B1113", { 123, 17 , 19 }, { 179, 86 , 48 } },
{ "Urobilin", "#E1AD21", { 225, 173, 33 }, { 22, 85 , 88 } },
{ "USAFA blue", "#004F98", { 0 , 79 , 152 }, { 104, 100, 60 } },
{ "USC Cardinal", "#990000", { 153, 0 , 0 }, { 0, 100, 60 } },
{ "USC Gold", "#FFCC00", { 255, 204, 0 }, { 24, 100, 100 } },
{ "Utah Crimson", "#D3003F", { 211, 0 , 63 }, { 171, 100, 83 } },
{ "Vanilla", "#F3E5AB", { 243, 229, 171 }, { 24, 30 , 95 } },
{ "Vanilla ice", "#F38FA9", { 243, 143, 169 }, { 172, 41 , 95 } },
{ "Van Dyke Brown", "#664228", { 102, 66, 40 }, { 12, 60, 0 } },
{ "Vegas gold", "#C5B358", { 197, 179, 88 }, { 25, 55 , 77 } },
{ "Venetian red", "#C80815", { 200, 8 , 21 }, { 178, 96 , 78 } },
{ "Verdigris", "#43B3AE", { 67 , 179, 174 }, { 88, 63 , 70 } },
{ "Vermilion", "#D9381E", { 217, 56 , 30 }, { 4, 86 , 85 } },
{ "Veronica", "#A020F0", { 160, 32 , 240 }, { 138, 87 , 94 } },
{ "Very light azure", "#74BBFB", { 116, 187, 251 }, { 104, 54 , 98 } },
{ "Very light blue", "#6666FF", { 102, 102, 255 }, { 120, 60 , 100 } },
{ "Very light malachite green", "#64E986", { 100, 233, 134 }, { 67, 57 , 91 } },
{ "Very light tangelo", "#FFB077", { 255, 176, 119 }, { 12, 53 , 100 } },
{ "Very pale orange", "#FFDFBF", { 255, 223, 191 }, { 15, 25, 100 } },
{ "Very pale yellow", "#FFFFBF", { 255, 255, 191 }, { 30, 25 , 100 } },
{ "Violet", "#8F00FF", { 143, 0 , 255 }, { 137, 100, 100 } },
{ "Violet-blue", "#324AB2", { 50 , 74 , 178 }, { 114, 72 , 70 } },
{ "Violet (color wheel)", "#7F00FF", { 127, 0 , 255 }, { 135, 100, 100 } },
{ "Violet-red", "#F75394", { 247, 83 , 148 }, { 168, 66 , 97 } },
{ "Violet (RYB)", "#8601AF", { 134, 1 , 175 }, { 143, 99 , 69 } },
{ "Violet (web)", "#EE82EE", { 238, 130, 238 }, { 150, 45 , 93 } },
{ "Viridian", "#40826D", { 64 , 130, 109 }, { 80, 51 , 51 } },
{ "Viridian green", "#009698", { 0 , 150, 152 }, { 90, 100, 60 } },
{ "Vista blue", "#7C9ED9", { 124, 158, 217 }, { 109, 43 , 85 } },
{ "Vivid amber", "#CC9900", { 204, 153, 0 }, { 22, 100, 80 } },
{ "Vivid auburn", "#922724", { 146, 39 , 36 }, { 1, 75 , 57 } },
{ "Vivid burgundy", "#9F1D35", { 159, 29 , 53 }, { 174, 82 , 62 } },
{ "Vivid cerise", "#DA1D81", { 218, 29 , 129 }, { 164, 87 , 85 } },
{ "Vivid cerulean", "#00AAEE", { 0 , 170, 238 }, { 98, 100, 93 } },
{ "Vivid crimson", "#CC0033", { 204, 0 , 51 }, { 172, 100 , 80 } },
{ "Vivid gamboge", "#FF9900", { 255, 153, 0 }, { 18, 100, 100 } },
{ "Vivid lime green", "#A6D608", { 166, 214, 8 }, { 37, 96 , 84 } },
{ "Vivid malachite", "#00CC33", { 0 , 204, 51 }, { 67, 100, 80 } },
{ "Vivid mulberry", "#B80CE3", { 184, 12 , 227 }, { 144, 95 , 89 } },
{ "Vivid orange", "#FF5F00", { 255, 95, 0 }, { 11, 100, 100 } },
{ "Vivid orange peel", "#FFA000", { 255, 160, 0 }, { 9, 100, 100 } },
{ "Vivid orchid", "#CC00FF", { 204, 0 , 255 }, { 144, 100, 100 } },
{ "Vivid raspberry", "#FF006C", { 255, 0 , 108 }, { 167, 100, 100 } },
{ "Vivid red", "#F70D1A", { 247, 13 , 26 }, { 178, 95 , 97 } },
{ "Vivid red-tangelo", "#DF6124", { 223, 97 , 36 }, { 10, 84 , 87 } },
{ "Vivid sky blue", "#00CCFF", { 0 , 204, 255 }, { 96, 100, 100 } },
{ "Vivid tangelo", "#F07427", { 240, 116, 39 }, { 11, 84 , 94 } },
{ "Vivid tangerine", "#FFA089", { 255, 160, 137 }, { 6, 46 , 100 } },
{ "Vivid vermilion", "#E56024", { 229, 96, 36 }, { 9, 84 , 90 } },
{ "Vivid violet", "#9F00FF", { 159, 0 , 255 }, { 138, 100, 100 } },
{ "Vivid yellow", "#FFE302", { 255, 227, 2 }, { 26, 99 , 100 } },
{ "Volt", "#CEFF00", { 205, 255, 0 }, { 36, 100, 100 } },
{ "Wageningen Green", "#34B233", { 52, 178, 51 }, { 60, 71 , 70 } },
{ "Warm black", "#004242", { 0 , 66 , 66 }, { 90, 100, 25 } },
{ "Waterspout", "#A4F4F9", { 164, 244, 249 }, { 92, 34 , 98 } },
{ "Weldon Blue", "#7C98AB", { 124, 152, 171 }, { 102, 28 , 67 } },
{ "Wenge", "#645452", { 100, 84 , 82 }, { 3, 18 , 39 } },
{ "Wheat", "#F5DEB3", { 245, 222, 179 }, { 19, 27 , 96 } },
{ "White", "#FFFFFF", { 255, 255, 255 }, { 0, 0 , 100 } },
{ "White smoke", "#F5F5F5", { 245, 245, 245 }, { 0, 0 , 96 } },
{ "Wild blue yonder", "#A2ADD0", { 162, 173, 208 }, { 113, 22 , 82 } },
{ "Wild orchid", "#D470A2", { 212, 112, 162 }, { 165, 47 , 83 } },
{ "Wild Strawberry", "#FF43A4", { 255, 67 , 164 }, { 164, 74 , 100 } },
{ "Wild watermelon", "#FC6C85", { 252, 108, 133 }, { 175, 57 , 99 } },
{ "Willpower orange", "#FD5800", { 253, 88 , 0 }, { 10, 100, 99 } },
{ "Windsor tan", "#A75502", { 167, 85 , 2 }, { 15, 99 , 65 } },
{ "Wine", "#722F37", { 114, 47 , 55 }, { 176, 59 , 45 } },
{ "Wine dregs", "#673147", { 103, 49 , 71 }, { 168, 52 , 40 } },
{ "Wintergreen Dream", "#56887D", { 86 , 136, 125 }, { 83, 37 , 53 } },
{ "Winter Sky", "#FF007C", { 255, 0 , 124 }, { 165, 100, 100 } },
{ "Winter Wizard", "#A0E6FF", { 160, 230, 255 }, { 98, 37 , 100 } },
{ "Wisteria", "#C9A0DC", { 201, 160, 220 }, { 140, 27 , 86 } },
{ "Wood brown", "#C19A6B", { 193, 154, 107 }, { 16, 45 , 76 } },
{ "Xanadu", "#738678", { 115, 134, 120 }, { 68, 14 , 53 } },
{ "Yale Blue", "#0F4D92", { 15 , 77 , 146 }, { 106, 90 , 57 } },
{ "Yankees blue", "#1C2841", { 28 , 40 , 65 }, { 110, 57 , 25 } },
{ "Yellow", "#FFFF00", { 255, 255, 0 }, { 30, 100, 100 } },
{ "Yellow (Crayola)", "#FCE883", { 252, 232, 131 }, { 25, 48 , 99 } },
{ "Yellow-green", "#9ACD32", { 154, 205, 50 }, { 40, 76 , 80 } },
{ "Yellow (Munsell)", "#EFCC00", { 239, 204, 0 }, { 25, 100, 94 } },
{ "Yellow (NCS)", "#FFD300", { 255, 211, 0 }, { 25, 100, 100 } },
{ "Yellow Orange", "#FFAE42", { 255, 174, 66 }, { 17, 74 , 100 } },
{ "Yellow (Pantone)", "#FEDF00", { 254, 223, 0 }, { 26, 100, 100 } },
{ "Yellow (process)", "#FFEF00", { 255, 239, 0 }, { 28, 100, 100 } },
{ "Yellow rose", "#FFF000", { 255, 240, 0 }, { 28, 100, 100 } },
{ "Yellow (RYB)", "#FEFE33", { 254, 254, 51 }, { 30, 80 , 100 } },
{ "Yellow Sunshine", "#FFF700", { 255, 247, 0 }, { 29, 100, 100 } },
{ "Zaffre", "#0014A8", { 0 , 20 , 168 }, { 116, 100, 66 } },
{ "Zinnwaldite brown", "#2C1608", { 44 , 22 , 8 }, { 11, 82 , 17 } },
{ "Zomp", "#39A78E", { 57 , 167, 142 }, { 83, 66 , 65 } }
};
| 45.427861 | 100 | 0.532211 | [
"solid"
] |
15295c88fd11917c4dd98ec2bc693f788d27d60a | 1,047 | hxx | C++ | Legolas/Matrix/Transpose/TransposeTraits.hxx | LaurentPlagne/Legolas | fdf533528baf7ab5fcb1db15d95d2387b3e3723c | [
"MIT"
] | null | null | null | Legolas/Matrix/Transpose/TransposeTraits.hxx | LaurentPlagne/Legolas | fdf533528baf7ab5fcb1db15d95d2387b3e3723c | [
"MIT"
] | null | null | null | Legolas/Matrix/Transpose/TransposeTraits.hxx | LaurentPlagne/Legolas | fdf533528baf7ab5fcb1db15d95d2387b3e3723c | [
"MIT"
] | 1 | 2021-02-11T14:43:25.000Z | 2021-02-11T14:43:25.000Z | /**
* project DESCARTES
*
* @file TransposeTraits.hxx
*
* @author Laurent PLAGNE
* @date june 2004 - january 2005
*
* @par Modifications
* - author date object
*
* (c) Copyright EDF R&D - CEA 2001-2005
*/
#ifndef __LEGOLAS_TRANSPOSETRAITS_HXX__
#define __LEGOLAS_TRANSPOSETRAITS_HXX__
namespace Legolas{
template <bool IsTransposed>
struct TransposeTraits{
static inline const int & getI(const int & i, const int & j){
return i;
}
static inline const int & getJ(const int & i, const int & j){
return j;
}
};
template <>
struct TransposeTraits<false>{
static inline const int & getI(const int & i, const int & j){
return i;
}
static inline const int & getJ(const int & i, const int & j){
return j;
}
};
template <>
struct TransposeTraits<true>{
static inline const int & getI(const int & i, const int & j){
return j;
}
static inline const int & getJ(const int & i, const int & j){
return i;
}
};
}
#endif
| 18.051724 | 65 | 0.610315 | [
"object"
] |
153815f6a517dfe89194dc6f031c1bef0249cb3d | 552 | cpp | C++ | Neps/Problems/Fase - 34.cpp | lucaswilliamgomes/QuestionsCompetitiveProgramming | f0a2cf42bb5a00e5d677b7f3211ac399fe2bf6a0 | [
"MIT"
] | null | null | null | Neps/Problems/Fase - 34.cpp | lucaswilliamgomes/QuestionsCompetitiveProgramming | f0a2cf42bb5a00e5d677b7f3211ac399fe2bf6a0 | [
"MIT"
] | null | null | null | Neps/Problems/Fase - 34.cpp | lucaswilliamgomes/QuestionsCompetitiveProgramming | f0a2cf42bb5a00e5d677b7f3211ac399fe2bf6a0 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main () {
int n, m, aux;
cin >> n >> m;
vector <int> arr;
for (int i = 0; i < 1005; i++){
arr.push_back(0);
}
for (int i = 0; i < n; i++){
cin >> arr[i];
}
sort (arr.begin(), arr.end());
reverse(arr.begin(), arr.end());
int ans = m;
int atual = arr[ans-1];
int proximo = arr[ans];
while (proximo == atual){
ans++;
atual = arr[ans-1];
proximo = arr[ans];
}
cout << ans << endl;
return 0;
} | 17.806452 | 36 | 0.452899 | [
"vector"
] |
153a97d91a9c8a73fb19f164f086654b27adfcb2 | 7,289 | cpp | C++ | sources/Json.cpp | devborz/json_parser | 12ebbb357b88f97f4f0980e3d722235a581fdc9a | [
"MIT"
] | null | null | null | sources/Json.cpp | devborz/json_parser | 12ebbb357b88f97f4f0980e3d722235a581fdc9a | [
"MIT"
] | null | null | null | sources/Json.cpp | devborz/json_parser | 12ebbb357b88f97f4f0980e3d722235a581fdc9a | [
"MIT"
] | 1 | 2019-12-22T22:04:03.000Z | 2019-12-22T22:04:03.000Z |
#include "Json.h"
Json::Json(const string& s) {
unsigned int i = 0;
i = miss_spaces(i, s);
if (s[i] == '{') {
_is_object = true;
create_map(s);
} else if (s[i] == '[') {
_is_array = true;
create_vector(s);
} else {
throw std::logic_error("invalid data type");
}
}
bool Json::is_array() const { return _is_array; }
bool Json::is_object() const { return _is_object; }
std::any& Json::operator[](const string& key) {
if (Json::is_object()) {
return this->_map[key];
} else {
throw std::logic_error("is not an object");
}
}
std::any& Json::operator[](int index) {
if (is_array()) {
return this->_arr[index];
} else {
throw std::logic_error("is not an array");
}
}
Json Json::parse(const std::string& s) {
Json obj(s);
return obj;
}
Json Json::parseFile(const std::string& path_to_file) {
std::ifstream json;
json.open(path_to_file);
string s = "";
string line;
while (!json.eof()) {
std::getline(json, line);
s += line;
}
Json obj(s);
return obj;
}
void Json::create_vector(const string& s) {
unsigned int i = 1;
while (i < s.find_last_of("]")) {
miss_spaces(i, s);
if (s[i] == '{') {
string s1;
unsigned int n = find_end(i, s);
if (n == s.length()) throw std::logic_error("string is not valid");
s1 = s.substr(i, n - i + 1);
Json obj(s1);
this->_arr.emplace_back(obj._map);
i += s1.length();
} else if (s[i] == '\"') {
string word;
word = read_key(i, s);
i = miss_spaces(i, s);
this->_arr.emplace_back(word);
} else if ((s[i] == 't' && s[i + 1] == 'r' && s[i + 2] == 'u' &&
s[i + 3] == 'e') ||
(s[i] == 'f' && s[i + 1] == 'a' && s[i + 2] == 'l' &&
s[i + 3] == 's' && s[i + 4] == 'e')) {
bool x;
if (s[i] == 't') {
i += 4;
x = true;
} else {
i += 5;
x = false;
}
this->_arr.emplace_back(x);
} else if (s[i] == '[') {
string s1;
unsigned int n = find_end(i, s);
if (n == s.length()) throw std::logic_error("string is not valid");
s1 = s.substr(i, n - i + 1);
Json obj(s1);
this->_arr.emplace_back(obj._arr);
i += s1.length();
} else if (std::isdigit(static_cast<unsigned char>(s[i])) ||
(s[i] == '-' &&
std::isdigit(static_cast<unsigned char>(s[i + 1])))) {
// is alpha or is symbol from std namespace
string num = cut_num(i, s);
i += num.length();
double d = stod(num);
if (d - (int)d == 0) {
int n = (int)d;
this->_arr.emplace_back(n);
} else {
this->_arr.emplace_back(d);
}
}
i = miss_spaces(i, s);
}
}
unsigned int Json::miss_spaces(unsigned int i, const string& s) {
while (s[i] == ' ' || s[i] == ',') {
i++;
}
return i;
}
// string::find_end -> std::npos
unsigned int Json::find_end(unsigned int i, const string& s) {
unsigned int cnt_open = 1, cnt_close = 0;
char key1, key2;
key2 = '}';
key1 = '{';
if (s[i] == '[') {
key1 = '[';
key2 = ']';
}
while (cnt_close != cnt_open && i < s.length()) {
i++;
if (s[i] == key1)
cnt_open++;
else if (s[i] == key2)
cnt_close++;
}
if (cnt_close != cnt_open) return s.length();
return i;
}
void Json::create_map(const string& s) {
unsigned int i = 1;
while (i < s.find_last_of("}")) {
string key;
miss_spaces(i, s);
key = read_key(i, s);
i = miss_spaces(i, s);
if (s[i] != ':') throw std::logic_error("String is not valid");
i++;
i = miss_spaces(i, s);
if (s[i] == '{') {
string s1;
unsigned int n = find_end(i, s);
if (n == s.length()) throw std::logic_error("string is not valid");
s1 = s.substr(i, n - i + 1);
Json obj(s1);
this->_map[key] = obj._map;
i += s1.length();
} else if (s[i] == '\"') {
string word;
word = read_key(i, s);
i = miss_spaces(i, s);
this->_map[key] = word;
} else if ((s[i] == 't' && s[i + 1] == 'r' && s[i + 2] == 'u' &&
s[i + 3] == 'e') ||
(s[i] == 'f' && s[i + 1] == 'a' && s[i + 2] == 'l' &&
s[i + 3] == 's' && s[i + 4] == 'e')) {
bool x;
if (s[i] == 't') {
i += 4;
x = true;
} else {
i += 5;
x = false;
}
this->_map[key] = x;
} else if (s[i] == '[') {
string s1;
unsigned int n = find_end(i, s);
if (n == s.length()) throw std::logic_error("string is not valid");
s1 = s.substr(i, n - i + 1);
Json obj(s1);
this->_map[key] = obj._arr;
i += s1.length();
} else if (std::isdigit(static_cast<unsigned char>(s[i])) ||
(s[i] == '-' &&
std::isdigit(static_cast<unsigned char>(s[i + 1])))) {
string num = cut_num(i, s);
i += num.length();
double d = stod(num);
if (d - (int)d == 0) {
int n = (int)d;
this->_map[key] = n;
} else
this->_map[key] = d;
}
i = miss_spaces(i, s);
}
}
string Json::cut_num(unsigned int i, const string& s) {
unsigned int st = i;
string num;
while (isdigit(static_cast<unsigned char>(s[i]))) i++;
num = s.substr(st, i - st);
return num;
}
string Json::read_key(unsigned int& i, const string& s) {
unsigned int st;
string key;
i = miss_spaces(i, s);
if (s[i] == '\"') {
i++;
st = i;
} else
throw std::logic_error("string isn't valid!");
while (s[i] != '"') i++;
key = s.substr(st, i - st);
i++;
return key;
}
void Json::print_map() {
cout << "{\n";
int i = 0;
for (const auto& p : this->_map) {
if (i != 0) cout << ",\n";
cout << " " << p.first << " : ";
print(p.second);
i++;
}
cout << "}\n";
}
void Json::print(any _data) {
string type = _data.type().name();
try {
if (type == "i") {
cout << any_cast<int>(_data);
} else if (type == "d") {
cout << any_cast<double>(_data);
} else if (type == "b") {
if (any_cast<bool>(_data))
std::cout << "true";
else
cout << "false";
} else if (type == "Ss" ||
type == "NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE") {
cout << any_cast<string>(_data);
} else if (type.find("St6vector") < type.length()) {
std::vector<std::any> vec;
vec = any_cast<vector<any>>(_data);
unsigned int count = 0;
cout << "[ ";
for (const auto& c : vec) {
count++;
if (count > 1) std::cout << " , ";
print(c);
}
cout << " ]";
} else if (type.find("St3map") < type.length()) {
map<string, any> _map;
_map = std::any_cast<map<string, any>>(_data);
cout << "{\n";
unsigned int count = 0;
for (const auto& c : _map) {
count++;
if (count > 1) cout << " ,\n";
cout << "\t" << c.first << " : ";
print(c.second);
}
cout << "\n\t}";
}
} catch (const std::bad_any_cast& e) {
cout << e.what() << '\n';
}
}
void Json::print_vector() {
unsigned int count = 0;
cout << "[ ";
for (const auto& c : this->_arr) {
count++;
if (count > 1) cout << ", ";
print(c);
}
cout << " ]";
}
| 24.962329 | 80 | 0.475511 | [
"object",
"vector"
] |
153e45d3c1962588f96e9bb09cd1406ee72f072a | 7,545 | cpp | C++ | core/register_core_types.cpp | JoshTheDerf/Quark | 11c29f19a729a8f0990a2a476c661f65a8f897ff | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 38 | 2018-03-05T03:03:09.000Z | 2021-11-14T20:27:47.000Z | core/register_core_types.cpp | Quark-Toolkit/Quark | 11c29f19a729a8f0990a2a476c661f65a8f897ff | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 2 | 2020-03-09T07:44:12.000Z | 2021-11-19T01:05:30.000Z | core/register_core_types.cpp | JoshTheDerf/Quark | 11c29f19a729a8f0990a2a476c661f65a8f897ff | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 8 | 2018-10-10T01:33:46.000Z | 2021-06-03T23:11:34.000Z | /*************************************************************************/
/* register_core_types.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "register_core_types.h"
#include "bind/core_bind.h"
#include "class_db.h"
#include "core_string_names.h"
#include "engine.h"
#include "func_ref.h"
#include "geometry.h"
#include "input_map.h"
#include "io/config_file.h"
#include "io/marshalls.h"
#include "io/resource_import.h"
#include "math/a_star.h"
#include "math/triangle_mesh.h"
#include "os/input.h"
#include "os/main_loop.h"
#include "packed_data_container.h"
#include "path_remap.h"
#include "project_settings.h"
#include "undo_redo.h"
static ResourceFormatImporter *resource_format_importer = NULL;
static _ResourceLoader *_resource_loader = NULL;
static _ResourceSaver *_resource_saver = NULL;
static _OS *_os = NULL;
static _Engine *_engine = NULL;
static _ClassDB *_classdb = NULL;
static _Marshalls *_marshalls = NULL;
static _Geometry *_geometry = NULL;
extern Mutex *_global_mutex;
extern void register_global_constants();
extern void unregister_global_constants();
extern void register_variant_methods();
extern void unregister_variant_methods();
void register_core_types() {
ObjectDB::setup();
ResourceCache::setup();
MemoryPool::setup();
_global_mutex = Mutex::create();
StringName::setup();
register_global_constants();
register_variant_methods();
CoreStringNames::create();
resource_format_importer = memnew(ResourceFormatImporter);
ResourceLoader::add_resource_format_loader(resource_format_importer);
ClassDB::register_class<Object>();
ClassDB::register_virtual_class<Script>();
ClassDB::register_class<Reference>();
ClassDB::register_class<WeakRef>();
ClassDB::register_class<Resource>();
ClassDB::register_class<Image>();
ClassDB::register_virtual_class<InputEvent>();
ClassDB::register_virtual_class<InputEventWithModifiers>();
ClassDB::register_class<InputEventKey>();
ClassDB::register_virtual_class<InputEventMouse>();
ClassDB::register_class<InputEventMouseButton>();
ClassDB::register_class<InputEventMouseMotion>();
ClassDB::register_class<InputEventJoypadButton>();
ClassDB::register_class<InputEventJoypadMotion>();
ClassDB::register_class<InputEventScreenDrag>();
ClassDB::register_class<InputEventScreenTouch>();
ClassDB::register_class<InputEventAction>();
ClassDB::register_virtual_class<InputEventGesture>();
ClassDB::register_class<InputEventMagnifyGesture>();
ClassDB::register_class<InputEventPanGesture>();
ClassDB::register_class<FuncRef>();
ClassDB::register_class<MainLoop>();
//ClassDB::register_type<OptimizedSaver>();
ClassDB::register_class<UndoRedo>();
ClassDB::register_class<TriangleMesh>();
ClassDB::register_virtual_class<ResourceInteractiveLoader>();
ClassDB::register_class<_File>();
ClassDB::register_class<_Directory>();
ClassDB::register_class<_Thread>();
ClassDB::register_class<_Mutex>();
ClassDB::register_class<_Semaphore>();
ClassDB::register_class<ConfigFile>();
ClassDB::register_class<PackedDataContainer>();
ClassDB::register_virtual_class<PackedDataContainerRef>();
ClassDB::register_class<AStar>();
ClassDB::register_class<EncodedObjectAsID>();
_geometry = memnew(_Geometry);
_resource_loader = memnew(_ResourceLoader);
_resource_saver = memnew(_ResourceSaver);
_os = memnew(_OS);
_engine = memnew(_Engine);
_classdb = memnew(_ClassDB);
_marshalls = memnew(_Marshalls);
}
void register_core_settings() {
}
void register_core_singletons() {
ClassDB::register_class<ProjectSettings>();
ClassDB::register_class<_Geometry>();
ClassDB::register_class<_ResourceLoader>();
ClassDB::register_class<_ResourceSaver>();
ClassDB::register_class<_OS>();
ClassDB::register_class<_Engine>();
ClassDB::register_class<_ClassDB>();
ClassDB::register_class<_Marshalls>();
ClassDB::register_virtual_class<Input>();
ClassDB::register_class<InputMap>();
Engine::get_singleton()->add_singleton(Engine::Singleton("ProjectSettings", ProjectSettings::get_singleton()));
Engine::get_singleton()->add_singleton(Engine::Singleton("Geometry", _Geometry::get_singleton()));
Engine::get_singleton()->add_singleton(Engine::Singleton("ResourceLoader", _ResourceLoader::get_singleton()));
Engine::get_singleton()->add_singleton(Engine::Singleton("ResourceSaver", _ResourceSaver::get_singleton()));
Engine::get_singleton()->add_singleton(Engine::Singleton("OS", _OS::get_singleton()));
Engine::get_singleton()->add_singleton(Engine::Singleton("Engine", _Engine::get_singleton()));
Engine::get_singleton()->add_singleton(Engine::Singleton("ClassDB", _classdb));
Engine::get_singleton()->add_singleton(Engine::Singleton("Marshalls", _Marshalls::get_singleton()));
Engine::get_singleton()->add_singleton(Engine::Singleton("Input", Input::get_singleton()));
Engine::get_singleton()->add_singleton(Engine::Singleton("InputMap", InputMap::get_singleton()));
}
void unregister_core_types() {
memdelete(_resource_loader);
memdelete(_resource_saver);
memdelete(_os);
memdelete(_engine);
memdelete(_classdb);
memdelete(_marshalls);
memdelete(_geometry);
if (resource_format_importer)
memdelete(resource_format_importer);
ObjectDB::cleanup();
unregister_variant_methods();
unregister_global_constants();
ClassDB::cleanup();
ResourceCache::clear();
CoreStringNames::free();
StringName::cleanup();
if (_global_mutex) {
memdelete(_global_mutex);
_global_mutex = NULL; //still needed at a few places
};
MemoryPool::cleanup();
}
| 37.537313 | 112 | 0.682174 | [
"geometry",
"object"
] |
153ec723c93147425c687bc2bef939e4d96c76da | 3,261 | cpp | C++ | src/util/CPGNode.cpp | wvat/NTRTsim | 0443cbd542e12e23c04adf79ea0d8d003c428baa | [
"Apache-2.0"
] | 148 | 2015-01-08T22:44:00.000Z | 2022-03-19T18:42:48.000Z | src/util/CPGNode.cpp | wvat/NTRTsim | 0443cbd542e12e23c04adf79ea0d8d003c428baa | [
"Apache-2.0"
] | 107 | 2015-01-02T16:41:42.000Z | 2021-06-14T22:09:19.000Z | src/util/CPGNode.cpp | wvat/NTRTsim | 0443cbd542e12e23c04adf79ea0d8d003c428baa | [
"Apache-2.0"
] | 86 | 2015-01-06T07:02:36.000Z | 2022-02-28T17:36:14.000Z | /*
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is 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.
*/
/**
* @file CPGNode.cpp
* @brief Implementation of class CPGNode
* @date March 2014
* @author Brian Tietz
* $Id$
*/
#include "CPGNode.h"
//#include "CPGEdge.h"
// The C++ Standard Library
#include <algorithm> //for_each
#include <math.h>
#include <assert.h>
CPGNode::CPGNode(int nodeNum, const std::vector<double> & params):
nodeValue(0),
phiValue(0),
phiDotValue(0),
rValue(0),
rDotValue(0),
m_nodeNumber(nodeNum),
rDoubleDotValue(0),
rConst(params[4]),
frequencyOffset(params[0]),
frequencyScale(params[1]),
radiusOffset(params[2]),
radiusScale(params[3]),
dMin(params[5]),
dMax(params[6])
{
//Precondition
assert(params.size() >= 7);
}
CPGNode::~CPGNode()
{
couplingList.clear();
}
void CPGNode::addCoupling( CPGNode* cNode,
const double cWeight,
const double cPhase)
{
couplingList.push_back(cNode);
weightList.push_back(cWeight);
phaseList.push_back(cPhase);
assert(couplingList.size() == weightList.size() && couplingList.size() == phaseList.size());
}
void CPGNode::updateDTs(double descCom)
{
phiDotValue = 2 * M_PI * nodeEquation(descCom, frequencyOffset, frequencyScale);
/**
* Iterate through every edge and affect the phase of this node
* accordingly.
* @todo ask about refactoring to use for_each
*/
const std::size_t n = couplingList.size();
for (std::size_t i = 0; i != n; i++){
const CPGNode& targetNode = *(couplingList[i]);
phiDotValue += weightList[i] * targetNode.rValue * sin (targetNode.phiValue - phiValue - phaseList[i]);
}
rDoubleDotValue = rConst * (rConst / 4 * (nodeEquation(descCom, radiusOffset, radiusScale)
- rValue) - rDotValue);
}
double CPGNode::nodeEquation( double d,
double c0,
double c1)
{
//@todo: Make parameters dMax, dMin
if(d >= dMin && d <= dMax){
return c1 * d + c0;
}
else{
return 0;
}
}
void CPGNode::updateNodeValues (double newPhi,
double newR,
double newRD)
{
rValue = newR;
rDotValue = newRD;
phiValue = newPhi;
nodeValue = rValue*cos(phiValue);
}
std::string CPGNode::toString(const std::string& prefix) const
{
std::string p = " ";
std::ostringstream os;
os << prefix << "CPGNode(" << p << m_nodeNumber << std::endl;
// TODO: add something about parameters of this node?
os << prefix << p << "Connectivity:" << std::endl;
for(int i = 0; i < couplingList.size(); i++) {
os << prefix << p << p << *(couplingList[i]);
}
os << prefix << ")";
return os.str();
}
| 25.084615 | 111 | 0.677093 | [
"vector"
] |
15431859a07915d1909be112b66c20477181a316 | 5,586 | cpp | C++ | modules/task_3/kamskov_e_grackham_hull/main.cpp | orcyyy/pp_2020_autumn_engineer-1 | 14cb1248b8b765a02eaa4c73f06807c250545491 | [
"BSD-3-Clause"
] | null | null | null | modules/task_3/kamskov_e_grackham_hull/main.cpp | orcyyy/pp_2020_autumn_engineer-1 | 14cb1248b8b765a02eaa4c73f06807c250545491 | [
"BSD-3-Clause"
] | 1 | 2020-12-27T20:31:37.000Z | 2020-12-27T20:31:37.000Z | modules/task_3/kamskov_e_grackham_hull/main.cpp | schelyanskovan/pp_2020_autumn_engineer | 2bacf7ccaf3c638044c41068565a693ac4fae828 | [
"BSD-3-Clause"
] | 1 | 2021-03-29T10:15:47.000Z | 2021-03-29T10:15:47.000Z | // Copyright 2020 Kamskov Evgeny
#include <gtest-mpi-listener.hpp>
#include <gtest/gtest.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include "./kamskov_e_grackham_hull.h"
TEST(Parallel_Operations_MPI, Test_task_10) {
int proc_size, proc;
MPI_Comm_rank(MPI_COMM_WORLD, &proc);
MPI_Comm_size(MPI_COMM_WORLD, &proc_size);
std::vector<Point> vector, vector1, vector2;
int Dimension = 10, points_size = 35;
double time;
if (proc == 0) {
std::cout << "Generating field..." << std::endl;
vector = get_field(Dimension, points_size);
print_field(vector, Dimension);
time = MPI_Wtime();
}
MPI_Barrier(MPI_COMM_WORLD);
vector1 = greckham_par(vector, points_size);
if (proc == 0) {
std::cout << "Grackham parallel:" << MPI_Wtime() - time << std::endl;
time = MPI_Wtime();
vector2 = greckham_seq(vector);
std::cout << "Grackham sequential:" << MPI_Wtime() - time << std::endl;
std::cout << "Convex hull points:" << std::endl;
for (size_t i = 0; i < vector2.size(); i++) {
std::cout << "(" << vector2[i].x << ", " << vector2[i].y << ")" << std::endl;
}
ASSERT_EQ(vector1, vector2);
}
MPI_Barrier(MPI_COMM_WORLD);
}
TEST(Parallel_Operations_MPI, Test_task_15) {
int proc_size, proc;
MPI_Comm_rank(MPI_COMM_WORLD, &proc);
MPI_Comm_size(MPI_COMM_WORLD, &proc_size);
std::vector<Point> vector, vector1, vector2;
int Dimension = 15, points_size = 100;
double time;
if (proc == 0) {
std::cout << "Generating field..." << std::endl;
vector = get_field(Dimension, points_size);
print_field(vector, Dimension);
time = MPI_Wtime();
}
MPI_Barrier(MPI_COMM_WORLD);
vector1 = greckham_par(vector, points_size);
if (proc == 0) {
std::cout << "Grackham parallel:" << MPI_Wtime() - time << std::endl;
time = MPI_Wtime();
vector2 = greckham_seq(vector);
std::cout << "Grackham sequential:" << MPI_Wtime() - time << std::endl;
std::cout << "Convex hull points:" << std::endl;
for (size_t i = 0; i < vector2.size(); i++) {
std::cout << "(" << vector2[i].x << ", " << vector2[i].y << ")" << std::endl;
}
ASSERT_EQ(vector1, vector2);
}
MPI_Barrier(MPI_COMM_WORLD);
}
TEST(Parallel_Operations_MPI, Test_task_10000) {
int proc_size, proc;
MPI_Comm_rank(MPI_COMM_WORLD, &proc);
MPI_Comm_size(MPI_COMM_WORLD, &proc_size);
std::vector<Point> vector, vector1, vector2;
int Dimension = 10000, points_size = 10000;
double time;
if (proc == 0) {
std::cout << "Generating field..." << std::endl;
vector = get_field(Dimension, points_size);
// print_field(vector, Dimension);
time = MPI_Wtime();
}
MPI_Barrier(MPI_COMM_WORLD);
vector1 = greckham_par(vector, points_size);
if (proc == 0) {
std::cout << "Grackham parallel:" << MPI_Wtime() - time << std::endl;
time = MPI_Wtime();
vector2 = greckham_seq(vector);
std::cout << "Grackham sequential:" << MPI_Wtime() - time << std::endl;
ASSERT_EQ(vector1, vector2);
}
MPI_Barrier(MPI_COMM_WORLD);
}
TEST(Parallel_Operations_MPI, Test_task_50000) {
int proc_size, proc;
MPI_Comm_rank(MPI_COMM_WORLD, &proc);
MPI_Comm_size(MPI_COMM_WORLD, &proc_size);
std::vector<Point> vector, vector1, vector2;
int Dimension = 8000, points_size = 30000;
double time;
if (proc == 0) {
std::cout << "Generating field..." << std::endl;
vector = get_field(Dimension, points_size);
// print_field(vector, Dimension);
time = MPI_Wtime();
}
MPI_Barrier(MPI_COMM_WORLD);
vector1 = greckham_par(vector, points_size);
if (proc == 0) {
std::cout << "Grackham parallel:" << MPI_Wtime() - time << std::endl;
time = MPI_Wtime();
vector2 = greckham_seq(vector);
std::cout << "Grackham sequential:" << MPI_Wtime() - time << std::endl;
ASSERT_EQ(vector1, vector2);
}
MPI_Barrier(MPI_COMM_WORLD);
}
TEST(Parallel_Operations_MPI, Test_task_100000) {
int proc_size, proc;
MPI_Comm_rank(MPI_COMM_WORLD, &proc);
MPI_Comm_size(MPI_COMM_WORLD, &proc_size);
std::vector<Point> vector, vector1, vector2;
int Dimension = 800000, points_size = 100000;
double time;
if (proc == 0) {
std::cout << "Generating field..." << std::endl;
vector = get_field(Dimension, points_size);
// print_field(vector, Dimension);
time = MPI_Wtime();
}
MPI_Barrier(MPI_COMM_WORLD);
vector1 = greckham_par(vector, points_size);
if (proc == 0) {
std::cout << "Grackham parallel:" << MPI_Wtime() - time << std::endl;
time = MPI_Wtime();
vector2 = greckham_seq(vector);
std::cout << "Grackham sequential:" << MPI_Wtime() - time << std::endl;
EXPECT_EQ(vector1.size(), vector2.size());
}
MPI_Barrier(MPI_COMM_WORLD);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment);
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Release(listeners.default_result_printer());
listeners.Release(listeners.default_xml_generator());
listeners.Append(new GTestMPIListener::MPIMinimalistPrinter);
return RUN_ALL_TESTS();
}
| 32.666667 | 89 | 0.616899 | [
"vector"
] |
15508704d4187c85076ed5d5cec0fa85a53e85d0 | 1,695 | cpp | C++ | leetcode.com/0041 First Missing Positive/main.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | 1 | 2020-08-20T11:02:49.000Z | 2020-08-20T11:02:49.000Z | leetcode.com/0041 First Missing Positive/main.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | null | null | null | leetcode.com/0041 First Missing Positive/main.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | 1 | 2022-01-01T23:23:13.000Z | 2022-01-01T23:23:13.000Z | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// time: O(n), space: O(n)
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int n = nums.size(), i;
vector<bool> _nums(n);
for (auto x: nums) if (x <= n && x > 0) _nums[x-1] = true;
for (i = 0; i < n && _nums[i]; ++i);
return i+1;
}
};
// time: O(n), space: O(1), does this counts as O(1) space, I his this implementation is bad
// class Solution {
// public:
// int firstMissingPositive(vector<int>& nums) {
// int r = nums.size(), i;
// for (i = 0; i < r;) {
// if (nums[i] > r || nums[i] <= 0) swap(nums[i], nums[--r]);
// else {
// int ind = nums[i]-1;
// if (nums[ind] == nums[i]) {
// if (i == ind) ++i;
// else nums[i++] = 0;
// } else {
// swap(nums[ind], nums[i]);
// }
// }
// }
// for (i = 0; i < r && nums[i] == i + 1; ++i);
// return i+1;
// }
// };
// time: O(nlogn)
// class Solution {
// public:
// int firstMissingPositive(vector<int>& nums) {
// sort(nums.begin(), nums.end());
// int i = 0, j = 1, n = nums.size();
// for (; i < n && nums[i] <= 0; ++i);
// for (; j + i - 1 < n && nums[j + i - 1] == j; ++j) {
// for (;j + i < n && nums[j + i - 1] == nums[j + i]; ++i);
// }
// return j;
// }
// };
int main(int argc, char const *argv[])
{
Solution s;
vector<int> vi = {1, 1};
cout<<s.firstMissingPositive(vi)<<endl;
return 0;
}
| 27.33871 | 92 | 0.417699 | [
"vector"
] |
15585b57eec854b4aa2f312f63c02fa45cc3922d | 31,854 | cc | C++ | flv_tag.cc | xieyugui/ts_flv | 2b614ac44b42c7cb7c489fe3305af37f7903d674 | [
"Apache-2.0"
] | 2 | 2018-08-01T09:40:50.000Z | 2019-09-13T13:27:46.000Z | flv_tag.cc | xieyugui/ts_flv | 2b614ac44b42c7cb7c489fe3305af37f7903d674 | [
"Apache-2.0"
] | null | null | null | flv_tag.cc | xieyugui/ts_flv | 2b614ac44b42c7cb7c489fe3305af37f7903d674 | [
"Apache-2.0"
] | 2 | 2017-11-23T09:57:30.000Z | 2019-07-17T06:41:49.000Z | /*
* @author: daemon.xie
* @license: Apache Licence
* @contact: xieyugui
* @software: CLion
* @file: flv_tag.cc
* @date: 2017/9/11 上午10:54
* @desc:
*/
#include "flv_tag.h"
static int64_t IOBufferReaderCopy(TSIOBufferReader readerp, void *buf, int64_t length);
static const char * get_amf_type_string(byte type);
static double int2double(uint64_t i)
{
union av_intfloat64 v;
v.i = i;
return v.f;
}
static uint64_t double2int(double f)
{
union av_intfloat64 v;
v.f = f;
return v.i;
}
int FlvTag::process_tag(TSIOBufferReader readerp, bool complete) {
int64_t avail;
int rc;
avail = TSIOBufferReaderAvail(readerp);
TSIOBufferCopy(tag_buffer, readerp, avail, 0);
TSDebug(PLUGIN_NAME, "[process_tag] readerp avail=%ld",avail);
TSIOBufferReaderConsume(readerp, avail);
rc = (this->*current_handler)();
TSDebug(PLUGIN_NAME, "[process_tag] rc=%d",rc);
if (rc == 0 && complete) {
rc = -1;
}
if (rc) {
this->content_length = this->cl;
if(this->start <= 0 && this->end > 0) {
this->content_length = this->end;
} else if (this->start > 0 && this->end <= 0) {
this->content_length = this->content_length - this->start_duration_file_size;
} else if (this->start > 0 && this->end > 0) {
this->content_length = this->end - this->start_duration_file_size;
}
TSDebug(PLUGIN_NAME, "[process_tag] content_length = %ld", content_length);
}
if(rc < 0) {
//如果异常的话,就不做处理,直接返回全部长度
this->content_length = this->cl;
}
return rc;
}
int64_t FlvTag::write_out(TSIOBuffer buffer, TSIOBuffer res_buffer) {
int64_t head_avail, modify_meta_avail, tag_avail;
head_avail = TSIOBufferReaderAvail(head_reader);
if (head_avail > 0) {
TSIOBufferCopy(buffer, head_reader, head_avail, 0);
TSIOBufferReaderConsume(head_reader, head_avail);
}
modify_meta_avail = TSIOBufferReaderAvail(modify_meta_reader);
if (modify_meta_avail > 0) {
TSIOBufferCopy(buffer, modify_meta_reader, modify_meta_avail, 0);
TSIOBufferReaderConsume(modify_meta_reader, modify_meta_avail);
}
TSDebug(PLUGIN_NAME, "[write_out] head_avail=%ld, modify_meta_avail=%ld",head_avail, modify_meta_avail);
//将剩余的拷贝回去
tag_avail = TSIOBufferReaderAvail(tag_reader);
if(tag_avail > 0) {
TSIOBufferCopy(res_buffer, tag_reader, tag_avail, 0);
TSIOBufferReaderConsume(tag_reader, tag_avail);
}
TSDebug(PLUGIN_NAME, "[write_out] tag_avail=%ld",tag_avail);
return head_avail + modify_meta_avail;
}
int FlvTag::process_header() {
int64_t avail;
flv_header header;
int result;
size_t flv_header_size = get_flv_header_size();
size_t need_length = flv_header_size + sizeof(uint32_be); // flv_header + first previoustagsize 第一个默认为0
//header长度4bytes 整个文件头的长度,一般是9(3+1+1+4),当然头部字段也有可能包含其它信息这个时间其长度就不是9了。
//FLV Body
//FLV body就是由很多tag组成的,一个tag包括下列信息:
// previoustagsize 4bytes 前一个tag的长度,第一个tag就是0
avail = TSIOBufferReaderAvail(tag_reader);
if (avail < (int64_t)need_length)
return 0;
TSIOBufferCopy(head_buffer, tag_reader, need_length, 0);
result = flv_read_flv_header(tag_reader, &header);
TSIOBufferReaderConsume(tag_reader, sizeof(uint32_be));
TSDebug(PLUGIN_NAME, "[process_header] header_length=%lu",need_length);
tag_pos += need_length;
if(result != 0) {
this->end = 0;
return -1;
}
this->current_handler = &FlvTag::process_meta_body;
return process_meta_body();
}
//解析metadataTag
int FlvTag::process_meta_body() {
uint64_t avail, sz;
uint32 body_length,timestamp;
size_t flv_tag_length = get_flv_tag_size();
char buf[12];
avail = TSIOBufferReaderAvail(tag_reader);
do {
flv_tag tag;
if (avail < flv_tag_length + 1) // find video key frame
return 0;
flv_read_flv_tag(tag_reader, &tag);
IOBufferReaderCopy(tag_reader, buf, flv_tag_length + 1);
body_length = flv_tag_get_body_length(tag);
sz = flv_tag_length + body_length + sizeof(uint32_be); //dup body keyframe size
if (avail < sz) // insure the whole tag
return 0;
timestamp = flv_tag_get_timestamp(tag);
if (timestamp != 0)
goto process_end;
if (tag.type == FLV_TAG_TYPE_VIDEO && (((uint8_t)buf[11]) >> 4) == 1) {
if (!key_found) {
key_found = true;
} else {
goto process_end;
}
}
TSIOBufferCopy(meta_buffer, tag_reader, sz, 0);
TSIOBufferReaderConsume(tag_reader, sz);
TSDebug(PLUGIN_NAME, "[process_meta_body] sz=%lu, tag_pos=%lu", sz, tag_pos);
tag_pos += sz;
avail -= sz;
} while(avail > 0);
return 0;
process_end:
TSDebug(PLUGIN_NAME, "[process_meta_body] meta_buff=%lu", TSIOBufferReaderAvail(meta_reader));
key_found = false;
this->current_handler = &FlvTag::parse_meta_body;
return parse_meta_body();
}
int FlvTag::parse_meta_body() {
size_t flv_tag_size = get_flv_tag_size();
TSDebug(PLUGIN_NAME, "parse_meta_body ");
TSIOBufferCopy(copy_meta_buffer, meta_reader, TSIOBufferReaderAvail(meta_reader), 0);
//parse flv tag header
flv_tag tag;
//parse flv tag data
uint32 body_length;
amf_data * name;
amf_data * data;
amf_data * on_metadata, *on_metadata_name;
byte *buf;
//这里指本身的tag长度
uint32 prev_tag_size;
name = NULL;
data = NULL;
on_metadata = NULL;
on_metadata_name = NULL;
//tag
flv_read_flv_tag(copy_meta_reader, &tag);
TSIOBufferReaderConsume(copy_meta_reader, flv_tag_size);
body_length = flv_tag_get_body_length(tag);
TSDebug(PLUGIN_NAME,"[parse_meta_body] body_length=%u",body_length);
//body data
buf = (byte *)TSmalloc(sizeof(byte) * body_length);
memset(buf, 0, body_length);
IOBufferReaderCopy(copy_meta_reader, buf, body_length);
TSIOBufferReaderConsume(copy_meta_reader, body_length);
flv_read_metadata(buf, &name, &data,body_length);
IOBufferReaderCopy(copy_meta_reader, &prev_tag_size, sizeof(uint32_be));
TSIOBufferReaderConsume(copy_meta_reader, sizeof(uint32_be));
prev_tag_size = swap_uint32(prev_tag_size);
TSDebug(PLUGIN_NAME,"[parse_meta_body] prev_tag_size=%u",prev_tag_size);
/* onMetaData checking */
if (!strcmp((char*) amf_string_get_bytes(name),"onMetaData")) {
on_metadata = amf_data_clone(data);
on_metadata_name = amf_data_clone(name);
/* check onMetadata type */
if (amf_data_get_type(on_metadata) != AMF_TYPE_ASSOCIATIVE_ARRAY) {
TSDebug(PLUGIN_NAME,"invalid onMetaData data type: %u, should be an associative array (8)\n",amf_data_get_type(on_metadata));
amf_data_free(name);
amf_data_free(data);
TSfree(buf);
goto end;
}
}
amf_data_free(name);
amf_data_free(data);
TSfree(buf);
//parse metadata
TSDebug(PLUGIN_NAME,"[parse_meta_body] start parse metadata");
amf_node * n;
/* more metadata checks */
//get keyframes array
for (n = amf_associative_array_first(on_metadata); n != NULL; n = amf_associative_array_next(n)) {
byte * name;
amf_data * data;
byte type;
name = amf_string_get_bytes(amf_associative_array_get_name(n));
data = amf_associative_array_get_data(n);
type = amf_data_get_type(data);
/* TODO: check UTF-8 strings, in key, and value if string type */
/* duration (number) */
if (!strcmp((char*) name, "duration")) {
if (type == AMF_TYPE_NUMBER) {
number64 file_duration;
file_duration = amf_number_get_value(data);
this->duration = int2double(file_duration);
TSDebug(PLUGIN_NAME,"[parse_meta_body] duration=%lf",this->duration);
} else {
TSDebug(PLUGIN_NAME,"invalid type for duration: expected %s, got %s\n",
get_amf_type_string(AMF_TYPE_NUMBER),
get_amf_type_string(type));
}
}
/* lasttimestamp: (number) */
if (!strcmp((char*) name, "lasttimestamp")) {
if (type == AMF_TYPE_NUMBER) {
number64 file_lasttimestamp;
file_lasttimestamp = amf_number_get_value(data);
this->lasttimestamp = int2double(file_lasttimestamp);
TSDebug(PLUGIN_NAME,"[parse_meta_body] lasttimestamp=%lf",this->lasttimestamp);
} else {
TSDebug(PLUGIN_NAME,"invalid type for lasttimestamp: expected %s, got %s\n",
get_amf_type_string(AMF_TYPE_NUMBER),
get_amf_type_string(type));
}
}
/* lastkeyframetimestamp: (number) */
if (!strcmp((char*) name, "lastkeyframetimestamp")) {
if (type == AMF_TYPE_NUMBER) {
number64 file_lastkeyframetimestamp;
file_lastkeyframetimestamp = amf_number_get_value(data);
this->lastkeyframetimestamp = int2double(file_lastkeyframetimestamp);
TSDebug(PLUGIN_NAME,"[parse_meta_body] lastkeyframetimestamp=%lf",this->lastkeyframetimestamp);
} else {
TSDebug(PLUGIN_NAME,"invalid type for lastkeyframetimestamp: expected %s, got %s\n",
get_amf_type_string(AMF_TYPE_NUMBER),
get_amf_type_string(type));
}
}
/* lastkeyframelocation: (number) */
if (!strcmp((char*) name, "lastkeyframelocation")) {
if (type == AMF_TYPE_NUMBER) {
number64 file_lastkeyframelocation;
file_lastkeyframelocation = amf_number_get_value(data);
this->lastkeyframelocation = int2double(file_lastkeyframelocation);
TSDebug(PLUGIN_NAME,"[parse_meta_body] lastkeyframelocation=%lf",this->lastkeyframelocation);
} else {
TSDebug(PLUGIN_NAME,"invalid type for lastkeyframelocation: expected %s, got %s\n",
get_amf_type_string(AMF_TYPE_NUMBER),
get_amf_type_string(type));
}
}
/* filesize: (number) */
if (!strcmp((char*) name, "filesize")) {
if (type == AMF_TYPE_NUMBER) {
number64 file_filesize;
file_filesize = amf_number_get_value(data);
this->filesize = int2double(file_filesize);
TSDebug(PLUGIN_NAME,"[parse_meta_body] filesize=%lf",this->filesize);
} else {
TSDebug(PLUGIN_NAME,"invalid type for filesize: expected %s, got %s\n",
get_amf_type_string(AMF_TYPE_NUMBER),
get_amf_type_string(type));
}
}
/* keyframes: (object) */
if (!strcmp((char*) name, "keyframes")) {
if (type == AMF_TYPE_OBJECT) {
amf_data * file_times, *file_filepositions;
file_times = amf_object_get(data, "times");
file_filepositions = amf_object_get(data, "filepositions");
/* check sub-arrays' presence */
if (file_times == NULL) {
TSDebug(PLUGIN_NAME,"Missing times metadata\n");
}
if (file_filepositions == NULL) {
TSDebug(PLUGIN_NAME,"Missing filepositions metadata\n");
}
if (file_times != NULL && file_filepositions != NULL) {
/* check types */
uint8 times_type, fp_type;
times_type = amf_data_get_type(file_times);
if (times_type != AMF_TYPE_ARRAY) {
TSDebug(PLUGIN_NAME,"times_type != AMF_TYPE_ARRAY -- invalid type for times: expected %s, got %s\n",
get_amf_type_string(AMF_TYPE_ARRAY),
get_amf_type_string(times_type));
}
fp_type = amf_data_get_type(file_filepositions);
if (fp_type != AMF_TYPE_ARRAY) {
TSDebug(PLUGIN_NAME,"fp_type != AMF_TYPE_ARRAY -- invalid type for filepositions: expected %s, got %s\n",
get_amf_type_string(AMF_TYPE_ARRAY),
get_amf_type_string(fp_type));
}
if (times_type == AMF_TYPE_ARRAY && fp_type == AMF_TYPE_ARRAY) {
TSDebug(PLUGIN_NAME,"[parse_meta_body] fp_len=%u",amf_array_size(file_filepositions));
this->keyframes_len = amf_array_size(file_filepositions);
amf_node * ff_node, *ft_node;
ft_node = amf_array_first(file_times);
ff_node = amf_array_first(file_filepositions);
if (ft_node != NULL && ff_node != NULL)
haskeyframe = true;
number64 f_time,f_position;
double df_time ,df_position;
while (ft_node != NULL && ff_node != NULL) {
f_time =0;
f_position = 0;
df_time = 0;
df_position = 0;
/* time */
if (amf_data_get_type(amf_array_get(ft_node)) != AMF_TYPE_NUMBER) {
TSDebug(PLUGIN_NAME,"!= AMF_TYPE_NUMBER -- invalid type for time: expected %s, got %s\n",
get_amf_type_string(AMF_TYPE_NUMBER),
get_amf_type_string(type));
} else {
f_time = amf_number_get_value(amf_array_get(ft_node));
df_time = int2double(f_time);
}
/* position */
if (amf_data_get_type(amf_array_get(ff_node)) != AMF_TYPE_NUMBER) {
TSDebug(PLUGIN_NAME,
"!= AMF_TYPE_NUMBER invalid type for file position: expected %s, got %s\n",
get_amf_type_string(AMF_TYPE_NUMBER),
get_amf_type_string(type));
} else {
f_position = amf_number_get_value(amf_array_get(ff_node));
df_position = int2double(f_position);
}
TSDebug(PLUGIN_NAME,"[parse_meta_body] keyframes time=%lf,position=%lf",df_time, df_position);
TSDebug(PLUGIN_NAME,"[parse_meta_body] start=%lu",start);
if (start > 0) {
TSDebug(PLUGIN_NAME,"[parse_meta_body] start > 0");
if (end > 0) {
TSDebug(PLUGIN_NAME,"[parse_meta_body] start > 0 end > 0");
if (df_position < start || df_time <= 0) {
start_keyframe_len += 1;
start_keyframe_positions = df_position;
start_keyframe_times = df_time;
}
if (df_position > end && end_keyframe_times > 0)
break;
end_keyframe_len += 1;
end_keyframe_positions = df_position;
end_keyframe_times = df_time;
} else {
TSDebug(PLUGIN_NAME,"[parse_meta_body] start > 0 else");
if (df_position > start && start_keyframe_times > 0)
break;
start_keyframe_len += 1;
start_keyframe_positions = df_position;
start_keyframe_times = df_time;
}
} else {
if (df_position > end && end_keyframe_times > 0)
break;
end_keyframe_len += 1;
end_keyframe_positions = df_position;
end_keyframe_times = df_time;
}
/* next entry */
ft_node = amf_array_next(ft_node);
ff_node = amf_array_next(ff_node);
}
}
}
} else {
TSDebug(PLUGIN_NAME,"invalid type for keyframes: expected %s, got %s\n",
get_amf_type_string(AMF_TYPE_BOOLEAN),
get_amf_type_string(type));
}
}//end keyframes
}// end for
end:
amf_data_free(on_metadata);
amf_data_free(on_metadata_name);
//如果没有关键帧,就不实现end功能
if (!haskeyframe) {
this->end = 0;
this->end_keyframe_len = 0;
this->end_keyframe_positions = 0;
} else {
this->start = (uint64_t)this->start_keyframe_positions;
this->end = (uint64_t)this->end_keyframe_positions;
if (this->end > 0) {
lastkeyframelocation = end_keyframe_positions;
lastkeyframetimestamp = end_keyframe_times;
lasttimestamp = end_keyframe_times;
}
TSDebug(PLUGIN_NAME,"start_keyframe=%d,%lf end_keyframe=%d,%lf",start_keyframe_len,start_keyframe_positions
,end_keyframe_len,end_keyframe_positions);
TSDebug(PLUGIN_NAME,"lastkeyframe location=%lf, timestamp=%lf lasttimestamp=%lf, end_keyframe_len=%d",lastkeyframelocation,lastkeyframetimestamp
,lasttimestamp,end_keyframe_len);
this->real_end_keyframe_positions = this->end;
//计算delete 的关键帧大小
uint32 k_len;
k_len = 0;
if(this->start_keyframe_len > 0)
k_len = this->start_keyframe_len -1;
if (this->end_keyframe_len > 0)
k_len += keyframes_len - this->end_keyframe_len;
//一个keyframe 为9 删除ft_node 和ff_node
this->delete_meta_size = k_len * 18;
TSDebug(PLUGIN_NAME,"[parse_meta_body] delete_meta_size=%lu",this->delete_meta_size);
}
if (this->start <=0 && this->end <= 0) {
this->end = 0;
this->real_end_keyframe_positions = this->end;
return -1;
}
TSDebug(PLUGIN_NAME,"[parse_meta_body] start=%lu end=%lu",this->start, this->end);
if (this->start > 0) {
this->current_handler = &FlvTag::process_medial_body;
return process_medial_body();
} else {
this->current_handler = &FlvTag::update_flv_meta_data;
return update_flv_meta_data();
}
}
//丢失视频和音频
int FlvTag::process_medial_body() {
int64_t avail, sz;
uint32 body_length, timestamp;
size_t flv_tag_length = get_flv_tag_size();
avail = TSIOBufferReaderAvail(tag_reader);
do {
flv_tag tag;
if (avail < (int64_t)flv_tag_length )
return 0;
flv_read_flv_tag(tag_reader, &tag);
body_length = flv_tag_get_body_length(tag);
sz = flv_tag_length + body_length + sizeof(uint32_be); //tag->(tag header, tag body), tagsize
if (avail < sz) // insure the whole tag
return 0;
start_dup_size += sz;
TSDebug(PLUGIN_NAME,"[process_medial_body] start_duration_file_size=%lu,start_dup_size=%lu",start_duration_file_size,start_dup_size);
timestamp = flv_tag_get_timestamp(tag);
if (tag.type == FLV_TAG_TYPE_VIDEO) {
TSDebug(PLUGIN_NAME,"[process_medial_body] FLV_TAG_TYPE_VIDEO");
TSDebug(PLUGIN_NAME,"[process_medial_body] start_dup_size=%lu, start=%lu",start_dup_size,start);
if (start_dup_size <= start) {
start_duration_time = timestamp; //ms
} else {
TSDebug(PLUGIN_NAME, "process_medial_body success!!! tag_pos= %ld,start_duration_file_size=%lu",tag_pos, start_duration_file_size);
//return 1;
this->current_handler = &FlvTag::update_flv_meta_data;
return update_flv_meta_data();
}
}
start_duration_file_size += sz;
TSIOBufferReaderConsume(tag_reader, sz);
avail -= sz;
tag_pos += sz;
} while (avail > 0);
return 0;
}
/**
* 1. 当start=0,end>0;更新duration,lasttimestamp,lastkeyframetimestamp,lastkeyframelocation,filesize,keyframes
* 2. 当start>0,end=0; 更新duration,videosize,audiosize,datasize,lasttimestamp,lastkeyframetimestamp,lastkeyframelocation,
* filesize,如果有keyframes的话,也需要更新
* 3. 当start>0,end>0; 更新duration,lasttimestamp,lastkeyframetimestamp,lastkeyframelocation,filesize,keyframes
* 注意 由于end 的videosize,audiosize没办法更新,脚本数据是先于end产生的
* 本次暂时只是更新了duration,lasttimestamp,filesize
*/
int FlvTag::update_flv_meta_data() {
this->start_duration_time = this->start_duration_time / 1000;
// ---this->start_duration_file_size += this->delete_meta_size;
TSDebug(PLUGIN_NAME, "[update_flv_meta_data] this->start_duration_time=%lf", this->start_duration_time);
if(this->start <= 0 && this->end > 0) {
TSDebug(PLUGIN_NAME, "[update_flv_meta_data] this->start <= 0 && this->end > 0");
this->start_duration_time = 0;
this->start_duration_video_size = 0;
this->start_duration_audio_size = 0;
this->duration = this->lastkeyframetimestamp;
this->filesize = this->lastkeyframelocation;
//keyframes 在遍历过程中删除
} else if (this->start > 0 && this->end <= 0) {
TSDebug(PLUGIN_NAME, "[update_flv_meta_data] this->start > 0 && this->end <= 0");
this->lastkeyframelocation = this->lastkeyframelocation - this->start_duration_file_size;
this->lastkeyframetimestamp = this->lastkeyframetimestamp - this->start_duration_time;
this->lasttimestamp = this->lastkeyframetimestamp;
this->duration = this->lastkeyframetimestamp;
this->filesize = this->filesize - (double)this->start_duration_file_size;
// this->videosize = this->videosize - this->start_duration_video_size;--
// this->audiosize = this->audiosize - this->start_duration_audio_size;--
// this->datasize = this->datasize - this->start_duration_video_size - this->start_duration_audio_size;--
//keyframes 在遍历过程中删除
} else if (this->start > 0 && this->end > 0) {
TSDebug(PLUGIN_NAME, "[update_flv_meta_data] this->start > 0 && this->end > 0");
this->lastkeyframelocation = this->lastkeyframelocation - this->start_duration_file_size;
this->lastkeyframetimestamp = this->lastkeyframetimestamp - this->start_keyframe_times;
this->lasttimestamp = this->lastkeyframetimestamp;
this->duration = this->lastkeyframetimestamp;
this->filesize = this->lastkeyframelocation;
//keyframes 在遍历过程中删除
} else {
this->end = 0;
this->real_end_keyframe_positions = this->end;
return -1;
}
TSDebug(PLUGIN_NAME, "[update_flv_meta_data] start_duration_file_size=%lu",this->start_duration_file_size);
TSDebug(PLUGIN_NAME, "[update_flv_meta_data] start_duration_time=%lf",this->start_duration_time);
TSDebug(PLUGIN_NAME, "[update_flv_meta_data] start_duration_video_size=%lu",this->start_duration_video_size);
TSDebug(PLUGIN_NAME, "[update_flv_meta_data] start_duration_audio_size=%lu",this->start_duration_audio_size);
TSDebug(PLUGIN_NAME, "[update_flv_meta_data] lastkeyframelocation=%lf",this->lastkeyframelocation);
TSDebug(PLUGIN_NAME, "[update_flv_meta_data] lastkeyframetimestamp=%lf",this->lastkeyframetimestamp);
TSDebug(PLUGIN_NAME, "[update_flv_meta_data] lasttimestamp=%lf",this->lasttimestamp);
TSDebug(PLUGIN_NAME, "[update_flv_meta_data] duration=%lf",this->duration);
TSDebug(PLUGIN_NAME, "[update_flv_meta_data] filesize=%lf",this->filesize);
int64_t avail;
avail = TSIOBufferReaderAvail(meta_reader);
TSDebug(PLUGIN_NAME, "update_flv_meta_data meta data length=%ld",avail);
clear_copy_meta_buffer();
create_copy_meta_buffer();
TSIOBufferCopy(copy_meta_buffer, meta_reader,avail , 0);
size_t flv_tag_size = get_flv_tag_size();
//parse flv tag
flv_tag tag;
uint32 body_length;
amf_data * name;
amf_data * data;
amf_data * on_metadata, *on_metadata_name;
byte *buf;
uint32 prev_tag_size;
name = NULL;
data = NULL;
on_metadata = NULL;
on_metadata_name = NULL;
flv_read_flv_tag(copy_meta_reader, &tag);
TSIOBufferReaderConsume(copy_meta_reader, flv_tag_size);
body_length = flv_tag_get_body_length(tag);
TSDebug(PLUGIN_NAME, "[update_flv_meta_data] tag header=%u, tag body=%u",flv_tag_size,body_length);
buf = (byte *)TSmalloc(sizeof(byte) * body_length);
memset(buf, 0, body_length);
IOBufferReaderCopy(copy_meta_reader, buf, body_length);
TSIOBufferReaderConsume(copy_meta_reader, body_length);
flv_read_metadata(buf, &name, &data,body_length);
IOBufferReaderCopy(copy_meta_reader, &prev_tag_size, sizeof(uint32_be));
TSIOBufferReaderConsume(copy_meta_reader, sizeof(uint32_be));
prev_tag_size = swap_uint32(prev_tag_size);
/* onMetaData checking */
if (!strcmp((char*) amf_string_get_bytes(name),"onMetaData")) {
TSDebug(PLUGIN_NAME,"start on_medata_size: %lu",amf_data_size(data));
on_metadata = amf_data_clone(data);
on_metadata_name = amf_data_clone(name);
/* check onMetadata type */
if (amf_data_get_type(on_metadata) != AMF_TYPE_ASSOCIATIVE_ARRAY) {
TSDebug(PLUGIN_NAME,"invalid onMetaData data type: %u, should be an associative array (8)\n",amf_data_get_type(on_metadata));
amf_data_free(name);
amf_data_free(data);
TSfree(buf);
goto end;
}
}
amf_data_free(name);
amf_data_free(data);
TSfree(buf);
//parse metadata
amf_node * n;
/* more metadata checks */
for (n = amf_associative_array_first(on_metadata); n != NULL; n = amf_associative_array_next(n)) {
byte * name;
amf_data * data;
byte type;
name = amf_string_get_bytes(amf_associative_array_get_name(n));
data = amf_associative_array_get_data(n);
type = amf_data_get_type(data);
/* TODO: check UTF-8 strings, in key, and value if string type */
/* duration (number) */
if (!strcmp((char*) name, "duration")) {
if (type == AMF_TYPE_NUMBER) {
amf_number_set_value(data,double2int(this->duration));
} else {
TSDebug(PLUGIN_NAME,"invalid type for duration: expected %s, got %s\n",
get_amf_type_string(AMF_TYPE_NUMBER),
get_amf_type_string(type));
}
}
//
// /* lasttimestamp: (number) */
// if (!strcmp((char*) name, "lasttimestamp")) {
// if (type == AMF_TYPE_NUMBER) {
// amf_number_set_value(data,double2int(this->lasttimestamp));
// } else {
// TSDebug(PLUGIN_NAME,"invalid type for lasttimestamp: expected %s, got %s\n",
// get_amf_type_string(AMF_TYPE_NUMBER),
// get_amf_type_string(type));
// }
// }
//
// /* lastkeyframetimestamp: (number) */
// if (!strcmp((char*) name, "lastkeyframetimestamp")) {
// if (type == AMF_TYPE_NUMBER) {
// amf_number_set_value(data,double2int(this->lastkeyframetimestamp));
// } else {
// TSDebug(PLUGIN_NAME,"invalid type for lastkeyframetimestamp: expected %s, got %s\n",
// get_amf_type_string(AMF_TYPE_NUMBER),
// get_amf_type_string(type));
// }
// }
//
// /* lastkeyframelocation: (number) */
// if (!strcmp((char*) name, "lastkeyframelocation")) {
// if (type == AMF_TYPE_NUMBER) {
// amf_number_set_value(data,double2int(this->lastkeyframelocation));
// } else {
// TSDebug(PLUGIN_NAME,"invalid type for lastkeyframelocation: expected %s, got %s\n",
// get_amf_type_string(AMF_TYPE_NUMBER),
// get_amf_type_string(type));
// }
// }
//
// /* filesize: (number) */
// if (!strcmp((char*) name, "filesize")) {
// if (type == AMF_TYPE_NUMBER) {
// amf_number_set_value(data,double2int(this->filesize));
// } else {
// TSDebug(PLUGIN_NAME,"invalid type for filesize: expected %s, got %s\n",
// get_amf_type_string(AMF_TYPE_NUMBER),
// get_amf_type_string(type));
// }
// }
}// end for
// TSDebug(PLUGIN_NAME,"end delete_meta_size: %lu",delete_meta_size);
// size_t delete_size;
// delete_size = on_medata_size- amf_data_size(on_metadata);
// if (delete_meta_size != delete_size)
// this->delete_meta_size = delete_size;
// TSDebug(PLUGIN_NAME,"end on_medata_size: %u, delete=%lu",amf_data_size(on_metadata), on_medata_size- amf_data_size(on_metadata));
end:
uint32 meta_data_length = amf_data_size(on_metadata_name) + amf_data_size(on_metadata);
prev_tag_size = flv_tag_size + meta_data_length;
TSDebug(PLUGIN_NAME, "[update_flv_meta_data] prev_tag_size=%lu",prev_tag_size);
tag.body_length = uint32_to_uint24_be(meta_data_length);
TSIOBufferWrite(modify_meta_buffer,&tag, (int64_t)flv_tag_size);
byte metadata_name_b[amf_data_size(on_metadata_name)];
amf_data_buffer_write(on_metadata_name,metadata_name_b, amf_data_size(on_metadata_name));
TSIOBufferWrite(modify_meta_buffer, metadata_name_b, (int64_t)amf_data_size(on_metadata_name));
byte *on_medata_data_b = (byte *)TSmalloc(sizeof(byte) * amf_data_size(on_metadata));
amf_data_buffer_write(on_metadata,on_medata_data_b, amf_data_size(on_metadata));
TSIOBufferWrite(modify_meta_buffer, on_medata_data_b, (int64_t)amf_data_size(on_metadata));
/* first "previous tag size" */
uint32_be size = swap_uint32(prev_tag_size);
TSIOBufferWrite(modify_meta_buffer, &size, (int64_t)sizeof(uint32_be));
//将非meta的数据copy
TSIOBufferCopy(modify_meta_buffer, copy_meta_reader,TSIOBufferReaderAvail(copy_meta_reader) , 0);
amf_data_free(on_metadata);
amf_data_free(on_metadata_name);
return 1;
}
static int64_t IOBufferReaderCopy(TSIOBufferReader readerp, void *buf,
int64_t length) {
int64_t avail, need, n;
const char *start;
TSIOBufferBlock blk;
n = 0;
blk = TSIOBufferReaderStart(readerp);
while (blk) {
start = TSIOBufferBlockReadStart(blk, readerp, &avail);
need = length < avail ? length : avail;
if (need > 0) {
memcpy((char *) buf + n, start, need);
length -= need;
n += need;
}
if (length == 0)
break;
blk = TSIOBufferBlockNext(blk);
}
return n;
}
int FlvTag::flv_read_metadata(byte *stream,amf_data ** name, amf_data ** data, size_t maxbytes) {
amf_data * d;
// byte error_code;
/* read metadata name */
// d = amf_data_file_read(stream);
d = amf_data_buffer_read(stream,maxbytes);
*name = d;
// error_code = amf_data_get_error_code(d);
size_t name_length = amf_data_size(d);
/* if only name can be read, metadata are invalid */
// data_size = amf_data_size(d);
/* read metadata contents */
d = amf_data_buffer_read(stream+name_length ,maxbytes);
*data = d;
// error_code = amf_data_get_error_code(d);
// data_size = amf_data_size(d);
return 0;
}
/* get string representing given AMF type */
static const char * get_amf_type_string(byte type) {
switch (type) {
case AMF_TYPE_NUMBER:
return "Number";
case AMF_TYPE_BOOLEAN:
return "Boolean";
case AMF_TYPE_STRING:
return "String";
case AMF_TYPE_NULL:
return "Null";
case AMF_TYPE_UNDEFINED:
return "Undefined";
/*case AMF_TYPE_REFERENCE:*/
case AMF_TYPE_OBJECT:
return "Object";
case AMF_TYPE_ASSOCIATIVE_ARRAY:
return "Associative array";
case AMF_TYPE_ARRAY:
return "Array";
case AMF_TYPE_DATE:
return "Date";
/*case AMF_TYPE_SIMPLEOBJECT:*/
case AMF_TYPE_XML:
return "XML";
case AMF_TYPE_CLASS:
return "Class";
default:
return "Unknown type";
}
}
size_t FlvTag::get_flv_tag_size() {
flv_tag tag;
return (sizeof(tag.type) + sizeof(tag.body_length) +sizeof(tag.timestamp) + sizeof(tag.timestamp_extended) + sizeof(tag.stream_id));
}
int FlvTag::flv_read_flv_tag(TSIOBufferReader readerp, flv_tag * tag) {
size_t flv_tag_size = get_flv_tag_size();
byte buf[flv_tag_size];
IOBufferReaderCopy(readerp, buf, flv_tag_size);
memcpy(&tag->type,buf,sizeof(tag->type));
memcpy(&tag->body_length,buf + sizeof(tag->type),sizeof(tag->body_length));
memcpy(&tag->timestamp,buf +sizeof(tag->type) +sizeof(tag->body_length) ,sizeof(tag->timestamp));
memcpy(&tag->timestamp_extended,buf + sizeof(tag->type) +sizeof(tag->body_length) +sizeof(tag->timestamp),sizeof(tag->timestamp_extended));
memcpy(&tag->stream_id,buf + sizeof(tag->type) +sizeof(tag->body_length) +sizeof(tag->timestamp) +sizeof(tag->timestamp_extended),sizeof(tag->stream_id));
return 0;
}
size_t FlvTag::get_flv_header_size() {
flv_header header;
return (sizeof(header.signature) + sizeof(header.version) +sizeof(header.flags) + sizeof(header.offset));
}
int FlvTag::flv_read_flv_header(TSIOBufferReader readerp, flv_header * header) {
IOBufferReaderCopy(readerp, &header->signature, sizeof(header->signature));
TSIOBufferReaderConsume(readerp, sizeof(header->signature));
IOBufferReaderCopy(readerp, &header->version, sizeof(header->version));
TSIOBufferReaderConsume(readerp, sizeof(header->version));
IOBufferReaderCopy(readerp, &header->flags, sizeof(header->flags));
TSIOBufferReaderConsume(readerp, sizeof(header->flags));
IOBufferReaderCopy(readerp, &header->offset, sizeof(header->offset));
TSIOBufferReaderConsume(readerp, sizeof(header->offset));
if (header->signature[0] != 'F'
|| header->signature[1] != 'L'
|| header->signature[2] != 'V') {
this->end = 0;
return -1;
}
return 0;
}
void FlvTag::create_copy_meta_buffer() {
copy_meta_buffer = TSIOBufferCreate();
copy_meta_reader = TSIOBufferReaderAlloc(copy_meta_buffer);
}
void FlvTag::clear_copy_meta_buffer(){
if (copy_meta_reader) {
TSIOBufferReaderFree(copy_meta_reader);
copy_meta_reader = NULL;
}
if (copy_meta_buffer) {
TSIOBufferDestroy(copy_meta_buffer);
copy_meta_buffer = NULL;
}
}
| 34.141479 | 155 | 0.678345 | [
"object"
] |
155c5fc58d72c2fd1bc210ea6e96cb4643f4e79a | 5,745 | hxx | C++ | main/svx/inc/svx/EnhancedCustomShapeFunctionParser.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/svx/inc/svx/EnhancedCustomShapeFunctionParser.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/svx/inc/svx/EnhancedCustomShapeFunctionParser.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*************************************************************/
#ifndef _ENHANCEDCUSTOMSHAPEFUNCTIONPARSER_HXX
#define _ENHANCEDCUSTOMSHAPEFUNCTIONPARSER_HXX
#include <sal/config.h>
#include <boost/shared_ptr.hpp>
#include "EnhancedCustomShapeFunctionParser.hxx"
#include <com/sun/star/drawing/EnhancedCustomShapeParameter.hpp>
#include <com/sun/star/drawing/EnhancedCustomShapeParameterType.hpp>
#include <vector>
#include <svx/svxdllapi.h>
struct EnhancedCustomShapeEquation
{
sal_Int32 nOperation;
sal_Int32 nPara[ 3 ];
EnhancedCustomShapeEquation() :
nOperation ( 0 )
{
nPara[ 0 ] = nPara[ 1 ] = nPara[ 2 ] = 0;
}
};
class EnhancedCustomShape2d;
namespace EnhancedCustomShape {
enum ExpressionFunct
{
FUNC_CONST,
ENUM_FUNC_PI,
ENUM_FUNC_LEFT,
ENUM_FUNC_TOP,
ENUM_FUNC_RIGHT,
ENUM_FUNC_BOTTOM,
ENUM_FUNC_XSTRETCH,
ENUM_FUNC_YSTRETCH,
ENUM_FUNC_HASSTROKE,
ENUM_FUNC_HASFILL,
ENUM_FUNC_WIDTH,
ENUM_FUNC_HEIGHT,
ENUM_FUNC_LOGWIDTH,
ENUM_FUNC_LOGHEIGHT,
ENUM_FUNC_ADJUSTMENT,
ENUM_FUNC_EQUATION,
UNARY_FUNC_ABS,
UNARY_FUNC_SQRT,
UNARY_FUNC_SIN,
UNARY_FUNC_COS,
UNARY_FUNC_TAN,
UNARY_FUNC_ATAN,
UNARY_FUNC_NEG,
BINARY_FUNC_PLUS,
BINARY_FUNC_MINUS,
BINARY_FUNC_MUL,
BINARY_FUNC_DIV,
BINARY_FUNC_MIN,
BINARY_FUNC_MAX,
BINARY_FUNC_ATAN2,
TERNARY_FUNC_IF
};
#define EXPRESSION_FLAG_SUMANGLE_MODE 1
SVX_DLLPUBLIC void FillEquationParameter( const com::sun::star::drawing::EnhancedCustomShapeParameter&, const sal_Int32, EnhancedCustomShapeEquation& );
class ExpressionNode
{
public:
virtual ~ExpressionNode();
/** Predicate whether this node is constant.
This predicate returns true, if this node is
neither time- nor ViewInfo dependent. This allows
for certain obtimizations, i.e. not the full
expression tree needs be represented by
ExpressionNodes.
@returns true, if the note is constant
*/
virtual bool isConstant() const = 0;
/** Operator to calculate function value.
This method calculates the function value.
*/
virtual double operator()() const = 0;
/** Operator to retrieve the type of expression node
*/
virtual ExpressionFunct getType() const = 0;
/** Operator to retrieve the ms version of expression
*/
virtual com::sun::star::drawing::EnhancedCustomShapeParameter fillNode(
std::vector< EnhancedCustomShapeEquation >& rEquations, ExpressionNode* pOptionalArg, sal_uInt32 nFlags ) = 0;
};
typedef ::boost::shared_ptr< ExpressionNode > ExpressionNodeSharedPtr;
/** This exception is thrown, when the arithmetic expression
parser failed to parse a string.
*/
struct ParseError
{
ParseError() {}
ParseError( const char* ) {}
};
class FunctionParser
{
public:
/** Parse a string
The following grammar is accepted by this method:
<code>
number_digit = '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'
number = number number_digit | number_digit
identifier = 'pi'|'left'|'top'|'right'|'bottom'|'xstretch'|'ystretch'|
'hasstroke'|'hasfill'|'width'|'height'|'logwidth'|'logheight'
unary_function = 'abs'|'sqrt'|'sin'|'cos'|'tan'|'atan'
binary_function = 'min'|'max'|'atan2'
ternary_function = 'if'
function_reference = '?' 'a-z,A-Z,0-9' ' '
modifier_reference = '$' '0-9' ' '
basic_expression =
number |
identifier |
function_reference |
unary_function '(' additive_expression ')' |
binary_function '(' additive_expression ',' additive_expression ')' |
ternary_function '(' additive_expression ',' additive_expression ',
' additive_expression ')' | '(' additive_expression ')'
unary_expression = '-' basic_expression
multiplicative_expression =
basic_expression |
multiplicative_expression '*' basic_expression |
multiplicative_expression '/' basic_expression
additive_expression =
multiplicative_expression |
additive_expression '+' multiplicative_expression |
additive_expression '-' multiplicative_expression
</code>
@param rFunction
The string to parse
@param rCustoShape
The CustomShape is required for calculation of dynamic values such
"hasstroke", function references and or modifier references ...
@throws ParseError if an invalid expression is given.
@return the generated function object.
*/
SVX_DLLPUBLIC static ExpressionNodeSharedPtr parseFunction( const ::rtl::OUString& rFunction, const EnhancedCustomShape2d& rCustoShape );
private:
// disabled constructor/destructor, since this is
// supposed to be a singleton
FunctionParser();
// default: disabled copy/assignment
FunctionParser(const FunctionParser&);
FunctionParser& operator=( const FunctionParser& );
};
}
#endif /* _ENHANCEDCUSTOMSHAPEFUNCTIONPARSER_HXX */
| 27.227488 | 152 | 0.706005 | [
"object",
"vector"
] |
155ddf6a860a9b0cddc8b3cab3fda817c41dd0f3 | 1,625 | cpp | C++ | Algorithm_C/Algorithm_C/LeetCode/01_TwoSum/TwoSum.cpp | chm994483868/HMDailyLearningRecord | 95ff0a5347927ce4527bcdd70374e5be22bfc60d | [
"MIT"
] | 2 | 2021-06-26T08:07:04.000Z | 2021-08-03T06:05:40.000Z | Algorithm_C/Algorithm_C/LeetCode/01_TwoSum/TwoSum.cpp | chm994483868/HMDailyLearningRecord | 95ff0a5347927ce4527bcdd70374e5be22bfc60d | [
"MIT"
] | null | null | null | Algorithm_C/Algorithm_C/LeetCode/01_TwoSum/TwoSum.cpp | chm994483868/HMDailyLearningRecord | 95ff0a5347927ce4527bcdd70374e5be22bfc60d | [
"MIT"
] | null | null | null | //
// TwoSum.cpp
// Algorithm_C
//
// Created by CHM on 2020/8/5.
// Copyright © 2020 CHM. All rights reserved.
//
#include "TwoSum.hpp"
vector<int> TwoSum::twoSum(vector<int>& nums, int target) {
map<int, int> a;
vector<int> b(2, -1);
for (int i = 0; i < nums.size(); ++i) {
if (a.count(target - nums[i]) > 0) {
b[0] = a[target - nums[i]];
b[1] = i;
}
a.insert(map<int, int>::value_type(nums[i], i));
}
return b;
}
void mapPractice() {
std::map<int, string> personnel;
typedef map<int, string> UDT_MAP_INT_STRING;
UDT_MAP_INT_STRING enumMap;
// 定义一个 map 对象
map<int, string> mapStudent;
// 第一种 用 insert 函数插入 pair
mapStudent.insert(pair<int, string>(000, "student_zero"));
// 第二种 用 insert 函数插入 value_type 数据
mapStudent.insert(map<int, string>::value_type(001, "student_one"));
// 第三种 用 array 方式插入
mapStudent[123] = "student_first";
mapStudent[456] = "student_second";
// 构造定义,返回一个 pair 对象
pair<map<int, string>::iterator, bool> Insert_Pair;
Insert_Pair = mapStudent.insert(map<int, string>::value_type(001, "student_one"));
if (!Insert_Pair.second) {
printf("Error insert new element");
}
map<int, string>::iterator iter = mapStudent.find(123);
if (iter != mapStudent.end()) {
// 删除元素
// 用关键字删除
mapStudent.erase(123);
// 用迭代器删除
mapStudent.erase(mapStudent.begin(), mapStudent.end());
// map 大小
unsigned long nSize = mapStudent.size();
printf("%ld", nSize);
}
}
| 26.639344 | 86 | 0.574769 | [
"vector"
] |
1562334380d01ea89fdae0d803c44fa147dc8d2a | 3,381 | cpp | C++ | source/MLPartMgr.cpp | luk036/ckpttn-cpp | 9d15cdadf5e6b968e6e6a9d5e3db500256a11a6f | [
"Unlicense"
] | null | null | null | source/MLPartMgr.cpp | luk036/ckpttn-cpp | 9d15cdadf5e6b968e6e6a9d5e3db500256a11a6f | [
"Unlicense"
] | 1 | 2021-07-24T12:00:14.000Z | 2021-08-11T04:35:10.000Z | source/MLPartMgr.cpp | luk036/ckpttn-cpp | 9d15cdadf5e6b968e6e6a9d5e3db500256a11a6f | [
"Unlicense"
] | null | null | null | #include <ckpttn/FMConstrMgr.hpp> // for LegalCheck, LegalCheck::allsatisfied
#include <ckpttn/MLPartMgr.hpp> // for MLPartMgr
#include <cstdint> // for uint8_t
#include <gsl/span> // for span
#include <memory> // for unique_ptr
#include <py2cpp/set.hpp> // for set
#include <utility> // for pair
#include <vector> // for vector
#include "ckpttn/HierNetlist.hpp" // for HierNetlist, SimpleHierNetlist
#include "ckpttn/netlist.hpp" // for SimpleNetlist
// #include <iostream>
using node_t = typename SimpleNetlist::node_t;
extern auto create_contraction_subgraph(const SimpleNetlist&, const py::set<node_t>&)
-> std::unique_ptr<SimpleHierNetlist>;
/**
* @brief run_Partition
*
* @tparam Gnl
* @tparam PartMgr
* @param H
* @param[in] H
* @param[in,out] part
* @return LegalCheck
*/
template <typename Gnl, typename PartMgr>
auto MLPartMgr::run_FMPartition(const Gnl& H, gsl::span<std::uint8_t> part) -> LegalCheck {
using GainMgr = typename PartMgr::GainMgr_;
using ConstrMgr = typename PartMgr::ConstrMgr_;
auto legalcheck_fn = [&]() {
GainMgr gainMgr(H, this->K);
ConstrMgr constrMgr(H, this->BalTol, this->K);
PartMgr partMgr(H, gainMgr, constrMgr, this->K);
auto legalcheck = partMgr.legalize(part);
return std::make_pair(legalcheck, partMgr.totalcost);
// release memory resource all memory saving
};
auto optimize_fn = [&]() {
GainMgr gainMgr(H, this->K);
ConstrMgr constrMgr(H, this->BalTol, this->K);
PartMgr partMgr(H, gainMgr, constrMgr, this->K);
partMgr.optimize(part);
return partMgr.totalcost;
// release memory resource all memory saving
};
auto legalcheck_cost = legalcheck_fn();
if (legalcheck_cost.first != LegalCheck::allsatisfied) {
this->totalcost = legalcheck_cost.second;
return legalcheck_cost.first;
}
if (H.number_of_modules() >= this->limitsize) { // OK
const auto H2 = create_contraction_subgraph(H, py::set<typename Gnl::node_t>{});
if (H2->number_of_modules() <= H.number_of_modules()) {
auto part2 = std::vector<std::uint8_t>(H2->number_of_modules(), 0);
H2->projection_up(part, part2);
auto legalcheck_recur = this->run_FMPartition<Gnl, PartMgr>(*H2, part2);
if (legalcheck_recur == LegalCheck::allsatisfied) {
H2->projection_down(part2, part);
}
}
}
this->totalcost = optimize_fn();
return legalcheck_cost.first;
}
#include <ckpttn/FMBiConstrMgr.hpp> // for FMBiConstrMgr
#include <ckpttn/FMBiGainMgr.hpp> // for FMBiGainMgr
#include <ckpttn/FMKWayConstrMgr.hpp> // for FMKWayConstrMgr
#include <ckpttn/FMKWayGainMgr.hpp> // for FMKWayGainMgr
#include <ckpttn/FMPartMgr.hpp> // for FMPartMgr
template auto MLPartMgr::run_FMPartition<
SimpleNetlist,
FMPartMgr<SimpleNetlist, FMBiGainMgr<SimpleNetlist>, FMBiConstrMgr<SimpleNetlist>>>(
const SimpleNetlist& H, gsl::span<std::uint8_t> part) -> LegalCheck;
template auto MLPartMgr::run_FMPartition<
SimpleNetlist,
FMPartMgr<SimpleNetlist, FMKWayGainMgr<SimpleNetlist>, FMKWayConstrMgr<SimpleNetlist>>>(
const SimpleNetlist& H, gsl::span<std::uint8_t> part) -> LegalCheck;
| 38.420455 | 92 | 0.659272 | [
"vector"
] |
156469af45c7a3f8f4858d674487ca5944956198 | 7,986 | cc | C++ | pw_protobuf/encoder.cc | curtin-space/pigweed | fe2e1743e03fabd2676f01d9de0ac9d34a426076 | [
"Apache-2.0"
] | 86 | 2021-03-09T23:49:40.000Z | 2022-03-30T08:14:51.000Z | pw_protobuf/encoder.cc | curtin-space/pigweed | fe2e1743e03fabd2676f01d9de0ac9d34a426076 | [
"Apache-2.0"
] | 4 | 2021-07-27T20:32:03.000Z | 2022-03-08T10:39:07.000Z | pw_protobuf/encoder.cc | curtin-space/pigweed | fe2e1743e03fabd2676f01d9de0ac9d34a426076 | [
"Apache-2.0"
] | 22 | 2021-03-11T15:15:47.000Z | 2022-02-09T06:16:36.000Z | // Copyright 2021 The Pigweed Authors
//
// 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
//
// https://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 "pw_protobuf/encoder.h"
#include <cstddef>
#include <cstring>
#include <span>
#include "pw_assert/check.h"
#include "pw_bytes/span.h"
#include "pw_protobuf/serialized_size.h"
#include "pw_protobuf/wire_format.h"
#include "pw_status/status.h"
#include "pw_status/try.h"
#include "pw_stream/memory_stream.h"
#include "pw_stream/stream.h"
#include "pw_varint/varint.h"
namespace pw::protobuf {
StreamEncoder StreamEncoder::GetNestedEncoder(uint32_t field_number) {
PW_CHECK(!nested_encoder_open());
PW_CHECK(ValidFieldNumber(field_number));
nested_field_number_ = field_number;
// Pass the unused space of the scratch buffer to the nested encoder to use
// as their scratch buffer.
size_t key_size =
varint::EncodedSize(FieldKey(field_number, WireType::kDelimited));
size_t reserved_size = key_size + config::kMaxVarintSize;
size_t max_size = std::min(memory_writer_.ConservativeWriteLimit(),
writer_.ConservativeWriteLimit());
// Account for reserved bytes.
max_size = max_size > reserved_size ? max_size - reserved_size : 0;
// Cap based on max varint size.
max_size = std::min(varint::MaxValueInBytes(config::kMaxVarintSize),
static_cast<uint64_t>(max_size));
ByteSpan nested_buffer;
if (max_size > 0) {
nested_buffer = ByteSpan(
memory_writer_.data() + reserved_size + memory_writer_.bytes_written(),
max_size);
} else {
nested_buffer = ByteSpan();
}
return StreamEncoder(*this, nested_buffer);
}
StreamEncoder::~StreamEncoder() {
// If this was an invalidated StreamEncoder which cannot be used, permit the
// object to be cleanly destructed by doing nothing.
if (nested_field_number_ == kFirstReservedNumber) {
return;
}
PW_CHECK(
!nested_encoder_open(),
"Tried to destruct a proto encoder with an active submessage encoder");
if (parent_ != nullptr) {
parent_->CloseNestedMessage(*this);
}
}
void StreamEncoder::CloseNestedMessage(StreamEncoder& nested) {
PW_DCHECK_PTR_EQ(nested.parent_,
this,
"CloseNestedMessage() called on the wrong Encoder parent");
// Make the nested encoder look like it has an open child to block writes for
// the remainder of the object's life.
nested.nested_field_number_ = kFirstReservedNumber;
nested.parent_ = nullptr;
// Temporarily cache the field number of the child so we can re-enable
// writing to this encoder.
uint32_t temp_field_number = nested_field_number_;
nested_field_number_ = 0;
// TODO(amontanez): If a submessage fails, we could optionally discard
// it and continue happily. For now, we'll always invalidate the entire
// encoder if a single submessage fails.
status_.Update(nested.status_);
if (!status_.ok()) {
return;
}
if (varint::EncodedSize(nested.memory_writer_.bytes_written()) >
config::kMaxVarintSize) {
status_ = Status::OutOfRange();
return;
}
status_ = WriteLengthDelimitedField(temp_field_number,
nested.memory_writer_.WrittenData());
}
Status StreamEncoder::WriteVarintField(uint32_t field_number, uint64_t value) {
PW_TRY(UpdateStatusForWrite(
field_number, WireType::kVarint, varint::EncodedSize(value)));
WriteVarint(FieldKey(field_number, WireType::kVarint))
.IgnoreError(); // TODO(pwbug/387): Handle Status properly
return WriteVarint(value);
}
Status StreamEncoder::WriteLengthDelimitedField(uint32_t field_number,
ConstByteSpan data) {
PW_TRY(UpdateStatusForWrite(field_number, WireType::kDelimited, data.size()));
status_.Update(WriteLengthDelimitedKeyAndLengthPrefix(
field_number, data.size(), writer_));
PW_TRY(status_);
if (Status status = writer_.Write(data); !status.ok()) {
status_ = status;
}
return status_;
}
Status StreamEncoder::WriteLengthDelimitedFieldFromStream(
uint32_t field_number,
stream::Reader& bytes_reader,
size_t num_bytes,
ByteSpan stream_pipe_buffer) {
PW_CHECK_UINT_GT(
stream_pipe_buffer.size(), 0, "Transfer buffer cannot be 0 size");
PW_TRY(UpdateStatusForWrite(field_number, WireType::kDelimited, num_bytes));
status_.Update(
WriteLengthDelimitedKeyAndLengthPrefix(field_number, num_bytes, writer_));
PW_TRY(status_);
// Stream data from `bytes_reader` to `writer_`.
// TODO(pwbug/468): move the following logic to pw_stream/copy.h at a later
// time.
for (size_t bytes_written = 0; bytes_written < num_bytes;) {
const size_t chunk_size_bytes =
std::min(num_bytes - bytes_written, stream_pipe_buffer.size_bytes());
const Result<ByteSpan> read_result =
bytes_reader.Read(stream_pipe_buffer.data(), chunk_size_bytes);
status_.Update(read_result.status());
PW_TRY(status_);
status_.Update(writer_.Write(read_result.value()));
PW_TRY(status_);
bytes_written += read_result.value().size();
}
return OkStatus();
}
Status StreamEncoder::WriteFixed(uint32_t field_number, ConstByteSpan data) {
WireType type =
data.size() == sizeof(uint32_t) ? WireType::kFixed32 : WireType::kFixed64;
PW_TRY(UpdateStatusForWrite(field_number, type, data.size()));
WriteVarint(FieldKey(field_number, type))
.IgnoreError(); // TODO(pwbug/387): Handle Status properly
if (Status status = writer_.Write(data); !status.ok()) {
status_ = status;
}
return status_;
}
Status StreamEncoder::WritePackedFixed(uint32_t field_number,
std::span<const std::byte> values,
size_t elem_size) {
if (values.empty()) {
return status_;
}
PW_CHECK_NOTNULL(values.data());
PW_DCHECK(elem_size == sizeof(uint32_t) || elem_size == sizeof(uint64_t));
PW_TRY(UpdateStatusForWrite(
field_number, WireType::kDelimited, values.size_bytes()));
WriteVarint(FieldKey(field_number, WireType::kDelimited))
.IgnoreError(); // TODO(pwbug/387): Handle Status properly
WriteVarint(values.size_bytes())
.IgnoreError(); // TODO(pwbug/387): Handle Status properly
for (auto val_start = values.begin(); val_start != values.end();
val_start += elem_size) {
// Allocates 8 bytes so both 4-byte and 8-byte types can be encoded as
// little-endian for serialization.
std::array<std::byte, sizeof(uint64_t)> data;
if (std::endian::native == std::endian::little) {
std::copy(val_start, val_start + elem_size, std::begin(data));
} else {
std::reverse_copy(val_start, val_start + elem_size, std::begin(data));
}
status_.Update(writer_.Write(std::span(data).first(elem_size)));
PW_TRY(status_);
}
return status_;
}
Status StreamEncoder::UpdateStatusForWrite(uint32_t field_number,
WireType type,
size_t data_size) {
PW_CHECK(!nested_encoder_open());
PW_TRY(status_);
if (!ValidFieldNumber(field_number)) {
return status_ = Status::InvalidArgument();
}
const Result<size_t> field_size = SizeOfField(field_number, type, data_size);
status_.Update(field_size.status());
PW_TRY(status_);
if (field_size.value() > writer_.ConservativeWriteLimit()) {
status_ = Status::ResourceExhausted();
}
return status_;
}
} // namespace pw::protobuf
| 34.274678 | 80 | 0.697596 | [
"object"
] |
15649c1efe61adfa7d63c36382e6b6b50fcf5601 | 1,051 | cpp | C++ | aws-cpp-sdk-elasticfilesystem/source/model/UpdateFileSystemRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-elasticfilesystem/source/model/UpdateFileSystemRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-elasticfilesystem/source/model/UpdateFileSystemRequest.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2022-02-28T21:36:42.000Z | 2022-02-28T21:36:42.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/elasticfilesystem/model/UpdateFileSystemRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::EFS::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
UpdateFileSystemRequest::UpdateFileSystemRequest() :
m_fileSystemIdHasBeenSet(false),
m_throughputMode(ThroughputMode::NOT_SET),
m_throughputModeHasBeenSet(false),
m_provisionedThroughputInMibps(0.0),
m_provisionedThroughputInMibpsHasBeenSet(false)
{
}
Aws::String UpdateFileSystemRequest::SerializePayload() const
{
JsonValue payload;
if(m_throughputModeHasBeenSet)
{
payload.WithString("ThroughputMode", ThroughputModeMapper::GetNameForThroughputMode(m_throughputMode));
}
if(m_provisionedThroughputInMibpsHasBeenSet)
{
payload.WithDouble("ProvisionedThroughputInMibps", m_provisionedThroughputInMibps);
}
return payload.View().WriteReadable();
}
| 23.355556 | 106 | 0.778306 | [
"model"
] |
d07ee3333c99aacc70c7ccf4692063bcdca112c9 | 15,116 | cpp | C++ | PuzzleCommon/PuzzleImageSource.cpp | x-sheep/puzzles | 86c38672865a6e2acb3386c0f3b12954a4c2a257 | [
"MIT"
] | 5 | 2017-05-02T08:53:03.000Z | 2020-12-07T02:04:15.000Z | PuzzleCommon/PuzzleImageSource.cpp | x-sheep/puzzles | 86c38672865a6e2acb3386c0f3b12954a4c2a257 | [
"MIT"
] | 7 | 2019-07-18T00:06:02.000Z | 2022-02-20T20:10:47.000Z | PuzzleCommon/PuzzleImageSource.cpp | x-sheep/puzzles | 86c38672865a6e2acb3386c0f3b12954a4c2a257 | [
"MIT"
] | null | null | null | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// 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 "IPuzzleCanvas.h"
#include "windows.ui.xaml.media.dxinterop.h"
#include "PuzzleImageSource.h"
using namespace Platform;
using namespace Microsoft::WRL;
using namespace Windows::ApplicationModel;
using namespace Windows::Graphics::Display;
using namespace Windows::UI;
using namespace Windows::UI::Xaml;
using namespace Windows::Foundation::Collections;
namespace PuzzleCommon
{
PuzzleImageSource::PuzzleImageSource()
{
Application::Current->Suspending += ref new SuspendingEventHandler(this, &PuzzleImageSource::OnSuspending);
}
SurfaceImageSource ^PuzzleImageSource::CreateImageSource(int pixelWidth, int pixelHeight)
{
m_imageSource = ref new SurfaceImageSource(pixelWidth, pixelHeight, true);
m_width = pixelWidth;
m_height = pixelHeight;
m_clipActive = false;
CreateDeviceResources();
return m_imageSource;
}
// Initialize hardware-dependent resources.
void PuzzleImageSource::CreateDeviceResources()
{
// This flag adds support for surfaces with a different color channel ordering
// than the API default. It is required for compatibility with Direct2D.
UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#if defined(_DEBUG)
// If the project is in a debug build, enable debugging via SDK Layers.
creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
// This array defines the set of DirectX hardware feature levels this app will support.
// Note the ordering should be preserved.
// Don't forget to declare your application's minimum required feature level in its
// description. All applications are assumed to support 9.1 unless otherwise stated.
const D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
D3D_FEATURE_LEVEL_9_3,
D3D_FEATURE_LEVEL_9_2,
D3D_FEATURE_LEVEL_9_1,
};
D2D1CreateFactory(
D2D1_FACTORY_TYPE_SINGLE_THREADED,
__uuidof(ID2D1Factory1),
nullptr,
&m_d2dFactory
);
// Create the Direct3D 11 API device object.
ThrowIfFailed(
D3D11CreateDevice(
nullptr, // Specify nullptr to use the default adapter.
D3D_DRIVER_TYPE_HARDWARE,
nullptr,
creationFlags, // Set debug and Direct2D compatibility flags.
featureLevels, // List of feature levels this app can support.
ARRAYSIZE(featureLevels),
D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION for Windows Store apps.
&m_d3dDevice, // Returns the Direct3D device created.
nullptr,
nullptr
)
);
// Get the Direct3D 11.1 API device.
ComPtr<IDXGIDevice> dxgiDevice;
ThrowIfFailed(
m_d3dDevice.As(&dxgiDevice)
);
// Create the Direct2D device object and a corresponding context.
ThrowIfFailed(
m_d2dFactory->CreateDevice(
dxgiDevice.Get(),
&m_d2dDevice
)
);
ThrowIfFailed(
m_d2dDevice->CreateDeviceContext(
D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
&m_d2dBufferContext
)
);
ThrowIfFailed(
DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED,
__uuidof(IDWriteFactory),
&m_dwriteFactory
)
);
// Query for ISurfaceImageSourceNative interface.
Microsoft::WRL::ComPtr<ISurfaceImageSourceNative> sisNative;
ThrowIfFailed(
reinterpret_cast<IUnknown*>(m_imageSource)->QueryInterface(IID_PPV_ARGS(&sisNative))
);
// Associate the DXGI device with the SurfaceImageSource.
ThrowIfFailed(
sisNative->SetDevice(dxgiDevice.Get())
);
m_d2dContext = nullptr;
m_blitters.clear();
}
void PuzzleImageSource::LoadFontMetrics(ComPtr<IDWriteTextFormat> textFormat, DWRITE_FONT_METRICS *target)
{
IDWriteFontCollection* collection;
TCHAR name[64]; UINT32 findex; BOOL exists;
textFormat->GetFontFamilyName(name, 64);
textFormat->GetFontCollection(&collection);
collection->FindFamilyName(name, &findex, &exists);
IDWriteFontFamily *ffamily;
collection->GetFontFamily(findex, &ffamily);
IDWriteFont* font;
ffamily->GetFirstMatchingFont(textFormat->GetFontWeight(), textFormat->GetFontStretch(), textFormat->GetFontStyle(), &font);
font->GetMetrics(target);
}
void PuzzleImageSource::BlitterNew(int id, uint32 w, uint32 h)
{
// No-op. The bitmap can only be created after drawing has started.
}
void PuzzleImageSource::BlitterSave(int id, int x, int y, int w, int h)
{
if (!m_blitters[id])
{
ComPtr<ID2D1Bitmap> bitmap;
auto size = D2D1::SizeU(w, h);
D2D1_BITMAP_PROPERTIES props;
props.pixelFormat = m_d2dBufferContext->GetPixelFormat();
m_d2dBufferContext->GetDpi(&props.dpiX, &props.dpiY);
ThrowIfFailed(
m_d2dBufferContext->CreateBitmap(size, nullptr, 0, props, &bitmap)
);
m_blitters[id] = bitmap;
}
auto rect = D2D1::RectU(x, y, x + w, y + h);
m_blitters[id]->CopyFromRenderTarget(nullptr, m_d2dContext.Get(), &rect);
}
void PuzzleImageSource::BlitterLoad(int id, int x, int y, int w, int h)
{
auto rect = D2D1::RectF(x, y, x + w, y + h);
auto srcRect = D2D1::RectF(0, 0, w, h);
m_d2dContext->DrawBitmap(m_blitters[id].Get(), &rect, 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, &srcRect);
}
void PuzzleImageSource::BlitterFree(int id)
{
m_blitters.erase(id);
}
// Begins drawing, allowing updates to content in the specified area.
bool PuzzleImageSource::BeginDraw(Windows::Foundation::Rect updateRect)
{
POINT offset;
ComPtr<IDXGISurface> surface;
// Express target area as a native RECT type.
RECT updateRectNative;
updateRectNative.left = static_cast<LONG>(updateRect.Left);
updateRectNative.top = static_cast<LONG>(updateRect.Top);
updateRectNative.right = static_cast<LONG>(updateRect.Right);
updateRectNative.bottom = static_cast<LONG>(updateRect.Bottom);
// Query for ISurfaceImageSourceNative interface.
Microsoft::WRL::ComPtr<ISurfaceImageSourceNative> sisNative;
ThrowIfFailed(
reinterpret_cast<IUnknown*>(m_imageSource)->QueryInterface(IID_PPV_ARGS(&sisNative))
);
// Begin drawing - returns a target surface and an offset to use as the top left origin when drawing.
HRESULT beginDrawHR = sisNative->BeginDraw(updateRectNative, &surface, &offset);
if (SUCCEEDED(beginDrawHR))
{
Microsoft::WRL::ComPtr<ID2D1Bitmap1> bitmap;
ThrowIfFailed(
m_d2dBufferContext->CreateBitmapFromDxgiSurface(
surface.Get(),
nullptr,
&bitmap
)
);
// Begin drawing using D2D context.
m_d2dBufferContext->BeginDraw();
// Set context's render target.
m_d2dBufferContext->SetTarget(bitmap.Get());
if (!m_d2dContext)
{
m_d2dBufferContext->CreateCompatibleRenderTarget(&m_d2dContext);
}
auto clip = D2D1::RectF(
static_cast<float>(offset.x),
static_cast<float>(offset.y),
static_cast<float>(offset.x + updateRect.Width),
static_cast<float>(offset.y + updateRect.Height)
);
auto translation = D2D1::Matrix3x2F::Translation(
static_cast<float>(offset.x),
static_cast<float>(offset.y)
);
// Apply a clip and transform to constrain updates to the target update area.
// This is required to ensure coordinates within the target surface remain
// consistent by taking into account the offset returned by BeginDraw, and
// can also improve performance by optimizing the area that is drawn by D2D.
// Apps should always account for the offset output parameter returned by
// BeginDraw, since it may not match the passed updateRect input parameter's location.
m_d2dBufferContext->PushAxisAlignedClip(clip,
D2D1_ANTIALIAS_MODE_ALIASED
);
m_d2dBufferContext->SetTransform(translation);
m_d2dContext->BeginDraw();
return true;
}
else if (beginDrawHR == DXGI_ERROR_DEVICE_REMOVED || beginDrawHR == DXGI_ERROR_DEVICE_RESET)
{
// If the device has been removed or reset, attempt to recreate it and continue drawing.
CreateDeviceResources();
return BeginDraw(updateRect);
}
else
{
OutputDebugString(("Skipping BeginDraw " + beginDrawHR.ToString() + "\n")->Data());
return false;
}
}
// Ends drawing updates started by a previous BeginDraw call.
bool PuzzleImageSource::EndDraw()
{
bool success = true;
HRESULT endDrawHR;
endDrawHR = m_d2dContext->EndDraw();
if (endDrawHR == D2DERR_RECREATE_TARGET)
success = false;
else
ThrowIfFailed(endDrawHR);
ComPtr<ID2D1Bitmap> bitmap;
m_d2dContext->GetBitmap(&bitmap);
m_d2dBufferContext->DrawBitmap(bitmap.Get());
// Remove the transform and clip applied in BeginDraw since
// the target area can change on every update.
m_d2dBufferContext->SetTransform(D2D1::IdentityMatrix());
m_d2dBufferContext->PopAxisAlignedClip();
// Remove the render target and end drawing.
endDrawHR = m_d2dBufferContext->EndDraw();
if (endDrawHR == D2DERR_RECREATE_TARGET)
success = false;
else
ThrowIfFailed(endDrawHR);
m_d2dBufferContext->SetTarget(nullptr);
// Query for ISurfaceImageSourceNative interface.
Microsoft::WRL::ComPtr<ISurfaceImageSourceNative> sisNative;
ThrowIfFailed(
reinterpret_cast<IUnknown*>(m_imageSource)->QueryInterface(IID_PPV_ARGS(&sisNative))
);
endDrawHR = sisNative->EndDraw();
if (endDrawHR == D2DERR_RECREATE_TARGET)
success = false;
else
ThrowIfFailed(endDrawHR);
return success;
}
// Clears the background with the given color.
void PuzzleImageSource::Clear(Windows::UI::Color color)
{
m_d2dContext->Clear(ConvertToColorF(color));
}
// Draws a filled rectangle with the given color and position.
void PuzzleImageSource::FillSolidRect(uint32 color, Windows::Foundation::Rect rect)
{
// Create a solid color D2D brush.
ComPtr<ID2D1SolidColorBrush> brush;
ThrowIfFailed(
m_d2dContext->CreateSolidColorBrush(
ConvertToColorF(color),
&brush
)
);
// Draw a filled rectangle.
m_d2dContext->FillRectangle(ConvertToRectF(rect), brush.Get());
}
void PuzzleImageSource::DrawLine(uint32 color, float x1, float y1, float x2, float y2, float thick)
{
ComPtr<ID2D1SolidColorBrush> brush;
ThrowIfFailed(
m_d2dContext->CreateSolidColorBrush(
ConvertToColorF(color),
&brush
)
);
auto p1 = D2D1::Point2F(x1, y1);
auto p2 = D2D1::Point2F(x2, y2);
m_d2dContext->DrawLine(p1, p2, brush.Get(), thick);
}
void PuzzleImageSource::DrawEllipse(uint32 outline, uint32 fill, float x, float y, float rw, float rh)
{
auto ellipse = D2D1::Ellipse(
D2D1::Point2F(x, y),
rw, rh
);
if (outline != ~0)
{
ComPtr<ID2D1SolidColorBrush> outlineBrush;
ThrowIfFailed(
m_d2dContext->CreateSolidColorBrush(
ConvertToColorF(outline),
&outlineBrush
)
);
m_d2dContext->DrawEllipse(ellipse, outlineBrush.Get());
}
if (fill != ~0)
{
ComPtr<ID2D1SolidColorBrush> fillBrush;
ThrowIfFailed(
m_d2dContext->CreateSolidColorBrush(
ConvertToColorF(fill),
&fillBrush
)
);
m_d2dContext->FillEllipse(ellipse, fillBrush.Get());
}
}
void PuzzleImageSource::DrawGeometry(uint32 outline, uint32 fill, IVector<Windows::Foundation::Point> ^points)
{
ComPtr<ID2D1PathGeometry> pathGeometry;
ThrowIfFailed(
m_d2dFactory->CreatePathGeometry(&pathGeometry)
);
ComPtr<ID2D1GeometrySink> geometrySink;
ThrowIfFailed(
pathGeometry->Open(&geometrySink)
);
geometrySink->SetFillMode(D2D1_FILL_MODE_WINDING);
geometrySink->BeginFigure(ConvertToPoint(points->GetAt(points->Size - 1)), D2D1_FIGURE_BEGIN_FILLED);
for (uint32 i = 0; i < points->Size; i++)
{
geometrySink->AddLine(ConvertToPoint(points->GetAt(i)));
}
geometrySink->EndFigure(D2D1_FIGURE_END_CLOSED);
ThrowIfFailed(
geometrySink->Close()
);
if (outline != ~0)
{
ComPtr<ID2D1SolidColorBrush> outlineBrush;
ThrowIfFailed(
m_d2dContext->CreateSolidColorBrush(
ConvertToColorF(outline),
&outlineBrush
)
);
m_d2dContext->DrawGeometry(pathGeometry.Get(), outlineBrush.Get());
}
if (fill != ~0)
{
ComPtr<ID2D1SolidColorBrush> fillBrush;
ThrowIfFailed(
m_d2dContext->CreateSolidColorBrush(
ConvertToColorF(fill),
&fillBrush
)
);
m_d2dContext->FillGeometry(pathGeometry.Get(), fillBrush.Get());
}
}
void PuzzleImageSource::StartClip(Windows::Foundation::Rect rect)
{
if (m_clipActive)
m_d2dContext->PopAxisAlignedClip();
m_d2dContext->PushAxisAlignedClip(ConvertToRectF(rect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
m_clipActive = true;
}
void PuzzleImageSource::EndClip()
{
if (m_clipActive)
m_d2dContext->PopAxisAlignedClip();
m_clipActive = false;
}
void PuzzleImageSource::DrawText(uint32 color, int x, int y, float size, GameFontType fonttype, GameFontHAlign halign, GameFontVAlign valign, Platform::String ^text)
{
ComPtr<IDWriteTextFormat> textFormat;
ThrowIfFailed(
m_dwriteFactory->CreateTextFormat(
fonttype == GameFontType::VariableWidth ? L"Segoe UI" : L"Courier New",
nullptr,
DWRITE_FONT_WEIGHT_NORMAL,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
size,
L"en-us",
&textFormat
)
);
if (fonttype == GameFontType::VariableWidth && !m_variableFontMetrics.designUnitsPerEm)
LoadFontMetrics(textFormat, &m_variableFontMetrics);
else if (fonttype == GameFontType::FixedWidth && !m_fixedFontMetrics.designUnitsPerEm)
LoadFontMetrics(textFormat, &m_fixedFontMetrics);
DWRITE_FONT_METRICS *metrics = fonttype == GameFontType::VariableWidth ? &m_variableFontMetrics : &m_fixedFontMetrics;
ThrowIfFailed(
textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
);
ComPtr<IDWriteTextLayout> textLayout;
ThrowIfFailed(
m_dwriteFactory->CreateTextLayout(
text->Data(),
text->Length(),
textFormat.Get(),
m_width,
m_height,
&textLayout
)
);
ComPtr<ID2D1SolidColorBrush> textBrush;
ThrowIfFailed(
m_d2dContext->CreateSolidColorBrush(
ConvertToColorF(color),
&textBrush
)
);
float fx = x, fy = y, width;
if (valign == GameFontVAlign::VerticalBase)
fy -= metrics->ascent * (size / metrics->designUnitsPerEm);
else
fy -= (metrics->ascent + metrics->descent) * (size / (2*metrics->designUnitsPerEm));
textLayout->DetermineMinWidth(&width);
if (halign == GameFontHAlign::HorizontalCenter)
fx -= width / 2;
else if (halign == GameFontHAlign::HorizontalRight)
fx -= width;
m_d2dContext->DrawTextLayout(
D2D1::Point2F(fx, fy),
textLayout.Get(),
textBrush.Get(),
D2D1_DRAW_TEXT_OPTIONS_NO_SNAP
);
}
void PuzzleImageSource::OnSuspending(Object ^sender, SuspendingEventArgs ^e)
{
ComPtr<IDXGIDevice3> dxgiDevice;
m_d3dDevice.As(&dxgiDevice);
// Hints to the driver that the app is entering an idle state and that its memory can be used temporarily for other apps.
dxgiDevice->Trim();
}
}
| 28.520755 | 166 | 0.721818 | [
"render",
"object",
"transform",
"solid"
] |
d081612c3730d20db0bb1b5c362b40b44155efe6 | 18,550 | cpp | C++ | src/Evolution/Systems/NewtonianEuler/BoundaryCorrections/Hllc.cpp | macedo22/spectre | 97b2b7ae356cf86830258cb5f689f1191fdb6ddd | [
"MIT"
] | 1 | 2018-10-01T06:07:16.000Z | 2018-10-01T06:07:16.000Z | src/Evolution/Systems/NewtonianEuler/BoundaryCorrections/Hllc.cpp | macedo22/spectre | 97b2b7ae356cf86830258cb5f689f1191fdb6ddd | [
"MIT"
] | 4 | 2018-06-04T20:26:40.000Z | 2018-07-27T14:54:55.000Z | src/Evolution/Systems/NewtonianEuler/BoundaryCorrections/Hllc.cpp | macedo22/spectre | 97b2b7ae356cf86830258cb5f689f1191fdb6ddd | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Evolution/Systems/NewtonianEuler/BoundaryCorrections/Hllc.hpp"
#include <cmath>
#include <memory>
#include <optional>
#include <pup.h>
#include "DataStructures/DataVector.hpp"
#include "DataStructures/Tags/TempTensor.hpp"
#include "DataStructures/Tensor/EagerMath/DotProduct.hpp"
#include "DataStructures/Tensor/Tensor.hpp"
#include "DataStructures/Variables.hpp"
#include "Evolution/Systems/NewtonianEuler/SoundSpeedSquared.hpp"
#include "NumericalAlgorithms/DiscontinuousGalerkin/Formulation.hpp"
#include "NumericalAlgorithms/DiscontinuousGalerkin/NormalDotFlux.hpp"
#include "Utilities/GenerateInstantiations.hpp"
#include "Utilities/Gsl.hpp"
namespace NewtonianEuler::BoundaryCorrections {
template <size_t Dim>
Hllc<Dim>::Hllc(CkMigrateMessage* msg) noexcept
: BoundaryCorrection<Dim>(msg) {}
template <size_t Dim>
std::unique_ptr<BoundaryCorrection<Dim>> Hllc<Dim>::get_clone() const noexcept {
return std::make_unique<Hllc>(*this);
}
template <size_t Dim>
void Hllc<Dim>::pup(PUP::er& p) {
BoundaryCorrection<Dim>::pup(p);
}
template <size_t Dim>
template <size_t ThermodynamicDim>
double Hllc<Dim>::dg_package_data(
const gsl::not_null<Scalar<DataVector>*> packaged_mass_density,
const gsl::not_null<tnsr::I<DataVector, Dim, Frame::Inertial>*>
packaged_momentum_density,
const gsl::not_null<Scalar<DataVector>*> packaged_energy_density,
const gsl::not_null<Scalar<DataVector>*> packaged_pressure,
const gsl::not_null<Scalar<DataVector>*>
packaged_normal_dot_flux_mass_density,
const gsl::not_null<tnsr::I<DataVector, Dim, Frame::Inertial>*>
packaged_normal_dot_flux_momentum_density,
const gsl::not_null<Scalar<DataVector>*>
packaged_normal_dot_flux_energy_density,
const gsl::not_null<tnsr::i<DataVector, Dim, Frame::Inertial>*>
packaged_interface_unit_normal,
const gsl::not_null<Scalar<DataVector>*> packaged_normal_dot_velocity,
const gsl::not_null<Scalar<DataVector>*>
packaged_largest_outgoing_char_speed,
const gsl::not_null<Scalar<DataVector>*>
packaged_largest_ingoing_char_speed,
const Scalar<DataVector>& mass_density,
const tnsr::I<DataVector, Dim, Frame::Inertial>& momentum_density,
const Scalar<DataVector>& energy_density,
const tnsr::I<DataVector, Dim, Frame::Inertial>& flux_mass_density,
const tnsr::IJ<DataVector, Dim, Frame::Inertial>& flux_momentum_density,
const tnsr::I<DataVector, Dim, Frame::Inertial>& flux_energy_density,
const tnsr::I<DataVector, Dim, Frame::Inertial>& velocity,
const Scalar<DataVector>& specific_internal_energy,
const tnsr::i<DataVector, Dim, Frame::Inertial>& normal_covector,
const std::optional<tnsr::I<DataVector, Dim, Frame::Inertial>>&
/*mesh_velocity*/,
const std::optional<Scalar<DataVector>>& normal_dot_mesh_velocity,
const EquationsOfState::EquationOfState<false, ThermodynamicDim>&
equation_of_state) const noexcept {
{
// Compute pressure
if constexpr (ThermodynamicDim == 1) {
*packaged_pressure =
equation_of_state.pressure_from_density(mass_density);
} else if constexpr (ThermodynamicDim == 2) {
*packaged_pressure = equation_of_state.pressure_from_density_and_energy(
mass_density, specific_internal_energy);
}
// Compute sound speed
Scalar<DataVector>& sound_speed = *packaged_mass_density;
sound_speed_squared(make_not_null(&sound_speed), mass_density,
specific_internal_energy, equation_of_state);
get(sound_speed) = sqrt(get(sound_speed));
// Compute normal velocity of fluid w.r.t. mesh
Scalar<DataVector>& normal_dot_velocity = *packaged_energy_density;
dot_product(make_not_null(&normal_dot_velocity), velocity, normal_covector);
// Compute the normal velocity and largest outgoing / ingoing characteristic
// speeds. Note that the notion of being 'largest ingoing' means taking the
// most negative value given that the positive direction is outward normal.
if (normal_dot_mesh_velocity.has_value()) {
get(*packaged_largest_outgoing_char_speed) =
get(normal_dot_velocity) + get(sound_speed) -
get(*normal_dot_mesh_velocity);
get(*packaged_largest_ingoing_char_speed) =
get(normal_dot_velocity) - get(sound_speed) -
get(*normal_dot_mesh_velocity);
get(*packaged_normal_dot_velocity) =
get(normal_dot_velocity) - get(*normal_dot_mesh_velocity);
} else {
get(*packaged_largest_outgoing_char_speed) =
get(normal_dot_velocity) + get(sound_speed);
get(*packaged_largest_ingoing_char_speed) =
get(normal_dot_velocity) - get(sound_speed);
get(*packaged_normal_dot_velocity) = get(normal_dot_velocity);
}
}
*packaged_mass_density = mass_density;
*packaged_momentum_density = momentum_density;
*packaged_energy_density = energy_density;
*packaged_interface_unit_normal = normal_covector;
normal_dot_flux(packaged_normal_dot_flux_mass_density, normal_covector,
flux_mass_density);
normal_dot_flux(packaged_normal_dot_flux_momentum_density, normal_covector,
flux_momentum_density);
normal_dot_flux(packaged_normal_dot_flux_energy_density, normal_covector,
flux_energy_density);
return fmax(max(get(*packaged_largest_outgoing_char_speed)),
-min(get(*packaged_largest_ingoing_char_speed)));
}
template <size_t Dim>
void Hllc<Dim>::dg_boundary_terms(
const gsl::not_null<Scalar<DataVector>*> boundary_correction_mass_density,
const gsl::not_null<tnsr::I<DataVector, Dim, Frame::Inertial>*>
boundary_correction_momentum_density,
const gsl::not_null<Scalar<DataVector>*> boundary_correction_energy_density,
const Scalar<DataVector>& mass_density_int,
const tnsr::I<DataVector, Dim, Frame::Inertial>& momentum_density_int,
const Scalar<DataVector>& energy_density_int,
const Scalar<DataVector>& pressure_int,
const Scalar<DataVector>& normal_dot_flux_mass_density_int,
const tnsr::I<DataVector, Dim, Frame::Inertial>&
normal_dot_flux_momentum_density_int,
const Scalar<DataVector>& normal_dot_flux_energy_density_int,
const tnsr::i<DataVector, Dim, Frame::Inertial>& interface_unit_normal_int,
const Scalar<DataVector>& normal_dot_velocity_int,
const Scalar<DataVector>& largest_outgoing_char_speed_int,
const Scalar<DataVector>& largest_ingoing_char_speed_int,
const Scalar<DataVector>& mass_density_ext,
const tnsr::I<DataVector, Dim, Frame::Inertial>& momentum_density_ext,
const Scalar<DataVector>& energy_density_ext,
const Scalar<DataVector>& pressure_ext,
const Scalar<DataVector>& normal_dot_flux_mass_density_ext,
const tnsr::I<DataVector, Dim, Frame::Inertial>&
normal_dot_flux_momentum_density_ext,
const Scalar<DataVector>& normal_dot_flux_energy_density_ext,
const tnsr::i<DataVector, Dim, Frame::Inertial>& interface_unit_normal_ext,
const Scalar<DataVector>& normal_dot_velocity_ext,
const Scalar<DataVector>& largest_outgoing_char_speed_ext,
const Scalar<DataVector>& largest_ingoing_char_speed_ext,
const dg::Formulation dg_formulation) const noexcept {
// Allocate a temp buffer
const size_t vector_size = get(mass_density_int).size();
Variables<tmpl::list<::Tags::TempScalar<0>, ::Tags::TempScalar<1>,
::Tags::TempScalar<2>, ::Tags::TempScalar<3>,
::Tags::TempScalar<4>>>
temps{vector_size};
// Determine lambda_max and lambda_min from the characteristic speeds from
// interior and exterior
get(get<::Tags::TempScalar<0>>(temps)) =
min(0., get(largest_ingoing_char_speed_int),
-get(largest_outgoing_char_speed_ext));
const DataVector& lambda_min = get(get<::Tags::TempScalar<0>>(temps));
get(get<::Tags::TempScalar<1>>(temps)) =
max(0., get(largest_outgoing_char_speed_int),
-get(largest_ingoing_char_speed_ext));
const DataVector& lambda_max = get(get<::Tags::TempScalar<1>>(temps));
// Compute lambda_star, the contact wave speed. (cf. Eq 10.37 of Toro2009,
// note that here lambda instead of S was used to denote characteristic
// speeds)
get(get<::Tags::TempScalar<2>>(temps)) =
(get(pressure_ext) - get(pressure_int) +
get(mass_density_int) * get(normal_dot_velocity_int) *
(lambda_min - get(normal_dot_velocity_int)) +
get(mass_density_ext) * get(normal_dot_velocity_ext) *
(lambda_max + get(normal_dot_velocity_ext))) /
(get(mass_density_int) * (lambda_min - get(normal_dot_velocity_int)) -
get(mass_density_ext) * (lambda_max + get(normal_dot_velocity_ext)));
const DataVector& lambda_star = get(get<::Tags::TempScalar<2>>(temps));
// Precompute common numerical factors for state variables in star region
// (cf. Eq 10.39 of Toro2009)
get(get<::Tags::TempScalar<3>>(temps)) =
(lambda_min - get(normal_dot_velocity_int)) / (lambda_min - lambda_star);
const DataVector& prefactor_int = get(get<::Tags::TempScalar<3>>(temps));
get(get<::Tags::TempScalar<4>>(temps)) =
(lambda_max + get(normal_dot_velocity_ext)) / (lambda_max - lambda_star);
const DataVector& prefactor_ext = get(get<::Tags::TempScalar<4>>(temps));
for (size_t i = 0; i < vector_size; ++i) {
// check if lambda_star falls in the correct range [lambda_min,lambda_max]
ASSERT(
(lambda_star[i] <= lambda_max[i]) and (lambda_star[i] >= lambda_min[i]),
"lambda_star in HLLC boundary correction is not consistent : "
<< "\n lambda_min = " << lambda_min[i] << "\n lambda_* = "
<< lambda_star[i] << "\n lambda_max = " << lambda_max[i]);
if (dg_formulation == dg::Formulation::WeakInertial) {
// Compute intermediate flux F_star (cf. Eq 10.71 - 10.73 of Toro2009)
if (lambda_star[i] >= 0.0) {
get(*boundary_correction_mass_density)[i] =
get(normal_dot_flux_mass_density_int)[i] +
lambda_min[i] * (prefactor_int[i] - 1.0) * get(mass_density_int)[i];
for (size_t spatial_index = 0; spatial_index < Dim; ++spatial_index) {
boundary_correction_momentum_density->get(spatial_index)[i] =
normal_dot_flux_momentum_density_int.get(spatial_index)[i] +
lambda_min[i] *
(get(mass_density_int)[i] * prefactor_int[i] *
(lambda_star[i] - get(normal_dot_velocity_int)[i]) *
interface_unit_normal_int.get(spatial_index)[i] +
momentum_density_int.get(spatial_index)[i] *
(prefactor_int[i] - 1.0));
}
get(*boundary_correction_energy_density)[i] =
get(normal_dot_flux_energy_density_int)[i] +
lambda_min[i] *
((prefactor_int[i] - 1.0) *
(get(energy_density_int)[i] + get(pressure_int)[i]) +
prefactor_int[i] * get(mass_density_int)[i] * lambda_star[i] *
(lambda_star[i] - get(normal_dot_velocity_int)[i]));
} else {
get(*boundary_correction_mass_density)[i] =
-get(normal_dot_flux_mass_density_ext)[i] +
lambda_max[i] * (prefactor_ext[i] - 1.0) * get(mass_density_ext)[i];
for (size_t spatial_index = 0; spatial_index < Dim; ++spatial_index) {
boundary_correction_momentum_density->get(spatial_index)[i] =
-normal_dot_flux_momentum_density_ext.get(spatial_index)[i] +
lambda_max[i] *
(get(mass_density_ext)[i] * prefactor_ext[i] *
(lambda_star[i] + get(normal_dot_velocity_ext)[i]) *
(-interface_unit_normal_ext.get(spatial_index)[i]) +
momentum_density_ext.get(spatial_index)[i] *
(prefactor_ext[i] - 1.0));
}
get(*boundary_correction_energy_density)[i] =
-get(normal_dot_flux_energy_density_ext)[i] +
lambda_max[i] *
((prefactor_ext[i] - 1.0) *
(get(energy_density_ext)[i] + get(pressure_ext)[i]) +
prefactor_ext[i] * get(mass_density_ext)[i] * lambda_star[i] *
(lambda_star[i] + get(normal_dot_velocity_ext)[i]));
}
} else {
// Compute boundary correction for strong formulation
if (lambda_star[i] >= 0.0) {
get(*boundary_correction_mass_density)[i] =
lambda_min[i] * (prefactor_int[i] - 1.0) * get(mass_density_int)[i];
for (size_t spatial_index = 0; spatial_index < Dim; ++spatial_index) {
boundary_correction_momentum_density->get(spatial_index)[i] =
lambda_min[i] *
(get(mass_density_int)[i] * prefactor_int[i] *
(lambda_star[i] - get(normal_dot_velocity_int)[i]) *
interface_unit_normal_int.get(spatial_index)[i] +
momentum_density_int.get(spatial_index)[i] *
(prefactor_int[i] - 1.0));
}
get(*boundary_correction_energy_density)[i] =
lambda_min[i] *
((prefactor_int[i] - 1.0) *
(get(energy_density_int)[i] + get(pressure_int)[i]) +
prefactor_int[i] * get(mass_density_int)[i] * lambda_star[i] *
(lambda_star[i] - get(normal_dot_velocity_int)[i]));
} else {
get(*boundary_correction_mass_density)[i] =
-get(normal_dot_flux_mass_density_int)[i] -
get(normal_dot_flux_mass_density_ext)[i] +
lambda_max[i] * (prefactor_ext[i] - 1.0) * get(mass_density_ext)[i];
for (size_t spatial_index = 0; spatial_index < Dim; ++spatial_index) {
boundary_correction_momentum_density->get(spatial_index)[i] =
-normal_dot_flux_momentum_density_int.get(spatial_index)[i] -
normal_dot_flux_momentum_density_ext.get(spatial_index)[i] +
lambda_max[i] *
(get(mass_density_ext)[i] * prefactor_ext[i] *
(lambda_star[i] + get(normal_dot_velocity_ext)[i]) *
(-interface_unit_normal_ext.get(spatial_index)[i]) +
momentum_density_ext.get(spatial_index)[i] *
(prefactor_ext[i] - 1.0));
}
get(*boundary_correction_energy_density)[i] =
-get(normal_dot_flux_energy_density_int)[i] -
get(normal_dot_flux_energy_density_ext)[i] +
lambda_max[i] *
((prefactor_ext[i] - 1.0) *
(get(energy_density_ext)[i] + get(pressure_ext)[i]) +
prefactor_ext[i] * get(mass_density_ext)[i] * lambda_star[i] *
(lambda_star[i] + get(normal_dot_velocity_ext)[i]));
}
}
}
}
template <size_t Dim>
// NOLINTNEXTLINE
PUP::able::PUP_ID Hllc<Dim>::my_PUP_ID = 0;
#define DIM(data) BOOST_PP_TUPLE_ELEM(0, data)
#define INSTANTIATION(_, data) template class Hllc<DIM(data)>;
GENERATE_INSTANTIATIONS(INSTANTIATION, (1, 2, 3))
#undef INSTANTIATION
#define THERMODIM(data) BOOST_PP_TUPLE_ELEM(1, data)
#define INSTANTIATION(_, data) \
template double Hllc<DIM(data)>::dg_package_data<THERMODIM(data)>( \
gsl::not_null<Scalar<DataVector>*> packaged_mass_density, \
gsl::not_null<tnsr::I<DataVector, DIM(data), Frame::Inertial>*> \
packaged_momentum_density, \
gsl::not_null<Scalar<DataVector>*> packaged_energy_density, \
gsl::not_null<Scalar<DataVector>*> packaged_pressure, \
gsl::not_null<Scalar<DataVector>*> \
packaged_normal_dot_flux_mass_density, \
gsl::not_null<tnsr::I<DataVector, DIM(data), Frame::Inertial>*> \
packaged_normal_dot_flux_momentum_density, \
gsl::not_null<Scalar<DataVector>*> \
packaged_normal_dot_flux_energy_density, \
gsl::not_null<tnsr::i<DataVector, DIM(data), Frame::Inertial>*> \
packaged_interface_unit_normal, \
gsl::not_null<Scalar<DataVector>*> packaged_normal_dot_velocity, \
gsl::not_null<Scalar<DataVector>*> packaged_largest_outgoing_char_speed, \
gsl::not_null<Scalar<DataVector>*> packaged_largest_ingoing_char_speed, \
\
const Scalar<DataVector>& mass_density, \
const tnsr::I<DataVector, DIM(data), Frame::Inertial>& momentum_density, \
const Scalar<DataVector>& energy_density, \
\
const tnsr::I<DataVector, DIM(data), Frame::Inertial>& \
flux_mass_density, \
const tnsr::IJ<DataVector, DIM(data), Frame::Inertial>& \
flux_momentum_density, \
const tnsr::I<DataVector, DIM(data), Frame::Inertial>& \
flux_energy_density, \
\
const tnsr::I<DataVector, DIM(data), Frame::Inertial>& velocity, \
const Scalar<DataVector>& specific_internal_energy, \
\
const tnsr::i<DataVector, DIM(data), Frame::Inertial>& normal_covector, \
const std::optional<tnsr::I<DataVector, DIM(data), Frame::Inertial>>& \
mesh_velocity, \
const std::optional<Scalar<DataVector>>& normal_dot_mesh_velocity, \
const EquationsOfState::EquationOfState<false, THERMODIM(data)>& \
equation_of_state) const noexcept;
GENERATE_INSTANTIATIONS(INSTANTIATION, (1, 2, 3), (1, 2))
#undef INSTANTIATION
#undef THERMODIM
#undef DIM
} // namespace NewtonianEuler::BoundaryCorrections
| 50.68306 | 80 | 0.641348 | [
"mesh"
] |
d088b2261902e91fa53fbf7bfa8a6fdc085e03bd | 15,070 | cpp | C++ | src/objects/computer_vision/BackgroundSubtraction.cpp | DHaylock/ofxVisualProgramming | ea821226d7903ff18f7594086b90090e13c84080 | [
"MIT"
] | 2 | 2018-09-11T13:17:32.000Z | 2018-11-12T02:29:51.000Z | src/objects/computer_vision/BackgroundSubtraction.cpp | DHaylock/ofxVisualProgramming | ea821226d7903ff18f7594086b90090e13c84080 | [
"MIT"
] | null | null | null | src/objects/computer_vision/BackgroundSubtraction.cpp | DHaylock/ofxVisualProgramming | ea821226d7903ff18f7594086b90090e13c84080 | [
"MIT"
] | null | null | null | /*==============================================================================
ofxVisualProgramming: A visual programming patching environment for OF
Copyright (c) 2018 Emanuele Mazza aka n3m3da <emanuelemazza@d3cod3.org>
ofxVisualProgramming is distributed under the MIT License.
This gives everyone the freedoms to use ofxVisualProgramming in any context:
commercial or non-commercial, public or private, open or closed source.
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.
See https://github.com/d3cod3/ofxVisualProgramming for documentation
==============================================================================*/
#include "BackgroundSubtraction.h"
using namespace ofxCv;
using namespace cv;
//--------------------------------------------------------------
BackgroundSubtraction::BackgroundSubtraction() : PatchObject(){
this->numInlets = 2;
this->numOutlets = 1;
_inletParams[0] = new ofTexture(); // input
_inletParams[1] = new float(); // bang
*(float *)&_inletParams[1] = 0.0f;
_outletParams[0] = new ofTexture(); // output
this->initInletsState();
resetTextures(320,240);
bgSubTech = 0; // 0 abs, 1 lighter than, 2 darker than
isGUIObject = true;
this->isOverGUI = true;
posX = posY = drawW = drawH = 0.0f;
newConnection = false;
bLearnBackground = false;
}
//--------------------------------------------------------------
void BackgroundSubtraction::newObject(){
this->setName("background subtraction");
this->addInlet(VP_LINK_TEXTURE,"input");
this->addInlet(VP_LINK_NUMERIC,"reset");
this->addOutlet(VP_LINK_TEXTURE);
this->setCustomVar(static_cast<float>(80.0),"THRESHOLD");
this->setCustomVar(static_cast<float>(bgSubTech),"SUBTRACTION_TECHNIQUE");
this->setCustomVar(static_cast<float>(0.0),"BRIGHTNESS");
this->setCustomVar(static_cast<float>(0.0),"CONTRAST");
this->setCustomVar(static_cast<float>(1.0),"BLUR");
this->setCustomVar(static_cast<float>(0.0),"ERODE");
this->setCustomVar(static_cast<float>(0.0),"DILATE");
}
//--------------------------------------------------------------
void BackgroundSubtraction::setupObjectContent(shared_ptr<ofAppGLFWWindow> &mainWindow){
gui = new ofxDatGui( ofxDatGuiAnchor::TOP_RIGHT );
gui->setAutoDraw(false);
gui->setUseCustomMouse(true);
gui->setWidth(this->width);
header = gui->addHeader("CONFIG",false);
header->setUseCustomMouse(true);
header->setCollapsable(true);
resetButton = gui->addButton("RESET BACKGROUND");
resetButton->setUseCustomMouse(true);
thresholdValue = gui->addSlider("THRESH",0,255);
thresholdValue->setUseCustomMouse(true);
thresholdValue->setValue(static_cast<double>(this->getCustomVar("THRESHOLD")));
vector<int> techs = {0,1,2};
bgSubTechSelector = gui->addMatrix("TECHNIQUE",techs.size(),true);
bgSubTechSelector->setUseCustomMouse(true);
bgSubTechSelector->setRadioMode(true);
bgSubTech = static_cast<int>(floor(this->getCustomVar("SUBTRACTION_TECHNIQUE")));
bgSubTechSelector->getChildAt(bgSubTech)->setSelected(true);
gui->addBreak();
brightnessValue = gui->addSlider("BRIGTH",-1.0,3.0);
brightnessValue->setUseCustomMouse(true);
brightnessValue->setValue(static_cast<double>(this->getCustomVar("BRIGHTNESS")));
contrastValue = gui->addSlider("CONTRAST",0.0,1.0);
contrastValue->setUseCustomMouse(true);
contrastValue->setValue(static_cast<double>(this->getCustomVar("CONTRAST")));
blurValue = gui->addSlider("BLUR",0,33);
blurValue->setUseCustomMouse(true);
blurValue->setValue(static_cast<double>(this->getCustomVar("BLUR")));
erodeButton = gui->addToggle("ERODE",static_cast<int>(floor(this->getCustomVar("ERODE"))));
erodeButton->setUseCustomMouse(true);
dilateButton = gui->addToggle("DILATE",static_cast<int>(floor(this->getCustomVar("DILATE"))));
dilateButton->setUseCustomMouse(true);
gui->onButtonEvent(this, &BackgroundSubtraction::onButtonEvent);
gui->onToggleEvent(this, &BackgroundSubtraction::onToggleEvent);
gui->onSliderEvent(this, &BackgroundSubtraction::onSliderEvent);
gui->onMatrixEvent(this, &BackgroundSubtraction::onMatrixEvent);
gui->setPosition(0,this->height - header->getHeight());
gui->collapse();
header->setIsCollapsed(true);
}
//--------------------------------------------------------------
void BackgroundSubtraction::updateObjectContent(map<int,PatchObject*> &patchObjects){
gui->update();
header->update();
if(!header->getIsCollapsed()){
resetButton->update();
thresholdValue->update();
bgSubTechSelector->update();
brightnessValue->update();
contrastValue->update();
blurValue->update();
erodeButton->update();
dilateButton->update();
}
if(this->inletsConnected[0] && static_cast<ofTexture *>(_inletParams[0])->isAllocated()){
if(!newConnection){
newConnection = true;
resetTextures(static_cast<ofTexture *>(_inletParams[0])->getWidth(),static_cast<ofTexture *>(_inletParams[0])->getHeight());
}
static_cast<ofTexture *>(_inletParams[0])->readToPixels(*pix);
colorImg->setFromPixels(*pix);
colorImg->updateTexture();
grayImg = *colorImg;
grayImg.updateTexture();
grayImg.brightnessContrast(brightnessValue->getValue(),contrastValue->getValue());
if(bgSubTech == 0){
grayThresh.absDiff(grayBg, grayImg);
}else if(bgSubTech == 1){
grayThresh = grayImg;
grayThresh -= grayBg;
}else if(bgSubTech == 2){
grayThresh = grayBg;
grayThresh -= grayImg;
}
grayThresh.threshold(thresholdValue->getValue());
if(erodeButton->getChecked()){
grayThresh.erode();
}
if(dilateButton->getChecked()){
grayThresh.dilate();
}
if(static_cast<int>(floor(blurValue->getValue()))%2 == 0){
grayThresh.blur(static_cast<int>(floor(blurValue->getValue()))+1);
}else{
grayThresh.blur(static_cast<int>(floor(blurValue->getValue())));
}
grayThresh.updateTexture();
*static_cast<ofTexture *>(_outletParams[0]) = grayThresh.getTexture();
}else{
newConnection = false;
}
// External background reset (BANG)
if(this->inletsConnected[1] && *(float *)&_inletParams[1] == 1.0f){
bLearnBackground = true;
}
//////////////////////////////////////////////
// background learning
if(bLearnBackground == true){
bLearnBackground = false;
grayBg = grayImg;
grayBg.updateTexture();
}
//////////////////////////////////////////////
}
//--------------------------------------------------------------
void BackgroundSubtraction::drawObjectContent(ofxFontStash *font){
ofSetColor(255);
ofEnableAlphaBlending();
if(this->inletsConnected[0] && static_cast<ofTexture *>(_outletParams[0])->isAllocated()){
if(static_cast<ofTexture *>(_outletParams[0])->getWidth() >= static_cast<ofTexture *>(_outletParams[0])->getHeight()){ // horizontal texture
drawW = this->width;
drawH = (this->width/static_cast<ofTexture *>(_outletParams[0])->getWidth())*static_cast<ofTexture *>(_outletParams[0])->getHeight();
posX = 0;
posY = (this->height-drawH)/2.0f;
}else{ // vertical texture
drawW = (static_cast<ofTexture *>(_outletParams[0])->getWidth()*this->height)/static_cast<ofTexture *>(_outletParams[0])->getHeight();
drawH = this->height;
posX = (this->width-drawW)/2.0f;
posY = 0;
}
static_cast<ofTexture *>(_outletParams[0])->draw(posX,posY,drawW,drawH);
}
gui->draw();
ofDisableAlphaBlending();
}
//--------------------------------------------------------------
void BackgroundSubtraction::removeObjectContent(){
}
//--------------------------------------------------------------
void BackgroundSubtraction::mouseMovedObjectContent(ofVec3f _m){
gui->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
header->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
resetButton->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
thresholdValue->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
bgSubTechSelector->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
brightnessValue->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
contrastValue->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
blurValue->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
erodeButton->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
dilateButton->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
if(!header->getIsCollapsed()){
this->isOverGUI = header->hitTest(_m-this->getPos()) || resetButton->hitTest(_m-this->getPos()) || thresholdValue->hitTest(_m-this->getPos()) || bgSubTechSelector->hitTest(_m-this->getPos()) || brightnessValue->hitTest(_m-this->getPos()) || contrastValue->hitTest(_m-this->getPos()) || blurValue->hitTest(_m-this->getPos()) || erodeButton->hitTest(_m-this->getPos()) || dilateButton->hitTest(_m-this->getPos());
}else{
this->isOverGUI = header->hitTest(_m-this->getPos());
}
}
//--------------------------------------------------------------
void BackgroundSubtraction::dragGUIObject(ofVec3f _m){
if(this->isOverGUI){
gui->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
header->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
resetButton->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
thresholdValue->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
bgSubTechSelector->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
brightnessValue->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
contrastValue->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
blurValue->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
erodeButton->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
dilateButton->setCustomMousePos(static_cast<int>(_m.x - this->getPos().x),static_cast<int>(_m.y - this->getPos().y));
}else{
ofNotifyEvent(dragEvent, nId);
box->setFromCenter(_m.x, _m.y,box->getWidth(),box->getHeight());
headerBox->set(box->getPosition().x,box->getPosition().y,box->getWidth(),headerHeight);
x = box->getPosition().x;
y = box->getPosition().y;
for(int j=0;j<static_cast<int>(outPut.size());j++){
outPut[j]->linkVertices[0].move(outPut[j]->posFrom.x,outPut[j]->posFrom.y);
outPut[j]->linkVertices[1].move(outPut[j]->posFrom.x+20,outPut[j]->posFrom.y);
}
}
}
//--------------------------------------------------------------
void BackgroundSubtraction::resetTextures(int w, int h){
pix = new ofPixels();
colorImg = new ofxCvColorImage();
pix->allocate(static_cast<size_t>(w),static_cast<size_t>(h),1);
colorImg->allocate(w,h);
grayImg.allocate(w,h);
grayBg.allocate(w,h);
grayThresh.allocate(w,h);
}
//--------------------------------------------------------------
void BackgroundSubtraction::onButtonEvent(ofxDatGuiButtonEvent e){
if(!header->getIsCollapsed()){
if(e.target == resetButton){
bLearnBackground = true;
}
}
}
//--------------------------------------------------------------
void BackgroundSubtraction::onToggleEvent(ofxDatGuiToggleEvent e){
if(!header->getIsCollapsed()){
if(e.target == erodeButton){
this->setCustomVar(static_cast<float>(e.checked),"ERODE");
}else if(e.target == dilateButton){
this->setCustomVar(static_cast<float>(e.checked),"DILATE");
}
}
}
//--------------------------------------------------------------
void BackgroundSubtraction::onSliderEvent(ofxDatGuiSliderEvent e){
if(!header->getIsCollapsed()){
if(e.target == thresholdValue){
this->setCustomVar(static_cast<float>(e.value),"THRESHOLD");
}else if(e.target == brightnessValue){
this->setCustomVar(static_cast<float>(e.value),"BRIGHTNESS");
}else if(e.target == contrastValue){
this->setCustomVar(static_cast<float>(e.value),"CONTRAST");
}else if(e.target == blurValue){
this->setCustomVar(static_cast<float>(e.value),"BLUR");
}
}
}
//--------------------------------------------------------------
void BackgroundSubtraction::onMatrixEvent(ofxDatGuiMatrixEvent e){
if(!header->getIsCollapsed()){
if(e.target == bgSubTechSelector){
bgSubTech = e.child;
this->setCustomVar(static_cast<float>(bgSubTech),"SUBTRACTION_TECHNIQUE");
}
}
}
| 44.064327 | 419 | 0.615395 | [
"vector"
] |
d09f707186a9bcd6c82449e8a52a13df33c4e8d9 | 596 | cc | C++ | code/dataStructures/DSUV.cc | Zeldacrafter/CompProg | 5367583f45b6fe30c4c84f3ae81accf14f8f7fd3 | [
"Unlicense"
] | 4 | 2020-02-06T15:44:57.000Z | 2020-12-21T03:51:21.000Z | code/dataStructures/DSUV.cc | Zeldacrafter/CompProg | 5367583f45b6fe30c4c84f3ae81accf14f8f7fd3 | [
"Unlicense"
] | null | null | null | code/dataStructures/DSUV.cc | Zeldacrafter/CompProg | 5367583f45b6fe30c4c84f3ae81accf14f8f7fd3 | [
"Unlicense"
] | null | null | null | #include "../template.hh"
template<typename V, typename F>
struct DSU {
int sz;
vi p;
vector<V> v;
F f;
DSU(int size, const V& _v, F _f) :
sz{size}, p(size, -1), v(size, _v), f{_f} {}
bool sameSet(int a, int b) { return find(a) == find(b); }
int find(int x) { return p[x] < 0 ? x : p[x] = find(p[x]); }
bool join(int a, int b) {
a = find(a), b = find(b);
if (a == b) return false;
if (p[a] > p[b]) swap(a, b);
p[a] += p[b], p[b] = a;
v[a] = f(v[a], v[b]);
return --sz, true;
}
int size() { return sz; }
int size(int a) { return -p[find(a)]; }
};
| 25.913043 | 62 | 0.496644 | [
"vector"
] |
d0a15adde5824d7f9a86585fea5df29f177e793f | 953 | cpp | C++ | iterator/iterator.cpp | iceylala/design-pattern | 62865dd8ede485be874556233b0d9469139fdc85 | [
"MIT"
] | null | null | null | iterator/iterator.cpp | iceylala/design-pattern | 62865dd8ede485be874556233b0d9469139fdc85 | [
"MIT"
] | null | null | null | iterator/iterator.cpp | iceylala/design-pattern | 62865dd8ede485be874556233b0d9469139fdc85 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Iter
{
public:
virtual void next()=0;
virtual void first()=0;
virtual int* current()=0;
};
class Iterm
{
public:
virtual Iter* create()=0;
};
class ConIterm:public Iterm
{
public:
vector<int> data;
ConIterm(){
data.push_back(1);
data.push_back(2);
}
Iter* create();
int& operator[](int index){
return data[index];
}
int getlen(){
return data.size();
}
};
class ConIter:public Iter
{
ConIterm* aggr;
int _cnt;
public:
ConIter(ConIterm* a):aggr(a),_cnt(0){}
void first(){
_cnt=0;
}
void next(){
if(_cnt<aggr->getlen()){
_cnt++;
}
}
int* current(){
return &(*aggr)[_cnt];
}
};
Iter* ConIterm::create(){
return new ConIter(this);
}
int main()
{
Iterm* aggr = new ConIterm();
Iter *it = aggr->create();
it->first();
cout<<*(it->current())<<endl;
it->next();
cout<<*(it->current())<<endl;
return 0;
}
| 13.054795 | 40 | 0.592865 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.