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
77c31a4b17796c91afaf5dba4b15e6f00824e5c1
5,777
cpp
C++
hdf/HDFAtom.cpp
ggraham/blasr_libcpp
4abef36585bbb677ebc4acb9d4e44e82331d59f7
[ "RSA-MD" ]
4
2015-07-03T11:59:54.000Z
2018-05-17T00:03:22.000Z
hdf/HDFAtom.cpp
ggraham/blasr_libcpp
4abef36585bbb677ebc4acb9d4e44e82331d59f7
[ "RSA-MD" ]
79
2015-06-29T18:07:21.000Z
2018-09-19T13:38:39.000Z
hdf/HDFAtom.cpp
ggraham/blasr_libcpp
4abef36585bbb677ebc4acb9d4e44e82331d59f7
[ "RSA-MD" ]
19
2015-06-23T08:43:29.000Z
2021-04-28T18:37:47.000Z
#include <hdf/HDFAtom.hpp> template <> void HDFAtom<std::string>::Create(H5::H5Object &object, const std::string &atomName) { H5::StrType strType(0, H5T_VARIABLE); hsize_t defaultDims[] = {1}; H5::DataSpace defaultDataSpace(1, defaultDims); attribute = object.createAttribute(atomName.c_str(), strType, H5::DataSpace(H5S_SCALAR)); } #define DEFINE_TYPED_CREATE_ATOM(T, predtype) \ template <> \ void HDFAtom<T>::TypedCreate(H5::H5Object &object, const std::string &atomName, \ H5::DataSpace &defaultDataSpace) \ { \ attribute = object.createAttribute(atomName.c_str(), (predtype), defaultDataSpace); \ } DEFINE_TYPED_CREATE_ATOM(int, H5::PredType::NATIVE_INT) DEFINE_TYPED_CREATE_ATOM(unsigned int, H5::PredType::NATIVE_UINT) DEFINE_TYPED_CREATE_ATOM(unsigned char, H5::PredType::NATIVE_UINT8) DEFINE_TYPED_CREATE_ATOM(char, H5::PredType::NATIVE_INT8) DEFINE_TYPED_CREATE_ATOM(float, H5::PredType::NATIVE_FLOAT) DEFINE_TYPED_CREATE_ATOM(uint16_t, H5::PredType::NATIVE_UINT16) DEFINE_TYPED_CREATE_ATOM(uint64_t, H5::PredType::STD_I64LE) template <> void HDFAtom<std::vector<int> >::Write(const std::vector<int> vect) { hsize_t length = vect.size(); H5::DataType baseType = H5::PredType::NATIVE_INT; H5::ArrayType arrayDataType(baseType, 1, &length); attribute.write(arrayDataType, &((vect)[0])); } template <> void HDFAtom<std::string>::Write(std::string value) { // H5::StrType strType(0, value.size()); H5::StrType strType(0, H5T_VARIABLE); attribute.write(strType, std::string(value.c_str())); } template <> void HDFAtom<uint64_t>::Write(uint64_t value) { attribute.write(H5::PredType::STD_I64LE, &value); } template <> void HDFAtom<int>::Write(int value) { attribute.write(H5::PredType::NATIVE_INT, &value); } template <> void HDFAtom<unsigned int>::Write(unsigned int value) { attribute.write(H5::PredType::NATIVE_INT, &value); } template <> void HDFAtom<unsigned char>::Write(unsigned char value) { attribute.write(H5::PredType::NATIVE_UINT8, &value); } template <> void HDFAtom<uint16_t>::Write(uint16_t value) { attribute.write(H5::PredType::NATIVE_UINT16, &value); } template <> void HDFAtom<char>::Write(char value) { attribute.write(H5::PredType::NATIVE_INT8, &value); } template <> void HDFAtom<float>::Write(float value) { attribute.write(H5::PredType::NATIVE_FLOAT, &value); } template <> void HDFAtom<std::string>::Read(std::string &value) { /* * Read in a std::string that has been stored either as an array or a * variable length std::string. To decide which, query the * isVariableStr() option. */ H5::StrType stringType = attribute.getStrType(); bool stringIsVariableLength = stringType.isVariableStr(); if (stringIsVariableLength) attribute.read(stringType, value); else { hsize_t stsize = attribute.getStorageSize(); value.resize(stsize); attribute.read(stringType, &value[0]); if (stsize > 0 and value[stsize - 1] == '\0') { value.resize(stsize - 1); } } } template <> void HDFAtom<int>::Read(int &value) { H5::DataType intType(H5::PredType::NATIVE_INT); attribute.read(intType, &value); } template <> void HDFAtom<uint16_t>::Read(uint16_t &value) { H5::DataType intType(H5::PredType::NATIVE_UINT16); attribute.read(intType, &value); } template <> void HDFAtom<uint64_t>::Read(uint64_t &value) { H5::DataType intType(H5::PredType::STD_I64LE); attribute.read(intType, &value); } template <> void HDFAtom<unsigned int>::Read(unsigned int &value) { H5::DataType uintType(H5::PredType::NATIVE_UINT); attribute.read(uintType, &value); } template <> void HDFAtom<float>::Read(float &value) { H5::DataType type(H5::PredType::NATIVE_FLOAT); attribute.read(type, &value); } template <> void HDFAtom<std::vector<std::string> >::Read(std::vector<std::string> &values) { std::string value; /* * This attribute is an array of std::strings. They are read in by * storing pointers to std::strings in memory controlled by HDF. To read * the std::strings, read the pointers into a temporary array, then copy * those std::strings to the values array. This way when the values array * is destroyed, it will not try and get rid of space that is under * HDF control. */ H5::DataSpace attributeSpace = attribute.getSpace(); hsize_t nPoints; nPoints = attributeSpace.getSelectNpoints(); H5::DataType attrType = attribute.getDataType(); // necessary for attr.read() // Declare and initialize std::vector of pointers to std::string attribute list. std::vector<char *> ptrsToHDFControlledMemory; ptrsToHDFControlledMemory.resize(nPoints); // Copy the pointers. attribute.read(attrType, &ptrsToHDFControlledMemory[0]); // Copy the std::strings into memory the main program has control over. unsigned int i; for (i = 0; i < ptrsToHDFControlledMemory.size(); i++) { values.push_back(ptrsToHDFControlledMemory[i]); free(ptrsToHDFControlledMemory[i]); } } // Explict instantiate classes template class HDFAtom<int>; template class HDFAtom<unsigned int>; template class HDFAtom<char>; template class HDFAtom<unsigned char>; template class HDFAtom<uint64_t>; template class HDFAtom<float>; template class HDFAtom<std::string>; template class HDFAtom<std::vector<int> >; template class HDFAtom<std::vector<unsigned int> >; template class HDFAtom<std::vector<std::string> >;
31.396739
93
0.67336
ggraham
77c9c917282782bff71239cb08fc720f5b9ce9b1
185
cpp
C++
renderer/Ray.cpp
AdrienVannson/3D-Renderer
78148e88b9ab91ccaea0f883a746ee93cac5d767
[ "MIT" ]
null
null
null
renderer/Ray.cpp
AdrienVannson/3D-Renderer
78148e88b9ab91ccaea0f883a746ee93cac5d767
[ "MIT" ]
null
null
null
renderer/Ray.cpp
AdrienVannson/3D-Renderer
78148e88b9ab91ccaea0f883a746ee93cac5d767
[ "MIT" ]
1
2021-03-18T08:05:35.000Z
2021-03-18T08:05:35.000Z
#include "Ray.hpp" Ray::Ray (const Vect &pos, const Vect &dir) : m_pos (pos), m_dir (dir) { m_dir.normalize(); } void Ray::moveByEpsilon () { m_pos += 1e-5 * m_dir; }
13.214286
45
0.572973
AdrienVannson
77cb146f356229fe62208f9c724d8f9e7374900b
2,773
cpp
C++
src/examples/Serialisation/example1.cpp
gwaredd/reflector
f7c4184e5bd98d3744dfb45ea8cd4030b8078bae
[ "MIT" ]
8
2015-03-27T06:15:27.000Z
2021-07-04T03:45:10.000Z
src/examples/Serialisation/example1.cpp
gwaredd/reflector
f7c4184e5bd98d3744dfb45ea8cd4030b8078bae
[ "MIT" ]
null
null
null
src/examples/Serialisation/example1.cpp
gwaredd/reflector
f7c4184e5bd98d3744dfb45ea8cd4030b8078bae
[ "MIT" ]
3
2016-06-21T12:39:14.000Z
2019-08-27T15:48:25.000Z
//////////////////////////////////////////////////////////////////////////////// #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <time.h> #include "json.h" #include "classes.h" std::vector< GameObject* > GameObjects; //////////////////////////////////////////////////////////////////////////////// void Create() { srand( (unsigned int) time( nullptr ) ); for( int i=0; i < 10; i++ ) { auto go = new GameObject(); GameObjects.push_back( go->CreateRandom() ); } } //////////////////////////////////////////////////////////////////////////////// void Save( const char* filename ) { // create output file std::cout << "Saving '" << filename << "'" << std::endl; auto fp = fopen( filename, "wb" ); if( fp == nullptr ) { std::cerr << "Failed to open output file" << std::endl; return; } char writeBuffer[ 65536 ]; FileWriteStream os( fp, writeBuffer, sizeof( writeBuffer ) ); PrettyWriter< FileWriteStream > writer( os ); // save objects via reflection writer.StartArray(); for( auto o : GameObjects ) { ExampleWrite( writer, o->GetType(), o ); } writer.EndArray(); fclose( fp ); } //////////////////////////////////////////////////////////////////////////////// void Load( const char* filename ) { // open file std::cout << "Loading '" << filename << "'" << std::endl; auto fp = fopen( filename, "rb" ); if( fp == nullptr ) { std::cerr << "Failed to open input file" << std::endl; return; } char readBuffer[ 65536 ]; FileReadStream is( fp, readBuffer, sizeof( readBuffer ) ); // parse document Document doc; doc.ParseStream( is ); if( doc.IsArray() ) { std::string ObjTag = "GameObject"; for( auto itr = doc.Begin(); itr != doc.End(); ++itr ) { const Document::GenericValue& node = *itr; if( node.HasMember( "Type" ) && ObjTag == node[ "Type" ].GetString() ) { if( auto obj = ExampleRead( nullptr, *itr ) ) { auto go = reinterpret_cast<GameObject*>( obj ); GameObjects.push_back( go ); } } } } else { std::cerr << "Was expecting an array" << std::endl; } fclose(fp); } //////////////////////////////////////////////////////////////////////////////// int main( int argc, char* argv[] ) { auto filename = argc > 1 ? argv[1] : "Serialisation/gameobjects.json"; /** Create(); Save( filename ); /*/ Load( filename ); /**/ std::cout << "We have " << GameObjects.size() << " objects" << std::endl; return 0; }
20.69403
82
0.443563
gwaredd
77d30eab9a22ff8d87a8b37f87a3941556abde12
377
cpp
C++
docs/mfc/reference/codesnippet/CPP/cmfctoolbarbutton-class_1.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
14
2018-01-28T18:10:55.000Z
2021-11-16T13:21:18.000Z
docs/mfc/reference/codesnippet/CPP/cmfctoolbarbutton-class_1.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
1
2021-04-01T04:17:07.000Z
2021-04-01T04:17:07.000Z
docs/mfc/reference/codesnippet/CPP/cmfctoolbarbutton-class_1.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
2
2018-11-01T12:33:08.000Z
2021-11-16T13:21:19.000Z
CMFCToolBarButton* pOffice2007 = NULL; int nIndex = -1; for (UINT uiCmd = ID_VIEW_APPLOOK_2007_1; uiCmd <= ID_VIEW_APPLOOK_2007_4; uiCmd++) { // CMFCToolBar m_wndToolBarTheme nIndex = m_wndToolBarTheme.CommandToIndex (uiCmd); CMFCToolBarButton* pButton = m_wndToolBarTheme.GetButton (nIndex); if (pButton != NULL) { pOffice2007 = pButton; break; } }
23.5625
84
0.71618
jmittert
77dae2c04282627fd4f9a0978948934f845c8a8c
7,410
cpp
C++
sssp-cuda/src/util.cpp
aeonstasis/sssp-fpga
6ea890f159176695a50f1d7bc2ed1406d1d8599c
[ "MIT" ]
7
2019-05-23T06:57:01.000Z
2022-03-09T06:24:29.000Z
sssp-cuda/src/util.cpp
aaron-zou/sssp-fpga
6ea890f159176695a50f1d7bc2ed1406d1d8599c
[ "MIT" ]
null
null
null
sssp-cuda/src/util.cpp
aaron-zou/sssp-fpga
6ea890f159176695a50f1d7bc2ed1406d1d8599c
[ "MIT" ]
1
2018-08-11T09:55:33.000Z
2018-08-11T09:55:33.000Z
#include "util.h" #include "pthread.h" #include <algorithm> #include <cmath> #include <fstream> #include <iostream> #include <random> #include <sstream> #include <stdexcept> using std::vector; namespace util { vector<Point> random_centroids(int k, size_t num_features) { auto centroids = vector<Point>{}; for (int i = 0; i < k; i++) { centroids.push_back(Point::random(num_features)); } return centroids; } Point Point::random(size_t dim) { auto point = vector<double>(dim); std::generate(point.begin(), point.end(), []() { return static_cast<double>(std::rand()) / RAND_MAX; }); return Point{point}; } double Point::dist(const Point &other) const { if (this->dim() != other.dim()) { throw std::invalid_argument( "Point::dist(): two points must have same dimensionality!"); } double result = 0.0f; for (size_t i = 0; i < this->dim(); i++) { result += std::pow(this->_point[i] - other._point[i], 2); } return std::sqrt(result); } Point &Point::operator+=(const Point &other) { if (this->dim() != other.dim()) { throw std::invalid_argument( "Point::operator+=(): two points must have same dimensionality!"); } for (size_t i = 0; i < this->dim(); i++) { this->_point[i] += other._point[i]; } return *this; } Point &Point::operator/=(size_t divisor) { if (divisor == 0) { throw std::invalid_argument("Point::operator/=(): divide by zero error!"); } for (auto &coord : this->_point) { coord /= divisor; } return *this; } std::ostream &operator<<(std::ostream &os, const util::Point &obj) { os << "<"; for (size_t i = 0; i < obj._point.size(); i++) { if (i > 0) { os << ", "; } os << obj._point[i]; } os << ">"; return os; } std::pair<bool, double> converged(const vector<Point> &centroids, const vector<Point> &old_centroids, double threshold) { // Check if the most movement for a given centroid is less than threshold auto delta_dists = vector<double>{}; std::transform(centroids.begin(), centroids.end(), old_centroids.begin(), std::back_inserter(delta_dists), [](const auto &point1, const auto &point2) { return point1.dist(point2); }); auto max_change = *std::max_element(delta_dists.begin(), delta_dists.end()); return {max_change <= threshold, max_change}; } vector<range_t> partition(size_t size, int num_threads) { auto ranges = vector<range_t>{}; auto step_size = size / num_threads; int get_extra = size % num_threads; auto start = 0; auto end = step_size; for (int i = 0; i < num_threads; i++) { // Some threads are assigned additional work beyond minimum if (i < get_extra) { end++; } else if (i == num_threads - 1) { end = size; } ranges.push_back(range_t{start, end}); // Take a "step" forward start = end; end = start + step_size; } return ranges; } void DataSet::nearest_centroids(const vector<Point> &centroids, vector<label_t> &labels, range_t range) const { // No synchronization necessary, disjoint read-only intervals of centroids for (size_t i = range.first; i < range.second; i++) { // Calculate distance from current point to each centroid auto dists = vector<double>{}; std::transform( centroids.begin(), centroids.end(), std::back_inserter(dists), [this, i](const auto &centroid) { return _points[i].dist(centroid); }); // Store index of closest centroid labels[i] = std::distance(dists.begin(), std::min_element(dists.begin(), dists.end())); } } void DataSet::sum_labeled_centroids(vector<Point> &centroids, const vector<label_t> &labels, vector<size_t> &counts, range_t range, SyncType type) const { if (type == SyncType::FINE) { // Increment local variables first, then bulk update shared state size_t k = centroids.size(); auto local_centroids = vector<Point>{k, Point{num_features()}}; auto local_counts = vector<size_t>(k); for (size_t i = range.first; i < range.second; i++) { auto label = labels[i]; local_centroids[label] += this->_points[i]; local_counts[label]++; } for (size_t i = 0; i < k; i++) { this->lock(); if (counts[i] == 0) { centroids[i] = local_centroids[i]; } else { centroids[i] += local_centroids[i]; } counts[i] += local_counts[i]; this->unlock(); } } else { // Add each point to corresponding centroid for (size_t i = range.first; i < range.second; i++) { auto label = labels[i]; this->lock(); if (counts[label] == 0) { centroids[label] = this->_points[i]; } else { centroids[label] += this->_points[i]; } counts[label]++; this->unlock(); } } } void DataSet::normalize_centroids(vector<Point> &centroids, vector<label_t> &counts, range_t k_range) const { // Divide by number of points and handle case where no points are assigned for (size_t i = k_range.first; i < k_range.second; i++) { if (counts[i] > 0) { centroids[i] /= counts[i]; } else { // Assign a random point to this centroid auto index = std::rand() % this->_points.size(); centroids[i] = this->_points[index]; } // Always reset count counts[i] = 0; } } void DataSet::lock() const { if (_type == locks::LockType::MUTEX) { _mutex.lock(); } else if (_type == locks::LockType::SPIN) { _spinlock.lock(); } else { return; } } void DataSet::unlock() const { if (_type == locks::LockType::MUTEX) { _mutex.unlock(); } else if (_type == locks::LockType::SPIN) { _spinlock.unlock(); } else { return; } } vector<double> DataSet::make_raw() const { auto raw_output = vector<double>{}; for (const auto &point : _points) { raw_output.insert(raw_output.end(), point._point.begin(), point._point.end()); } return raw_output; } std::shared_ptr<const DataSet> DataSet::make_dataset(const std::string &filename, locks::LockType lockType) { auto file = std::ifstream{filename}; auto line = std::string{}; auto points = vector<Point>{}; size_t num_dims = 0; // Get number of points std::getline(file, line); int num_points = std::stoi(line); points.reserve(num_points); if (num_points < 1) { throw std::invalid_argument("File must have at least one point!"); } // Read each line in as a n-dim point for (int i = 0; i < num_points; i++) { std::getline(file, line); auto stream = std::stringstream{line}; auto point = vector<double>{}; // Discard point index (line number) int index; stream >> index; double coord; while (stream >> coord) { point.push_back(coord); } if (num_dims == 0) { num_dims = point.size(); } else if (point.size() != num_dims) { throw std::invalid_argument( "Points must all have the same number of dimensions!"); } points.push_back(Point{point}); } return std::make_shared<const DataSet>(points, lockType); } } /* namespace util */
28.5
79
0.589474
aeonstasis
77df632bbbfa0e752892dc546e7ab3f57d91f611
5,026
cpp
C++
examples/cpp/train_relation_extraction/train_relation_extraction_example.cpp
maxmert/nlp-mitie
ec3153ef2fe7a80e7cf3d80d14b388b8cd679343
[ "Unlicense" ]
2,695
2015-01-01T21:13:47.000Z
2022-03-31T04:45:32.000Z
examples/cpp/train_relation_extraction/train_relation_extraction_example.cpp
maxmert/nlp-mitie
ec3153ef2fe7a80e7cf3d80d14b388b8cd679343
[ "Unlicense" ]
208
2015-01-23T19:29:07.000Z
2022-02-08T02:55:17.000Z
examples/cpp/train_relation_extraction/train_relation_extraction_example.cpp
maxmert/nlp-mitie
ec3153ef2fe7a80e7cf3d80d14b388b8cd679343
[ "Unlicense" ]
567
2015-01-06T19:22:19.000Z
2022-03-21T17:01:04.000Z
/* This example shows how to use the MITIE C++ API to train a binary_relation_detector. */ #include <mitie/binary_relation_detector_trainer.h> #include <iostream> using namespace dlib; using namespace std; using namespace mitie; // ---------------------------------------------------------------------------------------- int main(int argc, char** argv) { if (argc != 2) { cout << "You must give the path to the MITIE English ner_model.dat file." << endl; cout << "So run this program with a command like: " << endl; cout << "./train_relation_extraction_example ../../../MITIE-models/english/ner_model.dat" << endl; return 1; } // The training process for a binary relation detector requires a MITIE NER object as // input. So we load the saved NER model first. named_entity_extractor ner; string classname; deserialize(argv[1]) >> classname >> ner; // This object is responsible for doing the training work. The first argument to the // constructor is a string that is used to identify the relation detector. So you // should put some informative string here. In this case, we use the name of one of // the freebase relations. That is, the "person born-in location" relation. binary_relation_detector_trainer trainer("people.person.place_of_birth", ner); // When you train this kind of algorithm, you need to create a set of training // examples. This dataset should include examples of the binary relations you would // like to detect as well as examples of things that are not what you want to detect. // To keep this little tutorial simple, we will use just the sentence "Ben Franklin was born in Boston" // as training data, but note that for real applications you will likely require many // thousands of examples to create a high quality relation detector. // // So here we create a tokenized version of that sentence. std::vector<std::string> sentence; sentence.push_back("Ben"); sentence.push_back("Franklin"); sentence.push_back("was"); sentence.push_back("born"); sentence.push_back("in"); sentence.push_back("Boston"); // Tell the trainer that "Ben Franklin" was born in the location "Boston". trainer.add_positive_binary_relation(sentence, make_pair(0, 2), // person's name, given as a half open range. make_pair(5, 6)); // The location, given as a half open range. // You should also give some negative examples. Here we give a single negative where // we keep the same sentence but flip the named entity arguments. So this is telling // the trainer that it is not true that Boston was born in Ben Franklin. trainer.add_negative_binary_relation(sentence, make_pair(5, 6), make_pair(0, 2)); // Again, note that you need much more training data than this to make high quality // relation detectors. We use just this small amount here to keep the example program // simple. // This call runs the actual trainer based on all the training data. It might take a // while to run so be patient. binary_relation_detector brd = trainer.train(); // Once finished, we can save the relation detector to disk like so. This will allow you // to use a function call like mitie_load_binary_relation_detector("rel_classifier.svm") // to read the detector later on. serialize("rel_classifier.svm") << "mitie::binary_relation_detector" << brd; // Now let's test it out a little bit. // Was Ben Franklin born in Boson? If the score is > 0 then the // binary_relation_detector is predicting that he was. In this case, the number is // positive so the detector made the right decision. cout << "detection score: " << brd(extract_binary_relation(sentence, make_pair(0,2), make_pair(5,6), ner.get_total_word_feature_extractor())) << endl; // Now let's try a different sentence sentence.clear(); sentence.push_back("Jimmy"); sentence.push_back("Smith"); sentence.push_back(","); sentence.push_back("a"); sentence.push_back("guy"); sentence.push_back("raised"); sentence.push_back("in"); sentence.push_back("France"); // Was Jimmy Smith born in France? Again, the detector correctly gives a number > 0. cout << "detection score: " << brd(extract_binary_relation(sentence, make_pair(0,2), make_pair(7,8), ner.get_total_word_feature_extractor())) << endl; // Now let's ask if France was born in Jimmy Smith. This should be false and happily // the detector also correctly predicts a number < 0. cout << "detection score: " << brd(extract_binary_relation(sentence, make_pair(7,8), make_pair(0,2), ner.get_total_word_feature_extractor())) << endl; } // ----------------------------------------------------------------------------------------
46.110092
154
0.653999
maxmert
77e16feec06706c51b625123d38efe49715bdf6c
11,574
cpp
C++
src/Character.cpp
dinodeck/dinodeck
091f0e31ba9e921eab7fa6dd219f5c40ea3ed78c
[ "MIT" ]
110
2016-06-23T23:07:23.000Z
2022-03-25T03:18:16.000Z
src/Character.cpp
dinodeck/dinodeck
091f0e31ba9e921eab7fa6dd219f5c40ea3ed78c
[ "MIT" ]
9
2016-06-24T13:20:01.000Z
2020-05-05T18:43:46.000Z
src/Character.cpp
dinodeck/dinodeck
091f0e31ba9e921eab7fa6dd219f5c40ea3ed78c
[ "MIT" ]
23
2016-04-26T23:37:13.000Z
2021-09-27T07:10:08.000Z
#include "Character.h" #include <assert.h> #include "DDLog.h" #include "Game.h" #include "GraphicsPipeline.h" #include "LuaState.h" #include "reflect/Reflect.h" #include "Renderer.h" #ifdef ANDROID #include <FTGL/ftgles.h> #include "FTGL/../FTGlyph/FTTextureGlyphImpl.h" #else #include <FTGL/ftgl.h> #include "FTGL/../FTGlyph/FTTextureGlyphImpl.h" #include "FTGL/../FTFont/FTTextureFontImpl.h" #include "FTGL/../FTGlyphContainer.h" #include "FTGL/../FTCharmap.h" #include "FTGL/../FTVector.h" #endif // Move mFont->Render code to character. Reflect Character::Meta("Character", Character::Bind); Character::Character() : mX(0), mY(0), mGlyph('\0') { } Character::~Character() { } static int lua_Character_Create(lua_State* state) { // If there's inheritance I think this may causes problems if(lua_isuserdata(state, 1) && luaL_checkudata (state, 1, "Character")) { Character* character = (Character*)lua_touserdata(state, 1); Character* pi = new (lua_newuserdata(state, sizeof(Character))) Character(); if(character == NULL) { return luaL_argerror(state, 1, "Expected Character or string"); } pi->SetGlyph(character->GetGlyph()); } else { const char* str = lua_tostring(state, 1); if(NULL == str) { return luaL_argerror(state, 1, "string"); } Character* pi = new (lua_newuserdata(state, sizeof(Character))) Character(); pi->SetGlyph(str[0]); } luaL_getmetatable(state, "Character"); lua_setmetatable(state, -2); return 1; } static int lua_Character_FaceMaxHeight(lua_State* state) { Renderer* renderer = (Renderer*)lua_touserdata(state, 1); if (renderer == NULL) { return luaL_typerror(state, 1, "Renderer"); } GraphicsPipeline* gp = renderer->Graphics(); lua_pushnumber(state, Character::GetMaxHeight(gp)); return 1; } float Character::GetKern(GraphicsPipeline* gp, unsigned int current, unsigned int next) { FTTextureFont* font = gp->GetFont(); FTTextureFontImpl* impl = (FTTextureFontImpl*) font->GetImpl(); FTGlyphContainer* glyphList = impl->GetGlyphList(); // Not sure if necessary. if(!impl->CheckGlyph(current) || !impl->CheckGlyph(next)) { return 0; } return glyphList->Advance(current, next); } static int lua_Character_GetKern(lua_State* state) { Renderer* renderer = (Renderer*)lua_touserdata(state, 1); if (renderer == NULL) { return luaL_typerror(state, 1, "Renderer"); } const char* firstStr = lua_tostring(state, 2); const char* secondStr = lua_tostring(state, 3); unsigned int first = 0; unsigned int second = 0; if(firstStr) { first = firstStr[0]; } if(secondStr) { second = secondStr[0]; } GraphicsPipeline* gp = renderer->Graphics(); lua_pushnumber(state, Character::GetKern(gp, first, second)); return 1; } static int lua_Character_PixelWidth(lua_State* state) { Character* character = (Character*)lua_touserdata(state, 1); if(character == NULL) { return luaL_typerror(state, 1, "Character"); } Renderer* renderer = (Renderer*)lua_touserdata(state, 2); if (renderer == NULL) { return luaL_typerror(state, 2, "Renderer"); } GraphicsPipeline* gp = renderer->Graphics(); lua_pushnumber(state, character->GetPixelWidth(gp)); return 1; } static int lua_Character_GetCorner(lua_State* state) { Character* character = (Character*)lua_touserdata(state, 1); if(character == NULL) { return luaL_typerror(state, 1, "Character"); } Renderer* renderer = (Renderer*)lua_touserdata(state, 2); if (renderer == NULL) { return luaL_typerror(state, 2, "Renderer"); } GraphicsPipeline* gp = renderer->Graphics(); FTPoint point = character->GetCorner(gp); lua_pushnumber(state, point.X()); lua_pushnumber(state, point.Y()); lua_pushnumber(state, point.Z()); return 3; } static int lua_Character_PixelHeight(lua_State* state) { Character* character = (Character*)lua_touserdata(state, 1); if(character == NULL) { return luaL_typerror(state, 1, "Character"); } Renderer* renderer = (Renderer*)lua_touserdata(state, 2); if (renderer == NULL) { return luaL_typerror(state, 2, "Renderer"); } GraphicsPipeline* gp = renderer->Graphics(); lua_pushnumber(state, character->GetPixelHeight(gp)); return 1; } int Character::GetPixelWidth(GraphicsPipeline* gp) { FTTextureFont* font = gp->GetFont(); FTTextureFontImpl* impl = (FTTextureFontImpl*) font->GetImpl(); FTGlyphContainer* glyphList = impl->GetGlyphList(); FTCharmap* charMap = glyphList->GetCharmap(); FTVector<FTGlyph*>* glyphVector = glyphList->GetGlyphVector(); unsigned int charCode = (unsigned int) mGlyph; // This isn't just a check! It's lazy loader if(!impl->CheckGlyph(charCode)) { return 0; } unsigned int index = charMap->GlyphListIndex(charCode); FTTextureGlyphImpl* glyph = (FTTextureGlyphImpl*) (*glyphVector)[index]->GetImpl(); return glyph->GetWidth(); } int Character::GetPixelHeight(GraphicsPipeline* gp) { FTTextureFont* font = gp->GetFont(); FTTextureFontImpl* impl = (FTTextureFontImpl*) font->GetImpl(); FTGlyphContainer* glyphList = impl->GetGlyphList(); FTCharmap* charMap = glyphList->GetCharmap(); FTVector<FTGlyph*>* glyphVector = glyphList->GetGlyphVector(); unsigned int charCode = (unsigned int) mGlyph; // This isn't just a check! It's lazy loader if(!impl->CheckGlyph(charCode)) { return 0; } unsigned int index = charMap->GlyphListIndex(charCode); FTTextureGlyphImpl* glyph = (FTTextureGlyphImpl*) (*glyphVector)[index]->GetImpl(); return glyph->GetHeight(); } FTPoint Character::GetCorner(GraphicsPipeline* gp) { FTTextureFont* font = gp->GetFont(); FTTextureFontImpl* impl = (FTTextureFontImpl*) font->GetImpl(); FTGlyphContainer* glyphList = impl->GetGlyphList(); FTCharmap* charMap = glyphList->GetCharmap(); FTVector<FTGlyph*>* glyphVector = glyphList->GetGlyphVector(); unsigned int charCode = (unsigned int) mGlyph; // This isn't just a check! It's lazy loader if(!impl->CheckGlyph(charCode)) { return FTPoint(); } unsigned int index = charMap->GlyphListIndex(charCode); FTTextureGlyphImpl* glyph = (FTTextureGlyphImpl*) (*glyphVector)[index]->GetImpl(); FTPoint point = glyph->GetCorner(); return point; } int Character::GetMaxHeight(GraphicsPipeline* gp) { FTTextureFont* font = gp->GetFont(); FTTextureFontImpl* impl = (FTTextureFontImpl*) font->GetImpl(); return impl->GetMaxHeight(); } void Character::DrawGlyph(GraphicsPipeline* gp) { FTTextureFont* font = gp->GetFont(); // FTTextureFont->Render is a virtual function from FTFont // // virtual FTPoint Render(const char* string, const int len = -1, // FTPoint position = FTPoint(), // FTPoint spacing = FTPoint(), // int renderMode = FTGL::RENDER_ALL); // // This is implemented in FTTextureFontImpl::Render // // FTPoint FTTextureFontImpl::Render(const char * string, const int len, // FTPoint position, FTPoint spacing, // int renderMode) // { // return RenderI(string, len, position, spacing, renderMode); // } // // This is implemented as // template <typename T> // inline FTPoint FTTextureFontImpl::RenderI(const T* string, const int len, // FTPoint position, FTPoint spacing, // int renderMode) // { // // Protect GL_TEXTURE_2D, GL_BLEND and blending functions // glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT); // // glEnable(GL_BLEND); // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // GL_ONE // // glEnable(GL_TEXTURE_2D); // // FTTextureGlyphImpl::ResetActiveTexture(); // // FTPoint tmp = FTFontImpl::Render(string, len, // position, spacing, renderMode); // // glPopAttrib(); // // return tmp; // } // //mFont->Render(text); FTTextureFontImpl* impl = (FTTextureFontImpl*) font->GetImpl(); FTGlyphContainer* glyphList = impl->GetGlyphList(); FTCharmap* charMap = glyphList->GetCharmap(); FTVector<FTGlyph*>* glyphVector = glyphList->GetGlyphVector(); glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT); //FTTextureGlyphImpl::ResetActiveTexture(); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); unsigned int charCode = (unsigned int) mGlyph; // This isn't just a check! It's lazy loader if(!impl->CheckGlyph(charCode)) { return; } unsigned int index = charMap->GlyphListIndex(charCode); (*glyphVector)[index]->Render(FTPoint(mX, mY), FTGL::RENDER_ALL); glPopAttrib(); } static int lua_Character_Render(lua_State* state) { Character* character = (Character*)lua_touserdata(state, 1); if(character == NULL) { return luaL_typerror(state, 1, "Character"); } Renderer* renderer = (Renderer*)lua_touserdata(state, 2); if (renderer == NULL) { return luaL_typerror(state, 2, "Renderer"); } GraphicsPipeline* gp = renderer->Graphics(); character->DrawGlyph(gp); // gp->PushText // ( // character->mX, // character->mY, // std::string(1, character->mGlyph).c_str(), // Vector(1,1,1,1), // 99999 // ); return 0; } static int lua_Character_SetPosition(lua_State* state) { Character* character = (Character*)lua_touserdata(state, 1); if(character == NULL) { return luaL_typerror(state, 1, "Character"); } if(lua_isnumber(state, 2) == false) { return luaL_typerror(state, 2, "number"); } character->mX = lua_tonumber(state, 2); if(lua_isnumber(state, 3) == false) { return 0; } character->mY = lua_tonumber(state, 3); return 0; } static const struct luaL_reg luaBinding [] = { {"Create", lua_Character_Create}, {"FaceMaxHeight", lua_Character_FaceMaxHeight}, {"GetKern", lua_Character_GetKern}, {"PixelWidth", lua_Character_PixelWidth}, {"PixelHeight", lua_Character_PixelHeight}, {"Render", lua_Character_Render}, {"SetPosition", lua_Character_SetPosition}, {"GetCorner", lua_Character_GetCorner}, {NULL, NULL} /* sentinel */ }; void Character::Bind(LuaState* state) { state->Bind ( Character::Meta.Name(), luaBinding ); }
28.437346
91
0.601089
dinodeck
77e4dfad08f0efdffaa89ee51592d1c3d686193c
284
hpp
C++
src/player/humanplayer.hpp
josselinauguste/pongo0
cb5d1ed3fa4e7fbaf1eaf8b39e7a923a5bf44776
[ "Unlicense" ]
null
null
null
src/player/humanplayer.hpp
josselinauguste/pongo0
cb5d1ed3fa4e7fbaf1eaf8b39e7a923a5bf44776
[ "Unlicense" ]
null
null
null
src/player/humanplayer.hpp
josselinauguste/pongo0
cb5d1ed3fa4e7fbaf1eaf8b39e7a923a5bf44776
[ "Unlicense" ]
null
null
null
#ifndef HUMANPLAYERH #define HUMANPLAYERH #include "localplayer.hpp" class Game; class CL_Vector; class HumanPlayer : public LocalPlayer { public: HumanPlayer(SIDE, float, float, float, std::string); ~HumanPlayer(); virtual void updateInfos(unsigned int); private: }; #endif
13.52381
53
0.753521
josselinauguste
77ecc4013888764d65ec5df85e1859471df206e5
11,875
hpp
C++
include/ph_parser/lexer.hpp
phiwen96/ph_parser
c729f960867e0f2a233609cb61910ea692f66cab
[ "Apache-2.0" ]
null
null
null
include/ph_parser/lexer.hpp
phiwen96/ph_parser
c729f960867e0f2a233609cb61910ea692f66cab
[ "Apache-2.0" ]
null
null
null
include/ph_parser/lexer.hpp
phiwen96/ph_parser
c729f960867e0f2a233609cb61910ea692f66cab
[ "Apache-2.0" ]
null
null
null
#pragma once #include "token.hpp" #include "expression.hpp" #include <ph_coroutines/co_promise.hpp> #include <ph_coroutines/i_was_co_awaited_and_now_i_am_suspending.hpp> #include <experimental/coroutine> #include <ph_vari/vari.hpp> #include <ph_type/type.hpp> using namespace std; using namespace experimental; //struct lexer //{ // using value_type = ph::expression_t*; // using initial_suspend_awaitable_type = suspend_never; // using final_suspend_awaitable_type = i_was_co_awaited_and_now_i_am_suspending; // // // // struct promise_type : co_promise <lexer> // { // // operator coroutine_handle <promise_type> () // { // return coroutine_handle <promise_type>::from_promise (*this); // } // // token::type m_looking_for_token; // token m_found_token; // function <bool(int)> m_ok; // promise_type* m_current = this; // promise_type* m_parent {nullptr}; // //// binary_expression* m_value {new binary_expression {binary_expression::number}}; //// expression* m_rhs; // //// auto yield_value (expression* lhs) //// { //// m_lhs = lhs; //// return suspend_never {}; //// } // // auto yield_value (struct value* value) // { // m_value -> m_lhs = value; // return suspend_never {}; // } // auto yield_value (binary_expression::type t) // { // m_value -> m_type = t; // return suspend_never {}; // } //// auto yield_value (struct binary_expression* exp) //// { //// exp -> m_lhs = m_value; //// m_value = exp; //// //// return suspend_never {}; //// } // // auto final_suspend () noexcept // { // // struct i_was_co_awaited // { // auto await_ready () noexcept -> bool // { // return false; // } // // /** // @param my_handle is a handle to this function // // @return a handle to the function that co_awaited us. // */ // // auto await_suspend (coroutine_handle <promise_type> my_handle) noexcept -> coroutine_handle <> // { // if (my_handle.promise().m_this_function_co_awaited_me) // { // my_handle.promise().m_parent -> m_current = &my_handle.promise(); // // } // // auto& parent = my_handle.promise().m_this_function_co_awaited_me; // // return parent ? parent : noop_coroutine (); // } // // auto await_resume () noexcept // { // // } // }; // return i_was_co_awaited {}; // } // // template <int N> // auto await_transform (int const(&a)[N]) // { // m_ok = [a](int i) { // for (auto j : a) // { // if (i == j) // { // return true; // } // } // return false; // }; // // struct awaitable // { // promise_type& m_promise; // // auto await_ready () // { // return false; // } // // auto await_suspend (coroutine_handle <> co_awaited_me) //-> coroutine_handle <promise_type> // { // m_promise.m_this_function_co_awaited_me = co_awaited_me; // return true; // } // // auto await_resume () -> token& // { // return m_promise.m_found_token; // } // }; // return awaitable {*this}; // } // // // auto await_transform (lexer co_awaited) // { // co_awaited.m_promise.m_parent = this; // m_current = &co_awaited.m_promise; // m_value -> m_rhs = co_awaited.m_promise.m_value; // // struct awaitable // { // promise_type& m_promise; // coroutine_handle<promise_type> m_handle = coroutine_handle<promise_type>::from_promise(m_promise); // auto await_ready () // { //// return false; //// return m_handle.done(); // return false; // } // // auto await_suspend (coroutine_handle <> co_awaited_me) //-> coroutine_handle <promise_type> // { // m_promise.m_this_function_co_awaited_me = co_awaited_me; //// return true; //// return m_handle; // return true; // } // // auto await_resume () //-> token& // { //// return m_promise.m_found_token; // return m_handle.resume(); // cout << "tjo" << endl; //// return coroutine_handle<promise_type>::from_promise(m_promise); //// return m_handle; // } // }; // return awaitable {co_awaited.m_promise}; // } // // void lex (token const& t) // { // if (m_current == this) // { // if (m_ok (t.m_type)) // { // // cout << "OK" << endl; // m_found_token = t; // coroutine_handle <promise_type>::from_promise (*m_current).resume (); // } else // { // // cout << "NOT OK" << endl; // } // // } else // { // m_current->lex (t); // } // // // } // }; // // // void lex (token const& t) // { // m_promise.lex (t); //// if (m_promise.m_ok (t.m_type)) //// { ////// cout << "OK" << endl; //// m_promise.m_found_token = t; //// static_cast <coroutine_handle<promise_type>>(m_promise).resume (); //// } else //// { ////// cout << "NOT OK" << endl; //// } // } // // // auto get_value () -> ph::expression_t* // { // return m_promise.m_value; // } // auto resume () // { // return coroutine_handle <promise_type>::from_promise (m_promise).resume (); // } // lexer (promise_type& p) : m_promise {p} // { // // } // lexer (lexer&& other) : m_promise {other.m_promise} // { // // } // lexer (lexer const&) = delete; // lexer& operator=(lexer const&) = delete; // lexer& operator=(lexer&&) = delete; //// coroutine_handle <promise_type> m_coro; // promise_type& m_promise; // //}; template <typename T> auto lex (string const& input) -> vector <T>; //#ifdef EAD template <> auto lex (string const& input) -> vector <var <TOKENS>> { vector <var <TOKENS>> result; struct Num { int m_power {0}; string m_number; } num; for (auto c : input) { if (isdigit (c)) { num.m_number += c; ++num.m_power; } else { if (num.m_power > 0) { if (c == '.') { num.m_number += c; continue; } else { result.emplace_back (ph::number_t {stod (num.m_number)}); // cout << "mf" << endl; num.m_power = 0; num.m_number.clear (); } } if (c == '+') { result.emplace_back (ph::plus_t{}); } else if (c == '-') { result.emplace_back (ph::minus_t{}); } else if (c == '*') { result.emplace_back (ph::multi_t{}); } else if (c == '/') { result.emplace_back (ph::divi_t{}); } else if (c == '(') { result.emplace_back (ph::lparen_t{}); } else if (c == ')') { result.emplace_back (ph::rparen_t{}); } } } if (num.m_power > 0) { result.emplace_back (ph::number_t {stod (num.m_number)}); } // for (auto& i : result) // cout << i << endl; return result; } //#endif template <> auto lex (string const& input) -> vector <any> { vector <any> result; struct Num { int m_power {0}; string m_number; } num; for (auto c : input) { if (isdigit (c)) { num.m_number += c; ++num.m_power; } else { if (num.m_power > 0) { if (c == '.') { num.m_number += c; continue; } else { result.push_back (ph::number_t {stod (num.m_number)}); num.m_power = 0; num.m_number.clear (); } } if (c == '+') { result.push_back (ph::plus_t{}); } else if (c == '-') { result.emplace_back (ph::minus_t{}); } else if (c == '*') { result.emplace_back (ph::multi_t{}); } else if (c == '/') { result.emplace_back (ph::divi_t{}); } else if (c == '(') { result.emplace_back (ph::lparen_t{}); } else if (c == ')') { result.emplace_back (ph::rparen_t{}); } } } if (num.m_power > 0) { result.emplace_back (ph::number_t {stod (num.m_number)}); } return result; } auto lex_oldie (string const& input) -> vector <ph::Token> { vector <ph::Token> result; struct Num { int m_power {0}; string m_number; } num; for (auto c : input) { if (isdigit (c)) { num.m_number += c; ++num.m_power; } else { if (num.m_power > 0) { if (c == '.') { num.m_number += c; continue; } else { result.push_back (ph::number_t {stod (num.m_number)}); num.m_power = 0; num.m_number.clear (); } } if (c == '+') { result.push_back (ph::plus_t{}); } else if (c == '-') { result.emplace_back (ph::minus_t{}); } else if (c == '*') { result.emplace_back (ph::multi_t{}); } else if (c == '/') { result.emplace_back (ph::divi_t{}); } else if (c == '(') { result.emplace_back (ph::lparen_t{}); } else if (c == ')') { result.emplace_back (ph::rparen_t{}); } } } if (num.m_power > 0) { result.emplace_back (ph::number_t {stod (num.m_number)}); } return result; }
25.815217
116
0.401347
phiwen96
77f372ac14b1d224a343af75041505efcc94cd94
3,218
hpp
C++
modules/core/sdk/include/nt2/core/container/view/adapted/view_type.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/core/sdk/include/nt2/core/container/view/adapted/view_type.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/core/sdk/include/nt2/core/container/view/adapted/view_type.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
//============================================================================== // Copyright 2009 - 2014 LRI UMR 8623 CNRS/Univ Paris Sud XI // Copyright 2012 - 2014 NumScale SAS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_CORE_CONTAINER_VIEW_ADAPTED_VIEW_TYPE_HPP_INCLUDED #define NT2_CORE_CONTAINER_VIEW_ADAPTED_VIEW_TYPE_HPP_INCLUDED #include <nt2/sdk/memory/container_ref.hpp> #include <nt2/sdk/meta/container_traits.hpp> #include <boost/config.hpp> namespace nt2 { namespace container { template<class Expression, class ResultType> struct expression; } } namespace nt2 { namespace details { template<typename Container> struct view_type { // Base container type typedef typename meta::kind_<Container>::type kind_type; typedef typename meta::value_type_<Container>::type value_type; typedef typename Container::settings_type settings_type; typedef memory::container_ref < kind_type , value_type , settings_type > container_ref; typedef memory::container < kind_type , value_type , settings_type >& container_type; typedef boost::proto::basic_expr< nt2::tag::terminal_ , boost::proto::term<container_ref> , 0l > basic_expr; typedef nt2::container::expression< basic_expr , container_type > nt2_expression; }; template<typename Container> struct view_type<Container const> { // Base container type typedef typename meta::kind_<Container>::type kind_type; typedef typename meta::value_type_<Container>::type value_type; typedef typename Container::settings_type settings_type; typedef memory::container_ref < kind_type , value_type const , settings_type > container_ref; typedef memory::container < kind_type , value_type , settings_type > const& container_type; typedef boost::proto::basic_expr< nt2::tag::terminal_ , boost::proto::term<container_ref> , 0l > basic_expr; typedef nt2::container::expression< basic_expr , container_type > nt2_expression; }; } } #endif
39.728395
80
0.474208
psiha
af80aab144d6ba161863e0dbc8e057ea6490d296
15,181
cpp
C++
NoiseStudioLib/NoiseStudioLib/graph.cpp
SneakyMax/NoiseStudio
b0c3c72e787d61b798acbcd2147f36e1e78f5bad
[ "Unlicense" ]
null
null
null
NoiseStudioLib/NoiseStudioLib/graph.cpp
SneakyMax/NoiseStudio
b0c3c72e787d61b798acbcd2147f36e1e78f5bad
[ "Unlicense" ]
null
null
null
NoiseStudioLib/NoiseStudioLib/graph.cpp
SneakyMax/NoiseStudio
b0c3c72e787d61b798acbcd2147f36e1e78f5bad
[ "Unlicense" ]
null
null
null
#include "graph.h" #include "utils.h" #include "nodes/uniform_buffer.h" #include "nodes/attribute_buffer.h" #include "graph_executor.h" namespace noises { Graph::Graph() : id_counter_(0), in_refresh_after_(false) { } int Graph::add_node(std::unique_ptr<GraphNode> node) { node->set_id(id_counter_); node->set_parent(*this); id_counter_++; GraphNode& node_ref = *node; nodes_.push_back(std::move(node)); node_ref.request_recalculate_sockets(); node_ref.outputs().listen_socket_changed([this, &node_ref](const OutputSocket&) { this->refresh_after(node_ref); }); return id_counter_ - 1; } void Graph::remove_node(GraphNode* node) { // Disconnect all connections to this node for(auto& socket : node->inputs().all_sockets()) disconnect(socket); for(auto& socket : node->outputs().all_sockets()) disconnect_all(socket); utils::remove_by_pointer(nodes_, node); } std::vector<GraphNode*> Graph::get_nodes_by_node_name(const std::string &name) const { std::vector<GraphNode*> return_list; for(auto& node : nodes_) { if(node->node_name() == name) return_list.push_back(node.get()); } return return_list; } boost::optional<std::reference_wrapper<GraphNode>> Graph::get_node_by_name(const std::string &name) const { for(auto& node : nodes_) { if(node->name() == name) return std::ref(*node); } return boost::none; } boost::optional<std::reference_wrapper<GraphNode>> Graph::get_node_by_id(int id) const { for(auto& node : nodes_) { if(node->id() == id) return std::ref(*node); } for(auto& node : input_nodes_) { if(node->id() == id) return std::ref(*node); } for(auto& node : output_nodes_) { if(node->id() == id) return std::ref(*node); } return boost::none; } void Graph::connect(OutputSocket& output, InputSocket& input) { if(input.connection() != nullptr) disconnect(input); std::unique_ptr<Connection> connection(new Connection(input, output, *this)); output.add_connection(*connection); input.set_connection(*connection); connection->set_id(id_counter_); id_counter_++; connections_.push_back(std::move(connection)); } void Graph::connect(GraphNode &output, std::string output_name, GraphNode &input, std::string input_name) { connect(output.output(output_name), input.input(input_name)); } void Graph::connect(GraphNode& output, GraphNode& input) { auto outputs = output.outputs().all_sockets(); auto inputs = input.inputs().all_sockets(); if(outputs.size() != 1) throw std::logic_error("Cannot use this overload of Graph::Connect because the output node does not have exactly one output socket."); if(inputs.size() != 1) throw std::logic_error("Cannot use this overload of Graph::Connect because the input node does not have exactly one input socket."); connect(outputs.front(), inputs.front()); } void Graph::connect(GraphNode &output, std::string output_name, GraphNode &input) { auto inputs = input.inputs().all_sockets(); if(inputs.size() != 1) throw std::logic_error("Cannot use this overload of Graph::Connect because the input node does not have exactly one input socket."); connect(output.output(output_name), inputs.front()); } void Graph::connect(GraphNode &output, GraphNode &input, std::string input_name) { auto outputs = output.outputs().all_sockets(); if(outputs.size() != 1) throw std::logic_error("Cannot use this overload of Graph::Connect because the output node does not have exactly one output socket."); connect(outputs.front(), input.input(input_name)); } void Graph::disconnect(InputSocket& input) { auto possible_connection = input.connection(); if(!possible_connection) return; //Could iterate connection_ to find same non-const object but a const cast is simpler Connection& connection = const_cast<Connection&>(possible_connection->get()); connection.disconnect(); remove_connection(connection); } void Graph::disconnect_all(OutputSocket& output) { for(auto& connection_wrapper : output.connections()) { //Could iterate connection_ to find same non-const object but a const cast is simpler Connection& connection = const_cast<Connection&>(connection_wrapper.get()); connection.disconnect(); remove_connection(connection); } } void Graph::remove_connection(const Connection& connection) { utils::remove_by_pointer(connections_, &connection); } void Graph::remove_property(const std::string &name) { properties_.remove(name); } boost::optional<std::reference_wrapper<Property>> Graph::get_property_by_name(const std::string &name) { return properties_.get_property_by_name(name); } // Icky repetitive GraphNode& Graph::add_attribute_output(const std::string &name) { if(get_attribute_output(name) || get_uniform_output(name)) throw std::invalid_argument(name + " is already taken as an output."); std::unique_ptr<GraphNode> buffer_node(new nodes::AttributeBuffer); buffer_node->set_name(name); buffer_node->set_id(id_counter_); buffer_node->set_is_graph_internal_node(true); buffer_node->input("Input").set_accepts(ConnectionDataType::any()); id_counter_++; GraphNode& buffer_node_ref = *buffer_node; output_nodes_.push_back(std::move(buffer_node)); return buffer_node_ref; } GraphNode& Graph::add_uniform_output(const std::string &name) { if(get_uniform_output(name) || get_attribute_output(name)) throw std::invalid_argument(name + " is already taken as an output."); std::unique_ptr<GraphNode> buffer_node(new nodes::UniformBuffer); buffer_node->set_name(name); buffer_node->set_id(id_counter_); buffer_node->set_is_graph_internal_node(true); buffer_node->input("Input").set_accepts(ConnectionDataType::any()); id_counter_++; GraphNode& buffer_node_ref = *buffer_node; output_nodes_.push_back(std::move(buffer_node)); return buffer_node_ref; } GraphNode& Graph::add_uniform_input(const std::string &name) { if(get_uniform_input(name) || get_attribute_input(name)) throw std::invalid_argument(name + " is already taken as an input."); std::unique_ptr<GraphNode> buffer_node(new nodes::UniformBuffer); buffer_node->set_name(name); buffer_node->set_id(id_counter_); buffer_node->set_is_graph_internal_node(true); buffer_node->input("Input").set_optional(true); id_counter_++; GraphNode& buffer_node_ref = *buffer_node; input_nodes_.push_back(std::move(buffer_node)); return buffer_node_ref; } GraphNode& Graph::add_attribute_input(const std::string &name) { if(get_uniform_input(name) || get_attribute_input(name)) throw std::invalid_argument(name + " is already taken as an input."); std::unique_ptr<GraphNode> buffer_node(new nodes::AttributeBuffer); buffer_node->set_name(name); buffer_node->set_id(id_counter_); buffer_node->set_is_graph_internal_node(true); buffer_node->input("Input").set_optional(true); id_counter_++; GraphNode& buffer_node_ref = *buffer_node; input_nodes_.push_back(std::move(buffer_node)); return buffer_node_ref; } boost::optional<std::reference_wrapper<nodes::AttributeBuffer>> Graph::get_attribute_input(const std::string &name) { return get_buffer<nodes::AttributeBuffer>(name, input_nodes_); } boost::optional<std::reference_wrapper<nodes::AttributeBuffer>> Graph::get_attribute_output(const std::string &name) { return get_buffer<nodes::AttributeBuffer>(name, output_nodes_); } boost::optional<std::reference_wrapper<nodes::UniformBuffer>> Graph::get_uniform_input(const std::string &name) { return get_buffer<nodes::UniformBuffer>(name, input_nodes_); } boost::optional<std::reference_wrapper<nodes::UniformBuffer>> Graph::get_uniform_output(const std::string &name) { return get_buffer<nodes::UniformBuffer>(name, output_nodes_); } //Below be boring getters std::vector<std::reference_wrapper<Connection>> Graph::connections() { return utils::to_reference_array(connections_); } const std::vector<std::reference_wrapper<const Connection>> Graph::connections() const { return utils::to_reference_array_const(connections_); } std::vector<std::reference_wrapper<GraphNode>> Graph::nodes() { return utils::to_reference_array(nodes_); } const std::vector<std::reference_wrapper<const GraphNode>> Graph::nodes() const { return utils::to_reference_array_const(nodes_); } std::vector<std::reference_wrapper<GraphNode>> Graph::output_nodes() { return utils::to_reference_array(output_nodes_); } const std::vector<std::reference_wrapper<const GraphNode>> Graph::output_nodes() const { return utils::to_reference_array_const(output_nodes_); } std::vector<std::reference_wrapper<GraphNode>> Graph::input_nodes() { return utils::to_reference_array(input_nodes_); } const std::vector<std::reference_wrapper<const GraphNode>> Graph::input_nodes() const { return utils::to_reference_array_const(input_nodes_); } void Graph::set_input_uniform_raw(const std::string &input_name, const ConnectionDataType &data_type, const unsigned char *data_ptr) { // Make sure there's an input node with [input_name] and it's a uniform type. auto node_it = std::find_if(input_nodes_.begin(), input_nodes_.end(), [input_name](std::unique_ptr<GraphNode>& node) { return node->name() == input_name; }); if(node_it == input_nodes_.end()) throw std::invalid_argument(input_name + " is not a valid input."); if((**node_it).output("Output").type() != SocketType::uniform) throw std::invalid_argument(input_name + " is not a uniform argument."); auto existing_it = manual_input_buffers_.find(input_name); if(existing_it != manual_input_buffers_.end()) manual_input_buffers_.erase(existing_it); AttributeInfo attr_info(0, ""); std::unique_ptr<DataBuffer> new_buffer(new DataBuffer(attr_info)); new_buffer->add_uniform(data_type); new_buffer->set_uniform_raw(0, data_type.size_full(), data_ptr); manual_input_buffers_.insert(std::pair<std::string, std::unique_ptr<DataBuffer>>(input_name, std::move(new_buffer))); nodes::UniformBuffer& input_node = *this->get_uniform_input(input_name); input_node.set_output_type(data_type); input_node.input().set_accepts(data_type); refresh_all_sockets(); } void Graph::set_input_attribute_raw(const std::string &input_name, const ConnectionDataType &data_type, const unsigned char *data_ptr, DataBuffer::size_type attribute_length) { auto node_it = std::find_if(input_nodes_.begin(), input_nodes_.end(), [input_name](std::unique_ptr<GraphNode>& node) { return node->name() == input_name; }); if(node_it == input_nodes_.end()) throw std::invalid_argument(input_name + " is not a valid input."); if((**node_it).output("Output").type() != SocketType::attribute) throw std::invalid_argument(input_name + " is not an attribute type."); auto existing_it = manual_input_buffers_.find(input_name); if(existing_it != manual_input_buffers_.end()) manual_input_buffers_.erase(existing_it); AttributeInfo attr_info(attribute_length, ""); std::unique_ptr<DataBuffer> new_buffer(new DataBuffer(attr_info)); new_buffer->add_attribute(data_type); new_buffer->set_attribute_all_raw(0, data_ptr, attribute_length * data_type.size_full()); manual_input_buffers_.insert(std::pair<std::string, std::unique_ptr<DataBuffer>>(input_name, std::move(new_buffer))); nodes::AttributeBuffer& input_node = *this->get_attribute_input(input_name); input_node.set_output_type(data_type); input_node.input().set_accepts(data_type); refresh_all_sockets(); } boost::optional<std::reference_wrapper<const DataBuffer>> Graph::get_input_buffer(const std::string &input_name) const { auto it = manual_input_buffers_.find(input_name); if(it == manual_input_buffers_.end()) return boost::none; return std::ref(static_cast<const DataBuffer&>(*std::get<1>(*it))); } GraphOutputs Graph::execute() const { GraphExecutor executor(*this); return executor.execute(); } void Graph::refresh_after(GraphNode& node) { if(in_refresh_after_) return; in_refresh_after_ = true; refresh_after_inner(node, 0); in_refresh_after_ = false; } void Graph::refresh_after_inner(GraphNode& node, std::size_t recursion_depth) { if(recursion_depth > 1000) // In case of node loops this would stack overflow return; for(const OutputSocket& socket : node.outputs().all_sockets()) { for(const Connection& connection : socket.connections()) { const GraphNode* next_const = connection.input().parent(); GraphNode& next = *get_node_by_id(next_const->id()); next.request_recalculate_sockets(); refresh_after_inner(next, recursion_depth + 1); } } } void Graph::refresh_all_sockets() { for(GraphNode& node : nodes()) { node.request_recalculate_sockets(); } for(GraphNode& node : input_nodes()) { node.request_recalculate_sockets(); } for(GraphNode& node : output_nodes()) { node.request_recalculate_sockets(); } } }
35.804245
179
0.629076
SneakyMax
af86ca4059d46eabc3c409f79b3b7e1703633161
1,498
hpp
C++
libs/python/include/python/service/py_feed_subscription_manager.hpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
3
2019-07-11T08:49:27.000Z
2021-09-07T16:49:15.000Z
libs/python/include/python/service/py_feed_subscription_manager.hpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
null
null
null
libs/python/include/python/service/py_feed_subscription_manager.hpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
2
2019-07-13T12:45:22.000Z
2021-03-12T08:48:57.000Z
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI 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 // // 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 "service/feed_subscription_manager.hpp" #include "fetch_pybind.hpp" namespace fetch { namespace service { void BuildFeedSubscriptionManager(pybind11::module &module) { namespace py = pybind11; py::class_<FeedSubscriptionManager>(module, "FeedSubscriptionManager") .def(py::init<const fetch::service::feed_handler_type &, fetch::service::AbstractPublicationFeed *>()) .def("feed", &FeedSubscriptionManager::feed) .def("Subscribe", &FeedSubscriptionManager::Subscribe) .def("Unsubscribe", &FeedSubscriptionManager::Unsubscribe) .def("publisher", &FeedSubscriptionManager::publisher); } }; // namespace service }; // namespace fetch
37.45
80
0.640854
devjsc
af8a02303398d3927b135864e03492be0f564544
503
cpp
C++
game/src/component/player_paddle.cpp
IsmailSamir/BreakOut-Game
b2ddc413a39cfd677d585f2d9968262a53b2165d
[ "BSD-3-Clause" ]
null
null
null
game/src/component/player_paddle.cpp
IsmailSamir/BreakOut-Game
b2ddc413a39cfd677d585f2d9968262a53b2165d
[ "BSD-3-Clause" ]
null
null
null
game/src/component/player_paddle.cpp
IsmailSamir/BreakOut-Game
b2ddc413a39cfd677d585f2d9968262a53b2165d
[ "BSD-3-Clause" ]
null
null
null
#include "component/player_paddle.h" using namespace glm; namespace bko { Player_Paddle player_paddle_new(const Texture& texture, const vec2& position, const vec2& size, const vec2& velocity) { Player_Paddle self{}; self.sprite.texture = texture; self.sprite.color = vec3{ 1.0f, 1.0f , 1.0f }; self.sprite.position = position; self.sprite.size = size; self.velocity = velocity; return self; } void player_paddle_free(Player_Paddle& self) { destruct(self.sprite.texture); } }
19.346154
104
0.719682
IsmailSamir
af8c5b76acd26c8cd35d5aba0cacac3e19013dcc
776
cpp
C++
PressureEngineCore/Src/Graphics/PostProcessing/Contrast/ContrastShader.cpp
Playturbo/PressureEngine
6b023165fcaecb267e13cf5532ea26a8da3f1450
[ "MIT" ]
1
2017-09-13T13:29:27.000Z
2017-09-13T13:29:27.000Z
PressureEngineCore/Src/Graphics/PostProcessing/Contrast/ContrastShader.cpp
Playturbo/PressureEngine
6b023165fcaecb267e13cf5532ea26a8da3f1450
[ "MIT" ]
null
null
null
PressureEngineCore/Src/Graphics/PostProcessing/Contrast/ContrastShader.cpp
Playturbo/PressureEngine
6b023165fcaecb267e13cf5532ea26a8da3f1450
[ "MIT" ]
1
2019-01-18T07:16:59.000Z
2019-01-18T07:16:59.000Z
#include "ContrastShader.h" namespace Pressure { const std::string ContrastShader::s_VertexShader = R"(#version 140 in vec2 position; out vec2 textureCoords; void main(void) { gl_Position = vec4(position, 0.0, 1.0); textureCoords = position * 0.5 + 0.5; })"; const std::string ContrastShader::s_FragmentShader = R"(#version 140 in vec2 textureCoords; out vec4 out_Color; uniform sampler2D colorTexture; const float contrast = 0.15; void main(void) { out_Color = texture(colorTexture, textureCoords); out_Color.rgb = (out_Color.rgb - 0.5) * (1.0 + contrast) + 0.5; })"; ContrastShader::ContrastShader() { Shader::loadShaders(s_VertexShader, s_FragmentShader); } void ContrastShader::bindAttributes() { Shader::bindAttribute(0, "position"); } }
17.244444
64
0.715206
Playturbo
af8ecfffc96391390d14fcced63f2f43fb0677d7
22,128
cpp
C++
csapex_point_cloud/src/visualization/cloud_renderer_adapter.cpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
2
2016-09-02T15:33:22.000Z
2019-05-06T22:09:33.000Z
csapex_point_cloud/src/visualization/cloud_renderer_adapter.cpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
1
2021-02-14T19:53:30.000Z
2021-02-14T19:53:30.000Z
csapex_point_cloud/src/visualization/cloud_renderer_adapter.cpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
6
2016-10-12T00:55:23.000Z
2021-02-10T17:49:25.000Z
/// HEADER #include "cloud_renderer_adapter.h" /// PROJECT #include <csapex/model/node_facade_impl.h> #include <csapex/msg/io.h> #include <csapex/param/set_parameter.h> #include <csapex/view/utility/register_node_adapter.h> #include <csapex_point_cloud/msg/point_cloud_message.h> /// SYSTEM #include <QtOpenGL> #include <csapex/view/utility/QtCvImageConverter.h> #include <pcl/conversions.h> #include <pcl/for_each_type.h> #include <pcl/point_types.h> using namespace csapex; using namespace csapex::connection_types; CSAPEX_REGISTER_LOCAL_NODE_ADAPTER(CloudRendererAdapter, csapex::CloudRenderer) CloudRendererAdapter::CloudRendererAdapter(NodeFacadeImplementationPtr worker, NodeBox* parent, std::weak_ptr<CloudRenderer> node) : QGLWidget(QGLFormat(QGL::SampleBuffers)) , DefaultNodeAdapter(worker, parent) , wrapped_(node) , view_(nullptr) , pixmap_(nullptr) , fbo_(nullptr) , drag_(false) , repaint_(true) , w_view_(10) , h_view_(10) , point_size_(1) , phi_(0) , theta_(M_PI / 2) , r_(-10.0) , axes_(false) , grid_size_(10) , grid_resolution_(1.0) , grid_xy_(true) , grid_yz_(false) , grid_xz_(false) , list_cloud_(0) , list_augmentation_(0) { auto node_ptr = wrapped_.lock(); observe(node_ptr->display_request, this, &CloudRendererAdapter::display); observe(node_ptr->refresh_request, this, &CloudRendererAdapter::refresh); QObject::connect(this, SIGNAL(repaintRequest()), this, SLOT(paintGLImpl()), Qt::QueuedConnection); QObject::connect(this, SIGNAL(resizeRequest()), this, SLOT(resize()), Qt::QueuedConnection); } CloudRendererAdapter::~CloudRendererAdapter() { delete fbo_; } void CloudRendererAdapter::stop() { DefaultNodeAdapter::stop(); disconnect(); } void CloudRendererAdapter::setupUi(QBoxLayout* layout) { view_ = new QGraphicsView; QGraphicsScene* scene = view_->scene(); if (scene == nullptr) { scene = new QGraphicsScene(); // scene->addWidget(this); view_->setScene(scene); } view_->setContextMenuPolicy(Qt::PreventContextMenu); scene->installEventFilter(this); layout->addWidget(view_); QObject::connect(this, SIGNAL(displayRequest()), this, SLOT(displayCloud())); DefaultNodeAdapter::setupUi(layout); } void CloudRendererAdapter::initializeGL() { makeCurrent(); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glShadeModel(GL_SMOOTH); glDisable(GL_LIGHTING); glEnable(GL_MULTISAMPLE); glEnable(GL_LINE_SMOOTH); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); } void CloudRendererAdapter::resizeGL(int width, int height) { makeCurrent(); glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); QMatrix4x4 projection; projection.setToIdentity(); projection.perspective(45.0f, (GLfloat)width / (GLfloat)height, 0.0001f, 300.0f); glLoadMatrixf(projection.data()); glMatrixMode(GL_MODELVIEW); } void CloudRendererAdapter::resize() { if (w_view_ != view_->width() || h_view_ != view_->height()) { view_->setFixedSize(w_view_, h_view_); } resizeGL(w_out_, h_out_); } void CloudRendererAdapter::paintAugmentation() { makeCurrent(); if (list_augmentation_ == 0) { list_augmentation_ = glGenLists(1); } // push settings glPushAttrib(GL_CULL_FACE); glPushAttrib(GL_LINE_SMOOTH); glPushAttrib(GL_BLEND); glNewList(list_augmentation_, GL_COMPILE); // change settings glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glDisable(GL_CULL_FACE); glEnable(GL_LINE_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); // grid qglColor(color_grid_); glLineWidth(1.5f); glBegin(GL_QUADS); double dim = grid_resolution_ * grid_size_ / 2.0; double r = grid_resolution_; if (grid_xy_) { for (double x = -dim; x < dim; x += grid_resolution_) { for (double y = -dim; y < dim; y += grid_resolution_) { glVertex3d(x, y, 0); glVertex3d(x + r, y, 0); glVertex3d(x + r, y + r, 0); glVertex3d(x, y + r, 0); } } } if (grid_yz_) { for (double y = -dim; y < dim; y += grid_resolution_) { for (double z = -dim; z < dim; z += grid_resolution_) { glVertex3d(0, y, z); glVertex3d(0, y + r, z); glVertex3d(0, y + r, z + r); glVertex3d(0, y, z + r); } } } if (grid_xz_) { for (double x = -dim; x < dim; x += grid_resolution_) { for (double z = -dim; z < dim; z += grid_resolution_) { glVertex3d(x, 0, z); glVertex3d(x + r, 0, z); glVertex3d(x + r, 0, z + r); glVertex3d(x, 0, z + r); } } } glEnd(); if (axes_) { // axes double d = 0.5; glLineWidth(20.f); glBegin(GL_LINES); // x glColor3d(1, 0, 0); glVertex3d(0, 0, 0); glVertex3d(d, 0, 0); // y glColor3d(0, 1, 0); glVertex3d(0, 0, 0); glVertex3d(0, d, 0); // z glColor3d(0, 0, 1); glVertex3d(0, 0, 0); glVertex3d(0, 0, d); glEnd(); } glEndList(); // pop settings glPopAttrib(); glPopAttrib(); glPopAttrib(); } void CloudRendererAdapter::paintGLImpl(bool request) { auto n = wrapped_.lock(); if (!n) { return; } // initialization makeCurrent(); initializeGL(); if (fbo_) { delete fbo_; } QGLFramebufferObjectFormat format; format.setAttachment(QGLFramebufferObject::CombinedDepthStencil); format.setMipmap(false); format.setInternalTextureFormat(GL_RGB8); fbo_ = new QGLFramebufferObject(QSize(w_out_, h_out_), format); fbo_->bind(); qglClearColor(color_bg_); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); // model view matrix QMatrix4x4 lookat; lookat.setToIdentity(); QVector3D eye(-r_ * std::sin(theta_) * std::cos(phi_), -r_ * std::sin(theta_) * std::sin(phi_), -r_ * std::cos(theta_)); QVector3D center(0, 0, 0); QVector3D up(0, 0, 1); lookat.lookAt(eye + offset_, center + offset_, up); glLoadMatrixf(lookat.data()); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glCallList(list_cloud_); // grid if (repaint_ || !list_augmentation_) { paintAugmentation(); } glCallList(list_augmentation_); // center point if (drag_) { QVector3D o = center + offset_; glPointSize(point_size_ * 5); glBegin(GL_POINTS); glColor3f(1, 1, 1); glVertex3d(o.x(), o.y(), o.z()); glEnd(); } // extract image QImage img = fbo_->toImage(); fbo_->release(); if (pixmap_ == nullptr) { pixmap_ = view_->scene()->addPixmap(QPixmap::fromImage(img)); } else { pixmap_->setPixmap(QPixmap::fromImage(img)); } view_->blockSignals(true); view_->scene()->setSceneRect(img.rect()); view_->fitInView(view_->scene()->sceneRect(), Qt::KeepAspectRatio); view_->blockSignals(false); // view_->scene()->update(); if (n->isOutputConnected() && request) { cv::Mat mat = QtCvImageConverter::Converter::QImage2Mat(img); n->publishImage(mat); } } bool CloudRendererAdapter::eventFilter(QObject* o, QEvent* e) { auto n = node_.lock(); if (!n) { return false; } if (view_->signalsBlocked()) { return false; } QGraphicsSceneMouseEvent* me = dynamic_cast<QGraphicsSceneMouseEvent*>(e); switch (e->type()) { case QEvent::GraphicsSceneMousePress: mousePressEventImpl(me); return true; case QEvent::GraphicsSceneMouseRelease: mouseReleaseEventImpl(me); return true; case QEvent::GraphicsSceneMouseMove: mouseMoveEventImpl(me); return true; case QEvent::GraphicsSceneWheel: wheelEventImpl(dynamic_cast<QGraphicsSceneWheelEvent*>(e)); return true; default: break; } return false; } void CloudRendererAdapter::mousePressEventImpl(QGraphicsSceneMouseEvent* event) { last_pos_ = event->screenPos(); drag_ = true; event->accept(); } void CloudRendererAdapter::mouseReleaseEventImpl(QGraphicsSceneMouseEvent* event) { auto node = wrapped_.lock(); if (!node) { return; } drag_ = false; node->getParameter("~size/width")->set<int>(w_view_); node->getParameter("~size/height")->set<int>(h_view_); if (size_sync_) { w_out_ = w_view_; h_out_ = h_view_; node->getParameter("~size/out/width")->set<int>(w_out_); node->getParameter("~size/out/height")->set<int>(h_out_); } event->accept(); } void CloudRendererAdapter::mouseMoveEventImpl(QGraphicsSceneMouseEvent* event) { auto node = wrapped_.lock(); if (!node) { return; } if (!drag_) { return; } event->accept(); QPointF pos = event->screenPos(); double dx = pos.x() - last_pos_.x(); double dy = pos.y() - last_pos_.y(); double f = 0.01; if (event->buttons() & Qt::LeftButton) { setTheta(theta_ + f * dy); setPhi(phi_ + f * -dx); } else if (event->buttons() & Qt::MidButton) { w_view_ = std::max(40, std::min(2000, w_view_ + (int)dx)); h_view_ = std::max(40, std::min(2000, h_view_ + (int)dy)); view_->setFixedSize(w_view_, h_view_); if (size_sync_) { w_out_ = w_view_; h_out_ = h_view_; resizeGL(w_out_, h_out_); } } else if (event->buttons() & Qt::RightButton) { QMatrix4x4 rot; rot.setToIdentity(); rot.rotate(phi_ * 180.0 / M_PI, QVector3D(0, 0, 1)); offset_ += rot * QVector3D(f * dy, f * dx, 0); node->getParameter("~view/dx")->set<double>(offset_.x()); node->getParameter("~view/dy")->set<double>(offset_.y()); node->getParameter("~view/dz")->set<double>(offset_.z()); } last_pos_ = pos; Q_EMIT repaintRequest(); } void CloudRendererAdapter::wheelEventImpl(QGraphicsSceneWheelEvent* event) { auto node = wrapped_.lock(); if (!node) { return; } event->accept(); r_ += event->delta() * -0.0025; node->getParameter("~view/r")->set<double>(r_); Q_EMIT repaintRequest(); } void CloudRendererAdapter::display() { Q_EMIT displayRequest(); } void CloudRendererAdapter::refresh() { auto node = wrapped_.lock(); if (!node) { return; } if (!drag_) { { const std::vector<int>& c = node->readParameter<std::vector<int>>("color/background"); color_bg_ = QColor::fromRgb(c[0], c[1], c[2]); } { const std::vector<int>& c = node->readParameter<std::vector<int>>("color/grid"); color_grid_ = QColor::fromRgb(c[0], c[1], c[2]); } { const std::vector<int>& c = node->readParameter<std::vector<int>>("color/gradient/start"); color_grad_start_ = QVector3D(c[0] / 255.0, c[1] / 255.0, c[2] / 255.0); } { const std::vector<int>& c = node->readParameter<std::vector<int>>("color/gradient/end"); color_grad_end_ = QVector3D(c[0] / 255.0, c[1] / 255.0, c[2] / 255.0); } r_ = node->readParameter<double>("~view/r"); theta_ = node->readParameter<double>("~view/theta"); phi_ = node->readParameter<double>("~view/phi"); double dx = node->readParameter<double>("~view/dx"); double dy = node->readParameter<double>("~view/dy"); double dz = node->readParameter<double>("~view/dz"); offset_ = QVector3D(dx, dy, dz); point_size_ = node->readParameter<double>("point/size"); size_sync_ = node->readParameter<bool>("~size/out/sync"); w_view_ = node->readParameter<int>("~size/width"); h_view_ = node->readParameter<int>("~size/height"); if (size_sync_) { w_out_ = w_view_; h_out_ = h_view_; } else { w_out_ = node->readParameter<int>("~size/out/width"); h_out_ = node->readParameter<int>("~size/out/height"); } axes_ = node->readParameter<bool>("show axes"); grid_size_ = node->readParameter<int>("~grid/size"); grid_resolution_ = node->readParameter<double>("~grid/resolution"); grid_xy_ = node->readParameter<bool>("~grid/xy"); grid_yz_ = node->readParameter<bool>("~grid/yz"); grid_xz_ = node->readParameter<bool>("~grid/xz"); repaint_ = true; Q_EMIT resizeRequest(); Q_EMIT repaintRequest(); } } void CloudRendererAdapter::displayCloud() { auto node = wrapped_.lock(); if (!node) { return; } auto copy = node->getMessage(); boost::apply_visitor(PointCloudMessage::Dispatch<CloudRendererAdapter>(this, copy), copy->value); } namespace { enum Component { X, Y, Z, I, AUTO }; template <class PointT, int Component> struct Access { }; template <class PointT> struct Access<PointT, X> { static double access(typename pcl::PointCloud<PointT>::const_iterator it) { return it->x; } }; template <class PointT> struct Access<PointT, Y> { static double access(typename pcl::PointCloud<PointT>::const_iterator it) { return it->y; } }; template <class PointT> struct Access<PointT, Z> { static double access(typename pcl::PointCloud<PointT>::const_iterator it) { return it->z; } }; template <class PointT> struct Access<PointT, I> { static double access(typename pcl::PointCloud<PointT>::const_iterator it) { return 0; } }; template <class PointT> struct Access<PointT, AUTO> { static double access(typename pcl::PointCloud<PointT>::const_iterator it) { return 0; } }; template <> struct Access<pcl::PointXYZI, I> { static double access(typename pcl::PointCloud<pcl::PointXYZI>::const_iterator it) { return it->intensity; } }; template <class PointT, int Component> struct Util { static void findExtrema(typename pcl::PointCloud<PointT>::ConstPtr cloud, double& min, double& max) { min = std::numeric_limits<double>::max(); max = std::numeric_limits<double>::min(); for (auto it = cloud->points.begin(); it != cloud->points.end(); ++it) { if (Access<PointT, Component>::access(it) < min) { min = Access<PointT, Component>::access(it); } if (Access<PointT, Component>::access(it) > max) { max = Access<PointT, Component>::access(it); } } } }; // adapted from RVIZ template <typename Color> void getRainbowColor(float value, Color& color) { value = std::max(std::min(value, 1.0f), 0.0f); float h = value * 5.0f + 1.0f; int i = floor(h); float f = h - i; if (!(i & 1)) f = 1 - f; // if i is even float n = 1 - f; if (i <= 1) color.setX(n), color.setY(0), color.setZ(1); else if (i == 2) color.setX(0), color.setY(n), color.setZ(1); else if (i == 3) color.setX(0), color.setY(1), color.setZ(n); else if (i == 4) color.setX(n), color.setY(1), color.setZ(0); else if (i >= 5) color.setX(1), color.setY(n), color.setZ(0); } template <class PointT, int Component> struct RendererGradient { static void render(typename pcl::PointCloud<PointT>::ConstPtr cloud, bool rainbow, const QVector3D& color_grad_start, const QVector3D& color_grad_end) { if (rainbow) { renderRainbow(cloud); } else { renderGradient(cloud, color_grad_start, color_grad_end); } } static void renderGradient(typename pcl::PointCloud<PointT>::ConstPtr cloud, const QVector3D& color_grad_start, const QVector3D& color_grad_end) { double min, max; Util<PointT, Component>::findExtrema(cloud, min, max); for (auto it = cloud->points.begin(); it != cloud->points.end(); ++it) { const PointT& pt = *it; double v = Access<PointT, Component>::access(it); double f = (v - min) / (max - min); QVector3D c = f * color_grad_start + (1.0 - f) * color_grad_end; glColor3d(c.x(), c.y(), c.z()); glVertex3d(pt.x, pt.y, pt.z); } } static void renderRainbow(typename pcl::PointCloud<PointT>::ConstPtr cloud) { double min, max; Util<PointT, Component>::findExtrema(cloud, min, max); for (auto it = cloud->points.begin(); it != cloud->points.end(); ++it) { const PointT& pt = *it; double v = Access<PointT, Component>::access(it); double f = (v - min) / (max - min); QVector3D c; getRainbowColor(f, c); glColor3d(c.x(), c.y(), c.z()); glVertex3d(pt.x, pt.y, pt.z); } } }; template <class PointT, int Component> struct Renderer { static void render(typename pcl::PointCloud<PointT>::ConstPtr cloud, bool rainbow, const QVector3D& color_grad_start, const QVector3D& color_grad_end) { RendererGradient<PointT, Component>::render(cloud, rainbow, color_grad_start, color_grad_end); } }; template <> struct Renderer<pcl::PointXYZRGB, AUTO> { static void render(typename pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud, bool, const QVector3D&, const QVector3D&) { for (auto it = cloud->points.begin(); it != cloud->points.end(); ++it) { const pcl::PointXYZRGB& pt = *it; glColor3d(pt.r / 255.0, pt.g / 255.0, pt.b / 255.0); glVertex3d(pt.x, pt.y, pt.z); } } }; } // namespace template <class PointT> void CloudRendererAdapter::inputCloud(typename pcl::PointCloud<PointT>::ConstPtr cloud) { auto node = wrapped_.lock(); if (!node) { return; } std::vector<pcl::PCLPointField> fields; std::vector<std::string> field_names; pcl::for_each_type<typename pcl::traits::fieldList<PointT>::type>(pcl::detail::FieldAdder<PointT>(fields)); for (size_t d = 0; d < fields.size(); ++d) { field_names.push_back(fields[d].name); } param::SetParameter::Ptr list = node->getParameter<param::SetParameter>("color/field"); apex_assert(list); std::vector<std::string> list_values = list->getSetTexts(); std::sort(field_names.begin(), field_names.end()); std::sort(list_values.begin(), list_values.end()); bool change = false; for (std::size_t i = 0; i < field_names.size(); ++i) { if (field_names[i] != list_values[i]) { change = true; break; } } if (change) { list->setSet(field_names); } makeCurrent(); if (list_cloud_ == 0) { list_cloud_ = glGenLists(1); } glNewList(list_cloud_, GL_COMPILE); glPointSize(point_size_); glBegin(GL_POINTS); std::string component = node->readParameter<std::string>("color/field"); bool rainbow = node->readParameter<bool>("color/rainbow"); if (node->readParameter<bool>("color/force gradient")) { if (component == "x") { RendererGradient<PointT, X>::render(cloud, rainbow, color_grad_start_, color_grad_end_); } else if (component == "y") { RendererGradient<PointT, Y>::render(cloud, rainbow, color_grad_start_, color_grad_end_); } else if (component == "z") { RendererGradient<PointT, Z>::render(cloud, rainbow, color_grad_start_, color_grad_end_); } else if (component == "intensity" || component == "i") { RendererGradient<PointT, I>::render(cloud, rainbow, color_grad_start_, color_grad_end_); } else { Renderer<PointT, AUTO>::render(cloud, rainbow, color_grad_start_, color_grad_end_); } } else { if (component == "x") { Renderer<PointT, X>::render(cloud, rainbow, color_grad_start_, color_grad_end_); } else if (component == "y") { Renderer<PointT, Y>::render(cloud, rainbow, color_grad_start_, color_grad_end_); } else if (component == "z") { Renderer<PointT, Z>::render(cloud, rainbow, color_grad_start_, color_grad_end_); } else if (component == "intensity" || component == "i") { Renderer<PointT, I>::render(cloud, rainbow, color_grad_start_, color_grad_end_); } else { Renderer<PointT, AUTO>::render(cloud, rainbow, color_grad_start_, color_grad_end_); } } glEnd(); glEndList(); Q_EMIT repaintRequest(); } QSize CloudRendererAdapter::minimumSizeHint() const { return QSize(10, 10); } QSize CloudRendererAdapter::sizeHint() const { return QSize(w_view_, h_view_); } namespace { double normalizeAngle(double angle) { while (angle <= -M_PI) { angle += 2 * M_PI; } while (angle > M_PI) { angle -= 2 * M_PI; } return angle; } } // namespace void CloudRendererAdapter::setTheta(double angle) { auto node = wrapped_.lock(); if (!node) { return; } double eps = 1e-3; if (angle < eps) { angle = eps; } else if (angle > M_PI - eps) { angle = M_PI - eps; } if (angle != theta_) { theta_ = angle; Q_EMIT thetaChanged(angle); node->getParameter("~view/theta")->set<double>(theta_); } } void CloudRendererAdapter::setPhi(double angle) { auto node = wrapped_.lock(); if (!node) { return; } angle = normalizeAngle(angle); if (angle != phi_) { phi_ = angle; Q_EMIT phiChanged(angle); node->getParameter("~view/phi")->set<double>(phi_); } } /// MOC #include "moc_cloud_renderer_adapter.cpp"
26.596154
154
0.59906
AdrianZw
af8ed14c28407ef5fee4a1d02e840d3173a2eecf
28,605
cpp
C++
Source/Graphics/GteShader.cpp
vehsakul/gtl
498bb20947e9ff21c08dd5a884ac3dc6f8313bb9
[ "BSL-1.0" ]
null
null
null
Source/Graphics/GteShader.cpp
vehsakul/gtl
498bb20947e9ff21c08dd5a884ac3dc6f8313bb9
[ "BSL-1.0" ]
null
null
null
Source/Graphics/GteShader.cpp
vehsakul/gtl
498bb20947e9ff21c08dd5a884ac3dc6f8313bb9
[ "BSL-1.0" ]
null
null
null
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2016 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) #include <GTEnginePCH.h> #include <Graphics/GteShader.h> using namespace gte; Shader::Data::Data(GraphicsObjectType inType, std::string const& inName, int inBindPoint, int inNumBytes, unsigned int inExtra, bool inIsGpuWritable) : type(inType), name(inName), bindPoint(inBindPoint), numBytes(inNumBytes), extra(inExtra), isGpuWritable(inIsGpuWritable) { } #if defined(GTE_DEV_OPENGL) Shader::Shader(GLSLReflection const& reflector, int type) : mNumXThreads(0), // TODO: compute shader support mNumYThreads(0), mNumZThreads(0) { // If this is a compute shader, then query the number of threads per group. if (GLSLReflection::ST_COMPUTE == type) { GLint sizeX, sizeY, sizeZ; reflector.GetComputeShaderWorkGroupSize(sizeX, sizeY, sizeZ); mNumXThreads = sizeX; mNumYThreads = sizeY; mNumZThreads = sizeZ; } // Will need to access uniforms more than once. auto const& uniforms = reflector.GetUniforms(); // Gather the uninforms information to create texture data. for (auto const& uni : uniforms) { if (uni.referencedBy[type]) { // Only interested in these particular uniform types (for gsampler* and gimage*) switch (uni.type) { case GL_SAMPLER_1D: case GL_INT_SAMPLER_1D: case GL_UNSIGNED_INT_SAMPLER_1D: mData[TextureSingle::shaderDataLookup].push_back( Data(GT_TEXTURE_SINGLE, uni.name, uni.location, 0, 1, false)); mData[SamplerState::shaderDataLookup].push_back( Data(GT_SAMPLER_STATE, uni.name, uni.location, 0, GT_TEXTURE1, false)); break; case GL_SAMPLER_2D: case GL_INT_SAMPLER_2D: case GL_UNSIGNED_INT_SAMPLER_2D: mData[TextureSingle::shaderDataLookup].push_back( Data(GT_TEXTURE_SINGLE, uni.name, uni.location, 0, 2, false)); mData[SamplerState::shaderDataLookup].push_back( Data(GT_SAMPLER_STATE, uni.name, uni.location, 0, GT_TEXTURE2, false)); break; case GL_SAMPLER_3D: case GL_INT_SAMPLER_3D: case GL_UNSIGNED_INT_SAMPLER_3D: mData[TextureSingle::shaderDataLookup].push_back( Data(GT_TEXTURE_SINGLE, uni.name, uni.location, 0, 3, false)); mData[SamplerState::shaderDataLookup].push_back( Data(GT_SAMPLER_STATE, uni.name, uni.location, 0, GT_TEXTURE3, false)); break; case GL_SAMPLER_1D_ARRAY: case GL_INT_SAMPLER_1D_ARRAY: case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: mData[TextureArray::shaderDataLookup].push_back( Data(GT_TEXTURE_ARRAY, uni.name, uni.location, 0, 1, false)); mData[SamplerState::shaderDataLookup].push_back( Data(GT_SAMPLER_STATE, uni.name, uni.location, 0, GT_TEXTURE1_ARRAY, false)); break; case GL_SAMPLER_2D_ARRAY: case GL_INT_SAMPLER_2D_ARRAY: case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: mData[TextureArray::shaderDataLookup].push_back( Data(GT_TEXTURE_ARRAY, uni.name, uni.location, 0, 2, false)); mData[SamplerState::shaderDataLookup].push_back( Data(GT_SAMPLER_STATE, uni.name, uni.location, 0, GT_TEXTURE2_ARRAY, false)); break; case GL_SAMPLER_CUBE: case GL_INT_SAMPLER_CUBE: case GL_UNSIGNED_INT_SAMPLER_CUBE: mData[TextureArray::shaderDataLookup].push_back( Data(GT_TEXTURE_ARRAY, uni.name, uni.location, 0, 2, false)); mData[SamplerState::shaderDataLookup].push_back( Data(GT_SAMPLER_STATE, uni.name, uni.location, 0, GT_TEXTURE_CUBE, false)); break; case GL_SAMPLER_CUBE_MAP_ARRAY: case GL_INT_SAMPLER_CUBE_MAP_ARRAY: case GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY: mData[TextureArray::shaderDataLookup].push_back( Data(GT_TEXTURE_ARRAY, uni.name, uni.location, 0, 3, false)); mData[SamplerState::shaderDataLookup].push_back( Data(GT_SAMPLER_STATE, uni.name, uni.location, 0, GT_TEXTURE_CUBE_ARRAY, false)); break; case GL_IMAGE_1D: case GL_INT_IMAGE_1D: case GL_UNSIGNED_INT_IMAGE_1D: mData[TextureSingle::shaderDataLookup].push_back( Data(GT_TEXTURE_SINGLE, uni.name, uni.location, 0, 1, true)); break; case GL_IMAGE_2D: case GL_INT_IMAGE_2D: case GL_UNSIGNED_INT_IMAGE_2D: mData[TextureSingle::shaderDataLookup].push_back( Data(GT_TEXTURE_SINGLE, uni.name, uni.location, 0, 2, true)); break; case GL_IMAGE_3D: case GL_INT_IMAGE_3D: case GL_UNSIGNED_INT_IMAGE_3D: mData[TextureSingle::shaderDataLookup].push_back( Data(GT_TEXTURE_SINGLE, uni.name, uni.location, 0, 3, true)); break; case GL_IMAGE_1D_ARRAY: case GL_INT_IMAGE_1D_ARRAY: case GL_UNSIGNED_INT_IMAGE_1D_ARRAY: mData[TextureArray::shaderDataLookup].push_back( Data(GT_TEXTURE_ARRAY, uni.name, uni.location, 0, 1, true)); break; case GL_IMAGE_2D_ARRAY: case GL_INT_IMAGE_2D_ARRAY: case GL_UNSIGNED_INT_IMAGE_2D_ARRAY: mData[TextureArray::shaderDataLookup].push_back( Data(GT_TEXTURE_ARRAY, uni.name, uni.location, 0, 2, true)); break; case GL_IMAGE_CUBE: case GL_INT_IMAGE_CUBE: case GL_UNSIGNED_INT_IMAGE_CUBE: mData[TextureArray::shaderDataLookup].push_back( Data(GT_TEXTURE_ARRAY, uni.name, uni.location, 0, 2, true)); break; case GL_IMAGE_CUBE_MAP_ARRAY: case GL_INT_IMAGE_CUBE_MAP_ARRAY: case GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY: mData[TextureArray::shaderDataLookup].push_back( Data(GT_TEXTURE_ARRAY, uni.name, uni.location, 0, 3, true)); break; } } } // Gather the uniform blocks information to create constant buffer data. auto const& uniformBlocks = reflector.GetUniformBlocks(); int numUniformBlockReferences = 0; for (auto const& block : uniformBlocks) { if (block.referencedBy[type]) { ++numUniformBlockReferences; } } if (numUniformBlockReferences > 0) { mCBufferLayouts.resize(numUniformBlockReferences); // Store information needed by GL4Engine for enabling/disabling the // constant buffers. int blockIndex = 0; int layoutIndex = 0; for (auto const& block : uniformBlocks) { if (block.referencedBy[type]) { mData[ConstantBuffer::shaderDataLookup].push_back( Data(GT_CONSTANT_BUFFER, block.name, block.bufferBinding, block.bufferDataSize, 0, false)); // Assemble the constant buffer layout information. for (auto const& uniform : uniforms) { if (uniform.blockIndex != blockIndex) { continue; } MemberLayout item; item.name = uniform.name; item.offset = uniform.offset; // TODO: The HLSL reflection has numElements of 0 when // the item is not an array, but the actual number when // it is an array. ConstantBuffer::SetMember(...) uses // this information, so we need to adhere to the pattern. // Change this design in a refactor? item.numElements = (uniform.arraySize > 1 ? uniform.arraySize : 0); mCBufferLayouts[layoutIndex].push_back(item); } ++layoutIndex; } ++blockIndex; } } // Gather the atomic counter buffer information to create atomic counter buffer data. auto const& atomicCounterBuffers = reflector.GetAtomicCounterBuffers(); int numAtomicCounterBufferReferences = 0; for (auto const& block : atomicCounterBuffers) { if (block.referencedBy[type]) { ++numAtomicCounterBufferReferences; } } if (numAtomicCounterBufferReferences > 0) { unsigned blockIndex = 0; for (auto const& block : atomicCounterBuffers) { if (block.referencedBy[type]) { // It is possible for the atomic counter buffer to indicate it // only has 4 bytes for a single counter located at offset=4. // But we will want to allocate a buffer large enough to store // from offset=0 to the last counter declared in the buffer. unsigned bufferDataSize = block.bufferDataSize; for (unsigned i=0; i < block.activeVariables.size(); ++i) { auto const& ac = uniforms[block.activeVariables[i]]; unsigned const lastByte = ac.offset + 4; bufferDataSize = std::max(bufferDataSize, lastByte); } mData[AtomicCounterBufferShaderDataLookup].push_back( Data(GT_RESOURCE, "atomicCounterBuffer" + std::to_string(blockIndex), block.bufferBinding, bufferDataSize, 0, true)); } ++blockIndex; } } // Gather the buffer blocks information to create structured buffer data. auto const& bufferBlocks = reflector.GetBufferBlocks(); int numBufferBlockReferences = 0; for (auto const& block : bufferBlocks) { if (block.referencedBy[type]) { ++numBufferBlockReferences; } } if (numBufferBlockReferences > 0) { auto const& bufferVariables = reflector.GetBufferVariables(); mSBufferLayouts.resize(numBufferBlockReferences); // Store information needed by GL4Engine for enabling/disabling the // structured buffers. int blockIndex = 0; int layoutIndex = 0; for (auto const& block : bufferBlocks) { if (block.referencedBy[type]) { // Search through uniforms looking for atomic counter with // the same name and "Counter" suffix. The ID is the index // for this uniform so that it can be looked up later. auto const counterName = block.name + "Counter"; bool hasAtomicCounter = false; unsigned int idAtomicCounter = ~0U; for (auto const& uniform : uniforms) { if ((counterName == uniform.name) && (uniform.atomicCounterBufferIndex >= 0)) { hasAtomicCounter = true; idAtomicCounter = static_cast<unsigned int>(mData[AtomicCounterShaderDataLookup].size()); mData[AtomicCounterShaderDataLookup].push_back( Data(GT_STRUCTURED_BUFFER, uniform.name, uniform.atomicCounterBufferIndex, 4, uniform.offset, false)); break; } } // Assemble the structured buffer layout information. // Only interested in variables in the buffer that are part of // a top level array stride. Anything up to this block is ignored // and anything after this block is ignored which means only one // top level array is supported. auto& layout = mSBufferLayouts[layoutIndex]; GLint structSize = 0; for (unsigned v = 0; v < block.activeVariables.size(); ++v) { auto const& bufferVar = bufferVariables[block.activeVariables[v]]; if (bufferVar.topLevelArrayStride != structSize) { // Stop when we were processing buffer variables with a certain // a top-level array stride and that changed. if (0 != structSize) { break; } structSize = bufferVar.topLevelArrayStride; } // These are the variables in the structured buffer. if (structSize > 0) { MemberLayout item; item.name = bufferVar.name; item.offset = bufferVar.offset; // TODO: The HLSL reflection has numElements of 0 when // the item is not an array, but the actual number when // it is an array. ConstantBuffer::SetMember(...) uses // this information, so we need to adhere to the pattern. // Change this design in a refactor? item.numElements = (bufferVar.arraySize > 1 ? bufferVar.arraySize : 0); layout.push_back(item); } } // Use the top level array stride as a better indication // of the overall struct size. mData[StructuredBuffer::shaderDataLookup].push_back( Data(GT_STRUCTURED_BUFFER, block.name, block.bufferBinding, structSize, idAtomicCounter, hasAtomicCounter)); ++layoutIndex; } ++blockIndex; } } // The conversion depends on the 'type' of the ordering: {vertex = 0, // geometry = 1, pixel = 2, compute = 3}. mType = static_cast<GraphicsObjectType>(GT_SHADER + 1 + type); } #else Shader::Shader(HLSLShader const& program) : mCompiledCode(program.GetCompiledCode()), mNumXThreads(program.GetNumXThreads()), mNumYThreads(program.GetNumYThreads()), mNumZThreads(program.GetNumZThreads()) { mCBufferLayouts.resize(program.GetCBuffers().size()); int i = 0; for (auto const& cb : program.GetCBuffers()) { mData[ConstantBuffer::shaderDataLookup].push_back( Data(GT_CONSTANT_BUFFER, cb.GetName(), cb.GetBindPoint(), cb.GetNumBytes(), 0, false)); cb.GenerateLayout(mCBufferLayouts[i]); ++i; } mTBufferLayouts.resize(program.GetTBuffers().size()); i = 0; for (auto const& tb : program.GetTBuffers()) { mData[TextureBuffer::shaderDataLookup].push_back( Data(GT_TEXTURE_BUFFER, tb.GetName(), tb.GetBindPoint(), tb.GetNumBytes(), 0, false)); tb.GenerateLayout(mTBufferLayouts[i]); ++i; } for (auto const& sb : program.GetSBuffers()) { unsigned int ctrtype = 0xFFFFFFFFu; switch (sb.GetType()) { case HLSLStructuredBuffer::SBT_BASIC: ctrtype = StructuredBuffer::CT_NONE; break; case HLSLStructuredBuffer::SBT_APPEND: case HLSLStructuredBuffer::SBT_CONSUME: ctrtype = StructuredBuffer::CT_APPEND_CONSUME; break; case HLSLStructuredBuffer::SBT_COUNTER: ctrtype = StructuredBuffer::CT_COUNTER; break; default: LogError("Unexpected structured buffer option: " + std::to_string(static_cast<int>(sb.GetType()))); } mData[StructuredBuffer::shaderDataLookup].push_back( Data(GT_STRUCTURED_BUFFER, sb.GetName(), sb.GetBindPoint(), sb.GetNumBytes(), ctrtype, sb.IsGpuWritable())); } for (auto const& rb : program.GetRBuffers()) { mData[RawBuffer::shaderDataLookup].push_back( Data(GT_RAW_BUFFER, rb.GetName(), rb.GetBindPoint(), rb.GetNumBytes(), 0, rb.IsGpuWritable())); } for (auto const& tx : program.GetTextures()) { mData[TextureSingle::shaderDataLookup].push_back( Data(GT_TEXTURE_SINGLE, tx.GetName(), tx.GetBindPoint(), 0, tx.GetNumDimensions(), tx.IsGpuWritable())); } for (auto const& ta : program.GetTextureArrays()) { mData[TextureArray::shaderDataLookup].push_back( Data(GT_TEXTURE_ARRAY, ta.GetName(), ta.GetBindPoint(), 0, ta.GetNumDimensions(), ta.IsGpuWritable())); } for (auto const& s : program.GetSamplerStates()) { mData[SamplerState::shaderDataLookup].push_back( Data(GT_SAMPLER_STATE, s.GetName(), s.GetBindPoint(), 0, 0, false)); } // The conversion depends on the HLSLShader::Type ordering to be the // same as GraphicsObjectType for GL_SHADER through GL_COMPUTE_SHADER. int index = program.GetShaderTypeIndex(); mType = static_cast<GraphicsObjectType>(GT_SHADER + 1 + index); } #endif int Shader::Get(std::string const& name) const { for (int lookup = 0; lookup < NUM_LOOKUP_INDICES; ++lookup) { int handle = 0; for (auto const& data : mData[lookup]) { if (name == data.name) { return handle; } ++handle; } } return -1; } unsigned int Shader::GetConstantBufferSize(int handle) const { auto const& data = mData[ConstantBuffer::shaderDataLookup]; if (0 <= handle && handle < static_cast<int>(data.size())) { return data[handle].numBytes; } LogError("Invalid handle for object."); return 0; } unsigned int Shader::GetConstantBufferSize(std::string const& name) const { int handle = 0; for (auto& data : mData[ConstantBuffer::shaderDataLookup]) { if (name == data.name) { return data.numBytes; } ++handle; } LogError("Cannot find object " + name + "."); return 0; } unsigned int Shader::GetTextureBufferSize(int handle) const { auto const& data = mData[TextureBuffer::shaderDataLookup]; if (0 <= handle && handle < static_cast<int>(data.size())) { return data[handle].numBytes; } LogError("Invalid handle for object."); return 0; } unsigned int Shader::GetTextureBufferSize(std::string const& name) const { int handle = 0; for (auto& data : mData[TextureBuffer::shaderDataLookup]) { if (name == data.name) { return data.numBytes; } ++handle; } LogError("Cannot find object " + name + "."); return 0; } unsigned int Shader::GetStructuredBufferSize(int handle) const { auto const& data = mData[StructuredBuffer::shaderDataLookup]; if (0 <= handle && handle < static_cast<int>(data.size())) { return data[handle].numBytes; } LogError("Invalid handle for object."); return 0; } unsigned int Shader::GetStructuredBufferSize(std::string const& name) const { int handle = 0; for (auto& data : mData[StructuredBuffer::shaderDataLookup]) { if (name == data.name) { return data.numBytes; } ++handle; } LogError("Cannot find object " + name + "."); return 0; } bool Shader::GetConstantBufferLayout(int handle, BufferLayout& layout) const { auto const& data = mData[ConstantBuffer::shaderDataLookup]; if (0 <= handle && handle < static_cast<int>(data.size())) { layout = mCBufferLayouts[handle]; return true; } LogError("Invalid handle for object."); return false; } bool Shader::GetConstantBufferLayout(std::string const& name, BufferLayout& layout) const { int handle = 0; for (auto& data : mData[ConstantBuffer::shaderDataLookup]) { if (name == data.name) { layout = mCBufferLayouts[handle]; return true; } ++handle; } LogError("Cannot find object " + name + "."); return false; } bool Shader::GetTextureBufferLayout(int handle, BufferLayout& layout) const { auto const& data = mData[TextureBuffer::shaderDataLookup]; if (0 <= handle && handle < static_cast<int>(data.size())) { layout = mTBufferLayouts[handle]; return true; } LogError("Invalid handle for object."); return false; } bool Shader::GetTextureBufferLayout(std::string const& name, BufferLayout& layout) const { int handle = 0; for (auto& data : mData[TextureBuffer::shaderDataLookup]) { if (name == data.name) { layout = mTBufferLayouts[handle]; return true; } ++handle; } LogError("Cannot find object " + name + "."); return false; } #if defined(GTE_DEV_OPENGL) bool Shader::GetStructuredBufferLayout(int handle, BufferLayout& layout) const { auto const& data = mData[StructuredBuffer::shaderDataLookup]; if (0 <= handle && handle < static_cast<int>(data.size())) { layout = mSBufferLayouts[handle]; return true; } LogError("Invalid handle for object."); return false; } bool Shader::GetStructuredBufferLayout(std::string const& name, BufferLayout& layout) const { int handle = 0; for (auto& data : mData[StructuredBuffer::shaderDataLookup]) { if (name == data.name) { layout = mSBufferLayouts[handle]; return true; } ++handle; } LogError("Cannot find object " + name + "."); return false; } #endif bool Shader::IsValid(Data const& goal, ConstantBuffer* resource) const { if (!resource) { LogError("Resource is null."); return false; } if (goal.type != GT_CONSTANT_BUFFER) { LogError("Mismatch of buffer type."); return false; } if (resource->GetNumBytes() >= static_cast<size_t>(goal.numBytes)) { return true; } LogError("Invalid number of bytes."); return false; } bool Shader::IsValid(Data const& goal, TextureBuffer* resource) const { if (!resource) { LogError("Resource is null."); return false; } if (goal.type != GT_TEXTURE_BUFFER) { LogError("Mismatch of buffer type."); return false; } if (resource->GetNumBytes() >= static_cast<size_t>(goal.numBytes)) { return true; } LogError("Invalid number of bytes."); return false; } bool Shader::IsValid(Data const& goal, StructuredBuffer* resource) const { if (!resource) { LogError("Resource is null."); return false; } if (goal.type != GT_STRUCTURED_BUFFER) { LogError("Mismatch of buffer type."); return false; } #if !defined(GTE_DEV_OPENGL) // GL4 reflection does not provide information about writable access of // buffer objects in a shader because by definition, shader storage buffer // objects can be read-write by shaders. For GL4, the isGpuWritable flag is // used to indicate whether the structured buffer has a counter attached or not. if (goal.isGpuWritable && resource->GetUsage() != Resource::SHADER_OUTPUT) { LogError("Mismatch of GPU write flag."); return false; } #endif #if defined(GTE_DEV_OPENGL) // OpenGL does not have the concept of an append-consume type structured // buffer nor does it have the concept of a structured buffer with counter. // But, this GL4 support does associate an atomic counter with a structured // buffer as long as it has the same name. If the shader is expecting // a counter, then the structured buffer needs to be declared with one. if (goal.isGpuWritable && (StructuredBuffer::CT_NONE == resource->GetCounterType())) { LogError("Mismatch of counter type."); return false; } #else // A countered structure buffer can be attached as a read-only input to // a shader. We care about the mismatch in counter type only when the // shader needs a countered structure buffer but the attached resource // does not have one. if (goal.extra != 0 && goal.extra != static_cast<unsigned int>(resource->GetCounterType())) { LogError("Mismatch of counter type."); return false; } #endif return true; } bool Shader::IsValid(Data const& goal, RawBuffer* resource) const { if (!resource) { LogError("Resource is null."); return false; } if (goal.type != GT_RAW_BUFFER) { LogError("Mismatch of buffer type."); return false; } if (goal.isGpuWritable && resource->GetUsage() != Resource::SHADER_OUTPUT) { LogError("Mismatch of GPU write flag."); return false; } return true; } bool Shader::IsValid(Data const& goal, TextureSingle* resource) const { if (!resource) { LogError("Resource is null."); return false; } if (goal.type != GT_TEXTURE_SINGLE) { LogError("Mismatch of texture type."); return false; } #if !defined(GTE_DEV_OPENGL) // GL4 reflection does not provide information about writable access // of gimage* and gsampler* objects in a shader. For GL4, the isGpuWritable flag is // used to indicate whether the texture could be writable in shader which // is false for gshader* objects and is true for gimage* objects. if (goal.isGpuWritable && resource->GetUsage() != Resource::SHADER_OUTPUT) { LogError("Mismatch of GPU write flag."); return false; } #endif if (goal.extra != resource->GetNumDimensions()) { LogError("Mismatch of texture dimensions."); return false; } // TODO: Add validation for HLSLTexture::Component and number of // components (requires comparison to TextureFormat value). return true; } bool Shader::IsValid(Data const& goal, TextureArray* resource) const { if (!resource) { LogError("Resource is null."); return false; } if (goal.type != GT_TEXTURE_ARRAY) { LogError("Mismatch of texture type."); return false; } #if !defined(GTE_DEV_OPENGL) // GL4 reflection does not provide information about writable access // of gimage* and gsampler* objects in a shader. For GL4, the isGpuWritable flag is // used to indicate whether the texture could be writable in shader which // is false for gshader* objects and is true for gimage* objects. if (goal.isGpuWritable && resource->GetUsage() != Resource::SHADER_OUTPUT) { LogError("Mismatch of GPU write flag."); return false; } #endif if (goal.extra != resource->GetNumDimensions()) { LogError("Mismatch of texture dimensions."); return false; } // TODO: Add validation for HLSLTexture::Component and number of // components (requires comparison to TextureFormat value). return true; } bool Shader::IsValid(Data const& goal, SamplerState* resource) const { if (!resource) { LogError("Resource is null."); return false; } if (goal.type != GT_SAMPLER_STATE) { LogError("Mismatch of state."); return false; } return true; }
33.184455
113
0.581052
vehsakul
af92c6b864d1d5a23b6d0b66c006dbfb2017bac7
800
cpp
C++
app/editor/editor_app.cpp
walkinsky8/nana-runner
103992e07e7e644d349437fdf959364ffe9cb653
[ "BSL-1.0" ]
5
2017-12-28T08:22:20.000Z
2022-03-30T01:26:17.000Z
app/editor/editor_app.cpp
walkinsky8/nana-runner
103992e07e7e644d349437fdf959364ffe9cb653
[ "BSL-1.0" ]
null
null
null
app/editor/editor_app.cpp
walkinsky8/nana-runner
103992e07e7e644d349437fdf959364ffe9cb653
[ "BSL-1.0" ]
null
null
null
/** * Runa C++ Library * Copyright (c) 2017-2019 walkinsky:lyh6188(at)hotmail(dot)com * * 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) */ // Created on 2018/11/09 #include "stdafx.h" #include "editor_app.h" using namespace runa::editor; editor_app::editor_app() { } void editor_app::on_init() { if (cmdargs().has_option(L"nologin")) nologin_ = true; if (cmdargs().has_option(L"nologwin")) nologwin_ = true; if (!nologin_) { login_.open([&] { editor_.open(nullptr, nologwin_); }); } else { editor_.open(nullptr, nologwin_); } } void editor_app::on_fini() { login_.close(); editor_.close(); }
17.777778
62
0.61875
walkinsky8
af980276f44f4250fc4a513282b4e4d59875bb6a
7,504
cpp
C++
triangle/main.cpp
amecky/ds_sandbox
f31e69f72a76c40aeb0fa3e3fbe9b651660df770
[ "MIT" ]
1
2017-09-28T19:41:04.000Z
2017-09-28T19:41:04.000Z
triangle/main.cpp
amecky/ds_sandbox
f31e69f72a76c40aeb0fa3e3fbe9b651660df770
[ "MIT" ]
null
null
null
triangle/main.cpp
amecky/ds_sandbox
f31e69f72a76c40aeb0fa3e3fbe9b651660df770
[ "MIT" ]
null
null
null
#define DS_IMPLEMENTATION #define DS_MATH_IMPLEMENTATION #include <diesel.h> #include "Triangle_VS_Main.h" #include "Triangle_PS_Main.h" #include "Camera.h" static const ds::Color COLORS[] = { ds::Color(255,0,0,255), ds::Color(0,255,0,255), ds::Color(255,255,0,255), ds::Color(0,0,255,255), ds::Color(32,32,32,255) }; struct ConstantBuffer { ds::matrix viewprojectionMatrix; ds::matrix worldMatrix; }; // --------------------------------------------------------------- // Vertex // --------------------------------------------------------------- struct Vertex { ds::vec3 p; ds::Color color; }; int createBox(Vertex* v, int offset, float width, float depth, const ds::vec3& center, float r1, float r2,float angle, float step, const ds::Color& c) { int cnt = offset; ds::vec3 p1 = center + ds::vec3(cos(angle), sin(angle), 0.0f) * r1; ds::vec3 p2 = center + ds::vec3(cos(angle), sin(angle), 0.0f) * r2; ds::vec3 p3 = center + ds::vec3(cos(angle - step), sin(angle - step), 0.0f) * r2; ds::vec3 p4 = center + ds::vec3(cos(angle - step), sin(angle - step), 0.0f) * r1; v[cnt++] = { p1, c }; v[cnt++] = { p2, c }; v[cnt++] = { p3, c }; v[cnt++] = { p4, c }; p1 = center + ds::vec3(cos(angle), sin(angle), 0.0f) * r2; p2 = center + ds::vec3(cos(angle), sin(angle), depth) * r2; p3 = center + ds::vec3(cos(angle - step), sin(angle - step), depth) * r2; p4 = center + ds::vec3(cos(angle - step), sin(angle - step), 0.0f) * r2; v[cnt++] = { p1, c }; v[cnt++] = { p2, c }; v[cnt++] = { p3, c }; v[cnt++] = { p4, c }; p1 = center + ds::vec3(cos(angle), sin(angle), depth) * r1; p2 = center + ds::vec3(cos(angle), sin(angle), 0.0f) * r1; p3 = center + ds::vec3(cos(angle - step), sin(angle - step), 0.0f) * r1; p4 = center + ds::vec3(cos(angle - step), sin(angle - step), depth) * r1; v[cnt++] = { p1, c }; v[cnt++] = { p2, c }; v[cnt++] = { p3, c }; v[cnt++] = { p4, c }; p4 = center + ds::vec3(cos(angle), sin(angle), depth) * r1; p3 = center + ds::vec3(cos(angle), sin(angle), depth) * r2; p2 = center + ds::vec3(cos(angle - step), sin(angle - step), depth) * r2; p1 = center + ds::vec3(cos(angle - step), sin(angle - step), depth) * r1; v[cnt++] = { p1, c }; v[cnt++] = { p2, c }; v[cnt++] = { p3, c }; v[cnt++] = { p4, c }; return cnt; } int createTorus(Vertex* v, int offset, float width, float depth, const ds::vec3& center, float r1, float r2, float angle, float step, const ds::Color& c) { int cnt = offset; float w = 0.5f; float ts = ds::TWO_PI / static_cast<float>(16); float ta = 0.0f; ds::vec3 rd1 = center; ds::vec3 rd2 = center; for (int i = 0; i < 1; ++i) { rd1 = center + ds::vec3(cos(ta) * i, sin(ta) * i, 0.0f); rd2 = center + ds::vec3(cos(ta + ts) * i, sin(ta + ts) * i, 0.0f); ds::vec3 p1 = ds::vec3(cos(angle), sin(angle), 0.0f) * w + rd1; ds::vec3 p2 = ds::vec3(cos(angle), sin(angle), 0.0f) * w + rd2; ds::vec3 p3 = ds::vec3(cos(angle - step), sin(angle - step), 0.0f) * w + rd2; ds::vec3 p4 = ds::vec3(cos(angle - step), sin(angle - step), 0.0f) * w + rd1; v[cnt++] = { p1, c }; v[cnt++] = { p2, c }; v[cnt++] = { p3, c }; v[cnt++] = { p4, c }; ta += ts; } return cnt; } void createTorus(Vertex* v, int maxVertices, int segments, float width, float depth) { int cnt = 0; float r1 = 1.0f; float r2 = r1 + width; float step = ds::TWO_PI / static_cast<float>(segments); float angle = 0.0f; ds::Color c(255, 0, 0, 255); ds::vec3 center(0.0f, 0.0f,1.0f); for (int i = 0; i < segments; ++i) { int idx = i % 5; c = COLORS[idx]; //center = ds::vec3(0.0f, 0.0f, 1.0f); center = ds::vec3(cos(angle), sin(angle), 1.0f); //cnt = createTorus(v, cnt, width, 0.2f, center, r1, r2, angle, step, c); //center = ds::vec3(0.0f, 0.0f, 0.0f); cnt = createBox(v, cnt, width, 0.2f, center, r1, r2, angle, step, c); angle += step; } } // --------------------------------------------------------------- // main method // --------------------------------------------------------------- int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdshow) { // // prepare application // ds::RenderSettings rs; rs.width = 1024; rs.height = 768; rs.title = "Triangle demo"; rs.clearColor = ds::Color(0.1f, 0.1f, 0.1f, 1.0f); rs.multisampling = 4; rs.useGPUProfiling = false; rs.supportDebug = true; ds::init(rs); // // create render with view and projection matrix // ds::matrix viewMatrix = ds::matLookAtLH(ds::vec3(0.0f, 0.0f, -4.0f), ds::vec3(0, 0, 0), ds::vec3(0, 1, 0)); ds::matrix projectionMatrix = ds::matPerspectiveFovLH(ds::PI / 4.0f, ds::getScreenAspectRatio(), 0.01f, 100.0f); ds::Camera camera = { viewMatrix, projectionMatrix, viewMatrix * projectionMatrix, ds::vec3(0,0,-4), ds::vec3(0,0,1), ds::vec3(0,1,0), ds::vec3(1,0,0), 0.0f, 0.0f, 0.0f }; RID vp = ds::createViewport(ds::ViewportDesc() .Top(0) .Left(0) .Width(1024) .Height(768) .MinDepth(0.0f) .MaxDepth(1.0f) ); RID basicPass = ds::createRenderPass(ds::RenderPassDesc() .Camera(&camera) .Viewport(vp) .DepthBufferState(ds::DepthBufferState::ENABLED) .RenderTargets(0) .NumRenderTargets(0)); // // create resources // RID vertexShader = ds::createShader(ds::ShaderDesc() .Data(Triangle_VS_Main) .DataSize(sizeof(Triangle_VS_Main)) .ShaderType(ds::ShaderType::ST_VERTEX_SHADER) ); RID pixelShader = ds::createShader(ds::ShaderDesc() .Data(Triangle_PS_Main) .DataSize(sizeof(Triangle_PS_Main)) .ShaderType(ds::ShaderType::ST_PIXEL_SHADER) ); // create buffer input layout ds::InputLayoutDefinition decl[] = { { "POSITION", 0, ds::BufferAttributeType::FLOAT3 }, { "COLOR", 0, ds::BufferAttributeType::FLOAT4 } }; // --------------------------------------------------- // create tube // --------------------------------------------------- const int segments = 128; const int numVertices = segments * 16 * 2; Vertex v[numVertices]; createTorus(v, numVertices, segments, 0.1f, 0.2f); RID rid = ds::createInputLayout(ds::InputLayoutDesc() . Declarations(decl) .NumDeclarations(2) .VertexShader(vertexShader) ); RID vbid = ds::createVertexBuffer(ds::VertexBufferDesc() .BufferType(ds::BufferType::STATIC) .Data(v) .NumVertices(numVertices) .VertexSize(sizeof(Vertex)) ); RID indexBuffer = ds::createQuadIndexBuffer(numVertices / 4); ConstantBuffer constantBuffer; constantBuffer.worldMatrix = ds::matIdentity(); constantBuffer.viewprojectionMatrix = ds::matIdentity(); RID cbId = ds::createConstantBuffer(sizeof(ConstantBuffer), &constantBuffer); // // create state group // RID stateGroup = ds::StateGroupBuilder() .inputLayout(rid) .constantBuffer(cbId,vertexShader) .vertexBuffer(vbid) .vertexShader(vertexShader) .indexBuffer(indexBuffer) .pixelShader(pixelShader) .build(); // // the draw command // ds::DrawCommand drawCmd = { numVertices / 4 * 6, ds::DrawType::DT_INDEXED, ds::PrimitiveTypes::TRIANGLE_LIST }; // // and finally we can create the draw item // RID drawItem = ds::compile(drawCmd, stateGroup); FPSCamera fpsCamera(&camera); fpsCamera.setPosition(ds::vec3(0, 0, -4)); fpsCamera.buildView(); while (ds::isRunning()) { ds::begin(); fpsCamera.update(static_cast<float>(ds::getElapsedSeconds())); constantBuffer.viewprojectionMatrix = ds::matTranspose(camera.viewProjectionMatrix); ds::submit(basicPass, drawItem); ds::dbgPrint(0, 0, "FPS: %d", ds::getFramesPerSecond()); ds::end(); } ds::shutdown(); return 0; }
29.3125
155
0.600213
amecky
af996685901d480ecac762916235176f4aaed8c7
301
hpp
C++
examples/send_inline/include/send_inline.hpp
nathanielhourt/eosio.cdt
798162d323680fa6d4691bcea7928729213c7172
[ "MIT" ]
476
2018-09-07T01:27:11.000Z
2022-03-21T05:16:50.000Z
examples/send_inline/include/send_inline.hpp
eosio-cmd/eosio.cdt
ac7161e702856711503933a8631d3005a55e0b98
[ "MIT" ]
594
2018-09-06T02:03:01.000Z
2022-03-23T19:18:26.000Z
examples/send_inline/include/send_inline.hpp
eosio-cmd/eosio.cdt
ac7161e702856711503933a8631d3005a55e0b98
[ "MIT" ]
349
2018-09-06T05:02:09.000Z
2022-03-12T11:07:17.000Z
#include <eosio/eosio.hpp> using namespace eosio; class [[eosio::contract]] send_inline : public contract { public: using contract::contract; [[eosio::action]] void test( name user, name inline_code ); using test_action = action_wrapper<"test"_n, &send_inline::test>; };
23.153846
71
0.671096
nathanielhourt
af997b1c0250dd6daf582b90502b71c0a288bbe3
230
hpp
C++
src/entity.hpp
WesOfX/block-game
0f52a7668cade1481a3beb659885462274dc9369
[ "MIT" ]
null
null
null
src/entity.hpp
WesOfX/block-game
0f52a7668cade1481a3beb659885462274dc9369
[ "MIT" ]
null
null
null
src/entity.hpp
WesOfX/block-game
0f52a7668cade1481a3beb659885462274dc9369
[ "MIT" ]
null
null
null
#pragma once #include "vec3.hpp" struct entity{ typedef vec3<float> position_type; position_type position, velocity; void move(const position_type& offset); void accelerate(const position_type& amount); void update(); };
17.692308
46
0.756522
WesOfX
af9b9097e1c293e81052ffd85b56171a4b8015bb
161
hpp
C++
src/left09.hpp
nghiaho12/OpenCV_camera_in_OpenGL
bce72d57fdb21b44671be826d61bc2b7c1e3210c
[ "BSD-2-Clause" ]
4
2021-03-04T20:52:07.000Z
2022-03-26T05:49:54.000Z
src/left09.hpp
nghiaho12/OpenCV_camera_in_OpenGL
bce72d57fdb21b44671be826d61bc2b7c1e3210c
[ "BSD-2-Clause" ]
null
null
null
src/left09.hpp
nghiaho12/OpenCV_camera_in_OpenGL
bce72d57fdb21b44671be826d61bc2b7c1e3210c
[ "BSD-2-Clause" ]
3
2021-01-04T11:18:29.000Z
2021-08-04T03:29:36.000Z
#pragma once // left09.jpg from OpenCV sample directory converted to raw char array int left09_width(); int left09_height(); const unsigned char *left09_data();
26.833333
70
0.782609
nghiaho12
af9ff4a5b82392bbada2faf07045d0043c8cf74f
5,355
cpp
C++
VC2015Samples/Hilo/C++/Common/source/WindowLayout.cpp
alonmm/VCSamples
6aff0b4902f5027164d593540fcaa6601a0407c3
[ "MIT" ]
300
2019-05-09T05:32:33.000Z
2022-03-31T20:23:24.000Z
VC2015Samples/Hilo/C++/Common/source/WindowLayout.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
9
2016-09-19T18:44:26.000Z
2018-10-26T10:20:05.000Z
VC2015Samples/Hilo/C++/Common/source/WindowLayout.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
633
2019-05-08T07:34:12.000Z
2022-03-30T04:38:28.000Z
//=================================================================================== // Copyright (c) Microsoft Corporation. All 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 // FITNESS FOR A PARTICULAR PURPOSE. //=================================================================================== #include "stdafx.h" #include "WindowLayoutChildInterface.h" using namespace Hilo::Direct2DHelpers; using namespace Hilo::WindowApiHelpers; HRESULT WindowLayout::SetMainWindow(__in_opt IWindow* mainWindow) { m_applicationWindow = mainWindow; return S_OK; } HRESULT WindowLayout::GetMainWindow(IWindow** mainWindow) { return AssignToOutputPointer(mainWindow, m_applicationWindow); } HRESULT WindowLayout::GetChildWindowCount(unsigned int* count) { // Check for valid out parameter assert(count); (*count) = static_cast<unsigned int>(m_childWindows.size()); return S_OK; } HRESULT WindowLayout::GetChildWindow(unsigned int index, IWindow** childWindow) { // Check for valid out parameter assert(childWindow); *childWindow = nullptr; // Check for valid index value if (index >= m_childWindows.size()) { return E_INVALIDARG; } return AssignToOutputPointer(childWindow, m_childWindows[index]); } HRESULT WindowLayout::GetChildWindowLayoutHeight(unsigned int index, unsigned int* height) { // Check for valid out parameter assert(height); // Check for valid index value if (index >= m_childWindows.size()) { return E_INVALIDARG; } if (index == 0) { if (m_isSlideShow) { *height = 0; } else { *height = m_carouselPaneHeight; } } return S_OK; } HRESULT WindowLayout::SetChildWindowLayoutHeight(unsigned int /*index*/, unsigned int height) { m_carouselPaneHeight = height; return S_OK; } WindowLayout::WindowLayout() : m_isSlideShow(false) { } WindowLayout::~WindowLayout() { } HRESULT WindowLayout::SwitchDisplayMode(bool mode) { // Update slide show mode m_isSlideShow = mode; // Update window layout return UpdateLayout(); } HRESULT WindowLayout::UpdateLayout() { RECT clientRect; HRESULT hr = m_applicationWindow->GetClientRect(&clientRect); if (SUCCEEDED(hr)) { // Tracks remaining width and height unsigned int width = clientRect.right - clientRect.left; unsigned int height = clientRect.bottom - clientRect.top; // Tracks current position for window placement unsigned int xPos = 0; unsigned int yPos = 0; if (m_isSlideShow) { // Hide the carousel pane during slide-show mode hr = m_childWindows[0]->SetSize(0, 0); } else { // Update carousel pane position hr = m_childWindows[0]->SetPosition(xPos, yPos); if (SUCCEEDED(hr)) { // Update carousel pane position hr = m_childWindows[0]->SetSize(width, m_carouselPaneHeight); } // Update current y-position yPos = min(yPos + m_carouselPaneHeight, height); } if (SUCCEEDED(hr)) { // Update media pane position hr = m_childWindows[1]->SetPosition(xPos, yPos); } if (SUCCEEDED(hr)) { // Update media pane size hr = m_childWindows[1]->SetSize(width, height - yPos); } } return hr; } HRESULT WindowLayout::InsertChildWindow(IWindow* childWindow, __out unsigned int* index) { assert(index); // Add child window to vector of child windows m_childWindows.push_back(childWindow); *index = static_cast<unsigned int>(m_childWindows.size() - 1); ComPtr<IWindowMessageHandler> messageHandler; ComPtr<IWindowLayoutChild> windowLayoutChild; HRESULT hr = childWindow->GetMessageHandler(&messageHandler); if (SUCCEEDED(hr)) { hr = messageHandler.QueryInterface(&windowLayoutChild); } if (SUCCEEDED(hr)) { // Set the window layout information for this child window hr = windowLayoutChild->SetWindowLayout(this); } return hr; } HRESULT WindowLayout::Finalize() { HRESULT hr = S_OK; // Call each child window's 'Finalize' method. This allows each child window to remove any COM object dependencies // and stops the asynchronous loader threads. for (auto iter = m_childWindows.begin(); iter < m_childWindows.end(); iter++) { // Retrieve the message handler ComPtr<IWindowMessageHandler> handler; hr = (*iter)->GetMessageHandler(&handler); if (FAILED(hr)) { continue; } ComPtr<IWindowLayoutChild> child; hr = handler.QueryInterface(&child); if (FAILED(hr)) { continue; } hr = child->Finalize(); } return hr; }
25.869565
118
0.588609
alonmm
afa03a142d245a57c4963fd03c8a7117d116f404
9,084
cpp
C++
Source/Engine/Core/RHI/D3D12/D3D12DescriptorHeap.cpp
flygod1159/Kaguya
47dbb3940110ed490d0b70eed31383cfc82bc8df
[ "MIT" ]
1
2022-01-13T16:32:40.000Z
2022-01-13T16:32:40.000Z
Source/Engine/Core/RHI/D3D12/D3D12DescriptorHeap.cpp
flygod1159/Kaguya
47dbb3940110ed490d0b70eed31383cfc82bc8df
[ "MIT" ]
null
null
null
Source/Engine/Core/RHI/D3D12/D3D12DescriptorHeap.cpp
flygod1159/Kaguya
47dbb3940110ed490d0b70eed31383cfc82bc8df
[ "MIT" ]
null
null
null
#include "D3D12DescriptorHeap.h" #include "D3D12LinkedDevice.h" D3D12DescriptorHeap::D3D12DescriptorHeap( D3D12LinkedDevice* Parent, D3D12_DESCRIPTOR_HEAP_TYPE Type, UINT NumDescriptors) : D3D12LinkedDeviceChild(Parent) , DescriptorHeap(InitializeDescriptorHeap(Type, NumDescriptors)) , Desc(DescriptorHeap->GetDesc()) , CpuBaseAddress(DescriptorHeap->GetCPUDescriptorHandleForHeapStart()) , GpuBaseAddress(DescriptorHeap->GetGPUDescriptorHandleForHeapStart()) , DescriptorSize(Parent->GetParentDevice()->GetSizeOfDescriptor(Type)) { } void D3D12DescriptorHeap::Allocate( D3D12_CPU_DESCRIPTOR_HANDLE& CpuDescriptorHandle, D3D12_GPU_DESCRIPTOR_HANDLE& GpuDescriptorHandle, UINT& Index) { MutexGuard Guard(Mutex); Index = static_cast<UINT>(IndexPool.Allocate()); CpuDescriptorHandle = this->GetCpuDescriptorHandle(Index); GpuDescriptorHandle = this->GetGpuDescriptorHandle(Index); } void D3D12DescriptorHeap::Release(UINT Index) { MutexGuard Guard(Mutex); IndexPool.Release(static_cast<size_t>(Index)); } D3D12_CPU_DESCRIPTOR_HANDLE D3D12DescriptorHeap::GetCpuDescriptorHandle(UINT Index) const noexcept { return CD3DX12_CPU_DESCRIPTOR_HANDLE(CpuBaseAddress, static_cast<INT>(Index), DescriptorSize); } D3D12_GPU_DESCRIPTOR_HANDLE D3D12DescriptorHeap::GetGpuDescriptorHandle(UINT Index) const noexcept { return CD3DX12_GPU_DESCRIPTOR_HANDLE(GpuBaseAddress, static_cast<INT>(Index), DescriptorSize); } Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> D3D12DescriptorHeap::InitializeDescriptorHeap( D3D12_DESCRIPTOR_HEAP_TYPE Type, UINT NumDescriptors) { Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> DescriptorHeap; D3D12_DESCRIPTOR_HEAP_DESC Desc = {}; Desc.Type = Type; Desc.NumDescriptors = NumDescriptors; Desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; Desc.NodeMask = 0; VERIFY_D3D12_API(Parent->GetDevice()->CreateDescriptorHeap( &Desc, IID_PPV_ARGS(&DescriptorHeap))); return DescriptorHeap; } D3D12DescriptorArray::D3D12DescriptorArray( D3D12DescriptorPage* Parent, D3D12_CPU_DESCRIPTOR_HANDLE CpuDescriptorHandle, UINT Offset, UINT NumDescriptors) noexcept : Parent(Parent) , CpuDescriptorHandle(CpuDescriptorHandle) , Offset(Offset) , NumDescriptors(NumDescriptors) { } D3D12DescriptorArray::D3D12DescriptorArray(D3D12DescriptorArray&& D3D12DescriptorArray) noexcept : Parent(std::exchange(D3D12DescriptorArray.Parent, {})) , CpuDescriptorHandle(std::exchange(D3D12DescriptorArray.CpuDescriptorHandle, {})) , Offset(std::exchange(D3D12DescriptorArray.Offset, {})) , NumDescriptors(std::exchange(D3D12DescriptorArray.NumDescriptors, {})) { } D3D12DescriptorArray& D3D12DescriptorArray::operator=(D3D12DescriptorArray&& D3D12DescriptorArray) noexcept { if (this == &D3D12DescriptorArray) { return *this; } // Release any descriptors if we have any InternalDestruct(); Parent = std::exchange(D3D12DescriptorArray.Parent, {}); CpuDescriptorHandle = std::exchange(D3D12DescriptorArray.CpuDescriptorHandle, {}); Offset = std::exchange(D3D12DescriptorArray.Offset, {}); NumDescriptors = std::exchange(D3D12DescriptorArray.NumDescriptors, {}); return *this; } D3D12DescriptorArray::~D3D12DescriptorArray() { InternalDestruct(); } D3D12_CPU_DESCRIPTOR_HANDLE D3D12DescriptorArray::operator[](UINT Index) const noexcept { assert(Index < NumDescriptors); return CD3DX12_CPU_DESCRIPTOR_HANDLE(CpuDescriptorHandle, static_cast<INT>(Index), Parent->GetDescriptorSize()); } void D3D12DescriptorArray::InternalDestruct() { if (IsValid()) { Parent->Release(std::move(*this)); Parent = nullptr; CpuDescriptorHandle = {}; Offset = 0; NumDescriptors = 0; } } D3D12DescriptorPage::D3D12DescriptorPage( D3D12LinkedDevice* Parent, D3D12_DESCRIPTOR_HEAP_TYPE Type, UINT NumDescriptors) : D3D12LinkedDeviceChild(Parent) , DescriptorHeap(InitializeDescriptorHeap(Type, NumDescriptors)) , Desc(DescriptorHeap->GetDesc()) , CpuBaseAddress(DescriptorHeap->GetCPUDescriptorHandleForHeapStart()) , DescriptorSize(Parent->GetParentDevice()->GetSizeOfDescriptor(Type)) { AllocateFreeBlock(0, NumDescriptors); } std::optional<D3D12DescriptorArray> D3D12DescriptorPage::Allocate(UINT NumDescriptors) { MutexGuard Guard(Mutex); if (NumDescriptors > Desc.NumDescriptors) { return std::nullopt; } // Get a block in the pool that is large enough to satisfy the required descriptor, // The function returns an iterator pointing to the key in the map container which is equivalent to k passed in the // parameter. In case k is not present in the map container, the function returns an iterator pointing to the // immediate next element which is just greater than k. auto Iter = SizePool.lower_bound(NumDescriptors); if (Iter == SizePool.end()) { return std::nullopt; } // Query all information about this available block SizeType Size = Iter->first; FreeBlocksByOffsetPoolIter OffsetIter(Iter->second); OffsetType Offset = OffsetIter.Iterator->first; // Remove the block from the pool SizePool.erase(Size); FreeBlocksByOffsetPool.erase(OffsetIter.Iterator); // Allocate a available block OffsetType NewOffset = Offset + NumDescriptors; SizeType NewSize = Size - NumDescriptors; // Return left over block to the pool if (NewSize > 0) { AllocateFreeBlock(NewOffset, NewSize); } Desc.NumDescriptors -= NumDescriptors; return D3D12DescriptorArray( this, CD3DX12_CPU_DESCRIPTOR_HANDLE(CpuBaseAddress, static_cast<INT>(Offset), DescriptorSize), Offset, NumDescriptors); } void D3D12DescriptorPage::Release(D3D12DescriptorArray&& DescriptorArray) { MutexGuard Guard(Mutex); FreeBlock(DescriptorArray.GetOffset(), DescriptorArray.GetNumDescriptors()); } Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> D3D12DescriptorPage::InitializeDescriptorHeap( D3D12_DESCRIPTOR_HEAP_TYPE Type, UINT NumDescriptors) { Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> DescriptorHeap; D3D12_DESCRIPTOR_HEAP_DESC Desc = {}; Desc.Type = Type; Desc.NumDescriptors = NumDescriptors; Desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; Desc.NodeMask = 0; VERIFY_D3D12_API(Parent->GetDevice()->CreateDescriptorHeap( &Desc, IID_PPV_ARGS(&DescriptorHeap))); return DescriptorHeap; } void D3D12DescriptorPage::AllocateFreeBlock(OffsetType Offset, SizeType Size) { auto OffsetElement = FreeBlocksByOffsetPool.emplace(Offset, SizePool.begin()); auto SizeElement = SizePool.emplace(Size, OffsetElement.first); OffsetElement.first->second.Iterator = SizeElement; } void D3D12DescriptorPage::FreeBlock(OffsetType Offset, SizeType Size) { // upper_bound returns end if it there is no next block auto NextIter = FreeBlocksByOffsetPool.upper_bound(Offset); auto PrevIter = NextIter; if (PrevIter != FreeBlocksByOffsetPool.begin()) { // there is no free block in front of this one --PrevIter; } else { PrevIter = FreeBlocksByOffsetPool.end(); } Desc.NumDescriptors += Size; if (PrevIter != FreeBlocksByOffsetPool.end()) { OffsetType PrevOffset = PrevIter->first; SizeType PrevSize = PrevIter->second.Iterator->first; if (Offset == PrevOffset + PrevSize) { // Merge previous and current block // PrevBlock.Offset CurrentBlock.Offset // | | // |<--------PrevBlock.Size-------->|<--------CurrentBlock.Size-------->| Offset = PrevOffset; Size += PrevSize; // Remove this block now that it has been merged // Erase order needs to be size the offset, because offset iter still references element in the offset pool SizePool.erase(PrevIter->second.Iterator); FreeBlocksByOffsetPool.erase(PrevOffset); } } if (NextIter != FreeBlocksByOffsetPool.end()) { OffsetType NextOffset = NextIter->first; SizeType NextSize = NextIter->second.Iterator->first; if (Offset + Size == NextOffset) { // Merge current and next block // CurrentBlock.Offset NextBlock.Offset // | | // |<--------CurrentBlock.Size-------->|<--------NextBlock.Size--------> // only increase the size of the block Size += NextSize; // Remove this block now that it has been merged // Erase order needs to be size the offset, because offset iter still references element in the offset pool SizePool.erase(NextIter->second.Iterator); FreeBlocksByOffsetPool.erase(NextOffset); } } AllocateFreeBlock(Offset, Size); } D3D12DescriptorArray D3D12DescriptorAllocator::Allocate(UINT NumDescriptors) { D3D12DescriptorArray DescriptorArray; for (auto& Page : DescriptorPages) { auto OptDescriptorArray = Page->Allocate(NumDescriptors); if (OptDescriptorArray.has_value()) { DescriptorArray = std::move(OptDescriptorArray.value()); break; } } if (!DescriptorArray.IsValid()) { auto& NewPage = DescriptorPages.emplace_back(std::make_unique<D3D12DescriptorPage>(GetParentLinkedDevice(), Type, PageSize)); DescriptorArray = NewPage->Allocate(NumDescriptors).value(); } return DescriptorArray; }
31.003413
127
0.753853
flygod1159
afa190c8dd26326b593ca248739b5016b5e882c9
10,706
cpp
C++
src/testindex.cpp
maciejwlodek/blend
00c892363876692c5370def0e37a106ad5f7b07e
[ "BSD-3-Clause" ]
null
null
null
src/testindex.cpp
maciejwlodek/blend
00c892363876692c5370def0e37a106ad5f7b07e
[ "BSD-3-Clause" ]
null
null
null
src/testindex.cpp
maciejwlodek/blend
00c892363876692c5370def0e37a106ad5f7b07e
[ "BSD-3-Clause" ]
1
2019-01-24T16:14:56.000Z
2019-01-24T16:14:56.000Z
// testindex.cpp #include "pointless.hh" #include "testindex.hh" #include "normalise.hh" #include "normaliseunmerge.hh" #include "average.hh" #include "getCCsigfac.hh" namespace scala { //-------------------------------------------------------------- std::vector<ReindexScore> TestIndexUnmerged (hkl_merged_list& RefList, hkl_unmerge_list& hkl_list, const std::vector<ReindexOp>& ReindexList, const GlobalControls& GC, const all_controls& controls, phaser_io::Output& output) // Test unmerged data for alternative // indexing schemes against reference dataset (HKLREF) // MODE INDEX { std::vector<ReindexScore> ReindexScoreList(ReindexList.begin(),ReindexList.end()); int Nalt = ReindexScoreList.size(); // * std::vector<IsigI> IsigRef(Nalt); IsigI IsigRef; // int PrintLevel = 0; ResoRange RRange = RefList.ResRange(); output.logTab(0,LOGFILE, "\n>>>> Normalising reference dataset"); Normalise NormResRef = SetNormaliseMerged(RefList, -1.0, RRange); output.logTabPrintf(0,LOGFILE, "\nLog(<I>) fit for intensity normalisation: B (slope) %10.2f\n", NormResRef.Bcorr()); output.logTab(0,LOGFILE, "\n>>>> Normalising test dataset"); Normalise NormResTest = scala::NormaliseUnmerge(hkl_list, GC, controls, true, output); output.logTabPrintf(0,LOGFILE, "\nLog(<I>) fit for intensity normalisation: B (slope) %10.2f\n", NormResTest.Bcorr()); // Set mininum resolution range for test list ResoRange minrange = RefList.ResRange().MinRange(hkl_list.ResLimRange()); hkl_list.SetResoLimits(minrange.ResLow(), minrange.ResHigh()); reflection this_refl; observation this_obs; IsigI Isig; int isym; hkl_symmetry RefSymm = RefList.symmetry(); hkl_list.rewind(); // loop all reflections from test list while (hkl_list.next_reflection(this_refl) >= 0) { /* --- Using average test data: not appropriate if symmetry is wrong! Hkl hkl = this_refl.hkl(); // fetch equivalent IsigI for possible hkl's from reference list for (int i=0;i<Nalt;i++) { IsigRef[i] = RefList.Isig(RefSymm.put_in_asu (hkl.change_basis(ReindexScoreList[i]),isym)); } // Average unmerged I's average_I(this_refl, Isig.I(), Isig.sigI()); float sSqr = this_refl.invresolsq(); for (int i=0;i<Nalt;i++) // add pairs of test, reference into scores { if (IsigRef[i].sigI() > 0.001) { ReindexScoreList[i].addDsetIstats(Isig, IsigRef[i], NormResTest, NormResRef, sSqr); } }*/ ///*---- Unaveraged alternative float sSqr = this_refl.invresolsq(); int Nobs = this_refl.num_observations(); for (int lobs = 0; lobs < Nobs; lobs++) { this_obs = this_refl.get_observation(lobs); if (this_obs.IsAccepted()) { Hkl hkl = this_obs.hkl_original(); IsigI Isig = this_obs.I_sigI(); // fetch equivalent IsigI for possible hkl's from reference list for (int i=0;i<Nalt;i++) { IsigRef = RefList.Isig(RefSymm.put_in_asu (hkl.change_basis(ReindexScoreList[i]),isym)); if (IsigRef.sigI() > 0.001) { // add pairs of test, reference into scores ReindexScoreList[i].addDsetIstats(Isig, IsigRef, NormResTest, NormResRef, sSqr); } } } } // ----*/ } // update ReindexScoreList to add likelihood GetTestUnmergedSignificance(hkl_list, NormResTest, ReindexScoreList, output); // Restore resolution limits which were reset by normalisation hkl_list.ResetResoLimits(); std::sort(ReindexScoreList.begin(), ReindexScoreList.end()); return ReindexScoreList; } //-------------------------------------------------------------- std::vector<ReindexScore> TestIndexMerged (hkl_merged_list& RefList, const hkl_merged_list& TestList, const std::vector<ReindexOp>& ReindexList, const GlobalControls& GC, phaser_io::Output& output) // Test merged data for alternative // indexing schemes against reference dataset (HKLREF) // MODE INDEX { std::vector<ReindexScore> ReindexScoreList(ReindexList.begin(),ReindexList.end()); int Nalt = ReindexScoreList.size(); std::vector<IsigI> IsigRef(Nalt); // int PrintLevel = 0; ResoRange RRange = RefList.ResRange(); output.logTab(0,LOGFILE, "\n>>>> Normalising reference dataset"); Normalise NormResRef = SetNormaliseMerged(RefList, -1.0, RRange); output.logTabPrintf(0,LOGFILE, "\nLog(<I>) fit for intensity normalisation: B (slope) %10.2f\n", NormResRef.Bcorr()); output.logTab(0,LOGFILE, "\n>>>> Normalising test dataset"); Normalise NormResTest = SetNormaliseMerged(TestList, GC.GetMinIsig(), RRange); output.logTabPrintf(0,LOGFILE, "\nLog(<I>) fit for intensity normalisation: B (slope) %10.2f\n", NormResTest.Bcorr()); // loop all reflections in TestList TestList.start(); IsigI Isig, Is; int isym; hkl_symmetry RefSymm = RefList.symmetry(); bool OK; while (TestList.next(Isig)) { if ( ! Isig.missing()) { Hkl hkl = TestList.hkl(); float sSqr = TestList.invresolsq(); IsigI Is1 = NormResTest.applyAvg(Isig, sSqr); if (NormResTest.NotTooLarge(Is1)) { // fetch equivalent IsigI for possible hkl's from reference list OK = true; for (int i=0;i<Nalt;i++) { Is = RefList.Isig(RefSymm.put_in_asu (hkl.change_basis(ReindexScoreList[i]),isym)); if (Is.sigI() < 0.001) { OK = false; } else { IsigRef[i] = NormResRef.applyAvg(Is, sSqr); if (!NormResRef.NotTooLarge(IsigRef[i])) { OK = false; } } } if (OK) { for (int i=0;i<Nalt;i++) { ReindexScoreList[i].addDsetIstats(Is1, IsigRef[i]); } } } } } std::sort(ReindexScoreList.begin(), ReindexScoreList.end()); return ReindexScoreList; } //-------------------------------------------------------------- std::vector<ReindexScore> TestIndexBothUnmerged (hkl_unmerge_list& ref_list, hkl_unmerge_list& test_list, const std::vector<ReindexOp>& ReindexList, const GlobalControls& GC, const all_controls& controls, const int& PrintLevel, phaser_io::Output& output) // Test unmerged data against unmerged reference dataset // for alternative indexing schemes { std::vector<ReindexScore> ReindexScoreList(ReindexList.begin(),ReindexList.end()); int Nalt = ReindexScoreList.size(); // * std::vector<IsigI> IsigRef(Nalt); IsigI IsigRef; ResoRange RRange = ref_list.ResRange(); bool verbose = false; if (PrintLevel > 0) verbose = true; // Note that after the following normalise operations, both reflection lists // have resolution limits set // These are reset at end of this procedure (ResetResoLimits) Normalise NormResRef = NormaliseUnmerge(ref_list, GC, controls, verbose, output); Normalise NormResTest = NormaliseUnmerge(test_list, GC, controls, verbose, output); // Set mininum resolution range for test list ResoRange minrange = ref_list.ResLimRange().MinRange(test_list.ResLimRange()); test_list.SetResoLimits(minrange.ResLow(), minrange.ResHigh()); reflection this_refl, ref_refl; observation this_obs; IsigI Isig; IsigI Isig0(0.0,0.0); int idx_refl; int isym; hkl_symmetry RefSymm = ref_list.symmetry(); test_list.rewind(); // loop all reflections from test list // Note that we assume that the symmetry of the reference list is correct, // but we cannot assume that the test list symmetry is, so don't merge test list Is while (test_list.next_reflection(this_refl) >= 0) { int Nobs = this_refl.num_observations(); float sSqr = this_refl.invresolsq(); for (int lobs = 0; lobs < Nobs; lobs++) { this_obs = this_refl.get_observation(lobs); if (this_obs.IsAccepted()) { Hkl hkl = this_obs.hkl_original(); IsigI Isig = this_obs.I_sigI(); // fetch equivalent IsigI for possible hkl's from reference list for (int i=0;i<Nalt;i++) { idx_refl = ref_list.get_reflection(ref_refl, RefSymm.put_in_asu (hkl.change_basis(ReindexScoreList[i]), isym)); if (idx_refl >= 0) { IsigRef = average_Is(ref_refl); } else { IsigRef = Isig0; } // add pairs of test, reference into scores if (IsigRef.sigI() > 0.001) { ReindexScoreList[i].addDsetIstats(Isig, IsigRef, NormResTest, NormResRef, sSqr); } } } } } // update ReindexScoreList to add likelihood GetTestUnmergedSignificance(test_list, NormResTest, ReindexScoreList, output); // Restore resolution limits which were reset by normalisation ref_list.ResetResoLimits(); test_list.ResetResoLimits(); std::sort(ReindexScoreList.begin(), ReindexScoreList.end()); return ReindexScoreList; } //-------------------------------------------------------------- void GetTestUnmergedSignificance(hkl_unmerge_list& test_list, const Normalise& NormRes, std::vector<ReindexScore>& ReindexScoreList, phaser_io::Output& output) // Update ReindexScoreList with significance score (likelihood) { // ************************************************************ // *** Get significance of scores (cf testlauegroup) // Get factor for sd(CC) ResoRange ResRange = test_list.ResRange(); // Make list of unrelated pairs double ECC0; // estimated E(CC) double CCsigFac = GetCCsigFac(test_list, ResRange, NormRes, ECC0, false, output); //^ // std::cout << "ECC0, CCsigFac " << ECC0 <<" "<< CCsigFac << "\n"; //^- // Make list of CC-significance for each reindex op from scores list std::vector<scala::SetScores> scorelist; for (size_t i=0;i<ReindexScoreList.size();++i) { scorelist.push_back(ReindexScoreList[i]); //^ // std::cout << "ReindexScoreList " << i << " " << ReindexScoreList[i].OverallCC().result().val <<"\n"; //^- } std::vector<SCsignificance> CCsig = CCsum(scorelist); // update CCsig with sd(CC) etc ScoreSig<correl_coeff>(CCsigFac, ECC0, CCsig); // Store probabilities back into ReindexScoreList ASSERT (ReindexScoreList.size() == CCsig.size()); float totprob = 0.0; // total likelihood = 1.0 for (size_t i=0;i<ReindexScoreList.size();++i) { // std::cout << "Lkl " << CCsig[i].Likelihood() <<"\n"; //^ totprob += CCsig[i].Likelihood(); } for (size_t i=0;i<ReindexScoreList.size();++i) { ReindexScoreList[i].SetLikelihood(CCsig[i].Likelihood()/totprob); } } //-------------------------------------------------------------- } // namespace scala
36.047138
114
0.638427
maciejwlodek
afaee8716123bfc54d496c4999db57418c7dea4c
3,137
cpp
C++
Source/managementBS.cpp
L0mion/Makes-a-Click
c7f53a53ea3a58da027ea5f00176352edb914718
[ "MIT" ]
1
2016-04-28T06:24:15.000Z
2016-04-28T06:24:15.000Z
Source/managementBS.cpp
L0mion/Makes-a-Click
c7f53a53ea3a58da027ea5f00176352edb914718
[ "MIT" ]
null
null
null
Source/managementBS.cpp
L0mion/Makes-a-Click
c7f53a53ea3a58da027ea5f00176352edb914718
[ "MIT" ]
null
null
null
#include "managementBS.h" #include "utility.h" ManagementBS::ManagementBS() { for( int bsIdx=0; bsIdx<BSTypes_CNT; bsIdx++ ) { m_blendStates[bsIdx] = NULL; } } ManagementBS::~ManagementBS() { for( int bsIdx=0; bsIdx<BSTypes_CNT; bsIdx++ ) { SAFE_RELEASE( m_blendStates[bsIdx] ); } } void ManagementBS::setBlendState(ID3D11DeviceContext* p_devcon, BSTypes p_type) { FLOAT blendFactor[4] = {0.0f, 0.0f, 0.0f, 0.0f}; UINT sampleMask = 0xffffffff; p_devcon->OMSetBlendState( m_blendStates[p_type], blendFactor, sampleMask ); } HRESULT ManagementBS::init(ID3D11Device* p_device) { HRESULT hr = S_OK; hr = initBSDefault(p_device); if(SUCCEEDED(hr)) hr = initBSTransparency(p_device); if(SUCCEEDED(hr)) hr = initBSAdditive(p_device); return hr; } HRESULT ManagementBS::initBSDefault(ID3D11Device* p_device) { HRESULT hr = S_OK; D3D11_BLEND_DESC blendDesc; ZeroMemory(&blendDesc, sizeof(blendDesc)); blendDesc.RenderTarget[0].BlendEnable = FALSE; blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; hr = p_device->CreateBlendState(&blendDesc, &m_blendStates[BSTypes_DEFAULT]); if(FAILED(hr)) MessageBox(NULL, L"ManagmenetBS::initBSDefault() | CreateBlendState() | Failed", L"Blend State Default", MB_OK | MB_ICONEXCLAMATION); return hr; } HRESULT ManagementBS::initBSTransparency(ID3D11Device* p_device) { HRESULT hr = S_OK; D3D11_BLEND_DESC blendDesc; ZeroMemory(&blendDesc, sizeof(blendDesc)); blendDesc.RenderTarget[0].BlendEnable = true; blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget[0].RenderTargetWriteMask = 0x0f; hr = p_device->CreateBlendState(&blendDesc, &m_blendStates[BSTypes_TRANSPARENCY]); if(FAILED(hr)) MessageBox(NULL, L"ManagmenetBS::initBSTransparency() | CreateBlendState() | Failed", L"Blend State Transparency", MB_OK | MB_ICONEXCLAMATION); return hr; } HRESULT ManagementBS::initBSAdditive(ID3D11Device* p_device) { HRESULT hr = S_OK; D3D11_BLEND_DESC blendDesc; ZeroMemory(&blendDesc, sizeof(blendDesc)); blendDesc.RenderTarget[0].BlendEnable = true; blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_ONE; blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA; blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE; blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; hr = p_device->CreateBlendState(&blendDesc, &m_blendStates[BSTypes_ADDITIVE]); if(FAILED(hr)) MessageBox(NULL, L"ManagmenetBS::initBSAdditive() | CreateBlendState() | Failed", L"Blend State Additive", MB_OK | MB_ICONEXCLAMATION); return hr; }
30.163462
145
0.768569
L0mion
afb099f57cd2be83f6b9d147a38492a729f9a1d6
464
hpp
C++
src/neo/sqlite3/blob.hpp
vector-of-bool/neo-sqlite3
149b762f983126e26502a9625659706eab0dcc25
[ "BSL-1.0" ]
4
2019-11-13T09:11:03.000Z
2022-03-11T01:00:45.000Z
src/neo/sqlite3/blob.hpp
vector-of-bool/neo-sqlite3
149b762f983126e26502a9625659706eab0dcc25
[ "BSL-1.0" ]
null
null
null
src/neo/sqlite3/blob.hpp
vector-of-bool/neo-sqlite3
149b762f983126e26502a9625659706eab0dcc25
[ "BSL-1.0" ]
null
null
null
#pragma once #include <utility> namespace neo::sqlite3 { class connection; class blob { friend class connection_ref; void* _ptr = nullptr; struct from_raw {}; blob(from_raw, void* ptr) : _ptr(ptr) {} public: ~blob(); blob(blob&& o) : _ptr(std::exchange(o._ptr, nullptr)) {} blob& operator=(blob&& other) noexcept { std::swap(_ptr, other._ptr); return *this; } }; } // namespace neo::sqlite3
16
49
0.584052
vector-of-bool
afb65b2f7cf6ceb50ce34e77ed2aa092768ea9ac
45,434
cpp
C++
src/Compiler.cpp
mita4829/Pine
0269d466eaf3b228745def5cec7796d257aa90a1
[ "MIT" ]
1
2018-07-07T21:16:00.000Z
2018-07-07T21:16:00.000Z
src/Compiler.cpp
mita4829/Pine
0269d466eaf3b228745def5cec7796d257aa90a1
[ "MIT" ]
1
2018-07-07T17:14:58.000Z
2018-07-08T18:17:14.000Z
src/Compiler.cpp
mita4829/Pine
0269d466eaf3b228745def5cec7796d257aa90a1
[ "MIT" ]
null
null
null
#include "Compiler.hpp" CompilerResult EmptyResult; string requestTmpVarName(){ LOG("Compiler:requestTmpVarName"); static Int32 id = -1; id += 1; return "var" + to_string(id); } Int32 align32ByteStack(Int32 varCount){ const Int32 ALIGNMENT = 32; Int32 byteCount = varCount * ARCH64; Int32 next32Factor = (byteCount + ALIGNMENT) / ALIGNMENT; Int32 stackSize = next32Factor * ALIGNMENT; return stackSize; } Int32 requestStringID(){ static Int32 id = -1; id += 1; return id; } Int32 requestFloatID(){ static Int32 id = -1; id += 1; return id; } Int32 requestJumpID(){ static Int32 id = -1; id += 1; return id; } Int32 requestShortID(){ static Int32 id = -1; id += 1; return id; } /* Returns the type of the expr. If it's a VAR type, cast to VAR can get its type. */ Int32 Compiler::getImplicitType(Object* expr){ LOG("Compiler:getImplicitType"); LOG(" expr: 0x"+AddressOf(&expr)); if (expr == nullptr) { return NIT; } Int32 Type = expr->getExplicitType(); if(Type == VAR){ Var* v = Safe_Cast<Var*>(expr); return v->getVarType(); } else if(Type == INDEX){ Index* i = Safe_Cast<Index*>(expr); if (isPrimative(i->getElementType())) { return i->getElementType(); } string arrayName = i->getArrayName(); CompileBinding binding = getBindings(arrayName); return getImplicitType(binding.obj); } else if(Type == BINARY){ Binary* b = Safe_Cast<Binary*>(expr); return b->typeContext.implicitType; } else if(Type == ARRAY){ Array* a = Safe_Cast<Array*>(expr); vector<Object*> array = a->getArray(); return getImplicitType(array.size() > 1 ? array[1] : nullptr); } return Type; } bool isValue(Int32 expr_type){ LOG("Compiler:isValue"); LOG(" expr_type: "+to_string(expr_type)); return (expr_type == INTEGER || expr_type == VAR || expr_type == FLOAT || expr_type == DOUBLE || expr_type == BOOLEAN || expr_type == STRING || expr_type == INDEX); } Compiler::Compiler(){ LOG("Compiler:Compiler"); pushNewFlatStack(); pushNewStackFrame(); } Compiler::Compiler(vector<Object*> _ast) : Compiler() { LOG("Compiler:Compiler"); LOG(" _ast: 0x"+AddressOf(&_ast)); LOG(" _ast.size():"+to_string(_ast.size())); ast = _ast; for(const auto& tree : ast){ flatten(tree); } flatAst = popFlatStack(); LOG(" flatAst.size():"+to_string(flatAst.size())); for(const auto& tree : flatAst){ compile(tree); } LOG(" Completed compile"); } Compiler::~Compiler(){ LOG("Compiler:~Compiler"); while(flattenStmt.size() != 0){ vector<Object*>* frame = &(flattenStmt.top()); for(auto& stmt : *frame){ if(stmt != nullptr){ deleteObject(stmt); stmt = nullptr; } } flattenStmt.pop(); } LOG("Compiler: Deleting flatAst"); for(auto& tree : flatAst){ if(tree != nullptr){ deleteObject(tree); tree = nullptr; } } LOG("Compiler: Deleting ast"); for(auto& tree : ast){ if(tree != nullptr){ deleteObject(tree); tree = nullptr; } } } Object* Compiler::flatten(Object* expr){ LOG("Compiler:flatten"); LOG(" expr: 0x"+AddressOf(&expr)); Int32 Type = expr->getExplicitType(); LOG(" Type: "+getTypeName(Type)); /* Primatives */ /* We cannot just return the primative expr/node, as the original AST holds a reference to these nodes. Otherwise, freeing the memory of the original AST and the flatAST will cause a double free assert. */ if(Type == VAR || Type == INTEGER || Type == FLOAT || Type == DOUBLE || Type == STRING || Type == BOOLEAN){ return expr->clone(); } /* Unary */ else if(Type == UNARY){ Unary* u = Safe_Cast<Unary*>(expr); Object* rval = flatten(u->getVal()); string lval = requestTmpVarName(); TypeContext context; context.explicitType = rval->getExplicitType(); context.implicitType = getImplicitType(rval);; Let* l = new Let(lval, context, new Unary(rval, u->getOperation())); addFlatStmtToStack(l); return new Var(lval, context.implicitType); } /* Let */ else if(Type == LET){ Let* l = Safe_Cast<Let*>(expr); Object* rval = flatten(l->getVal()); TypeContext context; context.explicitType = rval->getExplicitType(); context.implicitType = getImplicitType(rval); Let* fl = new Let(l->getName(), context, rval); addFlatStmtToStack(fl); return fl; } /* Assign */ else if(Type == ASSIGN){ Assign* a = Safe_Cast<Assign*>(expr); Object* f = flatten(a->getVal()); Assign* fa = new Assign(a->getVar(), f); addFlatStmtToStack(fa); return fa; } /* Binary */ else if(Type == BINARY){ Binary* b = Safe_Cast<Binary*>(expr); Object* fl = flatten(b->getLeft()); Object* fr = flatten(b->getRight()); Int32 lt = fl->getExplicitType(); Int32 rt = fr->getExplicitType(); Int32 operation = b->getOperation(); string name = requestTmpVarName(); while(isValue(fl->getExplicitType()) == false){ fl = flatten(fl); } while(isValue(fr->getExplicitType()) == false){ fr = flatten(fr); } /* We let the type of the binary expr be the evaluated left operand. */ TypeContext context; context.explicitType = fl->getExplicitType(); context.implicitType = getImplicitType(fl); Let* l = new Let(name, context, new Binary(operation, fl, fr)); addFlatStmtToStack(l); return new Var(name, context.implicitType); } /* Function */ else if(Type == FUNCTION){ Function* f = Safe_Cast<Function*>(expr); Seq* flatBody = Safe_Cast<Seq*>(flatten(f->getBody())); /* Func body only contains non-const code to remove dead instructions */ addFlatStmtToStack(new Function(f->getName(), f->getArgv(), flatBody, f->getReturnType())); return nullptr; } /* Print */ else if(Type == PRINT){ Print* p = Safe_Cast<Print*>(expr); Object* f_print = flatten(p->getVal()); addFlatStmtToStack(new Print(f_print)); return nullptr; } /* Seq */ else if(Type == SEQ){ Seq* s = Safe_Cast<Seq*>(expr); /* Expand function stack */ pushNewFlatStack(); vector<Object*> body_stmt = s->getStatements(); for(const auto& stmt : body_stmt){ flatten(stmt); } vector<Object*> flatBody = popFlatStack(); return new Seq(flatBody); } /* If */ else if(Type == IF){ If* ifExpr = Safe_Cast<If*>(expr); vector<tuple<Object*, Seq*>> ifStmt = ifExpr->getIfStmt(); vector<tuple<Object*, Seq*>> flatStmt; Object* elseBody = nullptr; for(const auto& stmt : ifStmt){ tuple<Object*, Seq*> flatIfStmt = make_tuple(flatten(get<0>(stmt)), Safe_Cast<Seq*>(flatten(get<1>(stmt)))); flatStmt.push_back(flatIfStmt); } elseBody = ifExpr->getElse(); elseBody = flatten(elseBody); addFlatStmtToStack(new If(flatStmt, Safe_Cast<Seq*>(elseBody))); return nullptr; } /*Compare*/ else if(Type == COMPARE){ Compare* c = Safe_Cast<Compare*>(expr); Int32 operation = c->getOperation(); Object* l = flatten(c->getLeft()); Object* r = flatten(c->getRight()); string name = requestTmpVarName(); TypeContext context; context.explicitType = BOOLEAN; Let* fl = new Let(name, context, new Compare(operation, l, r)); addFlatStmtToStack(fl); return new Var(name, BOOLEAN); } /*Logical*/ else if(Type == LOGICAL){ Logical* l = Safe_Cast<Logical*>(expr); Int32 operation = l->getOperation(); Object* lf = flatten(l->getLeft()); Object* rf = flatten(l->getRight()); string name = requestTmpVarName(); TypeContext context; context.explicitType = BOOLEAN; Let* fl = new Let(name, context, new Logical(operation, lf, rf)); addFlatStmtToStack(fl); return new Var(name, BOOLEAN); } /*For*/ else if(Type == FOR){ For* f = Safe_Cast<For*>(expr); Object* f_decl = (f->getDeclare()); Object* f_cond = (f->getCondition()); Object* f_incl = (f->getIncl()); Seq* f_body = Safe_Cast<Seq*>(flatten(f->getBody())); addFlatStmtToStack(new For(f_decl, f_cond, f_incl, f_body)); return nullptr; } /* While */ else if(Type == WHILE){ While* w = Safe_Cast<While*>(expr); Object* cond = w->getCondition(); Seq* body = (Seq*)flatten(w->getBody()); addFlatStmtToStack(new While(cond, body)); return nullptr; } /* Array */ else if(Type == ARRAY){ Array* a = Safe_Cast<Array*>(expr); vector<Object*> array = a->getArray(); vector<Object*> flatArray; for(const auto& element : array){ flatArray.push_back(flatten(element)); } Array* flatArrayObj = new Array(flatArray, a->getLength(), a->getElementType()); flatArrayObj->typeContext.arrayDepth = a->typeContext.arrayDepth; flatArrayObj->typeContext.arrayPrimativeElementType = a->typeContext.arrayPrimativeElementType; return flatArrayObj; } /* Index */ else if(Type == INDEX){ Index* i = Safe_Cast<Index*>(expr); vector<Object*> indices = i->getIndex(); vector<Object*> flatIndices; for (const auto& i : indices) { flatIndices.push_back(flatten(i)); } string name = requestTmpVarName(); Index* flat = new Index(i->getArrayName(), flatIndices, i->getElementType()); return flat; } RaisePineWarning("Flatten reached end of token matching ("+getTypeName(Type)+")."); return nullptr; } CompilerResult Compiler::compile(Object* expr){ LOG("Compiler:compile"); LOG(" expr: 0x"+AddressOf(&expr)); Int32 Type = expr->getExplicitType(); LOG(" Type: "+getTypeName(Type)); /* Integer */ if(Type == INTEGER){ Integer* i = Safe_Cast<Integer*>(expr); Int64 v = i->getVal(); string operand = "$"+STR(v); CompilerResult result = EmptyResult; result.resultType = INTEGER; result.data = operand; return result; } /* Float */ else if(Type == FLOAT){ class Float* f = Safe_Cast<class Float*>(expr); float val = f->getVal(); union { double f_bits; Int64 i_bits; }; f_bits = (double)val; Int32 id = requestFloatID(); string ins1 = "FLOAT_"+STR(id)+":"; string ins2 = ".quad " + STR(i_bits) + " #" + STR(f_bits); string ins4 = "movq FLOAT_"+STR(id)+"(%rip), %xmm0"; header.push_back(ins1); header.push_back(ins2); addCompileStmt(ins4); CompilerResult result = EmptyResult; result.resultType = REG; /* TODO: Update reg manager to use other SIMD registers */ result.data = "%xmm0"; return result; } /* Double */ else if(Type == DOUBLE){ class Double* d = Safe_Cast<class Double*>(expr); double val = d->getVal(); union { double d_bits; Int64 i_bits; }; d_bits = val; Int32 id = requestFloatID(); string ins1 = "DOUBLE_"+STR(id)+":"; string ins2 = ".quad " + STR(i_bits) + " #" + STR(d_bits); string ins3 = ".align " + STR(ARCH32); string ins4 = "movq DOUBLE_"+STR(id)+"(%rip), %xmm0"; header.push_back(ins1); header.push_back(ins2); header.push_back(ins3); addCompileStmt(ins4); CompilerResult result = EmptyResult; result.resultType = REG; /* TODO: Update reg manager to use other SIMD registers */ result.data = "%xmm0"; return result; } /* Var */ else if(Type == VAR){ Var* var = Safe_Cast<Var*>(expr); Int32 type = var->getVarType(); string name = var->getName(); Int32 stackLocation = retrieveStackLocation(name); string ins1 = "-"+to_string(stackLocation)+"(%rbp)"; CompilerResult result = EmptyResult; result.resultType = STACKLOC; result.stackLocation = stackLocation; result.data = "-" + STR(stackLocation) + "(%rbp)"; return result; } /* String */ else if(Type == STRING){ class String* s = Safe_Cast<class String*>(expr); string val = s->getVal(); Int32 id = requestStringID(); string ins1 = "STR_"+STR(id)+".str"; string ins2 = ".asciz " + val; header.push_back(ins1+":"); header.push_back(ins2); string ins3 = registerManager.getRegister(); string ins4 = "leaq " + ins1 + "(%rip), %"+ins3; addCompileStmt(ins4); CompilerResult result = EmptyResult; result.resultType = REG; result.data = ins3; return result; } /*Boolean*/ else if(Type == BOOLEAN){ Boolean* boolean = Safe_Cast<Boolean*>(expr); bool val = boolean->getVal(); Int32 cast = (Int32)val; string operand = "$"+STR(cast); CompilerResult result = EmptyResult; result.resultType = BOOLEAN; result.data = operand; return result; } /* Binary */ else if(Type == BINARY){ Binary* b = Safe_Cast<Binary*>(expr); Int32 operation = b->getOperation(); CompilerResult left = compile(b->getLeft()); string regleft = IntoRegister(left.data); CompilerResult right = compile(b->getRight()); string regright = IntoRegister(right.data); Int32 ltype = getImplicitType(b->getLeft()); Int32 rtype = getImplicitType(b->getRight()); if(operation == ADD){ if(ltype == INTEGER && rtype == INTEGER){ string stmt = "addq %"+regleft+", %"+regright; addCompileStmt(stmt); }else if((ltype == FLOAT && rtype == FLOAT) || (ltype == DOUBLE && rtype == DOUBLE)){ string x0 = "movq %"+regleft+", %xmm0"; string x1 = "movq %"+regright+", %xmm1"; string add = "addss %xmm0, %xmm1"; string mov = "movq %xmm1, %"+regright; addCompileStmt(x0); addCompileStmt(x1); addCompileStmt(add); addCompileStmt(mov); }else if(ltype != rtype){ RaisePineException("Binary operation + on non-matching type operands."); } }else if(operation == SUB){ if(ltype == INTEGER && rtype == INTEGER){ string stmt = "subq %"+regright+", %"+regleft; string orient = "movq %"+regleft+", %"+regright; addCompileStmt(stmt); addCompileStmt(orient); }else if((ltype == FLOAT && rtype == FLOAT) || (ltype == DOUBLE && rtype == DOUBLE)){ string x0 = "movq %"+regleft+", %xmm0"; string x1 = "movq %"+regright+", %xmm1"; string sub = "subss %xmm1, %xmm0"; string mov = "movq %xmm0, %"+regright; addCompileStmt(x0); addCompileStmt(x1); addCompileStmt(sub); addCompileStmt(mov); }else if(ltype != rtype){ RaisePineException("Binary operation - on non-matching type operands."); } }else if(operation == MUL){ if(ltype == INTEGER && rtype == INTEGER){ string stmt = "imulq %"+regleft+", %"+regright; addCompileStmt(stmt); }else if((ltype == FLOAT && rtype == FLOAT) || (ltype == DOUBLE && rtype == DOUBLE)){ string x0 = "movq %"+regleft+", %xmm0"; string x1 = "movq %"+regright+", %xmm1"; string mul = "mulss %xmm0, %xmm1"; string mov = "movq %xmm1, %"+regright; addCompileStmt(x0); addCompileStmt(x1); addCompileStmt(mul); addCompileStmt(mov); }else if(ltype != rtype){ RaisePineException("Binary operation * on non-matching type operands."); } }else if(operation == DIV){ if(ltype == INTEGER && rtype == INTEGER){ string movq = "movq %"+regleft+", %rcx"; string movq2 = "movq %"+regright+", %rax"; string movq3 = "movq %rcx, %rax"; string cqld = "cltd"; string movq4 = "movq %"+regright+", %rcx"; string stmt = "idivq %rcx"; string movq5 = "movq %rax, %"+regright; addCompileStmt(movq); addCompileStmt(movq2); addCompileStmt(movq3); addCompileStmt(cqld); addCompileStmt(movq4); addCompileStmt(stmt); addCompileStmt(movq5); }else if((ltype == FLOAT && rtype == FLOAT) || (ltype == DOUBLE && rtype == DOUBLE)){ string movq = "movq %"+regleft+", %xmm0"; string movq2 = "movq %"+regright+", %xmm1"; string stmt = "divss %xmm1, %xmm0"; string movq3 = "movq %xmm0, %"+regright; addCompileStmt(movq); addCompileStmt(movq2); addCompileStmt(stmt); addCompileStmt(movq3); }else if(ltype != rtype){ RaisePineException("Binary operation / on non-matching type operands."); } } else if(operation == MOD){ if(ltype == INTEGER && rtype == INTEGER){ string movq = "movq %"+regleft+", %rcx"; string movq2 = "movq %"+regright+", %rax"; string movq3 = "movq %rcx, %rax"; string cqld = "cltd"; string movq4 = "movq %"+regright+", %rcx"; string stmt = "idivq %rcx"; /* TODO Task: Check if %rdx is free before taking it*/ string movq5 = "movq %rdx, %"+regright; addCompileStmt(movq); addCompileStmt(movq2); addCompileStmt(movq3); addCompileStmt(cqld); addCompileStmt(movq4); addCompileStmt(stmt); addCompileStmt(movq5); }else{ RaisePineException("Modulo is not defined for non-integer operands."); } } else if(operation == BAND){ if(ltype == INTEGER && rtype == INTEGER){ string ins1 = "movq %"+regleft+", %rcx"; string ins2 = "movq %"+regright+", %rax"; string ins3 = "andq %rcx, %rax"; string ins4 = "movq %rax, %"+regright; addCompileStmt(ins1); addCompileStmt(ins2); addCompileStmt(ins3); addCompileStmt(ins4); }else{ RaisePineException("Bit-wise And is not defined for non-integer operands."); } } else if(operation == BOR){ if(ltype == INTEGER && rtype == INTEGER){ string ins1 = "movq %"+regleft+", %rcx"; string ins2 = "movq %"+regright+", %rax"; string ins3 = "orq %rcx, %rax"; string ins4 = "movq %rax, %"+regright; addCompileStmt(ins1); addCompileStmt(ins2); addCompileStmt(ins3); addCompileStmt(ins4); }else{ RaisePineException("Bit-wise Or is not defined for non-integer operands."); } } else if(operation == XOR){ if(ltype == INTEGER && rtype == INTEGER){ string ins1 = "movq %"+regleft+", %rcx"; string ins2 = "movq %"+regright+", %rax"; string ins3 = "xorq %rcx, %rax"; string ins4 = "movq %rax, %"+regright; addCompileStmt(ins1); addCompileStmt(ins2); addCompileStmt(ins3); addCompileStmt(ins4); }else{ RaisePineException("Bit-wise Xor is not defined for non-integer operands."); } } else if(operation == LS){ if(ltype == INTEGER && rtype == INTEGER){ string ins1 = "movq %"+regright+", %rcx"; string ins2 = "movq %"+regleft+", %rax"; string ins3 = "shlq %cl, %rax"; string ins4 = "movq %rax, %"+regright; addCompileStmt(ins1); addCompileStmt(ins2); addCompileStmt(ins3); addCompileStmt(ins4); }else{ RaisePineException("Left shift is not defined for non-integer operands."); } } else if(operation == RS){ if(ltype == INTEGER && rtype == INTEGER){ string ins1 = "movq %"+regright+", %rcx"; string ins2 = "movq %"+regleft+", %rax"; string ins3 = "sarq %cl, %rax"; string ins4 = "movq %rax, %"+regright; addCompileStmt(ins1); addCompileStmt(ins2); addCompileStmt(ins3); addCompileStmt(ins4); }else{ RaisePineException("Right shift is not defined for non-integer operands."); } } else{ RaisePineWarning("Uncaught Binary operation in compile "+STR(operation)); } registerManager.releaseRegister(regleft); b->typeContext.implicitType = ltype; CompilerResult result = EmptyResult; result.resultType = REG; result.data = regright; return result; } /* Function */ else if(Type == FUNCTION){ Function* f = Safe_Cast<Function*>(expr); pushNewStackFrame(); /* TODO: Expand args here */ Seq* body = f->getBody(); compile(body); /* Create stack space dependent on variable count */ Int32 varCount = bindings.top().size(); Int32 stackSize = align32ByteStack(varCount); string ins1 = "addq $"+STR(stackSize)+", %rsp"; string ins2 = "popq %rbp"; string ins3 = "retq"; string ins4 = "subq $"+STR(stackSize)+", %rsp"; string ins5 = "movq %rsp, %rbp"; string ins6 = "pushq %rbp"; addCompileStmt(ins1); addCompileStmt(ins2); addCompileStmt(ins3); addFrontCompileStmt(ins4); addFrontCompileStmt(ins5); addFrontCompileStmt(ins6); string ins7 = "_"+f->getName()+":"; string ins8 = ".global _"+f->getName(); addFrontCompileStmt(ins7); addFrontCompileStmt(ins8); popStackFrame(); CompilerResult result = EmptyResult; result.resultType = VOID; return result; } /* Seq */ else if(Type == SEQ){ Seq* seq = Safe_Cast<Seq*>(expr); vector<Object*> body = seq->getStatements(); for(const auto& stmt : body){ compile(stmt); } CompilerResult result = EmptyResult; result.resultType = VOID; return result; } /* Let */ else if(Type == LET){ Let* let = Safe_Cast<Let*>(expr); Object* rval = let->getVal(); string name = let->getName(); CompilerResult compiledResult = compile(rval); string reg = IntoRegister(compiledResult.data); Int32 stackLocation; CompileBinding binding; CompilerResult result = EmptyResult; if(rval->getExplicitType() == ARRAY){ string ins1 = "movq %"+reg+", "+compiledResult.data; addCompileStmt(ins1); string location = compiledResult.data; binding.stackLocation = compiledResult.stackLocation; result.stackLocation = compiledResult.stackLocation; let->typeContext.stackLocation = compiledResult.stackLocation; }else{ setBindings(name); stackLocation = retrieveStackLocation(name); binding.stackLocation = stackLocation; string ins1 = "movq %"+reg+", -"+STR(stackLocation)+"(%rbp)"; result.stackLocation = stackLocation; let->typeContext.stackLocation = stackLocation; addCompileStmt(ins1); } binding.obj = rval; setBindings(name, binding); registerManager.releaseRegister(reg); result.resultType = VOID; return result; } /* Assign */ else if(Type == ASSIGN){ Assign* a = Safe_Cast<Assign*>(expr); Object* rval = a->getVal(); string reg = IntoRegister(compile(rval).data); string varName = Safe_Cast<Var*>(a->getVar())->getName(); Int32 stackLocation = retrieveStackLocation(varName); string stmt = "movq %"+reg+", -"+to_string(stackLocation)+"(%rbp)"; addCompileStmt(stmt); registerManager.releaseRegister(reg); CompilerResult result = EmptyResult; result.resultType = VOID; return result; } /* Print */ else if(Type == PRINT){ Print* p = Safe_Cast<Print*>(expr); CompilerResult compiledResult = compile(p->getVal()); PolymorphicPrint(p->getVal(), compiledResult); CompilerResult result = EmptyResult; result.resultType = VOID; return result; } /*If*/ else if(Type == IF){ If* i = Safe_Cast<If*>(expr); vector<tuple<Object*, Seq*>> ifStmt = i->getIfStmt(); /* For each if / if else statement, compile the condition and the following body. */ string ins2 = "SHORT_"+to_string(requestShortID()); for (const auto& stmt : ifStmt){ Object* condition = get<0>(stmt); Int32 conType = getImplicitType(condition); if(conType != BOOLEAN && conType != COMPARE && conType != LOGICAL) { RaisePineException("If statement conditions must be evaluable to a Boolean type."); } CompilerResult con = compile(condition); string ins1 = IntoRegister(con.data); string ins3 = "ELSE_ELIF_"+STR(requestJumpID()); string ins4 = "cmpq $1, %"+ins1; string ins5 = "jne "+ins3; addCompileStmt(ins4); addCompileStmt(ins5); /* Compile then body */ compile(get<1>(stmt)); addCompileStmt("jmp "+ins2); addCompileStmt(ins3+":"); } /* Compile else body if it exist*/ if(i->getElse() != nullptr){ compile(i->getElse()); } addCompileStmt(ins2+":"); CompilerResult result = EmptyResult; result.resultType = VOID; return result; } /* Compare */ else if(Type == COMPARE){ Compare* c = Safe_Cast<Compare*>(expr); Int32 operation = c->getOperation(); CompilerResult left = compile(c->getLeft()); CompilerResult right = compile(c->getRight()); Int32 ltype = getImplicitType(c->getLeft()); Int32 rtype = getImplicitType(c->getRight()); if(ltype != rtype){ RaisePineException("Comparison operation require like-type operands.\n" "Recieved ("+getTypeName(ltype)+") and ("+getTypeName(rtype)+")"); } string instruction; /* Jump if comparison is false */ if(operation == EQU){ instruction = "jne"; }else if(operation == NEQ){ instruction = "je"; }else if(operation == LT){ instruction = "jge"; }else if(operation == LTE){ instruction = "jg"; }else if(operation == GTE){ instruction = "jl"; }else if(operation == GT){ instruction = "jle"; } string regleft = IntoRegister(left.data); string regright = IntoRegister(right.data); string cmp = "cmpq %"+regright+", %"+regleft; addCompileStmt(cmp); string label = "COMPARE_T"+to_string(requestJumpID()); string Short = "COMPARE_F"+to_string(requestShortID()); /* Move $1 into the right register */ string jmp = instruction+" "+label; addCompileStmt(jmp); addCompileStmt("movq $1, %"+regright); addCompileStmt("jmp "+Short); addCompileStmt(label+":"); addCompileStmt("movq $0, %"+regright); addCompileStmt(Short+":"); registerManager.releaseRegister(regleft); CompilerResult result = EmptyResult; result.resultType = REG; result.data = regright; return result; } /* For */ else if(Type == FOR){ For* f = Safe_Cast<For*>(expr); compile(f->getDeclare()); string ins1 = "FOR_" + STR(requestJumpID()); addCompileStmt(ins1 + ":"); string ins2 = "SHORT_" + STR(requestShortID()); CompilerResult compiledResult = compile(f->getCondition()); string reg = IntoRegister(compiledResult.data); string ins3 = "cmpq $1, %" + reg; string ins4 = "jne " + ins2; addCompileStmt(ins3); addCompileStmt(ins4); compile(f->getBody()); compile(f->getIncl()); string ins5 = "jmp " + ins1; addCompileStmt(ins5); addCompileStmt(ins2 + ":"); registerManager.releaseRegister(reg); CompilerResult result = EmptyResult; result.resultType = VOID; return result; } /*While*/ else if(Type == WHILE){ While* w = Safe_Cast<While*>(expr); string ins1 = "WHILE_" + STR(requestJumpID()); addCompileStmt(ins1 + ":"); CompilerResult compiledResult = compile(w->getCondition()); string reg = IntoRegister(compiledResult.data); string ins2 = "cmpq $1, %" + reg; string ins3 = "SHORT_" + STR(requestShortID()); string ins4 = "jne " + ins3; addCompileStmt(ins2); addCompileStmt(ins4); compile(w->getBody()); string ins5 = "jmp " + ins1; addCompileStmt(ins5); addCompileStmt(ins3 + ":"); registerManager.releaseRegister(reg); CompilerResult result = EmptyResult; result.resultType = VOID; return result; } /* Array */ else if(Type == ARRAY){ Array* a = Safe_Cast<Array*>(expr); vector<Object*> array = a->getArray(); static Int32 elementCounter = 0; const Int32 NO_LOCATION = -1; Int32 pointerToArray = NO_LOCATION; Int32 elementType = NIT; Int32 stackLocation = NO_LOCATION; for(const auto& element : array){ const string elementName = "ARRAY_ELEMENT_"+STR(elementCounter); elementCounter += 1; CompilerResult compiledResult = compile(element); if(element->getExplicitType() != ARRAY){ string reg = IntoRegister(compiledResult.data); setBindings(elementName); stackLocation = retrieveStackLocation(elementName); string ins1 = "movq %"+reg+", -"+STR(stackLocation)+"(%rbp)"; addCompileStmt(ins1); registerManager.releaseRegister(reg); }else{ stackLocation = compiledResult.stackLocation; } if(pointerToArray == NO_LOCATION){ /* Assign the first element of the array as the pointerToArray */ pointerToArray = stackLocation; } } CompilerResult result = EmptyResult; result.resultType = ARRAY; result.stackLocation = pointerToArray; result.data = "-" + STR(pointerToArray) + "(%rbp)"; a->typeContext.stackLocation = pointerToArray; return result; } /* Index */ else if(Type == INDEX){ Index* i = Safe_Cast<Index*>(expr); string arrayName = i->getArrayName(); Array* a = Safe_Cast<Array*>(getBindings(arrayName).obj); Int32 indexOffset = a->getIndexOffsetSize(); Int32 arrayStackLocation = retrieveStackLocation(arrayName); vector<Int32> offsetTable = a->getOffsetTable(); vector<Object*> indices = i->getIndex(); string reg; string toReg = registerManager.getRegister(); string ins0 = "xorq %"+toReg+", %"+toReg; addCompileStmt(ins0); for (Int32 i = 0; i < indices.size(); i++) { Object* nthIndex = indices[i]; CompilerResult compiledResult = compile(nthIndex); reg = IntoRegister(compiledResult.data); string ins1 = "imulq $"+STR(offsetTable[offsetTable.size()-1-i])+", %"+reg; string ins2 = "addq %"+reg+", %"+toReg; string ins3 = "incq %"+toReg; addCompileStmt(ins1); addCompileStmt(ins2); addCompileStmt(ins3); } string ins3 = "negq %"+toReg; string ins4 = "movq -"+STR(arrayStackLocation)+"(%rbp, %"+toReg+ ", "+STR(ARCH64)+"), %"+reg; addCompileStmt(ins3); addCompileStmt(ins4); CompilerResult result = EmptyResult; result.resultType = REG; result.data = reg; i->typeContext.indexInstruction = "-"+STR(arrayStackLocation)+"(%rbp, %"+toReg+ ", "+STR(ARCH64)+")"; return result; } RaisePineWarning("Compiler reached end of token matching. Type: "+getTypeName(Type)); LOG("Compile:compile escaped type: "+STR(Type)); CompilerResult result = EmptyResult; result.resultType = VOID; return result; } void Compiler::addFlatStmtToStack(Object* stmt){ vector<Object*>* last = &(flattenStmt.top()); last->push_back(stmt); } void Compiler::pushNewFlatStack(){ vector<Object*> frame; flattenStmt.push(frame); } vector<Object*> Compiler::popFlatStack(){ vector<Object*> last = (flattenStmt.top()); flattenStmt.pop(); return last; } string Compiler::IntoRegister(string operand){ LOG("Compiler:IntoRegister"); LOG(" operand:"+operand); if(operand == VOID_ASM_OPERAND){ RaisePineException("Compiler reached a fatel error when assigning registers."); } Char first = operand[0]; /* Check if it's a register i.e. rax or eax by the first char. We assume the operand register could be 32 or 64 bits. */ if(first == 'r' || first == 'e'){ return operand; } string reg = registerManager.getRegister(); if(reg == VOID_ASM_OPERAND){ RaisePineWarning("Ran out of registers. Please report this issue."); } if(first == '-' || ((first - '0' >= 0) || (first - '0' <= 9)) || first == '$'){ string stmt = "movq " + operand + ", %" + reg; addCompileStmt(stmt); return reg; } RaisePineException("Compiler reached a fatel error when assigning registers."); return VOID_ASM_OPERAND; } void Compiler::addCompileStmt(string stmt){ vector<string>* last = &(compileStmt.top()); last->push_back(stmt); } void Compiler::addFrontCompileStmt(string stmt){ vector<string>* last = &(compileStmt.top()); last->insert(last->begin(), stmt); } void Compiler::pushNewStackFrame(){ vector<string> frame; compileStmt.push(frame); pushNewBindings(); } void Compiler::popStackFrame(){ vector<string> second_last = (compileStmt.top()); compileStmt.pop(); vector<string> last = (compileStmt.top()); last.insert(last.begin(), second_last.begin(), second_last.end()); compileStmt.pop(); compileStmt.push(last); popBindings(); } void Compiler::PolymorphicPrint(Object* expr, CompilerResult result){ LOG("Compiler:PolymorphicPrint"); LOG(" expr: 0x"+AddressOf(&expr)); LOG(" result: ("+result.data+", "+getTypeName(result.resultType)+")"); Int32 explicitType = expr->getExplicitType(); LOG(" explicitType: "+getTypeName(explicitType)); switch (explicitType) { case VAR: { Var* v = Safe_Cast<Var*>(expr); string varName = v->getName(); Int32 stackLocation = retrieveStackLocation(varName); if (isPrimative(v->getVarType())) { string ins1 = "leaq -"+STR(stackLocation)+"(%rbp), %rsi"; string ins2 = "movq $"+STR(v->getVarType())+", %rdi"; string ins3 = "callq _PinePrint"; addCompileStmt(ins1); addCompileStmt(ins2); addCompileStmt(ins3); } else { CompileBinding binding = getBindings(varName); Object* bindedExpr = binding.obj; PolymorphicPrint(bindedExpr, result); } } break; case ARRAY: { Array* a = Safe_Cast<Array*>(expr); vector<Object*> array = a->getArray(); Int32 arrayLength = a->getLength(); string ins1 = "leaq "+result.data+", %rsi"; string ins2; /* If the explicit type is still not primative, retrieve the implicit type */ Int32 primativeType = a->typeContext.arrayPrimativeElementType; if (isPrimative(primativeType) != true) { primativeType = getImplicitType(array.size() > 1 ? array[1] : nullptr); } ins2 = "movq $"+STR(primativeType)+", %rdi"; string ins3 = "callq _PinePrintArray"; addCompileStmt(ins1); addCompileStmt(ins2); addCompileStmt(ins3); } break; case INTEGER: { string ins1 = "movq "+result.data+", %rdi"; string ins2 = "callq _PinePrintInt"; addCompileStmt(ins1); addCompileStmt(ins2); } break; case STRING: { string ins1 = "movq %"+result.data+", %rdi"; string ins2 = "callq _PinePrintString"; addCompileStmt(ins1); addCompileStmt(ins2); registerManager.releaseRegister(result.data); } break; case INDEX: { Index* i = Safe_Cast<Index*>(expr); string arrayName = i->getArrayName(); Int32 elementType = i->getElementType(); CompileBinding binding = getBindings(arrayName); Array* a = Safe_Cast<Array*>(binding.obj); string ins1; string ins2; string ins3; if (isPrimative(elementType)) { ins1 = "leaq "+i->typeContext.indexInstruction+", %rsi"; ins2 = "movq $"+STR(elementType)+", %rdi"; ins3 = "callq _PinePrint"; } else if (i->getIndex().size() == a->typeContext.arrayDepth){ ins1 = "leaq "+i->typeContext.indexInstruction+", %rsi"; ins2 = "movq $"+STR(a->typeContext.arrayPrimativeElementType)+", %rdi"; ins3 = "callq _PinePrint"; } else { ins1 = "leaq "+i->typeContext.indexInstruction+", %rsi"; ins2 = "movq $"+STR(a->typeContext.arrayPrimativeElementType)+", %rdi"; ins3 = "callq _PinePrintArray"; } addCompileStmt(ins1); addCompileStmt(ins2); addCompileStmt(ins3); } break; case BOOLEAN: { string ins1 = "movq "+result.data+", %rdi"; string ins2 = "callq _PinePrintBoolean"; addCompileStmt(ins1); addCompileStmt(ins2); } break; case FLOAT: { string ins1 = "movq "+result.data+", %rdi"; string ins2 = "callq _PinePrintFloat"; addCompileStmt(ins1); addCompileStmt(ins2); } break; case DOUBLE: { string ins1 = "movq "+result.data+", %rdi"; string ins2 = "callq _PinePrintDouble"; addCompileStmt(ins1); addCompileStmt(ins2); } break; default: RaisePineWarning("Print function caught unknown type ("+getTypeName(explicitType)+")"); break; } LOG("Compiler:-PolymorphicPrint"); } string Compiler::getAssembly(){ LOG("Compiler:getAssembly"); header.insert(header.end(), compileStmt.top().begin(), compileStmt.top().end()); string output = ""; for(auto s : header){ Char first = s[0]; string tab = "\t"; if(first != '.' && !(first >= 'A' && first <= 'Z')) { s = tab + s; } output += (s + "\n"); } LOG("Compiler:-getAssembly"); return output; } void Compiler::generateBinary(){ LOG("Compiler:generateBinary"); string asmCode = getAssembly(); ofstream asmFile; asmFile.open("Pine.s"); asmFile << asmCode; asmFile.close(); /* TODO: Variable for gcc or llvm */ system("gcc -std=c11 -o a.out Pine.s PineRuntime.s"); LOG("Compiler:-generateBinary"); } // --- void Compiler::pushNewBindings(){ map<string, CompileBinding> m; bindings.push(m); } void Compiler::popBindings(){ map<string, CompileBinding>* last = &(bindings.top()); bindings.pop(); } void Compiler::setBindings(string varName, CompileBinding binding){ map<string, CompileBinding>* last = &(bindings.top()); (*last)[varName] = binding; } void Compiler::setBindings(string varName){ map<string, CompileBinding>* frame = &(bindings.top()); if(frame->count(varName) > 0){ RaisePineException("Redeclarion of variable named: "+varName); } /* Stack address are aligned by 0x8. Give the Var the next location based on the given size of the scope's variable count. */ Int32 stackLocation = (frame->size() + 1) << 3; CompileBinding binding; binding.stackLocation = stackLocation; binding.obj = nullptr; setBindings(varName, binding); } CompileBinding Compiler::getBindings(string varName){ map<string, CompileBinding>* frame = &(bindings.top()); return (*frame)[varName]; } Int32 Compiler::retrieveStackLocation(string varName){ map<string, CompileBinding>* frame = &(bindings.top()); if (frame->find(varName) == frame->end()) { RaisePineException("Stack location could not be found for: "+varName); } CompileBinding binding = (*frame)[varName]; return binding.stackLocation; }
34.263952
105
0.521438
mita4829
afba28db80716d54652e33545d25b1b91e6b5dd7
1,789
hpp
C++
include/uri/uri.hpp
ledocc/uri
0767d923f7d1690e495ddca8a84352746b572904
[ "BSL-1.0" ]
null
null
null
include/uri/uri.hpp
ledocc/uri
0767d923f7d1690e495ddca8a84352746b572904
[ "BSL-1.0" ]
null
null
null
include/uri/uri.hpp
ledocc/uri
0767d923f7d1690e495ddca8a84352746b572904
[ "BSL-1.0" ]
null
null
null
#ifndef uri__uri_hpp #define uri__uri_hpp #include <uri/basic_uri.hpp> #include <uri/parsers/rules/uri/fragment.hpp> #include <uri/parsers/rules/uri/host.hpp> #include <uri/parsers/rules/uri/path.hpp> #include <uri/parsers/rules/uri/port.hpp> #include <uri/parsers/rules/uri/query.hpp> #include <uri/parsers/rules/uri/scheme.hpp> #include <uri/parsers/rules/uri/userinfo.hpp> #include <uri/traits.hpp> #include <string> namespace uri { struct uri_tag {}; using string_scheme_trait = helpers::string_component_traits< parsers::rules::uri::scheme >; using string_userinfo_trait = helpers::string_component_traits< parsers::rules::uri::userinfo >; using string_host_trait = helpers::string_component_traits< parsers::rules::uri::host >; using string_port_trait = helpers::string_component_traits< parsers::rules::uri::port >; using string_path_trait = helpers::string_component_traits< parsers::rules::uri::path >; using string_query_trait = helpers::string_component_traits< parsers::rules::uri::query >; using string_fragment_trait = helpers::string_component_traits< parsers::rules::uri::fragment >; template <> struct traits< uri_tag > : public helpers::composed_traits< string_scheme_trait, string_userinfo_trait, string_host_trait, string_port_trait, string_path_trait, string_query_trait, string_fragment_trait > {}; using uri = basic_uri< uri_tag >; } // namespace uri #endif // uri__uri_hpp
35.78
96
0.618781
ledocc
afbad93be7334b61e37a15c16d63fecb541a6b9a
442
cpp
C++
displayOverload.cpp
compliment/cpp-tasks
31c5771e97c319860a1b546c68d92601b77e0223
[ "Unlicense" ]
null
null
null
displayOverload.cpp
compliment/cpp-tasks
31c5771e97c319860a1b546c68d92601b77e0223
[ "Unlicense" ]
null
null
null
displayOverload.cpp
compliment/cpp-tasks
31c5771e97c319860a1b546c68d92601b77e0223
[ "Unlicense" ]
null
null
null
#include<iostream> using namespace std; template <class T> void display(const T & a) { cout << a << endl; } template <class T> void display(const T & a, const int n) //overloaded version of display() { int ctr; for(ctr=0;ctr<n;ctr++) cout << a << endl; } int main() { char c = 'a'; int i = 10; display(c); cout<<endl; display(c,3); cout<<endl; display(i); cout<<endl; display(i,5); cout<<endl; }
14.733333
73
0.574661
compliment
afc7d73c50c66c6be85300345be71330b6eda4ef
1,207
cpp
C++
src/parsing/mSetParser.cpp
athanor/athanor
0e7a654c360be05dc6f6e50427b2ee3df92c1aaf
[ "BSD-3-Clause" ]
4
2018-08-31T09:44:52.000Z
2021-03-01T19:10:00.000Z
src/parsing/mSetParser.cpp
athanor/athanor
0e7a654c360be05dc6f6e50427b2ee3df92c1aaf
[ "BSD-3-Clause" ]
21
2019-12-29T08:33:34.000Z
2020-11-22T16:38:37.000Z
src/parsing/mSetParser.cpp
athanor/athanor
0e7a654c360be05dc6f6e50427b2ee3df92c1aaf
[ "BSD-3-Clause" ]
null
null
null
#include <algorithm> #include "parsing/parserCommon.h" #include "types/mSetVal.h" using namespace std; using namespace lib; using namespace nlohmann; shared_ptr<MSetDomain> parseDomainMSet(json& mSetDomainExpr, ParsedModel& parsedModel) { SizeAttr sizeAttr = parseSizeAttr(mSetDomainExpr[1][0], parsedModel); if (!mSetDomainExpr[1][1].count("OccurAttr_None")) { myCerr << "Error: for the moment, given attribute " "must be " "OccurAttr_None. This is not handled yet: " << mSetDomainExpr[1][1] << endl; myAbort(); } return make_shared<MSetDomain>(sizeAttr, parseDomain(mSetDomainExpr[2], parsedModel)); } ParseResult parseOpMSetLit(json& mSetExpr, ParsedModel& parsedModel) { auto result = parseAllAsSameType(mSetExpr, parsedModel); size_t numberElements = result.numberElements(); auto mSet = OpMaker<OpMSetLit>::make(move(result.exprs)); mSet->setConstant(result.allConstant); auto domain = make_shared<MSetDomain>(exactSize(numberElements), result.domain); return ParseResult(domain, mSet, result.hasEmptyType); }
40.233333
80
0.657829
athanor
afc91090961c3bef164251d716eb7aad1da465a2
1,246
cc
C++
0236_Lowest_Common_Ancestor_of_a_Binary_Tree/0236.cc
LuciusKyle/LeetCode
66c9090e5244b10eca0be50398764da2b4b48a6c
[ "Apache-2.0" ]
null
null
null
0236_Lowest_Common_Ancestor_of_a_Binary_Tree/0236.cc
LuciusKyle/LeetCode
66c9090e5244b10eca0be50398764da2b4b48a6c
[ "Apache-2.0" ]
null
null
null
0236_Lowest_Common_Ancestor_of_a_Binary_Tree/0236.cc
LuciusKyle/LeetCode
66c9090e5244b10eca0be50398764da2b4b48a6c
[ "Apache-2.0" ]
null
null
null
#include <set> #include <vector> using std::vector; using std::set; // Definition for a binary tree node. struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { vector<TreeNode*> first_traversal; return nullptr; } private: int preOrderTraversal(TreeNode* node, vector<TreeNode *>& ptr_vec, const TreeNode* p, const TreeNode* q, int count) { if (node == nullptr) return; if (node->left == p || node->right == q) ptr_vec.push_back(node); preOrderTraversal(node->left, ptr_vec, p, q, count); preOrderTraversal(node->right, ptr_vec, p, q, count); } void inOrderTraversal(TreeNode* node, set<TreeNode *>& in_order_traversal, const TreeNode* p, const TreeNode* q, bool start_record) { if (node == nullptr) return; inOrderTraversal(node->left, in_order_traversal, p, q, start_record); if (node == p || node == q) { if (start_record) return; else start_record = true; } in_order_traversal.insert(node); inOrderTraversal(node->right, in_order_traversal, p, q, start_record); } };
27.688889
135
0.666934
LuciusKyle
afcfee485a254d48f6d3bc3cee8c58e573af849b
7,188
cc
C++
src/cmapfile.cc
h20y6m/HaranoAjiFonts-generator
a8f15232154201635ab38b454056af15b6c515c8
[ "BSD-2-Clause" ]
7
2019-03-04T03:16:49.000Z
2022-02-26T08:02:12.000Z
src/cmapfile.cc
h20y6m/HaranoAjiFonts-generator
a8f15232154201635ab38b454056af15b6c515c8
[ "BSD-2-Clause" ]
3
2020-02-09T08:19:56.000Z
2020-04-15T15:31:55.000Z
src/cmapfile.cc
h20y6m/HaranoAjiFonts-generator
a8f15232154201635ab38b454056af15b6c515c8
[ "BSD-2-Clause" ]
3
2019-04-16T11:17:10.000Z
2020-02-18T03:55:46.000Z
// // Harano Aji Fonts generator // https://github.com/trueroad/HaranoAjiFonts-generator // // cmapfile.cc: // read CMap file (UTF-32 to pre-defined CID) and create map // // Copyright (C) 2019, 2020 Masamichi Hosoda. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. // #include "cmapfile.hh" #include <fstream> #include <iomanip> #include <iostream> #include <map> #include <regex> #include <string> #include "regex_dispatcher_m.hh" cmapfile::cmapfile (): regex_dispatcher::member_table<cmapfile> ({ { std::regex (R"(<([\da-fA-F]+)>\s*(\d+)\r?)"), &cmapfile::cidchar_dec}, { std::regex (R"(<([\da-fA-F]+)>\s*([\da-fA-F]+)\r?)"), &cmapfile::cidchar_hex}, { std::regex (R"(<([\da-fA-F]+)>\s*<([\da-fA-F]+)>\s*(\d+)\r?)"), &cmapfile::cidrange_dec}, { std::regex (R"(<([\da-fA-F]+)>\s*<([\da-fA-F]+)>\s*([\da-fA-F]+)\r?)"), &cmapfile::cidrange_hex}, { std::regex (R"((\d+)\s*begincidchar\r?)"), &cmapfile::begincidchar}, { std::regex (R"((\d+)\s*begincidrange\r?)"), &cmapfile::begincidrange}, { std::regex (R"(endcidchar\r?)"), &cmapfile::endcidchar}, { std::regex (R"(endcidrange\r?)"), &cmapfile::endcidrange}, }) { } void cmapfile::load (const std::string &filename) { map_.clear (); dup_.clear (); std::ifstream ifs; ifs.open (filename); if (!ifs) { std::cerr << "error: " << __func__ << ": open failed." << std::endl; return; } process_stream (ifs); } void cmapfile::set_map (int uni, int cid) { if (dup_.find (cid) != dup_.end ()) std::cout << "#duplicate in CMap file: U+" << std::setw (4) << std::setfill ('0') << std::hex << std::uppercase << dup_[cid] << ", U+" << std::setw (4) << uni << std::nouppercase << std::dec << std::setfill (' ') << " -> cid " << cid << std::endl; else dup_[cid] = uni; if (map_.find (uni) != map_.end ()) std::cout << "#warning: invalid CMap file: duplicate U+" << std::setw (4) << std::setfill ('0') << std::hex << std::uppercase << uni << std::nouppercase << std::dec << std::setfill (' ') << std::endl; else map_[uni] = cid; } bool cmapfile::cidchar (int uni, int cid) { if (is_char_) { set_map (uni, cid); if (chars_ > 0) --chars_; else std::cout << "#warning: invalid CMap file: " << __func__ << ": extra char" << std::endl; } return true; } bool cmapfile::cidchar_dec (const std::smatch &sm) { auto uni {std::stoi (sm[1].str (), nullptr, 16)}; auto cid {std::stoi (sm[2].str ())}; return cidchar (uni, cid); } bool cmapfile::cidchar_hex (const std::smatch &sm) { auto uni {std::stoi (sm[1].str (), nullptr, 16)}; auto cid {std::stoi (sm[2].str (), nullptr, 16)}; return cidchar (uni, cid); } bool cmapfile::cidrange (int u1, int u2, int cid) { if (is_range_) { if (u1 > u2) { std::cout << "#warning: invalid CMap file: " << __func__ << ": start > end" << std::endl; } int i = u1, c = cid; while ( i <= u2) set_map (i++, c++); if (ranges_ > 0) --ranges_; else std::cout << "#warning: invalid CMap file: " << __func__ << ": extra range" << std::endl; } return true; } bool cmapfile::cidrange_dec (const std::smatch &sm) { auto u1 {std::stoi (sm[1].str (), nullptr, 16)}; auto u2 {std::stoi (sm[2].str (), nullptr, 16)}; auto cid {std::stoi (sm[3].str ())}; return cidrange (u1, u2, cid); } bool cmapfile::cidrange_hex (const std::smatch &sm) { auto u1 {std::stoi (sm[1].str (), nullptr, 16)}; auto u2 {std::stoi (sm[2].str (), nullptr, 16)}; auto cid {std::stoi (sm[3].str (), nullptr, 16)}; return cidrange (u1, u2, cid); } bool cmapfile::begincidchar (const std::smatch &sm) { auto chars {std::stoi (sm[1].str ())}; if (is_char_) { std::cout << "#warning: invalid CMap file: " << __func__ << ": no endcidchar" << std::endl; } if (is_range_) { std::cout << "#warning: invalid CMap file: " << __func__ << ": no endcidrange" << std::endl; is_range_ = false; } is_char_ = true; chars_ = chars; return true; } bool cmapfile::begincidrange (const std::smatch &sm) { auto ranges {std::stoi (sm[1].str ())}; if (is_char_) { std::cout << "#warning: invalid CMap file: " << __func__ << ": no endcidchar" << std::endl; is_char_ = false; } if (is_range_) { std::cout << "#warning: invalid CMap file:" << __func__ << ": no endcidrange" << std::endl; } is_range_ = true; ranges_ = ranges; return true; } bool cmapfile::endcidchar (const std::smatch &sm) { if (is_char_) { if (chars_) std::cout << "#warning: invalid CMap file: " << __func__ << ": wrong begincidchar" << std::endl; is_char_ = false; } else std::cout << "#warning: invalid CMap file: " << __func__ << ": no begincidchar" << std::endl; if (is_range_) { std::cout << "#warning: invalid CMap file: " << __func__ << ": no endcidrange" << std::endl; is_range_ = false; } return true; } bool cmapfile::endcidrange (const std::smatch &sm) { if (is_char_) { std::cout << "#warning: invalid CMap file: " << __func__ << ": no endcidchar" << std::endl; is_char_ = false; } if (is_range_) { if (ranges_) std::cout << "#warning: invalid CMap file: " << __func__ << ": wrong begincidrange" << std::endl; is_range_ = false; } else std::cout << "#warning: invalid CMap file: " << __func__ << ": no begincidrange" << std::endl; return true; }
26.043478
78
0.570534
h20y6m
afd005abc339d89edfa6749a035e0d477df3ffa2
1,262
cpp
C++
Source Code/AI/ActionInterface/AIProcessor.cpp
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
9
2018-05-02T19:53:41.000Z
2021-10-18T18:30:47.000Z
Source Code/AI/ActionInterface/AIProcessor.cpp
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
7
2018-02-01T12:16:43.000Z
2019-10-21T14:03:43.000Z
Source Code/AI/ActionInterface/AIProcessor.cpp
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
1
2020-09-08T03:28:22.000Z
2020-09-08T03:28:22.000Z
#include "stdafx.h" #include "Headers/AIProcessor.h" #include "AI/Headers/AIManager.h" namespace Divide::AI { AIProcessor::AIProcessor(AIManager& parentManager) : _entity(nullptr), _parentManager(parentManager), _currentStep(-1), _activeGoal(nullptr) { _init = false; } AIProcessor::~AIProcessor() { _actionSet.clear(); _goals.clear(); } void AIProcessor::addEntityRef(AIEntity* entity) { if (entity) { _entity = entity; } } void AIProcessor::registerAction(const GOAPAction& action) { _actionSet.push_back(&action); } void AIProcessor::registerActionSet(const GOAPActionSet& actionSet) { _actionSet.insert(std::end(_actionSet), std::begin(actionSet), std::end(actionSet)); } void AIProcessor::registerGoal(const GOAPGoal& goal) { assert(!goal.vars_.empty()); _goals.push_back(goal); } void AIProcessor::registerGoalList(const GOAPGoalList& goalList) { for (const GOAPGoal& goal : goalList) { registerGoal(goal); } } const string& AIProcessor::printActionStats(const GOAPAction& planStep) const { static const string placeholder(""); return placeholder; } } // namespace Divide::AI
22.535714
80
0.656101
IonutCava
afd24d7882b448e2b83c8586a9326b17946fec5c
7,187
cpp
C++
Robocup/Thread/Brain.cpp
MaximV88/RoboCup
7066f3f1370145cf0a7bad06a7774716cb0b4573
[ "MIT" ]
null
null
null
Robocup/Thread/Brain.cpp
MaximV88/RoboCup
7066f3f1370145cf0a7bad06a7774716cb0b4573
[ "MIT" ]
null
null
null
Robocup/Thread/Brain.cpp
MaximV88/RoboCup
7066f3f1370145cf0a7bad06a7774716cb0b4573
[ "MIT" ]
null
null
null
// // Brain.cpp // Ex3 // // Created by Maxim Vainshtein on 1/9/15. // Copyright (c) 2015 Maxim Vainshtein. All rights reserved. // #include "Brain.h" #include "Player.h" #include "BehaviorTree.h" //How many updates required to continue on Wait command #define WAIT_UPDATES 2 #define DEBUG_PRINT_EXECUTION_INDEX_MESSAGE "Debug: At execution index " #define BRAIN_UNKNOWN_BEHAVIOR_NAME_ERROR "Brain Error: Behavior change to unknown name requested." #define BRAIN_NO_SELECTED_BEHAVIOR_ERROR "Brain Error: No behavior has been selected." #define BRAIN_INVALID_SHUTTING_DOWN "Invalid setup. Shutting Down." #define BRAIN_TOO_MANY_UNIQUE_INSTRUCTIONS_ERROR "Brain Error: Too many unique instructions per message." #define BRAIN_UNIQUE_INSTRUCTION_PER_MESSAGE 1 #define EXECUTE_ACTION_DESCRIPTION "Brain: Execution will end the Act." Brain::Brain(ThreadQueue<std::string*>& qInstructionQueue) : m_qInstructionQueue(qInstructionQueue), m_cConditionVariable(m_cMutualExclusionPrimary) { m_dIsBodyStateUpdate = 0; m_dIsSeeStateUpdate = 0; m_dIsTeamStateUpdate = 0; m_cBehavior = NULL; //Start playing start(); } Brain::~Brain() { } void Brain::addBehavior(behavior::BehaviorTree &cBehaviorTree) { //Map the Tree pointer to the name m_mcBehaviors[cBehaviorTree.getName()] = &cBehaviorTree; } void Brain::setBehavior(std::string strName) { //Check if the requested behavior was added if (m_mcBehaviors.find(strName)->second == NULL) { std::cerr << BRAIN_UNKNOWN_BEHAVIOR_NAME_ERROR << std::endl; return; } // m_cMutualExclusionSecondary.lock(); //Reset the current tree // if (m_cBehavior != NULL) // m_cBehavior->abort(); //Set the acting behavior m_cBehavior = m_mcBehaviors.find(strName)->second; // m_cMutualExclusionSecondary.unlock(); } void Brain::execute() { //Dont start doing anything until startAct has been called m_cMutualExclusionPrimary.lock(); //Dont start doing anything until startAct has been called m_cConditionVariable.wait(); //Unlock since we need it elsewhere m_cMutualExclusionPrimary.unlock(); //Always check before run that the selected tree is valid if (m_cBehavior == NULL) { std::cerr << BRAIN_NO_SELECTED_BEHAVIOR_ERROR << std::endl; std::cerr << BRAIN_INVALID_SHUTTING_DOWN << std::endl; return; } while (true) { // m_cMutualExclusionSecondary.lock(); //Always tick the behavior tree m_cBehavior->tick(); // m_cMutualExclusionSecondary.unlock(); } } void Brain::perform(const Instruction &cInstruction) { //Add it to the queue m_qInstructionWaitingQueue.push(&cInstruction); } void Brain::waitBodyStateUpdate() { m_dIsBodyStateUpdate = 1; } void Brain::waitSeeStateUpdate() { m_dIsSeeStateUpdate = 1; } void Brain::waitTeamStateUpdate() { m_dIsTeamStateUpdate = 1; } void Brain::updateState(const State &cState) { double dDifference = 1.f/WAIT_UPDATES; switch (cState.eType) { case StateTypeBody: m_dIsBodyStateUpdate -= dDifference; break; case StateTypeSee: m_dIsSeeStateUpdate -= dDifference; break; case StateTypeTeam: m_dIsTeamStateUpdate -= dDifference; break; default: break; } } void Brain::startAct() { /* * Dont broadcast if any of the flags * still on (tree building should take that in mind) */ if (m_dIsBodyStateUpdate > 0 || m_dIsSeeStateUpdate > 0 || m_dIsTeamStateUpdate > 0) { return; } //Continue as normal (per every update) #if DEBUG_PRINT_EXECUTION_INDEX static int iExcIndex = 0; //Mainly used to compare updates vs server cycles std::cout << DEBUG_PRINT_EXECUTION_INDEX_MESSAGE << ++iExcIndex << std::endl; #endif //Remove any waiting thread in this object m_cConditionVariable.broadcast(); } void Brain::executeAct() { //Check if there is something to execute if (!m_qInstructionWaitingQueue.empty()) { #if DEBUG_PRINT_ACTION std::cout << EXECUTE_ACTION_DESCRIPTION << std::endl; #endif //Prevent duplicate code endAct(); } } /**************************************************************************************************** * function name: endAct * * The Input: none * * The output: double * * The Function Opertion: Checks if instructions are available from the player. If so, takes * * it and adds it to the sent string, and appends any other instruction. * * if more than one unique (a special insturction that can be called only * * once per cycle) is present, make an error and fail to send (this needs * * to handled manually in the player inhereted function implementation). * * *************************************************************************************************/ void Brain::endAct() { //Put a lock on the thread m_cMutualExclusionPrimary.lock(); //Put all of the waiting instructions to the threaded queue (will start process elsewhere) if (!m_qInstructionWaitingQueue.empty()) { //Avoid multiple copies std::string *strToTransmit = new std::string; unsigned int uiValidCounter = 0; //Append all instructions and send them while (!m_qInstructionWaitingQueue.empty()) { const Instruction* cInsToTransmit = m_qInstructionWaitingQueue.front(); m_qInstructionWaitingQueue.pop(); //If there is a single cycle instruction, add it to the counter if (!cInsToTransmit->isAttachable()) ++uiValidCounter; //Append the strings strToTransmit->append(cInsToTransmit->getInstruction()); delete cInsToTransmit; } //Check if the (parsed) instructions are valid if (uiValidCounter > BRAIN_UNIQUE_INSTRUCTION_PER_MESSAGE) std::cerr << BRAIN_TOO_MANY_UNIQUE_INSTRUCTIONS_ERROR << std::endl; else { //Get the resulting string to the server m_qInstructionQueue.push(strToTransmit); } } //Wait after sending the instructions m_cConditionVariable.wait(); //Unlock after wait has been released m_cMutualExclusionPrimary.unlock(); }
26.817164
105
0.581606
MaximV88
afdec9682e913ea9d7f6e66027d6adb41bf38a08
1,128
cpp
C++
codes/UVA/00001-00999/uva586.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/UVA/00001-00999/uva586.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/UVA/00001-00999/uva586.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 105; int a[maxn]; char order[maxn]; void dfs (int n, int k) { int op = 0, x; while (scanf("%s", order) == 1 && strcmp(order, "END") ) { if (strcmp(order, "LOOP") == 0) { scanf("%s", order); if (strcmp(order, "n") == 0) dfs(n+1, k); else { sscanf(order, "%d", &x); dfs(n, k * x); } } else if (strcmp(order, "OP") == 0) { scanf("%d", &x); op += x; } } a[n] += op * k; } void put (int i, int flag) { if (a[i] == 0) return; if (flag) printf("+"); if (a[i] > 1 && i) printf("%d*", a[i]); else if (i == 0) printf("%d", a[i]); if (i) printf("n"); if (i > 1) printf("^%d", i); } int main () { int cas; scanf("%d", &cas); for (int kcas = 1; kcas <= cas; kcas++) { memset(a, 0, sizeof(a)); scanf("%s", order); dfs(0, 1); int mv = 10; while (mv >= 0 && a[mv] == 0) mv--; printf("Program #%d\nRuntime = ", kcas); if (mv != -1) { put(mv, 0); for (int i = mv-1; i >= 0; i--) put(i, 1); } else printf("0"); printf("\n\n"); } return 0; }
14.842105
59
0.468972
JeraKrs
afe5dd7662ac5a986609d9553cde0cb521c962f0
1,171
cpp
C++
src/planning/RrtNode.cpp
brychanrobot/orrt-star-ros
f3dd3f2e973229fe179c785ea464e5f751f6c2a5
[ "MIT" ]
3
2017-10-19T07:32:36.000Z
2018-11-10T14:03:25.000Z
src/planning/RrtNode.cpp
brychanrobot/orrt-star-ros
f3dd3f2e973229fe179c785ea464e5f751f6c2a5
[ "MIT" ]
null
null
null
src/planning/RrtNode.cpp
brychanrobot/orrt-star-ros
f3dd3f2e973229fe179c785ea464e5f751f6c2a5
[ "MIT" ]
1
2019-12-09T13:27:49.000Z
2019-12-09T13:27:49.000Z
#include "RrtNode.hpp" using namespace std; RrtNode::RrtNode(Coord coord, shared_ptr<RrtNode> parent, double cumulativeCost) : Node(coord, parent) { this->cumulativeCost = cumulativeCost; } bool RrtNode::operator<(shared_ptr<RrtNode> rhs) { return this->heuristic < rhs->heuristic; } void RrtNode::addChild(shared_ptr<RrtNode> child, double cost) { this->children.push_back(child); child->parent = shared_from_this(); child->cumulativeCost = this->cumulativeCost + cost; } void RrtNode::rewire(shared_ptr<RrtNode> newParent, double cost) { if (this->parent) { this->parent->removeChild(shared_from_this()); } newParent->children.push_back(shared_from_this()); this->parent = newParent; this->updateCumulativeCost(newParent->cumulativeCost + cost); } void RrtNode::updateCumulativeCost(double newCumulativeCost) { auto oldCumulativeCost = this->cumulativeCost; this->cumulativeCost = newCumulativeCost; for (const shared_ptr<Node>& childBase : this->children) { auto child = static_pointer_cast<RrtNode>(childBase); auto costToParent = child->cumulativeCost - oldCumulativeCost; child->updateCumulativeCost(newCumulativeCost + costToParent); } }
35.484848
145
0.766866
brychanrobot
afe751cff19415f82b13f363694fd4c33df6dc7b
1,367
cpp
C++
aws-cpp-sdk-wellarchitected/source/model/ListLensSharesResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-wellarchitected/source/model/ListLensSharesResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-wellarchitected/source/model/ListLensSharesResult.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/wellarchitected/model/ListLensSharesResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::WellArchitected::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ListLensSharesResult::ListLensSharesResult() { } ListLensSharesResult::ListLensSharesResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } ListLensSharesResult& ListLensSharesResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("LensShareSummaries")) { Array<JsonView> lensShareSummariesJsonList = jsonValue.GetArray("LensShareSummaries"); for(unsigned lensShareSummariesIndex = 0; lensShareSummariesIndex < lensShareSummariesJsonList.GetLength(); ++lensShareSummariesIndex) { m_lensShareSummaries.push_back(lensShareSummariesJsonList[lensShareSummariesIndex].AsObject()); } } if(jsonValue.ValueExists("NextToken")) { m_nextToken = jsonValue.GetString("NextToken"); } return *this; }
27.34
138
0.769568
perfectrecall
afe780183b01514917bd117c7f56fc56b11f1f96
446
cpp
C++
test/Math/FFT/fft_test.cpp
YanagiAyame/AlgorithmLibrary
2769c41e0e51218072f78772d1f11a92465838e4
[ "Unlicense" ]
null
null
null
test/Math/FFT/fft_test.cpp
YanagiAyame/AlgorithmLibrary
2769c41e0e51218072f78772d1f11a92465838e4
[ "Unlicense" ]
null
null
null
test/Math/FFT/fft_test.cpp
YanagiAyame/AlgorithmLibrary
2769c41e0e51218072f78772d1f11a92465838e4
[ "Unlicense" ]
1
2020-02-09T17:22:04.000Z
2020-02-09T17:22:04.000Z
#define PROBLEM "https://atcoder.jp/contests/atc001/tasks/fft_c" #include <src/Math/FFT/fft.hpp> #include <complex> #include <iostream> #include <vector> int main() { int n; std::cin >> n; std::vector<std::complex<double>> v(n + 1), w(n + 1); for (int i = 1; i <= n; ++i) { std::cin >> v[i] >> w[i]; } auto ans = Convolution(v, w); for (int i = 1; i <= 2 * n; ++i) { std::cout << (long long)(ans[i].real() + 0.1) << std::endl; } }
20.272727
64
0.560538
YanagiAyame
afeb4311d72bf36bc4a8e7a638fe641ecb85c46d
77
hpp
C++
Firmware/firmware_tests/stubs/interfaces/spi/mocked_spi.hpp
ValentiWorkLearning/GradWork
70bb5a629df056a559bae3694b47a2e5dc98c23b
[ "MIT" ]
39
2019-10-23T12:06:16.000Z
2022-01-26T04:28:29.000Z
Firmware/firmware_tests/stubs/interfaces/spi/mocked_spi.hpp
ValentiWorkLearning/GradWork
70bb5a629df056a559bae3694b47a2e5dc98c23b
[ "MIT" ]
20
2020-03-21T20:21:46.000Z
2021-11-19T14:34:03.000Z
Firmware/firmware_tests/stubs/interfaces/spi/mocked_spi.hpp
ValentiWorkLearning/GradWork
70bb5a629df056a559bae3694b47a2e5dc98c23b
[ "MIT" ]
7
2019-10-18T09:44:10.000Z
2021-06-11T13:05:16.000Z
#pragma once namespace Mocked::Interface { } // namespace Mocked::Interface
12.833333
32
0.753247
ValentiWorkLearning
afef1da6f97c951d69bc14d8136683adc00155c5
1,257
cpp
C++
classes/ftest10read.cpp
angusoutlook/OOProgrammingInCpp
42c66b2652d4814e4f8b31d060189bd853cce416
[ "FSFAP" ]
null
null
null
classes/ftest10read.cpp
angusoutlook/OOProgrammingInCpp
42c66b2652d4814e4f8b31d060189bd853cce416
[ "FSFAP" ]
null
null
null
classes/ftest10read.cpp
angusoutlook/OOProgrammingInCpp
42c66b2652d4814e4f8b31d060189bd853cce416
[ "FSFAP" ]
null
null
null
/* The following code example is taken from the book * "Object-Oriented Programming in C++" * by Nicolai M. Josuttis, Wiley, 2002 * * (C) Copyright Nicolai M. Josuttis 2002. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ CPPBook::Fraction readFraction() { CPPBook::Fraction x; // fraction variable bool error; // error occurred? do { error = false; // no error yet /* try to read the fraction x and catch * errors of the type DenomIsZero */ try { std::cout << "enter fraction (numer/denom): "; std::cin >> x; std::cout << "input was: " << x << std::endl; } catch (const CPPBook::Fraction::DenomIsZero&) { /* output error message and continue the loop */ std::cout << "input error: numerator can not be zero" << std::endl; error = true; } } while (error); return x; // return read fraction }
33.078947
69
0.571201
angusoutlook
aff55e9ee0db0a480ad7d2bc87e985a280b4e51d
5,975
hh
C++
src/common/types.hh
danieldeankon/hypertrace
d58a6ea28af45b875c477df4065667e9b4b88a49
[ "MIT" ]
null
null
null
src/common/types.hh
danieldeankon/hypertrace
d58a6ea28af45b875c477df4065667e9b4b88a49
[ "MIT" ]
null
null
null
src/common/types.hh
danieldeankon/hypertrace
d58a6ea28af45b875c477df4065667e9b4b88a49
[ "MIT" ]
null
null
null
#pragma once #ifdef OPENCL typedef uchar uint8_t; typedef char int8_t; typedef ushort uint16_t; typedef short int16_t; typedef uint uint32_t; typedef int int32_t; #define make_int2 (int2) #define make_int3 (int3) #define make_int4 (int4) #define make_uint2 (uint2) #define make_uint3 (uint3) #define make_uint4 (uint4) #define make_float2 (float2) #define make_float3 (float3) #define make_float4 (float4) #ifdef OPENCL_INTEROP typedef uchar uchar_pk; typedef char char_pk; typedef ushort ushort_pk; typedef short short_pk; typedef uint uint_pk; typedef int int_pk; typedef float float_pk; #define pack_float(x) ((float_pk)(x)) #define unpack_float(x) ((float)(x)) #define DEF_VEC_PACK(type, n, size) \ typedef struct { type s[size]; } type##n##_pk; \ type##n##_pk pack_##type##n(type##n v) { type##n##_pk p; vstore##n(v, 0, p.s); return p; } \ type##n unpack_##type##n(type##n##_pk p) { return vload##n(0, p.s); } #define DEF_VEC_PACK_234(type) \ DEF_VEC_PACK(type, 2, 2) \ DEF_VEC_PACK(type, 3, 4) \ DEF_VEC_PACK(type, 4, 4) DEF_VEC_PACK_234(int) DEF_VEC_PACK_234(uint) DEF_VEC_PACK_234(float) #endif // OPENCL_INTEROP #else // OPENCL #include <stdint.h> #include <stdbool.h> #include <vec.hpp> #define __global #define __local #define __constant const typedef unsigned char uchar; typedef unsigned short ushort; typedef unsigned int uint; typedef vec<char, 2> char2; typedef vec<char, 3> char3; typedef vec<char, 4> char4; typedef vec<uchar, 2> uchar2; typedef vec<uchar, 3> uchar3; typedef vec<uchar, 4> uchar4; typedef vec<short, 2> short2; typedef vec<short, 3> short3; typedef vec<short, 4> short4; typedef vec<ushort, 2> ushort2; typedef vec<ushort, 3> ushort3; typedef vec<ushort, 4> ushort4; typedef vec<int, 2> int2; typedef vec<int, 3> int3; typedef vec<int, 4> int4; typedef vec<uint, 2> uint2; typedef vec<uint, 3> uint3; typedef vec<uint, 4> uint4; typedef vec<float, 2> float2; typedef vec<float, 3> float3; typedef vec<float, 4> float4; typedef vec<double, 2> double2; typedef vec<double, 3> double3; typedef vec<double, 4> double4; #define make_int2 int2 #define make_int3 int3 #define make_int4 int4 #define make_uint2 uint2 #define make_uint3 uint3 #define make_uint4 uint4 #define make_float2 float2 #define make_float3 float3 #define make_float4 float4 #define make_double2 double2 #define make_double3 double3 #define make_double4 double4 #define convert_int2(x) (x).cast<int>() #define convert_int3(x) (x).cast<int>() #define convert_int4(x) (x).cast<int>() #define convert_uint2(x) (x).cast<uint>() #define convert_uint3(x) (x).cast<uint>() #define convert_uint4(x) (x).cast<uint>() #define convert_float2(x) (x).cast<float>() #define convert_float3(x) (x).cast<float>() #define convert_float4(x) (x).cast<float>() #define convert_double2(x) (x).cast<double>() #define convert_double3(x) (x).cast<double>() #define convert_double4(x) (x).cast<double>() #ifdef OPENCL_INTEROP #include <CL/cl.h> typedef cl_uchar uchar_pk; typedef cl_char char_pk; typedef cl_ushort ushort_pk; typedef cl_short short_pk; typedef cl_uint uint_pk; typedef cl_int int_pk; typedef cl_float float_pk; typedef float_pk double_pk; typedef cl_int2 int2_pk; typedef cl_int3 int3_pk; typedef cl_int4 int4_pk; typedef cl_uint2 uint2_pk; typedef cl_uint3 uint3_pk; typedef cl_uint4 uint4_pk; typedef cl_float2 float2_pk; typedef cl_float3 float3_pk; typedef cl_float4 float4_pk; typedef float2_pk double2_pk; typedef float3_pk double3_pk; typedef float4_pk double4_pk; #define pack_float(x) ((float_pk)(x)) #define unpack_float(x) ((float)(x)) #define pack_double(x) ((double_pk)(x)) #define unpack_double(x) ((double)(x)) template <typename T, typename P, int N> P pack_vectype(T t) { P p; for (int i = 0; i < N; ++i) { p.s[i] = t[i]; } return p; } template <typename T, typename P, int N> T unpack_vectype(P p) { T t; for (int i = 0; i < N; ++i) { t[i] = p.s[i]; } return t; } #define pack_int2 pack_vectype<uint2, uint2_pk, 2> #define pack_int3 pack_vectype<uint3, uint3_pk, 3> #define pack_int4 pack_vectype<uint4, uint4_pk, 4> #define unpack_int2 unpack_vectype<uint2, uint2_pk, 2> #define unpack_int3 unpack_vectype<uint3, uint3_pk, 3> #define unpack_int4 unpack_vectype<uint4, uint4_pk, 4> #define pack_uint2 pack_vectype<int2, int2_pk, 2> #define pack_uint3 pack_vectype<int3, int3_pk, 3> #define pack_uint4 pack_vectype<int4, int4_pk, 4> #define unpack_uint2 unpack_vectype<int2, int2_pk, 2> #define unpack_uint3 unpack_vectype<int3, int3_pk, 3> #define unpack_uint4 unpack_vectype<int4, int4_pk, 4> #define pack_float2 pack_vectype<float2, float2_pk, 2> #define pack_float3 pack_vectype<float3, float3_pk, 3> #define pack_float4 pack_vectype<float4, float4_pk, 4> #define unpack_float2 unpack_vectype<float2, float2_pk, 2> #define unpack_float3 unpack_vectype<float3, float3_pk, 3> #define unpack_float4 unpack_vectype<float4, float4_pk, 4> inline double2_pk pack_double2(double2 v) { return pack_float2(v.cast<float>()); } inline double3_pk pack_double3(double3 v) { return pack_float3(v.cast<float>()); } inline double4_pk pack_double4(double4 v) { return pack_float4(v.cast<float>()); } inline double2 unpack_double2(double2_pk v) { return unpack_float2(v).cast<double>(); } inline double3 unpack_double3(double3_pk v) { return unpack_float3(v).cast<double>(); } inline double4 unpack_double4(double4_pk v) { return unpack_float4(v).cast<double>(); } #endif // OPENCL_INTEROP #endif // OPENCL #ifdef OPENCL_INTEROP #define _PACKED_ALIGNMENT_ 4 #define _PACKED_STRUCT_ATTRIBUTE_ __attribute__((packed, aligned(_PACKED_ALIGNMENT_))) #define _PACKED_FIELD_ATTRIBUTE_ __attribute__((packed, aligned(_PACKED_ALIGNMENT_))) #endif // OPENCL_INTEROP #define INTERPOLATE_FIELD(o, a, b, field, t) \ ((o).field = (a).field*(1 - (t)) + (b).field*(t)) inline int mod(int a, int b) { int r = a % b; return r >= 0 ? r : r + b; }
26.438053
92
0.737406
danieldeankon
aff6ddd67afbcd455688d9a6bff49471998d0f99
148
cpp
C++
Codeforces/Cards.cpp
canis-majoris123/CompetitiveProgramming
be6c208abe6e0bd748c3bb0e715787506d73588d
[ "MIT" ]
null
null
null
Codeforces/Cards.cpp
canis-majoris123/CompetitiveProgramming
be6c208abe6e0bd748c3bb0e715787506d73588d
[ "MIT" ]
null
null
null
Codeforces/Cards.cpp
canis-majoris123/CompetitiveProgramming
be6c208abe6e0bd748c3bb0e715787506d73588d
[ "MIT" ]
null
null
null
//https://codeforces.com/problemset/problem/1220/A #include<bits/stdc++.h> using namespace std; #define aakriti long long int int main() { }
18.5
51
0.702703
canis-majoris123
aff714228867d16a550671164fbb2bb322243060
1,343
hpp
C++
bulletgba/generator/data/code/daiouzyou/round_4_boss_1.hpp
pqrs-org/BulletGBA
a294007902970242b496f2528b4762cfef22bc86
[ "Unlicense" ]
5
2020-03-24T07:44:49.000Z
2021-08-30T14:43:31.000Z
bulletgba/generator/data/code/daiouzyou/round_4_boss_1.hpp
pqrs-org/BulletGBA
a294007902970242b496f2528b4762cfef22bc86
[ "Unlicense" ]
null
null
null
bulletgba/generator/data/code/daiouzyou/round_4_boss_1.hpp
pqrs-org/BulletGBA
a294007902970242b496f2528b4762cfef22bc86
[ "Unlicense" ]
null
null
null
#ifndef GENERATED_1e778d101ffc91be48d0fa7f5de68e83_HPP #define GENERATED_1e778d101ffc91be48d0fa7f5de68e83_HPP #include "bullet.hpp" void stepfunc_5aa98bab57516922045abb7f2c427635_67282d4d149d442e6a0edf83bf861696(BulletInfo *p); void stepfunc_e4547dce74c2f31cf07f256255486988_67282d4d149d442e6a0edf83bf861696(BulletInfo *p); void stepfunc_63b4654334aeda3a0ad7530b7a3c4e1e_67282d4d149d442e6a0edf83bf861696(BulletInfo *p); void stepfunc_f3aa7fee26dafd5f4f1a065c8ead4e21_67282d4d149d442e6a0edf83bf861696(BulletInfo *p); void stepfunc_e170367e74fd2935ce3aecc3f76bbd41_67282d4d149d442e6a0edf83bf861696(BulletInfo *p); void stepfunc_4fd9cb086608cf7afaae6eaa73a4e2bc_67282d4d149d442e6a0edf83bf861696(BulletInfo *p); void stepfunc_9a262eab9bee9a27b0f4b6d72eb6d017_67282d4d149d442e6a0edf83bf861696(BulletInfo *p); void stepfunc_a678d8bc571ed6f1d4e72f41bfaa998f_67282d4d149d442e6a0edf83bf861696(BulletInfo *p); extern const BulletStepFunc bullet_6286a9c6fec71a8d8045ecfeda8fdc69_67282d4d149d442e6a0edf83bf861696[]; const unsigned int bullet_6286a9c6fec71a8d8045ecfeda8fdc69_67282d4d149d442e6a0edf83bf861696_size = 44; extern const BulletStepFunc bullet_f1b866f583992e3b3fe9f83e142967fe_67282d4d149d442e6a0edf83bf861696[]; const unsigned int bullet_f1b866f583992e3b3fe9f83e142967fe_67282d4d149d442e6a0edf83bf861696_size = 2; #endif
55.958333
104
0.908414
pqrs-org
9b85bed7e052f21b6e18cb40b5d9bce010e42075
7,937
cpp
C++
stack.cpp
malaise/xfreecell
b44169ac15e82f7cbc5379f8ba8b818e9faab611
[ "Unlicense" ]
1
2021-05-01T16:29:08.000Z
2021-05-01T16:29:08.000Z
stack.cpp
malaise/xfreecell
b44169ac15e82f7cbc5379f8ba8b818e9faab611
[ "Unlicense" ]
null
null
null
stack.cpp
malaise/xfreecell
b44169ac15e82f7cbc5379f8ba8b818e9faab611
[ "Unlicense" ]
null
null
null
#include <cstdio> #ifdef SHAPE #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/extensions/shape.h> #endif #include "card.h" #include "freecell.h" #include "general.h" #include "option.h" #include "stack.h" #include "util.h" #ifdef SHAPE #include "boundingMask.bm" #include "clipMask.bm" #endif extern Display* dpy; extern Window gameWindow; extern Card* hilighted; extern bool cursorChanged; extern Cursor cursor; static unsigned int stackingHeight = 28; Stack::Stack(int x_ini, int y_ini) : NSWindow(true, gameWindow, x_ini - 1, y_ini - 1) { _next_x = x_ini; _next_y = y_ini; } Card* Stack::topCard() const { if (_cards.size() == 0) return 0; return _cards.back(); } // Nth card: 0 for bottom of the stack (front of the vector) Card* Stack::nthCard(unsigned int i) const { if (_cards.size() == 0) return 0; if (i >= _cards.size()) return 0; return _cards.at(_cards.size() - i - 1); } Card* Stack::popCard() { if (_cards.size() == 0) return 0; Card* tmp = _cards.back(); _cards.pop_back(); return tmp; } void Stack::initialize() { while (_cards.size() > 0) _cards.pop_back(); } // PlayStack PlayStack::PlayStack(int x_ini, int y_ini) : Stack(x_ini, y_ini) { resize(cardWidth, cardHeight * 20); background(getColor(dpy, DefaultBackground)); selectInput(ButtonPressMask | EnterWindowMask | LeaveWindowMask); map(); } void PlayStack::pushCard(Card* c) { Stack::pushCard(c); _next_y += stackingHeight; } Card* PlayStack::popCard() { if (size() == 0) return 0; _next_y -= stackingHeight; return Stack::popCard(); } bool PlayStack::acceptable(Card* c) const { if (size() == 0) return true; return topCard()->canBeParent(c); } void PlayStack::initialize() { _next_y -= stackingHeight * size(); Stack::initialize(); } void PlayStack::dispatchEvent(const XEvent& ev) { switch (ev.type) { case ButtonPress: dispatchButtonPress(ev); break; case EnterNotify: dispatchEnterNotify(); break; case LeaveNotify: dispatchLeaveNotify(); break; } } void PlayStack::dispatchButtonPress(const XEvent& ev) { if (hilighted == 0 || size() != 0 || !cursorChanged) return; if (Option::queryWindow()) { if (hilighted->parent() == 0) { //single hilighted->unhilighten(); hilighted->moveToStack(this); hilighted = 0; XUndefineCursor(dpy, window()); cursorChanged = false; } else { mapSingleOrMultiple(); if (singleButtonPressed()) { //single hilighted->unhilighten(); hilighted->moveToStack(this); hilighted = 0; XUndefineCursor(dpy, window()); cursorChanged = false; } else if (multipleButtonPressed()) { //multiple hilighted->unhilighten(); moveMultipleCards(hilighted, this); hilighted = 0; XUndefineCursor(dpy, window()); cursorChanged = false; } else fprintf(stderr, "Error in PlayStack::dispatchButtonPress()\n"); } } else { switch (ev.xbutton.button) { case 1: // single hilighted->unhilighten(); hilighted->moveToStack(this); XUndefineCursor(dpy, window()); cursorChanged = false; hilighted = 0; break; case 3: if (hilighted->parent() == 0) { //single hilighted->unhilighten(); hilighted->moveToStack(this); XUndefineCursor(dpy, window()); cursorChanged = false; hilighted = 0; } else { hilighted->unhilighten(); moveMultipleCards(hilighted, this); XUndefineCursor(dpy, window()); cursorChanged = false; hilighted = 0; } break; } } } void PlayStack::dispatchEnterNotify() { if (hilighted != 0 && size() == 0) { XDefineCursor(dpy, window(), cursor); cursorChanged = true; } } void PlayStack::dispatchLeaveNotify() { if (cursorChanged) { XUndefineCursor(dpy, window()); cursorChanged = false; } } //SingleStack SingleStack::SingleStack(int x_ini, int y_ini) : Stack(x_ini, y_ini) { resize(cardWidth, cardHeight); background(getColor(dpy, "darkgreen")); border(getColor(dpy, "green")); borderWidth(1); selectInput(ButtonPressMask | EnterWindowMask | LeaveWindowMask); map(); } Card* SingleStack::popCard() { if (size() == 0) return 0; return Stack::popCard(); } bool SingleStack::acceptable(Card* c __attribute__ ((unused)) ) const { if (size() == 0) return true; return false; } void SingleStack::dispatchButtonPress() { if (hilighted == 0) return; if (acceptable(hilighted)) { hilighted->unhilighten(); hilighted->moveToStack(this); hilighted = 0; } } void SingleStack::dispatchEnterNotify() { if (hilighted != 0 && size() == 0) { XDefineCursor(dpy, window(), cursor); cursorChanged = true; } } void SingleStack::dispatchLeaveNotify() { if (cursorChanged) { XUndefineCursor(dpy, window()); cursorChanged = false; } } void SingleStack::dispatchEvent(const XEvent& ev) { switch (ev.type) { case ButtonPress: dispatchButtonPress(); break; case EnterNotify: dispatchEnterNotify(); break; case LeaveNotify: dispatchLeaveNotify(); break; } } //DoneStack #ifdef SHAPE static Pixmap clipMask = 0; static Pixmap boundingMask = 0; static bool initialized = false; #endif static char bitmap[bmWidth * (cardHeight - 2)]; DoneStack::DoneStack(int x_ini, int y_ini, Suit s) : Stack(x_ini, y_ini) { #ifdef SHAPE if (Option::roundCard() && !initialized) { boundingMask = XCreateBitmapFromData(dpy, RootWindow(dpy, 0), (char*) boundingMask_bits, boundingMask_width, boundingMask_height); clipMask = XCreateBitmapFromData(dpy, RootWindow(dpy, 0), (char*) clipMask_bits, clipMask_width, clipMask_height); initialized = true; } #endif _suit = s; unsigned long fore, back; Pixmap bgpixmap; if (suitColor(s) == RedSuit) fore = getColor(dpy, "red"); else fore = getColor(dpy, "black"); back = WhitePixel(dpy, 0); makeOneSymbolBitmap(s, bitmap); bgpixmap = XCreatePixmapFromBitmapData(dpy, gameWindow, bitmap, cardWidth - 2, cardHeight - 2, fore, back, DefaultDepth(dpy, DefaultScreen(dpy))); resize(cardWidth, cardHeight); backgroundPixmap(bgpixmap); border(getColor(dpy, "black")); borderWidth(1); selectInput(ButtonPressMask | EnterWindowMask | LeaveWindowMask); #ifdef SHAPE if (Option::roundCard()) { XShapeCombineMask(dpy, window(), ShapeBounding, 0, 0, boundingMask, ShapeSet); XShapeCombineMask(dpy, window(), ShapeClip, 0, 0, clipMask, ShapeSet); } #endif map(); } void DoneStack::pushCard(Card* c) { c->removed(); Stack::pushCard(c); } Card* DoneStack::popCard() { if (size() == 0) return 0; // fprintf(stderr, "Can't pop\n"); // exit(1); Card *c = Stack::popCard(); c->undone(); return c; } bool DoneStack::acceptable(Card* c) const { if (c == 0) return false; if (size() == 0) { if ((c->suit() == _suit) && (c->value() == 0)) // Ace return true; else return false; } if ((c->suit() == _suit) && (c->value() == topCard()->value() + 1)) return true; return false; } void DoneStack::dispatchEvent(const XEvent& ev) { if (hilighted == 0) return; switch (ev.type) { case ButtonPress: if (acceptable(hilighted)) { hilighted->unhilighten(); hilighted->moveToStack(this); hilighted = 0; if (cursorChanged) { XUndefineCursor(dpy, window()); cursorChanged = false; } } break; case EnterNotify: if (acceptable(hilighted)) { XDefineCursor(dpy, window(), cursor); cursorChanged = true; } break; case LeaveNotify: if (cursorChanged) { XUndefineCursor(dpy, window()); cursorChanged = false; } } }
21.05305
93
0.628449
malaise
9b88a0f21bf503848ae2f356eb16ba20c29c4673
907
cpp
C++
EndGame/EndGame/Src/SubSystems/RenderSubSystem/OpenGlContext.cpp
siddharthgarg4/EndGame
ba608714b3eacb5dc05d0c852db573231c867d8b
[ "MIT" ]
null
null
null
EndGame/EndGame/Src/SubSystems/RenderSubSystem/OpenGlContext.cpp
siddharthgarg4/EndGame
ba608714b3eacb5dc05d0c852db573231c867d8b
[ "MIT" ]
null
null
null
EndGame/EndGame/Src/SubSystems/RenderSubSystem/OpenGlContext.cpp
siddharthgarg4/EndGame
ba608714b3eacb5dc05d0c852db573231c867d8b
[ "MIT" ]
null
null
null
// // OpenGlContext.cpp // // // Created by Siddharth on 05/06/20. // #include "OpenGlContext.hpp" #include <glad/glad.h> namespace EndGame { OpenGlContext::OpenGlContext(GLFWwindow *windowHandle) : windowHandle(windowHandle) { EG_ENGINE_ASSERT(windowHandle, "Window handle cannot be null") } void OpenGlContext::init() { glfwMakeContextCurrent(windowHandle); //init glad __unused int gladInitSuccess = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); EG_ENGINE_ASSERT(gladInitSuccess, "Could not intialize Glad!"); EG_ENGINE_INFO("OpenGL Info:"); EG_ENGINE_INFO("vendor: {0}", glGetString(GL_VENDOR)); EG_ENGINE_INFO("renderer: {0}", glGetString(GL_RENDERER)); EG_ENGINE_INFO("version: {0}", glGetString(GL_VERSION)); } void OpenGlContext::swapBuffers() { glfwSwapBuffers(windowHandle); } }
29.258065
90
0.679162
siddharthgarg4
9b910255eb107185c8417d1e03c8d7dd6d978018
212
cpp
C++
source/dodbm/builders/delete_data.cpp
WopsS/dodbm
053f0a6b90e1e081b07418a91cf1f3420d69e390
[ "MIT" ]
1
2021-02-19T07:22:21.000Z
2021-02-19T07:22:21.000Z
source/dodbm/builders/delete_data.cpp
WopsS/dodbm
053f0a6b90e1e081b07418a91cf1f3420d69e390
[ "MIT" ]
null
null
null
source/dodbm/builders/delete_data.cpp
WopsS/dodbm
053f0a6b90e1e081b07418a91cf1f3420d69e390
[ "MIT" ]
null
null
null
#include <dodbm/builders/delete_data.hpp> const dodbm::builders::delete_data& dodbm::builders::delete_data::from(const std::string& table_name) const { m_operation->set_table(table_name); return *this; }
30.285714
107
0.754717
WopsS
9b949a8381fb00a020fc93639e1488f89fd42d29
217
cpp
C++
Libraries/LibHTML/DOM/HTMLHeadingElement.cpp
JamiKettunen/serenity
232da5cc188496f570ef55276a897f1095509c87
[ "BSD-2-Clause" ]
3
2020-05-01T02:39:03.000Z
2021-11-26T08:34:54.000Z
Libraries/LibHTML/DOM/HTMLHeadingElement.cpp
JamiKettunen/serenity
232da5cc188496f570ef55276a897f1095509c87
[ "BSD-2-Clause" ]
null
null
null
Libraries/LibHTML/DOM/HTMLHeadingElement.cpp
JamiKettunen/serenity
232da5cc188496f570ef55276a897f1095509c87
[ "BSD-2-Clause" ]
1
2021-08-03T13:04:49.000Z
2021-08-03T13:04:49.000Z
#include <LibHTML/DOM/HTMLHeadingElement.h> HTMLHeadingElement::HTMLHeadingElement(Document& document, const String& tag_name) : HTMLElement(document, tag_name) { } HTMLHeadingElement::~HTMLHeadingElement() { }
19.727273
82
0.78341
JamiKettunen
9b977c64be8d76406cf37c9dd5efe5afe8a427da
22,827
cpp
C++
libmultidisplay/native/MultiDisplayService.cpp
zenfone-6/android_device_asus_a600cg
1073b3cae60b0e877c47f33048a7979bf3a96428
[ "Apache-2.0" ]
1
2021-11-21T21:45:36.000Z
2021-11-21T21:45:36.000Z
libmultidisplay/native/MultiDisplayService.cpp
zenfone-6/android_device_asus_a600cg
1073b3cae60b0e877c47f33048a7979bf3a96428
[ "Apache-2.0" ]
null
null
null
libmultidisplay/native/MultiDisplayService.cpp
zenfone-6/android_device_asus_a600cg
1073b3cae60b0e877c47f33048a7979bf3a96428
[ "Apache-2.0" ]
6
2016-03-01T16:25:22.000Z
2022-03-02T03:54:14.000Z
/* * Copyright (c) 2012-2013, Intel Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: tianyang.zhu@intel.com */ //#define LOG_NDEBUG 0 #include <utils/Log.h> #include <utils/Errors.h> #include <binder/IServiceManager.h> #include <binder/IPCThreadState.h> #include <display/MultiDisplayService.h> #include "MultiDisplayComposer.h" namespace android { namespace intel { #define MDC_CHECK_OBJECT(OBJECT, ERR) \ do { \ if (OBJECT == NULL) { \ ALOGE("%s: a non-instantiated object", __func__); \ return ERR; \ } \ ALOGV("Entering %s", __func__);\ } while(0) #define IMPLEMENT_API_0(CLASS, OBJECT, INTERFACE, RETURN, ERR) \ RETURN CLASS::INTERFACE() { \ MDC_CHECK_OBJECT(OBJECT, ERR); \ return OBJECT->INTERFACE(); \ } #define IMPLEMENT_API_1(CLASS, OBJECT, INTERFACE, PARAM0, RETURN, ERR) \ RETURN CLASS::INTERFACE(PARAM0 p0) { \ MDC_CHECK_OBJECT(OBJECT, ERR); \ return OBJECT->INTERFACE(p0); \ } #define IMPLEMENT_API_2(CLASS, OBJECT, INTERFACE, PARAM0, PARAM1, RETURN, ERR) \ RETURN CLASS::INTERFACE(PARAM0 p0, PARAM1 p1) { \ MDC_CHECK_OBJECT(OBJECT, ERR); \ return OBJECT->INTERFACE(p0, p1); \ } #define IMPLEMENT_API_3(CLASS, OBJECT, INTERFACE, PARAM0, PARAM1, PARAM2, RETURN, ERR) \ RETURN CLASS::INTERFACE(PARAM0 p0, PARAM1 p1, PARAM2 p2) { \ MDC_CHECK_OBJECT(OBJECT, ERR); \ return OBJECT->INTERFACE(p0, p1, p2); \ } #define IMPLEMENT_API_4(CLASS, OBJECT, INTERFACE, PARAM0, PARAM1, PARAM2, PARAM3, RETURN, ERR) \ RETURN CLASS::INTERFACE(PARAM0 p0, PARAM1 p1, PARAM2 p2, PARAM3 p3) { \ MDC_CHECK_OBJECT(OBJECT, ERR); \ return OBJECT->INTERFACE(p0, p1, p2, p3); \ } #define IMPLEMENT_API_7(CLASS, OBJECT, INTERFACE, PARAM0, PARAM1, PARAM2, PARAM3, PARAM4, PARAM5, PARAM6, RETURN, ERR) \ RETURN CLASS::INTERFACE(PARAM0 p0, PARAM1 p1, PARAM2 p2, PARAM3 p3, PARAM4 p4, PARAM5 p5, PARAM6 p6) { \ MDC_CHECK_OBJECT(OBJECT, ERR); \ return OBJECT->INTERFACE(p0, p1, p2, p3, p4, p5, p6); \ } class MultiDisplayHdmiControlImpl : public BnMultiDisplayHdmiControl { private: sp<MultiDisplayComposer> pCom; static sp<MultiDisplayHdmiControlImpl> sHdmiInstance; public: MultiDisplayHdmiControlImpl(const sp<MultiDisplayComposer>& com); int getCurrentHdmiTimingIndex(); int getHdmiTimingCount(); status_t setHdmiTiming(const MDSHdmiTiming&); status_t getHdmiTimingList(int, MDSHdmiTiming**); status_t getCurrentHdmiTiming(MDSHdmiTiming*); status_t setHdmiTimingByIndex(int); status_t setHdmiScalingType(MDS_SCALING_TYPE); status_t setHdmiOverscan(int, int); bool checkHdmiTimingIsFixed(); static sp<MultiDisplayHdmiControlImpl> getInstance() { return sHdmiInstance; } }; // singleton sp<MultiDisplayHdmiControlImpl> MultiDisplayHdmiControlImpl::sHdmiInstance = NULL; MultiDisplayHdmiControlImpl::MultiDisplayHdmiControlImpl(const sp<MultiDisplayComposer>& com) { pCom = com; sHdmiInstance = this; } IMPLEMENT_API_0(MultiDisplayHdmiControlImpl, pCom, getHdmiTimingCount, status_t, NO_INIT) IMPLEMENT_API_0(MultiDisplayHdmiControlImpl, pCom, getCurrentHdmiTimingIndex, status_t, NO_INIT) IMPLEMENT_API_0(MultiDisplayHdmiControlImpl, pCom, checkHdmiTimingIsFixed, bool, false) IMPLEMENT_API_1(MultiDisplayHdmiControlImpl, pCom, setHdmiTiming, const MDSHdmiTiming&, status_t, NO_INIT) IMPLEMENT_API_1(MultiDisplayHdmiControlImpl, pCom, getCurrentHdmiTiming, MDSHdmiTiming*, status_t, NO_INIT) IMPLEMENT_API_1(MultiDisplayHdmiControlImpl, pCom, setHdmiScalingType, MDS_SCALING_TYPE, status_t, NO_INIT) IMPLEMENT_API_1(MultiDisplayHdmiControlImpl, pCom, setHdmiTimingByIndex, int, status_t, NO_INIT) IMPLEMENT_API_2(MultiDisplayHdmiControlImpl, pCom, setHdmiOverscan, int, int, status_t, NO_INIT) IMPLEMENT_API_2(MultiDisplayHdmiControlImpl, pCom, getHdmiTimingList, int, MDSHdmiTiming**, status_t, NO_INIT) // singleton class MultiDisplayVideoControlImpl : public BnMultiDisplayVideoControl { private: sp<MultiDisplayComposer> pCom; static sp<MultiDisplayVideoControlImpl> sVideoInstance; public: MultiDisplayVideoControlImpl(const sp<MultiDisplayComposer>& com); int allocateVideoSessionId(); status_t updateVideoState(int, MDS_VIDEO_STATE); status_t resetVideoPlayback(); status_t updateVideoSourceInfo(int, const MDSVideoSourceInfo&); static sp<MultiDisplayVideoControlImpl> getInstance() { return sVideoInstance; } }; // singleton sp<MultiDisplayVideoControlImpl> MultiDisplayVideoControlImpl::sVideoInstance = NULL; MultiDisplayVideoControlImpl::MultiDisplayVideoControlImpl(const sp<MultiDisplayComposer>& com) { pCom = com; sVideoInstance = this; } IMPLEMENT_API_0(MultiDisplayVideoControlImpl, pCom, resetVideoPlayback, status_t, NO_INIT) IMPLEMENT_API_0(MultiDisplayVideoControlImpl, pCom, allocateVideoSessionId, int, -1) IMPLEMENT_API_2(MultiDisplayVideoControlImpl, pCom, updateVideoState, int, MDS_VIDEO_STATE, status_t, NO_INIT) IMPLEMENT_API_2(MultiDisplayVideoControlImpl, pCom, updateVideoSourceInfo, int, const MDSVideoSourceInfo&, status_t, NO_INIT) class MultiDisplaySinkRegistrarImpl : public BnMultiDisplaySinkRegistrar { private: sp<MultiDisplayComposer> pCom; static sp<MultiDisplaySinkRegistrarImpl> sSinkInstance; public: MultiDisplaySinkRegistrarImpl(const sp<MultiDisplayComposer>& com); int32_t registerListener(const sp<IMultiDisplayListener>&, const char*, int); status_t unregisterListener(int32_t id); static sp<MultiDisplaySinkRegistrarImpl> getInstance() { return sSinkInstance; } }; // singleton sp<MultiDisplaySinkRegistrarImpl> MultiDisplaySinkRegistrarImpl::sSinkInstance = NULL; MultiDisplaySinkRegistrarImpl::MultiDisplaySinkRegistrarImpl(const sp<MultiDisplayComposer>& com) { pCom = com; sSinkInstance = this; } IMPLEMENT_API_1(MultiDisplaySinkRegistrarImpl, pCom, unregisterListener, int32_t, status_t, NO_INIT) IMPLEMENT_API_3(MultiDisplaySinkRegistrarImpl, pCom, registerListener, const sp<IMultiDisplayListener>&, const char*, int, int32_t, -1) class MultiDisplayCallbackRegistrarImpl : public BnMultiDisplayCallbackRegistrar { private: sp<MultiDisplayComposer> pCom; static sp<MultiDisplayCallbackRegistrarImpl> sCbInstance; public: MultiDisplayCallbackRegistrarImpl(const sp<MultiDisplayComposer>& com); status_t registerCallback(const sp<IMultiDisplayCallback>&); status_t unregisterCallback(const sp<IMultiDisplayCallback>&); static sp<MultiDisplayCallbackRegistrarImpl> getInstance() { return sCbInstance; } }; // singleton sp<MultiDisplayCallbackRegistrarImpl> MultiDisplayCallbackRegistrarImpl::sCbInstance = NULL; MultiDisplayCallbackRegistrarImpl::MultiDisplayCallbackRegistrarImpl(const sp<MultiDisplayComposer>& com) { pCom = com; sCbInstance = this; } IMPLEMENT_API_1(MultiDisplayCallbackRegistrarImpl, pCom, registerCallback, const sp<IMultiDisplayCallback>&, status_t, NO_INIT) IMPLEMENT_API_1(MultiDisplayCallbackRegistrarImpl, pCom, unregisterCallback, const sp<IMultiDisplayCallback>&, status_t, NO_INIT) class MultiDisplayInfoProviderImpl : public BnMultiDisplayInfoProvider { private: sp<MultiDisplayComposer> pCom; static sp<MultiDisplayInfoProviderImpl> sInfoInstance; public: MultiDisplayInfoProviderImpl(const sp<MultiDisplayComposer>& com); MDS_VIDEO_STATE getVideoState(int); uint32_t getVppState(); int getVideoSessionNumber(); MDS_DISPLAY_MODE getDisplayMode(bool); status_t getVideoSourceInfo(int, MDSVideoSourceInfo*); status_t getDecoderOutputResolution(int, int32_t* width, int32_t* height, int32_t* offX, int32_t* offY, int32_t* bufW, int32_t* bufH); static sp<MultiDisplayInfoProviderImpl> getInstance() { return sInfoInstance; } }; // singleton sp<MultiDisplayInfoProviderImpl> MultiDisplayInfoProviderImpl::sInfoInstance = NULL; MultiDisplayInfoProviderImpl::MultiDisplayInfoProviderImpl(const sp<MultiDisplayComposer>& com) { pCom = com; sInfoInstance = this; } IMPLEMENT_API_0(MultiDisplayInfoProviderImpl, pCom, getVideoSessionNumber, int, 0) IMPLEMENT_API_0(MultiDisplayInfoProviderImpl, pCom, getVppState, uint32_t, false) IMPLEMENT_API_1(MultiDisplayInfoProviderImpl, pCom, getVideoState, int, MDS_VIDEO_STATE, MDS_VIDEO_STATE_UNKNOWN) IMPLEMENT_API_1(MultiDisplayInfoProviderImpl, pCom, getDisplayMode, bool, MDS_DISPLAY_MODE, MDS_MODE_NONE) IMPLEMENT_API_2(MultiDisplayInfoProviderImpl, pCom, getVideoSourceInfo, int, MDSVideoSourceInfo*, status_t, NO_INIT) IMPLEMENT_API_7(MultiDisplayInfoProviderImpl, pCom, getDecoderOutputResolution, int, int32_t*, int32_t*, int32_t*, int32_t*, int32_t*, int32_t*, status_t, NO_INIT) class MultiDisplayEventMonitorImpl : public BnMultiDisplayEventMonitor { private: sp<MultiDisplayComposer> pCom; static sp<MultiDisplayEventMonitorImpl> sEventInstance; public: MultiDisplayEventMonitorImpl(const sp<MultiDisplayComposer>& com); status_t updatePhoneCallState(bool); status_t updateInputState(bool); static sp<MultiDisplayEventMonitorImpl> getInstance() { return sEventInstance; } }; // singleton sp<MultiDisplayEventMonitorImpl> MultiDisplayEventMonitorImpl::sEventInstance = NULL; MultiDisplayEventMonitorImpl::MultiDisplayEventMonitorImpl(const sp<MultiDisplayComposer>& com) { pCom = com; sEventInstance = this; } IMPLEMENT_API_1(MultiDisplayEventMonitorImpl, pCom, updatePhoneCallState, bool, status_t, NO_INIT) IMPLEMENT_API_1(MultiDisplayEventMonitorImpl, pCom, updateInputState, bool, status_t, NO_INIT) class MultiDisplayConnectionObserverImpl : public BnMultiDisplayConnectionObserver { private: sp<MultiDisplayComposer> pCom; static sp<MultiDisplayConnectionObserverImpl> sConnInstance; public: MultiDisplayConnectionObserverImpl(const sp<MultiDisplayComposer>& com); status_t updateWidiConnectionStatus(bool); status_t updateHdmiConnectionStatus(bool); static sp<MultiDisplayConnectionObserverImpl> getInstance() { return sConnInstance; } }; // singleton sp<MultiDisplayConnectionObserverImpl> MultiDisplayConnectionObserverImpl::sConnInstance = NULL; MultiDisplayConnectionObserverImpl::MultiDisplayConnectionObserverImpl(const sp<MultiDisplayComposer>& com) { pCom = com; sConnInstance = this; } IMPLEMENT_API_1(MultiDisplayConnectionObserverImpl, pCom, updateWidiConnectionStatus, bool, status_t, NO_INIT) IMPLEMENT_API_1(MultiDisplayConnectionObserverImpl, pCom, updateHdmiConnectionStatus, bool, status_t, NO_INIT) class MultiDisplayDecoderConfigImpl : public BnMultiDisplayDecoderConfig { private: sp<MultiDisplayComposer> pCom; static sp<MultiDisplayDecoderConfigImpl> sDecoderInstance; public: MultiDisplayDecoderConfigImpl(const sp<MultiDisplayComposer>& com); status_t setDecoderOutputResolution( int videoSessionId, int32_t width, int32_t height, int32_t offX, int32_t offY, int32_t bufW, int32_t bufH); static sp<MultiDisplayDecoderConfigImpl> getInstance() { return sDecoderInstance; } }; // singleton sp<MultiDisplayDecoderConfigImpl> MultiDisplayDecoderConfigImpl::sDecoderInstance = NULL; MultiDisplayDecoderConfigImpl::MultiDisplayDecoderConfigImpl(const sp<MultiDisplayComposer>& com) { pCom = com; sDecoderInstance = this; } IMPLEMENT_API_7(MultiDisplayDecoderConfigImpl, pCom, setDecoderOutputResolution, int, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, status_t, NO_INIT) class MultiDisplayVppConfigImpl : public BnMultiDisplayVppConfig { private: sp<MultiDisplayComposer> pCom; static sp<MultiDisplayVppConfigImpl> sVppInstance; public: MultiDisplayVppConfigImpl(const sp<MultiDisplayComposer>& com); status_t setVppState(MDS_DISPLAY_ID, bool, int); static sp<MultiDisplayVppConfigImpl> getInstance() { return sVppInstance; } }; // singleton sp<MultiDisplayVppConfigImpl> MultiDisplayVppConfigImpl::sVppInstance = NULL; MultiDisplayVppConfigImpl::MultiDisplayVppConfigImpl(const sp<MultiDisplayComposer>& com) { pCom = com; sVppInstance = this; } IMPLEMENT_API_3(MultiDisplayVppConfigImpl, pCom, setVppState, MDS_DISPLAY_ID, bool, int, status_t, NO_INIT) enum { MDS_SERVICE_GET_HDMI_CONTROL = IBinder::FIRST_CALL_TRANSACTION, MDS_SERVICE_GET_VIDEO_CONTROL, MDS_SERVICE_GET_EVENT_MONITOR, MDS_SERVICE_GET_CALLBACK_REGISTRAR, MDS_SERVICE_GET_SINK_REGISTRAR, MDS_SERVICE_GET_INFO_PROVIDER, MDS_SERVICE_GET_CONNECTION_OBSERVER, MDS_SERVICE_GET_DECODER_CONFIG, MDS_SERVICE_GET_VPP_CONFIG, }; class BpMDService : public BpInterface<IMDService> { public: BpMDService(const sp<IBinder>& impl) : BpInterface<IMDService>(impl) { } virtual sp<IMultiDisplayHdmiControl> getHdmiControl() { Parcel data, reply; data.writeInterfaceToken(IMDService::getInterfaceDescriptor()); status_t result = remote()->transact( MDS_SERVICE_GET_HDMI_CONTROL, data, &reply); if (result != NO_ERROR) ALOGE("Trasaction is fail"); return interface_cast<IMultiDisplayHdmiControl>(reply.readStrongBinder()); } virtual sp<IMultiDisplayVideoControl> getVideoControl() { Parcel data, reply; data.writeInterfaceToken(IMDService::getInterfaceDescriptor()); status_t result = remote()->transact( MDS_SERVICE_GET_VIDEO_CONTROL, data, &reply); if (result != NO_ERROR) ALOGE("Trasaction is fail"); return interface_cast<IMultiDisplayVideoControl>(reply.readStrongBinder()); } virtual sp<IMultiDisplayEventMonitor> getEventMonitor() { Parcel data, reply; data.writeInterfaceToken(IMDService::getInterfaceDescriptor()); status_t result = remote()->transact( MDS_SERVICE_GET_EVENT_MONITOR, data, &reply); if (result != NO_ERROR) ALOGE("Trasaction is fail"); return interface_cast<IMultiDisplayEventMonitor>(reply.readStrongBinder()); } virtual sp<IMultiDisplayCallbackRegistrar> getCallbackRegistrar() { Parcel data, reply; data.writeInterfaceToken(IMDService::getInterfaceDescriptor()); status_t result = remote()->transact( MDS_SERVICE_GET_CALLBACK_REGISTRAR, data, &reply); if (result != NO_ERROR) ALOGE("Trasaction is fail"); ALOGV("%s", __func__); return interface_cast<IMultiDisplayCallbackRegistrar>(reply.readStrongBinder()); } virtual sp<IMultiDisplaySinkRegistrar> getSinkRegistrar() { Parcel data, reply; ALOGV("%s, %d", __func__, __LINE__); data.writeInterfaceToken(IMDService::getInterfaceDescriptor()); status_t result = remote()->transact( MDS_SERVICE_GET_SINK_REGISTRAR, data, &reply); if (result != NO_ERROR) ALOGE("Trasaction is fail"); ALOGV("%s, %d", __func__, __LINE__); return interface_cast<IMultiDisplaySinkRegistrar>(reply.readStrongBinder()); } virtual sp<IMultiDisplayInfoProvider> getInfoProvider() { Parcel data, reply; data.writeInterfaceToken(IMDService::getInterfaceDescriptor()); status_t result = remote()->transact( MDS_SERVICE_GET_INFO_PROVIDER, data, &reply); if (result != NO_ERROR) ALOGE("Trasaction is fail"); return interface_cast<IMultiDisplayInfoProvider>(reply.readStrongBinder()); } virtual sp<IMultiDisplayConnectionObserver> getConnectionObserver() { Parcel data, reply; data.writeInterfaceToken(IMDService::getInterfaceDescriptor()); status_t result = remote()->transact( MDS_SERVICE_GET_CONNECTION_OBSERVER, data, &reply); if (result != NO_ERROR) ALOGE("Trasaction is fail"); return interface_cast<IMultiDisplayConnectionObserver>(reply.readStrongBinder()); } virtual sp<IMultiDisplayDecoderConfig> getDecoderConfig() { Parcel data, reply; data.writeInterfaceToken(IMDService::getInterfaceDescriptor()); status_t result = remote()->transact( MDS_SERVICE_GET_DECODER_CONFIG, data, &reply); if (result != NO_ERROR) ALOGE("Trasaction is fail"); return interface_cast<IMultiDisplayDecoderConfig>(reply.readStrongBinder()); } virtual sp<IMultiDisplayVppConfig> getVppConfig() { Parcel data, reply; data.writeInterfaceToken(IMDService::getInterfaceDescriptor()); status_t result = remote()->transact( MDS_SERVICE_GET_VPP_CONFIG, data, &reply); if (result != NO_ERROR) ALOGE("Trasaction is fail"); return interface_cast<IMultiDisplayVppConfig>(reply.readStrongBinder()); } }; IMPLEMENT_META_INTERFACE(MDService,"com.intel.MDService"); status_t BnMDService::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch (code) { case MDS_SERVICE_GET_HDMI_CONTROL: { CHECK_INTERFACE(IMDService, data, reply); sp<IBinder> b = this->getHdmiControl()->asBinder(); reply->writeStrongBinder(b); return NO_ERROR; } case MDS_SERVICE_GET_VIDEO_CONTROL: { CHECK_INTERFACE(IMDService, data, reply); sp<IBinder> b = this->getVideoControl()->asBinder(); reply->writeStrongBinder(b); return NO_ERROR; } case MDS_SERVICE_GET_EVENT_MONITOR: { CHECK_INTERFACE(IMDService, data, reply); sp<IBinder> b = this->getEventMonitor()->asBinder(); reply->writeStrongBinder(b); return NO_ERROR; } case MDS_SERVICE_GET_CALLBACK_REGISTRAR: { CHECK_INTERFACE(IMDService, data, reply); sp<IBinder> b = this->getCallbackRegistrar()->asBinder(); reply->writeStrongBinder(b); ALOGV("%s", __func__); return NO_ERROR; } case MDS_SERVICE_GET_SINK_REGISTRAR: { CHECK_INTERFACE(IMDService, data, reply); sp<IBinder> b = this->getSinkRegistrar()->asBinder(); reply->writeStrongBinder(b); ALOGV("%s", __func__); return NO_ERROR; } case MDS_SERVICE_GET_INFO_PROVIDER: { CHECK_INTERFACE(IMDService, data, reply); sp<IBinder> b = this->getInfoProvider()->asBinder(); reply->writeStrongBinder(b); return NO_ERROR; } case MDS_SERVICE_GET_CONNECTION_OBSERVER: { CHECK_INTERFACE(IMDService, data, reply); sp<IBinder> b = this->getConnectionObserver()->asBinder(); reply->writeStrongBinder(b); return NO_ERROR; } case MDS_SERVICE_GET_DECODER_CONFIG: { CHECK_INTERFACE(IMDService, data, reply); sp<IBinder> b = this->getDecoderConfig()->asBinder(); reply->writeStrongBinder(b); return NO_ERROR; } case MDS_SERVICE_GET_VPP_CONFIG: { CHECK_INTERFACE(IMDService, data, reply); sp<IBinder> b = this->getVppConfig()->asBinder(); reply->writeStrongBinder(b); return NO_ERROR; } default: return BBinder::onTransact(code, data, reply, flags); } // switch } MultiDisplayService::MultiDisplayService() { ALOGI("%s: create a MultiDisplay service %p", __func__, this); sp<MultiDisplayComposer> com = new MultiDisplayComposer(); new MultiDisplayHdmiControlImpl(com); new MultiDisplayVideoControlImpl(com); new MultiDisplayEventMonitorImpl(com); new MultiDisplayCallbackRegistrarImpl(com); new MultiDisplaySinkRegistrarImpl(com); new MultiDisplayInfoProviderImpl(com); new MultiDisplayConnectionObserverImpl(com); new MultiDisplayDecoderConfigImpl(com); new MultiDisplayVppConfigImpl(com); } MultiDisplayService::~MultiDisplayService() { ALOGV("%s: MultiDisplay service %p is destoryed", __func__, this); } void MultiDisplayService::instantiate() { sp<IServiceManager> sm(defaultServiceManager()); if (sm->addService(String16(INTEL_MDS_SERVICE_NAME),new MultiDisplayService())) ALOGE("Failed to start %s service", INTEL_MDS_SERVICE_NAME); } sp<IMultiDisplayHdmiControl> MultiDisplayService::getHdmiControl() { return MultiDisplayHdmiControlImpl::getInstance(); } sp<IMultiDisplayVideoControl> MultiDisplayService::getVideoControl() { return MultiDisplayVideoControlImpl::getInstance(); } sp<IMultiDisplayEventMonitor> MultiDisplayService::getEventMonitor() { return MultiDisplayEventMonitorImpl::getInstance(); } sp<IMultiDisplayCallbackRegistrar> MultiDisplayService::getCallbackRegistrar() { ALOGV("%s", __func__); return MultiDisplayCallbackRegistrarImpl::getInstance(); } sp<IMultiDisplaySinkRegistrar> MultiDisplayService::getSinkRegistrar() { ALOGV("%s", __func__); return MultiDisplaySinkRegistrarImpl::getInstance(); } sp<IMultiDisplayInfoProvider> MultiDisplayService::getInfoProvider() { return MultiDisplayInfoProviderImpl::getInstance(); } sp<IMultiDisplayConnectionObserver> MultiDisplayService::getConnectionObserver() { return MultiDisplayConnectionObserverImpl::getInstance(); } sp<IMultiDisplayDecoderConfig> MultiDisplayService::getDecoderConfig() { return MultiDisplayDecoderConfigImpl::getInstance(); } sp<IMultiDisplayVppConfig> MultiDisplayService::getVppConfig() { return MultiDisplayVppConfigImpl::getInstance(); } }; //namespace intel }; //namespace android
40.11775
163
0.718973
zenfone-6
9b9e42fb2d72aad7cda074e8dfa40b607ef8d8db
6,378
cpp
C++
Image And Video Processing/Lab/Lab01/exercise01/ColorTransformer.cpp
source-reference/digital-image-processing
dc90b569677b31dfeabfb8740a2d8b4ccb167ce9
[ "Apache-2.0" ]
null
null
null
Image And Video Processing/Lab/Lab01/exercise01/ColorTransformer.cpp
source-reference/digital-image-processing
dc90b569677b31dfeabfb8740a2d8b4ccb167ce9
[ "Apache-2.0" ]
null
null
null
Image And Video Processing/Lab/Lab01/exercise01/ColorTransformer.cpp
source-reference/digital-image-processing
dc90b569677b31dfeabfb8740a2d8b4ccb167ce9
[ "Apache-2.0" ]
null
null
null
#include "ColorTransformer.h" int ColorTransformer::ChangeBrighness(const Mat &sourceImage, Mat &destinationImage, short b) { if (sourceImage.empty()) { return -1; } int rows = sourceImage.rows; int cols = sourceImage.cols; int chanels = sourceImage.channels(); destinationImage = Mat(rows, cols, CV_MAKETYPE(CV_8U, chanels)); for (int i = 0; i < rows; i++) { const uchar *pRow = sourceImage.ptr<uchar>(i); uchar *destRow = destinationImage.ptr<uchar>(i); for (int j = 0; j < cols; j++, pRow += chanels, destRow += chanels) { for (int k = 0; k < chanels; k++) { int brighterValue = pRow[k] + b; destRow[k] = brighterValue > 255 ? 255 : brighterValue; } } } return 1; } int ColorTransformer::ChangeContrast(const Mat &sourceImage, Mat &destinationImage, float c) { if (sourceImage.empty()) { return -1; } int rows = sourceImage.rows; int cols = sourceImage.cols; int chanels = sourceImage.channels(); destinationImage = Mat(rows, cols, CV_MAKETYPE(CV_8U, chanels)); float f = (259 * (c + 255)) / (float)(255 * (259 - c)); for (int i = 0; i < rows; i++) { const uchar *pRow = sourceImage.ptr<uchar>(i); uchar *destRow = destinationImage.ptr<uchar>(i); for (int j = 0; j < cols; j++, pRow += chanels, destRow += chanels) { for (int k = 0; k < chanels; k++) { float v = f * (pRow[k] - 128) + 128; if (v < 0) { v = 0; } if (v > 255) { v = 255; } destRow[k] = v; } } } return 1; } int ColorTransformer::CalcHistogram(const Mat &sourceImage, Mat &histMatrix) { if (sourceImage.empty()) { return -1; } int rows = sourceImage.rows; int cols = sourceImage.cols; int chanels = sourceImage.channels(); histMatrix = Mat(chanels, 256, CV_32F, Scalar(0, 0, 0)); uint sum[chanels]; for (int i = 0; i < chanels; i++) { sum[i] = 0; } for (int i = 0; i < rows; i++) { const uchar *pRow = sourceImage.ptr<uchar>(i); for (int j = 0; j < cols; j++, pRow += chanels) { for (int k = 0; k < chanels; k++) { float *histRow = histMatrix.ptr<float>(k); int color = pRow[k]; // chanel k histRow[color]++; sum[k]++; } } } for (int i = 0; i < chanels; i++) { float *histRow = histMatrix.ptr<float>(i); for (int j = 0; j < 256; j++) { histRow[j] = histRow[j] / sum[i]; } } return 1; } int ColorTransformer::HistogramEqualization(const Mat &sourceImage, Mat &destinationImage) { return -1; } int ColorTransformer::DrawHistogram(const Mat &histMatrix, Mat &histImage) { int chanels = histMatrix.rows; int colorNum = histMatrix.cols; int width = 300; int height = 250 * chanels; int chartHeight = 200; int marginLeft = 10; histImage = Mat(height, width, CV_8UC3, Scalar(255, 255, 255)); int bin = cvRound((double)width / colorNum); for(int k = 0; k < chanels; k++) { const float *pRow = histMatrix.ptr<float>(k); Scalar scalar; if(chanels == 3) { if(k == 0) { scalar = Scalar(255, 0, 0); } else if (k == 1) { scalar = Scalar(0, 128, 0); } else { scalar = Scalar(0, 0, 255); } } else { scalar = Scalar(128, 128, 128); } for (int i = 0; i < colorNum; i++) { line(histImage, Point(marginLeft + bin * (i), chartHeight * (k + 1)), Point(marginLeft + bin * (i), (k + 1) * chartHeight - cvRound(pRow[i] * 5000)), scalar, 2, 8, 0); } } return 1; } float ColorTransformer::CompareImage(const Mat &image1, Mat &image2) { Mat histMatrix1; Mat histMatrix2; this->CalcHistogram(image1, histMatrix1); this->CalcHistogram(image2, histMatrix2); int chanels = histMatrix1.rows; int colorNum = histMatrix2.cols; float sum = 0; for (int i = 0; i < chanels; i++) { float *pChanelImage1 = histMatrix1.ptr<float>(i); float *pChanelImage2 = histMatrix2.ptr<float>(i); for (int bin = 0; bin < colorNum; bin++) { sum += min(pChanelImage1[bin], pChanelImage2[bin]); } } return sum * 100 / (float)chanels; } int ColorTransformer::ReduceImageColor(const Mat& sourceImage, Mat& destinationImage, RgbColor *paletteColor, int nPalette) { if (sourceImage.empty()) { return -1; } int rows = sourceImage.rows; int cols = sourceImage.cols; int chanels = sourceImage.channels(); destinationImage = Mat(rows, cols, CV_MAKETYPE(CV_8U, chanels)); for (int i = 0; i < rows; i++) { const uchar *pRow = sourceImage.ptr<uchar>(i); uchar *destRow = destinationImage.ptr<uchar>(i); for (int j = 0; j < cols; j++, pRow += chanels, destRow += chanels) { uchar blue = pRow[0]; uchar green = pRow[1]; uchar red = pRow[2]; RgbColor rgbColor = RgbColor(); rgbColor.blue = blue; rgbColor.green = green; rgbColor.red = red; float min = 99999999.0; RgbColor nearestColor; for (int k = 0; k < nPalette; k++) { RgbColor color = paletteColor[k]; float diffBlue = rgbColor.blue - color.blue; float diffGreen = rgbColor.green - color.green; float diffRed = rgbColor.red - color.red; float sum = diffBlue * diffBlue + diffGreen * diffGreen + diffRed * diffRed; float norm2 = sqrt(sum); if(norm2 < min) { min = norm2; nearestColor = color; } } destRow[0] = nearestColor.blue; destRow[1] = nearestColor.green; destRow[2] = nearestColor.red; } } return 1; }
27.730435
179
0.510975
source-reference
9ba082f972781f9a4e40f913638ecd9a8644dc39
1,658
cpp
C++
image_ops.cpp
neil-okikiolu/working-with-tensor-rt
90252662a506d689f560f13bd1084ab3a7554184
[ "MIT" ]
5
2020-08-18T10:32:19.000Z
2021-08-09T06:06:48.000Z
image_ops.cpp
neil-okikiolu/working-with-tensor-rt
90252662a506d689f560f13bd1084ab3a7554184
[ "MIT" ]
1
2021-04-28T13:17:25.000Z
2021-04-29T01:11:31.000Z
image_ops.cpp
neil-okikiolu/working-with-tensor-rt
90252662a506d689f560f13bd1084ab3a7554184
[ "MIT" ]
2
2020-12-10T03:39:18.000Z
2021-03-18T03:24:06.000Z
/** * @author - neil okikiolu */ #include "image_ops.h" #include <iostream> #include <ctime> #include <sstream> #include <ros/ros.h> #include <cv_bridge/cv_bridge.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgcodecs.hpp> namespace imgops { void saveImage(cv::Mat *cvImage, std::string *base_path, std::string *suffix) { // create date time string for captures auto t = std::time(nullptr); auto tm = *std::localtime(&t); std::ostringstream oss; oss << std::put_time(&tm, "%Y-%m-%d %H-%M-%S"); auto str = oss.str(); // combine date time string with path for final image path std::string out_string = *base_path + "capture_" + str + *suffix +".png"; ROS_INFO ( "Starting to save image: %s", out_string.c_str() ); bool result = false; try { std::vector<int> compression_params; compression_params.push_back(cv::IMWRITE_PNG_COMPRESSION); compression_params.push_back(9); // try saving the cv::Mat as a png result = imwrite(out_string, *cvImage, compression_params); } catch (const cv::Exception& ex) { ROS_ERROR( "Exception converting image to PNG format: %s\n", ex.what() ); } if (result) { ROS_INFO( "Saved %s", out_string.c_str() ); } else { ROS_ERROR("ERROR: Can't save PNG file."); return; } } }
25.121212
83
0.534982
neil-okikiolu
9ba8f00425c133e2f1906ad2d637833d76a53c56
2,559
cpp
C++
csr.cpp
bartlomiejn/phosphor-certificate-manager
014be0bf55ebfb930c3f158aa78fa10c9a25da1e
[ "Apache-2.0" ]
null
null
null
csr.cpp
bartlomiejn/phosphor-certificate-manager
014be0bf55ebfb930c3f158aa78fa10c9a25da1e
[ "Apache-2.0" ]
null
null
null
csr.cpp
bartlomiejn/phosphor-certificate-manager
014be0bf55ebfb930c3f158aa78fa10c9a25da1e
[ "Apache-2.0" ]
null
null
null
#include "config.h" #include "csr.hpp" #include <openssl/bio.h> #include <openssl/buffer.h> #include <openssl/ossl_typ.h> #include <openssl/pem.h> #include <openssl/x509.h> #include <cstdio> #include <filesystem> #include <memory> #include <phosphor-logging/elog-errors.hpp> #include <phosphor-logging/elog.hpp> #include <phosphor-logging/log.hpp> #include <utility> #include <xyz/openbmc_project/Certs/error.hpp> #include <xyz/openbmc_project/Common/error.hpp> namespace phosphor::certs { using ::phosphor::logging::elog; using ::phosphor::logging::entry; using ::phosphor::logging::level; using ::phosphor::logging::log; using ::sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; namespace fs = std::filesystem; using X509ReqPtr = std::unique_ptr<X509_REQ, decltype(&::X509_REQ_free)>; using BIOPtr = std::unique_ptr<BIO, decltype(&::BIO_free_all)>; CSR::CSR(sdbusplus::bus::bus& bus, const char* path, std::string&& installPath, const Status& status) : internal::CSRInterface(bus, path, true), objectPath(path), certInstallPath(std::move(installPath)), csrStatus(status) { // Emit deferred signal. this->emit_object_added(); } std::string CSR::csr() { if (csrStatus == Status::FAILURE) { log<level::ERR>("Failure in Generating CSR"); elog<InternalFailure>(); } fs::path csrFilePath = certInstallPath; csrFilePath = csrFilePath.parent_path() / defaultCSRFileName; if (!fs::exists(csrFilePath)) { log<level::ERR>("CSR file doesn't exists", entry("FILENAME=%s", csrFilePath.c_str())); elog<InternalFailure>(); } FILE* fp = std::fopen(csrFilePath.c_str(), "r"); X509ReqPtr x509Req(PEM_read_X509_REQ(fp, nullptr, nullptr, nullptr), ::X509_REQ_free); if (x509Req == nullptr || fp == nullptr) { if (fp != nullptr) { std::fclose(fp); } log<level::ERR>("ERROR occurred while reading CSR file", entry("FILENAME=%s", csrFilePath.c_str())); elog<InternalFailure>(); } std::fclose(fp); BIOPtr bio(BIO_new(BIO_s_mem()), ::BIO_free_all); int ret = PEM_write_bio_X509_REQ(bio.get(), x509Req.get()); if (ret <= 0) { log<level::ERR>("Error occurred while calling PEM_write_bio_X509_REQ"); elog<InternalFailure>(); } BUF_MEM* mem = nullptr; BIO_get_mem_ptr(bio.get(), &mem); std::string pem(mem->data, mem->length); return pem; } } // namespace phosphor::certs
28.752809
80
0.645565
bartlomiejn
9baa9b0081fba3a73c352b5d6fed319305dd0cab
869
cpp
C++
113#path-sum-ii/solution.cpp
llwwns/leetcode_solutions
e352c9bf6399ab3ee0f23889e70361c9f2a3bd33
[ "MIT" ]
null
null
null
113#path-sum-ii/solution.cpp
llwwns/leetcode_solutions
e352c9bf6399ab3ee0f23889e70361c9f2a3bd33
[ "MIT" ]
null
null
null
113#path-sum-ii/solution.cpp
llwwns/leetcode_solutions
e352c9bf6399ab3ee0f23889e70361c9f2a3bd33
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> ans; vector<int> cur; void calc(TreeNode* root, int sum) { if (root == NULL) return; if (root->left == NULL && root->right == NULL && root->val == sum) { cur.push_back(root->val); ans.push_back(cur); cur.pop_back(); return; } sum -= root->val; cur.push_back(root->val); calc(root->left, sum); calc(root->right, sum); cur.pop_back(); } vector<vector<int>> pathSum(TreeNode* root, int sum) { ans.clear(); calc(root, sum); return ans; } };
26.333333
77
0.487917
llwwns
9bad6d90f3d22cfee7626efc26c437381e604dd4
818
cpp
C++
D3DApplication/App/AppHelpers/Renderer/ClearPass.cpp
d4rkz3r0/GPU-Vertex-Skinning-Animation-Project
f9667992e49599038ee2f46b014ea205fafcb6c3
[ "MIT" ]
null
null
null
D3DApplication/App/AppHelpers/Renderer/ClearPass.cpp
d4rkz3r0/GPU-Vertex-Skinning-Animation-Project
f9667992e49599038ee2f46b014ea205fafcb6c3
[ "MIT" ]
null
null
null
D3DApplication/App/AppHelpers/Renderer/ClearPass.cpp
d4rkz3r0/GPU-Vertex-Skinning-Animation-Project
f9667992e49599038ee2f46b014ea205fafcb6c3
[ "MIT" ]
null
null
null
#include "ClearPass.h" #include <d3d11.h> #include "../../../Shared/SharedUtils.h" ClearPass::ClearPass(ID3D11Device* pDevice, ID3D11RenderTargetView* pRTV, ID3D11DepthStencilView* pDSV) : mDevice(pDevice), mRTV(pRTV), mDSV(pDSV), m_Enabled(true) { mDevice->GetImmediateContext(&mDeviceContext); } ClearPass::~ClearPass() { Destroy(); } void ClearPass::SetEnabled(bool enabled) { m_Enabled = enabled; } bool ClearPass::IsEnabled() const { return m_Enabled; } void ClearPass::Render() { mDeviceContext->ClearRenderTargetView(mRTV, reinterpret_cast<const float*>(&mClearColor)); mDeviceContext->ClearDepthStencilView(mDSV, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); } void ClearPass::Destroy() { ReleaseObject(mDevice); ReleaseObject(mDeviceContext); ReleaseObject(mRTV); ReleaseObject(mDSV); }
20.974359
163
0.756724
d4rkz3r0
9bae0f7039deac6d1bc69bb861908fc6d0dfdd95
1,311
cc
C++
internal/platform/input_stream.cc
deling-google/nearby
338faab8c902d1de4a244611d5cd9ca68a91a135
[ "Apache-2.0" ]
69
2021-10-18T00:37:29.000Z
2022-03-20T19:53:38.000Z
internal/platform/input_stream.cc
deling-google/nearby
338faab8c902d1de4a244611d5cd9ca68a91a135
[ "Apache-2.0" ]
14
2021-10-13T19:49:27.000Z
2022-03-31T22:19:13.000Z
internal/platform/input_stream.cc
deling-google/nearby
338faab8c902d1de4a244611d5cd9ca68a91a135
[ "Apache-2.0" ]
22
2021-10-20T12:36:47.000Z
2022-03-31T18:39:46.000Z
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "internal/platform/input_stream.h" #include <algorithm> #include <cstddef> #include <cstdint> #include "internal/platform/byte_array.h" #include "internal/platform/exception.h" namespace location { namespace nearby { namespace { constexpr size_t kSkipBufferSize = 64 * 1024; } // namespace ExceptionOr<size_t> InputStream::Skip(size_t offset) { size_t bytes_left = offset; while (bytes_left > 0) { size_t chunk_size = std::min(bytes_left, kSkipBufferSize); ExceptionOr<ByteArray> result = Read(chunk_size); if (!result.ok()) { return result.GetException(); } bytes_left -= chunk_size; } return ExceptionOr<size_t>(offset); } } // namespace nearby } // namespace location
29.133333
75
0.729214
deling-google
9bafe3701a7c347425494e3d4ceddc9fa5e2b874
550
hpp
C++
header/Animation.hpp
Vincent11276/Platformer2D
6d2c3718ff6f2cbc7da1d63021b2d36b0758808e
[ "MIT" ]
null
null
null
header/Animation.hpp
Vincent11276/Platformer2D
6d2c3718ff6f2cbc7da1d63021b2d36b0758808e
[ "MIT" ]
null
null
null
header/Animation.hpp
Vincent11276/Platformer2D
6d2c3718ff6f2cbc7da1d63021b2d36b0758808e
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <string> #include <iostream> // fuck using namespace std; #include <SFML/Graphics/Sprite.hpp> #include <SFML/Graphics/Texture.hpp> class Animation { public: std::vector<sf::Sprite> frames; std::string name; int frameIndex=0; float fps = 5; bool loop; sf::Sprite &getCurrentFrame(); void resetFrame(); void nextFrame(); void previousFrame(); bool loadSpriteSheet(std::string name, sf::Texture &texture, sf::Vector2i frameSize, bool append=0, int row=0); };
15.277778
115
0.669091
Vincent11276
9bb0a0917a28051ed39c24b26e60a80d1b86e601
3,010
cpp
C++
src/main.cpp
Ymagis/EclairLooks
c04fb1af1160305fb1dbffb2ea92cc478cd70b31
[ "BSD-3-Clause" ]
9
2019-07-03T13:11:33.000Z
2021-10-06T13:55:31.000Z
src/main.cpp
Ymagis/EclairLooks
c04fb1af1160305fb1dbffb2ea92cc478cd70b31
[ "BSD-3-Clause" ]
1
2019-07-09T09:04:59.000Z
2019-08-06T13:23:47.000Z
src/main.cpp
Ymagis/EclairLooks
c04fb1af1160305fb1dbffb2ea92cc478cd70b31
[ "BSD-3-Clause" ]
4
2019-07-02T15:03:43.000Z
2019-09-28T14:33:03.000Z
#include <locale> #include <QtWidgets/QApplication> #include <QtGui/QSurfaceFormat> #include <QtWidgets/QDesktopWidget> #include <QFile> #include <context.h> #include <gui/mainwindow.h> #include <operator/ocio/matrix.h> #include <operator/ocio/filetransform.h> #include <operator/ocio/colorspace.h> #include <operator/ctl/operator.h> void setupContext() { // Settings using FP = FilePathParameter; ParameterSerialList& s = Context::getInstance().settings(); s.Add<FP>("Default CTL Folder", "", "Choose a folder", "", FP::PathType::Folder); s.Add<FP>("Default OCIO Config", "", "Choose an ocio config file", ""); s.Add<FP>("Default Image", "", "Choose an image", ""); s.Add<FP>("Image Base Folder", "", "Choose a folder", "", FP::PathType::Folder); s.Add<FP>("Look Base Folder", "", "Choose a folder", "", FP::PathType::Folder); s.Add<FP>("Look Tonemap LUT", "", "Choose a LUT", ""); // Pipeline ImagePipeline& p = Context::getInstance().pipeline(); p.SetName("main"); QFile f = QFile(":/images/stresstest.exr"); QByteArray blob; if (f.open(QIODevice::ReadOnly)) blob = f.readAll(); if (Image img = Image::FromBuffer((void *) blob.data(), blob.count())) p.SetInput(img); // Operators ImageOperatorList& o = Context::getInstance().operators(); o.Register<OCIOMatrix>(); o.Register<OCIOFileTransform>(); o.Register<OCIOColorSpace>(); o.Register<CTLTransform>(); } int main(int argc, char **argv) { QCoreApplication::setApplicationName("Eclair Looks"); QCoreApplication::setOrganizationName("Ymagis"); QCoreApplication::setOrganizationDomain("ymagis.com"); QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts); QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL); QSurfaceFormat format; format.setSamples(16); format.setProfile(QSurfaceFormat::CoreProfile); format.setSwapBehavior(QSurfaceFormat::TripleBuffer); format.setSwapInterval(1); format.setVersion(3, 2); format.setDepthBufferSize(24); QSurfaceFormat::setDefaultFormat(format); setupContext(); std::string imgPath = Context::getInstance().settings() .Get<FilePathParameter>("Default Image")->value(); if(Image img = Image::FromFile(imgPath)) Context::getInstance().pipeline().SetInput(img); QApplication app(argc, argv); // Make sure we use C locale to parse float // This need to be placed right after QApplication initialization // See : http://doc.qt.io/qt-5/qcoreapplication.html#locale-settings QLocale::setDefault(QLocale("C")); setlocale(LC_NUMERIC, "C"); QFile cssFile(":/css/application.css"); cssFile.open(QFile::ReadOnly); QString cssString = QLatin1String(cssFile.readAll()); app.setStyleSheet(cssString); MainWindow mainWindow; mainWindow.setup(); mainWindow.show(); mainWindow.centerOnScreen(); Context::getInstance().pipeline().Init(); return app.exec(); }
32.021277
85
0.67608
Ymagis
9bb6eda69859d4cb3b653689b98e954708125aa4
2,245
cpp
C++
tests/crypt_vfs.cpp
terrakuh/ysqlite3
d7e784f2e809462bef83805d853838a73fdf0d15
[ "MIT" ]
null
null
null
tests/crypt_vfs.cpp
terrakuh/ysqlite3
d7e784f2e809462bef83805d853838a73fdf0d15
[ "MIT" ]
3
2020-09-29T18:00:39.000Z
2020-10-01T14:59:58.000Z
tests/crypt_vfs.cpp
terrakuh/ysqlite3
d7e784f2e809462bef83805d853838a73fdf0d15
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include <cstring> #include <random> #include <string> #include <vector> #include <ysqlite3/database.hpp> #include <ysqlite3/vfs/crypt_file.hpp> #include <ysqlite3/vfs/sqlite3_file_wrapper.hpp> #include <ysqlite3/vfs/sqlite3_vfs_wrapper.hpp> using namespace ysqlite3; TEST_CASE("opening crypt db") { vfs::register_vfs(std::make_shared<vfs::SQLite3_vfs_wrapper<vfs::Crypt_file<vfs::SQLite3_file_wrapper>>>( vfs::find_vfs(nullptr), YSQLITE3_CRYPT_VFS_NAME), true); REQUIRE(vfs::find_vfs(YSQLITE3_CRYPT_VFS_NAME) == vfs::find_vfs(nullptr)); REQUIRE(vfs::find_vfs(nullptr)); std::vector<std::uint8_t> data; { std::remove("test.db"); Database db{ "test.db" }; db.set_reserved_size(vfs::crypt_file_reserve_size()); db.execute(R"( PRAGMA key="r'my secret'"; PRAGMA cipher="aes-256-gcm"; CREATE TABLE crypt(val BLOB); )"); // generate payload data.reserve(4096 * 2); std::default_random_engine engine{ 616161 }; std::uniform_int_distribution<std::uint8_t> distribution{ std::numeric_limits<std::uint8_t>::lowest(), std::numeric_limits<std::uint8_t>::max() }; for (auto& i : data) { i = distribution(engine); } auto stmt = db.prepare_statement("INSERT INTO crypt(val) VALUES(?)"); stmt.bind_reference(0, { data.data(), data.size() }); stmt.finish(); } { Database db; db.open("test.db", open_flag_readwrite); db.execute(R"( PRAGMA key="r'my secret'"; PRAGMA cipher="aes-256-gcm"; )"); // compare data auto stmt = db.prepare_statement("SELECT val FROM crypt"); auto r = stmt.step(); REQUIRE(r); auto blob = r.blob(0); REQUIRE(blob.size() == data.size()); REQUIRE(std::memcmp(blob.begin(), data.data(), data.size()) == 0); } { Database db; db.open("file:test.db?key=r%27my%20secret%27&cipher=aes-256-gcm", open_flag_readwrite | open_flag_uri); // compare data auto stmt = db.prepare_statement("SELECT val FROM crypt"); auto r = stmt.step(); REQUIRE(r); auto blob = r.blob(0); REQUIRE(blob.size() == data.size()); REQUIRE(std::memcmp(blob.begin(), data.data(), data.size()) == 0); } }
25.804598
106
0.653007
terrakuh
9bb869e5575f89dab20ba4f04581e158b7ccf14e
2,857
hpp
C++
include/aikido/statespace/StateHandle.hpp
usc-csci-545/aikido
afd8b203c17cb0b05d7db436f8bffbbe2111a75a
[ "BSD-3-Clause" ]
null
null
null
include/aikido/statespace/StateHandle.hpp
usc-csci-545/aikido
afd8b203c17cb0b05d7db436f8bffbbe2111a75a
[ "BSD-3-Clause" ]
null
null
null
include/aikido/statespace/StateHandle.hpp
usc-csci-545/aikido
afd8b203c17cb0b05d7db436f8bffbbe2111a75a
[ "BSD-3-Clause" ]
null
null
null
#ifndef AIKIDO_STATESPACE_STATEHANDLE_HPP_ #define AIKIDO_STATESPACE_STATEHANDLE_HPP_ #include <type_traits> namespace aikido { namespace statespace { /// Wrap a State with its StateSpace to provide convenient accessor methods. /// The template parameter \c _QualifiedState is necessary to support both /// \c const and non-<tt>const</tt> states. /// /// \tparam _StateSpace Type of \c StateSpace this state is a member of /// \tparam _QualifiedState Type of \c State being wrapped template <class _StateSpace, class _QualifiedState> class StateHandle { public: using StateSpace = _StateSpace; using QualifiedState = _QualifiedState; using State = typename StateSpace::State; using ConstState = typename std::conditional<std::is_const<QualifiedState>::value, QualifiedState, const QualifiedState>::type; /// Constructs a nullptr handle. StateHandle(); /// Wrap state, which must be form the provided StateSpace. /// /// \param space State space that created \c state. /// \param state State created by \c space. StateHandle(const StateSpace* space, QualifiedState* state); StateHandle(const StateHandle&) = default; StateHandle(StateHandle&&) = default; StateHandle& operator=(StateHandle&&) = default; StateHandle& operator=(const StateHandle&) = default; /// Implicitly convert to a \c State pointer. operator QualifiedState*() const; /// Resets StateHandle to nullptr. void reset(); /// Resets the state, which must be from the provided StateSpace. /// /// \param space State space that created \c state. /// \param state State created by \c space. void reset(const StateSpace* space, QualifiedState* state); /// Returns the State. This function is enabled only if QualifiedState is a /// non-const State type. /// /// \return state wrapped by this handle template <typename Q = QualifiedState> auto getState() -> typename std::enable_if<!std::is_const<Q>::value, Q*>::type; // Note: We don't define non-const function for const State type because it // violates const-correctness. /// Returns the State. /// /// \return State wrapped by this handle template <typename Q = QualifiedState> auto getState() const -> typename std::conditional<std::is_const<Q>::value, Q*, const Q*>::type; /// Returns the state space that created this state. /// /// \return State space created this state const StateSpace* getStateSpace() const; protected: /// State space of the sate that is managed by this handler. const StateSpace* mSpace; /// State managed by this handler. This can be either const or non-const type. QualifiedState* mState; }; } // namespace statespace } // namespace aikido #include "detail/StateHandle-impl.hpp" #endif // AIKIDO_STATESPACE_STATEHANDLE_HPP_
31.395604
80
0.707035
usc-csci-545
9bb9205ce240b18fea5db59ed12e3a3b9769caff
5,229
cpp
C++
src/knn/annClassify.cpp
wmotte/toolkid
2a8f82e1492c9efccde9a4935ce3019df1c68cde
[ "MIT" ]
null
null
null
src/knn/annClassify.cpp
wmotte/toolkid
2a8f82e1492c9efccde9a4935ce3019df1c68cde
[ "MIT" ]
null
null
null
src/knn/annClassify.cpp
wmotte/toolkid
2a8f82e1492c9efccde9a4935ce3019df1c68cde
[ "MIT" ]
null
null
null
#include "tkdCmdParser.h" #include "annCommon.h" /** * Classify using ANN. */ class AnnClassify { public: typedef float PixelType; /** * Run. */ void Run( const std::string& trainingDataFileName, const std::vector< std::string >& imageFileNames, const std::string& maskFileName, const std::string& outputFileName, unsigned int k, double errorBound, bool normalize, bool addSpatialProperties, bool addEuclideanDistance, bool addAngles, std::vector< int > probabilistic, double percentage, const std::string& dumpFileName, bool prioritySearch ) { // [ 1 ] Get training data into matrix and classes into vector ... ann::Ann< PixelType >::MatrixType trainingData; // raw data ... ann::Ann< PixelType >::VectorType trainingClasses; // classes ... ann::Ann< PixelType >::ReadTrainingData( trainingDataFileName, trainingData, trainingClasses, percentage ); // [ 2 ] Get query data (images) into matrix ... ann::Ann< PixelType >::MatrixType queryData; ann::Ann< PixelType >::FillIntensityData( queryData, imageFileNames, maskFileName ); // x, y, z if( addSpatialProperties ) { ann::Ann< PixelType >::FillSpatialData( queryData, maskFileName, maskFileName ); } // euclidean distance ... if( addEuclideanDistance ) { ann::Ann< PixelType >::FillEuclideanData( queryData, maskFileName, maskFileName ); } // angles ... if ( addAngles ) { ann::Ann< PixelType >::FillAnglesData( queryData, maskFileName, maskFileName ); } if( normalize ) { // [ 3 ] Normalize training data ... ann::Ann< PixelType >::Normalize( trainingData ); // [ 4 ] Normalize query data ... ann::Ann< PixelType >::Normalize( queryData ); } // [ 5 ] Query ... ann::Ann< PixelType >::MatrixType queryResultMatrix; ann::Ann< PixelType >::Query( trainingData, trainingClasses, queryData, queryResultMatrix, k, errorBound, probabilistic, dumpFileName, prioritySearch ); // [ 6 ] Project to image ... ann::Ann< PixelType >::Project2Image( queryResultMatrix, maskFileName, outputFileName, probabilistic ); } }; /** * ANN Classify. */ int main( int argc, char ** argv ) { tkd::CmdParser p( "ann classify", "Classify images using ANN based on trained data" ); std::string trainingData; std::vector< std::string > inputFileNames; std::string maskFileName; std::string outputFileName; std::string dumpFileName; int k = 1; double errorBound = 0.0; bool normalize = true; bool addSpatialProperties = false; bool addEuclideanDistance = false; std::vector< int > probabilistic; double percentage = 100.0; bool prioritySearch = false; bool addAngles = false; p.AddArgument( trainingData, "training-data" ) ->AddAlias( "t" ) ->SetDescription( "Training data" ) ->SetRequired( true ); p.AddArgument( inputFileNames, "inputs" ) ->AddAlias( "i" ) ->SetDescription( "Input images" ) ->SetRequired( true ); p.AddArgument( maskFileName, "mask" ) ->AddAlias( "m" ) ->SetDescription( "Mask image" ) ->SetRequired( true ); p.AddArgument( outputFileName, "output" ) ->AddAlias( "o" ) ->SetDescription( "Output image" ) ->SetRequired( true ); p.AddArgument( dumpFileName, "dump-tree" ) ->AddAlias( "d" ) ->SetDescription( "Output file; if specified kd-tree is dumped to file [useful for ann2fig]" ) ->SetRequired( false ); p.AddArgument( k, "k" ) ->AddAlias( "k" ) ->SetDescription( "K (default: 1)" ) ->SetRequired( false ); p.AddArgument( errorBound, "error-bound" ) ->AddAlias( "e" ) ->SetDescription( "Error boundaries [default: 0.0]" ) ->SetRequired( false ); p.AddArgument( probabilistic, "probabilistic" ) ->AddAlias( "p" ) ->SetDescription( "Vector with classes (non-zero) to return as probabilisitic classification (Anbeek, Neuroimage 2005)" )->SetRequired( false )->SetMinMax( 1, 1000 ); p.AddArgument( percentage, "percentage" ) ->AddAlias( "c" ) ->SetDescription( "Use random percentage of training dataset (to save computational burden); [default: 100]" ) ->SetRequired( false ); p.AddArgument( normalize, "normalize" ) ->AddAlias( "n" ) ->SetDescription( "Normalize features (default: true)" ) ->SetRequired( false ); p.AddArgument( prioritySearch, "priority-search" ) ->AddAlias( "r" ) ->SetDescription( "Priority search instead of standard search (default: false)" ) ->SetRequired( false ); p.AddArgument( addSpatialProperties, "spatial-properties" ) ->AddAlias( "s" ) ->SetDescription( "Include spatial properies as features [default: false]" ) ->SetRequired( false ); p.AddArgument( addEuclideanDistance, "euclidean-distance" ) ->AddAlias( "euc" ) ->SetDescription( "Add euclidean distance as feature, relative to COG) [default: false]" ) ->SetRequired( false ); p.AddArgument( addAngles, "angles" ) ->AddAlias( "a" ) ->SetDescription( "Include x,y,z angles, relative to COG) [default: false]" ) ->SetRequired( false ); if ( !p.Parse( argc, argv ) ) { p.PrintUsage( std::cout ); return EXIT_FAILURE; } AnnClassify annClassify; annClassify.Run( trainingData, inputFileNames, maskFileName, outputFileName, (unsigned) k, errorBound, normalize, addSpatialProperties, addEuclideanDistance, addAngles, probabilistic, percentage, dumpFileName, prioritySearch ); return EXIT_SUCCESS; }
36.3125
233
0.69803
wmotte
9bbcc3c947bfc7f9d2c5347cbeb82c5776f6ac8b
6,038
cpp
C++
src/editor/Widgets/RichTextEditor.cpp
tedvalson/NovelTea
f731951f25936cb7f5ff23e543e0301c1b5bfe82
[ "MIT" ]
null
null
null
src/editor/Widgets/RichTextEditor.cpp
tedvalson/NovelTea
f731951f25936cb7f5ff23e543e0301c1b5bfe82
[ "MIT" ]
null
null
null
src/editor/Widgets/RichTextEditor.cpp
tedvalson/NovelTea
f731951f25936cb7f5ff23e543e0301c1b5bfe82
[ "MIT" ]
null
null
null
#include "RichTextEditor.hpp" #include "ui_RichTextEditor.h" #include "EditorUtils.hpp" #include <NovelTea/TextBlock.hpp> #include <NovelTea/TextFragment.hpp> #include <NovelTea/ProjectData.hpp> #include <QTextBlock> #include <iostream> RichTextEditor::RichTextEditor(QWidget *parent) : QWidget(parent), ui(new Ui::RichTextEditor), m_isChanged(false) { ui->setupUi(this); ui->toolBarText->insertWidget(ui->actionFinish, ui->spinBox); startTimer(1000); } RichTextEditor::~RichTextEditor() { delete ui; } void RichTextEditor::mergeFormat(const QTextCharFormat &format) { QTextCursor cursor = ui->textEdit->textCursor(); if (!cursor.hasSelection()) cursor.select(QTextCursor::WordUnderCursor); cursor.mergeCharFormat(format); ui->textEdit->mergeCurrentCharFormat(format); } void RichTextEditor::invoke() { emit invoked(); } void RichTextEditor::setValue(const std::shared_ptr<NovelTea::ActiveText> &text) { auto doc = activeTextToDocument(text); ui->textEdit->setDocument(doc); m_isChanged = false; } std::shared_ptr<NovelTea::ActiveText> RichTextEditor::getValue() const { return documentToActiveText(ui->textEdit->document()); } void RichTextEditor::setFormattingEnabled(bool value) { m_formattingEnabled = value; ui->actionBold->setEnabled(value); ui->actionItalic->setEnabled(value); ui->actionUnderline->setEnabled(value); } bool RichTextEditor::getFormattingEnabled() const { return m_formattingEnabled; } QTextDocument *RichTextEditor::activeTextToDocument(const std::shared_ptr<NovelTea::ActiveText> &activeText) { auto doc = new QTextDocument; auto cursor = QTextCursor{doc}; auto firstBlock = true; QFont defaultFont("DejaVu Sans", 12); QTextBlockFormat blockFormat; doc->setDefaultFont(defaultFont); for (auto &block : activeText->blocks()) { blockFormat.setAlignment(Qt::AlignLeft); if (firstBlock) { firstBlock = false; cursor.setBlockFormat(blockFormat); } else cursor.insertBlock(blockFormat); for (auto &fragment : block->fragments()) { // auto textformat = toQTextCharFormat(Proj.textFormat(jfrag[0])); // cursor.insertText(QString::fromStdString(jfrag[1]), textformat); auto textformat = EditorUtils::toQTextCharFormat(fragment->getTextFormat()); cursor.insertText(QString::fromStdString(fragment->getText()), textformat); } } return doc; } std::shared_ptr<NovelTea::ActiveText> RichTextEditor::documentToActiveText(const QTextDocument *doc) { auto activeText = std::make_shared<NovelTea::ActiveText>(); int fmtIndexLast = -1; for (auto qblock = doc->begin(); qblock != doc->end(); qblock = qblock.next()) { if (qblock.isValid()) { auto block = std::make_shared<NovelTea::TextBlock>(); NovelTea::TextFragment fragment; auto sfrag = std::string(); // block->setAlignment for (auto it = qblock.begin(); !it.atEnd(); ++it) { QTextFragment qfragment = it.fragment(); if (qfragment.isValid()) { auto format = EditorUtils::toTextFormat(qfragment.charFormat()); auto fmtIndex = NovelTea::ProjectData::instance().addTextFormat(format); if (fmtIndex != fmtIndexLast) { if (fmtIndexLast >= 0) { fragment.setText(sfrag); block->addFragment(std::make_shared<NovelTea::TextFragment>(fragment)); // jfrag[1] = sfrag; // jblock[1].push_back(jfrag); } fmtIndexLast = fmtIndex; // jfrag[0] = fmtIndex; fragment.setTextFormat(format); sfrag.clear(); } sfrag += qfragment.text().toStdString(); } // if ((++it).atEnd()) // { // fmtIndexLast = -1; // fragment.setText(sfrag); // } } fmtIndexLast = -1; fragment.setText(sfrag); block->addFragment(std::make_shared<NovelTea::TextFragment>(fragment)); activeText->addBlock(block); // jfrag[1] = sfrag; // jblock[1].push_back(jfrag); // j.push_back(jblock); } } return activeText; } //void RichTextEditor::setValue(const json &j) //{ // auto doc = Utils::jsonToDocument(j); // ui->textEdit->setDocument(doc); //} void RichTextEditor::fontChanged(const QFont &font) { // comboFont->setCurrentIndex(comboFont->findText(QFontInfo(f).family())); // comboSize->setCurrentIndex(comboSize->findText(QString::number(f.pointSize()))); ui->actionBold->setChecked(font.bold()); ui->actionItalic->setChecked(font.italic()); ui->actionUnderline->setChecked(font.underline()); } void RichTextEditor::colorChanged(const QColor &color) { QPixmap pix(16, 16); pix.fill(color); // actionTextColor->setIcon(pix); } void RichTextEditor::timerEvent(QTimerEvent *event) { if (m_isChanged) { m_isChanged = false; emit changed(documentToActiveText(ui->textEdit->document())); } } void RichTextEditor::on_actionFinish_triggered() { // auto doc = ui->textEdit->document(); // json j = Utils::documentToJson(doc); // NovelTea::TextFormat f; // json j = f; // std::cout << j.dump() << std::endl; emit saved(documentToActiveText(ui->textEdit->document())); // NovelTea::ProjectData::instance().saveToFile("/home/android/test.ntp"); // NovelTea::ProjectData::instance().loadFromFile("/home/android/test.ntp"); } void RichTextEditor::on_actionBold_triggered() { QTextCharFormat fmt; fmt.setFontWeight(ui->actionBold->isChecked() ? QFont::Bold : QFont::Normal); mergeFormat(fmt); m_isChanged = true; } void RichTextEditor::on_actionItalic_triggered() { QTextCharFormat fmt; fmt.setFontItalic(ui->actionItalic->isChecked()); mergeFormat(fmt); m_isChanged = true; } void RichTextEditor::on_actionUnderline_triggered() { QTextCharFormat fmt; fmt.setFontUnderline(ui->actionUnderline->isChecked()); mergeFormat(fmt); m_isChanged = true; } void RichTextEditor::on_textEdit_currentCharFormatChanged(const QTextCharFormat &format) { fontChanged(format.font()); colorChanged(format.foreground().color()); } void RichTextEditor::on_spinBox_valueChanged(int arg1) { QTextCharFormat fmt; fmt.setFontPointSize(arg1); mergeFormat(fmt); m_isChanged = true; } void RichTextEditor::on_textEdit_textChanged() { m_isChanged = true; }
24.745902
108
0.716628
tedvalson
9bbe221ba5d9af3fc6979783d28c12fd33c86bf6
2,104
cpp
C++
example/src/ofApp.cpp
P-A-N/ofxBlackmagicATEM
28ecc8d49b6a38dab4c610db03e938872838c52c
[ "MIT" ]
null
null
null
example/src/ofApp.cpp
P-A-N/ofxBlackmagicATEM
28ecc8d49b6a38dab4c610db03e938872838c52c
[ "MIT" ]
null
null
null
example/src/ofApp.cpp
P-A-N/ofxBlackmagicATEM
28ecc8d49b6a38dab4c610db03e938872838c52c
[ "MIT" ]
null
null
null
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ atem.setup("10.0.0.91"); } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ switch (key) { case '1': atem.changePgOut(ofxBlackmagicATEM::NO1); break; case '2': atem.changePgOut(ofxBlackmagicATEM::NO2); break; case '3': atem.changePgOut(ofxBlackmagicATEM::NO3); break; case '4': atem.changePgOut(ofxBlackmagicATEM::NO4); break; case '5': atem.changePgOut(ofxBlackmagicATEM::NO5); break; case '6': atem.changePgOut(ofxBlackmagicATEM::NO6); break; case '7': atem.changePgOut(ofxBlackmagicATEM::NO7); break; case '8': atem.changePgOut(ofxBlackmagicATEM::NO8); break; default: break; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
18.45614
64
0.379278
P-A-N
9bc0863c80c90a31161eef579ea0a0fbd5049ded
1,467
cpp
C++
filter.cpp
iphelf/Digital-Image-Processing
8c736d208bf7806b2839540e41216d07f2a27e52
[ "WTFPL" ]
null
null
null
filter.cpp
iphelf/Digital-Image-Processing
8c736d208bf7806b2839540e41216d07f2a27e52
[ "WTFPL" ]
null
null
null
filter.cpp
iphelf/Digital-Image-Processing
8c736d208bf7806b2839540e41216d07f2a27e52
[ "WTFPL" ]
null
null
null
#include "filter.h" #include "ui_filter.h" #include <iostream> Filter::Filter(QWidget *parent,cv::Mat mat) : QDialog(parent),mat(mat), ui(new Ui::Filter) { ui->setupUi(this); connect(ui->radioButton_mean,SIGNAL(clicked(bool)), this,SLOT(updated())); connect(ui->radioButton_median,SIGNAL(clicked(bool)), this,SLOT(updated())); connect(ui->radioButton_laplacian,SIGNAL(clicked(bool)), this,SLOT(updated())); connect(ui->spinBox_size,SIGNAL(valueChanged(int)), this,SLOT(updated())); connect(ui->horizontalSlider_size,SIGNAL(valueChanged(int)), this,SLOT(updated())); connect(ui->checkBox_preview,SIGNAL(clicked(bool)), this,SLOT(updated())); } Filter::~Filter() { delete ui; } cv::Mat Filter::process() { cv::Mat res=mat.clone(); if(ui->radioButton_mean->isChecked()) { int n=ui->spinBox_size->value(); cv::blur(res,res,cv::Size(n,n)); } else if(ui->radioButton_median->isChecked()) { int n=ui->spinBox_size->value(); cv::medianBlur(res,res,n); } else if(ui->radioButton_laplacian->isChecked()) { cv::Mat mask=res.clone(); cv::Laplacian(mask,mask,CV_8UC3); cv::subtract(res,mask,res); } return res; } void Filter::updated() { if(!ui->checkBox_preview->isChecked()) return; emit updatePreview(process()); } void Filter::on_Filter_accepted() { mat=process(); }
28.764706
64
0.619632
iphelf
9bc1411e4f46194349fafe3123b086b2c807925d
12,710
cpp
C++
src/fft3d_wrap.cpp
lammps/fftmpi
09473e21e5211e5c3250f86c42bf5ef204cb5cf7
[ "BSD-3-Clause" ]
11
2021-08-01T14:51:59.000Z
2022-01-14T02:07:51.000Z
src/fft3d_wrap.cpp
lammps/fftmpi
09473e21e5211e5c3250f86c42bf5ef204cb5cf7
[ "BSD-3-Clause" ]
null
null
null
src/fft3d_wrap.cpp
lammps/fftmpi
09473e21e5211e5c3250f86c42bf5ef204cb5cf7
[ "BSD-3-Clause" ]
null
null
null
/* ---------------------------------------------------------------------- fftMPI - library for computing 3d/2d FFTs in parallel http://fftmpi.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright 2018 National Technology & Engineering Solutions of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights in this software. This software is distributed under the modified Berkeley Software Distribution (BSD) License. See the README file in the top-level fftMPI directory. ------------------------------------------------------------------------- */ // C interface to fftMPI library, 3d FFT functions #include <mpi.h> #include <string.h> #include <stdlib.h> #include "fft3d_wrap.h" #include "fft3d.h" using namespace FFTMPI_NS; // ---------------------------------------------------------------------- // 3d FFT library calls // ---------------------------------------------------------------------- /* ---------------------------------------------------------------------- create an instance of a 3d FFT and return pointer to it pass in MPI communicator to run on ------------------------------------------------------------------------- */ void fft3d_create(MPI_Comm communicator, int precision, void **ptr) { FFT3d *fft = new FFT3d(communicator,precision); *ptr = (void *) fft; } // ---------------------------------------------------------------------- void fft3d_create_fortran(MPI_Fint fcomm, int precision, void **ptr) { MPI_Comm ccomm = MPI_Comm_f2c(fcomm); FFT3d *fft = new FFT3d(ccomm,precision); *ptr = (void *) fft; } /* ---------------------------------------------------------------------- destruct an instance of a 3d FFT ------------------------------------------------------------------------- */ void fft3d_destroy(void *ptr) { FFT3d *fft = (FFT3d *) ptr; delete fft; } /* ---------------------------------------------------------------------- set an internal variable, before setup() or compute() ------------------------------------------------------------------------- */ void fft3d_set(void *ptr, const char *keyword, int value) { FFT3d *fft = (FFT3d *) ptr; if (strcmp(keyword,"collective") == 0) fft->collective = value; else if (strcmp(keyword,"exchange") == 0) fft->exchange = value; else if (strcmp(keyword,"pack") == 0) fft->packflag = value; else if (strcmp(keyword,"memory") == 0) fft->memoryflag = value; else if (strcmp(keyword,"scale") == 0) fft->scaled = value; else if (strcmp(keyword,"remaponly") == 0) fft->remaponly = value; } /* ---------------------------------------------------------------------- get value of an internal integer variable ------------------------------------------------------------------------- */ int fft3d_get_int(void *ptr, const char *keyword) { FFT3d *fft = (FFT3d *) ptr; if (strcmp(keyword,"collective") == 0) return fft->collective; else if (strcmp(keyword,"exchange") == 0) return fft->exchange; else if (strcmp(keyword,"pack") == 0) return fft->packflag; else if (strcmp(keyword,"npfast1") == 0) return fft->npfast1; else if (strcmp(keyword,"npfast2") == 0) return fft->npfast2; else if (strcmp(keyword,"npfast3") == 0) return fft->npfast3; else if (strcmp(keyword,"npmid1") == 0) return fft->npmid1; else if (strcmp(keyword,"npmid2") == 0) return fft->npmid2; else if (strcmp(keyword,"npmid3") == 0) return fft->npmid3; else if (strcmp(keyword,"npslow1") == 0) return fft->npslow1; else if (strcmp(keyword,"npslow2") == 0) return fft->npslow2; else if (strcmp(keyword,"npslow3") == 0) return fft->npslow3; else if (strcmp(keyword,"npbrick1") == 0) return fft->npbrick1; else if (strcmp(keyword,"npbrick2") == 0) return fft->npbrick2; else if (strcmp(keyword,"npbrick3") == 0) return fft->npbrick3; else if (strcmp(keyword,"ntrial") == 0) return fft->ntrial; else if (strcmp(keyword,"npertrial") == 0) return fft->npertrial; return -1; } /* ---------------------------------------------------------------------- get value of an internal double variable ------------------------------------------------------------------------- */ double fft3d_get_double(void *ptr, const char *keyword) { FFT3d *fft = (FFT3d *) ptr; if (strcmp(keyword,"setuptime") == 0) return fft->setuptime; return -1.0; } /* ---------------------------------------------------------------------- get value of an internal int64 variable ------------------------------------------------------------------------- */ int64_t fft3d_get_int64(void *ptr, const char *keyword) { FFT3d *fft = (FFT3d *) ptr; if (strcmp(keyword,"memusage") == 0) return fft->memusage; return -1; } /* ---------------------------------------------------------------------- get value of an internal string variable ------------------------------------------------------------------------- */ char *fft3d_get_string(void *ptr, const char *keyword, int *len) { FFT3d *fft = (FFT3d *) ptr; if (strcmp(keyword,"fft1d") == 0) { *len = strlen(fft->fft1d); return (char *) fft->fft1d; } else if (strcmp(keyword,"precision") == 0) { *len = strlen(fft->precision); return (char *) fft->precision; } return NULL; } /* ---------------------------------------------------------------------- get pointer to an internal vector of ints variable ------------------------------------------------------------------------- */ int *fft3d_get_int_vector(void *ptr, const char *keyword, int *len) { FFT3d *fft = (FFT3d *) ptr; *len = fft->ntrial; if (strcmp(keyword,"cflags") == 0) return fft->cflags; else if (strcmp(keyword,"eflags") == 0) return fft->eflags; else if (strcmp(keyword,"pflags") == 0) return fft->pflags; return NULL; } /* ---------------------------------------------------------------------- get pointer to an internal vector of doubles variable ------------------------------------------------------------------------- */ double *fft3d_get_double_vector(void *ptr, const char *keyword, int *len) { FFT3d *fft = (FFT3d *) ptr; *len = fft->ntrial; if (strcmp(keyword,"tfft") == 0) return fft->tfft; else if (strcmp(keyword,"t1d") == 0) return fft->t1d; else if (strcmp(keyword,"tremap") == 0) return fft->tremap; else if (strcmp(keyword,"tremap1") == 0) return fft->tremap1; else if (strcmp(keyword,"tremap2") == 0) return fft->tremap2; else if (strcmp(keyword,"tremap3") == 0) return fft->tremap3; else if (strcmp(keyword,"tremap4") == 0) return fft->tremap4; return NULL; } /* ---------------------------------------------------------------------- create plan for performing a 3d FFT ------------------------------------------------------------------------- */ void fft3d_setup(void *ptr, int nfast, int nmid, int nslow, int in_ilo, int in_ihi, int in_jlo, int in_jhi, int in_klo, int in_khi, int out_ilo, int out_ihi, int out_jlo, int out_jhi, int out_klo, int out_khi, int permute, int *fftsize_caller, int *sendsize_caller, int *recvsize_caller) { FFT3d *fft = (FFT3d *) ptr; int fftsize,sendsize,recvsize; fft->setup(nfast,nmid,nslow, in_ilo,in_ihi,in_jlo,in_jhi,in_klo,in_khi, out_ilo,out_ihi,out_jlo,out_jhi,out_klo,out_khi, permute,fftsize,sendsize,recvsize); *fftsize_caller = fftsize; *sendsize_caller = sendsize; *recvsize_caller = recvsize; } /* ---------------------------------------------------------------------- create plan for performing a 3d FFT Fortran interface where indices are 1 to N inclusive ------------------------------------------------------------------------- */ void fft3d_setup_fortran(void *ptr, int nfast, int nmid, int nslow, int in_ilo, int in_ihi, int in_jlo, int in_jhi, int in_klo, int in_khi, int out_ilo, int out_ihi, int out_jlo, int out_jhi, int out_klo, int out_khi, int permute, int *fftsize_caller, int *sendsize_caller, int *recvsize_caller) { FFT3d *fft = (FFT3d *) ptr; int fftsize,sendsize,recvsize; fft->setup(nfast,nmid,nslow, in_ilo-1,in_ihi-1,in_jlo-1,in_jhi-1,in_klo-1,in_khi-1, out_ilo-1,out_ihi-1,out_jlo-1,out_jhi-1,out_klo-1,out_khi-1, permute,fftsize,sendsize,recvsize); *fftsize_caller = fftsize; *sendsize_caller = sendsize; *recvsize_caller = recvsize; } /* ---------------------------------------------------------------------- pass in user memory for a 3d remap send/recv ------------------------------------------------------------------------- */ void fft3d_setup_memory(void *ptr, FFT_SCALAR *sendbuf, FFT_SCALAR *recvbuf) { FFT3d *fft = (FFT3d *) ptr; fft->setup_memory(sendbuf,recvbuf); } /* ---------------------------------------------------------------------- perform a 3d FFT ------------------------------------------------------------------------- */ void fft3d_compute(void *ptr, FFT_SCALAR *in, FFT_SCALAR *out, int flag) { FFT3d *fft = (FFT3d *) ptr; fft->compute(in,out,flag); } /* ---------------------------------------------------------------------- perform just the 1d FFTs needed by a 3d FFT, no data movement ------------------------------------------------------------------------- */ void fft3d_only_1d_ffts(void *ptr, FFT_SCALAR *in, int flag) { FFT3d *fft = (FFT3d *) ptr; fft->only_1d_ffts(in,flag); } /* ---------------------------------------------------------------------- perform all the remaps in a 3d FFT, but no 1d FFTs ------------------------------------------------------------------------- */ void fft3d_only_remaps(void *ptr, FFT_SCALAR *in, FFT_SCALAR *out, int flag) { FFT3d *fft = (FFT3d *) ptr; fft->only_remaps(in,out,flag); } /* ---------------------------------------------------------------------- perform just a single 3d remap operation ------------------------------------------------------------------------- */ void fft3d_only_one_remap(void *ptr, FFT_SCALAR *in, FFT_SCALAR *out, int flag, int which) { FFT3d *fft = (FFT3d *) ptr; fft->only_one_remap(in,out,flag,which); } /* ---------------------------------------------------------------------- tune settings for fastest FFT: collective, exchange, pack flags ------------------------------------------------------------------------- */ void fft3d_tune(void *ptr, int nfast, int nmid, int nslow, int in_ilo, int in_ihi, int in_jlo, int in_jhi, int in_klo, int in_khi, int out_ilo, int out_ihi, int out_jlo, int out_jhi, int out_klo, int out_khi, int permute, int *fftsize_caller, int *sendsize_caller, int *recvsize_caller, int flag, int niter, double tmax, int tflag) { FFT3d *fft = (FFT3d *) ptr; int fftsize,sendsize,recvsize; fft->tune(nfast,nmid,nslow, in_ilo,in_ihi,in_jlo,in_jhi,in_klo,in_khi, out_ilo,out_ihi,out_jlo,out_jhi,out_klo,out_khi, permute,fftsize,sendsize,recvsize, flag,niter,tmax,tflag); *fftsize_caller = fftsize; *sendsize_caller = sendsize; *recvsize_caller = recvsize; } /* ---------------------------------------------------------------------- tune settings for fastest FFT: collective, exchange, pack flags Fortran interface where indices are 1 to N inclusive ------------------------------------------------------------------------- */ void fft3d_tune_fortran(void *ptr, int nfast, int nmid, int nslow, int in_ilo, int in_ihi, int in_jlo, int in_jhi, int in_klo, int in_khi, int out_ilo, int out_ihi, int out_jlo, int out_jhi, int out_klo, int out_khi, int permute, int *fftsize_caller, int *sendsize_caller, int *recvsize_caller, int flag, int niter, double tmax, int tflag) { FFT3d *fft = (FFT3d *) ptr; int fftsize,sendsize,recvsize; fft->tune(nfast,nmid,nslow, in_ilo-1,in_ihi-1,in_jlo-1,in_jhi-1,in_klo-1,in_khi-1, out_ilo-1,out_ihi-1,out_jlo-1,out_jhi-1,out_klo-1,out_khi-1, permute,fftsize,sendsize,recvsize, flag,niter,tmax,tflag); *fftsize_caller = fftsize; *sendsize_caller = sendsize; *recvsize_caller = recvsize; }
36.947674
79
0.488749
lammps
9bc58a226cb7c7a2882a0173dc1e9336e20ce434
4,876
cpp
C++
src/shader_s.cpp
lhswei/learnopengl
e3670b20707598ded433c61a551819deec4cc6e8
[ "MIT" ]
null
null
null
src/shader_s.cpp
lhswei/learnopengl
e3670b20707598ded433c61a551819deec4cc6e8
[ "MIT" ]
null
null
null
src/shader_s.cpp
lhswei/learnopengl
e3670b20707598ded433c61a551819deec4cc6e8
[ "MIT" ]
null
null
null
#include "shader_s.h" Shader::Shader(const char* vertexPath, const char* fragmentPath) { // 1. retrieve the vertex/fragment source code from filePath std::string vertexCode; std::string fragmetCode; std::ifstream vShaderFile; std::ifstream fShaderFile; // ensure ifstream objects can throw exceptions: vShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit); fShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit); try { // open file vShaderFile.open(vertexPath); fShaderFile.open(fragmentPath); std::stringstream vShaderStream, fShaderSteam; // read file's buffer contents into streams vShaderStream << vShaderFile.rdbuf(); fShaderSteam << fShaderFile.rdbuf(); // close file handlers vShaderFile.close(); fShaderFile.close(); // convert stream into string vertexCode = vShaderStream.str(); fragmetCode = fShaderSteam.str(); } catch (std::ifstream::failure e) { std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl; } auto vShaderCode = vertexCode.c_str(); auto fShaderCode = fragmetCode.c_str(); // 2. compile unsigned int vertex, fragment; // vertex shader vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex, 1, &vShaderCode, NULL); glCompileShader(vertex); CheckCompileErrors(vertex, "VERTEX"); // fragment shader fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment, 1, &fShaderCode, NULL); glCompileShader(fragment); CheckCompileErrors(fragment, "FRAGMENT"); // 3. shader program m_nId = glCreateProgram(); glAttachShader(m_nId, vertex); glAttachShader(m_nId, fragment); glLinkProgram(m_nId); CheckCompileErrors(m_nId, "PROGRAM"); // 4. delete the shader as they're linked into our program now and no longer necessary glDeleteShader(vertex); glDeleteShader(fragment); } Shader::~Shader() { glDeleteProgram(m_nId); } void Shader::Use() { glUseProgram(m_nId); } void Shader::SetBool(const std::string &name, bool value) const { glUniform1i(glGetUniformLocation(m_nId, name.c_str()), (int)value); } void Shader::SetInt(const std::string &name, int value) const { glUniform1i(glGetUniformLocation(m_nId, name.c_str()), value); } void Shader::SetFloat(const std::string &name, float value) const { glUniform1f(glGetUniformLocation(m_nId, name.c_str()), value); } void Shader::Set1iv(const std::string &name, int count, int* value) const { glUniform1iv(glGetUniformLocation(m_nId, name.c_str()), count, value); } void Shader::Set2iv(const std::string &name, int count, int* value) const { glUniform2iv(glGetUniformLocation(m_nId, name.c_str()), count, value); } void Shader::Set3iv(const std::string &name, int count, int* value) const { glUniform3iv(glGetUniformLocation(m_nId, name.c_str()), count, value); } void Shader::Set4iv(const std::string &name, int count, int* value) const { glUniform4iv(glGetUniformLocation(m_nId, name.c_str()), count, value); } void Shader::Set1fv(const std::string &name, int count, float* value) const { glUniform1fv(glGetUniformLocation(m_nId, name.c_str()), count, value); } void Shader::Set2fv(const std::string &name, int count, float* value) const { glUniform2fv(glGetUniformLocation(m_nId, name.c_str()), count, value); } void Shader::Set3fv(const std::string &name, int count, float* value) const { glUniform3fv(glGetUniformLocation(m_nId, name.c_str()), count, value); } void Shader::Set4fv(const std::string &name, int count, float* value) const { glUniform4fv(glGetUniformLocation(m_nId, name.c_str()), count, value); } void Shader::SetMt2fv(const std::string &name, int count, unsigned char transpose, float* value) const { glUniformMatrix2fv(glGetUniformLocation(m_nId, name.c_str()), count, transpose, value); } void Shader::SetMt3fv(const std::string &name, int count, unsigned char transpose, float* value) const { glUniformMatrix3fv(glGetUniformLocation(m_nId, name.c_str()), count, transpose, value); } void Shader::SetMt4fv(const std::string &name, int count, unsigned char transpose, float* value) const { glUniformMatrix4fv(glGetUniformLocation(m_nId, name.c_str()), count, transpose, value); } void Shader::CheckCompileErrors(unsigned int shader, std::string type) { int success; char infoLog[1024]; if (type != "PROGRAM") { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } else { glGetProgramiv(shader, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } }
29.373494
167
0.712879
lhswei
9bd11636034e539294c22be2079be58b2ea9f163
2,309
cpp
C++
test_cef_app/main_util.cpp
kkkon/test_cef
ded0685f60e33adddf70d40fd807b9aff2b54bcc
[ "MIT" ]
1
2020-08-17T08:56:08.000Z
2020-08-17T08:56:08.000Z
test_cef_app/main_util.cpp
kkkon/test_cef
ded0685f60e33adddf70d40fd807b9aff2b54bcc
[ "MIT" ]
null
null
null
test_cef_app/main_util.cpp
kkkon/test_cef
ded0685f60e33adddf70d40fd807b9aff2b54bcc
[ "MIT" ]
null
null
null
/** * The MIT License * * Copyright (C) 2017 Kiyofumi Kondoh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "stdafx.h" #include "main_util.h" namespace { const char kProcessType[] = "type"; const char kRendererProcess[] = "renderer"; #if defined(LINUX) const char kZygoteProcess[] = "zygote"; #endif // defined(LINUX) } // namespace CefRefPtr<CefCommandLine> createCommandLine( const CefMainArgs& main_args ) { CefRefPtr<CefCommandLine> command_line = CefCommandLine::CreateCommandLine(); #if defined(_WIN32) command_line->InitFromString(::GetCommandLineW()); #else command_line->InitFromArgv( main_args.argc, main_args.argv ); #endif return command_line; } ProcessType getProcessType( const CefRefPtr<CefCommandLine>& command_line ) { if ( command_line->HasSwitch( kProcessType ) ) { // none } else { return enmProcessType_Browser; } const std::string& process_type = command_line->GetSwitchValue( kProcessType ); if ( process_type == kRendererProcess ) { return enmProcessType_Renderer; } #if defined(LINUX) if ( process_type == kZygoteProcess ) { return enmProcessType_Renderer; } #endif // defined(LINUX) return enmProcessType_Other; }
27.164706
83
0.72369
kkkon
9bd1af4ef41f8bfcc353f7cfbb4ff3eb63d8f780
825
cpp
C++
Striver SDE Sheet/Day - 8 (Greedy)/Job Sequencing Problem.cpp
HariAcidReign/Striver-SDE-Solutions
80757b212abe479f3975b890398a8d877ebfd41e
[ "MIT" ]
25
2021-08-17T04:04:41.000Z
2022-03-16T07:43:30.000Z
Striver SDE Sheet/Day - 8 (Greedy)/Job Sequencing Problem.cpp
hashwanthalla/Striver-Sheets-Resources
80757b212abe479f3975b890398a8d877ebfd41e
[ "MIT" ]
null
null
null
Striver SDE Sheet/Day - 8 (Greedy)/Job Sequencing Problem.cpp
hashwanthalla/Striver-Sheets-Resources
80757b212abe479f3975b890398a8d877ebfd41e
[ "MIT" ]
8
2021-08-18T02:02:23.000Z
2022-02-11T06:05:07.000Z
//Hari's static bool compareProfit(Job a, Job b){ return (a.profit > b.profit); } vector<long> JobScheduling(Job arr[], int n) { // your code here vector<long> ans; sort(arr, arr+n, compareProfit); long count = 0, totProfit = 0; long maxi = arr[0].dead; for(int i = 1; i<n; i++) maxi = max(maxi, arr[i].dead); vector<long> slots(-1, maxi+1); for(int i = 0; i<n; i++){ for(int j = arr[i].dead; j>0; j--){ if(slots[j] == -1){ slots[j] = i; count++; totProfit += arr[i].profit; break; } } } ans.push_back(count); ans.push_back(totProfit); return ans; }
25.78125
63
0.419394
HariAcidReign
9bd1b40ebc6e5d353a62c8555e75fe0e4627a939
2,073
cxx
C++
PWGCF/FEMTOSCOPY/AliFemto/AliFemtoEventReaderAlt.cxx
eciesla/AliPhysics
a9a6dc33c8793ea999348c57cebbce445797e8e4
[ "BSD-3-Clause" ]
null
null
null
PWGCF/FEMTOSCOPY/AliFemto/AliFemtoEventReaderAlt.cxx
eciesla/AliPhysics
a9a6dc33c8793ea999348c57cebbce445797e8e4
[ "BSD-3-Clause" ]
null
null
null
PWGCF/FEMTOSCOPY/AliFemto/AliFemtoEventReaderAlt.cxx
eciesla/AliPhysics
a9a6dc33c8793ea999348c57cebbce445797e8e4
[ "BSD-3-Clause" ]
null
null
null
#include "AliFemtoEventReaderAlt.h" #include "AliFemtoTrack.h" #include "AliAODTrack.h" #include <TRandom3.h> AliFemtoEventReaderAlt::AliFemtoEventReaderAlt() : AliFemtoEventReaderAODMultSelection() , fRng(nullptr) , fEnhanceSmearing(0.0) { } AliFemtoEventReaderAlt::AliFemtoEventReaderAlt(const AliFemtoEventReaderAlt &orig) : AliFemtoEventReaderAODMultSelection(orig) , fRng(nullptr) , fEnhanceSmearing(0.0) { SetEnhanceSmearing(orig.GetEnhanceSmearing()); } AliFemtoEventReaderAlt AliFemtoEventReaderAlt::operator=(const AliFemtoEventReaderAlt& rhs) { if (&rhs != this) { AliFemtoEventReaderAODMultSelection::operator=(rhs); SetEnhanceSmearing(rhs.GetEnhanceSmearing()); } return *this; } AliFemtoEventReaderAlt::~AliFemtoEventReaderAlt() { } void AliFemtoEventReaderAlt::SetEnhanceSmearing(double n) { if (fRng == nullptr) { fRng = new TRandom3(); } fEnhanceSmearing = n; } AliFemtoTrack* AliFemtoEventReaderAlt::CopyAODtoFemtoTrack(AliAODTrack *aod_trk) { auto *femto_trk = AliFemtoEventReaderAODMultSelection::CopyAODtoFemtoTrack(aod_trk); if (femto_trk) { femto_trk->SetITSchi2(aod_trk->GetITSchi2()); femto_trk->SetITSncls(aod_trk->GetITSNcls()); femto_trk->SetTPCchi2(aod_trk->GetTPCchi2()); femto_trk->SetTPCncls(aod_trk->GetTPCNcls()); femto_trk->SetTPCnclsF(aod_trk->GetTPCNclsF()); } if (fEnhanceSmearing != 0.0) { auto p = femto_trk->P(); p.SetX(p.x() * fRng->Gaus(1, fEnhanceSmearing)); p.SetY(p.y() * fRng->Gaus(1, fEnhanceSmearing)); p.SetZ(p.z() * fRng->Gaus(1, fEnhanceSmearing)); femto_trk->SetP(p); } return femto_trk; } void AliFemtoEventReaderAlt::CopyPIDtoFemtoTrack(AliAODTrack *aod_trk, AliFemtoTrack *femto_trk) { AliFemtoEventReaderAODMultSelection::CopyPIDtoFemtoTrack(aod_trk, femto_trk); femto_trk->SetITSchi2(aod_trk->GetITSchi2()); femto_trk->SetITSncls(aod_trk->GetITSNcls()); femto_trk->SetTPCchi2(aod_trk->GetTPCchi2()); femto_trk->SetTPCncls(aod_trk->GetTPCNcls()); femto_trk->SetTPCnclsF(aod_trk->GetTPCNclsF()); }
24.388235
91
0.742402
eciesla
9bd48fdba2625e8acba8115782bd487eb9a5f1dc
2,963
cpp
C++
Grafos_Estructuras_Particion/SerpientesEscaleras/SerpientesEscaleras.cpp
manumonforte/AdvancedAlgorithm
fe82ef552147a041e7ad717f85999eb677f5340a
[ "MIT" ]
4
2019-01-30T21:35:40.000Z
2019-06-25T03:19:44.000Z
Grafos_Estructuras_Particion/SerpientesEscaleras/SerpientesEscaleras.cpp
manumonforte/AdvancedAlgorithm
fe82ef552147a041e7ad717f85999eb677f5340a
[ "MIT" ]
null
null
null
Grafos_Estructuras_Particion/SerpientesEscaleras/SerpientesEscaleras.cpp
manumonforte/AdvancedAlgorithm
fe82ef552147a041e7ad717f85999eb677f5340a
[ "MIT" ]
3
2019-06-06T17:01:28.000Z
2021-06-27T10:55:34.000Z
// Manuel Monforte // TAIS62 #include <iostream> #include <iomanip> #include <fstream> #include "GrafoDirigido.h" #include <queue> //Coste del problema-->O(V+E) //La idea coniste en colocar todasd las aristas, y aprovechar el recorrido en anchura para sacar el camino a la ultima casilla, a la hora de colocar aristas //nos creamos un vector para saber si en ese vertice hay escalera y serpiente y donde apuntapara poder colocarlo como arista del vertice, class juegoSyE{ public: juegoSyE(GrafoDirigido & G, int s, int k,int ser, int esc) :D(k), marked(G.V(), false), SyE(G.V(), -1), distTo(G.V()) { //leemos serpientes y escaleras leerSyE(G,ser, esc,D); bfs(G, s); int x = 1; } // ¿Hay camino del origen a v? bool hayCamino(int v) const { return marked[v]; } // número de aristas entre s y v int distancia(int v) const { return distTo[v]; } private: int D;//caras del dado std::vector<bool> marked; // marked[v] = ¿hay camino de s a v? std::vector<int> distTo; // distTo[v] = aristas en el camino s-v más corto std::vector<int>SyE;//vector que marca si hay S o E en la casilla void bfs(GrafoDirigido & G, int s) { std::queue<int> q; distTo[s] = 0; marked[s] = true; q.push(s); while (!q.empty()) { int v = q.front(); q.pop(); for (int w : G.ady(v)) { if (!marked[w]) { distTo[w] = distTo[v] +1; marked[w] = true; q.push(w); } } } } void leerSyE(GrafoDirigido & G,int s, int e,int K){ int v, w; //leemos serpientes y las colocamos for (int i = 0; i < s; i++){ std::cin >> v >> w; SyE[v - 1] = w-1; } //leemos escaleras y las colocamos for (int i = 0; i < e; i++){ std::cin >> v >> w; SyE[v - 1] = w-1; } //colocamos aristas segun las caras del dado //ponemos todas las aristas para ir avanzando dependiendo de las caras del dado for (int i = 0; i < G.V(); i++){ for (int j = i+1; j <= K+i && j <= G.V() - 1; j++){ // si en esa casilla hay serpiente o escalera,colocamos el destino como arista if (SyE[j]!=-1) G.ponArista(i, SyE[j]); else G.ponArista(i, j); } } } }; // Resuelve un caso de prueba, leyendo de la entrada la // configuración, y escribiendo la respuesta bool resuelveCaso() { // leer los datos de la entrada int N, K, S, E; std::cin >> N; if (!N) return false; std::cin >> K >> S >> E; GrafoDirigido tablero(N*N); juegoSyE mejorPartida(tablero,0,K,S,E); // escribir sol std::cout << mejorPartida.distancia(tablero.V()-1) << "\n"; return true; } int main() { // Para la entrada por fichero. // Comentar para acepta el reto #ifndef DOMJUDGE std::ifstream in("datos.txt"); auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save old buf and redirect std::cin to casos.txt #endif while (resuelveCaso()) ; // Para restablecer entrada. Comentar para acepta el reto #ifndef DOMJUDGE // para dejar todo como estaba al principio std::cin.rdbuf(cinbuf); system("PAUSE"); #endif return 0; }
24.089431
156
0.629767
manumonforte
9bdba0b51f30c4a80598fd5ba7c5bc60631e5b35
1,855
hpp
C++
3rdparty/libbitcoin/src/wallet/parse_encrypted_keys/parse_encrypted_token.hpp
anatolse/beam
43c4ce0011598641d9cdeffbfdee66fde0a49730
[ "Apache-2.0" ]
631
2018-11-10T05:56:05.000Z
2022-03-30T13:21:00.000Z
3rdparty/libbitcoin/src/wallet/parse_encrypted_keys/parse_encrypted_token.hpp
anatolse/beam
43c4ce0011598641d9cdeffbfdee66fde0a49730
[ "Apache-2.0" ]
1,824
2018-11-08T11:32:58.000Z
2022-03-28T12:33:03.000Z
3rdparty/libbitcoin/src/wallet/parse_encrypted_keys/parse_encrypted_token.hpp
anatolse/beam
43c4ce0011598641d9cdeffbfdee66fde0a49730
[ "Apache-2.0" ]
216
2018-11-12T08:07:21.000Z
2022-03-08T20:50:19.000Z
/** * Copyright (c) 2011-2017 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBBITCOIN_PARSE_ENCRYPTED_TOKEN_HPP #define LIBBITCOIN_PARSE_ENCRYPTED_TOKEN_HPP #include <cstdint> #include <cstddef> #include <bitcoin/bitcoin/math/hash.hpp> #include <bitcoin/bitcoin/utility/data.hpp> #include <bitcoin/bitcoin/wallet/encrypted_keys.hpp> #include "parse_encrypted_key.hpp" namespace libbitcoin { namespace wallet { // Swap not defined. class parse_encrypted_token : public parse_encrypted_prefix<8u> { public: static byte_array<prefix_size> prefix_factory(bool lot_sequence); explicit parse_encrypted_token(const encrypted_token& value); bool lot_sequence() const; hash_digest data() const; ek_entropy entropy() const; one_byte sign() const; private: bool verify_context() const; bool verify_magic() const; static constexpr uint8_t lot_context_ = 0x51; static constexpr uint8_t default_context_ = 0x53; static const byte_array<magic_size> magic_; const ek_entropy entropy_; const one_byte sign_; const hash_digest data_; }; } // namespace wallet } // namespace libbitcoin #endif
29.444444
78
0.754717
anatolse
9be246f01f7cb05991c9745c0da67d2a685e30d5
2,583
cpp
C++
codelib/data_structs/segtree_iter_lazy.cpp
TissueRoll/admu-progvar-notebook
efd1c48872d40aeabe2b03af7b986bb831c062b1
[ "MIT" ]
null
null
null
codelib/data_structs/segtree_iter_lazy.cpp
TissueRoll/admu-progvar-notebook
efd1c48872d40aeabe2b03af7b986bb831c062b1
[ "MIT" ]
null
null
null
codelib/data_structs/segtree_iter_lazy.cpp
TissueRoll/admu-progvar-notebook
efd1c48872d40aeabe2b03af7b986bb831c062b1
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdlib> #include <cassert> #include <ctime> using namespace std; const int MAX_N = 100001; int N; long long ar[MAX_N], vals[4*MAX_N], temp_vals[4*MAX_N]; void build(int idx, int lo, int hi) { temp_vals[idx] = 0; if (lo == hi) { vals[idx] = ar[lo]; } else { int k = (lo + hi) / 2; build(2*idx, lo, k); build(2*idx+1, k+1, hi); vals[idx] = vals[2*idx] + vals[2*idx+1]; } } void build() { build(1, 0, N-1); } void visit(int idx, int left, int right) { if (temp_vals[idx]) { vals[idx] += (right - left + 1) * temp_vals[idx]; if (2*idx < 4*MAX_N) { temp_vals[2*idx] += temp_vals[idx]; temp_vals[2*idx+1] += temp_vals[idx]; } temp_vals[idx] = 0; } } void increase(int idx, int left, int right, int lo, int hi, long long val) { visit(idx, left, right); if (lo <= left && right <= hi) { temp_vals[idx] += val; visit(idx, left, right); } else if (hi < left || right < lo) { // do nothing } else { int k = (left + right) / 2; increase(2*idx, left, k, lo, hi, val); increase(2*idx+1, k+1, right, lo, hi, val); vals[idx] = vals[2*idx] + vals[2*idx+1]; } } void increase(int lo, int hi, long long val) { increase(1, 0, N-1, lo, hi, val); } long long sum(int idx, int left, int right, int lo, int hi) { visit(idx, left, right); if (lo <= left && right <= hi) { return vals[idx]; } else if (hi < left || right < lo) { return 0; } else { int k = (left + right) / 2; return sum(2*idx, left, k, lo, hi) + sum(2*idx+1, k+1, right, lo, hi); } } long long sum(int lo, int hi) { sum(1, 0, N-1, lo, hi); } int main() { srand((unsigned)time(0)); N = 100000; int Q = 100000; bool TEST = false; long long br[N]; for (int i = 0; i < N; ++i) ar[i] = br[i] = rand(); build(); while (Q--) { int type = rand()%2; if (type == 0) { int lo = rand()%N; int hi = rand()%N; if (lo > hi) swap(lo, hi); int val = rand(); increase(lo, hi, val); if (TEST) { for (int i = lo; i <= hi; ++i) br[i] += val; for (int i = lo; i <= hi; ++i) assert(br[i] == sum(i, i)); } } else if (type == 1) { int lo = rand()%N; int hi = rand()%N; if (lo > hi) swap(lo, hi); long long res1 = sum(lo, hi); if (TEST) { long long res2 = 0; for (int i = lo; i <= hi; ++i) res2 += br[i]; assert(res1 == res2); } } else { assert(type == 0 || type == 1); } } return 0; }
20.664
76
0.498258
TissueRoll
9be4dd1be7b97424e4532fe0777f83afd84bb229
4,594
cpp
C++
11_learning_materials/stanford_self_driving_car/perception/velodyne/src/vlf_cut.cpp
EatAllBugs/autonomous_learning
02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47
[ "MIT" ]
14
2021-09-01T14:25:45.000Z
2022-02-21T08:49:57.000Z
11_learning_materials/stanford_self_driving_car/perception/velodyne/src/vlf_cut.cpp
yinflight/autonomous_learning
02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47
[ "MIT" ]
null
null
null
11_learning_materials/stanford_self_driving_car/perception/velodyne/src/vlf_cut.cpp
yinflight/autonomous_learning
02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47
[ "MIT" ]
3
2021-10-10T00:58:29.000Z
2022-01-23T13:16:09.000Z
/******************************************************** Stanford Driving Software Copyright (c) 2011 Stanford University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ********************************************************/ #include <logio.h> #include <applanix_interface.h> #include <velo_support.h> namespace dgc { int dgc_velodyne_write_packet(dgc_FILE* fp, double timestamp, unsigned char* msg_buffer) { int n; unsigned short len; n = dgc_fputc(VLF_START_BYTE, fp); if(n != VLF_START_BYTE) { fprintf(stderr, "# ERROR: could not write start byte.\n"); perror("Could not write start byte"); return -1; } n = dgc_fwrite(&timestamp, 8, 1, fp); if(n != 1) { fprintf(stderr, "Error: could not write time stamp.\n"); return -1; } len = VELO_PACKET_SIZE; n = dgc_fwrite(&len, 2, 1, fp); if(n != 1) { fprintf(stderr, "Error: could not write packet length.\n"); return -1; } n = dgc_fwrite(msg_buffer, len+1, 1, fp); if(n != 1) { fprintf(stderr, "Error: could not write message buffer.\n"); return -1; } return 0; } } // namespace dgc using namespace dgc; int main(int argc, char **argv) { double start_time, end_time = 1e6; char velodyne_in_file[200]; char velodyne_out_file[200]; int err; dgc_velodyne_packet_t pkt; dgc_velodyne_file_p velodyne = NULL; dgc_FILE* fout; if(argc < 3) dgc_die("Error: not enough arguments.\n" "Usage: %s logfile start-second [end-second]\n" " seconds since beginning of logfile\n", argv[0]); start_time = atof(argv[2]); if(argc >= 4) end_time = atof(argv[3]); strcpy(velodyne_in_file, argv[1]); strcpy(velodyne_out_file, argv[1]); if(strcmp(velodyne_out_file + strlen(velodyne_out_file) - 4, ".vlf") == 0) strcpy(velodyne_out_file + strlen(velodyne_out_file) - 4, "-cut.vlf"); else dgc_die("Error: input logfile must end in .vlf\n"); fout = dgc_fopen(velodyne_out_file, "w"); if(fout == NULL) dgc_die("Error: could not open file %s for writing.\n", velodyne_out_file); fprintf(stderr, "Opening logfile... "); /* prepare velodyne */ velodyne = dgc_velodyne_open_file(velodyne_in_file); if(velodyne == NULL) dgc_die("Error: could not open velodyne file %s\n", velodyne_in_file); err = dgc_velodyne_read_packet(velodyne, &pkt); if (err) dgc_die("Error: could not read velodyne file %s\n", velodyne_in_file); start_time += pkt.timestamp; end_time += pkt.timestamp; int count = 0; while (pkt.timestamp < start_time) { count++; int err = dgc_velodyne_read_packet(velodyne, &pkt); if (err) break; } fprintf(stderr, "skipped %d packets\n", count); count = 0; while (pkt.timestamp <= end_time) { count++; err = dgc_velodyne_write_packet(fout, pkt.timestamp, velodyne->msg_buffer); if (err) dgc_die("Error: could not write to file %s\n", velodyne_out_file); err = dgc_velodyne_read_packet(velodyne, &pkt); if (err) break; } fprintf(stderr, "wrote %d packets about %f seconds\n", count, count / 10.0); fprintf(stderr, "done.\n"); dgc_fclose(velodyne->fp); dgc_fclose(fout); return 0; }
29.831169
84
0.681541
EatAllBugs
9bf0ea0f962b1a1d8e26f8bb12f8ad6f70f033a2
480
cpp
C++
source/Texture.cpp
xzrunner/gum
b9170ae8b65e8686766dd57c01a48694722eb999
[ "MIT" ]
null
null
null
source/Texture.cpp
xzrunner/gum
b9170ae8b65e8686766dd57c01a48694722eb999
[ "MIT" ]
null
null
null
source/Texture.cpp
xzrunner/gum
b9170ae8b65e8686766dd57c01a48694722eb999
[ "MIT" ]
null
null
null
#include "gum/Texture.h" #include "gum/RenderContext.h" #include <unirender/RenderContext.h> #include <unirender/Blackboard.h> #include <shaderlab/Blackboard.h> #include <shaderlab/ShaderMgr.h> #include <shaderlab/RenderContext.h> namespace gum { Texture::Texture(uint16_t w, uint16_t h, uint32_t id, int format) : pt2::Texture(w, h, id, format) { } Texture::~Texture() { auto& ur_rc = ur::Blackboard::Instance()->GetRenderContext(); ur_rc.ReleaseTexture(GetTexID()); } }
19.2
65
0.73125
xzrunner
9bf2c1dc289b9f53c7fd6de5b57655fc9ff974ce
6,114
cc
C++
src/partition.cc
felix-halim/indexing-benchmark
f6325aff444c7bb0403588195cca83d767ca0144
[ "MIT" ]
5
2017-07-27T14:00:03.000Z
2017-11-29T05:09:58.000Z
src/partition.cc
felix-halim/indexing-benchmark
f6325aff444c7bb0403588195cca83d767ca0144
[ "MIT" ]
5
2017-06-15T06:58:18.000Z
2017-06-16T08:02:45.000Z
src/partition.cc
felix-halim/c-tree
f6325aff444c7bb0403588195cca83d767ca0144
[ "MIT" ]
null
null
null
/* To run, go to the root folder and execute: make partition */ #include <cassert> #include <cstdio> #include <algorithm> #include <functional> #include <vector> #include "random.h" #include "time_it.h" #define BSIZE (1 << 12) #define block_size 64 static long long arr[BSIZE]; int std_partition(long long p) { return int( std::partition(arr, arr + BSIZE, [p](long long v) { return v < p; }) - arr); } template <typename RandomAccessIterator> void swap_offsets(RandomAccessIterator first, RandomAccessIterator last, unsigned char* hi, unsigned char* lo, int num, bool use_swaps) { typedef typename std::iterator_traits<RandomAccessIterator>::value_type T; if (use_swaps) { // This case is needed for the descending distribution, where we need // to have proper swapping for pdqsort to remain O(n). for (int i = 0; i < num; ++i) { std::iter_swap(first + hi[i], last - lo[i]); } } else if (num > 0) { RandomAccessIterator l = first + hi[0]; RandomAccessIterator r = last - lo[0]; T tmp(*l); *l = *r; for (int i = 1; i < num; ++i) { l = first + hi[i]; *r = (*l); r = last - lo[i]; *l = (*r); } *r = (tmp); } } long long* partition_right_branchless(long long* begin, long long* end, long long pivot) { long long* first = begin; long long* last = end; auto comp = std::less<long long>(); while (first < last && comp(*first, pivot)) first++; while (first < last && !comp(*(last - 1), pivot)) last--; // The branchless partitioning is derived from "BlockQuicksort: How Branch // Mispredictions don’t affect Quicksort" by Stefan Edelkamp and Armin Weiss. unsigned char hi[block_size]; unsigned char lo[block_size]; int nhi = 0, nlo = 0, ihi = 0, ilo = 0; while (last - first > 2 * block_size) { if (nhi == 0) { ihi = 0; long long* it = first; for (unsigned char i = 0; i < block_size;) { hi[nhi] = i++; nhi += !comp(*it++, pivot); hi[nhi] = i++; nhi += !comp(*it++, pivot); hi[nhi] = i++; nhi += !comp(*it++, pivot); hi[nhi] = i++; nhi += !comp(*it++, pivot); hi[nhi] = i++; nhi += !comp(*it++, pivot); hi[nhi] = i++; nhi += !comp(*it++, pivot); hi[nhi] = i++; nhi += !comp(*it++, pivot); hi[nhi] = i++; nhi += !comp(*it++, pivot); } } if (nlo == 0) { ilo = 0; long long* it = last; for (unsigned char i = 0; i < block_size;) { lo[nlo] = ++i; nlo += comp(*--it, pivot); lo[nlo] = ++i; nlo += comp(*--it, pivot); lo[nlo] = ++i; nlo += comp(*--it, pivot); lo[nlo] = ++i; nlo += comp(*--it, pivot); lo[nlo] = ++i; nlo += comp(*--it, pivot); lo[nlo] = ++i; nlo += comp(*--it, pivot); lo[nlo] = ++i; nlo += comp(*--it, pivot); lo[nlo] = ++i; nlo += comp(*--it, pivot); } } // Swap elements and update block sizes and first/last boundaries. int num = std::min(nhi, nlo); swap_offsets(first, last, hi + ihi, lo + ilo, num, nhi == nlo); nhi -= num; nlo -= num; ihi += num; ilo += num; if (nhi == 0) first += block_size; if (nlo == 0) last -= block_size; } int l_size = 0, r_size = 0; int unknown_left = int((last - first) - ((nlo || nhi) ? block_size : 0)); if (nlo) { // Handle leftover block by assigning the unknown elements to the other // block. l_size = unknown_left; r_size = block_size; } else if (nhi) { l_size = block_size; r_size = unknown_left; } else { // No leftover block, split the unknown elements in two blocks. l_size = unknown_left / 2; r_size = unknown_left - l_size; } // Fill offset buffers if needed. if (unknown_left && !nhi) { ihi = 0; long long* it = first; for (unsigned char i = 0; i < l_size;) { hi[nhi] = i++; nhi += !comp(*it++, pivot); } } if (unknown_left && !nlo) { ilo = 0; long long* it = last; for (unsigned char i = 0; i < r_size;) { lo[nlo] = ++i; nlo += comp(*--it, pivot); } } int num = std::min(nhi, nlo); swap_offsets(first, last, hi + ihi, lo + ilo, num, nhi == nlo); nhi -= num; nlo -= num; ihi += num; ilo += num; if (nhi == 0) first += l_size; if (nlo == 0) last -= r_size; // We have now fully identified [first, last)'s proper position. Swap the last // elements. if (nhi) { while (nhi--) std::iter_swap(first + hi[ihi + nhi], --last); first = last; } if (nlo) { while (nlo--) std::iter_swap(last - lo[ilo + nlo], first), ++first; last = first; } // Put the pivot in the right place. return first; } int fusion(long long p) { return int(partition_right_branchless(arr, arr + BSIZE, p) - arr); } int lo[BSIZE], hi[BSIZE]; int marker(long long p) { int nhi = 0, nlo = 0; for (int i = 0; i < BSIZE; i++) { hi[nhi] = i; nhi += (arr[i] >= p); } for (int i = 0; i < BSIZE; i++) { lo[nlo] = i; nlo += (arr[i] < p); } int* hip = hi; int* lop = lo + nlo - 1; int m = std::min(nhi, nlo); while (m-- && *hip < *lop) { std::swap(arr[*(hip++)], arr[*(lop--)]); } return nlo; } int main() { Random rng(140384); double total_time = 0; long long chk = 0; for (int m = 0; m < 200000; m++) { for (int i = 0; i < BSIZE; i++) { arr[i] = rng.nextLong(); } long long p = arr[rng.nextInt(BSIZE)]; int pos = -1; total_time += time_it([&]() { // pos = std_partition(p); pos = fusion(p); // pos = marker(p); }); // fprintf(stderr, "pos = %d\n", pos); for (int i = 0; i < BSIZE; i++) { // fprintf(stderr, "%4d %4d %20lld, %20lld\n", i, pos, arr[i], p); assert((i < pos) ? (arr[i] < p) : (arr[i] >= p)); } chk = chk * 13 + pos; } fprintf(stderr, "tt = %.6lf, chk = %lld\n", total_time, chk); assert(chk == 2144819404491265167LL); }
25.369295
80
0.519136
felix-halim
5000b217366934b4aa8ae73b251ff6f122af2f33
2,308
cpp
C++
tests/models/Ising2dTest.cpp
dtoconnor/quantum-monte-carlo-methods
c599ec010954c7c4f8ad62076e408a70b8ff2f13
[ "MIT" ]
15
2018-11-15T00:51:51.000Z
2021-11-17T06:26:14.000Z
tests/models/Ising2dTest.cpp
dtoconnor/quantum-monte-carlo-methods
c599ec010954c7c4f8ad62076e408a70b8ff2f13
[ "MIT" ]
null
null
null
tests/models/Ising2dTest.cpp
dtoconnor/quantum-monte-carlo-methods
c599ec010954c7c4f8ad62076e408a70b8ff2f13
[ "MIT" ]
4
2019-01-29T11:56:22.000Z
2021-11-24T15:19:54.000Z
#include <QMC-methods.h> #include <catch2/catch.hpp> using namespace QMCm; TEST_CASE("Ising2d Ising2d()", "[ising]") { Ising2d ising; REQUIRE(ising.nodes.size() == 0); } TEST_CASE("Ising2d generate()", "[ising]") { Ising2d ising; ising.generate(); for (int i = 0; i < ising.nodes.size(); i++) for (int j = 0; j < ising.nodes[i].size(); j++) REQUIRE(ising.nodes[i][j].id == std::to_string(i) + "-" + std::to_string(j)); for (int i = 0; i < ising.arcs.size(); i++) for (int j = 0; j < ising.arcs[i].size(); j++) for (int k = 0; k < ising.arcs[i][j].size(); k++) if (i > 0 && j > 0) { REQUIRE(ising.arcs[i][j][k].node1 != nullptr); REQUIRE(ising.arcs[i][j][k].node2 != nullptr); REQUIRE(ising.arcs[i][j][k].node1->id == std::to_string(i) + "-" + std::to_string(j)); } ising.size = 1; ising.generate(); REQUIRE(ising.arcs.size() == 1); REQUIRE(ising.nodes.size() == 1); ising.size = 2; ising.generate(); REQUIRE(ising.arcs.size() == 2); REQUIRE(ising.nodes.size() == 2); } TEST_CASE("Ising2d getEnergy()", "[ising]") { Ising2d ising; REQUIRE(ising.getEnergy() == 0); ising.generate(); double energy = ising.getEnergy(); ising.periodicBoundary = true; ising.generate(); REQUIRE(ising.getEnergy() != energy); } TEST_CASE("Ising2d ising1 = ising2", "[ising]") { Ising2d ising1, ising2; ising1.size = 2; ising1.periodicBoundary = true; ising1.generate(); ising2 = ising1; REQUIRE(ising2.size == ising1.size); REQUIRE(ising2.periodicBoundary == ising1.periodicBoundary); REQUIRE(ising2.getEnergy() == ising1.getEnergy()); ising1.nodes[0][0].flip(); REQUIRE(ising2.getEnergy() != ising1.getEnergy()); } TEST_CASE("Ising2d getDelta()", "[ising1,ising2]") { Ising2d ising1, ising2; ising1.size = 1; ising2.size = 1; ising1.generate(); ising2.generate(); ising1.nodes[0][0].spin = 1; ising1.nodes[0][0].value = 1; ising2.nodes[0][0].spin = 1; ising2.nodes[0][0].value = 1; REQUIRE(ising1.getEnergy() == -1); REQUIRE(ising2.getEnergy() == -1); REQUIRE(ising1.getDelta(ising2) == 0); REQUIRE(ising2.getDelta(ising1) == 0); ising1.nodes[0][0].value = 2; REQUIRE(ising1.getDelta(ising2) == -1); REQUIRE(ising2.getDelta(ising1) == 1); }
30.368421
96
0.607019
dtoconnor
5001779936468270aaf05dfcb32a5bfa0252a856
1,057
cpp
C++
c-and-cpp/Community-Course-Project-16.06/Community-Project/ProjectExamples.cpp
dkalinkov/fmi-projects
367cb50ba57b00c604380a984e71ede003ef027b
[ "MIT" ]
null
null
null
c-and-cpp/Community-Course-Project-16.06/Community-Project/ProjectExamples.cpp
dkalinkov/fmi-projects
367cb50ba57b00c604380a984e71ede003ef027b
[ "MIT" ]
null
null
null
c-and-cpp/Community-Course-Project-16.06/Community-Project/ProjectExamples.cpp
dkalinkov/fmi-projects
367cb50ba57b00c604380a984e71ede003ef027b
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <stdlib.h> #include "Person.h" #include "Community.h" using std::cout; using std::endl; using std::vector; void writeInFile(char*, const Community&); int main() { try { char fileName[] = "com-info.txt"; Person pesho("pesho", "8578213741", "u tqh si jivee", Baker, 518); Person tosho("tosho", "9191198191", "hamalskata", Baker, 189); Person gosho("pesho", "9484166161", "sunny beach", Baker, 789); Person grozo("grozo", "8894951989", "sunny beach", Baker, 326); gosho.SetName("gosho"); Community sik("SIK", "10.10.10", gosho, 100); sik.AddMember(tosho); Community vis = sik; vis.SetName("VIS"); vis.RemoveMember(gosho.GetEGN()); vis.AddMember(pesho); vis.AddMember(grozo); cout << vis.GetComCount(); writeInFile(fileName, vis); } catch (std::exception& ex) { cout << ex.what(); } return 0; } void writeInFile(char* fileName, const Community& com) { std::ofstream file(fileName); if(file.is_open()) { file << com; } file.close(); }
19.574074
68
0.640492
dkalinkov
50043ab9a810bf087e721e5d99fa32b777afd037
7,425
cxx
C++
src/sprokit/pipeline/modules.cxx
linus-sherrill/sprokit
6b3f6cf87f625904e9061a447bd16f96800fef77
[ "BSD-3-Clause" ]
14
2015-05-02T17:06:34.000Z
2019-06-20T10:10:20.000Z
src/sprokit/pipeline/modules.cxx
linus-sherrill/sprokit
6b3f6cf87f625904e9061a447bd16f96800fef77
[ "BSD-3-Clause" ]
3
2015-02-11T20:09:24.000Z
2018-09-04T21:45:56.000Z
src/sprokit/pipeline/modules.cxx
linus-sherrill/sprokit
6b3f6cf87f625904e9061a447bd16f96800fef77
[ "BSD-3-Clause" ]
9
2015-08-19T04:48:16.000Z
2021-02-15T14:28:06.000Z
/*ckwg +29 * Copyright 2011-2013 by Kitware, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither name of Kitware, Inc. nor the names of any contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "modules.h" #if defined(_WIN32) || defined(_WIN64) #include <sprokit/pipeline/module-paths.h> #endif #include "utils.h" #include <sprokit/pipeline_util/path.h> #include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/filesystem/operations.hpp> #include <boost/foreach.hpp> #include <string> #include <vector> #if defined(_WIN32) || defined(_WIN64) #include <windows.h> #else #include <dlfcn.h> #endif #include <cstddef> #include <iostream> /** * \file modules.cxx * * \brief Implementation of module loading. */ namespace sprokit { namespace { #if defined(_WIN32) || defined(_WIN64) typedef HMODULE library_t; typedef FARPROC function_t; #else typedef void* library_t; typedef void* function_t; #endif typedef void (*load_module_t)(); typedef path_t::string_type module_path_t; typedef std::vector<module_path_t> module_paths_t; typedef std::string lib_suffix_t; typedef std::string function_name_t; } static void look_in_directory(module_path_t const& directory); static void load_from_module(module_path_t const& path); static bool is_separator(module_path_t::value_type ch); static function_name_t const process_function_name = function_name_t("register_processes"); static function_name_t const scheduler_function_name = function_name_t("register_schedulers"); static module_path_t const default_module_dirs = module_path_t(DEFAULT_MODULE_PATHS); static envvar_name_t const sprokit_module_envvar = envvar_name_t("SPROKIT_MODULE_PATH"); static lib_suffix_t const library_suffix = lib_suffix_t(LIBRARY_SUFFIX); void load_known_modules() { module_paths_t module_dirs; envvar_value_t const extra_module_dirs = get_envvar(sprokit_module_envvar); if (extra_module_dirs) { boost::split(module_dirs, *extra_module_dirs, is_separator, boost::token_compress_on); } module_paths_t module_dirs_tmp; boost::split(module_dirs_tmp, default_module_dirs, is_separator, boost::token_compress_on); module_dirs.insert(module_dirs.end(), module_dirs_tmp.begin(), module_dirs_tmp.end()); BOOST_FOREACH (module_path_t const& module_dir, module_dirs) { look_in_directory(module_dir); #ifdef USE_CONFIGURATION_SUBDIRECTORY module_path_t const subdir = module_dir + #if defined(_WIN32) || defined(_WIN64) L"/" SPROKIT_CONFIGURATION_L; #else "/" SPROKIT_CONFIGURATION; #endif ; look_in_directory(subdir); #endif } } void look_in_directory(module_path_t const& directory) { if (directory.empty()) { return; } if (!boost::filesystem::exists(directory)) { /// \todo Log error that path doesn't exist. return; } if (!boost::filesystem::is_directory(directory)) { /// \todo Log error that path isn't a directory. return; } boost::system::error_code ec; boost::filesystem::directory_iterator module_dir_iter(directory, ec); while (module_dir_iter != boost::filesystem::directory_iterator()) { boost::filesystem::directory_entry const ent = *module_dir_iter; ++module_dir_iter; if (!boost::ends_with(ent.path().native(), library_suffix)) { continue; } if (ent.status().type() != boost::filesystem::regular_file) { /// \todo Log warning that we found a non-file matching path. continue; } load_from_module(ent.path().native()); } } // ---------------------------------------------------------------- /** * \brief Load single module from shared object / DLL * * @param path Name of module to load. */ void load_from_module(module_path_t const& path) { library_t library = NULL; #if defined(_WIN32) || defined(_WIN64) library = LoadLibraryW(path.c_str()); #else dlerror(); // clear error message library = dlopen(path.c_str(), RTLD_GLOBAL | RTLD_LAZY); #endif if (!library) { /// \todo Log an error. Also have system dependent way of getting error. // This is important because libraries used by these modules can cause failure if // they are not found. std::cerr << "ERROR - Unable to load module: " << path << " (" << dlerror() << ")" << std::endl; return; } function_t process_function = NULL; function_t scheduler_function = NULL; #if defined(_WIN32) || defined(_WIN64) process_function = GetProcAddress(library, process_function_name.c_str()); scheduler_function = GetProcAddress(library, scheduler_function_name.c_str()); #else process_function = dlsym(library, process_function_name.c_str()); scheduler_function = dlsym(library, scheduler_function_name.c_str()); #endif #ifdef __GNUC__ // See https://trac.osgeo.org/qgis/ticket/234#comment:17 __extension__ #endif load_module_t const process_registrar = reinterpret_cast<load_module_t>(process_function); #ifdef __GNUC__ // See https://trac.osgeo.org/qgis/ticket/234#comment:17 __extension__ #endif load_module_t const scheduler_registrar = reinterpret_cast<load_module_t>(scheduler_function); bool functions_found = false; if (process_registrar) { /// \todo Log info that we have loaded processes. std::cerr << "INFO - Processes from module " << path << " loaded\n"; (*process_registrar)(); functions_found = true; } if (scheduler_registrar) { /// \todo Log info that we have loaded schedulers. (*scheduler_registrar)(); functions_found = true; } if (!functions_found) { #if defined(_WIN32) || defined(_WIN64) int const ret = FreeLibrary(library); if (!ret) { /// \todo Log the error. } #else int const ret = dlclose(library); if (ret) { /// \todo Log the error. } #endif } } bool is_separator(module_path_t::value_type ch) { module_path_t::value_type const separator = #if defined(_WIN32) || defined(_WIN64) ';'; #else ':'; #endif return (ch == separator); } }
26.805054
96
0.719461
linus-sherrill
5008e6e941e54c3abdde6c2bf90f08388ba15034
1,221
hpp
C++
include/model/MachineLearningModel.hpp
fdbresearch/FBENCH
9f6c4ea79448649a74d2136ead93e4e5008a33a5
[ "Apache-2.0" ]
3
2019-02-28T11:29:45.000Z
2021-03-24T23:22:05.000Z
include/model/MachineLearningModel.hpp
fdbresearch/FBENCH
9f6c4ea79448649a74d2136ead93e4e5008a33a5
[ "Apache-2.0" ]
null
null
null
include/model/MachineLearningModel.hpp
fdbresearch/FBENCH
9f6c4ea79448649a74d2136ead93e4e5008a33a5
[ "Apache-2.0" ]
1
2021-03-19T02:56:16.000Z
2021-03-19T02:56:16.000Z
//===----------------------------------------------------------------------===// // // FBench // // https://fdbresearch.github.io/ // // Copyright (c) 2019, FDB Research Group, University of Oxford // //===----------------------------------------------------------------------===// #ifndef INCLUDE_ML_MACHINELEARNINGMODEL_HPP_ #define INCLUDE_ML_MACHINELEARNINGMODEL_HPP_ #include <memory> #include <DataHandler.hpp> /** * Abstract class to provide a uniform interface used to process the received data. */ class MachineLearningModel { public: virtual ~MachineLearningModel() { } /** * Runs the data processing task. */ virtual void run() = 0; /** * Returns the features extracted from the configuration files. */ virtual int** getFeatures() = 0; /** * Returns the cofactor matrix produced by the engine. */ virtual dfdb::types::ResultType* getCofactorMatrix() = 0; protected: //! Method calculates the number of combinations (nCk) unsigned int choose(unsigned int n, unsigned int k) { if (k > n) { return 0; } unsigned int r = 1; for (unsigned int d = 1; d <= k; ++d) { r *= n--; r /= d; } return r; } }; #endif /* INCLUDE_ML_MACHINELEARNINGMODEL_HPP_ */
18.784615
83
0.580672
fdbresearch
500a7b41ca7d3aa352990740624435d6420eb49b
2,429
cc
C++
Codeforces/361 Division 2/Problem D/D.cc
VastoLorde95/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
170
2017-07-25T14:47:29.000Z
2022-01-26T19:16:31.000Z
Codeforces/361 Division 2/Problem D/D.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
null
null
null
Codeforces/361 Division 2/Problem D/D.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
55
2017-07-28T06:17:33.000Z
2021-10-31T03:06:22.000Z
#include <bits/stdc++.h> #define sd(x) scanf("%d",&x) #define sd2(x,y) scanf("%d%d",&x,&y) #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define fi first #define se second #define pb push_back #define mp make_pair #define foreach(it, v) for(__typeof((v).begin()) it=(v).begin(); it != (v).end(); ++it) #define meta __FUNCTION__,__LINE__ #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout); using namespace std; const long double PI = 3.1415926535897932384626433832795; template<typename S, typename T> ostream& operator<<(ostream& out,pair<S,T> const& p){out<<'('<<p.fi<<", "<<p.se<<')';return out;} template<typename T> ostream& operator<<(ostream& out,vector<T> const& v){ int l=v.size();for(int i=0;i<l-1;i++)out<<v[i]<<' ';if(l>0)out<<v[l-1];return out;} void tr(){cout << endl;} template<typename S, typename ... Strings> void tr(S x, const Strings&... rest){cout<<x<<' ';tr(rest...);} typedef long long ll; typedef pair<int,int> pii; const int LOGN = 18; const int N = 1 << LOGN; int n; int sp1[LOGN][N]; int sp2[LOGN][N]; int k[N], o[N]; int a[N], b[N]; void sparseTable(){ for(int i = 0; i < n; i++){ sp1[0][i] = a[i], sp2[0][i] = b[i]; } for(int j = 1; j < LOGN; j++){ for(int i = 0; (i+(1<<j)-1) < n; i++){ sp1[j][i] = max(sp1[j-1][i], sp1[j-1][i+(1<<(j-1))]); sp2[j][i] = min(sp2[j-1][i], sp2[j-1][i+(1<<(j-1))]); } } for(int i = 2; i < n; i++){ k[i] = k[i-1] + ((i&(i-1)) == 0); o[i] = (k[i] == k[i-1])? o[i-1] : (o[i-1] << 1)+1; } } int mx(int x, int y){ int l = y-x+1; return max(sp1[k[l]][x], sp1[k[l]][y-o[l]]); } int mn(int x, int y){ int l = y-x+1; return min(sp2[k[l]][x], sp2[k[l]][y-o[l]]); } int getLeft(int x){ int lo = x-1, hi = n-1, mid; while(lo+1 < hi){ mid = (lo + hi) >> 1; if(mx(x,mid) >= mn(x,mid)) hi = mid; else lo = mid; } if(mx(x,hi) != mn(x,hi)) hi = -1; return hi; } int getRight(int x, int y){ int lo = y, hi = n, mid; while(lo+1 < hi){ mid = (lo + hi) >> 1; if(mx(x,mid) == mn(x,mid)) lo = mid; else hi = mid; } return lo; } int main(){ sd(n); for(int i = 0; i < n; i++) sd(a[i]); for(int i = 0; i < n; i++) sd(b[i]); sparseTable(); ll ans = 0; int x; for(int i = 0; i < n; i++){ if(a[i] > b[i]) continue; if((x = getLeft(i)) == -1) continue; ans += getRight(i, x)-x+1; } printf("%I64d\n", ans); return 0; }
22.081818
97
0.541375
VastoLorde95
500f17ccdbad5b03f50c4843c501dfdd384aeaca
693
hpp
C++
phoenix/cocoa/widget/combo-button.hpp
vgmtool/vgm2pre
f4f917df35d531512292541234a5c1722b8af96f
[ "MIT" ]
21
2015-04-13T03:07:12.000Z
2021-11-20T00:27:00.000Z
phoenix/cocoa/widget/combo-button.hpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
2
2015-10-06T14:59:48.000Z
2022-01-27T08:57:57.000Z
phoenix/cocoa/widget/combo-button.hpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
2
2021-11-19T08:36:57.000Z
2022-03-04T16:03:16.000Z
@interface CocoaComboButton : NSPopUpButton { @public phoenix::ComboButton* comboButton; } -(id) initWith:(phoenix::ComboButton&)comboButton; -(IBAction) activate:(id)sender; @end namespace phoenix { struct pComboButton : public pWidget { ComboButton& comboButton; CocoaComboButton* cocoaComboButton = nullptr; void append(string text); Size minimumSize(); void remove(unsigned selection); void reset(); void setGeometry(Geometry geometry); void setSelection(unsigned selection); void setText(unsigned selection, string text); pComboButton(ComboButton& comboButton) : pWidget(comboButton), comboButton(comboButton) {} void constructor(); void destructor(); }; }
23.896552
92
0.75469
vgmtool
500f49a9992b20b00f94995e709a18be163f1ba7
70,512
cpp
C++
build/linux-build/Sources/src/zpp_nape/constraint/ZPP_PivotJoint.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
build/linux-build/Sources/src/zpp_nape/constraint/ZPP_PivotJoint.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
build/linux-build/Sources/src/zpp_nape/constraint/ZPP_PivotJoint.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
// Generated by Haxe 4.0.0-preview.5 #include <hxcpp.h> #ifndef INCLUDED_95f339a1d026d52c #define INCLUDED_95f339a1d026d52c #include "hxMath.h" #endif #ifndef INCLUDED_nape_Config #include <hxinc/nape/Config.h> #endif #ifndef INCLUDED_nape_constraint_Constraint #include <hxinc/nape/constraint/Constraint.h> #endif #ifndef INCLUDED_nape_constraint_PivotJoint #include <hxinc/nape/constraint/PivotJoint.h> #endif #ifndef INCLUDED_nape_geom_Vec2 #include <hxinc/nape/geom/Vec2.h> #endif #ifndef INCLUDED_nape_geom_Vec3 #include <hxinc/nape/geom/Vec3.h> #endif #ifndef INCLUDED_nape_phys_Body #include <hxinc/nape/phys/Body.h> #endif #ifndef INCLUDED_nape_phys_Interactor #include <hxinc/nape/phys/Interactor.h> #endif #ifndef INCLUDED_nape_util_Debug #include <hxinc/nape/util/Debug.h> #endif #ifndef INCLUDED_zpp_nape_constraint_ZPP_Constraint #include <hxinc/zpp_nape/constraint/ZPP_Constraint.h> #endif #ifndef INCLUDED_zpp_nape_constraint_ZPP_CopyHelper #include <hxinc/zpp_nape/constraint/ZPP_CopyHelper.h> #endif #ifndef INCLUDED_zpp_nape_constraint_ZPP_PivotJoint #include <hxinc/zpp_nape/constraint/ZPP_PivotJoint.h> #endif #ifndef INCLUDED_zpp_nape_geom_ZPP_Vec2 #include <hxinc/zpp_nape/geom/ZPP_Vec2.h> #endif #ifndef INCLUDED_zpp_nape_phys_ZPP_Body #include <hxinc/zpp_nape/phys/ZPP_Body.h> #endif #ifndef INCLUDED_zpp_nape_phys_ZPP_Interactor #include <hxinc/zpp_nape/phys/ZPP_Interactor.h> #endif #ifndef INCLUDED_zpp_nape_space_ZPP_Component #include <hxinc/zpp_nape/space/ZPP_Component.h> #endif #ifndef INCLUDED_zpp_nape_space_ZPP_Space #include <hxinc/zpp_nape/space/ZPP_Space.h> #endif #ifndef INCLUDED_zpp_nape_util_ZNPList_ZPP_Constraint #include <hxinc/zpp_nape/util/ZNPList_ZPP_Constraint.h> #endif #ifndef INCLUDED_zpp_nape_util_ZPP_PubPool #include <hxinc/zpp_nape/util/ZPP_PubPool.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_e49efd2d085e96b5_174_new,"zpp_nape.constraint.ZPP_PivotJoint","new",0x51312e0f,"zpp_nape.constraint.ZPP_PivotJoint.new","zpp_nape/constraint/PivotJoint.hx",174,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_177_bodyImpulse,"zpp_nape.constraint.ZPP_PivotJoint","bodyImpulse",0x3bab9ae2,"zpp_nape.constraint.ZPP_PivotJoint.bodyImpulse","zpp_nape/constraint/PivotJoint.hx",177,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_183_activeBodies,"zpp_nape.constraint.ZPP_PivotJoint","activeBodies",0x66ef5e57,"zpp_nape.constraint.ZPP_PivotJoint.activeBodies","zpp_nape/constraint/PivotJoint.hx",183,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_191_inactiveBodies,"zpp_nape.constraint.ZPP_PivotJoint","inactiveBodies",0x5bb73bfc,"zpp_nape.constraint.ZPP_PivotJoint.inactiveBodies","zpp_nape/constraint/PivotJoint.hx",191,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_205_validate_a1,"zpp_nape.constraint.ZPP_PivotJoint","validate_a1",0xa6d5c0a8,"zpp_nape.constraint.ZPP_PivotJoint.validate_a1","zpp_nape/constraint/PivotJoint.hx",205,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_226_invalidate_a1,"zpp_nape.constraint.ZPP_PivotJoint","invalidate_a1",0x73201ea3,"zpp_nape.constraint.ZPP_PivotJoint.invalidate_a1","zpp_nape/constraint/PivotJoint.hx",226,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_250_setup_a1,"zpp_nape.constraint.ZPP_PivotJoint","setup_a1",0xba3ed063,"zpp_nape.constraint.ZPP_PivotJoint.setup_a1","zpp_nape/constraint/PivotJoint.hx",250,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_263_validate_a2,"zpp_nape.constraint.ZPP_PivotJoint","validate_a2",0xa6d5c0a9,"zpp_nape.constraint.ZPP_PivotJoint.validate_a2","zpp_nape/constraint/PivotJoint.hx",263,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_284_invalidate_a2,"zpp_nape.constraint.ZPP_PivotJoint","invalidate_a2",0x73201ea4,"zpp_nape.constraint.ZPP_PivotJoint.invalidate_a2","zpp_nape/constraint/PivotJoint.hx",284,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_308_setup_a2,"zpp_nape.constraint.ZPP_PivotJoint","setup_a2",0xba3ed064,"zpp_nape.constraint.ZPP_PivotJoint.setup_a2","zpp_nape/constraint/PivotJoint.hx",308,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_325_copy,"zpp_nape.constraint.ZPP_PivotJoint","copy",0xb2995726,"zpp_nape.constraint.ZPP_PivotJoint.copy","zpp_nape/constraint/PivotJoint.hx",325,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_346_copy,"zpp_nape.constraint.ZPP_PivotJoint","copy",0xb2995726,"zpp_nape.constraint.ZPP_PivotJoint.copy","zpp_nape/constraint/PivotJoint.hx",346,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_367_copy,"zpp_nape.constraint.ZPP_PivotJoint","copy",0xb2995726,"zpp_nape.constraint.ZPP_PivotJoint.copy","zpp_nape/constraint/PivotJoint.hx",367,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_481_validate,"zpp_nape.constraint.ZPP_PivotJoint","validate",0x9be97887,"zpp_nape.constraint.ZPP_PivotJoint.validate","zpp_nape/constraint/PivotJoint.hx",481,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_487_wake_connected,"zpp_nape.constraint.ZPP_PivotJoint","wake_connected",0x0ccf825f,"zpp_nape.constraint.ZPP_PivotJoint.wake_connected","zpp_nape/constraint/PivotJoint.hx",487,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_491_forest,"zpp_nape.constraint.ZPP_PivotJoint","forest",0xc14fa68e,"zpp_nape.constraint.ZPP_PivotJoint.forest","zpp_nape/constraint/PivotJoint.hx",491,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_590_pair_exists,"zpp_nape.constraint.ZPP_PivotJoint","pair_exists",0x45618f50,"zpp_nape.constraint.ZPP_PivotJoint.pair_exists","zpp_nape/constraint/PivotJoint.hx",590,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_592_clearcache,"zpp_nape.constraint.ZPP_PivotJoint","clearcache",0x24a5afc6,"zpp_nape.constraint.ZPP_PivotJoint.clearcache","zpp_nape/constraint/PivotJoint.hx",592,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_615_preStep,"zpp_nape.constraint.ZPP_PivotJoint","preStep",0xaf30223e,"zpp_nape.constraint.ZPP_PivotJoint.preStep","zpp_nape/constraint/PivotJoint.hx",615,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_826_warmStart,"zpp_nape.constraint.ZPP_PivotJoint","warmStart",0x78f072cc,"zpp_nape.constraint.ZPP_PivotJoint.warmStart","zpp_nape/constraint/PivotJoint.hx",826,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_858_applyImpulseVel,"zpp_nape.constraint.ZPP_PivotJoint","applyImpulseVel",0x63db6fe5,"zpp_nape.constraint.ZPP_PivotJoint.applyImpulseVel","zpp_nape/constraint/PivotJoint.hx",858,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_1034_applyImpulsePos,"zpp_nape.constraint.ZPP_PivotJoint","applyImpulsePos",0x63d6eb1c,"zpp_nape.constraint.ZPP_PivotJoint.applyImpulsePos","zpp_nape/constraint/PivotJoint.hx",1034,0x4ef23406) HX_LOCAL_STACK_FRAME(_hx_pos_e49efd2d085e96b5_1342_draw,"zpp_nape.constraint.ZPP_PivotJoint","draw",0xb344c775,"zpp_nape.constraint.ZPP_PivotJoint.draw","zpp_nape/constraint/PivotJoint.hx",1342,0x4ef23406) namespace zpp_nape{ namespace constraint{ void ZPP_PivotJoint_obj::__construct(){ HX_STACKFRAME(&_hx_pos_e49efd2d085e96b5_174_new) HXLINE( 324) this->stepped = false; HXLINE( 323) this->biasy = ((Float)0.0); HXLINE( 322) this->biasx = ((Float)0.0); HXLINE( 321) this->gamma = ((Float)0.0); HXLINE( 320) this->jMax = ((Float)0.0); HXLINE( 319) this->jAccy = ((Float)0.0); HXLINE( 318) this->jAccx = ((Float)0.0); HXLINE( 317) this->kMassc = ((Float)0.0); HXLINE( 316) this->kMassb = ((Float)0.0); HXLINE( 315) this->kMassa = ((Float)0.0); HXLINE( 314) this->wrap_a2 = null(); HXLINE( 261) this->a2rely = ((Float)0.0); HXLINE( 260) this->a2relx = ((Float)0.0); HXLINE( 259) this->a2localy = ((Float)0.0); HXLINE( 258) this->a2localx = ((Float)0.0); HXLINE( 257) this->b2 = null(); HXLINE( 256) this->wrap_a1 = null(); HXLINE( 203) this->a1rely = ((Float)0.0); HXLINE( 202) this->a1relx = ((Float)0.0); HXLINE( 201) this->a1localy = ((Float)0.0); HXLINE( 200) this->a1localx = ((Float)0.0); HXLINE( 199) this->b1 = null(); HXLINE( 175) this->outer_zn = null(); HXLINE( 373) super::__construct(); HXLINE( 374) this->stepped = false; HXLINE( 375) { HXLINE( 376) this->jAccx = ( (Float)(0) ); HXLINE( 377) this->jAccy = ( (Float)(0) ); } HXLINE( 395) this->jMax = ::Math_obj::POSITIVE_INFINITY; HXLINE( 396) { HXLINE( 397) { HXLINE( 398) this->a1localx = ( (Float)(0) ); HXLINE( 399) this->a1localy = ( (Float)(0) ); } HXLINE( 417) { HXLINE( 418) this->a1relx = ( (Float)(0) ); HXLINE( 419) this->a1rely = ( (Float)(0) ); } } HXLINE( 438) { HXLINE( 439) { HXLINE( 440) this->a2localx = ( (Float)(0) ); HXLINE( 441) this->a2localy = ( (Float)(0) ); } HXLINE( 459) { HXLINE( 460) this->a2relx = ( (Float)(0) ); HXLINE( 461) this->a2rely = ( (Float)(0) ); } } } Dynamic ZPP_PivotJoint_obj::__CreateEmpty() { return new ZPP_PivotJoint_obj; } void *ZPP_PivotJoint_obj::_hx_vtable = 0; Dynamic ZPP_PivotJoint_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< ZPP_PivotJoint_obj > _hx_result = new ZPP_PivotJoint_obj(); _hx_result->__construct(); return _hx_result; } bool ZPP_PivotJoint_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x731bc4b7) { return inClassId==(int)0x00000001 || inClassId==(int)0x731bc4b7; } else { return inClassId==(int)0x7c84a5ec; } } ::nape::geom::Vec3 ZPP_PivotJoint_obj::bodyImpulse( ::zpp_nape::phys::ZPP_Body b){ HX_STACKFRAME(&_hx_pos_e49efd2d085e96b5_177_bodyImpulse) HXDLIN( 177) if (this->stepped) { HXLINE( 178) if (hx::IsEq( b,this->b1 )) { HXLINE( 178) return ::nape::geom::Vec3_obj::get(-(this->jAccx),-(this->jAccy),-(((this->jAccy * this->a1relx) - (this->jAccx * this->a1rely)))); } else { HXLINE( 179) return ::nape::geom::Vec3_obj::get(this->jAccx,this->jAccy,((this->jAccy * this->a2relx) - (this->jAccx * this->a2rely))); } } else { HXLINE( 181) return ::nape::geom::Vec3_obj::get(0,0,0); } HXLINE( 177) return null(); } HX_DEFINE_DYNAMIC_FUNC1(ZPP_PivotJoint_obj,bodyImpulse,return ) void ZPP_PivotJoint_obj::activeBodies(){ HX_STACKFRAME(&_hx_pos_e49efd2d085e96b5_183_activeBodies) HXLINE( 185) if (hx::IsNotNull( this->b1 )) { HXLINE( 185) this->b1->constraints->add(hx::ObjectPtr<OBJ_>(this)); } HXLINE( 187) if (hx::IsNotEq( this->b2,this->b1 )) { HXLINE( 188) if (hx::IsNotNull( this->b2 )) { HXLINE( 188) this->b2->constraints->add(hx::ObjectPtr<OBJ_>(this)); } } } void ZPP_PivotJoint_obj::inactiveBodies(){ HX_STACKFRAME(&_hx_pos_e49efd2d085e96b5_191_inactiveBodies) HXLINE( 193) if (hx::IsNotNull( this->b1 )) { HXLINE( 193) this->b1->constraints->remove(hx::ObjectPtr<OBJ_>(this)); } HXLINE( 195) if (hx::IsNotEq( this->b2,this->b1 )) { HXLINE( 196) if (hx::IsNotNull( this->b2 )) { HXLINE( 196) this->b2->constraints->remove(hx::ObjectPtr<OBJ_>(this)); } } } void ZPP_PivotJoint_obj::validate_a1(){ HX_STACKFRAME(&_hx_pos_e49efd2d085e96b5_205_validate_a1) HXLINE( 206) this->wrap_a1->zpp_inner->x = this->a1localx; HXLINE( 207) this->wrap_a1->zpp_inner->y = this->a1localy; } HX_DEFINE_DYNAMIC_FUNC0(ZPP_PivotJoint_obj,validate_a1,(void)) void ZPP_PivotJoint_obj::invalidate_a1( ::zpp_nape::geom::ZPP_Vec2 x){ HX_STACKFRAME(&_hx_pos_e49efd2d085e96b5_226_invalidate_a1) HXLINE( 227) this->immutable_midstep((HX_("Constraint::",7d,10,25,6e) + HX_("a1",b0,54,00,00))); HXLINE( 228) { HXLINE( 229) this->a1localx = x->x; HXLINE( 230) this->a1localy = x->y; } HXLINE( 248) this->wake(); } HX_DEFINE_DYNAMIC_FUNC1(ZPP_PivotJoint_obj,invalidate_a1,(void)) void ZPP_PivotJoint_obj::setup_a1(){ HX_GC_STACKFRAME(&_hx_pos_e49efd2d085e96b5_250_setup_a1) HXLINE( 251) Float x = this->a1localx; HXDLIN( 251) Float y = this->a1localy; HXDLIN( 251) bool _hx_tmp; HXDLIN( 251) if ((x == x)) { HXLINE( 251) _hx_tmp = (y != y); } else { HXLINE( 251) _hx_tmp = true; } HXDLIN( 251) if (_hx_tmp) { HXLINE( 251) HX_STACK_DO_THROW(HX_("Error: Vec2 components cannot be NaN",85,ba,d8,c1)); } HXDLIN( 251) ::nape::geom::Vec2 ret; HXDLIN( 251) if (hx::IsNull( ::zpp_nape::util::ZPP_PubPool_obj::poolVec2 )) { HXLINE( 251) ret = ::nape::geom::Vec2_obj::__alloc( HX_CTX ,null(),null()); } else { HXLINE( 251) ret = ::zpp_nape::util::ZPP_PubPool_obj::poolVec2; HXDLIN( 251) ::zpp_nape::util::ZPP_PubPool_obj::poolVec2 = ret->zpp_pool; HXDLIN( 251) ret->zpp_pool = null(); HXDLIN( 251) ret->zpp_disp = false; HXDLIN( 251) if (hx::IsEq( ret,::zpp_nape::util::ZPP_PubPool_obj::nextVec2 )) { HXLINE( 251) ::zpp_nape::util::ZPP_PubPool_obj::nextVec2 = null(); } } HXDLIN( 251) if (hx::IsNull( ret->zpp_inner )) { HXLINE( 251) ::zpp_nape::geom::ZPP_Vec2 ret1; HXDLIN( 251) { HXLINE( 251) if (hx::IsNull( ::zpp_nape::geom::ZPP_Vec2_obj::zpp_pool )) { HXLINE( 251) ret1 = ::zpp_nape::geom::ZPP_Vec2_obj::__alloc( HX_CTX ); } else { HXLINE( 251) ret1 = ::zpp_nape::geom::ZPP_Vec2_obj::zpp_pool; HXDLIN( 251) ::zpp_nape::geom::ZPP_Vec2_obj::zpp_pool = ret1->next; HXDLIN( 251) ret1->next = null(); } HXDLIN( 251) ret1->weak = false; } HXDLIN( 251) ret1->_immutable = false; HXDLIN( 251) { HXLINE( 251) ret1->x = x; HXDLIN( 251) ret1->y = y; } HXDLIN( 251) ret->zpp_inner = ret1; HXDLIN( 251) ret->zpp_inner->outer = ret; } else { HXLINE( 251) bool _hx_tmp1; HXDLIN( 251) if (hx::IsNotNull( ret )) { HXLINE( 251) _hx_tmp1 = ret->zpp_disp; } else { HXLINE( 251) _hx_tmp1 = false; } HXDLIN( 251) if (_hx_tmp1) { HXLINE( 251) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74))); } HXDLIN( 251) { HXLINE( 251) ::zpp_nape::geom::ZPP_Vec2 _this = ret->zpp_inner; HXDLIN( 251) if (_this->_immutable) { HXLINE( 251) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc)); } HXDLIN( 251) if (hx::IsNotNull( _this->_isimmutable )) { HXLINE( 251) _this->_isimmutable(); } } HXDLIN( 251) bool _hx_tmp2; HXDLIN( 251) if ((x == x)) { HXLINE( 251) _hx_tmp2 = (y != y); } else { HXLINE( 251) _hx_tmp2 = true; } HXDLIN( 251) if (_hx_tmp2) { HXLINE( 251) HX_STACK_DO_THROW(HX_("Error: Vec2 components cannot be NaN",85,ba,d8,c1)); } HXDLIN( 251) bool _hx_tmp3; HXDLIN( 251) bool _hx_tmp4; HXDLIN( 251) if (hx::IsNotNull( ret )) { HXLINE( 251) _hx_tmp4 = ret->zpp_disp; } else { HXLINE( 251) _hx_tmp4 = false; } HXDLIN( 251) if (_hx_tmp4) { HXLINE( 251) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74))); } HXDLIN( 251) { HXLINE( 251) ::zpp_nape::geom::ZPP_Vec2 _this1 = ret->zpp_inner; HXDLIN( 251) if (hx::IsNotNull( _this1->_validate )) { HXLINE( 251) _this1->_validate(); } } HXDLIN( 251) if ((ret->zpp_inner->x == x)) { HXLINE( 251) bool _hx_tmp5; HXDLIN( 251) if (hx::IsNotNull( ret )) { HXLINE( 251) _hx_tmp5 = ret->zpp_disp; } else { HXLINE( 251) _hx_tmp5 = false; } HXDLIN( 251) if (_hx_tmp5) { HXLINE( 251) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74))); } HXDLIN( 251) { HXLINE( 251) ::zpp_nape::geom::ZPP_Vec2 _this2 = ret->zpp_inner; HXDLIN( 251) if (hx::IsNotNull( _this2->_validate )) { HXLINE( 251) _this2->_validate(); } } HXDLIN( 251) _hx_tmp3 = (ret->zpp_inner->y == y); } else { HXLINE( 251) _hx_tmp3 = false; } HXDLIN( 251) if (!(_hx_tmp3)) { HXLINE( 251) { HXLINE( 251) ret->zpp_inner->x = x; HXDLIN( 251) ret->zpp_inner->y = y; } HXDLIN( 251) { HXLINE( 251) ::zpp_nape::geom::ZPP_Vec2 _this3 = ret->zpp_inner; HXDLIN( 251) if (hx::IsNotNull( _this3->_invalidate )) { HXLINE( 251) _this3->_invalidate(_this3); } } } } HXDLIN( 251) ret->zpp_inner->weak = false; HXDLIN( 251) this->wrap_a1 = ret; HXLINE( 252) this->wrap_a1->zpp_inner->_inuse = true; HXLINE( 253) this->wrap_a1->zpp_inner->_validate = this->validate_a1_dyn(); HXLINE( 254) this->wrap_a1->zpp_inner->_invalidate = this->invalidate_a1_dyn(); } HX_DEFINE_DYNAMIC_FUNC0(ZPP_PivotJoint_obj,setup_a1,(void)) void ZPP_PivotJoint_obj::validate_a2(){ HX_STACKFRAME(&_hx_pos_e49efd2d085e96b5_263_validate_a2) HXLINE( 264) this->wrap_a2->zpp_inner->x = this->a2localx; HXLINE( 265) this->wrap_a2->zpp_inner->y = this->a2localy; } HX_DEFINE_DYNAMIC_FUNC0(ZPP_PivotJoint_obj,validate_a2,(void)) void ZPP_PivotJoint_obj::invalidate_a2( ::zpp_nape::geom::ZPP_Vec2 x){ HX_STACKFRAME(&_hx_pos_e49efd2d085e96b5_284_invalidate_a2) HXLINE( 285) this->immutable_midstep((HX_("Constraint::",7d,10,25,6e) + HX_("a2",b1,54,00,00))); HXLINE( 286) { HXLINE( 287) this->a2localx = x->x; HXLINE( 288) this->a2localy = x->y; } HXLINE( 306) this->wake(); } HX_DEFINE_DYNAMIC_FUNC1(ZPP_PivotJoint_obj,invalidate_a2,(void)) void ZPP_PivotJoint_obj::setup_a2(){ HX_GC_STACKFRAME(&_hx_pos_e49efd2d085e96b5_308_setup_a2) HXLINE( 309) Float x = this->a2localx; HXDLIN( 309) Float y = this->a2localy; HXDLIN( 309) bool _hx_tmp; HXDLIN( 309) if ((x == x)) { HXLINE( 309) _hx_tmp = (y != y); } else { HXLINE( 309) _hx_tmp = true; } HXDLIN( 309) if (_hx_tmp) { HXLINE( 309) HX_STACK_DO_THROW(HX_("Error: Vec2 components cannot be NaN",85,ba,d8,c1)); } HXDLIN( 309) ::nape::geom::Vec2 ret; HXDLIN( 309) if (hx::IsNull( ::zpp_nape::util::ZPP_PubPool_obj::poolVec2 )) { HXLINE( 309) ret = ::nape::geom::Vec2_obj::__alloc( HX_CTX ,null(),null()); } else { HXLINE( 309) ret = ::zpp_nape::util::ZPP_PubPool_obj::poolVec2; HXDLIN( 309) ::zpp_nape::util::ZPP_PubPool_obj::poolVec2 = ret->zpp_pool; HXDLIN( 309) ret->zpp_pool = null(); HXDLIN( 309) ret->zpp_disp = false; HXDLIN( 309) if (hx::IsEq( ret,::zpp_nape::util::ZPP_PubPool_obj::nextVec2 )) { HXLINE( 309) ::zpp_nape::util::ZPP_PubPool_obj::nextVec2 = null(); } } HXDLIN( 309) if (hx::IsNull( ret->zpp_inner )) { HXLINE( 309) ::zpp_nape::geom::ZPP_Vec2 ret1; HXDLIN( 309) { HXLINE( 309) if (hx::IsNull( ::zpp_nape::geom::ZPP_Vec2_obj::zpp_pool )) { HXLINE( 309) ret1 = ::zpp_nape::geom::ZPP_Vec2_obj::__alloc( HX_CTX ); } else { HXLINE( 309) ret1 = ::zpp_nape::geom::ZPP_Vec2_obj::zpp_pool; HXDLIN( 309) ::zpp_nape::geom::ZPP_Vec2_obj::zpp_pool = ret1->next; HXDLIN( 309) ret1->next = null(); } HXDLIN( 309) ret1->weak = false; } HXDLIN( 309) ret1->_immutable = false; HXDLIN( 309) { HXLINE( 309) ret1->x = x; HXDLIN( 309) ret1->y = y; } HXDLIN( 309) ret->zpp_inner = ret1; HXDLIN( 309) ret->zpp_inner->outer = ret; } else { HXLINE( 309) bool _hx_tmp1; HXDLIN( 309) if (hx::IsNotNull( ret )) { HXLINE( 309) _hx_tmp1 = ret->zpp_disp; } else { HXLINE( 309) _hx_tmp1 = false; } HXDLIN( 309) if (_hx_tmp1) { HXLINE( 309) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74))); } HXDLIN( 309) { HXLINE( 309) ::zpp_nape::geom::ZPP_Vec2 _this = ret->zpp_inner; HXDLIN( 309) if (_this->_immutable) { HXLINE( 309) HX_STACK_DO_THROW(HX_("Error: Vec2 is immutable",60,ee,1f,bc)); } HXDLIN( 309) if (hx::IsNotNull( _this->_isimmutable )) { HXLINE( 309) _this->_isimmutable(); } } HXDLIN( 309) bool _hx_tmp2; HXDLIN( 309) if ((x == x)) { HXLINE( 309) _hx_tmp2 = (y != y); } else { HXLINE( 309) _hx_tmp2 = true; } HXDLIN( 309) if (_hx_tmp2) { HXLINE( 309) HX_STACK_DO_THROW(HX_("Error: Vec2 components cannot be NaN",85,ba,d8,c1)); } HXDLIN( 309) bool _hx_tmp3; HXDLIN( 309) bool _hx_tmp4; HXDLIN( 309) if (hx::IsNotNull( ret )) { HXLINE( 309) _hx_tmp4 = ret->zpp_disp; } else { HXLINE( 309) _hx_tmp4 = false; } HXDLIN( 309) if (_hx_tmp4) { HXLINE( 309) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74))); } HXDLIN( 309) { HXLINE( 309) ::zpp_nape::geom::ZPP_Vec2 _this1 = ret->zpp_inner; HXDLIN( 309) if (hx::IsNotNull( _this1->_validate )) { HXLINE( 309) _this1->_validate(); } } HXDLIN( 309) if ((ret->zpp_inner->x == x)) { HXLINE( 309) bool _hx_tmp5; HXDLIN( 309) if (hx::IsNotNull( ret )) { HXLINE( 309) _hx_tmp5 = ret->zpp_disp; } else { HXLINE( 309) _hx_tmp5 = false; } HXDLIN( 309) if (_hx_tmp5) { HXLINE( 309) HX_STACK_DO_THROW(((HX_("Error: ",4e,a8,5b,b7) + HX_("Vec2",7e,53,25,39)) + HX_(" has been disposed and cannot be used!",2e,07,ae,74))); } HXDLIN( 309) { HXLINE( 309) ::zpp_nape::geom::ZPP_Vec2 _this2 = ret->zpp_inner; HXDLIN( 309) if (hx::IsNotNull( _this2->_validate )) { HXLINE( 309) _this2->_validate(); } } HXDLIN( 309) _hx_tmp3 = (ret->zpp_inner->y == y); } else { HXLINE( 309) _hx_tmp3 = false; } HXDLIN( 309) if (!(_hx_tmp3)) { HXLINE( 309) { HXLINE( 309) ret->zpp_inner->x = x; HXDLIN( 309) ret->zpp_inner->y = y; } HXDLIN( 309) { HXLINE( 309) ::zpp_nape::geom::ZPP_Vec2 _this3 = ret->zpp_inner; HXDLIN( 309) if (hx::IsNotNull( _this3->_invalidate )) { HXLINE( 309) _this3->_invalidate(_this3); } } } } HXDLIN( 309) ret->zpp_inner->weak = false; HXDLIN( 309) this->wrap_a2 = ret; HXLINE( 310) this->wrap_a2->zpp_inner->_inuse = true; HXLINE( 311) this->wrap_a2->zpp_inner->_validate = this->validate_a2_dyn(); HXLINE( 312) this->wrap_a2->zpp_inner->_invalidate = this->invalidate_a2_dyn(); } HX_DEFINE_DYNAMIC_FUNC0(ZPP_PivotJoint_obj,setup_a2,(void)) ::nape::constraint::Constraint ZPP_PivotJoint_obj::copy(::Array< ::Dynamic> dict,::Array< ::Dynamic> todo){ HX_GC_STACKFRAME(&_hx_pos_e49efd2d085e96b5_325_copy) HXLINE( 326) ::nape::constraint::PivotJoint _this = this->outer_zn; HXDLIN( 326) if (hx::IsNull( _this->zpp_inner_zn->wrap_a1 )) { HXLINE( 326) _this->zpp_inner_zn->setup_a1(); } HXDLIN( 326) ::nape::geom::Vec2 ret = _this->zpp_inner_zn->wrap_a1; HXDLIN( 326) ::nape::constraint::PivotJoint _this1 = this->outer_zn; HXDLIN( 326) if (hx::IsNull( _this1->zpp_inner_zn->wrap_a2 )) { HXLINE( 326) _this1->zpp_inner_zn->setup_a2(); } HXDLIN( 326) ::nape::constraint::PivotJoint ret1 = ::nape::constraint::PivotJoint_obj::__alloc( HX_CTX ,null(),null(),ret,_this1->zpp_inner_zn->wrap_a2); HXLINE( 327) this->copyto(ret1); HXLINE( 329) bool _hx_tmp; HXDLIN( 329) if (hx::IsNotNull( dict )) { HXLINE( 329) _hx_tmp = hx::IsNotNull( this->b1 ); } else { HXLINE( 329) _hx_tmp = false; } HXDLIN( 329) if (_hx_tmp) { HXLINE( 338) ::nape::phys::Body b = null(); HXLINE( 339) { HXLINE( 339) int _g = 0; HXDLIN( 339) while((_g < dict->length)){ HXLINE( 339) ::zpp_nape::constraint::ZPP_CopyHelper idc = dict->__get(_g).StaticCast< ::zpp_nape::constraint::ZPP_CopyHelper >(); HXDLIN( 339) _g = (_g + 1); HXLINE( 340) if ((idc->id == this->b1->id)) { HXLINE( 341) b = idc->bc; HXLINE( 342) goto _hx_goto_10; } } _hx_goto_10:; } HXLINE( 345) if (hx::IsNotNull( b )) { HXLINE( 345) ret1->zpp_inner_zn->b1 = b->zpp_inner; } else { HX_BEGIN_LOCAL_FUNC_S1(hx::LocalFunc,_hx_Closure_0, ::nape::constraint::PivotJoint,ret1) HXARGC(1) void _hx_run( ::nape::phys::Body b1){ HX_GC_STACKFRAME(&_hx_pos_e49efd2d085e96b5_346_copy) HXLINE( 346) ret1->zpp_inner_zn->b1 = b1->zpp_inner; } HX_END_LOCAL_FUNC1((void)) HXLINE( 346) todo->push(::zpp_nape::constraint::ZPP_CopyHelper_obj::todo(this->b1->id, ::Dynamic(new _hx_Closure_0(ret1)))); } } HXLINE( 350) bool _hx_tmp1; HXDLIN( 350) if (hx::IsNotNull( dict )) { HXLINE( 350) _hx_tmp1 = hx::IsNotNull( this->b2 ); } else { HXLINE( 350) _hx_tmp1 = false; } HXDLIN( 350) if (_hx_tmp1) { HXLINE( 359) ::nape::phys::Body b2 = null(); HXLINE( 360) { HXLINE( 360) int _g1 = 0; HXDLIN( 360) while((_g1 < dict->length)){ HXLINE( 360) ::zpp_nape::constraint::ZPP_CopyHelper idc1 = dict->__get(_g1).StaticCast< ::zpp_nape::constraint::ZPP_CopyHelper >(); HXDLIN( 360) _g1 = (_g1 + 1); HXLINE( 361) if ((idc1->id == this->b2->id)) { HXLINE( 362) b2 = idc1->bc; HXLINE( 363) goto _hx_goto_11; } } _hx_goto_11:; } HXLINE( 366) if (hx::IsNotNull( b2 )) { HXLINE( 366) ret1->zpp_inner_zn->b2 = b2->zpp_inner; } else { HX_BEGIN_LOCAL_FUNC_S1(hx::LocalFunc,_hx_Closure_1, ::nape::constraint::PivotJoint,ret1) HXARGC(1) void _hx_run( ::nape::phys::Body b3){ HX_GC_STACKFRAME(&_hx_pos_e49efd2d085e96b5_367_copy) HXLINE( 367) ret1->zpp_inner_zn->b2 = b3->zpp_inner; } HX_END_LOCAL_FUNC1((void)) HXLINE( 367) todo->push(::zpp_nape::constraint::ZPP_CopyHelper_obj::todo(this->b2->id, ::Dynamic(new _hx_Closure_1(ret1)))); } } HXLINE( 370) return ret1; } void ZPP_PivotJoint_obj::validate(){ HX_STACKFRAME(&_hx_pos_e49efd2d085e96b5_481_validate) HXLINE( 482) bool _hx_tmp; HXDLIN( 482) if (hx::IsNotNull( this->b1 )) { HXLINE( 482) _hx_tmp = hx::IsNull( this->b2 ); } else { HXLINE( 482) _hx_tmp = true; } HXDLIN( 482) if (_hx_tmp) { HXLINE( 482) HX_STACK_DO_THROW(HX_("Error: PivotJoint cannot be simulated null bodies",af,f3,ba,a1)); } HXLINE( 483) if (hx::IsEq( this->b1,this->b2 )) { HXLINE( 483) HX_STACK_DO_THROW(((HX_("Error: PivotJoint cannot be simulated with body1 == body2 (body1=body2=",54,9d,c6,0e) + this->b1->outer->toString()) + HX_(")",29,00,00,00))); } HXLINE( 484) bool _hx_tmp1; HXDLIN( 484) if (hx::IsEq( this->b1->space,this->space )) { HXLINE( 484) _hx_tmp1 = hx::IsNotEq( this->b2->space,this->space ); } else { HXLINE( 484) _hx_tmp1 = true; } HXDLIN( 484) if (_hx_tmp1) { HXLINE( 484) ::String _hx_tmp2 = ((HX_("Error: Constraints must have each body within the same space to which the constraint has been assigned (body1=",fe,98,58,d3) + this->b1->outer->toString()) + HX_(", body2=",61,88,43,62)); HXDLIN( 484) HX_STACK_DO_THROW(((_hx_tmp2 + this->b2->outer->toString()) + HX_(")",29,00,00,00))); } HXLINE( 485) bool _hx_tmp3; HXDLIN( 485) if ((this->b1->type != 2)) { HXLINE( 485) _hx_tmp3 = (this->b2->type != 2); } else { HXLINE( 485) _hx_tmp3 = false; } HXDLIN( 485) if (_hx_tmp3) { HXLINE( 485) ::String _hx_tmp4 = ((HX_("Error: Constraints cannot have both bodies non-dynamic (body1=",e1,da,d7,49) + this->b1->outer->toString()) + HX_(", body2=",61,88,43,62)); HXDLIN( 485) HX_STACK_DO_THROW(((_hx_tmp4 + this->b2->outer->toString()) + HX_(")",29,00,00,00))); } } void ZPP_PivotJoint_obj::wake_connected(){ HX_STACKFRAME(&_hx_pos_e49efd2d085e96b5_487_wake_connected) HXLINE( 488) bool _hx_tmp; HXDLIN( 488) if (hx::IsNotNull( this->b1 )) { HXLINE( 488) _hx_tmp = (this->b1->type == 2); } else { HXLINE( 488) _hx_tmp = false; } HXDLIN( 488) if (_hx_tmp) { HXLINE( 488) this->b1->wake(); } HXLINE( 489) bool _hx_tmp1; HXDLIN( 489) if (hx::IsNotNull( this->b2 )) { HXLINE( 489) _hx_tmp1 = (this->b2->type == 2); } else { HXLINE( 489) _hx_tmp1 = false; } HXDLIN( 489) if (_hx_tmp1) { HXLINE( 489) this->b2->wake(); } } void ZPP_PivotJoint_obj::forest(){ HX_STACKFRAME(&_hx_pos_e49efd2d085e96b5_491_forest) HXLINE( 492) if ((this->b1->type == 2)) { HXLINE( 493) ::zpp_nape::space::ZPP_Component xr; HXDLIN( 493) if (hx::IsEq( this->b1->component,this->b1->component->parent )) { HXLINE( 493) xr = this->b1->component; } else { HXLINE( 496) ::zpp_nape::space::ZPP_Component obj = this->b1->component; HXLINE( 497) ::zpp_nape::space::ZPP_Component stack = null(); HXLINE( 498) while(hx::IsNotEq( obj,obj->parent )){ HXLINE( 499) ::zpp_nape::space::ZPP_Component nxt = obj->parent; HXLINE( 500) obj->parent = stack; HXLINE( 501) stack = obj; HXLINE( 502) obj = nxt; } HXLINE( 504) while(hx::IsNotNull( stack )){ HXLINE( 505) ::zpp_nape::space::ZPP_Component nxt1 = stack->parent; HXLINE( 506) stack->parent = obj; HXLINE( 507) stack = nxt1; } HXLINE( 493) xr = obj; } HXLINE( 512) ::zpp_nape::space::ZPP_Component yr; HXDLIN( 512) if (hx::IsEq( this->component,this->component->parent )) { HXLINE( 512) yr = this->component; } else { HXLINE( 515) ::zpp_nape::space::ZPP_Component obj1 = this->component; HXLINE( 516) ::zpp_nape::space::ZPP_Component stack1 = null(); HXLINE( 517) while(hx::IsNotEq( obj1,obj1->parent )){ HXLINE( 518) ::zpp_nape::space::ZPP_Component nxt2 = obj1->parent; HXLINE( 519) obj1->parent = stack1; HXLINE( 520) stack1 = obj1; HXLINE( 521) obj1 = nxt2; } HXLINE( 523) while(hx::IsNotNull( stack1 )){ HXLINE( 524) ::zpp_nape::space::ZPP_Component nxt3 = stack1->parent; HXLINE( 525) stack1->parent = obj1; HXLINE( 526) stack1 = nxt3; } HXLINE( 512) yr = obj1; } HXLINE( 531) if (hx::IsNotEq( xr,yr )) { HXLINE( 532) if ((xr->rank < yr->rank)) { HXLINE( 532) xr->parent = yr; } else { HXLINE( 533) if ((xr->rank > yr->rank)) { HXLINE( 533) yr->parent = xr; } else { HXLINE( 535) yr->parent = xr; HXLINE( 536) xr->rank++; } } } } HXLINE( 540) if ((this->b2->type == 2)) { HXLINE( 541) ::zpp_nape::space::ZPP_Component xr1; HXDLIN( 541) if (hx::IsEq( this->b2->component,this->b2->component->parent )) { HXLINE( 541) xr1 = this->b2->component; } else { HXLINE( 544) ::zpp_nape::space::ZPP_Component obj2 = this->b2->component; HXLINE( 545) ::zpp_nape::space::ZPP_Component stack2 = null(); HXLINE( 546) while(hx::IsNotEq( obj2,obj2->parent )){ HXLINE( 547) ::zpp_nape::space::ZPP_Component nxt4 = obj2->parent; HXLINE( 548) obj2->parent = stack2; HXLINE( 549) stack2 = obj2; HXLINE( 550) obj2 = nxt4; } HXLINE( 552) while(hx::IsNotNull( stack2 )){ HXLINE( 553) ::zpp_nape::space::ZPP_Component nxt5 = stack2->parent; HXLINE( 554) stack2->parent = obj2; HXLINE( 555) stack2 = nxt5; } HXLINE( 541) xr1 = obj2; } HXLINE( 560) ::zpp_nape::space::ZPP_Component yr1; HXDLIN( 560) if (hx::IsEq( this->component,this->component->parent )) { HXLINE( 560) yr1 = this->component; } else { HXLINE( 563) ::zpp_nape::space::ZPP_Component obj3 = this->component; HXLINE( 564) ::zpp_nape::space::ZPP_Component stack3 = null(); HXLINE( 565) while(hx::IsNotEq( obj3,obj3->parent )){ HXLINE( 566) ::zpp_nape::space::ZPP_Component nxt6 = obj3->parent; HXLINE( 567) obj3->parent = stack3; HXLINE( 568) stack3 = obj3; HXLINE( 569) obj3 = nxt6; } HXLINE( 571) while(hx::IsNotNull( stack3 )){ HXLINE( 572) ::zpp_nape::space::ZPP_Component nxt7 = stack3->parent; HXLINE( 573) stack3->parent = obj3; HXLINE( 574) stack3 = nxt7; } HXLINE( 560) yr1 = obj3; } HXLINE( 579) if (hx::IsNotEq( xr1,yr1 )) { HXLINE( 580) if ((xr1->rank < yr1->rank)) { HXLINE( 580) xr1->parent = yr1; } else { HXLINE( 581) if ((xr1->rank > yr1->rank)) { HXLINE( 581) yr1->parent = xr1; } else { HXLINE( 583) yr1->parent = xr1; HXLINE( 584) xr1->rank++; } } } } } bool ZPP_PivotJoint_obj::pair_exists(int id,int di){ HX_STACKFRAME(&_hx_pos_e49efd2d085e96b5_590_pair_exists) HXDLIN( 590) bool _hx_tmp; HXDLIN( 590) if ((this->b1->id == id)) { HXDLIN( 590) _hx_tmp = (this->b2->id == di); } else { HXDLIN( 590) _hx_tmp = false; } HXDLIN( 590) if (!(_hx_tmp)) { HXDLIN( 590) if ((this->b1->id == di)) { HXDLIN( 590) return (this->b2->id == id); } else { HXDLIN( 590) return false; } } else { HXDLIN( 590) return true; } HXDLIN( 590) return false; } void ZPP_PivotJoint_obj::clearcache(){ HX_STACKFRAME(&_hx_pos_e49efd2d085e96b5_592_clearcache) HXLINE( 593) { HXLINE( 594) this->jAccx = ( (Float)(0) ); HXLINE( 595) this->jAccy = ( (Float)(0) ); } HXLINE( 613) this->pre_dt = ((Float)-1.0); } bool ZPP_PivotJoint_obj::preStep(Float dt){ HX_STACKFRAME(&_hx_pos_e49efd2d085e96b5_615_preStep) HXLINE( 616) if ((this->pre_dt == ((Float)-1.0))) { HXLINE( 616) this->pre_dt = dt; } HXLINE( 617) Float dtratio = (dt / this->pre_dt); HXLINE( 618) this->pre_dt = dt; HXLINE( 619) this->stepped = true; HXLINE( 620) { HXLINE( 621) this->a1relx = ((this->b1->axisy * this->a1localx) - (this->b1->axisx * this->a1localy)); HXLINE( 622) this->a1rely = ((this->a1localx * this->b1->axisx) + (this->a1localy * this->b1->axisy)); } HXLINE( 624) { HXLINE( 625) this->a2relx = ((this->b2->axisy * this->a2localx) - (this->b2->axisx * this->a2localy)); HXLINE( 626) this->a2rely = ((this->a2localx * this->b2->axisx) + (this->a2localy * this->b2->axisy)); } HXLINE( 628) { HXLINE( 629) Float m = (this->b1->smass + this->b2->smass); HXLINE( 630) { HXLINE( 631) this->kMassa = m; HXLINE( 632) this->kMassb = ( (Float)(0) ); HXLINE( 633) this->kMassc = m; } HXLINE( 635) if ((this->b1->sinertia != 0)) { HXLINE( 636) Float X = (this->a1relx * this->b1->sinertia); HXLINE( 637) Float Y = (this->a1rely * this->b1->sinertia); HXLINE( 638) { HXLINE( 639) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp = hx::ObjectPtr<OBJ_>(this); HXDLIN( 639) _hx_tmp->kMassa = (_hx_tmp->kMassa + (Y * this->a1rely)); HXLINE( 640) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp1 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 640) _hx_tmp1->kMassb = (_hx_tmp1->kMassb + (-(Y) * this->a1relx)); HXLINE( 641) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp2 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 641) _hx_tmp2->kMassc = (_hx_tmp2->kMassc + (X * this->a1relx)); } } HXLINE( 644) if ((this->b2->sinertia != 0)) { HXLINE( 645) Float X1 = (this->a2relx * this->b2->sinertia); HXLINE( 646) Float Y1 = (this->a2rely * this->b2->sinertia); HXLINE( 647) { HXLINE( 648) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp3 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 648) _hx_tmp3->kMassa = (_hx_tmp3->kMassa + (Y1 * this->a2rely)); HXLINE( 649) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp4 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 649) _hx_tmp4->kMassb = (_hx_tmp4->kMassb + (-(Y1) * this->a2relx)); HXLINE( 650) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp5 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 650) _hx_tmp5->kMassc = (_hx_tmp5->kMassc + (X1 * this->a2relx)); } } } HXLINE( 655) Float det = ((this->kMassa * this->kMassc) - (this->kMassb * this->kMassb)); HXLINE( 654) int flag; HXLINE( 656) if ((det != det)) { HXLINE( 657) this->kMassa = (this->kMassb = (this->kMassc = ( (Float)(0) ))); HXLINE( 654) flag = 3; } else { HXLINE( 660) if ((det == 0)) { HXLINE( 661) int flag1 = 0; HXLINE( 662) if ((this->kMassa != 0)) { HXLINE( 662) this->kMassa = (( (Float)(1) ) / this->kMassa); } else { HXLINE( 664) this->kMassa = ( (Float)(0) ); HXLINE( 665) flag1 = (flag1 | 1); } HXLINE( 667) if ((this->kMassc != 0)) { HXLINE( 667) this->kMassc = (( (Float)(1) ) / this->kMassc); } else { HXLINE( 669) this->kMassc = ( (Float)(0) ); HXLINE( 670) flag1 = (flag1 | 2); } HXLINE( 672) this->kMassb = ( (Float)(0) ); HXLINE( 654) flag = flag1; } else { HXLINE( 676) det = (( (Float)(1) ) / det); HXLINE( 677) Float t = (this->kMassc * det); HXLINE( 678) this->kMassc = (this->kMassa * det); HXLINE( 679) this->kMassa = t; HXLINE( 680) ::zpp_nape::constraint::ZPP_PivotJoint flag2 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 680) flag2->kMassb = (flag2->kMassb * -(det)); HXLINE( 654) flag = 0; } } HXLINE( 684) if (((flag & 1) != 0)) { HXLINE( 684) this->jAccx = ( (Float)(0) ); } HXLINE( 685) if (((flag & 2) != 0)) { HXLINE( 685) this->jAccy = ( (Float)(0) ); } HXLINE( 686) if (!(this->stiff)) { HXLINE( 687) Float biasCoef; HXLINE( 688) { HXLINE( 690) Float omega = ((( (Float)(2) ) * ::Math_obj::PI) * this->frequency); HXLINE( 691) this->gamma = (( (Float)(1) ) / ((dt * omega) * ((( (Float)(2) ) * this->damping) + (omega * dt)))); HXLINE( 692) Float ig = (( (Float)(1) ) / (1 + this->gamma)); HXLINE( 693) biasCoef = (((dt * omega) * omega) * this->gamma); HXLINE( 694) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp6 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 694) _hx_tmp6->gamma = (_hx_tmp6->gamma * ig); HXLINE( 689) Float X2 = ig; HXLINE( 697) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp7 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 697) _hx_tmp7->kMassa = (_hx_tmp7->kMassa * X2); HXLINE( 698) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp8 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 698) _hx_tmp8->kMassb = (_hx_tmp8->kMassb * X2); HXLINE( 699) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp9 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 699) _hx_tmp9->kMassc = (_hx_tmp9->kMassc * X2); } HXLINE( 701) { HXLINE( 702) this->biasx = ((this->b2->posx + this->a2relx) - (this->b1->posx + this->a1relx)); HXLINE( 703) this->biasy = ((this->b2->posy + this->a2rely) - (this->b1->posy + this->a1rely)); } HXLINE( 705) bool _hx_tmp10; HXDLIN( 705) if (this->breakUnderError) { HXLINE( 705) _hx_tmp10 = (((this->biasx * this->biasx) + (this->biasy * this->biasy)) > (this->maxError * this->maxError)); } else { HXLINE( 705) _hx_tmp10 = false; } HXDLIN( 705) if (_hx_tmp10) { HXLINE( 705) return true; } HXLINE( 706) { HXLINE( 707) Float t1 = -(biasCoef); HXLINE( 716) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp11 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 716) _hx_tmp11->biasx = (_hx_tmp11->biasx * t1); HXLINE( 717) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp12 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 717) _hx_tmp12->biasy = (_hx_tmp12->biasy * t1); } HXLINE( 719) { HXLINE( 720) Float t2 = this->maxError; HXLINE( 729) Float ls = ((this->biasx * this->biasx) + (this->biasy * this->biasy)); HXLINE( 730) if ((ls > (t2 * t2))) { HXLINE( 740) Float t3 = (t2 * (((Float)1.0) / ::Math_obj::sqrt(ls))); HXLINE( 749) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp13 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 749) _hx_tmp13->biasx = (_hx_tmp13->biasx * t3); HXLINE( 750) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp14 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 750) _hx_tmp14->biasy = (_hx_tmp14->biasy * t3); } } } else { HXLINE( 756) { HXLINE( 757) this->biasx = ( (Float)(0) ); HXLINE( 758) this->biasy = ( (Float)(0) ); } HXLINE( 776) this->gamma = ( (Float)(0) ); } HXLINE( 778) { HXLINE( 779) Float t4 = dtratio; HXLINE( 788) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp15 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 788) _hx_tmp15->jAccx = (_hx_tmp15->jAccx * t4); HXLINE( 789) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp16 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 789) _hx_tmp16->jAccy = (_hx_tmp16->jAccy * t4); } HXLINE( 791) this->jMax = (this->maxForce * dt); HXLINE( 792) return false; } void ZPP_PivotJoint_obj::warmStart(){ HX_STACKFRAME(&_hx_pos_e49efd2d085e96b5_826_warmStart) HXLINE( 827) { HXLINE( 828) Float t = this->b1->imass; HXLINE( 837) ::zpp_nape::phys::ZPP_Body _hx_tmp = this->b1; HXDLIN( 837) _hx_tmp->velx = (_hx_tmp->velx - (this->jAccx * t)); HXLINE( 838) ::zpp_nape::phys::ZPP_Body _hx_tmp1 = this->b1; HXDLIN( 838) _hx_tmp1->vely = (_hx_tmp1->vely - (this->jAccy * t)); } HXLINE( 840) { HXLINE( 841) Float t1 = this->b2->imass; HXLINE( 850) ::zpp_nape::phys::ZPP_Body _hx_tmp2 = this->b2; HXDLIN( 850) _hx_tmp2->velx = (_hx_tmp2->velx + (this->jAccx * t1)); HXLINE( 851) ::zpp_nape::phys::ZPP_Body _hx_tmp3 = this->b2; HXDLIN( 851) _hx_tmp3->vely = (_hx_tmp3->vely + (this->jAccy * t1)); } HXLINE( 853) ::zpp_nape::phys::ZPP_Body _hx_tmp4 = this->b1; HXDLIN( 853) _hx_tmp4->angvel = (_hx_tmp4->angvel - (((this->jAccy * this->a1relx) - (this->jAccx * this->a1rely)) * this->b1->iinertia)); HXLINE( 854) ::zpp_nape::phys::ZPP_Body _hx_tmp5 = this->b2; HXDLIN( 854) _hx_tmp5->angvel = (_hx_tmp5->angvel + (((this->jAccy * this->a2relx) - (this->jAccx * this->a2rely)) * this->b2->iinertia)); } bool ZPP_PivotJoint_obj::applyImpulseVel(){ HX_STACKFRAME(&_hx_pos_e49efd2d085e96b5_858_applyImpulseVel) HXLINE( 859) Float Ex = ((Float)0.0); HXLINE( 860) Float Ey = ((Float)0.0); HXLINE( 861) { HXLINE( 862) Ex = (((this->b2->velx + this->b2->kinvelx) - (this->a2rely * (this->b2->angvel + this->b2->kinangvel))) - ((this->b1->velx + this->b1->kinvelx) - (this->a1rely * (this->b1->angvel + this->b1->kinangvel)))); HXLINE( 863) Ey = (((this->b2->vely + this->b2->kinvely) + (this->a2relx * (this->b2->angvel + this->b2->kinangvel))) - ((this->b1->vely + this->b1->kinvely) + (this->a1relx * (this->b1->angvel + this->b1->kinangvel)))); } HXLINE( 865) Float Jx = ((Float)0.0); HXLINE( 866) Float Jy = ((Float)0.0); HXLINE( 867) { HXLINE( 868) Jx = (this->biasx - Ex); HXLINE( 869) Jy = (this->biasy - Ey); } HXLINE( 871) { HXLINE( 872) Float t = ((this->kMassa * Jx) + (this->kMassb * Jy)); HXLINE( 873) Jy = ((this->kMassb * Jx) + (this->kMassc * Jy)); HXLINE( 874) Jx = t; } HXLINE( 876) { HXLINE( 877) Float t1 = this->gamma; HXLINE( 886) Jx = (Jx - (this->jAccx * t1)); HXLINE( 887) Jy = (Jy - (this->jAccy * t1)); } HXLINE( 889) { HXLINE( 890) Float jOldx = ((Float)0.0); HXLINE( 891) Float jOldy = ((Float)0.0); HXLINE( 892) { HXLINE( 893) jOldx = this->jAccx; HXLINE( 894) jOldy = this->jAccy; } HXLINE( 912) { HXLINE( 913) Float t2 = ((Float)1.0); HXLINE( 922) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp = hx::ObjectPtr<OBJ_>(this); HXDLIN( 922) _hx_tmp->jAccx = (_hx_tmp->jAccx + (Jx * t2)); HXLINE( 923) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp1 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 923) _hx_tmp1->jAccy = (_hx_tmp1->jAccy + (Jy * t2)); } HXLINE( 926) if (this->breakUnderForce) { HXLINE( 927) if ((((this->jAccx * this->jAccx) + (this->jAccy * this->jAccy)) > (this->jMax * this->jMax))) { HXLINE( 927) return true; } } else { HXLINE( 929) if (!(this->stiff)) { HXLINE( 930) Float t3 = this->jMax; HXLINE( 939) Float ls = ((this->jAccx * this->jAccx) + (this->jAccy * this->jAccy)); HXLINE( 940) if ((ls > (t3 * t3))) { HXLINE( 950) Float t4 = (t3 * (((Float)1.0) / ::Math_obj::sqrt(ls))); HXLINE( 959) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp2 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 959) _hx_tmp2->jAccx = (_hx_tmp2->jAccx * t4); HXLINE( 960) ::zpp_nape::constraint::ZPP_PivotJoint _hx_tmp3 = hx::ObjectPtr<OBJ_>(this); HXDLIN( 960) _hx_tmp3->jAccy = (_hx_tmp3->jAccy * t4); } } } HXLINE( 965) { HXLINE( 966) Jx = (this->jAccx - jOldx); HXLINE( 967) Jy = (this->jAccy - jOldy); } } HXLINE(1001) { HXLINE(1002) { HXLINE(1003) Float t5 = this->b1->imass; HXLINE(1012) ::zpp_nape::phys::ZPP_Body _hx_tmp4 = this->b1; HXDLIN(1012) _hx_tmp4->velx = (_hx_tmp4->velx - (Jx * t5)); HXLINE(1013) ::zpp_nape::phys::ZPP_Body _hx_tmp5 = this->b1; HXDLIN(1013) _hx_tmp5->vely = (_hx_tmp5->vely - (Jy * t5)); } HXLINE(1015) { HXLINE(1016) Float t6 = this->b2->imass; HXLINE(1025) ::zpp_nape::phys::ZPP_Body _hx_tmp6 = this->b2; HXDLIN(1025) _hx_tmp6->velx = (_hx_tmp6->velx + (Jx * t6)); HXLINE(1026) ::zpp_nape::phys::ZPP_Body _hx_tmp7 = this->b2; HXDLIN(1026) _hx_tmp7->vely = (_hx_tmp7->vely + (Jy * t6)); } HXLINE(1028) ::zpp_nape::phys::ZPP_Body _hx_tmp8 = this->b1; HXDLIN(1028) _hx_tmp8->angvel = (_hx_tmp8->angvel - (((Jy * this->a1relx) - (Jx * this->a1rely)) * this->b1->iinertia)); HXLINE(1029) ::zpp_nape::phys::ZPP_Body _hx_tmp9 = this->b2; HXDLIN(1029) _hx_tmp9->angvel = (_hx_tmp9->angvel + (((Jy * this->a2relx) - (Jx * this->a2rely)) * this->b2->iinertia)); } HXLINE(1032) return false; } bool ZPP_PivotJoint_obj::applyImpulsePos(){ HX_STACKFRAME(&_hx_pos_e49efd2d085e96b5_1034_applyImpulsePos) HXLINE(1035) Float r1x = ((Float)0.0); HXLINE(1036) Float r1y = ((Float)0.0); HXLINE(1038) { HXLINE(1039) r1x = ((this->b1->axisy * this->a1localx) - (this->b1->axisx * this->a1localy)); HXLINE(1040) r1y = ((this->a1localx * this->b1->axisx) + (this->a1localy * this->b1->axisy)); } HXLINE(1043) Float r2x = ((Float)0.0); HXLINE(1044) Float r2y = ((Float)0.0); HXLINE(1046) { HXLINE(1047) r2x = ((this->b2->axisy * this->a2localx) - (this->b2->axisx * this->a2localy)); HXLINE(1048) r2y = ((this->a2localx * this->b2->axisx) + (this->a2localy * this->b2->axisy)); } HXLINE(1051) Float Ex = ((Float)0.0); HXLINE(1052) Float Ey = ((Float)0.0); HXLINE(1053) { HXLINE(1054) Ex = ((this->b2->posx + r2x) - (this->b1->posx + r1x)); HXLINE(1055) Ey = ((this->b2->posy + r2y) - (this->b1->posy + r1y)); } HXLINE(1057) bool _hx_tmp; HXDLIN(1057) if (this->breakUnderError) { HXLINE(1057) _hx_tmp = (((Ex * Ex) + (Ey * Ey)) > (this->maxError * this->maxError)); } else { HXLINE(1057) _hx_tmp = false; } HXDLIN(1057) if (_hx_tmp) { HXLINE(1057) return true; } HXLINE(1058) if ((((Ex * Ex) + (Ey * Ey)) < (::nape::Config_obj::constraintLinearSlop * ::nape::Config_obj::constraintLinearSlop))) { HXLINE(1058) return false; } HXLINE(1059) { HXLINE(1060) Float t = ((Float)0.5); HXLINE(1069) Ex = (Ex * t); HXLINE(1070) Ey = (Ey * t); } HXLINE(1072) Float Jx = ((Float)0.0); HXLINE(1073) Float Jy = ((Float)0.0); HXLINE(1074) if ((((Ex * Ex) + (Ey * Ey)) > 6)) { HXLINE(1075) Float k = (this->b1->smass + this->b2->smass); HXLINE(1076) if ((k > ::nape::Config_obj::epsilon)) { HXLINE(1077) k = (((Float)0.75) / k); HXLINE(1078) { HXLINE(1079) Jx = (-(Ex) * k); HXLINE(1080) Jy = (-(Ey) * k); } HXLINE(1098) { HXLINE(1099) int t1 = 20; HXLINE(1108) Float ls = ((Jx * Jx) + (Jy * Jy)); HXLINE(1109) if ((ls > (t1 * t1))) { HXLINE(1119) Float t2 = (( (Float)(t1) ) * (((Float)1.0) / ::Math_obj::sqrt(ls))); HXLINE(1128) Jx = (Jx * t2); HXLINE(1129) Jy = (Jy * t2); } } HXLINE(1133) { HXLINE(1134) Float t3 = this->b1->imass; HXLINE(1143) ::zpp_nape::phys::ZPP_Body _hx_tmp1 = this->b1; HXDLIN(1143) _hx_tmp1->posx = (_hx_tmp1->posx - (Jx * t3)); HXLINE(1144) ::zpp_nape::phys::ZPP_Body _hx_tmp2 = this->b1; HXDLIN(1144) _hx_tmp2->posy = (_hx_tmp2->posy - (Jy * t3)); } HXLINE(1146) { HXLINE(1147) Float t4 = this->b2->imass; HXLINE(1156) ::zpp_nape::phys::ZPP_Body _hx_tmp3 = this->b2; HXDLIN(1156) _hx_tmp3->posx = (_hx_tmp3->posx + (Jx * t4)); HXLINE(1157) ::zpp_nape::phys::ZPP_Body _hx_tmp4 = this->b2; HXDLIN(1157) _hx_tmp4->posy = (_hx_tmp4->posy + (Jy * t4)); } HXLINE(1159) { HXLINE(1160) Ex = ((this->b2->posx + r2x) - (this->b1->posx + r1x)); HXLINE(1161) Ey = ((this->b2->posy + r2y) - (this->b1->posy + r1y)); } HXLINE(1163) { HXLINE(1164) Float t5 = ((Float)0.5); HXLINE(1173) Ex = (Ex * t5); HXLINE(1174) Ey = (Ey * t5); } } } HXLINE(1178) Float Ka = ((Float)0.0); HXLINE(1179) Float Kb = ((Float)0.0); HXLINE(1180) Float Kc = ((Float)0.0); HXLINE(1181) { HXLINE(1182) Float m = (this->b1->smass + this->b2->smass); HXLINE(1183) { HXLINE(1184) Ka = m; HXLINE(1185) Kb = ( (Float)(0) ); HXLINE(1186) Kc = m; } HXLINE(1188) if ((this->b1->sinertia != 0)) { HXLINE(1189) Float X = (r1x * this->b1->sinertia); HXLINE(1190) Float Y = (r1y * this->b1->sinertia); HXLINE(1191) { HXLINE(1192) Ka = (Ka + (Y * r1y)); HXLINE(1193) Kb = (Kb + (-(Y) * r1x)); HXLINE(1194) Kc = (Kc + (X * r1x)); } } HXLINE(1197) if ((this->b2->sinertia != 0)) { HXLINE(1198) Float X1 = (r2x * this->b2->sinertia); HXLINE(1199) Float Y1 = (r2y * this->b2->sinertia); HXLINE(1200) { HXLINE(1201) Ka = (Ka + (Y1 * r2y)); HXLINE(1202) Kb = (Kb + (-(Y1) * r2x)); HXLINE(1203) Kc = (Kc + (X1 * r2x)); } } } HXLINE(1207) { HXLINE(1208) Jx = -(Ex); HXLINE(1209) Jy = -(Ey); } HXLINE(1227) { HXLINE(1228) int t6 = 6; HXLINE(1237) Float ls1 = ((Jx * Jx) + (Jy * Jy)); HXLINE(1238) if ((ls1 > (t6 * t6))) { HXLINE(1248) Float t7 = (( (Float)(t6) ) * (((Float)1.0) / ::Math_obj::sqrt(ls1))); HXLINE(1257) Jx = (Jx * t7); HXLINE(1258) Jy = (Jy * t7); } } HXLINE(1262) { HXLINE(1263) Float det = ((Ka * Kc) - (Kb * Kb)); HXLINE(1264) if ((det != det)) { HXLINE(1264) Jy = ( (Float)(0) ); HXDLIN(1264) Jx = Jy; } else { HXLINE(1265) if ((det == 0)) { HXLINE(1266) if ((Ka != 0)) { HXLINE(1266) Jx = (Jx / Ka); } else { HXLINE(1267) Jx = ( (Float)(0) ); } HXLINE(1268) if ((Kc != 0)) { HXLINE(1268) Jy = (Jy / Kc); } else { HXLINE(1269) Jy = ( (Float)(0) ); } } else { HXLINE(1272) det = (( (Float)(1) ) / det); HXLINE(1273) Float t8 = (det * ((Kc * Jx) - (Kb * Jy))); HXLINE(1274) Jy = (det * ((Ka * Jy) - (Kb * Jx))); HXLINE(1275) Jx = t8; } } } HXLINE(1279) { HXLINE(1280) { HXLINE(1281) Float t9 = this->b1->imass; HXLINE(1290) ::zpp_nape::phys::ZPP_Body _hx_tmp5 = this->b1; HXDLIN(1290) _hx_tmp5->posx = (_hx_tmp5->posx - (Jx * t9)); HXLINE(1291) ::zpp_nape::phys::ZPP_Body _hx_tmp6 = this->b1; HXDLIN(1291) _hx_tmp6->posy = (_hx_tmp6->posy - (Jy * t9)); } HXLINE(1293) { HXLINE(1294) Float t10 = this->b2->imass; HXLINE(1303) ::zpp_nape::phys::ZPP_Body _hx_tmp7 = this->b2; HXDLIN(1303) _hx_tmp7->posx = (_hx_tmp7->posx + (Jx * t10)); HXLINE(1304) ::zpp_nape::phys::ZPP_Body _hx_tmp8 = this->b2; HXDLIN(1304) _hx_tmp8->posy = (_hx_tmp8->posy + (Jy * t10)); } HXLINE(1306) { HXLINE(1306) ::zpp_nape::phys::ZPP_Body _this = this->b1; HXDLIN(1306) Float dr = (-(((Jy * r1x) - (Jx * r1y))) * this->b1->iinertia); HXDLIN(1306) ::zpp_nape::phys::ZPP_Body _this1 = _this; HXDLIN(1306) _this1->rot = (_this1->rot + dr); HXDLIN(1306) if (((dr * dr) > ((Float)0.0001))) { HXLINE(1306) _this->axisx = ::Math_obj::sin(_this->rot); HXDLIN(1306) _this->axisy = ::Math_obj::cos(_this->rot); } else { HXLINE(1306) Float d2 = (dr * dr); HXDLIN(1306) Float p = (( (Float)(1) ) - (((Float)0.5) * d2)); HXDLIN(1306) Float m1 = (( (Float)(1) ) - ((d2 * d2) / ( (Float)(8) ))); HXDLIN(1306) Float nx = (((p * _this->axisx) + (dr * _this->axisy)) * m1); HXDLIN(1306) _this->axisy = (((p * _this->axisy) - (dr * _this->axisx)) * m1); HXDLIN(1306) _this->axisx = nx; } } HXLINE(1307) { HXLINE(1307) ::zpp_nape::phys::ZPP_Body _this2 = this->b2; HXDLIN(1307) Float dr1 = (((Jy * r2x) - (Jx * r2y)) * this->b2->iinertia); HXDLIN(1307) ::zpp_nape::phys::ZPP_Body _this3 = _this2; HXDLIN(1307) _this3->rot = (_this3->rot + dr1); HXDLIN(1307) if (((dr1 * dr1) > ((Float)0.0001))) { HXLINE(1307) _this2->axisx = ::Math_obj::sin(_this2->rot); HXDLIN(1307) _this2->axisy = ::Math_obj::cos(_this2->rot); } else { HXLINE(1307) Float d21 = (dr1 * dr1); HXDLIN(1307) Float p1 = (( (Float)(1) ) - (((Float)0.5) * d21)); HXDLIN(1307) Float m2 = (( (Float)(1) ) - ((d21 * d21) / ( (Float)(8) ))); HXDLIN(1307) Float nx1 = (((p1 * _this2->axisx) + (dr1 * _this2->axisy)) * m2); HXDLIN(1307) _this2->axisy = (((p1 * _this2->axisy) - (dr1 * _this2->axisx)) * m2); HXDLIN(1307) _this2->axisx = nx1; } } } HXLINE(1340) return false; } void ZPP_PivotJoint_obj::draw( ::nape::util::Debug g){ HX_STACKFRAME(&_hx_pos_e49efd2d085e96b5_1342_draw) } hx::ObjectPtr< ZPP_PivotJoint_obj > ZPP_PivotJoint_obj::__new() { hx::ObjectPtr< ZPP_PivotJoint_obj > __this = new ZPP_PivotJoint_obj(); __this->__construct(); return __this; } hx::ObjectPtr< ZPP_PivotJoint_obj > ZPP_PivotJoint_obj::__alloc(hx::Ctx *_hx_ctx) { ZPP_PivotJoint_obj *__this = (ZPP_PivotJoint_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(ZPP_PivotJoint_obj), true, "zpp_nape.constraint.ZPP_PivotJoint")); *(void **)__this = ZPP_PivotJoint_obj::_hx_vtable; __this->__construct(); return __this; } ZPP_PivotJoint_obj::ZPP_PivotJoint_obj() { } void ZPP_PivotJoint_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(ZPP_PivotJoint); HX_MARK_MEMBER_NAME(outer_zn,"outer_zn"); HX_MARK_MEMBER_NAME(b1,"b1"); HX_MARK_MEMBER_NAME(a1localx,"a1localx"); HX_MARK_MEMBER_NAME(a1localy,"a1localy"); HX_MARK_MEMBER_NAME(a1relx,"a1relx"); HX_MARK_MEMBER_NAME(a1rely,"a1rely"); HX_MARK_MEMBER_NAME(wrap_a1,"wrap_a1"); HX_MARK_MEMBER_NAME(b2,"b2"); HX_MARK_MEMBER_NAME(a2localx,"a2localx"); HX_MARK_MEMBER_NAME(a2localy,"a2localy"); HX_MARK_MEMBER_NAME(a2relx,"a2relx"); HX_MARK_MEMBER_NAME(a2rely,"a2rely"); HX_MARK_MEMBER_NAME(wrap_a2,"wrap_a2"); HX_MARK_MEMBER_NAME(kMassa,"kMassa"); HX_MARK_MEMBER_NAME(kMassb,"kMassb"); HX_MARK_MEMBER_NAME(kMassc,"kMassc"); HX_MARK_MEMBER_NAME(jAccx,"jAccx"); HX_MARK_MEMBER_NAME(jAccy,"jAccy"); HX_MARK_MEMBER_NAME(jMax,"jMax"); HX_MARK_MEMBER_NAME(gamma,"gamma"); HX_MARK_MEMBER_NAME(biasx,"biasx"); HX_MARK_MEMBER_NAME(biasy,"biasy"); HX_MARK_MEMBER_NAME(stepped,"stepped"); ::zpp_nape::constraint::ZPP_Constraint_obj::__Mark(HX_MARK_ARG); HX_MARK_END_CLASS(); } void ZPP_PivotJoint_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(outer_zn,"outer_zn"); HX_VISIT_MEMBER_NAME(b1,"b1"); HX_VISIT_MEMBER_NAME(a1localx,"a1localx"); HX_VISIT_MEMBER_NAME(a1localy,"a1localy"); HX_VISIT_MEMBER_NAME(a1relx,"a1relx"); HX_VISIT_MEMBER_NAME(a1rely,"a1rely"); HX_VISIT_MEMBER_NAME(wrap_a1,"wrap_a1"); HX_VISIT_MEMBER_NAME(b2,"b2"); HX_VISIT_MEMBER_NAME(a2localx,"a2localx"); HX_VISIT_MEMBER_NAME(a2localy,"a2localy"); HX_VISIT_MEMBER_NAME(a2relx,"a2relx"); HX_VISIT_MEMBER_NAME(a2rely,"a2rely"); HX_VISIT_MEMBER_NAME(wrap_a2,"wrap_a2"); HX_VISIT_MEMBER_NAME(kMassa,"kMassa"); HX_VISIT_MEMBER_NAME(kMassb,"kMassb"); HX_VISIT_MEMBER_NAME(kMassc,"kMassc"); HX_VISIT_MEMBER_NAME(jAccx,"jAccx"); HX_VISIT_MEMBER_NAME(jAccy,"jAccy"); HX_VISIT_MEMBER_NAME(jMax,"jMax"); HX_VISIT_MEMBER_NAME(gamma,"gamma"); HX_VISIT_MEMBER_NAME(biasx,"biasx"); HX_VISIT_MEMBER_NAME(biasy,"biasy"); HX_VISIT_MEMBER_NAME(stepped,"stepped"); ::zpp_nape::constraint::ZPP_Constraint_obj::__Visit(HX_VISIT_ARG); } hx::Val ZPP_PivotJoint_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 2: if (HX_FIELD_EQ(inName,"b1") ) { return hx::Val( b1 ); } if (HX_FIELD_EQ(inName,"b2") ) { return hx::Val( b2 ); } break; case 4: if (HX_FIELD_EQ(inName,"jMax") ) { return hx::Val( jMax ); } if (HX_FIELD_EQ(inName,"copy") ) { return hx::Val( copy_dyn() ); } if (HX_FIELD_EQ(inName,"draw") ) { return hx::Val( draw_dyn() ); } break; case 5: if (HX_FIELD_EQ(inName,"jAccx") ) { return hx::Val( jAccx ); } if (HX_FIELD_EQ(inName,"jAccy") ) { return hx::Val( jAccy ); } if (HX_FIELD_EQ(inName,"gamma") ) { return hx::Val( gamma ); } if (HX_FIELD_EQ(inName,"biasx") ) { return hx::Val( biasx ); } if (HX_FIELD_EQ(inName,"biasy") ) { return hx::Val( biasy ); } break; case 6: if (HX_FIELD_EQ(inName,"a1relx") ) { return hx::Val( a1relx ); } if (HX_FIELD_EQ(inName,"a1rely") ) { return hx::Val( a1rely ); } if (HX_FIELD_EQ(inName,"a2relx") ) { return hx::Val( a2relx ); } if (HX_FIELD_EQ(inName,"a2rely") ) { return hx::Val( a2rely ); } if (HX_FIELD_EQ(inName,"kMassa") ) { return hx::Val( kMassa ); } if (HX_FIELD_EQ(inName,"kMassb") ) { return hx::Val( kMassb ); } if (HX_FIELD_EQ(inName,"kMassc") ) { return hx::Val( kMassc ); } if (HX_FIELD_EQ(inName,"forest") ) { return hx::Val( forest_dyn() ); } break; case 7: if (HX_FIELD_EQ(inName,"wrap_a1") ) { return hx::Val( wrap_a1 ); } if (HX_FIELD_EQ(inName,"wrap_a2") ) { return hx::Val( wrap_a2 ); } if (HX_FIELD_EQ(inName,"stepped") ) { return hx::Val( stepped ); } if (HX_FIELD_EQ(inName,"preStep") ) { return hx::Val( preStep_dyn() ); } break; case 8: if (HX_FIELD_EQ(inName,"outer_zn") ) { return hx::Val( outer_zn ); } if (HX_FIELD_EQ(inName,"a1localx") ) { return hx::Val( a1localx ); } if (HX_FIELD_EQ(inName,"a1localy") ) { return hx::Val( a1localy ); } if (HX_FIELD_EQ(inName,"setup_a1") ) { return hx::Val( setup_a1_dyn() ); } if (HX_FIELD_EQ(inName,"a2localx") ) { return hx::Val( a2localx ); } if (HX_FIELD_EQ(inName,"a2localy") ) { return hx::Val( a2localy ); } if (HX_FIELD_EQ(inName,"setup_a2") ) { return hx::Val( setup_a2_dyn() ); } if (HX_FIELD_EQ(inName,"validate") ) { return hx::Val( validate_dyn() ); } break; case 9: if (HX_FIELD_EQ(inName,"warmStart") ) { return hx::Val( warmStart_dyn() ); } break; case 10: if (HX_FIELD_EQ(inName,"clearcache") ) { return hx::Val( clearcache_dyn() ); } break; case 11: if (HX_FIELD_EQ(inName,"bodyImpulse") ) { return hx::Val( bodyImpulse_dyn() ); } if (HX_FIELD_EQ(inName,"validate_a1") ) { return hx::Val( validate_a1_dyn() ); } if (HX_FIELD_EQ(inName,"validate_a2") ) { return hx::Val( validate_a2_dyn() ); } if (HX_FIELD_EQ(inName,"pair_exists") ) { return hx::Val( pair_exists_dyn() ); } break; case 12: if (HX_FIELD_EQ(inName,"activeBodies") ) { return hx::Val( activeBodies_dyn() ); } break; case 13: if (HX_FIELD_EQ(inName,"invalidate_a1") ) { return hx::Val( invalidate_a1_dyn() ); } if (HX_FIELD_EQ(inName,"invalidate_a2") ) { return hx::Val( invalidate_a2_dyn() ); } break; case 14: if (HX_FIELD_EQ(inName,"inactiveBodies") ) { return hx::Val( inactiveBodies_dyn() ); } if (HX_FIELD_EQ(inName,"wake_connected") ) { return hx::Val( wake_connected_dyn() ); } break; case 15: if (HX_FIELD_EQ(inName,"applyImpulseVel") ) { return hx::Val( applyImpulseVel_dyn() ); } if (HX_FIELD_EQ(inName,"applyImpulsePos") ) { return hx::Val( applyImpulsePos_dyn() ); } } return super::__Field(inName,inCallProp); } hx::Val ZPP_PivotJoint_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 2: if (HX_FIELD_EQ(inName,"b1") ) { b1=inValue.Cast< ::zpp_nape::phys::ZPP_Body >(); return inValue; } if (HX_FIELD_EQ(inName,"b2") ) { b2=inValue.Cast< ::zpp_nape::phys::ZPP_Body >(); return inValue; } break; case 4: if (HX_FIELD_EQ(inName,"jMax") ) { jMax=inValue.Cast< Float >(); return inValue; } break; case 5: if (HX_FIELD_EQ(inName,"jAccx") ) { jAccx=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"jAccy") ) { jAccy=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"gamma") ) { gamma=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"biasx") ) { biasx=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"biasy") ) { biasy=inValue.Cast< Float >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"a1relx") ) { a1relx=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"a1rely") ) { a1rely=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"a2relx") ) { a2relx=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"a2rely") ) { a2rely=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"kMassa") ) { kMassa=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"kMassb") ) { kMassb=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"kMassc") ) { kMassc=inValue.Cast< Float >(); return inValue; } break; case 7: if (HX_FIELD_EQ(inName,"wrap_a1") ) { wrap_a1=inValue.Cast< ::nape::geom::Vec2 >(); return inValue; } if (HX_FIELD_EQ(inName,"wrap_a2") ) { wrap_a2=inValue.Cast< ::nape::geom::Vec2 >(); return inValue; } if (HX_FIELD_EQ(inName,"stepped") ) { stepped=inValue.Cast< bool >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"outer_zn") ) { outer_zn=inValue.Cast< ::nape::constraint::PivotJoint >(); return inValue; } if (HX_FIELD_EQ(inName,"a1localx") ) { a1localx=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"a1localy") ) { a1localy=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"a2localx") ) { a2localx=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"a2localy") ) { a2localy=inValue.Cast< Float >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void ZPP_PivotJoint_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("outer_zn",38,07,b0,a2)); outFields->push(HX_("b1",8f,55,00,00)); outFields->push(HX_("a1localx",5d,6d,78,fb)); outFields->push(HX_("a1localy",5e,6d,78,fb)); outFields->push(HX_("a1relx",af,c1,e7,4a)); outFields->push(HX_("a1rely",b0,c1,e7,4a)); outFields->push(HX_("wrap_a1",45,eb,57,0d)); outFields->push(HX_("b2",90,55,00,00)); outFields->push(HX_("a2localx",1e,e4,0d,25)); outFields->push(HX_("a2localy",1f,e4,0d,25)); outFields->push(HX_("a2relx",30,56,4e,de)); outFields->push(HX_("a2rely",31,56,4e,de)); outFields->push(HX_("wrap_a2",46,eb,57,0d)); outFields->push(HX_("kMassa",82,a0,7f,5e)); outFields->push(HX_("kMassb",83,a0,7f,5e)); outFields->push(HX_("kMassc",84,a0,7f,5e)); outFields->push(HX_("jAccx",a1,d1,bb,33)); outFields->push(HX_("jAccy",a2,d1,bb,33)); outFields->push(HX_("jMax",5a,60,4b,46)); outFields->push(HX_("gamma",27,87,b6,8e)); outFields->push(HX_("biasx",df,3f,f6,b2)); outFields->push(HX_("biasy",e0,3f,f6,b2)); outFields->push(HX_("stepped",03,05,60,81)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo ZPP_PivotJoint_obj_sMemberStorageInfo[] = { {hx::fsObject /* ::nape::constraint::PivotJoint */ ,(int)offsetof(ZPP_PivotJoint_obj,outer_zn),HX_("outer_zn",38,07,b0,a2)}, {hx::fsObject /* ::zpp_nape::phys::ZPP_Body */ ,(int)offsetof(ZPP_PivotJoint_obj,b1),HX_("b1",8f,55,00,00)}, {hx::fsFloat,(int)offsetof(ZPP_PivotJoint_obj,a1localx),HX_("a1localx",5d,6d,78,fb)}, {hx::fsFloat,(int)offsetof(ZPP_PivotJoint_obj,a1localy),HX_("a1localy",5e,6d,78,fb)}, {hx::fsFloat,(int)offsetof(ZPP_PivotJoint_obj,a1relx),HX_("a1relx",af,c1,e7,4a)}, {hx::fsFloat,(int)offsetof(ZPP_PivotJoint_obj,a1rely),HX_("a1rely",b0,c1,e7,4a)}, {hx::fsObject /* ::nape::geom::Vec2 */ ,(int)offsetof(ZPP_PivotJoint_obj,wrap_a1),HX_("wrap_a1",45,eb,57,0d)}, {hx::fsObject /* ::zpp_nape::phys::ZPP_Body */ ,(int)offsetof(ZPP_PivotJoint_obj,b2),HX_("b2",90,55,00,00)}, {hx::fsFloat,(int)offsetof(ZPP_PivotJoint_obj,a2localx),HX_("a2localx",1e,e4,0d,25)}, {hx::fsFloat,(int)offsetof(ZPP_PivotJoint_obj,a2localy),HX_("a2localy",1f,e4,0d,25)}, {hx::fsFloat,(int)offsetof(ZPP_PivotJoint_obj,a2relx),HX_("a2relx",30,56,4e,de)}, {hx::fsFloat,(int)offsetof(ZPP_PivotJoint_obj,a2rely),HX_("a2rely",31,56,4e,de)}, {hx::fsObject /* ::nape::geom::Vec2 */ ,(int)offsetof(ZPP_PivotJoint_obj,wrap_a2),HX_("wrap_a2",46,eb,57,0d)}, {hx::fsFloat,(int)offsetof(ZPP_PivotJoint_obj,kMassa),HX_("kMassa",82,a0,7f,5e)}, {hx::fsFloat,(int)offsetof(ZPP_PivotJoint_obj,kMassb),HX_("kMassb",83,a0,7f,5e)}, {hx::fsFloat,(int)offsetof(ZPP_PivotJoint_obj,kMassc),HX_("kMassc",84,a0,7f,5e)}, {hx::fsFloat,(int)offsetof(ZPP_PivotJoint_obj,jAccx),HX_("jAccx",a1,d1,bb,33)}, {hx::fsFloat,(int)offsetof(ZPP_PivotJoint_obj,jAccy),HX_("jAccy",a2,d1,bb,33)}, {hx::fsFloat,(int)offsetof(ZPP_PivotJoint_obj,jMax),HX_("jMax",5a,60,4b,46)}, {hx::fsFloat,(int)offsetof(ZPP_PivotJoint_obj,gamma),HX_("gamma",27,87,b6,8e)}, {hx::fsFloat,(int)offsetof(ZPP_PivotJoint_obj,biasx),HX_("biasx",df,3f,f6,b2)}, {hx::fsFloat,(int)offsetof(ZPP_PivotJoint_obj,biasy),HX_("biasy",e0,3f,f6,b2)}, {hx::fsBool,(int)offsetof(ZPP_PivotJoint_obj,stepped),HX_("stepped",03,05,60,81)}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo *ZPP_PivotJoint_obj_sStaticStorageInfo = 0; #endif static ::String ZPP_PivotJoint_obj_sMemberFields[] = { HX_("outer_zn",38,07,b0,a2), HX_("bodyImpulse",33,76,a2,5f), HX_("activeBodies",e6,69,f8,ba), HX_("inactiveBodies",4b,89,c5,8c), HX_("b1",8f,55,00,00), HX_("a1localx",5d,6d,78,fb), HX_("a1localy",5e,6d,78,fb), HX_("a1relx",af,c1,e7,4a), HX_("a1rely",b0,c1,e7,4a), HX_("validate_a1",f9,9b,cc,ca), HX_("invalidate_a1",34,30,01,a7), HX_("setup_a1",72,28,39,23), HX_("wrap_a1",45,eb,57,0d), HX_("b2",90,55,00,00), HX_("a2localx",1e,e4,0d,25), HX_("a2localy",1f,e4,0d,25), HX_("a2relx",30,56,4e,de), HX_("a2rely",31,56,4e,de), HX_("validate_a2",fa,9b,cc,ca), HX_("invalidate_a2",35,30,01,a7), HX_("setup_a2",73,28,39,23), HX_("wrap_a2",46,eb,57,0d), HX_("kMassa",82,a0,7f,5e), HX_("kMassb",83,a0,7f,5e), HX_("kMassc",84,a0,7f,5e), HX_("jAccx",a1,d1,bb,33), HX_("jAccy",a2,d1,bb,33), HX_("jMax",5a,60,4b,46), HX_("gamma",27,87,b6,8e), HX_("biasx",df,3f,f6,b2), HX_("biasy",e0,3f,f6,b2), HX_("stepped",03,05,60,81), HX_("copy",b5,bb,c4,41), HX_("validate",96,d0,e3,04), HX_("wake_connected",ae,cf,dd,3d), HX_("forest",dd,8c,88,fd), HX_("pair_exists",a1,6a,58,69), HX_("clearcache",95,69,f1,82), HX_("preStep",0f,c1,c0,24), HX_("warmStart",dd,27,03,eb), HX_("applyImpulseVel",b6,c7,50,1f), HX_("applyImpulsePos",ed,42,4c,1f), HX_("draw",04,2c,70,42), ::String(null()) }; hx::Class ZPP_PivotJoint_obj::__mClass; void ZPP_PivotJoint_obj::__register() { ZPP_PivotJoint_obj _hx_dummy; ZPP_PivotJoint_obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("zpp_nape.constraint.ZPP_PivotJoint",9d,7a,47,ba); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(ZPP_PivotJoint_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< ZPP_PivotJoint_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = ZPP_PivotJoint_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = ZPP_PivotJoint_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace zpp_nape } // end namespace constraint
43.047619
238
0.62015
HedgehogFog
501468204233322d8c55fd850f6924e6e22017f5
29,849
hpp
C++
hpx/runtime/components/server/preprocessed/runtime_support_implementations_5.hpp
Titzi90/hpx
150fb0de1cfe40c26a722918097199147957b45c
[ "BSL-1.0" ]
null
null
null
hpx/runtime/components/server/preprocessed/runtime_support_implementations_5.hpp
Titzi90/hpx
150fb0de1cfe40c26a722918097199147957b45c
[ "BSL-1.0" ]
null
null
null
hpx/runtime/components/server/preprocessed/runtime_support_implementations_5.hpp
Titzi90/hpx
150fb0de1cfe40c26a722918097199147957b45c
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2007-2013 Hartmut Kaiser // Copyright (c) 2012-2013 Thomas Heller // // 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) // This file has been automatically generated using the Boost.Wave tool. // Do not edit manually. namespace hpx { namespace components { namespace server { template <typename Component > struct create_component_action0 : ::hpx::actions::action< naming::gid_type (runtime_support::*)() , &runtime_support::create_component0< Component > , create_component_action0< Component > > {}; template <typename Component > struct create_component_direct_action0 : ::hpx::actions::direct_action< naming::gid_type (runtime_support::*)() , &runtime_support::create_component0< Component > , create_component_direct_action0< Component > > {}; }}} namespace hpx { namespace components { namespace server { template <typename Component, typename A0> naming::gid_type runtime_support::create_component1( A0 a0) { components::component_type const type = components::get_component_type< typename Component::wrapped_type>(); component_map_mutex_type::scoped_lock l(cm_mtx_); component_map_type::const_iterator it = components_.find(type); if (it == components_.end()) { hpx::util::osstream strm; strm << "attempt to create component instance of " << "invalid/unknown type: " << components::get_component_type_name(type) << " (component type not found in map)"; HPX_THROW_EXCEPTION(hpx::bad_component_type, "runtime_support::create_component", hpx::util::osstream_get_string(strm)); return naming::invalid_gid; } if (!(*it).second.first) { hpx::util::osstream strm; strm << "attempt to create component instance of " << "invalid/unknown type: " << components::get_component_type_name(type) << " (map entry is NULL)"; HPX_THROW_EXCEPTION(hpx::bad_component_type, "runtime_support::create_component", hpx::util::osstream_get_string(strm)); return naming::invalid_gid; } naming::gid_type id; boost::shared_ptr<component_factory_base> factory((*it).second.first); { util::scoped_unlock<component_map_mutex_type::scoped_lock> ul(l); id = factory->create_with_args( component_constructor_functor1< typename Component::wrapping_type, A0>( std::forward<A0>( a0 ))); } LRT_(info) << "successfully created component " << id << " of type: " << components::get_component_type_name(type); return id; } template <typename Component , typename A0> struct create_component_action1 : ::hpx::actions::action< naming::gid_type (runtime_support::*)(A0) , &runtime_support::create_component1< Component , A0> , create_component_action1< Component , A0> > {}; template <typename Component , typename A0> struct create_component_direct_action1 : ::hpx::actions::direct_action< naming::gid_type (runtime_support::*)(A0) , &runtime_support::create_component1< Component , A0> , create_component_direct_action1< Component , A0> > {}; template <typename Component > struct bulk_create_component_action1 : ::hpx::actions::action< std::vector<naming::gid_type> (runtime_support::*)( std::size_t ) , &runtime_support::bulk_create_component1< Component > , bulk_create_component_action1< Component > > {}; template <typename Component > struct bulk_create_component_direct_action1 : ::hpx::actions::direct_action< std::vector<naming::gid_type> (runtime_support::*)( std::size_t ) , &runtime_support::bulk_create_component1< Component > , bulk_create_component_direct_action1< Component > > {}; }}} namespace hpx { namespace components { namespace server { template <typename Component, typename A0 , typename A1> naming::gid_type runtime_support::create_component2( A0 a0 , A1 a1) { components::component_type const type = components::get_component_type< typename Component::wrapped_type>(); component_map_mutex_type::scoped_lock l(cm_mtx_); component_map_type::const_iterator it = components_.find(type); if (it == components_.end()) { hpx::util::osstream strm; strm << "attempt to create component instance of " << "invalid/unknown type: " << components::get_component_type_name(type) << " (component type not found in map)"; HPX_THROW_EXCEPTION(hpx::bad_component_type, "runtime_support::create_component", hpx::util::osstream_get_string(strm)); return naming::invalid_gid; } if (!(*it).second.first) { hpx::util::osstream strm; strm << "attempt to create component instance of " << "invalid/unknown type: " << components::get_component_type_name(type) << " (map entry is NULL)"; HPX_THROW_EXCEPTION(hpx::bad_component_type, "runtime_support::create_component", hpx::util::osstream_get_string(strm)); return naming::invalid_gid; } naming::gid_type id; boost::shared_ptr<component_factory_base> factory((*it).second.first); { util::scoped_unlock<component_map_mutex_type::scoped_lock> ul(l); id = factory->create_with_args( component_constructor_functor2< typename Component::wrapping_type, A0 , A1>( std::forward<A0>( a0 ) , std::forward<A1>( a1 ))); } LRT_(info) << "successfully created component " << id << " of type: " << components::get_component_type_name(type); return id; } template <typename Component , typename A0 , typename A1> struct create_component_action2 : ::hpx::actions::action< naming::gid_type (runtime_support::*)(A0 , A1) , &runtime_support::create_component2< Component , A0 , A1> , create_component_action2< Component , A0 , A1> > {}; template <typename Component , typename A0 , typename A1> struct create_component_direct_action2 : ::hpx::actions::direct_action< naming::gid_type (runtime_support::*)(A0 , A1) , &runtime_support::create_component2< Component , A0 , A1> , create_component_direct_action2< Component , A0 , A1> > {}; template <typename Component, typename A0> std::vector<naming::gid_type> runtime_support::bulk_create_component2(std::size_t count, A0 a0) { components::component_type const type = components::get_component_type< typename Component::wrapped_type>(); component_map_mutex_type::scoped_lock l(cm_mtx_); component_map_type::const_iterator it = components_.find(type); if (it == components_.end()) { hpx::util::osstream strm; strm << "attempt to create component(s) instance of " << "invalid/unknown type: " << components::get_component_type_name(type) << " (component type not found in map)"; HPX_THROW_EXCEPTION(hpx::bad_component_type, "runtime_support::create_component", hpx::util::osstream_get_string(strm)); return std::vector<naming::gid_type>(); } if (!(*it).second.first) { hpx::util::osstream strm; strm << "attempt to create component instance(s) of " << "invalid/unknown type: " << components::get_component_type_name(type) << " (map entry is NULL)"; HPX_THROW_EXCEPTION(hpx::bad_component_type, "runtime_support::create_component", hpx::util::osstream_get_string(strm)); return std::vector<naming::gid_type>(); } std::vector<naming::gid_type> ids; ids.reserve(count); boost::shared_ptr<component_factory_base> factory((*it).second.first); { util::scoped_unlock<component_map_mutex_type::scoped_lock> ul(l); for (std::size_t i = 0; i != count; ++i) { ids.push_back(factory->create_with_args( component_constructor_functor1< typename Component::wrapping_type, A0 >(std::forward<A0>( a0 ))) ); } } LRT_(info) << "successfully created " << count << " component(s) of type: " << components::get_component_type_name(type); return std::move(ids); } template <typename Component , typename A0> struct bulk_create_component_action2 : ::hpx::actions::action< std::vector<naming::gid_type> (runtime_support::*)( std::size_t , A0) , &runtime_support::bulk_create_component2< Component , A0> , bulk_create_component_action2< Component , A0> > {}; template <typename Component , typename A0> struct bulk_create_component_direct_action2 : ::hpx::actions::direct_action< std::vector<naming::gid_type> (runtime_support::*)( std::size_t , A0) , &runtime_support::bulk_create_component2< Component , A0> , bulk_create_component_direct_action2< Component , A0> > {}; }}} namespace hpx { namespace components { namespace server { template <typename Component, typename A0 , typename A1 , typename A2> naming::gid_type runtime_support::create_component3( A0 a0 , A1 a1 , A2 a2) { components::component_type const type = components::get_component_type< typename Component::wrapped_type>(); component_map_mutex_type::scoped_lock l(cm_mtx_); component_map_type::const_iterator it = components_.find(type); if (it == components_.end()) { hpx::util::osstream strm; strm << "attempt to create component instance of " << "invalid/unknown type: " << components::get_component_type_name(type) << " (component type not found in map)"; HPX_THROW_EXCEPTION(hpx::bad_component_type, "runtime_support::create_component", hpx::util::osstream_get_string(strm)); return naming::invalid_gid; } if (!(*it).second.first) { hpx::util::osstream strm; strm << "attempt to create component instance of " << "invalid/unknown type: " << components::get_component_type_name(type) << " (map entry is NULL)"; HPX_THROW_EXCEPTION(hpx::bad_component_type, "runtime_support::create_component", hpx::util::osstream_get_string(strm)); return naming::invalid_gid; } naming::gid_type id; boost::shared_ptr<component_factory_base> factory((*it).second.first); { util::scoped_unlock<component_map_mutex_type::scoped_lock> ul(l); id = factory->create_with_args( component_constructor_functor3< typename Component::wrapping_type, A0 , A1 , A2>( std::forward<A0>( a0 ) , std::forward<A1>( a1 ) , std::forward<A2>( a2 ))); } LRT_(info) << "successfully created component " << id << " of type: " << components::get_component_type_name(type); return id; } template <typename Component , typename A0 , typename A1 , typename A2> struct create_component_action3 : ::hpx::actions::action< naming::gid_type (runtime_support::*)(A0 , A1 , A2) , &runtime_support::create_component3< Component , A0 , A1 , A2> , create_component_action3< Component , A0 , A1 , A2> > {}; template <typename Component , typename A0 , typename A1 , typename A2> struct create_component_direct_action3 : ::hpx::actions::direct_action< naming::gid_type (runtime_support::*)(A0 , A1 , A2) , &runtime_support::create_component3< Component , A0 , A1 , A2> , create_component_direct_action3< Component , A0 , A1 , A2> > {}; template <typename Component, typename A0 , typename A1> std::vector<naming::gid_type> runtime_support::bulk_create_component3(std::size_t count, A0 a0 , A1 a1) { components::component_type const type = components::get_component_type< typename Component::wrapped_type>(); component_map_mutex_type::scoped_lock l(cm_mtx_); component_map_type::const_iterator it = components_.find(type); if (it == components_.end()) { hpx::util::osstream strm; strm << "attempt to create component(s) instance of " << "invalid/unknown type: " << components::get_component_type_name(type) << " (component type not found in map)"; HPX_THROW_EXCEPTION(hpx::bad_component_type, "runtime_support::create_component", hpx::util::osstream_get_string(strm)); return std::vector<naming::gid_type>(); } if (!(*it).second.first) { hpx::util::osstream strm; strm << "attempt to create component instance(s) of " << "invalid/unknown type: " << components::get_component_type_name(type) << " (map entry is NULL)"; HPX_THROW_EXCEPTION(hpx::bad_component_type, "runtime_support::create_component", hpx::util::osstream_get_string(strm)); return std::vector<naming::gid_type>(); } std::vector<naming::gid_type> ids; ids.reserve(count); boost::shared_ptr<component_factory_base> factory((*it).second.first); { util::scoped_unlock<component_map_mutex_type::scoped_lock> ul(l); for (std::size_t i = 0; i != count; ++i) { ids.push_back(factory->create_with_args( component_constructor_functor2< typename Component::wrapping_type, A0 , A1 >(std::forward<A0>( a0 ) , std::forward<A1>( a1 ))) ); } } LRT_(info) << "successfully created " << count << " component(s) of type: " << components::get_component_type_name(type); return std::move(ids); } template <typename Component , typename A0 , typename A1> struct bulk_create_component_action3 : ::hpx::actions::action< std::vector<naming::gid_type> (runtime_support::*)( std::size_t , A0 , A1) , &runtime_support::bulk_create_component3< Component , A0 , A1> , bulk_create_component_action3< Component , A0 , A1> > {}; template <typename Component , typename A0 , typename A1> struct bulk_create_component_direct_action3 : ::hpx::actions::direct_action< std::vector<naming::gid_type> (runtime_support::*)( std::size_t , A0 , A1) , &runtime_support::bulk_create_component3< Component , A0 , A1> , bulk_create_component_direct_action3< Component , A0 , A1> > {}; }}} namespace hpx { namespace components { namespace server { template <typename Component, typename A0 , typename A1 , typename A2 , typename A3> naming::gid_type runtime_support::create_component4( A0 a0 , A1 a1 , A2 a2 , A3 a3) { components::component_type const type = components::get_component_type< typename Component::wrapped_type>(); component_map_mutex_type::scoped_lock l(cm_mtx_); component_map_type::const_iterator it = components_.find(type); if (it == components_.end()) { hpx::util::osstream strm; strm << "attempt to create component instance of " << "invalid/unknown type: " << components::get_component_type_name(type) << " (component type not found in map)"; HPX_THROW_EXCEPTION(hpx::bad_component_type, "runtime_support::create_component", hpx::util::osstream_get_string(strm)); return naming::invalid_gid; } if (!(*it).second.first) { hpx::util::osstream strm; strm << "attempt to create component instance of " << "invalid/unknown type: " << components::get_component_type_name(type) << " (map entry is NULL)"; HPX_THROW_EXCEPTION(hpx::bad_component_type, "runtime_support::create_component", hpx::util::osstream_get_string(strm)); return naming::invalid_gid; } naming::gid_type id; boost::shared_ptr<component_factory_base> factory((*it).second.first); { util::scoped_unlock<component_map_mutex_type::scoped_lock> ul(l); id = factory->create_with_args( component_constructor_functor4< typename Component::wrapping_type, A0 , A1 , A2 , A3>( std::forward<A0>( a0 ) , std::forward<A1>( a1 ) , std::forward<A2>( a2 ) , std::forward<A3>( a3 ))); } LRT_(info) << "successfully created component " << id << " of type: " << components::get_component_type_name(type); return id; } template <typename Component , typename A0 , typename A1 , typename A2 , typename A3> struct create_component_action4 : ::hpx::actions::action< naming::gid_type (runtime_support::*)(A0 , A1 , A2 , A3) , &runtime_support::create_component4< Component , A0 , A1 , A2 , A3> , create_component_action4< Component , A0 , A1 , A2 , A3> > {}; template <typename Component , typename A0 , typename A1 , typename A2 , typename A3> struct create_component_direct_action4 : ::hpx::actions::direct_action< naming::gid_type (runtime_support::*)(A0 , A1 , A2 , A3) , &runtime_support::create_component4< Component , A0 , A1 , A2 , A3> , create_component_direct_action4< Component , A0 , A1 , A2 , A3> > {}; template <typename Component, typename A0 , typename A1 , typename A2> std::vector<naming::gid_type> runtime_support::bulk_create_component4(std::size_t count, A0 a0 , A1 a1 , A2 a2) { components::component_type const type = components::get_component_type< typename Component::wrapped_type>(); component_map_mutex_type::scoped_lock l(cm_mtx_); component_map_type::const_iterator it = components_.find(type); if (it == components_.end()) { hpx::util::osstream strm; strm << "attempt to create component(s) instance of " << "invalid/unknown type: " << components::get_component_type_name(type) << " (component type not found in map)"; HPX_THROW_EXCEPTION(hpx::bad_component_type, "runtime_support::create_component", hpx::util::osstream_get_string(strm)); return std::vector<naming::gid_type>(); } if (!(*it).second.first) { hpx::util::osstream strm; strm << "attempt to create component instance(s) of " << "invalid/unknown type: " << components::get_component_type_name(type) << " (map entry is NULL)"; HPX_THROW_EXCEPTION(hpx::bad_component_type, "runtime_support::create_component", hpx::util::osstream_get_string(strm)); return std::vector<naming::gid_type>(); } std::vector<naming::gid_type> ids; ids.reserve(count); boost::shared_ptr<component_factory_base> factory((*it).second.first); { util::scoped_unlock<component_map_mutex_type::scoped_lock> ul(l); for (std::size_t i = 0; i != count; ++i) { ids.push_back(factory->create_with_args( component_constructor_functor3< typename Component::wrapping_type, A0 , A1 , A2 >(std::forward<A0>( a0 ) , std::forward<A1>( a1 ) , std::forward<A2>( a2 ))) ); } } LRT_(info) << "successfully created " << count << " component(s) of type: " << components::get_component_type_name(type); return std::move(ids); } template <typename Component , typename A0 , typename A1 , typename A2> struct bulk_create_component_action4 : ::hpx::actions::action< std::vector<naming::gid_type> (runtime_support::*)( std::size_t , A0 , A1 , A2) , &runtime_support::bulk_create_component4< Component , A0 , A1 , A2> , bulk_create_component_action4< Component , A0 , A1 , A2> > {}; template <typename Component , typename A0 , typename A1 , typename A2> struct bulk_create_component_direct_action4 : ::hpx::actions::direct_action< std::vector<naming::gid_type> (runtime_support::*)( std::size_t , A0 , A1 , A2) , &runtime_support::bulk_create_component4< Component , A0 , A1 , A2> , bulk_create_component_direct_action4< Component , A0 , A1 , A2> > {}; }}} namespace hpx { namespace components { namespace server { template <typename Component, typename A0 , typename A1 , typename A2 , typename A3 , typename A4> naming::gid_type runtime_support::create_component5( A0 a0 , A1 a1 , A2 a2 , A3 a3 , A4 a4) { components::component_type const type = components::get_component_type< typename Component::wrapped_type>(); component_map_mutex_type::scoped_lock l(cm_mtx_); component_map_type::const_iterator it = components_.find(type); if (it == components_.end()) { hpx::util::osstream strm; strm << "attempt to create component instance of " << "invalid/unknown type: " << components::get_component_type_name(type) << " (component type not found in map)"; HPX_THROW_EXCEPTION(hpx::bad_component_type, "runtime_support::create_component", hpx::util::osstream_get_string(strm)); return naming::invalid_gid; } if (!(*it).second.first) { hpx::util::osstream strm; strm << "attempt to create component instance of " << "invalid/unknown type: " << components::get_component_type_name(type) << " (map entry is NULL)"; HPX_THROW_EXCEPTION(hpx::bad_component_type, "runtime_support::create_component", hpx::util::osstream_get_string(strm)); return naming::invalid_gid; } naming::gid_type id; boost::shared_ptr<component_factory_base> factory((*it).second.first); { util::scoped_unlock<component_map_mutex_type::scoped_lock> ul(l); id = factory->create_with_args( component_constructor_functor5< typename Component::wrapping_type, A0 , A1 , A2 , A3 , A4>( std::forward<A0>( a0 ) , std::forward<A1>( a1 ) , std::forward<A2>( a2 ) , std::forward<A3>( a3 ) , std::forward<A4>( a4 ))); } LRT_(info) << "successfully created component " << id << " of type: " << components::get_component_type_name(type); return id; } template <typename Component , typename A0 , typename A1 , typename A2 , typename A3 , typename A4> struct create_component_action5 : ::hpx::actions::action< naming::gid_type (runtime_support::*)(A0 , A1 , A2 , A3 , A4) , &runtime_support::create_component5< Component , A0 , A1 , A2 , A3 , A4> , create_component_action5< Component , A0 , A1 , A2 , A3 , A4> > {}; template <typename Component , typename A0 , typename A1 , typename A2 , typename A3 , typename A4> struct create_component_direct_action5 : ::hpx::actions::direct_action< naming::gid_type (runtime_support::*)(A0 , A1 , A2 , A3 , A4) , &runtime_support::create_component5< Component , A0 , A1 , A2 , A3 , A4> , create_component_direct_action5< Component , A0 , A1 , A2 , A3 , A4> > {}; template <typename Component, typename A0 , typename A1 , typename A2 , typename A3> std::vector<naming::gid_type> runtime_support::bulk_create_component5(std::size_t count, A0 a0 , A1 a1 , A2 a2 , A3 a3) { components::component_type const type = components::get_component_type< typename Component::wrapped_type>(); component_map_mutex_type::scoped_lock l(cm_mtx_); component_map_type::const_iterator it = components_.find(type); if (it == components_.end()) { hpx::util::osstream strm; strm << "attempt to create component(s) instance of " << "invalid/unknown type: " << components::get_component_type_name(type) << " (component type not found in map)"; HPX_THROW_EXCEPTION(hpx::bad_component_type, "runtime_support::create_component", hpx::util::osstream_get_string(strm)); return std::vector<naming::gid_type>(); } if (!(*it).second.first) { hpx::util::osstream strm; strm << "attempt to create component instance(s) of " << "invalid/unknown type: " << components::get_component_type_name(type) << " (map entry is NULL)"; HPX_THROW_EXCEPTION(hpx::bad_component_type, "runtime_support::create_component", hpx::util::osstream_get_string(strm)); return std::vector<naming::gid_type>(); } std::vector<naming::gid_type> ids; ids.reserve(count); boost::shared_ptr<component_factory_base> factory((*it).second.first); { util::scoped_unlock<component_map_mutex_type::scoped_lock> ul(l); for (std::size_t i = 0; i != count; ++i) { ids.push_back(factory->create_with_args( component_constructor_functor4< typename Component::wrapping_type, A0 , A1 , A2 , A3 >(std::forward<A0>( a0 ) , std::forward<A1>( a1 ) , std::forward<A2>( a2 ) , std::forward<A3>( a3 ))) ); } } LRT_(info) << "successfully created " << count << " component(s) of type: " << components::get_component_type_name(type); return std::move(ids); } template <typename Component , typename A0 , typename A1 , typename A2 , typename A3> struct bulk_create_component_action5 : ::hpx::actions::action< std::vector<naming::gid_type> (runtime_support::*)( std::size_t , A0 , A1 , A2 , A3) , &runtime_support::bulk_create_component5< Component , A0 , A1 , A2 , A3> , bulk_create_component_action5< Component , A0 , A1 , A2 , A3> > {}; template <typename Component , typename A0 , typename A1 , typename A2 , typename A3> struct bulk_create_component_direct_action5 : ::hpx::actions::direct_action< std::vector<naming::gid_type> (runtime_support::*)( std::size_t , A0 , A1 , A2 , A3) , &runtime_support::bulk_create_component5< Component , A0 , A1 , A2 , A3> , bulk_create_component_direct_action5< Component , A0 , A1 , A2 , A3> > {}; }}}
42.100141
149
0.564341
Titzi90
5016487a04e535553fb0fcd059cfc77f97a18abe
1,275
cpp
C++
dmoj/tsoc/15c1#5-giant-ants.cpp
ruar18/competitive-programming
f264675fab92bf27dce184dd65eb81e302381f96
[ "MIT" ]
null
null
null
dmoj/tsoc/15c1#5-giant-ants.cpp
ruar18/competitive-programming
f264675fab92bf27dce184dd65eb81e302381f96
[ "MIT" ]
null
null
null
dmoj/tsoc/15c1#5-giant-ants.cpp
ruar18/competitive-programming
f264675fab92bf27dce184dd65eb81e302381f96
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstring> using namespace std; bool adj[101][101], vis[101]; int n, m, w, x, y, curw, ants[101], q[101], f, b, dists[101]; void a_bfs(int disp){ f=b=0; q[++b]=disp; vis[disp]=1; ants[disp]=0; while(f!=b){ curw=q[++f]; for(int i=1;i<=n;i++){ if(adj[curw][i]&&!vis[i]&&ants[curw]+4<ants[i]){ ants[i]=ants[curw]+4; vis[i]=1; q[++b]=i; } } } } int main(){ scanf("%d%d", &n, &m); for(int i=0;i<m;i++){ scanf("%d%d", &x, &y); adj[x][y]=1; adj[y][x]=1; } memset(ants, 0x3f, sizeof(ants)); scanf("%d", &w); for(int i=0;i<w;i++){ memset(vis, 0, sizeof(vis)); scanf("%d", &curw); a_bfs(curw); } // their bfs f=b=0; memset(vis,0,sizeof(vis)); q[++b]=1; vis[1]=1; dists[1]=0; while(f!=b && curw!=n){ curw=q[++f]; for(int i=0;i<=n;i++){ if(adj[curw][i]&&!vis[i]&&dists[curw]+1<ants[i]){ vis[i]=1; dists[i]=dists[curw]+1; q[++b]=i; } } } if(vis[n]) printf("%d\n", dists[n]); else printf("sacrifice bobhob314\n"); return 0; }
22.368421
61
0.410196
ruar18
501bd61115d03861a468c2f3e5a8882e1ac600df
3,341
cpp
C++
DFNs/Executors/PointCloudAssembly/PointCloudAssemblyExecutor.cpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
7
2019-02-26T15:09:50.000Z
2021-09-30T07:39:01.000Z
DFNs/Executors/PointCloudAssembly/PointCloudAssemblyExecutor.cpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
null
null
null
DFNs/Executors/PointCloudAssembly/PointCloudAssemblyExecutor.cpp
H2020-InFuse/cdff
e55fd48f9a909d0c274c3dfa4fe2704bc5071542
[ "BSD-2-Clause" ]
1
2020-12-06T12:09:05.000Z
2020-12-06T12:09:05.000Z
/** * @addtogroup DFNs * @{ */ #include "PointCloudAssemblyExecutor.hpp" #include <Errors/Assert.hpp> using namespace PointCloudWrapper; using namespace PoseWrapper; namespace CDFF { namespace DFN { namespace Executors { void Execute(PointCloudAssemblyInterface* dfn, PointCloudConstPtr inputFirstCloud, PointCloudConstPtr inputSecondCloud, PointCloudConstPtr& outputAssembledCloud) { Execute(dfn, *inputFirstCloud, *inputSecondCloud, outputAssembledCloud); } void Execute(PointCloudAssemblyInterface* dfn, PointCloudConstPtr inputFirstCloud, PointCloudConstPtr inputSecondCloud, PointCloudPtr outputAssembledCloud) { ASSERT(outputAssembledCloud != NULL, "PointCloudAssemblyExecutor, Calling NO instance creation Executor with a NULL pointer"); Execute(dfn, *inputFirstCloud, *inputSecondCloud, *outputAssembledCloud); } void Execute(PointCloudAssemblyInterface* dfn, const PointCloud& inputFirstCloud, const PointCloud& inputSecondCloud, PointCloudConstPtr& outputAssembledCloud) { ASSERT( dfn!= NULL, "PointCloudAssemblyExecutor, input dfn is null"); ASSERT( outputAssembledCloud == NULL, "PointCloudAssemblyExecutor, Calling instance creation executor with a non-NULL pointer"); dfn->firstPointCloudInput(inputFirstCloud); dfn->secondPointCloudInput(inputSecondCloud); dfn->process(); outputAssembledCloud = & ( dfn->assembledCloudOutput() ); } void Execute(PointCloudAssemblyInterface* dfn, const PointCloud& inputFirstCloud, const PointCloud& inputSecondCloud, PointCloud& outputAssembledCloud) { ASSERT( dfn!= NULL, "PointCloudAssemblyExecutor, input dfn is null"); dfn->firstPointCloudInput(inputFirstCloud); dfn->secondPointCloudInput(inputSecondCloud); dfn->process(); Copy( dfn->assembledCloudOutput(), outputAssembledCloud); } void Execute(PointCloudAssemblyInterface* dfn, PointCloudConstPtr cloud, Pose3DConstPtr viewCenter, float viewRadius, PointCloudConstPtr& outputAssembledCloud) { Execute(dfn, *cloud, *viewCenter, viewRadius, outputAssembledCloud); } void Execute(PointCloudAssemblyInterface* dfn, PointCloudConstPtr cloud, Pose3DConstPtr viewCenter, float viewRadius, PointCloudPtr outputAssembledCloud) { ASSERT(outputAssembledCloud != NULL, "PointCloudAssemblyExecutor, Calling NO instance creation Executor with a NULL pointer"); Execute(dfn, *cloud, *viewCenter, viewRadius, *outputAssembledCloud); } void Execute(PointCloudAssemblyInterface* dfn, const PointCloud& cloud, const Pose3D& viewCenter, float viewRadius, PointCloudConstPtr& outputAssembledCloud) { ASSERT( dfn!= NULL, "PointCloudAssemblyExecutor, input dfn is null"); ASSERT( outputAssembledCloud == NULL, "PointCloudAssemblyExecutor, Calling instance creation executor with a non-NULL pointer"); dfn->firstPointCloudInput(cloud); dfn->viewCenterInput(viewCenter); dfn->viewRadiusInput(viewRadius); dfn->process(); outputAssembledCloud = & ( dfn->assembledCloudOutput() ); } void Execute(PointCloudAssemblyInterface* dfn, const PointCloud& cloud, const Pose3D& viewCenter, float viewRadius, PointCloud& outputAssembledCloud) { ASSERT( dfn!= NULL, "PointCloudAssemblyExecutor, input dfn is null"); dfn->firstPointCloudInput(cloud); dfn->viewCenterInput(viewCenter); dfn->viewRadiusInput(viewRadius); dfn->process(); Copy( dfn->assembledCloudOutput(), outputAssembledCloud); } } } } /** @} */
38.848837
161
0.801856
H2020-InFuse
501f4233dcde1397cabe9612e0263a254128a2b8
638
cpp
C++
recursion/backtracking/permutations.cpp
Zim95/cpp_proj
b73781be17e818fc778320a7498dc4d021b92ffa
[ "MIT" ]
2
2019-04-22T11:04:59.000Z
2021-03-01T18:32:25.000Z
recursion/backtracking/permutations.cpp
Zim95/cpp_proj
b73781be17e818fc778320a7498dc4d021b92ffa
[ "MIT" ]
null
null
null
recursion/backtracking/permutations.cpp
Zim95/cpp_proj
b73781be17e818fc778320a7498dc4d021b92ffa
[ "MIT" ]
1
2019-04-18T14:04:38.000Z
2019-04-18T14:04:38.000Z
/* PERMUTATIONS: ============= Main string: "abc" Find all options ------------------ abc acb cab cba abc acb */ #include<iostream> using namespace std; void permutations(char *ip, int i) { if(ip[i]=='\0'){ cout << ip << endl; return; } for(int j=i; ip[j]!='\0'; j++) { swap(ip[i], ip[j]); permutations(ip, i+1); // Backtracking swap(ip[i], ip[j]); // Without this the array wont reset. // And we will have repeated permutation sets. } } int main(){ char input[] = "abc"; permutations(input, 0); return 0; }
17.722222
65
0.479624
Zim95
5024831d3d161954153b67e2b1a317c37d7d0b5f
603
cpp
C++
Difficulty 1000/Absent_Remainder.cpp
desmondweh29/A-Problem-A-Day
135b21d21d74e6c716c9f7e36e8fa3a216f02727
[ "MIT" ]
null
null
null
Difficulty 1000/Absent_Remainder.cpp
desmondweh29/A-Problem-A-Day
135b21d21d74e6c716c9f7e36e8fa3a216f02727
[ "MIT" ]
null
null
null
Difficulty 1000/Absent_Remainder.cpp
desmondweh29/A-Problem-A-Day
135b21d21d74e6c716c9f7e36e8fa3a216f02727
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // Question: https://codeforces.com/problemset/problem/1613/B void solve() { int n; cin >> n; vector<long long> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a.begin(), a.end()); long long limit = n / 2; long long count = 0; int index = 1; while (count < limit) { cout << a[index] << " " << a[0] << "\n"; count++; index++; } } int main() { ios::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while (t--) { solve(); } }
15.461538
61
0.451078
desmondweh29
50255f96f50978d84ae0db8e6c37c107df54d281
6,154
cpp
C++
src/json_parser.cpp
chadvoegele/ledger-rest
23a920a57964c9f7e987c5d2d9f72eba3dc89c1e
[ "BSD-3-Clause" ]
null
null
null
src/json_parser.cpp
chadvoegele/ledger-rest
23a920a57964c9f7e987c5d2d9f72eba3dc89c1e
[ "BSD-3-Clause" ]
null
null
null
src/json_parser.cpp
chadvoegele/ledger-rest
23a920a57964c9f7e987c5d2d9f72eba3dc89c1e
[ "BSD-3-Clause" ]
null
null
null
// // Copyright (c) 2015-2020 Chad Voegele // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // * The name of Chad Voegele may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #include "json_parser.h" #include <sstream> #include <cstring> namespace ledger_rest { std::string trim_whitespace(std::string s) { std::stringstream ss; bool in_quote = false; for (auto iter = s.cbegin(); iter != s.cend(); iter++) { if (in_quote || (*iter != ' ' && *iter != '\n' && *iter != '\t')) { ss << *iter; } if (*iter == '"') { in_quote = !in_quote; } } std::string trimmed = ss.str(); return trimmed; } std::optional<std::string> parse_json_string(std::string& working_json) { if (working_json.length() == 0) { return {}; } if (working_json.at(0) != '"') { return {}; } working_json.erase(0, 1); // " std::string::size_type end_quote_position = working_json.find('"'); if (end_quote_position == std::string::npos) { return {}; } std::string arg; arg = working_json.substr(0, end_quote_position); working_json.erase(0, end_quote_position); // the string working_json.erase(0, 1); // " return arg; } std::optional<std::list<std::string>> parse_json_array_of_strings( std::string& working_json) { if (working_json.length() == 0) { return {}; } // []... // ["test"]... // ["test","test2"]... // ["test","test2","test3"]... if (working_json.at(0) != '[') { return {}; } working_json.erase(0, 1); // [ std::list<std::string> list; auto s = parse_json_string(working_json); while (s) { list.push_back(s.value()); if (working_json.at(0) == ',') { working_json.erase(0, 1); } s = parse_json_string(working_json); } if (working_json.length() == 0) { return {}; } if (working_json.at(0) != ']') { return {}; } working_json.erase(0, 1); // ] return list; } std::optional<std::pair<std::string,std::list<std::string>>> parse_json_key_object( std::string& working_json) { if (working_json.length() == 0) { return {}; } auto key = parse_json_string(working_json); if (working_json.length() > 0 && working_json.at(0) != ':') { return {}; } working_json.erase(0, 1); // : auto args = parse_json_array_of_strings(working_json); if (key && args) { return std::make_pair(key.value(), args.value()); } else { return {}; } } std::optional<std::unordered_map<std::string, std::list<std::string>>> parse_json_object_of_arrays_of_strings(std::string& working_json) { if (working_json.length() == 0) { return {}; } if (working_json.at(0) != '{') { return {}; } working_json.erase(0, 1); // { std::unordered_map<std::string, std::list<std::string>> req; auto keyObject = parse_json_key_object(working_json); while (keyObject) { auto key = std::get<0>(keyObject.value()); auto args = std::get<1>(keyObject.value()); req[key] = args; if (working_json.at(0) == ',') { working_json.erase(0, 1); } keyObject = parse_json_key_object(working_json); } if (working_json.length() == 0) { return {}; } if (working_json.at(0) != '}') { return {}; } working_json.erase(0, 1); // } return req; } std::optional<std::list<std::unordered_map<std::string,std::list<std::string>>>> parse_json_array_of_object_of_arrays_of_strings(std::string& working_json) { if (working_json.length() == 0) { return {}; } if (working_json.at(0) != '[') { return {}; } working_json.erase(0, 1); // [ std::list<std::unordered_map<std::string,std::list<std::string>>> array; auto obj = parse_json_object_of_arrays_of_strings(working_json); while (obj) { array.push_back(obj.value()); if (working_json.at(0) == ',') { working_json.erase(0, 1); } obj = parse_json_object_of_arrays_of_strings(working_json); } if (working_json.length() == 0) { return {}; } if (working_json.at(0) != ']') { return {}; } working_json.erase(0, 1); // ] return array; } std::list<std::unordered_map<std::string, std::list<std::string>>> parse_register_request_json(std::string json) { std::string working_json = trim_whitespace(json); auto data = parse_json_array_of_object_of_arrays_of_strings(working_json); if (data) { return data.value(); } else { std::list<std::unordered_map<std::string, std::list<std::string>>> empty; return empty; } } }
26.640693
85
0.612447
chadvoegele
df2250eb838bca9df50a05972285f4e81f4b63a9
1,527
cpp
C++
new_software/microcontroller/RetractMode.cpp
feklee/stm
ad08964db80819fb3b0415d3840178a077554c94
[ "WTFPL" ]
10
2016-06-26T14:19:38.000Z
2021-11-17T11:40:21.000Z
new_software/microcontroller/RetractMode.cpp
feklee/stm
ad08964db80819fb3b0415d3840178a077554c94
[ "WTFPL" ]
4
2015-11-17T11:46:52.000Z
2016-01-18T21:33:38.000Z
new_software/microcontroller/RetractMode.cpp
feklee/stm
ad08964db80819fb3b0415d3840178a077554c94
[ "WTFPL" ]
5
2017-06-01T00:33:45.000Z
2020-12-31T23:19:10.000Z
#include <Arduino.h> #include "util.hpp" #include "RetractMode.hpp" RetractMode::RetractMode(Motor &motor, BiasVoltage &biasVoltage, Current &current, Piezo &piezo, TipPositionLog &tipPositionLog) : motor_(motor), biasVoltage_(biasVoltage), current_(current), piezo_(piezo), tipPositionLog_(tipPositionLog) {} const char *RetractMode::name() { return "retract"; } bool RetractMode::rotateMotor( int steps, uint16_t targetSignal = 0, // 0xffff/3.3 V bool stopAtTarget = false ) { for (int i = 0; i < steps; i ++) { motor_.stepUp(); current_.measure(); tipPositionLog_.add(0, 0, 0, current_.signal()); if (stopAtTarget && current_.signal() <= targetSignal) { return true; } } return false; } void RetractMode::retract( int steps ) { motor_.activate(); rotateMotor(steps); motor_.deactivate(); } bool RetractMode::retractToTarget( int steps, uint16_t targetSignal // 0xffff/3.3 V ) { motor_.activate(); bool targetSignalReached = rotateMotor(steps, targetSignal, true); motor_.deactivate(); return targetSignalReached; } void RetractMode::finish() { retract(250); tipPositionLog_.flush(); } bool RetractMode::step() { piezo_.displace(0); bool targetSignalReached = retractToTarget(500, targetSignal_); if (targetSignalReached) { finish(); return false; } return true; } void RetractMode::setTargetSignal( float targetSignal // V ) { targetSignal_ = integerFromVolt(targetSignal); }
22.130435
68
0.67649
feklee
df22633e656698b53985442f5866bf137c77baa9
10,578
cpp
C++
src/utils/inet_pton.cpp
neheb/npupnp
d00aaf2c5af8b9453cda32f9ed3981d49ef1d01c
[ "BSD-3-Clause" ]
null
null
null
src/utils/inet_pton.cpp
neheb/npupnp
d00aaf2c5af8b9453cda32f9ed3981d49ef1d01c
[ "BSD-3-Clause" ]
null
null
null
src/utils/inet_pton.cpp
neheb/npupnp
d00aaf2c5af8b9453cda32f9ed3981d49ef1d01c
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 1996-1999 by Internet Software Consortium. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. */ #include "autoconfig.h" #ifndef HAVE_INET_PTON #include <stdio.h> #include "UpnpInet.h" #include "inet_pton.h" /* For upnp_strlcpy */ #include "genut.h" /*% * WARNING: Don't even consider trying to compile this on a system where * sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX. */ static char *inet_ntop4(const unsigned char *src, char *dst, socklen_t size); static char *inet_ntop6(const unsigned char *src, char *dst, socklen_t size); /* const char *inet_ntop(af, src, dst, size) * convert a network format address to presentation format. * return: * pointer to presentation format address (`dst'), or NULL (see errno). * author: * Paul Vixie, 1996. */ const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) { switch (af) { case AF_INET: return (inet_ntop4((const unsigned char*)src, dst, size)); case AF_INET6: return (inet_ntop6((const unsigned char*)src, dst, size)); default: return (NULL); } /* NOTREACHED */ } /* const char *inet_ntop4(src, dst, size) * format an IPv4 address * return: * `dst' (as a const) * notes: * (1) uses no statics * (2) takes a u_char* not an in_addr as input * author: * Paul Vixie, 1996. */ static char *inet_ntop4(const unsigned char *src, char *dst, socklen_t size) { static const char fmt[] = "%u.%u.%u.%u"; char tmp[sizeof "255.255.255.255"]; int l; l = snprintf(tmp, sizeof(tmp), fmt, src[0], src[1], src[2], src[3]); if (l <= 0 || (socklen_t) l >= size) { return (NULL); } upnp_strlcpy(dst, tmp, size); return (dst); } /* const char *inet_ntop6(src, dst, size) * convert IPv6 binary address into presentation (printable) format * author: * Paul Vixie, 1996. */ static char *inet_ntop6(const unsigned char *src, char *dst, socklen_t size) { /* * Note that int32_t and int16_t need only be "at least" large enough * to contain a value of the specified size. On some systems, like * Crays, there is no such thing as an integer variable with 16 bits. * Keep this in mind if you think this function should have been coded * to use pointer overlays. All the world's not a VAX. */ char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"], *tp; struct { int base, len; } best, cur; #define NS_IN6ADDRSZ 16 #define NS_INT16SZ 2 u_int words[NS_IN6ADDRSZ / NS_INT16SZ]; int i; /* * Preprocess: * Copy the input (bytewise) array into a wordwise array. * Find the longest run of 0x00's in src[] for :: shorthanding. */ memset(words, '\0', sizeof words); for (i = 0; i < NS_IN6ADDRSZ; i++) words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3)); best.base = -1; best.len = 0; cur.base = -1; cur.len = 0; for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) { if (words[i] == 0) { if (cur.base == -1) cur.base = i, cur.len = 1; else cur.len++; } else { if (cur.base != -1) { if (best.base == -1 || cur.len > best.len) best = cur; cur.base = -1; } } } if (cur.base != -1) { if (best.base == -1 || cur.len > best.len) best = cur; } if (best.base != -1 && best.len < 2) best.base = -1; /* * Format the result. */ tp = tmp; for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) { /* Are we inside the best run of 0x00's? */ if (best.base != -1 && i >= best.base && i < (best.base + best.len)) { if (i == best.base) *tp++ = ':'; continue; } /* Are we following an initial run of 0x00s or any real hex? */ if (i != 0) *tp++ = ':'; /* Is this address an encapsulated IPv4? */ if (i == 6 && best.base == 0 && (best.len == 6 || (best.len == 7 && words[7] != 0x0001) || (best.len == 5 && words[5] == 0xffff))) { if (!inet_ntop4(src+12, tp, sizeof tmp - (tp - tmp))) return (NULL); tp += strlen(tp); break; } tp += sprintf(tp, "%x", words[i]); } /* Was it a trailing run of 0x00's? */ if (best.base != -1 && (best.base + best.len) == (NS_IN6ADDRSZ / NS_INT16SZ)) *tp++ = ':'; *tp++ = '\0'; /* * Check for overflow, copy, and we're done. */ if ((socklen_t)(tp - tmp) > size) { return (NULL); } strcpy(dst, tmp); return (dst); } /* * WARNING: Don't even consider trying to compile this on a system where * sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX. */ static int inet_pton4(const char *src, u_char *dst); static int inet_pton6(const char *src, u_char *dst); /* int * inet_pton(af, src, dst) * convert from presentation format (which usually means ASCII printable) * to network format (which is usually some kind of binary format). * return: * 1 if the address was valid for the specified address family * 0 if the address wasn't valid (`dst' is untouched in this case) * -1 if some other error occurred (`dst' is untouched in this case, too) * author: * Paul Vixie, 1996. */ int inet_pton(int af, const char *src, void *dst) { switch (af) { case AF_INET: return (inet_pton4(src, (unsigned char *)dst)); case AF_INET6: return (inet_pton6(src, (unsigned char *)dst)); default: return (-1); } /* NOTREACHED */ } /* int * inet_pton4(src, dst) * like inet_aton() but without all the hexadecimal and shorthand. * return: * 1 if `src' is a valid dotted quad, else 0. * notice: * does not touch `dst' unless it's returning 1. * author: * Paul Vixie, 1996. */ static int inet_pton4(const char *src, u_char *dst) { static const char digits[] = "0123456789"; int saw_digit, octets, ch; #define NS_INADDRSZ 4 u_char tmp[NS_INADDRSZ], *tp; saw_digit = 0; octets = 0; *(tp = tmp) = 0; while ((ch = *src++) != '\0') { const char *pch; if ((pch = strchr(digits, ch)) != NULL) { u_int uiNew = *tp * 10 + (pch - digits); if (saw_digit && *tp == 0) return (0); if (uiNew > 255) return (0); *tp = uiNew; if (!saw_digit) { if (++octets > 4) return (0); saw_digit = 1; } } else if (ch == '.' && saw_digit) { if (octets == 4) return (0); *++tp = 0; saw_digit = 0; } else return (0); } if (octets < 4) return (0); memcpy(dst, tmp, NS_INADDRSZ); return (1); } /* int * inet_pton6(src, dst) * convert presentation level address to network order binary form. * return: * 1 if `src' is a valid [RFC1884 2.2] address, else 0. * notice: * (1) does not touch `dst' unless it's returning 1. * (2) :: in a full address is silently ignored. * credit: * inspired by Mark Andrews. * author: * Paul Vixie, 1996. */ static int inet_pton6(const char *src, u_char *dst) { static const char xdigits_l[] = "0123456789abcdef", xdigits_u[] = "0123456789ABCDEF"; #define NS_IN6ADDRSZ 16 #define NS_INT16SZ 2 u_char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp; const char *xdigits, *curtok; int ch, seen_xdigits; u_int val; memset((tp = tmp), '\0', NS_IN6ADDRSZ); endp = tp + NS_IN6ADDRSZ; colonp = NULL; /* Leading :: requires some special handling. */ if (*src == ':') if (*++src != ':') return (0); curtok = src; seen_xdigits = 0; val = 0; while ((ch = *src++) != '\0') { const char *pch; if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL) pch = strchr((xdigits = xdigits_u), ch); if (pch != NULL) { val <<= 4; val |= (pch - xdigits); if (++seen_xdigits > 4) return (0); continue; } if (ch == ':') { curtok = src; if (!seen_xdigits) { if (colonp) return (0); colonp = tp; continue; } else if (*src == '\0') { return (0); } if (tp + NS_INT16SZ > endp) return (0); *tp++ = (u_char) (val >> 8) & 0xff; *tp++ = (u_char) val & 0xff; seen_xdigits = 0; val = 0; continue; } if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) && inet_pton4(curtok, tp) > 0) { tp += NS_INADDRSZ; seen_xdigits = 0; break; /*%< '\\0' was seen by inet_pton4(). */ } return (0); } if (seen_xdigits) { if (tp + NS_INT16SZ > endp) return (0); *tp++ = (u_char) (val >> 8) & 0xff; *tp++ = (u_char) val & 0xff; } if (colonp != NULL) { /* * Since some memmove()'s erroneously fail to handle * overlapping regions, we'll do the shift by hand. */ const int n = tp - colonp; int i; if (tp == endp) return (0); for (i = 1; i <= n; i++) { endp[- i] = colonp[n - i]; colonp[n - i] = 0; } tp = endp; } if (tp != endp) return (0); memcpy(dst, tmp, NS_IN6ADDRSZ); return (1); } #endif /* !HAVE_INET_PTON */
29.383333
80
0.531386
neheb
df24ce1bdfa1b5f2653f883ef2207256a13be241
15,857
cpp
C++
kernel/drivers/tty.cpp
ethan4984/rock
751b9af1009b622bedf384c1f80970b333c436c3
[ "BSD-2-Clause" ]
207
2020-05-27T21:57:28.000Z
2022-02-26T15:17:27.000Z
kernel/drivers/tty.cpp
ethan4984/crepOS
751b9af1009b622bedf384c1f80970b333c436c3
[ "BSD-2-Clause" ]
3
2020-07-26T18:14:05.000Z
2020-12-09T05:32:07.000Z
kernel/drivers/tty.cpp
ethan4984/rock
751b9af1009b622bedf384c1f80970b333c436c3
[ "BSD-2-Clause" ]
17
2020-07-05T19:08:48.000Z
2021-10-13T12:30:13.000Z
#include <drivers/tty.hpp> #include <mm/vmm.hpp> #include <fs/vfs.hpp> #include <debug.hpp> #include <fs/dev.hpp> namespace tty { static size_t tty_cnt = 0; static uint32_t ansi_colours[] = { 0, // black 0xff3333, // red 0x46ff33, // green 0xa52a2a, // brown 0x3f33ff, // blue 0xfc33ff, // magenta 0x33a8ff, // cyan 0xc1bdc2 // grey }; screen::screen(stivale *stivale_struct) { framebuffer = reinterpret_cast<volatile uint32_t*>(stivale_struct->fb_addr + vmm::high_vma); height = stivale_struct->fb_height; width = stivale_struct->fb_width; pitch = stivale_struct->fb_pitch; bpp = stivale_struct->fb_bpp; size = height * pitch; double_buffer = reinterpret_cast<volatile uint32_t*>(pmm::calloc(div_roundup(size, vmm::page_size)) + vmm::high_vma); size_t fb_page_off = stivale_struct->fb_addr / vmm::page_size; for(ssize_t i = 0; i < div_roundup(size, 0x200000); i++) { // map fb and double fb as wc vmm::kernel_mapping->map_page_raw(fb_page_off + vmm::high_vma + i * 0x200000, fb_page_off + i * 0x200000, 0x3, 0x3 | (1 << 7) | (1 << 8), vmm::pa_wc); vmm::kernel_mapping->map_page_raw((size_t)double_buffer + i * 0x200000, (size_t)double_buffer - vmm::high_vma + i * 0x200000, 0x3, 0x3 | (1 << 7) | (1 << 8), vmm::pa_wc); } } inline void screen::set_pixel(ssize_t x, ssize_t y, uint32_t colour) { size_t index = x + pitch / (bpp / 8) * y; framebuffer[index] = colour; double_buffer[index] = colour; } inline uint32_t screen::get_pixel(ssize_t x, ssize_t y) { return double_buffer[x + pitch / (bpp / 8) * y]; } void screen::flush(uint32_t colour) { for(size_t i = 0; i < height; i++) { for(size_t j = 0; j < width; j++) { set_pixel(j, i, colour); } } } void tty::render_char(ssize_t x, ssize_t y, uint32_t fg, uint32_t bg, char c) { uint16_t offset = ((uint8_t)c - 0x20) * font_height; for(uint8_t i = 0, i_cnt = 8; i < font_width && i_cnt > 0; i++, i_cnt--) { for(uint8_t j = 0; j < font_height; j++) { if((font[offset + j] >> i) & 1) sc.set_pixel(x + i_cnt, y + j, fg); else sc.set_pixel(x + i_cnt, y + j, bg); } } } void tty::plot_char(ssize_t x, ssize_t y, uint32_t fg, uint32_t bg, char c) { render_char(x * font_width, y * font_height, fg, bg, c); char_grid[x + y * cols] = c; } void tty::update_cursor(ssize_t x, ssize_t y) { clear_cursor(); cursor_x = x; cursor_y = y; draw_cursor(); } void tty::clear_cursor() { for(size_t i = 0; i < font_height; i++) { for(size_t j = 0; j < font_width; j++) { sc.set_pixel(j + cursor_x * font_width, i + cursor_y * font_height, text_background); } } } void tty::draw_cursor() { for(size_t i = 0; i < font_height; i++) { for(size_t j = 0; j < font_width; j++) { sc.set_pixel(j + cursor_x * font_width, i + cursor_y * font_height, cursor_foreground); } } } void tty::scroll() { clear_cursor(); for(ssize_t i = cols; i < rows * cols; i++) { char_grid[i - cols] = char_grid[i]; } for(ssize_t i = rows * cols - cols; i < rows * cols; i++) { char_grid[i] = 0; } memcpy64((uint64_t*)sc.framebuffer, (uint64_t*)sc.double_buffer + (sc.pitch * font_height) / 8, (sc.size - sc.pitch * font_height) / 8); memcpy64((uint64_t*)sc.double_buffer, (uint64_t*)sc.double_buffer + (sc.pitch * font_height) / 8, (sc.size - sc.pitch * font_height) / 8); memset32((uint32_t*)sc.framebuffer + (sc.size - sc.pitch * font_height) / 4, text_background, sc.pitch * font_height / 4); memset32((uint32_t*)sc.double_buffer + (sc.size - sc.pitch * font_height) / 4, text_background, sc.pitch * font_height / 4); draw_cursor(); } void ps2_keyboard([[maybe_unused]] regs *regs_cur, void*) { static char keymap[] = { '\0', '\0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', '\b', '\t', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\0', '\0', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'', '`', '\0', '\\', 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', '\0', '\0', '\0', ' ' }; static char cap_keymap[] = { '\0', '\e', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '\b', '\t', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', '\0', '\0', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', '\'', '~', '\0', '\\', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?', '\0', '\0', '\0', ' ' }; static bool upkey = false; uint8_t keycode = inb(0x60); switch(keycode) { case 0xaa: // left shift release upkey = false; break; case 0x2a: // left shift press upkey = true; break; case 0xf: // tab tty_list[current_tty]->putchar('\t'); break; case 0xe: // backspace tty_list[current_tty]->putchar('\b'); break; case 0x1c: // enter tty_list[current_tty]->putchar('\n'); break; default: if(keycode <= 128) { if(upkey) { tty_list[current_tty]->putchar(cap_keymap[keycode]); } else { tty_list[current_tty]->putchar(keymap[keycode]); } } } } bool console_code::validate(uint8_t c) { if(c >= '0' && c <= '9') { rrr = true; escape_grid[grid_index] *= 10; escape_grid[grid_index] += c - '0'; return false; } if(rrr) { grid_index++; rrr = false; if(c == ';') return false; } else if(c == ';') { escape_grid[grid_index++] = 1; return false; } for(auto i = grid_index; i < max_escape_size; i++) { escape_grid[i] = 1; } return true; } void console_code::add_character(uint8_t c) { if(!control_sequence) { if(c == '[') { memset8((uint8_t*)escape_grid, 0, sizeof(escape_grid)); grid_index = 0; rrr = false; control_sequence = true; } else { parent->escape = false; } return; } if(!validate(c)) return; switch(c) { case 'A': action_cuu(); break; case 'B': action_cud(); break; case 'C': action_cuf(); break; case 'D': action_cub(); break; case 'E': action_cnl(); break; case 'F': action_cpl(); break; case 'G': action_cha(); break; case 'H': action_cup(); break; case 'J': action_ed(); break; case 'f': action_cup(); break; case 'd': action_vpa(); break; case 'r': action_decstbm(); break; case 's': action_s(); break; case 'u': action_u(); break; case 'h': action_sm(); break; case 'l': action_rm(); break; case 'm': action_sgr(); break; case '`': action_cha(); break; case '?': dec_private_mode = true; } control_sequence = false; parent->escape = false; } console_code::console_code(tty *parent) : parent(parent) { rrr = false; decckm = false; control_sequence = false; dec_private_mode = false; memset8((uint8_t*)escape_grid, 0, sizeof(escape_grid)); grid_index = 0; saved_cursor_x = 0; saved_cursor_y = 0; scrolling_region_top = 0; scrolling_region_bottom = 0; } void console_code::action_cuu() { if(escape_grid[0] > parent->cursor_y) escape_grid[0] = parent->cursor_y; parent->update_cursor(parent->cursor_x, parent->cursor_y + escape_grid[0]); } void console_code::action_cud() { if((parent->cursor_y + escape_grid[0]) > (parent->rows - 1)) escape_grid[0] = (parent->rows - 1) - parent->cursor_y; parent->update_cursor(parent->cursor_x, parent->cursor_y + escape_grid[0]); } void console_code::action_cuf() { if((parent->cursor_x + escape_grid[0]) > (parent->cols - 1)) escape_grid[0] = (parent->cols - 1) - parent->cursor_x; parent->update_cursor(parent->cursor_x + escape_grid[0], parent->cursor_y); } void console_code::action_cub() { if(escape_grid[0] > parent->cursor_x) escape_grid[0] = parent->cursor_x; parent->update_cursor(parent->cursor_x - escape_grid[0], parent->cursor_y); } void console_code::action_cnl() { if(parent->cursor_y + escape_grid[0] >= parent->rows) parent->update_cursor(0, parent->rows - 1); else parent->update_cursor(0, parent->cursor_y + escape_grid[0]); } void console_code::action_cpl() { if(parent->cursor_y - escape_grid[0] < 0) parent->update_cursor(0, 0); else parent->update_cursor(0, parent->cursor_y - escape_grid[0]); } void console_code::action_cha() { if(escape_grid[0] >= parent->cols) return; parent->clear_cursor(); parent->cursor_x = escape_grid[0]; parent->draw_cursor(); } void console_code::action_ed() { switch(escape_grid[0]) { case 1: { parent->clear_cursor(); for(int i = 0; i < (parent->cursor_y * parent->cols + parent->cursor_x); i++) { parent->plot_char(i % parent->cols, i / parent->cols, parent->text_foreground, parent->text_background, ' '); } parent->draw_cursor(); break; } case 2: parent->clear(); } } void console_code::action_cup() { escape_grid[0] -= 1; escape_grid[1] -= 1; if(escape_grid[1] >= parent->cols) { escape_grid[1] = parent->cols - 1; } if(escape_grid[0] >= parent->rows) { escape_grid[0] = parent->rows - 1; } parent->update_cursor(escape_grid[1], escape_grid[0]); } void console_code::action_vpa() { if(escape_grid[0] >= parent->rows) return; parent->clear_cursor(); parent->cursor_y = escape_grid[0]; parent->draw_cursor(); } void console_code::action_decstbm() { scrolling_region_top = escape_grid[0]; scrolling_region_bottom = escape_grid[1]; } void console_code::action_s() { saved_cursor_x = parent->cursor_x; saved_cursor_y = parent->cursor_y; } void console_code::action_u() { parent->clear_cursor(); parent->cursor_x = saved_cursor_x; parent->cursor_y = saved_cursor_y; parent->draw_cursor(); } void console_code::action_sm() { if(dec_private_mode) { dec_private_mode = false; if(escape_grid[1] == 1) { decckm = true; } } } void console_code::action_rm() { if(dec_private_mode) { dec_private_mode = false; if(escape_grid[1] == 1) { decckm = false; } } } void console_code::action_sgr() { if(!grid_index) { parent->text_foreground = default_text_fg; parent->text_background = default_text_bg; return; } for(auto i = 0; i < grid_index; i++) { if(!escape_grid[i]) { parent->text_foreground = default_text_fg; parent->text_background = default_text_bg; } else { if(escape_grid[i] >= 30 && escape_grid[i] <= 37) { parent->text_foreground = ansi_colours[escape_grid[i] - 30]; } else if(escape_grid[i] >= 40 && escape_grid[i] <= 47) { parent->text_background = ansi_colours[escape_grid[i] - 40]; } } } } void tty::putchar(char c) { if(escape) { escape_sequence.add_character(c); return; } switch(c) { case '\n': if(cursor_y == (rows - 1)) { scroll(); update_cursor(0, rows - 1); } else { update_cursor(0, cursor_y + 1); } break; case '\r': update_cursor(0, cursor_y); break; case '\0': break; case '\b': if(cursor_x || cursor_y) { clear_cursor(); if(cursor_x) { cursor_x--; } else { cursor_y--; cursor_x = cols - 1; } draw_cursor(); } break; case '\e': escape = true; break; default: clear_cursor(); plot_char(cursor_x++, cursor_y, text_foreground, text_background, c); if(cursor_x == cols) { cursor_x = 0; cursor_y++; } if(cursor_y == rows) { cursor_y--; scroll(); } draw_cursor(); } last_char = c; new_key = true; } void tty::clear() { clear_cursor(); for(int i = 0; i < rows * cols; i++) { plot_char(i % cols, i / cols, text_foreground, text_background, ' '); } cursor_x = 0; cursor_y = 0; draw_cursor(); } int tty_ioctl::call(regs *regs_cur) { switch(regs_cur->rsi) { case tiocginsz: { winsize *win = reinterpret_cast<winsize*>(regs_cur->rdx); win->ws_row = tty_cur.rows; win->ws_col = tty_cur.cols; win->ws_xpixel = tty_cur.sc.width; win->ws_ypixel = tty_cur.sc.height; return 0; } } return -1; } int tty::raw_read([[maybe_unused]] vfs::node *vfs_node, [[maybe_unused]] off_t off, off_t cnt, void *buf) { char *buffer = (char*)buf; asm ("sti"); while(!new_key) { asm ("pause"); } buffer[0] = last_char; new_key = false; return cnt; } int tty::raw_write([[maybe_unused]] vfs::node *vfs_node, [[maybe_unused]] off_t off, off_t cnt, void *buf) { lib::string str((char*)buf, cnt); for(size_t i = 0; i < str.length(); i++) { putchar(str[i]); } return cnt; } int tty::raw_open([[maybe_unused]] vfs::node *vfs_node, [[maybe_unused]] uint16_t status) { return 0; } tty::tty(screen &sc, uint8_t *font, size_t font_height, size_t font_width) : font(font), font_height(font_height), font_width(font_width), sc(sc) { cursor_x = 0; cursor_y = 0; tab_size = default_tab_size; new_key = false; escape = false; cursor_foreground = default_cursor_fg; text_foreground = default_text_fg; text_background = default_text_bg; sc.flush(text_background); rows = sc.height / font_height; cols = sc.width / font_width; char_grid = (char*)kmm::calloc(rows * cols); draw_cursor(); current_tty = tty_cnt; escape_sequence = console_code(this); ioctl_device = new tty_ioctl(*this); tty_list[tty_cnt] = this; dev::root_cluster.generate_node(lib::string("tty"), this, s_iwusr | s_irusr, ioctl_device); } extern "C" void syscall_syslog(regs *regs_cur) { print("\e[32m"); lib::string message((char*)regs_cur->rdi); if(message[message.length() - 1] == '\n') message = lib::string((char*)regs_cur->rdi, message.length() - 1); print("{}\n", message); } }
27.198971
178
0.517185
ethan4984
df26ea23cbbb1d9c7fda9c77329756588040320c
650
hpp
C++
source/ui/rect.hpp
Stephouuu/Epitech-Bomberman
8650071a6a21ba2e0606e4d8e38794de37bdf39f
[ "Unlicense" ]
null
null
null
source/ui/rect.hpp
Stephouuu/Epitech-Bomberman
8650071a6a21ba2e0606e4d8e38794de37bdf39f
[ "Unlicense" ]
null
null
null
source/ui/rect.hpp
Stephouuu/Epitech-Bomberman
8650071a6a21ba2e0606e4d8e38794de37bdf39f
[ "Unlicense" ]
null
null
null
/* ** rect.hpp for UI in /home/escoba_j/class ** ** Made by Joffrey Escobar ** Login <escoba_j@epitech.net> ** ** Started on Sat May 21 01:35:13 2016 Joffrey Escobar */ #ifndef _RECT_HPP_ # define _RECT_HPP_ #include "IObject.hpp" class rect : public IObject { public: rect(const std::string& name); rect(const std::string & name, const irr::core::position2d<irr::s32> & pos, const irr::core::dimension2d<irr::s32>& dimension, const irr::video::SColor & color); ~rect(); /* method */ bool draw(irr::video::IVideoDriver *driver, const std::string &style = "default"); }; #endif
20.967742
84
0.621538
Stephouuu
df2f1dbf8b91de4d5edef744bab9a42d322ff1e1
3,639
cpp
C++
Game/src/game/BasicTower.cpp
franticsoftware/vlad-heavy-strike
a4da4df617e9ccd6ebd9819ad166d892924638ce
[ "MIT" ]
3
2019-10-04T19:44:44.000Z
2021-07-27T15:59:39.000Z
Game/src/game/BasicTower.cpp
franticsoftware/vlad-heavy-strike
a4da4df617e9ccd6ebd9819ad166d892924638ce
[ "MIT" ]
1
2019-07-20T05:36:31.000Z
2019-07-20T22:22:49.000Z
Game/src/game/BasicTower.cpp
aminere/vlad-heavy-strike
a4da4df617e9ccd6ebd9819ad166d892924638ce
[ "MIT" ]
null
null
null
/* Amine Rehioui Created: March 3rd 2013 */ #include "ShootTest.h" #include "BasicTower.h" #include "MeshEntity.h" namespace shoot { DEFINE_OBJECT(BasicTower); DEFINE_OBJECT(BasicTowerSettings); //! constructor BasicTowerSettings::BasicTowerSettings() : m_fAimDuration(1.5f) , m_fAimOffset(2.0f) , m_fFirstShotDelay(1.0f) , m_fBulletSpeed(15.0f) , m_fBulletLife(4.0f) , m_vBulletOffset(Vector3::Create(0.0f, 2.0f, 0.0f)) , m_fBulletSize(1.0f) , m_fBulletDamage(30.0f) { } //! serializes the entity to/from a PropertyStream void BasicTowerSettings::Serialize(PropertyStream& stream) { super::Serialize(stream); stream.Serialize(PT_Float, "AimDuration", &m_fAimDuration); stream.Serialize(PT_Float, "FirstShotDelay", &m_fFirstShotDelay); stream.Serialize(PT_Float, "BulletSpeed", &m_fBulletSpeed); stream.Serialize(PT_Float, "BulletLife", &m_fBulletLife); stream.Serialize(PT_Vec3, "BulletOffset", &m_vBulletOffset); stream.Serialize(PT_Float, "BulletSize", &m_fBulletSize); stream.Serialize(PT_Float, "BulletDamage", &m_fBulletDamage); } //! constructor BasicTower::BasicTower() : m_fFirstShotTimer(0.0f) , m_vKnownPlayerPos(Vector3::Zero) { } //! called during the initialization of the entity void BasicTower::Init() { super::Init(); if(BasicTowerSettings* pSettings = static_cast<BasicTowerSettings*>(m_Settings.Get())) { m_fFirstShotTimer = pSettings->m_fFirstShotDelay; } if(Player* pPlayer = Player::Instance()) { m_vKnownPlayerPos = pPlayer->GetMeshEntity()->GetTransformationMatrix().GetTranslation(); } m_Core = static_cast<Entity3D*>(GetChildByName("Core")); if(m_Core.IsValid()) { m_Core->SetUseRotationMatrix(true); } } //! called during the update of the entity void BasicTower::Update() { super::Update(); if(m_HitPoints < 0) { return; } Player* pPlayer = Player::Instance(); Vector3 vPosition = m_Core->GetTransformationMatrix().GetTranslation(); Vector3 vPlayerMeshPos = pPlayer->GetMeshEntity()->GetTransformationMatrix().GetTranslation(); if(vPosition.Y > vPlayerMeshPos.Y) { // aim BasicTowerSettings* pSettings = static_cast<BasicTowerSettings*>(m_Settings.Get()); Vector3 vAimPos = vPlayerMeshPos+Vector3::Create(0.0f, pSettings->m_fAimOffset, 0.0f); m_vKnownPlayerPos = Math::Damp(m_vKnownPlayerPos, vAimPos, g_fDeltaTime, pSettings->m_fAimDuration); Vector3 vDirection = (m_vKnownPlayerPos - vPosition).Normalize(); Matrix44 lookAt; Camera* p3DCamera = EntityRenderer::Instance()->Get3DCamera(); lookAt.BuildLookAtLH(Vector3::Zero, vDirection, Vector3::Create(0.0f, 0.0f, 1.0f)); Matrix44 invLookAt; if(lookAt.GetInverse(invLookAt)) { Matrix44 baseRotation; baseRotation.SetRotation(Vector3::Create(Math::PI/2.0f, 0.0f, 0.0f)); Matrix44 rotation = baseRotation*invLookAt; m_Core->SetRotationMatrix(rotation); // shoot if(!m_Timer.IsRunning() && m_fFirstShotTimer < 0.0f) { Bullet::BulletParams params; Vector3 vBulletOffset = pSettings->m_vBulletOffset*m_Mesh->GetScale().Y; Vector3 vBulletLocalPos = rotation.TransformVect(vBulletOffset); params.vPosition = vPosition + vBulletLocalPos; params.vDirection = vDirection; params.fSpeed = pSettings->m_fBulletSpeed; params.fLife = pSettings->m_fBulletLife; params.fRadius = pSettings->m_fBulletSize/2.0f; params.damage = pSettings->m_fBulletDamage; SFXManager::Instance()->GetEnemyPulseManager()->AddBullet(params); m_Timer.Start(pSettings->m_fAimDuration); } } m_fFirstShotTimer -= g_fDeltaTime; } } }
27.360902
103
0.720802
franticsoftware
df417c6a71237a15d76f83665a718a515574f51e
614
hpp
C++
tests/initializer_list/initializer_list_fwd.hpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
11
2021-03-15T07:06:21.000Z
2021-09-27T13:54:25.000Z
tests/initializer_list/initializer_list_fwd.hpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
null
null
null
tests/initializer_list/initializer_list_fwd.hpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
1
2021-06-24T10:46:46.000Z
2021-06-24T10:46:46.000Z
#pragma once #include <stdfwd/initializer_list> //------------------------------------------------------------------------------ #ifdef STDFWD_IS_CPP11 #define STDFWD_IS_INITIALIZER_LIST #endif //------------------------------------------------------------------------------ namespace initializer_list_tests { //------------------------------------------------------------------------------ class TestClass { public: int getInt(); #ifdef STDFWD_IS_INITIALIZER_LIST std::initializer_list< int > getList(); #endif }; //------------------------------------------------------------------------------ }
19.806452
80
0.359935
olegpublicprofile
df43c47d59ad46553c746931455c9d2dbc8996cb
9,544
cpp
C++
libalf/src/parser.cpp
zkSNARK/alf
fb428e43ee4bfc99ba326fc3fe0e9179870e2c2b
[ "MIT" ]
null
null
null
libalf/src/parser.cpp
zkSNARK/alf
fb428e43ee4bfc99ba326fc3fe0e9179870e2c2b
[ "MIT" ]
8
2020-03-29T22:32:45.000Z
2020-04-16T06:44:42.000Z
libalf/src/parser.cpp
zkSNARK/alf
fb428e43ee4bfc99ba326fc3fe0e9179870e2c2b
[ "MIT" ]
null
null
null
// // Created by Christopher Goebel on 3/21/20. // #include "parser.h" #include <filesystem> #include <string> #include <vector> #include <stack> #include <cstring> #include <stdexcept> namespace { auto is_quote(char c) -> bool { return c == '\'' or c == '"'; } auto make_token(std::string_view token, bool& is_pos_req, std::vector<alf::types::TokenBase>& tokens) { switch (token[0]) { case '|': { tokens.emplace_back(alf::types::operators::OR{}); is_pos_req = true; break; } case '&': { tokens.emplace_back(alf::types::operators::AND{}); is_pos_req = true; break; } case '^': { tokens.emplace_back(alf::types::operators::XOR{}); is_pos_req = true; break; } case '+': { is_pos_req = true; break; } case '!': { is_pos_req = true; break; } case '-': { is_pos_req = false; break; } case '(': { tokens.emplace_back(alf::types::brackets::OpenParen{}); is_pos_req = true; break; } case '[': { tokens.emplace_back(alf::types::brackets::OpenSquareBracket{}); is_pos_req = true; break; } case '{': { tokens.emplace_back(alf::types::brackets::OpenCurlyBracket{}); is_pos_req = true; break; } case ')': { tokens.emplace_back(alf::types::brackets::CloseParen{}); is_pos_req = true; break; } case ']': { tokens.emplace_back(alf::types::brackets::CloseSquareBracket{}); is_pos_req = true; break; } case '}': { tokens.emplace_back(alf::types::brackets::CloseCurlyBracket{}); is_pos_req = true; break; } default: tokens.emplace_back(alf::types::SubStr{ token, is_pos_req }); is_pos_req = true; break; } } auto handle_quote(char const*& first, char const*& second, char const*& last, std::vector<alf::types::TokenBase>& tokens, bool& is_pos_req) { static std::string const single_quote = "'"; static std::string const double_quote = "\""; first = second + 1; switch (*second) { case '\'': { second = std::find_first_of(first, last, std::cbegin(single_quote), std::cend(single_quote)); if (second == last) { throw std::runtime_error("imperfect quotes"); } std::string_view sv(first, second - first); tokens.emplace_back(alf::types::SubStr{ sv, is_pos_req }); is_pos_req = true; } break; case '"': { second = std::find_first_of(first, last, std::cbegin(double_quote), std::cend(double_quote)); if (second == last) { throw std::runtime_error("imperfect quotes"); } std::string_view sv(first, second - first); tokens.emplace_back(alf::types::SubStr{ sv, is_pos_req }); is_pos_req = true; } break; } } void add_or_pack(std::vector<alf::types::TokenBase>& tokens, std::vector<alf::types::TokenBase> v) { tokens.emplace_back(alf::types::brackets::OpenParen{}); for (auto e = v.begin(); e != v.end(); ++e) { tokens.emplace_back(std::move(*e)); if (e != v.end() - 1) { tokens.emplace_back(alf::types::operators::OR{}); } } tokens.emplace_back(alf::types::brackets::CloseParen{}); } void add_alg_pack(std::vector<alf::types::TokenBase>& tokens, std::vector<alf::types::TokenBase> v) { tokens.emplace_back(alf::types::brackets::OpenParen{}); tokens.insert(std::end(tokens), std::begin(v), std::end(v)); tokens.emplace_back(alf::types::brackets::CloseParen{}); } } namespace alf::parser { /** * Since the user is allowed to enter statements like 'a b' and then is supposed to mean * require substr 'a' AND require substr 'b', but the postfix converter wants to see all * binary operators in place, we need to fill in those operators. We could do this inside * of the parser for extra speed, but for now I am keeping this separate. I believe this * is the correct thing to do because the parsing and this fill in together are fast enough * for expected input sizes that the 2 phase parsing and fill in will probably never be of * concern compared to the actual search phase. That could be wrong is someone comes up * with some million token algebra for their requirements, but even then I don't think this * would cost much time. * * Small state machine which scans the parsed tokens and fills in implied '&' tokens. * * @param v * @return */ auto fill_in_missing_AND_symbols(std::vector<types::TokenBase>& v) -> std::vector<types::TokenBase> { using alf::types::TYPE_TOKEN; std::vector<types::TokenBase> tokens; tokens.reserve(v.size() * 2); TYPE_TOKEN previous_type = TYPE_TOKEN::OPERATOR_AND; for (types::TokenBase& t : v) { TYPE_TOKEN cur_type = t.type; if (cur_type == TYPE_TOKEN::SUBSTR and (previous_type == TYPE_TOKEN::SUBSTR or is_closing_bracket(previous_type))) { tokens.emplace_back(alf::types::operators::AND{}); } else if (is_opening_bracket(cur_type) and (previous_type == TYPE_TOKEN::SUBSTR or is_closing_bracket(previous_type))) { tokens.emplace_back(alf::types::operators::AND{}); } tokens.emplace_back(std::move(t)); previous_type = cur_type; } return std::move(tokens); } /** * Parse the input args into a vector, splitting tokens out, and either prefixing * strings with either + or -. * * This parser prepares the input for the shunting yard algorithm. * * @param s * @return */ auto parse_algebraic(std::string_view const& s) -> std::vector<types::TokenBase> { static std::string_view const delims = " '\"&|{([])}!^-+"; std::stack<char> paren_stk; std::vector<alf::types::TokenBase> tokens; tokens.reserve(s.size() / 2); bool is_positive_req = true; for (auto first = s.data(), second = s.data(), last = first + s.size(); second != last && first != last; first = second + 1) { second = std::find_first_of(first, last, std::cbegin(delims), std::cend(delims)); if (first != second) { make_token(std::string_view(first, second - first), is_positive_req, tokens); } if (is_quote(*second)) { handle_quote(first, second, last, tokens, is_positive_req); } else if (*second != ' ' and second != last) { make_token(std::string_view{ second, 1 }, is_positive_req, tokens); } } return tokens; } /** * * @param argc * @param argv * @return */ auto parse_arguments(int argc, const char** argv) -> parser::ArgPack { std::optional<std::string> infile; std::optional<std::string> outfile; std::vector<alf::types::TokenBase> tokens; for (int i{ 1 }; i < argc; ++i) { std::string arg{ argv[i] }; if (arg == "-o" or arg == "--outfile") { if (i + 1 >= argc) { throw std::runtime_error("-o or --outfile must be followed by a valid file name"); } outfile = argv[i + 1]; ++i; continue; } if (arg == "-i" or arg == "--infile") { if (i + 1 >= argc) { throw std::runtime_error("-i or --infile must be followed by a valid file name"); } infile = argv[i + 1]; if (!std::filesystem::exists(*infile)) { throw std::runtime_error("infile : " + *infile + " does not exist"); } ++i; continue; } if (arg == "-a" or arg == "--algebra") { if (i + 1 >= argc) { throw std::runtime_error("-a or --algebra must be followed by set of algebraic requirement expression"); } add_alg_pack(tokens, parse_algebraic(argv[i + 1])); ++i; continue; } // If a string is not prefixed, it is considered a positive requirement. // Accepts strings starting with '+' or otherwise not starting with '-' prefix std::vector<alf::types::TokenBase> pos_group; if (arg[0] == '+') { // do nothing (why?.. I forgot) if (arg[0] == '+' and arg.size() > 1) { // if user input a string like "+hello", this strips off the + pos_group.emplace_back(alf::types::SubStr{ std::string{ argv[i] + 1 }, true }); } while (i + 1 < argc and strncmp(argv[i + 1], "+", 1) != 0 and strncmp(argv[i + 1], "-", 1) != 0) { pos_group.emplace_back(alf::types::SubStr{ std::string{ argv[i + 1] }, true }); ++i; } add_or_pack(tokens, std::move(pos_group)); continue; } if (arg[0] == '-') { std::vector<alf::types::TokenBase> neg_group; if (arg.size() > 1) { // if the user input a string like "-hello", this will strip off the - neg_group.emplace_back(alf::types::SubStr{ std::string{ argv[i] + 1 }, false }); } while (i + 1 < argc and strncmp(argv[i + 1], "+", 1) != 0 and strncmp(argv[i + 1], "-", 1) != 0) { neg_group.emplace_back(alf::types::SubStr{ std::string{ argv[i + 1] }, false }); ++i; } add_or_pack(tokens, std::move(neg_group)); continue; } tokens.emplace_back(alf::types::SubStr{ arg, true }); } return { std::move(infile), std::move(outfile), std::move(tokens) }; } } // end namespace alf
31.919732
114
0.575231
zkSNARK
df483a65372b07fbd3cb529099db04db317e2654
832
hpp
C++
src/systems/physics/resources/vertexbuffer.hpp
vi3itor/Blunted2
318af452e51174a3a4634f3fe19b314385838992
[ "Unlicense" ]
56
2020-07-22T22:11:06.000Z
2022-03-09T08:11:43.000Z
GameplayFootball/src/systems/physics/resources/vertexbuffer.hpp
ElsevierSoftwareX/SOFTX-D-20-00016
48c28adb72aa167a251636bc92111b3c43c0be67
[ "MIT" ]
9
2021-04-22T07:06:25.000Z
2022-01-22T12:54:52.000Z
GameplayFootball/src/systems/physics/resources/vertexbuffer.hpp
ElsevierSoftwareX/SOFTX-D-20-00016
48c28adb72aa167a251636bc92111b3c43c0be67
[ "MIT" ]
20
2017-11-07T16:52:32.000Z
2022-01-25T02:42:48.000Z
// written by bastiaan konings schuiling 2008 - 2014 // this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important. // i do not offer support, so don't ask. to be used for inspiration :) #ifndef _HPP_SYSTEM_PHYSICS_RESOURCE_VERTEXBUFFER #define _HPP_SYSTEM_PHYSICS_RESOURCE_VERTEXBUFFER #include "defines.hpp" #include "base/geometry/triangle.hpp" namespace blunted { class Renderer3D; class VertexBuffer { public: VertexBuffer(); virtual ~VertexBuffer(); int CreateVertexBuffer(Renderer3D *renderer3D, std::vector<Triangle*> triangles); void SetID(int value); int GetID(); int GetVertexCount(); protected: int vertexBufferID; int vertexCount; Renderer3D *renderer3D; }; } #endif
21.333333
132
0.715144
vi3itor
df4b492212be9b36e3d2d468201e4bc8a5c3c68c
1,386
cpp
C++
source/src/G3DCam/g3dcam.cpp
hlfstr/gdutil
eb1db9a0cb381bd9c3ef7b359c1413655f0dddec
[ "MIT" ]
null
null
null
source/src/G3DCam/g3dcam.cpp
hlfstr/gdutil
eb1db9a0cb381bd9c3ef7b359c1413655f0dddec
[ "MIT" ]
null
null
null
source/src/G3DCam/g3dcam.cpp
hlfstr/gdutil
eb1db9a0cb381bd9c3ef7b359c1413655f0dddec
[ "MIT" ]
null
null
null
#include "g3dcam.hpp" namespace godot { GDREGISTER(G3DCam) G3DCam::~G3DCam() {} void G3DCam::_register_methods() { register_property<G3DCam, real_t>("Movement/Speed", &G3DCam::speed, 10.0); register_property<G3DCam, real_t>("Movement/Mouse Sensitivity", &G3DCam::mouse_sensitivity, 10.0f); register_property<G3DCam, bool>("Movement/Collision", &G3DCam::collide, true); register_property<G3DCam, String>("Conrol/Forward", &G3DCam::_forward, "ui_up"); register_property<G3DCam, String>("Conrol/Back", &G3DCam::_back, "ui_down"); register_property<G3DCam, String>("Conrol/Left", &G3DCam::_left, "ui_left"); register_property<G3DCam, String>("Conrol/Right", &G3DCam::_right, "ui_right"); register_property<G3DCam, String>("Conrol/Up", &G3DCam::_up, "ui_page_up"); register_property<G3DCam, String>("Conrol/Down", &G3DCam::_down, "ui_page_down"); register_property<G3DCam, String>("Conrol/Toggle Collision", &G3DCam::_collide, "ui_accept"); register_method("_ready", &G3DCam::_ready); } void G3DCam::_init() { speed = 10.0f; mouse_sensitivity = 10.0f; collide = true; _forward = "ui_up"; _back = "ui_down"; _left = "ui_left"; _right = "ui_right"; _up = "ui_page_up"; _down = "ui_page_down"; _collide = "ui_accept"; } void G3DCam::_ready() { _body = G3DBody::_new(); _body->_setup(this); get_parent()->call_deferred("add_child", _body); } } // namespace godot
31.5
100
0.71645
hlfstr
df4ccb9cb0b3805b7b10c2dbce15813c8b8dbc00
2,603
cpp
C++
tests/KeyTests.cpp
dkun7944/mxml
6450e7cab88eb6ee0ac469f437047072e1868ea4
[ "MIT" ]
18
2016-05-22T00:55:28.000Z
2021-03-29T08:44:23.000Z
tests/KeyTests.cpp
dkun7944/mxml
6450e7cab88eb6ee0ac469f437047072e1868ea4
[ "MIT" ]
6
2017-05-17T13:20:09.000Z
2018-10-22T20:00:57.000Z
tests/KeyTests.cpp
dkun7944/mxml
6450e7cab88eb6ee0ac469f437047072e1868ea4
[ "MIT" ]
14
2016-05-12T22:54:34.000Z
2021-10-19T12:43:16.000Z
// Copyright © 2016 Venture Media Labs. // // This file is part of mxml. The full mxml copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include <mxml/dom/Key.h> #include <boost/test/unit_test.hpp> using namespace mxml::dom; BOOST_AUTO_TEST_CASE(alterForCMajor) { Key key; key.setFifths(0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::C), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::D), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::E), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::F), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::G), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::A), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::B), 0); } BOOST_AUTO_TEST_CASE(alterForGMajor) { Key key; key.setFifths(1); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::C), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::D), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::E), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::F), 1); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::G), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::A), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::B), 0); } BOOST_AUTO_TEST_CASE(alterForBMajor) { Key key; key.setFifths(5); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::C), 1); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::D), 1); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::E), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::F), 1); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::G), 1); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::A), 1); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::B), 0); } BOOST_AUTO_TEST_CASE(alterForFMajor) { Key key; key.setFifths(-1); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::C), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::D), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::E), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::F), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::G), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::A), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::B), -1); } BOOST_AUTO_TEST_CASE(alterForGFlatMajor) { Key key; key.setFifths(-6); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::C), -1); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::D), -1); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::E), -1); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::F), 0); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::G), -1); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::A), -1); BOOST_CHECK_EQUAL(key.alter(Pitch::Step::B), -1); }
36.661972
77
0.688821
dkun7944
df5a98dc049e191d85710cc8064a7208c4fcac4b
420
hpp
C++
include/IRGenerator/YAPLValue.hpp
emilienlemaire/YAPL
b25dc6ef776db0acf612f36070446df11cad3cfd
[ "Apache-2.0" ]
7
2020-06-01T16:32:15.000Z
2021-11-07T21:32:32.000Z
include/IRGenerator/YAPLValue.hpp
emilienlemaire/YAPL
b25dc6ef776db0acf612f36070446df11cad3cfd
[ "Apache-2.0" ]
null
null
null
include/IRGenerator/YAPLValue.hpp
emilienlemaire/YAPL
b25dc6ef776db0acf612f36070446df11cad3cfd
[ "Apache-2.0" ]
null
null
null
#pragma once #include <string> #include "AST/ASTNode.hpp" #include "llvm/ADT/StringRef.h" enum class YAPLType { NONE, VOID, INT, DOUBLE, BOOL, STRING }; class YAPLValue { private: YAPLType m_Type; std::string m_Name; public: static YAPLType AstTypeToYAPLType(ASTNode::TYPE); YAPLValue(llvm::StringRef name, YAPLType type) : m_Type(type), m_Name(name.str()) {} };
15.555556
53
0.642857
emilienlemaire
df5ae61a0e0cd5d7e28c77e896a845c246b80048
1,780
hpp
C++
src/simplelog/backend/null/LogBackendMacros.hpp
jenisys/cxx.simplelog
d9b1a7665d503984cdd3b3e74c3761b6f2f4b5f1
[ "MIT" ]
null
null
null
src/simplelog/backend/null/LogBackendMacros.hpp
jenisys/cxx.simplelog
d9b1a7665d503984cdd3b3e74c3761b6f2f4b5f1
[ "MIT" ]
8
2020-01-31T20:07:27.000Z
2021-03-06T13:13:25.000Z
src/simplelog/backend/null/LogBackendMacros.hpp
jenisys/cxx.simplelog
d9b1a7665d503984cdd3b3e74c3761b6f2f4b5f1
[ "MIT" ]
3
2020-01-31T20:03:24.000Z
2021-02-28T11:34:42.000Z
/** * @file simplelog/backend/null/LogBackendMacros.hpp * Null implementation of a logging backend. * @note Any logging statement output is suppressed. **/ #pragma once namespace simplelog { namespace backend_null { struct NullCategory {}; typedef NullCategory* LoggerPtr; }} // -- SPECIFY: LoggerPtr in a backend-independent way. #if 0 namespace simplelog { namespace backend { using simplelog::backend_null::LoggerPtr; } #endif // -------------------------------------------------------------------------- // LOGGING BACKEND MACROS // -------------------------------------------------------------------------- #define SIMPLELOG_BACKEND_NULL_STATEMENT (void)0 #define SIMPLELOG_BACKEND_DEFINE_MODULE(vname, name) ::simplelog::backend_null::NullCategory *vname = nullptr #define SIMPLELOG_BACKEND_LOG(logger, level, ...) SIMPLELOG_BACKEND_NULL_STATEMENT #define SIMPLELOG_BACKEND_LOG_IF(condition, logger, level, ...) SIMPLELOG_BACKEND_NULL_STATEMENT // -------------------------------------------------------------------------- // LOGGING BACKEND: LEVEL DEFINITIONS // -------------------------------------------------------------------------- #define SIMPLELOG_BACKEND_LEVEL_OFF 10 #define SIMPLELOG_BACKEND_LEVEL_FATAL 6 #define SIMPLELOG_BACKEND_LEVEL_CRITICAL 5 #define SIMPLELOG_BACKEND_LEVEL_ERROR 4 #define SIMPLELOG_BACKEND_LEVEL_WARN 3 #define SIMPLELOG_BACKEND_LEVEL_INFO 2 #define SIMPLELOG_BACKEND_LEVEL_DEBUG 1 // -------------------------------------------------------------------------- // REUSE: LOGGING BACKEND DERIVED MACROS // -------------------------------------------------------------------------- #include "simplelog/detail/LogBackendDerivedMacros.hpp" // -- ENDOF-HEADER-FILE
35.6
109
0.569663
jenisys
df5c91cd08421cc262d680964989435ebd56118f
3,217
cpp
C++
src/ir-to-opencl_main.cpp
cuda-on-cl/cuda-on-cl
4f051a4c0bd777059138a16b54a6660267d3e9c7
[ "Apache-2.0" ]
11
2017-04-13T02:48:23.000Z
2021-12-16T08:33:02.000Z
src/ir-to-opencl_main.cpp
cuda-on-cl/cuda-on-cl
4f051a4c0bd777059138a16b54a6660267d3e9c7
[ "Apache-2.0" ]
null
null
null
src/ir-to-opencl_main.cpp
cuda-on-cl/cuda-on-cl
4f051a4c0bd777059138a16b54a6660267d3e9c7
[ "Apache-2.0" ]
1
2021-09-09T09:19:29.000Z
2021-09-09T09:19:29.000Z
// Copyright Hugh Perkins 2016 // 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 "argparsecpp.h" #include "kernel_dumper.h" #include "llvm/IR/DebugInfoMetadata.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/SourceMgr.h" #include "llvm/IRReader/IRReader.h" #include <iostream> #include <fstream> using namespace std; using namespace cocl; using namespace llvm; // extern bool add_ir_to_cl; // void convertLlFileToClFile(string llFilename, string ClFilename, string specificFunction); int main(int argc, char *argv[]) { string llFilename; string ClFilename; string kernelname = ""; bool add_ir_to_cl = false; // bool dumpCl = false; // string rcFile = ""; argparsecpp::ArgumentParser parser; parser.add_string_argument("--inputfile", &llFilename)->required(); parser.add_string_argument("--outputfile", &ClFilename)->required(); parser.add_string_argument("--kernelname", &kernelname)->required(); // parser.add_bool_argument("--debug", &debug); // parser.add_string_argument("--rcfile", &rcFile) // ->help("Path to rcfile, containing default options, set to blank to disable") // ->defaultValue("~/.coclrc"); // parser.add_bool_argument("--no-load_rcfile", &add_ir_to_cl)->help("Dont load the ~/.coclrc file"); parser.add_bool_argument("--add_ir_to_cl", &add_ir_to_cl)->help("Adds some approximation of the original IR to the opencl code, for debugging"); // parser.add_bool_argument("--dump_cl", &dumpCl)->help("prints the opencl code to stdout"); // parser.add_bool_argument("--run_branching_transforms", &runBranchingTransforms)->help("might make the kernels more acceptable to your gpu driver; buggy though..."); // parser.add_bool_argument("--branches_as_switch", &branchesAsSwitch)->help("might make the kernels more acceptable to your gpu driver; slow though..."); // parser.add_bool_argument("--dump_transforms", &dumpTransforms)->help("mostly for dev/debug. prints the results of branching transforms"); if(!parser.parse_args(argc, argv)) { return -1; } llvm::LLVMContext context; SMDiagnostic smDiagnostic; std::unique_ptr<llvm::Module> M = parseIRFile(llFilename, smDiagnostic, context); if(!M) { smDiagnostic.print("irtoopencl", errs()); // return 1; throw runtime_error("failed to parse IR"); } KernelDumper kernelDumper(M.get(), kernelname); if(add_ir_to_cl) { kernelDumper.addIRToCl(); } // if(dumpCl) { // kernelDumper.setDumpCl(); // } string cl = kernelDumper.toCl(); ofstream of; of.open(ClFilename, ios_base::out); of << cl; of.close(); return 0; }
37.847059
171
0.698477
cuda-on-cl
df5e921f117c6bbcd4c92f8d5a3f92786ad7e6fe
215
hpp
C++
src/initialization/iequilibrium.hpp
gyselax/gyselalibxx
5f9b4b1e20050f87e2a9f05d510bedf0f9a15b34
[ "MIT" ]
3
2022-02-28T08:47:07.000Z
2022-03-01T10:29:08.000Z
src/initialization/iequilibrium.hpp
gyselax/gyselalibxx
5f9b4b1e20050f87e2a9f05d510bedf0f9a15b34
[ "MIT" ]
null
null
null
src/initialization/iequilibrium.hpp
gyselax/gyselalibxx
5f9b4b1e20050f87e2a9f05d510bedf0f9a15b34
[ "MIT" ]
null
null
null
// SPDX-License-Identifier: MIT #pragma once #include <geometry.hpp> class IEquilibrium { public: virtual ~IEquilibrium() = default; virtual DSpanSpVx operator()(DSpanSpVx allfequilibrium) const = 0; };
15.357143
70
0.72093
gyselax