hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
976d5f6ce0c858fbfeffa29adf5af638fa8e4d70
3,129
cpp
C++
source/qt_common/s4qt_unicTreeView.cpp
chinsaiki/s4-gui
c8a11aad28150da71127b89370bea9b7e2530fee
[ "MIT" ]
null
null
null
source/qt_common/s4qt_unicTreeView.cpp
chinsaiki/s4-gui
c8a11aad28150da71127b89370bea9b7e2530fee
[ "MIT" ]
null
null
null
source/qt_common/s4qt_unicTreeView.cpp
chinsaiki/s4-gui
c8a11aad28150da71127b89370bea9b7e2530fee
[ "MIT" ]
null
null
null
#include "qt_common/s4qt_unicTreeView.h" #include <QDebug> #include <QMouseEvent> #include <QStandardItem> #include <QLineEdit> #include <QShortcut> namespace S4 { namespace QT { unicTreeView::unicTreeView(QWidget* parent): QTreeView(parent) { QShortcut* shortCut = new QShortcut(Qt::Key_Delete, this); connect(shortCut, &QShortcut::activated, this, &unicTreeView::onDelkey); connect(this, &unicTreeView::signal_blankDoubleClick, this, &unicTreeView::onBlankDoubleClick); connect(this, &QTreeView::clicked, this, &unicTreeView::onMouseClick); } void unicTreeView::onSetCurrentRoot(QStandardItem* root) { _current_root = root; //connect((QStandardItemModel*)model(), &QStandardItemModel::itemChanged, this, &unicTreeView::onItemChanged); } void unicTreeView::onSetTextFormater(unicTreeView::textFormater_t* textFormater) { _textFormater = textFormater; } void unicTreeView::mouseDoubleClickEvent(QMouseEvent* event) { QTreeView::mouseDoubleClickEvent(event); QModelIndex index = this->indexAt(event->pos()); //QAbstractItemModel *model = this->model(); //QMap<int, QVariant> ItemData = model->itemData(index); if (index.row() < 0) { qDebug() << "onBlankDoubleClick"; emit signal_blankDoubleClick(); } } void unicTreeView::onDelkey() { if (!this->currentIndex().parent().isValid()) return; qDebug() << "onDelkey " << this->currentIndex(); emit signal_delItem(this->currentIndex().data().toString()); _current_root->removeRow(this->currentIndex().row()); } void unicTreeView::onDelItem(const QString& text) { int i = findChild(text); if (i >= 0) { _current_root->removeRow(i); } } void unicTreeView::onMouseClick(const QModelIndex& index) { if (!this->currentIndex().parent().isValid()) return; emit signal_selectItem(this->currentIndex().data().toString()); } void unicTreeView::onBlankDoubleClick() { //if (!index.parent().isValid()) // return; //if (!index.parent().parent().isValid()) return; QStandardItem * item = new QStandardItem; item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsEditable); _current_root->appendRow(item); this->expandAll(); this->edit(item->index()); } void unicTreeView::onItemChanged(QWidget* editor, int hint) { if (QLineEdit* le = qobject_cast<QLineEdit*>(editor)) { int row = findChild(le->text()); if (_textFormater) { QString fmt_text; if (!(*_textFormater)(le->text(), fmt_text)) { _current_root->removeRow(row); qDebug() << "error format, please retry!"; return; } _current_root->child(row)->setText(fmt_text); } if (findChild(_current_root->child(row)->text()) != row) { _current_root->removeRow(row); qDebug() << "dual input, please change!"; return; } _current_root->child(row)->setFlags(_current_root->child(row)->flags() & (~Qt::ItemIsEditable)); emit signal_newItem(_current_root->child(row)->text()); } } int unicTreeView::findChild(const QString& text) { for (int i = 0; i < _current_root->rowCount(); ++i) { if (_current_root->child(i)->text() == text) { return i; } } return -1; } } // namespace QT } // namespace S4
26.74359
111
0.705657
[ "model" ]
976fbb363ff93d16cdc1b63c3f61b6b63216b4eb
12,731
cc
C++
src/chrome/browser/component_updater/widevine_cdm_component_installer.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
9
2018-09-21T05:36:12.000Z
2021-11-15T15:14:36.000Z
src/chrome/browser/component_updater/widevine_cdm_component_installer.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
null
null
null
src/chrome/browser/component_updater/widevine_cdm_component_installer.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
3
2018-11-28T14:54:13.000Z
2020-07-02T07:36:07.000Z
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/component_updater/widevine_cdm_component_installer.h" #include <string.h> #include <vector> #include "base/base_paths.h" #include "base/bind.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/strings/string_split.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "base/version.h" #include "build/build_config.h" #include "chrome/browser/component_updater/component_updater_service.h" #include "chrome/browser/plugins/plugin_prefs.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/widevine_cdm_constants.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/plugin_service.h" #include "content/public/common/pepper_plugin_info.h" #include "ppapi/c/private/ppb_pdf.h" #include "third_party/widevine/cdm/widevine_cdm_common.h" #include "webkit/plugins/plugin_constants.h" #include "webkit/plugins/ppapi/plugin_module.h" #include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR. using content::BrowserThread; using content::PluginService; namespace { // TODO(xhwang): Move duplicate code among all component installer // implementations to some common place. // TODO(xhwang): This is the sha256sum of "Widevine CDM". Get the real extension // ID for Widevine CDM. // CRX hash. The extension id is: lgafhhiijclkaikclkjjofekikijofcm. const uint8 kSha2Hash[] = {0xb6, 0x05, 0x77, 0x88, 0x92, 0xba, 0x08, 0xa2, 0xba, 0x99, 0xe5, 0x4a, 0x8a, 0x89, 0xe5, 0x2c, 0x88, 0x38, 0x2f, 0xf5, 0xa7, 0x7b, 0x93, 0xe7, 0xf1, 0x84, 0xcc, 0x37, 0xe1, 0xe5, 0x7a, 0xbd}; // File name of the Widevine CDM component manifest on different platforms. const char kWidevineCdmManifestName[] = "WidevineCdm"; // Name of the Widevine CDM OS in the component manifest. const char kWidevineCdmOperatingSystem[] = #if defined(OS_MACOSX) "mac"; #elif defined(OS_WIN) "win"; #else // OS_LINUX, etc. TODO(viettrungluu): Separate out Chrome OS and Android? "linux"; #endif // Name of the Widevine CDM architecture in the component manifest. const char kWidevineCdmArch[] = #if defined(ARCH_CPU_X86) "ia32"; #elif defined(ARCH_CPU_X86_64) "x64"; #else // TODO(viettrungluu): Support an ARM check? "???"; #endif // If we don't have a Widevine CDM component, this is the version we claim. const char kNullVersion[] = "0.0.0.0"; // The base directory on Windows looks like: // <profile>\AppData\Local\Google\Chrome\User Data\WidevineCdm\. base::FilePath GetWidevineCdmBaseDirectory() { base::FilePath result; PathService::Get(chrome::DIR_WIDEVINE_CDM, &result); return result; } #if defined(WIDEVINE_CDM_AVAILABLE) && !defined(OS_LINUX) // Widevine CDM plugins have the version encoded in the path itself // so we need to enumerate the directories to find the full path. // On success, |latest_dir| returns something like: // <profile>\AppData\Local\Google\Chrome\User Data\WidevineCdm\10.3.44.555\. // |latest_version| returns the corresponding version number. |older_dirs| // returns directories of all older versions. bool GetWidevineCdmDirectory(base::FilePath* latest_dir, base::Version* latest_version, std::vector<base::FilePath>* older_dirs) { base::FilePath base_dir = GetWidevineCdmBaseDirectory(); bool found = false; file_util::FileEnumerator file_enumerator( base_dir, false, file_util::FileEnumerator::DIRECTORIES); for (base::FilePath path = file_enumerator.Next(); !path.value().empty(); path = file_enumerator.Next()) { base::Version version(path.BaseName().MaybeAsASCII()); if (!version.IsValid()) continue; if (found) { if (version.CompareTo(*latest_version) > 0) { older_dirs->push_back(*latest_dir); *latest_dir = path; *latest_version = version; } else { older_dirs->push_back(path); } } else { *latest_dir = path; *latest_version = version; found = true; } } return found; } #endif // defined(WIDEVINE_CDM_AVAILABLE) && !defined(OS_LINUX) // Returns true if the Pepper |interface_name| is implemented by this browser. // It does not check if the interface is proxied. bool SupportsPepperInterface(const char* interface_name) { if (webkit::ppapi::PluginModule::SupportsInterface(interface_name)) return true; // The PDF interface is invisible to SupportsInterface() on the browser // process because it is provided using PpapiInterfaceFactoryManager. We need // to check for that as well. // TODO(cpu): make this more sane. return (strcmp(interface_name, PPB_PDF_INTERFACE) == 0); } bool MakeWidevineCdmPluginInfo(const base::FilePath& path, const base::Version& version, content::PepperPluginInfo* plugin_info) { if (!version.IsValid() || version.components().size() != static_cast<size_t>(kWidevineCdmVersionNumComponents)) { return false; } plugin_info->is_internal = false; // Widevine CDM must run out of process. plugin_info->is_out_of_process = true; plugin_info->path = path; plugin_info->name = kWidevineCdmPluginName; plugin_info->description = kWidevineCdmPluginDescription; plugin_info->version = version.GetString(); webkit::WebPluginMimeType widevine_cdm_mime_type( kWidevineCdmPluginMimeType, kWidevineCdmPluginExtension, kWidevineCdmPluginMimeTypeDescription); plugin_info->mime_types.push_back(widevine_cdm_mime_type); plugin_info->permissions = kWidevineCdmPluginPermissions; return true; } void RegisterWidevineCdmWithChrome(const base::FilePath& path, const base::Version& version) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); content::PepperPluginInfo plugin_info; if (!MakeWidevineCdmPluginInfo(path, version, &plugin_info)) return; PluginService::GetInstance()->RegisterInternalPlugin( plugin_info.ToWebPluginInfo(), true); PluginService::GetInstance()->RefreshPlugins(); } // Returns true if this browser implements one of the interfaces given in // |interface_string|, which is a '|'-separated string of interface names. bool CheckWidevineCdmInterfaceString(const std::string& interface_string) { std::vector<std::string> interface_names; base::SplitString(interface_string, '|', &interface_names); for (size_t i = 0; i < interface_names.size(); i++) { if (SupportsPepperInterface(interface_names[i].c_str())) return true; } return false; } // Returns true if this browser implements all the interfaces that Widevine CDM // specifies in its component installer manifest. bool CheckWidevineCdmInterfaces(const base::DictionaryValue& manifest) { const base::ListValue* interface_list = NULL; // We don't *require* an interface list, apparently. if (!manifest.GetList("x-ppapi-required-interfaces", &interface_list)) return true; for (size_t i = 0; i < interface_list->GetSize(); i++) { std::string interface_string; if (!interface_list->GetString(i, &interface_string)) return false; if (!CheckWidevineCdmInterfaceString(interface_string)) return false; } return true; } // Returns true if this browser is compatible with the given Widevine CDM // manifest, with the version specified in the manifest in |version_out|. bool CheckWidevineCdmManifest(const base::DictionaryValue& manifest, base::Version* version_out) { std::string name; manifest.GetStringASCII("name", &name); if (name != kWidevineCdmManifestName) return false; std::string proposed_version; manifest.GetStringASCII("version", &proposed_version); base::Version version(proposed_version.c_str()); if (!version.IsValid()) return false; if (!CheckWidevineCdmInterfaces(manifest)) return false; std::string os; manifest.GetStringASCII("x-ppapi-os", &os); if (os != kWidevineCdmOperatingSystem) return false; std::string arch; manifest.GetStringASCII("x-ppapi-arch", &arch); if (arch != kWidevineCdmArch) return false; *version_out = version; return true; } } // namespace class WidevineCdmComponentInstaller : public ComponentInstaller { public: explicit WidevineCdmComponentInstaller(const base::Version& version); virtual ~WidevineCdmComponentInstaller() {} virtual void OnUpdateError(int error) OVERRIDE; virtual bool Install(base::DictionaryValue* manifest, const base::FilePath& unpack_path) OVERRIDE; private: base::Version current_version_; }; WidevineCdmComponentInstaller::WidevineCdmComponentInstaller( const base::Version& version) : current_version_(version) { DCHECK(version.IsValid()); } void WidevineCdmComponentInstaller::OnUpdateError(int error) { NOTREACHED() << "Widevine CDM update error: " << error; } bool WidevineCdmComponentInstaller::Install(base::DictionaryValue* manifest, const base::FilePath& unpack_path) { base::Version version; if (!CheckWidevineCdmManifest(*manifest, &version)) return false; if (current_version_.CompareTo(version) > 0) return false; // TODO(xhwang): Also check if Widevine CDM binary exists. if (!file_util::PathExists(unpack_path.Append(kWidevineCdmPluginFileName))) return false; // Passed the basic tests. Time to install it. base::FilePath path = GetWidevineCdmBaseDirectory().AppendASCII(version.GetString()); if (file_util::PathExists(path)) return false; if (!file_util::Move(unpack_path, path)) return false; // Installation is done. Now tell the rest of chrome. Both the path service // and to the plugin service. current_version_ = version; PathService::Override(chrome::DIR_PEPPER_FLASH_PLUGIN, path); path = path.Append(kWidevineCdmPluginFileName); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&RegisterWidevineCdmWithChrome, path, version)); return true; } namespace { #if defined(WIDEVINE_CDM_AVAILABLE) && !defined(OS_LINUX) void StartWidevineCdmUpdateRegistration(ComponentUpdateService* cus) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); base::FilePath path = GetWidevineCdmBaseDirectory(); if (!file_util::PathExists(path) && !file_util::CreateDirectory(path)) { NOTREACHED() << "Could not create Widevine CDM directory."; return; } base::Version version(kNullVersion); std::vector<base::FilePath> older_dirs; if (GetWidevineCdmDirectory(&path, &version, &older_dirs)) { path = path.Append(kWidevineCdmPluginFileName); if (file_util::PathExists(path)) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&RegisterWidevineCdmWithChrome, path, version)); } else { version = base::Version(kNullVersion); } } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&FinishWidevineCdmUpdateRegistration, cus, version)); // Remove older versions of Widevine CDM. for (std::vector<base::FilePath>::iterator iter = older_dirs.begin(); iter != older_dirs.end(); ++iter) { file_util::Delete(*iter, true); } } void FinishWidevineCdmUpdateRegistration(ComponentUpdateService* cus, const base::Version& version) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); CrxComponent widevine_cdm; widevine_cdm.name = "WidevineCdm"; widevine_cdm.installer = new WidevineCdmComponentInstaller(version); widevine_cdm.version = version; widevine_cdm.pk_hash.assign(kSha2Hash, &kSha2Hash[sizeof(kSha2Hash)]); if (cus->RegisterComponent(widevine_cdm) != ComponentUpdateService::kOk) { NOTREACHED() << "Widevine CDM component registration failed."; } } #endif // defined(WIDEVINE_CDM_AVAILABLE) && !defined(OS_LINUX) } // namespace void RegisterWidevineCdmComponent(ComponentUpdateService* cus) { #if defined(WIDEVINE_CDM_AVAILABLE) && !defined(OS_LINUX) BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, base::Bind(&StartWidevineCdmUpdateRegistration, cus)); #endif // defined(WIDEVINE_CDM_AVAILABLE) && !defined(OS_LINUX) }
35.761236
80
0.719346
[ "vector" ]
977b76f26399905076c989dcddf7dd959257cf3f
7,828
cpp
C++
mpc_controller/ros_acado_bridge/ACADOtoolkit/examples/code_generation/simulation/quadcopter.cpp
kurshakuz/graduation-project
352a94c2d3e24ce714460446342b612fbb6d1f52
[ "BSD-2-Clause" ]
2
2021-04-07T08:37:28.000Z
2021-09-30T09:38:22.000Z
mpc_controller/ros_acado_bridge/ACADOtoolkit/examples/code_generation/simulation/quadcopter.cpp
kurshakuz/graduation-project
352a94c2d3e24ce714460446342b612fbb6d1f52
[ "BSD-2-Clause" ]
null
null
null
mpc_controller/ros_acado_bridge/ACADOtoolkit/examples/code_generation/simulation/quadcopter.cpp
kurshakuz/graduation-project
352a94c2d3e24ce714460446342b612fbb6d1f52
[ "BSD-2-Clause" ]
2
2021-03-01T14:20:58.000Z
2021-06-21T12:34:33.000Z
/* * This file is part of ACADO Toolkit. * * ACADO Toolkit -- A Toolkit for Automatic Control and Dynamic Optimization. * Copyright (C) 2008-2014 by Boris Houska, Hans Joachim Ferreau, * Milan Vukov, Rien Quirynen, KU Leuven. * Developed within the Optimization in Engineering Center (OPTEC) * under supervision of Moritz Diehl. All rights reserved. * * ACADO Toolkit is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * ACADO Toolkit is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with ACADO Toolkit; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <acado_code_generation.hpp> using namespace std; USING_NAMESPACE_ACADO int main( ) { // Define variables, functions and constants: // ---------------------------------------------------------- DifferentialState dT1; DifferentialState dT2; DifferentialState dT3; DifferentialState dT4; DifferentialState T1; DifferentialState T2; DifferentialState T3; DifferentialState T4; DifferentialState W1; DifferentialState W2; DifferentialState W3; DifferentialState W4; DifferentialState q1; DifferentialState q2; DifferentialState q3; DifferentialState q4; DifferentialState Omega1; DifferentialState Omega2; DifferentialState Omega3; DifferentialState V1; DifferentialState V2; DifferentialState V3; DifferentialState P1; // x DifferentialState P2; // y DifferentialState P3; // z DifferentialState IP1; DifferentialState IP2; DifferentialState IP3; Control U1; Control U2; Control U3; Control U4; DifferentialEquation f1, f2; const double rho = 1.23; const double A = 0.1; const double Cl = 0.25; const double Cd = 0.3*Cl; const double m = 10; const double g = 9.81; const double L = 0.5; const double Jp = 1e-2; const double xi = 1e-2; const double J1 = 0.25; const double J2 = 0.25; const double J3 = 1; const double gain = 1e-4; const double alpha = 0.0; // Define the quadcopter ODE model in fully nonlinear form: // ---------------------------------------------------------- f1 << dot(dT1) == U1*gain; f1 << dot(dT2) == U2*gain; f1 << dot(dT3) == U3*gain; f1 << dot(dT4) == U4*gain; f1 << dot(T1) == dT1; f1 << dot(T2) == dT2; f1 << dot(T3) == dT3; f1 << dot(T4) == dT4; f1 << dot(W1) == (T1 - W1*xi)/Jp; f1 << dot(W2) == (T2 - W2*xi)/Jp; f1 << dot(W3) == (T3 - W3*xi)/Jp; f1 << dot(W4) == (T4 - W4*xi)/Jp; f1 << dot(q1) == - (Omega1*q2)/2 - (Omega2*q3)/2 - (Omega3*q4)/2 - (alpha*q1*(q1*q1 + q2*q2 + q3*q3 + q4*q4 - 1))/(q1*q1 + q2*q2 + q3*q3 + q4*q4); f1 << dot(q2) == (Omega1*q1)/2 - (Omega3*q3)/2 + (Omega2*q4)/2 - (alpha*q2*(q1*q1 + q2*q2 + q3*q3 + q4*q4 - 1))/(q1*q1 + q2*q2 + q3*q3 + q4*q4); f1 << dot(q3) == (Omega2*q1)/2 + (Omega3*q2)/2 - (Omega1*q4)/2 - (alpha*q3*(q1*q1 + q2*q2 + q3*q3 + q4*q4 - 1))/(q1*q1 + q2*q2 + q3*q3 + q4*q4); f1 << dot(q4) == (Omega3*q1)/2 - (Omega2*q2)/2 + (Omega1*q3)/2 - (alpha*q4*(q1*q1 + q2*q2 + q3*q3 + q4*q4 - 1))/(q1*q1 + q2*q2 + q3*q3 + q4*q4); f1 << dot(Omega1) == (J3*Omega2*Omega3 - J2*Omega2*Omega3 + (A*Cl*L*rho*(W2*W2 - W4*W4))/2)/J1; f1 << dot(Omega2) == -(J3*Omega1*Omega3 - J1*Omega1*Omega3 + (A*Cl*L*rho*(W1*W1 - W3*W3))/2)/J2; f1 << dot(Omega3) == (J2*Omega1*Omega2 - J1*Omega1*Omega2 + (A*Cd*rho*(W1*W1 - W2*W2 + W3*W3 - W4*W4))/2)/J3; f1 << dot(V1) == (A*Cl*rho*(2*q1*q3 + 2*q2*q4)*(W1*W1 + W2*W2 + W3*W3 + W4*W4))/(2*m); f1 << dot(V2) == -(A*Cl*rho*(2*q1*q2 - 2*q3*q4)*(W1*W1 + W2*W2 + W3*W3 + W4*W4))/(2*m); f1 << dot(V3) == (A*Cl*rho*(W1*W1 + W2*W2 + W3*W3 + W4*W4)*(q1*q1 - q2*q2 - q3*q3 + q4*q4))/(2*m) - g; f1 << dot(P1) == V1; f1 << dot(P2) == V2; f1 << dot(P3) == V3; f1 << dot(IP1) == P1; f1 << dot(IP2) == P2; f1 << dot(IP3) == P3; // Define the quadcopter ODE model in 3-stage format: // ---------------------------------------------------------- // LINEAR INPUT SYSTEM (STAGE 1): DMatrix M1, A1, B1; M1 = eye<double>(12); A1 = zeros<double>(12,12); B1 = zeros<double>(12,4); A1(4,0) = 1.0; A1(5,1) = 1.0; A1(6,2) = 1.0; A1(7,3) = 1.0; A1(8,4) = 1.0/Jp; A1(8,8) = -xi/Jp; A1(9,5) = 1.0/Jp; A1(9,9) = -xi/Jp; A1(10,6) = 1.0/Jp; A1(10,10) = -xi/Jp; A1(11,7) = 1.0/Jp; A1(11,11) = -xi/Jp; B1(0,0) = gain; B1(1,1) = gain; B1(2,2) = gain; B1(3,3) = gain; // NONLINEAR SYSTEM (STAGE 2): f2 << dot(q1) == - (Omega1*q2)/2 - (Omega2*q3)/2 - (Omega3*q4)/2 - (alpha*q1*(q1*q1 + q2*q2 + q3*q3 + q4*q4 - 1))/(q1*q1 + q2*q2 + q3*q3 + q4*q4); f2 << dot(q2) == (Omega1*q1)/2 - (Omega3*q3)/2 + (Omega2*q4)/2 - (alpha*q2*(q1*q1 + q2*q2 + q3*q3 + q4*q4 - 1))/(q1*q1 + q2*q2 + q3*q3 + q4*q4); f2 << dot(q3) == (Omega2*q1)/2 + (Omega3*q2)/2 - (Omega1*q4)/2 - (alpha*q3*(q1*q1 + q2*q2 + q3*q3 + q4*q4 - 1))/(q1*q1 + q2*q2 + q3*q3 + q4*q4); f2 << dot(q4) == (Omega3*q1)/2 - (Omega2*q2)/2 + (Omega1*q3)/2 - (alpha*q4*(q1*q1 + q2*q2 + q3*q3 + q4*q4 - 1))/(q1*q1 + q2*q2 + q3*q3 + q4*q4); f2 << dot(Omega1) == (J3*Omega2*Omega3 - J2*Omega2*Omega3 + (A*Cl*L*rho*(W2*W2 - W4*W4))/2)/J1; f2 << dot(Omega2) == -(J3*Omega1*Omega3 - J1*Omega1*Omega3 + (A*Cl*L*rho*(W1*W1 - W3*W3))/2)/J2; f2 << dot(Omega3) == (J2*Omega1*Omega2 - J1*Omega1*Omega2 + (A*Cd*rho*(W1*W1 - W2*W2 + W3*W3 - W4*W4))/2)/J3; f2 << dot(V1) == (A*Cl*rho*(2*q1*q3 + 2*q2*q4)*(W1*W1 + W2*W2 + W3*W3 + W4*W4))/(2*m); f2 << dot(V2) == -(A*Cl*rho*(2*q1*q2 - 2*q3*q4)*(W1*W1 + W2*W2 + W3*W3 + W4*W4))/(2*m); f2 << dot(V3) == (A*Cl*rho*(W1*W1 + W2*W2 + W3*W3 + W4*W4)*(q1*q1 - q2*q2 - q3*q3 + q4*q4))/(2*m) - g; // LINEAR OUTPUT SYSTEM (STAGE 3): DMatrix M3, A3; M3 = eye<double>(6); A3 = zeros<double>(6,6); A3(3,0) = 1.0; A3(4,1) = 1.0; A3(5,2) = 1.0; OutputFcn f3; f3 << V1; f3 << V2; f3 << V3; f3 << 0.0; f3 << 0.0; f3 << 0.0; // ---------------------------------------------------------- // ---------------------------------------------------------- SIMexport sim1( 10, 1.0 ); sim1.setModel( f1 ); sim1.set( INTEGRATOR_TYPE, INT_IRK_GL4 ); sim1.set( NUM_INTEGRATOR_STEPS, 50 ); sim1.setTimingSteps( 10000 ); cout << "-----------------------------------------------------------\n Using a QuadCopter ODE model in fully nonlinear form:\n-----------------------------------------------------------\n"; sim1.exportAndRun( "quadcopter_export", "init_quadcopter.txt", "controls_quadcopter.txt" ); // ---------------------------------------------------------- // ---------------------------------------------------------- SIMexport sim2( 10, 1.0 ); sim2.setLinearInput( M1, A1, B1 ); sim2.setModel( f2 ); sim2.setLinearOutput( M3, A3, f3 ); sim2.set( INTEGRATOR_TYPE, INT_IRK_GL4 ); sim2.set( NUM_INTEGRATOR_STEPS, 50 ); sim2.setTimingSteps( 10000 ); cout << "-----------------------------------------------------------\n Using a QuadCopter ODE model in 3-stage format:\n-----------------------------------------------------------\n"; sim2.exportAndRun( "quadcopter_export", "init_quadcopter.txt", "controls_quadcopter.txt" ); return 0; }
36.924528
191
0.531681
[ "model" ]
97834fbbb675708f730a3fb3b3f6b69dd0af50f1
739
cpp
C++
35.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
35.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
35.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ull = uint64_t; using ll = int64_t; using ld = long double; class Solution { public: int searchInsert(vector<int>& nums, int target) { // binary search to find the target in the ascending sequence int lo = 0, hi = (int) nums.size() - 1; int mid = -1; while (lo <= hi) { mid = (lo + hi) / 2; if (nums[mid] == target) // found the target return mid; else if (nums[mid] < target) lo = mid + 1; else hi = mid - 1; } // not found the target, we need to check whether the position is pointed to its smaller neighbor or bigger neighbor if (nums[mid] < target) // ensure the position is pointed to its bigger neighbor ++mid; return mid; } };
23.09375
118
0.631935
[ "vector" ]
9783a27cc52160b3d9ae301b6e386fb6d6997a09
5,590
cpp
C++
mobilitypath_publisher/src/mobilitypath_publisher.cpp
adamlm/carma-platform
f6d46274cf6b6e14eddf8715b1a5204050d4c0e2
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
112
2020-04-27T17:06:46.000Z
2022-03-31T15:27:14.000Z
mobilitypath_publisher/src/mobilitypath_publisher.cpp
adamlm/carma-platform
f6d46274cf6b6e14eddf8715b1a5204050d4c0e2
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
982
2020-04-17T11:28:04.000Z
2022-03-31T21:12:19.000Z
mobilitypath_publisher/src/mobilitypath_publisher.cpp
adamlm/carma-platform
f6d46274cf6b6e14eddf8715b1a5204050d4c0e2
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
57
2020-05-07T15:48:11.000Z
2022-03-09T23:31:45.000Z
/* * Copyright (C) 2019-2021 LEIDOS. * * 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 "mobilitypath_publisher.h" namespace mobilitypath_publisher { // @SONAR_STOP@ MobilityPathPublication::MobilityPathPublication(): path_pub_rate_(10.0) {} void MobilityPathPublication::initialize() { nh_.reset(new ros::CARMANodeHandle()); pnh_.reset(new ros::CARMANodeHandle("~")); pnh_->param<double>("path_pub_rate", path_pub_rate_, 10.0); pnh_->getParam("vehicle_id", sender_id); mob_path_pub_ = nh_->advertise<cav_msgs::MobilityPath>("mobility_path_msg", 5); traj_sub_ = nh_->subscribe("plan_trajectory", 5, &MobilityPathPublication::trajectory_cb, this); bsm_sub_ = nh_->subscribe("bsm_outbound", 1, &MobilityPathPublication::bsm_cb, this); georeference_sub_ = nh_->subscribe("georeference", 1, &MobilityPathPublication::georeference_cb, this); path_pub_timer_ = pnh_->createTimer( ros::Duration(ros::Rate(path_pub_rate_)), [this](const auto&) { this->spinCallback(); }); } void MobilityPathPublication::run() { initialize(); ros::CARMANodeHandle::spin(); } bool MobilityPathPublication::spinCallback() { mob_path_pub_.publish(latest_mobility_path_); return true; } void MobilityPathPublication::georeference_cb(const std_msgs::StringConstPtr& msg) { map_projector_ = std::make_shared<lanelet::projection::LocalFrameProjector>(msg->data.c_str()); // Build projector from proj string } void MobilityPathPublication::trajectory_cb(const cav_msgs::TrajectoryPlanConstPtr& msg) { latest_trajectory_ = *msg; latest_mobility_path_ = mobilityPathMessageGenerator(latest_trajectory_); } void MobilityPathPublication::bsm_cb(const cav_msgs::BSMConstPtr& msg) { bsm_core_ = msg->core_data; } // @SONAR_START@ cav_msgs::MobilityPath MobilityPathPublication::mobilityPathMessageGenerator(const cav_msgs::TrajectoryPlan& trajectory_plan) { cav_msgs::MobilityPath mobility_path_msg; uint64_t millisecs =trajectory_plan.header.stamp.toNSec()/1000000; mobility_path_msg.header = composeMobilityHeader(millisecs); if (!map_projector_) { ROS_ERROR_STREAM("MobilityPath cannot be populated as map projection is not available"); return mobility_path_msg; } cav_msgs::Trajectory mob_path_traj = TrajectoryPlantoTrajectory(trajectory_plan.trajectory_points); mobility_path_msg.trajectory = mob_path_traj; return mobility_path_msg; } cav_msgs::MobilityHeader MobilityPathPublication::composeMobilityHeader(uint64_t time){ cav_msgs::MobilityHeader header; header.sender_id = sender_id; header.recipient_id = recipient_id; header.sender_bsm_id = bsmIDtoString(bsm_core_); // random GUID that identifies this particular plan for future reference header.plan_id = boost::uuids::to_string(boost::uuids::random_generator()()); header.timestamp = time; //time in millisecond return header; } cav_msgs::Trajectory MobilityPathPublication::TrajectoryPlantoTrajectory(const std::vector<cav_msgs::TrajectoryPlanPoint>& traj_points) const{ cav_msgs::Trajectory traj; cav_msgs::LocationECEF ecef_location = TrajectoryPointtoECEF(traj_points[0]); //m to cm to fit the msg standard if (traj_points.size()<2){ ROS_WARN("Received Trajectory Plan is too small"); traj.offsets = {}; } else{ cav_msgs::LocationECEF prev_point = ecef_location; for (size_t i=1; i<traj_points.size(); i++){ cav_msgs::LocationOffsetECEF offset; cav_msgs::LocationECEF new_point = TrajectoryPointtoECEF(traj_points[i]); //m to cm to fit the msg standard offset.offset_x = (int16_t)(new_point.ecef_x - prev_point.ecef_x); offset.offset_y = (int16_t)(new_point.ecef_y - prev_point.ecef_y); offset.offset_z = (int16_t)(new_point.ecef_z - prev_point.ecef_z); prev_point = new_point; traj.offsets.push_back(offset); } } traj.location = ecef_location; return traj; } cav_msgs::LocationECEF MobilityPathPublication::TrajectoryPointtoECEF(const cav_msgs::TrajectoryPlanPoint& traj_point) const{ if (!map_projector_) { throw std::invalid_argument("No map projector available for ecef conversion"); } cav_msgs::LocationECEF location; lanelet::BasicPoint3d ecef_point = map_projector_->projectECEF({traj_point.x, traj_point.y, 0.0}, 1); location.ecef_x = ecef_point.x() * 100.0; location.ecef_y = ecef_point.y() * 100.0; location.ecef_z = ecef_point.z() * 100.0; return location; } }
37.516779
146
0.668515
[ "vector" ]
978b2551a2f5e68c50a39573b72322301ed61fb4
33,443
cpp
C++
progression/graphics/vulkan.cpp
LiamTyler/OpenGL_Starter
7110e94cb583e5fbfefb70ede40d305674261c5a
[ "MIT" ]
null
null
null
progression/graphics/vulkan.cpp
LiamTyler/OpenGL_Starter
7110e94cb583e5fbfefb70ede40d305674261c5a
[ "MIT" ]
null
null
null
progression/graphics/vulkan.cpp
LiamTyler/OpenGL_Starter
7110e94cb583e5fbfefb70ede40d305674261c5a
[ "MIT" ]
null
null
null
#include "graphics/vulkan.hpp" #include "core/platform_defines.hpp" #include <vulkan/vulkan.h> #include "core/window.hpp" #include "graphics/debug_marker.hpp" #include "graphics/graphics_api.hpp" #include "graphics/render_system.hpp" #include "graphics/pg_to_vulkan_types.hpp" #include "utils/logger.hpp" #include <algorithm> #include <iostream> #include <set> #include <string> #include <vector> std::vector< const char* > VK_VALIDATION_LAYERS = { "VK_LAYER_KHRONOS_validation" }; std::vector< const char* > VK_DEVICE_EXTENSIONS = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; namespace Progression { namespace Gfx { RenderState g_renderState; bool PhysicalDeviceInfo::ExtensionSupported( const std::string& extensionName ) const { return std::find( availableExtensions.begin(), availableExtensions.end(), extensionName ) != availableExtensions.end(); } static std::vector< std::string > FindMissingValidationLayers( const std::vector< const char* >& layers ) { uint32_t layerCount; vkEnumerateInstanceLayerProperties( &layerCount, nullptr ); std::vector< VkLayerProperties > availableLayers( layerCount ); vkEnumerateInstanceLayerProperties( &layerCount, availableLayers.data() ); LOG( "Available validation layers:" ); for ( const auto& layerProperties : availableLayers ) { LOG( "\t", layerProperties.layerName ); } std::vector< std::string > missing; for ( const auto& layer : layers ) { bool found = false; for ( const auto& availableLayer : availableLayers ) { if ( strcmp( layer, availableLayer.layerName ) == 0 ) { found = true; break; } } if ( !found ) { missing.push_back( layer ); } } return missing; } static VKAPI_ATTR VkBool32 VKAPI_CALL DebugCallback( VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData ) { PG_UNUSED( pUserData ); std::string messageTypeString; switch ( messageType ) { case VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT: return VK_FALSE; case VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT: messageTypeString = "Validation"; break; case VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT: messageTypeString = "Performance"; break; default: messageTypeString = "Unknown"; } if ( messageSeverity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT ) { LOG_ERR( "Vulkan message type ", messageTypeString, ": ", pCallbackData->pMessage, "'" ); } else if ( messageSeverity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT ) { LOG_WARN( "Vulkan message type ", messageTypeString, ": ", pCallbackData->pMessage, "'" ); } else { LOG( "Vulkan message type ", messageTypeString, ": '", pCallbackData->pMessage, "'" ); } return VK_FALSE; } /** Since the createDebugUtilsMessenger function is from an extension, it is not loaded * automatically. Look up its address manually and call it. */ static bool CreateDebugUtilsMessengerEXT( const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator ) { auto func = ( PFN_vkCreateDebugUtilsMessengerEXT ) vkGetInstanceProcAddr( g_renderState.instance, "vkCreateDebugUtilsMessengerEXT" ); if ( func != nullptr ) { return func( g_renderState.instance, pCreateInfo, pAllocator, &g_renderState.debugMessenger ) == VK_SUCCESS; } else { return false; } } /** Same thing as the CreateDebugUtilsMessenger; load the function manually and call it */ static void DestroyDebugUtilsMessengerEXT( const VkAllocationCallbacks* pAllocator = nullptr ) { auto func = ( PFN_vkDestroyDebugUtilsMessengerEXT ) vkGetInstanceProcAddr( g_renderState.instance, "vkDestroyDebugUtilsMessengerEXT" ); if ( func != nullptr ) { func( g_renderState.instance, g_renderState.debugMessenger, pAllocator ); } } /** \brief Find and select the first avaiable queues for graphics and presentation * Queues are where commands get submitted to and are processed asynchronously. Some queues * might only be usable for certain operations, like graphics or memory operations. * Currently we just need 1 queue for graphics commands, and 1 queue for * presenting the images we create to the surface. */ static QueueFamilyIndices FindQueueFamilies( VkPhysicalDevice device, VkSurfaceKHR surface ) { QueueFamilyIndices indices; uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties( device, &queueFamilyCount, nullptr ); std::vector<VkQueueFamilyProperties> queueFamilies( queueFamilyCount ); vkGetPhysicalDeviceQueueFamilyProperties( device, &queueFamilyCount, queueFamilies.data() ); for ( uint32_t i = 0; i < static_cast< uint32_t >( queueFamilies.size() ) && !indices.IsComplete(); ++i ) { // check if the queue supports graphics operations if ( queueFamilies[i].queueCount > 0 && queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT ) { // check if the queue supports presenting images to the surface VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR( device, i, surface, &presentSupport ); if ( queueFamilies[i].queueCount > 0 && presentSupport ) { indices.presentFamily = i; indices.graphicsFamily = i; } } // check for dedicated compute queue if ( queueFamilies[i].queueCount > 0 && ( queueFamilies[i].queueFlags & VK_QUEUE_COMPUTE_BIT ) && ( ( queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT ) == 0 ) ) { indices.computeFamily = i; } } // if there existed no queuefamily for both graphics and presenting, then look for separate ones if ( indices.graphicsFamily == ~0u ) { for ( uint32_t i = 0; i < static_cast< uint32_t >( queueFamilies.size() ) && !indices.IsComplete(); ++i ) { // check if the queue supports graphics operations if ( queueFamilies[i].queueCount > 0 && queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT ) { indices.graphicsFamily = i; } // check if the queue supports presenting images to the surface VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR( device, i, surface, &presentSupport ); if ( queueFamilies[i].queueCount > 0 && presentSupport ) { indices.presentFamily = i; } } } // Look for first compute queue if no dedicated one exists if ( !indices.IsComplete() ) { for ( uint32_t i = 0; i < static_cast< uint32_t >( queueFamilies.size() ); ++i ) { // check if the queue supports graphics operations if ( queueFamilies[i].queueCount > 0 && queueFamilies[i].queueFlags & VK_QUEUE_COMPUTE_BIT ) { indices.computeFamily = i; break; } } } return indices; } static bool CheckPhysicalDeviceExtensionSupport( const PhysicalDeviceInfo& info ) { for ( const auto& extension : VK_DEVICE_EXTENSIONS ) { if ( !info.ExtensionSupported( extension ) ) { return false; } } return true; } struct SwapChainSupportDetails { VkSurfaceCapabilitiesKHR capabilities; std::vector< VkSurfaceFormatKHR > formats; std::vector< VkPresentModeKHR > presentModes; }; static VkExtent2D ChooseSwapExtent( const VkSurfaceCapabilitiesKHR& capabilities ) { // check if the driver specified the size already if ( capabilities.currentExtent.width != std::numeric_limits< uint32_t >::max() ) { return capabilities.currentExtent; } else { // select the closest feasible resolution possible to the window size int SW = GetMainWindow()->Width(); int SH = GetMainWindow()->Height(); glfwGetFramebufferSize( GetMainWindow()->GetGLFWHandle(), &SW, &SH ); VkExtent2D actualExtent = { static_cast< uint32_t >( SW ), static_cast< uint32_t >( SH ) }; actualExtent.width = std::max( capabilities.minImageExtent.width, std::min( capabilities.maxImageExtent.width, actualExtent.width ) ); actualExtent.height = std::max( capabilities.minImageExtent.height, std::min( capabilities.maxImageExtent.height, actualExtent.height ) ); return actualExtent; } } static VkPresentModeKHR ChooseSwapPresentMode( const std::vector< VkPresentModeKHR >& availablePresentModes ) { VkPresentModeKHR mode = VK_PRESENT_MODE_FIFO_KHR; for (const auto& availablePresentMode : availablePresentModes) { #if USING( WINDOWS_PROGRAM ) if ( availablePresentMode == VK_PRESENT_MODE_IMMEDIATE_KHR ) #else // #if USING( WINDOWS_PROGRAM ) if ( availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR ) #endif // #else // #if USING( WINDOWS_PROGRAM ) { return availablePresentMode; } // else if ( availablePresentMode == VK_PRESENT_MODE_IMMEDIATE_KHR ) // { // mode = availablePresentMode; // } } return mode; } static VkSurfaceFormatKHR ChooseSwapSurfaceFormat( const std::vector< VkSurfaceFormatKHR >& availableFormats ) { // check if the surface has no preferred format (best case) // if ( availableFormats.size() == 1 && availableFormats[0].format == VK_FORMAT_UNDEFINED ) // { // return { VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR }; // } for ( const auto& availableFormat : availableFormats ) { if ( availableFormat.format == VK_FORMAT_B8G8R8A8_UNORM && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR ) { return availableFormat; } } LOG_WARN( "Format not RGBA8 with SRGB colorspace. Instead format = ", availableFormats[0].format, ", colorspace = ", availableFormats[0].colorSpace ); return availableFormats[0]; } static SwapChainSupportDetails QuerySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface) { SwapChainSupportDetails details; vkGetPhysicalDeviceSurfaceCapabilitiesKHR( device, surface, &details.capabilities ); uint32_t formatCount; vkGetPhysicalDeviceSurfaceFormatsKHR( device, surface, &formatCount, nullptr ); if ( formatCount != 0 ) { details.formats.resize( formatCount ); vkGetPhysicalDeviceSurfaceFormatsKHR( device, surface, &formatCount, details.formats.data() ); } uint32_t presentModeCount; vkGetPhysicalDeviceSurfacePresentModesKHR( device, surface, &presentModeCount, nullptr ); if ( presentModeCount != 0 ) { details.presentModes.resize( presentModeCount ); vkGetPhysicalDeviceSurfacePresentModesKHR( device, surface, &presentModeCount, details.presentModes.data() ); } return details; } /** Return a rating of how good this device is. 0 is incompatible, and the higher the better. */ static int RatePhysicalDevice( const PhysicalDeviceInfo& deviceInfo ) { // check the required features first: queueFamilies, extension support, // and swap chain support bool extensionsSupported = CheckPhysicalDeviceExtensionSupport( deviceInfo ); bool swapChainAdequate = false; if ( extensionsSupported ) { SwapChainSupportDetails swapChainSupport = QuerySwapChainSupport( deviceInfo.device, g_renderState.surface ); swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty(); } if ( !deviceInfo.indices.IsComplete() || !extensionsSupported || !swapChainAdequate || !deviceInfo.deviceFeatures.samplerAnisotropy ) { return 0; } int score = 10; if ( deviceInfo.deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU ) { score += 1000; } return score; } static bool CreateInstance() { // struct that holds info about our application. Mainly used by some layers / drivers // for labeling debug messages, logging, etc. Possible for drivers to run differently // depending on the application that is running. VkApplicationInfo appInfo = {}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pNext = nullptr; // pointer to extension information appInfo.pApplicationName = "Progression"; appInfo.applicationVersion = VK_MAKE_VERSION( 1, 0, 0 ); appInfo.pEngineName = "Progression"; appInfo.engineVersion = VK_MAKE_VERSION( 1, 0, 0 ); appInfo.apiVersion = VK_API_VERSION_1_1; // non-optional struct that specifies which global extension and validation layers to use VkInstanceCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pApplicationInfo = &appInfo; // Vulkan by itself doesn't know how to do any platform specifc things, so we do need // extensions. Specifically, we at least need the ones to interface with the windowing API, // so ask glfw for the extensions needed for this. These are global to the program. uint32_t glfwExtensionCount = 0; const char** glfwExtensions = glfwGetRequiredInstanceExtensions( &glfwExtensionCount ); std::vector<const char*> extensionNames( glfwExtensions, glfwExtensions + glfwExtensionCount ); #if !USING( SHIP_BUILD ) // Also want the debug utils extension so we can print out layer messages extensionNames.push_back( VK_EXT_DEBUG_UTILS_EXTENSION_NAME ); #endif // #if !USING( SHIP_BUILD ) createInfo.enabledExtensionCount = static_cast< uint32_t >( extensionNames.size() ); createInfo.ppEnabledExtensionNames = extensionNames.data(); // Specify global validation layers #if !USING( SHIP_BUILD ) createInfo.enabledLayerCount = static_cast< uint32_t >( VK_VALIDATION_LAYERS.size() ); createInfo.ppEnabledLayerNames = VK_VALIDATION_LAYERS.data(); #else // #if !USING( SHIP_BUILD ) createInfo.enabledLayerCount = 0; #endif // #else // #if !USING( SHIP_BUILD ) auto ret = vkCreateInstance( &createInfo, nullptr, &g_renderState.instance ); if ( ret == VK_ERROR_EXTENSION_NOT_PRESENT ) { LOG_ERR( "Could not find all of the instance extensions" ); } else if ( ret == VK_ERROR_LAYER_NOT_PRESENT ) { auto missingLayers = FindMissingValidationLayers( VK_VALIDATION_LAYERS ); LOG_ERR( "Could not find the following validation layers: " ); for ( const auto& layer : missingLayers ) { LOG_ERR( "\t", layer ); } } else if ( ret != VK_SUCCESS ) { LOG_ERR( "Error while creating instance: ", ret ); } return ret == VK_SUCCESS; } static bool SetupDebugCallback() { VkDebugUtilsMessengerCreateInfoEXT createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; // | VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT; // general verbose debug info createInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; createInfo.pfnUserCallback = DebugCallback; createInfo.pUserData = nullptr; return CreateDebugUtilsMessengerEXT( &createInfo, nullptr ); } static bool CreateSurface() { return glfwCreateWindowSurface( g_renderState.instance, GetMainWindow()->GetGLFWHandle(), nullptr, &g_renderState.surface ) == VK_SUCCESS; } static bool PickPhysicalDevice() { uint32_t deviceCount = 0; vkEnumeratePhysicalDevices( g_renderState.instance, &deviceCount, nullptr ); if ( deviceCount == 0 ) { return false; } std::vector< VkPhysicalDevice > devices( deviceCount ); vkEnumeratePhysicalDevices( g_renderState.instance, &deviceCount, devices.data() ); std::vector< PhysicalDeviceInfo > deviceInfos( deviceCount ); for ( uint32_t i = 0; i < deviceCount; ++i ) { deviceInfos[i].device = devices[i]; vkGetPhysicalDeviceProperties( devices[i], &deviceInfos[i].deviceProperties ); vkGetPhysicalDeviceFeatures( devices[i], &deviceInfos[i].deviceFeatures ); deviceInfos[i].deviceFeatures.samplerAnisotropy = VK_TRUE; uint32_t extensionCount; vkEnumerateDeviceExtensionProperties( deviceInfos[i].device, nullptr, &extensionCount, nullptr ); std::vector< VkExtensionProperties > availableExtensions( extensionCount ); vkEnumerateDeviceExtensionProperties( deviceInfos[i].device, nullptr, &extensionCount, availableExtensions.data() ); deviceInfos[i].availableExtensions.resize( availableExtensions.size() ); for ( size_t ext = 0; ext < availableExtensions.size(); ++ext ) { deviceInfos[i].availableExtensions[ext] = availableExtensions[ext].extensionName; } deviceInfos[i].name = deviceInfos[i].deviceProperties.deviceName; deviceInfos[i].indices = FindQueueFamilies( devices[i], g_renderState.surface ); deviceInfos[i].score = RatePhysicalDevice( deviceInfos[i] ); } // sort and select the best GPU available std::sort( deviceInfos.begin(), deviceInfos.end(), []( const auto& lhs, const auto& rhs ) { return lhs.score > rhs.score; } ); auto& physicalInfo = g_renderState.physicalDeviceInfo; physicalInfo = deviceInfos[0]; if ( physicalInfo.score <= 0 ) { physicalInfo.device = VK_NULL_HANDLE; return false; } vkGetPhysicalDeviceMemoryProperties( physicalInfo.device, &physicalInfo.memProperties ); return true; } static bool CreateRenderPass() { RenderPassDescriptor renderPassDesc; renderPassDesc.colorAttachmentDescriptors[0].format = VulkanToPGPixelFormat( g_renderState.swapChain.imageFormat ); renderPassDesc.colorAttachmentDescriptors[0].finalLayout = ImageLayout::PRESENT_SRC_KHR; renderPassDesc.depthAttachmentDescriptor.format = PixelFormat::DEPTH_32_FLOAT; renderPassDesc.depthAttachmentDescriptor.loadAction = LoadAction::CLEAR; renderPassDesc.depthAttachmentDescriptor.storeAction = StoreAction::DONT_CARE; renderPassDesc.depthAttachmentDescriptor.finalLayout = ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL; renderPassDesc.depthAttachmentDescriptor.finalLayout = ImageLayout::PRESENT_SRC_KHR; g_renderState.renderPass = g_renderState.device.NewRenderPass( renderPassDesc, "final output" ); return g_renderState.renderPass; } static bool CreateDepthTexture() { ImageDescriptor info; info.type = ImageType::TYPE_2D; info.format = PixelFormat::DEPTH_32_FLOAT; info.width = g_renderState.swapChain.extent.width; info.height = g_renderState.swapChain.extent.height; info.sampler = "nearest_clamped_nearest"; info.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; g_renderState.depthTex = g_renderState.device.NewTexture( info, false, "main depth texture" ); return g_renderState.depthTex; } static bool CreateSwapChainFrameBuffers() { VkImageView attachments[2]; attachments[1] = g_renderState.depthTex.GetView(); VkFramebufferCreateInfo framebufferInfo = {}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = g_renderState.renderPass.GetHandle(); framebufferInfo.attachmentCount = 2; framebufferInfo.pAttachments = attachments; framebufferInfo.width = g_renderState.swapChain.extent.width; framebufferInfo.height = g_renderState.swapChain.extent.height; framebufferInfo.layers = 1; g_renderState.swapChainFramebuffers.resize( g_renderState.swapChain.images.size() ); for ( size_t i = 0; i < g_renderState.swapChain.images.size(); ++i ) { attachments[0] = g_renderState.swapChain.imageViews[i]; g_renderState.swapChainFramebuffers[i] = g_renderState.device.NewFramebuffer( framebufferInfo, "swapchain " + std::to_string( i ) ); if ( !g_renderState.swapChainFramebuffers[i] ) { return false; } } return true; } static bool CreateCommandPoolAndBuffers() { g_renderState.graphicsCommandPool = g_renderState.device.NewCommandPool( COMMAND_POOL_RESET_COMMAND_BUFFER, CommandPoolQueueFamily::GRAPHICS, "global graphics" ); g_renderState.computeCommandPool = g_renderState.device.NewCommandPool( COMMAND_POOL_RESET_COMMAND_BUFFER, CommandPoolQueueFamily::COMPUTE, "global compute" ); g_renderState.transientCommandPool = g_renderState.device.NewCommandPool( COMMAND_POOL_TRANSIENT, CommandPoolQueueFamily::GRAPHICS, "global graphics transient" ); if ( !g_renderState.graphicsCommandPool || !g_renderState.transientCommandPool || !g_renderState.computeCommandPool ) { return false; } g_renderState.computeCommandBuffer = g_renderState.computeCommandPool.NewCommandBuffer( "compute" ); g_renderState.graphicsCommandBuffer = g_renderState.graphicsCommandPool.NewCommandBuffer( "global graphics" ); if ( !g_renderState.graphicsCommandBuffer ) { return false; } return true; } static bool CreateSynchronizationObjects() { g_renderState.presentCompleteSemaphore = g_renderState.device.NewSemaphore( "present complete" ); g_renderState.renderCompleteSemaphore = g_renderState.device.NewSemaphore( "render complete" ); g_renderState.computeFence = g_renderState.device.NewFence( true, "compute" ); return true; } bool SwapChain::Create( VkDevice dev ) { device = dev; SwapChainSupportDetails swapChainSupport = QuerySwapChainSupport( g_renderState.physicalDeviceInfo.device, g_renderState.surface ); VkSurfaceFormatKHR surfaceFormat = ChooseSwapSurfaceFormat( swapChainSupport.formats ); VkPresentModeKHR presentMode = ChooseSwapPresentMode( swapChainSupport.presentModes ); imageFormat = surfaceFormat.format; extent = ChooseSwapExtent( swapChainSupport.capabilities ); uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1; if ( swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount ) { imageCount = swapChainSupport.capabilities.maxImageCount; } VkSwapchainCreateInfoKHR createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; createInfo.surface = g_renderState.surface; createInfo.minImageCount = imageCount; createInfo.imageFormat = surfaceFormat.format; createInfo.imageColorSpace = surfaceFormat.colorSpace; createInfo.imageExtent = extent; createInfo.imageArrayLayers = 1; // always 1 unless doing VR createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; const auto& indices = g_renderState.physicalDeviceInfo.indices; uint32_t queueFamilyIndices[] = { indices.graphicsFamily, indices.presentFamily, indices.computeFamily }; if ( indices.graphicsFamily != indices.presentFamily ) { LOG_WARN( "Graphics queue is not the same as the presentation queue! Possible performance drop" ); createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; createInfo.queueFamilyIndexCount = 3; createInfo.pQueueFamilyIndices = queueFamilyIndices; } else { createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; } // can specify transforms to happen (90 rotation, horizontal flip, etc). None used for now createInfo.preTransform = swapChainSupport.capabilities.currentTransform; createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; createInfo.presentMode = presentMode; createInfo.clipped = VK_TRUE; // only applies if you have to create a new swap chain (like on window resizing) createInfo.oldSwapchain = VK_NULL_HANDLE; if ( vkCreateSwapchainKHR( device, &createInfo, nullptr, &swapChain ) != VK_SUCCESS ) { return false; } PG_DEBUG_MARKER_SET_SWAPCHAIN_NAME( swapChain, "global" ); vkGetSwapchainImagesKHR( device, swapChain, &imageCount, nullptr ); images.resize( imageCount ); vkGetSwapchainImagesKHR( device, swapChain, &imageCount, images.data() ); // image views imageViews.resize( images.size() ); for ( size_t i = 0; i < images.size(); ++i ) { imageViews[i] = CreateImageView( images[i], imageFormat, VK_IMAGE_ASPECT_COLOR_BIT, 1 ); PG_DEBUG_MARKER_SET_IMAGE_VIEW_NAME( imageViews[i], "swapchain image " + std::to_string( i ) ); PG_DEBUG_MARKER_SET_IMAGE_ONLY_NAME( images[i], "swapchain " + std::to_string( i ) ); } return true; } uint32_t SwapChain::AcquireNextImage( const Semaphore& presentCompleteSemaphore ) { vkAcquireNextImageKHR( device, swapChain, UINT64_MAX, presentCompleteSemaphore.GetHandle(), VK_NULL_HANDLE, &currentImage ); return currentImage; } bool VulkanInit() { if ( !CreateInstance() ) { LOG_ERR( "Could not create vulkan instance" ); return false; } #if !USING( SHIP_BUILD ) if ( !SetupDebugCallback() ) { LOG_ERR( "Could not setup the debug callback" ); return false; } #endif // #if !USING( SHIP_BUILD ) if ( !CreateSurface() ) { LOG_ERR( "Could not create glfw vulkan surface" ); return false; } if ( !PickPhysicalDevice() ) { LOG_ERR( "Could not find any suitable GPU device to use" ); return false; } g_renderState.device = Device::CreateDefault(); if ( !g_renderState.device ) { LOG_ERR( "Could not create logical device" ); return false; } DebugMarker::Init( g_renderState.device.GetHandle(), g_renderState.physicalDeviceInfo.device ); LOG( "Using device: ", g_renderState.physicalDeviceInfo.name ); // PG_DEBUG_MARKER_SET_PHYSICAL_DEVICE_NAME( g_renderState.physicalDeviceInfo.device, g_renderState.physicalDeviceInfo.name ); PG_DEBUG_MARKER_SET_INSTANCE_NAME( g_renderState.instance, "global" ); PG_DEBUG_MARKER_SET_LOGICAL_DEVICE_NAME( g_renderState.device, "default" ); PG_DEBUG_MARKER_SET_QUEUE_NAME( g_renderState.device.GraphicsQueue(), "graphics" ); PG_DEBUG_MARKER_SET_QUEUE_NAME( g_renderState.device.PresentQueue(), "present" ); RenderSystem::InitSamplers(); if ( !g_renderState.swapChain.Create( g_renderState.device.GetHandle() ) ) { LOG_ERR( "Could not create swap chain" ); return false; } if ( !CreateRenderPass() ) { LOG_ERR( "Could not create render pass" ); return false; } if ( !CreateDepthTexture() ) { LOG_ERR( "Could not create depth texture" ); return false; } if ( !CreateSwapChainFrameBuffers() ) { LOG_ERR( "Could not create swap chain framebuffers" ); return false; } if ( !CreateCommandPoolAndBuffers() ) { LOG_ERR( "Could not create commandPool / buffers" ); return false; } if ( !CreateSynchronizationObjects() ) { LOG_ERR( "Could not create synchronization objects" ); return false; } return true; } void VulkanShutdown() { RenderSystem::FreeSamplers(); VkDevice dev = g_renderState.device.GetHandle(); g_renderState.presentCompleteSemaphore.Free(); g_renderState.renderCompleteSemaphore.Free(); g_renderState.computeFence.Free(); g_renderState.depthTex.Free(); g_renderState.graphicsCommandPool.Free(); g_renderState.computeCommandPool.Free(); g_renderState.transientCommandPool.Free(); for ( auto framebuffer : g_renderState.swapChainFramebuffers ) { framebuffer.Free(); } g_renderState.renderPass.Free(); for ( size_t i = 0; i < g_renderState.swapChain.imageViews.size(); ++i ) { vkDestroyImageView( dev, g_renderState.swapChain.imageViews[i], nullptr ); } vkDestroySwapchainKHR( dev, g_renderState.swapChain.swapChain, nullptr); g_renderState.device.Free(); DestroyDebugUtilsMessengerEXT(); vkDestroySurfaceKHR( g_renderState.instance, g_renderState.surface, nullptr ); vkDestroyInstance( g_renderState.instance, nullptr ); } uint32_t FindMemoryType( uint32_t typeFilter, VkMemoryPropertyFlags properties ) { auto& memProperties = g_renderState.physicalDeviceInfo.memProperties; for ( uint32_t i = 0; i < memProperties.memoryTypeCount; ++i ) { if ( ( typeFilter & ( 1 << i ) ) && ( memProperties.memoryTypes[i].propertyFlags & properties ) == properties ) { return i; } } PG_ASSERT( false ); return ~0u; } void TransitionImageLayout( VkImage image, VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, uint32_t layers ) { CommandBuffer cmdBuf = g_renderState.transientCommandPool.NewCommandBuffer(); cmdBuf.BeginRecording( COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT ); VkImageMemoryBarrier barrier = {}; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.oldLayout = oldLayout; barrier.newLayout = newLayout; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.image = image; barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.levelCount = mipLevels; barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.layerCount = layers; barrier.srcAccessMask = 0; barrier.dstAccessMask = 0; PG_UNUSED( format ); VkPipelineStageFlags srcStage, dstStage; if ( oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ) { barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT; } else if ( oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL ) { barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT; dstStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; } else { PG_ASSERT( false, "The transition barriers are unknown for the given old and new layouts" ); } cmdBuf.PipelineBarrier( srcStage, dstStage, barrier ); cmdBuf.EndRecording(); g_renderState.device.Submit( cmdBuf ); g_renderState.device.WaitForIdle(); cmdBuf.Free(); } bool FormatSupported( VkFormat format, VkFormatFeatureFlags requestedSupport ) { VkFormatProperties props; vkGetPhysicalDeviceFormatProperties( g_renderState.physicalDeviceInfo.device, format, &props ); return ( props.optimalTilingFeatures & requestedSupport ) == requestedSupport; } VkImageView CreateImageView( VkImage image, VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels, uint32_t layers ) { VkImageViewCreateInfo viewCreateInfo = {}; viewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; viewCreateInfo.image = image; PG_ASSERT( layers == 1 || layers == 6 ); viewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; if ( layers == 6 ) { viewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_CUBE; } viewCreateInfo.format = format; viewCreateInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; viewCreateInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; viewCreateInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; viewCreateInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; // specify image purpose and which part to access viewCreateInfo.subresourceRange.aspectMask = aspectFlags; viewCreateInfo.subresourceRange.baseMipLevel = 0; viewCreateInfo.subresourceRange.levelCount = mipLevels; viewCreateInfo.subresourceRange.baseArrayLayer = 0; viewCreateInfo.subresourceRange.layerCount = layers; VkImageView view; VkResult res = vkCreateImageView( g_renderState.device.GetHandle(), &viewCreateInfo, nullptr, &view ); PG_ASSERT( res == VK_SUCCESS ); return view; } } // namespace Gfx } // namespace Progression
37.117647
172
0.695302
[ "render", "vector" ]
97a3f978bf3d11831e60e44d67d1fc6790597f8e
2,877
cpp
C++
src/game/engine/rendering-unit.cpp
strdavis/tetris-clone
299b2cc954b87edff5c2d54bfc222d488925f4bd
[ "MIT" ]
1
2020-12-26T11:46:32.000Z
2020-12-26T11:46:32.000Z
src/game/engine/rendering-unit.cpp
strdavis/tetris-clone
299b2cc954b87edff5c2d54bfc222d488925f4bd
[ "MIT" ]
null
null
null
src/game/engine/rendering-unit.cpp
strdavis/tetris-clone
299b2cc954b87edff5c2d54bfc222d488925f4bd
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2020 Spencer Davis * * 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 "rendering-unit.h" #include <iostream> #include "SDL.h" #include "SDL_gpu.h" #include "game-element.h" #include "sprite.h" using std::vector; using std::shared_ptr; using std::make_shared; RenderingUnit::RenderingUnit(GPU_Target *window) : window(window) { setWindowCentre(); } void RenderingUnit::drawSprites(vector <shared_ptr <Sprite>> sprites) { GPU_Clear(window); // Copy all sprites to the frame buffer for (auto sprite : sprites) { // Many sprites can share the same image, but have different sizes, // so the virtual resolution must be set for each sprite before it is drawn. GPU_SetImageVirtualResolution(sprite->getRawImage(), sprite->getWidth(), sprite->getHeight()); // Convert origin-relative coordinates of each sprite to absolute coordinates. SDL_Point absPos = calculateAbsPos(sprite->getPos()); blit(sprite->getRawImage(), window, absPos); } // Swap current rendered frame with frame buffer contents GPU_Flip(window); } SDL_Point RenderingUnit::calculateAbsPos(SDL_Point posRelOrigin) { SDL_Point absPos = windowCentre; absPos.x += posRelOrigin.x; absPos.y -= posRelOrigin.y; return absPos; } void RenderingUnit::blit(GPU_Image *rawImage, GPU_Target *window, SDL_Point pos) { // Remember that GPU_Blit() draws the image *centered* at the given position GPU_Blit(rawImage, NULL, window, pos.x, pos.y); } void RenderingUnit::setWindowCentre() { Uint16 width; Uint16 height; GPU_GetVirtualResolution(window, &width, &height); windowCentre = {(width / 2), (height / 2)}; }
29.060606
86
0.696211
[ "vector" ]
97a5bd2501e0fbd887a9563572220acabce63940
7,457
cc
C++
arc/vm/libvda/decode_gpu_test.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
arc/vm/libvda/decode_gpu_test.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
arc/vm/libvda/decode_gpu_test.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdint.h> #include <unistd.h> #include <memory> #include <string> #include <vector> #include <base/at_exit.h> #include <base/command_line.h> #include <base/files/file_path.h> #include <base/files/file_util.h> #include <base/logging.h> #include <base/macros.h> #include <base/memory/writable_shared_memory_region.h> #include <base/posix/eintr_wrapper.h> #include <base/strings/string_util.h> #include <base/threading/platform_thread.h> #include <base/time/time.h> #include <base/timer/elapsed_timer.h> #include <gtest/gtest.h> #include "arc/vm/libvda/decode/test/decode_event_thread.h" #include "arc/vm/libvda/decode/test/decode_unittest_common.h" #include "arc/vm/libvda/decode/test/encoded_data_helper.h" #include "arc/vm/libvda/libvda_decode.h" namespace { // Maximum number of running decodes. constexpr uint32_t kMaxDecodes = 20; base::FilePath GetTestVideoFilePath(const base::CommandLine* cmd_line) { base::FilePath path = cmd_line->GetSwitchValuePath("test_video_file"); if (path.empty()) path = base::FilePath("test-25fps.h264"); if (!path.IsAbsolute()) path = base::MakeAbsoluteFilePath(path); return path; } vda_profile_t GetVideoFileProfile(const base::FilePath& video_file) { const std::string& extension = video_file.Extension(); if (base::EqualsCaseInsensitiveASCII(extension, ".h264")) return H264PROFILE_MAIN; if (base::EqualsCaseInsensitiveASCII(extension, ".vp8")) return VP8PROFILE_ANY; if (base::EqualsCaseInsensitiveASCII(extension, ".vp9")) return VP9PROFILE_MIN; LOG(ERROR) << "Unsupported file extension: " << extension; return VIDEO_CODEC_PROFILE_UNKNOWN; } bool WaitForDecodesDone(arc::test::DecodeEventThread* event_thread, uint32_t* waiting_decodes, uint32_t max_decodes) { constexpr base::TimeDelta wait_interval = base::Milliseconds(5); constexpr base::TimeDelta max_wait_time = base::Seconds(5); base::ElapsedTimer wait_timer; while (wait_timer.Elapsed() < max_wait_time) { *waiting_decodes -= event_thread->GetAndClearEndOfBitstreamBufferEventCount(); if (*waiting_decodes <= max_decodes) return true; base::PlatformThread::Sleep(wait_interval); } return false; } } // namespace class LibvdaGpuTest : public ::testing::Test { public: LibvdaGpuTest() = default; LibvdaGpuTest(const LibvdaGpuTest&) = delete; LibvdaGpuTest& operator=(const LibvdaGpuTest&) = delete; ~LibvdaGpuTest() override = default; }; // Test that the gpu implementation initializes and deinitializes successfully. TEST_F(LibvdaGpuTest, InitializeGpu) { ImplPtr impl = SetupImpl(GAVDA); ASSERT_NE(impl, nullptr); } // Test that the GPU implementation creates and closes a decode session // successfully. TEST_F(LibvdaGpuTest, InitDecodeSessionGpu) { ImplPtr impl = SetupImpl(GAVDA); ASSERT_NE(impl, nullptr); SessionPtr session = SetupSession(impl, H264PROFILE_MAIN); ASSERT_NE(session, nullptr); EXPECT_NE(session->ctx, nullptr); EXPECT_GT(session->event_pipe_fd, 0); } // Test that the gpu implementation has valid input and output capabilities. TEST_F(LibvdaGpuTest, GetCapabilitiesGpu) { ImplPtr impl = SetupImpl(GAVDA); ASSERT_NE(impl, nullptr); const vda_capabilities_t* capabilities = get_vda_capabilities(impl.get()); EXPECT_GT(capabilities->num_input_formats, 0); EXPECT_NE(capabilities->input_formats, nullptr); EXPECT_GT(capabilities->num_output_formats, 0); EXPECT_NE(capabilities->output_formats, nullptr); } // Tests the full decode flow using a provided video file. This tests several // things: // - shmem data can successfully be passed using vda_decode. // - dmabuf handles can successfully be passed using vda_use_output_buffer. // - PictureReady, ProvidePictureBuffers, NotifyEndOfBitstreamBuffer events are // successfully propagated. TEST_F(LibvdaGpuTest, DecodeFileGpu) { const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess(); ASSERT_NE(cmd_line, nullptr); base::FilePath test_video_file(GetTestVideoFilePath(cmd_line)); ASSERT_TRUE(!test_video_file.empty()); // TODO(alexlau): Check more parameters (num frames, fragments, fps) similar // to VDA tests, perhaps reading from JSON file. vda_profile_t file_profile = GetVideoFileProfile(test_video_file); ASSERT_NE(file_profile, VIDEO_CODEC_PROFILE_UNKNOWN); int64_t file_size; ASSERT_EQ(base::GetFileSize(test_video_file, &file_size), true); ASSERT_GT(file_size, 0); VLOG(3) << "Test file: " << test_video_file.value() << ", VDA profile: " << file_profile << ", file size: " << file_size; std::vector<uint8_t> data(file_size); ASSERT_EQ( base::ReadFile(test_video_file, reinterpret_cast<char*>(data.data()), base::checked_cast<int>(file_size)), file_size); ImplPtr impl = SetupImpl(GAVDA); ASSERT_NE(impl, nullptr); SessionPtr session = SetupSession(impl, file_profile); ASSERT_NE(session, nullptr); const vda_capabilities_t* capabilities = get_vda_capabilities(impl.get()); EXPECT_GT(capabilities->num_input_formats, 0); EXPECT_NE(capabilities->input_formats, nullptr); EXPECT_GT(capabilities->num_output_formats, 0); EXPECT_NE(capabilities->output_formats, nullptr); arc::test::DecodeEventThread event_thread(capabilities, session.get()); event_thread.Start(); EncodedDataHelper encoded_data_helper(data, file_profile); int32_t next_bitstream_id = 1; uint32_t waiting_decodes = 0; while (!encoded_data_helper.ReachEndOfStream()) { std::string data = encoded_data_helper.GetBytesForNextData(); size_t data_size = data.size(); ASSERT_NE(data_size, 0); base::WritableSharedMemoryRegion shm_region = base::WritableSharedMemoryRegion::Create(data_size); base::WritableSharedMemoryMapping shm_mapping = shm_region.Map(); base::subtle::PlatformSharedMemoryRegion platform_shm = base::WritableSharedMemoryRegion::TakeHandleForSerialization( std::move(shm_region)); memcpy(shm_mapping.GetMemoryAs<uint8_t>(), data.data(), data_size); base::ScopedFD handle(std::move(platform_shm.PassPlatformHandle().fd)); ASSERT_GT(handle.get(), 0); int32_t bitstream_id = next_bitstream_id; next_bitstream_id = (next_bitstream_id + 1) & 0x3FFFFFFF; // Pass ownership of handle to vda_decode. vda_decode(session->ctx, bitstream_id, handle.release(), 0 /* offset */, data_size /* bytes_used */); waiting_decodes++; if (waiting_decodes > kMaxDecodes) { VLOG(3) << "Waiting for some decodes to finish, currently at " << waiting_decodes; ASSERT_TRUE( WaitForDecodesDone(&event_thread, &waiting_decodes, kMaxDecodes)); VLOG(3) << "Some decodes finished, currently at " << waiting_decodes; } } if (waiting_decodes > 0) { VLOG(3) << "Waiting for remaining decodes to finish."; ASSERT_TRUE(WaitForDecodesDone(&event_thread, &waiting_decodes, 0)); VLOG(3) << "Remaining decodes have finished."; } } int main(int argc, char** argv) { base::CommandLine::Init(argc, argv); logging::InitLogging(logging::LoggingSettings()); base::ShadowingAtExitManager at_exit_manager_; ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
35.00939
79
0.73488
[ "vector" ]
97a9ebde3141fd1289c588e88827c2c6338f8c2b
4,540
cpp
C++
src/server/implementation/objects/ImageOverlayFilterImpl.cpp
synergysky/kms-filters
ec9da10a17246363491abddc2f8b898c83e2b195
[ "Apache-2.0" ]
19
2015-10-08T15:19:37.000Z
2021-11-25T07:09:27.000Z
src/server/implementation/objects/ImageOverlayFilterImpl.cpp
synergysky/kms-filters
ec9da10a17246363491abddc2f8b898c83e2b195
[ "Apache-2.0" ]
4
2018-07-30T13:58:15.000Z
2021-11-22T14:07:19.000Z
src/server/implementation/objects/ImageOverlayFilterImpl.cpp
synergysky/kms-filters
ec9da10a17246363491abddc2f8b898c83e2b195
[ "Apache-2.0" ]
77
2015-01-09T06:44:59.000Z
2022-02-08T10:43:53.000Z
/* * (C) Copyright 2016 Kurento (http://kurento.org/) * * 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 <gst/gst.h> #include "MediaPipeline.hpp" #include "MediaPipelineImpl.hpp" #include <ImageOverlayFilterImplFactory.hpp> #include "ImageOverlayFilterImpl.hpp" #include <jsonrpc/JsonSerializer.hpp> #include <KurentoException.hpp> #define GST_CAT_DEFAULT kurento_image_overlay_filter_impl GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoImageOverlayFilterImpl" #define IMAGES_TO_OVERLAY "images-to-overlay" namespace kurento { ImageOverlayFilterImpl::ImageOverlayFilterImpl (const boost::property_tree::ptree &config, std::shared_ptr<MediaPipeline> mediaPipeline) : FilterImpl (config, std::dynamic_pointer_cast<MediaObjectImpl> ( mediaPipeline) ) { g_object_set (element, "filter-factory", "logooverlay", NULL); g_object_get (G_OBJECT (element), "filter", &imageOverlay, NULL); if (imageOverlay == nullptr) { throw KurentoException (MEDIA_OBJECT_NOT_AVAILABLE, "Media Object not available"); } gst_object_unref (imageOverlay); } void ImageOverlayFilterImpl::removeImage (const std::string &id) { GstStructure *imagesLayout; gint len; /* The function obtains the actual window list */ g_object_get (G_OBJECT (imageOverlay), IMAGES_TO_OVERLAY, &imagesLayout, NULL); len = gst_structure_n_fields (imagesLayout); if (len == 0) { GST_WARNING ("There are no images in the layout"); return; } for (int i = 0; i < len; i++) { const gchar *name; name = gst_structure_nth_field_name (imagesLayout, i); if (strcmp (id.c_str (), name) == 0) { /* this image will be removed */ gst_structure_remove_field (imagesLayout, name); break; } } /* Set the buttons layout list without the window with id = id */ g_object_set (G_OBJECT (imageOverlay), IMAGES_TO_OVERLAY, imagesLayout, NULL); gst_structure_free (imagesLayout); } void ImageOverlayFilterImpl::addImage (const std::string &id, const std::string &uri, float offsetXPercent, float offsetYPercent, float widthPercent, float heightPercent, bool keepAspectRatio, bool center) { GstStructure *imagesLayout, *imageSt; imageSt = gst_structure_new ("image_position", "id", G_TYPE_STRING, id.c_str (), "uri", G_TYPE_STRING, uri.c_str (), "offsetXPercent", G_TYPE_FLOAT, float (offsetXPercent), "offsetYPercent", G_TYPE_FLOAT, float (offsetYPercent), "widthPercent", G_TYPE_FLOAT, float (widthPercent), "heightPercent", G_TYPE_FLOAT, float (heightPercent), "keepAspectRatio", G_TYPE_BOOLEAN, keepAspectRatio, "center", G_TYPE_BOOLEAN, center, NULL); /* The function obtains the actual window list */ g_object_get (G_OBJECT (imageOverlay), IMAGES_TO_OVERLAY, &imagesLayout, NULL); gst_structure_set (imagesLayout, id.c_str(), GST_TYPE_STRUCTURE, imageSt, NULL); g_object_set (G_OBJECT (imageOverlay), IMAGES_TO_OVERLAY, imagesLayout, NULL); gst_structure_free (imagesLayout); gst_structure_free (imageSt); } MediaObjectImpl * ImageOverlayFilterImplFactory::createObject (const boost::property_tree::ptree &config, std::shared_ptr<MediaPipeline> mediaPipeline) const { return new ImageOverlayFilterImpl (config, mediaPipeline); } ImageOverlayFilterImpl::StaticConstructor ImageOverlayFilterImpl::staticConstructor; ImageOverlayFilterImpl::StaticConstructor::StaticConstructor() { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } } /* kurento */
34.135338
106
0.667841
[ "object" ]
97ac27101efe655a731ac4368127320923ae7360
1,129
cpp
C++
problems/cs-grip/Dynamic Programming/LCS.cpp
DeathNet123/Team7-ICPC-CP3
a80404de3dbba761b842f4096c254fe667d11adb
[ "MIT" ]
null
null
null
problems/cs-grip/Dynamic Programming/LCS.cpp
DeathNet123/Team7-ICPC-CP3
a80404de3dbba761b842f4096c254fe667d11adb
[ "MIT" ]
null
null
null
problems/cs-grip/Dynamic Programming/LCS.cpp
DeathNet123/Team7-ICPC-CP3
a80404de3dbba761b842f4096c254fe667d11adb
[ "MIT" ]
null
null
null
#include<iostream> #include<algorithm> #include<string> #include<vector> using namespace std; int** LCS(string x, string y) { int **dp = new int *[x.length()+1]; for(int idx = 0; idx < x.length()+1; idx++) { dp[idx] = new int[y.length()+1]; for(int kdx = 0; kdx < y.length()+1; kdx++) { dp[idx][kdx] = 0; } } for(int idx = 1; idx <= x.length(); idx++) { for(int kdx = 1; kdx <= y.length(); kdx++) { if(x[idx-1] == y[kdx-1]) dp[idx][kdx] = dp[idx-1][kdx-1] + 1; else { dp[idx][kdx] = max(dp[idx-1][kdx], dp[idx][kdx-1]); } } } for(int idx = 0; idx <= x.length(); idx++) { for(int kdx = 0; kdx <= y.length(); kdx++) { cout<<dp[idx][kdx]<<" "; } cout<<"\n"; } return dp; } void print_lcs(string x, int idx, int kdx) { if(idx == 0 || kdx == 0) return; } int main(void) { string x = "AABCBAALMNO"; string y = "NFEQRAAAA"; LCS(x, y); return 0; }
23.040816
74
0.420726
[ "vector" ]
97b273fbe48c396cb05828e460bb620ca0107eff
9,494
cc
C++
src/ila/instr_lvl_abs.cc
yuex1994/iw_ilang
e31ffdca4e2c6503804e229b54a44211eb214980
[ "MIT" ]
null
null
null
src/ila/instr_lvl_abs.cc
yuex1994/iw_ilang
e31ffdca4e2c6503804e229b54a44211eb214980
[ "MIT" ]
null
null
null
src/ila/instr_lvl_abs.cc
yuex1994/iw_ilang
e31ffdca4e2c6503804e229b54a44211eb214980
[ "MIT" ]
null
null
null
/// \file /// The source for the class InstrLvlAbs. #include <ilang/ila/instr_lvl_abs.h> #include <ilang/util/log.h> // Do the simplification by hashing AST sub-trees. static const bool kUnifyAst = false; // please design a better hash function -- HZ // ISSUE: hash collision on large designs like AES128 function namespace ilang { InstrLvlAbs::InstrLvlAbs(const std::string& name, const InstrLvlAbsPtr parent) : Object(name), parent_(parent) { ILA_WARN_IF(name == "") << "ILA name not specified..."; InitObject(); } InstrLvlAbs::~InstrLvlAbs() {} InstrLvlAbsPtr InstrLvlAbs::New(const std::string& name, const InstrLvlAbsPtr parent) { return std::make_shared<InstrLvlAbs>(name, parent); } const ExprPtr InstrLvlAbs::input(const std::string& name) const { auto inp = find_input(Symbol(name)); return inp; } const ExprPtr InstrLvlAbs::state(const std::string& name) const { auto stt = find_state(Symbol(name)); return stt; } const InstrPtr InstrLvlAbs::instr(const std::string& name) const { auto instr = find_instr(Symbol(name)); return instr; } const InstrLvlAbsPtr InstrLvlAbs::child(const std::string& name) const { auto child = find_child(Symbol(name)); return child; } const ExprPtr InstrLvlAbs::find_input(const Symbol& name) const { auto pos = inputs_.find(name); return (pos == inputs_.end()) ? NULL : pos->second; } const ExprPtr InstrLvlAbs::find_state(const Symbol& name) const { auto pos = states_.find(name); return (pos == states_.end()) ? NULL : pos->second; } const InstrPtr InstrLvlAbs::find_instr(const Symbol& name) const { auto pos = instrs_.find(name); return (pos == instrs_.end()) ? NULL : pos->second; } const InstrLvlAbsPtr InstrLvlAbs::find_child(const Symbol& name) const { auto pos = childs_.find(name); return (pos == childs_.end()) ? NULL : pos->second; } void InstrLvlAbs::AddInput(const ExprPtr input_var) { // sanity check ILA_NOT_NULL(input_var); ILA_ASSERT(input_var->is_var()) << "Register non-var to Inputs."; // should be the first auto name = input_var->name(); auto posi = inputs_.find(name); auto poss = states_.find(name); ILA_ASSERT(posi == inputs_.end() && poss == states_.end()) << "Input variable " << input_var << " has been declared."; // register to the simplifier auto var = Unify(input_var); // register to Inputs inputs_.push_back(name, var); } void InstrLvlAbs::AddState(const ExprPtr state_var) { // sanity check ILA_NOT_NULL(state_var); ILA_ASSERT(state_var->is_var()) << "Register non-var to States."; // should be the first auto name = state_var->name(); auto poss = states_.find(name); auto posi = inputs_.find(name); ILA_ASSERT(poss == states_.end() && posi == inputs_.end()) << "State variable " << state_var << " has been declared."; // register to the simplifier auto var = Unify(state_var); // register to States states_.push_back(name, var); } void InstrLvlAbs::AddInit(const ExprPtr cntr_expr) { // sanity check ILA_NOT_NULL(cntr_expr); ILA_ASSERT(cntr_expr->is_bool()) << "Initial condition must be Boolean."; // simplify auto cntr = Unify(cntr_expr); // register to Initial conditions inits_.push_back(cntr); } void InstrLvlAbs::SetFetch(const ExprPtr fetch_expr) { // sanity check ILA_NOT_NULL(fetch_expr); ILA_ASSERT(fetch_expr->is_bv()) << "Fetch function must be bit-vector."; // should be the first ILA_ASSERT(!fetch_) << "Fetch function has been assigned."; // simplify auto fetch = Unify(fetch_expr); // set as fetch function fetch_ = fetch; } void InstrLvlAbs::SetValid(const ExprPtr valid_expr) { // sanity check ILA_NOT_NULL(valid_expr); ILA_ASSERT(valid_expr->is_bool()) << "Valid function must be Boolean."; // should be the first ILA_ASSERT(!valid_) << "Valid function has been assigned."; // simplify auto valid = Unify(valid_expr); // set as valid function valid_ = valid; } void InstrLvlAbs::AddInstr(const InstrPtr instr) { ILA_NOT_NULL(instr); // register the instruction and idx auto name = instr->name(); instrs_.push_back(name, instr); } void InstrLvlAbs::AddChild(const InstrLvlAbsPtr child) { ILA_NOT_NULL(child); /// register the child-ILA and idx auto name = child->name(); childs_.push_back(name, child); } const ExprPtr InstrLvlAbs::NewBoolInput(const std::string& name) { ExprPtr bool_input = ExprFuse::NewBoolVar(name); // set host bool_input->set_host(shared_from_this()); // register AddInput(bool_input); return bool_input; } const ExprPtr InstrLvlAbs::NewBvInput(const std::string& name, const int& bit_width) { ExprPtr bv_input = ExprFuse::NewBvVar(name, bit_width); // set host bv_input->set_host(shared_from_this()); // register AddInput(bv_input); return bv_input; } const ExprPtr InstrLvlAbs::NewMemInput(const std::string& name, const int& addr_width, const int& data_width) { ExprPtr mem_input = ExprFuse::NewMemVar(name, addr_width, data_width); // set host mem_input->set_host(shared_from_this()); // register AddInput(mem_input); return mem_input; } const ExprPtr InstrLvlAbs::NewBoolState(const std::string& name) { ExprPtr bool_state = ExprFuse::NewBoolVar(name); // set host bool_state->set_host(shared_from_this()); // register AddState(bool_state); return bool_state; } const ExprPtr InstrLvlAbs::NewBvState(const std::string& name, const int& bit_width) { ExprPtr bv_state = ExprFuse::NewBvVar(name, bit_width); // set host bv_state->set_host(shared_from_this()); // register AddState(bv_state); return bv_state; } const ExprPtr InstrLvlAbs::NewMemState(const std::string& name, const int& addr_width, const int& data_width) { ExprPtr mem_state = ExprFuse::NewMemVar(name, addr_width, data_width); // set host mem_state->set_host(shared_from_this()); // register AddState(mem_state); return mem_state; } const ExprPtr InstrLvlAbs::NewBoolFreeVar(const std::string& name) { // create new var ExprPtr bool_var = ExprFuse::NewBoolVar(name); // set host bool_var->set_host(shared_from_this()); return bool_var; } const ExprPtr InstrLvlAbs::NewBvFreeVar(const std::string& name, const int& bit_width) { // create new var ExprPtr bv_var = ExprFuse::NewBvVar(name, bit_width); // set host bv_var->set_host(shared_from_this()); return bv_var; } const ExprPtr InstrLvlAbs::NewMemFreeVar(const std::string& name, const int& addr_width, const int& data_width) { // create new var ExprPtr mem_var = ExprFuse::NewMemVar(name, addr_width, data_width); // set host mem_var->set_host(shared_from_this()); return mem_var; } const InstrPtr InstrLvlAbs::NewInstr(const std::string& name) { auto tmp_name = (name == "") ? "I." + std::to_string(instr_num()) : name; InstrPtr instr = Instr::New(tmp_name, shared_from_this()); // register AddInstr(instr); return instr; } const InstrLvlAbsPtr InstrLvlAbs::NewChild(const std::string& name) { InstrLvlAbsPtr child = New(name, shared_from_this()); // inherit states for (size_t i = 0; i != states_.size(); i++) { child->AddState(states_[i]); } // inherit inputs for (size_t i = 0; i != inputs_.size(); i++) { child->AddInput(inputs_[i]); } // register AddChild(child); return child; } bool InstrLvlAbs::Check() const { ILA_WARN << "Check in InstrLvlAbs not implemented."; // TODO // check input // check state // check init // check fetch // check valid // check instr // check child-ILA? // check sequencing return true; } void InstrLvlAbs::MergeChild() { ILA_WARN << "MergeChild in InstrLvlAbs not implemented."; // TODO // merge shared states // merge simplifier } void InstrLvlAbs::SortInstr() { ILA_WARN << "SortInstr in InstrLvlAbs not implemented."; // TODO // check this is a micro-ILA and has sequencing // sort instructions based on the sequencing } void InstrLvlAbs::AddSeqTran(const InstrPtr src, const InstrPtr dst, const ExprPtr cnd) { // XXX src, dst should already registered. auto cnd_simplified = Unify(cnd); instr_seq_.AddTran(src, dst, cnd_simplified); } std::string InstrLvlAbs::GetRootName() const { if (parent()) { return parent()->GetRootName() + "." + name().str(); } else { return name().str(); } } std::ostream& InstrLvlAbs::Print(std::ostream& out) const { out << "ILA." << name(); return out; } std::ostream& operator<<(std::ostream& out, InstrLvlAbs& ila) { return ila.Print(out); } std::ostream& operator<<(std::ostream& out, InstrLvlAbsPtr ila) { return ila->Print(out); } std::ostream& operator<<(std::ostream& out, InstrLvlAbsCnstPtr ila) { return ila->Print(out); } ExprPtr InstrLvlAbs::Unify(const ExprPtr e) { return kUnifyAst ? expr_mngr_->GetRep(e) : e; } void InstrLvlAbs::InitObject() { // local inputs_.clear(); states_.clear(); inits_.clear(); instrs_.clear(); childs_.clear(); instr_seq_.clear(); // shared if (parent_) { expr_mngr_ = parent_->expr_mngr(); } else { expr_mngr_ = kUnifyAst ? ExprMngr::New() : NULL; } } } // namespace ilang
28.0059
78
0.668001
[ "object", "vector" ]
b63664122a4cb8224a14c0fbcb37f85da31eb385
902
hpp
C++
libs/core/render/include/bksge/core/render/vulkan/detail/logic_operation.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/core/render/include/bksge/core/render/vulkan/detail/logic_operation.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/core/render/include/bksge/core/render/vulkan/detail/logic_operation.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file logic_operation.hpp * * @brief LogicOperation クラスの定義 * * @author myoukaku */ #ifndef BKSGE_CORE_RENDER_VULKAN_DETAIL_LOGIC_OPERATION_HPP #define BKSGE_CORE_RENDER_VULKAN_DETAIL_LOGIC_OPERATION_HPP #include <bksge/core/render/fwd/logic_operation_fwd.hpp> #include <bksge/core/render/vulkan/detail/vulkan.hpp> namespace bksge { namespace render { namespace vulkan { /** * @brief */ class LogicOperation { public: explicit LogicOperation(bksge::LogicOperation logic_operation); operator ::VkLogicOp() const; private: ::VkLogicOp m_logic_operation; }; } // namespace vulkan } // namespace render } // namespace bksge #include <bksge/fnd/config.hpp> #if defined(BKSGE_HEADER_ONLY) #include <bksge/core/render/vulkan/detail/inl/logic_operation_inl.hpp> #endif #endif // BKSGE_CORE_RENDER_VULKAN_DETAIL_LOGIC_OPERATION_HPP
18.04
71
0.736142
[ "render" ]
b63fa4d4bf598db932ad745a7bd5157e0e678292
5,813
cc
C++
chrome/browser/ash/guest_os/guest_os_mime_types_service.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/ash/guest_os/guest_os_mime_types_service.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/ash/guest_os/guest_os_mime_types_service.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/guest_os/guest_os_mime_types_service.h" #include <map> #include <string> #include <vector> #include "base/logging.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "chrome/browser/ash/guest_os/guest_os_pref_names.h" #include "chrome/browser/profiles/profile.h" #include "chromeos/dbus/vm_applications/apps.pb.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" using vm_tools::apps::App; namespace guest_os { namespace { constexpr char kMimeTypeKey[] = "mime_type"; } // namespace GuestOsMimeTypesService::GuestOsMimeTypesService(Profile* profile) : prefs_(profile->GetPrefs()) {} GuestOsMimeTypesService::~GuestOsMimeTypesService() = default; // static // TODO(crbug.com/1015353): Can be removed after M99. void GuestOsMimeTypesService::MigrateVerboseMimeTypePrefs( PrefService* pref_service) { DictionaryPrefUpdate update(pref_service, prefs::kGuestOsMimeTypes); base::DictionaryValue* mime_types = update.Get(); std::map<std::string, std::map<std::string, std::map<std::string, std::string>>> migrated; std::vector<std::string> to_remove; for (const auto item : mime_types->DictItems()) { std::vector<std::string> parts = base::SplitString( item.first, "/", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY); if (parts.size() == 1) { // Already migrated. continue; } // Migrate: "termina/penguin/txt": { "mime_type": "text/plain" } to: // "termina": { "penguin": { "txt": "text/plain" } } to_remove.push_back(item.first); std::string* mime_type; if (parts.size() == 3 && item.second.is_dict() && (mime_type = item.second.FindStringKey(kMimeTypeKey))) { migrated[parts[0]][parts[1]][parts[2]] = *mime_type; } else { LOG(ERROR) << "Deleting unexpected crostini.mime_types key " << item.first << "=" << item.second; } } // Delete old values. for (const std::string& s : to_remove) { mime_types->RemoveKey(s); } auto get_or_create = [](base::Value* v, const std::string& k) { base::Value* result = v->FindDictKey(k); if (!result) { result = v->SetKey(k, base::Value(base::Value::Type::DICTIONARY)); } return result; }; // Add migrated values. for (const auto& vm_item : migrated) { base::Value* vm = get_or_create(mime_types, vm_item.first); for (const auto& container_item : vm_item.second) { base::Value* container = get_or_create(vm, container_item.first); for (const auto& ext : container_item.second) { container->SetStringKey(ext.first, ext.second); } } } } std::string GuestOsMimeTypesService::GetMimeType( const base::FilePath& file_path, const std::string& vm_name, const std::string& container_name) const { const base::Value* vm = prefs_->GetDictionary(prefs::kGuestOsMimeTypes)->FindDictKey(vm_name); if (vm) { const base::Value* container = vm->FindDictKey(container_name); if (container) { // Try Extension() which may be a double like ".tar.gz". std::string extension = file_path.Extension(); // Remove leading dot. extension.erase(0, 1); const std::string* result = container->FindStringKey(extension); if (!result) { // Try lowercase. result = container->FindStringKey(base::ToLowerASCII(extension)); } // If this was a double extension, then try FinalExtension(). if (!result && extension.find('.') != std::string::npos) { extension = file_path.FinalExtension(); extension.erase(0, 1); result = container->FindStringKey(extension); if (!result) { // Try lowercase. result = container->FindStringKey(base::ToLowerASCII(extension)); } } if (result) { return *result; } } } return ""; } void GuestOsMimeTypesService::ClearMimeTypes( const std::string& vm_name, const std::string& container_name) { VLOG(1) << "ClearMimeTypes(" << vm_name << ", " << container_name << ")"; DictionaryPrefUpdate update(prefs_, prefs::kGuestOsMimeTypes); base::DictionaryValue* mime_types = update.Get(); base::Value* vm = mime_types->FindDictKey(vm_name); if (vm) { vm->RemoveKey(container_name); if (container_name.empty() || vm->DictEmpty()) { mime_types->RemoveKey(vm_name); } } } void GuestOsMimeTypesService::UpdateMimeTypes( const vm_tools::apps::MimeTypes& mime_type_mappings) { if (mime_type_mappings.vm_name().empty()) { LOG(WARNING) << "Received MIME type list with missing VM name"; return; } if (mime_type_mappings.container_name().empty()) { LOG(WARNING) << "Received MIME type list with missing container name"; return; } base::Value exts(base::Value::Type::DICTIONARY); for (const auto& mapping : mime_type_mappings.mime_type_mappings()) { exts.SetStringKey(mapping.first, mapping.second); } VLOG(1) << "UpdateMimeTypes(" << mime_type_mappings.vm_name() << ", " << mime_type_mappings.container_name() << ")=" << exts; DictionaryPrefUpdate update(prefs_, prefs::kGuestOsMimeTypes); base::DictionaryValue* mime_types = update.Get(); base::Value* vm = mime_types->FindDictKey(mime_type_mappings.vm_name()); if (!vm) { vm = mime_types->SetKey(mime_type_mappings.vm_name(), base::Value(base::Value::Type::DICTIONARY)); } vm->SetKey(mime_type_mappings.container_name(), std::move(exts)); } } // namespace guest_os
33.796512
80
0.666093
[ "vector" ]
b644ad6a9d445aa41dc294ae3d68660148b1e106
1,000
hpp
C++
include/Mirage/Image/ImageParser.hpp
PlathC/ImPro
f391a49d2e381df53b22002fc57b9f13935cd910
[ "MIT" ]
3
2019-07-29T20:29:02.000Z
2020-04-15T13:47:36.000Z
include/Mirage/Image/ImageParser.hpp
PlathC/ImPro
f391a49d2e381df53b22002fc57b9f13935cd910
[ "MIT" ]
1
2021-01-20T14:09:04.000Z
2021-01-20T16:52:09.000Z
include/Mirage/Image/ImageParser.hpp
PlathC/ImPro
f391a49d2e381df53b22002fc57b9f13935cd910
[ "MIT" ]
null
null
null
// // Created by Cyprien Plateau--Holleville on 20/06/2019. // #ifndef MIRAGE_IMAGEPARSER_HPP #define MIRAGE_IMAGEPARSER_HPP #include <filesystem> #include <fstream> #include <iostream> #include <memory> #include <regex> #include <sstream> #include <string> #include <unordered_map> #include <utility> #include <vector> namespace fs = std::filesystem; #include "Mirage/Core/Vec.hpp" #include "Matrix.hpp" namespace mrg { namespace ImageParser { enum class ImageFile { PNG, JPEG }; const std::unordered_map<ImageFile, std::vector<std::string>> formats = { {ImageFile::PNG, {"png"}}, {ImageFile::JPEG, {"jpeg", "jpg"}} }; template<typename Type> Matrix<Type> FromFile(const std::string& fileName); template<typename Type> void ToFile(const Matrix<Type>& mat, const std::string& fileName); } } #include "ImageParser.inl" #endif //MIRAGE_IMAGEPARSER_HPP
20
81
0.632
[ "vector" ]
b644cfbdbd401827243325803f60668f82361fab
3,950
cpp
C++
src/Game.cpp
fklemme/DungeonsAndDoenekes
ce57b3f445ba3cf3e6f82922abd08dd58894c33c
[ "MIT" ]
null
null
null
src/Game.cpp
fklemme/DungeonsAndDoenekes
ce57b3f445ba3cf3e6f82922abd08dd58894c33c
[ "MIT" ]
null
null
null
src/Game.cpp
fklemme/DungeonsAndDoenekes
ce57b3f445ba3cf3e6f82922abd08dd58894c33c
[ "MIT" ]
1
2020-06-24T16:08:05.000Z
2020-06-24T16:08:05.000Z
#include "Game.hpp" #include <algorithm> #include <iostream> #include <stdexcept> #include "Enemy.hpp" #include "Layers/Battle.hpp" #include "utility/algorithm.hpp" #include <imgui.h> #include <imgui-SFML.h> #include <SFML/System/Clock.hpp> Game::Game() : m_main_window(sf::VideoMode(800, 600), "Dungeons And Doenekes") { // Init ImGui ImGui::SFML::Init(m_main_window); // Load font const std::string font_path = "res/dejavu-fonts/DejaVuSans.ttf"; if (!m_font.loadFromFile(font_path)) throw std::runtime_error("Could not load " + font_path); // Create player m_player = std::make_unique<Player>("Player", 5, 100); } Game::~Game() {ImGui::SFML::Shutdown();} void Game::run() { // TODO: Testing! Enemy enemy1("Enemy 1", 5, 25); emplace_layer<Battle>(m_player.get(), &enemy1); // Stack of layers must not be changed while iterating through it. // Thus we iterate over a copy holding references. auto layer_view = std::vector<observer_ptr<Layer>>(m_layers.begin(), m_layers.end()); auto layer_draw_begin = layer_view.begin(); sf::Clock frame_timer; while (m_main_window.isOpen()) { // Handle events, or forward to layers sf::Event event; while (m_main_window.pollEvent(event)) { ImGui::SFML::ProcessEvent(event); if (event.type == sf::Event::Closed) { m_main_window.close(); // TODO: Move to main menu } else { // Dispatch event, top to bottom, until some layer returns true. for (auto it = layer_view.rbegin(); it != layer_view.rend(); ++it) { if ((*it)->handle_event(event)) break; } } } // Update layer stack and view if (m_layers_update) { // Remove all layers marked for removal auto marked_for_removal = [](observer_ptr<Layer> ptr) { return ptr->m_marked_for_removal; }; m_layers.erase(std::remove_if(m_layers.begin(), m_layers.end(), marked_for_removal), m_layers.end()); // If layer stack is empty, close application if (m_layers.empty()) { m_main_window.close(); return; } // Get a new layer view and update iterator to first drawing layer layer_view = std::vector<observer_ptr<Layer>>(m_layers.begin(), m_layers.end()); auto bottom_layer_to_draw = [](observer_ptr<Layer> ptr) { return !ptr->m_render_underlying_layers; }; layer_draw_begin = find_last_if(layer_view.begin(), layer_view.end(), bottom_layer_to_draw); // TOOD: Could be removed in the future: layer_draw_begin = layer_draw_begin == layer_view.end() ? layer_view.begin() : layer_draw_begin; m_layers_update = false; // reset flag, so checks are not done on every frame std::cout << "Layers on stack: " << layer_view.size() << "\n"; // DEBUG! std::cout << "Layers to draw: " << std::distance(layer_draw_begin, layer_view.end()) << "\n"; // DEBUG! } // Draw stuff to the window auto elapsed_time = frame_timer.restart(); ImGui::SFML::Update(m_main_window, elapsed_time); m_main_window.clear(); // Debugging layer stack ImGui::Begin("Layer Stack"); for (auto layer : layer_view) ImGui::Text("Type name: %s", typeid(*layer).name()); ImGui::End(); // Dispatch rendering, bottom to top for (auto it = layer_draw_begin; it != layer_view.end(); ++it) (*it)->render(m_main_window, elapsed_time); ImGui::SFML::Render(m_main_window); m_main_window.display(); // swap buffers } } void Game::push_layer(std::unique_ptr<Layer> layer) { m_layers.push_back(std::move(layer)); m_layers.back()->m_game.reset(this); // set back reference update_layers(); }
38.349515
116
0.607089
[ "render", "vector" ]
b65167011372e609f82e0b9aaf44f35554a88299
2,855
cpp
C++
16rllight/game.cpp
lightbits/akari
63c411ca3b269a2844154834b01c8114a39c6a33
[ "MIT" ]
11
2015-02-13T13:18:01.000Z
2017-10-14T02:27:35.000Z
16rllight/game.cpp
lightbits/akari
63c411ca3b269a2844154834b01c8114a39c6a33
[ "MIT" ]
null
null
null
16rllight/game.cpp
lightbits/akari
63c411ca3b269a2844154834b01c8114a39c6a33
[ "MIT" ]
2
2019-05-18T03:14:08.000Z
2019-12-10T15:03:41.000Z
#include "game.h" #define GLSL(src) "#version 150 core\n" #src static const char *GEOMETRY_VS = GLSL( in vec2 position; out vec2 texel; void main() { texel = 0.5 * position + vec2(0.5); gl_Position = vec4(position, 0.0, 1.0); } ); static const char *GEOMETRY_FS = GLSL( in vec2 texel; uniform sampler2D tex; out vec4 outColor; void main() { outColor = texture(tex, texel); } ); static const char *LIGHT_VS = GLSL( in vec2 position; uniform mat4 translation; uniform mat4 scale; uniform float aspect; out vec2 texel; void main() { texel = 0.5 * position + vec2(0.5); gl_Position = translation * scale * vec4(vec2(1.0, aspect) * position, 0.0, 1.0); } ); static const char *LIGHT_FS = GLSL( in vec2 texel; out vec4 outColor; void main() { vec2 dt = 2.0 * texel - vec2(1.0); float r2 = dot(dt, dt); if (r2 > 1.0) discard; outColor = vec4(1.0); } ); Shader shader_geometry, shader_light; Mesh quad; uint tex_fill, tex_line; vec2 resolution; bool load_game(int width, int height) { if (!shader_geometry.load_from_src(GEOMETRY_VS, GEOMETRY_FS) || !shader_light.load_from_src(LIGHT_VS, LIGHT_FS) || !load_texture_from_file(tex_fill, "./test_fill.png") || !load_texture_from_file(tex_line, "./test_line.png")) return false; resolution = vec2(width, height); return true; } void free_game() { } void init_game() { quad = Primitive::quad(); } void update_game(float dt) { } void stencil_light(float x, float y, float outer_radius, float inner_radius) { uniform("translation", translate(x, y, 0.0f)); glStencilFunc(GL_NEVER, 1, 0xFF); glStencilMask(0xFF); glStencilOp(GL_REPLACE, GL_KEEP, GL_KEEP); uniform("scale", scale(outer_radius)); quad.draw(); glStencilFunc(GL_NEVER, 2, 0xFF); uniform("scale", scale(inner_radius)); quad.draw(); } void render_game(float dt) { vec2 p = 2.0f * vec2(get_mouse_pos()) / resolution - vec2(1.0f); glEnable(GL_STENCIL_TEST); glStencilMask(0xFF); glClear(GL_STENCIL_BUFFER_BIT); clearc(0x4a2a2a00); use_shader(shader_light); blend_mode(true, GL_ONE, GL_ONE, GL_FUNC_ADD); uniform("aspect", resolution.x / resolution.y); stencil_light(p.x, -p.y, 0.5f, 0.25f); use_shader(shader_geometry); uniform("tex", 0); blend_mode(true, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glStencilMask(0x00); glStencilFunc(GL_EQUAL, 1, 0xFF); glBindTexture(GL_TEXTURE_2D, tex_line); quad.draw(); glStencilFunc(GL_EQUAL, 2, 0xFF); glBindTexture(GL_TEXTURE_2D, tex_fill); quad.draw(); glDisable(GL_STENCIL_TEST); } void on_key_up(uint16 mod, SDL_Keycode key) { } void on_key_down(uint16 mod, SDL_Keycode key) { } void on_mouse_moved(int x, int y, int dx, int dy) { } void on_mouse_dragged(int button, int x, int y, int dx, int dy) { } void on_mouse_pressed(int button, int x, int y) { } void on_mouse_released(int button, int x, int y) { }
20.992647
83
0.700525
[ "mesh" ]
b656b8970b0a27c5ac374eb07683eb6e7bc0543a
6,547
cpp
C++
src/data_science/kernel_smooth.cpp
arotem3/numerics
ba208d9fc0ccb9471cfec9927a21622eb3535f54
[ "Apache-2.0" ]
18
2019-04-18T17:34:49.000Z
2021-11-15T07:57:29.000Z
src/data_science/kernel_smooth.cpp
arotem3/numerics
ba208d9fc0ccb9471cfec9927a21622eb3535f54
[ "Apache-2.0" ]
null
null
null
src/data_science/kernel_smooth.cpp
arotem3/numerics
ba208d9fc0ccb9471cfec9927a21622eb3535f54
[ "Apache-2.0" ]
4
2019-12-02T04:04:21.000Z
2022-02-17T08:23:09.000Z
#include <numerics.hpp> void numerics::KernelSmooth::fit(const arma::mat& x, const arma::vec& y) { _check_xy(x,y); _dim = x.n_cols; if (x.n_cols > 1) { throw std::logic_error("KernelSmooth does not support 2+ dimensional data yet."); } else { if (_binning) _bins.fit(x, y); else { arma::uvec I = arma::sort_index(x); _X = x(I); _y = y(I); } double stddev = arma::stddev(x.as_col()); if (_bdw <= 0) _bdw = bw::grid_mse(x, y, _kern, stddev, 40, _binning); } } arma::vec numerics::KernelSmooth::predict(const arma::mat& x) const { _check_x(x); if (_bdw <= 0) { throw std::runtime_error("KernelSmooth object not fitted."); } if (x.n_cols > 1) { throw std::logic_error("KernelSmooth does not support 2+ dimensional data yet."); } else { arma::vec yhat(x.n_elem); for (u_int i=0; i < x.n_elem; ++i) { arma::vec r; if (_binning) r = arma::abs(_bins.bins - x(i))/_bdw; else r = arma::abs(_X - x(i))/_bdw; arma::vec K = bw::eval_kernel(r, _kern); if (_binning) yhat(i) = arma::dot(_bins.counts, K) / arma::sum(K); else yhat(i) = arma::dot(y, K) / arma::sum(K); } return yhat; } } double numerics::KernelSmooth::score(const arma::mat& x, const arma::vec& y) const { _check_xy(x,y); return r2_score(y, predict(x)); } // /* kernel_smooth(k, estim, binning) : initialize kernel smoothing object by specifying bandwidth estimation method // * --- k : choice of kernel. options include : RBF, square, triangle, parabolic // * --- estim : method of selecting bandwidth. // * --- binning : whether to bin data or not. */ // numerics::kernel_smooth::kernel_smooth(kernels k, bool binning) : data_x(x), data_y(y), bandwidth(bdw) { // kern = k; // this->binning = binning; // bdw = 0; // } // /* kernel_smooth(h, k, binning) : initialize kernel smoothing object by specifying bandwidth. // * --- bdw : kernel bandwidth. default bdw=0.0; when fitting the default value tells the object to choose a bandwidth by k-fold cross validation. // * --- k : choice of kernel. options include : RBF, square, triangle, parabolic // * --- binning : whether to bin data or not */ // numerics::kernel_smooth::kernel_smooth(double h, kernels k, bool binning) : data_x(x), data_y(y), bandwidth(bdw) { // if (h <= 0) { // std::cerr << "kernel_smooth::kernel_smooth() error: invalid choice for bandwidth (must be > 0 but bdw recieved = " << h << ").\n"; // bdw = 0; // } else { // bdw = h; // } // kern = k; // this->binning = binning; // } // /* kernel_smooth(in) : initialize kernel smoothing object from saved instance in file */ // numerics::kernel_smooth::kernel_smooth(const std::string& fname) : data_x(x), data_y(y), bandwidth(bdw) { // load(fname); // } // /* save(out) : save kernel smoothing object to output stream. */ // void numerics::kernel_smooth::save(const std::string& fname) { // std::ofstream out(fname); // out << n << " " << (int)kern << " " << bdw << " " << std::endl; // x.t().raw_print(out); // y.t().raw_print(out); // } // /* load(in) : load kernel smoothing object from input stream. */ // void numerics::kernel_smooth::load(const std::string& fname) { // std::ifstream in(fname); // int k; // in >> n >> k >> bdw; // if (k==0) kern = kernels::gaussian; // else if (k==1) kern = kernels::square; // else if (k==2) kern = kernels::triangle; // else kern = kernels::parabolic; // x = arma::zeros(n); // y = arma::zeros(n); // for (uint i=0; i < n; ++i) in >> x(i); // for (uint i=0; i < n; ++i) in >> y(i); // } // /* predict(t) : predict a single value of the function // * --- t : input to predict response of. */ // double numerics::kernel_smooth::predict(double t) { // arma::vec tt = {t}; // return predict(tt)(0); // } // /* predict(t) : predict values of the function // * --- t : input to predict response of. */ // arma::vec numerics::kernel_smooth::predict(const arma::vec& t) { // if (bdw <= 0) { // std::cerr << "kernel_smooth::predict() error: bandwidth must be strictly greater than 0" << std::endl; // return 0; // } // arma::vec yhat(t.n_elem); // for (int i=0; i < t.n_elem; ++i) { // arma::vec r; // if (binning) r = (bins.bins - t(i))/bdw; // else r = arma::abs(x - t(i))/bdw; // arma::vec K = bw::eval_kernel(r, kern); // if (binning) yhat(i) = arma::dot(bins.counts, K) / arma::sum(K); // else yhat(i) = arma::dot(y, K) / arma::sum(K); // } // return yhat; // } // /* fit(X, Y) : supply x and y values to fit object to. // * --- X : data vector of independent variable // * --- Y : data vector of dependent variable // * returns reference to 'this', so function object can be continuously called. */ // numerics::kernel_smooth& numerics::kernel_smooth::fit(const arma::vec& X, const arma::vec& Y) { // if (X.n_elem != Y.n_elem) { // std::cerr << "kernel_smooth::fit() error: input vectors must have the same length." << std::endl // << "x.n_elem = " << X.n_elem << " != " << Y.n_elem << " = y.n_elem" << std::endl; // return *this; // } // if (X.n_elem <= 2) { // std::cerr << "kernel_smooth::fit() error: input vectors must have length > 2 (input vector length = " << x.n_elem << ").\n"; // return *this; // } // arma::uvec I = arma::sort_index(X); // x = X(I); // double stddev = arma::stddev(x); // y = Y(I); // n = x.n_elem; // if (binning) bins.to_bins(x,y); // if (bdw <= 0) bdw = smooth_grid_mse(x, y, kern, stddev, 40, binning); // return *this; // } // /* fit_predict(X, Y) : fit object to data and predict on the same data. // * --- X : data vector of independent variable // * --- Y : data vector of dependent variable // * note: this is equivalent to calling this.fit(X,Y).predict(X) */ // arma::vec numerics::kernel_smooth::fit_predict(const arma::vec& X, const arma::vec& Y) { // return fit(X,Y).predict(X); // } // /* operator() : same as predict(double t) */ // double numerics::kernel_smooth::operator()(double t) { // return predict(t); // } // /* operator() : same as predict(const arma::vec& t) */ // arma::vec numerics::kernel_smooth::operator()(const arma::vec& t) { // return predict(t); // }
37.411429
148
0.566977
[ "object", "vector" ]
b66afb2abe6a09b8af3c17ae69e2c6357e094d89
3,296
cpp
C++
Graph/Tree/BST/Fix a BT that is only one swap away from becoming a BST.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
8
2021-02-13T17:07:27.000Z
2021-08-20T08:20:40.000Z
Graph/Tree/BST/Fix a BT that is only one swap away from becoming a BST.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
null
null
null
Graph/Tree/BST/Fix a BT that is only one swap away from becoming a BST.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
5
2021-02-17T18:12:20.000Z
2021-10-10T17:49:34.000Z
// Similar Problem: https://www.interviewbit.com/problems/recover-binary-search-tree/ // Ref: https://www.youtube.com/watch?v=HsSSUSckMns&list=PL7JyMDSI2BfZugpAjdWc8ES_mYMz2F9Qo&index=7 // https://www.techiedelight.com/fix-binary-tree-one-swap-bst/ /********************************************************************************************************/ #include<bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define pb push_back #define mp make_pair #define F first #define S second #define PI 3.1415926535897932384626 #define deb(x) cout << #x << "=" << x << endl #define deb2(x, y) cout << #x << "=" << x << ", " << #y << "=" << y << endl typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<ull> vull; typedef vector<pii> vpii; typedef vector<pll> vpll; typedef vector<vi> vvi; typedef vector<vll> vvll; typedef vector<vull> vvull; mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count()); int rng(int lim) { uniform_int_distribution<int> uid(0,lim-1); return uid(rang); } const int INF = 0x3f3f3f3f; const int mod = 1e9+7; class TreeNode { public: int val; TreeNode *left; TreeNode *right; TreeNode(): val(0), left(NULL), right(NULL) {} TreeNode(int data): val(data), left(NULL), right(NULL) {} TreeNode(int data, TreeNode *left, TreeNode *right): val(data), left(left), right(right) {} }; // remember to pass pointer x, y and prev by reference void inorder(TreeNode* root, TreeNode* &x, TreeNode* &y, TreeNode* &prev) { // base case if(root == NULL) return; // recur for the left subtree inorder(root->left, x, y, prev); // if the current node is less than the previous node if(prev->val > root->val) { // if this is the first occurrence, update x if(x == NULL) x = prev; // if second occurrence update y if(x) y = root; } // update the previous node and recur for the right subtree prev = root; inorder(root->right, x, y, prev); } // Fix given binary tree that is only one swap away from becoming a BST void correctBST(TreeNode *root) { // x and y stores node to be swapped TreeNode *x = NULL, *y = NULL; // stores previously processed node in the inorder traversal // initialize it by -INFINITY TreeNode *prev = new TreeNode(INT_MIN); inorder(root, x, y, prev); // swap the nodes if(x and y) swap(x->val, y->val); } void solve() { TreeNode* root = new TreeNode(2); root->left = new TreeNode(1); root->right = new TreeNode(15); root->right->left = new TreeNode(7); root->right->right = new TreeNode(26); root->right->left->left = new TreeNode(5); root->right->left->right = new TreeNode(10); root->right->left->right->left = new TreeNode(8); root->right->left->right->right = new TreeNode(9); correctBST(root); } int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); srand(chrono::high_resolution_clock::now().time_since_epoch().count()); // #ifndef ONLINE_JUDGE // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); // #endif int t = 1; // int test = 1; // cin >> t; while(t--) { // cout << "Case #" << test++ << ": "; solve(); } return 0; }
27.932203
106
0.635012
[ "vector" ]
b66e62440ddcce3a432da0b0d4cb891c88db1157
3,114
cpp
C++
QuantExt/qle/termstructures/blackvariancecurve3.cpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
335
2016-10-07T16:31:10.000Z
2022-03-02T07:12:03.000Z
QuantExt/qle/termstructures/blackvariancecurve3.cpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
59
2016-10-31T04:20:24.000Z
2022-01-03T16:39:57.000Z
QuantExt/qle/termstructures/blackvariancecurve3.cpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
180
2016-10-08T14:23:50.000Z
2022-03-28T10:43:05.000Z
/* Copyright (C) 2016 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <ql/math/interpolations/linearinterpolation.hpp> #include <qle/termstructures/blackvariancecurve3.hpp> namespace QuantExt { BlackVarianceCurve3::BlackVarianceCurve3(Natural settlementDays, const Calendar& cal, BusinessDayConvention bdc, const DayCounter& dc, const std::vector<Time>& times, const std::vector<Handle<Quote> >& blackVolCurve, bool requireMonotoneVariance) : BlackVarianceTermStructure(settlementDays, cal, bdc, dc), times_(times), quotes_(blackVolCurve), requireMonotoneVariance_(requireMonotoneVariance) { QL_REQUIRE(times.size() == blackVolCurve.size(), "mismatch between date vector and black vol vector"); // cannot have dates[0]==referenceDate, since the // value of the vol at dates[0] would be lost // (variance at referenceDate must be zero) QL_REQUIRE(times[0] > 0, "cannot have times[0] <= 0"); // Now insert 0 at the start of times_ times_.insert(times_.begin(), 0); variances_ = std::vector<Real>(times_.size()); variances_[0] = 0.0; for (Size j = 1; j < times_.size(); j++) { QL_REQUIRE(times_[j] > times_[j - 1], "times must be sorted unique!"); registerWith(quotes_[j - 1]); } varianceCurve_ = Linear().interpolate(times_.begin(), times_.end(), variances_.begin()); } void BlackVarianceCurve3::update() { TermStructure::update(); // calls notifyObservers LazyObject::update(); // as does this } void BlackVarianceCurve3::performCalculations() const { for (Size j = 1; j <= quotes_.size(); j++) { variances_[j] = times_[j] * quotes_[j - 1]->value() * quotes_[j - 1]->value(); if (requireMonotoneVariance_) { QL_REQUIRE(variances_[j] >= variances_[j - 1], "variance must be non-decreasing at j:" << j << " got var[j]:" << variances_[j] << " and var[j-1]:" << variances_[j - 1]); } } varianceCurve_.update(); } Real BlackVarianceCurve3::blackVarianceImpl(Time t, Real) const { calculate(); if (t <= times_.back()) { return varianceCurve_(t, true); } else { // extrapolate with flat vol return varianceCurve_(times_.back(), true) * t / times_.back(); } } } // namespace QuantExt
40.973684
120
0.657354
[ "vector", "model" ]
b67da578bd039b4b2467894a43069e53bba18944
4,944
hpp
C++
src/perception/tracking/include/tracking/track_creator.hpp
ruvus/auto
25ae62d6e575cae40212356eed43ec3e76e9a13e
[ "Apache-2.0" ]
1
2022-02-24T07:36:59.000Z
2022-02-24T07:36:59.000Z
src/perception/tracking/include/tracking/track_creator.hpp
ruvus/auto
25ae62d6e575cae40212356eed43ec3e76e9a13e
[ "Apache-2.0" ]
null
null
null
src/perception/tracking/include/tracking/track_creator.hpp
ruvus/auto
25ae62d6e575cae40212356eed43ec3e76e9a13e
[ "Apache-2.0" ]
1
2021-12-09T15:44:10.000Z
2021-12-09T15:44:10.000Z
// Copyright 2021 Apex.AI, 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. // // Co-developed by Tier IV, Inc. and Apex.AI, Inc. #ifndef TRACKING__TRACK_CREATOR_HPP_ #define TRACKING__TRACK_CREATOR_HPP_ #include <autoware_auto_perception_msgs/msg/classified_roi_array.hpp> #include <autoware_auto_perception_msgs/msg/detected_objects.hpp> #include <common/types.hpp> #include <message_filters/cache.h> #include <tf2/buffer_core.h> #include <tracking/greedy_roi_associator.hpp> #include <tracking/objects_with_associations.hpp> #include <tracking/tracked_object.hpp> #include <tracking/tracker_types.hpp> #include <tracking/visibility_control.hpp> #include <memory> #include <string> #include <unordered_map> #include <utility> #include <vector> namespace autoware { namespace perception { namespace tracking { /// Struct defining configuration parameters for LidarIfVision policy struct TRACKING_PUBLIC VisionPolicyConfig { // Struct defining parameters for vision association GreedyRoiAssociatorConfig associator_cfg; // Maximum allowed difference in the timestamp of the two messages being associated std::chrono::milliseconds max_vision_lidar_timestamp_diff{20}; }; /// Struct to be used as the return value from track creation process struct TRACKING_PUBLIC TrackCreationResult { /// List of newly created tracks std::vector<TrackedObject> tracks; /// List of associations that matches an association to each track Associations associations; /// Timestamps of msgs from each of the ClassifiedROIArray topics used for track creation builtin_interfaces::msg::Time related_rois_stamp; }; // Class implementing LidarOnly track creation policy class TRACKING_PUBLIC LidarOnlyPolicy { public: LidarOnlyPolicy( const common::types::float64_t default_variance, const common::types::float64_t noise_variance, const tf2::BufferCore & tf_buffer); TrackCreationResult create(const ObjectsWithAssociations & objects) const; private: common::types::float64_t m_default_variance; common::types::float64_t m_noise_variance; const tf2::BufferCore & m_tf_buffer; }; /// Class implementing LidarIfVision track creation policy class TRACKING_PUBLIC LidarClusterIfVisionPolicy { public: LidarClusterIfVisionPolicy( const VisionPolicyConfig & cfg, const common::types::float64_t default_variance, const common::types::float64_t noise_variance, const tf2::BufferCore & tf_buffer); TrackCreationResult create(const ObjectsWithAssociations & objects) const; void add_objects( const autoware_auto_perception_msgs::msg::ClassifiedRoiArray & vision_rois, const AssociatorResult & associator_result); private: using VisionCache = message_filters::Cache<autoware_auto_perception_msgs::msg::ClassifiedRoiArray>; void create_using_cache( const ObjectsWithAssociations & objects, const VisionCache & vision_cache, TrackCreationResult & result) const; static constexpr std::uint32_t kVisionCacheSize = 20U; common::types::float64_t m_default_variance; common::types::float64_t m_noise_variance; const tf2::BufferCore & m_tf_buffer; VisionPolicyConfig m_cfg; GreedyRoiAssociator m_associator; std::unordered_map<std::string, VisionCache> m_vision_cache_map; }; /// \brief Class to create new tracks based on a predefined policy and unassociated detections template<class PolicyT> class TRACKING_PUBLIC TrackCreator { public: /// \brief Constructor explicit TrackCreator(std::shared_ptr<PolicyT> policy) : m_policy{policy} {} /// \brief Create new tracks based on the policy and unassociated detections. Call the /// appropriate add_unassigned_* functions before calling this. /// \return vector of newly created TrackedObject objects inline TrackCreationResult create_tracks(const ObjectsWithAssociations & objects) { return m_policy->create(objects); } /// Function to add unassigned detections. This function just passes through the arguments. /// The actual implementation is handled by the individual policy implementation classes. /// Refer to the CreationPolicyBase doc for details template<typename ... Ts> inline auto add_objects(Ts && ... args) { return m_policy->add_objects(std::forward<Ts>(args)...); } private: std::shared_ptr<PolicyT> m_policy{}; }; } // namespace tracking } // namespace perception } // namespace autoware #endif // TRACKING__TRACK_CREATOR_HPP_
32.526316
94
0.777508
[ "vector" ]
b67f18e171fa5dfefa7af93c16a877be527d1bba
1,256
hpp
C++
include/ordered_trie_serialise.hpp
IgorNitto/ordered-trie
a5b35e4ce4899ad20625513b93a57cd94c3aeaf7
[ "MIT" ]
null
null
null
include/ordered_trie_serialise.hpp
IgorNitto/ordered-trie
a5b35e4ce4899ad20625513b93a57cd94c3aeaf7
[ "MIT" ]
null
null
null
include/ordered_trie_serialise.hpp
IgorNitto/ordered-trie
a5b35e4ce4899ad20625513b93a57cd94c3aeaf7
[ "MIT" ]
null
null
null
/** * @file ordered_trie_serialise.hpp * @brief Serialisation scheme * * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. * */ #ifndef ORDERED_TRIE_SERIALISE_HPP #define ORDERED_TRIE_SERIALISE_HPP #include <cstddef> #include <cstdint> #include <vector> namespace ordered_trie { /** * Payload data serialisation/deserialisation API. * This has to be specialised for any user defined * metadata type. */ template<typename T> struct Serialise { /** * Unique version name associated to this serialisation format */ constexpr static char* format_id (); /** * Append serialisation to output */ static inline void serialise (std::vector<std::uint8_t> &output, T &&input); /** * Deserialise object starting at given input address */ static inline auto deserialise (const std::uint8_t *start) -> T; /** * Advance pointer to first byte past end of encoding */ static inline auto skip (const std::uint8_t *start) -> const std::uint8_t*; /** * Expected maximum encoding length of a generic metadata */ static inline auto constexpr estimated_max_size () -> size_t; }; } // namespace ordered_trie { #endif
20.590164
65
0.696656
[ "object", "vector" ]
b684f2f6ed21570f0e1090238053297f7bb025b8
1,665
cc
C++
components/autofill/core/browser/form_structure_process_query_response_fuzzer.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/autofill/core/browser/form_structure_process_query_response_fuzzer.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/autofill/core/browser/form_structure_process_query_response_fuzzer.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdlib.h> #include <iostream> #include "base/strings/utf_string_conversions.h" #include "components/autofill/core/browser/form_structure.h" #include "components/autofill/core/common/form_data.h" #include "components/autofill/core/common/form_field_data.h" #include "testing/libfuzzer/proto/lpm_interface.h" namespace autofill { namespace { using ::base::ASCIIToUTF16; void AddField(const std::string& label, const std::string& name, const std::string& control_type, FormData* form_data) { FormFieldData field; field.label = ASCIIToUTF16(label); field.name = ASCIIToUTF16(name); field.form_control_type = control_type; form_data->fields.push_back(field); } // We run ProcessQueryResponse twice with hardcoded forms vectors. Ideally we // should also generate forms vectors by using fuzzing, but at the moment we use // simplified approach. There is no specific reason to use those two hardcoded // forms vectors, so it can be changed if needed. DEFINE_BINARY_PROTO_FUZZER(const AutofillQueryResponseContents& response) { std::vector<FormStructure*> forms; FormStructure::ProcessQueryResponse(response, forms, nullptr); FormData form_data; AddField("username", "username", "text", &form_data); AddField("password", "password", "password", &form_data); FormStructure form(form_data); forms.push_back(&form); FormStructure::ProcessQueryResponse(response, forms, nullptr); } } // namespace } // namespace autofill
32.647059
80
0.74955
[ "vector" ]
b689983816a829a1d31632d84d593f17a569728d
10,694
cpp
C++
common/storage.cpp
michealbrownm/phantom
a1a41a6f9317c26e621952637c7e331c8dacf79d
[ "Apache-2.0" ]
27
2020-09-24T03:14:13.000Z
2021-11-29T14:00:36.000Z
common/storage.cpp
david2011dzha/phantom
eff76713e03966eb44e20a07806b8d47ec73ad09
[ "Apache-2.0" ]
null
null
null
common/storage.cpp
david2011dzha/phantom
eff76713e03966eb44e20a07806b8d47ec73ad09
[ "Apache-2.0" ]
10
2020-09-24T14:34:30.000Z
2021-02-22T06:50:31.000Z
/* phantom is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. phantom 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 phantom. If not, see <http://www.gnu.org/licenses/>. */ #include <pcrecpp.h> #include <utils/strings.h> #include <utils/logger.h> #include <utils/file.h> #include "storage.h" #include "general.h" #define PHANTOM_ROCKSDB_MAX_OPEN_FILES 5000 namespace phantom { KeyValueDb::KeyValueDb() {} KeyValueDb::~KeyValueDb() {} #ifdef WIN32 LevelDbDriver::LevelDbDriver() { db_ = NULL; } LevelDbDriver::~LevelDbDriver() { if (db_ != NULL) { delete db_; db_ = NULL; } } bool LevelDbDriver::Open(const std::string &db_path, int max_open_files) { leveldb::Options options; if (max_open_files > 0) { options.max_open_files = max_open_files; } options.create_if_missing = true; leveldb::Status status = leveldb::DB::Open(options, db_path, &db_); if (!status.ok()) { utils::MutexGuard guard(mutex_); error_desc_ = status.ToString(); } return status.ok(); } bool LevelDbDriver::Close() { delete db_; db_ = NULL; return true; } int32_t LevelDbDriver::Get(const std::string &key, std::string &value) { assert(db_ != NULL); //retry 10s size_t timers = 0; int32_t ret = -1; while (timers < 10) { leveldb::Status status = db_->Get(leveldb::ReadOptions(), key, &value); if (status.ok()) { ret = 1; break; } else if (status.IsNotFound()) { ret = 0; break; } else { utils::MutexGuard guard(mutex_); error_desc_ = status.ToString(); ret = -1; } timers++; utils::Sleep(100); } return ret; } bool LevelDbDriver::Put(const std::string &key, const std::string &value) { assert(db_ != NULL); leveldb::WriteOptions opt; opt.sync = true; leveldb::Status status = db_->Put(opt, key, value); if (!status.ok()) { utils::MutexGuard guard(mutex_); error_desc_ = status.ToString(); } return status.ok(); } bool LevelDbDriver::Delete(const std::string &key) { assert(db_ != NULL); leveldb::Status status = db_->Delete(leveldb::WriteOptions(), key); if (!status.ok()) { error_desc_ = status.ToString(); } return status.ok(); } bool LevelDbDriver::WriteBatch(WRITE_BATCH &write_batch) { leveldb::WriteOptions opt; opt.sync = true; leveldb::Status status = db_->Write(opt, &write_batch); if (!status.ok()) { utils::MutexGuard guard(mutex_); error_desc_ = status.ToString(); } return status.ok(); } void* LevelDbDriver::NewIterator() { return db_->NewIterator(leveldb::ReadOptions()); } bool LevelDbDriver::GetOptions(Json::Value &options) { return true; } #else RocksDbDriver::RocksDbDriver() { db_ = NULL; } RocksDbDriver::~RocksDbDriver() { if (db_ != NULL) { delete db_; db_ = NULL; } } bool RocksDbDriver::Open(const std::string &db_path, int max_open_files) { rocksdb::Options options; if (max_open_files > 0) { options.max_open_files = max_open_files; } options.create_if_missing = true; rocksdb::Status status = rocksdb::DB::Open(options, db_path, &db_); if (!status.ok()) { utils::MutexGuard guard(mutex_); error_desc_ = status.ToString(); } return status.ok(); } bool RocksDbDriver::Close() { delete db_; db_ = NULL; return true; } int32_t RocksDbDriver::Get(const std::string &key, std::string &value) { assert(db_ != NULL); rocksdb::Status status = db_->Get(rocksdb::ReadOptions(), key, &value); if (status.ok()) { return 1; } else if (status.IsNotFound()) { return 0; } else { utils::MutexGuard guard(mutex_); error_desc_ = status.ToString(); return -1; } } bool RocksDbDriver::Put(const std::string &key, const std::string &value) { assert(db_ != NULL); rocksdb::WriteOptions opt; opt.sync = true; rocksdb::Status status = db_->Put(opt, key, value); if (!status.ok()) { utils::MutexGuard guard(mutex_); error_desc_ = status.ToString(); } return status.ok(); } bool RocksDbDriver::Delete(const std::string &key) { assert(db_ != NULL); rocksdb::WriteOptions opt; opt.sync = true; rocksdb::Status status = db_->Delete(opt, key); if (!status.ok()) { utils::MutexGuard guard(mutex_); error_desc_ = status.ToString(); } return status.ok(); } bool RocksDbDriver::WriteBatch(WRITE_BATCH &write_batch) { rocksdb::WriteOptions opt; opt.sync = true; rocksdb::Status status = db_->Write(opt, &write_batch); if (!status.ok()) { utils::MutexGuard guard(mutex_); error_desc_ = status.ToString(); } return status.ok(); } void* RocksDbDriver::NewIterator() { return db_->NewIterator(rocksdb::ReadOptions()); } bool RocksDbDriver::GetOptions(Json::Value &options) { std::string out; db_->GetProperty("rocksdb.estimate-table-readers-mem", &out); options["rocksdb.estimate-table-readers-mem"] = out; db_->GetProperty("rocksdb.cur-size-all-mem-tables", &out); options["rocksdb.cur-size-all-mem-tables"] = out; db_->GetProperty("rocksdb.stats", &out); options["rocksdb.stats"] = out; return true; } #endif Storage::Storage() { keyvalue_db_ = NULL; ledger_db_ = NULL; account_db_ = NULL; check_interval_ = utils::MICRO_UNITS_PER_SEC; } Storage::~Storage() {} bool Storage::Initialize(const DbConfigure &db_config, bool bdropdb) { do { std::string strConnect = ""; std::string str_dbname = ""; std::vector<std::string> nparas = utils::String::split(db_config.rational_string_, " "); for (std::size_t i = 0; i < nparas.size(); i++) { std::string str = nparas[i]; std::vector<std::string> n = utils::String::split(str, "="); if (n.size() == 2) { if (n[0] != "dbname") { strConnect += " "; strConnect += str; } else { str_dbname = n[1]; } } } if (bdropdb) { bool do_success = false; do { //check the db if opened only for linux or mac #ifndef WIN32 KeyValueDb *account_db = NewKeyValueDb(db_config); if (!account_db->Open(db_config.account_db_path_, -1)) { LOG_ERROR("Drop failed, error desc(%s)", account_db->error_desc().c_str()); delete account_db; break; } account_db->Close(); delete account_db; #endif if (utils::File::IsExist(db_config.keyvalue_db_path_) && !utils::File::DeleteFolder(db_config.keyvalue_db_path_)) { LOG_ERROR_ERRNO("Delete keyvalue db failed", STD_ERR_CODE, STD_ERR_DESC); break; } if (utils::File::IsExist(db_config.ledger_db_path_) && !utils::File::DeleteFolder(db_config.ledger_db_path_)) { LOG_ERROR_ERRNO("Delete ledger db failed", STD_ERR_CODE, STD_ERR_DESC); break; } if (utils::File::IsExist(db_config.account_db_path_) && !utils::File::DeleteFolder(db_config.account_db_path_)) { LOG_ERROR_ERRNO("Delete account db failed", STD_ERR_CODE, STD_ERR_DESC); break; } LOG_INFO("Drop db successful"); do_success = true; } while (false); return do_success; } int32_t keyvaule_max_open_files = -1; int32_t ledger_max_open_files = -1; int32_t account_max_open_files = -1; #ifdef OS_MAC FILE* fp = NULL; char ulimit_cmd[1024] = {0}; char ulimit_result[1024] = {0}; sprintf(ulimit_cmd, "ulimit -n"); if ((fp = popen(ulimit_cmd, "r")) != NULL) { fgets(ulimit_result, sizeof(ulimit_result), fp); pclose(fp); } int32_t max_open_files = utils::String::Stoi(std::string(ulimit_result)); if (max_open_files <= 100) { keyvaule_max_open_files = 2; ledger_max_open_files = 4; account_max_open_files = 4; LOG_ERROR("mac os max open files is too lower:%d.", max_open_files); } else { keyvaule_max_open_files = 2 + (max_open_files - 100) * 0.2; ledger_max_open_files = 4 + (max_open_files - 100) * 0.4; account_max_open_files = 4 + (max_open_files - 100) * 0.4; keyvaule_max_open_files = (keyvaule_max_open_files > PHANTOM_ROCKSDB_MAX_OPEN_FILES) ? -1 : keyvaule_max_open_files; ledger_max_open_files = (ledger_max_open_files > PHANTOM_ROCKSDB_MAX_OPEN_FILES) ? -1 : ledger_max_open_files; account_max_open_files = (account_max_open_files > PHANTOM_ROCKSDB_MAX_OPEN_FILES) ? -1 : account_max_open_files; } LOG_INFO("mac os db file limited:%d, keyvaule:%d, ledger:%d, account:%d:", max_open_files, keyvaule_max_open_files, ledger_max_open_files, account_max_open_files); #endif keyvalue_db_ = NewKeyValueDb(db_config); if (!keyvalue_db_->Open(db_config.keyvalue_db_path_, keyvaule_max_open_files)) { LOG_ERROR("Keyvalue_db path(%s) open fail(%s)\n", db_config.keyvalue_db_path_.c_str(), keyvalue_db_->error_desc().c_str()); break; } ledger_db_ = NewKeyValueDb(db_config); if (!ledger_db_->Open(db_config.ledger_db_path_, ledger_max_open_files)) { LOG_ERROR("Ledger db path(%s) open fail(%s)\n", db_config.ledger_db_path_.c_str(), ledger_db_->error_desc().c_str()); break; } account_db_ = NewKeyValueDb(db_config); if (!account_db_->Open(db_config.account_db_path_, account_max_open_files)) { LOG_ERROR("Ledger db path(%s) open fail(%s)\n", db_config.account_db_path_.c_str(), account_db_->error_desc().c_str()); break; } TimerNotify::RegisterModule(this); return true; } while (false); CloseDb(); return false; } bool Storage::CloseDb() { bool ret1 = true, ret2 = true, ret3 = true; if (keyvalue_db_ != NULL) { ret1 = keyvalue_db_->Close(); delete keyvalue_db_; keyvalue_db_ = NULL; } if (ledger_db_ != NULL) { ret2 = ledger_db_->Close(); delete ledger_db_; ledger_db_ = NULL; } if (account_db_ != NULL) { ret3 = account_db_->Close(); delete account_db_; account_db_ = NULL; } return ret1 && ret2 && ret3; } bool Storage::Exit() { return CloseDb(); } void Storage::OnSlowTimer(int64_t current_time) { } KeyValueDb *Storage::keyvalue_db() { return keyvalue_db_; } KeyValueDb *Storage::ledger_db() { return ledger_db_; } KeyValueDb *Storage::account_db() { return account_db_; } KeyValueDb *Storage::NewKeyValueDb(const DbConfigure &db_config) { KeyValueDb *db = NULL; #ifdef WIN32 db = new LevelDbDriver(); #else db = new RocksDbDriver(); #endif return db; } }
25.461905
120
0.667851
[ "vector" ]
b689dc8ffecee97a1051165115c8554f2cc249ce
11,639
cpp
C++
vendor/sll/tests/non_periodic_spline_builder.cpp
gyselax/gyselalibxx
5f9b4b1e20050f87e2a9f05d510bedf0f9a15b34
[ "MIT" ]
3
2022-02-28T08:47:07.000Z
2022-03-01T10:29:08.000Z
vendor/sll/tests/non_periodic_spline_builder.cpp
gyselax/gyselalibxx
5f9b4b1e20050f87e2a9f05d510bedf0f9a15b34
[ "MIT" ]
null
null
null
vendor/sll/tests/non_periodic_spline_builder.cpp
gyselax/gyselalibxx
5f9b4b1e20050f87e2a9f05d510bedf0f9a15b34
[ "MIT" ]
null
null
null
#include <algorithm> #include <array> #include <cmath> #include <iosfwd> #include <vector> #include <experimental/mdspan> #include <ddc/ddc.hpp> #include <sll/bsplines_non_uniform.hpp> #include <sll/bsplines_uniform.hpp> #include <sll/null_boundary_value.hpp> #include <sll/spline_builder.hpp> #include <sll/spline_evaluator.hpp> #include <sll/view.hpp> #include <gtest/gtest.h> #include "cosine_evaluator.hpp" #include "polynomial_evaluator.hpp" #include "test_utils.hpp" template <class T> struct NonPeriodicSplineBuilderTestFixture; template <std::size_t D, class Evaluator, BoundCond BcL, BoundCond BcR, bool Uniform> struct NonPeriodicSplineBuilderTestFixture<std::tuple< std::integral_constant<std::size_t, D>, Evaluator, std::integral_constant<BoundCond, BcL>, std::integral_constant<BoundCond, BcR>, std::integral_constant<bool, Uniform>>> : public testing::Test { // Needs to be defined here to avoid multiple initializations of the discretization function struct DimX { static constexpr bool PERIODIC = false; }; static constexpr std::size_t s_degree = D; static constexpr BoundCond s_bcl = BcL; static constexpr BoundCond s_bcr = BcR; using BSpline = std::conditional_t<Uniform, UniformBSplines<DimX, D>, NonUniformBSplines<DimX, D>>; using IDimX = typename SplineBuilder<BSpline, BcL, BcR>::interpolation_mesh_type; using evaluator_type = typename Evaluator::template Evaluator<IDimX>; }; using degrees = std::integer_sequence<std::size_t, 1, 2, 3, 4, 5, 6>; using evaluators = std::tuple<CosineEvaluator>; using boundary_conds = std::integer_sequence<BoundCond, BoundCond::GREVILLE, BoundCond::HERMITE>; using is_uniform_types = std::tuple<std::true_type, std::false_type>; using Cases = tuple_to_types_t< cartesian_product_t<degrees, evaluators, boundary_conds, boundary_conds, is_uniform_types>>; TYPED_TEST_SUITE(NonPeriodicSplineBuilderTestFixture, Cases); TYPED_TEST(NonPeriodicSplineBuilderTestFixture, Constructor) { using DimX = typename TestFixture::DimX; using BSplinesX = UniformBSplines<DimX, TestFixture::s_degree>; init_discretization<BSplinesX>(Coordinate<DimX>(0.), Coordinate<DimX>(0.02), 100); SplineBuilder<BSplinesX, TestFixture::s_bcl, TestFixture::s_bcr> spline_builder; spline_builder.interpolation_domain(); } // Checks that when evaluating the spline at interpolation points one // recovers values that were used to build the spline TYPED_TEST(NonPeriodicSplineBuilderTestFixture, Identity) { using DimX = typename TestFixture::DimX; using IDimX = typename TestFixture::IDimX; using IndexX = DiscreteCoordinate<IDimX>; using BSplinesX = typename TestFixture::BSpline; using BsplIndexX = DiscreteCoordinate<BSplinesX>; using SplineX = Chunk<double, DiscreteDomain<BSplinesX>>; using FieldX = Chunk<double, DiscreteDomain<IDimX>>; using CoordX = Coordinate<DimX>; CoordX constexpr x0(0.); CoordX constexpr xN(1.); std::size_t constexpr ncells = 100; // 1. Create BSplines if constexpr (BSplinesX::is_uniform()) { init_discretization<BSplinesX>(x0, xN, ncells); } else { IndexX constexpr npoints(ncells + 1); std::vector<double> breaks(npoints); double dx = (xN - x0) / ncells; for (std::size_t i(0); i < npoints; ++i) { breaks[i] = x0 + i * dx; } init_discretization<BSplinesX>(breaks); } DiscreteDomain<BSplinesX> const dom_bsplines_x( BsplIndexX(0), DiscreteVector<BSplinesX>(discretization<BSplinesX>().size())); // 2. Create a Spline represented by a chunk over BSplines // The chunk is filled with garbage data, we need to initialize it SplineX coef(dom_bsplines_x); // 3. Create a SplineBuilder over BSplines using some boundary conditions SplineBuilder<BSplinesX, TestFixture::s_bcl, TestFixture::s_bcr> spline_builder; auto interpolation_domain = spline_builder.interpolation_domain(); // 4. Allocate and fill a chunk over the interpolation domain FieldX yvals(interpolation_domain); typename TestFixture::evaluator_type evaluator; evaluator(yvals.span_view()); int constexpr shift = TestFixture::s_degree % 2; // shift = 0 for even order, 1 for odd order std::array<double, TestFixture::s_degree / 2> Sderiv_lhs_data; DSpan1D Sderiv_lhs(Sderiv_lhs_data.data(), Sderiv_lhs_data.size()); for (std::size_t ii = 0; ii < Sderiv_lhs.extent(0); ++ii) { Sderiv_lhs(ii) = evaluator.deriv(x0, ii + shift); } std::array<double, TestFixture::s_degree / 2> Sderiv_rhs_data; DSpan1D Sderiv_rhs(Sderiv_rhs_data.data(), Sderiv_rhs_data.size()); for (std::size_t ii = 0; ii < Sderiv_rhs.extent(0); ++ii) { Sderiv_rhs(ii) = evaluator.deriv(xN, ii + shift); } DSpan1D* deriv_l(TestFixture::s_bcl == BoundCond::HERMITE ? &Sderiv_lhs : nullptr); DSpan1D* deriv_r(TestFixture::s_bcr == BoundCond::HERMITE ? &Sderiv_rhs : nullptr); // 5. Finally build the spline by filling `coef` spline_builder(coef, yvals, deriv_l, deriv_r); // 6. Create a SplineEvaluator to evaluate the spline at any point in the domain of the BSplines SplineEvaluator<BSplinesX> spline_evaluator( NullBoundaryValue<BSplinesX>::value, NullBoundaryValue<BSplinesX>::value); FieldX coords_eval(interpolation_domain); for (IndexX const ix : interpolation_domain) { coords_eval(ix) = to_real(ix); } FieldX spline_eval(interpolation_domain); spline_evaluator(spline_eval.span_view(), coords_eval.span_cview(), coef.span_cview()); FieldX spline_eval_deriv(interpolation_domain); spline_evaluator .deriv(spline_eval_deriv.span_view(), coords_eval.span_cview(), coef.span_cview()); // 7. Checking errors double max_norm_error = 0.; double max_norm_error_diff = 0.; for (IndexX const ix : interpolation_domain) { CoordX const x = to_real(ix); // Compute error double const error = spline_eval(ix) - yvals(ix); max_norm_error = std::fmax(max_norm_error, std::fabs(error)); // Compute error double const error_deriv = spline_eval_deriv(ix) - evaluator.deriv(x, 1); max_norm_error_diff = std::fmax(max_norm_error_diff, std::fabs(error_deriv)); } EXPECT_LE(max_norm_error, 1.0e-12); } template <class T> struct PolynomialNonPeriodicSplineBuilderTestFixture; template <std::size_t D, BoundCond BcL, BoundCond BcR, bool Uniform> struct PolynomialNonPeriodicSplineBuilderTestFixture<std::tuple< std::integral_constant<std::size_t, D>, std::integral_constant<BoundCond, BcL>, std::integral_constant<BoundCond, BcR>, std::integral_constant<bool, Uniform>>> : public testing::Test { // Needs to be defined here to avoid multiple initializations of the discretization function struct DimX { static constexpr bool PERIODIC = false; }; static constexpr std::size_t s_degree = D; static constexpr BoundCond s_bcl = BcL; static constexpr BoundCond s_bcr = BcR; using BSpline = std::conditional_t<Uniform, UniformBSplines<DimX, D>, NonUniformBSplines<DimX, D>>; using IDimX = typename SplineBuilder<BSpline, BcL, BcR>::interpolation_mesh_type; }; using poly_Cases = tuple_to_types_t< cartesian_product_t<degrees, boundary_conds, boundary_conds, is_uniform_types>>; TYPED_TEST_SUITE(PolynomialNonPeriodicSplineBuilderTestFixture, poly_Cases); // Checks that when evaluating the spline at interpolation points one // recovers values that were used to build the spline TYPED_TEST(PolynomialNonPeriodicSplineBuilderTestFixture, PolynomialIdentity) { using DimX = typename TestFixture::DimX; using IDimX = typename TestFixture::IDimX; using IndexX = DiscreteCoordinate<IDimX>; using BSplinesX = typename TestFixture::BSpline; using BsplIndexX = DiscreteCoordinate<BSplinesX>; using SplineX = Chunk<double, DiscreteDomain<BSplinesX>>; using FieldX = Chunk<double, DiscreteDomain<IDimX>>; using CoordX = Coordinate<DimX>; std::size_t constexpr degree = TestFixture::s_degree; CoordX constexpr x0(0.); CoordX constexpr xN(1.); std::size_t constexpr ncells = 100; // 1. Create BSplines if constexpr (BSplinesX::is_uniform()) { init_discretization<BSplinesX>(x0, xN, ncells); } else { IndexX constexpr npoints(ncells + 1); std::vector<double> breaks(npoints); double dx = (xN - x0) / ncells; for (std::size_t i(0); i < npoints; ++i) { breaks[i] = x0 + i * dx; } init_discretization<BSplinesX>(breaks); } DiscreteDomain<BSplinesX> const dom_bsplines_x( BsplIndexX(0), DiscreteVector<BSplinesX>(discretization<BSplinesX>().size())); // 2. Create a Spline represented by a chunk over BSplines // The chunk is filled with garbage data, we need to initialize it SplineX coef(dom_bsplines_x); // 3. Create a SplineBuilder over BSplines using some boundary conditions SplineBuilder<BSplinesX, TestFixture::s_bcl, TestFixture::s_bcr> spline_builder; auto interpolation_domain = spline_builder.interpolation_domain(); // 4. Allocate and fill a chunk over the interpolation domain FieldX yvals(interpolation_domain); typename PolynomialEvaluator::Evaluator<IDimX> evaluator(degree); evaluator(yvals.span_view()); int constexpr shift = degree % 2; // shift = 0 for even order, 1 for odd order std::array<double, degree / 2> Sderiv_lhs_data; DSpan1D Sderiv_lhs(Sderiv_lhs_data.data(), Sderiv_lhs_data.size()); for (std::size_t ii = 0; ii < Sderiv_lhs.extent(0); ++ii) { Sderiv_lhs(ii) = evaluator.deriv(x0, ii + shift); } std::array<double, TestFixture::s_degree / 2> Sderiv_rhs_data; DSpan1D Sderiv_rhs(Sderiv_rhs_data.data(), Sderiv_rhs_data.size()); for (std::size_t ii = 0; ii < Sderiv_rhs.extent(0); ++ii) { Sderiv_rhs(ii) = evaluator.deriv(xN, ii + shift); } DSpan1D* deriv_l(TestFixture::s_bcl == BoundCond::HERMITE ? &Sderiv_lhs : nullptr); DSpan1D* deriv_r(TestFixture::s_bcr == BoundCond::HERMITE ? &Sderiv_rhs : nullptr); // 5. Finally build the spline by filling `coef` spline_builder(coef, yvals, deriv_l, deriv_r); // 6. Create a SplineEvaluator to evaluate the spline at any point in the domain of the BSplines SplineEvaluator<BSplinesX> spline_evaluator( NullBoundaryValue<BSplinesX>::value, NullBoundaryValue<BSplinesX>::value); // 7. Checking errors double max_norm_error = 0.; double max_norm_error_diff = 0.; double dx = (xN - x0) / (ncells * 3); for (std::size_t i(0); i < ncells * 3 + 1; ++i) { CoordX const x = x0 + i * dx; // Compute error double const error = spline_evaluator(x, coef.span_cview()) - evaluator(x); max_norm_error = std::fmax(max_norm_error, std::fabs(error)); // Compute error double const error_deriv = spline_evaluator.deriv(x, coef.span_cview()) - evaluator.deriv(x, 1); max_norm_error_diff = std::fmax(max_norm_error_diff, std::fabs(error_deriv)); } double const max_norm_error_integ = std::fabs( spline_evaluator.integrate(coef.span_cview()) - evaluator.deriv(xN, -1) + evaluator.deriv(x0, -1)); EXPECT_LE(max_norm_error, 1.0e-12); EXPECT_LE(max_norm_error_diff, 1.0e-11); EXPECT_LE(max_norm_error_integ, 1.0e-11); }
40.554007
100
0.701607
[ "vector" ]
b68c6ef7ee7c0322a377a639dcf8a3f24852b53e
1,965
cpp
C++
plugins/core/tools/src/inject/injectortool.cpp
MadManRises/Madgine
c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f
[ "MIT" ]
5
2018-05-16T14:09:34.000Z
2019-10-24T19:01:15.000Z
plugins/core/tools/src/inject/injectortool.cpp
MadManRises/Madgine
c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f
[ "MIT" ]
71
2017-06-20T06:41:42.000Z
2021-01-11T11:18:53.000Z
plugins/core/tools/src/inject/injectortool.cpp
MadManRises/Madgine
c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f
[ "MIT" ]
2
2018-05-16T13:57:25.000Z
2018-05-16T13:57:51.000Z
#include "../toolslib.h" #include "Meta/inject/variable.h" #include "Meta/inject/inject.h" #include "controlflow.h" #include "injectortool.h" #include "Modules/uniquecomponent/uniquecomponentcollector.h" #include <imgui/imgui.h> #include "Meta/keyvalue/metatable_impl.h" #include "Meta/serialize/serializetable_impl.h" UNIQUECOMPONENT(Engine::Tools::InjectorTool); METATABLE_BEGIN_BASE(Engine::Tools::InjectorTool, Engine::Tools::ToolBase) METATABLE_END(Engine::Tools::InjectorTool) SERIALIZETABLE_INHERIT_BEGIN(Engine::Tools::InjectorTool, Engine::Tools::ToolBase) SERIALIZETABLE_END(Engine::Tools::InjectorTool) namespace Engine { namespace Tools { template <typename... Injectors> Inject::Variable<int, Injectors...> sample() { Inject::Variable<int, Injectors...> v = 3; Inject::Variable<int, Injectors...> v2 = 3; while (v2 > 0) { ++v; --v2; } return v; } InjectorTool::InjectorTool(ImRoot &root) : Tool<InjectorTool>(root) { auto result = Inject::inject<Inject::ControlFlow>(&sample<Inject::ControlFlow>); mGraph = result->mContext.graph(); } InjectorTool::~InjectorTool() { } void InjectorTool::render() { if (ImGui::Begin("InjectorTool", &mVisible)) { for (const Inject::ControlFlow::BasicBlock& block : mGraph) { ImGui::BeginChild(ImGui::GetID(&block)); ImGui::Text("Block"); ImGui::Text("Range: %p - %p", block.mAddresses.front(), block.mAddresses.back()); std::stringstream ss; for (size_t i : block.mTargets) ss << " " << i; ImGui::Text(("Targets:" + ss.str()).c_str()); ImGui::EndChild(); } } ImGui::End(); } std::string_view InjectorTool::key() const { return "InjectorTool"; } } }
25.855263
97
0.592875
[ "render" ]
b68ee74738a7544a20520903a136f95da01739b3
11,782
cpp
C++
ds/security/gina/snapins/gpedit/dataobj.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/security/gina/snapins/gpedit/dataobj.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/security/gina/snapins/gpedit/dataobj.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "main.h" #include <initguid.h> #include "dataobj.h" unsigned int CDataObject::m_cfNodeType = RegisterClipboardFormat(CCF_NODETYPE); unsigned int CDataObject::m_cfNodeTypeString = RegisterClipboardFormat(CCF_SZNODETYPE); unsigned int CDataObject::m_cfDisplayName = RegisterClipboardFormat(CCF_DISPLAY_NAME); unsigned int CDataObject::m_cfCoClass = RegisterClipboardFormat(CCF_SNAPIN_CLASSID); unsigned int CDataObject::m_cfPreloads = RegisterClipboardFormat(CCF_SNAPIN_PRELOADS); unsigned int CDataObject::m_cfNodeID = RegisterClipboardFormat(CCF_NODEID); unsigned int CDataObject::m_cfDescription = RegisterClipboardFormat(L"CCF_DESCRIPTION"); unsigned int CDataObject::m_cfHTMLDetails = RegisterClipboardFormat(L"CCF_HTML_DETAILS"); /////////////////////////////////////////////////////////////////////////////// // // // CDataObject implementation // // // /////////////////////////////////////////////////////////////////////////////// CDataObject::CDataObject(CComponentData *pComponent) { m_cRef = 1; InterlockedIncrement(&g_cRefThisDll); m_pcd = pComponent; m_pcd->AddRef(); m_type = CCT_UNINITIALIZED; m_cookie = -1; } CDataObject::~CDataObject() { m_pcd->Release(); InterlockedDecrement(&g_cRefThisDll); } /////////////////////////////////////////////////////////////////////////////// // // // CDataObject object implementation (IUnknown) // // // /////////////////////////////////////////////////////////////////////////////// HRESULT CDataObject::QueryInterface (REFIID riid, void **ppv) { if (IsEqualIID(riid, IID_IGPEInformation)) { *ppv = (LPGPEINFORMATION)this; m_cRef++; return S_OK; } else if (IsEqualIID(riid, IID_IGroupPolicyObject)) { if (m_pcd->m_pGPO) { return (m_pcd->m_pGPO->QueryInterface (riid, ppv)); } else { *ppv = NULL; return E_NOINTERFACE; } } else if (IsEqualIID(riid, IID_IGPEDataObject)) { *ppv = (LPGPEDATAOBJECT)this; m_cRef++; return S_OK; } else if (IsEqualIID(riid, IID_IDataObject) || IsEqualIID(riid, IID_IUnknown)) { *ppv = (LPDATAOBJECT)this; m_cRef++; return S_OK; } else { *ppv = NULL; return E_NOINTERFACE; } } ULONG CDataObject::AddRef (void) { return ++m_cRef; } ULONG CDataObject::Release (void) { if (--m_cRef == 0) { delete this; return 0; } return m_cRef; } /////////////////////////////////////////////////////////////////////////////// // // // CDataObject object implementation (IDataObject) // // // /////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CDataObject::GetDataHere(LPFORMATETC lpFormatetc, LPSTGMEDIUM lpMedium) { HRESULT hr = DV_E_CLIPFORMAT; // Based on the CLIPFORMAT write data to the stream const CLIPFORMAT cf = lpFormatetc->cfFormat; if(cf == m_cfNodeType) { hr = CreateNodeTypeData(lpMedium); } else if(cf == m_cfNodeTypeString) { hr = CreateNodeTypeStringData(lpMedium); } else if (cf == m_cfDisplayName) { hr = CreateDisplayName(lpMedium); } else if (cf == m_cfCoClass) { hr = CreateCoClassID(lpMedium); } else if (cf == m_cfPreloads) { hr = CreatePreloadsData(lpMedium); } else if (cf == m_cfDescription) { hr = DV_E_TYMED; if (lpMedium->tymed == TYMED_ISTREAM) { ULONG ulWritten; TCHAR szDesc[300]; IStream *lpStream = lpMedium->pstm; if(lpStream) { LoadString (g_hInstance, g_NameSpace[m_cookie].iStringDescID, szDesc, ARRAYSIZE(szDesc)); hr = lpStream->Write(szDesc, lstrlen(szDesc) * sizeof(TCHAR), &ulWritten); } } } else if (cf == m_cfHTMLDetails) { hr = DV_E_TYMED; if (lpMedium->tymed == TYMED_ISTREAM) { ULONG ulWritten; if (m_cookie == 0) { IStream *lpStream = lpMedium->pstm; if(lpStream) { hr = lpStream->Write(g_szDisplayProperties, lstrlen(g_szDisplayProperties) * sizeof(TCHAR), &ulWritten); } } } } return hr; } STDMETHODIMP CDataObject::GetData(LPFORMATETC lpFormatetc, LPSTGMEDIUM lpMedium) { HRESULT hr = DV_E_CLIPFORMAT; // Based on the CLIPFORMAT write data to the stream const CLIPFORMAT cf = lpFormatetc->cfFormat; if (cf == m_cfNodeID) { hr = CreateNodeIDData(lpMedium); } return hr; } /////////////////////////////////////////////////////////////////////////////// // // // CDataObject object implementation (IGPEInformation) // // // /////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CDataObject::GetName (LPOLESTR pszName, int cchMaxLength) { return m_pcd->m_pGPO->GetName(pszName, cchMaxLength); } STDMETHODIMP CDataObject::GetDisplayName (LPOLESTR pszName, int cchMaxLength) { return m_pcd->m_pGPO->GetDisplayName(pszName, cchMaxLength); } STDMETHODIMP CDataObject::GetRegistryKey (DWORD dwSection, HKEY *hKey) { return m_pcd->m_pGPO->GetRegistryKey(dwSection, hKey); } STDMETHODIMP CDataObject::GetDSPath (DWORD dwSection, LPOLESTR pszPath, int cchMaxPath) { return m_pcd->m_pGPO->GetDSPath(dwSection, pszPath, cchMaxPath); } STDMETHODIMP CDataObject::GetFileSysPath (DWORD dwSection, LPOLESTR pszPath, int cchMaxPath) { return m_pcd->m_pGPO->GetFileSysPath(dwSection, pszPath, cchMaxPath); } STDMETHODIMP CDataObject::GetOptions (DWORD *dwOptions) { return m_pcd->GetOptions(dwOptions); } STDMETHODIMP CDataObject::GetType (GROUP_POLICY_OBJECT_TYPE *gpoType) { return m_pcd->m_pGPO->GetType(gpoType); } STDMETHODIMP CDataObject::GetHint (GROUP_POLICY_HINT_TYPE *gpHint) { if (!gpHint) { return E_INVALIDARG; } *gpHint = m_pcd->m_gpHint; return S_OK; } STDMETHODIMP CDataObject::PolicyChanged (BOOL bMachine, BOOL bAdd, GUID *pGuidExtension, GUID *pGuidSnapin) { return m_pcd->m_pGPO->Save(bMachine, bAdd, pGuidExtension, pGuidSnapin); } /////////////////////////////////////////////////////////////////////////////// // // // CDataObject object implementation (Internal functions) // // // /////////////////////////////////////////////////////////////////////////////// HRESULT CDataObject::Create(LPVOID pBuffer, INT len, LPSTGMEDIUM lpMedium) { HRESULT hr = DV_E_TYMED; // Do some simple validation if (pBuffer == NULL || lpMedium == NULL) return E_POINTER; // Make sure the type medium is HGLOBAL if (lpMedium->tymed == TYMED_HGLOBAL) { // Create the stream on the hGlobal passed in LPSTREAM lpStream; hr = CreateStreamOnHGlobal(lpMedium->hGlobal, FALSE, &lpStream); if (SUCCEEDED(hr)) { // Write to the stream the number of bytes unsigned long written; hr = lpStream->Write(pBuffer, len, &written); // Because we told CreateStreamOnHGlobal with 'FALSE', // only the stream is released here. // Note - the caller (i.e. snap-in, object) will free the HGLOBAL // at the correct time. This is according to the IDataObject specification. lpStream->Release(); } } return hr; } HRESULT CDataObject::CreateNodeTypeData(LPSTGMEDIUM lpMedium) { const GUID * pGUID; LPRESULTITEM lpResultItem = (LPRESULTITEM) m_cookie; if (m_cookie == -1) return E_UNEXPECTED; if (m_type == CCT_RESULT) pGUID = g_NameSpace[lpResultItem->dwNameSpaceItem].pNodeID; else pGUID = g_NameSpace[m_cookie].pNodeID; // Create the node type object in GUID format return Create((LPVOID)pGUID, sizeof(GUID), lpMedium); } HRESULT CDataObject::CreateNodeTypeStringData(LPSTGMEDIUM lpMedium) { const GUID * pGUID; LPRESULTITEM lpResultItem = (LPRESULTITEM) m_cookie; TCHAR szNodeType[50]; if (m_cookie == -1) return E_UNEXPECTED; if (m_type == CCT_RESULT) pGUID = g_NameSpace[lpResultItem->dwNameSpaceItem].pNodeID; else pGUID = g_NameSpace[m_cookie].pNodeID; szNodeType[0] = TEXT('\0'); StringFromGUID2 (*pGUID, szNodeType, 50); // Create the node type object in GUID string format return Create((LPVOID)szNodeType, ((lstrlenW(szNodeType)+1) * sizeof(WCHAR)), lpMedium); } HRESULT CDataObject::CreateDisplayName(LPSTGMEDIUM lpMedium) { WCHAR szDisplayName[300]; // // This is the display named used in the scope pane and snap-in manager // szDisplayName[0] = TEXT('\0'); if (m_pcd->m_pGPO && m_pcd->m_pDisplayName) { lstrcpyn (szDisplayName, m_pcd->m_pDisplayName, 300); } else { LoadStringW (g_hInstance, IDS_SNAPIN_NAME, szDisplayName, ARRAYSIZE(szDisplayName)); } return Create((LPVOID)szDisplayName, (lstrlenW(szDisplayName) + 1) * sizeof(WCHAR), lpMedium); } HRESULT CDataObject::CreateCoClassID(LPSTGMEDIUM lpMedium) { // Create the CoClass information return Create((LPVOID)&CLSID_GPESnapIn, sizeof(CLSID), lpMedium); } HRESULT CDataObject::CreatePreloadsData(LPSTGMEDIUM lpMedium) { BOOL bPreload = TRUE; return Create((LPVOID)&bPreload, sizeof(bPreload), lpMedium); } HRESULT CDataObject::CreateNodeIDData(LPSTGMEDIUM lpMedium) { const GUID * pGUID; LPRESULTITEM lpResultItem = (LPRESULTITEM) m_cookie; TCHAR szNodeType[50]; SNodeID * psNode; if (m_cookie == -1) return E_UNEXPECTED; if (m_type == CCT_RESULT) pGUID = g_NameSpace[lpResultItem->dwNameSpaceItem].pNodeID; else pGUID = g_NameSpace[m_cookie].pNodeID; szNodeType[0] = TEXT('\0'); StringFromGUID2 (*pGUID, szNodeType, 50); lpMedium->hGlobal = GlobalAlloc (GMEM_SHARE | GMEM_MOVEABLE, (lstrlen(szNodeType) * sizeof(TCHAR)) + sizeof(SNodeID)); if (!lpMedium->hGlobal) { return (STG_E_MEDIUMFULL); } psNode = (SNodeID *) GlobalLock (lpMedium->hGlobal); psNode->cBytes = lstrlen(szNodeType) * sizeof(TCHAR); CopyMemory (psNode->id, szNodeType, psNode->cBytes); GlobalUnlock (lpMedium->hGlobal); return S_OK; }
29.308458
125
0.533865
[ "object" ]
b6a219273faa3cc8ebaa6c2d3c258f5e39bdd707
6,196
cpp
C++
examples/tess_dense/prod.cpp
tpeterka/decaf
ad6ad823070793bfd7fc8d9384d5475f7cf20848
[ "BSD-3-Clause" ]
1
2019-05-10T02:50:50.000Z
2019-05-10T02:50:50.000Z
examples/tess_dense/prod.cpp
tpeterka/decaf
ad6ad823070793bfd7fc8d9384d5475f7cf20848
[ "BSD-3-Clause" ]
2
2020-10-28T03:44:51.000Z
2021-01-18T19:49:33.000Z
examples/tess_dense/prod.cpp
tpeterka/decaf
ad6ad823070793bfd7fc8d9384d5475f7cf20848
[ "BSD-3-Clause" ]
2
2018-08-31T14:02:47.000Z
2020-04-17T16:01:54.000Z
//--------------------------------------------------------------------------- // // generates synthetic particles and sends them to the rest of the workflow // // Tom Peterka // Argonne National Laboratory // 9700 S. Cass Ave. // Argonne, IL 60439 // tpeterka@mcs.anl.gov // //-------------------------------------------------------------------------- #include <decaf/decaf.hpp> #include <bredala/data_model/simplefield.hpp> #include <bredala/data_model/arrayfield.hpp> #include <bredala/data_model/blockfield.hpp> #include <bredala/data_model/boost_macros.h> #include <assert.h> #include <math.h> #include <mpi.h> #include <map> #include <cstdlib> using namespace decaf; using namespace std; // producer void prod(Decaf* decaf, int tot_npts, int nsteps) { // hacc produces 3 arrays of position coordinates // we're making up some synthetic data instead // number of points, randomly placed in a box of size [0, npts - 1]^3 int npts = tot_npts / decaf->local_comm_size(); fprintf(stderr, "Generates locally %i particles.\n", npts); // add 1 to the rank because on some compilers, srand(0) = srand(1) srand(decaf->world->rank() + 1); // produce data for some number of timesteps for (int timestep = 0; timestep < nsteps; timestep++) { // create the synthetic points for the timestep fprintf(stderr, "producer timestep %d\n", timestep); // the point arrays need to be allocated inside the loop because // decaf will automatically free them at the end of the loop after sending // (smart pointer reference counting) float* x = new float[npts]; float* y = new float[npts]; float* z = new float[npts]; for (unsigned i = 0; i < npts; ++i) { // debug: test what happens when a point is duplicated or outside the domain // if (i == 1) // duplicate point test // { // x[i] = x[i - 1]; // y[i] = y[i - 1]; // z[i] = z[i - 1]; // } // else if (i == npts - 1) // out of bounds test // { // float t = (float) rand() / RAND_MAX; // x[i] = npts; // t = (float) rand() / RAND_MAX; // y[i] = t * (npts - 1); // t = (float) rand() / RAND_MAX; // z[i] = t * (npts - 1); // } // else // { float t = (float) rand() / RAND_MAX; x[i] = t * (npts - 1); t = (float) rand() / RAND_MAX; y[i] = t * (npts - 1); t = (float) rand() / RAND_MAX; z[i] = t * (npts - 1); // } } // mins and sizes, not mins and maxs vector<unsigned int> extendsBlock = {0, 0, 0, (unsigned)npts, (unsigned)npts, (unsigned)npts}; vector<float> bboxBlock = {0.0, 0.0, 0.0, (float)npts, float(npts), float(npts)}; // describe to decaf the global and local domain BlockField domainData(true); Block<3>* domainBlock = domainData.getBlock(); domainBlock->setGridspace(1.0); domainBlock->setGlobalExtends(extendsBlock); domainBlock->setLocalExtends(extendsBlock); domainBlock->setOwnExtends(extendsBlock); domainBlock->setGlobalBBox(bboxBlock); domainBlock->setLocalBBox(bboxBlock); domainBlock->setOwnBBox(bboxBlock); domainBlock->ghostSize_ = 0; // define the fields of the data model ArrayFieldf x_pos(x, npts, 1, true); ArrayFieldf y_pos(y, npts, 1, true); ArrayFieldf z_pos(z, npts, 1, true); // debug // for (int i = 0; i < npts; i++) // fprintf(stderr, "%.3f %.3f %.3f\n", x[i], y[i], z[i]); // push the fields into a container pConstructData container; container->appendData(string("x_pos"), x_pos, DECAF_NOFLAG, DECAF_PRIVATE, DECAF_SPLIT_DEFAULT, DECAF_MERGE_APPEND_VALUES); container->appendData(string("y_pos"), y_pos, DECAF_NOFLAG, DECAF_PRIVATE, DECAF_SPLIT_DEFAULT, DECAF_MERGE_APPEND_VALUES); container->appendData(string("z_pos"), z_pos, DECAF_NOFLAG, DECAF_PRIVATE, DECAF_SPLIT_DEFAULT, DECAF_MERGE_APPEND_VALUES); container->appendData("domain_block", domainData, DECAF_NOFLAG, DECAF_PRIVATE, DECAF_SPLIT_KEEP_VALUE, DECAF_MERGE_FIRST_VALUE); // send the data on all outbound dataflows // in this example there is only one outbound dataflow, but in general there could be more decaf->put(container); } // terminate the task (mandatory) by sending a quit message to the rest of the workflow fprintf(stderr, "producer terminating\n"); decaf->terminate(); } int main(int argc, char** argv) { MPI_Init(NULL, NULL); if(argc < 3) { fprintf(stderr, "Usage: points tot_npts nsteps\n"); MPI_Abort(MPI_COMM_WORLD, 0); } int tot_npts = atoi(argv[1]); int nsteps = atoi(argv[2]); fprintf(stderr, "Will generate %i particles in total.\n", tot_npts); // define the workflow Workflow workflow; Workflow::make_wflow_from_json(workflow, "tess_dense.json"); // create decaf Decaf* decaf = new Decaf(MPI_COMM_WORLD, workflow); // timing MPI_Barrier(decaf->prod_comm_handle()); double t0 = MPI_Wtime(); if (decaf->prod_comm()->rank() == 0) fprintf(stderr, "*** workflow starting time = %.3lf s. ***\n", t0); // start the task prod(decaf, tot_npts, nsteps); // timing MPI_Barrier(decaf->prod_comm_handle()); if (decaf->prod_comm()->rank() == 0) fprintf(stderr, "*** prod. elapsed time = %.3lf s. ***\n", MPI_Wtime() - t0); // cleanup delete decaf; MPI_Finalize(); fprintf(stderr, "finished prod\n"); return 0; }
35.00565
98
0.545675
[ "vector", "model" ]
b6a34bedf23b4740a1af0f2d18555e7d4e195417
818
cpp
C++
ARCC/generic.cpp
LukJA/ARCC
d4361cb5adfd166a1aa27779126f47a11c8de3ee
[ "MIT" ]
null
null
null
ARCC/generic.cpp
LukJA/ARCC
d4361cb5adfd166a1aa27779126f47a11c8de3ee
[ "MIT" ]
null
null
null
ARCC/generic.cpp
LukJA/ARCC
d4361cb5adfd166a1aa27779126f47a11c8de3ee
[ "MIT" ]
null
null
null
#include "pch.h" #include "generic.h" using namespace Platform; #include <vector> #include <codecvt> #include <string> std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; // -- for use in textblock to int long ToLongS(String^ str) { const wchar_t* begin = str->Data(); return std::wcstol(begin, nullptr, 10); } // -- for use in text to int long ToLong(std::string str) { return std::stoi(str, nullptr, 10); } // std string to platform string String^ toPlat(std::string str) { std::wstring wide = converter.from_bytes(str); //string to wstring return ref new String(wide.c_str()); //convert the wstring back to a platform } std::string toCstr(String^ str) { std::wstring wide = str->Data(); //string to wstring return converter.to_bytes(wide); //convert the wstring back to a platform }
22.108108
78
0.709046
[ "vector" ]
b6ae22d1c3e52626792e7cbee294a88522dcd652
6,964
cpp
C++
src/k2/dto/ControlPlaneOracle.cpp
jfunston/chogori-platform
e329e892411eeb2142c8d4b603944244d3c559d4
[ "MIT" ]
33
2020-05-16T10:12:05.000Z
2022-01-26T07:33:44.000Z
src/k2/dto/ControlPlaneOracle.cpp
jfunston/chogori-platform
e329e892411eeb2142c8d4b603944244d3c559d4
[ "MIT" ]
131
2020-05-18T21:39:40.000Z
2022-03-31T21:10:09.000Z
src/k2/dto/ControlPlaneOracle.cpp
jfunston/chogori-platform
e329e892411eeb2142c8d4b603944244d3c559d4
[ "MIT" ]
16
2020-06-02T02:56:01.000Z
2021-12-07T07:42:32.000Z
/* MIT License Copyright(c) 2020 Futurewei Cloud 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 "ControlPlaneOracle.h" namespace k2 { namespace dto { void Schema::setKeyFieldsByName(const std::vector<String>& keys, std::vector<uint32_t>& keyFields) { for (const String& keyName : keys) { bool found = false; for (size_t i = 0; i < fields.size(); ++i) { if (keyName == fields[i].name) { found = true; keyFields.push_back(i); break; } } K2ASSERT(log::dto, found, "failed to find field by name"); } } void Schema::setPartitionKeyFieldsByName(const std::vector<String>& keys) { setKeyFieldsByName(keys, partitionKeyFields); } void Schema::setRangeKeyFieldsByName(const std::vector<String>& keys) { setKeyFieldsByName(keys, rangeKeyFields); } // Checks if the schema itself is well-formed (e.g. field names are unique) // and returns a 400 status if not Status Schema::basicValidation() const { std::unordered_set<String> uniqueNames; for (const dto::SchemaField& field : fields) { auto [it, isUnique] = uniqueNames.insert(field.name); if (!isUnique) { return Statuses::S400_Bad_Request("Duplicated field name in schema"); } } if (partitionKeyFields.size() == 0) { K2LOG_W(log::dto, "Bad CreateSchemaRequest: No partitionKeyFields defined"); return Statuses::S400_Bad_Request("No partitionKeyFields defined"); } std::unordered_set<uint32_t> uniqueIndex; std::vector<bool> foundIndexes(partitionKeyFields.size() + rangeKeyFields.size(), false); uint32_t maxIndex = 0; for (uint32_t keyIndex : partitionKeyFields) { auto [it, isUnique] = uniqueIndex.insert(keyIndex); if (!isUnique) { return Statuses::S400_Bad_Request("Duplicated field in partitionKeys"); } if (keyIndex >= fields.size()) { K2LOG_W(log::dto, "Bad CreateSchemaRequest: partitionKeyField index out of bounds"); return Statuses::S400_Bad_Request("partitionKeyField index out of bounds"); } if (keyIndex >= foundIndexes.size()) { K2LOG_W(log::dto, "Bad CreateSchemaRequest: All key fields must precede all value fields"); return Statuses::S400_Bad_Request("All key fields must precede all value fields"); } foundIndexes[keyIndex] = true; maxIndex = std::max(maxIndex, keyIndex); } uniqueIndex.clear(); for (uint32_t keyIndex : rangeKeyFields) { auto [it, isUnique] = uniqueIndex.insert(keyIndex); if (!isUnique) { return Statuses::S400_Bad_Request("Duplicated field in partitionKeys"); } if (keyIndex >= fields.size()) { K2LOG_W(log::dto, "Bad CreateSchemaRequest: rangeKeyField index out of bounds"); return Statuses::S400_Bad_Request("rangeKeyField index out of bounds"); } if (keyIndex >= foundIndexes.size()) { K2LOG_W(log::dto, "Bad CreateSchemaRequest: All key fields must precede all value fields"); return Statuses::S400_Bad_Request("All key fields must precede all value fields"); } foundIndexes[keyIndex] = true; maxIndex = std::max(maxIndex, keyIndex); } for (uint32_t i = 0; i < maxIndex; ++i) { if (!foundIndexes[i]) { K2LOG_W(log::dto, "Bad CreateSchemaRequest: All key fields must precede all value fields"); return Statuses::S400_Bad_Request("All key fields must precede all value fields"); } } return Statuses::S200_OK("basic validation passed"); } // Used to make sure that the partition and range key definitions do not change between versions Status Schema::canUpgradeTo(const dto::Schema& other) const { if (partitionKeyFields.size() != other.partitionKeyFields.size()) { return Statuses::S409_Conflict("partitionKey fields of schema versions do not match"); } if (rangeKeyFields.size() != other.rangeKeyFields.size()) { return Statuses::S409_Conflict("rangeKey fields of schema versions do not match"); } // Key field names, types, and positions must remain invariant among versions so that // a read request can be constructed without regards to a particular version for (size_t i = 0; i < partitionKeyFields.size(); ++i) { uint32_t a_fieldIndex = partitionKeyFields[i]; const String& a_name = fields[a_fieldIndex].name; dto::FieldType a_type = fields[a_fieldIndex].type; uint32_t b_fieldIndex = other.partitionKeyFields[i]; if (a_fieldIndex != b_fieldIndex) { return Statuses::S409_Conflict("partitionKey fields of schema versions do not match"); } const String& b_name = other.fields[b_fieldIndex].name; dto::FieldType b_type = other.fields[b_fieldIndex].type; if (b_name != a_name || b_type != a_type) { return Statuses::S409_Conflict("partitionKey fields of schema versions do not match"); } } for (size_t i = 0; i < rangeKeyFields.size(); ++i) { uint32_t a_fieldIndex = rangeKeyFields[i]; const String& a_name = fields[a_fieldIndex].name; dto::FieldType a_type = fields[a_fieldIndex].type; uint32_t b_fieldIndex = other.rangeKeyFields[i]; if (a_fieldIndex != b_fieldIndex) { return Statuses::S409_Conflict("partitionKey fields of schema versions do not match"); } const String& b_name = other.fields[b_fieldIndex].name; dto::FieldType b_type = other.fields[b_fieldIndex].type; if (b_name != a_name || b_type != a_type) { return Statuses::S409_Conflict("rangeKey fields of schema versions do not match"); } } return Statuses::S200_OK("Upgrade compatible"); } } // namespace dto } // namespace k2
40.488372
408
0.666571
[ "vector" ]
b6aedc3162bc24162a5087fc2b18d9ec5d46edeb
3,095
hpp
C++
src/efscape/impl/RelogoWrapper.hpp
clinejc/efscape
ef8bbf272827c7b364aa02af33dc5d239f070e0b
[ "0BSD" ]
1
2019-07-29T07:44:13.000Z
2019-07-29T07:44:13.000Z
src/efscape/impl/RelogoWrapper.hpp
clinejc/efscape
ef8bbf272827c7b364aa02af33dc5d239f070e0b
[ "0BSD" ]
null
null
null
src/efscape/impl/RelogoWrapper.hpp
clinejc/efscape
ef8bbf272827c7b364aa02af33dc5d239f070e0b
[ "0BSD" ]
1
2019-07-11T10:49:48.000Z
2019-07-11T10:49:48.000Z
// __COPYRIGHT_START__ // Package Name : efscape // File Name : RelogoWrapper.hpp // Copyright (C) 2006-2018 Jon C. Cline // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. // __COPYRIGHT_END__ #ifndef EFSCAPE_IMPL_RELOGOWRAPPER_HPP #define EFSCAPE_IMPL_RELOGOWRAPPER_HPP // boost serialization definitions #include <boost/serialization/base_object.hpp> #include <boost/serialization/version.hpp> #include <efscape/impl/efscapelib.hpp> #include <relogo/SimulationRunnerPlus.h> #include <json/json.h> namespace efscape { namespace impl { /** * Provides an ADEVS wrapper template class for Repast HPC models. * <br><br> * Assumes that the wrapped model has implemented the following functions: * -# const repast::Properties& getProperties() * -# void setup(repast::Properties&) * -# Json::Value outputFunction() * * @author Jon Cline <clinej@stanfordalumni.org> * @version 0.0.1 created 28 Jan 2019, updated 29 Jan 2019 */ template <typename ObserverType, typename PatchType> class RelogoWrapper : public ATOMIC { friend class boost::serialization::access; public: RelogoWrapper(); RelogoWrapper(Json::Value aC_modelProps); virtual ~RelogoWrapper(); //------------------- // devs model methods //------------------- /// Internal transition function. void delta_int(); /// External transition function. void delta_ext(double e, const adevs::Bag<IO_Type> &xb); /// Confluent transition function. void delta_conf(const adevs::Bag<IO_Type> &xb); /// Output function. void output_func(adevs::Bag<IO_Type> &yb); /// Time advance function. double ta(); /// Output value garbage collection. void gc_output(adevs::Bag<IO_Type> &g); //----------------- // devs model ports //----------------- static const efscape::impl::PortType setup_in; private: void setup(std::string aC_propsFile); template <class Archive> void serialize(Archive &ar, const unsigned int version) const { // save parent class data ar &BOOST_SERIALIZATION_BASE_OBJECT_NVP(ATOMIC); } /** handle to Repast properties in JSON format */ Json::Value mC_modelProps; /** handle to Repast model */ std::unique_ptr< repast::relogo::SimulationRunnerPlus<ObserverType, PatchType> > mCp_model; }; // template class<> RelogoWrapper } // namespace impl } // namespace efscape #endif // #ifndef EFSCAPE_IMPL_RELOGOWRAPPER_HPP
30.048544
158
0.712763
[ "model" ]
b6b7f4fb06a73ce10a917e540dbf8e45531292f2
9,675
hpp
C++
src/include/Lexer.hpp
albertonl/alb
8779ed2f047d63eff2bc96b658b2659641364322
[ "MIT" ]
2
2019-06-08T16:47:22.000Z
2019-06-08T16:56:18.000Z
src/include/Lexer.hpp
albertonl/alb
8779ed2f047d63eff2bc96b658b2659641364322
[ "MIT" ]
2
2019-02-02T21:15:45.000Z
2019-06-10T08:23:09.000Z
src/include/Lexer.hpp
albertonl/alb
8779ed2f047d63eff2bc96b658b2659641364322
[ "MIT" ]
1
2019-06-08T17:23:55.000Z
2019-06-08T17:23:55.000Z
/* The ALB Programming Language Alb Developers Team (C) 2019 This software is distributed under the MIT license Visit https://github.com/albertonl/alb/LICENSE for further details */ #ifndef ALB_LEXER_HPP #define ALB_LEXER_HPP #include <cstdint> #include <vector> #include "Token.hpp" #include <stdexcept> namespace alb_lang { /** * Performs lexical analysis of input data (parsing the text). */ class Lexer { private: /** * Returns true if codepoint passed represents a valid whitespace character. * * Valid whitespace character codepoints are: * - U+0000 (NULL) * - U+0009 (tab) * - U+000A (LF) * - U+000B (VT) * - U+000C (FF) * - U+000D (CR) * - U+0020 (space) * - U+0085 (unicode NEXT LINE) * - U+00A0 (nbsp) * - U+1680 (Ogham space) * - U+2000 (en space, variant 1) * - U+2001 (em space, variant 1) * - U+2002 (en space, variant 2) * - U+2003 (em space, variant 2) * - U+2004 (one third of em space) * - U+2005 (one fourth of em space) * - U+2006 (one sixth of em space) * - U+2007 (figure space) * - U+2008 (punctuation space) * - U+2009 (thin space) * - U+200A (hair space) * - U+2028 (line separator) * - U+2029 (paragraph separator) * - U+202F (narrow nbsp) * - U+205F (medium mathspace) * - U+3000 (some other space) * - U+200B (zero width space) * - U+2060 (word joiner (zero width nbsp)) * - U+FEFF (deprecated zero width nbsp) * * Also, this method returns true for some technically non-whitespace * characters, which are however included if only just for fun: * - U+00B7 (interpunct - · ) * - U+237D (visual representation of nbsp - ⍽ ) * - U+2420 (symbol for space - ␠ ) * - U+2422 (symbol for blank - ␢ ) * - U+2423 (handwriting symbol for space - ␣ ) * * @param codepoint The unicode codepoint for which to check for whitespaceness. * @return true when the character is whitespace from the upper list */ static constexpr bool isCharacterWhitespace(uint32_t codepoint) noexcept ; /** * Returns true if codepoint passed represents a valid newline character. * * Valid newline character codepoints are: * - U+000A (LF) * - U+000B (VT) * - U+000C (FF) * - U+000D (CR) * - U+0085 (unicode NEXT LINE) * - U+2028 (line separator) * - U+2029 (paragraph separator) * * @param codepoint The unicode codepoint which to check * @return true when the character is newline from the upper list */ static constexpr bool isCharacterNewline(uint32_t codepoint) noexcept ; /** * Returns true if codepoint passed represents a character with special meaning in alb. * * These characters are all in the ASCII range, and specifically are: * - \c +*-/ for basic math operations * - \c = for assignments, also in \c == and variants for comparing * - \c (){}[] as ever useful brackets * - \c % for modulo operation * - \c ?: as "conditional operator" (also known as ternary operator) * - \c ;., for generic separating/chaining * - \c ^&|<>~ as bitwise operators * - \c ! for logical negation * - \c "' for marking strings * * @param codepoint The unicode codepoint for which to check for special meaning. * @return true when the character has special meaning assigned */ static constexpr bool isCharacterSpecialMeaning(uint32_t codepoint) noexcept ; /** * Returns next character as unicode codepoint from the block of input data. * @param utf8Data Block of UTF-8 input data. * @param currindex The index of the first byte of the next character * @return The next character as unicode codepoint */ static uint32_t getNextChar(unsigned char* utf8Data, uint64_t& currindex) noexcept(false); public: Lexer() = default; /** * Performs lexical analysis of input data in \c utf8Data, appending them to \c tokenList * @param utf8Data Pointer to the beginning of the block of data * @param dataSize Complete size of the data * @param tokenList Reference to vector to append the tokens to. */ static void tokenizeUTF8(char* utf8Data, uint64_t dataSize, std::vector<Token*>& tokenList) noexcept(false); }; constexpr bool Lexer::isCharacterWhitespace(uint32_t codepoint) noexcept { switch (codepoint) { case 0x0000: case 0x0009: case 0x000A: case 0x000B: case 0x000C: case 0x000D: case 0x0020: case 0x0085: case 0x00A0: case 0x1680: case 0x2000: case 0x2001: case 0x2002: case 0x2003: case 0x2006: case 0x2004: case 0x2005: case 0x2007: case 0x2008: case 0x2009: case 0x200A: case 0x2028: case 0x2029: case 0x202F: case 0x205F: case 0x3000: case 0x200B: case 0x2060: case 0xFEFF: case 0x00B7: case 0x237D: case 0x2420: case 0x2422: case 0x2423: return true; default: return false; } } constexpr bool Lexer::isCharacterNewline(uint32_t codepoint) noexcept { switch (codepoint) { case 0x000A: case 0x000B: case 0x000C: case 0x000D: case 0x0085: case 0x2028: case 0x2029: return true; default: return false; } } constexpr bool Lexer::isCharacterSpecialMeaning(uint32_t codepoint) noexcept { if (codepoint > 127) { // Character is not in ASCII range -> it is not a special meaning char return false; } switch ((uint8_t) codepoint) { case '+': case '*': case '-': case '/': case '=': case '(': case ')': case '{': case '}': case '[': case ']': case '%': case '?': case ':': case ';': case '.': case ',': case '^': case '&': case '|': case '<': case '>': case '~': case '!': case '"': case '\'': return true; default: return false; } } uint32_t Lexer::getNextChar(unsigned char *utf8Data, uint64_t &currindex) noexcept(false) { if (((utf8Data[currindex]) & 0b10000000u) == 0) { return utf8Data[currindex++]; } if ((utf8Data[currindex] & 0b11100000u) == 0b11000000) { const uint32_t firstByteBits = utf8Data[currindex++] & 0b00011111u; const uint32_t secondByteBits = utf8Data[currindex++] & 0b00111111u; return (firstByteBits << 6u) + secondByteBits; } if ((utf8Data[currindex] & 0b11110000u) == 0b11100000) { const uint32_t firstByteBits = utf8Data[currindex++] & 0b00001111u; const uint32_t secondByteBits = utf8Data[currindex++] & 0b00111111u; const uint32_t thirdByteBits = utf8Data[currindex++] & 0b00111111u; return (firstByteBits << 12u) + (secondByteBits << 6u) + thirdByteBits; } if ((utf8Data[currindex] &0b11111000u) == 0b11110000u) { const uint32_t firstByteBits = utf8Data[currindex++] & 0b00000111u; const uint32_t secondByteBits = utf8Data[currindex++] & 0b00111111u; const uint32_t thirdByteBits = utf8Data[currindex++] & 0b00111111u; const uint32_t fourthByteBits = utf8Data[currindex++] & 0b00111111u; return (firstByteBits << 18u) + (secondByteBits << 12u) + (thirdByteBits << 6u) + fourthByteBits; } throw std::runtime_error{"Invalid UTF-8 data."}; } void Lexer::tokenizeUTF8(char *utf8Data, uint64_t dataSize, std::vector<Token*> &tokenList) { uint64_t startindex=0, endindex= 0, currindex = 0; while (currindex < dataSize) { endindex = currindex - 1; uint32_t nextChar = getNextChar((unsigned char*)(utf8Data), currindex); if (isCharacterWhitespace(nextChar) || isCharacterSpecialMeaning((nextChar))) { if (!(endindex < startindex || endindex == UINT64_MAX)) { tokenList.push_back(new BasicToken{std::string{(char *) utf8Data + startindex, endindex - startindex + 1}}); } startindex = currindex; if (isCharacterSpecialMeaning(nextChar)) { // Handle comments in code if (nextChar == '/') { if (currindex < dataSize) { uint64_t tempCurrindex = currindex; uint32_t nextNextChar = getNextChar((unsigned char*)(utf8Data), tempCurrindex); if (nextNextChar == '/' || nextNextChar == '*') { getNextChar((unsigned char*)utf8Data, currindex); // To get currindex past nextNextChar while (currindex < dataSize) { uint32_t nextInCommentChar = getNextChar((unsigned char*)utf8Data, currindex); if (nextNextChar == '/' && isCharacterNewline(nextInCommentChar)) { break; } else if (nextNextChar == '*' && nextInCommentChar == '*') { uint64_t anotherTempCurrIndex = currindex; uint32_t nextNextInCommentChar = getNextChar((unsigned char*) utf8Data, anotherTempCurrIndex); if (nextNextInCommentChar == '/') { getNextChar((unsigned char*) utf8Data, currindex); // To get currindex past nextNextInCommentChar break; } } } startindex = currindex; continue; } } } tokenList.push_back(new BasicToken{std::string{(char)nextChar}}); } } } } } #endif //ALB_LEXER_HPP
33.710801
119
0.599276
[ "vector" ]
b6bae2bc02e9bb0c56ca4b9acbe210d9fea630b0
7,665
cpp
C++
src/race/src/central_controller2.cpp
young43/ISCC_2020
2a7187410bceca901bd87b753a91fd35b73ca036
[ "MIT" ]
8
2019-07-22T08:22:43.000Z
2020-12-09T06:25:14.000Z
src/race/src/central_controller2.cpp
yongbeomkwak/ISCC_2021
7e7e5a8a14b9ed88e1cfbe2ee585fe24e4701015
[ "MIT" ]
2
2019-07-13T16:30:16.000Z
2019-08-15T10:37:33.000Z
src/race/src/central_controller2.cpp
yongbeomkwak/ISCC_2021
7e7e5a8a14b9ed88e1cfbe2ee585fe24e4701015
[ "MIT" ]
5
2020-09-13T09:06:16.000Z
2021-06-19T02:31:23.000Z
#include <ros/ros.h> #include <race/lane_info.h> #include <nav_msgs/Odometry.h> #include <race/mode.h> #include <race/drive_values.h> #include <std_msgs/Float64.h> #include <std_msgs/Int32.h> #include <sensor_msgs/Imu.h> #include <obstacle_detector/Obstacles.h> #include <geometry_msgs/Point.h> #include <vector> #include <fstream> #include <cstring> #include <iostream> #include <cmath> #include <cstdlib> #include <mutex> #define _USE_MATH_DEFINES struct Point { double x; double y; Point() {x = 0; y = 0;} Point(double _x, double _y) : x(_x), y(_y) {} }; enum { BASE, STATIC_OBSTACLE_1, STATIC_OBSTACLE_2, }; double path_arrived_threshold = 2.0; double yaw_refresh_threshold = 1.0; int mode = BASE; int current_path_index = 0; std::vector<Point> path; bool is_path_set = false; Point current_position; Point rear_position; bool is_lane_detected = false; float yaw = 0.0; ros::Publisher drive_msg_pub; Point initial_position; Point prev_position; float front_heading = 0.0; float rear_heading = 0.0; double steering, throttle=3; float data_transform(float x, float in_min, float in_max, float out_min, float out_max) // 적외선 센서 데이터 변환 함수 { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } double cal_distance(const Point A, const Point B) { return sqrt((A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y)); } double getAngle(std::vector<Point> v1, std::vector<Point> v2) { double x1, y1, x2, y2; x1 = v1[1].x - v1[0].x; y1 = v1[1].y - v1[0].y; x2 = v2[1].x - v2[0].x; y2 = v2[1].y - v2[0].y; double u1 = sqrt(x1*x1 + y1*y1); double u2 = sqrt(x2*x2 + y2*y2); x1 /= u1; y1 /= u1; x2 /= u2; y2 /= u2; std::cout << "v1 : " << x1 << ' ' << y1 << std::endl; std::cout << "v2 : " << x2 << ' ' << y2 << std::endl; // std::cout << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << std::endl; // return asin((x1*y2-x2*y1)/(cal_distance(v2[0], v2[1]))) * 180.0 / M_PI; float ang1 = atan2(y1, x1) * 180.0 / M_PI; float ang2 = atan2(y2, x2) * 180.0 / M_PI; if(ang1 < 0) ang1 += 360; if(ang2 < 0) ang2 += 360; std::cout << "asin v1, v2 : " << ang1 << ' ' << ang2 << std::endl; if(ang1 - ang2 > 180) return (ang1 - ang2) - 360; if(ang1 - ang2 < -180) return 360 + (ang1 - ang2); } bool operator<(geometry_msgs::Point A, geometry_msgs::Point B) { if(A.x == B.x) { return A.y < B.y; } return A.x < B.x; } void set_path() { std::string HOME = std::getenv("HOME") ? std::getenv("HOME") : "."; std::ifstream infile(HOME+"/ISCC_2019/src/race/src/path/path_contest1.txt"); std::string line; float min_dis = 9999999; float x, y; while(infile >> x >> y) { path.push_back(Point(x, y)); std::cout.precision(11); std::cout << std::fixed << path.back().x << ' ' << path.back().y << std::endl; double cur_dis = cal_distance(path.back(), current_position); if(min_dis > cur_dis) { min_dis = cur_dis; current_path_index = path.size()-1; } } initial_position.x = current_position.x; initial_position.y = current_position.y; ROS_INFO("path initialized, index : %d, position : %f %f", current_path_index, current_position.x, current_position.y); is_path_set = true; } void imu_callback(const sensor_msgs::Imu::ConstPtr& msg) { yaw = msg->orientation.z; } void odom_front_callback(const nav_msgs::Odometry::ConstPtr& odom) { current_position.x = odom->pose.pose.position.x; current_position.y = odom->pose.pose.position.y; front_heading = odom->pose.pose.position.z; if(!is_path_set) { set_path(); } if(mode == BASE && is_path_set) { std::vector<Point> v1, v2; Point center_point; //(0,0) Point temp; // temp.x = 1*cos(front_heading); // temp.y = 1*sin(front_heading); temp.x = 1*cos(yaw*3.1415926535/180.0); temp.y = 1*sin(yaw*3.1415926535/180.0); // std::cout << "current_position : " << current_position.x << ' ' << current_position.y << std::endl; std::cout << "yaw : " << yaw << std::endl; // steering 계산 부분 v1.push_back(center_point); v1.push_back(temp); v2.push_back(current_position); v2.push_back(path[current_path_index+2]); // v2.push_back(path[current_path_index]); // v2.push_back(path[current_path_index+1]); // std::cout << "current_position : " << current_position.x << ' ' << current_position.y << std::endl; steering = getAngle(v1, v2); // drive msg publising 부분 race::drive_values drive_msg; throttle = data_transform(-abs(steering), -180, 0, 3, 8); drive_msg.throttle = (int)throttle; drive_msg.steering = (steering*5); // ROS_INFO("steering : %f", steering); std::cout << "steering : " << drive_msg.steering << std::endl; drive_msg_pub.publish(drive_msg); } else if(mode == STATIC_OBSTACLE_1) { race::drive_values drive_msg; drive_msg.throttle = (int)throttle; drive_msg.steering = (-steering*0.5); // ROS_INFO("steering : %f", steering); std::cout << "steering : " << drive_msg.steering << std::endl; drive_msg_pub.publish(drive_msg); } else if(mode == STATIC_OBSTACLE_2){ } std::cout << current_path_index << std::endl; if(cal_distance(current_position, path[current_path_index]) < path_arrived_threshold) current_path_index++; } void obstacle_callback(const obstacle_detector::Obstacles::ConstPtr& msg) { geometry_msgs::Point target_point; target_point.x = 100000; target_point.y = 100000; target_point.z = 0; for(int i = 0 ; i < msg->circles.size() ; i++) { // if(msg->circles[i].center < target_point) { // target_point = msg->circles[i].center; // } if(msg->circles[i].center.y < target_point.y) { target_point = msg->circles[i].center; } } Point center_point; Point y_axis; Point circle; y_axis.y = 1; circle.x = target_point.x; circle.y = target_point.y; ROS_INFO_STREAM("x = " << target_point.x << "y = " << target_point.y ) ; std::vector<Point> v1, v2; v1.push_back(center_point); v1.push_back(y_axis); v2.push_back(center_point); v2.push_back(circle); double angle = getAngle(v1, v2); steering = -angle-5; } void odom_rear_callback(const nav_msgs::Odometry::ConstPtr& odom) { rear_position.x = odom->pose.pose.position.x; rear_position.y = odom->pose.pose.position.y; rear_heading = odom->pose.pose.position.z; std::cout << "rear_position : " << rear_position.x << ' ' << rear_position.y << std::endl; } void lane_info_callback(const race::lane_info::ConstPtr& msg) { } void mode_callback(const race::mode::ConstPtr& msg) { mode = msg->mode; } int main(int argc, char** argv) { ros::init(argc, argv, "central_controller_node2"); ros::NodeHandle nh; ros::Subscriber odom_front_sub = nh.subscribe("odom_front", 1, odom_front_callback); ros::Subscriber odom_rear_sub = nh.subscribe("odom_rear", 1, odom_rear_callback); ros::Subscriber lane_info_sub = nh.subscribe("lane_info", 1, lane_info_callback); ros::Subscriber mode_sub = nh.subscribe("mode", 1, mode_callback); ros::Subscriber imu_sub = nh.subscribe("imu/data", 1, imu_callback); ros::Subscriber obstacle_sub = nh.subscribe("obstacles", 1, obstacle_callback); drive_msg_pub = nh.advertise<race::drive_values>("control_value", 1); ros::spin(); }
29.034091
123
0.614873
[ "vector" ]
b6d1da6e276b1261da8f386af652cd2faf941983
4,971
hpp
C++
python/plot/plotter.hpp
LevinJ/pypangolin
3ac794aff96c3db103ec2bbc298ab013eaf6f6e8
[ "MIT" ]
221
2018-01-06T12:29:12.000Z
2022-03-31T08:05:09.000Z
python/plot/plotter.hpp
LevinJ/pypangolin
3ac794aff96c3db103ec2bbc298ab013eaf6f6e8
[ "MIT" ]
39
2018-01-11T19:51:48.000Z
2022-03-24T00:48:12.000Z
python/plot/plotter.hpp
LevinJ/pypangolin
3ac794aff96c3db103ec2bbc298ab013eaf6f6e8
[ "MIT" ]
78
2018-01-06T12:14:51.000Z
2022-02-26T05:14:47.000Z
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pangolin/handler/handler.h> #include <pangolin/plot/plotter.h> #include "datalog.hpp" #include "range.hpp" namespace py = pybind11; using namespace pybind11::literals; namespace pangolin { struct Colour; void declarePlotter(py::module & m) { declareDataLog(m); declareRange(m); // py::class_<Colour>(m, "Colour") // .def(py::init<>()) // ; py::class_<Colour>(m, "Colour") .def_static("White", &Colour::White) .def_static("Black", &Colour::Black) .def_static("Red", &Colour::Red) .def_static("Green", &Colour::Green) .def_static("Blue", &Colour::Blue) .def_static("Unspecified", &Colour::Unspecified) .def(py::init<>()) .def(py::init<float, float, float, float>(), "red"_a, "green"_a, "blue"_a, "alpha"_a=1.0) // .def(py::init<float[4]>(), "rgba") .def("Get", &Colour::Get) .def("WithAlpha", &Colour::WithAlpha) .def_static("Hsv", &Colour::Hsv, "hue"_a, "sat"_a=1.0, "val"_a=1.0, "alpha"_a=1.0) ; py::enum_<DrawingMode>(m, "DrawingMode") .value("DrawingModePoints", DrawingMode::DrawingModePoints) .value("DrawingModeDashed", DrawingMode::DrawingModeDashed) .value("DrawingModeLine", DrawingMode::DrawingModeLine) .value("DrawingModeNone", DrawingMode::DrawingModeNone) .export_values() ; py::class_<Marker> cls_mk(m, "Marker"); py::enum_<Marker::Direction>(cls_mk, "Direction") .value("Horizontal", Marker::Direction::Horizontal) .value("Vertical", Marker::Direction::Vertical) .export_values() ; py::enum_<Marker::Equality>(cls_mk, "Equality") .value("LessThan", Marker::Equality::LessThan) .value("Equal", Marker::Equality::Equal) .value("GreaterThan", Marker::Equality::GreaterThan) .export_values() ; cls_mk.def(py::init<Marker::Direction, float, Marker::Equality, Colour>(), "d"_a, "value"_a, "leg"_a=Marker::Equality::Equal, "c"_a=Colour()); cls_mk.def(py::init<const XYRangef&, const Colour&>(), "range"_a, "c"_a=Colour()); cls_mk.def_readwrite("range", &Marker::range); cls_mk.def_readwrite("colour", &Marker::colour); py::class_<Plotter, View/*, Handler*/, std::shared_ptr<Plotter>>(m, "Plotter") .def(py::init<DataLog*, float, float, float, float, float, float, Plotter*, Plotter*>(), "default_log"_a, "left"_a, "right"_a=600, "bottom"_a=-1, "top"_a=1, "tickx"_a=30, "ticky"_a=0.5, "linked_plotter_x"_a=nullptr, "linked_plotter_y"_a=nullptr) .def("Render", &Plotter::Render) .def("GetSelection", &Plotter::GetSelection) .def("GetDefaultView", &Plotter::GetDefaultView) .def("SetDefaultView", &Plotter::SetDefaultView) .def("GetView", &Plotter::GetView) .def("SetView", &Plotter::SetView) .def("SetViewSmooth", &Plotter::SetViewSmooth) .def("ScrollView", &Plotter::ScrollView) .def("ScrollViewSmooth", &Plotter::ScrollViewSmooth) .def("ScaleView", &Plotter::ScaleView) .def("ScaleViewSmooth", &Plotter::ScaleViewSmooth) .def("ResetView", &Plotter::ResetView) .def("SetTicks", &Plotter::SetTicks) .def("Track", &Plotter::Track, "x"_a="$i", "y"_a="") .def("ToggleTracking", &Plotter::ToggleTracking) .def("Trigger", &Plotter::Trigger, "x"_a="$0", "edge"_a=-1, "value"_a=0.0) .def("ToggleTrigger", &Plotter::ToggleTrigger) .def("SetBackgroundColour", &Plotter::SetBackgroundColour) .def("SetAxisColour", &Plotter::SetAxisColour) .def("SetTickColour", &Plotter::SetTickColour) .def("ScreenToPlot", &Plotter::ScreenToPlot) .def("Keyboard", &Plotter::Keyboard) .def("Mouse", &Plotter::Mouse) .def("MouseMotion", &Plotter::MouseMotion) .def("PassiveMouseMotion", &Plotter::PassiveMouseMotion) .def("Special", &Plotter::Special) .def("ClearSeries", &Plotter::ClearSeries) .def("AddSeries", &Plotter::AddSeries, "x_expr"_a, "y_expr"_a, "mode"_a=DrawingModeLine, "colour"_a=Colour::Unspecified(), "title"_a="$y", "log"_a=nullptr) .def("PlotTitleFromExpr", &Plotter::PlotTitleFromExpr) .def("ClearMarkers", &Plotter::ClearMarkers) .def("AddMarker", (Marker& (Plotter::*) (Marker::Direction, float, Marker::Equality, Colour)) &Plotter::AddMarker, "d"_a, "value"_a, "leg"_a=Marker::Equal, "c"_a=Colour()) .def("AddMarker", (Marker& (Plotter::*) (const Marker&)) &Plotter::AddMarker) // .def("ClearImplicitPlots", &Plotter::ClearImplicitPlots) // .def("AddImplicitPlot", &Plotter::AddImplicitPlot) ; } }
36.822222
96
0.598873
[ "render" ]
b6d2a78a4b5358cf55a05428ef11da747419cc56
5,560
cpp
C++
src/modules/osg/generated_code/ArrayDispatchers.pypp.cpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
3
2017-04-20T09:11:47.000Z
2021-04-29T19:24:03.000Z
src/modules/osg/generated_code/ArrayDispatchers.pypp.cpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
null
null
null
src/modules/osg/generated_code/ArrayDispatchers.pypp.cpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
null
null
null
// This file has been generated by Py++. #include "boost/python.hpp" #include "wrap_osg.h" #include "wrap_referenced.h" #include "ArrayDispatchers.pypp.hpp" namespace bp = boost::python; void register_ArrayDispatchers_class(){ bp::class_< osg::ArrayDispatchers, bp::bases< osg::Referenced >, osg::ref_ptr< ::osg::ArrayDispatchers >, boost::noncopyable >( "ArrayDispatchers", "\n Helper class for managing the dispatch to OpenGL of various attribute arrays such as stored in osg::Geometry.\n", bp::init< >("\n Helper class for managing the dispatch to OpenGL of various attribute arrays such as stored in osg::Geometry.\n") ) .def( "activate" , (void ( ::osg::ArrayDispatchers::* )( unsigned int,::osg::AttributeDispatch * ) )( &::osg::ArrayDispatchers::activate ) , ( bp::arg("binding"), bp::arg("at") ) ) .def( "activateColorArray" , (void ( ::osg::ArrayDispatchers::* )( ::osg::Array * ) )( &::osg::ArrayDispatchers::activateColorArray ) , ( bp::arg("array") ) ) .def( "activateFogCoordArray" , (void ( ::osg::ArrayDispatchers::* )( ::osg::Array * ) )( &::osg::ArrayDispatchers::activateFogCoordArray ) , ( bp::arg("array") ) ) .def( "activateNormalArray" , (void ( ::osg::ArrayDispatchers::* )( ::osg::Array * ) )( &::osg::ArrayDispatchers::activateNormalArray ) , ( bp::arg("array") ) ) .def( "activateSecondaryColorArray" , (void ( ::osg::ArrayDispatchers::* )( ::osg::Array * ) )( &::osg::ArrayDispatchers::activateSecondaryColorArray ) , ( bp::arg("array") ) ) .def( "activateTexCoordArray" , (void ( ::osg::ArrayDispatchers::* )( unsigned int,::osg::Array * ) )( &::osg::ArrayDispatchers::activateTexCoordArray ) , ( bp::arg("unit"), bp::arg("array") ) ) .def( "activateVertexArray" , (void ( ::osg::ArrayDispatchers::* )( ::osg::Array * ) )( &::osg::ArrayDispatchers::activateVertexArray ) , ( bp::arg("array") ) ) .def( "activateVertexAttribArray" , (void ( ::osg::ArrayDispatchers::* )( unsigned int,::osg::Array * ) )( &::osg::ArrayDispatchers::activateVertexAttribArray ) , ( bp::arg("unit"), bp::arg("array") ) ) .def( "active" , (bool ( ::osg::ArrayDispatchers::* )( unsigned int ) const)( &::osg::ArrayDispatchers::active ) , ( bp::arg("binding") ) ) .def( "colorDispatcher" , (::osg::AttributeDispatch * ( ::osg::ArrayDispatchers::* )( ::osg::Array * ) )( &::osg::ArrayDispatchers::colorDispatcher ) , ( bp::arg("array") ) , bp::return_internal_reference< >() ) .def( "dispatch" , (void ( ::osg::ArrayDispatchers::* )( unsigned int,unsigned int ) )( &::osg::ArrayDispatchers::dispatch ) , ( bp::arg("binding"), bp::arg("index") ) ) .def( "fogCoordDispatcher" , (::osg::AttributeDispatch * ( ::osg::ArrayDispatchers::* )( ::osg::Array * ) )( &::osg::ArrayDispatchers::fogCoordDispatcher ) , ( bp::arg("array") ) , bp::return_internal_reference< >() ) .def( "getUseVertexAttribAlias" , (bool ( ::osg::ArrayDispatchers::* )( ) const)( &::osg::ArrayDispatchers::getUseVertexAttribAlias ) ) .def( "normalDispatcher" , (::osg::AttributeDispatch * ( ::osg::ArrayDispatchers::* )( ::osg::Array * ) )( &::osg::ArrayDispatchers::normalDispatcher ) , ( bp::arg("array") ) , bp::return_internal_reference< >() ) .def( "reset" , (void ( ::osg::ArrayDispatchers::* )( ) )( &::osg::ArrayDispatchers::reset ) ) .def( "secondaryColorDispatcher" , (::osg::AttributeDispatch * ( ::osg::ArrayDispatchers::* )( ::osg::Array * ) )( &::osg::ArrayDispatchers::secondaryColorDispatcher ) , ( bp::arg("array") ) , bp::return_internal_reference< >() ) .def( "setState" , (void ( ::osg::ArrayDispatchers::* )( ::osg::State * ) )( &::osg::ArrayDispatchers::setState ) , ( bp::arg("state") ) ) .def( "setUseVertexAttribAlias" , (void ( ::osg::ArrayDispatchers::* )( bool ) )( &::osg::ArrayDispatchers::setUseVertexAttribAlias ) , ( bp::arg("flag") ) ) .def( "texCoordDispatcher" , (::osg::AttributeDispatch * ( ::osg::ArrayDispatchers::* )( unsigned int,::osg::Array * ) )( &::osg::ArrayDispatchers::texCoordDispatcher ) , ( bp::arg("unit"), bp::arg("array") ) , bp::return_internal_reference< >() ) .def( "vertexAttribDispatcher" , (::osg::AttributeDispatch * ( ::osg::ArrayDispatchers::* )( unsigned int,::osg::Array * ) )( &::osg::ArrayDispatchers::vertexAttribDispatcher ) , ( bp::arg("unit"), bp::arg("array") ) , bp::return_internal_reference< >() ) .def( "vertexDispatcher" , (::osg::AttributeDispatch * ( ::osg::ArrayDispatchers::* )( ::osg::Array * ) )( &::osg::ArrayDispatchers::vertexDispatcher ) , ( bp::arg("array") ) , bp::return_internal_reference< >() ); }
53.461538
405
0.526799
[ "geometry" ]
b6d858489dc788abdc842035638ebc054dc7721d
13,477
cc
C++
gnuradio-3.7.13.4/gr-blocks/lib/file_meta_sink_impl.cc
v1259397/cosmic-gnuradio
64c149520ac6a7d44179c3f4a38f38add45dd5dc
[ "BSD-3-Clause" ]
1
2021-03-09T07:32:37.000Z
2021-03-09T07:32:37.000Z
gnuradio-3.7.13.4/gr-blocks/lib/file_meta_sink_impl.cc
v1259397/cosmic-gnuradio
64c149520ac6a7d44179c3f4a38f38add45dd5dc
[ "BSD-3-Clause" ]
null
null
null
gnuradio-3.7.13.4/gr-blocks/lib/file_meta_sink_impl.cc
v1259397/cosmic-gnuradio
64c149520ac6a7d44179c3f4a38f38add45dd5dc
[ "BSD-3-Clause" ]
null
null
null
/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio 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 GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "file_meta_sink_impl.h" #include <gnuradio/io_signature.h> #include <cstdio> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdexcept> #include <stdio.h> // win32 (mingw/msvc) specific #ifdef HAVE_IO_H #include <io.h> #endif #ifdef O_BINARY #define OUR_O_BINARY O_BINARY #else #define OUR_O_BINARY 0 #endif // should be handled via configure #ifdef O_LARGEFILE #define OUR_O_LARGEFILE O_LARGEFILE #else #define OUR_O_LARGEFILE 0 #endif namespace gr { namespace blocks { file_meta_sink::sptr file_meta_sink::make(size_t itemsize, const std::string &filename, double samp_rate, double relative_rate, gr_file_types type, bool complex, size_t max_segment_size, const std::string &extra_dict, bool detached_header) { return gnuradio::get_initial_sptr (new file_meta_sink_impl(itemsize, filename, samp_rate, relative_rate, type, complex, max_segment_size, extra_dict, detached_header)); } file_meta_sink_impl::file_meta_sink_impl(size_t itemsize, const std::string &filename, double samp_rate, double relative_rate, gr_file_types type, bool complex, size_t max_segment_size, const std::string &extra_dict, bool detached_header) : sync_block("file_meta_sink", io_signature::make(1, 1, itemsize), io_signature::make(0, 0, 0)), d_itemsize(itemsize), d_samp_rate(samp_rate), d_relative_rate(relative_rate), d_max_seg_size(max_segment_size), d_total_seg_size(0), d_updated(false), d_unbuffered(false) { d_fp = 0; d_new_fp = 0; d_hdr_fp = 0; d_new_hdr_fp = 0; if(detached_header == true) d_state = STATE_DETACHED; else d_state = STATE_INLINE; if(!open(filename)) throw std::runtime_error("file_meta_sink: can't open file\n"); pmt::pmt_t timestamp = pmt::make_tuple(pmt::from_uint64(0), pmt::from_double(0)); // handle extra dictionary d_extra = pmt::make_dict(); if(extra_dict.size() > 0) { pmt::pmt_t extras = pmt::deserialize_str(extra_dict); pmt::pmt_t keys = pmt::dict_keys(extras); pmt::pmt_t vals = pmt::dict_values(extras); size_t nitems = pmt::length(keys); for(size_t i = 0; i < nitems; i++) { d_extra = pmt::dict_add(d_extra, pmt::nth(i, keys), pmt::nth(i, vals)); } } d_extra_size = pmt::serialize_str(d_extra).size(); d_header = pmt::make_dict(); d_header = pmt::dict_add(d_header, pmt::mp("version"), pmt::mp(METADATA_VERSION)); d_header = pmt::dict_add(d_header, pmt::mp("rx_rate"), pmt::mp(samp_rate)); d_header = pmt::dict_add(d_header, pmt::mp("rx_time"), timestamp); d_header = pmt::dict_add(d_header, pmt::mp("size"), pmt::from_long(d_itemsize)); d_header = pmt::dict_add(d_header, pmt::mp("type"), pmt::from_long(type)); d_header = pmt::dict_add(d_header, pmt::mp("cplx"), complex ? pmt::PMT_T : pmt::PMT_F); d_header = pmt::dict_add(d_header, pmt::mp("strt"), pmt::from_uint64(METADATA_HEADER_SIZE+d_extra_size)); d_header = pmt::dict_add(d_header, mp("bytes"), pmt::from_uint64(0)); do_update(); if(d_state == STATE_DETACHED) write_header(d_hdr_fp, d_header, d_extra); else write_header(d_fp, d_header, d_extra); } file_meta_sink_impl::~file_meta_sink_impl() { close(); } bool file_meta_sink_impl::open(const std::string &filename) { bool ret = true; if(d_state == STATE_DETACHED) { std::string s = filename + ".hdr"; ret = _open(&d_new_hdr_fp, s.c_str()); } ret = ret && _open(&d_new_fp, filename.c_str()); d_updated = true; return ret; } bool file_meta_sink_impl::_open(FILE **fp, const char *filename) { gr::thread::scoped_lock guard(d_setlock); // hold mutex for duration of this function bool ret = true; int fd; if((fd = ::open(filename, O_WRONLY|O_CREAT|O_TRUNC|OUR_O_LARGEFILE|OUR_O_BINARY, 0664)) < 0){ perror(filename); return false; } if(*fp) { // if we've already got a new one open, close it fclose(*fp); fp = 0; } if((*fp = fdopen(fd, "wb")) == NULL) { perror(filename); ::close(fd); // don't leak file descriptor if fdopen fails. } ret = fp != 0; return ret; } void file_meta_sink_impl::close() { gr::thread::scoped_lock guard(d_setlock); // hold mutex for duration of this function update_last_header(); if(d_state == STATE_DETACHED) { if(d_new_hdr_fp) { fclose(d_new_hdr_fp); d_new_hdr_fp = 0; } } if(d_new_fp) { fclose(d_new_fp); d_new_fp = 0; } d_updated = true; if (d_fp) { fclose(d_fp); d_fp = 0; } if (d_state == STATE_DETACHED) { if (d_hdr_fp) { fclose(d_hdr_fp); d_hdr_fp = 0; } } } void file_meta_sink_impl::do_update() { if(d_updated) { gr::thread::scoped_lock guard(d_setlock); // hold mutex for duration of this block if(d_state == STATE_DETACHED) { if(d_hdr_fp) fclose(d_hdr_fp); d_hdr_fp = d_new_hdr_fp; // install new file pointer d_new_hdr_fp = 0; } if(d_fp) fclose(d_fp); d_fp = d_new_fp; // install new file pointer d_new_fp = 0; d_updated = false; } } void file_meta_sink_impl::write_header(FILE *fp, pmt::pmt_t header, pmt::pmt_t extra) { std::string header_str = pmt::serialize_str(header); std::string extra_str = pmt::serialize_str(extra); if((header_str.size() != METADATA_HEADER_SIZE) && (extra_str.size() != d_extra_size)) throw std::runtime_error("file_meta_sink: header or extras is wrong size.\n"); size_t nwritten = 0; while(nwritten < header_str.size()) { std::string sub = header_str.substr(nwritten); int count = fwrite(sub.c_str(), sizeof(char), sub.size(), fp); nwritten += count; if((count == 0) && (ferror(fp))) { fclose(fp); throw std::runtime_error("file_meta_sink: error writing header to file.\n"); } } nwritten = 0; while(nwritten < extra_str.size()) { std::string sub = extra_str.substr(nwritten); int count = fwrite(sub.c_str(), sizeof(char), sub.size(), fp); nwritten += count; if((count == 0) && (ferror(fp))) { fclose(fp); throw std::runtime_error("file_meta_sink: error writing extra to file.\n"); } } fflush(fp); } void file_meta_sink_impl::update_header(pmt::pmt_t key, pmt::pmt_t value) { // Special handling caveat to transform rate from radio source into // the rate at this sink. if(pmt::eq(key, mp("rx_rate"))) { d_samp_rate = pmt::to_double(value); value = pmt::from_double(d_samp_rate*d_relative_rate); } // If the tag is not part of the standard header, we put it into the // extra data, which either updates the current dictionary or adds a // new item. if(pmt::dict_has_key(d_header, key)) { d_header = pmt::dict_add(d_header, key, value); } else { d_extra = pmt::dict_add(d_extra, key, value); d_extra_size = pmt::serialize_str(d_extra).size(); } } void file_meta_sink_impl::update_last_header() { if(d_state == STATE_DETACHED) { if (d_hdr_fp) update_last_header_detached(); } else { if(d_fp) update_last_header_inline(); } } void file_meta_sink_impl::update_last_header_inline() { // Update the last header info with the number of samples this // block represents. size_t hdrlen = pmt::to_uint64(pmt::dict_ref(d_header, mp("strt"), pmt::PMT_NIL)); size_t seg_size = d_itemsize*d_total_seg_size; pmt::pmt_t s = pmt::from_uint64(seg_size); update_header(mp("bytes"), s); update_header(mp("strt"), pmt::from_uint64(METADATA_HEADER_SIZE+d_extra_size)); fseek(d_fp, -seg_size-hdrlen, SEEK_CUR); write_header(d_fp, d_header, d_extra); fseek(d_fp, seg_size, SEEK_CUR); } void file_meta_sink_impl::update_last_header_detached() { // Update the last header info with the number of samples this // block represents. size_t hdrlen = pmt::to_uint64(pmt::dict_ref(d_header, mp("strt"), pmt::PMT_NIL)); size_t seg_size = d_itemsize*d_total_seg_size; pmt::pmt_t s = pmt::from_uint64(seg_size); update_header(mp("bytes"), s); update_header(mp("strt"), pmt::from_uint64(METADATA_HEADER_SIZE+d_extra_size)); fseek(d_hdr_fp, -hdrlen, SEEK_CUR); write_header(d_hdr_fp, d_header, d_extra); } void file_meta_sink_impl::write_and_update() { // New header, so set current size of chunk to 0 and start of chunk // based on current index + header size. //uint64_t loc = get_last_header_loc(); pmt::pmt_t s = pmt::from_uint64(0); update_header(mp("bytes"), s); // If we have multiple tags on the same offset, this makes // sure we just overwrite the same header each time instead // of creating a new header per tag. s = pmt::from_uint64(METADATA_HEADER_SIZE + d_extra_size); update_header(mp("strt"), s); if(d_state == STATE_DETACHED) write_header(d_hdr_fp, d_header, d_extra); else write_header(d_fp, d_header, d_extra); } void file_meta_sink_impl::update_rx_time() { pmt::pmt_t rx_time = pmt::string_to_symbol("rx_time"); pmt::pmt_t r = pmt::dict_ref(d_header, rx_time, pmt::PMT_NIL); uint64_t secs = pmt::to_uint64(pmt::tuple_ref(r, 0)); double fracs = pmt::to_double(pmt::tuple_ref(r, 1)); double diff = d_total_seg_size / (d_samp_rate*d_relative_rate); //std::cerr << "old secs: " << secs << std::endl; //std::cerr << "old fracs: " << fracs << std::endl; //std::cerr << "seg size: " << d_total_seg_size << std::endl; //std::cerr << "diff: " << diff << std::endl; fracs += diff; uint64_t new_secs = static_cast<uint64_t>(fracs); secs += new_secs; fracs -= new_secs; //std::cerr << "new secs: " << secs << std::endl; //std::cerr << "new fracs: " << fracs << std::endl << std::endl; r = pmt::make_tuple(pmt::from_uint64(secs), pmt::from_double(fracs)); d_header = pmt::dict_add(d_header, rx_time, r); } int file_meta_sink_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { char *inbuf = (char*)input_items[0]; int nwritten = 0; do_update(); // update d_fp is reqd if(!d_fp) return noutput_items; // drop output on the floor uint64_t abs_N = nitems_read(0); uint64_t end_N = abs_N + (uint64_t)(noutput_items); std::vector<tag_t> all_tags; get_tags_in_range(all_tags, 0, abs_N, end_N); std::vector<tag_t>::iterator itr; for(itr = all_tags.begin(); itr != all_tags.end(); itr++) { int item_offset = (int)(itr->offset - abs_N); // Write date to file up to the next tag location while(nwritten < item_offset) { size_t towrite = std::min(d_max_seg_size - d_total_seg_size, (size_t)(item_offset - nwritten)); int count = fwrite(inbuf, d_itemsize, towrite, d_fp); if(count == 0) // FIXME add error handling break; nwritten += count; inbuf += count * d_itemsize; d_total_seg_size += count; // Only add a new header if we are not at the position of the // next tag if((d_total_seg_size == d_max_seg_size) && (nwritten < item_offset)) { update_last_header(); update_rx_time(); write_and_update(); d_total_seg_size = 0; } } if(d_total_seg_size > 0) { update_last_header(); update_header(itr->key, itr->value); write_and_update(); d_total_seg_size = 0; } else { update_header(itr->key, itr->value); update_last_header(); } } // Finish up the rest of the data after tags while(nwritten < noutput_items) { size_t towrite = std::min(d_max_seg_size - d_total_seg_size, (size_t)(noutput_items - nwritten)); int count = fwrite(inbuf, d_itemsize, towrite, d_fp); if(count == 0) // FIXME add error handling break; nwritten += count; inbuf += count * d_itemsize; d_total_seg_size += count; if(d_total_seg_size == d_max_seg_size) { update_last_header(); update_rx_time(); write_and_update(); d_total_seg_size = 0; } } if(d_unbuffered) fflush(d_fp); return nwritten; } } /* namespace blocks */ } /* namespace gr */
28.613588
111
0.64176
[ "vector", "transform" ]
b6dbcab3e116b97addbf17f5899f0853b68b0542
24,082
cpp
C++
dbus_interface.cpp
kode54/wayfire-dbus
f360a10554871affa8cc8e2931531c1d906a0b0f
[ "MIT" ]
2
2020-07-04T19:23:57.000Z
2020-07-26T09:50:00.000Z
dbus_interface.cpp
kode54/wayfire-dbus
f360a10554871affa8cc8e2931531c1d906a0b0f
[ "MIT" ]
1
2020-07-26T08:35:18.000Z
2020-07-26T08:35:18.000Z
dbus_interface.cpp
kode54/wayfire-dbus
f360a10554871affa8cc8e2931531c1d906a0b0f
[ "MIT" ]
2
2020-07-05T04:54:03.000Z
2020-07-26T07:49:00.000Z
extern "C" { #include <gio/gio.h> #include <sys/socket.h> #include <sys/types.h> }; //these are in wf-utils //#include <wayfire/action/action.hpp> //#include <wayfire/action/action_interface.hpp> #include <iostream> #include <string> #include <charconv> #include <algorithm> #include <cmath> #include <linux/input.h> #include <wayfire/singleton-plugin.hpp> #include <wayfire/output.hpp> #include <wayfire/output-layout.hpp> #include <wayfire/workspace-manager.hpp> #include <wayfire/plugins/common/view-change-viewport-signal.hpp> #include <wayfire/core.hpp> #include <wayfire/util/log.hpp> #include <wayfire/option-wrapper.hpp> #include <wayfire/signal-definitions.hpp> #include <wayfire/view.hpp> #include <wayfire/plugin.hpp> #include <wayfire/output.hpp> #include <wayfire/core.hpp> #include <wayfire/view.hpp> #include <wayfire/util/duration.hpp> #include <wayfire/workspace-manager.hpp> #include <wayfire/render-manager.hpp> #include <wayfire/compositor-view.hpp> #include <wayfire/output-layout.hpp> #include <wayfire/debug.hpp> #include <wayfire/util.hpp> #include <wayfire/input-device.hpp> #include <wayfire/signal-definitions.hpp> #include "dbus_interface_backend.cpp" class dbus_interface_t { wf::option_wrapper_t<std::string> test_string{"dbus_interface/test-string"}; public: void constrain_pointer(const bool constrain) { return; } dbus_interface_t() { /************* Connect all signals for already existing objects *************/ for (wf::output_t *wf_output : wf_outputs) { wf_output->connect_signal("view-mapped", &output_view_added); wf_output->connect_signal("output-configuration-changed", &output_configuration_changed); wf_output->connect_signal("view-minimize-request", &output_view_minimized); wf_output->connect_signal("view-tile-request", &output_view_maximized); wf_output->connect_signal("view-move-request", &output_view_moving); wf_output->connect_signal("view-resize-request", &output_view_resizing); wf_output->connect_signal("view-change-viewport", &view_workspaces_changed); ///////////// wf_output->connect_signal("set-workspace-request", // &output_workspace_changed); wf_output->connect_signal("viewport-changed", &output_workspace_changed); wf_output->connect_signal("view-focused", &output_view_focus_changed); wf_output->connect_signal("view-fullscreen-request", &view_fullscreen_changed); wf_output->connect_signal("view-self-request-focus", &view_self_request_focus); LOG(wf::log::LOG_LEVEL_ERROR, "output connected "); connected_wf_outputs.insert(wf_output); // nonstd::observer_ptr<wf::sublayer_t> sticky_layer; // sticky_layer = wf_output->workspace->create_sublayer(wf::LAYER_WORKSPACE, // wf::SUBLAYER_DOCKED_ABOVE); // sticky_layers.push_back(sticky_layer); } LOG(wf::log::LOG_LEVEL_ERROR, "output count: " + std::to_string(wf::get_core().output_layout->get_outputs().size())); for (wayfire_view m_view : wf::get_core().get_all_views()) { m_view->connect_signal("app-id-changed", &view_app_id_changed); m_view->connect_signal("title-changed", &view_title_changed); m_view->connect_signal("geometry-changed", &view_geometry_changed); m_view->connect_signal("unmapped", &view_closed); m_view->connect_signal("tiled", &view_tiled); // m_view->connect_signal("fullscreen", &view_fullscreened); // this->emit_signal("decoration-state-updated", &data); // view->emit_signal("mapped", &data); // emit_signal("unmapped", &data); // emit_signal("disappeared", &data); // emit_signal("pre-unmapped", &data); } wf::get_core().connect_signal("view-move-to-output", &view_output_move_requested); wf::get_core().connect_signal("view-moved-to-output", &view_output_moved); // wf::get_core().output_layout->connect_signal("configuration-changed", &output_layout_configuration_changed); wf::get_core().output_layout->connect_signal("output-added", &output_layout_output_added); wf::get_core().output_layout->connect_signal("output-removed", &output_layout_output_removed); wf::get_core().connect_signal("pointer_button", &pointer_button_signal); wf::get_core().connect_signal("tablet_button", &tablet_button_signal); /************* LOAD DBUS SERVICE THREAD *************/ // g_main_context_push_thread_default(wf_context); // GMainContext *wwf_context = g_main_context_new(); //the end of the attached source needs to quit the event loop // wf_context = g_main_context_new(); // wf_event_loop = g_main_loop_new(wf_context, FALSE); dbus_context = g_main_context_new(); g_thread_new("dbus_thread", dbus_thread_exec_function, g_main_context_ref(dbus_context)); g_main_context_invoke_full(dbus_context, G_PRIORITY_DEFAULT, //int priority reinterpret_cast<GSourceFunc>(acquire_bus), nullptr, //data to pass nullptr); } ~dbus_interface_t() { LOG(wf::log::LOG_LEVEL_ERROR, "DBUS UNLOAD", "DBUS PLUGIN", 42); // for (int i = sticky_layers.size(); i -- > 0; ) // { // output->workspace->destroy_sublayer(sticky_layer); // } // for (int i = wf_outputs.size(); i-- > 0;) // { // wf::output_t *output = wf_outputs[i]; // output->workspace->destroy_sublayer(sticky_layers[i]); // } g_bus_unown_name(owner_id); g_main_loop_quit(dbus_event_loop); g_dbus_node_info_unref(introspection_data); } wf::signal_connection_t pointer_button_signal{[=](wf::signal_data_t *data) { LOG(wf::log::LOG_LEVEL_ERROR, "Some input signal:"); // nonstd::observer_ptr<input_event_signal> device; // device = static_cast<nonstd::observer_ptr<input_event_signal>>(data); LOG(wf::log::LOG_LEVEL_ERROR, "Some input signal casted:"); // GVariant *signal_data = g_variant_new("(u)", m_view->get_id()); // g_variant_ref(signal_data); bus_emit_signal("pointer_clicked", nullptr); }}; wf::signal_connection_t tablet_button_signal{[=](wf::signal_data_t *data) { LOG(wf::log::LOG_LEVEL_ERROR, "Some tablet_button_signal signal:"); bus_emit_signal("tablet_touched", nullptr); // LOG(wf::log::LOG_LEVEL_ERROR, "Some tablet_button_signal signal casted:"); }}; wf::signal_connection_t dbus_activation_test{[=](wf::signal_data_t *data) { LOG(wf::log::LOG_LEVEL_ERROR, "dbus_activation_test"); // LOG(wf::log::LOG_LEVEL_ERROR, "Some tablet_button_signal signal casted:"); }}; wf::signal_connection_t output_view_added{[=](wf::signal_data_t *data) { wayfire_view m_view = get_signaled_view(data); if (m_view == nullptr) { LOG(wf::log::LOG_LEVEL_ERROR, "WAYFIRE BUG: ", "output_view_added but signaled view is nullptr"); return; } GVariant *signal_data = g_variant_new("(u)", m_view->get_id()); g_variant_ref(signal_data); bus_emit_signal("view_added", signal_data); m_view->connect_signal("app-id-changed", &view_app_id_changed); m_view->connect_signal("title-changed", &view_title_changed); m_view->connect_signal("geometry-changed", &view_geometry_changed); m_view->connect_signal("unmapped", &view_closed); m_view->connect_signal("tiled", &view_tiled); //wf_gtk_shell s = wf::get_core().gtk_shell; // m_view->connect_signal("fullscreen", &view_fullscreened); // wf::get_core().get_active_output()->wor // wf::get_core() // grab_interface->name = "minimize"; // grab_interface->capabilities = wf::CAPABILITY_MANAGE_DESKTOP; //xdotool // wf::get_core().warp_cursor //for emit click //you could try to simulate a wlr event //shouldn't be too hard //for example, there's the virtual-pointer protocol so it is possible to have virtual devices, you can then simulate everything you want // wayfire's architecture is that plugins rely on each other as little as possible, so currently there are very few signals between them // tux2020 the thing is for example, if I want to trigger expo plugin // I will now have to change the expo plugin // at some point I may want to trigger a different plugin via dbus // than I have to change that plugin // ammen99_ I think that in this particular case, what we are missing is activating an activator binding programmatically // which is indeed something we could add // because activator bindings can be activated by just about anything // tux2020 but, any application that is focused would also get this binding // ammen99_ nooooo // activator binding can be triggered by different sources // so you could add a virtual source for activator bindings // tux2020 I guess this is the same what I mean that // than* // ammen99_ yes but it works only for activator bindings // you can't start the move plugin for example, because it does require a pointer button }}; wf::signal_connection_t view_closed{[=](wf::signal_data_t *data) { wayfire_view m_view = get_signaled_view(data); if (m_view == nullptr) { LOG(wf::log::LOG_LEVEL_ERROR, "WAYFIRE BUG: ", "view_closed but signaled view is nullptr"); return; } GVariant *signal_data = g_variant_new("(u)", m_view->get_id()); g_variant_ref(signal_data); bus_emit_signal("view_closed", signal_data); }}; wf::signal_connection_t view_app_id_changed{[=](wf::signal_data_t *data) { wayfire_view m_view = get_signaled_view(data); if (m_view == nullptr) { LOG(wf::log::LOG_LEVEL_ERROR, "WAYFIRE BUG: ", "view_app_id_changed but signaled view is nullptr"); return; } GVariant *signal_data = g_variant_new("(us)", m_view->get_id(), m_view->get_app_id().c_str()); g_variant_ref(signal_data); bus_emit_signal("view_app_id_changed", signal_data); LOG(wf::log::LOG_LEVEL_ERROR, "view_app_id_changed: " + m_view->get_app_id() + " on " + m_view->get_output()->to_string(), "DBUS PLUGIN", 32); }}; wf::signal_connection_t view_title_changed{[=](wf::signal_data_t *data) { wayfire_view m_view = get_signaled_view(data); if (m_view == nullptr) { LOG(wf::log::LOG_LEVEL_ERROR, "WAYFIRE BUG: ", "view_title_changed but signaled view is nullptr"); return; } GVariant *signal_data = g_variant_new("(us)", m_view->get_id(), m_view->get_title().c_str()); g_variant_ref(signal_data); bus_emit_signal("view_title_changed", signal_data); LOG(wf::log::LOG_LEVEL_ERROR, "view_title_changed: " + m_view->get_app_id() + " on " + m_view->get_title(), "DBUS PLUGIN", 32); }}; wf::signal_connection_t view_fullscreen_changed{[=](wf::signal_data_t *data) { LOG(wf::log::LOG_LEVEL_ERROR, "view_state_changed: view_fullscreened"); wf::view_fullscreen_signal *signal = static_cast<wf::view_fullscreen_signal *>(data); wayfire_view m_view = signal->view; GVariant *signal_data = g_variant_new("(ub)", m_view->get_id(), signal->state); g_variant_ref(signal_data); bus_emit_signal("view_fullscreen_changed", signal_data); }}; wf::signal_connection_t view_geometry_changed{[=](wf::signal_data_t *data) { // wayfire_view closed_view = get_signaled_view(data); // LOG(wf::log::LOG_LEVEL_ERROR, "geometry_changed VIEW: " + closed_view->get_app_id() + " on " + closed_view->get_output()->to_string(), "DBUS PLUGIN", 32); GVariant *signal_data = g_variant_new("(s)", "test"); g_variant_ref(signal_data); bus_emit_signal("view_geometry_changed", signal_data); }}; wf::signal_connection_t view_tiled{[=](wf::signal_data_t *data) { // LOG(wf::log::LOG_LEVEL_ERROR, "tiled VIEW: ", "DBUS PLUGIN", 32); GVariant *signal_data = g_variant_new("(s)", "test"); g_variant_ref(signal_data); bus_emit_signal("view_tiling_changed", signal_data); }}; wf::signal_connection_t view_output_moved{[=](wf::signal_data_t *data) { LOG(wf::log::LOG_LEVEL_ERROR, "view_output_moved: ", "DBUS PLUGIN"); wf::view_pre_moved_to_output_signal *signal = static_cast<wf::view_pre_moved_to_output_signal *>(data); wayfire_view view = signal->view; wf::output_t *old_output = signal->old_output; wf::output_t *new_output = signal->new_output; GVariant *signal_data = g_variant_new("(uuu)", view->get_id(), old_output->get_id(), new_output->get_id()); g_variant_ref(signal_data); bus_emit_signal("view_output_moved", signal_data); }}; wf::signal_connection_t view_output_move_requested{[=](wf::signal_data_t *data) { // See force fullscreen LOG(wf::log::LOG_LEVEL_ERROR, "output_changed not connected signal may cause crash?"); // no one listens // GVariant *signal_data = g_variant_new("(uuu)", view->get_id(), // old_output->get_id(), // new_output->get_id()); // g_variant_ref(signal_data); // bus_emit_signal("view_output_move_requested", signal_data); }}; //******************************Output Slots***************************// wf::signal_connection_t output_configuration_changed{[=](wf::signal_data_t *data) { LOG(wf::log::LOG_LEVEL_ERROR, "output_configuration_changed VIEW: ", "DBUS PLUGIN", 32); }}; wf::signal_connection_t view_workspaces_changed{[=](wf::signal_data_t *data) { LOG(wf::log::LOG_LEVEL_ERROR, "view viewport_changed : ", "DBUS PLUGIN"); view_change_viewport_signal *signal = static_cast<view_change_viewport_signal *>(data); wayfire_view view = signal->view; /**************************************************************** * It it useless to take signal from and to as they only condier * One workspace for to and from * though a user may put in the square of 4 ****************************************************************/ GVariant *signal_data; signal_data = g_variant_new("(u)", view->get_id()); g_variant_ref(signal_data); bus_emit_signal("view_workspaces_changed", signal_data); }}; wf::signal_connection_t output_workspace_changed{[=](wf::signal_data_t *data) { wf::workspace_changed_signal *signal = static_cast<wf::workspace_changed_signal *>(data); int newHorizontalWorkspace = signal->new_viewport.x; int newVerticalWorkspace = signal->new_viewport.y; wf::output_t *output = signal->output; GVariant *signal_data = g_variant_new("(uii)", output->get_id(), newHorizontalWorkspace, newVerticalWorkspace); g_variant_ref(signal_data); bus_emit_signal("output_workspace_changed", signal_data); }}; wf::signal_connection_t output_view_maximized{[=](wf::signal_data_t *data) { LOG(wf::log::LOG_LEVEL_ERROR, "view_state_changed: output_view_minimized"); wf::view_tile_request_signal *signal = static_cast<wf::view_tile_request_signal *>(data); wayfire_view m_view = signal->view; const bool maximized = (signal->edges == wf::TILED_EDGES_ALL); GVariant *signal_data = g_variant_new("(ub)", m_view->get_id(), maximized); g_variant_ref(signal_data); bus_emit_signal("view_maximized_changed", signal_data); }}; wf::signal_connection_t output_view_minimized{[=](wf::signal_data_t *data) { LOG(wf::log::LOG_LEVEL_ERROR, "view_state_changed: output_view_minimized"); wf::view_minimize_request_signal *signal = static_cast<wf::view_minimize_request_signal *>(data); wayfire_view m_view = signal->view; const bool minimized = signal->state; GVariant *signal_data = g_variant_new("(ub)", m_view->get_id(), minimized); g_variant_ref(signal_data); bus_emit_signal("view_minimized_changed", signal_data); }}; wf::signal_connection_t output_view_focus_changed{[=](wf::signal_data_t *data) { wf::focus_view_signal *signal = static_cast<wf::focus_view_signal *>(data); wayfire_view view = signal->view; if (!view) return; uint view_id = view->get_id(); if (view_id == focused_view_id || view->role != wf::VIEW_ROLE_TOPLEVEL) { LOG(wf::log::LOG_LEVEL_ERROR, "focus_view_signal: ignoring"); return; } LOG(wf::log::LOG_LEVEL_ERROR, "focus_view_signal: ", view_id, view->get_title()); if (view->has_data("view-demands-attention")) view->erase_data("view-demands-attention"); focused_view_id = view_id; GVariant *signal_data = g_variant_new("(u)", view_id); g_variant_ref(signal_data); bus_emit_signal("view_focus_changed", signal_data); }}; wf::signal_connection_t view_self_request_focus{[=](wf::signal_data_t *data) { wf::view_self_request_focus_signal *signal = static_cast<wf::view_self_request_focus_signal *>(data); wayfire_view view = signal->view; wf::output_t *active_output = wf::get_core().get_active_output(); wf::get_core().move_view_to_output(view, active_output, true); active_output->workspace->add_view(view, wf::LAYER_WORKSPACE); view->set_activated(true); }}; wf::signal_connection_t output_detach_view{[=](wf::signal_data_t *data) { // wayfire_view closed_view = get_signaled_view(data); // LOG(wf::log::LOG_LEVEL_ERROR, "detach_view VIEW: " + closed_view->get_app_id() + " on " + closed_view->get_output()->to_string(), "DBUS PLUGIN", 32); }}; wf::signal_connection_t output_view_disappeared{[=](wf::signal_data_t *data) { // wayfire_view closed_view = get_signaled_view(data); // LOG(wf::log::LOG_LEVEL_ERROR, "view_disappeared VIEW: " + closed_view->get_app_id() + " on " + closed_view->get_output()->to_string(), "DBUS PLUGIN", 32); }}; wf::signal_connection_t output_view_attached{[=](wf::signal_data_t *data) { // wayfire_view closed_view = get_signaled_view(data); // LOG(wf::log::LOG_LEVEL_ERROR, "view_attached VIEW: " + closed_view->get_app_id() + " on " + std::to_string(closed_view->role), "DBUS PLUGIN", 32); }}; wf::signal_connection_t output_view_moving{[=](wf::signal_data_t *data) { // // wayfire_view closed_view = get_signaled_view(data); // // LOG(wf::log::LOG_LEVEL_ERROR, "moving VIEW: " + closed_view->get_app_id() + " on " + closed_view->get_output()->to_string(), "DBUS PLUGIN", 32); GVariant *signal_data = g_variant_new("(s)", "test"); g_variant_ref(signal_data); bus_emit_signal("view_moving_changed", signal_data); }}; wf::signal_connection_t output_view_resizing{[=](wf::signal_data_t *data) { // // wayfire_view closed_view = get_signaled_view(data); // // LOG(wf::log::LOG_LEVEL_ERROR, "moving VIEW: " + closed_view->get_app_id() + " on " + closed_view->get_output()->to_string(), "DBUS PLUGIN", 32); GVariant *signal_data = g_variant_new("(s)", "test"); g_variant_ref(signal_data); bus_emit_signal("view_resizing_changed", signal_data); }}; wf::signal_connection_t output_view_decoration_changed{[=](wf::signal_data_t *data) { // // wayfire_view d_view = get_signaled_view(data); // // LOG(wf::log::LOG_LEVEL_ERROR, "decoration-state-updated-view" + d_view->get_app_id() + " on " + d_view->get_output()->to_string(), "DBUS PLUGIN", 32); }}; //******************************Output Layout Slots***************************// // wf::signal_connection_t output_layout_configuration_changed{[=](wf::signal_data_t *data) { // LOG(wf::log::LOG_LEVEL_ERROR, "output_config_changed VIEW: ", "DBUS PLUGIN", 32); // }}; wf::signal_connection_t output_layout_output_added{[=](wf::signal_data_t *data) { LOG(wf::log::LOG_LEVEL_ERROR, "output_added VIEW: ", "DBUS PLUGIN", 32); wf::output_t *wf_output = get_signaled_output(data); /** These are better to listen to from the view itself each view signal cause the corresponding output to call them **/ // wf_output->connect_signal("attach-view", &output_view_attached); // wf_output->connect_signal("detach-view", &detach_view); // wf_output->connect_signal("view-disappeared", &view_disappeared); // wf_output->connect_signal("decoration-state-updated-view", &output_view_decoration_changed); // Skip already connected outputs // if (std::find(connected_wf_outputs.begin(), connected_wf_outputs.end(), wf_output) != connected_wf_outputs.end()) auto search = connected_wf_outputs.find(wf_output); if (search != connected_wf_outputs.end()) return; wf_output->connect_signal("view-fullscreen-request", &view_fullscreen_changed); wf_output->connect_signal("view-mapped", &output_view_added); wf_output->connect_signal("output-configuration-changed", &output_configuration_changed); wf_output->connect_signal("view-minimize-request", &output_view_minimized); wf_output->connect_signal("view-tile-request", &output_view_maximized); wf_output->connect_signal("view-move-request", &output_view_moving); wf_output->connect_signal("view-change-viewport", &view_workspaces_changed); wf_output->connect_signal("viewport-changed", &output_workspace_changed); wf_output->connect_signal("view-self-request-focus", &view_self_request_focus); wf_output->connect_signal("view-resize-request", &output_view_resizing); // wf_output->connect_signal("fullscreen-layer-focused", &fullscreen_focus_changed); // wf_output->connect_signal("set-workspace-request", &output_workspace_changed); wf_output->connect_signal("view-focused", &output_view_focus_changed); // view->get_output()->emit_signal("wm-focus-request", &data); // utput.cpp: emit_signal("view-focused", &data); // active_output->emit_signal("output-gain-focus", nullptr); // view->get_output()->emit_signal("wm-focus-request", &data); connected_wf_outputs.insert(wf_output); // nonstd::observer_ptr<wf::sublayer_t> sticky_layer; // sticky_layer = wf_output->workspace->create_sublayer(wf::LAYER_WORKSPACE, // wf::SUBLAYER_DOCKED_ABOVE); // sticky_layers.push_back(sticky_layer); }}; wf::signal_connection_t output_layout_output_removed{[=](wf::signal_data_t *data) { LOG(wf::log::LOG_LEVEL_ERROR, "output_removed VIEW: ", "DBUS PLUGIN", 32); wf::output_t *wf_output = get_signaled_output(data); auto search = connected_wf_outputs.find(wf_output); if (search != connected_wf_outputs.end()) connected_wf_outputs.erase(wf_output); //maybe use pre-removed instead? }}; }; DECLARE_WAYFIRE_PLUGIN((wf::singleton_plugin_t<dbus_interface_t, true>)); //bool = unloadable
42.926916
162
0.648825
[ "geometry", "render" ]
b6e7af56ed5a0e69b2b2b5ce4913c1feec5e0987
2,741
cpp
C++
PAT_B/PAT_B1095.cpp
EnhydraGod/PATCode
ff38ea33ba319af78b3aeba8aa6c385cc5e8329f
[ "BSD-2-Clause" ]
3
2019-07-08T05:20:28.000Z
2021-09-22T10:53:26.000Z
PAT_B/PAT_B1095.cpp
EnhydraGod/PATCode
ff38ea33ba319af78b3aeba8aa6c385cc5e8329f
[ "BSD-2-Clause" ]
null
null
null
PAT_B/PAT_B1095.cpp
EnhydraGod/PATCode
ff38ea33ba319af78b3aeba8aa6c385cc5e8329f
[ "BSD-2-Clause" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int n, m, ch, tempSc; string str; char pat; struct node1 { string stuId = ""; int stuSc = 0; node1(string _stuId = "", int _stuSc = 0){ stuId = _stuId; stuSc = _stuSc; } }; struct node3 { string ss; int nums; node3(string _ss = "", int _nums = 0) { ss = _ss; nums = _nums; } }; vector<node1> BBB, AAA, TTT; map<string, pair<int, int>> type2;//考场号-> <人数, 总分> unordered_map<string, unordered_map<string, int>> type3; bool CMP1(const node1 &a, const node1 &b){if(a.stuSc != b.stuSc) return a.stuSc > b.stuSc; return a.stuId < b.stuId;} bool CMP2(const node3 &a, const node3 &b){if(a.nums != b.nums) return a.nums > b.nums; return a.ss < b.ss; } int main() { scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) { cin >> str >> tempSc; if(str[0] == 'B') BBB.push_back(node1(str, tempSc)); else if(str[0] == 'A') AAA.push_back(node1(str, tempSc)); else TTT.push_back(node1(str, tempSc)); string tempStr1 = str.substr(1, 3); if(type2.find(tempStr1) == type2.end()) type2[tempStr1] = make_pair(1, tempSc); else { type2[tempStr1].first++; type2[tempStr1].second += tempSc; } string tempStr2 = str.substr(4, 6); type3[tempStr2][tempStr1]++; } sort(BBB.begin(), BBB.end(), CMP1); sort(AAA.begin(), AAA.end(), CMP1); sort(TTT.begin(), TTT.end(), CMP1); for (int i = 1; i <= m; i++) { scanf("%d", &ch); getchar(); printf("Case %d: ", i); if(ch == 1) { scanf("%c", &pat); printf("1 %c\n", pat); if(pat == 'B' && BBB.size() != 0) for(auto&i:BBB) cout << i.stuId << " " << i.stuSc << endl; else if(pat == 'A' && AAA.size() != 0) for(auto&i:AAA) cout << i.stuId << " " << i.stuSc << endl; else if(pat == 'T' && TTT.size() != 0) for(auto&i:TTT) cout << i.stuId << " " << i.stuSc << endl; else printf("NA\n"); } else if(ch == 2) { cin >> str; cout << "2 " << str << endl; if(type2.find(str) != type2.end()) cout << type2[str].first << " " << type2[str].second << endl; else printf("NA\n"); } else { cin >> str; cout << "3 " << str << endl; vector<node3> vec; for(auto&i:type3[str]) vec.push_back(node3(i.first, i.second)); if(vec.size() == 0) { printf("NA\n"); continue; } sort(vec.begin(), vec.end(), CMP2); for(auto&i:vec) printf("%s %d\n", i.ss.c_str(), i.nums); } } return 0; }
33.426829
117
0.481211
[ "vector" ]
b6ebe01493f9804cf3b8ea25b21bf4b72e77fc39
9,160
cpp
C++
engine/src/bard/renderer/2D/Renderer.cpp
baard047/bard_engine
595d5e35faf2f59a84a4f70e952caa8ca322093b
[ "Apache-2.0" ]
null
null
null
engine/src/bard/renderer/2D/Renderer.cpp
baard047/bard_engine
595d5e35faf2f59a84a4f70e952caa8ca322093b
[ "Apache-2.0" ]
null
null
null
engine/src/bard/renderer/2D/Renderer.cpp
baard047/bard_engine
595d5e35faf2f59a84a4f70e952caa8ca322093b
[ "Apache-2.0" ]
null
null
null
/* * \file Renderer.cpp.cc * \copyright (C) 2021 Special Technological Center Ltd * \author : Bardashevsky A.K. * \date : 15.01.2021 * \time : 9:41 */ #include "Renderer.h" #include <array> #include <bard/renderer/Shader.h> #include <bard/renderer/Texture.h> #include <bard/renderer/VertexArray.h> #include <bard/renderer/RenderCommand.h> #include <glm/gtc/matrix_transform.hpp> namespace bard { namespace { //per draw call constexpr const uint32_t MAX_QUADS = 20000; constexpr const uint32_t MAX_VERTICES = MAX_QUADS * 4; constexpr const uint32_t MAX_INDICES = MAX_QUADS * 6; constexpr const uint32_t MAX_TEXTURE_SLOTS = 32; constexpr size_t QUAD_VERTEX_COUNT = 4; constexpr glm::vec4 QUAD_VERTEX_POSITIONS[ QUAD_VERTEX_COUNT ] = { { -0.5f, -0.5f, 0.0f, 1.0f }, { 0.5f, -0.5f, 0.0f, 1.0f }, { 0.5f, 0.5f, 0.0f, 1.0f }, { -0.5f, 0.5f, 0.0f, 1.0f } }; constexpr glm::vec2 TEXTURE_COORDINATES[] = { { 0.0f, 0.0f }, { 1.0f, 0.0f }, { 1.0f, 1.0f }, { 0.0f, 1.0f } }; struct QuadVertex { glm::vec3 position; glm::vec4 color; glm::vec2 texCoord; float textureIndex; float tilingFactor; }; struct Renderer2DData { VertexArray::Ptr quadVA; VertexBuffer::Ptr quadVB; Shader::Ptr textureShader; Texture2D::Ptr whiteTexture; uint32_t quadIndexCount = 0; QuadVertex * quadVertexBufferBase = nullptr; QuadVertex * quadVertexBufferPtr = nullptr; std::array< Texture2D::Ptr, MAX_TEXTURE_SLOTS > textureSlots; uint32_t textureSlotIndex = 1; // 0 = white texture Renderer2D::Statistics stats; }; Renderer2DData s_Data; } void Renderer2D::init() noexcept { s_Data.quadVA = VertexArray::create(); s_Data.quadVB = VertexBuffer::create( MAX_VERTICES * sizeof( QuadVertex ) ); s_Data.quadVB->setLayout( { { ShaderDataType::Float3, "a_Position" }, { ShaderDataType::Float4, "a_Color" }, { ShaderDataType::Float2, "a_TexCoord" }, { ShaderDataType::Float, "a_TexIndex" }, { ShaderDataType::Float, "a_TilingFactor" }} ); s_Data.quadVA->addVertexBuffer( s_Data.quadVB ); s_Data.quadVertexBufferBase = new QuadVertex[ MAX_VERTICES ]; auto * quadIndices = new uint32_t[ MAX_INDICES ]; uint32_t offset = 0; for (uint32_t i = 0; i < MAX_INDICES; i += 6) { quadIndices[i + 0] = offset + 0; quadIndices[i + 1] = offset + 1; quadIndices[i + 2] = offset + 2; quadIndices[i + 3] = offset + 2; quadIndices[i + 4] = offset + 3; quadIndices[i + 5] = offset + 0; offset += 4; } //TODO maybe change to shared_ptr later. Its right away send in GPU for now s_Data.quadVA->setIndexBuffer( IndexBuffer::create( quadIndices, MAX_INDICES ) ); delete[] quadIndices; s_Data.whiteTexture = Texture2D::create(1, 1); uint32_t white = 0xffffffff; s_Data.whiteTexture->setData( &white, sizeof( white ) ); int32_t samplers[ MAX_TEXTURE_SLOTS ]; for( uint32_t i = 0; i < MAX_TEXTURE_SLOTS; i++ ) { samplers[ i ] = i; } s_Data.textureShader = Shader::create( "assets/shaders/Texture.glsl" ); s_Data.textureShader->bind(); s_Data.textureShader->setIntArray( "u_Textures", samplers, MAX_TEXTURE_SLOTS ); s_Data.textureSlots[ 0 ] = s_Data.whiteTexture; // Set first texture slot to 0 } void Renderer2D::shutdown() noexcept { delete[] s_Data.quadVertexBufferBase; } void Renderer2D::BeginScene( const OrthographicCamera & camera ) noexcept { s_Data.textureShader->bind(); s_Data.textureShader->setMat4( "u_viewProjection", camera.viewProjectionMatrix() ); StartBatch(); } void Renderer2D::EndScene() noexcept { Flush(); } void Renderer2D::StartBatch() noexcept { s_Data.quadIndexCount = 0; s_Data.quadVertexBufferPtr = s_Data.quadVertexBufferBase; s_Data.textureSlotIndex = 1; } void Renderer2D::NextBatch() noexcept { Flush(); StartBatch(); } void Renderer2D::Flush() noexcept { if( s_Data.quadIndexCount == 0 ) { return; } auto dataSize = ( uint32_t ) ( ( uint8_t * ) s_Data.quadVertexBufferPtr - ( uint8_t * ) s_Data.quadVertexBufferBase ); s_Data.quadVB->setData( s_Data.quadVertexBufferBase, dataSize ); for( uint32_t i = 0; i < s_Data.textureSlotIndex; i++ ) { s_Data.textureSlots[ i ]->bind( i ); } RenderCommand::drawIndexed( s_Data.quadVA, s_Data.quadIndexCount ); s_Data.stats.drawCalls++; } void Renderer2D::DrawQuad( const glm::vec2 & pos, const glm::vec2 & size, const glm::vec4 & color ) noexcept { DrawQuad( { pos.x, pos.y, 0.f }, size, color ); } void Renderer2D::DrawQuad( const glm::vec3 & pos, const glm::vec2 & size, const glm::vec4 & color ) noexcept { glm::mat4 transform = glm::translate( glm::mat4{ 1.f }, pos ) /* TODO * rotation */ * glm::scale( glm::mat4{ 1.f }, { size.x, size.y, 1.f } ); DrawQuad( transform, color ); } void Renderer2D::DrawQuad( const glm::mat4 & transform, const glm::vec4 & color ) noexcept { static constexpr float whiteTextureIndex = 0.0f; static constexpr float tilingFactor = 1.0; if (s_Data.quadIndexCount >= MAX_INDICES ) { NextBatch(); } for( size_t i = 0; i < QUAD_VERTEX_COUNT; ++i ) { s_Data.quadVertexBufferPtr->position = transform * QUAD_VERTEX_POSITIONS[ i ]; s_Data.quadVertexBufferPtr->color = color; s_Data.quadVertexBufferPtr->texCoord = TEXTURE_COORDINATES[ i ]; s_Data.quadVertexBufferPtr->textureIndex = whiteTextureIndex; s_Data.quadVertexBufferPtr->tilingFactor = tilingFactor; s_Data.quadVertexBufferPtr++; } s_Data.quadIndexCount += 6; s_Data.stats.quadCount++; } void Renderer2D::DrawQuad( const glm::vec2 & pos, const glm::vec2 & size, const Texture2D::Ptr & texture, float tilingFactor ) noexcept { DrawQuad( { pos.x, pos.y, 0.f }, size, texture, tilingFactor ); } void Renderer2D::DrawQuad( const glm::vec3 & pos, const glm::vec2 & size, const Texture2D::Ptr & texture, float tilingFactor ) noexcept { constexpr glm::vec2 textureCoords[] = { { 0.0f, 0.0f }, { 1.0f, 0.0f }, { 1.0f, 1.0f }, { 0.0f, 1.0f } }; constexpr glm::vec4 color{ 1.0f, 1.0f, 1.0f, 1.0f }; if (s_Data.quadIndexCount >= MAX_INDICES ) { NextBatch(); } float textureIndex = 0.0f; for ( uint32_t i = 1; i < s_Data.textureSlotIndex; i++ ) { if ( *s_Data.textureSlots[ i ] == *texture ) { textureIndex = static_cast< float >( i ); break; } } if( textureIndex == 0.0f ) { if (s_Data.quadIndexCount >= MAX_TEXTURE_SLOTS ) { NextBatch(); } textureIndex = static_cast< float >( s_Data.textureSlotIndex ); s_Data.textureSlots[ s_Data.textureSlotIndex ] = texture; s_Data.textureSlotIndex++; } s_Data.quadVertexBufferPtr->position = pos; s_Data.quadVertexBufferPtr->color = color; s_Data.quadVertexBufferPtr->texCoord = textureCoords[0]; s_Data.quadVertexBufferPtr->textureIndex = textureIndex; s_Data.quadVertexBufferPtr->tilingFactor = tilingFactor; s_Data.quadVertexBufferPtr++; s_Data.quadVertexBufferPtr->position = { pos.x + size.x, pos.y, 0.f }; s_Data.quadVertexBufferPtr->color = color; s_Data.quadVertexBufferPtr->texCoord = textureCoords[1]; s_Data.quadVertexBufferPtr->textureIndex = textureIndex; s_Data.quadVertexBufferPtr->tilingFactor = tilingFactor; s_Data.quadVertexBufferPtr++; s_Data.quadVertexBufferPtr->position = { pos.x + size.x, pos.y + size.y, 0.f }; s_Data.quadVertexBufferPtr->color = color; s_Data.quadVertexBufferPtr->texCoord = textureCoords[2]; s_Data.quadVertexBufferPtr->textureIndex = textureIndex; s_Data.quadVertexBufferPtr->tilingFactor = tilingFactor; s_Data.quadVertexBufferPtr++; s_Data.quadVertexBufferPtr->position = { pos.x, pos.y + size.y, 0.f }; s_Data.quadVertexBufferPtr->color = color; s_Data.quadVertexBufferPtr->texCoord = textureCoords[3]; s_Data.quadVertexBufferPtr->textureIndex = textureIndex; s_Data.quadVertexBufferPtr->tilingFactor = tilingFactor; s_Data.quadVertexBufferPtr++; s_Data.quadIndexCount += 6; s_Data.stats.quadCount++; /* s_Data.textureShader->setFloat4( "u_Color", glm::vec4( 1.f ) ); //TODO setColor texture->bind(); auto transform = glm::translate( glm::mat4{ 1.f }, pos ) *//* TODO * rotation *//* * glm::scale( glm::mat4{ 1.f }, { size.x, size.y, 1.f } ); s_Data.textureShader->setMat4( "u_Transform", transform ); //TODO apply color later s_Data.quadVA->bind(); RenderCommand::drawIndexed( s_Data.quadVA );*/ } void Renderer2D::DrawQuad( const glm::mat4 & transform, const Texture2D::Ptr & texture, float tilingFactor ) noexcept { //TODO } void Renderer2D::resetStats() { std::memset( &s_Data.stats, 0, sizeof( Statistics ) ); } Renderer2D::Statistics Renderer2D::getStats() { return s_Data.stats; } }
29.934641
135
0.651638
[ "transform" ]
b6f640fc27cce7c33fb91983ad0eb6a17f3c0690
13,689
cpp
C++
src/core/transform.cpp
guerarda/rt1w
2fa13326e0a745214fb1a9fdc49a345c1407b6f3
[ "MIT" ]
null
null
null
src/core/transform.cpp
guerarda/rt1w
2fa13326e0a745214fb1a9fdc49a345c1407b6f3
[ "MIT" ]
null
null
null
src/core/transform.cpp
guerarda/rt1w
2fa13326e0a745214fb1a9fdc49a345c1407b6f3
[ "MIT" ]
null
null
null
#include "rt1w/transform.hpp" #include "rt1w/error.h" #include "rt1w/interaction.hpp" #include "rt1w/ray.hpp" #include "rt1w/utils.hpp" #include <cmath> Transform Transform::operator*(const Transform &t) const { return Transform(Mul(m_mat, t.m_mat), Mul(t.m_inv, m_inv)); } Ray Transform::operator()(const Ray &r) const { v3f o = Mulp(*this, r.org()); v3f d = Mulv(*this, r.dir()); return { o, d, r.max() }; } Ray Transform::operator()(const Ray &r, v3f &oError, v3f &dError) const { v3f o = Mulp(*this, r.org(), oError); v3f d = Mulv(*this, r.dir(), dError); return { o, d, r.max() }; } Ray Transform::operator()(const Ray &r, const v3f &oErrorIn, const v3f &dErrorIn, v3f &oErrorOut, v3f &dErrorOut) const { v3f o = Mulp(*this, r.org(), oErrorIn, oErrorOut); v3f d = Mulv(*this, r.dir(), dErrorIn, dErrorOut); return { o, d, r.max() }; } bounds3f Transform::operator()(const bounds3f &b) const { bounds3f rb; rb = Union(rb, Mulp(*this, v3f{ b.lo.x, b.lo.y, b.lo.z })); rb = Union(rb, Mulp(*this, v3f{ b.lo.x, b.hi.y, b.lo.z })); rb = Union(rb, Mulp(*this, v3f{ b.hi.x, b.hi.y, b.lo.z })); rb = Union(rb, Mulp(*this, v3f{ b.hi.x, b.lo.y, b.lo.z })); rb = Union(rb, Mulp(*this, v3f{ b.lo.x, b.lo.y, b.hi.z })); rb = Union(rb, Mulp(*this, v3f{ b.lo.x, b.hi.y, b.hi.z })); rb = Union(rb, Mulp(*this, v3f{ b.hi.x, b.hi.y, b.hi.z })); rb = Union(rb, Mulp(*this, v3f{ b.hi.x, b.lo.y, b.hi.z })); return rb; } Interaction Transform::operator()(const Interaction &i) const { Interaction ri; ri.p = Mulp(*this, i.p, i.error, ri.error); ri.t = i.t; ri.uv = i.uv; ri.wo = Normalize(Mulv(*this, i.wo)); ri.n = Normalize(Muln(*this, i.n)); ri.dpdu = Mulv(*this, i.dpdu); ri.dpdv = Mulv(*this, i.dpdv); ri.shading.n = Normalize(Muln(*this, i.shading.n)); ri.shading.dpdu = Mulv(*this, i.shading.dpdu); ri.shading.dpdv = Mulv(*this, i.shading.dpdv); ri.mat = i.mat; ri.prim = i.prim; return ri; } Transform Inverse(const Transform &t) { return Transform(t.m_inv, t.m_mat); } template <typename T> Vector3<T> Mulv(const Transform &t, const Vector3<T> &v) { T x = v.x, y = v.y, z = v.z; m44f mat = t.mat(); return { mat.vx.x * x + mat.vx.y * y + mat.vx.z * z, mat.vy.x * x + mat.vy.y * y + mat.vy.z * z, mat.vz.x * x + mat.vz.y * y + mat.vz.z * z }; } template <typename T> Vector3<T> Mulv(const Transform &t, const Vector3<T> &v, Vector3<T> &e) { T x = v.x, y = v.y, z = v.z; m44f m = t.m_mat; e.x = gamma(3) * (std::abs(m.vx.x * x) + std::abs(m.vx.y * y) + std::abs(m.vx.z * z)); e.y = gamma(3) * (std::abs(m.vy.x * x) + std::abs(m.vy.y * y) + std::abs(m.vy.z * z)); e.z = gamma(3) * (std::abs(m.vz.x * x) + std::abs(m.vz.y * y) + std::abs(m.vz.z * z)); return { m.vx.x * x + m.vx.y * y + m.vx.z * z, m.vy.x * x + m.vy.y * y + m.vy.z * z, m.vz.x * x + m.vz.y * y + m.vz.z * z }; } template <typename T> Vector3<T> Mulv(const Transform &t, const Vector3<T> &v, const Vector3<T> &vError, Vector3<T> &tError) { T x = v.x, y = v.y, z = v.z; m44f m = t.m_mat; tError.x = gamma(3) * (std::abs(m.vx.x * x) + std::abs(m.vx.y * y) + std::abs(m.vx.z * z)) + (T{ 1.0 } + gamma(3)) * (std::abs(m.vx.x * vError.x) + std::abs(m.vx.y * vError.y) + std::abs(m.vx.z * vError.z)); tError.y = gamma(3) * (std::abs(m.vy.x * x) + std::abs(m.vy.y * y) + std::abs(m.vy.z * z)) + (T{ 1.0 } + gamma(3)) * (std::abs(m.vy.x * vError.x) + std::abs(m.vy.y * vError.y) + std::abs(m.vy.z * vError.z)); tError.z = gamma(3) * (std::abs(m.vz.x * x) + std::abs(m.vx.z * y) + std::abs(m.vz.z * z)) + (T{ 1.0 } + gamma(3)) * (std::abs(m.vz.x * vError.x) + std::abs(m.vz.y * vError.y) + std::abs(m.vz.z * vError.z)); return { m.vx.x * x + m.vx.y * y + m.vx.z * z, m.vy.x * x + m.vy.y * y + m.vy.z * z, m.vz.x * x + m.vz.y * y + m.vz.z * z }; } template <typename T> Vector3<T> Mulp(const Transform &t, const Vector3<T> &p) { m44f m = t.m_mat; T x = m.vx.x * p.x + m.vx.y * p.y + m.vx.z * p.z + m.vx.w; T y = m.vy.x * p.x + m.vy.y * p.y + m.vy.z * p.z + m.vy.w; T z = m.vz.x * p.x + m.vz.y * p.y + m.vz.z * p.z + m.vz.w; T w = m.vw.x * p.x + m.vw.y * p.y + m.vw.z * p.z + m.vw.w; if (FloatEqual(w, T{ 1.0 })) { return { x, y, z }; } return { x / w, y / w, z / w }; } template <typename T> Vector3<T> Mulp(const Transform &t, const Vector3<T> &p, Vector3<T> &e) { m44f m = t.m_mat; T x = m.vx.x * p.x + m.vx.y * p.y + m.vx.z * p.z + m.vx.w; T y = m.vy.x * p.x + m.vy.y * p.y + m.vy.z * p.z + m.vy.w; T z = m.vz.x * p.x + m.vz.y * p.y + m.vz.z * p.z + m.vz.w; T w = m.vw.x * p.x + m.vw.y * p.y + m.vw.z * p.z + m.vw.w; e.x = gamma(3) * (std::abs(m.vx.x * x) + std::abs(m.vx.y * y) + std::abs(m.vx.z * z) + std::abs(m.vx.w)); e.y = gamma(3) * (std::abs(m.vy.x * x) + std::abs(m.vy.y * y) + std::abs(m.vy.z * z) + std::abs(m.vy.w)); e.z = gamma(3) * (std::abs(m.vz.x * x) + std::abs(m.vz.y * y) + std::abs(m.vz.z * z) + std::abs(m.vz.w)); if (FloatEqual(w, T{ 1.0 })) { return { x, y, z }; } return { x / w, y / w, z / w }; } template <typename T> Vector3<T> Mulp(const Transform &t, const Vector3<T> &p, const Vector3<T> &pError, Vector3<T> &tError) { m44f m = t.m_mat; T x = m.vx.x * p.x + m.vx.y * p.y + m.vx.z * p.z + m.vx.w; T y = m.vy.x * p.x + m.vy.y * p.y + m.vy.z * p.z + m.vy.w; T z = m.vz.x * p.x + m.vz.y * p.y + m.vz.z * p.z + m.vz.w; T w = m.vw.x * p.x + m.vw.y * p.y + m.vw.z * p.z + m.vw.w; tError.x = gamma(3) * (std::abs(m.vx.x * x) + std::abs(m.vx.y * y) + std::abs(m.vx.z * z) + std::abs(m.vx.w)) + (T{ 1.0 } + gamma(3)) * (std::abs(m.vx.x * pError.x) + std::abs(m.vx.y * pError.y) + std::abs(m.vx.z * pError.z)); tError.y = gamma(3) * (std::abs(m.vy.x * x) + std::abs(m.vy.y * y) + std::abs(m.vy.z * z) + std::abs(m.vy.w)) + (T{ 1.0 } + gamma(3)) * (std::abs(m.vy.x * pError.x) + std::abs(m.vy.y * pError.y) + std::abs(m.vy.z * pError.z)); tError.z = gamma(3) * (std::abs(m.vz.x * x) + std::abs(m.vx.z * y) + std::abs(m.vz.z * z) + std::abs(m.vz.w)) + (T{ 1.0 } + gamma(3)) * (std::abs(m.vz.x * pError.x) + std::abs(m.vz.y * pError.y) + std::abs(m.vz.z * pError.z)); if (FloatEqual(w, T{ 1.0 })) { return { x, y, z }; } return { x / w, y / w, z / w }; } template <typename T> Vector3<T> Muln(const Transform &t, const Vector3<T> &n) { T x = t.m_inv.vx.x * n.x + t.m_inv.vy.x * n.y + t.m_inv.vz.x * n.z; T y = t.m_inv.vx.y * n.x + t.m_inv.vy.y * n.y + t.m_inv.vz.y * n.z; T z = t.m_inv.vx.z * n.x + t.m_inv.vy.z * n.y + t.m_inv.vz.z * n.z; return { x, y, z }; } /* Explicit template instantiations */ template Vector3<float> Mulv(const Transform &t, const Vector3<float> &v); template Vector3<double> Mulv(const Transform &t, const Vector3<double> &v); template Vector3<float> Mulv(const Transform &t, const Vector3<float> &v, Vector3<float> &e); template Vector3<double> Mulv(const Transform &t, const Vector3<double> &v, Vector3<double> &e); template Vector3<float> Mulv(const Transform &t, const Vector3<float> &v, const Vector3<float> &vError, Vector3<float> &tError); template Vector3<double> Mulv(const Transform &t, const Vector3<double> &v, const Vector3<double> &vError, Vector3<double> &tError); template Vector3<float> Mulp(const Transform &t, const Vector3<float> &p); template Vector3<double> Mulp(const Transform &t, const Vector3<double> &p); template Vector3<float> Mulp(const Transform &t, const Vector3<float> &p, Vector3<float> &e); template Vector3<double> Mulp(const Transform &t, const Vector3<double> &p, Vector3<double> &e); template Vector3<float> Mulp(const Transform &t, const Vector3<float> &p, const Vector3<float> &pError, Vector3<float> &tError); template Vector3<double> Mulp(const Transform &t, const Vector3<double> &p, const Vector3<double> &pError, Vector3<double> &tError); template Vector3<float> Muln(const Transform &t, const Vector3<float> &n); template Vector3<double> Muln(const Transform &t, const Vector3<double> &n); #pragma mark - Static Functions Transform Transform::Scale(float s) { return Transform::Scale(s, s, s); } Transform Transform::Scale(float x, float y, float z) { float m[4][4] = { { x, 0.0f, 0.0f, 0.0f }, { 0.0f, y, 0.0f, 0.0f }, { 0.0f, 0.0f, z, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } }; float i[4][4] = { { 1.0f / x, 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f / y, 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f / z, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } }; return Transform(m44f(m), m44f(i)); } Transform Transform::Translate(const v3f &v) { float m[4][4] = { { 1.0f, 0.0f, 0.0f, v.x }, { 0.0f, 1.0f, 0.0f, v.y }, { 0.0f, 0.0f, 1.0f, v.z }, { 0.0f, 0.0f, 0.0f, 1.0f } }; float i[4][4] = { { 1.0f, 0.0f, 0.0f, -v.x }, { 0.0f, 1.0f, 0.0f, -v.y }, { 0.0f, 0.0f, 1.0f, -v.z }, { 0.0f, 0.0f, 0.0f, 1.0f } }; return Transform(m44f(m), m44f(i)); } Transform Transform::RotateX(float theta) { float cos = std::cos(Radians(theta)); float sin = std::sin(Radians(theta)); float m[4][4] = { { 1.0f, 0.0f, 0.0f, 0.0f }, { 0.0f, cos, -sin, 0.0f }, { 0.0f, sin, cos, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } }; return Transform(m44f(m), Transpose(m44f(m))); } Transform Transform::RotateY(float theta) { float cos = std::cos(Radians(theta)); float sin = std::sin(Radians(theta)); float m[4][4] = { { cos, 0.0f, sin, 0.0f }, { 0.0f, 1.0f, 0.0f, 0.0f }, { -sin, 0.0f, cos, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } }; return Transform(m44f(m), Transpose(m44f(m))); } Transform Transform::RotateZ(float theta) { float cos = std::cos(Radians(theta)); float sin = std::sin(Radians(theta)); float m[4][4] = { { cos, -sin, 0.0f, 0.0f }, { sin, cos, 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } }; return Transform(m44f(m), Transpose(m44f(m))); } Transform Transform::Rotate(float theta, const v3f &axis) { v3f a = Normalize(axis); float sinTheta = std::sin(Radians(theta)); float cosTheta = std::cos(Radians(theta)); m44f m = m44f_identity(); m.vx.x = a.x * a.x + (1 - a.x * a.x) * cosTheta; m.vx.y = a.x * a.y * (1 - cosTheta) - a.z * sinTheta; m.vx.z = a.x * a.z * (1 - cosTheta) + a.y * sinTheta; m.vx.w = 0; m.vy.x = a.x * a.y * (1 - cosTheta) + a.z * sinTheta; m.vy.y = a.y * a.y + (1 - a.y * a.y) * cosTheta; m.vy.z = a.y * a.z * (1 - cosTheta) - a.x * sinTheta; m.vy.w = 0; m.vz.x = a.x * a.z * (1 - cosTheta) - a.y * sinTheta; m.vz.y = a.y * a.z * (1 - cosTheta) + a.x * sinTheta; m.vz.z = a.z * a.z + (1 - a.z * a.z) * cosTheta; m.vz.w = 0; return Transform(m, Transpose(m)); } Transform Transform::LookAt(const v3f &p, const v3f &look, const v3f &up) { v3f w = Normalize(p - look); v3f u = Normalize(Cross(up, w)); v3f v = Cross(w, u); float m[4][4] = { { u.x, v.x, w.x, p.x }, { u.y, v.y, w.y, p.y }, { u.z, v.z, w.z, p.z }, { 0.0, 0.0, 0.0, 1.0 } }; return Transform(m44f(m), Inverse(m44f(m))); } Transform Transform::Orthographic(float znear, float zfar) { return Scale(1.0f, 1.0f, 1.0f / (zfar - znear)) * Translate({ 0.0f, 0.0f, -znear }); } Transform Transform::Perspective(float fov, float znear, float zfar) { ASSERT(fov > 0.0f); float itan = 1.0f / std::tan(Radians(fov / 2.0f)); float A = zfar / (zfar - znear); float B = -zfar * znear / (zfar - znear); float m[4][4] = { { itan, 0.0f, 0.0f, 0.0f }, { 0.0f, itan, 0.0f, 0.0f }, { 0.0f, 0.0f, A, B }, { 0.0f, 0.0f, -1.0f, 0.0f } }; return Transform(m); }
35.280928
90
0.465264
[ "transform" ]
8e006b8fcc1fc3969d0d6457229350767a761128
7,979
cpp
C++
MAME4all/trunk/src/sound/c140.cpp
lofunz/mieme
4226c2960b46121ec44fa8eab9717d2d644bff04
[ "Unlicense" ]
51
2015-11-22T14:53:28.000Z
2021-12-14T07:17:42.000Z
MAME4all/trunk/src/sound/c140.cpp
lofunz/mieme
4226c2960b46121ec44fa8eab9717d2d644bff04
[ "Unlicense" ]
8
2018-01-14T07:19:06.000Z
2021-08-22T15:29:59.000Z
src/sound/c140.cpp
raytlin/iMameAtariArcadeDuo
24adc56d1a6080822a6c9d1770ddbc607814373a
[ "Unlicense" ]
35
2017-02-15T09:39:00.000Z
2021-12-14T07:17:43.000Z
/* C140.c Simulator based on AMUSE sources. The C140 sound chip is used by Namco SystemII, System21 This chip controls 24 channels of PCM. 16 bytes are associated with each channel. Channels can be 8 bit signed PCM, or 12 bit signed PCM. Timer behavior is not yet handled. Unmapped registers: 0x1f8:timer interval? (Nx0.1 ms) 0x1fa:irq ack? timer restart? 0x1fe:timer switch?(0:off 1:on) */ /* 2000.06.26 CAB fixed compressed pcm playback */ #include <math.h> #include "driver.h" #include "osinline.h" #define MAX_VOICE 24 struct voice_registers { UINT8 volume_right; UINT8 volume_left; UINT8 frequency_msb; UINT8 frequency_lsb; UINT8 bank; UINT8 mode; UINT8 start_msb; UINT8 start_lsb; UINT8 end_msb; UINT8 end_lsb; UINT8 loop_msb; UINT8 loop_lsb; UINT8 reserved[4]; }; static int sample_rate; static int stream; /* internal buffers */ static INT16 *mixer_buffer_left; static INT16 *mixer_buffer_right; static int baserate; static void *pRom; static UINT8 REG[0x200]; static INT16 pcmtbl[8]; //2000.06.26 CAB typedef struct { long ptoffset; long pos; long key; //--work long lastdt; long prevdt; long dltdt; //--reg long rvol; long lvol; long frequency; long bank; long mode; long sample_start; long sample_end; long sample_loop; } VOICE; VOICE voi[MAX_VOICE]; static void init_voice( VOICE *v ) { v->key=0; v->ptoffset=0; v->rvol=0; v->lvol=0; v->frequency=0; v->bank=0; v->mode=0; v->sample_start=0; v->sample_end=0; v->sample_loop=0; } READ_HANDLER( C140_r ) { offset&=0x1ff; return REG[offset]; } static long find_sample( long adrs, long bank) { adrs=(bank<<16)+adrs; return ((adrs&0x200000)>>2)|(adrs&0x7ffff); //SYSTEM2 mapping } WRITE_HANDLER( C140_w ) { #ifndef MAME_FASTSOUND stream_update(stream, 0); #else { extern int fast_sound; if (!fast_sound) stream_update(stream, 0); } #endif offset&=0x1ff; REG[offset]=data; if( offset<0x180 ) { VOICE *v = &voi[offset>>4]; if( (offset&0xf)==0x5 ) { if( data&0x80 ) { const struct voice_registers *vreg = (struct voice_registers *) &REG[offset&0x1f0]; v->key=1; v->ptoffset=0; v->pos=0; v->lastdt=0; v->prevdt=0; v->dltdt=0; v->bank = vreg->bank; v->mode = data; v->sample_loop = vreg->loop_msb*256 + vreg->loop_lsb; v->sample_start = vreg->start_msb*256 + vreg->start_lsb; v->sample_end = vreg->end_msb*256 + vreg->end_lsb; } else { v->key=0; } } } } #ifndef clip_short_ret INLINE int limit(INT32 in) { if(in>0x7fff) return 0x7fff; else if(in<-0x8000) return -0x8000; return in; } #else #define limit clip_short_ret #endif static void update_stereo(int ch, INT16 **buffer, int length) { int i,j; INT32 rvol,lvol; INT32 dt; INT32 sdt; INT32 st,ed,sz; INT8 *pSampleData; INT32 frequency,delta,offset,pos; INT32 cnt; INT32 lastdt,prevdt,dltdt; float pbase=(float)baserate*2.0 / (float)sample_rate; INT16 *lmix, *rmix; if(length>sample_rate) length=sample_rate; /* zap the contents of the mixer buffer */ memset(mixer_buffer_left, 0, length * sizeof(INT16)); memset(mixer_buffer_right, 0, length * sizeof(INT16)); //--- audio update for( i=0;i<MAX_VOICE;i++ ) { VOICE *v = &voi[i]; const struct voice_registers *vreg = (struct voice_registers *)&REG[i*16]; if( v->key ) { frequency= vreg->frequency_msb*256 + vreg->frequency_lsb; /* Abort voice if no frequency value set */ if(frequency==0) continue; /* Delta = frequency * ((8Mhz/374)*2 / sample rate) */ delta=(long)((float)frequency * pbase); /* Calculate left/right channel volumes */ lvol=(vreg->volume_left*32)/MAX_VOICE; //32ch -> 24ch rvol=(vreg->volume_right*32)/MAX_VOICE; /* Set mixer buffer base pointers */ lmix = mixer_buffer_left; rmix = mixer_buffer_right; /* Retrieve sample start/end and calculate size */ st=v->sample_start; ed=v->sample_end; sz=ed-st; /* Retrieve base pointer to the sample data */ pSampleData=(signed char*)((unsigned long)pRom + find_sample(st,v->bank)); /* Fetch back previous data pointers */ offset=v->ptoffset; pos=v->pos; lastdt=v->lastdt; prevdt=v->prevdt; dltdt=v->dltdt; /* Switch on data type */ if(v->mode&8) { //compressed PCM (maybe correct...) /* Loop for enough to fill sample buffer as requested */ for(j=0;j<length;j++) { offset += delta; cnt = (offset>>16)&0x7fff; offset &= 0xffff; pos+=cnt; //for(;cnt>0;cnt--) { /* Check for the end of the sample */ if(pos >= sz) { /* Check if its a looping sample, either stop or loop */ if(v->mode&0x10) { pos = (v->sample_loop - st); } else { v->key=0; break; } } /* Read the chosen sample byte */ dt=pSampleData[pos]; /* decompress to 13bit range */ //2000.06.26 CAB sdt=dt>>3; //signed if(sdt<0) sdt = (sdt<<(dt&7)) - pcmtbl[dt&7]; else sdt = (sdt<<(dt&7)) + pcmtbl[dt&7]; prevdt=lastdt; lastdt=sdt; dltdt=(lastdt - prevdt); } /* Caclulate the sample value */ dt=((dltdt*offset)>>16)+prevdt; /* Write the data to the sample buffers */ *lmix++ +=(dt*lvol)>>(5+5); *rmix++ +=(dt*rvol)>>(5+5); } } else { /* linear 8bit signed PCM */ for(j=0;j<length;j++) { offset += delta; cnt = (offset>>16)&0x7fff; offset &= 0xffff; pos += cnt; /* Check for the end of the sample */ if(pos >= sz) { /* Check if its a looping sample, either stop or loop */ if( v->mode&0x10 ) { pos = (v->sample_loop - st); } else { v->key=0; break; } } if( cnt ) { prevdt=lastdt; lastdt=pSampleData[pos]; dltdt=(lastdt - prevdt); } /* Caclulate the sample value */ dt=((dltdt*offset)>>16)+prevdt; /* Write the data to the sample buffers */ *lmix++ +=(dt*lvol)>>5; *rmix++ +=(dt*rvol)>>5; } } /* Save positional data for next callback */ v->ptoffset=offset; v->pos=pos; v->lastdt=lastdt; v->prevdt=prevdt; v->dltdt=dltdt; } } /* render to MAME's stream buffer */ lmix = mixer_buffer_left; rmix = mixer_buffer_right; { INT16 *dest1 = buffer[0]; INT16 *dest2 = buffer[1]; for (i = 0; i < length; i++) { *dest1++ = limit(8*(*lmix++)); *dest2++ = limit(8*(*rmix++)); } } } int C140_sh_start( const struct MachineSound *msound ) { const struct C140interface *intf = (const struct C140interface *)msound->sound_interface; int vol[2]; const char *stereo_names[2] = { "C140 Left", "C140 Right" }; vol[0] = MIXER(intf->mixing_level,MIXER_PAN_LEFT); vol[1] = MIXER(intf->mixing_level,MIXER_PAN_RIGHT); sample_rate=baserate=intf->frequency; stream = stream_init_multi(2,stereo_names,vol,sample_rate,0,update_stereo); pRom=memory_region(intf->region); /* make decompress pcm table */ //2000.06.26 CAB { int i; INT32 segbase=0; for(i=0;i<8;i++) { pcmtbl[i]=segbase; //segment base value segbase += 16<<i; } } memset(REG,0,0x200 ); { int i; for(i=0;i<MAX_VOICE;i++) init_voice( &voi[i] ); } /* allocate a pair of buffers to mix into - 1 second's worth should be more than enough */ mixer_buffer_left = (INT16*)malloc(2 * sizeof(INT16)*sample_rate ); if( mixer_buffer_left ) { mixer_buffer_right = mixer_buffer_left + sample_rate; return 0; } return 1; } void C140_sh_stop( void ) { free( mixer_buffer_left ); }
20.942257
92
0.592054
[ "render" ]
8e070b139ae506d07d2e3a33a8d018005a0378f4
3,859
cpp
C++
tree/heavy_light_decomposition.cpp
KSkun/OI-Templates
a193da03a531700858fe45d455a946074bda5007
[ "WTFPL" ]
12
2018-03-30T08:44:07.000Z
2021-09-03T07:43:56.000Z
tree/heavy_light_decomposition.cpp
KSkun/OI-Templates
a193da03a531700858fe45d455a946074bda5007
[ "WTFPL" ]
null
null
null
tree/heavy_light_decomposition.cpp
KSkun/OI-Templates
a193da03a531700858fe45d455a946074bda5007
[ "WTFPL" ]
1
2018-08-09T01:39:30.000Z
2018-08-09T01:39:30.000Z
// Code by KSkun, 2018/4 #include <cstdio> #include <algorithm> #include <vector> typedef long long LL; inline char fgc() { static char buf[100000], *p1 = buf, *p2 = buf; return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2) ? EOF : *p1++; } inline LL readint() { register LL res = 0, neg = 1; char c = fgc(); while(c < '0' || c > '9') { if(c == '-') neg = -1; c = fgc(); } while(c >= '0' && c <= '9') { res = res * 10 + c - '0'; c = fgc(); } return res * neg; } const int MAXN = 100005; int n, m, r, p, dfn[MAXN], ptn[MAXN], w[MAXN]; std::vector<int> gra[MAXN]; // Segment Tree #define lch o << 1 #define rch (o << 1) | 1 #define mid ((l + r) >> 1) LL val[MAXN << 2], tag[MAXN << 2]; inline void pushdown(int o, int l, int r) { if(tag[o]) { tag[lch] = (tag[lch] + tag[o]) % p; tag[rch] = (tag[rch] + tag[o]) % p; val[lch] = (val[lch] + tag[o] * (mid - l + 1) % p) % p; val[rch] = (val[rch] + tag[o] * (r - mid) % p) % p; tag[o] = 0; } } inline void merge(int o) { val[o] = (val[lch] + val[rch]) % p; } inline void build(int o, int l, int r) { if(l == r) { val[o] = w[ptn[l]]; return; } build(lch, l, mid); build(rch, mid + 1, r); merge(o); } inline void add(int o, int l, int r, int ll, int rr, LL v) { if(l >= ll && r <= rr) { val[o] = (val[o] + v * (r - l + 1) % p) % p; tag[o] = (tag[o] + v) % p; return; } pushdown(o, l, r); if(ll <= mid) add(lch, l, mid, ll, rr, v); if(rr > mid) add(rch, mid + 1, r, ll, rr, v); merge(o); } inline LL query(int o, int l, int r, int ll, int rr) { if(l >= ll && r <= rr) { return val[o]; } pushdown(o, l, r); LL res = 0; if(ll <= mid) res = (res + query(lch, l, mid, ll, rr)) % p; if(rr > mid) res = (res + query(rch, mid + 1, r, ll, rr)) % p; return res; } int fa[MAXN], siz[MAXN], dep[MAXN], top[MAXN], son[MAXN], clk; /* * Collect tree info. */ inline void dfs1(int u) { siz[u] = 1; for(int v : gra[u]) { if(v == fa[u]) continue; fa[v] = u; dep[v] = dep[u] + 1; dfs1(v); siz[u] += siz[v]; if(siz[v] > siz[son[u]]) son[u] = v; } } /* * Give every node number. */ inline void dfs2(int u, int tp) { dfn[u] = ++clk; ptn[dfn[u]] = u; top[u] = tp; if(son[u]) { dfs2(son[u], tp); } for(int v : gra[u]) { if(v == fa[u] || v == son[u]) continue; dfs2(v, v); } } inline void add(int x, int y, LL z) { int tx = top[x], ty = top[y]; while(tx != ty) { if(dep[tx] > dep[ty]) { std::swap(x, y); std::swap(tx, ty); } add(1, 1, n, dfn[ty], dfn[y], z); y = fa[ty]; ty = top[y]; } if(dep[x] > dep[y]) { std::swap(x, y); } add(1, 1, n, dfn[x], dfn[y], z); } // Path function inline LL query(int x, int y) { int tx = top[x], ty = top[y]; LL res = 0; while(tx != ty) { if(dep[tx] > dep[ty]) { std::swap(x, y); std::swap(tx, ty); } res = (res + query(1, 1, n, dfn[ty], dfn[y])) % p; y = fa[ty]; ty = top[y]; } if(dep[x] > dep[y]) { std::swap(x, y); } res = (res + query(1, 1, n, dfn[x], dfn[y])) % p; return res; } // Sub-tree function inline void add(int x, LL z) { add(1, 1, n, dfn[x], dfn[x] + siz[x] - 1, z); } inline LL query(int x) { return query(1, 1, n, dfn[x], dfn[x] + siz[x] - 1); } // an example of HLD // can pass luogu p3384 int op, x, y, z; int main() { n = readint(); m = readint(); r = readint(); p = readint(); for(int i = 1; i <= n; i++) w[i] = readint(); for(int i = 1; i < n; i++) { x = readint(); y = readint(); gra[x].push_back(y); gra[y].push_back(x); } dfs1(r); dfs2(r, r); build(1, 1, n); while(m--) { op = readint(); x = readint(); if(op <= 2) y = readint(); if(op == 1 || op == 3) z = readint(); switch(op) { case 1: add(x, y, z); break; case 2: printf("%lld\n", query(x, y)); break; case 3: add(x, z); break; case 4: printf("%lld\n", query(x)); } } return 0; }
18.73301
93
0.491837
[ "vector" ]
8e0b64b6127402df10d52d28b5bce23472b287ff
1,172
cpp
C++
day-2.cpp
EcutDavid/advent-of-code-2020
ee5e5386e4854224312880e8fdbb1ac11d920fe8
[ "MIT" ]
null
null
null
day-2.cpp
EcutDavid/advent-of-code-2020
ee5e5386e4854224312880e8fdbb1ac11d920fe8
[ "MIT" ]
null
null
null
day-2.cpp
EcutDavid/advent-of-code-2020
ee5e5386e4854224312880e8fdbb1ac11d920fe8
[ "MIT" ]
1
2020-12-01T09:00:46.000Z
2020-12-01T09:00:46.000Z
#include <bits/stdc++.h> using namespace std; typedef int i32; i32 main() { vector<string> strs; string str; i32 total = 0; // Q1 // while (cin >> str) { // strs.push_back(str); // if (strs.size() < 3) { // continue; // } // i32 l = stoi(strs[0].substr(0, strs[0].find("-"))); // i32 r = stoi(strs[0].substr(strs[0].find("-") + 1)); // char target = strs[1][0]; // i32 sum = 0; // for (char c : strs[2]) { // if (c == target) { // sum++; // } // } // total += (sum >= l) && (sum <= r); // strs.clear(); // } // cout << "Answer for Q1: " << total << endl; // Q2 total = 0; while (cin >> str) { strs.push_back(str); if (strs.size() < 3) { continue; } i32 l = stoi(strs[0].substr(0, strs[0].find("-"))); i32 r = stoi(strs[0].substr(strs[0].find("-") + 1)); char target = strs[1][0]; if (l > strs[2].size() || r > strs[2].size()) continue; total += (strs[2][l - 1] == target) && (strs[2][r - 1] != target) || (strs[2][l - 1] != target) && (strs[2][r - 1] == target); strs.clear(); } cout << "Answer for Q2: " << total << endl; }
23.918367
69
0.456485
[ "vector" ]
8e0d4cbfdcee1dca7d88400a41b9fc2eef90186a
581
cpp
C++
lang/C++/sum-of-squares-1.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
5
2021-01-29T20:08:05.000Z
2022-03-22T06:16:05.000Z
lang/C++/sum-of-squares-1.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
null
null
null
lang/C++/sum-of-squares-1.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
1
2021-04-13T04:19:31.000Z
2021-04-13T04:19:31.000Z
#include <iostream> #include <numeric> #include <vector> double add_square(double prev_sum, double new_val) { return prev_sum + new_val*new_val; } double vec_add_squares(std::vector<double>& v) { return std::accumulate(v.begin(), v.end(), 0.0, add_square); } int main() { // first, show that for empty vectors we indeed get 0 std::vector<double> v; // empty std::cout << vec_add_squares(v) << std::endl; // now, use some values double data[] = { 0, 1, 3, 1.5, 42, 0.1, -4 }; v.assign(data, data+7); std::cout << vec_add_squares(v) << std::endl; return 0; }
21.518519
62
0.650602
[ "vector" ]
8e10a9f624875719ef9c8ed8d3a1b9fff389d60a
3,916
hh
C++
src/include/utils/b64.hh
spuriousdata/hush
978d6ad23ad771b90d0e4178fd87822049880b64
[ "MIT" ]
null
null
null
src/include/utils/b64.hh
spuriousdata/hush
978d6ad23ad771b90d0e4178fd87822049880b64
[ "MIT" ]
null
null
null
src/include/utils/b64.hh
spuriousdata/hush
978d6ad23ad771b90d0e4178fd87822049880b64
[ "MIT" ]
null
null
null
#ifndef B64_HH_ #define B64_HH_ #include <cstdint> #include <stdexcept> #include <algorithm> // transform, toupper #include "crypto/ciphertext.hh" #define BETWEEN(x, a, b) ((x) >= (a) && (x) <= (b)) namespace hush { namespace utils { class B64Exception : public std::runtime_error { using std::runtime_error::runtime_error; using std::runtime_error::what; }; // T should be some kind of vector<unsigned char> // R should be some kind of string template<class T, class R> class B64 { public: R const encode(T const & in) const { R out; uint8_t a, b, c, oa, ob, oc, od; int pad = 0; for (auto it = in.cbegin(); it != in.cend() && pad == 0; it += 3) { a = *it; if ((it+1) == in.end()) { b = c = 0; pad = 2; } else if ((it+2) == in.end()) { b = *(it+1); c = 0; pad = 1; } else { b = *(it+1); c = *(it+2); } oa = (a & 0xFC) >> 2; ob = ((a & 0x03) << 4) | ((b & 0xF0) >> 4); oc = ((b & 0x0F) << 2) | ((c & 0xC0) >> 6); od = c & 0x3F; out.push_back(b64chars[oa]); out.push_back(b64chars[ob]); if (pad == 2) { out.append("=="); } else if (pad == 1) { out.push_back(b64chars[oc]); out.append("="); } else { out.push_back(b64chars[oc]); out.push_back(b64chars[od]); } } return out; }; T const decode(R const & in) const { T out; typename T::value_type item; int8_t a, b, c, d; for (auto it = in.cbegin(); it != in.cend(); it += 4) { a = decode_byte(*it); b = decode_byte(*(it+1)); c = decode_byte(*(it+2)); d = decode_byte(*(it+3)); if (c == -1) c = 0; item = (a << 2) | ((b & 0x30) >> 4); out.push_back(item); item = ((b & 0x0F) << 4) | ((c & 0x3C) >> 2); if (item != 0) out.push_back(item); if (d != -1) out.push_back(((c & 0x03) << 6) | d); } return out; }; R const encode(hush::crypto::CipherText const & ct) const { R out; out.append(encode(ct.get_nonce())); out.append(encode(ct.get_data())); return out; }; R const encode(R const & in) const { T vec(in.begin(), in.end()); return encode(vec); } R const pemify(R const & in, char const *keytype) const { std::string k = keytype; return pemify(in, k); } R const pemify(R const & in, std::string const & keytype) const { R out; int linelen = 0; std::string kt = keytype; std::transform(kt.begin(), kt.end(), kt.begin(), ::toupper); out = "-----BEGIN SODIUM "+ kt + " KEY-----\r\n"; for (auto it = in.cbegin(); it != in.cend(); it++) { out.push_back(*it); if (++linelen == 64) { linelen = 0; out.append("\r\n"); } } if (linelen != 0) out.append("\r\n"); out.append("-----END SODIUM " + kt + " KEY-----"); return out; }; R const unpemify(R const & in) const { R out; size_t pos; std::string marker = "-----"; if (in.find(marker) != 0) throw B64Exception("Bad PEM data, can't unencode"); out = in.substr(in.find("\r\n")+2, in.rfind("\r\n")); while ((pos = out.find("\r\n")) != -1) out.replace(pos, 2, ""); return out.substr(0, out.find(marker)); }; int const decode_byte(char x) const { if (BETWEEN(x, 'A', 'Z')) { return x - 'A'; } else if (BETWEEN(x, 'a', 'z')) { return (x - 'a') + 26; } else if (BETWEEN(x, '0', '9')) { return (x - '0') + 52; } else if (x == '+') { return 62; } else if (x == '/') { return 63; } else if (x == '=') { return -1; } else { throw B64Exception("Invalid Base 64 Character!"); } }; private: char const *b64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; }; }; }; #endif /* B64_HH_ */
21.755556
93
0.493871
[ "vector", "transform" ]
8e17365a803082f4a960416075a455626c233680
18,149
cpp
C++
src/ir/instruction.cpp
hobama/maat
3f0a7d3ef90fff3f1c465d0ae155488b245981b4
[ "MIT" ]
2
2020-03-23T06:47:19.000Z
2021-03-07T21:14:24.000Z
src/ir/instruction.cpp
hobama/maat
3f0a7d3ef90fff3f1c465d0ae155488b245981b4
[ "MIT" ]
null
null
null
src/ir/instruction.cpp
hobama/maat
3f0a7d3ef90fff3f1c465d0ae155488b245981b4
[ "MIT" ]
null
null
null
#include "instruction.hpp" #include "exception.hpp" #include <iostream> /* ===================================== */ bool iroperation_is_assignment(IROperation& op){ return op == IROperation::ADD || op == IROperation::SUB || op == IROperation::MUL || op == IROperation::MULH || op == IROperation::SMULL || op == IROperation::SMULH || op == IROperation::DIV || op == IROperation::SDIV || op == IROperation::SHL || op == IROperation::SHR || op == IROperation::NEG || op == IROperation::AND || op == IROperation::OR || op == IROperation::XOR || op == IROperation::NOT || op == IROperation::MOD || op == IROperation::SMOD || op == IROperation::MOV || op == IROperation::CONCAT; } bool iroperation_is_memory(IROperation& op){ return op == IROperation::STM || op == IROperation::LDM ; } ostream& operator<<(ostream& os, IROperation& op){ switch(op){ case IROperation::ADD: os << "ADD"; break; case IROperation::SUB: os << "SUB"; break; case IROperation::MUL: os << "MUL"; break; case IROperation::MULH: os << "MUL(h)"; break; case IROperation::SMULL: os << "SMUL(l)"; break; case IROperation::SMULH: os << "SMUL(h)"; break; case IROperation::DIV: os << "DIV"; break; case IROperation::SDIV: os << "SDIV"; break; case IROperation::SHL: os << "SHL"; break; case IROperation::SHR: os << "SHR"; break; case IROperation::NEG: os << "NEG"; break; case IROperation::AND: os << "AND"; break; case IROperation::OR: os << "OR"; break; case IROperation::XOR: os << "XOR"; break; case IROperation::NOT: os << "NOT"; break; case IROperation::MOV: os << "MOV"; break; case IROperation::MOD: os << "MOD"; break; case IROperation::SMOD: os << "MOD"; break; case IROperation::STM: os << "STM"; break; case IROperation::LDM: os << "LDM"; break; case IROperation::BCC: os << "BCC"; break; case IROperation::JCC: os << "JCC"; break; case IROperation::BISZ: os << "BISZ"; break; case IROperation::CONCAT: os << "CONCAT"; break; case IROperation::INT: os << "INT"; break; case IROperation::SYSCALL: os << "SYSCALL"; break; default: os << "???"; break; } return os; } /* ===================================== */ IROperand::IROperand(): type(IROperandType::NONE), _val(0), high(0), low(0), size(0){} IROperand::IROperand(IROperandType t, cst_t cst, exprsize_t h, exprsize_t l): type(t), _val(cst_sign_extend(sizeof(cst_t)*8, cst)), high(h), low(l), size(h-l+1){} bool IROperand::is_cst(){ return type == IROperandType::CST; } bool IROperand::is_var(){ return type == IROperandType::VAR; } bool IROperand::is_tmp(){ return type == IROperandType::TMP; } bool IROperand::is_none(){ return type == IROperandType::NONE; } cst_t IROperand::cst(){ return _val; } IRVar IROperand::var(){ return (IRVar)_val;} IRVar IROperand::tmp(){return (IRVar)_val;} ostream& operator<<(ostream& os, IROperand& op){ switch(op.type){ case IROperandType::CST: os << op.cst(); break; case IROperandType::TMP: os << "TMP_" << op.tmp(); break; case IROperandType::VAR: os << "VAR_" << op.var(); break; case IROperandType::NONE: os << "_" ; break; } os << "[" << op.high << ":" << op.low << "]"; return os; } /* Helpers to create operands */ IROperand ir_cst(cst_t val, exprsize_t high, exprsize_t low){ return IROperand(IROperandType::CST, val, high, low); } IROperand ir_var(cst_t num, exprsize_t high, exprsize_t low){ return IROperand(IROperandType::VAR, num, high, low); } IROperand ir_tmp(cst_t num, exprsize_t high, exprsize_t low){ return IROperand(IROperandType::TMP, num, high, low); } IROperand ir_none(){ return IROperand(); } /* ===================================== */ IRInstruction::IRInstruction(IROperation _op, IROperand _dst, IROperand _src1, addr_t a){ op = _op; dst = _dst; src1 = _src1; src2 = IROperand(); addr = a; } IRInstruction::IRInstruction(IROperation _op, IROperand _dst, IROperand _src1, IROperand _src2, addr_t a){ op = _op; dst = _dst; src1 = _src1; src2 = _src2; addr = a; } bool IRInstruction::reads_var(IRVar var){ if( iroperation_is_assignment(op)){ return (src1.is_var() && src1.var() == var) || (src2.is_var() && src2.var() == var); }else if( iroperation_is_memory(op)){ return (dst.is_var() && dst.var() == var) || (src1.is_var() && src1.var() == var) || (src2.is_var() && src2.var() == var); }else if( op == IROperation::BCC || op == IROperation::JCC){ return (dst.is_var() && dst.var() == var) || (src1.is_var() && src1.var() == var) || (src2.is_var() && src2.var() == var); }else if( op == IROperation::BISZ ){ return src1.is_var() && src1.var() == var; }else{ throw runtime_exception("IRInstruction::reads_var() got unknown IROperation"); } } bool IRInstruction::writes_var(IRVar var){ if( iroperation_is_assignment(op)){ return (dst.is_var() && dst.var() == var); }else if( iroperation_is_memory(op)){ return false; }else if( op == IROperation::BCC || op == IROperation::JCC){ return false; }else if( op == IROperation::BISZ){ return (dst.is_var() && dst.var() == var); }else{ throw runtime_exception("IRInstruction::writes_var() got unknown IROperation"); } } bool IRInstruction::uses_var(IRVar var){ return reads_var(var) || writes_var(var); } bool IRInstruction::reads_tmp(IRVar tmp){ if( iroperation_is_assignment(op)){ return (src1.is_tmp() && src1.tmp() == tmp) || (src2.is_tmp() && src2.tmp() == tmp); }else if( iroperation_is_memory(op)){ return (dst.is_tmp() && dst.tmp() == tmp) || (src1.is_tmp() && src1.tmp() == tmp) || (src2.is_tmp() && src2.tmp() == tmp); }else if( op == IROperation::BCC || op == IROperation::JCC){ return (dst.is_tmp() && dst.tmp() == tmp) || (src1.is_tmp() && src1.tmp() == tmp) || (src2.is_tmp() && src2.tmp() == tmp); }else if( op == IROperation::BISZ ){ return src1.is_tmp() && src1.tmp() == tmp; }else{ throw runtime_exception("IRInstruction::reads_tmp() got unknown IROperation"); } } bool IRInstruction::writes_tmp(IRVar tmp){ if( iroperation_is_assignment(op)){ return (dst.is_tmp() && dst.tmp() == tmp); }else if( iroperation_is_memory(op)){ return false; }else if( op == IROperation::BCC || op == IROperation::JCC){ return false; }else if( op == IROperation::BISZ){ return (dst.is_tmp() && dst.tmp() == tmp); }else{ throw runtime_exception("IRInstruction::writes_tmp() got unknown IROperation"); } } vector<IROperand> IRInstruction::used_vars_read(){ vector<IROperand> res; if( iroperation_is_assignment(op)){ if(src1.is_var()) res.push_back(src1); if( src2.is_var()) res.push_back(src2); }else if( iroperation_is_memory(op) || op == IROperation::BCC || op == IROperation::JCC ){ if(src1.is_var()) res.push_back(src1); if( src2.is_var()) res.push_back(src2); if( dst.is_var() ) res.push_back(dst); }else if( op == IROperation::BISZ ){ if(src1.is_var()) res.push_back(src1); }else if( op == IROperation::INT || op == IROperation::SYSCALL){ // Ignore }else{ throw runtime_exception("IRInstruction::used_vars_read() got unknown IROperation"); } return res; } vector<IROperand> IRInstruction::used_vars_write(){ vector<IROperand> res; if( iroperation_is_assignment(op) || op == IROperation::LDM || op == IROperation::BISZ){ if(dst.is_var()) res.push_back(dst); }else if( op == IROperation::STM || op == IROperation::BCC || op == IROperation::JCC || op == IROperation::INT || op == IROperation::SYSCALL ){ // Ignore those even if they rewrite pc }else{ throw runtime_exception("IRInstruction::used_vars_write() got unknown IROperation"); } return res; } vector<IROperand> IRInstruction::used_tmps_read(){ vector<IROperand> res; if( iroperation_is_assignment(op)){ if(src1.is_tmp()) res.push_back(src1); if( src2.is_tmp()) res.push_back(src2); }else if( iroperation_is_memory(op) || op == IROperation::BCC || op == IROperation::JCC || op == IROperation::INT ){ if(src1.is_tmp()) res.push_back(src1); if( src2.is_tmp()) res.push_back(src2); if( dst.is_tmp() ) res.push_back(dst); }else if( op == IROperation::BISZ ){ if(src1.is_tmp()) res.push_back(src1); }else if( op == IROperation::SYSCALL ){ if( src1.is_tmp() ) res.push_back(src1); }else{ throw runtime_exception("IRInstruction::used_tmps_read() got unknown IROperation"); } return res; } vector<IROperand> IRInstruction::used_tmps_write(){ vector<IROperand> res; if( iroperation_is_assignment(op)){ if(dst.is_tmp()) res.push_back(dst); }else if( iroperation_is_memory(op) || op == IROperation::BCC || op == IROperation::JCC || op == IROperation::INT || op == IROperation::SYSCALL){ // Ignore }else if( op == IROperation::BISZ ){ if(dst.is_tmp()) res.push_back(dst); }else{ throw runtime_exception("IRInstruction::used_tmps_write() got unknown IROperation"); } return res; } ostream& operator<<(ostream& os, IRInstruction& ins){ os << "(0x" << std::hex << ins.addr << ")"; os << "\t" << ins.op << "\t"; if( ins.op == IROperation::BCC ){ os << ins.dst << ",\tbblk_" << ins.src1.cst(); if( !ins.src2.is_none()){ os << ",\t\tbblk_" << ins.src2.cst(); } }else{ os << ins.dst << ",\t" << ins.src1; if( !ins.src2.is_none()){ os << ",\t" << ins.src2; } } os << std::endl; return os; } /* Helpers to create instructions */ IRInstruction ir_add(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::ADD, dst, src1, src2, addr); } IRInstruction ir_sub(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::SUB, dst, src1, src2, addr); } IRInstruction ir_mul(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::MUL, dst, src1, src2, addr); } IRInstruction ir_mulh(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::MULH, dst, src1, src2, addr); } IRInstruction ir_smull(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::SMULL, dst, src1, src2, addr); } IRInstruction ir_smulh(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::SMULH, dst, src1, src2, addr); } IRInstruction ir_div(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::DIV, dst, src1, src2, addr); } IRInstruction ir_sdiv(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::SDIV, dst, src1, src2, addr); } IRInstruction ir_and(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::AND, dst, src1, src2, addr); } IRInstruction ir_or(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::OR, dst, src1, src2, addr); } IRInstruction ir_xor(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::XOR, dst, src1, src2, addr); } IRInstruction ir_shl(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::SHL, dst, src1, src2, addr); } IRInstruction ir_shr(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::SHR, dst, src1, src2, addr); } IRInstruction ir_mod(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::MOD, dst, src1, src2, addr); } IRInstruction ir_smod(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::SMOD, dst, src1, src2, addr); } IRInstruction ir_neg(IROperand dst, IROperand src1, addr_t addr){ return IRInstruction(IROperation::NEG, dst, src1, addr); } IRInstruction ir_not(IROperand dst, IROperand src1, addr_t addr){ return IRInstruction(IROperation::NOT, dst, src1, addr); } IRInstruction ir_ldm(IROperand dst, IROperand src1, addr_t addr){ return IRInstruction(IROperation::LDM, dst, src1, addr); } IRInstruction ir_stm(IROperand dst, IROperand src1, addr_t addr){ return IRInstruction(IROperation::STM, dst, src1, addr); } IRInstruction ir_mov(IROperand dst, IROperand src1, addr_t addr){ return IRInstruction(IROperation::MOV, dst, src1, addr); } IRInstruction ir_bcc(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::BCC, dst, src1, src2, addr); } IRInstruction ir_jcc(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::JCC, dst, src1, src2, addr); } IRInstruction ir_bisz(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::BISZ, dst, src1, src2, addr); } IRInstruction ir_concat(IROperand dst, IROperand src1, IROperand src2, addr_t addr){ return IRInstruction(IROperation::CONCAT, dst, src1, src2, addr); } IRInstruction ir_int(IROperand num, IROperand ret, addr_t addr){ return IRInstruction(IROperation::INT, num, ret, addr); } IRInstruction ir_syscall(IROperand type, IROperand ret, addr_t addr){ return IRInstruction(IROperation::SYSCALL, type, ret, addr); } /* ====================================== */ IRContext::IRContext(VarContext* varctx):_var(nullptr), _nb_var(0), _varctx(varctx){} IRContext::IRContext(IRVar nb_var, VarContext* varctx){ _var = new Expr[nb_var]{nullptr}; _nb_var = nb_var; _varctx = varctx; } IRContext::~IRContext(){ delete [] _var; _var = nullptr; } int IRContext::nb_vars(){ return _nb_var; } void IRContext::set(IRVar num, Expr e){ if( num >= _nb_var ){ throw ir_exception("IRContext::set(): Invalid register argument"); } _var[num] = e; } Expr IRContext::get(IRVar num){ if( num >= _nb_var ){ throw ir_exception("IRContext::get(): Invalid register argument"); } return _var[num]; } cst_t IRContext::concretize(IRVar num, VarContext* varctx){ if( num >= _nb_var ){ throw ir_exception("IRContext::concretize(): Invalid register argument"); } if( varctx == nullptr ){ if( _varctx == nullptr ){ throw runtime_exception("IRContext::concretize(): called with null VarContext"); } return _var[num]->concretize(_varctx); }else{ return _var[num]->concretize(varctx); } } cst_t IRContext::as_signed(IRVar num, VarContext* varctx){ return concretize(num, varctx); } cst_t IRContext::as_unsigned(IRVar num, VarContext* varctx){ if( num >= _nb_var ){ throw ir_exception("IRContext::as_unsigned(): Invalid register argument"); } if( varctx == nullptr ){ if( _varctx == nullptr ){ throw runtime_exception("IRContext::as_unsigned(): called with null VarContext"); } return cst_sign_trunc(_var[num]->size, _var[num]->concretize(_varctx)); }else{ return cst_sign_trunc(_var[num]->size, _var[num]->concretize(varctx)); } } // Make purely symbolic (replace the expression) string IRContext::make_symbolic(IRVar num, string name){ if( num >= _nb_var ){ throw ir_exception("IRContext::make_symbolic(): Invalid register argument"); } else if( _varctx == nullptr ){ throw runtime_exception("IRContext::make_symbolic(): called with null VarContext"); } // We don't want the supplied name to correspond to an existing variable so use // new_name_from :) string new_name = _varctx->new_name_from(name); _var[num] = exprvar(_var[num]->size, new_name); return new_name; } // Make the expression tainted :) void IRContext::make_tainted(IRVar num){ if( num >= _nb_var ){ throw ir_exception("IRContext::make_tainted(): Invalid register argument"); } _var[num]->make_tainted(); } // Represent the register by a simple var (but keep its concrete value) string IRContext::make_var(IRVar num, string name){ if( num >= _nb_var ){ throw ir_exception("IRContext::make_var(): Invalid register argument"); } else if( _varctx == nullptr ){ throw runtime_exception("IRContext::make_var(): called with null VarContext"); } // We don't want the supplied name to correspond to an existing variable so use // new_name_from :) string new_name = _varctx->new_name_from(name); // First we save the concrete value of the register in the VarContext _varctx->set(new_name, _var[num]->concretize(_varctx)); _var[num] = exprvar(_var[num]->size, new_name); return new_name; } void IRContext::copy_from(IRContext& other){ for( int i = 0; i < _nb_var; i++){ _var[i] = other._var[i]; } } IRContext* IRContext::copy(){ IRContext* res = new IRContext(_nb_var); res->copy_from(*this); return res; } ostream& operator<<(ostream& os, IRContext& ctx){ for( int i = 0; i < ctx.nb_vars(); i++){ os << "Var_" << i << " : " << ctx.get(i) << std::endl; } return os; } /* ====================================== */
37.420619
147
0.618657
[ "vector" ]
8e18b7d068e301cdaed3fc6eb2be060bf2ce10e0
11,682
hpp
C++
include/VROSC/ThereminParticles_Hand.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/VROSC/ThereminParticles_Hand.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/VROSC/ThereminParticles_Hand.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: VROSC.ThereminParticles #include "VROSC/ThereminParticles.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: ParticleSystemForceField class ParticleSystemForceField; } // Forward declaring namespace: VROSC namespace VROSC { // Forward declaring type: InputDevice class InputDevice; // Forward declaring type: ControllerInputNode class ControllerInputNode; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; } // Completed forward declares #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::VROSC::ThereminParticles::Hand); DEFINE_IL2CPP_ARG_TYPE(::VROSC::ThereminParticles::Hand*, "VROSC", "ThereminParticles/Hand"); // Type namespace: VROSC namespace VROSC { // Size: 0x48 #pragma pack(push, 1) // Autogenerated type: VROSC.ThereminParticles/VROSC.Hand // [TokenAttribute] Offset: FFFFFFFF class ThereminParticles::Hand : public ::Il2CppObject { public: public: // private UnityEngine.ParticleSystemForceField _forceField // Size: 0x8 // Offset: 0x10 ::UnityEngine::ParticleSystemForceField* forceField; // Field size check static_assert(sizeof(::UnityEngine::ParticleSystemForceField*) == 0x8); // private System.Boolean _isLeft // Size: 0x1 // Offset: 0x18 bool isLeft; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: isLeft and: inputDevice char __padding1[0x7] = {}; // private VROSC.InputDevice _inputDevice // Size: 0x8 // Offset: 0x20 ::VROSC::InputDevice* inputDevice; // Field size check static_assert(sizeof(::VROSC::InputDevice*) == 0x8); // private System.Boolean _isHandInside // Size: 0x1 // Offset: 0x28 bool isHandInside; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean _isPlaying // Size: 0x1 // Offset: 0x29 bool isPlaying; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: isPlaying and: initialEndRange char __padding4[0x2] = {}; // private System.Single _initialEndRange // Size: 0x4 // Offset: 0x2C float initialEndRange; // Field size check static_assert(sizeof(float) == 0x4); // private VROSC.ControllerInputNode _input // Size: 0x8 // Offset: 0x30 ::VROSC::ControllerInputNode* input; // Field size check static_assert(sizeof(::VROSC::ControllerInputNode*) == 0x8); // private System.Single _scaling // Size: 0x4 // Offset: 0x38 float scaling; // Field size check static_assert(sizeof(float) == 0x4); // Padding between fields: scaling and: players char __padding7[0x4] = {}; // private System.Collections.Generic.List`1<System.Object> _players // Size: 0x8 // Offset: 0x40 ::System::Collections::Generic::List_1<::Il2CppObject*>* players; // Field size check static_assert(sizeof(::System::Collections::Generic::List_1<::Il2CppObject*>*) == 0x8); public: // Get instance field reference: private UnityEngine.ParticleSystemForceField _forceField [[deprecated("Use field access instead!")]] ::UnityEngine::ParticleSystemForceField*& dyn__forceField(); // Get instance field reference: private System.Boolean _isLeft [[deprecated("Use field access instead!")]] bool& dyn__isLeft(); // Get instance field reference: private VROSC.InputDevice _inputDevice [[deprecated("Use field access instead!")]] ::VROSC::InputDevice*& dyn__inputDevice(); // Get instance field reference: private System.Boolean _isHandInside [[deprecated("Use field access instead!")]] bool& dyn__isHandInside(); // Get instance field reference: private System.Boolean _isPlaying [[deprecated("Use field access instead!")]] bool& dyn__isPlaying(); // Get instance field reference: private System.Single _initialEndRange [[deprecated("Use field access instead!")]] float& dyn__initialEndRange(); // Get instance field reference: private VROSC.ControllerInputNode _input [[deprecated("Use field access instead!")]] ::VROSC::ControllerInputNode*& dyn__input(); // Get instance field reference: private System.Single _scaling [[deprecated("Use field access instead!")]] float& dyn__scaling(); // Get instance field reference: private System.Collections.Generic.List`1<System.Object> _players [[deprecated("Use field access instead!")]] ::System::Collections::Generic::List_1<::Il2CppObject*>*& dyn__players(); // public System.Void .ctor() // Offset: 0x8DD148 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ThereminParticles::Hand* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::ThereminParticles::Hand::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<ThereminParticles::Hand*, creationType>())); } // public System.Void Setup(System.Boolean isLeft, VROSC.InputDevice inputDevice, VROSC.ControllerInputNode input) // Offset: 0x8DCAD0 void Setup(bool isLeft, ::VROSC::InputDevice* inputDevice, ::VROSC::ControllerInputNode* input); // private System.Void HoverEnd(VROSC.InputDevice inputDevice) // Offset: 0x8DCC78 void HoverEnd(::VROSC::InputDevice* inputDevice); // private System.Void HoverBegin(VROSC.InputDevice inputDevice) // Offset: 0x8DCCFC void HoverBegin(::VROSC::InputDevice* inputDevice); // public System.Void SetNewScale(System.Single scale) // Offset: 0x8DCD84 void SetNewScale(float scale); // public System.Void ObjectIsPlaying(System.Boolean playing, System.Object source) // Offset: 0x8DCDC0 void ObjectIsPlaying(bool playing, ::Il2CppObject* source); // private System.Void SetIsPlaying(System.Boolean playing) // Offset: 0x8DCC3C void SetIsPlaying(bool playing); // public System.Void Update() // Offset: 0x8DCEC8 void Update(); }; // VROSC.ThereminParticles/VROSC.Hand #pragma pack(pop) static check_size<sizeof(ThereminParticles::Hand), 64 + sizeof(::System::Collections::Generic::List_1<::Il2CppObject*>*)> __VROSC_ThereminParticles_HandSizeCheck; static_assert(sizeof(ThereminParticles::Hand) == 0x48); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: VROSC::ThereminParticles::Hand::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: VROSC::ThereminParticles::Hand::Setup // Il2CppName: Setup template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ThereminParticles::Hand::*)(bool, ::VROSC::InputDevice*, ::VROSC::ControllerInputNode*)>(&VROSC::ThereminParticles::Hand::Setup)> { static const MethodInfo* get() { static auto* isLeft = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; static auto* inputDevice = &::il2cpp_utils::GetClassFromName("VROSC", "InputDevice")->byval_arg; static auto* input = &::il2cpp_utils::GetClassFromName("VROSC", "ControllerInputNode")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ThereminParticles::Hand*), "Setup", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{isLeft, inputDevice, input}); } }; // Writing MetadataGetter for method: VROSC::ThereminParticles::Hand::HoverEnd // Il2CppName: HoverEnd template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ThereminParticles::Hand::*)(::VROSC::InputDevice*)>(&VROSC::ThereminParticles::Hand::HoverEnd)> { static const MethodInfo* get() { static auto* inputDevice = &::il2cpp_utils::GetClassFromName("VROSC", "InputDevice")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ThereminParticles::Hand*), "HoverEnd", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{inputDevice}); } }; // Writing MetadataGetter for method: VROSC::ThereminParticles::Hand::HoverBegin // Il2CppName: HoverBegin template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ThereminParticles::Hand::*)(::VROSC::InputDevice*)>(&VROSC::ThereminParticles::Hand::HoverBegin)> { static const MethodInfo* get() { static auto* inputDevice = &::il2cpp_utils::GetClassFromName("VROSC", "InputDevice")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ThereminParticles::Hand*), "HoverBegin", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{inputDevice}); } }; // Writing MetadataGetter for method: VROSC::ThereminParticles::Hand::SetNewScale // Il2CppName: SetNewScale template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ThereminParticles::Hand::*)(float)>(&VROSC::ThereminParticles::Hand::SetNewScale)> { static const MethodInfo* get() { static auto* scale = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ThereminParticles::Hand*), "SetNewScale", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{scale}); } }; // Writing MetadataGetter for method: VROSC::ThereminParticles::Hand::ObjectIsPlaying // Il2CppName: ObjectIsPlaying template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ThereminParticles::Hand::*)(bool, ::Il2CppObject*)>(&VROSC::ThereminParticles::Hand::ObjectIsPlaying)> { static const MethodInfo* get() { static auto* playing = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; static auto* source = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ThereminParticles::Hand*), "ObjectIsPlaying", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{playing, source}); } }; // Writing MetadataGetter for method: VROSC::ThereminParticles::Hand::SetIsPlaying // Il2CppName: SetIsPlaying template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ThereminParticles::Hand::*)(bool)>(&VROSC::ThereminParticles::Hand::SetIsPlaying)> { static const MethodInfo* get() { static auto* playing = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ThereminParticles::Hand*), "SetIsPlaying", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{playing}); } }; // Writing MetadataGetter for method: VROSC::ThereminParticles::Hand::Update // Il2CppName: Update template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ThereminParticles::Hand::*)()>(&VROSC::ThereminParticles::Hand::Update)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::ThereminParticles::Hand*), "Update", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
51.0131
213
0.725817
[ "object", "vector" ]
8e1a1305ada3eaae82c48f6b9baadc68b8409f99
40,044
cpp
C++
src/OpenGLAutoMaskObj/OpenGL_Auto_Obj_Masker/EasyMask2D.cpp
565353780/opengl-automaskobj
bae7c35a0aece5a09ec67b02241aff58932c6daf
[ "MIT" ]
null
null
null
src/OpenGLAutoMaskObj/OpenGL_Auto_Obj_Masker/EasyMask2D.cpp
565353780/opengl-automaskobj
bae7c35a0aece5a09ec67b02241aff58932c6daf
[ "MIT" ]
null
null
null
src/OpenGLAutoMaskObj/OpenGL_Auto_Obj_Masker/EasyMask2D.cpp
565353780/opengl-automaskobj
bae7c35a0aece5a09ec67b02241aff58932c6daf
[ "MIT" ]
null
null
null
#include "EasyMask2D.h" bool EasyMask2D::getUnionPolygonVec( std::vector<EasyPolygon2D> &polygon_vec, std::vector<EasyPolygon2D> &union_polygon_vec) { union_polygon_vec.clear(); std::vector<EasyPolygon2D> valid_polygon_vec; for(const EasyPolygon2D &polygon : polygon_vec) { if(polygon.point_list.size() > 0) { valid_polygon_vec.emplace_back(polygon); } } if(valid_polygon_vec.size() == 0) { return true; } if(valid_polygon_vec.size() == 1) { union_polygon_vec.emplace_back(valid_polygon_vec[0]); return true; } std::vector<EasyIntersection2D> intersection_vec; getPolygonIntersection(valid_polygon_vec, intersection_vec); std::vector<EasyPolygon2D> split_polygon_vec; std::vector<EasyIntersection2D> split_intersection_vec; splitPolygonsByIntersection( intersection_vec, valid_polygon_vec, split_intersection_vec, split_polygon_vec); size_t connected_polygon_point_num = 0; size_t total_polygon_point_num = 0; std::vector<std::vector<bool>> polygon_point_connected_vec_vec; polygon_point_connected_vec_vec.resize(split_polygon_vec.size()); for(size_t i = 0; i < split_polygon_vec.size(); ++i) { polygon_point_connected_vec_vec[i].resize(split_polygon_vec[i].point_list.size(), false); total_polygon_point_num += split_polygon_vec[i].point_list.size(); } while(connected_polygon_point_num < total_polygon_point_num) { EasyPolygon2D current_union_polygon; float x_min; float y_max; int current_start_polygon_idx = -1; int current_start_point_idx = -1; for(size_t i = 0; i < split_polygon_vec.size(); ++i) { EasyPolygon2D &split_polygon = split_polygon_vec[i]; for(size_t j = 0; j < split_polygon.point_list.size(); ++j) { EasyPoint2D &polygon_point = split_polygon.point_list[j]; if(!polygon_point_connected_vec_vec[i][j]) { if(current_start_polygon_idx == -1) { x_min = polygon_point.x; y_max = polygon_point.y; current_start_polygon_idx = i; current_start_point_idx = j; } else if(polygon_point.x < x_min) { x_min = polygon_point.x; current_start_polygon_idx = i; current_start_point_idx = j; } else if(polygon_point.x == x_min) { if(polygon_point.y > y_max) { y_max = polygon_point.y; current_start_polygon_idx = i; current_start_point_idx = j; } } } } } if(true) { for(size_t i = 0; i < split_polygon_vec.size(); ++i) { const EasyPolygon2D &split_polygon = split_polygon_vec[i]; std::cout << "current polygon " << i << " :" << std::endl << "points :" << std::endl; for(int j = 0; j < split_polygon.point_list.size(); ++j) { std::cout << "\t" << j << " : [" << split_polygon.point_list[j].x << "," << split_polygon.point_list[j].y << "]" << std::endl; } } std::cout << "current intersection:" << std::endl; for(int i = 0; i < split_intersection_vec.size(); ++i) { std::cout << "points :" << std::endl; std::cout << "\t" << i << " : [" << split_intersection_vec[i].point.x << "," << split_intersection_vec[i].point.y << "]" << std::endl; std::cout << "idx :" << std::endl; for(int j = 0; j < split_intersection_vec[i].polygon_point_idx_vec_pair_vec.size(); ++j) { const auto &polygon_line_idx_vec_pair = split_intersection_vec[i].polygon_point_idx_vec_pair_vec[j]; std::cout << "\tpolygon id : " << polygon_line_idx_vec_pair.first << std::endl; std::cout << "\tpolygon line idx :"; for(int k = 0; k < polygon_line_idx_vec_pair.second.size(); ++k) { std::cout << polygon_line_idx_vec_pair.second[k] << " , "; } std::cout << std::endl; } } } int start_point_idx = current_start_point_idx; addNewPolygonPoint( split_polygon_vec, current_start_polygon_idx, current_start_point_idx, current_union_polygon, polygon_point_connected_vec_vec); std::cout << "current running at p" << current_start_polygon_idx << current_start_point_idx << std::endl; size_t intersection_idx; if(getIntersectionIdxOnPolygonPoint( split_polygon_vec, split_intersection_vec, current_start_polygon_idx, current_start_point_idx, intersection_idx)) { updatePolygonIntersectionPointConnectedState( split_intersection_vec[intersection_idx], polygon_point_connected_vec_vec); } current_start_point_idx = (current_start_point_idx + 1) % split_polygon_vec[current_start_polygon_idx].point_list.size(); std::cout << "current running at p" << current_start_polygon_idx << current_start_point_idx << std::endl; std::cout << "start running getUnionPolygonPoints" << std::endl; getUnionPolygonPoints( split_polygon_vec, split_intersection_vec, current_start_polygon_idx, start_point_idx, current_start_polygon_idx, current_start_point_idx, current_union_polygon, polygon_point_connected_vec_vec); updatePolygonNotIntersectionPointConnectedState( split_polygon_vec, current_union_polygon, polygon_point_connected_vec_vec); union_polygon_vec.emplace_back(current_union_polygon); std::cout << "current union_polygon:" << std::endl << "points :" << std::endl; for(int i = 0; i < current_union_polygon.point_list.size(); ++i) { std::cout << "\t" << i << " : [" << current_union_polygon.point_list[i].x << "," << current_union_polygon.point_list[i].y << "]" << std::endl; } connected_polygon_point_num = 0; for(const std::vector<bool> &polygon_point_connected_vec : polygon_point_connected_vec_vec) { connected_polygon_point_num += count( polygon_point_connected_vec.cbegin(), polygon_point_connected_vec.cend(), true); } std::cout << "now still have :"; for(size_t i = 0; i < polygon_point_connected_vec_vec.size(); ++i) { const auto &polygon_point_connected_vec = polygon_point_connected_vec_vec[i]; for(size_t j = 0; j < polygon_point_connected_vec.size(); ++j) { if(!polygon_point_connected_vec[j]) { std::cout << " p" << i << j; } } } std::cout << " not connected!" << std::endl; std::cout << "connected_polygon_point_num = " << connected_polygon_point_num << std::endl; std::cout << "total_polygon_point_num = " << total_polygon_point_num << std::endl; } return true; } float EasyMask2D::dot( const float &x_1, const float &y_1, const float &x_2, const float &y_2) { return x_1 * x_2 + y_1 * y_2; } float EasyMask2D::dot( const EasyLine2D &line_1, const EasyLine2D &line_2) { return dot(line_1.x_diff, line_1.y_diff, line_2.x_diff, line_2.y_diff); } float EasyMask2D::cross( const float &x_1, const float &y_1, const float &x_2, const float &y_2) { return x_1 * y_2 - x_2 * y_1; } float EasyMask2D::cross( const EasyLine2D &line_1, const EasyLine2D &line_2) { return cross(line_1.x_diff, line_1.y_diff, line_2.x_diff, line_2.y_diff); } float EasyMask2D::pointDist2( const EasyPoint2D &point_1, const EasyPoint2D &point_2) { float dist_2 = pow(point_1.x - point_2.x, 2) + pow(point_1.y - point_2.y, 2); return dist_2; } float EasyMask2D::pointDist( const EasyPoint2D &point_1, const EasyPoint2D &point_2) { return sqrt(pointDist2(point_1, point_2)); } float EasyMask2D::lineLength2( const EasyLine2D &line) { float length_2 = pow(line.x_diff, 2) + pow(line.y_diff, 2); return length_2; } float EasyMask2D::lineLength( const EasyLine2D &line) { return sqrt(lineLength2(line)); } float EasyMask2D::angle( const EasyLine2D &line_1, const EasyLine2D &line_2) { int sign = 1; float cross_value = cross(line_1, line_2); if(cross_value == 0) { return 0; } if(cross_value < 0) { sign = -1; } float dot_value = dot(line_1, line_2); float line_1_length = lineLength(line_1); float line_2_length = lineLength(line_2); float cos_value = dot_value / (line_1_length * line_2_length); float angle_value = sign * acos(cos_value); return angle_value; } float EasyMask2D::getClockWiseAngle( const EasyLine2D &line_1, const EasyLine2D &line_2) { float cross_value = cross(line_1, line_2); float anti_clock_small_angle = angle(line_1, line_2); if(cross_value > 0) { return 2.0 * M_PI - anti_clock_small_angle; } if(cross_value == 0) { if(line_1.x_diff != 0) { float x_diff_mul = line_1.x_diff * line_2.x_diff; if(x_diff_mul < 0) { return M_PI; } return 0; } if(line_1.y_diff != 0) { float y_diff_mul = line_1.y_diff * line_2.y_diff; if(y_diff_mul < 0) { return M_PI; } return 0; } return 0; } return - anti_clock_small_angle; } float EasyMask2D::getAntiClockWiseAngle( const EasyLine2D &line_1, const EasyLine2D &line_2) { float cross_value = cross(line_1, line_2); float anti_clock_small_angle = angle(line_1, line_2); if(cross_value < 0) { return 2.0 * M_PI + anti_clock_small_angle; } if(cross_value == 0) { if(line_1.x_diff != 0) { float x_diff_mul = line_1.x_diff * line_2.x_diff; if(x_diff_mul < 0) { return M_PI; } return 0; } if(line_1.y_diff != 0) { float y_diff_mul = line_1.y_diff * line_2.y_diff; if(y_diff_mul < 0) { return M_PI; } return 0; } return 0; } return anti_clock_small_angle; } bool EasyMask2D::isPointInRect( const EasyPoint2D &point, const EasyRect2D &rect) { if(point.x < rect.x_min) { return false; } if(point.x > rect.x_max) { return false; } if(point.y < rect.y_min) { return false; } if(point.y > rect.y_max) { return false; } return true; } bool EasyMask2D::isPointInLineRect( const EasyPoint2D &point, const EasyLine2D &line) { if(point.x < line.rect.x_min) { return false; } if(point.x > line.rect.x_max) { return false; } if(point.y < line.rect.y_min) { return false; } if(point.y > line.rect.y_max) { return false; } return true; } bool EasyMask2D::isRectCross( const EasyLine2D &line_1, const EasyLine2D &line_2) { if(line_1.rect.x_max < line_2.rect.x_min) { return false; } if(line_1.rect.x_min > line_2.rect.x_max) { return false; } if(line_1.rect.y_max < line_2.rect.y_min) { return false; } if(line_1.rect.y_min > line_2.rect.y_max) { return false; } return true; } bool EasyMask2D::isRectCross( const EasyRect2D &rect_1, const EasyRect2D &rect_2) { if(rect_1.x_max < rect_2.x_min) { return false; } if(rect_1.x_min > rect_2.x_max) { return false; } if(rect_1.y_max < rect_2.y_min) { return false; } if(rect_1.y_min > rect_2.y_max) { return false; } return true; } bool EasyMask2D::isLineCross( const EasyLine2D &line_1, const EasyLine2D &line_2) { if(!isRectCross(line_1, line_2)) { return false; } EasyLine2D line_22_to_11; EasyLine2D line_22_to_12; line_22_to_11.setPosition( line_2.point_2, line_1.point_1); line_22_to_12.setPosition( line_2.point_2, line_1.point_2); float line_1_point_1_cross_line_2 = cross(line_22_to_11, line_2); float line_1_point_2_corss_line_2 = cross(line_22_to_12, line_2); if(line_1_point_1_cross_line_2 == 0) { if(line_1_point_2_corss_line_2 == 0) { return true; } return isPointInLineRect(line_1.point_1, line_2); } if(line_1_point_2_corss_line_2 == 0) { return isPointInLineRect(line_1.point_2, line_2); } if(line_1_point_1_cross_line_2 * line_1_point_2_corss_line_2 < 0) { return true; } return false; } bool EasyMask2D::isLineParallel( const EasyLine2D &line_1, const EasyLine2D &line_2) { if(cross(line_1, line_2) == 0) { return true; } return false; } bool EasyMask2D::isPointOnOpenBoundedLine( const EasyPoint2D &point, const EasyLine2D &line) { if(line.point_1.x != line.point_2.x) { if(point.x > line.rect.x_min && point.x < line.rect.x_max) { return true; } } else if(line.point_1.y != line.point_2.y) { if(point.y > line.rect.y_min && point.y < line.rect.y_max) { return true; } } return false; } bool EasyMask2D::isPointInPolygon( const EasyPoint2D &point, const EasyPolygon2D &polygon) { float angle_value_sum = 0; for(size_t i = 0; i < polygon.point_list.size(); ++i) { int next_point_idx = i + 1; if(i == polygon.point_list.size() - 1) { next_point_idx = 0; } EasyLine2D line_1; EasyLine2D line_2; line_1.setPosition( point, polygon.point_list[i]); line_2.setPosition( point, polygon.point_list[next_point_idx]); angle_value_sum += angle(line_1, line_2); } float angle_value_sum_to_0 = fabs(angle_value_sum); float angle_value_sum_to_pi = fabs(angle_value_sum_to_0 - M_PI); float angle_value_sum_to_2pi = fabs(angle_value_sum - 2.0 * M_PI); if(angle_value_sum_to_0 < angle_value_sum_to_pi) { return false; } if(angle_value_sum_to_2pi < angle_value_sum_to_pi) { return true; } // here is the case point on the bound of polygon return true; } bool EasyMask2D::isPolygonCross( EasyPolygon2D &polygon_1, EasyPolygon2D &polygon_2) { EasyRect2D pylygon_1_rect; EasyRect2D polygon_2_rect; polygon_1.getPolygonRect(pylygon_1_rect); polygon_2.getPolygonRect(polygon_2_rect); if(!isRectCross(pylygon_1_rect, polygon_2_rect)) { return false; } for(const EasyPoint2D &point : polygon_1.point_list) { if(isPointInPolygon(point, polygon_2)) { return true; } } return false; } bool EasyMask2D::getLineCrossPoint( const EasyLine2D &line_1, const EasyLine2D &line_2, EasyPoint2D &line_cross_point) { float line_cross = cross(line_1, line_2); if(line_cross == 0) { std::cout << "EasyPolygon2D::getLineCrossPoint : lines are parallel!" << std::endl; return false; } float line_1_weight = (line_2.point_2.y - line_2.point_1.y) * line_2.point_1.x + (line_2.point_1.x - line_2.point_2.x) * line_2.point_1.y; float line_2_weight = (line_1.point_2.y - line_1.point_1.y) * line_1.point_1.x + (line_1.point_1.x - line_1.point_2.x) * line_1.point_1.y; float line_cross_point_x_weight = line_1_weight * (line_1.point_2.x - line_1.point_1.x) - line_2_weight * (line_2.point_2.x - line_2.point_1.x); float line_cross_point_y_weight = line_1_weight * (line_1.point_2.y - line_1.point_1.y) - line_2_weight * (line_2.point_2.y - line_2.point_1.y); line_cross_point.x = line_cross_point_x_weight / line_cross; line_cross_point.y = line_cross_point_y_weight / line_cross; return true; } bool EasyMask2D::getBoundedLineCrossPointVec( const EasyLine2D &line_1, const EasyLine2D &line_2, std::vector<EasyPoint2D> &line_cross_point_vec) { line_cross_point_vec.clear(); if(!isLineCross(line_1, line_2)) { return true; } if(isLineParallel(line_1, line_2)) { if(isSamePoint(line_1.point_1, line_2.point_1)) { line_cross_point_vec.emplace_back(line_1.point_1); if(isSamePoint(line_1.point_2, line_2.point_2)) { line_cross_point_vec.emplace_back(line_1.point_2); } } else if(isSamePoint(line_1.point_2, line_2.point_1)) { line_cross_point_vec.emplace_back(line_1.point_2); if(isSamePoint(line_1.point_1, line_2.point_2)) { line_cross_point_vec.emplace_back(line_1.point_1); } } if(isPointOnOpenBoundedLine(line_1.point_1, line_2)) { line_cross_point_vec.emplace_back(line_1.point_1); } if(isPointOnOpenBoundedLine(line_1.point_2, line_2)) { line_cross_point_vec.emplace_back(line_1.point_2); } if(isPointOnOpenBoundedLine(line_2.point_1, line_1)) { line_cross_point_vec.emplace_back(line_2.point_1); } if(isPointOnOpenBoundedLine(line_2.point_2, line_1)) { line_cross_point_vec.emplace_back(line_2.point_2); } return true; } EasyPoint2D line_cross_point; getLineCrossPoint(line_1, line_2, line_cross_point); line_cross_point_vec.emplace_back(line_cross_point); return true; } bool EasyMask2D::isSamePoint( const EasyPoint2D &point_1, const EasyPoint2D &point_2) { if(point_1.x == point_2.x && point_1.y == point_2.y) { return true; } return false; } bool EasyMask2D::getPolygonIntersection( std::vector<EasyPolygon2D> &polygon_vec, std::vector<EasyIntersection2D> &intersection_vec) { intersection_vec.clear(); if(polygon_vec.size() < 2) { return true; } for(size_t i = 1; i < polygon_vec.size(); ++i) { EasyPolygon2D &polygon_1 = polygon_vec[i]; for(size_t j = 0; j < i; ++j) { EasyPolygon2D &polygon_2 = polygon_vec[j]; for(size_t k = 0; k < polygon_1.point_list.size(); ++k) { EasyLine2D polygon_1_line; polygon_1_line.setPosition( polygon_1.point_list[k], polygon_1.point_list[(k + 1) % polygon_1.point_list.size()]); for(size_t l = 0; l < polygon_2.point_list.size(); ++l) { EasyLine2D polygon_2_line; polygon_2_line.setPosition( polygon_2.point_list[l], polygon_2.point_list[(l + 1) % polygon_2.point_list.size()]); std::vector<EasyPoint2D> line_cross_point_vec; getBoundedLineCrossPointVec( polygon_1_line, polygon_2_line, line_cross_point_vec); if(line_cross_point_vec.size() == 0) { continue; } for(const EasyPoint2D &line_cross_point : line_cross_point_vec) { bool cross_point_exist = false; for(EasyIntersection2D &exist_intersection : intersection_vec) { if(isSamePoint(exist_intersection.point, line_cross_point)) { exist_intersection.addPolygonPointIdx(i, k); exist_intersection.addPolygonPointIdx(j, l); cross_point_exist = true; break; } } if(!cross_point_exist) { EasyIntersection2D intersection; intersection.setPosition(line_cross_point); intersection.addPolygonPointIdx(i, k); intersection.addPolygonPointIdx(j, l); intersection_vec.emplace_back(intersection); } } } } } } return true; } bool EasyMask2D::getSortedIntersectionOnPolygonLine( const EasyPolygon2D &polygon, const std::vector<EasyIntersection2D> &intersection_vec, const size_t &polygon_idx, const size_t &point_idx, std::vector<size_t> &sorted_intersection_idx_on_polygon_line_vec) { sorted_intersection_idx_on_polygon_line_vec.clear(); if(intersection_vec.size() == 0) { return true; } std::vector<size_t> intersection_idx_on_polygon_line_vec; for(size_t i = 0; i < intersection_vec.size(); ++i) { const EasyIntersection2D &intersection = intersection_vec[i]; if(intersection.haveThisPointIdx(polygon_idx, point_idx)) { intersection_idx_on_polygon_line_vec.emplace_back(i); } } const EasyPoint2D &point_start = polygon.point_list[point_idx]; const EasyPoint2D &point_end = polygon.point_list[(point_idx + 1) % polygon.point_list.size()]; std::vector<float> intersection_to_point_start_diff_vec; intersection_to_point_start_diff_vec.resize(intersection_idx_on_polygon_line_vec.size()); std::vector<bool> intersection_idx_selected_vec; intersection_idx_selected_vec.resize(intersection_idx_on_polygon_line_vec.size(), false); if(point_start.x != point_end.x) { float line_x_diff = point_end.x - point_start.x; for(size_t i = 0; i < intersection_idx_on_polygon_line_vec.size(); ++i) { intersection_to_point_start_diff_vec[i] = (intersection_vec[intersection_idx_on_polygon_line_vec[i]].point.x - point_start.x) / line_x_diff; } for(size_t i = 0; i < intersection_idx_on_polygon_line_vec.size(); ++i) { float min_dist = -1; int min_dist_intersection_idx = -1; for(size_t j = 0; j < intersection_idx_on_polygon_line_vec.size(); ++j) { if(intersection_idx_selected_vec[j]) { continue; } if(min_dist_intersection_idx == -1 || intersection_to_point_start_diff_vec[j] < min_dist) { min_dist = intersection_to_point_start_diff_vec[j]; min_dist_intersection_idx = j; } } intersection_idx_selected_vec[min_dist_intersection_idx] = true; sorted_intersection_idx_on_polygon_line_vec.emplace_back( intersection_idx_on_polygon_line_vec[min_dist_intersection_idx]); } return true; } float line_y_diff = point_end.y - point_start.y; for(size_t i = 0; i < intersection_idx_on_polygon_line_vec.size(); ++i) { intersection_to_point_start_diff_vec[i] = (intersection_vec[intersection_idx_on_polygon_line_vec[i]].point.y - point_start.y) / line_y_diff; } for(size_t i = 0; i < intersection_idx_on_polygon_line_vec.size(); ++i) { float min_dist = -1; int min_dist_intersection_idx = -1; for(size_t j = 0; j < intersection_idx_on_polygon_line_vec.size(); ++j) { if(intersection_idx_selected_vec[j]) { continue; } if(min_dist_intersection_idx == -1 || intersection_to_point_start_diff_vec[j] < min_dist) { min_dist = intersection_to_point_start_diff_vec[j]; min_dist_intersection_idx = j; } } intersection_idx_selected_vec[min_dist_intersection_idx] = true; sorted_intersection_idx_on_polygon_line_vec.emplace_back( intersection_idx_on_polygon_line_vec[min_dist_intersection_idx]); } return true; } bool EasyMask2D::getSplitPolygonAndIntersectionPosition( const EasyPolygon2D &polygon, const std::vector<EasyIntersection2D> &intersection_vec, const size_t &polygon_idx, EasyPolygon2D &split_polygon, std::vector<std::pair<size_t, size_t>> &intersection_idx_polygon_point_idx_pair_vec) { intersection_idx_polygon_point_idx_pair_vec.clear(); if(intersection_vec.size() == 0) { return true; } size_t current_new_point_idx = 0; for(size_t i = 0; i < polygon.point_list.size(); ++i) { split_polygon.addPoint(polygon.point_list[i]); ++current_new_point_idx; std::vector<size_t> sorted_intersection_idx_on_polygon_line_vec; getSortedIntersectionOnPolygonLine( polygon, intersection_vec, polygon_idx, i, sorted_intersection_idx_on_polygon_line_vec); if(sorted_intersection_idx_on_polygon_line_vec.size() == 0) { continue; } for(const size_t &sorted_intersection_idx : sorted_intersection_idx_on_polygon_line_vec) { if(isSamePoint( polygon.point_list[i], intersection_vec[sorted_intersection_idx].point)) { std::pair<size_t, size_t> intersection_idx_polygon_point_idx_pair; intersection_idx_polygon_point_idx_pair.first = sorted_intersection_idx; intersection_idx_polygon_point_idx_pair.second = current_new_point_idx - 1; intersection_idx_polygon_point_idx_pair_vec.emplace_back( intersection_idx_polygon_point_idx_pair); continue; } if(isSamePoint( polygon.point_list[(i + 1) % polygon.point_list.size()], intersection_vec[sorted_intersection_idx].point)) { continue; } split_polygon.addPoint(intersection_vec[sorted_intersection_idx].point); std::pair<size_t, size_t> intersection_idx_polygon_point_idx_pair; intersection_idx_polygon_point_idx_pair.first = sorted_intersection_idx; intersection_idx_polygon_point_idx_pair.second = current_new_point_idx; intersection_idx_polygon_point_idx_pair_vec.emplace_back( intersection_idx_polygon_point_idx_pair); ++current_new_point_idx; } } return true; } bool EasyMask2D::splitPolygonsByIntersection( const std::vector<EasyIntersection2D> &intersection_vec, const std::vector<EasyPolygon2D> &polygon_vec, std::vector<EasyIntersection2D> &split_intersection_vec, std::vector<EasyPolygon2D> &split_polygon_vec) { split_intersection_vec.clear(); split_polygon_vec.clear(); if(intersection_vec.size() == 0) { split_polygon_vec = polygon_vec; return true; } for(const EasyIntersection2D &intersection : intersection_vec) { const EasyPoint2D &intersection_point = intersection.point; EasyIntersection2D empty_split_intersection; empty_split_intersection.setPosition(intersection_point); split_intersection_vec.emplace_back(empty_split_intersection); } for(size_t i = 0; i < polygon_vec.size(); ++i) { const EasyPolygon2D &polygon = polygon_vec[i]; EasyPolygon2D split_polygon; std::vector<std::pair<size_t, size_t>> intersection_idx_polygon_point_idx_pair_vec; getSplitPolygonAndIntersectionPosition( polygon, intersection_vec, i, split_polygon, intersection_idx_polygon_point_idx_pair_vec); split_polygon_vec.emplace_back(split_polygon); for(const std::pair<size_t, size_t> &intersection_idx_polygon_point_idx_pair : intersection_idx_polygon_point_idx_pair_vec) { split_intersection_vec[intersection_idx_polygon_point_idx_pair.first].addPolygonPointIdx( i, intersection_idx_polygon_point_idx_pair.second); } } return true; } bool EasyMask2D::getIntersectionIdxOnPolygonPoint( const std::vector<EasyPolygon2D> &polygon_vec, const std::vector<EasyIntersection2D> &intersection_vec, const size_t &polygon_idx, const size_t &point_idx, size_t &intersection_idx) { if(intersection_vec.size() == 0) { return false; } for(size_t i = 0; i < intersection_vec.size(); ++i) { if(isSamePoint(intersection_vec[i].point, polygon_vec[polygon_idx].point_list[point_idx])) { intersection_idx = i; return true; } } return false; } bool EasyMask2D::updatePolygonIntersectionPointConnectedState( const EasyIntersection2D &intersection, std::vector<std::vector<bool>> &polygon_point_connected_vec_vec) { for(const std::pair<size_t, std::vector<size_t>> &polygon_point_idx_vec_pair : intersection.polygon_point_idx_vec_pair_vec) { for(const size_t polygon_point_idx : polygon_point_idx_vec_pair.second) { polygon_point_connected_vec_vec[polygon_point_idx_vec_pair.first][polygon_point_idx] = true; } } return true; } bool EasyMask2D::updatePolygonNotIntersectionPointConnectedState( const std::vector<EasyPolygon2D> &polygon_vec, const EasyPolygon2D &union_polygon, std::vector<std::vector<bool>> &polygon_point_connected_vec_vec) { for(size_t i = 0; i < polygon_vec.size(); ++i) { const EasyPolygon2D &polygon = polygon_vec[i]; for(size_t j = 0; j < polygon.point_list.size(); ++j) { if(polygon_point_connected_vec_vec[i][j]) { continue; } const EasyPoint2D &polygon_point = polygon.point_list[j]; if(isPointInPolygon(polygon_point, union_polygon)) { polygon_point_connected_vec_vec[i][j] = true; } } } return true; } bool EasyMask2D::addNewPolygonPoint( const std::vector<EasyPolygon2D> &polygon_vec, const size_t &polygon_idx, const size_t &start_point_idx, EasyPolygon2D &union_polygon, std::vector<std::vector<bool>> &polygon_point_connected_vec_vec) { if(polygon_idx >= polygon_vec.size()) { std::cout << "EasyMask2D::addNewPolygonPoint : polygon_idx out of range!" << std::endl; return false; } union_polygon.addPoint( polygon_vec[polygon_idx].point_list[start_point_idx]); polygon_point_connected_vec_vec[polygon_idx][start_point_idx] = true; return true; } bool EasyMask2D::getMinimalAnglePolygonPointIdx( const std::vector<EasyPolygon2D> &polygon_vec, const std::vector<EasyIntersection2D> &intersection_vec, const size_t &polygon_idx, const size_t &start_point_idx, const size_t &start_intersection_idx, std::pair<size_t, size_t> &minimal_angle_polygon_point_idx) { if(intersection_vec.size() == 0) { std::cout << "EasyMask2D::getMinimalAnglePolygonPointIdx : intersection is empty!" << std::endl; return false; } float minimal_angle = 2.0 * M_PI; const size_t polygon_prev_point_idx = (start_point_idx - 1 + polygon_vec[polygon_idx].point_list.size()) % polygon_vec[polygon_idx].point_list.size(); EasyLine2D line_intersection_to_polygon_prev_point; line_intersection_to_polygon_prev_point.setPosition( intersection_vec[start_intersection_idx].point, polygon_vec[polygon_idx].point_list[polygon_prev_point_idx]); for(const std::pair<size_t, std::vector<size_t>> &polygon_point_idx_vec_pair : intersection_vec[start_intersection_idx].polygon_point_idx_vec_pair_vec) { for(const size_t &polygon_point_idx : polygon_point_idx_vec_pair.second) { const size_t polygon_next_point_idx = (polygon_point_idx + 1) % polygon_vec[polygon_point_idx_vec_pair.first].point_list.size(); EasyLine2D line_intersection_to_polygon_next_point; line_intersection_to_polygon_next_point.setPosition( intersection_vec[start_intersection_idx].point, polygon_vec[polygon_point_idx_vec_pair.first].point_list[polygon_next_point_idx]); float current_angle = getAntiClockWiseAngle( line_intersection_to_polygon_prev_point, line_intersection_to_polygon_next_point); if(current_angle == 0) { continue; } if(current_angle < minimal_angle) { minimal_angle = current_angle; minimal_angle_polygon_point_idx.first = polygon_point_idx_vec_pair.first; minimal_angle_polygon_point_idx.second = polygon_next_point_idx; } } } if(minimal_angle == 2.0 * M_PI) { std::cout << "no new polygon point found!" << std::endl; return false; } return true; } bool EasyMask2D::getUnionPolygonPoints( const std::vector<EasyPolygon2D> &polygon_vec, const std::vector<EasyIntersection2D> &intersection_vec, const size_t &start_polygon_idx, const size_t &start_point_idx, const size_t &current_start_polygon_idx, const size_t &current_start_point_idx, EasyPolygon2D &union_polygon, std::vector<std::vector<bool>> &polygon_point_connected_vec_vec) { std::cout << "current running at p" << current_start_polygon_idx << current_start_point_idx << std::endl; size_t connected_polygon_point_num = 0; for(const std::vector<bool> &polygon_point_connected_vec : polygon_point_connected_vec_vec) { connected_polygon_point_num += count( polygon_point_connected_vec.cbegin(), polygon_point_connected_vec.cend(), true); } std::cout << "connected_polygon_point_num_ = " << connected_polygon_point_num_ << std::endl; std::cout << "connected_polygon_point_num = " << connected_polygon_point_num << std::endl; if(connected_polygon_point_num_ == connected_polygon_point_num) { std::cout << "force quit" << std::endl; if(true) { std::cout << "+++++++++++++++" << std::endl; for(size_t i = 0; i < polygon_vec.size(); ++i) { const EasyPolygon2D &split_polygon = polygon_vec[i]; std::cout << "current polygon " << i << " :" << std::endl << "points :" << std::endl; for(int j = 0; j < split_polygon.point_list.size(); ++j) { std::cout << "\t" << j << " : [" << split_polygon.point_list[j].x << "," << split_polygon.point_list[j].y << "]" << std::endl; } } std::cout << "current intersection:" << std::endl; for(int i = 0; i < intersection_vec.size(); ++i) { std::cout << "points :" << std::endl; std::cout << "\t" << i << " : [" << intersection_vec[i].point.x << "," << intersection_vec[i].point.y << "]" << std::endl; std::cout << "idx :" << std::endl; for(int j = 0; j < intersection_vec[i].polygon_point_idx_vec_pair_vec.size(); ++j) { const auto &polygon_line_idx_vec_pair = intersection_vec[i].polygon_point_idx_vec_pair_vec[j]; std::cout << "\tpolygon id : " << polygon_line_idx_vec_pair.first << std::endl; std::cout << "\tpolygon line idx :"; for(int k = 0; k < polygon_line_idx_vec_pair.second.size(); ++k) { std::cout << polygon_line_idx_vec_pair.second[k] << " , "; } std::cout << std::endl; } } std::cout << "+++++++++++++++" << std::endl; } exit(0); } connected_polygon_point_num_ = connected_polygon_point_num; if(current_start_polygon_idx == start_polygon_idx && current_start_point_idx == start_point_idx) { return true; } size_t new_start_polygon_idx = current_start_polygon_idx; size_t new_start_point_idx = current_start_point_idx; addNewPolygonPoint( polygon_vec, new_start_polygon_idx, new_start_point_idx, union_polygon, polygon_point_connected_vec_vec); size_t intersection_idx; if(getIntersectionIdxOnPolygonPoint( polygon_vec, intersection_vec, new_start_polygon_idx, new_start_point_idx, intersection_idx)) { updatePolygonIntersectionPointConnectedState( intersection_vec[intersection_idx], polygon_point_connected_vec_vec); std::pair<size_t, size_t> minimal_angle_polygon_point_idx_pair; getMinimalAnglePolygonPointIdx( polygon_vec, intersection_vec, new_start_polygon_idx, new_start_point_idx, intersection_idx, minimal_angle_polygon_point_idx_pair); new_start_polygon_idx = minimal_angle_polygon_point_idx_pair.first; new_start_point_idx = minimal_angle_polygon_point_idx_pair.second; return getUnionPolygonPoints( polygon_vec, intersection_vec, start_polygon_idx, start_point_idx, new_start_polygon_idx, new_start_point_idx, union_polygon, polygon_point_connected_vec_vec); } new_start_point_idx = (new_start_point_idx + 1) % polygon_vec[new_start_polygon_idx].point_list.size(); return getUnionPolygonPoints( polygon_vec, intersection_vec, start_polygon_idx, start_point_idx, new_start_polygon_idx, new_start_point_idx, union_polygon, polygon_point_connected_vec_vec); }
28.767241
113
0.592249
[ "vector" ]
8e2203ae9b4ae6de1539481a5a1bc1d69b85c611
5,362
cpp
C++
apps/jpegresize/server/coproc.cpp
TonyBrewer/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
13
2015-02-26T22:46:18.000Z
2020-03-24T11:53:06.000Z
apps/jpegresize/server/coproc.cpp
PacificBiosciences/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
5
2016-02-25T17:08:19.000Z
2018-01-20T15:24:36.000Z
apps/jpegresize/server/coproc.cpp
TonyBrewer/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
12
2015-04-13T21:39:54.000Z
2021-01-15T01:00:13.000Z
/* Copyright (c) 2015 Convey Computer Corporation * * This file is part of the OpenHT jpegscale application. * * Use and distribution licensed under the BSD 3-clause license. * See the LICENSE file for the complete license text. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include "JobInfo.h" #include "JpegResizeHif.h" #include "JpegHdr.h" #include "job.hpp" #include <Magick++.h> using namespace Magick; using namespace Ht; extern long long g_dataMoverUsecs; extern long long g_dataMoverCnt; JpegResizeHif * g_pJpegResizeHif=0; bool magickFallback(jobDefinition &job); bool coprocInit(int threads) { CHtHifParams hifParams; // host memory accessed by coproc per image // jobInfo, input image, output buffer size_t alignedJobInfoSize = (sizeof(JobInfo) + 63) & ~63; hifParams.m_appUnitMemSize = (alignedJobInfoSize + 3*MAX_JPEG_IMAGE_SIZE) * threads; g_pJpegResizeHif = new JpegResizeHif(&hifParams); JobInfo::SetThreadCnt(threads); JobInfo::SetHifMemBase( g_pJpegResizeHif->GetAppUnitMemBase(0) ); //klc printf("HT frequency is %d MHz\n", g_pJpegResizeHif->GetUnitMHz()); fflush(stdout); return(1); } bool coprocResize(jobDefinition & job) { JobInfo * pJobInfo = new ( job.threadId ) JobInfo; uint8_t *pInPic = NULL; //struct stat buf; pJobInfo->m_inPicSize = job.inputBuffer.size; pInPic = (uint8_t *)job.inputBuffer.ptr; if ((job.jobMode & MODE_MAGICK)) { bool status=magickFallback(job); delete pJobInfo; return status; } pJobInfo->m_pInPic = (uint8_t *)job.inputBuffer.ptr; pJobInfo->m_inPicSize = job.inputBuffer.size; pInPic=pJobInfo->m_pInPic; assert(pInPic != NULL); char const * pErrMsg = parseJpegHdr( pJobInfo, pInPic, appArguments.addRestarts ); if (pErrMsg) { bool status=true; printf("%s - Unsupported image format: %s\n", job.inputFile.c_str(), pErrMsg); printf("Attempting to process using ImageMagick fallback\n"); status=magickFallback(job); delete pJobInfo; return status; } if(job.jobMode & MODE_KEEP_ASPECT) { int newX,newY; if(job.sizeX == 0) { newY = job.sizeY; newX = (pJobInfo->m_dec.m_imageCols * newY) / pJobInfo->m_dec.m_imageRows; }else if (job.sizeY == 0) { newX = job.sizeX; newY = (pJobInfo->m_dec.m_imageRows * newX) / pJobInfo->m_dec.m_imageCols; } else { // adjust target size to fit in bounding box // BB is defined by job.sizeX by job.sizeY // input filesize is pJobInfo->m_dec.m_imageCols by pJobInfo->m_dec.m_imageRows // start by assuming x is controlling dimension // then scale y by same ratio (newX/imageCols) newX = job.sizeX; newY = (pJobInfo->m_dec.m_imageRows * newX) / pJobInfo->m_dec.m_imageCols; if(newY > job.sizeY) { // doesn't fit, y is controlling dimension newY = job.sizeY; newX = (pJobInfo->m_dec.m_imageCols * newY) / pJobInfo->m_dec.m_imageRows; } } job.sizeX = newX; job.sizeY = newY; } if(job.jobMode & MODE_NO_UPSCALE) { if((pJobInfo->m_dec.m_imageRows < job.sizeY) && (pJobInfo->m_dec.m_imageCols < job.sizeX)) { // upscaling with MODE_NO_UPSCALE set - just return a copy of the input image job.outputBuffer.ptr = (char *) malloc(pJobInfo->m_inPicSize); memcpy((void *)job.outputBuffer.ptr,pJobInfo->m_pInPic,pJobInfo->m_inPicSize); job.outputBuffer.size = pJobInfo->m_inPicSize; delete pJobInfo; return 1; } } // check for unsupported features pErrMsg = jobInfoCheck( pJobInfo, job.sizeX, job.sizeY, job.scale ); if (pErrMsg) { bool status=true; // printf("%s - Unsupported image format: %s\n", job.inputFile.c_str(), pErrMsg); // printf("Attempting to process using ImageMagick fallback\n"); status=magickFallback(job); delete pJobInfo; return status; } // parseJpegHdr filled in some info, calculate derived values jobInfoInit( pJobInfo, job.sizeY, job.sizeX, job.scale); g_pJpegResizeHif->SubmitJob( pJobInfo ); job.outputBuffer.size=jpegWriteBuffer(pJobInfo, (uint8_t *&)job.outputBuffer.ptr); delete pJobInfo; // return pJobInfo back to jobInfo pool return 1; } bool magickFallback(jobDefinition &job) { Blob blob(job.inputBuffer.ptr, job.inputBuffer.size); Image image; image.magick("JPEG"); try { image.read(blob); } catch(...) { printf("Error reading JPEG blob in ImageMagick fallback\n"); return(0); } Geometry scaleFactor; if(job.jobMode & MODE_KEEP_ASPECT) { scaleFactor.aspect(false); } else { scaleFactor.aspect(true); } if(job.scale > 0) { scaleFactor.percent(true); scaleFactor.width(job.scale); scaleFactor.height(job.scale); } else { scaleFactor.percent(false); scaleFactor.width(job.sizeX); scaleFactor.height(job.sizeY); } //a simple resize try { image.resize(scaleFactor); } catch(...) { printf("Error resizing JPEG in ImageMagick fallback\n"); return(0); } if(job.quality) { image.quality(job.quality); } try { image.write( &blob ); } catch(...) { printf("Error writing JPEG blob in ImageMagick fallback\n"); } job.outputBuffer.ptr=(char *)malloc(blob.length()); memcpy((void *)job.outputBuffer.ptr, blob.data(), blob.length()); job.outputBuffer.size=blob.length(); return 1; }
30.99422
96
0.68053
[ "geometry" ]
8e24d97aceaf391c80b165976f01038950a7ce1a
1,712
cc
C++
tests/prediction-by-partial-matching-test.cc
pixie-grasper/research-library
26745bb0810a2fbe0292c7591ce01a2d6ee31acb
[ "MIT" ]
2
2016-03-06T08:03:18.000Z
2016-03-06T11:07:20.000Z
tests/prediction-by-partial-matching-test.cc
pixie-grasper/research-library
26745bb0810a2fbe0292c7591ce01a2d6ee31acb
[ "MIT" ]
1
2016-03-07T06:26:09.000Z
2016-03-07T06:26:09.000Z
tests/prediction-by-partial-matching-test.cc
pixie-grasper/research-library
26745bb0810a2fbe0292c7591ce01a2d6ee31acb
[ "MIT" ]
2
2016-03-06T08:19:49.000Z
2021-09-08T10:17:05.000Z
// Copyright 2015 pixie.grasper #include <cstdlib> #include <vector> #include "../includes/prediction-by-partial-matching.h" int main() { std::vector<int> buffer(1000); unsigned int seed = 10; for (std::size_t i = 0; i < buffer.size(); i++) { buffer[i] = rand_r(&seed) % 100; } auto&& ppma = ResearchLibrary::PredictionByPartialMatching ::Encode<MethodA, 2>(buffer); auto&& ippma = ResearchLibrary::PredictionByPartialMatching ::Decode<MethodA, 2>(ppma); for (size_t i = 0; i < buffer.size(); i++) { if (ippma[i] != buffer[i]) { return 1; } } auto&& ppmb = ResearchLibrary::PredictionByPartialMatching ::Encode<MethodB, 2>(buffer); auto&& ippmb = ResearchLibrary::PredictionByPartialMatching ::Decode<MethodB, 2>(ppmb); for (size_t i = 0; i < buffer.size(); i++) { if (ippmb[i] != buffer[i]) { return 1; } } auto&& ppmc = ResearchLibrary::PredictionByPartialMatching ::Encode<MethodC, 2>(buffer); auto&& ippmc = ResearchLibrary::PredictionByPartialMatching ::Decode<MethodC, 2>(ppmc); for (size_t i = 0; i < buffer.size(); i++) { if (ippmc[i] != buffer[i]) { return 1; } } auto&& ppmd = ResearchLibrary::PredictionByPartialMatching ::Encode<MethodD, 2>(buffer); auto&& ippmd = ResearchLibrary::PredictionByPartialMatching ::Decode<MethodD, 2>(ppmd); for (size_t i = 0; i < buffer.size(); i++) { if (ippmd[i] != buffer[i]) { return 1; } } return 0; }
30.035088
61
0.543224
[ "vector" ]
8e2834807cc6dd66f40d031cb95a32b66e4cf72a
14,644
cpp
C++
Engine/ModuleRenderer3D.cpp
carlosredolar/R-Engine
4d62a6f0da518322c9f66b999bdce8369aec60fe
[ "MIT" ]
null
null
null
Engine/ModuleRenderer3D.cpp
carlosredolar/R-Engine
4d62a6f0da518322c9f66b999bdce8369aec60fe
[ "MIT" ]
null
null
null
Engine/ModuleRenderer3D.cpp
carlosredolar/R-Engine
4d62a6f0da518322c9f66b999bdce8369aec60fe
[ "MIT" ]
null
null
null
#include "Globals.h" #include "Application.h" #include "GameObject.h" #include "Component_Material.h" #include "Component_Camera.h" #include <vector> #include "FileManager.h" #include "ModuleJson.h" #include "ModuleWindow.h" #include "ModuleRenderer3D.h" #include "Libs/Glew/include/glew.h" #include "Libs/SDL/include/SDL_opengl.h" #include <gl/GL.h> #include <gl/GLU.h> #include "Libs/Devil/include/IL/il.h" #pragma comment (lib, "glu32.lib") /* link OpenGL Utility lib */ #pragma comment (lib, "opengl32.lib") /* link Microsoft OpenGL lib */ #pragma comment (lib, "Libs/Glew/libx86/glew32.lib") /* link glew lib */ ModuleRenderer3D::ModuleRenderer3D(bool start_enabled) : Module(start_enabled), cameraCulling(true), context(nullptr) { name = "renderer"; _ray = LineSegment(); display_mode = SOLID; } // Destructor ModuleRenderer3D::~ModuleRenderer3D() {} // Called before render is available bool ModuleRenderer3D::Init() { LOG("Creating 3D Renderer context"); bool ret = true; //Create context context = SDL_GL_CreateContext(App->window->window); if (context == NULL) { LOG_ERROR("OpenGL context could not be created! SDL_Error: %s\n", SDL_GetError()); ret = false; } GLenum error = glewInit(); if (error != GL_NO_ERROR) { LOG_ERROR("Error initializing glew library! %s", SDL_GetError()); ret = false; } if (ret == true) { //Use Vsync if (vsync && SDL_GL_SetSwapInterval(1) < 0) LOG_ERROR("Warning: Unable to set VSync! SDL Error: %s\n", SDL_GetError()); //Initialize Projection Matrix glMatrixMode(GL_PROJECTION); glLoadIdentity(); glLoadMatrixf(App->camera->GetProjectionMatrix()); //Check for error GLenum error = glGetError(); if (error != GL_NO_ERROR) { LOG_ERROR("Error initializing OpenGL! %s\n", gluErrorString(error)); ret = false; } //Initialize Modelview Matrix glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glLoadMatrixf(App->camera->GetViewMatrix()); //Check for error error = glGetError(); if (error != GL_NO_ERROR) { LOG_ERROR("Error initializing OpenGL! %s\n", gluErrorString(error)); ret = false; } glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glClearDepth(1.0f); //Initialize clear color glClearColor(0.f, 0.f, 0.f, 1.f); //Check for error error = glGetError(); if (error != GL_NO_ERROR) { LOG_ERROR("Error initializing OpenGL! %s\n", gluErrorString(error)); ret = false; } GLfloat LightModelAmbient[] = { 0.0f, 0.0f, 0.0f, 1.0f }; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, LightModelAmbient); lights[0].reference = GL_LIGHT0; lights[0].ambient.Set(0.25f, 0.25f, 0.25f, 1.0f); lights[0].diffuse.Set(0.75f, 0.75f, 0.75f, 1.0f); lights[0].SetPosition(0.0f, 0.0f, 2.5f); lights[0].Init(); GLfloat MaterialAmbient[] = { 1.0f, 1.0f, 1.0f, 1.0f }; glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, MaterialAmbient); GLfloat MaterialDiffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f }; glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialDiffuse); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_COLOR_MATERIAL); glEnable(GL_TEXTURE_2D); glEnable(GL_LIGHTING); glEnable(GL_STENCIL_TEST); lights[0].Enable(true); } GenerateBuffers(); return ret; } bool ModuleRenderer3D::LoadConfig(JsonObj& config) { debug = config.GetBool("debug"); vsync = config.GetBool("vsync"); drawVertexNormals = config.GetBool("draw_vertex_normals"); drawFaceFormals = config.GetBool("draw_face_normals"); return true; } // PreUpdate: clear buffer update_status ModuleRenderer3D::PreUpdate(float dt) { glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer); Color c = App->camera->background; glClearColor(c.r, c.g, c.b, c.a); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glLoadMatrixf(App->camera->GetViewMatrix()); float3 cameraPosition = App->camera->GetPosition(); lights[0].SetPosition(cameraPosition.x, cameraPosition.y, cameraPosition.z); for (uint i = 0; i < MAX_LIGHTS; ++i) lights[i].Render(); return UPDATE_CONTINUE; } update_status ModuleRenderer3D::Update(float dt) { update_status ret = UPDATE_CONTINUE; DrawRay(); return ret; } update_status ModuleRenderer3D::PostUpdate(float dt) { glBindVertexArray(0); glBindFramebuffer(GL_FRAMEBUFFER, 0); App->gui->Draw(); SDL_GL_SwapWindow(App->window->window); if (App->scene->selectedGameObject != nullptr && App->scene->selectedGameObject->toDelete) { App->scene->DeleteGameObject(App->scene->selectedGameObject); App->scene->selectedGameObject = nullptr; } return UPDATE_CONTINUE; } // Called before quitting bool ModuleRenderer3D::CleanUp() { LOG("Destroying 3D Renderer"); glDeleteFramebuffers(1, &frameBuffer); glDeleteTextures(1, &colorTexture); SDL_GL_DeleteContext(context); mainCamera = nullptr; return true; } void ModuleRenderer3D::ScreenResized(int width, int height) { glViewport(0, 0, width, height); glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer); glBindTexture(GL_TEXTURE_2D, colorTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glBindFramebuffer(GL_FRAMEBUFFER, 0); glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); glBindRenderbuffer(GL_RENDERBUFFER, 0); glBindTexture(GL_TEXTURE_2D, 0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glLoadMatrixf(App->camera->GetProjectionMatrix()); } void ModuleRenderer3D::UpdateProjectionMatrix(float* projectionMatrix) { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glLoadMatrixf(App->camera->GetViewMatrix()); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glLoadMatrixf(App->camera->GetProjectionMatrix()); } void ModuleRenderer3D::SetDisplayMode(RenderMode display) { GLenum face = GL_FRONT; display_mode = display; if (!glIsEnabled(GL_CULL_FACE_MODE)) face = GL_FRONT_AND_BACK; switch (display) { case SOLID: glPolygonMode(face, GL_FILL); glDisable(GL_POLYGON_SMOOTH); break; case WIREFRAME: glPolygonMode(face, GL_LINE); glDisable(GL_POLYGON_SMOOTH); break; case SOLIDWIRE: glPolygonMode(face, GL_FILL); glEnable(GL_POLYGON_SMOOTH); break; default: break; } } RenderMode ModuleRenderer3D::GetDisplayMode() { return display_mode; } void ModuleRenderer3D::SetMainCamera(Component_Camera* camera) { mainCamera = camera; } Component_Camera* ModuleRenderer3D::GetMainCamera() { return mainCamera; } void ModuleRenderer3D::SetCap(GLenum cap, bool enabled) { if (enabled) glEnable(cap); else glDisable(cap); } void ModuleRenderer3D::SetVSync(bool enabled) { if (enabled) { if (SDL_GL_SetSwapInterval(1) == -1) { LOG_ERROR("VSync not supported"); } else { LOG("VSync enabled"); } } else { if (SDL_GL_SetSwapInterval(0) == -1) { LOG_ERROR("VSync not supported"); } else { LOG("VSync disabled"); } } } void ModuleRenderer3D::DrawRay() { glBegin(GL_LINES); glColor3f(0.0f, 0.85f, 0.85f); glVertex3f(_ray.a.x, _ray.a.y, _ray.a.z); glVertex3f(_ray.b.x, _ray.b.y, _ray.b.z); glColor3f(1.0f, 1.0f, 1.0f); glEnd(); } void ModuleRenderer3D::GenerateBuffers() { //FrameBuffer glGenFramebuffers(1, &frameBuffer); glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer); //Color Texture Buffer =========================================================================================================== glGenTextures(1, &colorTexture); glBindTexture(GL_TEXTURE_2D, colorTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, App->window->width, App->window->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); //RenderBuffer glGenRenderbuffers(1, &renderBuffer); glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, App->window->width, App->window->height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, renderBuffer); //Depth RenderBuffer ============================================================================================================= //glGenRenderbuffers(1, &depthRenderBuffer); //glBindRenderbuffer(GL_RENDERBUFFER, depthRenderBuffer); //glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, App->window->width, App->window->height); //glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderBuffer); glGenTextures(1, &depthTexture); glBindTexture(GL_TEXTURE_2D, depthTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, App->window->width, App->window->height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0); //================================================================================================================================== glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorTexture, 0); //glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTexture, 0); /*GLenum DrawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, DrawBuffers);*/ if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) LOG_ERROR("Famebuffer is not complete"); glBindFramebuffer(GL_FRAMEBUFFER, 0); glBindTexture(GL_TEXTURE_2D, 0); } void ModuleRenderer3D::DrawDirectModeCube() { int CHECKERS_WIDTH = 64; int CHECKERS_HEIGHT = 64; GLubyte checkerImage[64][64][4]; for (int i = 0; i < CHECKERS_HEIGHT; i++) { for (int j = 0; j < CHECKERS_WIDTH; j++) { int c = ((((i & 0x8) == 0) ^ (((j & 0x8)) == 0))) * 255; checkerImage[i][j][0] = (GLubyte)c; checkerImage[i][j][1] = (GLubyte)c; checkerImage[i][j][2] = (GLubyte)c; checkerImage[i][j][3] = (GLubyte)255; } } GLuint textureID; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_2D, textureID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); { glBegin(GL_TRIANGLES); //Bottom Face glTexCoord2f(0.0f, 0.0f); glVertex3f(0.f, 0.f, 0.f); glTexCoord2f(1.0f, 0.0f); glVertex3f(1.f, 0.f, 0.f); glTexCoord2f(1.0f, 1.0f); glVertex3f(1.f, 0.f, 1.f); glTexCoord2f(1.0f, 1.0f); glVertex3f(1.f, 0.f, 1.f); glTexCoord2f(0.0f, 1.0f); glVertex3f(0.f, 0.f, 1.f); glTexCoord2f(0.0f, 0.0f); glVertex3f(0.f, 0.f, 0.f); //Front Face glTexCoord2f(0.0f, 0.0f); glVertex3f(0.f, 0.f, 1.f); glTexCoord2f(1.0f, 0.0f); glVertex3f(1.f, 0.f, 1.f); glTexCoord2f(1.0f, 1.0f); glVertex3f(1.f, 1.f, 1.f); glTexCoord2f(1.0f, 1.0f); glVertex3f(1.f, 1.f, 1.f); glTexCoord2f(0.0f, 1.0f); glVertex3f(0.f, 1.f, 1.f); glTexCoord2f(0.0f, 0.0f); glVertex3f(0.f, 0.f, 1.f); //Left Face glTexCoord2f(0.0f, 0.0f); glVertex3f(0.f, 0.f, 0.f); glTexCoord2f(1.0f, 0.0f); glVertex3f(0.f, 0.f, 1.f); glTexCoord2f(1.0f, 1.0f); glVertex3f(0.f, 1.f, 1.f); glTexCoord2f(1.0f, 1.0f); glVertex3f(0.f, 1.f, 1.f); glTexCoord2f(0.0f, 1.0f); glVertex3f(0.f, 1.f, 0.f); glTexCoord2f(0.0f, 0.0f); glVertex3f(0.f, 0.f, 0.f); //Right Face glTexCoord2f(0.0f, 0.0f); glVertex3f(1.f, 0.f, 0.f); glTexCoord2f(1.0f, 0.0f); glVertex3f(1.f, 1.f, 0.f); glTexCoord2f(1.0f, 1.0f); glVertex3f(1.f, 1.f, 1.f); glTexCoord2f(1.0f, 1.0f); glVertex3f(1.f, 1.f, 1.f); glTexCoord2f(0.0f, 1.0f); glVertex3f(1.f, 0.f, 1.f); glTexCoord2f(0.0f, 0.0f); glVertex3f(1.f, 0.f, 0.f); //Back Face glTexCoord2f(0.0f, 0.0f); glVertex3f(0.f, 0.f, 0.f); glTexCoord2f(1.0f, 0.0f); glVertex3f(0.f, 1.f, 0.f); glTexCoord2f(1.0f, 1.0f); glVertex3f(1.f, 1.f, 0.f); glTexCoord2f(1.0f, 1.0f); glVertex3f(1.f, 1.f, 0.f); glTexCoord2f(0.0f, 1.0f); glVertex3f(1.f, 0.f, 0.f); glTexCoord2f(0.0f, 0.0f); glVertex3f(0.f, 0.f, 0.f); //Top Face glTexCoord2f(0.0f, 0.0f); glVertex3f(0.f, 1.f, 0.f); glTexCoord2f(1.0f, 0.0f); glVertex3f(0.f, 1.f, 1.f); glTexCoord2f(1.0f, 1.0f); glVertex3f(1.f, 1.f, 1.f); glTexCoord2f(1.0f, 1.0f); glVertex3f(1.f, 1.f, 1.f); glTexCoord2f(0.0f, 1.0f); glVertex3f(1.f, 1.f, 0.f); glTexCoord2f(0.0f, 0.0f); glVertex3f(0.f, 1.f, 0.f); glEnd(); } glDeleteTextures(1, &textureID); glBindTexture(GL_TEXTURE_2D, 0); ilBindImage(0); } void ModuleRenderer3D::DrawAABB(float3* cornerPoints, ImVec4 color) { glDisable(GL_LIGHTING); glColor3f(color.x, color.y, color.z); glBegin(GL_LINES); glVertex3f(cornerPoints[0].x, cornerPoints[0].y, cornerPoints[0].z); glVertex3f(cornerPoints[1].x, cornerPoints[1].y, cornerPoints[1].z); glVertex3f(cornerPoints[0].x, cornerPoints[0].y, cornerPoints[0].z); glVertex3f(cornerPoints[2].x, cornerPoints[2].y, cornerPoints[2].z); glVertex3f(cornerPoints[2].x, cornerPoints[2].y, cornerPoints[2].z); glVertex3f(cornerPoints[3].x, cornerPoints[3].y, cornerPoints[3].z); glVertex3f(cornerPoints[1].x, cornerPoints[1].y, cornerPoints[1].z); glVertex3f(cornerPoints[3].x, cornerPoints[3].y, cornerPoints[3].z); glVertex3f(cornerPoints[0].x, cornerPoints[0].y, cornerPoints[0].z); glVertex3f(cornerPoints[4].x, cornerPoints[4].y, cornerPoints[4].z); glVertex3f(cornerPoints[5].x, cornerPoints[5].y, cornerPoints[5].z); glVertex3f(cornerPoints[4].x, cornerPoints[4].y, cornerPoints[4].z); glVertex3f(cornerPoints[5].x, cornerPoints[5].y, cornerPoints[5].z); glVertex3f(cornerPoints[1].x, cornerPoints[1].y, cornerPoints[1].z); glVertex3f(cornerPoints[5].x, cornerPoints[5].y, cornerPoints[5].z); glVertex3f(cornerPoints[7].x, cornerPoints[7].y, cornerPoints[7].z); glVertex3f(cornerPoints[7].x, cornerPoints[7].y, cornerPoints[7].z); glVertex3f(cornerPoints[6].x, cornerPoints[6].y, cornerPoints[6].z); glVertex3f(cornerPoints[6].x, cornerPoints[6].y, cornerPoints[6].z); glVertex3f(cornerPoints[2].x, cornerPoints[2].y, cornerPoints[2].z); glVertex3f(cornerPoints[6].x, cornerPoints[6].y, cornerPoints[6].z); glVertex3f(cornerPoints[4].x, cornerPoints[4].y, cornerPoints[4].z); glVertex3f(cornerPoints[7].x, cornerPoints[7].y, cornerPoints[7].z); glVertex3f(cornerPoints[3].x, cornerPoints[3].y, cornerPoints[3].z); glEnd(); glColor3f(1.0f, 1.0f, 1.0f); glEnable(GL_LIGHTING); }
26.771481
133
0.698989
[ "render", "vector", "3d", "solid" ]
8e35bb4e6f4132db1288c3f86b82e78398c23c41
1,267
cpp
C++
src/interpreter/cli_input.cpp
Grossley/opengml
bc3494aae64092f1c32a16361fd781249e2ea630
[ "MIT" ]
26
2019-07-18T04:45:08.000Z
2022-03-13T09:52:04.000Z
src/interpreter/cli_input.cpp
Grossley/opengml
bc3494aae64092f1c32a16361fd781249e2ea630
[ "MIT" ]
6
2021-09-10T00:48:00.000Z
2021-11-27T22:00:48.000Z
src/interpreter/cli_input.cpp
Grossley/opengml
bc3494aae64092f1c32a16361fd781249e2ea630
[ "MIT" ]
9
2019-07-26T06:32:53.000Z
2022-01-12T14:38:59.000Z
#include "cli_input.hpp" #include "ogm/common/util.hpp" #include <iostream> #include <string> #ifdef OGM_CROSSLINE #include <crossline.h> #endif namespace ogm { namespace interpreter { #ifdef OGM_CROSSLINE namespace { #define BUFFSIZE 2048 char buff[BUFFSIZE]; // currently-registered input completer input_completer_t input_completer = nullptr; void completer_dispatch(const char* text, crossline_completions_t* acc) { if (input_completer) { std::vector<std::string> completions; input_completer(text, completions); for (const std::string& c : completions) { crossline_completion_add(acc, c.c_str(), nullptr); } } } } std::string input(const char* prompt, input_completer_t completer) { input_completer = completer; crossline_completion_register(completer_dispatch); const char* result = crossline_readline(prompt, buff, BUFFSIZE); if (result) return result; return ""; } #else std::string input(const char* prompt, char** (*completer)(const char* text, int start, int end)) { std::cout << prompt << std::flush; std::string _input; std::getline(std::cin, _input); return _input; } #endif }}
21.474576
96
0.656669
[ "vector" ]
8e3ab9fddcb7c925f65f837b5cf7e30794755b2c
3,063
cpp
C++
trunk/RayTracer/RayTracer/src/Cube.cpp
Monster88Ra/RayTracer
948cc707e12ef0e75266b26aaca42ee07adb6b0b
[ "MIT" ]
null
null
null
trunk/RayTracer/RayTracer/src/Cube.cpp
Monster88Ra/RayTracer
948cc707e12ef0e75266b26aaca42ee07adb6b0b
[ "MIT" ]
1
2018-11-23T04:56:10.000Z
2018-11-27T04:29:58.000Z
trunk/RayTracer/RayTracer/src/Cube.cpp
Monster88Ra/RayTracer
948cc707e12ef0e75266b26aaca42ee07adb6b0b
[ "MIT" ]
null
null
null
#include "Cube.h" #include "Intersection.h" #include <limits> Cube::Cube(Vector3f center, Material lightingMaterial): Object(lightingMaterial) { SetLocalOrigin(center); ConstructAABB(); } Cube::~Cube() { } bool Cube::IsIntersectingRay(Ray ray, float * out_ValueT, Intersection * out_Intersection) { if (!IsEnable()) { return false; } // use bounding box test const float originalT = (out_ValueT) ? *out_ValueT : 0; // transform ray to world space ray = GetWorldInvTransform().TransformRay(ray); const bool isIntersecting = GetBoundingBox().IsIntersectingRay(ray, out_ValueT); if (isIntersecting && out_Intersection && originalT > *out_ValueT) { // get intersection point in world space Vector3f intersectingpoint = GetWorldTransform().TransformPosition(ray.origin + *out_ValueT * ray.direction); ConstructIntersection(intersectingpoint, out_Intersection); } else if (out_ValueT && originalT < *out_ValueT) { return false; } return isIntersecting; } Material Cube::GetMaterial(Vector3f surfacePoint) { // ??? const TextureInfo& DiffuseInfo = m_Material.GetDiffuseTexture(); if (!DiffuseInfo.texture) return m_Material; surfacePoint = GetWorldInvTransform().TransformPosition(surfacePoint); const Vector3f& Scale = GetWorldTransform().GetScale(); float U = 0.0f, V = 0.0f; if (1.0f - abs(surfacePoint.x) < _EPSILON) { U = Scale.z * (surfacePoint.z + 1.0f) / 2.0f; V = Scale.y * (surfacePoint.y + 1.0f) / 2.0f; } else if (1.0f - abs(surfacePoint.y)< _EPSILON) { U = Scale.x * (surfacePoint.x + 1.0f) / 2.0f; V = Scale.z * (surfacePoint.z + 1.0f) / 2.0f; } else { U = Scale.x * (surfacePoint.x + 1.0f) / 2.0f; V = Scale.y * (surfacePoint.y + 1.0f) / 2.0f; } U *= DiffuseInfo.UAxisScale; V *= DiffuseInfo.VAxisScale; m_Material.SetDiffuse(DiffuseInfo.texture->GetSample(U, V)); return m_Material; } void Cube::ConstructIntersection(const Vector3f & intersectionPoint, Intersection *intersectionOut) { float largestSide = 0; int intersectionAxis = 0; int intersectionSide = 0; // transform point to local space const Matrix4 modelInverse = GetWorldInvTransform(); const Vector3f intersectionInObjectSpace = modelInverse.TransformPosition(intersectionPoint); // get largest side for (int i = 0; i < 3; i++) { if (abs(intersectionInObjectSpace[i]) > largestSide) { largestSide = abs(intersectionInObjectSpace[i]); // judge inside or outside intersectionSide = (intersectionInObjectSpace[i] < 0.0f) ? -1:1; intersectionAxis = i; } } Vector3f normal; normal[intersectionAxis] = (float)intersectionSide; // transform to world spcae normal = modelInverse.TransformDirection(normal).Normalize(); intersectionOut->normal = normal; intersectionOut->object = this; intersectionOut->point = intersectionPoint + (normal * _EPSILON); } void Cube::ConstructAABB(Vector3f min, Vector3f max) { min = Vector3f(-1, -1, -1); max = Vector3f(1, 1, 1); SetBoundingBox(AABB{ min,max }); }
26.405172
112
0.693764
[ "object", "transform" ]
8e49f675801792610d4322aa39ca82d5a8bfce53
4,630
cpp
C++
lib/src/utils/random.cpp
masumhabib/quest
afef1166b361236144be83f07303a3ec0d5c187c
[ "Apache-2.0" ]
5
2017-04-04T20:57:41.000Z
2021-04-23T02:08:22.000Z
lib/src/utils/random.cpp
masumhabib/quest
afef1166b361236144be83f07303a3ec0d5c187c
[ "Apache-2.0" ]
14
2016-10-06T03:00:24.000Z
2017-05-30T06:43:32.000Z
lib/src/utils/random.cpp
masumhabib/quest
afef1166b361236144be83f07303a3ec0d5c187c
[ "Apache-2.0" ]
1
2016-10-03T04:09:25.000Z
2016-10-03T04:09:25.000Z
/* * File: random.cpp * Copyright (C) 2014 K M Masum Habib <masum.habib@ail.com> * * Created on November 6, 2014, 10:30 AM */ #include "utils/random.h" namespace utils{ namespace random{ Random::Random() : generator(device) { } std::vector<double> Random::generate (int count) { if (count < 0) { throw std::invalid_argument("Random::generate(): count must be >= 0"); } return generate((size_t) count); } std::vector<double> Random::generate (size_t count) { vector<double> numbers(count); for (size_t i = 0; i < count; i += 1){ numbers[i] = generate(); } return numbers; } //----------------------------------------------------------------------------- // Uniform Random //----------------------------------------------------------------------------- UniformRandom::UniformRandom (double min, double max) : max(max), min(min), distribution(min, max) { } double UniformRandom::generate () { return distribution(generator); } void UniformRandom::reset() { distribution.reset(); } //----------------------------------------------------------------------------- // Normal Random //----------------------------------------------------------------------------- NormalRandom::NormalRandom(double std_dev, double mean) : distribution (mean, std_dev) { } NormalRandom::NormalRandom(double std_dev, double mean, double min, double max) : min (min), max (max), distribution (mean, std_dev) { } void NormalRandom::reset() { distribution.reset(); } double NormalRandom::generate() { double random_number; for (size_t retry = 0; retry < MAX_RETRY; retry += 1) { random_number = distribution(generator); // check the range if ((std::isnan(min) || random_number >= min) && (std::isnan(max) || random_number <= max)) { break; } } return random_number; } //----------------------------------------------------------------------------- // Discrete Random //----------------------------------------------------------------------------- DiscreteRandom::DiscreteRandom (const std::vector<double>& values, const std::vector<double>& weights) : domain (values), distribution (weights) { if (values.size() != weights.size()) { throw invalid_argument ("DiscreteRandom::DiscreteRandom(): values.size() != weights.size()"); } } DiscreteRandom::DiscreteRandom(const std::vector<double>& values, const WeightFunction& weight_function): domain (values), distribution ( calculate_weights(values, weight_function)) { } DiscreteRandom::DiscreteRandom(double xmin, double xmax, std::size_t count, const WeightFunction& weight_function) : domain (create_domain (xmin, xmax, count)), distribution (calculate_weights (domain, weight_function)) { } DiscreteRandom::DiscreteRandom(double xmin, double xmax, double step, const WeightFunction& weight_function) : domain (create_domain (xmin, xmax, step)), distribution (calculate_weights (domain, weight_function)) { } void DiscreteRandom::reset() { distribution.reset(); } double DiscreteRandom::generate () { int random_number = distribution(generator); assert (random_number < domain.size()); return domain[random_number]; } std::vector<double> DiscreteRandom::calculate_weights ( const std::vector<double>& domain, const WeightFunction& weight_function) { std::vector<double> weights; // for performance boost weights.reserve(domain.size()); for (auto x : domain) { weights.push_back(weight_function(x)); } return weights; } std::vector<double> DiscreteRandom::create_domain ( double xmin, double xmax, size_t count) { std::vector<double> new_domain = utils::stds::linspace(xmin, xmax, count); return new_domain; } std::vector<double> DiscreteRandom::create_domain ( double xmin, double xmax, double step) { std::vector<double> new_domain = utils::stds::linspace(xmin, xmax, step); return new_domain; } //----------------------------------------------------------------------------- // Discrete Cosine Random //----------------------------------------------------------------------------- // DiscreteCosineRandom::DiscreteCosineRandom (const std::vector<double>& angles) : DiscreteRandom (angles, CosineFunction()) { } DiscreteCosineRandom::DiscreteCosineRandom(double angle_min, double angle_max, std::size_t count) : DiscreteRandom (angle_min, angle_max, count, CosineFunction ()) { } DiscreteCosineRandom::DiscreteCosineRandom(double angle_min, double angle_max, double step) : DiscreteRandom (angle_min, angle_max, step, CosineFunction()) { } }}
28.580247
101
0.599784
[ "vector" ]
8e4c73415c7a52bc2b802d34e463f87fa99b88bf
18,186
cpp
C++
apiwznm/DlgWznmPrjNew.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
3
2020-09-20T16:24:48.000Z
2021-12-01T19:44:51.000Z
apiwznm/DlgWznmPrjNew.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
apiwznm/DlgWznmPrjNew.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
/** * \file DlgWznmPrjNew.cpp * API code for job DlgWznmPrjNew (implementation) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 5 Dec 2020 */ // IP header --- ABOVE #include "DlgWznmPrjNew.h" using namespace std; using namespace Sbecore; using namespace Xmlio; /****************************************************************************** class DlgWznmPrjNew::VecVDo ******************************************************************************/ uint DlgWznmPrjNew::VecVDo::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "detbutautclick") return DETBUTAUTCLICK; if (s == "butcncclick") return BUTCNCCLICK; if (s == "butcreclick") return BUTCRECLICK; return(0); }; string DlgWznmPrjNew::VecVDo::getSref( const uint ix ) { if (ix == DETBUTAUTCLICK) return("DetButAutClick"); if (ix == BUTCNCCLICK) return("ButCncClick"); if (ix == BUTCRECLICK) return("ButCreClick"); return(""); }; /****************************************************************************** class DlgWznmPrjNew::VecVSge ******************************************************************************/ uint DlgWznmPrjNew::VecVSge::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "idle") return IDLE; if (s == "alraer") return ALRAER; if (s == "auth") return AUTH; if (s == "autdone") return AUTDONE; if (s == "create") return CREATE; if (s == "sync") return SYNC; if (s == "done") return DONE; return(0); }; string DlgWznmPrjNew::VecVSge::getSref( const uint ix ) { if (ix == IDLE) return("idle"); if (ix == ALRAER) return("alraer"); if (ix == AUTH) return("auth"); if (ix == AUTDONE) return("autdone"); if (ix == CREATE) return("create"); if (ix == SYNC) return("sync"); if (ix == DONE) return("done"); return(""); }; /****************************************************************************** class DlgWznmPrjNew::ContIac ******************************************************************************/ DlgWznmPrjNew::ContIac::ContIac( const string& DetTxfSho , const string& DetTxfTit , const string& DetTxfAbt , const vector<uint>& numsFDetLstDty , const vector<uint>& numsFDetLstLoc , const uint numFDetPupPlc , const uint numFDetPupPmc ) : Block() { this->DetTxfSho = DetTxfSho; this->DetTxfTit = DetTxfTit; this->DetTxfAbt = DetTxfAbt; this->numsFDetLstDty = numsFDetLstDty; this->numsFDetLstLoc = numsFDetLstLoc; this->numFDetPupPlc = numFDetPupPlc; this->numFDetPupPmc = numFDetPupPmc; mask = {DETTXFSHO, DETTXFTIT, DETTXFABT, NUMSFDETLSTDTY, NUMSFDETLSTLOC, NUMFDETPUPPLC, NUMFDETPUPPMC}; }; bool DlgWznmPrjNew::ContIac::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContIacDlgWznmPrjNew"); else basefound = checkXPath(docctx, basexpath); string itemtag = "ContitemIacDlgWznmPrjNew"; if (basefound) { if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "DetTxfSho", DetTxfSho)) add(DETTXFSHO); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "DetTxfTit", DetTxfTit)) add(DETTXFTIT); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "DetTxfAbt", DetTxfAbt)) add(DETTXFABT); if (extractUintvecAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numsFDetLstDty", numsFDetLstDty)) add(NUMSFDETLSTDTY); if (extractUintvecAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numsFDetLstLoc", numsFDetLstLoc)) add(NUMSFDETLSTLOC); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFDetPupPlc", numFDetPupPlc)) add(NUMFDETPUPPLC); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFDetPupPmc", numFDetPupPmc)) add(NUMFDETPUPPMC); }; return basefound; }; void DlgWznmPrjNew::ContIac::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "ContIacDlgWznmPrjNew"; string itemtag; if (shorttags) itemtag = "Ci"; else itemtag = "ContitemIacDlgWznmPrjNew"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeStringAttr(wr, itemtag, "sref", "DetTxfSho", DetTxfSho); writeStringAttr(wr, itemtag, "sref", "DetTxfTit", DetTxfTit); writeStringAttr(wr, itemtag, "sref", "DetTxfAbt", DetTxfAbt); writeUintvecAttr(wr, itemtag, "sref", "numsFDetLstDty", numsFDetLstDty); writeUintvecAttr(wr, itemtag, "sref", "numsFDetLstLoc", numsFDetLstLoc); writeUintAttr(wr, itemtag, "sref", "numFDetPupPlc", numFDetPupPlc); writeUintAttr(wr, itemtag, "sref", "numFDetPupPmc", numFDetPupPmc); xmlTextWriterEndElement(wr); }; set<uint> DlgWznmPrjNew::ContIac::comm( const ContIac* comp ) { set<uint> items; if (DetTxfSho == comp->DetTxfSho) insert(items, DETTXFSHO); if (DetTxfTit == comp->DetTxfTit) insert(items, DETTXFTIT); if (DetTxfAbt == comp->DetTxfAbt) insert(items, DETTXFABT); if (compareUintvec(numsFDetLstDty, comp->numsFDetLstDty)) insert(items, NUMSFDETLSTDTY); if (compareUintvec(numsFDetLstLoc, comp->numsFDetLstLoc)) insert(items, NUMSFDETLSTLOC); if (numFDetPupPlc == comp->numFDetPupPlc) insert(items, NUMFDETPUPPLC); if (numFDetPupPmc == comp->numFDetPupPmc) insert(items, NUMFDETPUPPMC); return(items); }; set<uint> DlgWznmPrjNew::ContIac::diff( const ContIac* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {DETTXFSHO, DETTXFTIT, DETTXFABT, NUMSFDETLSTDTY, NUMSFDETLSTLOC, NUMFDETPUPPLC, NUMFDETPUPPMC}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class DlgWznmPrjNew::ContInf ******************************************************************************/ DlgWznmPrjNew::ContInf::ContInf( const uint numFSge ) : Block() { this->numFSge = numFSge; mask = {NUMFSGE}; }; bool DlgWznmPrjNew::ContInf::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContInfDlgWznmPrjNew"); else basefound = checkXPath(docctx, basexpath); string itemtag = "ContitemInfDlgWznmPrjNew"; if (basefound) { if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFSge", numFSge)) add(NUMFSGE); }; return basefound; }; set<uint> DlgWznmPrjNew::ContInf::comm( const ContInf* comp ) { set<uint> items; if (numFSge == comp->numFSge) insert(items, NUMFSGE); return(items); }; set<uint> DlgWznmPrjNew::ContInf::diff( const ContInf* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {NUMFSGE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class DlgWznmPrjNew::StatApp ******************************************************************************/ DlgWznmPrjNew::StatApp::StatApp( const string& shortMenu , const uint DetLstDtyNumFirstdisp , const uint DetLstLocNumFirstdisp ) : Block() { this->shortMenu = shortMenu; this->DetLstDtyNumFirstdisp = DetLstDtyNumFirstdisp; this->DetLstLocNumFirstdisp = DetLstLocNumFirstdisp; mask = {SHORTMENU, DETLSTDTYNUMFIRSTDISP, DETLSTLOCNUMFIRSTDISP}; }; bool DlgWznmPrjNew::StatApp::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatAppDlgWznmPrjNew"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StatitemAppDlgWznmPrjNew"; if (basefound) { if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "shortMenu", shortMenu)) add(SHORTMENU); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "DetLstDtyNumFirstdisp", DetLstDtyNumFirstdisp)) add(DETLSTDTYNUMFIRSTDISP); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "DetLstLocNumFirstdisp", DetLstLocNumFirstdisp)) add(DETLSTLOCNUMFIRSTDISP); }; return basefound; }; set<uint> DlgWznmPrjNew::StatApp::comm( const StatApp* comp ) { set<uint> items; if (shortMenu == comp->shortMenu) insert(items, SHORTMENU); if (DetLstDtyNumFirstdisp == comp->DetLstDtyNumFirstdisp) insert(items, DETLSTDTYNUMFIRSTDISP); if (DetLstLocNumFirstdisp == comp->DetLstLocNumFirstdisp) insert(items, DETLSTLOCNUMFIRSTDISP); return(items); }; set<uint> DlgWznmPrjNew::StatApp::diff( const StatApp* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {SHORTMENU, DETLSTDTYNUMFIRSTDISP, DETLSTLOCNUMFIRSTDISP}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class DlgWznmPrjNew::StatShr ******************************************************************************/ DlgWznmPrjNew::StatShr::StatShr( const bool DetButAutActive , const bool ButCncActive , const bool ButCreActive ) : Block() { this->DetButAutActive = DetButAutActive; this->ButCncActive = ButCncActive; this->ButCreActive = ButCreActive; mask = {DETBUTAUTACTIVE, BUTCNCACTIVE, BUTCREACTIVE}; }; bool DlgWznmPrjNew::StatShr::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatShrDlgWznmPrjNew"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StatitemShrDlgWznmPrjNew"; if (basefound) { if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "DetButAutActive", DetButAutActive)) add(DETBUTAUTACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButCncActive", ButCncActive)) add(BUTCNCACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButCreActive", ButCreActive)) add(BUTCREACTIVE); }; return basefound; }; set<uint> DlgWznmPrjNew::StatShr::comm( const StatShr* comp ) { set<uint> items; if (DetButAutActive == comp->DetButAutActive) insert(items, DETBUTAUTACTIVE); if (ButCncActive == comp->ButCncActive) insert(items, BUTCNCACTIVE); if (ButCreActive == comp->ButCreActive) insert(items, BUTCREACTIVE); return(items); }; set<uint> DlgWznmPrjNew::StatShr::diff( const StatShr* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {DETBUTAUTACTIVE, BUTCNCACTIVE, BUTCREACTIVE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class DlgWznmPrjNew::Tag ******************************************************************************/ DlgWznmPrjNew::Tag::Tag( const string& Cpt , const string& DetCptSho , const string& DetCptTit , const string& DetCptAbt , const string& DetCptDty , const string& DetCptLoc , const string& DetCptPlc , const string& DetCptTmc , const string& DetButAut , const string& ButCnc , const string& ButCre ) : Block() { this->Cpt = Cpt; this->DetCptSho = DetCptSho; this->DetCptTit = DetCptTit; this->DetCptAbt = DetCptAbt; this->DetCptDty = DetCptDty; this->DetCptLoc = DetCptLoc; this->DetCptPlc = DetCptPlc; this->DetCptTmc = DetCptTmc; this->DetButAut = DetButAut; this->ButCnc = ButCnc; this->ButCre = ButCre; mask = {CPT, DETCPTSHO, DETCPTTIT, DETCPTABT, DETCPTDTY, DETCPTLOC, DETCPTPLC, DETCPTTMC, DETBUTAUT, BUTCNC, BUTCRE}; }; bool DlgWznmPrjNew::Tag::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "TagDlgWznmPrjNew"); else basefound = checkXPath(docctx, basexpath); string itemtag = "TagitemDlgWznmPrjNew"; if (basefound) { if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "Cpt", Cpt)) add(CPT); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "DetCptSho", DetCptSho)) add(DETCPTSHO); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "DetCptTit", DetCptTit)) add(DETCPTTIT); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "DetCptAbt", DetCptAbt)) add(DETCPTABT); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "DetCptDty", DetCptDty)) add(DETCPTDTY); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "DetCptLoc", DetCptLoc)) add(DETCPTLOC); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "DetCptPlc", DetCptPlc)) add(DETCPTPLC); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "DetCptTmc", DetCptTmc)) add(DETCPTTMC); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "DetButAut", DetButAut)) add(DETBUTAUT); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "ButCnc", ButCnc)) add(BUTCNC); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "ButCre", ButCre)) add(BUTCRE); }; return basefound; }; /****************************************************************************** class DlgWznmPrjNew::DpchAppData ******************************************************************************/ DlgWznmPrjNew::DpchAppData::DpchAppData( const string& scrJref , ContIac* contiac , const set<uint>& mask ) : DpchAppWznm(VecWznmVDpch::DPCHAPPDLGWZNMPRJNEWDATA, scrJref) { if (find(mask, ALL)) this->mask = {SCRJREF, CONTIAC}; else this->mask = mask; if (find(this->mask, CONTIAC) && contiac) this->contiac = *contiac; }; string DlgWznmPrjNew::DpchAppData::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(CONTIAC)) ss.push_back("contiac"); StrMod::vectorToString(ss, srefs); return(srefs); }; void DlgWznmPrjNew::DpchAppData::writeXML( xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchAppDlgWznmPrjNewData"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wznm"); if (has(SCRJREF)) writeString(wr, "scrJref", scrJref); if (has(CONTIAC)) contiac.writeXML(wr); xmlTextWriterEndElement(wr); }; /****************************************************************************** class DlgWznmPrjNew::DpchAppDo ******************************************************************************/ DlgWznmPrjNew::DpchAppDo::DpchAppDo( const string& scrJref , const uint ixVDo , const set<uint>& mask ) : DpchAppWznm(VecWznmVDpch::DPCHAPPDLGWZNMPRJNEWDO, scrJref) { if (find(mask, ALL)) this->mask = {SCRJREF, IXVDO}; else this->mask = mask; this->ixVDo = ixVDo; }; string DlgWznmPrjNew::DpchAppDo::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(IXVDO)) ss.push_back("ixVDo"); StrMod::vectorToString(ss, srefs); return(srefs); }; void DlgWznmPrjNew::DpchAppDo::writeXML( xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchAppDlgWznmPrjNewDo"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wznm"); if (has(SCRJREF)) writeString(wr, "scrJref", scrJref); if (has(IXVDO)) writeString(wr, "srefIxVDo", VecVDo::getSref(ixVDo)); xmlTextWriterEndElement(wr); }; /****************************************************************************** class DlgWznmPrjNew::DpchEngData ******************************************************************************/ DlgWznmPrjNew::DpchEngData::DpchEngData() : DpchEngWznm(VecWznmVDpch::DPCHENGDLGWZNMPRJNEWDATA) { feedFDetLstDty.tag = "FeedFDetLstDty"; feedFDetLstLoc.tag = "FeedFDetLstLoc"; feedFDetPupPlc.tag = "FeedFDetPupPlc"; feedFDetPupPmc.tag = "FeedFDetPupPmc"; feedFSge.tag = "FeedFSge"; }; string DlgWznmPrjNew::DpchEngData::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(CONTIAC)) ss.push_back("contiac"); if (has(CONTINF)) ss.push_back("continf"); if (has(FEEDFDETLSTDTY)) ss.push_back("feedFDetLstDty"); if (has(FEEDFDETLSTLOC)) ss.push_back("feedFDetLstLoc"); if (has(FEEDFDETPUPPLC)) ss.push_back("feedFDetPupPlc"); if (has(FEEDFDETPUPPMC)) ss.push_back("feedFDetPupPmc"); if (has(FEEDFSGE)) ss.push_back("feedFSge"); if (has(STATAPP)) ss.push_back("statapp"); if (has(STATSHR)) ss.push_back("statshr"); if (has(TAG)) ss.push_back("tag"); StrMod::vectorToString(ss, srefs); return(srefs); }; void DlgWznmPrjNew::DpchEngData::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchEngDlgWznmPrjNewData"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) add(SCRJREF); if (contiac.readXML(docctx, basexpath, true)) add(CONTIAC); if (continf.readXML(docctx, basexpath, true)) add(CONTINF); if (feedFDetLstDty.readXML(docctx, basexpath, true)) add(FEEDFDETLSTDTY); if (feedFDetLstLoc.readXML(docctx, basexpath, true)) add(FEEDFDETLSTLOC); if (feedFDetPupPlc.readXML(docctx, basexpath, true)) add(FEEDFDETPUPPLC); if (feedFDetPupPmc.readXML(docctx, basexpath, true)) add(FEEDFDETPUPPMC); if (feedFSge.readXML(docctx, basexpath, true)) add(FEEDFSGE); if (statapp.readXML(docctx, basexpath, true)) add(STATAPP); if (statshr.readXML(docctx, basexpath, true)) add(STATSHR); if (tag.readXML(docctx, basexpath, true)) add(TAG); } else { contiac = ContIac(); continf = ContInf(); feedFDetLstDty.clear(); feedFDetLstLoc.clear(); feedFDetPupPlc.clear(); feedFDetPupPmc.clear(); feedFSge.clear(); statapp = StatApp(); statshr = StatShr(); tag = Tag(); }; };
30.259567
144
0.65336
[ "vector" ]
8e52ec19cf99f683e565d75b13db0e961ba089b0
5,841
cc
C++
common_video/h264/pps_parser.cc
jxfwinter/webrtc
abd2ed091133fe2201c90638bfc93aca6d1bd1ae
[ "BSD-3-Clause" ]
null
null
null
common_video/h264/pps_parser.cc
jxfwinter/webrtc
abd2ed091133fe2201c90638bfc93aca6d1bd1ae
[ "BSD-3-Clause" ]
null
null
null
common_video/h264/pps_parser.cc
jxfwinter/webrtc
abd2ed091133fe2201c90638bfc93aca6d1bd1ae
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "common_video/h264/pps_parser.h" #include <cstdint> #include <vector> #include "absl/numeric/bits.h" #include "common_video/h264/h264_common.h" #include "rtc_base/bitstream_reader.h" #include "rtc_base/checks.h" namespace webrtc { namespace { constexpr int kMaxPicInitQpDeltaValue = 25; constexpr int kMinPicInitQpDeltaValue = -26; } // namespace // General note: this is based off the 02/2014 version of the H.264 standard. // You can find it on this page: // http://www.itu.int/rec/T-REC-H.264 absl::optional<PpsParser::PpsState> PpsParser::ParsePps(const uint8_t* data, size_t length) { // First, parse out rbsp, which is basically the source buffer minus emulation // bytes (the last byte of a 0x00 0x00 0x03 sequence). RBSP is defined in // section 7.3.1 of the H.264 standard. return ParseInternal(H264::ParseRbsp(data, length)); } bool PpsParser::ParsePpsIds(const uint8_t* data, size_t length, uint32_t* pps_id, uint32_t* sps_id) { RTC_DCHECK(pps_id); RTC_DCHECK(sps_id); // First, parse out rbsp, which is basically the source buffer minus emulation // bytes (the last byte of a 0x00 0x00 0x03 sequence). RBSP is defined in // section 7.3.1 of the H.264 standard. std::vector<uint8_t> unpacked_buffer = H264::ParseRbsp(data, length); BitstreamReader reader(unpacked_buffer); *pps_id = reader.ReadExponentialGolomb(); *sps_id = reader.ReadExponentialGolomb(); return reader.Ok(); } absl::optional<uint32_t> PpsParser::ParsePpsIdFromSlice(const uint8_t* data, size_t length) { std::vector<uint8_t> unpacked_buffer = H264::ParseRbsp(data, length); BitstreamReader slice_reader(unpacked_buffer); // first_mb_in_slice: ue(v) slice_reader.ReadExponentialGolomb(); // slice_type: ue(v) slice_reader.ReadExponentialGolomb(); // pic_parameter_set_id: ue(v) uint32_t slice_pps_id = slice_reader.ReadExponentialGolomb(); if (!slice_reader.Ok()) { return absl::nullopt; } return slice_pps_id; } absl::optional<PpsParser::PpsState> PpsParser::ParseInternal( rtc::ArrayView<const uint8_t> buffer) { BitstreamReader reader(buffer); PpsState pps; pps.id = reader.ReadExponentialGolomb(); pps.sps_id = reader.ReadExponentialGolomb(); // entropy_coding_mode_flag: u(1) pps.entropy_coding_mode_flag = reader.Read<bool>(); // bottom_field_pic_order_in_frame_present_flag: u(1) pps.bottom_field_pic_order_in_frame_present_flag = reader.Read<bool>(); // num_slice_groups_minus1: ue(v) uint32_t num_slice_groups_minus1 = reader.ReadExponentialGolomb(); if (num_slice_groups_minus1 > 0) { // slice_group_map_type: ue(v) uint32_t slice_group_map_type = reader.ReadExponentialGolomb(); if (slice_group_map_type == 0) { for (uint32_t i_group = 0; i_group <= num_slice_groups_minus1 && reader.Ok(); ++i_group) { // run_length_minus1[iGroup]: ue(v) reader.ReadExponentialGolomb(); } } else if (slice_group_map_type == 1) { // TODO(sprang): Implement support for dispersed slice group map type. // See 8.2.2.2 Specification for dispersed slice group map type. } else if (slice_group_map_type == 2) { for (uint32_t i_group = 0; i_group <= num_slice_groups_minus1 && reader.Ok(); ++i_group) { // top_left[iGroup]: ue(v) reader.ReadExponentialGolomb(); // bottom_right[iGroup]: ue(v) reader.ReadExponentialGolomb(); } } else if (slice_group_map_type == 3 || slice_group_map_type == 4 || slice_group_map_type == 5) { // slice_group_change_direction_flag: u(1) reader.ConsumeBits(1); // slice_group_change_rate_minus1: ue(v) reader.ReadExponentialGolomb(); } else if (slice_group_map_type == 6) { // pic_size_in_map_units_minus1: ue(v) uint32_t pic_size_in_map_units = reader.ReadExponentialGolomb() + 1; int slice_group_id_bits = 1 + absl::bit_width(num_slice_groups_minus1); // slice_group_id: array of size pic_size_in_map_units, each element // is represented by ceil(log2(num_slice_groups_minus1 + 1)) bits. reader.ConsumeBits(slice_group_id_bits * pic_size_in_map_units); } } // num_ref_idx_l0_default_active_minus1: ue(v) reader.ReadExponentialGolomb(); // num_ref_idx_l1_default_active_minus1: ue(v) reader.ReadExponentialGolomb(); // weighted_pred_flag: u(1) pps.weighted_pred_flag = reader.Read<bool>(); // weighted_bipred_idc: u(2) pps.weighted_bipred_idc = reader.ReadBits(2); // pic_init_qp_minus26: se(v) pps.pic_init_qp_minus26 = reader.ReadSignedExponentialGolomb(); // Sanity-check parsed value if (!reader.Ok() || pps.pic_init_qp_minus26 > kMaxPicInitQpDeltaValue || pps.pic_init_qp_minus26 < kMinPicInitQpDeltaValue) { return absl::nullopt; } // pic_init_qs_minus26: se(v) reader.ReadExponentialGolomb(); // chroma_qp_index_offset: se(v) reader.ReadExponentialGolomb(); // deblocking_filter_control_present_flag: u(1) // constrained_intra_pred_flag: u(1) reader.ConsumeBits(2); // redundant_pic_cnt_present_flag: u(1) pps.redundant_pic_cnt_present_flag = reader.ReadBit(); if (!reader.Ok()) { return absl::nullopt; } return pps; } } // namespace webrtc
37.683871
80
0.69697
[ "vector" ]
8e56d259dbb57aef36590f04f4d7bb37c4339813
8,210
cc
C++
tensorflow/compiler/tf2xla/kernels/gather_op.cc
Asurada2015/tensorflow
5828e285209ff8c3d1bef2e4bd7c55ca611080d5
[ "Apache-2.0" ]
1
2020-06-10T10:59:35.000Z
2020-06-10T10:59:35.000Z
tensorflow/compiler/tf2xla/kernels/gather_op.cc
ChenAugustus/tensorflow
5828e285209ff8c3d1bef2e4bd7c55ca611080d5
[ "Apache-2.0" ]
null
null
null
tensorflow/compiler/tf2xla/kernels/gather_op.cc
ChenAugustus/tensorflow
5828e285209ff8c3d1bef2e4bd7c55ca611080d5
[ "Apache-2.0" ]
1
2019-11-13T11:33:56.000Z
2019-11-13T11:33:56.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/tf2xla/kernels/gather_op.h" #include "tensorflow/compiler/tf2xla/kernels/gather_op_helpers.h" #include "tensorflow/compiler/tf2xla/shape_util.h" #include "tensorflow/compiler/tf2xla/xla_context.h" #include "tensorflow/compiler/tf2xla/xla_helpers.h" #include "tensorflow/compiler/tf2xla/xla_op_kernel.h" #include "tensorflow/compiler/tf2xla/xla_op_registry.h" #include "tensorflow/core/framework/kernel_def_builder.h" namespace tensorflow { xla::ComputationDataHandle XlaComputeGatherDynamicSlice( const xla::ComputationDataHandle& input, const TensorShape& input_shape, const xla::ComputationDataHandle& indices, const TensorShape& indices_shape, DataType dtype, xla::ComputationBuilder* builder) { const int num_indices = indices_shape.num_elements(); // Flatten the indices into 1-D. auto indices_1d = builder->Reshape(indices, {num_indices}); // Compute the slice for each of these indices separately. std::vector<xla::ComputationDataHandle> slices(num_indices); for (int i = 0; i < num_indices; ++i) { auto index = builder->Slice(indices_1d, {i}, {i + 1}, {1}); auto start_indices = XlaHelpers::PadWithZeros(builder, index, input_shape.dims() - 1); auto slice_shape = input_shape.dim_sizes(); slice_shape[0] = 1; slices[i] = builder->DynamicSlice(input, start_indices, slice_shape); } xla::ComputationDataHandle gather; if (slices.empty()) { auto shape = input_shape.dim_sizes(); shape[0] = 0; gather = builder->Broadcast(XlaHelpers::Zero(builder, dtype), shape); } else { gather = builder->ConcatInDim(slices, 0); } // Compute the shape of the result tensor, which is: // indices.shape + resource.shape[1:] TensorShape gather_shape = indices_shape; gather_shape.AppendShape(input_shape); gather_shape.RemoveDim(indices_shape.dims()); // Reshape the concatenated slices into the shape expected of the result // tensor. return builder->Reshape(gather, gather_shape.dim_sizes()); } namespace { class GatherOpCustomCall : public XlaOpKernel { public: explicit GatherOpCustomCall(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} void Compile(XlaOpKernelContext* ctx) override { const TensorShape params_shape = ctx->InputShape(0); const auto params_dims = params_shape.dims(); const TensorShape indices_shape = ctx->InputShape(1); OP_REQUIRES( ctx, TensorShapeUtils::IsVectorOrHigher(params_shape), errors::InvalidArgument("params must be at least 1 dimensional")); DataType index_type = input_type(1); OP_REQUIRES(ctx, index_type == DT_INT32 || index_type == DT_INT64, errors::InvalidArgument("index must be int32 or int64")); // GatherV2 added an axis argument. We support both Gather and GatherV2 in // this kernel by defaulting axis to 0 if there are 2 inputs. int64 axis = 0; if (ctx->num_inputs() == 3) { const TensorShape axis_shape = ctx->InputShape(2); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(axis_shape), errors::InvalidArgument("axis must be scalar")); DataType axis_type = input_type(2); OP_REQUIRES(ctx, axis_type == DT_INT32 || axis_type == DT_INT64, errors::InvalidArgument("axis must be int32 or int64")); xla::Literal literal; OP_REQUIRES_OK(ctx, ctx->ConstantInput(2, &literal)); int64 axis_input = axis_type == DT_INT32 ? literal.Get<int32>({}) : literal.Get<int64>({}); axis = axis_input < 0 ? axis_input + params_dims : axis_input; OP_REQUIRES(ctx, 0 <= axis && axis < params_dims, errors::InvalidArgument("Expected axis in the range [", -params_dims, ", ", params_dims, "), but got ", axis_input)); } // Check that we have enough index space. const int64 limit = index_type == DT_INT32 ? std::numeric_limits<int32>::max() : std::numeric_limits<int64>::max(); OP_REQUIRES(ctx, params_shape.dim_size(axis) <= limit, errors::InvalidArgument( "params.shape[", axis, "] too large for ", DataTypeString(index_type), " indexing: ", params_shape.dim_size(axis), " > ", limit)); // The result shape is params.shape[0:axis] + indices.shape + // params.shape[axis + 1:]. TensorShape result_shape; int64 outer_size = 1; int64 inner_size = 1; for (int i = 0; i < axis; i++) { result_shape.AddDim(params_shape.dim_size(i)); outer_size *= params_shape.dim_size(i); } result_shape.AppendShape(indices_shape); for (int i = axis + 1; i < params_dims; i++) { result_shape.AddDim(params_shape.dim_size(i)); inner_size *= params_shape.dim_size(i); } XlaContext& tc = XlaContext::Get(ctx); OP_REQUIRES( ctx, tc.allow_cpu_custom_calls(), errors::InvalidArgument("Gather op requires CustomCall on CPU")); xla::ComputationBuilder& b = *ctx->builder(); // Call gather_xla_float_kernel (from gather_op_kernel_float.cc). // XLA passes <out> to the function, so it is not included here. std::vector<xla::ComputationDataHandle> args; args.push_back(tc.GetOrCreateRuntimeContextParameter()); args.push_back(b.ConstantLiteral( *xla::Literal::CreateR0<int64>(indices_shape.num_elements()))); args.push_back( b.ConstantLiteral(*xla::Literal::CreateR0<int64>(outer_size))); args.push_back(b.ConstantLiteral( *xla::Literal::CreateR0<int64>(params_shape.dim_size(axis)))); args.push_back( b.ConstantLiteral(*xla::Literal::CreateR0<int64>(inner_size))); args.push_back(ctx->Input(0)); args.push_back(ctx->Input(1)); xla::Shape xla_out_shape; OP_REQUIRES_OK( ctx, TensorShapeToXLAShape(DT_FLOAT, result_shape, &xla_out_shape)); // Call the custom code with args: xla::ComputationDataHandle output; if (index_type == DT_INT32) { output = b.CustomCall("gather_float_int32_xla_impl", args, xla_out_shape); } else { output = b.CustomCall("gather_float_int64_xla_impl", args, xla_out_shape); } ctx->SetOutput(0, output); } private: TF_DISALLOW_COPY_AND_ASSIGN(GatherOpCustomCall); }; REGISTER_XLA_OP(Name("Gather") .TypeConstraint("Tparams", DT_FLOAT) .Device(DEVICE_CPU_XLA_JIT), GatherOpCustomCall); REGISTER_XLA_OP(Name("GatherV2") .TypeConstraint("Tparams", DT_FLOAT) .Device(DEVICE_CPU_XLA_JIT), GatherOpCustomCall); } // namespace GatherOpDynamicSlice::GatherOpDynamicSlice(OpKernelConstruction* context) : XlaOpKernel(context) {} void GatherOpDynamicSlice::Compile(XlaOpKernelContext* context) { xla::ComputationBuilder* builder = context->builder(); auto input = context->Input(0); auto input_shape = context->InputShape(0); auto indices = context->Input(1); auto indices_shape = context->InputShape(1); xla::ComputationDataHandle gather = XlaComputeGatherDynamicSlice( input, input_shape, indices, indices_shape, DT_FLOAT, builder); context->SetOutput(0, gather); } REGISTER_XLA_OP(Name("Gather") .TypeConstraint("Tparams", DT_FLOAT) .Device(DEVICE_GPU_XLA_JIT), GatherOpDynamicSlice); } // namespace tensorflow
39.661836
80
0.669671
[ "shape", "vector" ]
8e5a4180121ee22f0d8addc5e6e6d514c242b4ea
412
cpp
C++
Source/Novah.AdvancedMath/Ray.cpp
jorgy343/NovahTracer
d430d8ff4871bd838dafd7beef9d745193206fa7
[ "MIT" ]
null
null
null
Source/Novah.AdvancedMath/Ray.cpp
jorgy343/NovahTracer
d430d8ff4871bd838dafd7beef9d745193206fa7
[ "MIT" ]
null
null
null
Source/Novah.AdvancedMath/Ray.cpp
jorgy343/NovahTracer
d430d8ff4871bd838dafd7beef9d745193206fa7
[ "MIT" ]
null
null
null
#include "NovahAdvancedMath.h" using namespace Novah::AdvancedMath; Ray::Ray(Vector3 position, Vector3 direction) : Position(position), Direction(direction) { } const Surface* Ray::IntersectRay(const Ray& ray, IntersectionData* intersectionData) const { return nullptr; } const Surface* Ray::IntersectRay(const Ray& ray, std::vector<IntersectionData>* intersectionData) const { return nullptr; }
21.684211
103
0.757282
[ "vector" ]
8e5c20e1d0e3f0cbd618a1b0c9dcd59024c1d150
1,863
hpp
C++
include/ghostfragment/property_types/subset_map.hpp
rmrresearch/GhostFragment
7f0dbcfab3054416ee788c9e972528f15b4d611b
[ "Apache-2.0" ]
null
null
null
include/ghostfragment/property_types/subset_map.hpp
rmrresearch/GhostFragment
7f0dbcfab3054416ee788c9e972528f15b4d611b
[ "Apache-2.0" ]
1
2022-02-25T16:20:50.000Z
2022-02-25T16:20:50.000Z
include/ghostfragment/property_types/subset_map.hpp
rmrresearch/GhostFragment
7f0dbcfab3054416ee788c9e972528f15b4d611b
[ "Apache-2.0" ]
null
null
null
#pragma once #include <simde/simde.hpp> namespace ghostfragment::pt { template<typename Type2Fragment, typename MappedType> struct SubsetMapTraits { /// Type of the FamilyOfSets used for the keys using fos_key_type = chemist::set_theory::FamilyOfSets<Type2Fragment>; /// Type of the FamilyOfSets used for the values using fos_value_type = chemist::set_theory::FamilyOfSets<MappedType>; /// Type of the key in the returned map using key_type = typename fos_key_type::value_type; /// Type of the value in the returned map using value_type = typename fos_value_type::value_type; using input0_type = const fos_key_type&; using input1_type = MappedType; using result_type = std::map<key_type, value_type>; }; template<typename Type2Fragment, typename MappedType> DECLARE_TEMPLATED_PROPERTY_TYPE(SubsetMap, Type2Fragment, MappedType); template<typename Type2Fragment, typename MappedType> TEMPLATED_PROPERTY_TYPE_INPUTS(SubsetMap, Type2Fragment, MappedType) { using traits_type = SubsetMapTraits<Type2Fragment, MappedType>; using input0_type = typename traits_type::input0_type; using input1_type = typename traits_type::input1_type; return pluginplay::declare_input() .add_field<input0_type>("Subsets") .template add_field<input1_type>("Object to map"); } template<typename Type2Fragment, typename MappedType> TEMPLATED_PROPERTY_TYPE_RESULTS(SubsetMap, Type2Fragment, MappedType) { using traits_type = SubsetMapTraits<Type2Fragment, MappedType>; using result_type = typename traits_type::result_type; return pluginplay::declare_result().add_field<result_type>("map"); } using Frag2AO = SubsetMap<simde::type::molecule, simde::type::ao_basis_set>; using Frag2AOTraits = SubsetMapTraits<simde::type::molecule, simde::type::ao_basis_set>; } // namespace ghostfragment::pt
35.826923
76
0.770263
[ "object" ]
769d7e96e5614eda033954d9164ee619faa60ba9
9,473
cpp
C++
src/graphics/texture/objectlod.cpp
Terebinth/freefalcon-central
c28d807183ab447ef6a801068aa3769527d55deb
[ "BSD-2-Clause" ]
117
2015-01-13T14:48:49.000Z
2022-03-16T01:38:19.000Z
src/graphics/texture/objectlod.cpp
darongE/freefalcon-central
c28d807183ab447ef6a801068aa3769527d55deb
[ "BSD-2-Clause" ]
4
2015-05-01T13:09:53.000Z
2017-07-22T09:11:06.000Z
src/graphics/texture/objectlod.cpp
darongE/freefalcon-central
c28d807183ab447ef6a801068aa3769527d55deb
[ "BSD-2-Clause" ]
78
2015-01-13T09:27:47.000Z
2022-03-18T14:39:09.000Z
/***************************************************************************\ ObjectLOD.cpp Scott Randolph February 9, 1998 Provides structures and definitions for 3D objects. \***************************************************************************/ #include "stdafx.h" #include <io.h> #include <fcntl.h> #include "Loader.h" #include "ObjectLOD.h" #ifdef USE_SH_POOLS extern MEM_POOL gBSPLibMemPool; #endif ObjectLOD *TheObjectLODs = NULL; int TheObjectLODsCount = 0; #ifdef _DEBUG int ObjectLOD::lodsLoaded = 0; #endif FileMemMap ObjectLOD::ObjectLodMap; CRITICAL_SECTION ObjectLOD::cs_ObjectLOD; static int maxTagList; extern bool g_bUseMappedFiles; ObjectLOD::ObjectLOD() { root = NULL; flags = 0; refCount = 0; onOrder = 0; } ObjectLOD::~ObjectLOD() { ShiAssert(!onOrder); ShiAssert(!root); } void ObjectLOD::SetupEmptyTable(int numEntries) { #ifdef USE_SMART_HEAP pool = MemPoolInit(0); #endif // Create the contiguous array of (unitialized) LOD records ShiAssert(TheObjectLODs == NULL); #ifdef USE_SH_POOLS TheObjectLODs = (ObjectLOD *)MemAllocPtr(gBSPLibMemPool, sizeof(ObjectLOD) * (numEntries), 0); #else TheObjectLODs = new ObjectLOD[numEntries]; #endif TheObjectLODsCount = numEntries; // Init our critical section InitializeCriticalSection(&cs_ObjectLOD); } void ObjectLOD::SetupTable(int file, char *basename) { char filename[_MAX_PATH]; int result; #ifdef USE_SMART_HEAP pool = MemPoolInit(0); #endif // Read the number of elements in the longest tag list we saw in the LOD data result = read(file, &maxTagList, sizeof(maxTagList)); // Read the length of the LOD header array result = read(file, &TheObjectLODsCount, sizeof(TheObjectLODsCount)); // Allocate memory for the LOD array TheObjectLODs = new ObjectLOD[TheObjectLODsCount]; ShiAssert(TheObjectLODs); // Allocate memory for the tag list buffer (read time use only) tagListBuffer = new BNodeType[maxTagList + 1]; ShiAssert(tagListBuffer); // Read the elements of the header array result = read(file, TheObjectLODs, sizeof(*TheObjectLODs) * TheObjectLODsCount); if (result < 0) { char message[256]; sprintf(message, "Reading object LOD headers: %s", strerror(errno)); ShiError(message); } // Open the data file we'll read from at run time as object LODs are required strcpy(filename, basename); strcat(filename, ".LOD"); if (!ObjectLodMap.Open(filename, FALSE, !g_bUseMappedFiles)) { char message[256]; sprintf(message, "Failed to open object LOD database %s", filename); ShiError(message); } // Init our critical section InitializeCriticalSection(&cs_ObjectLOD); } void ObjectLOD::CleanupTable(void) { // Make sure all objects are freed for (int i = 0; i < TheObjectLODsCount; i++) { ShiAssert(TheObjectLODs[i].refCount == 0); // Must wait until loader is done before we delete the object out from under it. while (TheObjectLODs[i].onOrder); } // Free our array of object LODs delete[] TheObjectLODs; TheObjectLODs = NULL; TheObjectLODsCount = 0; // Free our tag list buffer delete[] tagListBuffer; tagListBuffer = NULL; // Close our data file ObjectLodMap.Close(); //close( objectFile ); // Free our critical section DeleteCriticalSection(&cs_ObjectLOD); #ifdef USE_SMART_HEAP MemPoolFree(pool); #endif } BOOL ObjectLOD::Fetch(void) { BOOL result; EnterCriticalSection(&cs_ObjectLOD); ShiAssert(refCount > 0); // If we already have our data, we can draw if (root) { result = TRUE; } else { if (onOrder == 1) { // Normal case, do nothing but wait } else if (onOrder == 0) { // Not requested yet, so go get it RequestLoad(); onOrder = 1; } else { // Requested, dropped, and now requested again all before the IO completed ShiAssert(onOrder == -1); onOrder = 1; } result = FALSE; } LeaveCriticalSection(&cs_ObjectLOD); // Return a flag indicating whether or not the data is available for drawing return result; } // This is called from inside our critical section... void ObjectLOD::RequestLoad(void) { LoaderQ *request; // Allocate space for the async IO request request = new LoaderQ; if (!request) { ShiError("Failed to allocate memory for an object read request"); } // Build the data transfer request to get the required object data request->filename = NULL; request->fileoffset = fileoffset; request->callback = LoaderCallBack; request->parameter = this; // Submit the request to the asynchronous loader TheLoader.EnqueueRequest(request); } void ObjectLOD::LoaderCallBack(LoaderQ* request) { int size; int tagCount; BYTE *nodeTreeData; BRoot *root; BNodeType *tagList = tagListBuffer; ObjectLOD *objLOD = (ObjectLOD*)request->parameter; DWORD offset = objLOD->fileoffset; // TODO: Decompress in here... // Seek to the required data on disk ShiAssert(request->fileoffset == objLOD->fileoffset); if (g_bUseMappedFiles) { BYTE *data = ObjectLodMap.GetData(offset, objLOD->filesize); if (data == NULL) { char message[120]; sprintf(message, "%s: Bad object map", strerror(errno)); ShiError(message); } tagCount = *(DWORD *)data;; data += sizeof(DWORD); ShiAssert(tagCount <= maxTagList); memcpy(tagListBuffer, data, tagCount * sizeof(*tagListBuffer)); data += tagCount * sizeof(*tagListBuffer); size = objLOD->filesize - sizeof(tagCount) - tagCount * sizeof(*tagListBuffer); #ifdef USE_SMART_HEAP nodeTreeData = (BYTE*)MemAllocPtr(pool, size, 0); #else nodeTreeData = (BYTE*)malloc(size); #endif ShiAssert(nodeTreeData); memcpy(nodeTreeData, data, size); } else { // Read the tag list length if (!ObjectLodMap.ReadDataAt(offset, &tagCount, sizeof(tagCount))) { char message[120]; sprintf(message, "%s: Bad object seek", strerror(errno)); ShiError(message); } offset += sizeof(tagCount); ShiAssert(tagCount <= maxTagList); // Read the tag list if (!ObjectLodMap.ReadDataAt(offset, tagListBuffer, tagCount * sizeof(*tagListBuffer))) { char message[120]; sprintf(message, "%s: Bad taglist read", strerror(errno)); ShiError(message); } offset += tagCount * sizeof(*tagListBuffer); // Compute the size of the node tree size = objLOD->filesize - sizeof(tagCount) - tagCount * sizeof(*tagListBuffer); // Allocate memory for the node tree #ifdef USE_SMART_HEAP nodeTreeData = (BYTE*)MemAllocPtr(pool, size, 0); #else nodeTreeData = (BYTE*)malloc(size); #endif ShiAssert(nodeTreeData); // Read the BSP tree node data if (!ObjectLodMap.ReadDataAt(offset, nodeTreeData, size)) { char message[120]; sprintf(message, "%s: Bad Lod read", strerror(errno)); ShiError(message); } } // Restore the virtual function tables and pointer connectivity of the node tree root = (BRoot*)BNode::RestorePointers(nodeTreeData, 0, &tagList); ShiAssert(root->Type() == tagBRoot); ShiAssert((BYTE*)root == nodeTreeData); // Ensure it will be legal to use "root" to delete the whole buffer later... // Load all our textures root->LoadTextures(); // Mark ourselves no longer queued for IO EnterCriticalSection(&cs_ObjectLOD); #ifdef _DEBUG objLOD->lodsLoaded ++; #endif if (objLOD->onOrder == 1) { objLOD->root = root; } else { ShiAssert(objLOD->onOrder == -1); // We must have been Unloaded before IO completed root->UnloadTextures(); #ifdef _DEBUG objLOD->lodsLoaded --; #endif delete root; } objLOD->onOrder = 0; LeaveCriticalSection(&cs_ObjectLOD); // Free the request queue entry delete request; } void ObjectLOD::Unload(void) { BYTE *nodeTreeData; EnterCriticalSection(&cs_ObjectLOD); if (!onOrder) { if (root) { root->UnloadTextures(); nodeTreeData = (BYTE*)root; #ifdef USE_SMART_HEAP MemFreePtr(nodeTreeData); #else free(nodeTreeData); #endif root = NULL; #ifdef _DEBUG lodsLoaded --; #endif } } else { if (TheLoader.CancelRequest(LoaderCallBack, this, NULL, fileoffset)) { // Normal case, we canceled the request, so we're done. onOrder = 0; } else { // Couldn't cancel the request, so set a flag to drop the object when it finally arrives. ShiAssert(onOrder == 1); onOrder = -1; } } LeaveCriticalSection(&cs_ObjectLOD); } // Privatly used static members //int ObjectLOD::objectFile = -1; BNodeType* ObjectLOD::tagListBuffer = NULL; #ifdef USE_SMART_HEAP MEM_POOL ObjectLOD::pool; #endif
24.478036
120
0.61575
[ "object", "3d" ]
76a2c17a0818f88cd069a3f70f01d3f7bbfb0737
4,308
cpp
C++
CARET_analyze_cpp_impl/src/records_map_impl.cpp
tier4/CARET_analyze_cpp_impl
e4c6abfc3f76ef036130fc1cae4e904c685d69fd
[ "Apache-2.0" ]
null
null
null
CARET_analyze_cpp_impl/src/records_map_impl.cpp
tier4/CARET_analyze_cpp_impl
e4c6abfc3f76ef036130fc1cae4e904c685d69fd
[ "Apache-2.0" ]
null
null
null
CARET_analyze_cpp_impl/src/records_map_impl.cpp
tier4/CARET_analyze_cpp_impl
e4c6abfc3f76ef036130fc1cae4e904c685d69fd
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 Research Institute of Systems Planning, 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 <unordered_set> #include <unordered_map> #include <vector> #include <string> #include <limits> #include <iostream> #include <fstream> #include <algorithm> #include <set> #include <map> #include <memory> #include <tuple> #include <utility> #include <iterator> #include "nlohmann/json.hpp" #include "caret_analyze_cpp_impl/record.hpp" #include "caret_analyze_cpp_impl/common.hpp" #include "caret_analyze_cpp_impl/column_manager.hpp" #include "caret_analyze_cpp_impl/progress.hpp" #include "caret_analyze_cpp_impl/records.hpp" RecordsMapImpl::RecordsMapImpl( std::vector<Record> records, const std::vector<std::string> columns, const std::vector<std::string> key_columns ) : RecordsBase(columns), data_(std::make_unique<DataT>()), key_columns_(key_columns) { if (key_columns.size() > max_key_size_) { throw std::exception(); } for (auto & record : records) { append(record); } } RecordsMapImpl::~RecordsMapImpl() { } RecordsMapImpl::RecordsMapImpl( const std::vector<std::string> key_columns ) : RecordsMapImpl({}, {}, key_columns) { } RecordsMapImpl::RecordsMapImpl(const RecordsMapImpl & records) : RecordsMapImpl(records, records.get_columns()) { } RecordsMapImpl::RecordsMapImpl( const std::vector<std::string> columns, const std::vector<std::string> key_columns ) : RecordsMapImpl({}, columns, key_columns) { } RecordsMapImpl::RecordsMapImpl( const RecordsMapImpl & records, const std::vector<std::string> key_columns) : RecordsMapImpl(records.get_data(), records.get_columns(), key_columns) { } void RecordsMapImpl::bind_drop_as_delay() { throw std::exception(); } void RecordsMapImpl::append(const Record & other) { auto key = make_key(other); auto pair = std::make_pair(key, other); data_->insert(pair); } RecordsMapImpl::KeyT RecordsMapImpl::make_key(const Record & record) { std::vector<uint64_t> key_values = {0, 0, 0}; for (size_t i = 0; i < key_columns_.size(); i++) { auto & column = key_columns_[i]; key_values[i] = record.get(column); } return std::make_tuple(key_values[0], key_values[1], key_values[2]); } std::unique_ptr<RecordsBase> RecordsMapImpl::clone() const { return std::make_unique<RecordsMapImpl>(*this); } std::vector<Record> RecordsMapImpl::get_data() const { std::vector<Record> data; for (auto & record : *data_) { data.push_back(record.second); } return data; } void RecordsMapImpl::filter_if(const std::function<bool(Record)> & f) { auto tmp = std::make_unique<DataT>(); for (auto it = begin(); it->has_next(); it->next()) { auto & record = it->get_record(); if (f(record)) { auto key = make_key(record); tmp->insert(std::make_pair(key, record)); } } data_ = std::move(tmp); } void RecordsMapImpl::sort(std::string key, std::string sub_key, bool ascending) { (void) key; (void) sub_key; (void) ascending; throw std::exception(); } void RecordsMapImpl::sort_column_order(bool ascending, bool put_none_at_top) { (void) ascending; (void) put_none_at_top; throw std::exception(); } std::size_t RecordsMapImpl::size() const { return data_->size(); } std::unique_ptr<IteratorBase> RecordsMapImpl::begin() { return std::make_unique<MapIterator>(data_->begin(), data_->end()); } std::unique_ptr<ConstIteratorBase> RecordsMapImpl::cbegin() const { return std::make_unique<MapConstIterator>(data_->begin(), data_->end()); } std::unique_ptr<IteratorBase> RecordsMapImpl::rbegin() { return std::make_unique<MapIterator>(data_->rbegin(), data_->rend()); } std::unique_ptr<ConstIteratorBase> RecordsMapImpl::crbegin() const { return std::make_unique<MapConstIterator>(data_->rbegin(), data_->rend()); }
23.933333
79
0.716574
[ "vector" ]
76ad921a93fac4e957ac09b457669470082caf7d
1,879
hpp
C++
test/dtl_test_common.hpp
JanX2/dtl
36e808308e7c95b59e0b3bb3029a524a1e90a270
[ "BSD-3-Clause" ]
238
2015-02-28T12:07:23.000Z
2022-02-24T02:22:52.000Z
test/dtl_test_common.hpp
JanX2/dtl
36e808308e7c95b59e0b3bb3029a524a1e90a270
[ "BSD-3-Clause" ]
10
2015-10-22T17:25:36.000Z
2021-05-10T13:50:10.000Z
test/dtl_test_common.hpp
JanX2/dtl
36e808308e7c95b59e0b3bb3029a524a1e90a270
[ "BSD-3-Clause" ]
55
2015-05-15T12:01:08.000Z
2021-12-20T13:34:09.000Z
#ifndef DTL_TEST_COMMON #define DTL_TEST_COMMON #include <gtest/gtest.h> #include <cstdio> #include <string> #include <vector> #include <utility> #include <iostream> #include <fstream> #include <dtl/dtl.hpp> using std::cerr; using std::endl; using std::string; using std::vector; using std::pair; using std::ifstream; using std::ofstream; using dtl::Diff; using dtl::Diff3; using dtl::Compare; using dtl::SES_COMMON; using dtl::SES_ADD; using dtl::SES_DELETE; using dtl::elemInfo; using dtl::uniHunk; #define dtl_test_typedefs(e_type, seq_type) \ typedef e_type elem; \ typedef seq_type sequence; \ typedef pair< elem, elemInfo > sesElem; \ typedef vector< elem > elemVec; \ typedef vector< sesElem > sesElemVec; \ typedef vector< uniHunk< sesElem > > uniHunkVec; enum type_diff { TYPE_DIFF_SES, TYPE_DIFF_UNI }; string create_path (const string& test_name, string diff_name, enum type_diff t, bool is_use_suffix = false); size_t cal_diff_uni (const string& path_l, const string& path_r); bool is_file_exist (string& fs); void diff_resultset_exist_check (string &fs); template <typename T> class Remover { public : void operator()(const T& v){ remove(v.path_rses.c_str()); remove(v.path_rhunks.c_str()); } }; template < typename elem, typename sequence, typename comparator > void create_file (const string& path, Diff< elem, sequence, comparator >& diff, enum type_diff t) { ofstream ofs; ofs.open(path.c_str()); switch (t) { case TYPE_DIFF_SES: diff.printSES(ofs); break; case TYPE_DIFF_UNI: diff.printUnifiedFormat(ofs); break; } ofs.close(); } #endif // DTL_TEST_COMMON
26.464789
109
0.632251
[ "vector" ]
76b5f7a2fc7afaca1fb6488d73dd19c473bb4566
3,240
cpp
C++
cpp/A0695/main.cpp
Modnars/LeetCode
1c91fe9598418e6ed72233260f9cd8d5737fe216
[ "Apache-2.0" ]
2
2021-11-26T14:06:13.000Z
2021-11-26T14:34:34.000Z
cpp/A0695/main.cpp
Modnars/LeetCode
1c91fe9598418e6ed72233260f9cd8d5737fe216
[ "Apache-2.0" ]
2
2021-11-26T14:06:49.000Z
2021-11-28T11:28:49.000Z
cpp/A0695/main.cpp
Modnars/LeetCode
1c91fe9598418e6ed72233260f9cd8d5737fe216
[ "Apache-2.0" ]
null
null
null
// URL : https://leetcode-cn.com/problems/max-area-of-island/ // Author : Modnar // Date : 2020/03/15 #include <bits/stdc++.h> /* ************************* */ /** * 深度优先搜索(DFS) * 遍历grid中的结点,若grid[i][j]为1,则对该点进行深度优先搜索,计算其所在“岛屿” * 的area,并更新ans。 * 需要注意的是,每当添加一个点到area中时,应当更新该点状态为“已遍历”,这样操作可 * 以通过修改grid中的值来实现。当然,如果要求不可修改grid内容,可将grid内容进行拷贝。 * * 复杂度: * 由于每个顶点均只遍历一次,故算法复杂度为O(m*n),其中尽管对一些顶点进行了DFS,但 * 这些顶点后续不会被遍历,因而得到算法复杂度。 * * 同理,使用广度优先搜索也可以实现解题。 */ // Time: 8ms(99.40%) Memory: 24.4MB(5.71%) class Solution { public: int maxAreaOfIsland(std::vector<std::vector<int>> &grid) { int m = grid.size(), ans = 0; if (m == 0) return ans; int n = grid[0].size(); std::stack<std::pair<int, int>> stk; for (int i = 0; i != m; ++i) { for (int j = 0; j != n; ++j) { if (grid[i][j]) { // std::cout << "Here" << std::endl; int area = 0; stk.push(std::make_pair(i, j)); grid[i][j] = 0; while (!stk.empty()) { // DFS auto pos = stk.top(); stk.pop(); ++area; ans = std::max(ans, area); // std::cout << pos.first << " " << pos.second << std::endl; for (int k = 0; k != 4; ++k) { int tx = pos.first + dir_x[k], ty = pos.second + dir_y[k]; if (tx < 0 || tx == m || ty < 0 || ty == n || !grid[tx][ty]) continue; stk.push(std::make_pair(tx, ty)); grid[tx][ty] = 0; } } } } } return ans; } private: const static std::vector<int> dir_x; const static std::vector<int> dir_y; }; const std::vector<int> Solution::dir_x = {1, -1, 0, 0}; const std::vector<int> Solution::dir_y = {0, 0, -1, 1}; /* ************************* */ // 推荐阅读: // Thanks: LeetCode(leetcode.cn) // Solution: https://leetcode-cn.com/problems/max-area-of-island/solution/dao-yu-de-zui-da-mian-ji-by-leetcode-solution/ int main(int argc, const char *argv[]) { Solution *solution = new Solution(); std::vector<std::vector<int>> grid = { {0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0}, {0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0}, {0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0} }; std::cout << solution->maxAreaOfIsland(grid) << std::endl; // Ans: 6 grid = {{0, 0, 0, 0, 0, 0, 0, 0}}; std::cout << solution->maxAreaOfIsland(grid) << std::endl; // Ans: 0 grid = { {1, 1, 0, 0, 0}, {1, 1, 0, 0, 0}, {0, 0, 0, 1, 1}, {0, 0, 0, 1, 1} }; std::cout << solution->maxAreaOfIsland(grid) << std::endl; // Ans: 4 return EXIT_SUCCESS; }
32.727273
120
0.421296
[ "vector" ]
76bed0ef799e77f20a368ff62e35779ef7117bf2
704
cpp
C++
0022-Generate Parentheses/0022-Generate Parentheses.cpp
zhuangli1987/LeetCode-1
e81788abf9e95e575140f32a58fe983abc97fa4a
[ "MIT" ]
49
2018-05-05T02:53:10.000Z
2022-03-30T12:08:09.000Z
0001-0100/0022-Generate Parentheses/0022-Generate Parentheses.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
11
2017-12-15T22:31:44.000Z
2020-10-02T12:42:49.000Z
0001-0100/0022-Generate Parentheses/0022-Generate Parentheses.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
28
2017-12-05T10:56:51.000Z
2022-01-26T18:18:27.000Z
class Solution { public: vector<string> generateParenthesis(int n) { vector<string> result; string path = ""; dfs(path, n, n, result); return result; } private: void dfs(string& path, int left, int right, vector<string>& result) { if (left == 0 && right == 0) { result.push_back(path); return; } if (left > 0) { path.push_back('('); dfs(path, left - 1, right, result); path.pop_back(); } if (left < right) { path.push_back(')'); dfs(path, left, right - 1, result); path.pop_back(); } } };
23.466667
73
0.451705
[ "vector" ]
76c20a3b1cb43582c8eeea8e876e7efc3ce8b924
3,466
hpp
C++
hw3/src/object/geometry/cylinder.hpp
xupei0610/ComputerGraphics-HW
299416c0d75db17f6490bbab95a3561210a6277e
[ "MIT" ]
2
2017-10-11T13:48:30.000Z
2020-06-04T05:30:13.000Z
hw3/src/object/geometry/cylinder.hpp
xupei0610/ComputerGraphics-HW
299416c0d75db17f6490bbab95a3561210a6277e
[ "MIT" ]
null
null
null
hw3/src/object/geometry/cylinder.hpp
xupei0610/ComputerGraphics-HW
299416c0d75db17f6490bbab95a3561210a6277e
[ "MIT" ]
2
2018-10-05T15:37:29.000Z
2021-12-20T15:25:48.000Z
#ifndef PX_CG_OBJECT_GEOMETRY_CYLINDER_HPP #define PX_CG_OBJECT_GEOMETRY_CYLINDER_HPP #include "object/geometry/base_geometry.hpp" namespace px { class Cylinder; class BaseCylinder; } class px::BaseCylinder { public: PX_CUDA_CALLABLE static GeometryObj *hitCheck(void * const &obj, Ray const &ray, PREC const &range_start, PREC const &range_end, PREC &hit_at); PX_CUDA_CALLABLE static Vec3<PREC> getTextureCoord(void * const &obj, PREC const &x, PREC const &y, PREC const &z); PX_CUDA_CALLABLE static Direction normalVec(void * const &obj, PREC const &x, PREC const &y, PREC const &z, bool &double_face); void setParams(Point const &center_of_bottom_face, PREC const &radius_x, PREC const &radius_y, PREC const &height); ~BaseCylinder() = default; protected: Point _center; PREC _radius_x; PREC _radius_y; PREC _height; PREC _a, _b; PREC _z0, _z1; PREC _abs_height; GeometryObj *_dev_obj; BaseCylinder(Point const &center_of_bottom_face, PREC const &radius_x, PREC const &radius_y, PREC const &height); BaseCylinder &operator=(BaseCylinder const &) = delete; BaseCylinder &operator=(BaseCylinder &&) = delete; friend class Cylinder; }; class px::Cylinder : public BaseGeometry { public: static std::shared_ptr<BaseGeometry> create(Point const &center_of_bottom_face, PREC const &radius_x, PREC const &radius_y, PREC const &height, std::shared_ptr<BaseMaterial> const &material, std::shared_ptr<Transformation> const &trans); void up2Gpu() override; void clearGpuData() override; void setParams(Point const &center_of_bottom_face, PREC const &radius_x, PREC const &radius_y, PREC const &height); ~Cylinder(); protected: BaseCylinder *_obj; void *_gpu_obj; bool _need_upload; void _updateVertices(); Vec3<PREC> getTextureCoord(PREC const &x, PREC const &y, PREC const &z) const override; const BaseGeometry *hitCheck(Ray const &ray, PREC const &range_start, PREC const &range_end, PREC &hit_at) const override; Direction normalVec(PREC const &x, PREC const &y, PREC const &z, bool &double_face) const override; Cylinder(Point const &center_of_bottom_face, PREC const &radius_x, PREC const &radius_y, PREC const &height, std::shared_ptr<BaseMaterial> const &material, std::shared_ptr<Transformation> const &trans); Cylinder &operator=(Cylinder const &) = delete; Cylinder &operator=(Cylinder &&) = delete; }; #endif // PX_CG_OBJECT_GEOMETRY_CYLINDER_HPP
31.509091
94
0.532314
[ "geometry", "object" ]
76c44c62408cb525690657928c383a5820f51641
5,828
cpp
C++
src/io/http.cpp
msindwan/serverpp
d4377abdde92cc5abb39e8a416134bd1802d75cb
[ "MIT" ]
null
null
null
src/io/http.cpp
msindwan/serverpp
d4377abdde92cc5abb39e8a416134bd1802d75cb
[ "MIT" ]
null
null
null
src/io/http.cpp
msindwan/serverpp
d4377abdde92cc5abb39e8a416134bd1802d75cb
[ "MIT" ]
null
null
null
/** * Serverpp HTTP implementation * * Author: Mayank Sindwani * Date: 2015-09-18 */ #include <spp\http.h> using namespace spp; using namespace std; /** * HTTPRequest Constructor * * @description Parses the HTTP request and stores required information. * @param[out] {request} // The request string. * @param[out] {size} // The size of the request. */ HTTPRequest::HTTPRequest(char* request, size_t size) { char *key, *value, *next; string uri, query; int pos, cpos; cpos = 0; // Parse the request line. We don't need other headers at the moment. m_method = string(request, trim(&request, size, &cpos)); uri = string(request, trim(&request, size, &cpos)); m_protocol = string(request, trim(&request, size, &cpos)); m_uri = uri; // Parse query string parameters. if ((pos = m_uri.find_first_of("?")) != string::npos) { m_uri = uri.substr(0, pos++); query = uri.substr(pos, uri.length()); // Get key. #if defined(_MSC_VER) key = strtok_s((char*)query.c_str(), "=", &next); #else key = strtok((char*)query.c_str(), "="); #endif while (key != NULL) { // Get value. #if defined(_MSC_VER) value = strtok_s(NULL, "&", &next); #else value = strtok(NULL, "&"); #endif if (value == NULL) break; // Store the key value pair. m_params[key] = value; #if defined(_MSC_VER) key = strtok_s(NULL, "=", &next); #else key = strtok(NULL, "="); #endif } } } /** * HTTPLocation Constructor * * @description Creates a location for responses. * @param[out] {location} // The location configuration. * @param[out] {server} // The server configuration. */ HTTPLocation::HTTPLocation(jToken* location, jToken* server) { jToken* root_token; char* groot; m_aliased = false; m_proxy_pass = false; // Get root directory. root_token = jconf_get(server, "o", "root"); if (root_token != NULL) { if (root_token->type != JCONF_STRING) throw HTTPException(); groot = (char*)root_token->data; m_root = string(groot); } // Construct the location based on the object type. switch (location->type) { case JCONF_STRING: // A global root is required. if (root_token == NULL) throw HTTPException(); // The location is aliased. m_index = string((char*)location->data); m_aliased = true; break; case JCONF_NULL: // A global root is required. if (root_token == NULL) throw HTTPException(); case JCONF_OBJECT: // TODO: object and other configurations break; } } /** * HTTPLocation::get_path * * @description Returns the path to a resource on a GET request. * @param[out] {request} // The request object to retrieve the path. */ string HTTPLocation::get_path(HTTPRequest* request) { map<string, string> params; string path; params = request->get_params(); path = m_aliased ? m_root + m_index : m_root + request->get_uri(); render_template(path, &params); return path; } /** * HTTPLocation::get_path * * @description Returns the path to a resource with template parameters. * @param[out] {params} // The substitution parameters. */ string HTTPLocation::get_path(map<string, string>* params) { string path; path = m_root + m_index; render_template(path, params); return path; } /** * HTTPUriMap::set_location * * @description Assoicates a key with the provided location. * @param[out] {key} // The location key. * @param[out] {location} // The location. */ void HTTPUriMap::set_location(const char* type, const char* key, HTTPLocation* location) { try { // Create a regex rule for locations. if (!strcmp(SPP_HTTP_REGEX, type)) { m_expressions.push_back(make_pair(regex(key), location)); } // Create a regex rule for errors. else if (!strcmp(SPP_HTTP_ERROR, type) && !location->is_proxied()) { m_errors.push_back(make_pair(regex(key), location)); } // Add the rule to the suffix tree. else if (!strcmp(SPP_HTTP_MAP, type)) { m_locations.set(key, location); } } catch (regex_error) { throw HTTPException(); } } /** * HTTPUriMap::get_error * * @description Retrieves the error location. * @param[out] {key} // The location key. * @returns // The location (NULL if not found). */ char* HTTPUriMap::get_error(const char* key, size_t* size) { list< pair<regex, HTTPLocation*> >::iterator it; map<string, string> m_params; string path; // Compare against each regex. for (it = m_errors.begin(); it != m_errors.end(); it++) { if (regex_match(key, it->first)) { m_params["code"] = key; path = it->second->get_path(&m_params); return read_file(path.c_str(), size); } } return NULL; } /** * HTTPUriMap::get_location * * @description Retrieves the location. * @param[out] {key} // The location key. * @returns // The location (NULL if not found). */ HTTPLocation* HTTPUriMap::get_location(HTTPRequest* request) { list< pair<regex, HTTPLocation*> >::iterator it; HTTPLocation* location; string uri; // First do a direct string comparision. uri = request->get_uri(); // If not found, compare each regex. if ((location = m_locations.get(uri.c_str())) == NULL) { for (it = m_expressions.begin(); it != m_expressions.end(); it++) { if (regex_match(uri, it->first)) return it->second; } } return location; }
24.182573
88
0.594544
[ "object" ]
76cb27af5870664702e9c3241975d9ee239f7ecc
3,018
cpp
C++
code archive/CF/1009F.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
4
2018-04-08T08:07:58.000Z
2021-06-07T14:55:24.000Z
code archive/CF/1009F.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
null
null
null
code archive/CF/1009F.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
1
2018-10-29T12:37:25.000Z
2018-10-29T12:37:25.000Z
//{ #include<bits/stdc++.h> using namespace std; typedef int ll; typedef double lf; typedef pair<ll,ll> ii; #define REP(i,n) for(ll i=0;i<n;i++) #define REP1(i,n) for(ll i=1;i<=n;i++) #define FILL(i,n) memset(i,n,sizeof i) #define X first #define Y second #define SZ(_a) (int)_a.size() #define ALL(_a) _a.begin(),_a.end() #define pb push_back #ifdef brian #define debug(...) do{\ fprintf(stderr,"%s - %d (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);\ _do(__VA_ARGS__);\ }while(0) template<typename T>void _do(T &&_x){cerr<<_x<<endl;} template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<" ,";_do(_t...);} template<typename _a,typename _b> ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";} template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb) { _s<<"{"; for(It _it=_ita;_it!=_itb;_it++) { _s<<(_it==_ita?"":",")<<*_it; } _s<<"}"; return _s; } template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));} template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));} template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));} template<typename _t> void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<<endl;} #define IOS() #else #define debug(...) #define pary(...) #define endl '\n' #define IOS() ios_base::sync_with_stdio(0);cin.tie(0); #endif // brian //} const ll MAXn=1e6+5,MAXlg=__lg(MAXn)+2; const ll MOD=1000000007; const ll INF=ll(1e15); struct node{ ll dph,ct; node *nxt; }; vector<ll> v[MAXn]; ll dph[MAXn],p[MAXn],h[MAXn]; node *nd[MAXn]; ii mx[MAXn]; ll ans[MAXn]; ii mg(node *&a,node *b) { ii rt = {0,0}; if(a)debug(a->dph); if(b)debug(b->dph); if(!a){ a=b; return rt; } node * ta = a,* tb = b; while(ta && tb){ ta->ct += tb->ct; debug(ta->ct); rt = max(rt,{ta->ct,-ta->dph}); if(!ta->nxt){ ta->nxt = tb->nxt; break; } ta = ta->nxt; tb = tb->nxt; } return rt; } int main() { IOS(); ll n; cin>>n; REP(i,n-1) { ll a,b; cin>>a>>b; v[a].pb(b); v[b].pb(a); } FILL(dph,-1); queue<ll> q; q.push(1); dph[1] = 0; p[1] = -1; while(SZ(q)) { ll t = q.front();q.pop(); for(ll k:v[t])if(dph[k] == -1) { dph[k] = dph[t] + 1; q.push(k); p[k] = t; } } vector<ll> dt; REP1(i,n)dt.pb(i); sort(ALL(dt),[](int a,int b){return dph[a] > dph[b];}); debug(dt); for(ll t : dt){ nd[t] = new node{dph[t],1,0}; mx[t] = ii(1,-dph[t]); //if(p[t]!=-1)h[p[t]] = h[t] + 1; for(ll k : v[t])if(dph[k] == dph[t] + 1) { debug(t,k,mx[t],mx[k]); mx[t] = max(mx[t],mx[k]); mx[t] = max(mx[t],mg(nd[t]->nxt,nd[k])); } ans[t] = -mx[t].Y - dph[t]; } REP1(i,n)debug(i,mx[i]); REP1(i,n)cout<<ans[i]<<endl; }
22.691729
129
0.529821
[ "vector" ]
76d606b8a950012028c74f932ab29cf95c22d7de
5,708
cpp
C++
bsp_Barchid/src/p3d/render/Shader.cpp
Barchid/M3DS
37505c7a23d43ee51ee43ea15fa6d3bc8693ae14
[ "MIT" ]
1
2019-12-10T01:59:15.000Z
2019-12-10T01:59:15.000Z
winged_Barchid/src/p3d/render/Shader.cpp
Barchid/M3DS
37505c7a23d43ee51ee43ea15fa6d3bc8693ae14
[ "MIT" ]
null
null
null
winged_Barchid/src/p3d/render/Shader.cpp
Barchid/M3DS
37505c7a23d43ee51ee43ea15fa6d3bc8693ae14
[ "MIT" ]
2
2020-02-27T18:13:54.000Z
2022-02-24T14:37:22.000Z
#include "Shader.h" #include "Matrix4.h" #include "Matrix3.h" #include "Vector3.h" #include "Vector4.h" #include "Tools.h" #include <sstream> #include <iostream> #include <fstream> #include <vector> using namespace p3d; using namespace std; /*! * * @file * * @brief * @author F. Aubert * */ Shader *Shader::_current=NULL; Shader::Shader() { _name=""; _isInit=false; } Shader::~Shader() { glDeleteShader(_vertexId); glDeleteShader(_fragmentId); glDeleteProgram(_programId); } void Shader::init() { _programId=glCreateProgram(); _fragmentId=glCreateShader(GL_FRAGMENT_SHADER); _vertexId=glCreateShader(GL_VERTEX_SHADER); _vertexSource=""; _fragmentSource=""; glAttachShader(_programId,_vertexId); glAttachShader(_programId,_fragmentId); _isInit=true; } void Shader::readFile(const string &resourceName,string *res) { QFileInfo resource=p3d::resourceFile(resourceName); ifstream f(resource.filePath().toStdString().c_str()); if (f.fail()) throw ErrorD("fichier shader inexistant"); char readChar[1000]; string readString; while (f.good()) { f.getline(readChar,1000); readString=string(readChar); *res+=readString+"\n"; } f.close(); } void Shader::checkCompileError(GLuint id,const std::string &message) { int compile_ok; int info_length; glGetShaderiv(id,GL_COMPILE_STATUS,&compile_ok); glGetShaderiv(id,GL_INFO_LOG_LENGTH,&info_length); if (!compile_ok) { cout << "=============================" << endl; cout << "GLSL Error : " << message << endl; char *info=new char[info_length]; glGetShaderInfoLog(id,info_length,NULL,info); cout << info; cout << endl; delete info; throw ErrorD("Shader compilation error"); } } void Shader::compile(GLuint shader,const string &source) { const char *buffer=source.c_str(); glShaderSource(shader,1,&buffer,NULL); glCompileShader(shader); } void Shader::read(const string &name) { _name=name; if (!_isInit) init(); readFile(name+".vert",&_vertexSource); readFile(name+".frag",&_fragmentSource); compile(_vertexId,_vertexSource); checkCompileError(_vertexId,"in "+name+".vert"); compile(_fragmentId,_fragmentSource); checkCompileError(_fragmentId,"in "+name+".frag"); link(); use(); } void Shader::link() { for(auto attrib:_attribute) { glBindAttribLocation(_programId,attrib.second,attrib.first.c_str()); } glLinkProgram(_programId); int link_ok,info_length; glGetProgramiv(_programId,GL_LINK_STATUS,&link_ok); glGetProgramiv(_programId,GL_INFO_LOG_LENGTH,&info_length); if (!link_ok) { char *info=new char[info_length]; glGetProgramInfoLog(_programId,info_length,NULL,info); cout << "Info Log :" << endl; cout << info; cout << endl; delete info; throw ErrorD("Link shader program error"); } } void Shader::use() { glUseProgram(_programId); Shader::_current=this; } void Shader::disable() { glUseProgram(0); Shader::_current=NULL; } int Shader::uniform(string nom) { int res=glGetUniformLocation(_programId,nom.c_str()); return res; } void Shader::uniform(const string &nom,float value) { int loc=uniform(nom); glUniform1f(loc,value); } void Shader::uniform(int loc,float value) { glUniform1f(loc,value); } void Shader::uniform(const string &nom,int value) { int loc=uniform(nom); glUniform1i(loc,value); } void Shader::uniform(int loc,int value) { glUniform1i(loc,value); } void Shader::uniform(const string &nom,const Vector3 &v) { int loc=uniform(nom); glUniform3fv(loc,1,v.fv()); } void Shader::uniform(int loc,const Vector3 &v) { glUniform3fv(loc,1,v.fv()); } void Shader::uniform(const string &nom,const Matrix4 &m) { int loc=uniform(nom); glUniformMatrix4fv(loc,1,GL_FALSE,m.fv()); } void Shader::uniform(int loc,const Matrix4 &m) { glUniformMatrix4fv(loc,1,GL_FALSE,m.fv()); } void Shader::uniform(const string &nom,const Vector4 &p,int offset) { int loc=uniform(nom); glUniform4fv(loc+offset,1,p.fv()); } void Shader::uniform(int loc,const Vector4 &p,int offset) { glUniform4fv(loc+offset,1,p.fv()); } void Shader::uniform(const string &nom,const vector<int> &t) { int loc=uniform(nom+"[0]"); uniform(loc,t); } void Shader::uniform(int loc,const vector<int> &t) { glUniform1iv(loc,t.size(),t.data()); } // must be called **before** link !! (or recall link after attributes are set). void Shader::attribute(const string &name,GLuint loc) { _attribute[name]=loc; //glBindAttribLocation(_programId,loc,name.c_str()); } GLint Shader::attribute(const string &name) { return glGetAttribLocation(_programId,name.c_str()); } void Shader::uniform(const string &nom,const Matrix3 &m) { int loc=uniform(nom); glUniformMatrix3fv(loc,1,GL_FALSE,m.fv()); } void Shader::uniform(int loc,const Matrix3 &m) { glUniformMatrix3fv(loc,1,GL_FALSE,m.fv()); } void Shader::uniform(const string &name,const vector<Matrix4> &m) { int loc=uniform(name+"[0]"); uniform(loc,m); } void Shader::uniform(const string &name,const vector<Vector4> &v) { int loc=uniform(name+"[0]"); uniform(loc,v); } void Shader::uniform(int loc,const vector<Matrix4> &m) { vector<float> mf; mf.resize(m.size()*16); int i=0,j=0; for(auto &v:mf) { v=m[i](j); if (j==15) {++i;j=0;} else ++j; } glUniformMatrix4fv(loc,m.size(),GL_FALSE,mf.data()); } void Shader::uniform(int loc,const vector<Vector4> &v) { vector<float> mv; mv.resize(v.size()*4); int i=0,j=0; for(auto &val:mv) { val=v[i](j); if (j==3) {++i;j=0;} else ++j; } glUniform4fv(loc,v.size(),mv.data()); } GLuint Shader::id() { return _programId; } Shader *Shader::current() { return Shader::_current; }
20.985294
79
0.680974
[ "vector" ]
76dbf1e2b64d71bb40cdae8792cf5af732d22d99
12,525
cpp
C++
tests/test_layout_mapping_left_basics.cpp
brycelelbach/boost.mdspan
0f4b1329bbabef14b180ecd5f8a7a5282a2f9ee2
[ "BSL-1.0" ]
1
2019-10-02T21:33:43.000Z
2019-10-02T21:33:43.000Z
tests/test_layout_mapping_left_basics.cpp
brycelelbach/boost.mdspan
0f4b1329bbabef14b180ecd5f8a7a5282a2f9ee2
[ "BSL-1.0" ]
2
2018-04-27T21:51:28.000Z
2018-04-27T23:43:43.000Z
tests/test_layout_mapping_left_basics.cpp
brycelelbach/boost.mdspan
0f4b1329bbabef14b180ecd5f8a7a5282a2f9ee2
[ "BSL-1.0" ]
1
2018-04-27T22:37:37.000Z
2018-04-27T22:37:37.000Z
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2015 Bryce Adelstein Lelbach aka wash // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) //////////////////////////////////////////////////////////////////////////////// #include <mdspan> #include <vector> #include <tuple> #include <boost/core/lightweight_test.hpp> using std::vector; using std::tuple; using std::experimental::dyn; using std::experimental::dimensions; using std::experimental::layout_mapping_left; template <std::size_t X> void test_1d_static() { // {{{ layout_mapping_left< dimensions<X>, dimensions<1>, dimensions<0> > const l{}; BOOST_TEST_EQ((l.is_regular()), true); BOOST_TEST_EQ((l.is_dynamic_stride(0)), false); BOOST_TEST_EQ((l.stride(0)), 1); BOOST_TEST_EQ((l.size()), X); BOOST_TEST_EQ((l.span()), X); int dptr[X]; // Set all elements to a unique value. for (auto i = 0; i < l[0]; ++i) { BOOST_TEST_EQ((l.index(i)), i); BOOST_TEST_EQ(&(dptr[l.index(i)]), &(dptr[i])); dptr[l.index(i)] = i; BOOST_TEST_EQ((dptr[l.index(i)]), i); } } // }}} template <std::size_t X> void test_1d_dynamic() { // {{{ layout_mapping_left< dimensions<dyn>, dimensions<1>, dimensions<0> > const l(X); BOOST_TEST_EQ((l.is_regular()), true); BOOST_TEST_EQ((l.is_dynamic_stride(0)), false); BOOST_TEST_EQ((l.stride(0)), 1); BOOST_TEST_EQ((l.size()), X); BOOST_TEST_EQ((l.span()), X); vector<int> data(l[0]); int* dptr = data.data(); // Set all elements to a unique value. for (auto i = 0; i < l[0]; ++i) { BOOST_TEST_EQ((l.index(i)), i); BOOST_TEST_EQ(&(dptr[l.index(i)]), &(dptr[i])); dptr[l.index(i)] = i; BOOST_TEST_EQ((dptr[l.index(i)]), i); // Bounds-checking. BOOST_TEST_EQ((data.at(l.index(i))), i); } } // }}} template <std::size_t X, std::size_t Y> void test_2d_static() { // {{{ layout_mapping_left< dimensions<X, Y>, dimensions<1, 1>, dimensions<0, 0> > const l{}; BOOST_TEST_EQ((l.is_regular()), true); BOOST_TEST_EQ((l.is_dynamic_stride(0)), false); BOOST_TEST_EQ((l.is_dynamic_stride(1)), false); BOOST_TEST_EQ((l.stride(0)), 1); BOOST_TEST_EQ((l.stride(1)), X); BOOST_TEST_EQ((l.size()), X * Y); BOOST_TEST_EQ((l.span()), X * Y); tuple<int, int> dptr[X * Y]; // Set all elements to a unique value. for (auto j = 0; j < l[1]; ++j) for (auto i = 0; i < l[0]; ++i) { auto const true_idx = (i) + (l[0]) * (j); BOOST_TEST_EQ((l.index(i, j)), true_idx); BOOST_TEST_EQ(&(dptr[l.index(i, j)]), &(dptr[true_idx])); std::get<0>(dptr[l.index(i, j)]) = i; std::get<1>(dptr[l.index(i, j)]) = j; BOOST_TEST_EQ((std::get<0>(dptr[l.index(i, j)])), i); BOOST_TEST_EQ((std::get<1>(dptr[l.index(i, j)])), j); } } // }}} template <std::size_t X, std::size_t Y> void test_2d_dynamic() { // {{{ layout_mapping_left< dimensions<dyn, dyn>, dimensions<1, 1>, dimensions<0, 0> > const l(X, Y); BOOST_TEST_EQ((l.is_regular()), true); BOOST_TEST_EQ((l.is_dynamic_stride(0)), false); BOOST_TEST_EQ((l.is_dynamic_stride(1)), true); BOOST_TEST_EQ((l.stride(0)), 1); BOOST_TEST_EQ((l.stride(1)), X); BOOST_TEST_EQ((l.size()), X * Y); BOOST_TEST_EQ((l.span()), X * Y); vector<tuple<int, int> > data(l[0] * l[1]); tuple<int, int>* dptr = data.data(); // Set all elements to a unique value. for (auto j = 0; j < l[1]; ++j) for (auto i = 0; i < l[0]; ++i) { auto const true_idx = (i) + (l[0]) * (j); BOOST_TEST_EQ((l.index(i, j)), true_idx); BOOST_TEST_EQ(&(dptr[l.index(i, j)]), &(dptr[true_idx])); std::get<0>(dptr[l.index(i, j)]) = i; std::get<1>(dptr[l.index(i, j)]) = j; BOOST_TEST_EQ((std::get<0>(dptr[l.index(i, j)])), i); BOOST_TEST_EQ((std::get<1>(dptr[l.index(i, j)])), j); // Bounds-checking. BOOST_TEST_EQ((std::get<0>(data.at(l.index(i, j)))), i); BOOST_TEST_EQ((std::get<1>(data.at(l.index(i, j)))), j); } } // }}} template <std::size_t X, std::size_t Y> void test_2d_mixed_DS() { // {{{ layout_mapping_left< dimensions<dyn, Y>, dimensions<1, 1>, dimensions<0, 0> > const l(X); BOOST_TEST_EQ((l.is_regular()), true); BOOST_TEST_EQ((l.is_dynamic_stride(0)), false); BOOST_TEST_EQ((l.is_dynamic_stride(1)), true); // Depends on l[0]. BOOST_TEST_EQ((l.stride(0)), 1); BOOST_TEST_EQ((l.stride(1)), X); BOOST_TEST_EQ((l.size()), X * Y); BOOST_TEST_EQ((l.span()), X * Y); vector<tuple<int, int> > data(l[0] * l[1]); tuple<int, int>* dptr = data.data(); // Set all elements to a unique value. for (auto j = 0; j < l[1]; ++j) for (auto i = 0; i < l[0]; ++i) { auto const true_idx = (i) + (l[0]) * (j); BOOST_TEST_EQ((l.index(i, j)), true_idx); BOOST_TEST_EQ(&(dptr[l.index(i, j)]), &(dptr[true_idx])); std::get<0>(dptr[l.index(i, j)]) = i; std::get<1>(dptr[l.index(i, j)]) = j; BOOST_TEST_EQ((std::get<0>(dptr[l.index(i, j)])), i); BOOST_TEST_EQ((std::get<1>(dptr[l.index(i, j)])), j); // Bounds-checking. BOOST_TEST_EQ((std::get<0>(data.at(l.index(i, j)))), i); BOOST_TEST_EQ((std::get<1>(data.at(l.index(i, j)))), j); } } // }}} template <std::size_t X, std::size_t Y> void test_2d_mixed_SD() { // {{{ layout_mapping_left< dimensions<X, dyn>, dimensions<1, 1>, dimensions<0, 0> > const l(Y); BOOST_TEST_EQ((l.is_regular()), true); BOOST_TEST_EQ((l.is_dynamic_stride(0)), false); BOOST_TEST_EQ((l.is_dynamic_stride(1)), false); BOOST_TEST_EQ((l.stride(0)), 1); BOOST_TEST_EQ((l.stride(1)), X); BOOST_TEST_EQ((l.size()), X * Y); BOOST_TEST_EQ((l.span()), X * Y); vector<tuple<int, int> > data(l[0] * l[1]); tuple<int, int>* dptr = data.data(); // Set all elements to a unique value. for (auto j = 0; j < l[1]; ++j) for (auto i = 0; i < l[0]; ++i) { auto const true_idx = (i) + (l[0]) * (j); BOOST_TEST_EQ((l.index(i, j)), true_idx); BOOST_TEST_EQ(&(dptr[l.index(i, j)]), &(dptr[true_idx])); std::get<0>(dptr[l.index(i, j)]) = i; std::get<1>(dptr[l.index(i, j)]) = j; BOOST_TEST_EQ((std::get<0>(dptr[l.index(i, j)])), i); BOOST_TEST_EQ((std::get<1>(dptr[l.index(i, j)])), j); // Bounds-checking. BOOST_TEST_EQ((std::get<0>(data.at(l.index(i, j)))), i); BOOST_TEST_EQ((std::get<1>(data.at(l.index(i, j)))), j); } } // }}} template <std::size_t X, std::size_t Y, std::size_t Z> void test_3d_static() { // {{{ layout_mapping_left< dimensions<X, Y, Z>, dimensions<1, 1, 1>, dimensions<0, 0, 0> > const l{}; BOOST_TEST_EQ((l.is_regular()), true); BOOST_TEST_EQ((l.is_dynamic_stride(0)), false); BOOST_TEST_EQ((l.is_dynamic_stride(1)), false); BOOST_TEST_EQ((l.is_dynamic_stride(2)), false); BOOST_TEST_EQ((l.stride(0)), 1); BOOST_TEST_EQ((l.stride(1)), X); BOOST_TEST_EQ((l.stride(2)), X * Y); BOOST_TEST_EQ((l.size()), X * Y * Z); BOOST_TEST_EQ((l.span()), X * Y * Z); tuple<int, int, int> dptr[X * Y * Z]; // Set all elements to a unique value. for (auto k = 0; k < l[2]; ++k) for (auto j = 0; j < l[1]; ++j) for (auto i = 0; i < l[0]; ++i) { auto const true_idx = (i) + (l[0]) * (j) + (l[0]) * (l[1]) * (k); BOOST_TEST_EQ((l.index(i, j, k)), true_idx); BOOST_TEST_EQ(&(dptr[l.index(i, j, k)]), &(dptr[true_idx])); std::get<0>(dptr[l.index(i, j, k)]) = i; std::get<1>(dptr[l.index(i, j, k)]) = j; std::get<2>(dptr[l.index(i, j, k)]) = k; BOOST_TEST_EQ((std::get<0>(dptr[l.index(i, j, k)])), i); BOOST_TEST_EQ((std::get<1>(dptr[l.index(i, j, k)])), j); BOOST_TEST_EQ((std::get<2>(dptr[l.index(i, j, k)])), k); } } // }}} template <std::size_t X, std::size_t Y, std::size_t Z> void test_3d_dynamic() { // {{{ layout_mapping_left< dimensions<dyn, dyn, dyn>, dimensions<1, 1, 1>, dimensions<0, 0, 0> > const l(X, Y, Z); BOOST_TEST_EQ((l.is_regular()), true); BOOST_TEST_EQ((l.is_dynamic_stride(0)), false); BOOST_TEST_EQ((l.is_dynamic_stride(1)), true); BOOST_TEST_EQ((l.is_dynamic_stride(2)), true); BOOST_TEST_EQ((l.stride(0)), 1); BOOST_TEST_EQ((l.stride(1)), X); BOOST_TEST_EQ((l.stride(2)), X * Y); BOOST_TEST_EQ((l.size()), l[0] * l[1] * l[2]); BOOST_TEST_EQ((l.span()), l[0] * l[1] * l[2]); vector<tuple<int, int, int> > data(l[0] * l[1] * l[2]); tuple<int, int, int>* dptr = data.data(); // Set all elements to a unique value. for (auto k = 0; k < l[2]; ++k) for (auto j = 0; j < l[1]; ++j) for (auto i = 0; i < l[0]; ++i) { auto const true_idx = (i) + (l[0]) * (j) + (l[0]) * (l[1]) * (k); BOOST_TEST_EQ((l.index(i, j, k)), true_idx); BOOST_TEST_EQ(&(dptr[l.index(i, j, k)]), &(dptr[true_idx])); std::get<0>(dptr[l.index(i, j, k)]) = i; std::get<1>(dptr[l.index(i, j, k)]) = j; std::get<2>(dptr[l.index(i, j, k)]) = k; BOOST_TEST_EQ((std::get<0>(dptr[l.index(i, j, k)])), i); BOOST_TEST_EQ((std::get<1>(dptr[l.index(i, j, k)])), j); BOOST_TEST_EQ((std::get<2>(dptr[l.index(i, j, k)])), k); // Bounds-checking. BOOST_TEST_EQ((std::get<0>(data.at(l.index(i, j, k)))), i); BOOST_TEST_EQ((std::get<1>(data.at(l.index(i, j, k)))), j); BOOST_TEST_EQ((std::get<2>(data.at(l.index(i, j, k)))), k); } } // }}} int main() { // Empty { layout_mapping_left<dimensions<>, dimensions<>, dimensions<> > const l{}; BOOST_TEST_EQ((l.is_regular()), true); BOOST_TEST_EQ((l.size()), 1); BOOST_TEST_EQ((l.span()), 1); int data = 42; int* dptr = &data; BOOST_TEST_EQ((l.index()), 0); BOOST_TEST_EQ((dptr[l.index()]), 42); BOOST_TEST_EQ(&(dptr[l.index()]), dptr); dptr[l.index()] = 17; BOOST_TEST_EQ((dptr[l.index()]), 17); } // 1D Static test_1d_static<1 >(); test_1d_static<30>(); // 1D Dynamic test_1d_dynamic<1 >(); test_1d_dynamic<30>(); // 2D Static test_2d_static<1, 1 >(); test_2d_static<30, 1 >(); test_2d_static<1, 30>(); test_2d_static<30, 15>(); test_2d_static<15, 30>(); test_2d_static<30, 30>(); // 2D Dynamic test_2d_dynamic<1, 1 >(); test_2d_dynamic<30, 1 >(); test_2d_dynamic<1, 30>(); test_2d_dynamic<30, 15>(); test_2d_dynamic<15, 30>(); test_2d_dynamic<30, 30>(); // 2D Mixed - A[dynamic][static] test_2d_mixed_SD<1, 1 >(); test_2d_mixed_SD<30, 1 >(); test_2d_mixed_SD<1, 30>(); test_2d_mixed_SD<30, 15>(); test_2d_mixed_SD<15, 30>(); test_2d_mixed_SD<30, 30>(); // 2D Mixed - A[static][dynamic] test_2d_mixed_SD<1, 1 >(); test_2d_mixed_SD<30, 1 >(); test_2d_mixed_SD<1, 30>(); test_2d_mixed_SD<30, 15>(); test_2d_mixed_SD<15, 30>(); test_2d_mixed_SD<30, 30>(); // 3D Static test_3d_static<1, 1, 1 >(); test_3d_static<30, 1, 1 >(); test_3d_static<1, 30, 1 >(); test_3d_static<1, 1, 30>(); test_3d_static<1, 30, 30>(); test_3d_static<30, 1, 30>(); test_3d_static<30, 30, 1 >(); test_3d_static<30, 15, 15>(); test_3d_static<15, 30, 15>(); test_3d_static<15, 15, 30>(); test_3d_static<15, 30, 30>(); test_3d_static<30, 15, 30>(); test_3d_static<30, 30, 15>(); test_3d_static<30, 30, 30>(); // 3D Dynamic test_3d_dynamic<1, 1, 1 >(); test_3d_dynamic<30, 1, 1 >(); test_3d_dynamic<1, 30, 1 >(); test_3d_dynamic<1, 1, 30>(); test_3d_dynamic<1, 30, 30>(); test_3d_dynamic<30, 1, 30>(); test_3d_dynamic<30, 30, 1 >(); test_3d_dynamic<30, 15, 15>(); test_3d_dynamic<15, 30, 15>(); test_3d_dynamic<15, 15, 30>(); test_3d_dynamic<15, 30, 30>(); test_3d_dynamic<30, 15, 30>(); test_3d_dynamic<30, 30, 15>(); test_3d_dynamic<30, 30, 30>(); return boost::report_errors(); }
26.762821
81
0.540359
[ "vector", "3d" ]
76e0fc6509644ab2f533b865c626b221b404c4ec
1,352
cpp
C++
Card.cpp
FrankBotos/PokerHandStrength
bd11de0f90bbf517b3b4cd10d7d6c933478047a9
[ "MIT" ]
null
null
null
Card.cpp
FrankBotos/PokerHandStrength
bd11de0f90bbf517b3b4cd10d7d6c933478047a9
[ "MIT" ]
null
null
null
Card.cpp
FrankBotos/PokerHandStrength
bd11de0f90bbf517b3b4cd10d7d6c933478047a9
[ "MIT" ]
null
null
null
#include "Card.hpp" Card::Card(Suit suit, size_t value){ this->suit = suit; this->value = value; //initializing our array of suits in string format for easy retreival at a later stage this->suitsInStringFormat = { "hearts", "diamonds", "spades", "clubs" }; //quick validity check if(value < 2 || value > 14){ throw InvalidCardException(); } } Card::~Card(){} //getters Suit Card::getSuitIndex() const{ return this->suit; } size_t Card::getValue() const{ return this->value; } std::vector<std::string> Card::getSuitVector() const { return this->suitsInStringFormat; } bool Card::operator==(const Card& c){ bool e = false; if((c.getSuitIndex() == this->getSuitIndex()) && (c.getValue() == this->getValue())){ e = true; } return e; } std::ostream& operator<<(std::ostream& os, const Card& c){ //retrieve our rank if (c.getValue() < 11){ os << c.getValue(); } else { if (c.getValue() == 11){ os << "Jack"; } else if (c.getValue() == 12){ os << "King"; } else if (c.getValue() == 13){ os << "Queen"; } else { os << "Ace"; } } //retrieve our suit os << " of " << c.getSuitVector().at(c.getSuitIndex()); return os; }
21.460317
90
0.531065
[ "vector" ]
76e2d1ffb8d5c3bf8c835d2bb0dcfec9fa9c8ed7
12,817
cpp
C++
dynamic-programming/fibonacci-modified/fibonacci-modified.cpp
agusti-t/hackerrank
f30ce9362dc5e1b3489567a2c3910ade3ce0233a
[ "MIT" ]
null
null
null
dynamic-programming/fibonacci-modified/fibonacci-modified.cpp
agusti-t/hackerrank
f30ce9362dc5e1b3489567a2c3910ade3ce0233a
[ "MIT" ]
null
null
null
dynamic-programming/fibonacci-modified/fibonacci-modified.cpp
agusti-t/hackerrank
f30ce9362dc5e1b3489567a2c3910ade3ce0233a
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <climits> #include <iterator> #include <cstddef> #include <chrono> #include <map> #include <type_traits> #include <iomanip> #include <functional> using namespace std; using namespace std::chrono; using namespace std::placeholders; constexpr unsigned outputBase = 10; constexpr unsigned long long internalBase = 1000000000; constexpr unsigned baseRatio = 9; static map<string, nanoseconds> durations; void printVector(const vector<unsigned long long int>& v, const string& name); void printAllDurations(); struct Check { Check(string k): time1{std::chrono::high_resolution_clock::now()}, key{k} {} ~Check() { std::chrono::high_resolution_clock::time_point time2 = std::chrono::high_resolution_clock::now(); auto duration = (time2 - time1); durations[key] += duration; } std::chrono::high_resolution_clock::time_point time1; string key; }; template<typename F, typename... Tail> typename std::result_of<F(Tail&&...)>::type measureAndExecute(string key, F f, Tail&&... tail) { Check check(key); (void)check; return f(std::forward<Tail>(tail)...); } class BigNumber { private: vector<unsigned long long int> num; public: BigNumber(unsigned long long int num = 0); BigNumber(const BigNumber& a); BigNumber(BigNumber&& a); BigNumber& operator+=(const BigNumber& a); BigNumber& operator=(const BigNumber& a); BigNumber& operator=(BigNumber&& a); friend BigNumber operator*(const BigNumber& a, const BigNumber& b); friend BigNumber operator+(const BigNumber& a, const BigNumber& b); friend BigNumber operator-(const BigNumber& a, const BigNumber& b); friend ostream& operator<<(ostream& outstream, const BigNumber& a); friend bool operator<(const BigNumber& a, const BigNumber& b); friend bool operator==(const BigNumber& a, const BigNumber& b); friend bool operator!=(const BigNumber& a, const BigNumber& b); friend void printNaked(const BigNumber& a); friend void printVector(const vector<unsigned long long int>& v, const string& name); friend BigNumber singleSlotMultiplication(const BigNumber& a, const BigNumber& b); friend BigNumber karatsubaMultiplication(const BigNumber& a, const BigNumber& b); private: BigNumber getLowerHalf() const; BigNumber getHigherHalf() const; BigNumber& shiftLeft(unsigned long long int p); }; BigNumber findFibonacciModified(vector<BigNumber>& terms, vector<bool>& calculated, unsigned long n); void testLessThan(); void testSubstraction(); void testAddition(); void testMultiplication(); BigNumber::BigNumber(unsigned long long int n) { for (; n; n /= internalBase) { num.push_back(n % internalBase); } if (num.empty()) { num.push_back(0); } } BigNumber::BigNumber(const BigNumber& a) : num(a.num) { } BigNumber::BigNumber(BigNumber&& a) : num(std::move(a.num)) { } BigNumber& BigNumber::operator+=(const BigNumber& a) { *this = *this + a; return *this; } BigNumber& BigNumber::operator=(BigNumber&& a) { num = std::move(a.num); return *this; } BigNumber& BigNumber::operator=(const BigNumber& a) { num = a.num; return *this; } BigNumber singleSlotMultiplication(const BigNumber& a, const BigNumber& b) { BigNumber result; if (a.num.size() == 0 || b.num.size() == 0) { result.num.clear(); result.num.push_back(0); } else if (a.num.size() > 1 && b.num.size() > 1) { cout << "Trying to multiply : a = " << a << " * b = " << b << ". One of them has more than one digit so it is not possible with this function." << endl; } else if ((a.num.size() == 1 && a.num[0] == 0) || (b.num.size() == 1 && b.num[0] == 0)) { result.num.clear(); result.num.push_back(0); } else { auto shortest = a.num.size() < b.num.size() ? a : b; auto longest = a.num.size() < b.num.size() ? b : a; auto singleDigitOperand = shortest.num[0]; for (unsigned long i = 0; i < longest.num.size(); ++i) { result = result + (BigNumber(longest.num[i] * singleDigitOperand)).shiftLeft(i); } } return result; } BigNumber& BigNumber::shiftLeft(unsigned long long int p) { num.insert(num.begin(), p, 0); return *this; } BigNumber BigNumber::getLowerHalf() const { BigNumber result ; auto& r = result.num; r.assign(num.begin(), num.begin() + num.size() / 2); //Now make sure we don't have 0's left in front while (!(r.size() == 1) && (r.back() == 0)) { r.pop_back(); } return result; } BigNumber BigNumber::getHigherHalf() const { BigNumber result; auto& r = result.num; r.assign(num.begin() + num.size() / 2, num.end()); //Now make sure we don't have 0's left in front while (!(r.size() == 1) && (r.back() == 0)) { r.pop_back(); } return result; } BigNumber karatsubaMultiplication(const BigNumber& a, const BigNumber& b) { if (a.num.size() == 1 || b.num.size() == 1) { return singleSlotMultiplication(a, b); } else { auto m = static_cast<unsigned long long int>(max(ceil(a.num.size() / 2), ceil(b.num.size() / 2))); BigNumber lowA = a.getLowerHalf(); BigNumber highA = a.getHigherHalf(); BigNumber lowB = b.getLowerHalf(); BigNumber highB = b.getHigherHalf(); BigNumber z0, z1, z2; z0 = karatsubaMultiplication(lowA, lowB); z1 = karatsubaMultiplication((lowA+highA), (lowB+highB)); z2 = karatsubaMultiplication(highA, highB); BigNumber resPart2 = (z1 - z2 - z0).shiftLeft(m); return (z2.shiftLeft(m << 1) + resPart2 + z0); } } BigNumber operator*(const BigNumber& a, const BigNumber& b) { BigNumber result = karatsubaMultiplication(a, b); return result; } bool operator<(const BigNumber& a, const BigNumber& b) { if (a.num.size() < b.num.size()) { return true; } else if (a.num.size() > b.num.size()) { return false; } else { bool lessThan = false; for (unsigned long i = a.num.size()-1 ; i+1 > 0; --i) { if (a.num[i] < b.num[i]) { lessThan = true; break; } else if (a.num[i] > b.num[i]) { break; } } return lessThan; } } bool operator==(const BigNumber& a, const BigNumber& b) { return a.num == b.num; } bool operator!=(const BigNumber& a, const BigNumber& b) { return a.num != b.num; } ostream& operator<<(ostream& outstream, const BigNumber& a) { vector<unsigned long long int> result(a.num.size() * baseRatio, 0); for (unsigned long i = 0; i < a.num.size(); ++i) { auto d = a.num[i]; for (unsigned long j = 0; j < baseRatio; ++j) { result[baseRatio * i + j] = d % outputBase; d /= outputBase; } } reverse(result.begin(), result.end()); auto it = result.begin(); while (*it == 0 && it < result.end()) { ++it; } if (it != result.end()) { result.erase(result.begin(), it); } else { result.clear(); result.push_back(0); } for (auto r : result) { outstream << r; } return outstream; } BigNumber operator+(const BigNumber& a, const BigNumber& b) { auto& shortest = a.num.size() < b.num.size() ? a.num : b.num; auto& longest = a.num.size() < b.num.size() ? b.num : a.num; auto nShortest = shortest.size(); auto nLongest = longest.size(); BigNumber result; auto& r = result.num; r.clear(); unsigned long long int carry = 0; for (unsigned long i = 0; i < nShortest; ++i) { auto toAdd = shortest[i] + longest[i] + carry; r.push_back(toAdd % internalBase); carry = toAdd / internalBase; } for (unsigned long j = nShortest; j < nLongest; ++j) { auto toAdd = longest[j] + carry; r.push_back(toAdd % internalBase); carry = toAdd / internalBase; } if (carry) { r.push_back(carry); } return result; } BigNumber operator-(const BigNumber& a, const BigNumber& b) { //I am using the fact that according to the problem, there are no negative terms in the fibonacci series. if (a < b) { cout << endl << "Trying to substract BigNumbers : a = " << a << " - b = " << b << ". Since a < b, the behaviour is undefined." << endl; printVector(a.num, "a"); printVector(b.num, "b"); return BigNumber(); } else if (a == b) { return BigNumber(); } else { BigNumber result; auto& r = result.num; r.clear(); unsigned long long int carry = 0; auto nA = a.num.size(); auto nB = b.num.size(); auto& vecA = a.num; auto& vecB = b.num; for (unsigned long i = 0; i < nB; ++i) { if (vecA[i] < vecB[i] + carry) { r.push_back((vecA[i] + internalBase) - (vecB[i] + carry)); carry = 1; } else { r.push_back(vecA[i] - (vecB[i] + carry)); carry = 0; } } for (unsigned long j = nB; j < nA; ++j) { if (vecA[j] < carry) { r.push_back((vecA[j] + internalBase) - carry); carry = 1; } else { r.push_back(vecA[j] - carry); carry = 0; } } //Now make sure we don't have 0's left in front while (!(r.size() == 1) && (r.back() == 0)) { r.pop_back(); } return result; } } void printVector(const vector<unsigned long long int>& v, const string& name) { cout << endl << "Printing vector - " << name << " of size = " << v.size() << " : ["; for (unsigned long i = 0; i < v.size()-1; ++i) { cout << v[i] << ","; } cout << v[v.size()-1] << "]"; cout << endl; } /*void printNaked(const BigNumber& a) { if (a.num.size() == 0) { cout << "" << endl; return; } vector<unsigned long long int> copy(a.num); reverse(copy.begin(), copy.end()); for (auto n : copy) { cout << n << ","; } }*/ void testLessThan() { BigNumber a, b; a = 819025; b = 797449; cout << "a = " << a << " - b = " << b << " a < b ? : " << (a < b) << endl; } void testSubstraction() { BigNumber a, b; a = 3854896209; b = 2969166187; cout << "a = " << a << " - b = " << b << " | a - b = " << (a - b) << endl; } void testAddition() { BigNumber a, b; a = 3854896209; b = 2969166187; cout << "a = " << a << " - b = " << b << " | a + b = " << (a + b) << endl; auto res = a + b; for (unsigned long i = 0; i < 2000; ++i) { res += res; cout << "res + res = " << res << endl; } } void testMultiplication() { BigNumber a, b; a = 3854896209; b = 2969166187; cout << "a = " << a << " - b = " << b << " | a * b = " << (a * b) << endl; } BigNumber findFibonacciModified(vector<BigNumber>& terms, vector<bool>& calculated, unsigned long n) { if (calculated[n]) { return terms[n]; } BigNumber termToPower = findFibonacciModified(terms, calculated, n-1); terms[n] = findFibonacciModified(terms, calculated, n-2) + termToPower*termToPower; calculated[n] = true; return terms[n]; } void printAllDurations() { for (auto mapIt = durations.begin(); mapIt != durations.end(); ++mapIt) { auto durationMillis = duration_cast<milliseconds>(mapIt->second).count(); cout << setw(25) << mapIt->first << " : " << durationMillis << " milliseconds" << endl; } } int main() { //testLessThan(); //testSubstraction(); //testAddition(); //testMultiplication(); unsigned long long int t1, t2; cin >> t1; cin >> t2; unsigned long n; cin >> n; vector<BigNumber> terms(n+1); vector<bool> calculated(n+1, false); terms[0] = t1; terms[1] = t2; /* unsigned long n = 15; vector<BigNumber> terms(n+1); vector<bool> calculated(n+1, false); terms[0] = 1; terms[1] = 2;*/ // cout << "terms[0] = " << terms[0] << " - terms[1] = " << terms[1] << " - n = " << n << endl; calculated[0] = true; calculated[1] = true; cout << findFibonacciModified(terms, calculated, n-1) << endl; return 0; }
28.107456
143
0.550285
[ "vector" ]
76e6a7e2c470cd856d3999505b9ecf051bd6abb8
12,167
cpp
C++
scanner/video/nvidia/nvidia_video_decoder.cpp
photoszzt/scanner
712796dffed7411791499b9226a57410b4ce216c
[ "Apache-2.0" ]
1
2021-06-27T08:00:04.000Z
2021-06-27T08:00:04.000Z
scanner/video/nvidia/nvidia_video_decoder.cpp
photoszzt/scanner
712796dffed7411791499b9226a57410b4ce216c
[ "Apache-2.0" ]
1
2017-10-26T03:22:56.000Z
2017-10-26T03:22:56.000Z
scanner/video/nvidia/nvidia_video_decoder.cpp
qinglan233/scanner
61ce0d35e49c92cab265b746bd55ae75ab57fb42
[ "Apache-2.0" ]
1
2019-05-10T19:44:44.000Z
2019-05-10T19:44:44.000Z
/* Copyright 2016 Carnegie Mellon University, NVIDIA Corporation * * 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 "scanner/video/nvidia/nvidia_video_decoder.h" #include "scanner/util/cuda.h" #include "scanner/util/image.h" #include "scanner/util/queue.h" #include "storehouse/storage_backend.h" #include <cassert> #include <thread> #include <cuda.h> #include <nvcuvid.h> namespace scanner { namespace internal { NVIDIAVideoDecoder::NVIDIAVideoDecoder(int device_id, DeviceType output_type, CUcontext cuda_context) : device_id_(device_id), output_type_(output_type), cuda_context_(cuda_context), streams_(max_mapped_frames_), parser_(nullptr), decoder_(nullptr), frame_queue_read_pos_(0), frame_queue_elements_(0), last_displayed_frame_(-1) { CUcontext dummy; CUD_CHECK(cuCtxPushCurrent(cuda_context_)); cudaSetDevice(device_id_); for (int i = 0; i < max_mapped_frames_; ++i) { cudaStreamCreate(&streams_[i]); mapped_frames_[i] = 0; } for (i32 i = 0; i < max_output_frames_; ++i) { frame_in_use_[i] = false; undisplayed_frames_[i] = false; invalid_frames_[i] = false; } CUD_CHECK(cuCtxPopCurrent(&dummy)); } NVIDIAVideoDecoder::~NVIDIAVideoDecoder() { CUD_CHECK(cuCtxPushCurrent(cuda_context_)); cudaSetDevice(device_id_); for (int i = 0; i < max_mapped_frames_; ++i) { if (mapped_frames_[i] != 0) { CUD_CHECK(cuvidUnmapVideoFrame(decoder_, mapped_frames_[i])); } } if (parser_) { CUD_CHECK(cuvidDestroyVideoParser(parser_)); } if (decoder_) { CUD_CHECK(cuvidDestroyDecoder(decoder_)); } for (int i = 0; i < max_mapped_frames_; ++i) { CU_CHECK(cudaStreamDestroy(streams_[i])); } CUcontext dummy; CUD_CHECK(cuCtxPopCurrent(&dummy)); // HACK(apoms): We are only using the primary context right now instead of // allowing the user to specify their own CUcontext. Thus we need to release // the primary context we retained when using the factory function to create // this object (see VideoDecoder::make_from_config). CUD_CHECK(cuDevicePrimaryCtxRelease(device_id_)); } void NVIDIAVideoDecoder::configure(const FrameInfo& metadata) { frame_width_ = metadata.width(); frame_height_ = metadata.height(); CUcontext dummy; CUD_CHECK(cuCtxPushCurrent(cuda_context_)); cudaSetDevice(device_id_); for (int i = 0; i < max_mapped_frames_; ++i) { if (mapped_frames_[i] != 0) { CUD_CHECK(cuvidUnmapVideoFrame(decoder_, mapped_frames_[i])); } } if (parser_) { CUD_CHECK(cuvidDestroyVideoParser(parser_)); } if (decoder_) { CUD_CHECK(cuvidDestroyDecoder(decoder_)); } for (int i = 0; i < max_mapped_frames_; ++i) { mapped_frames_[i] = 0; } for (i32 i = 0; i < max_output_frames_; ++i) { frame_in_use_[i] = false; undisplayed_frames_[i] = false; invalid_frames_[i] = false; } frame_queue_read_pos_ = 0; frame_queue_elements_ = 0; CUVIDPARSERPARAMS cuparseinfo = {}; // cuparseinfo.CodecType = metadata.codec_type; cuparseinfo.CodecType = cudaVideoCodec_H264; cuparseinfo.ulMaxNumDecodeSurfaces = max_output_frames_; cuparseinfo.ulMaxDisplayDelay = 1; cuparseinfo.pUserData = this; cuparseinfo.pfnSequenceCallback = NVIDIAVideoDecoder::cuvid_handle_video_sequence; cuparseinfo.pfnDecodePicture = NVIDIAVideoDecoder::cuvid_handle_picture_decode; cuparseinfo.pfnDisplayPicture = NVIDIAVideoDecoder::cuvid_handle_picture_display; CUD_CHECK(cuvidCreateVideoParser(&parser_, &cuparseinfo)); CUVIDDECODECREATEINFO cuinfo = {}; // cuinfo.CodecType = metadata.codec_type; cuinfo.CodecType = cudaVideoCodec_H264; // cuinfo.ChromaFormat = metadata.chroma_format; cuinfo.ChromaFormat = cudaVideoChromaFormat_420; cuinfo.OutputFormat = cudaVideoSurfaceFormat_NV12; cuinfo.ulWidth = frame_width_; cuinfo.ulHeight = frame_height_; cuinfo.ulTargetWidth = cuinfo.ulWidth; cuinfo.ulTargetHeight = cuinfo.ulHeight; cuinfo.target_rect.left = 0; cuinfo.target_rect.top = 0; cuinfo.target_rect.right = cuinfo.ulWidth; cuinfo.target_rect.bottom = cuinfo.ulHeight; cuinfo.ulNumDecodeSurfaces = max_output_frames_; cuinfo.ulNumOutputSurfaces = max_mapped_frames_; cuinfo.ulCreationFlags = cudaVideoCreate_PreferCUVID; cuinfo.DeinterlaceMode = cudaVideoDeinterlaceMode_Weave; CUD_CHECK(cuvidCreateDecoder(&decoder_, &cuinfo)); CUD_CHECK(cuCtxPopCurrent(&dummy)); size_t pos = 0; while (pos < metadata_packets_.size()) { int encoded_packet_size = *reinterpret_cast<int*>(metadata_packets_.data() + pos); pos += sizeof(int); u8* encoded_packet = (u8*)(metadata_packets_.data() + pos); pos += encoded_packet_size; feed(encoded_packet, encoded_packet_size); } } bool NVIDIAVideoDecoder::feed(const u8* encoded_buffer, size_t encoded_size, bool discontinuity) { CUD_CHECK(cuCtxPushCurrent(cuda_context_)); cudaSetDevice(device_id_); if (discontinuity) { { std::unique_lock<std::mutex> lock(frame_queue_mutex_); while (frame_queue_elements_ > 0) { const auto& dispinfo = frame_queue_[frame_queue_read_pos_]; frame_in_use_[dispinfo.picture_index] = false; frame_queue_read_pos_ = (frame_queue_read_pos_ + 1) % max_output_frames_; frame_queue_elements_--; } } CUVIDSOURCEDATAPACKET cupkt = {}; cupkt.flags |= CUVID_PKT_DISCONTINUITY; CUD_CHECK(cuvidParseVideoData(parser_, &cupkt)); std::unique_lock<std::mutex> lock(frame_queue_mutex_); last_displayed_frame_ = -1; // Empty queue because we have a new section of frames for (i32 i = 0; i < max_output_frames_; ++i) { invalid_frames_[i] = undisplayed_frames_[i]; undisplayed_frames_[i] = false; } while (frame_queue_elements_ > 0) { const auto& dispinfo = frame_queue_[frame_queue_read_pos_]; frame_in_use_[dispinfo.picture_index] = false; frame_queue_read_pos_ = (frame_queue_read_pos_ + 1) % max_output_frames_; frame_queue_elements_--; } CUcontext dummy; CUD_CHECK(cuCtxPopCurrent(&dummy)); return false; } CUVIDSOURCEDATAPACKET cupkt = {}; cupkt.payload_size = encoded_size; cupkt.payload = reinterpret_cast<const uint8_t*>(encoded_buffer); if (encoded_size == 0) { cupkt.flags |= CUVID_PKT_ENDOFSTREAM; } CUD_CHECK(cuvidParseVideoData(parser_, &cupkt)); // Feed metadata packets after EOS to reinit decoder if (encoded_size == 0) { size_t pos = 0; while (pos < metadata_packets_.size()) { int encoded_packet_size = *reinterpret_cast<int*>(metadata_packets_.data() + pos); pos += sizeof(int); u8* encoded_packet = (u8*)(metadata_packets_.data() + pos); pos += encoded_packet_size; feed(encoded_packet, encoded_packet_size); } } CUcontext dummy; CUD_CHECK(cuCtxPopCurrent(&dummy)); return frame_queue_elements_ > 0; } bool NVIDIAVideoDecoder::discard_frame() { std::unique_lock<std::mutex> lock(frame_queue_mutex_); CUD_CHECK(cuCtxPushCurrent(cuda_context_)); cudaSetDevice(device_id_); if (frame_queue_elements_ > 0) { const auto& dispinfo = frame_queue_[frame_queue_read_pos_]; frame_in_use_[dispinfo.picture_index] = false; frame_queue_read_pos_ = (frame_queue_read_pos_ + 1) % max_output_frames_; frame_queue_elements_--; } CUcontext dummy; CUD_CHECK(cuCtxPopCurrent(&dummy)); return frame_queue_elements_ > 0; } bool NVIDIAVideoDecoder::get_frame(u8* decoded_buffer, size_t decoded_size) { auto start = now(); std::unique_lock<std::mutex> lock(frame_queue_mutex_); CUD_CHECK(cuCtxPushCurrent(cuda_context_)); cudaSetDevice(device_id_); if (frame_queue_elements_ > 0) { CUVIDPARSERDISPINFO dispinfo = frame_queue_[frame_queue_read_pos_]; frame_queue_read_pos_ = (frame_queue_read_pos_ + 1) % max_output_frames_; frame_queue_elements_--; lock.unlock(); CUVIDPROCPARAMS params = {}; params.progressive_frame = dispinfo.progressive_frame; params.second_field = 0; params.top_field_first = dispinfo.top_field_first; int mapped_frame_index = dispinfo.picture_index % max_mapped_frames_; auto start_map = now(); unsigned int pitch = 0; CUD_CHECK(cuvidMapVideoFrame(decoder_, dispinfo.picture_index, &mapped_frames_[mapped_frame_index], &pitch, &params)); // cuvidMapVideoFrame does not wait for convert kernel to finish so sync // TODO(apoms): make this an event insertion and have the async 2d memcpy // depend on the event if (profiler_) { profiler_->add_interval("map_frame", start_map, now()); } CUdeviceptr mapped_frame = mapped_frames_[mapped_frame_index]; CU_CHECK(convertNV12toRGBA((const u8*)mapped_frame, pitch, decoded_buffer, frame_width_ * 3, frame_width_, frame_height_, 0)); CU_CHECK(cudaDeviceSynchronize()); CUD_CHECK( cuvidUnmapVideoFrame(decoder_, mapped_frames_[mapped_frame_index])); mapped_frames_[mapped_frame_index] = 0; std::unique_lock<std::mutex> lock(frame_queue_mutex_); frame_in_use_[dispinfo.picture_index] = false; } CUcontext dummy; CUD_CHECK(cuCtxPopCurrent(&dummy)); if (profiler_) { profiler_->add_interval("get_frame", start, now()); } return frame_queue_elements_; } int NVIDIAVideoDecoder::decoded_frames_buffered() { return frame_queue_elements_; } void NVIDIAVideoDecoder::wait_until_frames_copied() {} int NVIDIAVideoDecoder::cuvid_handle_video_sequence(void* opaque, CUVIDEOFORMAT* format) { NVIDIAVideoDecoder& decoder = *reinterpret_cast<NVIDIAVideoDecoder*>(opaque); return 1; } int NVIDIAVideoDecoder::cuvid_handle_picture_decode(void* opaque, CUVIDPICPARAMS* picparams) { NVIDIAVideoDecoder& decoder = *reinterpret_cast<NVIDIAVideoDecoder*>(opaque); int mapped_frame_index = picparams->CurrPicIdx; while (decoder.frame_in_use_[picparams->CurrPicIdx]) { usleep(500); }; std::unique_lock<std::mutex> lock(decoder.frame_queue_mutex_); decoder.undisplayed_frames_[picparams->CurrPicIdx] = true; CUresult result = cuvidDecodePicture(decoder.decoder_, picparams); CUD_CHECK(result); return result == CUDA_SUCCESS; } int NVIDIAVideoDecoder::cuvid_handle_picture_display( void* opaque, CUVIDPARSERDISPINFO* dispinfo) { NVIDIAVideoDecoder& decoder = *reinterpret_cast<NVIDIAVideoDecoder*>(opaque); if (!decoder.invalid_frames_[dispinfo->picture_index]) { { std::unique_lock<std::mutex> lock(decoder.frame_queue_mutex_); decoder.frame_in_use_[dispinfo->picture_index] = true; } while (true) { std::unique_lock<std::mutex> lock(decoder.frame_queue_mutex_); if (decoder.frame_queue_elements_ < max_output_frames_) { int write_pos = (decoder.frame_queue_read_pos_ + decoder.frame_queue_elements_) % max_output_frames_; decoder.frame_queue_[write_pos] = *dispinfo; decoder.frame_queue_elements_++; decoder.last_displayed_frame_++; break; } usleep(1000); } } else { std::unique_lock<std::mutex> lock(decoder.frame_queue_mutex_); decoder.invalid_frames_[dispinfo->picture_index] = false; } std::unique_lock<std::mutex> lock(decoder.frame_queue_mutex_); decoder.undisplayed_frames_[dispinfo->picture_index] = false; return true; } } }
32.187831
80
0.708967
[ "object" ]
76e9ff541efd34d5eeaf40ddd6e46a42fef110a1
675
cpp
C++
greedy/455-assign-cookies.cpp
geyixin/awesome-Leetcode
488cb477beeaa6fa7e65950615bfafa899eed3a3
[ "MIT" ]
1
2020-04-10T05:05:50.000Z
2020-04-10T05:05:50.000Z
greedy/455-assign-cookies.cpp
geyixin/awesome-Leetcode
488cb477beeaa6fa7e65950615bfafa899eed3a3
[ "MIT" ]
null
null
null
greedy/455-assign-cookies.cpp
geyixin/awesome-Leetcode
488cb477beeaa6fa7e65950615bfafa899eed3a3
[ "MIT" ]
null
null
null
/* * @Author: Eashin * @Date: 2020-05-23 20:26:24 * @LastEditors: Eashin * @LastEditTime: 2020-05-23 22:08:02 * @Description: * @FilePath: /greedy/455-assign-cookies.cpp */ #include<iostream> #include <vector> using namespace std; class Solution { public: int findContentChildren(vector<int>& g, vector<int>& s) { sort(g.begin(),g.end()); sort(s.begin(),s.end()); int g_index = 0, s_index = 0, cnt = 0; while (g_index < g.size() && s_index < s.size()) { if (s[s_index] >= g[g_index]) { g_index ++; s_index ++; cnt ++; } else s_index ++; } return cnt; } };
23.275862
61
0.53037
[ "vector" ]
76ea9dc4fe76b503417422f91e2fbcaffa3d05b9
3,831
cpp
C++
apps/opencs/view/settings/settingwindow.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/opencs/view/settings/settingwindow.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/opencs/view/settings/settingwindow.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
#include <QApplication> #include <QDebug> #include "../../model/settings/setting.hpp" #include "../../model/settings/connector.hpp" #include "../../model/settings/usersettings.hpp" #include "settingwindow.hpp" #include "page.hpp" #include "view.hpp" CSVSettings::SettingWindow::SettingWindow(QWidget *parent) : QMainWindow(parent), mModel(NULL) {} void CSVSettings::SettingWindow::createPages() { CSMSettings::SettingPageMap pageMap = mModel->settingPageMap(); QList <CSMSettings::Setting *> connectedSettings; foreach (const QString &pageName, pageMap.keys()) { QList <CSMSettings::Setting *> pageSettings = pageMap.value (pageName).second; mPages.append (new Page (pageName, pageSettings, this, pageMap.value (pageName).first)); for (int i = 0; i < pageSettings.size(); i++) { CSMSettings::Setting *setting = pageSettings.at(i); if (!setting->proxyLists().isEmpty()) connectedSettings.append (setting); } } if (!connectedSettings.isEmpty()) createConnections(connectedSettings); } void CSVSettings::SettingWindow::createConnections (const QList <CSMSettings::Setting *> &list) { foreach (const CSMSettings::Setting *setting, list) { View *masterView = findView (setting->page(), setting->name()); CSMSettings::Connector *connector = new CSMSettings::Connector (masterView, this); connect (masterView, SIGNAL (viewUpdated(const QString &, const QStringList &)), connector, SLOT (slotUpdateSlaves()) ); const CSMSettings::ProxyValueMap &proxyMap = setting->proxyLists(); foreach (const QString &key, proxyMap.keys()) { QStringList keyPair = key.split('/'); if (keyPair.size() != 2) continue; View *slaveView = findView (keyPair.at(0), keyPair.at(1)); if (!slaveView) { qWarning () << "Unable to create connection for view " << key; continue; } QList <QStringList> proxyList = proxyMap.value (key); connector->addSlaveView (slaveView, proxyList); connect (slaveView, SIGNAL (viewUpdated(const QString &, const QStringList &)), connector, SLOT (slotUpdateMaster())); } } } void CSVSettings::SettingWindow::setViewValues() { //iterate each page and view, setting their definitions //if they exist in the model foreach (const Page *page, mPages) { foreach (const View *view, page->views()) { //testing beforehand prevents overwriting a proxy setting if (!mModel->hasSettingDefinitions (view->viewKey())) continue; QStringList defs = mModel->definitions (view->viewKey()); view->setSelectedValues(defs); } } } CSVSettings::View *CSVSettings::SettingWindow::findView (const QString &pageName, const QString &setting) { foreach (const Page *page, mPages) { if (page->objectName() == pageName) return page->findView (pageName, setting); } return 0; } void CSVSettings::SettingWindow::saveSettings() { //setting the definition in the model automatically syncs with the file foreach (const Page *page, mPages) { foreach (const View *view, page->views()) { if (!view->serializable()) continue; mModel->setDefinitions (view->viewKey(), view->selectedValues()); } } mModel->saveDefinitions(); }
29.022727
96
0.5787
[ "model" ]
76edab0d4f23dcea9b2ed3f60271732c591bfa06
2,535
hh
C++
inc/promotion.hh
lysyjakk/neuralchess
d1e7b73580784026a4087b11d6939870dcf0f4e4
[ "MIT" ]
null
null
null
inc/promotion.hh
lysyjakk/neuralchess
d1e7b73580784026a4087b11d6939870dcf0f4e4
[ "MIT" ]
null
null
null
inc/promotion.hh
lysyjakk/neuralchess
d1e7b73580784026a4087b11d6939870dcf0f4e4
[ "MIT" ]
null
null
null
#ifndef PROMOTION_H_INCLUDED #define PROMOTION_H_INCLUDED #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include "textureManager.hh" #include "constants.hh" #include <iostream> #define PROMOTION_TO_QUEEN 0 #define PROMOTION_TO_ROOK 1 #define PROMOTION_TO_BISHOP 2 #define PROMOTION_TO_KNIGHT 3 enum class Site; static int promotion_pawn(Site site) { int result; /*if (site == (Site)0) // Only for white { SDL_Renderer *promotion_rend; SDL_Window *promotion_win; SDL_Rect srcRect, destRect; if(SDL_Init(SDL_INIT_EVERYTHING) == 0) { promotion_win = SDL_CreateWindow("Promotion", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 410, 150, false); promotion_rend = SDL_CreateRenderer(promotion_win, -1, 0); if(promotion_rend) { SDL_SetRenderDrawColor(promotion_rend, 140, 140, 140, 255); } } SDL_Texture *queen = TextureManager::LoadTexture(WHITE_QUEEN_TEX, promotion_rend); SDL_Texture *bishop = TextureManager::LoadTexture(WHITE_BISHOP_TEX, promotion_rend); SDL_Texture *rook = TextureManager::LoadTexture(WHITE_ROOK_TEX, promotion_rend); SDL_Texture *knight = TextureManager::LoadTexture(WHITE_KNIGHT_TEX, promotion_rend); //Render promotion window SDL_RenderClear(promotion_rend); srcRect.w = 99; srcRect.h = 99; srcRect.x = 0; srcRect.y = 0; destRect.x = 0; destRect.y = 20; destRect.w = srcRect.w; destRect.h = srcRect.h; SDL_RenderCopy(promotion_rend, queen, &srcRect, &destRect); destRect.x += 100; SDL_RenderCopy(promotion_rend, rook, &srcRect, &destRect); destRect.x += 100; SDL_RenderCopy(promotion_rend, bishop, &srcRect, &destRect); destRect.x += 100; SDL_RenderCopy(promotion_rend, knight, &srcRect, &destRect); SDL_RenderPresent(promotion_rend); SDL_Event event; bool is_promotion_event = true; while(is_promotion_event) { while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_MOUSEBUTTONDOWN: if(event.button.button == SDL_BUTTON_LEFT) { result = (int)event.button.x / 100; is_promotion_event = false; SDL_DestroyRenderer(promotion_rend); SDL_DestroyWindow(promotion_win); } break; default: break; } } SDL_Delay(100); } }*/ //else { result = PROMOTION_TO_QUEEN; } return result; } #endif //PROMOTION_H_INCLUDED
24.375
117
0.660355
[ "render" ]
76f5ba66e02a0295d011127c6dd78a25aa030805
1,140
cpp
C++
C++_Programs/Manual/10.1.cpp
NikhilParekh47/Programs
e986ec4a0f43f37a08f000cd0f2e08190dcc7bd9
[ "MIT" ]
5
2019-07-15T14:22:52.000Z
2020-12-17T10:16:37.000Z
C++_Programs/Manual/10.1.cpp
parekhnikhil47/Programs
e986ec4a0f43f37a08f000cd0f2e08190dcc7bd9
[ "MIT" ]
null
null
null
C++_Programs/Manual/10.1.cpp
parekhnikhil47/Programs
e986ec4a0f43f37a08f000cd0f2e08190dcc7bd9
[ "MIT" ]
2
2019-07-26T11:30:10.000Z
2019-08-18T16:42:09.000Z
/* * This program is for illustrate concept of constructor and destructor. * In this we will create date class and it's constructor and destructor. */ #include <iostream> // Header using namespace std; class DATE { // Creating class DATE. public: DATE (int i){ // Constructor of class DATE. constructor have same as class name. cout<<"Enter date"<<i<<" (ddmmyyyy) : "; cin>>dd>>mm>>yy; if(dd>31||mm>12||yy>3000){ // Checking if the given date is valid or not. cout<<"Enter a valid date."<<endl; dd=mm=yy=0; } } ~DATE(){ // Destructor, '~' is used to define it. cout<<"Destructed."; } void print(){ // It will print the dates. cout<<"Date is "<<dd<<"/"<<mm<<"/"<<yy<<endl; } private: unsigned int dd,mm,yy; // Declaring variables required for the date. }; int main(){ { // In this scope we will declare 2 date objects. DATE D1(1),D2(2); // Declaring DATE1 and DATE2; cout<<endl<<"Printing DATE : "<<endl; D1.print(); // Print date1. D2.print(); // Print date2. } // Destructor will be automatically called. when the scope of object is over. cout<<endl<<endl; return 0; }
31.666667
83
0.633333
[ "object" ]
76f861af33b5db3213c7c59bf8bea56a530f0922
7,978
cpp
C++
src/caffe/aicore_layers/conv_layer.cpp
jizhuoran/caffe-atlas
f818b3601d32ad4dc4154d533716b6c6a35b0d1c
[ "Intel", "BSD-2-Clause" ]
2
2020-06-28T03:05:59.000Z
2020-07-06T14:18:10.000Z
src/caffe/aicore_layers/conv_layer.cpp
jizhuoran/caffe-atlas
f818b3601d32ad4dc4154d533716b6c6a35b0d1c
[ "Intel", "BSD-2-Clause" ]
null
null
null
src/caffe/aicore_layers/conv_layer.cpp
jizhuoran/caffe-atlas
f818b3601d32ad4dc4154d533716b6c6a35b0d1c
[ "Intel", "BSD-2-Clause" ]
null
null
null
#include "caffe/layers/conv_layer.hpp" namespace caffe { template <typename Dtype> void ochw2fracZ(const Dtype* ochw, _Float16* fracZ, int channel_out, int channel_in, int kernel_h, int kernel_w) { auto fracZ_array = *reinterpret_cast<_Float16 (*)[kernel_h * kernel_w * ((channel_in + 15) / 16)][(channel_out + 15) / 16][16][16]>(fracZ); auto ochw_array = *reinterpret_cast<const Dtype (*)[channel_out][channel_in][kernel_h][kernel_w]>(ochw); #pragma omp parallel for for (int o_i = 0; o_i < channel_out; o_i++) { for (int c_i = 0; c_i < channel_in; c_i++) { for (int h_i = 0; h_i < kernel_h; h_i++) { for (int w_i = 0; w_i < kernel_w; w_i++) { fracZ_array[(c_i/16) * (kernel_w * kernel_h) + h_i * (kernel_w) + w_i][(o_i)/16][o_i%16][c_i%16] = ochw_array[o_i][c_i][h_i][w_i]; } } } } } template void ochw2fracZ<_Float16>(const _Float16* ochw, _Float16* fracZ, int channel_out, int channel_in, int kernel_h, int kernel_w); template void ochw2fracZ<float>(const float* ochw, _Float16* fracZ, int channel_out, int channel_in, int kernel_h, int kernel_w); template void ochw2fracZ<double>(const double* ochw, _Float16* fracZ, int channel_out, int channel_in, int kernel_h, int kernel_w); template <typename Dtype> void fracZ2ochw(const float* fracZ, Dtype* ochw, int channel_out, int channel_in, int kernel_h, int kernel_w) { auto fracZ_array = *reinterpret_cast<const float (*)[kernel_h * kernel_w * ((channel_in + 15) / 16)][(channel_out + 15) / 16][16][16]>(fracZ); auto ochw_array = *reinterpret_cast<Dtype (*)[channel_out][channel_in][kernel_h][kernel_w]>(ochw); #pragma omp parallel for for (int o_i = 0; o_i < channel_out; o_i++) { for (int c_i = 0; c_i < channel_in; c_i++) { for (int h_i = 0; h_i < kernel_h; h_i++) { for (int w_i = 0; w_i < kernel_w; w_i++) { ochw_array[o_i][c_i][h_i][w_i] = fracZ_array[(c_i/16) * (kernel_w * kernel_h) + h_i * (kernel_w) + w_i][(o_i)/16][o_i%16][c_i%16]; } } } } } template void fracZ2ochw<_Float16>(const float* fracZ, _Float16* ochw, int channel_out, int channel_in, int kernel_h, int kernel_w); template void fracZ2ochw<float>(const float* fracZ, float* ochw, int channel_out, int channel_in, int kernel_h, int kernel_w); template void fracZ2ochw<double>(const float* fracZ, double* ochw, int channel_out, int channel_in, int kernel_h, int kernel_w); template <typename Dtype> void five2four(const _Float16* five, Dtype* four, int batch_size, int channel_in, int in_height, int in_width) { auto five_array = *reinterpret_cast<const _Float16 (*)[batch_size][(channel_in+15)/16][in_height][in_width][16]>(five); auto four_array = *reinterpret_cast<Dtype (*)[batch_size][channel_in][in_height][in_width]>(four); #pragma omp parallel for for (int n_i = 0; n_i < batch_size; n_i++) { for (int c_i = 0; c_i < channel_in; c_i++) { for (int h_i = 0; h_i < in_height; h_i++) { for (int w_i = 0; w_i < in_width; w_i++) { four_array[n_i][c_i][h_i][w_i] = five_array[n_i][c_i/16][h_i][w_i][c_i%16]; } } } } } template void five2four<float>(const _Float16* five, float* four, int batch_size, int channel_in, int in_height, int in_width); template void five2four<double>(const _Float16* five, double* four, int batch_size, int channel_in, int in_height, int in_width); template <typename Dtype> void four2five(const Dtype* four, _Float16* five, int batch_size, int channel_in, int in_height, int in_width) { auto five_array = *reinterpret_cast<_Float16 (*)[batch_size][(channel_in+15)/16][in_height][in_width][16]>(five); auto four_array = *reinterpret_cast<const Dtype (*)[batch_size][channel_in][in_height][in_width]>(four); #pragma omp parallel for for (int n_i = 0; n_i < batch_size; n_i++) { for (int c_i = 0; c_i < channel_in; c_i++) { for (int h_i = 0; h_i < in_height; h_i++) { for (int w_i = 0; w_i < in_width; w_i++) { five_array[n_i][c_i/16][h_i][w_i][c_i%16] = four_array[n_i][c_i][h_i][w_i]; } } } } } template void four2five<float>(const float* four, _Float16* five, int batch_size, int channel_in, int in_height, int in_width); template void four2five<double>(const double* four, _Float16* five, int batch_size, int channel_in, int in_height, int in_width); template <typename Dtype> void ConvolutionLayer<Dtype>::Forward_aicore(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { four2five(bottom[0]->cpu_data(), this->bottom_five_fp16_.mutable_cpu_data(), bottom[0]->shape(0), bottom[0]->shape(1), bottom[0]->shape(2), bottom[0]->shape(3)); ochw2fracZ(this->blobs_[0]->cpu_data(), this->fracZ_fp16_.mutable_cpu_data(), this->num_output_, this->channels_, this->blobs_[0]->shape(2), this->blobs_[0]->shape(3)); std::vector<void*> args = {(void*)this->bottom_five_fp16_.aicore_data(), (void*)this->fracZ_fp16_.aicore_data()}; std::unique_ptr<Blob<_Float16>> bias_fp16; if (this->bias_term_) { auto bias_fp16_data = this->bias_fp16_.mutable_cpu_data(); auto bias_data = this->blobs_[1]->cpu_data(); for(int i = 0; i < this->blobs_[1]->count(); ++i) { bias_fp16_data[i] = bias_data[i]; } args.push_back((void*)this->bias_fp16_.aicore_data()); } args.push_back((void*)this->top_five_fp16_.mutable_aicore_data()); AICORE_CHECK(rtKernelLaunch(this->aicore_kernel_info_[0].kernel_, this->aicore_kernel_info_[0].block_num_, args.data(), args.size() * sizeof(void*), NULL, Caffe::Get().aicore_stream)); AICORE_CHECK(rtStreamSynchronize(Caffe::Get().aicore_stream)); five2four(this->top_five_fp16_.cpu_data(), top[0]->mutable_cpu_data(), top[0]->shape(0), top[0]->shape(1), top[0]->shape(2), top[0]->shape(3)); } template <typename Dtype> void ConvolutionLayer<Dtype>::Backward_aicore(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { // Bias gradient, if necessary. if (this->bias_term_ && this->param_propagate_down_[1]) { const Dtype* top_diff = top[0]->cpu_diff(); Dtype* bias_diff = this->blobs_[1]->mutable_cpu_diff(); for (int i = 0; i < this->num_; ++i) { for(int m = 0; m < this->num_output_; ++m) { for(int n = 0; n < this->out_spatial_dim_; ++n) { bias_diff[m] += top_diff[m * this->out_spatial_dim_ + n]; } } top_diff += this->top_dim_; } } four2five(top[0]->cpu_diff(), this->top_five_fp16_.mutable_cpu_diff(), top[0]->shape(0), top[0]->shape(1), top[0]->shape(2), top[0]->shape(3)); std::vector<void*> args = { (void*)this->bottom_five_fp16_.aicore_data(), (void*)this->top_five_fp16_.aicore_diff(), (void*)this->fracZ_fp32_.mutable_aicore_diff()}; AICORE_CHECK(rtKernelLaunch(this->aicore_kernel_info_[1].kernel_, this->aicore_kernel_info_[1].block_num_, args.data(), args.size() * sizeof(void*), NULL, Caffe::Get().aicore_stream)); AICORE_CHECK(rtStreamSynchronize(Caffe::Get().aicore_stream)); fracZ2ochw(this->fracZ_fp32_.cpu_diff(), this->blobs_[0]->mutable_cpu_diff(), this->num_output_, this->channels_, this->blobs_[0]->shape(2), this->blobs_[0]->shape(3)); std::vector<void*> args1 = { (void*)this->fracZ_fp16_.aicore_data(), (void*)this->top_five_fp16_.aicore_diff(), (void*)this->bottom_five_fp16_.mutable_aicore_diff()}; AICORE_CHECK(rtKernelLaunch(this->aicore_kernel_info_[2].kernel_, this->aicore_kernel_info_[2].block_num_, args1.data(), args1.size() * sizeof(void*), NULL, Caffe::Get().aicore_stream)); AICORE_CHECK(rtStreamSynchronize(Caffe::Get().aicore_stream)); five2four(this->bottom_five_fp16_.cpu_diff(), bottom[0]->mutable_cpu_diff(), bottom[0]->shape(0), bottom[0]->shape(1), bottom[0]->shape(2), bottom[0]->shape(3)); } INSTANTIATE_LAYER_AICORE_FUNCS(ConvolutionLayer); } // namespace caffe
48.646341
188
0.673602
[ "shape", "vector" ]
76f9438a3fe281b3a0df2b4d367f44b90bef5e93
9,105
hpp
C++
Xor/XorCommandList.hpp
jknuuttila/xor-renderer
553657e1aa6f5a4e5aa7da31752d748c78375f88
[ "MIT" ]
1
2016-07-11T11:38:52.000Z
2016-07-11T11:38:52.000Z
Xor/XorCommandList.hpp
jknuuttila/xor-renderer
553657e1aa6f5a4e5aa7da31752d748c78375f88
[ "MIT" ]
null
null
null
Xor/XorCommandList.hpp
jknuuttila/xor-renderer
553657e1aa6f5a4e5aa7da31752d748c78375f88
[ "MIT" ]
null
null
null
#pragma once #include "Core/Core.hpp" #include "Xor/Shaders.h" #include "Xor/XorBackend.hpp" #include "Xor/XorResources.hpp" namespace Xor { static constexpr int MaxRenderTargets = 8; namespace backend { struct QueryHeap; struct ProfilingEventData; struct CommandListState; } class ProfilingEvent { friend class Device; friend class CommandList; MovingPtr<backend::QueryHeap *> m_queryHeap; MovingPtr<backend::CommandListState *> m_cmd; MovingValue<int64_t, -1> m_offset; MovingPtr<backend::ProfilingEventData *> m_data; public: ProfilingEvent() = default; ~ProfilingEvent() { done(); } ProfilingEvent(ProfilingEvent &&) = default; ProfilingEvent &operator=(ProfilingEvent &&e) { done(); m_queryHeap = std::move(e.m_queryHeap); m_cmd = std::move(e.m_cmd); m_offset = std::move(e.m_offset); m_data = std::move(e.m_data); return *this; } void done(); float minimumMs() const; float averageMs() const; float maximumMs() const; }; enum class ProfilingDisplay { Enabled, Disabled, }; namespace backend { struct QueryHeap; struct CommandListState : DeviceChild { ComPtr<ID3D12CommandAllocator> allocator; ComPtr<ID3D12GraphicsCommandList> cmd; uint64_t timesStarted = 0; ComPtr<ID3D12Fence> timesCompleted; Handle completedEvent; SeqNum seqNum = -1; GPUTransientChunk uploadChunk; GPUTransientChunk readbackChunk; bool closed = false; std::array<Texture, MaxRenderTargets> activeRenderTargets; XorShaderDebugConstants debugConstants; BufferUAV shaderDebugData; std::vector<D3D12_CONSTANT_BUFFER_VIEW_DESC> cbvs; std::vector<D3D12_CPU_DESCRIPTOR_HANDLE> srvs; std::vector<D3D12_CPU_DESCRIPTOR_HANDLE> uavs; std::vector<D3D12_CPU_DESCRIPTOR_HANDLE> viewDescriptorSrcs; std::vector<uint> viewDescriptorAmounts; std::shared_ptr<QueryHeap> queryHeap; ProfilingEvent cmdListEvent; backend::ProfilingEventData *profilingEventStackTop = nullptr; int64_t firstProfilingEvent = -1; int64_t lastProfilingEvent = -1; CommandListState(Device &dev); }; } class CommandList : private backend::SharedState<backend::CommandListState> { friend class Device; friend class ProfilingEvent; friend struct backend::DeviceState; friend struct backend::GPUProgressTracking; SeqNum m_number = -1; public: CommandList() = default; ~CommandList(); CommandList(CommandList &&c); CommandList& operator=(CommandList &&c); CommandList(const CommandList &) = delete; CommandList& operator=(const CommandList &) = delete; explicit operator bool() const { return valid(); } SeqNum number() const; Device device(); void bind(GraphicsPipeline &pipeline); void bind(const info::GraphicsPipelineInfo &pipelineInfo); void bind(ComputePipeline &pipeline); void bind(const info::ComputePipelineInfo &pipelineInfo); void clearRTV(TextureRTV &rtv, float4 color = 0); void clearDSV(TextureDSV &dsv, float depth = 0); void clearUAV(TextureUAV &uav, uint4 clearValue = uint4(0)); void clearUAV(TextureUAV &uav, float4 clearValue); void clearUAV(BufferUAV &uav, uint4 clearValue = uint4(0)); void clearUAV(BufferUAV &uav, float4 clearValue); void setViewport(uint2 size); void setViewport(uint2 size, Rect scissor); void setScissor(Rect scissor); void setRenderTargets(); void setRenderTargets(TextureRTV &rtv); void setRenderTargets(TextureRTV &rtv, TextureDSV &dsv); void setRenderTargets(Span<TextureRTV * const> rtvs); void setRenderTargets(Span<TextureRTV * const> rtvs, TextureDSV &dsv); void setRenderTargets(TextureDSV &dsv); template <typename T> inline BufferVBV dynamicBufferVBV(Span<const T> vertices); BufferVBV dynamicBufferVBV(Span<const uint8_t> bytes, uint stride); template <typename T> inline BufferIBV dynamicBufferIBV(Span<const T> indices); BufferIBV dynamicBufferIBV(Span<const uint8_t> bytes, Format format); void setVBV(const BufferVBV &vbv, uint index = 0); void setVBVs(Span<const BufferVBV> vbvs); void setIBV(const BufferIBV &ibv); void setShaderView(unsigned slot, const TextureSRV &srv); void setShaderView(unsigned slot, TextureUAV &uav); void setShaderView(unsigned slot, const BufferSRV &srv); void setShaderView(unsigned slot, BufferUAV &uav); void setShaderViewNullTextureSRV(unsigned slot); void setShaderViewNullTextureUAV(unsigned slot); void setConstantBuffer(unsigned slot, Span<const uint8_t> bytes); template <typename T> void setConstants(unsigned slot, const T &t) { setConstantBuffer(slot, Span<const uint8_t>( reinterpret_cast<const uint8_t *>(&t), sizeof(t))); } template <typename T, unsigned Slot> void setConstants(const backend::ShaderCBuffer<T, Slot> &constants) { setConstants(Slot, static_cast<const T &>(constants)); } void setTopology(D3D_PRIMITIVE_TOPOLOGY topology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); void draw(uint vertices, uint startVertex = 0); void drawIndexed(uint indices, uint startIndex = 0); void dispatch(uint3 threadGroups); void dispatchThreads(uint3 threadGroupSize, uint3 threads) { dispatch(max(uint3(1), divRoundUp(threads, threadGroupSize))); } template <unsigned SX, unsigned SY, unsigned SZ> void dispatchThreads(const backend::ThreadGroupSize<SX, SY, SZ> &, uint3 threads) { dispatchThreads(uint3(SX, SY, SZ), threads); } void updateBuffer(Buffer &buffer, Span<const uint8_t> data, size_t offset = 0); void updateTexture(Texture &texture, ImageData data, ImageRect dstPos = {}); void readbackBuffer(Buffer &buffer, std::function<void(Span<const uint8_t>)> calledWhenDone, size_t offset = 0, size_t bytes = 0); void copyTexture(Texture &dst, ImageRect dstPos, const Texture &src, ImageRect srcArea = {}); void copyTexture(Texture &dst, const Texture &src); void imguiBeginFrame(SwapChain &swapChain, double deltaTime, ProfilingDisplay profiling = ProfilingDisplay::Enabled); void imguiEndFrame(SwapChain &swapChain); ProfilingEvent profilingEvent(const char *name, uint64_t uniqueId = 0); void profilingMarker(const char *msg); void profilingMarkerFormat(const char *fmt, ...); private: ID3D12GraphicsCommandList *cmd(); void close(); void reset(backend::GPUProgressTracking &progress); bool hasCompleted(); void waitUntilCompleted(DWORD timeout = INFINITE); CommandList(StatePtr state); void release(); // FIXME: This is horribly inefficient and bad void transition(const backend::Resource &resource, D3D12_RESOURCE_STATES state); void resetRenderTargets(); void transitionRenderTargets(); void setupRootArguments(bool compute); backend::HeapBlock uploadBytes(Span<const uint8_t> bytes, uint alignment = DefaultAlignment); static void handleShaderDebug(SeqNum cmdListNumber, Span<const uint8_t> shaderDebugData, uint4 *shaderDebugFeedback = nullptr); }; void cpuProfilingMarker(const char *msg); void cpuProfilingMarkerFormat(const char *fmt, ...); template<typename T> inline BufferVBV CommandList::dynamicBufferVBV(Span<const T> vertices) { return dynamicBufferVBV(asBytes(vertices), sizeof(T)); } template<typename T> inline BufferIBV CommandList::dynamicBufferIBV(Span<const T> indices) { if (sizeof(T) == 2) { return dynamicBufferIBV(asBytes(indices), DXGI_FORMAT_R16_UINT); } else if (sizeof(T) == 4) { return dynamicBufferIBV(asBytes(indices), DXGI_FORMAT_R32_UINT); } else { XOR_CHECK(false, "Invalid index size"); __assume(0); } } }
34.358491
101
0.616035
[ "vector" ]
0a0158dba17e87f13843ae0dfc67b077b220e908
4,729
cpp
C++
Codeforces/vk 2018/B.cpp
dipta007/Competitive-Programming
998d47f08984703c5b415b98365ddbc84ad289c4
[ "MIT" ]
6
2018-10-15T18:45:05.000Z
2022-03-29T04:30:10.000Z
Codeforces/vk 2018/B.cpp
dipta007/Competitive-Programming
998d47f08984703c5b415b98365ddbc84ad289c4
[ "MIT" ]
null
null
null
Codeforces/vk 2018/B.cpp
dipta007/Competitive-Programming
998d47f08984703c5b415b98365ddbc84ad289c4
[ "MIT" ]
4
2018-01-07T06:20:07.000Z
2019-08-21T15:45:59.000Z
#include <stdio.h> #include <algorithm> using namespace std; const double EPS = 1e-9; const int INF = 0x7f7f7f7f; #define READ(f) freopen(f, "r", stdin) #define WRITE(f) freopen(f, "w", stdout) #define MP(x, y) make_pair(x, y) #define PB(x) push_back(x) #define rep(i,n) for(int i = 1 ; i<=(n) ; i++) #define repI(i,n) for(int i = 0 ; i<(n) ; i++) #define FOR(i,L,R) for (int i = (int)(L); i <= (int)(R); i++) #define ROF(i,L,R) for (int i = (int)(L); i >= (int)(R); i--) #define FOREACH(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++) #define ALL(p) p.begin(),p.end() #define ALLR(p) p.rbegin(),p.rend() #define SET(p) memset(p, -1, sizeof(p)) #define CLR(p) memset(p, 0, sizeof(p)) #define MEM(p, v) memset(p, v, sizeof(p)) #define getI(a) scanf("%d", &a) #define getII(a,b) scanf("%d%d", &a, &b) #define getIII(a,b,c) scanf("%d%d%d", &a, &b, &c) #define getL(a) scanf("%lld",&a) #define getLL(a,b) scanf("%lld%lld",&a,&b) #define getLLL(a,b,c) scanf("%lld%lld%lld",&a,&b,&c) #define getC(n) scanf("%c",&n) #define getF(n) scanf("%lf",&n) #define getS(n) scanf("%s",n) #define bitCheck(N,in) ((bool)(N&(1<<(in)))) #define bitOff(N,in) (N&(~(1<<(in)))) #define bitOn(N,in) (N|(1<<(in))) #define bitFlip(a,k) (a^(1<<(k))) #define bitCount(a) __builtin_popcount(a) #define bitCountLL(a) __builtin_popcountll(a) #define bitLeftMost(a) (63-__builtin_clzll((a))) #define bitRightMost(a) (__builtin_ctzll(a)) #define iseq(a,b) (fabs(a-b)<EPS) #define UNIQUE(V) (V).erase(unique((V).begin(),(V).end()),(V).end()) #define vi vector < int > #define vii vector < vector < int > > #define pii pair< int, int > #define ff first #define ss second #define ll long long #define ull unsigned long long #define POPCOUNT __builtin_popcount #define POPCOUNTLL __builtin_popcountll #define RIGHTMOST __builtin_ctzll #define LEFTMOST(x) (63-__builtin_clzll((x))) template< class T > inline T gcd(T a, T b) { return (b) == 0 ? (a) : gcd((b), ((a) % (b))); } template< class T > inline T lcm(T a, T b) { return ((a) / gcd((a), (b)) * (b)); } // g++ -g -O2 -std=gnu++11 A.cpp // ./a.out // A utility function to swap two elements void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ int partition (int arr[], int low, int high) { int pivot = arr[high]; // pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high- 1; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // increment index of smaller element swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); return (i + 1); } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ void quickSort(int arr[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } int main() { #ifdef dipta007 //READ("in.txt"); //WRITE("out.txt"); #endif // dipta007 // ios_base::sync_with_stdio(0);cin.tie(0); int n; while(~getI(n)) { int v[n]; int mn = INF; FOR(i,0,n-1) { getI(v[i]); } quickSort(v, 0, n-1); ll gc = -1; FOR(i,1,n-1) { int kk = abs(v[i] - v[i-1]); if(gc == -1) gc = abs(kk); else gc = gcd(gc, (ll)abs(kk)); mn = min(mn, kk); } ll prev = v[0]; ll res = 0; FOR(i,1,n-1) { int kk = abs(v[i] - v[i-1]); if(kk != gc) { res += (kk / gc) - 1; } } printf("%lld\n",res); } return 0; }
30.509677
93
0.483823
[ "vector" ]
0a108d560cd00bcdfcbba2e2601ab33ac0d51cc2
9,460
cpp
C++
Sources/Core/Vulkan/SwapChain.cpp
alelievr/LWGEngine
655ed35350206401e20bc2fe6063574e1ede603f
[ "MIT" ]
3
2019-09-05T12:49:14.000Z
2020-06-08T00:13:49.000Z
Sources/Core/Vulkan/SwapChain.cpp
alelievr/LWGEngine
655ed35350206401e20bc2fe6063574e1ede603f
[ "MIT" ]
4
2018-12-16T15:39:19.000Z
2019-03-23T20:29:26.000Z
Sources/Core/Vulkan/SwapChain.cpp
alelievr/LWGEngine
655ed35350206401e20bc2fe6063574e1ede603f
[ "MIT" ]
2
2020-06-08T00:13:55.000Z
2021-12-12T10:10:20.000Z
#include "SwapChain.hpp" #include "Vk.hpp" #include <array> #include <limits> using namespace LWGC; SwapChain::SwapChain(void) : _instance(nullptr), _window(nullptr), _imageCount(0) { this->_swapChain = VK_NULL_HANDLE; this->_device = VK_NULL_HANDLE; } SwapChain::~SwapChain(void) { Cleanup(); } void SwapChain::Initialize(const VulkanSurface & surface) { _instance = VulkanInstance::Get(); _surface = surface.GetSurface(); _device = _instance->GetDevice(); _window = surface.GetWindow(); Create(); } void SwapChain::Create(void) { CreateSwapChain(); CreateImageViews(); } void SwapChain::Cleanup(void) noexcept { vkDestroyImageView(_device, _depthImageView, nullptr); vkDestroyImage(_device, _depthImage, nullptr); vkFreeMemory(_device, _depthImageMemory, nullptr); for (size_t i = 0; i < _framebuffers.size(); i++) vkDestroyFramebuffer(_device, _framebuffers[i], nullptr); for (size_t i = 0; i < _imageViews.size(); i++) vkDestroyImageView(_device, _imageViews[i], nullptr); vkDestroySwapchainKHR(_device, _swapChain, nullptr); } void SwapChain::CreateSwapChain(void) { VkSurfaceFormatKHR surfaceFormat = ChooseSurfaceFormat(); VkPresentModeKHR presentMode = ChoosePresentMode(); VkExtent2D extent = ChooseExtent(); const auto & capabilities = _instance->GetSurfaceCapabilities(); _imageCount = capabilities.minImageCount + 1; if (capabilities.maxImageCount > 0 && _imageCount > capabilities.maxImageCount) { _imageCount = capabilities.maxImageCount; } VkSwapchainCreateInfoKHR createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; createInfo.surface = _surface; createInfo.minImageCount = _imageCount; createInfo.imageFormat = surfaceFormat.format; createInfo.imageColorSpace = surfaceFormat.colorSpace; createInfo.imageExtent = extent; createInfo.imageArrayLayers = 1; createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; createInfo.preTransform = capabilities.currentTransform; createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; createInfo.presentMode = presentMode; createInfo.clipped = VK_TRUE; if (vkCreateSwapchainKHR(_device, &createInfo, nullptr, &_swapChain) != VK_SUCCESS) throw std::runtime_error("failed to create swap chain!"); vkGetSwapchainImagesKHR(_device, _swapChain, &_imageCount, nullptr); _images.resize(_imageCount); vkGetSwapchainImagesKHR(_device, _swapChain, &_imageCount, _images.data()); _imageFormat = surfaceFormat.format; _extent = extent; } void SwapChain::CreateImageViews(void) noexcept { _imageViews.resize(_images.size()); for (uint32_t i = 0; i < _images.size(); i++) _imageViews[i] = Vk::CreateImageView(_images[i], _imageFormat, 1, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_COLOR_BIT); } // TODO: this may not be in this class void SwapChain::TransitionDepthImageLayout(VkImage image, VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout) { VkCommandBuffer commandBuffer = _instance->GetCommandBufferPool()->BeginSingle(); VkImageMemoryBarrier barrier = {}; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.oldLayout = oldLayout; barrier.newLayout = newLayout; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.image = image; if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; if (Vk::HasStencilComponent(format)) { barrier.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT; } } else { barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; } barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.levelCount = 1; barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.layerCount = 1; VkPipelineStageFlags sourceStage; VkPipelineStageFlags destinationStage; if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT; } else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT; destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; } else if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; destinationStage = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT; } else { throw std::invalid_argument("unsupported layout transition!"); } vkCmdPipelineBarrier( commandBuffer, sourceStage, destinationStage, 0, 0, nullptr, 0, nullptr, 1, &barrier ); _instance->GetCommandBufferPool()->EndSingle(commandBuffer); } void SwapChain::CreateDepthResources(void) { VkFormat depthFormat = _instance->FindDepthFormat(); Vk::CreateImage(_extent.width, _extent.height, 1, 1, 1, depthFormat, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, _depthImage, _depthImageMemory); _depthImageView = Vk::CreateImageView(_depthImage, depthFormat, 1, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_DEPTH_BIT); TransitionDepthImageLayout(_depthImage, depthFormat, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); } void SwapChain::CreateFrameBuffers(const RenderPass & renderPass) { _framebuffers.resize(_imageViews.size()); CreateDepthResources(); for (size_t i = 0; i < _imageViews.size(); i++) { std::array<VkImageView, 2> attachments = {{ _imageViews[i], _depthImageView }}; VkFramebufferCreateInfo framebufferInfo = {}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = renderPass.GetRenderPass(); framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size()); framebufferInfo.pAttachments = attachments.data(); framebufferInfo.width = _extent.width; framebufferInfo.height = _extent.height; framebufferInfo.layers = 1; if (vkCreateFramebuffer(_device, &framebufferInfo, nullptr, &_framebuffers[i]) != VK_SUCCESS) throw std::runtime_error("failed to create framebuffer!"); } onRecreated.Invoke(); } VkSurfaceFormatKHR SwapChain::ChooseSurfaceFormat(void) noexcept { const auto & availableFormats = _instance->GetSupportedSurfaceFormats(); if (availableFormats.size() == 1 && availableFormats[0].format == VK_FORMAT_UNDEFINED) return {VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}; for (const auto& availableFormat : availableFormats) { if (availableFormat.format == VK_FORMAT_B8G8R8A8_UNORM && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) return availableFormat; } return availableFormats[0]; } VkPresentModeKHR SwapChain::ChoosePresentMode(void) noexcept { // return VK_PRESENT_MODE_FIFO_KHR; const auto & availablePresentModes = _instance->GetSupportedPresentModes(); VkPresentModeKHR bestMode = VK_PRESENT_MODE_FIFO_KHR; for (const auto & availablePresentMode : availablePresentModes) { if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) return availablePresentMode; else if (availablePresentMode == VK_PRESENT_MODE_IMMEDIATE_KHR) bestMode = availablePresentMode; } return bestMode; } VkExtent2D SwapChain::ChooseExtent(void) noexcept { const auto & capabilities = _instance->GetSurfaceCapabilities(); if (capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max()) return capabilities.currentExtent; int width, height; glfwGetFramebufferSize(_window, &width, &height); VkExtent2D actualExtent = { static_cast<uint32_t>(width), static_cast<uint32_t>(height) }; actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } VkSwapchainKHR SwapChain::GetSwapChain(void) const noexcept { return (this->_swapChain); } const std::vector< VkImage > SwapChain::GetImages(void) const noexcept { return (this->_images); } VkFormat SwapChain::GetImageFormat(void) const noexcept { return (this->_imageFormat); } VkExtent2D SwapChain::GetExtent(void) const noexcept { return (this->_extent); } const std::vector< VkImageView >SwapChain::GetImageViews(void) const noexcept { return (this->_imageViews); } const std::vector< VkFramebuffer >SwapChain::GetFramebuffers(void) const noexcept { return (this->_framebuffers); } uint32_t SwapChain::GetImageCount(void) const noexcept { return (this->_imageCount); } std::ostream & operator<<(std::ostream & o, SwapChain const & r) { o << "SwapChain of " << r.GetImageCount() << " framebuffers" << std::endl; (void)r; return (o); }
35.167286
209
0.774947
[ "vector" ]
0a21097b12d1fa2aa335e51f72ed731eb4b56288
2,499
hpp
C++
src/ms/env/match_env.hpp
toppic-suite/toppic-suite
b5f0851f437dde053ddc646f45f9f592c16503ec
[ "Apache-2.0" ]
8
2018-05-23T14:37:31.000Z
2022-02-04T23:48:38.000Z
src/ms/env/match_env.hpp
toppic-suite/toppic-suite
b5f0851f437dde053ddc646f45f9f592c16503ec
[ "Apache-2.0" ]
9
2019-08-31T08:17:45.000Z
2022-02-11T20:58:06.000Z
src/ms/env/match_env.hpp
toppic-suite/toppic-suite
b5f0851f437dde053ddc646f45f9f592c16503ec
[ "Apache-2.0" ]
4
2018-04-25T01:39:38.000Z
2020-05-20T19:25:07.000Z
//Copyright (c) 2014 - 2020, The Trustees of Indiana University. // //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 TOPPIC_TOPFD_ENV_MATCH_ENVELOPE_HPP_ #define TOPPIC_TOPFD_ENV_MATCH_ENVELOPE_HPP_ #include "ms/env/env_para.hpp" #include "ms/env/envelope.hpp" #include "ms/env/real_env.hpp" namespace toppic { class MatchEnv; typedef std::shared_ptr<MatchEnv> MatchEnvPtr; class MatchEnv { public: MatchEnv(int mass_group, EnvelopePtr theo_env_ptr, RealEnvPtr real_env_ptr); void compScr(EnvParaPtr env_para_ptr); static bool cmpScoreDec(const MatchEnvPtr &a, const MatchEnvPtr &b) { return a->getScore() > b->getScore();} double calcPeakScr(int id_x, double inte_sum, double tolerance); int getId() {return id_;} int getMassGroup() {return mass_group_;} RealEnvPtr getRealEnvPtr() {return real_env_ptr_;} EnvelopePtr getTheoEnvPtr() {return theo_env_ptr_;} double getScore() {return score_;} void setScore(double score) {score_ = score;} void setId(int id) {id_ = id;} void setTheoEnvPtr(EnvelopePtr theo_env_ptr) {theo_env_ptr_ = theo_env_ptr;} void appendXml(XmlDOMDocument* xml_doc,xercesc::DOMElement* parent); static std::string getXmlElementName() {return "match_env";} private: int id_; // we divide envelopes into several groups based on monoisotopic masses int mass_group_; double score_; EnvelopePtr theo_env_ptr_; RealEnvPtr real_env_ptr_; double calcShareInteAccu(int id_x, double inte_sum); double calcMzFactor(int id_x, double shift, double tolerance); double calcIntensityFactor(double theo_inte, double real_inte); double calcIntensityFactor(int id_x, double ratio); double findBestShift(EnvParaPtr env_para_ptr); double findBestRatio(EnvParaPtr env_para_ptr); double calcScrWithSftRatio(double shift, double ratio, double tolerance); }; typedef std::vector<MatchEnvPtr> MatchEnvPtrVec; typedef std::vector<MatchEnvPtrVec> MatchEnvPtr2D; } // namespace toppic #endif
28.078652
78
0.761104
[ "vector" ]
0a28e23bfadd6cdef94f02a76f66941e2d9c78eb
748
cpp
C++
src/zscore.cpp
srmocher/of-ParallelCoordinates
c4a53876f2dede5c49abb2ec5ef8e49769c0bdd0
[ "MIT" ]
null
null
null
src/zscore.cpp
srmocher/of-ParallelCoordinates
c4a53876f2dede5c49abb2ec5ef8e49769c0bdd0
[ "MIT" ]
null
null
null
src/zscore.cpp
srmocher/of-ParallelCoordinates
c4a53876f2dede5c49abb2ec5ef8e49769c0bdd0
[ "MIT" ]
null
null
null
#include "zscore.h" #include <numeric> ZScore::ZScore(Column c) { this->selectedColumn = c; } void ZScore::calculateMeanAndSD() { vector<DataPoint> values = selectedColumn.get_numeric_values(); double sum = 0; for (int i = 0;i < values.size();i++) sum += values[i].val; this->mean = sum / values.size(); double sq_sum = 0; for (auto i = 0;i < values.size();i++) sq_sum += values[i].val*values[i].val; this->standardDeviation = std::sqrt(sq_sum / values.size() - mean * mean); } float ZScore::getZScore(int rowIndex) { vector<DataPoint> values = this->selectedColumn.get_numeric_values(); float value = values[rowIndex].val; return (value - this->mean) / this->standardDeviation; } float ZScore::getMean() { return this->mean; }
22.666667
75
0.681818
[ "vector" ]
0a2b7f4eb96f535bfb49bd28cc51f14513d77547
1,801
cc
C++
tensorflow/contrib/star/star_channel_spec.cc
ShaunHeNJU/DeepRec-1
e280fb19de179f03dc05e1d8e3f4f7459796d96e
[ "Apache-2.0" ]
292
2021-12-24T03:24:33.000Z
2022-03-31T15:41:05.000Z
tensorflow/contrib/star/star_channel_spec.cc
ShaunHeNJU/DeepRec-1
e280fb19de179f03dc05e1d8e3f4f7459796d96e
[ "Apache-2.0" ]
54
2021-12-24T06:40:09.000Z
2022-03-30T07:57:24.000Z
tensorflow/contrib/star/star_channel_spec.cc
ShaunHeNJU/DeepRec-1
e280fb19de179f03dc05e1d8e3f4f7459796d96e
[ "Apache-2.0" ]
75
2021-12-24T04:48:21.000Z
2022-03-29T10:13:39.000Z
#include "tensorflow/contrib/star/star_channel_spec.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/gtl/map_util.h" #include "tensorflow/core/lib/strings/numbers.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/platform/mutex.h" #include "tensorflow/core/platform/thread_annotations.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/util/device_name_utils.h" namespace tensorflow { namespace { Status ValidateHostPortPair(const string& host_port) { uint32 port; std::vector<string> parts = str_util::Split(host_port, ':'); if (parts.size() != 2 || !strings::safe_strtou32(parts[1], &port) || parts[0].find("/") != string::npos) { return errors::InvalidArgument("Could not interpret \"", host_port, "\" as a host-port pair."); } return Status::OK(); } } // namespace Status StarChannelSpec::AddHostPortsJob( const string& job_id, const std::vector<string>& host_ports) { std::map<int, string> host_ports_map; for (size_t i = 0; i < host_ports.size(); ++i) { host_ports_map[i] = host_ports[i]; } return AddHostPortsJob(job_id, host_ports_map); } Status StarChannelSpec::AddHostPortsJob( const string& job_id, const std::map<int, string>& host_ports) { if (!job_ids_.insert(job_id).second) { return errors::InvalidArgument( "Duplicate job ID in cluster specification: ", job_id); } for (const auto& id_host_port : host_ports) { TF_RETURN_IF_ERROR(ValidateHostPortPair(id_host_port.second)); } host_ports_jobs_.emplace_back(job_id, host_ports); return Status::OK(); } } // namespace tensorflow
32.745455
71
0.721821
[ "vector" ]
0a2c24d386a7600e84b18ac1c50b11f09fb0b58a
6,249
hpp
C++
mochimochi/classifier/factory/binary_oml_factory.hpp
georgeslabreche/MochiMochi
6ed0e8e078504a068a812735567d196f5d88e69f
[ "MIT" ]
null
null
null
mochimochi/classifier/factory/binary_oml_factory.hpp
georgeslabreche/MochiMochi
6ed0e8e078504a068a812735567d196f5d88e69f
[ "MIT" ]
null
null
null
mochimochi/classifier/factory/binary_oml_factory.hpp
georgeslabreche/MochiMochi
6ed0e8e078504a068a812735567d196f5d88e69f
[ "MIT" ]
null
null
null
/** * Implement the Factory Design Pattern to instanciate Online ML algorithm objects. * https://refactoring.guru/design-patterns/factory-method/cpp/example * * Also implemented BinaryOMLInterface to give the option to develop the Proxy design pattern: * https://refactoring.guru/design-patterns/proxy/cpp/example#lang-features */ #ifndef MOCHIMOCHI_BINARY_OML_FACTORY_HPP_ #define MOCHIMOCHI_BINARY_OML_FACTORY_HPP_ #include <string> #include <iostream> #include <Eigen/Dense> #include "binary_oml.hpp" #include "../binary/adagrad_rda.hpp" #include "../binary/adam.hpp" #include "../binary/arow.hpp" #include "../binary/nherd.hpp" #include "../binary/pa.hpp" #include "../binary/scw.hpp" #include "../../utility/load_svmlight_file.hpp" using namespace std; /** * This interface declares common operations for both BinaryOMLCreator and whatever Proxy class will be implemented. */ class BinaryOMLInterface { public: /** * Name of the ML algorithm. */ virtual string name() = 0; /** * Train/update the model with the given training input. */ virtual void train(string *pInput, int dim) = 0; /** * Train/update the model with the given training input and save/serialize the model. */ virtual void trainAndSave(string *pInput, size_t dim, const string modelFilePath) = 0; /** * Infer/predict the label with the given input. */ virtual int infer(string *pInput, size_t dim) = 0; /** * Load a saved/serialized model. */ virtual void load(const string modelFilePath) = 0; /** * Save/serialize the trained model. */ virtual void save(const string modelFilePath) = 0; }; /** * The Creator class declares the factory method that returns an object * of the BinaryOML class. The Creator's subclasses provide the * implementation of this method. * * Despite its name, the Creator's primary responsibility isn't to create * BinaryOML. Usually, it contains some core business logic that relies * on BinaryOML objects, returned by the factory method. Subclasses can * indirectly change that business logic by overriding the factory method * and returning a different type of BinaryOML from it. */ class BinaryOMLCreator : public BinaryOMLInterface { /** * Note that the Creator may also provide some default implementation of * the factory method. */ protected: BinaryOML* m_pBinaryOML; /* The constructor. */ BinaryOMLCreator(BinaryOML* pBinaryOML) { m_pBinaryOML = pBinaryOML; } public: virtual ~BinaryOMLCreator() { delete m_pBinaryOML; }; BinaryOML* FactoryMethod() { return m_pBinaryOML; }; /** * The name of the ML method tied to the instance of the Creator class. */ string name() { return m_pBinaryOML->name(); } /** * Train the model. */ void train(string *pInput, int dim) { /* Convert training string input into training vector. */ auto data = utility::read_ones<int>(*pInput, dim); /* Update the model with the new training data. */ m_pBinaryOML->update(data.second, data.first); } /** * Train and save/serialize the model. */ void trainAndSave(string *pInput, size_t dim, const string modelFilePath) { /* Convert training string input into data vector. */ auto data = utility::read_ones<int>(*pInput, dim); /* Update the model with the new training data. */ m_pBinaryOML->update(data.second, data.first); /* Serialize the model. */ m_pBinaryOML->save(modelFilePath); } /** * Infer/predict the label of the given data input */ int infer(string *pInput, size_t dim) { /* Convert inference string input into data vector. */ auto data = utility::read_ones<int>(*pInput, dim); /* Invoke prediction method and return result. */ return m_pBinaryOML->predict(data.second); } /** * Load the model. */ void load(const string modelFilePath) { m_pBinaryOML->load(modelFilePath); } /** * Save/serialize the model. */ void save(const string modelFilePath) { m_pBinaryOML->save(modelFilePath); } }; /** * Concrete Creators override the factory method in order to change the * resulting BinaryOML's type. */ class BinaryADAGRADRDACreator : public BinaryOMLCreator { /** * Note that the signature of the method still uses the abstract binary OML type, * even though the concrete binary OML is actually returned from the method. This * way the Creator can stay independent of concrete binary OML classes. */ public: virtual ~BinaryADAGRADRDACreator() {} /* The BinaryOML creator for ADAGRAD RDA. */ BinaryADAGRADRDACreator(const size_t dim, const double eta, const double lambda) : BinaryOMLCreator(new ADAGRAD_RDA(dim, eta, lambda)) { } }; /** * Concrete Creator for ADAGRAD RDA. */ class BinaryADAMCreator : public BinaryOMLCreator { public: virtual ~BinaryADAMCreator() {}; /* The BinaryOML creator for ADAM. */ BinaryADAMCreator(const size_t dim) : BinaryOMLCreator(new ADAM(dim)) { } }; /** * Concrete Creator for AROW. */ class BinaryAROWCreator : public BinaryOMLCreator { public: virtual ~BinaryAROWCreator() {} /* The BinaryOML creator for AROW. */ BinaryAROWCreator(const size_t dim, const double r) : BinaryOMLCreator(new AROW(dim, r)) { } }; /** * Concrete Creator for NHERD. */ class BinaryNHERDCreator : public BinaryOMLCreator { public: virtual ~BinaryNHERDCreator() {} /* The BinaryOML creator for NHERD. */ BinaryNHERDCreator(const size_t dim, const double c, const int diagonal) : BinaryOMLCreator(new NHERD(dim, c, diagonal)) { } }; /** * Concrete Creator for PA. */ class BinaryPACreator : public BinaryOMLCreator { public: virtual ~BinaryPACreator() {} /* The BinaryOML creator for PA. */ BinaryPACreator(const size_t dim, const double c, const int select) : BinaryOMLCreator(new PA(dim, c, select)) { } }; /** * Concrete Creator for SCW. */ class BinarySCWCreator : public BinaryOMLCreator { public: virtual ~BinarySCWCreator() {} /* The BinaryOML creator for SCW. */ BinarySCWCreator(const size_t dim, const double c, const double eta) : BinaryOMLCreator(new SCW(dim, c, eta)) { } }; #endif // MOCHIMOCHI_BINARY_OML_FACTORY_HPP_
24.127413
116
0.698512
[ "object", "vector", "model" ]
0a2fc16dd51c15315f6d9e7e761473f275b53b79
3,180
cpp
C++
Engine/Graphics/Direct3D12/D3D12PostProcess.cpp
ZackShrout/HavanaEngine
b8869acfff27e41bd37079716d152c2df9674fe2
[ "Apache-2.0" ]
null
null
null
Engine/Graphics/Direct3D12/D3D12PostProcess.cpp
ZackShrout/HavanaEngine
b8869acfff27e41bd37079716d152c2df9674fe2
[ "Apache-2.0" ]
null
null
null
Engine/Graphics/Direct3D12/D3D12PostProcess.cpp
ZackShrout/HavanaEngine
b8869acfff27e41bd37079716d152c2df9674fe2
[ "Apache-2.0" ]
null
null
null
#include "D3D12PostProcess.h" #include "D3D12Core.h" #include "D3D12Shaders.h" #include "D3D12Surface.h" #include "D3D12GPass.h" namespace Havana::Graphics::D3D12::FX { namespace { struct FXRootParamIndices { enum : u32 { rootConstants, descriptorTable, count }; }; ID3D12RootSignature* fxRootSig{ nullptr }; ID3D12PipelineState* fxPSO{ nullptr }; bool CreateFXPSOAndRootSignature() { assert(!fxRootSig && !fxPSO); // Create Post-Process FX root signature D3DX::D3D12_Descriptor_Range range { D3D12_DESCRIPTOR_RANGE_TYPE_SRV, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND, 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE }; using idx = FXRootParamIndices; D3DX::D3D12_Root_Parameter paramters[idx::count]{}; paramters[idx::rootConstants].AsConstants(1, D3D12_SHADER_VISIBILITY_PIXEL, 1); paramters[idx::descriptorTable].AsDescriptorTable(D3D12_SHADER_VISIBILITY_PIXEL, &range, 1); const D3DX::D3D12_Root_Signature_Desc rootSignature{ &paramters[0], _countof(paramters) }; fxRootSig = rootSignature.Create(); assert(fxRootSig); NAME_D3D12_OBJECT(fxRootSig, L"Post-Process FX Root Signature"); // Create Post-Process FX Pipeline State Object struct { D3DX::D3D12_Pipeline_State_Subobject_rootSignature rootSignature{ fxRootSig }; D3DX::D3D12_Pipeline_State_Subobject_vs vs{ Shaders::GetEngineShader(Shaders::EngineShader::fullscreenTriangleVS) }; D3DX::D3D12_Pipeline_State_Subobject_ps ps{ Shaders::GetEngineShader(Shaders::EngineShader::postProcessPS) }; D3DX::D3D12_Pipeline_State_Subobject_primitiveTopology primitiveTopology{ D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE }; D3DX::D3D12_Pipeline_State_Subobject_renderTargetFormats renderTargetFormats; D3DX::D3D12_Pipeline_State_Subobject_rasterizer rasterizer{ D3DX::rasterizerState.noCull }; } stream; D3D12_RT_FORMAT_ARRAY rtfArray{}; rtfArray.NumRenderTargets = 1; rtfArray.RTFormats[0] = D3D12Surface::defaultBackBufferFormat; stream.renderTargetFormats = rtfArray; fxPSO = D3DX::CreatePipelineState(&stream, sizeof(stream)); NAME_D3D12_OBJECT(fxRootSig, L"Post-Process FX Pipeline State Object"); return fxRootSig && fxPSO; } } //anonymous namespace bool Initialize() { return CreateFXPSOAndRootSignature(); } void Shutdown() { Core::Release(fxRootSig); Core::Release(fxPSO); } void PostProcess(ID3D12GraphicsCommandList* cmdList, D3D12_CPU_DESCRIPTOR_HANDLE targetRTV) { cmdList->SetGraphicsRootSignature(fxRootSig); cmdList->SetPipelineState(fxPSO); using idx = FXRootParamIndices; cmdList->SetGraphicsRoot32BitConstant(idx::rootConstants, GPass::MainBuffer().SRV().index, 0); cmdList->SetGraphicsRootDescriptorTable(idx::descriptorTable, Core::SRVHeap().GpuStart()); cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // NOTE: we don't need to clear the render target, because each pixel will // be overwritten by pixels from the gpass main buffer. // We also don't need a depth buffer. cmdList->OMSetRenderTargets(1, &targetRTV, 1, nullptr); cmdList->DrawInstanced(3, 1, 0, 0); } }
32.44898
125
0.759434
[ "render", "object" ]
0a31f125ce7c74e77313b56e0a2597de3b1600bd
2,705
cpp
C++
day5/main5.cpp
nspo/adventOfCode2020-cpp
9ecd1a721b3821b5d1dbd7438ef61dc28af7c8b8
[ "BSD-3-Clause" ]
null
null
null
day5/main5.cpp
nspo/adventOfCode2020-cpp
9ecd1a721b3821b5d1dbd7438ef61dc28af7c8b8
[ "BSD-3-Clause" ]
null
null
null
day5/main5.cpp
nspo/adventOfCode2020-cpp
9ecd1a721b3821b5d1dbd7438ef61dc28af7c8b8
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <fstream> #include <cassert> #include <vector> #include <algorithm> #include <deque> // helper class for seat identification class BinarySelector { public: BinarySelector(int min, int max) { assert(min <= max); this->min = min; this->max = max; } // constrict to upper half void top() { min = (min+max)/2+1; } // constrict to lower half void bottom() { max = (min+max)/2; } [[nodiscard]] int get() const { if(min != max) throw std::logic_error("Did not find element yet"); return min; } private: int min; int max; }; class BoardingPass { public: int row; int col; int id; // init with 10-letter code explicit BoardingPass(const std::string& code) { if(code.size() != 10) throw std::invalid_argument("code length must be 10"); // row identification BinarySelector rowSelector(0, 127); for(int i=0; i<7; ++i) { if(code[i] == 'F') { rowSelector.bottom(); } else if(code[i] == 'B') { rowSelector.top(); } else { throw std::invalid_argument("code malformed"); } } this->row = rowSelector.get(); // column identification BinarySelector colSelector(0, 7); for(int i=7; i<10; ++i) { if(code[i] == 'L') { colSelector.bottom(); } else if(code[i] == 'R') { colSelector.top(); } else { throw std::invalid_argument("code malformed"); } } this->col = colSelector.get(); this->id = this->row*8 + this->col; } }; int main(int argc, char** argv) { (void) argc; (void) argv; std::ifstream reader("../day5/input.txt"); if(!reader) { std::cerr << "Error while opening input\n"; return EXIT_FAILURE; } std::vector<BoardingPass> bps; std::string line; std::deque<bool> seatTaken(128*8, false); // don't use vector<bool> while(std::getline(reader, line)) { bps.emplace_back(line); seatTaken[(--bps.end())->id] = true; } auto itHighestId = std::max_element(bps.begin(), bps.end(), [](const BoardingPass& bp1, const BoardingPass& bp2) { return bp1.id < bp2.id; }); std::cout<<"highest seat id: "<<itHighestId->id<<"\n"; // find seat that's not taken but has rows with people in front and behind it for(int id=0+1; id<128*8-1; ++id) { if(!seatTaken[id] && seatTaken[id-1] && seatTaken[id+1]) { std::cout<<id<<" is your seat\n"; break; } } }
26.009615
146
0.52939
[ "vector" ]
0a33c65a271418993d27d5bb0ca0660e5a071294
239
hpp
C++
demos/console_demo.hpp
nathanmullenax83/rhizome
e7410341fdc4d38ab5aaecc55c94d3ac6efd51da
[ "MIT" ]
1
2020-07-11T14:53:38.000Z
2020-07-11T14:53:38.000Z
demos/console_demo.hpp
nathanmullenax83/rhizome
e7410341fdc4d38ab5aaecc55c94d3ac6efd51da
[ "MIT" ]
1
2020-07-04T16:45:49.000Z
2020-07-04T16:45:49.000Z
demos/console_demo.hpp
nathanmullenax83/rhizome
e7410341fdc4d38ab5aaecc55c94d3ac6efd51da
[ "MIT" ]
null
null
null
#ifndef RHIZOME_DEMO_CONSOLE #define RHIZOME_DEMO_CONSOLE #include <vector> #include <iostream> #include "rhizome.hpp" namespace ru = rhizome::ui; namespace rhizome { namespace demo { void console_demo(); } } #endif
11.95
28
0.698745
[ "vector" ]
0a3a92c64bb4e759d6f067b36e14637730a653c6
27,979
cpp
C++
Infinion/GeneratedCCode/SimulinkModel/Infinion_grt_rtw/Infinion_data.cpp
AadityaChaudhary/Simulink-Sim
1563ae1ac43fe8d77a203fde18ea48409643b911
[ "BSD-3-Clause" ]
null
null
null
Infinion/GeneratedCCode/SimulinkModel/Infinion_grt_rtw/Infinion_data.cpp
AadityaChaudhary/Simulink-Sim
1563ae1ac43fe8d77a203fde18ea48409643b911
[ "BSD-3-Clause" ]
null
null
null
Infinion/GeneratedCCode/SimulinkModel/Infinion_grt_rtw/Infinion_data.cpp
AadityaChaudhary/Simulink-Sim
1563ae1ac43fe8d77a203fde18ea48409643b911
[ "BSD-3-Clause" ]
null
null
null
/* * Infinion_data.cpp * * Academic License - for use in teaching, academic research, and meeting * course requirements at degree granting institutions only. Not for * government, commercial, or other organizational use. * * Code generation for model "Infinion". * * Model version : 1.259 * Simulink Coder version : 9.3 (R2020a) 18-Nov-2019 * C++ source code generated on : Fri Dec 18 20:43:15 2020 * * Target selection: grt.tlc * Note: GRT includes extra infrastructure and instrumentation for prototyping * Embedded hardware selection: Intel->x86-64 (Windows64) * Code generation objectives: Unspecified * Validation result: Not run */ #include "Infinion.h" #include "Infinion_private.h" /* Block parameters (default storage) */ P_Infinion_T InfinionModelClass::Infinion_P = { { 0.0, 0.0 }, 0.69, 0.69, { 30.0, 0.0, 0.0 }, 2.4, 2.4, 0.3, 0.3, 180.0, 90.0, 180.0, 180.0, 90.0, 180.0, { 0.0, 0.0, 0.0 }, { 0.33, 0.0, 0.0, 0.0, 0.4, 0.0, 0.0, 0.0, 0.66 }, 1.9, { 0.0, 0.0, 0.0 }, 0.0, { 0.0, 0.0, 20.0 }, -90.0, -1.0, 90.0, 180.0, -180.0, 180.0, -180.0, 0.0, 180.0, -90.0, -1.0, 90.0, 360.0, 180.0, -180.0, 360.0, 180.0, -180.0, -1.0, 21.322, 1.0, 6.378137E+6, 1.0, 1.0, 0.0033528106647474805, 1.0, 1.0, 1.0, 360.0, -157.924, 180.0, 0.0, 360.0, 0.0, -1.0, 3.1415926535897931, -3.1415926535897931, 1.2754, 0.5, 0.0, { -15.0, -10.0, -5.0, -2.5, 0.0, 2.5, 5.0, 10.0, 15.0 }, 343.0, { 0.02, 0.04, 0.06 }, { 10.0, 50.0, 100.0 }, { -0.053259, -0.036256, -0.018128, -0.0090639, 0.0, 0.0090639, 0.018128, 0.036256, 0.053259, -0.053459, -0.036392, -0.018196, -0.0090979, 0.0, 0.0090979, 0.018196, 0.036392, 0.053459, -0.053535, -0.036443, -0.018222, -0.0091109, 0.0, 0.0091109, 0.018222, 0.036443, 0.053535, -0.053258, -0.036255, -0.018128, -0.0090638, 0.0, 0.0090638, 0.018128, 0.036255, 0.053258, -0.053458, -0.036391, -0.018195, -0.0090977, 0.0, 0.0090977, 0.018195, 0.036391, 0.053458, -0.053534, -0.036443, -0.018221, -0.0091107, 0.0, 0.0091107, 0.018221, 0.036443, 0.053534, -0.053257, -0.036254, -0.018127, -0.0090636, 0.0, 0.0090636, 0.018127, 0.036254, 0.053257, -0.053456, -0.03639, -0.018195, -0.0090975, 0.0, 0.0090975, 0.018195, 0.03639, 0.053456, -0.053533, -0.036442, -0.018221, -0.0091105, 0.0, 0.0091105, 0.018221, 0.036442, 0.053533 }, { -16.0, -12.0, -8.0, -4.0, -2.0, 0.0, 2.0, 4.0, 8.0, 12.0, 16.0, 20.0 }, { -0.01228, -0.00818, -0.004215, -0.0005361, 0.001208, 0.003048, 0.00498, 0.006987, 0.01115, 0.01491, 0.01717, 0.01638, -0.008362, -0.005568, -0.002869, -0.0003649, 0.0008222, 0.002075, 0.00339, 0.004756, 0.007591, 0.01015, 0.01169, 0.01115, -0.004181, -0.002784, -0.001434, -0.0001825, 0.0004111, 0.001038, 0.001695, 0.002378, 0.003796, 0.005075, 0.005843, 0.005575, -0.002091, -0.001392, -0.0007172, -9.123E-5, 0.0002056, 0.0005188, 0.0008475, 0.001189, 0.001898, 0.002537, 0.002922, 0.002787, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.002091, 0.001392, 0.0007172, 9.123E-5, -0.0002056, -0.0005188, -0.0008475, -0.001189, -0.001898, -0.002537, -0.002922, -0.002787, 0.004181, 0.002784, 0.001434, 0.0001825, -0.0004111, -0.001038, -0.001695, -0.002378, -0.003796, -0.005075, -0.005843, -0.005575, 0.008362, 0.005568, 0.002869, 0.0003649, -0.0008222, -0.002075, -0.00339, -0.004756, -0.007591, -0.01015, -0.01169, -0.01115, 0.01228, 0.00818, 0.004215, 0.0005361, -0.001208, -0.003048, -0.00498, -0.006987, -0.01115, -0.01491, -0.01717, -0.01638, -0.01233, -0.008208, -0.004229, -0.0005379, 0.001212, 0.003059, 0.004997, 0.007011, 0.01119, 0.01496, 0.01723, 0.01645, -0.008391, -0.005587, -0.002879, -0.0003661, 0.000825, 0.002082, 0.003402, 0.004772, 0.007618, 0.01019, 0.01173, 0.0112, -0.004196, -0.002794, -0.001439, -0.0001831, 0.0004125, 0.001041, 0.001701, 0.002386, 0.003809, 0.005093, 0.005865, 0.005599, -0.002098, -0.001397, -0.0007197, -9.154E-5, 0.0002062, 0.0005205, 0.0008504, 0.001193, 0.001904, 0.002546, 0.002932, 0.0028, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.002098, 0.001397, 0.0007197, 9.154E-5, -0.0002062, -0.0005205, -0.0008504, -0.001193, -0.001904, -0.002546, -0.002932, -0.0028, 0.004196, 0.002794, 0.001439, 0.0001831, -0.0004125, -0.001041, -0.001701, -0.002386, -0.003809, -0.005093, -0.005865, -0.005599, 0.008391, 0.005587, 0.002879, 0.0003661, -0.000825, -0.002082, -0.003402, -0.004772, -0.007618, -0.01019, -0.01173, -0.0112, 0.01233, 0.008208, 0.004229, 0.0005379, -0.001212, -0.003059, -0.004997, -0.007011, -0.01119, -0.01496, -0.01723, -0.01645, -0.01235, -0.008224, -0.004237, -0.000539, 0.001214, 0.003065, 0.005007, 0.007024, 0.01121, 0.01499, 0.01726, 0.01647, -0.008407, -0.005598, -0.002884, -0.0003669, 0.0008267, 0.002086, 0.003408, 0.004782, 0.007632, 0.0102, 0.01175, 0.01121, -0.004203, -0.002799, -0.001442, -0.0001834, 0.0004133, 0.001043, 0.001704, 0.002391, 0.003816, 0.005101, 0.005874, 0.005605, -0.002102, -0.001399, -0.0007211, -9.172E-5, 0.0002067, 0.0005215, 0.0008521, 0.001195, 0.001908, 0.002551, 0.002937, 0.002802, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.002102, 0.001399, 0.0007211, 9.172E-5, -0.0002067, -0.0005215, -0.0008521, -0.001195, -0.001908, -0.002551, -0.002937, -0.002802, 0.004203, 0.002799, 0.001442, 0.0001834, -0.0004133, -0.001043, -0.001704, -0.002391, -0.003816, -0.005101, -0.005874, -0.005605, 0.008407, 0.005598, 0.002884, 0.0003669, -0.0008267, -0.002086, -0.003408, -0.004782, -0.007632, -0.0102, -0.01175, -0.01121, 0.01235, 0.008224, 0.004237, 0.000539, -0.001214, -0.003065, -0.005007, -0.007024, -0.01121, -0.01499, -0.01726, -0.01647, -0.01228, -0.00818, -0.004215, -0.0005361, 0.001208, 0.003048, 0.00498, 0.006987, 0.01115, 0.01491, 0.01717, 0.01638, -0.008362, -0.005568, -0.002869, -0.0003649, 0.0008222, 0.002075, 0.00339, 0.004756, 0.007591, 0.01015, 0.01169, 0.01115, -0.004181, -0.002784, -0.001434, -0.0001825, 0.0004111, 0.001037, 0.001695, 0.002378, 0.003796, 0.005074, 0.005843, 0.005575, -0.002091, -0.001392, -0.0007172, -9.123E-5, 0.0002055, 0.0005187, 0.0008475, 0.001189, 0.001898, 0.002537, 0.002922, 0.002787, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.002091, 0.001392, 0.0007172, 9.123E-5, -0.0002055, -0.0005187, -0.0008475, -0.001189, -0.001898, -0.002537, -0.002922, -0.002787, 0.004181, 0.002784, 0.001434, 0.0001825, -0.0004111, -0.001037, -0.001695, -0.002378, -0.003796, -0.005074, -0.005843, -0.005575, 0.008362, 0.005568, 0.002869, 0.0003649, -0.0008222, -0.002075, -0.00339, -0.004756, -0.007591, -0.01015, -0.01169, -0.01115, 0.01228, 0.00818, 0.004215, 0.0005361, -0.001208, -0.003048, -0.00498, -0.006987, -0.01115, -0.01491, -0.01717, -0.01638, -0.01233, -0.008208, -0.004229, -0.0005379, 0.001212, 0.003059, 0.004997, 0.007011, 0.01119, 0.01496, 0.01723, 0.01645, -0.008391, -0.005587, -0.002879, -0.0003661, 0.000825, 0.002082, 0.003402, 0.004772, 0.007617, 0.01019, 0.01173, 0.0112, -0.004195, -0.002794, -0.001439, -0.0001831, 0.0004125, 0.001041, 0.001701, 0.002386, 0.003809, 0.005093, 0.005864, 0.005599, -0.002098, -0.001397, -0.0007197, -9.153E-5, 0.0002062, 0.0005205, 0.0008504, 0.001193, 0.001904, 0.002546, 0.002932, 0.0028, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.002098, 0.001397, 0.0007197, 9.153E-5, -0.0002062, -0.0005205, -0.0008504, -0.001193, -0.001904, -0.002546, -0.002932, -0.0028, 0.004195, 0.002794, 0.001439, 0.0001831, -0.0004125, -0.001041, -0.001701, -0.002386, -0.003809, -0.005093, -0.005864, -0.005599, 0.008391, 0.005587, 0.002879, 0.0003661, -0.000825, -0.002082, -0.003402, -0.004772, -0.007617, -0.01019, -0.01173, -0.0112, 0.01233, 0.008208, 0.004229, 0.0005379, -0.001212, -0.003059, -0.004997, -0.007011, -0.01119, -0.01496, -0.01723, -0.01645, -0.01235, -0.008223, -0.004237, -0.000539, 0.001214, 0.003065, 0.005007, 0.007024, 0.01121, 0.01499, 0.01726, 0.01647, -0.008407, -0.005598, -0.002884, -0.0003669, 0.0008266, 0.002086, 0.003408, 0.004782, 0.007632, 0.0102, 0.01175, 0.01121, -0.004203, -0.002799, -0.001442, -0.0001834, 0.0004133, 0.001043, 0.001704, 0.002391, 0.003816, 0.005101, 0.005874, 0.005605, -0.002102, -0.001399, -0.0007211, -9.172E-5, 0.0002067, 0.0005215, 0.0008521, 0.001195, 0.001908, 0.002551, 0.002937, 0.002802, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.002102, 0.001399, 0.0007211, 9.172E-5, -0.0002067, -0.0005215, -0.0008521, -0.001195, -0.001908, -0.002551, -0.002937, -0.002802, 0.004203, 0.002799, 0.001442, 0.0001834, -0.0004133, -0.001043, -0.001704, -0.002391, -0.003816, -0.005101, -0.005874, -0.005605, 0.008407, 0.005598, 0.002884, 0.0003669, -0.0008266, -0.002086, -0.003408, -0.004782, -0.007632, -0.0102, -0.01175, -0.01121, 0.01235, 0.008223, 0.004237, 0.000539, -0.001214, -0.003065, -0.005007, -0.007024, -0.01121, -0.01499, -0.01726, -0.01647, -0.01228, -0.008179, -0.004214, -0.0005361, 0.001208, 0.003048, 0.00498, 0.006987, 0.01115, 0.01491, 0.01717, 0.01638, -0.008362, -0.005568, -0.002869, -0.0003649, 0.0008222, 0.002075, 0.00339, 0.004756, 0.007591, 0.01015, 0.01169, 0.01115, -0.004181, -0.002784, -0.001434, -0.0001825, 0.0004111, 0.001037, 0.001695, 0.002378, 0.003795, 0.005074, 0.005843, 0.005575, -0.00209, -0.001392, -0.0007172, -9.123E-5, 0.0002055, 0.0005187, 0.0008475, 0.001189, 0.001898, 0.002537, 0.002921, 0.002787, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.00209, 0.001392, 0.0007172, 9.123E-5, -0.0002055, -0.0005187, -0.0008475, -0.001189, -0.001898, -0.002537, -0.002921, -0.002787, 0.004181, 0.002784, 0.001434, 0.0001825, -0.0004111, -0.001037, -0.001695, -0.002378, -0.003795, -0.005074, -0.005843, -0.005575, 0.008362, 0.005568, 0.002869, 0.0003649, -0.0008222, -0.002075, -0.00339, -0.004756, -0.007591, -0.01015, -0.01169, -0.01115, 0.01228, 0.008179, 0.004214, 0.0005361, -0.001208, -0.003048, -0.00498, -0.006987, -0.01115, -0.01491, -0.01717, -0.01638, -0.01233, -0.008207, -0.004229, -0.0005379, 0.001212, 0.003058, 0.004997, 0.007011, 0.01119, 0.01496, 0.01723, 0.01645, -0.008391, -0.005587, -0.002879, -0.0003661, 0.000825, 0.002082, 0.003402, 0.004772, 0.007617, 0.01019, 0.01173, 0.0112, -0.004195, -0.002793, -0.001439, -0.0001831, 0.0004125, 0.001041, 0.001701, 0.002386, 0.003809, 0.005093, 0.005864, 0.005599, -0.002098, -0.001397, -0.0007197, -9.153E-5, 0.0002062, 0.0005205, 0.0008504, 0.001193, 0.001904, 0.002546, 0.002932, 0.002799, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.002098, 0.001397, 0.0007197, 9.153E-5, -0.0002062, -0.0005205, -0.0008504, -0.001193, -0.001904, -0.002546, -0.002932, -0.002799, 0.004195, 0.002793, 0.001439, 0.0001831, -0.0004125, -0.001041, -0.001701, -0.002386, -0.003809, -0.005093, -0.005864, -0.005599, 0.008391, 0.005587, 0.002879, 0.0003661, -0.000825, -0.002082, -0.003402, -0.004772, -0.007617, -0.01019, -0.01173, -0.0112, 0.01233, 0.008207, 0.004229, 0.0005379, -0.001212, -0.003058, -0.004997, -0.007011, -0.01119, -0.01496, -0.01723, -0.01645, -0.01235, -0.008223, -0.004237, -0.000539, 0.001214, 0.003065, 0.005007, 0.007024, 0.01121, 0.01499, 0.01726, 0.01647, -0.008407, -0.005598, -0.002884, -0.0003669, 0.0008266, 0.002086, 0.003408, 0.004781, 0.007632, 0.0102, 0.01175, 0.01121, -0.004203, -0.002799, -0.001442, -0.0001834, 0.0004133, 0.001043, 0.001704, 0.002391, 0.003816, 0.005101, 0.005874, 0.005605, -0.002102, -0.001399, -0.0007211, -9.172E-5, 0.0002067, 0.0005215, 0.0008521, 0.001195, 0.001908, 0.002551, 0.002937, 0.002802, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.002102, 0.001399, 0.0007211, 9.172E-5, -0.0002067, -0.0005215, -0.0008521, -0.001195, -0.001908, -0.002551, -0.002937, -0.002802, 0.004203, 0.002799, 0.001442, 0.0001834, -0.0004133, -0.001043, -0.001704, -0.002391, -0.003816, -0.005101, -0.005874, -0.005605, 0.008407, 0.005598, 0.002884, 0.0003669, -0.0008266, -0.002086, -0.003408, -0.004781, -0.007632, -0.0102, -0.01175, -0.01121, 0.01235, 0.008223, 0.004237, 0.000539, -0.001214, -0.003065, -0.005007, -0.007024, -0.01121, -0.01499, -0.01726, -0.01647 }, -1.0, { -25.0, -16.0, -8.0, 0.0, 8.0, 16.0, 25.0 }, { 0.0112, 0.00951, 0.00791, 0.00624, 0.00537, 0.00451, 0.00364, 0.0028, 0.00109, -0.000819, -0.00317, -0.00621, 0.0116, 0.00989, 0.00825, 0.00653, 0.00564, 0.00475, 0.00387, 0.003, 0.00125, -0.000714, -0.00313, -0.00625, 0.0118, 0.0101, 0.00846, 0.00672, 0.00581, 0.00491, 0.00401, 0.00313, 0.00135, -0.000648, -0.0031, -0.00627, 0.0111, 0.0095, 0.0079, 0.00623, 0.00536, 0.0045, 0.00364, 0.00279, 0.00109, -0.000821, -0.00317, -0.00621, 0.0116, 0.00988, 0.00824, 0.00652, 0.00563, 0.00475, 0.00386, 0.00299, 0.00125, -0.000717, -0.00313, -0.00624, 0.0118, 0.0101, 0.00845, 0.00671, 0.0058, 0.00491, 0.004, 0.00312, 0.00135, -0.00065, -0.0031, -0.00627, 0.0111, 0.00949, 0.00789, 0.00623, 0.00536, 0.0045, 0.00363, 0.00279, 0.00109, -0.000822, -0.00317, -0.00621, 0.0116, 0.00988, 0.00823, 0.00652, 0.00563, 0.00474, 0.00386, 0.00299, 0.00124, -0.000719, -0.00313, -0.00624, 0.0118, 0.0101, 0.00844, 0.0067, 0.0058, 0.0049, 0.004, 0.00312, 0.00134, -0.000653, -0.0031, -0.00627, 0.0102, 0.00863, 0.00713, 0.00557, 0.00475, 0.00395, 0.00314, 0.00234, 0.000749, -0.00104, -0.00324, -0.00609, 0.0106, 0.00898, 0.00744, 0.00583, 0.00499, 0.00416, 0.00333, 0.00252, 0.00088, -0.000961, -0.00322, -0.00615, 0.0108, 0.0092, 0.00763, 0.00599, 0.00514, 0.0043, 0.00346, 0.00263, 0.000964, -0.000908, -0.00321, -0.00618, 0.0102, 0.00863, 0.00713, 0.00556, 0.00475, 0.00394, 0.00313, 0.00234, 0.000746, -0.00105, -0.00325, -0.00609, 0.0106, 0.00897, 0.00743, 0.00582, 0.00499, 0.00416, 0.00333, 0.00252, 0.000877, -0.000963, -0.00322, -0.00614, 0.0108, 0.00919, 0.00762, 0.00599, 0.00514, 0.0043, 0.00345, 0.00263, 0.000961, -0.00091, -0.00321, -0.00618, 0.0102, 0.00862, 0.00712, 0.00556, 0.00475, 0.00394, 0.00313, 0.00234, 0.000744, -0.00105, -0.00325, -0.00609, 0.0105, 0.00896, 0.00742, 0.00582, 0.00498, 0.00415, 0.00332, 0.00251, 0.000874, -0.000965, -0.00322, -0.00614, 0.0108, 0.00918, 0.00761, 0.00598, 0.00513, 0.00429, 0.00345, 0.00262, 0.000957, -0.000913, -0.00321, -0.00618, 0.00452, 0.00368, 0.00286, 0.00201, 0.00157, 0.00112, 0.000683, 0.000252, -0.000618, -0.0016, -0.0028, -0.00435, 0.00468, 0.00381, 0.00297, 0.0021, 0.00164, 0.00119, 0.000734, 0.000291, -0.000602, -0.00161, -0.00284, -0.00443, 0.00477, 0.0039, 0.00304, 0.00215, 0.00169, 0.00123, 0.000767, 0.000317, -0.000591, -0.00161, -0.00286, -0.00449, 0.00452, 0.00368, 0.00286, 0.00201, 0.00156, 0.00112, 0.000682, 0.000251, -0.000619, -0.0016, -0.00279, -0.00435, 0.00467, 0.00381, 0.00297, 0.00209, 0.00164, 0.00119, 0.000733, 0.000291, -0.000603, -0.00161, -0.00284, -0.00443, 0.00477, 0.00389, 0.00304, 0.00215, 0.00169, 0.00123, 0.000766, 0.000316, -0.000592, -0.00161, -0.00286, -0.00448, 0.00451, 0.00368, 0.00286, 0.00201, 0.00156, 0.00112, 0.000681, 0.00025, -0.000619, -0.0016, -0.00279, -0.00435, 0.00467, 0.00381, 0.00297, 0.00209, 0.00164, 0.00119, 0.000732, 0.00029, -0.000603, -0.00161, -0.00284, -0.00443, 0.00477, 0.00389, 0.00304, 0.00215, 0.00168, 0.00123, 0.000765, 0.000315, -0.000592, -0.00161, -0.00286, -0.00448, -4.11E-6, -3.06E-6, -2.04E-6, -9.72E-7, -4.17E-7, 1.33E-7, 6.86E-7, 1.22E-6, 2.31E-6, 3.53E-6, 5.03E-6, 6.97E-6, -4.22E-6, -3.14E-6, -2.09E-6, -9.98E-7, -4.28E-7, 1.37E-7, 7.05E-7, 1.26E-6, 2.37E-6, 3.63E-6, 5.17E-6, 7.16E-6, -4.29E-6, -3.2E-6, -2.13E-6, -1.01E-6, -4.35E-7, 1.39E-7, 7.16E-7, 1.28E-6, 2.41E-6, 3.69E-6, 5.26E-6, 7.28E-6, -4.11E-6, -3.06E-6, -2.04E-6, -9.71E-7, -4.17E-7, 1.33E-7, 6.85E-7, 1.22E-6, 2.31E-6, 3.53E-6, 5.03E-6, 6.97E-6, -4.22E-6, -3.14E-6, -2.09E-6, -9.98E-7, -4.28E-7, 1.37E-7, 7.04E-7, 1.26E-6, 2.37E-6, 3.63E-6, 5.17E-6, 7.16E-6, -4.29E-6, -3.19E-6, -2.13E-6, -1.01E-6, -4.35E-7, 1.39E-7, 7.15E-7, 1.28E-6, 2.41E-6, 3.69E-6, 5.25E-6, 7.28E-6, -4.11E-6, -3.06E-6, -2.04E-6, -9.71E-7, -4.17E-7, 1.33E-7, 6.85E-7, 1.22E-6, 2.31E-6, 3.53E-6, 5.03E-6, 6.96E-6, -4.22E-6, -3.14E-6, -2.09E-6, -9.97E-7, -4.28E-7, 1.37E-7, 7.04E-7, 1.26E-6, 2.37E-6, 3.63E-6, 5.16E-6, 7.16E-6, -4.29E-6, -3.19E-6, -2.13E-6, -1.01E-6, -4.35E-7, 1.39E-7, 7.15E-7, 1.28E-6, 2.41E-6, 3.69E-6, 5.25E-6, 7.28E-6, -0.00206, -0.00122, -0.000402, 0.000451, 0.000895, 0.00134, 0.00178, 0.00221, 0.00308, 0.00406, 0.00526, 0.00681, -0.00208, -0.00122, -0.00038, 0.000496, 0.000952, 0.0014, 0.00186, 0.0023, 0.00319, 0.0042, 0.00543, 0.00702, -0.0021, -0.00122, -0.000366, 0.000525, 0.000988, 0.00145, 0.00191, 0.00236, 0.00327, 0.00429, 0.00554, 0.00716, -0.00206, -0.00122, -0.000403, 0.00045, 0.000894, 0.00133, 0.00178, 0.00221, 0.00308, 0.00405, 0.00525, 0.0068, -0.00208, -0.00122, -0.000381, 0.000495, 0.000951, 0.0014, 0.00186, 0.0023, 0.00319, 0.0042, 0.00543, 0.00702, -0.0021, -0.00122, -0.000366, 0.000524, 0.000987, 0.00145, 0.00191, 0.00236, 0.00326, 0.00428, 0.00554, 0.00716, -0.00206, -0.00122, -0.000403, 0.000449, 0.000893, 0.00133, 0.00177, 0.0022, 0.00307, 0.00405, 0.00525, 0.0068, -0.00208, -0.00122, -0.000381, 0.000494, 0.00095, 0.0014, 0.00185, 0.0023, 0.00319, 0.00419, 0.00542, 0.00702, -0.0021, -0.00122, -0.000367, 0.000523, 0.000985, 0.00144, 0.00191, 0.00235, 0.00326, 0.00428, 0.00553, 0.00715, -0.0019, -0.000356, 0.00114, 0.00271, 0.00352, 0.00433, 0.00514, 0.00593, 0.00753, 0.00932, 0.0115, 0.0144, -0.00184, -0.000255, 0.00129, 0.00289, 0.00373, 0.00456, 0.00539, 0.00621, 0.00784, 0.00969, 0.0119, 0.0149, -0.0018, -0.00019, 0.00138, 0.00301, 0.00386, 0.0047, 0.00555, 0.00638, 0.00804, 0.00991, 0.0122, 0.0152, -0.0019, -0.000358, 0.00114, 0.00271, 0.00352, 0.00433, 0.00514, 0.00593, 0.00752, 0.00932, 0.0115, 0.0144, -0.00184, -0.000257, 0.00128, 0.00289, 0.00373, 0.00456, 0.00539, 0.0062, 0.00784, 0.00968, 0.0119, 0.0149, -0.0018, -0.000193, 0.00137, 0.00301, 0.00386, 0.0047, 0.00554, 0.00637, 0.00804, 0.00991, 0.0122, 0.0152, -0.0019, -0.00036, 0.00114, 0.0027, 0.00352, 0.00432, 0.00513, 0.00592, 0.00752, 0.00931, 0.0115, 0.0144, -0.00184, -0.00026, 0.00128, 0.00289, 0.00372, 0.00455, 0.00538, 0.00619, 0.00783, 0.00967, 0.0119, 0.0148, -0.0018, -0.000195, 0.00137, 0.003, 0.00385, 0.00469, 0.00554, 0.00636, 0.00803, 0.0099, 0.0122, 0.0152, -0.00173, -8.48E-5, 0.00152, 0.00319, 0.00406, 0.00492, 0.00578, 0.00663, 0.00833, 0.0102, 0.0126, 0.0156, -0.00165, 3.9E-5, 0.00168, 0.0034, 0.00429, 0.00518, 0.00607, 0.00693, 0.00868, 0.0106, 0.0131, 0.0162, -0.0016, 0.000118, 0.00179, 0.00353, 0.00444, 0.00534, 0.00624, 0.00712, 0.0089, 0.0109, 0.0133, 0.0165, -0.00173, -8.74E-5, 0.00151, 0.00318, 0.00405, 0.00491, 0.00578, 0.00662, 0.00832, 0.0102, 0.0126, 0.0156, -0.00165, 3.63E-5, 0.00168, 0.00339, 0.00429, 0.00517, 0.00606, 0.00693, 0.00867, 0.0106, 0.013, 0.0162, -0.0016, 0.000115, 0.00179, 0.00353, 0.00443, 0.00533, 0.00624, 0.00712, 0.00889, 0.0109, 0.0133, 0.0165, -0.00173, -8.93E-5, 0.00151, 0.00318, 0.00405, 0.00491, 0.00577, 0.00662, 0.00832, 0.0102, 0.0126, 0.0156, -0.00165, 3.33E-5, 0.00168, 0.00339, 0.00428, 0.00517, 0.00605, 0.00692, 0.00867, 0.0106, 0.013, 0.0162, -0.0016, 0.000112, 0.00178, 0.00352, 0.00443, 0.00533, 0.00623, 0.00711, 0.00889, 0.0109, 0.0133, 0.0165 }, 0.0, { -0.095, -0.089, -0.049, 0.0, 0.049, 0.089, 0.095, -0.098, -0.092, -0.05, 0.0, 0.05, 0.092, 0.098, -0.099, -0.093, -0.051, 0.0, 0.051, 0.093, 0.099, -0.095, -0.089, -0.049, 0.0, 0.049, 0.089, 0.095, -0.098, -0.092, -0.05, 0.0, 0.05, 0.092, 0.098, -0.099, -0.093, -0.051, 0.0, 0.051, 0.093, 0.099, -0.095, -0.089, -0.049, 0.0, 0.049, 0.089, 0.095, -0.098, -0.092, -0.05, 0.0, 0.05, 0.092, 0.098, -0.099, -0.093, -0.051, 0.0, 0.051, 0.093, 0.099 }, { 0.2447, 0.227, 0.1236, -0.0002, -0.1236, -0.227, -0.2447, 0.2507, 0.2326, 0.1267, -0.0002, -0.1267, -0.2326, -0.2507, 0.2537, 0.2354, 0.1282, -0.0002, -0.1282, -0.2354, -0.2537, 0.2415, 0.224, 0.122, -0.0002, -0.122, -0.224, -0.2415, 0.2428, 0.2252, 0.1226, -0.0002, -0.1226, -0.2252, -0.2428, 0.2361, 0.2189, 0.1192, -0.0001, -0.1192, -0.2189, -0.2361, 0.2121, 0.1965, 0.107, -0.0001, -0.107, -0.1965, -0.2122, 0.1989, 0.1845, 0.1005, -0.0001, -0.1005, -0.1845, -0.1989, 0.1816, 0.1687, 0.0919, -0.0001, -0.0919, -0.1687, -0.1816 }, 0.0, -1.0, { -16.0, -8.0, 0.0, 8.0, 16.0 }, { 0.0917, 0.0486, -0.0001, -0.0486, -0.0917, 0.0941, 0.0499, -0.0001, -0.0499, -0.0941, 0.0941, 0.0499, -0.0001, -0.0499, -0.0941, 0.0917, 0.0486, -0.0001, -0.0486, -0.0917, 0.0941, 0.0499, -0.0001, -0.0499, -0.0941, 0.0941, 0.0499, -0.0001, -0.0499, -0.0941, 0.0917, 0.0486, -0.0001, -0.0486, -0.0917, 0.0941, 0.0499, -0.0001, -0.0499, -0.0941, 0.0941, 0.0499, -0.0001, -0.0499, -0.0941 }, { 1.0, 1.0, 1.0 }, 0.0, { -16.0, -12.0, -8.0, -4.0, -2.0, 0.0, 2.0, 4.0, 8.0, 12.0, 16.0, 20.0 }, { 0.02, 0.04, 0.06 }, { 10.0, 50.0, 100.0 }, { 0.119, 0.071, 0.044, 0.032, 0.031, 0.034, 0.04, 0.051, 0.087, 0.136, 0.177, 0.18, 0.114, 0.067, 0.04, 0.028, 0.028, 0.03, 0.037, 0.048, 0.084, 0.132, 0.173, 0.175, 0.112, 0.065, 0.039, 0.027, 0.026, 0.029, 0.035, 0.046, 0.082, 0.13, 0.171, 0.173, 0.119, 0.071, 0.044, 0.032, 0.031, 0.034, 0.04, 0.051, 0.087, 0.136, 0.177, 0.18, 0.114, 0.067, 0.04, 0.028, 0.028, 0.03, 0.037, 0.048, 0.084, 0.132, 0.173, 0.175, 0.112, 0.065, 0.039, 0.027, 0.026, 0.029, 0.035, 0.046, 0.082, 0.13, 0.171, 0.173, 0.119, 0.071, 0.044, 0.032, 0.031, 0.034, 0.04, 0.051, 0.087, 0.136, 0.177, 0.18, 0.114, 0.067, 0.041, 0.028, 0.028, 0.03, 0.037, 0.048, 0.084, 0.132, 0.173, 0.175, 0.112, 0.065, 0.039, 0.027, 0.026, 0.029, 0.035, 0.046, 0.082, 0.13, 0.171, 0.173 }, 0.0, { -1.4, -0.939, -0.507, -0.098, 0.098, 0.304, 0.519, 0.742, 1.205, 1.629, 1.904, 1.867, -1.401, -0.939, -0.508, -0.098, 0.098, 0.304, 0.519, 0.742, 1.205, 1.629, 1.904, 1.868, -1.403, -0.94, -0.508, -0.098, 0.098, 0.304, 0.519, 0.742, 1.205, 1.63, 1.904, 1.868, -1.4, -0.939, -0.507, -0.098, 0.098, 0.304, 0.519, 0.742, 1.205, 1.629, 1.904, 1.867, -1.401, -0.939, -0.508, -0.098, 0.098, 0.304, 0.519, 0.742, 1.205, 1.629, 1.904, 1.868, -1.403, -0.94, -0.508, -0.098, 0.098, 0.304, 0.519, 0.742, 1.205, 1.63, 1.904, 1.868, -1.4, -0.939, -0.507, -0.098, 0.098, 0.304, 0.519, 0.742, 1.205, 1.629, 1.904, 1.867, -1.401, -0.939, -0.508, -0.098, 0.098, 0.304, 0.519, 0.742, 1.205, 1.629, 1.904, 1.868, -1.403, -0.94, -0.508, -0.098, 0.098, 0.304, 0.519, 0.742, 1.205, 1.63, 1.904, 1.868 }, -1.0, { -1.0, -1.0, -1.0 }, { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }, { -0.041, -0.015, -0.003, 0.409, -0.713, -0.327, -0.254, -0.225, -0.207, -0.218, -0.252, -0.252, -0.042, -0.016, -0.005, 0.417, -0.719, -0.329, -0.255, -0.226, -0.208, -0.218, -0.252, -0.252, -0.043, -0.016, -0.006, 0.42, -0.721, -0.33, -0.256, -0.227, -0.208, -0.218, -0.253, -0.253, -0.041, -0.015, -0.003, 0.409, -0.713, -0.327, -0.254, -0.225, -0.207, -0.218, -0.252, -0.252, -0.042, -0.016, -0.005, 0.417, -0.719, -0.329, -0.255, -0.226, -0.208, -0.218, -0.252, -0.252, -0.043, -0.016, -0.006, 0.42, -0.721, -0.33, -0.256, -0.227, -0.208, -0.218, -0.253, -0.253, -0.041, -0.015, -0.003, 0.409, -0.713, -0.327, -0.254, -0.225, -0.207, -0.218, -0.252, -0.252, -0.042, -0.016, -0.005, 0.417, -0.719, -0.329, -0.255, -0.226, -0.208, -0.218, -0.252, -0.252, -0.043, -0.016, -0.006, 0.42, -0.721, -0.33, -0.256, -0.227, -0.208, -0.218, -0.253, -0.253 }, 0.3, 0.0, 0.0, 0.0, { 0.0, 0.0, 0.0 }, { 0.001061, 0.0005229, 1.036E-6, -0.0004811, -0.0007087, -0.0009486, -0.001201, -0.001463, -0.00201, -0.002506, -0.002804, -0.002691, 0.00106, 0.0005219, 1.772E-7, -0.0004819, -0.0007094, -0.0009492, -0.001201, -0.001464, -0.002011, -0.002507, -0.002805, -0.002694, 0.00106, 0.0005217, -2.813E-7, -0.0004826, -0.0007103, -0.0009502, -0.001202, -0.001465, -0.002012, -0.002508, -0.002806, -0.002694, 0.001061, 0.0005229, 1.035E-6, -0.0004811, -0.0007087, -0.0009486, -0.001201, -0.001463, -0.00201, -0.002506, -0.002804, -0.002691, 0.00106, 0.0005219, 1.769E-7, -0.0004819, -0.0007094, -0.0009492, -0.001201, -0.001464, -0.002011, -0.002507, -0.002805, -0.002694, 0.00106, 0.0005217, -2.817E-7, -0.0004826, -0.0007103, -0.0009502, -0.001202, -0.001465, -0.002012, -0.002508, -0.002806, -0.002694, 0.001061, 0.0005229, 1.035E-6, -0.0004811, -0.0007087, -0.0009486, -0.001201, -0.001463, -0.00201, -0.002506, -0.002804, -0.002691, 0.00106, 0.0005219, 1.764E-7, -0.0004819, -0.0007094, -0.0009492, -0.001201, -0.001464, -0.002011, -0.002507, -0.002805, -0.002694, 0.00106, 0.0005217, -2.821E-7, -0.0004826, -0.0007103, -0.0009502, -0.001202, -0.001465, -0.002012, -0.002508, -0.002806, -0.002694 }, { 0.056, 0.0136, 0.0017, -0.0409, -0.0691, -0.0995, -0.1323, -0.1678, -0.2501, -0.3532, -0.4743, -0.4743, 0.0577, 0.0146, 0.0027, -0.0415, -0.0697, -0.1001, -0.1328, -0.1683, -0.2505, -0.3534, -0.474, -0.474, 0.0589, 0.0153, 0.0033, -0.0418, -0.07, -0.1004, -0.1331, -0.1686, -0.2508, -0.3537, -0.4742, -0.4742, 0.0559, 0.0136, 0.0017, -0.0409, -0.0691, -0.0995, -0.1323, -0.1678, -0.25, -0.3532, -0.4743, -0.4743, 0.0577, 0.0146, 0.0027, -0.0415, -0.0697, -0.1001, -0.1328, -0.1683, -0.2505, -0.3534, -0.474, -0.474, 0.0588, 0.0153, 0.0033, -0.0418, -0.07, -0.1004, -0.1331, -0.1686, -0.2508, -0.3537, -0.4742, -0.4742, 0.0559, 0.0136, 0.0017, -0.0409, -0.0691, -0.0995, -0.1323, -0.1677, -0.25, -0.3532, -0.4743, -0.4743, 0.0577, 0.0146, 0.0027, -0.0415, -0.0697, -0.1001, -0.1328, -0.1683, -0.2505, -0.3534, -0.474, -0.474, 0.0588, 0.0153, 0.0033, -0.0418, -0.07, -0.1004, -0.1331, -0.1686, -0.2508, -0.3537, -0.4742, -0.4742 }, { 0.001603, 0.001603, 0.001603, 0.001603, 0.001603, 0.001603, 0.001603, 0.001603, 0.001603, 0.001603, 0.001603, 0.001603, 0.001787, 0.001787, 0.001787, 0.001787, 0.001787, 0.001787, 0.001787, 0.001787, 0.001787, 0.001787, 0.001787, 0.001787, 0.001895, 0.001895, 0.001895, 0.001895, 0.001895, 0.001895, 0.001895, 0.001895, 0.001895, 0.001895, 0.001895, 0.001895, 0.001602, 0.001602, 0.001602, 0.001602, 0.001602, 0.001602, 0.001602, 0.001602, 0.001602, 0.001602, 0.001602, 0.001602, 0.001786, 0.001786, 0.001786, 0.001786, 0.001786, 0.001786, 0.001786, 0.001786, 0.001786, 0.001786, 0.001786, 0.001786, 0.001894, 0.001894, 0.001894, 0.001894, 0.001894, 0.001894, 0.001894, 0.001894, 0.001894, 0.001894, 0.001894, 0.001894, 0.0016, 0.0016, 0.0016, 0.0016, 0.0016, 0.0016, 0.0016, 0.0016, 0.0016, 0.0016, 0.0016, 0.0016, 0.001785, 0.001785, 0.001785, 0.001785, 0.001785, 0.001785, 0.001785, 0.001785, 0.001785, 0.001785, 0.001785, 0.001785, 0.001893, 0.001893, 0.001893, 0.001893, 0.001893, 0.001893, 0.001893, 0.001893, 0.001893, 0.001893, 0.001893, 0.001893 }, -1.0, { 1U, 9U, 27U }, { 1U, 12U, 108U, 324U }, { 1U, 12U, 36U, 108U }, { 1U, 7U, 21U }, { 1U, 7U, 21U }, { 1U, 5U, 15U }, { 1U, 12U, 36U }, { 1U, 12U, 36U }, { 1U, 12U, 36U }, { 1U, 12U, 36U }, { 1U, 12U, 36U }, { 1U, 12U, 36U } };
55.624254
81
0.584367
[ "model" ]
0a41fa4098c126c90064218ba0c4a9268dd83a7d
3,967
hpp
C++
include/engine/plugins/nearest.hpp
mortada/osrm-backend
aae02cd1be7e99eb75117c7d8c9f39b858ad9019
[ "BSD-2-Clause" ]
null
null
null
include/engine/plugins/nearest.hpp
mortada/osrm-backend
aae02cd1be7e99eb75117c7d8c9f39b858ad9019
[ "BSD-2-Clause" ]
null
null
null
include/engine/plugins/nearest.hpp
mortada/osrm-backend
aae02cd1be7e99eb75117c7d8c9f39b858ad9019
[ "BSD-2-Clause" ]
1
2019-09-20T00:55:14.000Z
2019-09-20T00:55:14.000Z
#ifndef NEAREST_HPP #define NEAREST_HPP #include "engine/plugins/plugin_base.hpp" #include "engine/phantom_node.hpp" #include "util/integer_range.hpp" #include "osrm/json_container.hpp" #include <string> namespace osrm { namespace engine { namespace plugins { /* * This Plugin locates the nearest point on a street in the road network for a given coordinate. */ template <class DataFacadeT> class NearestPlugin final : public BasePlugin { public: explicit NearestPlugin(DataFacadeT *facade) : facade(facade), descriptor_string("nearest") {} const std::string GetDescriptor() const override final { return descriptor_string; } Status HandleRequest(const RouteParameters &route_parameters, util::json::Object &json_result) override final { // check number of parameters if (route_parameters.coordinates.empty() || !route_parameters.coordinates.front().IsValid()) { return Status::Error; } const auto &input_bearings = route_parameters.bearings; if (input_bearings.size() > 0 && route_parameters.coordinates.size() != input_bearings.size()) { json_result.values["status_message"] = "Number of bearings does not match number of coordinates"; return Status::Error; } auto number_of_results = static_cast<std::size_t>(route_parameters.num_results); const int bearing = input_bearings.size() > 0 ? input_bearings.front().first : 0; const int range = input_bearings.size() > 0 ? (input_bearings.front().second ? *input_bearings.front().second : 10) : 180; auto phantom_node_vector = facade->NearestPhantomNodes(route_parameters.coordinates.front(), number_of_results, bearing, range); if (phantom_node_vector.empty()) { json_result.values["status_message"] = std::string("Could not find a matching segments for coordinate"); return Status::NoSegment; } else { json_result.values["status_message"] = "Found nearest edge"; if (number_of_results > 1) { util::json::Array results; auto vector_length = phantom_node_vector.size(); for (const auto i : util::irange<std::size_t>(0, std::min(number_of_results, vector_length))) { const auto &node = phantom_node_vector[i].phantom_node; util::json::Array json_coordinate; util::json::Object result; json_coordinate.values.push_back(node.location.lat / COORDINATE_PRECISION); json_coordinate.values.push_back(node.location.lon / COORDINATE_PRECISION); result.values["mapped coordinate"] = json_coordinate; result.values["name"] = facade->get_name_for_id(node.name_id); results.values.push_back(result); } json_result.values["results"] = results; } else { util::json::Array json_coordinate; json_coordinate.values.push_back( phantom_node_vector.front().phantom_node.location.lat / COORDINATE_PRECISION); json_coordinate.values.push_back( phantom_node_vector.front().phantom_node.location.lon / COORDINATE_PRECISION); json_result.values["mapped_coordinate"] = json_coordinate; json_result.values["name"] = facade->get_name_for_id(phantom_node_vector.front().phantom_node.name_id); } } return Status::Ok; } private: DataFacadeT *facade; std::string descriptor_string; }; } } } #endif /* NEAREST_HPP */
36.731481
100
0.599445
[ "object" ]
0a4a26d7da3e6c7347cf20c617dda6d0cc2066df
9,147
cpp
C++
test/graph_visualisation_test.cpp
lsscecilia/GraphVisualisation
7490062ac0596835620e2026a756b6be8f0667e7
[ "MIT" ]
3
2021-03-29T09:15:39.000Z
2021-06-03T18:51:51.000Z
test/graph_visualisation_test.cpp
lsscecilia/GraphVisualisation
7490062ac0596835620e2026a756b6be8f0667e7
[ "MIT" ]
null
null
null
test/graph_visualisation_test.cpp
lsscecilia/GraphVisualisation
7490062ac0596835620e2026a756b6be8f0667e7
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include <memory.h> #include "../src/algorithm.cpp" TEST (MathVectorTest, equalOperator){ MathVector mv; mv = 10; EXPECT_EQ(10, mv.x); EXPECT_EQ(10, mv.y); } TEST (MathVectorTest, equalOperatorWhenAssigned){ MathVector mv(10,10); mv = 100; EXPECT_EQ(100, mv.x); EXPECT_EQ(100, mv.y); } TEST (MathVectorTest, additionOperator){ MathVector mv1(1,2); MathVector mv2(3,4); MathVector mv = mv1 + mv2; EXPECT_EQ(4, mv.x); EXPECT_EQ(6, mv.y); } TEST (MathVectorTest, minusOperator){ MathVector mv1(1,2); MathVector mv2(3,2); MathVector mv = mv1 - mv2; EXPECT_EQ(-2, mv.x); EXPECT_EQ(0, mv.y); } TEST (MathVectorTest, multiplyOperator){ MathVector mv1(1,2); MathVector mv2(3,4); MathVector mv = mv1 * mv2; EXPECT_EQ(3, mv.x); EXPECT_EQ(8, mv.y); } TEST (MathVectorTest, multiplyByDouble){ MathVector mv1(1,2); MathVector mv = mv1*5; EXPECT_EQ(5, mv.x); EXPECT_EQ(10,mv.y); } TEST (MathVectorTest, divisionOperator){ MathVector mv1(1,2); MathVector mv2(3,4); MathVector mv = mv1/mv2; EXPECT_EQ((double)1/3, mv.x); EXPECT_EQ(0.5,mv.y); } TEST (MathVectorTest, divideByDouble){ MathVector mv1(6,2); MathVector mv = mv1/2; EXPECT_EQ(3, mv.x); EXPECT_EQ(1,mv.y); } TEST (MathVectorTest, plusEqualOperator){ MathVector mv1(1,2); MathVector mv2(3,4); mv1 += mv2; EXPECT_EQ(4, mv1.x); EXPECT_EQ(6, mv1.y); } TEST (MathVectorTest, minusEqualOperator){ MathVector mv1(1,2); MathVector mv2(3,4); mv1 -= mv2; EXPECT_EQ(-2, mv1.x); EXPECT_EQ(-2, mv1.y); } TEST (MathVectorTest, multiplyEqualDouble){ MathVector mv1(1,2); mv1 *= 3.0; EXPECT_EQ(3, mv1.x); EXPECT_EQ(6, mv1.y); } TEST (MathVectorTest, divideEqualDouble){ MathVector mv1(1,2); mv1 /= 0.5; EXPECT_EQ(2, mv1.x); EXPECT_EQ(4, mv1.y); } TEST (MathVectorTest, abs){ MathVector mv1(1,2); double abs = mv1.abs(); EXPECT_EQ(sqrt(5), abs); } TEST (MathVectorTest, min){ MathVector mv1(10,2); MathVector mv = mv1.min(5); EXPECT_EQ(5, mv.x); EXPECT_EQ(2, mv.y); } TEST (Tree, generateTree){ vector<Vertex> vertices; vertices.push_back({{1,1},{0,0}}); vertices.push_back({{2,2},{0,0}}); vertices.push_back({{4,3},{0,0}}); vertices.push_back({{5,5},{0,0}}); shared_ptr<Node> tree = make_shared<Node>(); vector<shared_ptr<Vertex>> spVertices; for (int i=0;i<vertices.size();i++){ spVertices.push_back(make_shared<Vertex>(vertices[i])); } generateTree(spVertices, 8,8, tree ,false); EXPECT_EQ(false, tree->noParticles()); EXPECT_EQ(5, tree->third->n->pos.x); EXPECT_EQ(5, tree->third->n->pos.y); EXPECT_EQ(4, tree->first->third->n->pos.x); EXPECT_EQ(3, tree->first->third->n->pos.y); EXPECT_EQ(2, tree->first->first->third->n->pos.x); EXPECT_EQ(2, tree->first->first->third->n->pos.y); EXPECT_EQ(1, tree->first->first->first->n->pos.x); EXPECT_EQ(1, tree->first->first->first->n->pos.y); } TEST (Tree, generateTree2){ vector<Vertex> vertices; vertices.push_back({{1.51738,5.26204},{0,0}}); vertices.push_back({{3.07885,3.23085},{0,0}}); vertices.push_back({{4.01661,3.44349},{0,0}}); vertices.push_back({{0.0584325,0.287978},{0,0}}); vertices.push_back({{5.48902,6.29487},{0,0}}); vertices.push_back({{1.56064,8.20051},{0,0}}); vertices.push_back({{7.59669,1.91242},{0,0}}); vertices.push_back({{7.75213,1.2933},{0,0}}); vector<shared_ptr<Vertex>> spVertices; for (int i=0;i<vertices.size();i++){ spVertices.push_back(make_shared<Vertex>(vertices[i])); } shared_ptr<Node> tree = make_shared<Node>(); generateTree(spVertices, 10,10, tree, false); EXPECT_EQ(false, tree->noParticles()); EXPECT_EQ(0.0584325,tree->first->first->n->pos.x); EXPECT_EQ(0.287978,tree->first->first->n->pos.y); EXPECT_EQ(3.07885, tree->first->third->first->n->pos.x); EXPECT_EQ(3.23085, tree->first->third->first->n->pos.y); EXPECT_EQ(4.01661, tree->first->third->second->n->pos.x); EXPECT_EQ(3.44349, tree->first->third->second->n->pos.y); EXPECT_EQ(7.75213,tree->second->second->fourth->first->n->pos.x); EXPECT_EQ(1.2933,tree->second->second->fourth->first->n->pos.y); EXPECT_EQ(7.59669,tree->second->second->fourth->fourth->n->pos.x); EXPECT_EQ(1.91242,tree->second->second->fourth->fourth->n->pos.y); EXPECT_EQ(5.48902, tree->third->n->pos.x); EXPECT_EQ(6.29487, tree->third->n->pos.y); EXPECT_EQ(1.51738, tree->fourth->first->n->pos.x); EXPECT_EQ(5.26204, tree->fourth->first->n->pos.y); EXPECT_EQ(1.56064, tree->fourth->fourth->n->pos.x); EXPECT_EQ(8.20051, tree->fourth->fourth->n->pos.y); } TEST (Tree, mass){ //better to mock values vector<Vertex> vertices; vertices.push_back({{1,1},{0,0}}); vertices.push_back({{2,2},{0,0}}); vertices.push_back({{4,3},{0,0}}); vertices.push_back({{5,5},{0,0}}); shared_ptr<Node> tree = make_shared<Node>(); vector<shared_ptr<Vertex>> spVertices; for (int i=0;i<vertices.size();i++){ spVertices.push_back(make_shared<Vertex>(vertices[i])); } generateTree(spVertices, 8,8, tree, false); computeMassDistribution(tree); EXPECT_EQ(4 , tree->mass); EXPECT_EQ(3, tree->first->mass); EXPECT_EQ(2, tree->first->first->mass); EXPECT_EQ(1, tree->first->first->first->mass); EXPECT_EQ(1, tree->first->first->third->mass); EXPECT_EQ(1, tree->first->third->mass); EXPECT_EQ(1, tree->third->mass); } TEST (Tree, centreOfMass){ //better to mock values vector<Vertex> vertices; vertices.push_back({{1,1},{0,0}}); vertices.push_back({{2,2},{0,0}}); vertices.push_back({{4,3},{0,0}}); vertices.push_back({{5,5},{0,0}}); shared_ptr<Node> tree = make_shared<Node>(); vector<shared_ptr<Vertex>> spVertices; for (int i=0;i<vertices.size();i++){ spVertices.push_back(make_shared<Vertex>(vertices[i])); } generateTree(spVertices, 8,8, tree, false); computeMassDistribution(tree); EXPECT_EQ(1.5,tree->first->first->centreOfMass.x); EXPECT_EQ(1.5,tree->first->first->centreOfMass.y); EXPECT_EQ(5.5/3, tree->first->centreOfMass.x); EXPECT_EQ(1.5, tree->first->centreOfMass.y); EXPECT_EQ((5.5/3 + 5)/4, tree->centreOfMass.x); EXPECT_EQ(1.625, tree->centreOfMass.y); EXPECT_EQ(1,tree->first->first->first->centreOfMass.x); EXPECT_EQ(1,tree->first->first->first->centreOfMass.y); } TEST (ErrorTree, generateTree){ vector<Vertex> vertices; vertices.push_back({{3.44718,1.40869},{0,0}}); vertices.push_back({{7.318,1.19414},{0,0}}); vertices.push_back({{9.54089,0.993429},{0,0}}); vertices.push_back({{9.45409,5.05656},{0,0}}); vertices.push_back({{0.326581,1.17779},{0,0}}); vertices.push_back({{7.55364,1.90332},{0,0}}); shared_ptr<Node> tree = make_shared<Node>(); vector<shared_ptr<Vertex>> spVertices; for (int i=0;i<vertices.size();i++){ spVertices.push_back(make_shared<Vertex>(vertices[i])); } generateTree(spVertices, 10,10, tree, false); EXPECT_EQ(false, tree->noParticles()); EXPECT_EQ(9.45409, tree->third->n->pos.x); EXPECT_EQ(5.05656, tree->third->n->pos.y); EXPECT_EQ(0.326581, tree->first->first->n->pos.x); EXPECT_EQ(1.17779, tree->first->first->n->pos.y); EXPECT_EQ(3.44718, tree->first->second->n->pos.x); EXPECT_EQ(1.40869, tree->first->second->n->pos.y); EXPECT_EQ(7.318, tree->second->first->n->pos.x); EXPECT_EQ(1.19414, tree->second->first->n->pos.y); EXPECT_EQ(9.54089, tree->second->second->second->n->pos.x); EXPECT_EQ(0.993429, tree->second->second->second->n->pos.y); EXPECT_EQ(7.55364, tree->second->second->fourth->n->pos.x); EXPECT_EQ(1.90332, tree->second->second->fourth->n->pos.y); //check all the nullptr EXPECT_EQ(nullptr, tree->n); EXPECT_EQ(nullptr, tree->fourth); EXPECT_EQ(nullptr, tree->first->n); EXPECT_EQ(nullptr, tree->first->third); EXPECT_EQ(nullptr, tree->first->fourth); EXPECT_EQ(nullptr, tree->second->n); EXPECT_EQ(nullptr, tree->second->third); EXPECT_EQ(nullptr, tree->second->fourth); EXPECT_EQ(nullptr, tree->second->second->n); EXPECT_EQ(nullptr, tree->second->second->first); EXPECT_EQ(nullptr, tree->second->second->third); } TEST (ErrorTree, mass){ vector<Vertex> vertices; vertices.push_back({{3.44718,1.40869},{0,0}}); vertices.push_back({{7.318,1.19414},{0,0}}); vertices.push_back({{9.54089,0.993429},{0,0}}); vertices.push_back({{9.45409,5.05656},{0,0}}); vertices.push_back({{0.326581,1.17779},{0,0}}); vertices.push_back({{7.55364,1.90332},{0,0}}); shared_ptr<Node> tree = make_shared<Node>(); vector<shared_ptr<Vertex>> spVertices; for (int i=0;i<vertices.size();i++){ spVertices.push_back(make_shared<Vertex>(vertices[i])); } generateTree(spVertices, 10,10, tree, false); //mass computeMassDistribution(tree); //leaf EXPECT_EQ(1, tree->first->first->mass); EXPECT_EQ(1, tree->first->second->mass); EXPECT_EQ(1, tree->second->first->mass); EXPECT_EQ(1, tree->second->second->second->mass); EXPECT_EQ(1, tree->second->second->fourth->mass); EXPECT_EQ(1, tree->third->mass); EXPECT_EQ(3 , tree->second->mass); EXPECT_EQ(2, tree->first->mass); EXPECT_EQ(6, tree->mass); } int main(int argc, char** argv){ ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
27.972477
68
0.66776
[ "vector" ]
aecf51aec06ece5a62c66ba7ebf9787ed5ade79a
1,025
cpp
C++
CODEFORCES/246/test.cpp
henviso/contests
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
[ "Apache-2.0" ]
null
null
null
CODEFORCES/246/test.cpp
henviso/contests
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
[ "Apache-2.0" ]
null
null
null
CODEFORCES/246/test.cpp
henviso/contests
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string> #include <algorithm> #include <vector> #include <bitset> #include <cstring> #define CLEAR(v, x) memset(v, x, sizeof(v)) #define REP(i,n) for(int i = 0; i<n; i++) #define REPP(i,a,n) for(int i = a; i<n; i++) using namespace std; int A[1100][1100]; int B[1100][1100]; class PairGame { public: void btA(int x, int y){ A[x][y] = 1; //cout << " A " << x << " " << y << endl; if(y-x > 0 && A[x][y-x] == -1) btA(x, y-x); if(x-y > 0 && A[x-y][y] == -1) btA(x-y, y); } void btB(int x, int y){ B[x][y] = 1; //cout << " B " << x << " " << y << endl; if(y-x > 0 && B[x][y-x] == -1) btB(x, y-x); if(x-y > 0 && B[x-y][y] == -1) btB(x-y, y); } int maxSum(int a, int b, int c, int d) { REP(i, 1100) REP(j, 1100) A[i][j] = B[i][j] = -1; btA(a, b); btB(c, d); int ans = -1; REP(i, 1001) REP(j, 1001){ if(A[i][j] == 1 && B[i][j] == 1) ans = max(ans, i+j); } return ans; } }; int main(){ PairGame p; cout << p.maxSum(1000, 1001, 2000, 2001) << endl; }
20.5
56
0.487805
[ "vector" ]
aed0a426df39cfd0e408903fc545af87ac9edcf6
1,107
cpp
C++
first_missing_positive.cpp
zhoujqia/leetcode
5e620a22d34762af329d5d7df1e8688949353fa1
[ "MIT" ]
null
null
null
first_missing_positive.cpp
zhoujqia/leetcode
5e620a22d34762af329d5d7df1e8688949353fa1
[ "MIT" ]
null
null
null
first_missing_positive.cpp
zhoujqia/leetcode
5e620a22d34762af329d5d7df1e8688949353fa1
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <ctime> #include <cstdlib> #include <utility> using namespace std; class Solution { public: int firstMissingPositive(vector<int>& nums) { int size = nums.size(); for (int i = 0; i < size; ) { //nums[i] in range[1,n] shoud put in the position nums[i] - 1 if (nums[i] > 0 && nums[i] <= size && nums[nums[i]-1] != nums[i]) { swap(nums[i],nums[nums[i]-1]); } //nums[i] in the right position or nums[i] out of range[1,n] else { i++; } } for (int i = 0; i < size; ++i) { if (nums[i] != i+1) { return i+1; } } return size+1; } }; int main(int argc, char const *argv[]) { vector<int> v1{3,4,-1,1}; vector<int> v2{1,2,3}; vector<int> v3{}; vector<int> v4{2,3,1}; Solution s; cout << s.firstMissingPositive(v1) << endl; cout << s.firstMissingPositive(v2) << endl; cout << s.firstMissingPositive(v3) << endl; cout << s.firstMissingPositive(v4) << endl; return 0; }
20.886792
72
0.514905
[ "vector" ]
aed221ec9659be9c23793d2bd5a38fcab7175dd9
7,173
cpp
C++
src/IndigoConfiguration.cpp
vsemionov/indigo-filer
bb8de3308fbc547cb419ecc2edc264fc28806cdd
[ "BSD-2-Clause" ]
null
null
null
src/IndigoConfiguration.cpp
vsemionov/indigo-filer
bb8de3308fbc547cb419ecc2edc264fc28806cdd
[ "BSD-2-Clause" ]
null
null
null
src/IndigoConfiguration.cpp
vsemionov/indigo-filer
bb8de3308fbc547cb419ecc2edc264fc28806cdd
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2010, Victor Semionov * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ #include <string> #include <algorithm> #include <Poco/Path.h> #include <Poco/Exception.h> #include <Poco/String.h> #include "IndigoConfiguration.h" using namespace std; using namespace Poco; IndigoConfiguration *IndigoConfiguration::singleton = NULL; const string IndigoConfiguration::defaultPath = ""; const string IndigoConfiguration::defaultMimeType = "application/octet-stream"; const IndigoConfiguration &IndigoConfiguration::init( const string &serverName, const string &address, int port, int backlog, int minThreads, int maxThreads, int maxQueued, int timeout, bool keepalive, int keepaliveTimeout, int maxKeepaliveRequests, int idleTime, int threadIdleTime, bool collectIdleThreads, const string &root, const vector<string> &indexes, bool autoIndex, const unordered_map<string, string> &shares, const unordered_map<string, string> &mimeTypes ) { poco_assert(singleton == NULL); singleton = new IndigoConfiguration( serverName, address, port, backlog, minThreads, maxThreads, maxQueued, timeout, keepalive, keepaliveTimeout, maxKeepaliveRequests, idleTime, threadIdleTime, collectIdleThreads, root, indexes, autoIndex, shares, mimeTypes ); return get(); } const IndigoConfiguration &IndigoConfiguration::get() { poco_assert(singleton != NULL); return *singleton; } IndigoConfiguration::IndigoConfiguration( const string &serverName, const string &address, int port, int backlog, int minThreads, int maxThreads, int maxQueued, int timeout, bool keepalive, int keepaliveTimeout, int maxKeepaliveRequests, int idleTime, int threadIdleTime, bool collectIdleThreads, const string &root, const vector<string> &indexes, bool autoIndex, const unordered_map<string, string> &shares, const unordered_map<string, string> &mimeTypes ): serverName(serverName), address(address), port(port), backlog(backlog), minThreads(minThreads), maxThreads(maxThreads), maxQueued(maxQueued), timeout(timeout), keepalive(keepalive), keepaliveTimeout(keepaliveTimeout), maxKeepaliveRequests(maxKeepaliveRequests), idleTime(idleTime), threadIdleTime(threadIdleTime), collectIdleThreads(collectIdleThreads), root(root), indexes(indexes), indexesNative(), autoIndex(autoIndex), shares(shares), mimeTypes(mimeTypes), shareVec() { for (unordered_map<string, string>::const_iterator it = shares.begin(); it != shares.end(); ++it) { shareVec.push_back(it->first); } sort(shareVec.begin(), shareVec.end()); for (vector<string>::const_iterator it = indexes.begin(); it != indexes.end(); ++it) { string index = *it; replaceInPlace(index, string("/"), string(1, Path::separator())); indexesNative.push_back(index); } } void IndigoConfiguration::validate() const { if (!root.empty()) { Path p(root); if (!p.isAbsolute()) throw ApplicationException("\"" + root + "\" is not an absolute path"); } for (unordered_map<string, string>::const_iterator it = shares.begin(); it != shares.end(); ++it) { const string &shareName = it->first; const string &sharePath = it->second; Path p; string uri = '/' + shareName + '/'; p.assign(uri, Path::PATH_UNIX); string resolved = p.toString(Path::PATH_UNIX); if (resolved != uri || p.depth() != 1) throw ApplicationException("\"" + shareName + "\" is not a valid share name"); p.assign(sharePath); if (!p.isAbsolute()) throw ApplicationException("\"" + sharePath + "\" is not an absolute path"); } } const string &IndigoConfiguration::getServerName() const { return serverName; } const string &IndigoConfiguration::getAddress() const { return address; } int IndigoConfiguration::getPort() const { return port; } int IndigoConfiguration::getBacklog() const { return backlog; } int IndigoConfiguration::getMinThreads() const { return minThreads; } int IndigoConfiguration::getMaxThreads() const { return maxThreads; } int IndigoConfiguration::getMaxQueued() const { return maxQueued; } int IndigoConfiguration::getTimeout() const { return timeout; } bool IndigoConfiguration::getKeepalive() const { return keepalive; } int IndigoConfiguration::getKeepaliveTimeout() const { return keepaliveTimeout; } int IndigoConfiguration::getMaxKeepaliveRequests() const { return maxKeepaliveRequests; } int IndigoConfiguration::getIdleTime() const { return idleTime; } int IndigoConfiguration::getThreadIdleTime() const { return threadIdleTime; } bool IndigoConfiguration::getCollectIdleThreads() const { return collectIdleThreads; } const string &IndigoConfiguration::getRoot() const { return root; } const vector<string> &IndigoConfiguration::getIndexes(bool native) const { if (!native) return indexes; else return indexesNative; } bool IndigoConfiguration::getAutoIndex() const { return autoIndex; } const vector<string> &IndigoConfiguration::getShares() const { return shareVec; } const string &IndigoConfiguration::getSharePath(const string &share) const { unordered_map<string, string>::const_iterator it = shares.find(share); if (it != shares.end()) return it->second; else return defaultPath; } const string &IndigoConfiguration::getMimeType(const string &extension) const { unordered_map<string, string>::const_iterator it = mimeTypes.find(extension); if (it != mimeTypes.end()) return it->second; else return defaultMimeType; } bool IndigoConfiguration::virtualRoot() const { return getRoot().empty(); }
23.751656
99
0.70863
[ "vector" ]
aed865db10ec8fdb4baeeb3798a1e913883cab02
31,837
cpp
C++
code/hud/hudets.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
307
2015-04-10T13:27:32.000Z
2022-03-21T03:30:38.000Z
code/hud/hudets.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
2,231
2015-04-27T10:47:35.000Z
2022-03-31T19:22:37.000Z
code/hud/hudets.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
282
2015-01-05T12:16:57.000Z
2022-03-28T04:45:11.000Z
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on the * source. * */ #include "freespace.h" #include "gamesnd/gamesnd.h" #include "globalincs/systemvars.h" #include "hud/hudets.h" #include "hud/hudmessage.h" #include "io/timer.h" #include "localization/localize.h" #include "object/object.h" #include "object/objectshield.h" #include "ship/ship.h" #include "ship/subsysdamage.h" #include "weapon/emp.h" #include "weapon/weapon.h" float Energy_levels[NUM_ENERGY_LEVELS] = {0.0f, 0.0833f, 0.167f, 0.25f, 0.333f, 0.417f, 0.5f, 0.583f, 0.667f, 0.75f, 0.833f, 0.9167f, 1.0f}; bool Weapon_energy_cheat = false; // ------------------------------------------------------------------------------------------------- // ets_init_ship() is called by a ship when it is created (effectively, for every ship at the start // of a mission). This will set the default charge rates for the different systems and initialize // the weapon energy reserve. // void ets_init_ship(object* obj) { ship* sp; // fred should bail here if(Fred_running){ return; } Assert(obj->type == OBJ_SHIP); sp = &Ships[obj->instance]; sp->weapon_energy = Ship_info[sp->ship_info_index].max_weapon_reserve; if ((sp->flags[Ship::Ship_Flags::No_ets]) == 0) { sp->next_manage_ets = timestamp(AI_MODIFY_ETS_INTERVAL); } else { sp->next_manage_ets = -1; } set_default_recharge_rates(obj); } // ------------------------------------------------------------------------------------------------- // update_ets() is called once per frame for every OBJ_SHIP in the game. The amount of energy // to send to the weapons and shields is calculated, and the top ship speed is calculated. The // amount of time elapsed from the previous call is passed in as the parameter fl_frametime. // // parameters: obj ==> object that is updating their energy system // fl_frametime ==> game frametime (in seconds) // void update_ets(object* objp, float fl_frametime) { float max_new_shield_energy, max_new_weapon_energy, _ss; if ( fl_frametime <= 0 ){ return; } ship* ship_p = &Ships[objp->instance]; ship_info* sinfo_p = &Ship_info[ship_p->ship_info_index]; float max_g=sinfo_p->max_weapon_reserve; if ( ship_p->flags[Ship::Ship_Flags::Dying] ){ return; } if ( sinfo_p->power_output == 0 ){ return; } // new_energy = fl_frametime * sinfo_p->power_output; // update weapon energy max_new_weapon_energy = fl_frametime * ship_p->max_weapon_regen_per_second * max_g; if ( objp->flags[Object::Object_Flags::Player_ship] ) { ship_p->weapon_energy += Energy_levels[ship_p->weapon_recharge_index] * max_new_weapon_energy * The_mission.ai_profile->weapon_energy_scale[Game_skill_level]; } else { ship_p->weapon_energy += Energy_levels[ship_p->weapon_recharge_index] * max_new_weapon_energy; } if ( ship_p->weapon_energy > sinfo_p->max_weapon_reserve ){ ship_p->weapon_energy = sinfo_p->max_weapon_reserve; } float shield_delta; max_new_shield_energy = fl_frametime * ship_p->max_shield_regen_per_second * shield_get_max_strength(objp, true); // recharge rate is unaffected by $Max Shield Recharge if ( objp->flags[Object::Object_Flags::Player_ship] ) { shield_delta = Energy_levels[ship_p->shield_recharge_index] * max_new_shield_energy * The_mission.ai_profile->shield_energy_scale[Game_skill_level]; } else { shield_delta = Energy_levels[ship_p->shield_recharge_index] * max_new_shield_energy; } if (Missiontime - Ai_info[ship_p->ai_index].last_hit_time < fl2f(sinfo_p->shield_regen_hit_delay)) shield_delta = 0.0f; shield_add_strength(objp, shield_delta); // if strength now exceeds max, scale back segments proportionally float max_shield = shield_get_max_strength(objp); if ( (_ss = shield_get_strength(objp)) > max_shield ){ for (int i=0; i<objp->n_quadrants; i++){ objp->shield_quadrant[i] *= max_shield / _ss; } } // calculate the top speed of the ship based on the energy flow to engines float y = Energy_levels[ship_p->engine_recharge_index]; ship_p->current_max_speed = ets_get_max_speed(objp, y); // AL 11-15-97: Rules for engine strength affecting max speed: // 1. if strength >= 0.5 no affect // 2. if strength < 0.5 then max_speed = sqrt(strength) // // This will translate to 71% max speed at 50% engines, and 31% max speed at 10% engines // float strength = ship_get_subsystem_strength(ship_p, SUBSYSTEM_ENGINE); // don't let engine strength affect max speed when playing on lowest skill level if ( (objp != Player_obj) || (Game_skill_level > 0) ) { if ( strength < SHIP_MIN_ENGINES_FOR_FULL_SPEED ) { ship_p->current_max_speed *= fl_sqrt(strength); } } if ( timestamp_elapsed(ship_p->next_manage_ets) ) { if ( !(objp->flags[Object::Object_Flags::Player_ship]) ) { ai_manage_ets(objp); ship_p->next_manage_ets = timestamp(AI_MODIFY_ETS_INTERVAL); } else { if ( Weapon_energy_cheat ){ ship_p->weapon_energy = sinfo_p->max_weapon_reserve; } } } } float ets_get_max_speed(object* objp, float engine_energy) { Assertion(objp != NULL, "Invalid object pointer passed!"); Assertion(objp->type == OBJ_SHIP, "Object needs to be a ship object!"); Assertion(engine_energy >= 0.0f && engine_energy <= 1.0f, "Invalid float passed, needs to be in [0, 1], was %f!", engine_energy); ship* shipp = &Ships[objp->instance]; ship_info* sip = &Ship_info[shipp->ship_info_index]; // check for a shortcuts first before doing linear interpolation if ( engine_energy == Energy_levels[INTIAL_ENGINE_RECHARGE_INDEX] ){ return sip->max_speed; } else if ( engine_energy == 0.0f ){ return 0.5f * sip->max_speed; } else if ( engine_energy == 1.0f ){ return sip->max_overclocked_speed; } else { // do a linear interpolation to find the current max speed, using points (0,1/2 default_max_speed) (.333,default_max_speed) // x = x1 + (y-y1) * (x2-x1) / (y2-y1); if ( engine_energy < Energy_levels[INTIAL_ENGINE_RECHARGE_INDEX] ){ return 0.5f*sip->max_speed + (engine_energy * (0.5f*sip->max_speed) ) / Energy_levels[INTIAL_ENGINE_RECHARGE_INDEX]; } else { // do a linear interpolation to find the current max speed, using points (.333,default_max_speed) (1,max_overclock_speed) return sip->max_speed + (engine_energy - Energy_levels[INTIAL_ENGINE_RECHARGE_INDEX]) * (sip->max_overclocked_speed - sip->max_speed) / (1.0f - Energy_levels[INTIAL_ENGINE_RECHARGE_INDEX]); } } } // ------------------------------------------------------------------------------------------------- // ai_manage_ets() will determine if a ship should modify it's energy transfer percentages, or // transfer energy from shields->weapons or from weapons->shields // // minimum level rule constants #define SHIELDS_MIN_LEVEL_PERCENT 0.3f #define WEAPONS_MIN_LEVEL_PERCENT 0.3f // maximum level rule constants #define SHIELDS_MAX_LEVEL_PERCENT 0.8f #define WEAPONS_MAX_LEVEL_PERCENT 0.8f // emergency rule constants #define SHIELDS_EMERG_LEVEL_PERCENT 0.10f #define WEAPONS_EMERG_LEVEL_PERCENT 0.05f // need this, or ai's tend to totally eliminate engine power! #define MIN_ENGINE_RECHARGE_INDEX 3 #define DEFAULT_CHARGE_INDEX 4 #define NORMAL_TOLERANCE_PERCENT .10f void ai_manage_ets(object* obj) { ship* ship_p = &Ships[obj->instance]; ship_info* ship_info_p = &Ship_info[ship_p->ship_info_index]; ai_info* aip = &Ai_info[Ships[obj->instance].ai_index]; if ( ship_info_p->power_output == 0 ) return; if (ship_p->flags[Ship::Ship_Flags::Dying]) return; // check if weapons or engines are not being used. If so, don't allow energy management. if (!ship_info_p->max_speed || !ship_info_p->max_weapon_reserve) { return; } // also check if the ship has no shields and if the AI is allowed to manage weapons and engines --wookieejedi if ( !(ship_p->ship_max_shield_strength) && !( (aip->ai_profile_flags[AI::Profile_Flags::all_nonshielded_ships_can_manage_ets]) || ( (ship_info_p->is_fighter_bomber()) && (aip->ai_profile_flags[AI::Profile_Flags::fightercraft_nonshielded_ships_can_manage_ets])) ) ) { return; } float weapon_left_percent = ship_p->weapon_energy/ship_info_p->max_weapon_reserve; // maximum level check for weapons // MK, changed these, might as well let them go up to 100% if nothing else needs the recharge ability. if ( weapon_left_percent == 1.0f) { decrease_recharge_rate(obj, WEAPONS); } if (!(obj->flags[Object::Object_Flags::No_shields])) { float shield_left_percent = get_shield_pct(obj); // maximum level check for shields if (shield_left_percent == 1.0f) { decrease_recharge_rate(obj, SHIELDS); } // minimum check for shields if (shield_left_percent < SHIELDS_MIN_LEVEL_PERCENT) { if (weapon_left_percent > WEAPONS_MIN_LEVEL_PERCENT) increase_recharge_rate(obj, SHIELDS); } } // minimum check for weapons and engines if ( weapon_left_percent < WEAPONS_MIN_LEVEL_PERCENT ) { increase_recharge_rate(obj, WEAPONS); } if ( ship_p->engine_recharge_index < MIN_ENGINE_RECHARGE_INDEX ) { increase_recharge_rate(obj, ENGINES); } // emergency check for ships with shields if (!(obj->flags[Object::Object_Flags::No_shields])) { float shield_left_percent = get_shield_pct(obj); if ( shield_left_percent < SHIELDS_EMERG_LEVEL_PERCENT ) { if (ship_p->target_shields_delta == 0.0f) transfer_energy_to_shields(obj); } else if ( weapon_left_percent < WEAPONS_EMERG_LEVEL_PERCENT ) { if ( shield_left_percent > SHIELDS_MIN_LEVEL_PERCENT || weapon_left_percent <= 0.01 ) // dampen ai enthusiasm for sucking energy to weapons transfer_energy_to_weapons(obj); } // check for return to normal values if ( fl_abs( shield_left_percent - 0.5f ) < NORMAL_TOLERANCE_PERCENT ) { if ( ship_p->shield_recharge_index > DEFAULT_CHARGE_INDEX ) decrease_recharge_rate(obj, SHIELDS); else if ( ship_p->shield_recharge_index < DEFAULT_CHARGE_INDEX ) increase_recharge_rate(obj, SHIELDS); } } if ( fl_abs( weapon_left_percent - 0.5f ) < NORMAL_TOLERANCE_PERCENT ) { if ( ship_p->weapon_recharge_index > DEFAULT_CHARGE_INDEX ) decrease_recharge_rate(obj, WEAPONS); else if ( ship_p->weapon_recharge_index < DEFAULT_CHARGE_INDEX ) increase_recharge_rate(obj, WEAPONS); } } // ------------------------------------------------------------------------------------------------- // set_default_recharge_rates() will set the charge levels for the weapons, shields and // engines to their default levels void set_default_recharge_rates(object* obj) { int ship_properties; ship* ship_p = &Ships[obj->instance]; ship_info* ship_info_p = &Ship_info[ship_p->ship_info_index]; if ( ship_info_p->power_output == 0 ) return; ship_properties = 0; if (ship_has_energy_weapons(ship_p)) ship_properties |= HAS_WEAPONS; if (!(obj->flags[Object::Object_Flags::No_shields])) ship_properties |= HAS_SHIELDS; if (ship_has_engine_power(ship_p)) ship_properties |= HAS_ENGINES; // the default charge rate depends on what systems are on each ship switch ( ship_properties ) { case HAS_ENGINES | HAS_WEAPONS | HAS_SHIELDS: ship_p->shield_recharge_index = INTIAL_SHIELD_RECHARGE_INDEX; ship_p->weapon_recharge_index = INTIAL_WEAPON_RECHARGE_INDEX; ship_p->engine_recharge_index = INTIAL_ENGINE_RECHARGE_INDEX; break; case HAS_ENGINES | HAS_SHIELDS: ship_p->shield_recharge_index = ONE_HALF_INDEX; ship_p->weapon_recharge_index = ZERO_INDEX; ship_p->engine_recharge_index = ONE_HALF_INDEX; break; case HAS_WEAPONS | HAS_SHIELDS: ship_p->shield_recharge_index = ONE_HALF_INDEX; ship_p->weapon_recharge_index = ONE_HALF_INDEX; ship_p->engine_recharge_index = ZERO_INDEX; break; case HAS_ENGINES | HAS_WEAPONS: ship_p->shield_recharge_index = ZERO_INDEX; ship_p->weapon_recharge_index = ONE_HALF_INDEX; ship_p->engine_recharge_index = ONE_HALF_INDEX; break; case HAS_SHIELDS: ship_p->shield_recharge_index = ALL_INDEX; ship_p->weapon_recharge_index = ZERO_INDEX; ship_p->engine_recharge_index = ZERO_INDEX; break; case HAS_ENGINES: ship_p->shield_recharge_index = ZERO_INDEX; ship_p->weapon_recharge_index = ZERO_INDEX; ship_p->engine_recharge_index = ALL_INDEX; break; case HAS_WEAPONS: ship_p->shield_recharge_index = ZERO_INDEX; ship_p->weapon_recharge_index = ALL_INDEX; ship_p->engine_recharge_index = ZERO_INDEX; break; default: Int3(); // if no systems, power output should be zero, and this funtion shouldn't be called break; } // end switch } // ------------------------------------------------------------------------------------------------- // increase_recharge_rate() will increase the energy flow to the specified system (one of // WEAPONS, SHIELDS or ENGINES). The increase in energy will result in a decrease to // the other two systems. void increase_recharge_rate(object* obj, SYSTEM_TYPE ship_system) { int *gain_index=NULL, *lose_index1=NULL, *lose_index2=NULL, *tmp=NULL; int count=0; ship *ship_p = &Ships[obj->instance]; if (ship_p->flags[Ship::Ship_Flags::No_ets]) return; switch ( ship_system ) { case WEAPONS: if ( !ship_has_energy_weapons(ship_p) ) return; gain_index = &ship_p->weapon_recharge_index; if ( obj->flags[Object::Object_Flags::No_shields] ) lose_index1 = NULL; else lose_index1 = &ship_p->shield_recharge_index; if ( !ship_has_engine_power(ship_p) ) lose_index2 = NULL; else lose_index2 = &ship_p->engine_recharge_index; break; case SHIELDS: if ( obj->flags[Object::Object_Flags::No_shields] ) return; gain_index = &ship_p->shield_recharge_index; if ( !ship_has_energy_weapons(ship_p) ) lose_index1 = NULL; else lose_index1 = &ship_p->weapon_recharge_index; if ( !ship_has_engine_power(ship_p) ) lose_index2 = NULL; else lose_index2 = &ship_p->engine_recharge_index; break; case ENGINES: if ( !ship_has_engine_power(ship_p) ) return; gain_index = &ship_p->engine_recharge_index; if ( !ship_has_energy_weapons(ship_p) ) lose_index1 = NULL; else lose_index1 = &ship_p->weapon_recharge_index; if ( obj->flags[Object::Object_Flags::No_shields] ) lose_index2 = NULL; else lose_index2 = &ship_p->shield_recharge_index; break; } // end switch // return if we can't transfer energy if (!lose_index1 && !lose_index2) return; // already full, nothing to do count = MAX_ENERGY_INDEX - *gain_index; if ( count > 2 ) count = 2; if ( count <= 0 ) { if ( obj == Player_obj ) { snd_play( gamesnd_get_game_sound(GameSounds::ENERGY_TRANS_FAIL), 0.0f ); } return; } *gain_index += count; // ensure that the highest lose index takes the first decrease if ( lose_index1 && lose_index2 ) { if ( *lose_index1 < *lose_index2 ) { tmp = lose_index1; lose_index1 = lose_index2; lose_index2 = tmp; } } int sanity = 0; while(count > 0) { if ( lose_index1 && *lose_index1 > 0 ) { *lose_index1 -= 1; count--; } if ( count <= 0 ) break; if ( lose_index2 && *lose_index2 > 0 ) { *lose_index2 -= 1; count--; } if ( sanity++ > 10 ) { Int3(); // get Alan break; } } if ( obj == Player_obj ) snd_play( gamesnd_get_game_sound(GameSounds::ENERGY_TRANS), 0.0f ); } // ------------------------------------------------------------------------------------------------- // decrease_recharge_rate() will decrease the energy flow to the specified system (one of // WEAPONS, SHIELDS or ENGINES). The decrease in energy will result in an increase to // the other two systems. void decrease_recharge_rate(object* obj, SYSTEM_TYPE ship_system) { int *lose_index=NULL, *gain_index1=NULL, *gain_index2=NULL, *tmp=NULL; int count; ship *ship_p = &Ships[obj->instance]; if (ship_p->flags[Ship::Ship_Flags::No_ets]) return; switch ( ship_system ) { case WEAPONS: if ( !ship_has_energy_weapons(ship_p) ) return; lose_index = &ship_p->weapon_recharge_index; if ( obj->flags[Object::Object_Flags::No_shields] ) gain_index1 = NULL; else gain_index1 = &ship_p->shield_recharge_index; if ( !ship_has_engine_power(ship_p) ) gain_index2 = NULL; else gain_index2 = &ship_p->engine_recharge_index; break; case SHIELDS: if ( obj->flags[Object::Object_Flags::No_shields] ) return; lose_index = &ship_p->shield_recharge_index; if ( !ship_has_energy_weapons(ship_p) ) gain_index1 = NULL; else gain_index1 = &ship_p->weapon_recharge_index; if ( !ship_has_engine_power(ship_p) ) gain_index2 = NULL; else gain_index2 = &ship_p->engine_recharge_index; break; case ENGINES: if ( !ship_has_engine_power(ship_p) ) return; lose_index = &ship_p->engine_recharge_index; if ( !ship_has_energy_weapons(ship_p) ) gain_index1 = NULL; else gain_index1 = &ship_p->weapon_recharge_index; if ( obj->flags[Object::Object_Flags::No_shields] ) gain_index2 = NULL; else gain_index2 = &ship_p->shield_recharge_index; break; } // end switch // return if we can't transfer energy if (!gain_index1 && !gain_index2) return; // check how much there is to lose count = MIN(2, *lose_index); if ( count <= 0 ) { if ( obj == Player_obj ) { snd_play( gamesnd_get_game_sound(GameSounds::ENERGY_TRANS_FAIL), 0.0f ); } return; } *lose_index -= count; // make sure that the gain starts with the system which needs it most if ( gain_index1 && gain_index2 ) { if ( *gain_index1 > *gain_index2 ) { tmp = gain_index1; gain_index1 = gain_index2; gain_index2 = tmp; } } int sanity=0; while(count > 0) { if ( gain_index1 && *gain_index1 < MAX_ENERGY_INDEX ) { *gain_index1 += 1; count--; } if ( count <= 0 ) break; if ( gain_index2 && *gain_index2 < MAX_ENERGY_INDEX ) { *gain_index2 += 1; count--; } if ( sanity++ > 10 ) { Int3(); // get Alan break; } } if ( obj == Player_obj ) snd_play( gamesnd_get_game_sound(GameSounds::ENERGY_TRANS), 0.0f ); } void transfer_energy_weapon_common(object *objp, float from_field, float to_field, float *from_delta, float *to_delta, float from_max, float to_max, float scale, float eff) { float delta; delta = from_max * scale; if (to_field + *to_delta + eff * delta > to_max && eff > 0) delta = (to_max - to_field - *to_delta) / eff; if ( delta > 0 ) { if ( objp == Player_obj ) snd_play( gamesnd_get_game_sound(GameSounds::ENERGY_TRANS), 0.0f ); if (delta > from_field) delta = from_field; *to_delta += eff * delta; *from_delta -= delta; } else if ( objp == Player_obj ) snd_play( gamesnd_get_game_sound(GameSounds::ENERGY_TRANS_FAIL), 0.0f ); } // ------------------------------------------------------------------------------------------------- // transfer_energy_to_shields() will transfer a tabled percentage of max weapon energy // to shield energy. void transfer_energy_to_shields(object* obj) { ship* ship_p = &Ships[obj->instance]; ship_info* sinfo_p = &Ship_info[ship_p->ship_info_index]; if (ship_p->flags[Ship::Ship_Flags::Dying]) return; if ( !ship_has_energy_weapons(ship_p) || obj->flags[Object::Object_Flags::No_shields] ) { return; } if (sinfo_p->weap_shield_amount == 0 && obj == Player_obj) { HUD_sourced_printf(HUD_SOURCE_HIDDEN, "%s", XSTR("Ship does not support weapon->shield transfer.", -1)); snd_play( gamesnd_get_game_sound(GameSounds::ENERGY_TRANS_FAIL), 0.0f ); return; } transfer_energy_weapon_common(obj, ship_p->weapon_energy, shield_get_strength(obj), &ship_p->target_weapon_energy_delta, &ship_p->target_shields_delta, sinfo_p->max_weapon_reserve, shield_get_max_strength(obj), sinfo_p->weap_shield_amount, sinfo_p->weap_shield_efficiency); } // ------------------------------------------------------------------------------------------------- // transfer_energy_to_weapons() will transfer a tabled percentage of max shield energy // to weapon energy. void transfer_energy_to_weapons(object* obj) { ship* ship_p = &Ships[obj->instance]; ship_info* sinfo_p = &Ship_info[ship_p->ship_info_index]; if (ship_p->flags[Ship::Ship_Flags::Dying]) return; if ( !ship_has_energy_weapons(ship_p) || obj->flags[Object::Object_Flags::No_shields] ) { return; } if (sinfo_p->shield_weap_amount == 0 && obj == Player_obj) { HUD_sourced_printf(HUD_SOURCE_HIDDEN, "%s", XSTR("Ship does not support shield->weapon transfer.", -1)); snd_play( gamesnd_get_game_sound(GameSounds::ENERGY_TRANS_FAIL), 0.0f ); return; } transfer_energy_weapon_common(obj, shield_get_strength(obj), ship_p->weapon_energy, &ship_p->target_shields_delta, &ship_p->target_weapon_energy_delta, shield_get_max_strength(obj), sinfo_p->max_weapon_reserve, sinfo_p->shield_weap_amount, sinfo_p->shield_weap_efficiency); } /** * decrease one ets index to zero & adjust others up */ void zero_one_ets (int *reduce, int *add1, int *add2) { int *tmp; // add to the smallest index 1st if (*add1 > *add2) { tmp = add1; add1 = add2; add2 = tmp; } while (*reduce > ZERO_INDEX) { if (*add1 < ALL_INDEX) { ++*add1; --*reduce; } if (*reduce <= ZERO_INDEX) { break; } if (*add2 < ALL_INDEX) { ++*add2; --*reduce; } } } /** * ensure input ETS indexs are valid. * If not, "fix" them by moving outliers towards the middle index */ void sanity_check_ets_inputs(int (&ets_indexes)[num_retail_ets_gauges]) { int i; int ets_delta = MAX_ENERGY_INDEX - ets_indexes[ENGINES] - ets_indexes[SHIELDS] - ets_indexes[WEAPONS]; if ( ets_delta != 0 ) { if ( ets_delta > 0) { // add to lowest indexes while ( ets_delta != 0 ) { int lowest_val = MAX_ENERGY_INDEX; int lowest_idx = 0; for (i = 0; i < num_retail_ets_gauges; ++i) { if (ets_indexes[i] <= lowest_val ) { lowest_val = ets_indexes[i]; lowest_idx = i; } } ++ets_indexes[lowest_idx]; --ets_delta; } } else { // remove from highest indexes while ( ets_delta != 0 ) { int highest_val = 0; int highest_idx = 0; for (i = 0; i < num_retail_ets_gauges; ++i) { if (ets_indexes[i] >= highest_val ) { highest_val = ets_indexes[i]; highest_idx = i; } } --ets_indexes[highest_idx]; ++ets_delta; } } } } /** * adjust input ETS indexes to handle missing systems on the target ship * return true if indexes are valid to be set */ bool validate_ship_ets_indxes(const int &ship_idx, int (&ets_indexes)[num_retail_ets_gauges]) { if (ship_idx < 0) { return false; } if (Ships[ship_idx].objnum < 0) { return false; } ship *ship_p = &Ships[ship_idx]; if (ship_p->flags[Ship::Ship_Flags::No_ets]) return false; // handle ships that are missing parts of the ETS int ship_properties = 0; if (ship_has_energy_weapons(ship_p)) { ship_properties |= HAS_WEAPONS; } if (!(Objects[ship_p->objnum].flags[Object::Object_Flags::No_shields])) { ship_properties |= HAS_SHIELDS; } if (ship_has_engine_power(ship_p)) { ship_properties |= HAS_ENGINES; } switch ( ship_properties ) { case HAS_ENGINES | HAS_WEAPONS | HAS_SHIELDS: // all present, don't change ets indexes break; case HAS_ENGINES | HAS_SHIELDS: zero_one_ets(&ets_indexes[WEAPONS], &ets_indexes[ENGINES], &ets_indexes[SHIELDS]); break; case HAS_WEAPONS | HAS_SHIELDS: zero_one_ets(&ets_indexes[ENGINES], &ets_indexes[SHIELDS], &ets_indexes[WEAPONS]); break; case HAS_ENGINES | HAS_WEAPONS: zero_one_ets(&ets_indexes[SHIELDS], &ets_indexes[ENGINES], &ets_indexes[WEAPONS]); break; case HAS_ENGINES: case HAS_SHIELDS: case HAS_WEAPONS: // can't change anything if only one is active on this ship return false; break; default: Error(LOCATION, "Encountered a ship (%s) with a broken ETS", ship_p->ship_name); break; } return true; } HudGaugeEts::HudGaugeEts(): HudGauge(HUD_OBJECT_ETS_ENGINES, HUD_ETS_GAUGE, false, false, (VM_EXTERNAL | VM_DEAD_VIEW | VM_WARP_CHASE | VM_PADLOCK_ANY | VM_OTHER_SHIP), 255, 255, 255), System_type(0) { } HudGaugeEts::HudGaugeEts(int _gauge_object, int _system_type): HudGauge(_gauge_object, HUD_ETS_GAUGE, false, false, (VM_EXTERNAL | VM_DEAD_VIEW | VM_WARP_CHASE | VM_PADLOCK_ANY | VM_OTHER_SHIP), 255, 255, 255), System_type(_system_type) { } void HudGaugeEts::initBarHeight(int _ets_h) { ETS_bar_h = _ets_h; } void HudGaugeEts::initLetterOffsets(int _x, int _y) { Letter_offsets[0] = _x; Letter_offsets[1] = _y; } void HudGaugeEts::initTopOffsets(int _x, int _y) { Top_offsets[0] = _x; Top_offsets[1] = _y; } void HudGaugeEts::initBottomOffsets(int _x, int _y) { Bottom_offsets[0] = _x; Bottom_offsets[1] = _y; } void HudGaugeEts::initLetter(char _letter) { Letter = _letter; } void HudGaugeEts::initBitmaps(char *fname) { Ets_bar.first_frame = bm_load_animation(fname, &Ets_bar.num_frames); if ( Ets_bar.first_frame < 0 ) { Warning(LOCATION,"Cannot load hud ani: %s\n", fname); } } void HudGaugeEts::render(float /*frametime*/) { } void HudGaugeEts::pageIn() { bm_page_in_aabitmap( Ets_bar.first_frame, Ets_bar.num_frames ); } /** * Draw one ETS bar to screen */ void HudGaugeEts::blitGauge(int index) { int y_start, y_end, clip_h, w, h, x, y; clip_h = fl2i( (1 - Energy_levels[index]) * ETS_bar_h ); bm_get_info(Ets_bar.first_frame,&w,&h); if ( index < NUM_ENERGY_LEVELS-1 ) { // some portion of dark needs to be drawn setGaugeColor(); // draw the top portion x = position[0] + Top_offsets[0]; y = position[1] + Top_offsets[1]; renderBitmapEx(Ets_bar.first_frame,x,y,w,clip_h,0,0); // draw the bottom portion x = position[0] + Bottom_offsets[0]; y = position[1] + Bottom_offsets[1]; y_start = y + (ETS_bar_h - clip_h); y_end = y + ETS_bar_h; renderBitmapEx(Ets_bar.first_frame, x, y_start, w, y_end-y_start, 0, ETS_bar_h-clip_h); } if ( index > 0 ) { if ( maybeFlashSexp() == 1 ) { setGaugeColor(HUD_C_DIM); // hud_set_dim_color(); } else { setGaugeColor(HUD_C_BRIGHT); // hud_set_bright_color(); } // some portion of recharge needs to be drawn // draw the top portion x = position[0] + Top_offsets[0]; y = position[1] + Top_offsets[1]; y_start = y + clip_h; y_end = y + ETS_bar_h; renderBitmapEx(Ets_bar.first_frame+1, x, y_start, w, y_end-y_start, 0, clip_h); // draw the bottom portion x = position[0] + Bottom_offsets[0]; y = position[1] + Bottom_offsets[1]; renderBitmapEx(Ets_bar.first_frame+2, x,y,w,ETS_bar_h-clip_h,0,0); } } /** * Default ctor for retail ETS gauge * 2nd arg (0) is not used */ HudGaugeEtsRetail::HudGaugeEtsRetail(): HudGaugeEts(HUD_OBJECT_ETS_RETAIL, 0) { } /** * Render the ETS retail gauge to the screen (weapon+shield+engine) */ void HudGaugeEtsRetail::render(float /*frametime*/) { int i; int initial_position; ship* ship_p = &Ships[Player_obj->instance]; if ( Ets_bar.first_frame < 0 ) { return; } // if at least two gauges are not shown, don't show any i = 0; if (!ship_has_energy_weapons(ship_p)) i++; if (Player_obj->flags[Object::Object_Flags::No_shields]) i++; if (!ship_has_engine_power(ship_p)) i++; if (i >= 2) return; setGaugeColor(); // draw the letters for the gauges first, before any clipping occurs // skip letter for any missing gauges (max one, see check above) initial_position = 0; if (ship_has_energy_weapons(ship_p)) { Letter = Letters[0]; position[0] = Gauge_positions[initial_position++]; renderPrintf(position[0] + Letter_offsets[0], position[1] + Letter_offsets[1], NOX("%c"), Letter); } if (!(Player_obj->flags[Object::Object_Flags::No_shields])) { Letter = Letters[1]; position[0] = Gauge_positions[initial_position++]; renderPrintf(position[0] + Letter_offsets[0], position[1] + Letter_offsets[1], NOX("%c"), Letter); } if (ship_has_engine_power(ship_p)) { Letter = Letters[2]; position[0] = Gauge_positions[initial_position++]; renderPrintf(position[0] + Letter_offsets[0], position[1] + Letter_offsets[1], NOX("%c"), Letter); } // draw gauges, skipping any gauge that is missing initial_position = 0; if (ship_has_energy_weapons(ship_p)) { Letter = Letters[0]; position[0] = Gauge_positions[initial_position++]; blitGauge(ship_p->weapon_recharge_index); } if (!(Player_obj->flags[Object::Object_Flags::No_shields])) { Letter = Letters[1]; position[0] = Gauge_positions[initial_position++]; blitGauge(ship_p->shield_recharge_index); } if (ship_has_engine_power(ship_p)) { Letter = Letters[2]; position[0] = Gauge_positions[initial_position++]; blitGauge(ship_p->engine_recharge_index); } } /** * Set ETS letters for retail ETS gauge * Allows for different languages to be used in the hud */ void HudGaugeEtsRetail::initLetters(char *_letters) { int i; for ( i = 0; i < num_retail_ets_gauges; ++i) Letters[i] = _letters[i]; } /** * Set the three possible positions for ETS bars */ void HudGaugeEtsRetail::initGaugePositions(int *_gauge_positions) { int i; for ( i = 0; i < num_retail_ets_gauges; ++i) Gauge_positions[i] = _gauge_positions[i]; } HudGaugeEtsWeapons::HudGaugeEtsWeapons(): HudGaugeEts(HUD_OBJECT_ETS_WEAPONS, (int)WEAPONS) { } void HudGaugeEtsWeapons::render(float /*frametime*/) { int i; ship* ship_p = &Ships[Player_obj->instance]; if ( Ets_bar.first_frame < 0 ) { return; } // if at least two gauges are not shown, don't show any i = 0; if (!ship_has_energy_weapons(ship_p)) i++; if (Player_obj->flags[Object::Object_Flags::No_shields]) i++; if (!ship_has_engine_power(ship_p)) i++; if (i >= 2) return; // no weapon energy, no weapon gauge if (!ship_has_energy_weapons(ship_p)) { return; } setGaugeColor(); // draw the letters for the gauge first, before any clipping occurs renderPrintf(position[0] + Letter_offsets[0], position[1] + Letter_offsets[1], NOX("%c"), Letter); // draw the gauges for the weapon system blitGauge(ship_p->weapon_recharge_index); } HudGaugeEtsShields::HudGaugeEtsShields(): HudGaugeEts(HUD_OBJECT_ETS_SHIELDS, (int)SHIELDS) { } void HudGaugeEtsShields::render(float /*frametime*/) { int i; ship* ship_p = &Ships[Player_obj->instance]; if ( Ets_bar.first_frame < 0 ) { return; } // if at least two gauges are not shown, don't show any i = 0; if (!ship_has_energy_weapons(ship_p)) i++; if (Player_obj->flags[Object::Object_Flags::No_shields]) i++; if (!ship_has_engine_power(ship_p)) i++; if (i >= 2) return; // no shields, no shields gauge if (Player_obj->flags[Object::Object_Flags::No_shields]) { return; } setGaugeColor(); // draw the letters for the gauge first, before any clipping occurs renderPrintf(position[0] + Letter_offsets[0], position[1] + Letter_offsets[1], NOX("%c"), Letter); // draw the gauge for the shield system blitGauge(ship_p->shield_recharge_index); } HudGaugeEtsEngines::HudGaugeEtsEngines(): HudGaugeEts(HUD_OBJECT_ETS_ENGINES, (int)ENGINES) { } void HudGaugeEtsEngines::render(float /*frametime*/) { int i; ship* ship_p = &Ships[Player_obj->instance]; if ( Ets_bar.first_frame < 0 ) { return; } // if at least two gauges are not shown, don't show any i = 0; if (!ship_has_energy_weapons(ship_p)) i++; if (Player_obj->flags[Object::Object_Flags::No_shields]) i++; if (!ship_has_engine_power(ship_p)) i++; if (i >= 2) return; // no engines, no engine gauge if (!ship_has_engine_power(ship_p)) { return; } setGaugeColor(); // draw the letters for the gauge first, before any clipping occurs renderPrintf(position[0] + Letter_offsets[0], position[1] + Letter_offsets[1], NOX("%c"), Letter); // draw the gauge for the engine system blitGauge(ship_p->engine_recharge_index); }
28.375223
274
0.69281
[ "render", "object" ]
aedccfc866e1be00c331db7711dbbf3a94077c33
824
cpp
C++
editor/compiler/interface/ConstantValue.cpp
remaininlight/axiom
abd3d9232ffe89dff84b0ef56ab4a1ba9e58d7ce
[ "MIT" ]
642
2017-12-10T14:22:04.000Z
2022-03-03T15:23:23.000Z
editor/compiler/interface/ConstantValue.cpp
remaininlight/axiom
abd3d9232ffe89dff84b0ef56ab4a1ba9e58d7ce
[ "MIT" ]
151
2017-12-21T02:08:45.000Z
2020-07-03T14:18:51.000Z
editor/compiler/interface/ConstantValue.cpp
remaininlight/axiom
abd3d9232ffe89dff84b0ef56ab4a1ba9e58d7ce
[ "MIT" ]
30
2018-09-11T14:06:31.000Z
2021-11-09T04:19:00.000Z
#include "ConstantValue.h" #include "Frontend.h" using namespace MaximCompiler; ConstantValue::ConstantValue(void *handle) : OwnedObject(handle, &MaximFrontend::maxim_destroy_constant) {} ConstantValue ConstantValue::num(AxiomModel::NumValue value) { return ConstantValue(MaximFrontend::maxim_constant_num(value.left, value.right, (uint8_t) value.form)); } ConstantValue ConstantValue::tuple(MaximCompiler::ConstantValue *items, size_t count) { std::vector<void *> mapped_values; mapped_values.reserve(count); for (size_t i = 0; i < count; i++) { mapped_values[i] = items[i].release(); } return ConstantValue(MaximFrontend::maxim_constant_tuple(&mapped_values[0], count)); } ConstantValue ConstantValue::clone() { return ConstantValue(MaximFrontend::maxim_constant_clone(get())); }
32.96
107
0.746359
[ "vector" ]
aee5ef4b1c203fb28fd83983ff6b951cf8580e36
1,222
cpp
C++
Codeforces/1490E_Accidental_Victory.cpp
a3X3k/Competitive-programing-hacktoberfest-2021
bc3997997318af4c5eafad7348abdd9bf5067b4f
[ "Unlicense" ]
12
2021-06-05T09:40:10.000Z
2021-10-07T17:59:51.000Z
Codeforces/1490E_Accidental_Victory.cpp
a3X3k/Competitive-programing-hacktoberfest-2021
bc3997997318af4c5eafad7348abdd9bf5067b4f
[ "Unlicense" ]
21
2021-09-30T22:25:03.000Z
2021-10-05T18:23:25.000Z
Codeforces/1490E_Accidental_Victory.cpp
a3X3k/Competitive-programing-hacktoberfest-2021
bc3997997318af4c5eafad7348abdd9bf5067b4f
[ "Unlicense" ]
67
2021-08-01T10:04:52.000Z
2021-10-10T00:25:04.000Z
// Problem Link: https://codeforces.com/contest/1490/problem/E // Solution: #include"bits/stdc++.h" using namespace std; #define int long long #define fio ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0) #define endl '\n' #define mod 1000000007 int min(int a, int b) { if (a < b) return a; else return b; } bool compare(pair<int, int>a, pair<int, int>b) { return a.first > b.first; } int32_t main() { fio; int t; cin >> t; while (t--) { int n; cin >> n; int a[n]; vector<pair<int, int>>cumm; for (int i = 0; i < n; i++) { cin >> a[i]; } vector<pair<int, int>>v; for (int i = 0; i < n; i++) { cumm.push_back({a[i], i + 1}); } sort(cumm.begin(), cumm.end()); v.push_back({cumm[0].first, cumm[0].second}); for (int i = 1; i < n; i++) { v.push_back({v[i - 1].first + cumm[i].first, cumm[i].second}); } sort(v.begin(), v.end(), compare); vector<int>ans; ans.push_back(v[0].second); for (int i = 1; i < n; i++) { if (2 * v[i].first >= v[i - 1].first) { ans.push_back(v[i].second); } else { break; } } cout << ans.size() << endl; sort(ans.begin(), ans.end()); for (auto p : ans) { cout << p << " "; } cout << endl; } return 0; }
20.032787
67
0.550736
[ "vector" ]
aeee1380dfb05091d00e5c13073aca0ad278592a
844
hpp
C++
identity_matrix.hpp
RyanPersson/EigenC
cb82fcfcb09754b3f1a41cf78c58a2802568c5d2
[ "MIT" ]
null
null
null
identity_matrix.hpp
RyanPersson/EigenC
cb82fcfcb09754b3f1a41cf78c58a2802568c5d2
[ "MIT" ]
null
null
null
identity_matrix.hpp
RyanPersson/EigenC
cb82fcfcb09754b3f1a41cf78c58a2802568c5d2
[ "MIT" ]
null
null
null
/******************************************************************************************************************************************************************************* ** Program: identity_matrix.hpp ** Author: Ryan Persson ** Date Created: 8/6/2020 *******************************************************************************************************************************************************************************/ #ifndef _IDENTITY_MATRIX_HPP #define _IDENTITY_MATRIX_HPP #include <vector> #include <string> #include <iostream> //only needed for print_matrix #include "matrix.hpp" class Identity_Matrix: public Matrix { public: Identity_Matrix(int size=0) : Matrix(size, size) { this->fill(0); for(int i = 0; i < this->height; i++) { this->insert(1, i,i); } } }; #endif
32.461538
176
0.373223
[ "vector" ]
aef14ed8da3bd72193ee5db5d3e3c4dbff2a76aa
4,828
cpp
C++
external/webkit/Source/WebCore/platform/graphics/chromium/WebGLLayerChromium.cpp
ghsecuritylab/android_platform_sony_nicki
526381be7808e5202d7865aa10303cb5d249388a
[ "Apache-2.0" ]
2
2017-05-19T08:53:12.000Z
2017-08-28T11:59:26.000Z
external/webkit/Source/WebCore/platform/graphics/chromium/WebGLLayerChromium.cpp
ghsecuritylab/android_platform_sony_nicki
526381be7808e5202d7865aa10303cb5d249388a
[ "Apache-2.0" ]
2
2017-07-25T09:37:22.000Z
2017-08-04T07:18:56.000Z
external/webkit/Source/WebCore/platform/graphics/chromium/WebGLLayerChromium.cpp
ghsecuritylab/android_platform_sony_nicki
526381be7808e5202d7865aa10303cb5d249388a
[ "Apache-2.0" ]
2
2017-08-09T09:03:23.000Z
2020-05-26T09:14:49.000Z
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #if USE(ACCELERATED_COMPOSITING) #include "WebGLLayerChromium.h" #include "GraphicsContext3D.h" #include "LayerRendererChromium.h" namespace WebCore { PassRefPtr<WebGLLayerChromium> WebGLLayerChromium::create(GraphicsLayerChromium* owner) { return adoptRef(new WebGLLayerChromium(owner)); } WebGLLayerChromium::WebGLLayerChromium(GraphicsLayerChromium* owner) : CanvasLayerChromium(owner) , m_context(0) , m_textureUpdated(false) { } WebGLLayerChromium::~WebGLLayerChromium() { if (m_context && layerRenderer()) layerRenderer()->removeChildContext(m_context); } void WebGLLayerChromium::updateCompositorResources() { if (!m_contentsDirty) return; GraphicsContext3D* rendererContext = layerRendererContext(); ASSERT(m_context); if (m_textureChanged) { rendererContext->bindTexture(GraphicsContext3D::TEXTURE_2D, m_textureId); // Set the min-mag filters to linear and wrap modes to GL_CLAMP_TO_EDGE // to get around NPOT texture limitations of GLES. rendererContext->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::LINEAR); rendererContext->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MAG_FILTER, GraphicsContext3D::LINEAR); rendererContext->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_S, GraphicsContext3D::CLAMP_TO_EDGE); rendererContext->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_T, GraphicsContext3D::CLAMP_TO_EDGE); m_textureChanged = false; } // Update the contents of the texture used by the compositor. if (m_contentsDirty && m_textureUpdated) { // prepareTexture copies the contents of the off-screen render target into the texture // used by the compositor. // m_context->prepareTexture(); m_context->markLayerComposited(); m_contentsDirty = false; m_textureUpdated = false; } } void WebGLLayerChromium::setTextureUpdated() { m_textureUpdated = true; } void WebGLLayerChromium::setContext(const GraphicsContext3D* context) { if (m_context != context && layerRenderer()) { if (m_context) layerRenderer()->removeChildContext(m_context); if (context) layerRenderer()->addChildContext(const_cast<GraphicsContext3D*>(context)); } m_context = const_cast<GraphicsContext3D*>(context); unsigned int textureId = m_context->platformTexture(); if (textureId != m_textureId) { m_textureChanged = true; m_textureUpdated = true; } m_textureId = textureId; m_premultipliedAlpha = m_context->getContextAttributes().premultipliedAlpha; } void WebGLLayerChromium::setLayerRenderer(LayerRendererChromium* newLayerRenderer) { if (layerRenderer() != newLayerRenderer) { if (m_context) { if (layerRenderer()) layerRenderer()->removeChildContext(m_context); if (newLayerRenderer) newLayerRenderer->addChildContext(m_context); } LayerChromium::setLayerRenderer(newLayerRenderer); } } } #endif // USE(ACCELERATED_COMPOSITING)
37.138462
139
0.733637
[ "render" ]
aef700cde7f5699f54a54785c0a9c7865dfe04db
3,083
hpp
C++
ros/catkin_ws/src/kobuki/kobuki_core/kobuki_driver/include/kobuki_driver/packets/gp_input.hpp
Kanaderu/spiking-ddpg-mapless-navigation
2b5e7e67385dee4428b8036bc4ffe95e812b34e0
[ "MIT" ]
null
null
null
ros/catkin_ws/src/kobuki/kobuki_core/kobuki_driver/include/kobuki_driver/packets/gp_input.hpp
Kanaderu/spiking-ddpg-mapless-navigation
2b5e7e67385dee4428b8036bc4ffe95e812b34e0
[ "MIT" ]
null
null
null
ros/catkin_ws/src/kobuki/kobuki_core/kobuki_driver/include/kobuki_driver/packets/gp_input.hpp
Kanaderu/spiking-ddpg-mapless-navigation
2b5e7e67385dee4428b8036bc4ffe95e812b34e0
[ "MIT" ]
null
null
null
/** * @file include/kobuki_driver/packets/gp_input.hpp * * @brief gpio data command packets. * * License: BSD * https://raw.github.com/yujinrobot/kobuki_core/hydro-devel/kobuki_driver/LICENSE */ /***************************************************************************** ** Preprocessor *****************************************************************************/ #ifndef KOBUKI_GP_INPUT_HPP__ #define KOBUKI_GP_INPUT_HPP__ /***************************************************************************** ** Include *****************************************************************************/ #include <vector> #include "../packet_handler/payload_base.hpp" #include "../packet_handler/payload_headers.hpp" /***************************************************************************** ** Namespace *****************************************************************************/ namespace kobuki { /***************************************************************************** ** Interface *****************************************************************************/ class GpInput : public packet_handler::payloadBase { public: GpInput() : packet_handler::payloadBase(false, 16) {}; struct Data { Data() : analog_input(4) {} uint16_t digital_input; /** * This currently returns 4 unsigned shorts containing analog values that * vary between 0 and 4095. These represent the values coming in on the * analog pins. */ std::vector<uint16_t> analog_input; } data; bool serialise(ecl::PushAndPop<unsigned char> & byteStream) { buildBytes(Header::GpInput, byteStream); buildBytes(length, byteStream); buildBytes(data.digital_input, byteStream); for (unsigned int i = 0; i < data.analog_input.size(); ++i) { buildBytes(data.analog_input[i], byteStream); } for (unsigned int i = 0; i < 3; ++i) { buildBytes(0x0000, byteStream); //dummy } return true; } bool deserialise(ecl::PushAndPop<unsigned char> & byteStream) { if (byteStream.size() < length+2) { //std::cout << "kobuki_node: kobuki_inertia: deserialise failed. not enough byte stream." << std::endl; return false; } unsigned char header_id, length_packed; buildVariable(header_id, byteStream); buildVariable(length_packed, byteStream); if( header_id != Header::GpInput ) return false; if( length_packed != length ) return false; buildVariable(data.digital_input, byteStream); //for (unsigned int i = 0; i < data.analog_input.size(); ++i) // It's actually sending seven 16-bit variables. // 0-3 : the analog pin inputs // 4 : ??? // 5-6 : 0 for (unsigned int i = 0; i < 4; ++i) { buildVariable(data.analog_input[i], byteStream); } for (unsigned int i = 0; i < 3; ++i) { uint16_t dummy; buildVariable(dummy, byteStream); } //showMe(); return constrain(); } bool constrain() { return true; } void showMe() { } }; } // namespace kobuki #endif /* KOBUKI_GP_INPUT_HPP__ */
27.04386
109
0.517678
[ "vector" ]
aefbc59a572738be796a1f379a41c7c15f52ba94
2,856
cpp
C++
src/hotspot/share/jfr/leakprofiler/utilities/rootType.cpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2020-12-26T04:52:15.000Z
2020-12-26T04:52:15.000Z
src/hotspot/share/jfr/leakprofiler/utilities/rootType.cpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2020-12-26T04:57:19.000Z
2020-12-26T04:57:19.000Z
src/hotspot/share/jfr/leakprofiler/utilities/rootType.cpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2021-12-06T01:13:18.000Z
2021-12-06T01:13:18.000Z
/* * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "gc/shared/oopStorage.hpp" #include "gc/shared/oopStorageSet.hpp" #include "jfr/leakprofiler/utilities/rootType.hpp" #include "utilities/debug.hpp" #include "utilities/enumIterator.hpp" OopStorage* OldObjectRoot::system_oop_storage(System system) { int val = int(system); if (val >= _strong_oop_storage_set_first && val <= _strong_oop_storage_set_last) { using StrongId = OopStorageSet::StrongId; using Underlying = std::underlying_type_t<StrongId>; auto first = static_cast<Underlying>(EnumRange<StrongId>().first()); auto id = static_cast<StrongId>(first + (val - _strong_oop_storage_set_first)); return OopStorageSet::storage(id); } return NULL; } const char* OldObjectRoot::system_description(System system) { OopStorage* oop_storage = system_oop_storage(system); if (oop_storage != NULL) { return oop_storage->name(); } switch (system) { case _system_undetermined: return "<unknown>"; case _universe: return "Universe"; case _threads: return "Threads"; case _class_loader_data: return "Class Loader Data"; case _code_cache: return "Code Cache"; #if INCLUDE_JVMCI case _jvmci: return "JVMCI"; #endif default: ShouldNotReachHere(); } return NULL; } const char* OldObjectRoot::type_description(Type type) { switch (type) { case _type_undetermined: return "<unknown>"; case _stack_variable: return "Stack Variable"; case _local_jni_handle: return "Local JNI Handle"; case _global_jni_handle: return "Global JNI Handle"; case _global_oop_handle: return "Global Object Handle"; case _handle_area: return "Handle Area"; default: ShouldNotReachHere(); } return NULL; }
32.089888
84
0.714636
[ "object" ]
aefecd84ff47d06e6c9fbdd8d0815e4b55de4a73
5,430
hh
C++
Core/Bezier.hh
ThibaultReuille/raindance
79f1f6aeeaf6cbe378e911cd510e6550ae34eb75
[ "BSD-2-Clause" ]
12
2015-01-15T03:30:10.000Z
2022-02-24T21:25:29.000Z
Core/Bezier.hh
ThibaultReuille/raindance
79f1f6aeeaf6cbe378e911cd510e6550ae34eb75
[ "BSD-2-Clause" ]
1
2017-06-06T15:39:21.000Z
2017-06-06T15:39:21.000Z
Core/Bezier.hh
ThibaultReuille/raindance
79f1f6aeeaf6cbe378e911cd510e6550ae34eb75
[ "BSD-2-Clause" ]
4
2015-07-02T22:06:56.000Z
2022-02-24T21:25:30.000Z
#pragma once #include <raindance/Core/Headers.hh> #include <raindance/Core/Geometry.hh> class BezierCurve { public: struct ControlPoint { ControlPoint(const glm::vec3& pos, const glm::vec4& color) : Position(pos), Color(color) {} ControlPoint(const glm::vec4& pos) : Position(pos), Color(glm::vec4(1.0, 1.0, 1.0, 1.0)) {} glm::vec3 Position; glm::vec4 Color; }; struct Vertex { Vertex(const glm::vec3& pos, const glm::vec4& color) : Position(pos), Color(color) {} Vertex(const glm::vec3& pos) : Position(pos), Color(glm::vec4(1.0, 1.0, 1.0, 1.0)) {} glm::vec3 Position; glm::vec4 Color; }; BezierCurve() { m_FirstUpdate = true; m_Divisions = 5; } ~BezierCurve() { } inline void clearControlPoints() { m_ControlPoints.clear(); } inline void addControlPoint(const ControlPoint& point) { m_ControlPoints.push_back(point); } inline ControlPoint getControlPoint(unsigned long i) { return m_ControlPoints[i]; } inline void setControlPoint(unsigned long i, const ControlPoint& cp) { m_ControlPoints[i] = cp; } inline unsigned long size() { return m_ControlPoints.size(); } inline void setDivisions(unsigned int divisions) { m_Divisions = divisions; } void update() { m_VertexBuffer.clear(); for (unsigned int i = 0; i <= m_Divisions; i++) { float t = (float) i / (float) m_Divisions; Vertex vertex = interpolate(m_ControlPoints, t); m_VertexBuffer.push(&vertex, sizeof(Vertex)); } if (m_FirstUpdate) { m_VertexBuffer.describe("a_Position", 3, GL_FLOAT, sizeof(Vertex), 0); m_VertexBuffer.describe("a_Color", 4, GL_FLOAT, sizeof(Vertex), sizeof(glm::vec3)); m_VertexBuffer.generate(Buffer::DYNAMIC); } else { m_VertexBuffer.update(); m_VertexBuffer.describe("a_Position", 3, GL_FLOAT, sizeof(Vertex), 0); m_VertexBuffer.describe("a_Color", 4, GL_FLOAT, sizeof(Vertex), sizeof(glm::vec3)); } m_FirstUpdate = false; } const Vertex interpolate(const std::vector<ControlPoint>& points, const float t) { switch(points.size()) { case 0: case 1: LOG("[BEZIER] Not enough control points to make a curve !\n"); return Vertex(glm::vec3(0, 0, 0), glm::vec4(1.0, 1.0, 1.0, 1.0)); case 2: return Vertex(linear(points[0].Position, points[1].Position, t), linear(points[0].Color, points[1].Color, t)); case 3: return Vertex(quadratic(points[0].Position, points[1].Position, points[2].Position, t), quadratic(points[0].Color, points[1].Color, points[2].Color, t)); case 4: return Vertex(cubic(points[0].Position, points[1].Position, points[2].Position, points[3].Position, t), cubic(points[0].Color, points[1].Color, points[2].Color, points[3].Color, t)); case 5: return Vertex(hypercubic(points[0].Position, points[1].Position, points[2].Position, points[3].Position, points[4].Position, t), hypercubic(points[0].Color, points[1].Color, points[2].Color, points[3].Color, points[4].Color, t)); default: LOG("[BEZIER] High order curves are not supported yet !\n"); // TODO return Vertex(glm::vec3(0, 0, 0), glm::vec4(1.0, 1.0, 1.0, 1.0)); } } static inline glm::vec3 linear(const glm::vec3& a, const glm::vec3& b, const float t) { return a + (b - a) * t; // NOTE : Same as : (1 - t) * a + t * b } static inline glm::vec4 linear(const glm::vec4& a, const glm::vec4& b, const float t) { return a + (b - a) * t; // NOTE : Same as : (1 - t) * a + t * b } static inline glm::vec3 quadratic(const glm::vec3& a, const glm::vec3& b, const glm::vec3& c, const float t) { return linear(linear(a, b, t), linear(b, c, t), t); } static inline glm::vec4 quadratic(const glm::vec4& a, const glm::vec4& b, const glm::vec4& c, const float t) { return linear(linear(a, b, t), linear(b, c, t), t); } static glm::vec3 cubic(const glm::vec3& a, const glm::vec3& b, const glm::vec3& c, const glm::vec3& d, const float t) { return linear(quadratic(a, b, c, t), quadratic(b, c, d, t), t); } static glm::vec4 cubic(const glm::vec4& a, const glm::vec4& b, const glm::vec4& c, const glm::vec4& d, const float t) { return linear(quadratic(a, b, c, t), quadratic(b, c, d, t), t); } static inline glm::vec3 hypercubic(const glm::vec3& a, const glm::vec3& b, const glm::vec3& c, const glm::vec3& d, const glm::vec3& e, const float t) { return linear(cubic(a, b, c, d, t), cubic(b, c, d, e, t), t); } static inline glm::vec4 hypercubic(const glm::vec4& a, const glm::vec4& b, const glm::vec4& c, const glm::vec4& d, const glm::vec4& e, const float t) { return linear(cubic(a, b, c, d, t), cubic(b, c, d, e, t), t); } static inline float bezier(const unsigned int order, const unsigned int nth, const float t) { return binomial(nth, order) * pow(1 - t, order - nth) * pow(t, nth); } static inline unsigned int binomial(unsigned int k, unsigned int n) { return factorial(n) / (factorial(n - k) * factorial(k)); } static unsigned int factorial(unsigned int n) { unsigned int result = 1; for (unsigned int i = 2; i <= n; i++) result *= i; return result; } inline Buffer& getVertexBuffer() { return m_VertexBuffer; } private: std::vector<ControlPoint> m_ControlPoints; unsigned int m_Divisions; Buffer m_VertexBuffer; bool m_FirstUpdate; };
31.206897
153
0.637017
[ "geometry", "vector" ]