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
1ef07f284291c1d3a93f5d07346049b8236e62f4
5,687
cpp
C++
lib/src/platform/gtk/dialog.cpp
perjonsson/DeskGap
5e74de37c057de3bac3ac16b3fabdb79b934d21e
[ "MIT" ]
1,910
2019-02-08T05:41:48.000Z
2022-03-24T23:41:33.000Z
lib/src/platform/gtk/dialog.cpp
perjonsson/DeskGap
5e74de37c057de3bac3ac16b3fabdb79b934d21e
[ "MIT" ]
73
2019-02-13T02:58:20.000Z
2022-03-02T05:49:34.000Z
lib/src/platform/gtk/dialog.cpp
ci010/DeskGap
b3346fea3dd3af7df9a0420131da7f4ac1518092
[ "MIT" ]
88
2019-02-13T12:41:00.000Z
2022-03-25T05:04:31.000Z
#include "./BrowserWindow_impl.h" #include "dialog.hpp" namespace DeskGap { namespace { inline const char* NullableCStr(const std::optional<std::string>& str, const char* fallback = nullptr) { return str.has_value() ? str->c_str() : fallback; } } struct Dialog::Impl { static GtkFileChooserDialog* FileChooserDialogNew( std::optional<std::reference_wrapper<BrowserWindow>> browserWindow, GtkFileChooserAction action, const char* defaultCancelLabel, const char* defaultAcceptLabel, const Dialog::CommonFileDialogOptions& commonOptions ) { GtkWidget* dialog = gtk_file_chooser_dialog_new( NullableCStr(commonOptions.title), browserWindow.has_value() ? browserWindow->get().impl_->gtkWindow : nullptr, action, defaultCancelLabel, GTK_RESPONSE_CANCEL, NullableCStr(commonOptions.buttonLabel, defaultAcceptLabel), GTK_RESPONSE_ACCEPT, nullptr ); if (commonOptions.defaultDirectory.has_value()) { gtk_file_chooser_set_current_folder( GTK_FILE_CHOOSER(dialog), commonOptions.defaultDirectory->c_str() ); } if (commonOptions.defaultFilename.has_value()) { gtk_file_chooser_set_current_name( GTK_FILE_CHOOSER(dialog), commonOptions.defaultFilename->c_str() ); } for (const auto& filter: commonOptions.filters) { GtkFileFilter* gtkFilter = gtk_file_filter_new(); gtk_file_filter_set_name(gtkFilter, filter.name.c_str()); for (const std::string& extension: filter.extensions) { gtk_file_filter_add_pattern(gtkFilter, ("*." + extension).c_str()); } gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), gtkFilter); } return GTK_FILE_CHOOSER_DIALOG(dialog); } }; void Dialog::ShowErrorBox(const std::string& title, const std::string& content) { GtkWidget* dialog = gtk_message_dialog_new( nullptr, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, title.c_str(), content.c_str() ); gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(dialog), "%s", content.c_str()); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); } void Dialog::ShowOpenDialog( std::optional<std::reference_wrapper<BrowserWindow>> browserWindow, const OpenDialogOptions& options, Callback<OpenDialogResult>&& callback ) { GtkFileChooserDialog* dialog = Impl::FileChooserDialogNew( browserWindow, (options.properties & OpenDialogOptions::PROPERTY_OPEN_DIRECTORY) != 0 ? GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER : GTK_FILE_CHOOSER_ACTION_OPEN, "Cancel", "Open", options.commonOptions ); gtk_file_chooser_set_select_multiple( GTK_FILE_CHOOSER(dialog), (options.properties & OpenDialogOptions::PROPERTY_MULTI_SELECTIONS) != 0 ); gtk_file_chooser_set_show_hidden( GTK_FILE_CHOOSER(dialog), (options.properties & OpenDialogOptions::PROPERTY_SHOW_HIDDEN_FILES) != 0 ); Dialog::OpenDialogResult result; if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { std::vector<std::string> filePaths; GSList *filenameList = gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER (dialog)); GSList* currentNode = filenameList; while (currentNode != nullptr) { filePaths.emplace_back(static_cast<const char*>(currentNode->data)); currentNode = currentNode->next; } g_slist_free_full(filenameList, g_free); result.filePaths.emplace(std::move(filePaths)); } gtk_widget_destroy(GTK_WIDGET(dialog)); callback(std::move(result)); // gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog), TRUE); // Dialog::SaveDialogResult result; // if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { // char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER (dialog)); // result.filePath.emplace(filename); // g_free(filename); // } // gtk_widget_destroy(GTK_WIDGET(dialog)); // callback(std::move(result)); } void Dialog::ShowSaveDialog( std::optional<std::reference_wrapper<BrowserWindow>> browserWindow, const SaveDialogOptions& options, Callback<SaveDialogResult>&& callback ) { GtkFileChooserDialog* dialog = Impl::FileChooserDialogNew( browserWindow, GTK_FILE_CHOOSER_ACTION_SAVE, "Cancel", "Save", options.commonOptions ); gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog), TRUE); Dialog::SaveDialogResult result; if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER (dialog)); result.filePath.emplace(filename); g_free(filename); } gtk_widget_destroy(GTK_WIDGET(dialog)); callback(std::move(result)); } }
37.913333
112
0.611043
perjonsson
1ef1fd4571a534f87a45240fe528c374e53a8d2c
10,706
cpp
C++
pwiz/data/misc/PeakDataTest.cpp
edyp-lab/pwiz-mzdb
d13ce17f4061596c7e3daf9cf5671167b5996831
[ "Apache-2.0" ]
11
2015-01-08T08:33:44.000Z
2019-07-12T06:14:54.000Z
pwiz/data/misc/PeakDataTest.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
61
2015-05-27T11:20:11.000Z
2019-12-20T15:06:21.000Z
pwiz/data/misc/PeakDataTest.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
4
2016-02-03T09:41:16.000Z
2021-08-01T18:42:36.000Z
// // $Id: PeakDataTest.cpp 4129 2012-11-20 00:05:37Z chambm $ // // // Original author: Darren Kessner <[email protected]> // // Copyright 2007 Spielberg Family Center for Applied Proteomics // Cedars Sinai Medical Center, Los Angeles, California 90048 // // 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 "PeakData.hpp" #include "pwiz/utility/misc/unit.hpp" #include <boost/filesystem/operations.hpp> #include "pwiz/utility/misc/Std.hpp" using namespace pwiz::util; using namespace pwiz::minimxml; using namespace pwiz::math; using namespace pwiz::data::peakdata; ostream* os_ = 0; PeakFamily initializePeakFamily() { PeakFamily peakFamily; peakFamily.mzMonoisotopic = 329.86; peakFamily.charge = 3; peakFamily.score = 0.11235811; Peak peak; Peak a; Peak boo; peak.mz = 329.86; a.mz = 109.87; boo.mz = 6.022141730; peakFamily.peaks.push_back(peak); peakFamily.peaks.push_back(a); peakFamily.peaks.push_back(boo); return peakFamily; } Scan initializeScan() { Scan scan; scan.index = 12; scan.nativeID = "24"; scan.scanNumber = 24; scan.retentionTime = 12.345; scan.observationDuration = 6.78; scan.calibrationParameters.A = 987.654; scan.calibrationParameters.B = 321.012; PeakFamily flintstones = initializePeakFamily(); PeakFamily jetsons = initializePeakFamily(); scan.peakFamilies.push_back(flintstones); scan.peakFamilies.push_back(jetsons); return scan; } Software initializeSoftware() { Software software; software.name = "World of Warcraft"; software.version = "Wrath of the Lich King"; software.source = "Blizzard Entertainment"; Software::Parameter parameter1("Burke ping","level 70"); Software::Parameter parameter2("Kate ping", "level 0"); software.parameters.push_back(parameter1); software.parameters.push_back(parameter2); return software; } PeakData initializePeakData() { PeakData pd; Software software = initializeSoftware(); pd.software = software; Scan scan = initializeScan(); pd.scans.push_back(scan); pd.scans.push_back(scan); return pd; } PeakelPtr initializePeakel() { PeakelPtr pkl(new Peakel); pkl->mz = 432.1; pkl->retentionTime = 1234.56; pkl->maxIntensity = 9876.54; pkl->totalIntensity = 32123.45; pkl->mzVariance = 6.023; PeakFamily peakFamily = initializePeakFamily(); pkl->peaks = peakFamily.peaks; return pkl; } void testPeakEquality() { if (os_) *os_ << "testPeakEquality()" <<endl; Peak peak; peak.id = 5; peak.mz = 1; peak.retentionTime = 1.5; peak.intensity = 2; peak.area = 3; peak.error = 4; Peak peak2 = peak; unit_assert(peak == peak2); peak.attributes[Peak::Attribute_Phase] = 4.20; unit_assert(peak != peak2); peak2.attributes[Peak::Attribute_Phase] = 4.20; peak2.attributes[Peak::Attribute_Decay] = 6.66; unit_assert(peak != peak2); peak.attributes[Peak::Attribute_Decay] = 6.66; unit_assert(peak == peak2); } void testPeak() { if (os_) *os_ << "testPeak()" <<endl; // instantiate a Peak Peak peak; peak.id = 5; peak.mz = 1; peak.retentionTime = 1.5; peak.intensity = 2; peak.area = 3; peak.error = 4; peak.data.push_back(OrderedPair(1,2)); peak.data.push_back(OrderedPair(3,4)); peak.attributes[Peak::Attribute_Frequency] = 5; peak.attributes[Peak::Attribute_Phase] = 6; peak.attributes[Peak::Attribute_Decay] = 7; if (os_) *os_ << peak << endl; // write out XML to a stream ostringstream oss; XMLWriter writer(oss); peak.write(writer); // allocate a new Peak Peak peakIn; unit_assert(peak != peakIn); // read from stream into new Peak istringstream iss(oss.str()); peakIn.read(iss); if (os_) *os_ << peakIn << endl; // verify that new Peak is the same as old Peak unit_assert(peak == peakIn); } void testPeakFamily() { // initialize a PeakFamily PeakFamily jetsons = initializePeakFamily(); // write out XML to a stream ostringstream oss; XMLWriter writer(oss); jetsons.write(writer); // instantiate new PeakFamily PeakFamily flintstones; // read from stream into new PeakFamily istringstream iss(oss.str()); flintstones.read(iss); // verify that new PeakFamily is the same as old PeakFamily unit_assert(flintstones == jetsons); if (os_) *os_ << "Testing PeakFamily ... " << endl << oss.str() <<endl; } void testScan() { // initialize a new Scan Scan scan = initializeScan(); // write out XML to a stream ostringstream oss_scan; XMLWriter writer_scan(oss_scan); scan.write(writer_scan); // instantiate a second Scan Scan scan2; // read it back in istringstream iss_scan(oss_scan.str()); scan2.read(iss_scan); // assert that the two Scans are equal unit_assert(scan == scan2); if (os_) *os_ << "Testing Scan ... " << endl << oss_scan.str() << endl; } void testSoftware() { // initialize a new Software Software software = initializeSoftware(); // write out XML to a stream ostringstream oss_soft; XMLWriter writer_soft(oss_soft); software.write(writer_soft); // instantiate another Software Software software2; // read it back in istringstream iss_soft(oss_soft.str()); software2.read(iss_soft); // assert that the two Softwares are equal unit_assert(software == software2); if (os_) *os_ << "Testing Software ... " << endl << oss_soft.str() <<endl; } void testPeakData() { // initialize a PeakData PeakData pd = initializePeakData(); ostringstream oss_pd; XMLWriter writer_pd(oss_pd); pd.write(writer_pd); // instantiate another PeakData PeakData pd2; // read into it istringstream iss_pd(oss_pd.str()); pd2.read(iss_pd); // assert that the two PeakData are equal unit_assert(pd == pd2); if (os_) *os_ << "Testing PeakData ... " << endl << oss_pd.str()<<endl; } void testPeakel() { // initialize a peakel PeakelPtr dill = initializePeakel(); // write it out ostringstream oss_pkl; XMLWriter writer_pkl(oss_pkl); dill->write(writer_pkl); // instantiate another Peakel Peakel gherkin; // read into it istringstream iss_pkl(oss_pkl.str()); gherkin.read(iss_pkl); // assert that the two Peakels are equal unit_assert(*dill == gherkin); if (os_) *os_ << "Testing Peakel ... " << endl << oss_pkl.str() << endl; } void testPeakelAux() { Peakel p; p.retentionTime = 420; unit_assert(p.retentionTimeMin() == 420); unit_assert(p.retentionTimeMax() == 420); p.peaks.resize(2); p.peaks[0].retentionTime = 666; p.peaks[1].retentionTime = 667; unit_assert(p.retentionTimeMin() == 666); unit_assert(p.retentionTimeMax() == 667); } void testPeakelConstruction() { Peak peak(420, 666); Peakel peakel(Peak(420,666)); unit_assert(peakel.mz == 420); unit_assert(peakel.retentionTime == 666); unit_assert(peakel.peaks.size() == 1); unit_assert(peakel.peaks[0] == peak); } void testFeature() { // initialize a new Feature Feature feature; feature.mz = 1863.0101; feature.retentionTime = 1492.1012; feature.charge = 3; feature.totalIntensity = 1776.0704; feature.rtVariance = 1969.0720; feature.score = 420.0; feature.error = 666.0; PeakelPtr stateFair = initializePeakel(); PeakelPtr deli = initializePeakel(); feature.peakels.push_back(stateFair); feature.peakels.push_back(deli); // write it out ostringstream oss_f; XMLWriter writer_f(oss_f); feature.write(writer_f); // instantiate another feature Feature feature2; // read into it istringstream iss(oss_f.str()); feature2.read(iss); // assert that the two Features are equal if (os_) { *os_ << "Testing Feature ... " << endl << oss_f.str() << endl; *os_ << "feature2:\n"; XMLWriter writer(*os_); feature2.write(writer); } unit_assert(feature == feature2); } void testFeatureAux() { Feature feature; feature.retentionTime = 420; unit_assert(feature.retentionTimeMin() == 420); unit_assert(feature.retentionTimeMax() == 420); // retention time ranges determined by first two peakels PeakelPtr dill(new Peakel); dill->peaks.push_back(Peak(666,419)); dill->peaks.push_back(Peak(666,423)); PeakelPtr sweet(new Peakel); sweet->peaks.push_back(Peak(666,421)); sweet->peaks.push_back(Peak(666,424)); PeakelPtr gherkin(new Peakel); gherkin->peaks.push_back(Peak(666,418)); gherkin->peaks.push_back(Peak(666,425)); feature.peakels.push_back(dill); feature.peakels.push_back(sweet); feature.peakels.push_back(gherkin); unit_assert(feature.retentionTimeMin() == 419); unit_assert(feature.retentionTimeMax() == 424); } void test() { testPeakEquality(); testPeak(); testPeakFamily(); testScan(); testSoftware(); testPeakData(); testPeakel(); testPeakelAux(); testPeakelConstruction(); testFeature(); testFeatureAux(); } int main(int argc, char* argv[]) { TEST_PROLOG(argc, argv) try { if (argc>1 && !strcmp(argv[1],"-v")) os_ = &cout; if (os_) *os_ << "PeakDataTest\n"; test(); } catch (exception& e) { TEST_FAILED(e.what()) } catch (...) { TEST_FAILED("Caught unknown exception.") } TEST_EPILOG }
22.211618
180
0.6204
edyp-lab
1ef9dcfadf57af939eb6934da5e0edde6fc2abc0
901
cpp
C++
MultiComposite/MultiComposite/Compositor.cpp
DrPotatoNet/MultiComposite
d71e065661a55b22bfcec8b162859e4fbec18782
[ "MIT" ]
2
2020-09-06T08:14:15.000Z
2020-09-06T19:03:12.000Z
MultiComposite/MultiComposite/Compositor.cpp
Bluscream/MultiComposite
eac46d3fc7167629181b0652087cb6c2ab12747a
[ "MIT" ]
4
2020-09-07T09:50:31.000Z
2020-09-30T05:16:31.000Z
MultiComposite/MultiComposite/Compositor.cpp
Bluscream/MultiComposite
eac46d3fc7167629181b0652087cb6c2ab12747a
[ "MIT" ]
1
2020-09-29T20:57:15.000Z
2020-09-29T20:57:15.000Z
#include "Compositor.h" #include <cassert> #include "Logger.h" #include <string> ICompositor* ICompositor::pD11Compositor; D3D_FEATURE_LEVEL featureLevel; UINT flags = D3D11_CREATE_DEVICE_SINGLETHREADED; void D3D11Compositor::Init() { HRESULT hr = D3D11CreateDevice( NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, D3D11_CREATE_DEVICE_DEBUG, NULL, 0, D3D11_SDK_VERSION, &pDevice, &featureLevel, &pContext); assert(S_OK == hr && pDevice && pContext); } void D3D11Compositor::SetupTexture(vr::Texture_t* texture, HANDLE handle) { if (handle == nullptr) return; pDevice->OpenSharedResource(handle, __uuidof(ID3D11Texture2D), (void**)&texture->handle); } void D3D11Compositor::ReleaseTexture(vr::Texture_t* texture) { ((ID3D11Texture2D*)texture->handle)->Release(); texture->handle = nullptr; }
21.452381
93
0.674806
DrPotatoNet
1efa947bdb52c2df00c3e74faa120ae5d53fab46
7,679
cpp
C++
Microsoft.WindowsAzure.Storage/src/xml_wrapper.cpp
JasonDictos/azure-storage-cpp
8accecace59ad631cd7686f9e11fa7498fe717ac
[ "Apache-2.0" ]
null
null
null
Microsoft.WindowsAzure.Storage/src/xml_wrapper.cpp
JasonDictos/azure-storage-cpp
8accecace59ad631cd7686f9e11fa7498fe717ac
[ "Apache-2.0" ]
null
null
null
Microsoft.WindowsAzure.Storage/src/xml_wrapper.cpp
JasonDictos/azure-storage-cpp
8accecace59ad631cd7686f9e11fa7498fe717ac
[ "Apache-2.0" ]
2
2020-04-06T11:22:08.000Z
2020-11-14T19:16:58.000Z
/*** * ==++== * * Copyright (c) Microsoft 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. * * ==--== * =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ * * xml_wrapper.cpp * * This file contains wrapper for libxml2 * * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ****/ #include "stdafx.h" #include "wascore/xml_wrapper.h" #ifndef _WIN32 namespace azure { namespace storage { namespace core { namespace xml { std::string xml_char_to_string(const xmlChar * xml_char) { return std::string(reinterpret_cast<const char*>(xml_char)); } xml_text_reader_wrapper::xml_text_reader_wrapper(const unsigned char * buffer, unsigned int size) { m_reader = xmlReaderForMemory((const char*)buffer, size, NULL, 0, 0); } xml_text_reader_wrapper::~xml_text_reader_wrapper() { if (!m_reader) { xmlFreeTextReader(m_reader); m_reader = nullptr; } } bool xml_text_reader_wrapper::read() { return xmlTextReaderRead(m_reader) != 0; } unsigned xml_text_reader_wrapper::get_node_type() { return xmlTextReaderNodeType(m_reader); } bool xml_text_reader_wrapper::is_empty_element() { return xmlTextReaderIsEmptyElement(m_reader) != 0; } std::string xml_text_reader_wrapper::get_local_name() { return xml_char_to_string(xmlTextReaderLocalName(m_reader)); } std::string xml_text_reader_wrapper::get_value() { return xml_char_to_string(xmlTextReaderValue(m_reader)); } bool xml_text_reader_wrapper::move_to_first_attribute() { return xmlTextReaderMoveToFirstAttribute(m_reader) != 0; } bool xml_text_reader_wrapper::move_to_next_attribute() { return xmlTextReaderMoveToNextAttribute(m_reader) != 0; } xml_element_wrapper::~xml_element_wrapper() { } xml_element_wrapper::xml_element_wrapper(xmlNode * node) { m_ele = node; m_ele->_private = this; } xml_element_wrapper * xml_element_wrapper::add_child(const std::string & name, const std::string & prefix) { xmlNs* ns = nullptr; xmlNode* child = nullptr; if (m_ele->type != XML_ELEMENT_NODE) { return nullptr; } if (!prefix.empty()) { ns = xmlSearchNs(m_ele->doc, m_ele, (const xmlChar*)prefix.c_str()); if (!ns) { return nullptr; } } child = xmlNewNode(ns, (const xmlChar*)name.c_str()); //mem leak? if (!child) return nullptr; xmlNode* node = xmlAddChild(m_ele, child); if (!node) return nullptr; node->_private = new xml_element_wrapper(node); return reinterpret_cast<xml_element_wrapper*>(node->_private); } void xml_element_wrapper::set_namespace_declaration(const std::string & uri, const std::string & prefix) { xmlNewNs(m_ele, (const xmlChar*)(uri.empty() ? nullptr : uri.c_str()), (const xmlChar*)(prefix.empty() ? nullptr : prefix.c_str())); } void xml_element_wrapper::set_namespace(const std::string & prefix) { xmlNs* ns = xmlSearchNs(m_ele->doc, m_ele, (xmlChar*)(prefix.empty() ? nullptr : prefix.c_str())); if (ns) { xmlSetNs(m_ele, ns); } } void xml_element_wrapper::set_attribute(const std::string & name, const std::string & value, const std::string & prefix) { xmlAttr* attr = 0; if (prefix.empty()) { attr = xmlSetProp(m_ele, (const xmlChar*)name.c_str(), (const xmlChar*)value.c_str()); } else { xmlNs* ns = xmlSearchNs(m_ele->doc, m_ele, (const xmlChar*)prefix.c_str()); if (ns) { attr = xmlSetNsProp(m_ele, ns, (const xmlChar*)name.c_str(), (const xmlChar*)value.c_str()); } else { return; } } if (attr) { attr->_private = new xml_element_wrapper(reinterpret_cast<xmlNode*>(attr)); } } void xml_element_wrapper::set_child_text(const std::string & text) { xml_element_wrapper* node = nullptr; for (xmlNode* child = m_ele->children; child; child = child->next) if (child->type == xmlElementType::XML_TEXT_NODE) { child->_private = new xml_element_wrapper(child); node = reinterpret_cast<xml_element_wrapper*>(child->_private); } if (node) { if (node->m_ele->type != xmlElementType::XML_ELEMENT_NODE) { xmlNodeSetContent(node->m_ele, (xmlChar*)text.c_str()); } } else { if (m_ele->type == XML_ELEMENT_NODE) { xmlNode* node = xmlNewText((const xmlChar*)text.c_str()); node = xmlAddChild(m_ele, node); node->_private = new xml_element_wrapper(node); } } } void xml_element_wrapper::free_wrappers(xmlNode * node) { if (!node) return; for (xmlNode* child = node->children; child; child = child->next) free_wrappers(child); switch (node->type) { case XML_DTD_NODE: case XML_ELEMENT_DECL: case XML_ATTRIBUTE_NODE: case XML_ATTRIBUTE_DECL: case XML_ENTITY_DECL: if (node->_private) { delete reinterpret_cast<xml_element_wrapper*>(node->_private); node->_private = nullptr; } break; case XML_DOCUMENT_NODE: break; default: if (node->_private) { delete reinterpret_cast<xml_element_wrapper*>(node->_private); node->_private = nullptr; } break; } } xml_document_wrapper::xml_document_wrapper() { m_doc = xmlNewDoc(reinterpret_cast<const xmlChar*>("1.0")); } xml_document_wrapper::~xml_document_wrapper() { xml_element_wrapper::free_wrappers(reinterpret_cast<xmlNode*>(m_doc)); xmlFreeDoc(m_doc); m_doc = nullptr; } std::string xml_document_wrapper::write_to_string() { xmlIndentTreeOutput = 0; xmlChar* buffer = 0; int size = 0; xmlDocDumpFormatMemoryEnc(m_doc, &buffer, &size, 0, 0); std::string result; if (buffer) { result = std::string(reinterpret_cast<const char *>(buffer), reinterpret_cast<const char *>(buffer + size)); xmlFree(buffer); } return result; } xml_element_wrapper* xml_document_wrapper::create_root_node(const std::string & name, const std::string & namespace_name, const std::string & prefix) { xmlNode* node = xmlNewDocNode(m_doc, 0, (const xmlChar*)name.c_str(), 0); xmlDocSetRootElement(m_doc, node); xml_element_wrapper* element = get_root_node(); if (!namespace_name.empty()) { element->set_namespace_declaration(namespace_name, prefix); element->set_namespace(prefix); } return element; } xml_element_wrapper* xml_document_wrapper::get_root_node() const { xmlNode* root = xmlDocGetRootElement(m_doc); if (root == NULL) return NULL; else { root->_private = new xml_element_wrapper(root); return reinterpret_cast<xml_element_wrapper*>(root->_private); } return nullptr; } }}}};// namespace azure::storage::core::xml #endif //#ifdef _WIN32
25.768456
149
0.63029
JasonDictos
1efd3eec8179fcabb009c7b871ffb59ca240e0f0
519
cpp
C++
HDUOJ/2107/implementation.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2018-02-14T01:59:31.000Z
2018-03-28T03:30:45.000Z
HDUOJ/2107/implementation.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
null
null
null
HDUOJ/2107/implementation.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2017-12-30T02:46:35.000Z
2018-03-28T03:30:49.000Z
#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <cstring> #include <string> #include <climits> #include <iomanip> using namespace std; int main() { ios::sync_with_stdio(false); int num; while (cin >> num) { if (num == 0) break; int maxAC = -1; for (int i = 0; i < num; i++) { int cnt; cin >> cnt; maxAC = max(maxAC, cnt); } cout << maxAC << endl; } return 0; }
17.3
37
0.493256
codgician
480045f02400a442128bc7f8dac3c4f556842671
845
cpp
C++
examples/convex_hull/example_small.cpp
digu-007/Boost_Geometry_Competency_Test_2020
53a75c82ddf29bc7f842e653e2a1664839113b53
[ "MIT" ]
null
null
null
examples/convex_hull/example_small.cpp
digu-007/Boost_Geometry_Competency_Test_2020
53a75c82ddf29bc7f842e653e2a1664839113b53
[ "MIT" ]
null
null
null
examples/convex_hull/example_small.cpp
digu-007/Boost_Geometry_Competency_Test_2020
53a75c82ddf29bc7f842e653e2a1664839113b53
[ "MIT" ]
null
null
null
/* Boost Competency Test - GSoC 2020 digu_J - Digvijay Janartha NIT Hamirpur - INDIA */ #include <algorithm> #include <iostream> #include <utility> #include "../../includes/convex_hull_gift_wrapping.hpp" #include <boost/geometry/geometry.hpp> namespace bg = boost::geometry; using bg::dsv; int main() { typedef bg::model::point<double, 2, bg::cs::cartesian> point_t; typedef bg::model::multi_point<point_t> mpoint_t; mpoint_t mpt1, hull; bg::read_wkt("MULTIPOINT(0 0,6 0,2 2,4 2,5 3,5 5,-2 2)", mpt1); algo1::GiftWrapping(mpt1, hull); std::cout << "Dataset: " << dsv(mpt1) << std::endl; std::cout << "Convex hull: " << dsv(hull) << std::endl; return 0; } /* Output: Dataset: ((0, 0), (6, 0), (2, 2), (4, 2), (5, 3), (5, 5), (-2, 2)) Convex hull: ((-2, 2), (0, 0), (6, 0), (5, 5), (-2, 2)) */
22.236842
67
0.595266
digu-007
48051423bc5c493b50ebae69a545a1c307765da5
834
cpp
C++
google/2015/r1a/a/a.cpp
suhwanhwang/problem-solving
9421488fb97c4628bea831ac59ad5c5d9b8131d4
[ "MIT" ]
null
null
null
google/2015/r1a/a/a.cpp
suhwanhwang/problem-solving
9421488fb97c4628bea831ac59ad5c5d9b8131d4
[ "MIT" ]
null
null
null
google/2015/r1a/a/a.cpp
suhwanhwang/problem-solving
9421488fb97c4628bea831ac59ad5c5d9b8131d4
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; void printSolution(const vector<int>& m) { int m1 = 0; for (int i = 1; i < (int)m.size(); ++i) { if (m[i - 1] > m[i]) { m1 += m[i - 1] - m[i]; } } int max_d = 0; for (int i = 1; i < (int)m.size(); ++i) { max_d = max(max_d, m[i - 1] - m[i]); } int m2 = 0; for (int i = 0; i < (int)m.size() - 1; ++i) { m2 += min(max_d, m[i]); } cout << m1 << ' ' << m2 << endl; } int main(int argc, char* argv[]) { int t; cin >> t; for (int i = 1; i <= t; ++i) { int n; cin >> n; vector<int> m(n); for (int j = 0; j < n; ++j) { cin >> m[j]; } cout << "Case #" << i << ": "; printSolution(m); } return 0; }
19.857143
49
0.383693
suhwanhwang
4808e862bfc0d52cf5df59d3ce7118508cf15f97
1,933
hpp
C++
include/hfsm2/detail/shared/macros_off.hpp
amessing/HFSM2
419c6847adcc644cabb6634757ec1b403bf2e192
[ "MIT" ]
null
null
null
include/hfsm2/detail/shared/macros_off.hpp
amessing/HFSM2
419c6847adcc644cabb6634757ec1b403bf2e192
[ "MIT" ]
null
null
null
include/hfsm2/detail/shared/macros_off.hpp
amessing/HFSM2
419c6847adcc644cabb6634757ec1b403bf2e192
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------ #if defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic pop #endif #if _MSC_VER == 1900 #pragma warning(pop) #endif //////////////////////////////////////////////////////////////////////////////// //#undef HFSM2_UNUSED //#undef HFSM2_ATTRIBUTE //#undef HFSM2_ATTRIBUTE_FALLTHROUGH //#undef HFSM2_ATTRIBUTE_NO_UNIQUE_ADDRESS //#undef HFSM2_CONSTEXPR //#undef HFSM2_CONSTEXPR_EXTENDED //#undef HFSM2_ARCHITECTURE //#undef HFSM2_ARCHITECTURE_64 //#undef HFSM2_ARCHITECTURE_32 #undef HFSM2_64BIT_OR_32BIT //#undef HFSM2_BREAK #undef HFSM2_BREAK_AVAILABLE #undef HFSM2_IF_DEBUG #undef HFSM2_UNLESS_DEBUG #undef HFSM2_DEBUG_OR //#undef HFSM2_ASSERT_AVAILABLE #undef HFSM2_IF_ASSERT //#undef HFSM2_CHECKED #undef HFSM2_ASSERT #undef HFSM2_ASSERT_OR #undef HFSM2_EXPLICIT_MEMBER_SPECIALIZATION_AVAILABLE #undef HFSM2_IF_TYPEINDEX #undef HFSM2_TYPEINDEX_AVAILABLE #undef HFSM2_IF_TYPEINDEX //#undef HFSM2_DEBUG_STATE_TYPE_AVAILABLE //#undef HFSM2_PLANS_AVAILABLE #undef HFSM2_IF_PLANS #undef HFSM2_SERIALIZATION_AVAILABLE #undef HFSM2_IF_SERIALIZATION #undef HFSM2_STRUCTURE_REPORT_AVAILABLE #undef HFSM2_IF_STRUCTURE_REPORT //#undef HFSM2_TRANSITION_HISTORY_AVAILABLE #undef HFSM2_IF_TRANSITION_HISTORY //#undef HFSM2_UTILITY_THEORY_AVAILABLE #undef HFSM2_IF_UTILITY_THEORY #undef HFSM2_VERBOSE_DEBUG_LOG_AVAILABLE #undef HFSM2_LOG_INTERFACE_AVAILABLE #undef HFSM2_IF_LOG_INTERFACE #undef HFSM2_LOG_TRANSITION #if HFSM2_PLANS_AVAILABLE() #undef HFSM2_LOG_TASK_STATUS #undef HFSM2_LOG_PLAN_STATUS #endif #undef HFSM2_LOG_CANCELLED_PENDING #if HFSM2_UTILITY_THEORY_AVAILABLE() #undef HFSM2_LOG_UTILITY_RESOLUTION #undef HFSM2_LOG_RANDOM_RESOLUTION #endif #undef HFSM2_LOG_STATE_METHOD ////////////////////////////////////////////////////////////////////////////////
21.965909
80
0.741852
amessing
480cc56e31a8c4c9948f2c76f1a697313526ba52
2,306
cpp
C++
implementations/divisors.cpp
LeoRiether/Competicao-Programativa
ad5bd4eba58792ad1ce7057fdf9fa6ef8970b17e
[ "MIT" ]
1
2019-12-15T22:23:20.000Z
2019-12-15T22:23:20.000Z
implementations/divisors.cpp
LeoRiether/Competicao-Programativa
ad5bd4eba58792ad1ce7057fdf9fa6ef8970b17e
[ "MIT" ]
null
null
null
implementations/divisors.cpp
LeoRiether/Competicao-Programativa
ad5bd4eba58792ad1ce7057fdf9fa6ef8970b17e
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <iterator> // Just so I can cout a vector template <class T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { int a{0}; for (const auto& e : v) { os << (a++ ? " " : "") << e; } return os; } // O(sqrt(n)) std::vector<int> getDivisors(int n) { std::vector<int> front, back; for (int i = 1; i*i <= n; i++) { if (n % i == 0) { int j = n/i; front.push_back(i); if (i != j) back.push_back(j); } } std::move(back.rbegin(), back.rend(), std::back_inserter(front)); return front; } // O(n*log n) std::vector<int> countMultiplesTill(int n) { std::vector<int> divCount(n, 1); for (int i = 2; i < n; i++) { for (int d = i; d < n; d += i) { divCount[d]++; } } return divCount; } // O (n*log(log n)) std::vector<int> sieve(int n) { std::vector<int> primes; std::vector<bool> marked(n, false); for (int i = 2; i < n; i++) { if (!marked[i]) { primes.push_back(i); for (int j = i+i; j < n; j += i) marked[j] = true; } } return primes; } // O(n*log(log n)) std::vector<int> maxFactorTable(int n) { std::vector<int> f(n, 0); for (int i {2}; i < n; i++) { if (f[i] == 0) for (int j = i; j < n; j += i) f[j] = i; } return f; } // O(log n) with a maxFactorTable std::vector<int> factorize(int n, const std::vector<int>& mft) { if (static_cast<int>(mft.size()) <= n) return {-1}; std::vector<int> f; while (mft[n]) { f.push_back(mft[n]); n /= mft[n]; } return f; } int main() { std::cout << getDivisors(10) << std::endl; std::cout << getDivisors(12) << std::endl; std::cout << getDivisors(16) << std::endl; std::cout << getDivisors(7727) << std::endl; std::cout << std::endl; std::cout << countMultiplesTill(50) << std::endl; std::cout << std::endl; std::cout << sieve(100) << std::endl; std::cout << std::endl; std::vector<int> mft {maxFactorTable(50)}; std::cout << mft << std::endl; std::cout << std::endl; std::cout << factorize(32, mft) << std::endl; std::cout << factorize(42, mft) << std::endl; std::cout << factorize(47, mft) << std::endl; std::cout << std::endl; return 0; }
23.773196
70
0.519081
LeoRiether
480dd44b55b36de2c87762ac429a259273a77a24
1,754
hpp
C++
ext/hdmi/native/FillView.hpp
rsperanza/BB10-WebWorks-Framework
4d68e97f07bba2eeca5b4299e6fafae042a4cbc2
[ "Apache-2.0" ]
1
2022-01-27T17:02:37.000Z
2022-01-27T17:02:37.000Z
ext/hdmi/native/FillView.hpp
rsperanza/BB10-WebWorks-Framework
4d68e97f07bba2eeca5b4299e6fafae042a4cbc2
[ "Apache-2.0" ]
null
null
null
ext/hdmi/native/FillView.hpp
rsperanza/BB10-WebWorks-Framework
4d68e97f07bba2eeca5b4299e6fafae042a4cbc2
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2011-2012 Research In Motion 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. */ #ifndef FILLVIEW_HPP #define FILLVIEW_HPP #include <assert.h> #include <screen/screen.h> #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <bps/navigator.h> #include <bps/screen.h> #include <bps/bps.h> #include <bps/event.h> #include <EGL/egl.h> #include <GLES/gl.h> #include <QtCore/QObject> #include <QtCore/QString> #include "OpenGLView.hpp" #include "OpenGLThread.hpp" class FillView : public OpenGLView { Q_OBJECT Q_PROPERTY(QVariantList objectColor READ objectColor WRITE setObjectColor) // object color public: FillView(VIEW_DISPLAY display); virtual ~FillView(); // property signals QVariantList& objectColor(); public Q_SLOTS: // property slots void setObjectColor(QVariantList objectColor); // action slots void reset(bool skipColour); public: // overriden methods from OpenGLView int initialize(); int regenerate(); void cleanup(); void handleScreenEvent(bps_event_t *event); void update(); void render(); private: float obj_color[4]; }; #endif /* FILLVIEW_HPP */
21.654321
91
0.701254
rsperanza
480e4057f810f381ed34a96ffd35ccec1dae750d
576
cpp
C++
tests/test_strcspn.cpp
sushisharkjl/aolc
6658f7954611de969b1fe1de017ad96bbfadf759
[ "BSD-3-Clause" ]
null
null
null
tests/test_strcspn.cpp
sushisharkjl/aolc
6658f7954611de969b1fe1de017ad96bbfadf759
[ "BSD-3-Clause" ]
null
null
null
tests/test_strcspn.cpp
sushisharkjl/aolc
6658f7954611de969b1fe1de017ad96bbfadf759
[ "BSD-3-Clause" ]
null
null
null
#include "aolc/_test_string.h" #include <string.h> #include "aolc/compare_buffer_functions.h" #include "gtest/gtest.h" TEST(strcspn, Basic) { char str[] = {'x', 'x', 'x', 'X', 'y', 'X', 'X', '\0'}; char x[] = "x"; char xX[] = "xX"; char X[] = "X"; char y[] = "y"; char xyX[] = "xyX"; EXPECT_EQ(strcspn(str, x), _strcspn(str, x)); EXPECT_EQ(strcspn(str, xX), _strcspn(str, xX)); EXPECT_EQ(strcspn(str, X), _strcspn(str, X)); EXPECT_EQ(strcspn(str, y), _strcspn(str, y)); EXPECT_EQ(strcspn(str, xyX), _strcspn(str, xyX)); }
27.428571
59
0.564236
sushisharkjl
480eecc0a0c8d313706107d8572398af58326e8b
2,229
hpp
C++
src/assembler/Assembler.hpp
ldXiao/polyfem
d4103af16979ff67d461a9ebe46a14bbc4dc8c7c
[ "MIT" ]
null
null
null
src/assembler/Assembler.hpp
ldXiao/polyfem
d4103af16979ff67d461a9ebe46a14bbc4dc8c7c
[ "MIT" ]
null
null
null
src/assembler/Assembler.hpp
ldXiao/polyfem
d4103af16979ff67d461a9ebe46a14bbc4dc8c7c
[ "MIT" ]
null
null
null
#ifndef ASSEMBLER_HPP #define ASSEMBLER_HPP #include <polyfem/ElementAssemblyValues.hpp> #include <polyfem/Problem.hpp> #include <Eigen/Sparse> #include <vector> #include <iostream> #include <cmath> #include <memory> namespace polyfem { template<class LocalAssembler> class Assembler { public: void assemble( const bool is_volume, const int n_basis, const std::vector< ElementBases > &bases, const std::vector< ElementBases > &gbases, StiffnessMatrix &stiffness) const; inline LocalAssembler &local_assembler() { return local_assembler_; } inline const LocalAssembler &local_assembler() const { return local_assembler_; } private: LocalAssembler local_assembler_; }; template<class LocalAssembler> class MixedAssembler { public: void assemble( const bool is_volume, const int n_psi_basis, const int n_phi_basis, const std::vector< ElementBases > &psi_bases, const std::vector< ElementBases > &phi_bases, const std::vector< ElementBases > &gbases, StiffnessMatrix &stiffness) const; inline LocalAssembler &local_assembler() { return local_assembler_; } inline const LocalAssembler &local_assembler() const { return local_assembler_; } private: LocalAssembler local_assembler_; }; template<class LocalAssembler> class NLAssembler { public: void assemble_grad( const bool is_volume, const int n_basis, const std::vector< ElementBases > &bases, const std::vector< ElementBases > &gbases, const Eigen::MatrixXd &displacement, Eigen::MatrixXd &rhs) const; void assemble_hessian( const bool is_volume, const int n_basis, const std::vector< ElementBases > &bases, const std::vector< ElementBases > &gbases, const Eigen::MatrixXd &displacement, StiffnessMatrix &grad) const; double assemble( const bool is_volume, const std::vector< ElementBases > &bases, const std::vector< ElementBases > &gbases, const Eigen::MatrixXd &displacement) const; inline LocalAssembler &local_assembler() { return local_assembler_; } inline const LocalAssembler &local_assembler() const { return local_assembler_; } void clear_cache() { } private: LocalAssembler local_assembler_; }; } #endif //ASSEMBLER_HPP
23.967742
83
0.740691
ldXiao
481455ffabbc21e4d72ae04a61143c43ed73ea65
3,694
cpp
C++
irob_vision_support/src/camera_preprocessor.cpp
BenGab/irob-saf
3a0fee98239bd935aa99c9d9526eb9b4cfc8963c
[ "MIT" ]
11
2018-06-07T22:56:06.000Z
2021-11-04T14:56:36.000Z
irob_vision_support/src/camera_preprocessor.cpp
BenGab/irob-saf
3a0fee98239bd935aa99c9d9526eb9b4cfc8963c
[ "MIT" ]
2
2019-12-19T10:04:02.000Z
2021-04-19T13:45:25.000Z
irob_vision_support/src/camera_preprocessor.cpp
BenGab/irob-saf
3a0fee98239bd935aa99c9d9526eb9b4cfc8963c
[ "MIT" ]
8
2018-05-24T23:45:01.000Z
2021-05-07T23:33:43.000Z
/* * camera_preprocessor.cpp * * Author(s): Tamas D. Nagy * Created on: 2018-03-13 * */ #include <iostream> #include <sstream> #include <vector> #include <cmath> #include <ros/ros.h> #include <ros/package.h> #include <sensor_msgs/Image.h> #include <irob_vision_support/camera_preprocessor.hpp> namespace saf { CameraPreprocessor::CameraPreprocessor(ros::NodeHandle nh, std::string camera, std::string command): nh(nh), camera(camera) { if (!command.compare("none")) { this->command = Command::NONE; } else if (!command.compare("avg_adjacent")) { this->command = Command::AVG_ADJACENT; } subscribeTopics(); advertiseTopics(); cam_info_service = nh.advertiseService("preprocessed/" + camera + "/set_camera_info", &CameraPreprocessor::setCameraInfoCB, this); } CameraPreprocessor::~CameraPreprocessor() {} void CameraPreprocessor::subscribeTopics() { image_sub = nh.subscribe<sensor_msgs::Image>( camera + "/image_raw", 1000, &CameraPreprocessor::imageCB,this); camera_info_sub = nh.subscribe<sensor_msgs::CameraInfo>( camera + "/camera_info", 1000, &CameraPreprocessor::cameraInfoCB,this); } void CameraPreprocessor::advertiseTopics() { image_pub = nh.advertise<sensor_msgs::Image>("preprocessed/" + camera + "/image_raw", 1000); camera_info_pub = nh.advertise<sensor_msgs::CameraInfo>("preprocessed/" + camera + "/camera_info", 1); } void CameraPreprocessor::imageCB( const sensor_msgs::ImageConstPtr& msg) { try { cv_bridge::CvImagePtr image_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); cv::Mat processed_image; image_ptr->image.copyTo(processed_image); switch(command) { case Command::NONE: break; case Command::AVG_ADJACENT: if(!prev_image.empty()) processed_image = (processed_image + prev_image) / 2.0; break; } sensor_msgs::ImagePtr processed_msg = cv_bridge::CvImage(msg->header, "bgr8", processed_image).toImageMsg(); image_pub.publish(processed_msg); image_ptr->image.copyTo(prev_image); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } } void CameraPreprocessor::cameraInfoCB( const sensor_msgs::CameraInfoConstPtr& msg) { camera_info_pub.publish(*msg); } bool CameraPreprocessor::setCameraInfoCB(sensor_msgs::SetCameraInfo::Request& request, sensor_msgs::SetCameraInfo::Response& response) { ros::ServiceClient client = nh.serviceClient<sensor_msgs::SetCameraInfo>(camera +"/set_camera_info"); sensor_msgs::SetCameraInfo srv; srv.request = request; srv.response = response; if (client.call(srv)) { response = srv.response; return true; } response = srv.response; return false; } } using namespace saf; /** * Image preprocessor main */ int main(int argc, char **argv) { // Initialize ros node ros::init(argc, argv, "camera_preprocessor"); ros::NodeHandle nh; ros::NodeHandle priv_nh("~"); std::string command; priv_nh.getParam("command", command); std::string camera; priv_nh.getParam("camera", camera); std::string calibration; priv_nh.getParam("calibration", calibration); // Start Vision server try { CameraPreprocessor prep(nh, camera, command); ros::spin(); ROS_INFO_STREAM("Program finished succesfully, shutting down ..."); } catch (const std::exception& e) { ROS_ERROR_STREAM(e.what()); ROS_ERROR_STREAM("Program stopped by an error, shutting down ..."); } // Exit ros::shutdown(); return 0; }
18.107843
134
0.67163
BenGab
4818553a9e987f2d528ff7da296a7cdbac63890c
1,235
cpp
C++
BAC_2nd/ch6/UVa11853.cpp
Anyrainel/aoapc-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
3
2017-08-15T06:00:01.000Z
2018-12-10T09:05:53.000Z
BAC_2nd/ch6/UVa11853.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
null
null
null
BAC_2nd/ch6/UVa11853.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
2
2017-09-16T18:46:27.000Z
2018-05-22T05:42:03.000Z
// UVa11853 Paintball // Rujia Liu #include<cstdio> #include<cstdlib> #include<cmath> #include<cstring> #include<algorithm> using namespace std; const int maxn = 1000 + 5; const double W = 1000.0; int n, vis[maxn]; double x[maxn], y[maxn], r[maxn], left, right; bool ok; bool intersect(int c1, int c2) { return sqrt((x[c1]-x[c2])*(x[c1]-x[c2]) + (y[c1]-y[c2])*(y[c1]-y[c2])) < r[c1] + r[c2]; } void check_circle(int u) { if(x[u] - r[u] < 0) left = min(left, y[u] - sqrt(r[u]*r[u] - x[u]*x[u])); if(x[u] + r[u] > W) right = min(right, y[u] - sqrt(r[u]*r[u] - (W-x[u])*(W-x[u]))); } // 能达到底部则返回true bool dfs(int u) { if(vis[u]) return false; vis[u] = 1; if(y[u] - r[u] < 0) return true; for(int v = 0; v < n; v++) if(intersect(u, v) && dfs(v)) return true; check_circle(u); return false; } int main() { while(scanf("%d", &n) == 1) { ok = true; left = right = W; memset(vis, 0, sizeof(vis)); for(int i = 0; i < n; i++) scanf("%lf%lf%lf", &x[i], &y[i], &r[i]); for(int i = 0; i < n; i++) if(y[i] + r[i] >= W && dfs(i)) { ok = false; break; } // 从上往下dfs if(ok) printf("0.00 %.2lf %.2lf %.2lf\n", left, W, right); else printf("IMPOSSIBLE\n"); } return 0; }
22.87037
89
0.527935
Anyrainel
4823be4f463910cd08208685aee8a37cc52df35c
1,433
cpp
C++
Highwaycam/program.cpp
42yeah/Highwaycam
02d06c3e30eef741e252b9f518ab24b3c7ac7e64
[ "MIT" ]
1
2020-06-16T10:29:25.000Z
2020-06-16T10:29:25.000Z
Highwaycam/program.cpp
42yeah/Highwaycam
02d06c3e30eef741e252b9f518ab24b3c7ac7e64
[ "MIT" ]
null
null
null
Highwaycam/program.cpp
42yeah/Highwaycam
02d06c3e30eef741e252b9f518ab24b3c7ac7e64
[ "MIT" ]
null
null
null
// // program.cpp // Highwaycam // // Created by Hao Zhou on 28/05/2020. // Copyright © 2020 John Boiles . All rights reserved. // #include "program.hpp" #include "app.hpp" #include <sstream> GLuint compile(App *app, GLuint type, std::string path) { std::string reason = "Failed to compile shader: " + path; GLuint shader = glCreateShader(type); std::fstream reader(path); if (!reader.good()) { app->warnings.push_back(reason + " (shader path not found)"); return 0; } std::stringstream ss; ss << reader.rdbuf(); std::string src = ss.str(); const char *raw = src.c_str(); glShaderSource(shader, 1, &raw, nullptr); glCompileShader(shader); char log[512] = { 0 }; glGetShaderInfoLog(shader, sizeof(log), nullptr, log); if (std::string(log).length() > 0 && log[0] != '\n') { app->warnings.push_back(reason + " (" + log + ")"); } return shader; } GLuint link(App *app, std::string vpath, std::string fpath) { std::string reason = "Failed to link program"; GLuint program = glCreateProgram(); glAttachShader(program, compile(app, GL_VERTEX_SHADER, vpath)); glAttachShader(program, compile(app, GL_FRAGMENT_SHADER, fpath)); glLinkProgram(program); char log[512] = { 0 }; if (std::string(log).length() > 0 && log[0] != '\n') { app->warnings.push_back(reason + " (" + log + ")"); } return program; }
29.244898
69
0.611305
42yeah
48274f205b1f63788b25f6e88be3fad4cfc1e0af
128
cpp
C++
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/SelfAdjointEigenSolver_operatorSqrt.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/SelfAdjointEigenSolver_operatorSqrt.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/SelfAdjointEigenSolver_operatorSqrt.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:eb2d0741391080bf616202edba473e05dcf8d96886d2d80f3f78df48f9dbe6f9 size 363
32
75
0.882813
initialz
48287ef19fb1ed0ec68f9a36e5be0cc193faf01a
414
cpp
C++
src/core/subsystem/utility/SSStartupScript.cpp
Robograde/Robograde
2c9a7d0b8250ec240102d504127f5c54532cb2b0
[ "Zlib" ]
5
2015-10-11T10:22:39.000Z
2019-07-24T10:09:13.000Z
src/core/subsystem/utility/SSStartupScript.cpp
Robograde/Robograde
2c9a7d0b8250ec240102d504127f5c54532cb2b0
[ "Zlib" ]
null
null
null
src/core/subsystem/utility/SSStartupScript.cpp
Robograde/Robograde
2c9a7d0b8250ec240102d504127f5c54532cb2b0
[ "Zlib" ]
null
null
null
/************************************************** Copyright 2015 Ola Enberg ***************************************************/ #include "SSStartupScript.h" #include <script/ScriptEngine.h> SSStartupScript& SSStartupScript::GetInstance( ) { static SSStartupScript instance; return instance; } void SSStartupScript::Startup( ) { g_Script.Perform( "dofile( SRC_DIR .. \"personal/Startup.lua\" )" ); }
23
69
0.548309
Robograde
482ec84b9153a0c8d412c008e2197b91e8194cff
15,556
hpp
C++
polympc/src/nmpc.hpp
alexandreguerradeoliveira/rocket_gnc
164e96daca01d9edbc45bfaac0f6b55fe7324f24
[ "MIT" ]
null
null
null
polympc/src/nmpc.hpp
alexandreguerradeoliveira/rocket_gnc
164e96daca01d9edbc45bfaac0f6b55fe7324f24
[ "MIT" ]
null
null
null
polympc/src/nmpc.hpp
alexandreguerradeoliveira/rocket_gnc
164e96daca01d9edbc45bfaac0f6b55fe7324f24
[ "MIT" ]
null
null
null
// This file is part of PolyMPC, a lightweight C++ template library // for real-time nonlinear optimization and optimal control. // // Copyright (C) 2020 Listov Petr <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef NMPC_HPP #define NMPC_HPP #include <memory> #include "chebyshev.hpp" #define POLYMPC_USE_CONSTRAINTS namespace polympc { /** std::set<std::string> available_options = {"spectral.number_segments", "spectral.poly_order", "spectral.tf"}; template<typename ParamType> ParamType get_param(const std::string &key, const casadi::Dict dict, const ParamType &default_val) { if((available_options.find(key) != available_options.end()) && (dict.find(key) != dict.end())) return dict.find(key)->second; else if((available_options.find(key) == available_options.end()) && (dict.find(key) != dict.end())) { std::cout << "Unknown parameter: " << key << "\n"; // << "Available parameters: " << available_options << "\n"; return default_val; } else return default_val; } */ template <typename System, int NX, int NU, int NumSegments = 2, int PolyOrder = 5> class nmpc { public: nmpc(const casadi::DM &_reference, const double &tf = 1.0, const casadi::DMDict &mpc_options = casadi::DMDict(), const casadi::Dict &solver_options = casadi::Dict()); ~nmpc(){} /** contsraints setters */ void setLBX(const casadi::DM &_lbx) { ARG["lbx"](casadi::Slice(0, NX * (PolyOrder * NumSegments + 1 ))) = casadi::SX::repmat(casadi::SX::mtimes(Scale_X, _lbx), PolyOrder * NumSegments + 1, 1); } void setUBX(const casadi::DM &_ubx) { ARG["ubx"](casadi::Slice(0, NX * (PolyOrder * NumSegments + 1 ))) = casadi::SX::repmat(casadi::SX::mtimes(Scale_X, _ubx), PolyOrder * NumSegments + 1, 1); } void setLBU(const casadi::DM &_lbu) { int start = NX * (PolyOrder * NumSegments + 1 ); int finish = start + NU * (PolyOrder * NumSegments + 1 ); ARG["lbx"](casadi::Slice(start, finish)) = casadi::SX::repmat(casadi::SX::mtimes(Scale_U, _lbu), PolyOrder * NumSegments + 1, 1); } void setUBU(const casadi::DM &_ubu) { int start = NX * (PolyOrder * NumSegments + 1 ); int finish = start + NU * (PolyOrder * NumSegments + 1 ); ARG["ubx"](casadi::Slice(start, finish)) = casadi::SX::repmat(casadi::SX::mtimes(Scale_U, _ubu), PolyOrder * NumSegments + 1, 1); } void setStateScaling(const casadi::DM &Scaling){Scale_X = Scaling; invSX = casadi::DM::solve(Scale_X, casadi::DM::eye(Scale_X.size1()));} void setControlScaling(const casadi::DM &Scaling){Scale_U = Scaling; invSU = casadi::DM::solve(Scale_U, casadi::DM::eye(Scale_U.size1()));} void createNLP(const casadi::Dict &solver_options); void updateParams(const casadi::Dict &params); void enableWarmStart(){WARM_START = true;} void disableWarmStart(){WARM_START = false;} void computeControl(const casadi::DM &_X0); casadi::DM getOptimalControl() const {return OptimalControl;} casadi::DM getOptimalTrajetory() const {return OptimalTrajectory;} casadi::Dict getStats() const {return stats;} bool initialized() const {return _initialized;} double getPathError(); private: System system; casadi::SX Reference; uint nx, nu, ny, np; double Tf; casadi::SX Contraints; casadi::Function ContraintsFunc; /** state box constraints */ casadi::DM LBX, UBX; /** nonlinear inequality constraints */ casadi::DM LBG, UBG; /** control box constraints */ casadi::DM LBU, UBU; /** state and control scaling matrixces */ casadi::DM Scale_X, invSX; casadi::DM Scale_U, invSU; /** cost function weight matrices */ casadi::SX Q, R, P; casadi::DM NLP_X, NLP_LAM_G, NLP_LAM_X; casadi::Function NLP_Solver; casadi::SXDict NLP; casadi::Dict OPTS; casadi::DMDict ARG; casadi::Dict stats; casadi::DM OptimalControl; casadi::DM OptimalTrajectory; unsigned NUM_COLLOCATION_POINTS; bool WARM_START; bool _initialized; bool scale; /** TRACE FUNCTIONS */ casadi::Function DynamicsFunc; casadi::Function DynamicConstraints; casadi::Function PerformanceIndex; casadi::Function CostFunction; casadi::Function PathError; casadi::Function m_Jacobian; casadi::Function m_Dynamics; }; template<typename System, int NX, int NU, int NumSegments, int PolyOrder> nmpc<System, NX, NU, NumSegments, PolyOrder>::nmpc(const casadi::DM &_reference, const double &tf, const casadi::DMDict &mpc_options, const casadi::Dict &solver_options) { /** set up default */ casadi::Function dynamics = system.getDynamics(); nx = dynamics.nnz_out(); nu = dynamics.nnz_in() - nx; Tf = tf; assert(NX == nx); assert(NU == nu); casadi::Function output = system.getOutputMapping(); ny = output.nnz_out(); Reference = _reference; assert(ny == Reference.size1()); Q = casadi::SX::eye(ny); P = casadi::SX::eye(ny); R = casadi::SX::eye(NU); Scale_X = casadi::DM::eye(ny); invSX = Scale_X; Scale_U = casadi::DM::eye(NU); invSU = Scale_U; if(mpc_options.find("mpc.Q") != mpc_options.end()) { Q = mpc_options.find("mpc.Q")->second; assert(ny == Q.size1()); assert(ny == Q.size2()); } if(mpc_options.find("mpc.R") != mpc_options.end()) { R = mpc_options.find("mpc.R")->second; assert(NU == R.size1()); assert(NU == R.size2()); } if(mpc_options.find("mpc.P") != mpc_options.end()) { P = mpc_options.find("mpc.P")->second; assert(ny == P.size1()); assert(ny == P.size2()); } /** problem scaling */ scale = false; if(mpc_options.find("mpc.scaling") != mpc_options.end()) scale = static_cast<bool>(mpc_options.find("mpc.scaling")->second.nonzeros()[0]); if(mpc_options.find("mpc.scale_x") != mpc_options.end() && scale) { Scale_X = mpc_options.find("mpc.scale_x")->second; assert(NX == Scale_X.size1()); assert(NX == Scale_X.size2()); invSX = casadi::DM::solve(Scale_X, casadi::DM::eye(Scale_X.size1())); } if(mpc_options.find("mpc.scale_u") != mpc_options.end() && scale) { Scale_U = mpc_options.find("mpc.scale_u")->second; assert(NU == Scale_U.size1()); assert(NU == Scale_U.size2()); invSU = casadi::DM::solve(Scale_U, casadi::DM::eye(Scale_U.size1())); } /** assume unconstrained problem */ LBX = -casadi::DM::inf(nx); UBX = casadi::DM::inf(nx); LBU = -casadi::DM::inf(nu); UBU = casadi::DM::inf(nu); WARM_START = false; _initialized = false; /** create NLP */ createNLP(solver_options); } /** update solver paramters */ template<typename System, int NX, int NU, int NumSegments, int PolyOrder> void nmpc<System, NX, NU, NumSegments, PolyOrder>::updateParams(const casadi::Dict &params) { for (casadi::Dict::const_iterator it = params.begin(); it != params.end(); ++it) { OPTS[it->first] = it->second; } } template<typename System, int NX, int NU, int NumSegments, int PolyOrder> void nmpc<System, NX, NU, NumSegments, PolyOrder>::createNLP(const casadi::Dict &solver_options) { /** get dynamics function and state Jacobian */ casadi::Function dynamics = system.getDynamics(); casadi::Function output = system.getOutputMapping(); casadi::SX x = casadi::SX::sym("x", nx); casadi::SX u = casadi::SX::sym("u", nu); DynamicsFunc = dynamics; if(scale) { assert(Scale_X.size1() != 0); assert(Scale_U.size1() != 0); } /** ----------------------------------------------------------------------------------*/ /** set default properties of approximation */ const int num_segments = NumSegments; //get_param<int>("spectral.number_segments", spectral_props.props, 2); const int poly_order = PolyOrder; //get_param<int>("spectral.poly_order", spectral_props.props, 5); const int dimx = NX; const int dimu = NU; const int dimp = 0; const double tf = Tf; //get_param<double>("spectral.tf", spectral_props.props, 1.0); NUM_COLLOCATION_POINTS = num_segments * poly_order; /** Order of polynomial interpolation */ Chebyshev<casadi::SX, poly_order, num_segments, dimx, dimu, dimp> spectral; casadi::SX diff_constr; if(scale) { casadi::SX SODE = dynamics(casadi::SXVector{casadi::SX::mtimes(invSX, x), casadi::SX::mtimes(invSU, u)})[0]; SODE = casadi::SX::mtimes(Scale_X, SODE); casadi::Function FunSODE = casadi::Function("scaled_ode", {x, u}, {SODE}); diff_constr = spectral.CollocateDynamics(FunSODE, 0, tf); } else { diff_constr = spectral.CollocateDynamics(DynamicsFunc, 0, tf); } diff_constr = diff_constr(casadi::Slice(0, diff_constr.size1() - dimx)); /** define an integral cost */ casadi::SX lagrange, residual; if(scale) { casadi::SX _invSX = invSX(casadi::Slice(0, NX), casadi::Slice(0, NX)); residual = Reference - output({casadi::SX::mtimes(_invSX, x)})[0]; lagrange = casadi::SX::sum1( casadi::SX::mtimes(Q, pow(residual, 2)) ); lagrange = lagrange + casadi::SX::sum1( casadi::SX::mtimes(R, pow(u, 2)) ); } else { residual = Reference - output({x})[0]; lagrange = casadi::SX::sum1( casadi::SX::mtimes(Q, pow(residual, 2)) ); lagrange = lagrange + casadi::SX::sum1( casadi::SX::mtimes(R, pow(u, 2)) ); } casadi::Function LagrangeTerm = casadi::Function("Lagrange", {x, u}, {lagrange}); /** trace functions */ PathError = casadi::Function("PathError", {x}, {residual}); casadi::SX mayer = casadi::SX::sum1( casadi::SX::mtimes(P, pow(residual, 2)) ); casadi::Function MayerTerm = casadi::Function("Mayer",{x}, {mayer}); casadi::SX performance_idx = spectral.CollocateCost(MayerTerm, LagrangeTerm, 0.0, tf); casadi::SX varx = spectral.VarX(); casadi::SX varu = spectral.VarU(); casadi::SX opt_var = casadi::SX::vertcat(casadi::SXVector{varx, varu}); /** debugging output */ DynamicConstraints = casadi::Function("constraint_func", {opt_var}, {diff_constr}); PerformanceIndex = casadi::Function("performance_idx", {opt_var}, {performance_idx}); casadi::SX lbg = casadi::SX::zeros(diff_constr.size()); casadi::SX ubg = casadi::SX::zeros(diff_constr.size()); /** set inequality (box) constraints */ /** state */ casadi::SX lbx = casadi::SX::repmat(casadi::SX::mtimes(Scale_X, LBX), poly_order * num_segments + 1, 1); casadi::SX ubx = casadi::SX::repmat(casadi::SX::mtimes(Scale_X, UBX), poly_order * num_segments + 1, 1); /** control */ lbx = casadi::SX::vertcat( {lbx, casadi::SX::repmat(casadi::SX::mtimes(Scale_U, LBU), poly_order * num_segments + 1, 1)} ); ubx = casadi::SX::vertcat( {ubx, casadi::SX::repmat(casadi::SX::mtimes(Scale_U, UBU), poly_order * num_segments + 1, 1)} ); casadi::SX diff_constr_jacobian = casadi::SX::jacobian(diff_constr, opt_var); /** Augmented Jacobian */ m_Jacobian = casadi::Function("aug_jacobian",{opt_var}, {diff_constr_jacobian}); /** formulate NLP */ NLP["x"] = opt_var; NLP["f"] = performance_idx; // 1e-3 * casadi::SX::dot(diff_constr, diff_constr); NLP["g"] = diff_constr; /** default solver options */ OPTS["ipopt.linear_solver"] = "mumps"; OPTS["ipopt.print_level"] = 1; OPTS["ipopt.tol"] = 1e-4; OPTS["ipopt.acceptable_tol"] = 1e-4; OPTS["ipopt.max_iter"] = 150; OPTS["ipopt.warm_start_init_point"] = "yes"; //OPTS["ipopt.hessian_approximation"] = "limited-memory"; /** set user defined options */ if(!solver_options.empty()) updateParams(solver_options); NLP_Solver = casadi::nlpsol("solver", "ipopt", NLP, OPTS); /** set default args */ ARG["lbx"] = lbx; ARG["ubx"] = ubx; ARG["lbg"] = lbg; ARG["ubg"] = ubg; casadi::DM feasible_state = casadi::DM::zeros(UBX.size()); casadi::DM feasible_control = casadi::DM::zeros(UBU.size()); ARG["x0"] = casadi::DM::vertcat(casadi::DMVector{casadi::DM::repmat(feasible_state, poly_order * num_segments + 1, 1), casadi::DM::repmat(feasible_control, poly_order * num_segments + 1, 1)}); } template<typename System, int NX, int NU, int NumSegments, int PolyOrder> void nmpc<System, NX, NU, NumSegments, PolyOrder>::computeControl(const casadi::DM &_X0) { int N = NUM_COLLOCATION_POINTS; /** scale input */ casadi::DM X0 = casadi::DM::mtimes(Scale_X, _X0); std::cout << "Compute control at: " << X0 << "\n"; if(WARM_START) { int idx_in = N * NX; int idx_out = idx_in + NX; ARG["lbx"](casadi::Slice(idx_in, idx_out), 0) = X0; ARG["ubx"](casadi::Slice(idx_in, idx_out), 0) = X0; ARG["x0"] = NLP_X; ARG["lam_g0"] = NLP_LAM_G; ARG["lam_x0"] = NLP_LAM_X; } else { ARG["x0"](casadi::Slice(0, (N + 1) * NX), 0) = casadi::DM::repmat(X0, (N + 1), 1); int idx_in = N * NX; int idx_out = idx_in + NX; ARG["lbx"](casadi::Slice(idx_in, idx_out), 0) = X0; ARG["ubx"](casadi::Slice(idx_in, idx_out), 0) = X0; } /** store optimal solution */ casadi::DMDict res = NLP_Solver(ARG); NLP_X = res.at("x"); NLP_LAM_X = res.at("lam_x"); NLP_LAM_G = res.at("lam_g"); casadi::DM opt_x = NLP_X(casadi::Slice(0, (N + 1) * NX)); //DM invSX = DM::solve(Scale_X, DM::eye(15)); OptimalTrajectory = casadi::DM::mtimes(invSX, casadi::DM::reshape(opt_x, NX, N + 1)); //casadi::DM opt_u = NLP_X( casadi::Slice((N + 1) * NX, NLP_X.size1()) ); casadi::DM opt_u = NLP_X( casadi::Slice((N + 1) * NX, (N + 1) * NX + (N + 1) * NU ) ); //DM invSU = DM::solve(Scale_U, DM::eye(4)); OptimalControl = casadi::DM::mtimes(invSU, casadi::DM::reshape(opt_u, NU, N + 1)); stats = NLP_Solver.stats(); std::cout << stats << "\n"; std::string solve_status = static_cast<std::string>(stats["return_status"]); if(solve_status.compare("Invalid_Number_Detected") == 0) { std::cout << "X0 : " << ARG["x0"] << "\n"; //assert(false); } if(solve_status.compare("Infeasible_Problem_Detected") == 0) { std::cout << "X0 : " << ARG["x0"] << "\n"; //assert(false); } enableWarmStart(); } /** get path error */ template<typename System, int NX, int NU, int NumSegments, int PolyOrder> double nmpc<System, NX, NU, NumSegments, PolyOrder>::getPathError() { double error = 0; if(!OptimalTrajectory.is_empty()) { casadi::DM state = OptimalTrajectory(casadi::Slice(0, OptimalTrajectory.size1()), OptimalTrajectory.size2() - 1); state = casadi::DM::mtimes(Scale_X, state); casadi::DMVector tmp = PathError(casadi::DMVector{state}); error = casadi::DM::norm_2( tmp[0] ).nonzeros()[0]; } return error; } } //polympc namespace #endif // NMPC_HPP
34.800895
170
0.607547
alexandreguerradeoliveira
482f0c351449b350b65187e77b7a0bfc69803464
4,073
cpp
C++
mlir/lib/Dialect/ArmSVE/IR/ArmSVEDialect.cpp
jinge90/llvm
1f3f9b9b1181feb559e85970155678c18a436711
[ "Apache-2.0" ]
null
null
null
mlir/lib/Dialect/ArmSVE/IR/ArmSVEDialect.cpp
jinge90/llvm
1f3f9b9b1181feb559e85970155678c18a436711
[ "Apache-2.0" ]
null
null
null
mlir/lib/Dialect/ArmSVE/IR/ArmSVEDialect.cpp
jinge90/llvm
1f3f9b9b1181feb559e85970155678c18a436711
[ "Apache-2.0" ]
null
null
null
//===- ArmSVEDialect.cpp - MLIR ArmSVE dialect implementation -------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the ArmSVE dialect and its operations. // //===----------------------------------------------------------------------===// #include "mlir/Dialect/ArmSVE/ArmSVEDialect.h" #include "mlir/Dialect/LLVMIR/LLVMTypes.h" #include "mlir/Dialect/Vector/VectorOps.h" #include "mlir/IR/Builders.h" #include "mlir/IR/DialectImplementation.h" #include "mlir/IR/OpImplementation.h" #include "mlir/IR/TypeUtilities.h" #include "llvm/ADT/TypeSwitch.h" using namespace mlir; using namespace arm_sve; #include "mlir/Dialect/ArmSVE/ArmSVEDialect.cpp.inc" static Type getI1SameShape(Type type); static void buildScalableCmpIOp(OpBuilder &build, OperationState &result, arith::CmpIPredicate predicate, Value lhs, Value rhs); static void buildScalableCmpFOp(OpBuilder &build, OperationState &result, arith::CmpFPredicate predicate, Value lhs, Value rhs); #define GET_OP_CLASSES #include "mlir/Dialect/ArmSVE/ArmSVE.cpp.inc" #define GET_TYPEDEF_CLASSES #include "mlir/Dialect/ArmSVE/ArmSVETypes.cpp.inc" void ArmSVEDialect::initialize() { addOperations< #define GET_OP_LIST #include "mlir/Dialect/ArmSVE/ArmSVE.cpp.inc" >(); addTypes< #define GET_TYPEDEF_LIST #include "mlir/Dialect/ArmSVE/ArmSVETypes.cpp.inc" >(); } //===----------------------------------------------------------------------===// // ScalableVectorType //===----------------------------------------------------------------------===// void ScalableVectorType::print(AsmPrinter &printer) const { printer << "<"; for (int64_t dim : getShape()) printer << dim << 'x'; printer << getElementType() << '>'; } Type ScalableVectorType::parse(AsmParser &parser) { SmallVector<int64_t> dims; Type eltType; if (parser.parseLess() || parser.parseDimensionList(dims, /*allowDynamic=*/false) || parser.parseType(eltType) || parser.parseGreater()) return {}; return ScalableVectorType::get(eltType.getContext(), dims, eltType); } //===----------------------------------------------------------------------===// // ScalableVector versions of general helpers for comparison ops //===----------------------------------------------------------------------===// // Return the scalable vector of the same shape and containing i1. static Type getI1SameShape(Type type) { auto i1Type = IntegerType::get(type.getContext(), 1); if (auto sVectorType = type.dyn_cast<ScalableVectorType>()) return ScalableVectorType::get(type.getContext(), sVectorType.getShape(), i1Type); return nullptr; } //===----------------------------------------------------------------------===// // CmpFOp //===----------------------------------------------------------------------===// static void buildScalableCmpFOp(OpBuilder &build, OperationState &result, arith::CmpFPredicate predicate, Value lhs, Value rhs) { result.addOperands({lhs, rhs}); result.types.push_back(getI1SameShape(lhs.getType())); result.addAttribute(ScalableCmpFOp::getPredicateAttrName(), build.getI64IntegerAttr(static_cast<int64_t>(predicate))); } static void buildScalableCmpIOp(OpBuilder &build, OperationState &result, arith::CmpIPredicate predicate, Value lhs, Value rhs) { result.addOperands({lhs, rhs}); result.types.push_back(getI1SameShape(lhs.getType())); result.addAttribute(ScalableCmpIOp::getPredicateAttrName(), build.getI64IntegerAttr(static_cast<int64_t>(predicate))); }
38.065421
80
0.57206
jinge90
482fa342f6894b7348fd53358f2a5855d85cd4f5
74,542
cpp
C++
gazebo_lwr4_simulator/src/gazebo_kuka_lwr/src/kuka_lwr_plugin.cpp
mfigat/public_rshpn_tool
3555cb8f1eb35ef12441b9aef63dae8f578c2aa7
[ "BSD-3-Clause" ]
null
null
null
gazebo_lwr4_simulator/src/gazebo_kuka_lwr/src/kuka_lwr_plugin.cpp
mfigat/public_rshpn_tool
3555cb8f1eb35ef12441b9aef63dae8f578c2aa7
[ "BSD-3-Clause" ]
null
null
null
gazebo_lwr4_simulator/src/gazebo_kuka_lwr/src/kuka_lwr_plugin.cpp
mfigat/public_rshpn_tool
3555cb8f1eb35ef12441b9aef63dae8f578c2aa7
[ "BSD-3-Clause" ]
null
null
null
// ################################################################################################### /* Choose either GAZEBO_CALCULATIONS or EXTERNAL_CALCULATIONS */ //#define GAZEBO_CALCULATIONS /* calculation done in gazebo, no shared memory utilised */ #define EXTERNAL_CALCULATIONS /* calculation done in external process, data sent through share memory */ // ################################################################################################### // ############################################## #define CALCULATE_SAMPLING_PERIOD /* An information whether the sampling period has to be calculated - leave it if you want to calculate sampling period otherwise comment it */ // ############################################## //#define PRINT_DEBUG_INFO /* if defined all cout will be printed otherwise all information will not be printed to the console */ // ########################################## #include <iostream> #include <fstream> // ################ #include <chrono> // needed to get the current time #include <ctime> // ################ #include <functional> #include <gazebo/gazebo.hh> #include <gazebo/physics/physics.hh> #include <gazebo/common/common.hh> #include <ignition/math/Vector3.hh> // Communication #include <gazebo/transport/transport.hh> #include <gazebo/msgs/msgs.hh> // Kuka communication messages - my own //#include "msgs/kuka_joints.pb.h" #include "kuka_joints.pb.h" // lwr4_kinematics_dynamics - moja biblioteka #include "../../../../my_libs/lwr4_kinematics_dynamics/lwr4_kinematics_dynamics.h" // shared memory - moja biblioteka #include "../../../../my_libs/shared_memory/shared_memory.h" //#define gravity_constant 9.80665 // gravity acceleration - from General Conference on Weights and Measures - 1901 year #define gravity_constant 9.81 // gravity acceleration - option 2 #define L1 0.2 // według gazebo 0.2005 // 0.2 // l1=0.2m #define L2 0.2 // l2=0.2m #define L3 0.2 // l3=0.2m #define L4 0.195 // l4=0.195m #define L5 0.195 // według gazebo 0.2 //0.195 // l5=0.195m #define D1 0.31 // d1=0.31m #define D3 0.4 // d3=0.4m #define D5 0.39 // d5=0.39m #define D7 0.078 // d7=0.078m #define OPTION_1 //#define OPTION_2 #ifdef GAZEBO_CALCULATIONS // for GAZEBO_CALCULATIONS #define MAX_ITERATIONS 360 #define ITERATIONS_IN_ONE_CYCLE 50 #endif // GAZEBO_CALCULATIONS #ifdef EXTERNAL_CALCULATIONS // for EXTERNAL_CALCULATIONS #define MAX_ITERATIONS 360 #define ITERATIONS_IN_ONE_CYCLE 50 #endif // EXTERNAL_CALCULATIONS //std::array<double,7> equilibrium_global={0.04, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4}; namespace gazebo { class ModelKukaLwr : public ModelPlugin { // pointer to Int message typedef const boost::shared_ptr<const gazebo::msgs::Any> AnyPtr; typedef const boost::shared_ptr<const kuka_joints_msgs::KukaJoints> KukaJointsPtr; // Load function public: void Load(physics::ModelPtr _parent, sdf::ElementPtr /*_sdf*/) { // Stores the pointer to the model this->model_ = _parent; // Listen to the update event. This event is broadcast every simulation iteration. // connects OnUpadate method to the world update start signal this->updateConnection = event::Events::ConnectWorldUpdateBegin( std::bind(&ModelKukaLwr::OnUpdate, this)); #ifdef PRINT_DEBUG_INFO std::cout << "plugin loaded" << std::endl; #endif // #################################################### // test // set equilibrium to base position //equilibrium= {0.04, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4}; // equilibrium joint position equilibrium= {0, 0, 0, 1.57, 0, 0, 0}; // equilibrium joint position equilibrium_x=0.56; equilibrium_y=0.17; equilibrium_z=0.8; equilibrium_roll=0; equilibrium_pitch=0; equilibrium_yaw=0; eq_0_step=0.001; // eq_3_step=0.001; kinematic_chain_index=0; // #################################################### const std::string name = "lwr"; for (int i = 0; i < 7; ++i) { std::string joint_name = std::string("lwr::") + name + "_arm_" + std::to_string(i) + "_joint"; joints_.push_back(model_->GetJoint(joint_name)); // add joint to joints_ vector (added joint is found from the model based on its name) } for (int i = 0; i < 7; ++i) { std::string link_name = std::string("lwr::") + name + "_arm_" + std::to_string(i+1) + "_link"; links_.push_back(model_->GetLink(link_name)); // analogously like in joints } // ############################################ // subscribe to specific topic, e.g. ~/test/maxym // create node for communication gazebo::transport::NodePtr node(new gazebo::transport::Node); node->Init(); // listen to gazebo ~/test/maxym topic sub=node->Subscribe("~/test/maxym", &ModelKukaLwr::subscribe_callback_function, this); // ############################################### // subscribe to kuka_joints topic gazebo::transport::NodePtr node_kuka_joints(new gazebo::transport::Node); node_kuka_joints->Init(); sub_kuka_joints=node_kuka_joints->Subscribe("~/kuka_joints", &ModelKukaLwr::subscribe_callback_function_kuka_joints, this); _iterations=0; _iterations2=0; _flag=true; // add to vector the base position saveBasePoseToFile(); // tests // shared memory test #ifdef EXTERNAL_CALCULATIONS /* if data are calculated in external process and transfered through shared memory */ std::cout<<"SetUpSharedMemory"<<std::endl; setUpSharedMemory(); #endif // ########################### #ifdef CALCULATE_SAMPLING_PERIOD start_time=std::chrono::system_clock::now(); #endif // CALCULATE_SAMPLING_PERIOD // ############################# // ############################################ } // end of function Load #ifdef EXTERNAL_CALCULATIONS /* Set up shared memory */ void setUpSharedMemory(){ //#ifdef PRINT_DEBUG_INFO std::cout<<"[EXTERNAL_CALCULATIONS] - setUpSharedMemory"<<std::endl; //#endif //shm_producer= new SharedMemory<float>("shared_memory_float", SharedMemoryType::Producer); /* shared memory - test */ shm_torque_consumer= new SharedMemory<struct lwr4_joints>("shared_memory_torque", SharedMemoryType::Consumer); /* Consumer of torque data received from shared memory */ shm_parameters_producer= new SharedMemory<struct lwr4_kinematics_params>("shared_memory_lwr4_kinematics_params", SharedMemoryType::Producer); /* Consumer of torque data received from shared memory */ } #endif // set forces to joints based on given torques void setForces(const std::array<double, 7 > &t) { for (int i=0; i<joints_.size(); i++) { joints_[i]->SetForce(0, t[i]); // axis 0 jest default //std::cout<<"Torque["<<i<<"]="<<t[i]<<std::endl; } } // end of function setForces double gravity_compensation_joint_7(){ double tau=0; return tau; } double gravity_compensation_joint_6(){ double g=gravity_constant; double m6 = links_[5]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double m7 = links_[6]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double d7= D7, d5 = D5, d3=D3, d1=D1; double theta1=joints_[0]->Position(0); double theta2=joints_[1]->Position(0); double theta3=joints_[2]->Position(0); double theta4=joints_[3]->Position(0); double theta5=joints_[4]->Position(0); double theta6=joints_[5]->Position(0); double theta7=joints_[6]->Position(0); double c1=cos(theta1), c2=cos(theta2), c3=cos(theta3), c4=cos(theta4), c5=cos(theta5), c6=cos(theta6), c7=cos(theta7); double s1=sin(theta1), s2=sin(theta2), s3=sin(theta3), s4=sin(theta4), s5=sin(theta5), s6=sin(theta6), s7=sin(theta7); double tau=0; #ifdef OPTION_1 // wersja nr 1 /* tau=-d7*(c7*m7*(s7*(s5*(c2*g*s4 - c3*c4*g*s2) - c5*g*s2*s3) + c7*(s6*(c2*c4*g + c3*g*s2*s4) - c6*(c5*(c2*g*s4 - c3*c4*g*s2) + g*s2*s3*s5))) + m7*s7*(s7*(s6*(c2*c4*g + c3*g*s2*s4) - c6*(c5*(c2*g*s4 - c3*c4*g*s2) + g*s2*s3*s5)) - c7*(s5*(c2*g*s4 - c3*c4*g*s2) - c5*g*s2*s3))); */ //tau=-(m6*(s6*(c2*c4*g + c3*g*s2*s4) - c6*(c5*(c2*g*s4 - c3*c4*g*s2) + g*s2*s3*s5)))/16.0; tau=-(m6*(s6*(c2*c4*g + c3*g*s2*s4) - c6*(c5*(c2*g*s4 - c3*c4*g*s2) + g*s2*s3*s5)))/16.0; #endif return tau; } ///////////////////////////////////////////// double gravity_compensation_joint_5(){ //std::cout<<"sin="<<sin(1.57)<<std::endl; double g=gravity_constant; double m5 = links_[4]->GetInertial()->Mass(); // because 4-th link in links_ is in fact 5-th link of the lwr4+ manipulator double m6 = links_[5]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double m7 = links_[6]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double d7= D7, d5 = D5, d3=D3, d1=D1; double l5= L5; double theta1=joints_[0]->Position(0); double theta2=joints_[1]->Position(0); double theta3=joints_[2]->Position(0); double theta4=joints_[3]->Position(0); double theta5=joints_[4]->Position(0); double theta6=joints_[5]->Position(0); double theta7=joints_[6]->Position(0); double c1=cos(theta1), c2=cos(theta2), c3=cos(theta3), c4=cos(theta4), c5=cos(theta5), c6=cos(theta6), c7=cos(theta7); double s1=sin(theta1), s2=sin(theta2), s3=sin(theta3), s4=sin(theta4), s5=sin(theta5), s6=sin(theta6), s7=sin(theta7); double tau=0; #ifdef OPTION_1 // wersja nr 1 /* */ //tau=(g*m6*s6*(c5*s2*s3 - c2*s4*s5 + c3*c4*s2*s5))/16.0; tau=(g*m6*s6*(c5*s2*s3 - c2*s4*s5 + c3*c4*s2*s5))/16.0; #ifdef PRINT_DEBUG_INFO std::cout<<"tau5="<<tau<<std::endl; #endif #endif return tau; } double gravity_compensation_joint_4(){ //std::cout<<"sin="<<sin(1.57)<<std::endl; double g=gravity_constant; double m4 = links_[3]->GetInertial()->Mass(); // because 3-th link in links_ is in fact 4-th link of the lwr4+ manipulator double m5 = links_[4]->GetInertial()->Mass(); // because 4-th link in links_ is in fact 5-th link of the lwr4+ manipulator double m6 = links_[5]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double m7 = links_[6]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double d7= D7, d5 = D5, d3=D3, d1=D1; double l5= L5, l4=L4; double theta1=joints_[0]->Position(0); double theta2=joints_[1]->Position(0); double theta3=joints_[2]->Position(0); double theta4=joints_[3]->Position(0); double theta5=joints_[4]->Position(0); double theta6=joints_[5]->Position(0); double theta7=joints_[6]->Position(0); double c1=cos(theta1), c2=cos(theta2), c3=cos(theta3), c4=cos(theta4), c5=cos(theta5), c6=cos(theta6), c7=cos(theta7); double s1=sin(theta1), s2=sin(theta2), s3=sin(theta3), s4=sin(theta4), s5=sin(theta5), s6=sin(theta6), s7=sin(theta7); double tau=0; #ifdef OPTION_1 // wersja nr 1 /* */ // tau=(g*(140*c3*c4*m4*s2 - 140*c2*m4*s4 + 152*c2*c5*c5*m5*s4 + 152*c2*m5*s4*s5*s5 + 125*c2*c4*c5*m6*s6 - 152*c3*c4*c5*c5*m5*s2 - 125*c2*c5*c5*c6*m6*s4 - 2000*c2*c5*c5*d5*m5*s4 - 152*c3*c4*m5*s2*s5*s5 - 125*c2*c6*m6*s4*s5*s5 - 2000*c2*d5*m5*s4*s5*s5 - 2000*c2*d5*m6*s4*s5*s5 + 125*c3*c4*c5*c5*c6*m6*s2 + 2000*c3*c4*c5*c5*d5*m5*s2 + 125*c3*c4*c6*m6*s2*s5*s5 + 2000*c3*c4*d5*m5*s2*s5*s5 + 2000*c3*c4*d5*m6*s2*s5*s5 - 2000*c2*c5*c5*c6*c6*d5*m6*s4 - 2000*c2*c5*c5*d5*m6*s4*s6*s6 + 125*c3*c5*m6*s2*s4*s6 + 2000*c5*d5*m6*s2*s3*s5 - 2000*c5*c6*c6*d5*m6*s2*s3*s5 - 2000*c5*d5*m6*s2*s3*s5*s6*s6 + 2000*c3*c4*c5*c5*c6*c6*d5*m6*s2 + 2000*c3*c4*c5*c5*d5*m6*s2*s6*s6))/2000.0; //tau=(g*(180*c3*c4*m4*s2 - 180*c2*m4*s4 + 152*c2*c5*c5*m5*s4 + 152*c2*m5*s4*s5*s5 + 125*c2*c4*c5*m6*s6 - 152*c3*c4*c5*c5*m5*s2 - 125*c2*c5*c5*c6*m6*s4 - 2000*c2*c5*c5*d5*m5*s4 - 152*c3*c4*m5*s2*s5*s5 - 125*c2*c6*m6*s4*s5*s5 - 2000*c2*d5*m5*s4*s5*s5 - 2000*c2*d5*m6*s4*s5*s5 + 125*c3*c4*c5*c5*c6*m6*s2 + 2000*c3*c4*c5*c5*d5*m5*s2 + 125*c3*c4*c6*m6*s2*s5*s5 + 2000*c3*c4*d5*m5*s2*s5*s5 + 2000*c3*c4*d5*m6*s2*s5*s5 - 2000*c2*c5*c5*c6*c6*d5*m6*s4 - 2000*c2*c5*c5*d5*m6*s4*s6*s6 + 125*c3*c5*m6*s2*s4*s6 + 2000*c5*d5*m6*s2*s3*s5 - 2000*c5*c6*c6*d5*m6*s2*s3*s5 - 2000*c5*d5*m6*s2*s3*s5*s6*s6 + 2000*c3*c4*c5*c5*c6*c6*d5*m6*s2 + 2000*c3*c4*c5*c5*d5*m6*s2*s6*s6))/2000.0; tau=(g*(160*c3*c4*m4*s2 - 160*c2*m4*s4 + 152*c2*c5*c5*m5*s4 + 152*c2*m5*s4*s5*s5 + 125*c2*c4*c5*m6*s6 - 152*c3*c4*c5*c5*m5*s2 - 125*c2*c5*c5*c6*m6*s4 - 2000*c2*c5*c5*d5*m5*s4 - 152*c3*c4*m5*s2*s5*s5 - 125*c2*c6*m6*s4*s5*s5 - 2000*c2*d5*m5*s4*s5*s5 - 2000*c2*d5*m6*s4*s5*s5 + 125*c3*c4*c5*c5*c6*m6*s2 + 2000*c3*c4*c5*c5*d5*m5*s2 + 125*c3*c4*c6*m6*s2*s5*s5 + 2000*c3*c4*d5*m5*s2*s5*s5 + 2000*c3*c4*d5*m6*s2*s5*s5 - 2000*c2*c5*c5*c6*c6*d5*m6*s4 - 2000*c2*c5*c5*d5*m6*s4*s6*s6 + 125*c3*c5*m6*s2*s4*s6 + 2000*c5*d5*m6*s2*s3*s5 - 2000*c5*c6*c6*d5*m6*s2*s3*s5 - 2000*c5*d5*m6*s2*s3*s5*s6*s6 + 2000*c3*c4*c5*c5*c6*c6*d5*m6*s2 + 2000*c3*c4*c5*c5*d5*m6*s2*s6*s6))/2000.0; #endif return tau; } double gravity_compensation_joint_3(){ //std::cout<<"sin="<<sin(1.57)<<std::endl; double g=gravity_constant; double m3 = links_[2]->GetInertial()->Mass(); // because 3-th link in links_ is in fact 4-th link of the lwr4+ manipulator double m4 = links_[3]->GetInertial()->Mass(); // because 3-th link in links_ is in fact 4-th link of the lwr4+ manipulator double m5 = links_[4]->GetInertial()->Mass(); // because 4-th link in links_ is in fact 5-th link of the lwr4+ manipulator double m6 = links_[5]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double m7 = links_[6]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double d7= D7, d5 = D5, d3=D3, d1=D1; double l5= L5, l4=L4, l3=L3; double theta1=joints_[0]->Position(0); double theta2=joints_[1]->Position(0); double theta3=joints_[2]->Position(0); double theta4=joints_[3]->Position(0); double theta5=joints_[4]->Position(0); double theta6=joints_[5]->Position(0); double theta7=joints_[6]->Position(0); double c1=cos(theta1), c2=cos(theta2), c3=cos(theta3), c4=cos(theta4), c5=cos(theta5), c6=cos(theta6), c7=cos(theta7); double s1=sin(theta1), s2=sin(theta2), s3=sin(theta3), s4=sin(theta4), s5=sin(theta5), s6=sin(theta6), s7=sin(theta7); double tau=0; #ifdef OPTION_1 // wersja nr 1 /* */ //tau=-(g*(140*m4*s2*s3*s4 - 120*c3*m3*s2 + 120*c3*c4*c4*m4*s2 + 120*c3*m4*s2*s4*s4 - 152*c5*c5*m5*s2*s3*s4 - 152*m5*s2*s3*s4*s5*s5 - 2000*c2*c5*d5*m6*s4*s4*s5 - 125*c3*c4*c4*m6*s2*s5*s6 + 125*c5*c5*c6*m6*s2*s3*s4 + 2000*c5*c5*d5*m5*s2*s3*s4 + 2000*c5*c5*d5*m6*s2*s3*s4 - 125*c3*m6*s2*s4*s4*s5*s6 + 125*c6*m6*s2*s3*s4*s5*s5 + 2000*d5*m5*s2*s3*s4*s5*s5 - 125*c4*c5*m6*s2*s3*s6 + 2000*c2*c5*d5*m6*s4*s4*s5*s6*s6 + 2000*c6*c6*d5*m6*s2*s3*s4*s5*s5 + 2000*d5*m6*s2*s3*s4*s5*s5*s6*s6 + 2000*c2*c5*c6*c6*d5*m6*s4*s4*s5 + 2000*c3*c4*c5*d5*m6*s2*s4*s5 - 2000*c3*c4*c5*c6*c6*d5*m6*s2*s4*s5 - 2000*c3*c4*c5*d5*m6*s2*s4*s5*s6*s6))/2000.0; tau=-(g*(160*m4*s2*s3*s4 - 120*c3*m3*s2 + 120*c3*c4*c4*m4*s2 + 120*c3*m4*s2*s4*s4 - 152*c5*c5*m5*s2*s3*s4 - 152*m5*s2*s3*s4*s5*s5 - 2000*c2*c5*d5*m6*s4*s4*s5 - 125*c3*c4*c4*m6*s2*s5*s6 + 125*c5*c5*c6*m6*s2*s3*s4 + 2000*c5*c5*d5*m5*s2*s3*s4 + 2000*c5*c5*d5*m6*s2*s3*s4 - 125*c3*m6*s2*s4*s4*s5*s6 + 125*c6*m6*s2*s3*s4*s5*s5 + 2000*d5*m5*s2*s3*s4*s5*s5 - 125*c4*c5*m6*s2*s3*s6 + 2000*c2*c5*d5*m6*s4*s4*s5*s6*s6 + 2000*c6*c6*d5*m6*s2*s3*s4*s5*s5 + 2000*d5*m6*s2*s3*s4*s5*s5*s6*s6 + 2000*c2*c5*c6*c6*d5*m6*s4*s4*s5 + 2000*c3*c4*c5*d5*m6*s2*s4*s5 - 2000*c3*c4*c5*c6*c6*d5*m6*s2*s4*s5 - 2000*c3*c4*c5*d5*m6*s2*s4*s5*s6*s6))/2000.0; #endif return tau; } double gravity_compensation_joint_2(){ double g=gravity_constant; double m2 = links_[1]->GetInertial()->Mass(); // because 1-th link in links_ is in fact 2-th link of the lwr4+ manipulator double m3 = links_[2]->GetInertial()->Mass(); // because 2-th link in links_ is in fact 3-th link of the lwr4+ manipulator double m4 = links_[3]->GetInertial()->Mass(); // because 3-th link in links_ is in fact 4-th link of the lwr4+ manipulator double m5 = links_[4]->GetInertial()->Mass(); // because 4-th link in links_ is in fact 5-th link of the lwr4+ manipulator double m6 = links_[5]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double m7 = links_[6]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double d7= D7, d5 = D5, d3=D3, d1=D1; double l5= L5, l4=L4, l3=L3, l2=L2; double theta1=joints_[0]->Position(0); double theta2=joints_[1]->Position(0); double theta3=joints_[2]->Position(0); double theta4=joints_[3]->Position(0); double theta5=joints_[4]->Position(0); double theta6=joints_[5]->Position(0); double theta7=joints_[6]->Position(0); double c1=cos(theta1), c2=cos(theta2), c3=cos(theta3), c4=cos(theta4), c5=cos(theta5), c6=cos(theta6), c7=cos(theta7); double s1=sin(theta1), s2=sin(theta2), s3=sin(theta3), s4=sin(theta4), s5=sin(theta5), s6=sin(theta6), s7=sin(theta7); double tau=0; #ifdef OPTION_1 // wersja nr 1 /* */ /* tau=-(g*(140*m2*s2 - 140*c3*c3*m3*s2 - 140*m3*s2*s3*s3 - 120*c2*m3*s3 - 140*c2*c3*m4*s4 + 120*c2*c4*c4*m4*s3 + 140*c3*c3*c4*m4*s2 + 2000*c3*c3*d3*m3*s2 + 120*c2*m4*s3*s4*s4 + 140*c4*m4*s2*s3*s3 + 2000*d3*m3*s2*s3*s3 + 2000*d3*m4*s2*s3*s3 - 152*c3*c3*c4*c5*c5*m5*s2 + 2000*c3*c3*c4*c4*d3*m4*s2 - 152*c4*c5*c5*m5*s2*s3*s3 - 152*c3*c3*c4*m5*s2*s5*s5 + 2000*c3*c3*d3*m4*s2*s4*s4 + 2000*c3*c3*d3*m5*s2*s4*s4 + 2000*c5*c5*d3*m5*s2*s3*s3 + 2000*c5*c5*d3*m6*s2*s3*s3 - 152*c4*m5*s2*s3*s3*s5*s5 + 2000*d3*m5*s2*s3*s3*s5*s5 + 152*c2*c3*c5*c5*m5*s4 + 152*c2*c3*m5*s4*s5*s5 + 2000*c3*c3*d3*m6*s2*s4*s4*s6*s6 + 2000*c6*c6*d3*m6*s2*s3*s3*s5*s5 + 2000*d3*m6*s2*s3*s3*s5*s5*s6*s6 - 125*c2*c3*c5*c5*c6*m6*s4 - 2000*c2*c3*c5*c5*d5*m5*s4 - 125*c2*c3*c6*m6*s4*s5*s5 - 2000*c2*c3*d5*m5*s4*s5*s5 - 2000*c2*c3*d5*m6*s4*s5*s5 - 125*c2*c4*c4*m6*s3*s5*s6 + 125*c3*c3*c5*m6*s2*s4*s6 - 125*c2*m6*s3*s4*s4*s5*s6 + 125*c5*m6*s2*s3*s3*s4*s6 + 125*c3*c3*c4*c5*c5*c6*m6*s2 + 2000*c3*c3*c4*c5*c5*d5*m5*s2 + 125*c4*c5*c5*c6*m6*s2*s3*s3 + 125*c3*c3*c4*c6*m6*s2*s5*s5 + 2000*c4*c5*c5*d5*m5*s2*s3*s3 + 2000*c3*c3*c4*d5*m5*s2*s5*s5 + 2000*c4*c5*c5*d5*m6*s2*s3*s3 + 2000*c3*c3*c4*d5*m6*s2*s5*s5 + 125*c4*c6*m6*s2*s3*s3*s5*s5 + 2000*c4*d5*m5*s2*s3*s3*s5*s5 + 125*c2*c3*c4*c5*m6*s6 + 2000*c2*c3*c4*d3*m5*s4 + 2000*c3*c3*c4*c4*c5*c5*d3*m5*s2 + 2000*c3*c3*c4*c4*d3*m5*s2*s5*s5 + 2000*c3*c3*c4*c4*d3*m6*s2*s5*s5 + 2000*c3*c3*c6*c6*d3*m6*s2*s4*s4 + 2000*c3*c3*c4*c5*c5*c6*c6*d5*m6*s2 - 2000*c2*c5*d3*m6*s3*s4*s5 + 2000*c3*c5*d5*m6*s2*s3*s5 + 2000*c3*c3*c4*c5*c5*d5*m6*s2*s6*s6 + 2000*c4*c6*c6*d5*m6*s2*s3*s3*s5*s5 + 2000*c4*d5*m6*s2*s3*s3*s5*s5*s6*s6 - 2000*c2*c3*c4*c5*c5*d3*m5*s4 + 2000*c2*c3*c4*c6*c6*d3*m6*s4 - 2000*c2*c3*c4*d3*m5*s4*s5*s5 - 2000*c2*c3*c4*d3*m6*s4*s5*s5 + 2000*c2*c3*c4*d3*m6*s4*s6*s6 + 2000*c3*c3*c4*c4*c5*c5*c6*c6*d3*m6*s2 + 2000*c3*c3*c4*c4*c5*c5*d3*m6*s2*s6*s6 - 2000*c2*c3*c5*c5*c6*c6*d5*m6*s4 - 2000*c2*c3*c5*c5*d5*m6*s4*s6*s6 + 2000*c3*c4*c4*c5*d5*m6*s2*s3*s5 + 2000*c2*c5*c6*c6*d3*m6*s3*s4*s5 - 2000*c3*c5*c6*c6*d5*m6*s2*s3*s5 + 2000*c2*c5*d3*m6*s3*s4*s5*s6*s6 - 2000*c3*c5*d5*m6*s2*s3*s5*s6*s6 - 2000*c2*c3*c4*c5*c5*c6*c6*d3*m6*s4 - 2000*c2*c3*c4*c5*c5*d3*m6*s4*s6*s6 + 4000*c3*c4*c5*d3*m6*s2*s3*s5 - 2000*c2*c4*c5*d5*m6*s3*s4*s5 - 4000*c3*c4*c5*c6*c6*d3*m6*s2*s3*s5 + 2000*c2*c4*c5*c6*c6*d5*m6*s3*s4*s5 - 4000*c3*c4*c5*d3*m6*s2*s3*s5*s6*s6 + 2000*c2*c4*c5*d5*m6*s3*s4*s5*s6*s6 - 2000*c3*c4*c4*c5*c6*c6*d5*m6*s2*s3*s5 - 2000*c3*c4*c4*c5*d5*m6*s2*s3*s5*s6*s6))/2000.0; */ tau=-(g*(140*m2*s2 - 140*c3*c3*m3*s2 - 140*m3*s2*s3*s3 - 120*c2*m3*s3 - 160*c2*c3*m4*s4 + 120*c2*c4*c4*m4*s3 + 160*c3*c3*c4*m4*s2 + 2000*c3*c3*d3*m3*s2 + 120*c2*m4*s3*s4*s4 + 160*c4*m4*s2*s3*s3 + 2000*d3*m3*s2*s3*s3 + 2000*d3*m4*s2*s3*s3 - 152*c3*c3*c4*c5*c5*m5*s2 + 2000*c3*c3*c4*c4*d3*m4*s2 - 152*c4*c5*c5*m5*s2*s3*s3 - 152*c3*c3*c4*m5*s2*s5*s5 + 2000*c3*c3*d3*m4*s2*s4*s4 + 2000*c3*c3*d3*m5*s2*s4*s4 + 2000*c5*c5*d3*m5*s2*s3*s3 + 2000*c5*c5*d3*m6*s2*s3*s3 - 152*c4*m5*s2*s3*s3*s5*s5 + 2000*d3*m5*s2*s3*s3*s5*s5 + 152*c2*c3*c5*c5*m5*s4 + 152*c2*c3*m5*s4*s5*s5 + 2000*c3*c3*d3*m6*s2*s4*s4*s6*s6 + 2000*c6*c6*d3*m6*s2*s3*s3*s5*s5 + 2000*d3*m6*s2*s3*s3*s5*s5*s6*s6 - 125*c2*c3*c5*c5*c6*m6*s4 - 2000*c2*c3*c5*c5*d5*m5*s4 - 125*c2*c3*c6*m6*s4*s5*s5 - 2000*c2*c3*d5*m5*s4*s5*s5 - 2000*c2*c3*d5*m6*s4*s5*s5 - 125*c2*c4*c4*m6*s3*s5*s6 + 125*c3*c3*c5*m6*s2*s4*s6 - 125*c2*m6*s3*s4*s4*s5*s6 + 125*c5*m6*s2*s3*s3*s4*s6 + 125*c3*c3*c4*c5*c5*c6*m6*s2 + 2000*c3*c3*c4*c5*c5*d5*m5*s2 + 125*c4*c5*c5*c6*m6*s2*s3*s3 + 125*c3*c3*c4*c6*m6*s2*s5*s5 + 2000*c4*c5*c5*d5*m5*s2*s3*s3 + 2000*c3*c3*c4*d5*m5*s2*s5*s5 + 2000*c4*c5*c5*d5*m6*s2*s3*s3 + 2000*c3*c3*c4*d5*m6*s2*s5*s5 + 125*c4*c6*m6*s2*s3*s3*s5*s5 + 2000*c4*d5*m5*s2*s3*s3*s5*s5 + 125*c2*c3*c4*c5*m6*s6 + 2000*c2*c3*c4*d3*m5*s4 + 2000*c3*c3*c4*c4*c5*c5*d3*m5*s2 + 2000*c3*c3*c4*c4*d3*m5*s2*s5*s5 + 2000*c3*c3*c4*c4*d3*m6*s2*s5*s5 + 2000*c3*c3*c6*c6*d3*m6*s2*s4*s4 + 2000*c3*c3*c4*c5*c5*c6*c6*d5*m6*s2 - 2000*c2*c5*d3*m6*s3*s4*s5 + 2000*c3*c5*d5*m6*s2*s3*s5 + 2000*c3*c3*c4*c5*c5*d5*m6*s2*s6*s6 + 2000*c4*c6*c6*d5*m6*s2*s3*s3*s5*s5 + 2000*c4*d5*m6*s2*s3*s3*s5*s5*s6*s6 - 2000*c2*c3*c4*c5*c5*d3*m5*s4 + 2000*c2*c3*c4*c6*c6*d3*m6*s4 - 2000*c2*c3*c4*d3*m5*s4*s5*s5 - 2000*c2*c3*c4*d3*m6*s4*s5*s5 + 2000*c2*c3*c4*d3*m6*s4*s6*s6 + 2000*c3*c3*c4*c4*c5*c5*c6*c6*d3*m6*s2 + 2000*c3*c3*c4*c4*c5*c5*d3*m6*s2*s6*s6 - 2000*c2*c3*c5*c5*c6*c6*d5*m6*s4 - 2000*c2*c3*c5*c5*d5*m6*s4*s6*s6 + 2000*c3*c4*c4*c5*d5*m6*s2*s3*s5 + 2000*c2*c5*c6*c6*d3*m6*s3*s4*s5 - 2000*c3*c5*c6*c6*d5*m6*s2*s3*s5 + 2000*c2*c5*d3*m6*s3*s4*s5*s6*s6 - 2000*c3*c5*d5*m6*s2*s3*s5*s6*s6 - 2000*c2*c3*c4*c5*c5*c6*c6*d3*m6*s4 - 2000*c2*c3*c4*c5*c5*d3*m6*s4*s6*s6 + 4000*c3*c4*c5*d3*m6*s2*s3*s5 - 2000*c2*c4*c5*d5*m6*s3*s4*s5 - 4000*c3*c4*c5*c6*c6*d3*m6*s2*s3*s5 + 2000*c2*c4*c5*c6*c6*d5*m6*s3*s4*s5 - 4000*c3*c4*c5*d3*m6*s2*s3*s5*s6*s6 + 2000*c2*c4*c5*d5*m6*s3*s4*s5*s6*s6 - 2000*c3*c4*c4*c5*c6*c6*d5*m6*s2*s3*s5 - 2000*c3*c4*c4*c5*d5*m6*s2*s3*s5*s6*s6))/2000.0; #endif return tau; } double gravity_compensation_joint_1(){ double g=gravity_constant; double m1 = links_[0]->GetInertial()->Mass(); // because 0-th link in links_ is in fact 1-th link of the lwr4+ manipulator double m2 = links_[1]->GetInertial()->Mass(); // because 1-th link in links_ is in fact 2-th link of the lwr4+ manipulator double m3 = links_[2]->GetInertial()->Mass(); // because 2-th link in links_ is in fact 3-th link of the lwr4+ manipulator double m4 = links_[3]->GetInertial()->Mass(); // because 3-th link in links_ is in fact 4-th link of the lwr4+ manipulator double m5 = links_[4]->GetInertial()->Mass(); // because 4-th link in links_ is in fact 5-th link of the lwr4+ manipulator double m6 = links_[5]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator double m7 = links_[6]->GetInertial()->Mass(); // because 5-th link in links_ is in fact 6-th link of the lwr4+ manipulator #ifdef PRINT_DEBUG_INFO std::cout<<"M1="<<m1<<std::endl; std::cout<<"M2="<<m2<<std::endl; std::cout<<"M3="<<m3<<std::endl; std::cout<<"M4="<<m4<<std::endl; std::cout<<"M5="<<m5<<std::endl; std::cout<<"M6="<<m6<<std::endl; std::cout<<"M7="<<m7<<std::endl; #endif double d7= D7, d5 = D5, d3=D3, d1=D1; double l5= L5, l4=L4, l3=L3, l2=L2, l1=L1; double theta1=joints_[0]->Position(0); double theta2=joints_[1]->Position(0); double theta3=joints_[2]->Position(0); double theta4=joints_[3]->Position(0); double theta5=joints_[4]->Position(0); double theta6=joints_[5]->Position(0); double theta7=joints_[6]->Position(0); double c1=cos(theta1), c2=cos(theta2), c3=cos(theta3), c4=cos(theta4), c5=cos(theta5), c6=cos(theta6), c7=cos(theta7); double s1=sin(theta1), s2=sin(theta2), s3=sin(theta3), s4=sin(theta4), s5=sin(theta5), s6=sin(theta6), s7=sin(theta7); double tau=0; #ifdef OPTION_1 // wersja nr 1 /* tau=-g*(c3*c4*c4*d3*m4*s2*s2*s3 - c3*d3*m4*s2*s2*s3 - c3*c5*c5*d3*m5*s2*s2*s3 - c3*c5*c5*d3*m6*s2*s2*s3 - c2*c2*c5*d5*m6*s4*s4*s5 + c3*d3*m4*s2*s2*s3*s4*s4 + c3*d3*m5*s2*s2*s3*s4*s4 - c3*d3*m5*s2*s2*s3*s5*s5 + c5*d5*m6*s2*s2*s3*s3*s5 + c3*c4*d5*m6*s2*s2*s3*s5*s5 + c4*c5*d3*m6*s2*s2*s3*s3*s5 + c2*c4*d3*m5*s2*s3*s4 + c3*c4*c4*c5*c5*d3*m5*s2*s2*s3 - c3*c3*c4*c4*c5*d5*m6*s2*s2*s5 + c2*c2*c5*c6*c6*d5*m6*s4*s4*s5 + c3*c4*c4*d3*m5*s2*s2*s3*s5*s5 + c3*c4*c4*d3*m6*s2*s2*s3*s5*s5 + c3*c6*c6*d3*m6*s2*s2*s3*s4*s4 - c3*c6*c6*d3*m6*s2*s2*s3*s5*s5 - c5*c6*c6*d5*m6*s2*s2*s3*s3*s5 + c2*c2*c5*d5*m6*s4*s4*s5*s6*s6 + c3*d3*m6*s2*s2*s3*s4*s4*s6*s6 - c3*d3*m6*s2*s2*s3*s5*s5*s6*s6 - c5*d5*m6*s2*s2*s3*s3*s5*s6*s6 + c2*c5*c5*d5*m6*s2*s3*s4 - c2*d5*m6*s2*s3*s4*s5*s5 - c3*c4*c5*c5*d5*m6*s2*s2*s3 - c3*c3*c4*c5*d3*m6*s2*s2*s5 - c2*c4*c5*c5*d3*m5*s2*s3*s4 + c2*c4*c6*c6*d3*m6*s2*s3*s4 + c3*c4*c4*c5*c5*c6*c6*d3*m6*s2*s2*s3 + c3*c3*c4*c4*c5*c6*c6*d5*m6*s2*s2*s5 - c2*c4*d3*m5*s2*s3*s4*s5*s5 - c2*c4*d3*m6*s2*s3*s4*s5*s5 + c2*c4*d3*m6*s2*s3*s4*s6*s6 + c3*c4*c4*c5*c5*d3*m6*s2*s2*s3*s6*s6 + c3*c3*c4*c4*c5*d5*m6*s2*s2*s5*s6*s6 - c2*c5*c5*c6*c6*d5*m6*s2*s3*s4 - c2*c5*c5*d5*m6*s2*s3*s4*s6*s6 + c2*c6*c6*d5*m6*s2*s3*s4*s5*s5 + c2*d5*m6*s2*s3*s4*s5*s5*s6*s6 + c2*c3*c5*d3*m6*s2*s4*s5 + c3*c4*c5*c5*c6*c6*d5*m6*s2*s2*s3 + c3*c3*c4*c5*c6*c6*d3*m6*s2*s2*s5 + c3*c4*c5*c5*d5*m6*s2*s2*s3*s6*s6 - c3*c4*c6*c6*d5*m6*s2*s2*s3*s5*s5 - c4*c5*c6*c6*d3*m6*s2*s2*s3*s3*s5 + c3*c3*c4*c5*d3*m6*s2*s2*s5*s6*s6 - c3*c4*d5*m6*s2*s2*s3*s5*s5*s6*s6 - c4*c5*d3*m6*s2*s2*s3*s3*s5*s6*s6 + 2*c2*c3*c4*c5*d5*m6*s2*s4*s5 - c2*c3*c5*c6*c6*d3*m6*s2*s4*s5 - c2*c3*c5*d3*m6*s2*s4*s5*s6*s6 - c2*c4*c5*c5*c6*c6*d3*m6*s2*s3*s4 - c2*c4*c5*c5*d3*m6*s2*s3*s4*s6*s6 - 2*c2*c3*c4*c5*c6*c6*d5*m6*s2*s4*s5 - 2*c2*c3*c4*c5*d5*m6*s2*s4*s5*s6*s6); */ tau=-g*(c3*c4*c4*d3*m4*s2*s2*s3 - c3*d3*m4*s2*s2*s3 - c3*c5*c5*d3*m5*s2*s2*s3 - c3*c5*c5*d3*m6*s2*s2*s3 - c2*c2*c5*d5*m6*s4*s4*s5 + c3*d3*m4*s2*s2*s3*s4*s4 + c3*d3*m5*s2*s2*s3*s4*s4 - c3*d3*m5*s2*s2*s3*s5*s5 + c5*d5*m6*s2*s2*s3*s3*s5 + c3*c4*d5*m6*s2*s2*s3*s5*s5 + c4*c5*d3*m6*s2*s2*s3*s3*s5 + c2*c4*d3*m5*s2*s3*s4 + c3*c4*c4*c5*c5*d3*m5*s2*s2*s3 - c3*c3*c4*c4*c5*d5*m6*s2*s2*s5 + c2*c2*c5*c6*c6*d5*m6*s4*s4*s5 + c3*c4*c4*d3*m5*s2*s2*s3*s5*s5 + c3*c4*c4*d3*m6*s2*s2*s3*s5*s5 + c3*c6*c6*d3*m6*s2*s2*s3*s4*s4 - c3*c6*c6*d3*m6*s2*s2*s3*s5*s5 - c5*c6*c6*d5*m6*s2*s2*s3*s3*s5 + c2*c2*c5*d5*m6*s4*s4*s5*s6*s6 + c3*d3*m6*s2*s2*s3*s4*s4*s6*s6 - c3*d3*m6*s2*s2*s3*s5*s5*s6*s6 - c5*d5*m6*s2*s2*s3*s3*s5*s6*s6 + c2*c5*c5*d5*m6*s2*s3*s4 - c2*d5*m6*s2*s3*s4*s5*s5 - c3*c4*c5*c5*d5*m6*s2*s2*s3 - c3*c3*c4*c5*d3*m6*s2*s2*s5 - c2*c4*c5*c5*d3*m5*s2*s3*s4 + c2*c4*c6*c6*d3*m6*s2*s3*s4 + c3*c4*c4*c5*c5*c6*c6*d3*m6*s2*s2*s3 + c3*c3*c4*c4*c5*c6*c6*d5*m6*s2*s2*s5 - c2*c4*d3*m5*s2*s3*s4*s5*s5 - c2*c4*d3*m6*s2*s3*s4*s5*s5 + c2*c4*d3*m6*s2*s3*s4*s6*s6 + c3*c4*c4*c5*c5*d3*m6*s2*s2*s3*s6*s6 + c3*c3*c4*c4*c5*d5*m6*s2*s2*s5*s6*s6 - c2*c5*c5*c6*c6*d5*m6*s2*s3*s4 - c2*c5*c5*d5*m6*s2*s3*s4*s6*s6 + c2*c6*c6*d5*m6*s2*s3*s4*s5*s5 + c2*d5*m6*s2*s3*s4*s5*s5*s6*s6 + c2*c3*c5*d3*m6*s2*s4*s5 + c3*c4*c5*c5*c6*c6*d5*m6*s2*s2*s3 + c3*c3*c4*c5*c6*c6*d3*m6*s2*s2*s5 + c3*c4*c5*c5*d5*m6*s2*s2*s3*s6*s6 - c3*c4*c6*c6*d5*m6*s2*s2*s3*s5*s5 - c4*c5*c6*c6*d3*m6*s2*s2*s3*s3*s5 + c3*c3*c4*c5*d3*m6*s2*s2*s5*s6*s6 - c3*c4*d5*m6*s2*s2*s3*s5*s5*s6*s6 - c4*c5*d3*m6*s2*s2*s3*s3*s5*s6*s6 + 2*c2*c3*c4*c5*d5*m6*s2*s4*s5 - c2*c3*c5*c6*c6*d3*m6*s2*s4*s5 - c2*c3*c5*d3*m6*s2*s4*s5*s6*s6 - c2*c4*c5*c5*c6*c6*d3*m6*s2*s3*s4 - c2*c4*c5*c5*d3*m6*s2*s3*s4*s6*s6 - 2*c2*c3*c4*c5*c6*c6*d5*m6*s2*s4*s5 - 2*c2*c3*c4*c5*d5*m6*s2*s4*s5*s6*s6); #endif return tau; } /* Gravity compensation - algorithm nr 2 */ void getGravComp2(std::array<double, 7> &t) { // #ifdef PRINT_DEBUG_INFO std::cout<<"Gravitation compensation based on Newton-Euler dynamics equations"<<std::endl; #endif // // t[6]=gravity_compensation_joint_7(); // t[5]=gravity_compensation_joint_6(); //t[5]=0; // t[4]=gravity_compensation_joint_5(); //t[4]=0; // t[3]=gravity_compensation_joint_4(); //t[3]*=1.2; // t[2]=gravity_compensation_joint_3(); t[2]=0; // t[1]=gravity_compensation_joint_2(); //t[1]=t[1]*1.2; // t[0]=gravity_compensation_joint_1(); //t[0]=0; // eksperyment t[6]=gravity_compensation_joint_7(); t[5]=gravity_compensation_joint_6(); //t[5]=0; t[4]=gravity_compensation_joint_5(); //t[4]=0; t[3]=gravity_compensation_joint_4(); //t[3]*=1.2; t[2]=gravity_compensation_joint_3(); // t[2]=0; t[1]=gravity_compensation_joint_2(); //t[1]=t[1]*1.2; t[0]=gravity_compensation_joint_1(); //t[0]=0; // change the sign of the torque #ifdef PRINT_DEBUG_INFO std::cout<<std::endl; for (int i = 0; i < 7; ++i) { std::cout<<"[Optional] t["<<i<<"]="<<t[i]<<std::endl; } std::cout<<std::endl; #endif } /* gravity compensation - basic algorithm */ void getGravComp(std::array<double, 7 > &t) { // gravity vector ignition::math::Vector3d gr = gazebo::physics::get_world()->Gravity(); ignition::math::Vector3d tool_com; #ifdef PRINT_DEBUG_INFO std::cout<<"tool_com="<<tool_com<<std::endl; #endif // tool mass double tool_mass = 0; // pointer to the last link from the links_ vector - i.e. end effector gazebo::physics::LinkPtr link = links_[6]; // pointer to the last joint from the joints_ vector gazebo::physics::JointPtr joint = joints_[6]; // get the world pose of the link ignition::math::Pose3d T_W_L7 = link->WorldPose(); // get the global position of the last link, i.e. in simulation the last link is 6-th link #ifdef PRINT_DEBUG_INFO std::cout<<"T_W_L7="<<T_W_L7<<std::endl; #endif // add to T_W_L7 pose vector tool_com (is it empty?) ignition::math::Vector3d cog = T_W_L7.CoordPositionAdd( tool_com ); // calculate the center of gravity of link nr 6 (in fact we number all link from 0 to 6, so in fact here the last link is 6-th but in reality we say it is the 7-th link) #ifdef PRINT_DEBUG_INFO std::cout<<"tool_com for link 6 => tool_com="<<tool_com<<std::endl; std::cout<<"cog for link 6 => cog="<<cog<<std::endl; #endif // calculate new vector which is vector cog - position of last joint ignition::math::Vector3d r = cog - joint->WorldPose().Pos(); // calculate the distance between the global joint position and the center of gravity (i.e. it's a center of mass) #ifdef PRINT_DEBUG_INFO std::cout<<"r for link 6 => r="<<r<<std::endl; #endif // set a mass to tool_mass - i.e. it equals zero double mass = tool_mass; // tool mass we assume equals zero #ifdef PRINT_DEBUG_INFO std::cout<<"mass="<<mass<<std::endl; #endif // calculate torque as a cross product of two vectors r and gravity vector multiplied by mass (which is still zero) ignition::math::Vector3d torque = r.Cross(mass * gr); // we calculate the torque exerting on the last joint as a cross product of r and (mass * gr) [arm x mass * gravity constant], pay attention that the mass of the last link is zero // calculate axis ignition::math::Vector3d axis = joint->GlobalAxis(0); // rotation axis of joint nr 6 in global position t[6] = axis.Dot(torque); // dot product of axis and torque is a torque compansating the gravity for the last link #ifdef PRINT_DEBUG_INFO std::cout<<"#####################################"<<std::endl; std::cout<<"Joint position for i=6-th joint: "<<joint->WorldPose().Pos()<<std::endl; std::cout<<"Axis for i=6-th joint: "<<axis<<std::endl; std::cout<<"Torque for i=6-th joint: "<<t[6]<<std::endl; #endif // for each link within links_ - except the 6-th link for (int i = 6; i > 0; i--) { link = links_[i-1]; // get the (i-1)th link joint = joints_[i-1]; // get the (i-1)th joint // WorldCoGPose - get the pose of the body's center of gravity in the world coordinate frame // now we calculate the center of gravity for all links already visited, i.e. (i-1) to 6, we are using weighted mean cog = (cog * mass + link->WorldCoGPose().Pos() * link->GetInertial()->Mass()) / (mass+link->GetInertial()->Mass()); // we calculate here the weighted mean, based on this we calculate the center of gravity of the links (from i-1-th link do 6-th link) #ifdef PRINT_DEBUG_INFO std::cout<<"cog="<<cog<<std::endl; #endif // update the total mass of already visited links, i.e. (i-1) to 6 mass += link->GetInertial()->Mass(); // here we calculate the total sum of the manipulator (iteratively adding masses of links starting from end-effector, which has zero mass) #ifdef PRINT_DEBUG_INFO std::cout<<"mass["<<i-1<<"]="<<mass<<std::endl; #endif // caluclate the distance between the joint position and the center of gravity of all already visited joints r = cog - joint->WorldPose().Pos(); // calculate the torque excerting on joint, as a cross product of arm and the gravitation force acting on the arm torque = r.Cross(mass * gr); // global axis of joint (i-1) - i.e. rotation axis of joint, in other words the z-th vector from transformation matrix ^0_(i-1)T axis = joint->GlobalAxis(0); // torque exerting on joint (i-1) along, why dot product? because we calculate torque along z-th axis from transformation matrix (rotation axis of joint i-1 from poiint of view of base frame) t[i-1] = axis.Dot(torque); #ifdef PRINT_DEBUG_INFO std::cout<<"#####################################"<<std::endl; std::cout<<"Joint position for i="<<i-1<<"-th joint "<<joint->WorldPose().Pos()<<std::endl; std::cout<<"Axis for i="<<i-1<<"-th joint "<<axis<<std::endl; std::cout<<"Torque for i="<<i-1<<"-th joint "<<t[i-1]<<std::endl; #endif } #ifdef PRINT_DEBUG_INFO std::cout<<"#####################################"<<std::endl; std::cout<<""<<std::endl; std::cout<<""<<std::endl; std::cout<<"#####################################"<<std::endl; #endif // change the sign of the torque for (int i = 0; i < 7; ++i) { t[i] = -t[i]; #ifdef PRINT_DEBUG_INFO std::cout<<"[Original] t["<<i<<"]="<<t[i]<<std::endl; #endif } } // end of function getGravComp // just get center of gravity of each links void getCenterOfGravityJustForTests(){ #ifdef PRINT_DEBUG_INFO std::cout<<"Get center of gravity of links"<<std::endl; for(int i=0; i<7; i++){ std::cout<<"CoG of link "<<i+1<<"="<<links_[i]->WorldCoGPose().Pos()<<std::endl; } for(int i=0; i<7; i++){ std::cout<<"Joint position "<<i+1<<"="<<joints_[i]->WorldPose().Pos()<<std::endl; } for(int i=0; i<7; i++){ std::cout<<"Link position "<<i+1<<"="<<links_[i]->WorldPose().Pos()<<std::endl; } for(int i=0; i<7; i++){ std::cout<<"Delta "<<i+1<<"="<<links_[i]->WorldPose().Pos()-links_[i]->WorldCoGPose().Pos()<<std::endl; } #endif } #ifdef EXTERNAL_CALCULATIONS /* Set torque based on received data */ void setTorqueBasedOnReceiveDataFromSharedMemory(){ /* Read torques from shared memory */ struct lwr4_joints received_torque; //received_torque=shm_torque_consumer->readSynchronously(); // or received_torque=shm_torque_consumer->readAsynchronously(); // get table of joints for(int i=0;i<7;i++){ torque[i]=received_torque._joints[i]; //std::cout<<"Received data - torque["<<i+1<<"]="<<received_torque._joints[i]<<std::endl; } } /* Send current position and velocity of the last frame, i.e. end-effector frame */ void sendCurrentLWRManipulatorParameters(){ #ifdef PRINT_DEBUG_INFO std::cout<<"[sendCurrentLWRManipulatorParameters] -- Start "<<std::endl; #endif struct lwr4_kinematics_params current_lwr_params; current_lwr_params.theta1=joints_[0]->Position(0); //std::cout<<"sets theta1="<<joints_[0]->Position(0)<<std::endl; current_lwr_params.theta2=joints_[1]->Position(0); //std::cout<<"sets theta2="<<joints_[1]->Position(0)<<std::endl; current_lwr_params.theta3=joints_[2]->Position(0); //std::cout<<"sets theta3="<<joints_[2]->Position(0)<<std::endl; current_lwr_params.theta4=joints_[3]->Position(0); //std::cout<<"sets theta4="<<joints_[3]->Position(0)<<std::endl; current_lwr_params.theta5=joints_[4]->Position(0); //std::cout<<"sets theta5="<<joints_[4]->Position(0)<<std::endl; current_lwr_params.theta6=joints_[5]->Position(0); //std::cout<<"sets theta6="<<joints_[5]->Position(0)<<std::endl; current_lwr_params.theta7=joints_[6]->Position(0); //std::cout<<"sets theta7="<<joints_[6]->Position(0)<<std::endl; current_lwr_params.x_current=links_[6]->WorldPose().Pos().X()-links_[0]->WorldPose().Pos().X(); current_lwr_params.y_current=links_[6]->WorldPose().Pos().Y()-links_[0]->WorldPose().Pos().Y(); current_lwr_params.z_current=links_[6]->WorldPose().Pos().Z();//-links_[0]->WorldPose().Pos().Z(); //######################################## current_lwr_params.roll_current=equilibrium_roll; current_lwr_params.pitch_current=equilibrium_pitch; current_lwr_params.yaw_current=equilibrium_yaw; current_lwr_params.v_x=links_[6]->WorldLinearVel().X(); current_lwr_params.v_y=links_[6]->WorldLinearVel().Y(); current_lwr_params.v_z=links_[6]->WorldLinearVel().Z(); current_lwr_params.w_roll=0; current_lwr_params.w_pitch=0; current_lwr_params.w_yaw=0; /* Writes asynchronously - or in other way, e.g. Synchornously */ shm_parameters_producer->writeAsynchronously(current_lwr_params); } #endif // Called by the world update start event public: void OnUpdate() { torque.fill(0); // initialize all torques to 0 #ifdef EXTERNAL_CALCULATIONS /* calculation done in external process, data sent through share memory */ /* Shared memory - test */ //float msg_tmp = rand() % 360; //std::cout<<"Writes message: "<<msg_tmp<<std::endl; //shm_producer->writeSynchronously(msg_tmp); /* Update torque from shared memory */ setTorqueBasedOnReceiveDataFromSharedMemory(); #endif // END of EXTERNAL_CALCULATIONS #ifdef GAZEBO_CALCULATIONS // WORKS //LWR4KinematicsDynamics lwr=LWR4KinematicsDynamics(0, 30, 0, 10); //int i = lwr.function(4); // get gravity compensation torques - our function //getGravComp(t); //t.fill(0); // initialize all torques to 0 /* SUCCESS !!! - my version of gravity compensation based on Euler-Newton equations !!! - it works! */ // GRAVITY COMPENSATION!!! getGravComp2(torque); // gravity compensation version based on Euler-Newton equations (my version) //getCenterOfGravityJustForTests(); // ########################### // update equilibrium // equilibrium=equilibrium_global; // UpdateEquilibirum(); // ########################### // ############################################## // impedance control in joints //impedanceControlInJointSpace(t); // <<< ================================================================= // ############################################## // ############################################## // impedance control in joints impedanceControlInCartesianSpace(torque); // <<< ================================================================= // ############################################## // just to test impedance control in cartesian space updateCartesianImpedance(); #endif // END of GAZEBO_CALCULATIONS // ### - just for tests #ifdef CALCULATE_SAMPLING_PERIOD { std::cout<<"CALCULATE SAMPLING PERIOD"<<std::endl; std::chrono::duration<double> elapsed_time_between_iterations = std::chrono::system_clock::now()-end_time; std::cout<< "Elapsed between iterations: "<<elapsed_time_between_iterations.count()<<std::endl; end_time=std::chrono::system_clock::now(); } #endif // CALCULATE_SAMPLING_PERIOD // apply torques setForces(torque); saveEndEffectorPoseToFile(); // save to file current position of end-effector #ifdef EXTERNAL_CALCULATIONS /* SEND current position of end-effector frame */ sendCurrentLWRManipulatorParameters(); #endif } // end of function OnUpdate void updateCartesianImpedance(){ double radius=0.3; double origin_x=0; double origin_y=0; double origin_z=0.5; // ############# JUST TO print time - i.e. calculate the sampling period ######################## _iterations2++; // how many iterations are within a single cycle (waiting a whole cycle to change the desired cartesian position) if(_iterations2>ITERATIONS_IN_ONE_CYCLE){ _iterations2=0; // if number of iterations is greater then ITERATIONS_IN_ONE_CYCLE (the waiting time has been ended, set zero and calculate new cartesian position for end-effector) } else{ return; } //saveEndEffectorPoseToFile(); // save to file current position of end-effector if(_flag) // one direction of movement of manipulator's end-effector _iterations++; else // another direction of movement of manipulator's end-effector _iterations--; if(_iterations>MAX_ITERATIONS){ // check whether the whole movement in a desired direction has ended _iterations--; _flag=false; // change direction of movement } if(_iterations<0){ // check whether the whole movement in a desired direction has ended _iterations++; _flag=true; // change direction of movement } // ########################################################################################################################### // ######## Calculate desired position in cartesian space, i.e. equilibrium point ############################# // ########################################################################################################################### // in X-Y plane // double theta=(_iterations/MAX_ITERATIONS) * 360 * 3.14/180.0; // std::cout<<"!!!!!ITERATIONS="<<_iterations<<" theta="<<theta<<std::endl; // equilibrium_x= origin_x + radius * cos(theta); // equilibrium_y= origin_y + radius * sin(theta); // in Z-Y plane double theta=(_iterations/MAX_ITERATIONS) * 360 * 3.14/180.0; #ifdef PRINT_DEBUG_INFO std::cout<<"!!!!!ITERATIONS="<<_iterations<<" theta="<<theta<<" EQUILIBRIUM=("<<equilibrium_x<<","<<equilibrium_y<<","<<equilibrium_z<<")"<<std::endl; #endif equilibrium_z= origin_z + radius * sin(theta); equilibrium_y= origin_y + radius * cos(theta); // equilibrium in X coordinate is always the same - i.e. as defined at the beginning of this file: equilibrium_x=0.56; // ########################################################################################################################### // ########################################################################################################################### // ############# JUST TO print time - i.e. calculate the sampling period ######################## #ifdef CALCULATE_SAMPLING_PERIOD { end_time=std::chrono::system_clock::now(); std::cout<<"CALCULATE SAMPLING PERIOD"<<std::endl; std::chrono::duration<double> elapsed_seconds = end_time-start_time; std::cout<< "Elapsed time for a single iteration, i.e. time between calculating a new cartesian position: "<<elapsed_seconds.count()<<std::endl; start_time=end_time; } #endif // CALCULATE_SAMPLING_PERIOD // ######################################################### } // impedance control in joints void impedanceControlInJointSpace(std::array<double, 7> &t) { #ifdef PRINT_DEBUG_INFO std::cout<<"Impedance Control In Joint Space"<<std::endl; #endif // declare equilibrium point - set the desired position of the kinematic chain //std::array<double, 7 > eq({0.04, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4}); // almost vertical //std::array<double, 7 > eq ({0.04, 0, 0, 0, 0, 0, 0}); // joint angles in radians std::array<double, 7> eq = equilibrium; // calculate spring forces - becasue we utilise the impedance control - in joint space! // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! double k = 10; // stiffness constant for (int i = 0; i < t.size(); ++i) { double diff = eq[i] - joints_[i]->Position(0); // the difference between the equilibrium point and the current joint positions (Position(0) returns the current position of the axis nr 0) t[i] += k * diff; // add to torque additional force ? } } // # end of impedanceControlInJointSpace void saveInFile(std::string fileName, std::string what){ std::ofstream myfile; myfile.open (fileName, std::ios::app); myfile << what; myfile.close(); } void saveBasePoseToFile(){ std::ostringstream strs; strs << links_[0]->WorldPose().Pos().X()<<" "<<links_[0]->WorldPose().Pos().Y()<<" "<<0<<" "; strs<<0<<" "<<0<<" "<<0<<" "<<0<<" "<<0<<" "<<0<<" "<<0<<"\n"; std::string what = strs.str(); saveInFile("pozycje.txt", what); } void saveEndEffectorPoseToFile(){ double theta1=joints_[0]->Position(0); double theta2=joints_[1]->Position(0); double theta3=joints_[2]->Position(0); double theta4=joints_[3]->Position(0); double theta5=joints_[4]->Position(0); double theta6=joints_[5]->Position(0); double theta7=joints_[6]->Position(0); std::ostringstream strs; strs << links_[6]->WorldPose().Pos().X()<<" "<<links_[6]->WorldPose().Pos().Y()<<" "<<links_[6]->WorldPose().Pos().Z()<<" "; strs<<theta1<<" "<<theta2<<" "<<theta3<<" "<<theta4<<" "<<theta5<<" "<<theta6<<" "<<theta7<<"\n"; std::string what = strs.str(); saveInFile("pozycje.txt", what); } // impedance control in joints void impedanceControlInCartesianSpace(std::array<double, 7> &t) { #ifdef PRINT_DEBUG_INFO std::cout<<"Impedance Control In Cartesian Space"<<std::endl; #endif //ignition::math::Pose3d pos=ignition::math::Pose3d(links_[6]->WorldPose().Pos().X(), links_[6]->WorldPose().Pos().Y(), links_[6]->WorldPose().Pos().Z()); //_end_effector_position_vector.push_back(pos); // ################################################################################################## double d7= D7, d5 = D5, d3=D3, d1=D1; double l5= L5, l4=L4, l3=L3, l2=L2, l1=L1; double theta1=joints_[0]->Position(0); double theta2=joints_[1]->Position(0); double theta3=joints_[2]->Position(0); double theta4=joints_[3]->Position(0); double theta5=joints_[4]->Position(0); double theta6=joints_[5]->Position(0); double theta7=joints_[6]->Position(0); double c1=cos(theta1), c2=cos(theta2), c3=cos(theta3), c4=cos(theta4), c5=cos(theta5), c6=cos(theta6), c7=cos(theta7); double s1=sin(theta1), s2=sin(theta2), s3=sin(theta3), s4=sin(theta4), s5=sin(theta5), s6=sin(theta6), s7=sin(theta7); // ################################################################################################## // ################################################################################################## // declare equilibrium point - set the desired position of the kinematic chain // equilibrium point (x,y,z) double x_desired= equilibrium_x; double y_desired= equilibrium_y; double z_desired= equilibrium_z; double roll_desired = equilibrium_roll; double pitch_desired = equilibrium_pitch; double yaw_desired = equilibrium_yaw; // ################################################################################################## // ################################################################################################## // calculate spring forces - becasue we utilise the impedance control - in cartesian space! // ################################################################################################## // ################################################################################################## // double x_current=links_[6]->WorldPose().Pos().X()-links_[0]->WorldPose().Pos().X(); // double y_current=links_[6]->WorldPose().Pos().Y()-links_[0]->WorldPose().Pos().Y(); // double z_current=links_[6]->WorldPose().Pos().Z(); // double roll_current=links_[6]->WorldPose().Rot().Yaw(); // double pitch_current=links_[6]->WorldPose().Rot().Pitch(); // double yaw_current=links_[6]->WorldPose().Rot().Roll(); // ################################################################################### // in XY AXIS // double x_current=links_[6]->WorldPose().Pos().X()-links_[0]->WorldPose().Pos().X(); // double y_current=links_[6]->WorldPose().Pos().Y()-links_[0]->WorldPose().Pos().Y(); // double z_current=z_desired;//links_[6]->WorldPose().Pos().Z()-links_[0]->WorldPose().Pos().Z(); //######################################## // ################################################################################### // in XZ AXIS double x_current=links_[6]->WorldPose().Pos().X()-links_[0]->WorldPose().Pos().X(); double y_current=links_[6]->WorldPose().Pos().Y()-links_[0]->WorldPose().Pos().Y(); double z_current=links_[6]->WorldPose().Pos().Z();//-links_[0]->WorldPose().Pos().Z(); //######################################## double roll_current=roll_desired; double pitch_current=pitch_desired; double yaw_current=yaw_desired; // ################################################################################################## // ################################################################################################## // linear and angular velocities of the end-effector of LWR4+ manipulator // double v_x=links_[6]->WorldLinearVel().X(); // double v_y=links_[6]->WorldLinearVel().Y(); // double v_z=links_[6]->WorldLinearVel().Z(); //double w_roll=links_[6]->WorldAngularVel().X(); //double w_pitch=links_[6]->WorldAngularVel().Y(); //double w_yaw=links_[6]->WorldAngularVel().Z(); // ################# in XY AXIS // double v_x=links_[6]->WorldLinearVel().X(); // double v_y=links_[6]->WorldLinearVel().Y(); // double v_z=0;//links_[6]->WorldLinearVel().Z(); // ################# in ZY AXIS double v_x=links_[6]->WorldLinearVel().X(); double v_y=links_[6]->WorldLinearVel().Y(); double v_z=links_[6]->WorldLinearVel().Z(); double w_roll=0; double w_pitch=0; double w_yaw=0; // ################################################################################################## #ifdef PRINT_DEBUG_INFO std::cout<<"Current position of end-effector (X,Y,Z)=("<<x_current<<","<<y_current<<","<<z_current<<") angles (ROLL,PITCH,YAW)="<<roll_current<<","<<pitch_current<<","<<yaw_current<<")"<<std::endl; #endif // difference_k means the distance between k_desired and k_current along k-axis //double difference_x=x_desired-x_current; //double difference_y=y_desired-y_current; //double difference_z=z_desired-z_current; //double difference_roll=roll_desired-roll_current; //double difference_pitch=pitch_desired-pitch_current; //double difference_yaw=yaw_desired-yaw_current; double difference_x=x_desired-x_current; double difference_y=y_desired-y_current; double difference_z=z_desired-z_current; double difference_roll=0; double difference_pitch=0; double difference_yaw=0; #ifdef PRINT_DEBUG_INFO std::cout<<"Difference between desired and current position of end-effector (X,Y,Z)=("<<difference_x<<","<<difference_y<<","<<difference_z<<") angles (ROLL,PITCH,YAW)="<<roll_current<<","<<pitch_current<<","<<yaw_current<<")"<<std::endl; #endif // delta time - time between two iterations //double delta_t =0.0001; // stiffness constant double k=0; // stiffness matrix components double k11=k, k12=k, k13=k, k14=k, k15=k, k16=k, k21=k, k22=k, k23=k, k24=k, k25=k, k26=k, k31=k, k32=k, k33=k, k34=k, k35=k, k36=k, k41=k, k42=k, k43=k, k44=k, k45=k, k46=k, k51=k, k52=k, k53=k, k54=k, k55=k, k56=k, k61=k, k62=k, k63=k, k64=k, k65=k, k66=k; double k_diag=30; // 40 ok // set up diagonal parameters of stiffness matrix k11=k_diag; k22=k_diag; k33=k_diag; k44=k_diag; k55=k_diag; k66=k_diag; //damping constant double d=0; // damping matrix components double d11=d, d12=d, d13=d, d14=d, d15=d, d16=d, d21=d, d22=d, d23=d, d24=d, d25=d, d26=d, d31=d, d32=d, d33=d, d34=d, d35=d, d36=d, d41=d, d42=d, d43=d, d44=d, d45=d, d46=d, d51=d, d52=d, d53=d, d54=d, d55=d, d56=d, d61=d, d62=d, d63=d, d64=d, d65=d, d66=d; double d_diag=10; d11=d_diag; d22=d_diag; d33=d_diag; d44=d_diag; d55=d_diag; d66=d_diag; // torque for joint 1 double t1=k65*(pitch_desired - pitch_current) - d62*v_y - d63*v_z - d65*w_pitch - d64*w_roll - d66*w_yaw - (d5*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) + d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3))) + c1*d3*s2)*(d21*v_x + d22*v_y + d23*v_z + d25*w_pitch + d24*w_roll + d26*w_yaw - k25*(pitch_desired - pitch_current) - k24*(roll_desired - roll_current) + k21*(x_current - x_desired) + k22*(y_current - y_desired) - k26*(yaw_desired - yaw_current) + k23*(z_current - z_desired)) - d61*v_x + k64*(roll_desired - roll_current) - k61*(x_current - x_desired) - k62*(y_current - y_desired) + k66*(yaw_desired - yaw_current) - k63*(z_current - z_desired) - (d5*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) + d7*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3))) - d3*s1*s2)*(d11*v_x + d12*v_y + d13*v_z + d15*w_pitch + d14*w_roll + d16*w_yaw - k15*(pitch_desired - pitch_current) - k14*(roll_desired - roll_current) + k11*(x_current - x_desired) + k12*(y_current - y_desired) - k16*(yaw_desired - yaw_current) + k13*(z_current - z_desired)); // torque for joint nr 2 double t2=(c1*(d5*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) + d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3))) + c1*d3*s2) - s1*(d5*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) + d7*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3))) - d3*s1*s2))*(d31*v_x + d32*v_y + d33*v_z + d35*w_pitch + d34*w_roll + d36*w_yaw - k35*(pitch_desired - pitch_current) - k34*(roll_desired - roll_current) + k31*(x_current - x_desired) + k32*(y_current - y_desired) - k36*(yaw_desired - yaw_current) + k33*(z_current - z_desired)) - c1*(d51*v_x + d52*v_y + d53*v_z + d55*w_pitch + d54*w_roll + d56*w_yaw - k55*(pitch_desired - pitch_current) - k54*(roll_desired - roll_current) + k51*(x_current - x_desired) + k52*(y_current - y_desired) - k56*(yaw_desired - yaw_current) + k53*(z_current - z_desired)) + s1*(d41*v_x + d42*v_y + d43*v_z + d45*w_pitch + d44*w_roll + d46*w_yaw - k45*(pitch_desired - pitch_current) - k44*(roll_desired - roll_current) + k41*(x_current - x_desired) + k42*(y_current - y_desired) - k46*(yaw_desired - yaw_current) + k43*(z_current - z_desired)) - c1*(c2*d3 + d7*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4)) + d5*(c2*c4 + c3*s2*s4))*(d11*v_x + d12*v_y + d13*v_z + d15*w_pitch + d14*w_roll + d16*w_yaw - k15*(pitch_desired - pitch_current) - k14*(roll_desired - roll_current) + k11*(x_current - x_desired) + k12*(y_current - y_desired) - k16*(yaw_desired - yaw_current) + k13*(z_current - z_desired)) - s1*(c2*d3 + d7*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4)) + d5*(c2*c4 + c3*s2*s4))*(d21*v_x + d22*v_y + d23*v_z + d25*w_pitch + d24*w_roll + d26*w_yaw - k25*(pitch_desired - pitch_current) - k24*(roll_desired - roll_current) + k21*(x_current - x_desired) + k22*(y_current - y_desired) - k26*(yaw_desired - yaw_current) + k23*(z_current - z_desired)); // torque for joint nr 3 double t3=(s1*s2*(d5*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) + d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3)))) + c1*s2*(d5*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) + d7*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3)))))*(d31*v_x + d32*v_y + d33*v_z + d35*w_pitch + d34*w_roll + d36*w_yaw - k35*(pitch_desired - pitch_current) - k34*(roll_desired - roll_current) + k31*(x_current - x_desired) + k32*(y_current - y_desired) - k36*(yaw_desired - yaw_current) + k33*(z_current - z_desired)) - (c2*(d5*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) + d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3)))) - c1*s2*(d7*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4)) + d5*(c2*c4 + c3*s2*s4)))*(d21*v_x + d22*v_y + d23*v_z + d25*w_pitch + d24*w_roll + d26*w_yaw - k25*(pitch_desired - pitch_current) - k24*(roll_desired - roll_current) + k21*(x_current - x_desired) + k22*(y_current - y_desired) - k26*(yaw_desired - yaw_current) + k23*(z_current - z_desired)) - (c2*(d5*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) + d7*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3)))) + s1*s2*(d7*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4)) + d5*(c2*c4 + c3*s2*s4)))*(d11*v_x + d12*v_y + d13*v_z + d15*w_pitch + d14*w_roll + d16*w_yaw - k15*(pitch_desired - pitch_current) - k14*(roll_desired - roll_current) + k11*(x_current - x_desired) + k12*(y_current - y_desired) - k16*(yaw_desired - yaw_current) + k13*(z_current - z_desired)) - c2*(d61*v_x + d62*v_y + d63*v_z + d65*w_pitch + d64*w_roll + d66*w_yaw - k65*(pitch_desired - pitch_current) - k64*(roll_desired - roll_current) + k61*(x_current - x_desired) + k62*(y_current - y_desired) - k66*(yaw_desired - yaw_current) + k63*(z_current - z_desired)) - c1*s2*(d41*v_x + d42*v_y + d43*v_z + d45*w_pitch + d44*w_roll + d46*w_yaw - k45*(pitch_desired - pitch_current) - k44*(roll_desired - roll_current) + k41*(x_current - x_desired) + k42*(y_current - y_desired) - k46*(yaw_desired - yaw_current) + k43*(z_current - z_desired)) - s1*s2*(d51*v_x + d52*v_y + d53*v_z + d55*w_pitch + d54*w_roll + d56*w_yaw - k55*(pitch_desired - pitch_current) - k54*(roll_desired - roll_current) + k51*(x_current - x_desired) + k52*(y_current - y_desired) - k56*(yaw_desired - yaw_current) + k53*(z_current - z_desired)); // torque for joint nr 4 double t4=(c1*c3 - c2*s1*s3)*(d51*v_x + d52*v_y + d53*v_z + d55*w_pitch + d54*w_roll + d56*w_yaw - k55*(pitch_desired - pitch_current) - k54*(roll_desired - roll_current) + k51*(x_current - x_desired) + k52*(y_current - y_desired) - k56*(yaw_desired - yaw_current) + k53*(z_current - z_desired)) - (c3*s1 + c1*c2*s3)*(d41*v_x + d42*v_y + d43*v_z + d45*w_pitch + d44*w_roll + d46*w_yaw - k45*(pitch_desired - pitch_current) - k44*(roll_desired - roll_current) + k41*(x_current - x_desired) + k42*(y_current - y_desired) - k46*(yaw_desired - yaw_current) + k43*(z_current - z_desired)) + ((c3*s1 + c1*c2*s3)*(d7*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4)) + d5*(c2*c4 + c3*s2*s4)) + s2*s3*(d5*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) + d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3)))))*(d21*v_x + d22*v_y + d23*v_z + d25*w_pitch + d24*w_roll + d26*w_yaw - k25*(pitch_desired - pitch_current) - k24*(roll_desired - roll_current) + k21*(x_current - x_desired) + k22*(y_current - y_desired) - k26*(yaw_desired - yaw_current) + k23*(z_current - z_desired)) - ((c1*c3 - c2*s1*s3)*(d5*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) + d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3)))) - (d5*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) + d7*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3))))*(c3*s1 + c1*c2*s3))*(d31*v_x + d32*v_y + d33*v_z + d35*w_pitch + d34*w_roll + d36*w_yaw - k35*(pitch_desired - pitch_current) - k34*(roll_desired - roll_current) + k31*(x_current - x_desired) + k32*(y_current - y_desired) - k36*(yaw_desired - yaw_current) + k33*(z_current - z_desired)) + ((c1*c3 - c2*s1*s3)*(d7*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4)) + d5*(c2*c4 + c3*s2*s4)) + s2*s3*(d5*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) + d7*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3)))))*(d11*v_x + d12*v_y + d13*v_z + d15*w_pitch + d14*w_roll + d16*w_yaw - k15*(pitch_desired - pitch_current) - k14*(roll_desired - roll_current) + k11*(x_current - x_desired) + k12*(y_current - y_desired) - k16*(yaw_desired - yaw_current) + k13*(z_current - z_desired)) + s2*s3*(d61*v_x + d62*v_y + d63*v_z + d65*w_pitch + d64*w_roll + d66*w_yaw - k65*(pitch_desired - pitch_current) - k64*(roll_desired - roll_current) + k61*(x_current - x_desired) + k62*(y_current - y_desired) - k66*(yaw_desired - yaw_current) + k63*(z_current - z_desired)); // torque for joint nr 5 double t5=(d7*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4))*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3)))*(c2*c4 + c3*s2*s4))*(d21*v_x + d22*v_y + d23*v_z + d25*w_pitch + d24*w_roll + d26*w_yaw - k25*(pitch_desired - pitch_current) - k24*(roll_desired - roll_current) + k21*(x_current - x_desired) + k22*(y_current - y_desired) - k26*(yaw_desired - yaw_current) + k23*(z_current - z_desired)) - (c2*c4 + c3*s2*s4)*(d61*v_x + d62*v_y + d63*v_z + d65*w_pitch + d64*w_roll + d66*w_yaw - k65*(pitch_desired - pitch_current) - k64*(roll_desired - roll_current) + k61*(x_current - x_desired) + k62*(y_current - y_desired) - k66*(yaw_desired - yaw_current) + k63*(z_current - z_desired)) - (d7*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3)))*(c2*c4 + c3*s2*s4) - d7*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2)*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4)))*(d11*v_x + d12*v_y + d13*v_z + d15*w_pitch + d14*w_roll + d16*w_yaw - k15*(pitch_desired - pitch_current) - k14*(roll_desired - roll_current) + k11*(x_current - x_desired) + k12*(y_current - y_desired) - k16*(yaw_desired - yaw_current) + k13*(z_current - z_desired)) - (s4*(s1*s3 - c1*c2*c3) + c1*c4*s2)*(d41*v_x + d42*v_y + d43*v_z + d45*w_pitch + d44*w_roll + d46*w_yaw - k45*(pitch_desired - pitch_current) - k44*(roll_desired - roll_current) + k41*(x_current - x_desired) + k42*(y_current - y_desired) - k46*(yaw_desired - yaw_current) + k43*(z_current - z_desired)) + (s4*(c1*s3 + c2*c3*s1) - c4*s1*s2)*(d51*v_x + d52*v_y + d53*v_z + d55*w_pitch + d54*w_roll + d56*w_yaw - k55*(pitch_desired - pitch_current) - k54*(roll_desired - roll_current) + k51*(x_current - x_desired) + k52*(y_current - y_desired) - k56*(yaw_desired - yaw_current) + k53*(z_current - z_desired)) - (d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3)))*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - d7*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3)))*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2))*(d31*v_x + d32*v_y + d33*v_z + d35*w_pitch + d34*w_roll + d36*w_yaw - k35*(pitch_desired - pitch_current) - k34*(roll_desired - roll_current) + k31*(x_current - x_desired) + k32*(y_current - y_desired) - k36*(yaw_desired - yaw_current) + k33*(z_current - z_desired)); // torque for joint nr 6 double t6=(s5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) - c5*(c1*c3 - c2*s1*s3))*(d51*v_x + d52*v_y + d53*v_z + d55*w_pitch + d54*w_roll + d56*w_yaw - k55*(pitch_desired - pitch_current) - k54*(roll_desired - roll_current) + k51*(x_current - x_desired) + k52*(y_current - y_desired) - k56*(yaw_desired - yaw_current) + k53*(z_current - z_desired)) + (d7*(s5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) - c5*(c3*s1 + c1*c2*s3))*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4)) + d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3)))*(s5*(c2*s4 - c3*c4*s2) - c5*s2*s3))*(d21*v_x + d22*v_y + d23*v_z + d25*w_pitch + d24*w_roll + d26*w_yaw - k25*(pitch_desired - pitch_current) - k24*(roll_desired - roll_current) + k21*(x_current - x_desired) + k22*(y_current - y_desired) - k26*(yaw_desired - yaw_current) + k23*(z_current - z_desired)) + (d7*(s5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) - c5*(c3*s1 + c1*c2*s3))*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3))) - d7*(c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3)))*(s5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) - c5*(c1*c3 - c2*s1*s3)))*(d31*v_x + d32*v_y + d33*v_z + d35*w_pitch + d34*w_roll + d36*w_yaw - k35*(pitch_desired - pitch_current) - k34*(roll_desired - roll_current) + k31*(x_current - x_desired) + k32*(y_current - y_desired) - k36*(yaw_desired - yaw_current) + k33*(z_current - z_desired)) + (d7*(s5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) - c5*(c1*c3 - c2*s1*s3))*(s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4)) + d7*(s5*(c2*s4 - c3*c4*s2) - c5*s2*s3)*(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3))))*(d11*v_x + d12*v_y + d13*v_z + d15*w_pitch + d14*w_roll + d16*w_yaw - k15*(pitch_desired - pitch_current) - k14*(roll_desired - roll_current) + k11*(x_current - x_desired) + k12*(y_current - y_desired) - k16*(yaw_desired - yaw_current) + k13*(z_current - z_desired)) + (s5*(c2*s4 - c3*c4*s2) - c5*s2*s3)*(d61*v_x + d62*v_y + d63*v_z + d65*w_pitch + d64*w_roll + d66*w_yaw - k65*(pitch_desired - pitch_current) - k64*(roll_desired - roll_current) + k61*(x_current - x_desired) + k62*(y_current - y_desired) - k66*(yaw_desired - yaw_current) + k63*(z_current - z_desired)) - (s5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) - c5*(c3*s1 + c1*c2*s3))*(d41*v_x + d42*v_y + d43*v_z + d45*w_pitch + d44*w_roll + d46*w_yaw - k45*(pitch_desired - pitch_current) - k44*(roll_desired - roll_current) + k41*(x_current - x_desired) + k42*(y_current - y_desired) - k46*(yaw_desired - yaw_current) + k43*(z_current - z_desired)); // torque for joint nr 7 double t7=(c6*(s4*(c1*s3 + c2*c3*s1) - c4*s1*s2) - s6*(c5*(c4*(c1*s3 + c2*c3*s1) + s1*s2*s4) + s5*(c1*c3 - c2*s1*s3)))*(d51*v_x + d52*v_y + d53*v_z + d55*w_pitch + d54*w_roll + d56*w_yaw - k55*(pitch_desired - pitch_current) - k54*(roll_desired - roll_current) + k51*(x_current - x_desired) + k52*(y_current - y_desired) - k56*(yaw_desired - yaw_current) + k53*(z_current - z_desired)) - (s6*(c5*(c2*s4 - c3*c4*s2) + s2*s3*s5) + c6*(c2*c4 + c3*s2*s4))*(d61*v_x + d62*v_y + d63*v_z + d65*w_pitch + d64*w_roll + d66*w_yaw - k65*(pitch_desired - pitch_current) - k64*(roll_desired - roll_current) + k61*(x_current - x_desired) + k62*(y_current - y_desired) - k66*(yaw_desired - yaw_current) + k63*(z_current - z_desired)) - (c6*(s4*(s1*s3 - c1*c2*c3) + c1*c4*s2) - s6*(c5*(c4*(s1*s3 - c1*c2*c3) - c1*s2*s4) + s5*(c3*s1 + c1*c2*s3)))*(d41*v_x + d42*v_y + d43*v_z + d45*w_pitch + d44*w_roll + d46*w_yaw - k45*(pitch_desired - pitch_current) - k44*(roll_desired - roll_current) + k41*(x_current - x_desired) + k42*(y_current - y_desired) - k46*(yaw_desired - yaw_current) + k43*(z_current - z_desired)); #ifdef PRINT_DEBUG_INFO std::cout<<"Calculated torques - impedance control in Cartesian space: "<<std::endl; std::cout<<"[Torque] t1 = "<<t1<<std::endl; std::cout<<"[Torque] t2 = "<<t2<<std::endl; std::cout<<"[Torque] t3 = "<<t3<<std::endl; std::cout<<"[Torque] t4 = "<<t4<<std::endl; std::cout<<"[Torque] t5 = "<<t5<<std::endl; std::cout<<"[Torque] t6 = "<<t6<<std::endl; std::cout<<"[Torque] t7 = "<<t7<<std::endl; #endif t[0]+=t1; t[1]+=t2; t[2]+=t3; t[3]+=t4; t[4]+=t5; t[5]+=t6; t[6]+=t7; // for (int i = 0; i < t.size(); ++i) { // double diff = eq[i] - joints_[i]->Position(0); // the difference between the equilibrium point and the current joint positions (Position(0) returns the current position of the axis nr 0) // t[i] += k * diff; // add to torque additional force ? // } } // # end of impedanceControlInCartesianSpace // ################################# // update equilibrium public: void UpdateEquilibirum(){ equilibrium[0]+=eq_0_step; equilibrium[3]+=eq_3_step; if(equilibrium[0]>3.14) { equilibrium[0]=3.14; eq_0_step*=-1; } else if(equilibrium[0]<-3.14){ equilibrium[0]=-3.14; eq_0_step*=-1; } if(equilibrium[3]>1.14) { equilibrium[3]=1.14; eq_3_step*=-1; } else if(equilibrium[3]<-1.14){ equilibrium[3]=-1.14; eq_3_step*=-1; } } private: void subscribe_callback_function(AnyPtr & _msg){ int i; #ifdef PRINT_DEBUG_INFO std::cout << "Message received:\nMessage type="<<_msg->type()<<std::endl; #endif if(_msg->type()==2){ // double -> angle #ifdef PRINT_DEBUG_INFO std::cout << "Double="<<_msg->double_value()<<std::endl; #endif // equilibrium_global[0]=_msg->double_value(); equilibrium[kinematic_chain_index]=_msg->double_value(); } else if(_msg->type()==3){ // int -> index of kinematic chain i=_msg->int_value(); #ifdef PRINT_DEBUG_INFO std::cout << "Int="<<i<<std::endl; #endif if(i>=0 && i<=6){ kinematic_chain_index=i; } } } private: void subscribe_callback_function_kuka_joints(KukaJointsPtr & _msg){ int i; equilibrium[0]=_msg->joint_0(); equilibrium[1]=_msg->joint_1(); equilibrium[2]=_msg->joint_2(); equilibrium[3]=_msg->joint_3(); equilibrium[4]=_msg->joint_4(); equilibrium[5]=_msg->joint_5(); equilibrium[6]=_msg->joint_6(); #ifdef PRINT_DEBUG_INFO std::cout << "Message received:\n\ Joint_0="<<_msg->joint_0()<< "\nJoint_1="<<_msg->joint_1()<< "\nJoint_2="<<_msg->joint_2()<< "\nJoint_3="<<_msg->joint_3()<< "\nJoint_4="<<_msg->joint_4()<< "\nJoint_5="<<_msg->joint_5()<< "\nJoint_6="<<_msg->joint_6()<<std::endl; #endif } private: double eq_0_step, eq_3_step; public: std::array<double,7> equilibrium; public: double equilibrium_x; public: double equilibrium_y; public: double equilibrium_z; public: double equilibrium_roll; public: double equilibrium_pitch; public: double equilibrium_yaw; public: double x_last; public: double y_last; public: double z_last; public: double roll_last; public: double pitch_last; public: double yaw_last; public: double _iterations; // for impedance control test public: double _iterations2; // for impedance control test public: double _flag; // for impedance control test public: std::vector<ignition::math::Pose3d> _end_effector_position_vector; private: int kinematic_chain_index; // ################################# // Pointer to the model private: physics::ModelPtr model_; // Pointer to the update event connection private: event::ConnectionPtr updateConnection; // Pointer to the subscriber private: transport::SubscriberPtr sub, sub_kuka_joints; private: // vector of joint pointers std::vector<gazebo::physics::JointPtr > joints_; // vector of link pointers std::vector<gazebo::physics::LinkPtr > links_; /* For communication - shared memory */ //SharedMemory<float> *shm_producer; /* Shared memory - torque calculated for gazebo simulation */ SharedMemory<struct lwr4_joints> *shm_torque_consumer; /* Shared memory - manipulator parameters, such as angles in joint space (theta) and velocities */ SharedMemory<struct lwr4_kinematics_params> *shm_parameters_producer; /* Manipulator torque */ std::array<double, 7 > torque; /* Measuring the iteration time */ std::chrono::time_point<std::chrono::system_clock> start_time; std::chrono::time_point<std::chrono::system_clock> end_time; }; // Register this plugin with the simulator GZ_REGISTER_MODEL_PLUGIN(ModelKukaLwr) }
63.224767
2,711
0.599192
mfigat
483116ba7daa8eed90262193e27e4f97eb2872bc
9,344
cpp
C++
libs/vgc/ui/lineedit.cpp
PixelRick/vgc
154cc275449a51327a36cb6386a17bbcf1149686
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
libs/vgc/ui/lineedit.cpp
PixelRick/vgc
154cc275449a51327a36cb6386a17bbcf1149686
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
libs/vgc/ui/lineedit.cpp
PixelRick/vgc
154cc275449a51327a36cb6386a17bbcf1149686
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// Copyright 2021 The VGC Developers // See the COPYRIGHT file at the top-level directory of this distribution // and at https://github.com/vgc/vgc/blob/master/COPYRIGHT // // 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 <vgc/ui/lineedit.h> #include <QKeyEvent> #include <vgc/core/array.h> #include <vgc/core/colors.h> #include <vgc/core/performancelog.h> #include <vgc/ui/cursor.h> #include <vgc/ui/strings.h> #include <vgc/ui/style.h> #include <vgc/ui/internal/paintutil.h> namespace vgc { namespace ui { LineEdit::LineEdit(std::string_view text) : Widget(), text_(""), shapedText_(graphics::fontLibrary()->defaultFace(), text_), textCursor_(false, 0), scrollLeft_(0.0f), reload_(true), isHovered_(false), isMousePressed_(false) { addClass(strings::LineEdit); setText(text); } LineEditPtr LineEdit::create() { return LineEditPtr(new LineEdit("")); } LineEditPtr LineEdit::create(std::string_view text) { return LineEditPtr(new LineEdit(text)); } void LineEdit::setText(std::string_view text) { if (text_ != text) { text_ = text; shapedText_.setText(text); reload_ = true; repaint(); } } void LineEdit::onResize() { reload_ = true; } void LineEdit::onPaintCreate(graphics::Engine* engine) { triangles_ = engine->createTriangles(); } void LineEdit::onPaintDraw(graphics::Engine*) { if (reload_) { reload_ = false; core::FloatArray a; core::Color backgroundColor = internal::getColor(this, isHovered_ ? strings::background_color_on_hover : strings::background_color); #ifdef VGC_QOPENGL_EXPERIMENT static core::Stopwatch sw = {}; auto t = sw.elapsed() * 50.f; backgroundColor = core::Color::hsl(t, 0.6f, 0.3f); #endif core::Color textColor = internal::getColor(this, strings::text_color); float borderRadius = internal::getLength(this, strings::border_radius); float paddingLeft = internal::getLength(this, strings::padding_left); float paddingRight = internal::getLength(this, strings::padding_right); float textWidth = width() - paddingLeft - paddingRight; graphics::TextProperties textProperties( graphics::TextHorizontalAlign::Left, graphics::TextVerticalAlign::Middle); if (hasFocus()) { textCursor_.setVisible(true); } else { textCursor_.setVisible(false); } updateScroll_(textWidth); bool hinting = style(strings::pixel_hinting) == strings::normal; internal::insertRect(a, backgroundColor, 0, 0, width(), height(), borderRadius); internal::insertText(a, textColor, 0, 0, width(), height(), paddingLeft, paddingRight, 0, 0, shapedText_, textProperties, textCursor_, hinting, scrollLeft_); triangles_->load(a.data(), a.length()); } triangles_->draw(); } void LineEdit::onPaintDestroy(graphics::Engine*) { triangles_.reset(); } bool LineEdit::onMouseMove(MouseEvent* event) { if (isMousePressed_) { updateBytePosition_(event->pos()); } return true; } bool LineEdit::onMousePress(MouseEvent* event) { isMousePressed_ = true; setFocus(); updateBytePosition_(event->pos()); return true; } bool LineEdit::onMouseRelease(MouseEvent* /*event*/) { isMousePressed_ = false; return true; } bool LineEdit::onMouseEnter() { pushCursor(Qt::IBeamCursor); return true; } bool LineEdit::onMouseLeave() { popCursor(); return true; } bool LineEdit::onFocusIn() { reload_ = true; repaint(); return true; } bool LineEdit::onFocusOut() { reload_ = true; repaint(); return true; } bool LineEdit::onKeyPress(QKeyEvent* event) { int key = event->key(); if (key == Qt::Key_Delete || key == Qt::Key_Backspace) { Int p1_ = textCursor_.bytePosition(); Int p2_ = -1; graphics::TextBoundaryType boundaryType = (event->modifiers().testFlag(Qt::ControlModifier)) ? graphics::TextBoundaryType::Word : graphics::TextBoundaryType::Grapheme; graphics::TextBoundaryIterator it(boundaryType, text()); it.setPosition(p1_); if (key == Qt::Key_Delete) { p2_ = it.toNextBoundary(); } else { // Backspace p2_ = p1_; p1_ = it.toPreviousBoundary(); } if (p1_ != -1 && p2_ != -1) { size_t p1 = core::int_cast<size_t>(p1_); size_t p2 = core::int_cast<size_t>(p2_); std::string newText; newText.reserve(text().size() - (p2 - p1)); newText.append(text(), 0, p1); newText.append(text(), p2); textCursor_.setBytePosition(p1_); setText(newText); } return true; } else if (key == Qt::Key_Home) { Int p1 = textCursor_.bytePosition(); Int home = 0; if (p1 != home) { textCursor_.setBytePosition(home); reload_ = true; repaint(); } return true; } else if (key == Qt::Key_End) { Int p1 = textCursor_.bytePosition(); Int end = core::int_cast<Int>(text().size()); if (p1 != end) { textCursor_.setBytePosition(end); reload_ = true; repaint(); } return true; } else if (key == Qt::Key_Left || key == Qt::Key_Right) { Int p1 = textCursor_.bytePosition(); Int p2 = -1; graphics::TextBoundaryType boundaryType = (event->modifiers().testFlag(Qt::ControlModifier)) ? graphics::TextBoundaryType::Word : graphics::TextBoundaryType::Grapheme; graphics::TextBoundaryIterator it(boundaryType, text()); it.setPosition(p1); if (key == Qt::Key_Left) { p2 = it.toPreviousBoundary(); } else { // Right p2 = it.toNextBoundary(); } if (p2 != -1 && p1 != p2) { textCursor_.setBytePosition(it.position()); reload_ = true; repaint(); } return true; } else { std::string t = event->text().toStdString(); if (!t.empty()) { size_t p = core::int_cast<size_t>(textCursor_.bytePosition()); std::string newText; newText.reserve(text().size() + t.size()); newText.append(text(), 0, p); newText.append(t); newText.append(text(), p); textCursor_.setBytePosition(p + t.size()); setText(newText); return true; } else { return false; } } } geometry::Vec2f LineEdit::computePreferredSize() const { PreferredSizeType auto_ = PreferredSizeType::Auto; PreferredSize w = preferredWidth(); PreferredSize h = preferredHeight(); geometry::Vec2f res(0, 0); if (w.type() == auto_) { res[0] = 100; // TODO: compute appropriate width based on text length } else { res[0] = w.value(); } if (h.type() == auto_) { res[1] = 26; // TODO: compute appropriate height based on font size? } else { res[1] = h.value(); } return res; } void LineEdit::updateBytePosition_(const geometry::Vec2f& mousePosition) { Int bytePosition = bytePosition_(mousePosition); if (bytePosition != textCursor_.bytePosition()) { textCursor_.setBytePosition(bytePosition); reload_ = true; repaint(); } } Int LineEdit::bytePosition_(const geometry::Vec2f& mousePosition) { float paddingLeft = internal::getLength(this, strings::padding_left); float x = mousePosition[0] - paddingLeft; float y = mousePosition[1]; return shapedText_.bytePosition( geometry::Vec2d(static_cast<double>(x + scrollLeft_), static_cast<double>(y))); } void LineEdit::updateScroll_(float textWidth) { float textEndAdvance = shapedText_.advance()[0]; float currentTextEndPos = textEndAdvance - scrollLeft_; if (currentTextEndPos < textWidth && scrollLeft_ > 0) { if (textEndAdvance < textWidth) { scrollLeft_ = 0; } else { scrollLeft_ = textEndAdvance - textWidth; } } if (textCursor_.isVisible()) { float cursorAdvance = shapedText_.advance(textCursor_.bytePosition())[0]; float currentCursorPos = cursorAdvance - scrollLeft_; if (currentCursorPos < 0) { scrollLeft_ = cursorAdvance; } else if (currentCursorPos > textWidth) { scrollLeft_ = cursorAdvance - textWidth; } } } } // namespace ui } // namespace vgc
28.487805
165
0.600171
PixelRick
4834cf71f04bd80152ab8157b8e743a86618080f
10,483
cpp
C++
AvxBlas/PixelShuffle3D/pixelshuffle3d_spacetochannel.cpp
tk-yoshimura/AvxBlas
37ae77f05e35aa3e97109785276afba3835585ec
[ "MIT" ]
null
null
null
AvxBlas/PixelShuffle3D/pixelshuffle3d_spacetochannel.cpp
tk-yoshimura/AvxBlas
37ae77f05e35aa3e97109785276afba3835585ec
[ "MIT" ]
null
null
null
AvxBlas/PixelShuffle3D/pixelshuffle3d_spacetochannel.cpp
tk-yoshimura/AvxBlas
37ae77f05e35aa3e97109785276afba3835585ec
[ "MIT" ]
null
null
null
#include "../avxblas.h" #include "../constants.h" #include "../utils.h" #include "../Inline/inline_copy_s.hpp" #pragma unmanaged int pixelshuffle3d_spacetochannel_aligned( const uint n, const uint ic, const uint oc, const uint iw, const uint ow, const uint ih, const uint oh, const uint id, const uint od, const uint s, infloats x_ptr, outfloats y_ptr) { const uint cs = ic * s; #ifdef _DEBUG if ((cs & AVX2_FLOAT_REMAIN_MASK) != 0 || ((size_t)x_ptr % AVX2_ALIGNMENT) != 0 || ((size_t)y_ptr % AVX2_ALIGNMENT) != 0) { return FAILURE_BADPARAM; } #endif // _DEBUG for (uint i = 0; i < n; i++) { for (uint oz = 0; oz < od; oz++) { for (uint cz = 0; cz < s; cz++) { for (uint oy = 0; oy < oh; oy++) { for (uint cy = 0; cy < s; cy++) { float* yc_ptr = y_ptr + cs * (cy + s * cz) + oc * ow * (oy + oh * oz); for (uint ox = 0; ox < ow; ox++) { copy_aligned_s(cs, x_ptr, yc_ptr); x_ptr += cs; yc_ptr += oc; } } } } } y_ptr += oc * ow * oh * od; } return SUCCESS; } int pixelshuffle3d_spacetochannel_unaligned( const uint n, const uint ic, const uint oc, const uint iw, const uint ow, const uint ih, const uint oh, const uint id, const uint od, const uint s, infloats x_ptr, outfloats y_ptr) { const uint cs = ic * s; #ifdef _DEBUG if ((cs & AVX2_FLOAT_REMAIN_MASK) == 0) { return FAILURE_BADPARAM; } #endif // _DEBUG const __m256i mask = _mm256_setmask_ps(cs & AVX2_FLOAT_REMAIN_MASK); for (uint i = 0; i < n; i++) { for (uint oz = 0; oz < od; oz++) { for (uint cz = 0; cz < s; cz++) { for (uint oy = 0; oy < oh; oy++) { for (uint cy = 0; cy < s; cy++) { float* yc_ptr = y_ptr + cs * (cy + s * cz) + oc * ow * (oy + oh * oz); for (uint ox = 0; ox < ow; ox++) { copy_unaligned_s(cs, x_ptr, yc_ptr, mask); x_ptr += cs; yc_ptr += oc; } } } } } y_ptr += oc * ow * oh * od; } return SUCCESS; } int pixelshuffle3d_spacetochannel_cs2to3( const uint n, const uint ic, const uint oc, const uint iw, const uint ow, const uint ih, const uint oh, const uint id, const uint od, const uint s, infloats x_ptr, outfloats y_ptr) { const uint cs = ic * s; #ifdef _DEBUG if (cs != 2 && cs != 3) { return FAILURE_BADPARAM; } #endif // _DEBUG __m128 x; const __m128i mask = _mm_setmask_ps(cs); for (uint i = 0; i < n; i++) { for (uint oz = 0; oz < od; oz++) { for (uint cz = 0; cz < s; cz++) { for (uint oy = 0; oy < oh; oy++) { for (uint cy = 0; cy < s; cy++) { float* yc_ptr = y_ptr + cs * (cy + s * cz) + oc * ow * (oy + oh * oz); for (uint ox = 0; ox < ow; ox++) { x = _mm_loadu_ps(x_ptr); _mm_maskstore_ps(yc_ptr, mask, x); x_ptr += cs; yc_ptr += oc; } } } } } y_ptr += oc * ow * oh * od; } return SUCCESS; } int pixelshuffle3d_spacetochannel_cs4( const uint n, const uint ic, const uint oc, const uint iw, const uint ow, const uint ih, const uint oh, const uint id, const uint od, const uint s, infloats x_ptr, outfloats y_ptr) { const uint cs = ic * s; #ifdef _DEBUG if (cs != AVX1_FLOAT_STRIDE || ((size_t)x_ptr % AVX1_ALIGNMENT) != 0 || ((size_t)y_ptr % AVX1_ALIGNMENT) != 0) { return FAILURE_BADPARAM; } #endif // _DEBUG __m128 x; for (uint i = 0; i < n; i++) { for (uint oz = 0; oz < od; oz++) { for (uint cz = 0; cz < s; cz++) { for (uint oy = 0; oy < oh; oy++) { for (uint cy = 0; cy < s; cy++) { float* yc_ptr = y_ptr + cs * (cy + s * cz) + oc * ow * (oy + oh * oz); for (uint ox = 0; ox < ow; ox++) { x = _mm_load_ps(x_ptr); _mm_stream_ps(yc_ptr, x); x_ptr += cs; yc_ptr += oc; } } } } } y_ptr += oc * ow * oh * od; } return SUCCESS; } int pixelshuffle3d_spacetochannel_cs5to7( const uint n, const uint ic, const uint oc, const uint iw, const uint ow, const uint ih, const uint oh, const uint id, const uint od, const uint s, infloats x_ptr, outfloats y_ptr) { const uint cs = ic * s; #ifdef _DEBUG if (cs <= AVX1_FLOAT_STRIDE || cs >= AVX2_FLOAT_STRIDE) { return FAILURE_BADPARAM; } #endif // _DEBUG const __m256i mask = _mm256_setmask_ps(cs & AVX2_FLOAT_REMAIN_MASK); __m256 x; for (uint i = 0; i < n; i++) { for (uint oz = 0; oz < od; oz++) { for (uint cz = 0; cz < s; cz++) { for (uint oy = 0; oy < oh; oy++) { for (uint cy = 0; cy < s; cy++) { float* yc_ptr = y_ptr + cs * (cy + s * cz) + oc * ow * (oy + oh * oz); for (uint ox = 0; ox < ow; ox++) { _mm256_loadu_x1_ps(x_ptr, x); _mm256_maskstore_x1_ps(yc_ptr, x, mask); x_ptr += cs; yc_ptr += oc; } } } } } y_ptr += oc * ow * oh * od; } return SUCCESS; } int pixelshuffle3d_spacetochannel_cs8( const uint n, const uint ic, const uint oc, const uint iw, const uint ow, const uint ih, const uint oh, const uint id, const uint od, const uint s, infloats x_ptr, outfloats y_ptr) { const uint cs = ic * s; #ifdef _DEBUG if (cs != AVX2_FLOAT_STRIDE || ((size_t)x_ptr % AVX2_ALIGNMENT) != 0 || ((size_t)y_ptr % AVX2_ALIGNMENT) != 0) { return FAILURE_BADPARAM; } #endif // _DEBUG __m256 x; for (uint i = 0; i < n; i++) { for (uint oz = 0; oz < od; oz++) { for (uint cz = 0; cz < s; cz++) { for (uint oy = 0; oy < oh; oy++) { for (uint cy = 0; cy < s; cy++) { float* yc_ptr = y_ptr + cs * (cy + s * cz) + oc * ow * (oy + oh * oz); for (uint ox = 0; ox < ow; ox++) { _mm256_load_x1_ps(x_ptr, x); _mm256_stream_x1_ps(yc_ptr, x); x_ptr += cs; yc_ptr += oc; } } } } } y_ptr += oc * ow * oh * od; } return SUCCESS; } int pixelshuffle3d_spacetochannel_csleq8( const uint n, const uint ic, const uint oc, const uint iw, const uint ow, const uint ih, const uint oh, const uint id, const uint od, const uint s, infloats x_ptr, outfloats y_ptr) { const uint cs = ic * s; if (cs <= 1) { return FAILURE_BADPARAM; } if (cs < AVX1_FLOAT_STRIDE) { return pixelshuffle3d_spacetochannel_cs2to3(n, ic, oc, iw, ow, ih, oh, id, od, s, x_ptr, y_ptr); } if (cs == AVX1_FLOAT_STRIDE) { return pixelshuffle3d_spacetochannel_cs4(n, ic, oc, iw, ow, ih, oh, id, od, s, x_ptr, y_ptr); } if (cs < AVX2_FLOAT_STRIDE) { return pixelshuffle3d_spacetochannel_cs5to7(n, ic, oc, iw, ow, ih, oh, id, od, s, x_ptr, y_ptr); } if (cs == AVX2_FLOAT_STRIDE) { return pixelshuffle3d_spacetochannel_cs8(n, ic, oc, iw, ow, ih, oh, id, od, s, x_ptr, y_ptr); } return FAILURE_BADPARAM; } #pragma managed void AvxBlas::PixelShuffle3D::SpaceToChannel( UInt32 n, UInt32 ic, UInt32 iw, UInt32 ih, UInt32 id, UInt32 s, Array<float>^ xs, Array<float>^ yc) { if (n > MAX_BATCHES) { throw gcnew System::ArgumentOutOfRangeException(ErrorMessage::InvalidBatches); } if (s <= 0 || s > MAX_PIXELSHUFFLE_STRIDE) { throw gcnew System::ArgumentOutOfRangeException(ErrorMessage::InvalidStride); } if (ic > MAX_CHANNELS || ic * s * s * s > MAX_CHANNELS) { throw gcnew System::ArgumentOutOfRangeException(ErrorMessage::InvalidChannels); } if (n <= 0 || ic <= 0 || iw <= 0 || ih <= 0 || id <= 0) { return; } if ((iw % s) != 0 || iw > MAX_MAP_SIZE || (ih % s) != 0 || ih > MAX_MAP_SIZE || (id % s) != 0 || id > MAX_MAP_SIZE) { throw gcnew System::ArgumentOutOfRangeException(ErrorMessage::InvalidDataSize); } Util::CheckProdOverflow(ic, s, s, s); UInt32 ow = iw / s, oh = ih / s, od = id / s, oc = ic * s * s * s; Util::CheckProdOverflow(n, ic, iw, ih, id); Util::CheckProdOverflow(n, oc, ow, oh, od); Util::CheckLength(n * ic * iw * ih * id, xs); Util::CheckLength(n * oc * ow * oh * od, yc); Util::CheckDuplicateArray(xs, yc); if (s == 1) { Elementwise::Copy(n * ic * iw * ih * id, xs, yc); return; } const float* x_ptr = (const float*)(xs->Ptr.ToPointer()); float* y_ptr = (float*)(yc->Ptr.ToPointer()); int ret = UNEXECUTED; const uint cs = ic * s; if (cs <= AVX2_FLOAT_STRIDE) { #ifdef _DEBUG Console::WriteLine("type leq8"); #endif // _DEBUG ret = pixelshuffle3d_spacetochannel_csleq8(n, ic, oc, iw, ow, ih, oh, id, od, s, x_ptr, y_ptr); } else if ((cs & AVX2_FLOAT_REMAIN_MASK) == 0) { #ifdef _DEBUG Console::WriteLine("type aligned"); #endif // _DEBUG ret = pixelshuffle3d_spacetochannel_aligned(n, ic, oc, iw, ow, ih, oh, id, od, s, x_ptr, y_ptr); } else { #ifdef _DEBUG Console::WriteLine("type unaligned"); #endif // _DEBUG ret = pixelshuffle3d_spacetochannel_unaligned(n, ic, oc, iw, ow, ih, oh, id, od, s, x_ptr, y_ptr); } Util::AssertReturnCode(ret); }
28.958564
127
0.485643
tk-yoshimura
4835242860ac2aaf3c74f023f0f6d81329fd7e9e
933
hpp
C++
include/jln/mp/smp/algorithm/is_sorted.hpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
9
2020-07-04T16:46:13.000Z
2022-01-09T21:59:31.000Z
include/jln/mp/smp/algorithm/is_sorted.hpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
null
null
null
include/jln/mp/smp/algorithm/is_sorted.hpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
1
2021-05-23T13:37:40.000Z
2021-05-23T13:37:40.000Z
#pragma once #include <jln/mp/smp/functional/identity.hpp> #include <jln/mp/smp/utility/always.hpp> #include <jln/mp/smp/number/operators.hpp> #include <jln/mp/functional/tee.hpp> #include <jln/mp/functional/if.hpp> #include <jln/mp/list/size.hpp> #include <jln/mp/algorithm/is_sorted.hpp> namespace jln::mp::smp { template<class Cmp = less<>, class C = identity> using is_sorted = contract< mp::if_< mp::size<mp::less_than_c<2>>, always<mp::number<1>, C>, mp::tee< mp::pop_front<>, mp::rotate_c<-1, mp::pop_front<>>, mp::zip_with< try_assume_binary<Cmp>, mp::try_<mp::or_<mp::not_<try_assume_unary<C>>>> > > > >; } /// \cond namespace jln::mp::detail { template<template<class> class sfinae, class Cmp, class C> struct _sfinae<sfinae, is_sorted<Cmp, C>> { using type = smp::is_sorted<sfinae<Cmp>, sfinae<C>>; }; } /// \endcond
23.325
60
0.624866
jonathanpoelen
483acf982086365972c20530d88987b51d3e746a
20,901
hpp
C++
src/c4/dump.hpp
kasper93/c4core
170509d06aceefda8980c98a2785e838bb19e578
[ "BSL-1.0", "MIT" ]
null
null
null
src/c4/dump.hpp
kasper93/c4core
170509d06aceefda8980c98a2785e838bb19e578
[ "BSL-1.0", "MIT" ]
null
null
null
src/c4/dump.hpp
kasper93/c4core
170509d06aceefda8980c98a2785e838bb19e578
[ "BSL-1.0", "MIT" ]
null
null
null
#ifndef C4_DUMP_HPP_ #define C4_DUMP_HPP_ #include <c4/substr.hpp> namespace c4 { //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** type of the function to dump characters */ using DumperPfn = void (*)(csubstr buf); //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- template<DumperPfn dumpfn, class Arg> inline size_t dump(substr buf, Arg const& a) { size_t sz = to_chars(buf, a); // need to serialize to the buffer if(C4_LIKELY(sz <= buf.len)) dumpfn(buf.first(sz)); return sz; } template<class DumperFn, class Arg> inline size_t dump(DumperFn &&dumpfn, substr buf, Arg const& a) { size_t sz = to_chars(buf, a); // need to serialize to the buffer if(C4_LIKELY(sz <= buf.len)) dumpfn(buf.first(sz)); return sz; } template<DumperPfn dumpfn> inline size_t dump(substr buf, csubstr a) { if(buf.len) dumpfn(a); // dump directly, no need to serialize to the buffer return 0; // no space was used in the buffer } template<class DumperFn> inline size_t dump(DumperFn &&dumpfn, substr buf, csubstr a) { if(buf.len) dumpfn(a); // dump directly, no need to serialize to the buffer return 0; // no space was used in the buffer } template<DumperPfn dumpfn, size_t N> inline size_t dump(substr buf, const char (&a)[N]) { if(buf.len) dumpfn(csubstr(a)); // dump directly, no need to serialize to the buffer return 0; // no space was used in the buffer } template<class DumperFn, size_t N> inline size_t dump(DumperFn &&dumpfn, substr buf, const char (&a)[N]) { if(buf.len) dumpfn(csubstr(a)); // dump directly, no need to serialize to the buffer return 0; // no space was used in the buffer } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** */ struct DumpResults { enum : size_t { noarg = (size_t)-1 }; size_t bufsize = 0; size_t lastok = noarg; bool success_until(size_t expected) const { return lastok == noarg ? false : lastok >= expected; } bool write_arg(size_t arg) const { return lastok == noarg || arg > lastok; } size_t argfail() const { return lastok + 1; } }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /// @cond dev // terminates the variadic recursion template<class DumperFn> size_t cat_dump(DumperFn &&, substr) { return 0; } // terminates the variadic recursion template<DumperPfn dumpfn> size_t cat_dump(substr) { return 0; } /// @endcond /** take the function pointer as a function argument */ template<class DumperFn, class Arg, class... Args> size_t cat_dump(DumperFn &&dumpfn, substr buf, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { size_t size_for_a = dump(dumpfn, buf, a); if(C4_UNLIKELY(size_for_a > buf.len)) buf = buf.first(0); // ensure no more calls size_t size_for_more = cat_dump(dumpfn, buf, more...); return size_for_more > size_for_a ? size_for_more : size_for_a; } /** take the function pointer as a template argument */ template<DumperPfn dumpfn,class Arg, class... Args> size_t cat_dump(substr buf, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { size_t size_for_a = dump<dumpfn>(buf, a); if(C4_LIKELY(size_for_a > buf.len)) buf = buf.first(0); // ensure no more calls size_t size_for_more = cat_dump<dumpfn>(buf, more...); return size_for_more > size_for_a ? size_for_more : size_for_a; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /// @cond dev namespace detail { // terminates the variadic recursion template<DumperPfn dumpfn, class Arg> DumpResults cat_dump_resume(size_t currarg, DumpResults results, substr buf, Arg const& C4_RESTRICT a) { if(C4_LIKELY(results.write_arg(currarg))) { size_t sz = dump<dumpfn>(buf, a); // yield to the specialized function if(currarg == results.lastok + 1 && sz <= buf.len) results.lastok = currarg; results.bufsize = sz > results.bufsize ? sz : results.bufsize; } return results; } // terminates the variadic recursion template<class DumperFn, class Arg> DumpResults cat_dump_resume(size_t currarg, DumperFn &&dumpfn, DumpResults results, substr buf, Arg const& C4_RESTRICT a) { if(C4_LIKELY(results.write_arg(currarg))) { size_t sz = dump(dumpfn, buf, a); // yield to the specialized function if(currarg == results.lastok + 1 && sz <= buf.len) results.lastok = currarg; results.bufsize = sz > results.bufsize ? sz : results.bufsize; } return results; } template<DumperPfn dumpfn, class Arg, class... Args> DumpResults cat_dump_resume(size_t currarg, DumpResults results, substr buf, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { results = detail::cat_dump_resume<dumpfn>(currarg, results, buf, a); return detail::cat_dump_resume<dumpfn>(currarg + 1u, results, buf, more...); } template<class DumperFn, class Arg, class... Args> DumpResults cat_dump_resume(size_t currarg, DumperFn &&dumpfn, DumpResults results, substr buf, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { results = detail::cat_dump_resume(currarg, dumpfn, results, buf, a); return detail::cat_dump_resume(currarg + 1u, dumpfn, results, buf, more...); } } // namespace detail /// @endcond template<DumperPfn dumpfn, class Arg, class... Args> C4_ALWAYS_INLINE DumpResults cat_dump_resume(DumpResults results, substr buf, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { if(results.bufsize > buf.len) return results; return detail::cat_dump_resume<dumpfn>(0u, results, buf, a, more...); } template<class DumperFn, class Arg, class... Args> C4_ALWAYS_INLINE DumpResults cat_dump_resume(DumperFn &&dumpfn, DumpResults results, substr buf, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { if(results.bufsize > buf.len) return results; return detail::cat_dump_resume(0u, dumpfn, results, buf, a, more...); } template<DumperPfn dumpfn, class Arg, class... Args> C4_ALWAYS_INLINE DumpResults cat_dump_resume(substr buf, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { return detail::cat_dump_resume<dumpfn>(0u, DumpResults{}, buf, a, more...); } template<class DumperFn, class Arg, class... Args> C4_ALWAYS_INLINE DumpResults cat_dump_resume(DumperFn &&dumpfn, substr buf, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { return detail::cat_dump_resume(0u, dumpfn, DumpResults{}, buf, a, more...); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /// @cond dev // terminate the recursion template<class DumperFn, class Sep> size_t catsep_dump(DumperFn &&, substr, Sep const& C4_RESTRICT) { return 0; } // terminate the recursion template<DumperPfn dumpfn, class Sep> size_t catsep_dump(substr, Sep const& C4_RESTRICT) { return 0; } /// @endcond /** take the function pointer as a function argument */ template<class DumperFn, class Sep, class Arg, class... Args> size_t catsep_dump(DumperFn &&dumpfn, substr buf, Sep const& C4_RESTRICT sep, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { size_t sz = dump(dumpfn, buf, a); if(C4_UNLIKELY(sz > buf.len)) buf = buf.first(0); // ensure no more calls if C4_IF_CONSTEXPR (sizeof...(more) > 0) { size_t szsep = dump(dumpfn, buf, sep); if(C4_UNLIKELY(szsep > buf.len)) buf = buf.first(0); // ensure no more calls sz = sz > szsep ? sz : szsep; } size_t size_for_more = catsep_dump(dumpfn, buf, sep, more...); return size_for_more > sz ? size_for_more : sz; } /** take the function pointer as a template argument */ template<DumperPfn dumpfn, class Sep, class Arg, class... Args> size_t catsep_dump(substr buf, Sep const& C4_RESTRICT sep, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { size_t sz = dump<dumpfn>(buf, a); if(C4_UNLIKELY(sz > buf.len)) buf = buf.first(0); // ensure no more calls if C4_IF_CONSTEXPR (sizeof...(more) > 0) { size_t szsep = dump<dumpfn>(buf, sep); if(C4_UNLIKELY(szsep > buf.len)) buf = buf.first(0); // ensure no more calls sz = sz > szsep ? sz : szsep; } size_t size_for_more = catsep_dump<dumpfn>(buf, sep, more...); return size_for_more > sz ? size_for_more : sz; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /// @cond dev namespace detail { template<DumperPfn dumpfn, class Arg> void catsep_dump_resume_(size_t currarg, DumpResults *C4_RESTRICT results, substr *C4_RESTRICT buf, Arg const& C4_RESTRICT a) { if(C4_LIKELY(results->write_arg(currarg))) { size_t sz = dump<dumpfn>(*buf, a); results->bufsize = sz > results->bufsize ? sz : results->bufsize; if(C4_LIKELY(sz <= buf->len)) results->lastok = currarg; else buf->len = 0; } } template<class DumperFn, class Arg> void catsep_dump_resume_(size_t currarg, DumperFn &&dumpfn, DumpResults *C4_RESTRICT results, substr *C4_RESTRICT buf, Arg const& C4_RESTRICT a) { if(C4_LIKELY(results->write_arg(currarg))) { size_t sz = dump(dumpfn, *buf, a); results->bufsize = sz > results->bufsize ? sz : results->bufsize; if(C4_LIKELY(sz <= buf->len)) results->lastok = currarg; else buf->len = 0; } } template<DumperPfn dumpfn, class Sep, class Arg> C4_ALWAYS_INLINE void catsep_dump_resume(size_t currarg, DumpResults *C4_RESTRICT results, substr *C4_RESTRICT buf, Sep const& C4_RESTRICT, Arg const& C4_RESTRICT a) { detail::catsep_dump_resume_<dumpfn>(currarg, results, buf, a); } template<class DumperFn, class Sep, class Arg> C4_ALWAYS_INLINE void catsep_dump_resume(size_t currarg, DumperFn &&dumpfn, DumpResults *C4_RESTRICT results, substr *C4_RESTRICT buf, Sep const& C4_RESTRICT, Arg const& C4_RESTRICT a) { detail::catsep_dump_resume_(currarg, dumpfn, results, buf, a); } template<DumperPfn dumpfn, class Sep, class Arg, class... Args> C4_ALWAYS_INLINE void catsep_dump_resume(size_t currarg, DumpResults *C4_RESTRICT results, substr *C4_RESTRICT buf, Sep const& C4_RESTRICT sep, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { detail::catsep_dump_resume_<dumpfn>(currarg , results, buf, a); detail::catsep_dump_resume_<dumpfn>(currarg + 1u, results, buf, sep); detail::catsep_dump_resume <dumpfn>(currarg + 2u, results, buf, sep, more...); } template<class DumperFn, class Sep, class Arg, class... Args> C4_ALWAYS_INLINE void catsep_dump_resume(size_t currarg, DumperFn &&dumpfn, DumpResults *C4_RESTRICT results, substr *C4_RESTRICT buf, Sep const& C4_RESTRICT sep, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { detail::catsep_dump_resume_(currarg , dumpfn, results, buf, a); detail::catsep_dump_resume_(currarg + 1u, dumpfn, results, buf, sep); detail::catsep_dump_resume (currarg + 2u, dumpfn, results, buf, sep, more...); } } // namespace detail /// @endcond template<DumperPfn dumpfn, class Sep, class... Args> C4_ALWAYS_INLINE DumpResults catsep_dump_resume(DumpResults results, substr buf, Sep const& C4_RESTRICT sep, Args const& C4_RESTRICT ...more) { detail::catsep_dump_resume<dumpfn>(0u, &results, &buf, sep, more...); return results; } template<class DumperFn, class Sep, class... Args> C4_ALWAYS_INLINE DumpResults catsep_dump_resume(DumperFn &&dumpfn, DumpResults results, substr buf, Sep const& C4_RESTRICT sep, Args const& C4_RESTRICT ...more) { detail::catsep_dump_resume(0u, dumpfn, &results, &buf, sep, more...); return results; } template<DumperPfn dumpfn, class Sep, class... Args> C4_ALWAYS_INLINE DumpResults catsep_dump_resume(substr buf, Sep const& C4_RESTRICT sep, Args const& C4_RESTRICT ...more) { DumpResults results; detail::catsep_dump_resume<dumpfn>(0u, &results, &buf, sep, more...); return results; } template<class DumperFn, class Sep, class... Args> C4_ALWAYS_INLINE DumpResults catsep_dump_resume(DumperFn &&dumpfn, substr buf, Sep const& C4_RESTRICT sep, Args const& C4_RESTRICT ...more) { DumpResults results; detail::catsep_dump_resume(0u, dumpfn, &results, &buf, sep, more...); return results; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** take the function pointer as a function argument */ template<class DumperFn> C4_ALWAYS_INLINE size_t format_dump(DumperFn &&dumpfn, substr buf, csubstr fmt) { // we can dump without using buf // but we'll only dump if the buffer is ok if(C4_LIKELY(buf.len > 0 && fmt.len)) dumpfn(fmt); return 0u; } /** take the function pointer as a function argument */ template<DumperPfn dumpfn> C4_ALWAYS_INLINE size_t format_dump(substr buf, csubstr fmt) { // we can dump without using buf // but we'll only dump if the buffer is ok if(C4_LIKELY(buf.len > 0 && fmt.len > 0)) dumpfn(fmt); return 0u; } /** take the function pointer as a function argument */ template<class DumperFn, class Arg, class... Args> size_t format_dump(DumperFn &&dumpfn, substr buf, csubstr fmt, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { // we can dump without using buf // but we'll only dump if the buffer is ok size_t pos = fmt.find("{}"); // @todo use _find_fmt() if(C4_UNLIKELY(pos == csubstr::npos)) { if(C4_LIKELY(buf.len > 0 && fmt.len > 0)) dumpfn(fmt); return 0u; } if(C4_LIKELY(buf.len > 0 && pos > 0)) dumpfn(fmt.first(pos)); // we can dump without using buf fmt = fmt.sub(pos + 2); // skip {} do this before assigning to pos again pos = dump(dumpfn, buf, a); if(C4_UNLIKELY(pos > buf.len)) buf.len = 0; // ensure no more calls to dump size_t size_for_more = format_dump(dumpfn, buf, fmt, more...); return size_for_more > pos ? size_for_more : pos; } /** take the function pointer as a template argument */ template<DumperPfn dumpfn, class Arg, class... Args> size_t format_dump(substr buf, csubstr fmt, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { // we can dump without using buf // but we'll only dump if the buffer is ok size_t pos = fmt.find("{}"); // @todo use _find_fmt() if(C4_UNLIKELY(pos == csubstr::npos)) { if(C4_LIKELY(buf.len > 0 && fmt.len > 0)) dumpfn(fmt); return 0u; } if(C4_LIKELY(buf.len > 0 && pos > 0)) dumpfn(fmt.first(pos)); // we can dump without using buf fmt = fmt.sub(pos + 2); // skip {} do this before assigning to pos again pos = dump<dumpfn>(buf, a); if(C4_UNLIKELY(pos > buf.len)) buf.len = 0; // ensure no more calls to dump size_t size_for_more = format_dump<dumpfn>(buf, fmt, more...); return size_for_more > pos ? size_for_more : pos; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /// @cond dev namespace detail { template<DumperPfn dumpfn> DumpResults format_dump_resume(size_t currarg, DumpResults results, substr buf, csubstr fmt) { // we can dump without using buf // but we'll only dump if the buffer is ok if(C4_LIKELY(buf.len > 0)) { dumpfn(fmt); results.lastok = currarg; } return results; } template<class DumperFn> DumpResults format_dump_resume(size_t currarg, DumperFn &&dumpfn, DumpResults results, substr buf, csubstr fmt) { // we can dump without using buf // but we'll only dump if the buffer is ok if(C4_LIKELY(buf.len > 0)) { dumpfn(fmt); results.lastok = currarg; } return results; } template<DumperPfn dumpfn, class Arg, class... Args> DumpResults format_dump_resume(size_t currarg, DumpResults results, substr buf, csubstr fmt, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { // we need to process the format even if we're not // going to print the first arguments because we're resuming size_t pos = fmt.find("{}"); // @todo use _find_fmt() // we can dump without using buf // but we'll only dump if the buffer is ok if(C4_LIKELY(results.write_arg(currarg))) { if(C4_UNLIKELY(pos == csubstr::npos)) { if(C4_LIKELY(buf.len > 0)) { results.lastok = currarg; dumpfn(fmt); } return results; } if(C4_LIKELY(buf.len > 0)) { results.lastok = currarg; dumpfn(fmt.first(pos)); } } fmt = fmt.sub(pos + 2); if(C4_LIKELY(results.write_arg(currarg + 1))) { pos = dump<dumpfn>(buf, a); results.bufsize = pos > results.bufsize ? pos : results.bufsize; if(C4_LIKELY(pos <= buf.len)) results.lastok = currarg + 1; else buf.len = 0; } return detail::format_dump_resume<dumpfn>(currarg + 2u, results, buf, fmt, more...); } /// @endcond template<class DumperFn, class Arg, class... Args> DumpResults format_dump_resume(size_t currarg, DumperFn &&dumpfn, DumpResults results, substr buf, csubstr fmt, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more) { // we need to process the format even if we're not // going to print the first arguments because we're resuming size_t pos = fmt.find("{}"); // @todo use _find_fmt() // we can dump without using buf // but we'll only dump if the buffer is ok if(C4_LIKELY(results.write_arg(currarg))) { if(C4_UNLIKELY(pos == csubstr::npos)) { if(C4_LIKELY(buf.len > 0)) { results.lastok = currarg; dumpfn(fmt); } return results; } if(C4_LIKELY(buf.len > 0)) { results.lastok = currarg; dumpfn(fmt.first(pos)); } } fmt = fmt.sub(pos + 2); if(C4_LIKELY(results.write_arg(currarg + 1))) { pos = dump(dumpfn, buf, a); results.bufsize = pos > results.bufsize ? pos : results.bufsize; if(C4_LIKELY(pos <= buf.len)) results.lastok = currarg + 1; else buf.len = 0; } return detail::format_dump_resume(currarg + 2u, dumpfn, results, buf, fmt, more...); } } // namespace detail template<DumperPfn dumpfn, class... Args> C4_ALWAYS_INLINE DumpResults format_dump_resume(DumpResults results, substr buf, csubstr fmt, Args const& C4_RESTRICT ...more) { return detail::format_dump_resume<dumpfn>(0u, results, buf, fmt, more...); } template<class DumperFn, class... Args> C4_ALWAYS_INLINE DumpResults format_dump_resume(DumperFn &&dumpfn, DumpResults results, substr buf, csubstr fmt, Args const& C4_RESTRICT ...more) { return detail::format_dump_resume(0u, dumpfn, results, buf, fmt, more...); } template<DumperPfn dumpfn, class... Args> C4_ALWAYS_INLINE DumpResults format_dump_resume(substr buf, csubstr fmt, Args const& C4_RESTRICT ...more) { return detail::format_dump_resume<dumpfn>(0u, DumpResults{}, buf, fmt, more...); } template<class DumperFn, class... Args> C4_ALWAYS_INLINE DumpResults format_dump_resume(DumperFn &&dumpfn, substr buf, csubstr fmt, Args const& C4_RESTRICT ...more) { return detail::format_dump_resume(0u, dumpfn, DumpResults{}, buf, fmt, more...); } } // namespace c4 #endif /* C4_DUMP_HPP_ */
36.036207
221
0.601933
kasper93
483ae437a02f74fadf782d2e3e83a8cec9d68bf9
326
cpp
C++
dialog/dialogsectorsetup.cpp
ignmiz/ATC_Console
549dd67a007cf54b976e33fed1581f30beb08b06
[ "Intel", "MIT" ]
5
2018-01-08T22:20:07.000Z
2021-06-19T17:42:29.000Z
dialog/dialogsectorsetup.cpp
ignmiz/ATC_Console
549dd67a007cf54b976e33fed1581f30beb08b06
[ "Intel", "MIT" ]
null
null
null
dialog/dialogsectorsetup.cpp
ignmiz/ATC_Console
549dd67a007cf54b976e33fed1581f30beb08b06
[ "Intel", "MIT" ]
2
2017-08-07T23:07:42.000Z
2021-05-09T13:02:39.000Z
#include "dialogsectorsetup.h" #include "ui_dialogsectorsetup.h" DialogSectorSetup::DialogSectorSetup(QWidget *parent) : ATCDialog(parent, "Sector Setup", 600, 800), uiInner(new Ui::DialogSectorSetup) { uiInner->setupUi(this); windowSetup(); } DialogSectorSetup::~DialogSectorSetup() { delete uiInner; }
20.375
55
0.726994
ignmiz
c61c1689a56d922465da5c25fd6b6d9ad8e5aec0
5,971
cpp
C++
dblib/src/EDatabase.cpp
cxxjava/CxxDBC
01bee98aa407c9e762cf75f63a2c21942968cf0a
[ "Apache-2.0" ]
20
2017-09-01T08:56:25.000Z
2021-03-18T11:07:38.000Z
dblib/src/EDatabase.cpp
foolishantcat/CxxDBC
f0f9e95baad72318e7fe53231aeca2ffa4a8b574
[ "Apache-2.0" ]
null
null
null
dblib/src/EDatabase.cpp
foolishantcat/CxxDBC
f0f9e95baad72318e7fe53231aeca2ffa4a8b574
[ "Apache-2.0" ]
14
2017-09-01T12:23:36.000Z
2021-09-02T01:06:27.000Z
/* * EDatabase.cpp * * Created on: 2017-6-12 * Author: [email protected] */ #include "../inc/EDatabase.hh" #include "../../interface/EDBInterface.h" namespace efc { namespace edb { EDatabase::~EDatabase() { // } EDatabase::EDatabase(EDBProxyInf* proxy) : m_DBProxy(proxy), m_AutoCommit(true), m_ErrorCode(0), m_CursorID(0) { } sp<EBson> EDatabase::processSQL(EBson *req, void *arg) { #ifdef DEBUG showMessage(req); #endif sp<EBson> rep; int ope = req->getInt(EDB_KEY_MSGTYPE); switch (ope) { case DB_SQL_DBOPEN: rep = onOpen(req); break; case DB_SQL_DBCLOSE: rep = onClose(req); break; case DB_SQL_EXECUTE: { EIterable<EInputStream*>* itb = (EIterable<EInputStream*>*)arg; rep = onExecute(req, itb); break; } case DB_SQL_UPDATE: { EIterable<EInputStream*>* itb = (EIterable<EInputStream*>*)arg; rep = onUpdate(req, itb); break; } case DB_SQL_MORE_RESULT: rep = onMoreResult(req); break; case DB_SQL_RESULT_FETCH: rep = onResultFetch(req); break; case DB_SQL_RESULT_CLOSE: rep = onResultClose(req); break; case DB_SQL_SET_AUTOCOMMIT: { boolean flag = req->getByte(EDB_KEY_AUTOCOMMIT) ? true : false; rep = setAutoCommit(flag); break; } case DB_SQL_COMMIT: rep = onCommit(); break; case DB_SQL_ROLLBACK: rep = onRollback(); break; case DB_SQL_SETSAVEPOINT: rep = setSavepoint(req); break; case DB_SQL_BACKSAVEPOINT: rep = rollbackSavepoint(req); break; case DB_SQL_RELESAVEPOINT: rep = releaseSavepoint(req); break; case DB_SQL_LOB_CREATE: rep = onLOBCreate(); break; case DB_SQL_LOB_WRITE: { EInputStream *is = (EInputStream*)arg; llong oid = req->getLLong(EDB_KEY_OID); rep = onLOBWrite(oid, is); break; } case DB_SQL_LOB_READ: { EOutputStream *os = (EOutputStream*)arg; llong oid = req->getLLong(EDB_KEY_OID); rep = onLOBRead(oid, os); break; } default: { m_ErrorCode = -1; m_ErrorMessage = EString::formatOf("No #%d message.", ope); break; } } if (!rep) { rep = genRspCommFailure(); } #ifdef DEBUG showMessage(rep.get()); #endif return rep; } sp<EBson> EDatabase::onOpen(EBson *req) { char* database = req->get(EDB_KEY_DATABASE); char* host = req->get(EDB_KEY_HOST); int port = req->getInt(EDB_KEY_PORT); char* username = req->get(EDB_KEY_USERNAME); char* password = req->get(EDB_KEY_PASSWORD); char* charset = req->get(EDB_KEY_CHARSET); int timeout = req->getInt(EDB_KEY_TIMEOUT, 60); //默认60秒 boolean ret = open(database, host, port, username, password, charset, timeout); if (!ret) { return null; } sp<EBson> rep = new EBson(); rep->addInt(EDB_KEY_ERRCODE, ES_SUCCESS); rep->add(EDB_KEY_VERSION, m_DBProxy ? m_DBProxy->getProxyVersion().c_str(): null); rep->add(EDB_KEY_DBTYPE, dbtype().c_str()); rep->add(EDB_KEY_DBVERSION, dbversion().c_str()); return rep; } sp<EBson> EDatabase::onClose(EBson *req) { boolean ret = close(); if (!ret) { return null; } sp<EBson> rep = new EBson(); rep->addInt(EDB_KEY_ERRCODE, ES_SUCCESS); return rep; } sp<EBson> EDatabase::doSavepoint(EBson *req, EString& sql) { //转换请求为onUpdate(req) req->setInt(EDB_KEY_MSGTYPE, DB_SQL_UPDATE); req->add(EDB_KEY_SQLS "/" EDB_KEY_SQL, sql.c_str()); return onUpdate(req, null); } sp<EBson> EDatabase::setSavepoint(EBson *req) { EString name = req->getString(EDB_KEY_NAME); EString sql = EString::formatOf("SAVEPOINT %s", name.c_str()); return doSavepoint(req, sql); } sp<EBson> EDatabase::rollbackSavepoint(EBson *req) { EString name = req->getString(EDB_KEY_NAME); EString sql = EString::formatOf("ROLLBACK TO SAVEPOINT %s", name.c_str()); return doSavepoint(req, sql); } sp<EBson> EDatabase::releaseSavepoint(EBson *req) { EString name = req->getString(EDB_KEY_NAME); EString sql = EString::formatOf("RELEASE SAVEPOINT %s", name.c_str()); return doSavepoint(req, sql); } boolean EDatabase::getAutoCommit() { return m_AutoCommit; } llong EDatabase::newCursorID() { return ++m_CursorID; } llong EDatabase::currCursorID() { return m_CursorID; } sp<EBson> EDatabase::genRspCommSuccess() { sp<EBson> rep = new EBson(); rep->addInt(EDB_KEY_ERRCODE, ES_SUCCESS); return rep; } sp<EBson> EDatabase::genRspCommFailure() { sp<EBson> rep = new EBson(); rep->addInt(EDB_KEY_ERRCODE, ES_FAILURE); rep->add(EDB_KEY_ERRMSG, m_ErrorMessage.c_str()); return rep; } void EDatabase::dumpSQL(const char *oldSql, const char *newSql) { if (m_DBProxy != null && (oldSql || newSql)) { m_DBProxy->dumpSQL(oldSql, newSql); } } void EDatabase::setErrorCode(int errcode) { m_ErrorCode = errcode; } int EDatabase::getErrorCode() { return m_ErrorCode; } void EDatabase::setErrorMessage(const char* message) { m_ErrorMessage = message; } EString EDatabase::getErrorMessage() { return m_ErrorMessage; } EString EDatabase::getDBType() { return dbtype(); } #ifdef DEBUG void EDatabase::showMessage(EBson* bson) { EByteArrayOutputStream baos; bson->Export(&baos, NULL); EByteArrayInputStream bais(baos.data(), baos.size()); class BsonParser : public EBsonParser { public: BsonParser(EInputStream *is) : EBsonParser(is) { } void parsing(es_bson_node_t* node) { if (!node) return; for (int i=1; i<_bson->levelOf(node); i++) { printf("\t"); } printf(node->name); printf("-->"); if (eso_strcmp(node->name, "param") == 0) { printf("?"); } else if (eso_strcmp(node->name, "record") == 0) { es_size_t size = 0; void *value = EBson::nodeGet(node, &size); EByteArrayInputStream bais(value, size); EDataInputStream dis(&bais); int len; try { while ((len = dis.readInt()) != -1) { EA<byte> buf(len + 1); dis.read(buf.address(), len); printf(" %s |", buf.address()); } } catch (...) { } } else { printf(EBson::nodeGetString(node).c_str()); } printf("\n"); } }; BsonParser ep(&bais); EBson bson_; while (ep.nextBson(&bson_)) { // } } #endif } /* namespace edb */ } /* namespace efc */
21.555957
83
0.676269
cxxjava
c61cd1991f720bd75987be76adaf0f5cca6e7768
4,409
cc
C++
bigtable/client/table_admin.cc
cschuet/google-cloud-cpp
e6397ac48571202ee9a7adef298aad9c7c6facde
[ "Apache-2.0" ]
null
null
null
bigtable/client/table_admin.cc
cschuet/google-cloud-cpp
e6397ac48571202ee9a7adef298aad9c7c6facde
[ "Apache-2.0" ]
null
null
null
bigtable/client/table_admin.cc
cschuet/google-cloud-cpp
e6397ac48571202ee9a7adef298aad9c7c6facde
[ "Apache-2.0" ]
null
null
null
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "bigtable/client/table_admin.h" #include "bigtable/client/internal/throw_delegate.h" #include <sstream> namespace btproto = ::google::bigtable::admin::v2; namespace bigtable { inline namespace BIGTABLE_CLIENT_NS { ::google::bigtable::admin::v2::Table TableAdmin::CreateTable( std::string table_id, TableConfig config) { grpc::Status status; auto result = impl_.CreateTable(std::move(table_id), std::move(config), status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } return result; } std::vector<::google::bigtable::admin::v2::Table> TableAdmin::ListTables( ::google::bigtable::admin::v2::Table::View view) { grpc::Status status; auto result = impl_.ListTables(std::move(view), status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } return result; } ::google::bigtable::admin::v2::Table TableAdmin::GetTable( std::string table_id, ::google::bigtable::admin::v2::Table::View view) { grpc::Status status; auto result = impl_.GetTable(std::move(table_id), status, std::move(view)); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } return result; } void TableAdmin::DeleteTable(std::string table_id) { grpc::Status status; impl_.DeleteTable(std::move(table_id), status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } } ::google::bigtable::admin::v2::Table TableAdmin::ModifyColumnFamilies( std::string table_id, std::vector<ColumnFamilyModification> modifications) { grpc::Status status; auto result = impl_.ModifyColumnFamilies(std::move(table_id), std::move(modifications), status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } return result; } void TableAdmin::DropRowsByPrefix(std::string table_id, std::string row_key_prefix) { grpc::Status status; impl_.DropRowsByPrefix(std::move(table_id), std::move(row_key_prefix), status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } } void TableAdmin::DropAllRows(std::string table_id) { grpc::Status status; impl_.DropAllRows(std::move(table_id), status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } } ::google::bigtable::admin::v2::Snapshot TableAdmin::GetSnapshot( bigtable::ClusterId const& cluster_id, bigtable::SnapshotId const& snapshot_id) { grpc::Status status; auto result = impl_.GetSnapshot(cluster_id, snapshot_id, status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } return result; } std::string TableAdmin::GenerateConsistencyToken(std::string const& table_id) { grpc::Status status; std::string token = impl_.GenerateConsistencyToken(std::move(table_id), status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } return token; } bool TableAdmin::CheckConsistency( bigtable::TableId const& table_id, bigtable::ConsistencyToken const& consistency_token) { grpc::Status status; bool consistent = impl_.CheckConsistency(table_id, consistency_token, status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } return consistent; } void TableAdmin::DeleteSnapshot(bigtable::ClusterId const& cluster_id, bigtable::SnapshotId const& snapshot_id) { grpc::Status status; impl_.DeleteSnapshot(cluster_id, snapshot_id, status); if (not status.ok()) { internal::RaiseRpcError(status, status.error_message()); } } } // namespace BIGTABLE_CLIENT_NS } // namespace bigtable
32.902985
80
0.700386
cschuet
c62335a7a24ee968a1db12ff3eb2771af010d9c5
8,847
cpp
C++
source/Irrlicht/CGUIProfiler.cpp
vell001/Irrlicht-vell
23d4f03dbcd35dd93681dc0751f327f584516709
[ "IJG" ]
null
null
null
source/Irrlicht/CGUIProfiler.cpp
vell001/Irrlicht-vell
23d4f03dbcd35dd93681dc0751f327f584516709
[ "IJG" ]
null
null
null
source/Irrlicht/CGUIProfiler.cpp
vell001/Irrlicht-vell
23d4f03dbcd35dd93681dc0751f327f584516709
[ "IJG" ]
null
null
null
// This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h // Written by Michael Zeilfelder #include "CGUIProfiler.h" #ifdef _IRR_COMPILE_WITH_GUI_ #include "IGUITable.h" #include "IGUIScrollBar.h" #include "IGUIEnvironment.h" #include "CProfiler.h" namespace irr { namespace gui { //! constructor CGUIProfiler::CGUIProfiler(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect<s32> rectangle, IProfiler* profiler) : IGUIProfiler(environment, parent, id, rectangle, profiler) , Profiler(profiler) , DisplayTable(0), CurrentGroupIdx(0), CurrentGroupPage(0), NumGroupPages(1) , DrawBackground(false), Frozen(false), UnfreezeOnce(false), ShowGroupsTogether(false) , MinCalls(0), MinTimeSum(0), MinTimeAverage(0.f), MinTimeMax(0) { if ( !Profiler ) Profiler = &getProfiler(); core::recti r(0, 0, rectangle.getWidth(), rectangle.getHeight()); // Really just too lazy to code a complete new element for this. // If anyone can do this nicer he's welcome. DisplayTable = Environment->addTable(r, this, -1, DrawBackground); DisplayTable->setAlignment(EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_LOWERRIGHT); DisplayTable->setSubElement(true); rebuildColumns(); } void CGUIProfiler::fillRow(u32 rowIndex, const SProfileData& data, bool overviewTitle, bool groupTitle) { DisplayTable->setCellText(rowIndex, 0, data.getName()); if ( !overviewTitle ) DisplayTable->setCellText(rowIndex, 1, core::stringw(data.getCallsCounter())); if ( data.getCallsCounter() > 0 ) { DisplayTable->setCellText(rowIndex, 2, core::stringw(data.getTimeSum())); DisplayTable->setCellText(rowIndex, 3, core::stringw((u32)((f32)data.getTimeSum()/(f32)data.getCallsCounter()))); DisplayTable->setCellText(rowIndex, 4, core::stringw(data.getLongestTime())); } if ( overviewTitle || groupTitle ) { const video::SColor titleColor(255, 0, 0, 255); DisplayTable->setCellColor(rowIndex, 0, titleColor); } } void CGUIProfiler::rebuildColumns() { if ( DisplayTable ) { DisplayTable->clear(); DisplayTable->addColumn(L"name "); DisplayTable->addColumn(L"count calls"); DisplayTable->addColumn(L"time(sum)"); DisplayTable->addColumn(L"time(avg)"); DisplayTable->addColumn(L"time(max) "); DisplayTable->setActiveColumn(-1); } } u32 CGUIProfiler::addDataToTable(u32 rowIndex, u32 dataIndex, u32 groupIndex) { const SProfileData& data = Profiler->getProfileDataByIndex(dataIndex); if ( data.getGroupIndex() == groupIndex && data.getCallsCounter() >= MinCalls && ( data.getCallsCounter() == 0 || (data.getTimeSum() >= MinTimeSum && (f32)data.getTimeSum()/(f32)data.getCallsCounter() >= MinTimeAverage && data.getLongestTime() >= MinTimeMax)) ) { rowIndex = DisplayTable->addRow(rowIndex); fillRow(rowIndex, data, false, false); ++rowIndex; } return rowIndex; } void CGUIProfiler::updateDisplay() { if ( DisplayTable ) { DisplayTable->clearRows(); if ( CurrentGroupIdx < Profiler->getGroupCount() ) { bool overview = CurrentGroupIdx == 0; u32 rowIndex = 0; // show description row (overview or name of the following group) const SProfileData& groupData = Profiler->getGroupData(CurrentGroupIdx); if ( !ShowGroupsTogether && (overview || groupData.getCallsCounter() >= MinCalls) ) { rowIndex = DisplayTable->addRow(rowIndex); fillRow(rowIndex, groupData, overview, true); ++rowIndex; } // show overview over all groups? if ( overview ) { for ( u32 i=1; i<Profiler->getGroupCount(); ++i ) { const SProfileData& groupData = Profiler->getGroupData(i); if ( groupData.getCallsCounter() >= MinCalls ) { rowIndex = DisplayTable->addRow(rowIndex); fillRow(rowIndex, groupData, false, false); ++rowIndex; } } } // show data for all elements in current group else { for ( u32 i=0; i < Profiler->getProfileDataCount(); ++i ) { rowIndex = addDataToTable(rowIndex, i, CurrentGroupIdx); } } // Show the rest of the groups if (ShowGroupsTogether) { for ( u32 groupIdx = CurrentGroupIdx+1; groupIdx < Profiler->getGroupCount(); ++groupIdx) { for ( u32 i=0; i < Profiler->getProfileDataCount(); ++i ) { rowIndex = addDataToTable(rowIndex, i, groupIdx); } } } } // IGUITable has no page-wise scrolling yet. The following code can be replaced when we add that. // For now we use some CGUITable implementation info to figure this out. // (If you wonder why I didn't code page-scrolling directly in CGUITable ... because then it needs to be a // public interface and I don't have enough time currently to design & implement that well) s32 itemsTotalHeight = DisplayTable->getRowCount() * DisplayTable->getItemHeight(); s32 tableHeight = DisplayTable->getAbsolutePosition().getHeight(); s32 heightTitleRow = DisplayTable->getItemHeight()+1; if ( itemsTotalHeight+heightTitleRow < tableHeight ) { NumGroupPages = 1; } else { s32 heightHScrollBar = DisplayTable->getHorizontalScrollBar() ? DisplayTable->getHorizontalScrollBar()->getAbsolutePosition().getHeight() : 0; s32 pageHeight = tableHeight - (heightTitleRow+heightHScrollBar); if ( pageHeight > 0 ) { NumGroupPages = (itemsTotalHeight/pageHeight); if ( itemsTotalHeight % pageHeight ) ++NumGroupPages; } else // won't see anything, but that's up to the user { NumGroupPages = DisplayTable->getRowCount(); } if ( NumGroupPages < 1 ) NumGroupPages = 1; } if ( CurrentGroupPage < 0 ) CurrentGroupPage = (s32)NumGroupPages-1; IGUIScrollBar* vScrollBar = DisplayTable->getVerticalScrollBar(); if ( vScrollBar ) { if ( NumGroupPages < 2 ) vScrollBar->setPos(0); else { f32 factor = (f32)CurrentGroupPage/(f32)(NumGroupPages-1); vScrollBar->setPos( s32(factor * (f32)vScrollBar->getMax()) ); } } } } void CGUIProfiler::draw() { if ( isVisible() ) { if (!Frozen || UnfreezeOnce) { UnfreezeOnce = false; updateDisplay(); } } IGUIElement::draw(); } void CGUIProfiler::nextPage(bool includeOverview) { UnfreezeOnce = true; if ( CurrentGroupPage < NumGroupPages-1 ) ++CurrentGroupPage; else { CurrentGroupPage = 0; if ( ++CurrentGroupIdx >= Profiler->getGroupCount() ) { if ( includeOverview ) CurrentGroupIdx = 0; else CurrentGroupIdx = 1; // can be invalid } } } void CGUIProfiler::previousPage(bool includeOverview) { UnfreezeOnce = true; if ( CurrentGroupPage > 0 ) { --CurrentGroupPage; } else { CurrentGroupPage = -1; // unknown because NumGroupPages has to be re-calculated first if ( CurrentGroupIdx > 0 ) --CurrentGroupIdx; else CurrentGroupIdx = Profiler->getGroupCount()-1; if ( CurrentGroupIdx == 0 && !includeOverview ) { if ( Profiler->getGroupCount() ) CurrentGroupIdx = Profiler->getGroupCount()-1; if ( CurrentGroupIdx == 0 ) CurrentGroupIdx = 1; // invalid to avoid showing the overview } } } void CGUIProfiler::setShowGroupsTogether(bool groupsTogether) { ShowGroupsTogether = groupsTogether; } bool CGUIProfiler::getShowGroupsTogether() const { return ShowGroupsTogether; } void CGUIProfiler::firstPage(bool includeOverview) { UnfreezeOnce = true; if ( includeOverview ) CurrentGroupIdx = 0; else CurrentGroupIdx = 1; // can be invalid CurrentGroupPage = 0; } //! Sets another skin independent font. void CGUIProfiler::setOverrideFont(IGUIFont* font) { if ( DisplayTable ) { DisplayTable->setOverrideFont(font); rebuildColumns(); } } //! Gets the override font (if any) IGUIFont * CGUIProfiler::getOverrideFont() const { if ( DisplayTable ) return DisplayTable->getOverrideFont(); return 0; } //! Get the font which is used right now for drawing IGUIFont* CGUIProfiler::getActiveFont() const { if ( DisplayTable ) return DisplayTable->getActiveFont(); return 0; } //! Sets whether to draw the background. By default disabled, void CGUIProfiler::setDrawBackground(bool draw) { DrawBackground = draw; if ( DisplayTable ) DisplayTable->setDrawBackground(draw); } //! Checks if background drawing is enabled bool CGUIProfiler::isDrawBackgroundEnabled() const { return DrawBackground; } //! Allows to freeze updates which makes it easier to read the numbers void CGUIProfiler::setFrozen(bool freeze) { Frozen = freeze; } //! Are updates currently frozen bool CGUIProfiler::getFrozen() const { return Frozen; } void CGUIProfiler::setFilters(irr::u32 minCalls, irr::u32 minTimeSum, irr::f32 minTimeAverage, irr::u32 minTimeMax) { MinCalls = minCalls; MinTimeSum = minTimeSum; MinTimeAverage = minTimeAverage; MinTimeMax = minTimeMax; } } // end namespace gui } // end namespace irr #endif // _IRR_COMPILE_WITH_GUI_
26.64759
145
0.703628
vell001
c623e28ad67a964099a008365d871a39ceb7eb6f
6,161
hpp
C++
foedus_code/foedus-core/include/foedus/log/log_type.hpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/foedus-core/include/foedus/log/log_type.hpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/foedus-core/include/foedus/log/log_type.hpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2014-2015, Hewlett-Packard Development Company, LP. * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * HP designates this particular file as subject to the "Classpath" exception * as provided by HP in the LICENSE.txt file that accompanied this code. */ #ifndef FOEDUS_LOG_LOG_TYPE_HPP_ #define FOEDUS_LOG_LOG_TYPE_HPP_ #include "foedus/cxx11.hpp" // include all header files that forward-declare log types defined in the xmacro. // don't include headers that really declare them. we just need foward-declarations here. #include "foedus/log/fwd.hpp" #include "foedus/storage/fwd.hpp" #include "foedus/storage/array/fwd.hpp" #include "foedus/storage/hash/fwd.hpp" #include "foedus/storage/masstree/fwd.hpp" #include "foedus/storage/sequential/fwd.hpp" namespace foedus { namespace log { /** * @defgroup LOGTYPE Log Types * @ingroup LOG * @brief Defines the content and \e apply logic of transactional operatrions. * @details * Each loggable operation defines a struct XxxLogType that has the following methods: * * \li "populate" method to populate all properties, but the method is not overridden and its * signature varies. This is just to have a uniform method name for readability. * \li One of the 3 apply methods as follows. These also populate xct_order in log if applicable * (remember, XctId or xct_order is finalized only at commit time, so populate() can't do it). * \li void apply_engine(Thread*) : For engine-wide operation. * \li void apply_storage(Engine*, StorageId) : For storage-wide operation. * \li void apply_record(Thread*, StorageId, RwLockableXctId*, char*) : For record-wise operation. * \li void assert_valid() : For debugging (should have no cost in NDEBUG). * \li is_engine_log()/is_storage_log()/is_record_log() * \li ostream operator, preferably in xml format. * * For non-applicable apply-type, the implmentation class should abort. * Remember that these are all non-virtual methods. See the next section for more details. * * @par No polymorphism * There is no polymorphism guaranteed for log types. * Because we read/write just a bunch of bytes and do reinterpret_cast, there is no dynamic * type information. We of course can't afford instantiating objects for each log entry, either. * Do not use any override in log type classes. You should even delete \b all constructors to avoid * misuse (see LOG_TYPE_NO_CONSTRUCT(clazz) ). * We do have base classes (EngineLogType, StorageLogType, and RecordLogType), but this is only * to reduce typing. No virtual methods. * * @par Current List of LogType * See foedus::log::LogCode * * @par log_type.hpp and log_type_invoke.hpp * This file defines only log codes and names, so quite compact even after preprocessing. * On the other hand, log_type_invoke.hpp defines more methods that need to include a few * more headers, so its size is quite big after proprocessing. Most places should need only * log_type.hpp. Include log_type_invoke.hpp only where we invoke apply/ostream etc. */ /** * @var LogCode * @brief A unique identifier of all log types. * @ingroup LOGTYPE * @details * Log code values must follow the convention. * Most significant 4 bits are used to denote the kind of the log: * \li 0x0000: record targetted logs * \li 0x1000: storage targetted logs * \li 0x2000: engine targetted logs * \li 0x3000: markers/fillers * \li ~0xF000 (reserved for future use) */ #define X(a, b, c) /** b: c. @copydoc c */ a = b, enum LogCode { /** 0 is reserved as a non-existing log type. */ kLogCodeInvalid = 0, #include "foedus/log/log_type.xmacro" // NOLINT }; #undef X /** * @var LogCodeKind * @brief Represents the kind of log types. * @ingroup LOGTYPE * @details * This is the most significant 4 bits of LogCode. */ enum LogCodeKind { /** record targetted logs */ kRecordLogs = 0, /** storage targetted logs */ kStorageLogs = 1, /** engine targetted logs */ kEngineLogs = 2, /** markers/fillers */ kMarkerLogs = 3, }; /** * @brief Returns the kind of the given log code. * @ingroup LOGTYPE * @details * This is inlined here because it's called frequently. */ inline LogCodeKind get_log_code_kind(LogCode code) { return static_cast<LogCodeKind>(code >> 12); } /** * @brief Returns if the LogCode value exists. * @ingroup LOGTYPE * @details * This is inlined here because it's called frequently. */ inline bool is_valid_log_type(LogCode code) { switch (code) { #define X(a, b, c) case a: return true; #include "foedus/log/log_type.xmacro" // NOLINT #undef X default: return false; } } /** * @brief Returns the names of LogCode enum defined in log_type.xmacro. * @ingroup LOGTYPE * @details * This is NOT inlined because this is used only in debugging situation. */ const char* get_log_type_name(LogCode code); /** * @brief Returns LogCode for the log type defined in log_type.xmacro. * @ingroup LOGTYPE * @details * This is inlined below because it's called VERY frequently. * This method is declared as constexpr if C++11 is enabled, in which case there should * be really no overheads to call this method. */ template <typename LOG_TYPE> CXX11_CONSTEXPR LogCode get_log_code(); // give a template specialization for each log type class #define X(a, b, c) template <> inline CXX11_CONSTEXPR LogCode get_log_code< c >() { return a ; } #include "foedus/log/log_type.xmacro" // NOLINT #undef X } // namespace log } // namespace foedus #endif // FOEDUS_LOG_LOG_TYPE_HPP_
37.339394
100
0.735108
sam1016yu
c6266ab319663c6f8892dc11f413a75e87b5a237
1,021
hpp
C++
soccer/src/soccer/planning/planner/pivot_path_planner.hpp
xiaoqingyu0113/robocup-software
6127d25fc455051ef47610d0e421b2ca7330b4fa
[ "Apache-2.0" ]
200
2015-01-26T01:45:34.000Z
2022-03-19T13:05:31.000Z
soccer/src/soccer/planning/planner/pivot_path_planner.hpp
xiaoqingyu0113/robocup-software
6127d25fc455051ef47610d0e421b2ca7330b4fa
[ "Apache-2.0" ]
1,254
2015-01-03T01:57:35.000Z
2022-03-16T06:32:21.000Z
soccer/src/soccer/planning/planner/pivot_path_planner.hpp
xiaoqingyu0113/robocup-software
6127d25fc455051ef47610d0e421b2ca7330b4fa
[ "Apache-2.0" ]
206
2015-01-21T02:03:18.000Z
2022-02-01T17:57:46.000Z
#pragma once #include "planner.hpp" namespace planning { class PivotPathPlanner : public PlannerForCommandType<PivotCommand> { public: PivotPathPlanner() : PlannerForCommandType<PivotCommand>("PivotPathPlanner") {} ~PivotPathPlanner() override = default; PivotPathPlanner(PivotPathPlanner&&) noexcept = default; PivotPathPlanner& operator=(PivotPathPlanner&&) noexcept = default; PivotPathPlanner(const PivotPathPlanner&) = default; PivotPathPlanner& operator=(const PivotPathPlanner&) = default; Trajectory plan(const PlanRequest& request) override; void reset() override { previous_ = Trajectory{}; cached_pivot_target_ = std::nullopt; cached_pivot_point_ = std::nullopt; } private: Trajectory previous_; // Cache the pivot point and target so we don't just push the ball across the field. std::optional<rj_geometry::Point> cached_pivot_point_; std::optional<rj_geometry::Point> cached_pivot_target_; }; } // namespace planning
31.90625
88
0.728697
xiaoqingyu0113
c626a868fd2d71e50fd03c69ba5e5795e54b5462
626
cpp
C++
src/realsense_demo.cpp
ivision-ufba/depth-face-detection
f70441eb9e72fa3f509458ffc202648c2f3e27d1
[ "MIT" ]
15
2017-11-01T11:39:32.000Z
2021-04-02T02:42:59.000Z
src/realsense_demo.cpp
ivision-ufba/depth-face-detection
f70441eb9e72fa3f509458ffc202648c2f3e27d1
[ "MIT" ]
6
2017-07-26T17:55:27.000Z
2020-11-15T22:04:35.000Z
src/realsense_demo.cpp
ivision-ufba/depth-face-detection
f70441eb9e72fa3f509458ffc202648c2f3e27d1
[ "MIT" ]
5
2018-05-09T13:42:17.000Z
2020-01-17T06:22:59.000Z
#include <opencv2/highgui.hpp> #include "face_detector.hpp" #include "realsense.hpp" /* RealSense demonstration for faces in angles from 0 to 30 degrees in the * x-axis, -20 to 20 in the y-xis and no rotation in the z-axis */ int main() { RealSense rs; FaceDetector detector; while (true) { rs.get_images(); auto dets = detector.range_detect(rs.depth, rs.calibration, 0, -20, 0, 30, 20, 0); cvtColor(rs.depth, rs.depth, CV_GRAY2RGB); for (auto det : dets) cv::rectangle(rs.depth, det, cv::Scalar((1 << 16) - 1, 0, 0), 1); cv::imshow("depth", rs.depth); cv::waitKey(10); } }
25.04
78
0.635783
ivision-ufba
c628548dee59482174d11be3a487ed1748817b0d
5,817
cpp
C++
c86ctl/src/vis/vis_c86sub.cpp
honet/c86ctl
c1e454d4e0652c55dacb9435dfac218dfad89e7f
[ "BSD-3-Clause" ]
10
2015-04-04T17:05:04.000Z
2021-12-31T02:51:43.000Z
c86ctl/src/vis/vis_c86sub.cpp
honet/c86ctl
c1e454d4e0652c55dacb9435dfac218dfad89e7f
[ "BSD-3-Clause" ]
null
null
null
c86ctl/src/vis/vis_c86sub.cpp
honet/c86ctl
c1e454d4e0652c55dacb9435dfac218dfad89e7f
[ "BSD-3-Clause" ]
2
2015-04-09T14:16:29.000Z
2020-12-16T02:00:50.000Z
/*** c86ctl Copyright (c) 2009-2012, honet. All rights reserved. This software is licensed under the BSD license. honet.kk(at)gmail.com */ #include "stdafx.h" #include <stdlib.h> #include <stdio.h> #include <math.h> #include "resource.h" #include "vis_c86sub.h" #include "vis_c86skin.h" #ifdef _DEBUG #define new new(_NORMAL_BLOCK,__FILE__,__LINE__) #endif // -------------------------------------------------------------------------------------- void c86ctl::vis::blt( IVisBitmap *dst, int dst_x, int dst_y, int w, int h, IVisBitmap *src, int src_x, int src_y ) { if( dst_x<0 || dst_y<0 || src_x<0 || src_y<0 ) return; if( src_x+w > src->getWidth() || src_y+h > src->getHeight() || dst_x+w > dst->getWidth() || dst_y+h > dst->getHeight() ) return; for( int y=0; y<h; y++ ){ UINT *ps = ((UINT*)src->getRow0( src_y+y )) + src_x; UINT *pd = ((UINT*)dst->getRow0( dst_y+y )) + dst_x; for( int x=0; x<w; x++ ){ *pd++ = (*ps++|0xff000000); } } } void c86ctl::vis::alphablt( IVisBitmap *dst, int dst_x, int dst_y, int w, int h, IVisBitmap *src, int src_x, int src_y ) { if( dst_x<0 || dst_y<0 || src_x<0 || src_y<0 ) return; if( src_x+w > src->getWidth() || src_y+h > src->getHeight() || dst_x+w > dst->getWidth() || dst_y+h > dst->getHeight() ) return; for( int y=0; y<h; y++ ){ UINT *ps = ((UINT*)src->getRow0( src_y+y )) + src_x; UINT *pd = ((UINT*)dst->getRow0( dst_y+y )) + dst_x; for( int x=0; x<w; x++ ){ UINT a = *ps >> 24; UINT na = a^0xff; // 255-a UINT s = *ps; UINT d = *pd; UINT t; // (s*a) + (d*(1-a)) t = (((((s&0x00ff00ff) * ( a+1)) >> 8) & 0x00ff00ff) | ((((s&0x0000ff00) * ( a+1)) >> 8) & 0x0000ff00)) + + (((((d&0x00ff00ff) * (na+1)) >> 8) & 0x00ff00ff) | ((((d&0x0000ff00) * (na+1)) >> 8) & 0x0000ff00)); *pd = t; ps++; pd++; } } } void c86ctl::vis::transblt( IVisBitmap *dst, int dst_x, int dst_y, int w, int h, IVisBitmap *src1, int src1_x, int src1_y, IVisBitmap *src2, int src2_x, int src2_y, IVisBitmap *trans, int trans_x, int trans_y, int t ) { if( dst_x<0 || dst_y<0 || trans_x<0 || trans_y<0 ) return; if( src1_x<0 || src1_y<0 || src2_x<0 || src2_y<0 ) return; if( dst_x+w > dst->getWidth() || dst_y+h > dst->getHeight() || src1_x+w > src1->getWidth() || src1_y+h > src1->getHeight() || src2_x+w > src2->getWidth() || src2_y+h > src2->getHeight() || trans_x+w > trans->getWidth() || trans_y+h > trans->getHeight() ) return; for( int y=0; y<h; y++ ){ UINT *pd = (UINT*)dst->getRow0( dst_y+y ) + dst_x; UINT *ps1 = (UINT*)src1->getRow0( src1_y+y ) + src1_x; UINT *ps2 = (UINT*)src2->getRow0( src2_y+y ) + src2_x; UINT *ts = (UINT*)trans->getRow0( trans_y+y ) + trans_x; for( int x=0; x<w; x++ ){ int a = *ts&0xff; *pd = ( (t<=a) ? *ps1 : *ps2 ) | 0xff000000; pd++; ps1++; ps2++; ts++; } } } // [tmin, tmax) void c86ctl::vis::transblt2( IVisBitmap *dst, int dst_x, int dst_y, int w, int h, IVisBitmap *src1, int src1_x, int src1_y, IVisBitmap *src2, int src2_x, int src2_y, IVisBitmap *trans, int trans_x, int trans_y, int tmin, int tmax ) { if( dst_x<0 || dst_y<0 || trans_x<0 || trans_y<0 ) return; if( src1_x<0 || src1_y<0 || src2_x<0 || src2_y<0 ) return; if( dst_x+w > dst->getWidth() || dst_y+h > dst->getHeight() || src1_x+w > src1->getWidth() || src1_y+h > src1->getHeight() || src2_x+w > src2->getWidth() || src2_y+h > src2->getHeight() || trans_x+w > trans->getWidth() || trans_y+h > trans->getHeight() ) return; for( int y=0; y<h; y++ ){ UINT *pd = (UINT*)dst->getRow0( dst_y+y ) + dst_x; UINT *ps1 = (UINT*)src1->getRow0( src1_y+y ) + src1_x; UINT *ps2 = (UINT*)src2->getRow0( src2_y+y ) + src2_x; UINT *ts = (UINT*)trans->getRow0( trans_y+y ) + trans_x; for( int x=0; x<w; x++ ){ int a = *ts&0xff; *pd = ( (tmin<=a && a<tmax) ? *ps2 : *ps1 ) | 0xff000000; pd++; ps1++; ps2++; ts++; } } } void c86ctl::vis::visDrawLine( IVisBitmap *bmp, int xs, int ys, int xe, int ye, COLORREF col ) { // note: めんどくさがって bpp==4専用コードで書いてるので注意 if( !bmp ) return; if( xs<0 || ys<0 || bmp->getWidth()<=xs || bmp->getHeight()<=ys ) return; if( xe<0 || ye<0 || bmp->getWidth()<=xe || bmp->getHeight()<=ye ) return; int step = bmp->getStep()>>2; if( xs == xe ){ // 垂直線 if( ye<ys ) SWAP(ys,ye); UINT *p = ((UINT*)bmp->getRow0(ys)) + xs; for( int y=ys; y<=ye; y++ ){ *p = col; p += step; } }else if( ys == ye ){ //水平線 if( xe<xs ) SWAP(xs,xe); UINT *p = ((UINT*)bmp->getRow0(ys)) + xs; for( int x=xs; x<=xe; x++ ){ *p++ = col; } }else{ // 斜め // TODO : デバッグしてないの。 int dx = abs(xe-xs); int dy = abs(ye-ys); int dx2=dx*2; int dy2=dy*2; if( dx > dy ){ if( xe<xs ){ SWAP(xs,xe); SWAP(ys,ye); } UINT *p = ((UINT*)bmp->getRow0(ys)) + xs; int dstep = ys<ye ? step : -step; for( int e=dy, x=xs; x<=xe; x++, p+=1 ){ *p = col; e+=dy2; if( e>=dx2 ){ e-=dx2; p+=dstep; } } }else{ if( ye<ys ){ SWAP(xs,xe); SWAP(ys,ye); } UINT *p = ((UINT*)bmp->getRow0(ys)) + xs; int dstep = xs<xe ? 1 : -1; for( int e=dx, y=ys; y<=ye; y++, p+=step ){ *p = col; e+=dx2; if( e>=dy2 ){ e-=dy2; p+=dstep; } } } } } void c86ctl::vis::visFillRect( IVisBitmap *bmp, int xs, int ys, int w, int h, COLORREF col ) { if( !bmp ) return; if( xs<0 || ys<0 || bmp->getWidth()<(xs+w) || bmp->getHeight()<(ys+h) ) return; for( int y=0; y<h; y++ ){ UINT *p = ((UINT*)bmp->getRow0(ys+y)) + xs; for( int x=0; x<w; x++ ){ *p++ = col; } } }
26.440909
90
0.517105
honet
c6318ce193499b2925946ca964effcaef39c3f7b
6,842
cpp
C++
dotnet/native/sealnet/galoiskeys_wrapper.cpp
MasterMann/SEAL
791ae130de895e6323d36a12515cf2d59071e414
[ "MIT" ]
5
2019-04-29T01:46:05.000Z
2021-10-10T10:28:02.000Z
dotnet/native/sealnet/galoiskeys_wrapper.cpp
MasterMann/SEAL
791ae130de895e6323d36a12515cf2d59071e414
[ "MIT" ]
null
null
null
dotnet/native/sealnet/galoiskeys_wrapper.cpp
MasterMann/SEAL
791ae130de895e6323d36a12515cf2d59071e414
[ "MIT" ]
4
2019-04-18T11:28:13.000Z
2020-11-01T14:25:35.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. // SEALNet #include "sealnet/stdafx.h" #include "sealnet/galoiskeys_wrapper.h" #include "sealnet/utilities.h" // SEAL #include "seal/galoiskeys.h" using namespace std; using namespace seal; using namespace sealnet; namespace seal { struct GaloisKeys::GaloisKeysPrivateHelper { static void set_decomposition_bit_count(GaloisKeys &keys, int value) { keys.decomposition_bit_count_ = value; } }; } namespace { HRESULT GetKeyFromVector(const vector<Ciphertext> &key, uint64_t *count, void **ciphers) { *count = key.size(); if (nullptr == ciphers) { // We only wanted the count return S_OK; } auto ciphertexts = reinterpret_cast<Ciphertext**>(ciphers); for (size_t i = 0; i < key.size(); i++) { ciphertexts[i] = new Ciphertext(key[i]); } return S_OK; } } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_Create1(void **galois_keys) { IfNullRet(galois_keys, E_POINTER); GaloisKeys *keys = new GaloisKeys(); *galois_keys = keys; return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_Create2(void *copy, void **galois_keys) { GaloisKeys *copyptr = FromVoid<GaloisKeys>(copy); IfNullRet(copyptr, E_POINTER); IfNullRet(galois_keys, E_POINTER); GaloisKeys *keys = new GaloisKeys(*copyptr); *galois_keys = keys; return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_Destroy(void *thisptr) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); delete keys; return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_Set(void *thisptr, void *assign) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); GaloisKeys *assignptr = FromVoid<GaloisKeys>(assign); IfNullRet(assignptr, E_POINTER); *keys = *assignptr; return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_Size(void *thisptr, uint64_t *size) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(size, E_POINTER); *size = keys->size(); return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_DBC(void *thisptr, int *dbc) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(dbc, E_POINTER); *dbc = keys->decomposition_bit_count(); return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_SetDBC(void *thisptr, int dbc) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); GaloisKeys::GaloisKeysPrivateHelper::set_decomposition_bit_count(*keys, dbc); return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_GetKeyCount(void *thisptr, uint64_t *key_count) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(key_count, E_POINTER); *key_count = keys->data().size(); return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_GetKeyList(void *thisptr, uint64_t index, uint64_t *count, void **ciphers) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(count, E_POINTER); auto list = keys->data()[index]; return GetKeyFromVector(list, count, ciphers); } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_GetKey(void *thisptr, uint64_t galois_elt, uint64_t *count, void **ciphers) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(count, E_POINTER); if (!keys->has_key(galois_elt)) { return E_INVALIDARG; } const auto &key = keys->key(galois_elt); return GetKeyFromVector(key, count, ciphers); } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_ClearDataAndReserve(void *thisptr, uint64_t size) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); keys->data().clear(); keys->data().reserve(size); return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_AddKeyList(void *thisptr, uint64_t count, void **ciphers) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(ciphers, E_POINTER); Ciphertext **ciphertexts = reinterpret_cast<Ciphertext**>(ciphers); // Don't resize, only reserve keys->data().emplace_back(); keys->data().back().reserve(count); for (uint64_t i = 0; i < count; i++) { Ciphertext *cipher = ciphertexts[i]; Ciphertext new_key(keys->pool()); new_key = *cipher; keys->data().back().emplace_back(move(new_key)); } return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_HasKey(void *thisptr, uint64_t galois_elt, bool *has_key) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(has_key, E_POINTER); try { *has_key = keys->has_key(galois_elt); return S_OK; } catch (const invalid_argument&) { return E_INVALIDARG; } } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_GetParmsId(void *thisptr, uint64_t *parms_id) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(parms_id, E_POINTER); for (size_t i = 0; i < keys->parms_id().size(); i++) { parms_id[i] = keys->parms_id()[i]; } return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_SetParmsId(void *thisptr, uint64_t *parms_id) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(parms_id, E_POINTER); CopyParmsId(parms_id, keys->parms_id()); return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_IsValidFor(void *thisptr, void *contextptr, bool *result) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); const auto &sharedctx = SharedContextFromVoid(contextptr); IfNullRet(sharedctx.get(), E_POINTER); IfNullRet(result, E_POINTER); *result = keys->is_valid_for(sharedctx); return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_IsMetadataValidFor(void *thisptr, void *contextptr, bool *result) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); const auto &sharedctx = SharedContextFromVoid(contextptr); IfNullRet(sharedctx.get(), E_POINTER); IfNullRet(result, E_POINTER); *result = keys->is_metadata_valid_for(sharedctx); return S_OK; } SEALNETNATIVE HRESULT SEALCALL GaloisKeys_Pool(void *thisptr, void **pool) { GaloisKeys *keys = FromVoid<GaloisKeys>(thisptr); IfNullRet(keys, E_POINTER); IfNullRet(pool, E_POINTER); MemoryPoolHandle *handleptr = new MemoryPoolHandle(keys->pool()); *pool = handleptr; return S_OK; }
26.315385
117
0.691026
MasterMann
c6326b407c937159bc6842753b2255d41c32e2b7
5,110
cpp
C++
tests/algo/test_bad_cmp.cpp
hthetran/stxxl
7f0223e52e9f10f28ed7d368cffecbbeeaa60ca7
[ "BSL-1.0" ]
null
null
null
tests/algo/test_bad_cmp.cpp
hthetran/stxxl
7f0223e52e9f10f28ed7d368cffecbbeeaa60ca7
[ "BSL-1.0" ]
null
null
null
tests/algo/test_bad_cmp.cpp
hthetran/stxxl
7f0223e52e9f10f28ed7d368cffecbbeeaa60ca7
[ "BSL-1.0" ]
null
null
null
/*************************************************************************** * tests/algo/test_bad_cmp.cpp * * Part of the STXXL. See http://stxxl.org * * Copyright (C) 2002 Roman Dementiev <[email protected]> * Copyright (C) 2011 Andreas Beckmann <[email protected]> * * 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) **************************************************************************/ #define STXXL_DEFAULT_BLOCK_SIZE(T) 4096 //! \example algo/test_bad_cmp.cpp //! This is an example of how NOT to use \c stxxl::sort() algorithm. //! Here min_value and max_value are used as keys which is forbidden. #include <tlx/die.hpp> #include <tlx/logger.hpp> #include <foxxll/mng.hpp> #include <stxxl/bits/defines.h> #include <stxxl/sort> #include <stxxl/vector> struct my_type { using key_type = unsigned; key_type m_key; key_type m_data; my_type() { } explicit my_type(key_type k) : m_key(k), m_data(0) { } static my_type min_value() { return my_type(std::numeric_limits<key_type>::min()); } static my_type max_value() { return my_type(std::numeric_limits<key_type>::max()); } ~my_type() { } }; std::ostream& operator << (std::ostream& o, const my_type& obj) { o << obj.m_key; return o; } bool operator < (const my_type& a, const my_type& b) { return a.m_key < b.m_key; } bool operator == (const my_type& a, const my_type& b) { return a.m_key == b.m_key; } bool operator != (const my_type& a, const my_type& b) { return a.m_key != b.m_key; } struct cmp : public std::less<my_type> { my_type min_value() const { return my_type::min_value(); } my_type max_value() const { return my_type::max_value(); } }; int main(int argc, char* argv[]) { const size_t SIZE = (argc >= 2) ? strtoul(argv[1], nullptr, 0) : 16; #if STXXL_PARALLEL_MULTIWAY_MERGE LOG1 << "STXXL_PARALLEL_MULTIWAY_MERGE"; #endif size_t memory_to_use = SIZE * STXXL_DEFAULT_BLOCK_SIZE(my_type); using vector_type = stxxl::vector<my_type>; const uint64_t n_records = uint64_t(SIZE * 2 + SIZE / 2) * STXXL_DEFAULT_BLOCK_SIZE(my_type) / sizeof(my_type); vector_type v(n_records); uint64_t aliens, not_stable; size_t bs = vector_type::block_type::size; LOG1 << "Filling vector with min_value..., input size = " << v.size() << " elements (" << ((v.size() * sizeof(my_type)) >> 20) << " MiB)"; for (vector_type::size_type i = 0; i < v.size(); i++) { v[i].m_key = 0; v[i].m_data = static_cast<int>(i + 1); } LOG1 << "Checking order..."; die_unless(stxxl::is_sorted(v.cbegin(), v.cend(), cmp())); LOG1 << "Sorting (using " << (memory_to_use >> 20) << " MiB of memory)..."; stxxl::sort(v.begin(), v.end(), cmp(), memory_to_use); LOG1 << "Checking order..."; die_unless(stxxl::is_sorted(v.cbegin(), v.cend(), cmp())); aliens = not_stable = 0; for (vector_type::size_type i = 0; i < v.size(); i++) { if (v[i].m_data < 1) ++aliens; else if (v[i].m_data != i + 1) ++not_stable; v[i].m_data = static_cast<int>(i + 1); } LOG1 << "elements that were not in the input: " << aliens; LOG1 << "elements not on their expected location: " << not_stable; LOG1 << "Sorting subset (using " << (memory_to_use >> 20) << " MiB of memory)..."; stxxl::sort(v.begin() + bs - 1, v.end() - bs + 2, cmp(), memory_to_use); LOG1 << "Checking order..."; die_unless(stxxl::is_sorted(v.cbegin(), v.cend(), cmp())); aliens = not_stable = 0; for (vector_type::size_type i = 0; i < v.size(); i++) { if (v[i].m_data < 1) ++aliens; else if (v[i].m_data != i + 1) ++not_stable; v[i].m_data = static_cast<int>(i + 1); } LOG1 << "elements that were not in the input: " << aliens; LOG1 << "elements not on their expected location: " << not_stable; LOG1 << "Filling vector with max_value..., input size = " << v.size() << " elements (" << ((v.size() * sizeof(my_type)) >> 20) << " MiB)"; for (vector_type::size_type i = 0; i < v.size(); i++) { v[i].m_key = unsigned(-1); v[i].m_data = int(i + 1); } LOG1 << "Sorting subset (using " << (memory_to_use >> 20) << " MiB of memory)..."; stxxl::sort(v.begin() + bs - 1, v.end() - bs + 2, cmp(), memory_to_use); LOG1 << "Checking order..."; die_unless(stxxl::is_sorted(v.cbegin(), v.cend(), cmp())); aliens = not_stable = 0; for (vector_type::size_type i = 0; i < v.size(); i++) { if (v[i].m_data < 1) ++aliens; else if (v[i].m_data != i + 1) ++not_stable; v[i].m_data = int(i + 1); } LOG1 << "elements that were not in the input: " << aliens; LOG1 << "elements not on their expected location: " << not_stable; LOG1 << "Done, output size=" << v.size() << " block size=" << bs; return 0; }
29.883041
142
0.567906
hthetran
c6384197ea85f1031d58c965a8cf21977a20dc72
1,499
cpp
C++
hash/hash.cpp
kozok-dev/samples
2a33da9ba458a26bc0be373320323a63641e3582
[ "CC0-1.0" ]
null
null
null
hash/hash.cpp
kozok-dev/samples
2a33da9ba458a26bc0be373320323a63641e3582
[ "CC0-1.0" ]
null
null
null
hash/hash.cpp
kozok-dev/samples
2a33da9ba458a26bc0be373320323a63641e3582
[ "CC0-1.0" ]
null
null
null
#include "hash.h" void Hash::Str(const void *pstr, void *pdata, UINT len, const void *pkey, UINT key_len) { if (pkey == NULL) Init(); else initHMAC((BYTE *)pkey, key_len > 0 ? key_len : strlen((char *)pkey)); Update((BYTE *)pstr, len > 0 ? len : strlen((char *)pstr)); if (pkey == NULL) Final(); else finalHMAC(); getHash((BYTE *)pdata); } bool Hash::File(LPCSTR pfilename, void *pdata, const void *pkey, UINT key_len) { BYTE buf[4096]; UINT r; FILE *pfile; pfile = fopen(pfilename, "rb"); if (pfile == NULL) return false; m_stop = false; if (pkey == NULL) Init(); else initHMAC((BYTE *)pkey, key_len); for (;;) { r = fread(buf, 1, sizeof(buf), pfile); if (r == 0 || m_stop) break; Update(buf, r); } if (pkey == NULL) Final(); else finalHMAC(); getHash((BYTE *)pdata); return true; } void Hash::initHMAC(const BYTE *pkey, UINT len) { BYTE buf[128], i; if (len > getBlockSize()) { Init(); Update(pkey, len); Final(); getHash(buf); pkey = buf; len = getHashSize(); } for (i = 0; i < len; i++) { buf[i] = pkey[i] ^ 0x36; m_opad[i] = pkey[i] ^ 0x5c; } for (; i < getBlockSize(); i++) { buf[i] = 0x36; m_opad[i] = 0x5c; } Init(); Update(buf, getBlockSize()); } void Hash::finalHMAC() { BYTE buf[128]; Final(); getHash(buf); Init(); Update(m_opad, getBlockSize()); Update(buf, getHashSize()); Final(); } void Hash::Stop() { m_stop = true; }
18.280488
90
0.559039
kozok-dev
c63a2b28c87818ae1402720a990319b4c7d06c53
2,381
cpp
C++
test/libp2p/peer/key_book/inmem_key_repository_test.cpp
Alexey-N-Chernyshov/cpp-libp2p
8b52253f9658560a4b1311b3ba327f02284a42a6
[ "Apache-2.0", "MIT" ]
135
2020-06-13T08:57:36.000Z
2022-03-27T05:26:11.000Z
test/libp2p/peer/key_book/inmem_key_repository_test.cpp
igor-egorov/cpp-libp2p
7c9d83bf0760a5f653d86ddbb00645414c61d4fc
[ "Apache-2.0", "MIT" ]
41
2020-06-12T15:45:05.000Z
2022-03-07T23:10:33.000Z
test/libp2p/peer/key_book/inmem_key_repository_test.cpp
igor-egorov/cpp-libp2p
7c9d83bf0760a5f653d86ddbb00645414c61d4fc
[ "Apache-2.0", "MIT" ]
43
2020-06-15T10:12:45.000Z
2022-03-21T03:04:50.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include <exception> #include <gtest/gtest.h> #include <libp2p/crypto/key.hpp> #include <libp2p/peer/key_repository.hpp> #include <libp2p/peer/key_repository/inmem_key_repository.hpp> #include "testutil/outcome.hpp" using namespace libp2p::peer; using namespace libp2p::multi; using namespace libp2p::common; using namespace libp2p::crypto; struct InmemKeyRepositoryTest : ::testing::Test { static PeerId createPeerId(HashType type, Buffer b) { auto hash = Multihash::create(type, std::move(b)); if (!hash) { throw std::invalid_argument(hash.error().message()); } auto r1 = PeerId::fromHash(hash.value()); if (!r1) { throw std::invalid_argument(r1.error().message()); } return r1.value(); } PeerId p1_ = createPeerId(HashType::sha256, {1}); PeerId p2_ = createPeerId(HashType::sha256, {2}); std::unique_ptr<KeyRepository> db_ = std::make_unique<InmemKeyRepository>(); }; TEST_F(InmemKeyRepositoryTest, PubkeyStore) { EXPECT_OUTCOME_TRUE_1(db_->addPublicKey(p1_, {{Key::Type::Ed25519, {'a'}}})); EXPECT_OUTCOME_TRUE_1(db_->addPublicKey(p1_, {{Key::Type::Ed25519, {'b'}}})); // insert same pubkey. it should not be inserted EXPECT_OUTCOME_TRUE_1(db_->addPublicKey(p1_, {{Key::Type::Ed25519, {'b'}}})); // same pubkey but different type EXPECT_OUTCOME_TRUE_1(db_->addPublicKey(p1_, {{Key::Type::RSA, {'b'}}})); // put pubkey to different peer EXPECT_OUTCOME_TRUE_1(db_->addPublicKey(p2_, {{Key::Type::RSA, {'c'}}})); EXPECT_OUTCOME_TRUE(v, db_->getPublicKeys(p1_)); EXPECT_EQ(v->size(), 3); db_->clear(p1_); EXPECT_EQ(v->size(), 0); } TEST_F(InmemKeyRepositoryTest, KeyPairStore) { PublicKey pub = {{Key::Type::RSA, {'a'}}}; PrivateKey priv = {{Key::Type::RSA, {'b'}}}; KeyPair kp{pub, priv}; EXPECT_OUTCOME_TRUE_1(db_->addKeyPair({pub, priv})); EXPECT_OUTCOME_TRUE(v, db_->getKeyPairs()); EXPECT_EQ(v->size(), 1); EXPECT_EQ(*v, std::unordered_set<KeyPair>{kp}); } /** * @given 2 peers in storage * @when get peers * @then 2 peers returned */ TEST_F(InmemKeyRepositoryTest, GetPeers) { PublicKey z{}; KeyPair kp{}; EXPECT_OUTCOME_TRUE_1(db_->addPublicKey(p1_, z)); EXPECT_OUTCOME_TRUE_1(db_->addKeyPair(kp)); auto s = db_->getPeers(); EXPECT_EQ(s.size(), 1); }
28.011765
79
0.685006
Alexey-N-Chernyshov
c63c2969392e17bbec61c48820aee3f2b18bc67f
12,025
cpp
C++
co-op/UI/ProjectPropsDlg.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
67
2018-03-02T10:50:02.000Z
2022-03-23T18:20:29.000Z
co-op/UI/ProjectPropsDlg.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
null
null
null
co-op/UI/ProjectPropsDlg.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
9
2018-03-01T16:38:28.000Z
2021-03-02T16:17:09.000Z
//------------------------------------ // (c) Reliable Software, 2000 - 2008 //------------------------------------ #include "precompiled.h" #include "ProjectPropsDlg.h" #include "ProjectOptionsEx.h" #include "ProjectDb.h" #include "OutputSink.h" #include "AppInfo.h" #include "DistributorInfo.h" #include "BrowseForFolder.h" #include <Ctrl/Output.h> #include <Win/Dialog.h> #include <Com/Shell.h> #include <Sys/WinString.h> bool ProjectOptionsCtrl::OnInitDialog () throw (Win::Exception) { Win::Dow::Handle dlgWin (GetWindow ()); _autoSynch.Init (dlgWin, IDC_PROJ_OPTIONS_AUTO_SYNCH); _autoJoin.Init (dlgWin, IDC_PROJ_OPTIONS_AUTO_JOIN); _keepCheckedOut.Init (dlgWin, IDC_PROJ_OPTIONS_KEEP_CHECKED_OUT); _checkoutNotification.Init (dlgWin, IDC_START_CHECKOUT_NOTIFICATIONS); _autoInvite.Init (dlgWin, IDC_OPTIONS_AUTO_INVITE); _projectPath.Init (dlgWin, IDC_OPTIONS_PATH); _pathBrowse.Init (dlgWin, IDC_OPTIONS_BROWSE); InitializeControls (); return true; } bool ProjectOptionsCtrl::OnDlgControl (unsigned ctrlId, unsigned notifyCode) throw (Win::Exception) { if (ctrlId == IDC_OPTIONS_AUTO_INVITE && Win::SimpleControl::IsClicked (notifyCode)) { if (_autoInvite.IsChecked ()) { _projectPath.Enable (); _pathBrowse.Enable (); } else { _projectPath.Disable (); _pathBrowse.Disable (); } } else if (ctrlId == IDC_OPTIONS_BROWSE && Win::SimpleControl::IsClicked (notifyCode)) { std::string path = _projectPath.GetString (); if (BrowseForAnyFolder (path, GetWindow (), "Select folder (existing or not) where new projects will be created.", path.c_str ())) { _projectPath.SetString (path); } } return true; } void ProjectOptionsCtrl::OnSetActive (long & result) throw (Win::Exception) { result = 0; // Assume everything is OK InitializeControls (); } void ProjectOptionsCtrl::OnCancel (long & result) throw (Win::Exception) { _options.Clear (); _options.SetAutoInviteProjectPath (""); _options.SetAutoInvite (false); } void ProjectOptionsCtrl::OnApply (long & result) throw (Win::Exception) { result = 0; // Assume everything is OK _options.SetAutoSynch (_autoSynch.IsChecked ()); if (_options.IsProjectAdmin () && !_options.IsDistribution ()) _options.SetAutoJoin (_autoJoin.IsChecked ()); _options.SetKeepCheckedOut (_keepCheckedOut.IsChecked ()); _options.SetCheckoutNotification (_checkoutNotification.IsChecked ()); if (_options.IsProjectAdmin () && _options.IsAutoSynch () && !_options.IsAutoJoin ()) { Out::Answer userChoice = TheOutput.Prompt ( "You are the Admin for this project and you have selected to\n" "automatically execute all incoming synchronization changes,\n" "but not to automatically accept join requests.\n\n" "You'll have to occasionally check for join request and execute them manually\n\n" "Do you want to continue with your current settings (automatic join request\n" "processing not selected)?", Out::PromptStyle (Out::YesNo, Out::No)); if (userChoice == Out::No) result = 1; // Don't close dialog } _options.SetAutoInvite (_autoInvite.IsChecked ()); _options.SetAutoInviteProjectPath (_projectPath.GetString ()); if (!_options.ValidateAutoInvite (GetWindow ())) result = 1; // Don't close dialog } void ProjectOptionsCtrl::InitializeControls () { if (_options.IsAutoSynch ()) _autoSynch.Check (); else _autoSynch.UnCheck (); if (_options.IsProjectAdmin ()) { if (_options.IsDistribution ()) { _autoJoin.UnCheck (); _autoJoin.Disable (); } else { _autoJoin.Enable (); if (_options.IsAutoJoin ()) _autoJoin.Check (); else _autoJoin.UnCheck (); } } else { _autoJoin.UnCheck (); _autoJoin.Disable (); } if (_options.IsReceiver ()) { _keepCheckedOut.Disable (); _checkoutNotification.Disable (); } else { if (_options.IsKeepCheckedOut ()) _keepCheckedOut.Check (); else _keepCheckedOut.UnCheck (); if (_options.IsCheckoutNotification ()) _checkoutNotification.Check (); else _checkoutNotification.UnCheck (); } _projectPath.SetString (_options.GetAutoInviteProjectPath ()); if (_options.IsAutoInvite ()) { _autoInvite.Check (); } else { _autoInvite.UnCheck (); _projectPath.Disable (); _pathBrowse.Disable (); } } bool ProjectDistributorCtrl::OnInitDialog () throw (Win::Exception) { Win::Dow::Handle dlgWin (GetWindow ()); _distributor.Init (dlgWin, IDC_PROJ_OPTIONS_DISTRIBUTOR); _noBranching.Init (dlgWin, IDC_PROJ_OPTIONS_DISALLOW_BRANCHING); _frame.Init (dlgWin, IDC_DISTRIBUTOR_FRAME); _allBcc.Init (dlgWin, IDC_PROJ_OPTIONS_ALL_BCC_RECIPIENTS); _singleRecipient.Init (dlgWin, IDC_PROJ_OPTIONS_SINGLE_TO_RECIPIENT); _status.Init (dlgWin, IDC_DISTRIBUTOR_STATUS); _license.Init (dlgWin, IDC_DISTRIBUTOR_LICENSE); _buyLicense.Init (dlgWin, IDC_LICENSE_PURCHASE); if (_options.IsDistribution ()) { _status.Hide (); _distributor.Check (); if (_options.IsNoBranching ()) _noBranching.Check (); else _noBranching.UnCheck (); if (_options.UseBccRecipients ()) _allBcc.Check (); else _singleRecipient.Check (); if (!_options.MayBecomeDistributor ()) { // Distributor administrator cannot change his/her distributor status // because there are some other project members beside him/her _distributor.Disable (); _noBranching.Disable (); } } else if (_options.MayBecomeDistributor ()) { _status.Hide (); _distributor.Enable (); _noBranching.Disable (); _allBcc.Check (); _allBcc.Disable (); _singleRecipient.Disable (); } else { _distributor.Hide (); _noBranching.Hide (); _frame.Hide (); _allBcc.Hide (); _singleRecipient.Hide (); _status.SetText ("You cannot become a distributor in this project.\n" "You must be the only member of the project."); } if (_options.GetSeatTotal () != 0) { std::string license ("You have "); license += ToString (_options.GetSeatsAvailable ()); license += " distribution licenses left out of total "; license += ToString (_options.GetSeatTotal ()); license += " licenses assigned to "; license += _options.GetDistributorLicensee (); _license.SetText (license.c_str ()); } else { _license.SetText ("You may purchase a distribution license over the Internet."); } return true; } bool ProjectDistributorCtrl::OnDlgControl (unsigned ctrlId, unsigned notifyCode) throw (Win::Exception) { switch (ctrlId) { case IDC_LICENSE_PURCHASE: if (Win::SimpleControl::IsClicked (notifyCode)) { Win::Dow::Handle appWnd = TheAppInfo.GetWindow (); int errCode = ShellMan::Open (appWnd, DistributorPurchaseLink); if (errCode != -1) { std::string msg = ShellMan::HtmlOpenError (errCode, "license", DistributorPurchaseLink); TheOutput.Display (msg.c_str (), Out::Error, GetWindow ()); } else { PressButton (PropPage::Ok); } } return true; case IDC_PROJ_OPTIONS_DISTRIBUTOR: if (Win::SimpleControl::IsClicked (notifyCode)) { if (_distributor.IsChecked ()) { _options.SetDistribution (true); _noBranching.Enable (); _allBcc.Enable (); _singleRecipient.Enable (); _options.SetAutoJoin (false); } else { _options.SetDistribution (false); _noBranching.Disable (); _allBcc.Disable (); _singleRecipient.Disable (); } } return true; } return false; } void ProjectDistributorCtrl::OnCancel (long & result) throw (Win::Exception) { _options.Clear (); } void ProjectDistributorCtrl::OnApply (long & result) throw (Win::Exception) { result = 0; // Assume everything is OK if (_options.MayBecomeDistributor () || _options.IsDistribution ()) { _options.SetDistribution (_distributor.IsChecked ()); _options.SetNoBranching (_noBranching.IsChecked ()); _options.SetBccRecipients (_allBcc.IsChecked ()); } } bool ProjectEncryptionCtrl::OnInitDialog () throw (Win::Exception) { Win::Dow::Handle dlgWin (GetWindow ()); _isEncrypt.Init (dlgWin, IDC_PROJ_OPTIONS_ENCRYPT); _useCommonKey.Init (dlgWin, IDC_PROJ_OPTIONS_COMMON_PASS); _key.Init (dlgWin, IDC_PROJ_OPTIONS_ENCRYPT_PASS); _key2.Init (dlgWin, IDC_PROJ_OPTIONS_ENCRYPT_PASS2); _keyStatic.Init (dlgWin, IDC_PROJ_OPTIONS_STATIC); _key2Static.Init (dlgWin, IDC_PROJ_OPTIONS_STATIC2); InitializeControls (); return true; } bool ProjectEncryptionCtrl::OnDlgControl (unsigned ctrlId, unsigned notifyCode) throw (Win::Exception) { if (ctrlId == IDC_PROJ_OPTIONS_ENCRYPT) { if (_isEncrypt.IsChecked ()) EnableKeyControls (); else DisableKeyControls (); } else if (ctrlId == IDC_PROJ_OPTIONS_COMMON_PASS) { if (_useCommonKey.IsChecked ()) { _key.SetText (_options.GetEncryptionCommonKey ()); _key2.SetText (_options.GetEncryptionCommonKey ()); _key.Disable (); _key2.Disable (); } else { _key.Enable (); _key2.Enable (); _key.Clear (); _key2.Clear (); } } return true; } void ProjectEncryptionCtrl::OnKillActive (long & result) throw (Win::Exception) { result = 0; std::string key; std::string key2; if (_isEncrypt.IsChecked ()) { key = _key.GetString (); key2 = _key2.GetString (); if (key.empty ()) { TheOutput.Display ("Please specify the encryption key."); result = -1; return; } else if (key != key2) { TheOutput.Display ("Encryption keys do not match. Please re-enter the keys."); result = -1; return; } } std::string const originalKey = _options.GetEncryptionOriginalKey (); if (!originalKey.empty ()) { if (key.empty ()) { if (TheOutput.Prompt ("Are you sure you want to turn the encryption off?" "\nYou will not be able to receive encoded scripts.") != Out::Yes) { result = -1; return; } } else if (key != originalKey) { if (TheOutput.Prompt ("Are you sure you want to change the encryption key?" "\n(You will not be able to receive scripts encrypted" "\nwith the old key.)") != Out::Yes) { result = -1; return; } } } _options.SetEncryptionKey (key); } void ProjectEncryptionCtrl::OnCancel (long & result) throw (Win::Exception) { _options.Clear (); } void ProjectEncryptionCtrl::InitializeControls () { if (_options.GetEncryptionCommonKey ().empty ()) _useCommonKey.Disable (); std::string const key = _options.GetEncryptionKey (); if (key.empty ()) { _isEncrypt.UnCheck (); DisableKeyControls (); } else { _isEncrypt.Check (); EnableKeyControls (); _key.SetString (key); _key2.SetString (key); } } void ProjectEncryptionCtrl::DisableKeyControls () { _useCommonKey.Disable (); _keyStatic.Disable (); _key2Static.Disable (); _key.Disable (); _key2.Disable (); } void ProjectEncryptionCtrl::EnableKeyControls () { if (!_options.GetEncryptionCommonKey ().empty ()) _useCommonKey.Enable (); _keyStatic.Enable (); _key2Static.Enable (); _key.Enable (); _key2.Enable (); } ProjectOptionsHndlrSet::ProjectOptionsHndlrSet (Project::OptionsEx & options) : PropPage::HandlerSet (options.GetCaption ()), _options (options), _optionsPageHndlr (options), _distributorPageHndlr (options), _encryptionPageHndlr (options) { AddHandler (_optionsPageHndlr, "General"); AddHandler (_distributorPageHndlr, "Distributor"); // Notice: Encryption page is ready for use // AddHandler (_encryptionPageHndlr, "Encryption"); } // command line // -project_options autosynch:"on" or "off" autojoin:"on" or "off" keepcheckedout:"on" or "off" bool ProjectOptionsHndlrSet::GetDataFrom (NamedValues const & source) { std::string autoSyncValue; std::string autoJoinValue; autoSyncValue = source.GetValue ("autosynch"); std::transform (autoSyncValue.begin (), autoSyncValue.end (), autoSyncValue.begin (), tolower); autoJoinValue = source.GetValue ("autojoin"); std::transform (autoJoinValue.begin (), autoJoinValue.end (), autoJoinValue.begin (), tolower); _options.SetAutoSynch (autoSyncValue == "on"); if (_options.IsAutoSynch ()) _options.SetAutoJoin (autoJoinValue == "on"); return !autoSyncValue.empty () || !autoJoinValue.empty (); }
26.141304
103
0.701289
BartoszMilewski
c645e3f9178c4968c207a235b93709d9a8e7bed8
2,944
cpp
C++
DPC++Compiler/simple-vector-inc/src/simple-vector-incr.cpp
jcarlosrm/BaseKit-code-samples
aef313f3846e6095e91ec27609fdd947056dc952
[ "MIT" ]
1
2020-02-21T06:58:51.000Z
2020-02-21T06:58:51.000Z
DPC++Compiler/simple-vector-inc/src/simple-vector-incr.cpp
jcarlosrm/BaseKit-code-samples
aef313f3846e6095e91ec27609fdd947056dc952
[ "MIT" ]
null
null
null
DPC++Compiler/simple-vector-inc/src/simple-vector-incr.cpp
jcarlosrm/BaseKit-code-samples
aef313f3846e6095e91ec27609fdd947056dc952
[ "MIT" ]
null
null
null
//============================================================== // Copyright © 2019 Intel Corporation // // SPDX-License-Identifier: MIT // ============================================================= #include <CL/sycl.hpp> #include <iostream> using namespace cl::sycl; static const size_t N = 2; // ############################################################ // work void work(queue &q) { std::cout << "Device : " << q.get_device().get_info<info::device::name>() << std::endl; // ### Step 1 - Inspect // The code presents one input buffer (vector1) for which Sycl buffer memory // is allocated. The associated with vector1_accessor set to read/write gets // the contents of the buffer. int vector1[N] = {10, 10}; std::cout << "Input : " << vector1[0] << ", " << vector1[1] << std::endl; // ### Step 2 - Add another input vector - vector2 // Uncomment the following line to add input vector2 // int vector2[N] = {20,20}; // ### Step 3 - Print out for vector2 // Uncomment the following line // std::cout << "Input : " << vector2[0] << ", " << vector2[1] << std::endl; buffer<int, 1> vector1_buffer(vector1, range<1>(N)); // ### Step 4 - Add another Sycl buffer - vector2_buffer // Uncomment the following line // buffer<int, 1> vector2_buffer(vector2, range<1>(N)); q.submit([&](handler &h) { auto vector1_accessor = vector1_buffer.get_access<access::mode::read_write>(h); // Step 5 - add an accessor for vector2_buffer // Look in the source code for the comment // auto vector2_accessor = vector2_buffer.template get_access < // access::mode::read > (my_handler); h.parallel_for<class test>(range<1>(N), [=](id<1> index) { // ### Step 6 - Replace the existing vector1_accessor to accumulate // vector2_accessor Comment the line: vector1_accessor[index] += 1; vector1_accessor[index] += 1; // Uncomment the following line // vector1_accessor[index] += vector2_accessor[index]; }); }); q.wait_and_throw(); vector1_buffer.get_access<access::mode::read>(); std::cout << "Output : " << vector1[0] << ", " << vector1[1] << std::endl; } // ############################################################ // entry point for the program int main() { auto exception_handler = [](cl::sycl::exception_list exceptionList) { for (std::exception_ptr const &e : exceptionList) { try { std::rethrow_exception(e); } catch (cl::sycl::exception const &e) { std::cout << "ASYNCHRONOUS SYCL exception:\n" << e.what() << std::endl; std::terminate(); // exit the process immediately. } } }; try { queue q(default_selector{}, exception_handler); work(q); } catch (exception e) { std::cerr << "Exception: " << e.what() << std::endl; std::terminate(); } catch (...) { std::cerr << "Unknown exception" << std::endl; std::terminate(); } }
34.635294
79
0.56284
jcarlosrm
c6515a5a74e42f4587d05da3d5dab3833a584e14
8,397
cpp
C++
server/Enclave/enclave_csk.cpp
ndokmai/sgx-genome-variants-search
dd83fb53d0a82594b9ab2c253a246a80095ca12b
[ "MIT" ]
17
2019-01-07T14:32:31.000Z
2022-03-17T00:36:05.000Z
server/Enclave/enclave_csk.cpp
ndokmai/sgx-genome-variants-search
dd83fb53d0a82594b9ab2c253a246a80095ca12b
[ "MIT" ]
2
2020-04-20T19:05:30.000Z
2021-11-23T05:58:02.000Z
server/Enclave/enclave_csk.cpp
ndokmai/sgx-genome-variants-search
dd83fb53d0a82594b9ab2c253a246a80095ca12b
[ "MIT" ]
3
2019-05-30T20:33:29.000Z
2020-07-29T19:25:17.000Z
#include <stdlib.h> #include <string.h> #include <sgx_trts.h> #include "enclave_csk.h" #include "util.h" struct csk* m_csk = NULL; static inline uint32_t calc_hash(uint64_t x, uint64_t a, uint64_t b) { uint64_t result = a * x + b; result = (result & 0x7FFFFFFF) + (result >> 31); if(result >= 0x7FFFFFFF) { return (uint32_t) (result - 0x7FFFFFFF); } return (uint32_t) result; } void csk_init_param(uint32_t width, uint32_t depth) { m_csk = (csk*) malloc(sizeof(csk)); m_csk->width = width; m_csk->depth = depth; m_csk->width_minus_one = width - 1; m_csk->seeds = NULL; m_csk->s_thres = 200; } void csk_init_seeds() { uint32_t d = m_csk->depth; m_csk->seeds = (uint64_t*) malloc(d * sizeof(uint64_t) << 2); for(size_t i = 0; i < d << 1; i++) { m_csk->seeds[(i << 1)] = my_sgx_rand(); while(m_csk->seeds[(i << 1)] == 0) { m_csk->seeds[(i << 1)] = my_sgx_rand(); } m_csk->seeds[(i << 1) + 1] = my_sgx_rand(); } } void csk_init(uint32_t width, uint32_t depth) { csk_init_param(width, depth); m_csk->sketch = (int16_t**) malloc(depth * sizeof(int16_t*)); m_csk->sketchf = NULL; for(size_t i = 0; i < depth; i++) { m_csk->sketch[i] = (int16_t*) malloc(width * sizeof(int16_t)); memset(m_csk->sketch[i], 0, width * sizeof(int16_t)); } csk_init_seeds(); } void csk_init_f(uint32_t width, uint32_t depth) { csk_init_param(width, depth); m_csk->sketch = NULL; m_csk->sketchf = (float**) malloc(depth * sizeof(float*)); for(size_t i = 0; i < depth; i++) { m_csk->sketchf[i] = (float*) malloc(width * sizeof(float)); memset(m_csk->sketchf[i], 0, width * sizeof(float)); } csk_init_seeds(); } void csk_free() { if(m_csk->seeds != NULL) { free(m_csk->seeds); } if(m_csk->sketch != NULL) { for(size_t i = 0; i < m_csk->depth; i++) { free(m_csk->sketch[i]); } free(m_csk->sketch); } if(m_csk->sketchf != NULL) { for(size_t i = 0; i < m_csk->depth; i++) { free(m_csk->sketchf[i]); } free(m_csk->sketchf); } free(m_csk); } void csk_setsth(int new_threshold) { m_csk->s_thres = new_threshold; } void csk_update_var(uint64_t item, int16_t count) { uint32_t hash; uint32_t pos; int16_t count_; for(size_t i = 0; i < m_csk->depth; i++) { hash = calc_hash(item, m_csk->seeds[i << 1], m_csk->seeds[(i << 1) + 1]); // hash = cal_hash(item, m_csk->seeds[i << 1], m_csk->seeds[(i << 1) + 1]); pos = hash & m_csk->width_minus_one; uint32_t temp = (i + m_csk->depth) << 1; hash = calc_hash(item, m_csk->seeds[temp], m_csk->seeds[temp + 1]); // hash = calc_hash(item, m_csk->seeds[(i + m_csk->depth) << 1], m_csk->seeds[((i + m_csk->depth) << 1) + 1]); // hash = cal_hash(item, m_csk->seeds[(i + m_csk->depth) << 1], m_csk->seeds[((i + m_csk->depth) << 1) + 1]); count_ = (((hash & 0x1) == 0) ? -1 : 1) * count; if(m_csk->sketch[i][pos] >= HASH_MAX_16 && count_ > 0) { continue; } if(m_csk->sketch[i][pos] <= HASH_MIN_16 && count_ < 0) { continue; } m_csk->sketch[i][pos] = m_csk->sketch[i][pos] + count_; } } void csk_update_var_f(uint64_t item, float count) { uint32_t hash; uint32_t pos; for(size_t i = 0; i < m_csk->depth; i++) { hash = cal_hash(item, m_csk->seeds[i << 1], m_csk->seeds[(i << 1) + 1]); pos = hash & m_csk->width_minus_one; hash = cal_hash(item, m_csk->seeds[(i + m_csk->depth) << 1], m_csk->seeds[((i + m_csk->depth) << 1) + 1]); if((hash & 0x1) == 0) { m_csk->sketchf[i][pos] = m_csk->sketchf[i][pos] - count; } else { m_csk->sketchf[i][pos] = m_csk->sketchf[i][pos] + count; } } } /***** Test function *****/ void csk_update_var_row(uint64_t item, int16_t count, size_t row) { uint32_t hash; hash = cal_hash(item, m_csk->seeds[row << 1], m_csk->seeds[(row << 1) + 1]); uint32_t pos = hash & m_csk->width_minus_one; hash = cal_hash(item, m_csk->seeds[(row + m_csk->depth) << 1], m_csk->seeds[((row + m_csk->depth) << 1) + 1]); int16_t count_ = (((hash & 0x1) == 0) ? -1 : 1) * count; if(m_csk->sketch[row][pos] >= HASH_MAX_16 && count_ > 0) { return; } if(m_csk->sketch[row][pos] <= HASH_MIN_16 && count_ < 0) { return; } m_csk->sketch[row][pos] = m_csk->sketch[row][pos] + count_; } void csk_update_var_row_f(uint64_t item, float count, size_t row) { uint32_t hash; hash = cal_hash(item, m_csk->seeds[row << 1], m_csk->seeds[(row << 1) + 1]); uint32_t pos = hash & m_csk->width_minus_one; hash = cal_hash(item, m_csk->seeds[(row + m_csk->depth) << 1], m_csk->seeds[((row + m_csk->depth) << 1) + 1]); if((hash & 0x1) == 0) { m_csk->sketchf[row][pos] = m_csk->sketchf[row][pos] - count; } else { m_csk->sketchf[row][pos] = m_csk->sketchf[row][pos] + count; } } /***** END: Test function *****/ int16_t csk_query_median_odd(uint64_t item) { int16_t* values; int16_t median; uint32_t hash; uint32_t pos; int32_t sign; values = (int16_t*) malloc(m_csk->depth * sizeof(int16_t)); for(size_t i = 0; i < m_csk->depth; i++) { hash = cal_hash(item, m_csk->seeds[i << 1], m_csk->seeds[(i << 1) + 1]); pos = hash & m_csk->width_minus_one; hash = cal_hash(item, m_csk->seeds[(i + m_csk->depth) << 1], m_csk->seeds[((i + m_csk->depth) << 1) + 1]); sign = ((hash & 0x1) == 0) ? -1 : 1; values[i] = m_csk->sketch[i][pos] * sign; } // Sort values qsort(values, m_csk->depth, sizeof(int16_t), cmpfunc_int16); // Get median of values median = values[m_csk->depth / 2]; // Free memory free(values); return median; } int16_t csk_query_median_even(uint64_t item) { int16_t* values; int16_t median; uint32_t hash; uint32_t pos; int32_t sign; values = (int16_t*) malloc(m_csk->depth * sizeof(int16_t)); for(size_t i = 0; i < m_csk->depth; i++) { hash = cal_hash(item, m_csk->seeds[i << 1], m_csk->seeds[(i << 1) + 1]); pos = hash & m_csk->width_minus_one; hash = cal_hash(item, m_csk->seeds[(i + m_csk->depth) << 1], m_csk->seeds[((i + m_csk->depth) << 1) + 1]); sign = ((hash & 0x1) == 0) ? -1 : 1; values[i] = m_csk->sketch[i][pos] * sign; } // Sort values qsort(values, m_csk->depth, sizeof(int16_t), cmpfunc_int16); // Get median of values if(values[m_csk->depth / 2] < -(m_csk->s_thres)) { median = values[m_csk->depth / 2 - 1]; } else if(values[m_csk->depth / 2 - 1] > m_csk->s_thres) { median = values[m_csk->depth / 2]; } else { median = (values[m_csk->depth / 2 - 1] + values[m_csk->depth / 2]) / 2; } // Free memory free(values); return median; } float csk_query_median_odd_f(uint64_t item) { float* values; float median; uint32_t hash; uint32_t pos; //int sign; values = (float*) malloc(m_csk->depth * sizeof(float)); for(size_t i = 0; i < m_csk->depth; i++) { hash = cal_hash(item, m_csk->seeds[i << 1], m_csk->seeds[(i << 1) + 1]); pos = hash & m_csk->width_minus_one; hash = cal_hash(item, m_csk->seeds[(i + m_csk->depth) << 1], m_csk->seeds[((i + m_csk->depth) << 1) + 1]); //sign = ((hash & 0x1) == 0) ? -1 : 1; if((hash & 0x1) == 0) { values[i] = -m_csk->sketchf[i][pos]; } else { values[i] = m_csk->sketchf[i][pos]; } //values[i] = m_csk->sketchf[i][pos] * sign; } // Sort values qsort(values, m_csk->depth, sizeof(float), cmpfunc_float); // Get median of values median = values[m_csk->depth / 2]; // Free memory free(values); return median; } float csk_query_median_even_f(uint64_t item) { float* values; float median; uint32_t hash; uint32_t pos; //int sign; values = (float*) malloc(m_csk->depth * sizeof(float)); for(size_t i = 0; i < m_csk->depth; i++) { hash = cal_hash(item, m_csk->seeds[i << 1], m_csk->seeds[(i << 1) + 1]); pos = hash & m_csk->width_minus_one; hash = cal_hash(item, m_csk->seeds[(i + m_csk->depth) << 1], m_csk->seeds[((i + m_csk->depth) << 1) + 1]); //sign = ((hash & 0x1) == 0) ? -1 : 1; //values[i] = m_csk->sketch32[i][pos] * sign; if((hash & 0x1) == 0) { values[i] = -m_csk->sketchf[i][pos]; } else { values[i] = m_csk->sketchf[i][pos]; } } // Sort values qsort(values, m_csk->depth, sizeof(float), cmpfunc_float); // Get median of values if(values[m_csk->depth / 2] + m_csk->s_thres < 0.0) { median = values[m_csk->depth / 2 - 1]; } else if(values[m_csk->depth / 2 - 1] - m_csk->s_thres > 0.0) { median = values[m_csk->depth / 2]; } else { median = (values[m_csk->depth / 2 - 1] + values[m_csk->depth / 2]) / 2; } // Free memory free(values); return median; }
22.942623
111
0.605097
ndokmai
c65445b0564c02430e6e98c76662a90bc47cb8c0
654
hpp
C++
framework/include/GeometryNode.hpp
GottaGoGitHub/CGLab_Almert119915_Portwich119649
027babb2018ee1ae1eb03d37ceb5777db708941c
[ "MIT" ]
null
null
null
framework/include/GeometryNode.hpp
GottaGoGitHub/CGLab_Almert119915_Portwich119649
027babb2018ee1ae1eb03d37ceb5777db708941c
[ "MIT" ]
null
null
null
framework/include/GeometryNode.hpp
GottaGoGitHub/CGLab_Almert119915_Portwich119649
027babb2018ee1ae1eb03d37ceb5777db708941c
[ "MIT" ]
null
null
null
#ifndef OPENGL_FRAMEWORK_GEOMETRYNODE_H #define OPENGL_FRAMEWORK_GEOMETRYNODE_H # include "Node.hpp" #include "model.hpp" #include "structs.hpp" class GeometryNode : public Node { public: // constructor explicit GeometryNode(std::string name); GeometryNode(const std::shared_ptr<Node> &parent, std::string name); GeometryNode(const std::shared_ptr<Node> &parent, std::string name, model geometry); // destructor ~GeometryNode(); // Getter und Setter model getGeometry() const; void setGeometry(model const &geometry); private: // Member model geometry_; }; #endif //OPENGL_FRAMEWORK_GEOMETRYNODE_H
19.235294
88
0.718654
GottaGoGitHub
c656b522b117929a0f5323359307667d0728e617
2,857
cpp
C++
Super Synthesis Engine/Source/Graphics/Texture2D.cpp
nstearns96/Super-Synthesis-Engine
64824c50557e64decc9710a5b2aa63cd93712122
[ "MIT" ]
null
null
null
Super Synthesis Engine/Source/Graphics/Texture2D.cpp
nstearns96/Super-Synthesis-Engine
64824c50557e64decc9710a5b2aa63cd93712122
[ "MIT" ]
null
null
null
Super Synthesis Engine/Source/Graphics/Texture2D.cpp
nstearns96/Super-Synthesis-Engine
64824c50557e64decc9710a5b2aa63cd93712122
[ "MIT" ]
null
null
null
#include "Graphics/Texture2D.h" #include "Logging/Logger.h" #include "Resources/Assets/TextureAssetUtils.h" #include "Vulkan/Devices/VulkanDeviceManager.h" #include "Vulkan/Memory/VulkanBuffer.h" namespace SSE { extern Logger gLogger; namespace Graphics { bool Texture2D::create(Bitmap& bitmap, VkImageTiling _tiling) { bool result = false; if (bitmap.getFormat() != VK_FORMAT_B8G8R8A8_UINT) { BitmapFormatTransitionParams params = {}; params.newFormat = VK_FORMAT_B8G8R8A8_UINT; params.channelParams[CHANNEL_GREEN].destinationChannel = CHANNEL_GREEN; params.channelParams[CHANNEL_BLUE].destinationChannel = CHANNEL_BLUE; params.channelParams[CHANNEL_ALPHA].destinationChannel = CHANNEL_ALPHA; params.channelParams[CHANNEL_ALPHA].constant = UINT_MAX; if (!bitmap.transitionFormat(params)) { GLOG_CRITICAL("Could not create texture. Failed to transition input bitmap."); return false; } } if (image.create(bitmap.getData(), bitmap.getDimensions(), VK_FORMAT_B8G8R8A8_SRGB, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT)) { if (image.transitionLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) && imageView.create(image.getImage(), VK_FORMAT_B8G8R8A8_SRGB, VK_IMAGE_ASPECT_COLOR_BIT)) { VkSamplerCreateInfo samplerInfo{}; samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; samplerInfo.magFilter = VK_FILTER_LINEAR; samplerInfo.minFilter = VK_FILTER_LINEAR; samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.anisotropyEnable = VK_TRUE; samplerInfo.maxAnisotropy = 16.0f; samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK; samplerInfo.unnormalizedCoordinates = VK_FALSE; samplerInfo.compareEnable = VK_FALSE; samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; samplerInfo.mipLodBias = 0.0f; samplerInfo.minLod = 0.0f; samplerInfo.maxLod = 0.0f; if (vkCreateSampler(LOGICAL_DEVICE_DEVICE, &samplerInfo, nullptr, &sampler) == VK_SUCCESS) { result = true; tiling = _tiling; } else { GLOG_CRITICAL("Failed to create sampler."); imageView.destroy(); image.destroy(); } } else { image.destroy(); } } return result; } void Texture2D::destroy() { image.destroy(); vkDestroyImageView(LOGICAL_DEVICE_DEVICE, imageView.getImageView(), nullptr); vkDestroySampler(LOGICAL_DEVICE_DEVICE, sampler, nullptr); } Vulkan::VulkanImageView Texture2D::getImageView() const { return imageView; } VkSampler Texture2D::getSampler() const { return sampler; } } }
29.760417
149
0.732587
nstearns96
c6588f3d9d41f0506b7ab80b6ad5cad2fff9c7f6
1,493
cpp
C++
owGameM2/M2_Part_Material.cpp
adan830/OpenWow
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
[ "Apache-2.0" ]
null
null
null
owGameM2/M2_Part_Material.cpp
adan830/OpenWow
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
[ "Apache-2.0" ]
null
null
null
owGameM2/M2_Part_Material.cpp
adan830/OpenWow
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
[ "Apache-2.0" ]
1
2020-05-11T13:32:49.000Z
2020-05-11T13:32:49.000Z
#include "stdafx.h" // General #include "M2_Part_Material.h" // M2Blend converter struct { SM2_Material::BlendModes M2Blend; uint8 EGxBLend; } M2Blend_To_EGxBlend[SM2_Material::COUNT] = { { SM2_Material::M2BLEND_OPAQUE, 0 }, { SM2_Material::M2BLEND_ALPHA_KEY, 1 }, { SM2_Material::M2BLEND_ALPHA, 2 }, { SM2_Material::M2BLEND_NO_ALPHA_ADD, 10 }, { SM2_Material::M2BLEND_ADD, 3 }, { SM2_Material::M2BLEND_MOD, 4 }, { SM2_Material::M2BLEND_MOD2X, 5 } }; CM2_Part_Material::CM2_Part_Material(const SM2_Material& _proto) { m_IsLightingDisable = _proto.flags.UNLIT; m_IsFogDisable = _proto.flags.UNFOGGED; m_IsTwoSided = _proto.flags.TWOSIDED; m_DepthTestEnabled = _proto.flags.DEPTHTEST == 0; m_DepthMaskEnabled = _proto.flags.DEPTHWRITE == 0; m_M2BlendMode = _proto.m_BlendMode; } void CM2_Part_Material::fillRenderState(RenderState* _state) const { _state->setCullMode(m_IsTwoSided ? R_CullMode::RS_CULL_NONE : R_CullMode::RS_CULL_BACK); _state->setDepthTest(m_DepthTestEnabled); _state->setDepthMask(m_DepthMaskEnabled); _Render->getRenderStorage()->SetEGxBlend(_state, M2Blend_To_EGxBlend[m_M2BlendMode].EGxBLend); } void CM2_Part_Material::Set() const { _Render->r.setCullMode(m_IsTwoSided ? R_CullMode::RS_CULL_NONE : R_CullMode::RS_CULL_BACK); _Render->r.setDepthTest(m_DepthTestEnabled); _Render->r.setDepthMask(m_DepthMaskEnabled); _Render->getRenderStorage()->SetEGxBlend(_Render->r.getState(), M2Blend_To_EGxBlend[m_M2BlendMode].EGxBLend); }
31.104167
110
0.77294
adan830
c65be78a5202ef05fe8255c9f4c4ab3489a57fea
10,253
cpp
C++
OpenCP/libimq/ssim.cpp
norishigefukushima/OpenCP
63090131ec975e834f85b04e84ec29b2893845b2
[ "BSD-3-Clause" ]
137
2015-03-27T07:11:19.000Z
2022-03-30T05:58:22.000Z
OpenCP/libimq/ssim.cpp
Pandinosaurus/OpenCP
a5234ed531c610d7944fa14d42f7320442ea34a1
[ "BSD-3-Clause" ]
2
2016-05-18T06:33:16.000Z
2016-07-11T17:39:17.000Z
OpenCP/libimq/ssim.cpp
Pandinosaurus/OpenCP
a5234ed531c610d7944fa14d42f7320442ea34a1
[ "BSD-3-Clause" ]
43
2015-02-20T15:34:25.000Z
2022-01-27T14:59:37.000Z
#include <math.h> #include "imq.h" //MS_SSIMF(float *forig_img, float *fcomp_img, _INT32 PX, _INT32 PY, bool Wang, bool SSIM, _INT32 bits_per_pixel_1, bool fast, float a, float b, float g) const float aa = 0.05f; const float bb = 0.15f; const float gg = 0.10f; //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- double ABGDoSSIM(_INT32 *orig_img, _INT32 *comp_img, _INT32 PX, _INT32 PY, _INT32 BPP, bool fast, float a, float b, float g) { _INT32 size = PX * PY; double result = 0.0; float *orig_imgb = NULL; float *comp_imgb = NULL; try { orig_imgb = new float [ size ]; comp_imgb = new float [ size ]; } catch (...) { if (orig_imgb) delete orig_imgb; if (comp_imgb) delete [] comp_imgb; return result; } switch(BPP) { case 8: { for(_INT32 i = 0; i < size; ++i) { orig_imgb[i] = (float)(orig_img[i]&_MBYTE); comp_imgb[i] = (float)(comp_img[i]&_MBYTE); } result = MS_SSIMF(orig_imgb,comp_imgb,PX,PY,false,true,8,fast,a,b,g); }; break; case 16: { for(_INT32 i = 0; i < size; ++i) { orig_imgb[i] = (float)(orig_img[i]&_MINT16); comp_imgb[i] = (float)(comp_img[i]&_MINT16); } result = MS_SSIMF(orig_imgb,comp_imgb,PX,PY,false,true,16,fast,a,b,g); }; break; default: break; } delete [] orig_imgb; delete [] comp_imgb; return result; } //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- double ABGSSIM8bit(_BYTE *orig_img, _BYTE *comp_img, _INT32 PX, _INT32 PY, bool fast, float a, float b, float g) { _INT32 size = PX * PY; double result = 0.0; float *orig_imgb = NULL; float *comp_imgb = NULL; try { orig_imgb = new float [ size ]; comp_imgb = new float [ size ]; } catch (...) { if (orig_imgb) delete orig_imgb; if (comp_imgb) delete [] comp_imgb; return result; } for(_INT32 i = 0; i < size; ++i) { orig_imgb[i] = (float)(orig_img[i]&_MBYTE); comp_imgb[i] = (float)(comp_img[i]&_MBYTE); } result = MS_SSIMF(orig_imgb,comp_imgb,PX,PY,false,true,8,fast,a,b,g); delete [] orig_imgb; delete [] comp_imgb; return result; } //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- double ABGSSIM16bit(_UINT16 *orig_img, _UINT16 *comp_img, _INT32 PX, _INT32 PY, bool fast, float a, float b, float g) { _INT32 size = PX * PY; double result = 0.0; float *orig_imgb = NULL; float *comp_imgb = NULL; try { orig_imgb = new float [ size ]; comp_imgb = new float [ size ]; } catch (...) { if (orig_imgb) delete orig_imgb; if (comp_imgb) delete [] comp_imgb; return result; } for(_INT32 i = 0; i < size; ++i) { orig_imgb[i] = (float)(orig_img[i]&_MINT16); comp_imgb[i] = (float)(comp_img[i]&_MINT16); } result = MS_SSIMF(orig_imgb,comp_imgb,PX,PY,false,true,16,fast,a,b,g); delete [] orig_imgb; delete [] comp_imgb; return result; } //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- double ABGDoSSIMY(_INT32 *orig_img, _INT32 *comp_img, _INT32 PX, _INT32 PY, _INT32 BPP, bool fast, float a, float b, float g) { _INT32 size = PX * PY; double result = 0.0; switch (BPP) { case 8: case 16: result = ABGDoSSIM(orig_img, comp_img, PX,PY,BPP, fast,a,b,g); break; case 24: { float *orig_imgb = NULL; float *comp_imgb = NULL; try { orig_imgb = new float [ size ]; comp_imgb = new float [ size ]; } catch (...) { if (orig_imgb) delete orig_imgb; if (comp_imgb) delete [] comp_imgb; return result; } for(_INT32 i=0; i < size; ++i) { double Y1 = rgB * (double)((orig_img[i]>>16)&_MBYTE) + rGb * (double)((orig_img[i]>>8)&_MBYTE) + Rgb * (double)(orig_img[i]&_MBYTE) + Crgb; double Y2 = rgB * (double)((comp_img[i]>>16)&_MBYTE) + rGb * (double)((comp_img[i]>>8)&_MBYTE) + Rgb * (double)(comp_img[i]&_MBYTE) + Crgb; comp_imgb[i] = (float)Y2; orig_imgb[i] = (float)Y1; } result = MS_SSIMF(orig_imgb,comp_imgb,PX,PY,false,true,8,fast,a,b,g); delete [] orig_imgb; delete [] comp_imgb; }; break; default: break; } return result; } //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- double ABGDoSSIMY(_BYTE *orig_img, _BYTE *comp_img, _INT32 PX, _INT32 PY, _INT32 BPP, bool fast, float a, float b, float g) { _INT32 size = PX * PY; _INT32 bsize = size * 3; double result = 0.0; switch (BPP) { case 24: { float *orig_imgb = NULL; float *comp_imgb = NULL; try { orig_imgb = new float [ size ]; comp_imgb = new float [ size ]; } catch (...) { if (orig_imgb) delete orig_imgb; if (comp_imgb) delete [] comp_imgb; return result; } for(_INT32 i=0,j=0; i < bsize; i+=3,++j) { if ((i < bsize) && (i + 1 < bsize) && (i + 2 < bsize) && (j < size)) { double Y1 = rgB * (double)(orig_img[i]) + rGb * (double)(orig_img[i+1]) + Rgb * (double)(orig_img[i+2]) + Crgb; double Y2 = rgB * (double)(comp_img[i]) + rGb * (double)(comp_img[i+1]) + Rgb * (double)(comp_img[i+2]) + Crgb; comp_imgb[j] = (float)Y2; orig_imgb[j] = (float)Y1; } } result = MS_SSIMF(orig_imgb,comp_imgb,PX,PY,false,true,8,fast,a,b,g); delete [] orig_imgb; delete [] comp_imgb; }; break; default: break; } return result; } //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- double DoSSIMY(_BYTE *orig_img, _BYTE *comp_img, _INT32 PX, _INT32 PY, _INT32 BPP, bool fast) { return ABGDoSSIMY(orig_img,comp_img,PX,PY,BPP,fast,1.0f,1.0f,1.0f); } double DoSSIMY(_INT32 *orig_img, _INT32 *comp_img, _INT32 PX, _INT32 PY, _INT32 BPP, bool fast) { return ABGDoSSIMY(orig_img,comp_img,PX,PY,BPP,fast,1.0f,1.0f,1.0f); } double DoSSIM(_INT32 *orig_img, _INT32 *comp_img, _INT32 PX, _INT32 PY, _INT32 BPP, bool fast) { return ABGDoSSIM(orig_img,comp_img,PX,PY,BPP,fast, 1.0f, 1.0f, 1.0f); } double SSIM16bit(_UINT16 *orig_img, _UINT16 *comp_img, _INT32 PX, _INT32 PY, bool fast) { return ABGSSIM16bit(orig_img,comp_img,PX,PY,fast,1.0f,1.0f,1.0f); } double SSIM8bit(_BYTE *orig_img, _BYTE *comp_img, _INT32 PX, _INT32 PY, bool fast) { return ABGSSIM8bit(orig_img, comp_img, PX, PY,fast,1.0f,1.0f,1.0f); } //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- double mDoSSIMY(_BYTE *orig_img, _BYTE *comp_img, _INT32 PX, _INT32 PY, _INT32 BPP, bool fast) { return ABGDoSSIMY(orig_img,comp_img,PX,PY,BPP,fast,aa,bb,gg); } double mDoSSIMY(_INT32 *orig_img, _INT32 *comp_img, _INT32 PX, _INT32 PY, _INT32 BPP, bool fast) { return ABGDoSSIMY(orig_img,comp_img,PX,PY,BPP,fast,aa,bb,gg); } double mDoSSIM(_INT32 *orig_img, _INT32 *comp_img, _INT32 PX, _INT32 PY, _INT32 BPP, bool fast) { return ABGDoSSIM(orig_img,comp_img,PX,PY,BPP,fast,aa,bb,gg); } double mSSIM16bit(_UINT16 *orig_img, _UINT16 *comp_img, _INT32 PX, _INT32 PY, bool fast) { return ABGSSIM16bit(orig_img,comp_img,PX,PY,fast,aa,bb,gg); } double mSSIM8bit(_BYTE *orig_img, _BYTE *comp_img, _INT32 PX, _INT32 PY, bool fast) { return ABGSSIM8bit(orig_img, comp_img, PX, PY,fast,aa,bb,gg); } //---------------------------------------------------------------------------------------------------------------------------------------------- double __DoSSIM(_INT32 *orig_img,_INT32 *comp_img,_INT32 PX,_INT32 PY,_INT32 BPP, float a,float b,float g, bool fast) { return ABGDoSSIMY(orig_img,comp_img,PX,PY,BPP,fast,a,b,g); } //---------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------------------------------------
35.975439
153
0.424071
norishigefukushima
c65c030429c89ebdddaa12559bd3bf44cc74607a
10,761
cpp
C++
src/utils/vrad/disp_vrad.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/utils/vrad/disp_vrad.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/utils/vrad/disp_vrad.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "disp_vrad.h" #include "utllinkedlist.h" #include "utlvector.h" #include "iscratchpad3d.h" #include "scratchpadutils.h" //#define USE_SCRATCHPAD #if defined( USE_SCRATCHPAD ) static IScratchPad3D *g_pPad = 0; #endif int FindNeighborCornerVert(CCoreDispInfo *pDisp, const Vector &vTest) { CDispUtilsHelper *pDispHelper = pDisp; int iClosest = 0; float flClosest = 1e24; for (int iCorner = 0; iCorner < 4; iCorner++) { // Has it been touched? CVertIndex cornerVert = pDispHelper->GetPowerInfo()->GetCornerPointIndex(iCorner); int iCornerVert = pDispHelper->VertIndexToInt(cornerVert); const Vector &vCornerVert = pDisp->GetVert(iCornerVert); float flDist = vCornerVert.DistTo(vTest); if (flDist < flClosest) { iClosest = iCorner; flClosest = flDist; } } if (flClosest <= 0.1f) return iClosest; else return -1; } int GetAllNeighbors(const CCoreDispInfo *pDisp, int (&iNeighbors)[512]) { int nNeighbors = 0; // Check corner neighbors. for (int iCorner = 0; iCorner < 4; iCorner++) { const CDispCornerNeighbors *pCorner = pDisp->GetCornerNeighbors(iCorner); for (int i = 0; i < pCorner->m_nNeighbors; i++) { if (nNeighbors < ARRAYSIZE(iNeighbors)) iNeighbors[nNeighbors++] = pCorner->m_Neighbors[i]; } } for (int iEdge = 0; iEdge < 4; iEdge++) { const CDispNeighbor *pEdge = pDisp->GetEdgeNeighbor(iEdge); for (int i = 0; i < 2; i++) { if (pEdge->m_SubNeighbors[i].IsValid()) if (nNeighbors < 512) iNeighbors[nNeighbors++] = pEdge->m_SubNeighbors[i].GetNeighborIndex(); } } return nNeighbors; } void BlendCorners(CCoreDispInfo **ppListBase, int listSize) { CUtlVector<int> nbCornerVerts; for (int iDisp = 0; iDisp < listSize; iDisp++) { CCoreDispInfo *pDisp = ppListBase[iDisp]; int iNeighbors[512]; int nNeighbors = GetAllNeighbors(pDisp, iNeighbors); // Make sure we have room for all the neighbors. nbCornerVerts.RemoveAll(); nbCornerVerts.EnsureCapacity(nNeighbors); nbCornerVerts.AddMultipleToTail(nNeighbors); // For each corner. for (int iCorner = 0; iCorner < 4; iCorner++) { // Has it been touched? CVertIndex cornerVert = pDisp->GetCornerPointIndex(iCorner); int iCornerVert = pDisp->VertIndexToInt(cornerVert); const Vector &vCornerVert = pDisp->GetVert(iCornerVert); // For each displacement sharing this corner.. Vector vAverage = pDisp->GetNormal(iCornerVert); for (int iNeighbor = 0; iNeighbor < nNeighbors; iNeighbor++) { int iNBListIndex = iNeighbors[iNeighbor]; CCoreDispInfo *pNeighbor = ppListBase[iNBListIndex]; // Find out which vert it is on the neighbor. int iNBCorner = FindNeighborCornerVert(pNeighbor, vCornerVert); if (iNBCorner == -1) { nbCornerVerts[iNeighbor] = -1; // remove this neighbor from the list. } else { CVertIndex viNBCornerVert = pNeighbor->GetCornerPointIndex(iNBCorner); int iNBVert = pNeighbor->VertIndexToInt(viNBCornerVert); nbCornerVerts[iNeighbor] = iNBVert; vAverage += pNeighbor->GetNormal(iNBVert); } } // Blend all the neighbor normals with this one. VectorNormalize(vAverage); pDisp->SetNormal(iCornerVert, vAverage); #if defined( USE_SCRATCHPAD ) ScratchPad_DrawArrowSimple( g_pPad, pDisp->GetVert( iCornerVert ), pDisp->GetNormal( iCornerVert ), Vector( 0, 0, 1 ), 25 ); #endif for (int iNeighbor = 0; iNeighbor < nNeighbors; iNeighbor++) { int iNBListIndex = iNeighbors[iNeighbor]; if (nbCornerVerts[iNeighbor] == -1) continue; CCoreDispInfo *pNeighbor = ppListBase[iNBListIndex]; pNeighbor->SetNormal(nbCornerVerts[iNeighbor], vAverage); } } } } void BlendTJuncs(CCoreDispInfo **ppListBase, int listSize) { for (int iDisp = 0; iDisp < listSize; iDisp++) { CCoreDispInfo *pDisp = ppListBase[iDisp]; for (int iEdge = 0; iEdge < 4; iEdge++) { CDispNeighbor *pEdge = pDisp->GetEdgeNeighbor(iEdge); CVertIndex viMidPoint = pDisp->GetEdgeMidPoint(iEdge); int iMidPoint = pDisp->VertIndexToInt(viMidPoint); if (pEdge->m_SubNeighbors[0].IsValid() && pEdge->m_SubNeighbors[1].IsValid()) { const Vector &vMidPoint = pDisp->GetVert(iMidPoint); CCoreDispInfo *pNeighbor1 = ppListBase[pEdge->m_SubNeighbors[0].GetNeighborIndex()]; CCoreDispInfo *pNeighbor2 = ppListBase[pEdge->m_SubNeighbors[1].GetNeighborIndex()]; int iNBCorners[2]; iNBCorners[0] = FindNeighborCornerVert(pNeighbor1, vMidPoint); iNBCorners[1] = FindNeighborCornerVert(pNeighbor2, vMidPoint); if (iNBCorners[0] != -1 && iNBCorners[1] != -1) { CVertIndex viNBCorners[2] = { pNeighbor1->GetCornerPointIndex(iNBCorners[0]), pNeighbor2->GetCornerPointIndex(iNBCorners[1]) }; Vector vAverage = pDisp->GetNormal(iMidPoint); vAverage += pNeighbor1->GetNormal(viNBCorners[0]); vAverage += pNeighbor2->GetNormal(viNBCorners[1]); VectorNormalize(vAverage); pDisp->SetNormal(iMidPoint, vAverage); pNeighbor1->SetNormal(viNBCorners[0], vAverage); pNeighbor2->SetNormal(viNBCorners[1], vAverage); #if defined( USE_SCRATCHPAD ) ScratchPad_DrawArrowSimple( g_pPad, pDisp->GetVert( iMidPoint ), pDisp->GetNormal( iMidPoint ), Vector( 0, 1, 1 ), 25 ); #endif } } } } } void BlendEdges(CCoreDispInfo **ppListBase, int listSize) { for (int iDisp = 0; iDisp < listSize; iDisp++) { CCoreDispInfo *pDisp = ppListBase[iDisp]; for (int iEdge = 0; iEdge < 4; iEdge++) { CDispNeighbor *pEdge = pDisp->GetEdgeNeighbor(iEdge); for (int iSub = 0; iSub < 2; iSub++) { CDispSubNeighbor *pSub = &pEdge->m_SubNeighbors[iSub]; if (!pSub->IsValid()) continue; CCoreDispInfo *pNeighbor = ppListBase[pSub->GetNeighborIndex()]; int iEdgeDim = g_EdgeDims[iEdge]; CDispSubEdgeIterator it; it.Start(pDisp, iEdge, iSub, true); // Get setup on the first corner vert. it.Next(); CVertIndex viPrevPos = it.GetVertIndex(); while (it.Next()) { // Blend the two. if (!it.IsLastVert()) { Vector vAverage = pDisp->GetNormal(it.GetVertIndex()) + pNeighbor->GetNormal(it.GetNBVertIndex()); VectorNormalize(vAverage); pDisp->SetNormal(it.GetVertIndex(), vAverage); pNeighbor->SetNormal(it.GetNBVertIndex(), vAverage); #if defined( USE_SCRATCHPAD ) ScratchPad_DrawArrowSimple( g_pPad, pDisp->GetVert( it.GetVertIndex() ), pDisp->GetNormal( it.GetVertIndex() ), Vector( 1, 0, 0 ), 25 ); #endif } // Now blend the in-between verts (if this edge is high-res). int iPrevPos = viPrevPos[!iEdgeDim]; int iCurPos = it.GetVertIndex()[!iEdgeDim]; for (int iTween = iPrevPos + 1; iTween < iCurPos; iTween++) { float flPercent = RemapVal(iTween, iPrevPos, iCurPos, 0, 1); Vector vNormal; VectorLerp(pDisp->GetNormal(viPrevPos), pDisp->GetNormal(it.GetVertIndex()), flPercent, vNormal); VectorNormalize(vNormal); CVertIndex viTween; viTween[iEdgeDim] = it.GetVertIndex()[iEdgeDim]; viTween[!iEdgeDim] = iTween; pDisp->SetNormal(viTween, vNormal); #if defined( USE_SCRATCHPAD ) ScratchPad_DrawArrowSimple( g_pPad, pDisp->GetVert( viTween ), pDisp->GetNormal( viTween ), Vector( 1, 0.5, 0 ), 25 ); #endif } viPrevPos = it.GetVertIndex(); } } } } } #if defined( USE_SCRATCHPAD ) void ScratchPad_DrawOriginalNormals( const CCoreDispInfo *pListBase, int listSize ) { for ( int i=0; i < listSize; i++ ) { const CCoreDispInfo *pDisp = &pListBase[i]; const CPowerInfo *pPowerInfo = pDisp->GetPowerInfo(); // Draw the triangles. for ( int iTri=0; iTri < pPowerInfo->GetNumTriInfos(); iTri++ ) { const CTriInfo *pTriInfo = pPowerInfo->GetTriInfo( iTri ); for ( int iLine=0; iLine < 3; iLine++ ) { const Vector &v1 = pDisp->GetVert( pTriInfo->m_Indices[iLine] ); const Vector &v2 = pDisp->GetVert( pTriInfo->m_Indices[(iLine+1)%3] ); g_pPad->DrawLine( CSPVert( v1 ), CSPVert( v2 ) ); } } // Draw the normals. CDispCircumferenceIterator it( pPowerInfo->GetSideLength() ); while ( it.Next() ) { ScratchPad_DrawArrowSimple( g_pPad, pDisp->GetVert( it.GetVertIndex() ), pDisp->GetNormal( it.GetVertIndex() ), Vector( 0, 1, 0 ), 15 ); } } } #endif void SmoothNeighboringDispSurfNormals(CCoreDispInfo **ppListBase, int listSize) { //#if defined( USE_SCRATCHPAD ) // g_pPad = ScratchPad3D_Create(); // ScratchPad_DrawOriginalNormals( pListBase, listSize ); //#endif BlendTJuncs(ppListBase, listSize); BlendCorners(ppListBase, listSize); BlendEdges(ppListBase, listSize); }
35.166667
160
0.552086
cstom4994
c65d53273ae435ccfd3c072836fa7c16ebd5c802
19,973
hpp
C++
include/xframe/xaxis_variant.hpp
jeandet/xframe
b4fa0759cab381418a3d23f0d61f74d0d400a5c0
[ "BSD-3-Clause" ]
null
null
null
include/xframe/xaxis_variant.hpp
jeandet/xframe
b4fa0759cab381418a3d23f0d61f74d0d400a5c0
[ "BSD-3-Clause" ]
null
null
null
include/xframe/xaxis_variant.hpp
jeandet/xframe
b4fa0759cab381418a3d23f0d61f74d0d400a5c0
[ "BSD-3-Clause" ]
null
null
null
/*************************************************************************** * Copyright (c) 2017, Johan Mabille, Sylvain Corlay and Wolf Vollprecht * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XFRAME_XAXIS_VARIANT_HPP #define XFRAME_XAXIS_VARIANT_HPP #include <functional> #include "xtl/xclosure.hpp" #include "xtl/xmeta_utils.hpp" #include "xtl/xvariant.hpp" #include "xaxis.hpp" #include "xaxis_default.hpp" #include "xvector_variant.hpp" namespace xf { namespace detail { template <class V, class S, class... L> struct add_default_axis; template <class... A, class S> struct add_default_axis<xtl::variant<A...>, S> { using type = xtl::variant<A...>; }; template <class... A, class S, class L1, class... L> struct add_default_axis<xtl::variant<A...>, S, L1, L...> { using type = typename xtl::mpl::if_t<std::is_integral<L1>, add_default_axis<xtl::variant<A..., xaxis_default<L1, S>>, S, L...>, add_default_axis<xtl::variant<A...>, S, L...>>::type; }; template <class V, class S, class... L> using add_default_axis_t = typename add_default_axis<V, S, L...>::type; template <class V> struct get_axis_variant_iterator; template <class... A> struct get_axis_variant_iterator<xtl::variant<A...>> { using type = xtl::variant<typename A::const_iterator...>; }; template <class V> using get_axis_variant_iterator_t = typename get_axis_variant_iterator<V>::type; template <class S, class MT, class TL> struct xaxis_variant_traits; template <class S, class MT, template <class...> class TL, class... L> struct xaxis_variant_traits<S, MT, TL<L...>> { using tmp_storage_type = xtl::variant<xaxis<L, S, MT>...>; using storage_type = add_default_axis_t<tmp_storage_type, S, L...>; using label_list = xvector_variant_cref<L...>; using key_type = xtl::variant<typename xaxis<L, S, MT>::key_type...>; using key_reference = xtl::variant<xtl::xclosure_wrapper<const typename xaxis<L, S, MT>::key_type&>...>; using mapped_type = S; using value_type = std::pair<key_type, mapped_type>; using reference = std::pair<key_reference, mapped_type&>; using const_reference = std::pair<key_reference, const mapped_type&>; using pointer = xtl::xclosure_pointer<reference>; using const_pointer = xtl::xclosure_pointer<const_reference>; using size_type = typename label_list::size_type; using difference_type = typename label_list::difference_type; using subiterator = get_axis_variant_iterator_t<storage_type>; }; } template <class L, class T, class MT> class xaxis_variant_iterator; /***************** * xaxis_variant * *****************/ template <class L, class T, class MT = hash_map_tag> class xaxis_variant { public: static_assert(std::is_integral<T>::value, "index_type must be an integral type"); using self_type = xaxis_variant<L, T, MT>; using map_container_tag = MT; using traits_type = detail::xaxis_variant_traits<T, MT, L>; using storage_type = typename traits_type::storage_type; using key_type = typename traits_type::key_type; using key_reference = typename traits_type::key_reference; using mapped_type = T; using label_list = typename traits_type::label_list; using value_type = typename traits_type::value_type; using reference = typename traits_type::reference; using const_reference = typename traits_type::const_reference; using pointer = typename traits_type::pointer; using const_pointer = typename traits_type::const_pointer; using size_type = typename traits_type::size_type; using difference_type = typename traits_type::difference_type; using iterator = xaxis_variant_iterator<L, T, MT>; using const_iterator = iterator; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using subiterator = typename traits_type::subiterator; xaxis_variant() = default; template <class LB> xaxis_variant(const xaxis<LB, T, MT>& axis); template <class LB> xaxis_variant(xaxis<LB, T, MT>&& axis); template <class LB> xaxis_variant(const xaxis_default<LB, T>& axis); template <class LB> xaxis_variant(xaxis_default<LB, T>&& axis); label_list labels() const; key_type label(size_type i) const; bool empty() const; size_type size() const; bool is_sorted() const noexcept; bool contains(const key_type& key) const; mapped_type operator[](const key_type& key) const; template <class F> self_type filter(const F& f) const; template <class F> self_type filter(const F& f, size_type size) const; const_iterator find(const key_type& key) const; const_iterator begin() const; const_iterator end() const; const_iterator cbegin() const; const_iterator cend() const; const_reverse_iterator rbegin() const; const_reverse_iterator rend() const; const_reverse_iterator crbegin() const; const_reverse_iterator crend() const; template <class... Args> bool merge(const Args&... axes); template <class... Args> bool intersect(const Args&... axes); self_type as_xaxis() const; bool operator==(const self_type& rhs) const; bool operator!=(const self_type& rhs) const; private: storage_type m_data; template <class OS, class L1, class T1, class MT1> friend OS& operator<<(OS&, const xaxis_variant<L1, T1, MT1>&); }; template <class OS, class L, class T, class MT> OS& operator<<(OS& out, const xaxis_variant<L, T, MT>& axis); /************************** * xaxis_variant_iterator * **************************/ template <class L, class T, class MT> class xaxis_variant_iterator : public xtl::xrandom_access_iterator_base<xaxis_variant_iterator<L, T, MT>, typename xaxis_variant<L, T, MT>::value_type, typename xaxis_variant<L, T, MT>::difference_type, typename xaxis_variant<L, T, MT>::const_pointer, typename xaxis_variant<L, T, MT>::const_reference> { public: using self_type = xaxis_variant_iterator<L, T, MT>; using container_type = xaxis_variant<L, T, MT>; using key_reference = typename container_type::key_reference; using value_type = typename container_type::value_type; using reference = typename container_type::const_reference; using pointer = typename container_type::const_pointer; using difference_type = typename container_type::difference_type; using iterator_category = std::random_access_iterator_tag; using subiterator = typename container_type::subiterator; xaxis_variant_iterator() = default; xaxis_variant_iterator(subiterator it); self_type& operator++(); self_type& operator--(); self_type& operator+=(difference_type n); self_type& operator-=(difference_type n); difference_type operator-(const self_type& rhs) const; reference operator*() const; pointer operator->() const; bool equal(const self_type& rhs) const; bool less_than(const self_type& rhs) const; private: subiterator m_it; }; template <class L, class T, class MT> typename xaxis_variant_iterator<L, T, MT>::difference_type operator-(const xaxis_variant_iterator<L, T, MT>& lhs, const xaxis_variant_iterator<L, T, MT>& rhs); template <class L, class T, class MT> bool operator==(const xaxis_variant_iterator<L, T, MT>& lhs, const xaxis_variant_iterator<L, T, MT>& rhs); template <class L, class T, class MT> bool operator<(const xaxis_variant_iterator<L, T, MT>& lhs, const xaxis_variant_iterator<L, T, MT>& rhs); /******************************** * xaxis_variant implementation * ********************************/ template <class L, class T, class MT> template <class LB> inline xaxis_variant<L, T, MT>::xaxis_variant(const xaxis<LB, T, MT>& axis) : m_data(axis) { } template <class L, class T, class MT> template <class LB> inline xaxis_variant<L, T, MT>::xaxis_variant(xaxis<LB, T, MT>&& axis) : m_data(std::move(axis)) { } template <class L, class T, class MT> template <class LB> inline xaxis_variant<L, T, MT>::xaxis_variant(const xaxis_default<LB, T>& axis) : m_data(axis) { } template <class L, class T, class MT> template <class LB> inline xaxis_variant<L, T, MT>::xaxis_variant(xaxis_default<LB, T>&& axis) : m_data(std::move(axis)) { } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::labels() const -> label_list { return xtl::visit([](auto&& arg) -> label_list { return arg.labels(); }, m_data); }; template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::label(size_type i) const -> key_type { return xtl::visit([i](auto&& arg) -> key_type { return arg.labels()[i]; }, m_data); } template <class L, class T, class MT> inline bool xaxis_variant<L, T, MT>::empty() const { return xtl::visit([](auto&& arg) { return arg.empty(); }, m_data); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::size() const -> size_type { return xtl::visit([](auto&& arg) { return arg.size(); }, m_data); } template <class L, class T, class MT> inline bool xaxis_variant<L, T, MT>::is_sorted() const noexcept { return xtl::visit([](auto&& arg) { return arg.is_sorted(); }, m_data); } template <class L, class T, class MT> inline bool xaxis_variant<L, T, MT>::contains(const key_type& key) const { auto lambda = [&key](auto&& arg) -> bool { using type = typename std::decay_t<decltype(arg)>::key_type; return arg.contains(xtl::get<type>(key)); }; return xtl::visit(lambda, m_data); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::operator[](const key_type& key) const -> mapped_type { auto lambda = [&key](auto&& arg) -> mapped_type { using type = typename std::decay_t<decltype(arg)>::key_type; return arg[xtl::get<type>(key)]; }; return xtl::visit(lambda, m_data); } template <class L, class T, class MT> template <class F> inline auto xaxis_variant<L, T, MT>::filter(const F& f) const -> self_type { return xtl::visit([&f](const auto& arg) { return self_type(arg.filter(f)); }, m_data); } template <class L, class T, class MT> template <class F> inline auto xaxis_variant<L, T, MT>::filter(const F& f, size_type size) const -> self_type { return xtl::visit([&f, size](const auto& arg) { return self_type(arg.filter(f, size)); }, m_data); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::find(const key_type& key) const -> const_iterator { auto lambda = [&key](auto&& arg) -> const_iterator { using type = typename std::decay_t<decltype(arg)>::key_type; return subiterator(arg.find(xtl::get<type>(key))); }; return xtl::visit(lambda, m_data); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::begin() const -> const_iterator { return cbegin(); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::end() const -> const_iterator { return cend(); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::cbegin() const -> const_iterator { return xtl::visit([](auto&& arg) { return subiterator(arg.cbegin()); }, m_data); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::cend() const -> const_iterator { return xtl::visit([](auto&& arg) { return subiterator(arg.cend()); }, m_data); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::rbegin() const -> const_reverse_iterator { return crbegin(); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::rend() const -> const_reverse_iterator { return crend(); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::crbegin() const -> const_reverse_iterator { return xtl::visit([](auto&& arg) { return subiterator(arg.cend()); }, m_data); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::crend() const -> const_reverse_iterator { return xtl::visit([](auto&& arg) { return subiterator(arg.cbegin()); }, m_data); } template <class L, class T, class MT, class K> struct xaxis_variant_adaptor { using axis_variant_type = xaxis_variant<L, T, MT>; using key_type = K; using axis_type = xaxis<K, T, MT>; using label_list = typename axis_type::label_list; xaxis_variant_adaptor(const axis_variant_type& axis) : m_axis(axis) { }; inline const label_list& labels() const { return xget_vector<key_type>(m_axis.labels()); }; inline bool is_sorted() const noexcept { return m_axis.is_sorted(); }; private: const axis_variant_type& m_axis; }; template <class L, class T, class MT> template <class... Args> inline bool xaxis_variant<L, T, MT>::merge(const Args&... axes) { auto lambda = [&axes...](auto&& arg) -> bool { using key_type = typename std::decay_t<decltype(arg)>::key_type; return arg.merge(xaxis_variant_adaptor<L, T, MT, key_type>(axes)...); }; return xtl::visit(lambda, m_data); } template <class L, class T, class MT> template <class... Args> inline bool xaxis_variant<L, T, MT>::intersect(const Args&... axes) { auto lambda = [&axes...](auto&& arg) -> bool { using key_type = typename std::decay_t<decltype(arg)>::key_type; return arg.intersect(xaxis_variant_adaptor<L, T, MT, key_type>(axes)...); }; return xtl::visit(lambda, m_data); } template <class L, class T, class MT> inline auto xaxis_variant<L, T, MT>::as_xaxis() const -> self_type { return xtl::visit([](auto&& arg) { return self_type(xaxis<typename std::decay_t<decltype(arg)>::key_type, T, MT>(arg)); }, m_data); } template <class L, class T, class MT> inline bool xaxis_variant<L, T, MT>::operator==(const self_type& rhs) const { return m_data == rhs.m_data; } template <class L, class T, class MT> inline bool xaxis_variant<L, T, MT>::operator!=(const self_type& rhs) const { return m_data != rhs.m_data; } template <class OS, class L, class T, class MT> inline OS& operator<<(OS& out, const xaxis_variant<L, T, MT>& axis) { xtl::visit([&out](auto&& arg) { out << arg; }, axis.m_data); return out; } /***************************************** * xaxis_variant_iterator implementation * *****************************************/ template<class L, class T, class MT> inline xaxis_variant_iterator<L, T, MT>::xaxis_variant_iterator(subiterator it) : m_it(it) { } template <class L, class T, class MT> inline auto xaxis_variant_iterator<L, T, MT>::operator++() -> self_type& { xtl::visit([](auto&& arg) { ++arg; }, m_it); return *this; } template <class L, class T, class MT> inline auto xaxis_variant_iterator<L, T, MT>::operator--() -> self_type& { xtl::visit([](auto&& arg) { --arg; }, m_it); return *this; } template <class L, class T, class MT> inline auto xaxis_variant_iterator<L, T, MT>::operator+=(difference_type n) -> self_type& { xtl::visit([n](auto&& arg) { arg += n; }, m_it); return *this; } template <class L, class T, class MT> inline auto xaxis_variant_iterator<L, T, MT>::operator-=(difference_type n) -> self_type& { xtl::visit([n](auto&& arg) { arg -= n; }, m_it); return *this; } template <class L, class T, class MT> inline auto xaxis_variant_iterator<L, T, MT>::operator-(const self_type& rhs) const -> difference_type { xtl::visit([&rhs](auto&& arg) { return arg - std::get<std::decay_t<decltype(arg)>>(rhs); }, m_it); return *this; } template <class L, class T, class MT> inline auto xaxis_variant_iterator<L, T, MT>::operator*() const -> reference { return xtl::visit([](auto&& arg) { return reference(key_reference(xtl::closure(arg->first)), arg->second); }, m_it); } template <class T> struct DEBUG; template <class L, class T, class MT> inline auto xaxis_variant_iterator<L, T, MT>::operator->() const -> pointer { return xtl::visit([](auto&& arg) { return pointer(reference(key_reference(xtl::closure(arg->first)), arg->second)); }, m_it); } template <class L, class T, class MT> inline bool xaxis_variant_iterator<L, T, MT>::equal(const self_type& rhs) const { return m_it == rhs.m_it; } template <class L, class T, class MT> inline bool xaxis_variant_iterator<L, T, MT>::less_than(const self_type& rhs) const { return m_it < rhs.m_it; } template <class L, class T, class MT> inline auto operator-(const xaxis_variant_iterator<L, T, MT>& lhs, const xaxis_variant_iterator<L, T, MT>& rhs) -> typename xaxis_variant_iterator<L, T, MT>::difference_type { return lhs.operator-(rhs); } template <class L, class T, class MT> inline bool operator==(const xaxis_variant_iterator<L, T, MT>& lhs, const xaxis_variant_iterator<L, T, MT>& rhs) { return lhs.equal(rhs); } template <class L, class T, class MT> inline bool operator<(const xaxis_variant_iterator<L, T, MT>& lhs, const xaxis_variant_iterator<L, T, MT>& rhs) { return lhs.less_than(rhs); } template <class LB, class L, class T, class MT> auto get_labels(const xaxis_variant<L, T, MT>& axis_variant) -> const typename xaxis<LB, T, MT>::label_list& { using label_list = typename xaxis<LB, T, MT>::label_list; return xtl::xget<const label_list&>(axis_variant.labels().storage()); } } #endif
34.856894
139
0.588945
jeandet
c663069e51486f921da516fb37120d1ba02b2955
3,289
cpp
C++
src/controller.cpp
hrandib/pc_fancontrol
74fd5e38a7910144bfcf5fe690ad4b22c7356c91
[ "MIT" ]
null
null
null
src/controller.cpp
hrandib/pc_fancontrol
74fd5e38a7910144bfcf5fe690ad4b22c7356c91
[ "MIT" ]
4
2020-12-22T17:48:49.000Z
2021-02-20T21:48:24.000Z
src/controller.cpp
hrandib/pc_fancontrol
74fd5e38a7910144bfcf5fe690ad4b22c7356c91
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020 Dmytro Shestakov * * 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 "controller.h" std::atomic_bool Controller::breakExecution_; void Controller::handle() { while(!breakExecution_) { int temp = getHighestTemp(); samples_.add(temp); double meanValue = samples_.getMean(); double setpoint = algo_->getSetpoint(meanValue); if(temp != previousDegreeValue_ && setpoint > -1) { previousDegreeValue_ = temp; std::cout << name_ << " Peak: " << temp << " Mean: " << round(meanValue * 10) / 10 << " | " << round(setpoint * 10) / 10 << "% pwm" << std::endl; } setAllPwms(setpoint, algo_->getNormalizedTemperature(meanValue)); std::this_thread::sleep_for(ms(config_.getPollConfig().timeMsecs)); } } int32_t Controller::getHighestTemp() { auto sensors = config_.getSensors(); auto highest = std::max_element( sensors.cbegin(), sensors.cend(), [](const auto& a, const auto& b) { return a->get() < b->get(); }); return (*highest)->get(); } void Controller::setAllPwms(double value, int tempOffset) { for(auto& pwm : config_.getPwms()) { pwm->set(value, tempOffset, name_); } } Controller::Controller(const Controller::string& name, ConfigEntry& conf) : name_{name}, config_{std::move(conf)}, samples_(static_cast<size_t>(conf.getPollConfig().samplesCount)), previousDegreeValue_{} { switch(conf.getMode()) { case ConfigEntry::SETMODE_TWO_POINT: { ConfigEntry::TwoPointConfMode mode = std::get<ConfigEntry::SETMODE_TWO_POINT>(config_.getModeConfig()); algo_ = std::make_unique<AlgoTwoPoint>(mode.temp_a, mode.temp_b); } break; case ConfigEntry::SETMODE_MULTI_POINT: { ConfigEntry::MultiPointConfMode mode = std::get<ConfigEntry::SETMODE_MULTI_POINT>(config_.getModeConfig()); algo_ = std::make_unique<AlgoMultiPoint>(mode.pointVec); } break; case ConfigEntry::SETMODE_PI: { ConfigEntry::PiConfMode mode = std::get<ConfigEntry::SETMODE_PI>(config_.getModeConfig()); algo_ = std::make_unique<AlgoPI>(mode.temp, mode.kp, mode.ki, mode.max_i); } break; } }
42.166667
119
0.678322
hrandib
c6731fe6f4d0b69900a6e5b7bf5254eee44b1b09
10,697
cpp
C++
nv/g_dbscan.cpp
houwenbo87/DBSCAN
3452d32186f2b59f2f1e515cebdf0ce15cb3e2f7
[ "BSD-2-Clause-FreeBSD" ]
1
2020-09-18T22:40:39.000Z
2020-09-18T22:40:39.000Z
nv/g_dbscan.cpp
houwenbo87/DBSCAN
3452d32186f2b59f2f1e515cebdf0ce15cb3e2f7
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
nv/g_dbscan.cpp
houwenbo87/DBSCAN
3452d32186f2b59f2f1e515cebdf0ce15cb3e2f7
[ "BSD-2-Clause-FreeBSD" ]
1
2021-09-15T11:06:53.000Z
2021-09-15T11:06:53.000Z
#include "g_dbscan.h" #include <cuda.h> namespace { bool has_nonzero(std::vector<int>& v) { for (size_t i = 0; i < v.size(); ++i) { if (v[i] > 0) return true; } return false; } } namespace clustering { GDBSCAN::GDBSCAN(const Dataset::Ptr dset) : m_dset(dset) , d_data(0) , vA_size(sizeof(int) * dset->rows()) , d_Va0(0) , d_Va1(0) , h_Va0(dset->rows(), 0) , h_Va1(dset->rows(), 0) , d_Ea(0) , d_Fa(0) , d_Xa(0) , m_fit_time(.0) , m_predict_time(.0) , core(dset->rows(), false) , labels(dset->rows(), -1) { size_t alloc_size = sizeof(float) * m_dset->num_points(); cudaError_t r = cudaMalloc(reinterpret_cast<void**>(&d_data), alloc_size); if (r != cudaSuccess) { throw std::runtime_error("Cuda d_data malloc error :" + std::to_string(r)); } LOG(INFO) << "Allocated " << alloc_size << " bytes on device for " << m_dset->num_points() << " points"; r = cudaMalloc(reinterpret_cast<void**>(&d_Va0), vA_size); if (r != cudaSuccess) { throw std::runtime_error("Cuda d_Va0 malloc error :" + std::to_string(r)); } r = cudaMalloc(reinterpret_cast<void**>(&d_Va1), vA_size); if (r != cudaSuccess) { throw std::runtime_error("Cuda d_Va1 malloc error :" + std::to_string(r)); } LOG(INFO) << "Allocated " << vA_size << " bytes on device for Va0 and Va1"; r = cudaMalloc(reinterpret_cast<void**>(&d_Fa), vA_size); if (r != cudaSuccess) { throw std::runtime_error("Cuda d_Fa malloc error :" + std::to_string(r)); } LOG(INFO) << "Allocated " << vA_size << " bytes on device for d_Fa"; r = cudaMalloc(reinterpret_cast<void**>(&d_Xa), vA_size); if (r != cudaSuccess) { throw std::runtime_error("Cuda d_Xa malloc error :" + std::to_string(r)); } LOG(INFO) << "Allocated " << vA_size << " bytes on device for d_Xa"; const size_t cols = m_dset->cols(); size_t copysize = cols * sizeof(float); for (size_t i = 0; i < m_dset->rows(); ++i) { r = cudaMemcpy(d_data + i * cols, m_dset->data()[i].data(), copysize, cudaMemcpyHostToDevice); if (r != cudaSuccess) { throw std::runtime_error("Cuda memcpy error :" + std::to_string(r)); } VLOG(3) << "Copied " << i << "th row to device, size = " << copysize; } } GDBSCAN::~GDBSCAN() { if (d_data) { cudaFree(d_data); d_data = 0; } if (d_Va0) { cudaFree(d_Va0); d_Va0 = 0; } if (d_Va1) { cudaFree(d_Va1); d_Va1 = 0; } if (d_Ea) { cudaFree(d_Ea); d_Ea = 0; } if (d_Fa) { cudaFree(d_Fa); d_Fa = 0; } if (d_Xa) { cudaFree(d_Xa); d_Xa = 0; } } void GDBSCAN::Va_device_to_host() { cudaError_t r = cudaMemcpy(&h_Va0[0], d_Va0, vA_size, cudaMemcpyDeviceToHost); if (r != cudaSuccess) { throw std::runtime_error("Cuda memcpy Va0 device to host error :" + std::to_string(r)); } r = cudaMemcpy(&h_Va1[0], d_Va1, vA_size, cudaMemcpyDeviceToHost); if (r != cudaSuccess) { throw std::runtime_error("Cuda memcpy Va1 device to host error :" + std::to_string(r)); } } void GDBSCAN::fit(float eps, size_t min_elems) { const double start = omp_get_wtime(); // First Step (Vertices degree calculation): For each vertex, we calculate the // total number of adjacent vertices. However we can use the multiple cores of // the GPU to process multiple vertices in parallel. Our parallel strategy // using GPU assigns a thread to each vertex, i.e., each entry of the vector // Va. Each GPU thread will count how many adjacent vertex has under its // responsibility, filling the first value on the vector Va. As we can see, // there are no dependency (or communication) between those parallel tasks // (embarrassingly parallel problem). Thus, the computational complexity can // be reduced from O(V2) to O(V). int N = static_cast<int>(m_dset->rows()); int colsize = static_cast<int>(m_dset->cols()); LOG(INFO) << "Starting vertdegree on " << N << "x" << colsize << " " << (N + 255) / 256 << "x" << 256; vertdegree(N, colsize, eps, d_data, d_Va0); LOG(INFO) << "Executed vertdegree transfer"; // Second Step (Calculation of the adjacency lists indices): The second // value in Va is related to the start // index in Ea of the adjacency list of a particular vertex. The calculation // of this value depends on the start index of the vertex adjacency list and // the degree of the previous vertex. For example, the start index for the // vertex 0 is 0, since it is the first vertex. For the vertex 1, the start // index is the start index from the previous vertex (i.e. 0), plus its // degree, already calculated in the previous step. We realize that we have a // data dependency where the next vertex depends on the calculation of the // preceding vertices. This is a problem that can be efficiently done in // parallel using an exclusive scan operation [23]. For this operation, we // used the thrust library, distributed as part of the CUDA SDK. This library // provides, among others algorithms, an optimized exclusive scan // implementation that is suitable for our method adjlistsind(N, d_Va0, d_Va1); LOG(INFO) << "Executed adjlistsind transfer"; Va_device_to_host(); LOG(INFO) << "Finished transfer"; for (int i = 0; i < N; ++i) { if (static_cast<size_t>(h_Va0[i]) >= min_elems) { core[i] = true; } } // Third Step (Assembly of adjacency lists): Having the vector Va been // completely filled, i.e., for each // vertex, we know its degree and the start index of its adjacency list, // calculated in the two previous steps, we can now simply mount the compact // adjacency list, represented by Ea. Following the logic of the first step, // we assign a GPU thread to each vertex. Each of these threads will fill the // adjacency list of its associated vertex with all vertices adjacent to it. // The adjacency list for each vertex starts at the indices present in the // second value of Va, and has an offset related to the degree of the vertex. size_t Ea_size = static_cast<size_t>(h_Va0[h_Va0.size() - 1] + h_Va1[h_Va1.size() - 1]) * sizeof(int); LOG(INFO) << "Allocating " << Ea_size << " bytes for Ea " << h_Va0[h_Va0.size() - 1] << "+" << h_Va1[h_Va1.size() - 1]; if (d_Ea) { cudaFree(d_Ea); d_Ea = 0; } cudaError_t r = cudaMalloc(reinterpret_cast<void**>(&d_Ea), Ea_size); if (r != cudaSuccess) { throw std::runtime_error("Cuda d_Ea malloc error :" + std::to_string(r)); } asmadjlist(N, colsize, eps, d_data, d_Va1, d_Ea); m_fit_time = omp_get_wtime() - start; LOG(INFO) << "Executed asmadjlist transfer"; } void GDBSCAN::Fa_Xa_to_device(const std::vector<int>& Fa, const std::vector<int>& Xa) { cudaError_t r = cudaMemcpy(d_Fa, &Fa[0], vA_size, cudaMemcpyHostToDevice); if (r != cudaSuccess) { throw std::runtime_error("Cuda memcpy Fa host to device :" + std::to_string(r)); } r = cudaMemcpy(d_Xa, &Xa[0], vA_size, cudaMemcpyHostToDevice); if (r != cudaSuccess) { throw std::runtime_error("Cuda memcpy Xa host to device :" + std::to_string(r)); } } void GDBSCAN::Xa_to_host(std::vector<int>& Xa) { cudaError_t r = cudaMemcpy(&Xa[0], d_Xa, vA_size, cudaMemcpyDeviceToHost); if (r != cudaSuccess) { throw std::runtime_error("Cuda memcpy Xa device to host :" + std::to_string(r)); } } void GDBSCAN::Fa_to_host(std::vector<int>& Fa) { cudaError_t r = cudaMemcpy(&Fa[0], d_Fa, vA_size, cudaMemcpyDeviceToHost); if (r != cudaSuccess) { throw std::runtime_error("Cuda memcpy Fa device to host :" + std::to_string(r)); } } void GDBSCAN::breadth_first_search(int i, int32_t cluster, std::vector<bool>& visited) { int N = static_cast<int>(m_dset->rows()); std::vector<int> Xa(m_dset->rows(), 0); std::vector<int> Fa(m_dset->rows(), 0); Fa[i] = 1; Fa_Xa_to_device(Fa, Xa); while (has_nonzero(Fa)) { breadth_first_search_kern(N, d_Ea, d_Va0, d_Va1, d_Fa, d_Xa); Fa_to_host(Fa); } Xa_to_host(Xa); for (size_t j = 0; j < m_dset->rows(); ++j) { if (Xa[j]) { visited[j] = true; labels[j] = cluster; // LOG(INFO) << "Assigning " << j << " " << cluster; } } } int32_t GDBSCAN::predict() { // Clusters identification // For this step, we decided to parallelize the BFS. Our parallelization // approach in CUDA is based on the work presented in [22], which performs a // level synchronization, i.e. the BFS traverses the graph in levels. Once a // level is visited, it is not visited again. The concept of border in the BFS // corresponds to all nodes being processed at the current level. In our // implementation we assign one thread to each vertex. Two Boolean vectors, // Borders and Visiteds, namely Fa and Xa, respectively, of size V are created // to store the vertices that are on the border of BFS (vertices of the // current level) and the vertices already visited. In each iteration, each // thread (vertex) looks for its entry in the vector Fa. If its position is // marked, the vertex removes its own entry on Fa and marks its position in // the vector Xa (it is removed from the border, and it has been visited, so // we can go to the next level). It also adds its neighbours to the vector Fa // if they have not already been visited, thus beginning the search in a new // level. This process is repeated until the boundary becomes empty. We // illustrate the functioning of our BFS parallel implementation in Algorithm // 3 and 4. int32_t cluster = 0; std::vector<bool> visited(m_dset->rows(), false); const double start = omp_get_wtime(); for (size_t i = 0; i < m_dset->rows(); ++i) { if (visited[i]) continue; if (!core[i]) continue; visited[i] = true; labels[i] = cluster; breadth_first_search(static_cast<int>(i), cluster, visited); cluster += 1; } m_predict_time = omp_get_wtime() - start; return cluster; } const GDBSCAN::Labels& GDBSCAN::get_labels() { return labels; } } // namespace clustering
31.09593
81
0.618304
houwenbo87
c6735e0f7e36f1d9c9effe211678d06a91179a9f
307
cpp
C++
Lesson 06/CallByVal2.cpp
noenemy/Book-Quick-Guide-C-
51ddffb6c5e4b1f4351ba878e543b179b744388b
[ "MIT" ]
null
null
null
Lesson 06/CallByVal2.cpp
noenemy/Book-Quick-Guide-C-
51ddffb6c5e4b1f4351ba878e543b179b744388b
[ "MIT" ]
null
null
null
Lesson 06/CallByVal2.cpp
noenemy/Book-Quick-Guide-C-
51ddffb6c5e4b1f4351ba878e543b179b744388b
[ "MIT" ]
null
null
null
#include <stdio.h> void AddAndPrint( int *pnParam ); int main() { int a = 10; AddAndPrint( &a ); printf("a = %d\n", a); return 0; } void AddAndPrint( int *pnParam ) { if ( pnParam == NULL ) return; *pnParam = *pnParam + 10; printf("*pnParam = %d\n", *pnParam); }
12.28
40
0.527687
noenemy
c678dfa624154fe38517d29e1e7f5058a3da162f
5,099
cpp
C++
samples/cortex/mx-gcc/4-debug-m3-stm32f2xx/src/main.cpp
diamondx131/scmrtos-sample-projects
3b34a485b6ca4b16705c250383ae5d30c81966f1
[ "MIT" ]
9
2015-10-07T15:27:27.000Z
2021-04-07T06:13:24.000Z
samples/cortex/mx-gcc/4-debug-m3-stm32f2xx/src/main.cpp
diamondx131/scmrtos-sample-projects
3b34a485b6ca4b16705c250383ae5d30c81966f1
[ "MIT" ]
4
2017-07-04T10:51:51.000Z
2019-09-25T11:20:24.000Z
samples/cortex/mx-gcc/4-debug-m3-stm32f2xx/src/main.cpp
diamondx131/scmrtos-sample-projects
3b34a485b6ca4b16705c250383ae5d30c81966f1
[ "MIT" ]
9
2015-12-04T15:34:32.000Z
2020-07-01T16:10:59.000Z
//****************************************************************************** //* //* FULLNAME: Single-Chip Microcontroller Real-Time Operating System //* //* NICKNAME: scmRTOS //* //* PROCESSOR: ARM Cortex-M3 //* //* TOOLKIT: ARM GCC //* //* PURPOSE: Port Test File //* //* Version: v5.2.0 //* //* //* Copyright (c) 2003-2021, scmRTOS Team //* //* 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. //* //* ================================================================= //* Project sources: https://github.com/scmrtos/scmrtos //* Documentation: https://github.com/scmrtos/scmrtos/wiki/Documentation //* Wiki: https://github.com/scmrtos/scmrtos/wiki //* Sample projects: https://github.com/scmrtos/scmrtos-sample-projects //* ================================================================= //* //****************************************************************************** //* gcc port by Anton B. Gusev aka AHTOXA, Copyright (c) 2009-2021 #include "stm32f2xx.h" #include "pin.h" #include <scmRTOS.h> //--------------------------------------------------------------------------- // // Process types // typedef OS::process<OS::pr0, 300> TProc0; typedef OS::process<OS::pr1, 300> TProc1; typedef OS::process<OS::pr2, 300> TProc2; //--------------------------------------------------------------------------- // // Process objects // TProc0 Proc0; TProc1 Proc1; TProc2 Proc2; //--------------------------------------------------------------------------- // // IO Pins // typedef Pin<'E', 0> PE0; typedef Pin<'E', 1> PE1; //--------------------------------------------------------------------------- // // Event Flags to test // OS::TEventFlag event; OS::TEventFlag timer_event; int main() { // configure IO pins PE0::Direct(OUTPUT); PE0::Off(); PE1::Direct(OUTPUT); PE1::Off(); // run OS::run(); } /** * Waste some time (payload emulation). */ NOINLINE void waste_time() { for (volatile int i = 0; i < 0x3FF; i++) ; } /** * Stack angry function. * Eats approximately (12 * count) bytes from caller process stack. * Called by different processes some time after start. * Stack usage changes can be observed in debug terminal. */ NOINLINE int waste_stack(int count) { volatile int arr[2]; arr[0] = TIM2->CNT; // any volatile register arr[1] = count ? waste_stack(count - 1) : TIM2->CNT; return (arr[0] + arr[1]) / 2; } namespace OS { template <> OS_PROCESS void TProc0::exec() { for(;;) { // PE0 "ON" time = context switch time (~9.6us at 24MHz) event.wait(); PE0::Off(); // waste some time (simulate payload) waste_time(); // waste some stack (increasing with time) tick_count_t t = (OS::get_tick_count() % 40000) / 5000; waste_stack(t); } } template <> OS_PROCESS void TProc1::exec() { for(;;) { sleep(10); PE0::On(); event.signal(); // waste time (2x Proc0) waste_time(); waste_time(); } } template <> OS_PROCESS void TProc2::exec() { for (;;) { timer_event.wait(); PE1::On(); // increase load, one step at every 5 seconds after start, // resetting at 8th step. tick_count_t t = (OS::get_tick_count() % 40000) / 5000; for (uint32_t i = 0; i < t; i++) waste_time(); // PE1 led "ON" time ~ Proc2 load PE1::Off(); } } } void OS::system_timer_user_hook() { static const int reload_value = 10; // 100 Hz static int counter = reload_value; if (!--counter) { counter = reload_value; timer_event.signal_isr(); } } #if scmRTOS_IDLE_HOOK_ENABLE void OS::idle_process_user_hook() { __WFI(); } #endif
27.413978
80
0.521867
diamondx131
c6794313406de573af08d9f97f4b5f705f70a7a5
1,471
cpp
C++
oclint-rules/rules/basic/ForLoopShouldBeWhileLoopRule.cpp
BGU-AiDnD/oclint
484fed44ca0e34532745b3d4f04124cbf5bb42fa
[ "BSD-3-Clause" ]
3,128
2015-01-01T06:00:31.000Z
2022-03-29T23:43:20.000Z
oclint-rules/rules/basic/ForLoopShouldBeWhileLoopRule.cpp
BGU-AiDnD/oclint
484fed44ca0e34532745b3d4f04124cbf5bb42fa
[ "BSD-3-Clause" ]
432
2015-01-03T15:43:08.000Z
2022-03-29T02:32:48.000Z
oclint-rules/rules/basic/ForLoopShouldBeWhileLoopRule.cpp
BGU-AiDnD/oclint
484fed44ca0e34532745b3d4f04124cbf5bb42fa
[ "BSD-3-Clause" ]
454
2015-01-06T03:11:12.000Z
2022-03-22T05:49:38.000Z
#include "oclint/AbstractASTVisitorRule.h" #include "oclint/RuleSet.h" using namespace std; using namespace clang; using namespace oclint; class ForLoopShouldBeWhileLoopRule : public AbstractASTVisitorRule<ForLoopShouldBeWhileLoopRule> { public: virtual const string name() const override { return "for loop should be while loop"; } virtual int priority() const override { return 3; } virtual const string category() const override { return "basic"; } #ifdef DOCGEN virtual const std::string since() const override { return "0.6"; } virtual const std::string description() const override { return "Under certain circumstances, some ``for`` loops can be simplified to " "``while`` loops to make code more concise."; } virtual const std::string example() const override { return R"rst( .. code-block:: cpp void example(int a) { for (; a < 100;) { foo(a); } } )rst"; } #endif bool VisitForStmt(ForStmt *forStmt) { Stmt *initStmt = forStmt->getInit(); Expr *condExpr = forStmt->getCond(); Expr *incExpr = forStmt->getInc(); if (!initStmt && !incExpr && condExpr && !isa<NullStmt>(condExpr)) { addViolation(forStmt, this); } return true; } }; static RuleSet rules(new ForLoopShouldBeWhileLoopRule());
21.318841
96
0.600952
BGU-AiDnD
c681b7875e762a600648e5b7332ccc0ae0817de5
10,769
cpp
C++
Umbrella-Engine/Image/Image.cpp
jfla-fan/JFla-Engine
dcbdcdff815fd1729bed35ec556b850cc94f6553
[ "MIT" ]
null
null
null
Umbrella-Engine/Image/Image.cpp
jfla-fan/JFla-Engine
dcbdcdff815fd1729bed35ec556b850cc94f6553
[ "MIT" ]
null
null
null
Umbrella-Engine/Image/Image.cpp
jfla-fan/JFla-Engine
dcbdcdff815fd1729bed35ec556b850cc94f6553
[ "MIT" ]
null
null
null
#include "Image.h" #include <map> namespace J::Utils { using namespace J::Math; static uint8 _GetBytesPerChannel(ERawImageFormat InFormat) { switch (InFormat) { case ERawImageFormat::L8: case ERawImageFormat::LA8: case ERawImageFormat::R8: case ERawImageFormat::RGB8: case ERawImageFormat::RGBA8: return 1; case ERawImageFormat::RH: case ERawImageFormat::RG8: case ERawImageFormat::RGBH: case ERawImageFormat::RGBAH: return 2; case ERawImageFormat::RF: case ERawImageFormat::RGBF: case ERawImageFormat::RGBAF: return 4; default: throw "Cannot define bytes per channel"; break; } return 0; // should never reach this } static uint32 _GetChannelsCount(ERawImageFormat InFormat) { switch (InFormat) { case ERawImageFormat::L8: case ERawImageFormat::R8: case ERawImageFormat::RF: case ERawImageFormat::RH: return 1; case ERawImageFormat::LA8: case ERawImageFormat::RG8: return 2; case ERawImageFormat::RGB8: case ERawImageFormat::RGBF: case ERawImageFormat::RGBH: return 3; case ERawImageFormat::RGBA8: case ERawImageFormat::RGBAH: case ERawImageFormat::RGBAF: return 4; default: throw "Unknown image format"; break; } return 0; // should never reach this } static std::string _GetImageFormatString(ERawImageFormat format) { #define CASE_LABEL(format_type)\ case ERawImageFormat::format_type:\ return #format_type switch (format) { CASE_LABEL(L8); CASE_LABEL(LA8); CASE_LABEL(R8); CASE_LABEL(RG8); CASE_LABEL(RGB8); CASE_LABEL(RGBA8); CASE_LABEL(RF); CASE_LABEL(RGBF); CASE_LABEL(RGBAF); CASE_LABEL(RH); CASE_LABEL(RGBH); CASE_LABEL(RGBAH); default: return "Unknown"; } #undef CASE_LABEL } Image::Image() : SizeX(0) , SizeY(0) , ChannelsCount(0) , BytesPerChannel(0) , Format(ERawImageFormat::AUTO) , bInitialized(false) { } Image::Image(uint32 InSizeX, uint32 InSizeY, ERawImageFormat InImageFormat) : SizeX(InSizeX) , SizeY(InSizeY) , ChannelsCount(_GetChannelsCount(InImageFormat)) , BytesPerChannel(_GetBytesPerChannel(InImageFormat)) , Format(InImageFormat) , bInitialized(false) { Source.assign((SIZE_T)SizeX * SizeY * ChannelsCount * GetBytesPerPixel(), byte(0x00)); } Image::Image(VectorUInt2 InSize, ERawImageFormat InImageFormat) : Image(InSize.x, InSize.y, InImageFormat) { } Image::Image(const byte* InData, uint32 InSizeX, uint32 InSizeY, ERawImageFormat InImageFormat) : Image(InSizeX, InSizeY, InImageFormat) { Source.assign(InData, InData + Source.size()); bInitialized = true; } Image::Image(const byte* InData, VectorUInt2 InSize, ERawImageFormat InImageFormat) : Image(InData, InSize.x, InSize.y, InImageFormat) { } Image::Image(const Image& another) { this->Source = another.Source; this->SizeX = another.SizeX; this->SizeY = another.SizeY; this->ChannelsCount = another.ChannelsCount; this->BytesPerChannel = another.BytesPerChannel; this->Format = another.Format; this->bInitialized = another.bInitialized; } Image::Image(Image&& another) NOEXCEPT { this->Source = std::move(another.Source); this->SizeX = another.SizeX; this->SizeY = another.SizeY; this->ChannelsCount = another.ChannelsCount; this->BytesPerChannel = another.BytesPerChannel; this->Format = another.Format; this->bInitialized = another.bInitialized; another.SizeX = 0; another.SizeY = 0; another.ChannelsCount = 0; another.BytesPerChannel = 0; another.bInitialized = false; } Image& Image::operator = (const Image& another) { if (this == &another) { return *this; } this->Source = another.Source; this->SizeX = another.SizeX; this->SizeY = another.SizeY; this->ChannelsCount = another.ChannelsCount; this->BytesPerChannel = another.BytesPerChannel; this->Format = another.Format; this->bInitialized = another.bInitialized; return *this; } Image& Image::operator = (Image&& another) NOEXCEPT { this->Source = std::move(another.Source); this->SizeX = another.SizeX; this->SizeY = another.SizeY; this->ChannelsCount = another.ChannelsCount; this->BytesPerChannel = another.BytesPerChannel; this->Format = another.Format; this->bInitialized = another.bInitialized; another.SizeX = 0; another.SizeY = 0; another.ChannelsCount = 0; another.BytesPerChannel = 0; another.bInitialized = false; return *this; } Image::~Image() { Release(); } void Image::Release() { JVector<byte>().swap(Source); // clears and releases vector resources bInitialized = false; } void Image::SetData(byte* Data, SIZE_T Size) { Release(); Source = JVector<byte>(Data, Data + Size); } void Image::MarkInitialized(bool initialized) { this->bInitialized = initialized; } void Image::PrintImageMetaData(std::ostream& os) { os << std::format("Size - ({}, {})\n", SizeX, SizeY) << "Channel count: " << ChannelsCount << '\n' << "Bytes per channel: " << (uint32)BytesPerChannel << '\n' << _GetImageFormatString(Format) << '\n'; } bool Image::IsInitialized() const { return bInitialized; } uint32 Image::GetBytesPerPixel() const { switch (this->Format) { case ERawImageFormat::L8: case ERawImageFormat::R8: return 1; case ERawImageFormat::LA8: case ERawImageFormat::RG8: case ERawImageFormat::RH: return 2; case ERawImageFormat::RGB8: return 3; case ERawImageFormat::RGBA8: case ERawImageFormat::RF: return 4; case ERawImageFormat::RGBH: return 6; case ERawImageFormat::RGBAH: return 8; case ERawImageFormat::RGBF: return 12; case ERawImageFormat::RGBAF: return 16; default: // todo: warning or fatal assert: Unsupported file format break; } return 0; // should never reach this } VectorUInt2 Image::GetSize() const { return { SizeX, SizeY }; } uint32 Image::GetWidth() const { return SizeX; } uint32 Image::GetHeight() const { return SizeY; } SIZE_T Image::GetBytesSize() const { return Source.size(); } uint32 Image::GetChannelsCount() const { return ChannelsCount; } uint32 Image::GetBytesPerChannel() const { return BytesPerChannel; } ERawImageFormat Image::GetFormat() const { return Format; } byte* Image::RawData() { return Source.data(); } const byte* Image::RawData() const { return Source.data(); } // data accessors std::span<byte> Image::RawView() { return std::span<byte>(this->Source); } std::span<uint8> Image::AsL8() { check(this->Format == ERawImageFormat::L8); return std::span((uint8*)this->Source.data(), this->Source.size() / sizeof(uint8)); } std::span<uint8> Image::AsR8() { check(this->Format == ERawImageFormat::R8); return std::span((uint8*)this->Source.data(), this->Source.size() / sizeof(uint8)); } std::span<uint16> Image::AsLA8() { check(this->Format == ERawImageFormat::LA8); return std::span((uint16*)this->Source.data(), this->Source.size() / sizeof(uint16)); } std::span<float16> Image::AsRH() { check(this->Format == ERawImageFormat::RH); return std::span((float16*)this->Source.data(), this->Source.size() / sizeof(float16)); } std::span<uint8> Image::AsRGB8() { check(this->Format == ERawImageFormat::RGB8); return std::span((uint8*)this->Source.data(), this->Source.size() / sizeof(uint8)); } std::span<Color> Image::AsRGBA8() { check(this->Format == ERawImageFormat::RGBA8); return std::span((Color*)this->Source.data(), this->Source.size() / sizeof(Color)); } std::span<float> Image::AsRF() { check(this->Format == ERawImageFormat::RF); return std::span((float*)this->Source.data(), this->Source.size() / sizeof(float)); } std::span<float16> Image::AsRGBH() { check(this->Format == ERawImageFormat::RGBH); return std::span((float16*)this->Source.data(), this->Source.size() / sizeof(float16)); } std::span<float16> Image::AsRGBAH() { check(this->Format == ERawImageFormat::RGBAH); return std::span((float16*)this->Source.data(), this->Source.size() / sizeof(float16)); } std::span<float> Image::AsRGBF() { check(this->Format == ERawImageFormat::RGBF); return std::span((float*)this->Source.data(), this->Source.size() / sizeof(float)); } std::span<LinearColor> Image::AsRGBAF() { check(this->Format == ERawImageFormat::RGBAF); return std::span((LinearColor*)this->Source.data(), this->Source.size() / sizeof(LinearColor)); } // const data accessors std::span<const byte> Image::RawView() const { return std::span<const byte>(this->Source); } std::span<const uint8> Image::AsL8() const { check(this->Format == ERawImageFormat::L8); return std::span((const uint8*)this->Source.data(), this->Source.size() / sizeof(uint8)); } std::span<const uint8> Image::AsR8() const { check(this->Format == ERawImageFormat::R8); return std::span((const uint8*)this->Source.data(), this->Source.size() / sizeof(uint8)); } std::span<const uint16> Image::AsLA8() const { check(this->Format == ERawImageFormat::LA8); return std::span((const uint16*)this->Source.data(), this->Source.size() / sizeof(uint16)); } std::span<const float16> Image::AsRH() const { check(this->Format == ERawImageFormat::RH); return std::span((const float16*)this->Source.data(), this->Source.size() / sizeof(float16)); } std::span<const uint8> Image::AsRGB8() const { check(this->Format == ERawImageFormat::RGB8); return std::span((const uint8*)this->Source.data(), this->Source.size() / sizeof(uint8)); } std::span<const Color> Image::AsRGBA8() const { check(this->Format == ERawImageFormat::RGBA8); return std::span((const Color*)this->Source.data(), this->Source.size() / sizeof(Color)); } std::span<const float> Image::AsRF() const { check(this->Format == ERawImageFormat::RF); return std::span((const float*)this->Source.data(), this->Source.size() / sizeof(float)); } std::span<const float16> Image::AsRGBH() const { check(this->Format == ERawImageFormat::RGBH); return std::span((const float16*)this->Source.data(), this->Source.size() / sizeof(float16)); } std::span<const float16> Image::AsRGBAH() const { check(this->Format == ERawImageFormat::RGBAH); return std::span((const float16*)this->Source.data(), this->Source.size() / sizeof(float16)); } std::span<const float> Image::AsRGBF() const { check(this->Format == ERawImageFormat::RGBF); return std::span((const float*)this->Source.data(), this->Source.size() / sizeof(float)); } std::span<const LinearColor> Image::AsRGBAF() const { check(this->Format == ERawImageFormat::RGBAF); return std::span((const LinearColor*)this->Source.data(), this->Source.size() / sizeof(LinearColor)); } }
24.530752
103
0.679172
jfla-fan
c6834844a8fbe1aaac74578b70ab9dda587242ba
2,101
inl
C++
examples/volcano/command.inl
djohansson/slang
69227ad7d46b8741274c93a42a891d70458f2d45
[ "MIT" ]
2
2019-08-16T13:33:28.000Z
2020-08-12T21:48:24.000Z
examples/volcano/command.inl
djohansson/slang
69227ad7d46b8741274c93a42a891d70458f2d45
[ "MIT" ]
null
null
null
examples/volcano/command.inl
djohansson/slang
69227ad7d46b8741274c93a42a891d70458f2d45
[ "MIT" ]
null
null
null
template <GraphicsBackend B> CommandBufferAccessScope<B> CommandPoolContext<B>::commands(const CommandBufferAccessScopeDesc<B>& beginInfo) { if (myRecordingCommands[beginInfo.level] && myRecordingCommands[beginInfo.level].value().getDesc() == beginInfo) return internalCommands(beginInfo); else return internalBeginScope(beginInfo); } template <GraphicsBackend B> void CommandPoolContext<B>::internalEndCommands(CommandBufferLevel<B> level) { if (myRecordingCommands[level]) myRecordingCommands[level] = std::nullopt; } template <GraphicsBackend B> CommandBufferAccessScope<B>::CommandBufferAccessScope( CommandBufferArray<B>* array, const CommandBufferAccessScopeDesc<B>& beginInfo) : myDesc(beginInfo) , myRefCount(std::make_shared<uint32_t>(1)) , myArray(array) , myIndex(myDesc.scopedBeginEnd ? myArray->begin(beginInfo) : 0) { } template <GraphicsBackend B> CommandBufferAccessScope<B>::CommandBufferAccessScope(const CommandBufferAccessScope& other) : myDesc(other.myDesc) , myRefCount(other.myRefCount) , myArray(other.myArray) , myIndex(other.myIndex) { (*myRefCount)++; } template <GraphicsBackend B> CommandBufferAccessScope<B>::CommandBufferAccessScope(CommandBufferAccessScope&& other) noexcept : myDesc(std::exchange(other.myDesc, {})) , myRefCount(std::exchange(other.myRefCount, {})) , myArray(std::exchange(other.myArray, {})) , myIndex(std::exchange(other.myIndex, {})) { } template <GraphicsBackend B> CommandBufferAccessScope<B>::~CommandBufferAccessScope() { if (myDesc.scopedBeginEnd && myRefCount && (--(*myRefCount) == 0) && myArray->recording(myIndex)) myArray->end(myIndex); } template <GraphicsBackend B> CommandBufferAccessScope<B>& CommandBufferAccessScope<B>::operator=(CommandBufferAccessScope other) { swap(other); return *this; } template <GraphicsBackend B> void CommandBufferAccessScope<B>::swap(CommandBufferAccessScope& rhs) noexcept { std::swap(myDesc, rhs.myDesc); std::swap(myRefCount, rhs.myRefCount); std::swap(myArray, rhs.myArray); std::swap(myIndex, rhs.myIndex); }
30.449275
116
0.753927
djohansson
c68717e0c2888726e89bf12a28c2c90853b0bc01
2,132
cpp
C++
Week 2/7_last_digit_of_the_sum_of_fibonacci_numbers_again/fibonacci_partial_sum.cpp
osamamagdy/Algorithmic-Toolbox
c095e64ae89aa376eabf579dafc959975de78a4d
[ "MIT" ]
null
null
null
Week 2/7_last_digit_of_the_sum_of_fibonacci_numbers_again/fibonacci_partial_sum.cpp
osamamagdy/Algorithmic-Toolbox
c095e64ae89aa376eabf579dafc959975de78a4d
[ "MIT" ]
null
null
null
Week 2/7_last_digit_of_the_sum_of_fibonacci_numbers_again/fibonacci_partial_sum.cpp
osamamagdy/Algorithmic-Toolbox
c095e64ae89aa376eabf579dafc959975de78a4d
[ "MIT" ]
1
2021-01-29T21:57:48.000Z
2021-01-29T21:57:48.000Z
/* #include <iostream> #include <vector> using std::vector; long long get_fibonacci_partial_sum_naive(long long from, long long to) { long long sum = 0; long long current = 0; long long next = 1; for (long long i = 0; i <= to; ++i) { if (i >= from) { sum += current; } long long new_current = next; next = next + current; current = new_current; } return sum % 10; } int get_fibonacci_partial_sum_fast(long long m , long long n) { //Start Computing pisano period int prev = 0; int curr = 1; int result; //Store pisano period in a vector vector<int> v; v.push_back(0); v.push_back(1); do { result = (curr + prev) % 10; prev = curr; curr = result; v.push_back(result); } while ((prev != 0) || (curr != 1)); //Get rid of the occurence of 0 1 v.pop_back(); v.pop_back(); //pisano period length int period = v.size(); //Reduce n,m as the last digit of the sum remains the same for each period //it depends only on its index in pisano period n = n % period; m = m % period; //Compute the last digit of the sum of all last digits in pisano period int sum = 0; /// <summary> /// It might happen to you that the index of smaller number(m) in pisano period is actually beyond the index of bigger number (n) /// In that case you need to split your sum into two parts: /// 1-from m to the end of the period /// 2-assign 0 to m and start the next loop from 0 to n /// </summary> /// <param name="m"></param> /// <param name="n"></param> /// <returns></returns> if (m>n) { for (int i = m; i < period; i++) { sum = (sum + v[i]) % 10; } m = 0; } /// <summary> /// The main Computation loop /// </summary> /// <param name="m"></param> /// <param name="n"></param> /// <returns></returns> for (int i = m; i <= n; i++) { sum = (sum + v[i]) % 10; } return sum; } int main() { long long from, to; std::cin >> from >> to; //std::cout << get_fibonacci_partial_sum_naive(from, to) << '\n'; std::cout << get_fibonacci_partial_sum_fast(from, to) << '\n'; return 0; } */
19.207207
131
0.587711
osamamagdy
c68f2536aab3eb7207f1c8fb417e434ea0b30229
1,872
cpp
C++
c++/en/dropbox/representative_numbers/representative_numbers/representative_numbers.cpp
aimldl/coding
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
[ "MIT" ]
null
null
null
c++/en/dropbox/representative_numbers/representative_numbers/representative_numbers.cpp
aimldl/coding
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
[ "MIT" ]
null
null
null
c++/en/dropbox/representative_numbers/representative_numbers/representative_numbers.cpp
aimldl/coding
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
[ "MIT" ]
null
null
null
// representative_numbers.cpp #include "pch.h" #include <iostream> #include <fstream> using namespace std; //#define DEBUG 1 #define DEBUG 0 void swap(int &a, int &b) { int t; t = a; a = b; b = t; } void bubble_sort(int* arr, int N) { int b = N; // bar for (int i = 0; i < N; i++) { for (int j = 0; j < b - 1; j++) // j < b-1 { if (arr[j] > arr[j + 1]) swap(arr[j], arr[j + 1]); } b--; } } int get_most_freq_num(int* nums, int N); int main() { ifstream ifs("representative_numbers-ex1.txt"); // Input int N = 10; int* nums = new int[N]; for (int i = 0; i < N; i++) ifs >> nums[i]; int mean; int freq; // Mean mean = 0; for (int i = 0; i < N; i++) { mean += nums[i]; } mean /= N; // Output cout << mean << endl; cout << get_most_freq_num(nums, N) << endl; return 0; } int get_most_freq_num(int* nums, int N) { bubble_sort(nums, N); // Find the frequency of each number int** arr = new int*[2]; //arr[0][i] : number, arr[1][i] : frequency for (int i = 0; i < 2; i++) arr[i] = new int[N]; int ref = nums[0]; int count = 1; int j = 0; for (int i = 1; i < N; i++) { if (ref == nums[i]) { count++; } else { arr[0][j] = ref; arr[1][j] = count; ref = nums[i]; count = 1; j++; } } arr[0][j] = ref; arr[1][j] = count; arr[0][j+1] = -1; arr[1][j+1] = -1; if ( DEBUG ) { j = 0; while (arr[0][j] >= 0) { cout << arr[0][j] << " " << arr[1][j] << endl; j++; } } // Find the max frequency int max_freq = arr[1][0]; int max_idx = 0; j = 1; while (arr[0][j] >= 0) { if (max_freq < arr[1][j]) { max_freq = arr[1][j]; max_idx = j; } j++; } int num_wt_max_freq = arr[0][max_idx]; return num_wt_max_freq; }
14.740157
71
0.470085
aimldl
578dc541119789c17a31f55d05729d25c98556df
6,307
cpp
C++
WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/WebProcess/Storage/WebToStorageProcessConnection.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
1
2021-05-27T07:29:31.000Z
2021-05-27T07:29:31.000Z
WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/WebProcess/Storage/WebToStorageProcessConnection.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/WebProcess/Storage/WebToStorageProcessConnection.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
/* * Copyright (C) 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. 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 "config.h" #include "WebToStorageProcessConnection.h" #include "ServiceWorkerClientFetchMessages.h" #include "StorageToWebProcessConnectionMessages.h" #include "WebIDBConnectionToServerMessages.h" #include "WebProcess.h" #include "WebSWClientConnection.h" #include "WebSWClientConnectionMessages.h" #include "WebSWContextManagerConnection.h" #include "WebSWContextManagerConnectionMessages.h" #include "WebServiceWorkerProvider.h" #include <WebCore/SWContextManager.h> using namespace PAL; using namespace WebCore; namespace WebKit { WebToStorageProcessConnection::WebToStorageProcessConnection(IPC::Connection::Identifier connectionIdentifier) : m_connection(IPC::Connection::createClientConnection(connectionIdentifier, *this)) { m_connection->open(); } WebToStorageProcessConnection::~WebToStorageProcessConnection() { m_connection->invalidate(); } void WebToStorageProcessConnection::didReceiveMessage(IPC::Connection& connection, IPC::Decoder& decoder) { #if ENABLE(INDEXED_DATABASE) if (decoder.messageReceiverName() == Messages::WebIDBConnectionToServer::messageReceiverName()) { auto idbConnection = m_webIDBConnectionsByIdentifier.get(decoder.destinationID()); if (idbConnection) idbConnection->didReceiveMessage(connection, decoder); return; } #endif #if ENABLE(SERVICE_WORKER) if (decoder.messageReceiverName() == Messages::WebSWClientConnection::messageReceiverName()) { auto serviceWorkerConnection = m_swConnectionsByIdentifier.get(makeObjectIdentifier<SWServerConnectionIdentifierType>(decoder.destinationID())); if (serviceWorkerConnection) serviceWorkerConnection->didReceiveMessage(connection, decoder); return; } if (decoder.messageReceiverName() == Messages::ServiceWorkerClientFetch::messageReceiverName()) { WebServiceWorkerProvider::singleton().didReceiveServiceWorkerClientFetchMessage(connection, decoder); return; } if (decoder.messageReceiverName() == Messages::WebSWContextManagerConnection::messageReceiverName()) { ASSERT(SWContextManager::singleton().connection()); if (auto* contextManagerConnection = SWContextManager::singleton().connection()) static_cast<WebSWContextManagerConnection&>(*contextManagerConnection).didReceiveMessage(connection, decoder); return; } #endif ASSERT_NOT_REACHED(); } void WebToStorageProcessConnection::didReceiveSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder) { #if ENABLE(SERVICE_WORKER) if (decoder.messageReceiverName() == Messages::WebSWContextManagerConnection::messageReceiverName()) { ASSERT(SWContextManager::singleton().connection()); if (auto* contextManagerConnection = SWContextManager::singleton().connection()) static_cast<WebSWContextManagerConnection&>(*contextManagerConnection).didReceiveSyncMessage(connection, decoder, replyEncoder); return; } #endif ASSERT_NOT_REACHED(); } void WebToStorageProcessConnection::didClose(IPC::Connection& connection) { auto protectedThis = makeRef(*this); #if ENABLE(INDEXED_DATABASE) for (auto& connection : m_webIDBConnectionsByIdentifier.values()) connection->connectionToServerLost(); #endif #if ENABLE(SERVICE_WORKER) for (auto& connection : m_swConnectionsBySession.values()) connection->connectionToServerLost(); m_swConnectionsByIdentifier.clear(); m_swConnectionsBySession.clear(); #endif WebProcess::singleton().webToStorageProcessConnectionClosed(this); #if ENABLE(INDEXED_DATABASE) m_webIDBConnectionsByIdentifier.clear(); m_webIDBConnectionsBySession.clear(); #endif } void WebToStorageProcessConnection::didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference messageReceiverName, IPC::StringReference messageName) { } #if ENABLE(INDEXED_DATABASE) WebIDBConnectionToServer& WebToStorageProcessConnection::idbConnectionToServerForSession(SessionID sessionID) { return *m_webIDBConnectionsBySession.ensure(sessionID, [&] { auto connection = WebIDBConnectionToServer::create(sessionID); auto result = m_webIDBConnectionsByIdentifier.add(connection->identifier(), connection.copyRef()); ASSERT_UNUSED(result, result.isNewEntry); return connection; }).iterator->value; } #endif #if ENABLE(SERVICE_WORKER) WebSWClientConnection& WebToStorageProcessConnection::serviceWorkerConnectionForSession(SessionID sessionID) { ASSERT(sessionID.isValid()); return *m_swConnectionsBySession.ensure(sessionID, [&] { auto connection = WebSWClientConnection::create(m_connection, sessionID); auto result = m_swConnectionsByIdentifier.add(connection->serverConnectionIdentifier(), connection.ptr()); ASSERT_UNUSED(result, result.isNewEntry); return connection; }).iterator->value; } #endif } // namespace WebKit
39.41875
154
0.767243
mlcldh
578e01324ff9a18f505abef35d050a68776d75d7
296
cpp
C++
engine/src/Graphics/TerrainInstance.cpp
aleksigron/graphics-toolkit
f8e60c57316a72dff9de07512e9771deb3799208
[ "MIT" ]
14
2017-10-17T16:20:20.000Z
2021-12-21T14:49:00.000Z
engine/src/Graphics/TerrainInstance.cpp
aleksigron/graphics-toolkit
f8e60c57316a72dff9de07512e9771deb3799208
[ "MIT" ]
null
null
null
engine/src/Graphics/TerrainInstance.cpp
aleksigron/graphics-toolkit
f8e60c57316a72dff9de07512e9771deb3799208
[ "MIT" ]
1
2019-05-12T13:50:23.000Z
2019-05-12T13:50:23.000Z
#include "Graphics/TerrainInstance.hpp" TerrainInstance::TerrainInstance() : meshId(MeshId::Null), terrainSize(128.0f), terrainResolution(128), textureScale(0.25f, 0.25f), minHeight(-0.25f), maxHeight(0.05f), heightData(nullptr), vertexArrayId(0), uniformBufferId(0), textureId(0) { }
18.5
39
0.736486
aleksigron
5790db543563f27ea8ff6c6c0e0ae7f4e464bdc0
845
cpp
C++
Library/Room/Mode.cpp
theater/ArduinoMega
6515e6b6fbe62f75bf67ea2470760757af457b92
[ "Apache-2.0" ]
null
null
null
Library/Room/Mode.cpp
theater/ArduinoMega
6515e6b6fbe62f75bf67ea2470760757af457b92
[ "Apache-2.0" ]
null
null
null
Library/Room/Mode.cpp
theater/ArduinoMega
6515e6b6fbe62f75bf67ea2470760757af457b92
[ "Apache-2.0" ]
null
null
null
/* * Mode.cpp * * Created on: Mar 15, 2018 * Author: theater */ #include <Mode.h> #include <MqttUtil.h> Mode::Mode(ModeType mode) : Mode(mode, NULL) { } Mode::Mode(ModeType mode, char * id ) { this->id = id; this->mode = mode; this->callbackTopic = createCallbackTopic(id); MqttUtil::subscribe(id); } void Mode::updateValue(const char* id, const char* value) { if (!strcmp(id, this->id)) { if (!strcmp(value, "ALL_OFF")) { setMode(ALL_OFF); } else if (!strcmp(value, "MANUAL")) { setMode(MANUAL); } else { setMode(AUTO); } logDebug("Updated MODE " + String(id) + " to value: " + String(value)); } } Mode::~Mode() { } char* Mode::getId() { return id; } ModeType Mode::getMode() { return mode; } void Mode::setMode(ModeType mode) { this->mode = mode; }
17.604167
74
0.577515
theater
579f25abdbd7a27642bfc7bf6bca97650fc0110b
1,260
cpp
C++
ke_mode/winnt/ntke_cpprtl/gstatic_test_suite/test_gstatic01.cpp
133a/project_ntke_cpprtl
f2d3fd36a2c44f968f7b10c344abe7e0b7aa2e4c
[ "MIT" ]
12
2016-08-02T19:22:26.000Z
2022-02-28T21:20:18.000Z
ke_mode/winnt/ntke_cpprtl/gstatic_test_suite/test_gstatic01.cpp
133a/project_ntke_cpprtl
f2d3fd36a2c44f968f7b10c344abe7e0b7aa2e4c
[ "MIT" ]
null
null
null
ke_mode/winnt/ntke_cpprtl/gstatic_test_suite/test_gstatic01.cpp
133a/project_ntke_cpprtl
f2d3fd36a2c44f968f7b10c344abe7e0b7aa2e4c
[ "MIT" ]
6
2018-04-15T16:51:40.000Z
2021-04-23T19:32:34.000Z
///////////////////////////////////////////////////////////////////////////// //// copyright (c) 2012-2017 project_ntke_cpprtl //// mailto:[email protected] //// license: the MIT license ///////////////////////////////////////////////////////////////////////////// #ifdef NT_KERNEL_MODE # include "ntddk.include.h" #endif namespace { enum { TEST_101 = 101 , TEST_102 , TEST_103 }; int ftest_101(int&); int ftest_102(int&); int ftest_103(int&); int res = 0; } int test_101 = ftest_101(res); static int test_102 = ftest_102(res); namespace { int test_103 = ftest_103(res); } namespace { int ftest_101(int& r) { #ifdef NT_KERNEL_MODE DbgPrint("test_gstatic01 ---> ftest_101\n"); #endif r += TEST_101; return TEST_101; } int ftest_102(int& r) { #ifdef NT_KERNEL_MODE DbgPrint("test_gstatic01 ---> ftest_102\n"); #endif r += TEST_102; return TEST_102; } int ftest_103(int& r) { #ifdef NT_KERNEL_MODE DbgPrint("test_gstatic01 ---> ftest_103\n"); #endif r += TEST_103; return TEST_103; } } namespace cpprtl { namespace test { namespace gstatic { int test_gstatic01() { return res - test_101 - test_102 - test_103 ; } } } }
15.75
77
0.543651
133a
57a666a259ae8493beef0554fc47706ad0ab4cec
1,603
hxx
C++
c++/src/laolx/parser/OperatorFunctionId.hxx
kpfalzer/laolx
66e5571a63c289294af69949b9ec56f752efc51b
[ "MIT" ]
null
null
null
c++/src/laolx/parser/OperatorFunctionId.hxx
kpfalzer/laolx
66e5571a63c289294af69949b9ec56f752efc51b
[ "MIT" ]
null
null
null
c++/src/laolx/parser/OperatorFunctionId.hxx
kpfalzer/laolx
66e5571a63c289294af69949b9ec56f752efc51b
[ "MIT" ]
null
null
null
// // OperatorFunctionId.hxx // // // Created by Karl W Pfalzer. // #ifndef laolx_parser_OperatorFunctionId_hxx #define laolx_parser_OperatorFunctionId_hxx #include "laolx/parser/laolx.hxx" namespace laolx { namespace parser { class OverloadableOperator : public _Acceptor { public: explicit OverloadableOperator() {} virtual ~OverloadableOperator() {} class Node : public NodeVector { public: virtual ~Node() {} virtual ostream& operator<<(ostream& os) const; NODE_TYPE_DECLARE; private: friend class OverloadableOperator; explicit Node(const TPNode& node); }; static const OverloadableOperator& THE_ONE; protected: TPNode _accept(Consumer& consumer) const; }; typedef PTRcObjPtr<OverloadableOperator::Node> TPOverloadableOperatorNode; DEF_TO_XXXNODE(OverloadableOperator) class OperatorFunctionId : public _Acceptor { public: explicit OperatorFunctionId() {} virtual ~OperatorFunctionId() {} class Node : public NodeVector { public: virtual ~Node() {} virtual ostream& operator<<(ostream& os) const; NODE_TYPE_DECLARE; private: friend class OperatorFunctionId; explicit Node(const TPNode& node); }; static const OperatorFunctionId& THE_ONE; protected: TPNode _accept(Consumer& consumer) const; }; typedef PTRcObjPtr<OperatorFunctionId::Node> TPOperatorFunctionIdNode; DEF_TO_XXXNODE(OperatorFunctionId) } } #endif /* laolx_parser_OperatorFunctionId_hxx */
19.083333
74
0.679351
kpfalzer
57a71d2cfb1d136a1e75e095ade0219ba494b7fc
159
hh
C++
src/Zynga/Framework/Service/V2/Swagger.hh
chintan-j-patel/zynga-hacklang-framework
d9893b8873e3c8c7223772fd3c94d2531760172a
[ "MIT" ]
19
2018-04-23T09:30:48.000Z
2022-03-06T21:35:18.000Z
src/Zynga/Framework/Service/V2/Swagger.hh
chintan-j-patel/zynga-hacklang-framework
d9893b8873e3c8c7223772fd3c94d2531760172a
[ "MIT" ]
22
2017-11-27T23:39:25.000Z
2019-08-09T08:56:57.000Z
src/Zynga/Framework/Service/V2/Swagger.hh
chintan-j-patel/zynga-hacklang-framework
d9893b8873e3c8c7223772fd3c94d2531760172a
[ "MIT" ]
28
2017-11-16T20:53:56.000Z
2021-01-04T11:13:17.000Z
<?hh // strict namespace Zynga\Framework\Service\V2; use Zynga\Framework\Service\V2\Swagger\Base as SwaggerBase; final class Swagger extends SwaggerBase {}
19.875
59
0.786164
chintan-j-patel
57b1eb7fd98b09c64f7ee1df48067fc178d13085
1,575
cpp
C++
source/app/iosuhax.cpp
emiyl/dumpling
48d76f5a4c035585683e1b414df2b66d5bb12e15
[ "MIT" ]
53
2020-04-11T15:49:21.000Z
2022-03-20T03:47:33.000Z
source/app/iosuhax.cpp
emiyl/dumpling
48d76f5a4c035585683e1b414df2b66d5bb12e15
[ "MIT" ]
22
2020-08-14T19:45:13.000Z
2022-03-30T00:49:27.000Z
source/app/iosuhax.cpp
emiyl/dumpling
48d76f5a4c035585683e1b414df2b66d5bb12e15
[ "MIT" ]
11
2020-04-19T09:19:08.000Z
2022-03-21T20:16:54.000Z
#include "iosuhax.h" #include "gui.h" int32_t mcpHookHandle = -1; int32_t fsaHandle = -1; int32_t iosuhaxHandle = -1; OSEvent haxStartEvent = {}; void haxStartCallback(IOSError arg1, void *arg2) { } bool openIosuhax() { WHBLogPrint("Preparing iosuhax..."); WHBLogConsoleDraw(); // Open MCP to send the start command mcpHookHandle = MCP_Open(); if (mcpHookHandle < 0) { WHBLogPrint("Failed to open the MCP IPC!"); return false; } // Send 0x62 ioctl command that got replaced in the ios_kernel to run the wupserver IOS_IoctlAsync(mcpHookHandle, 0x62, nullptr, 0, nullptr, 0, haxStartCallback, nullptr); OSSleepTicks(OSSecondsToTicks(1)); // Connect to dumplinghax iosuhaxHandle = IOSUHAX_Open("/dev/mcp"); if (iosuhaxHandle < 0) { WHBLogPrint("Couldn't open iosuhax :/"); WHBLogPrint("Something interfered with the exploit..."); WHBLogPrint("Try restarting your Wii U and launching Dumpling again!"); return false; } fsaHandle = IOSUHAX_FSA_Open(); if (fsaHandle < 0) { WHBLogPrint("Couldn't open iosuhax FSA!"); return false; } return true; } void closeIosuhax() { if (fsaHandle > 0) IOSUHAX_FSA_Close(fsaHandle); if (iosuhaxHandle > 0) IOSUHAX_Close(); if (mcpHookHandle > 0) MCP_Close(mcpHookHandle); OSSleepTicks(OSSecondsToTicks(1)); mcpHookHandle = -1; fsaHandle = -1; iosuhaxHandle = -1; } int32_t getFSAHandle() { return fsaHandle; } int32_t getIosuhaxHandle() { return iosuhaxHandle; }
25.819672
91
0.660317
emiyl
57b23524ca7c81bb0b3701aa84c555431b8cda0c
3,826
cpp
C++
SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.cpp
ercdndrs/Arduino-Source
c0490f0f06aaa38759aa8f11def9e1349e551679
[ "MIT" ]
null
null
null
SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.cpp
ercdndrs/Arduino-Source
c0490f0f06aaa38759aa8f11def9e1349e551679
[ "MIT" ]
null
null
null
SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.cpp
ercdndrs/Arduino-Source
c0490f0f06aaa38759aa8f11def9e1349e551679
[ "MIT" ]
null
null
null
/* Egg Super-Combined 2 * * From: https://github.com/PokemonAutomation/Arduino-Source * */ #include "Common/SwitchFramework/FrameworkSettings.h" #include "PokemonSwSh/Programs/ReleaseHelpers.h" #include "PokemonSwSh_EggHelpers.h" #include "PokemonSwSh_EggCombinedShared.h" #include "PokemonSwSh_EggSuperCombined2.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonSwSh{ EggSuperCombined2::EggSuperCombined2() : SingleSwitchProgram( FeedbackType::NONE, PABotBaseLevel::PABOTBASE_31KB, "Egg Super-Combined 2", "NativePrograms/EggSuperCombined2.md", "Fetch and hatch eggs at the same time. (Fastest - 1700 eggs/day for 5120-step)" ) , BOXES_TO_RELEASE( "<b>Boxes to Release:</b><br>Start by releasing this many boxes.", 2, 0, 32 ) , BOXES_TO_SKIP( "<b>Boxes to Skip:</b><br>Then skip this many boxes.", 1, 0, 32 ) , BOXES_TO_HATCH( "<b>Boxes to Hatch:</b>", 31, 0, 32 ) , FETCHES_PER_BATCH( "<b>Fetches per Batch:</b><br>For each batch of eggs, attempt this many egg fetches.", 6.0, 0, 7 ) , TOUCH_DATE_INTERVAL( "<b>Rollover Prevention:</b><br>Prevent a den from rolling over by periodically touching the date. If set to zero, this feature is disabled.", "4 * 3600 * TICKS_PER_SECOND" ) , m_advanced_options( "<font size=4><b>Advanced Options:</b> You should not need to touch anything below here.</font>" ) , SAFETY_TIME( "<b>Safety Time:</b><br>Additional time added to the spinning.", "8 * TICKS_PER_SECOND" ) , EARLY_HATCH_SAFETY( "<b>Safety Time:</b><br>Additional time added to the spinning.", "5 * TICKS_PER_SECOND" ) , HATCH_DELAY( "<b>Hatch Delay:</b><br>Total animation time for hatching 5 eggs when there are no shinies.", "88 * TICKS_PER_SECOND" ) { m_options.emplace_back(&BOXES_TO_RELEASE, "BOXES_TO_RELEASE"); m_options.emplace_back(&BOXES_TO_SKIP, "BOXES_TO_SKIP"); m_options.emplace_back(&BOXES_TO_HATCH, "BOXES_TO_HATCH"); m_options.emplace_back(&STEPS_TO_HATCH, "STEPS_TO_HATCH"); m_options.emplace_back(&FETCHES_PER_BATCH, "FETCHES_PER_BATCH"); m_options.emplace_back(&TOUCH_DATE_INTERVAL, "TOUCH_DATE_INTERVAL"); m_options.emplace_back(&m_advanced_options, ""); m_options.emplace_back(&SAFETY_TIME, "SAFETY_TIME"); m_options.emplace_back(&EARLY_HATCH_SAFETY, "EARLY_HATCH_SAFETY"); m_options.emplace_back(&HATCH_DELAY, "HATCH_DELAY"); } void EggSuperCombined2::program(SingleSwitchProgramEnvironment& env) const{ EggCombinedSession session{ .BOXES_TO_HATCH = BOXES_TO_HATCH, .STEPS_TO_HATCH = STEPS_TO_HATCH, .FETCHES_PER_BATCH = (float)FETCHES_PER_BATCH, .SAFETY_TIME = SAFETY_TIME, .EARLY_HATCH_SAFETY = EARLY_HATCH_SAFETY, .HATCH_DELAY = HATCH_DELAY, .TOUCH_DATE_INTERVAL = TOUCH_DATE_INTERVAL, }; grip_menu_connect_go_home(env.console); resume_game_back_out(env.console, TOLERATE_SYSTEM_UPDATE_MENU_FAST, 400); // Mass Release ssf_press_button2(env.console, BUTTON_X, OVERWORLD_TO_MENU_DELAY, 20); ssf_press_button1(env.console, BUTTON_A, 200); ssf_press_button1(env.console, BUTTON_R, 250); release_boxes(env.console, BOXES_TO_RELEASE, BOX_SCROLL_DELAY, BOX_CHANGE_DELAY); // Skip Boxes for (uint8_t c = 0; c <= BOXES_TO_SKIP; c++){ ssf_press_button1(env.console, BUTTON_R, 60); } pbf_mash_button(env.console, BUTTON_B, 600); session.eggcombined2_body(env); end_program_callback(env.console); end_program_loop(env.console); } } } }
34.781818
151
0.670413
ercdndrs
57bc0a7501acae5ab7ed283ba9bdc7dd3d49b10a
1,952
hpp
C++
include/Log.hpp
savageking-io/evelengine
f4f31419077e3467db271e82b05164eafa521eb7
[ "Apache-2.0" ]
null
null
null
include/Log.hpp
savageking-io/evelengine
f4f31419077e3467db271e82b05164eafa521eb7
[ "Apache-2.0" ]
null
null
null
include/Log.hpp
savageking-io/evelengine
f4f31419077e3467db271e82b05164eafa521eb7
[ "Apache-2.0" ]
null
null
null
#ifndef __EVEL_ENGINE_LOG_HPP__ #define __EVEL_ENGINE_LOG_HPP__ #include "spdlog/spdlog.h" #include "spdlog/sinks/stdout_color_sinks.h" #include "spdlog/sinks/basic_file_sink.h" namespace EvelEngine { class Log { public: Log(); ~Log(); void initialize(); void setLevel(spdlog::level::level_enum level); std::shared_ptr<spdlog::logger> sget(); template<typename... Args> void trace(const char* fmt, const Args&... args) { if (_log == nullptr) return; _log->trace(fmt, args...); } template<typename... Args> void debug(const char* fmt, const Args&... args) { if (_log == nullptr) return; _log->debug(fmt, args...); } template<typename... Args> void info(const char* fmt, const Args&... args) { if (_log == nullptr) return; _log->info(fmt, args...); } template<typename... Args> void warn(const char* fmt, const Args&... args) { if (_log == nullptr) return; _log->warn(fmt, args...); } template<typename... Args> void error(const char* fmt, const Args&... args) { if (_log == nullptr) return; _log->error(fmt, args...); } template<typename... Args> void critical(const char* fmt, const Args&... args) { if (_log == nullptr) return; _log->critical(fmt, args...); } private: std::shared_ptr<spdlog::logger> _log; ///< Logging subsystem }; } #endif
30.030769
72
0.441598
savageking-io
57bd226413697bca6d490a522c7cc5a8a4f0b247
12,156
cpp
C++
src/OVAFTModel.cpp
kokarare1212/OpenVAFT
42dbec4ed1123a98f465e61833a69f25bc948cd2
[ "Apache-2.0" ]
1
2022-03-23T02:35:52.000Z
2022-03-23T02:35:52.000Z
src/OVAFTModel.cpp
kokarare1212/OpenVAFT
42dbec4ed1123a98f465e61833a69f25bc948cd2
[ "Apache-2.0" ]
null
null
null
src/OVAFTModel.cpp
kokarare1212/OpenVAFT
42dbec4ed1123a98f465e61833a69f25bc948cd2
[ "Apache-2.0" ]
null
null
null
#include "OVAFTModel.h" #include <CubismDefaultParameterId.hpp> #include <CubismModelSettingJson.hpp> #include <Motion/CubismMotion.hpp> #include <fstream> #include <Id/CubismIdManager.hpp> #include <Rendering/OpenGL/CubismRenderer_OpenGLES2.hpp> #include <Utils/CubismString.hpp> #include "OVAFTFaceTracker.h" #include "OVAFTGLWidget.h" #include "OVAFTTextureManager.h" using namespace Live2D::Cubism::Framework; using namespace Live2D::Cubism::Framework::DefaultParameterId; using namespace std; namespace { csmByte *CreateBuffer(const string &filePath, csmSizeInt *outSize) { const char *path = filePath.c_str(); int size = 0; struct stat statBuf{}; if (stat(path, &statBuf) == 0) { size = statBuf.st_size; } std::fstream file; char *buf = new char[size]; file.open(path, std::ios::in | std::ios::binary); if (!file.is_open()) { return nullptr; } file.read(buf, size); file.close(); *outSize = size; return reinterpret_cast<csmByte *>(buf); } } OVAFTModel::OVAFTModel() : CubismUserModel(), modelSetting(nullptr), userTimeSeconds(0.0f) { idParamAngleX = CubismFramework::GetIdManager()->GetId(ParamAngleX); idParamAngleY = CubismFramework::GetIdManager()->GetId(ParamAngleY); idParamAngleZ = CubismFramework::GetIdManager()->GetId(ParamAngleZ); idParamBodyAngleX = CubismFramework::GetIdManager()->GetId(ParamBodyAngleX); idParamBodyAngleY = CubismFramework::GetIdManager()->GetId(ParamBodyAngleY); idParamBodyAngleZ = CubismFramework::GetIdManager()->GetId(ParamBodyAngleZ); idParamCheek = CubismFramework::GetIdManager()->GetId(ParamCheek); idParamEyeLOpen = CubismFramework::GetIdManager()->GetId(ParamEyeLOpen); idParamEyeLSmile = CubismFramework::GetIdManager()->GetId(ParamEyeLSmile); idParamEyeROpen = CubismFramework::GetIdManager()->GetId(ParamEyeROpen); idParamEyeRSmile = CubismFramework::GetIdManager()->GetId(ParamEyeRSmile); idParamMouthForm = CubismFramework::GetIdManager()->GetId(ParamMouthForm); idParamMouthOpenY = CubismFramework::GetIdManager()->GetId(ParamMouthOpenY); } OVAFTModel::~OVAFTModel() { renderBuffer.DestroyOffscreenFrame(); ReleaseMotions(); ReleaseExpressions(); for (csmInt32 i = 0; i < modelSetting->GetMotionGroupCount(); i++) { const csmChar *group = modelSetting->GetMotionGroupName(i); ReleaseMotionGroup(group); } delete (modelSetting); } void OVAFTModel::DoDraw() { if (_model == nullptr) return; GetRenderer<Rendering::CubismRenderer_OpenGLES2>()->DrawModel(); } void OVAFTModel::Draw(CubismMatrix44 &matrix) { if (_model == nullptr) return; matrix.MultiplyByMatrix(_modelMatrix); GetRenderer<Rendering::CubismRenderer_OpenGLES2>()->SetMvpMatrix(&matrix); DoDraw(); } Csm::Rendering::CubismOffscreenFrame_OpenGLES2 &OVAFTModel::GetRenderBuffer() { return renderBuffer; } void OVAFTModel::LoadAssets(const csmChar *dir, const csmChar *fileName) { modelHomeDir = dir; csmSizeInt size; const csmString path = csmString(dir) + fileName; csmByte *buffer = CreateBuffer(path.GetRawString(), &size); ICubismModelSetting *setting = new CubismModelSettingJson(buffer, size); delete[] buffer; SetupModel(setting); CreateRenderer(); SetupTextures(); } void OVAFTModel::PreloadMotionGroup(const csmChar *group) { const csmInt32 count = modelSetting->GetMotionCount(group); for (csmInt32 i = 0; i < count; i++) { csmString name = Utils::CubismString::GetFormatedString("%s_%d", group, i); csmString path = modelSetting->GetMotionFileName(group, i); path = modelHomeDir + path; csmByte *buffer1; csmSizeInt size; buffer1 = CreateBuffer(path.GetRawString(), &size); auto *tmpMotion = dynamic_cast<CubismMotion *>(LoadMotion(buffer1, size, name.GetRawString())); csmFloat32 fadeTime = modelSetting->GetMotionFadeInTimeValue(group, i); if (fadeTime >= 0.0f) { tmpMotion->SetFadeInTime(fadeTime); } fadeTime = modelSetting->GetMotionFadeOutTimeValue(group, i); if (fadeTime >= 0.0f) { tmpMotion->SetFadeOutTime(fadeTime); } tmpMotion->SetEffectIds(eyeBlinkIds, lipSyncIds); if (motions[name] != NULL) { ACubismMotion::Delete(motions[name]); } motions[name] = tmpMotion; } } void OVAFTModel::ReleaseExpressions() { for (csmMap<csmString, ACubismMotion *>::const_iterator iter = expressions.Begin(); iter != expressions.End(); ++iter) { ACubismMotion::Delete(iter->Second); } expressions.Clear(); } void OVAFTModel::ReleaseMotionGroup(const csmChar *group) const { const csmInt32 count = modelSetting->GetMotionCount(group); for (csmInt32 i = 0; i < count; i++) { csmString voice = modelSetting->GetMotionSoundFileName(group, i); if (strcmp(voice.GetRawString(), "") != 0) { csmString path = voice; path = modelHomeDir + path; } } } void OVAFTModel::ReleaseMotions() { for (csmMap<csmString, ACubismMotion *>::const_iterator iter = motions.Begin(); iter != motions.End(); ++iter) { ACubismMotion::Delete(iter->Second); } motions.Clear(); } void OVAFTModel::SetupModel(ICubismModelSetting *setting) { _updating = true; _initialized = false; modelSetting = setting; csmSizeInt size; // Cubism Model if (strcmp(modelSetting->GetModelFileName(), "") != 0) { csmString path = modelSetting->GetModelFileName(); path = modelHomeDir + path; csmByte *buffer1; buffer1 = CreateBuffer(path.GetRawString(), &size); LoadModel(buffer1, size); } // Expression if (modelSetting->GetExpressionCount() > 0) { const csmInt32 count = modelSetting->GetExpressionCount(); for (csmInt32 i = 0; i < count; i++) { csmString name = modelSetting->GetExpressionName(i); csmString path = modelSetting->GetExpressionFileName(i); path = modelHomeDir + path; csmByte *buffer2; buffer2 = CreateBuffer(path.GetRawString(), &size); ACubismMotion *motion = LoadExpression(buffer2, size, name.GetRawString()); if (expressions[name] != NULL) { ACubismMotion::Delete(expressions[name]); expressions[name] = NULL; } expressions[name] = motion; } } // Physics if (strcmp(modelSetting->GetPhysicsFileName(), "") != 0) { csmString path = modelSetting->GetPhysicsFileName(); path = modelHomeDir + path; csmByte *buffer3; buffer3 = CreateBuffer(path.GetRawString(), &size); LoadPhysics(buffer3, size); } // Pose if (strcmp(modelSetting->GetPoseFileName(), "") != 0) { csmString path = modelSetting->GetPoseFileName(); path = modelHomeDir + path; csmByte *buffer4; buffer4 = CreateBuffer(path.GetRawString(), &size); LoadPose(buffer4, size); } // EyeBlink if (modelSetting->GetEyeBlinkParameterCount() > 0) { _eyeBlink = CubismEyeBlink::Create(modelSetting); } // Breath _breath = CubismBreath::Create(); csmVector<CubismBreath::BreathParameterData> breathParameters; breathParameters.PushBack(CubismBreath::BreathParameterData(idParamAngleX, 0.0f, 15.0f, 6.5345f, 0.5f)); breathParameters.PushBack(CubismBreath::BreathParameterData(idParamAngleY, 0.0f, 8.0f, 3.5345f, 0.5f)); breathParameters.PushBack(CubismBreath::BreathParameterData(idParamAngleZ, 0.0f, 10.0f, 5.5345f, 0.5f)); breathParameters.PushBack(CubismBreath::BreathParameterData(idParamBodyAngleX, 0.0f, 4.0f, 15.5345f, 0.5f)); breathParameters.PushBack( CubismBreath::BreathParameterData(CubismFramework::GetIdManager()->GetId(ParamBreath), 0.5f, 0.5f, 3.2345f, 0.5f)); _breath->SetParameters(breathParameters); // UserData if (strcmp(modelSetting->GetUserDataFile(), "") != 0) { csmString path = modelSetting->GetUserDataFile(); path = modelHomeDir + path; csmByte *buffer5; buffer5 = CreateBuffer(path.GetRawString(), &size); LoadUserData(buffer5, size); } // EyeBlinkIds csmInt32 eyeBlinkIdCount = modelSetting->GetEyeBlinkParameterCount(); for (csmInt32 i = 0; i < eyeBlinkIdCount; ++i) { eyeBlinkIds.PushBack(modelSetting->GetEyeBlinkParameterId(i)); } // LipSyncIds csmInt32 lipSyncIdCount = modelSetting->GetLipSyncParameterCount(); for (csmInt32 i = 0; i < lipSyncIdCount; ++i) { lipSyncIds.PushBack(modelSetting->GetLipSyncParameterId(i)); } // Layout csmMap<csmString, csmFloat32> layout; modelSetting->GetLayoutMap(layout); _modelMatrix->SetupFromLayout(layout); _model->SaveParameters(); for (csmInt32 i = 0; i < modelSetting->GetMotionGroupCount(); i++) { const csmChar *group = modelSetting->GetMotionGroupName(i); PreloadMotionGroup(group); } _motionManager->StopAllMotions(); _updating = false; _initialized = true; } void OVAFTModel::SetupTextures() { for (csmInt32 modelTextureNumber = 0; modelTextureNumber < modelSetting->GetTextureCount(); modelTextureNumber++) { // Skip Bind / Load if (strcmp(modelSetting->GetTextureFileName(modelTextureNumber), "") == 0) continue; // Load Texture csmString texturePath = modelSetting->GetTextureFileName(modelTextureNumber); texturePath = modelHomeDir + texturePath; OVAFTTextureManager::TextureInfo *texture = OVAFTGLWidget::GetInstance()->GetTextureManager()->CreateTextureFromPngFile( texturePath.GetRawString()); const auto glTextureNumber = static_cast<csmInt32>(texture->id); // OpenGL GetRenderer<Rendering::CubismRenderer_OpenGLES2>()->BindTexture(modelTextureNumber, glTextureNumber); } GetRenderer<Rendering::CubismRenderer_OpenGLES2>()->IsPremultipliedAlpha(false); } void OVAFTModel::Update() { const csmFloat32 deltaTimeSeconds = OVAFTGLWidget::GetDeltaTime(); userTimeSeconds += deltaTimeSeconds; _dragManager->Update(deltaTimeSeconds); _dragX = _dragManager->GetX(); _dragY = _dragManager->GetY(); // Motion _model->LoadParameters(); _motionManager->UpdateMotion(_model, deltaTimeSeconds); _model->SaveParameters(); if (_expressionManager != nullptr) { _expressionManager->UpdateMotion(_model, deltaTimeSeconds); } // Face Tracking auto *faceTracker = OVAFTFaceTracker::GetInstance(); _model->SetParameterValue(idParamAngleX, faceTracker->AngleX()); _model->SetParameterValue(idParamAngleY, faceTracker->AngleY()); _model->SetParameterValue(idParamAngleZ, faceTracker->AngleZ()); _model->SetParameterValue(idParamBodyAngleX, faceTracker->BodyAngleX()); _model->SetParameterValue(idParamBodyAngleY, faceTracker->BodyAngleY()); _model->SetParameterValue(idParamBodyAngleZ, faceTracker->BodyAngleZ()); _model->SetParameterValue(idParamCheek, faceTracker->Cheek()); _model->SetParameterValue(idParamEyeLOpen, faceTracker->EyeLOpen()); _model->SetParameterValue(idParamEyeLSmile, faceTracker->EyeLSmile()); _model->SetParameterValue(idParamEyeROpen, faceTracker->EyeROpen()); _model->SetParameterValue(idParamEyeRSmile, faceTracker->EyeRSmile()); _model->SetParameterValue(idParamMouthForm, faceTracker->MouthForm()); _model->SetParameterValue(idParamMouthOpenY, faceTracker->MouthOpenY()); // Breath Setting if (_breath != nullptr) { _breath->UpdateParameters(_model, deltaTimeSeconds); } // Physics Setting if (_physics != nullptr) { _physics->Evaluate(_model, deltaTimeSeconds); } // Pose Setting if (_pose != nullptr) { _pose->UpdateParameters(_model, deltaTimeSeconds); } _model->Update(); }
35.964497
128
0.675716
kokarare1212
57c513e32a933ef4abb0e53b6e0bec1df76a9448
1,419
cpp
C++
data/dailyCodingProblem457.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
2
2020-09-04T20:56:23.000Z
2021-06-11T07:42:26.000Z
data/dailyCodingProblem457.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
data/dailyCodingProblem457.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /* Given a word W and a string S, find all starting indices in S which are anagrams of W. For example, given that W is "ab", and S is "abxaba", return 0, 3, and 4. */ // return true if umap2 contains all the keys of umap1 with respective values // and all other keys of umap2 are with value zero bool areSame(unordered_map<char, int> umap1, unordered_map<char,int> umap2){ for(auto it : umap1){ if(umap2[it.first] == 0) if(it.second != 0) return false; else{ if(it.second != umap2[it.first]) return false; } } return true; } vector<int> findAnagramIndices(string w, string s){ unordered_map<char, int> wordMap; // stores the characters of word with their respective counts unordered_map<char, int> stringMap; // stores the characters in the window of string with their respective counts vector<int> indices = {}; // stores the starting indices of anagrams for(int i=0;i<w.length();i++){ wordMap[w[i]]++; stringMap[s[i]]++; } for(int i=w.length();i<s.length();i++){ if(areSame(wordMap, stringMap)) indices.push_back(i-w.length()); stringMap[s[i]]++; stringMap[s[i-w.length()]]--; } if(areSame(wordMap,stringMap)) indices.push_back(s.length()-w.length()); return indices; } // main function int main(){ vector<int> indices = findAnagramIndices("ab","abxaba"); for(int i : indices) cout << i << "\n"; return 0; }
26.773585
114
0.676533
vidit1999
57dc91b93565abdfc2ee7dc1e690cd091ca2cbaf
2,302
cpp
C++
InfoBar.cpp
NamaChikara/Minesweeper_Cpp
1edfc0c886d21dc172c5c387978d5212cf81fa1f
[ "MIT" ]
null
null
null
InfoBar.cpp
NamaChikara/Minesweeper_Cpp
1edfc0c886d21dc172c5c387978d5212cf81fa1f
[ "MIT" ]
null
null
null
InfoBar.cpp
NamaChikara/Minesweeper_Cpp
1edfc0c886d21dc172c5c387978d5212cf81fa1f
[ "MIT" ]
null
null
null
#include "InfoBar.h" InfoBar::InfoBar(float swidth, float yloc, float height, std::string font_file) : screen_width{ swidth }, y_offset{ yloc }, info_height{ height } { if (!font.loadFromFile(font_file)) { std::cerr << "Could not load " << font_file << " font file." << std::endl; } // note: the string values of these text boxes is set in main.cpp // the locations are also set in main.cpp via InfoBar::update_location(); clock_text.setFont(font); clock_text.setCharacterSize(30); clock_text.setFillColor(sf::Color(255,255,255)); bomb_text.setFont(font); bomb_text.setCharacterSize(30); bomb_text.setFillColor(sf::Color(255,255,255)); mistake_text.setFont(font); mistake_text.setCharacterSize(30); mistake_text.setFillColor(sf::Color(255,255,255)); } void InfoBar::update_text(sf::Clock clock, const Board& m_board) { int mistakes_made = m_board.num_mistakes(); std::string m_text = "Mistakes: " + std::to_string(mistakes_made); mistake_text.setString(m_text); int bombs_unmarked = m_board.num_bombs() - m_board.num_marked() - mistakes_made; std::string b_text = "Unmarked: " + std::to_string(bombs_unmarked); bomb_text.setString(b_text); sf::Time elapsed = clock.getElapsedTime(); int time = (int)elapsed.asSeconds(); clock_text.setString(std::to_string(time)); } void InfoBar::update_location() { // x spacing first float clock_width = clock_text.getGlobalBounds().width; float bomb_width = bomb_text.getGlobalBounds().width; float mistake_width = mistake_text.getGlobalBounds().width; float spacing = (screen_width - clock_width - bomb_width - mistake_width) / 4; // y spacing float y_set = y_offset + (info_height - bomb_text.getGlobalBounds().height) / 2; float clock_x = spacing; clock_text.setPosition(sf::Vector2f(clock_x, y_set)); float bomb_x = 2 * spacing + clock_width; bomb_text.setPosition(sf::Vector2f(bomb_x, y_set)); float mistake_x = 3 * spacing + clock_width + bomb_width; mistake_text.setPosition(sf::Vector2f(mistake_x, y_set)); } void InfoBar::update(sf::Clock clock, const Board& m_board, sf::RenderTarget& target) { update_text(clock, m_board); update_location(); } void InfoBar::draw(sf::RenderTarget& target, sf::RenderStates) const { target.draw(clock_text); target.draw(bomb_text); target.draw(mistake_text); }
30.289474
81
0.739357
NamaChikara
57e0c53b9df2aed101c81120bc0523b33ce3ccec
911
cpp
C++
devdc133.cpp
vidit1999/coding_problems
b6c9fa7fda37d9424cd11bcd54b385fd8cf1ee0a
[ "BSD-2-Clause" ]
1
2020-02-24T18:28:48.000Z
2020-02-24T18:28:48.000Z
devdc133.cpp
vidit1999/coding_problems
b6c9fa7fda37d9424cd11bcd54b385fd8cf1ee0a
[ "BSD-2-Clause" ]
null
null
null
devdc133.cpp
vidit1999/coding_problems
b6c9fa7fda37d9424cd11bcd54b385fd8cf1ee0a
[ "BSD-2-Clause" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /* Mr. Square is going on holiday. He wants to bring 2 of his favorite squares with him, so he put them in his rectangle suitcase. Write a function that, given the size of the squares and the suitcase, return whether the squares can fit inside the suitcase. fit_in(a,b,m,n) a,b are the sizes of the squares m,n are the sizes of the suitcase Example fit_in(1,2,3,2) should return True fit_in(1,2,2,1) should return False fit_in(3,2,3,2) should return False fit_in(1,2,1,2) should return False */ bool fit_in(int a, int b, int m, int n){ return ((a + b) <= max(m, n)) && (max(a, b) <= min(m, n)); } void testFunc(vector<vector<int>> v){ for(auto it : v){ if(fit_in(it[0], it[1], it[2], it[3])) cout << "Yes\n"; else cout << "No\n"; } } // main function int main(){ testFunc({ {1,2,3,2}, {1,2,2,1}, {3,2,3,2}, {1,2,1,2}, }); return 0; }
20.704545
85
0.642151
vidit1999
57e3b19dad6d500cbd34c4778663bf4ed6443daf
130,234
cpp
C++
Unity-Project/App-HL2/Il2CppOutputProject/Source/il2cppOutput/Il2CppCCWs117.cpp
JBrentJ/mslearn-mixed-reality-and-azure-digital-twins-in-unity
6e13b31a0b053443b9c93267d8f174f1554e79dd
[ "CC-BY-4.0", "MIT" ]
1
2021-06-01T19:33:53.000Z
2021-06-01T19:33:53.000Z
Unity-Project/App-HL2/Il2CppOutputProject/Source/il2cppOutput/Il2CppCCWs117.cpp
JBrentJ/mslearn-mixed-reality-and-azure-digital-twins-in-unity
6e13b31a0b053443b9c93267d8f174f1554e79dd
[ "CC-BY-4.0", "MIT" ]
null
null
null
Unity-Project/App-HL2/Il2CppOutputProject/Source/il2cppOutput/Il2CppCCWs117.cpp
JBrentJ/mslearn-mixed-reality-and-azure-digital-twins-in-unity
6e13b31a0b053443b9c93267d8f174f1554e79dd
[ "CC-BY-4.0", "MIT" ]
null
null
null
#include "pch-cpp.hpp" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include <limits> #include "vm/CachedCCWBase.h" #include "utils/New.h" // UnityEngine.EventSystems.RaycastResult[] struct RaycastResultU5BU5D_t55B9DF597EFA3BE063604C0950E370D850283B9D; // System.Text.Json.ReadStackFrame[] struct ReadStackFrameU5BU5D_tB1A9284204A44718E083DDC3A099B723E2F6763E; // UnityEngine.Rect[] struct RectU5BU5D_tD4F5052A6F89820365269FF4CA7C3EB1ACD4B1EE; // UnityEngine.UI.RectMask2D[] struct RectMask2DU5BU5D_tB3154B58708CFB10CC9FCB6C15301C2EFEAAB2D7; // UnityEngine.RectTransform[] struct RectTransformU5BU5D_tA38C18F6D88709B30F107C43E0669847172879D5; // Newtonsoft.Json.Utilities.ReflectionObject[] struct ReflectionObjectU5BU5D_t5BFC5E4615B234D61E7A5108FC35331A2FCA751F; // System.Text.RegularExpressions.RegexNode[] struct RegexNodeU5BU5D_tDCE5A1DFD56515BBA16233216439F0948F453056; // System.Text.RegularExpressions.RegexOptions[] struct RegexOptionsU5BU5D_t7331675FC2B3783AD45B7A664FB7365174D43C67; // UnityEngine.Renderer[] struct RendererU5BU5D_tE2D3C4350893C593CA40DE876B9F2F0EBBEC49B7; // UnityEngine.AddressableAssets.ResourceLocators.ResourceLocationData[] struct ResourceLocationDataU5BU5D_t1AA66640C35B4DB8F9C452CA4CE7EF141D72E87F; struct IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8; struct IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB; struct IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA; struct IIterator_1_t6A46A7244E5AAD0AE4F2A07AF43DA5052D55F4A4; struct IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C; IL2CPP_EXTERN_C_BEGIN IL2CPP_EXTERN_C_END #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Windows.Foundation.Collections.IIterable`1<System.Collections.IEnumerable> struct NOVTABLE IIterable_1_t6359E278A71A51A15FA83695BA7C54F9B3E04824 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IIterable_1_First_m512126C71D7E9D1C31B56F64455F33E9FEEC89F8(IIterator_1_t6A46A7244E5AAD0AE4F2A07AF43DA5052D55F4A4** comReturnValue) = 0; }; // Windows.Foundation.Collections.IIterable`1<System.Object> struct NOVTABLE IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619(IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C** comReturnValue) = 0; }; // Windows.Foundation.Collections.IVectorView`1<System.Collections.IEnumerable> struct NOVTABLE IVectorView_1_t7215C7C44306F73B6AC4A835AEABA3B0222EA80A : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IVectorView_1_GetAt_m72849F526862E096635BA971A074D9B06ABFEE1E(uint32_t ___index0, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IVectorView_1_get_Size_mB93C08E36F2225BE1862007FAF30C9F2DEE8DAD9(uint32_t* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IVectorView_1_IndexOf_m3D87181F28EC65303ECB5017476C3B38D0944E17(IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8* ___value0, uint32_t* ___index1, bool* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IVectorView_1_GetMany_mE432D0460C5D84FEC9104DF80F5809975EAE32F8(uint32_t ___startIndex0, uint32_t ___items1ArraySize, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8** ___items1, uint32_t* comReturnValue) = 0; }; // Windows.Foundation.Collections.IVectorView`1<System.Object> struct NOVTABLE IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260(uint32_t ___index0, Il2CppIInspectable** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B(uint32_t* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1(uint32_t ___startIndex0, uint32_t ___items1ArraySize, Il2CppIInspectable** ___items1, uint32_t* comReturnValue) = 0; }; // Windows.UI.Xaml.Interop.IBindableIterable struct NOVTABLE IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8 : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) = 0; }; // Windows.UI.Xaml.Interop.IBindableVector struct NOVTABLE IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC : Il2CppIInspectable { static const Il2CppGuid IID; virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) = 0; virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) = 0; virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) = 0; virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) = 0; virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) = 0; virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() = 0; virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() = 0; }; // System.Object // System.Collections.Generic.List`1<UnityEngine.EventSystems.RaycastResult> struct List_1_t367B604D3EA3D6A9EC95A32A521EF83F5DA9B447 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items RaycastResultU5BU5D_t55B9DF597EFA3BE063604C0950E370D850283B9D* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t367B604D3EA3D6A9EC95A32A521EF83F5DA9B447, ____items_1)); } inline RaycastResultU5BU5D_t55B9DF597EFA3BE063604C0950E370D850283B9D* get__items_1() const { return ____items_1; } inline RaycastResultU5BU5D_t55B9DF597EFA3BE063604C0950E370D850283B9D** get_address_of__items_1() { return &____items_1; } inline void set__items_1(RaycastResultU5BU5D_t55B9DF597EFA3BE063604C0950E370D850283B9D* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t367B604D3EA3D6A9EC95A32A521EF83F5DA9B447, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t367B604D3EA3D6A9EC95A32A521EF83F5DA9B447, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t367B604D3EA3D6A9EC95A32A521EF83F5DA9B447, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t367B604D3EA3D6A9EC95A32A521EF83F5DA9B447_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray RaycastResultU5BU5D_t55B9DF597EFA3BE063604C0950E370D850283B9D* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t367B604D3EA3D6A9EC95A32A521EF83F5DA9B447_StaticFields, ____emptyArray_5)); } inline RaycastResultU5BU5D_t55B9DF597EFA3BE063604C0950E370D850283B9D* get__emptyArray_5() const { return ____emptyArray_5; } inline RaycastResultU5BU5D_t55B9DF597EFA3BE063604C0950E370D850283B9D** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(RaycastResultU5BU5D_t55B9DF597EFA3BE063604C0950E370D850283B9D* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<System.Text.Json.ReadStackFrame> struct List_1_t814EF893AA45ADB5DD8897F915DAADC58EBB5CDD : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items ReadStackFrameU5BU5D_tB1A9284204A44718E083DDC3A099B723E2F6763E* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t814EF893AA45ADB5DD8897F915DAADC58EBB5CDD, ____items_1)); } inline ReadStackFrameU5BU5D_tB1A9284204A44718E083DDC3A099B723E2F6763E* get__items_1() const { return ____items_1; } inline ReadStackFrameU5BU5D_tB1A9284204A44718E083DDC3A099B723E2F6763E** get_address_of__items_1() { return &____items_1; } inline void set__items_1(ReadStackFrameU5BU5D_tB1A9284204A44718E083DDC3A099B723E2F6763E* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t814EF893AA45ADB5DD8897F915DAADC58EBB5CDD, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t814EF893AA45ADB5DD8897F915DAADC58EBB5CDD, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t814EF893AA45ADB5DD8897F915DAADC58EBB5CDD, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t814EF893AA45ADB5DD8897F915DAADC58EBB5CDD_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray ReadStackFrameU5BU5D_tB1A9284204A44718E083DDC3A099B723E2F6763E* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t814EF893AA45ADB5DD8897F915DAADC58EBB5CDD_StaticFields, ____emptyArray_5)); } inline ReadStackFrameU5BU5D_tB1A9284204A44718E083DDC3A099B723E2F6763E* get__emptyArray_5() const { return ____emptyArray_5; } inline ReadStackFrameU5BU5D_tB1A9284204A44718E083DDC3A099B723E2F6763E** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(ReadStackFrameU5BU5D_tB1A9284204A44718E083DDC3A099B723E2F6763E* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<UnityEngine.Rect> struct List_1_t7AFC5094F7C1D24DAAA8893B11B1743A7A0D2CFE : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items RectU5BU5D_tD4F5052A6F89820365269FF4CA7C3EB1ACD4B1EE* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t7AFC5094F7C1D24DAAA8893B11B1743A7A0D2CFE, ____items_1)); } inline RectU5BU5D_tD4F5052A6F89820365269FF4CA7C3EB1ACD4B1EE* get__items_1() const { return ____items_1; } inline RectU5BU5D_tD4F5052A6F89820365269FF4CA7C3EB1ACD4B1EE** get_address_of__items_1() { return &____items_1; } inline void set__items_1(RectU5BU5D_tD4F5052A6F89820365269FF4CA7C3EB1ACD4B1EE* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t7AFC5094F7C1D24DAAA8893B11B1743A7A0D2CFE, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t7AFC5094F7C1D24DAAA8893B11B1743A7A0D2CFE, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t7AFC5094F7C1D24DAAA8893B11B1743A7A0D2CFE, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t7AFC5094F7C1D24DAAA8893B11B1743A7A0D2CFE_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray RectU5BU5D_tD4F5052A6F89820365269FF4CA7C3EB1ACD4B1EE* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t7AFC5094F7C1D24DAAA8893B11B1743A7A0D2CFE_StaticFields, ____emptyArray_5)); } inline RectU5BU5D_tD4F5052A6F89820365269FF4CA7C3EB1ACD4B1EE* get__emptyArray_5() const { return ____emptyArray_5; } inline RectU5BU5D_tD4F5052A6F89820365269FF4CA7C3EB1ACD4B1EE** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(RectU5BU5D_tD4F5052A6F89820365269FF4CA7C3EB1ACD4B1EE* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<UnityEngine.UI.RectMask2D> struct List_1_t5709CD2CBFF795FF126CD146B019D4F8EC972EA0 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items RectMask2DU5BU5D_tB3154B58708CFB10CC9FCB6C15301C2EFEAAB2D7* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t5709CD2CBFF795FF126CD146B019D4F8EC972EA0, ____items_1)); } inline RectMask2DU5BU5D_tB3154B58708CFB10CC9FCB6C15301C2EFEAAB2D7* get__items_1() const { return ____items_1; } inline RectMask2DU5BU5D_tB3154B58708CFB10CC9FCB6C15301C2EFEAAB2D7** get_address_of__items_1() { return &____items_1; } inline void set__items_1(RectMask2DU5BU5D_tB3154B58708CFB10CC9FCB6C15301C2EFEAAB2D7* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t5709CD2CBFF795FF126CD146B019D4F8EC972EA0, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t5709CD2CBFF795FF126CD146B019D4F8EC972EA0, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t5709CD2CBFF795FF126CD146B019D4F8EC972EA0, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t5709CD2CBFF795FF126CD146B019D4F8EC972EA0_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray RectMask2DU5BU5D_tB3154B58708CFB10CC9FCB6C15301C2EFEAAB2D7* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t5709CD2CBFF795FF126CD146B019D4F8EC972EA0_StaticFields, ____emptyArray_5)); } inline RectMask2DU5BU5D_tB3154B58708CFB10CC9FCB6C15301C2EFEAAB2D7* get__emptyArray_5() const { return ____emptyArray_5; } inline RectMask2DU5BU5D_tB3154B58708CFB10CC9FCB6C15301C2EFEAAB2D7** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(RectMask2DU5BU5D_tB3154B58708CFB10CC9FCB6C15301C2EFEAAB2D7* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<UnityEngine.RectTransform> struct List_1_t432BA4439FC00E108A9A351BD7FBCD9242270BB3 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items RectTransformU5BU5D_tA38C18F6D88709B30F107C43E0669847172879D5* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t432BA4439FC00E108A9A351BD7FBCD9242270BB3, ____items_1)); } inline RectTransformU5BU5D_tA38C18F6D88709B30F107C43E0669847172879D5* get__items_1() const { return ____items_1; } inline RectTransformU5BU5D_tA38C18F6D88709B30F107C43E0669847172879D5** get_address_of__items_1() { return &____items_1; } inline void set__items_1(RectTransformU5BU5D_tA38C18F6D88709B30F107C43E0669847172879D5* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t432BA4439FC00E108A9A351BD7FBCD9242270BB3, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t432BA4439FC00E108A9A351BD7FBCD9242270BB3, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t432BA4439FC00E108A9A351BD7FBCD9242270BB3, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t432BA4439FC00E108A9A351BD7FBCD9242270BB3_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray RectTransformU5BU5D_tA38C18F6D88709B30F107C43E0669847172879D5* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t432BA4439FC00E108A9A351BD7FBCD9242270BB3_StaticFields, ____emptyArray_5)); } inline RectTransformU5BU5D_tA38C18F6D88709B30F107C43E0669847172879D5* get__emptyArray_5() const { return ____emptyArray_5; } inline RectTransformU5BU5D_tA38C18F6D88709B30F107C43E0669847172879D5** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(RectTransformU5BU5D_tA38C18F6D88709B30F107C43E0669847172879D5* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<Newtonsoft.Json.Utilities.ReflectionObject> struct List_1_t04A11A365D1B0F4481DE8D0B98866FF3448D2190 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items ReflectionObjectU5BU5D_t5BFC5E4615B234D61E7A5108FC35331A2FCA751F* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t04A11A365D1B0F4481DE8D0B98866FF3448D2190, ____items_1)); } inline ReflectionObjectU5BU5D_t5BFC5E4615B234D61E7A5108FC35331A2FCA751F* get__items_1() const { return ____items_1; } inline ReflectionObjectU5BU5D_t5BFC5E4615B234D61E7A5108FC35331A2FCA751F** get_address_of__items_1() { return &____items_1; } inline void set__items_1(ReflectionObjectU5BU5D_t5BFC5E4615B234D61E7A5108FC35331A2FCA751F* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t04A11A365D1B0F4481DE8D0B98866FF3448D2190, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t04A11A365D1B0F4481DE8D0B98866FF3448D2190, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t04A11A365D1B0F4481DE8D0B98866FF3448D2190, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t04A11A365D1B0F4481DE8D0B98866FF3448D2190_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray ReflectionObjectU5BU5D_t5BFC5E4615B234D61E7A5108FC35331A2FCA751F* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t04A11A365D1B0F4481DE8D0B98866FF3448D2190_StaticFields, ____emptyArray_5)); } inline ReflectionObjectU5BU5D_t5BFC5E4615B234D61E7A5108FC35331A2FCA751F* get__emptyArray_5() const { return ____emptyArray_5; } inline ReflectionObjectU5BU5D_t5BFC5E4615B234D61E7A5108FC35331A2FCA751F** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(ReflectionObjectU5BU5D_t5BFC5E4615B234D61E7A5108FC35331A2FCA751F* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<System.Text.RegularExpressions.RegexNode> struct List_1_t692D260BEBA1E69864C98DEEDB3E9256C38CD9B9 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items RegexNodeU5BU5D_tDCE5A1DFD56515BBA16233216439F0948F453056* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t692D260BEBA1E69864C98DEEDB3E9256C38CD9B9, ____items_1)); } inline RegexNodeU5BU5D_tDCE5A1DFD56515BBA16233216439F0948F453056* get__items_1() const { return ____items_1; } inline RegexNodeU5BU5D_tDCE5A1DFD56515BBA16233216439F0948F453056** get_address_of__items_1() { return &____items_1; } inline void set__items_1(RegexNodeU5BU5D_tDCE5A1DFD56515BBA16233216439F0948F453056* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t692D260BEBA1E69864C98DEEDB3E9256C38CD9B9, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t692D260BEBA1E69864C98DEEDB3E9256C38CD9B9, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t692D260BEBA1E69864C98DEEDB3E9256C38CD9B9, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t692D260BEBA1E69864C98DEEDB3E9256C38CD9B9_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray RegexNodeU5BU5D_tDCE5A1DFD56515BBA16233216439F0948F453056* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t692D260BEBA1E69864C98DEEDB3E9256C38CD9B9_StaticFields, ____emptyArray_5)); } inline RegexNodeU5BU5D_tDCE5A1DFD56515BBA16233216439F0948F453056* get__emptyArray_5() const { return ____emptyArray_5; } inline RegexNodeU5BU5D_tDCE5A1DFD56515BBA16233216439F0948F453056** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(RegexNodeU5BU5D_tDCE5A1DFD56515BBA16233216439F0948F453056* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<System.Text.RegularExpressions.RegexOptions> struct List_1_tE931333A40AB4E57F72E00F9F23D19057C78120A : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items RegexOptionsU5BU5D_t7331675FC2B3783AD45B7A664FB7365174D43C67* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_tE931333A40AB4E57F72E00F9F23D19057C78120A, ____items_1)); } inline RegexOptionsU5BU5D_t7331675FC2B3783AD45B7A664FB7365174D43C67* get__items_1() const { return ____items_1; } inline RegexOptionsU5BU5D_t7331675FC2B3783AD45B7A664FB7365174D43C67** get_address_of__items_1() { return &____items_1; } inline void set__items_1(RegexOptionsU5BU5D_t7331675FC2B3783AD45B7A664FB7365174D43C67* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_tE931333A40AB4E57F72E00F9F23D19057C78120A, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_tE931333A40AB4E57F72E00F9F23D19057C78120A, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_tE931333A40AB4E57F72E00F9F23D19057C78120A, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_tE931333A40AB4E57F72E00F9F23D19057C78120A_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray RegexOptionsU5BU5D_t7331675FC2B3783AD45B7A664FB7365174D43C67* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_tE931333A40AB4E57F72E00F9F23D19057C78120A_StaticFields, ____emptyArray_5)); } inline RegexOptionsU5BU5D_t7331675FC2B3783AD45B7A664FB7365174D43C67* get__emptyArray_5() const { return ____emptyArray_5; } inline RegexOptionsU5BU5D_t7331675FC2B3783AD45B7A664FB7365174D43C67** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(RegexOptionsU5BU5D_t7331675FC2B3783AD45B7A664FB7365174D43C67* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<UnityEngine.Renderer> struct List_1_tB73BF10E0869BDB4D391E61BA46B75BECA4DCDBE : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items RendererU5BU5D_tE2D3C4350893C593CA40DE876B9F2F0EBBEC49B7* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_tB73BF10E0869BDB4D391E61BA46B75BECA4DCDBE, ____items_1)); } inline RendererU5BU5D_tE2D3C4350893C593CA40DE876B9F2F0EBBEC49B7* get__items_1() const { return ____items_1; } inline RendererU5BU5D_tE2D3C4350893C593CA40DE876B9F2F0EBBEC49B7** get_address_of__items_1() { return &____items_1; } inline void set__items_1(RendererU5BU5D_tE2D3C4350893C593CA40DE876B9F2F0EBBEC49B7* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_tB73BF10E0869BDB4D391E61BA46B75BECA4DCDBE, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_tB73BF10E0869BDB4D391E61BA46B75BECA4DCDBE, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_tB73BF10E0869BDB4D391E61BA46B75BECA4DCDBE, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_tB73BF10E0869BDB4D391E61BA46B75BECA4DCDBE_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray RendererU5BU5D_tE2D3C4350893C593CA40DE876B9F2F0EBBEC49B7* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_tB73BF10E0869BDB4D391E61BA46B75BECA4DCDBE_StaticFields, ____emptyArray_5)); } inline RendererU5BU5D_tE2D3C4350893C593CA40DE876B9F2F0EBBEC49B7* get__emptyArray_5() const { return ____emptyArray_5; } inline RendererU5BU5D_tE2D3C4350893C593CA40DE876B9F2F0EBBEC49B7** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(RendererU5BU5D_tE2D3C4350893C593CA40DE876B9F2F0EBBEC49B7* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<UnityEngine.AddressableAssets.ResourceLocators.ResourceLocationData> struct List_1_tBDF311CB6BA8AF1C9046A9DAC3502AC9DF88EF55 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items ResourceLocationDataU5BU5D_t1AA66640C35B4DB8F9C452CA4CE7EF141D72E87F* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_tBDF311CB6BA8AF1C9046A9DAC3502AC9DF88EF55, ____items_1)); } inline ResourceLocationDataU5BU5D_t1AA66640C35B4DB8F9C452CA4CE7EF141D72E87F* get__items_1() const { return ____items_1; } inline ResourceLocationDataU5BU5D_t1AA66640C35B4DB8F9C452CA4CE7EF141D72E87F** get_address_of__items_1() { return &____items_1; } inline void set__items_1(ResourceLocationDataU5BU5D_t1AA66640C35B4DB8F9C452CA4CE7EF141D72E87F* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_tBDF311CB6BA8AF1C9046A9DAC3502AC9DF88EF55, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_tBDF311CB6BA8AF1C9046A9DAC3502AC9DF88EF55, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_tBDF311CB6BA8AF1C9046A9DAC3502AC9DF88EF55, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_tBDF311CB6BA8AF1C9046A9DAC3502AC9DF88EF55_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray ResourceLocationDataU5BU5D_t1AA66640C35B4DB8F9C452CA4CE7EF141D72E87F* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_tBDF311CB6BA8AF1C9046A9DAC3502AC9DF88EF55_StaticFields, ____emptyArray_5)); } inline ResourceLocationDataU5BU5D_t1AA66640C35B4DB8F9C452CA4CE7EF141D72E87F* get__emptyArray_5() const { return ____emptyArray_5; } inline ResourceLocationDataU5BU5D_t1AA66640C35B4DB8F9C452CA4CE7EF141D72E87F** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(ResourceLocationDataU5BU5D_t1AA66640C35B4DB8F9C452CA4CE7EF141D72E87F* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif il2cpp_hresult_t IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue); il2cpp_hresult_t IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t ___index0, Il2CppIInspectable** comReturnValue); il2cpp_hresult_t IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t* comReturnValue); il2cpp_hresult_t IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue); il2cpp_hresult_t IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(RuntimeObject* __this, Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue); il2cpp_hresult_t IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t ___index0, Il2CppIInspectable* ___value1); il2cpp_hresult_t IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t ___index0, Il2CppIInspectable* ___value1); il2cpp_hresult_t IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t ___index0); il2cpp_hresult_t IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(RuntimeObject* __this, Il2CppIInspectable* ___value0); il2cpp_hresult_t IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(RuntimeObject* __this); il2cpp_hresult_t IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(RuntimeObject* __this); il2cpp_hresult_t IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C** comReturnValue); il2cpp_hresult_t IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t ___index0, Il2CppIInspectable** comReturnValue); il2cpp_hresult_t IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t* comReturnValue); il2cpp_hresult_t IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67_ComCallableWrapperProjectedMethod(RuntimeObject* __this, Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue); il2cpp_hresult_t IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t ___startIndex0, uint32_t ___items1ArraySize, Il2CppIInspectable** ___items1, uint32_t* comReturnValue); il2cpp_hresult_t IIterable_1_First_m512126C71D7E9D1C31B56F64455F33E9FEEC89F8_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IIterator_1_t6A46A7244E5AAD0AE4F2A07AF43DA5052D55F4A4** comReturnValue); il2cpp_hresult_t IVectorView_1_GetAt_m72849F526862E096635BA971A074D9B06ABFEE1E_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t ___index0, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8** comReturnValue); il2cpp_hresult_t IVectorView_1_get_Size_mB93C08E36F2225BE1862007FAF30C9F2DEE8DAD9_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t* comReturnValue); il2cpp_hresult_t IVectorView_1_IndexOf_m3D87181F28EC65303ECB5017476C3B38D0944E17_ComCallableWrapperProjectedMethod(RuntimeObject* __this, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8* ___value0, uint32_t* ___index1, bool* comReturnValue); il2cpp_hresult_t IVectorView_1_GetMany_mE432D0460C5D84FEC9104DF80F5809975EAE32F8_ComCallableWrapperProjectedMethod(RuntimeObject* __this, uint32_t ___startIndex0, uint32_t ___items1ArraySize, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8** ___items1, uint32_t* comReturnValue); // COM Callable Wrapper for System.Collections.Generic.List`1<UnityEngine.EventSystems.RaycastResult> struct List_1_t367B604D3EA3D6A9EC95A32A521EF83F5DA9B447_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_t367B604D3EA3D6A9EC95A32A521EF83F5DA9B447_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC { inline List_1_t367B604D3EA3D6A9EC95A32A521EF83F5DA9B447_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_t367B604D3EA3D6A9EC95A32A521EF83F5DA9B447_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(2); interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[1] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; *iidCount = 2; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_t367B604D3EA3D6A9EC95A32A521EF83F5DA9B447(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_t367B604D3EA3D6A9EC95A32A521EF83F5DA9B447_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_t367B604D3EA3D6A9EC95A32A521EF83F5DA9B447_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.List`1<System.Text.Json.ReadStackFrame> struct List_1_t814EF893AA45ADB5DD8897F915DAADC58EBB5CDD_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_t814EF893AA45ADB5DD8897F915DAADC58EBB5CDD_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC { inline List_1_t814EF893AA45ADB5DD8897F915DAADC58EBB5CDD_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_t814EF893AA45ADB5DD8897F915DAADC58EBB5CDD_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(2); interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[1] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; *iidCount = 2; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_t814EF893AA45ADB5DD8897F915DAADC58EBB5CDD(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_t814EF893AA45ADB5DD8897F915DAADC58EBB5CDD_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_t814EF893AA45ADB5DD8897F915DAADC58EBB5CDD_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.List`1<UnityEngine.Rect> struct List_1_t7AFC5094F7C1D24DAAA8893B11B1743A7A0D2CFE_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_t7AFC5094F7C1D24DAAA8893B11B1743A7A0D2CFE_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC { inline List_1_t7AFC5094F7C1D24DAAA8893B11B1743A7A0D2CFE_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_t7AFC5094F7C1D24DAAA8893B11B1743A7A0D2CFE_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(2); interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[1] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; *iidCount = 2; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_t7AFC5094F7C1D24DAAA8893B11B1743A7A0D2CFE(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_t7AFC5094F7C1D24DAAA8893B11B1743A7A0D2CFE_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_t7AFC5094F7C1D24DAAA8893B11B1743A7A0D2CFE_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.List`1<UnityEngine.UI.RectMask2D> struct List_1_t5709CD2CBFF795FF126CD146B019D4F8EC972EA0_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_t5709CD2CBFF795FF126CD146B019D4F8EC972EA0_ComCallableWrapper>, IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC, IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A { inline List_1_t5709CD2CBFF795FF126CD146B019D4F8EC972EA0_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_t5709CD2CBFF795FF126CD146B019D4F8EC972EA0_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(4); interfaceIds[0] = IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID; interfaceIds[1] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[2] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; interfaceIds[3] = IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID; *iidCount = 4; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619(IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C** comReturnValue) IL2CPP_OVERRIDE { return IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1(uint32_t ___startIndex0, uint32_t ___items1ArraySize, Il2CppIInspectable** ___items1, uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___startIndex0, ___items1ArraySize, ___items1, comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_t5709CD2CBFF795FF126CD146B019D4F8EC972EA0(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_t5709CD2CBFF795FF126CD146B019D4F8EC972EA0_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_t5709CD2CBFF795FF126CD146B019D4F8EC972EA0_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.List`1<UnityEngine.RectTransform> struct List_1_t432BA4439FC00E108A9A351BD7FBCD9242270BB3_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_t432BA4439FC00E108A9A351BD7FBCD9242270BB3_ComCallableWrapper>, IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4, IIterable_1_t6359E278A71A51A15FA83695BA7C54F9B3E04824, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC, IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A, IVectorView_1_t7215C7C44306F73B6AC4A835AEABA3B0222EA80A { inline List_1_t432BA4439FC00E108A9A351BD7FBCD9242270BB3_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_t432BA4439FC00E108A9A351BD7FBCD9242270BB3_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IIterable_1_t6359E278A71A51A15FA83695BA7C54F9B3E04824::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IIterable_1_t6359E278A71A51A15FA83695BA7C54F9B3E04824*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IVectorView_1_t7215C7C44306F73B6AC4A835AEABA3B0222EA80A::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IVectorView_1_t7215C7C44306F73B6AC4A835AEABA3B0222EA80A*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(6); interfaceIds[0] = IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID; interfaceIds[1] = IIterable_1_t6359E278A71A51A15FA83695BA7C54F9B3E04824::IID; interfaceIds[2] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[3] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; interfaceIds[4] = IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID; interfaceIds[5] = IVectorView_1_t7215C7C44306F73B6AC4A835AEABA3B0222EA80A::IID; *iidCount = 6; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619(IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C** comReturnValue) IL2CPP_OVERRIDE { return IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IIterable_1_First_m512126C71D7E9D1C31B56F64455F33E9FEEC89F8(IIterator_1_t6A46A7244E5AAD0AE4F2A07AF43DA5052D55F4A4** comReturnValue) IL2CPP_OVERRIDE { return IIterable_1_First_m512126C71D7E9D1C31B56F64455F33E9FEEC89F8_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1(uint32_t ___startIndex0, uint32_t ___items1ArraySize, Il2CppIInspectable** ___items1, uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___startIndex0, ___items1ArraySize, ___items1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetAt_m72849F526862E096635BA971A074D9B06ABFEE1E(uint32_t ___index0, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8** comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetAt_m72849F526862E096635BA971A074D9B06ABFEE1E_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_get_Size_mB93C08E36F2225BE1862007FAF30C9F2DEE8DAD9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_get_Size_mB93C08E36F2225BE1862007FAF30C9F2DEE8DAD9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_IndexOf_m3D87181F28EC65303ECB5017476C3B38D0944E17(IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_IndexOf_m3D87181F28EC65303ECB5017476C3B38D0944E17_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetMany_mE432D0460C5D84FEC9104DF80F5809975EAE32F8(uint32_t ___startIndex0, uint32_t ___items1ArraySize, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8** ___items1, uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetMany_mE432D0460C5D84FEC9104DF80F5809975EAE32F8_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___startIndex0, ___items1ArraySize, ___items1, comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_t432BA4439FC00E108A9A351BD7FBCD9242270BB3(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_t432BA4439FC00E108A9A351BD7FBCD9242270BB3_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_t432BA4439FC00E108A9A351BD7FBCD9242270BB3_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.List`1<Newtonsoft.Json.Utilities.ReflectionObject> struct List_1_t04A11A365D1B0F4481DE8D0B98866FF3448D2190_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_t04A11A365D1B0F4481DE8D0B98866FF3448D2190_ComCallableWrapper>, IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC, IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A { inline List_1_t04A11A365D1B0F4481DE8D0B98866FF3448D2190_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_t04A11A365D1B0F4481DE8D0B98866FF3448D2190_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(4); interfaceIds[0] = IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID; interfaceIds[1] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[2] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; interfaceIds[3] = IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID; *iidCount = 4; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619(IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C** comReturnValue) IL2CPP_OVERRIDE { return IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1(uint32_t ___startIndex0, uint32_t ___items1ArraySize, Il2CppIInspectable** ___items1, uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___startIndex0, ___items1ArraySize, ___items1, comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_t04A11A365D1B0F4481DE8D0B98866FF3448D2190(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_t04A11A365D1B0F4481DE8D0B98866FF3448D2190_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_t04A11A365D1B0F4481DE8D0B98866FF3448D2190_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.List`1<System.Text.RegularExpressions.RegexNode> struct List_1_t692D260BEBA1E69864C98DEEDB3E9256C38CD9B9_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_t692D260BEBA1E69864C98DEEDB3E9256C38CD9B9_ComCallableWrapper>, IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC, IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A { inline List_1_t692D260BEBA1E69864C98DEEDB3E9256C38CD9B9_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_t692D260BEBA1E69864C98DEEDB3E9256C38CD9B9_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(4); interfaceIds[0] = IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID; interfaceIds[1] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[2] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; interfaceIds[3] = IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID; *iidCount = 4; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619(IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C** comReturnValue) IL2CPP_OVERRIDE { return IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1(uint32_t ___startIndex0, uint32_t ___items1ArraySize, Il2CppIInspectable** ___items1, uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___startIndex0, ___items1ArraySize, ___items1, comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_t692D260BEBA1E69864C98DEEDB3E9256C38CD9B9(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_t692D260BEBA1E69864C98DEEDB3E9256C38CD9B9_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_t692D260BEBA1E69864C98DEEDB3E9256C38CD9B9_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.List`1<System.Text.RegularExpressions.RegexOptions> struct List_1_tE931333A40AB4E57F72E00F9F23D19057C78120A_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_tE931333A40AB4E57F72E00F9F23D19057C78120A_ComCallableWrapper>, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC { inline List_1_tE931333A40AB4E57F72E00F9F23D19057C78120A_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_tE931333A40AB4E57F72E00F9F23D19057C78120A_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(2); interfaceIds[0] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[1] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; *iidCount = 2; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_tE931333A40AB4E57F72E00F9F23D19057C78120A(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_tE931333A40AB4E57F72E00F9F23D19057C78120A_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_tE931333A40AB4E57F72E00F9F23D19057C78120A_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.List`1<UnityEngine.Renderer> struct List_1_tB73BF10E0869BDB4D391E61BA46B75BECA4DCDBE_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_tB73BF10E0869BDB4D391E61BA46B75BECA4DCDBE_ComCallableWrapper>, IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC, IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A { inline List_1_tB73BF10E0869BDB4D391E61BA46B75BECA4DCDBE_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_tB73BF10E0869BDB4D391E61BA46B75BECA4DCDBE_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(4); interfaceIds[0] = IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID; interfaceIds[1] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[2] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; interfaceIds[3] = IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID; *iidCount = 4; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619(IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C** comReturnValue) IL2CPP_OVERRIDE { return IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1(uint32_t ___startIndex0, uint32_t ___items1ArraySize, Il2CppIInspectable** ___items1, uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___startIndex0, ___items1ArraySize, ___items1, comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_tB73BF10E0869BDB4D391E61BA46B75BECA4DCDBE(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_tB73BF10E0869BDB4D391E61BA46B75BECA4DCDBE_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_tB73BF10E0869BDB4D391E61BA46B75BECA4DCDBE_ComCallableWrapper(obj)); } // COM Callable Wrapper for System.Collections.Generic.List`1<UnityEngine.AddressableAssets.ResourceLocators.ResourceLocationData> struct List_1_tBDF311CB6BA8AF1C9046A9DAC3502AC9DF88EF55_ComCallableWrapper IL2CPP_FINAL : il2cpp::vm::CachedCCWBase<List_1_tBDF311CB6BA8AF1C9046A9DAC3502AC9DF88EF55_ComCallableWrapper>, IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4, IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8, IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC, IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A { inline List_1_tBDF311CB6BA8AF1C9046A9DAC3502AC9DF88EF55_ComCallableWrapper(RuntimeObject* obj) : il2cpp::vm::CachedCCWBase<List_1_tBDF311CB6BA8AF1C9046A9DAC3502AC9DF88EF55_ComCallableWrapper>(obj) {} virtual il2cpp_hresult_t STDCALL QueryInterface(const Il2CppGuid& iid, void** object) IL2CPP_OVERRIDE { if (::memcmp(&iid, &Il2CppIUnknown::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIInspectable::IID, sizeof(Il2CppGuid)) == 0 || ::memcmp(&iid, &Il2CppIAgileObject::IID, sizeof(Il2CppGuid)) == 0) { *object = GetIdentity(); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIManagedObjectHolder::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIManagedObjectHolder*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIMarshal::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIMarshal*>(this); AddRefImpl(); return IL2CPP_S_OK; } if (::memcmp(&iid, &Il2CppIWeakReferenceSource::IID, sizeof(Il2CppGuid)) == 0) { *object = static_cast<Il2CppIWeakReferenceSource*>(this); AddRefImpl(); return IL2CPP_S_OK; } *object = NULL; return IL2CPP_E_NOINTERFACE; } virtual uint32_t STDCALL AddRef() IL2CPP_OVERRIDE { return AddRefImpl(); } virtual uint32_t STDCALL Release() IL2CPP_OVERRIDE { return ReleaseImpl(); } virtual il2cpp_hresult_t STDCALL GetIids(uint32_t* iidCount, Il2CppGuid** iids) IL2CPP_OVERRIDE { Il2CppGuid* interfaceIds = il2cpp_codegen_marshal_allocate_array<Il2CppGuid>(4); interfaceIds[0] = IIterable_1_t64693143CE4E5082C6101BC54B0427C21F3C01C4::IID; interfaceIds[1] = IBindableIterable_tF6BD0C070562CD9C91E3C1B1A5F4667E9C3C74A8::IID; interfaceIds[2] = IBindableVector_tC070A96258CD93818901E9B7808E1A8EFB64B7EC::IID; interfaceIds[3] = IVectorView_1_t9D427951F2D09C2E6F846759B5273E993F185D4A::IID; *iidCount = 4; *iids = interfaceIds; return IL2CPP_S_OK; } virtual il2cpp_hresult_t STDCALL GetRuntimeClassName(Il2CppHString* className) IL2CPP_OVERRIDE { return GetRuntimeClassNameImpl(className); } virtual il2cpp_hresult_t STDCALL GetTrustLevel(int32_t* trustLevel) IL2CPP_OVERRIDE { return ComObjectBase::GetTrustLevel(trustLevel); } virtual il2cpp_hresult_t STDCALL IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619(IIterator_1_tB1AB5AB497E87D6A397AA084D3D3D6B8D211022C** comReturnValue) IL2CPP_OVERRIDE { return IIterable_1_First_m54AC7E778E98ED35C6B7AD98C35C325B8A3DF619_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7(IBindableIterator_tD7550F1144CFBE58090050457A2BE92B1CAEABBB** comReturnValue) IL2CPP_OVERRIDE { return IBindableIterable_First_m91EC6ED0173145266318FDB7F9074798CD766BD7_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetAt_m33D2170810828C01473D9BDC22745A0354FA4FED_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_get_Size_m45347BCD42A1FE180ED2B377BB9C88C7B50CD7D9_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38(IBindableVectorView_tD80A01049DD2609FEA5FACD5E77BF95A875534FA** comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_GetView_m9736FE93BC8979E0CBF8ED26090D1FE54C2E1A38_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IBindableVector_IndexOf_m2F1A64750D19C5A03E9B65880F4A04275E6AABF4_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_SetAt_mD4C84EC02EAD7F636873B77E6D48E7132055A213_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5(uint32_t ___index0, Il2CppIInspectable* ___value1) IL2CPP_OVERRIDE { return IBindableVector_InsertAt_m19A0C885F7C7A7FFA257A46218D7232317E022B5_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, ___value1); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0(uint32_t ___index0) IL2CPP_OVERRIDE { return IBindableVector_RemoveAt_m1AC6E54165809374E91F456B9922A9B24F8652B0_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0); } virtual il2cpp_hresult_t STDCALL IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F(Il2CppIInspectable* ___value0) IL2CPP_OVERRIDE { return IBindableVector_Append_mCA138F8E4026725AC867B607FA63709B6752BB7F_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0); } virtual il2cpp_hresult_t STDCALL IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3() IL2CPP_OVERRIDE { return IBindableVector_RemoveAtEnd_mB3178911995D4CC7BAC0EA43720C1280267E54E3_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF() IL2CPP_OVERRIDE { return IBindableVector_Clear_mEF05B40EFF6D42CBB5A5E336B0946FECE7A4A6EF_ComCallableWrapperProjectedMethod(GetManagedObjectInline()); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260(uint32_t ___index0, Il2CppIInspectable** comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetAt_m38CCDDE1E25317AEF5170D9818FC01816AF34260_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___index0, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B(uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_get_Size_m33BC340C458F20A80A8B07FF4764CEF1F5513F8B_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67(Il2CppIInspectable* ___value0, uint32_t* ___index1, bool* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_IndexOf_mFAE432DA0C1902EEF54AB68CFFD3E2182C443F67_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___value0, ___index1, comReturnValue); } virtual il2cpp_hresult_t STDCALL IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1(uint32_t ___startIndex0, uint32_t ___items1ArraySize, Il2CppIInspectable** ___items1, uint32_t* comReturnValue) IL2CPP_OVERRIDE { return IVectorView_1_GetMany_m6AA46969FB50015EB7107EBCC29E48B7AD4BB6B1_ComCallableWrapperProjectedMethod(GetManagedObjectInline(), ___startIndex0, ___items1ArraySize, ___items1, comReturnValue); } }; IL2CPP_EXTERN_C Il2CppIUnknown* CreateComCallableWrapperFor_List_1_tBDF311CB6BA8AF1C9046A9DAC3502AC9DF88EF55(RuntimeObject* obj) { void* memory = il2cpp::utils::Memory::Malloc(sizeof(List_1_tBDF311CB6BA8AF1C9046A9DAC3502AC9DF88EF55_ComCallableWrapper)); if (memory == NULL) { il2cpp_codegen_raise_out_of_memory_exception(); } return static_cast<Il2CppIManagedObjectHolder*>(new(memory) List_1_tBDF311CB6BA8AF1C9046A9DAC3502AC9DF88EF55_ComCallableWrapper(obj)); }
49.688668
528
0.849571
JBrentJ
57e4487c4befc46e5a1b9538a1355ee1c7cfe0a8
2,090
cc
C++
tests/test_minibus_web.cc
clambassador/minibus
7a9699a53461911b503840b55ac630c894a0bb78
[ "Apache-2.0" ]
1
2019-01-17T15:17:32.000Z
2019-01-17T15:17:32.000Z
tests/test_minibus_web.cc
clambassador/minibus
7a9699a53461911b503840b55ac630c894a0bb78
[ "Apache-2.0" ]
null
null
null
tests/test_minibus_web.cc
clambassador/minibus
7a9699a53461911b503840b55ac630c894a0bb78
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <functional> #include <ncurses.h> #include <sstream> #include <string> #include <vector> #include "minibus/driver/minibus_driver.h" #include "minibus/io/key.h" #include "minibus/web/minibus_web.h" #include "minibus/widgets/close_on_key.h" #include "minibus/widgets/list_select.h" #include "minibus/widgets/text.h" using namespace std; using namespace std::placeholders; using namespace minibus; vector<string> vs; bool decide(ListSelect* ls) { if (!ls) return true; return ls->get_selected(); } class MinibusDriverTest : public MinibusDriver { public: MinibusDriverTest(IDisplay* display, IInput* input) : MinibusDriver(display, input) { vs.push_back("new const"); _ls = new ListSelect("ls", vs); _tx1 = new Text("tx1", "Hello THERE!!"); _tx1->bold(); _tx2 = new Text("tx2", "loading."); _f_pos = _ls->get_selected_pos(); _cur = build_program("main", new CloseOnKey(_tx1)) ->then(new CloseOnKey(_ls)) ->when(new CloseOnKey(_tx1), new CloseOnKey(_tx2), bind(&decide, _ls)) ->loop(nullptr, bind(&decide, nullptr)) ->loop(nullptr, bind(&decide, nullptr))->finish(); } virtual ~MinibusDriverTest() { Logger::error("EXIT"); } protected: virtual void after_keypress(const Key& key, Widget* widget) { if (state(widget, _tx2)) { _tx2->set_text( Logger::stringify("You chose: % (item %)", vs[_ls->get_selected()], _ls->get_selected())); } } virtual bool pos_ready() { if (!_f_pos.valid()) return false; return _f_pos.wait_for(chrono::seconds(0)) == future_status::ready; } ListSelect* _ls; Text* _tx1; Text* _tx2; future<int> _f_pos; }; int main() { vs.push_back("hello"); vs.push_back("there"); vs.push_back("good"); vs.push_back("sir"); Config::_()->load("tests/test.cfg"); MinibusWeb<MinibusDriverTest> mw; WebServer webserver(&mw); webserver.start_server(Config::_()->get("http_port")); cout << Config::_()->get("http_port") << endl; cout << "Running.\nHit enter to stop."; getchar(); webserver.stop_server(); }
24.022989
62
0.664115
clambassador
57e534fb967978afcc9738fe78957e05f949a79e
3,406
cpp
C++
CSES/PrefixSumQueries.cpp
julianferres/Codeforces
ac80292a4d53b8078fc1a85e91db353c489555d9
[ "MIT" ]
4
2020-01-31T15:49:25.000Z
2020-07-07T11:44:03.000Z
CSES/prefix_sum_queries.cpp
julianferres/CodeForces
14e8369e82a2403094183d6f7824201f681c9f65
[ "MIT" ]
null
null
null
CSES/prefix_sum_queries.cpp
julianferres/CodeForces
14e8369e82a2403094183d6f7824201f681c9f65
[ "MIT" ]
null
null
null
/* AUTHOR: julianferres */ #include <bits/stdc++.h> using namespace std; // neal Debugger template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; } template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { os << '{'; string sep; for (const T &x : v) os << sep << x, sep = ", "; return os << '}'; } void dbg_out() { cerr << endl; } template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); } #ifdef LOCAL #define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__) #else #define dbg(...) #endif typedef long long ll; typedef vector<ll> vi; typedef pair<ll,ll> ii; typedef vector<ii> vii; typedef vector<bool> vb; #define FIN ios::sync_with_stdio(0);cin.tie(0);cout.tie(0) #define forr(i, a, b) for(int i = (a); i < (int) (b); i++) #define forn(i, n) forr(i, 0, n) #define DBG(x) cerr << #x << " = " << (x) << endl #define RAYA cerr << "===============================" << endl #define pb push_back #define mp make_pair #define all(c) (c).begin(),(c).end() #define esta(x,c) ((c).find(x) != (c).end()) const int INF = 1e9+15; // const ll INF = 2e18; const int MOD = 1e9+7; // 998244353 const int MAXN = 2e5+5; typedef long long tipo; struct segtree { struct node { tipo ans, l, r; // Poner el neutro del update tipo suma_total; tipo nomatch = 0; // No match en el intervalo de query node base(node aux) {aux.ans = nomatch; aux.suma_total = 0; return aux;} //Poner el neutro de la query void set_node(tipo x, tipo pos) {suma_total = x, ans = max(0LL, x), l = r = pos;}; // Assigment void combine(node a, node b) { suma_total = a.suma_total + b.suma_total; //Operacion de query ans = max(a.ans, a.suma_total + b.ans); l = min(a.l,b.l); r = max(a.r,b.r); } }; vector <node> t; node ask(int p, tipo l, tipo r) { if(l > t[p].r || r < t[p].l) return t[p].base(t[p]); if(l <= t[p].l && t[p].r <= r) return t[p]; node ans; ans.combine(ask(2*p+1,l,r),ask(2*p+2,l,r)); return ans; } void update(int p, tipo pos, tipo val) { if(t[p].r < pos || t[p].l > pos) return; if(t[p].l == t[p].r) { t[p].set_node(val,pos); return; } update(2*p+1, pos, val); update(2*p+2, pos, val); t[p].combine(t[2*p+1], t[2*p+2]); } void build(tipo a, tipo b, int p, vector <tipo> &v) { if(a==b) {t[p].set_node(v[a],a); return;} tipo med=(a+b)/2; build(a, med, 2*p+1, v); build(med+1, b, 2*p+2, v); t[p].combine(t[2*p+1], t[2*p+2]); } node query(tipo l, tipo r) {return ask(0,l,r);} void modificar(tipo pos, tipo val) {update(0,pos,val);} void construir(vector <tipo> &v, int n) { t.resize(4*n); build(0,n-1,0,v); } }; //~ Range Minimum Query with cont int main(){ FIN; int n, q; cin >> n >> q; vi a(n); forn(i, n) cin >> a[i]; segtree st; st.construir(a, n); forn(i, q){ int tipo; cin >> tipo; if(tipo == 1){ int k, u; cin >> k >> u; k--; st.modificar(k, u); } else{ int a, b; cin >> a >> b; a--, b--; cout << st.query(a, b).ans << "\n"; } } return 0; }
33.067961
290
0.548444
julianferres
57e60b13c663fdb02c754af29c1957114ae8f8aa
233
cpp
C++
source/dynamic_value/value_not_found.cpp
diegoarjz/selector
976abd0d9e721639e6314e2599ef7e6f3dafdc4f
[ "MIT" ]
12
2019-04-16T17:35:53.000Z
2020-04-12T14:37:27.000Z
source/dynamic_value/value_not_found.cpp
diegoarjz/selector
976abd0d9e721639e6314e2599ef7e6f3dafdc4f
[ "MIT" ]
47
2019-05-27T15:24:43.000Z
2020-04-27T17:54:54.000Z
source/dynamic_value/value_not_found.cpp
diegoarjz/selector
976abd0d9e721639e6314e2599ef7e6f3dafdc4f
[ "MIT" ]
null
null
null
#include "value_not_found.h" namespace pagoda { ValueNotFoundException::ValueNotFoundException(const std::string &valueName) : Exception("Value with name '" + valueName + "' not found in value table") { } } // namespace pagoda
23.3
79
0.733906
diegoarjz
57eb44abdeb263cef210716a830cab9a64e07624
2,451
cpp
C++
framework/scene_graph/components/orthographic_camera.cpp
NoreChair/Vulkan-Samples
30e0ef953f9492726945d2042400a3808c8408f5
[ "Apache-2.0" ]
2,842
2016-02-16T14:01:31.000Z
2022-03-30T19:10:32.000Z
framework/scene_graph/components/orthographic_camera.cpp
ZandroFargnoli/Vulkan-Samples
04278ed5f0f9847ae6897509eb56d7b21b4e8cde
[ "Apache-2.0" ]
316
2016-02-16T20:41:29.000Z
2022-03-29T02:20:32.000Z
framework/scene_graph/components/orthographic_camera.cpp
ZandroFargnoli/Vulkan-Samples
04278ed5f0f9847ae6897509eb56d7b21b4e8cde
[ "Apache-2.0" ]
504
2016-02-16T16:43:37.000Z
2022-03-31T20:24:35.000Z
/* Copyright (c) 2020, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * * 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 "orthographic_camera.h" VKBP_DISABLE_WARNINGS() #include <glm/gtc/matrix_transform.hpp> VKBP_ENABLE_WARNINGS() namespace vkb { namespace sg { OrthographicCamera::OrthographicCamera(const std::string &name) : Camera{name} {} OrthographicCamera::OrthographicCamera(const std::string &name, float left, float right, float bottom, float top, float near_plane, float far_plane) : Camera{name}, left{left}, right{right}, top{top}, bottom{bottom}, near_plane{near_plane}, far_plane{far_plane} { } void OrthographicCamera::set_left(float new_left) { left = new_left; } float OrthographicCamera::get_left() const { return left; } void OrthographicCamera::set_right(float new_right) { right = new_right; } float OrthographicCamera::get_right() const { return right; } void OrthographicCamera::set_bottom(float new_bottom) { bottom = new_bottom; } float OrthographicCamera::get_bottom() const { return bottom; } void OrthographicCamera::set_top(float new_top) { top = new_top; } float OrthographicCamera::get_top() const { return top; } void OrthographicCamera::set_near_plane(float new_near_plane) { near_plane = new_near_plane; } float OrthographicCamera::get_near_plane() const { return near_plane; } void OrthographicCamera::set_far_plane(float new_far_plane) { far_plane = new_far_plane; } float OrthographicCamera::get_far_plane() const { return far_plane; } glm::mat4 OrthographicCamera::get_projection() { // Note: Using Revsered depth-buffer for increased precision, so Znear and Zfar are flipped return glm::ortho(left, right, bottom, top, far_plane, near_plane); } } // namespace sg } // namespace vkb
22.281818
151
0.712362
NoreChair
57eb7f4b019dcbe6bcb29f2f86ddb9ebd1d408d9
7,893
cpp
C++
auxiliary/generate-blas3-solve-align1.cpp
bollig/viennacl
6dac70e558ed42abe63d8c5bfd08465aafeda859
[ "MIT" ]
1
2020-09-21T08:33:10.000Z
2020-09-21T08:33:10.000Z
auxiliary/generate-blas3-solve-align1.cpp
bollig/viennacl
6dac70e558ed42abe63d8c5bfd08465aafeda859
[ "MIT" ]
null
null
null
auxiliary/generate-blas3-solve-align1.cpp
bollig/viennacl
6dac70e558ed42abe63d8c5bfd08465aafeda859
[ "MIT" ]
null
null
null
/* * Generates BLAS level 3 routines for direct solve */ #include <iostream> #include <fstream> #include <sstream> #include <string> #include <iostream> #include <stdlib.h> //generate code for inplace_solve(op1(A), op2(B), tag) where A and B can have different storage layouts and opX(D) = D or trans(D) void printMatrixMatrixSolve(bool row_major_A, bool row_major_B, bool transpose_A, bool transpose_B, bool upper_solve, bool unit_diagonal) { //write header: std::cout << "// file automatically generated - do not edit!" << std::endl; std::cout << "// inplace solve "; if (transpose_A) std::cout << "A^T \\\\ "; else std::cout << "A \\\\ "; if (transpose_B) std::cout << "B^T" << std::endl; else std::cout << "B" << std::endl; std::cout << "// matrix layouts: "; if (row_major_A) std::cout << "A...row_major, "; else std::cout << "A...col_major, "; if (row_major_B) std::cout << "B...row_major" << std::endl; else std::cout << "B...col_major" << std::endl; //start OpenCL code: std::cout << "__kernel void "; if (transpose_A) std::cout << "trans_"; if (unit_diagonal) std::cout << "unit_"; if (upper_solve) std::cout << "upper_"; else std::cout << "lower_"; if (transpose_B) std::cout << "trans_"; std::cout << "solve"; std::cout << "(" << std::endl; std::cout << " __global const float * A," << std::endl; std::cout << " unsigned int A_start1, unsigned int A_start2," << std::endl; std::cout << " unsigned int A_inc1, unsigned int A_inc2," << std::endl; std::cout << " unsigned int A_size1, unsigned int A_size2," << std::endl; std::cout << " unsigned int A_internal_size1, unsigned int A_internal_size2," << std::endl; std::cout << " __global float * B," << std::endl; std::cout << " unsigned int B_start1, unsigned int B_start2," << std::endl; std::cout << " unsigned int B_inc1, unsigned int B_inc2," << std::endl; std::cout << " unsigned int B_size1, unsigned int B_size2," << std::endl; std::cout << " unsigned int B_internal_size1, unsigned int B_internal_size2)" << std::endl; std::cout << "{ " << std::endl; std::cout << " float temp; " << std::endl; if (upper_solve) { //Note: A is square, thus A_rows == A_cols and no dispatch for transposedness needed std::cout << " for (unsigned int row_cnt = 0; row_cnt < A_size1; ++row_cnt) " << std::endl; std::cout << " { " << std::endl; std::cout << " unsigned int row = A_size1 - 1 - row_cnt;" << std::endl; } else //lower triangular solve { std::cout << " for (unsigned int row = 0; row < A_size1; ++row) " << std::endl; std::cout << " { " << std::endl; } if (!unit_diagonal) { std::cout << " barrier(CLK_GLOBAL_MEM_FENCE); " << std::endl; std::cout << " if (get_local_id(0) == 0) " << std::endl; //Note: A is square, thus A_internal_rows == A_internal_cols and no dispatch for transposedness needed if (row_major_B && transpose_B) std::cout << " B[(get_group_id(0) * B_inc1 + B_start1) * B_internal_size2 + (row * B_inc2 + B_start2)] /= "; else if (row_major_B && !transpose_B) std::cout << " B[(row * B_inc1 + B_start1) * B_internal_size2 + (get_group_id(0) * B_inc2 + B_start2)] /= "; else if (!row_major_B && transpose_B) std::cout << " B[(get_group_id(0) * B_inc1 + B_start1) + (row * B_inc2 + B_start2) * B_internal_size1] /= "; else if (!row_major_B && !transpose_B) std::cout << " B[(row * B_inc1 + B_start1) + (get_group_id(0) * B_inc2 + B_start2) * B_internal_size1] /= "; if (row_major_A) std::cout << "A[(row * A_inc1 + A_start1) * A_internal_size2 + (row * A_inc2 + A_start2)];" << std::endl; else std::cout << "A[(row * A_inc1 + A_start1) + (row * A_inc2 + A_start2)*A_internal_size1];" << std::endl; } std::cout << " barrier(CLK_GLOBAL_MEM_FENCE); " << std::endl; if (row_major_B && transpose_B) std::cout << " temp = B[(get_group_id(0) * B_inc1 + B_start1) * B_internal_size2 + (row * B_inc2 + B_start2)]; " << std::endl; else if (row_major_B && !transpose_B) std::cout << " temp = B[(row * B_inc1 + B_start1) * B_internal_size2 + (get_group_id(0) * B_inc2 + B_start2)]; " << std::endl; else if (!row_major_B && transpose_B) std::cout << " temp = B[(get_group_id(0) * B_inc1 + B_start1) + (row * B_inc2 + B_start2) * B_internal_size1]; " << std::endl; else if (!row_major_B && !transpose_B) std::cout << " temp = B[(row * B_inc1 + B_start1) + (get_group_id(0) * B_inc2 + B_start2) * B_internal_size1]; " << std::endl; std::cout << " //eliminate column of op(A) with index 'row' in parallel: " << std::endl; if (upper_solve) std::cout << " for (unsigned int elim = get_local_id(0); elim < row; elim += get_local_size(0)) " << std::endl; else std::cout << " for (unsigned int elim = row + get_local_id(0) + 1; elim < A_size1; elim += get_local_size(0)) " << std::endl; if (row_major_B && transpose_B) std::cout << " B[(get_group_id(0) * B_inc1 + B_start1) * B_internal_size2 + (elim * B_inc2 + B_start2)] -= temp * "; else if (row_major_B && !transpose_B) std::cout << " B[(elim * B_inc1 + B_start1) * B_internal_size2 + (get_group_id(0) * B_inc2 + B_start2)] -= temp * "; else if (!row_major_B && transpose_B) std::cout << " B[(get_group_id(0) * B_inc1 + B_start1) + (elim * B_inc2 + B_start2) * B_internal_size1] -= temp * "; else if (!row_major_B && !transpose_B) std::cout << " B[(elim * B_inc1 + B_start1) + (get_group_id(0) * B_inc2 + B_start2) * B_internal_size1] -= temp * "; if (row_major_A && transpose_A) std::cout << "A[(row * A_inc1 + A_start1) * A_internal_size2 + (elim * A_inc2 + A_start2)];" << std::endl; else if (row_major_A && !transpose_A) std::cout << "A[(elim * A_inc1 + A_start1) * A_internal_size2 + (row * A_inc2 + A_start2)];" << std::endl; else if (!row_major_A && transpose_A) std::cout << "A[(row * A_inc1 + A_start1) + (elim * A_inc2 + A_start2) * A_internal_size1];" << std::endl; else if (!row_major_A && !transpose_A) std::cout << "A[(elim * A_inc1 + A_start1) + (row * A_inc2 + A_start2) * A_internal_size1];" << std::endl; std::cout << " }" << std::endl; std::cout << "}" << std::endl; } void printUsage() { std::cout << "Must have six parameters for A \\ B:" << std::endl; std::cout << " 0/1 : storage layout for A (column_major/row_major)" << std::endl; std::cout << " 0/1 : storage layout for B (column_major/row_major)" << std::endl; std::cout << " 0/1 : transpose for A (no/yes)" << std::endl; std::cout << " 0/1 : transpose for B (no/yes)" << std::endl; std::cout << " 0/1 : upper triangular system (no/yes)" << std::endl; std::cout << " 0/1 : has unit diagonal (no/yes)" << std::endl; } void readParameter(bool & param, char input) { if (input == '0') param = false; else if (input == '1') param = true; else { printUsage(); exit(EXIT_FAILURE); } } int main(int args, char * argsv[]) { if (args != 7) { printUsage(); exit(EXIT_FAILURE); } //the following flags are 'true' for row_major layout bool layout_A; bool layout_B; readParameter(layout_A, argsv[1][0]); readParameter(layout_B, argsv[2][0]); bool transpose_A; bool transpose_B; readParameter(transpose_A, argsv[3][0]); readParameter(transpose_B, argsv[4][0]); bool upper_solve; bool unit_diagonal; readParameter(upper_solve, argsv[5][0]); readParameter(unit_diagonal, argsv[6][0]); printMatrixMatrixSolve(layout_A, layout_B, transpose_A, transpose_B, upper_solve, unit_diagonal); }
41.109375
133
0.592044
bollig
57ecb6efbd0f4dc142a301c4fb47a828d7f09729
569
cpp
C++
dayOfYear.cpp
jlokhande46/LeetcodeProblems
2023902e392e651f67cf226be1760f43111a3b55
[ "MIT" ]
null
null
null
dayOfYear.cpp
jlokhande46/LeetcodeProblems
2023902e392e651f67cf226be1760f43111a3b55
[ "MIT" ]
null
null
null
dayOfYear.cpp
jlokhande46/LeetcodeProblems
2023902e392e651f67cf226be1760f43111a3b55
[ "MIT" ]
null
null
null
iclass Solution: def dayOfYear(self, date: str) -> int: year=int(date[0:4]) month=int(date[5:7]) day=int(date[8:10]) dayOfYear=day # print(year,day,month) for i in range(month-1): if(i==1): if((year%4==0 and year%100!=0) or (year%400==0)): dayOfYear+=29 else: dayOfYear+=28 elif(i in [0,2,4,6,7,9,11]): dayOfYear+=31 else: dayOfYear+=30 # if() return dayOfYear
28.45
65
0.427065
jlokhande46
57f1b76dc005b240d929f240073585fe1410f9e5
822
cpp
C++
Problem 4/main4.cpp
NickKaparinos/Project-Euler-Solutions
6dbb884a79b01e8b8712ffbb623bcc4d809d3f53
[ "MIT" ]
null
null
null
Problem 4/main4.cpp
NickKaparinos/Project-Euler-Solutions
6dbb884a79b01e8b8712ffbb623bcc4d809d3f53
[ "MIT" ]
null
null
null
Problem 4/main4.cpp
NickKaparinos/Project-Euler-Solutions
6dbb884a79b01e8b8712ffbb623bcc4d809d3f53
[ "MIT" ]
null
null
null
/* Project Euler Problem 4 Nick Kaparinos 2021 */ #include <iostream> #include <string> using namespace std; bool is_palindrome(int number) { string str = to_string(number); int num_iterations = str.size() / 2; for (int i = 0; i <= num_iterations; i++) { if (str[i] != str[str.size() - 1 - i]) { return false; } } return true; } int main(int argc, char *argv[]) { int result = -1; for (int i = 999; i > 1; i--) { for (int j = 999; j > 1; j--) { int product = i * j; if (is_palindrome(product)) { if (product > result) { result = product; } } if (product <= result) { break; } } } cout << result << endl; }
18.681818
48
0.454988
NickKaparinos
57f3abd46a69814ddfdfd384134f2e86e414f8d1
1,373
cpp
C++
ui-qt/LearningDialog/Learning.cpp
qianyongjun123/FPGA-Industrial-Smart-Camera
54b3e2c2661cf7f6774a7fb4d6ae637fa73cba32
[ "MIT" ]
1
2017-12-28T08:08:02.000Z
2017-12-28T08:08:02.000Z
ui-qt/LearningDialog/Learning.cpp
qianyongjun123/FPGA-Industrial-Smart-Camera
54b3e2c2661cf7f6774a7fb4d6ae637fa73cba32
[ "MIT" ]
null
null
null
ui-qt/LearningDialog/Learning.cpp
qianyongjun123/FPGA-Industrial-Smart-Camera
54b3e2c2661cf7f6774a7fb4d6ae637fa73cba32
[ "MIT" ]
3
2017-12-28T08:08:05.000Z
2021-11-12T07:59:13.000Z
#include "Learning.h" #include "ui_Learning.h" #include <QSettings> #include <QDebug> #if _MSC_VER >= 1600 #pragma execution_character_set("utf-8") #endif Learning::Learning(QWidget *parent) : QDialog(parent), ui(new Ui::Learning) { ui->setupUi(this); this->move(272,520); this->setWindowFlags(Qt::WindowTitleHint); m_Timer = new QTimer; connect(m_Timer,&QTimer::timeout,this,&Learning::TimerSlot); ui->pushButton->setVisible(false); m_Timer->start(200); } Learning::~Learning() { delete ui; } /** * @brief Learning::on_pushButton_clicked * @author dgq * @note OK按钮响应函数 */ void Learning::on_pushButton_clicked() { QDialog::reject(); } /** * @brief Learning::SetResultString * @param code_str * @author dgq * @note 设置取样结果信息 */ void Learning::SetResultString(QString code_str) { ui->pushButton->setVisible(true); m_Timer->stop(); m_rst_Str = code_str; ui->textBrowser->setText(code_str); ui->progressBar->setValue(100); } /** * @brief Learning::TimerSlot * @author dgq * @note 刷新进度条的定时器响应函数 */ void Learning::TimerSlot() { // qDebug()<<"ui->progressBar->value() =="<<ui->progressBar->value(); if(ui->progressBar->value() < 99) ui->progressBar->setValue(ui->progressBar->value()+1); else { m_Timer->stop(); ui->textBrowser->setText(tr("取样超时!")); } }
19.898551
72
0.648216
qianyongjun123
57f876e6f245324c90ff20460666832b75390b2e
427
cpp
C++
timus/1880.cpp
y-wan/OJ
5dea140dbaaec98e440ad4b1c10fa5072f1ceea7
[ "MIT" ]
null
null
null
timus/1880.cpp
y-wan/OJ
5dea140dbaaec98e440ad4b1c10fa5072f1ceea7
[ "MIT" ]
null
null
null
timus/1880.cpp
y-wan/OJ
5dea140dbaaec98e440ad4b1c10fa5072f1ceea7
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <map> using namespace std; map<int, int> dict; int main() { int a, tmp, kase = 0, res = 0; while (cin >> a) { kase++; for (int i = 0; i < a; i++) { cin >> tmp; if (!dict.count(tmp)) dict[tmp] = 1; else dict[tmp]++; } } for (map<int, int>::iterator it = dict.begin(); it != dict.end(); it++) if (it->second == kase) res++; cout << res << endl; return 0; }
18.565217
72
0.540984
y-wan
520605250313984057f9925718623df850d46c51
311
cpp
C++
ch0105/ch0105_07.cpp
sun1218/openjudge
07e44235fc6ac68bf8e8125577dcd008b08d59ec
[ "MIT" ]
null
null
null
ch0105/ch0105_07.cpp
sun1218/openjudge
07e44235fc6ac68bf8e8125577dcd008b08d59ec
[ "MIT" ]
null
null
null
ch0105/ch0105_07.cpp
sun1218/openjudge
07e44235fc6ac68bf8e8125577dcd008b08d59ec
[ "MIT" ]
1
2021-05-16T13:36:06.000Z
2021-05-16T13:36:06.000Z
#include <iostream> #include <cstdio> using namespace std; int main(void){ int n,x=0,y=0,z=0,c=0; scanf("%d",&n); for(int i = 0;i<n;i++){ int temp1,temp2,temp3; scanf("%d%d%d",&temp1,&temp2,&temp3); x += temp1; y += temp2; z += temp3; } c += (x+y+z); printf("%d %d %d %d",x,y,z,c); return 0; }
17.277778
39
0.546624
sun1218
5206522abfa144bbf6f920469aa768667566b9bc
4,006
hpp
C++
modules/dnn/src/cuda/functors.hpp
artun3e/opencv
524a2fffe96195b906a95b548b0a185d3251eb7e
[ "BSD-3-Clause" ]
4
2020-06-29T20:14:08.000Z
2020-12-12T20:04:25.000Z
modules/dnn/src/cuda/functors.hpp
artun3e/opencv
524a2fffe96195b906a95b548b0a185d3251eb7e
[ "BSD-3-Clause" ]
null
null
null
modules/dnn/src/cuda/functors.hpp
artun3e/opencv
524a2fffe96195b906a95b548b0a185d3251eb7e
[ "BSD-3-Clause" ]
1
2022-01-19T15:08:40.000Z
2022-01-19T15:08:40.000Z
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. #ifndef OPENCV_DNN_SRC_CUDA_FUNCTORS_HPP #define OPENCV_DNN_SRC_CUDA_FUNCTORS_HPP #include <cuda_runtime.h> #include "math.hpp" namespace cv { namespace dnn { namespace cuda4dnn { namespace kernels { template <class T> struct abs_functor { __device__ T operator()(T value) { using csl::device::abs; return abs(value); } }; template <class T> struct tanh_functor { __device__ T operator()(T value) { using csl::device::tanh; return tanh(value); } }; template <class T> struct swish_functor { __device__ T operator()(T value) { // f(x) = x * sigmoid(x) using csl::device::fast_divide; using csl::device::fast_exp; return fast_divide(value, static_cast<T>(1) + fast_exp(-value)); } }; template <class T> struct mish_functor { __device__ T operator()(T value) { using csl::device::tanh; using csl::device::log1pexp; return value * tanh(log1pexp(value)); } }; template <> struct mish_functor<float> { __device__ float operator()(float value) { // f(x) = x * tanh(log1pexp(x)); using csl::device::fast_divide; using csl::device::fast_exp; auto e = fast_exp(value); auto n = e * e + 2 * e; if (value <= -0.6f) return value * fast_divide(n, n + 2); return value - 2 * fast_divide(value, n + 2); } }; #if !defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 530) template <> struct mish_functor<__half> { __device__ __half operator()(__half value) { return mish_functor<float>()(value); } }; #endif template <class T> struct sigmoid_functor { __device__ T operator()(T value) { using csl::device::fast_sigmoid; return fast_sigmoid(value); } }; template <class T> struct bnll_functor { __device__ T operator()(T value) { using csl::device::log1pexp; return value > T(0) ? value + log1pexp(-value) : log1pexp(value); } }; template <class T> struct elu_functor { __device__ T operator()(T value) { using csl::device::expm1; return value >= T(0) ? value : expm1(value); } }; template <class T> struct relu_functor { __device__ relu_functor(T slope_) : slope{slope_} { } __device__ T operator()(T value) { using csl::device::log1pexp; return value >= T(0) ? value : slope * value; } T slope; }; template <class T> struct clipped_relu_functor { __device__ clipped_relu_functor(T floor_, T ceiling_) : floor{floor_}, ceiling{ceiling_} { } __device__ T operator()(T value) { using csl::device::clamp; return clamp(value, floor, ceiling); } T floor, ceiling; }; template <class T> struct power_functor { __device__ power_functor(T exp_, T scale_, T shift_) : exp{exp_}, scale{scale_}, shift{shift_} { } __device__ T operator()(T value) { using csl::device::pow; return pow(shift + scale * value, exp); } T exp, scale, shift; }; template <class T> struct max_functor { __device__ T operator()(T x, T y) { using csl::device::max; return max(x, y); } }; template <class T> struct sum_functor { __device__ T operator()(T x, T y) { return x + y; } }; template <class T> struct scaled_sum_functor { __device__ scaled_sum_functor(T scale_x_, T scale_y_) : scale_x{scale_x_}, scale_y{scale_y_} { } __device__ T operator()(T x, T y) { return scale_x * x + scale_y * y; } T scale_x, scale_y; }; template <class T> struct product_functor { __device__ T operator()(T x, T y) { return x * y; } }; template <class T> struct div_functor { __device__ T operator()(T x, T y) { return x / y; } }; }}}} /* namespace cv::dnn::cuda4dnn::kernels */ #endif /* OPENCV_DNN_SRC_CUDA_FUNCTORS_HPP */
24.278788
102
0.629056
artun3e
52093ff0013f1a3c41a541c5edcf5e3dfc562a3b
11,016
hpp
C++
Lib-Core/include/skipifzero_pool.hpp
PetorSFZ/sfz_tech
0d4027ad2c2bb444b83e78f009b649478cb97a73
[ "Zlib" ]
2
2020-09-04T16:52:47.000Z
2021-04-21T18:30:25.000Z
Lib-Core/include/skipifzero_pool.hpp
PetorSFZ/sfz_tech
0d4027ad2c2bb444b83e78f009b649478cb97a73
[ "Zlib" ]
null
null
null
Lib-Core/include/skipifzero_pool.hpp
PetorSFZ/sfz_tech
0d4027ad2c2bb444b83e78f009b649478cb97a73
[ "Zlib" ]
null
null
null
// Copyright (c) Peter Hillerström (skipifzero.com, [email protected]) // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. #ifndef SKIPIFZERO_POOL_HPP #define SKIPIFZERO_POOL_HPP #pragma once #include <new> #include "skipifzero.hpp" namespace sfz { // PoolSlot // ------------------------------------------------------------------------------------------------ constexpr u8 POOL_SLOT_ACTIVE_BIT_MASK = u8(0x80); constexpr u8 POOL_SLOT_VERSION_MASK = u8(0x7F); // Represents meta data about a slot in a Pool's value array. // // The first 7 bits stores the version of the slot. Each time the slot is "allocated" the version // is increased. When it reaches 128 it wraps around to 1. Versions are in range [1, 127], 0 is // reserved as invalid. // // The 8th bit is the "active" bit, i.e. whether the slot is currently in use (allocated) or not. struct PoolSlot final { u8 bits; u8 version() const { return bits & POOL_SLOT_VERSION_MASK; } bool active() const { return (bits & POOL_SLOT_ACTIVE_BIT_MASK) != u8(0); } }; static_assert(sizeof(PoolSlot) == 1, "PoolSlot is padded"); // Pool // ------------------------------------------------------------------------------------------------ constexpr u32 POOL_MAX_CAPACITY = 1u << SFZ_HANDLE_INDEX_NUM_BITS; // An sfz::Pool is a datastructure that is somewhat a mix between an array, an allocator and the // entity allocation part of an ECS system. Basically, it's an array from which you allocate // slots from. The array can have holes where you have deallocated objects. Each slot have an // associated version number so stale handles can't be used when a slot has been deallocated and // then allocated again. // // It is more of a low-level datastructure than either sfz::Array or sfz::HashMap, it is not as // general purpose as either of those. The following restrictions apply: // // * Will only call destructors when the entire pool is destroyed. When deallocating a slot it // will be set to "{}", or a user-defined value. The type must support this. // * Does not support resize, capacity must be specified in advance. // * Pointers are guaranteed stable because values are never moved/copied, due to above. // * There is no "_Local" variant, because then pointers would not be stable. // // It's possible to manually (and efficiently) iterate over the contents of a Pool. Example: // // T* values = pool.data(); // const PoolSlot* slots = pool.slots(); // const u32 arraySize = pool.arraySize(); // for (u32 idx = 0; idx < arraySize; idx++) { // PoolSlot slot = slots[idx]; // T& value = values[idx]; // // "value" will always be initialized here, but depending on your use case it's probably // // a bug to read/write to it. Mostly you will want to do the active check shown below. // if (!slot.active()) continue; // // Now value should be guaranteed safe to use regardless of your use case // } // // A Pool will never "shrink", i.e. arraySize() will never return a smaller value than before until // you destroy() the pool completely. template<typename T> class Pool final { public: SFZ_DECLARE_DROP_TYPE(Pool); explicit Pool(u32 capacity, SfzAllocator* allocator, SfzDbgInfo allocDbg) noexcept { this->init(capacity, allocator, allocDbg); } // State methods // -------------------------------------------------------------------------------------------- void init(u32 capacity, SfzAllocator* allocator, SfzDbgInfo allocDbg) { sfz_assert(capacity != 0); // We don't support resize, so this wouldn't make sense. sfz_assert(capacity <= POOL_MAX_CAPACITY); sfz_assert(alignof(T) <= 32); // Destroy previous pool this->destroy(); // Calculate offsets, allocate memory and clear it const u32 alignment = 32; const u32 slotsOffset = u32(roundUpAligned(sizeof(T) * capacity, alignment)); const u32 freeIndicesOffset = slotsOffset + u32(roundUpAligned(sizeof(PoolSlot) * capacity, alignment)); const u32 numBytesNeeded = freeIndicesOffset + u32(roundUpAligned(sizeof(u32) * capacity, alignment)); u8* memory = reinterpret_cast<u8*>( allocator->alloc(allocDbg, numBytesNeeded, alignment)); memset(memory, 0, numBytesNeeded); // Set members mAllocator = allocator; mCapacity = capacity; mData = reinterpret_cast<T*>(memory); mSlots = reinterpret_cast<PoolSlot*>(memory + slotsOffset); mFreeIndices = reinterpret_cast<u32*>(memory + freeIndicesOffset); } void destroy() { if (mData != nullptr) { // Only call destructors if T is not trivially destructible if constexpr (!std::is_trivially_destructible_v<T>) { for (u32 i = 0; i < mArraySize; i++) { mData[i].~T(); } } mAllocator->dealloc(mData); } mNumAllocated = 0; mArraySize = 0; mCapacity = 0; mData = nullptr; mSlots = nullptr; mFreeIndices = nullptr; mAllocator = nullptr; } // Getters // -------------------------------------------------------------------------------------------- u32 numAllocated() const { return mNumAllocated; } u32 numHoles() const { return mArraySize - mNumAllocated; } u32 arraySize() const { return mArraySize; } u32 capacity() const { return mCapacity; } bool isFull() const { return mNumAllocated >= mCapacity; } const T* data() const { return mData; } T* data() { return mData; } const PoolSlot* slots() const { return mSlots; } SfzAllocator* allocator() const { return mAllocator; } PoolSlot getSlot(u32 idx) const { sfz_assert(idx < mArraySize); return mSlots[idx]; } u8 getVersion(u32 idx) const { sfz_assert(idx < mArraySize); return mSlots[idx].version(); } bool slotIsActive(u32 idx) const { sfz_assert(idx < mArraySize); return mSlots[idx].active(); } bool handleIsValid(SfzHandle handle) const { const u32 idx = handle.idx(); if (idx >= mArraySize) return false; PoolSlot slot = mSlots[idx]; if (!slot.active()) return false; if (handle.version() != slot.version()) return false; sfz_assert(slot.version() != u8(0)); return true; } T* get(SfzHandle handle) { const u8 version = handle.version(); const u32 idx = handle.idx(); if (idx >= mArraySize) return nullptr; PoolSlot slot = mSlots[idx]; if (slot.version() != version) return nullptr; if (!slot.active()) return nullptr; return &mData[idx]; } const T* get(SfzHandle handle) const { return const_cast<Pool<T>*>(this)->get(handle); } T& operator[] (SfzHandle handle) { T* v = get(handle); sfz_assert(v != nullptr); return *v; } const T& operator[] (SfzHandle handle) const { return (*const_cast<Pool<T>*>(this))[handle]; } // Methods // -------------------------------------------------------------------------------------------- SfzHandle allocate() { return allocateImpl<T>({}); } SfzHandle allocate(const T& value) { return allocateImpl<const T&>(value); } SfzHandle allocate(T&& value) { return allocateImpl<T>(sfz_move(value)); } void deallocate(SfzHandle handle) { return deallocateImpl<T>(handle, {}); } void deallocate(SfzHandle handle, const T& emptyValue) { return deallocateImpl<const T&>(handle, emptyValue); } void deallocate(SfzHandle handle, T&& emptyValue) { return deallocateImpl<T>(handle, sfz_move(emptyValue)); } void deallocate(u32 idx) { return deallocateImpl<T>(idx, {}); } void deallocate(u32 idx, const T& emptyValue) { return deallocateImpl<const T&>(idx, emptyValue); } void deallocate(u32 idx, T&& emptyValue) { return deallocateImpl<T>(idx, sfz_move(emptyValue)); } private: // Private methods // -------------------------------------------------------------------------------------------- // Perfect forwarding: const reference: ForwardT == const T&, rvalue: ForwardT == T // std::forward<ForwardT>(value) will then return the correct version of value template<typename ForwardT> SfzHandle allocateImpl(ForwardT&& value) { sfz_assert(mNumAllocated < mCapacity); // Different path depending on if there are holes or not const u32 holes = numHoles(); u32 idx = ~0u; if (holes > 0) { idx = mFreeIndices[holes - 1]; mFreeIndices[holes - 1] = 0; // If we are reusing a slot the memory should already be constructed, therefore we // should use move/copy assignment in order to make sure we don't skip running a // destructor. mData[idx] = sfz_forward(value); } else { idx = mArraySize; mArraySize += 1; // First time we are using this slot, memory is uninitialized and need to be // initialized before usage. Therefore use placement new move/copy constructor. new (mData + idx) T(sfz_forward(value)); } // Update number of allocated mNumAllocated += 1; sfz_assert(idx < mArraySize); sfz_assert(mArraySize <= mCapacity); sfz_assert(mNumAllocated <= mArraySize); // Update active bit and version in slot PoolSlot& slot = mSlots[idx]; sfz_assert(!slot.active()); u8 newVersion = slot.bits + 1; if (newVersion > 127) newVersion = 1; slot.bits = POOL_SLOT_ACTIVE_BIT_MASK | newVersion; // Create and return handle SfzHandle handle = SfzHandle::create(idx, newVersion); return handle; } template<typename ForwardT> void deallocateImpl(SfzHandle handle, ForwardT&& emptyValue) { const u32 idx = handle.idx(); sfz_assert(idx < mArraySize); sfz_assert(handle.version() == getVersion(idx)); deallocateImpl<ForwardT>(idx, sfz_forward(emptyValue)); } template<typename ForwardT> void deallocateImpl(u32 idx, ForwardT&& emptyValue) { sfz_assert(mNumAllocated > 0); sfz_assert(idx < mArraySize); PoolSlot& slot = mSlots[idx]; sfz_assert(slot.active()); sfz_assert(slot.version() != 0); // Set version and empty value slot.bits = slot.version(); // Remove active bit mData[idx] = sfz_forward(emptyValue); mNumAllocated -= 1; // Store the new hole in free indices const u32 holes = numHoles(); sfz_assert(holes > 0); mFreeIndices[holes - 1] = idx; } // Private members // -------------------------------------------------------------------------------------------- u32 mNumAllocated = 0; u32 mArraySize = 0; u32 mCapacity = 0; T* mData = nullptr; PoolSlot* mSlots = nullptr; u32* mFreeIndices = nullptr; SfzAllocator* mAllocator = nullptr; }; } // namespace sfz #endif
36.842809
112
0.662763
PetorSFZ
5209f798b0fdddaf2e99a1830c64686aeb7cab41
1,278
hpp
C++
android-31/android/widget/FrameLayout.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/widget/FrameLayout.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/widget/FrameLayout.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../view/ViewGroup.hpp" namespace android::content { class Context; } namespace android::view { class ViewGroup_LayoutParams; } namespace android::widget { class FrameLayout_LayoutParams; } class JString; namespace android::widget { class FrameLayout : public android::view::ViewGroup { public: // Fields // QJniObject forward template<typename ...Ts> explicit FrameLayout(const char *className, const char *sig, Ts...agv) : android::view::ViewGroup(className, sig, std::forward<Ts>(agv)...) {} FrameLayout(QJniObject obj); // Constructors FrameLayout(android::content::Context arg0); FrameLayout(android::content::Context arg0, JObject arg1); FrameLayout(android::content::Context arg0, JObject arg1, jint arg2); FrameLayout(android::content::Context arg0, JObject arg1, jint arg2, jint arg3); // Methods android::widget::FrameLayout_LayoutParams generateLayoutParams(JObject arg0) const; JString getAccessibilityClassName() const; jboolean getConsiderGoneChildrenWhenMeasuring() const; jboolean getMeasureAllChildren() const; void setForegroundGravity(jint arg0) const; void setMeasureAllChildren(jboolean arg0) const; jboolean shouldDelayChildPressedState() const; }; } // namespace android::widget
27.191489
169
0.758216
YJBeetle
520a20b05947e2ceb5ade199cb60f9b86fe1dd4a
277
hpp
C++
include/RED4ext/Scripting/Natives/Generated/quest/VisionModeType.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/quest/VisionModeType.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/quest/VisionModeType.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> namespace RED4ext { namespace quest { enum class VisionModeType : uint32_t { Undefined = 0, FocusMode = 1, EnhancedMode = 2, }; } // namespace quest } // namespace RED4ext
16.294118
57
0.696751
jackhumbert
520a7d315c017eb83cd8c8537513b82b64f44da7
277
cpp
C++
Source/Client/Main.cpp
chahoseong/TinyHippo
7153849337944f0459dfd24551f28e417314e2de
[ "Unlicense" ]
1
2019-09-10T06:32:07.000Z
2019-09-10T06:32:07.000Z
Source/Client/Main.cpp
chahoseong/TinyHippo
7153849337944f0459dfd24551f28e417314e2de
[ "Unlicense" ]
null
null
null
Source/Client/Main.cpp
chahoseong/TinyHippo
7153849337944f0459dfd24551f28e417314e2de
[ "Unlicense" ]
null
null
null
#include "stdafx.h" #include "Engine/GameMain.h" int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { return TinyHippo::GameMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow); }
27.7
75
0.732852
chahoseong
648c4345060f1628043a76e0230041d398586b45
1,388
cp
C++
validation/default/golomb4-salldiff-reverse.cp
kad15/SandBoxToulbar2
31430ec5e6c6cec1eabe6f5d04bfb8134777821c
[ "MIT" ]
33
2018-08-16T18:14:35.000Z
2022-03-14T10:26:18.000Z
validation/default/golomb4-salldiff-reverse.cp
kad15/SandBoxToulbar2
31430ec5e6c6cec1eabe6f5d04bfb8134777821c
[ "MIT" ]
13
2018-08-09T06:53:08.000Z
2022-03-28T10:26:24.000Z
validation/default/golomb4-salldiff-reverse.cp
kad15/SandBoxToulbar2
31430ec5e6c6cec1eabe6f5d04bfb8134777821c
[ "MIT" ]
12
2018-06-06T15:19:46.000Z
2022-02-11T17:09:27.000Z
# problem name and initial upper bound GOLOMB_4_ALLDIFF_REVERSE 9 # variables for marks g4 0 1 2 3 4 5 6 7 8 g3 0 1 2 3 4 5 6 7 8 g2 0 1 2 3 4 5 6 7 8 g1 0 1 2 3 4 5 6 7 8 # variables for mark differences d3_4 0 1 2 3 4 5 6 7 8 d2_4 0 1 2 3 4 5 6 7 8 d2_3 0 1 2 3 4 5 6 7 8 d1_4 0 1 2 3 4 5 6 7 8 d1_3 0 1 2 3 4 5 6 7 8 d1_2 0 1 2 3 4 5 6 7 8 # optimization criterion: minimizes the last mark g4 # channeling constraints to express mark differences shared(hard(d1_2 == g2 - g1)) d1_3 g3 g1 defined by 1 d1_4 g4 g1 defined by 1 d2_3 g3 g2 defined by 1 d2_4 g4 g2 defined by 1 d3_4 g4 g3 defined by 1 # AllDifferent constraint on mark differences # equivalent to: hard(alldiff(d1_2,d1_3,d1_4,d2_3,d2_4,d3_4)) d1_2 d1_3 d1_4 d2_3 d2_4 d3_4 -1 salldiff var -1 # first mark is fixed hard(g1 == 0) # g variables must be strictly increasing shared(hard(d1_2 > 0)) d1_3 defined by 2 d1_4 defined by 2 d2_3 defined by 2 d2_4 defined by 2 d3_4 defined by 2 # breaking symmetries # equivalent to: hard(g2 < d3_4) g2 d3_4 -1 < 0 0 # redundant constraints # equivalent to: hard(g4 >= d1_2 + 3) g4 d1_2 -1 >= 3 0 # equivalent to: hard(g4 >= d1_3 + 1) g4 d1_3 -1 >= 1 0 # equivalent to: hard(g4 >= d1_4 + 0) g4 d1_4 -1 >= 0 0 # equivalent to: hard(g4 >= d2_3 + 3) g4 d2_3 -1 >= 3 0 # equivalent to: hard(g4 >= d2_4 + 1) g4 d2_4 -1 >= 1 0 # equivalent to: hard(g4 >= d3_4 + 3) g4 d3_4 -1 >= 3 0
22.754098
61
0.680115
kad15
648e5e816650f95b804c9b0220db80da664770ce
1,891
cc
C++
examples/pulse_compression.cc
ShaneFlandermeyer/plasma-dsp
50d969f3873052a582e2b17745c469a8d22f0fe1
[ "MIT" ]
null
null
null
examples/pulse_compression.cc
ShaneFlandermeyer/plasma-dsp
50d969f3873052a582e2b17745c469a8d22f0fe1
[ "MIT" ]
7
2022-01-12T19:04:37.000Z
2022-01-16T15:07:41.000Z
examples/pulse_compression.cc
ShaneFlandermeyer/plasma-dsp
50d969f3873052a582e2b17745c469a8d22f0fe1
[ "MIT" ]
null
null
null
#include "linear_fm_waveform.h" #include "pulse_doppler.h" #include <matplot/matplot.h> using namespace matplot; using namespace plasma; using namespace Eigen; int main() { // Waveform parameter double B = 50e6; double fs = 4 * B; double ts = 1 / fs; double Tp = 5e-6; double prf = 20e3; LinearFMWaveform wave(B, Tp, prf, fs); VectorXcd x = wave.waveform(); // Target parameters double range = 1e3; double tau = 2 * range / physconst::c; VectorXcd y; // = delay(x,5e-6,(size_t)(fs/prf),fs); VectorXcd h = wave.MatchedFilter(); size_t num_samps_pri = (int)(fs / prf); size_t num_range_bins = num_samps_pri + h.size() - 1; size_t num_pulses = 32; MatrixXcd fast_time_slow_time = MatrixXcd::Zero(num_samps_pri, num_pulses); MatrixXcd range_pulse_map = MatrixXcd::Zero(num_range_bins, num_pulses); MatrixXcd range_doppler_map = MatrixXcd::Zero(num_range_bins, num_pulses); for (size_t m = 0; m < num_pulses; m++) { y = delay(x, tau, num_samps_pri, fs); // TODO: Add a scale factor fast_time_slow_time.col(m) = y; range_pulse_map.col(m) = conv(y, h); } // Range doppler map range_doppler_map = fftshift(fft(range_pulse_map, 1), 1); // Convert the Eigen matrix to a vector of vectors figure(); std::vector<std::vector<double>> xv( range_doppler_map.rows(), std::vector<double>(range_doppler_map.cols())); for (size_t i = 0; i < xv.size(); i++) { for (size_t j = 0; j < xv.front().size(); j++) { xv[i][j] = abs(range_doppler_map(i, j)); } } // Plot the range doppler map double ti = 0; double min_range = physconst::c / 2 * (ts - Tp + ti); double max_range = physconst::c / 2 * (ts*(num_range_bins-1) - Tp + ti); double min_doppler = -prf / 2; double max_doppler = prf / 2 - 1 / (double)num_pulses; imagesc(min_doppler, max_doppler, min_range, max_range, xv); show(); return 0; }
30.5
79
0.659439
ShaneFlandermeyer
648ec7580476982f69f82de1f20af95c502a408a
2,694
cpp
C++
tests/Bootstrap.Tests/tests/TimerServiceTests.cpp
samcragg/Autocrat
179e0b42ddd3ecbf75467e479cd8f2f6c67c82ec
[ "MIT" ]
null
null
null
tests/Bootstrap.Tests/tests/TimerServiceTests.cpp
samcragg/Autocrat
179e0b42ddd3ecbf75467e479cd8f2f6c67c82ec
[ "MIT" ]
2
2020-09-30T07:09:46.000Z
2021-01-03T20:01:02.000Z
tests/Bootstrap.Tests/tests/TimerServiceTests.cpp
samcragg/Autocrat
179e0b42ddd3ecbf75467e479cd8f2f6c67c82ec
[ "MIT" ]
null
null
null
#include "timer_service.h" #include <chrono> #include <gtest/gtest.h> #include <cpp_mock.h> #include "TestMocks.h" #include "pal.h" #include "pal_mock.h" using namespace std::chrono_literals; class MockPalService : public pal_service { public: MockMethod(std::chrono::microseconds, current_time, ()) }; namespace { std::function<void(std::int32_t)> on_timer_callback; void* timer_callback(std::int32_t handle) { on_timer_callback(handle); return nullptr; } } class TimerServiceTests : public testing::Test { protected: TimerServiceTests() : _service(&_thread_pool) { active_service_mock = &_pal; } ~TimerServiceTests() { active_service_mock = nullptr; on_timer_callback = nullptr; } autocrat::timer_service _service; MockPalService _pal; FakeThreadPool _thread_pool; }; TEST_F(TimerServiceTests, ShouldInvokeTheCallbackAfterTheInitialDelay) { When(_pal.current_time).Return({ 0us, 5us, 10us }); bool timer_called = false; on_timer_callback = [&](auto) { timer_called = true; }; _service.add_timer_callback(10us, 0us, &timer_callback); _service.check_and_dispatch(); EXPECT_FALSE(timer_called); _service.check_and_dispatch(); EXPECT_TRUE(timer_called); } TEST_F(TimerServiceTests, ShouldInvokeTheCallbackAfterTheRepeat) { // Add an initial 0 for when we add it to the service When(_pal.current_time).Return({ 0us, 0us, 5us, 10us, 15us, 20us }); int timer_called_count = 0; on_timer_callback = [&](auto) { timer_called_count++; }; _service.add_timer_callback(0us, 10us, &timer_callback); // 0 _service.check_and_dispatch(); EXPECT_EQ(1, timer_called_count); // 5 _service.check_and_dispatch(); EXPECT_EQ(1, timer_called_count); // 10 _service.check_and_dispatch(); EXPECT_EQ(2, timer_called_count); // 15 _service.check_and_dispatch(); EXPECT_EQ(2, timer_called_count); // 20 _service.check_and_dispatch(); EXPECT_EQ(3, timer_called_count); } TEST_F(TimerServiceTests, ShouldInvokeTheCallbackWithTheUniqueHandle) { When(_pal.current_time).Return({ 0us, 0us, 3us, 5us }); std::uint32_t called_handle = 0u; on_timer_callback = [&](std::uint32_t handle) { called_handle = static_cast<std::uint32_t>(handle); }; std::uint32_t five_handle = _service.add_timer_callback(0us, 5us, &timer_callback); std::uint32_t three_handle = _service.add_timer_callback(0us, 3us, &timer_callback); _service.check_and_dispatch(); EXPECT_EQ(three_handle, called_handle); _service.check_and_dispatch(); EXPECT_EQ(five_handle, called_handle); }
24.490909
106
0.703786
samcragg
648fd358cf12d13190a4d20eef10d8f38195a472
3,976
cpp
C++
common/OrderListImpl.cpp
caozhiyi/Hudp
85108e675d90985666d1d2a8f364015a467ae72f
[ "BSD-3-Clause" ]
57
2019-07-26T06:26:47.000Z
2022-03-22T13:12:12.000Z
common/OrderListImpl.cpp
caozhiyi/Hudp
85108e675d90985666d1d2a8f364015a467ae72f
[ "BSD-3-Clause" ]
1
2019-12-09T11:16:06.000Z
2020-04-09T12:22:23.000Z
common/OrderListImpl.cpp
caozhiyi/Hudp
85108e675d90985666d1d2a8f364015a467ae72f
[ "BSD-3-Clause" ]
20
2019-08-21T08:26:14.000Z
2021-11-21T09:58:48.000Z
#include <cstring> //for memset #include "IMsg.h" #include "ISocket.h" #include "HudpImpl.h" #include "HudpConfig.h" #include "OrderListImpl.h" using namespace hudp; CRecvList::CRecvList() : _discard_msg_count(0){ } CRecvList::~CRecvList() { } uint16_t CRecvList::HashFunc(uint16_t id) { return id & (__msx_cache_msg_num - 1); } CReliableOrderlyList::CReliableOrderlyList(uint16_t start_id) : _expect_id(start_id) { memset(_order_list, 0, sizeof(_order_list)); } CReliableOrderlyList::~CReliableOrderlyList() { std::unique_lock<std::mutex> lock(_mutex); for (size_t i = 0; i < __msx_cache_msg_num; i++) { if (_order_list[i]) { _order_list[i].reset(); } } } void CReliableOrderlyList::Clear() { std::unique_lock<std::mutex> lock(_mutex); memset(_order_list, 0, sizeof(_order_list)); _recv_list.Clear(); } uint16_t CReliableOrderlyList::Insert(std::shared_ptr<CMsg> msg) { auto id = msg->GetId(); uint16_t index = HashFunc(id); // too farm, discard this msg if (std::abs(id - _expect_id) > __max_compare_num || (_expect_id > (__max_id - __max_compare_num / 2) && id < __max_compare_num / 2)) { _discard_msg_count++; if (_discard_msg_count >= __msg_discard_limit) { return 2; } return 0; } { std::unique_lock<std::mutex> lock(_mutex); if (id == _expect_id) { _order_list[index] = msg; while (_order_list[index]) { _expect_id++; _recv_list.Push(_order_list[index]); _order_list[index] = nullptr; index++; if (index >= __msx_cache_msg_num) { index = 0; } } // is't expect id } else { // a repeat bag if (_order_list[index]) { return 1; } else { _order_list[index] = msg; } } } if (_recv_list.Size() > 0) { std::shared_ptr<CMsg> item; while (_recv_list.Pop(item)) { auto sock = item->GetSocket(); sock->ToRecv(item); } _recv_list.Clear(); } return 0; } CReliableList::CReliableList(uint16_t start_id) : _expect_id(start_id) { memset(_order_list, 0, sizeof(_order_list)); } CReliableList::~CReliableList() { } // reliable list, only judgement repetition in msg cache uint16_t CReliableList::Insert(std::shared_ptr<CMsg> msg) { auto id = msg->GetId(); uint16_t index = HashFunc(id); // too farm, discard this msg /*if (std::abs(id - _expect_id) > __max_compare_num || (_expect_id > (__max_id - __max_compare_num / 2) && id < __max_compare_num / 2)) { _discard_msg_count++; if (_discard_msg_count >= __msg_discard_limit) { return 2; } return 0; }*/ { std::unique_lock<std::mutex> lock(_mutex); if (_order_list[index] == id) { return 1; } else { _order_list[index] = id; } } _expect_id = id; auto sock = msg->GetSocket(); sock->ToRecv(msg); return 0; } COrderlyList::COrderlyList(uint16_t start_id) : _expect_id(start_id) { } COrderlyList::~COrderlyList() { } // orderly list, if msg id is bigger than expect id, recv it. uint16_t COrderlyList::Insert(std::shared_ptr<CMsg> msg) { auto id = msg->GetId(); // too farm, discard this msg if (std::abs(id - _expect_id) > __max_compare_num || (_expect_id > (__max_id - __max_compare_num / 2) && id < __max_compare_num / 2)) { _discard_msg_count++; if (_discard_msg_count >= __msg_discard_limit) { return 2; } return 0; } if (id < _expect_id) { return 0; } _expect_id = id; auto sock = msg->GetSocket(); sock->ToRecv(msg); return 0; }
24.243902
90
0.56841
caozhiyi
649889497cf1f508fe74922469d0424f7a6199c6
13,705
cpp
C++
src/elona/lua_env/lua_api/lua_api_map.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
src/elona/lua_env/lua_api/lua_api_map.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
src/elona/lua_env/lua_api/lua_api_map.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
1
2020-02-24T18:52:19.000Z
2020-02-24T18:52:19.000Z
#include "lua_api_map.hpp" #include "../../area.hpp" #include "../../character.hpp" #include "../../data/types/type_map.hpp" #include "../../lua_env/enums/enums.hpp" #include "../../map.hpp" #include "../../map_cell.hpp" #include "../../mapgen.hpp" #include "../interface.hpp" namespace elona { namespace lua { /** * @luadoc * * Returns the current map's width. This is only valid until the map * changes. * @treturn num the current map's width in tiles */ int LuaApiMap::width() { return map_data.width; } /** * @luadoc * * Returns the current map's height. This is only valid until the map * changes. * @treturn num the current map's height in tiles */ int LuaApiMap::height() { return map_data.height; } /** * @luadoc * * Returns the current map's ID. * @treturn[1] string the current map's ID * @treturn[2] nil */ sol::optional<std::string> LuaApiMap::id() { auto legacy_id = LuaApiMap::legacy_id(); auto id = the_mapdef_db.get_id_from_legacy(legacy_id); if (!legacy_id) { return sol::nullopt; } return id->get(); } /** * @luadoc * * Returns the current map's legacy ID. * @treturn[1] num the current map's legacy ID * @treturn[2] nil */ int LuaApiMap::legacy_id() { return area_data[game_data.current_map].id; } /** * @luadoc * * Returns the ID of the current map's instance. There can be more than one * instance of a map of the same kind, like player-owned buildings. * @treturn num the current map's instance ID */ int LuaApiMap::instance_id() { return game_data.current_map; } /** * @luadoc * * Returns the current dungeon level. * TODO: unify with World.data or Map.data */ int LuaApiMap::current_dungeon_level() { return game_data.current_dungeon_level; } /** * @luadoc * * Returns true if this map is the overworld. * @treturn bool */ bool LuaApiMap::is_overworld() { return elona::map_data.atlas_number == 0; } /** * @luadoc * * Checks if a position is inside the map. It might be blocked by something. * @tparam LuaPosition position * @treturn bool true if the position is inside the map. */ bool LuaApiMap::valid(const Position& position) { return LuaApiMap::valid_xy(position.x, position.y); } bool LuaApiMap::valid_xy(int x, int y) { return x >= 0 && y >= 0 && x < LuaApiMap::width() && y < LuaApiMap::height(); } /** * @luadoc * * Returns true if the map tile at the given position is solid. * @tparam LuaPosition position * @treturn bool */ bool LuaApiMap::is_solid(const Position& position) { return LuaApiMap::is_solid_xy(position.x, position.y); } bool LuaApiMap::is_solid_xy(int x, int y) { if (LuaApiMap::is_overworld()) { return true; } if (!LuaApiMap::valid_xy(x, y)) { return true; } return elona::chip_data.for_cell(x, y).effect & 4; } /** * @luadoc * * Checks if a position is blocked and cannot be reached by walking. * @tparam LuaPosition position * @treturn bool */ bool LuaApiMap::is_blocked(const Position& position) { return LuaApiMap::is_blocked_xy(position.x, position.y); } bool LuaApiMap::is_blocked_xy(int x, int y) { if (LuaApiMap::is_overworld()) { return true; } if (!LuaApiMap::valid_xy(x, y)) { return true; } elona::cell_check(x, y); return cellaccess == 0; } /** * @luadoc * * Returns a random position in the current map. It might be blocked by * something. * @treturn LuaPosition a random position */ Position LuaApiMap::random_pos() { return Position{elona::rnd(map_data.width - 1), elona::rnd(map_data.height - 1)}; } /** * @luadoc * * Generates a random tile ID from the current map's tileset. * Tile kinds can contain one of several different tile variations. * @tparam Enums.TileKind tile_kind the tile kind to set * @treturn num the generated tile ID * @see Enums.TileKind */ int LuaApiMap::generate_tile(const EnumString& tile_kind) { TileKind tile_kind_value = LuaEnums::TileKindTable.ensure_from_string(tile_kind); return elona::cell_get_type(tile_kind_value); } /** * @luadoc * * Returns the type of chip for the given tile kind. */ int LuaApiMap::chip_type(int tile_id) { return elona::chip_data[tile_id].kind; } /** * @luadoc * * Gets the tile type of a tile position. * @tparam LuaPosition position * @treturn num */ int LuaApiMap::get_tile(const Position& position) { return LuaApiMap::get_tile_xy(position.x, position.y); } int LuaApiMap::get_tile_xy(int x, int y) { if (LuaApiMap::is_overworld()) { return -1; } if (!LuaApiMap::valid_xy(x, y)) { return -1; } return elona::cell_data.at(x, y).chip_id_actual; } /** * @luadoc * * Gets the player's memory of a tile position. * @tparam LuaPosition position * @treturn num */ int LuaApiMap::get_memory(const Position& position) { return LuaApiMap::get_memory_xy(position.x, position.y); } int LuaApiMap::get_memory_xy(int x, int y) { if (LuaApiMap::is_overworld()) { return -1; } if (!LuaApiMap::valid_xy(x, y)) { return -1; } return elona::cell_data.at(x, y).chip_id_memory; } /** * @luadoc * * Returns a table containing map feature information at the given tile * position. * - id: Feature id. * - param1: Extra parameter. * - param2: Extra parameter. * - param3: Extra parameter. (unused) * @tparam LuaPosition position * @treturn table */ sol::table LuaApiMap::get_feat(const Position& position) { return LuaApiMap::get_feat_xy(position.x, position.y); } sol::table LuaApiMap::get_feat_xy(int x, int y) { if (LuaApiMap::is_overworld()) { return lua::create_table(); } if (!LuaApiMap::valid_xy(x, y)) { return lua::create_table(); } auto feats = elona::cell_data.at(x, y).feats; auto id = feats % 1000; auto param1 = feats / 1000 % 100; auto param2 = feats / 100000 % 100; auto param3 = feats / 10000000; return lua::create_table( "id", id, "param1", param1, "param2", param2, "param3", param3); } /** * @luadoc * * Returns the ID of the map effect at the given position. * @tparam LuaPosition position * @treturn num */ int LuaApiMap::get_mef(const Position& position) { return LuaApiMap::get_mef_xy(position.x, position.y); } int LuaApiMap::get_mef_xy(int x, int y) { if (LuaApiMap::is_overworld()) { return 0; } if (!LuaApiMap::valid_xy(x, y)) { return 0; } int index_plus_one = cell_data.at(x, y).mef_index_plus_one; if (index_plus_one == 0) { return 0; } return mef(0, index_plus_one - 1); } /** * @luadoc * * Gets the character standing at a tile position. * @tparam LuaPosition position * @treturn[opt] LuaCharacter */ sol::optional<LuaCharacterHandle> LuaApiMap::get_chara(const Position& position) { return LuaApiMap::get_chara_xy(position.x, position.y); } sol::optional<LuaCharacterHandle> LuaApiMap::get_chara_xy(int x, int y) { if (!LuaApiMap::valid_xy(x, y)) { return sol::nullopt; } int index_plus_one = cell_data.at(x, y).chara_index_plus_one; if (index_plus_one == 0) { return sol::nullopt; } return lua::handle(cdata[index_plus_one - 1]); } /** * @luadoc * * Sets a tile of the current map. Only checks if the position is valid, not * things like blocking objects. * @tparam LuaPosition position * @tparam num id the tile ID to set * @usage Map.set_tile(10, 10, Map.generate_tile(Enums.TileKind.Room)) */ void LuaApiMap::set_tile(const Position& position, int id) { LuaApiMap::set_tile_xy(position.x, position.y, id); } void LuaApiMap::set_tile_xy(int x, int y, int id) { if (LuaApiMap::is_overworld()) { return; } if (!LuaApiMap::valid_xy(x, y)) { return; } // TODO: check validity of tile ID elona::cell_data.at(x, y).chip_id_actual = id; } /** * @luadoc * * Sets the player's memory of a tile position to the given tile kind. * @tparam LuaPosition position * @tparam num id the tile ID to set * @usage Map.set_memory(10, 10, Map.generate_tile(Enums.TileKind.Room)) */ void LuaApiMap::set_memory(const Position& position, int id) { LuaApiMap::set_memory_xy(position.x, position.y, id); } void LuaApiMap::set_memory_xy(int x, int y, int id) { if (LuaApiMap::is_overworld()) { return; } if (!LuaApiMap::valid_xy(x, y)) { return; } elona::cell_data.at(x, y).chip_id_memory = id; } /** * @luadoc * * Sets a feat at the given position. * @tparam LuaPosition position (const) the map position * @tparam num tile the tile ID of the feat * @tparam num param1 a parameter of the feat * @tparam num param2 a parameter of the feat */ void LuaApiMap::set_feat( const Position& position, int tile, int param1, int param2) { LuaApiMap::set_feat_xy(position.x, position.y, tile, param1, param2); } void LuaApiMap::set_feat_xy(int x, int y, int tile, int param1, int param2) { cell_featset(x, y, tile, param1, param2); } /** * @luadoc * * Clears the feat at the given position. * @tparam LuaPosition position (const) the map position */ void LuaApiMap::clear_feat(const Position& position) { LuaApiMap::clear_feat_xy(position.x, position.y); } void LuaApiMap::clear_feat_xy(int x, int y) { cell_featclear(x, y); } /** * @ luadoc * * Randomly sprays the map with the given tile type; */ void LuaApiMap::spray_tile(int tile, int amount) { elona::map_randomtile(tile, amount); } void LuaApiMap::travel_to(const std::string& map_id) { LuaApiMap::travel_to_with_level(map_id, 1); } void LuaApiMap::travel_to_with_level(const std::string& map_id, int level) { auto map = the_mapdef_db.ensure(map_id); game_data.player_x_on_map_leave = cdata.player().position.x; game_data.player_y_on_map_leave = cdata.player().position.y; game_data.previous_x = cdata.player().position.x; game_data.previous_y = cdata.player().position.y; // Set up the outer map of the map traveled to, such that the player will // appear on top the map's area when they leave via the map's edge. if (map.map_type != mdata_t::MapType::world_map) { auto outer_map = the_mapdef_db[map.outer_map]; if (outer_map) { game_data.previous_map2 = outer_map->legacy_id; game_data.previous_dungeon_level = 1; game_data.pc_x_in_world_map = map.outer_map_position.x; game_data.pc_y_in_world_map = map.outer_map_position.y; game_data.destination_outer_map = outer_map->legacy_id; } } else { game_data.previous_map2 = map.legacy_id; game_data.previous_dungeon_level = 1; game_data.destination_outer_map = map.legacy_id; } map_prepare_for_travel(map.legacy_id, level); exit_map(); initialize_map(); } void LuaApiMap::bind(sol::table& api_table) { LUA_API_BIND_FUNCTION(api_table, LuaApiMap, width); LUA_API_BIND_FUNCTION(api_table, LuaApiMap, height); LUA_API_BIND_FUNCTION(api_table, LuaApiMap, id); LUA_API_BIND_FUNCTION(api_table, LuaApiMap, legacy_id); LUA_API_BIND_FUNCTION(api_table, LuaApiMap, instance_id); LUA_API_BIND_FUNCTION(api_table, LuaApiMap, is_overworld); LUA_API_BIND_FUNCTION(api_table, LuaApiMap, current_dungeon_level); api_table.set_function( "valid", sol::overload(LuaApiMap::valid, LuaApiMap::valid_xy)); api_table.set_function( "is_solid", sol::overload(LuaApiMap::is_solid, LuaApiMap::is_solid_xy)); api_table.set_function( "is_blocked", sol::overload(LuaApiMap::is_blocked, LuaApiMap::is_blocked_xy)); LUA_API_BIND_FUNCTION(api_table, LuaApiMap, random_pos); LUA_API_BIND_FUNCTION(api_table, LuaApiMap, generate_tile); LUA_API_BIND_FUNCTION(api_table, LuaApiMap, chip_type); api_table.set_function( "get_tile", sol::overload(LuaApiMap::get_tile, LuaApiMap::get_tile_xy)); api_table.set_function( "get_memory", sol::overload(LuaApiMap::get_memory, LuaApiMap::get_memory_xy)); api_table.set_function( "get_feat", sol::overload(LuaApiMap::get_feat, LuaApiMap::get_feat_xy)); api_table.set_function( "get_mef", sol::overload(LuaApiMap::get_mef, LuaApiMap::get_mef_xy)); api_table.set_function( "get_chara", sol::overload(LuaApiMap::get_chara, LuaApiMap::get_chara_xy)); api_table.set_function( "set_tile", sol::overload(LuaApiMap::set_tile, LuaApiMap::set_tile_xy)); api_table.set_function( "set_memory", sol::overload(LuaApiMap::set_memory, LuaApiMap::set_memory_xy)); api_table.set_function( "set_feat", sol::overload(LuaApiMap::set_feat, LuaApiMap::set_feat_xy)); api_table.set_function( "clear_feat", sol::overload(LuaApiMap::clear_feat, LuaApiMap::clear_feat_xy)); LUA_API_BIND_FUNCTION(api_table, LuaApiMap, spray_tile); api_table.set_function( "travel_to", sol::overload(LuaApiMap::travel_to, LuaApiMap::travel_to_with_level)); /** * @luadoc data field LuaMapData * * [R] The map data for the current map. This contains serialized values * controlling various aspects of the current map. */ api_table.set("data", sol::property(&map_data)); /** * @luadoc area function * * Returns the area in the world map that corresponds to this map. */ api_table.set("area", sol::property([]() { return &area_data.current(); })); } } // namespace lua } // namespace elona
23.507719
80
0.664137
XrosFade
6499afc7c0372b645f794f58c71b664d3f81e93c
1,022
cpp
C++
src/lug/System/Exception.cpp
Lugdunum3D/Lugdunum3D
b6d6907d034fdba1ffc278b96598eba1d860f0d4
[ "MIT" ]
275
2016-10-08T15:33:17.000Z
2022-03-30T06:11:56.000Z
src/lug/System/Exception.cpp
Lugdunum3D/Lugdunum3D
b6d6907d034fdba1ffc278b96598eba1d860f0d4
[ "MIT" ]
24
2016-09-29T20:51:20.000Z
2018-05-09T21:41:36.000Z
src/lug/System/Exception.cpp
Lugdunum3D/Lugdunum3D
b6d6907d034fdba1ffc278b96598eba1d860f0d4
[ "MIT" ]
37
2017-02-25T05:03:48.000Z
2021-05-10T19:06:29.000Z
#include <lug/System/Exception.hpp> #include <sstream> lug::System::Exception::Exception(const char* typeName, const std::string& description, const char* file, const char* function, uint32_t line) : _typeName{typeName}, _description{description}, _file{file}, _function{function}, _line{line} {} const std::string& lug::System::Exception::getTypeName() const { return _typeName; } const std::string& lug::System::Exception::getDescription() const { return _description; } const std::string& lug::System::Exception::getFile() const { return _file; } const std::string& lug::System::Exception::getFunction() const { return _function; } uint32_t lug::System::Exception::getLine() const { return _line; } const char* lug::System::Exception::what() const noexcept { std::stringstream msg; msg << _typeName << ": " << _description << std::endl; msg << "In " << _file; msg << " at `" << _function << "` line " << _line; _fullDesc = msg.str(); return _fullDesc.c_str(); }
27.621622
142
0.67319
Lugdunum3D
649d5fb9befe93d9df8863af6f5f77568dc3baec
11,273
cpp
C++
src/vbk/test/unit/pop_service_tests.cpp
xagau/vbk-ri-btc
9907b6ec54894c01e1f6dcfd80764f08ac84743a
[ "MIT" ]
1
2020-04-20T15:20:23.000Z
2020-04-20T15:20:23.000Z
src/vbk/test/unit/pop_service_tests.cpp
xagau/vbk-ri-btc
9907b6ec54894c01e1f6dcfd80764f08ac84743a
[ "MIT" ]
null
null
null
src/vbk/test/unit/pop_service_tests.cpp
xagau/vbk-ri-btc
9907b6ec54894c01e1f6dcfd80764f08ac84743a
[ "MIT" ]
null
null
null
#include <boost/test/unit_test.hpp> #include <consensus/validation.h> #include <shutdown.h> #include <test/util/setup_common.h> #include <validation.h> #include <vbk/config.hpp> #include <vbk/init.hpp> #include <vbk/pop_service.hpp> #include <vbk/pop_service/pop_service_impl.hpp> #include <vbk/service_locator.hpp> #include <vbk/test/util/mock.hpp> #include <vbk/test/util/tx.hpp> using ::testing::Return; static CBlock createBlockWithPopTx(TestChain100Setup& test) { CMutableTransaction popTx = VeriBlockTest::makePopTx({1}, {{2}}); CScript scriptPubKey = CScript() << ToByteVector(test.coinbaseKey.GetPubKey()) << OP_CHECKSIG; return test.CreateAndProcessBlock({popTx}, scriptPubKey); } inline void setPublicationData(VeriBlock::PublicationData& pub, const CDataStream& stream, const int64_t& index) { pub.set_identifier(index); pub.set_header((void*)stream.data(), stream.size()); } struct PopServiceFixture : public TestChain100Setup { testing::NiceMock<VeriBlockTest::PopServiceImplMock> pop_service_impl_mock; PopServiceFixture() { AbortShutdown(); VeriBlock::InitUtilService(); VeriBlock::InitConfig(); VeriBlockTest::setUpPopServiceMock(pop_service_mock); ON_CALL(pop_service_impl_mock, parsePopTx) .WillByDefault( [](const CTransactionRef&, ScriptError* serror, VeriBlock::Publications*, VeriBlock::Context*, VeriBlock::PopTxType* type) -> bool { if (type != nullptr) { *type = VeriBlock::PopTxType::PUBLICATIONS; } if (serror != nullptr) { *serror = ScriptError::SCRIPT_ERR_OK; } return true; }); ON_CALL(pop_service_impl_mock, determineATVPlausibilityWithBTCRules) .WillByDefault(Return(true)); ON_CALL(pop_service_impl_mock, addTemporaryPayloads) .WillByDefault( [&](const CTransactionRef& tx, const CBlockIndex& pindexPrev, const Consensus::Params& params, TxValidationState& state) { return VeriBlock::addTemporaryPayloadsImpl(pop_service_impl_mock, tx, pindexPrev, params, state); }); ON_CALL(pop_service_impl_mock, clearTemporaryPayloads) .WillByDefault( [&]() { VeriBlock::clearTemporaryPayloadsImpl(pop_service_impl_mock); }); VeriBlock::initTemporaryPayloadsMock(pop_service_impl_mock); } void setNoAddRemovePayloadsExpectations() { EXPECT_CALL(pop_service_impl_mock, addPayloads).Times(0); EXPECT_CALL(pop_service_impl_mock, removePayloads).Times(0); } }; BOOST_AUTO_TEST_SUITE(pop_service_tests) BOOST_FIXTURE_TEST_CASE(blockPopValidation_test, PopServiceFixture) { CBlock block = createBlockWithPopTx(*this); CBlockIndex* endorsedBlockIndex = ChainActive().Tip()->pprev; CBlock endorsedBlock; BOOST_CHECK(ReadBlockFromDisk(endorsedBlock, endorsedBlockIndex, Params().GetConsensus())); CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << endorsedBlock.GetBlockHeader(); auto& config = VeriBlock::getService<VeriBlock::Config>(); ON_CALL(pop_service_impl_mock, getPublicationsData) .WillByDefault( [stream, config](const VeriBlock::Publications& pub, VeriBlock::PublicationData& publicationData) { setPublicationData(publicationData, stream, config.index.unwrap()); }); BlockValidationState state; { LOCK(cs_main); BOOST_CHECK(VeriBlock::blockPopValidationImpl(pop_service_impl_mock, block, *ChainActive().Tip()->pprev, Params().GetConsensus(), state)); } } BOOST_FIXTURE_TEST_CASE(blockPopValidation_test_wrong_index, PopServiceFixture) { CBlock block = createBlockWithPopTx(*this); CBlockIndex* endorsedBlockIndex = ChainActive().Tip()->pprev->pprev->pprev; CBlock endorsedBlock; BOOST_CHECK(ReadBlockFromDisk(endorsedBlock, endorsedBlockIndex, Params().GetConsensus())); CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << endorsedBlock.GetBlockHeader(); // make another index ON_CALL(pop_service_impl_mock, getPublicationsData) .WillByDefault( [stream](const VeriBlock::Publications& pub, VeriBlock::PublicationData& publicationData) { setPublicationData(publicationData, stream, -1); }); ON_CALL(pop_service_impl_mock, determineATVPlausibilityWithBTCRules) .WillByDefault( [](VeriBlock::AltchainId altChainIdentifier, const CBlockHeader& popEndorsementHeader, const Consensus::Params& params, TxValidationState& state) -> bool { VeriBlock::PopServiceImpl pop_service_impl(false, false); return pop_service_impl.determineATVPlausibilityWithBTCRules(altChainIdentifier, popEndorsementHeader, params, state); }); setNoAddRemovePayloadsExpectations(); BlockValidationState state; { LOCK(cs_main); BOOST_CHECK(!blockPopValidationImpl(pop_service_impl_mock, block, *ChainActive().Tip()->pprev, Params().GetConsensus(), state)); BOOST_CHECK_EQUAL(state.GetRejectReason(), "pop-tx-altchain-id"); } testing::Mock::VerifyAndClearExpectations(&pop_service_impl_mock); } BOOST_FIXTURE_TEST_CASE(blockPopValidation_test_endorsed_block_not_known_orphan_block, PopServiceFixture) { CBlockIndex* endorsedBlockIndex = ChainActive().Tip(); CBlock endorsedBlock; BOOST_CHECK(ReadBlockFromDisk(endorsedBlock, endorsedBlockIndex, Params().GetConsensus())); endorsedBlock.hashPrevBlock.SetHex("ff"); CBlock block = createBlockWithPopTx(*this); CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << endorsedBlock.GetBlockHeader(); auto& config = VeriBlock::getService<VeriBlock::Config>(); ON_CALL(pop_service_impl_mock, getPublicationsData) .WillByDefault( [stream, config](const VeriBlock::Publications& pub, VeriBlock::PublicationData& publicationData) { setPublicationData(publicationData, stream, config.index.unwrap()); }); setNoAddRemovePayloadsExpectations(); { BlockValidationState state; LOCK(cs_main); BOOST_CHECK(!blockPopValidationImpl(pop_service_impl_mock, block, *ChainActive().Tip()->pprev, Params().GetConsensus(), state)); BOOST_CHECK_EQUAL(state.GetRejectReason(), "pop-tx-endorsed-block-not-known-orphan-block"); } testing::Mock::VerifyAndClearExpectations(&pop_service_impl_mock); } BOOST_FIXTURE_TEST_CASE(blockPopValidation_test_endorsed_block_not_from_chain, PopServiceFixture) { CBlockIndex* endorsedBlockIndex = ChainActive().Tip()->pprev->pprev; CBlock endorsedBlock; BOOST_CHECK(ReadBlockFromDisk(endorsedBlock, endorsedBlockIndex, Params().GetConsensus())); int prevHeight = endorsedBlockIndex->nHeight; BlockValidationState state; BOOST_CHECK(InvalidateBlock(state, Params(), endorsedBlockIndex->pprev)); BOOST_CHECK(ActivateBestChain(state, Params())); BOOST_CHECK(ChainActive().Height() < prevHeight); CScript scriptPubKey = CScript() << OP_CHECKSIG; CreateAndProcessBlock({}, scriptPubKey); CreateAndProcessBlock({}, scriptPubKey); CreateAndProcessBlock({}, scriptPubKey); CBlock block = createBlockWithPopTx(*this); BOOST_CHECK(ChainActive().Height() > prevHeight); CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << endorsedBlock.GetBlockHeader(); auto& config = VeriBlock::getService<VeriBlock::Config>(); ON_CALL(pop_service_impl_mock, getPublicationsData) .WillByDefault( [stream, config](const VeriBlock::Publications& pub, VeriBlock::PublicationData& publicationData) { setPublicationData(publicationData, stream, config.index.unwrap()); }); setNoAddRemovePayloadsExpectations(); { LOCK(cs_main); BOOST_CHECK(!blockPopValidationImpl(pop_service_impl_mock, block, *ChainActive().Tip()->pprev, Params().GetConsensus(), state)); BOOST_CHECK_EQUAL(state.GetRejectReason(), "pop-tx-endorsed-block-not-from-this-chain"); } testing::Mock::VerifyAndClearExpectations(&pop_service_impl_mock); } BOOST_FIXTURE_TEST_CASE(blockPopValidation_test_wrong_settlement_interval, PopServiceFixture) { CBlockIndex* endorsedBlockIndex = ChainActive().Tip()->pprev->pprev->pprev; CBlock endorsedBlock; BOOST_CHECK(ReadBlockFromDisk(endorsedBlock, endorsedBlockIndex, Params().GetConsensus())); CBlock block = createBlockWithPopTx(*this); CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << endorsedBlock.GetBlockHeader(); auto& config = VeriBlock::getService<VeriBlock::Config>(); ON_CALL(pop_service_impl_mock, getPublicationsData) .WillByDefault( [stream, config](const VeriBlock::Publications& pub, VeriBlock::PublicationData& publicationData) { setPublicationData(publicationData, stream, config.index.unwrap()); }); setNoAddRemovePayloadsExpectations(); config.POP_REWARD_SETTLEMENT_INTERVAL = 0; VeriBlock::setService<VeriBlock::Config>(new VeriBlock::Config(config)); BlockValidationState state; { LOCK(cs_main); BOOST_CHECK(!blockPopValidationImpl(pop_service_impl_mock, block, *ChainActive().Tip()->pprev, Params().GetConsensus(), state)); BOOST_CHECK_EQUAL(state.GetRejectReason(), "pop-tx-endorsed-block-too-old"); } testing::Mock::VerifyAndClearExpectations(&pop_service_impl_mock); } BOOST_FIXTURE_TEST_CASE(blockPopValidation_test_wrong_addPayloads, PopServiceFixture) { CBlockIndex* endorsedBlockIndex = ChainActive().Tip()->pprev->pprev->pprev; CBlock endorsedBlock; BOOST_CHECK(ReadBlockFromDisk(endorsedBlock, endorsedBlockIndex, Params().GetConsensus())); CBlock block = createBlockWithPopTx(*this); CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << endorsedBlock.GetBlockHeader(); auto& config = VeriBlock::getService<VeriBlock::Config>(); ON_CALL(pop_service_impl_mock, getPublicationsData) .WillByDefault( [stream, config](const VeriBlock::Publications& pub, VeriBlock::PublicationData& publicationData) { setPublicationData(publicationData, stream, config.index.unwrap()); }); ON_CALL(pop_service_impl_mock, addPayloads) .WillByDefault( [](std::string hash, const int& nHeight, const VeriBlock::Publications& publications) -> void { throw VeriBlock::PopServiceException("fail"); }); EXPECT_CALL(pop_service_impl_mock, addPayloads).Times(1); EXPECT_CALL(pop_service_impl_mock, removePayloads).Times(0); BlockValidationState state; { LOCK(cs_main); BOOST_CHECK(!blockPopValidationImpl(pop_service_impl_mock, block, *ChainActive().Tip()->pprev, Params().GetConsensus(), state)); BOOST_CHECK_EQUAL(state.GetRejectReason(), "pop-tx-add-payloads-failed"); } testing::Mock::VerifyAndClearExpectations(&pop_service_impl_mock); } BOOST_AUTO_TEST_SUITE_END()
41.142336
148
0.710104
xagau
64abd26a4d2f35082486a3c26843733f29e118d9
75,963
cpp
C++
lib/crunch/crnlib/crn_comp.cpp
Wizermil/unordered_map
4d60bf16384b7ea9db1d43d8b15313f8752490ee
[ "MIT" ]
null
null
null
lib/crunch/crnlib/crn_comp.cpp
Wizermil/unordered_map
4d60bf16384b7ea9db1d43d8b15313f8752490ee
[ "MIT" ]
null
null
null
lib/crunch/crnlib/crn_comp.cpp
Wizermil/unordered_map
4d60bf16384b7ea9db1d43d8b15313f8752490ee
[ "MIT" ]
null
null
null
// File: crn_comp.cpp // This software is in the public domain. Please see license.txt. #include "crn_core.h" #include "crn_console.h" #include "crn_comp.h" #include "crn_zeng.h" #include "crn_checksum.h" #define CRNLIB_CREATE_DEBUG_IMAGES 0 #define CRNLIB_ENABLE_DEBUG_MESSAGES 0 namespace crnlib { static const uint cEncodingMapNumChunksPerCode = 3; crn_comp::crn_comp() : m_pParams(NULL) { } crn_comp::~crn_comp() { } float crn_comp::color_endpoint_similarity_func(uint index_a, uint index_b, void* pContext) { dxt_hc& hvq = *static_cast<dxt_hc*>(pContext); uint endpoint_a = hvq.get_color_endpoint(index_a); uint endpoint_b = hvq.get_color_endpoint(index_b); color_quad_u8 a[2]; a[0] = dxt1_block::unpack_color((uint16)(endpoint_a & 0xFFFF), true); a[1] = dxt1_block::unpack_color((uint16)((endpoint_a >> 16) & 0xFFFF), true); color_quad_u8 b[2]; b[0] = dxt1_block::unpack_color((uint16)(endpoint_b & 0xFFFF), true); b[1] = dxt1_block::unpack_color((uint16)((endpoint_b >> 16) & 0xFFFF), true); uint total_error = color::elucidian_distance(a[0], b[0], false) + color::elucidian_distance(a[1], b[1], false); float weight = 1.0f - math::clamp(total_error * 1.0f/8000.0f, 0.0f, 1.0f); return weight; } float crn_comp::alpha_endpoint_similarity_func(uint index_a, uint index_b, void* pContext) { dxt_hc& hvq = *static_cast<dxt_hc*>(pContext); uint endpoint_a = hvq.get_alpha_endpoint(index_a); int endpoint_a_lo = dxt5_block::unpack_endpoint(endpoint_a, 0); int endpoint_a_hi = dxt5_block::unpack_endpoint(endpoint_a, 1); uint endpoint_b = hvq.get_alpha_endpoint(index_b); int endpoint_b_lo = dxt5_block::unpack_endpoint(endpoint_b, 0); int endpoint_b_hi = dxt5_block::unpack_endpoint(endpoint_b, 1); int total_error = math::square(endpoint_a_lo - endpoint_b_lo) + math::square(endpoint_a_hi - endpoint_b_hi); float weight = 1.0f - math::clamp(total_error * 1.0f/256.0f, 0.0f, 1.0f); return weight; } void crn_comp::sort_color_endpoint_codebook(crnlib::vector<uint>& remapping, const crnlib::vector<uint>& endpoints) { remapping.resize(endpoints.size()); uint lowest_energy = UINT_MAX; uint lowest_energy_index = 0; for (uint i = 0; i < endpoints.size(); i++) { color_quad_u8 a(dxt1_block::unpack_color(static_cast<uint16>(endpoints[i] & 0xFFFF), true)); color_quad_u8 b(dxt1_block::unpack_color(static_cast<uint16>((endpoints[i] >> 16) & 0xFFFF), true)); uint total = a.r + a.g + a.b + b.r + b.g + b.b; if (total < lowest_energy) { lowest_energy = total; lowest_energy_index = i; } } uint cur_index = lowest_energy_index; crnlib::vector<bool> chosen_flags(endpoints.size()); uint n = 0; for ( ; ; ) { chosen_flags[cur_index] = true; remapping[cur_index] = n; n++; if (n == endpoints.size()) break; uint lowest_error = UINT_MAX; uint lowest_error_index = 0; color_quad_u8 a(dxt1_block::unpack_endpoint(endpoints[cur_index], 0, true)); color_quad_u8 b(dxt1_block::unpack_endpoint(endpoints[cur_index], 1, true)); for (uint i = 0; i < endpoints.size(); i++) { if (chosen_flags[i]) continue; color_quad_u8 c(dxt1_block::unpack_endpoint(endpoints[i], 0, true)); color_quad_u8 d(dxt1_block::unpack_endpoint(endpoints[i], 1, true)); uint total = color::elucidian_distance(a, c, false) + color::elucidian_distance(b, d, false); if (total < lowest_error) { lowest_error = total; lowest_error_index = i; } } cur_index = lowest_error_index; } } void crn_comp::sort_alpha_endpoint_codebook(crnlib::vector<uint>& remapping, const crnlib::vector<uint>& endpoints) { remapping.resize(endpoints.size()); uint lowest_energy = UINT_MAX; uint lowest_energy_index = 0; for (uint i = 0; i < endpoints.size(); i++) { uint a = dxt5_block::unpack_endpoint(endpoints[i], 0); uint b = dxt5_block::unpack_endpoint(endpoints[i], 1); uint total = a + b; if (total < lowest_energy) { lowest_energy = total; lowest_energy_index = i; } } uint cur_index = lowest_energy_index; crnlib::vector<bool> chosen_flags(endpoints.size()); uint n = 0; for ( ; ; ) { chosen_flags[cur_index] = true; remapping[cur_index] = n; n++; if (n == endpoints.size()) break; uint lowest_error = UINT_MAX; uint lowest_error_index = 0; const int a = dxt5_block::unpack_endpoint(endpoints[cur_index], 0); const int b = dxt5_block::unpack_endpoint(endpoints[cur_index], 1); for (uint i = 0; i < endpoints.size(); i++) { if (chosen_flags[i]) continue; const int c = dxt5_block::unpack_endpoint(endpoints[i], 0); const int d = dxt5_block::unpack_endpoint(endpoints[i], 1); uint total = math::square(a - c) + math::square(b - d); if (total < lowest_error) { lowest_error = total; lowest_error_index = i; } } cur_index = lowest_error_index; } } // The indices are only used for statistical purposes. bool crn_comp::pack_color_endpoints( crnlib::vector<uint8>& data, const crnlib::vector<uint>& remapping, const crnlib::vector<uint>& endpoint_indices, uint trial_index) { trial_index; #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("pack_color_endpoints: %u", trial_index); #endif crnlib::vector<uint> remapped_endpoints(m_hvq.get_color_endpoint_codebook_size()); for (uint i = 0; i < m_hvq.get_color_endpoint_codebook_size(); i++) remapped_endpoints[remapping[i]] = m_hvq.get_color_endpoint(i); const uint component_limits[6] = { 31, 63, 31, 31, 63, 31 }; symbol_histogram hist[2]; hist[0].resize(32); hist[1].resize(64); #if CRNLIB_CREATE_DEBUG_IMAGES image_u8 endpoint_image(2, m_hvq.get_color_endpoint_codebook_size()); image_u8 endpoint_residual_image(2, m_hvq.get_color_endpoint_codebook_size()); #endif crnlib::vector<uint> residual_syms; residual_syms.reserve(m_hvq.get_color_endpoint_codebook_size()*2*3); color_quad_u8 prev[2]; prev[0].clear(); prev[1].clear(); int total_residuals = 0; for (uint endpoint_index = 0; endpoint_index < m_hvq.get_color_endpoint_codebook_size(); endpoint_index++) { const uint endpoint = remapped_endpoints[endpoint_index]; color_quad_u8 cur[2]; cur[0] = dxt1_block::unpack_color((uint16)(endpoint & 0xFFFF), false); cur[1] = dxt1_block::unpack_color((uint16)((endpoint >> 16) & 0xFFFF), false); #if CRNLIB_CREATE_DEBUG_IMAGES endpoint_image(0, endpoint_index) = dxt1_block::unpack_color((uint16)(endpoint & 0xFFFF), true); endpoint_image(1, endpoint_index) = dxt1_block::unpack_color((uint16)((endpoint >> 16) & 0xFFFF), true); #endif for (uint j = 0; j < 2; j++) { for (uint k = 0; k < 3; k++) { int delta = cur[j][k] - prev[j][k]; total_residuals += delta*delta; int sym = delta & component_limits[j*3+k]; int table = (k == 1) ? 1 : 0; hist[table].inc_freq(sym); residual_syms.push_back(sym); #if CRNLIB_CREATE_DEBUG_IMAGES endpoint_residual_image(j, endpoint_index)[k] = static_cast<uint8>(sym); #endif } } prev[0] = cur[0]; prev[1] = cur[1]; } #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Total endpoint residuals: %i", total_residuals); #endif if (endpoint_indices.size() > 1) { uint prev_index = remapping[endpoint_indices[0]]; int64 total_delta = 0; for (uint i = 1; i < endpoint_indices.size(); i++) { uint cur_index = remapping[endpoint_indices[i]]; int delta = cur_index - prev_index; prev_index = cur_index; total_delta += delta * delta; } #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Total endpoint index delta: " CRNLIB_INT64_FORMAT_SPECIFIER, total_delta); #endif } #if CRNLIB_CREATE_DEBUG_IMAGES image_utils::write_to_file(dynamic_string(cVarArg, "color_endpoint_residuals_%u.tga", trial_index).get_ptr(), endpoint_residual_image); image_utils::write_to_file(dynamic_string(cVarArg, "color_endpoints_%u.tga", trial_index).get_ptr(), endpoint_image); #endif static_huffman_data_model residual_dm[2]; symbol_codec codec; codec.start_encoding(1024*1024); // Transmit residuals for (uint i = 0; i < 2; i++) { if (!residual_dm[i].init(true, hist[i], 15)) return false; if (!codec.encode_transmit_static_huffman_data_model(residual_dm[i], false)) return false; } #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Wrote %u bits for color endpoint residual Huffman tables", codec.encode_get_total_bits_written()); #endif uint start_bits = codec.encode_get_total_bits_written(); start_bits; for (uint i = 0; i < residual_syms.size(); i++) { const uint sym = residual_syms[i]; const uint table = ((i % 3) == 1) ? 1 : 0; codec.encode(sym, residual_dm[table]); } #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Wrote %u bits for color endpoint residuals", codec.encode_get_total_bits_written() - start_bits); #endif codec.stop_encoding(false); data.swap(codec.get_encoding_buf()); #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) { console::debug("Wrote a total of %u bits for color endpoint codebook", codec.encode_get_total_bits_written()); console::debug("Wrote %f bits per each color endpoint", data.size() * 8.0f / m_hvq.get_color_endpoint_codebook_size()); } #endif return true; } // The indices are only used for statistical purposes. bool crn_comp::pack_alpha_endpoints( crnlib::vector<uint8>& data, const crnlib::vector<uint>& remapping, const crnlib::vector<uint>& endpoint_indices, uint trial_index) { trial_index; #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("pack_alpha_endpoints: %u", trial_index); #endif crnlib::vector<uint> remapped_endpoints(m_hvq.get_alpha_endpoint_codebook_size()); for (uint i = 0; i < m_hvq.get_alpha_endpoint_codebook_size(); i++) remapped_endpoints[remapping[i]] = m_hvq.get_alpha_endpoint(i); symbol_histogram hist; hist.resize(256); #if CRNLIB_CREATE_DEBUG_IMAGES image_u8 endpoint_image(2, m_hvq.get_alpha_endpoint_codebook_size()); image_u8 endpoint_residual_image(2, m_hvq.get_alpha_endpoint_codebook_size()); #endif crnlib::vector<uint> residual_syms; residual_syms.reserve(m_hvq.get_alpha_endpoint_codebook_size()*2*3); uint prev[2]; utils::zero_object(prev); int total_residuals = 0; for (uint endpoint_index = 0; endpoint_index < m_hvq.get_alpha_endpoint_codebook_size(); endpoint_index++) { const uint endpoint = remapped_endpoints[endpoint_index]; uint cur[2]; cur[0] = dxt5_block::unpack_endpoint(endpoint, 0); cur[1] = dxt5_block::unpack_endpoint(endpoint, 1); #if CRNLIB_CREATE_DEBUG_IMAGES endpoint_image(0, endpoint_index) = cur[0]; endpoint_image(1, endpoint_index) = cur[1]; #endif for (uint j = 0; j < 2; j++) { int delta = cur[j] - prev[j]; total_residuals += delta*delta; int sym = delta & 255; hist.inc_freq(sym); residual_syms.push_back(sym); #if CRNLIB_CREATE_DEBUG_IMAGES endpoint_residual_image(j, endpoint_index) = static_cast<uint8>(sym); #endif } prev[0] = cur[0]; prev[1] = cur[1]; } #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Total endpoint residuals: %i", total_residuals); #endif if (endpoint_indices.size() > 1) { uint prev_index = remapping[endpoint_indices[0]]; int64 total_delta = 0; for (uint i = 1; i < endpoint_indices.size(); i++) { uint cur_index = remapping[endpoint_indices[i]]; int delta = cur_index - prev_index; prev_index = cur_index; total_delta += delta * delta; } #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Total endpoint index delta: " CRNLIB_INT64_FORMAT_SPECIFIER, total_delta); #endif } #if CRNLIB_CREATE_DEBUG_IMAGES image_utils::write_to_file(dynamic_string(cVarArg, "alpha_endpoint_residuals_%u.tga", trial_index).get_ptr(), endpoint_residual_image); image_utils::write_to_file(dynamic_string(cVarArg, "alpha_endpoints_%u.tga", trial_index).get_ptr(), endpoint_image); #endif static_huffman_data_model residual_dm; symbol_codec codec; codec.start_encoding(1024*1024); // Transmit residuals if (!residual_dm.init(true, hist, 15)) return false; if (!codec.encode_transmit_static_huffman_data_model(residual_dm, false)) return false; #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Wrote %u bits for alpha endpoint residual Huffman tables", codec.encode_get_total_bits_written()); #endif uint start_bits = codec.encode_get_total_bits_written(); start_bits; for (uint i = 0; i < residual_syms.size(); i++) { const uint sym = residual_syms[i]; codec.encode(sym, residual_dm); } #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Wrote %u bits for alpha endpoint residuals", codec.encode_get_total_bits_written() - start_bits); #endif codec.stop_encoding(false); data.swap(codec.get_encoding_buf()); #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) { console::debug("Wrote a total of %u bits for alpha endpoint codebook", codec.encode_get_total_bits_written()); console::debug("Wrote %f bits per each alpha endpoint", data.size() * 8.0f / m_hvq.get_alpha_endpoint_codebook_size()); } #endif return true; } float crn_comp::color_selector_similarity_func(uint index_a, uint index_b, void* pContext) { const crnlib::vector<dxt_hc::selectors>& selectors = *static_cast< const crnlib::vector<dxt_hc::selectors>* >(pContext); const dxt_hc::selectors& selectors_a = selectors[index_a]; const dxt_hc::selectors& selectors_b = selectors[index_b]; int total = 0; for (uint i = 0; i < 16; i++) { int a = g_dxt1_to_linear[selectors_a.get_by_index(i)]; int b = g_dxt1_to_linear[selectors_b.get_by_index(i)]; int delta = a - b; total += delta*delta; } float weight = 1.0f - math::clamp(total * 1.0f/20.0f, 0.0f, 1.0f); return weight; } float crn_comp::alpha_selector_similarity_func(uint index_a, uint index_b, void* pContext) { const crnlib::vector<dxt_hc::selectors>& selectors = *static_cast< const crnlib::vector<dxt_hc::selectors>* >(pContext); const dxt_hc::selectors& selectors_a = selectors[index_a]; const dxt_hc::selectors& selectors_b = selectors[index_b]; int total = 0; for (uint i = 0; i < 16; i++) { int a = g_dxt5_to_linear[selectors_a.get_by_index(i)]; int b = g_dxt5_to_linear[selectors_b.get_by_index(i)]; int delta = a - b; total += delta*delta; } float weight = 1.0f - math::clamp(total * 1.0f/100.0f, 0.0f, 1.0f); return weight; } void crn_comp::sort_selector_codebook(crnlib::vector<uint>& remapping, const crnlib::vector<dxt_hc::selectors>& selectors, const uint8* pTo_linear) { remapping.resize(selectors.size()); uint lowest_energy = UINT_MAX; uint lowest_energy_index = 0; for (uint i = 0; i < selectors.size(); i++) { uint total = 0; for (uint j = 0; j < 16; j++) { int a = pTo_linear[selectors[i].get_by_index(j)]; total += a*a; } if (total < lowest_energy) { lowest_energy = total; lowest_energy_index = i; } } uint cur_index = lowest_energy_index; crnlib::vector<bool> chosen_flags(selectors.size()); uint n = 0; for ( ; ; ) { chosen_flags[cur_index] = true; remapping[cur_index] = n; n++; if (n == selectors.size()) break; uint lowest_error = UINT_MAX; uint lowest_error_index = 0; for (uint i = 0; i < selectors.size(); i++) { if (chosen_flags[i]) continue; uint total = 0; for (uint j = 0; j < 16; j++) { int a = pTo_linear[selectors[cur_index].get_by_index(j)]; int b = pTo_linear[selectors[i].get_by_index(j)]; int delta = a - b; total += delta*delta; } if (total < lowest_error) { lowest_error = total; lowest_error_index = i; } } cur_index = lowest_error_index; } } // The indices are only used for statistical purposes. bool crn_comp::pack_selectors( crnlib::vector<uint8>& packed_data, const crnlib::vector<uint>& selector_indices, const crnlib::vector<dxt_hc::selectors>& selectors, const crnlib::vector<uint>& remapping, uint max_selector_value, const uint8* pTo_linear, uint trial_index) { trial_index; #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("pack_selectors: %u", trial_index); #endif crnlib::vector<dxt_hc::selectors> remapped_selectors(selectors.size()); for (uint i = 0; i < selectors.size(); i++) remapped_selectors[remapping[i]] = selectors[i]; #if CRNLIB_CREATE_DEBUG_IMAGES image_u8 residual_image(16, selectors.size());; image_u8 selector_image(16, selectors.size());; #endif crnlib::vector<uint> residual_syms; residual_syms.reserve(selectors.size() * 8); const uint num_baised_selector_values = (max_selector_value * 2 + 1); symbol_histogram hist(num_baised_selector_values * num_baised_selector_values); dxt_hc::selectors prev_selectors; utils::zero_object(prev_selectors); int total_residuals = 0; for (uint selector_index = 0; selector_index < selectors.size(); selector_index++) { const dxt_hc::selectors& s = remapped_selectors[selector_index]; uint prev_sym = 0; for (uint i = 0; i < 16; i++) { int p = pTo_linear[crnlib_assert_range_incl<uint>(prev_selectors.get_by_index(i), max_selector_value)]; int r = pTo_linear[crnlib_assert_range_incl<uint>(s.get_by_index(i), max_selector_value)] - p; total_residuals += r*r; uint sym = r + max_selector_value; CRNLIB_ASSERT(sym < num_baised_selector_values); if (i & 1) { uint paired_sym = (sym * num_baised_selector_values) + prev_sym; residual_syms.push_back(paired_sym); hist.inc_freq(paired_sym); } else prev_sym = sym; #if CRNLIB_CREATE_DEBUG_IMAGES selector_image(i, selector_index) = (pTo_linear[crnlib_assert_range_incl<uint>(s.get_by_index(i), max_selector_value)] * 255) / max_selector_value; residual_image(i, selector_index) = sym; #endif } prev_selectors = s; } #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Total selector endpoint residuals: %u", total_residuals); #endif if (selector_indices.size() > 1) { uint prev_index = remapping[selector_indices[1]]; int64 total_delta = 0; for (uint i = 1; i < selector_indices.size(); i++) { uint cur_index = remapping[selector_indices[i]]; int delta = cur_index - prev_index; prev_index = cur_index; total_delta += delta * delta; } #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Total selector index delta: " CRNLIB_INT64_FORMAT_SPECIFIER, total_delta); #endif } #if CRNLIB_CREATE_DEBUG_IMAGES image_utils::write_to_file(dynamic_string(cVarArg, "selectors_%u_%u.tga", trial_index, max_selector_value).get_ptr(), selector_image); image_utils::write_to_file(dynamic_string(cVarArg, "selector_residuals_%u_%u.tga", trial_index, max_selector_value).get_ptr(), residual_image); #endif static_huffman_data_model residual_dm; symbol_codec codec; codec.start_encoding(1024*1024); // Transmit residuals if (!residual_dm.init(true, hist, 15)) return false; if (!codec.encode_transmit_static_huffman_data_model(residual_dm, false)) return false; #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Wrote %u bits for selector residual Huffman tables", codec.encode_get_total_bits_written()); #endif uint start_bits = codec.encode_get_total_bits_written(); start_bits; for (uint i = 0; i < residual_syms.size(); i++) { const uint sym = residual_syms[i]; codec.encode(sym, residual_dm); } #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Wrote %u bits for selector residuals", codec.encode_get_total_bits_written() - start_bits); #endif codec.stop_encoding(false); packed_data.swap(codec.get_encoding_buf()); #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) { console::debug("Wrote a total of %u bits for selector codebook", codec.encode_get_total_bits_written()); console::debug("Wrote %f bits per each selector codebook entry", packed_data.size() * 8.0f / selectors.size()); } #endif return true; } bool crn_comp::pack_chunks( uint first_chunk, uint num_chunks, bool clear_histograms, symbol_codec* pCodec, const crnlib::vector<uint>* pColor_endpoint_remap, const crnlib::vector<uint>* pColor_selector_remap, const crnlib::vector<uint>* pAlpha_endpoint_remap, const crnlib::vector<uint>* pAlpha_selector_remap) { if (!pCodec) { m_chunk_encoding_hist.resize(1 << (3 * cEncodingMapNumChunksPerCode)); if (clear_histograms) m_chunk_encoding_hist.set_all(0); if (pColor_endpoint_remap) { CRNLIB_ASSERT(pColor_endpoint_remap->size() == m_hvq.get_color_endpoint_codebook_size()); m_endpoint_index_hist[0].resize(pColor_endpoint_remap->size()); if (clear_histograms) m_endpoint_index_hist[0].set_all(0); } if (pColor_selector_remap) { CRNLIB_ASSERT(pColor_selector_remap->size() == m_hvq.get_color_selector_codebook_size()); m_selector_index_hist[0].resize(pColor_selector_remap->size()); if (clear_histograms) m_selector_index_hist[0].set_all(0); } if (pAlpha_endpoint_remap) { CRNLIB_ASSERT(pAlpha_endpoint_remap->size() == m_hvq.get_alpha_endpoint_codebook_size()); m_endpoint_index_hist[1].resize(pAlpha_endpoint_remap->size()); if (clear_histograms) m_endpoint_index_hist[1].set_all(0); } if (pAlpha_selector_remap) { CRNLIB_ASSERT(pAlpha_selector_remap->size() == m_hvq.get_alpha_selector_codebook_size()); m_selector_index_hist[1].resize(pAlpha_selector_remap->size()); if (clear_histograms) m_selector_index_hist[1].set_all(0); } } uint prev_endpoint_index[cNumComps]; utils::zero_object(prev_endpoint_index); uint prev_selector_index[cNumComps]; utils::zero_object(prev_selector_index); uint num_encodings_left = 0; for (uint chunk_index = first_chunk; chunk_index < (first_chunk + num_chunks); chunk_index++) { if (!num_encodings_left) { uint index = 0; for (uint i = 0; i < cEncodingMapNumChunksPerCode; i++) if ((chunk_index + i) < (first_chunk + num_chunks)) index |= (m_hvq.get_chunk_encoding(chunk_index + i).m_encoding_index << (i * 3)); if (pCodec) pCodec->encode(index, m_chunk_encoding_dm); else m_chunk_encoding_hist.inc_freq(index); num_encodings_left = cEncodingMapNumChunksPerCode; } num_encodings_left--; const dxt_hc::chunk_encoding& encoding = m_hvq.get_chunk_encoding(chunk_index); const chunk_detail& details = m_chunk_details[chunk_index]; const uint comp_order[3] = { cAlpha0, cAlpha1, cColor }; for (uint c = 0; c < 3; c++) { const uint comp_index = comp_order[c]; if (!m_has_comp[comp_index]) continue; // endpoints if (comp_index == cColor) { if (pColor_endpoint_remap) { for (uint i = 0; i < encoding.m_num_tiles; i++) { uint cur_endpoint_index = (*pColor_endpoint_remap)[ m_endpoint_indices[cColor][details.m_first_endpoint_index + i] ]; int endpoint_delta = cur_endpoint_index - prev_endpoint_index[cColor]; int sym = endpoint_delta; if (sym < 0) sym += pColor_endpoint_remap->size(); CRNLIB_ASSERT(sym >= 0 && sym < (int)pColor_endpoint_remap->size()); if (!pCodec) m_endpoint_index_hist[cColor].inc_freq(sym); else pCodec->encode(sym, m_endpoint_index_dm[0]); prev_endpoint_index[cColor] = cur_endpoint_index; } } } else { if (pAlpha_endpoint_remap) { for (uint i = 0; i < encoding.m_num_tiles; i++) { uint cur_endpoint_index = (*pAlpha_endpoint_remap)[m_endpoint_indices[comp_index][details.m_first_endpoint_index + i]]; int endpoint_delta = cur_endpoint_index - prev_endpoint_index[comp_index]; int sym = endpoint_delta; if (sym < 0) sym += pAlpha_endpoint_remap->size(); CRNLIB_ASSERT(sym >= 0 && sym < (int)pAlpha_endpoint_remap->size()); if (!pCodec) m_endpoint_index_hist[1].inc_freq(sym); else pCodec->encode(sym, m_endpoint_index_dm[1]); prev_endpoint_index[comp_index] = cur_endpoint_index; } } } } // c // selectors for (uint y = 0; y < 2; y++) { for (uint x = 0; x < 2; x++) { for (uint c = 0; c < 3; c++) { const uint comp_index = comp_order[c]; if (!m_has_comp[comp_index]) continue; if (comp_index == cColor) { if (pColor_selector_remap) { uint cur_selector_index = (*pColor_selector_remap)[ m_selector_indices[cColor][details.m_first_selector_index + x + y * 2] ]; int selector_delta = cur_selector_index - prev_selector_index[cColor]; int sym = selector_delta; if (sym < 0) sym += pColor_selector_remap->size(); CRNLIB_ASSERT(sym >= 0 && sym < (int)pColor_selector_remap->size()); if (!pCodec) m_selector_index_hist[cColor].inc_freq(sym); else pCodec->encode(sym, m_selector_index_dm[cColor]); prev_selector_index[cColor] = cur_selector_index; } } else if (pAlpha_selector_remap) { uint cur_selector_index = (*pAlpha_selector_remap)[ m_selector_indices[comp_index][details.m_first_selector_index + x + y * 2] ]; int selector_delta = cur_selector_index - prev_selector_index[comp_index]; int sym = selector_delta; if (sym < 0) sym += pAlpha_selector_remap->size(); CRNLIB_ASSERT(sym >= 0 && sym < (int)pAlpha_selector_remap->size()); if (!pCodec) m_selector_index_hist[1].inc_freq(sym); else pCodec->encode(sym, m_selector_index_dm[1]); prev_selector_index[comp_index] = cur_selector_index; } } // c } // x } // y } // chunk_index return true; } bool crn_comp::pack_chunks_simulation( uint first_chunk, uint num_chunks, uint& total_bits, const crnlib::vector<uint>* pColor_endpoint_remap, const crnlib::vector<uint>* pColor_selector_remap, const crnlib::vector<uint>* pAlpha_endpoint_remap, const crnlib::vector<uint>* pAlpha_selector_remap) { if (!pack_chunks(first_chunk, num_chunks, true, NULL, pColor_endpoint_remap, pColor_selector_remap, pAlpha_endpoint_remap, pAlpha_selector_remap)) return false; symbol_codec codec; codec.start_encoding(2*1024*1024); codec.encode_enable_simulation(true); m_chunk_encoding_dm.init(true, m_chunk_encoding_hist, 16); for (uint i = 0; i < 2; i++) { if (m_endpoint_index_hist[i].size()) { m_endpoint_index_dm[i].init(true, m_endpoint_index_hist[i], 16); codec.encode_transmit_static_huffman_data_model(m_endpoint_index_dm[i], false); } if (m_selector_index_hist[i].size()) { m_selector_index_dm[i].init(true, m_selector_index_hist[i], 16); codec.encode_transmit_static_huffman_data_model(m_selector_index_dm[i], false); } } if (!pack_chunks(first_chunk, num_chunks, false, &codec, pColor_endpoint_remap, pColor_selector_remap, pAlpha_endpoint_remap, pAlpha_selector_remap)) return false; codec.stop_encoding(false); total_bits = codec.encode_get_total_bits_written(); return true; } void crn_comp::append_vec(crnlib::vector<uint8>& a, const void* p, uint size) { if (size) { uint ofs = a.size(); a.resize(ofs + size); memcpy(&a[ofs], p, size); } } void crn_comp::append_vec(crnlib::vector<uint8>& a, const crnlib::vector<uint8>& b) { if (!b.empty()) { uint ofs = a.size(); a.resize(ofs + b.size()); memcpy(&a[ofs], &b[0], b.size()); } } #if 0 bool crn_comp::init_chunk_encoding_dm() { symbol_histogram hist(1 << (3 * cEncodingMapNumChunksPerCode)); for (uint chunk_index = 0; chunk_index < m_hvq.get_num_chunks(); chunk_index += cEncodingMapNumChunksPerCode) { uint index = 0; for (uint i = 0; i < cEncodingMapNumChunksPerCode; i++) { if ((chunk_index + i) >= m_hvq.get_num_chunks()) break; const dxt_hc::chunk_encoding& encoding = m_hvq.get_chunk_encoding(chunk_index + i); index |= (encoding.m_encoding_index << (i * 3)); } hist.inc_freq(index); } if (!m_chunk_encoding_dm.init(true, hist, 16)) return false; return true; } #endif bool crn_comp::alias_images() { for (uint face_index = 0; face_index < m_pParams->m_faces; face_index++) { for (uint level_index = 0; level_index < m_pParams->m_levels; level_index++) { const uint width = math::maximum(1U, m_pParams->m_width >> level_index); const uint height = math::maximum(1U, m_pParams->m_height >> level_index); if (!m_pParams->m_pImages[face_index][level_index]) return false; m_images[face_index][level_index].alias((color_quad_u8*)m_pParams->m_pImages[face_index][level_index], width, height); } } image_utils::conversion_type conv_type = image_utils::get_image_conversion_type_from_crn_format((crn_format)m_pParams->m_format); if (conv_type != image_utils::cConversion_Invalid) { for (uint face_index = 0; face_index < m_pParams->m_faces; face_index++) { for (uint level_index = 0; level_index < m_pParams->m_levels; level_index++) { image_u8 cooked_image(m_images[face_index][level_index]); image_utils::convert_image(cooked_image, conv_type); m_images[face_index][level_index].swap(cooked_image); } } } m_mip_groups.clear(); m_mip_groups.resize(m_pParams->m_levels); utils::zero_object(m_levels); uint mip_group = 0; uint chunk_index = 0; uint mip_group_chunk_index = 0; (void)mip_group_chunk_index; for (uint level_index = 0; level_index < m_pParams->m_levels; level_index++) { const uint width = math::maximum(1U, m_pParams->m_width >> level_index); const uint height = math::maximum(1U, m_pParams->m_height >> level_index); const uint chunk_width = math::align_up_value(width, cChunkPixelWidth) / cChunkPixelWidth; const uint chunk_height = math::align_up_value(height, cChunkPixelHeight) / cChunkPixelHeight; const uint num_chunks = m_pParams->m_faces * chunk_width * chunk_height; m_mip_groups[mip_group].m_first_chunk = chunk_index; mip_group_chunk_index = 0; m_mip_groups[mip_group].m_num_chunks += num_chunks; m_levels[level_index].m_width = width; m_levels[level_index].m_height = height; m_levels[level_index].m_chunk_width = chunk_width; m_levels[level_index].m_chunk_height = chunk_height; m_levels[level_index].m_first_chunk = chunk_index; m_levels[level_index].m_num_chunks = num_chunks; m_levels[level_index].m_group_index = mip_group; m_levels[level_index].m_group_first_chunk = 0; chunk_index += num_chunks; mip_group++; } m_total_chunks = chunk_index; return true; } void crn_comp::append_chunks(const image_u8& img, uint num_chunks_x, uint num_chunks_y, dxt_hc::pixel_chunk_vec& chunks, float weight) { for (uint y = 0; y < num_chunks_y; y++) { int x_start = 0; int x_end = num_chunks_x; int x_dir = 1; if (y & 1) { x_start = num_chunks_x - 1; x_end = -1; x_dir = -1; } for (int x = x_start; x != x_end; x += x_dir) { chunks.resize(chunks.size() + 1); dxt_hc::pixel_chunk& chunk = chunks.back(); chunk.m_weight = weight; for (uint cy = 0; cy < cChunkPixelHeight; cy++) { uint py = y * cChunkPixelHeight + cy; py = math::minimum(py, img.get_height() - 1); for (uint cx = 0; cx < cChunkPixelWidth; cx++) { uint px = x * cChunkPixelWidth + cx; px = math::minimum(px, img.get_width() - 1); chunk(cx, cy) = img(px, py); } } } } } void crn_comp::create_chunks() { m_chunks.reserve(m_total_chunks); m_chunks.resize(0); for (uint level = 0; level < m_pParams->m_levels; level++) { for (uint face = 0; face < m_pParams->m_faces; face++) { if (!face) { CRNLIB_ASSERT(m_levels[level].m_first_chunk == m_chunks.size()); } float mip_weight = math::minimum(12.0f, powf( 1.3f, static_cast<float>(level) ) ); //float mip_weight = 1.0f; append_chunks(m_images[face][level], m_levels[level].m_chunk_width, m_levels[level].m_chunk_height, m_chunks, mip_weight); } } CRNLIB_ASSERT(m_chunks.size() == m_total_chunks); } void crn_comp::clear() { m_pParams = NULL; for (uint f = 0; f < cCRNMaxFaces; f++) for (uint l = 0; l < cCRNMaxLevels; l++) m_images[f][l].clear(); utils::zero_object(m_levels); m_mip_groups.clear(); utils::zero_object(m_has_comp); m_chunk_details.clear(); for (uint i = 0; i < cNumComps; i++) { m_endpoint_indices[i].clear(); m_selector_indices[i].clear(); } m_total_chunks = 0; m_chunks.clear(); utils::zero_object(m_crn_header); m_comp_data.clear(); m_hvq.clear(); m_chunk_encoding_hist.clear(); m_chunk_encoding_dm.clear(); for (uint i = 0; i < 2; i++) { m_endpoint_index_hist[i].clear(); m_endpoint_index_dm[i].clear(); m_selector_index_hist[i].clear(); m_selector_index_dm[i].clear(); } for (uint i = 0; i < cCRNMaxLevels; i++) m_packed_chunks[i].clear(); m_packed_data_models.clear(); m_packed_color_endpoints.clear(); m_packed_color_selectors.clear(); m_packed_alpha_endpoints.clear(); m_packed_alpha_selectors.clear(); } bool crn_comp::quantize_chunks() { dxt_hc::params params; params.m_adaptive_tile_alpha_psnr_derating = m_pParams->m_crn_adaptive_tile_alpha_psnr_derating; params.m_adaptive_tile_color_psnr_derating = m_pParams->m_crn_adaptive_tile_color_psnr_derating; if (m_pParams->m_flags & cCRNCompFlagManualPaletteSizes) { params.m_color_endpoint_codebook_size = math::clamp<int>(m_pParams->m_crn_color_endpoint_palette_size, cCRNMinPaletteSize, cCRNMaxPaletteSize); params.m_color_selector_codebook_size = math::clamp<int>(m_pParams->m_crn_color_selector_palette_size, cCRNMinPaletteSize, cCRNMaxPaletteSize); params.m_alpha_endpoint_codebook_size = math::clamp<int>(m_pParams->m_crn_alpha_endpoint_palette_size, cCRNMinPaletteSize, cCRNMaxPaletteSize); params.m_alpha_selector_codebook_size = math::clamp<int>(m_pParams->m_crn_alpha_selector_palette_size, cCRNMinPaletteSize, cCRNMaxPaletteSize); } else { uint max_codebook_entries = ((m_pParams->m_width + 3) / 4) * ((m_pParams->m_height + 3) / 4); max_codebook_entries = math::clamp<uint>(max_codebook_entries, cCRNMinPaletteSize, cCRNMaxPaletteSize); float quality = math::clamp<float>((float)m_pParams->m_quality_level / cCRNMaxQualityLevel, 0.0f, 1.0f); float color_quality_power_mul = 1.0f; float alpha_quality_power_mul = 1.0f; if (m_pParams->m_format == cCRNFmtDXT5_CCxY) { color_quality_power_mul = 3.5f; alpha_quality_power_mul = .35f; params.m_adaptive_tile_color_psnr_derating = 5.0f; } else if (m_pParams->m_format == cCRNFmtDXT5) color_quality_power_mul = .75f; float color_endpoint_quality = powf(quality, 1.8f * color_quality_power_mul); float color_selector_quality = powf(quality, 1.65f * color_quality_power_mul); params.m_color_endpoint_codebook_size = math::clamp<uint>(math::float_to_uint(.5f + math::lerp<float>(math::maximum<float>(64, cCRNMinPaletteSize), (float)max_codebook_entries, color_endpoint_quality)), cCRNMinPaletteSize, cCRNMaxPaletteSize); params.m_color_selector_codebook_size = math::clamp<uint>(math::float_to_uint(.5f + math::lerp<float>(math::maximum<float>(96, cCRNMinPaletteSize), (float)max_codebook_entries, color_selector_quality)), cCRNMinPaletteSize, cCRNMaxPaletteSize); float alpha_endpoint_quality = powf(quality, 2.1f * alpha_quality_power_mul); float alpha_selector_quality = powf(quality, 1.65f * alpha_quality_power_mul); params.m_alpha_endpoint_codebook_size = math::clamp<uint>(math::float_to_uint(.5f + math::lerp<float>(math::maximum<float>(24, cCRNMinPaletteSize), (float)max_codebook_entries, alpha_endpoint_quality)), cCRNMinPaletteSize, cCRNMaxPaletteSize);; params.m_alpha_selector_codebook_size = math::clamp<uint>(math::float_to_uint(.5f + math::lerp<float>(math::maximum<float>(48, cCRNMinPaletteSize), (float)max_codebook_entries, alpha_selector_quality)), cCRNMinPaletteSize, cCRNMaxPaletteSize);; } if (m_pParams->m_flags & cCRNCompFlagDebugging) { console::debug("Color endpoints: %u", params.m_color_endpoint_codebook_size); console::debug("Color selectors: %u", params.m_color_selector_codebook_size); console::debug("Alpha endpoints: %u", params.m_alpha_endpoint_codebook_size); console::debug("Alpha selectors: %u", params.m_alpha_selector_codebook_size); } params.m_hierarchical = (m_pParams->m_flags & cCRNCompFlagHierarchical) != 0; params.m_perceptual = (m_pParams->m_flags & cCRNCompFlagPerceptual) != 0; params.m_pProgress_func = m_pParams->m_pProgress_func; params.m_pProgress_func_data = m_pParams->m_pProgress_func_data; switch (m_pParams->m_format) { case cCRNFmtDXT1: { params.m_format = cDXT1; m_has_comp[cColor] = true; break; } case cCRNFmtDXT3: { m_has_comp[cAlpha0] = true; return false; } case cCRNFmtDXT5: { params.m_format = cDXT5; params.m_alpha_component_indices[0] = m_pParams->m_alpha_component; m_has_comp[cColor] = true; m_has_comp[cAlpha0] = true; break; } case cCRNFmtDXT5_CCxY: { params.m_format = cDXT5; params.m_alpha_component_indices[0] = 3; m_has_comp[cColor] = true; m_has_comp[cAlpha0] = true; params.m_perceptual = false; //params.m_adaptive_tile_color_alpha_weighting_ratio = 1.0f; params.m_adaptive_tile_color_alpha_weighting_ratio = 1.5f; break; } case cCRNFmtDXT5_xGBR: case cCRNFmtDXT5_AGBR: case cCRNFmtDXT5_xGxR: { params.m_format = cDXT5; params.m_alpha_component_indices[0] = 3; m_has_comp[cColor] = true; m_has_comp[cAlpha0] = true; params.m_perceptual = false; break; } case cCRNFmtDXN_XY: { params.m_format = cDXN_XY; params.m_alpha_component_indices[0] = 0; params.m_alpha_component_indices[1] = 1; m_has_comp[cAlpha0] = true; m_has_comp[cAlpha1] = true; params.m_perceptual = false; break; } case cCRNFmtDXN_YX: { params.m_format = cDXN_YX; params.m_alpha_component_indices[0] = 1; params.m_alpha_component_indices[1] = 0; m_has_comp[cAlpha0] = true; m_has_comp[cAlpha1] = true; params.m_perceptual = false; break; } case cCRNFmtDXT5A: { params.m_format = cDXT5A; params.m_alpha_component_indices[0] = m_pParams->m_alpha_component; m_has_comp[cAlpha0] = true; params.m_perceptual = false; break; } case cCRNFmtETC1: { console::warning("crn_comp::quantize_chunks: This class does not support ETC1"); return false; } default: { return false; } } params.m_debugging = (m_pParams->m_flags & cCRNCompFlagDebugging) != 0; params.m_num_levels = m_pParams->m_levels; for (uint i = 0; i < m_pParams->m_levels; i++) { params.m_levels[i].m_first_chunk = m_levels[i].m_first_chunk; params.m_levels[i].m_num_chunks = m_levels[i].m_num_chunks; } if (!m_hvq.compress(params, m_total_chunks, &m_chunks[0], m_task_pool)) return false; #if CRNLIB_CREATE_DEBUG_IMAGES if (params.m_debugging) { const dxt_hc::pixel_chunk_vec& pixel_chunks = m_hvq.get_compressed_chunk_pixels_final(); image_u8 img; dxt_hc::create_debug_image_from_chunks((m_pParams->m_width+7)>>3, (m_pParams->m_height+7)>>3, pixel_chunks, &m_hvq.get_chunk_encoding_vec(), img, true, -1); image_utils::write_to_file("quantized_chunks.tga", img); } #endif return true; } void crn_comp::create_chunk_indices() { m_chunk_details.resize(m_total_chunks); for (uint i = 0; i < cNumComps; i++) { m_endpoint_indices[i].clear(); m_selector_indices[i].clear(); } for (uint chunk_index = 0; chunk_index < m_total_chunks; chunk_index++) { const dxt_hc::chunk_encoding& chunk_encoding = m_hvq.get_chunk_encoding(chunk_index); for (uint i = 0; i < cNumComps; i++) { if (m_has_comp[i]) { m_chunk_details[chunk_index].m_first_endpoint_index = m_endpoint_indices[i].size(); m_chunk_details[chunk_index].m_first_selector_index = m_selector_indices[i].size(); break; } } for (uint i = 0; i < cNumComps; i++) { if (!m_has_comp[i]) continue; for (uint tile_index = 0; tile_index < chunk_encoding.m_num_tiles; tile_index++) m_endpoint_indices[i].push_back(chunk_encoding.m_endpoint_indices[i][tile_index]); for (uint y = 0; y < cChunkBlockHeight; y++) for (uint x = 0; x < cChunkBlockWidth; x++) m_selector_indices[i].push_back(chunk_encoding.m_selector_indices[i][y][x]); } } } struct optimize_color_endpoint_codebook_params { crnlib::vector<uint>* m_pTrial_color_endpoint_remap; uint m_iter_index; uint m_max_iter_index; }; void crn_comp::optimize_color_endpoint_codebook_task(uint64 data, void* pData_ptr) { data; optimize_color_endpoint_codebook_params* pParams = reinterpret_cast<optimize_color_endpoint_codebook_params*>(pData_ptr); if (pParams->m_iter_index == pParams->m_max_iter_index) { sort_color_endpoint_codebook(*pParams->m_pTrial_color_endpoint_remap, m_hvq.get_color_endpoint_vec()); } else { float f = pParams->m_iter_index / static_cast<float>(pParams->m_max_iter_index - 1); create_zeng_reorder_table( m_hvq.get_color_endpoint_codebook_size(), m_endpoint_indices[cColor].size(), &m_endpoint_indices[cColor][0], *pParams->m_pTrial_color_endpoint_remap, pParams->m_iter_index ? color_endpoint_similarity_func : NULL, &m_hvq, f); } crnlib_delete(pParams); } bool crn_comp::optimize_color_endpoint_codebook(crnlib::vector<uint>& remapping) { if (m_pParams->m_flags & cCRNCompFlagQuick) { remapping.resize(m_hvq.get_color_endpoint_vec().size()); for (uint i = 0; i < m_hvq.get_color_endpoint_vec().size(); i++) remapping[i] = i; if (!pack_color_endpoints(m_packed_color_endpoints, remapping, m_endpoint_indices[cColor], 0)) return false; return true; } const uint cMaxEndpointRemapIters = 3; uint best_bits = UINT_MAX; #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("----- Begin optimization of color endpoint codebook"); #endif crnlib::vector<uint> trial_color_endpoint_remaps[cMaxEndpointRemapIters + 1]; for (uint i = 0; i <= cMaxEndpointRemapIters; i++) { optimize_color_endpoint_codebook_params* pParams = crnlib_new<optimize_color_endpoint_codebook_params>(); pParams->m_iter_index = i; pParams->m_max_iter_index = cMaxEndpointRemapIters; pParams->m_pTrial_color_endpoint_remap = &trial_color_endpoint_remaps[i]; m_task_pool.queue_object_task(this, &crn_comp::optimize_color_endpoint_codebook_task, 0, pParams); } m_task_pool.join(); for (uint i = 0; i <= cMaxEndpointRemapIters; i++) { if (!update_progress(20, i, cMaxEndpointRemapIters+1)) return false; crnlib::vector<uint>& trial_color_endpoint_remap = trial_color_endpoint_remaps[i]; crnlib::vector<uint8> packed_data; if (!pack_color_endpoints(packed_data, trial_color_endpoint_remap, m_endpoint_indices[cColor], i)) return false; uint total_packed_chunk_bits; if (!pack_chunks_simulation(0, m_total_chunks, total_packed_chunk_bits, &trial_color_endpoint_remap, NULL, NULL, NULL)) return false; #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Pack chunks simulation: %u bits", total_packed_chunk_bits); #endif uint total_bits = packed_data.size() * 8 + total_packed_chunk_bits; #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Total bits: %u", total_bits); #endif if (total_bits < best_bits) { m_packed_color_endpoints.swap(packed_data); remapping.swap(trial_color_endpoint_remap); best_bits = total_bits; } } #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("End optimization of color endpoint codebook"); #endif return true; } struct optimize_color_selector_codebook_params { crnlib::vector<uint>* m_pTrial_color_selector_remap; uint m_iter_index; uint m_max_iter_index; }; void crn_comp::optimize_color_selector_codebook_task(uint64 data, void* pData_ptr) { data; optimize_color_selector_codebook_params* pParams = reinterpret_cast<optimize_color_selector_codebook_params*>(pData_ptr); if (pParams->m_iter_index == pParams->m_max_iter_index) { sort_selector_codebook(*pParams->m_pTrial_color_selector_remap, m_hvq.get_color_selectors_vec(), g_dxt1_to_linear); } else { float f = pParams->m_iter_index / static_cast<float>(pParams->m_max_iter_index - 1); create_zeng_reorder_table( m_hvq.get_color_selector_codebook_size(), m_selector_indices[cColor].size(), &m_selector_indices[cColor][0], *pParams->m_pTrial_color_selector_remap, pParams->m_iter_index ? color_selector_similarity_func : NULL, (void*)&m_hvq.get_color_selectors_vec(), f); } crnlib_delete(pParams); } bool crn_comp::optimize_color_selector_codebook(crnlib::vector<uint>& remapping) { if (m_pParams->m_flags & cCRNCompFlagQuick) { remapping.resize(m_hvq.get_color_selectors_vec().size()); for (uint i = 0; i < m_hvq.get_color_selectors_vec().size(); i++) remapping[i] = i; if (!pack_selectors( m_packed_color_selectors, m_selector_indices[cColor], m_hvq.get_color_selectors_vec(), remapping, 3, g_dxt1_to_linear, 0)) { return false; } return true; } const uint cMaxSelectorRemapIters = 3; uint best_bits = UINT_MAX; #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("----- Begin optimization of color selector codebook"); #endif crnlib::vector<uint> trial_color_selector_remaps[cMaxSelectorRemapIters + 1]; for (uint i = 0; i <= cMaxSelectorRemapIters; i++) { optimize_color_selector_codebook_params* pParams = crnlib_new<optimize_color_selector_codebook_params>(); pParams->m_iter_index = i; pParams->m_max_iter_index = cMaxSelectorRemapIters; pParams->m_pTrial_color_selector_remap = &trial_color_selector_remaps[i]; m_task_pool.queue_object_task(this, &crn_comp::optimize_color_selector_codebook_task, 0, pParams); } m_task_pool.join(); for (uint i = 0; i <= cMaxSelectorRemapIters; i++) { if (!update_progress(21, i, cMaxSelectorRemapIters+1)) return false; crnlib::vector<uint>& trial_color_selector_remap = trial_color_selector_remaps[i]; crnlib::vector<uint8> packed_data; if (!pack_selectors( packed_data, m_selector_indices[cColor], m_hvq.get_color_selectors_vec(), trial_color_selector_remap, 3, g_dxt1_to_linear, i)) { return false; } uint total_packed_chunk_bits; if (!pack_chunks_simulation(0, m_total_chunks, total_packed_chunk_bits, NULL, &trial_color_selector_remap, NULL, NULL)) return false; #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Pack chunks simulation: %u bits", total_packed_chunk_bits); #endif uint total_bits = packed_data.size() * 8 + total_packed_chunk_bits; #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Total bits: %u", total_bits); #endif if (total_bits < best_bits) { m_packed_color_selectors.swap(packed_data); remapping.swap(trial_color_selector_remap); best_bits = total_bits; } } #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("End optimization of color selector codebook"); #endif return true; } struct optimize_alpha_endpoint_codebook_params { crnlib::vector<uint>* m_pAlpha_indices; crnlib::vector<uint>* m_pTrial_alpha_endpoint_remap; uint m_iter_index; uint m_max_iter_index; }; void crn_comp::optimize_alpha_endpoint_codebook_task(uint64 data, void* pData_ptr) { data; optimize_alpha_endpoint_codebook_params* pParams = reinterpret_cast<optimize_alpha_endpoint_codebook_params*>(pData_ptr); if (pParams->m_iter_index == pParams->m_max_iter_index) { sort_alpha_endpoint_codebook(*pParams->m_pTrial_alpha_endpoint_remap, m_hvq.get_alpha_endpoint_vec()); } else { float f = pParams->m_iter_index / static_cast<float>(pParams->m_max_iter_index - 1); create_zeng_reorder_table( m_hvq.get_alpha_endpoint_codebook_size(), pParams->m_pAlpha_indices->size(), &(*pParams->m_pAlpha_indices)[0], *pParams->m_pTrial_alpha_endpoint_remap, pParams->m_iter_index ? alpha_endpoint_similarity_func : NULL, &m_hvq, f); } crnlib_delete(pParams); } bool crn_comp::optimize_alpha_endpoint_codebook(crnlib::vector<uint>& remapping) { crnlib::vector<uint> alpha_indices; alpha_indices.reserve(m_endpoint_indices[cAlpha0].size() + m_endpoint_indices[cAlpha1].size()); for (uint i = 0; i < m_endpoint_indices[cAlpha0].size(); i++) alpha_indices.push_back(m_endpoint_indices[cAlpha0][i]); for (uint i = 0; i < m_endpoint_indices[cAlpha1].size(); i++) alpha_indices.push_back(m_endpoint_indices[cAlpha1][i]); if (m_pParams->m_flags & cCRNCompFlagQuick) { remapping.resize(m_hvq.get_alpha_endpoint_vec().size()); for (uint i = 0; i < m_hvq.get_alpha_endpoint_vec().size(); i++) remapping[i] = i; if (!pack_alpha_endpoints(m_packed_alpha_endpoints, remapping, alpha_indices, 0)) return false; return true; } const uint cMaxEndpointRemapIters = 3; uint best_bits = UINT_MAX; #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("----- Begin optimization of alpha endpoint codebook"); #endif crnlib::vector<uint> trial_alpha_endpoint_remaps[cMaxEndpointRemapIters + 1]; for (uint i = 0; i <= cMaxEndpointRemapIters; i++) { optimize_alpha_endpoint_codebook_params* pParams = crnlib_new<optimize_alpha_endpoint_codebook_params>(); pParams->m_pAlpha_indices = &alpha_indices; pParams->m_iter_index = i; pParams->m_max_iter_index = cMaxEndpointRemapIters; pParams->m_pTrial_alpha_endpoint_remap = &trial_alpha_endpoint_remaps[i]; m_task_pool.queue_object_task(this, &crn_comp::optimize_alpha_endpoint_codebook_task, 0, pParams); } m_task_pool.join(); for (uint i = 0; i <= cMaxEndpointRemapIters; i++) { if (!update_progress(22, i, cMaxEndpointRemapIters+1)) return false; crnlib::vector<uint>& trial_alpha_endpoint_remap = trial_alpha_endpoint_remaps[i]; crnlib::vector<uint8> packed_data; if (!pack_alpha_endpoints(packed_data, trial_alpha_endpoint_remap, alpha_indices, i)) return false; uint total_packed_chunk_bits; if (!pack_chunks_simulation(0, m_total_chunks, total_packed_chunk_bits, NULL, NULL, &trial_alpha_endpoint_remap, NULL)) return false; #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Pack chunks simulation: %u bits", total_packed_chunk_bits); #endif uint total_bits = packed_data.size() * 8 + total_packed_chunk_bits; #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Total bits: %u", total_bits); #endif if (total_bits < best_bits) { m_packed_alpha_endpoints.swap(packed_data); remapping.swap(trial_alpha_endpoint_remap); best_bits = total_bits; } } #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("End optimization of alpha endpoint codebook"); #endif return true; } struct optimize_alpha_selector_codebook_params { crnlib::vector<uint>* m_pAlpha_indices; crnlib::vector<uint>* m_pTrial_alpha_selector_remap; uint m_iter_index; uint m_max_iter_index; }; void crn_comp::optimize_alpha_selector_codebook_task(uint64 data, void* pData_ptr) { data; optimize_alpha_selector_codebook_params* pParams = reinterpret_cast<optimize_alpha_selector_codebook_params*>(pData_ptr); if (pParams->m_iter_index == pParams->m_max_iter_index) { sort_selector_codebook(*pParams->m_pTrial_alpha_selector_remap, m_hvq.get_alpha_selectors_vec(), g_dxt5_to_linear); } else { float f = pParams->m_iter_index / static_cast<float>(pParams->m_max_iter_index - 1); create_zeng_reorder_table( m_hvq.get_alpha_selector_codebook_size(), pParams->m_pAlpha_indices->size(), &(*pParams->m_pAlpha_indices)[0], *pParams->m_pTrial_alpha_selector_remap, pParams->m_iter_index ? alpha_selector_similarity_func : NULL, (void*)&m_hvq.get_alpha_selectors_vec(), f); } } bool crn_comp::optimize_alpha_selector_codebook(crnlib::vector<uint>& remapping) { crnlib::vector<uint> alpha_indices; alpha_indices.reserve(m_selector_indices[cAlpha0].size() + m_selector_indices[cAlpha1].size()); for (uint i = 0; i < m_selector_indices[cAlpha0].size(); i++) alpha_indices.push_back(m_selector_indices[cAlpha0][i]); for (uint i = 0; i < m_selector_indices[cAlpha1].size(); i++) alpha_indices.push_back(m_selector_indices[cAlpha1][i]); if (m_pParams->m_flags & cCRNCompFlagQuick) { remapping.resize(m_hvq.get_alpha_selectors_vec().size()); for (uint i = 0; i < m_hvq.get_alpha_selectors_vec().size(); i++) remapping[i] = i; if (!pack_selectors( m_packed_alpha_selectors, alpha_indices, m_hvq.get_alpha_selectors_vec(), remapping, 7, g_dxt5_to_linear, 0)) { return false; } return true; } const uint cMaxSelectorRemapIters = 3; uint best_bits = UINT_MAX; #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("----- Begin optimization of alpha selector codebook"); #endif crnlib::vector<uint> trial_alpha_selector_remaps[cMaxSelectorRemapIters + 1]; for (uint i = 0; i <= cMaxSelectorRemapIters; i++) { optimize_alpha_selector_codebook_params* pParams = crnlib_new<optimize_alpha_selector_codebook_params>(); pParams->m_pAlpha_indices = &alpha_indices; pParams->m_iter_index = i; pParams->m_max_iter_index = cMaxSelectorRemapIters; pParams->m_pTrial_alpha_selector_remap = &trial_alpha_selector_remaps[i]; m_task_pool.queue_object_task(this, &crn_comp::optimize_alpha_selector_codebook_task, 0, pParams); } m_task_pool.join(); for (uint i = 0; i <= cMaxSelectorRemapIters; i++) { if (!update_progress(23, i, cMaxSelectorRemapIters+1)) return false; crnlib::vector<uint>& trial_alpha_selector_remap = trial_alpha_selector_remaps[i]; crnlib::vector<uint8> packed_data; if (!pack_selectors( packed_data, alpha_indices, m_hvq.get_alpha_selectors_vec(), trial_alpha_selector_remap, 7, g_dxt5_to_linear, i)) { return false; } uint total_packed_chunk_bits; if (!pack_chunks_simulation(0, m_total_chunks, total_packed_chunk_bits, NULL, NULL, NULL, &trial_alpha_selector_remap)) return false; #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Pack chunks simulation: %u bits", total_packed_chunk_bits); #endif uint total_bits = packed_data.size() * 8 + total_packed_chunk_bits; #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("Total bits: %u", total_bits); #endif if (total_bits < best_bits) { m_packed_alpha_selectors.swap(packed_data); remapping.swap(trial_alpha_selector_remap); best_bits = total_bits; } } #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) console::debug("End optimization of alpha selector codebook"); #endif return true; } bool crn_comp::pack_data_models() { symbol_codec codec; codec.start_encoding(1024*1024); if (!codec.encode_transmit_static_huffman_data_model(m_chunk_encoding_dm, false)) return false; for (uint i = 0; i < 2; i++) { if (m_endpoint_index_dm[i].get_total_syms()) { if (!codec.encode_transmit_static_huffman_data_model(m_endpoint_index_dm[i], false)) return false; } if (m_selector_index_dm[i].get_total_syms()) { if (!codec.encode_transmit_static_huffman_data_model(m_selector_index_dm[i], false)) return false; } } codec.stop_encoding(false); m_packed_data_models.swap(codec.get_encoding_buf()); return true; } bool crn_comp::create_comp_data() { utils::zero_object(m_crn_header); m_crn_header.m_width = static_cast<uint16>(m_pParams->m_width); m_crn_header.m_height = static_cast<uint16>(m_pParams->m_height); m_crn_header.m_levels = static_cast<uint8>(m_pParams->m_levels); m_crn_header.m_faces = static_cast<uint8>(m_pParams->m_faces); m_crn_header.m_format = static_cast<uint8>(m_pParams->m_format); m_crn_header.m_userdata0 = m_pParams->m_userdata0; m_crn_header.m_userdata1 = m_pParams->m_userdata1; m_comp_data.clear(); m_comp_data.reserve(2*1024*1024); append_vec(m_comp_data, &m_crn_header, sizeof(m_crn_header)); // tack on the rest of the variable size m_level_ofs array m_comp_data.resize( m_comp_data.size() + sizeof(m_crn_header.m_level_ofs[0]) * (m_pParams->m_levels - 1) ); if (m_packed_color_endpoints.size()) { m_crn_header.m_color_endpoints.m_num = static_cast<uint16>(m_hvq.get_color_endpoint_codebook_size()); m_crn_header.m_color_endpoints.m_size = m_packed_color_endpoints.size(); m_crn_header.m_color_endpoints.m_ofs = m_comp_data.size(); append_vec(m_comp_data, m_packed_color_endpoints); } if (m_packed_color_selectors.size()) { m_crn_header.m_color_selectors.m_num = static_cast<uint16>(m_hvq.get_color_selector_codebook_size()); m_crn_header.m_color_selectors.m_size = m_packed_color_selectors.size(); m_crn_header.m_color_selectors.m_ofs = m_comp_data.size(); append_vec(m_comp_data, m_packed_color_selectors); } if (m_packed_alpha_endpoints.size()) { m_crn_header.m_alpha_endpoints.m_num = static_cast<uint16>(m_hvq.get_alpha_endpoint_codebook_size()); m_crn_header.m_alpha_endpoints.m_size = m_packed_alpha_endpoints.size(); m_crn_header.m_alpha_endpoints.m_ofs = m_comp_data.size(); append_vec(m_comp_data, m_packed_alpha_endpoints); } if (m_packed_alpha_selectors.size()) { m_crn_header.m_alpha_selectors.m_num = static_cast<uint16>(m_hvq.get_alpha_selector_codebook_size()); m_crn_header.m_alpha_selectors.m_size = m_packed_alpha_selectors.size(); m_crn_header.m_alpha_selectors.m_ofs = m_comp_data.size(); append_vec(m_comp_data, m_packed_alpha_selectors); } m_crn_header.m_tables_ofs = m_comp_data.size(); m_crn_header.m_tables_size = m_packed_data_models.size(); append_vec(m_comp_data, m_packed_data_models); uint level_ofs[cCRNMaxLevels]; for (uint i = 0; i < m_mip_groups.size(); i++) { level_ofs[i] = m_comp_data.size(); append_vec(m_comp_data, m_packed_chunks[i]); } crnd::crn_header& dst_header = *(crnd::crn_header*)&m_comp_data[0]; // don't change the m_comp_data vector - or dst_header will be invalidated! memcpy(&dst_header, &m_crn_header, sizeof(dst_header)); for (uint i = 0; i < m_mip_groups.size(); i++) dst_header.m_level_ofs[i] = level_ofs[i]; const uint actual_header_size = sizeof(crnd::crn_header) + sizeof(dst_header.m_level_ofs[0]) * (m_mip_groups.size() - 1); dst_header.m_sig = crnd::crn_header::cCRNSigValue; dst_header.m_data_size = m_comp_data.size(); dst_header.m_data_crc16 = crc16(&m_comp_data[actual_header_size], m_comp_data.size() - actual_header_size); dst_header.m_header_size = actual_header_size; dst_header.m_header_crc16 = crc16(&dst_header.m_data_size, actual_header_size - (uint)((uint8*)&dst_header.m_data_size - (uint8*)&dst_header)); return true; } bool crn_comp::update_progress(uint phase_index, uint subphase_index, uint subphase_total) { if (!m_pParams->m_pProgress_func) return true; #if CRNLIB_ENABLE_DEBUG_MESSAGES if (m_pParams->m_flags & cCRNCompFlagDebugging) return true; #endif return (*m_pParams->m_pProgress_func)(phase_index, cTotalCompressionPhases, subphase_index, subphase_total, m_pParams->m_pProgress_func_data) != 0; } bool crn_comp::compress_internal() { if (!alias_images()) return false; create_chunks(); if (!quantize_chunks()) return false; create_chunk_indices(); crnlib::vector<uint> endpoint_remap[2]; crnlib::vector<uint> selector_remap[2]; if (m_has_comp[cColor]) { if (!optimize_color_endpoint_codebook(endpoint_remap[0])) return false; if (!optimize_color_selector_codebook(selector_remap[0])) return false; } if (m_has_comp[cAlpha0]) { if (!optimize_alpha_endpoint_codebook(endpoint_remap[1])) return false; if (!optimize_alpha_selector_codebook(selector_remap[1])) return false; } m_chunk_encoding_hist.clear(); for (uint i = 0; i < 2; i++) { m_endpoint_index_hist[i].clear(); m_endpoint_index_dm[i].clear(); m_selector_index_hist[i].clear(); m_selector_index_dm[i].clear(); } for (uint pass = 0; pass < 2; pass++) { for (uint mip_group = 0; mip_group < m_mip_groups.size(); mip_group++) { symbol_codec codec; codec.start_encoding(2*1024*1024); if (!pack_chunks( m_mip_groups[mip_group].m_first_chunk, m_mip_groups[mip_group].m_num_chunks, !pass && !mip_group, pass ? &codec : NULL, m_has_comp[cColor] ? &endpoint_remap[0] : NULL, m_has_comp[cColor] ? &selector_remap[0] : NULL, m_has_comp[cAlpha0] ? &endpoint_remap[1] : NULL, m_has_comp[cAlpha0] ? &selector_remap[1] : NULL)) { return false; } codec.stop_encoding(false); if (pass) m_packed_chunks[mip_group].swap(codec.get_encoding_buf()); } if (!pass) { m_chunk_encoding_dm.init(true, m_chunk_encoding_hist, 16); for (uint i = 0; i < 2; i++) { if (m_endpoint_index_hist[i].size()) m_endpoint_index_dm[i].init(true, m_endpoint_index_hist[i], 16); if (m_selector_index_hist[i].size()) m_selector_index_dm[i].init(true, m_selector_index_hist[i], 16); } } } if (!pack_data_models()) return false; if (!create_comp_data()) return false; if (!update_progress(24, 1, 1)) return false; if (m_pParams->m_flags & cCRNCompFlagDebugging) { crnlib_print_mem_stats(); } return true; } bool crn_comp::compress_init(const crn_comp_params& params) { params; return true; } bool crn_comp::compress_pass(const crn_comp_params& params, float *pEffective_bitrate) { clear(); if (pEffective_bitrate) *pEffective_bitrate = 0.0f; m_pParams = &params; if ((math::minimum(m_pParams->m_width, m_pParams->m_height) < 1) || (math::maximum(m_pParams->m_width, m_pParams->m_height) > cCRNMaxLevelResolution)) return false; if (!m_task_pool.init(params.m_num_helper_threads)) return false; bool status = compress_internal(); m_task_pool.deinit(); if ((status) && (pEffective_bitrate)) { uint total_pixels = 0; for (uint f = 0; f < m_pParams->m_faces; f++) for (uint l = 0; l < m_pParams->m_levels; l++) total_pixels += m_images[f][l].get_total_pixels(); *pEffective_bitrate = (m_comp_data.size() * 8.0f) / total_pixels; } return status; } void crn_comp::compress_deinit() { } } // namespace crnlib
34.861404
254
0.606874
Wizermil
64b9802d6088f22721eb36a90d0fc693e318718a
10,219
cpp
C++
code/wxWidgets/src/mac/carbon/dcclient.cpp
Bloodknight/NeuTorsion
a5890e9ca145a8c1b6bec7b70047a43d9b1c29ea
[ "MIT" ]
38
2016-02-20T02:46:28.000Z
2021-11-17T11:39:57.000Z
code/wxWidgets/src/mac/carbon/dcclient.cpp
Dwarf-King/TorsionEditor
e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50
[ "MIT" ]
17
2016-02-20T02:19:55.000Z
2021-02-08T15:15:17.000Z
code/wxWidgets/src/mac/carbon/dcclient.cpp
Dwarf-King/TorsionEditor
e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50
[ "MIT" ]
46
2016-02-20T02:47:33.000Z
2021-01-31T15:46:05.000Z
///////////////////////////////////////////////////////////////////////////// // Name: dcclient.cpp // Purpose: wxClientDC class // Author: Stefan Csomor // Modified by: // Created: 01/02/97 // RCS-ID: $Id: dcclient.cpp,v 1.38 2005/05/10 06:28:21 SC Exp $ // Copyright: (c) Stefan Csomor // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma implementation "dcclient.h" #endif #include "wx/wxprec.h" #include "wx/dcclient.h" #include "wx/dcmemory.h" #include "wx/region.h" #include "wx/window.h" #include "wx/toplevel.h" #include "wx/settings.h" #include "wx/math.h" #include "wx/mac/private.h" #include "wx/log.h" //----------------------------------------------------------------------------- // constants //----------------------------------------------------------------------------- #define RAD2DEG 57.2957795131 //----------------------------------------------------------------------------- // wxPaintDC //----------------------------------------------------------------------------- IMPLEMENT_DYNAMIC_CLASS(wxWindowDC, wxDC) IMPLEMENT_DYNAMIC_CLASS(wxClientDC, wxWindowDC) IMPLEMENT_DYNAMIC_CLASS(wxPaintDC, wxWindowDC) /* * wxWindowDC */ #include "wx/mac/uma.h" #include "wx/notebook.h" #include "wx/tabctrl.h" static wxBrush MacGetBackgroundBrush( wxWindow* window ) { wxBrush bkdBrush = window->MacGetBackgroundBrush() ; #if !TARGET_API_MAC_OSX // transparency cannot be handled by the OS when not using composited windows wxWindow* parent = window->GetParent() ; // if we have some 'pseudo' transparency if ( ! bkdBrush.Ok() || bkdBrush.GetStyle() == wxTRANSPARENT || window->GetBackgroundColour() == wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE ) ) { // walk up until we find something while( parent != NULL ) { if ( parent->GetBackgroundColour() != wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE ) ) { // if we have any other colours in the hierarchy bkdBrush.SetColour( parent->GetBackgroundColour() ) ; break ; } if ( parent->IsKindOf( CLASSINFO(wxTopLevelWindow) ) ) { bkdBrush = parent->MacGetBackgroundBrush() ; break ; } if ( parent->IsKindOf( CLASSINFO( wxNotebook ) ) || parent->IsKindOf( CLASSINFO( wxTabCtrl ) ) ) { Rect extent = { 0 , 0 , 0 , 0 } ; int x , y ; x = y = 0 ; wxSize size = parent->GetSize() ; parent->MacClientToRootWindow( &x , &y ) ; extent.left = x ; extent.top = y ; extent.top-- ; extent.right = x + size.x ; extent.bottom = y + size.y ; bkdBrush.MacSetThemeBackground( kThemeBackgroundTabPane , (WXRECTPTR) &extent ) ; break ; } parent = parent->GetParent() ; } } if ( !bkdBrush.Ok() || bkdBrush.GetStyle() == wxTRANSPARENT ) { // if we did not find something, use a default bkdBrush.MacSetTheme( kThemeBrushDialogBackgroundActive ) ; } #endif return bkdBrush ; } wxWindowDC::wxWindowDC() { m_window = NULL ; } wxWindowDC::wxWindowDC(wxWindow *window) { m_window = window ; wxTopLevelWindowMac* rootwindow = window->MacGetTopLevelWindow() ; if (!rootwindow) return; WindowRef windowref = (WindowRef) rootwindow->MacGetWindowRef() ; int x , y ; x = y = 0 ; wxSize size = window->GetSize() ; window->MacWindowToRootWindow( &x , &y ) ; m_macPort = UMAGetWindowPort( windowref ) ; #if wxMAC_USE_CORE_GRAPHICS m_macLocalOriginInPort.x = x ; m_macLocalOriginInPort.y = y ; if ( window->MacGetCGContextRef() ) { m_graphicContext = new wxMacCGContext( (CGContextRef) window->MacGetCGContextRef() ) ; m_graphicContext->SetPen( m_pen ) ; m_graphicContext->SetBrush( m_brush ) ; SetBackground(MacGetBackgroundBrush(window)); } else { // as out of order redraw is not supported under CQ, we have to create a qd port for these // situations m_macLocalOrigin.x = x ; m_macLocalOrigin.y = y ; m_graphicContext = new wxMacCGContext( (CGrafPtr) m_macPort ) ; m_graphicContext->SetPen( m_pen ) ; m_graphicContext->SetBrush( m_brush ) ; SetBackground(MacGetBackgroundBrush(window)); } // there is no out-of-order drawing on OSX #else m_macLocalOrigin.x = x ; m_macLocalOrigin.y = y ; CopyRgn( (RgnHandle) window->MacGetVisibleRegion(true).GetWXHRGN() , (RgnHandle) m_macBoundaryClipRgn ) ; OffsetRgn( (RgnHandle) m_macBoundaryClipRgn , m_macLocalOrigin.x , m_macLocalOrigin.y ) ; CopyRgn( (RgnHandle) m_macBoundaryClipRgn , (RgnHandle) m_macCurrentClipRgn ) ; SetBackground(MacGetBackgroundBrush(window)); #endif m_ok = TRUE ; SetFont( window->GetFont() ) ; } wxWindowDC::~wxWindowDC() { } void wxWindowDC::DoGetSize( int* width, int* height ) const { wxCHECK_RET( m_window, _T("GetSize() doesn't work without window") ); m_window->GetSize(width, height); } /* * wxClientDC */ wxClientDC::wxClientDC() { m_window = NULL ; } wxClientDC::wxClientDC(wxWindow *window) { m_window = window ; wxTopLevelWindowMac* rootwindow = window->MacGetTopLevelWindow() ; if (!rootwindow) return; WindowRef windowref = (WindowRef) rootwindow->MacGetWindowRef() ; wxPoint origin = window->GetClientAreaOrigin() ; wxSize size = window->GetClientSize() ; int x , y ; x = origin.x ; y = origin.y ; window->MacWindowToRootWindow( &x , &y ) ; m_macPort = UMAGetWindowPort( windowref ) ; #if wxMAC_USE_CORE_GRAPHICS m_macLocalOriginInPort.x = x ; m_macLocalOriginInPort.y = y ; if ( window->MacGetCGContextRef() ) { m_graphicContext = new wxMacCGContext( (CGContextRef) window->MacGetCGContextRef() ) ; m_graphicContext->SetPen( m_pen ) ; m_graphicContext->SetBrush( m_brush ) ; m_ok = TRUE ; SetClippingRegion( 0 , 0 , size.x , size.y ) ; SetBackground(MacGetBackgroundBrush(window)); } else { // as out of order redraw is not supported under CQ, we have to create a qd port for these // situations m_macLocalOrigin.x = x ; m_macLocalOrigin.y = y ; m_graphicContext = new wxMacCGContext( (CGrafPtr) m_macPort ) ; m_graphicContext->SetPen( m_pen ) ; m_graphicContext->SetBrush( m_brush ) ; m_ok = TRUE ; } #else m_macLocalOrigin.x = x ; m_macLocalOrigin.y = y ; SetRectRgn( (RgnHandle) m_macBoundaryClipRgn , origin.x , origin.y , origin.x + size.x , origin.y + size.y ) ; SectRgn( (RgnHandle) m_macBoundaryClipRgn , (RgnHandle) window->MacGetVisibleRegion().GetWXHRGN() , (RgnHandle) m_macBoundaryClipRgn ) ; OffsetRgn( (RgnHandle) m_macBoundaryClipRgn , -origin.x , -origin.y ) ; OffsetRgn( (RgnHandle) m_macBoundaryClipRgn , m_macLocalOrigin.x , m_macLocalOrigin.y ) ; CopyRgn( (RgnHandle) m_macBoundaryClipRgn ,(RgnHandle) m_macCurrentClipRgn ) ; m_ok = TRUE ; #endif SetBackground(MacGetBackgroundBrush(window)); SetFont( window->GetFont() ) ; } wxClientDC::~wxClientDC() { #if wxMAC_USE_CORE_GRAPHICS /* if ( m_window->MacGetCGContextRef() == 0) { CGContextRef cgContext = (wxMacCGContext*)(m_graphicContext)->GetNativeContext() ; CGContextFlush( cgContext ) ; } */ #endif } void wxClientDC::DoGetSize(int *width, int *height) const { wxCHECK_RET( m_window, _T("GetSize() doesn't work without window") ); m_window->GetClientSize( width, height ); } /* * wxPaintDC */ wxPaintDC::wxPaintDC() { m_window = NULL ; } wxPaintDC::wxPaintDC(wxWindow *window) { m_window = window ; wxTopLevelWindowMac* rootwindow = window->MacGetTopLevelWindow() ; WindowRef windowref = (WindowRef) rootwindow->MacGetWindowRef() ; wxPoint origin = window->GetClientAreaOrigin() ; wxSize size = window->GetClientSize() ; int x , y ; x = origin.x ; y = origin.y ; window->MacWindowToRootWindow( &x , &y ) ; m_macPort = UMAGetWindowPort( windowref ) ; #if wxMAC_USE_CORE_GRAPHICS m_macLocalOriginInPort.x = x ; m_macLocalOriginInPort.y = y ; if ( window->MacGetCGContextRef() ) { m_graphicContext = new wxMacCGContext( (CGContextRef) window->MacGetCGContextRef() ) ; m_graphicContext->SetPen( m_pen ) ; m_graphicContext->SetBrush( m_brush ) ; m_ok = TRUE ; SetClippingRegion( 0 , 0 , size.x , size.y ) ; SetBackground(MacGetBackgroundBrush(window)); } else { wxLogDebug(wxT("You cannot create a wxPaintDC outside an OS-draw event") ) ; m_graphicContext = NULL ; m_ok = TRUE ; } // there is no out-of-order drawing on OSX #else m_macLocalOrigin.x = x ; m_macLocalOrigin.y = y ; SetRectRgn( (RgnHandle) m_macBoundaryClipRgn , origin.x , origin.y , origin.x + size.x , origin.y + size.y ) ; SectRgn( (RgnHandle) m_macBoundaryClipRgn , (RgnHandle) window->MacGetVisibleRegion().GetWXHRGN() , (RgnHandle) m_macBoundaryClipRgn ) ; OffsetRgn( (RgnHandle) m_macBoundaryClipRgn , -origin.x , -origin.y ) ; SectRgn( (RgnHandle) m_macBoundaryClipRgn , (RgnHandle) window->GetUpdateRegion().GetWXHRGN() , (RgnHandle) m_macBoundaryClipRgn ) ; OffsetRgn( (RgnHandle) m_macBoundaryClipRgn , m_macLocalOrigin.x , m_macLocalOrigin.y ) ; CopyRgn( (RgnHandle) m_macBoundaryClipRgn , (RgnHandle) m_macCurrentClipRgn ) ; SetBackground(MacGetBackgroundBrush(window)); m_ok = TRUE ; #endif SetFont( window->GetFont() ) ; } wxPaintDC::~wxPaintDC() { } void wxPaintDC::DoGetSize(int *width, int *height) const { wxCHECK_RET( m_window, _T("GetSize() doesn't work without window") ); m_window->GetClientSize( width, height ); }
32.236593
152
0.608279
Bloodknight
64ba2650b392bb85157bc79c84bdfc4d6271d775
924
cpp
C++
online_judges/ac/513B1.cpp
miaortizma/competitive-programming
ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc
[ "MIT" ]
2
2018-02-20T14:44:57.000Z
2018-02-20T14:45:03.000Z
online_judges/ac/513B1.cpp
miaortizma/competitive-programming
ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc
[ "MIT" ]
null
null
null
online_judges/ac/513B1.cpp
miaortizma/competitive-programming
ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define ll long long #define pb push_back #ifdef PAPITAS #define DEBUG 1 #else #define DEBUG 0 #endif #define _DO_(x) if(DEBUG) x int check(vector<int> v, int tetra){ int n = v.size(); int ans = 0; for(int i = 0; i < n; i++){ int temp = v[i]; for(int j = i; j < n; j++){ temp = min(temp, v[j]); ans += temp; } } if(tetra == ans){ for(int i = 0; i < n; i++){ cout << v[i] << ' '; } cout << "\n value: " << ans << '\n'; } return ans; } int main() { ios::sync_with_stdio(false);cin.tie(NULL); #ifdef PAPITAS freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); #endif ll n, m; cin >> n >> m; m--; deque<int> v; v.push_back(n); for(ll i = 0; i < n - 1; i++){ if((m & (1LL << i))){ v.push_back(n - 1LL - i); }else{ v.push_front(n - 1LL - i); } } for(int i = 0; i < n; i++){ cout << v[i] << ' '; } return 0; }
16.210526
43
0.514069
miaortizma
64ba8d65849c855dda320dd863706df83ed9ea3b
5,263
cpp
C++
test/test_no_self_trade.cpp
liutongwei/ft
c75c1ea6b4e53128248113f9810b997d2f7ff236
[ "MIT" ]
null
null
null
test/test_no_self_trade.cpp
liutongwei/ft
c75c1ea6b4e53128248113f9810b997d2f7ff236
[ "MIT" ]
null
null
null
test/test_no_self_trade.cpp
liutongwei/ft
c75c1ea6b4e53128248113f9810b997d2f7ff236
[ "MIT" ]
null
null
null
// Copyright [2020] <Copyright Kevin, [email protected]> #include <gtest/gtest.h> #include "trader/risk_management/common/no_self_trade.h" static uint64_t order_id = 1; void GenLO(ft::Order* order, ft::Direction direction, ft::Offset offset, double price) { order->req.direction = direction; order->req.offset = offset; order->req.price = price; order->req.order_id = order_id++; order->req.type = ft::OrderType::kLimit; } void GenMO(ft::Order* order, ft::Direction direction, ft::Offset offset) { order->req.direction = direction; order->req.offset = offset; order->req.price = 0; order->req.order_id = order_id++; order->req.type = ft::OrderType::kMarket; } TEST(RMS, NoSelfTrade) { ft::RiskRuleParams params{}; ft::OrderMap order_map; ft::Contract contract{}; ft::Order order{}; params.order_map = &order_map; contract.ticker = "ticker001"; order.req.contract = &contract; order.req.volume = 1; ft::NoSelfTradeRule rule; rule.Init(&params); GenLO(&order, ft::Direction::kBuy, ft::Offset::kOpen, 100.1); order_map.emplace(static_cast<uint64_t>(order.req.order_id), order); GenLO(&order, ft::Direction::kBuy, ft::Offset::kOpen, 100.1); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kBuy, ft::Offset::kOpen, 99.0); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kBuy, ft::Offset::kOpen, 110.0); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kBuy, ft::Offset::kClose, 100.1); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kBuy, ft::Offset::kClose, 99.0); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kBuy, ft::Offset::kClose, 110.0); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kBuy, ft::Offset::kCloseToday, 100.1); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kBuy, ft::Offset::kCloseToday, 99.0); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kBuy, ft::Offset::kCloseToday, 110.0); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kBuy, ft::Offset::kCloseYesterday, 100.1); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kBuy, ft::Offset::kCloseYesterday, 99.0); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kBuy, ft::Offset::kCloseYesterday, 110.0); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kSell, ft::Offset::kOpen, 110.0); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kSell, ft::Offset::kOpen, 100.1); ASSERT_EQ(ft::ERR_SELF_TRADE, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kSell, ft::Offset::kOpen, 99.0); ASSERT_EQ(ft::ERR_SELF_TRADE, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kSell, ft::Offset::kClose, 110.0); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kSell, ft::Offset::kClose, 100.1); ASSERT_EQ(ft::ERR_SELF_TRADE, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kSell, ft::Offset::kClose, 99.0); ASSERT_EQ(ft::ERR_SELF_TRADE, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kSell, ft::Offset::kCloseToday, 110.0); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kSell, ft::Offset::kCloseToday, 100.1); ASSERT_EQ(ft::ERR_SELF_TRADE, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kSell, ft::Offset::kCloseToday, 99.0); ASSERT_EQ(ft::ERR_SELF_TRADE, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kSell, ft::Offset::kCloseYesterday, 110.0); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kSell, ft::Offset::kCloseYesterday, 100.1); ASSERT_EQ(ft::ERR_SELF_TRADE, rule.CheckOrderRequest(&order)); GenLO(&order, ft::Direction::kSell, ft::Offset::kCloseYesterday, 99.0); ASSERT_EQ(ft::ERR_SELF_TRADE, rule.CheckOrderRequest(&order)); GenMO(&order, ft::Direction::kBuy, ft::Offset::kOpen); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenMO(&order, ft::Direction::kBuy, ft::Offset::kClose); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenMO(&order, ft::Direction::kBuy, ft::Offset::kCloseToday); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenMO(&order, ft::Direction::kBuy, ft::Offset::kCloseYesterday); ASSERT_EQ(ft::NO_ERROR, rule.CheckOrderRequest(&order)); GenMO(&order, ft::Direction::kSell, ft::Offset::kOpen); ASSERT_EQ(ft::ERR_SELF_TRADE, rule.CheckOrderRequest(&order)); GenMO(&order, ft::Direction::kSell, ft::Offset::kClose); ASSERT_EQ(ft::ERR_SELF_TRADE, rule.CheckOrderRequest(&order)); GenMO(&order, ft::Direction::kSell, ft::Offset::kCloseToday); ASSERT_EQ(ft::ERR_SELF_TRADE, rule.CheckOrderRequest(&order)); GenMO(&order, ft::Direction::kSell, ft::Offset::kCloseYesterday); ASSERT_EQ(ft::ERR_SELF_TRADE, rule.CheckOrderRequest(&order)); }
38.137681
88
0.714801
liutongwei
64bf749522e131dda2ce01b960f8814b85de976f
2,798
cpp
C++
2DGame/terrainImpactSystem.cpp
Cimera42/2DGame
9135e3dbed8a909357d57e227ecaba885982e8dc
[ "MIT" ]
3
2015-08-18T12:59:29.000Z
2015-12-15T08:11:10.000Z
2DGame/terrainImpactSystem.cpp
Cimera42/2DGame
9135e3dbed8a909357d57e227ecaba885982e8dc
[ "MIT" ]
null
null
null
2DGame/terrainImpactSystem.cpp
Cimera42/2DGame
9135e3dbed8a909357d57e227ecaba885982e8dc
[ "MIT" ]
null
null
null
#include "terrainImpactSystem.h" #include "globals.h" #include "colliderComponent.h" #include "worldComponent.h" #include "physicsComponent.h" #include "terrainComponent.h" #include "logger.h" //Unique system ID SystemID TerrainImpactSystem::ID; TerrainImpactSystem::TerrainImpactSystem() { std::vector<ComponentID> subList1; //Components needed to subscribe to system subList1.push_back(WorldComponent::getStaticID()); subList1.push_back(TerrainComponent::getStaticID()); addSubList(subList1); } TerrainImpactSystem::~TerrainImpactSystem(){} void TerrainImpactSystem::update() { for(int subID = 0; subID < subscribedEntities[0].size(); subID++) { //Get terrain component Entity * terrainEnt = entities[subscribedEntities[0][subID]]; TerrainComponent* terrainComp = static_cast<TerrainComponent*>(terrainEnt->getComponent(TerrainComponent::getStaticID())); WorldComponent * terrainWorldComp = static_cast<WorldComponent*>(terrainEnt->getComponent(WorldComponent::getStaticID())); //Check projectile for collisions for(int i = 0; i < terrainComp->collisionData.size(); i++) { std::shared_ptr<CollisionPair> collision = terrainComp->collisionData[i]; int terrainPairID = collision->getCollisionPairID(subscribedEntities[0][subID]);//Terrains's CollisionPairID int collidingPairID = collision->getOppositePairID(terrainPairID);//The Colliding Ent's CollisionPairID Entity * collidingEnt = entities[collision->getCollisionEntityID(collidingPairID)]; //The Colliding Entity //Check the type of the collided entity and perform action if(collidingEnt->hasComponent(PhysicsComponent::getStaticID()) && collidingEnt->hasComponent(ColliderComponent::getStaticID())) { glm::vec2 col = collision->getNormal(terrainPairID); PhysicsComponent* physicsComp = static_cast<PhysicsComponent*>(collidingEnt->getComponent(PhysicsComponent::getStaticID())); //apply an upwards impulse to keep object above ground float normalMag = glm::dot(physicsComp->velocity*physicsComp->mass,glm::normalize(col)); float j = -(1+physicsComp->coefficientRestitution)*normalMag; float impulseMag = glm::max(j, 0.0f); physicsComp->impulse(impulseMag*glm::normalize(col)); //apply friction /*glm::vec2 dir = -glm::normalize(col); glm::vec2 friction = 5.0f * normalMag * glm::vec2(-dir.y,dir.x); Logger()<<friction.x<<" "<<friction.y<<std::endl; physicsComp->force += friction;*/ } } } }
46.633333
141
0.657255
Cimera42
64c2482c1c040909cefae9c1de19c0349f2e8f03
496
cpp
C++
01-operadores-aritmeticos/17_conversion_de_modeda.cpp
gemboedu/ejercicios-basicos-c-
648e2abe4c8e7f51bbfb1d21032eeeee3f5b9343
[ "MIT" ]
1
2021-12-03T03:37:04.000Z
2021-12-03T03:37:04.000Z
01-operadores-aritmeticos/17_conversion_de_modeda.cpp
gemboedu/ejercicios-basicos-c-
648e2abe4c8e7f51bbfb1d21032eeeee3f5b9343
[ "MIT" ]
null
null
null
01-operadores-aritmeticos/17_conversion_de_modeda.cpp
gemboedu/ejercicios-basicos-c-
648e2abe4c8e7f51bbfb1d21032eeeee3f5b9343
[ "MIT" ]
null
null
null
/* 17. Juana viajará a EEUU y luego a Europa, por tanto, requiere un programa que convierta x cantidad de Bs a dólares y a euros. $1 = Bs. 6.90 1 euro = Bs. 7.79 */ #include <iostream> using namespace std; int main() { float bolivianos, dolares, euros; cout << "Ingrese la moneda boliviana: "; cin >> bolivianos; dolares = bolivianos / 6.90; euros = bolivianos / 7.79; cout << "En dolares: " << dolares << endl; cout << "En euros: " << euros << endl; return 0; }
26.105263
126
0.625
gemboedu
64c297186805285fdf248cc03771da2730d288f2
764
hpp
C++
Source/Console/ConsoleFrame.hpp
gunstarpl/Game-Engine-12-2013
bfc53f5c998311c17e97c1b4d65792d615c51d36
[ "MIT", "Unlicense" ]
6
2017-12-31T17:28:40.000Z
2021-12-04T06:11:34.000Z
Source/Console/ConsoleFrame.hpp
gunstarpl/Game-Engine-12-2013
bfc53f5c998311c17e97c1b4d65792d615c51d36
[ "MIT", "Unlicense" ]
null
null
null
Source/Console/ConsoleFrame.hpp
gunstarpl/Game-Engine-12-2013
bfc53f5c998311c17e97c1b4d65792d615c51d36
[ "MIT", "Unlicense" ]
null
null
null
#pragma once #include "Precompiled.hpp" #include "Graphics/Font.hpp" // // Console Frame // Displays and lets user interact with the console system. // class ConsoleFrame { public: ConsoleFrame(); ~ConsoleFrame(); bool Initialize(); void Cleanup(); void Open(); void Close(); bool Process(const SDL_Event& event); void Draw(const glm::mat4& transform, glm::vec2 targetSize); bool IsOpen() const { return m_open; } private: void ClearInput(); private: // Current input. std::string m_input; // Input cursor position. int m_cursorPosition; // History positions. int m_historyOutput; int m_historyInput; // Frame state. bool m_open; bool m_initialized; };
14.980392
64
0.636126
gunstarpl
64c444ea6f51e4df3c08916ff98b277fc179396f
1,489
hpp
C++
addons/CBRN_units/units/NATO/unarmed.hpp
ASO-TheM/ChemicalWarfare
51322934ef1da7ba0f3bb04c1d537767d8e48cc4
[ "MIT" ]
null
null
null
addons/CBRN_units/units/NATO/unarmed.hpp
ASO-TheM/ChemicalWarfare
51322934ef1da7ba0f3bb04c1d537767d8e48cc4
[ "MIT" ]
null
null
null
addons/CBRN_units/units/NATO/unarmed.hpp
ASO-TheM/ChemicalWarfare
51322934ef1da7ba0f3bb04c1d537767d8e48cc4
[ "MIT" ]
null
null
null
class B_Soldier_unarmed_F; class B_CBRN_Unarmed: B_Soldier_unarmed_F { scope = 1; editorSubcategory = "CBRN"; //editorPreview = "\bonusUnits_CSF\editorPreviews\O_CSF_Unarmed.jpg"; author = "Assaultboy"; hiddenSelections[] = {"camo"}; hiddenSelectionsTextures[] = {"\skn_nbc_units\data_m50\NBC_M50_Uniform_CO.paa"}; modelSides[] = {0, 1, 2, 3}; model = "\skn_nbc_units\models\skn_b_nbc_uniform.p3d"; uniformClass = "U_B_CBRN"; class EventHandlers { class CBRN_giveMask { init = "(_this select 0) addItem 'G_CBRN_M50_Hood'"; }; }; }; class B_CBRN_CTRG_GER_S_Arid_Unarmed: B_Soldier_unarmed_F { scope = 1; editorSubcategory = "CBRN"; //editorPreview = "\bonusUnits_CSF\editorPreviews\O_CSF_Unarmed.jpg"; author = "The_M"; hiddenSelections[] = {"camo"}; hiddenSelectionsTextures[] = {"\CBRN_gear\data\clothing1_CTRG_GER_arid_co.paa"}; modelSides[] = {0, 1, 2, 3}; model = "\A3\Characters_F_Exp\BLUFOR\B_CTRG_Soldier_01_F.p3d"; uniformClass = "U_B_CBRN_CTRG_GER_S_Arid"; }; class B_CBRN_CTRG_GER_S_Tropic_Unarmed: B_Soldier_unarmed_F { scope = 1; editorSubcategory = "CBRN"; //editorPreview = "\bonusUnits_CSF\editorPreviews\O_CSF_Unarmed.jpg"; author = "The_M"; hiddenSelections[] = {"camo"}; hiddenSelectionsTextures[] = {"\CBRN_gear\data\clothing1_CTRG_GER_tropic_co.paa"}; modelSides[] = {0, 1, 2, 3}; model = "\A3\Characters_F_Exp\BLUFOR\B_CTRG_Soldier_01_F.p3d"; uniformClass = "U_B_CBRN_CTRG_GER_S_Tropic"; };
22.560606
83
0.723976
ASO-TheM
64c47577cd6e7377f1e1989c5ee8c523428a64af
3,032
cpp
C++
EasyFramework3d/managed/al/SoundManager.cpp
sizilium/FlexChess
f12b94e800ddcb00535067eca3b560519c9122e0
[ "MIT" ]
null
null
null
EasyFramework3d/managed/al/SoundManager.cpp
sizilium/FlexChess
f12b94e800ddcb00535067eca3b560519c9122e0
[ "MIT" ]
null
null
null
EasyFramework3d/managed/al/SoundManager.cpp
sizilium/FlexChess
f12b94e800ddcb00535067eca3b560519c9122e0
[ "MIT" ]
null
null
null
#include <vs/managed/al/SoundManager.h> #include <vs/managed/al/AlException.h> #include <vs/base/interfaces/AbstractManaged.h> #include <vs/base/util/IOStream.h> namespace vs { namespace managed { namespace al { using namespace base::interfaces; using namespace base::util; SoundManager::SoundManager() { int error; alutInit(NULL, 0); error = alGetError(); if (error != AL_NO_ERROR) { throw ALException ( "SoundManager.cpp", "SoundManager::SoundManager", "Could not init alut!", error, ALUT_ERROR); } // set default listener attributes ALfloat listenerPos[] = { 0.0, 0.0, 0.0 }; ALfloat listenerVel[] = { 0.0, 0.0, 0.0 }; ALfloat listenerOri[] = { 0.0, 0.0, -1.0, 0.0, 1.0, 0.0 }; alListenerfv(AL_POSITION, listenerPos); alListenerfv(AL_VELOCITY, listenerVel); alListenerfv(AL_ORIENTATION, listenerOri); // set cleanup function on exit atexit( killALData ); // set the default distance model (can be changed by SoundListener.h) alDistanceModel(AL_LINEAR_DISTANCE); } SoundManager::~SoundManager() { map<string, ALuint>::iterator it = buffers.begin(); while (it != buffers.end() ) { alDeleteBuffers(1, &it->second ); ++it; } buffers.clear(); alutExit(); } void SoundManager::update(double time) { } ALuint SoundManager::getBuffer(string path) { int error; // falls buffer noch nicht vorhanden ist neuen buffer anlegen und laden if (!buffers[path]) { ALuint newBuffer; alGenBuffers(1, &newBuffer); error = alGetError(); if (error != AL_NO_ERROR) { throw ALException ( "SoundManager.cpp", "SoundManager::getBuffer", "Could not generate buffer!", error, AL_ERROR); } // sound datei in buffer laden newBuffer = alutCreateBufferFromFile(path.c_str() ); if (newBuffer == AL_NONE) { ALenum error; error = alutGetError (); throw ALException("SoundManager.cpp", "SoundManager::getBuffer", "Could not create buffer from file: " + path + "(\nis the path and filename correct? is the wav format correct?)" , error, ALUT_ERROR); } return buffers[path] = newBuffer; } // falls buffer schon vorhanden war den alten buffer verwenden else return buffers[path]; } void SoundManager::delBuffer(ALuint fd) { --refCounts[fd]; // falls buffer nicht mehr gebraucht wird, l�schen if (refCounts[fd] <= 0) { map<string, ALuint>::iterator it = buffers.begin(); while (it != buffers.end()) { if (it->second == fd) break; it++; } alDeleteBuffers(1, &it->second); // buffer aus al l�schen buffers.erase(it); // buffer aus verwaltung l�schen refCounts.erase(fd); // refCounter l�schen } ALenum error; if (error = alGetError () != AL_NO_ERROR) { throw ALException( "SoundManager.cpp", "SoundManager::delBuffer", "Could not delete buffer", error, AL_ERROR); } } void SoundManager::outDebug() const { } void killALData() { // TODO (Administrator#1#): funktion �berhaupt notwendig? } } // al } // managed } // vs
19.069182
75
0.66128
sizilium
64c4c68adb0be5c06237e11d15fecfbbccff5595
1,814
cpp
C++
CPP/OJ problems/Graph Without Long Directed Paths.cpp
kratikasinghal/OJ-problems
fc5365cb4db9da780779e9912aeb2a751fe4517c
[ "MIT" ]
null
null
null
CPP/OJ problems/Graph Without Long Directed Paths.cpp
kratikasinghal/OJ-problems
fc5365cb4db9da780779e9912aeb2a751fe4517c
[ "MIT" ]
null
null
null
CPP/OJ problems/Graph Without Long Directed Paths.cpp
kratikasinghal/OJ-problems
fc5365cb4db9da780779e9912aeb2a751fe4517c
[ "MIT" ]
null
null
null
// Problem: F. Graph Without Long Directed Paths // Contest: Codeforces - Codeforces Round #550 (Div. 3) // URL: https://codeforces.com/contest/1144/problem/F // Memory Limit: 256 MB // Time Limit: 2000 ms // Powered by CP Editor (https://github.com/cpeditor/cpeditor) #include <bits/stdc++.h> #define F first #define S second #define PB push_back #define MP make_pair #define ll long long int #define vi vector<int> #define vii vector<int, int> #define vc vector<char> #define vl vector<ll> #define mod 1000000007 #define INF 1000000009 using namespace std; vi adj[200005]; bool color[200005]; bool vis[200005]; bool dfs(int node, bool col) { vis[node] = true; for(int child : adj[node]) { if(!vis[child]) { color[child] = col^1; bool res = dfs(child, col^1); if(res == false) return false; } else { if(color[child] == color[node]) { return false; } } } return true; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; t = 1; // cin >> t; while(t--) { int n, m; cin >> n >> m; int a, b; vector<pair<int, int> > A; for(int i = 1; i <= m; i++) { cin >> a >> b; A.push_back({a, b}); adj[a].PB(b); adj[b].PB(a); } bool flag = true; for(int i = 0; i <= n; i++) { bool res = dfs(i, 0); if(res == false) { flag = false; break; } } if(flag) { cout << "YES\n"; for(int i = 0; i < (int)A.size(); i++) { if(color[A[i].first] == 0) { cout << "1"; } else { cout << "0"; } } cout << "\n"; } else { cout << "NO\n"; } } return 0; }
17.960396
62
0.492282
kratikasinghal