hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
5f98ac8dc2a29343977db8d2ddc282487b256327
1,183
cpp
C++
libs/conversion/test/lexical_cast_containers_test.cpp
AishwaryaDoosa/Boost1.49
67bdb3b36d72dec7414a62f3b050162e608ea266
[ "BSL-1.0" ]
null
null
null
libs/conversion/test/lexical_cast_containers_test.cpp
AishwaryaDoosa/Boost1.49
67bdb3b36d72dec7414a62f3b050162e608ea266
[ "BSL-1.0" ]
null
null
null
libs/conversion/test/lexical_cast_containers_test.cpp
AishwaryaDoosa/Boost1.49
67bdb3b36d72dec7414a62f3b050162e608ea266
[ "BSL-1.0" ]
null
null
null
// Testing boost::lexical_cast with boost::container::string. // // See http://www.boost.org for most recent version, including documentation. // // Copyright Antony Polukhin, 2011. // // Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt). #include <boost/lexical_cast.hpp> #include <boost/test/unit_test.hpp> #include <boost/container/string.hpp> void testing_boost_containers_basic_string(); using namespace boost; boost::unit_test::test_suite *init_unit_test_suite(int, char *[]) { unit_test::test_suite *suite = BOOST_TEST_SUITE("Testing boost::lexical_cast with boost::container::string"); suite->add(BOOST_TEST_CASE(testing_boost_containers_basic_string)); return suite; } void testing_boost_containers_basic_string() { BOOST_CHECK("100" == lexical_cast<boost::container::string>("100")); BOOST_CHECK(L"100" == lexical_cast<boost::container::wstring>(L"100")); BOOST_CHECK("100" == lexical_cast<boost::container::string>(100)); boost::container::string str("1000"); BOOST_CHECK(1000 == lexical_cast<int>(str)); }
30.333333
86
0.72612
AishwaryaDoosa
5f9a09a6590471c0211f223f3bf4c4f15b99aabd
2,326
cpp
C++
LeetCode/Graph/DFS/PathSumii.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
3
2021-07-26T15:58:45.000Z
2021-09-08T14:55:11.000Z
LeetCode/Graph/DFS/PathSumii.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
null
null
null
LeetCode/Graph/DFS/PathSumii.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
2
2021-05-31T11:27:59.000Z
2021-10-03T13:26:00.000Z
/* * LeetCode 113 Path Sum ii * Medium * Jiawei Wang * 2021.8.22 */ /* Revision * $1 2021.9.28 Jiawei Wang * $2 2021.10.17 Jiawei Wang */ #include <vector> #include <deque> #include <stack> using namespace::std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; deque<int> current; vector<int> tmp; vector<vector<int>> ans; class Solution { public: // #1 BackTracking DFS // We passing a gloal variable or passing reference current for iteration // Reduce the storiage pressure vector<vector<int>> pathSum1(TreeNode* root, int targetSum) { vector<vector<int>> ret; vector<int> current; helper1(root, ret, current, targetSum); return ret; } private: void helper1(TreeNode* root, vector<vector<int>>& ret, vector<int>& current, int targetSum) { if (root == nullptr) return; targetSum -= root->val; current.push_back(root->val); if (targetSum == 0 && root->left == nullptr && root->right == nullptr) { // Termination Condition ret.push_back(current); } helper1(root->left, ret, current, targetSum); helper1(root->right, ret, current, targetSum); current.pop_back(); // remember pop back each layers } public: // #2 Classic DFS (Storage pressure) vector<vector<int>> pathSum2(TreeNode* root, int targetSum) { vector<vector<int>> ret; helper2(root, ret, {}, targetSum); return ret; } private: void helper2(TreeNode* root, vector<vector<int>>& ret, vector<int> current, int targetSum) { if (root == nullptr) return; targetSum -= root->val; current.push_back(root->val); if (targetSum == 0 && root->left == nullptr && root->right == nullptr) { // Termination Condition ret.push_back(current); return; } helper2(root->left, ret, current, targetSum); helper2(root->right, ret, current, targetSum); } };
25.844444
97
0.580396
a4org
5f9c641d3ffe79a888629e8ded33ab1b26fe9c5e
57,524
cpp
C++
SILENT/pthreed.cpp
DPSablowski/silent
a042dadb9bfa0b2219e95d2b292e3e61c0298d0d
[ "Apache-2.0" ]
2
2020-10-15T08:32:42.000Z
2021-07-02T23:17:17.000Z
SILENT/pthreed.cpp
DPSablowski/silent
a042dadb9bfa0b2219e95d2b292e3e61c0298d0d
[ "Apache-2.0" ]
null
null
null
SILENT/pthreed.cpp
DPSablowski/silent
a042dadb9bfa0b2219e95d2b292e3e61c0298d0d
[ "Apache-2.0" ]
null
null
null
#include "pthreed.h" #include "ui_pthreed.h" #include <fstream> #include <sstream> using namespace std; double x13d, x23d, y13d, y23d; string ptdpath; QString qptdpath; pthreed::pthreed(QWidget *parent) : QDialog(parent), ui(new Ui::pthreed) { ui->setupUi(this); this->setWindowTitle("3D Spectrograph Parameters"); ui->checkBox_15->setChecked(true); ui->customPlot->setInteraction(QCP::iRangeDrag, true); ui->customPlot->setInteraction(QCP::iRangeZoom, true); ui->customPlot->setInteraction(QCP::iSelectPlottables, true); ui->comboBox->addItem("Resolving Power"); ui->comboBox->addItem("2-Pixel Resolving Power"); ui->comboBox->addItem("Dispersion"); ui->comboBox->addItem("Anamorphism"); ui->comboBox->addItem("Nyquist"); ui->comboBox->addItem("Slit Width"); ui->comboBox->addItem("Earth Transmission"); ui->comboBox->addItem("Photons/s @ Telescope"); ui->comboBox->addItem("QE CCD"); ui->comboBox->addItem("Grating Efficiency"); ui->comboBox->addItem("Instrument Efficiency"); ui->comboBox->addItem("Overall Efficiency"); ui->comboBox->addItem("Surface Efficiency"); ui->comboBox->addItem("Layout"); ui->comboBox->addItem("Neon Spectrum"); ui->comboBox->addItem("Planck Spectrum"); ui->comboBox->addItem("Balmer Spectrum"); ui->customPlot->axisRect()->setupFullAxesBox(true); connect(ui->customPlot, SIGNAL(mouseMove(QMouseEvent*)), this ,SLOT(showPointToolTip(QMouseEvent*))); } pthreed::~pthreed() { delete ui; } //******************************************************** //show mouse coordinates //******************************************************** void pthreed::showPointToolTip(QMouseEvent *event) { double xc = ui->customPlot->xAxis->pixelToCoord(event->pos().x()); double yc = ui->customPlot->yAxis->pixelToCoord(event->pos().y()); setToolTip(QString("%1 , %2").arg(xc).arg(yc)); } void pthreed::seData(QString str) { ui->lineEdit_2->setText(str); } // find values void pthreed::on_pushButton_2_clicked() { qptdpath = ui->lineEdit_2->text(); ptdpath = qptdpath.toUtf8().constData(); string zeile, one, two; this->setCursor(QCursor(Qt::WaitCursor)); if(ui->comboBox->currentIndex()==0){ QFile checkfile3(qptdpath+"resolving3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/resolving3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); x13d=a[0]; x23d=a[0]; y13d=b[0]; y23d=b[0]; for(int i=0; i<number_of_lines; i++){ if(a[i]<x13d){ x13d=a[i]; } if(a[i]>x23d){ x23d=a[i]; } if(b[i]<y13d){ y13d=b[i]; } if(b[i]>y23d){ y23d=b[i]; } } ui->doubleSpinBox->setValue(x13d); ui->doubleSpinBox_2->setValue(x23d); ui->doubleSpinBox_3->setValue(y13d); ui->doubleSpinBox_4->setValue(y23d); } if(ui->comboBox->currentIndex()==1){ QFile checkfile3(qptdpath+"twopixR3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/twopixR3d3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); x13d=a[0]; x23d=a[0]; y13d=b[0]; y23d=b[0]; for(int i=0; i<number_of_lines; i++){ if(a[i]<x13d){ x13d=a[i]; } if(a[i]>x23d){ x23d=a[i]; } if(b[i]<y13d){ y13d=b[i]; } if(b[i]>y23d){ y23d=b[i]; } } ui->doubleSpinBox->setValue(x13d); ui->doubleSpinBox_2->setValue(x23d); ui->doubleSpinBox_3->setValue(y13d); ui->doubleSpinBox_4->setValue(y23d); } if(ui->comboBox->currentIndex()==2){ QFile checkfile3(qptdpath+"dispersion3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/dispersion3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); x13d=a[0]; x23d=a[0]; y13d=b[0]; y23d=b[0]; for(int i=0; i<number_of_lines; i++){ if(a[i]<x13d){ x13d=a[i]; } if(a[i]>x23d){ x23d=a[i]; } if(b[i]<y13d){ y13d=b[i]; } if(b[i]>y23d){ y23d=b[i]; } } ui->doubleSpinBox->setValue(x13d); ui->doubleSpinBox_2->setValue(x23d); ui->doubleSpinBox_3->setValue(y13d); ui->doubleSpinBox_4->setValue(y23d); } if(ui->comboBox->currentIndex()==3){ QFile checkfile3(qptdpath+"anamorphism3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/anamorphism3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); x13d=a[0]; x23d=a[0]; y13d=b[0]; y23d=b[0]; for(int i=0; i<number_of_lines; i++){ if(a[i]<x13d){ x13d=a[i]; } if(a[i]>x23d){ x23d=a[i]; } if(b[i]<y13d){ y13d=b[i]; } if(b[i]>y23d){ y23d=b[i]; } } ui->doubleSpinBox->setValue(x13d); ui->doubleSpinBox_2->setValue(x23d); ui->doubleSpinBox_3->setValue(y13d); ui->doubleSpinBox_4->setValue(y23d); } if(ui->comboBox->currentIndex()==4){ QFile checkfile3(qptdpath+"nyquist3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/nyquist3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); x13d=a[0]; x23d=a[0]; y13d=b[0]; y23d=b[0]; for(int i=0; i<number_of_lines; i++){ if(a[i]<x13d){ x13d=a[i]; } if(a[i]>x23d){ x23d=a[i]; } if(b[i]<y13d){ y13d=b[i]; } if(b[i]>y23d){ y23d=b[i]; } } ui->doubleSpinBox->setValue(x13d); ui->doubleSpinBox_2->setValue(x23d); ui->doubleSpinBox_3->setValue(y13d); ui->doubleSpinBox_4->setValue(y23d); } if(ui->comboBox->currentIndex()==5){ QFile checkfile3(qptdpath+"slit3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/slit3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); x13d=a[0]; x23d=a[0]; y13d=b[0]; y23d=b[0]; for(int i=0; i<number_of_lines; i++){ if(a[i]<x13d){ x13d=a[i]; } if(a[i]>x23d){ x23d=a[i]; } if(b[i]<y13d){ y13d=b[i]; } if(b[i]>y23d){ y23d=b[i]; } } ui->doubleSpinBox->setValue(x13d); ui->doubleSpinBox_2->setValue(x23d); ui->doubleSpinBox_3->setValue(y13d); ui->doubleSpinBox_4->setValue(y23d); } if(ui->comboBox->currentIndex()==6){ QFile checkfile3(qptdpath+"atmosphere3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/atmosphere3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); x13d=a[0]; x23d=a[0]; y13d=b[0]; y23d=b[0]; for(int i=0; i<number_of_lines; i++){ if(a[i]<x13d){ x13d=a[i]; } if(a[i]>x23d){ x23d=a[i]; } if(b[i]<y13d){ y13d=b[i]; } if(b[i]>y23d){ y23d=b[i]; } } ui->doubleSpinBox->setValue(x13d); ui->doubleSpinBox_2->setValue(x23d); ui->doubleSpinBox_3->setValue(y13d); ui->doubleSpinBox_4->setValue(y23d); } if(ui->comboBox->currentIndex()==7){ QFile checkfile3(qptdpath+"telescope3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/telescope3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); x13d=a[0]; x23d=a[0]; y13d=b[0]; y23d=b[0]; for(int i=0; i<number_of_lines; i++){ if(a[i]<x13d){ x13d=a[i]; } if(a[i]>x23d){ x23d=a[i]; } if(b[i]<y13d){ y13d=b[i]; } if(b[i]>y23d){ y23d=b[i]; } } ui->doubleSpinBox->setValue(x13d); ui->doubleSpinBox_2->setValue(x23d); ui->doubleSpinBox_3->setValue(y13d); ui->doubleSpinBox_4->setValue(y23d); } if(ui->comboBox->currentIndex()==8){ QFile checkfile3(qptdpath+"ccd3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/ccd3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); x13d=a[0]; x23d=a[0]; y13d=b[0]; y23d=b[0]; for(int i=0; i<number_of_lines; i++){ if(a[i]<x13d){ x13d=a[i]; } if(a[i]>x23d){ x23d=a[i]; } if(b[i]<y13d){ y13d=b[i]; } if(b[i]>y23d){ y23d=b[i]; } } ui->doubleSpinBox->setValue(x13d); ui->doubleSpinBox_2->setValue(x23d); ui->doubleSpinBox_3->setValue(y13d); ui->doubleSpinBox_4->setValue(y23d); } if(ui->comboBox->currentIndex()==9){ QFile checkfile3(qptdpath+"grating3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/grating3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); x13d=a[0]; x23d=a[0]; y13d=b[0]; y23d=b[0]; for(int i=0; i<number_of_lines; i++){ if(a[i]<x13d){ x13d=a[i]; } if(a[i]>x23d){ x23d=a[i]; } if(b[i]<y13d){ y13d=b[i]; } if(b[i]>y23d){ y23d=b[i]; } } ui->doubleSpinBox->setValue(x13d); ui->doubleSpinBox_2->setValue(x23d); ui->doubleSpinBox_3->setValue(y13d); ui->doubleSpinBox_4->setValue(y23d); } if(ui->comboBox->currentIndex()==10){ QFile checkfile3(qptdpath+"efficiency3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/efficiency3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); x13d=a[0]; x23d=a[0]; y13d=b[0]; y23d=b[0]; for(int i=0; i<number_of_lines; i++){ if(a[i]<x13d){ x13d=a[i]; } if(a[i]>x23d){ x23d=a[i]; } if(b[i]<y13d){ y13d=b[i]; } if(b[i]>y23d){ y23d=b[i]; } } ui->doubleSpinBox->setValue(x13d); ui->doubleSpinBox_2->setValue(x23d); ui->doubleSpinBox_3->setValue(y13d); ui->doubleSpinBox_4->setValue(y23d); } if(ui->comboBox->currentIndex()==11){ QFile checkfile3(qptdpath+"overall3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/overall3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); x13d=a[0]; x23d=a[0]; y13d=b[0]; y23d=b[0]; for(int i=0; i<number_of_lines; i++){ if(a[i]<x13d){ x13d=a[i]; } if(a[i]>x23d){ x23d=a[i]; } if(b[i]<y13d){ y13d=b[i]; } if(b[i]>y23d){ y23d=b[i]; } } ui->doubleSpinBox->setValue(x13d); ui->doubleSpinBox_2->setValue(x23d); ui->doubleSpinBox_3->setValue(y13d); ui->doubleSpinBox_4->setValue(y23d); } if(ui->comboBox->currentIndex()==12){ QFile checkfile3(qptdpath+"surfaces3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/surfaces3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); x13d=a[0]; x23d=a[0]; y13d=b[0]; y23d=b[0]; for(int i=0; i<number_of_lines; i++){ if(a[i]<x13d){ x13d=a[i]; } if(a[i]>x23d){ x23d=a[i]; } if(b[i]<y13d){ y13d=b[i]; } if(b[i]>y23d){ y23d=b[i]; } } ui->doubleSpinBox->setValue(x13d); ui->doubleSpinBox_2->setValue(x23d); ui->doubleSpinBox_3->setValue(y13d); ui->doubleSpinBox_4->setValue(y23d); } if(ui->comboBox->currentIndex()==13){ QFile checkfile3(qptdpath+"layout3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/layout3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); x13d=a[0]; x23d=a[0]; y13d=b[0]; y23d=b[0]; for(int i=0; i<number_of_lines; i++){ if(a[i]<x13d){ x13d=a[i]; } if(a[i]>x23d){ x23d=a[i]; } if(b[i]<y13d){ y13d=b[i]; } if(b[i]>y23d){ y23d=b[i]; } } ui->doubleSpinBox->setValue(x13d); ui->doubleSpinBox_2->setValue(x23d); ui->doubleSpinBox_3->setValue(y13d); ui->doubleSpinBox_4->setValue(y23d); } if(ui->comboBox->currentIndex()==14){ QFile checkfile3(qptdpath+"neon3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/neon3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); x13d=a[0]; x23d=a[0]; y13d=b[0]; y23d=b[0]; for(int i=0; i<number_of_lines; i++){ if(a[i]<x13d){ x13d=a[i]; } if(a[i]>x23d){ x23d=a[i]; } if(b[i]<y13d){ y13d=b[i]; } if(b[i]>y23d){ y23d=b[i]; } } ui->doubleSpinBox->setValue(x13d); ui->doubleSpinBox_2->setValue(x23d); ui->doubleSpinBox_3->setValue(y13d); ui->doubleSpinBox_4->setValue(y23d); } if(ui->comboBox->currentIndex()==15){ QFile checkfile3(qptdpath+"planck3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/planck3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); x13d=a[0]; x23d=a[0]; y13d=b[0]; y23d=b[0]; for(int i=0; i<number_of_lines; i++){ if(a[i]<x13d){ x13d=a[i]; } if(a[i]>x23d){ x23d=a[i]; } if(b[i]<y13d){ y13d=b[i]; } if(b[i]>y23d){ y23d=b[i]; } } ui->doubleSpinBox->setValue(x13d); ui->doubleSpinBox_2->setValue(x23d); ui->doubleSpinBox_3->setValue(y13d); ui->doubleSpinBox_4->setValue(y23d); } if(ui->comboBox->currentIndex()==16){ QFile checkfile3(qptdpath+"balmer3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/balmer3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); x13d=a[0]; x23d=a[0]; y13d=b[0]; y23d=b[0]; for(int i=0; i<number_of_lines; i++){ if(a[i]<x13d){ x13d=a[i]; } if(a[i]>x23d){ x23d=a[i]; } if(b[i]<y13d){ y13d=b[i]; } if(b[i]>y23d){ y23d=b[i]; } } ui->doubleSpinBox->setValue(x13d); ui->doubleSpinBox_2->setValue(x23d); ui->doubleSpinBox_3->setValue(y13d); ui->doubleSpinBox_4->setValue(y23d); } this->setCursor(QCursor(Qt::ArrowCursor)); } void pthreed::on_pushButton_3_clicked() { x13d=ui->doubleSpinBox->value(); x23d=ui->doubleSpinBox_2->value(); y13d=ui->doubleSpinBox_3->value(); y23d=ui->doubleSpinBox_4->value(); ui->customPlot->clearPlottables(); string zeile, one, two; this->setCursor(QCursor(Qt::ArrowCursor)); if(ui->comboBox->currentIndex()==0){ QFile checkfile3(qptdpath+"resolving3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/resolving3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); ui->customPlot->addGraph(); ui->customPlot->graph(0)->setData(a, b); ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone); ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2)); ui->customPlot->xAxis->setLabel("Wavelength [nm]"); ui->customPlot->yAxis->setLabel("Resolving Power"); ui->customPlot->xAxis->setRange(x13d, x23d); ui->customPlot->yAxis->setRange(y13d, y23d); ui->customPlot->replot(); } if(ui->comboBox->currentIndex()==1){ QFile checkfile3(qptdpath+"twopixR3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/twopixR3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); ui->customPlot->addGraph(); ui->customPlot->graph(0)->setData(a, b); ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone); ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2)); ui->customPlot->xAxis->setLabel("Wavelength [nm]"); ui->customPlot->yAxis->setLabel("Resolving Power"); ui->customPlot->xAxis->setRange(x13d, x23d); ui->customPlot->yAxis->setRange(y13d, y23d); ui->customPlot->replot(); } if(ui->comboBox->currentIndex()==2){ QFile checkfile3(qptdpath+"dispersion3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/dispersion3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); ui->customPlot->addGraph(); ui->customPlot->graph(0)->setData(a, b); ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone); ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2)); ui->customPlot->xAxis->setLabel("Wavelength [nm]"); ui->customPlot->yAxis->setLabel("Dispersion [nm/pix]"); ui->customPlot->xAxis->setRange(x13d, x23d); ui->customPlot->yAxis->setRange(y13d, y23d); ui->customPlot->replot(); } if(ui->comboBox->currentIndex()==3){ QFile checkfile3(qptdpath+"anamorphism3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/anamorphism3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); ui->customPlot->addGraph(); ui->customPlot->graph(0)->setData(a, b); ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone); ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2)); ui->customPlot->xAxis->setLabel("Wavelength [nm]"); ui->customPlot->yAxis->setLabel("Anamorphism"); ui->customPlot->xAxis->setRange(x13d, x23d); ui->customPlot->yAxis->setRange(y13d, y23d); ui->customPlot->replot(); } if(ui->comboBox->currentIndex()==4){ QFile checkfile3(qptdpath+"nyquist3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/nyquist3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); ui->customPlot->addGraph(); ui->customPlot->graph(0)->setData(a, b); ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone); ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2)); ui->customPlot->xAxis->setLabel("Wavelength [nm]"); ui->customPlot->yAxis->setLabel("Nyquist Factor"); ui->customPlot->xAxis->setRange(x13d, x23d); ui->customPlot->yAxis->setRange(y13d, y23d); ui->customPlot->replot(); } if(ui->comboBox->currentIndex()==5){ QFile checkfile3(qptdpath+"slit3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/slit3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); ui->customPlot->addGraph(); ui->customPlot->graph(0)->setData(a, b); ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone); ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2)); ui->customPlot->xAxis->setLabel("Wavelength [nm]"); ui->customPlot->yAxis->setLabel("Imaged Slit Width [mm]"); ui->customPlot->xAxis->setRange(x13d, x23d); ui->customPlot->yAxis->setRange(y13d, y23d); ui->customPlot->replot(); } if(ui->comboBox->currentIndex()==6){ QFile checkfile3(qptdpath+"atmosphere3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/atmosphere3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); ui->customPlot->addGraph(); ui->customPlot->graph(0)->setData(a, b); ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone); ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2)); ui->customPlot->xAxis->setLabel("Wavelength [nm]"); ui->customPlot->yAxis->setLabel("Earth Transmission"); ui->customPlot->xAxis->setRange(x13d, x23d); ui->customPlot->yAxis->setRange(y13d, y23d); ui->customPlot->replot(); } if(ui->comboBox->currentIndex()==7){ QFile checkfile3(qptdpath+"telescope3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/telescope3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); ui->customPlot->addGraph(); ui->customPlot->graph(0)->setData(a, b); ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone); ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2)); ui->customPlot->xAxis->setLabel("Wavelength [nm]"); ui->customPlot->yAxis->setLabel("Photons/s @ Telescope"); ui->customPlot->xAxis->setRange(x13d, x23d); ui->customPlot->yAxis->setRange(y13d, y23d); ui->customPlot->replot(); } if(ui->comboBox->currentIndex()==8){ QFile checkfile3(qptdpath+"ccd3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/ccd3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); ui->customPlot->addGraph(); ui->customPlot->graph(0)->setData(a, b); ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone); ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2)); ui->customPlot->xAxis->setLabel("Wavelength [nm]"); ui->customPlot->yAxis->setLabel("CCD Efficiency"); ui->customPlot->xAxis->setRange(x13d, x23d); ui->customPlot->yAxis->setRange(y13d, y23d); ui->customPlot->replot(); } if(ui->comboBox->currentIndex()==9){ QFile checkfile3(qptdpath+"grating3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/grating3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); ui->customPlot->addGraph(); ui->customPlot->graph(0)->setData(a, b); ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone); ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2)); ui->customPlot->xAxis->setLabel("Wavelength [nm]"); ui->customPlot->yAxis->setLabel("Grating Efficiecy"); ui->customPlot->xAxis->setRange(x13d, x23d); ui->customPlot->yAxis->setRange(y13d, y23d); ui->customPlot->replot(); } if(ui->comboBox->currentIndex()==10){ QFile checkfile3(qptdpath+"efficiency3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/efficiency3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); ui->customPlot->addGraph(); ui->customPlot->graph(0)->setData(a, b); ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone); ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2)); ui->customPlot->xAxis->setLabel("Wavelength [nm]"); ui->customPlot->yAxis->setLabel("Instrument Efficiency"); ui->customPlot->xAxis->setRange(x13d, x23d); ui->customPlot->yAxis->setRange(y13d, y23d); ui->customPlot->replot(); } if(ui->comboBox->currentIndex()==11){ QFile checkfile3(qptdpath+"overall3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/overall3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); ui->customPlot->addGraph(); ui->customPlot->graph(0)->setData(a, b); ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone); ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2)); ui->customPlot->xAxis->setLabel("Wavelength [nm]"); ui->customPlot->yAxis->setLabel("Overall Efficiency"); ui->customPlot->xAxis->setRange(x13d, x23d); ui->customPlot->yAxis->setRange(y13d, y23d); ui->customPlot->replot(); } if(ui->comboBox->currentIndex()==12){ QFile checkfile3(qptdpath+"surfaces3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/surfaces3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); ui->customPlot->addGraph(); ui->customPlot->graph(0)->setData(a, b); ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone); ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2)); ui->customPlot->xAxis->setLabel("Wavelength [nm]"); ui->customPlot->yAxis->setLabel("Surface Efficiency"); ui->customPlot->xAxis->setRange(x13d, x23d); ui->customPlot->yAxis->setRange(y13d, y23d); ui->customPlot->replot(); } if(ui->comboBox->currentIndex()==13){ QFile checkfile3(qptdpath+"layout3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/layout3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); ui->customPlot->addGraph(); ui->customPlot->graph(0)->setData(a, b); ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone); ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2)); ui->customPlot->xAxis->setLabel("Pixel x"); ui->customPlot->yAxis->setLabel("Pixel y"); ui->customPlot->xAxis->setRange(x13d, x23d); ui->customPlot->yAxis->setRange(y13d, y23d); ui->customPlot->replot(); } if(ui->comboBox->currentIndex()==14){ QFile checkfile3(qptdpath+"neon3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/neon3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); ui->customPlot->addGraph(); ui->customPlot->graph(0)->setData(a, b); ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsLine); ui->customPlot->xAxis->setLabel("Wavelength [nm]"); ui->customPlot->yAxis->setLabel("rel. Intensity"); ui->customPlot->xAxis->setRange(x13d, x23d); ui->customPlot->yAxis->setRange(y13d, y23d); ui->customPlot->replot(); } if(ui->comboBox->currentIndex()==15){ ui->customPlot->clearPlottables(); QFile checkfile3(qptdpath+"planck3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/planck3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); ui->customPlot->addGraph(); ui->customPlot->graph(0)->setData(a, b); ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsLine); ui->customPlot->xAxis->setLabel("Wavelength [nm]"); ui->customPlot->yAxis->setLabel("rel. Intensity"); ui->customPlot->xAxis->setRange(x13d, x23d); ui->customPlot->yAxis->setRange(y13d, y23d); ui->customPlot->replot(); } if(ui->comboBox->currentIndex()==16){ QFile checkfile3(qptdpath+"balmer3d.txt"); if(!checkfile3.exists()){ QMessageBox::information(this, "Error", "Parameters not calculated."); this->setCursor(QCursor(Qt::ArrowCursor)); return; } std::ostringstream datNameStream(ptdpath); datNameStream<<ptdpath<<"/balmer3d.txt"; std::string datName = datNameStream.str(); ifstream toplot1(datName.c_str()); ui->customPlot->clearPlottables(); int number_of_lines =0; while(std::getline(toplot1, zeile)) ++ number_of_lines; toplot1.clear(); toplot1.seekg(0, ios::beg); QVector<double> a(number_of_lines), b(number_of_lines); for (int i=0; i<number_of_lines; i++){ toplot1 >> one >>two; istringstream ist(one); ist >> a[i]; istringstream ist2(two); ist2 >> b[i]; } toplot1.close(); ui->customPlot->addGraph(); ui->customPlot->graph(0)->setData(a, b); ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsLine); ui->customPlot->xAxis->setLabel("Wavelength [nm]"); ui->customPlot->yAxis->setLabel("re Intensity"); ui->customPlot->xAxis->setRange(x13d, x23d); ui->customPlot->yAxis->setRange(y13d, y23d); ui->customPlot->replot(); } this->setCursor(QCursor(Qt::ArrowCursor)); } void pthreed::on_pushButton_4_clicked() { QString save=ui->lineEdit_2->text()+"/"+ui->lineEdit->text(); if(ui->checkBox_15->isChecked()){ ui->customPlot->savePdf(save); } if(ui->checkBox_16->isChecked()){ ui->customPlot->savePng(save); } } void pthreed::on_checkBox_15_clicked() { ui->checkBox_16->setChecked(false); } void pthreed::on_checkBox_16_clicked() { ui->checkBox_15->setChecked(false); } void pthreed::on_spinBox_valueChanged() { QFont legendFont = font(); legendFont.setPointSize(ui->spinBox->value()); ui->customPlot->xAxis->setLabelFont(legendFont); ui->customPlot->yAxis->setLabelFont(legendFont); ui->customPlot->xAxis->setTickLabelFont(legendFont); ui->customPlot->yAxis->setTickLabelFont(legendFont); }
31.52
105
0.513473
DPSablowski
5f9f096d5967322c3eb1d8ae124bcf402357d4ef
1,452
cpp
C++
toml/src/storage.cpp
Hun1eR/TOML
7c47b3fd7b9d0321f0614cc8c51da8c7e458c22b
[ "MIT" ]
5
2020-05-12T20:11:00.000Z
2021-02-26T16:59:05.000Z
toml/src/storage.cpp
Hun1eR/TOML
7c47b3fd7b9d0321f0614cc8c51da8c7e458c22b
[ "MIT" ]
null
null
null
toml/src/storage.cpp
Hun1eR/TOML
7c47b3fd7b9d0321f0614cc8c51da8c7e458c22b
[ "MIT" ]
null
null
null
// *********************************************************************** // Author : the_hunter // Created : 04-01-2020 // // Last Modified By : the_hunter // Last Modified On : 04-01-2020 // *********************************************************************** #include <toml/pch.h> /// <summary> /// </summary> static std::list<TomlHolder> g_holders; /// <summary> /// </summary> cell Storage::add(toml_t&& toml) { auto* const root = new toml_t(toml); g_holders.emplace_back(root); return g_holders.back().handle(); } /// <summary> /// </summary> TomlHolder* Storage::get(const cell handle, const bool throw_error) { for (auto& toml_holder : g_holders) { auto* holder = toml_holder.find(handle); if (holder) { return holder; } } if (!throw_error) { return nullptr; } throw std::invalid_argument("Invalid TOML handle provided (" + std::to_string(handle) + ")."); } /// <summary> /// </summary> void Storage::remove(const cell handle) { if (handle == TOML_INVALID_HANDLE) { return; } const auto& it = std::find(g_holders.begin(), g_holders.end(), handle); if (it != g_holders.end()) { auto* toml = it->toml(); g_holders.erase(it); delete toml; return; } for (auto& holder : g_holders) { if (holder.remove(handle)) { break; } } } /// <summary> /// </summary> void Storage::clear() { for (const auto& holder : g_holders) { delete holder.toml(); } g_holders.clear(); }
18.379747
95
0.562672
Hun1eR
5fa42e7f7a4287c5bd7052bb8399ef7c4786dab7
1,548
cpp
C++
DevelopmentGame/Game/Source/Hearts.cpp
RubokiReuchi/Development-Platform-Game
59175b86863bf3691422e9289fbb9fa46316f047
[ "MIT" ]
null
null
null
DevelopmentGame/Game/Source/Hearts.cpp
RubokiReuchi/Development-Platform-Game
59175b86863bf3691422e9289fbb9fa46316f047
[ "MIT" ]
null
null
null
DevelopmentGame/Game/Source/Hearts.cpp
RubokiReuchi/Development-Platform-Game
59175b86863bf3691422e9289fbb9fa46316f047
[ "MIT" ]
null
null
null
#include "App.h" #include "Textures.h" #include "Render.h" #include "Map.h" #include "Hearts.h" #include "Player.h" #include "Defs.h" #include "Log.h" Hearts::Hearts() : Entity() {} // Destructor Hearts::~Hearts() {} void Hearts::InitCustomEntity() { b2BodyDef c_body; c_body.type = b2_staticBody; c_body.position.Set(position.x,position.y); body = app->physics->world->CreateBody(&c_body); b2PolygonShape box; box.SetAsBox(PIXELS_TO_METERS(w), PIXELS_TO_METERS(h), b2Vec2(PIXELS_TO_METERS(16), PIXELS_TO_METERS(16)), 0); b2FixtureDef fixture; fixture.shape = &box; b2Fixture* bodyFixture = body->CreateFixture(&fixture); bodyFixture->SetSensor(true); bodyFixture->SetUserData((void*)10); // heart collision picked = false; } // Called each loop iteration bool Hearts::PreUpdate() { position.x = body->GetPosition().x; position.y = body->GetPosition().y; return true; } // Called each loop iteration bool Hearts::Update(float dt) { return true; } // Called each loop iteration bool Hearts::Draw() { bool ret = true; if (plan_to_delete) { app->physics->world->DestroyBody(body); plan_to_delete = false; } if (!picked) { app->render->DrawTexture(app->tex->heart_texture, METERS_TO_PIXELS(position.x), METERS_TO_PIXELS(position.y)); } return ret; } bool Hearts::DeleteEntity() { app->entities->nlifes++; sprintf_s(app->entities->numLifes, 3, "%02d", app->entities->nlifes); picked = true; position.x = body->GetPosition().x; position.y = body->GetPosition().y; plan_to_delete = true; return true; }
19.111111
112
0.704134
RubokiReuchi
5fa5e0ef92cc0e2b77957b9b4cde329b971ef1cf
2,945
hpp
C++
include/makeshift/experimental/functional.hpp
mbeutel/makeshift
68e6bdee79060f3b258c031c53ff641325d13411
[ "BSL-1.0" ]
3
2020-04-03T14:06:41.000Z
2021-11-09T23:55:52.000Z
include/makeshift/experimental/functional.hpp
mbeutel/makeshift
68e6bdee79060f3b258c031c53ff641325d13411
[ "BSL-1.0" ]
2
2020-04-03T14:21:09.000Z
2022-02-08T14:37:01.000Z
include/makeshift/experimental/functional.hpp
mbeutel/makeshift
68e6bdee79060f3b258c031c53ff641325d13411
[ "BSL-1.0" ]
null
null
null
#ifndef INCLUDED_MAKESHIFT_EXPERIMENTAL_FUNCTIONAL_HPP_ #define INCLUDED_MAKESHIFT_EXPERIMENTAL_FUNCTIONAL_HPP_ #include <utility> // for move(), forward<>() #include <type_traits> // for move(), forward<>() #include <gsl-lite/gsl-lite.hpp> // for gsl_CPP17_OR_GREATER #include <makeshift/experimental/detail/functional.hpp> namespace makeshift { namespace gsl = ::gsl_lite; // // Forwards //ᅟ //ᅟ auto v = std::vector<int>{ ... }; //ᅟ auto f = forward_to( //ᅟ [context = ...]() //ᅟ { //ᅟ return [&](auto forward_capture){ //ᅟ { //ᅟ g(forward_capture(context)); //ᅟ }; //ᅟ }); // template <typename F> detail::forward_to_impl<F> forward_to(F func) { return detail::forward_to_impl<F>{ std::move(func) }; } // Usage: // // auto f = forward_to( // [shared_state] // { // return overload( // [&](int i) { g(i, shared_state); }, // [&](float f) { h(f, shared_state); }); // }); template <typename F> struct rvalue_ref_fn : F { constexpr rvalue_ref_fn(F func) : F(std::move(func)) { } template <typename... Ts> constexpr auto operator ()(Ts&&... args) && -> decltype(static_cast<F&&>(*this)(std::forward<Ts>(args)...)) { return static_cast<F&&>(*this)(std::forward<Ts>(args)...); } }; #if gsl_CPP17_OR_GREATER template <typename F> rvalue_ref_fn(F) -> rvalue_ref_fn<F>; #endif // gsl_CPP17_OR_GREATER template <typename F> constexpr rvalue_ref_fn<F> make_rvalue_ref_fn(F func) { return { std::move(func) }; } template <typename F> struct lvalue_ref_fn : F { constexpr lvalue_ref_fn(F func) : F(std::move(func)) { } template <typename... Ts> constexpr auto operator ()(Ts&&... args) & -> decltype(static_cast<F&>(*this)(std::forward<Ts>(args)...)) { return static_cast<F&>(*this)(std::forward<Ts>(args)...); } }; #if gsl_CPP17_OR_GREATER template <typename F> lvalue_ref_fn(F) -> lvalue_ref_fn<F>; #endif // gsl_CPP17_OR_GREATER template <typename F> constexpr lvalue_ref_fn<F> make_lvalue_ref_fn(F func) { return { std::move(func) }; } template <typename F> struct lvalue_const_ref_fn : F { constexpr lvalue_const_ref_fn(F func) : F(std::move(func)) { } template <typename... Ts> constexpr auto operator ()(Ts&&... args) const& -> decltype(static_cast<F const&>(*this)(std::forward<Ts>(args)...)) { return static_cast<F const&>(*this)(std::forward<Ts>(args)...); } }; #if gsl_CPP17_OR_GREATER template <typename F> lvalue_const_ref_fn(F) -> lvalue_const_ref_fn<F>; #endif // gsl_CPP17_OR_GREATER template <typename F> constexpr lvalue_const_ref_fn<F> make_lvalue_const_ref_fn(F func) { return { std::move(func) }; } } // namespace makeshift #endif // INCLUDED_MAKESHIFT_EXPERIMENTAL_FUNCTIONAL_HPP_
24.139344
76
0.615959
mbeutel
5fa7529d1d4cff8639920472a609926a5bcc7b84
16,384
cpp
C++
vkconfig_core/test/test_configuration_built_in.cpp
Puschel2020/VulkanTools
6698657af2291c8cba809069a77e8fc90ff70406
[ "Apache-2.0" ]
null
null
null
vkconfig_core/test/test_configuration_built_in.cpp
Puschel2020/VulkanTools
6698657af2291c8cba809069a77e8fc90ff70406
[ "Apache-2.0" ]
null
null
null
vkconfig_core/test/test_configuration_built_in.cpp
Puschel2020/VulkanTools
6698657af2291c8cba809069a77e8fc90ff70406
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020 Valve Corporation * Copyright (c) 2020 LunarG, Inc. * * 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. * * Authors: * - Christophe Riccio <christophe@lunarg.com> */ #include "../configuration.h" #include "../util.h" #include "../layer_manager.h" #include <array> #include <string> #include <gtest/gtest.h> static bool operator==(const Configuration& a, const Configuration& b) { if (a.key != b.key) return false; else if (a.platform_flags != b.platform_flags) return false; else if (a.description != b.description) return false; else if (a.setting_tree_state != b.setting_tree_state) return false; else if (a.parameters != b.parameters) return false; return true; } static bool operator!=(const Configuration& a, const Configuration& b) { return !(a == b); } static bool operator==(const Parameter& a, const Parameter& b) { if (a.key != b.key) return false; if (a.state != b.state) return false; if (a.settings.Size() != b.settings.Size()) return false; for (std::size_t i = 0, n = a.settings.Size(); i < n; ++i) { if (a.settings[i] != b.settings[i]) return false; } return true; } static bool operator!=(const std::vector<Parameter>& a, const std::vector<Parameter>& b) { return !(a == b); } struct TestBuilin { TestBuilin(const char* layers_version) : layers_version(layers_version), environment(paths), layer_manager(environment) { this->layer_manager.LoadLayersFromPath(format(":/layers/%s", layers_version).c_str()); EXPECT_TRUE(!this->layer_manager.available_layers.empty()); } ~TestBuilin() { environment.Reset(Environment::SYSTEM); // Don't change the system settings on exit } Configuration Load(const char* configuration_name) { Configuration configuration_loaded; EXPECT_TRUE(configuration_loaded.Load(layer_manager.available_layers, format(":/configurations/%s.json", configuration_name).c_str())); EXPECT_TRUE(!configuration_loaded.parameters.empty()); return configuration_loaded; } Configuration Restore(const Configuration& configuration_loaded) { const std::string filename = format("test_%s_layers_%s.json", configuration_loaded.key.c_str(), layers_version.c_str()); const bool saved = configuration_loaded.Save(this->layer_manager.available_layers, filename.c_str()); EXPECT_TRUE(saved); Configuration configuration_saved; EXPECT_TRUE(configuration_saved.Load(this->layer_manager.available_layers, filename.c_str())); return configuration_saved; } std::string layers_version; PathManager paths; Environment environment; LayerManager layer_manager; }; // Layers 130 TEST(test_built_in_load, layers_130_with_api_dump) { TestBuilin test("130"); EXPECT_EQ(5, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("API dump"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_130_with_frame_capture) { TestBuilin test("130"); EXPECT_EQ(5, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Frame Capture"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_130_with_portability) { TestBuilin test("130"); EXPECT_EQ(5, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Portability"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_130_with_synchronization) { TestBuilin test("130"); EXPECT_EQ(5, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Synchronization"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_130_with_validation) { TestBuilin test("130"); EXPECT_EQ(5, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Validation"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } // Layers 135 TEST(test_built_in_load, layers_135_with_api_dump) { TestBuilin test("135"); EXPECT_EQ(5, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("API dump"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_135_with_frame_capture) { TestBuilin test("135"); EXPECT_EQ(5, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Frame Capture"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_135_with_portability) { TestBuilin test("135"); EXPECT_EQ(5, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Portability"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_135_with_synchronization) { TestBuilin test("135"); EXPECT_EQ(5, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Synchronization"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_135_with_validation) { TestBuilin test("135"); EXPECT_EQ(5, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Validation"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } // Layers 141 TEST(test_built_in_load, layers_141_with_api_dump) { TestBuilin test("141"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("API dump"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_141_with_frame_capture) { TestBuilin test("141"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Frame Capture"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_141_with_portability) { TestBuilin test("141"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Portability"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_141_with_synchronization) { TestBuilin test("141"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Synchronization"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_141_with_validation) { TestBuilin test("141"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Validation"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } // Layers 148 TEST(test_built_in_load, layers_148_with_api_dump) { TestBuilin test("148"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("API dump"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_148_with_frame_capture) { TestBuilin test("148"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Frame Capture"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_148_with_portability) { TestBuilin test("148"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Portability"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_148_with_synchronization) { TestBuilin test("148"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Synchronization"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_148_with_validation) { TestBuilin test("148"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Validation"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } // Layers 154 TEST(test_built_in_load, layers_154_with_api_dump) { TestBuilin test("154"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("API dump"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_154_with_frame_capture) { TestBuilin test("154"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Frame Capture"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_154_with_portability) { TestBuilin test("154"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Portability"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_154_with_synchronization) { TestBuilin test("154"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Synchronization"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_154_with_validation) { TestBuilin test("154"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Validation"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } // Layers 162 TEST(test_built_in_load, layers_162_with_api_dump) { TestBuilin test("162"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("API dump"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_162_with_frame_capture) { TestBuilin test("162"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Frame Capture"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_162_with_portability) { TestBuilin test("162"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Portability"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_162_with_synchronization) { TestBuilin test("162"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Synchronization"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_162_with_validation) { TestBuilin test("162"); EXPECT_EQ(6, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Validation"); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(configuration_loaded, configuration_saved); } // Layers Latest TEST(test_built_in_load, layers_latest_with_api_dump) { TestBuilin test("latest"); EXPECT_EQ(7, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("API dump"); EXPECT_EQ(1, configuration_loaded.parameters.size()); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(1, configuration_saved.parameters.size()); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_latest_with_frame_capture) { TestBuilin test("latest"); EXPECT_EQ(7, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Frame Capture"); EXPECT_EQ(1, configuration_loaded.parameters.size()); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(1, configuration_saved.parameters.size()); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_latest_with_portability) { TestBuilin test("latest"); EXPECT_EQ(7, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Portability"); EXPECT_EQ(7, configuration_loaded.parameters.size()); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(7, configuration_saved.parameters.size()); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_latest_with_synchronization) { TestBuilin test("latest"); EXPECT_EQ(7, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Synchronization"); EXPECT_EQ(2, configuration_loaded.parameters.size()); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(2, configuration_saved.parameters.size()); EXPECT_EQ(configuration_loaded, configuration_saved); } TEST(test_built_in_load, layers_latest_with_validation) { TestBuilin test("latest"); EXPECT_EQ(7, test.layer_manager.available_layers.size()); Configuration configuration_loaded = test.Load("Validation"); EXPECT_EQ(1, configuration_loaded.parameters.size()); Configuration configuration_saved = test.Restore(configuration_loaded); EXPECT_EQ(1, configuration_saved.parameters.size()); EXPECT_EQ(configuration_loaded, configuration_saved); }
34.565401
128
0.76123
Puschel2020
5faaf4b0cbc8272189025dd8e2311605f58fe634
1,082
cpp
C++
Core/Core.cpp
Zaangetsuu/Zia
05868c5cc94c571ba76fd414fac970f5cd6e4556
[ "MIT" ]
null
null
null
Core/Core.cpp
Zaangetsuu/Zia
05868c5cc94c571ba76fd414fac970f5cd6e4556
[ "MIT" ]
null
null
null
Core/Core.cpp
Zaangetsuu/Zia
05868c5cc94c571ba76fd414fac970f5cd6e4556
[ "MIT" ]
null
null
null
// // Created by corentin on 20/02/18. // #include "Core.hpp" //Core Core::_singleton = Core(); Core::Core() : _configHandler("zia.conf"), _moduleManager(), _mutex() { } Core::~Core() = default; void Core::run() { updateConfig(); } void Core::updateConfig() { zia::api::Conf configuration; configuration = _configHandler.getConfiguration(); _moduleManager.updateModules(configuration, _moduleNet, _pipeline); } void Core::callback(zia::api::Net::Raw raw, zia::api::NetInfo info) { _mutex.lock(); updateConfig(); std::string string1(reinterpret_cast<const char *>(&raw[0]), raw.size()); std::cout << "-------- Received Data --------- " << std::endl << string1; zia::api::HttpDuplex duplex; duplex.raw_req = raw; zia::api::Conf conf = _configHandler.getConfiguration(); for (auto &module : _pipeline) { module->config(conf); module->exec(duplex); } _moduleNet->send(info.sock, duplex.raw_resp); _mutex.unlock(); } Core &Core::Instance() { static Core _instance; return _instance; }
20.415094
77
0.630314
Zaangetsuu
5fb0e05c133e2dab3ebf65e9d1127851ef965d8c
826
cpp
C++
game/src/Settings.cpp
Hvvang/Puzzle
0f798e3d1f4388b255a7a393b8671e4d1930cdb0
[ "MIT" ]
null
null
null
game/src/Settings.cpp
Hvvang/Puzzle
0f798e3d1f4388b255a7a393b8671e4d1930cdb0
[ "MIT" ]
null
null
null
game/src/Settings.cpp
Hvvang/Puzzle
0f798e3d1f4388b255a7a393b8671e4d1930cdb0
[ "MIT" ]
null
null
null
// // Created by Artem Shemidko on 6/22/21. // #include "Settings.hpp" Settings *Settings::m_instance = nullptr; Settings::Settings() { std::ifstream file(ConfigFilePath); if (!file.is_open()) { throw std::invalid_argument(ConfigFilePath); } m_settings = json::parse(file); file.close(); m_instance = this; } void Settings::setValue(const std::string &key, const json &value) { m_settings[key] = value; std::fstream file(ConfigFilePath); if (!file.is_open()) { throw std::invalid_argument(ConfigFilePath); } file << m_settings.dump(4); file.close(); } json Settings::getValue(const std::string &key) { return m_settings[key]; } Settings *Settings::singleton() { if (!m_instance) { m_instance = new Settings; } return m_instance; }
20.65
68
0.639225
Hvvang
5fb3b850bd54d5d5fc57b674c97c079236794cb6
35,086
cpp
C++
Source/Mesh/kdtree.cpp
INM-RAS/INMOST
2846aa63c1fc11c406cb2d558646237223183201
[ "BSD-3-Clause" ]
null
null
null
Source/Mesh/kdtree.cpp
INM-RAS/INMOST
2846aa63c1fc11c406cb2d558646237223183201
[ "BSD-3-Clause" ]
7
2015-01-05T16:41:55.000Z
2015-01-17T11:21:06.000Z
Source/Mesh/kdtree.cpp
INM-RAS/INMOST
2846aa63c1fc11c406cb2d558646237223183201
[ "BSD-3-Clause" ]
null
null
null
#include "inmost_mesh.h" #if defined(USE_MESH) #define _m0(x) (x & 0x7FF) #define _m1(x) (x >> 11 & 0x7FF) #define _m2(x) (x >> 22 ) namespace INMOST { inline static void crossproduct(const Storage::real vecin1[3],const Storage::real vecin2[3], Storage::real vecout[3]) { vecout[0] = vecin1[1]*vecin2[2] - vecin1[2]*vecin2[1]; vecout[1] = vecin1[2]*vecin2[0] - vecin1[0]*vecin2[2]; vecout[2] = vecin1[0]*vecin2[1] - vecin1[1]*vecin2[0]; } inline static Storage::real dotproduct(const Storage::real * vecin1, const Storage::real * vecin2) { return vecin1[0]*vecin2[0]+vecin1[1]*vecin2[1]+vecin1[2]*vecin2[2]; } template<typename bbox_type> inline int SearchKDTree::bbox_point(const Storage::real p[3], const bbox_type bbox[6]) { for(int i = 0; i < 3; i++) { if( p[i] < bbox[i*2]-1.0e-3 || p[i] > bbox[i*2+1]+1.0e-3 ) return 0; } return 1; } template<typename bbox_type> inline int SearchKDTree::bbox_point_print(const Storage::real p[3], const bbox_type bbox[6], std::ostream & sout) { for (int i = 0; i < 3; i++) { if (p[i] < bbox[i * 2] - 1.0e-3 || p[i] > bbox[i * 2 + 1] + 1.0e-3) { sout << "fail on " << i << " "; if (p[i] < bbox[i * 2] - 1.0e-3) sout << p[i] << " is less then " << bbox[i * 2] - 1.0e-3 << "(" << bbox[i * 2] << ")"; if (p[i] > bbox[i * 2 + 1] + 1.0e-3) sout << p[i] << " is greater then " << bbox[i * 2 + 1] + 1.0e-3 << "(" << bbox[i * 2 + 1] << ")"; sout << std::endl; return 0; } } sout << "all ok!" << std::endl; return 1; } template<typename bbox_type> inline void SearchKDTree::bbox_closest_point(const Storage::real p[3], const bbox_type bbox[6], Storage::real pout[3]) { for (int i = 0; i < 3; i++) { if (p[i] < bbox[i * 2] ) pout[i] = bbox[i * 2]; else if (p[i] > bbox[i * 2 + 1]) pout[i] = bbox[i * 2 + 1]; else pout[i] = p[i]; } return; } template<typename bbox_type> inline int SearchKDTree::bbox_sphere(const Storage::real p[3], Storage::real r, const bbox_type bbox[6]) { Storage::real pb[3], d; bbox_closest_point(p, bbox, pb); d = sqrt((pb[0] - p[0]) * (pb[0] - p[0]) + (pb[1] - p[1]) * (pb[1] - p[1]) + (pb[2] - p[2]) * (pb[2] - p[2])); return d <= r ? 1 : 0; } inline Storage::real SearchKDTree::segment_distance(const Storage::real a[3], const Storage::real b[3], const Storage::real p[3]) { Storage::real pout[3]; Storage::real v[3] = { b[0] - a[0],b[1] - a[1],b[2] - a[2] }; Storage::real d = v[0] * v[0] + v[1] * v[1] + v[2] * v[2]; Storage::real t = (v[0] * (p[0] - a[0]) + v[1] * (p[1] - a[1]) + v[2] * (p[2] - a[2])) / d; if (t >= 0.0 && t <= 1.0) { pout[0] = a[0] + t * v[0]; pout[1] = a[1] + t * v[1]; pout[2] = a[2] + t * v[2]; } else if (t < 0.0) { pout[0] = a[0]; pout[1] = a[1]; pout[2] = a[2]; } else { pout[0] = b[0]; pout[1] = b[1]; pout[2] = b[2]; } return sqrt((pout[0] - p[0]) * (pout[0] - p[0]) + (pout[1] - p[1]) * (pout[1] - p[1]) + (pout[2] - p[2]) * (pout[2] - p[2])); } inline Storage::real SearchKDTree::triangle_distance(const Storage::real a[3], const Storage::real b[3], const Storage::real c[3], const Storage::real p[3]) { Storage::real pout[3]; Storage::real n[3], d, t, q1[3], q2[3], q3[3], q12, q23, q13; n[0] = (b[1] - a[1]) * (c[2] - a[2]) - (b[2] - a[2]) * (c[1] - a[1]); n[1] = (b[2] - a[2]) * (c[0] - a[0]) - (b[0] - a[0]) * (c[2] - a[2]); n[2] = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); d = sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]); if (d) { n[0] /= d; n[1] /= d; n[2] /= d; } t = (a[0] - p[0]) * n[0] + (a[1] - p[1]) * n[1] + (a[2] - p[2]) * n[2]; pout[0] = p[0] + t * n[0]; pout[1] = p[1] + t * n[1]; pout[2] = p[2] + t * n[2]; q1[0] = (pout[1] - a[1]) * (pout[2] - b[2]) - (pout[1] - b[1]) * (pout[2] - a[2]); q1[1] = (pout[2] - a[2]) * (pout[0] - b[0]) - (pout[2] - b[2]) * (pout[0] - a[0]); q1[2] = (pout[0] - a[0]) * (pout[1] - b[1]) - (pout[0] - b[0]) * (pout[1] - a[1]); q2[0] = (pout[1] - b[1]) * (pout[2] - c[2]) - (pout[1] - c[1]) * (pout[2] - b[2]); q2[1] = (pout[2] - b[2]) * (pout[0] - c[0]) - (pout[2] - c[2]) * (pout[0] - b[0]); q2[2] = (pout[0] - b[0]) * (pout[1] - c[1]) - (pout[0] - c[0]) * (pout[1] - b[1]); q3[0] = (pout[1] - c[1]) * (pout[2] - a[2]) - (pout[1] - a[1]) * (pout[2] - c[2]); q3[1] = (pout[2] - c[2]) * (pout[0] - a[0]) - (pout[2] - a[2]) * (pout[0] - c[0]); q3[2] = (pout[0] - c[0]) * (pout[1] - a[1]) - (pout[0] - a[0]) * (pout[1] - c[1]); q12 = q1[0] * q2[0] + q1[1] * q2[1] + q1[2] * q2[2]; q23 = q2[0] * q3[0] + q2[1] * q3[1] + q2[2] * q3[2]; q13 = q1[0] * q3[0] + q1[1] * q3[1] + q1[2] * q3[2]; if (q12 >= 0 && q23 >= 0 && q13 >= 0) return fabs(t); Storage::real dmin = segment_distance(a, b, p); dmin = std::min(dmin, segment_distance(b, c, p)); dmin = std::min(dmin, segment_distance(c, a, p)); return dmin; } int SearchKDTree::cmpElements0(const void * a,const void * b) { const entry * ea = ((const entry *)a); const entry * eb = ((const entry *)b); float ad = ea->xyz[0]; float bd = eb->xyz[0]; return (ad > bd) - (ad < bd); } int SearchKDTree::cmpElements1(const void * a,const void * b) { const entry * ea = ((const entry *)a); const entry * eb = ((const entry *)b); float ad = ea->xyz[1]; float bd = eb->xyz[1]; return (ad > bd) - (ad < bd); } int SearchKDTree::cmpElements2(const void * a,const void * b) { const entry * ea = ((const entry *)a); const entry * eb = ((const entry *)b); float ad = ea->xyz[2]; float bd = eb->xyz[2]; return (ad > bd) - (ad < bd); } inline unsigned int SearchKDTree::flip(const unsigned int * fp) { unsigned int mask = -((int)(*fp >> 31)) | 0x80000000; return *fp ^ mask; } void SearchKDTree::radix_sort(int dim, struct entry * temp) { unsigned int i; const unsigned int kHist = 2048; unsigned int b0[kHist * 3]; unsigned int *b1 = b0 + kHist; unsigned int *b2 = b1 + kHist; memset(b0,0,sizeof(unsigned int)*kHist*3); for (i = 0; i < size; i++) { unsigned int fi = flip((unsigned int *)&set[i].xyz[dim]); ++b0[_m0(fi)]; ++b1[_m1(fi)]; ++b2[_m2(fi)]; } { unsigned int sum0 = 0, sum1 = 0, sum2 = 0; for (i = 0; i < kHist; i++) { b0[kHist-1] = b0[i] + sum0; b0[i] = sum0 - 1; sum0 = b0[kHist-1]; b1[kHist-1] = b1[i] + sum1; b1[i] = sum1 - 1; sum1 = b1[kHist-1]; b2[kHist-1] = b2[i] + sum2; b2[i] = sum2 - 1; sum2 = b2[kHist-1]; } } for (i = 0; i < size; i++) temp[++b0[_m0(flip((unsigned int *)&set[i].xyz[dim]))]] = set[i]; for (i = 0; i < size; i++) set[++b1[_m1(flip((unsigned int *)&temp[i].xyz[dim]))]] = temp[i]; for (i = 0; i < size; i++) temp[++b2[_m2(flip((unsigned int *)&set[i].xyz[dim]))]] = set[i]; for (i = 0; i < size; i++) set[i] = temp[i]; } void SearchKDTree::kdtree_build(int dim, int & done, int total, struct entry * temp) { if( size > 1 ) { if( size > 128 ) radix_sort(dim,temp); else switch(dim) { case 0: qsort(set,size,sizeof(entry),cmpElements0);break; case 1: qsort(set,size,sizeof(entry),cmpElements1);break; case 2: qsort(set,size,sizeof(entry),cmpElements2);break; } children = static_cast<SearchKDTree *>(malloc(sizeof(SearchKDTree)*2));//new kdtree[2]; children[0].children = NULL; children[0].set = set; children[0].size = size/2; children[0].m = m; children[1].children = NULL; children[1].set = set+size/2; children[1].size = size - size/2; children[1].m = m; children[0].kdtree_build((dim+1)%3,done,total,temp); children[1].kdtree_build((dim+1)%3,done,total,temp); for(int k = 0; k < 3; k++) { bbox[0+2*k] = std::min<float>(children[0].bbox[0+2*k],children[1].bbox[0+2*k]); bbox[1+2*k] = std::max<float>(children[0].bbox[1+2*k],children[1].bbox[1+2*k]); } } else { assert(size == 1); { bool checkm = false, invm = false; if( m->HideMarker() ) { checkm = true; if( m->GetMarker(set[0].e,m->HideMarker()) ) invm = true; } std::vector<HandleType> nodes; if (GetHandleElementType(set[0].e) == CELL) { if (m->HighConnTag().isDefined(CELL)) { Element::adj_type& cnodes = m->HighConn(set[0].e); nodes.insert(nodes.end(), cnodes.begin(), cnodes.end()); } else { MarkerType mrk = m->CreatePrivateMarker(); Element::adj_type& faces = m->LowConn(set[0].e); for (unsigned k = 0; k < faces.size(); ++k) { Element::adj_type& fedges = m->LowConn(faces[k]); for (unsigned q = 0; q < fedges.size(); ++q) { Element::adj_type& enodes = m->LowConn(fedges[q]); for (unsigned l = 0; l < enodes.size(); ++l) if (!m->GetPrivateMarker(enodes[l], mrk)) { nodes.push_back(enodes[l]); m->SetPrivateMarker(enodes[l], mrk); } } } if (!nodes.empty()) m->RemPrivateMarkerArray(&nodes[0], (Storage::enumerator)nodes.size(), mrk); m->ReleasePrivateMarker(mrk); } } else if (GetHandleElementType(set[0].e) == FACE) { MarkerType mrk = m->CreatePrivateMarker(); Element::adj_type& fedges = m->LowConn(set[0].e); for (unsigned q = 0; q < fedges.size(); ++q) { Element::adj_type& enodes = m->LowConn(fedges[q]); for (unsigned l = 0; l < enodes.size(); ++l) if (!m->GetPrivateMarker(enodes[l], mrk)) { nodes.push_back(enodes[l]); m->SetPrivateMarker(enodes[l], mrk); } } if (!nodes.empty()) m->RemPrivateMarkerArray(&nodes[0], (Storage::enumerator)nodes.size(), mrk); m->ReleasePrivateMarker(mrk); } else { std::cout << "Unsupported element type in kd-tree" << std::endl; throw Impossible; } bbox[0] = bbox[2] = bbox[4] = 1.0e20f; bbox[1] = bbox[3] = bbox[5] = -1.0e20f; if( checkm ) { for(unsigned k = 0; k < nodes.size(); ++k) { bool hidn = m->GetMarker(nodes[k],m->HideMarker()); bool newn = m->GetMarker(nodes[k],m->NewMarker()); if( invm && newn ) continue; if( !invm && hidn ) continue; Storage::real_array coords = m->RealArrayDF(nodes[k],m->CoordsTag());; for(unsigned q = 0; q < coords.size(); q++) { bbox[q*2+0] = std::min<float>(bbox[q*2+0],(float)coords[q]); bbox[q*2+1] = std::max<float>(bbox[q*2+1],(float)coords[q]); } } } else for(unsigned k = 0; k < nodes.size(); ++k) { Storage::real_array coords = m->RealArrayDF(nodes[k],m->CoordsTag());; for(unsigned q = 0; q < coords.size(); q++) { bbox[q*2+0] = std::min<float>(bbox[q*2+0],(float)coords[q]); bbox[q*2+1] = std::max<float>(bbox[q*2+1],(float)coords[q]); } } for(int k = m->GetDimensions(); k < 3; ++k) { bbox[k*2+0] = -1.0e20f; bbox[k*2+1] = 1.0e20f; } } } } Cell SearchKDTree::SubSearchCell(const Storage::real p[3]) const { Cell ret = InvalidCell(); if( size == 1 ) { if( m->HideMarker() && m->GetMarker(set[0].e,m->HideMarker()) ) { m->SwapModification(false); if( cell_point(Cell(m,set[0].e),p) ) ret = Cell(m,set[0].e); m->SwapModification(false); } else { if( cell_point(Cell(m,set[0].e),p) ) ret = Cell(m,set[0].e); } } else { assert(size > 1); if( bbox_point(p,bbox) ) { ret = children[0].SubSearchCell(p); if( !ret.isValid() ) ret = children[1].SubSearchCell(p); } } return ret; } void PrintElement(Element c, std::ostream& sout) { sout << ElementTypeName(c.GetElementType()) << ":" << c.LocalID(); sout << " " << Element::GeometricTypeName(c.GetGeometricType()) << std::endl; sout << " faces: " << c.nbAdjElements(FACE) << " edges: " << c.nbAdjElements(EDGE) << " nodes: " << c.nbAdjElements(NODE) << std::endl; if (c.GetElementType() == CELL) { Storage::real xc[3]; c.Centroid(xc); sout << " closure: " << (c.getAsCell().Closure() ? "true" : "false"); sout << " volume: " << c.getAsCell().Volume(); sout << " x " << xc[0] << " " << xc[1] << " " << xc[2]; sout << std::endl; ElementArray<Face> faces = c.getFaces(); for (ElementArray<Face>::iterator it = faces.begin(); it != faces.end(); ++it) { Storage::real x[3], n[3]; it->Centroid(x); it->UnitNormal(n); sout << "FACE:" << it->LocalID() << " nodes " << it->nbAdjElements(NODE); sout << " closure: " << (it->Closure() ? "true" : "false"); sout << " flat: " << (it->Planarity() ? "true" : "false"); sout << " bnd " << (it->Boundary() ? "true" : "false"); sout << " ornt " << (it->CheckNormalOrientation() ? "true" : "false"); sout << " x " << x[0] << " " << x[1] << " " << x[2] << " n " << n[0] << " " << n[1] << " " << n[2] << " " << " area " << it->Area() << std::endl; } } else if (c.GetElementType() == FACE) { Face it = c.getAsFace(); Storage::real x[3], n[3]; it->Centroid(x); it->UnitNormal(n); sout << " closure: " << (it->Closure() ? "true" : "false"); sout << " flat: " << (it->Planarity() ? "true" : "false"); sout << " bnd " << (it->Boundary() ? "true" : "false"); sout << " ornt " << (it->CheckNormalOrientation() ? "true" : "false"); sout << " x " << x[0] << " " << x[1] << " " << x[2] << " n " << n[0] << " " << n[1] << " " << n[2] << " " << " area " << it->Area() << std::endl; } ElementArray<Node> nodes = c.getNodes(); for (ElementArray<Node>::iterator it = nodes.begin(); it != nodes.end(); ++it) sout << "NODE:" << it->LocalID() << " x " << it->Coords()[0] << " " << it->Coords()[1] << " " << it->Coords()[2] << std::endl; } Cell SearchKDTree::SubSearchCellPrint(const Storage::real p[3], std::ostream & sout) const { Cell ret = InvalidCell(); if (size == 1) { sout << "test cell " << GetHandleID(set[0].e) << std::endl; PrintElement(Cell(m, set[0].e), sout); if (m->HideMarker() && m->GetMarker(set[0].e, m->HideMarker())) { m->SwapModification(false); if (cell_point_print(Cell(m, set[0].e), p,sout)) ret = Cell(m, set[0].e); m->SwapModification(false); } else { if (cell_point_print(Cell(m, set[0].e), p,sout)) ret = Cell(m, set[0].e); } } else { assert(size > 1); if (bbox_point(p, bbox)) { { sout << "point " << p[0] << " " << p[1] << " " << p[2] << " is in bbox "; sout << " x " << bbox[0] << ":" << bbox[1]; sout << " y " << bbox[2] << ":" << bbox[3]; sout << " z " << bbox[4] << ":" << bbox[5]; sout << std::endl; } sout << "try left child" << std::endl; ret = children[0].SubSearchCellPrint(p, sout); sout << "ret " << (ret.isValid() ? ret.LocalID() : -1) << std::endl; if (!ret.isValid()) { sout << "try right child" << std::endl; ret = children[1].SubSearchCellPrint(p, sout); sout << "ret " << (ret.isValid() ? ret.LocalID() : -1) << std::endl; } } else { sout << "point " << p[0] << " " << p[1] << " " << p[2] << " is not in bbox "; sout << " x " << bbox[0] << ":" << bbox[1]; sout << " y " << bbox[2] << ":" << bbox[3]; sout << " z " << bbox[4] << ":" << bbox[5]; sout << std::endl; bbox_point_print(p, bbox, sout); } } return ret; } void SearchKDTree::clear_children() { if( children ) { children[0].clear_children(); children[1].clear_children(); free(children); } } SearchKDTree::SearchKDTree(Mesh * m) : m(m), children(NULL) { size = m->NumberOfCells(); if( size ) { set = new entry[size]; INMOST_DATA_ENUM_TYPE k = 0; for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); ++it) { set[k].e = it->GetHandle(); Storage::real cnt[3] = {0,0,0}; m->GetGeometricData(set[k].e,CENTROID,cnt); set[k].xyz[0] = (float)cnt[0]; set[k].xyz[1] = (float)cnt[1]; set[k].xyz[2] = (float)cnt[2]; ++k; } int done = 0, total = size; struct entry * temp = new entry[size]; kdtree_build(0,done,total,temp); delete [] temp; if( size > 1 ) { for(int k = 0; k < 3; k++) { bbox[0+2*k] = std::min<float>(children[0].bbox[0+2*k],children[1].bbox[0+2*k]); bbox[1+2*k] = std::max<float>(children[0].bbox[1+2*k],children[1].bbox[1+2*k]); } } } } SearchKDTree::SearchKDTree(Mesh * m, HandleType * _set, unsigned set_size) : m(m), children(NULL) { size = set_size; if( size ) { set = new entry[size]; for(unsigned k = 0; k < set_size; ++k) { set[k].e = _set[k]; Storage::real cnt[3] = {0,0,0}; m->GetGeometricData(set[k].e,CENTROID,cnt); set[k].xyz[0] = (float)cnt[0]; set[k].xyz[1] = (float)cnt[1]; set[k].xyz[2] = (float)cnt[2]; } int done = 0, total = size; struct entry * temp = new entry[size]; kdtree_build(0,done,total,temp); delete [] temp; if( size > 1 ) { for(int k = 0; k < 3; k++) { bbox[0+2*k] = std::min<float>(children[0].bbox[0+2*k],children[1].bbox[0+2*k]); bbox[1+2*k] = std::max<float>(children[0].bbox[1+2*k],children[1].bbox[1+2*k]); } } } else set = NULL; } inline int SearchKDTree::sphere_tri(const Storage::real tri[3][3], const Storage::real p[3], Storage::real r) const { return triangle_distance(tri[0], tri[1], tri[2], p) <= r ? 1 : 0; } inline int SearchKDTree::segment_tri(const Storage::real tri[3][3], const Storage::real p1[3], const Storage::real p2[3]) const { const Storage::real eps = 1.0e-7; Storage::real a[3],b[3],c[3],n[3], ray[3], d, k, m, l; Storage::real dot00,dot01,dot02,dot11,dot12,invdenom, uq,vq; ray[0] = p2[0]-p1[0]; ray[1] = p2[1]-p1[1]; ray[2] = p2[2]-p1[2]; /* l = sqrt(dotproduct(ray,ray)); if (l) { ray[0] /= l; ray[1] /= l; ray[2] /= l; } */ a[0] = tri[0][0] - tri[2][0]; a[1] = tri[0][1] - tri[2][1]; a[2] = tri[0][2] - tri[2][2]; b[0] = tri[1][0] - tri[2][0]; b[1] = tri[1][1] - tri[2][1]; b[2] = tri[1][2] - tri[2][2]; crossproduct(a,b,n); l = sqrt(dotproduct(n, n)); if (l) { n[0] /= l; n[1] /= l; n[2] /= l; } d = -dotproduct(n,tri[2]); m = dotproduct(n,ray); if( fabs(m) < 1.0e-25 ) return 0; k = -(d + dotproduct(n,p1))/m; if (k < -1.0e-10 || k > 1.0 + 1.0e-10) return 0; c[0] = p1[0] + k*ray[0] - tri[2][0]; c[1] = p1[1] + k*ray[1] - tri[2][1]; c[2] = p1[2] + k*ray[2] - tri[2][2]; dot00 = dotproduct(a,a); dot01 = dotproduct(a,b); dot02 = dotproduct(a,c); dot11 = dotproduct(b,b); dot12 = dotproduct(b,c); invdenom = (dot00*dot11 - dot01*dot01); uq = (dot11*dot02-dot01*dot12); vq = (dot00*dot12-dot01*dot02); if( fabs(invdenom) < 1.0e-25 && fabs(uq) > 0.0 && fabs(vq) > 0.0 ) return 0; uq = uq/invdenom; vq = vq/invdenom; if( uq >= -eps && vq >= -eps && 1.0-(uq+vq) >= -eps ) return 1; return 0; } inline int SearchKDTree::segment_tri_print(const Storage::real tri[3][3], const Storage::real p1[3], const Storage::real p2[3], std::ostream& sout) const { const Storage::real eps = 1.0e-7; Storage::real a[3], b[3], c[3], n[3], ray[3], d, k, m, l; Storage::real dot00, dot01, dot02, dot11, dot12, invdenom, uq, vq; ray[0] = p2[0] - p1[0]; ray[1] = p2[1] - p1[1]; ray[2] = p2[2] - p1[2]; /* l = sqrt(dotproduct(ray,ray)); if (l) { ray[0] /= l; ray[1] /= l; ray[2] /= l; } */ a[0] = tri[0][0] - tri[2][0]; a[1] = tri[0][1] - tri[2][1]; a[2] = tri[0][2] - tri[2][2]; b[0] = tri[1][0] - tri[2][0]; b[1] = tri[1][1] - tri[2][1]; b[2] = tri[1][2] - tri[2][2]; crossproduct(a, b, n); l = sqrt(dotproduct(n, n)); if (l) { n[0] /= l; n[1] /= l; n[2] /= l; } sout << "n " << n[0] << " " << n[1] << " " << n[2]; d = -dotproduct(n, tri[2]); m = dotproduct(n, ray); sout << " d " << d << " m " << m; if (fabs(m) < 1.0e-25) { sout << std::endl; return 0; } k = -(d + dotproduct(n, p1)) / m; sout << " k " << k; if (k < -1.0e-10 || k > 1.0 + 1.0e-10) { sout << std::endl; return 0; } c[0] = p1[0] + k * ray[0] - tri[2][0]; c[1] = p1[1] + k * ray[1] - tri[2][1]; c[2] = p1[2] + k * ray[2] - tri[2][2]; sout << " c " << c[0] << " " << c[1] << " " << c[2]; dot00 = dotproduct(a, a); dot01 = dotproduct(a, b); dot02 = dotproduct(a, c); dot11 = dotproduct(b, b); dot12 = dotproduct(b, c); invdenom = (dot00 * dot11 - dot01 * dot01); uq = (dot11 * dot02 - dot01 * dot12); vq = (dot00 * dot12 - dot01 * dot02); sout << " invdenom " << invdenom << " uq " << uq << " vq " << vq; if (fabs(invdenom) < 1.0e-25 && fabs(uq) > 0.0 && fabs(vq) > 0.0) { sout << std::endl; return 0; } uq = uq / invdenom; vq = vq / invdenom; sout << " coefs " << 1 - uq - vq << " " << uq << " " << vq; if (uq >= -eps && vq >= -eps && 1.0 - (uq + vq) >= -eps) { sout << " hit!" << std::endl; return 1; } sout << std::endl; return 0; } inline int SearchKDTree::segment_bbox(const Storage::real p1[3], const Storage::real p2[3]) const { Storage::real tnear = -1.0e20, tfar = 1.0e20; Storage::real t1,t2,c; for(int i = 0; i < 3; i++) { if( fabs(p2[i]-p1[i]) < 1.0e-15 ) { if( p1[i] < bbox[i*2]-1.0e-3 || p1[i] > bbox[i*2+1]+1.0e-3 ) return 0; } else { t1 = (bbox[i*2+0]-1.0e-3 - p1[i])/(p2[i]-p1[i]); t2 = (bbox[i*2+1]+1.0e-3 - p1[i])/(p2[i]-p1[i]); if( t1 > t2 ) { c = t1; t1 = t2; t2 = c; } if( t1 > tnear ) tnear = t1; if( t2 < tfar ) tfar = t2; if( tnear > tfar ) return 0; if( tfar < 0 ) return 0; if( tnear > 1 ) return 0; } } return 1; } inline int SearchKDTree::sphere_bbox(const Storage::real p[3], Storage::real r) const { return bbox_sphere(p, r, bbox); } inline int SearchKDTree::ray_bbox(double pos[3], double ray[3], double closest) const { double tnear = -1.0e20, tfar = 1.0e20, t1, t2, c; for (int i = 0; i < 3; i++) { if (fabs(ray[i]) < 1.0e-15) { if (pos[i] < bbox[i * 2] || pos[i] > bbox[i * 2 + 1]) return 0; } else { t1 = (bbox[i * 2 + 0] - pos[i]) / ray[i]; t2 = (bbox[i * 2 + 1] - pos[i]) / ray[i]; if (t1 > t2) { c = t1; t1 = t2; t2 = c; } if (t1 > tnear) tnear = t1; if (t2 < tfar) tfar = t2; if (tnear > closest) return 0; if (tnear > tfar) return 0; if (tfar < 0) return 0; } } return 1; } inline bool SearchKDTree::segment_face(const Element & f, const Storage::real p1[3], const Storage::real p2[3]) const { Mesh * m = f->GetMeshLink(); Storage::real tri[3][3] = {{0,0,0},{0,0,0},{0,0,0}}; m->GetGeometricData(f->GetHandle(),CENTROID,tri[2]); ElementArray<Node> nodes = f->getNodes(); m->GetGeometricData(nodes[0]->GetHandle(),CENTROID,tri[1]); for(ElementArray<Node>::size_type k = 0; k < nodes.size(); ++k) { memcpy(tri[0],tri[1],sizeof(Storage::real)*3); //m->GetGeometricData(nodes[k]->GetHandle(),CENTROID,tri[0]); m->GetGeometricData(nodes[(k+1)%nodes.size()]->GetHandle(),CENTROID,tri[1]); if( segment_tri(tri,p1,p2) ) return true; } return false; } inline bool SearchKDTree::segment_face_print(const Element& f, const Storage::real p1[3], const Storage::real p2[3], std::ostream & sout) const { Mesh* m = f->GetMeshLink(); Storage::real tri[3][3] = { {0,0,0},{0,0,0},{0,0,0} }, nrm[3]; f.getAsFace().UnitNormal(nrm); m->GetGeometricData(f->GetHandle(), CENTROID, tri[2]); sout << "segment_face FACE:" << f.LocalID(); sout << " x " << tri[2][0] << " " << tri[2][1] << " " << tri[2][2]; sout << " n " << nrm[0] << " " << nrm[1] << " " << nrm[2]; sout << " bnd " << (f.getAsFace().Boundary() ? "true" : "false"); sout << " ornt " << (f.getAsFace().CheckNormalOrientation() ? "true" : "false"); sout << " nodes " << f.nbAdjElements(NODE); sout << std::endl; ElementArray<Node> nodes = f->getNodes(); m->GetGeometricData(nodes[0]->GetHandle(), CENTROID, tri[1]); for (ElementArray<Node>::size_type k = 0; k < nodes.size(); ++k) { memcpy(tri[0], tri[1], sizeof(Storage::real) * 3); //m->GetGeometricData(nodes[k]->GetHandle(),CENTROID,tri[0]); m->GetGeometricData(nodes[(k + 1) % nodes.size()]->GetHandle(), CENTROID, tri[1]); if (segment_tri_print(tri, p1, p2,sout)) return true; } return false; } inline bool SearchKDTree::sphere_face(const Element& f, const Storage::real p[3], Storage::real r) const { Mesh* m = f->GetMeshLink(); Storage::real tri[3][3] = { {0,0,0},{0,0,0},{0,0,0} }; m->GetGeometricData(f->GetHandle(), CENTROID, tri[2]); ElementArray<Node> nodes = f->getNodes(); m->GetGeometricData(nodes[0]->GetHandle(), CENTROID, tri[1]); for (ElementArray<Node>::size_type k = 0; k < nodes.size(); ++k) { memcpy(tri[0], tri[1], sizeof(Storage::real) * 3); //m->GetGeometricData(nodes[k]->GetHandle(),CENTROID,tri[0]); m->GetGeometricData(nodes[(k + 1) % nodes.size()]->GetHandle(), CENTROID, tri[1]); if (sphere_tri(tri, p, r)) return true; } return false; } inline bool SearchKDTree::segment_cell(const Element & c, const Storage::real p1[3], const Storage::real p2[3]) const { ElementArray<Face> faces = c->getFaces(); for(ElementArray<Face>::iterator it = faces.begin(); it != faces.end(); ++it) if( segment_face(it->self(),p1,p2) ) return true; return false; } inline bool SearchKDTree::sphere_cell(const Element& c, const Storage::real p[3], Storage::real r) const { ElementArray<Face> faces = c->getFaces(); for (ElementArray<Face>::iterator it = faces.begin(); it != faces.end(); ++it) if (sphere_face(it->self(), p, r)) return true; return false; } void SearchKDTree::IntersectSegment(ElementArray<Cell> & cells, const Storage::real p1[3], const Storage::real p2[3]) const { ElementArray<Element> temp(m); MarkerType mrk = m->CreatePrivateMarker(); sub_intersect_segment(temp, mrk, p1, p2); m->RemPrivateMarkerArray(temp.data(), static_cast<Storage::enumerator>(temp.size()), mrk); for (ElementArray<Element>::iterator it = temp.begin(); it != temp.end(); ++it) { if (it->GetElementType() == CELL && !it->GetPrivateMarker(mrk)) { cells.push_back(it->getAsCell()); it->SetPrivateMarker(mrk); } else if (it->GetElementType() == FACE) { ElementArray<Cell> f_cells = it->getCells(); for (ElementArray<Cell>::iterator kt = f_cells.begin(); kt != f_cells.end(); ++kt) if (!kt->GetPrivateMarker(mrk)) { cells.push_back(kt->self()); kt->SetPrivateMarker(mrk); } } } m->RemPrivateMarkerArray(cells.data(), static_cast<Storage::enumerator>(cells.size()), mrk); m->ReleasePrivateMarker(mrk); } void SearchKDTree::IntersectSegment(ElementArray<Face>& faces, const Storage::real p1[3], const Storage::real p2[3]) const { ElementArray<Element> temp(m); MarkerType mrk = m->CreatePrivateMarker(); sub_intersect_segment(temp, mrk, p1, p2); m->RemPrivateMarkerArray(temp.data(), static_cast<Storage::enumerator>(temp.size()), mrk); for (ElementArray<Element>::iterator it = temp.begin(); it != temp.end(); ++it) { if (it->GetElementType() == CELL) { ElementArray<Face> f = it->getFaces(); for (ElementArray<Face>::iterator jt = f.begin(); jt != f.end(); ++jt) if( !jt->GetPrivateMarker(mrk) ) { faces.push_back(*jt); jt->SetPrivateMarker(mrk); } } else if (it->GetElementType() == FACE) { faces.push_back(it->getAsFace()); it->SetPrivateMarker(mrk); } } m->RemPrivateMarkerArray(faces.data(), static_cast<Storage::enumerator>(faces.size()), mrk); m->ReleasePrivateMarker(mrk); } void SearchKDTree::IntersectSegmentPrint(ElementArray<Face>& faces, const Storage::real p1[3], const Storage::real p2[3], std::ostream & sout) const { ElementArray<Element> temp(m); MarkerType mrk = m->CreatePrivateMarker(); sub_intersect_segment_print(temp, mrk, p1, p2, sout); sout << "found elements: " << temp.size() << std::endl; m->RemPrivateMarkerArray(temp.data(), static_cast<Storage::enumerator>(temp.size()), mrk); for (ElementArray<Element>::iterator it = temp.begin(); it != temp.end(); ++it) { sout << ElementTypeName(it->GetElementType()) << ":" << it->LocalID() << " "; if (it->GetElementType() == CELL) { ElementArray<Face> f = it->getFaces(); for (ElementArray<Face>::iterator jt = f.begin(); jt != f.end(); ++jt) if (!jt->GetPrivateMarker(mrk)) { faces.push_back(*jt); jt->SetPrivateMarker(mrk); } } else if (it->GetElementType() == FACE) { faces.push_back(it->getAsFace()); it->SetPrivateMarker(mrk); } } sout << std::endl; sout << "Output faces: " << faces.size() << std::endl; for (ElementArray<Face>::iterator it = faces.begin(); it != faces.end(); ++it) sout << ElementTypeName(it->GetElementType()) << ":" << it->LocalID() << " "; sout << std::endl; m->RemPrivateMarkerArray(faces.data(), static_cast<Storage::enumerator>(faces.size()), mrk); m->ReleasePrivateMarker(mrk); } void SearchKDTree::IntersectSphere(ElementArray<Cell>& cells, const Storage::real p[3], Storage::real r) const { ElementArray<Element> temp(m); MarkerType mrk = m->CreatePrivateMarker(); sub_intersect_sphere(temp, mrk, p, r); m->RemPrivateMarkerArray(temp.data(), static_cast<Storage::enumerator>(temp.size()), mrk); for (ElementArray<Element>::iterator it = temp.begin(); it != temp.end(); ++it) { if (it->GetElementType() == CELL && !it->GetPrivateMarker(mrk)) { cells.push_back(it->getAsCell()); it->SetPrivateMarker(mrk); } else if (it->GetElementType() == FACE) { ElementArray<Cell> f_cells = it->getCells(); for (ElementArray<Cell>::iterator kt = f_cells.begin(); kt != f_cells.end(); ++kt) if (!kt->GetPrivateMarker(mrk)) { cells.push_back(kt->self()); kt->SetPrivateMarker(mrk); } } } m->RemPrivateMarkerArray(cells.data(), static_cast<Storage::enumerator>(cells.size()), mrk); m->ReleasePrivateMarker(mrk); } void SearchKDTree::IntersectSphere(ElementArray<Face>& faces, const Storage::real p[3], Storage::real r) const { ElementArray<Element> temp(m); MarkerType mrk = m->CreatePrivateMarker(); sub_intersect_sphere(temp, mrk, p, r); m->RemPrivateMarkerArray(temp.data(), static_cast<Storage::enumerator>(temp.size()), mrk); for (ElementArray<Element>::iterator it = temp.begin(); it != temp.end(); ++it) { if (it->GetElementType() == CELL) { ElementArray<Face> f = it->getFaces(); for (ElementArray<Face>::iterator jt = f.begin(); jt != f.end(); ++jt) if (!jt->GetPrivateMarker(mrk)) { faces.push_back(*jt); jt->SetPrivateMarker(mrk); } } else if (it->GetElementType() == FACE) { faces.push_back(it->getAsFace()); it->SetPrivateMarker(mrk); } } m->RemPrivateMarkerArray(faces.data(), static_cast<Storage::enumerator>(faces.size()), mrk); m->ReleasePrivateMarker(mrk); } void SearchKDTree::sub_intersect_segment(ElementArray<Element> & hits, MarkerType mrk, const Storage::real p1[3], const Storage::real p2[3]) const { if( size == 1 ) { if( !m->GetPrivateMarker(set[0].e,mrk) ) { Storage::integer edim = Element::GetGeometricDimension(m->GetGeometricType(set[0].e)); if( edim == 2 ) { if( segment_face(Element(m,set[0].e),p1,p2) ) { hits.push_back(set[0].e); m->SetPrivateMarker(set[0].e,mrk); } } else if( edim == 3 ) { if( segment_cell(Element(m,set[0].e),p1,p2) ) { hits.push_back(set[0].e); m->SetPrivateMarker(set[0].e,mrk); } } else { std::cout << __FILE__ << ":" << __LINE__ << " kd-tree structure is not implemented to intersect edges with segments" << std::endl; exit(-1); } } } else { assert(size > 1); if( segment_bbox(p1,p2) ) { children[0].sub_intersect_segment(hits,mrk,p1,p2); children[1].sub_intersect_segment(hits,mrk,p1,p2); } } } void SearchKDTree::sub_intersect_segment_print(ElementArray<Element>& hits, MarkerType mrk, const Storage::real p1[3], const Storage::real p2[3], std::ostream & sout) const { if (size == 1) { if (!m->GetPrivateMarker(set[0].e, mrk)) { Storage::integer edim = Element::GetGeometricDimension(m->GetGeometricType(set[0].e)); PrintElement(Cell(m, set[0].e), sout); if (edim == 2) { if (segment_face_print(Element(m, set[0].e), p1, p2, sout)) { hits.push_back(set[0].e); m->SetPrivateMarker(set[0].e, mrk); } } else if (edim == 3) { if (segment_cell(Element(m, set[0].e), p1, p2)) { hits.push_back(set[0].e); m->SetPrivateMarker(set[0].e, mrk); } } else { std::cout << __FILE__ << ":" << __LINE__ << " kd-tree structure is not implemented to intersect edges with segments" << std::endl; exit(-1); } } } else { assert(size > 1); if (segment_bbox(p1, p2)) { { sout << "segment "; sout << p1[0] << " " << p1[1] << " " << p1[2]; sout << " <-> "; sout << p2[0] << " " << p2[1] << " " << p2[2]; sout << " is in bbox "; sout << " x " << bbox[0] << ":" << bbox[1]; sout << " y " << bbox[2] << ":" << bbox[3]; sout << " z " << bbox[4] << ":" << bbox[5]; sout << std::endl; } children[0].sub_intersect_segment_print(hits, mrk, p1, p2, sout); children[1].sub_intersect_segment_print(hits, mrk, p1, p2, sout); } else { sout << "segment "; sout << p1[0] << " " << p1[1] << " " << p1[2]; sout << " <-> "; sout << p2[0] << " " << p2[1] << " " << p2[2]; sout << " is not in bbox "; sout << " x " << bbox[0] << ":" << bbox[1]; sout << " y " << bbox[2] << ":" << bbox[3]; sout << " z " << bbox[4] << ":" << bbox[5]; sout << std::endl; } } } void SearchKDTree::sub_intersect_sphere(ElementArray<Element>& hits, MarkerType mrk, const Storage::real p[3], Storage::real r) const { if (size == 1) { if (!m->GetPrivateMarker(set[0].e, mrk)) { Storage::integer edim = Element::GetGeometricDimension(m->GetGeometricType(set[0].e)); if (edim == 2) { if (sphere_face(Element(m, set[0].e), p, r)) { hits.push_back(set[0].e); m->SetPrivateMarker(set[0].e, mrk); } } else if (edim == 3) { if (sphere_cell(Element(m, set[0].e), p, r)) { hits.push_back(set[0].e); m->SetPrivateMarker(set[0].e, mrk); } } else { std::cout << __FILE__ << ":" << __LINE__ << " kd-tree structure is not implemented to intersect edges with spheres" << std::endl; exit(-1); } } } else { assert(size > 1); if (sphere_bbox(p, r)) { children[0].sub_intersect_sphere(hits, mrk, p, r); children[1].sub_intersect_sphere(hits, mrk, p, r); } } } SearchKDTree::~SearchKDTree() { if( size ) { delete [] set; clear_children(); } } Cell SearchKDTree::SearchCell(const Storage::real * point) const { return SubSearchCell(point); } Cell SearchKDTree::SearchCellPrint(const Storage::real* point, std::ostream & sout) const { return SubSearchCellPrint(point, sout); } } #endif
31.439068
173
0.545716
INM-RAS
5fb3ffb00d3187d775d28e7408b077d2f8160ca0
946
cpp
C++
rw_rh_engine_lib/render_client/light_state_recorder.cpp
petrgeorgievsky/gtaRenderHook
124358410c3edca56de26381e239ca29aa6dc1cc
[ "MIT" ]
232
2016-08-29T00:33:32.000Z
2022-03-29T22:39:51.000Z
rw_rh_engine_lib/render_client/light_state_recorder.cpp
petrgeorgievsky/gtaRenderHook
124358410c3edca56de26381e239ca29aa6dc1cc
[ "MIT" ]
10
2021-01-02T12:40:49.000Z
2021-08-31T06:31:04.000Z
rw_rh_engine_lib/render_client/light_state_recorder.cpp
petrgeorgievsky/gtaRenderHook
124358410c3edca56de26381e239ca29aa6dc1cc
[ "MIT" ]
40
2017-12-18T06:14:39.000Z
2022-01-29T16:35:23.000Z
// // Created by peter on 16.02.2021. // #include "light_state_recorder.h" #include <ipc/MemoryReader.h> #include <ipc/MemoryWriter.h> namespace rh::rw::engine { constexpr size_t gLightBufferSize = 1024; LightStateRecorder::LightStateRecorder() noexcept { PointLights.resize( gLightBufferSize ); PointLightCount = 0; } LightStateRecorder::~LightStateRecorder() noexcept = default; uint64_t LightStateRecorder::Serialize( MemoryWriter &writer ) { uint64_t point_light_count = PointLightCount; writer.Write( &point_light_count ); if ( point_light_count > 0 ) writer.Write( PointLights.data(), point_light_count ); return 0; } void LightStateRecorder::Flush() { PointLightCount = 0; } void LightStateRecorder::RecordPointLight( PointLight &&light ) { if ( PointLightCount >= gLightBufferSize ) return; PointLights[PointLightCount] = light; PointLightCount++; } } // namespace rh::rw::engine
24.25641
63
0.726216
petrgeorgievsky
5fbc7950a61cd3bba983184cdf49e6d6fa78c527
4,127
cpp
C++
src/Imploder/Linux/Imploder.cpp
perriera/ng-monitor
38b47773d7a4cc39fd677622648f0e59a616a751
[ "MIT" ]
null
null
null
src/Imploder/Linux/Imploder.cpp
perriera/ng-monitor
38b47773d7a4cc39fd677622648f0e59a616a751
[ "MIT" ]
null
null
null
src/Imploder/Linux/Imploder.cpp
perriera/ng-monitor
38b47773d7a4cc39fd677622648f0e59a616a751
[ "MIT" ]
null
null
null
#include "../include/Imploder/Linux/Imploder.hpp" #include "../extra/include/Directory.hpp" #include "../extra/include/string_support.hpp" #include <fstream> #include <iostream> #include <sstream> #include <vector> using namespace std; std::ostream &operator<<(std::ostream &out, const LinuxImploder &obj) { out << "rm -rf /tmp/t1/t3" << endl; for (auto line : obj._lines) { if (line.isImplodable()) { out << obj.create_path(line.path()) << endl; out << obj.move_content(line.path()) << endl; out << obj.stub_content(line.path()) << endl; } } return out; } std::istream &operator>>(std::istream &in, LinuxImploder &obj) { while (in.good()) { ZipEntry line; in >> line; if (in.good()) obj._lines.push_back(line); } return in; } void LinuxImploder::prerequisites() const { FileNotFoundException::assertion(this->_filename); } void LinuxImploder::unzip() const { string script_name = "./unzipit.sh"; { ofstream script(script_name); script << "rm -rf /tmp/t1" << endl; script << "mkdir /tmp/t1" << endl; script << "cp " << _filename << " /tmp/t1 " << endl; string just_the_filename = Directory(_filename).filename(); script << "unzip /tmp/t1/" << just_the_filename << " -d /tmp/t1/t2" << endl; script << "find /tmp/t1 -ls >/tmp/t1/listing.txt" << endl; script << "echo STUB >/tmp/t1/STUB.txt" << endl; } string chmod = "chmod +x " + script_name; string rm_script = "rm " + script_name; system(chmod.c_str()); system(script_name.c_str()); system(rm_script.c_str()); } void LinuxImploder::execute() { prerequisites(); unzip(); { ifstream listing("/tmp/t1/listing.txt"); ofstream script("/tmp/t1/listing.sh"); listing >> *this; script << *this; } system("chmod +x /tmp/t1/listing.sh"); system("/tmp/t1/listing.sh"); system("rm /tmp/t1/STUB.txt"); rezip(); } void LinuxImploder::rezip() const { string script_name = "./rezip.sh"; string just_the_filename = Directory(_filename).filename(); string just_the_pathname = Directory(_filename).pathname(); string imploded_name = replace_all(just_the_filename, ".zip", ".imploded.zip"); string implosion_name = replace_all(just_the_filename, ".zip", ".implosion.zip"); { ofstream script(script_name); script << "cd /tmp/t1/" << endl; script << "cp " << just_the_filename << " " << imploded_name << endl; script << "cd /tmp/t1/t2" << endl; script << "zip -r ../" << imploded_name << " . " << endl; script << "cd /tmp/t1/t3" << endl; script << "zip -r ../" << implosion_name << " . " << endl; script << "cp /tmp/t1/" << imploded_name << " " << "/tmp/" << imploded_name << endl; script << "cp /tmp/t1/" << implosion_name << " " << "/tmp/" << implosion_name << endl; script << "cp /tmp/t1/" << just_the_filename << " " << "/tmp/" << just_the_filename << endl; script << "rm -rf /tmp/t1/" << endl; } string chmod = "chmod +x " + script_name; string rm_script = "rm " + script_name; system(chmod.c_str()); system(script_name.c_str()); system(rm_script.c_str()); // manually copy the resulting files { Directory cp1("/tmp/" + implosion_name); Directory cp2("/tmp/" + imploded_name); Directory cp3("/tmp/" + just_the_filename); cp1.copyTo(Directory(just_the_pathname + implosion_name)); cp2.copyTo(Directory(just_the_pathname + imploded_name)); cp1.remove(); cp2.remove(); cp3.remove(); } } std::string LinuxImploder::create_path(const std::string &path) const { stringstream ss; auto pathname = Directory(path).pathname(); ss << "mkdir -p " << replace_all(pathname, "/tmp/t1/t2/", "/tmp/t1/t3/"); string updated = ss.str(); return updated; } std::string LinuxImploder::move_content(const std::string &path) const { stringstream ss; ss << "mv " << path << " " << replace_all(path, "/tmp/t1/t2/", "/tmp/t1/t3/"); return ss.str(); } std::string LinuxImploder::stub_content(const std::string &path) const { stringstream ss; ss << "cp /tmp/t1/STUB.txt " << path; return ss.str(); }
31.503817
80
0.618609
perriera
5fc3b7a4ee1de9f25f0a42435b224d43751ead56
7,634
inl
C++
src/cryptonote_core/cryptonote_core_idle.inl
flywithfang/dfa
8f796294a2c8ed24f142183545ab87afd77c2b4e
[ "MIT" ]
null
null
null
src/cryptonote_core/cryptonote_core_idle.inl
flywithfang/dfa
8f796294a2c8ed24f142183545ab87afd77c2b4e
[ "MIT" ]
null
null
null
src/cryptonote_core/cryptonote_core_idle.inl
flywithfang/dfa
8f796294a2c8ed24f142183545ab87afd77c2b4e
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------------------------------- double factorial(unsigned int n) { if (n <= 1) return 1.0; double f = n; while (n-- > 1) f *= n; return f; } //----------------------------------------------------------------------------------------------- static double probability1(unsigned int blocks, unsigned int expected) { // https://www.umass.edu/wsp/resources/poisson/#computing return pow(expected, blocks) / (factorial(blocks) * exp(expected)); } //----------------------------------------------------------------------------------------------- static double probability(unsigned int blocks, unsigned int expected) { double p = 0.0; if (blocks <= expected) { for (unsigned int b = 0; b <= blocks; ++b) p += probability1(b, expected); } else if (blocks > expected) { for (unsigned int b = blocks; b <= expected * 3 /* close enough */; ++b) p += probability1(b, expected); } return p; } //----------------------------------------------------------------------------------------------- bool core::on_idle() { if(!m_starter_message_showed) { std::string main_message; if (m_offline) main_message = "The daemon is running offline and will not attempt to sync to the Monero network."; else main_message = "The daemon will start synchronizing with the network. This may take a long time to complete."; MGINFO_YELLOW(ENDL << "**********************************************************************" << ENDL << main_message << ENDL << ENDL << "You can set the level of process detailization through \"set_log <level|categories>\" command," << ENDL << "where <level> is between 0 (no details) and 4 (very verbose), or custom category based levels (eg, *:WARNING)." << ENDL << ENDL << "Use the \"help\" command to see the list of available commands." << ENDL << "Use \"help <command>\" to see a command's documentation." << ENDL << "**********************************************************************" << ENDL); m_starter_message_showed = true; } m_check_updates_interval.do_call(boost::bind(&core::check_updates, this)); m_check_disk_space_interval.do_call(boost::bind(&core::check_disk_space, this)); m_blockchain_pruning_interval.do_call(boost::bind(&core::update_blockchain_pruning, this)); m_tx_pool.on_idle(); return true; } //----------------------------------------------------------------------------------------------- bool core::check_updates() { static const char software[] = "dfad"; #ifdef BUILD_TAG static const char buildtag[] = BOOST_PP_STRINGIZE(BUILD_TAG); static const char subdir[] = "cli"; // because it can never be simple #else static const char buildtag[] = "source"; static const char subdir[] = "source"; // because it can never be simple #endif if (m_offline) return true; if (check_updates_level == UPDATES_DISABLED) return true; std::string version, hash; MCDEBUG("updates", "Checking for a new " << software << " version for " << buildtag); if (!tools::check_updates(software, buildtag, version, hash)) return false; if (tools::vercmp(version.c_str(), MONERO_VERSION) <= 0) { m_update_available = false; return true; } std::string url = tools::get_update_url(software, subdir, buildtag, version, true); MCLOG_CYAN(el::Level::Info, "global", "Version " << version << " of " << software << " for " << buildtag << " is available: " << url << ", SHA256 hash " << hash); m_update_available = true; if (check_updates_level == UPDATES_NOTIFY) return true; url = tools::get_update_url(software, subdir, buildtag, version, false); std::string filename; const char *slash = strrchr(url.c_str(), '/'); if (slash) filename = slash + 1; else filename = std::string(software) + "-update-" + version; boost::filesystem::path path(epee::string_tools::get_current_module_folder()); path /= filename; boost::unique_lock<boost::mutex> lock(m_update_mutex); if (m_update_download != 0) { MCDEBUG("updates", "Already downloading update"); return true; } crypto::hash file_hash; if (!tools::sha256sum(path.string(), file_hash) || (hash != epee::string_tools::pod_to_hex(file_hash))) { MCDEBUG("updates", "We don't have that file already, downloading"); const std::string tmppath = path.string() + ".tmp"; if (epee::file_io_utils::is_file_exist(tmppath)) { MCDEBUG("updates", "We have part of the file already, resuming download"); } m_last_update_length = 0; m_update_download = tools::download_async(tmppath, url, [this, hash, path](const std::string &tmppath, const std::string &uri, bool success) { bool remove = false, good = true; if (success) { crypto::hash file_hash; if (!tools::sha256sum(tmppath, file_hash)) { MCERROR("updates", "Failed to hash " << tmppath); remove = true; good = false; } else if (hash != epee::string_tools::pod_to_hex(file_hash)) { MCERROR("updates", "Download from " << uri << " does not match the expected hash"); remove = true; good = false; } } else { MCERROR("updates", "Failed to download " << uri); good = false; } boost::unique_lock<boost::mutex> lock(m_update_mutex); m_update_download = 0; if (success && !remove) { std::error_code e = tools::replace_file(tmppath, path.string()); if (e) { MCERROR("updates", "Failed to rename downloaded file"); good = false; } } else if (remove) { if (!boost::filesystem::remove(tmppath)) { MCERROR("updates", "Failed to remove invalid downloaded file"); good = false; } } if (good) MCLOG_CYAN(el::Level::Info, "updates", "New version downloaded to " << path.string()); }, [this](const std::string &path, const std::string &uri, size_t length, ssize_t content_length) { if (length >= m_last_update_length + 1024 * 1024 * 10) { m_last_update_length = length; MCDEBUG("updates", "Downloaded " << length << "/" << (content_length ? std::to_string(content_length) : "unknown")); } return true; }); } else { MCDEBUG("updates", "We already have " << path << " with expected hash"); } lock.unlock(); if (check_updates_level == UPDATES_DOWNLOAD) return true; MCERROR("updates", "Download/update not implemented yet"); return true; } //----------------------------------------------------------------------------------------------- bool core::check_disk_space() { uint64_t free_space = get_free_space(); if (free_space < 1ull * 1024 * 1024 * 1024) // 1 GB { const el::Level level = el::Level::Warning; MCLOG_RED(level, "global", "Free space is below 1 GB on " << m_config_folder); } return true; } //----------------------------------------------------------------------------------------------- bool core::update_blockchain_pruning() { return m_blockchain.update_blockchain_pruning(); }
35.179724
166
0.529211
flywithfang
5fd81ae9cfe65941cbb90aa3dd2ec9a4c5c3c695
2,104
cpp
C++
src/interp_gen_inv.cpp
vincenzocoia/igcop
1ac1affbb7ec50f5946181207f6816dd37669d70
[ "MIT" ]
null
null
null
src/interp_gen_inv.cpp
vincenzocoia/igcop
1ac1affbb7ec50f5946181207f6816dd37669d70
[ "MIT" ]
null
null
null
src/interp_gen_inv.cpp
vincenzocoia/igcop
1ac1affbb7ec50f5946181207f6816dd37669d70
[ "MIT" ]
1
2021-02-09T08:50:05.000Z
2021-02-09T08:50:05.000Z
#include <Rcpp.h> using namespace Rcpp; //' @rdname generators_vec // [[Rcpp::export]] NumericVector interp_gen_inv_vec(NumericVector p, NumericVector eta, NumericVector alpha) { int i; int n = p.size(); double interp_gen_inv_algo (double, double, double, int, double, double); NumericVector inv(n); double eps = 1.e-13, bd = 5.; int mxiter = 25; for(i=0;i<n;i++) { inv[i] = interp_gen_inv_algo(p[i],eta[i],alpha[i],mxiter,eps,bd); R_CheckUserInterrupt(); } return(inv); } // The `interp_gen_inv()` function, with scalar inputs and output. // mxiter = the number of Newton Raphson iterations before stopping. // eps = precision; steps smaller than this will end the algorithm. // bd = truncates step sizes to this value, if exceeded. double interp_gen_inv_algo(double p, double eta, double alpha, int mxiter, double eps, double bd) { double x1,x2,p1,p2,diff1,diff2; double x,diff,g,gp,prod; double interp_gen_single(double, double, double); double interp_gen_D1_single(double, double, double); double igl_gen_inv_algo (double, double, int, double, double); int iter; prod = alpha * eta * p; if (ISNAN(prod)) return(prod); if (p <= 0.) return(DBL_MAX); // Inf if (p >= 1.) return(0.); x1 = -log(p); x2 = igl_gen_inv_algo(p, alpha, mxiter, eps, bd) / eta; p1 = interp_gen_single(x1, eta, alpha); p2 = interp_gen_single(x2, eta, alpha); diff1 = fabs(p1-p); diff2 = fabs(p2-p); x=x1; if(diff2<diff1) { x=x2; } //x = log(x); iter = 0; diff = 1.; while(iter < mxiter && fabs(diff) > eps) { //ex = exp(x); //g = interp_gen(ex, eta, alpha) - p; //gp = interp_gen_D1(ex, eta, alpha) * ex; g = interp_gen_single(x, eta, alpha) - p; gp = interp_gen_D1_single(x, eta, alpha); diff = g / gp; if (diff > bd) diff = bd; if (diff < -bd) diff = -bd; if (x - diff < 0.) diff = x / 2.; x -= diff; //while (fabs(diff) > bd) //{ diff/=2.; x += diff; R_CheckUserInterrupt(); } iter++; R_CheckUserInterrupt(); } //return(exp(x)); return(x); }
32.369231
75
0.61692
vincenzocoia
5fdc1449b4fd53a3bcbd6e00abaefbba821519ea
34,474
cpp
C++
TommyGun/FrameWork/ZXProjectManager.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
34
2017-05-08T18:39:13.000Z
2022-02-13T05:05:33.000Z
TommyGun/FrameWork/ZXProjectManager.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
null
null
null
TommyGun/FrameWork/ZXProjectManager.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
6
2017-05-27T01:14:20.000Z
2020-01-20T14:54:30.000Z
/*--------------------------------------------------------------------------- (c) 2004 Scorpio Software 19 Wittama Drive Glenmore Park Sydney NSW 2745 Australia ----------------------------------------------------------------------------- $Workfile:: $ $Revision:: $ $Date:: $ $Author:: $ ---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- #include <fstream> #include <iostream> #include <vcl.h> #pragma hdrstop #include <assert.h> //- APP --------------------------------------------------------------------- #include "..\SafeMacros.h" //- APP --------------------------------------------------------------------- #include "ZXGuiManager.h" #include "ZXProjectManager.h" #include "ZXUndoManager.h" #include "ZXPluginManager.h" #include "ZXGuiManager.h" #include "ZXBackup.h" #include "ZXLogFile.h" //#include "fProblems.h" //--------------------------------------------------------------------------- #pragma package(smart_init) //--------------------------------------------------------------------------- using namespace Scorpio; using namespace Project; using namespace Plugin; using namespace GUI; using namespace Logging; //--------------------------------------------------------------------------- const String g_sSignature = "TommyGun Project"; const String g_sVersion = "2.0"; // version 2.0 const String g_sTypes[] = { "Error", "Warning", "Info" }; //--------------------------------------------------------------------------- __fastcall ZXProjectManager::ZXProjectManager() : m_XmlInfo(NULL) , m_XmlDefaults(NULL) , m_XmlUpdate(NULL) , m_dwVersion(0) { } //--------------------------------------------------------------------------- __fastcall ZXProjectManager::~ZXProjectManager() { Release(); } //--------------------------------------------------------------------------- bool __fastcall ZXProjectManager::Initialize(HINSTANCE hInstance) { ZX_LOG_INFO(lfGeneral, "Initialized Project Manager") g_PluginManager.OnQuerySave = OnQuerySave; g_PluginManager.OnQueryProjectFolder = OnQueryProjectFolder; m_XmlInfo = new KXmlInfo(); m_XmlDefaults = new KXmlInfo(); return true; } //--------------------------------------------------------------------------- void __fastcall ZXProjectManager::Release(void) { ZX_LOG_INFO(lfGeneral, "Releasing Project Manager") SAFE_DELETE(m_XmlUpdate); SAFE_DELETE(m_XmlInfo); SAFE_DELETE(m_XmlDefaults); } //--------------------------------------------------------------------------- TSaveQuery __fastcall ZXProjectManager::QuerySave(void) { TSaveQuery QueryReply = sqSaved; if (true == IsDirty()) { int iResponse = g_GuiManager.ShowMessage( mbtQuestion, "Do you want to save the changes you made?", "You made changes that have not been saved.", "You can choose to save or discard your changes before continuing. Cancelling will leave your changes unsaved.\n\nClick,\n\tYes\tto save your changes\n\tNo\tto discard your changes\n\tCancel\tto cancel this operation and leave your changes unsaved.", "Cancel", "No", "Yes"); // respond to the users request if (g_msgQueryYes == iResponse) { QueryReply = sqSaved; if (false == Save()) { QueryReply = sqCancelled; } } else if (g_msgQueryNo == iResponse) { QueryReply = sqSaved; } else { QueryReply = sqCancelled; } } return QueryReply; } //--------------------------------------------------------------------------- void __fastcall ZXProjectManager::New(const String& sProjectFile, const String& sMachine) { if (sqSaved == QuerySave()) { m_sMachine = sMachine; // initialize the main xml object SAFE_DELETE(m_XmlInfo); m_XmlInfo = new KXmlInfo(); m_XmlInfo->SetName("TommyGunProject"); m_XmlInfo->Add("Version", "2.0"); m_XmlInfo->Add("Machine", sMachine); String sErrors; //m_XmlInfo->SaveFile("d:\\test1.xml", sErrors); g_GuiManager.XmlInitialize(m_XmlInfo); //m_XmlInfo->SaveFile("d:\\test2.xml", sErrors); LoadDefaultsXml(sMachine); m_XmlInfo->Add(*m_XmlDefaults); //m_XmlInfo->SaveFile("d:\\test3.xml", sErrors); m_sFilename = sProjectFile; Clear(); g_PluginManager.UnloadPlugins(); g_PluginManager.LoadPlugins(); g_GuiManager.ProjectActive(true); String projectName = ExtractFilePath(m_sFilename); projectName[projectName.LastDelimiter("\\")] = ' '; projectName = projectName.SubString(projectName.LastDelimiter("\\") + 1, projectName.Length()).Trim(); g_GuiManager.ProjectTitle(projectName); // initialize the plugins xml data g_PluginManager.XmlNotify(TZXN_XML_NEW); BackupProjectFile(); m_XmlInfo->SaveFile(sProjectFile); AddProjectFileToMRU(sProjectFile); } } //--------------------------------------------------------------------------- bool __fastcall ZXProjectManager::Load(const String& sFile) { bool bLoaded = false; if (sqSaved == QuerySave()) { // load the file m_sFilename = sFile; AddProjectFileToMRU(m_sFilename); bLoaded = LoadProject(true); g_GuiManager.ProjectActive(bLoaded); String projectName = ExtractFilePath(m_sFilename); projectName[projectName.LastDelimiter("\\")] = ' '; projectName = projectName.SubString(projectName.LastDelimiter("\\") + 1, projectName.Length()).Trim(); g_GuiManager.ProjectTitle(projectName); } return bLoaded; } //--------------------------------------------------------------------------- void __fastcall ZXProjectManager::Reload(void) { if (false == m_sFilename.Trim().IsEmpty()) { Save(); SAFE_DELETE(m_XmlInfo); m_XmlInfo = new KXmlInfo(); LoadProject(true); } } //--------------------------------------------------------------------------- bool __fastcall ZXProjectManager::Merge(const String& sFile) { // TODO: Query for the merge options - ie. ask each plugin to provide a list of items that they load/save // TODO: Do a merge by allowing the plugins to load the data from the new XML file m_sFilename = sFile; bool bLoaded = LoadProject(false); return bLoaded; } //--------------------------------------------------------------------------- void __fastcall ZXProjectManager::UpdateTGRExtension(void) { m_sFilename = ChangeFileExt(m_sFilename, ".xml"); } //--------------------------------------------------------------------------- bool __fastcall ZXProjectManager::Save(const String& sFile) { UpdateTGRExtension(); AddProjectFileToMRU(m_sFilename); SaveProject(); return true; } //--------------------------------------------------------------------------- bool __fastcall ZXProjectManager::LoadProject(bool bClearProject) { bool bLoaded = false; if (true == FileExists(m_sFilename)) { // clear the file messages m_FileMessages.clear(); if (true == bClearProject && !Close()) { return false; // remove the old items //m_sMachine = ""; //Clear(); //g_PluginManager.XmlNotify(TZXN_XML_NEW); //SAFE_DELETE(m_XmlInfo); //m_XmlInfo = new KXmlInfo(); } // load the xml object String sXmlErrors; g_PluginManager.XmlNotify(TZXN_XML_PRE_LOAD, "", m_XmlInfo); if (m_XmlInfo->LoadFile(m_sFilename, sXmlErrors)) { String sMachine; KXmlInfo* node = m_XmlInfo->GetNode("Machine", 0); if (true == SAFE_PTR(node)) { sMachine = node->GetText(); } // get the project version number m_dwVersion = 0; node = m_XmlInfo->GetNode("Version", 0); if (true == SAFE_PTR(node)) { String sVersion = node->GetText(); int dot = sVersion.Pos('.'); if (dot) { m_dwVersion = StrToInt(sVersion.SubString(1, dot - 1)) << 16; m_dwVersion += StrToInt(sVersion.SubString(dot + 1, sVersion.Length())); } else { m_dwVersion = StrToInt(sVersion); } } // if the machine is unkown AND the project is loading or its // merging and the machines are the same, then continue loading if (sMachine != "" && (false == bClearProject || sMachine == m_sMachine || m_sMachine == "")) { // save the machine type m_sMachine = sMachine; // and then load the defaults for it LoadDefaultsXml(m_sMachine); if (true == bClearProject) { m_XmlInfo->Add(*m_XmlDefaults); // unload the old plugins g_PluginManager.UnloadPlugins(); // change the machine folder g_GuiManager.WriteMachineFolder(sMachine); // load the required plugins g_PluginManager.LoadPlugins(); } // notify the new plugins of the loaded xml file g_PluginManager.XmlNotify(TZXN_XML_POST_LOAD, "", m_XmlInfo); // file loaded bLoaded = true; } else { // TODO: failed to find the machine for the project int iResponse = g_GuiManager.ShowMessage( mbtError, "Failed to find the Machine for the Project!", "TommyGun failed to locate a Machine type for the project file", "TommyGun could not load the project, because the machine type is unknown. \n\nClick\n\tOK\tto continue.", "OK", "", ""); } } else { // TODO: Show xml load errors } } return bLoaded; } //--------------------------------------------------------------------------- bool __fastcall ZXProjectManager::SaveProject(void) { bool bSaved = false; String sErrors; // read the remove whitespace flag from the registry KXmlInfo::m_bRemoveWhitespace = false; KRegistry* regScorpio = new KRegistry(NULL); regScorpio->Section = "TommyGun"; regScorpio->SoftwareKey = "\\Software\\Scorpio\\"; regScorpio->RootKey = rkHKEY_CURRENT_USER; regScorpio->Read("States", "RemoveXmlWhitespace", KXmlInfo::m_bRemoveWhitespace); g_PluginManager.XmlNotify(TZXN_XML_PRE_SAVE, "", m_XmlInfo); // remove the defaults node before saving KXmlInfo* defaults; if (m_XmlInfo->Find(defaults, "Defaults", 0)) { m_XmlInfo->Remove(defaults); } // set the project version number KXmlInfo* node = m_XmlInfo->GetNode("Version", 0); if (true == SAFE_PTR(node)) { node->SetText(g_sVersion); } BackupProjectFile(); if (true == m_XmlInfo->SaveFile(m_sFilename, sErrors)) { g_PluginManager.XmlNotify(TZXN_XML_POST_SAVE, "", m_XmlInfo); bSaved = true; ZXBackup Backup; Backup.Backup(m_sFilename, beOnSave); } else { // TODO: display xml save errors } // load the defaults node back into the xml node //LoadDefaultsXml(m_sMachine); bool bClearUndo = false; if (regScorpio->Read("Undo", "ClearAfterSave", bClearUndo) && bClearUndo) { g_UndoManager.Clear(); } SAFE_DELETE(regScorpio); return bSaved; } //--------------------------------------------------------------------------- bool __fastcall ZXProjectManager::Save(void) { return Save(m_sFilename); } //--------------------------------------------------------------------------- bool __fastcall ZXProjectManager::Close(void) { // save the project if (sqSaved == QuerySave()) { // then, deactivate the project actions and unload the plugins Application->MainForm->Caption = "TommyGun"; g_GuiManager.ProjectActive(false); g_PluginManager.UnloadPlugins(); SAFE_DELETE(m_XmlInfo); m_XmlInfo = new KXmlInfo(); ZXBackup Backup; Backup.Backup(m_sFilename, beOnClose); return true; } return false; } //--------------------------------------------------------------------------- void __fastcall ZXProjectManager::Clear(void) { // TODO: Clear the UNDO object g_PluginManager.Notify(NULL, TZX_VERB_NEW, NULL, 0, 0); } //--------------------------------------------------------------------------- bool __fastcall ZXProjectManager::IsDirty(void) { bool bNeedToSave = false; // Is the project? ie. Do any plugins have any unsaved data? We only need 1 plugin to answer yes g_PluginManager.Notify(NULL, TZX_QUERY_DATASAVED, (LPDATA)&bNeedToSave, 0, 0); return bNeedToSave; } //--------------------------------------------------------------------------- void __fastcall ZXProjectManager::AddProjectFileToMRU(const String& sFilename) { bool bExists = false; // is the file already in the mru list? GetMRUList(m_MRUProjects, false); if (m_MRUProjects.size()) { for (unsigned int i = 0; i < m_MRUProjects.size() && !bExists; ++i) { bExists = m_MRUProjects[i].File.LowerCase() == sFilename.LowerCase(); } } if (false == bExists) { TMRUProject mruProject; mruProject.File = sFilename; mruProject.Exists = true; m_MRUProjects.insert(m_MRUProjects.begin(), mruProject); SaveMRU(); } } //--------------------------------------------------------------------------- void __fastcall ZXProjectManager::SaveMRU(void) { // write the list back to the registry KRegistry* regScorpio = new KRegistry(NULL); regScorpio->Section = "TommyGun"; regScorpio->SoftwareKey = "\\Software\\Scorpio\\"; regScorpio->RootKey = rkHKEY_CURRENT_USER; regScorpio->ClearKey("MRU"); for (unsigned int i = 0; i < m_MRUProjects.size(); ++i) { regScorpio->Write("MRU", IntToStr(i), m_MRUProjects[i].File); } SAFE_DELETE(regScorpio); } //--------------------------------------------------------------------------- void __fastcall ZXProjectManager::Restore(String sProjectName) { int iProject = -1; if (m_MRUProjects.size() == 0) { GetMRUList(m_MRUProjects, false); } for (int i = 0; i < (int)m_MRUProjects.size(); i++) { AnsiString sFile = m_MRUProjects[i].File; sFile = ExtractFilePath(sFile); sFile = sFile.SubString(1, sFile.Length() - 1); int iSlash = sFile.LastDelimiter("\\"); if (iSlash) { sFile = sFile.SubString(iSlash + 1, sFile.Length()); } // sfile contains the project name if (sProjectName == sFile) { ZXBackup Backup; Backup.Restore(m_MRUProjects[i].File); break; } } } //--------------------------------------------------------------------------- void __fastcall ZXProjectManager::Remove(String sName, bool bRemoveFolder) { int iProject = -1; if (m_MRUProjects.size() == 0) { GetMRUList(m_MRUProjects, false); } for (int i = 0; i < (int)m_MRUProjects.size(); i++) { AnsiString sFile = m_MRUProjects[i].File; sFile = ExtractFilePath(sFile); sFile = sFile.SubString(1, sFile.Length() - 1); int iSlash = sFile.LastDelimiter("\\"); if (iSlash) { sFile = sFile.SubString(iSlash + 1, sFile.Length()); } // sfile contains the project name if (sName == sFile) { iProject = i; break; } } if (0 <= iProject && iProject < (int)m_MRUProjects.size()) { bool bDeleted = true; // erase the list from the list if (bRemoveFolder) { // delete the folder bDeleted = Delete(iProject); } if (bDeleted) { m_MRUProjects.erase(m_MRUProjects.begin() + iProject); SaveMRU(); } } } //--------------------------------------------------------------------------- bool __fastcall ZXProjectManager::DeleteFolder(String sFolder, bool bRemoveFolder) { DWORD dwError = 0; bool bDeleted = true; TSearchRec sr; int iFound = FindFirst(sFolder + "*.*", faAnyFile, sr); while (0 == iFound && true == bDeleted) { if (sr.Attr & faDirectory) { if (sr.Name[1] != '.') { bDeleted = DeleteFolder(sFolder + sr.Name + "\\"); } } else { if (FileSetAttr(sFolder + sr.Name, 0) == 0) { bDeleted = DeleteFile(sFolder + sr.Name); } else { bDeleted = false; } } iFound = FindNext(sr); } FindClose(sr); if (bRemoveFolder) return 0 != RemoveDirectory(sFolder.c_str()); return true; } //--------------------------------------------------------------------------- bool __fastcall ZXProjectManager::Delete(int iProject) { if (0 <= iProject && iProject < (int)m_MRUProjects.size()) { int iAnswer; if (m_MRUProjects[iProject].File != m_sFilename) { if (false == DeleteFolder(ExtractFilePath(m_MRUProjects[iProject].File))) { Message ( mbtError, "Failed to Delete Project Folder!", "", "TommyGun failed to Delete the project folder.\nThis could be because the system has a lock on a file in the folder or the directory is read-only.", "Ok", "", "", iAnswer ); return false; } } else { Message ( mbtError, "Cannot Delete current project or last loaded project", "You cannot delete the current or last used project", "The current project or last used project will contain a system lock due to the use of the Windows Open Dialog." " So you cannot delete it. You must either open another project or restart TommyGun.", "Ok", "", "", iAnswer ); return false; } } return true; } //--------------------------------------------------------------------------- void __fastcall ZXProjectManager::Rename(String sOldName, String sNewName) { String sPath; int iProject = -1; if (m_MRUProjects.size() == 0) { GetMRUList(m_MRUProjects, false); } for (int i = 0; i < (int)m_MRUProjects.size(); i++) { String sFile = m_MRUProjects[i].File; sFile = ExtractFilePath(sFile); sFile = sFile.SubString(1, sFile.Length() - 1); int iSlash = sFile.LastDelimiter("\\"); if (iSlash) { sPath = sFile.SubString(1, iSlash); sFile = sFile.SubString(iSlash + 1, sFile.Length()); } // sfile contains the project name if (sOldName == sFile) { iProject = i; break; } } if (0 <= iProject && iProject < (int)m_MRUProjects.size()) { sOldName = sPath + sOldName + "\\"; sNewName = sPath + sNewName + "\\"; int iOk; if (true == DirectoryExists(sOldName)) { if (false == DirectoryExists(sNewName)) { if (rename(sOldName.c_str(), sNewName.c_str()) == 0) { m_MRUProjects[iProject].File = sNewName + "project.xml"; SaveMRU(); } else { // failed to rename the project Message ( mbtError, "Failed to Rename the Project", "Folder rename operation failed", "Failed to Rename the Project folder to the new project name.\n" "Either access was denied or the new project name contains invalid characters.", "Ok", "", "", iOk ); } } else { // new name already exists Message ( mbtError, "New Project name already exists", "Cannot rename project to an existing project name", "You cannot rename a project to the name of an existing project." "It just ain't gonna happen dude!", "Ok", "", "", iOk ); } } else { // project to rename doesn't exist Message ( mbtError, "Project folder does not exist", "Project folder to rename does not exist", "The project folder has disappeared and so it cannot be renamed\n" "Duh!", "Ok", "", "", iOk ); } } } //--------------------------------------------------------------------------- bool __fastcall ZXProjectManager::CopyFiles(String sOldName, String sNewName) { if (ForceDirectories(ExtractFileDir(sNewName))) { DWORD dwError = 0; TSearchRec sr; int iFound = FindFirst(sOldName + "*.*", faAnyFile, sr); while (0 == iFound) { if (sr.Attr & ~faDirectory) { String sOldFile = sOldName + sr.Name; String sNewFile = sNewName + sr.Name; if (CopyFile(sOldFile.c_str(), sNewFile.c_str(), TRUE) == FALSE) { return false; } } iFound = FindNext(sr); } FindClose(sr); return true; } return false; } //--------------------------------------------------------------------------- void __fastcall ZXProjectManager::Copy(String sOldName, String sNewName) { String sPath; int iProject = -1; if (m_MRUProjects.size() == 0) { GetMRUList(m_MRUProjects, false); } for (int i = 0; i < (int)m_MRUProjects.size(); i++) { String sFile = m_MRUProjects[i].File; sFile = ExtractFilePath(sFile); sFile = sFile.SubString(1, sFile.Length() - 1); int iSlash = sFile.LastDelimiter("\\"); if (iSlash) { sPath = sFile.SubString(1, iSlash); sFile = sFile.SubString(iSlash + 1, sFile.Length()); } // sfile contains the project name if (sOldName == sFile) { iProject = i; break; } } if (0 <= iProject && iProject < (int)m_MRUProjects.size()) { sOldName = sPath + sOldName + "\\"; sNewName = sPath + sNewName + "\\"; int iOk; if (true == DirectoryExists(sOldName)) { if (false == DirectoryExists(sNewName)) { if (CopyFiles(sOldName, sNewName)) { AddProjectFileToMRU(sNewName + "project.xml"); SaveMRU(); } else { // failed to copy the project Message ( mbtError, "Failed to Copy the Project", "Folder copy operation failed", "Failed to Copy the Project folder to the new project folder name.\n" "Either access was denied or the new project name contains invalid characters.", "Ok", "", "", iOk ); } } else { // new name already exists Message ( mbtError, "New Project name already exists", "Cannot copy project to an existing project name", "You cannot copy a project to the name of an existing project." "It just ain't gonna happen dude!", "Ok", "", "", iOk ); } } else { // project to rename doesn't exist Message ( mbtError, "Project folder does not exist", "Project folder to rename does not exist", "The project folder has disappeared and so it cannot be copied\n" "Duh!", "Ok", "", "", iOk ); } } } //--------------------------------------------------------------------------- void __fastcall ZXProjectManager::GetMRUList(TMRUProjectsVector& mruProjects, bool bGetMachine) { PROTECT_BEGIN // clear the lists mruProjects.clear(); TStringList* list = new TStringList(); KRegistry* regScorpio = new KRegistry(NULL); regScorpio->Section = "TommyGun"; regScorpio->SoftwareKey = "\\Software\\Scorpio\\"; regScorpio->RootKey = rkHKEY_CURRENT_USER; if (true == SAFE_PTR(list)) { if (regScorpio->GetValues("MRU", list) && list->Count) { // read all the files for the entries for (int i = 0; i < list->Count; ++i) { AnsiString sFile; if (regScorpio->Read("MRU", list->Strings[i], sFile)) { //sFile = ChangeFileExt(sFile, ".xml"); TMRUProject mruProject; mruProject.File = sFile; mruProject.Exists = FileExists(sFile); mruProject.TimeStamp = 0; // get the machine mruProject.Machine = bGetMachine ? GetMachine(sFile) : String("Unknown"); if (mruProject.Exists) { // get the time stamp mruProject.TimeStamp = FileDateToDateTime(FileAge(sFile)); } mruProjects.push_back(mruProject); } } // sort the projects by the timestamp (using a slow bubble sort) /*bool bSwapped = true; int i = 0; while (i < (int)mruProjects.size() - 1) { if (mruProjects[i].TimeStamp < mruProjects[i+1].TimeStamp) { TMRUProject temp = mruProjects[i ]; mruProjects[i ].File = mruProjects[i+1].File; mruProjects[i ].Machine = mruProjects[i+1].Machine; mruProjects[i ].Exists = mruProjects[i+1].Exists; mruProjects[i ].TimeStamp = mruProjects[i+1].TimeStamp; mruProjects[i+1].File = temp.File; mruProjects[i+1].Machine = temp.Machine; mruProjects[i+1].Exists = temp.Exists; mruProjects[i+1].TimeStamp = temp.TimeStamp; i = 0; } else { ++i; } }*/ // remove any excess items while (mruProjects.size() > 31) { mruProjects.pop_back(); } } } SAFE_DELETE(regScorpio); SAFE_DELETE(list); PROTECT_END } //--------------------------------------------------------------------------- String __fastcall ZXProjectManager::GetMachine(const String& sFile) { // read the machine name from the file String sMachine = "Unknown"; if (FileExists(sFile)) { ifstream ifs; ifs.open(sFile.c_str(),ios::binary ); if (ifs.is_open()) { // get length of file: ifs.seekg (0, ios::end); int length = ifs.tellg(); ifs.seekg (0, ios::beg); String strXml; strXml.SetLength(length+1); LPSTR buffer = strXml.c_str(); // read data as a block: ifs.read (buffer,length); // find the machine string char* pMachineBegin = strstr(buffer, "<Machine>"); if (NULL != pMachineBegin) { char* pMachineEnd = strstr(buffer, "</Machine>"); if (NULL != pMachineEnd) { sMachine = String(pMachineBegin + 9, pMachineEnd - pMachineBegin - 9).Trim(); } } } } return sMachine; } //--------------------------------------------------------------------------- void __fastcall ZXProjectManager::LogFileError(ZXFileErrorType MessageType, const String& sPlugin, String sErrorMessage) { ZXFileMessage message; message.Type = MessageType; message.Plugin = sPlugin; message.Message = sErrorMessage; m_FileMessages.push_back(message); } //--------------------------------------------------------------------------- /*void __fastcall ZXProjectManager::DisplayFileMessages(void) { bool bDonNotShowProblems = false; KRegistry* regScorpio = new KRegistry(NULL); regScorpio->Section = "TommyGun"; regScorpio->SoftwareKey = "\\Software\\Scorpio\\"; regScorpio->RootKey = rkHKEY_CURRENT_USER; regScorpio->Read("States", "DoNotShowProblems", bDonNotShowProblems); SAFE_DELETE(regScorpio); if (m_FileMessages.size() && !bDonNotShowProblems) { // display a dialog with the messages in it frmProblems = new TfrmProblems(NULL); frmProblems->lstProblems->Clear(); for (unsigned int i = 0; i < m_FileMessages.size(); ++i) { TListItem *item = frmProblems->lstProblems->Items->Add(); item->Caption = g_sTypes[m_FileMessages[i].Type]; item->SubItems->Add(m_FileMessages[i].Plugin); item->SubItems->Add(m_FileMessages[i].Message); } frmProblems->ShowModal(); SAFE_DELETE(frmProblems); } }*/ //--------------------------------------------------------------------------- void __fastcall ZXProjectManager::LoadDefaultsXml(const String& sMachine) { String sDefaultsFile = ExtractFilePath(Application->ExeName); sDefaultsFile += "Plugins\\_" + sMachine + "\\defaults.xml"; if (FileExists(sDefaultsFile)) { SAFE_DELETE(m_XmlDefaults); m_XmlDefaults = new KXmlInfo(); m_XmlDefaults->LoadFile(sDefaultsFile); } } //--------------------------------------------------------------------------- void __fastcall ZXProjectManager::BackupProjectFile(void) { // backup the project file before saving if (FileExists(m_sFilename)) { String sBackupFile = ChangeFileExt(m_sFilename, ".bak"); CopyFile(m_sFilename.c_str(), sBackupFile.c_str(), FALSE); } } //--------------------------------------------------------------------------- void __fastcall ZXProjectManager::OnQuerySave(bool &bSaved) { bSaved = QuerySave() == sqSaved; } //--------------------------------------------------------------------------- void __fastcall ZXProjectManager::OnQueryProjectFolder(String& sFolder) { sFolder = ProjectFile; } //--------------------------------------------------------------------------- bool __fastcall ZXProjectManager::SortProjects(int iColumn) { static int iLastColumn = -1; static bool bSortAscending = true; if (iLastColumn == iColumn) { bSortAscending = !bSortAscending; } iLastColumn = iColumn; if (m_MRUProjects.size() == 0) { GetMRUList(m_MRUProjects, false); } bool bSwapped = true; while(bSwapped) { bool bSwap = false; bSwapped = false; for (unsigned int i = 0; i < m_MRUProjects.size() - 1; i++) { bSwap = false; TMRUProject tmp = m_MRUProjects[i]; switch(iColumn) { case 0: // name bSwap = bSortAscending ? (m_MRUProjects[i+1].File < m_MRUProjects[i].File) : (m_MRUProjects[i].File < m_MRUProjects[i+1].File); break; case 1: // macine bSwap = bSortAscending ? (m_MRUProjects[i+1].Machine < m_MRUProjects[i].Machine) : (m_MRUProjects[i].Machine < m_MRUProjects[i+1].Machine); break; case 2: // modified data bSwap = bSortAscending ? (m_MRUProjects[i+1].TimeStamp < m_MRUProjects[i].TimeStamp) : (m_MRUProjects[i].TimeStamp < m_MRUProjects[i+1].TimeStamp); break; default:// error :-( break; } if (bSwap) { m_MRUProjects[i] = m_MRUProjects[i+1]; m_MRUProjects[i+1] = tmp; } bSwapped |= bSwap; } } SaveMRU(); return bSortAscending; } //--------------------------------------------------------------------------- KXmlInfo* __fastcall ZXProjectManager::GetXmlInfo(void) { SAFE_DELETE(m_XmlUpdate); m_XmlUpdate = new KXmlInfo(); if (true == SAFE_PTR(m_XmlUpdate)) { PostNotifyEvent(NULL, TZXN_XML_UPDATE, (LPDATA)m_XmlUpdate, NULL, 0); return m_XmlUpdate; } return NULL; } //---------------------------------------------------------------------------
35.141692
278
0.483553
tonyt73
5fdc82ee6a7af0e8ff43d8d09ecb0dc07ab4d219
4,151
cpp
C++
Tests/TestHarness/TestHarness.cpp
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
28
2015-09-22T21:43:32.000Z
2022-02-28T01:35:01.000Z
Tests/TestHarness/TestHarness.cpp
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
98
2015-01-22T03:21:27.000Z
2022-03-02T01:47:00.000Z
Tests/TestHarness/TestHarness.cpp
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
4
2019-02-21T16:45:25.000Z
2022-02-18T13:40:04.000Z
/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "Stroika/Foundation/StroikaPreComp.h" #include <cstdlib> #include <iostream> #include "Stroika/Foundation/Characters/CodePage.h" #include "Stroika/Foundation/Characters/ToString.h" #include "Stroika/Foundation/Containers/Common.h" #include "Stroika/Foundation/Debug/Assertions.h" #include "Stroika/Foundation/Debug/Debugger.h" #include "Stroika/Foundation/Debug/Fatal.h" #include "Stroika/Foundation/Execution/Exceptions.h" #include "Stroika/Foundation/Execution/SignalHandlers.h" #include "TestHarness.h" using namespace Stroika; using namespace Stroika::Foundation; using namespace Stroika::TestHarness; namespace { void ASSERT_HANDLER_ (const char* assertCategory, const char* assertionText, const char* fileName, int lineNum, const char* functionName) noexcept { if (assertCategory == nullptr) { assertCategory = "Unknown assertion"; } if (assertionText == nullptr) { assertionText = ""; } if (functionName == nullptr) { functionName = ""; } cerr << "FAILED: " << assertCategory << "; " << assertionText << ";" << functionName << ";" << fileName << ": " << lineNum << endl; DbgTrace ("FAILED: %s; %s; %s; %s; %d", assertCategory, assertionText, functionName, fileName, lineNum); Debug::DropIntoDebuggerIfPresent (); _Exit (EXIT_FAILURE); // skip } void FatalErrorHandler_ (const Characters::SDKChar* msg) noexcept { #if qTargetPlatformSDKUseswchar_t cerr << "FAILED: " << Characters::WideStringToNarrowSDKString (msg) << endl; #else cerr << "FAILED: " << msg << endl; #endif Debug::DropIntoDebuggerIfPresent (); _Exit (EXIT_FAILURE); // skip } void FatalSignalHandler_ (Execution::SignalID signal) noexcept { cerr << "FAILED: SIGNAL= " << Execution::SignalToName (signal).AsNarrowSDKString () << endl; DbgTrace (L"FAILED: SIGNAL= %s", Execution::SignalToName (signal).c_str ()); Debug::DropIntoDebuggerIfPresent (); _Exit (EXIT_FAILURE); // skip } } void TestHarness::Setup () { #if qDebug Stroika::Foundation::Debug::SetAssertionHandler (ASSERT_HANDLER_); #endif Debug::RegisterDefaultFatalErrorHandlers (FatalErrorHandler_); using namespace Execution; SignalHandlerRegistry::Get ().SetStandardCrashHandlerSignals (SignalHandler (FatalSignalHandler_, SignalHandler::Type::eDirect)); } int TestHarness::PrintPassOrFail (void (*regressionTest) ()) { try { (*regressionTest) (); cout << "Succeeded" << endl; DbgTrace (L"Succeeded"); } catch (...) { auto exc = current_exception (); cerr << "FAILED: REGRESSION TEST DUE TO EXCEPTION: '" << Characters::ToString (exc).AsNarrowSDKString () << "'" << endl; cout << "Failed" << endl; DbgTrace (L"FAILED: REGRESSION TEST (Exception): '%s", Characters::ToString (exc).c_str ()); Debug::DropIntoDebuggerIfPresent (); return EXIT_FAILURE; } return EXIT_SUCCESS; } void TestHarness::Test_ (bool failIfFalse, bool isFailureElseWarning, const char* regressionTestText, const char* fileName, int lineNum) { if (not failIfFalse) { if (isFailureElseWarning) { ASSERT_HANDLER_ ("RegressionTestFailure", regressionTestText, fileName, lineNum, ""); } else { cerr << "WARNING: REGRESSION TEST ISSUE: " << regressionTestText << ";" << fileName << ": " << lineNum << endl; DbgTrace ("WARNING: REGRESSION TEST ISSUE: ; %s; %s; %d", regressionTestText, fileName, lineNum); // OK to continue } } } void TestHarness::WarnTestIssue (const char* issue) { cerr << "WARNING: REGRESSION TEST ISSUE: '" << issue << "'" << endl; DbgTrace ("WARNING: REGRESSION TEST ISSUE: '%s", issue); } void TestHarness::WarnTestIssue (const wchar_t* issue) { using namespace Characters; string r; WideStringToNarrow (issue, issue + wcslen (issue), GetDefaultSDKCodePage (), &r); WarnTestIssue (r.c_str ()); }
35.478632
150
0.655264
SophistSolutions
5fdeba227402e5fa7c2d0ed0354709a04aee8e0b
3,887
cpp
C++
src/packet.cpp
sQu1rr/wenet
83f87f5bcd6bcacb21c92b35be67ff1ecf478f84
[ "MIT" ]
null
null
null
src/packet.cpp
sQu1rr/wenet
83f87f5bcd6bcacb21c92b35be67ff1ecf478f84
[ "MIT" ]
null
null
null
src/packet.cpp
sQu1rr/wenet
83f87f5bcd6bcacb21c92b35be67ff1ecf478f84
[ "MIT" ]
1
2020-05-01T19:01:38.000Z
2020-05-01T19:01:38.000Z
#include "wenet/packet.hpp" #include <algorithm> namespace sq { namespace wenet { Packet::Flags convertFlags(Packet::Flags flags) { using Exception = Packet::Exception; if (!flags) throw Exception{"Flags cannot be empty"}; if (flags & Packet::Flag::Reliable) { if (flags & Packet::Flag::Unsequenced) { throw Exception{"Unsequenced packet cannot be reliable"}; } if (flags & Packet::Flag::Fragment) { throw Exception{"Fragmented packets override reliability flag"}; } if (flags & Packet::Flag::Unreliable) { throw Exception{"Packet is either reliable or unreliable"}; } } return flags & ~Packet::Flag::Unreliable; // unreliable is a dummy flag } // ENetPacket Deleter void Packet::Deleter::operator () (ENetPacket* packet) const noexcept { enet_packet_destroy(packet); } Packet::Packet(span<const byte> data, Flag flag) : Packet(data, belks::underlying_cast(flag)) { } Packet::Packet(span<const byte> data, Flags flags) { create(data, convertFlags(flags)); } Packet::Packet(size_t size, Flag flag) : Packet(size, belks::underlying_cast(flag)) { } Packet::Packet(size_t size, Flags flags) noexcept : Packet(*enet_packet_create(nullptr, size, convertFlags(flags))) { } Packet::Packet(ENetPacket& packet, bool manage) noexcept : packet_(&packet), packetOwned_(manage ? &packet : nullptr) { } void Packet::operator = (span<const byte> data) const { throwIfLocked(); if (packet_->flags & Flag::Unmanaged) { // const cast is ok here because enet should not modify data // and the type being non-const seems like an oversight packet_->data = const_cast<byte*>(&data[0]); } else { if (size_t(data.size()) != packet_->dataLength) { enet_packet_resize(packet_, data.size()); } std::copy(data.begin(), data.end(), packet_->data); } } const Packet& Packet::operator << (span<const byte> data) const { throwIfLocked(); if (packet_->flags & Flag::Unmanaged) { throw FlagException{"Cannot modify unmanaged packet"}; } const auto size = getSize(); enet_packet_resize(packet_, size + data.size()); std::copy(data.begin(), data.end(), packet_->data + size); return *this; } void Packet::onDestroy(const FreeCallback& callback) const noexcept { if (packet_->userData) { delete reinterpret_cast<FreeCallback*>(packet_->userData); packet_->userData = nullptr; packet_->freeCallback = nullptr; } if (callback) { packet_->userData = new FreeCallback(callback); packet_->freeCallback = [](ENetPacket* packet) { const auto callback = reinterpret_cast<FreeCallback*>(packet->userData); (*callback)({*packet, false}); delete reinterpret_cast<FreeCallback*>(packet->userData); }; } } void Packet::setFlags(Flags flags) const { throwIfLocked(); if (flags & Flag::Unmanaged) { throw FlagException{"Cannot modify unmanaged flag"}; } packet_->flags = convertFlags(flags); } void Packet::resize(size_t size) const { throwIfLocked(); if (packet_->flags & Flag::Unmanaged) packet_->dataLength = size; else enet_packet_resize(packet_, size); } span<byte> Packet::getData() const noexcept { return {packet_->data, std::ptrdiff_t(packet_->dataLength)}; } void Packet::create(span<const byte> data, uint32_t flags) noexcept { packetOwned_.reset(enet_packet_create(&data[0], data.size(), flags)); packet_ = packetOwned_.get(); } void Packet::throwIfLocked() const { if (!packetOwned_.get()) { if (!packet_) { throw UninitialisedException{"Packet is not initialised yet"}; } else throw UninitialisedException{"Packet cannot be modified"}; } } } // \network } // \sq
27.373239
84
0.647286
sQu1rr
5fe3994efdad7e149c195d80c3b463adf9e663de
15,356
cpp
C++
Electro/src/Platform/DX11/DX11Renderbuffer.cpp
SurgeTechnologies/Electro
8a7dfb6aabdf5d2e6fe31a8d9c976607fc2f1394
[ "MIT" ]
21
2021-08-30T15:30:22.000Z
2022-02-09T14:05:36.000Z
Electro/src/Platform/DX11/DX11Renderbuffer.cpp
SurgeTechnologies/Electro
8a7dfb6aabdf5d2e6fe31a8d9c976607fc2f1394
[ "MIT" ]
null
null
null
Electro/src/Platform/DX11/DX11Renderbuffer.cpp
SurgeTechnologies/Electro
8a7dfb6aabdf5d2e6fe31a8d9c976607fc2f1394
[ "MIT" ]
null
null
null
// ELECTRO ENGINE // Copyright(c) 2021 - Electro Team - All rights reserved #include "epch.hpp" #include "DX11Renderbuffer.hpp" #include "DX11Internal.hpp" namespace Electro { // Max: 8K Texture; 8192 / 1204 = 8 static const Uint sMaxFramebufferSize = 8192; namespace Utils { static void AttachColorTexture(RenderBufferTextureSpecification textureSpec, RenderbufferSpecification renderbufferSpec, RenderbufferColorAttachment* outColorAttachment) { ID3D11Device* device = DX11Internal::GetDevice(); // Render Target texture D3D11_TEXTURE2D_DESC textureDesc = {}; textureDesc.Width = renderbufferSpec.Width; textureDesc.Height = renderbufferSpec.Height; textureDesc.MipLevels = 1; textureDesc.ArraySize = 1; textureDesc.Format = static_cast<DXGI_FORMAT>(textureSpec.TextureFormat); textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; textureDesc.Usage = D3D11_USAGE_DEFAULT; textureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; textureDesc.CPUAccessFlags = 0; textureDesc.MiscFlags = 0; if (renderbufferSpec.Flags == RenderBufferFlags::COMPUTEWRITE) textureDesc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS; DX_CALL(device->CreateTexture2D(&textureDesc, nullptr, &outColorAttachment->RenderTargetTexture)); #ifdef E_DEBUG if (!renderbufferSpec.DebugName.empty()) outColorAttachment->RenderTargetTexture->SetPrivateData(WKPDID_D3DDebugObjectName, sizeof(renderbufferSpec.DebugName.c_str()), renderbufferSpec.DebugName.c_str()); #endif // Render Target View D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc = {}; renderTargetViewDesc.Format = static_cast<DXGI_FORMAT>(textureSpec.TextureFormat); renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; renderTargetViewDesc.Texture2D.MipSlice = 0; DX_CALL(device->CreateRenderTargetView(outColorAttachment->RenderTargetTexture.Get(), &renderTargetViewDesc, &outColorAttachment->RenderTargetView)); { // Shader Resource View D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc = {}; shaderResourceViewDesc.Format = static_cast<DXGI_FORMAT>(textureSpec.TextureFormat); shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; shaderResourceViewDesc.Texture2D.MostDetailedMip = 0; shaderResourceViewDesc.Texture2D.MipLevels = 1; DX_CALL(device->CreateShaderResourceView(outColorAttachment->RenderTargetTexture.Get(), &shaderResourceViewDesc, &outColorAttachment->ShaderResourceView)); } if (renderbufferSpec.Flags == RenderBufferFlags::COMPUTEWRITE) { // Shader Resource View D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc = {}; uavDesc.Format = static_cast<DXGI_FORMAT>(textureSpec.TextureFormat); uavDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D; uavDesc.Texture2D.MipSlice = 0; DX_CALL(device->CreateUnorderedAccessView(outColorAttachment->RenderTargetTexture.Get(), &uavDesc, &outColorAttachment->UnorderedAccessView)); } } static void AttachDepthTexture(RenderBufferTextureSpecification textureSpec, RenderbufferSpecification renderbufferSpec, RenderbufferDepthAttachment* outDepthAttachment) { ID3D11Device* device = DX11Internal::GetDevice(); D3D11_TEXTURE2D_DESC textureDesc = {}; textureDesc.Width = renderbufferSpec.Width; textureDesc.Height = renderbufferSpec.Height; textureDesc.MipLevels = 1; textureDesc.ArraySize = 1; textureDesc.Format = static_cast<DXGI_FORMAT>(textureSpec.TextureFormat); textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; textureDesc.Usage = D3D11_USAGE_DEFAULT; textureDesc.CPUAccessFlags = 0; textureDesc.MiscFlags = 0; textureDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; if (static_cast<DXGI_FORMAT>(textureSpec.TextureFormat) == DXGI_FORMAT_R32_TYPELESS) textureDesc.BindFlags |= D3D11_BIND_SHADER_RESOURCE; DX_CALL(device->CreateTexture2D(&textureDesc, nullptr, &outDepthAttachment->DepthStencilBuffer)); #ifdef E_DEBUG if (!renderbufferSpec.DebugName.empty()) outDepthAttachment->DepthStencilBuffer->SetPrivateData(WKPDID_D3DDebugObjectName, sizeof(renderbufferSpec.DebugName.c_str()), renderbufferSpec.DebugName.c_str()); #endif if (static_cast<DXGI_FORMAT>(textureSpec.TextureFormat) == DXGI_FORMAT_R32_TYPELESS) // Shadows { D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc = {}; shaderResourceViewDesc.Format = DXGI_FORMAT_R32_FLOAT; shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; shaderResourceViewDesc.Texture2D.MostDetailedMip = 0; shaderResourceViewDesc.Texture2D.MipLevels = 1; DX_CALL(device->CreateShaderResourceView(outDepthAttachment->DepthStencilBuffer.Get(), &shaderResourceViewDesc, &outDepthAttachment->ShaderResourceView)); D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc = {}; depthStencilViewDesc.Format = DXGI_FORMAT_D32_FLOAT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; DX_CALL(device->CreateDepthStencilView(outDepthAttachment->DepthStencilBuffer.Get(), &depthStencilViewDesc, &outDepthAttachment->DepthStencilView)); } else // Normal { D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc = {}; depthStencilViewDesc.Format = static_cast<DXGI_FORMAT>(textureSpec.TextureFormat); depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; DX_CALL(device->CreateDepthStencilView(outDepthAttachment->DepthStencilBuffer.Get(), &depthStencilViewDesc, &outDepthAttachment->DepthStencilView)); } } static void AttachToSwapchain(RenderbufferColorAttachment* outColorAttachment, RenderbufferSpecification renderbufferSpec) { Microsoft::WRL::ComPtr<ID3D11Texture2D> backBuffer; ID3D11Device* device = DX11Internal::GetDevice(); IDXGISwapChain* swapChain = DX11Internal::GetSwapChain(); swapChain->GetBuffer(0, __uuidof(ID3D11Resource), &backBuffer); device->CreateRenderTargetView(backBuffer.Get(), nullptr, &outColorAttachment->RenderTargetView); #ifdef E_DEBUG if (!renderbufferSpec.DebugName.empty()) outColorAttachment->RenderTargetTexture->SetPrivateData(WKPDID_D3DDebugObjectName, sizeof(renderbufferSpec.DebugName.c_str()), renderbufferSpec.DebugName.c_str()); #endif } static bool IsDepthFormat(RenderBufferTextureFormat format) { switch (format) { case RenderBufferTextureFormat::D24S8UINT: return true; case RenderBufferTextureFormat::R32VOID: return true; } return false; } } DX11Renderbuffer::DX11Renderbuffer(const RenderbufferSpecification& spec) : mSpecification(spec) { for (const RenderBufferTextureSpecification& format : mSpecification.Attachments.Attachments) { if (!Utils::IsDepthFormat(format.TextureFormat)) mColorAttachmentSpecifications.emplace_back(format); else mDepthAttachmentSpecification = format; } Invalidate(); } void DX11Renderbuffer::Bind() const { ID3D11DeviceContext* deviceContext = DX11Internal::GetDeviceContext(); deviceContext->RSSetViewports(1, &mViewport); Microsoft::WRL::ComPtr<ID3D11RenderTargetView> pRenderViews[2]; for (Uint i = 0; i < mColorAttachments.size(); i++) pRenderViews[i] = mColorAttachments[i].RenderTargetView; deviceContext->OMSetRenderTargets(static_cast<Uint>(mColorAttachments.size()), pRenderViews[0].GetAddressOf(), mDepthAttachment.DepthStencilView.Get()); } void DX11Renderbuffer::Unbind() const { DX11Internal::GetDeviceContext()->OMSetRenderTargets(1, &mNullRTV, NULL); } void DX11Renderbuffer::BindColorBuffer(Uint index, Uint slot, ShaderDomain shaderDomain) const { ID3D11DeviceContext* deviceContext = DX11Internal::GetDeviceContext(); switch (shaderDomain) { case ShaderDomain::PIXEL: deviceContext->PSSetShaderResources(slot, 1, mColorAttachments[index].ShaderResourceView.GetAddressOf()); break; case ShaderDomain::COMPUTE: deviceContext->CSSetShaderResources(slot, 1, mColorAttachments[index].ShaderResourceView.GetAddressOf()); break; case ShaderDomain::VERTEX: deviceContext->VSSetShaderResources(slot, 1, mColorAttachments[index].ShaderResourceView.GetAddressOf()); break; case ShaderDomain::NONE: E_INTERNAL_ASSERT("ShaderDomain::NONE is invalid in this context!") break; } } void DX11Renderbuffer::BindDepthBuffer(Uint slot, ShaderDomain shaderDomain) const { ID3D11DeviceContext* deviceContext = DX11Internal::GetDeviceContext(); switch (shaderDomain) { case ShaderDomain::PIXEL: deviceContext->PSSetShaderResources(slot, 1, mDepthAttachment.ShaderResourceView.GetAddressOf()); break; case ShaderDomain::COMPUTE: deviceContext->CSSetShaderResources(slot, 1, mDepthAttachment.ShaderResourceView.GetAddressOf()); break; case ShaderDomain::VERTEX: deviceContext->VSSetShaderResources(slot, 1, mDepthAttachment.ShaderResourceView.GetAddressOf()); break; case ShaderDomain::NONE: E_INTERNAL_ASSERT("ShaderDomain::NONE is invalid in this context!") break; } } void DX11Renderbuffer::UnbindBuffer(Uint slot, ShaderDomain shaderDomain) const { ID3D11DeviceContext* deviceContext = DX11Internal::GetDeviceContext(); switch (shaderDomain) { case ShaderDomain::PIXEL: deviceContext->PSSetShaderResources(slot, 1, &mNullSRV); break; case ShaderDomain::COMPUTE: deviceContext->CSSetShaderResources(slot, 1, &mNullSRV); break; case ShaderDomain::VERTEX: deviceContext->VSSetShaderResources(slot, 1, &mNullSRV); break; case ShaderDomain::NONE: E_INTERNAL_ASSERT("ShaderDomain::NONE is invalid in this context!") break; } } void DX11Renderbuffer::CSBindUAV(Uint textureIndex, Uint slot) const { constexpr UINT noOffset = -1; DX11Internal::GetDeviceContext()->CSSetUnorderedAccessViews(slot, 1, mColorAttachments[textureIndex].UnorderedAccessView.GetAddressOf(), &noOffset); } void DX11Renderbuffer::CSUnbindUAV(Uint slot) const { constexpr UINT noOffset = -1; DX11Internal::GetDeviceContext()->CSSetUnorderedAccessViews(slot, 1, &mNullUAV, &noOffset); } void DX11Renderbuffer::Invalidate() { Clean(); mViewport.TopLeftX = 0.0f; mViewport.TopLeftY = 0.0f; mViewport.Width = static_cast<float>(mSpecification.Width); mViewport.Height = static_cast<float>(mSpecification.Height); mViewport.MinDepth = 0.0f; mViewport.MaxDepth = 1.0f; if (!mColorAttachmentSpecifications.empty()) { mColorAttachments.resize(mColorAttachmentSpecifications.size()); // Attachments for (size_t i = 0; i < mColorAttachments.size(); i++) { if (mSpecification.SwapChainTarget) { Utils::AttachToSwapchain(&mColorAttachments[i], mSpecification); break; } switch (mColorAttachmentSpecifications[i].TextureFormat) { case RenderBufferTextureFormat::RGBA32F: Utils::AttachColorTexture(mColorAttachmentSpecifications[i], mSpecification, &mColorAttachments[i]); break; case RenderBufferTextureFormat::RGBA8UNORM: Utils::AttachColorTexture(mColorAttachmentSpecifications[i], mSpecification, &mColorAttachments[i]); break; case RenderBufferTextureFormat::R32SINT: Utils::AttachColorTexture(mColorAttachmentSpecifications[i], mSpecification, &mColorAttachments[i]); break; } } } if (mDepthAttachmentSpecification.TextureFormat != RenderBufferTextureFormat::NONE) { switch (mDepthAttachmentSpecification.TextureFormat) { case RenderBufferTextureFormat::D24S8UINT: Utils::AttachDepthTexture(mDepthAttachmentSpecification, mSpecification, &mDepthAttachment); break; case RenderBufferTextureFormat::R32VOID: Utils::AttachDepthTexture(mDepthAttachmentSpecification, mSpecification, &mDepthAttachment); break; } } } void DX11Renderbuffer::Clean() { for (size_t i = 0; i < mColorAttachments.size(); i++) { mColorAttachments[i].RenderTargetTexture.Reset(); mColorAttachments[i].RenderTargetView.Reset(); mColorAttachments[i].ShaderResourceView.Reset(); } mColorAttachments.clear(); mDepthAttachment.DepthStencilView.Reset(); mDepthAttachment.DepthStencilBuffer.Reset(); } void DX11Renderbuffer::Clear(const glm::vec4& clearColor) const { ID3D11DeviceContext* deviceContext = DX11Internal::GetDeviceContext(); for (Uint i = 0; i < mColorAttachments.size(); i++) deviceContext->ClearRenderTargetView(mColorAttachments[i].RenderTargetView.Get(), (float*)&clearColor); if (mDepthAttachmentSpecification.TextureFormat != RenderBufferTextureFormat::NONE) deviceContext->ClearDepthStencilView(mDepthAttachment.DepthStencilView.Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); } void DX11Renderbuffer::Resize(Uint width, Uint height) { if (width == 0 || height == 0 || width > sMaxFramebufferSize || height > sMaxFramebufferSize) { Log::Warn("Attempted to resize renderbuffer to {0}, {0}", width, height); return; } mSpecification.Width = width; mSpecification.Height = height; Invalidate(); } void DX11Renderbuffer::EnsureSize(Uint width, Uint height) { if (width != mSpecification.Width || height != mSpecification.Height) { mSpecification.Width = width; mSpecification.Height = height; Invalidate(); } } }
47.395062
179
0.670096
SurgeTechnologies
5fe53c0029d1e5affde4c094dfca9df22124ab1d
2,994
cpp
C++
_2007 - Undemo/src/libTexture/Texture.cpp
retgone/cmc-cg
7e5a76992e524958353ee799092f810681a13107
[ "MIT" ]
null
null
null
_2007 - Undemo/src/libTexture/Texture.cpp
retgone/cmc-cg
7e5a76992e524958353ee799092f810681a13107
[ "MIT" ]
null
null
null
_2007 - Undemo/src/libTexture/Texture.cpp
retgone/cmc-cg
7e5a76992e524958353ee799092f810681a13107
[ "MIT" ]
null
null
null
// // Simple texture class // #ifdef _WIN32 #include <windows.h> #endif #include <GL/gl.h> #include <GL/glu.h> #include <malloc.h> #include <memory.h> #include "Texture.h" Texture :: Texture () { width = 0; height = 0; numComponents = 0; data = NULL; levels = 0; compressed = false; mipmapped = false; format = GL_NONE; } Texture :: Texture ( int theWidth, int theHeight, int theNumComponents ) { width = theWidth; height = theHeight; numComponents = theNumComponents; data = (byte *) malloc ( width * height * numComponents ); levels = 1; compressed = false; mipmapped = false; switch ( numComponents ) { case 1: format = GL_ALPHA; break; case 3: format = GL_RGB; break; case 4: format = GL_RGBA; break; default: format = -1; } } Texture :: ~Texture () { if ( data != NULL ) free ( data ); } // store 32-bit RGBA image into texture in a // specified line void Texture :: putLine ( int y, dword * bits ) { if ( y < 0 || y >= height ) return; int offs = y * width * numComponents; byte * ptr = data + offs; if ( numComponents == 4 ) // RGBA image memcpy ( ptr, bits, 4 * width ); else if ( numComponents == 3 ) // RGB image { byte * src = (byte *) bits; for ( int i = 0; i < width; i++, src += 4 ) { *ptr++ = src [0]; *ptr++ = src [1]; *ptr++ = src [2]; } } else if ( numComponents == 1 ) // greyscale image { for ( int i = 0; i < width ; i++, bits++ ) *ptr++ = *(byte *) bits; } } bool Texture :: upload ( int target, bool mipmap ) { if ( target == GL_TEXTURE_1D ) { if ( mipmap ) gluBuild1DMipmaps ( target, getNumComponents (), getWidth (), getFormat (), GL_UNSIGNED_BYTE, getData () ); else glTexImage1D ( target, 0, getNumComponents (), getWidth (), 0, getFormat (), GL_UNSIGNED_BYTE, getData () ); } else { if ( mipmap ) gluBuild2DMipmaps ( target, getNumComponents (), getWidth (), getHeight (), getFormat (), GL_UNSIGNED_BYTE, getData () ); else glTexImage2D ( target, 0, getNumComponents (), getWidth (), getHeight (), 0, getFormat (), GL_UNSIGNED_BYTE, getData () ); } mipmapped = mipmap; return true; }
25.159664
94
0.434202
retgone
5fe95fdfc63eb73eb12ecfd4e687164a67eb02a1
3,396
hpp
C++
math/private/taylor.hpp
Better-Idea/Mix-C
71f34a5fc8c17a516cf99bc397289d046364a82e
[ "Apache-2.0" ]
41
2019-09-24T02:17:34.000Z
2022-01-18T03:14:46.000Z
math/private/taylor.hpp
Better-Idea/Mix-C
71f34a5fc8c17a516cf99bc397289d046364a82e
[ "Apache-2.0" ]
2
2019-11-04T09:01:40.000Z
2020-06-23T03:03:38.000Z
math/private/taylor.hpp
Better-Idea/Mix-C
71f34a5fc8c17a516cf99bc397289d046364a82e
[ "Apache-2.0" ]
8
2019-09-24T02:17:35.000Z
2021-09-11T00:21:03.000Z
#ifndef xpack_math_private_taylor #define xpack_math_private_taylor #pragma push_macro("xuser") #undef xuser #define xuser mixc::math_private_taylor::inc #include"define/base_type.hpp" #include"macro/xexport.hpp" #pragma pop_macro("xuser") // 生成 4x6 常量系数 // coe (coefficient) #define xcoe(name) \ template<class float_t> \ struct coe_ ## name{ \ private: \ static constexpr float_t value(uxx n); \ public: \ using float_type = float_t; \ static constexpr float_t lut[] = { \ value(0x00), value(0x01), value(0x02), value(0x03), \ value(0x04), value(0x05), value(0x06), value(0x07), \ value(0x08), value(0x09), value(0x0a), value(0x0b), \ value(0x0c), value(0x0d), value(0x0e), value(0x0f), \ value(0x10), value(0x11), value(0x12), value(0x13), \ value(0x14), value(0x15), value(0x16), value(0x17), \ }; \ static constexpr uxx length = sizeof(lut) / sizeof(lut[0]); \ }; \ template<class float_t> \ constexpr float_t coe_ ## name<float_t>::value(uxx n) namespace mixc::math_private_taylor::imm{ template<class type> inline constexpr type factorial(type n){ if (n <= 1){ return 1; } return n * factorial(n - 1); } template<class type> inline constexpr type pow(type x, uxx n){ if (n == 0){ return 1; } if (n == 1){ return x; } else{ return x * pow(x, n - 1); } } template<class type> // cumulative product inline constexpr type cum(type x, uxx n, uxx step){ if (n == 0){ return 1; } if (n == 1){ return x; } return x * cum(x + step, n - 1, step); } } namespace mixc::math_private_taylor::origin{ template<class lut_t> inline typename lut_t::float_type taylor( typename lut_t::float_type x0, typename lut_t::float_type x1, typename lut_t::float_type x2, typename lut_t::float_type x3, typename lut_t::float_type mx){ auto s0 = typename lut_t::float_type(0); auto s1 = typename lut_t::float_type(0); auto s2 = typename lut_t::float_type(0); auto s3 = typename lut_t::float_type(0); static_assert(lut_t::length % 4 == 0); for(uxx i = 0; i < lut_t::length; i += 4){ s0 += lut_t::lut[0x0 + i] * x0; s1 += lut_t::lut[0x1 + i] * x1; s2 += lut_t::lut[0x2 + i] * x2; s3 += lut_t::lut[0x3 + i] * x3; x0 *= mx; x1 *= mx; x2 *= mx; x3 *= mx; } s0 += s2; s1 += s3; s0 += s1; return s0; } } #endif xexport_space(mixc::math_private_taylor::origin) xexport_spacex(adv, mixc::math_private_taylor::imm)
32.653846
69
0.46172
Better-Idea
5fedb50d51f7ad15cb04e0cbcde7555b65d6519f
1,023
cpp
C++
src/core/math/matrix3x3.cpp
ValtoForks/crown
0d273f352de01f0adac8a29db7f520979540b916
[ "MIT" ]
null
null
null
src/core/math/matrix3x3.cpp
ValtoForks/crown
0d273f352de01f0adac8a29db7f520979540b916
[ "MIT" ]
null
null
null
src/core/math/matrix3x3.cpp
ValtoForks/crown
0d273f352de01f0adac8a29db7f520979540b916
[ "MIT" ]
null
null
null
/* * Copyright (c) 2012-2018 Daniele Bartolini and individual contributors. * License: https://github.com/dbartolini/crown/blob/master/LICENSE */ #include "core/math/matrix3x3.h" namespace crown { Matrix3x3& invert(Matrix3x3& m) { const f32 xx = m.x.x; const f32 xy = m.x.y; const f32 xz = m.x.z; const f32 yx = m.y.x; const f32 yy = m.y.y; const f32 yz = m.y.z; const f32 zx = m.z.x; const f32 zy = m.z.y; const f32 zz = m.z.z; f32 det = 0.0f; det += m.x.x * (m.y.y * m.z.z - m.z.y * m.y.z); det -= m.y.x * (m.x.y * m.z.z - m.z.y * m.x.z); det += m.z.x * (m.x.y * m.y.z - m.y.y * m.x.z); const f32 inv_det = 1.0f / det; m.x.x = + (yy*zz - zy*yz) * inv_det; m.x.y = - (xy*zz - zy*xz) * inv_det; m.x.z = + (xy*yz - yy*xz) * inv_det; m.y.x = - (yx*zz - zx*yz) * inv_det; m.y.y = + (xx*zz - zx*xz) * inv_det; m.y.z = - (xx*yz - yx*xz) * inv_det; m.z.x = + (yx*zy - zx*yy) * inv_det; m.z.y = - (xx*zy - zx*xy) * inv_det; m.z.z = + (xx*yy - yx*xy) * inv_det; return m; } } // namespace crown
22.733333
73
0.54741
ValtoForks
5ff1c66b9dd889cc507f35caba96ca46cbadae5c
1,174
cpp
C++
csapex_core_plugins/src/text/text_input.cpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
2
2016-09-02T15:33:22.000Z
2019-05-06T22:09:33.000Z
csapex_core_plugins/src/text/text_input.cpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
1
2021-02-11T09:14:31.000Z
2021-02-27T09:30:14.000Z
csapex_core_plugins/src/text/text_input.cpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
6
2016-10-12T00:55:23.000Z
2021-02-10T17:49:25.000Z
/// HEADER #include "text_input.h" /// PROJECT #include <csapex/model/node_modifier.h> #include <csapex/model/token.h> #include <csapex/msg/generic_value_message.hpp> #include <csapex/msg/io.h> #include <csapex/param/parameter_factory.h> #include <csapex/signal/event.h> #include <csapex/utility/register_apex_plugin.h> CSAPEX_REGISTER_CLASS(csapex::TextInput, csapex::Node) using namespace csapex; TextInput::TextInput() { } void TextInput::setupParameters(Parameterizable& parameters) { parameters.addParameter(csapex::param::factory::declareText("text", ""), [this](param::Parameter* p) { std::string txt = p->as<std::string>(); if (txt != text_) { text_ = txt; auto text_message = std::make_shared<connection_types::GenericValueMessage<std::string>>(); text_message->value = text_; event_->triggerWith(std::make_shared<Token>(text_message)); } }); } void TextInput::process() { msg::publish(output_, text_); } void TextInput::setup(NodeModifier& node_modifier) { output_ = node_modifier.addOutput<std::string>("Text"); event_ = node_modifier.addEvent("text changed"); }
26.088889
106
0.689949
AdrianZw
5ff1f07f3de7eab200bafd6036dd24e193a40690
6,710
hh
C++
cc/virus/passage.hh
skepner/ae
d53336a561df1a46a39debb143c9f9496b222a46
[ "MIT" ]
null
null
null
cc/virus/passage.hh
skepner/ae
d53336a561df1a46a39debb143c9f9496b222a46
[ "MIT" ]
null
null
null
cc/virus/passage.hh
skepner/ae
d53336a561df1a46a39debb143c9f9496b222a46
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include "ext/fmt.hh" #include "ext/compare.hh" #include "utils/string.hh" #include "utils/messages.hh" // ====================================================================== namespace ae::virus::passage { struct deconstructed_t { struct element_t { std::string name{}; std::string count{}; // if count empty, name did not parsed std::string subtype{}; // NIID E4(AM2AL2) bool new_lab{false}; bool operator==(const element_t& rhs) const = default; std::string construct(bool add_new_lab_separator) const { std::string result; result.append(name); result.append(count); result.append(subtype); if (!count.empty() && add_new_lab_separator && new_lab) result.append(1, '/'); return result; } bool egg() const { return name == "E" || name == "SPFCE"; } bool cell() const { return name == "MDCK" || name == "SIAT" || name == "HCK" || name == "SPFCK"; } bool good() const { return !name.empty() && (name == "OR" || !count.empty()); } }; std::vector<element_t> elements{}; std::string date{}; constexpr deconstructed_t() = default; constexpr deconstructed_t(int) : deconstructed_t() {} // to support lexy::fold_inplace in passage-parse.cc deconstructed_t(const std::vector<element_t>& a_elements, const std::string& a_date) : elements{a_elements}, date{a_date} {} // deconstructed_t(std::string_view not_parsed) : elements{element_t{.name{not_parsed}}} {} bool operator==(const deconstructed_t& rhs) const = default; auto operator<=>(const deconstructed_t& rhs) const { return construct() <=> rhs.construct(); } bool empty() const { return elements.empty(); } const element_t& last() const { return elements.back(); } bool egg() const { return !empty() && last().egg(); } bool cell() const { return !empty() && last().cell(); } enum class with_date { no, yes }; std::string construct(with_date wd = with_date::yes) const { std::string result; for (const auto& elt : elements) result.append(elt.construct(true)); if (wd == with_date::yes && !date.empty()) result.append(fmt::format(" ({})", date)); return result; } auto& uppercase() { for (auto& elt : elements) { string::uppercase_in_place(elt.name); string::uppercase_in_place(elt.count); } return *this; } bool good() const { return !elements.empty() && elements.front().good() && std::count_if(std::begin(elements), std::end(elements), [](const auto& elt) { return !elt.good() || elt.count[0] == '?'; }) < 2; } }; // ---------------------------------------------------------------------- class parse_settings { public: enum class tracing { no, yes }; parse_settings(tracing a_trace = tracing::no) : tracing_{a_trace} {} constexpr bool trace() const { return tracing_ == tracing::yes; } private: tracing tracing_{tracing::no}; }; deconstructed_t parse(std::string_view source, const parse_settings& settings, Messages& messages, const MessageLocation& location); inline deconstructed_t parse(std::string_view source, parse_settings::tracing tracing = parse_settings::tracing::no) { Messages messages; return parse(source, parse_settings{tracing}, messages, MessageLocation{}); } inline bool is_good(std::string_view source) { return parse(source).good(); } } // namespace ae::virus::passage // ---------------------------------------------------------------------- namespace ae::virus { class Passage { public: enum class parse { no, yes }; Passage() = default; Passage(const Passage&) = default; Passage(Passage&&) = default; explicit Passage(std::string_view src, parse pars = parse::yes, passage::parse_settings::tracing tracing = passage::parse_settings::tracing::no) { if (!src.empty()) { if (pars == parse::yes) deconstructed_ = passage::parse(src, tracing); else deconstructed_.elements.push_back(passage::deconstructed_t::element_t{.name{std::string{src}}}); // g++-11 wants std::string{src} } } Passage& operator=(const Passage&) = default; Passage& operator=(Passage&&) = default; bool operator==(const Passage& rhs) const = default; auto operator<=>(const Passage& rhs) const { return static_cast<std::string>(*this) <=> static_cast<std::string>(rhs); } bool good() const { return deconstructed_.good(); } bool empty() const { return deconstructed_.empty(); } bool is_egg() const { return deconstructed_.egg(); } bool is_cell() const { return deconstructed_.cell(); } std::string without_date() const { return deconstructed_.construct(passage::deconstructed_t::with_date::no); } operator std::string() const { return deconstructed_.construct(); } std::string to_string() const { return deconstructed_.construct(); } size_t size() const { return deconstructed_.construct().size(); } size_t number_of_elements() const { return deconstructed_.elements.size(); } // std::string_view last_number() const; // E2/E3 -> 3, X? -> ? // std::string_view last_type() const; // MDCK3/SITA1 -> SIAT std::string_view passage_type() const { using namespace std::string_view_literals; if (is_egg()) return "egg"sv; else return "cell"sv; } // size_t find(std::string_view look_for) const { return get().find(look_for); } // bool search(const std::regex& re) const { return std::regex_search(get(), re); } private: passage::deconstructed_t deconstructed_{}; }; } // namespace ae::virus template <> struct fmt::formatter<ae::virus::Passage> : public fmt::formatter<std::string> { template <typename FormatContext> auto format(const ae::virus::Passage& ts, FormatContext& ctx) { return fmt::formatter<std::string>::format(static_cast<std::string>(ts), ctx); } }; // ======================================================================
37.277778
195
0.557526
skepner
5ff2dbff101f428a796f1ec674d67868ca7fdab4
3,905
cpp
C++
Bumblebee/BumblebeeGLSLProgram.cpp
radical-bumblebee/bumblebee-engine
c5b7eb4bcd825bc2c5be66d6306912c519a56a2d
[ "MIT" ]
1
2017-08-15T03:56:22.000Z
2017-08-15T03:56:22.000Z
Bumblebee/BumblebeeGLSLProgram.cpp
radical-bumblebee/bumblebee-engine
c5b7eb4bcd825bc2c5be66d6306912c519a56a2d
[ "MIT" ]
null
null
null
Bumblebee/BumblebeeGLSLProgram.cpp
radical-bumblebee/bumblebee-engine
c5b7eb4bcd825bc2c5be66d6306912c519a56a2d
[ "MIT" ]
null
null
null
#include "BumblebeeGLSLProgram.h" // Compiles a pipeline of shaders bool BumblebeeGLSLProgram::compile(bool transform) { _program = glCreateProgram(); if (_vertex_src) { _vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(_vertex, 1, &_vertex_src, 0); glCompileShader(_vertex); glAttachShader(_program, _vertex); } else { Logger::get()->log("Failed to attach vertex shader"); } if (_geometry_src) { _geometry = glCreateShader(GL_GEOMETRY_SHADER); glShaderSource(_geometry, 1, &_geometry_src, 0); glCompileShader(_geometry); glAttachShader(_program, _geometry); } if (_fragment_src) { _fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(_fragment, 1, &_fragment_src, 0); glCompileShader(_fragment); glAttachShader(_program, _fragment); } else { Logger::get()->log("Failed to attach fragment shader"); } // Set up geometry varyings if (transform) { const GLchar* geometry_varyings[4]; geometry_varyings[0] = "fs_position"; geometry_varyings[1] = "fs_velocity"; geometry_varyings[2] = "fs_type"; geometry_varyings[3] = "fs_age"; glTransformFeedbackVaryings(_program, 4, geometry_varyings, GL_INTERLEAVED_ATTRIBS); } link(); return true; } bool BumblebeeGLSLProgram::link() { glLinkProgram(_program); GLint link_success = 0; glGetProgramiv(_program, GL_LINK_STATUS, &link_success); // Linking failed, report something useful, hopefully if (!link_success) { GLint buffer_length = 0; glGetProgramiv(_program, GL_INFO_LOG_LENGTH, &buffer_length); if (buffer_length > 0) { char* buffer = new char[buffer_length]; if (buffer) { glGetProgramInfoLog(_program, buffer_length, NULL, buffer); std::cout << "Error linking program\n" << buffer << std::endl; delete[] buffer; } } return false; } return true; } // Sets a uniform matrix in the shader bool BumblebeeGLSLProgram::set_matrix(const char* name, const float* value, bool transpose) { GLint location = glGetUniformLocation(_program, name); if (location < 0) { return false; } glUniformMatrix4fv(location, 1, transpose, value); return true; } // Sets a uniform vec4 in the shader bool BumblebeeGLSLProgram::set_vec4(const char* name, const float* value) { GLint location = glGetUniformLocation(_program, name); if (location < 0) { return false; } glUniform4f(location, value[0], value[1], value[2], value[3]); return true; } // Sets a uniform float in the shader bool BumblebeeGLSLProgram::set_float(const char* name, const float value) { GLint location = glGetUniformLocation(_program, name); if (location < 0) { return false; } glUniform1f(location, value); return true; } // Sets a uniform int in the shader bool BumblebeeGLSLProgram::set_int(const char* name, const int value) { GLint location = glGetUniformLocation(_program, name); if (location < 0) { return false; } glUniform1i(location, value); return true; } // Reads a shader source file bool BumblebeeGLSLProgram::set_shader_source(ShaderType shader_type, const char* shader_path) { FILE* file = nullptr; if (fopen_s(&file, shader_path, "rb") != 0) { return false; } int length = 0; fseek(file, 0, SEEK_END); length = ftell(file); fseek(file, 0, SEEK_SET); switch (shader_type) { case VERTEX_SHADER: _vertex_src = new char[length + 1]; fread(_vertex_src, 1, length, file); _vertex_src[length] = '\0'; break; case GEOMETRY_SHADER: _geometry_src = new char[length + 1]; fread(_geometry_src, 1, length, file); _geometry_src[length] = '\0'; break; case FRAGMENT_SHADER: _fragment_src = new char[length + 1]; fread(_fragment_src, 1, length, file); _fragment_src[length] = '\0'; break; } fclose(file); return true; } // Sets shader to active void BumblebeeGLSLProgram::enable() { glUseProgram(_program); } // Returns shader id GLuint BumblebeeGLSLProgram::id() { return _program; }
22.442529
95
0.715237
radical-bumblebee
5ff732b63bfcd41acfa362ff09a498db600c9e2b
38,389
cpp
C++
SkyBox.cpp
havokentity/Reaction-Engine-Renderer
cb0452d81da6a6baf8a681141fcc8e1ba0e04b14
[ "MIT" ]
2
2020-03-09T18:48:54.000Z
2020-05-14T03:58:45.000Z
SkyBox.cpp
havokentity/Reaction-Engine-Renderer
cb0452d81da6a6baf8a681141fcc8e1ba0e04b14
[ "MIT" ]
null
null
null
SkyBox.cpp
havokentity/Reaction-Engine-Renderer
cb0452d81da6a6baf8a681141fcc8e1ba0e04b14
[ "MIT" ]
null
null
null
/* Description: Skybox class and Lens flare object class classes contained are: class Skybox class LensFlareTexObj */ #include "SkyBox.h" #include "CoreEngine.h" #include "Console.h" namespace DifferentialArts { Skybox::~Skybox() { //this->Free(); } Skybox::Skybox() { this->inUse = false; this->size = Math::Vector3(1,1,1); } void Skybox::Free() { if(!this->inUse) return; glDeleteLists(this->drawlist, 1); glDeleteLists(this->drawlist2, 1); this->inUse = false; gConsole->LogSuccessText(LString("Skybox succesfully released!")); } bool Skybox::CreateSkyboxFromCrossCubeMap(const char* skyBoxCrossTextureName, const Math::Vector3 &size, bool mipmaps, GLuint HDRIFormat) { gConsole->LogInfo(LString("Skybox from Cross Cube map Image init started...")); this->size = size; gConsole->LogInfo(LString("Cross Cube map image Skybox: %s", skyBoxCrossTextureName)); gConsole->LogInfo(LString("Attempting to load texture: %s", skyBoxCrossTextureName)); if(!skyBoxCrossTextureName) { gConsole->LogError(LString("Invalid File Name")); return false; } ILuint myImage; myImage = GenerateSingleImage(); ilBindImage(myImage); if(IL_FALSE == ilLoadImage(skyBoxCrossTextureName)) { gConsole->LogError(LString("Invalid File Data or missing file\nErrorStrings are:\n")); ILenum Error; while ((Error = ilGetError()) != IL_NO_ERROR) { gConsole->LogError(LString("%d: %s\n", Error, iluErrorString(Error))); } return false; } int _width = ilGetInteger(IL_IMAGE_WIDTH); int _height = ilGetInteger(IL_IMAGE_HEIGHT); int _depth = 0; int _elementSize = ilGetInteger(IL_IMAGE_BPP); //gConsole->LogError(LString("w: %d h: %d", _width, _height)); if ( (_width / 3 != _height / 4) || (_width % 3 != 0) || (_height % 4 != 0) || (_depth != 0)) return false; GLubyte *data = ilGetData(); int fWidth = _width / 3; int fHeight = _height / 4; GLuint texID; GLubyte *face = new GLubyte[ fWidth * fHeight * _elementSize]; GLubyte *ptr; /* POSITIVE_X */ texID = RIGHT; ptr = face; for (int j=0; j<fHeight; j++) { memcpy( ptr, &data[(((fHeight + j + 1))*_width + 2 * fWidth) * _elementSize], fWidth*_elementSize); ptr += fWidth*_elementSize; } glGenTextures(1, &g_Textures[texID]); glBindTexture(GL_TEXTURE_2D, g_Textures[texID]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); if(mipmaps) { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR_MIPMAP_LINEAR); gluBuild2DMipmaps(GL_TEXTURE_2D, (ilGetInteger(IL_IMAGE_TYPE)==GL_FLOAT)?HDRIFormat:_elementSize, fWidth, fHeight, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), face); } else { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, (ilGetInteger(IL_IMAGE_TYPE)==GL_FLOAT)?HDRIFormat:_elementSize, fWidth, fHeight, 0, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), face); } /* NEGATIVE_X */ texID = LEFT; face = new GLubyte[ fWidth * fHeight * _elementSize]; ptr = face; for (int j=0; j<fHeight; j++) { memcpy( ptr, &data[((fHeight + j + 1))*_width*_elementSize], fWidth*_elementSize); ptr += fWidth*_elementSize; } glGenTextures(1, &g_Textures[texID]); glBindTexture(GL_TEXTURE_2D, g_Textures[texID]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); if(mipmaps) { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR_MIPMAP_LINEAR); gluBuild2DMipmaps(GL_TEXTURE_2D, (ilGetInteger(IL_IMAGE_TYPE)==GL_FLOAT)?HDRIFormat:_elementSize, fWidth, fHeight, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), face); } else { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, (ilGetInteger(IL_IMAGE_TYPE)==GL_FLOAT)?HDRIFormat:_elementSize, fWidth, fHeight, 0, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), face); } /* POSITIVE_Y */ texID = FRONT; face = new GLubyte[ fWidth * fHeight * _elementSize]; ptr = face; for (int j=0; j<fHeight; j++) { memcpy( ptr, &data[((4 * fHeight - j - 1)*_width + fWidth)*_elementSize], fWidth*_elementSize); ptr += fWidth*_elementSize; } glGenTextures(1, &g_Textures[texID]); glBindTexture(GL_TEXTURE_2D, g_Textures[texID]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); if(mipmaps) { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR_MIPMAP_LINEAR); gluBuild2DMipmaps(GL_TEXTURE_2D, (ilGetInteger(IL_IMAGE_TYPE)==GL_FLOAT)?HDRIFormat:_elementSize, fWidth, fHeight, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), face); } else { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, (ilGetInteger(IL_IMAGE_TYPE)==GL_FLOAT)?HDRIFormat:_elementSize, fWidth, fHeight, 0, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), face); } /* NEGATIVE_Y */ texID = BACK; face = new GLubyte[ fWidth * fHeight * _elementSize]; ptr = face; for (int j=0; j<fHeight; j++) { memcpy( ptr, &data[((2*fHeight - j - 1)*_width + fWidth)*_elementSize], fWidth*_elementSize); ptr += fWidth*_elementSize; } glGenTextures(1, &g_Textures[texID]); glBindTexture(GL_TEXTURE_2D, g_Textures[texID]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); if(mipmaps) { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR_MIPMAP_LINEAR); gluBuild2DMipmaps(GL_TEXTURE_2D, (ilGetInteger(IL_IMAGE_TYPE)==GL_FLOAT)?HDRIFormat:_elementSize, fWidth, fHeight, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), face); } else { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, (ilGetInteger(IL_IMAGE_TYPE)==GL_FLOAT)?HDRIFormat:_elementSize, fWidth, fHeight, 0, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), face); } /* POSITIVE_Z */ texID = BOTTOM; face = new GLubyte[ fWidth * fHeight * _elementSize]; ptr = face; for (int j=0; j<fHeight; j++) { memcpy( ptr, &data[((_height - (fHeight + j + 1))*_width + fWidth) * _elementSize], fWidth*_elementSize); ptr += fWidth*_elementSize; } glGenTextures(1, &g_Textures[texID]); glBindTexture(GL_TEXTURE_2D, g_Textures[texID]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); if(mipmaps) { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR_MIPMAP_LINEAR); gluBuild2DMipmaps(GL_TEXTURE_2D, (ilGetInteger(IL_IMAGE_TYPE)==GL_FLOAT)?HDRIFormat:_elementSize, fWidth, fHeight, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), face); } else { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, (ilGetInteger(IL_IMAGE_TYPE)==GL_FLOAT)?HDRIFormat:_elementSize, fWidth, fHeight, 0, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), face); } /* NEGATIVE_Z */ texID = TOP; face = new GLubyte[ fWidth * fHeight * _elementSize]; ptr = face; for (int j=0; j<fHeight; j++) { for (int i=0; i<fWidth; i++) { memcpy( ptr, &data[(j*_width + 2 * fWidth - (i + 1))*_elementSize], _elementSize); ptr += _elementSize; } } glGenTextures(1, &g_Textures[texID]); glBindTexture(GL_TEXTURE_2D, g_Textures[texID]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); if(mipmaps) { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR_MIPMAP_LINEAR); gluBuild2DMipmaps(GL_TEXTURE_2D, (ilGetInteger(IL_IMAGE_TYPE)==GL_FLOAT)?HDRIFormat:_elementSize, fWidth, fHeight, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), face); } else { glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, (ilGetInteger(IL_IMAGE_TYPE)==GL_FLOAT)?HDRIFormat:_elementSize, fWidth, fHeight, 0, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), face); } DeleteSingleImage(myImage); /* ===========BREAK================ */ /* Create skybox display list */ this->drawlist = glGenLists(1); glNewList(this->drawlist, GL_COMPILE); glPushAttrib(GL_ENABLE_BIT); //glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); glColor4f(1, 1, 1, 1); // Bind the BACK texture of the sky map to the BACK side of the cube glBindTexture(GL_TEXTURE_2D, g_Textures[BACK]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the BACK Side glTexCoord2f(1.0f, 0.0f); glVertex3f( size.x, 0, 0); glTexCoord2f(1.0f, 1.0f); glVertex3f( size.x, size.y, 0); glTexCoord2f(0.0f, 1.0f); glVertex3f(0, size.y, 0); glTexCoord2f(0.0f, 0.0f); glVertex3f(0, 0, 0); glEnd(); // Bind the FRONT texture of the sky map to the FRONT side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[FRONT]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the FRONT Side glTexCoord2f(0.0f, 1.0f); glVertex3f(0, 0, size.z); glTexCoord2f(0.0f, 0.0f); glVertex3f(0, size.y, size.z); glTexCoord2f(1.0f, 0.0f); glVertex3f( size.x, size.y, size.z); glTexCoord2f(1.0f, 1.0f); glVertex3f( size.x, 0, size.z); glEnd(); // Bind the BOTTOM texture of the sky map to the BOTTOM side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[BOTTOM]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the BOTTOM Side glTexCoord2f(0.0f, 1.0f); glVertex3f(0, 0, 0); glTexCoord2f(0.0f, 0.0f); glVertex3f(0, 0, size.z); glTexCoord2f(1.0f, 0.0f); glVertex3f( size.x, 0, size.z); glTexCoord2f(1.0f, 1.0f); glVertex3f( size.x, 0,0); glEnd(); // Bind the TOP texture of the sky map to the TOP side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[TOP]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the TOP Side glTexCoord2f(0.0f, 1.0f); glVertex3f( size.x, size.y, 0); glTexCoord2f(0.0f, 0.0f); glVertex3f( size.x, size.y, size.z); glTexCoord2f(1.0f, 0.0f); glVertex3f(0, size.y, size.z); glTexCoord2f(1.0f, 1.0f); glVertex3f(0, size.y, 0); glEnd(); // Bind the LEFT texture of the sky map to the LEFT side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[LEFT]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the LEFT Side glTexCoord2f(1.0f, 0.0f); glVertex3f(0, size.y, 0); glTexCoord2f(0.0f, 0.0f); glVertex3f(0, size.y, size.z); glTexCoord2f(0.0f, 1.0f); glVertex3f(0, 0, size.z); glTexCoord2f(1.0f, 1.0f); glVertex3f(0, 0,0); glEnd(); // Bind the RIGHT texture of the sky map to the RIGHT side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[RIGHT]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the RIGHT Side glTexCoord2f(0.0f, 1.0f); glVertex3f( size.x, 0, 0); glTexCoord2f(1.0f, 1.0f); glVertex3f( size.x, 0, size.z); glTexCoord2f(1.0f, 0.0f); glVertex3f( size.x, size.y, size.z); glTexCoord2f(0.0f, 0.0f); glVertex3f( size.x, size.y, 0); glEnd(); glPopAttrib(); glEndList(); /* End of skybox display list */ /* Create skybox display list FLIPPED */ this->drawlist2 = glGenLists(1); glNewList(this->drawlist2, GL_COMPILE); glPushAttrib(GL_ENABLE_BIT); //glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); glColor4f(1, 1, 1, 1); // Bind the BACK texture of the sky map to the BACK side of the cube glBindTexture(GL_TEXTURE_2D, g_Textures[BACK]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the BACK Side glTexCoord2f(1.0f, 0.0f); glVertex3f( size.x, 0, 0); glTexCoord2f(1.0f, 1.0f); glVertex3f( size.x, size.y, 0); glTexCoord2f(0.0f, 1.0f); glVertex3f(0, size.y, 0); glTexCoord2f(0.0f, 0.0f); glVertex3f(0, 0, 0); glEnd(); // Bind the FRONT texture of the sky map to the FRONT side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[FRONT]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the FRONT Side glTexCoord2f(0.0f, 1.0f); glVertex3f(0, 0, size.z); glTexCoord2f(0.0f, 0.0f); glVertex3f(0, size.y, size.z); glTexCoord2f(1.0f, 0.0f); glVertex3f( size.x, size.y, size.z); glTexCoord2f(1.0f, 1.0f); glVertex3f( size.x, 0, size.z); glEnd(); // Bind the BOTTOM texture of the sky map to the BOTTOM side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[BOTTOM]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the BOTTOM Side glTexCoord2f(0.0f, 1.0f); glVertex3f(0, 0, 0); glTexCoord2f(0.0f, 0.0f); glVertex3f(0, 0, size.z); glTexCoord2f(1.0f, 0.0f); glVertex3f( size.x, 0, size.z); glTexCoord2f(1.0f, 1.0f); glVertex3f( size.x, 0,0); glEnd(); // Bind the TOP texture of the sky map to the TOP side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[TOP]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the TOP Side glTexCoord2f(0.0f, 1.0f); glVertex3f( size.x, size.y, 0); glTexCoord2f(0.0f, 0.0f); glVertex3f( size.x, size.y, size.z); glTexCoord2f(1.0f, 0.0f); glVertex3f(0, size.y, size.z); glTexCoord2f(1.0f, 1.0f); glVertex3f(0, size.y, 0); glEnd(); // Bind the LEFT texture of the sky map to the LEFT side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[LEFT]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the LEFT Side glTexCoord2f(1.0f, 0.0f); glVertex3f(0, size.y, 0); glTexCoord2f(0.0f, 0.0f); glVertex3f(0, size.y, size.z); glTexCoord2f(0.0f, 1.0f); glVertex3f(0, 0, size.z); glTexCoord2f(1.0f, 1.0f); glVertex3f(0, 0,0); glEnd(); // Bind the RIGHT texture of the sky map to the RIGHT side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[RIGHT]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the RIGHT Side glTexCoord2f(0.0f, 1.0f); glVertex3f( size.x, 0, 0); glTexCoord2f(1.0f, 1.0f); glVertex3f( size.x, 0, size.z); glTexCoord2f(1.0f, 0.0f); glVertex3f( size.x, size.y, size.z); glTexCoord2f(0.0f, 0.0f); glVertex3f( size.x, size.y, 0); glEnd(); glPopAttrib(); glEndList(); /* End of skybox display list */ gConsole->LogSuccessText(LString("Skybox '%s' succesfully created!", skyBoxCrossTextureName)); this->inUse = true; return true; } bool Skybox::CreateSkybox(char* skyBoxTexFolderName, const Math::Vector3 &size, bool mipmaps) { char fileName[256]; char formatFileName[256]; char format[256]; strcpy(formatFileName, skyBoxTexFolderName); strcat(formatFileName, "format.format"); gConsole->LogInfo(LString("Skybox init started...")); std::ifstream fin(formatFileName); if(fin.fail()) { gConsole->LogError(LString("Failed to read format file in skybox %s", skyBoxTexFolderName)); return false; } fin>>format; fin.close(); this->size = size; gConsole->LogInfo(LString("Skybox: %s", skyBoxTexFolderName)); strcpy(fileName, skyBoxTexFolderName); strcat(fileName, "Back"); strcat(fileName, format); LoadTextureForSkyBox(fileName, g_Textures, BACK, mipmaps); strcpy(fileName, skyBoxTexFolderName); strcat(fileName, "Front"); strcat(fileName, format); LoadTextureForSkyBox(fileName, g_Textures, FRONT, mipmaps); strcpy(fileName, skyBoxTexFolderName); strcat(fileName, "Bottom"); strcat(fileName, format); LoadTextureForSkyBox(fileName, g_Textures, BOTTOM, mipmaps); strcpy(fileName, skyBoxTexFolderName); strcat(fileName, "Top"); strcat(fileName, format); LoadTextureForSkyBox(fileName, g_Textures, TOP, mipmaps); strcpy(fileName, skyBoxTexFolderName); strcat(fileName, "Left"); strcat(fileName, format); LoadTextureForSkyBox(fileName, g_Textures, LEFT, mipmaps); strcpy(fileName, skyBoxTexFolderName); strcat(fileName, "Right"); strcat(fileName, format); LoadTextureForSkyBox(fileName, g_Textures, RIGHT, mipmaps); this->setPosition(Math::Vector3(0, 0, 0)); /* Create skybox display list */ this->drawlist = glGenLists(1); glNewList(this->drawlist, GL_COMPILE); //glPushAttrib(GL_ENABLE_BIT); //glDisable(GL_DEPTH_TEST); //glDisable(GL_LIGHTING); //glEnable(GL_TEXTURE_2D); //glColor4f(1, 1, 1, 1); //glDisable(GL_CULL_FACE); // Bind the BACK texture of the sky map to the BACK side of the cube glBindTexture(GL_TEXTURE_2D, g_Textures[BACK]); /* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); */ glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the BACK Side glTexCoord2f(1.0f, 0.0f); glVertex3f( size.x, 0, 0); glTexCoord2f(1.0f, 1.0f); glVertex3f( size.x, size.y, 0); glTexCoord2f(0.0f, 1.0f); glVertex3f(0, size.y, 0); glTexCoord2f(0.0f, 0.0f); glVertex3f(0, 0, 0); glEnd(); // Bind the FRONT texture of the sky map to the FRONT side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[FRONT]); /* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); */ // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the FRONT Side glTexCoord2f(1.0f, 0.0f); glVertex3f(0, 0, size.z); glTexCoord2f(1.0f, 1.0f); glVertex3f(0, size.y, size.z); glTexCoord2f(0.0f, 1.0f); glVertex3f( size.x, size.y, size.z); glTexCoord2f(0.0f, 0.0f); glVertex3f( size.x, 0, size.z); glEnd(); // Bind the BOTTOM texture of the sky map to the BOTTOM side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[BOTTOM]); /* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); */ // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the BOTTOM Side glTexCoord2f(1.0f, 0.0f); glVertex3f(0, 0, 0); glTexCoord2f(1.0f, 1.0f); glVertex3f(0, 0, size.z); glTexCoord2f(0.0f, 1.0f); glVertex3f( size.x, 0, size.z); glTexCoord2f(0.0f, 0.0f); glVertex3f( size.x, 0,0); glEnd(); // Bind the TOP texture of the sky map to the TOP side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[TOP]); /* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); */ // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the TOP Side glTexCoord2f(0.0f, 1.0f); glVertex3f( size.x, size.y, 0); glTexCoord2f(0.0f, 0.0f); glVertex3f( size.x, size.y, size.z); glTexCoord2f(1.0f, 0.0f); glVertex3f(0, size.y, size.z); glTexCoord2f(1.0f, 1.0f); glVertex3f(0, size.y, 0); glEnd(); // Bind the LEFT texture of the sky map to the LEFT side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[LEFT]); /* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); */ // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the LEFT Side glTexCoord2f(1.0f, 1.0f); glVertex3f(0, size.y, 0); glTexCoord2f(0.0f, 1.0f); glVertex3f(0, size.y, size.z); glTexCoord2f(0.0f, 0.0f); glVertex3f(0, 0, size.z); glTexCoord2f(1.0f, 0.0f); glVertex3f(0, 0,0); glEnd(); // Bind the RIGHT texture of the sky map to the RIGHT side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[RIGHT]); /* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); */ // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the RIGHT Side glTexCoord2f(0.0f, 0.0f); glVertex3f( size.x, 0, 0); glTexCoord2f(1.0f, 0.0f); glVertex3f( size.x, 0, size.z); glTexCoord2f(1.0f, 1.0f); glVertex3f( size.x, size.y, size.z); glTexCoord2f(0.0f, 1.0f); glVertex3f( size.x, size.y, 0); glEnd(); //glPopAttrib(); glEndList(); /* End of skybox display list */ /* Create skybox display list FLIPPED */ this->drawlist2 = glGenLists(1); glNewList(this->drawlist2, GL_COMPILE); //glPushAttrib(GL_ENABLE_BIT); //glDisable(GL_DEPTH_TEST); //glDisable(GL_LIGHTING); //glEnable(GL_TEXTURE_2D); //glColor4f(1, 1, 1, 1); // Bind the BACK texture of the sky map to the BACK side of the cube glBindTexture(GL_TEXTURE_2D, g_Textures[BACK]); /* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); */ glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the BACK Side glTexCoord2f(1.0f, 1.0f); glVertex3f( size.x, 0, 0); glTexCoord2f(1.0f, 0.0f); glVertex3f( size.x, size.y, 0); glTexCoord2f(0.0f, 0.0f); glVertex3f(0, size.y, 0); glTexCoord2f(0.0f, 1.0f); glVertex3f(0, 0, 0); glEnd(); // Bind the FRONT texture of the sky map to the FRONT side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[FRONT]); /* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); */ // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the FRONT Side glTexCoord2f(1.0f, 1.0f); glVertex3f(0, 0, size.z); glTexCoord2f(1.0f, 0.0f); glVertex3f(0, size.y, size.z); glTexCoord2f(0.0f, 0.0f); glVertex3f( size.x, size.y, size.z); glTexCoord2f(0.0f, 1.0f); glVertex3f( size.x, 0, size.z); glEnd(); // Bind the BOTTOM texture of the sky map to the BOTTOM side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[TOP]); /* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); */ // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the BOTTOM Side glTexCoord2f(1.0f, 1.0f); glVertex3f(0, 0, 0); glTexCoord2f(1.0f, 0.0f); glVertex3f(0, 0, size.z); glTexCoord2f(0.0f, 0.0f); glVertex3f( size.x, 0, size.z); glTexCoord2f(0.0f, 1.0f); glVertex3f( size.x, 0,0); glEnd(); // Bind the TOP texture of the sky map to the TOP side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[BOTTOM]); /* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); */ // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the TOP Side glTexCoord2f(0.0f, 1.0f); glVertex3f( size.x, size.y, 0); glTexCoord2f(0.0f, 0.0f); glVertex3f( size.x, size.y, size.z); glTexCoord2f(1.0f, 0.0f); glVertex3f(0, size.y, size.z); glTexCoord2f(1.0f, 1.0f); glVertex3f(0, size.y, 0); glEnd(); // Bind the LEFT texture of the sky map to the LEFT side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[LEFT]); /* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); */ // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the LEFT Side glTexCoord2f(1.0f, 0.0f); glVertex3f(0, size.y, 0); glTexCoord2f(0.0f, 0.0f); glVertex3f(0, size.y, size.z); glTexCoord2f(0.0f, 1.0f); glVertex3f(0, 0, size.z); glTexCoord2f(1.0f, 1.0f); glVertex3f(0, 0,0); glEnd(); // Bind the RIGHT texture of the sky map to the RIGHT side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[RIGHT]); /* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); */ // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the RIGHT Side glTexCoord2f(0.0f, 1.0f); glVertex3f( size.x, 0, 0); glTexCoord2f(1.0f, 1.0f); glVertex3f( size.x, 0, size.z); glTexCoord2f(1.0f, 0.0f); glVertex3f( size.x, size.y, size.z); glTexCoord2f(0.0f, 0.0f); glVertex3f( size.x, size.y, 0); glEnd(); //glPopAttrib(); glEndList(); //end of flipped list /* End of skybox display list */ /* Skybox shadow display lists */ this->drawlistShadow = glGenLists(1); glNewList(this->drawlistShadow, GL_COMPILE); // Bind the BACK texture of the sky map to the BACK side of the cube glBindTexture(GL_TEXTURE_2D, g_Textures[BACK]); glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the BACK Side glVertex3f( size.x, 0, 0); glVertex3f( size.x, size.y, 0); glVertex3f(0, size.y, 0); glVertex3f(0, 0, 0); glEnd(); // Bind the FRONT texture of the sky map to the FRONT side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[FRONT]); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the FRONT Side glVertex3f(0, 0, size.z); glVertex3f(0, size.y, size.z); glVertex3f( size.x, size.y, size.z); glVertex3f( size.x, 0, size.z); glEnd(); // Bind the BOTTOM texture of the sky map to the BOTTOM side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[BOTTOM]); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the BOTTOM Side glVertex3f(0, 0, 0); glVertex3f(0, 0, size.z); glVertex3f( size.x, 0, size.z); glVertex3f( size.x, 0,0); glEnd(); // Bind the TOP texture of the sky map to the TOP side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[TOP]); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the TOP Side glVertex3f( size.x, size.y, 0); glVertex3f( size.x, size.y, size.z); glVertex3f(0, size.y, size.z); glVertex3f(0, size.y, 0); glEnd(); // Bind the LEFT texture of the sky map to the LEFT side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[LEFT]); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the LEFT Side glVertex3f(0, size.y, 0); glVertex3f(0, size.y, size.z); glVertex3f(0, 0, size.z); glVertex3f(0, 0,0); glEnd(); // Bind the RIGHT texture of the sky map to the RIGHT side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[RIGHT]); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the RIGHT Side glVertex3f( size.x, 0, 0); glVertex3f( size.x, 0, size.z); glVertex3f( size.x, size.y, size.z); glVertex3f( size.x, size.y, 0); glEnd(); //glPopAttrib(); glEndList(); /* End of skybox display list shadow */ /* Create skybox display list FLIPPED */ this->drawlistShadow2 = glGenLists(1); glNewList(this->drawlistShadow2, GL_COMPILE); // Bind the BACK texture of the sky map to the BACK side of the cube glBindTexture(GL_TEXTURE_2D, g_Textures[BACK]); glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the BACK Side glVertex3f( size.x, 0, 0); glVertex3f( size.x, size.y, 0); glVertex3f(0, size.y, 0); glVertex3f(0, 0, 0); glEnd(); // Bind the FRONT texture of the sky map to the FRONT side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[FRONT]); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the FRONT Side glVertex3f(0, 0, size.z); glVertex3f(0, size.y, size.z); glVertex3f( size.x, size.y, size.z); glVertex3f( size.x, 0, size.z); glEnd(); // Bind the BOTTOM texture of the sky map to the BOTTOM side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[TOP]); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the BOTTOM Side glVertex3f(0, 0, 0); glVertex3f(0, 0, size.z); glVertex3f( size.x, 0, size.z); glVertex3f( size.x, 0,0); glEnd(); // Bind the TOP texture of the sky map to the TOP side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[BOTTOM]); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the TOP Side glVertex3f( size.x, size.y, 0); glVertex3f( size.x, size.y, size.z); glVertex3f(0, size.y, size.z); glVertex3f(0, size.y, 0); glEnd(); // Bind the LEFT texture of the sky map to the LEFT side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[LEFT]); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the LEFT Side glVertex3f(0, size.y, 0); glVertex3f(0, size.y, size.z); glVertex3f(0, 0, size.z); glVertex3f(0, 0,0); glEnd(); // Bind the RIGHT texture of the sky map to the RIGHT side of the box glBindTexture(GL_TEXTURE_2D, g_Textures[RIGHT]); // Start drawing the side as a QUAD glBegin(GL_QUADS); // Assign the texture coordinates and vertices for the RIGHT Side glVertex3f( size.x, 0, 0); glVertex3f( size.x, 0, size.z); glVertex3f( size.x, size.y, size.z); glVertex3f( size.x, size.y, 0); glEnd(); //glPopAttrib(); glEndList(); //end of flipped shadow list gConsole->LogSuccessText(LString("Skybox '%s' succesfully created!", skyBoxTexFolderName)); this->inUse = true; return true; } void Skybox::setPosition(const Math::Vector3 &pos) { mv_pos = Math::Vector3((pos.x - size.x) * 0.5f, (pos.y - size.y) * 0.5f, (pos.z - size.z) * 0.5f); } void Skybox::Render(void) { if(!inUse) return; //glEnable(GL_CULL_FACE); glPushMatrix(); glTranslatef(mv_pos.x, mv_pos.y, mv_pos.z); glCallList(this->drawlist); glPopMatrix(); } void Skybox::RenderFlip(void) { if(!inUse) return; glPushMatrix(); glTranslatef(mv_pos.x, mv_pos.y, mv_pos.z); glCallList(this->drawlist2); glPopMatrix(); } void Skybox::RenderShadow(void) { if(!inUse) return; //glEnable(GL_CULL_FACE); glPushMatrix(); glTranslatef(mv_pos.x, mv_pos.y, mv_pos.z); glCallList(this->drawlistShadow); glPopMatrix(); } void Skybox::RenderFlipShadow(void) { if(!inUse) return; glPushMatrix(); glTranslatef(mv_pos.x, mv_pos.y, mv_pos.z); glCallList(this->drawlistShadow2); glPopMatrix(); } /* ====================================================================== LENS FLARE TEXTURE OBJECT ====================================================================== */ LensFlareTexObj::LensFlareTexObj(void) { this->pos = Math::Vector3(0, 0, 0); bigGlowTexture = 0; starTexture = 0; glowTexture = 0; haloTexture = 0; } LensFlareTexObj::LensFlareTexObj(char* bigGlow, char* star, char* glow, char* halo, float srcScale, float scale, float maxDistance, bool infinite, float sunLumino, float glowSunLumino) { this->pos = Math::Vector3(0, 0, 0); GLuint width, height; gConsole->LogInfo(LString("Lens flare init started...")); strcpy(bigGlowAddress, bigGlow); strcpy(starAddress, star); strcpy(glowAddress, glow); strcpy(haloAddress, halo); LoadTexture(bigGlow, &bigGlowTexture, bigGlowTexture, true, width, height, true, true); LoadTexture(star, &starTexture, starTexture, true, width, height, true, true); LoadTexture(glow, &glowTexture, glowTexture, true, width, height, true, true); LoadTexture(halo, &haloTexture, haloTexture, true, width, height, true, true); this->scale = scale; this->srcScale = srcScale; this->maxDistance = maxDistance; this->infinite = infinite; this->sunLumino = sunLumino; this->glowSunLumino = glowSunLumino; this->touchedLumino = sunLumino*glowSunLumino; gConsole->LogSuccessText(LString("Lens flare object succesfully created!")); } void LensFlareTexObj::Load(char* bigGlow, char* star, char* glow, char* halo, float srcScale, float scale, float maxDistance, bool infinite, float sunLumino, float glowSunLumino) { GLuint width, height; gConsole->LogInfo(LString("Lens flare init started...")); strcpy(bigGlowAddress, bigGlow); strcpy(starAddress, star); strcpy(glowAddress, glow); strcpy(haloAddress, halo); LoadTexture(bigGlow, &bigGlowTexture, bigGlowTexture, true, width, height, true, true); LoadTexture(star, &starTexture, starTexture, true, width, height, true, true); LoadTexture(glow, &glowTexture, glowTexture, true, width, height, true, true); LoadTexture(halo, &haloTexture, haloTexture, true, width, height, true, true); this->scale = scale; this->srcScale = srcScale; this->maxDistance = maxDistance; this->infinite = infinite; this->sunLumino = sunLumino; this->glowSunLumino = glowSunLumino; this->touchedLumino = sunLumino*glowSunLumino; gConsole->LogSuccessText(LString("Lens flare object succesfully created!")); } LensFlareTexObj::~LensFlareTexObj(void) { this->Free(); } void LensFlareTexObj::Free(void) { if(glIsTexture(bigGlowTexture)) { glDeleteTextures(1, &bigGlowTexture); } if(glIsTexture(starTexture)) { glDeleteTextures(1, &starTexture); } if(glIsTexture(glowTexture)) { glDeleteTextures(1, &glowTexture); } if(glIsTexture(haloTexture)) { glDeleteTextures(1, &haloTexture); } gConsole->LogSuccessText(LString("Lens flare Data succesfully released!")); } void LensFlareTexObj::useTexture(GLuint &texture) { glBindTexture(GL_TEXTURE_2D, texture); } bool LensFlareTexObj::LoadFromFile(char* file, const Math::Vector3 &pos) { this->pos = pos; gConsole->LogInfo(LString("%s lens flare is loading...", file)); std::ifstream fin; char strb[128]; char bigGlow[256], star[256], glow[256], halo[256]; float srcScale, scale, maxDistance, sunLumino, glowSunLumino; bool infinite = false; int tempInfinite; fin.open(file); if(fin.fail()) { gConsole->LogError(LString("%s lens flare failed to load!", file)); return false; } fin>>strb>>bigGlow; fin>>strb>>star; fin>>strb>>glow; fin>>strb>>halo; fin>>strb>>srcScale; fin>>strb>>scale; fin>>strb>>maxDistance; fin>>strb>>tempInfinite; fin>>strb>>sunLumino; fin>>strb>>glowSunLumino; fin.close(); if(tempInfinite == 1) { infinite = true; } gConsole->LogSuccessText(LString("%s lens flare loaded successfully", file)); return true; } }
31.937604
138
0.703587
havokentity
5ff9bf0b84bb5ff286261824a8340d93d731fd43
1,063
hpp
C++
Control_movement/gimbal/Src/Imu.hpp
PhilosopheAM/21_Fall_project_gabbishSorting
15ef612d9e483ad72f9e37953875a7303f94b38e
[ "MIT" ]
1
2021-12-31T09:27:00.000Z
2021-12-31T09:27:00.000Z
Control_movement/gimbal/Src/Imu.hpp
PhilosopheAM/21_Fall_project_gabbishSorting
15ef612d9e483ad72f9e37953875a7303f94b38e
[ "MIT" ]
null
null
null
Control_movement/gimbal/Src/Imu.hpp
PhilosopheAM/21_Fall_project_gabbishSorting
15ef612d9e483ad72f9e37953875a7303f94b38e
[ "MIT" ]
1
2021-12-22T03:34:04.000Z
2021-12-22T03:34:04.000Z
#ifndef IMU_HPP #define IMU_HPP #include "bsp_imu.h" #include "RobotEngine.hpp" class Imu : public SensorEntity { private: float m_YawRaw; float m_Yaw; float m_Pitch; float m_Roll; float m_WX; float m_WY; float m_WZ; float m_ZeroYaw; uint8_t m_FrameBuffer[64]; uint8_t m_BufferQueue[256]; uint8_t m_BufferIndex; uint8_t m_Front; uint8_t m_Rear; uint8_t m_ImuId; static uint8_t ImuCount; uint32_t LastMileStone; float freq; float real_freq; void ResolvePacket(); void HandlePacket(); public: Imu(); uint8_t GetImuId(){ return m_ImuId; } virtual void Init(); virtual void Update(); void Enqueue(uint8_t _data); void Enqueue(uint8_t* _pData, uint32_t _len); float YawRaw(){ return m_YawRaw; } float Yaw(){ return m_Yaw; } float Pitch(){ return m_Pitch; } float Roll(){ return m_Roll; } float WX(){ return m_WX; } float WY(){ return m_WY; } float WZ(){ return m_WZ; } void SetYawZero(){ m_ZeroYaw = m_YawRaw; } }; #endif
19.327273
49
0.648166
PhilosopheAM
dfd650ea0d737a754f9fbd0dd3fc1401d6610eec
2,177
cpp
C++
src/timer.cpp
narfg/gbemulator
4f911e50df966a79177b458f6f618f02d940e88c
[ "MIT" ]
3
2019-11-19T18:47:57.000Z
2019-11-24T12:45:36.000Z
src/timer.cpp
narfg/gbemulator
4f911e50df966a79177b458f6f618f02d940e88c
[ "MIT" ]
null
null
null
src/timer.cpp
narfg/gbemulator
4f911e50df966a79177b458f6f618f02d940e88c
[ "MIT" ]
null
null
null
#include "timer.h" Timer::Timer(uint8_t* ram): ram_(ram), div_tick_(0), tima_tick_(0) { } void Timer::tick() { // Game Boy clock frequency is 4 * 1024 * 1024 = 4194304 Hz div_tick_++; // On overflow (happens at 16384 Hz) if (div_tick_ == 0x00) { // Increment DIV ram_[0xFF04]++; } // TIMA uint8_t timer_enabled = ram_[0xFF07] & 0x04; if (timer_enabled) { uint16_t divider = 0; switch (ram_[0xFF07] & 0x03) { case 0x00: divider = 1024; break; case 0x01: divider = 16; break; case 0x02: divider = 64; break; case 0x03: divider = 256; break; } tima_tick_++; if (tima_tick_ % divider == 0) { tima_tick_ = 0; ram_[0xFF05]++; // Overflow if (ram_[0xFF05] == 0x00) { // Set TIMA to TMA ram_[0xFF05] = ram_[0xFF06]; // Request timer interrupt ram_[0xFF0F] |= (1 << 2); } } } } void Timer::tick4() { // Game Boy clock frequency is 4 * 1024 * 1024 = 4194304 Hz div_tick_ += 4; // On overflow (happens at 16384 Hz) if (div_tick_ == 0x00) { // Increment DIV ram_[0xFF04]++; } // TIMA uint8_t timer_enabled = ram_[0xFF07] & 0x04; if (timer_enabled) { uint16_t divider = 0; switch (ram_[0xFF07] & 0x03) { case 0x00: divider = 1024; break; case 0x01: divider = 16; break; case 0x02: divider = 64; break; case 0x03: divider = 256; break; } tima_tick_ += 4; if (tima_tick_ % divider == 0) { tima_tick_ = 0; ram_[0xFF05]++; // Overflow if (ram_[0xFF05] == 0x00) { // Set TIMA to TMA ram_[0xFF05] = ram_[0xFF06]; // Request timer interrupt ram_[0xFF0F] |= (1 << 2); } } } }
22.677083
63
0.439136
narfg
dfd6b522e5fe200349cfbfee506350f1accf450e
439
cpp
C++
old/AtCoder/abc075/B.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
7
2018-04-14T14:55:51.000Z
2022-01-31T10:49:49.000Z
old/AtCoder/abc075/B.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
5
2018-04-14T14:28:49.000Z
2019-05-11T02:22:10.000Z
old/AtCoder/abc075/B.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
null
null
null
#include "adjacent_loop.hpp" #include "string.hpp" #include "vector.hpp" int main() { int h(in), w(in); Vector<String> s(h, in); for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { if (s[i][j] == '#') { continue; } s[i][j] = '0'; for (auto k : AdjacentLoop<8>(i, j, h, w)) { if (s[k.get<0>()][k.get<1>()] == '#') { ++s[i][j]; } } } } s.output(); }
19.086957
50
0.396355
not522
dfdaadb1f936fdf7f0ca4d99a06279adce426195
8,891
cpp
C++
libcaf_core/src/detail/parse.cpp
jsiwek/actor-framework
06cd2836f4671725cb7eaa22b3cc115687520fc1
[ "BSL-1.0", "BSD-3-Clause" ]
4
2019-05-03T05:38:15.000Z
2020-08-25T15:23:19.000Z
libcaf_core/src/detail/parse.cpp
jsiwek/actor-framework
06cd2836f4671725cb7eaa22b3cc115687520fc1
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
libcaf_core/src/detail/parse.cpp
jsiwek/actor-framework
06cd2836f4671725cb7eaa22b3cc115687520fc1
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2019 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "caf/detail/parse.hpp" #include "caf/detail/config_consumer.hpp" #include "caf/detail/consumer.hpp" #include "caf/detail/parser/chars.hpp" #include "caf/detail/parser/read_bool.hpp" #include "caf/detail/parser/read_config.hpp" #include "caf/detail/parser/read_floating_point.hpp" #include "caf/detail/parser/read_ipv4_address.hpp" #include "caf/detail/parser/read_ipv6_address.hpp" #include "caf/detail/parser/read_signed_integer.hpp" #include "caf/detail/parser/read_string.hpp" #include "caf/detail/parser/read_timespan.hpp" #include "caf/detail/parser/read_unsigned_integer.hpp" #include "caf/detail/parser/read_uri.hpp" #include "caf/detail/print.hpp" #include "caf/error.hpp" #include "caf/ipv4_address.hpp" #include "caf/ipv4_endpoint.hpp" #include "caf/ipv4_subnet.hpp" #include "caf/ipv6_address.hpp" #include "caf/ipv6_endpoint.hpp" #include "caf/ipv6_subnet.hpp" #include "caf/uri_builder.hpp" #define PARSE_IMPL(type, parser_name) \ void parse(string_parser_state& ps, type& x) { \ parser::read_##parser_name(ps, make_consumer(x)); \ } namespace caf::detail { void parse(string_parser_state& ps, literal x) { CAF_ASSERT(!x.str.empty()); if (ps.current() != x.str[0]) { ps.code = pec::unexpected_character; return; } auto c = ps.next(); for (auto i = x.str.begin() + 1; i != x.str.end(); ++i) { if (c != *i) { ps.code = pec::unexpected_character; return; } c = ps.next(); } ps.code = ps.at_end() ? pec::success : pec::trailing_character; } void parse(string_parser_state& ps, time_unit& x) { if (ps.at_end()) { ps.code = pec::unexpected_eof; return; } switch (ps.current()) { case '\0': ps.code = pec::unexpected_eof; return; case 'h': x = time_unit::hours; break; case 's': x = time_unit::seconds; break; case 'u': if (ps.next() == 's') { x = time_unit::microseconds; break; } ps.code = ps.at_end() ? pec::unexpected_eof : pec::unexpected_character; return; case 'n': if (ps.next() == 's') { x = time_unit::nanoseconds; break; } ps.code = ps.at_end() ? pec::unexpected_eof : pec::unexpected_character; return; case 'm': switch (ps.next()) { case '\0': ps.code = pec::unexpected_eof; return; case 's': x = time_unit::milliseconds; break; case 'i': if (ps.next() == 'n') { x = time_unit::minutes; break; } ps.code = ps.at_end() ? pec::unexpected_eof : pec::unexpected_character; return; default: ps.code = pec::unexpected_character; return; } break; default: ps.code = pec::unexpected_character; } ps.next(); ps.code = ps.at_end() ? pec::success : pec::trailing_character; } PARSE_IMPL(bool, bool) PARSE_IMPL(int8_t, signed_integer) PARSE_IMPL(int16_t, signed_integer) PARSE_IMPL(int32_t, signed_integer) PARSE_IMPL(int64_t, signed_integer) PARSE_IMPL(uint8_t, unsigned_integer) PARSE_IMPL(uint16_t, unsigned_integer) PARSE_IMPL(uint32_t, unsigned_integer) PARSE_IMPL(uint64_t, unsigned_integer) PARSE_IMPL(float, floating_point) PARSE_IMPL(double, floating_point) PARSE_IMPL(long double, floating_point) void parse(string_parser_state& ps, uri& x) { uri_builder builder; if (ps.consume('<')) { parser::read_uri(ps, builder); if (ps.code > pec::trailing_character) return; if (!ps.consume('>')) { ps.code = pec::unexpected_character; return; } } else { parser::read_uri(ps, builder); } if (ps.code <= pec::trailing_character) x = builder.make(); } void parse(string_parser_state& ps, config_value& x) { ps.skip_whitespaces(); if (ps.at_end()) { ps.code = pec::unexpected_eof; return; } // Safe the string as fallback. string_view str{ps.i, ps.e}; // Dispatch to parser. detail::config_value_consumer f; parser::read_config_value(ps, f); if (ps.code <= pec::trailing_character) x = std::move(f.result); } PARSE_IMPL(ipv4_address, ipv4_address) void parse(string_parser_state& ps, ipv4_subnet& x) { ipv4_address addr; uint8_t prefix_length; parse_sequence(ps, addr, literal{{"/"}}, prefix_length); if (ps.code <= pec::trailing_character) { if (prefix_length > 32) { ps.code = pec::integer_overflow; return; } x = ipv4_subnet{addr, prefix_length}; } } void parse(string_parser_state& ps, ipv4_endpoint& x) { ipv4_address addr; uint16_t port; parse_sequence(ps, addr, literal{{":"}}, port); if (ps.code <= pec::trailing_character) x = ipv4_endpoint{addr, port}; } PARSE_IMPL(ipv6_address, ipv6_address) void parse(string_parser_state& ps, ipv6_subnet& x) { // TODO: this algorithm is currently not one-pass. The reason we need to // check whether the input is a valid ipv4_subnet first is that "1.2.3.0" is // a valid IPv6 address, but "1.2.3.0/16" results in the wrong subnet when // blindly reading the address as an IPv6 address. auto nested = ps; ipv4_subnet v4_subnet; parse(nested, v4_subnet); if (nested.code <= pec::trailing_character) { ps.i = nested.i; ps.code = nested.code; ps.line = nested.line; ps.column = nested.column; x = ipv6_subnet{v4_subnet}; return; } ipv6_address addr; uint8_t prefix_length; parse_sequence(ps, addr, literal{{"/"}}, prefix_length); if (ps.code <= pec::trailing_character) { if (prefix_length > 128) { ps.code = pec::integer_overflow; return; } x = ipv6_subnet{addr, prefix_length}; } } void parse(string_parser_state& ps, ipv6_endpoint& x) { ipv6_address addr; uint16_t port; if (ps.consume('[')) { parse_sequence(ps, addr, literal{{"]:"}}, port); } else { ipv4_address v4_addr; parse_sequence(ps, v4_addr, literal{{":"}}, port); if (ps.code <= pec::trailing_character) addr = ipv6_address{v4_addr}; } if (ps.code <= pec::trailing_character) x = ipv6_endpoint{addr, port}; } void parse(string_parser_state& ps, std::string& x) { ps.skip_whitespaces(); if (ps.current() == '"') { parser::read_string(ps, make_consumer(x)); return; } for (auto c = ps.current(); c != '\0'; c = ps.next()) x += c; while (!x.empty() && isspace(x.back())) x.pop_back(); ps.code = pec::success; } void parse_element(string_parser_state& ps, std::string& x, const char* char_blacklist) { ps.skip_whitespaces(); if (ps.current() == '"') { parser::read_string(ps, make_consumer(x)); return; } auto is_legal = [=](char c) { return c != '\0' && strchr(char_blacklist, c) == nullptr; }; for (auto c = ps.current(); is_legal(c); c = ps.next()) x += c; while (!x.empty() && isspace(x.back())) x.pop_back(); ps.code = ps.at_end() ? pec::success : pec::trailing_character; } // -- convenience functions ---------------------------------------------------- error parse_result(const string_parser_state& ps, string_view input) { if (ps.code == pec::success) return {}; auto msg = to_string(ps.code); msg += " at line "; print(msg, ps.line); msg += ", column "; print(msg, ps.column); msg += " for input "; print_escaped(msg, input); return make_error(ps.code, std::move(msg)); } } // namespace caf::detail
30.138983
80
0.570352
jsiwek
dfdf5ef1b67c7d6657aa8c7cb8339214d84fc674
580
hpp
C++
include/ndtree/relations/dimension.hpp
gnzlbg/htree
30e29145b6b0b0f4d1106f05376df94bd58cadc9
[ "BSL-1.0" ]
15
2015-09-02T13:25:55.000Z
2021-04-23T04:02:19.000Z
include/ndtree/relations/dimension.hpp
gnzlbg/htree
30e29145b6b0b0f4d1106f05376df94bd58cadc9
[ "BSL-1.0" ]
1
2015-11-18T03:50:18.000Z
2016-06-16T08:34:01.000Z
include/ndtree/relations/dimension.hpp
gnzlbg/htree
30e29145b6b0b0f4d1106f05376df94bd58cadc9
[ "BSL-1.0" ]
4
2016-05-20T18:57:27.000Z
2019-03-17T09:18:13.000Z
#pragma once /// \file dimension.hpp #include <ndtree/types.hpp> #include <ndtree/utility/assert.hpp> #include <ndtree/utility/ranges.hpp> namespace ndtree { inline namespace v1 { /// Range of spatial dimensions: [0, nd) /// /// TODO: make constexpr when view::iota is constexpr auto dimensions(uint_t nd) noexcept { return view::iota(0_u, nd); } NDTREE_STATIC_ASSERT_RANDOM_ACCESS_SIZED_RANGE(dimensions(1)); NDTREE_STATIC_ASSERT_RANDOM_ACCESS_SIZED_RANGE(dimensions(2)); NDTREE_STATIC_ASSERT_RANDOM_ACCESS_SIZED_RANGE(dimensions(3)); } // namespace v1 } // namespace ndtree
30.526316
67
0.775862
gnzlbg
dfdf9f59b62e76f3f7d1cada6dfafdd84c5f61b4
1,701
cpp
C++
src/gradientFill.cpp
da11an/tidyxl
44d47d667f0c86f2f8cea1216b821ae6a9da26c1
[ "MIT" ]
201
2016-09-15T23:04:37.000Z
2022-03-24T06:24:42.000Z
src/gradientFill.cpp
da11an/tidyxl
44d47d667f0c86f2f8cea1216b821ae6a9da26c1
[ "MIT" ]
60
2016-09-15T16:53:27.000Z
2022-03-31T20:57:16.000Z
src/gradientFill.cpp
da11an/tidyxl
44d47d667f0c86f2f8cea1216b821ae6a9da26c1
[ "MIT" ]
13
2017-01-02T22:04:55.000Z
2022-03-24T06:24:05.000Z
#include <Rcpp.h> #include "rapidxml.h" #include "gradientFill.h" #include "xlsxstyles.h" #include "color.h" using namespace Rcpp; gradientFill::gradientFill( rapidxml::xml_node<>* gradientFill, xlsxstyles* styles ) { // Initialize variables type_ = NA_STRING; degree_ = NA_INTEGER; left_ = NA_REAL; right_ = NA_REAL; top_ = NA_REAL; bottom_ = NA_REAL; if (gradientFill != NULL) { rapidxml::xml_attribute<>* type = gradientFill->first_attribute("type"); if (type != NULL) { type_ = type->value(); degree_ = NA_INTEGER; rapidxml::xml_attribute<>* left = gradientFill->first_attribute("left"); rapidxml::xml_attribute<>* right = gradientFill->first_attribute("right"); rapidxml::xml_attribute<>* top = gradientFill->first_attribute("top"); rapidxml::xml_attribute<>* bottom = gradientFill->first_attribute("bottom"); left_ = (left != NULL) ? strtod(left->value(), NULL) : 0; right_ = (right != NULL) ? strtod(right->value(), NULL) : 0; top_ = (top != NULL) ? strtod(top->value(), NULL) : 0; bottom_ = (bottom != NULL) ? strtod(bottom->value(), NULL) : 0; } else { type_ = NA_STRING; left_ = NA_REAL; right_ = NA_REAL; top_ = NA_REAL; bottom_ = NA_REAL; rapidxml::xml_attribute<>* degree = gradientFill->first_attribute("degree"); if (degree != NULL) { degree_ = strtol(degree->value(), NULL, 10); } else { degree_ = 0; } } rapidxml::xml_node<>* stop1 = gradientFill->first_node("stop"); stop1_ = gradientStop(stop1, styles); rapidxml::xml_node<>* stop2 = stop1->next_sibling(); stop2_ = gradientStop(stop2, styles); } }
33.352941
96
0.62963
da11an
dfe63303d58054b1b5169bb242b675ab720f9c39
1,145
cpp
C++
Stp/Base/System/LibraryPosix.cpp
markazmierczak/Polonite
240f099cafc5c38dc1ae1cc6fc5773e13f65e9de
[ "MIT" ]
1
2019-07-11T12:47:52.000Z
2019-07-11T12:47:52.000Z
Stp/Base/System/LibraryPosix.cpp
Polonite/Polonite
240f099cafc5c38dc1ae1cc6fc5773e13f65e9de
[ "MIT" ]
null
null
null
Stp/Base/System/LibraryPosix.cpp
Polonite/Polonite
240f099cafc5c38dc1ae1cc6fc5773e13f65e9de
[ "MIT" ]
1
2019-07-11T12:47:53.000Z
2019-07-11T12:47:53.000Z
// Copyright 2017 Polonite Authors. All rights reserved. // Distributed under MIT license that can be found in the LICENSE file. #include "Base/System/Library.h" #include "Base/Containers/Join.h" #include "Base/FileSystem/FilePath.h" #include "Base/Text/FormatMany.h" #include <dlfcn.h> namespace stp { static inline StringSpan DynamicLinkerErrorMessage() { return makeSpanFromNullTerminated(dlerror()); } void LibraryLoadError::formatImpl(TextWriter& out) const { out << message_; } NativeLibrary Library::TryLoadNative(const FilePathChar* path, LibraryLoadError* out_error) { void* dl = dlopen(path, RTLD_LAZY); if (!dl) { if (out_error) out_error->message_ = DynamicLinkerErrorMessage(); } return dl; } void Library::UnloadNative(NativeLibrary library) { int ret = dlclose(library); if (ret != 0) ASSERT(false, "failed to unload library: {}", DynamicLinkerErrorMessage()); } void* Library::TryResolveNative(NativeLibrary library, const char* name) { return dlsym(library, name); } String Library::DecorateName(StringSpan name) { return ConcatMany<String>("lib", name, ".so"); } } // namespace stp
24.891304
93
0.731004
markazmierczak
dfe7eca43a001a690c7d066899a2e34841f67702
11,500
cpp
C++
OneCodeTeam/C++ app automates Outlook (CppAutomateOutlook)/[C++]-C++ app automates Outlook (CppAutomateOutlook)/C++/CppAutomateOutlook/Solution2.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
2
2022-01-21T01:40:58.000Z
2022-01-21T01:41:10.000Z
OneCodeTeam/C++ app automates Outlook (CppAutomateOutlook)/[C++]-C++ app automates Outlook (CppAutomateOutlook)/C++/CppAutomateOutlook/Solution2.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
1
2022-03-15T04:21:41.000Z
2022-03-15T04:21:41.000Z
OneCodeTeam/C++ app automates Outlook (CppAutomateOutlook)/[C++]-C++ app automates Outlook (CppAutomateOutlook)/C++/CppAutomateOutlook/Solution2.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
null
null
null
/****************************** Module Header ******************************\ * Module Name: Solution2.cpp * Project: CppAutomateOutlook * Copyright (c) Microsoft Corporation. * * The code in Solution2.h/cpp demontrates the use of C/C++ and the COM APIs * to automate Outlook. The raw automation is much more difficult, but it is * sometimes necessary to avoid the overhead with MFC, or problems with * #import. Basically, you work with such APIs as CoCreateInstance(), and COM * interfaces such as IDispatch and IUnknown. * * This source is subject to the Microsoft Public License. * See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. * All other rights reserved. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. \***************************************************************************/ #pragma region Includes #include <stdio.h> #include <windows.h> #include "Solution2.h" #pragma endregion // // FUNCTION: AutoWrap(int, VARIANT*, IDispatch*, LPOLESTR, int,...) // // PURPOSE: Automation helper function. It simplifies most of the low-level // details involved with using IDispatch directly. Feel free to use it // in your own implementations. One caveat is that if you pass multiple // parameters, they need to be passed in reverse-order. // // PARAMETERS: // * autoType - Could be one of these values: DISPATCH_PROPERTYGET, // DISPATCH_PROPERTYPUT, DISPATCH_PROPERTYPUTREF, DISPATCH_METHOD. // * pvResult - Holds the return value in a VARIANT. // * pDisp - The IDispatch interface. // * ptName - The property/method name exposed by the interface. // * cArgs - The count of the arguments. // // RETURN VALUE: An HRESULT value indicating whether the function succeeds // or not. // // EXAMPLE: // AutoWrap(DISPATCH_METHOD, NULL, pDisp, L"call", 2, parm[1], parm[0]); // HRESULT AutoWrap(int autoType, VARIANT *pvResult, IDispatch *pDisp, LPOLESTR ptName, int cArgs...) { // Begin variable-argument list va_list marker; va_start(marker, cArgs); if (!pDisp) { _putws(L"NULL IDispatch passed to AutoWrap()"); _exit(0); return E_INVALIDARG; } // Variables used DISPPARAMS dp = { NULL, NULL, 0, 0 }; DISPID dispidNamed = DISPID_PROPERTYPUT; DISPID dispID; HRESULT hr; // Get DISPID for name passed hr = pDisp->GetIDsOfNames(IID_NULL, &ptName, 1, LOCALE_USER_DEFAULT, &dispID); if (FAILED(hr)) { wprintf(L"IDispatch::GetIDsOfNames(\"%s\") failed w/err 0x%08lx\n", ptName, hr); _exit(0); return hr; } // Allocate memory for arguments VARIANT *pArgs = new VARIANT[cArgs + 1]; // Extract arguments... for(int i=0; i < cArgs; i++) { pArgs[i] = va_arg(marker, VARIANT); } // Build DISPPARAMS dp.cArgs = cArgs; dp.rgvarg = pArgs; // Handle special-case for property-puts if (autoType & DISPATCH_PROPERTYPUT) { dp.cNamedArgs = 1; dp.rgdispidNamedArgs = &dispidNamed; } // Make the call hr = pDisp->Invoke(dispID, IID_NULL, LOCALE_SYSTEM_DEFAULT, autoType, &dp, pvResult, NULL, NULL); if (FAILED(hr)) { wprintf(L"IDispatch::Invoke(\"%s\"=%08lx) failed w/err 0x%08lx\n", ptName, dispID, hr); _exit(0); return hr; } // End variable-argument section va_end(marker); delete[] pArgs; return hr; } DWORD WINAPI AutomateOutlookByCOMAPI(LPVOID lpParam) { // Initializes the COM library on the current thread and identifies // the concurrency model as single-thread apartment (STA). // [-or-] CoInitialize(NULL); // [-or-] CoCreateInstance(NULL); CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); // Define vtMissing for optional parameters in some calls. VARIANT vtMissing; vtMissing.vt = VT_EMPTY; ///////////////////////////////////////////////////////////////////////// // Start Microsoft Outlook and log on with your profile. // // Get CLSID of the server CLSID clsid; HRESULT hr; // Option 1. Get CLSID from ProgID using CLSIDFromProgID. LPCOLESTR progID = L"Outlook.Application"; hr = CLSIDFromProgID(progID, &clsid); if (FAILED(hr)) { wprintf(L"CLSIDFromProgID(\"%s\") failed w/err 0x%08lx\n", progID, hr); return 1; } // Option 2. Build the CLSID directly. /*const IID CLSID_Application = {0x0006F03A,0x0000,0x0000,{0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46}}; clsid = CLSID_Application;*/ // Start the server and get the IDispatch interface IDispatch *pOutlookApp = NULL; hr = CoCreateInstance( // [-or-] CoCreateInstanceEx, CoGetObject clsid, // CLSID of the server NULL, CLSCTX_LOCAL_SERVER, // Outlook.Application is a local server IID_IDispatch, // Query the IDispatch interface (void **)&pOutlookApp); // Output if (FAILED(hr)) { wprintf(L"Outlook is not registered properly w/err 0x%08lx\n", hr); return 1; } _putws(L"Outlook.Application is started"); _putws(L"User logs on ..."); // Get the namespace and the logon. // pNS = pOutlookApp->GetNamespace("MAPI") IDispatch *pNS = NULL; { VARIANT x; x.vt = VT_BSTR; x.bstrVal = SysAllocString(L"MAPI"); VARIANT result; VariantInit(&result); AutoWrap(DISPATCH_METHOD, &result, pOutlookApp, L"GetNamespace", 1, x); pNS = result.pdispVal; VariantClear(&x); } // Log on by using a dialog box to choose the profile. // pNS->Logon(vtMissing, vtMissing, true, true) { VARIANT vtShowDialog; vtShowDialog.vt = VT_BOOL; vtShowDialog.boolVal = VARIANT_TRUE; VARIANT vtNewSession; vtNewSession.vt = VT_BOOL; vtNewSession.boolVal = VARIANT_TRUE; AutoWrap(DISPATCH_METHOD, NULL, pNS, L"Logon", 4, vtNewSession, vtShowDialog, vtMissing, vtMissing); } // Alternative logon method that uses a specific profile. // If you use this logon method, change the profile name to an // appropriate value. The second parameter of Logon is the password (if // any) associated with the profile. This parameter exists only for // backwards compatibility and for security reasons, and it is not // recommended for use. // pNS->Logon(L"YourValidProfile", vtMissing, false, true); //{ // VARIANT vtProfile; // vtProfile.vt = VT_BSTR; // vtProfile.bstrVal = SysAllocString(L"YourValidProfile"); // VARIANT vtShowDialog; // vtShowDialog.vt = VT_BOOL; // vtShowDialog.boolVal = VARIANT_TRUE; // VARIANT vtNewSession; // vtNewSession.vt = VT_BOOL; // vtNewSession.boolVal = VARIANT_TRUE; // AutoWrap(DISPATCH_METHOD, NULL, pNS, L"Logon", 4, vtNewSession, // vtShowDialog, vtMissing, vtProfile); // VariantClear(&vtProfile); //} wprintf(L"Press ENTER to continue when Outlook is ready."); getwchar(); ///////////////////////////////////////////////////////////////////////// // Enumerate the contact items. // _putws(L"Enumerate the contact items"); // pCtFolder = pNS->GetDefaultFolder(Outlook::olFolderContacts); IDispatch *pCtFolder = NULL; { VARIANT x; x.vt = VT_I4; x.lVal = 10; // Outlook::olFolderContacts VARIANT result; VariantInit(&result); AutoWrap(DISPATCH_METHOD, &result, pNS, L"GetDefaultFolder", 1, x); pCtFolder = result.pdispVal; } // pCts = pCtFolder->Items; IDispatch *pCts = NULL; { VARIANT result; VariantInit(&result); AutoWrap(DISPATCH_PROPERTYGET, &result, pCtFolder, L"Items", 0); pCts = result.pdispVal; } // Enumerate the contact items. // Get the count of items. long lCtsCount; { VARIANT result; VariantInit(&result); AutoWrap(DISPATCH_PROPERTYGET, &result, pCts, L"Count", 0); lCtsCount = result.lVal; } for (long i = 1; i <= lCtsCount; i++) { // Get the item at i // pItem = pCts->Item(i); IDispatch *pItem = NULL; { VARIANT x; x.vt = VT_I4; x.lVal = i; VARIANT result; VariantInit(&result); AutoWrap(DISPATCH_PROPERTYGET, &result, pCts, L"Item", 1, x); pItem = result.pdispVal; } // Attemp to QI _ContactItem const IID IID_ContactItem = {0x00063021,0x0000,0x0000,{0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46}}; IDispatch *pCt = NULL; { hr = pItem->QueryInterface(IID_ContactItem, (void **)&pCt); if (SUCCEEDED(hr)) { // pCt->Email1Address VARIANT vtAddress; VariantInit(&vtAddress); AutoWrap(DISPATCH_PROPERTYGET, &vtAddress, pCt, L"Email1Address", 0); wprintf(L"%s\n", (LPCWSTR)vtAddress.bstrVal); VariantClear(&vtAddress); pCt->Release(); } } // Attemp to QI _DistListItem const IID IID_DistListItem = {0x00063081,0x0000,0x0000,{0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46}}; IDispatch *pDL = NULL; { hr = pItem->QueryInterface(IID_DistListItem, (void **)&pDL); if (SUCCEEDED(hr)) { // pDL->DLName VARIANT vtDLName; VariantInit(&vtDLName); AutoWrap(DISPATCH_PROPERTYGET, &vtDLName, pDL, L"DLName", 0); wprintf(L"%s\n", (LPCWSTR)vtDLName.bstrVal); VariantClear(&vtDLName); pDL->Release(); } } // Release the interface. pItem->Release(); } ///////////////////////////////////////////////////////////////////////// // Create and send a new mail item. // _putws(L"Create and send a new mail item"); // pMail = pOutlookApp->CreateItem(Outlook::olMailItem); IDispatch *pMail = NULL; { VARIANT x; x.vt = VT_I4; x.lVal = 0; // Outlook::olMailItem VARIANT result; VariantInit(&result); AutoWrap(DISPATCH_METHOD, &result, pOutlookApp, L"CreateItem", 1, x); pMail = result.pdispVal; } // Set the properties of the email. // pMail->Subject = _bstr_t(L"Feedback of All-In-One Code Framework"); { VARIANT x; x.vt = VT_BSTR; x.bstrVal = SysAllocString(L"Feedback of All-In-One Code Framework"); AutoWrap(DISPATCH_PROPERTYPUT, NULL, pMail, L"Subject", 1, x); VariantClear(&x); } // pMail->To = _bstr_t(L"codefxf@microsoft.com"); { VARIANT x; x.vt = VT_BSTR; x.bstrVal = SysAllocString(L"codefxf@microsoft.com"); AutoWrap(DISPATCH_PROPERTYPUT, NULL, pMail, L"To", 1, x); VariantClear(&x); } // pMail->HTMLBody = _bstr_t(L"<b>Feedback:</b><br />"); { VARIANT x; x.vt = VT_BSTR; x.bstrVal = SysAllocString(L"<b>Feedback:</b><br />"); AutoWrap(DISPATCH_PROPERTYPUT, NULL, pMail, L"HTMLBody", 1, x); VariantClear(&x); } // Displays a new Inspector object for the item and allows users to click // on the Send button to send the mail manually. // Modal = true makes the Inspector window modal. // pMail->Display(true); { VARIANT vtModal; vtModal.vt = VT_BOOL; vtModal.boolVal = VARIANT_TRUE; AutoWrap(DISPATCH_METHOD, NULL, pMail, L"Display", 1, vtModal); } // [-or-] // Automatically send the mail without a new Inspector window. // pMail->Send(); /*AutoWrap(DISPATCH_METHOD, NULL, pMail, L"Send", 0);*/ ///////////////////////////////////////////////////////////////////////// // User logs off and quits Outlook. // _putws(L"Log off and quit the Outlook application"); // pNS->Logoff() AutoWrap(DISPATCH_METHOD, NULL, pNS, L"Logoff", 0); // pOutlookApp->Quit() AutoWrap(DISPATCH_METHOD, NULL, pOutlookApp, L"Quit", 0); ///////////////////////////////////////////////////////////////////// // Release the COM objects. // if (pMail != NULL) { pMail->Release(); } if (pCts != NULL) { pCts->Release(); } if (pCtFolder != NULL) { pCtFolder->Release(); } if (pNS != NULL) { pNS->Release(); } if (pOutlookApp != NULL) { pOutlookApp->Release(); } // Uninitialize COM for this thread. CoUninitialize(); return 0; }
26.136364
79
0.652957
zzgchina888
dfecca42c5fdb93c2256bf3b9c567f85b950a173
10,101
cxx
C++
Modules/Numerics/HighDimensionalOptimizers/test/itkRegistrationParameterScalesFromJacobianTest.cxx
CapeDrew/DCMTK-ITK
440bf8ed100445396912cfd0aa72f36d4cdefe0c
[ "Apache-2.0" ]
2
2015-06-19T07:18:36.000Z
2019-04-18T07:28:23.000Z
Modules/Numerics/HighDimensionalOptimizers/test/itkRegistrationParameterScalesFromJacobianTest.cxx
CapeDrew/DCMTK-ITK
440bf8ed100445396912cfd0aa72f36d4cdefe0c
[ "Apache-2.0" ]
null
null
null
Modules/Numerics/HighDimensionalOptimizers/test/itkRegistrationParameterScalesFromJacobianTest.cxx
CapeDrew/DCMTK-ITK
440bf8ed100445396912cfd0aa72f36d4cdefe0c
[ "Apache-2.0" ]
2
2017-05-02T07:18:49.000Z
2020-04-30T01:37:35.000Z
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 "itkRegistrationParameterScalesFromJacobian.h" #include "itkObjectToObjectMetric.h" #include "itkImage.h" #include "itkAffineTransform.h" #include "itkTranslationTransform.h" /** * \class RegistrationParameterScalesFromJacobianTestMetric for test. * Create a simple metric to use for testing here. */ template< class TFixedImage,class TMovingImage,class TVirtualImage = TFixedImage > class ITK_EXPORT RegistrationParameterScalesFromJacobianTestMetric: public itk::ObjectToObjectMetric { public: /** Standard class typedefs. */ typedef RegistrationParameterScalesFromJacobianTestMetric Self; typedef itk::ObjectToObjectMetric Superclass; typedef itk::SmartPointer< Self > Pointer; typedef itk::SmartPointer< const Self > ConstPointer; typedef typename Superclass::MeasureType MeasureType; typedef typename Superclass::DerivativeType DerivativeType; typedef typename Superclass::ParametersType ParametersType; typedef typename Superclass::ParametersValueType ParametersValueType; itkTypeMacro(RegistrationParameterScalesFromJacobianTestMetric, ObjectToObjectMetric); itkNewMacro(Self); // Pure virtual functions that all Metrics must provide unsigned int GetNumberOfParameters() const { return 5; } MeasureType GetValue() const { return 1.0; } void GetValueAndDerivative( MeasureType & value, DerivativeType & derivative ) const { value = 1.0; derivative.Fill(0.0); } unsigned int GetNumberOfLocalParameters() const { return 0; } bool HasLocalSupport() const { return false; } void UpdateTransformParameters( DerivativeType &, ParametersValueType ) {} const ParametersType & GetParameters() const { return m_Parameters; } void Initialize(void) throw ( itk::ExceptionObject ) {} ParametersType m_Parameters; // Image related types typedef TFixedImage FixedImageType; typedef TMovingImage MovingImageType; typedef TVirtualImage VirtualImageType; typedef typename FixedImageType::ConstPointer FixedImageConstPointer; typedef typename MovingImageType::ConstPointer MovingImageConstPointer; typedef typename VirtualImageType::Pointer VirtualImagePointer; /* Set/get images */ /** Connect the Fixed Image. */ itkSetConstObjectMacro(FixedImage, FixedImageType); /** Get the Fixed Image. */ itkGetConstObjectMacro(FixedImage, FixedImageType); /** Connect the Moving Image. */ itkSetConstObjectMacro(MovingImage, MovingImageType); /** Get the Moving Image. */ itkGetConstObjectMacro(MovingImage, MovingImageType); /** Set all virtual domain image */ itkSetObjectMacro(VirtualDomainImage, VirtualImageType); /** Get the virtual domain image */ itkGetObjectMacro(VirtualDomainImage, VirtualImageType); /* Image dimension accessors */ itkStaticConstMacro(FixedImageDimension, itk::SizeValueType, ::itk::GetImageDimension<FixedImageType>::ImageDimension); itkStaticConstMacro(MovingImageDimension, itk::SizeValueType, ::itk::GetImageDimension<MovingImageType>::ImageDimension); itkStaticConstMacro(VirtualImageDimension, itk::SizeValueType, ::itk::GetImageDimension<VirtualImageType>::ImageDimension); /** Type of the Transform Base classes */ typedef ::itk::Transform<CoordinateRepresentationType, itkGetStaticConstMacro( MovingImageDimension ), itkGetStaticConstMacro( VirtualImageDimension )> MovingTransformType; typedef ::itk::Transform<CoordinateRepresentationType, itkGetStaticConstMacro( FixedImageDimension ), itkGetStaticConstMacro( VirtualImageDimension )> FixedTransformType; typedef typename FixedTransformType::Pointer FixedTransformPointer; typedef typename MovingTransformType::Pointer MovingTransformPointer; typedef typename FixedTransformType::JacobianType FixedTransformJacobianType; typedef typename MovingTransformType::JacobianType MovingTransformJacobianType; /** Connect the fixed transform. */ itkSetObjectMacro(FixedTransform, FixedTransformType); /** Get a pointer to the fixed transform. */ itkGetConstObjectMacro(FixedTransform, FixedTransformType); /** Connect the moving transform. */ itkSetObjectMacro(MovingTransform, MovingTransformType); /** Get a pointer to the moving transform. */ itkGetConstObjectMacro(MovingTransform, MovingTransformType); private: FixedImageConstPointer m_FixedImage; MovingImageConstPointer m_MovingImage; VirtualImagePointer m_VirtualDomainImage; FixedTransformPointer m_FixedTransform; MovingTransformPointer m_MovingTransform; RegistrationParameterScalesFromJacobianTestMetric() {} ~RegistrationParameterScalesFromJacobianTestMetric() {} }; /** */ int itkRegistrationParameterScalesFromJacobianTest(int , char* []) { // Image begins const itk::SizeValueType ImageDimension = 2; typedef double PixelType; // Image Types typedef itk::Image<PixelType,ImageDimension> FixedImageType; typedef itk::Image<PixelType,ImageDimension> MovingImageType; typedef itk::Image<PixelType,ImageDimension> VirtualImageType; FixedImageType::Pointer fixedImage = FixedImageType::New(); MovingImageType::Pointer movingImage = MovingImageType::New(); VirtualImageType::Pointer virtualImage = fixedImage; MovingImageType::SizeType size; size.Fill(100); movingImage->SetRegions( size ); fixedImage->SetRegions( size ); // Image done // Transform begins typedef itk::AffineTransform<double, ImageDimension> MovingTransformType; MovingTransformType::Pointer movingTransform = MovingTransformType::New(); movingTransform->SetIdentity(); typedef itk::TranslationTransform<double, ImageDimension> FixedTransformType; FixedTransformType::Pointer fixedTransform = FixedTransformType::New(); fixedTransform->SetIdentity(); // Transform done // Metric begins typedef RegistrationParameterScalesFromJacobianTestMetric <FixedImageType, MovingImageType> MetricType; MetricType::Pointer metric = MetricType::New(); metric->SetVirtualDomainImage( virtualImage ); metric->SetFixedImage( fixedImage ); metric->SetMovingImage( movingImage ); metric->SetFixedTransform( fixedTransform ); metric->SetMovingTransform( movingTransform ); // Metric done // Scales for the affine transform from transform jacobians typedef itk::RegistrationParameterScalesFromJacobian< MetricType > RegistrationParameterScalesFromJacobianType; RegistrationParameterScalesFromJacobianType::Pointer jacobianScaleEstimator = RegistrationParameterScalesFromJacobianType::New(); jacobianScaleEstimator->SetMetric(metric); jacobianScaleEstimator->SetTransformForward(true); //by default jacobianScaleEstimator->Print( std::cout ); RegistrationParameterScalesFromJacobianType::ScalesType jacobianScales( movingTransform->GetNumberOfParameters()); jacobianScaleEstimator->EstimateScales(jacobianScales); std::cout << "Jacobian scales for the affine transform = " << jacobianScales << std::endl; // Check the correctness RegistrationParameterScalesFromJacobianType::ScalesType theoreticalJacobianScales( movingTransform->GetNumberOfParameters()); VirtualImageType::PointType upperPoint; virtualImage->TransformIndexToPhysicalPoint(virtualImage-> GetLargestPossibleRegion().GetUpperIndex(), upperPoint); itk::SizeValueType param = 0; for (itk::SizeValueType row = 0; row < ImageDimension; row++) { for (itk::SizeValueType col = 0; col < ImageDimension; col++) { //average of squares of consecutive integers [0,1,...,n] // = n*(n+1)*(2n+1)/6 / (n+1) = n*(2n+1)/6 theoreticalJacobianScales[param++] = (upperPoint[col] * (2*upperPoint[col]+1)) / 6.0; } } for (itk::SizeValueType row = 0; row < ImageDimension; row++) { theoreticalJacobianScales[param++] = 1; } bool jacobianPass = true; for (itk::SizeValueType p = 0; p < jacobianScales.GetSize(); p++) { //due to random sampling, it is not exactly equal if (vcl_abs((jacobianScales[p] - theoreticalJacobianScales[p]) / theoreticalJacobianScales[p]) > 0.2 ) { jacobianPass = false; break; } } bool nonUniformForJacobian = false; for (itk::SizeValueType p = 1; p < jacobianScales.GetSize(); p++) { if (jacobianScales[p] != jacobianScales[0]) { nonUniformForJacobian = true; break; } } // Check done std::cout << std::endl; if (!jacobianPass) { std::cout << "Failed: the jacobian scales for the affine transform are not correct." << std::endl; } else { std::cout << "Passed: the jacobian scales for the affine transform are correct." << std::endl; } if (!nonUniformForJacobian) { std::cout << "Error: the jacobian scales for an affine transform are equal for all parameters." << std::endl; } if (jacobianPass && nonUniformForJacobian) { std::cout << "Test passed" << std::endl; return EXIT_SUCCESS; } else { std::cout << "Test failed" << std::endl; return EXIT_FAILURE; } }
35.69258
113
0.717751
CapeDrew
dfed579475fe5b8d59f6690b9a0dc956a4215e7e
3,792
cpp
C++
app/src/main/cpp/audio/FileDataSource.cpp
codecameo/fast-mixer
5f9403a61239984ce23b8250159a1e1913beda06
[ "MIT" ]
1
2021-01-20T18:27:02.000Z
2021-01-20T18:27:02.000Z
app/src/main/cpp/audio/FileDataSource.cpp
codecameo/fast-mixer
5f9403a61239984ce23b8250159a1e1913beda06
[ "MIT" ]
null
null
null
app/src/main/cpp/audio/FileDataSource.cpp
codecameo/fast-mixer
5f9403a61239984ce23b8250159a1e1913beda06
[ "MIT" ]
null
null
null
/* * Copyright (C) 2018 The Android Open Source Project * * 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 "../logging_macros.h" #include <oboe/Oboe.h> #include <regex> #include <string> #include <sys/stat.h> #include "FileDataSource.h" #include "FFMpegExtractor.h" #include <regex> constexpr int kMaxCompressionRatio { 12 }; FileDataSource::FileDataSource ( unique_ptr<float[]> data, size_t size, const AudioProperties properties) : mBuffer(move(data)), mBufferSize(size), mProperties(properties) { for (int i = 0; i < mBufferSize; i++) { if (abs(mBuffer[i]) > mMaxSampleValue) { mMaxSampleValue = abs(mBuffer[i]); } } } FileDataSource* FileDataSource::newFromCompressedFile( const char *filename, const AudioProperties targetProperties) { string filenameStr(filename); FILE* fl = fopen(filenameStr.c_str(), "r"); if (!fl) { LOGE("Failed to open asset %s", filenameStr.c_str()); fclose(fl); return nullptr; } fclose(fl); off_t assetSize = getSizeOfFile(filenameStr.c_str()); // Allocate memory to store the decompressed audio. We don't know the exact // size of the decoded data until after decoding so we make an assumption about the // maximum compression ratio and the decoded sample format (float for FFmpeg, int16 for NDK). auto ffmpegExtractor = FFMpegExtractor(filenameStr, targetProperties); long maximumDataSizeInBytes = kMaxCompressionRatio * assetSize * sizeof(float); auto decodedData = new uint8_t [maximumDataSizeInBytes]; int64_t bytesDecoded = ffmpegExtractor.decode(decodedData); if (bytesDecoded <= 0) { return nullptr; } auto numSamples = bytesDecoded / sizeof(float); // Now we know the exact number of samples we can create a float array to hold the audio data auto outputBuffer = make_unique<float[]>(numSamples); memcpy(outputBuffer.get(), decodedData, (size_t)bytesDecoded); delete [] decodedData; return new FileDataSource(move(outputBuffer), numSamples, move(targetProperties)); } unique_ptr<buffer_data> FileDataSource::readData(size_t countPoints) { int channelCount = mProperties.channelCount; size_t samplesToHandle; if (countPoints * channelCount > mBufferSize) { samplesToHandle = (int) (mBufferSize / channelCount); } else { samplesToHandle = countPoints; } int ptsDistance = (int) (mBufferSize / (samplesToHandle * channelCount)); auto selectedSamples = new float [samplesToHandle]; for (int i = 0; i < samplesToHandle; i++) { float maxValue = 0; for (int j = i * ptsDistance; j < (i + 1) * ptsDistance; j += channelCount) { if (abs(mBuffer[j]) > maxValue) { maxValue = abs(mBuffer[j]); } } selectedSamples[i] = maxValue; } buffer_data buff = { .ptr = selectedSamples, .countPoints = samplesToHandle }; return make_unique<buffer_data>(buff); } void FileDataSource::setPlayHead(int64_t playHead) { mPlayHead = playHead; } int64_t FileDataSource::getPlayHead() { return mPlayHead; }
30.580645
97
0.663766
codecameo
dfefdfedbac7251dda93e256ce370a9ea96d275d
7,553
cpp
C++
trans_str_menu_snap.cpp
rsuzaki/FireAlpacaTranslation
529dc597f057da3f6abce63aa44dc92fc0cc3f0c
[ "MIT" ]
2
2021-08-16T20:56:54.000Z
2021-08-20T07:16:42.000Z
trans_str_menu_snap.cpp
rsuzaki/FireAlpacaTranslation
529dc597f057da3f6abce63aa44dc92fc0cc3f0c
[ "MIT" ]
null
null
null
trans_str_menu_snap.cpp
rsuzaki/FireAlpacaTranslation
529dc597f057da3f6abce63aa44dc92fc0cc3f0c
[ "MIT" ]
1
2021-10-17T14:07:35.000Z
2021-10-17T14:07:35.000Z
/* -*- coding: utf-8 -*- マルチバイト */ #if defined(_MSC_VER) #pragma execution_character_set("utf-8") #endif #include "trans.h" #include "trans_str_menu_snap.h" /////////////////////////////////////////////////////////////////////////// // - スナップメニューで使用される文字列 // - A string used in the snap menu. /////////////////////////////////////////////////////////////////////////// QString Trans_StrMenuSnap( int idx ) { CTranslationManager* man = &Trans(); if (man->TranslateJapanese()) { if (idx == 0) return QObject::tr("スナップ(&N)"); // Snap if (idx == 1) return QObject::tr("オフ(&O)"); // Off if (idx == 2) return QObject::tr("並行(&P)"); // Parallel if (idx == 3) return QObject::tr("十字(&C)"); // Crisscross if (idx == 4) return QObject::tr("消失点(&V)"); // Vanish if (idx == 5) return QObject::tr("集中線(&R)"); // Radial if (idx == 6) return QObject::tr("同心円(&E)"); // Circle if (idx == 7) return QObject::tr("曲線(&K)"); // Curve if (idx == 8) return QObject::tr("スナップの保存(&S)..."); // Save Snap if (idx == 9) return QObject::tr("曲線の描画"); // Draw Curve if (idx == 10) return QObject::tr("曲線の描画 (入り抜き)"); // Draw Curve (Fade In/Out) if (idx == 12) return QObject::tr("3Dパース"); // 3D Perspective if (idx == 13) return QObject::tr("3Dパースを追加"); // Add 3D Perspective } if (man->TranslateChineseSimp()) { if (idx == 0) return QObject::tr("捕捉(&N)"); // Snap if (idx == 1) return QObject::tr("关闭(&O)"); // Off if (idx == 2) return QObject::tr("平行(&P)"); // Parallel if (idx == 3) return QObject::tr("十字(&C)"); // Crisscross if (idx == 4) return QObject::tr("消失点(&V)"); // Vanish if (idx == 5) return QObject::tr("放射线(&R)"); // Radial if (idx == 6) return QObject::tr("同心圆"); // Circle if (idx == 7) return QObject::tr("曲线"); // Curve if (idx == 8) return QObject::tr("保存现有辅助(&S)..."); // Save Snap if (idx == 9) return QObject::tr("曲线描绘"); // Draw Curve if (idx == 10) return QObject::tr("曲线描绘(淡入淡出)"); // Draw Curve (Fade In/Out) } if (man->TranslateChineseTrad()) { if (idx == 0) return QObject::tr("輔助(&N)"); // Snap if (idx == 1) return QObject::tr("關掉(&O)"); // Off if (idx == 2) return QObject::tr("並行(&P)"); // Parallel if (idx == 3) return QObject::tr("十字(&C)"); // Crisscross if (idx == 4) return QObject::tr("消失分(&V)"); // Vanish if (idx == 5) return QObject::tr("放射線(&R)"); // Radial if (idx == 6) return QObject::tr("同心圓"); // Circle if (idx == 7) return QObject::tr("曲線"); // Curve if (idx == 8) return QObject::tr("儲存輔助(&S)..."); // Save Snap if (idx == 9) return QObject::tr("繪製曲線"); // Draw Curve if (idx == 10) return QObject::tr("繪製曲線(起筆/收筆)"); // Draw Curve (Fade In/Out) } if (man->TranslateKorean()) { if (idx == 0) return QObject::tr("스냅(&N)"); // Snap if (idx == 1) return QObject::tr("Off(&O)"); // Off if (idx == 2) return QObject::tr("병행(&P)"); // Parallel if (idx == 3) return QObject::tr("십자(&C)"); // Crisscross if (idx == 4) return QObject::tr("소실점(&V)"); // Vanish if (idx == 5) return QObject::tr("집중선(&R)"); // Radial if (idx == 6) return QObject::tr("원형 스냅"); // Circle if (idx == 7) return QObject::tr("곡선 스냅"); // Curve if (idx == 8) return QObject::tr("스냅의 저장(&S)..."); // Save Snap if (idx == 9) return QObject::tr("곡선 그리기"); // Draw Curve if (idx == 10) return QObject::tr("곡선 그리기(페이드 인/아웃)"); // Draw Curve (Fade In/Out) } if (man->TranslatePortugues()) { if (idx == 0) return QObject::tr("Ajustar(&N)"); // Snap if (idx == 1) return QObject::tr("Desativar(&O)"); // Off if (idx == 2) return QObject::tr("Paralelo(&P)"); // Parallel if (idx == 3) return QObject::tr("Entrecruzado(&C)"); // Crisscross if (idx == 4) return QObject::tr("Ponto de Fuga(&V)"); // Vanish if (idx == 5) return QObject::tr("Radial(&R)"); // Radial if (idx == 6) return QObject::tr("Ajuste de círculo"); // Circle if (idx == 7) return QObject::tr("Ajuste de curva"); // Curve if (idx == 8) return QObject::tr("Gravar instantâneo(&S)..."); // Save Snap } if (man->TranslateSpanish()) { if (idx == 0) return QObject::tr("Ajustar(&N)"); // Snap if (idx == 1) return QObject::tr("Desativar(&O)"); // Off if (idx == 2) return QObject::tr("Paralelo(&P)"); // Parallel if (idx == 3) return QObject::tr("Entrecruzado(&C)"); // Crisscross if (idx == 4) return QObject::tr("Ponto de Fuga(&V)"); // Vanish if (idx == 5) return QObject::tr("Radial(&R)"); // Radial if (idx == 6) return QObject::tr("Ajuste de círculo(&E)"); // Circle if (idx == 7) return QObject::tr("Ajuste de curva(&K)"); // Curve if (idx == 8) return QObject::tr("Gravar instantâneo(&S)..."); // Save Snap } if (man->TranslateGerman()) { if (idx == 0) return QObject::tr("Schnappfunktion(&N)"); // Snap if (idx == 1) return QObject::tr("Aus(&O)"); // Off if (idx == 2) return QObject::tr("Gleichlaufend(&P)"); // Parallel if (idx == 3) return QObject::tr("Kreuzschraffur(&C)"); // Crisscross if (idx == 4) return QObject::tr("Fluchtpunkt(&V)"); // Vanish if (idx == 5) return QObject::tr("Strahlenförmig(&R)"); // Radial if (idx == 6) return QObject::tr("Snap, Kreis"); // Circle if (idx == 7) return QObject::tr("Snap, Kurve"); // Curve if (idx == 8) return QObject::tr("Snap speichern(&S)..."); // Save Snap } if (man->TranslateFrench()) { if (idx == 0) return QObject::tr("Aligner(&N)"); // Snap if (idx == 1) return QObject::tr("Inactif(&O)"); // Off if (idx == 2) return QObject::tr("Parallèle(&P)"); // Parallel if (idx == 3) return QObject::tr("Axes(&C)"); // Crisscross if (idx == 4) return QObject::tr("Point de fuite(&V)"); // Vanish if (idx == 5) return QObject::tr("Radial(&R)"); // Radial if (idx == 6) return QObject::tr("Magnétisme cercle"); // Circle if (idx == 7) return QObject::tr("Magnétisme courbe"); // Curve if (idx == 8) return QObject::tr("Enregistrement magnétisme(&S)..."); // Save Snap } if (man->TranslateRussian()) { if (idx == 0) return QObject::tr("Линейка(&N)"); // Snap if (idx == 1) return QObject::tr("Отключить(&O)"); // Off if (idx == 2) return QObject::tr("Параллельный(&P)"); // Parallel if (idx == 3) return QObject::tr("Перекрестный(&C)"); // Crisscross if (idx == 4) return QObject::tr("Исправление перспективы(&V)"); // Vanish if (idx == 5) return QObject::tr("Радиальный(&R)"); // Radial if (idx == 6) return QObject::tr("Круговая привязка"); // Circle if (idx == 7) return QObject::tr("Привязка к кривой"); // Curve if (idx == 8) return QObject::tr("Сохранить привязку(&S)..."); // Save Snap } if (man->TranslateHindi()) { } if (man->TranslateBengali()) { } if (man->TranslatePolish()) { } if (idx == 0) return QObject::tr("Snap(&N)"); if (idx == 1) return QObject::tr("Off(&O)"); if (idx == 2) return QObject::tr("Parallel(&P)"); if (idx == 3) return QObject::tr("Crisscross(&C)"); if (idx == 4) return QObject::tr("Vanishing Point(&V)"); if (idx == 5) return QObject::tr("Radial(&R)"); if (idx == 6) return QObject::tr("Circle(&E)"); if (idx == 7) return QObject::tr("Curve(&K)"); if (idx == 8) return QObject::tr("Save Snap(&S)..."); if (idx == 9) return QObject::tr("Draw Curve"); if (idx == 10) return QObject::tr("Draw Curve (Fade In/Out)"); if (idx == 12) return QObject::tr("3D Perspective"); if (idx == 13) return QObject::tr("Add 3D Perspective"); return ""; }
43.408046
86
0.554879
rsuzaki
dff4c277ebc23a04cfd9677c3070ce5d044e5524
1,803
hpp
C++
library/ATF/GUILD_BATTLE__CGuildBattleReservedSchedule.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/GUILD_BATTLE__CGuildBattleReservedSchedule.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/GUILD_BATTLE__CGuildBattleReservedSchedule.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <GUILD_BATTLE__CGuildBattleSchedule.hpp> #include <_worlddb_guild_battle_schedule_list.hpp> START_ATF_NAMESPACE namespace GUILD_BATTLE { struct CGuildBattleReservedSchedule { unsigned int m_uiScheduleListID; bool m_bDone; unsigned int m_uiCurScheduleInx; bool m_bUseField[23]; CGuildBattleSchedule *m_pkSchedule[23]; public: char Add(unsigned int dwStartTimeInx, unsigned int dwElapseTimeCnt, struct CGuildBattleSchedule** ppkSchedule); CGuildBattleReservedSchedule(unsigned int uiScheduleListID); void ctor_CGuildBattleReservedSchedule(unsigned int uiScheduleListID); bool CheckNextEvent(int iRet); bool CleanUpDanglingReservedSchedule(); bool Clear(unsigned int dwID); void Clear(); void ClearElapsedSchedule(); bool CopyUseTimeField(bool* pbField); void Flip(); unsigned int GetCurScheduleID(); unsigned int GetID(); bool IsDone(); char IsEmptyTime(unsigned int dwStartTimeInx, unsigned int dwElapseTimeCnt); bool Load(bool bToday, struct _worlddb_guild_battle_schedule_list* pkInfo); bool Loop(); bool Next(); void UpdateUseField(unsigned int dwStartTimeInx, unsigned int dwElapseTimeCnt); struct CGuildBattleSchedule* UpdateUseFlag(unsigned int dwID); ~CGuildBattleReservedSchedule(); void dtor_CGuildBattleReservedSchedule(); }; }; // end namespace GUILD_BATTLE END_ATF_NAMESPACE
40.977273
123
0.667221
lemkova
5f0173e0560cf546f6adf0f2389f52e443286399
2,053
hpp
C++
tests/functional/coherence/util/ConcurrentMapTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-01T21:38:30.000Z
2021-11-03T01:35:11.000Z
tests/functional/coherence/util/ConcurrentMapTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
1
2020-07-24T17:29:22.000Z
2020-07-24T18:29:04.000Z
tests/functional/coherence/util/ConcurrentMapTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-10T18:40:58.000Z
2022-02-18T01:23:40.000Z
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #include "cxxtest/TestSuite.h" #include "coherence/lang.ns" #include "coherence/net/NamedCache.hpp" #include "coherence/util/ConcurrentMap.hpp" #include "common/TestUtils.hpp" using coherence::net::NamedCache; using coherence::util::ConcurrentMap; /** * ConcurrentMap Test Suite. */ class ConcurrentMapTest : public CxxTest::TestSuite { public: /** * Test lock(). */ void testLock() { NamedCache::Handle hCache = ensureCleanCache("dist-lock"); String::View vsKey = "key"; bool f = hCache->lock(vsKey); TS_ASSERT(f == true); f = hCache->lock(vsKey); TS_ASSERT(f == true); f = hCache->unlock(vsKey); TS_ASSERT(f == true); } /** * Test lock() with timeout. */ void testLockTimeout() { NamedCache::Handle hCache = ensureCleanCache("dist-lock"); String::View vsKey = "key"; bool f = hCache->lock(vsKey, 1000L); TS_ASSERT(f == true); f = hCache->lock(vsKey, 1000L); TS_ASSERT(f == true); f = hCache->unlock(vsKey); TS_ASSERT(f == true); } /** * Test lock() with global lock. */ void testLockAll() { NamedCache::Handle hCache = ensureCleanCache("dist-lock"); try { hCache->lock(ConcurrentMap::getLockAll()); TS_ASSERT(false); } catch (...) { } try { hCache->lock(ConcurrentMap::getLockAll(), 1000L); TS_ASSERT(false); } catch (...) { } } };
22.811111
70
0.476376
chpatel3
5f03597167a31394156365fd4ce9b1ad969e7d70
19,004
hpp
C++
src/operations/blas3/gemm_no_local.hpp
sgeor255/sycl-blas
447219a01d24b132694d6743f67ba27b67c42369
[ "Apache-2.0" ]
null
null
null
src/operations/blas3/gemm_no_local.hpp
sgeor255/sycl-blas
447219a01d24b132694d6743f67ba27b67c42369
[ "Apache-2.0" ]
null
null
null
src/operations/blas3/gemm_no_local.hpp
sgeor255/sycl-blas
447219a01d24b132694d6743f67ba27b67c42369
[ "Apache-2.0" ]
null
null
null
/*************************************************************************** * @license * Copyright (C) Codeplay Software Limited * 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 * * For your convenience, a copy of the License has been included in this * repository. * * 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. * * SYCL-BLAS: BLAS implementation using SYCL * * @filename gemm_no_local.hpp * **************************************************************************/ #ifndef SYCL_BLAS_BLAS3_NO_LOCAL_GEMM_HPP #define SYCL_BLAS_BLAS3_NO_LOCAL_GEMM_HPP #include "gemm_common.hpp" namespace blas { /*! * @brief NoLocalGemmFactory is a template class whose instantiations provide * different implementations of the GEMM kernel where the is no * local memory available on the device. * * To use the function, each item of a kernel dispatched with an nd_range given * by NoLocalGemmFactory::get_nd_range() should call eval(). * * @tparam ClSize the size of the cache line of the architecture * This parameter has been reserved for further optimisation * (If the value passed in is smaller than the actual cache * line size, some values fetched will be wasted, which can * significantly reduce performance. It can be set to a * multiple of the physical cache line size. In this case, it * will significantly increase local memory usage, but * will result in fewer local barriers.) * @tparam TileType determines the size of the local, work group, and top * level tiles to use, see Tile * @tparam TransA iff true, matrix A will be transposed on the fly * @tparam TransB iff true, matrix B will be transposed on the fly * @tparam element_t type of matrix elements */ template <typename input_t, typename output_t, bool DoubleBuffer, bool NbcA, bool NbcB, int ClSize, typename tile_type, bool TransA, bool TransB, typename element_t, bool is_beta_zero> class Gemm<input_t, output_t, DoubleBuffer, NbcA, NbcB, ClSize, tile_type, TransA, TransB, element_t, is_beta_zero, static_cast<int>(gemm_memory_t::no_local), static_cast<int>(gemm_algorithm_t::standard)> { public: using value_t = element_t; using index_t = typename std::make_signed<typename input_t::index_t>::type; static constexpr int local_memory_size = 0; /*! @brief The number of rows processed by each work item */ static constexpr index_t item_rows = tile_type::item_rows; /*! @brief The number of cols processed by each work item */ static constexpr index_t item_cols = tile_type::item_cols; /*! @brief The number of work items in each row of work group */ static constexpr index_t wg_rows = tile_type::wg_rows; /*! @brief The number of work items in each column of work group */ static constexpr index_t wg_cols = tile_type::wg_cols; /*! @brief Number of rows within a work-group level tile */ static constexpr index_t block_rows = wg_rows * item_rows; /*! @brief Number of columns within a work-group level tile */ static constexpr index_t block_cols = wg_cols * item_cols; /*! @brief The size of tile processed by a work-group */ static constexpr index_t tile_size = block_rows * block_cols; /*! @brief A boolean parameter represents wheather or not matrix A is * transposed */ static constexpr bool trans_a = TransA; /*! @brief A boolean parameter represents wheather or not matrix B is * transposed */ static constexpr bool trans_b = TransB; static_assert(wg_cols * item_cols == item_rows * wg_rows, "Work group size should be a multiple " "of the number of rows in a block\n" " --- this is ensured iff: item_rows | wg_cols"); input_t a_; input_t b_; output_t c_; element_t alpha_; element_t beta_; index_t m_; index_t n_; index_t k_; index_t lda_; index_t ldb_; index_t ldc_; index_t batch_size_; SYCL_BLAS_INLINE Gemm(input_t A, input_t B, output_t C, element_t alpha, element_t beta, index_t batch_size) : a_(A), b_(B), c_(C), alpha_(alpha), beta_(beta), m_(a_.get_size_row()), n_(b_.get_size_col()), k_(a_.get_size_col()), lda_(a_.getSizeL()), ldb_(b_.getSizeL()), ldc_(c_.getSizeL()), batch_size_(batch_size) {} /*! * @brief Get the type of this NoLocalGemmFactory as a human readable string. */ static SYCL_BLAS_INLINE std::string get_type_string() noexcept { std::ostringstream str{}; str << "NoLocalGemmFactory<" << ClSize << ", " << tile_type::get_type_string() << ", " << type_string<value_t>::get_value() << ">"; return str.str(); } /*! *@brief gt_workgroup_cluster. This function is used to find the optimum *number of work_group required to execute each GEMM. * */ static SYCL_BLAS_INLINE index_t get_workgroup_cluster(index_t m, index_t n) noexcept { return (((m - 1) / (item_rows * wg_rows) + 1) * ((n - 1) / (item_cols * wg_cols) + 1)); } /*! *@brief get_num_workgroup_cluster. This function is used to extend the number *of work_group cluster, in order to make sure that atleast 4 gemm operations *is available per work group. The number 4 is used based on empirical *research. * */ static SYCL_BLAS_INLINE index_t get_num_workgroup_cluster( index_t m, index_t n, index_t compute_units) noexcept { constexpr index_t num_gemm_per_compute_units = 4; return ((num_gemm_per_compute_units * compute_units - 1) / get_workgroup_cluster(m, n) + 1); } static SYCL_BLAS_INLINE cl::sycl::nd_range<1> get_nd_range( index_t m, index_t n, index_t compute_units) noexcept { const cl::sycl::range<1> nwg( get_workgroup_cluster(m, n) * get_num_workgroup_cluster(m, n, compute_units)); const cl::sycl::range<1> wgs(wg_rows * wg_cols); return cl::sycl::nd_range<1>(nwg * wgs, wgs); } SYCL_BLAS_INLINE index_t get_size() const { return m_ * n_; } SYCL_BLAS_INLINE bool valid_thread(cl::sycl::nd_item<1> ndItem) const { return true; } SYCL_BLAS_INLINE void eval(cl::sycl::nd_item<1> id) noexcept { // The batch index that each workgroup should start working with const index_t wg_batch_id = id.get_group(0) / get_workgroup_cluster(m_, n_); // This will disable all workgroups that dont have any batch to work on if (wg_batch_id >= batch_size_) { return; } const index_t batch_stride = id.get_group_range(0) / get_workgroup_cluster(m_, n_); const index_t a_size = trans_a ? m_ * lda_ : k_ * lda_; const index_t b_size = trans_b ? ldb_ * k_ : n_ * ldb_; const index_t c_size = ldc_ * n_; auto orig_A = a_.get_pointer() + (wg_batch_id * a_size); auto orig_B = b_.get_pointer() + (wg_batch_id * b_size); auto orig_C = c_.get_pointer() + (wg_batch_id * c_size); const index_t number_of_block_per_row = ((m_ - 1) / block_rows) + 1; /* linear work group id The number of work-group required to executed each * batch efficiently*/ const index_t wg_id = id.get_group(0) % get_workgroup_cluster(m_, n_); /* linear work item id */ const index_t item_id = id.get_local_id(0); /* row tile id per work group */ const index_t tile_id_row = wg_id % number_of_block_per_row; /* column tile id per work group */ const index_t tile_id_col = wg_id / number_of_block_per_row; /* work item id per row */ const index_t local_item_id_row = item_id % wg_rows; /* work item id per column */ const index_t local_item_id_col = item_id / wg_rows; /* the start position of the tile-row per work group */ const index_t wg_row = tile_id_row * block_rows; /* the start position of the tile-column per work group */ const index_t wg_col = tile_id_col * block_cols; /* Exiting from any threads outside of the m and n boundary */ const bool out_of_range = ((local_item_id_row + wg_row >= m_) || (local_item_id_col + wg_col >= n_)); /* * The ma and na are used to adjust the start position of each work-item for * A, B and C matrices. */ const index_t dim_m_a_start = (local_item_id_row + wg_row); const index_t dim_n_b_start = (local_item_id_col + wg_col); /*! @brief Adjusting the start position of A, B , and C */ orig_A += dim_m_a_start * (trans_a ? lda_ : 1); orig_B += dim_n_b_start * (trans_b ? 1 : ldb_); orig_C += dim_m_a_start + (dim_n_b_start * ldc_); /*! * @brief is_internal_block_m and is_internal_block_n is used to distinguish * the internal block. Therefore, work items using these blocks dont need to * check for boundaries. */ const bool is_internal_block = (m_ - wg_row >= block_rows) && (n_ - wg_col >= block_cols); /* * The following lambdas: boundary_check_m, boundary_check_n, and * boundary_check_c are used to check the A, B , and C boundaries * respectively. */ const auto boundary_check_m = [&](index_t dim_m_a_start) { return dim_m_a_start < m_; }; const auto boundary_check_n = [&](index_t dim_n_b_start) { return dim_n_b_start < n_; }; const auto boundary_check_c = [&](index_t dim_m_c_start, index_t dim_n_c_start) { return (dim_m_c_start < m_ && dim_n_c_start < n_); }; // computing the next element for a and b; const index_t A_ptr_index = (trans_a ? lda_ : 1) * wg_rows; const index_t B_ptr_index = (trans_b ? 1 : ldb_) * wg_cols; /* temporary register array used to prefetch columns of A*/ value_t reg_a[item_rows]; /* temporary register used to prefetch elements of B*/ value_t reg_b[item_cols]; /* * computing the gemm panel */ if ((is_internal_block == true)) { compute_gemm_no_shared_pannel<false>( orig_A, orig_B, orig_C, a_size, b_size, c_size, a_.get_size_col(), k_, dim_m_a_start, dim_n_b_start, A_ptr_index, B_ptr_index, boundary_check_m, boundary_check_n, boundary_check_c, reg_a, reg_b, out_of_range, batch_stride, wg_batch_id, batch_size_, lda_, ldb_, ldc_, alpha_, beta_ #ifdef ARM_GPU , id #endif ); } else { compute_gemm_no_shared_pannel<true>( orig_A, orig_B, orig_C, a_size, b_size, c_size, a_.get_size_col(), k_, dim_m_a_start, dim_n_b_start, A_ptr_index, B_ptr_index, boundary_check_m, boundary_check_n, boundary_check_c, reg_a, reg_b, out_of_range, batch_stride, wg_batch_id, batch_size_, lda_, ldb_, ldc_, alpha_, beta_ #ifdef ARM_GPU , id #endif ); } } template <bool need_check_boundary, typename A_t, typename B_t, typename C_t, typename check_boundary_m_t, typename check_boundary_n_t, typename check_boundary_c_t> static void SYCL_BLAS_INLINE compute_gemm_no_shared_pannel( A_t orig_A, B_t orig_B, C_t orig_C, const index_t &a_size, const index_t &b_size, const index_t &c_size, index_t orig_k, index_t k, const index_t &dim_m_a_start, const index_t &dim_n_b_start, const index_t &A_ptr_index, const index_t &B_ptr_index, const check_boundary_m_t &boundary_check_m, const check_boundary_n_t &boundary_check_n, const check_boundary_c_t &boundary_check_c, element_t (&reg_a)[item_rows], element_t (&reg_b)[item_cols], const bool out_of_range, const index_t &batch_stride, const index_t &wg_batch_id, index_t batch_size, const index_t &lda, const index_t &ldb, const index_t &ldc, const element_t &alpha, const element_t &beta #ifdef ARM_GPU , cl::sycl::nd_item<1> id #endif ) noexcept { do { auto A = orig_A; auto B = orig_B; auto C = orig_C; /* 2D register array used to store the result C*/ value_t reg_res[item_rows][item_cols] = {}; while (k > 0) { /* * Loading a corresponding block of matrix A into reg_a */ load<item_rows, wg_rows, need_check_boundary>( A, reg_a, A_ptr_index, dim_m_a_start, boundary_check_m, out_of_range); #ifdef ARM_GPU id.barrier(cl::sycl::access::fence_space::local_space); #endif /* * Loading a corresponding block of matrix B into reg_b */ load<item_cols, wg_cols, need_check_boundary>( B, reg_b, B_ptr_index, dim_n_b_start, boundary_check_n, out_of_range); /* * Computing a the partial GEMM for the loaded block of reg_a andd * reg_b and adding the result into reg_res */ compute_block_gemm_no_shared(reg_a, reg_b, reg_res); /* * Moving forward to the next block */ --k; A = A + (trans_a ? 1 : lda); B = B + (trans_b ? ldb : 1); } /* * Storing the reg_res into C matrix */ store<need_check_boundary>(C, reg_res, alpha, beta, dim_m_a_start, dim_n_b_start, boundary_check_c, out_of_range, ldc); orig_A += (a_size * batch_stride); orig_B += (b_size * batch_stride); orig_C += (c_size * batch_stride); k = orig_k; // batch_size_ must be signed as the negative value has meaning here. batch_size -= batch_stride; } while (batch_size > wg_batch_id); } /*! * @brief binding the placeholder accessors to the SYCL command group * handler * @param h: SYCL command group handler. */ void bind(cl::sycl::handler &h) { a_.bind(h); b_.bind(h); c_.bind(h); } void adjust_access_displacement() { a_.adjust_access_displacement(); b_.adjust_access_displacement(); c_.adjust_access_displacement(); } private: /*! * @brief Following function load a block of row_items/col_items elements from * A/B matrix into reg_a/reg_b. * @tparam item_size it is the size of private register: either row_items or * column_item * @tparam next_element : is the stride to acces the next element of A or B * matrix. it is either wg_rows or wg_cols. * @tparam check_block: determined whether or not the requested block is * internal. false means no need to check the boundaries * @tparam pointerType: the type of the input matrix * @tparam check_boundary: the type of a function used for checking the * boundary for blocks of data located at the edge of the input matrix * @param ptr : the input matrix, either A or B. * @param reg[item_size] the private array containing the input block per * work-item: it is either reg_a or reg_b. * @param ld : the leading dimension of the input matrix. * @param index: the start position of the block of data to be loaded. * @param chk_boundary: an instance of the check_boundary function */ template <index_t item_size, index_t next_element, bool check_block, typename PointerType, typename check_boundary> static SYCL_BLAS_INLINE void load(PointerType ptr, element_t (&reg)[item_size], const index_t &ld, index_t index, const check_boundary &chk_boundary, const bool out_of_range) noexcept { if (out_of_range) { return; } #pragma unroll for (int i = 0; i < item_size; i++) { reg[i] = do_check<check_block>(chk_boundary(index)) ? ptr[0] : element_t(0); ptr += ld; index += next_element; } } /*! * @brief The following function compute the partial GEMM for the input block * reg_a and reg_b and add the result to the reg_res * @param reg_a temporary register array used to prefetch columns of A * @param reg_b temporary register used to prefetch elements of B * @param reg_res 2D register array used to store the result C */ static SYCL_BLAS_INLINE void compute_block_gemm_no_shared( element_t (&reg_a)[item_rows], element_t (&reg_b)[item_cols], element_t (&reg_res)[item_rows][item_cols]) noexcept { #pragma unroll for (int j = 0; j < item_cols; j++) { #pragma unroll for (int i = 0; i < item_rows; i++) { reg_res[i][j] = cl::sycl::mad(reg_a[i], reg_b[j], reg_res[i][j]); } } } /*! * @brief For each work itemThe following function store the computed block of * GEMM reg_res into output matrix C * @tparam check_block: determined whether or not the requested block is * internal. false means no need to check the boundaries * @tparam pointerType: the type of the matrix C * @tparam check_boundary: the type of a function used for checking the * boundary for blocks of data located at the edge of the input matrix * @param c: is the output matrix C * @param reg_res 2D register array used to store the result C * @param chk_boundary: an instance of the check_boundary function * @param ldc is the leading dimension of C * @param mc and nc are indices, used to check the boundary of C */ template <bool check_block, typename PointerType, typename check_boundary> static SYCL_BLAS_INLINE void store( PointerType C, element_t (&reg_res)[item_rows][item_cols], const element_t &alpha, const element_t &beta, const index_t &dim_m_c_start, const index_t &dim_n_c_start, const check_boundary &chk_boundary, const bool out_of_range, const index_t &ldc) noexcept { if (out_of_range) { return; } #pragma unroll for (int j = 0; j < item_cols; j++) { #pragma unroll for (int i = 0; i < item_rows; i++) { if (do_check<check_block>(chk_boundary(dim_m_c_start + i * wg_rows, dim_n_c_start + j * wg_cols))) { // when C is uninitialized the element of the C can be NaN, and Nan*0 // will be NaN if (is_beta_zero) { C[i * wg_rows] = alpha * reg_res[i][j]; } else { C[i * wg_rows] = alpha * reg_res[i][j] + beta * C[i * wg_rows]; } } } C = C + (wg_cols * ldc); } } }; // end class No Local GemmFactory } // namespace blas #endif // SYCL_BLAS_BLAS3_NO_LOCAL_GEMM_HPP
40.008421
80
0.649074
sgeor255
5f0e74fb949fa1970136511ea2b7939392215ceb
982
cpp
C++
codeforces/A - Mind the Gap/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/A - Mind the Gap/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/A - Mind the Gap/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Apr/29/2018 19:27 * solution_verdict: Accepted language: GNU C++14 * run_time: 15 ms memory_used: 3700 KB * problem: https://codeforces.com/contest/967/problem/A ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; int n,s,x,y,t[100005],now; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin>>n>>s; for(int i=1;i<=n;i++) { cin>>x>>y; t[i]=x*60+y; } t[n+1]=1e9; now=0; for(int i=1;i<=n+1;i++) { if(t[i]-now-1>=s) { cout<<now/60<<" "<<now%60<<endl; return 0; } now=t[i]+s+1; } return 0; }
29.757576
111
0.35336
kzvd4729
5f0ea5324c1a2156ae92ef6b40a94826fbb94ffd
451
cpp
C++
src/libs/utility/unit-test/runtime_assert_test.cpp
jdmclark/gorc
a03d6a38ab7684860c418dd3d2e77cbe6a6d9fc8
[ "Apache-2.0" ]
97
2015-02-24T05:09:24.000Z
2022-01-23T12:08:22.000Z
src/libs/utility/unit-test/runtime_assert_test.cpp
annnoo/gorc
1889b4de6380c30af6c58a8af60ecd9c816db91d
[ "Apache-2.0" ]
8
2015-03-27T23:03:23.000Z
2020-12-21T02:34:33.000Z
src/libs/utility/unit-test/runtime_assert_test.cpp
annnoo/gorc
1889b4de6380c30af6c58a8af60ecd9c816db91d
[ "Apache-2.0" ]
10
2016-03-24T14:32:50.000Z
2021-11-13T02:38:53.000Z
#include "test/test.hpp" #include "utility/runtime_assert.hpp" begin_suite(assert_test); test_case(assert_passes) { try { gorc::runtime_assert(true, "assert not thrown"); } catch(...) { assert_always("exception thrown"); } } test_case(assert_fails) { assert_throws(gorc::runtime_assert(false, "assert thrown"), std::runtime_error, "assert thrown"); } end_suite(assert_test);
18.791667
63
0.627494
jdmclark
5f1208d498c3a2777b3be89e9e8c1e3327fdc063
4,158
cpp
C++
app/interaction_service/core-algo/test/temp/random_graph_minimum_spanning_tree.cpp
Philippe-Guyard/XOptimizer
d09644eb6b92253b1d56ca2ab9c1be681993d931
[ "MIT" ]
1
2021-11-07T18:34:20.000Z
2021-11-07T18:34:20.000Z
app/interaction_service/core-algo/test/temp/random_graph_minimum_spanning_tree.cpp
Philippe-Guyard/XOptimizer
d09644eb6b92253b1d56ca2ab9c1be681993d931
[ "MIT" ]
1
2021-11-16T21:29:32.000Z
2021-11-16T21:29:32.000Z
app/interaction_service/core-algo/test/src/random_graph_minimum_spanning_tree.cpp
Philippe-Guyard/XOptimizer
d09644eb6b92253b1d56ca2ab9c1be681993d931
[ "MIT" ]
2
2021-11-05T11:06:18.000Z
2021-11-07T18:49:17.000Z
// Copyright (c) 2021 XOptimzer Team. // All rights reserved. // Standard libraries #include <utility> // std::pair, std::make_pair #include <chrono> // std::chrono::system_clock::now().time_since_epoch().count() #include <random> // std::mt19937_64 #include <algorithm> // std::random_shuffle, std::min #include <vector> // std::vector #include <limits> // std::numeric_limits #include <queue> // std::priority_queue #include <stdexcept> // std::invalid_argument #include <iostream> #include <assert.h> // External libraries #include "random_graph.hpp" /** * Generate a random undirected weighted graph, and compute the cost of minimum * spanning tree using Prim's algorithm. The result is then compared with official * method implemented and provided in Graph class. * * Independent implementation of Minimum Spanning Tree algorithm, for testing purpose. * Here, Prim's algorithm is chosen. * * @param {int} number_of_vertices : Number of vertices. * @param {EdgeWeight} weight_limit : Upper limit for ranom weight. The lower bound is set by default to 0. Default set to be 6000.0 * @param {double} density : Density of random graph from 0 to 1, e.g. 0 corresponds to a tree, and 1 corresponds to complete graph. Default set to be 0.5 * @param {int} seed : Seed fed into random number generator. Default set to be the EPOCH time at runtime. * * @return {pair<EdgeWeight, EdgeWeight>} A pair of EdgeWeigt {expected_total_cost, computed_total_cost}, where expected_total_cost is computed by Prim's algorithm, and the computed_total_cost is computed by official method. */ std::pair<EdgeWeight, EdgeWeight> RandomGraph::minimum_spanning_tree_test( int number_of_vertices, EdgeWeight weight_limit = 6000.0, double density = 0.5, int seed = -1) { // Seeding the random number generator if (seed == -1) { seed = std::chrono::system_clock::now().time_since_epoch().count(); } if (density < 0.0 || density > 1.0) { density = 0.5; } // randomly initialize the graph random_graph(number_of_vertices, weight_limit, density, seed); // Actual Prim's algorithm implementation std::vector<bool> added(number_of_vertices); std::vector<EdgeWeight> final_cost(number_of_vertices, std::numeric_limits<EdgeWeight>::max()); final_cost[0] = 0; std::priority_queue<std::pair<EdgeWeight, int>, std::vector<std::pair<EdgeWeight, int> >, std::greater<std::pair<EdgeWeight, int> > > queue; queue.push({0, 0}); EdgeWeight expected_total_cost = 0.0, computed_total_cost = 0.0; // If the node is node not yet added to the minimum spanning tree add it, and increment the cost. while(!queue.empty()) { std::pair<EdgeWeight, int> u = queue.top(); queue.pop(); int index = u.second; if(!added[index]) { final_cost[index] = u.first; expected_total_cost += u.first; added[index] = true; // Iterate through all the nodes adjacent to the node taken out of priority queue. // Push only those nodes (weight,node) that are not yet present in the minumum spanning tree. for(int i = 0; i < number_of_vertices; i++) { if(get_edge_weight(index, i) < std::numeric_limits<EdgeWeight>::max() && !added[i] && u.first + get_edge_weight(index, i) < final_cost[i]) { queue.push({get_edge_weight(index, i), i}); } } } } std::vector<Edge*> minimum_spanning_tree_kruskal = min_spanning(); for (Edge* e : minimum_spanning_tree_kruskal) { computed_total_cost += e->get_weight(); } return {expected_total_cost, computed_total_cost}; }
39.6
224
0.604137
Philippe-Guyard
5f157134ea6a8536026b67f1ad3b648b3382fb09
694
cpp
C++
CPxRigidActor.cpp
bloeys/physx-c
0e2a4b2bd11a9a178c08a8137182c5ede647c3ac
[ "MIT" ]
null
null
null
CPxRigidActor.cpp
bloeys/physx-c
0e2a4b2bd11a9a178c08a8137182c5ede647c3ac
[ "MIT" ]
null
null
null
CPxRigidActor.cpp
bloeys/physx-c
0e2a4b2bd11a9a178c08a8137182c5ede647c3ac
[ "MIT" ]
null
null
null
#include <PxPhysicsAPI.h> #include "CPxRigidActor.h" #include "CPxDefaultAllocator.h" void CPxRigidActor_setSimFilterData(CPxRigidActor* cra, CPxFilterData* cfd) { physx::PxRigidActor* actor = static_cast<physx::PxRigidActor*>(cra->obj); const physx::PxU32 numShapes = actor->getNbShapes(); physx::PxShape** shapes = (physx::PxShape**)physxDefaultAlloc.allocate(sizeof(physx::PxShape*) * numShapes, 0, 0, 0); actor->getShapes(shapes, numShapes); physx::PxFilterData filterData(cfd->word0, cfd->word1, cfd->word2, cfd->word3); for (physx::PxU32 i = 0; i < numShapes; i++) { shapes[i]->setSimulationFilterData(filterData); } physxDefaultAlloc.deallocate(shapes); }
36.526316
119
0.723343
bloeys
5f15f8f9809f9ad5ae5b4d72ee9b6fc59e529727
128
cpp
C++
userland/utilities/reboot/main.cpp
smithersomer/pranaOS
b8ef2554af43fd3e0f67a5ceebbad8b1ae1c4cb1
[ "BSD-2-Clause" ]
1
2021-12-04T13:33:48.000Z
2021-12-04T13:33:48.000Z
userland/utilities/reboot/main.cpp
smithersomer/pranaOS
b8ef2554af43fd3e0f67a5ceebbad8b1ae1c4cb1
[ "BSD-2-Clause" ]
null
null
null
userland/utilities/reboot/main.cpp
smithersomer/pranaOS
b8ef2554af43fd3e0f67a5ceebbad8b1ae1c4cb1
[ "BSD-2-Clause" ]
null
null
null
#include <stdio.h> #include <signal.h> int main() { printf("rebooting..."); // return kill(1, SIGHUP); return 0; }
12.8
30
0.570313
smithersomer
5f18d49921f611a6fc34bc8a287cf420121b138d
125
cc
C++
Core/tests/testVector.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
1
2019-07-29T04:07:29.000Z
2019-07-29T04:07:29.000Z
Core/tests/testVector.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
null
null
null
Core/tests/testVector.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
1
2020-03-04T17:13:04.000Z
2020-03-04T17:13:04.000Z
#include <cc/Vector> namespace cc { template class Vector<double, 3>; } int main(int argc, char *argv[]) { return 0; }
13.888889
50
0.648
frankencode
5f1c2b05dcdaedfa9d9710cbd5536212ab55608b
590
cpp
C++
ThrowThingsTemplate/Vixen/source/vgraphics/vix_glcamera2d.cpp
eric-fonseca/Throw-Things-at-Monsters
c92d9cd4e244d4ddb54b74e8508cba2b6408abb7
[ "MIT" ]
null
null
null
ThrowThingsTemplate/Vixen/source/vgraphics/vix_glcamera2d.cpp
eric-fonseca/Throw-Things-at-Monsters
c92d9cd4e244d4ddb54b74e8508cba2b6408abb7
[ "MIT" ]
null
null
null
ThrowThingsTemplate/Vixen/source/vgraphics/vix_glcamera2d.cpp
eric-fonseca/Throw-Things-at-Monsters
c92d9cd4e244d4ddb54b74e8508cba2b6408abb7
[ "MIT" ]
null
null
null
#include <vix_glcamera2d.h> namespace Vixen { GLCamera2D::GLCamera2D(float L, float R, float T, float B) { SetBounds(L, R, T, B); } void GLCamera2D::SetBounds(float L, float R, float T, float B) { m_left = L; m_right = R; m_top = T; m_bottom = B; /*create projection*/ m_projection = glm::ortho(m_left, m_right, m_bottom, m_top); /*create view*/ m_view = glm::mat4(1.0f); } const Mat4 & GLCamera2D::Projection() { return m_projection; } const Mat4 & GLCamera2D::View() { return m_view; } }
14.390244
62
0.576271
eric-fonseca
5f1c5a83059ffe2ca09c9d147add2eb75d32de46
505
cpp
C++
src/the_framework/dstruct/shellsort/main.cpp
schnedann/linebuffer
494745a6d83eef1adebf9a6e30c636a8edd5f0c2
[ "BSD-3-Clause" ]
null
null
null
src/the_framework/dstruct/shellsort/main.cpp
schnedann/linebuffer
494745a6d83eef1adebf9a6e30c636a8edd5f0c2
[ "BSD-3-Clause" ]
null
null
null
src/the_framework/dstruct/shellsort/main.cpp
schnedann/linebuffer
494745a6d83eef1adebf9a6e30c636a8edd5f0c2
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <cstdlib> #include <stdint.h> #include <ctime> #include <sstream> using namespace std; /** * */ int main() { uint16_t* data; cout << "Hello world!" << endl; data = new uint16_t[dVALUES]; fillran(data,dVALUES); cout << "Unsorted:" << endl << List(data,dVALUES) << endl; Sort(data,dVALUES,Initgap(dVALUES)); cout << "Sorted:" << endl << List(data,dVALUES) << endl; delete(data); return 0; }
14.027778
63
0.548515
schnedann
5f1ca3ba83ee3e063c678dadfd2a01a0c4db3038
659
cpp
C++
215#kth-largest-element-in-an-array/solution.cpp
llwwns/leetcode_solutions
e352c9bf6399ab3ee0f23889e70361c9f2a3bd33
[ "MIT" ]
null
null
null
215#kth-largest-element-in-an-array/solution.cpp
llwwns/leetcode_solutions
e352c9bf6399ab3ee0f23889e70361c9f2a3bd33
[ "MIT" ]
null
null
null
215#kth-largest-element-in-an-array/solution.cpp
llwwns/leetcode_solutions
e352c9bf6399ab3ee0f23889e70361c9f2a3bd33
[ "MIT" ]
null
null
null
class Solution { public: void search(int l, int r) { } int findKthLargest(vector<int>& nums, int k) { int *arr = nums.data(); int l = 0, r = nums.size(); k--; while (true) { if (l == r - 1 && l == k) return arr[k]; int v = arr[l]; int i, j = l; for (i = l + 1; i < r; i++) { if (arr[i] > v) { swap(arr[++j], arr[i]); } } if (j == k) return arr[l]; swap(arr[l], arr[j]); if (j < k) l = j + 1; else r = j; } } };
26.36
53
0.314112
llwwns
5f1eb99a1fae7f113f2b06e2e265a0047583fd39
1,950
cpp
C++
src/Game/CogShape.cpp
ananace/LD44
472e5134a1f846d9c2244b31fe3753d08963b71e
[ "MIT" ]
null
null
null
src/Game/CogShape.cpp
ananace/LD44
472e5134a1f846d9c2244b31fe3753d08963b71e
[ "MIT" ]
null
null
null
src/Game/CogShape.cpp
ananace/LD44
472e5134a1f846d9c2244b31fe3753d08963b71e
[ "MIT" ]
null
null
null
#include "CogShape.hpp" #include "../Util.hpp" #include <cstdio> using Game::CogShape; CogShape::CogShape(float aRadius, float aToothHeight, size_t aToothCount, uint8_t aToothWidth, bool aToothSlope) : m_circleRadius(aRadius) , m_toothHeight(aToothHeight) , m_toothCount(aToothCount) , m_toothWidth(aToothWidth) , m_toothSlope(aToothSlope) { update(); } size_t CogShape::getToothCount() const { return m_toothCount; } void CogShape::setToothCount(size_t aCount) { m_toothCount = aCount; update(); } float CogShape::getToothHeight() const { return m_toothHeight; } void CogShape::setToothHeight(float aHeight) { m_toothHeight = aHeight; update(); } uint8_t CogShape::getToothWidth() const { return m_toothWidth; } void CogShape::setToothWidth(uint8_t aWidth) { m_toothWidth = aWidth; update(); } bool CogShape::getToothSlope() const { return m_toothSlope; } void CogShape::setToothSlope(bool aSlope) { m_toothSlope = aSlope; update(); } void CogShape::setRadius(float aRadius) { m_circleRadius = aRadius; } float CogShape::getRadius() const { return m_circleRadius; } size_t CogShape::getPointCount() const { return m_toothCount * 8; } sf::Vector2f CogShape::getPoint(size_t aIndex) const { const size_t offset = getPointCount() / m_toothCount; float mult = 1.f; if (aIndex % offset <= m_toothWidth || offset - (aIndex % offset) <= m_toothWidth) { mult = m_toothHeight; if (m_toothSlope && (aIndex % offset == m_toothWidth || offset - (aIndex % offset) == m_toothWidth)) mult = (3.f + m_toothHeight * 1) / 4.f; } // TODO: slope float angle = aIndex * 2.f * Pi() / getPointCount() - Pi() / 2.f; float multrad = m_circleRadius * mult; float x = cos(angle) * multrad; float y = sin(angle) * multrad; return { m_circleRadius + x, m_circleRadius + y }; }
20.744681
112
0.661026
ananace
5f1ebaf2a80daf73415741e7c9b16b1d1ab0c2f4
237
cpp
C++
Editor/Editor/Menu/ToolsMenu/ToolsMenu.cpp
gregory-vovchok/YEngine
e28552e52588bd90db01dd53e5fc817d0a26d146
[ "BSD-2-Clause" ]
null
null
null
Editor/Editor/Menu/ToolsMenu/ToolsMenu.cpp
gregory-vovchok/YEngine
e28552e52588bd90db01dd53e5fc817d0a26d146
[ "BSD-2-Clause" ]
null
null
null
Editor/Editor/Menu/ToolsMenu/ToolsMenu.cpp
gregory-vovchok/YEngine
e28552e52588bd90db01dd53e5fc817d0a26d146
[ "BSD-2-Clause" ]
1
2020-12-04T08:57:03.000Z
2020-12-04T08:57:03.000Z
#include "..\..\Editor.h" #include <Engine/Core/AssetLibrary/AssetLibrary.h> #include <Editor/WarningDialog/WarningDialog.h> void Editor::CreateToolsMenu(void) { toolsMenu = menuBar()->addMenu("Tools"); CreateDesignToolsMenu(); }
18.230769
50
0.734177
gregory-vovchok
5f22ba34654f5cb4d7e01db13a43e9e25eabfb47
111
hpp
C++
tool.hpp
Admaks/Minesweeper
6f2ca36e2eec5dba3e022a85542df7390278c7f7
[ "MIT" ]
null
null
null
tool.hpp
Admaks/Minesweeper
6f2ca36e2eec5dba3e022a85542df7390278c7f7
[ "MIT" ]
null
null
null
tool.hpp
Admaks/Minesweeper
6f2ca36e2eec5dba3e022a85542df7390278c7f7
[ "MIT" ]
null
null
null
#ifndef MINESWEEPER__TOOL_HPP_ #define MINESWEEPER__TOOL_HPP_ namespace TOOL { char toChar(int); } #endif
13.875
30
0.783784
Admaks
5f2785bbb9b796f967cdd0653e4aa8d97976cdfa
708
cpp
C++
2020-11-17/machado.cpp
pufe/programa
7f79566597446e9e39222e6c15fa636c3dd472bb
[ "MIT" ]
2
2020-12-12T00:02:40.000Z
2021-04-21T19:49:59.000Z
2020-11-17/machado.cpp
pufe/programa
7f79566597446e9e39222e6c15fa636c3dd472bb
[ "MIT" ]
null
null
null
2020-11-17/machado.cpp
pufe/programa
7f79566597446e9e39222e6c15fa636c3dd472bb
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstring> int main() { int n, lines_per_page, chars_per_line; char word[124]; while(true) { if (scanf(" %d %d %d", &n, &lines_per_page, &chars_per_line)!=3) break; ++chars_per_line; int current_page = 1; int current_line = 1; int current_char = 0; for(int i=0; i<n; ++i) { scanf(" %s", word); int length = strlen(word)+1; if (current_char + length > chars_per_line) { current_char = 0; ++current_line; if (current_line > lines_per_page) { current_line=1; ++current_page; } } current_char += length; } printf("%d\n", current_page); } return 0; }
21.454545
52
0.55226
pufe
5f3370b3f1607e6b5983749b0e156556e8513ffd
1,572
cpp
C++
ctest/tests/geometry/Quadric.cpp
mgradysaunders/Precept
0677c70ac4ed9e0a8c5aad7b049daad22998de9e
[ "BSD-2-Clause" ]
null
null
null
ctest/tests/geometry/Quadric.cpp
mgradysaunders/Precept
0677c70ac4ed9e0a8c5aad7b049daad22998de9e
[ "BSD-2-Clause" ]
null
null
null
ctest/tests/geometry/Quadric.cpp
mgradysaunders/Precept
0677c70ac4ed9e0a8c5aad7b049daad22998de9e
[ "BSD-2-Clause" ]
null
null
null
#include "../../testing.h" #include <pre/geometry/Quadric> using namespace pre; TEST_CASE("geometry:Quadric") { Pcg32 gen = RandomGen(); SUBCASE("Ellipse (2-dimensional)") { auto quad = Quadric2d::make_ellipsoid({3, 2}); double t0 = NaN<double>; double t1 = NaN<double>; CHECK(quad.ray_cast({{4, 0}, {-1, 0}}, t0, t1)); CHECK(t0 == Approx(1).epsilon(1e-4)); CHECK(t1 == Approx(7).epsilon(1e-4)); CHECK(quad.ray_cast({{0, 3}, {0, -1}}, t0, t1)); CHECK(t0 == Approx(1).epsilon(1e-4)); CHECK(t1 == Approx(5).epsilon(1e-4)); double angle = gen(-4.0, 4.0); CHECK( quad.field({3 * cos(angle), 2 * sin(angle)}) == Approx(0).epsilon(1e-4)); } SUBCASE("Ellipse (3-dimensional)") { auto quad = Quadric3d::make_ellipsoid({2, 3, 4}); Ray3d ray; ray.org = sample_domain::UniformSphere::sample( {gen(0.0, 1.0), gen(0.0, 1.0)}); ray.org += RandomArray<double, 3>(gen) * 0.2; ray.dir = -normalize(ray.org); ray.org *= 4.5; double t0 = NaN<double>; double t1 = NaN<double>; CHECK(quad.ray_cast(ray, t0, t1)); CHECK(quad.field(ray(t0)) == Approx(0).epsilon(1e-4)); CHECK(quad.field(ray(t1)) == Approx(0).epsilon(1e-4)); ray.org = {}; CHECK(quad.ray_cast(ray, t0, t1)); CHECK(quad.field(ray(t0)) == Approx(0).epsilon(1e-4)); CHECK(quad.field(ray(t1)) == Approx(0).epsilon(1e-4)); CHECK(not ray.is_in_range(t0)); } }
35.727273
62
0.533079
mgradysaunders
5f33f9f2ead49e0c61fd3f89f466907652e6cadd
348
cpp
C++
atcoder(abc)/171E.cpp
NafiAsib/competitive-programming
3255b2fe3329543baf9e720e1ccaf08466d77303
[ "MIT" ]
null
null
null
atcoder(abc)/171E.cpp
NafiAsib/competitive-programming
3255b2fe3329543baf9e720e1ccaf08466d77303
[ "MIT" ]
null
null
null
atcoder(abc)/171E.cpp
NafiAsib/competitive-programming
3255b2fe3329543baf9e720e1ccaf08466d77303
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 1; int a[maxn]; int main() { int n; cin >> n; cin >> a[0]; int xr = a[0]; for(int i=1; i<n; i++) { cin >> a[i]; xr = a[i]^xr; } for(int i=0; i<n; i++) cout << (a[i]^xr) << " "; cout << "\n"; return 0; }
15.818182
53
0.393678
NafiAsib
5f34a695185cd3b602cf7a5a639b1eafe33b5009
4,485
cpp
C++
pendulum-pointers.cpp
Riccardo-Beccalli/Physical-Simulation
a6dfcc6b9f8cfda977970fdf08ce7c57ccb02ca9
[ "MIT" ]
null
null
null
pendulum-pointers.cpp
Riccardo-Beccalli/Physical-Simulation
a6dfcc6b9f8cfda977970fdf08ce7c57ccb02ca9
[ "MIT" ]
null
null
null
pendulum-pointers.cpp
Riccardo-Beccalli/Physical-Simulation
a6dfcc6b9f8cfda977970fdf08ce7c57ccb02ca9
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> #include <fstream> #include <cstdlib> #include <unistd.h> using namespace std; #define W 20 #define G 9.81 void introduction (); void evolution (double *x, double *v, double *data, ofstream *ptrfout); void write (double *data, ofstream *ptrfout2); void choice (double *data, double *v); int main () { int scelta; int N = 50; double *x = (double *) calloc (N, sizeof (double)); double *v = (double *) calloc (N, sizeof (double)); v [0] = 5; double *data = (double *) calloc (7, sizeof (double)); data [0] = 10; data [1] = 1; data [2] = .1; data [3] = 1; data [4] = 200; data [5] = .05; data [6] = N; /*double A = 10, L = 1; double K = .1, M = 1; double T = 200, Delta = .05;*/ ofstream fout; fout.open ("data.dat"); ofstream *ptrfout; ptrfout = &fout; ofstream fout2; fout2.open ("fare2.plt"); ofstream *ptrfout2; ptrfout2 = &fout2; system ("clear"); error: introduction (); cin >> scelta; if (scelta == 0) { system ("clear"); cout << "You chose the simulation with fixed parameters!" << endl; cout << "How many pendulums do you want in the simulation?" cout << "You will now be able to see the positions of the respective pendulums as function of the time!" << endl; } else if (scelta == 1) { system ("clear"); choice (data, v); } else { system ("clear"); cout << "!!!WARNING!!! Choice not contemplated, you have to choose [0] or [1]!" << endl; goto error; } evolution (x, v, data, ptrfout); write (data, ptrfout2); sleep (1); system ("gnuplot fare2.plt -p"); fout.close (); fout2.close (); return 0; } void introduction () { cout << "╔═══════════════════════════════════════════════════════════════╗" << endl; cout << "║ Physics ║" << endl; cout << "╠═══════════════════════════════════════════════════════════════╣" << endl; cout << "║ Pendulums connected by a spring ║" << endl; cout << "╠═══════════════════════════════════════════════════════════════╣" << endl; cout << "║ Author: Riccardo Beccalli ║" << endl; cout << "╚═══════════════════════════════════════════════════════════════╝" << endl << endl; cout << "╔═══════════════════════════════════════════════════════════════╗" << endl; cout << "║ Choose the kind of simulation you want! ║" << endl; cout << "╠═══════════════════════════════════════════════════════════════╣" << endl; cout << "║ [0] = Simulation with fixed parameters ║" << endl; cout << "║ [1] = Simulation with user-selected parameters ║" << endl; cout << "╚═══════════════════════════════════════════════════════════════╝" << endl << endl; cout << "\n> "; } void evolution (double *x, double *v, double *data, ofstream *ptrfout) { double A = data [0], L = data [1]; double K = data [2], M = data [3]; double T = data [4], Delta = data [5], N = data [6]; *ptrfout << setw (W) << 0; for (int i = 0; i < N; i ++) *ptrfout << setw (W) << x [i] + i * A << setw (W) << v [i]; *ptrfout << endl; for (double t = Delta; t <= T; t += Delta) { for (int i = 0; i < N; i ++) if (i == 0) v [i] += (- (G/L) * x [i] - K/M * (x [i] - x [i + 1])) * Delta; else if (i == N - 1) v [i] += (- (G/L) * x [i] - K/M * (x [i] - x [i - 1])) * Delta; else v [i] += (- (G/L) * x [i] - K/M * (x [i] - x [i - 1]) - K/M * (x [i] - x [i + 1])) * Delta; for (int i = 0; i < N; i ++) x [i] += v [i] * Delta; *ptrfout << setw (W) << t; for (int i = 0; i < N; i ++) *ptrfout << setw (W) << x [i] + i * A << setw (W) << v [i]; *ptrfout << endl; } } void write (double *data, ofstream *ptrfout2) { *ptrfout2 << "p 'data.dat'"; for (int i = 0; i < data [6]; i++) *ptrfout2 << (i == 0 ? "" : "''") << " u 1:" << 2 * (i + 1) << " w l title ''" << (i == data [6] - 1 ? "" : ","); *ptrfout2 << endl; } void choice (double *data, double *v) { cout << "You have chosen the simulation with the parameters chosen by the user!" << endl; cout << "Enter the initial speed v [m/s] of the first pendulum\n> "; cin >> v [0]; cout << "Enter simulation time T [s]\n> "; cin >> data [4]; cout << "Enter the mass m [kg] of the pendulums\n> "; cin >> data [3]; cout << "Enter the length l [m] of the wire\n> "; cin >> data [1]; cout << "You will now be able to see the positions of the respective pendulums as function of the time!" << endl; }
30.304054
115
0.467781
Riccardo-Beccalli
5f367cbd72ff29e32509e52b53c8ae0501b0f53e
8,848
cpp
C++
src/lastfmpp/tag.cpp
chrismanning/lastfmpp
59439e62d2654359a48f8244a4b69b95d398beb3
[ "MIT" ]
null
null
null
src/lastfmpp/tag.cpp
chrismanning/lastfmpp
59439e62d2654359a48f8244a4b69b95d398beb3
[ "MIT" ]
null
null
null
src/lastfmpp/tag.cpp
chrismanning/lastfmpp
59439e62d2654359a48f8244a4b69b95d398beb3
[ "MIT" ]
null
null
null
/************************************************************************** ** Copyright (C) 2015 Christian Manning ** ** This software may be modified and distributed under the terms ** of the MIT license. See the LICENSE file for details. **************************************************************************/ #include <jbson/path.hpp> #include <lastfmpp/tag.hpp> #include <lastfmpp/artist.hpp> #include <lastfmpp/album.hpp> #include <lastfmpp/track.hpp> #include <lastfmpp/detail/service_access.hpp> #include <lastfmpp/detail/params.hpp> #include <lastfmpp/detail/transform.hpp> #include <lastfmpp/detail/deserialise_tag.hpp> #include <lastfmpp/detail/deserialise_album.hpp> #include <lastfmpp/detail/deserialise_artist.hpp> #include <lastfmpp/detail/deserialise_ext.hpp> #include <lastfmpp/detail/deserialise_track.hpp> namespace lastfmpp { std::experimental::string_view tag::name() const { return m_name; } void tag::name(std::experimental::string_view name) { m_name = name.to_string(); } const uri_t& tag::url() const { return m_url; } void tag::url(uri_t url) { m_url = std::move(url); } int tag::reach() const { return m_reach; } void tag::reach(int reach) { m_reach = reach; } int tag::taggings() const { return m_taggings; } void tag::taggings(int taggings) { m_taggings = taggings; } bool tag::streamable() const { return m_streamable; } void tag::streamable(bool streamable) { m_streamable = streamable; } const wiki& tag::wiki() const { return m_wiki; } void tag::wiki(struct wiki wiki) { m_wiki = wiki; } pplx::task<tag> tag::get_info(service& serv, std::experimental::string_view name) { return detail::service_access::get(serv, "tag.getinfo", detail::make_params(std::make_pair("tag", name)), transform_select<tag>("tag")); } pplx::task<tag> tag::get_info(service& serv) const { return get_info(serv, m_name); } pplx::task<std::vector<tag>> tag::get_similar(service& serv, std::experimental::string_view name) { return detail::service_access::get(serv, "tag.getsimilar", detail::make_params(std::make_pair("tag", name)), transform_select<std::vector<tag>>("similartags.tag.*")); } pplx::task<std::vector<tag>> tag::get_similar(service& serv) const { return get_similar(serv, m_name); } pplx::task<std::vector<album>> tag::get_top_albums(service& serv, std::experimental::string_view name, std::experimental::optional<int> limit, std::experimental::optional<int> page) { return detail::service_access::get(serv, "tag.gettopalbums", detail::make_params(std::make_tuple("tag", name), std::make_tuple("limit", limit), std::make_tuple("page", page)), transform_select<std::vector<album>>("topalbums.album.*")); } pplx::task<std::vector<album>> tag::get_top_albums(service& serv, std::experimental::optional<int> limit, std::experimental::optional<int> page) const { return get_top_albums(serv, m_name, limit, page); } pplx::task<std::vector<artist>> tag::get_top_artists(service& serv, std::experimental::string_view name, std::experimental::optional<int> limit, std::experimental::optional<int> page) { return detail::service_access::get(serv, "tag.gettopartists", detail::make_params(std::make_tuple("tag", name), std::make_tuple("limit", limit), std::make_tuple("page", page)), transform_select<std::vector<artist>>("topartists.artist.*")); } pplx::task<std::vector<artist>> tag::get_top_artists(service& serv, std::experimental::optional<int> limit, std::experimental::optional<int> page) const { return get_top_artists(serv, m_name, limit, page); } pplx::task<std::vector<tag>> tag::get_top_tags(service& serv) { return detail::service_access::get(serv, "tag.gettoptags", params_t{}, transform_select<std::vector<tag>>("toptags.tag.*")); } pplx::task<std::vector<track>> tag::get_top_tracks(service& serv, std::experimental::string_view name, std::experimental::optional<int> limit, std::experimental::optional<int> page) { return detail::service_access::get(serv, "tag.gettoptracks", detail::make_params(std::make_tuple("tag", name), std::make_tuple("limit", limit), std::make_tuple("page", page)), transform_select<std::vector<track>>("toptracks.track.*")); } pplx::task<std::vector<track>> tag::get_top_tracks(service& serv, std::experimental::optional<int> limit, std::experimental::optional<int> page) const { return get_top_tracks(serv, m_name, limit, page); } pplx::task<std::vector<artist>> tag::get_weekly_artist_chart(service& serv, std::experimental::string_view name, std::experimental::optional<std::tuple<time_point, time_point>> date_range, std::experimental::optional<int> limit) { std::experimental::optional<time_point> from, to; if(date_range) std::tie(from, to) = *date_range; return detail::service_access::get(serv, "tag.getweeklyartistchart", detail::make_params(std::make_tuple("tag", name), std::make_tuple("from", from), std::make_tuple("to", to), std::make_tuple("limit", limit)), transform_select<std::vector<artist>>("weeklyartistchart.artist.*")); } pplx::task<std::vector<artist>> tag::get_weekly_artist_chart(service& serv, std::experimental::optional<std::tuple<time_point, time_point>> date_range, std::experimental::optional<int> limit) const { return get_weekly_artist_chart(serv, m_name, date_range, limit); } pplx::task<std::vector<std::tuple<time_point, time_point>>> tag::get_weekly_chart_list(service& serv, std::experimental::string_view name) { auto transformer = [](jbson::document doc) { auto from = jbson::path_select(doc, "weeklychartlist.chart.*.from"); auto to = jbson::path_select(doc, "weeklychartlist.chart.*.to"); std::vector<std::tuple<time_point, time_point>> charts{}; namespace hana = boost::hana; boost::transform(from, to, std::back_inserter(charts), [](auto&& from, auto&& to) { return hana::transform(std::make_tuple(from, to), hana::compose(time_point::clock::from_time_t, convert<std::time_t>, deserialise<int>)); }); return charts; }; return detail::service_access::get(serv, "tag.getweeklychartlist", detail::make_params(std::make_tuple("tag", name)), transformer); } pplx::task<std::vector<std::tuple<time_point, time_point>>> tag::get_weekly_chart_list(service& serv) const { return get_weekly_chart_list(serv, m_name); } pplx::task<std::vector<tag>> tag::search(service& serv, std::experimental::string_view name, std::experimental::optional<int> limit, std::experimental::optional<int> page) { return detail::service_access::get(serv, "tag.search", detail::make_params(std::make_tuple("tag", name), std::make_tuple("limit", limit), std::make_tuple("page", page)), transform_select<std::vector<tag>>("results.tagmatches.tag.*")); } pplx::task<std::vector<tag>> tag::search(service& serv, std::experimental::optional<int> limit, std::experimental::optional<int> page) const { return search(serv, m_name, limit, page); } } // namespace lastfm
44.913706
119
0.555493
chrismanning
5f3a83a1d0cd000b55f50ee21386dfeca4e737d1
1,310
cpp
C++
src/OpenGL/entrypoints/GL1.5/gl_is_query.cpp
kbiElude/VKGL
fffabf412723a3612ba1c5bfeafe1da38062bd18
[ "MIT" ]
114
2018-08-05T16:26:53.000Z
2021-12-30T07:28:35.000Z
src/OpenGL/entrypoints/GL1.5/gl_is_query.cpp
kbiElude/VKGL
fffabf412723a3612ba1c5bfeafe1da38062bd18
[ "MIT" ]
5
2018-08-18T21:16:58.000Z
2018-11-22T21:50:48.000Z
src/OpenGL/entrypoints/GL1.5/gl_is_query.cpp
kbiElude/VKGL
fffabf412723a3612ba1c5bfeafe1da38062bd18
[ "MIT" ]
6
2018-08-05T22:32:28.000Z
2021-10-04T15:39:53.000Z
/* VKGL (c) 2018 Dominik Witczak * * This code is licensed under MIT license (see LICENSE.txt for details) */ #include "OpenGL/entrypoints/GL1.5/gl_is_query.h" #include "OpenGL/context.h" #include "OpenGL/globals.h" static bool validate(OpenGL::Context* in_context_ptr, const GLuint& in_id) { bool result = false; // .. result = true; return result; } GLboolean VKGL_APIENTRY OpenGL::vkglIsQuery(GLuint id) { const auto& dispatch_table_ptr = OpenGL::g_dispatch_table_ptr; VKGL_TRACE("glIsQuery(id=[%u])", id); return dispatch_table_ptr->pGLIsQuery(dispatch_table_ptr->bound_context_ptr, id) ? GL_TRUE : GL_FALSE; } static bool vkglIsQuery_execute(OpenGL::Context* in_context_ptr, const GLuint& in_id) { return in_context_ptr->is_query(in_id); } bool OpenGL::vkglIsQuery_with_validation(OpenGL::Context* in_context_ptr, const GLuint& in_id) { bool result = false; if (validate(in_context_ptr, in_id) ) { result = vkglIsQuery_execute(in_context_ptr, in_id); } return result; }
24.259259
80
0.575573
kbiElude
5f4312923a694bf986c8d2d753f2b6c79ca4c6b2
1,952
cpp
C++
Source/DynamicalModels/ObjectStates/imstkCPDState.cpp
quantingxie/vibe
965a79089ac3ec821ad65c45ac50e69bf32dc92f
[ "Apache-2.0" ]
2
2020-08-14T07:21:30.000Z
2021-08-30T09:39:09.000Z
Source/DynamicalModels/ObjectStates/imstkCPDState.cpp
quantingxie/vibe
965a79089ac3ec821ad65c45ac50e69bf32dc92f
[ "Apache-2.0" ]
null
null
null
Source/DynamicalModels/ObjectStates/imstkCPDState.cpp
quantingxie/vibe
965a79089ac3ec821ad65c45ac50e69bf32dc92f
[ "Apache-2.0" ]
1
2020-08-14T07:00:31.000Z
2020-08-14T07:00:31.000Z
/*========================================================================= Library: iMSTK Copyright (c) Kitware, Inc. & Center for Modeling, Simulation, & Imaging in Medicine, Rensselaer Polytechnic Institute. 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.txt 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 "imstkCPDState.h" namespace imstk { void CPDState::initialize(const size_t numNodes, const bool(&options)[3]) { if (options[0]) m_pos.resize(numNodes, Vec3d(0, 0, 0)); if (options[1]) m_vel.resize(numNodes, Vec3d(0, 0, 0)); if (options[2]) m_acc.resize(numNodes, Vec3d(0, 0, 0)); } void CPDState::initialize(const std::shared_ptr<PointSet>& m, const bool(&options)[3]) { this->initialize(m->getNumVertices(), options); } void CPDState::initialize(const cpd::ParticleObjectPtr p_particleObject, const bool(&options)[3]) { initialize(p_particleObject->getParticleCount(), options); updateStateFromParticleObject(p_particleObject); } void CPDState::setState(std::shared_ptr<CPDState> p_state) { m_pos = p_state->getPositions(); m_vel = p_state->getVelocities(); m_acc = p_state->getAccelerations(); } void CPDState::updateStateFromParticleObject(const cpd::ParticleObjectPtr p_particleObject) { auto& pos = p_particleObject->getPositions(); for (unsigned i = 0; i < m_pos.size(); i++) { setVertexPosition(i, pos[i]); } } } // imstk
30.030769
100
0.664959
quantingxie
5f44c8d245494a9b2b21a59f033300ff3882816c
950
cpp
C++
src/RenderMethod_GrassFFP.cpp
foxostro/CheeseTesseract
737ebbd19cee8f5a196bf39a11ca793c561e56cb
[ "MIT" ]
1
2016-05-17T03:36:52.000Z
2016-05-17T03:36:52.000Z
src/RenderMethod_GrassFFP.cpp
foxostro/CheeseTesseract
737ebbd19cee8f5a196bf39a11ca793c561e56cb
[ "MIT" ]
null
null
null
src/RenderMethod_GrassFFP.cpp
foxostro/CheeseTesseract
737ebbd19cee8f5a196bf39a11ca793c561e56cb
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "RenderMethod_GrassFFP.h" void RenderMethod_GrassFFP::renderPass(RENDER_PASS pass) { switch (pass) { case OPAQUE_PASS: pass_opaque(); break; default: return; } } void RenderMethod_GrassFFP::pass_opaque() { CHECK_GL_ERROR(); // Setup state glPushAttrib(GL_ALL_ATTRIB_BITS); glColor4fv(white); glEnable(GL_TEXTURE_2D); glDisable(GL_CULL_FACE); glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); // Setup client state glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); // Alpha-test pass glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.1f); renderChunks(); //Restore client state glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); // Restore settings glPopAttrib(); CHECK_GL_ERROR(); }
21.111111
59
0.74
foxostro
5f45faf4488d38fb890c45ddf4219c3ab8706e94
633
cpp
C++
src/main.cpp
maxwillf/Huffman
8de0e08050b5ada24c0114b8832fca192f8abce7
[ "MIT" ]
null
null
null
src/main.cpp
maxwillf/Huffman
8de0e08050b5ada24c0114b8832fca192f8abce7
[ "MIT" ]
null
null
null
src/main.cpp
maxwillf/Huffman
8de0e08050b5ada24c0114b8832fca192f8abce7
[ "MIT" ]
null
null
null
#include <fstream> #include <iostream> #include <map> #include <vector> #include "../include/node.h" #include "../include/util.h" #include "../include/huffman.h" #include "../include/ioManager.h" int main(int argc, char *argv[]) { std::ifstream input("res/input.txt"); std::ofstream output("res/output.txt"); std::ifstream decompress("res/output.txt"); std::ofstream unpacked("res/unpacked.txt"); IOManager io; io.readFile(input); io.compact(input, output); input.close(); output.close(); io.decodeTree(decompress, unpacked); decompress.close(); unpacked.close(); return 0; }
21.1
47
0.650869
maxwillf
5f473ae4e46a0335559d7c28cf870d7d8507d80b
15,136
cc
C++
src/EDepSimLogManager.cc
andrewmogan/edep-sim
4e9923ccba8b2f65f47b72cbb41ed683f19f1123
[ "MIT" ]
15
2017-04-25T14:20:22.000Z
2022-03-15T19:39:43.000Z
src/EDepSimLogManager.cc
andrewmogan/edep-sim
4e9923ccba8b2f65f47b72cbb41ed683f19f1123
[ "MIT" ]
24
2017-11-08T21:16:48.000Z
2022-03-04T13:33:18.000Z
src/EDepSimLogManager.cc
andrewmogan/edep-sim
4e9923ccba8b2f65f47b72cbb41ed683f19f1123
[ "MIT" ]
20
2017-11-09T15:41:46.000Z
2022-01-25T20:52:32.000Z
#include <vector> #include <sstream> #include <fstream> #include <time.h> #include "EDepSimLog.hh" EDepSim::LogManager::ErrorPriority EDepSim::LogManager::fErrorPriority = EDepSim::LogManager::ErrorLevel; EDepSim::LogManager::LogPriority EDepSim::LogManager::fLogPriority = EDepSim::LogManager::LogLevel; std::ostream* EDepSim::LogManager::fDebugStream = NULL; std::ostream* EDepSim::LogManager::fLogStream = NULL; std::map<std::string,EDepSim::LogManager::ErrorPriority> EDepSim::LogManager::fErrorTraces; std::map<std::string,EDepSim::LogManager::LogPriority> EDepSim::LogManager::fLogTraces; int EDepSim::LogManager::fIndentation = 0; EDepSim::LogManager::~LogManager() { } void EDepSim::LogManager::SetDebugLevel(const char* trace, EDepSim::LogManager::ErrorPriority level) { fErrorTraces[trace] = level; } EDepSim::LogManager::ErrorPriority EDepSim::LogManager::GetDebugLevel(const char* trace) { std::map<std::string,ErrorPriority>::iterator elem = fErrorTraces.find(trace); if (elem == fErrorTraces.end()) return fErrorPriority; return elem->second; } namespace { std::string MakeTimeStamp() { std::string stamp = "Unknown Time"; time_t t = time(NULL); struct tm *local = localtime(&t); if (!local) return stamp; char localTime[80]; if (!strftime(localTime,sizeof(localTime),"%c",local)) return stamp; struct tm *utc = gmtime(&t); if (!utc) return stamp; char utcTime[80]; if (!strftime(utcTime,sizeof(utcTime),"%Y-%m-%d %H:%M (UTC)",utc)) return stamp; stamp = localTime; stamp += " ["; stamp += utcTime; stamp += "]"; return stamp; } } void EDepSim::LogManager::SetDebugStream(std::ostream* err) { EDepSim::LogManager::fDebugStream = err; if (!fDebugStream) return; std::ofstream* ofile = dynamic_cast<std::ofstream*>(err); if (ofile && !(ofile->is_open())) { fDebugStream = NULL; EDepSimSevere("Debug stream is not open."); } *fDebugStream << std::endl << "##################################################" << std::endl << "# ERROR LOG STARTS AT: " << MakeTimeStamp() << std::endl << "##################################################" << std::endl << std::endl; } std::ostream& EDepSim::LogManager::GetDebugStream() { if (!EDepSim::LogManager::fDebugStream ) return GetLogStream(); return *EDepSim::LogManager::fDebugStream; } void EDepSim::LogManager::SetLogLevel(const char* trace, EDepSim::LogManager::LogPriority level) { fLogTraces[trace] = level; } EDepSim::LogManager::LogPriority EDepSim::LogManager::GetLogLevel(const char* trace) { std::map<std::string,LogPriority>::iterator elem = fLogTraces.find(trace); if (elem == fLogTraces.end()) return fLogPriority; return elem->second; } void EDepSim::LogManager::SetLogStream(std::ostream* log) { EDepSim::LogManager::fLogStream = log; if (!fLogStream) return; std::ofstream* ofile = dynamic_cast<std::ofstream*>(log); if (ofile && !(ofile->is_open())) { fLogStream = NULL; EDepSimSevere("Log stream is not open."); } *fLogStream << std::endl << "##################################################" << std::endl << "# LOG STARTS AT: " << MakeTimeStamp() << std::endl << "##################################################" << std::endl << std::endl; } std::ostream& EDepSim::LogManager::GetLogStream() { if (!EDepSim::LogManager::fLogStream) return std::cout; return *EDepSim::LogManager::fLogStream; } void EDepSim::LogManager::SetIndentation(int i) { EDepSim::LogManager::fIndentation = std::max(i,0); } void EDepSim::LogManager::IncreaseIndentation() { ++EDepSim::LogManager::fIndentation; } void EDepSim::LogManager::DecreaseIndentation() { if (EDepSim::LogManager::fIndentation>0) --EDepSim::LogManager::fIndentation; } void EDepSim::LogManager::ResetIndentation() { EDepSim::LogManager::fIndentation = 0; } std::string EDepSim::LogManager::MakeIndent() { if (fIndentation<1) return ""; std::string indent = ""; for (int i=0; i<fIndentation; ++i) { indent += ".."; } indent += " "; return indent; } namespace { bool TranslateLogLevel(const std::string& name, EDepSim::LogManager::LogPriority& level) { if (name == "QuietLevel") { level = EDepSim::LogManager::QuietLevel; return true; } if (name == "LogLevel") { level = EDepSim::LogManager::LogLevel; return true; } if (name == "InfoLevel") { level = EDepSim::LogManager::InfoLevel; return true; } if (name == "VerboseLevel") { level = EDepSim::LogManager::VerboseLevel; return true; } return false; } bool TranslateErrorLevel(const std::string& name, EDepSim::LogManager::ErrorPriority& level) { if (name == "SilentLevel") { level = EDepSim::LogManager::SilentLevel; return true; } if (name == "ErrorLevel") { level = EDepSim::LogManager::ErrorLevel; return true; } if (name == "SevereLevel") { level = EDepSim::LogManager::SevereLevel; return true; } if (name == "WarnLevel") { level = EDepSim::LogManager::WarnLevel; return true; } if (name == "DebugLevel") { level = EDepSim::LogManager::DebugLevel; return true; } if (name == "TraceLevel") { level = EDepSim::LogManager::TraceLevel; return true; } return false; } std::ostream* StreamPointer(const std::string& name) { if (name == "STDCOUT") return &std::cout; if (name == "STDCERR") return &std::cerr; if (name[0] != '"') return NULL; if (name[name.size()-1] != '"') return NULL; std::string file = name.substr(1,name.size()-2); std::ofstream* output = new std::ofstream(file.c_str(), std::ios::out|std::ios::app); if (output->is_open()) return output; return NULL; } bool ReadConfigurationFile(const char* config) { std::ifstream input(config); if (!input.is_open()) return false; int inputLine = 0; for (;;) { std::string line; std::getline(input,line); if (input.eof()) break; // Save the current line number and cache the value so error // messages can be printed later. std::string cache(line); ++inputLine; // Strip the comments out of the file. std::string::size_type position = line.find("#"); if (position != std::string::npos) line.erase(position); // Strip the white space at the beginning of the line. line.erase(0,line.find_first_not_of("\t ")); // Skip lines that are too short. if (line.size()==0) continue; // Split the line into fields and a value. position = line.find("="); if (position == std::string::npos) { // Houston, we have a problem... There isn't a value. std::cerr << "WARNING: " << config << ":" << inputLine << ": " << "Configuration line missing an '='" << std::endl; std::cerr << " Line: <" << cache << ">" << std::endl; std::cerr << " Configuration line has been skip" << std::endl; continue; } // Split the value off the end of the line. std::string value = line.substr(position+1); line.erase(position); // Strip the white space at the beginning of the value. value.erase(0,value.find_first_not_of("\t ")); // Strip the white space at the end of the value. position = value.find_last_not_of("\t "); if (position != std::string::npos) value.erase(position+1); // Strip the white space at the end of the fields. position = line.find_last_not_of("\t "); if (position != std::string::npos) line.erase(position+1); // Split the remaining line in to fields. std::vector<std::string> fields; for (;;) { position = line.find("."); if (position == std::string::npos) { fields.push_back(line); break; } fields.push_back(line.substr(0,position)); line.erase(0,position+1); } // Process the fields and value. if (fields.size() == 2 && fields[0] == "log" && fields[1] == "file") { // Set the log file name. std::ostream* str = StreamPointer(value); if (!str) { std::cerr << "WARNING: " << config << ":" << inputLine << ": " << "Cannot open log stream." << std::endl; std::cerr << " Line: <" << cache << ">" << std::endl; std::cerr << " Configuration line has been skip" << std::endl; continue; } EDepSim::LogManager::SetLogStream(str); } else if (fields.size() == 2 && fields[0] == "error" && fields[1] == "file") { // Set the error file name. std::ostream* str = StreamPointer(value); if (!str) { std::cerr << "WARNING: " << config << ":" << inputLine << ": " << "Cannot open error stream." << std::endl; std::cerr << " Line: <" << cache << ">" << std::endl; std::cerr << " Configuration line has been skip" << std::endl; continue; } EDepSim::LogManager::SetDebugStream(str); } else if (fields.size() == 3 && fields[0] == "log" && fields[1] == "default" && fields[2] == "level") { // Set the default log level. EDepSim::LogManager::LogPriority level; if (!TranslateLogLevel(value,level)) { std::cerr << "WARNING: " << config << ":" << inputLine << ": " << "Unknown log level name." << std::endl; std::cerr << " Line: <" << cache << ">" << std::endl; std::cerr << " Configuration line has been skip" << std::endl; continue; } EDepSim::LogManager::SetLogLevel(level); } else if (fields.size() == 3 && fields[0] == "error" && fields[1] == "default" && fields[2] == "level") { // Set the default error level. EDepSim::LogManager::ErrorPriority level; if (!TranslateErrorLevel(value,level)) { std::cerr << "WARNING: " << config << ":" << inputLine << ": " << "Unknown error level name." << std::endl; std::cerr << " Line: <" << cache << ">" << std::endl; std::cerr << " Configuration line has been skip" << std::endl; continue; } EDepSim::LogManager::SetDebugLevel(level); } else if (fields.size() == 3 && fields[0] == "log" && fields[2] == "level") { // Set the log level. EDepSim::LogManager::LogPriority level; if (!TranslateLogLevel(value,level)) { std::cerr << "WARNING: " << config << ":" << inputLine << ": " << "Unknown log level name." << std::endl; std::cerr << " Line: <" << cache << ">" << std::endl; std::cerr << " Configuration line has been skip" << std::endl; continue; } EDepSim::LogManager::SetLogLevel(fields[1].c_str(),level); } else if (fields.size() == 3 && fields[0] == "error" && fields[2] == "level") { // Set the error level. EDepSim::LogManager::ErrorPriority level; if (!TranslateErrorLevel(value,level)) { std::cerr << "WARNING: " << config << ":" << inputLine << ": " << "Unknown error level name." << std::endl; std::cerr << " Line: <" << cache << ">" << std::endl; std::cerr << " Configuration line has been skip" << std::endl; continue; } EDepSim::LogManager::SetDebugLevel(fields[1].c_str(),level); } else { std::cerr << "WARNING: " << config << ":" << inputLine << ": " << "Unknown command." << std::endl; std::cerr << " Line: <" << cache << ">" << std::endl; std::cerr << " Configuration line has been skip" << std::endl; } } return true; } } void EDepSim::LogManager::Configure(const char* conf) { // Try to read a local configuration file. ReadConfigurationFile("./edeplog.config"); if (conf) { bool success = ReadConfigurationFile(conf); if (!success) EDepSimLog("EDepSim::Log configuration file was not read."); } }
38.318987
105
0.461879
andrewmogan
5f47d2228527a5b7377eab7235caf037f212e4b1
5,516
hpp
C++
examples/game_2d/src/helpers/spritemap.hpp
Turtwiggy/Cplusplus_game_engine
71f66c047b0802232a32ec113eb83b310aaec0ab
[ "Apache-2.0" ]
null
null
null
examples/game_2d/src/helpers/spritemap.hpp
Turtwiggy/Cplusplus_game_engine
71f66c047b0802232a32ec113eb83b310aaec0ab
[ "Apache-2.0" ]
null
null
null
examples/game_2d/src/helpers/spritemap.hpp
Turtwiggy/Cplusplus_game_engine
71f66c047b0802232a32ec113eb83b310aaec0ab
[ "Apache-2.0" ]
null
null
null
#pragma once // your proj headers #include "engine/maths_core.hpp" // other proj headers #include <glm/glm.hpp> #include <imgui.h> // standard lib #include <array> #include <map> #include <vector> namespace game2d { namespace sprite { enum class type { // row 0 EMPTY, BUSH_0, BUSH_1, BUSH_2, BUSH_3, BUSH_4, BUSH_5, BUSH_6, PERSON_0, PERSON_1, PERSON_2, PERSON_3, PERSON_4, PERSON_5, PERSON_6, PERSON_7, // row 1 TREE_1, TREE_2, TREE_3, TREE_4, TREE_5, TREE_6, TREE_7, TREE_8, CASTLE_FLOOR, // row 3 WALL_BIG, // row 5 // SQUARE, // use: EMPTY WEAPON_ARROW_1, WEAPON_ARROW_2, WEAPON_SHOVEL, WEAPON_PICKAXE, // row 6 ORC, WEAPON_DAGGER_OUTLINED_1, WEAPON_DAGGER_SOLID_3, // row 9 WEAPON_PISTOL, WEAPON_RAY_PISTOL, WEAPON_SHOTGUN, WEAPON_SUB_MACHINE_GUN, WEAPON_MINI_UZI, WEAPON_MP5, WEAPON_RPG, AMMO_BOX, // row 10 CAMPFIRE, FIRE, ICON_HEART, ICON_HEART_OUTLINE, ICON_HEART_HALF_FULL, ICON_HEART_FULL, // row 15 SKULL_AND_BONES, // row 17 NUMBER_0, NUMBER_1, NUMBER_2, NUMBER_3, NUMBER_4, NUMBER_5, NUMBER_6, NUMBER_7, NUMBER_8, NUMBER_9, // row 19 BOAT, // row 21 SPACE_VEHICLE_1, SPACE_VEHICLE_2, SPACE_VEHICLE_3, FIREWORK, ROCKET_1, ROCKET_2 }; struct spritemap { static inline std::map<type, glm::ivec2>& get_locations() { static std::map<type, glm::ivec2> ret; // row 0 ret[type::EMPTY] = { 0, 0 }; ret[type::BUSH_0] = { 1, 0 }; ret[type::BUSH_1] = { 2, 0 }; ret[type::BUSH_2] = { 3, 0 }; ret[type::BUSH_3] = { 4, 0 }; ret[type::BUSH_4] = { 5, 0 }; ret[type::BUSH_5] = { 6, 0 }; ret[type::BUSH_6] = { 7, 0 }; ret[type::PERSON_0] = { 24, 0 }; ret[type::PERSON_1] = { 25, 0 }; ret[type::PERSON_2] = { 26, 0 }; ret[type::PERSON_3] = { 27, 0 }; ret[type::PERSON_4] = { 28, 0 }; ret[type::PERSON_5] = { 29, 0 }; ret[type::PERSON_6] = { 30, 0 }; ret[type::PERSON_7] = { 31, 0 }; // row 1 ret[type::TREE_1] = { 0, 1 }; ret[type::TREE_2] = { 1, 1 }; ret[type::TREE_3] = { 2, 1 }; ret[type::TREE_4] = { 3, 1 }; ret[type::TREE_5] = { 4, 1 }; ret[type::TREE_6] = { 5, 1 }; ret[type::TREE_7] = { 6, 1 }; ret[type::TREE_8] = { 7, 1 }; ret[type::CASTLE_FLOOR] = { 19, 1 }; // row 3 ret[type::WALL_BIG] = { 2, 3 }; // row 5 // ret[type::SQUARE] = { 8, 5 }; // use EMPTY ret[type::WEAPON_ARROW_1] = { 40, 5 }; ret[type::WEAPON_ARROW_2] = { 41, 5 }; ret[type::WEAPON_SHOVEL] = { 42, 5 }; ret[type::WEAPON_PICKAXE] = { 42, 5 }; // row 6 ret[type::ORC] = { 30, 6 }; ret[type::WEAPON_DAGGER_OUTLINED_1] = { 32, 6 }; ret[type::WEAPON_DAGGER_SOLID_3] = { 34, 6 }; // row 9 ret[type::WEAPON_PISTOL] = { 37, 9 }; ret[type::WEAPON_RAY_PISTOL] = { 38, 9 }; ret[type::WEAPON_SHOTGUN] = { 39, 9 }; ret[type::WEAPON_SUB_MACHINE_GUN] = { 40, 9 }; ret[type::WEAPON_MINI_UZI] = { 41, 9 }; ret[type::WEAPON_MP5] = { 42, 9 }; ret[type::WEAPON_RPG] = { 43, 9 }; ret[type::AMMO_BOX] = { 44, 9 }; // row 10 ret[type::CAMPFIRE] = { 14, 10 }; ret[type::FIRE] = { 15, 10 }; ret[type::ICON_HEART] = { 39, 10 }; ret[type::ICON_HEART_OUTLINE] = { 40, 10 }; ret[type::ICON_HEART_HALF_FULL] = { 41, 10 }; ret[type::ICON_HEART_FULL] = { 42, 10 }; // row 15 ret[type::SKULL_AND_BONES] = { 0, 15 }; // row 17 ret[type::NUMBER_0] = { 35, 17 }; ret[type::NUMBER_1] = { 36, 17 }; ret[type::NUMBER_2] = { 37, 17 }; ret[type::NUMBER_3] = { 38, 17 }; ret[type::NUMBER_4] = { 39, 17 }; ret[type::NUMBER_5] = { 40, 17 }; ret[type::NUMBER_6] = { 41, 17 }; ret[type::NUMBER_7] = { 42, 17 }; ret[type::NUMBER_8] = { 43, 17 }; ret[type::NUMBER_9] = { 44, 17 }; // row 19 ret[type::BOAT] = { 10, 19 }; // row 21 ret[type::SPACE_VEHICLE_1] = { 12, 21 }; ret[type::SPACE_VEHICLE_2] = { 13, 21 }; ret[type::SPACE_VEHICLE_3] = { 14, 21 }; ret[type::FIREWORK] = { 32, 21 }; ret[type::ROCKET_1] = { 33, 21 }; ret[type::ROCKET_2] = { 34, 21 }; return ret; } static inline std::map<type, float>& get_rotations() { static std::map<type, float> ret; // row 5 // ret[type::SQUARE] = { 0.0f }; ret[type::WEAPON_ARROW_1] = { -engine::PI / 4.0f }; ret[type::WEAPON_ARROW_2] = { -engine::PI / 4.0f }; ret[type::WEAPON_SHOVEL] = { engine::PI / 4.0f }; ret[type::WEAPON_PICKAXE] = { -engine::PI / 8.0f }; // row 6 ret[type::WEAPON_DAGGER_OUTLINED_1] = { -engine::PI / 4.0f }; ret[type::WEAPON_DAGGER_SOLID_3] = { -engine::PI / 4.0f }; // row 9 ret[type::WEAPON_PISTOL] = { 0.0f }; ret[type::WEAPON_RAY_PISTOL] = { 0.0f }; ret[type::WEAPON_SHOTGUN] = { 0.0f }; ret[type::WEAPON_SUB_MACHINE_GUN] = { 0.0f }; ret[type::WEAPON_MINI_UZI] = { 0.0f }; ret[type::WEAPON_MP5] = { 0.0f }; ret[type::WEAPON_RPG] = { 0.0f }; return ret; } static inline glm::vec2 get_sprite_offset(const type& t) { auto& tiles = get_locations(); return tiles[t]; }; static inline float get_sprite_rotation_offset(const type& t) { auto& tiles = get_rotations(); return tiles[t]; }; }; } // namespace sprite // util std::vector<sprite::type> convert_int_to_sprites(int damage); std::array<ImVec2, 2> convert_sprite_to_uv(sprite::type type, float pixels, glm::ivec2 wh); } // namespace game2d
21.297297
69
0.569072
Turtwiggy
5f483e6a2426241ae8f199c6432fd9fd32c22e94
50
cpp
C++
src/engine/assets/handle_manager.cpp
invaderjon/gdev
3f5c5da22160c4980afd6099b0b4e06fdf106204
[ "Apache-2.0" ]
1
2018-10-20T22:08:59.000Z
2018-10-20T22:08:59.000Z
src/engine/assets/handle_manager.cpp
invaderjon/gdev
3f5c5da22160c4980afd6099b0b4e06fdf106204
[ "Apache-2.0" ]
null
null
null
src/engine/assets/handle_manager.cpp
invaderjon/gdev
3f5c5da22160c4980afd6099b0b4e06fdf106204
[ "Apache-2.0" ]
null
null
null
// handle_manager.cpp #include "handle_manager.h"
16.666667
27
0.78
invaderjon
5f51192d7ae5ce2fddb892ddd514ed9d99682870
648
cpp
C++
Practice4/Task2.cpp
zuza-rzemieniewska/Cpp_Practices
96cade6c757185a533ecbb5ffd26dff929df8d9a
[ "MIT" ]
null
null
null
Practice4/Task2.cpp
zuza-rzemieniewska/Cpp_Practices
96cade6c757185a533ecbb5ffd26dff929df8d9a
[ "MIT" ]
null
null
null
Practice4/Task2.cpp
zuza-rzemieniewska/Cpp_Practices
96cade6c757185a533ecbb5ffd26dff929df8d9a
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> using namespace std; int main(){ int n, i=1; float a, sum = 0; cout << "Enter the number of numbers you want to count the average of: " << endl; cin >> n; if(n<=0){ cout << "The number of numbers must be positive!" << endl; cin >> n; } /* while(i<=n){ cout << "Enter numer: "; cin >> a; sum += a; i++; } */ for(i; i<=n; i++){ cout << "Enter numer: "; cin >> a; sum += a; } cout << "Arithmentic mean of " << n << " numbers is " << sum/n << endl; return 0; }
17.513514
86
0.433642
zuza-rzemieniewska
34fddf34fae9c8837fca2744dba4fd2b975db32d
1,203
hpp
C++
include/ValkyrieEngine/Util.hpp
VD-15/Valkyrie-Engine
2287568e24b3ab20dff4feecbbf523c2fbbced65
[ "MIT" ]
2
2020-06-18T21:32:29.000Z
2021-01-29T04:16:47.000Z
include/ValkyrieEngine/Util.hpp
VD-15/Valkyrie-Engine
2287568e24b3ab20dff4feecbbf523c2fbbced65
[ "MIT" ]
13
2020-02-02T19:00:15.000Z
2020-02-08T18:32:06.000Z
include/ValkyrieEngine/Util.hpp
VD-15/Valkyrie-Engine
2287568e24b3ab20dff4feecbbf523c2fbbced65
[ "MIT" ]
null
null
null
#ifndef VLK_UTIL_HPP #define VLK_UTIL_HPP #include <type_traits> namespace vlk { //Using `typename` keyword for templates like this is a C++17 extension /*! * \brief Is specialization template class * * Evaluates to <tt>std::true_type</tt> if template parameter <tt>T</tt> is a specialization of template class <tt>Primary</tt>. Otherwise evaluates to <tt>std::false_type</tt> */ template <class T, template<class...> class Primary> struct IsSpecialization : std::false_type {}; /*! * \copydoc vlk::IsSpecialization */ template <template <class...> class Primary, class... Args> struct IsSpecialization<Primary<Args...>, Primary> : std::true_type {}; /*! * \brief Extract parameter template class * * Extracts the template parameter of a template type <tt>T</tt>. * If <tt>T</tt> is not a template, <tt>type</tt> evaluates to <tt>T</tt>. * If <tt>T</tt> is a template of the form <tt>T\<S\></tt>, then <tt>type</tt> evaluates to <tt>S</tt>. */ template <class T> struct ExtractParameter { typedef T type; }; /*! * \copydoc vlk::ExtractParameter */ template <template <class> class T, class S> struct ExtractParameter<T<S>> { typedef S type; }; } #endif
27.976744
177
0.678304
VD-15
5500d43ef5b031fe38a3ccbd49fce332f8e78ac9
1,336
cpp
C++
sources/names.cpp
malytomas/unnatural-planets
57ad1a48629a37f95ff729b75f8aaf439e209093
[ "MIT" ]
1
2021-03-01T21:49:24.000Z
2021-03-01T21:49:24.000Z
sources/names.cpp
malytomas/unnatural-planets
57ad1a48629a37f95ff729b75f8aaf439e209093
[ "MIT" ]
2
2020-07-13T10:57:27.000Z
2021-02-24T21:10:09.000Z
sources/names.cpp
malytomas/unnatural-planets
57ad1a48629a37f95ff729b75f8aaf439e209093
[ "MIT" ]
null
null
null
#include <cage-core/math.h> #include <cage-core/string.h> using namespace cage; namespace { constexpr const char *Prefixes[] = { "bel", "nar", "xan", "bell", "natr", "ev", }; constexpr const char *Stems[] = { "adur", "aes", "anim", "apoll", "imac", "educ", "equis", "extr", "guius", "hann", "equi", "amora", "hum", "iace", "ille", "inept", "iuv", "obe", "ocul", "orbis", }; constexpr const char *Suffixes[] = { "us", "ix", "ox", "ith", "ath", "um", "ator", "or", "axia", "imus", "ais", "itur", "orex", "o", "y", }; constexpr const char *Appendixes[] = { " I", " II", " III", " IV", " V", " VI", " VII", " VIII", " IX", " X", }; #define PICK(NAMES) NAMES[randomRange(std::size_t(0), sizeof(NAMES)/sizeof(NAMES[0]))] String generateNameImpl() { Stringizer name; if (randomChance() < 0.5) name + PICK(Prefixes); if (randomChance() < 0.8) name + PICK(Stems); if (randomChance() < 0.1) name + PICK(Stems); if (randomChance() < 0.5) name + PICK(Suffixes); if (String(name).length() < 3) return generateNameImpl(); if (randomChance() < 0.1) name = Stringizer() + reverse(String(name)); if (randomChance() < 0.4) name + PICK(Appendixes); return name; } } String generateName() { String name = generateNameImpl(); name[0] = toUpper(String(name[0]))[0]; return name; }
24.290909
86
0.574102
malytomas
550426813a3db89ca22113035ac8bf7e59553647
3,142
hpp
C++
include/codegen/include/System/Array_SorterObjectArray.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/Array_SorterObjectArray.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/Array_SorterObjectArray.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Array #include "System/Array.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections namespace System::Collections { // Forward declaring type: IComparer class IComparer; } // Completed forward declares // Type namespace: System namespace System { // Autogenerated type: System.Array/SorterObjectArray struct Array::SorterObjectArray : public System::ValueType { public: // private System.Object[] keys // Offset: 0x0 ::Array<::Il2CppObject*>* keys; // private System.Object[] items // Offset: 0x8 ::Array<::Il2CppObject*>* items; // private System.Collections.IComparer comparer // Offset: 0x10 System::Collections::IComparer* comparer; // Creating value type constructor for type: SorterObjectArray SorterObjectArray(::Array<::Il2CppObject*>* keys_ = {}, ::Array<::Il2CppObject*>* items_ = {}, System::Collections::IComparer* comparer_ = {}) : keys{keys_}, items{items_}, comparer{comparer_} {} // System.Void .ctor(System.Object[] keys, System.Object[] items, System.Collections.IComparer comparer) // Offset: 0xA46144 static Array::SorterObjectArray* New_ctor(::Array<::Il2CppObject*>* keys, ::Array<::Il2CppObject*>* items, System::Collections::IComparer* comparer); // System.Void SwapIfGreaterWithItems(System.Int32 a, System.Int32 b) // Offset: 0xA4614C void SwapIfGreaterWithItems(int a, int b); // private System.Void Swap(System.Int32 i, System.Int32 j) // Offset: 0xA46154 void Swap(int i, int j); // System.Void Sort(System.Int32 left, System.Int32 length) // Offset: 0xA4615C void Sort(int left, int length); // private System.Void IntrospectiveSort(System.Int32 left, System.Int32 length) // Offset: 0xA46164 void IntrospectiveSort(int left, int length); // private System.Void IntroSort(System.Int32 lo, System.Int32 hi, System.Int32 depthLimit) // Offset: 0xA4616C void IntroSort(int lo, int hi, int depthLimit); // private System.Int32 PickPivotAndPartition(System.Int32 lo, System.Int32 hi) // Offset: 0xA46174 int PickPivotAndPartition(int lo, int hi); // private System.Void Heapsort(System.Int32 lo, System.Int32 hi) // Offset: 0xA4617C void Heapsort(int lo, int hi); // private System.Void DownHeap(System.Int32 i, System.Int32 n, System.Int32 lo) // Offset: 0xA46184 void DownHeap(int i, int n, int lo); // private System.Void InsertionSort(System.Int32 lo, System.Int32 hi) // Offset: 0xA4618C void InsertionSort(int lo, int hi); }; // System.Array/SorterObjectArray } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(System::Array::SorterObjectArray, "System", "Array/SorterObjectArray"); #pragma pack(pop)
44.253521
199
0.699236
Futuremappermydud
550d2001921a86a72e4fb90ade31e07c845639d0
610
hpp
C++
include/anisthesia/player.hpp
swiftcitrus/anisthesia
981c821d51b1115311eee9fba01dc93210dd757b
[ "MIT" ]
33
2017-02-07T00:03:31.000Z
2022-02-09T12:06:52.000Z
include/anisthesia/player.hpp
swiftcitrus/anisthesia
981c821d51b1115311eee9fba01dc93210dd757b
[ "MIT" ]
7
2017-07-26T22:40:22.000Z
2022-01-30T08:05:51.000Z
include/anisthesia/player.hpp
swiftcitrus/anisthesia
981c821d51b1115311eee9fba01dc93210dd757b
[ "MIT" ]
9
2017-08-05T10:33:05.000Z
2021-10-03T00:23:21.000Z
#pragma once #include <string> #include <vector> namespace anisthesia { enum class Strategy { WindowTitle, OpenFiles, UiAutomation, }; enum class PlayerType { Default, WebBrowser, }; struct Player { PlayerType type = PlayerType::Default; std::string name; std::string window_title_format; std::vector<std::string> windows; std::vector<std::string> executables; std::vector<Strategy> strategies; }; bool ParsePlayersData(const std::string& data, std::vector<Player>& players); bool ParsePlayersFile(const std::string& path, std::vector<Player>& players); } // namespace anisthesia
19.0625
77
0.727869
swiftcitrus
551189f990bff99aba9835310a35ecc5267a7297
1,113
cpp
C++
tests-batch/net/launchSwapClient.cpp
dtorban/MinVR_Old
8b09ba1a61f6dcef051c5dd8d3f3e607ee55955d
[ "BSD-3-Clause" ]
18
2016-08-04T16:09:52.000Z
2022-01-17T15:43:37.000Z
tests-batch/net/launchSwapClient.cpp
OpenSpace/MinVR
17b4f3bd57cefd07f99159288069f01713053054
[ "BSD-3-Clause" ]
123
2015-01-08T17:32:39.000Z
2021-12-22T00:55:00.000Z
tests-batch/net/launchSwapClient.cpp
OpenSpace/MinVR
17b4f3bd57cefd07f99159288069f01713053054
[ "BSD-3-Clause" ]
21
2016-11-04T18:36:29.000Z
2022-03-01T19:44:11.000Z
#include "net/VRNetClient.h" #ifdef WIN32 #include <process.h> #define getpid _getpid #endif // Program to launch one VRNetClient that connects to server. Created // client executes syncSwapBuffersAcrossAllNodes. The program is // intended to be executed by a forked child process in the network // tests. We do this in a separate program because of limitations of // execl() that are made less limiting when it simply starts up a new // binary. int main(int argc, char* argv[]) { MinVR::VRNetClient client = MinVR::VRNetClient("localhost", "3490"); // Get the client number from the argv list and the process ID. std::stringstream clientIDstring; clientIDstring << "client " << std::string(argv[1]) << ", pid = " << getpid(); // Make the swap buffers request. std::cout << "launchSwapClient: sync swap buffers request from " << clientIDstring.str() << std::endl; for (int i = 0; i < 10; i++) { client.syncSwapBuffersAcrossAllNodes(); std::cout << "launchSwapClient: swap request " << i << " received, " << clientIDstring.str() << std::endl; } exit(0); }
32.735294
80
0.679245
dtorban
5517ed72ba6dcfa449db9440d7378dbd6e212161
669
cpp
C++
_site/Competitive Programming/Codeforces/1136B.cpp
anujkyadav07/anuj-k-yadav.github.io
ac5cccc8cdada000ba559538cd84921437b3c5e6
[ "MIT" ]
1
2019-06-10T04:39:49.000Z
2019-06-10T04:39:49.000Z
_site/Competitive Programming/Codeforces/1136B.cpp
anujkyadav07/anuj-k-yadav.github.io
ac5cccc8cdada000ba559538cd84921437b3c5e6
[ "MIT" ]
2
2021-09-27T23:34:07.000Z
2022-02-26T05:54:27.000Z
_site/Competitive Programming/Codeforces/1136B.cpp
anujkyadav07/anuj-k-yadav.github.io
ac5cccc8cdada000ba559538cd84921437b3c5e6
[ "MIT" ]
3
2019-06-23T14:15:08.000Z
2019-07-09T20:40:58.000Z
#include "bits/stdc++.h" #ifdef PRINTERS #include "printers.hpp" using namespace printers; #define tr(a) cerr<<#a<<" : "<<a<<endl #else #define tr(a) #endif #define ll long long #define pb push_back #define mp make_pair #define pii pair<int,int> #define vi vector<int> #define all(a) (a).begin(),(a).end() #define F first #define S second #define sz(x) (int)x.size() #define hell 1000000007 #define endl '\n' #define rep(i,a,b) for(int i=a;i<b;i++) using namespace std; int main(){ ll n, k; cin>>n>>k; cout<<3*n + min(n-k, k-1)<<"\n"; //cout<<n-v[k]+1<<"\n"; }
20.90625
44
0.544096
anujkyadav07
551987d7d2abd0f6f163c02e0b95d9364cd025b5
424
cpp
C++
src/io/screen/screen.cpp
fishjump/osdevc_libinit
7221beb9c2a9035d3a24b90a9993fb73ee4063c3
[ "MIT" ]
null
null
null
src/io/screen/screen.cpp
fishjump/osdevc_libinit
7221beb9c2a9035d3a24b90a9993fb73ee4063c3
[ "MIT" ]
null
null
null
src/io/screen/screen.cpp
fishjump/osdevc_libinit
7221beb9c2a9035d3a24b90a9993fb73ee4063c3
[ "MIT" ]
null
null
null
#include <global/global.hpp> #include "../../lazyload.hpp" namespace { lazyload<system::io::entity::Screen> gobalScreen; } // namespace namespace system::global { namespace init { void initScreen() { gobalScreen.init(); } } // namespace init namespace instance { system::io::entity::Screen *getScreen() { return gobalScreen.get(); } } // namespace instance } // namespace system::global
18.434783
49
0.653302
fishjump
551b7262d22290ae2294c9e79a7a5bed441c8187
1,141
cpp
C++
Algorithms/Src/String.cpp
ikarusx/ModernCpp
8c0111dec2d0a2a183250e2f9594573b99687ec5
[ "MIT" ]
null
null
null
Algorithms/Src/String.cpp
ikarusx/ModernCpp
8c0111dec2d0a2a183250e2f9594573b99687ec5
[ "MIT" ]
null
null
null
Algorithms/Src/String.cpp
ikarusx/ModernCpp
8c0111dec2d0a2a183250e2f9594573b99687ec5
[ "MIT" ]
null
null
null
#include "Precompiled.hpp" #include "String.hpp" #include <limits> #include <string> #include <iostream> using namespace Algorithms; namespace { static const auto speedup = []() { std::ios::sync_with_stdio(false); std::cin.tie(NULL); return 0; }(); } // No std algorithms. int String::AToI(std::string str) { int size = static_cast<int>(str.size()); if (size == 0) { return 0; } int currIndex = str.find_first_not_of(' '); if (currIndex >= size) { return 0; } bool isPositive = str[currIndex] != '-'; if (!(isPositive && str[currIndex] != '+')) { ++currIndex; } int res = 0; int maxVal = (std::numeric_limits<int>::max)(); int maxValBy10 = maxVal / 10; //isDigit while (currIndex < size && str[currIndex] >= '0' && str[currIndex] <= '9') { int tempRes = res * 10; int currVal = static_cast<int>(str[currIndex++] - '0'); // Check if it will go oob (* and +). if (res > maxValBy10 || tempRes > maxVal - currVal) { return isPositive ? (std::numeric_limits<int>::max)() : (std::numeric_limits<int>::min)(); } res = tempRes + currVal; } return isPositive ? res : -res; }
16.779412
75
0.608238
ikarusx
551c3f2f5b73aa74c9961befe28aa3cc7891c65b
645
cpp
C++
docs/cpp/codesnippet/CPP/how-to-create-and-use-shared-ptr-instances_6.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
965
2017-06-25T23:57:11.000Z
2022-03-31T14:17:32.000Z
docs/cpp/codesnippet/CPP/how-to-create-and-use-shared-ptr-instances_6.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
3,272
2017-06-24T00:26:34.000Z
2022-03-31T22:14:07.000Z
docs/cpp/codesnippet/CPP/how-to-create-and-use-shared-ptr-instances_6.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
951
2017-06-25T12:36:14.000Z
2022-03-26T22:49:06.000Z
// Initialize two separate raw pointers. // Note that they contain the same values. auto song1 = new Song(L"Village People", L"YMCA"); auto song2 = new Song(L"Village People", L"YMCA"); // Create two unrelated shared_ptrs. shared_ptr<Song> p1(song1); shared_ptr<Song> p2(song2); // Unrelated shared_ptrs are never equal. wcout << "p1 < p2 = " << std::boolalpha << (p1 < p2) << endl; wcout << "p1 == p2 = " << std::boolalpha <<(p1 == p2) << endl; // Related shared_ptr instances are always equal. shared_ptr<Song> p3(p2); wcout << "p3 == p2 = " << std::boolalpha << (p3 == p2) << endl;
37.941176
68
0.593798
bobbrow
551d2a06b3e733b0bdca497ed5cb7f28a173baf1
18,865
hpp
C++
src/date.hpp
quantlibnode/quantlibnode
b50348131af77a2b6c295f44ef3245daf05c4afc
[ "MIT" ]
27
2016-11-19T16:51:21.000Z
2021-09-08T16:44:15.000Z
src/date.hpp
quantlibnode/quantlibnode
b50348131af77a2b6c295f44ef3245daf05c4afc
[ "MIT" ]
1
2016-12-28T16:38:38.000Z
2017-02-17T05:32:13.000Z
src/date.hpp
quantlibnode/quantlibnode
b50348131af77a2b6c295f44ef3245daf05c4afc
[ "MIT" ]
10
2016-12-28T02:31:38.000Z
2021-06-15T09:02:07.000Z
/* Copyright (C) 2016 -2017 Jerry Jin */ #ifndef date_h #define date_h #include <nan.h> #include <string> #include <queue> #include <utility> #include "../quantlibnode.hpp" #include <oh/objecthandler.hpp> using namespace node; using namespace v8; using namespace std; class PeriodFromFrequencyWorker : public Nan::AsyncWorker { public: string mFrequency; string mReturnValue; string mError; PeriodFromFrequencyWorker( Nan::Callback *callback ,string Frequency ): Nan::AsyncWorker(callback) ,mFrequency(Frequency) { }; //~PeriodFromFrequencyWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class FrequencyFromPeriodWorker : public Nan::AsyncWorker { public: std::vector<ObjectHandler::property_t> mPeriod; std::vector<string> mReturnValue; string mError; FrequencyFromPeriodWorker( Nan::Callback *callback ,std::vector<ObjectHandler::property_t> Period ): Nan::AsyncWorker(callback) ,mPeriod(Period) { }; //~FrequencyFromPeriodWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class PeriodLessThanWorker : public Nan::AsyncWorker { public: string mPeriod1; string mPeriod2; bool mReturnValue; string mError; PeriodLessThanWorker( Nan::Callback *callback ,string Period1 ,string Period2 ): Nan::AsyncWorker(callback) ,mPeriod1(Period1) ,mPeriod2(Period2) { }; //~PeriodLessThanWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class PeriodEquivalentWorker : public Nan::AsyncWorker { public: string mPeriod; string mReturnValue; string mError; PeriodEquivalentWorker( Nan::Callback *callback ,string Period ): Nan::AsyncWorker(callback) ,mPeriod(Period) { }; //~PeriodEquivalentWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class DateMinDateWorker : public Nan::AsyncWorker { public: long mReturnValue; string mError; DateMinDateWorker( Nan::Callback *callback ): Nan::AsyncWorker(callback) { }; //~DateMinDateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class DateMaxDateWorker : public Nan::AsyncWorker { public: long mReturnValue; string mError; DateMaxDateWorker( Nan::Callback *callback ): Nan::AsyncWorker(callback) { }; //~DateMaxDateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class DateIsLeapWorker : public Nan::AsyncWorker { public: std::vector<long> mYear; std::vector<bool> mReturnValue; string mError; DateIsLeapWorker( Nan::Callback *callback ,std::vector<long> Year ): Nan::AsyncWorker(callback) ,mYear(Year) { }; //~DateIsLeapWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class DateEndOfMonthWorker : public Nan::AsyncWorker { public: std::vector<ObjectHandler::property_t> mDate; std::vector<long> mReturnValue; string mError; DateEndOfMonthWorker( Nan::Callback *callback ,std::vector<ObjectHandler::property_t> Date ): Nan::AsyncWorker(callback) ,mDate(Date) { }; //~DateEndOfMonthWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class DateIsEndOfMonthWorker : public Nan::AsyncWorker { public: std::vector<ObjectHandler::property_t> mDate; std::vector<bool> mReturnValue; string mError; DateIsEndOfMonthWorker( Nan::Callback *callback ,std::vector<ObjectHandler::property_t> Date ): Nan::AsyncWorker(callback) ,mDate(Date) { }; //~DateIsEndOfMonthWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class DateNextWeekdayWorker : public Nan::AsyncWorker { public: std::vector<ObjectHandler::property_t> mDate; string mWeekday; std::vector<long> mReturnValue; string mError; DateNextWeekdayWorker( Nan::Callback *callback ,std::vector<ObjectHandler::property_t> Date ,string Weekday ): Nan::AsyncWorker(callback) ,mDate(Date) ,mWeekday(Weekday) { }; //~DateNextWeekdayWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class DateNthWeekdayWorker : public Nan::AsyncWorker { public: long mNth; string mWeekday; string mMonth; long mYear; long mReturnValue; string mError; DateNthWeekdayWorker( Nan::Callback *callback ,long Nth ,string Weekday ,string Month ,long Year ): Nan::AsyncWorker(callback) ,mNth(Nth) ,mWeekday(Weekday) ,mMonth(Month) ,mYear(Year) { }; //~DateNthWeekdayWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class IMMIsIMMdateWorker : public Nan::AsyncWorker { public: std::vector<ObjectHandler::property_t> mDate; bool mMainCycle; std::vector<bool> mReturnValue; string mError; IMMIsIMMdateWorker( Nan::Callback *callback ,std::vector<ObjectHandler::property_t> Date ,bool MainCycle ): Nan::AsyncWorker(callback) ,mDate(Date) ,mMainCycle(MainCycle) { }; //~IMMIsIMMdateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class IMMIsIMMcodeWorker : public Nan::AsyncWorker { public: std::vector<string> mCode; bool mMainCycle; std::vector<bool> mReturnValue; string mError; IMMIsIMMcodeWorker( Nan::Callback *callback ,std::vector<string> Code ,bool MainCycle ): Nan::AsyncWorker(callback) ,mCode(Code) ,mMainCycle(MainCycle) { }; //~IMMIsIMMcodeWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class IMMcodeWorker : public Nan::AsyncWorker { public: std::vector<ObjectHandler::property_t> mIMMdate; std::vector<string> mReturnValue; string mError; IMMcodeWorker( Nan::Callback *callback ,std::vector<ObjectHandler::property_t> IMMdate ): Nan::AsyncWorker(callback) ,mIMMdate(IMMdate) { }; //~IMMcodeWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class IMMNextCodeWorker : public Nan::AsyncWorker { public: ObjectHandler::property_t mRefDate; bool mMainCycle; string mReturnValue; string mError; IMMNextCodeWorker( Nan::Callback *callback ,ObjectHandler::property_t RefDate ,bool MainCycle ): Nan::AsyncWorker(callback) ,mRefDate(RefDate) ,mMainCycle(MainCycle) { }; //~IMMNextCodeWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class IMMNextCodesWorker : public Nan::AsyncWorker { public: ObjectHandler::property_t mRefDate; std::vector<bool> mMainCycle; std::vector<string> mReturnValue; string mError; IMMNextCodesWorker( Nan::Callback *callback ,ObjectHandler::property_t RefDate ,std::vector<bool> MainCycle ): Nan::AsyncWorker(callback) ,mRefDate(RefDate) ,mMainCycle(MainCycle) { }; //~IMMNextCodesWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class IMMdateWorker : public Nan::AsyncWorker { public: std::vector<string> mIMMcode; ObjectHandler::property_t mRefDate; std::vector<long> mReturnValue; string mError; IMMdateWorker( Nan::Callback *callback ,std::vector<string> IMMcode ,ObjectHandler::property_t RefDate ): Nan::AsyncWorker(callback) ,mIMMcode(IMMcode) ,mRefDate(RefDate) { }; //~IMMdateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class IMMNextDateWorker : public Nan::AsyncWorker { public: ObjectHandler::property_t mRefDate; bool mMainCycle; long mReturnValue; string mError; IMMNextDateWorker( Nan::Callback *callback ,ObjectHandler::property_t RefDate ,bool MainCycle ): Nan::AsyncWorker(callback) ,mRefDate(RefDate) ,mMainCycle(MainCycle) { }; //~IMMNextDateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class IMMNextDatesWorker : public Nan::AsyncWorker { public: ObjectHandler::property_t mRefDate; std::vector<bool> mMainCycle; std::vector<long> mReturnValue; string mError; IMMNextDatesWorker( Nan::Callback *callback ,ObjectHandler::property_t RefDate ,std::vector<bool> MainCycle ): Nan::AsyncWorker(callback) ,mRefDate(RefDate) ,mMainCycle(MainCycle) { }; //~IMMNextDatesWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ASXIsASXdateWorker : public Nan::AsyncWorker { public: std::vector<ObjectHandler::property_t> mDate; bool mMainCycle; std::vector<bool> mReturnValue; string mError; ASXIsASXdateWorker( Nan::Callback *callback ,std::vector<ObjectHandler::property_t> Date ,bool MainCycle ): Nan::AsyncWorker(callback) ,mDate(Date) ,mMainCycle(MainCycle) { }; //~ASXIsASXdateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ASXIsASXcodeWorker : public Nan::AsyncWorker { public: std::vector<string> mCode; bool mMainCycle; std::vector<bool> mReturnValue; string mError; ASXIsASXcodeWorker( Nan::Callback *callback ,std::vector<string> Code ,bool MainCycle ): Nan::AsyncWorker(callback) ,mCode(Code) ,mMainCycle(MainCycle) { }; //~ASXIsASXcodeWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ASXcodeWorker : public Nan::AsyncWorker { public: std::vector<ObjectHandler::property_t> mASXdate; std::vector<string> mReturnValue; string mError; ASXcodeWorker( Nan::Callback *callback ,std::vector<ObjectHandler::property_t> ASXdate ): Nan::AsyncWorker(callback) ,mASXdate(ASXdate) { }; //~ASXcodeWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ASXNextCodeWorker : public Nan::AsyncWorker { public: ObjectHandler::property_t mRefDate; bool mMainCycle; string mReturnValue; string mError; ASXNextCodeWorker( Nan::Callback *callback ,ObjectHandler::property_t RefDate ,bool MainCycle ): Nan::AsyncWorker(callback) ,mRefDate(RefDate) ,mMainCycle(MainCycle) { }; //~ASXNextCodeWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ASXNextCodesWorker : public Nan::AsyncWorker { public: ObjectHandler::property_t mRefDate; std::vector<bool> mMainCycle; std::vector<string> mReturnValue; string mError; ASXNextCodesWorker( Nan::Callback *callback ,ObjectHandler::property_t RefDate ,std::vector<bool> MainCycle ): Nan::AsyncWorker(callback) ,mRefDate(RefDate) ,mMainCycle(MainCycle) { }; //~ASXNextCodesWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ASXdateWorker : public Nan::AsyncWorker { public: std::vector<string> mASXcode; ObjectHandler::property_t mRefDate; std::vector<long> mReturnValue; string mError; ASXdateWorker( Nan::Callback *callback ,std::vector<string> ASXcode ,ObjectHandler::property_t RefDate ): Nan::AsyncWorker(callback) ,mASXcode(ASXcode) ,mRefDate(RefDate) { }; //~ASXdateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ASXNextDateWorker : public Nan::AsyncWorker { public: ObjectHandler::property_t mRefDate; bool mMainCycle; long mReturnValue; string mError; ASXNextDateWorker( Nan::Callback *callback ,ObjectHandler::property_t RefDate ,bool MainCycle ): Nan::AsyncWorker(callback) ,mRefDate(RefDate) ,mMainCycle(MainCycle) { }; //~ASXNextDateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ASXNextDatesWorker : public Nan::AsyncWorker { public: ObjectHandler::property_t mRefDate; std::vector<bool> mMainCycle; std::vector<long> mReturnValue; string mError; ASXNextDatesWorker( Nan::Callback *callback ,ObjectHandler::property_t RefDate ,std::vector<bool> MainCycle ): Nan::AsyncWorker(callback) ,mRefDate(RefDate) ,mMainCycle(MainCycle) { }; //~ASXNextDatesWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ECBKnownDatesWorker : public Nan::AsyncWorker { public: std::vector<long> mReturnValue; string mError; ECBKnownDatesWorker( Nan::Callback *callback ): Nan::AsyncWorker(callback) { }; //~ECBKnownDatesWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ECBAddDateWorker : public Nan::AsyncWorker { public: ObjectHandler::property_t mDate; string mError; ECBAddDateWorker( Nan::Callback *callback ,ObjectHandler::property_t Date ): Nan::AsyncWorker(callback) ,mDate(Date) { }; //~ECBAddDateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ECBRemoveDateWorker : public Nan::AsyncWorker { public: ObjectHandler::property_t mDate; string mError; ECBRemoveDateWorker( Nan::Callback *callback ,ObjectHandler::property_t Date ): Nan::AsyncWorker(callback) ,mDate(Date) { }; //~ECBRemoveDateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ECBdate2Worker : public Nan::AsyncWorker { public: string mMonth; long mYear; long mReturnValue; string mError; ECBdate2Worker( Nan::Callback *callback ,string Month ,long Year ): Nan::AsyncWorker(callback) ,mMonth(Month) ,mYear(Year) { }; //~ECBdate2Worker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ECBdateWorker : public Nan::AsyncWorker { public: string mECBcode; ObjectHandler::property_t mRefDate; long mReturnValue; string mError; ECBdateWorker( Nan::Callback *callback ,string ECBcode ,ObjectHandler::property_t RefDate ): Nan::AsyncWorker(callback) ,mECBcode(ECBcode) ,mRefDate(RefDate) { }; //~ECBdateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ECBcodeWorker : public Nan::AsyncWorker { public: ObjectHandler::property_t mECBdate; string mReturnValue; string mError; ECBcodeWorker( Nan::Callback *callback ,ObjectHandler::property_t ECBdate ): Nan::AsyncWorker(callback) ,mECBdate(ECBdate) { }; //~ECBcodeWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ECBNextDateWorker : public Nan::AsyncWorker { public: ObjectHandler::property_t mDate; long mReturnValue; string mError; ECBNextDateWorker( Nan::Callback *callback ,ObjectHandler::property_t Date ): Nan::AsyncWorker(callback) ,mDate(Date) { }; //~ECBNextDateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ECBNextDate2Worker : public Nan::AsyncWorker { public: string mCode; long mReturnValue; string mError; ECBNextDate2Worker( Nan::Callback *callback ,string Code ): Nan::AsyncWorker(callback) ,mCode(Code) { }; //~ECBNextDate2Worker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ECBNextDatesWorker : public Nan::AsyncWorker { public: ObjectHandler::property_t mDate; std::vector<long> mReturnValue; string mError; ECBNextDatesWorker( Nan::Callback *callback ,ObjectHandler::property_t Date ): Nan::AsyncWorker(callback) ,mDate(Date) { }; //~ECBNextDatesWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ECBIsECBdateWorker : public Nan::AsyncWorker { public: std::vector<ObjectHandler::property_t> mDate; std::vector<bool> mReturnValue; string mError; ECBIsECBdateWorker( Nan::Callback *callback ,std::vector<ObjectHandler::property_t> Date ): Nan::AsyncWorker(callback) ,mDate(Date) { }; //~ECBIsECBdateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ECBIsECBcodeWorker : public Nan::AsyncWorker { public: std::vector<string> mCode; std::vector<bool> mReturnValue; string mError; ECBIsECBcodeWorker( Nan::Callback *callback ,std::vector<string> Code ): Nan::AsyncWorker(callback) ,mCode(Code) { }; //~ECBIsECBcodeWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ECBNextCodeWorker : public Nan::AsyncWorker { public: ObjectHandler::property_t mRefDate; string mReturnValue; string mError; ECBNextCodeWorker( Nan::Callback *callback ,ObjectHandler::property_t RefDate ): Nan::AsyncWorker(callback) ,mRefDate(RefDate) { }; //~ECBNextCodeWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class ECBNextCode2Worker : public Nan::AsyncWorker { public: string mCode; string mReturnValue; string mError; ECBNextCode2Worker( Nan::Callback *callback ,string Code ): Nan::AsyncWorker(callback) ,mCode(Code) { }; //~ECBNextCode2Worker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; #endif
15.826342
59
0.616539
quantlibnode
551f1694353d2b86cc15f39bc78274bac6675a04
3,157
cpp
C++
competitive programming/codechef/TREE2.cpp
sureshmangs/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
16
2020-06-02T19:22:45.000Z
2022-02-05T10:35:28.000Z
competitive programming/codechef/TREE2.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
null
null
null
competitive programming/codechef/TREE2.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
2
2020-08-27T17:40:06.000Z
2022-02-05T10:33:52.000Z
/* On a sunny day, Akbar and Birbal were taking a leisurely walk in palace gardens. Suddenly, Akbar noticed a bunch of sticks on the ground and decided to test Birbal's wits. There are N stick holders with negligible size (numbered 1 through N) in a row on the ground. Akbar places all the sticks in them vertically; for each valid i, the initial height of the stick in the i-th holder is Ai. Birbal has a stick cutter and his task is to completely cut all these sticks, i.e. reduce the heights of all sticks to 0. He may perform zero or more operations; in each operation, he should do the following: Choose an integer H and fix the cutter at the height H above the ground. The cutter moves from the 1-st to the N-th stick holder. Whenever it encounters a stick whose current height is greater than H, it cuts this stick down to height H (i.e. for a stick with height h>H, it removes its upper part with length h−H). All the upper parts of sticks that are cut in one operation must have equal lengths. Otherwise, the operation may not be performed. For example, if the heights of sticks are initially [5,3,5], then some valid values for H in the first operation are 3 and 4 ― the cutter cuts the upper parts of two sticks and their lengths are [2,2] and [1,1] respectively. H=2 is an invalid choice because it would cut the upper parts of all three sticks with lengths [3,1,3], which are not all equal. Akbar wants Birbal to completely cut all sticks in the minimum possible number of operations. If you want to be friends with Birbal, help him solve the problem. Input The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N. The second line contains N space-separated integers A1,A2,…,AN. Output For each test case, print a single line containing one integer ― the minimum number of operations needed to completely cut all the sticks. Constraints 1≤T≤50 1≤N≤105 0≤Ai≤109 for each valid i Subtasks Subtask #1 (20 points): N≤50 Subtask #2 (80 points): original constraints Example Input 1 3 1 2 3 Example Output 3 Explanation Example case 1: Birbal may perform the following three operations: Fix the cutter at H=2. The heights of the sticks after this operation are [1,2,2]. Fix the cutter at H=1. The heights of the sticks after this operation are [1,1,1]. Fix the cutter at H=0. After this operation, all sticks are completely cut. */ #include<bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin>>t; while(t--){ int n; cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; priority_queue<int> q; // max heap for(int i=0;i<n;i++){ if(a[i]!=0) q.push(a[i]); } int cnt=0; while(!q.empty()){ int tmp=q.top(); q.pop(); if(!q.empty() && q.top()==tmp) continue; cnt++; if(q.empty()==true) break; tmp=tmp-(tmp-q.top()); } cout<<cnt<<endl; } return 0; }
36.709302
426
0.69528
sureshmangs
5520f325dbed7501f3d425b7abb2b0018f490070
390
cpp
C++
logout.cpp
fraxer/scgi-server
9f26eea5bb4e27c500bffddae5e91aec0f18ab52
[ "MIT" ]
null
null
null
logout.cpp
fraxer/scgi-server
9f26eea5bb4e27c500bffddae5e91aec0f18ab52
[ "MIT" ]
null
null
null
logout.cpp
fraxer/scgi-server
9f26eea5bb4e27c500bffddae5e91aec0f18ab52
[ "MIT" ]
null
null
null
class LogoutController: public Controller { public: string& run(map<const char*, const char*>& parms) { addHeader("Set-Cookie: id=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"); addHeader("Set-Cookie: token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"); return redirect(302, "Moved Temporarily", "/index.d", "/"); } };
43.333333
92
0.574359
fraxer
5531c27ffd7423825958ed95e59fd394e420a3d8
129
hpp
C++
dependencies/glm/gtx/euler_angles.hpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/glm/gtx/euler_angles.hpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/glm/gtx/euler_angles.hpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:83c1f5f2fc2dcc4d7d99f930b6aa29e09677df4d1148a7d86389ea8c2a9a5dd0 size 4609
32.25
75
0.883721
realtehcman
553dc8b35d6f9886b9491ca697dab6dc8117668a
2,890
cpp
C++
src/simulated_annealing.cpp
paulora2405/iar-tsp-sa
552ee4aea9122d6cc66bc2650ec128dc85a0a718
[ "MIT" ]
null
null
null
src/simulated_annealing.cpp
paulora2405/iar-tsp-sa
552ee4aea9122d6cc66bc2650ec128dc85a0a718
[ "MIT" ]
null
null
null
src/simulated_annealing.cpp
paulora2405/iar-tsp-sa
552ee4aea9122d6cc66bc2650ec128dc85a0a718
[ "MIT" ]
null
null
null
#include "simulated_annealing.hpp" #include <algorithm> #include <cmath> #include <ctime> #include <fstream> #include <iomanip> #include <iostream> #include <random> namespace sa { static std::default_random_engine gen(time(NULL)); static std::uniform_real_distribution<double> prob0_1(0.0f, 1.0f); std::vector<Trio> swapRand(std::vector<Trio> cities) { static std::uniform_int_distribution<int> dist(0, cities.size() - 1); static std::uniform_int_distribution<int> swapQnt(1, 5); for(int i = 0; i < swapQnt(gen); i++) { int first = dist(gen), second; do { second = dist(gen); } while(first == second); std::swap(cities.at(first), cities.at(second)); } return cities; } double euclDist(Trio &first, Trio &second) { return std::sqrt(std::pow((first.x - second.x), 2) + std::pow((first.y - second.y), 2)); } double tspTotal(std::vector<Trio> &s) { // O(n) double sumEucl = 0; for(size_t i = 0; i < s.size() - 1; ++i) { sumEucl += euclDist(s[i], s[i + 1]); } sumEucl += euclDist(s.front(), s.back()); return sumEucl; } double calcTi(int formula, int i, double T0, double TN, double N) { double a, b; switch(formula) { case 0: return (T0 - i * ((T0 - TN) / N)); case 1: return T0 * std::pow(TN / T0, i / N); case 2: a = ((T0 - TN) * (N + 1)) / N; b = T0 - a; return (a / (i + 1) + b); case 3: a = std::log(T0 - TN) / std::log(N); return (T0 - std::pow(i, a)); default: return 0; } } double simulated_annealing(std::vector<Trio> &s, int formula, bool drawGraph) { std::vector<PontoH> historico; int SAmax = 500; double T0 = 1500.0f; double N = 100000.0f; double TN = 0.000001f; double T = T0; int i = 0; std::cout << "T=" << T << " T0=" << T0 << " N=" << N << " TN=" << TN << " Formula " << formula << std::endl; std::shuffle(s.begin(), s.end(), gen); std::vector<Trio> sBest; sBest = s; while(T > 0.00001) { for(int iterT = 0; iterT < SAmax; ++iterT) { ++i; std::vector<Trio> s_ = swapRand(s); // s' double delta = tspTotal(s_) - tspTotal(s); if(delta < 0) { s = s_; if(tspTotal(s_) < tspTotal(sBest)) { sBest = s_; historico.push_back({i, tspTotal(s)}); } } else { if(prob0_1(gen) < std::exp(-delta / T)) { s = s_; historico.push_back({i, tspTotal(s)}); } } } T = calcTi(formula, i, T0, TN, N); } if(drawGraph) { std::ofstream os("convergencia.txt"); for(auto &p : historico) { os << p.i << ',' << p.cost << '\n'; } os.flush(); os.close(); std::string call = "python3 conver.py " + std::to_string(formula); if(std::system(call.c_str()) == 0) std::cout << "Generated Graph" << std::endl; } return tspTotal(sBest); } } // namespace sa
23.495935
96
0.547059
paulora2405
55433e84fe4a26b7293d7a091cfb84e51744cc4d
823
cpp
C++
src/offer.04.er-wei-shu-zu-zhong-de-cha-zhao-lcof/cpp/main.cpp
1-st/algos
d1f4cff9ee0b014e05629091fb3bdc3c9da90b15
[ "Apache-2.0" ]
1
2020-11-05T04:03:15.000Z
2020-11-05T04:03:15.000Z
src/offer.04.er-wei-shu-zu-zhong-de-cha-zhao-lcof/cpp/main.cpp
up0/algos
1ceee4a5e6445c3ac9b11482aad97d8cd44bbcec
[ "Apache-2.0" ]
null
null
null
src/offer.04.er-wei-shu-zu-zhong-de-cha-zhao-lcof/cpp/main.cpp
up0/algos
1ceee4a5e6445c3ac9b11482aad97d8cd44bbcec
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> /* { from:"https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/" , description:"二维数组中的查找" } */ using namespace std; class Solution { public: bool findNumberIn2DArray(vector<vector<int>> &matrix, int target) { if (matrix.size() == 0 || matrix[0].size() == 0) { return false; } int rows = matrix.size(), columns = matrix[0].size(); int row = 0, column = columns - 1; while (row < rows && column >= 0) { int num = matrix[row][column]; if (num == target) { return true; } else if (num > target) { column--; } else { row++; } } return false; } }; int main() { vector<vector<int>> matrix = {{-5}}; Solution s; cout << s.findNumberIn2DArray(matrix, -1); return 0; }
20.575
81
0.561361
1-st
5543ca29ea100c88d35f297233fc5a7fdacba642
13,639
cpp
C++
EvolutionDlg.cpp
CanadianYankee/TrafficSwarm
9b2eb423de89fdeba7195a7fd6f1a667ecdea12c
[ "MIT" ]
1
2019-12-14T15:52:28.000Z
2019-12-14T15:52:28.000Z
EvolutionDlg.cpp
CanadianYankee/TrafficSwarm
9b2eb423de89fdeba7195a7fd6f1a667ecdea12c
[ "MIT" ]
null
null
null
EvolutionDlg.cpp
CanadianYankee/TrafficSwarm
9b2eb423de89fdeba7195a7fd6f1a667ecdea12c
[ "MIT" ]
null
null
null
// EvolutionDlg.cpp : implementation file // #include "pch.h" #include "TrafficSwarm.h" #include "EvolutionDlg.h" #include "afxdialogex.h" #include "Course.h" #include "AgentGenome.h" #include "TrialRun.h" // CEvolutionDlg dialog UINT RunThreadedTrial(LPVOID pParams) { CEvolutionDlg* pOwner = ((CEvolutionDlg*)pParams); return pOwner->RunThreadedTrial(); } bool CompareResults(CTrialRun::RUN_RESULTS& r1, CTrialRun::RUN_RESULTS& r2) { return r1.Score() < r2.Score(); } IMPLEMENT_DYNAMIC(CEvolutionDlg, CDialogEx) CEvolutionDlg::CEvolutionDlg(CWnd* pParent, const CCourse& cCourse) : CDialogEx(IDD_DIALOG_EVOLVE, pParent) , m_strCourseName(cCourse.m_strName) , m_cCourse(cCourse) , m_strRunCount(_T("")) , m_strGeneration(_T("")) , m_eStatus(STATUS::NotRunning) , m_strStatus(_T("")) , m_nAgents(2048) , m_nChildren(100) , m_strLastRun(_T("")) , m_iCurrentChild(0) , m_iCurrentGeneration(0) , m_strSelGenome(_T("")) , m_strSelScores(_T("")) , m_nGenerations(10) { } CEvolutionDlg::~CEvolutionDlg() { } void CEvolutionDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_STATIC_COURSE, m_strCourseName); DDX_Text(pDX, IDC_STATIC_RUNCOUNT, m_strRunCount); DDX_Control(pDX, IDC_LIST_RESULTS, m_listResults); DDX_Text(pDX, IDC_STATIC_GENERATION, m_strGeneration); DDX_Text(pDX, IDC_STATIC_STATUS, m_strStatus); DDX_Text(pDX, IDC_EDIT_AGENTS, m_nAgents); DDV_MinMaxInt(pDX, m_nAgents, 0, INT_MAX); DDX_Text(pDX, IDC_EDIT_TRIALS, m_nChildren); DDV_MinMaxInt(pDX, m_nChildren, 0, INT_MAX); DDX_Text(pDX, IDC_EDIT_LASTRUN, m_strLastRun); DDX_Text(pDX, IDC_EDIT_SELGENOME, m_strSelGenome); DDX_Text(pDX, IDC_EDIT_SELSCORES, m_strSelScores); DDX_Text(pDX, IDC_EDIT_GENERATIONS, m_nGenerations); } BEGIN_MESSAGE_MAP(CEvolutionDlg, CDialogEx) ON_BN_CLICKED(IDCANCEL, &CEvolutionDlg::OnBnClickedCancel) ON_BN_CLICKED(IDC_BUTTON_EVOLVE, &CEvolutionDlg::OnBnClickedButtonEvolve) ON_MESSAGE(WM_USER_TRIAL_ENDED, &CEvolutionDlg::OnTrialEnded) ON_BN_CLICKED(IDC_BUTTON_ENDNOW, &CEvolutionDlg::OnBnClickedButtonEndnow) ON_MESSAGE(WM_USER_RESULTS_SELECTED, &CEvolutionDlg::OnUserResultsSelected) ON_BN_CLICKED(IDC_BUTTON_SAVERESULTS, &CEvolutionDlg::OnBnClickedButtonSaveresults) ON_BN_CLICKED(IDC_BUTTON_LOAD, &CEvolutionDlg::OnBnClickedButtonLoad) ON_BN_CLICKED(IDC_BUTTON_LOADTWO, &CEvolutionDlg::OnBnClickedButtonLoadtwo) ON_BN_CLICKED(IDC_BUTTON_ENDGEN, &CEvolutionDlg::OnBnClickedButtonEndgen) END_MESSAGE_MAP() // CEvolutionDlg message handlers void CEvolutionDlg::SetStatus(STATUS eStatus) { m_eStatus = eStatus; switch (eStatus) { case STATUS::NotRunning: m_strStatus = _T("Stopped"); GetDlgItem(IDC_BUTTON_EVOLVE)->EnableWindow(TRUE); GetDlgItem(IDC_BUTTON_ENDGEN)->EnableWindow(FALSE); GetDlgItem(IDC_BUTTON_ENDNOW)->EnableWindow(FALSE); GetDlgItem(IDC_BUTTON_SAVERESULTS)->EnableWindow(m_listResults.m_vecResults.size() > 0); GetDlgItem(IDC_BUTTON_LOADRESULTS)->EnableWindow(TRUE); GetDlgItem(IDC_BUTTON_LOADTWO)->EnableWindow(m_listResults.m_vecResults.size() > 0); GetDlgItem(IDCANCEL)->EnableWindow(TRUE); break; case STATUS::Running: m_strStatus.Format(_T("Evolving - generation with %d parents"), (int)m_vecParents.size()); GetDlgItem(IDC_BUTTON_EVOLVE)->EnableWindow(FALSE); GetDlgItem(IDC_BUTTON_ENDGEN)->EnableWindow(TRUE); GetDlgItem(IDC_BUTTON_ENDNOW)->EnableWindow(TRUE); GetDlgItem(IDC_BUTTON_SAVERESULTS)->EnableWindow(FALSE); GetDlgItem(IDC_BUTTON_LOADRESULTS)->EnableWindow(FALSE); GetDlgItem(IDC_BUTTON_LOADTWO)->EnableWindow(FALSE); GetDlgItem(IDCANCEL)->EnableWindow(FALSE); break; case STATUS::EndGeneration: m_strStatus = _T("Stopping after current generation"); GetDlgItem(IDC_BUTTON_EVOLVE)->EnableWindow(FALSE); GetDlgItem(IDC_BUTTON_ENDGEN)->EnableWindow(FALSE); GetDlgItem(IDC_BUTTON_ENDNOW)->EnableWindow(TRUE); GetDlgItem(IDC_BUTTON_SAVERESULTS)->EnableWindow(FALSE); GetDlgItem(IDC_BUTTON_LOADRESULTS)->EnableWindow(FALSE); GetDlgItem(IDC_BUTTON_LOADTWO)->EnableWindow(FALSE); GetDlgItem(IDCANCEL)->EnableWindow(FALSE); break; case STATUS::Ending: m_strStatus = _T("Stopping after current run"); GetDlgItem(IDC_BUTTON_EVOLVE)->EnableWindow(FALSE); GetDlgItem(IDC_BUTTON_ENDGEN)->EnableWindow(FALSE); GetDlgItem(IDC_BUTTON_ENDNOW)->EnableWindow(FALSE); GetDlgItem(IDC_BUTTON_SAVERESULTS)->EnableWindow(FALSE); GetDlgItem(IDC_BUTTON_LOADRESULTS)->EnableWindow(FALSE); GetDlgItem(IDC_BUTTON_LOADTWO)->EnableWindow(FALSE); GetDlgItem(IDCANCEL)->EnableWindow(FALSE); break; default: ASSERT(FALSE); } UpdateData(FALSE); } // Seed the next generation with a vector of parent genomes void CEvolutionDlg::SeedGenomes(const std::vector<CAgentGenome>& vecGenomes) { ASSERT(vecGenomes.size() <= m_nChildren); m_vecParents.clear(); m_vecParents = vecGenomes; } // After a completed generation, sort by ascending score and take the 10% // lowest-scoring children as the parents of the next generation. The remaining // 90% will be discarded. void CEvolutionDlg::PullParents(const std::vector<CTrialRun::RUN_RESULTS> &vecResults) { std::vector<CTrialRun::RUN_RESULTS> vec(vecResults); std::sort(vec.begin(), vec.end(), CompareResults); int nParents = min(max(1, m_nChildren / 10), (int)vec.size()); std::vector<CAgentGenome> vecParents(nParents); for (int i = 0; i < nParents; i++) { vecParents[i] = vec[i].genome; } SeedGenomes(vecParents); } // Given two trial runs, pull 10% of the lowest-scoring from each one and // cross breed them to be the parents of a new generation. void CEvolutionDlg::PullParents(const std::vector<CTrialRun::RUN_RESULTS>& vecRuns1, const std::vector<CTrialRun::RUN_RESULTS>& vecRuns2) { std::vector<CTrialRun::RUN_RESULTS> vec1(vecRuns1), vec2(vecRuns2); std::sort(vec1.begin(), vec1.end(), CompareResults); std::sort(vec2.begin(), vec2.end(), CompareResults); int nParents1 = min(max(1, m_nChildren / 10), (int)vec1.size()); int nParents2 = min(max(1, m_nChildren / 10), (int)vec2.size()); int nParents = min(nParents1, nParents2); std::vector<CAgentGenome> vecParents(nParents); for (int i = 0; i < nParents; i++) { vecParents[i] = CAgentGenome::CrossBreed(vec1[rand() % nParents1].genome, vec2[rand() % nParents2].genome); } SeedGenomes(vecParents); } // For each generation, the chosen parents survive intact. Then children // are bred to fill up 90% of the population and the final 10% are completely // random. // // Breeding process: // 1. Choose two parents at random, indexed as i,j. // 2. If i == j, then copy parent(i) and mutate one gene. A second gene gets mutated to a // random value with probability 0.2, a third with probability (0.2)(0.2) = 0.04, etc. // 3. If i != j, then randomly select each gene from either parent. One gene gets mutated // to a random value with probability 0.2, a second with probability (0.2)(0.2) = 0.04, etc. void CEvolutionDlg::SetupGeneration() { size_t iRandStart = 0; size_t nParents = m_vecParents.size(); size_t iChild = 0; m_vecChildren.clear(); m_vecChildren.resize(m_nChildren); if (nParents == 1) { m_vecChildren[0] = m_vecParents[0]; for (iChild = 1; iChild < m_nChildren / 5; iChild++) { m_vecChildren[iChild] = m_vecParents[0]; m_vecChildren[iChild].RandomizeOne(); } } else if (nParents > 1) { for (iChild = 0; iChild < nParents; iChild++) { m_vecChildren[iChild] = m_vecParents[iChild]; } for (; iChild < m_nChildren; iChild++) { bool bRepeat = false; do { bRepeat = false; size_t i = rand() % nParents; size_t j = rand() % nParents; if (i == j) { m_vecChildren[iChild] = m_vecParents[i]; do { m_vecChildren[iChild].RandomizeOne(); } while (frand() < 0.2); } else { m_vecChildren[iChild] = CAgentGenome::CrossBreed(m_vecParents[i], m_vecParents[j]); } for (size_t n = 0; n < iChild; n++) { // Don't create identical children - preserve genetic diversity if (m_vecChildren[n] == m_vecChildren[iChild]) { bRepeat = true; break; } } } while (bRepeat); } } for (; iChild < m_nChildren; iChild++) { m_vecChildren[iChild].RandomizeAll(); } m_iCurrentChild = 0; m_iCurrentGeneration++; m_vecResults.clear(); m_vecResults.reserve(m_nChildren); m_listResults.ClearAll(); m_strLastRun.Empty(); m_strSelGenome.Empty(); m_strSelScores.Empty(); m_strRunCount.Format(_T("%d of %d"), 1, m_nChildren); m_strGeneration.Format(_T("%d of %d"), m_iCurrentGeneration, m_nGenerations); } BOOL CEvolutionDlg::OnInitDialog() { CDialogEx::OnInitDialog(); SetStatus(STATUS::NotRunning); m_listResults.m_bAutoSort = TRUE; return TRUE; } void CEvolutionDlg::OnBnClickedCancel() { GetParent()->PostMessage(WM_USER_CHILD_CLOSING); CDialogEx::OnCancel(); } void CEvolutionDlg::OnBnClickedButtonEvolve() { if (UpdateData(TRUE)) { bool bSetup = true; if (m_iCurrentGeneration > 0 && !Complete()) { switch (MessageBox(_T("Would you like to continue the current evolution?\nChoosing 'No' will restart with a new random population."), _T("Evolve"), MB_YESNOCANCEL)) { case IDYES: bSetup = false; break; case IDNO: m_vecParents.clear(); m_iCurrentGeneration = 0; break; case IDCANCEL: return; } } if (bSetup) SetupGeneration(); SetStatus(STATUS::Running); AfxBeginThread(::RunThreadedTrial, (LPVOID)(this)); } } // Only called from within the worker run-trial thread UINT CEvolutionDlg::RunThreadedTrial() { HRESULT hr = S_OK; BOOL bResult = TRUE; CTrialRun cTrial; hr = cTrial.Intialize(m_nAgents, m_cCourse, m_vecChildren[m_iCurrentChild]); bResult = SUCCEEDED(hr); if (bResult) { m_vecResults.resize((size_t)m_iCurrentChild + 1); bResult = cTrial.Run(m_vecResults[m_iCurrentChild]); } ::PostMessage(this->GetSafeHwnd(), WM_USER_TRIAL_ENDED, (WPARAM)bResult, 0); return 0; } // Post results from last trial and launch next one if we're not done or // waiting for a stop. afx_msg LRESULT CEvolutionDlg::OnTrialEnded(WPARAM wParam, LPARAM lParam) { if (!wParam) { ASSERT(FALSE); SetStatus(STATUS::NotRunning); return 0; } // Report results CTrialRun::RUN_RESULTS& results = m_vecResults[m_iCurrentChild]; m_strLastRun.Format(_T("Child #%d: "), m_iCurrentChild + 1); m_strLastRun += results.ToParagraphString(_T("\r\n")); // Save full results in list box for breeding/saving/etc. m_listResults.AddResult(m_iCurrentChild + 1, results); // If we are still going, then launch the next child/trial m_iCurrentChild++; if (m_eStatus == STATUS::Ending) { SetStatus(STATUS::NotRunning); } else if (m_iCurrentChild < (UINT)m_nChildren) { m_strRunCount.Format(_T("%d of %d"), m_iCurrentChild + 1, m_nChildren); SetStatus(m_eStatus == STATUS::EndGeneration ? STATUS::EndGeneration : STATUS::Running); AfxBeginThread(::RunThreadedTrial, (LPVOID)(this)); } else if (Complete()) { SetStatus(STATUS::NotRunning); // TODO: save results } else { PullParents(m_listResults.m_vecResults); m_listResults.ClearAll(); SetupGeneration(); SetStatus(STATUS::Running); AfxBeginThread(::RunThreadedTrial, (LPVOID)(this)); } return 0; } void CEvolutionDlg::OnBnClickedButtonEndnow() { SetStatus(STATUS::Ending); } afx_msg LRESULT CEvolutionDlg::OnUserResultsSelected(WPARAM wParam, LPARAM lParam) { if (wParam) { auto pResults = (CTrialRun::RUN_RESULTS*)wParam; m_strSelGenome = pResults->genome.ToString(_T("\r\n")); m_strSelScores = pResults->ToListString(_T("\r\n")); } else { m_strSelGenome.Empty(); m_strSelScores.Empty(); } UpdateData(FALSE); return 0; } void CEvolutionDlg::OnBnClickedButtonSaveresults() { CTime time = CTime::GetCurrentTime(); CString strName = m_strCourseName + time.Format(_T("_%F_%H-%M-%S.txt")); CFileDialog dlgSaveAs(FALSE, _T(".txt"), strName.GetBuffer()); if (dlgSaveAs.DoModal() == IDOK) { strName = dlgSaveAs.GetPathName(); std::ofstream file; file.open(strName.GetBuffer(), std::ios_base::out | std::ios_base::trunc); file << m_listResults; file.close(); } } void CEvolutionDlg::OnBnClickedButtonLoad() { if (UpdateData(TRUE)) { CFileDialog dlgFile(TRUE, _T(".txt"), 0, 0, _T("Text files (*.txt)|*.txt|All Files (*.*)|*.*||")); if (dlgFile.DoModal() == IDOK) { CString strFile = dlgFile.GetPathName(); std::ifstream file; file.open(strFile.GetBuffer(), std::ios_base::in); file >> m_listResults; file.close(); PullParents(m_listResults.m_vecResults); m_iCurrentGeneration = 0; m_iCurrentChild = 0; SetStatus(STATUS::NotRunning); } } } void CEvolutionDlg::OnBnClickedButtonLoadtwo() { if (UpdateData(TRUE)) { if (m_listResults.m_vecResults.empty()) { MessageBox(_T("There must be results to cross-breed with. Either do an evolution run or load some previous results to cross-breed."), _T("Cross-breed error."), MB_OK); return; } CFileDialog dlgFile(TRUE, _T(".txt"), 0, 0, _T("Text files (*.txt)|*.txt|All Files (*.*)|*.*||")); if (dlgFile.DoModal() == IDOK) { std::vector<CTrialRun::RUN_RESULTS> vecOld = m_listResults.m_vecResults; m_listResults.ClearAll(); CString strFile = dlgFile.GetPathName(); std::ifstream file; file.open(strFile.GetBuffer(), std::ios_base::in); file >> m_listResults; file.close(); PullParents(vecOld, m_listResults.m_vecResults); m_listResults.ClearAll(); m_iCurrentGeneration = 0; m_iCurrentChild = 0; UpdateData(); OnBnClickedButtonEvolve(); } } } void CEvolutionDlg::OnBnClickedButtonEndgen() { SetStatus(STATUS::EndGeneration); }
28.713684
167
0.72586
CanadianYankee
55503ce84af159e368f44a017f1c2ce725063e81
2,210
cp
C++
gps/gps.cp
igor-almeida-github/meus-projetos-com-microcontroladores
be1ac244cd79db66461e7ae2fec843dac60c266d
[ "MIT" ]
2
2021-06-09T15:01:11.000Z
2021-07-13T19:25:06.000Z
gps/gps.cp
igor-almeida-github/meus-projetos-com-microcontroladores
be1ac244cd79db66461e7ae2fec843dac60c266d
[ "MIT" ]
null
null
null
gps/gps.cp
igor-almeida-github/meus-projetos-com-microcontroladores
be1ac244cd79db66461e7ae2fec843dac60c266d
[ "MIT" ]
null
null
null
#line 1 "C:/Users/igor_/Documents/Microcontroladores/PIC/Mikroc/gps/gps.c" sbit LCD_RS at RB4_bit; sbit LCD_EN at RB5_bit; sbit LCD_D4 at RB0_bit; sbit LCD_D5 at RB1_bit; sbit LCD_D6 at RB2_bit; sbit LCD_D7 at RB3_bit; sbit LCD_RS_Direction at TRISB4_bit; sbit LCD_EN_Direction at TRISB5_bit; sbit LCD_D7_Direction at TRISB3_bit; sbit LCD_D6_Direction at TRISB2_bit; sbit LCD_D5_Direction at TRISB1_bit; sbit LCD_D4_Direction at TRISB0_bit; void main() { unsigned char txt[]="$GPGLL,"; unsigned char LAT[12],LON[13],UTC[10],ack[4],GoogleMapstext[30]; unsigned short int i=0; ADCON1=0x07; UART1_Init(9600); Lcd_Init(); Lcd_Cmd(_LCD_CLEAR); Lcd_Cmd(_LCD_CURSOR_OFF); delay_ms(100); Lcd_Cmd(_LCD_CLEAR); Lcd_out(1,1,"GPS..."); delay_ms(2000); uart1_write(0x0F); for(;;){ i=0; while(i<7){ if(UART1_Data_Ready()){ if (UART1_Read()==txt[i]){ i++; } else i=0; } } UART1_Read_Text(LAT, ",", 255); while(!UART1_Data_Ready()); LAT[10]=UART1_Read(); while(!UART1_Data_Ready()); UART1_Read(); while(!UART1_Data_Ready()); UART1_Read_Text(LON, ",", 255); while(!UART1_Data_Ready()); LON[11]=UART1_Read(); while(!UART1_Data_Ready()); UART1_Read(); UART1_Read_Text(UTC, ",", 255); UART1_Read_Text(ack, "*", 255); if(ack[0]=='A'&&ack[2]=='A'){ GoogleMapstext[0]=LAT[0]; GoogleMapstext[1]=LAT[1]; GoogleMapstext[2]=0xB0; for (i=2;i<10;i++)GoogleMapstext[i+1]=LAT[i]; GoogleMapstext[11]=0x27; GoogleMapstext[12]=LAT[10]; GoogleMapstext[13]=LON[0]; GoogleMapstext[14]=LON[1]; GoogleMapstext[15]=LON[2]; GoogleMapstext[16]=0xB0; for(i=3;i<11;i++)GoogleMapstext[i+14]=LON[i]; GoogleMapstext[25]=0x27; GoogleMapstext[26]=LON[11]; GoogleMapstext[27]=0x0D; GoogleMapstext[28]=0x0A; GoogleMapstext[29]='\0'; UART1_Write_Text(GoogleMapstext); GoogleMapstext[2]=0xDF; GoogleMapstext[16]=0xDF; Lcd_Cmd(_LCD_CLEAR); Lcd_Cmd(_LCD_RETURN_HOME); for (i=0;i<13;i++) Lcd_Chr_Cp(GoogleMapstext[i]); Lcd_Cmd(_LCD_RETURN_HOME); Lcd_Cmd(_LCD_SECOND_ROW); for (i=13;i<27;i++) Lcd_Chr_Cp(GoogleMapstext[i]); } else { Lcd_Cmd(_LCD_CLEAR); Lcd_out(1,1,"No Signal"); } } }
22.323232
75
0.676923
igor-almeida-github
55649b809c20937903949393d4f3a7099fce8014
37,223
hpp
C++
core/os/windows/src/cogs/os/sync/atomic_operators.hpp
cogmine/cogs
ef1c369a36a4f811704e0ced0493c3a6f8eca821
[ "MIT" ]
5
2019-02-08T15:59:14.000Z
2022-01-22T19:12:33.000Z
core/os/windows/src/cogs/os/sync/atomic_operators.hpp
cogmine/cogs
ef1c369a36a4f811704e0ced0493c3a6f8eca821
[ "MIT" ]
1
2019-12-03T03:11:34.000Z
2019-12-03T03:11:34.000Z
core/os/windows/src/cogs/os/sync/atomic_operators.hpp
cogmine/cogs
ef1c369a36a4f811704e0ced0493c3a6f8eca821
[ "MIT" ]
null
null
null
// // Copyright (C) 2000-2020 - Colen M. Garoutte-Carson <colen at cogmine.com>, Cog Mine LLC // #ifdef COGS_HEADER_ENV_SYNC_ATOMIC_OPERATORS #ifndef COGS_HEADER_OS_SYNC_ATOMIC_OPERATORS #define COGS_HEADER_OS_SYNC_ATOMIC_OPERATORS #include "cogs/arch/sync/atomic_operators.hpp" namespace cogs { namespace os { namespace atomic { // Allow env layer to handle all Windows atomics COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(next) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(prev) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_and) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_or) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_xor) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(add) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(subtract) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(not) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(abs) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_not) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(negative) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_count) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_scan_forward) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_scan_reverse) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(endian_swap) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_rotate_left) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_rotate_right) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_shift_left) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_shift_right) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(inverse_subtract) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(multiply) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(modulo) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(inverse_modulo) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(divide) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(inverse_divide) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(reciprocal) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(divide_whole) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(inverse_divide_whole) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(gcd) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(lcm) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(greater) COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(lesser) // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && !std::is_const_v<T> // && (sizeof(T) <= sizeof(char)), // void> // exchange(volatile T& t, const T& src, T& rtn) // { // rtn = (T)InterlockedExchange8((char*)(unsigned char*)&t, (char)src); // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(char)) // && (sizeof(T) <= sizeof(short)), // void> // exchange(volatile T& t, const T& src, T& rtn) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // rtn = (T)InterlockedExchange16((short*)(unsigned char*)&t, (short)src); // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(short)) // && (sizeof(T) <= sizeof(long)), // void> // exchange(volatile T& t, const T& src, T& rtn) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // rtn = (T)InterlockedExchange((long*)(unsigned char*)&t, (long)src); // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(long)) // && (sizeof(T) <= sizeof(__int64)), // void> // exchange(T& t, const T& src, T& rtn) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // rtn = (T)InterlockedExchange64((__int64*)(unsigned char*)&t, (__int64)src); // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && !std::is_const_v<T> // && (sizeof(T) <= sizeof(char)), // T // > // exchange(volatile T& t, const T& src) // { // return (T)InterlockedExchange8((char*)(unsigned char*)&t, (char)src); // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(char)) // && (sizeof(T) <= sizeof(short)), // T // > // exchange(volatile T& t, const T& src) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // return (T)InterlockedExchange16((short*)(unsigned char*)&t, (short)src); // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(short)) // && (sizeof(T) <= sizeof(long)), // T // > // exchange(volatile T& t, const T& src) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // return (T)InterlockedExchange((long*)(unsigned char*)&t, (long)src); // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(long)) // && (sizeof(T) <= sizeof(__int64)), // std::remove_volatile_t<T> // > // exchange(T& t, const T& src) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // return (T)InterlockedExchange64((__int64*)(unsigned char*)&t, (__int64)src); // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && !std::is_const_v<T> // && (sizeof(T) <= sizeof(char)), // bool // > // compare_exchange(volatile T& t, const T& src, const T& cmp, T& rtn) // { // char tmp = InterlockedCompareExchange8((char*)(unsigned char*)&t, (char)src, (char)cmp); // bool b = tmp == (char)cmp; // rtn = (T)tmp; // return b; // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(char)) // && (sizeof(T) <= sizeof(short)), // bool // > // compare_exchange(volatile T& t, const T& src, const T& cmp, T& rtn) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // short tmp = InterlockedCompareExchange16((short*)(unsigned char*)&t, (short)src, (short)cmp); // bool b = tmp == (short)cmp; // rtn = (T)tmp; // return b; // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(short)) // && (sizeof(T) <= sizeof(long)), // bool // > // compare_exchange(volatile T& t, const T& src, const T& cmp, T& rtn) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // long tmp = InterlockedCompareExchange((long*)(unsigned char*)&t, (long)src, (long)cmp); // bool b = tmp == (long)cmp; // rtn = (T)tmp; // return b; // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(long)) // && (sizeof(T) <= sizeof(__int64)), // bool // > // compare_exchange(volatile T& t, const T& src, const T& cmp, T& rtn) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // __int64 tmp = InterlockedCompareExchange64((__int64*)(unsigned char*)&t, (__int64)src, (__int64)cmp); // bool b = tmp == (__int64)cmp; // rtn = (T)tmp; // return b; // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && !std::is_const_v<T> // && (sizeof(T) <= sizeof(char)), // bool // > // compare_exchange(volatile T& t, const T& src, const T& cmp) // { // return InterlockedCompareExchange8((char*)(unsigned char*)&t, (char)src, (char)cmp) == (char)cmp; // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(char)) // && (sizeof(T) <= sizeof(short)), // bool // > // compare_exchange(volatile T& t, const T& src, const T& cmp) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // return InterlockedCompareExchange16((short*)(unsigned char*)&t, (short)src, (short)cmp) == (short)cmp; // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(short)) // && (sizeof(T) <= sizeof(long)), // bool // > // compare_exchange(volatile T& t, const T& src, const T& cmp) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // return InterlockedCompareExchange((long*)(unsigned char*)&t, (long)src, (long)cmp) == (long)cmp; // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(long)) // && (sizeof(T) <= sizeof(__int64)), // bool // > // compare_exchange(volatile T& t, const T& src, const T& cmp) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // return InterlockedCompareExchange64((__int64*)(unsigned char*)&t, (__int64)src, (__int64)cmp) == (__int64)cmp; // } // #if defined(_M_X64) || defined(_M_AMD64) || defined(_M_ARM64) // template <typename T> // inline std::enable_if_t< // !std::is_empty_v<T> // && can_atomic_v<T> // && (sizeof(T) > sizeof(__int64)) // && (sizeof(T) <= (sizeof(__int64) * 2)), // void // > // load(const volatile T& t, T& rtn) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // // Note: CMPXCHG/CMPXCHG8B/CMPXCHG16B all issue an implicit write, even if not modified. // volatile T* srcPtr = const_cast<volatile T*>(&t); // __int64 tmpCmp[2] = {}; // InterlockedCompareExchange128((__int64*)(unsigned char*)srcPtr, tmpCmp[1], tmpCmp[0], tmpCmp); // bypass_strict_aliasing(tmpCmp, rtn); // } // template <typename T> // inline std::enable_if_t< // !std::is_empty_v<T> // && can_atomic_v<T> // && (sizeof(T) > sizeof(__int64)) // && (sizeof(T) <= (sizeof(__int64) * 2)), // T // > // load(const volatile T& t) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // // Note: CMPXCHG/CMPXCHG8B/CMPXCHG16B all issue an implicit write, even if not modified. // volatile T* srcPtr = const_cast<volatile T*>(&t); // __int64 tmpCmp[2] = {}; // InterlockedCompareExchange128((__int64*)(unsigned char*)srcPtr, tmpCmp[1], tmpCmp[0], tmpCmp); // T rtn; // bypass_strict_aliasing(tmpCmp, rtn); // return rtn; // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && !std::is_empty_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(__int64)) // && (sizeof(T) <= (sizeof(__int64) * 2)), // void // > // store(volatile T& t, const T& src) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // __int64 tmpSrc[2]; // bypass_strict_aliasing(src, tmpSrc); // __int64 tmpCmp[2] = {}; // do { } while (0 == InterlockedCompareExchange128((__int64*)(unsigned char*)&t, tmpSrc[1], tmpSrc[0], tmpCmp)); // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(__int64)) // && (sizeof(T) <= (sizeof(__int64) * 2)), // void // > // exchange(volatile T& t, const T& src, T& rtn) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // __int64 tmpSrc[2]; // bypass_strict_aliasing(src, tmpSrc); // __int64 tmpCmp[2] = {}; // do { } while (0 == InterlockedCompareExchange128((__int64*)(unsigned char*)&t, tmpSrc[1], tmpSrc[0], tmpCmp)); // bypass_strict_aliasing(tmpCmp, rtn); // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(__int64)) // && (sizeof(T) <= (sizeof(__int64) * 2)), // bool // > // compare_exchange(volatile T& t, const T& src, const T& cmp, T& rtn) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // __int64 tmpSrc[2]; // bypass_strict_aliasing(src, tmpSrc); // __int64 tmpCmp[2]; // bypass_strict_aliasing(cmp, tmpCmp); // bool b = InterlockedCompareExchange128((__int64*)(unsigned char*)&t, tmpSrc[1], tmpSrc[0], tmpCmp) != 0; // bypass_strict_aliasing(tmpCmp, rtn); // return b; // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(__int64)) // && (sizeof(T) <= (sizeof(__int64) * 2)), // bool // > // compare_exchange(volatile T& t, const T& src, const T& cmp) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // __int64 tmpSrc[2]; // bypass_strict_aliasing(src, tmpSrc); // __int64 tmpCmp[2]; // bypass_strict_aliasing(cmp, tmpCmp); // return InterlockedCompareExchange128((__int64*)(unsigned char*)&t, tmpSrc[1], tmpSrc[0], tmpCmp) != 0; // } // #endif // // next // // We fall back to the default (compare_exchange), if: // // 1 byte, since there is no InterlockedIncrement8 // // It's a floating point, as there is no intrinsic for it. // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_arithmetic_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && ((sizeof(T) <= sizeof(char)) || std::is_floating_point_v<T>), // std::remove_volatile_t<T> // > // pre_assign_next(T& t) // { // return arch::atomic::pre_assign_next(t); // } // template <typename T> // inline std::enable_if_t< // is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(char)) // && (sizeof(T) <= sizeof(short)), // std::remove_volatile_t<T> // > // pre_assign_next(T& t) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // return (std::remove_volatile_t<T>)InterlockedIncrement16((short*)(unsigned char*)&t); // } // template <typename T> // inline std::enable_if_t< // is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(short)) // && (sizeof(T) <= sizeof(long)), // std::remove_volatile_t<T> // > // pre_assign_next(T& t) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // return (std::remove_volatile_t<T>)InterlockedIncrement((long*)(unsigned char*)&t); // } // template <typename T> // inline std::enable_if_t< // is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(long)) // && (sizeof(T) <= sizeof(__int64)), // std::remove_volatile_t<T> // > // pre_assign_next(T& t) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // return (std::remove_volatile_t<T>)InterlockedIncrement64((__int64*)(unsigned char*)&t); // } // template <typename T> // inline std::enable_if_t< // std::is_pointer_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // std::remove_volatile_t<T> // > // pre_assign_next(T& t) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // #if defined(_M_X64) || defined(_M_AMD64) || defined(_M_ARM64) // return (std::remove_volatile_t<T>)InterlockedAdd64((__int64*)(unsigned char*)&t, sizeof(std::remove_pointer_t<T>)); // #else // return (std::remove_volatile_t<T>)InterlockedAdd((__int64*)(unsigned char*)&t, sizeof(std::remove_pointer_t<T>)); // #endif // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // void // > // assign_next(T& t) // { // pre_assign_next(t); // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // std::remove_volatile_t<T> // > // post_assign_next(T& t) // { // return pre_assign_next(t) - 1; // } // // prev // // We fall back to the default (compare_exchange), if: // // 1 byte, since there is no InterlockedDecrement8 // // It's a floating point, as there is no intrinsic for it. // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_arithmetic_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && ((sizeof(T) <= sizeof(char)) || std::is_floating_point_v<T>), // std::remove_volatile_t<T> // > // pre_assign_prev(T& t) // { // return arch::atomic::pre_assign_prev(t); // } // template <typename T> // inline std::enable_if_t< // is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(char)) // && (sizeof(T) <= sizeof(short)), // std::remove_volatile_t<T> // > // pre_assign_prev(T& t) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // return (std::remove_volatile_t<T>)InterlockedDecrement16((short*)(unsigned char*)&t); // } // template <typename T> // inline std::enable_if_t< // is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(short)) // && (sizeof(T) <= sizeof(long)), // std::remove_volatile_t<T> // > // pre_assign_prev(T& t) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // return (std::remove_volatile_t<T>)InterlockedDecrement((long*)(unsigned char*)&t); // } // template <typename T> // inline std::enable_if_t< // is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(long)) // && (sizeof(T) <= sizeof(__int64)), // std::remove_volatile_t<T> // > // pre_assign_prev(T& t) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // return (std::remove_volatile_t<T>)InterlockedDecrement64((__int64*)(unsigned char*)&t); // } // template <typename T> // inline std::enable_if_t< // std::is_pointer_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // std::remove_volatile_t<T> // > // pre_assign_prev(T& t) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // #if defined(_M_X64) || defined(_M_AMD64) || defined(_M_ARM64) // return (std::remove_volatile_t<T>)InterlockedAdd64((__int64*)(unsigned char*)&t, -sizeof(std::remove_pointer_t<T>)); // #else // return (std::remove_volatile_t<T>)InterlockedAdd((__int64*)(unsigned char*)&t, -sizeof(std::remove_pointer_t<T>)); // #endif // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // void // > // assign_prev(T& t) // { // pre_assign_prev(t); // } // template <typename T> // inline std::enable_if_t< // can_atomic_v<T> // && is_scalar_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // std::remove_volatile_t<T> // > // post_assign_prev(T& t) // { // return pre_assign_prev(t) + 1; // } // // bit_and // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) <= sizeof(char)), // std::remove_volatile_t<T> // > // post_assign_bit_and(T& t, const A1& a) // { // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedAnd8((char*)(unsigned char*)&t, (char)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(char)) // && (sizeof(T) <= sizeof(short)), // std::remove_volatile_t<T> // > // post_assign_bit_and(T& t, const A1& a) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedAnd16((short*)(unsigned char*)&t, (short)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(short)) // && (sizeof(T) <= sizeof(long)), // std::remove_volatile_t<T> // > // post_assign_bit_and(T& t, const A1& a) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedAnd((long*)(unsigned char*)&t, (long)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(long)) // && (sizeof(T) <= sizeof(__int64)), // std::remove_volatile_t<T> // > // post_assign_bit_and(T& t, const A1& a) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedAnd64((__int64*)(unsigned char*)&t, (__int64)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // void // > // assign_bit_and(T& t, const A1& a) // { // post_assign_bit_and(t, a); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // std::remove_volatile_t<T> // > // pre_assign_bit_and(T& t, const A1& a) // { // T tmp; // cogs::assign(tmp, a); // return (post_assign_bit_and(t, tmp) & tmp); // } // // bit_or // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) <= sizeof(char)), // std::remove_volatile_t<T> // > // post_assign_bit_or(T& t, const A1& a) // { // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedOr8((char*)(unsigned char*)&t, (char)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(char)) // && (sizeof(T) <= sizeof(short)), // std::remove_volatile_t<T> // > // post_assign_bit_or(T& t, const A1& a) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedOr16((short*)(unsigned char*)&t, (short)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(short)) // && (sizeof(T) <= sizeof(long)), // std::remove_volatile_t<T> // > // post_assign_bit_or(T& t, const A1& a) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedOr((long*)(unsigned char*)&t, (long)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(long)) // && (sizeof(T) <= sizeof(__int64)), // std::remove_volatile_t<T> // > // post_assign_bit_or(T& t, const A1& a) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedOr64((__int64*)(unsigned char*)&t, (__int64)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // void // > // assign_bit_or(T& t, const A1& a) // { // post_assign_bit_or(t, a); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // std::remove_volatile_t<T> // > // pre_assign_bit_or(T& t, const A1& a) // { // T tmp; // cogs::assign(tmp, a); // return (post_assign_bit_or(t, tmp) | tmp); // } // // bit_xor // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) <= sizeof(char)), // std::remove_volatile_t<T> // > // post_assign_bit_xor(T& t, const A1& a) // { // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedXor8((char*)(unsigned char*)&t, (char)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(char)) // && (sizeof(T) <= sizeof(short)), // std::remove_volatile_t<T> // > // post_assign_bit_xor(T& t, const A1& a) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedXor16((short*)(unsigned char*)&t, (short)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(short)) // && (sizeof(T) <= sizeof(long)), // std::remove_volatile_t<T> // > // post_assign_bit_xor(T& t, const A1& a) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedXor((long*)(unsigned char*)&t, (long)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(long)) // && (sizeof(T) <= sizeof(__int64)), // std::remove_volatile_t<T> // > // post_assign_bit_xor(T& t, const A1& a) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedXor64((__int64*)(unsigned char*)&t, (__int64)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // void // > // assign_bit_xor(T& t, const A1& a) // { // post_assign_bit_xor(t, a); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // std::remove_volatile_t<T> // > // pre_assign_bit_xor(T& t, const A1& a) // { // T tmp; // cogs::assign(tmp, a); // return (post_assign_bit_xor(t, tmp) ^ tmp); // } // // add // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) <= sizeof(char)), // std::remove_volatile_t<T> // > // post_assign_add(T& t, const A1& a) // { // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedExchangeAdd8((char*)(unsigned char*)&t, (char)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(char)) // && (sizeof(T) <= sizeof(short)), // std::remove_volatile_t<T> // > // post_assign_add(T& t, const A1& a) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedExchangeAdd16((short*)(unsigned char*)&t, (short)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(short)) // && (sizeof(T) <= sizeof(long)), // std::remove_volatile_t<T> // > // post_assign_add(T& t, const A1& a) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedExchangeAdd((long*)(unsigned char*)&t, (long)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(long)) // && (sizeof(T) <= sizeof(__int64)), // std::remove_volatile_t<T> // > // post_assign_add(T& t, const A1& a) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedExchangeAdd64((__int64*)(unsigned char*)&t, (__int64)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && std::is_pointer_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // std::remove_volatile_t<T> // > // post_assign_add(T& t, const A1& a) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // ptrdiff_t tmp; // cogs::assign(tmp, a); // #if defined(_M_X64) || defined(_M_AMD64) || defined(_M_ARM64) // return (std::remove_volatile_t<T>)InterlockedExchangeAdd64((__int64*)(unsigned char*)&t, tmp * sizeof(std::remove_pointer_t<T>)); // #else // return (std::remove_volatile_t<T>)InterlockedExchangeAdd((__int64*)(unsigned char*)&t, tmp * sizeof(std::remove_pointer_t<T>)); // #endif // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && std::is_floating_point_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // void // > // assign_add(T& t, const A1& a) // { // arch::atomic::assign_add(t, a); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && std::is_floating_point_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // std::remove_volatile_t<T> // > // pre_assign_add(T& t, const A1& a) // { // return arch::atomic::pre_assign_add(t, a); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && std::is_floating_point_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // std::remove_volatile_t<T> // > // post_assign_add(T& t, const A1& a) // { // return arch::atomic::post_assign_add(t, a); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && (is_integral_v<T> || std::is_pointer_v<T>) // && std::is_volatile_v<T> // && !std::is_const_v<T>, // void // > // assign_add(T& t, const A1& a) // { // post_assign_add(t, a); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // std::remove_volatile_t<T> // > // pre_assign_add(T& t, const A1& a) // { // T tmp; // cogs::assign(tmp, a); // return (post_assign_add(t, tmp) + tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && std::is_pointer_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // std::remove_volatile_t<T> // > // pre_assign_add(T& t, const A1& a) // { // ptrdiff_t tmp; // cogs::assign(tmp, a); // return (post_assign_add(t, tmp) + tmp); // } // // subtract // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) <= sizeof(char)), // std::remove_volatile_t<T> // > // post_assign_subtract(T& t, const A1& a) // { // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedExchangeAdd8((char*)(unsigned char*)&t, -(char)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(char)) // && (sizeof(T) <= sizeof(short)), // std::remove_volatile_t<T> // > // post_assign_subtract(T& t, const A1& a) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedExchangeAdd16((short*)(unsigned char*)&t, -(short)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T> // && (sizeof(T) > sizeof(short)) // && (sizeof(T) <= sizeof(long)), // std::remove_volatile_t<T> // > // post_assign_subtract(T& t, const A1& a) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // T tmp; // cogs::assign(tmp, a); // return (std::remove_volatile_t<T>)InterlockedExchangeAdd((long*)(unsigned char*)&t, -(long)tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && std::is_pointer_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // std::remove_volatile_t<T> // > // post_assign_subtract(T& t, const A1& a) // { // COGS_ASSERT((size_t)&t % cogs::atomic::get_alignment_v<T> == 0); // ptrdiff_t tmp; // cogs::assign(tmp, a); // #if defined(_M_X64) || defined(_M_AMD64) || defined(_M_ARM64) // return (std::remove_volatile_t<T>)InterlockedExchangeAdd64((__int64*)(unsigned char*)&t, tmp * -(ptrdiff_t)sizeof(std::remove_pointer_t<T>)); // #else // return (std::remove_volatile_t<T>)InterlockedExchangeAdd((__int64*)(unsigned char*)&t, tmp * -(ptrdiff_t)sizeof(std::remove_pointer_t<T>)); // #endif // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && std::is_pointer_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // void // > // post_assign_subtract(T& t, const A1& a) // { // ptrdiff_t tmp; // cogs::assign(tmp, a); // return post_assign_subtract(t, tmp * sizeof(std::remove_pointer_t<T>)); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && std::is_floating_point_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // void // > // assign_subtract(T& t, const A1& a) // { // arch::atomic::assign_subtract(t, a); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && std::is_floating_point_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // std::remove_volatile_t<T> // > // pre_assign_subtract(T& t, const A1& a) // { // return arch::atomic::pre_assign_subtract(t, a); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && std::is_floating_point_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // std::remove_volatile_t<T> // > // post_assign_subtract(T& t, const A1& a) // { // return arch::atomic::post_assign_subtract(t, a); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && (is_integral_v<T> || std::is_pointer_v<T>) // && std::is_volatile_v<T> // && !std::is_const_v<T>, // void // > // assign_subtract(T& t, const A1& a) // { // post_assign_subtract(t, a); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && is_integral_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // std::remove_volatile_t<T> // > // pre_assign_subtract(T& t, const A1& a) // { // T tmp; // cogs::assign(tmp, a); // return (post_assign_subtract(t, tmp) - tmp); // } // template <typename T, typename A1> // inline std::enable_if_t< // can_atomic_v<T> // && std::is_pointer_v<T> // && std::is_volatile_v<T> // && !std::is_const_v<T>, // std::remove_volatile_t<T> // > // pre_assign_subtract(T& t, const A1& a) // { // ptrdiff_t tmp; // cogs::assign(tmp, a); // return (post_assign_subtract(t, tmp) - tmp); // } // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(not) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(abs) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_not) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(negative) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_count) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_scan_forward) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_scan_reverse) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(endian_swap) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_rotate_left) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_rotate_right) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_shift_left) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(bit_shift_right) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(inverse_subtract) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(multiply) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(modulo) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(inverse_modulo) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(divide) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(inverse_divide) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(reciprocal) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(divide_whole) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(inverse_divide_whole) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(gcd) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(lcm) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(greater) // COGS_DEFINE_OS_DEFAULT_VOLATILE_ASSIGN_OPERATORS(lesser) } } } #endif #endif #include "cogs/env/sync/atomic_operators.hpp"
27.531805
145
0.644736
cogmine
556817c38c3259227c29c6b851cd31e277aa4ffb
434
cc
C++
LeetCode-278.cc
therainmak3r/dirty-laundry
39e295e9390b62830bef53282cdcb63716efac45
[ "MIT" ]
20
2015-12-22T14:14:59.000Z
2019-10-25T12:14:23.000Z
LeetCode-278.cc
therainmak3r/dirty-laundry
39e295e9390b62830bef53282cdcb63716efac45
[ "MIT" ]
null
null
null
LeetCode-278.cc
therainmak3r/dirty-laundry
39e295e9390b62830bef53282cdcb63716efac45
[ "MIT" ]
2
2016-06-27T13:34:08.000Z
2018-10-02T20:36:54.000Z
// Forward declaration of isBadVersion API. bool isBadVersion(int version); class Solution { public: int firstBadVersion(int n) { int low = 1; int high = n; while (low != high) { int mid = low + (high - low)/2; if (isBadVersion(mid)) high = mid; else low = mid + 1; } if (isBadVersion(low)) return low; else return low+1; } };
19.727273
44
0.509217
therainmak3r
556b86c30beb85f19996670f398c4b181dd3f7e4
2,941
hpp
C++
include/class_info.hpp
gordonwatts/func-adl-types-atlas
9d135371d4e21d69373a8e1611ea8118cf2fff7f
[ "MIT" ]
null
null
null
include/class_info.hpp
gordonwatts/func-adl-types-atlas
9d135371d4e21d69373a8e1611ea8118cf2fff7f
[ "MIT" ]
1
2022-02-23T17:56:48.000Z
2022-02-23T17:56:48.000Z
include/class_info.hpp
gordonwatts/func-adl-types-atlas
9d135371d4e21d69373a8e1611ea8118cf2fff7f
[ "MIT" ]
null
null
null
#ifndef __class_info__ #define __class_info__ #include <string> #include <iostream> #include <vector> struct typename_info { // The list of identifiers separated by "::" std::vector<typename_info> namespace_list; // The actual type name std::string type_name; // The template arguments (if there are any) std::vector<typename_info> template_arguments; // The full name of the type, including all qualifiers // int, int*, std::vector<std::jet>&, const int &, etc. std::string nickname; // Is this a const decl? bool is_const; // Is this a pointer? bool is_pointer; }; struct method_arg { // Name of the argument std::string name; // The raw and full type name std::string raw_typename; std::string full_typename; }; struct method_info { // The method name std::string name; // The return type std::string return_type; // Arguments std::vector<method_arg> arguments; // Parameterized callback arguments std::vector<method_arg> parameter_arguments; // The helper class if there are template arguments - otherwise it should // be empty. It is used as the method return type in order to // allow type-checking to proceed. std::string parameter_type_helper; // What should be the parameter method callback to process this if // template arguments are present? std::string param_method_callback; }; struct class_info { // Fully qualified C++ class name, as known to ROOT std::string name; typename_info name_as_type; // Include file where this object is declared std::string include_file; // List of aliases for this class (other names). std::vector<std::string> aliases; // List of fully qualified C++ class names that this directly inherits from std::vector<std::string> inherited_class_names; // List of all methods std::vector<method_info> methods; // The library this is located in std::string library_name; // Other classes this can take on a the behavior of std::vector<std::string> class_behaviors; }; std::ostream& operator <<(std::ostream& stream, const class_info& ci); std::ostream& operator <<(std::ostream& stream, const method_info& mi); std::ostream& operator <<(std::ostream& stream, const method_arg& ai); std::ostream& operator <<(std::ostream& stream, const typename_info& ai); // Return all types referenced std::vector<std::string> referenced_types(const class_info &c_info); std::vector<std::string> referenced_types(const method_info &m_info); std::vector<std::string> referenced_types(const method_arg &a_info); std::vector<std::string> referenced_types(const typename_info &a_info); // Return true if there is a method in the class bool has_methods(const class_info &ci, const std::vector<std::string> &names); std::vector<method_info> get_method(const class_info &ci, const std::string &method); #endif
29.118812
85
0.704862
gordonwatts
556d758ce55ee9695384de5046927f37fd8c679d
34
cpp
C++
src/game/GameProfilingSystem.cpp
amarsero/stridecpp
afc37c50c735d59a4e0784787f3c905ff98e3f66
[ "Unlicense" ]
null
null
null
src/game/GameProfilingSystem.cpp
amarsero/stridecpp
afc37c50c735d59a4e0784787f3c905ff98e3f66
[ "Unlicense" ]
null
null
null
src/game/GameProfilingSystem.cpp
amarsero/stridecpp
afc37c50c735d59a4e0784787f3c905ff98e3f66
[ "Unlicense" ]
null
null
null
#include "GameProfilingSystem.h"
17
33
0.794118
amarsero
556e0fceab431f3577aafff800cc003f1087236d
672
cpp
C++
korbo/src/Main.cpp
Txuritan/korbo
6a8b3fa2459a381ec9462f849a8ec55ef83cee10
[ "MIT" ]
null
null
null
korbo/src/Main.cpp
Txuritan/korbo
6a8b3fa2459a381ec9462f849a8ec55ef83cee10
[ "MIT" ]
null
null
null
korbo/src/Main.cpp
Txuritan/korbo
6a8b3fa2459a381ec9462f849a8ec55ef83cee10
[ "MIT" ]
null
null
null
#include "Main.hpp" #include <KorboWindow.hpp> #include <StartUp.hpp> #include <gtkmm.h> namespace Korbo { Main::Main() { } Main::~Main() { } int Main::runKorbo(int argc, char *argv[]) { Korbo::KLogc::StartUp startUp = Korbo::KLogc::StartUp(); startUp.run(); Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "com.github.txuritan.korbo"); Korbo::KUI::KorboWindow korboWindow; korboWindow.set_default_size(600, 400); return app->run(korboWindow); } } int main(int argc, char *argv[]) { return Korbo::Main::runKorbo(argc, argv); }
20.363636
112
0.583333
Txuritan
5575e93dfe614b58c169bddf6caf99988c5cd28b
2,357
cpp
C++
Plugins/UnLua/Source/UnLua/Public/LowLevel.cpp
xiejiangzhi/UnLua
86ad978f939016caed1d11f803bb79bc73dbdfc1
[ "MIT" ]
1
2022-03-24T02:56:59.000Z
2022-03-24T02:56:59.000Z
Plugins/UnLua/Source/UnLua/Public/LowLevel.cpp
xiejiangzhi/UnLua
86ad978f939016caed1d11f803bb79bc73dbdfc1
[ "MIT" ]
null
null
null
Plugins/UnLua/Source/UnLua/Public/LowLevel.cpp
xiejiangzhi/UnLua
86ad978f939016caed1d11f803bb79bc73dbdfc1
[ "MIT" ]
null
null
null
// Tencent is pleased to support the open source community by making UnLua available. // // Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // 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 "LowLevel.h" namespace UnLua { namespace LowLevel { bool IsReleasedPtr(const void* Ptr) { return Ptr == ReleasedPtr; } /** * Create weak key table */ void CreateWeakKeyTable(lua_State* L) { lua_newtable(L); lua_newtable(L); lua_pushstring(L, "__mode"); lua_pushstring(L, "k"); lua_rawset(L, -3); lua_setmetatable(L, -2); } /** * Create weak value table */ void CreateWeakValueTable(lua_State* L) { lua_newtable(L); lua_newtable(L); lua_pushstring(L, "__mode"); lua_pushstring(L, "v"); lua_rawset(L, -3); lua_setmetatable(L, -2); } FString GetMetatableName(const UObject* Object) { if (!Object) return ""; if (UNLIKELY(Object->IsA<UEnum>())) { return Object->IsNative() ? Object->GetName() : Object->GetPathName(); } const UStruct* Struct = Cast<UStruct>(Object); if (Struct) return GetMetatableName(Struct); Struct = Object->GetClass(); return GetMetatableName(Struct); } FString GetMetatableName(const UStruct* Struct) { if (!Struct) return ""; if (Struct->IsNative()) return FString::Printf(TEXT("%s%s"), Struct->GetPrefixCPP(), *Struct->GetName()); return Struct->GetPathName(); } } }
29.098765
107
0.556216
xiejiangzhi
55767b1c3386d704a4b2d5c6912fe81af4b22733
1,404
cpp
C++
Libraries/Led/Led.cpp
3KMedialab/Midi-Controller
412f1dff01b9f5c73c75e00aefb85ccf6d7bfe8a
[ "Apache-2.0" ]
null
null
null
Libraries/Led/Led.cpp
3KMedialab/Midi-Controller
412f1dff01b9f5c73c75e00aefb85ccf6d7bfe8a
[ "Apache-2.0" ]
1
2018-06-08T12:35:08.000Z
2018-06-08T12:35:08.000Z
Libraries/Led/Led.cpp
3KMedialab/Midi-Controller
412f1dff01b9f5c73c75e00aefb85ccf6d7bfe8a
[ "Apache-2.0" ]
null
null
null
/* * Led.cpp * * Class that represents a Led output component. * * Copyright 2017 3K MEDIALAB * * 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 <Led.h> /* * Constructor * pin: the pin on which the Led is connected to Arduino. */ Led::Led(uint8_t pin) : Component (pin, ComponentType::OUTPUT_DIGITAL) { _state = LOW; digitalWrite(pin, _state); } /* * Constructor * pin: the pin on which the Led is connected to Arduino. * state: indicates if the Led is HIGH or LOW */ Led::Led(uint8_t pin, uint8_t state) : Component (pin, ComponentType::OUTPUT_DIGITAL) { _state = state; digitalWrite(pin, _state); } /* * Assign a state to the Led * state: indicates if the Led is HIGH or LOW */ void Led::setState(uint8_t state) { _state = state; digitalWrite(_pin, _state); } /* * Returns the state of the Led */ uint8_t Led::getState() { return _state; }
23.4
85
0.700142
3KMedialab
5350b333d1af47769c9ef83d1a9b77438b9df807
11,202
cpp
C++
test/StructUnitTest.cpp
dic-iit/matio-cpp
d8a450ea7c3289ca78ea5111aea0f451a8b19b74
[ "BSD-2-Clause" ]
12
2020-11-06T11:02:11.000Z
2021-07-14T20:45:52.000Z
test/StructUnitTest.cpp
dic-iit/matio-cpp
d8a450ea7c3289ca78ea5111aea0f451a8b19b74
[ "BSD-2-Clause" ]
20
2020-11-06T07:35:13.000Z
2021-06-28T08:36:35.000Z
test/StructUnitTest.cpp
ami-iit/matio-cpp
d8a450ea7c3289ca78ea5111aea0f451a8b19b74
[ "BSD-2-Clause" ]
3
2021-09-05T03:10:55.000Z
2022-02-18T09:40:12.000Z
/* * Copyright (C) 2020 Fondazione Istituto Italiano di Tecnologia * * This software may be modified and distributed under the terms of the * BSD-2-Clause license (https://opensource.org/licenses/BSD-2-Clause). */ #include <catch2/catch.hpp> #include <vector> #include <matioCpp/matioCpp.h> void checkSameDimensions(matioCpp::Span<const size_t> a, matioCpp::Span<const size_t> b) { REQUIRE(a.size() == b.size()); for (size_t i = 0; i < static_cast<size_t>(a.size()); ++i) { REQUIRE(a[i] == b[i]); } } void checkVariable(const matioCpp::Variable& var, const std::string& name, matioCpp::VariableType type, matioCpp::ValueType value, bool complex, matioCpp::Span<const size_t> dimensions) { REQUIRE(var.name() == name); REQUIRE(var.variableType() == type); REQUIRE(var.valueType() == value); REQUIRE(var.isComplex() == complex); REQUIRE(var.dimensions().size() == dimensions.size()); checkSameDimensions(dimensions, var.dimensions()); } void checkVariable(const matioCpp::Variable& var, const std::string& name, matioCpp::VariableType type, matioCpp::ValueType value, bool complex, const std::vector<size_t>& dimensions) { checkVariable(var, name, type, value, complex, matioCpp::make_span(dimensions)); } void checkSameVariable(const matioCpp::Variable& a, const matioCpp::Variable& b) { checkVariable(a, b.name(), b.variableType(), b.valueType(), b.isComplex(), b.dimensions()); } void checkSameStruct(const matioCpp::Struct& a, const matioCpp::Struct& b) { checkVariable(a, b.name(), b.variableType(), b.valueType(), b.isComplex(), b.dimensions()); REQUIRE(a.numberOfFields() == b.numberOfFields()); for (size_t i = 0; i < a.numberOfFields(); ++i) { checkSameVariable(a, b); } } template <typename T1, typename T2> void checkSameVector(const T1& a, const T2& b, double precision = 1e-15) { REQUIRE(a.size() == b.size()); for (size_t i = 0; i < static_cast<size_t>(a.size()); ++i) { REQUIRE(std::abs(a[i] - b[i]) < precision); } } TEST_CASE("Constructors") { SECTION("Default") { matioCpp::Struct var; } SECTION("Name") { matioCpp::Struct var("test"); REQUIRE(var.variableType() == matioCpp::VariableType::Struct); REQUIRE(var.valueType() == matioCpp::ValueType::VARIABLE); } SECTION("Name and elements") { std::vector<matioCpp::Variable> data; data.emplace_back(matioCpp::Vector<double>("vector")); data.emplace_back(matioCpp::Element<int>("element")); data.emplace_back(matioCpp::MultiDimensionalArray<double>("array")); data.emplace_back(matioCpp::String("name", "content")); data.emplace_back(matioCpp::Struct("otherStruct")); matioCpp::Struct var("test", data); checkVariable(var, "test", matioCpp::VariableType::Struct, matioCpp::ValueType::VARIABLE, false, {1,1}); } SECTION("Copy constructor") { std::vector<matioCpp::Variable> data; data.emplace_back(matioCpp::Vector<double>("vector")); data.emplace_back(matioCpp::Element<int>("element")); data.emplace_back(matioCpp::MultiDimensionalArray<double>("array")); data.emplace_back(matioCpp::String("name", "content")); data.emplace_back(matioCpp::Struct("otherStruct")); matioCpp::Struct a("test", data); matioCpp::Struct b(a); REQUIRE(b.variableType() == matioCpp::VariableType::Struct); REQUIRE(b.valueType() == matioCpp::ValueType::VARIABLE); } SECTION("Move constructor") { std::vector<matioCpp::Variable> data; data.emplace_back(matioCpp::Vector<double>("vector")); data.emplace_back(matioCpp::Element<int>("element")); data.emplace_back(matioCpp::MultiDimensionalArray<double>("array")); data.emplace_back(matioCpp::String("name", "content")); data.emplace_back(matioCpp::Struct("otherStruct")); matioCpp::Struct a("test", data); matioCpp::Struct b(std::move(a)); REQUIRE(b.variableType() == matioCpp::VariableType::Struct); REQUIRE(b.valueType() == matioCpp::ValueType::VARIABLE); } SECTION("Shared ownership") { std::vector<size_t> dimensions = {1, 1}; std::vector<matvar_t*> data; data.emplace_back(Mat_VarDuplicate(matioCpp::Vector<double>("vector").toMatio(), 1)); data.emplace_back(Mat_VarDuplicate(matioCpp::Element<int>("element").toMatio(), 1)); data.emplace_back(Mat_VarDuplicate(matioCpp::MultiDimensionalArray<double>("array").toMatio(), 1)); data.emplace_back(Mat_VarDuplicate(matioCpp::String("name", "content").toMatio(), 1)); data.emplace_back(Mat_VarDuplicate(matioCpp::Struct("otherStruct").toMatio(), 1)); data.emplace_back(nullptr); matvar_t* matioVar = Mat_VarCreate("test", matio_classes::MAT_C_STRUCT, matio_types::MAT_T_STRUCT, 2, dimensions.data(), data.data(), 0); REQUIRE(matioVar); matioCpp::SharedMatvar sharedMatvar(matioVar); matioCpp::Struct sharedVar(sharedMatvar); REQUIRE(sharedVar.isValid()); REQUIRE(sharedVar.toMatio() == matioVar); checkVariable(sharedVar, "test", matioCpp::VariableType::Struct, matioCpp::ValueType::VARIABLE, false, dimensions); matioCpp::Struct weakVar((matioCpp::WeakMatvar(sharedMatvar))); REQUIRE(weakVar.isValid()); REQUIRE(weakVar.toMatio() == matioVar); checkVariable(weakVar, "test", matioCpp::VariableType::Struct, matioCpp::ValueType::VARIABLE, false, dimensions); } } TEST_CASE("Struct infos") { std::vector<matioCpp::Variable> data; data.emplace_back(matioCpp::Vector<double>("vector")); data.emplace_back(matioCpp::Element<int>("element")); data.emplace_back(matioCpp::MultiDimensionalArray<double>("array")); data.emplace_back(matioCpp::String("name", "content")); data.emplace_back(matioCpp::Struct("otherStruct")); matioCpp::Struct test("test", data); SECTION("Fields") { REQUIRE(test.numberOfFields() == 5); std::vector<std::string> fields = test.fields(); REQUIRE(fields.size() == 5); REQUIRE(fields[0] == "vector"); REQUIRE(fields[1] == "element"); REQUIRE(fields[2] == "array"); REQUIRE(fields[3] == "name"); REQUIRE(fields[4] == "otherStruct"); REQUIRE(test.isFieldExisting("vector")); REQUIRE(test.getFieldIndex("vector") == 0); REQUIRE(test.isFieldExisting("element")); REQUIRE(test.getFieldIndex("element") == 1); REQUIRE(test.isFieldExisting("array")); REQUIRE(test.getFieldIndex("array") == 2); REQUIRE(test.isFieldExisting("name")); REQUIRE(test.getFieldIndex("name") == 3); REQUIRE(test.isFieldExisting("otherStruct")); REQUIRE(test.getFieldIndex("otherStruct") == 4); REQUIRE_FALSE(test.isFieldExisting("inexistent")); } } TEST_CASE("Assignments") { std::vector<matioCpp::Variable> data; data.emplace_back(matioCpp::Vector<double>("vector")); data.emplace_back(matioCpp::Element<int>("element")); data.emplace_back(matioCpp::MultiDimensionalArray<double>("array")); data.emplace_back(matioCpp::String("name", "content")); data.emplace_back(matioCpp::Struct("otherStruct")); matioCpp::Struct in("test", data); matioCpp::Struct out; std::vector<size_t> dimensions = {1, 1}; std::vector<matvar_t*> pointers; pointers.emplace_back(Mat_VarDuplicate(matioCpp::Vector<double>("vector").toMatio(), 1)); pointers.emplace_back(Mat_VarDuplicate(matioCpp::Element<int>("element").toMatio(), 1)); pointers.emplace_back(Mat_VarDuplicate(matioCpp::MultiDimensionalArray<double>("array").toMatio(), 1)); pointers.emplace_back(Mat_VarDuplicate(matioCpp::String("name", "content").toMatio(), 1)); pointers.emplace_back(Mat_VarDuplicate(matioCpp::Struct("otherStruct").toMatio(), 1)); pointers.emplace_back(nullptr); matvar_t* matioVar = Mat_VarCreate("test", matio_classes::MAT_C_STRUCT, matio_types::MAT_T_STRUCT, 2, dimensions.data(), pointers.data(), 0); REQUIRE(matioVar); SECTION("From matio") { matioCpp::Struct var; REQUIRE(var.fromMatio(matioVar)); checkVariable(var, "test", matioCpp::VariableType::Struct, matioCpp::ValueType::VARIABLE, false, dimensions); } SECTION("Copy assignement") { matioCpp::Struct another; another = in; checkSameStruct(another, in); } SECTION("Move assignement") { matioCpp::Struct another, yetAnother; yetAnother = in; another = std::move(yetAnother); checkSameStruct(another, in); } SECTION("From other variable (copy)") { matioCpp::Variable var(matioVar); matioCpp::Struct array; REQUIRE(array.fromOther(var)); checkSameVariable(var, array); } SECTION("From other variable (move)") { matioCpp::Variable var(matioVar), var2; REQUIRE(var2.fromOther(var)); matioCpp::Struct array; REQUIRE(array.fromOther(std::move(var2))); checkSameVariable(var, array); } SECTION("From vector of Variables") { matioCpp::Struct imported("test"); REQUIRE(imported.fromVectorOfVariables(data)); checkSameStruct(in, imported); } Mat_VarFree(matioVar); } TEST_CASE("Modifications") { std::vector<matioCpp::Variable> data; data.emplace_back(matioCpp::Vector<double>("vector", 4)); data.emplace_back(matioCpp::Element<int>("element")); data.emplace_back(matioCpp::MultiDimensionalArray<double>("array")); data.emplace_back(matioCpp::String("name", "content")); data.emplace_back(matioCpp::Struct("otherStruct")); matioCpp::Struct in("test", data); matioCpp::Struct out; out = in; REQUIRE(out.setName("t")); REQUIRE(out.name() == "t"); std::vector<double> vectorIn; vectorIn.push_back(10); vectorIn.push_back(12); vectorIn.push_back(14); vectorIn.push_back(16); in(0).asVector<double>() = vectorIn; checkSameVector(in(0).asVector<double>(), vectorIn); in["element"].asElement<int>() = 7; REQUIRE(in[1].asElement<int>() == 7); matioCpp::CellArray cellArray("array"); REQUIRE(in.setField(cellArray)); REQUIRE(in[2].variableType() == matioCpp::VariableType::CellArray); matioCpp::String anotherString("another", "anotherString"); matioCpp::Variable previousElement = in(3); REQUIRE(previousElement.isValid()); REQUIRE(in.setField(3, anotherString)); REQUIRE(in("name").asString()() == "anotherString"); REQUIRE_FALSE(previousElement.isValid()); matioCpp::String string("yetAnotherString"); REQUIRE(in.setField("name", string)); REQUIRE(in("name").asString()() == "yetAnotherString"); in.clear(); REQUIRE(in.numberOfFields() == 0); }
33.240356
145
0.642207
dic-iit
5351edb474349634d08ce5c41cdcdb8a7809b766
2,920
cpp
C++
Demo.cpp
liurui39660/SNNDPC
2e75cd318335731b431eff66a54ea2b0c1ff29b8
[ "Apache-2.0" ]
23
2020-03-16T02:50:05.000Z
2022-03-29T00:51:40.000Z
Demo.cpp
liurui39660/SNNDPC
2e75cd318335731b431eff66a54ea2b0c1ff29b8
[ "Apache-2.0" ]
6
2020-03-08T07:18:48.000Z
2022-03-11T03:24:06.000Z
Demo.cpp
liurui39660/SNNDPC
2e75cd318335731b431eff66a54ea2b0c1ff29b8
[ "Apache-2.0" ]
10
2020-06-12T06:21:24.000Z
2021-11-15T11:38:02.000Z
#include <chrono> #include "SNNDPC.hpp" using namespace std::chrono; int main(int argc, char* argv[]) { // Parameter // -------------------------------------------------------------------------------- const auto pathData = SOLUTION_DIR"data/S2.tsv"; const int k = 35; const int n = 5000; // Number of data points const int d = 2; // Dimension const int nc = 15; // Number of centroids // Read dataset // -------------------------------------------------------------------------------- int label[n]; float data[n * d]; const auto fileData = fopen(pathData, "r"); for (int i = 0; i < n; i++) fscanf(fileData, "%f %f %d\n", &data[i * d], &data[i * d + 1], &label[i]); fclose(fileData); // Export ground truth // -------------------------------------------------------------------------------- const auto pathGroundTruth = SOLUTION_DIR"temp/GroundTruth.txt"; const auto fileGroundTruth = fopen(pathGroundTruth, "w"); for (int i: label) fprintf(fileGroundTruth, "%d\n", i); fclose(fileGroundTruth); // Normalize // -------------------------------------------------------------------------------- float least[d], most[d]; const auto infinity = std::numeric_limits<float>::infinity(); std::fill(least, least + d, infinity); std::fill(most, most + d, -infinity); for (int i = 0; i < n; i++) for (int j = 0; j < d; j++) { least[j] = std::min(least[j], data[i * d + j]); most[j] = std::max(most[j], data[i * d + j]); } for (int i = 0; i < n; i++) for (int j = 0; j < d; j++) data[i * d + j] = (data[i * d + j] - least[j]) / (most[j] - least[j]); // Do the magic // -------------------------------------------------------------------------------- const auto time = high_resolution_clock::now(); const auto [centroid, assignment] = SNNDPC(k, n, d, nc, data); printf("Time Cost = %lldms\n", duration_cast<milliseconds>(high_resolution_clock::now() - time).count()); // Export centroid // -------------------------------------------------------------------------------- const auto fileCentroid = fopen(SOLUTION_DIR"temp/Centroid.txt", "w"); for (int i = 0; i < nc; i++) fprintf(fileCentroid, "%d\n", centroid[i]); fclose(fileCentroid); // Export assignment // -------------------------------------------------------------------------------- const auto pathAssignment = SOLUTION_DIR"temp/Assignment.txt"; const auto fileAssignment = fopen(pathAssignment, "w"); for (int i = 0; i < n; i++) fprintf(fileAssignment, "%d\n", assignment[i]); fclose(fileAssignment); // Evaluate // -------------------------------------------------------------------------------- char command[1024]; sprintf(command, "python %s %s %s", SOLUTION_DIR"EvaluateAssignment.py", pathGroundTruth, pathAssignment); system(command); // Clean up // -------------------------------------------------------------------------------- delete[] centroid; delete[] assignment; }
32.808989
107
0.473288
liurui39660
53521fe0098612ae16ecd655a01b05afc3b28d3e
2,039
cpp
C++
tree-distance/main.cpp
svenstaro/challenges
3434b63ba585799eafac695a36cfc1bfbfb8a89d
[ "MIT" ]
null
null
null
tree-distance/main.cpp
svenstaro/challenges
3434b63ba585799eafac695a36cfc1bfbfb8a89d
[ "MIT" ]
null
null
null
tree-distance/main.cpp
svenstaro/challenges
3434b63ba585799eafac695a36cfc1bfbfb8a89d
[ "MIT" ]
null
null
null
#include <iostream> struct Node { int value = 0; Node* left = nullptr; Node* right = nullptr; }; int dfs(Node* root, Node* needle, int depth) { if (root == needle) { return depth; } if (root->left) { int result = dfs(root->left, needle, depth + 1); if (result >= 0) { return result; } } if (root->right) { int result = dfs(root->right, needle, depth + 1); if (result >= 0) { return result; } } return -1; } Node* lca(Node* root, Node* v, Node* w) { // Check whether the nodes we seach for are in the same // or separate subtrees. if (root->left && dfs(root->left, v, 0) >= 0 && dfs(root->left, w, 0) >= 0) return lca(root->left, v, w); else if (root->right && dfs(root->right, v, 0) >= 0 && dfs(root->right, w, 0) >= 0) return lca(root->right, v, w); else return root; } int dist(Node* root, Node* v, Node* w) { Node* common = lca(root, v, w); return dfs(common, v, 0) + dfs(common, w, 0); } int main(int argc, char *argv[]) { (void)argc; (void)argv; Node* root = new Node; root->value = 0; Node* n1 = new Node; n1->value = 1; Node* n2 = new Node; n2->value = 2; Node* n3 = new Node; n3->value = 3; Node* n4 = new Node; n4->value = 4; Node* n5 = new Node; n5->value = 5; Node* n6 = new Node; n6->value = 6; Node* n7 = new Node; n7->value = 7; Node* n8 = new Node; n8->value = 8; /* root / \ n1 n2 / \ / \ n3 n4 n5 n6 / \ n7 n8 */ root->left = n1; root->right = n2; n1->left = n3; n1->right = n4; n2->left = n5; n2->right = n6; n3->left = n7; n3->right = n8; std::cout << dist(root, n7, n6) << std::endl; // 5 std::cout << dist(root, n7, n4) << std::endl; // 3 std::cout << dist(root, n7, n8) << std::endl; // 2 return 0; }
19.056075
87
0.470329
svenstaro
53533278615ced6d910d02be431d600c1ae9194a
442
cpp
C++
Super Synthesis Engine/Source/Random/Random.cpp
nstearns96/Super-Synthesis-Engine
64824c50557e64decc9710a5b2aa63cd93712122
[ "MIT" ]
null
null
null
Super Synthesis Engine/Source/Random/Random.cpp
nstearns96/Super-Synthesis-Engine
64824c50557e64decc9710a5b2aa63cd93712122
[ "MIT" ]
null
null
null
Super Synthesis Engine/Source/Random/Random.cpp
nstearns96/Super-Synthesis-Engine
64824c50557e64decc9710a5b2aa63cd93712122
[ "MIT" ]
null
null
null
#include "Random/Random.h" namespace SSE { std::default_random_engine Random::randomEngine; bool Random::init() { std::random_device randomDevice; randomEngine.seed(randomDevice()); return true; } i32 Random::randInt(i32 min, i32 max) { return std::uniform_int_distribution<i32>{min, max}(randomEngine); } r32 Random::rand(r32 min, r32 max) { return std::uniform_real_distribution<r32>{min, max}(randomEngine); } };
17.68
69
0.714932
nstearns96
536431c4b708ead0c57095f5141f50d5777ba25a
371
cpp
C++
luogu/p1060.cpp
freedomDR/coding
310a68077de93ef445ccd2929e90ba9c22a9b8eb
[ "MIT" ]
null
null
null
luogu/p1060.cpp
freedomDR/coding
310a68077de93ef445ccd2929e90ba9c22a9b8eb
[ "MIT" ]
null
null
null
luogu/p1060.cpp
freedomDR/coding
310a68077de93ef445ccd2929e90ba9c22a9b8eb
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; vector<int> v(m), p(m), f(n+1); for(int i = 0; i < m; i++) cin >> v[i] >> p[i]; for(int i = 0; i < m; i++) { for(int j = n; j >= v[i]; j--) { f[j] = max(f[j], f[j-v[i]]+v[i]*p[i]); } } cout << f[n] << endl; return 0; }
20.611111
51
0.374663
freedomDR
536487bcf37f7d72dead2462f400c0b270a2b3be
151
cpp
C++
test/src/mock/animator.cpp
KazDragon/munin
ca5ae77cf5f75f6604fddd1a39393fa6acb88769
[ "MIT" ]
6
2017-07-15T10:16:20.000Z
2021-06-14T10:02:37.000Z
test/src/mock/animator.cpp
KazDragon/munin
ca5ae77cf5f75f6604fddd1a39393fa6acb88769
[ "MIT" ]
243
2017-05-01T19:27:07.000Z
2021-09-01T09:32:49.000Z
test/src/mock/animator.cpp
KazDragon/munin
ca5ae77cf5f75f6604fddd1a39393fa6acb88769
[ "MIT" ]
2
2019-07-16T00:29:43.000Z
2020-09-19T09:49:00.000Z
#include "mock/animator.hpp" std::shared_ptr<mock_animator> make_mock_animator() { return std::make_shared<testing::NiceMock<mock_animator>>(); }
21.571429
64
0.754967
KazDragon
5365e36475358434d0626764949a3e4e68227c3b
745
cpp
C++
BOJ_CPP/8273.cpp
tnsgh9603/BOJ_CPP
432b1350f6c67cce83aec3e723e30a3c6b5dbfda
[ "MIT" ]
null
null
null
BOJ_CPP/8273.cpp
tnsgh9603/BOJ_CPP
432b1350f6c67cce83aec3e723e30a3c6b5dbfda
[ "MIT" ]
null
null
null
BOJ_CPP/8273.cpp
tnsgh9603/BOJ_CPP
432b1350f6c67cce83aec3e723e30a3c6b5dbfda
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define fastio ios::sync_with_stdio(0), cin.tie(0), cout.tie(0) using namespace std; typedef long long ll; int main() { fastio; ll n, cnt = 0; cin >> n; vector<ll> v(n); for (int i = 0, a, b; i < n && cin >> a >> b; v[i++] = a + b); for (int i = 0, j = 0; i < n; i = j, ++cnt) { for (ll l = 0, r = v[i], t = 0; j < n && l <= r; ++j) { const ll val = j + 1 < n ? min(v[j], v[j + 1]) : v[j]; t = v[j] - t; if (j - i + 1 & 1) { l = max(l, t - val); r = min(r, t); } else { l = max(l, -t); r = min(r, val - t); } } } cout << n - cnt; return 0; }
25.689655
66
0.358389
tnsgh9603
53685dc4fb35e4d407b0a4f0627ee8a01eda8f1c
1,467
hpp
C++
sources/Notebook.hpp
itamaralmog/notebook-b
a511e2eb06c26cad5c684bd58ddf47c95eb004f0
[ "MIT" ]
null
null
null
sources/Notebook.hpp
itamaralmog/notebook-b
a511e2eb06c26cad5c684bd58ddf47c95eb004f0
[ "MIT" ]
null
null
null
sources/Notebook.hpp
itamaralmog/notebook-b
a511e2eb06c26cad5c684bd58ddf47c95eb004f0
[ "MIT" ]
null
null
null
#ifndef NOTEBOOK #define NOTEBOOK #include <string> #include "Direction.hpp" #include <vector> const int NUM_OF_COLUMNS = 100; // should be 100 const char EMPTY_PLACE = '_'; const char ERASE_PLACE = '~'; const int DEFULT_LENGTH = 10; const int START_RANGE_OF_CHARS = 32; const int END_RANGE_OF_CHARS = 126; const int NUM_RANGE_OF_CHARS = 256; namespace ariel{ class Notebook{ public: std::vector<std::vector<std::vector<char>>> * note_mat; bool exist; Notebook(){ this-> exist = true; this-> note_mat = new std::vector<std::vector<std::vector<char>>>(); } ~Notebook(){ delete this-> note_mat; } // void write(uint x,uint y, unsigned int z, Direction direct,const std::string &str); // static std::string read(uint x, uint y, uint z, Direction direct,uint length); // void erase(uint x,uint y, uint z, Direction direct, uint length); // void show(uint page); void write(int x,int y, int z, Direction direct,const std::string &str); std::string read(int x, int y, int z, Direction direct,int length) const; void erase(int x,int y, int z, Direction direct, int length) const; void show(int page) const; // private: // void addpages(int x,int y, int z,Direction direct, int length,Notebook note_mat); }; } #endif
34.116279
98
0.596455
itamaralmog
5368be57c66547fd5a9d2c04ce5277de04482b74
3,280
hh
C++
include/fabrique/names.hh
fabriquer/fabrique
d141ef698ddbeddb5b800f7f906d93751a06f809
[ "BSD-2-Clause" ]
2
2018-11-12T22:51:37.000Z
2019-03-13T12:46:03.000Z
include/fabrique/names.hh
fabriquer/fabrique
d141ef698ddbeddb5b800f7f906d93751a06f809
[ "BSD-2-Clause" ]
23
2015-03-06T16:14:49.000Z
2019-04-04T18:08:52.000Z
include/fabrique/names.hh
fabriquer/fabrique
d141ef698ddbeddb5b800f7f906d93751a06f809
[ "BSD-2-Clause" ]
null
null
null
//! @file names.hh Names defined or reserved by the Fabrique language /* * Copyright (c) 2018-2019 Jonathan Anderson * All rights reserved. * * This software was developed at Memorial University of Newfoundland * under the NSERC Discovery program (RGPIN-2015-06048). * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. */ #ifndef FAB_NAMES_H_ #define FAB_NAMES_H_ #include <string> namespace fabrique { namespace names { // // Reserved names: it is not permissible to define values with these names. // static const char Action[] = "action"; static const char And[] = "and"; static const char Arguments[] = "args"; static const char Bool[] = "bool"; static const char BuildDirectory[] = "builddir"; static const char BuildRoot[] = "buildroot"; static const char False[] = "false"; static const char Fields[] = "fields"; static const char File[] = "file"; static const char Files[] = "files"; static const char Function[] = "function"; static const char Import[] = "import"; static const char In[] = "in"; static const char Int[] = "int"; static const char List[] = "list"; static const char Nil[] = "nil"; static const char Not[] = "not"; static const char Or[] = "or"; static const char Out[] = "out"; static const char Print[] = "print"; static const char Record[] = "record"; static const char SourceRoot[] = "srcroot"; static const char String[] = "string"; static const char True[] = "true"; static const char Type[] = "type"; static const char TypeOf[] = "typeof"; static const char XOr[] = "xor"; // // Other names defined to have specific meanings in some contexts // but still usable as user-defined names. // static const char Basename[] = "basename"; static const char Extension[] = "extension"; static const char Generated[] = "generated"; static const char FileName[] = "filename"; static const char FullName[] = "fullname"; static const char Name[] = "name"; static const char Subdirectory[] = "subdir"; bool reservedName(const std::string&); } // namespace names } // namespace fabrique #endif // FAB_NAMES_H_
36.853933
77
0.729573
fabriquer
536982251a4430219d56d4e5ad9db862d02d8313
755
hpp
C++
StickWatch/src/ArduinoJson_6.2.0-beta/ArduinoJson/Strings/StringTypes.hpp
stahifpv/StickWatch
b9f2b3824e62b4e2366859559dbb19a531560758
[ "Apache-2.0" ]
83
2019-01-24T01:32:21.000Z
2022-02-20T06:54:43.000Z
src/ArduinoJson_6.2.0-beta/ArduinoJson/Strings/StringTypes.hpp
sysdl132/m5stack-stickwatch
968087b9f1b06e64e45699b0f4ac22ffb3e6f2a9
[ "Apache-2.0" ]
5
2019-02-18T12:19:31.000Z
2020-04-26T01:37:47.000Z
src/ArduinoJson_6.2.0-beta/ArduinoJson/Strings/StringTypes.hpp
sysdl132/m5stack-stickwatch
968087b9f1b06e64e45699b0f4ac22ffb3e6f2a9
[ "Apache-2.0" ]
27
2019-01-26T14:12:14.000Z
2022-02-28T14:38:14.000Z
// ArduinoJson - arduinojson.org // Copyright Benoit Blanchon 2014-2018 // MIT License #pragma once #include "../Polyfills/type_traits.hpp" namespace ArduinoJson { namespace Internals { template <typename> struct IsString : false_type {}; template <typename T> struct IsString<const T> : IsString<T> {}; template <typename T> struct IsString<T&> : IsString<T> {}; } // namespace Internals } // namespace ArduinoJson #include "FixedSizeRamString.hpp" #include "ZeroTerminatedRamString.hpp" #if ARDUINOJSON_ENABLE_STD_STRING #include "StlString.hpp" #endif #if ARDUINOJSON_ENABLE_ARDUINO_STRING #include "ArduinoString.hpp" #endif #if ARDUINOJSON_ENABLE_PROGMEM #include "FixedSizeFlashString.hpp" #include "ZeroTerminatedFlashString.hpp" #endif
20.405405
42
0.776159
stahifpv
5370056914bfdfe6034867a131acfab0054992d3
1,573
cpp
C++
galaxy/src/galaxy/graphics/Colour.cpp
DomRe/galaxy
dbffcbe3ff1ea0f1cb1f23a554b13be0eb681a57
[ "Apache-2.0" ]
19
2020-02-02T16:36:46.000Z
2021-12-25T07:02:28.000Z
galaxy/src/galaxy/graphics/Colour.cpp
DomRe/galaxy
dbffcbe3ff1ea0f1cb1f23a554b13be0eb681a57
[ "Apache-2.0" ]
103
2020-10-13T09:03:42.000Z
2022-03-26T03:41:50.000Z
galaxy/src/galaxy/graphics/Colour.cpp
DomRe/galaxy
dbffcbe3ff1ea0f1cb1f23a554b13be0eb681a57
[ "Apache-2.0" ]
5
2020-03-13T06:14:37.000Z
2021-12-12T02:13:46.000Z
/// /// Colour.cpp /// galaxy /// /// Refer to LICENSE.txt for more details. /// #include "Colour.hpp" namespace galaxy { namespace graphics { Colour::Colour() noexcept : m_red {255} , m_green {255} , m_blue {255} , m_alpha {255} { } Colour::Colour(const std::uint8_t r, const std::uint8_t g, const std::uint8_t b, const std::uint8_t a) noexcept : m_red {r} , m_green {g} , m_blue {b} , m_alpha {a} { } glm::vec4 Colour::normalized() noexcept { glm::vec4 out = {r_normal(), g_normal(), b_normal(), a_normal()}; return out; } const float Colour::r_normal() noexcept { if (m_red == 0) { return 0.0f; } else if (m_red == 255) { return 1.0f; } else { return static_cast<float>(m_red) / static_cast<float>(0xFF); } } const float Colour::g_normal() noexcept { if (m_green == 0) { return 0.0f; } else if (m_green == 255) { return 1.0f; } else { return static_cast<float>(m_green) / static_cast<float>(0xFF); } } const float Colour::b_normal() noexcept { if (m_blue == 0) { return 0.0f; } else if (m_blue == 255) { return 1.0f; } else { return static_cast<float>(m_blue) / static_cast<float>(0xFF); } } const float Colour::a_normal() noexcept { if (m_alpha == 0) { return 0.0f; } else if (m_alpha == 255) { return 1.0f; } else { return static_cast<float>(m_alpha) / static_cast<float>(0xFF); } } } // namespace graphics } // namespace galaxy
15.574257
113
0.562619
DomRe
53704cdb6bcba879e754189e21e1248aaee76b42
913
cpp
C++
test/concurrency_latch_wait_multiple_times.cpp
Farwaykorse/coroutine
cfe7f0ca5ab4670e539a9f4d6c69d85ba4cb18f7
[ "CC-BY-4.0" ]
null
null
null
test/concurrency_latch_wait_multiple_times.cpp
Farwaykorse/coroutine
cfe7f0ca5ab4670e539a9f4d6c69d85ba4cb18f7
[ "CC-BY-4.0" ]
null
null
null
test/concurrency_latch_wait_multiple_times.cpp
Farwaykorse/coroutine
cfe7f0ca5ab4670e539a9f4d6c69d85ba4cb18f7
[ "CC-BY-4.0" ]
null
null
null
// // Author : github.com/luncliff (luncliff@gmail.com) // License : CC BY 4.0 // #include <concurrency_helper.h> #include <coroutine/return.h> #include "test.h" using namespace std; using namespace coro; auto concrt_latch_wait_multiple_test() { latch wg{1}; _require_(wg.is_ready() == false); wg.count_down_and_wait(); _require_(wg.is_ready()); _require_(wg.is_ready()); // mutliple test is ok return EXIT_SUCCESS; } #if defined(CMAKE_TEST) int main(int, char* []) { return concrt_latch_wait_multiple_test(); } #elif __has_include(<CppUnitTest.h>) #include <CppUnitTest.h> template <typename T> using TestClass = ::Microsoft::VisualStudio::CppUnitTestFramework::TestClass<T>; class concrt_latch_wait_multiple : public TestClass<concrt_latch_wait_multiple> { TEST_METHOD(test_concrt_latch_wait_multiple) { concrt_latch_wait_multiple_test(); } }; #endif
21.738095
80
0.720701
Farwaykorse