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
9964588474c73e22dc4feb6eaba05e645647b616
1,730
cxx
C++
src/srtkThreeDCircularProjectionGeometryXMLFileWriter.cxx
cyrilmory/CyrilsRTK
bb829a9d6aff45181d1642b4b050dde999169ff8
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
src/srtkThreeDCircularProjectionGeometryXMLFileWriter.cxx
cyrilmory/CyrilsRTK
bb829a9d6aff45181d1642b4b050dde999169ff8
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
src/srtkThreeDCircularProjectionGeometryXMLFileWriter.cxx
cyrilmory/CyrilsRTK
bb829a9d6aff45181d1642b4b050dde999169ff8
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/*========================================================================= * * Copyright RTK Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "srtkThreeDCircularProjectionGeometryXMLFileWriter.h" #include <rtkThreeDCircularProjectionGeometryXMLFile.h> namespace rtk { namespace simple { ThreeDCircularProjectionGeometryXMLFileWriter ::ThreeDCircularProjectionGeometryXMLFileWriter() { this->m_Writer = rtk::ThreeDCircularProjectionGeometryXMLFileWriter::New(); } /** Set the filename to write */ void ThreeDCircularProjectionGeometryXMLFileWriter ::SetFilename(const std::string & _arg) { this->m_Writer->SetFilename(_arg); } /** determine whether a file can be opened and read */ int ThreeDCircularProjectionGeometryXMLFileWriter ::CanWriteFile(const char *name) { return this->m_Writer->CanWriteFile(name); } void ThreeDCircularProjectionGeometryXMLFileWriter ::Update() { this->m_Writer->WriteFile(); } void ThreeDCircularProjectionGeometryXMLFileWriter ::SetInput(GeometryType* geometry) { this->m_Writer->SetObject(geometry); } } // end namespace simple } // end namespace rtk
27.903226
77
0.702312
[ "geometry" ]
996c8a296141bf223e95c8d18391aa9a95f195ab
4,514
cc
C++
Codeforces/256 Division 1/Problem C/C.cc
VastoLorde95/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
170
2017-07-25T14:47:29.000Z
2022-01-26T19:16:31.000Z
Codeforces/256 Division 1/Problem C/C.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
null
null
null
Codeforces/256 Division 1/Problem C/C.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
55
2017-07-28T06:17:33.000Z
2021-10-31T03:06:22.000Z
#include <cstdio> #include <iostream> #include <cmath> #include <algorithm> #include <cstring> #include <map> #include <set> #include <vector> #include <utility> #include <queue> #include <stack> #include <cassert> #define sd(x) scanf("%d",&x) #define sd2(x,y) scanf("%d%d",&x,&y) #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define fi first #define se second #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define LET(x, a) __typeof(a) x(a) #define foreach(it, v) for(LET(it, v.begin()); it != v.end(); it++) #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cerr.tie(NULL); #define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout); #define meta __FUNCTION__<<' '<<__LINE__<<' ' #define tr(x) cerr<<meta<<#x<<' '<<x<<'\n'; #define tr2(x,y) cerr<<meta<<#x<<' '<<x<<' '<<#y<<' '<<y<<'\n'; #define tr3(x,y,z) cerr<<meta<<#x<<' '<<x<<' '<<#y<<' '<<y<<' '<<#z<<' '<<z<<'\n'; #define tr4(w,x,y,z) cerr<<meta<<#w<<' '<<w<<' '<<#x<<' ' <<x<<' '<<#y<<' '<<y<<' '<<#z<<' '<<z<<'\n'; #define tr5(v,w,x,y,z) cerr<<meta<<#v<<' '<<v<<' '<<#w<<' '<<w<<' '<<#x<<' '<<x<<' '<<#y<<' '<<y<<' '<<#z<<' '<<z<<'\n'; #define tr6(u,v,w,x,y,z) cerr<<meta<<#u<<' '<<u<<' '<<#v<<' '<<v<<' '<<#w<<' '<<w<<' '<<#x<<' '<<x<<' '<<#y<<' '<<y<<' '<<#z<<' '<<z<<'\n'; using namespace std; const int N = 1<<19; int MOD = 1e9 + 9; struct node{ int sum; void assign(int value){ sum = value; } void combine(node &left, node &right){ sum = left.sum + right.sum; if(sum >= MOD) sum -= MOD; } }; int n, m, a[N], t1[N], t2[N], f[N], sum[N]; node tree[2*N]; // [l, r) void build(int id = 1, int l = 0, int r = n){ if(l+1 == r){ tree[id].assign(a[l]); return; } int left = id<<1, right = left+1, mid = (l+r)>>1; build(left, l, mid); build(right, mid, r); tree[id].combine(tree[left], tree[right]); return; } // range update and utility functions void upd(int id, int l, int r, int x){ // update the current node and its index in the lazy array int temp = sum[r-x]-sum[l-x]; if(temp < 0) temp += MOD; tree[id].sum += temp; if(tree[id].sum >= MOD) tree[id].sum -= MOD; t1[id] += f[l-x+1]; if(t1[id] >= MOD) t1[id] -= MOD; t2[id] += f[l-x]; if(t2[id] >= MOD) t2[id] -= MOD; } void shift(int id,int l,int r){ //propogate update information to the children if(t1[id] > 0 or t2[id] > 0){ int left = id*2, right = left+1, mid = (l+r)/2; int tot = ((1ll*t1[id])*sum[mid-l])%MOD + ((1ll*t2[id])*sum[mid-l-1])%MOD; if(tot >= MOD) tot -= MOD; tree[left].sum += tot; if(tree[left].sum >= MOD) tree[left].sum -= MOD; t1[left] += t1[id]; if(t1[left] >= MOD) t1[left] -= MOD; t2[left] += t2[id]; if(t2[left] >= MOD) t2[left] -= MOD; int to1 = ((1ll*t1[id])*f[mid-l+1])%MOD + ((1ll*t2[id])*f[mid-l])%MOD; if(to1 >= MOD) to1 -= MOD; int to2 = ((1ll*t1[id])*f[mid-l])%MOD + ((1ll*t2[id])*f[mid-l-1])%MOD; if(to2 >= MOD) to2 -= MOD; t1[id] = to1, t2[id] = to2; tot = ((1ll*t1[id])*sum[r-mid])%MOD + ((1ll*t2[id])*sum[r-mid-1])%MOD; if(tot >= MOD) tot -= MOD; tree[right].sum += tot; if(tree[right].sum >= MOD) tree[right].sum -= MOD; t1[right] += t1[id]; if(t1[right] >= MOD) t1[right] -= MOD; t2[right] += t2[id]; if(t2[right] >= MOD) t2[right] -= MOD; t1[id] = t2[id] = 0; } } // range update -> update(x, y, val); void update(int x, int y, int val, int id = 1, int l = 0, int r = n){ if(x >= r or l >= y) return; if(x <= l && r <= y){ upd(id, l, r, val); return; } shift(id, l, r); // pass the updates to the children int left = id<<1, right = left+1, mid = (l+r)>>1; update(x, y, val, left, l, mid); update(x, y, val, right, mid, r); tree[id].combine(tree[left], tree[right]); return; } // range query -> query(x, y); int query(int x, int y, int id = 1, int l = 0, int r = n){ if(x >= r or l >= y) return 0; if(x <= l && r <= y) return tree[id].sum; shift(id, l, r); //use this with lazy propogation int left = id<<1, right = left+1, mid = (l+r)>>1; int ret = query(x, y, left, l, mid) + query(x, y, right, mid, r); if(ret >= MOD) ret -= MOD; return ret; } int main(){ f[1] = 1; for(int i = 2; i < N; i++){ f[i] = f[i-1] + f[i-2]; if(f[i] >= MOD) f[i] -= MOD; } for(int i = 1; i < N; i++){ sum[i] = sum[i-1] + f[i]; if(sum[i] >= MOD) sum[i] -= MOD; } sd2(n, m); for(int i = 0; i < n; i++) sd(a[i]); build(); int type, l, r; while(m--){ sd3(type, l, r); l--, r--; if(type == 1) update(l, r+1, l); else printf("%d\n", query(l, r+1)); } return 0; }
25.794286
139
0.518609
[ "vector" ]
996f035faf536d43f79cbcd0b1c79f0f03c2b042
2,649
hpp
C++
src/instance.hpp
jeffw387/vkaEngine
69bc21d4c10229ab823a887147cb45888d9afbaf
[ "MIT" ]
1
2019-01-12T22:11:32.000Z
2019-01-12T22:11:32.000Z
src/instance.hpp
jeffw387/vkaEngine
69bc21d4c10229ab823a887147cb45888d9afbaf
[ "MIT" ]
1
2019-01-15T23:10:50.000Z
2019-01-16T20:52:19.000Z
src/instance.hpp
jeffw387/vkaEngine
69bc21d4c10229ab823a887147cb45888d9afbaf
[ "MIT" ]
null
null
null
#include <vulkan/vulkan.h> #include <memory> #include <tl/expected.hpp> #include <vector> #include "gsl-lite.hpp" namespace vka { static const char* standard_validation = "VK_LAYER_LUNARG_standard_validation"; class instance { public: explicit instance(VkInstance instance) : m_instance(instance) {} ~instance() { vkDestroyInstance(m_instance, nullptr); } operator VkInstance() { return m_instance; } private: VkInstance m_instance = {}; }; class instance_builder { public: tl::expected<std::unique_ptr<instance>, VkResult> build() { m_create_info.pApplicationInfo = &m_app_info; m_create_info.enabledExtensionCount = static_cast<uint32_t>(m_extensions.size()); m_create_info.ppEnabledExtensionNames = m_extensions.data(); m_create_info.enabledLayerCount = static_cast<uint32_t>(m_layers.size()); m_create_info.ppEnabledLayerNames = m_layers.data(); VkInstance resultInstance = {}; auto result = vkCreateInstance( &m_create_info, nullptr, &resultInstance); if (result != VK_SUCCESS) { return tl::unexpected<VkResult>(result); } return std::make_unique<instance>(resultInstance); } instance_builder& add_extension(const char* name) { m_extensions.push_back(name); return *this; } instance_builder& add_extensions( gsl::span<const char*> names) { m_extensions.insert( std::end(m_extensions), std::begin(names), std::end(names)); return *this; } instance_builder& add_layer(const char* name) { m_layers.push_back(name); return *this; } instance_builder& set_engine_name(const char* name) { m_app_info.pEngineName = name; return *this; } instance_builder& set_app_name(const char* name) { m_app_info.pApplicationName = name; return *this; } instance_builder& set_api_version(int major, int minor, int patch) { m_app_info.apiVersion = VK_MAKE_VERSION(major, minor, patch); return *this; } instance_builder& set_engine_version(int major, int minor, int patch) { m_app_info.engineVersion = VK_MAKE_VERSION(major, minor, patch); return *this; } instance_builder& set_app_version(int major, int minor, int patch) { m_app_info.applicationVersion = VK_MAKE_VERSION(major, minor, patch); return *this; } private: std::vector<const char*> m_extensions = {}; std::vector<const char*> m_layers = {}; VkApplicationInfo m_app_info = { VK_STRUCTURE_TYPE_APPLICATION_INFO}; VkInstanceCreateInfo m_create_info = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; }; } // namespace vka
25.970588
57
0.695734
[ "vector" ]
9975d3e7c371b96ce4de622c086b70a2c7e8244c
9,516
cc
C++
src/attributes/EpsgramDecoderAttributes.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
41
2018-12-07T23:10:50.000Z
2022-02-19T03:01:49.000Z
src/attributes/EpsgramDecoderAttributes.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
59
2019-01-04T15:43:30.000Z
2022-03-31T09:48:15.000Z
src/attributes/EpsgramDecoderAttributes.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
13
2019-01-07T14:36:33.000Z
2021-09-06T14:48:36.000Z
/****************************** LICENSE ******************************* * (C) Copyright 1996-2017 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. ******************************* LICENSE *******************************/ /*! \\file EpsgramDecoderAttributes.h \\brief Definition of EpsgramDecoder Attributes class. This file is automatically generated. Do Not Edit! */ #include "EpsgramDecoderAttributes.h" #include "MagicsParameter.h" #include "ParameterSettings.h" using namespace magics; EpsgramDecoderAttributes::EpsgramDecoderAttributes(): title_(ParameterManager::getStringArray("eps_title")), type_(ParameterManager::getString("eps_type")), database_(ParameterManager::getString("eps_database")), title_text_(ParameterManager::getString("eps_title_text")), param_(ParameterManager::getString("eps_parameter")), param_title_(ParameterManager::getString("eps_parameter_title")), latitude_(ParameterManager::getDouble("eps_latitude")), longitude_(ParameterManager::getDouble("eps_longitude")), param_hour_shift_(ParameterManager::getDouble("eps_parameter_hour_shift")), param_scaling_factor_(ParameterManager::getDouble("eps_parameter_scaling_factor")), param_offset_factor_(ParameterManager::getDouble("eps_parameter_offset_factor")), date_(ParameterManager::getString("eps_date")), time_(ParameterManager::getString("eps_time")), long_title_(ParameterManager::getBool("eps_long_title")), long_title_station_(ParameterManager::getBool("eps_long_title_station")), long_title_height_(ParameterManager::getBool("eps_long_title_height")), long_title_point_(ParameterManager::getBool("eps_long_title_point")), station_(ParameterManager::getString("eps_station_name")), height_(ParameterManager::getDouble("eps_station_height")), correction_(ParameterManager::getBool("eps_temperature_correction")), percentile_(ParameterManager::getDouble("eps_y_axis_percentile")), threshold_(ParameterManager::getDouble("eps_y_axis_threshold")) { } EpsgramDecoderAttributes::~EpsgramDecoderAttributes() { } void EpsgramDecoderAttributes::set(const std::map<string, string>& params) { vector<string> prefix(1); int i = 0; prefix[i++] = "eps"; setAttribute(prefix, "eps_title", title_, params); setAttribute(prefix, "eps_type", type_, params); setAttribute(prefix, "eps_database", database_, params); setAttribute(prefix, "eps_title_text", title_text_, params); setAttribute(prefix, "eps_parameter", param_, params); setAttribute(prefix, "eps_parameter_title", param_title_, params); setAttribute(prefix, "eps_latitude", latitude_, params); setAttribute(prefix, "eps_longitude", longitude_, params); setAttribute(prefix, "eps_parameter_hour_shift", param_hour_shift_, params); setAttribute(prefix, "eps_parameter_scaling_factor", param_scaling_factor_, params); setAttribute(prefix, "eps_parameter_offset_factor", param_offset_factor_, params); setAttribute(prefix, "eps_date", date_, params); setAttribute(prefix, "eps_time", time_, params); setAttribute(prefix, "eps_long_title", long_title_, params); setAttribute(prefix, "eps_long_title_station", long_title_station_, params); setAttribute(prefix, "eps_long_title_height", long_title_height_, params); setAttribute(prefix, "eps_long_title_point", long_title_point_, params); setAttribute(prefix, "eps_station_name", station_, params); setAttribute(prefix, "eps_station_height", height_, params); setAttribute(prefix, "eps_temperature_correction", correction_, params); setAttribute(prefix, "eps_y_axis_percentile", percentile_, params); setAttribute(prefix, "eps_y_axis_threshold", threshold_, params); } void EpsgramDecoderAttributes::copy(const EpsgramDecoderAttributes& other) { title_ = other.title_; type_ = other.type_; database_ = other.database_; title_text_ = other.title_text_; param_ = other.param_; param_title_ = other.param_title_; latitude_ = other.latitude_; longitude_ = other.longitude_; param_hour_shift_ = other.param_hour_shift_; param_scaling_factor_ = other.param_scaling_factor_; param_offset_factor_ = other.param_offset_factor_; date_ = other.date_; time_ = other.time_; long_title_ = other.long_title_; long_title_station_ = other.long_title_station_; long_title_height_ = other.long_title_height_; long_title_point_ = other.long_title_point_; station_ = other.station_; height_ = other.height_; correction_ = other.correction_; percentile_ = other.percentile_; threshold_ = other.threshold_; } bool EpsgramDecoderAttributes::accept(const string& node) { if ( magCompare(node, "epsgram") ) return true; return false; } void EpsgramDecoderAttributes::set(const XmlNode& node) { bool apply = false; if ( this->accept(node.name()) == false ) return; if ( magCompare(node.name(), "epsgram") ) apply = true; if ( apply ) set(node.attributes()); else { } for (auto &elt : node.elements()) { } } void EpsgramDecoderAttributes::print(ostream& out) const { out << "Attributes["; out << " title = " << title_; out << " type = " << type_; out << " database = " << database_; out << " title_text = " << title_text_; out << " param = " << param_; out << " param_title = " << param_title_; out << " latitude = " << latitude_; out << " longitude = " << longitude_; out << " param_hour_shift = " << param_hour_shift_; out << " param_scaling_factor = " << param_scaling_factor_; out << " param_offset_factor = " << param_offset_factor_; out << " date = " << date_; out << " time = " << time_; out << " long_title = " << long_title_; out << " long_title_station = " << long_title_station_; out << " long_title_height = " << long_title_height_; out << " long_title_point = " << long_title_point_; out << " station = " << station_; out << " height = " << height_; out << " correction = " << correction_; out << " percentile = " << percentile_; out << " threshold = " << threshold_; out << "]" << "\n"; } void EpsgramDecoderAttributes::toxml(ostream& out) const { out << "\"epsgram\""; out << ", \"eps_title\":"; niceprint(out,title_); out << ", \"eps_type\":"; niceprint(out,type_); out << ", \"eps_database\":"; niceprint(out,database_); out << ", \"eps_title_text\":"; niceprint(out,title_text_); out << ", \"eps_parameter\":"; niceprint(out,param_); out << ", \"eps_parameter_title\":"; niceprint(out,param_title_); out << ", \"eps_latitude\":"; niceprint(out,latitude_); out << ", \"eps_longitude\":"; niceprint(out,longitude_); out << ", \"eps_parameter_hour_shift\":"; niceprint(out,param_hour_shift_); out << ", \"eps_parameter_scaling_factor\":"; niceprint(out,param_scaling_factor_); out << ", \"eps_parameter_offset_factor\":"; niceprint(out,param_offset_factor_); out << ", \"eps_date\":"; niceprint(out,date_); out << ", \"eps_time\":"; niceprint(out,time_); out << ", \"eps_long_title\":"; niceprint(out,long_title_); out << ", \"eps_long_title_station\":"; niceprint(out,long_title_station_); out << ", \"eps_long_title_height\":"; niceprint(out,long_title_height_); out << ", \"eps_long_title_point\":"; niceprint(out,long_title_point_); out << ", \"eps_station_name\":"; niceprint(out,station_); out << ", \"eps_station_height\":"; niceprint(out,height_); out << ", \"eps_temperature_correction\":"; niceprint(out,correction_); out << ", \"eps_y_axis_percentile\":"; niceprint(out,percentile_); out << ", \"eps_y_axis_threshold\":"; niceprint(out,threshold_); } static MagicsParameter<stringarray> eps_title("eps_title", stringarray()); static MagicsParameter<string> eps_type("eps_type", "eps10"); static MagicsParameter<string> eps_database("eps_database", "/vol/epsgram/data/spotbase/epsdb"); static MagicsParameter<string> eps_title_text("eps_title_text", "EPS Meteogram"); static MagicsParameter<string> eps_parameter("eps_parameter", ""); static MagicsParameter<string> eps_parameter_title("eps_parameter_title", ""); static MagicsParameter<double> eps_latitude("eps_latitude", 0); static MagicsParameter<double> eps_longitude("eps_longitude", 0); static MagicsParameter<double> eps_parameter_hour_shift("eps_parameter_hour_shift", 0); static MagicsParameter<double> eps_parameter_scaling_factor("eps_parameter_scaling_factor", 1); static MagicsParameter<double> eps_parameter_offset_factor("eps_parameter_offset_factor", 0); static MagicsParameter<string> eps_date("eps_date", "-1"); static MagicsParameter<string> eps_time("eps_time", "0000"); static MagicsParameter<string> eps_long_title("eps_long_title", "off"); static MagicsParameter<string> eps_long_title_station("eps_long_title_station", "on"); static MagicsParameter<string> eps_long_title_height("eps_long_title_height", "on"); static MagicsParameter<string> eps_long_title_point("eps_long_title_point", "on"); static MagicsParameter<string> eps_station_name("eps_station_name", ""); static MagicsParameter<double> eps_station_height("eps_station_height", INT_MAX); static MagicsParameter<string> eps_temperature_correction("eps_temperature_correction", "yes"); static MagicsParameter<double> eps_y_axis_percentile("eps_y_axis_percentile", 1); static MagicsParameter<double> eps_y_axis_threshold("eps_y_axis_threshold", 50);
37.464567
96
0.73781
[ "vector" ]
9977371ccecdf0b7beb179a31f22c5ed0f4e70e0
1,539
cpp
C++
HomeworkCodes/outdated/2015_hw3_num_inversions/sample_code/cpp/baseline.cpp
senselab/CodeSensor
a9ba992d2ece3df8019e0d8b4c43e0ec9d811091
[ "BSD-2-Clause" ]
3
2016-07-26T09:22:49.000Z
2022-02-04T09:38:15.000Z
HomeworkCodes/outdated/2015_hw3_num_inversions/sample_code/cpp/baseline.cpp
senselab/CodeSensor
a9ba992d2ece3df8019e0d8b4c43e0ec9d811091
[ "BSD-2-Clause" ]
null
null
null
HomeworkCodes/outdated/2015_hw3_num_inversions/sample_code/cpp/baseline.cpp
senselab/CodeSensor
a9ba992d2ece3df8019e0d8b4c43e0ec9d811091
[ "BSD-2-Clause" ]
2
2017-11-19T23:29:43.000Z
2020-03-06T08:39:21.000Z
#include <cstdio> #include <vector> #include <algorithm> #include <utility> #include <string.h> #include <msgpack.hpp> #include <msgpack/fbuffer.hpp> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdlib.h> #include <time.h> using namespace std; long long int NumberOfInversions( vector<int>& array) { int k, m, t; long long int cnt = 0; int length = array.size(); for ( k =1; k < length; k++) { t = array[k]; for ( m = k-1; m>=0; m--) { if ( array[m] > t) { array[m+1] = array[m]; cnt++; } else break; } array[m+1] = t; } return cnt; } int main() { FILE *fpIn, *fpOut; char *pTok, c; int k, p=2, num_tests; vector<int> NUMBERS; msgpack::sbuffer sbuf; msgpack::unpacked result; struct stat st; size_t off = 0; stat("input.txt", &st); char* buf = new char[st.st_size]; fpIn = fopen("input.txt", "rb"); fread(buf, st.st_size, 1, fpIn ); fclose(fpIn); msgpack::unpack(result, buf, st.st_size, off); result.get().convert(&num_tests); printf("num_tests = %d\n", num_tests); for ( k = 0; k < num_tests; k++) { msgpack::unpack(result, buf, st.st_size, off); result.get().convert(&NUMBERS); long long int n_inv = NumberOfInversions(NUMBERS); printf("length = %lu, inversion = %lld\n", NUMBERS.size(), n_inv); msgpack::pack(&sbuf, n_inv); } assert(off == st.st_size); fpOut = fopen("output.txt", "wb"); fwrite(sbuf.data(), sbuf.size(),1, fpOut); if(fpOut) fclose(fpOut); delete[] buf; return 0; }
15.237624
69
0.606238
[ "vector" ]
99797db822cc2e24f5f097533ea12147ca4b92e4
2,361
hpp
C++
word2vec.hpp
Astromis/tinyEmbeddingsEngine
fea1beb7b3fd32640f788209f79cc47312a20efb
[ "MIT" ]
null
null
null
word2vec.hpp
Astromis/tinyEmbeddingsEngine
fea1beb7b3fd32640f788209f79cc47312a20efb
[ "MIT" ]
null
null
null
word2vec.hpp
Astromis/tinyEmbeddingsEngine
fea1beb7b3fd32640f788209f79cc47312a20efb
[ "MIT" ]
1
2021-01-28T09:38:52.000Z
2021-01-28T09:38:52.000Z
#ifndef _WORD2VEC_H #define _WORD2VEC_H #define MAX_STRING 100 #define EXP_TABLE_SIZE 1000 #define MAX_EXP 6 #define MAX_SENTENCE_LENGTH 1000 #define MAX_CODE_LENGTH 40 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <pthread.h> #include <Eigen/Dense> #include <Eigen/Core> #include <iostream> #include <thread> #include <vector> #include "IEmbeddingModel.hpp" using namespace Eigen; using namespace std; //typedef float real; struct vocab_word { long long cn; int *point; char *word, *code, codelen; }; class Word2Vec: public IEmbeddingModel { private: // internal parameters const int vocab_hash_size = 30000000; // Maximum 30 * 0.7 = 21M words in the vocabulary int *vocab_hash; float starting_alpha; const int table_size = 1e8; int *table; clock_t start; bool read_vocab_flag; //adjustable params char train_file[MAX_STRING]; int cbow = 1, debug_mode = 2, window = 5, min_count = 1, num_threads = 10, min_reduce = 1; long long vocab_max_size = 100000, layer1_size = 50; long long train_words = 0, word_count_actual = 0, iter = 1, file_size = 0, classes = 0; float alpha = 0.025, sample = 1e-3; int hs = 0, negative = 5; protected: struct vocab_word *vocab; float *syn0, *syn1, *syn1neg, *expTable; long long vocab_size = 0; public: Word2Vec(char* _train_file); ~Word2Vec(); //native functions int AddWordToVocab(char *word); int ArgPos(char* str,int argc, char** argv); void CreateBinaryTree(); void InitNet(); void InitUnigramTable(); void LearnVocabFromTrainFile(); void ReadWord(char* word,FILE* fin); int ReadWordIndex(FILE* fin); void ReduceVocab(); int GetWordHash(char *word); int SearchVocab(char* word); void SortVocab(); //void *TrainModelThread(void* id); void TrainModelThread(int id); friend int VocabCompare(const void*a, const void* b); void GetVocab(vector<string> &vocabulary) override; void GetEmbeddingMatrix(MatrixXf &Embeddings) override; void GetEmbeddingMatrix(vector<VectorXf> &Embeddings) override; void clear_mem(); void word2vecStandartInit(); //modified function void TrainModel(); void SaveVocab(char * save_vocab_file); void ReadVocab(char * read_vocab_file); }; #endif
25.387097
94
0.689538
[ "vector" ]
5f56da854b00be85ae0f3f15fa83763c8ebaba9d
2,623
cpp
C++
src/fem/Assembler.cpp
tjhakkin/fluidtissue
4c3757bd9961690cb37ba51fbd89a78e4679b89e
[ "MIT" ]
null
null
null
src/fem/Assembler.cpp
tjhakkin/fluidtissue
4c3757bd9961690cb37ba51fbd89a78e4679b89e
[ "MIT" ]
null
null
null
src/fem/Assembler.cpp
tjhakkin/fluidtissue
4c3757bd9961690cb37ba51fbd89a78e4679b89e
[ "MIT" ]
null
null
null
#include <eigen3/Eigen/Sparse> #include <eigen3/Eigen/Geometry> #include "Assembler.hpp" #include "MathTypes.hpp" #include "common/Utils.hpp" namespace FEM { void Assembler::grad( const Mesh3D& mesh, const VecXd u, std::vector<Vec3f>& grad_t ) const { grad_t.resize( mesh.t().size() ); // 2nd order quadrature rule for P1 element: Quadrature qr(2, mesh.getElement(1)); #pragma omp parallel num_threads( nThreads_ ) { std::vector<Mat34d, Eigen::aligned_allocator<Mat34d>> gphi_global(4); #pragma omp for for (size_t k=0; k<mesh.t().size(); ++k) { auto& t = mesh.t(k); double detB; Mat3d invBt; getElementInfo_ij_( mesh, k, detB, invBt ); for (int j=0; j<4; j++) gphi_global[j] = invBt * qr.gphi()[j]; // NOTE: Assuming here that gradients are constants over elements, i.e., // col(i) = col(j), i,j € [0,3]. So we only compute the gradient at the // first quadrature point (col(0)). Vec3d g = u(t(0)) * gphi_global[0].col(0) + u(t(1)) * gphi_global[1].col(0) + u(t(2)) * gphi_global[2].col(0) + u(t(3)) * gphi_global[3].col(0); grad_t[k] = g.cast<float>(); } } // END pragma omp } void Assembler::grad_nodes( const Mesh3D& mesh, const VecXd u, std::vector<Vec3f>& grad_n ) const { // Gradient interpolation is done by first finding all elements // associated with a node, then setting the node gradient as the average // of the element gradients weighted by element volumes. std::vector<Vec3f> grad_t; grad( mesh, u, grad_t ); grad_n.resize( mesh.p().size() ); // For each node compute the mean normal vector from element normals. #pragma omp parallel for num_threads( nThreads_ ) for (size_t i=0; i<mesh.p().size(); ++i) { VecXi t_idx = mesh.p2t(i); // indices of t's associated with node Vec3f n( 0.0f, 0.0f, 0.0f ); // mean normal // TODO: Currently assuming tetras are all equal size! for (int j=0; j<t_idx.size(); ++j) n += grad_t[ t_idx(j) ]; n /= (float)t_idx.size(); grad_n[i] = n; } } void Assembler::lump_mass( const sparse_matrix& M, sparse_matrix& invM ) const { uint32_t n = M.rows(); VecXd ones = VecXd::Ones(n,1); auto rsum = M * ones; VecXd d = ones.cwiseQuotient( rsum ); sparse_matrix I(n,n); I.setIdentity(); invM = d.asDiagonal() * I; // much faster than calling sparseView() } } // END namespace
30.149425
81
0.580633
[ "mesh", "geometry", "vector" ]
5f67f3959e0acaa46fad3318eba92ae0be44e083
1,210
cpp
C++
Implementation/ Manasa and Stones.cpp
StavrosChryselis/hackerrank
42a3e393231e237a99a9e54522ce3ec954bf614f
[ "MIT" ]
null
null
null
Implementation/ Manasa and Stones.cpp
StavrosChryselis/hackerrank
42a3e393231e237a99a9e54522ce3ec954bf614f
[ "MIT" ]
null
null
null
Implementation/ Manasa and Stones.cpp
StavrosChryselis/hackerrank
42a3e393231e237a99a9e54522ce3ec954bf614f
[ "MIT" ]
null
null
null
/* **************************************************************** **************************************************************** -> Coded by Stavros Chryselis -> Visit my github for more solved problems over multiple sites -> https://github.com/StavrosChryselis -> Feel free to email me at stavrikios@gmail.com **************************************************************** **************************************************************** */ #include <set> #include <stdio.h> #include <vector> using namespace std; int N, A, B; inline void init() { scanf("%d %d %d", &N, &A, &B); } inline void solve() { set< pair<int, int > > Q; int i; Q.insert(make_pair(1, 0)); while(Q.begin()->first != N) { Q.insert(make_pair(Q.begin()->first + 1, Q.begin()->second + A)); Q.insert(make_pair(Q.begin()->first + 1, Q.begin()->second + B)); Q.erase(Q.begin()); } for(set<pair<int ,int> >::iterator ii = Q.begin(); ii != Q.end(); ii++) printf("%d ", ii->second); putchar('\n'); } int main() { int T; scanf("%d", &T); while(T--) { init(); solve(); } return 0; }
20.862069
75
0.404959
[ "vector" ]
5f697450d94d5b36ed6e7e3ce951e8b9713458d8
42,142
cpp
C++
pepnovo/src/QCDAT.cpp
compomics/jwrapper-pepnovo
1bd21a4910d7515dfab7747711917176a6b5ce99
[ "Apache-2.0" ]
null
null
null
pepnovo/src/QCDAT.cpp
compomics/jwrapper-pepnovo
1bd21a4910d7515dfab7747711917176a6b5ce99
[ "Apache-2.0" ]
null
null
null
pepnovo/src/QCDAT.cpp
compomics/jwrapper-pepnovo
1bd21a4910d7515dfab7747711917176a6b5ce99
[ "Apache-2.0" ]
null
null
null
#include "QuickClustering.h" #include "base64.h" DAT_FileBuff::~DAT_FileBuff() { if (buff && pos>buff) flush_buff(); if (buff) delete [] buff; } void DAT_FileBuff::init(string& _path, int dat_buff_size) { if (! ind_was_initialized) { buff = new char[dat_buff_size]; if (! buff) { cout << "Error: couldn't allocate memory for DAT file buff!" << endl; exit(1); } } ind_was_initialized = 1; path = _path; max_pos = buff + dat_buff_size - 100; pos = buff; ind_first_write = 1; } // copies the files to the DAT file void DAT_FileBuff::add_spec_to_DAT_file( mass_t m_over_z, int charge, int mzxml_file_idx, int scan_number, float retention_time, float precursor_intensity, int num_peaks, char *peak_buff) { const int spec_bytes = sizeof(mass_t) + 4 * sizeof(int) + 2 * sizeof(float) * num_peaks; if (num_peaks<=2) { //cout << mzxml_file_idx << " " << scan_number << " " << " p: " << num_peaks << endl; return; } if (mzxml_file_idx<0 || scan_number<0) { cout <<"Error: bad file idx or scan number! " << mzxml_file_idx << ", " << scan_number << endl; exit(1); } if (pos + spec_bytes >= max_pos) flush_buff(); mass_t *m_ptr = (mass_t *)pos; *m_ptr++ = m_over_z; int *i_ptr = (int *)m_ptr; *i_ptr++ = charge; *i_ptr++ = mzxml_file_idx; *i_ptr++ = scan_number; *i_ptr++ = num_peaks; float *f_ptr = (float *)i_ptr; *f_ptr++ = retention_time; *f_ptr++ = precursor_intensity; pos = (char *)f_ptr; memcpy(pos,peak_buff,2 * sizeof(float) * num_peaks); pos += 2 * sizeof(float) * num_peaks; this->counter++; } void DAT_FileBuff::flush_buff() { FILE* dat_stream; if (pos == buff) return; if (! ind_was_initialized) { cout << "Error: must first initialize the DAT_FileBuff!" << endl; exit(1); } if (ind_first_write) { dat_stream=fopen(path.c_str(),"wb"); ind_first_write = 0; } else dat_stream=fopen(path.c_str(),"ab"); if (! dat_stream) { cout << "Error: couldn't open DAT file for writing: " << path.c_str() << endl; exit(1); } fwrite(buff,1,pos-buff,dat_stream); fclose(dat_stream); pos=buff; } void DAT_Converter::init_DAT_Converter(mass_t _max_m_over_z, mass_t _mass_increment, int _dat_buff_size) { // name = _name; // out_dir = _out_dir; max_m_over_z = _max_m_over_z; mass_increment = _mass_increment; dat_buff_size = _dat_buff_size; max_dat_file_idx = (int)(max_m_over_z / mass_increment) + 1; dat_buffs.resize(max_dat_file_idx+1); ind_was_initialized =1; } // creates a file with the list of DAT files void DAT_Converter::create_list_file() const { FILE *list_stream; ostringstream oss; oss << batch; string list_path = out_dir + "/" + name + "_" + oss.str() + "_list.txt"; list_stream = fopen(list_path.c_str(),"w"); if (! list_stream) { cout << "Error: couldn't open list file for writing: " << list_path.c_str() << endl; exit(1); } int i; for (i=0; i<dat_buffs.size(); i++) { if (dat_buffs[i].buff) { fprintf(list_stream,"%s\n",dat_buffs[i].path.c_str()); } } fclose(list_stream); } int DAT_Converter::convert_single_non_MZXML_file_to_DAT(Config* config, string file, mass_t min_m_over_z, mass_t max_m_over_z, int file_idx) { static QCPeak *peak_buff=NULL; static float *dat_peak_buff=NULL; if (! peak_buff) { peak_buff = new QCPeak[20000]; dat_peak_buff = new float[40000]; } if (! peak_buff || ! dat_peak_buff) { cout << "Error: couldn't allocate memory for DAT conversion!" << endl; exit(1); } if (! ind_was_initialized) { cout << "Error: must initialize DAT_Converter!" << endl; exit(0); } vector<string> list; list.push_back(file); BasicSpecReader bsr; FileManager fm; FileSet all_spec_fs; fm.init_from_list(config,list,true,file_idx); all_spec_fs.select_all_files(fm); const int total_spectra = all_spec_fs.get_total_spectra(); const vector<SingleSpectrumFile *>& all_ssf = all_spec_fs.get_ssf_pointers(); cout << file_idx << " " << file << " ... " << endl; int num_spectra_extracted=0; int i; for (i=0; i<all_ssf.size(); i++) { SingleSpectrumFile *ssf = all_ssf[i]; // no small spectra if (ssf->num_peaks<5 || ssf->m_over_z<=min_m_over_z || ssf->m_over_z > max_m_over_z) continue; int j,pos=0; int num_spec_peaks = bsr.read_basic_spec(config,fm,ssf,peak_buff,true); if (num_spec_peaks<5) continue; mass_t m_over_z = ssf->m_over_z; int scan_number=-1, file_idx=-1; float precursor_intensity=0; if (ssf->type == DTA) { file_idx = 0; scan_number=-1; } else if (ssf->type == MGF) { MGF_single *mgf_single = (MGF_single *)ssf; file_idx = mgf_single->file_idx; scan_number = (mgf_single->scan_number > 0 ? mgf_single->scan_number : mgf_single->idx_in_file); // cout << "s " << mgf_single->scan_number << "\tidx " << mgf_single->idx_in_file << endl; } else if (ssf->type == MZXML) { MZXML_single *mzxml_single = (MZXML_single *)ssf; file_idx = mzxml_single->file_idx; scan_number = mzxml_single->scan_number; precursor_intensity = mzxml_single->precursor_intensity; } else if (ssf->type == DAT) { DAT_single *dat_single = (DAT_single *)ssf; file_idx = dat_single->mzxml_file_idx; scan_number = dat_single->scan_number; } // copy peaks for (j=0; j<num_spec_peaks; j++) { dat_peak_buff[pos++]=(float)peak_buff[j].mass; dat_peak_buff[pos++]=(float)peak_buff[j].intensity; } // add spectrum int DAT_file_idx = (int)(m_over_z/mass_increment); if (DAT_file_idx > max_dat_file_idx) DAT_file_idx = max_dat_file_idx; if (! dat_buffs[DAT_file_idx].ind_was_initialized) { ostringstream os,os_batch; os << DAT_file_idx; os_batch << batch; string path = out_dir + "/" + name + "_" + os_batch.str() + "_" + os.str() + ".dat"; dat_buffs[DAT_file_idx].init(path,dat_buff_size); } int charge = ssf->charge; if (charge<0 || charge>1000) charge=0; dat_buffs[DAT_file_idx].add_spec_to_DAT_file( m_over_z, charge, file_idx, scan_number,ssf->retention_time, precursor_intensity, num_spec_peaks, (char *)dat_peak_buff); num_spectra_extracted++; } cout << num_spectra_extracted << " spectra..." << endl; return num_spectra_extracted; } int DAT_Converter::convert_PKL_dir_to_DAT(Config* config, char *file_list, int file_start_idx, mass_t min_m_over_z, mass_t max_m_over_z) { FILE *list_stream=fopen(file_list,"r"); if (! list_stream) { cout << "Error: couldn't open pkl dir list for reading: " << file_list << endl; exit(1); } char line_buff[1024]; cout << "Read pkl files (idx path #spectra):" << endl; int total_extracted=0; int pkl_dir_idx=0; while (fgets(line_buff,1024,list_stream)) { istringstream is(line_buff); string pkl_dir_path = ""; string tsv_file = ""; is >> pkl_dir_path >> tsv_file; if (pkl_dir_path.length()>2 && tsv_file.length() >2) { FileManager fm; fm.init_from_single_pkl_dir(config, pkl_dir_path, tsv_file, pkl_dir_idx, min_m_over_z, max_m_over_z); FileSet fs; fs.select_all_files(fm); const vector<SingleSpectrumFile *>& all_ssf = fs.get_ssf_pointers(); cout << pkl_dir_idx << "\t" << pkl_dir_path << "\t" << all_ssf.size() << endl; static QCPeak *peak_buff=NULL; static float *dat_peak_buff=NULL; if (! peak_buff) { peak_buff = new QCPeak[20000]; dat_peak_buff = new float[40000]; } if (! peak_buff || ! dat_peak_buff) { cout << "Error: couldn't allocate memory for DAT conversion!" << endl; exit(1); } if (! ind_was_initialized) { cout << "Error: must initialize DAT_Converter!" << endl; exit(0); } BasicSpecReader bsr; int num_spectra_extracted=0; int i; for (i=0; i<all_ssf.size(); i++) { PKL_single *ssf = (PKL_single *)all_ssf[i]; // no small spectra if (ssf->num_peaks<5 || ssf->m_over_z<=min_m_over_z || ssf->m_over_z > max_m_over_z) continue; int j,pos=0; int num_spec_peaks = bsr.read_basic_spec(config,fm,ssf,peak_buff,true); if (num_spec_peaks<5) continue; mass_t m_over_z = ssf->m_over_z; int scan_number=ssf->scan_number; float precursor_intensity= (ssf->precursor_intensity >0 ? ssf->precursor_intensity : 0); // copy peaks for (j=0; j<num_spec_peaks; j++) { dat_peak_buff[pos++]=(float)peak_buff[j].mass; dat_peak_buff[pos++]=(float)peak_buff[j].intensity; } // add spectrum int DAT_file_idx = (int)(m_over_z/mass_increment); if (DAT_file_idx > max_dat_file_idx) DAT_file_idx = max_dat_file_idx; if (! dat_buffs[DAT_file_idx].ind_was_initialized) { ostringstream os,os_batch; os << DAT_file_idx; os_batch << batch; string path = out_dir + "/" + name + "_" + os_batch.str() + "_" + os.str() + ".dat"; dat_buffs[DAT_file_idx].init(path,dat_buff_size); } int charge = ssf->charge; if (charge<0 || charge>1000) charge=0; dat_buffs[DAT_file_idx].add_spec_to_DAT_file( m_over_z, charge, pkl_dir_idx + file_start_idx, scan_number,ssf->retention_time, precursor_intensity, num_spec_peaks, (char *)dat_peak_buff); num_spectra_extracted++; } cout << "(" << num_spectra_extracted << ")" << endl; total_extracted += num_spectra_extracted; pkl_dir_idx++; } } return total_extracted; } void DAT_Converter::convert_files_to_DAT_on_the_fly(Config* config, char *file_list, char * _out_dir, char * _name, int _batch, mass_t min_m_over_z, mass_t max_m_over_z, int file_start_idx, bool ind_is_pkl_dir) { name = _name; out_dir = _out_dir; batch = _batch; int num_spectra_extracted=0; name = _name; out_dir = _out_dir; if (! ind_was_initialized) { cout << "Error: must initialize DAT_Converter!" << endl; exit(0); } if (ind_is_pkl_dir) { num_spectra_extracted = convert_PKL_dir_to_DAT(config,file_list, file_start_idx, min_m_over_z,max_m_over_z); } else { vector<string> list; read_paths_into_list(file_list,list); cout << endl << endl <<"Extracting spectra and writing dat files for " << list.size() << " Files. " << endl << endl; int i; for (i=0; i<list.size(); i++) { int file_type = get_file_extension_type(list[i]); if (file_type == MZXML) { num_spectra_extracted += parse_single_MZXML_file(config,list[i],file_start_idx+i, min_m_over_z,max_m_over_z); } else { num_spectra_extracted += convert_single_non_MZXML_file_to_DAT(config,list[i], min_m_over_z,max_m_over_z,file_start_idx+i); } } } int d; for (d=0; d<dat_buffs.size(); d++) { if (dat_buffs[d].ind_was_initialized && dat_buffs[d].pos > dat_buffs[d].buff) dat_buffs[d].flush_buff(); } cout << "Total spectra extracted and converted to DAT: " << num_spectra_extracted << endl; create_list_file(); } int DAT_Converter::parse_single_MZXML_file(Config *config, string& mzxml_name, int file_idx, mass_t min_m_over_z, mass_t max_m_over_z) { static char* Buffer = NULL; static char* DecodedPeakBuffer = NULL; static float* Peaks = NULL; static float* FilteredPeaks = NULL; static int PeakBufferSize = 0; int Trail; static char* PrecursorStr; int FloatIndex; char* ByteOrderStr; int ByteOrderLittle = 1; int BytesToRead; int BufferStartPos = 0; int BytesRead; int BufferEnd = 0; FILE* MZXMLFile; int ParseState = 0; int FilePos = 0; // allocate if (! Buffer) Buffer = (char*)calloc(XML_BUFFER_SIZE + 1, sizeof(char)); MZXMLFile = fopen(mzxml_name.c_str(), "rb"); if (!MZXMLFile) { cout << "Error: Can't open MZXML file " << mzxml_name << endl; exit(1); } printf("File idx %d , '%s'...\n",file_idx, mzxml_name.c_str()); int idx_in_file = 0; int spec_counter =0; char *scan_start_ptr = NULL; while (1) { char* ScanStr; char* ScanNumberStr; int ScanNumber; char* MSLevelStr; int MSLevel; char *PrecursorStr; mass_t PrecursorMZ; char *retentionTimeStr; float retentionTime; char *precursorIntensityStr; float precursorIntensity; char* PeakStr; char* PeakBuffer; int BufferPos; // Read more data, to fill up the buffer: if ( ! scan_start_ptr || ( (Buffer + BufferEnd - scan_start_ptr) < XML_BUFFER_HALF_SIZE) ) { // try shunt half of the buffer if (scan_start_ptr) { if (BufferEnd - XML_BUFFER_HALF_SIZE>0) { memmove(Buffer, Buffer + XML_BUFFER_HALF_SIZE, BufferEnd - XML_BUFFER_HALF_SIZE); BufferEnd -= XML_BUFFER_HALF_SIZE; scan_start_ptr -= XML_BUFFER_HALF_SIZE; // cout << "MOVED!" << endl; } } else scan_start_ptr = Buffer; BytesToRead = XML_BUFFER_SIZE - BufferEnd; BytesRead = fread(Buffer + BufferEnd, sizeof(char), BytesToRead, MZXMLFile); if (BytesRead<5) break; BufferEnd += BytesRead; Buffer[BufferEnd] = '\0'; FilePos += BytesRead; } // Look for a new <scan tag opening: // this scan cannot be done with strstr since there might be NULL termination const char *last_pos = Buffer + BufferEnd - 5; char *pos = scan_start_ptr; while (++pos<last_pos) { if (*pos != '<') continue; if (*(pos+1)=='s' && *(pos+2)=='c' && *(pos+3)=='a' && *(pos+4)=='n') break; } ScanStr = (pos<last_pos) ? pos : NULL; if (ScanStr) { // if this is the case, read over more data to avoid the case where // the spectrum's record is not all in the buffer if (scan_start_ptr - Buffer > XML_BUFFER_HALF_SIZE) { scan_start_ptr = ScanStr-2; continue; } BufferPos = ScanStr - Buffer; } else { BufferPos = 0; } if (!ScanStr ) { scan_start_ptr = Buffer + BufferEnd-5; continue; } ScanNumberStr = strstr(ScanStr, "num="); if (!ScanNumberStr) { // printf("** Warning: mzXML parser encountered a scan with no scan number! File %s Pos %d\n", // mzxml_name.c_str(), FilePos + BufferPos - BufferEnd); ScanNumber = -1; } else { ScanNumber = ParseIntFromXML(ScanNumberStr); scan_start_ptr = ScanNumberStr; } retentionTimeStr = strstr(ScanStr,"retentionTime=\"PT"); if (! retentionTimeStr) { retentionTime = -1; } else { retentionTime = ParseMassFromXML(retentionTimeStr); } char *PeakCountStr = strstr(ScanStr, "peaksCount=\""); if (!PeakCountStr) { cout << "Warning: bad parsing peaks in mzxml. " << endl; cout << "Scan: " << ScanNumber << " Pos: " << FilePos << endl; scan_start_ptr += 50; continue; } int PeakCount = ParseIntFromXML(PeakCountStr); MSLevelStr = strstr(ScanStr, "msLevel="); if (!MSLevelStr) { printf("** Warning: mzXML parser encountered a scan with no scan level! File %s Pos %d\n", mzxml_name.c_str(), FilePos + BufferPos - BufferEnd); scan_start_ptr += 50; continue; } else { MSLevel = ParseIntFromXML(MSLevelStr); } if (MSLevel<=1) { scan_start_ptr += 50; continue; } precursorIntensityStr = strstr(ScanStr,"precursorIntensity="); if (! precursorIntensityStr) { cout << "Warning: no precursor intensity found for scan " << ScanNumber << " pos: " << BufferPos << endl; scan_start_ptr += 50; continue; } else { precursorIntensity = ParseMassFromXML(precursorIntensityStr); } PrecursorStr = strstr(ScanStr, "<precursorMz"); if (PrecursorStr) { PrecursorStr = strstr(PrecursorStr, ">"); PrecursorMZ = ParseMassFromXML(PrecursorStr); } if (!PrecursorStr && MSLevel > 1) { printf("Warning: mzXML parser encountered a scan with no m/z: File %s Pos %d\n", mzxml_name.c_str(), FilePos + BufferPos - BufferEnd); scan_start_ptr += 50; continue; } // check that this is a good spectrum to output if (MSLevel>1 && PeakCount>2 && PrecursorMZ>= min_m_over_z && PrecursorMZ <= max_m_over_z) { // read peaks PeakStr = strstr(PrecursorStr, "<peaks"); if (PeakStr) { // Get byte order: ByteOrderStr = strstr(PeakStr, "byteOrder=\""); if (ByteOrderStr) { ByteOrderStr += 11; if (!strncmp(ByteOrderStr, "network", 7)) { ByteOrderLittle = 0; } if (!strncmp(ByteOrderStr, "big", 3)) { ByteOrderLittle = 0; } if (!strncmp(ByteOrderStr, "little", 6)) { ByteOrderLittle = 1; } } PeakStr = strstr(PeakStr, ">"); } if (!PeakStr) { cout << "Warning couldn't find peaks tag for scan: " << ScanNumber << " Buffer pos: " << BufferPos << " skipping..." << endl; scan_start_ptr += 50; continue; } PeakStr++; PeakBuffer = PeakStr; if (PeakBufferSize < PeakCount) { if (DecodedPeakBuffer) { char *dbf = DecodedPeakBuffer; free(DecodedPeakBuffer); DecodedPeakBuffer = NULL; free(Peaks); Peaks = NULL; free(FilteredPeaks); FilteredPeaks=NULL; } PeakBufferSize = (int)(PeakCount*1.5); DecodedPeakBuffer = (char*)calloc(PeakBufferSize * 8 + 8, 1); Peaks = (float*)calloc(PeakBufferSize * 2, sizeof(float)); FilteredPeaks = (float*)calloc(PeakBufferSize * 2, sizeof(float)); } Trail = (PeakCount % 3); int pbf = PeakBufferSize; if (!(PeakCount % 3)) { PeakBuffer[PeakCount * 32/3] = '\0'; } else { PeakBuffer[(PeakCount * 32/3) + Trail + 1] = '\0'; } b64_decode_mio( DecodedPeakBuffer, PeakBuffer); for (FloatIndex = 0; FloatIndex < (2 * PeakCount); FloatIndex++) { #ifdef BYTEORDER_LITTLE_ENDIAN if (!ByteOrderLittle) { char ByteSwap = DecodedPeakBuffer[FloatIndex*4]; DecodedPeakBuffer[FloatIndex*4] = DecodedPeakBuffer[FloatIndex*4 + 3]; DecodedPeakBuffer[FloatIndex*4 + 3] = ByteSwap; ByteSwap = DecodedPeakBuffer[FloatIndex*4 + 1]; DecodedPeakBuffer[FloatIndex*4 + 1] = DecodedPeakBuffer[FloatIndex*4 + 2]; DecodedPeakBuffer[FloatIndex*4 + 2] = ByteSwap; } memcpy(Peaks + FloatIndex, DecodedPeakBuffer + FloatIndex * 4, 4); #else if (ByteOrderLittle) { char ByteSwap = DecodedPeakBuffer[FloatIndex*4]; DecodedPeakBuffer[FloatIndex*4] = DecodedPeakBuffer[FloatIndex*4 + 3]; DecodedPeakBuffer[FloatIndex*4 + 3] = ByteSwap; ByteSwap = DecodedPeakBuffer[FloatIndex*4 + 1]; DecodedPeakBuffer[FloatIndex*4 + 1] = DecodedPeakBuffer[FloatIndex*4 + 2]; DecodedPeakBuffer[FloatIndex*4 + 2] = ByteSwap; } memcpy(Peaks + FloatIndex, DecodedPeakBuffer + FloatIndex * 4, 4); #endif } // add spectrum int DAT_file_idx = (int)(PrecursorMZ/mass_increment); if (DAT_file_idx > max_dat_file_idx) DAT_file_idx = max_dat_file_idx; if (! dat_buffs[DAT_file_idx].ind_was_initialized) { ostringstream os, os_batch; os << DAT_file_idx; os_batch << batch; string path = out_dir + "/" + name + "_" + os_batch.str() + "_" + os.str() + ".dat"; dat_buffs[DAT_file_idx].init(path,dat_buff_size); } // join and filter peaks int new_num_peaks = join_and_filter_peak_list(config,PrecursorMZ,Peaks, PeakCount,FilteredPeaks); if (new_num_peaks>3) { dat_buffs[DAT_file_idx].add_spec_to_DAT_file(PrecursorMZ, 0, file_idx, ScanNumber, retentionTime, precursorIntensity, new_num_peaks, (char *)FilteredPeaks); spec_counter++; } scan_start_ptr = PeakStr + 8 * PeakCount; } else scan_start_ptr = ScanStr +50; } fclose(MZXMLFile); cout << spec_counter << " spectra..." << endl << endl; return spec_counter; } void create_annotated_mgf_from_dat(Config *config, char *dat_list, char *mzxml_list, char *anns_file, char *output_file) { vector<string> list, mzxml_names; read_paths_into_list(dat_list,list); vector< vector<int> > annotation_idxs; vector<mzXML_annotation> annotations; read_mzXML_annotations(mzxml_list,anns_file, annotation_idxs, annotations); FileManager fm; fm.init_from_list_file_and_add_annotations(config,dat_list,annotation_idxs,annotations,true); FileSet fs; fs.select_all_files(fm); const vector<SingleSpectrumFile *>& all_ssf = fs.get_ssf_pointers(); BasicSpecReader bsr; int i; ofstream mgf_stream(output_file); QCPeak peaks[5000]; for (i=0; i<all_ssf.size(); i++) { int num_spec_peaks = bsr.read_basic_spec(config,fm,all_ssf[i],peaks); BasicSpectrum bs; bs.num_peaks = num_spec_peaks; bs.peaks = peaks; bs.ssf = all_ssf[i]; bs.ssf->charge = 2; DAT_single *dat_single = (DAT_single *)all_ssf[i]; char single_name[256]; sprintf(single_name,"spec_%d_%d",dat_single->mzxml_file_idx,dat_single->scan_number); bs.ssf->single_name = single_name; bs.output_to_mgf(mgf_stream,config); } mgf_stream.close(); } int parse_single_MZXML_file_print_peaks(Config *config, string& mzxml_name, int the_scan) { static char* Buffer = NULL; static char* DecodedPeakBuffer = NULL; static float* Peaks = NULL; static float* FilteredPeaks = NULL; static int PeakBufferSize = 0; int Trail; static char* PrecursorStr; int FloatIndex; char* ByteOrderStr; int ByteOrderLittle = 1; int BytesToRead; int BufferStartPos = 0; int BytesRead; int BufferEnd = 0; FILE* MZXMLFile; int ParseState = 0; int FilePos = 0; // allocate if (! Buffer) Buffer = (char*)calloc(XML_BUFFER_SIZE + 1, sizeof(char)); MZXMLFile = fopen(mzxml_name.c_str(), "rb"); if (!MZXMLFile) { cout << "Error: Can't open MZXML file " << mzxml_name << endl; exit(1); } int idx_in_file = 0; int spec_counter =0; char *scan_start_ptr = NULL; while (1) { char* ScanStr; char* ScanNumberStr; int ScanNumber; char* MSLevelStr; int MSLevel; char *PrecursorStr; mass_t PrecursorMZ; char *retentionTimeStr; float retentionTime; char *precursorIntensityStr; float precursorIntensity; char* PeakStr; char* PeakBuffer; int BufferPos; // Read more data, to fill up the buffer: if ( ! scan_start_ptr || ( (Buffer + BufferEnd - scan_start_ptr) < XML_BUFFER_HALF_SIZE) ) { // try shunt half of the buffer if (scan_start_ptr) { if (BufferEnd - XML_BUFFER_HALF_SIZE>0) { memmove(Buffer, Buffer + XML_BUFFER_HALF_SIZE, BufferEnd - XML_BUFFER_HALF_SIZE); BufferEnd -= XML_BUFFER_HALF_SIZE; scan_start_ptr -= XML_BUFFER_HALF_SIZE; // cout << "MOVED!" << endl; } } else scan_start_ptr = Buffer; BytesToRead = XML_BUFFER_SIZE - BufferEnd; BytesRead = fread(Buffer + BufferEnd, sizeof(char), BytesToRead, MZXMLFile); if (BytesRead<5) break; BufferEnd += BytesRead; Buffer[BufferEnd] = '\0'; // remove all '\0' from buffer (these cause parsing errors. // replace them with ' ' // const char *end_ptr = Buffer + BufferEnd - 2; // for (char *ptr=Buffer; ptr<end_ptr; ptr++) // if (*ptr == '\0') // *ptr = ' '; FilePos += BytesRead; } // Look for a new <scan tag opening: // this scan cannot be done with strstr since there might be NULL termination const char *last_pos = Buffer + BufferEnd - 5; char *pos = scan_start_ptr; while (++pos<last_pos) { if (*pos != '<') continue; if (*(pos+1)=='s' && *(pos+2)=='c' && *(pos+3)=='a' && *(pos+4)=='n') break; } ScanStr = (pos<last_pos) ? pos : NULL; if (ScanStr) { // if this is the case, read over more data to avoid the case where // the spectrum's record is not all in the buffer if (scan_start_ptr - Buffer > XML_BUFFER_HALF_SIZE) { scan_start_ptr = ScanStr-2; continue; } BufferPos = ScanStr - Buffer; } else { BufferPos = 0; } if (!ScanStr ) { scan_start_ptr = Buffer + BufferEnd-5; continue; } ScanNumberStr = strstr(ScanStr, "num="); if (!ScanNumberStr) { // printf("** Warning: mzXML parser encountered a scan with no scan number! File %s Pos %d\n", // mzxml_name.c_str(), FilePos + BufferPos - BufferEnd); ScanNumber = -1; } else { ScanNumber = ParseIntFromXML(ScanNumberStr); scan_start_ptr = ScanNumberStr; } retentionTimeStr = strstr(ScanStr,"retentionTime=\"PT"); if (! retentionTimeStr) { // printf("Error: mzXML parser encountered a scan with no retnetion time: File %s Pos %d\n", // mzxml_name.c_str(), FilePos + BufferPos - BufferEnd); // cout <<"SCANSTR:"<<endl << ScanStr << endl; // exit(1); retentionTime = -1; } else { retentionTime = ParseMassFromXML(retentionTimeStr); } char *PeakCountStr = strstr(ScanStr, "peaksCount=\""); if (!PeakCountStr) { cout << "Warning: bad parsing peaks in mzxml. " << endl; cout << "Scan: " << ScanNumber << " Pos: " << FilePos << endl; scan_start_ptr += 50; continue; // exit(1); } int PeakCount = ParseIntFromXML(PeakCountStr); MSLevelStr = strstr(ScanStr, "msLevel="); if (!MSLevelStr) { printf("** Warning: mzXML parser encountered a scan with no scan level! File %s Pos %d\n", mzxml_name.c_str(), FilePos + BufferPos - BufferEnd); scan_start_ptr += 50; continue; } else { MSLevel = ParseIntFromXML(MSLevelStr); } if (MSLevel<=1) { scan_start_ptr += 50; continue; } if (ScanNumber != the_scan) { scan_start_ptr += 150; continue; } precursorIntensityStr = strstr(ScanStr,"precursorIntensity="); if (! precursorIntensityStr) { cout << "Warning: no precursor intensity found for scan " << ScanNumber << " pos: " << BufferPos << endl; scan_start_ptr += 50; continue; } else { precursorIntensity = ParseMassFromXML(precursorIntensityStr); } PrecursorStr = strstr(ScanStr, "<precursorMz"); if (PrecursorStr) { PrecursorStr = strstr(PrecursorStr, ">"); PrecursorMZ = ParseMassFromXML(PrecursorStr); } if (!PrecursorStr && MSLevel > 1) { printf("Warning: mzXML parser encountered a scan with no m/z: File %s Pos %d\n", mzxml_name.c_str(), FilePos + BufferPos - BufferEnd); scan_start_ptr += 50; continue; } // check that this is a good spectrum to output if (MSLevel>1 && PeakCount>2) { // read peaks PeakStr = strstr(PrecursorStr, "<peaks"); if (PeakStr) { // Get byte order: ByteOrderStr = strstr(PeakStr, "byteOrder=\""); if (ByteOrderStr) { ByteOrderStr += 11; if (!strncmp(ByteOrderStr, "network", 7)) { ByteOrderLittle = 0; } if (!strncmp(ByteOrderStr, "big", 3)) { ByteOrderLittle = 0; } if (!strncmp(ByteOrderStr, "little", 6)) { ByteOrderLittle = 1; } } PeakStr = strstr(PeakStr, ">"); } if (!PeakStr) { cout << "Warning couldn't find peaks tag for scan: " << ScanNumber << " Buffer pos: " << BufferPos << " skipping..." << endl; scan_start_ptr += 50; continue; } PeakStr++; PeakBuffer = PeakStr; if (PeakBufferSize < PeakCount) { if (DecodedPeakBuffer) { char *dbf = DecodedPeakBuffer; free(DecodedPeakBuffer); DecodedPeakBuffer = NULL; free(Peaks); Peaks = NULL; free(FilteredPeaks); FilteredPeaks=NULL; } PeakBufferSize = (int)(PeakCount*1.5); DecodedPeakBuffer = (char*)calloc(PeakBufferSize * 8 + 8, 1); Peaks = (float*)calloc(PeakBufferSize * 2, sizeof(float)); FilteredPeaks = (float*)calloc(PeakBufferSize * 2, sizeof(float)); } Trail = (PeakCount % 3); if (!(PeakCount % 3)) { PeakBuffer[PeakCount * 32/3] = '\0'; } else { PeakBuffer[(PeakCount * 32/3) + Trail + 1] = '\0'; } // cout << "dd " << spec_counter << " " << ScanNumber << endl; b64_decode_mio( DecodedPeakBuffer, PeakBuffer); for (FloatIndex = 0; FloatIndex < (2 * PeakCount); FloatIndex++) { #ifdef BYTEORDER_LITTLE_ENDIAN if (!ByteOrderLittle) { char ByteSwap = DecodedPeakBuffer[FloatIndex*4]; DecodedPeakBuffer[FloatIndex*4] = DecodedPeakBuffer[FloatIndex*4 + 3]; DecodedPeakBuffer[FloatIndex*4 + 3] = ByteSwap; ByteSwap = DecodedPeakBuffer[FloatIndex*4 + 1]; DecodedPeakBuffer[FloatIndex*4 + 1] = DecodedPeakBuffer[FloatIndex*4 + 2]; DecodedPeakBuffer[FloatIndex*4 + 2] = ByteSwap; } memcpy(Peaks + FloatIndex, DecodedPeakBuffer + FloatIndex * 4, 4); #else if (ByteOrderLittle) { char ByteSwap = DecodedPeakBuffer[FloatIndex*4]; DecodedPeakBuffer[FloatIndex*4] = DecodedPeakBuffer[FloatIndex*4 + 3]; DecodedPeakBuffer[FloatIndex*4 + 3] = ByteSwap; ByteSwap = DecodedPeakBuffer[FloatIndex*4 + 1]; DecodedPeakBuffer[FloatIndex*4 + 1] = DecodedPeakBuffer[FloatIndex*4 + 2]; DecodedPeakBuffer[FloatIndex*4 + 2] = ByteSwap; } memcpy(Peaks + FloatIndex, DecodedPeakBuffer + FloatIndex * 4, 4); #endif } // add spectrum int i; for (i=0; i<FloatIndex; i+=2) { cout << fixed << setprecision(3) << Peaks[i] << " " << Peaks[i+1] << endl; } exit(0); // join and filter peaks } else scan_start_ptr = ScanStr +50; } fclose(MZXMLFile); cout << spec_counter << " spectra..." << endl << endl; return spec_counter; } int DAT_Converter::parse_annotated_spectra_from_single_MZXML( Config *config, string& mzxml_name, int file_idx, map<mzXML_annotation,int>& ann_map) { static char* Buffer = NULL; static char* DecodedPeakBuffer = NULL; static float* Peaks = NULL; static float* FilteredPeaks = NULL; static int PeakBufferSize = 0; int Trail; static char* PrecursorStr; int FloatIndex; char* ByteOrderStr; int ByteOrderLittle = 1; int BytesToRead; int BufferStartPos = 0; int BytesRead; int BufferEnd = 0; FILE* MZXMLFile; int ParseState = 0; int FilePos = 0; // allocate if (! Buffer) Buffer = (char*)calloc(XML_BUFFER_SIZE + 1, sizeof(char)); MZXMLFile = fopen(mzxml_name.c_str(), "rb"); if (!MZXMLFile) { cout << "Error: Can't open MZXML file " << mzxml_name << endl; exit(1); } printf("File idx %d , '%s'...\n",file_idx, mzxml_name.c_str()); int idx_in_file = 0; int spec_counter =0; char *scan_start_ptr = NULL; while (1) { char* ScanStr; char* ScanNumberStr; int ScanNumber; char* MSLevelStr; int MSLevel; char *PrecursorStr; mass_t PrecursorMZ; char *retentionTimeStr; float retentionTime; char *precursorIntensityStr; float precursorIntensity; char* PeakStr; char* PeakBuffer; int BufferPos; // Read more data, to fill up the buffer: if ( ! scan_start_ptr || ( (Buffer + BufferEnd - scan_start_ptr) < XML_BUFFER_HALF_SIZE) ) { // try shunt half of the buffer if (scan_start_ptr) { if (BufferEnd - XML_BUFFER_HALF_SIZE>0) { memmove(Buffer, Buffer + XML_BUFFER_HALF_SIZE, BufferEnd - XML_BUFFER_HALF_SIZE); BufferEnd -= XML_BUFFER_HALF_SIZE; scan_start_ptr -= XML_BUFFER_HALF_SIZE; // cout << "MOVED!" << endl; } } else scan_start_ptr = Buffer; BytesToRead = XML_BUFFER_SIZE - BufferEnd; BytesRead = fread(Buffer + BufferEnd, sizeof(char), BytesToRead, MZXMLFile); if (BytesRead<5) break; BufferEnd += BytesRead; Buffer[BufferEnd] = '\0'; FilePos += BytesRead; } // Look for a new <scan tag opening: // this scan cannot be done with strstr since there might be NULL termination const char *last_pos = Buffer + BufferEnd - 5; char *pos = scan_start_ptr; while (++pos<last_pos) { if (*pos != '<') continue; if (*(pos+1)=='s' && *(pos+2)=='c' && *(pos+3)=='a' && *(pos+4)=='n') break; } ScanStr = (pos<last_pos) ? pos : NULL; if (ScanStr) { // if this is the case, read over more data to avoid the case where // the spectrum's record is not all in the buffer if (scan_start_ptr - Buffer > XML_BUFFER_HALF_SIZE) { scan_start_ptr = ScanStr-2; continue; } BufferPos = ScanStr - Buffer; } else { BufferPos = 0; } if (!ScanStr ) { scan_start_ptr = Buffer + BufferEnd-5; continue; } ScanNumberStr = strstr(ScanStr, "num="); if (!ScanNumberStr) { // printf("** Warning: mzXML parser encountered a scan with no scan number! File %s Pos %d\n", // mzxml_name.c_str(), FilePos + BufferPos - BufferEnd); ScanNumber = -1; } else { ScanNumber = ParseIntFromXML(ScanNumberStr); scan_start_ptr = ScanNumberStr; } retentionTimeStr = strstr(ScanStr,"retentionTime=\"PT"); if (! retentionTimeStr) { retentionTime = -1; } else { retentionTime = ParseMassFromXML(retentionTimeStr); } char *PeakCountStr = strstr(ScanStr, "peaksCount=\""); if (!PeakCountStr) { cout << "Warning: bad parsing peaks in mzxml. " << endl; cout << "Scan: " << ScanNumber << " Pos: " << FilePos << endl; scan_start_ptr += 50; continue; } int PeakCount = ParseIntFromXML(PeakCountStr); MSLevelStr = strstr(ScanStr, "msLevel="); if (!MSLevelStr) { printf("** Warning: mzXML parser encountered a scan with no scan level! File %s Pos %d\n", mzxml_name.c_str(), FilePos + BufferPos - BufferEnd); scan_start_ptr += 50; continue; } else { MSLevel = ParseIntFromXML(MSLevelStr); } if (MSLevel<=1) { scan_start_ptr += 50; continue; } precursorIntensityStr = strstr(ScanStr,"precursorIntensity="); if (! precursorIntensityStr) { cout << "Warning: no precursor intensity found for scan " << ScanNumber << " pos: " << BufferPos << endl; scan_start_ptr += 50; continue; } else { precursorIntensity = ParseMassFromXML(precursorIntensityStr); } PrecursorStr = strstr(ScanStr, "<precursorMz"); if (PrecursorStr) { PrecursorStr = strstr(PrecursorStr, ">"); PrecursorMZ = ParseMassFromXML(PrecursorStr); } if (!PrecursorStr && MSLevel > 1) { printf("Warning: mzXML parser encountered a scan with no m/z: File %s Pos %d\n", mzxml_name.c_str(), FilePos + BufferPos - BufferEnd); scan_start_ptr += 50; continue; } // check if this spectrum is in the list of annotated spectra // if not, don't output it. bool is_annotated_spectrum = false; map<mzXML_annotation,int>::const_iterator it; mzXML_annotation ann_pos; ann_pos.mzXML_file_idx = file_idx; ann_pos.scan = ScanNumber; it = ann_map.find(ann_pos); if (it != ann_map.end()) is_annotated_spectrum = true; // check that this is a good spectrum to output if (MSLevel>1 && PeakCount>2 && is_annotated_spectrum) { // read peaks PeakStr = strstr(PrecursorStr, "<peaks"); if (PeakStr) { // Get byte order: ByteOrderStr = strstr(PeakStr, "byteOrder=\""); if (ByteOrderStr) { ByteOrderStr += 11; if (!strncmp(ByteOrderStr, "network", 7)) { ByteOrderLittle = 0; } if (!strncmp(ByteOrderStr, "big", 3)) { ByteOrderLittle = 0; } if (!strncmp(ByteOrderStr, "little", 6)) { ByteOrderLittle = 1; } } PeakStr = strstr(PeakStr, ">"); } if (!PeakStr) { cout << "Warning couldn't find peaks tag for scan: " << ScanNumber << " Buffer pos: " << BufferPos << " skipping..." << endl; scan_start_ptr += 50; continue; } PeakStr++; PeakBuffer = PeakStr; if (PeakBufferSize < PeakCount) { if (DecodedPeakBuffer) { char *dbf = DecodedPeakBuffer; free(DecodedPeakBuffer); DecodedPeakBuffer = NULL; free(Peaks); Peaks = NULL; free(FilteredPeaks); FilteredPeaks=NULL; } PeakBufferSize = (int)(PeakCount*1.5); DecodedPeakBuffer = (char*)calloc(PeakBufferSize * 8 + 8, 1); Peaks = (float*)calloc(PeakBufferSize * 2, sizeof(float)); FilteredPeaks = (float*)calloc(PeakBufferSize * 2, sizeof(float)); } Trail = (PeakCount % 3); if (!(PeakCount % 3)) { PeakBuffer[PeakCount * 32/3] = '\0'; } else { PeakBuffer[(PeakCount * 32/3) + Trail + 1] = '\0'; } b64_decode_mio( DecodedPeakBuffer, PeakBuffer); for (FloatIndex = 0; FloatIndex < (2 * PeakCount); FloatIndex++) { #ifdef BYTEORDER_LITTLE_ENDIAN if (!ByteOrderLittle) { char ByteSwap = DecodedPeakBuffer[FloatIndex*4]; DecodedPeakBuffer[FloatIndex*4] = DecodedPeakBuffer[FloatIndex*4 + 3]; DecodedPeakBuffer[FloatIndex*4 + 3] = ByteSwap; ByteSwap = DecodedPeakBuffer[FloatIndex*4 + 1]; DecodedPeakBuffer[FloatIndex*4 + 1] = DecodedPeakBuffer[FloatIndex*4 + 2]; DecodedPeakBuffer[FloatIndex*4 + 2] = ByteSwap; } memcpy(Peaks + FloatIndex, DecodedPeakBuffer + FloatIndex * 4, 4); #else if (ByteOrderLittle) { char ByteSwap = DecodedPeakBuffer[FloatIndex*4]; DecodedPeakBuffer[FloatIndex*4] = DecodedPeakBuffer[FloatIndex*4 + 3]; DecodedPeakBuffer[FloatIndex*4 + 3] = ByteSwap; ByteSwap = DecodedPeakBuffer[FloatIndex*4 + 1]; DecodedPeakBuffer[FloatIndex*4 + 1] = DecodedPeakBuffer[FloatIndex*4 + 2]; DecodedPeakBuffer[FloatIndex*4 + 2] = ByteSwap; } memcpy(Peaks + FloatIndex, DecodedPeakBuffer + FloatIndex * 4, 4); #endif } // add spectrum int DAT_file_idx = (int)(PrecursorMZ/mass_increment); if (DAT_file_idx > max_dat_file_idx) DAT_file_idx = max_dat_file_idx; if (! dat_buffs[DAT_file_idx].ind_was_initialized) { ostringstream os, os_batch; os << DAT_file_idx; os_batch << batch; string path = out_dir + "/" + name + "_" + os_batch.str() + "_" + os.str() + ".dat"; dat_buffs[DAT_file_idx].init(path,dat_buff_size); } // join and filter peaks int new_num_peaks = join_and_filter_peak_list(config,PrecursorMZ,Peaks, PeakCount,FilteredPeaks); if (new_num_peaks>3) { dat_buffs[DAT_file_idx].add_spec_to_DAT_file(PrecursorMZ, 0, file_idx, ScanNumber, retentionTime, precursorIntensity, new_num_peaks, (char *)FilteredPeaks); spec_counter++; } scan_start_ptr = PeakStr + 8 * PeakCount; } else scan_start_ptr = ScanStr +50; } fclose(MZXMLFile); cout << spec_counter << " spectra..." << endl << endl; return spec_counter; } /******************************************************************************* Create DAT files only for annoated spectra ********************************************************************************/ void DAT_Converter::create_dat_files_for_anns(Config *config, char *mzXML_list, char *anns_file, char *_out_dir, char *_name) { map<mzXML_annotation,int> ann_map; // read_mzXML_annotations_to_map(anns_file,ann_map); vector<string> list; read_paths_into_list(mzXML_list,list); init_DAT_Converter((float)2000.0,(float)20.0,524288); name = _name; out_dir = _out_dir; batch = 0; int num_spectra_parsed=0; int f; for (f=0; f<list.size(); f++) { num_spectra_parsed += parse_annotated_spectra_from_single_MZXML( config, list[f], f, ann_map); } int d; for (d=0; d<dat_buffs.size(); d++) { if (dat_buffs[d].ind_was_initialized && dat_buffs[d].pos > dat_buffs[d].buff) dat_buffs[d].flush_buff(); } cout << "Total spectra extracted and converted to DAT: " << num_spectra_parsed << endl; create_list_file(); }
25.024941
131
0.598714
[ "vector" ]
5f7144368fe2748fbfdd5bdfaea1c96510b2c97d
1,331
cpp
C++
bootstrap/Game.cpp
deadglow/AIE-bootstrap-pathfinding
158ee426f896413d47293f3803a1a7aae687da21
[ "MIT" ]
1
2019-06-03T05:35:58.000Z
2019-06-03T05:35:58.000Z
bootstrap/Game.cpp
deadglow/AIE-bootstrap-pathfinding
158ee426f896413d47293f3803a1a7aae687da21
[ "MIT" ]
1
2019-05-29T00:41:13.000Z
2020-02-20T13:07:00.000Z
bootstrap/Game.cpp
deadglow/AIE-bootstrap-pathfinding
158ee426f896413d47293f3803a1a7aae687da21
[ "MIT" ]
null
null
null
#include "Game.h" #include "Application.h" #include "Input.h" #include "imgui_glfw3.h" namespace aie { Game::Game(const char* title, int width, int height, bool fullscreen) { // Create the Application. Application::Create(title, width, height, fullscreen); // Create the Input manager. Input::Create(); // Initalise ImGui. GLFWwindow* window = Application::GetInstance()->GetWindowPtr(); ImGui_Init(window, true); } Game::~Game() { // Destroy ImGui ImGui_Shutdown(); // Destroy the input system Input::Destroy(); // Destroy the Application Application::Destroy(); } void Game::Run() { Application* application = Application::GetInstance(); // Start game loop if successfully initialised. if (application) { // Loop while game is running. while (!application->GetQuitting()) { // Clear input. Input::GetInstance()->ClearStatus(); // Update the application. Must be after input has been cleared. application->Update(); // Skip if minimised. if (application->GetMinimised()) continue; // Clear ImGui ImGui_NewFrame(); // Update the Application Update(application->GetDeltaTime()); // Draw the Application Draw(); // Draw ImGui last. ImGui::Render(); // Present backbuffer to the monitor application->SwapBuffers(); } } } } // namespace aie
18.486111
69
0.677686
[ "render" ]
5f740fbafd12fa5c64044aa75b133288a60a7c43
2,237
cpp
C++
jpc/native/textbox/src/binding.cpp
Jim00000/RMMZ-Plugin-Collection
5bb530dd1fd1f6300ac10808f7e3734570c04d5d
[ "MIT" ]
3
2020-09-09T13:21:16.000Z
2021-03-30T02:35:33.000Z
jpc/native/textbox/src/binding.cpp
Jim00000/RMMZ-Plugin-Collection
5bb530dd1fd1f6300ac10808f7e3734570c04d5d
[ "MIT" ]
4
2020-09-09T07:18:06.000Z
2020-10-08T14:48:08.000Z
jpc/native/textbox/src/binding.cpp
Jim00000/RMMZ-Plugin-Collection
5bb530dd1fd1f6300ac10808f7e3734570c04d5d
[ "MIT" ]
6
2020-09-08T18:52:59.000Z
2022-03-04T10:31:38.000Z
#include <napi.h> #include <windows.h> #include "textbox.h" namespace { const std::wstring utf8ToWchar(const std::string& utf8) { std::wstring wchar(utf8.size(), 0); MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), utf8.size(), const_cast<LPWSTR>(wchar.c_str()), wchar.size()); return wchar; } const std::string wcharToUtf8(const std::wstring wstr) { const int needed_sz = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL); std::string utf8(needed_sz, 0); WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), wstr.size(), const_cast<LPSTR>(utf8.c_str()), utf8.size(), NULL, NULL); return utf8; } Napi::String registerOpenTextBox(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); std::wstring wOutputText; const uint32_t win_x = info[0].As<Napi::Number>().Int32Value(); const uint32_t win_y = info[1].As<Napi::Number>().Int32Value(); const uint32_t width = info[2].As<Napi::Number>().Int32Value(); const uint32_t height = info[3].As<Napi::Number>().Int32Value(); const std::string utf8_title = info[4].As<Napi::String>().Utf8Value(); JPC::TextBox::open(utf8ToWchar(utf8_title).c_str(), wOutputText, win_x, win_y, width, height); return Napi::String::New(env, wcharToUtf8(wOutputText)); } Napi::Object Init(Napi::Env env, Napi::Object exports) { exports.Set(Napi::String::New(env, "openTextBox"), Napi::Function::New(env, registerOpenTextBox)); return exports; } } NODE_API_MODULE(textbox, Init); /* MIT License Copyright (c) 2021 Jim00000 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. */
38.568966
125
0.680823
[ "object" ]
5f75ca254a2133e0ccc081b62329ffda3958e156
8,403
cpp
C++
Samples/ArchiveUtility/Sources/ArchiveUtility.cpp
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
28
2015-09-22T21:43:32.000Z
2022-02-28T01:35:01.000Z
Samples/ArchiveUtility/Sources/ArchiveUtility.cpp
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
98
2015-01-22T03:21:27.000Z
2022-03-02T01:47:00.000Z
Samples/ArchiveUtility/Sources/ArchiveUtility.cpp
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
4
2019-02-21T16:45:25.000Z
2022-02-18T13:40:04.000Z
/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include <iostream> #include "Stroika/Foundation/Characters/ToString.h" #include "Stroika/Foundation/DataExchange/Archive/Reader.h" #include "Stroika/Foundation/Debug/Trace.h" #include "Stroika/Foundation/Execution/CommandLine.h" #if qHasFeature_LZMA #include "Stroika/Foundation/DataExchange/Archive/7z/Reader.h" #endif #if qHasFeature_ZLib #include "Stroika/Foundation/DataExchange/Archive/Zip/Reader.h" #endif #include "Stroika/Foundation/IO/FileSystem/Directory.h" #include "Stroika/Foundation/IO/FileSystem/FileInputStream.h" #include "Stroika/Foundation/IO/FileSystem/FileOutputStream.h" #include "Stroika/Foundation/IO/FileSystem/PathName.h" #include "Stroika/Foundation/Streams/MemoryStream.h" #include "Stroika/Foundation/Streams/TextReader.h" using namespace std; using namespace Stroika::Foundation; #if qHasFeature_LZMA || qHasFeature_ZLib using namespace Stroika::Foundation::DataExchange; #endif using namespace Stroika::Foundation::Streams; using Characters::String; using Containers::Sequence; using Memory::BLOB; namespace { struct Options_ { enum class Operation { eList, eExtract, eCreate, eUpdate }; Operation fOperation; filesystem::path fArchiveFileName; optional<filesystem::path> fOutputDirectory; // applies only if extract optional<Sequence<String>> fFiles2Add; optional<bool> fNoFailOnMissingLibrary; // for regression tests }; void Usage_ () { cerr << "Usage: ArchiveUtility (--help | -h) | (--no-fail-on-missing-library) | ((--list | --create | --extract |--update) ARCHIVENAME [--outputDirectory D] [FILES])" << endl; cerr << " --help prints this help" << endl; cerr << " -h prints this help" << endl; cerr << " --no-fail-on-missing-library just warns when we fail because of missing library" << endl; cerr << " --list prints all the files in the argument archive" << endl; cerr << " --create creates the argument ARHCIVE and adds the argument FILES to it" << endl; cerr << " --extract extracts all the files from the argument ARHCIVE and to the output directory specified by --ouptutDirectory (defaulting to .)" << endl; cerr << " --update adds to the argument ARHCIVE and adds the argument FILES to it" << endl; cerr << " ARCHIVENAME can be the single character - to designate stdin" << endl; // NYI } // Emits errors to stderr, and Usage, etc, if needed, and not Optional<> has_value() optional<Options_> ParseOptions_ (int argc, const char* argv[]) { Options_ result{}; Sequence<String> args = Execution::ParseCommandLine (argc, argv); optional<Options_::Operation> operation; optional<String> archiveName; optional<bool> noFailOnMissingLibrary; for (auto argi = args.begin (); argi != args.end (); ++argi) { if (argi == args.begin ()) { continue; // skip argv[0] - command name } if (Execution::MatchesCommandLineArgument (*argi, L"h") or Execution::MatchesCommandLineArgument (*argi, L"help")) { Usage_ (); return optional<Options_>{}; } else if (Execution::MatchesCommandLineArgument (*argi, L"no-fail-on-missing-library")) { noFailOnMissingLibrary = true; } else if (Execution::MatchesCommandLineArgument (*argi, L"list")) { operation = Options_::Operation::eList; } else if (Execution::MatchesCommandLineArgument (*argi, L"create")) { operation = Options_::Operation::eCreate; } else if (Execution::MatchesCommandLineArgument (*argi, L"extract")) { operation = Options_::Operation::eExtract; } else if (Execution::MatchesCommandLineArgument (*argi, L"update")) { operation = Options_::Operation::eUpdate; } else if (not archiveName.has_value ()) { archiveName = *argi; } // else more cases todo } if (not archiveName) { cerr << "Missing name of archive" << endl; Usage_ (); return optional<Options_>{}; } if (not operation) { cerr << "Missing operation" << endl; Usage_ (); return optional<Options_>{}; } result.fOperation = *operation; result.fArchiveFileName = IO::FileSystem::ToPath (*archiveName); // @todo add more.. - files etc result.fNoFailOnMissingLibrary = noFailOnMissingLibrary; return result; } } namespace { DataExchange::Archive::Reader OpenArchive_ (const filesystem::path& archiveName) { // @todo - must support other formats, have a registry, and autodetect #if qHasFeature_LZMA if (IO::FileSystem::FromPath (archiveName).EndsWith (L".7z", Characters::CompareOptions::eCaseInsensitive)) { return move (Archive::_7z::Reader{IO::FileSystem::FileInputStream::New (archiveName)}); } #endif #if qHasFeature_ZLib if (IO::FileSystem::FromPath (archiveName).EndsWith (L".zip", Characters::CompareOptions::eCaseInsensitive)) { return move (Archive::Zip::Reader{IO::FileSystem::FileInputStream::New (archiveName)}); } #endif Execution::Throw (Execution::Exception{L"Unrecognized format"sv}); } } namespace { void ListArchive_ (const filesystem::path& archiveName) { for (String i : OpenArchive_ (archiveName).GetContainedFiles ()) { cout << i.AsNarrowSDKString () << endl; } } void ExtractArchive_ (const filesystem::path& archiveName, const filesystem::path& toDirectory) { Debug::TraceContextBumper ctx{L"ExtractArchive_"}; DbgTrace (L"(archiveName=%s, toDir=%s)", archiveName.c_str (), toDirectory.c_str ()); DataExchange::Archive::Reader archive{OpenArchive_ (archiveName)}; for (String i : archive.GetContainedFiles ()) { String srcFileName = i; filesystem::path trgFileName = toDirectory / IO::FileSystem::ToPath (srcFileName); //DbgTrace (L"(srcFileName=%s, trgFileName=%s)", Characters::ToString (srcFileName).c_str (), Characters::ToString (trgFileName).c_str ()); BLOB b = archive.GetData (srcFileName); //DbgTrace (L"IO::FileSystem::GetFileDirectory (trgFileName)=%s", IO::FileSystem::GetFileDirectory (trgFileName).c_str ()); create_directories (trgFileName.parent_path ()); IO::FileSystem::FileOutputStream::Ptr ostream = IO::FileSystem::FileOutputStream::New (trgFileName); ostream.Write (b); } } } int main (int argc, const char* argv[]) { Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"main", L"argv=%s", Characters::ToString (vector<const char*>{argv, argv + argc}).c_str ())}; if (optional<Options_> o = ParseOptions_ (argc, argv)) { try { switch (o->fOperation) { case Options_::Operation::eList: ListArchive_ (o->fArchiveFileName); break; case Options_::Operation::eExtract: ExtractArchive_ (o->fArchiveFileName, o->fOutputDirectory.value_or (L".")); break; default: cerr << "that option NYI" << endl; break; } } catch (...) { String exceptMsg = Characters::ToString (current_exception ()); cerr << "Exception: " << exceptMsg.AsNarrowSDKString () << " - terminating..." << endl; if (o->fNoFailOnMissingLibrary.value_or (false)) { #if !qHasFeature_LZMA || !qHasFeature_ZLib if (exceptMsg.Contains (L"Unrecognized format"sv)) { return EXIT_SUCCESS; } #endif } return EXIT_FAILURE; } } else { return EXIT_FAILURE; } return EXIT_SUCCESS; }
43.092308
183
0.610377
[ "vector" ]
5f7ead745b4a9979a382357759c8e1f9b3f7b58f
107,472
cc
C++
organizations/organizations.pb.cc
MruV-RP/mruv-pb-cpp
84bbde324c1c484d11909ac4b380c19a0db394ba
[ "MIT" ]
null
null
null
organizations/organizations.pb.cc
MruV-RP/mruv-pb-cpp
84bbde324c1c484d11909ac4b380c19a0db394ba
[ "MIT" ]
2
2020-11-22T15:45:25.000Z
2020-11-25T09:51:53.000Z
organizations/organizations.pb.cc
MruV-RP/mruv-pb-cpp
84bbde324c1c484d11909ac4b380c19a0db394ba
[ "MIT" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: organizations/organizations.proto #include "organizations/organizations.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> namespace mruv { namespace organizations { class CreateOrganizationRequestDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<CreateOrganizationRequest> _instance; } _CreateOrganizationRequest_default_instance_; class CreateOrganizationResponseDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<CreateOrganizationResponse> _instance; } _CreateOrganizationResponse_default_instance_; class GetOrganizationRequestDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<GetOrganizationRequest> _instance; } _GetOrganizationRequest_default_instance_; class GetOrganizationResponseDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<GetOrganizationResponse> _instance; } _GetOrganizationResponse_default_instance_; class UpdateOrganizationRequestDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<UpdateOrganizationRequest> _instance; } _UpdateOrganizationRequest_default_instance_; class UpdateOrganizationResponseDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<UpdateOrganizationResponse> _instance; } _UpdateOrganizationResponse_default_instance_; class DeleteOrganizationRequestDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<DeleteOrganizationRequest> _instance; } _DeleteOrganizationRequest_default_instance_; class DeleteOrganizationResponseDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<DeleteOrganizationResponse> _instance; } _DeleteOrganizationResponse_default_instance_; class AssignLeaderRequestDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<AssignLeaderRequest> _instance; } _AssignLeaderRequest_default_instance_; class AssignLeaderResponseDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<AssignLeaderResponse> _instance; } _AssignLeaderResponse_default_instance_; class UnassignLeaderRequestDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<UnassignLeaderRequest> _instance; } _UnassignLeaderRequest_default_instance_; class UnassignLeaderResponseDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<UnassignLeaderResponse> _instance; } _UnassignLeaderResponse_default_instance_; } // namespace organizations } // namespace mruv static void InitDefaultsscc_info_AssignLeaderRequest_organizations_2forganizations_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::mruv::organizations::_AssignLeaderRequest_default_instance_; new (ptr) ::mruv::organizations::AssignLeaderRequest(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::mruv::organizations::AssignLeaderRequest::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_AssignLeaderRequest_organizations_2forganizations_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_AssignLeaderRequest_organizations_2forganizations_2eproto}, {}}; static void InitDefaultsscc_info_AssignLeaderResponse_organizations_2forganizations_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::mruv::organizations::_AssignLeaderResponse_default_instance_; new (ptr) ::mruv::organizations::AssignLeaderResponse(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::mruv::organizations::AssignLeaderResponse::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_AssignLeaderResponse_organizations_2forganizations_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_AssignLeaderResponse_organizations_2forganizations_2eproto}, {}}; static void InitDefaultsscc_info_CreateOrganizationRequest_organizations_2forganizations_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::mruv::organizations::_CreateOrganizationRequest_default_instance_; new (ptr) ::mruv::organizations::CreateOrganizationRequest(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::mruv::organizations::CreateOrganizationRequest::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_CreateOrganizationRequest_organizations_2forganizations_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_CreateOrganizationRequest_organizations_2forganizations_2eproto}, {}}; static void InitDefaultsscc_info_CreateOrganizationResponse_organizations_2forganizations_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::mruv::organizations::_CreateOrganizationResponse_default_instance_; new (ptr) ::mruv::organizations::CreateOrganizationResponse(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::mruv::organizations::CreateOrganizationResponse::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_CreateOrganizationResponse_organizations_2forganizations_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_CreateOrganizationResponse_organizations_2forganizations_2eproto}, {}}; static void InitDefaultsscc_info_DeleteOrganizationRequest_organizations_2forganizations_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::mruv::organizations::_DeleteOrganizationRequest_default_instance_; new (ptr) ::mruv::organizations::DeleteOrganizationRequest(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::mruv::organizations::DeleteOrganizationRequest::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_DeleteOrganizationRequest_organizations_2forganizations_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_DeleteOrganizationRequest_organizations_2forganizations_2eproto}, {}}; static void InitDefaultsscc_info_DeleteOrganizationResponse_organizations_2forganizations_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::mruv::organizations::_DeleteOrganizationResponse_default_instance_; new (ptr) ::mruv::organizations::DeleteOrganizationResponse(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::mruv::organizations::DeleteOrganizationResponse::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_DeleteOrganizationResponse_organizations_2forganizations_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_DeleteOrganizationResponse_organizations_2forganizations_2eproto}, {}}; static void InitDefaultsscc_info_GetOrganizationRequest_organizations_2forganizations_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::mruv::organizations::_GetOrganizationRequest_default_instance_; new (ptr) ::mruv::organizations::GetOrganizationRequest(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::mruv::organizations::GetOrganizationRequest::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_GetOrganizationRequest_organizations_2forganizations_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_GetOrganizationRequest_organizations_2forganizations_2eproto}, {}}; static void InitDefaultsscc_info_GetOrganizationResponse_organizations_2forganizations_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::mruv::organizations::_GetOrganizationResponse_default_instance_; new (ptr) ::mruv::organizations::GetOrganizationResponse(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::mruv::organizations::GetOrganizationResponse::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_GetOrganizationResponse_organizations_2forganizations_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_GetOrganizationResponse_organizations_2forganizations_2eproto}, {}}; static void InitDefaultsscc_info_UnassignLeaderRequest_organizations_2forganizations_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::mruv::organizations::_UnassignLeaderRequest_default_instance_; new (ptr) ::mruv::organizations::UnassignLeaderRequest(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::mruv::organizations::UnassignLeaderRequest::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_UnassignLeaderRequest_organizations_2forganizations_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_UnassignLeaderRequest_organizations_2forganizations_2eproto}, {}}; static void InitDefaultsscc_info_UnassignLeaderResponse_organizations_2forganizations_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::mruv::organizations::_UnassignLeaderResponse_default_instance_; new (ptr) ::mruv::organizations::UnassignLeaderResponse(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::mruv::organizations::UnassignLeaderResponse::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_UnassignLeaderResponse_organizations_2forganizations_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_UnassignLeaderResponse_organizations_2forganizations_2eproto}, {}}; static void InitDefaultsscc_info_UpdateOrganizationRequest_organizations_2forganizations_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::mruv::organizations::_UpdateOrganizationRequest_default_instance_; new (ptr) ::mruv::organizations::UpdateOrganizationRequest(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::mruv::organizations::UpdateOrganizationRequest::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_UpdateOrganizationRequest_organizations_2forganizations_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_UpdateOrganizationRequest_organizations_2forganizations_2eproto}, {}}; static void InitDefaultsscc_info_UpdateOrganizationResponse_organizations_2forganizations_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::mruv::organizations::_UpdateOrganizationResponse_default_instance_; new (ptr) ::mruv::organizations::UpdateOrganizationResponse(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::mruv::organizations::UpdateOrganizationResponse::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_UpdateOrganizationResponse_organizations_2forganizations_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_UpdateOrganizationResponse_organizations_2forganizations_2eproto}, {}}; static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_organizations_2forganizations_2eproto[12]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_organizations_2forganizations_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_organizations_2forganizations_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_organizations_2forganizations_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::mruv::organizations::CreateOrganizationRequest, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::mruv::organizations::CreateOrganizationResponse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::mruv::organizations::GetOrganizationRequest, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::mruv::organizations::GetOrganizationRequest, id_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::mruv::organizations::GetOrganizationResponse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::mruv::organizations::UpdateOrganizationRequest, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::mruv::organizations::UpdateOrganizationRequest, id_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::mruv::organizations::UpdateOrganizationResponse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::mruv::organizations::DeleteOrganizationRequest, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::mruv::organizations::DeleteOrganizationRequest, id_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::mruv::organizations::DeleteOrganizationResponse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::mruv::organizations::AssignLeaderRequest, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::mruv::organizations::AssignLeaderRequest, id_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::mruv::organizations::AssignLeaderResponse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::mruv::organizations::UnassignLeaderRequest, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::mruv::organizations::UnassignLeaderRequest, id_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::mruv::organizations::UnassignLeaderResponse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::mruv::organizations::CreateOrganizationRequest)}, { 5, -1, sizeof(::mruv::organizations::CreateOrganizationResponse)}, { 10, -1, sizeof(::mruv::organizations::GetOrganizationRequest)}, { 16, -1, sizeof(::mruv::organizations::GetOrganizationResponse)}, { 21, -1, sizeof(::mruv::organizations::UpdateOrganizationRequest)}, { 27, -1, sizeof(::mruv::organizations::UpdateOrganizationResponse)}, { 32, -1, sizeof(::mruv::organizations::DeleteOrganizationRequest)}, { 38, -1, sizeof(::mruv::organizations::DeleteOrganizationResponse)}, { 43, -1, sizeof(::mruv::organizations::AssignLeaderRequest)}, { 49, -1, sizeof(::mruv::organizations::AssignLeaderResponse)}, { 54, -1, sizeof(::mruv::organizations::UnassignLeaderRequest)}, { 60, -1, sizeof(::mruv::organizations::UnassignLeaderResponse)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::mruv::organizations::_CreateOrganizationRequest_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::mruv::organizations::_CreateOrganizationResponse_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::mruv::organizations::_GetOrganizationRequest_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::mruv::organizations::_GetOrganizationResponse_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::mruv::organizations::_UpdateOrganizationRequest_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::mruv::organizations::_UpdateOrganizationResponse_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::mruv::organizations::_DeleteOrganizationRequest_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::mruv::organizations::_DeleteOrganizationResponse_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::mruv::organizations::_AssignLeaderRequest_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::mruv::organizations::_AssignLeaderResponse_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::mruv::organizations::_UnassignLeaderRequest_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::mruv::organizations::_UnassignLeaderResponse_default_instance_), }; const char descriptor_table_protodef_organizations_2forganizations_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n!organizations/organizations.proto\022\022mru" "v.organizations\032\034google/api/annotations." "proto\"\033\n\031CreateOrganizationRequest\"\034\n\032Cr" "eateOrganizationResponse\"$\n\026GetOrganizat" "ionRequest\022\n\n\002id\030\001 \001(\r\"\031\n\027GetOrganizatio" "nResponse\"\'\n\031UpdateOrganizationRequest\022\n" "\n\002id\030\001 \001(\r\"\034\n\032UpdateOrganizationResponse" "\"\'\n\031DeleteOrganizationRequest\022\n\n\002id\030\001 \001(" "\r\"\034\n\032DeleteOrganizationResponse\"!\n\023Assig" "nLeaderRequest\022\n\n\002id\030\001 \001(\r\"\026\n\024AssignLead" "erResponse\"#\n\025UnassignLeaderRequest\022\n\n\002i" "d\030\001 \001(\r\"\030\n\026UnassignLeaderResponse2\211\007\n\030Mr" "uVOrganizationsService\022\221\001\n\022CreateOrganiz" "ation\022-.mruv.organizations.CreateOrganiz" "ationRequest\032..mruv.organizations.Create" "OrganizationResponse\"\034\202\323\344\223\002\026\"\021/v1/organi" "zations:\001*\022\212\001\n\017GetOrganization\022*.mruv.or" "ganizations.GetOrganizationRequest\032+.mru" "v.organizations.GetOrganizationResponse\"" "\036\202\323\344\223\002\030\022\026/v1/organizations/{id}\022\226\001\n\022Upda" "teOrganization\022-.mruv.organizations.Upda" "teOrganizationRequest\032..mruv.organizatio" "ns.UpdateOrganizationResponse\"!\202\323\344\223\002\0332\026/" "v1/organizations/{id}:\001*\022\223\001\n\022DeleteOrgan" "ization\022-.mruv.organizations.DeleteOrgan" "izationRequest\032..mruv.organizations.Dele" "teOrganizationResponse\"\036\202\323\344\223\002\030*\026/v1/orga" "nizations/{id}\022\213\001\n\014AssignLeader\022\'.mruv.o" "rganizations.AssignLeaderRequest\032(.mruv." "organizations.AssignLeaderResponse\"(\202\323\344\223" "\002\"\032\035/v1/organizations/{id}/leader:\001*\022\216\001\n" "\016UnassignLeader\022).mruv.organizations.Una" "ssignLeaderRequest\032*.mruv.organizations." "UnassignLeaderResponse\"%\202\323\344\223\002\037*\035/v1/orga" "nizations/{id}/leaderB-Z+github.com/MruV" "-RP/mruv-pb-go/organizationsb\006proto3" ; static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_organizations_2forganizations_2eproto_deps[1] = { &::descriptor_table_google_2fapi_2fannotations_2eproto, }; static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_organizations_2forganizations_2eproto_sccs[12] = { &scc_info_AssignLeaderRequest_organizations_2forganizations_2eproto.base, &scc_info_AssignLeaderResponse_organizations_2forganizations_2eproto.base, &scc_info_CreateOrganizationRequest_organizations_2forganizations_2eproto.base, &scc_info_CreateOrganizationResponse_organizations_2forganizations_2eproto.base, &scc_info_DeleteOrganizationRequest_organizations_2forganizations_2eproto.base, &scc_info_DeleteOrganizationResponse_organizations_2forganizations_2eproto.base, &scc_info_GetOrganizationRequest_organizations_2forganizations_2eproto.base, &scc_info_GetOrganizationResponse_organizations_2forganizations_2eproto.base, &scc_info_UnassignLeaderRequest_organizations_2forganizations_2eproto.base, &scc_info_UnassignLeaderResponse_organizations_2forganizations_2eproto.base, &scc_info_UpdateOrganizationRequest_organizations_2forganizations_2eproto.base, &scc_info_UpdateOrganizationResponse_organizations_2forganizations_2eproto.base, }; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_organizations_2forganizations_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_organizations_2forganizations_2eproto = { false, false, descriptor_table_protodef_organizations_2forganizations_2eproto, "organizations/organizations.proto", 1436, &descriptor_table_organizations_2forganizations_2eproto_once, descriptor_table_organizations_2forganizations_2eproto_sccs, descriptor_table_organizations_2forganizations_2eproto_deps, 12, 1, schemas, file_default_instances, TableStruct_organizations_2forganizations_2eproto::offsets, file_level_metadata_organizations_2forganizations_2eproto, 12, file_level_enum_descriptors_organizations_2forganizations_2eproto, file_level_service_descriptors_organizations_2forganizations_2eproto, }; // Force running AddDescriptors() at dynamic initialization time. static bool dynamic_init_dummy_organizations_2forganizations_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_organizations_2forganizations_2eproto)), true); namespace mruv { namespace organizations { // =================================================================== void CreateOrganizationRequest::InitAsDefaultInstance() { } class CreateOrganizationRequest::_Internal { public: }; CreateOrganizationRequest::CreateOrganizationRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:mruv.organizations.CreateOrganizationRequest) } CreateOrganizationRequest::CreateOrganizationRequest(const CreateOrganizationRequest& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:mruv.organizations.CreateOrganizationRequest) } void CreateOrganizationRequest::SharedCtor() { } CreateOrganizationRequest::~CreateOrganizationRequest() { // @@protoc_insertion_point(destructor:mruv.organizations.CreateOrganizationRequest) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void CreateOrganizationRequest::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void CreateOrganizationRequest::ArenaDtor(void* object) { CreateOrganizationRequest* _this = reinterpret_cast< CreateOrganizationRequest* >(object); (void)_this; } void CreateOrganizationRequest::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void CreateOrganizationRequest::SetCachedSize(int size) const { _cached_size_.Set(size); } const CreateOrganizationRequest& CreateOrganizationRequest::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_CreateOrganizationRequest_organizations_2forganizations_2eproto.base); return *internal_default_instance(); } void CreateOrganizationRequest::Clear() { // @@protoc_insertion_point(message_clear_start:mruv.organizations.CreateOrganizationRequest) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* CreateOrganizationRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* CreateOrganizationRequest::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:mruv.organizations.CreateOrganizationRequest) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:mruv.organizations.CreateOrganizationRequest) return target; } size_t CreateOrganizationRequest::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:mruv.organizations.CreateOrganizationRequest) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CreateOrganizationRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:mruv.organizations.CreateOrganizationRequest) GOOGLE_DCHECK_NE(&from, this); const CreateOrganizationRequest* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<CreateOrganizationRequest>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:mruv.organizations.CreateOrganizationRequest) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:mruv.organizations.CreateOrganizationRequest) MergeFrom(*source); } } void CreateOrganizationRequest::MergeFrom(const CreateOrganizationRequest& from) { // @@protoc_insertion_point(class_specific_merge_from_start:mruv.organizations.CreateOrganizationRequest) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; } void CreateOrganizationRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:mruv.organizations.CreateOrganizationRequest) if (&from == this) return; Clear(); MergeFrom(from); } void CreateOrganizationRequest::CopyFrom(const CreateOrganizationRequest& from) { // @@protoc_insertion_point(class_specific_copy_from_start:mruv.organizations.CreateOrganizationRequest) if (&from == this) return; Clear(); MergeFrom(from); } bool CreateOrganizationRequest::IsInitialized() const { return true; } void CreateOrganizationRequest::InternalSwap(CreateOrganizationRequest* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); } ::PROTOBUF_NAMESPACE_ID::Metadata CreateOrganizationRequest::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== void CreateOrganizationResponse::InitAsDefaultInstance() { } class CreateOrganizationResponse::_Internal { public: }; CreateOrganizationResponse::CreateOrganizationResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:mruv.organizations.CreateOrganizationResponse) } CreateOrganizationResponse::CreateOrganizationResponse(const CreateOrganizationResponse& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:mruv.organizations.CreateOrganizationResponse) } void CreateOrganizationResponse::SharedCtor() { } CreateOrganizationResponse::~CreateOrganizationResponse() { // @@protoc_insertion_point(destructor:mruv.organizations.CreateOrganizationResponse) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void CreateOrganizationResponse::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void CreateOrganizationResponse::ArenaDtor(void* object) { CreateOrganizationResponse* _this = reinterpret_cast< CreateOrganizationResponse* >(object); (void)_this; } void CreateOrganizationResponse::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void CreateOrganizationResponse::SetCachedSize(int size) const { _cached_size_.Set(size); } const CreateOrganizationResponse& CreateOrganizationResponse::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_CreateOrganizationResponse_organizations_2forganizations_2eproto.base); return *internal_default_instance(); } void CreateOrganizationResponse::Clear() { // @@protoc_insertion_point(message_clear_start:mruv.organizations.CreateOrganizationResponse) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* CreateOrganizationResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* CreateOrganizationResponse::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:mruv.organizations.CreateOrganizationResponse) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:mruv.organizations.CreateOrganizationResponse) return target; } size_t CreateOrganizationResponse::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:mruv.organizations.CreateOrganizationResponse) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CreateOrganizationResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:mruv.organizations.CreateOrganizationResponse) GOOGLE_DCHECK_NE(&from, this); const CreateOrganizationResponse* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<CreateOrganizationResponse>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:mruv.organizations.CreateOrganizationResponse) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:mruv.organizations.CreateOrganizationResponse) MergeFrom(*source); } } void CreateOrganizationResponse::MergeFrom(const CreateOrganizationResponse& from) { // @@protoc_insertion_point(class_specific_merge_from_start:mruv.organizations.CreateOrganizationResponse) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; } void CreateOrganizationResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:mruv.organizations.CreateOrganizationResponse) if (&from == this) return; Clear(); MergeFrom(from); } void CreateOrganizationResponse::CopyFrom(const CreateOrganizationResponse& from) { // @@protoc_insertion_point(class_specific_copy_from_start:mruv.organizations.CreateOrganizationResponse) if (&from == this) return; Clear(); MergeFrom(from); } bool CreateOrganizationResponse::IsInitialized() const { return true; } void CreateOrganizationResponse::InternalSwap(CreateOrganizationResponse* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); } ::PROTOBUF_NAMESPACE_ID::Metadata CreateOrganizationResponse::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== void GetOrganizationRequest::InitAsDefaultInstance() { } class GetOrganizationRequest::_Internal { public: }; GetOrganizationRequest::GetOrganizationRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:mruv.organizations.GetOrganizationRequest) } GetOrganizationRequest::GetOrganizationRequest(const GetOrganizationRequest& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); id_ = from.id_; // @@protoc_insertion_point(copy_constructor:mruv.organizations.GetOrganizationRequest) } void GetOrganizationRequest::SharedCtor() { id_ = 0u; } GetOrganizationRequest::~GetOrganizationRequest() { // @@protoc_insertion_point(destructor:mruv.organizations.GetOrganizationRequest) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void GetOrganizationRequest::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void GetOrganizationRequest::ArenaDtor(void* object) { GetOrganizationRequest* _this = reinterpret_cast< GetOrganizationRequest* >(object); (void)_this; } void GetOrganizationRequest::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void GetOrganizationRequest::SetCachedSize(int size) const { _cached_size_.Set(size); } const GetOrganizationRequest& GetOrganizationRequest::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_GetOrganizationRequest_organizations_2forganizations_2eproto.base); return *internal_default_instance(); } void GetOrganizationRequest::Clear() { // @@protoc_insertion_point(message_clear_start:mruv.organizations.GetOrganizationRequest) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; id_ = 0u; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* GetOrganizationRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // uint32 id = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { id_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* GetOrganizationRequest::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:mruv.organizations.GetOrganizationRequest) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // uint32 id = 1; if (this->id() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_id(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:mruv.organizations.GetOrganizationRequest) return target; } size_t GetOrganizationRequest::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:mruv.organizations.GetOrganizationRequest) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // uint32 id = 1; if (this->id() != 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_id()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void GetOrganizationRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:mruv.organizations.GetOrganizationRequest) GOOGLE_DCHECK_NE(&from, this); const GetOrganizationRequest* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<GetOrganizationRequest>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:mruv.organizations.GetOrganizationRequest) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:mruv.organizations.GetOrganizationRequest) MergeFrom(*source); } } void GetOrganizationRequest::MergeFrom(const GetOrganizationRequest& from) { // @@protoc_insertion_point(class_specific_merge_from_start:mruv.organizations.GetOrganizationRequest) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.id() != 0) { _internal_set_id(from._internal_id()); } } void GetOrganizationRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:mruv.organizations.GetOrganizationRequest) if (&from == this) return; Clear(); MergeFrom(from); } void GetOrganizationRequest::CopyFrom(const GetOrganizationRequest& from) { // @@protoc_insertion_point(class_specific_copy_from_start:mruv.organizations.GetOrganizationRequest) if (&from == this) return; Clear(); MergeFrom(from); } bool GetOrganizationRequest::IsInitialized() const { return true; } void GetOrganizationRequest::InternalSwap(GetOrganizationRequest* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(id_, other->id_); } ::PROTOBUF_NAMESPACE_ID::Metadata GetOrganizationRequest::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== void GetOrganizationResponse::InitAsDefaultInstance() { } class GetOrganizationResponse::_Internal { public: }; GetOrganizationResponse::GetOrganizationResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:mruv.organizations.GetOrganizationResponse) } GetOrganizationResponse::GetOrganizationResponse(const GetOrganizationResponse& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:mruv.organizations.GetOrganizationResponse) } void GetOrganizationResponse::SharedCtor() { } GetOrganizationResponse::~GetOrganizationResponse() { // @@protoc_insertion_point(destructor:mruv.organizations.GetOrganizationResponse) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void GetOrganizationResponse::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void GetOrganizationResponse::ArenaDtor(void* object) { GetOrganizationResponse* _this = reinterpret_cast< GetOrganizationResponse* >(object); (void)_this; } void GetOrganizationResponse::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void GetOrganizationResponse::SetCachedSize(int size) const { _cached_size_.Set(size); } const GetOrganizationResponse& GetOrganizationResponse::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_GetOrganizationResponse_organizations_2forganizations_2eproto.base); return *internal_default_instance(); } void GetOrganizationResponse::Clear() { // @@protoc_insertion_point(message_clear_start:mruv.organizations.GetOrganizationResponse) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* GetOrganizationResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* GetOrganizationResponse::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:mruv.organizations.GetOrganizationResponse) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:mruv.organizations.GetOrganizationResponse) return target; } size_t GetOrganizationResponse::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:mruv.organizations.GetOrganizationResponse) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void GetOrganizationResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:mruv.organizations.GetOrganizationResponse) GOOGLE_DCHECK_NE(&from, this); const GetOrganizationResponse* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<GetOrganizationResponse>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:mruv.organizations.GetOrganizationResponse) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:mruv.organizations.GetOrganizationResponse) MergeFrom(*source); } } void GetOrganizationResponse::MergeFrom(const GetOrganizationResponse& from) { // @@protoc_insertion_point(class_specific_merge_from_start:mruv.organizations.GetOrganizationResponse) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; } void GetOrganizationResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:mruv.organizations.GetOrganizationResponse) if (&from == this) return; Clear(); MergeFrom(from); } void GetOrganizationResponse::CopyFrom(const GetOrganizationResponse& from) { // @@protoc_insertion_point(class_specific_copy_from_start:mruv.organizations.GetOrganizationResponse) if (&from == this) return; Clear(); MergeFrom(from); } bool GetOrganizationResponse::IsInitialized() const { return true; } void GetOrganizationResponse::InternalSwap(GetOrganizationResponse* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); } ::PROTOBUF_NAMESPACE_ID::Metadata GetOrganizationResponse::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== void UpdateOrganizationRequest::InitAsDefaultInstance() { } class UpdateOrganizationRequest::_Internal { public: }; UpdateOrganizationRequest::UpdateOrganizationRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:mruv.organizations.UpdateOrganizationRequest) } UpdateOrganizationRequest::UpdateOrganizationRequest(const UpdateOrganizationRequest& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); id_ = from.id_; // @@protoc_insertion_point(copy_constructor:mruv.organizations.UpdateOrganizationRequest) } void UpdateOrganizationRequest::SharedCtor() { id_ = 0u; } UpdateOrganizationRequest::~UpdateOrganizationRequest() { // @@protoc_insertion_point(destructor:mruv.organizations.UpdateOrganizationRequest) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void UpdateOrganizationRequest::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void UpdateOrganizationRequest::ArenaDtor(void* object) { UpdateOrganizationRequest* _this = reinterpret_cast< UpdateOrganizationRequest* >(object); (void)_this; } void UpdateOrganizationRequest::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void UpdateOrganizationRequest::SetCachedSize(int size) const { _cached_size_.Set(size); } const UpdateOrganizationRequest& UpdateOrganizationRequest::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_UpdateOrganizationRequest_organizations_2forganizations_2eproto.base); return *internal_default_instance(); } void UpdateOrganizationRequest::Clear() { // @@protoc_insertion_point(message_clear_start:mruv.organizations.UpdateOrganizationRequest) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; id_ = 0u; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* UpdateOrganizationRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // uint32 id = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { id_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* UpdateOrganizationRequest::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:mruv.organizations.UpdateOrganizationRequest) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // uint32 id = 1; if (this->id() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_id(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:mruv.organizations.UpdateOrganizationRequest) return target; } size_t UpdateOrganizationRequest::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:mruv.organizations.UpdateOrganizationRequest) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // uint32 id = 1; if (this->id() != 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_id()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void UpdateOrganizationRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:mruv.organizations.UpdateOrganizationRequest) GOOGLE_DCHECK_NE(&from, this); const UpdateOrganizationRequest* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<UpdateOrganizationRequest>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:mruv.organizations.UpdateOrganizationRequest) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:mruv.organizations.UpdateOrganizationRequest) MergeFrom(*source); } } void UpdateOrganizationRequest::MergeFrom(const UpdateOrganizationRequest& from) { // @@protoc_insertion_point(class_specific_merge_from_start:mruv.organizations.UpdateOrganizationRequest) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.id() != 0) { _internal_set_id(from._internal_id()); } } void UpdateOrganizationRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:mruv.organizations.UpdateOrganizationRequest) if (&from == this) return; Clear(); MergeFrom(from); } void UpdateOrganizationRequest::CopyFrom(const UpdateOrganizationRequest& from) { // @@protoc_insertion_point(class_specific_copy_from_start:mruv.organizations.UpdateOrganizationRequest) if (&from == this) return; Clear(); MergeFrom(from); } bool UpdateOrganizationRequest::IsInitialized() const { return true; } void UpdateOrganizationRequest::InternalSwap(UpdateOrganizationRequest* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(id_, other->id_); } ::PROTOBUF_NAMESPACE_ID::Metadata UpdateOrganizationRequest::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== void UpdateOrganizationResponse::InitAsDefaultInstance() { } class UpdateOrganizationResponse::_Internal { public: }; UpdateOrganizationResponse::UpdateOrganizationResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:mruv.organizations.UpdateOrganizationResponse) } UpdateOrganizationResponse::UpdateOrganizationResponse(const UpdateOrganizationResponse& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:mruv.organizations.UpdateOrganizationResponse) } void UpdateOrganizationResponse::SharedCtor() { } UpdateOrganizationResponse::~UpdateOrganizationResponse() { // @@protoc_insertion_point(destructor:mruv.organizations.UpdateOrganizationResponse) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void UpdateOrganizationResponse::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void UpdateOrganizationResponse::ArenaDtor(void* object) { UpdateOrganizationResponse* _this = reinterpret_cast< UpdateOrganizationResponse* >(object); (void)_this; } void UpdateOrganizationResponse::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void UpdateOrganizationResponse::SetCachedSize(int size) const { _cached_size_.Set(size); } const UpdateOrganizationResponse& UpdateOrganizationResponse::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_UpdateOrganizationResponse_organizations_2forganizations_2eproto.base); return *internal_default_instance(); } void UpdateOrganizationResponse::Clear() { // @@protoc_insertion_point(message_clear_start:mruv.organizations.UpdateOrganizationResponse) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* UpdateOrganizationResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* UpdateOrganizationResponse::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:mruv.organizations.UpdateOrganizationResponse) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:mruv.organizations.UpdateOrganizationResponse) return target; } size_t UpdateOrganizationResponse::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:mruv.organizations.UpdateOrganizationResponse) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void UpdateOrganizationResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:mruv.organizations.UpdateOrganizationResponse) GOOGLE_DCHECK_NE(&from, this); const UpdateOrganizationResponse* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<UpdateOrganizationResponse>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:mruv.organizations.UpdateOrganizationResponse) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:mruv.organizations.UpdateOrganizationResponse) MergeFrom(*source); } } void UpdateOrganizationResponse::MergeFrom(const UpdateOrganizationResponse& from) { // @@protoc_insertion_point(class_specific_merge_from_start:mruv.organizations.UpdateOrganizationResponse) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; } void UpdateOrganizationResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:mruv.organizations.UpdateOrganizationResponse) if (&from == this) return; Clear(); MergeFrom(from); } void UpdateOrganizationResponse::CopyFrom(const UpdateOrganizationResponse& from) { // @@protoc_insertion_point(class_specific_copy_from_start:mruv.organizations.UpdateOrganizationResponse) if (&from == this) return; Clear(); MergeFrom(from); } bool UpdateOrganizationResponse::IsInitialized() const { return true; } void UpdateOrganizationResponse::InternalSwap(UpdateOrganizationResponse* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); } ::PROTOBUF_NAMESPACE_ID::Metadata UpdateOrganizationResponse::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== void DeleteOrganizationRequest::InitAsDefaultInstance() { } class DeleteOrganizationRequest::_Internal { public: }; DeleteOrganizationRequest::DeleteOrganizationRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:mruv.organizations.DeleteOrganizationRequest) } DeleteOrganizationRequest::DeleteOrganizationRequest(const DeleteOrganizationRequest& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); id_ = from.id_; // @@protoc_insertion_point(copy_constructor:mruv.organizations.DeleteOrganizationRequest) } void DeleteOrganizationRequest::SharedCtor() { id_ = 0u; } DeleteOrganizationRequest::~DeleteOrganizationRequest() { // @@protoc_insertion_point(destructor:mruv.organizations.DeleteOrganizationRequest) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void DeleteOrganizationRequest::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void DeleteOrganizationRequest::ArenaDtor(void* object) { DeleteOrganizationRequest* _this = reinterpret_cast< DeleteOrganizationRequest* >(object); (void)_this; } void DeleteOrganizationRequest::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void DeleteOrganizationRequest::SetCachedSize(int size) const { _cached_size_.Set(size); } const DeleteOrganizationRequest& DeleteOrganizationRequest::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_DeleteOrganizationRequest_organizations_2forganizations_2eproto.base); return *internal_default_instance(); } void DeleteOrganizationRequest::Clear() { // @@protoc_insertion_point(message_clear_start:mruv.organizations.DeleteOrganizationRequest) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; id_ = 0u; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* DeleteOrganizationRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // uint32 id = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { id_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* DeleteOrganizationRequest::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:mruv.organizations.DeleteOrganizationRequest) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // uint32 id = 1; if (this->id() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_id(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:mruv.organizations.DeleteOrganizationRequest) return target; } size_t DeleteOrganizationRequest::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:mruv.organizations.DeleteOrganizationRequest) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // uint32 id = 1; if (this->id() != 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_id()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void DeleteOrganizationRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:mruv.organizations.DeleteOrganizationRequest) GOOGLE_DCHECK_NE(&from, this); const DeleteOrganizationRequest* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<DeleteOrganizationRequest>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:mruv.organizations.DeleteOrganizationRequest) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:mruv.organizations.DeleteOrganizationRequest) MergeFrom(*source); } } void DeleteOrganizationRequest::MergeFrom(const DeleteOrganizationRequest& from) { // @@protoc_insertion_point(class_specific_merge_from_start:mruv.organizations.DeleteOrganizationRequest) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.id() != 0) { _internal_set_id(from._internal_id()); } } void DeleteOrganizationRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:mruv.organizations.DeleteOrganizationRequest) if (&from == this) return; Clear(); MergeFrom(from); } void DeleteOrganizationRequest::CopyFrom(const DeleteOrganizationRequest& from) { // @@protoc_insertion_point(class_specific_copy_from_start:mruv.organizations.DeleteOrganizationRequest) if (&from == this) return; Clear(); MergeFrom(from); } bool DeleteOrganizationRequest::IsInitialized() const { return true; } void DeleteOrganizationRequest::InternalSwap(DeleteOrganizationRequest* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(id_, other->id_); } ::PROTOBUF_NAMESPACE_ID::Metadata DeleteOrganizationRequest::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== void DeleteOrganizationResponse::InitAsDefaultInstance() { } class DeleteOrganizationResponse::_Internal { public: }; DeleteOrganizationResponse::DeleteOrganizationResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:mruv.organizations.DeleteOrganizationResponse) } DeleteOrganizationResponse::DeleteOrganizationResponse(const DeleteOrganizationResponse& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:mruv.organizations.DeleteOrganizationResponse) } void DeleteOrganizationResponse::SharedCtor() { } DeleteOrganizationResponse::~DeleteOrganizationResponse() { // @@protoc_insertion_point(destructor:mruv.organizations.DeleteOrganizationResponse) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void DeleteOrganizationResponse::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void DeleteOrganizationResponse::ArenaDtor(void* object) { DeleteOrganizationResponse* _this = reinterpret_cast< DeleteOrganizationResponse* >(object); (void)_this; } void DeleteOrganizationResponse::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void DeleteOrganizationResponse::SetCachedSize(int size) const { _cached_size_.Set(size); } const DeleteOrganizationResponse& DeleteOrganizationResponse::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_DeleteOrganizationResponse_organizations_2forganizations_2eproto.base); return *internal_default_instance(); } void DeleteOrganizationResponse::Clear() { // @@protoc_insertion_point(message_clear_start:mruv.organizations.DeleteOrganizationResponse) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* DeleteOrganizationResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* DeleteOrganizationResponse::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:mruv.organizations.DeleteOrganizationResponse) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:mruv.organizations.DeleteOrganizationResponse) return target; } size_t DeleteOrganizationResponse::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:mruv.organizations.DeleteOrganizationResponse) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void DeleteOrganizationResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:mruv.organizations.DeleteOrganizationResponse) GOOGLE_DCHECK_NE(&from, this); const DeleteOrganizationResponse* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<DeleteOrganizationResponse>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:mruv.organizations.DeleteOrganizationResponse) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:mruv.organizations.DeleteOrganizationResponse) MergeFrom(*source); } } void DeleteOrganizationResponse::MergeFrom(const DeleteOrganizationResponse& from) { // @@protoc_insertion_point(class_specific_merge_from_start:mruv.organizations.DeleteOrganizationResponse) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; } void DeleteOrganizationResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:mruv.organizations.DeleteOrganizationResponse) if (&from == this) return; Clear(); MergeFrom(from); } void DeleteOrganizationResponse::CopyFrom(const DeleteOrganizationResponse& from) { // @@protoc_insertion_point(class_specific_copy_from_start:mruv.organizations.DeleteOrganizationResponse) if (&from == this) return; Clear(); MergeFrom(from); } bool DeleteOrganizationResponse::IsInitialized() const { return true; } void DeleteOrganizationResponse::InternalSwap(DeleteOrganizationResponse* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); } ::PROTOBUF_NAMESPACE_ID::Metadata DeleteOrganizationResponse::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== void AssignLeaderRequest::InitAsDefaultInstance() { } class AssignLeaderRequest::_Internal { public: }; AssignLeaderRequest::AssignLeaderRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:mruv.organizations.AssignLeaderRequest) } AssignLeaderRequest::AssignLeaderRequest(const AssignLeaderRequest& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); id_ = from.id_; // @@protoc_insertion_point(copy_constructor:mruv.organizations.AssignLeaderRequest) } void AssignLeaderRequest::SharedCtor() { id_ = 0u; } AssignLeaderRequest::~AssignLeaderRequest() { // @@protoc_insertion_point(destructor:mruv.organizations.AssignLeaderRequest) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void AssignLeaderRequest::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void AssignLeaderRequest::ArenaDtor(void* object) { AssignLeaderRequest* _this = reinterpret_cast< AssignLeaderRequest* >(object); (void)_this; } void AssignLeaderRequest::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void AssignLeaderRequest::SetCachedSize(int size) const { _cached_size_.Set(size); } const AssignLeaderRequest& AssignLeaderRequest::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_AssignLeaderRequest_organizations_2forganizations_2eproto.base); return *internal_default_instance(); } void AssignLeaderRequest::Clear() { // @@protoc_insertion_point(message_clear_start:mruv.organizations.AssignLeaderRequest) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; id_ = 0u; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* AssignLeaderRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // uint32 id = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { id_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* AssignLeaderRequest::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:mruv.organizations.AssignLeaderRequest) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // uint32 id = 1; if (this->id() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_id(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:mruv.organizations.AssignLeaderRequest) return target; } size_t AssignLeaderRequest::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:mruv.organizations.AssignLeaderRequest) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // uint32 id = 1; if (this->id() != 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_id()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void AssignLeaderRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:mruv.organizations.AssignLeaderRequest) GOOGLE_DCHECK_NE(&from, this); const AssignLeaderRequest* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<AssignLeaderRequest>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:mruv.organizations.AssignLeaderRequest) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:mruv.organizations.AssignLeaderRequest) MergeFrom(*source); } } void AssignLeaderRequest::MergeFrom(const AssignLeaderRequest& from) { // @@protoc_insertion_point(class_specific_merge_from_start:mruv.organizations.AssignLeaderRequest) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.id() != 0) { _internal_set_id(from._internal_id()); } } void AssignLeaderRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:mruv.organizations.AssignLeaderRequest) if (&from == this) return; Clear(); MergeFrom(from); } void AssignLeaderRequest::CopyFrom(const AssignLeaderRequest& from) { // @@protoc_insertion_point(class_specific_copy_from_start:mruv.organizations.AssignLeaderRequest) if (&from == this) return; Clear(); MergeFrom(from); } bool AssignLeaderRequest::IsInitialized() const { return true; } void AssignLeaderRequest::InternalSwap(AssignLeaderRequest* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(id_, other->id_); } ::PROTOBUF_NAMESPACE_ID::Metadata AssignLeaderRequest::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== void AssignLeaderResponse::InitAsDefaultInstance() { } class AssignLeaderResponse::_Internal { public: }; AssignLeaderResponse::AssignLeaderResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:mruv.organizations.AssignLeaderResponse) } AssignLeaderResponse::AssignLeaderResponse(const AssignLeaderResponse& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:mruv.organizations.AssignLeaderResponse) } void AssignLeaderResponse::SharedCtor() { } AssignLeaderResponse::~AssignLeaderResponse() { // @@protoc_insertion_point(destructor:mruv.organizations.AssignLeaderResponse) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void AssignLeaderResponse::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void AssignLeaderResponse::ArenaDtor(void* object) { AssignLeaderResponse* _this = reinterpret_cast< AssignLeaderResponse* >(object); (void)_this; } void AssignLeaderResponse::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void AssignLeaderResponse::SetCachedSize(int size) const { _cached_size_.Set(size); } const AssignLeaderResponse& AssignLeaderResponse::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_AssignLeaderResponse_organizations_2forganizations_2eproto.base); return *internal_default_instance(); } void AssignLeaderResponse::Clear() { // @@protoc_insertion_point(message_clear_start:mruv.organizations.AssignLeaderResponse) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* AssignLeaderResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* AssignLeaderResponse::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:mruv.organizations.AssignLeaderResponse) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:mruv.organizations.AssignLeaderResponse) return target; } size_t AssignLeaderResponse::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:mruv.organizations.AssignLeaderResponse) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void AssignLeaderResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:mruv.organizations.AssignLeaderResponse) GOOGLE_DCHECK_NE(&from, this); const AssignLeaderResponse* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<AssignLeaderResponse>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:mruv.organizations.AssignLeaderResponse) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:mruv.organizations.AssignLeaderResponse) MergeFrom(*source); } } void AssignLeaderResponse::MergeFrom(const AssignLeaderResponse& from) { // @@protoc_insertion_point(class_specific_merge_from_start:mruv.organizations.AssignLeaderResponse) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; } void AssignLeaderResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:mruv.organizations.AssignLeaderResponse) if (&from == this) return; Clear(); MergeFrom(from); } void AssignLeaderResponse::CopyFrom(const AssignLeaderResponse& from) { // @@protoc_insertion_point(class_specific_copy_from_start:mruv.organizations.AssignLeaderResponse) if (&from == this) return; Clear(); MergeFrom(from); } bool AssignLeaderResponse::IsInitialized() const { return true; } void AssignLeaderResponse::InternalSwap(AssignLeaderResponse* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); } ::PROTOBUF_NAMESPACE_ID::Metadata AssignLeaderResponse::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== void UnassignLeaderRequest::InitAsDefaultInstance() { } class UnassignLeaderRequest::_Internal { public: }; UnassignLeaderRequest::UnassignLeaderRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:mruv.organizations.UnassignLeaderRequest) } UnassignLeaderRequest::UnassignLeaderRequest(const UnassignLeaderRequest& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); id_ = from.id_; // @@protoc_insertion_point(copy_constructor:mruv.organizations.UnassignLeaderRequest) } void UnassignLeaderRequest::SharedCtor() { id_ = 0u; } UnassignLeaderRequest::~UnassignLeaderRequest() { // @@protoc_insertion_point(destructor:mruv.organizations.UnassignLeaderRequest) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void UnassignLeaderRequest::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void UnassignLeaderRequest::ArenaDtor(void* object) { UnassignLeaderRequest* _this = reinterpret_cast< UnassignLeaderRequest* >(object); (void)_this; } void UnassignLeaderRequest::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void UnassignLeaderRequest::SetCachedSize(int size) const { _cached_size_.Set(size); } const UnassignLeaderRequest& UnassignLeaderRequest::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_UnassignLeaderRequest_organizations_2forganizations_2eproto.base); return *internal_default_instance(); } void UnassignLeaderRequest::Clear() { // @@protoc_insertion_point(message_clear_start:mruv.organizations.UnassignLeaderRequest) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; id_ = 0u; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* UnassignLeaderRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // uint32 id = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { id_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* UnassignLeaderRequest::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:mruv.organizations.UnassignLeaderRequest) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // uint32 id = 1; if (this->id() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_id(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:mruv.organizations.UnassignLeaderRequest) return target; } size_t UnassignLeaderRequest::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:mruv.organizations.UnassignLeaderRequest) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // uint32 id = 1; if (this->id() != 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_id()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void UnassignLeaderRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:mruv.organizations.UnassignLeaderRequest) GOOGLE_DCHECK_NE(&from, this); const UnassignLeaderRequest* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<UnassignLeaderRequest>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:mruv.organizations.UnassignLeaderRequest) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:mruv.organizations.UnassignLeaderRequest) MergeFrom(*source); } } void UnassignLeaderRequest::MergeFrom(const UnassignLeaderRequest& from) { // @@protoc_insertion_point(class_specific_merge_from_start:mruv.organizations.UnassignLeaderRequest) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.id() != 0) { _internal_set_id(from._internal_id()); } } void UnassignLeaderRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:mruv.organizations.UnassignLeaderRequest) if (&from == this) return; Clear(); MergeFrom(from); } void UnassignLeaderRequest::CopyFrom(const UnassignLeaderRequest& from) { // @@protoc_insertion_point(class_specific_copy_from_start:mruv.organizations.UnassignLeaderRequest) if (&from == this) return; Clear(); MergeFrom(from); } bool UnassignLeaderRequest::IsInitialized() const { return true; } void UnassignLeaderRequest::InternalSwap(UnassignLeaderRequest* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(id_, other->id_); } ::PROTOBUF_NAMESPACE_ID::Metadata UnassignLeaderRequest::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== void UnassignLeaderResponse::InitAsDefaultInstance() { } class UnassignLeaderResponse::_Internal { public: }; UnassignLeaderResponse::UnassignLeaderResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:mruv.organizations.UnassignLeaderResponse) } UnassignLeaderResponse::UnassignLeaderResponse(const UnassignLeaderResponse& from) : ::PROTOBUF_NAMESPACE_ID::Message() { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:mruv.organizations.UnassignLeaderResponse) } void UnassignLeaderResponse::SharedCtor() { } UnassignLeaderResponse::~UnassignLeaderResponse() { // @@protoc_insertion_point(destructor:mruv.organizations.UnassignLeaderResponse) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void UnassignLeaderResponse::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void UnassignLeaderResponse::ArenaDtor(void* object) { UnassignLeaderResponse* _this = reinterpret_cast< UnassignLeaderResponse* >(object); (void)_this; } void UnassignLeaderResponse::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void UnassignLeaderResponse::SetCachedSize(int size) const { _cached_size_.Set(size); } const UnassignLeaderResponse& UnassignLeaderResponse::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_UnassignLeaderResponse_organizations_2forganizations_2eproto.base); return *internal_default_instance(); } void UnassignLeaderResponse::Clear() { // @@protoc_insertion_point(message_clear_start:mruv.organizations.UnassignLeaderResponse) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* UnassignLeaderResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* UnassignLeaderResponse::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:mruv.organizations.UnassignLeaderResponse) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:mruv.organizations.UnassignLeaderResponse) return target; } size_t UnassignLeaderResponse::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:mruv.organizations.UnassignLeaderResponse) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void UnassignLeaderResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:mruv.organizations.UnassignLeaderResponse) GOOGLE_DCHECK_NE(&from, this); const UnassignLeaderResponse* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<UnassignLeaderResponse>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:mruv.organizations.UnassignLeaderResponse) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:mruv.organizations.UnassignLeaderResponse) MergeFrom(*source); } } void UnassignLeaderResponse::MergeFrom(const UnassignLeaderResponse& from) { // @@protoc_insertion_point(class_specific_merge_from_start:mruv.organizations.UnassignLeaderResponse) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; } void UnassignLeaderResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:mruv.organizations.UnassignLeaderResponse) if (&from == this) return; Clear(); MergeFrom(from); } void UnassignLeaderResponse::CopyFrom(const UnassignLeaderResponse& from) { // @@protoc_insertion_point(class_specific_copy_from_start:mruv.organizations.UnassignLeaderResponse) if (&from == this) return; Clear(); MergeFrom(from); } bool UnassignLeaderResponse::IsInitialized() const { return true; } void UnassignLeaderResponse::InternalSwap(UnassignLeaderResponse* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); } ::PROTOBUF_NAMESPACE_ID::Metadata UnassignLeaderResponse::GetMetadata() const { return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) } // namespace organizations } // namespace mruv PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::mruv::organizations::CreateOrganizationRequest* Arena::CreateMaybeMessage< ::mruv::organizations::CreateOrganizationRequest >(Arena* arena) { return Arena::CreateMessageInternal< ::mruv::organizations::CreateOrganizationRequest >(arena); } template<> PROTOBUF_NOINLINE ::mruv::organizations::CreateOrganizationResponse* Arena::CreateMaybeMessage< ::mruv::organizations::CreateOrganizationResponse >(Arena* arena) { return Arena::CreateMessageInternal< ::mruv::organizations::CreateOrganizationResponse >(arena); } template<> PROTOBUF_NOINLINE ::mruv::organizations::GetOrganizationRequest* Arena::CreateMaybeMessage< ::mruv::organizations::GetOrganizationRequest >(Arena* arena) { return Arena::CreateMessageInternal< ::mruv::organizations::GetOrganizationRequest >(arena); } template<> PROTOBUF_NOINLINE ::mruv::organizations::GetOrganizationResponse* Arena::CreateMaybeMessage< ::mruv::organizations::GetOrganizationResponse >(Arena* arena) { return Arena::CreateMessageInternal< ::mruv::organizations::GetOrganizationResponse >(arena); } template<> PROTOBUF_NOINLINE ::mruv::organizations::UpdateOrganizationRequest* Arena::CreateMaybeMessage< ::mruv::organizations::UpdateOrganizationRequest >(Arena* arena) { return Arena::CreateMessageInternal< ::mruv::organizations::UpdateOrganizationRequest >(arena); } template<> PROTOBUF_NOINLINE ::mruv::organizations::UpdateOrganizationResponse* Arena::CreateMaybeMessage< ::mruv::organizations::UpdateOrganizationResponse >(Arena* arena) { return Arena::CreateMessageInternal< ::mruv::organizations::UpdateOrganizationResponse >(arena); } template<> PROTOBUF_NOINLINE ::mruv::organizations::DeleteOrganizationRequest* Arena::CreateMaybeMessage< ::mruv::organizations::DeleteOrganizationRequest >(Arena* arena) { return Arena::CreateMessageInternal< ::mruv::organizations::DeleteOrganizationRequest >(arena); } template<> PROTOBUF_NOINLINE ::mruv::organizations::DeleteOrganizationResponse* Arena::CreateMaybeMessage< ::mruv::organizations::DeleteOrganizationResponse >(Arena* arena) { return Arena::CreateMessageInternal< ::mruv::organizations::DeleteOrganizationResponse >(arena); } template<> PROTOBUF_NOINLINE ::mruv::organizations::AssignLeaderRequest* Arena::CreateMaybeMessage< ::mruv::organizations::AssignLeaderRequest >(Arena* arena) { return Arena::CreateMessageInternal< ::mruv::organizations::AssignLeaderRequest >(arena); } template<> PROTOBUF_NOINLINE ::mruv::organizations::AssignLeaderResponse* Arena::CreateMaybeMessage< ::mruv::organizations::AssignLeaderResponse >(Arena* arena) { return Arena::CreateMessageInternal< ::mruv::organizations::AssignLeaderResponse >(arena); } template<> PROTOBUF_NOINLINE ::mruv::organizations::UnassignLeaderRequest* Arena::CreateMaybeMessage< ::mruv::organizations::UnassignLeaderRequest >(Arena* arena) { return Arena::CreateMessageInternal< ::mruv::organizations::UnassignLeaderRequest >(arena); } template<> PROTOBUF_NOINLINE ::mruv::organizations::UnassignLeaderResponse* Arena::CreateMaybeMessage< ::mruv::organizations::UnassignLeaderResponse >(Arena* arena) { return Arena::CreateMessageInternal< ::mruv::organizations::UnassignLeaderResponse >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
41.494981
205
0.778138
[ "object" ]
5f84dc5507822fcbef062e54259d8b7d97c74376
559
cpp
C++
LeetCode/Solutions/LC0714.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
54
2019-05-13T12:13:09.000Z
2022-02-27T02:59:00.000Z
LeetCode/Solutions/LC0714.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
2
2020-10-02T07:16:43.000Z
2020-10-19T04:36:19.000Z
LeetCode/Solutions/LC0714.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
20
2020-05-26T09:48:13.000Z
2022-03-18T15:18:27.000Z
/* Problem Statement: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/ Time: O(n) Space: O(1) Author: Mohammed Shoaib, github.com/Mohammed-Shoaib */ class Solution { public: int maxProfit(vector<int>& prices, int fee) { int n = prices.size(); vector<int> prev, dp(2); // initialization dp[0] = numeric_limits<int>::min(); // dynamic programming for (int& price: prices) { prev = dp; dp[0] = max(prev[1] - price - fee, prev[0]); dp[1] = max(prev[0] + price, prev[1]); } return dp[1]; } };
21.5
102
0.631485
[ "vector" ]
5f8feab64ce0080b1be8d556481e297f0e2fc372
2,524
hpp
C++
dev/Code/Tools/CrySCompileServer/CrySCompileServer/Core/Server/CrySimpleCache.hpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Code/Tools/CrySCompileServer/CrySCompileServer/Core/Server/CrySimpleCache.hpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Code/Tools/CrySCompileServer/CrySCompileServer/Core/Server/CrySimpleCache.hpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #ifndef __CRYSIMPLECACHE__ #define __CRYSIMPLECACHE__ #include "CrySimpleMutex.hpp" #include <Core/STLHelper.hpp> #include <map> #include <vector> #include <list> /*class CCrySimpleCacheEntry { tdCache public: protected: private: };*/ typedef std::map<tdHash, tdHash> tdEntries; typedef std::map<tdHash, tdDataVector> tdData; class CCrySimpleCache { volatile bool m_CachingEnabled; int m_Hit; int m_Miss; tdEntries m_Entries; tdData m_Data; CCrySimpleMutex m_Mutex; CCrySimpleMutex m_FileMutex; std::list<tdDataVector*> m_PendingCacheEntries; std::string CreateFileName(const tdHash& rHash) const; public: void Init(); bool Find(const tdHash& rHash, tdDataVector& rData); void Add(const tdHash& rHash, const tdDataVector& rData); bool LoadCacheFile(const std::string& filename); void Finalize(); void ThreadFunc_SavePendingCacheEntries(); static CCrySimpleCache& Instance(); std::list<tdDataVector*>& PendingCacheEntries(){return m_PendingCacheEntries; } int Hit() const{return m_Hit; } int Miss() const{return m_Miss; } int EntryCount() const{return static_cast<int>(m_Entries.size()); } }; #endif
36.57971
119
0.525357
[ "vector" ]
5f90ef599488d685ee771bfc4a54b6858921e2f0
8,707
cpp
C++
es-core/src/guis/GuiTextEditPopupKeyboard.cpp
joaxn/EmulationStation
0a83e3bc1f63185fa7d38d5b83c8fb5869afffe3
[ "Apache-2.0", "MIT" ]
null
null
null
es-core/src/guis/GuiTextEditPopupKeyboard.cpp
joaxn/EmulationStation
0a83e3bc1f63185fa7d38d5b83c8fb5869afffe3
[ "Apache-2.0", "MIT" ]
null
null
null
es-core/src/guis/GuiTextEditPopupKeyboard.cpp
joaxn/EmulationStation
0a83e3bc1f63185fa7d38d5b83c8fb5869afffe3
[ "Apache-2.0", "MIT" ]
null
null
null
#include "guis/GuiTextEditPopupKeyboard.h" #include "components/MenuComponent.h" #include "utils/StringUtil.h" #include "Log.h" #include <locale> GuiTextEditPopupKeyboard::GuiTextEditPopupKeyboard(Window* window, const std::string& title, const std::string& initValue, const std::function<void(const std::string&)>& okCallback, bool multiLine, const char* acceptBtnText): GuiComponent(window), mBackground(window, ":/frame.png"), mGrid(window, Vector2i(1, 7)), mMultiLine(multiLine) { addChild(&mBackground); addChild(&mGrid); float gridHeight, buttonHeight, buttonWidth, gridWidth; float horizPadding = (float) 20; mTitle = std::make_shared<TextComponent>(mWindow, title, Font::get(FONT_SIZE_LARGE), 0x555555FF, ALIGN_CENTER); mTitle->setUppercase(true); mKeyboardGrid = std::make_shared<ComponentGrid>(mWindow, Vector2i(COLUMNS, ROWS)); mButtonGrid = std::make_shared<ComponentGrid>(mWindow, Vector2i(4, 1)); mText = std::make_shared<TextEditComponent>(mWindow); mText->setValue(initValue); mText->forceCursor(true); if(!multiLine) mText->setCursor(initValue.size()); // Header mGrid.setEntry(mTitle, Vector2i(0, 0), false, true); // Text edit add mGrid.setEntry(mText, Vector2i(0, 1), false, false, Vector2i(1, 1)); // Keyboard // Case for if multiline is enabled, then don't create the keyboard. if (!mMultiLine) { std::locale loc; // Digit Row for (int y = 0; y < ROWS; y++) { std::vector< std::shared_ptr<ButtonComponent> > buttons; for (int x = 0; x < COLUMNS; x++) { if (charArray[y][x] == "sft"){ mShiftButton = std::make_shared<ButtonComponent>(mWindow, charArray[y][x], "SHIFTS FOR UPPER,LOWER, AND SPECIAL", [this] { if (mShift) mShift = false; else mShift = true; shiftKeys(); },false,minText,":/kbd/sft.svg"); buttons.push_back(mShiftButton); } else if (charArray[y][x] == "chr"){ mSpecialButton = std::make_shared<ButtonComponent>(mWindow, charArray[y][x], "SPECIAL CHARACTERS", [this] { if (mSpecial) mSpecial = false; else mSpecial = true; specialKeys(); },false,minText,":/kbd/chr.svg"); buttons.push_back(mSpecialButton); } else if (charArray[y][x] == "cul"){ buttons.push_back(std::make_shared<ButtonComponent>(mWindow, charArray[y][x], charArrayUp[y][x], [this] { mText->moveCursorLeft(); },false,minText,":/kbd/cul.svg")); } else if (charArray[y][x] == "cur"){ buttons.push_back(std::make_shared<ButtonComponent>(mWindow, charArray[y][x], charArrayUp[y][x], [this] { mText->moveCursorRight(); },false,minText,":/kbd/cur.svg")); } else { buttons.push_back(std::make_shared<ButtonComponent>(mWindow, charArray[y][x], charArrayUp[y][x], [this, okCallback, x, y, loc] { okCallback(mText->getValue()); mText->startEditing(); if (mSpecial) mText->textInput(charArraySpecial[y][x]); else if(mShift) mText->textInput(charArrayUp[y][x]); else mText->textInput(charArray[y][x]); mText->stopEditing(); },false,minText)); } // Send just created button into mGrid mKeyboardGrid->setEntry(buttons[x], Vector2i(x, y), true, false); } buttonList.push_back(buttons); } buttonWidth = buttonList.at(0).at(0)->getSize().x(); buttonHeight = buttonList.at(0).at(0)->getSize().y(); gridHeight = (buttonHeight + 2) * ROWS + 2; gridWidth = (buttonWidth + 2) * COLUMNS + 2; mKeyboardGrid->setSize(gridWidth, gridHeight); mGrid.setEntry(mKeyboardGrid, Vector2i(0, 2), true, false); } // Accept/Cancel buttons std::vector< std::shared_ptr<ButtonComponent> > buttons; buttons.push_back(std::make_shared<ButtonComponent>(mWindow, "CANCEL", "DISCARD CHANGES", [this] { delete this; },true,"CANCEL")); buttons.push_back(std::make_shared<ButtonComponent>(mWindow, "SPACE", "SPACE", [this] {mText->startEditing();mText->textInput(" ");mText->stopEditing();},true,"CANCEL",":/kbd/spc.svg")); buttons.push_back(std::make_shared<ButtonComponent>(mWindow, "DELETE", "DELETE A CHAR", [this] {mText->startEditing();mText->textInput("\b");mText->stopEditing();},true,"CANCEL",":/kbd/del.svg")); buttons.push_back(std::make_shared<ButtonComponent>(mWindow, acceptBtnText, acceptBtnText, [this, okCallback] { okCallback(mText->getValue()); delete this; },true,"CANCEL")); // Add a/c buttons mButtonGrid->setEntry(buttons[0], Vector2i(0, 0), true, false); mButtonGrid->setEntry(buttons[1], Vector2i(1, 0), true, false); mButtonGrid->setEntry(buttons[2], Vector2i(2, 0), true, false); mButtonGrid->setEntry(buttons[3], Vector2i(3, 0), true, false); buttonWidth = buttons.at(0)->getSize().x(); buttonHeight = buttons.at(0)->getSize().y(); gridHeight = buttonHeight + 20; gridWidth = (buttonWidth + 10) * buttons.size() + 20; mButtonGrid->setSize(gridWidth, gridHeight); mGrid.setEntry(mButtonGrid, Vector2i(0, 3), true, false); // Determine size from text size float textHeight = mText->getFont()->getHeight(); if (multiLine) textHeight *= 6; mText->setSize(0, textHeight); // If multiline, set all diminsions back to default, else draw size for keyboard. if (mMultiLine) { setSize(Renderer::getScreenWidth() * 0.5f, mTitle->getFont()->getHeight() + textHeight + mKeyboardGrid->getSize().y() + 40); setPosition((Renderer::getScreenWidth() - mSize.x()) / 2, (Renderer::getScreenHeight() - mSize.y()) / 2); } else { // Set size based on ScreenHieght * .08f by the amount of keyboard rows there are. setSize(mKeyboardGrid->getSize().x()+40, mTitle->getFont()->getHeight() + textHeight + 40 + mKeyboardGrid->getSize().y() + mButtonGrid->getSize().y()); setPosition((Renderer::getScreenWidth() - mSize.x()) / 2, (Renderer::getScreenHeight() - mSize.y()) / 2); } } void GuiTextEditPopupKeyboard::onSizeChanged() { mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32)); mText->setSize(mSize.x() - 40, mText->getSize().y()); float fullHeight = mTitle->getFont()->getHeight() + mText->getSize().y() + mKeyboardGrid->getSize().y() + mButtonGrid->getSize().y(); // update grid mGrid.setRowHeightPerc(0, mTitle->getFont()->getHeight() / fullHeight); mGrid.setRowHeightPerc(1, mText->getSize().y() / fullHeight); mGrid.setRowHeightPerc(2, mKeyboardGrid->getSize().y() / fullHeight); mGrid.setRowHeightPerc(3, mButtonGrid->getSize().y() / fullHeight); mGrid.setSize(mSize); } bool GuiTextEditPopupKeyboard::input(InputConfig* config, Input input) { if (GuiComponent::input(config, input)) return true; // pressing back when not text editing closes us if (config->isMappedTo("b", input) && input.value) { delete this; return true; } // For deleting a chara (Left Top Button) if (config->isMappedTo("lefttop", input) && input.value) { mText->startEditing(); mText->textInput("\b"); mText->stopEditing(); } // For Adding a space (Right Top Button) if (config->isMappedTo("righttop", input) && input.value) { mText->startEditing(); mText->textInput(" "); } // For Shifting (X) if (config->isMappedTo("x", input) && input.value) { if (mShift) mShift = false; else mShift = true; shiftKeys(); } return false; } void GuiTextEditPopupKeyboard::update(int deltatime) { } // Shifts the keys when user hits the shift button. void GuiTextEditPopupKeyboard::shiftKeys() { if (mShift){ mShiftButton->setColorShift(0x00000044); mSpecialButton->removeColorShift(); mSpecial = false; }else{ mShiftButton->removeColorShift(); } updateKeys(); } // Special keys when user hits the shift button. void GuiTextEditPopupKeyboard::specialKeys() { if (mSpecial){ mSpecialButton->setColorShift(0x00000044); mShiftButton->removeColorShift(); mShift = false; }else{ mSpecialButton->removeColorShift(); } updateKeys(); } void GuiTextEditPopupKeyboard::updateKeys(){ for (int y = 0; y < ROWS; y++) { for (int x = 0; x < COLUMNS; x++) { if (charArray[y][x] != "sft" && charArray[y][x] != "chr" && charArray[y][x] != "cul" && charArray[y][x] != "cur"){ if (mSpecial){ buttonList.at(y).at(x)->setText(charArraySpecial[y][x],charArraySpecial[y][x],false,minText); }else if(mShift){ buttonList.at(y).at(x)->setText(charArrayUp[y][x],charArrayUp[y][x],false,minText); }else{ buttonList.at(y).at(x)->setText(charArray[y][x],charArrayUp[y][x],false,minText); } } } } } std::vector<HelpPrompt> GuiTextEditPopupKeyboard::getHelpPrompts() { std::vector<HelpPrompt> prompts = mGrid.getHelpPrompts(); prompts.push_back(HelpPrompt("x", "SHIFT")); prompts.push_back(HelpPrompt("b", "back")); prompts.push_back(HelpPrompt("r", "SPACE")); prompts.push_back(HelpPrompt("l", "DELETE")); return prompts; }
35.979339
336
0.678994
[ "vector" ]
5f9274d87e6c00d124a84125eba85f96d075b363
3,670
cpp
C++
lib/Target/Thru/MCTargetDesc/ThruMCTargetDesc.cpp
tkolar23/llvm-thruputer
1d7d69779eb8834fa2b792e72ab7e2819ec2cbec
[ "Apache-2.0" ]
null
null
null
lib/Target/Thru/MCTargetDesc/ThruMCTargetDesc.cpp
tkolar23/llvm-thruputer
1d7d69779eb8834fa2b792e72ab7e2819ec2cbec
[ "Apache-2.0" ]
null
null
null
lib/Target/Thru/MCTargetDesc/ThruMCTargetDesc.cpp
tkolar23/llvm-thruputer
1d7d69779eb8834fa2b792e72ab7e2819ec2cbec
[ "Apache-2.0" ]
null
null
null
//===-- ThruMCTargetDesc.cpp - Thru Target Descriptions -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides Thru specific target descriptions. // //===----------------------------------------------------------------------===// #include "ThruMCTargetDesc.h" #include "ThruInstPrinter.h" #include "ThruMCAsmInfo.h" #include "TargetInfo/ThruTargetInfo.h" #include "llvm/MC/MCELFStreamer.h" #include "llvm/MC/MCInstrAnalysis.h" #include "llvm/MC/MCInstPrinter.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/TargetRegistry.h" using namespace llvm; #define GET_INSTRINFO_MC_DESC #include "ThruGenInstrInfo.inc" #define GET_SUBTARGETINFO_MC_DESC #include "ThruGenSubtargetInfo.inc" #define GET_REGINFO_MC_DESC #include "ThruGenRegisterInfo.inc" static MCInstrInfo *createThruMCInstrInfo() { MCInstrInfo *X = new MCInstrInfo(); InitThruMCInstrInfo(X); return X; } static MCRegisterInfo *createThruMCRegisterInfo(const Triple &TT) { MCRegisterInfo *X = new MCRegisterInfo(); InitThruMCRegisterInfo(X, Thru::X1); return X; } static MCSubtargetInfo *createThruMCSubtargetInfo(const Triple &TT, StringRef CPU, StringRef FS) { return createThruMCSubtargetInfoImpl(TT, CPU, /*TuneCPU*/ CPU, FS); } static MCInstPrinter *createThruMCInstPrinter(const Triple &T, unsigned SyntaxVariant, const MCAsmInfo &MAI, const MCInstrInfo &MII, const MCRegisterInfo &MRI) { // if (SyntaxVariant == 0) return new ThruInstPrinter(MAI, MII, MRI); // return nullptr; } static MCAsmInfo *createThruMCAsmInfo(const MCRegisterInfo &MRI, const Triple &TT, const MCTargetOptions &Options) { MCAsmInfo *MAI = new ThruMCAsmInfo(TT); MCRegister SP = MRI.getDwarfRegNum(Thru::X2, true); MCCFIInstruction Inst = MCCFIInstruction::cfiDefCfa(nullptr, SP, 0); MAI->addInitialFrameState(Inst); return MAI; } static MCStreamer *createThruMCStreamer(const Triple &T, MCContext &Ctx, std::unique_ptr<MCAsmBackend> &&MAB, std::unique_ptr<MCObjectWriter> &&OW, std::unique_ptr<MCCodeEmitter> &&Emitter, bool RelaxAll) { return createELFStreamer(Ctx, std::move(MAB), std::move(OW), std::move(Emitter), RelaxAll); } extern "C" void LLVMInitializeThruTargetMC() { for (Target *T : {&getTheThruTarget()}) { // Register the MC asm info. TargetRegistry::RegisterMCAsmInfo(*T, createThruMCAsmInfo); // Register the MC instruction info. TargetRegistry::RegisterMCInstrInfo(*T, createThruMCInstrInfo); // Register the MC register info. TargetRegistry::RegisterMCRegInfo(*T, createThruMCRegisterInfo); // Register the MC subtarget info. TargetRegistry::RegisterMCSubtargetInfo(*T, createThruMCSubtargetInfo); // Register the MCInstPrinter. TargetRegistry::RegisterMCInstPrinter(*T, createThruMCInstPrinter); // Register the object streamer TargetRegistry::RegisterELFStreamer(*T, createThruMCStreamer); } }
36.336634
82
0.616621
[ "object" ]
5f96daba25a89812159e8f549f3c10858cb9359b
9,945
cpp
C++
MotionCueingInterface/Source/MotionCueingInterface/Private/MotionProbe.cpp
ue4plugins/MotionCueingInterface
ba7e30bd00422474745fe961a86dee4d49403cf0
[ "BSD-3-Clause" ]
7
2019-05-09T19:14:29.000Z
2021-02-11T13:21:21.000Z
MotionCueingInterface/Source/MotionCueingInterface/Private/MotionProbe.cpp
ue4plugins/MotionCueingInterface
ba7e30bd00422474745fe961a86dee4d49403cf0
[ "BSD-3-Clause" ]
null
null
null
MotionCueingInterface/Source/MotionCueingInterface/Private/MotionProbe.cpp
ue4plugins/MotionCueingInterface
ba7e30bd00422474745fe961a86dee4d49403cf0
[ "BSD-3-Clause" ]
2
2020-09-18T03:40:00.000Z
2022-02-15T19:38:43.000Z
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "MotionProbe.h" // IMPLEMENTATION NOTE: fmaheux // The controller needs to get data at high frequency (100-1000Hz) // Unfortunately, the usual Unreal project will run at a lower frequency, usually between 30-60 Hz // So we must collect the necessary data from the BaseObject at low frequency (30 Hz). // Then we interpolate the data and send it at high frequency to the controller. (100-1000 Hz) // The low frequency function is TickComponent() // The high frequency function is TickController() // We interpolate between PreviousAverageHostData and CurrentAverageHostData // This solution adds a lag equal to the low frequency interval (33ms -> 30 Hz) * TickControllerAverageCount // If lag is an issue, then we could lerp between CurrentData and a "PredictionData" // Sets default values for this component's properties UMotionProbe::UMotionProbe() { PrimaryComponentTick.bCanEverTick = true; PrimaryComponentTick.bStartWithTickEnabled = true; PrimaryComponentTick.bAllowTickOnDedicatedServer = true; NextTickTime = 0.033f; // FORCED 30Hz NextTickDT = 0.0f; TickControllerCount = 0; TickControllerAverageCount = 10; OutputFrequency = 100; TickControllerTotal = 0; ControllerIP = "127.0.0.1"; ControllerPort = 3000; HostReceivePort = 3001; UseDebugMode = true; VibrationInput = EVibrationType::Acceleration; VehicleType = EVehicleType::Car; InterpolationType = EInterpolationType::Linear; TickControllerCounter = 0; Buffer.Reset(); } // Called when the game starts void UMotionProbe::BeginPlay() { Super::BeginPlay(); // Clamp params OutputFrequency = FMath::Clamp(OutputFrequency, 1, 1000); // Reset TickControllerTotal = 0; TickControllerCounter = 0; TickControllerCount = 0; NextTickDT = 0.0f; Buffer.Reset(); CurrentHostData.Reset(); PreviousHostData.Reset(); CurrentAverageHostData.Reset(); PreviousAverageHostData.Reset(); // Set low frequency timer for TickComponent() PrimaryComponentTick.TickInterval = NextTickTime; // Set high frequency timer for TickController() TimerDel.BindUFunction(this, FName("TickController")); GetWorld()->GetTimerManager().SetTimer(TimerHandle, TimerDel, 1.0f/OutputFrequency, true); // Init Host interface HostInterface->Initialize(); // Connect to controller HostInterface->ConnectToController(ControllerIP, ControllerPort, HostReceivePort); } // Called when the game ends void UMotionProbe::EndPlay(const EEndPlayReason::Type EndPlayReason) { Super::EndPlay(EndPlayReason); HostInterface->Cleanup(); GetWorld()->GetTimerManager().ClearTimer(TimerHandle); } void UMotionProbe::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); NextTickDT += DeltaTime; if (NextTickDT > NextTickTime) { // How many times we tick the controller in that frame TickControllerCounter += FMath::FloorToInt(NextTickDT * OutputFrequency); // Save previous data since we interpolate between "previous" and "current" PreviousHostData = CurrentHostData; // Get current data CurrentHostData.VehiclePosition = BaseObject->GetComponentLocation(); CurrentHostData.VehicleRotation = BaseObject->GetComponentRotation(); // Create vehicle reference frame FTransform TM = FTransform(); TM.SetRotation(CurrentHostData.VehicleRotation.Quaternion()); // Calculate forward vector in vehicle space FVector ForwardVector = CurrentHostData.VehiclePosition - PreviousHostData.VehiclePosition; ForwardVector = TM.Inverse().TransformVector(ForwardVector); // Vehicle Direction and Displacement ForwardVector.ToDirectionAndLength(CurrentHostData.VehicleDirection, CurrentHostData.VehicleDisplacement); // Vehicle Velocity CurrentHostData.VehicleVelocity = CurrentHostData.VehicleDisplacement / NextTickDT; // Vehicle Acceleration CurrentHostData.VehicleAcceleration = (CurrentHostData.VehicleVelocity - PreviousHostData.VehicleVelocity) / NextTickDT; // Kinematic velocity and acceleration per axis CurrentHostData.VelocityX = (ForwardVector.X) / NextTickDT; // forward speed CurrentHostData.VelocityY = (ForwardVector.Y) / NextTickDT; // side speed CurrentHostData.VelocityZ = (ForwardVector.Z) / NextTickDT; // up speed CurrentHostData.AccelerationX = (CurrentHostData.VelocityX - PreviousHostData.VelocityX) / NextTickDT; // forward acceleration CurrentHostData.AccelerationY = (CurrentHostData.VelocityY - PreviousHostData.VelocityY) / NextTickDT; // side acceleration CurrentHostData.AccelerationZ = (CurrentHostData.VelocityZ - PreviousHostData.VelocityZ) / NextTickDT; // up acceleration // Rotational motion CurrentHostData.PitchDisplacement = RotationalDeltaDeg(CurrentHostData.VehicleRotation.Pitch, PreviousHostData.VehicleRotation.Pitch); CurrentHostData.RollDisplacement = RotationalDeltaDeg(CurrentHostData.VehicleRotation.Roll, PreviousHostData.VehicleRotation.Roll); CurrentHostData.YawDisplacement = RotationalDeltaDeg(CurrentHostData.VehicleRotation.Yaw, PreviousHostData.VehicleRotation.Yaw); CurrentHostData.PitchVelocity = CurrentHostData.PitchDisplacement / NextTickDT; CurrentHostData.RollVelocity = CurrentHostData.RollDisplacement / NextTickDT; CurrentHostData.YawVelocity = CurrentHostData.YawDisplacement / NextTickDT; CurrentHostData.PitchAcceleration = (CurrentHostData.PitchVelocity - PreviousHostData.PitchVelocity) / NextTickDT; CurrentHostData.RollAcceleration = (CurrentHostData.RollVelocity - PreviousHostData.RollVelocity) / NextTickDT; CurrentHostData.YawAcceleration = (CurrentHostData.YawVelocity - PreviousHostData.YawVelocity) / NextTickDT; // reset NextTickDT = 0.0f; // accumulate data in buffer to average over time Buffer.Add(CurrentHostData); } // average over time if (Buffer.Num() >= TickControllerAverageCount) { TickControllerTotal = TickControllerCounter; TickControllerCounter = 0; TickControllerCount = 0; PreviousAverageHostData = CurrentAverageHostData; CurrentAverageHostData.Reset(); for (FMotionData& Data : Buffer) { CurrentAverageHostData = CurrentAverageHostData + Data; } CurrentAverageHostData = CurrentAverageHostData / Buffer.Num(); Buffer.Empty(); } // Debug print if (UseDebugMode) { DebugPrint(DeltaTime * 2); } } // Will be called in a burst, not at equal intervals unfortunatly // Will need to add a delay to avoid burst effect? void UMotionProbe::TickController() { // Interpolate data float T = float(TickControllerCount) / float(TickControllerTotal - 1); T = FMath::Clamp(T, 0.0f, 1.0f); FMotionData InterpolatedData = InterpolateMotionData(PreviousAverageHostData, CurrentAverageHostData, T); // receive data from controller HostInterface->ReceiveDataFromController(); // go though the flow of state to control state machine HostInterface->SetStateFlow(); // send data to controller HostInterface->SendDataToController(InterpolatedData); TickControllerCount++; } void UMotionProbe::DebugPrint(float DeltaTime) { if (GEngine != nullptr) { GEngine->AddOnScreenDebugMessage(15, DeltaTime, FColor::White, TEXT("Vehicle Roll accel (deg/s2): ") + GetFloatAsStringWithPrecision(CurrentAverageHostData.RollAcceleration, 2)); GEngine->AddOnScreenDebugMessage(14, DeltaTime, FColor::White, TEXT("Vehicle Pitch accel (deg/s2): ") + GetFloatAsStringWithPrecision(CurrentAverageHostData.PitchAcceleration, 2)); GEngine->AddOnScreenDebugMessage(13, DeltaTime, FColor::White, TEXT("Vehicle Yaw accel (deg/s2): ") + GetFloatAsStringWithPrecision(CurrentAverageHostData.YawAcceleration, 2)); GEngine->AddOnScreenDebugMessage(12, DeltaTime, FColor::White, TEXT("Vehicle Roll velocity (deg/s): ") + GetFloatAsStringWithPrecision(CurrentAverageHostData.RollVelocity, 2)); GEngine->AddOnScreenDebugMessage(11, DeltaTime, FColor::White, TEXT("Vehicle Pitch velocity (deg/s): ") + GetFloatAsStringWithPrecision(CurrentAverageHostData.PitchVelocity, 2)); GEngine->AddOnScreenDebugMessage(10, DeltaTime, FColor::White, TEXT("Vehicle Yaw velocity (deg/s): ") + GetFloatAsStringWithPrecision(CurrentAverageHostData.YawVelocity, 2)); GEngine->AddOnScreenDebugMessage(4, DeltaTime, FColor::White, TEXT("Current Roll (deg): ") + GetFloatAsStringWithPrecision(CurrentAverageHostData.VehicleRotation.Roll, 2)); GEngine->AddOnScreenDebugMessage(3, DeltaTime, FColor::White, TEXT("Current Pitch (deg): ") + GetFloatAsStringWithPrecision(CurrentAverageHostData.VehicleRotation.Pitch, 2)); GEngine->AddOnScreenDebugMessage(2, DeltaTime, FColor::White, TEXT("Current Yaw (deg): ") + GetFloatAsStringWithPrecision(CurrentAverageHostData.VehicleRotation.Yaw, 2)); GEngine->AddOnScreenDebugMessage(9, DeltaTime, FColor::White, TEXT("Vehicle VelocityZ (m/s): ") + GetFloatAsStringWithPrecision(CurrentAverageHostData.VelocityZ*0.01f, 2)); GEngine->AddOnScreenDebugMessage(8, DeltaTime, FColor::White, TEXT("Vehicle VelocityY (m/s): ") + GetFloatAsStringWithPrecision(CurrentAverageHostData.VelocityY*0.01f, 2)); GEngine->AddOnScreenDebugMessage(7, DeltaTime, FColor::White, TEXT("Vehicle VelocityX (m/s): ") + GetFloatAsStringWithPrecision(CurrentAverageHostData.VelocityX*0.01f, 2)); GEngine->AddOnScreenDebugMessage(6, DeltaTime, FColor::White, TEXT("Vehicle Acceleration (m/s2): ") + GetFloatAsStringWithPrecision(CurrentAverageHostData.VehicleAcceleration*0.01f, 2)); GEngine->AddOnScreenDebugMessage(5, DeltaTime, FColor::White, TEXT("Vehicle Velocity (m/s): ") + GetFloatAsStringWithPrecision(CurrentAverageHostData.VehicleVelocity*0.01f, 2)); GEngine->AddOnScreenDebugMessage(1, DeltaTime, FColor::Red, TEXT("Current tick: ") + FString::FromInt(TickControllerCount)); GEngine->AddOnScreenDebugMessage(0, DeltaTime, FColor::Red, TEXT("Total Tick: ") + FString::FromInt(TickControllerTotal)); } } void UMotionProbe::SetBaseObject(UMeshComponent* Input) { BaseObject = Input; }
44.596413
188
0.788135
[ "vector" ]
5fb1995bad6f60d0171f2193fde8b32217a79ce7
1,151
tpp
C++
uppdev/TopicTest/topic++/src/Src.tpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
2
2016-04-07T07:54:26.000Z
2020-04-14T12:37:34.000Z
uppdev/TopicTest/topic++/src/Src.tpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
uppdev/TopicTest/topic++/src/Src.tpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
GROUP("Core", "src") TOPIC("AIndex", "EN-US") #include "src$AIndex$EN-US.topic" END_TOPIC TOPIC("Vector", "CS-CZ") #include "src$Vector$CS-CZ.topic" END_TOPIC TOPIC("Array", "EN-US") #include "src$Array$EN-US.topic" END_TOPIC TOPIC("Array", "CS-CZ") #include "src$Array$CS-CZ.topic" END_TOPIC TOPIC("ArrayIndex", "EN-US") #include "src$ArrayIndex$EN-US.topic" END_TOPIC TOPIC("BiArray", "EN-US") #include "src$BiArray$EN-US.topic" END_TOPIC TOPIC("AMap", "EN-US") #include "src$AMap$EN-US.topic" END_TOPIC TOPIC("ArrayMap", "EN-US") #include "src$ArrayMap$EN-US.topic" END_TOPIC TOPIC("Vector", "EN-US") #include "src$Vector$EN-US.topic" END_TOPIC TOPIC("BiVector", "EN-US") #include "src$BiVector$EN-US.topic" END_TOPIC TOPIC("Segtor", "EN-US") #include "src$Segtor$EN-US.topic" END_TOPIC TOPIC("Bits", "CS-CZ") #include "src$Bits$CS-CZ.topic" END_TOPIC TOPIC("VectorMap", "EN-US") #include "src$VectorMap$EN-US.topic" END_TOPIC TOPIC("algo", "EN-US") #include "src$algo$EN-US.topic" END_TOPIC TOPIC("Index", "EN-US") #include "src$Index$EN-US.topic" END_TOPIC END_GROUP
17.984375
38
0.662033
[ "vector" ]
5fbceb0934c54be222cf59c83a0f2e51804af542
2,685
cpp
C++
toolkits/examples/offlineEvaluate.cpp
bin70/Toolkit
ef47b0bd97334a2ceca415f01570886bfbb11e4a
[ "MIT" ]
null
null
null
toolkits/examples/offlineEvaluate.cpp
bin70/Toolkit
ef47b0bd97334a2ceca415f01570886bfbb11e4a
[ "MIT" ]
null
null
null
toolkits/examples/offlineEvaluate.cpp
bin70/Toolkit
ef47b0bd97334a2ceca415f01570886bfbb11e4a
[ "MIT" ]
1
2021-06-30T08:03:44.000Z
2021-06-30T08:03:44.000Z
#include <common.hpp> #include <utils/argparse.hpp> #include <io/TrajIO.hpp> #include <io/PCDOperator.hpp> #include <point_cloud/common.hpp> #include <build_map/MapManager.hpp> #include <visualization/ShowUtils.hpp> using namespace std; FileOperator fop; ShowUtils su; bool ShowUtils::isPause = true; bool show_cloud = false; float resolution = 0.03; vector<float> calculateError(PointCloud::Ptr refer, PointCloud::Ptr test) { float sum = 0; int n = refer->points.size(); vector<float> dis_vec(n); for(int i=0; i<n; ++i) { dis_vec[i] = getDistance(refer->points[i], test->points[i]); sum += dis_vec[i]; } float mean = sum / n; float std_deviation = 0; for(int i=0; i<n; ++i) { std_deviation += pow(dis_vec[i]-mean, 2); } std_deviation = sqrt(std_deviation)/n; vector<float> error; error.push_back(mean); error.push_back(std_deviation); return error; } int main(int argc, const char **argv) { ArgumentParser parser; parser.addArgument("-i", "--input_dir", true); parser.addArgument("-r", "--resolution"); parser.addArgument("-s", "--show_cloud"); parser.addArgument("-c", "--calib_matrix"); parser.parse(argc, argv); consoleProgress(0); if(parser.count("resolution")) resolution = parser.get<float>("resolution"); if(parser.count("show_cloud")) { show_cloud = parser.get<bool>("show_cloud"); su.init("Test Cloud", &ShowUtils::keyboardEvent); } string input_dir = parser.get("input_dir"); string keypoints_path = input_dir+"/keypoints.txt"; string test_cloud_path = input_dir+"/test_cloud.pcd"; string calib_matrix = input_dir+"matrix.txt"; PointCloud::Ptr keypoints(new PointCloud); PointCloud::Ptr test_cloud(new PointCloud); pcl::io::loadPCDFile(keypoints_path, *keypoints); pcl::io::loadPCDFile(test_cloud_path, *test_cloud); if(parser.count("calib_matrix")) { Eigen::Matrix4d m = fop.loadMatrix(parser.get("calib_matrix")); pcl::transformPointCloud(*test_cloud, *test_cloud, m); } MapManager map(resolution); map.UpdateMap(test_cloud); su.ShowCloud(map.getMapPtr()); su.waitSpace(); PointType pointSel; PointCloud::Ptr correspond(new PointCloud); for(auto &point : *keypoints) { point.curvature = (float)map.getNearestPoint(point, pointSel); if(point.curvature) correspond->points.push_back(pointSel); } vector<float> error = calculateError(keypoints, correspond); std::cout << "Mean: " << error[0] << ", Deration: "<< error[1] << std::endl; return 0; }
26.584158
80
0.645438
[ "vector" ]
5fc81f216bf52d28157f56686da7b4abf25f8c70
6,889
cpp
C++
SDKs/CryCode/3.6.15/CryEngine/CryAction/Mannequin/ProceduralClipParticleEffect.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
4
2017-12-18T20:10:16.000Z
2021-02-07T21:21:24.000Z
SDKs/CryCode/3.6.15/CryEngine/CryAction/Mannequin/ProceduralClipParticleEffect.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
null
null
null
SDKs/CryCode/3.6.15/CryEngine/CryAction/Mannequin/ProceduralClipParticleEffect.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
3
2019-03-11T21:36:15.000Z
2021-02-07T21:21:26.000Z
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2011. ------------------------------------------------------------------------- History: - 14:12:2011 Created by Jean Geffroy *************************************************************************/ #include "StdAfx.h" #include "ICryMannequin.h" #include "ICryMannequinEditor.h" #include <CryExtension/Impl/ClassWeaver.h> #include "ParticleParams.h" struct SPlayParticleEffectParams : SProceduralParams { Vec3 posOffset; Ang3 rotOffset; float cloneAttachment;// Clone an attachment from the specified bone (so as to leave any existing attachment intact) }; class CProceduralClipParticleEffect : public TProceduralClip<SPlayParticleEffectParams> { public: CRYINTERFACE_BEGIN() CRYINTERFACE_ADD(IProceduralClip) CRYINTERFACE_END() CRYGENERATE_CLASS(CProceduralClipParticleEffect, "ParticleEffect", 0xb3bb85112d6d4bbb, 0xad5dc5048a050127) virtual void OnEnter(float blendTime, float duration, const SPlayParticleEffectParams &params) { if ( gEnv->IsEditor() && gEnv->pGame->GetIGameFramework()->GetMannequinInterface().IsSilentPlaybackMode() ) return; IEntity *pEntity = &m_scope->GetEntity(); const char *szEffectName = params.dataString.c_str(); if (IParticleEffect *pEffect = gEnv->pParticleManager->FindEffect(szEffectName, "Particle.SpawnEffect")) { IParticleEmitter *pEmitter = NULL; IAttachment* pAttachment = NULL; if (ICharacterInstance *pCharInst = m_scope->GetCharInst()) { if (IAttachmentManager *pAttachmentManager = pCharInst->GetIAttachmentManager()) { pAttachment = pAttachmentManager->GetInterfaceByNameCRC(params.dataCRC.crc); const char* szNewAttachmentName = NULL; int32 attachmentJointId = -1; const bool cloneExisting = params.cloneAttachment > 0.0f; if (cloneExisting && pAttachment && pAttachment->GetType() == CA_BONE) { // Clone an already existing attachment interface attachmentJointId = pAttachment->GetJointID(); szNewAttachmentName = pAttachment->GetName(); } else if (!pAttachment) { // No existing attachment interface: try to create a new, dedicated one if the given data string is a valid joint name attachmentJointId = pCharInst->GetIDefaultSkeleton().GetJointIDByCRC32(params.dataCRC.crc); szNewAttachmentName = params.dataCRC.GetString(); } if (szNewAttachmentName && attachmentJointId >= 0) { // Create new attachment interface with a unique name static uint16 s_clonedAttachmentCount = 0; ++s_clonedAttachmentCount; CryFixedStringT<64> attachmentCloneName; attachmentCloneName.Format("%s%s%u", szNewAttachmentName, "FXClone", s_clonedAttachmentCount); const char* pBoneName = pCharInst->GetIDefaultSkeleton().GetJointNameByID(attachmentJointId); const IAttachment* const pOriginalAttachment = pAttachment; pAttachment = pAttachmentManager->CreateAttachment(attachmentCloneName.c_str(), CA_BONE, pBoneName); m_ownedAttachmentNameCRC = pAttachment->GetNameCRC(); if (!pOriginalAttachment) { // Attachment newly created from a joint: clear the relative transform pAttachment->AlignJointAttachment(); } else { // Cloning an attachment: copy original transforms CRY_ASSERT(cloneExisting); pAttachment->SetAttAbsoluteDefault(pOriginalAttachment->GetAttAbsoluteDefault()); pAttachment->SetAttRelativeDefault(pOriginalAttachment->GetAttRelativeDefault()); } } if (pAttachment && (pAttachment->GetType() == CA_BONE)) { const Matrix34 offsetMatrix(Vec3(1.0f), Quat::CreateRotationXYZ(params.rotOffset), params.posOffset); CEffectAttachment *pEffectAttachment = new CEffectAttachment(pEffect, offsetMatrix.GetTranslation(), offsetMatrix.GetColumn1(), 1.0f); pAttachment->AddBinding(pEffectAttachment); pAttachment->UpdateAttModelRelative(); pEffectAttachment->ProcessAttachment(pAttachment); pEmitter = pEffectAttachment->GetEmitter(); } } } if (!pEmitter && !pAttachment && pEntity) { if (pEffect->GetParticleParams().eAttachType != GeomType_None) { int slot = pEntity->LoadParticleEmitter(-1, pEffect); SEntitySlotInfo slotInfo; if (pEntity->GetSlotInfo(slot, slotInfo)) { pEmitter = slotInfo.pParticleEmitter; } } else { const Matrix34 &transform = pEntity->GetWorldTM(); const Matrix34 localOffset(Vec3(1.0f), Quat(params.rotOffset), params.posOffset); pEmitter = pEffect->Spawn(true, transform * localOffset); } } if (pEmitter) { pEmitter->AddRef(); m_pEmitter = pEmitter; IMannequin &mannequinInterface = gEnv->pGame->GetIGameFramework()->GetMannequinInterface(); uint32 numListeners = mannequinInterface.GetNumMannequinGameListeners(); for (uint32 itListeners = 0; itListeners < numListeners; ++itListeners) { mannequinInterface.GetMannequinGameListener(itListeners)->OnSpawnParticleEmitter(pEmitter, m_scope->GetActionController()); } } } else { CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_WARNING, "CProceduralClipParticleEffect: could not load requested effect %s", szEffectName); } } virtual void OnExit(float blendTime) { if (m_pEmitter) { if (ICharacterInstance *pCharInst = m_scope->GetCharInst()) { if (IAttachmentManager *pAttachmentManager = pCharInst->GetIAttachmentManager()) { if (IAttachment *pAttachment = pAttachmentManager->GetInterfaceByNameCRC((m_ownedAttachmentNameCRC ? m_ownedAttachmentNameCRC : GetParams().dataCRC.crc))) { IAttachmentObject *pAttachmentObject = pAttachment->GetIAttachmentObject(); if (pAttachmentObject && (pAttachmentObject->GetAttachmentType() == IAttachmentObject::eAttachment_Effect)) { CEffectAttachment *pEffectAttachment = (CEffectAttachment *)pAttachmentObject; if (pEffectAttachment->GetEmitter() == m_pEmitter) { pAttachment->ClearBinding(); } } } } } SAFE_RELEASE(m_pEmitter); } if(m_ownedAttachmentNameCRC) { if (ICharacterInstance *pCharInst = m_scope->GetCharInst()) { if (IAttachmentManager *pAttachmentManager = pCharInst->GetIAttachmentManager()) { pAttachmentManager->RemoveAttachmentByNameCRC(m_ownedAttachmentNameCRC); m_ownedAttachmentNameCRC = 0; } } } } virtual void Update(float timePassed) { } private: IParticleEmitter *m_pEmitter; uint32 m_ownedAttachmentNameCRC; }; CProceduralClipParticleEffect::CProceduralClipParticleEffect() : m_pEmitter(NULL), m_ownedAttachmentNameCRC(0) { } CProceduralClipParticleEffect::~CProceduralClipParticleEffect() { } CRYREGISTER_CLASS(CProceduralClipParticleEffect)
33.441748
159
0.702424
[ "transform" ]
5fd32939601f831e48bbfe1f6785d903dd628af3
920
cpp
C++
part-02/1_08_two-sum.cpp
abhijeetbodas2001/DSA
ff244dea639a4a5c203e21df3efa47ff079f452a
[ "MIT" ]
null
null
null
part-02/1_08_two-sum.cpp
abhijeetbodas2001/DSA
ff244dea639a4a5c203e21df3efa47ff079f452a
[ "MIT" ]
null
null
null
part-02/1_08_two-sum.cpp
abhijeetbodas2001/DSA
ff244dea639a4a5c203e21df3efa47ff079f452a
[ "MIT" ]
null
null
null
// Problem: https://leetcode.com/problems/two-sum/ // O(n) time, O(n) space two pass solution. // One can also d this in a single pass, because (a + b) == (b + a) holds! class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { int len = nums.size(); // Value to index mapping unordered_map<int, int> index_of; for (int i = 0; i < len; i++) { index_of[nums[i]] = i; } vector<int> ans; for (int i = 0; i < len; i++) { int to_find = target - nums[i]; if (index_of.find(to_find) != index_of.end()) { if (index_of[to_find] != i) { ans.push_back(i); ans.push_back(index_of[to_find]); return ans; } } } // Control never reaches here as per given constraint. return ans; } };
28.75
74
0.488043
[ "vector" ]
5fd42a87ad2a75c4c17b77b925bbe15f03237a35
4,019
cpp
C++
Html_Table_Editor/Row.cpp
rickycorte/Html_Table_Editor
c379d0b268d2bced8d93454aa45396fd18af692c
[ "Apache-2.0" ]
null
null
null
Html_Table_Editor/Row.cpp
rickycorte/Html_Table_Editor
c379d0b268d2bced8d93454aa45396fd18af692c
[ "Apache-2.0" ]
1
2016-04-03T19:10:54.000Z
2016-04-03T19:15:07.000Z
Html_Table_Editor/Row.cpp
rickycorte/Html_Table_Editor
c379d0b268d2bced8d93454aa45396fd18af692c
[ "Apache-2.0" ]
1
2016-03-21T18:28:16.000Z
2016-03-21T18:28:16.000Z
/* Html_Table_Editor https://github.com/rickycorte/Html_Table_Editor Copyright (c) 2016 Ricky Corte Licenced under Apache 2.0 Licence http://www.apache.org/licenses/LICENSE-2.0 */ #include "Row.h" Row::Row(const std::string& input, const int rowNumber) : RowNumber(rowNumber) { std::string _input = input; //input = Reduce(input, ">",""); // remove the open tag part Console::Msg::Log("Row " + std::to_string(RowNumber+1) + ":\n "); try { PopulateCells(_input); } catch (const CustomExceptions::FileError& e) { Console::Msg::LogError("E0014 - Sorry, wrong row formatting."); Console::Msg::LogError("Details: " + (std::string)e.what()); throw e; } catch (const std::exception& e) { Console::Msg::LogError("E0007 - Sorry, something went wrong reading table row."); Console::Msg::LogError("Details: " + (std::string)e.what()); } } Row::Row(int cells) { for (int i=0; i < cells;i++) { Cell c = Cell{}; Cells.push_back(c); } } Row::~Row() { } void Row::PopulateCells(std::string input) { std::vector<std::string> Parts; if (!CheckForPresence(input, HCellCloseTag) && !CheckForPresence(input, CellCloseTag)) // this is a empty row { if (RowNumber == 0) throw CustomExceptions::FileError("E00013 - First line can't be empty!"); // different error solution throw CustomExceptions::ReadError("E0012 - This row is empty!"); } if (CheckForPresence(input, CellCloseTag)) // normal line { Parts = SplitAt(input, CellCloseTag); } if (CheckForPresence(input, HCellCloseTag)) // layout line { //layout line Parts = SplitAt(input, HCellCloseTag); if (RowNumber == 0) isLayout = true; else { Console::Msg::LogError("E0009 - Table layout can't be declared in row that is not the 1st."); } } //TODO: create a empty line for (int i = 0; i < Parts.size(); i++) { Cell c = Cell{ Parts[i],i }; Cells.push_back(c); } } std::string Row::GetRowContent(OutputKind kind) { std::string OpenTag,CloseTag,temp; switch (kind) { case OutputKind::clean: OpenTag = "Row "+std::to_string(RowNumber+1)+": |"; CloseTag = ""; break; case OutputKind::normal: //TODO: add style string for rows OpenTag = "<tr"+style+">"; CloseTag = "</tr>"; break; } temp += OpenTag; for (int i = 0; i < Cells.size(); i++) { temp += Cells[i].GetContentForOutPut(kind, isLayout); } temp += CloseTag; return temp; } void Row::AddEmptyCell(unsigned pos) { if (Cells.size() == 0) return; //don't add cells to empty rows Cell c = Cell{}; if (pos > Cells.size()) // check for out of table pos = Cells.size(); Cells.insert(Cells.begin() + pos, c); ReEnumCells(); } void Row::ReEnumCells() { for (int i = 0; i < Cells.size(); i++) { Cells[i].SetCellNumber(i); } } void Row::RemoveCell(unsigned pos) { if (pos < Cells.size()) Cells.erase(Cells.begin() + pos); ReEnumCells(); } void Row::SetCellContent(unsigned Cpos, std::string newContent) { if (Cpos+1 > Cells.size()) { Console::Msg::LogWarn("The row "+std::to_string(RowNumber+1)+" has a null cell at: "+std::to_string(Cpos+1)+", filling row with empty cells"); FillWithEmptyCells(Cpos + 1 - Cells.size()); } Cells[Cpos].SetContent(newContent); } void Row::SetAllCellsContent(std::string newContent) { for (int i = 0; i < Cells.size(); i++) { Cells[i].SetContent(newContent); } } void Row::FillWithEmptyCells(unsigned cellNumber) { for (int i = 0; i < cellNumber; i++) { Cell c = Cell{}; Cells.push_back(c); } } std::string Row::GetCellContent(unsigned pos) { if (pos >= Cells.size()) return ""; return Cells[pos].GetContent(); } void Row::JoinCellContent(unsigned cPos, std::string pattern, std::string c2Content) { if (cPos >= Cells.size()) return; Cells[cPos].JoinContent(pattern, c2Content); } void Row::SetCellStyle(unsigned cPos, std::string newStyle) { if (cPos >= Cells.size() || IsEmpty()) return ; Cells[cPos].SetStyle(newStyle); } void Row::SetCellsStyle(std::string newStyle) { for (int i = 0; i < Cells.size(); i++) SetCellStyle(i, newStyle); }
21.37766
144
0.655885
[ "vector" ]
5fdcd24618787848ca8cfe02509d1e0c68cb99d8
12,103
cpp
C++
extractor/zio.cpp
eiselekd/dumpbin-py-zfs-rescue
042ce02a574c3216a13b3b3c1a78b824d584eb14
[ "BSD-3-Clause" ]
5
2018-08-02T10:11:21.000Z
2021-01-30T13:31:07.000Z
extractor/zio.cpp
eiselekd/dumpbin-py-zfs-rescue
042ce02a574c3216a13b3b3c1a78b824d584eb14
[ "BSD-3-Clause" ]
1
2020-09-29T08:41:02.000Z
2020-09-29T08:41:02.000Z
extractor/zio.cpp
eiselekd/dumpbin-py-zfs-rescue
042ce02a574c3216a13b3b3c1a78b824d584eb14
[ "BSD-3-Clause" ]
1
2020-01-24T07:35:41.000Z
2020-01-24T07:35:41.000Z
#include "defs.h" #include <assert.h> #include <stddef.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "zio.h" #undef MAX #undef MIN #undef roundup #define roundup(x, y) ((((x) + ((y) - 1)) / (y)) * (y)) #define MAX(x, y) (((x) > (y)) ? (x) : (y)) #define MIN(x, y) (((x) < (y)) ? (x) : (y)) #define B_FALSE 0 typedef uint32_t uint_t ; typedef struct raidz_col { uint64_t rc_devidx; /* child device index for I/O */ uint64_t rc_offset; /* device offset */ uint64_t rc_size; /* I/O size */ abd_t *rc_abd; /* I/O data */ void *rc_gdata; /* used to store the "good" version */ int rc_error; /* I/O error for this device */ uint8_t rc_tried; /* Did we attempt this I/O column? */ uint8_t rc_skipped; /* Did we skip this I/O column? */ } raidz_col_t; typedef struct raidz_map { uint64_t rm_cols; /* Regular column count */ uint64_t rm_scols; /* Count including skipped columns */ uint64_t rm_bigcols; /* Number of oversized columns */ uint64_t rm_asize; /* Actual total I/O size */ uint64_t rm_missingdata; /* Count of missing data devices */ uint64_t rm_missingparity; /* Count of missing parity devices */ uint64_t rm_firstdatacol; /* First data column/parity count */ uint64_t rm_nskip; /* Skipped sectors for padding */ uint64_t rm_skipstart; /* Column index of padding start */ abd_t *rm_abd_copy; /* rm_asize-buffer of copied data */ uintptr_t rm_reports; /* # of referencing checksum reports */ uint8_t rm_freed; /* map no longer has referencing ZIO */ uint8_t rm_ecksuminjected; /* checksum error was injected */ raidz_col_t rm_col[1]; /* Flexible array of I/O columns */ } raidz_map_t; //#define ASSERT3U(l,op,r) assert(l op r); //#define ASSERT(l) assert(l); typedef struct zio { uint64_t io_offset; uint64_t io_size; struct abd *io_abd; void *io_vsd; } zio_t; void abd_free(abd_t *abd) { if (abd->abd_flags & ABD_FLAG_OWNER) { free(abd->abd_buf); } free(abd); } abd_t * abd_alloc_linear(uint64_t size, int is_metadata) { (void)is_metadata; abd_t *c = (abd_t *)malloc(sizeof(abd_t)); c->abd_flags = (abd_flags_t) (ABD_FLAG_OWNER | ABD_FLAG_LINEAR); c->abd_parent = 0; c->abd_size = size; c->abd_buf = malloc(size);; return c; } abd_t * abd_get_offset_size(abd_t *sabd, size_t off, uint64_t size) { abd_t *c = (abd_t *)malloc(sizeof(abd_t)); c->abd_flags = (abd_flags_t) 0; c->abd_parent = sabd; c->abd_size = size; c->abd_buf = ((char*)c->abd_parent->abd_buf) + off; return c; } /* * Divides the IO evenly across all child vdevs; usually, dcols is * the number of children in the target vdev. * * Avoid inlining the function to keep vdev_raidz_io_start(), which * is this functions only caller, as small as possible on the stack. */ raidz_map_t * vdev_raidz_map_alloc(zio_t *zio, uint64_t ashift, uint64_t dcols, uint64_t nparity) { raidz_map_t *rm; /* The starting RAIDZ (parent) vdev sector of the block. */ uint64_t b = zio->io_offset >> ashift; /* The zio's size in units of the vdev's minimum sector size. */ uint64_t s = zio->io_size >> ashift; /* The first column for this stripe. */ uint64_t f = b % dcols; /* The starting byte offset on each child vdev. */ uint64_t o = (b / dcols) << ashift; uint64_t q, r, c, bc, col, acols, scols, coff, devidx, asize, tot; uint64_t off = 0; printf("[+] : 0x%llx:0x%lx ashift:%lu,%lu,%lu\n", (long long unsigned)zio->io_offset, (long unsigned)zio->io_size, ashift, dcols, nparity); /* * "Quotient": The number of data sectors for this stripe on all but * the "big column" child vdevs that also contain "remainder" data. */ q = s / (dcols - nparity); /* * "Remainder": The number of partial stripe data sectors in this I/O. * This will add a sector to some, but not all, child vdevs. */ r = s - q * (dcols - nparity); /* The number of "big columns" - those which contain remainder data. */ bc = (r == 0 ? 0 : r + nparity); /* * The total number of data and parity sectors associated with * this I/O. */ tot = s + nparity * (q + (r == 0 ? 0 : 1)); /* acols: The columns that will be accessed. */ /* scols: The columns that will be accessed or skipped. */ if (q == 0) { /* Our I/O request doesn't span all child vdevs. */ acols = bc; scols = MIN(dcols, roundup(bc, nparity + 1)); } else { acols = dcols; scols = dcols; } ASSERT3U(acols, <=, scols); rm = (raidz_map_t *) malloc(sizeof(raidz_map_t) + ((scols-1) * sizeof(raidz_col_t))); rm->rm_cols = acols; rm->rm_scols = scols; rm->rm_bigcols = bc; rm->rm_skipstart = bc; rm->rm_missingdata = 0; rm->rm_missingparity = 0; rm->rm_firstdatacol = nparity; rm->rm_abd_copy = NULL; rm->rm_reports = 0; rm->rm_freed = 0; rm->rm_ecksuminjected = 0; asize = 0; for (c = 0; c < scols; c++) { col = f + c; coff = o; if (col >= dcols) { col -= dcols; coff += 1ULL << ashift; } rm->rm_col[c].rc_devidx = col; rm->rm_col[c].rc_offset = coff; rm->rm_col[c].rc_abd = NULL; rm->rm_col[c].rc_gdata = NULL; rm->rm_col[c].rc_error = 0; rm->rm_col[c].rc_tried = 0; rm->rm_col[c].rc_skipped = 0; if (c >= acols) rm->rm_col[c].rc_size = 0; else if (c < bc) rm->rm_col[c].rc_size = (q + 1) << ashift; else rm->rm_col[c].rc_size = q << ashift; asize += rm->rm_col[c].rc_size; } ASSERT3U(asize, ==, tot << ashift); rm->rm_asize = roundup(asize, (nparity + 1) << ashift); rm->rm_nskip = roundup(tot, nparity + 1) - tot; ASSERT3U(rm->rm_asize - asize, ==, rm->rm_nskip << ashift); ASSERT3U(rm->rm_nskip, <=, nparity); for (c = 0; c < rm->rm_firstdatacol; c++) rm->rm_col[c].rc_abd = abd_alloc_linear(rm->rm_col[c].rc_size, B_FALSE); rm->rm_col[c].rc_abd = abd_get_offset_size(zio->io_abd, 0, rm->rm_col[c].rc_size); off = rm->rm_col[c].rc_size; for (c = c + 1; c < acols; c++) { rm->rm_col[c].rc_abd = abd_get_offset_size(zio->io_abd, off, rm->rm_col[c].rc_size); off += rm->rm_col[c].rc_size; } /* * If all data stored spans all columns, there's a danger that parity * will always be on the same device and, since parity isn't read * during normal operation, that that device's I/O bandwidth won't be * used effectively. We therefore switch the parity every 1MB. * * ... at least that was, ostensibly, the theory. As a practical * matter unless we juggle the parity between all devices evenly, we * won't see any benefit. Further, occasional writes that aren't a * multiple of the LCM of the number of children and the minimum * stripe width are sufficient to avoid pessimal behavior. * Unfortunately, this decision created an implicit on-disk format * requirement that we need to support for all eternity, but only * for single-parity RAID-Z. * * If we intend to skip a sector in the zeroth column for padding * we must make sure to note this swap. We will never intend to * skip the first column since at least one data and one parity * column must appear in each row. */ ASSERT(rm->rm_cols >= 2); ASSERT(rm->rm_col[0].rc_size == rm->rm_col[1].rc_size); if (rm->rm_firstdatacol == 1 && (zio->io_offset & (1ULL << 20))) { devidx = rm->rm_col[0].rc_devidx; o = rm->rm_col[0].rc_offset; rm->rm_col[0].rc_devidx = rm->rm_col[1].rc_devidx; rm->rm_col[0].rc_offset = rm->rm_col[1].rc_offset; rm->rm_col[1].rc_devidx = devidx; rm->rm_col[1].rc_offset = o; if (rm->rm_skipstart == 0) rm->rm_skipstart = 1; } return (rm); } const char *DMU_TYPE_DESC[] = { "unallocated", // 0 "object directory", // 1 "object array", // 2 "packed nvlist", // 3 "packed nvlist size", // 4 "bpobj", // 5 "bpobj header", // 6 "SPA space map header", // 7 "SPA space map", // 8 "ZIL intent log", // 9 "DMU dnode", // 10 "DMU objset", // 11 "DSL directory", // 12 "DSL directory child map", // 13 "DSL dataset snap map", // 14 "DSL props", // 15 "DSL dataset", // 16 "ZFS znode", // 17 "ZFS V0 ACL", // 18 "ZFS plain file", // 19 "ZFS directory", // 20 "ZFS master node", // 21 "ZFS delete queue", // 22 "zvol object", // 23 "zvol prop", // 24 "other uint8[]", // 25 "other uint64[]", // 26 "other ZAP", // 27 "persistent error log", // 28 "SPA history", // 29 "SPA history offsets", // 30 "Pool properties", // 31 "DSL permissions", // 32 "ZFS ACL", // 33 "ZFS SYSACL", // 34 "FUID table", // 35 "FUID table size", // 36 "DSL dataset next clones", // 37 "scan work queue", // 38 "ZFS user/group used", // 39 "ZFS user/group quota", // 40 "snapshot refcount tags", // 41 "DDT ZAP algorithm", // 42 "DDT statistics", // 43 "System attributes", // 44 "SA master node", // 45 "SA attr registration", // 46 "SA attr layouts", // 47 "scan translations", // 48 "deduplicated block", // 49 "DSL deadlist map", // 50 "DSL deadlist map hdr", // 51 "DSL dir clones", // 52 "bpobj subobj" // 53 }; void vdev_raidz_free(raidz_map_t *rm) { uint i; for (i = 0; i < rm->rm_cols; i++) { abd_free(rm->rm_col[i].rc_abd); } free(rm); } Raidz1Device::Raidz1Device(std::vector<std::string> &vdevs) : vdevs(vdevs) { assert(vdevs.size() == DCOLS); }; abd_t *Raidz1Device::read_physical(uint64_t offset, uint64_t psize) { zio_t io; uint i; uint64_t ashift = 12; raidz_map_t *rm; abd_t *c; io.io_offset = offset; io.io_size = psize; io.io_abd = c = abd_alloc_linear(psize, B_FALSE); rm = vdev_raidz_map_alloc(&io, ASHIFT, DCOLS, NPARITY); for (i = 0; i < rm->rm_cols; i++) { read_at(rm->rm_col[i].rc_abd, rm->rm_col[i].rc_devidx, rm->rm_col[i].rc_offset, rm->rm_col[i].rc_size); } vdev_raidz_free(rm); return c; } int Raidz1Device::read_at(abd_t *c, int vdev, uint64_t offset, uint64_t psize) { int fd; fd = open(vdevs[vdev].c_str(), O_RDONLY); pread64(fd, c->abd_buf, psize, offset); close(fd); } int Raidz1Device::loadLabel(int dev, int labidx) { vdev_label_t l; abd_t abd; abd.abd_buf = &l; uint64_t offset = 0; uint64_t psize = sizeof(vdev_label_t); struct uberblock *u; int usz = 1 << ASHIFT; int i; int ucnt = sizeof(l.vl_uberblock) / usz; read_at(&abd, dev, offset, psize); for (i = 0; i < ucnt; i++) { u = (struct uberblock *)&(l.vl_uberblock[i*usz]); tgxs[u->ub_txg] = *u; } } int Raidz1Device::loadMos(uint64_t tgx) { struct uberblock u; u = tgxs[tgx]; DNode *d = loadDnode(u.ub_rootbp); assert(d->type() == DMU_OT_DSL_DATASET); DSLDataset *mos = static_cast<DSLDataset*>(d); for (uint64_t i = 0; i < mos->len(); i++) { DNode *e = (*mos)[i]; if (e && e->type() == DMU_OT_DSL_DATASET) { datasets[i] = e; } } DNode *root_ds = (*mos)[1]; assert(root_ds->type() == DMU_OT_OBJECT_DIRECTORY); Zap *root_ds_z = root_ds->zap(); uint64_t rootdir_id = (*root_ds_z)["root_dataset"]; DNode *rdir = (*mos)[rootdir_id]; } DNode *Raidz1Device::loadDnode(blkptr_t &p) { dnode_phys_t *d; abd_t *c; c = loadBlkPtr(p); if (!c) return 0; d = (dnode_phys_t *)c->abd_buf; switch (d->dn_type) { case DMU_OT_DSL_DIR: break; case DMU_OT_DSL_DATASET: break; } return 0; } abd_t *Raidz1Device::loadBlkPtr(blkptr_t &p) { abd_t *c = 0; for (int i = 0; i < 3; i++) { dva d = p.blk_dva[i]; uint64_t asize; uint64_t offset; asize = (d.dva_word[0] & 0xffffffUL) << 9; offset = d.dva_word[1] & 0x7fffffffffffffffUL; c = read_physical(offset, asize); if (c) { return c; } } return 0; } int Raidz1Device::loadChildDS(uint64_t dsid) { } /* Local Variables: mode:c++ c-file-style:"linux" End: */
27.444444
140
0.609601
[ "object", "vector" ]
5fe71a1b8785c449af55668529719985af91c083
4,046
cpp
C++
ipsc/y2018/c.cpp
winger/team-competitions
df24b920181ddcee443764e956191ffc097f581f
[ "Unlicense" ]
1
2018-10-08T07:13:27.000Z
2018-10-08T07:13:27.000Z
ipsc/y2018/c.cpp
winger/team-competitions
df24b920181ddcee443764e956191ffc097f581f
[ "Unlicense" ]
null
null
null
ipsc/y2018/c.cpp
winger/team-competitions
df24b920181ddcee443764e956191ffc097f581f
[ "Unlicense" ]
null
null
null
#include <iostream> #include <tuple> #include <sstream> #include <vector> #include <cmath> #include <ctime> #include <bitset> #include <cassert> #include <cstdio> #include <queue> #include <set> #include <map> #include <fstream> #include <cstdlib> #include <string> #include <cstring> #include <algorithm> #include <numeric> #define mp make_pair #define mt make_tuple #define fi first #define se second #define pb push_back #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() #define forn(i, n) for (int i = 0; i < (int)(n); ++i) #define for1(i, n) for (int i = 1; i <= (int)(n); ++i) #define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i) #define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i) using namespace std; typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<pii> vpi; typedef vector<vi> vvi; typedef long long i64; typedef vector<i64> vi64; typedef vector<vi64> vvi64; typedef pair<i64, i64> pi64; typedef double ld; template<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; } template<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; } const int maxn = 5010; const int K = 2; const i64 P = 1000000000 + 7; //i64 dp[maxn][maxn]; //i64 fact[K * maxn], tcaf[K * maxn]; i64 pe[K * maxn]; i64 pcnk[K * maxn][K * maxn]; vi fact, inv; i64 deg(i64 x, i64 d) { if (d < 0) d += P - 1; d %= P - 1; i64 y = 1; while (d) { if (d & 1) (y *= x) %= P; (x *= x) %= P; d /= 2; } return y; } long long FactDivP(long long N, long long P = ::P) { long long res = 0; N /= P; while (N > 0) { res += N; N /= P; } return res; } long long FactGModP(long long N, bool isinv = false, long long P = ::P) { if (N == 0) { return 1; } long long res; if ((N / P) % 2 == 0) { res = 1; } else { res = P - 1; } res = isinv ? inv[N % P] : fact[N % P]; return (res * FactGModP(N / P, isinv, P)) % P; } long long CnkModP(long long N, long long K, long long P = ::P) { if (K < 0 || K > N) return 0; // assert(N < P && K < P && K <= N); return 1LL * fact[N] * inv[N - K] % P; if (FactDivP(N, P) > FactDivP(K, P) + FactDivP(N - K, P)) { return 0; } long long res = FactGModP(N); res *= FactGModP(K, 1); res %= P; res *= FactGModP(N - K, 1); res %= P; return res; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.precision(10); cout << fixed; #ifdef LOCAL_DEFINE freopen("input.txt", "rt", stdin); #endif fact.resize(P); fact[0] = 1; // for1(i, K * maxn - 1) fact[i] = i * fact[i - 1] % P; // forn(i, K * maxn) tcaf[i] = deg(fact[i], -1); for1(i, P - 1) fact[i] = 1LL * fact[i - 1] * i % P; inv.resize(P); inv[1] = 1; fore(i, 2, P - 1) inv[i] = -1LL * inv[P % i] * (P / i) % P; inv[0] = 1; for1(i, P - 1) inv[i] = 1LL * inv[i] * inv[i - 1] % P; //pe[0] = 1; //for1(i, K * maxn - 1) (pe[i] = pe[i - 1] + 1LL * deg(fact[i], -1) * (i % 2 ? P-1 : 1)) %= P; pcnk[0][0] = 1; forn(i, K * maxn - 1) forn(j, i + 1) forn(k, 2) (pcnk[i + 1][j + k] += pcnk[i][j]) %= P; for1(i, K * maxn - 1) forn(j, i + 1) { if ((i - j) % 2) pcnk[i][j] = -pcnk[i][j]; (pcnk[i][j] += pcnk[i - 1][j]) %= P; } int N; cin >> N; for1(n, N) { cerr << n << '\n'; i64 S = 0; for1(i, K * n) { i64 z = pcnk[K * n][i]; i64 res = 0; for1(j, i) { i64 t = 1LL * i * (i - 1) * j * (j - 1) / 4 % P; if (t < n) continue; i64 v = CnkModP(t, n) * pcnk[K * n][j]; if (j < i) v *= 2; (res += v) %= P; } (S += res * z) %= P; } (S *= inv[n]) %= P; if (S < 0) S += P; cout << S << '\n'; } #ifdef LOCAL_DEFINE cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n"; #endif return 0; }
24.822086
98
0.47479
[ "vector" ]
5feacb01e46321755a3421131d2f72d314360507
3,014
cpp
C++
test/test_entity.cpp
rht/ESL
f883155a167d3c48e5ecdca91c8302fefc901c22
[ "Apache-2.0" ]
37
2019-10-13T12:23:32.000Z
2022-03-19T10:40:29.000Z
test/test_entity.cpp
rht/ESL
f883155a167d3c48e5ecdca91c8302fefc901c22
[ "Apache-2.0" ]
3
2020-03-20T04:44:06.000Z
2021-01-12T06:18:33.000Z
test/test_entity.cpp
vishalbelsare/ESL
cea6feda1e588d5f441742dbb1e4c5479b47d357
[ "Apache-2.0" ]
10
2019-11-06T15:59:06.000Z
2021-08-09T17:28:24.000Z
/// \file test_entity.cpp /// /// \brief /// /// \authors Maarten P. Scholl /// \date 2019-08-15 /// \copyright Copyright 2017-2019 The Institute for New Economic Thinking, /// Oxford Martin School, University of Oxford /// /// 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. /// /// You may obtain instructions to fulfill the attribution /// requirements in CITATION.cff /// #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE entity #include <boost/test/included/unit_test.hpp> #include <esl/simulation/entity.hpp> #include <utility> BOOST_AUTO_TEST_SUITE(ESL) struct dummy_base : esl::entity<dummy_base> { dummy_base(esl::identity<dummy_base> i = esl::identity<dummy_base>()) : esl::entity<dummy_base>(std::move(i)) {} virtual ~dummy_base() = default; }; struct dummy_derived_direct : dummy_base , esl::identifiable_as<dummy_derived_direct> { dummy_derived_direct(esl::identity<dummy_derived_direct> i) : dummy_base(i) {} }; BOOST_AUTO_TEST_CASE(entity_implicit_conversion) { esl::identity<dummy_base> i = {1, 2, 3}; esl::identity<dummy_derived_direct> j = {1, 2, 3}; dummy_derived_direct ddd {j}; BOOST_CHECK_EQUAL(i, static_cast<esl::identity<dummy_base>>(ddd)); } BOOST_AUTO_TEST_CASE(entity_implicit_dynamic_conversion) { esl::identity<dummy_derived_direct> j = {1, 2, 3}; std::unique_ptr<esl::identifiable_as<dummy_derived_direct>> p = std::make_unique<dummy_derived_direct>(j); BOOST_CHECK_NO_THROW(auto X = static_cast<esl::identity<dummy_derived_direct>>(*p);); } BOOST_AUTO_TEST_CASE(entity_create_child) { esl::identity<dummy_base> i = {1, 2}; dummy_base db(i); auto ddd0 = db.template create<dummy_derived_direct>(); auto ddd1 = db.template create<dummy_derived_direct>(); auto c0 = static_cast<esl::identity<dummy_base>>(ddd0); auto c1 = static_cast<esl::identity<dummy_base>>(ddd1); BOOST_CHECK_LT(c0, c1); } /* #if WITH_PYTHON BOOST_AUTO_TEST_CASE(entity_create_python_object) { esl::identity<boost::python::object> i = {1, 2}; esl::entity<boost::python::object> e(i); BOOST_CHECK_NO_THROW(e.template create<boost::python::object>()); auto c = e.template create<boost::python::object>(); BOOST_CHECK_LT(i, c); } #endif */ BOOST_AUTO_TEST_SUITE_END() // ESL
28.704762
111
0.671201
[ "object" ]
5ff94560164e1f77977cd387ac2e6a9ce2378c2a
3,150
hpp
C++
include/iris/internal/broker_impl.hpp
p-ranav/iris
d45ff0a719196eaf3630cbc29ffda41dd9915593
[ "MIT" ]
50
2020-04-07T13:38:29.000Z
2022-01-21T11:25:33.000Z
include/iris/internal/broker_impl.hpp
p-ranav/iris
d45ff0a719196eaf3630cbc29ffda41dd9915593
[ "MIT" ]
1
2020-04-14T09:42:53.000Z
2020-04-14T14:07:20.000Z
include/iris/internal/broker_impl.hpp
p-ranav/iris
d45ff0a719196eaf3630cbc29ffda41dd9915593
[ "MIT" ]
3
2020-04-10T12:55:16.000Z
2020-04-25T09:51:55.000Z
#pragma once #include <atomic> #include <functional> #include <iris/cereal/archives/json.hpp> #include <iris/cereal/archives/portable_binary.hpp> #include <iris/cppzmq/zmq.hpp> #include <iris/kwargs.hpp> #include <iris/operation.hpp> #include <iris/task_system.hpp> #include <memory> #include <queue> #include <string> #include <vector> namespace iris { namespace internal { class BrokerImpl { std::uint8_t id_; class Component *component_; std::reference_wrapper<zmq::context_t> context_; std::unique_ptr<zmq::socket_t> frontend_; Endpoints frontend_endpoints_; std::unique_ptr<zmq::socket_t> backend_; Endpoints backend_endpoints_; std::thread thread_; std::atomic_bool started_{false}; std::atomic_bool done_{false}; std::atomic_bool ready_{false}; public: template <typename E> BrokerImpl(std::uint8_t id, Component *parent, zmq::context_t &context, E &&frontend_endpoints, E &&backend_endpoints) : id_(id), component_(parent), context_(context), frontend_endpoints_(std::move(frontend_endpoints)), backend_endpoints_(std::move(backend_endpoints)) { frontend_ = std::make_unique<zmq::socket_t>(context_, ZMQ_ROUTER); backend_ = std::make_unique<zmq::socket_t>(context_, ZMQ_DEALER); for (auto &e : frontend_endpoints_) { frontend_->bind(e); } for (auto &e : backend_endpoints_) { backend_->bind(e); } } ~BrokerImpl() { if (started_) if (thread_.joinable()) thread_.join(); frontend_->close(); backend_->close(); started_ = false; } void recv() { // Initialize poll set zmq::pollitem_t items[] = { {static_cast<void *>(*frontend_.get()), 0, ZMQ_POLLIN, 0}, {static_cast<void *>(*backend_.get()), 0, ZMQ_POLLIN, 0}}; // Switch messages between sockets while (!done_) { zmq::message_t message; zmq::poll(&items[0], 2, -1); if (items[0].revents & ZMQ_POLLIN) { while (!done_) { // Process all parts of the message auto ret = frontend_->recv(message, zmq::recv_flags::none); if (ret) { // Multipart detection auto more = frontend_->get(zmq::sockopt::rcvmore); backend_->send(message, more ? zmq::send_flags::sndmore : zmq::send_flags::none); if (!more) break; } } } if (items[1].revents & ZMQ_POLLIN) { while (!done_) { // Process all parts of the message auto ret = backend_->recv(message, zmq::recv_flags::none); if (ret) { // Multipart detection auto more = backend_->get(zmq::sockopt::rcvmore); frontend_->send(message, more ? zmq::send_flags::sndmore : zmq::send_flags::none); if (!more) break; } } } } } void start() { thread_ = std::thread(&BrokerImpl::recv, this); started_ = true; ready_ = true; } void stop() { done_ = true; } }; } // namespace internal } // namespace iris
27.391304
73
0.595873
[ "vector" ]
5fff0b9b4dc83525dbf72934d1762f81bcbd660b
11,011
cpp
C++
modules/task_3/kruglov_algorithm_strassen/Strassen_algorithm.cpp
Stepakrap/pp_2021_autumn
716803a14183172337d51712fb28fe8e86891a3d
[ "BSD-3-Clause" ]
1
2021-12-09T17:20:25.000Z
2021-12-09T17:20:25.000Z
modules/task_3/kruglov_algorithm_strassen/Strassen_algorithm.cpp
Stepakrap/pp_2021_autumn
716803a14183172337d51712fb28fe8e86891a3d
[ "BSD-3-Clause" ]
null
null
null
modules/task_3/kruglov_algorithm_strassen/Strassen_algorithm.cpp
Stepakrap/pp_2021_autumn
716803a14183172337d51712fb28fe8e86891a3d
[ "BSD-3-Clause" ]
3
2022-02-23T14:20:50.000Z
2022-03-30T09:00:02.000Z
// Copyright 2021 Kruglov Aleksei #include <mpi.h> #include <algorithm> #include <iostream> #include <climits> #include <fstream> #include <sstream> #include <random> #include <cmath> #include "../../../modules/task_3/kruglov_algorithm_strassen/Strassen_algorithm.h" Matrix get_random_matrix(int height, int width, double max_number) { std::random_device device; std::mt19937 gen(device()); Matrix matrix(height, std::vector<double>(width)); std::uniform_real_distribution<> dis(-max_number, max_number); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { matrix[i][j] = (dis(gen)); } } return matrix; } Matrix reference_multiply(const Matrix& a, const Matrix& b) { Matrix res(a.size(), std::vector<double>(b[0].size())); for (std::size_t i = 0; i < a.size(); i++) { for (std::size_t j = 0; j < b[0].size(); j++) { for (std::size_t k = 0; k < a[0].size(); k++) { res[i][j] += a[i][k] * b[k][j]; } } } return res; } Matrix parallel_multiply(const Matrix& a, const Matrix& b) { int proc_num, proc_rank; MPI_Comm_size(MPI_COMM_WORLD, &proc_num); MPI_Comm_rank(MPI_COMM_WORLD, &proc_rank); int n = static_cast<int>(a.size()); MPI_Bcast(reinterpret_cast<void*>(&n), 1, MPI_INT, 0, MPI_COMM_WORLD); if (n <= 2 && proc_rank == 0) { return reference_multiply(a, b); } // exit for other processes if (n <= 2) { return Matrix(); } Matrix a11, a12, a21, a22; Matrix b11, b12, b21, b22; if (proc_rank == 0) { n = n / 2; a11 = Matrix(n, std::vector<double>(n)); a12 = Matrix(n, std::vector<double>(n)); a21 = Matrix(n, std::vector<double>(n)); a22 = Matrix(n, std::vector<double>(n)); b11 = Matrix(n, std::vector<double>(n)); b12 = Matrix(n, std::vector<double>(n)); b21 = Matrix(n, std::vector<double>(n)); b22 = Matrix(n, std::vector<double>(n)); } if (proc_rank == 0) { std::vector<Matrix> all; all = split(a); a11 = std::move(all[0]), a12 = std::move(all[1]), a21 = std::move(all[2]), a22 = std::move(all[3]); all = split(b); b11 = std::move(all[0]), b12 = std::move(all[1]), b21 = std::move(all[2]), b22 = std::move(all[3]); } Matrix p1, p2, p3, p4, p5, p6, p7; p1 = parallel_multiply(matrix_sum(a11, a22), matrix_sum(b11, b22)); p2 = parallel_multiply(matrix_sum(a21, a22), b11); p3 = parallel_multiply(a11, matrix_sub(b12, b22)); p4 = parallel_multiply(a22, matrix_sub(b21, b11)); p5 = parallel_multiply(matrix_sum(a11, a12), b22); p6 = parallel_multiply(matrix_sub(a21, a11), matrix_sum(b11, b12)); p7 = parallel_multiply(matrix_sub(a12, a22), matrix_sum(b21, b22)); auto c11 = matrix_sum(matrix_sum(p1, p4), matrix_sub(p7, p5)); auto c12 = matrix_sum(p3, p5); auto c21 = matrix_sum(p2, p4); auto c22 = matrix_sum(matrix_sub(p1, p2), matrix_sum(p3, p6)); return merge(c11, c12, c21, c22); } std::vector<Matrix> split(const Matrix& a) { int n = static_cast<int>(a.size() / 2); std::vector<Matrix> result(4, Matrix(n)); for (int i = 0; i < n; i++) { result[0][i] = { a[i].begin(), a[i].begin() + n }; result[1][i] = { a[i].begin() + n, a[i].begin() + 2 * n }; result[2][i] = { a[i + n].begin(), a[i + n].begin() + n }; result[3][i] = { a[i + n].begin() + n, a[i + n].begin() + 2 * n }; } return result; } Matrix merge(const Matrix& a, const Matrix& b, const Matrix& c, const Matrix& d) { int n = static_cast<int>(a.size()); Matrix result(n * 2, std::vector<double>(n * 2)); for (int i = 0; i < n; i++) { result[i] = a[i]; result[i].insert(result[i].end(), b[i].begin(), b[i].end()); result[i + n] = c[i]; result[i + n].insert(result[i + n].end(), d[i].begin(), d[i].end()); } return result; } Matrix matrix_sum(const Matrix& a, const Matrix& b) { int proc_num, proc_rank; MPI_Comm_size(MPI_COMM_WORLD, &proc_num); MPI_Comm_rank(MPI_COMM_WORLD, &proc_rank); int n = 0; if (proc_rank == 0) { n = static_cast<int>(a.size()); } MPI_Bcast(reinterpret_cast<void*>(&n), 1, MPI_INT, 0, MPI_COMM_WORLD); Matrix cur_a, cur_b, res; if (proc_rank == 0) { int lines_per_proc = static_cast<int>(a.size() / proc_num); int above_average = static_cast<int>(a.size() % proc_num); int cur_lines_per_proc = lines_per_proc; if (proc_rank < above_average) cur_lines_per_proc++; // reserving for zero process int j = cur_lines_per_proc; for (int i = 1; i < proc_num; i++) { int cur_lines_per_proc = lines_per_proc; if (i < above_average) cur_lines_per_proc++; MPI_Send(reinterpret_cast<void*>(&cur_lines_per_proc), 1, MPI_INT, i, 0, MPI_COMM_WORLD); for (int c = 0; c < cur_lines_per_proc; c++, j++) { MPI_Send(reinterpret_cast<const void*>(a[j].data()), n, MPI_DOUBLE, i, c + 1, MPI_COMM_WORLD); MPI_Send(reinterpret_cast<const void*>(b[j].data()), n, MPI_DOUBLE, i, c + 1, MPI_COMM_WORLD); } } res.assign(cur_lines_per_proc, std::vector<double>(n)); for (int i = 0; i < cur_lines_per_proc; i++) { for (int j = 0; j < n; j++) { res[i][j] = a[i][j] + b[i][j]; } } } else { int h; MPI_Status* status = new MPI_Status(); MPI_Recv(reinterpret_cast<void*>(&h), 1, MPI_INT, 0, 0, MPI_COMM_WORLD, status); cur_a.assign(h, std::vector<double>(n)); cur_b.assign(h, std::vector<double>(n)); for (int i = 0; i < h; i++) { MPI_Recv(reinterpret_cast<void*>(cur_a[i].data()), n, MPI_DOUBLE, 0, i + 1, MPI_COMM_WORLD, status); MPI_Recv(reinterpret_cast<void*>(cur_b[i].data()), n, MPI_DOUBLE, 0, i + 1, MPI_COMM_WORLD, status); } res.assign(h, std::vector<double>(n)); for (int i = 0; i < h; i++) { for (int j = 0; j < n; j++) { res[i][j] = cur_a[i][j] + cur_b[i][j]; } } MPI_Send(reinterpret_cast<void*>(&h), 1, MPI_INT, 0, 0, MPI_COMM_WORLD); for (int i = 0; i < h; i++) { MPI_Send(reinterpret_cast<void*>(res[i].data()), n, MPI_DOUBLE, 0, i + 1, MPI_COMM_WORLD); } } Matrix all_res; if (proc_rank == 0) { all_res.assign(n, std::vector<double>(n)); int j = 0; for (std::size_t i = 0; i < res.size(); i++, j++) { all_res[j] = std::move(res[i]); } for (int i = 1; i < proc_num; i++) { int h; MPI_Status* status = new MPI_Status(); MPI_Recv(reinterpret_cast<void*>(&h), 1, MPI_INT, i, 0, MPI_COMM_WORLD, status); for (int c = 0; c < h; c++, j++) { MPI_Recv(reinterpret_cast<void*>(all_res[j].data()), n, MPI_DOUBLE, i, c + 1, MPI_COMM_WORLD, status); } } } return all_res; } Matrix matrix_sub(const Matrix& a, const Matrix& b) { int proc_num, proc_rank; MPI_Comm_size(MPI_COMM_WORLD, &proc_num); MPI_Comm_rank(MPI_COMM_WORLD, &proc_rank); int n = 0; if (proc_rank == 0) { n = static_cast<int>(a.size()); } MPI_Bcast(reinterpret_cast<void*>(&n), 1, MPI_INT, 0, MPI_COMM_WORLD); Matrix cur_a, cur_b, res; if (proc_rank == 0) { int lines_per_proc = static_cast<int>(a.size() / proc_num); int above_average = static_cast<int>(a.size() % proc_num); int cur_lines_per_proc = lines_per_proc; if (proc_rank < above_average) cur_lines_per_proc++; // reserving for zero process int j = cur_lines_per_proc; for (int i = 1; i < proc_num; i++) { int cur_lines_per_proc = lines_per_proc; if (i < above_average) cur_lines_per_proc++; MPI_Send(reinterpret_cast<void*>(&cur_lines_per_proc), 1, MPI_INT, i, 0, MPI_COMM_WORLD); for (int c = 0; c < cur_lines_per_proc; c++, j++) { MPI_Send(reinterpret_cast<const void*>(a[j].data()), n, MPI_DOUBLE, i, c + 1, MPI_COMM_WORLD); MPI_Send(reinterpret_cast<const void*>(b[j].data()), n, MPI_DOUBLE, i, c + 1, MPI_COMM_WORLD); } } res.assign(cur_lines_per_proc, std::vector<double>(n)); for (int i = 0; i < cur_lines_per_proc; i++) { for (int j = 0; j < n; j++) { res[i][j] = a[i][j] - b[i][j]; } } } else { int h; MPI_Status* status = new MPI_Status(); MPI_Recv(reinterpret_cast<void*>(&h), 1, MPI_INT, 0, 0, MPI_COMM_WORLD, status); cur_a.assign(h, std::vector<double>(n)); cur_b.assign(h, std::vector<double>(n)); for (int i = 0; i < h; i++) { MPI_Recv(reinterpret_cast<void*>(cur_a[i].data()), n, MPI_DOUBLE, 0, i + 1, MPI_COMM_WORLD, status); MPI_Recv(reinterpret_cast<void*>(cur_b[i].data()), n, MPI_DOUBLE, 0, i + 1, MPI_COMM_WORLD, status); } res.assign(h, std::vector<double>(n)); for (int i = 0; i < h; i++) { for (int j = 0; j < n; j++) { res[i][j] = cur_a[i][j] - cur_b[i][j]; } } MPI_Send(reinterpret_cast<void*>(&h), 1, MPI_INT, 0, 0, MPI_COMM_WORLD); for (int i = 0; i < h; i++) { MPI_Send(reinterpret_cast<void*>(res[i].data()), n, MPI_DOUBLE, 0, i + 1, MPI_COMM_WORLD); } } Matrix all_res; if (proc_rank == 0) { all_res.assign(n, std::vector<double>(n)); int j = 0; for (std::size_t i = 0; i < res.size(); i++, j++) { all_res[j] = std::move(res[i]); } for (int i = 1; i < proc_num; i++) { int h = 0; MPI_Status* status = new MPI_Status(); MPI_Recv(reinterpret_cast<void*>(&h), 1, MPI_INT, i, 0, MPI_COMM_WORLD, status); for (int c = 0; c < h; c++, j++) { MPI_Recv(reinterpret_cast<void*>(all_res[j].data()), n, MPI_DOUBLE, i, c + 1, MPI_COMM_WORLD, status); } } } return all_res; } bool is_equal(const Matrix& m1, const Matrix& m2, double threshold) { if (m1.size() != m2.size()) { return false; } for (std::size_t h = 0; h < m1.size(); h++) { if (m1[h].size() != m2[h].size()) { return false; } for (std::size_t w = 0; w < m1[h].size(); w++) { if (std::abs(m1[h][w] - m2[h][w]) > threshold) { return false; } } } return true; }
37.708904
107
0.527654
[ "vector" ]
dfdf2ab6ebc92b09554187fa10378915c685e8c4
3,928
cpp
C++
core/src/data/networkDataSource.cpp
yuqicxy/tangram-es
7c5c879cac79a77fd3691fc98c0447d02b6b73d3
[ "MIT" ]
769
2015-02-26T13:05:53.000Z
2022-03-31T16:34:37.000Z
core/src/data/networkDataSource.cpp
yuqicxy/tangram-es
7c5c879cac79a77fd3691fc98c0447d02b6b73d3
[ "MIT" ]
1,740
2015-01-05T23:46:33.000Z
2022-03-22T19:23:44.000Z
core/src/data/networkDataSource.cpp
yuqicxy/tangram-es
7c5c879cac79a77fd3691fc98c0447d02b6b73d3
[ "MIT" ]
254
2015-02-28T08:58:59.000Z
2022-02-27T07:32:35.000Z
#include "data/networkDataSource.h" #include "log.h" #include "platform.h" namespace Tangram { NetworkDataSource::NetworkDataSource(Platform& _platform, std::string url, UrlOptions options) : m_platform(_platform), m_urlTemplate(std::move(url)), m_options(std::move(options)) {} std::string NetworkDataSource::tileCoordinatesToQuadKey(const TileID &tile) { std::string quadKey; for (int i = tile.z; i > 0; i--) { char digit = '0'; int mask = 1 << (i - 1); if ((tile.x & mask) != 0) { digit++; } if ((tile.y & mask) != 0) { digit++; digit++; } quadKey.push_back(digit); } return quadKey; } bool NetworkDataSource::urlHasTilePattern(const std::string &url) { return (url.find("{x}") != std::string::npos && url.find("{y}") != std::string::npos && url.find("{z}") != std::string::npos) || (url.find("{q}") != std::string::npos); } std::string NetworkDataSource::buildUrlForTile(const TileID& tile, const std::string& urlTemplate, const UrlOptions& options, int subdomainIndex) { std::string url = urlTemplate; size_t xPos = url.find("{x}"); if (xPos != std::string::npos) { url.replace(xPos, 3, std::to_string(tile.x)); } size_t yPos = url.find("{y}"); if (yPos != std::string::npos) { int y = tile.y; int z = tile.z; if (options.isTms) { // Convert XYZ to TMS y = (1 << z) - 1 - tile.y; } url.replace(yPos, 3, std::to_string(y)); } size_t zPos = url.find("{z}"); if (zPos != std::string::npos) { url.replace(zPos, 3, std::to_string(tile.z)); } if (subdomainIndex < options.subdomains.size()) { size_t sPos = url.find("{s}"); if (sPos != std::string::npos) { url.replace(sPos, 3, options.subdomains[subdomainIndex]); } } size_t qPos = url.find("{q}"); if (qPos != std::string::npos) { auto quadkey = tileCoordinatesToQuadKey(tile); url.replace(qPos, 3, quadkey); } return url; } bool NetworkDataSource::loadTileData(std::shared_ptr<TileTask> task, TileTaskCb callback) { if (task->rawSource != this->level) { LOGE("NetworkDataSource must be last!"); return false; } auto tileId = task->tileId(); Url url(buildUrlForTile(tileId, m_urlTemplate, m_options, m_urlSubdomainIndex)); if (!m_options.subdomains.empty()) { m_urlSubdomainIndex = (m_urlSubdomainIndex + 1) % m_options.subdomains.size(); } LOGTInit(">>> %s", task->tileId().toString().c_str()); UrlCallback onRequestFinish = [=](UrlResponse&& response) mutable { auto source = task->source(); if (!source) { LOGW("URL Callback for deleted TileSource '%s'", url.string().c_str()); return; } LOGT("<<< %s -- canceled:%d", task->tileId().toString().c_str(), task->isCanceled()); if (task->isCanceled()) { return; } if (response.error) { LOGD("URL request '%s': %s", url.string().c_str(), response.error); } else if (!response.content.empty()) { auto& dlTask = static_cast<BinaryTileTask&>(*task); dlTask.rawTileData = std::make_shared<std::vector<char>>(std::move(response.content)); } callback.func(std::move(task)); }; auto& dlTask = static_cast<BinaryTileTask&>(*task); dlTask.urlRequestHandle = m_platform.startUrlRequest(url, std::move(onRequestFinish)); dlTask.urlRequestStarted = true; return true; } void NetworkDataSource::cancelLoadingTile(TileTask& task) { auto& dlTask = static_cast<BinaryTileTask&>(task); if (dlTask.urlRequestStarted) { dlTask.urlRequestStarted = false; m_platform.cancelUrlRequest(dlTask.urlRequestHandle); } } }
30.449612
147
0.582739
[ "vector" ]
dfedde047e70543dad2b766dd28c7ae9022e5a2d
28,909
cpp
C++
src/mj_sim.cpp
rohanpsingh/mc_mujoco
dd944da579a715967098c9d8261753d50ee4299c
[ "BSD-2-Clause" ]
8
2021-09-15T07:43:31.000Z
2021-12-28T08:18:22.000Z
src/mj_sim.cpp
rohanpsingh/mc_mujoco
dd944da579a715967098c9d8261753d50ee4299c
[ "BSD-2-Clause" ]
3
2021-09-15T09:56:44.000Z
2021-11-12T05:02:58.000Z
src/mj_sim.cpp
rohanpsingh/mc_mujoco
dd944da579a715967098c9d8261753d50ee4299c
[ "BSD-2-Clause" ]
4
2021-09-15T06:48:40.000Z
2022-02-28T10:14:27.000Z
#include "mj_sim_impl.h" #include "mj_utils.h" #include <cassert> #include <chrono> #include <type_traits> #include "MujocoClient.h" #include "config.h" #include "backends/imgui_impl_glfw.h" #include "backends/imgui_impl_opengl3.h" #include "implot.h" #include "ImGuizmo.h" #include "MujocoClient.h" #include <boost/filesystem.hpp> namespace bfs = boost::filesystem; #include <mc_rtc/version.h> namespace mc_mujoco { double MjRobot::PD(double jnt_id, double q_ref, double q, double qdot_ref, double qdot) { double p_error = q_ref - q; double v_error = qdot_ref - qdot; double ret = (kp[jnt_id] * p_error + kd[jnt_id] * v_error); return ret; } /* Load PD gains from file (taken from RobotHardware/robot.cpp) */ bool MjRobot::loadGain(const std::string & path_to_pd, const std::vector<std::string> & joints) { std::ifstream strm(path_to_pd.c_str()); if(!strm.is_open()) { mc_rtc::log::error_and_throw<std::runtime_error>("[mc_mujoco] Cannot open PD gains file for {} at {}", name, path_to_pd); } int num_joints = joints.size(); if(!num_joints) { return false; } std::vector<double> default_pgain(num_joints, 0); std::vector<double> default_dgain(num_joints, 0); for(int i = 0; i < num_joints; i++) { std::string str; bool getlinep; while((getlinep = !!(std::getline(strm, str)))) { if(str.empty()) { continue; } if(str[0] == '#') { continue; } double tmp; std::istringstream sstrm(str); sstrm >> tmp; default_pgain[i] = tmp; if(sstrm.eof()) break; sstrm >> tmp; default_dgain[i] = tmp; if(sstrm.eof()) break; break; } if(!getlinep) { if(i < num_joints) { mc_rtc::log::error( "[mc_mujoco] loadGain error: size of gains reading from file ({}) does not match size of joints", path_to_pd); } break; } } strm.close(); mc_rtc::log::info("[mc_mujoco] Gains for {}", name); for(unsigned int i = 0; i < num_joints; i++) { mc_rtc::log::info("[mc_mujoco] {}, pgain = {}, dgain = {}", joints[i], default_pgain[i], default_dgain[i]); // push to kp and kd default_kp.push_back(default_pgain[i]); default_kd.push_back(default_dgain[i]); kp.push_back(default_pgain[i]); kd.push_back(default_dgain[i]); } return true; } MjSimImpl::MjSimImpl(const MjConfiguration & config) : controller(std::make_unique<mc_control::MCGlobalController>(config.mc_config)), config(config) { auto get_robot_cfg_path = [&](const std::string & robot_name) -> std::string { if(bfs::exists(bfs::path(mc_mujoco::USER_FOLDER) / (robot_name + ".yaml"))) { return (bfs::path(mc_mujoco::USER_FOLDER) / (robot_name + ".yaml")).string(); } else if(bfs::exists(bfs::path(mc_mujoco::SHARE_FOLDER) / (robot_name + ".yaml"))) { return (bfs::path(mc_mujoco::SHARE_FOLDER) / (robot_name + ".yaml")).string(); } else { return ""; } }; std::vector<std::string> mujRobots; std::vector<std::string> xmlFiles; std::vector<std::string> pdGainsFiles; #if MC_RTC_VERSION_MAJOR > 1 for(const auto & r_ptr : controller->robots()) { const auto & r = *r_ptr; #else for(const auto & r : controller->robots()) { #endif const auto & robot_cfg_path = get_robot_cfg_path(r.module().name); if(robot_cfg_path.size()) { auto robot_cfg = mc_rtc::Configuration(robot_cfg_path); if(!robot_cfg.has("xmlModelPath")) { mc_rtc::log::error_and_throw<std::runtime_error>("Missing xmlModelPath in {}", robot_cfg_path); } mujRobots.push_back(r.name()); xmlFiles.push_back(static_cast<std::string>(robot_cfg("xmlModelPath"))); pdGainsFiles.push_back(robot_cfg("pdGainsPath", std::string(""))); if(!bfs::exists(xmlFiles.back())) { mc_rtc::log::error_and_throw<std::runtime_error>("[mc_mujoco] XML model cannot be found at {}", xmlFiles.back()); } } } if(!xmlFiles.size()) { mc_rtc::log::error_and_throw<std::runtime_error>("No Mujoco model associated to any robots in the controller"); } // initial mujoco here and load XML model bool initialized = mujoco_init(this, mujRobots, xmlFiles); if(!initialized) { mc_rtc::log::error_and_throw<std::runtime_error>("[mc_mujoco] Initialized failed."); } // read PD gains from file for(size_t i = 0; i < robots.size(); ++i) { auto & r = robots[i]; bool has_motor = std::any_of(r.mj_mot_names.begin(), r.mj_mot_names.end(), [](const std::string & m) { return m.size() != 0; }); const auto & robot = controller->robot(r.name); if(robot.mb().nrDof() == 0 || (robot.mb().nrDof() == 6 && robot.mb().joint(0).dof() == 6) || !has_motor) { continue; } if(!bfs::exists(pdGainsFiles[i])) { mc_rtc::log::error_and_throw<std::runtime_error>("[mc_mujoco] PD gains file for {} cannot be found at {}", r.name, pdGainsFiles.back()); } r.loadGain(pdGainsFiles[i], controller->robots().robot(r.name).module().ref_joint_order()); } if(config.with_visualization) { mujoco_create_window(this); if(config.with_mc_rtc_gui) { client = std::make_unique<MujocoClient>(); } } mc_rtc::log::info("[mc_mujoco] Initialized successful."); } void MjSimImpl::cleanup() { mujoco_cleanup(this); } void MjRobot::initialize(mjModel * model, const mc_rbdyn::Robot & robot) { mj_jnt_ids.resize(0); for(const auto & j : mj_jnt_names) { mj_jnt_ids.push_back(mj_name2id(model, mjOBJ_JOINT, j.c_str())); } auto fill_acuator_ids = [&](const std::vector<std::string> & names, std::vector<int> & ids) { ids.resize(0); for(const auto & n : names) { if(n.size()) { ids.push_back(mj_name2id(model, mjOBJ_ACTUATOR, n.c_str())); } else { ids.push_back(-1); } } }; fill_acuator_ids(mj_mot_names, mj_mot_ids); fill_acuator_ids(mj_pos_act_names, mj_pos_act_ids); fill_acuator_ids(mj_vel_act_names, mj_vel_act_ids); if(root_body.size()) { root_body_id = mj_name2id(model, mjOBJ_BODY, root_body.c_str()); } auto init_sensor_id = [&](const char * mj_name, const char * mc_name, const std::string & sensor_name, const char * suffix, mjtSensor type, std::unordered_map<std::string, int> & mapping) { auto mj_sensor = prefixed(fmt::format("{}_{}", sensor_name, suffix)); auto sensor_id = mujoco_get_sensor_id(*model, mj_sensor, type); if(sensor_id == -1) { mc_rtc::log::error("[mc_mujoco] No MuJoCo {} for {} {} in {}, expected to find a {} named {}", mj_name, sensor_name, mc_name, name, mj_name, mj_sensor); } mapping[sensor_name] = sensor_id; }; for(const auto & fs : robot.module().forceSensors()) { wrenches[fs.name()] = sva::ForceVecd(Eigen::Vector3d(0, 0, 0), Eigen::Vector3d(0, 0, 0)); init_sensor_id("force sensor", "force sensor", fs.name(), "fsensor", mjSENS_FORCE, mc_fs_to_mj_fsensor_id); init_sensor_id("torque sensor", "force sensor", fs.name(), "tsensor", mjSENS_TORQUE, mc_fs_to_mj_tsensor_id); } for(const auto & bs : robot.bodySensors()) { if(bs.name() == "FloatingBase" || bs.name().empty()) { continue; } gyros[bs.name()] = Eigen::Vector3d::Zero(); accelerometers[bs.name()] = Eigen::Vector3d::Zero(); init_sensor_id("gyro sensor", "body sensor", bs.name(), "gyro", mjSENS_GYRO, mc_bs_to_mj_gyro_id); init_sensor_id("accelerometer sensor", "body sensor", bs.name(), "accelerometer", mjSENS_ACCELEROMETER, mc_bs_to_mj_accelerometer_id); } reset(robot); } void MjRobot::reset(const mc_rbdyn::Robot & robot) { const auto & mbc = robot.mbc(); const auto & rjo = robot.module().ref_joint_order(); if(rjo.size() != mj_jnt_names.size()) { mc_rtc::log::error_and_throw<std::runtime_error>( "[mc_mujoco] Missmatch in model for {}, reference joint order has {} joints but MuJoCo models has {} joints", name, rjo.size(), mj_jnt_names.size()); } mj_to_mbc.resize(0); mj_prev_ctrl_q.resize(0); mj_prev_ctrl_alpha.resize(0); mj_jnt_to_rjo.resize(0); mj_to_mbc.resize(0); encoders = std::vector<double>(rjo.size(), 0.0); alphas = std::vector<double>(rjo.size(), 0.0); torques = std::vector<double>(rjo.size(), 0.0); for(const auto & mj_jn : mj_jnt_names) { const auto & jn = [&]() { if(prefix.size()) { return mj_jn.substr(prefix.size() + 1); } return mj_jn; }(); auto rjo_it = std::find(rjo.begin(), rjo.end(), jn); int rjo_idx = -1; if(rjo_it != rjo.end()) { rjo_idx = std::distance(rjo.begin(), rjo_it); } mj_jnt_to_rjo.push_back(rjo_idx); if(robot.hasJoint(jn)) { auto jIndex = robot.jointIndexByName(jn); mj_to_mbc.push_back(jIndex); if(robot.mb().joint(jIndex).dof() != 1) { mc_rtc::log::error_and_throw<std::runtime_error>( "[mc_mujoco] Only support revolute and prismatic joint for control"); } mj_prev_ctrl_q.push_back(robot.mbc().q[jIndex][0]); mj_prev_ctrl_alpha.push_back(robot.mbc().alpha[jIndex][0]); if(rjo_idx != -1) { encoders[rjo_idx] = mj_prev_ctrl_q.back(); alphas[rjo_idx] = mj_prev_ctrl_alpha.back(); } } else { mj_to_mbc.push_back(-1); } } mj_ctrl = mj_prev_ctrl_q; mj_next_ctrl_q = mj_prev_ctrl_q; mj_next_ctrl_alpha = mj_prev_ctrl_alpha; // reset the PD gains to default values kp = default_kp; kd = default_kd; } void MjSimImpl::setSimulationInitialState() { if(controller) { qInit.resize(0); alphaInit.resize(0); for(auto & r : robots) { const auto & robot = controller->robots().robot(r.name); r.initialize(model, robot); if(r.root_joint.size()) { r.root_qpos_idx = qInit.size(); r.root_qvel_idx = alphaInit.size(); if(robot.mb().joint(0).dof() == 6) { const auto & t = robot.posW().translation(); for(size_t i = 0; i < 3; ++i) { qInit.push_back(t[i]); // push linear/angular velocities alphaInit.push_back(0); alphaInit.push_back(0); } Eigen::Quaterniond q = Eigen::Quaterniond(robot.posW().rotation()).inverse(); qInit.push_back(q.w()); qInit.push_back(q.x()); qInit.push_back(q.y()); qInit.push_back(q.z()); } } else if(r.root_body_id != -1) { const auto & t = robot.posW().translation(); model->body_pos[3 * r.root_body_id + 0] = t.x(); model->body_pos[3 * r.root_body_id + 1] = t.y(); model->body_pos[3 * r.root_body_id + 2] = t.z(); Eigen::Quaterniond q = Eigen::Quaterniond(robot.posW().rotation()).inverse(); model->body_quat[4 * r.root_body_id + 0] = q.w(); model->body_quat[4 * r.root_body_id + 1] = q.x(); model->body_quat[4 * r.root_body_id + 2] = q.y(); model->body_quat[4 * r.root_body_id + 3] = q.z(); } for(size_t i = 0; i < r.mj_jnt_names.size(); ++i) { qInit.push_back(r.encoders[r.mj_jnt_to_rjo[i]]); alphaInit.push_back(r.alphas[r.mj_jnt_to_rjo[i]]); } } } // set initial qpos, qvel in mujoco if(!mujoco_set_const(model, data, qInit, alphaInit)) { mc_rtc::log::error_and_throw<std::runtime_error>("[mc_mujoco] Set inital state failed."); } mj_forward(model, data); } void MjSimImpl::makeDatastoreCalls() { for(auto & r : robots) { // make_call for setting pd gains (for all joints) controller->controller().datastore().make_call( r.name + "::SetPDGains", [this, &r](const std::vector<double> & p_vec, const std::vector<double> & d_vec) { const auto & rjo = controller->robots().robot(r.name).module().ref_joint_order(); if(p_vec.size() != rjo.size()) { mc_rtc::log::warning("[mc_mujoco] {}::SetPDGains failed. p_vec size({})!=ref_joint_order size({})", r.name, p_vec.size(), rjo.size()); return false; } if(d_vec.size() != rjo.size()) { mc_rtc::log::warning("[mc_mujoco] {}::SetPDGains failed. d_vec size({})!=ref_joint_order size({})", r.name, d_vec.size(), rjo.size()); return false; } r.kp = p_vec; r.kd = d_vec; return true; }); // make_call for setting pd gains (by name) controller->controller().datastore().make_call( r.name + "::SetPDGainsByName", [this, &r](const std::string & jn, double p, double d) { const auto & rjo = controller->robots().robot(r.name).module().ref_joint_order(); auto rjo_it = std::find(rjo.begin(), rjo.end(), jn); if(rjo_it == rjo.end()) { mc_rtc::log::warning("[mc_mujoco] {}::SetPDGainsByName failed. Joint {} not found in ref_joint_order.", r.name, jn); return false; } int rjo_idx = std::distance(rjo.begin(), rjo_it); r.kp[rjo_idx] = p; r.kd[rjo_idx] = d; return true; }); // make_call for reading pd gains (for all joints) controller->controller().datastore().make_call( r.name + "::GetPDGains", [this, &r](std::vector<double> & p_vec, std::vector<double> & d_vec) { p_vec.resize(0); d_vec.resize(0); p_vec = r.kp; d_vec = r.kd; const auto & rjo = controller->robots().robot(r.name).module().ref_joint_order(); if(p_vec.size() != rjo.size()) { mc_rtc::log::warning("[mc_mujoco] {}::GetPDGains failed. p_vec size({})!=ref_joint_order size({})", r.name, p_vec.size(), rjo.size()); return false; } if(d_vec.size() != rjo.size()) { mc_rtc::log::warning("[mc_mujoco] {}::GetPDGains failed. d_vec size({})!=ref_joint_order size({})", r.name, d_vec.size(), rjo.size()); return false; } return true; }); // make_call for reading pd gains (by name) controller->controller().datastore().make_call( r.name + "::GetPDGainsByName", [this, &r](const std::string & jn, double & p, double & d) { const auto & rjo = controller->robots().robot(r.name).module().ref_joint_order(); auto rjo_it = std::find(rjo.begin(), rjo.end(), jn); if(rjo_it == rjo.end()) { mc_rtc::log::warning("[mc_mujoco] {}::GetPDGainsByName failed. Joint {} not found in ref_joint_order.", r.name, jn); return false; } int rjo_idx = std::distance(rjo.begin(), rjo_it); p = r.kp[rjo_idx]; d = r.kd[rjo_idx]; return true; }); } } void MjSimImpl::startSimulation() { setSimulationInitialState(); if(!config.with_controller) { controller.reset(); return; } makeDatastoreCalls(); // get sim timestep and set the frameskip parameter double simTimestep = model->opt.timestep; frameskip_ = std::round(controller->timestep() / simTimestep); mc_rtc::log::info("[mc_mujoco] MC-RTC timestep: {}. MJ timestep: {}", controller->timestep(), simTimestep); mc_rtc::log::info("[mc_mujoco] Hence, Frameskip: {}", frameskip_); for(const auto & r : robots) { controller->setEncoderValues(r.name, r.encoders); } controller->init(robots[0].encoders); controller->running = true; } void MjRobot::updateSensors(mc_control::MCGlobalController * gc, mjModel * model, mjData * data) { for(size_t i = 0; i < mj_jnt_ids.size(); ++i) { if(mj_jnt_to_rjo[i] == -1) { continue; } encoders[mj_jnt_to_rjo[i]] = data->qpos[model->jnt_qposadr[mj_jnt_ids[i]]]; alphas[mj_jnt_to_rjo[i]] = data->qvel[model->jnt_dofadr[mj_jnt_ids[i]]]; } for(size_t i = 0; i < mj_mot_ids.size(); ++i) { if(mj_jnt_to_rjo[i] == -1) { continue; } torques[mj_jnt_to_rjo[i]] = data->qfrc_actuator[model->jnt_dofadr[mj_jnt_ids[i]]]; } if(!gc) { return; } auto & robot = gc->controller().robots().robot(name); // Body sensor updates if(root_qpos_idx != -1) { root_pos = Eigen::Map<Eigen::Vector3d>(&data->qpos[root_qpos_idx]); root_ori.w() = data->qpos[root_qpos_idx + 3]; root_ori.x() = data->qpos[root_qpos_idx + 4]; root_ori.y() = data->qpos[root_qpos_idx + 5]; root_ori.z() = data->qpos[root_qpos_idx + 6]; root_ori = root_ori.inverse(); root_linvel = Eigen::Map<Eigen::Vector3d>(&data->qvel[root_qvel_idx]); root_angvel = Eigen::Map<Eigen::Vector3d>(&data->qvel[root_qvel_idx + 3]); root_linacc = Eigen::Map<Eigen::Vector3d>(&data->qacc[root_qvel_idx]); root_angacc = Eigen::Map<Eigen::Vector3d>(&data->qacc[root_qvel_idx + 3]); if(robot.hasBodySensor("FloatingBase")) { gc->setSensorPositions(name, {{"FloatingBase", root_pos}}); gc->setSensorOrientations(name, {{"FloatingBase", root_ori}}); gc->setSensorLinearVelocities(name, {{"FloatingBase", root_linvel}}); gc->setSensorAngularVelocities(name, {{"FloatingBase", root_angvel}}); gc->setSensorLinearAccelerations(name, {{"FloatingBase", root_linacc}}); // FIXME Not implemented in mc_rtc // gc->setSensorAngularAccelerations(name, {{"FloatingBase", root_angacc}}); } } // Gyro update for(auto & gyro : gyros) { mujoco_get_sensordata(*model, *data, mc_bs_to_mj_gyro_id[gyro.first], gyro.second.data()); } gc->setSensorAngularVelocities(name, gyros); // Accelerometers update for(auto & accelerometer : accelerometers) { mujoco_get_sensordata(*model, *data, mc_bs_to_mj_accelerometer_id[accelerometer.first], accelerometer.second.data()); } gc->setSensorLinearAccelerations(name, accelerometers); // Force sensor update for(auto & fs : wrenches) { mujoco_get_sensordata(*model, *data, mc_fs_to_mj_fsensor_id[fs.first], fs.second.force().data()); mujoco_get_sensordata(*model, *data, mc_fs_to_mj_tsensor_id[fs.first], fs.second.couple().data()); fs.second *= -1; } gc->setWrenches(name, wrenches); // Joint sensor updates gc->setEncoderValues(name, encoders); gc->setEncoderVelocities(name, alphas); gc->setJointTorques(name, torques); } void MjSimImpl::updateData() { for(auto & r : robots) { r.updateSensors(controller.get(), model, data); } } void MjRobot::updateControl(const mc_rbdyn::Robot & robot) { mj_prev_ctrl_q = mj_next_ctrl_q; mj_prev_ctrl_alpha = mj_next_ctrl_alpha; size_t ctrl_idx = 0; for(size_t i = 0; i < mj_to_mbc.size(); ++i) { auto jIndex = mj_to_mbc[i]; if(jIndex != -1) { mj_next_ctrl_q[ctrl_idx] = robot.mbc().q[jIndex][0]; mj_next_ctrl_alpha[ctrl_idx] = robot.mbc().alpha[jIndex][0]; ctrl_idx++; } } } void MjRobot::sendControl(const mjModel & model, mjData & data, size_t interp_idx, size_t frameskip_) { for(size_t i = 0; i < mj_ctrl.size(); ++i) { auto mot_id = mj_mot_ids[i]; auto pos_act_id = mj_pos_act_ids[i]; auto vel_act_id = mj_vel_act_ids[i]; auto rjo_id = mj_jnt_to_rjo[i]; if(rjo_id == -1) { continue; } // compute desired q using interpolation double q_ref = (interp_idx + 1) * (mj_next_ctrl_q[i] - mj_prev_ctrl_q[i]) / frameskip_; q_ref += mj_prev_ctrl_q[i]; // compute desired alpha using interpolation double alpha_ref = (interp_idx + 1) * (mj_next_ctrl_alpha[i] - mj_prev_ctrl_alpha[i]) / frameskip_; alpha_ref += mj_prev_ctrl_alpha[i]; if(mot_id != -1) { // compute desired torque using PD control mj_ctrl[i] = PD(i, q_ref, encoders[rjo_id], alpha_ref, alphas[rjo_id]); double ratio = model.actuator_gear[6 * mot_id]; data.ctrl[mot_id] = mj_ctrl[i] / ratio; } if(pos_act_id != -1) { data.ctrl[pos_act_id] = q_ref; } if(vel_act_id != -1) { data.ctrl[vel_act_id] = alpha_ref; } } } bool MjSimImpl::controlStep() { auto interp_idx = iterCount_ % frameskip_; // After every frameskip iters if(config.with_controller && interp_idx == 0) { // run the controller if(!controller->run()) { return true; } for(auto & r : robots) { r.updateControl(controller->robots().robot(r.name)); } } // On each control iter for(auto & r : robots) { r.sendControl(*model, *data, interp_idx, frameskip_); } iterCount_++; return false; } void MjSimImpl::simStep() { // clear old perturbations, apply new mju_zero(data->xfrc_applied, 6 * model->nbody); mjv_applyPerturbPose(model, data, &pert, 0); // move mocap bodies only mjv_applyPerturbForce(model, data, &pert); // take one step in simulation // model.opt.timestep will be used here mj_step(model, data); } void MjSimImpl::resetSimulation(const std::map<std::string, std::vector<double>> & reset_qs, const std::map<std::string, sva::PTransformd> & reset_pos) { iterCount_ = 0; reset_simulation_ = false; if(controller) { controller->reset(reset_qs, reset_pos); for(auto & robot : robots) { robot.reset(controller->robot(robot.name)); } controller->running = true; } mj_resetData(model, data); setSimulationInitialState(); makeDatastoreCalls(); } bool MjSimImpl::stepSimulation() { if(reset_simulation_) { resetSimulation({}, {}); } auto start_step = clock::now(); // Only run the GUI update if the simulation is paused if(config.step_by_step && rem_steps == 0) { if(controller) { controller->running = false; controller->run(); controller->running = true; } mj_sim_start_t = start_step; std::this_thread::sleep_for(std::chrono::milliseconds(10)); return false; } if(iterCount_ > 0) { duration_us dt = start_step - mj_sim_start_t; mj_sync_delay += duration_us(1e6 * model->opt.timestep) - dt; mj_sim_dt[(iterCount_ - 1) % mj_sim_dt.size()] = dt.count(); } mj_sim_start_t = start_step; auto do_step = [this, &start_step]() { { std::lock_guard<std::mutex> lock(rendering_mutex_); simStep(); } updateData(); return controlStep(); }; bool done = false; if(!config.step_by_step) { done = do_step(); } if(config.step_by_step && rem_steps > 0) { // Doing 'frameskip_' steps of sim + control // (But controller.run() will execute only when interp_idx == 0) for(size_t i = 0; i < frameskip_; i++) { done = do_step() && done; } rem_steps--; } if(config.sync_real_time) { std::this_thread::sleep_until(start_step + duration_us(1e6 * model->opt.timestep) + mj_sync_delay); } return done; } void MjSimImpl::updateScene() { // update scene and render std::lock_guard<std::mutex> lock(rendering_mutex_); mjv_updateScene(model, data, &options, &pert, &camera, mjCAT_ALL, &scene); if(client) { client->updateScene(scene); } // process pending GUI events, call GLFW callbacks glfwPollEvents(); } bool MjSimImpl::render() { if(!config.with_visualization) { return true; } // mj render mjr_render(uistate.rect[0], &scene, &context); // Render ImGui ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); ImGuizmo::BeginFrame(); ImGuiIO & io = ImGui::GetIO(); ImGuizmo::AllowAxisFlip(false); ImGuizmo::SetRect(0, 0, io.DisplaySize.x, io.DisplaySize.y); if(client) { client->update(); client->draw2D(window); client->draw3D(); } { auto right_margin = 5.0f; auto top_margin = 5.0f; auto width = io.DisplaySize.x - 2 * right_margin; auto height = io.DisplaySize.y - 2 * top_margin; ImGui::SetNextWindowPos({0.8f * width - right_margin, top_margin}, ImGuiCond_FirstUseEver); ImGui::SetNextWindowSize({0.2f * width, 0.3f * height}, ImGuiCond_FirstUseEver); #if mjVERSION_HEADER <= 210 ImGui::Begin(fmt::format("mc_mujoco (MuJoCo {})", mj_version()).c_str()); #else ImGui::Begin(fmt::format("mc_mujoco (MuJoCo {})", mj_versionString()).c_str()); #endif size_t nsamples = std::min(mj_sim_dt.size(), iterCount_); mj_sim_dt_average = 0; for(size_t i = 0; i < nsamples; ++i) { mj_sim_dt_average += mj_sim_dt[i] / nsamples; } ImGui::Text("Average sim time: %.2fμs", mj_sim_dt_average); ImGui::Text("Simulation/Real time: %.2f", mj_sim_dt_average / (1e6 * model->opt.timestep)); if(ImGui::Checkbox("Sync with real-time", &config.sync_real_time)) { if(config.sync_real_time) { mj_sync_delay = duration_us(0); } } ImGui::Checkbox("Step-by-step", &config.step_by_step); if(config.step_by_step) { auto doNStepsButton = [&](size_t n, bool final_) { size_t n_ms = std::ceil(n * 1000 * (controller ? controller->timestep() : model->opt.timestep)); if(ImGui::Button(fmt::format("+{}ms", n_ms).c_str())) { rem_steps = n; } if(!final_) { ImGui::SameLine(); } }; doNStepsButton(1, false); doNStepsButton(5, false); doNStepsButton(10, false); doNStepsButton(50, false); doNStepsButton(100, true); } auto flag_to_gui = [&](const char * label, mjtVisFlag flag) { bool show = options.flags[flag]; if(ImGui::Checkbox(label, &show)) { options.flags[flag] = show; } }; flag_to_gui("Show contact points [C]", mjVIS_CONTACTPOINT); flag_to_gui("Show contact forces [F]", mjVIS_CONTACTFORCE); flag_to_gui("Make Transparent [T]", mjVIS_TRANSPARENT); auto group_to_checkbox = [&](size_t group, bool last) { bool show = options.geomgroup[group]; if(ImGui::Checkbox(fmt::format("{}", group).c_str(), &show)) { options.geomgroup[group] = show; } if(!last) { ImGui::SameLine(); } }; ImGui::Text("%s", fmt::format("Visible layers [0-{}]", mjNGROUP).c_str()); for(size_t i = 0; i < mjNGROUP; ++i) { group_to_checkbox(i, i == mjNGROUP - 1); } if(ImGui::Button("Reset simulation", ImVec2(-FLT_MIN, 0.0f))) { reset_simulation_ = true; } ImGui::End(); } ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); // swap OpenGL buffers (blocking call due to v-sync) glfwSwapBuffers(window); return !glfwWindowShouldClose(window); } void MjSimImpl::stopSimulation() {} void MjSimImpl::saveGUISettings() { auto user_path = bfs::path(USER_FOLDER); if(!bfs::exists(user_path)) { if(!bfs::create_directories(user_path)) { mc_rtc::log::critical("Failed to create the user directory: {}. GUI configuration will not be saved", user_path.string()); return; } } mc_rtc::Configuration config; auto camera_c = config.add("camera"); auto lookat = camera_c.array("lookat", 3); for(size_t i = 0; i < 3; ++i) { lookat.push(camera.lookat[i]); } camera_c.add("distance", camera.distance); camera_c.add("azimuth", camera.azimuth); camera_c.add("elevation", camera.elevation); auto visualize_c = config.add("visualize"); visualize_c.add("collisions", static_cast<bool>(options.geomgroup[0])); visualize_c.add("visuals", static_cast<bool>(options.geomgroup[1])); visualize_c.add("contact-points", static_cast<bool>(options.flags[mjVIS_CONTACTPOINT])); visualize_c.add("contact-forces", static_cast<bool>(options.flags[mjVIS_CONTACTFORCE])); auto path_out = (user_path / "mc_mujoco.yaml").string(); config.save(path_out); mc_rtc::log::success("[mc_mujoco] Configuration saved to {}", path_out); } MjSim::MjSim(const MjConfiguration & config) : impl(new MjSimImpl(config)) { impl->startSimulation(); } MjSim::~MjSim() { impl->cleanup(); } bool MjSim::stepSimulation() { return impl->stepSimulation(); } void MjSim::stopSimulation() { impl->stopSimulation(); } void MjSim::updateScene() { impl->updateScene(); } void MjSim::resetSimulation(const std::map<std::string, std::vector<double>> & reset_qs, const std::map<std::string, sva::PTransformd> & reset_pos) { impl->resetSimulation(reset_qs, reset_pos); } bool MjSim::render() { return impl->render(); } mc_control::MCGlobalController * MjSim::controller() noexcept { return impl->get_controller(); } } // namespace mc_mujoco
30.494726
120
0.612923
[ "render", "vector", "model" ]
dff296768bf3b36af5b7b466719fa44acd92596b
3,713
cpp
C++
scratch/projects/folds/xCylinder2.cpp
tingelst/versor
c831231e5011cfd1f62da8948cff7956d2f6670b
[ "BSD-3-Clause" ]
null
null
null
scratch/projects/folds/xCylinder2.cpp
tingelst/versor
c831231e5011cfd1f62da8948cff7956d2f6670b
[ "BSD-3-Clause" ]
null
null
null
scratch/projects/folds/xCylinder2.cpp
tingelst/versor
c831231e5011cfd1f62da8948cff7956d2f6670b
[ "BSD-3-Clause" ]
null
null
null
/* * ===================================================================================== * * Filename: xCylinder2.cpp * * Description: * * Version: 1.0 * Created: 12/20/2013 12:55:46 * Revision: none * Compiler: gcc * * Author: Pablo Colapinto (), wolftype (gmail) * Organization: Media Arts and Technology Program, UCSB * * ===================================================================================== */ #include "vsr_cga3D.h" #include "vsr_GLVimpl.h" #include "vsr_fold.h" #include "vsr_set.h" using namespace vsr; using namespace vsr::cga3D; struct MyApp : App { Pnt mouse; Lin ray; float amt; float dx,dy,decay,num,spacing,numK; MyApp(Window * win ) : App(win){ scene.camera.pos( 0,0,10 ); } void initGui(){ gui(dx,"dx")(dy,"dy")(decay,"decay",-10,10)(amt,"amt")(num,"num",1,100)(spacing,"spacing",1,100); gui(numK,"numK",0,10); dx = .2; dy = 0; amt = .1; num = 2; } void getMouse(){ auto tv = interface.vd().ray; Vec z (tv[0], tv[1], tv[2] ); auto tm = interface.mouse.projectMid; ray = Round::point( tm[0], tm[1], tm[2] ) ^ z ^ Inf(1); mouse = Round::point( ray, Ori(1) ); } virtual void onDraw(){ gfx::GL::twoSidedLighting(); scene.light = Vec3f(5,1,.3); int numSections = num; int numPoints = ( num * 2 ); Field<Pnt> f ( numPoints, numPoints, 1); //vector<Truss> truss; Set<Rigid3> rigid; //BUILD PATTERN double ts = spacing * num * 2; bool bSwitch = true; for (int i = 0; i < num; ++i){ double u = -ts/2.0 + ts * (double)i/num; double tu = -1.0 + 2*(double)i/num; bSwitch = !bSwitch; for (int j = 0; j < num; ++j){ double v = -ts/2.0 + ts * (double)j/num; double tv = -1.0 + 2* (double)j/num; double ttu = tu; for (int k = 0; k < (int)numK; ++k){ ttu *= tu; } double ddx = dx;// (bSwitch) ? dx : dx * decay ; Pnt a = PT( u, v, 0 ); Pnt b = PT( u + ddx, v + spacing + dy , 0 ); Pnt c = PT( u + spacing + ddx, v + spacing + dy, 0); Pnt d = PT( u + spacing, v, 0 ); f.at(i*2, j*2 ) = a; f.at(i*2, j*2+1) = b; f.at(i*2+1, j*2+1) = c; f.at(i*2+1, j*2) = d; /* if( j == num-1) { */ /* f.at(i*2, j*2+3) = PT( u, v + 2*spacing,0); */ /* f.at(i*2+1, j*2+3) = PT( u + spacing, v+ 2*spacing,0); */ /* } */ } } Draw(f); for (int i = 1; i < num-1; ++i){ for (int j = 1; j < num; ++j){ Rigid3 bl( f.at(i*2, j*2), f.at(i*2+1, j*2-1), f.at(i*2, j*2-1), f.at(i*2-1, j*2) ); //Bottom Left Rigid3 tl( f.at(i*2, j*2+1), f.at(i*2, j*2), f.at(i*2-1, j*2), f.at(i*2-1, j*2+1) ); //Top Left Rigid3 br( f.at(i*2+1, j*2), f.at(i*2+2, j*2-1), f.at(i*2+1, j*2-1), f.at(i*2,j*2) ); //Bottom Right Rigid3 tr( f.at(i*2+1,j*2+1), f.at(i*2+1,j*2), f.at(i*2,j*2), f.at(i*2,j*2+1) ); rigid.add(bl); rigid.add(tl); rigid.add(br); rigid.add(tr); } } int it = 0; for (int i = 1; i < num-1; ++i){ for (int j = 1; j < num; ++j){ rigid[it] rigid[it+1] rigid[it+2] rigid[it+3] it++; } } } }; MyApp * app; int main(){ GLV glv(0,0); Window * win = new Window(500,500,"Versor",&glv); app = new MyApp( win ); app -> initGui(); glv << *app; Application::run(); return 0; }
24.427632
110
0.424185
[ "vector" ]
5f0e2be47fd5ebf3b435c193529f87a3fb6813cc
6,429
hpp
C++
include/neo_state_machine.hpp
obhi-d/neoscript
408d95d06e5317b3873c9eed5559ac1ed5818bb9
[ "MIT" ]
null
null
null
include/neo_state_machine.hpp
obhi-d/neoscript
408d95d06e5317b3873c9eed5559ac1ed5818bb9
[ "MIT" ]
null
null
null
include/neo_state_machine.hpp
obhi-d/neoscript
408d95d06e5317b3873c9eed5559ac1ed5818bb9
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> #include <forward_list> #include <istream> #include <memory> #include <optional> #include <string> #include <string_view> #include <unordered_map> #include <vector> // neo #include <neo_command.hpp> #include <neo_command_instance.hpp> #include <neo_command_template.hpp> #include <neo_location.hpp> namespace neo { class registry; struct command_handler; class NEO_API state_machine { public: enum options { f_trace_scan = 1, f_trace_parse = 2, f_continue_on_error = 4, }; using option_flags = std::uint32_t; using import_handler = std::function<std::string_view(std::string_view)>; state_machine(registry const& registry, command_handler* handler, option_flags flags = 0) noexcept; using location_type = neo::location; void start_region(std::string_view) noexcept; bool consume(neo::command&& cmd) noexcept; void add_template(neo::command_template&&) noexcept; void push_template(neo::command_template const&) noexcept; void record_template(neo::command_template&) noexcept; void remove_template(std::string_view) noexcept; bool consume(neo::command_instance&&) noexcept; bool end_block() noexcept; void start_region(std::string_view region_id, text_content&& content) noexcept; void import_script(std::string_view file_id) noexcept; void parse(std::string_view src_name, std::string_view content) noexcept; void error(location_type const&, std::string const&) noexcept; // Import handler registration void set_import_handler(import_handler&& handler) noexcept { importer_ = std::move(handler); } // String container void put(std::int32_t len) noexcept { read_len(len); } void skip_len(std::int32_t len) noexcept { assert(len_reading_ == 0); pos_commit_ += len; } std::string_view get() const noexcept { return current_file_.substr(pos_commit_, len_reading_); } void commit() noexcept { pos_commit_ += len_reading_; len_reading_ = 0; } std::string_view make_token() noexcept { auto m = current_file_.substr(pos_commit_, len_reading_); commit(); return m; } void append_to_esqstr(std::string_view ss) noexcept { esq_string_ += ss; } std::string& manage_esq_string() noexcept { return esq_string_; } void push_content() noexcept { content_.fragments.push_back(make_token()); } // region id void set_current_reg_id(std::string_view name) noexcept { region_type_ = name; } text_content retrieve_content() noexcept { return std::move(content_); } // stream int read(char* buffer, int siz) noexcept; // Content creator neo::command_template make_command_template(std::vector<std::string_view>&&, neo::command&&) noexcept; neo::command_template make_command_template(std::string_view, std::vector<std::string_view>&&, neo::command&&) noexcept; neo::command make_command(std::string_view, neo::command::parameters&&, bool scope_trigger = false) noexcept; neo::command_instance make_instance(std::string_view, neo::command::param_t&&, bool scope_trigger = false) noexcept; std::string_view get_file_name() const noexcept { return source_name_; } location_type const& loc() const noexcept { return loc_; } location_type& loc() noexcept { return loc_; } void push_error(location const& l, std::string_view e) noexcept; void resolve(neo::command&) noexcept; neo::command_template const& find_template(std::string_view name) noexcept { auto it = templates_.find(name); if (it != templates_.end()) { return it->second.back().get(); } else { push_error(loc(), "template not found -> "); push_error(loc(), name); return null_template_; } } void begin_scan() noexcept; void end_scan() noexcept; void* scanner = nullptr; template <typename lambda> void for_each_error(lambda&& l) noexcept { std::for_each(errors_.begin(), errors_.end(), l); } bool fail_bit() const noexcept { return errors_.size() > 0 && !(flags_ & f_continue_on_error); } bool skip() const noexcept { return skip_ > 0; } void enter_skip_scope() noexcept { skip_++; } std::int32_t exit_skip_scope() noexcept { return --skip_; } inline void start_read_len(int len) noexcept { len_reading_ = len; } inline void read_len(int l) noexcept { len_reading_ += l; assert(current_file_[pos_commit_ + len_reading_ - 1] != 0); } inline int flush_read_len() noexcept { int r = len_reading_; len_reading_ = 0; return r; } private: using record_ptr = neo::command_template::record*; std::string_view default_import_handler(std::string_view) noexcept; using push_templates = std::vector<std::reference_wrapper<neo::command_template const>>; using template_map = std::unordered_map<std::string_view, push_templates>; using root_template_list = std::forward_list<neo::command_template>; using def_imported_string_map = std::unordered_map<std::string_view, std::string>; template_map templates_; std::vector<std::uint32_t> block_stack_; std::vector<record_ptr> record_stack_; std::vector<std::string> errors_; def_imported_string_map imported_; root_template_list root_template_storage_; registry const& registry_; command_handler* cmd_handler_; resolver* resolver_stack_ = nullptr; std::string_view region_; import_handler importer_; std::string_view current_file_; std::string source_name_; std::string_view region_type_; std::string esq_string_; location_type loc_; option_flags flags_ = 0; std::int32_t skip_ = 0; std::int32_t pos_ = 0; std::int32_t pos_commit_ = 0; std::int32_t len_reading_ = 0; text_content content_; static const command_template null_template_; }; } // namespace neo
27.474359
80
0.646446
[ "vector" ]
5f2cf216a76c06f3c6408ad945e1540b3421826c
13,969
cpp
C++
prob.cpp
juliannieb/IALab4
7612df2cb3f895a69bf50a36e3f31c092d0ac515
[ "MIT" ]
null
null
null
prob.cpp
juliannieb/IALab4
7612df2cb3f895a69bf50a36e3f31c092d0ac515
[ "MIT" ]
null
null
null
prob.cpp
juliannieb/IALab4
7612df2cb3f895a69bf50a36e3f31c092d0ac515
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstdlib> #include <iostream> #include <vector> #include <map> #include <string> #include <set> #include <stack> #include <algorithm> using namespace std; struct node { string key; vector<node*> parents; map<string, int> idxOfParents; map<string, float> probabilitiesTable; float probability; }; typedef struct node Node; float getProbability(string nodeKey, string probKey, map<string, Node*> &nodes_map); float calculateChainRule(vector< vector <string> > query, map<string, Node*> &nodes_map); string getSigns(vector<string> probability, Node *node); Node* initializeNode(string key) { Node *new_node = new Node; new_node -> key = key; new_node -> parents = vector<Node*>(0); new_node -> idxOfParents = map<string, int>(); new_node -> probabilitiesTable = map<string, float>(); new_node -> probability = 0.0; return new_node; } string remove_chars(string s, char c) { string ans = ""; for (int i = 0; i < s.size(); i++) { if (s[i] != c) ans.push_back(s[i]); } return ans; } vector<string> split(string complete_string, char c) { vector<string> ans = vector<string>(0); string s = ""; for (int i = 0; i < complete_string.size(); i++) { if (complete_string[i] == c) { ans.push_back(s); s = ""; } else { if (c != ' ' && complete_string[i] == ' ') { continue; } s.push_back(complete_string[i]); } } ans.push_back(s); return ans; } void readNodes(vector<Node*> &nodes, map<string, Node*> &nodes_map) { string line; getline(cin, line); line = remove_chars(line, ' '); vector<string> nodeKeys = split(line, ','); for (int i = 0; i < nodeKeys.size(); i++) { string node_key = nodeKeys[i]; Node *new_node = initializeNode(node_key); nodes.push_back(new_node); nodes_map[node_key] = new_node; } } void printParents(vector<Node*> parents) { cout << "Parents: " << endl; for (int i = 0; i < parents.size(); i++) { cout << "\t" << parents[i] -> key << (i < parents.size() - 1 ? ", " : "\n"); } } void printProbabilities(map<string, float> probabilitiesTable) { typedef map<string, float>::iterator it_type; cout << "Probabilities:" << endl; for(it_type iterator = probabilitiesTable.begin(); iterator != probabilitiesTable.end(); iterator++) { cout << "\t" << iterator -> first << " - " << iterator -> second << endl; } } void printNode(Node *node) { cout << "Node: " << node -> key << endl; cout << "Probability: " << node -> probability << endl; printParents(node -> parents); printProbabilities(node -> probabilitiesTable); cout << endl; } void printNodes(vector<Node*> nodes) { cout << "Nodes: "; for (int i = 0; i < nodes.size(); i++) { cout << nodes[i] -> key << (i == nodes.size() - 1 ? "\n" : ", "); } } void printNodesMap(map<string, Node*> nodes_map) { typedef map<string, Node*>::iterator it_type; for(it_type iterator = nodes_map.begin(); iterator != nodes_map.end(); iterator++) { cout << iterator -> first << " - " << iterator -> second << endl; } } void addParents(Node *node, vector<string> &evidenceKeys, map<string, Node*> &nodes_map) { for (int i = 0; i < evidenceKeys.size(); i++) { string parentKey = evidenceKeys[i].substr(1, evidenceKeys[i].size()-1); if (!((node -> idxOfParents).count(parentKey))) { (node -> idxOfParents)[parentKey] = (node -> parents).size(); Node *parentNode = nodes_map[parentKey]; (node -> parents).push_back(parentNode); } } } void set_probabilities(map<string, Node*> &nodes_map, string query, string evidence, string probability) { float prob = atof(probability.c_str()); if (query[0] == '-') prob = 1 - prob; query = query.substr(1, query.size()-1); Node *queryNode = nodes_map[query]; if (evidence == "") { (queryNode -> probability) = prob; } else { vector<string> evidenceKeys = split(evidence, ','); addParents(queryNode, evidenceKeys, nodes_map); string probKey = ""; for (int i = 0; i < evidenceKeys.size(); i++) probKey += '0'; for (int i = 0; i < evidenceKeys.size(); i++) { char sign = evidenceKeys[i][0]; string parentKey = evidenceKeys[i].substr(1, evidenceKeys[i].size()-1); int parentIdx = (queryNode -> idxOfParents)[parentKey]; //cout << "parent key idx = " << parentIdx << endl; probKey[parentIdx] = (sign == '+' ? '1' : '0'); } (queryNode -> probabilitiesTable)[probKey] = prob; } //printNode(queryNode); } void read_probabilities(vector<Node*> &nodes, map<string, Node*> &nodes_map) { string line; while(getline(cin, line)) { if (line.empty()) { //cout << "Empty" << endl; break; } line = remove_chars(line, ' '); //cout << line << endl; vector<string> nodes_and_prob = split(line, '='); string nodes = nodes_and_prob[0]; string prob = nodes_and_prob[1]; //cout << nodes << " ------ " << prob << endl; vector<string> query_and_evidence = split(nodes, '|'); if (query_and_evidence.size() == 2) { string query = query_and_evidence[0]; string evidence = query_and_evidence[1]; //cout << "Query: " << query_and_evidence[0] << " --- Evidence: " << evidence << " --- " << prob << endl; set_probabilities(nodes_map, query, evidence, prob); } else { string query = query_and_evidence[0]; //cout << "Query: " << query_and_evidence[0] << " --- " << prob << endl; set_probabilities(nodes_map, query, "", prob); } } } vector<string> principalNodes(vector<string> queries, vector<string> evidence) { vector<string> principalNodes = vector<string>(); for (int i = 0; i < queries.size(); i++) { principalNodes.push_back(queries[i]); } for (int i = 0; i < evidence.size(); i++) { principalNodes.push_back(evidence[i]); } return principalNodes; } string principalNodesContain(string nodeKey, vector<string> principalNodes) { for (int i = 0; i < principalNodes.size(); i++) { char sign = principalNodes[i][0]; string principalNodeKey = principalNodes[i].substr(1, principalNodes[i].size()-1); if (principalNodeKey == nodeKey) return principalNodes[i]; } return ""; } int num_ancestors(Node *node) { stack<Node*> nodesStack = stack<Node*>(); set<Node*> nodesSet = set<Node*>(); nodesStack.push(node); nodesSet.insert(node); int ancestors = 0; while(!nodesStack.empty()) { node = nodesStack.top(); nodesStack.pop(); for (int i = 0; i < (node -> parents).size(); i++) { Node *parent = (node -> parents)[i]; if (!nodesSet.count(parent)) { ancestors++; nodesSet.insert(parent); nodesStack.push(parent); } } } return ancestors; } bool compareNodes(Node *i, Node *j) { return (num_ancestors(i) > num_ancestors(j)); } vector<string> getRelevant(set<Node*> &relevantSet, stack<Node*> &nodesStack, vector<string> &mainNodes) { vector<string> relevant = vector<string>(); vector<Node*> relevantNodes = vector<Node*>(); while(!nodesStack.empty()) { Node *node = nodesStack.top(); nodesStack.pop(); if (!relevantSet.count(node)) { relevantNodes.push_back(node); relevantSet.insert(node); } vector<Node*> parents = node -> parents; for (int i = 0; i < parents.size(); i++) { Node *parent = parents[i]; if (!relevantSet.count(parent)) { relevantNodes.push_back(parent); relevantSet.insert(parent); nodesStack.push(parent); } } } sort(relevantNodes.begin(), relevantNodes.end(), compareNodes); for (int i = 0; i < relevantNodes.size(); i++) { Node *node = relevantNodes[i]; string containedInPrincipalNodes = principalNodesContain(node->key, mainNodes); if (containedInPrincipalNodes != "") { relevant.push_back(containedInPrincipalNodes); } else { relevant.push_back(node->key); } } return relevant; } void combinations(int idx, vector<string> initial, vector<string> curr, vector< vector<string> > &ans) { if (curr.size() == initial.size()) { ans.push_back(curr); } else { if (initial[idx][0] == '+' || initial[idx][0] == '-') { curr.push_back(initial[idx]); combinations(idx+1, initial, curr, ans); } else { curr.push_back('+' + initial[idx]); combinations(idx+1, initial, curr, ans); curr.pop_back(); curr.push_back('-' + initial[idx]); combinations(idx+1, initial, curr, ans); } } } void printCombinations(vector< vector <string> > &comb) { for (int i = 0; i < comb.size(); i++) { for (int j = 0; j < comb[i].size(); j++) { cout << comb[i][j] << " "; } cout << endl; } } void read_queries(vector<Node*> &nodes, map<string, Node*> &nodes_map) { string line; while(getline(cin, line)) { line = remove_chars(line, ' '); vector<string> query_and_evidence = split(line, '|'); string query = query_and_evidence[0]; vector<string> queries = split(query, ','); if (query_and_evidence.size() > 1) { string evidenceString = query_and_evidence[1]; vector<string> evidence = split(evidenceString, ','); vector<string> mainNodes = principalNodes(queries, evidence); set<Node*> relevantSet = set<Node*>(); stack<Node*> nodesStack = stack<Node*>(); for (int j = 0; j < mainNodes.size(); j++) { string mainNodeKey = mainNodes[j].substr(1, mainNodes[j].size()-1); Node *mainNode = nodes_map[mainNodeKey]; nodesStack.push(mainNode); } //nodesStack.push(node); vector<string> relevant = getRelevant(relevantSet, nodesStack, mainNodes); for (int j = 0; j < relevant.size(); j++) { //cout << relevant[j] << (j == relevant.size() - 1 ? '\n' : ' '); } vector< vector<string> > comb = vector< vector<string> >(0, vector<string>()); combinations(0, relevant, vector<string>(), comb); //printCombinations(comb); set<Node*> relevantEvidenceSet = set<Node*>(); stack<Node*> evidenceNodesStack = stack<Node*>(); for (int j = 0; j < evidence.size(); j++) { string evidenceNodeKey = evidence[j].substr(1, evidence[j].size()-1); Node *evidenceNode = nodes_map[evidenceNodeKey]; evidenceNodesStack.push(evidenceNode); } vector<string> relevantEvidence = getRelevant(relevantEvidenceSet, evidenceNodesStack, evidence); for (int j = 0; j < relevantEvidence.size(); j++) { //cout << relevantEvidence[j] << (j == relevantEvidence.size() - 1 ? '\n' : ' '); } vector< vector<string> > combEvidence = vector< vector<string> >(0, vector<string>()); combinations(0, relevantEvidence, vector<string>(), combEvidence); //printCombinations(combEvidence); float prob = prob = calculateChainRule(comb, nodes_map)/calculateChainRule(combEvidence, nodes_map); cout << prob << endl; } else { double prob = 1.0; for (int i = 0; i < queries.size(); i++) { char sign = queries[i][0]; string nodeKey = queries[i].substr(1, queries[i].size()-1); Node *node = nodes_map[nodeKey]; if ((node -> parents).size() == 0) { prob *= (sign == '+' ? node -> probability : (1.0 - node -> probability)); cout << prob << endl; } else { vector<string> mainNodes = principalNodes(queries, vector<string>()); for (int i = 0; i < queries.size(); i++) { string nodeKey = queries[i].substr(1, queries[i].size()-1); Node *node = nodes_map[nodeKey]; set<Node*> relevantSet = set<Node*>(); stack<Node*> nodesStack = stack<Node*>(); nodesStack.push(node); vector<string> relevant = getRelevant(relevantSet, nodesStack, mainNodes); for (int i = 0; i < relevant.size(); i++) { //cout << relevant[i] << (i == relevant.size() - 1 ? '\n' : ' '); } vector< vector<string> > comb = vector< vector<string> >(0, vector<string>()); combinations(0, relevant, vector<string>(), comb); //printCombinations(comb); prob = calculateChainRule(comb, nodes_map); cout << prob << endl; } } } //cout << prob << endl; } } } float calculateChainRule(vector< vector<string> > query, map<string, Node*> &nodes_map){ float prob = 0.0; string signs = ""; string nodeKey = ""; for (int i = 0; i < query.size(); i++){ float prob2 = 1.0; for (int j = 0; j < query[i].size(); j++){ nodeKey = query[i][j].substr(1, query[i][j].size() - 1); //cout << "Node key: " << nodeKey << endl; Node *node = nodes_map[nodeKey]; vector<string>::const_iterator first = query[i].begin() + j + 1; vector<string>::const_iterator last = query[i].end(); vector<string> letters(first, last); signs = getSigns(letters, node); //cout << "get Signs" << endl; prob2 *= getProbability(query[i][j], signs, nodes_map); //cout << "get Prob" << endl; } prob += prob2; } return prob; } float getProbability(string nodeKey, string probKey, map<string, Node*> &nodes_map){ float prob = 1.0; char sign = nodeKey[0]; nodeKey = nodeKey.substr(1, nodeKey.size() - 1); Node *node = nodes_map[nodeKey]; if ((node->parents).size() > 0){ prob = sign == '+' ? (node->probabilitiesTable)[probKey] : 1 - (node->probabilitiesTable)[probKey]; } else{ prob = sign == '+' ? (node->probability) : 1 - (node->probability); } return prob; } string getSigns(vector<string> probability, Node *node){ string signs = ""; //cout << "getting signs..." << endl; //printNode(node); //cout << (node->parents).size() << endl; for (int i = 0; i < (node->parents).size(); i++){ signs += '0'; } //cout << signs << endl; //cout << probability.size() << endl; for (int i = 0; i < probability.size(); i++){ char sign = probability[i][0]; string nodeKey = probability[i].substr(1, probability[i].size() - 1); if (sign == '+'){ int parentIndex = node->idxOfParents[nodeKey]; signs[parentIndex] = '1'; } } return signs; } int main () { string input_type; vector<Node*> nodes = vector<Node*>(0); map<string, Node*> nodes_map = map<string, Node*> (); while(getline(cin, input_type)) { if (input_type == "[Nodes]") { readNodes(nodes, nodes_map); } //getline(cin, input_type); if (input_type == "[Probabilities]") { read_probabilities(nodes, nodes_map); } //getline(cin, input_type); if (input_type == "[Queries]") { read_queries(nodes, nodes_map); } } return 0; }
30.904867
108
0.628177
[ "vector" ]
5f3724a07317ee2fe26ae2507e41caef96ebf94a
25,455
cpp
C++
source/EterLib/StateManager.cpp
beetle2k/Metin2Client
114f492b71fcc90e8f5010c5b35b9fddb51639ca
[ "MIT" ]
13
2018-08-27T19:06:54.000Z
2021-11-12T05:44:04.000Z
source/EterLib/StateManager.cpp
stempomzeskas/Metin2Client
114f492b71fcc90e8f5010c5b35b9fddb51639ca
[ "MIT" ]
null
null
null
source/EterLib/StateManager.cpp
stempomzeskas/Metin2Client
114f492b71fcc90e8f5010c5b35b9fddb51639ca
[ "MIT" ]
15
2018-10-25T14:28:10.000Z
2022-03-25T14:05:09.000Z
#include "StdAfx.h" #include "StateManager.h" //#define StateManager_Assert(a) if (!(a)) puts("assert"#a) #define StateManager_Assert(a) assert(a) struct SLightData { enum { LIGHT_NUM = 8, }; D3DLIGHT8 m_akD3DLight[LIGHT_NUM]; } m_kLightData; void CStateManager::SetLight(DWORD index, CONST D3DLIGHT8* pLight) { assert(index<SLightData::LIGHT_NUM); m_kLightData.m_akD3DLight[index]=*pLight; m_lpD3DDev->SetLight(index, pLight); } void CStateManager::GetLight(DWORD index, D3DLIGHT8* pLight) { assert(index<8); *pLight=m_kLightData.m_akD3DLight[index]; } bool CStateManager::BeginScene() { m_bScene=true; D3DXMATRIX m4Proj; D3DXMATRIX m4View; D3DXMATRIX m4World; GetTransform(D3DTS_WORLD, &m4World); GetTransform(D3DTS_PROJECTION, &m4Proj); GetTransform(D3DTS_VIEW, &m4View); SetTransform(D3DTS_WORLD, &m4World); SetTransform(D3DTS_PROJECTION, &m4Proj); SetTransform(D3DTS_VIEW, &m4View); if (FAILED(m_lpD3DDev->BeginScene())) return false; return true; } void CStateManager::EndScene() { m_lpD3DDev->EndScene(); m_bScene=false; } CStateManager::CStateManager(LPDIRECT3DDEVICE8 lpDevice) : m_lpD3DDev(NULL) { m_bScene = false; m_dwBestMinFilter = D3DTEXF_LINEAR; m_dwBestMagFilter = D3DTEXF_LINEAR; SetDevice(lpDevice); } CStateManager::~CStateManager() { if (m_lpD3DDev) { m_lpD3DDev->Release(); m_lpD3DDev = NULL; } } void CStateManager::SetDevice(LPDIRECT3DDEVICE8 lpDevice) { StateManager_Assert(lpDevice); lpDevice->AddRef(); if (m_lpD3DDev) { m_lpD3DDev->Release(); m_lpD3DDev = NULL; } m_lpD3DDev = lpDevice; D3DCAPS8 d3dCaps; m_lpD3DDev->GetDeviceCaps(&d3dCaps); if (d3dCaps.TextureFilterCaps & D3DPTFILTERCAPS_MAGFANISOTROPIC) m_dwBestMagFilter = D3DTEXF_ANISOTROPIC; else m_dwBestMagFilter = D3DTEXF_LINEAR; if (d3dCaps.TextureFilterCaps & D3DPTFILTERCAPS_MINFANISOTROPIC) m_dwBestMinFilter = D3DTEXF_ANISOTROPIC; else m_dwBestMinFilter = D3DTEXF_LINEAR; DWORD dwMax = d3dCaps.MaxAnisotropy; dwMax = dwMax < 4 ? dwMax : 4; for (int i = 0; i < 8; ++i) m_lpD3DDev->SetTextureStageState(i, D3DTSS_MAXANISOTROPY, dwMax); SetDefaultState(); } void CStateManager::SetBestFiltering(DWORD dwStage) { SetTextureStageState(dwStage, D3DTSS_MINFILTER, m_dwBestMinFilter); SetTextureStageState(dwStage, D3DTSS_MAGFILTER, m_dwBestMagFilter); SetTextureStageState(dwStage, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); } void CStateManager::Restore() { int i, j; m_bForce = true; for (i = 0; i < STATEMANAGER_MAX_RENDERSTATES; ++i) SetRenderState(D3DRENDERSTATETYPE(i), m_CurrentState.m_RenderStates[i]); for (i = 0; i < STATEMANAGER_MAX_STAGES; ++i) for (j = 0; j < STATEMANAGER_MAX_TEXTURESTATES; ++j) SetTextureStageState(i, D3DTEXTURESTAGESTATETYPE(j), m_CurrentState.m_TextureStates[i][j]); for (i = 0; i < STATEMANAGER_MAX_STAGES; ++i) SetTexture(i, m_CurrentState.m_Textures[i]); m_bForce = false; } void CStateManager::SetDefaultState() { m_CurrentState.ResetState(); m_CopyState.ResetState(); m_ChipState.ResetState(); m_bScene = false; m_bForce = true; D3DXMATRIX Identity; D3DXMatrixIdentity(&Identity); SetTransform(D3DTS_WORLD, &Identity); SetTransform(D3DTS_VIEW, &Identity); SetTransform(D3DTS_PROJECTION, &Identity); D3DMATERIAL8 DefaultMat; ZeroMemory(&DefaultMat, sizeof(D3DMATERIAL8)); DefaultMat.Diffuse.r = 1.0f; DefaultMat.Diffuse.g = 1.0f; DefaultMat.Diffuse.b = 1.0f; DefaultMat.Diffuse.a = 1.0f; DefaultMat.Ambient.r = 1.0f; DefaultMat.Ambient.g = 1.0f; DefaultMat.Ambient.b = 1.0f; DefaultMat.Ambient.a = 1.0f; DefaultMat.Emissive.r = 0.0f; DefaultMat.Emissive.g = 0.0f; DefaultMat.Emissive.b = 0.0f; DefaultMat.Emissive.a = 0.0f; DefaultMat.Specular.r = 0.0f; DefaultMat.Specular.g = 0.0f; DefaultMat.Specular.b = 0.0f; DefaultMat.Specular.a = 0.0f; DefaultMat.Power = 0.0f; SetMaterial(&DefaultMat); SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL); SetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_MATERIAL); SetRenderState(D3DRS_AMBIENTMATERIALSOURCE, D3DMCS_MATERIAL); SetRenderState(D3DRS_EMISSIVEMATERIALSOURCE, D3DMCS_MATERIAL); SetRenderState(D3DRS_LINEPATTERN, 0xFFFFFFFF); SetRenderState(D3DRS_LASTPIXEL, FALSE); SetRenderState(D3DRS_ALPHAREF, 1); SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL); SetRenderState(D3DRS_ZVISIBLE, FALSE); SetRenderState(D3DRS_FOGSTART, 0); SetRenderState(D3DRS_FOGEND, 0); SetRenderState(D3DRS_FOGDENSITY, 0); SetRenderState(D3DRS_EDGEANTIALIAS, FALSE); SetRenderState(D3DRS_ZBIAS, 0); SetRenderState(D3DRS_STENCILWRITEMASK, 0xFFFFFFFF); SetRenderState(D3DRS_AMBIENT, 0x00000000); SetRenderState(D3DRS_LOCALVIEWER, FALSE); SetRenderState(D3DRS_NORMALIZENORMALS, FALSE); SetRenderState(D3DRS_VERTEXBLEND, D3DVBF_DISABLE); SetRenderState(D3DRS_CLIPPLANEENABLE, 0); SetRenderState(D3DRS_SOFTWAREVERTEXPROCESSING, FALSE); SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, FALSE); SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF); SetRenderState(D3DRS_INDEXEDVERTEXBLENDENABLE, FALSE); SetRenderState(D3DRS_COLORWRITEENABLE, 0xFFFFFFFF); SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID); SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); SetRenderState(D3DRS_CULLMODE, D3DCULL_CW); SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD); SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); SetRenderState(D3DRS_FOGENABLE, FALSE); SetRenderState(D3DRS_FOGCOLOR, 0xFF000000); SetRenderState(D3DRS_FOGTABLEMODE, D3DFOG_NONE); SetRenderState(D3DRS_FOGVERTEXMODE, D3DFOG_LINEAR); SetRenderState(D3DRS_RANGEFOGENABLE, FALSE); SetRenderState(D3DRS_ZENABLE, TRUE); SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL); SetRenderState(D3DRS_ZWRITEENABLE, TRUE); SetRenderState(D3DRS_DITHERENABLE, TRUE); SetRenderState(D3DRS_STENCILENABLE, FALSE); SetRenderState(D3DRS_ALPHATESTENABLE, FALSE); SetRenderState(D3DRS_CLIPPING, TRUE); SetRenderState(D3DRS_LIGHTING, FALSE); SetRenderState(D3DRS_SPECULARENABLE, FALSE); SetRenderState(D3DRS_COLORVERTEX, FALSE); SetRenderState(D3DRS_WRAP0, 0); SetRenderState(D3DRS_WRAP1, 0); SetRenderState(D3DRS_WRAP2, 0); SetRenderState(D3DRS_WRAP3, 0); SetRenderState(D3DRS_WRAP4, 0); SetRenderState(D3DRS_WRAP5, 0); SetRenderState(D3DRS_WRAP6, 0); SetRenderState(D3DRS_WRAP7, 0); SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_CURRENT); SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_CURRENT); SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1); SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE); SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE); SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_DIFFUSE); SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE); SetTextureStageState(1, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); SetTextureStageState(1, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); SetTextureStageState(2, D3DTSS_COLOROP, D3DTOP_DISABLE); SetTextureStageState(2, D3DTSS_COLORARG1, D3DTA_TEXTURE); SetTextureStageState(2, D3DTSS_COLORARG2, D3DTA_DIFFUSE); SetTextureStageState(2, D3DTSS_ALPHAOP, D3DTOP_DISABLE); SetTextureStageState(2, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); SetTextureStageState(2, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); SetTextureStageState(3, D3DTSS_COLOROP, D3DTOP_DISABLE); SetTextureStageState(3, D3DTSS_COLORARG1, D3DTA_TEXTURE); SetTextureStageState(3, D3DTSS_COLORARG2, D3DTA_DIFFUSE); SetTextureStageState(3, D3DTSS_ALPHAOP, D3DTOP_DISABLE); SetTextureStageState(3, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); SetTextureStageState(3, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); SetTextureStageState(4, D3DTSS_COLOROP, D3DTOP_DISABLE); SetTextureStageState(4, D3DTSS_COLORARG1, D3DTA_TEXTURE); SetTextureStageState(4, D3DTSS_COLORARG2, D3DTA_DIFFUSE); SetTextureStageState(4, D3DTSS_ALPHAOP, D3DTOP_DISABLE); SetTextureStageState(4, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); SetTextureStageState(4, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); SetTextureStageState(5, D3DTSS_COLOROP, D3DTOP_DISABLE); SetTextureStageState(5, D3DTSS_COLORARG1, D3DTA_TEXTURE); SetTextureStageState(5, D3DTSS_COLORARG2, D3DTA_DIFFUSE); SetTextureStageState(5, D3DTSS_ALPHAOP, D3DTOP_DISABLE); SetTextureStageState(5, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); SetTextureStageState(5, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); SetTextureStageState(6, D3DTSS_COLOROP, D3DTOP_DISABLE); SetTextureStageState(6, D3DTSS_COLORARG1, D3DTA_TEXTURE); SetTextureStageState(6, D3DTSS_COLORARG2, D3DTA_DIFFUSE); SetTextureStageState(6, D3DTSS_ALPHAOP, D3DTOP_DISABLE); SetTextureStageState(6, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); SetTextureStageState(6, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); SetTextureStageState(7, D3DTSS_COLOROP, D3DTOP_DISABLE); SetTextureStageState(7, D3DTSS_COLORARG1, D3DTA_TEXTURE); SetTextureStageState(7, D3DTSS_COLORARG2, D3DTA_DIFFUSE); SetTextureStageState(7, D3DTSS_ALPHAOP, D3DTOP_DISABLE); SetTextureStageState(7, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); SetTextureStageState(7, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 0); SetTextureStageState(1, D3DTSS_TEXCOORDINDEX, 1); SetTextureStageState(2, D3DTSS_TEXCOORDINDEX, 2); SetTextureStageState(3, D3DTSS_TEXCOORDINDEX, 3); SetTextureStageState(4, D3DTSS_TEXCOORDINDEX, 4); SetTextureStageState(5, D3DTSS_TEXCOORDINDEX, 5); SetTextureStageState(6, D3DTSS_TEXCOORDINDEX, 6); SetTextureStageState(7, D3DTSS_TEXCOORDINDEX, 7); SetTextureStageState(0, D3DTSS_MINFILTER, D3DTEXF_LINEAR); SetTextureStageState(0, D3DTSS_MAGFILTER, D3DTEXF_LINEAR); SetTextureStageState(0, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); SetTextureStageState(1, D3DTSS_MINFILTER, D3DTEXF_LINEAR); SetTextureStageState(1, D3DTSS_MAGFILTER, D3DTEXF_LINEAR); SetTextureStageState(1, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); SetTextureStageState(2, D3DTSS_MINFILTER, D3DTEXF_LINEAR); SetTextureStageState(2, D3DTSS_MAGFILTER, D3DTEXF_LINEAR); SetTextureStageState(2, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); SetTextureStageState(3, D3DTSS_MINFILTER, D3DTEXF_LINEAR); SetTextureStageState(3, D3DTSS_MAGFILTER, D3DTEXF_LINEAR); SetTextureStageState(3, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); SetTextureStageState(4, D3DTSS_MINFILTER, D3DTEXF_LINEAR); SetTextureStageState(4, D3DTSS_MAGFILTER, D3DTEXF_LINEAR); SetTextureStageState(4, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); SetTextureStageState(5, D3DTSS_MINFILTER, D3DTEXF_LINEAR); SetTextureStageState(5, D3DTSS_MAGFILTER, D3DTEXF_LINEAR); SetTextureStageState(5, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); SetTextureStageState(6, D3DTSS_MINFILTER, D3DTEXF_LINEAR); SetTextureStageState(6, D3DTSS_MAGFILTER, D3DTEXF_LINEAR); SetTextureStageState(6, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); SetTextureStageState(7, D3DTSS_MINFILTER, D3DTEXF_LINEAR); SetTextureStageState(7, D3DTSS_MAGFILTER, D3DTEXF_LINEAR); SetTextureStageState(7, D3DTSS_MIPFILTER, D3DTEXF_LINEAR); SetTextureStageState(0, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); SetTextureStageState(0, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); SetTextureStageState(1, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); SetTextureStageState(1, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); SetTextureStageState(2, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); SetTextureStageState(2, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); SetTextureStageState(3, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); SetTextureStageState(3, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); SetTextureStageState(4, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); SetTextureStageState(4, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); SetTextureStageState(5, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); SetTextureStageState(5, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); SetTextureStageState(6, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); SetTextureStageState(6, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); SetTextureStageState(7, D3DTSS_ADDRESSU, D3DTADDRESS_WRAP); SetTextureStageState(7, D3DTSS_ADDRESSV, D3DTADDRESS_WRAP); SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, 0); SetTextureStageState(1, D3DTSS_TEXTURETRANSFORMFLAGS, 0); SetTextureStageState(2, D3DTSS_TEXTURETRANSFORMFLAGS, 0); SetTextureStageState(3, D3DTSS_TEXTURETRANSFORMFLAGS, 0); SetTextureStageState(4, D3DTSS_TEXTURETRANSFORMFLAGS, 0); SetTextureStageState(5, D3DTSS_TEXTURETRANSFORMFLAGS, 0); SetTextureStageState(6, D3DTSS_TEXTURETRANSFORMFLAGS, 0); SetTextureStageState(7, D3DTSS_TEXTURETRANSFORMFLAGS, 0); SetTexture(0, NULL); SetTexture(1, NULL); SetTexture(2, NULL); SetTexture(3, NULL); SetTexture(4, NULL); SetTexture(5, NULL); SetTexture(6, NULL); SetTexture(7, NULL); SetPixelShader(0); SetVertexShader(D3DFVF_XYZ); D3DXVECTOR4 av4Null[STATEMANAGER_MAX_VCONSTANTS]; memset(av4Null, 0, sizeof(av4Null)); SetVertexShaderConstant(0, av4Null, STATEMANAGER_MAX_VCONSTANTS); SetPixelShaderConstant(0, av4Null, STATEMANAGER_MAX_PCONSTANTS); m_bForce = false; #ifdef _DEBUG int i, j; for (i = 0; i < STATEMANAGER_MAX_RENDERSTATES; i++) m_bRenderStateSavingFlag[i] = FALSE; for (j = 0; j < STATEMANAGER_MAX_TRANSFORMSTATES; j++) m_bTransformSavingFlag[j] = FALSE; for (j = 0; j < STATEMANAGER_MAX_STAGES; ++j) for (i = 0; i < STATEMANAGER_MAX_TEXTURESTATES; ++i) m_bTextureStageStateSavingFlag[j][i] = FALSE; #endif _DEBUG } // Material void CStateManager::SaveMaterial() { m_CopyState.m_D3DMaterial = m_CurrentState.m_D3DMaterial; } void CStateManager::SaveMaterial(const D3DMATERIAL8 * pMaterial) { // Check that we have set this up before, if not, the default is this. m_CopyState.m_D3DMaterial = m_CurrentState.m_D3DMaterial; SetMaterial(pMaterial); } void CStateManager::RestoreMaterial() { SetMaterial(&m_CopyState.m_D3DMaterial); } void CStateManager::SetMaterial(const D3DMATERIAL8 * pMaterial) { m_lpD3DDev->SetMaterial(pMaterial); m_CurrentState.m_D3DMaterial = *pMaterial; } void CStateManager::GetMaterial(D3DMATERIAL8 * pMaterial) { // Set the renderstate and remember it. *pMaterial = m_CurrentState.m_D3DMaterial; } // Renderstates DWORD CStateManager::GetRenderState(D3DRENDERSTATETYPE Type) { return m_CurrentState.m_RenderStates[Type]; } void CStateManager::SaveRenderState(D3DRENDERSTATETYPE Type, DWORD dwValue) { #ifdef _DEBUG if (m_bRenderStateSavingFlag[Type]) { Tracef(" CStateManager::SaveRenderState - This render state is already saved [%d, %d]\n", Type, dwValue); StateManager_Assert(!" This render state is already saved!"); } m_bRenderStateSavingFlag[Type] = TRUE; #endif _DEBUG // Check that we have set this up before, if not, the default is this. m_CopyState.m_RenderStates[Type] = m_CurrentState.m_RenderStates[Type]; SetRenderState(Type, dwValue); } void CStateManager::RestoreRenderState(D3DRENDERSTATETYPE Type) { #ifdef _DEBUG if (!m_bRenderStateSavingFlag[Type]) { Tracef(" CStateManager::SaveRenderState - This render state was not saved [%d, %d]\n", Type); StateManager_Assert(!" This render state was not saved!"); } m_bRenderStateSavingFlag[Type] = FALSE; #endif _DEBUG SetRenderState(Type, m_CopyState.m_RenderStates[Type]); } void CStateManager::SetRenderState(D3DRENDERSTATETYPE Type, DWORD Value) { if (m_CurrentState.m_RenderStates[Type] == Value) return; m_lpD3DDev->SetRenderState(Type, Value); m_CurrentState.m_RenderStates[Type] = Value; } void CStateManager::GetRenderState(D3DRENDERSTATETYPE Type, DWORD * pdwValue) { *pdwValue = m_CurrentState.m_RenderStates[Type]; } // Textures void CStateManager::SaveTexture(DWORD dwStage, LPDIRECT3DBASETEXTURE8 pTexture) { // Check that we have set this up before, if not, the default is this. m_CopyState.m_Textures[dwStage] = m_CurrentState.m_Textures[dwStage]; SetTexture(dwStage, pTexture); } void CStateManager::RestoreTexture(DWORD dwStage) { SetTexture(dwStage, m_CopyState.m_Textures[dwStage]); } void CStateManager::SetTexture(DWORD dwStage, LPDIRECT3DBASETEXTURE8 pTexture) { if (pTexture == m_CurrentState.m_Textures[dwStage]) return; m_lpD3DDev->SetTexture(dwStage, pTexture); m_CurrentState.m_Textures[dwStage] = pTexture; } void CStateManager::GetTexture(DWORD dwStage, LPDIRECT3DBASETEXTURE8 * ppTexture) { *ppTexture = m_CurrentState.m_Textures[dwStage]; } // Texture stage states void CStateManager::SaveTextureStageState(DWORD dwStage,D3DTEXTURESTAGESTATETYPE Type, DWORD dwValue) { // Check that we have set this up before, if not, the default is this. #ifdef _DEBUG if (m_bTextureStageStateSavingFlag[dwStage][Type]) { Tracef(" CStateManager::SaveTextureStageState - This texture stage state is already saved [%d, %d]\n", dwStage, Type); StateManager_Assert(!" This texture stage state is already saved!"); } m_bTextureStageStateSavingFlag[dwStage][Type] = TRUE; #endif _DEBUG m_CopyState.m_TextureStates[dwStage][Type] = m_CurrentState.m_TextureStates[dwStage][Type]; SetTextureStageState(dwStage, Type, dwValue); } void CStateManager::RestoreTextureStageState(DWORD dwStage, D3DTEXTURESTAGESTATETYPE Type) { #ifdef _DEBUG if (!m_bTextureStageStateSavingFlag[dwStage][Type]) { Tracef(" CStateManager::RestoreTextureStageState - This texture stage state was not saved [%d, %d]\n", dwStage, Type); StateManager_Assert(!" This texture stage state was not saved!"); } m_bTextureStageStateSavingFlag[dwStage][Type] = FALSE; #endif _DEBUG SetTextureStageState(dwStage, Type, m_CopyState.m_TextureStates[dwStage][Type]); } void CStateManager::SetTextureStageState(DWORD dwStage, D3DTEXTURESTAGESTATETYPE Type, DWORD dwValue) { if (m_CurrentState.m_TextureStates[dwStage][Type] == dwValue) return; m_lpD3DDev->SetTextureStageState(dwStage, Type, dwValue); m_CurrentState.m_TextureStates[dwStage][Type] = dwValue; } void CStateManager::GetTextureStageState(DWORD dwStage, D3DTEXTURESTAGESTATETYPE Type, DWORD * pdwValue) { *pdwValue = m_CurrentState.m_TextureStates[dwStage][Type]; } // Vertex Shader void CStateManager::SaveVertexShader(DWORD dwShader) { m_CopyState.m_dwVertexShader = m_CurrentState.m_dwVertexShader; SetVertexShader(dwShader); } void CStateManager::RestoreVertexShader() { SetVertexShader(m_CopyState.m_dwVertexShader); } void CStateManager::SetVertexShader(DWORD dwShader) { if (m_CurrentState.m_dwVertexShader == dwShader) return; m_lpD3DDev->SetVertexShader(dwShader); m_CurrentState.m_dwVertexShader = dwShader; } void CStateManager::GetVertexShader(DWORD * pdwShader) { *pdwShader = m_CurrentState.m_dwVertexShader; } // Pixel Shader void CStateManager::SavePixelShader(DWORD dwShader) { m_CopyState.m_dwPixelShader = m_CurrentState.m_dwPixelShader; SetPixelShader(dwShader); } void CStateManager::RestorePixelShader() { SetPixelShader(m_CopyState.m_dwPixelShader); } void CStateManager::SetPixelShader(DWORD dwShader) { if (m_CurrentState.m_dwPixelShader == dwShader) return; m_lpD3DDev->SetPixelShader(dwShader); m_CurrentState.m_dwPixelShader = dwShader; } void CStateManager::GetPixelShader(DWORD * pdwShader) { *pdwShader = m_CurrentState.m_dwPixelShader; } // *** These states are cached, but not protected from multiple sends of the same value. // Transform void CStateManager::SaveTransform(D3DTRANSFORMSTATETYPE Type, const D3DMATRIX* pMatrix) { #ifdef _DEBUG if (m_bTransformSavingFlag[Type]) { Tracef(" CStateManager::SaveTransform - This transform is already saved [%d]\n", Type); StateManager_Assert(!" This trasform is already saved!"); } m_bTransformSavingFlag[Type] = TRUE; #endif _DEBUG m_CopyState.m_Matrices[Type] = m_CurrentState.m_Matrices[Type]; SetTransform(Type, (D3DXMATRIX *)pMatrix); } void CStateManager::RestoreTransform(D3DTRANSFORMSTATETYPE Type) { #ifdef _DEBUG if (!m_bTransformSavingFlag[Type]) { Tracef(" CStateManager::RestoreTransform - This transform was not saved [%d]\n", Type); StateManager_Assert(!" This render state was not saved!"); } m_bTransformSavingFlag[Type] = FALSE; #endif _DEBUG SetTransform(Type, &m_CopyState.m_Matrices[Type]); } // Don't cache-check the transform. To much to do void CStateManager::SetTransform(D3DTRANSFORMSTATETYPE Type, const D3DMATRIX* pMatrix) { if (m_bScene) { m_lpD3DDev->SetTransform(Type, pMatrix); } else { assert(D3DTS_VIEW==Type || D3DTS_PROJECTION==Type || D3DTS_WORLD==Type); } m_CurrentState.m_Matrices[Type] = *pMatrix; } void CStateManager::GetTransform(D3DTRANSFORMSTATETYPE Type, D3DMATRIX * pMatrix) { *pMatrix = m_CurrentState.m_Matrices[Type]; } // SetVertexShaderConstant void CStateManager::SaveVertexShaderConstant(DWORD dwRegister,CONST void* pConstantData,DWORD dwConstantCount) { DWORD i; for (i = 0; i < dwConstantCount; i++) { StateManager_Assert((dwRegister + i) < STATEMANAGER_MAX_VCONSTANTS); m_CopyState.m_VertexShaderConstants[dwRegister + i] = m_CurrentState.m_VertexShaderConstants[dwRegister + i]; } SetVertexShaderConstant(dwRegister, pConstantData, dwConstantCount); } void CStateManager::RestoreVertexShaderConstant(DWORD dwRegister, DWORD dwConstantCount) { SetVertexShaderConstant(dwRegister, &m_CopyState.m_VertexShaderConstants[dwRegister], dwConstantCount); } void CStateManager::SetVertexShaderConstant(DWORD dwRegister,CONST void* pConstantData,DWORD dwConstantCount) { m_lpD3DDev->SetVertexShaderConstant(dwRegister, pConstantData, dwConstantCount); // Set the renderstate and remember it. for (DWORD i = 0; i < dwConstantCount; i++) { StateManager_Assert((dwRegister + i) < STATEMANAGER_MAX_VCONSTANTS); m_CurrentState.m_VertexShaderConstants[dwRegister + i] = *(((D3DXVECTOR4*)pConstantData) + i); } } // SetPixelShaderConstant void CStateManager::SavePixelShaderConstant(DWORD dwRegister,CONST void* pConstantData,DWORD dwConstantCount) { DWORD i; for (i = 0; i < dwConstantCount; i++) { StateManager_Assert((dwRegister + i) < STATEMANAGER_MAX_VCONSTANTS); m_CopyState.m_PixelShaderConstants[dwRegister + i] = *(((D3DXVECTOR4*)pConstantData) + i); } SetPixelShaderConstant(dwRegister, pConstantData, dwConstantCount); } void CStateManager::RestorePixelShaderConstant(DWORD dwRegister, DWORD dwConstantCount) { SetPixelShaderConstant(dwRegister, &m_CopyState.m_PixelShaderConstants[dwRegister], dwConstantCount); } void CStateManager::SetPixelShaderConstant(DWORD dwRegister,CONST void* pConstantData,DWORD dwConstantCount) { m_lpD3DDev->SetPixelShaderConstant(dwRegister, pConstantData, dwConstantCount); // Set the renderstate and remember it. for (DWORD i = 0; i < dwConstantCount; i++) { StateManager_Assert((dwRegister + i) < STATEMANAGER_MAX_VCONSTANTS); m_CurrentState.m_PixelShaderConstants[dwRegister + i] = *(((D3DXVECTOR4*)pConstantData) + i); } } void CStateManager::SaveStreamSource(UINT StreamNumber, LPDIRECT3DVERTEXBUFFER8 pStreamData,UINT Stride) { // Check that we have set this up before, if not, the default is this. m_CopyState.m_StreamData[StreamNumber] = m_CurrentState.m_StreamData[StreamNumber]; SetStreamSource(StreamNumber, pStreamData, Stride); } void CStateManager::RestoreStreamSource(UINT StreamNumber) { SetStreamSource(StreamNumber, m_CopyState.m_StreamData[StreamNumber].m_lpStreamData, m_CopyState.m_StreamData[StreamNumber].m_Stride); } void CStateManager::SetStreamSource(UINT StreamNumber, LPDIRECT3DVERTEXBUFFER8 pStreamData, UINT Stride) { CStreamData kStreamData(pStreamData, Stride); if (m_CurrentState.m_StreamData[StreamNumber] == kStreamData) return; m_lpD3DDev->SetStreamSource(StreamNumber, pStreamData, Stride); m_CurrentState.m_StreamData[StreamNumber] = kStreamData; } void CStateManager::SaveIndices(LPDIRECT3DINDEXBUFFER8 pIndexData, UINT BaseVertexIndex) { m_CopyState.m_IndexData = m_CurrentState.m_IndexData; SetIndices(pIndexData, BaseVertexIndex); } void CStateManager::RestoreIndices() { SetIndices(m_CopyState.m_IndexData.m_lpIndexData, m_CopyState.m_IndexData.m_BaseVertexIndex); } void CStateManager::SetIndices(LPDIRECT3DINDEXBUFFER8 pIndexData, UINT BaseVertexIndex) { CIndexData kIndexData(pIndexData, BaseVertexIndex); if (m_CurrentState.m_IndexData == kIndexData) return; m_lpD3DDev->SetIndices(pIndexData, BaseVertexIndex); m_CurrentState.m_IndexData = kIndexData; } HRESULT CStateManager::DrawPrimitive(D3DPRIMITIVETYPE PrimitiveType, UINT StartVertex, UINT PrimitiveCount) { return (m_lpD3DDev->DrawPrimitive(PrimitiveType, StartVertex, PrimitiveCount)); } HRESULT CStateManager::DrawPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType, UINT PrimitiveCount, const void* pVertexStreamZeroData, UINT VertexStreamZeroStride) { m_CurrentState.m_StreamData[0] = NULL; return (m_lpD3DDev->DrawPrimitiveUP(PrimitiveType, PrimitiveCount, pVertexStreamZeroData, VertexStreamZeroStride)); } HRESULT CStateManager::DrawIndexedPrimitive(D3DPRIMITIVETYPE PrimitiveType, UINT minIndex, UINT NumVertices, UINT startIndex, UINT primCount) { return (m_lpD3DDev->DrawIndexedPrimitive(PrimitiveType, minIndex, NumVertices, startIndex, primCount)); } HRESULT CStateManager::DrawIndexedPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType, UINT MinVertexIndex, UINT NumVertexIndices, UINT PrimitiveCount, CONST void * pIndexData, D3DFORMAT IndexDataFormat, CONST void * pVertexStreamZeroData, UINT VertexStreamZeroStride) { m_CurrentState.m_IndexData = NULL; m_CurrentState.m_StreamData[0] = NULL; return (m_lpD3DDev->DrawIndexedPrimitiveUP(PrimitiveType, MinVertexIndex, NumVertexIndices, PrimitiveCount, pIndexData, IndexDataFormat, pVertexStreamZeroData, VertexStreamZeroStride)); }
33.058442
259
0.803104
[ "render", "transform" ]
5f3738befebbf4d4c2fd943ee1a4f14f8b4284e6
2,796
cpp
C++
src/bug_03.cpp
happanda/advent_2017
9e705f3088d79dac0caa471154ae88ed5106b2d2
[ "MIT" ]
null
null
null
src/bug_03.cpp
happanda/advent_2017
9e705f3088d79dac0caa471154ae88ed5106b2d2
[ "MIT" ]
null
null
null
src/bug_03.cpp
happanda/advent_2017
9e705f3088d79dac0caa471154ae88ed5106b2d2
[ "MIT" ]
null
null
null
#include "advent.h" std::pair<int, int> runFix2_toCoordinates(int N) { const int maxTier = static_cast<int>((-1.0 + std::sqrt(N)) / 2.0); const int tailLen = N - 1 - 4 * (1 + maxTier) * maxTier; std::pair<int, int> coords(maxTier, - maxTier); coords.first = coords.first + (tailLen > 0 ? 1 : 0); coords.second = coords.second + (tailLen > 0 ? tailLen % (2 * (maxTier + 1)) - 1 : 0); const int quadrant = tailLen / (2 * (maxTier + 1)); switch (quadrant) { case 1: std::swap(coords.first, coords.second); coords.first = -coords.first; break; case 2: coords.first = -coords.first; coords.second = -coords.second; break; case 3: std::swap(coords.first, coords.second); coords.second = -coords.second; break; } return coords; } void BugFix<3>::solve1st() { int number; *mIn >> number; //for (input_03 = 2; input_03 <= 25; ++input_03) { int manhattanDist = 0; if (number == 1) { *mOut << "0" << std::endl; return; } std::pair<int, int> coords = runFix2_toCoordinates(number); //*mOut << input_03 << " : " << coords.first << ", " << coords.second << std::endl; *mOut << std::abs(coords.first) + std::abs(coords.second) << std::endl; } } int runFix2_toSpiralNumber(const std::pair<int, int>& coords) { int maxTier = std::max(std::abs(coords.first), std::abs(coords.second)) - 1; int N = 4 * maxTier * (maxTier + 1); if (coords.second > -coords.first && coords.second <= coords.first) N += coords.second + maxTier + 1; else if (coords.first >= -coords.second && coords.first < coords.second) N += 2 * (maxTier + 1) + maxTier + 1 - coords.first; else if (coords.second < -coords.first && coords.second >= coords.first) N += 2 * 2 * (maxTier + 1) + maxTier + 1 - coords.second; else if (coords.first > coords.second && coords.first <= -coords.second) N += 3 * 2 * (maxTier + 1) + coords.first + maxTier + 1; return N + 1; } void BugFix<3>::solve2nd() { int number; *mIn >> number; const std::pair<int, int> shifts[] = { { 1, 0 },{ 1, 1 },{ 0, 1 },{ -1, 1 },{ -1, 0 },{ -1, -1 },{ 0, -1 },{ 1, -1 } }; std::vector<int> spiral{ 1, 1 }; while (*spiral.rbegin() < number) { int number = spiral.size() + 1; const std::pair<int, int> coords = runFix2_toCoordinates(number); int sum = 0; for (int c = 0; c < 8; ++c) { std::pair<int, int> shifted = coords; shifted.first += shifts[c].first; shifted.second += shifts[c].second; int neighborNum = runFix2_toSpiralNumber(shifted); if (neighborNum < number) sum += spiral[neighborNum - 1]; } spiral.push_back(sum); } *mOut << *spiral.rbegin() << std::endl; /*for (int x = -2; x <= 2; ++x) { for (int y = -2; y <= 2; ++y) { *mOut << x << ", " << y << " : " << runFix2_toSpiralNumber(std::make_pair(x, y)) << std::endl; } }*/ }
26.628571
120
0.590129
[ "vector" ]
5f3d9cebf54b2636d1dabfef5548f415b7573044
685
cpp
C++
String/42_recursive_sentence_generation.cpp
ritikrajdev/450DSA
a9efa8c8be781fd7b101407ac807a83b8a0929f4
[ "MIT" ]
null
null
null
String/42_recursive_sentence_generation.cpp
ritikrajdev/450DSA
a9efa8c8be781fd7b101407ac807a83b8a0929f4
[ "MIT" ]
null
null
null
String/42_recursive_sentence_generation.cpp
ritikrajdev/450DSA
a9efa8c8be781fd7b101407ac807a83b8a0929f4
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include "general.h" using namespace std; namespace ritik { void generate_sentences(vector<vector<string>> &vec, int curr = -1, string output = "") { if (curr == -1) curr = vec.size(); if (curr == 0) cout << output << '\n'; else { for (int i = 0; i < vec[curr - 1].size(); i++) { generate_sentences(vec, curr - 1, vec[curr - 1][i] + ' ' + output); } } } } // namespace ritik int main() { vector<vector<string>> vec{ {"you", "we"}, {"have", "are"}, {"sleep", "eat", "drink"}}; ritik::generate_sentences(vec); return 0; }
22.096774
79
0.515328
[ "vector" ]
5f3db91c6df0f5396ce5256efa160474716d9255
29,603
cpp
C++
src/node_graphics_view.cpp
zcutech/NodeTiler
e592d11962e2c87547fc6ed5631fb13e1a5eb5bd
[ "MIT" ]
4
2021-10-07T21:48:48.000Z
2022-03-30T15:04:12.000Z
src/node_graphics_view.cpp
zcutech/NodeTiler
e592d11962e2c87547fc6ed5631fb13e1a5eb5bd
[ "MIT" ]
null
null
null
src/node_graphics_view.cpp
zcutech/NodeTiler
e592d11962e2c87547fc6ed5631fb13e1a5eb5bd
[ "MIT" ]
null
null
null
// // Created by Charlie Zhong on 2021/9/6. // #include "node_graphics_view.h" #include <cmath> #include <QtWidgets> #include "node_graphics_wire.h" #include "node_graphics_socket.h" #include "node_graphics_scene.h" #include "node_graphics_cutline.h" #include "node_graphics_selection.h" #include "node_graphics_node.h" #include "node_wire.h" #include "node_socket.h" #include "node_node.h" #include "node_scene.h" #include "node_scene_history.h" QDMGraphicsView::QDMGraphicsView(QDMGraphicsScene *_grScene, QWidget *parent): QGraphicsView(parent), grScene(_grScene), zoomInFactor(1.25), zoomClamp(true), zoom(10), zoomStep(1), zoomRange({0, 15}), _elementAction(VIEW_A_NOOP), lastSceneMousePosition(QPointF(0, 0)), last_LMB_ClickScenePos(QPointF(0, 0)), last_LMB_ClickSceneObj(Q_NULLPTR), last_LMB_ClickSceneEvt(Q_NULLPTR), lastPressSocket(Q_NULLPTR), _socketDraggingWire(Q_NULLPTR), _socketDraggingEvent(Q_NULLPTR), _socketDraggingShift(false), _dragWireBeenHung(false), viewState(0), selectionPos(this->pos()), selPreSet({}), _viewSelectingGr(Q_NULLPTR), cutLine(Q_NULLPTR), editingFlag(false), _dragEnterListeners({}), _dropListeners({}) { this->setRenderHints(QPainter::Antialiasing | QPainter::HighQualityAntialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform); this->setViewportUpdateMode(QGraphicsView::FullViewportUpdate); this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // 使 view 以鼠标光标位置为中心进行缩放 this->setTransformationAnchor(QGraphicsView::AnchorUnderMouse); // 设置选区功能 // this->setDragMode(QGraphicsView::RubberBandDrag); // this->setRubberBandSelectionMode(Qt::ContainsItemShape); this->cutLine = new QDMCutLine(); this->grScene->addItem(this->cutLine); this->setScene(this->grScene); // 开启拖拽放置 this->setAcceptDrops(true); } void QDMGraphicsView::dragEnterEvent(QDragEnterEvent *event) { for (const auto& callback : this->_dragEnterListeners) callback(event); } void QDMGraphicsView::dropEvent(QDropEvent *event) { for (const auto& callback : this->_dropListeners) callback(event); } void QDMGraphicsView::addDragEnterListener(const std::function<void(QDragEnterEvent *event)> &callback) { this->_dragEnterListeners.push_back(callback); } void QDMGraphicsView::addDropListener(const std::function<void(QDropEvent *event)> &callback) { this->_dropListeners.push_back(callback); } // 绘制选区 void QDMGraphicsView::paintSelection(QMouseEvent *event) { // 矩形选区尺寸参数 auto curPos = event->pos(); // 选择器对象尺寸参数 auto curPos_s = this->mapToScene(curPos); // 需要跟随scene缩放 auto selWidth = curPos_s.x() - this->last_LMB_ClickScenePos.x(); auto selHeight = curPos_s.y() - this->last_LMB_ClickScenePos.y(); // 首次创建选择器 if (! this->_viewSelectingGr) { this->_viewSelectingGr = new QDMGraphicsSelection(this->last_LMB_ClickScenePos, selWidth, selHeight); this->grScene->addItem(this->_viewSelectingGr); } // 选取动作开始时,时被隐藏的选择器对象重新显示在新的位置 if (!this->_viewSelectingGr->isVisible()) { this->_viewSelectingGr->setPos(this->last_LMB_ClickScenePos); this->_viewSelectingGr->setVisible(true); } // 刷新选择器尺寸 this->_viewSelectingGr->width = selWidth; this->_viewSelectingGr->height = selHeight; this->_viewSelectingGr->setZValue(32); this->_viewSelectingGr->update(); // 选区矩形图元 auto recWidth = curPos.x() - this->selectionPos.x(); auto recHeight = curPos.y() - this->selectionPos.y(); auto selRec = new QRectF( fmin(this->selectionPos.x(), curPos.x()), fmin(this->selectionPos.y(), curPos.y()), std::abs(recWidth), std::abs(recHeight)); auto rangeItems = this->items(selRec->toRect(), recWidth < 0 ? Qt::IntersectsItemShape : Qt::ContainsItemShape); if (!rangeItems.empty()) rangeItems.erase(std::remove_if(rangeItems.begin(), rangeItems.end(), [](const QGraphicsItem* i) { return !(i->flags() & QGraphicsItem::ItemIsSelectable); }) ); // 选区中的对象集合 auto selCurSet = rangeItems.toSet(); // 实时刷新选区外的和新选择的 QSet<QGraphicsItem*> off_set; QSet<QGraphicsItem*> add_set; off_set = this->selPreSet - selCurSet; add_set = selCurSet - this->selPreSet; for (auto &i : off_set) i->setSelected(false); for (auto &i : add_set) i->setSelected(true); for (auto &i : selCurSet) // 按住Ctrl时拖拽可减选 i->setSelected(!(event->modifiers() & Qt::ControlModifier)); this->selPreSet = selCurSet; } void QDMGraphicsView::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::MiddleButton) this->middleMousePress(event); else if (event->button() == Qt::LeftButton) this->leftMousePress(event); else if (event->button() == Qt::RightButton) this->rightMousePress(event); else QGraphicsView::mousePressEvent(event); } void QDMGraphicsView::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::MiddleButton) this->middleMouseRelease(event); else if (event->button() == Qt::LeftButton) this->leftMouseRelease(event); else if (event->button() == Qt::RightButton) this->rightMouseRelease(event); else QGraphicsView::mouseReleaseEvent(event); } void QDMGraphicsView::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Control) this->viewState |= VIEW_STATE::VIEW_S_K_CTRL_PRESSED; else if (event->key() == Qt::Key_Shift) { this->viewState |= VIEW_STATE::VIEW_S_K_SHIFT_PRESSED; if (this->_elementAction == VIEW_A_WIRE_BATCHING || this->_elementAction == VIEW_A_WIRE_COPYING) this->_socketDraggingShift = true; } else if (event->key() == Qt::Key_Alt) this->viewState |= VIEW_STATE::VIEW_S_K_ALT_PRESSED; else QGraphicsView::keyPressEvent(event); } void QDMGraphicsView::keyReleaseEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Control) this->viewState &= ~VIEW_STATE::VIEW_S_K_CTRL_PRESSED; else if (event->key() == Qt::Key_Shift) { this->viewState &= ~VIEW_STATE::VIEW_S_K_SHIFT_PRESSED; if (this->_elementAction != VIEW_A_WIRE_BATCHING && this->_elementAction != VIEW_A_WIRE_COPYING) this->_socketDraggingShift = false; } else if (event->key() == Qt::Key_Alt) this->viewState &= ~VIEW_STATE::VIEW_S_K_ALT_PRESSED; else QGraphicsView::keyReleaseEvent(event); } // 使鼠标中键按住可以拖拽视图 void QDMGraphicsView::middleMousePress(QMouseEvent *event) { auto item = this->itemAtClick(event); // 正在拖拽创建edge时不响应中键拖拽 if (item != Q_NULLPTR || this->_elementAction != VIEW_A_NOOP) return; auto release_event = new QMouseEvent(QEvent::MouseButtonRelease, event->localPos(), event->screenPos(), Qt::LeftButton, Qt::NoButton, event->modifiers()); QGraphicsView::mouseReleaseEvent(release_event); this->setDragMode(QGraphicsView::ScrollHandDrag); auto fake_event = new QMouseEvent(event->type(), event->localPos(), event->screenPos(), Qt::LeftButton, event->buttons() | Qt::LeftButton, event->modifiers()); QGraphicsView::mousePressEvent(fake_event); } void QDMGraphicsView::middleMouseRelease(QMouseEvent *event) { auto fake_event = new QMouseEvent(event->type(), event->localPos(), event->screenPos(), Qt::LeftButton, event->button() | Qt::LeftButton, event->modifiers()); QGraphicsView::mouseReleaseEvent(fake_event); this->setDragMode(QGraphicsView::NoDrag); } void QDMGraphicsView::leftMousePress(QMouseEvent *event) { // 记录上一次鼠标点击位置 this->last_LMB_ClickScenePos = this->mapToScene(event->pos()); this->viewState |= VIEW_STATE::VIEW_S_LMB_PRESSED; auto item = this->itemAtClick(event); this->last_LMB_ClickSceneObj = item; this->last_LMB_ClickSceneEvt = event; this->selectionPos = event->pos(); auto withShift = bool(event->modifiers() & Qt::ShiftModifier); auto withAlt = bool(event->modifiers() & Qt::AltModifier); if (withShift) this->_socketDraggingShift = true; /* =========================== Alt键+左键可拖拽 ========================== */ // 正在拖拽创建edge时不响应中键拖拽 if (withAlt && !item && this->_elementAction == VIEW_A_NOOP) { this->setDragMode(QGraphicsView::ScrollHandDrag); QGraphicsView::mousePressEvent(event); return; } /* ========================= 画选区或点节点或者连线 ======================== */ if (!item || (item->type() != GRAPH_TYPE_SOCKET && this->grScene->isClickingOn(event->pos(), GRAPH_TYPE_NODE)) || item->type() == GRAPH_TYPE_WIRE) { // 点选和画选时Shift等效Ctrl if (withShift) { event->ignore(); auto fakeEvent = new QMouseEvent(QEvent::MouseButtonPress, event->localPos(), event->screenPos(), Qt::LeftButton, event->buttons() | Qt::LeftButton, event->modifiers() | Qt::ControlModifier); QGraphicsView::mousePressEvent(fakeEvent); // 按住Shift选择node时,同时选中其wires if (auto _node = this->grScene->isClickingOn(event->pos(), GRAPH_TYPE_NODE)) { auto grNode = qgraphicsitem_cast<QDMGraphicsNode*>(_node); grNode->selectAttachedWires(true); } return; } } /* ========================= 点击在节点端口,移动创建连线 ======================== */ if (item && item->type() == GRAPH_TYPE_SOCKET) { auto grSocket = qgraphicsitem_cast<QDMGraphicsSocket*>(item); if (!this->_socketDraggingShift) { // 场景1. 无shift键,点击在无连线输出端口 // 场景2. 无shift键,点击在有连线输出端口 // 场景3. 无shift键,点击在无连线输入端口 if (grSocket->socket->isOutput() || !grSocket->socket->hasWire()) { // 首次在一个端口上左击未释放,更改action,开始拖拽创建 if (!this->lastPressSocket) { this->lastPressSocket = grSocket->socket; this->_elementAction = VIEW_A_WIRE_DRAGGING; this->wireDragStart(grSocket); } // 再次在另一个端口上点击,更改action,完成拖拽创建 else if (this->lastPressSocket != grSocket->socket) { this->_elementAction = VIEW_A_NOOP; this->wireDragEnd(grSocket); this->lastPressSocket = Q_NULLPTR; this->_dragWireBeenHung = false; } } // 场景4. 无shift键,点击在有连线输入端口 else { // 首次在一个端口上左击未释放,更改action,开始拖拽移动 if (!this->lastPressSocket) { this->lastPressSocket = grSocket->socket; this->_elementAction = VIEW_A_WIRE_SHIFTING; this->wireDragTrans(grSocket->socket); } } } else { // 场景1. 有shift键,点击在无连线输出端口 // 场景2. 有shift键,点击在有连线输出端口 if (grSocket->socket->isOutput()) { // 首次在一个socket上左击未释放,更改action,等到原地释放后拖拽创建第一个 if (!this->lastPressSocket && this->_elementAction != VIEW_A_WIRE_BATCHING && this->_elementAction != VIEW_A_WIRE_COPYING) { this->lastPressSocket = grSocket->socket; this->_elementAction = VIEW_A_WIRE_BATCHING; } // 再次在同一个socket上左击未释放,无效 else if (this->lastPressSocket == grSocket->socket) this->lastPressSocket = Q_NULLPTR; } // 场景3. 有shift键,点击在无连线输入端口 else if (!grSocket->socket->hasWire()) { // 再次在另一个socket上左击未释放,更改action,完成批量创建当前的一个 if (this->_elementAction == VIEW_A_WIRE_BATCHING) { this->lastPressSocket = grSocket->socket; this->wireDragEnd(grSocket, true); } // 再次在另一个socket上左击未释放,更改action,完成批量复制当前的一个 else if (this->_elementAction == VIEW_A_WIRE_COPYING) { this->lastPressSocket = grSocket->socket; this->wireDragEnd(grSocket, true); } } // 场景4. 有shift键,点击在有连线输入端口 else { if (this->_elementAction == VIEW_A_WIRE_BATCHING) { // 再次在同一个socket上左击,无效 if (this->lastPressSocket == grSocket->socket) this->lastPressSocket = Q_NULLPTR; } else if (this->_elementAction == VIEW_A_NOOP) { this->lastPressSocket = grSocket->socket; this->_elementAction = VIEW_A_WIRE_COPYING; } // 再次在同一个socket上左击未释放,无效 else if (this->lastPressSocket == grSocket->socket) this->lastPressSocket = Q_NULLPTR; } } return; } /* ========================= 点击在空白位置,清理残留状态 ======================== */ this->_dragWireBeenHung = false; this->lastPressSocket = Q_NULLPTR; this->_elementAction = VIEW_A_NOOP; this->viewport()->unsetCursor(); if (this->_socketDraggingWire) { this->_socketDraggingWire->remove(); this->_socketDraggingWire = Q_NULLPTR; } // 在node区域中的socket等item须单独处理事件,避免不想要的可拖拽位置 QGraphicsView::mousePressEvent(event); } void QDMGraphicsView::leftMouseRelease(QMouseEvent *event) { this->viewState &= ~VIEW_STATE::VIEW_S_LMB_PRESSED; // 获取鼠标释放处图元对象 auto item = this->itemAtClick(event); auto withShift = bool(event->modifiers() & Qt::ShiftModifier); auto withAlt = bool(event->modifiers() & Qt::AltModifier); /* ======================= 释放鼠标左键,清除选区对象 ===================== */ if (this->_viewSelectingGr && this->_viewSelectingGr->isVisible() && this->_elementAction == VIEW_A_NOOP) { // 恢复自定义选择器状态 this->_viewSelectingGr->hide(); this->grScene->isSelecting = false; emit this->grScene->selsChanged(); this->selPreSet.clear(); return; } /* ========================== Alt键+左键可拖拽 ========================== */ if (withAlt && this->_elementAction == VIEW_A_NOOP) { this->setDragMode(QGraphicsView::NoDrag); QGraphicsView::mousePressEvent(event); return; } /* =========================== 点击节点或者连线 ========================== */ if (this->grScene->isClickingOn(event->pos(), GRAPH_TYPE_NODE) || (item && item->type() == GRAPH_TYPE_WIRE) || !item) { // 点选和画选时Shift等效Ctrl if (withShift && this->_elementAction == VIEW_A_NOOP) { event->ignore(); auto fake_event = new QMouseEvent(event->type(), event->localPos(), event->screenPos(), Qt::LeftButton, Qt::NoButton, event->modifiers() | Qt::ControlModifier); QGraphicsView::mouseReleaseEvent(fake_event); return; } } /* ====================== 释放在节点端口,完成创建连线 ===================== */ if (item && item->type() == GRAPH_TYPE_SOCKET) { auto grSocket = qgraphicsitem_cast<QDMGraphicsSocket*>(item); if (this->_elementAction == VIEW_A_WIRE_DRAGGING) { // 首次在另一个端口上释放,更改action,完成拖拽创建 if (grSocket->socket != this->lastPressSocket) { this->_elementAction = VIEW_A_NOOP; this->lastPressSocket = Q_NULLPTR; this->wireDragEnd(grSocket); } } else if (this->_elementAction == VIEW_A_WIRE_SHIFTING) { // 只要是曾移动到本端口外返回,更改action,完成拖拽移动 if (this->_dragWireBeenHung) { this->_elementAction = VIEW_A_NOOP; this->lastPressSocket = Q_NULLPTR; this->_dragWireBeenHung = false; this->wireDragEnd(grSocket, false, true); } } else if (this->_elementAction == VIEW_A_WIRE_BATCHING) { // 在一个端口上立即释放,更改action,开始批量创建新的一个 if (grSocket->socket == this->lastPressSocket) this->wireDragStart(grSocket, bool(this->_socketDraggingWire)); } else if (this->_elementAction == VIEW_A_WIRE_COPYING) { // 在一个端口上立即释放,更改action,开始复制创建新的一个 if (grSocket->socket == this->lastPressSocket) this->wireDragStart(grSocket, true); } return; } /* ====================== 释放在其他地方,删除临时连线 ===================== */ if (this->_socketDraggingWire || this->_elementAction != VIEW_A_NOOP) { auto grSocket = qgraphicsitem_cast<QDMGraphicsSocket*>(item); this->lastPressSocket = Q_NULLPTR; this->wireDragEnd(grSocket); } QGraphicsView::mouseReleaseEvent(event); } void QDMGraphicsView::rightMousePress(QMouseEvent *event) { this->viewState |= VIEW_STATE::VIEW_S_RMB_PRESSED; auto item = this->itemAtClick(event); if (!item && this->viewState & VIEW_STATE::VIEW_S_K_SHIFT_PRESSED && (this->viewState & VIEW_STATE::VIEW_S_MOUSE_PRESSED) == VIEW_STATE::VIEW_S_RMB_PRESSED) { this->viewport()->setCursor(QCursor(Qt::CrossCursor)); return; } // 删除连线 if (this->_socketDraggingWire && this->_elementAction != VIEW_A_NOOP) { this->lastPressSocket = Q_NULLPTR; this->wireDragEnd(Q_NULLPTR); } QGraphicsView::mousePressEvent(event); } void QDMGraphicsView::rightMouseRelease(QMouseEvent *event) { this->viewState &= ~VIEW_STATE::VIEW_S_RMB_PRESSED; // 结束画删除线,删除相交连线 if (this->_elementAction == VIEW_A_WIRE_CUTTING) { this->cutIntersectionWires(); this->cutLine->linePoints = {}; this->cutLine->update(); this->viewport()->unsetCursor(); this->_elementAction = VIEW_A_NOOP; return; } QGraphicsView::mouseReleaseEvent(event); } void QDMGraphicsView::mouseMoveEvent(QMouseEvent *event) { auto item = this->itemAtClick(event); auto grabItem = this->scene()->mouseGrabberItem(); this->viewState |= VIEW_STATE::VIEW_S_CURSOR_MOVING; auto withShift = bool(event->modifiers() & Qt::ShiftModifier); auto withAlt = bool(event->modifiers() & Qt::AltModifier); /* ========================== 正在拖拽视图场景 ========================== */ if (this->dragMode() == QGraphicsView::ScrollHandDrag) { QGraphicsView::mouseMoveEvent(event); return; } /* ========================== 点击节点对象拖拽 ========================== */ if (grabItem and grabItem->type() == GRAPH_TYPE_NODE) { QGraphicsView::mouseMoveEvent(event); return; } // std::cout << "mouse Move - after 点击节点对象拖拽" << std::endl; /* ========================== 点击背景拖拽选区 ========================== */ if (!this->last_LMB_ClickSceneObj && (this->viewState & VIEW_STATE::VIEW_S_LMB_DRAGGING) == VIEW_STATE::VIEW_S_LMB_DRAGGING) { if (this->dragMode() != QGraphicsView::ScrollHandDrag) { this->paintSelection(event); // 绘制选区 this->grScene->isSelecting = true; return; } else if (!withAlt) this->setDragMode(QGraphicsView::NoDrag); // 视图拖拽时松开了alt键 } /* ========================== 点击端口拖拽连线 ========================== */ if (this->_elementAction != VIEW_A_WIRE_BATCHING && this->_elementAction != VIEW_A_WIRE_COPYING) this->_socketDraggingShift = false; if (this->_elementAction == VIEW_A_WIRE_DRAGGING || this->_elementAction == VIEW_A_WIRE_BATCHING || this->_elementAction == VIEW_A_WIRE_SHIFTING || this->_elementAction == VIEW_A_WIRE_COPYING) { if (!this->_socketDraggingWire) return; this->_socketDraggingEvent = event; auto pos = this->mapToScene(event->pos()); if (!item || item->type() != GRAPH_TYPE_SOCKET) { this->_socketDraggingWire->state |= WIRE_STATE::WIRE_STATE_HANG; this->_dragWireBeenHung = true; } if (this->_socketDraggingWire->outputSocket) this->_socketDraggingWire->grWire->setDesPos(pos); else if (this->_socketDraggingWire->inputSocket) this->_socketDraggingWire->grWire->setSrcPos(pos); this->_socketDraggingWire->grWire->update(); this->_checkEndValid(event); return; } /* ========================== 批量和复制功能预览 ========================== */ // wire批量和复制功能 - 改变鼠标来预览 if (item && item->type() == GRAPH_TYPE_SOCKET && withShift) { auto grSocket = qgraphicsitem_cast<QDMGraphicsSocket*>(item); if (this->_elementAction == VIEW_A_NOOP && !(this->viewState & VIEW_STATE::VIEW_S_LMB_PRESSED)) { if (grSocket->socket->isOutput() || grSocket->socket->hasWire()) this->viewport()->setCursor(QCursor(Qt::DragCopyCursor)); } } /* ========================== Shift+右键画删除线 ========================= */ if (this->_elementAction == VIEW_A_WIRE_CUTTING || (this->viewState & VIEW_STATE::VIEW_S_WIRE_CUTTING) == VIEW_STATE::VIEW_S_WIRE_CUTTING) { this->_elementAction = VIEW_A_WIRE_CUTTING; auto pos = this->mapToScene(event->pos()); this->cutLine->linePoints.append(pos); this->cutLine->update(); return; } if (!item && this->_elementAction == VIEW_A_NOOP && this->dragMode() != QGraphicsView::ScrollHandDrag) this->viewport()->unsetCursor(); /* ========================== 鼠标移动触发信号 =========================== */ this->lastSceneMousePosition = this->mapToScene(event->pos()); emit scenePosChanged(this->lastSceneMousePosition); QGraphicsView::mouseMoveEvent(event); } void QDMGraphicsView::wheelEvent(QWheelEvent *event) { // 竖向Wheel + ALT = 横向Wheel, 反应在不同的angleDelta auto angleDelta = (event->modifiers() & Qt::AltModifier) ? event->angleDelta().x() : event->angleDelta().y(); // 计算缩放因子 float zoomOutFactor = 1.0f / this->zoomInFactor; float zoomFactor; // 计算缩放 if (angleDelta > 0) { zoomFactor = this->zoomInFactor; this->zoom += this->zoomStep; } else { zoomFactor = zoomOutFactor; this->zoom -= this->zoomStep; } bool clamped = false; if (this->zoom < this->zoomRange.first) { this->zoom = this->zoomRange.first; clamped = true; } if (this->zoom > this->zoomRange.second) { this->zoom = this->zoomRange.second; clamped = true; } if (!clamped || !this->zoomClamp) { // 同时解决拖拽时缩放的锚点问题 auto viewPos = event->pos(); auto scenePos = this->mapToScene(viewPos); this->centerOn(scenePos); // 设置 scene 比例 this->scale(zoomFactor, zoomFactor); auto delta = this->mapToScene(viewPos) - this->mapToScene(this->viewport()->rect().center()); this->centerOn(scenePos - delta); } } void QDMGraphicsView::deleteSelected(const QString& cutDesc) { for (auto item : this->grScene->selectedItems()) { if (item->type() == GRAPH_TYPE_WIRE) { auto grWire = qgraphicsitem_cast<QDMGraphicsWire*>(item); grWire->wire->remove(); } else if (item->type() == GRAPH_TYPE_NODE) { auto grNode = qgraphicsitem_cast<QDMGraphicsNode*>(item); grNode->node->remove(); } } if (!cutDesc.isEmpty()) this->grScene->scene->history->storeHistory(cutDesc, VIEW_HIST::CUT_ITEMS, true); else this->grScene->scene->history->storeHistory("Delete selected", VIEW_HIST::DELETE_ITEMS, true); } // return the object item on the position of mouse clicking QGraphicsItem* QDMGraphicsView::itemAtClick(QMouseEvent *event) { auto pos = event->pos(); auto obj = this->itemAt(pos); // 所在位置不是QGraphicsItem类型对象时,返回空指针 return obj; } // 检查和确保wire终点有效 bool QDMGraphicsView::_checkEndValid(QMouseEvent *event) { if (event == Q_NULLPTR) return true; Socket *boundSocket; if (this->_socketDraggingWire->state & WIRE_STATE::WIRE_STATE_HEAD) boundSocket = this->_socketDraggingWire->startSocket(); // 已绑定的一端 else boundSocket = this->_socketDraggingWire->endSocket(); auto grItem = this->itemAtClick(event); if (grItem && grItem->type() == GRAPH_TYPE_SOCKET) { this->_socketDraggingWire->state &= ~WIRE_STATE::WIRE_STATE_HANG; auto item = qgraphicsitem_cast<QDMGraphicsSocket*>(grItem); auto socket = item->socket; // two sockets have been bound each other, can't add more wires if (boundSocket->shareWireWith(socket)) { this->_socketDraggingWire->state &= ~WIRE_STATE::WIRE_STATE_GOON; return false; } // two sockets can't both be input or output else if ((boundSocket->isOutput() ^ socket->isOutput()) == 0) { this->_socketDraggingWire->state &= ~WIRE_STATE::WIRE_STATE_GOON; return false; } // wires can't be bound on two sockets of the same one node else if (boundSocket->node == socket->node) { this->_socketDraggingWire->state &= ~WIRE_STATE::WIRE_STATE_GOON; return false; } // able to bind else { this->_socketDraggingWire->state |= WIRE_STATE::WIRE_STATE_GOON; return true; } } return true; } void QDMGraphicsView::wireDragStart(QGraphicsItem *grItem, bool batch) { auto item = qgraphicsitem_cast<QDMGraphicsSocket*>(grItem); auto socket = item->socket; if (!this->_socketDraggingWire && !batch) this->_socketDraggingWire = new Wire( this->grScene->scene, socket, Q_NULLPTR, WIRE_TYPE_BEZIER); else { Wire *curWire; Socket *startSocket; Socket *endSocket; if (this->_socketDraggingWire) curWire = this->_socketDraggingWire; else curWire = socket->wires[0]; if (socket == curWire->endSocket()) { startSocket = curWire->startSocket(); endSocket = Q_NULLPTR; } else { startSocket = Q_NULLPTR; endSocket = curWire->endSocket(); } auto wireType = curWire->wireType(); this->_socketDraggingWire = new Wire( this->grScene->scene, startSocket, endSocket, wireType); } this->_socketDraggingWire->updatePositions(); } void QDMGraphicsView::wireDragEnd(QDMGraphicsSocket *grSocket, bool batch, bool afterTrans) { if (!batch) this->_elementAction = VIEW_A_NOOP; if (grSocket && this->_socketDraggingWire) { auto socket = grSocket->socket; if (this->_checkEndValid(this->_socketDraggingEvent)) { if (this->_socketDraggingWire->state & WIRE_STATE::WIRE_STATE_HEAD) { this->_socketDraggingWire->endSocket(socket); this->_socketDraggingWire->state |= WIRE_STATE::WIRE_STATE_TAIL; } else { this->_socketDraggingWire->startSocket(socket); this->_socketDraggingWire->state |= WIRE_STATE::WIRE_STATE_HEAD; } this->_socketDraggingWire->updatePositions(); if (!batch) this->_socketDraggingWire = Q_NULLPTR; auto desc = afterTrans? "Drag wire end to a new socket" : "Create new wire by dragging"; this->grScene->scene->history->storeHistory(desc, VIEW_HIST::CREATE_ITEMS, true); return; } } this->viewport()->unsetCursor(); this->_elementAction = VIEW_A_NOOP; this->lastPressSocket = Q_NULLPTR; if (this->_socketDraggingWire) { this->_socketDraggingWire->remove(); this->_socketDraggingWire = Q_NULLPTR; } } // 拖拽输入端口的wire可移动到其他socket void QDMGraphicsView::wireDragTrans(Socket *socket) { auto curWire = socket->wires[0]; curWire->detachFromSockets(socket); this->_socketDraggingWire = curWire; } // 检查鼠标左键点击释放间距是否大于阈值 bool QDMGraphicsView::lmbClickReleaseDistAway(QMouseEvent *event) { auto new_lmb_ReleaseScenePos = this->mapToScene(event->pos()); auto dragVec = new_lmb_ReleaseScenePos - this->last_LMB_ClickScenePos; auto dragSqr = dragVec.x() * dragVec.x() + dragVec.y() * dragVec.y(); return dragSqr > SCT_DRAG_START_THRESHOLD * SCT_DRAG_START_THRESHOLD; } void QDMGraphicsView::cutIntersectionWires() { auto hit = false; for (size_t ix = 0; ix < this->cutLine->linePoints.size() - 1; ++ix) { auto p1 = this->cutLine->linePoints[ix]; auto p2 = this->cutLine->linePoints[ix + 1]; for (auto &wire : this->grScene->scene->wires) { if (wire->grWire->intersectsWith(p1, p2)) { hit = true; wire->remove(); } } } if (hit) this->grScene->scene->history->storeHistory("Delete cut wires", VIEW_HIST::DELETE_ITEMS, true); }
37.567259
109
0.593048
[ "object" ]
5f467f06b5da89a52979ad1bddd322c9ae6125cf
7,017
cpp
C++
modules/task_2/makarov_a_jacobi_method/jacobi_method.cpp
LioBuitrago/pp_2020_autumn_informatics
1ecc1b5dae978295778176ff11ffe42bedbc602e
[ "BSD-3-Clause" ]
1
2020-11-20T15:05:12.000Z
2020-11-20T15:05:12.000Z
modules/task_2/makarov_a_jacobi_method/jacobi_method.cpp
LioBuitrago/pp_2020_autumn_informatics
1ecc1b5dae978295778176ff11ffe42bedbc602e
[ "BSD-3-Clause" ]
1
2021-02-13T03:00:05.000Z
2021-02-13T03:00:05.000Z
modules/task_2/makarov_a_jacobi_method/jacobi_method.cpp
LioBuitrago/pp_2020_autumn_informatics
1ecc1b5dae978295778176ff11ffe42bedbc602e
[ "BSD-3-Clause" ]
1
2020-10-11T09:11:57.000Z
2020-10-11T09:11:57.000Z
// Copyright 2020 Makarov Alexander #include <mpi.h> #include <vector> #include <random> #include "../../../modules/task_2/makarov_a_jacobi_method/jacobi_method.h" std::vector<double> generate_A(int size) { // diagonally dominant matrix generator if (size <=0) return std::vector<double>(); std::random_device rd; std::mt19937 gen(rd()); std::vector<double> A(size * size); for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) if (i != j) A[i * size + j] = static_cast<double>( static_cast<int>(gen() % 1000) - 500); for (int i = 0; i < size; i++) { double abs_sum = 0; for (int j = 0; j < size; j++) if (i != j) abs_sum += std::fabs(A[i * size + j]); A[i * size + i] = abs_sum + static_cast<double>(gen() % 500); } return A; } std::vector<double> generate_b(int size) { if (size <=0) return std::vector<double>(); std::random_device rd; std::mt19937 gen(rd()); std::vector<double> b(size); for (int i = 0; i < size; i++) b[i] = static_cast<double>( static_cast<int>(gen() % 1000) - 500); return b; } double getMaxDistance(const std::vector<double>& v1, const std::vector<double>& v2) { double max_dist = 0.; for (unsigned int i = 0; i < v1.size(); i++) { double dist = std::fabs(v1[i] - v2[i]); if (dist > max_dist) max_dist = dist; } return max_dist; } double calculateError(const std::vector<double>& A, const std::vector<double>& x, const std::vector<double>& b) { int size = static_cast<int>(x.size()); std::vector<double> Ax(size, 0.); for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) Ax[i] += A[i * size + j] * x[j]; double error = getMaxDistance(Ax, b); return error; } std::vector<double> solveJacobiSequential(const std::vector<double>& A, const std::vector<double>& b) { int iter = 0; int size = static_cast<int>(b.size()); std::vector<double> x(size); std::vector<double> x_prev(b); double error = 0.; do { for (int i = 0; i < size; i++) { x[i] = b[i]; for (int j = 0; j < size; j++) if (i != j) x[i] -= A[i * size + j] * x_prev[j]; x[i] /= A[i * size + i]; } for (int i = 0; i < size; i++) x_prev[i] = x[i]; iter++; error = calculateError(A, x, b); } while (error > epsilon && iter < max_iter); return x; } std::vector<double> solveJacobiParallel(const std::vector<double>& A, const std::vector<double>& b) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int proc_count; MPI_Comm_size(MPI_COMM_WORLD, &proc_count); int size; if (rank == 0) size = static_cast<int>(b.size()); MPI_Bcast(&size, 1, MPI_INT, 0, MPI_COMM_WORLD); // создание коммуникатора без лишних процессов MPI_Comm comm; if (rank < size) { MPI_Comm_split(MPI_COMM_WORLD, 0, rank, &comm); } else { MPI_Comm_split(MPI_COMM_WORLD, MPI_UNDEFINED, rank, &comm); } if (comm != MPI_COMM_NULL) { int new_rank; MPI_Comm_rank(comm, &new_rank); int new_proc_count; MPI_Comm_size(comm, &new_proc_count); // распределение количества строк по процессам int* counts_b = nullptr; int* displs_b = nullptr; int* counts_A = nullptr; int* displs_A = nullptr; if (new_rank == 0) { int delta = size / new_proc_count; int remaind = size % new_proc_count; counts_b = new int[new_proc_count]; displs_b = new int[new_proc_count]; counts_A = new int[new_proc_count]; displs_A = new int[new_proc_count]; for (int i = 0; i < new_proc_count; i++) { counts_b[i] = delta; displs_b[i] = 0; } for (int i = 0; i < remaind; i++) counts_b[i]++; for (int i = 1; i < new_proc_count; i++) displs_b[i] += displs_b[i - 1] + counts_b[i - 1]; for (int i = 0; i < new_proc_count; i++) { counts_A[i] = counts_b[i] * size; displs_A[i] = displs_b[i] * size; } } double error = 0.; int iter = 0; // узнаем сколько получать строк int local_size; MPI_Scatter(counts_b, 1, MPI_INT, &local_size, 1, MPI_INT, 0, comm); std::vector<double> x_global; std::vector<double> x_local(local_size); std::vector<double> x_prev(size); if (rank == 0) { x_global.resize(size); x_prev = b; } // передать/получить элементы b std::vector<double> b_local(local_size); MPI_Scatterv(b.data(), counts_b, displs_b, MPI_DOUBLE, b_local.data(), local_size, MPI_DOUBLE, 0, comm); // передать/получить строки А std::vector<double> A_local(local_size * size); MPI_Scatterv(A.data(), counts_A, displs_A, MPI_DOUBLE, A_local.data(), local_size * size, MPI_DOUBLE, 0, comm); // получить номер первой строки (для диагональных элементов) int first_row_num; MPI_Scatter(displs_b, 1, MPI_INT, &first_row_num, 1, MPI_INT, 0, comm); do { // передать/получить результат предыдущей итерации MPI_Bcast(x_prev.data(), size, MPI_DOUBLE, 0, comm); // обработать свои куски for (int i = 0; i < local_size; i++) { x_local[i] = b_local[i]; for (int j = 0; j < size; j++) if (j != first_row_num + i) x_local[i] -= A_local[i * size + j] * x_prev[j]; x_local[i] /= A_local[i * size + first_row_num + i]; } iter++; // собрать результаты этой итерации MPI_Gatherv(x_local.data(), local_size, MPI_DOUBLE, x_global.data(), counts_b, displs_b, MPI_DOUBLE, 0, comm); if (rank == 0) { for (int i = 0; i < size; i++) x_prev[i] = x_global[i]; error = calculateError(A, x_global, b); } // передать/получить ошибку MPI_Bcast(&error, 1, MPI_DOUBLE, 0, comm); } while (error > epsilon && iter < max_iter); // принять результат от всех процессоров MPI_Comm_free(&comm); if (rank == 0) { delete[] counts_b; delete[] displs_b; delete[] counts_A; delete[] displs_A; } return x_global; } else { return std::vector<double>(); } }
35.261307
79
0.508764
[ "vector" ]
5f4aff76add1c9417042c79afa16557392aeaf4f
1,050
hpp
C++
Outpost/CommodityDeck.hpp
chiendarrendor/AlbertsGameMachine
29855669056bf23666791960dc2e79eab47f6a0b
[ "MIT" ]
null
null
null
Outpost/CommodityDeck.hpp
chiendarrendor/AlbertsGameMachine
29855669056bf23666791960dc2e79eab47f6a0b
[ "MIT" ]
null
null
null
Outpost/CommodityDeck.hpp
chiendarrendor/AlbertsGameMachine
29855669056bf23666791960dc2e79eab47f6a0b
[ "MIT" ]
null
null
null
#include "Serialize.hpp" #include "Commodity.hpp" class CommodityDeck { public: CommodityDeck(); CommodityDeck(CommodityType i_type,int i_megavalue,int i_averagevalue); CommodityDeck(const CommodityDeck &i_right); CommodityDeck &operator=(const CommodityDeck &i_right); int GetDeckSize() const; int GetDiscardSize() const; void ZeroMegaValue(); void AddCards(int i_CardValue,int i_NumCards); Commodity DrawCommodity(bool i_IsMega); void DiscardCommodity(Commodity i_Commodity); bool HasMega() const; int GetMegaValue() const; int GetAverageValue() const; private: friend std::ostream &operator<<(std::ostream &o,const CommodityDeck &i_deck); SERIALIZE_FUNC { SERIALIZE(m_deck); SERIALIZE(m_discard); SERIALIZE(m_ctype); SERIALIZE(m_megavalue); SERIALIZE(m_averagevalue); } std::vector<Commodity> m_deck; std::vector<Commodity> m_discard; CommodityType m_ctype; int m_megavalue; int m_averagevalue; }; std::ostream &operator<<(std::ostream &o,const CommodityDeck &i_deck);
21.875
79
0.741905
[ "vector" ]
5f4ff267c345a586d2d4599e3d24b8d0dbe95548
2,928
cpp
C++
engine/src/Sprite.cpp
CutiaGames/CutiaEngine
b81d9e7a01c7ec6f49d2a94df1a1976ac7634151
[ "MIT" ]
1
2018-05-11T04:11:27.000Z
2018-05-11T04:11:27.000Z
engine/src/Sprite.cpp
CutiaGames/CutiaEngine
b81d9e7a01c7ec6f49d2a94df1a1976ac7634151
[ "MIT" ]
8
2018-05-11T03:15:30.000Z
2018-06-06T18:47:58.000Z
engine/src/Sprite.cpp
CutiaGames/CutiaEngine
b81d9e7a01c7ec6f49d2a94df1a1976ac7634151
[ "MIT" ]
1
2018-05-11T16:28:17.000Z
2018-05-11T16:28:17.000Z
#include "Sprite.hpp" #include "Game.hpp" #include "Resources.hpp" #include "Camera.hpp" Sprite::Sprite(GameObject& associated) : Component(associated) { texture = nullptr; scale = Vec2(1.f, 1.f); } Sprite::Sprite(GameObject& associated, std::string file, int frameCount, float frameTime, float secondsToSelfDestruct) : Sprite(associated) { SetFrameCount(frameCount); SetFrameTime(frameTime); this->currentFrame = 0; this->secondsToSelfDestruct = secondsToSelfDestruct; Open(file); } Sprite::~Sprite() { } void Sprite::Open(string file) { if(texture != nullptr) { SDL_DestroyTexture(texture.get()); } texture = Resources::GetImage(file); SDL_QueryTexture(texture.get(), nullptr, nullptr, &width, &height); SetClip(0, 0, width / frameCount, height); } void Sprite::SetClip(int x, int y, int w, int h) { clipRect = SDL_Rect {x, y, w, h}; } void Sprite::Render() { //SDL_Rect destRect = SDL_Rect {(int)associated.box.x, (int)associated.box.y, clipRect.w, clipRect.h}; //SDL_RenderCopy(Game::GetInstance().GetRenderer(), texture, &clipRect, &destRect); if( !denyCamera ){ Render(associated.box.x - Camera::pos.x, associated.box.y - Camera::pos.y); }else{ Render(associated.box.x, associated.box.y); } } void Sprite::Render(float x, float y) { SDL_Rect destRect = SDL_Rect {(int)x, (int)y, (int)(clipRect.w * scale.x), (int)(clipRect.h * scale.y)}; SDL_RenderCopyEx(Game::GetInstance().GetRenderer(), texture.get(), &clipRect, &destRect, associated.angleDeg, nullptr, SDL_FLIP_NONE); } bool Sprite::Is(std::string type) { return type == "Sprite"; } void Sprite::Update(float dt) { if(secondsToSelfDestruct > 0) { selfDestructCount.Update(dt); if(selfDestructCount.Get() >= secondsToSelfDestruct) { associated.RequestDelete(); } } this->timeElapsed += dt; if(this->timeElapsed > frameTime) { SetFrame(currentFrame + 1); } if(frameCount == currentFrame) { SetFrame(0); } } int Sprite::GetWidth() { return (width * (int)scale.x) / frameCount; } int Sprite::GetHeight() { return height * (int)scale.y; } bool Sprite::IsOpen() { return texture != nullptr; } void Sprite::Start() { } void Sprite::SetScaleX(float scaleX, float scaleY) { if(scaleX > 0.f) { scale.x = scaleX; } if(scaleY > 0.f) { scale.y = scaleY; } associated.box.h = GetHeight(); associated.box.w = GetWidth(); } void Sprite::SetFrame(int frame) { currentFrame = frame; SetClip(frame * GetWidth(), clipRect.y, GetWidth(), GetHeight()); this->timeElapsed = 0.f; } void Sprite::SetFrameCount(int frameCount) { this->frameCount = frameCount; SetFrame(0); associated.box.w = GetWidth(); } void Sprite::SetFrameTime(float frameTime) { this->frameTime = frameTime; }
19.651007
139
0.639686
[ "render" ]
55046835167ff1e8d778ebb795892f439e0bab6a
3,813
hpp
C++
nd/src/Operators.hpp
Steve132/ndarray
33962eefc5b7bb031c70b5de8c81365e2638b5f6
[ "MIT" ]
null
null
null
nd/src/Operators.hpp
Steve132/ndarray
33962eefc5b7bb031c70b5de8c81365e2638b5f6
[ "MIT" ]
null
null
null
nd/src/Operators.hpp
Steve132/ndarray
33962eefc5b7bb031c70b5de8c81365e2638b5f6
[ "MIT" ]
null
null
null
#ifndef NDARRAY_SRC_OPERATORS_HPP #define NDARRAY_SRC_OPERATORS_HPP #include<type_traits> #include<iostream> namespace nd { template<class ArrayClass,typename std::enable_if<ArrayClass::num_dimensions==1,int>::type = 0> std::ostream& operator<<(std::ostream& out,const ArrayClass& arr) { for(size_t i=0;i<arr.shape(0);i++) out << arr(i) << "\n"; return out; } template<class ArrayClass,typename std::enable_if<ArrayClass::num_dimensions==2,int>::type = 0> std::ostream& operator<<(std::ostream& out,const ArrayClass& arr) { for(size_t i=0;i<arr.shape(0);i++) { for(size_t j=0;j<arr.shape(1);j++) out << arr(i,j) << " "; out << "\n"; } return out; } /* namespace impl { template<class ArrayClass,unsigned int DI,typename std::enable_if<DI==0,int>::type = 0> static void print_recursive(std::ostream& out,const ArrayClass& arr) { for(size_t i=0;i<arr.shape(0);i++) out << arr(i) << " "; } } template<class ArrayClass,typename std::enable_if<(ArrayClass::num_dimensions > 2),int>::type = 0> std::ostream& operator<<(std::ostream& out,const ArrayClass& arr) { for(size_t i=0;i<arr.shape(ArrayClass::num_dimensions-1);i++) { auto outmap=arr.pop_order_ref(i); //TODO this doesn't work because the whole thing is implemented bizarrely out << "Dim[" << ArrayClass::num_dimensions-1 << "]=" << i << "\n"; out << outmap; } return out; }*/ //external values because SFNIAE for operator selection. #define BINARY_OPERATOR_TEMPLATE( XXX ) \ template<class V,unsigned int D,class StG,class V2,class StG2> \ auto operator XXX(const Array<V,D,StG>& a,const Array<V2,D,StG2>& b) \ ->Array<decltype(a[0] XXX b[0]),D,StG> \ { \ return a.elementWise([](const V& v1,const V2& v2){ return v1 XXX v2; },b); \ } \ template<class V,unsigned int D,class StG,class TypeB> \ auto operator XXX(const Array<V,D,StG>& a,const TypeB& b) \ -> Array<decltype(a[0] XXX b),D,StG> \ { \ return a.elementWise([&b](const V& v1){ return v1 XXX b; }); \ } \ template<class V,unsigned int D,class StG,class TypeB> \ auto operator XXX(const TypeB& b,const Array<V,D,StG>& a) \ -> Array<decltype(b XXX a[0]),D,StG> \ { \ return a.elementWise([&b](const V& v1){ return b XXX v1; }); \ } \ BINARY_OPERATOR_TEMPLATE(*) BINARY_OPERATOR_TEMPLATE(/) BINARY_OPERATOR_TEMPLATE(%) BINARY_OPERATOR_TEMPLATE(+) BINARY_OPERATOR_TEMPLATE(-) BINARY_OPERATOR_TEMPLATE(<<) BINARY_OPERATOR_TEMPLATE(>>) BINARY_OPERATOR_TEMPLATE(<) BINARY_OPERATOR_TEMPLATE(>) BINARY_OPERATOR_TEMPLATE(<=) BINARY_OPERATOR_TEMPLATE(>=) BINARY_OPERATOR_TEMPLATE(==) BINARY_OPERATOR_TEMPLATE(!=) BINARY_OPERATOR_TEMPLATE(&) BINARY_OPERATOR_TEMPLATE(|) BINARY_OPERATOR_TEMPLATE(^) BINARY_OPERATOR_TEMPLATE(&&) BINARY_OPERATOR_TEMPLATE(||) #define UNARY_OPERATOR_TEMPLATE( XXX ) \ template<class V,unsigned int D, class StG> \ auto operator XXX(const Array<V,D,StG>& a) \ ->Array<decltype(XXX(a[0])),D,StG> \ { \ return a.elementWise([](const V& v1){ return XXX(v1); }); \ } \ UNARY_OPERATOR_TEMPLATE(~) UNARY_OPERATOR_TEMPLATE(!) UNARY_OPERATOR_TEMPLATE(-) UNARY_OPERATOR_TEMPLATE(+) #define INPLACE_OPERATOR_TEMPLATE( XXX ) \ template<class V,unsigned int D,class StG,class V2, class StG2> \ auto operator XXX(Array<V,D,StG>& a,const Array<V2,D,StG2>& b) \ ->Array<V,D,StG>& \ { \ return a.elementWiseInPlace([](V& v1,const V2& v2){ v1 XXX v2; },b); \ } \ template<class V,unsigned int D,class StG,class TypeB> \ auto operator XXX(Array<V,D,StG>& a,const TypeB& b) \ -> Array<V,D,StG>& \ { \ return a.elementWiseInPlace([&b](V& v1){ v1 XXX b; }); \ } \ INPLACE_OPERATOR_TEMPLATE(*=) INPLACE_OPERATOR_TEMPLATE(/=) INPLACE_OPERATOR_TEMPLATE(+=) INPLACE_OPERATOR_TEMPLATE(-=) INPLACE_OPERATOR_TEMPLATE(>>=) INPLACE_OPERATOR_TEMPLATE(<<=) INPLACE_OPERATOR_TEMPLATE(&=) INPLACE_OPERATOR_TEMPLATE(^=) INPLACE_OPERATOR_TEMPLATE(|=) //TODO: ++,-- } #endif
28.669173
109
0.709415
[ "shape" ]
550546946916acbaba706ae18a55bbb14bc6fd22
38,445
cpp
C++
imgui_nodes.cpp
pborsutzki/imgui-nodes
51146bd146b6dfbae51e662731a1a1d7a52d1534
[ "BSD-3-Clause" ]
10
2018-01-27T19:01:04.000Z
2021-11-04T19:22:10.000Z
imgui_nodes.cpp
pborsutzki/imgui-nodes
51146bd146b6dfbae51e662731a1a1d7a52d1534
[ "BSD-3-Clause" ]
null
null
null
imgui_nodes.cpp
pborsutzki/imgui-nodes
51146bd146b6dfbae51e662731a1a1d7a52d1534
[ "BSD-3-Clause" ]
3
2019-11-24T07:57:06.000Z
2020-11-26T11:47:50.000Z
#include "imgui_nodes.hpp" #include <imgui.h> #ifndef IMGUI_DEFINE_MATH_OPERATORS #define IMGUI_DEFINE_MATH_OPERATORS #endif // IMGUI_DEFINE_MATH_OPERATORS //#define IMGUI_ANTIALIASFRINGESCALE #include <imgui_internal.h> #include <math.h> #include <vector> #include <array> #include <algorithm> #include "cubicSpline/CubicSpline.h" #include <sstream> std::stringstream debug; namespace nodes { namespace { // from imgui.cpp static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true) { const int key_index = GImGui->IO.KeyMap[key]; return (key_index >= 0) ? ImGui::IsKeyPressed(key_index, repeat) : false; } inline ImVec2 operator+(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x + rhs, lhs.y + rhs); } inline ImVec2 operator-(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x - rhs, lhs.y - rhs); } inline bool operator==(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } inline bool operator!=(const ImVec2& lhs, const ImVec2& rhs) { return !(lhs == rhs); } inline ImVec2 operator-(const ImVec2& lhs) { return ImVec2(-lhs.x, -lhs.y); } inline float ImVec2Dot(const ImVec2& S1, const ImVec2& S2) { return (S1.x*S2.x + S1.y*S2.y); } float distanceToBezierSquared(const ImVec2& point, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4) { static CubicSplineTest::ClosestPointSolver staticSolver; std::array<CubicSplineTest::WorldSpace, 4> cp = { { { p1.x, p1.y }, { p2.x, p2.y }, { p3.x, p3.y }, { p4.x, p4.y } } }; CubicSplineTest::CubicBezierPath path(cp.data(), (int)cp.size()); CubicSplineTest::WorldSpace closestws = path.ClosestPointToPath({ point.x, point.y }, &staticSolver); ImVec2 closest(closestws.x, closestws.y); return ImLengthSqr(point - closest); } bool closeToBezier(const ImVec2& point, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, float maxDist) { ImRect aabb; aabb.Add(p1); aabb.Add(p2); aabb.Add(p3); aabb.Add(p4); aabb.Expand(maxDist); if (aabb.Contains(point)) { float d = distanceToBezierSquared(point, p1, p2, p3, p4); return d < maxDist * maxDist; } return false; } template <typename T> int sgn(T val) { return (T(0) < val) - (val < T(0)); } /*based on http://mysite.verizon.net/res148h4j/javascript/script_exact_cubic.html#the%20source%20code */ std::array<float, 3> cubicRoots(ImVec4 const &P) { float A = P.y / P.x; float B = P.z / P.x; float C = P.w / P.x; float Q = (3.f * B - pow(A, 2.f)) / 9.f; float R = (9.f * A*B - 27.f * C - 2.f * pow(A, 3.f)) / 54.f; float D = pow(Q, 3.f) + pow(R, 2.f); // polynomial discriminant std::array<float, 3> t; if (D >= 0) // complex or duplicate roots { float S = sgn(R + sqrt(D))*pow(abs(R + sqrt(D)), (1.f / 3.f)); float T = sgn(R - sqrt(D))*pow(abs(R - sqrt(D)), (1.f / 3.f)); t[0] = -A / 3.f + (S + T); // real root t[1] = -A / 3.f - (S + T) / 2.f; // real part of complex root t[2] = -A / 3.f - (S + T) / 2.f; // real part of complex root float Im = abs(sqrt(3.f)*(S - T) / 2.f); // complex part of root pair /*discard complex roots*/ if (Im != 0.f) { t[1] = -1.f; t[2] = -1.f; } } else // distinct real roots { float th = acos(R / sqrt(-pow(Q, 3.f))); t[0] = 2.f * sqrt(-Q)*cos(th / 3.f) - A / 3.f; t[1] = 2.f * sqrt(-Q)*cos((th + 2.f * IM_PI) / 3.f) - A / 3.f; t[2] = 2.f * sqrt(-Q)*cos((th + 4.f * IM_PI) / 3.f) - A / 3.f; } return t; } // From https://www.particleincell.com/2013/cubic-line-intersection/ bool IntersectBezierAndLine(ImVec2 const &a, ImVec2 const &b, ImVec2 const &p0, ImVec2 const &p1, ImVec2 const &p2, ImVec2 const &p3) { auto bezierCoeffs = [](float p0, float p1, float p2, float p3) { std::array<float, 4> result; result[0] = -p0 + 3.f * p1 + -3.f * p2 + p3; result[1] = 3.f * p0 - 6.f * p1 + 3.f * p2; result[2] = -3.f * p0 + 3.f * p1; result[3] = p0; return result; }; float A = b.y - a.y; //A=y2-y1 float B = a.x - b.x; //B=x1-x2 float C = a.x * (a.y - b.y) + a.y * (b.x - a.x); //C=x1*(y1-y2)+y1*(x2-x1) if (A == 0.f && B == 0.f && C == 0.f) { return false; } std::array<float, 4> bx = bezierCoeffs(p0.x, p1.x, p2.x, p3.x); std::array<float, 4> by = bezierCoeffs(p0.y, p1.y, p2.y, p3.y); ImVec4 P; P.x = A*bx[0] + B*by[0]; /*t^3*/ P.y = A*bx[1] + B*by[1]; /*t^2*/ P.z = A*bx[2] + B*by[2]; /*t*/ P.w = A*bx[3] + B*by[3] + C; /*1*/ std::array<float, 3> r = cubicRoots(P); /*verify the roots are in bounds of the linear segment*/ for (int i = 0; i < 3; ++i) { float t = r[i]; if (t < 0.f || t > 1.f) { continue; } ImVec2 X; X.x = bx[0] * t*t*t + bx[1] * t*t + bx[2] * t + bx[3]; X.y = by[0] * t*t*t + by[1] * t*t + by[2] * t + by[3]; /*above is intersection point assuming infinitely long line segment, make sure we are also in bounds of the line*/ float s; if ((b.x - a.x) != 0) /*if not vertical line*/ s = (X.x - a.x) / (b.x - a.x); else s = (X.y - a.y) / (b.y - a.y); /*in bounds?*/ if (s >= 0.f && s <= 1.f) { // X is intersection point return true; } } return false; } bool isInSelectedRect(NodeArea &area, ImRect rect) { ImRect selectionRect; selectionRect.Add(area.state.dragStart); selectionRect.Add(area.state.dragEnd); if (ImGui::GetIO().KeyAlt) { return selectionRect.Contains(rect); } else { return selectionRect.Overlaps(rect); } } bool handleNodeDragSelection(NodeArea &area, int nodeId, ImRect rect) { if (isInSelectedRect(area, rect)) { if (area.state.mode == NodeArea::Mode::SelectionCaptureAdd) { area.state.selectedNodes.addToSelection(nodeId); } else if (area.state.mode == NodeArea::Mode::SelectionCaptureRemove) { area.state.selectedNodes.removeFromSelection(nodeId); } return area.state.mode == NodeArea::Mode::Selecting; } return false; } bool handleConnectorDragSelection(NodeArea &area, int connectorId, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4) { if (area.state.mode != NodeArea::Mode::None) { ImRect selectionRect; selectionRect.Add(area.state.dragStart); selectionRect.Add(area.state.dragEnd); bool contained = selectionRect.Contains(p1) && selectionRect.Contains(p4); if (!contained && !ImGui::GetIO().KeyAlt) { ImVec2 q0 = selectionRect.Min; ImVec2 q1 = ImVec2(selectionRect.Max.x, selectionRect.Min.y); ImVec2 q2 = ImVec2(selectionRect.Min.x, selectionRect.Max.y); ImVec2 q3 = selectionRect.Max; contained = IntersectBezierAndLine(q0, q1, p1, p2, p3, p4) || IntersectBezierAndLine(q0, q2, p1, p2, p3, p4) || IntersectBezierAndLine(q3, q1, p1, p2, p3, p4) || IntersectBezierAndLine(q3, q2, p1, p2, p3, p4); } if (contained) { if (area.state.mode == NodeArea::Mode::SelectionCaptureAdd) { area.state.selectedLinks.addToSelection(connectorId); } else if (area.state.mode == NodeArea::Mode::SelectionCaptureRemove) { area.state.selectedLinks.removeFromSelection(connectorId); } return area.state.mode == NodeArea::Mode::Selecting; } } return false; } ImGuiContext* setupInnerContext(ImGuiContext* outerContext) { ImGuiContext *innerContext = ImGui::CreateContext(outerContext->IO.MemAllocFn, outerContext->IO.MemFreeFn); memcpy(innerContext->IO.KeyMap, outerContext->IO.KeyMap, ImGuiKey_COUNT * sizeof(int)); innerContext->IO.RenderDrawListsFn = nullptr; innerContext->IO.SetClipboardTextFn = outerContext->IO.SetClipboardTextFn; innerContext->IO.GetClipboardTextFn = outerContext->IO.GetClipboardTextFn; innerContext->IO.ClipboardUserData = outerContext->IO.ClipboardUserData; innerContext->IO.ImeWindowHandle = outerContext->IO.ImeWindowHandle; innerContext->Style = outerContext->Style; return innerContext; } void innerContextNewFrame(ImGuiContext const* outerContext, ImGuiContext* innerContext, float scale, ImGuiIO& outerIo, ImVec2 outerWindowSize, ImVec2 outerWindowPos, bool active, bool hovered) { ImGuiIO& innerIo = innerContext->IO; innerIo.DisplaySize = outerWindowSize; innerIo.DisplayFramebufferScale = ImVec2(1.0f, 1.0f); innerIo.DeltaTime = outerIo.DeltaTime; if (active || hovered) { innerIo.MousePos = (outerIo.MousePos - outerWindowPos) / scale; } for (int i = 0; i < 3; i++) { if (active || !active && innerIo.MouseDown[i]) { innerIo.MouseDown[i] = outerIo.MouseDown[i]; } } if (active) { innerIo.MouseWheel = outerIo.MouseWheel; memcpy(innerContext->IO.KeysDown, outerContext->IO.KeysDown, sizeof(outerContext->IO.KeysDown)); memcpy(innerContext->IO.InputCharacters, outerContext->IO.InputCharacters, sizeof(outerContext->IO.InputCharacters)); } else { innerIo.MouseWheel = 0.f; memset(innerContext->IO.KeysDown, 0, sizeof(innerContext->IO.KeysDown)); memset(innerContext->IO.InputCharacters, 0, sizeof(innerContext->IO.InputCharacters)); } innerContext->IO.KeyCtrl = outerContext->IO.KeyCtrl; innerContext->IO.KeyShift = outerContext->IO.KeyShift; innerContext->IO.KeyAlt = outerContext->IO.KeyAlt; innerContext->IO.KeySuper = outerContext->IO.KeySuper; } void copyTransformDrawList(ImDrawList *targetDrawList, ImDrawList *sourceDrawList, ImVec2 scale = ImVec2(1.f, 1.f), ImVec2 translate = {}) { ImRect targetClip(targetDrawList->_ClipRectStack.back()); int indexBase = targetDrawList->_VtxCurrentIdx; targetDrawList->PrimReserve(0, sourceDrawList->VtxBuffer.size()); for (int vtx = 0; vtx < sourceDrawList->VtxBuffer.size(); ++vtx) { auto const& vertex = sourceDrawList->VtxBuffer[vtx]; targetDrawList->PrimWriteVtx(vertex.pos * scale + translate, vertex.uv, vertex.col); } int sourceIdx = 0; for (int dc = 0; dc < sourceDrawList->CmdBuffer.size(); ++dc) { targetDrawList->CmdBuffer.resize(targetDrawList->CmdBuffer.size() + 1); ImDrawCmd const &sourceDrawCmd = sourceDrawList->CmdBuffer[dc]; targetDrawList->CmdBuffer.back() = sourceDrawCmd; targetDrawList->CmdBuffer.back().ElemCount = 0; targetDrawList->PrimReserve(sourceDrawCmd.ElemCount, 0); for (unsigned int idx = 0; idx < sourceDrawCmd.ElemCount; ++idx, ++sourceIdx) { targetDrawList->PrimWriteIdx((ImDrawIdx)(sourceDrawList->IdxBuffer[sourceIdx] + indexBase)); } ImVec2 clipRectMin(sourceDrawCmd.ClipRect.x, sourceDrawCmd.ClipRect.y); ImVec2 clipRectMax(sourceDrawCmd.ClipRect.z, sourceDrawCmd.ClipRect.w); ImRect clipRect(clipRectMin * scale + translate, clipRectMax * scale + translate); clipRect.ClipWith(targetClip); targetDrawList->CmdBuffer.back().ClipRect = ImVec4(clipRect.Min.x, clipRect.Min.y, clipRect.Max.x, clipRect.Max.y); } } // Copies all the draw call, vertex and index data from the inner imgui context to our current draw list: // * Translate and scale the vertices and clip rects accordingly // * Rebases the indices to fit into the outer index buffer // * Reclips the clip rects to our outer clip rect void copyTransformDrawCmds(ImDrawData* sourceDrawData, ImVec2 scale, ImVec2 translate) { ImDrawList *targetDrawList = ImGui::GetWindowDrawList(); for (int i = 0; i < sourceDrawData->CmdListsCount; ++i) { ImDrawList *sourceDrawList = sourceDrawData->CmdLists[i]; copyTransformDrawList(targetDrawList, sourceDrawList, scale, translate); } // make sure no one messes with our copied draw calls targetDrawList->AddDrawCmd(); } void switchCurrentDrawList(ImDrawList *newList) { ImGuiWindow* wnd = ImGui::GetCurrentWindow(); wnd->DrawList = newList; } bool WasItemActive() { ImGuiContext& g = *GImGui; if (g.ActiveIdPreviousFrame) { ImGuiWindow* window = g.CurrentWindow; return g.ActiveIdPreviousFrame == window->DC.LastItemId; } return false; } void paintGrid(Style const &style) { if (style.gridSpacing <= 0.f) { return; } // Uses the current clip rects extent for painting. This allows for large node areas, // without the performance loss of emitting grid lines that end up culled. ImDrawList* draw_list = ImGui::GetWindowDrawList(); ImVec4 clipRect = draw_list->_ClipRectStack[draw_list->_ClipRectStack.size() - 1]; ImVec2 windowPos = ImGui::GetWindowPos(); int repx = (int)(abs(windowPos.x) / style.gridSpacing); for (float x = clipRect.x + fmodf(windowPos.x, style.gridSpacing); x < clipRect.z; (x += style.gridSpacing), ++repx) { for (auto const &grid : style.grid) { if (repx % grid.spacingMultiplier == 0) { draw_list->AddLine(ImVec2(x, clipRect.y - 1.f), ImVec2(x, clipRect.w + 1.f), grid.lineColor, grid.thickness); break; } } } int repy = (int)(abs(windowPos.y) / style.gridSpacing); for (float y = clipRect.y + fmodf(windowPos.y, style.gridSpacing); y < clipRect.w; (y += style.gridSpacing), ++repy) { for (auto const &grid : style.grid) { if (repy % grid.spacingMultiplier == 0) { draw_list->AddLine(ImVec2(clipRect.x - 1.f, y), ImVec2(clipRect.z + 1.f, y), grid.lineColor, grid.thickness); break; } } } } } // anonymous namespace void NodeArea::Selection::clearSelection() { selectedItems.clear(); selectedCount = 0; } void NodeArea::Selection::addToSelection(int id) { IM_ASSERT(id >= 0); if (id >= (int)selectedItems.size()) { selectedItems.resize(id + 1); } if (!selectedItems[id]) { selectedItems[id] = true; ++selectedCount; } } void NodeArea::Selection::removeFromSelection(int id) { IM_ASSERT(id >= 0); if (id >= (int)selectedItems.size()) { return; } if (selectedItems[id]) { selectedItems[id] = false; --selectedCount; } } void NodeArea::Selection::toggleSelection(int id) { if (isSelected(id)) { removeFromSelection(id); } else { addToSelection(id); } } bool NodeArea::Selection::isSelected(int id) const { if (id >= (int)selectedItems.size()) { return false; } return selectedItems[id]; } void NodeArea::BeginNodeArea(std::function<void(UserAction)> actionCallback, bool updateStyle) { state.outerContext = ImGui::GetCurrentContext(); if (!state.initialized) { state.zoom = 1.f; state.innerWndPos = -state.nodeAreaSize / 2.f + ImGui::GetWindowSize() / 2.f; state.mode = Mode::None; state.scrolling = false; state.innerContext = setupInnerContext(state.outerContext); state.initialized = true; } if (updateStyle) { state.innerContext->Style = state.outerContext->Style; } debug.str(""); debug.clear(); ImVec2 windowSize = ImGui::GetWindowSize() / state.zoom; ImVec2 windowPos = ImGui::GetWindowPos(); ImGuiIO& outerIo = ImGui::GetIO(); bool outerWindowHovered = ImGui::IsWindowHovered(); if (outerWindowHovered) { for (int i = 0; i < IM_ARRAYSIZE(outerIo.MouseDown); ++i) { if (outerIo.MouseDown[i] && !ImGui::IsMouseDragging(i)) { ImGui::SetWindowFocus(); break; } } } bool setWindowPos = false; state.outerWindowFocused = ImGui::IsWindowFocused(); state.outerWindowHovered = ImGui::IsWindowHovered(); if (state.outerWindowFocused && state.hoveredNode == -1 && ImGui::IsKeyReleased(outerIo.KeyMap[ImGuiKey_Home])) { state.zoom = 1.f; state.innerWndPos = -state.nodeAreaSize / 2.f + ImGui::GetWindowSize() / 2.f; setWindowPos = true; } if (state.outerWindowFocused && state.hoveredNode == -1 && outerIo.MouseWheel != 0.f) { const float factor = 1.25f; float newZoom = outerIo.MouseWheel > 0 ? (state.zoom * factor) : (state.zoom / factor); if (newZoom > 0.15f && newZoom < 16.f) { //ImVec2 pos = ImGui::GetWindowSize() / 2.f; // zoom to window center ImVec2 pos = outerIo.MousePos - ImGui::GetWindowPos(); // zoom to mouse position state.innerWndPos = (pos * state.zoom - pos * newZoom + state.innerWndPos * newZoom * state.zoom) / (newZoom * state.zoom); setWindowPos = true; state.zoom = newZoom; } } ImGui::SetCurrentContext(state.innerContext); innerContextNewFrame(state.outerContext, state.innerContext, state.zoom, outerIo, windowSize, windowPos, state.outerWindowFocused, state.outerWindowHovered); ImGui::NewFrame(); debug << "BeginNodeArea " << ImGui::IsAnyItemActive() << std::endl; #ifdef IMGUI_ANTIALIASFRINGESCALE ImGui::PushStyleVar(ImGuiStyleVar_AntiAliasFringeScale, state.innerContext->Style.AntiAliasFringeScale / state.zoom); #endif ImGui::SetNextWindowPos(state.innerWndPos, setWindowPos ? ImGuiSetCond_Always : ImGuiSetCond_Once); ImGui::SetNextWindowSize(state.nodeAreaSize); ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4()); ImGui::Begin("node_graph", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar); // Avoids early clipping when zoomed in ImGui::PushClipRect(ImVec2(-1.f, -1.f), ImVec2(windowSize) + ImVec2(1.f, 1.f), false); // Window movement if (state.outerWindowFocused && ImGui::IsWindowHovered() && !ImGui::IsAnyItemHovered() && ImGui::IsMouseDown(2) && !ImGui::IsMouseDragging(2, 1.0f)) { state.scrolling = true; } if (state.outerWindowFocused && state.scrolling && ImGui::IsMouseDragging(2, 0.0f)) { ImGui::ClearActiveID(); ImGui::SetWindowPos(ImGui::GetCurrentWindowRead()->PosFloat + ImGui::GetIO().MouseDelta); } else { state.scrolling = false; } if (state.outerWindowFocused) { // Selection cruft switch (state.mode) { case Mode::SelectionCaptureAdd: case Mode::SelectionCaptureRemove: state.mode = Mode::None; break; case Mode::Selecting: { if (ImGui::IsKeyPressed(ImGui::GetIO().KeyMap[ImGuiKey_Escape])) { state.mode = Mode::Escaped; break; } if (ImGui::IsMouseReleased(0)) { state.mode = Mode::SelectionCaptureAdd; if (!ImGui::GetIO().KeyShift) { clearAllSelections(); } if (ImGui::GetIO().KeyShift && ImGui::GetIO().KeyCtrl) { state.mode = Mode::SelectionCaptureRemove; } } break; } case Mode::None: { if (ImGui::IsWindowHovered() && !ImGui::IsAnyItemActive() && state.hoveredNode == -1 && state.hoveredLink == -1) { if (ImGui::IsMouseDown(0) && !ImGui::IsMouseDragging(0, 1.0f)) { state.dragStart = ImGui::GetMousePos() - ImGui::GetWindowPos(); state.mode = Mode::Selecting; } else if (ImGui::IsMouseReleased(0)) { clearAllSelections(); } } break; } } if (state.mode == Mode::Selecting || state.mode == Mode::DraggingConnectorInput || state.mode == Mode::DraggingConnectorOutput) { state.dragEnd = ImGui::GetMousePos() - ImGui::GetWindowPos(); } if (state.mode == Mode::DraggingConnectorInput || state.mode == Mode::DraggingConnectorOutput) { if (ImGui::IsMouseReleased(0) && state.connectorStartNode != state.connectorEndNode && ((state.connectorStartNode != -1 && state.connectorStartSlot != -1) || (state.connectorEndNode != -1 && state.connectorEndSlot != -1))) { actionCallback(UserAction::NewConnection); state.mode = Mode::None; } else if (ImGui::IsMouseReleased(0) || ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Escape))) { state.mode = Mode::None; } } if (!ImGui::IsAnyItemActive()) { ImGuiIO const& io = ImGui::GetIO(); // from imgui.cpp const bool is_shortcut_key_only = (io.OptMacOSXBehaviors ? (io.KeySuper && !io.KeyCtrl) : (io.KeyCtrl && !io.KeySuper)) && !io.KeyAlt && !io.KeyShift; // OS X style: Shortcuts using Cmd/Super instead of Ctrl if (is_shortcut_key_only) { if (IsKeyPressedMap(ImGuiKey_X)) { actionCallback(UserAction::Cut); } else if (IsKeyPressedMap(ImGuiKey_C)) { actionCallback(UserAction::Copy); } else if (IsKeyPressedMap(ImGuiKey_V)) { actionCallback(UserAction::Paste); } else if (IsKeyPressedMap(ImGuiKey_Z)) { actionCallback(UserAction::Undo); } else if (IsKeyPressedMap(ImGuiKey_Y)) { actionCallback(UserAction::Redo); } else if (IsKeyPressedMap(ImGuiKey_A) && state.mode == Mode::None) { state.mode = Mode::SelectAll; } } if (IsKeyPressedMap(ImGuiKey_Delete)) { actionCallback(UserAction::Delete); } } } ImVec2 unclampedPos = ImGui::GetCurrentWindowRead()->PosFloat; ImVec2 clampedPos = ImClamp(unclampedPos, -ImGui::GetWindowSize() + windowSize, ImVec2()); if (unclampedPos != clampedPos) { ImGui::SetWindowPos(clampedPos); } paintGrid(style); if (ImGui::IsWindowHovered()/* && !ImGui::IsAnyItemHovered()*/) { state.activeNode = -1; state.hoveredNode = -1; state.hoveredLink = -1; state.connectorEndNode = -1; state.connectorEndSlot = -1; } ImGuiWindow* wnd = ImGui::GetCurrentWindow(); state.windowDrawList = wnd->DrawList; state.nodeDrawList.Clear(); state.nodeDrawList.PushClipRect(state.windowDrawList->GetClipRectMin(), state.windowDrawList->GetClipRectMax()); state.nodeDrawList.PushTextureID(state.windowDrawList->_TextureIdStack.back()); state.overlayDrawList.Clear(); state.overlayDrawList.PushClipRect(state.windowDrawList->GetClipRectMin(), state.windowDrawList->GetClipRectMax()); state.overlayDrawList.PushTextureID(state.windowDrawList->_TextureIdStack.back()); debug << "BeginNodeArea " << ImGui::IsAnyItemActive() << " scrolling " << state.scrolling << std::endl; } void NodeArea::EndNodeArea() { debug << "EndNodeArea " << ImGui::IsAnyItemActive() << std::endl; copyTransformDrawList(state.windowDrawList, &state.nodeDrawList); copyTransformDrawList(state.windowDrawList, &state.overlayDrawList); switch (state.mode) { case Mode::DraggingNodes: case Mode::Escaped: if (ImGui::IsMouseReleased(0)) { state.mode = Mode::None; } break; case Mode::None: if (state.activeNode != -1 && ImGui::IsMouseDragging(0)) { if (!state.selectedNodes.isSelected(state.activeNode) || state.selectedNodes.selectedCount == 0) { state.selectedLinks.clearSelection(); state.selectedNodes.clearSelection(); state.selectedNodes.addToSelection(state.activeNode); } state.mode = Mode::DraggingNodes; } break; case Mode::SelectAll: state.mode = Mode::None; break; } if (state.mode == Mode::Selecting) { ImDrawList *draw_list = ImGui::GetWindowDrawList(); ImVec2 offset = ImGui::GetWindowPos(); draw_list->AddRectFilled(offset + state.dragStart, offset + state.dragEnd, style.selectionFill); draw_list->AddRect(offset + state.dragStart, offset + state.dragEnd, style.selectionBorder); } if (state.mode == Mode::DraggingConnectorInput || state.mode == Mode::DraggingConnectorOutput) { ImDrawList *draw_list = ImGui::GetWindowDrawList(); ImVec2 offset = ImGui::GetWindowPos(); ImVec2 p1 = offset + (state.mode == Mode::DraggingConnectorInput ? state.dragStart : state.dragEnd); ImVec2 cp1 = p1 + ImVec2(+50, 0); ImVec2 p2 = offset + (state.mode == Mode::DraggingConnectorInput ? state.dragEnd : state.dragStart); ImVec2 cp2 = p2 + ImVec2(-50, 0); draw_list->AddBezierCurve(p1, cp1, cp2, p2, style.connectorDragging, style.connectorDraggingSize); } state.innerWndPos = ImGui::GetCurrentWindowRead()->PosFloat; ImGui::PopClipRect(); ImGui::End(); ImGui::PopStyleColor(); #ifdef IMGUI_ANTIALIASFRINGESCALE ImGui::PopStyleVar(); #endif ImGui::Render(); ImDrawData* innerDrawData = ImGui::GetDrawData(); IM_ASSERT(innerDrawData->Valid); ImGui::SetCurrentContext(state.outerContext); // ImGui snaps geometry to whole pixels. This leads to jaggy movement when zooming in. // We fix this by translating by the fract of the exact position. // This is also why we push a one pixel bigger clip-rect than usually necessary. ImVec2 fractInnerWndPos( floor(fmodf(state.innerWndPos.x, 1.f) * state.zoom), floor(fmodf(state.innerWndPos.y, 1.f) * state.zoom)); ImVec2 translate = state.outerContext->CurrentWindow->PosFloat + fractInnerWndPos; ImVec2 scale = ImVec2(state.zoom, state.zoom); copyTransformDrawCmds(innerDrawData, scale, translate); debug << "active node " << state.activeNode << std::endl; ImGui::SetCursorPos(ImVec2(10.f, 5.f)); ImGui::Text("x %.2f, y %.2f\nz %.2f\n%s", state.innerWndPos.x, state.innerWndPos.y, state.zoom, debug.str().c_str()); } bool NodeArea::BeginNode(NodeState &node) { ImGui::PushID(&node); node.inputSlots.resize(0); node.outputSlots.resize(0); bool selected = state.selectedNodes.isSelected(node.id); // put nodes into a separate draw list so we can paint them on top // of connectors if (selected) { switchCurrentDrawList(&state.overlayDrawList); } else { switchCurrentDrawList(&state.nodeDrawList); } ImDrawList* draw_list = ImGui::GetWindowDrawList(); draw_list->ChannelsSplit(3); draw_list->ChannelsSetCurrent(2); ImGui::PushItemWidth(150.f); ImGui::SetCursorPos(node.pos + style.nodePadding); ImGui::BeginGroup(); // Lock horizontal position debug << "BeginNode " << node.id << " " << ImGui::IsAnyItemActive() << std::endl; return true; } void NodeArea::EndNode(NodeState &node, bool resizable) { debug << "EndNode " << node.id << " " << ImGui::IsAnyItemActive() << std::endl; ImGui::EndGroup(); ImGui::PopItemWidth(); ImVec2 offset = ImGui::GetWindowPos(); if (!resizable || node.size.x < 0.f) { node.size = ImGui::GetItemRectSize() + style.nodePadding * 2.f; } const float window_rounding = style.nodeRounding; const float resize_corner_size = ImMax(state.innerContext->FontSize * 1.35f, window_rounding + 1.0f + state.innerContext->FontSize * 0.2f); const ImVec2 br = offset + node.pos + node.size; ImU32 resize_col = 0; if (resizable) { const ImRect resize_rect(br - ImFloor(ImVec2(resize_corner_size * 0.75f, resize_corner_size * 0.75f)), br); const ImGuiID resize_id = ImGui::GetID(&node); bool resizeHovered, resizeHeld; ImGui::ButtonBehavior(resize_rect, resize_id, &resizeHovered, &resizeHeld, ImGuiButtonFlags_FlattenChilds); resize_col = ImGui::GetColorU32(resizeHeld ? ImGuiCol_ResizeGripActive : resizeHovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); if (resizeHeld && (state.mode == Mode::None || state.mode == Mode::ResizingNode)) { state.mode = Mode::ResizingNode; node.size += ImGui::GetIO().MouseDelta; } else if (!resizeHeld && state.mode == Mode::ResizingNode) { state.mode = Mode::None; } } ImDrawList* draw_list = ImGui::GetWindowDrawList(); draw_list->ChannelsSetCurrent(0); ImGui::SetCursorPos(node.pos); ImGui::InvisibleButton("node", node.size); bool itemActive = state.outerWindowFocused && ImGui::IsItemActive(); bool itemWasActive = state.outerWindowFocused && WasItemActive(); ImU32 nodeBg = style.nodeFill; ImU32 nodeBorder = style.nodeBorder; bool hovered = state.outerWindowHovered && ImGui::IsItemHovered(); if (state.mode == Mode::SelectAll) { state.selectedNodes.addToSelection(node.id); } if (itemWasActive && ImGui::IsMouseReleased(0) && state.mode == Mode::None) { if (ImGui::GetIO().KeyShift) { state.selectedNodes.toggleSelection(node.id); } else { // Allows selection of nodes with a simple click. // Clears other selections. clearAllSelections(); state.selectedNodes.addToSelection(node.id); } } if (itemActive) { state.activeNode = node.id; } if (hovered) { state.hoveredNode = node.id; nodeBg = style.nodeFillHovered; } bool selected = state.selectedNodes.isSelected(node.id); bool wouldSelect = handleNodeDragSelection(*this, node.id, ImRect(node.pos, node.pos + node.size)); if (selected || wouldSelect) { nodeBorder = style.nodeBorderSelected; } draw_list->AddRectFilled(offset + node.pos, offset + node.pos + node.size, nodeBg, style.nodeRounding); draw_list->AddRect(offset + node.pos, offset + node.pos + node.size, nodeBorder, style.nodeRounding, -1, style.nodeBorderSize); bool canMove = selected || hovered; if (state.mode == Mode::DraggingNodes && canMove && ImGui::GetIO().MouseDelta != ImVec2()) { node.posFloat = node.posFloat + ImGui::GetIO().MouseDelta; if (ImGui::GetIO().KeyShift) { node.pos = node.posFloat; } else { node.pos = ImVec2( floor(node.posFloat.x / state.snapGrid) * state.snapGrid, floor(node.posFloat.y / state.snapGrid) * state.snapGrid ); } } else if (state.mode == Mode::None) { node.posFloat = node.pos; } if (resizable) { draw_list->PathLineTo(br + ImVec2(-resize_corner_size, -style.nodeBorderSize)); draw_list->PathLineTo(br + ImVec2(-style.nodeBorderSize, -resize_corner_size)); draw_list->PathArcToFast(ImVec2(br.x - window_rounding - style.nodeBorderSize, br.y - window_rounding - style.nodeBorderSize), window_rounding, 0, 3); draw_list->PathFillConvex(resize_col); } draw_list->ChannelsMerge(); IM_ASSERT(ImGui::GetWindowDrawList() == &state.nodeDrawList || ImGui::GetWindowDrawList() == &state.overlayDrawList); switchCurrentDrawList(state.windowDrawList); ImGui::PopID(); } void NodeArea::BeginSlot(NodeState &node) { ImVec2 offset = ImGui::GetWindowPos(); ImDrawList* draw_list = ImGui::GetWindowDrawList(); draw_list->ChannelsSetCurrent(1); node.lastCursor = ImGui::GetCursorPos(); ImVec2 pos = ImVec2(node.pos.x, node.lastCursor.y); draw_list->AddLine(offset + pos, offset + pos + ImVec2(node.size.x, 0), ImColor(100, 100, 100), 1.5f); draw_list->ChannelsSetCurrent(2); ImGui::Spacing(); } void NodeArea::EndSlot(NodeState &node, int inputType, int outputType) { ImDrawList* draw_list = ImGui::GetWindowDrawList(); ImVec2 inputPos = ImVec2(node.pos.x, node.lastCursor.y + (ImGui::GetCursorPos().y - node.lastCursor.y) / 2.f); ImVec2 outputPos = inputPos + ImVec2(node.size.x, 0); ImVec2 offset = ImGui::GetWindowPos(); auto paintConnectorDock = [&](ImVec2 pos, ImColor col, bool input, int slotIdx) { draw_list->AddCircleFilled(offset + pos, style.slotRadius, col); bool hovered = state.outerWindowFocused && ImLengthSqr(offset + pos - ImGui::GetMousePos()) <= style.slotMouseRadius * style.slotMouseRadius; if (hovered) { bool addCircle = true; Mode mode = input ? Mode::DraggingConnectorInput : Mode::DraggingConnectorOutput; if (ImGui::IsMouseDown(0) && !ImGui::IsMouseDragging(0, 1.f) && state.mode == Mode::None) { state.mode = mode; state.dragStart = state.dragEnd = pos; state.connectorStartNode = node.id; state.connectorStartSlot = slotIdx; } else { if (mode != state.mode) { // makes sure, we cannot connect input and input or output and output state.connectorEndNode = node.id; state.connectorEndSlot = slotIdx; } else { addCircle = false; } } if (addCircle) { draw_list->AddCircle(offset + pos, style.slotRadius, style.slotBorderHovered); } } }; if (inputType != -1) { node.inputSlots.push_back({ inputType, inputPos }); paintConnectorDock(inputPos, style.connectorTypeColor.at(inputType), false, (int)node.inputSlots.size() - 1); } if (outputType != -1) { node.outputSlots.push_back({ outputType, outputPos }); paintConnectorDock(outputPos, style.connectorTypeColor.at(outputType), true, (int)node.outputSlots.size() - 1); } node.lastCursor = ImGui::GetCursorPos(); } bool NodeArea::ConnectNodeSlots(int connectorId, NodeState &sourceNode, int sourceSlot, NodeState &sinkNode, int sinkSlot) { if (sourceNode.outputSlots.size() <= sourceSlot || sinkNode.inputSlots.size() <= sinkSlot) return false; ImVec2 offset = ImGui::GetWindowPos(); ImDrawList* draw_list = ImGui::GetWindowDrawList(); ImVec2 p1 = sourceNode.outputSlots[sourceSlot].pos; ImVec2 cp1 = p1 + ImVec2(+50, 0); ImVec2 p2 = sinkNode.inputSlots[sinkSlot].pos; ImVec2 cp2 = p2 + ImVec2(-50, 0); if (state.mode == Mode::SelectAll) { state.selectedLinks.addToSelection(connectorId); } bool wouldSelect = handleConnectorDragSelection(*this, connectorId, p1, cp1, cp2, p2); p1 += offset; p2 += offset; cp1 += offset; cp2 += offset; bool hovered = state.outerWindowFocused && closeToBezier(ImGui::GetMousePos(), p1, cp1, cp2, p2, 8.f); if (state.selectedLinks.isSelected(connectorId) || wouldSelect) { draw_list->AddBezierCurve(p1, cp1, cp2, p2, style.connectorSelectedColor, style.connectorSelectedSize); } int outType = sourceNode.outputSlots[sourceSlot].type; ImColor color = style.connectorInvalid; if (outType >= 0 && outType < (int)style.connectorTypeColor.size()) { color = style.connectorTypeColor.at(outType); } if (hovered && state.mode == Mode::None) { state.hoveredLink = connectorId; color = style.connectorHovered; if (ImGui::IsMouseClicked(0)) { if (!ImGui::GetIO().KeyShift) { clearAllSelections(); } state.selectedLinks.toggleSelection(connectorId); } } draw_list->AddBezierCurve(p1, cp1, cp2, p2, color, style.connectorSize); return true; } bool NodeArea::GetNewConnection(int *connectorSourceNode, int *connectorSourceNodeSlot, int *connectorSinkNode, int *connectorSinkNodeSlot) { if (ImGui::IsMouseReleased(0) && state.connectorStartNode != state.connectorEndNode && ((state.connectorStartNode != -1 && state.connectorStartSlot != -1) || (state.connectorEndNode != -1 && state.connectorEndSlot != -1))) { if (state.mode == Mode::DraggingConnectorInput) { *connectorSourceNode = state.connectorStartNode; *connectorSourceNodeSlot = state.connectorStartSlot; *connectorSinkNode = state.connectorEndNode; *connectorSinkNodeSlot = state.connectorEndSlot; return true; } else if(state.mode == Mode::DraggingConnectorOutput) { *connectorSourceNode = state.connectorEndNode; *connectorSourceNodeSlot = state.connectorEndSlot; *connectorSinkNode = state.connectorStartNode; *connectorSinkNodeSlot = state.connectorStartSlot; return true; } } return false; } void Style::generate() { ImGuiStyle const& style = ImGui::GetStyle(); selectionFill = ImColor(50, 50, 50, 50); selectionBorder = ImColor(255, 255, 255, 150); connectorSize = 3.f; connectorSelectedColor = ImColor(255, 128, 0); connectorSelectedSize = 4.f; connectorDragging = ImColor(255, 128, 0); connectorDraggingSize = 3.f; connectorHovered = ImColor(192, 192, 192); connectorInvalid = ImColor(255, 0, 0); nodePadding = style.WindowPadding; nodeFill = style.Colors[ImGuiCol_WindowBg]; nodeFillHovered = style.Colors[ImGuiCol_PopupBg]; nodeBorder = style.Colors[ImGuiCol_Border]; nodeBorderSelected = style.Colors[ImGuiCol_FrameBgActive]; nodeRounding = style.WindowRounding; nodeBorderSize = 2.f; slotRadius = 4.f; slotMouseRadius = 6.f; slotBorderHovered = ImColor(255, 128, 0); grid = { Grid{ 64, 1.f, ImColor(150, 150, 150, 200) }, Grid{ 16, 1.f, ImColor(200, 200, 200, 100) }, Grid{ 1, 1.f, ImColor(230, 230, 230, 40) } }; } NodeState::NodeState(int id, ImVec2 initialPos) : id(id) , pos(initialPos) , posFloat(initialPos) , size(-1.f, -1.f) {} } // namespace nodes
38.026706
219
0.622162
[ "geometry", "render", "vector" ]
550775e82dc72e1a11a50c4a381b4e1adb2b5fcd
19,579
cpp
C++
Engine_Source/Source/Platform/DirectX_11/Direct3D11_Context.cpp
GCourtney27/DirectX11RenderingEngine
ebbe470b697c6e5ab98502c0be4163500d91641a
[ "Apache-2.0" ]
2
2021-01-29T08:03:01.000Z
2021-04-10T19:18:54.000Z
Engine_Source/Source/Platform/DirectX_11/Direct3D11_Context.cpp
GCourtney27/DirectX11RenderingEngine
ebbe470b697c6e5ab98502c0be4163500d91641a
[ "Apache-2.0" ]
3
2020-06-04T23:37:07.000Z
2020-06-04T23:39:04.000Z
Engine_Source/Source/Platform/DirectX_11/Direct3D11_Context.cpp
GCourtney27/DirectX11RenderingEngine
ebbe470b697c6e5ab98502c0be4163500d91641a
[ "Apache-2.0" ]
1
2021-04-10T13:36:23.000Z
2021-04-10T13:36:23.000Z
#include <Engine_pch.h> #include "Direct3D11_Context.h" #include "Insight/Core/Application.h" #include "Platform/Win32/Win32_Window.h" #include "Platform/DirectX_11/Geometry/D3D11_Index_Buffer.h" #include "Platform/DirectX_11/Geometry/D3D11_Vertex_Buffer.h" #include "Platform/DirectX_11/Geometry/D3D11_Sphere_Renderer.h" #include "Insight/Runtime/Archetypes/APlayer_Character.h" #include "Insight/Systems/Managers/Geometry_Manager.h" #include "Insight/Rendering/APost_Fx.h" #include "Insight/Rendering/ASky_Light.h" #include "Insight/Rendering/ASky_Sphere.h" #include "Insight/Rendering/Lighting/ASpot_Light.h" #include "Insight/Rendering/Lighting/APoint_Light.h" #include "Insight/Rendering/Lighting/ADirectional_Light.h" namespace Insight { Direct3D11Context::Direct3D11Context() { } Direct3D11Context::~Direct3D11Context() { } bool Direct3D11Context::Init_Impl() { IE_DEBUG_LOG(LogSeverity::Log, "Renderer: D3D 11"); CreateDXGIFactory(); CreateDeviceAndSwapChain(); CreateRTV(); CreateConstantBufferViews(); CreateViewports(); CreateScissorRect(); CreateSamplers(); m_DeferredShadingTech.Init(m_pDevice.Get(), m_pDeviceContext.Get(), m_pWindowRef.get()); LoadAssets(); return true; } void Direct3D11Context::SetVertexBuffers_Impl(uint32_t StartSlot, uint32_t NumBuffers, ieVertexBuffer* pBuffers) { IE_ASSERT(dynamic_cast<D3D11VertexBuffer*>(pBuffers) != nullptr, "A vertex buffer passed to renderer with D3D 11 active must be a \"D3D11VertexBuffer\""); m_pDeviceContext->IASetVertexBuffers(StartSlot, NumBuffers, reinterpret_cast<D3D11VertexBuffer*>(pBuffers)->GetBufferPtr(), reinterpret_cast<D3D11VertexBuffer*>(pBuffers)->GetStridePtr(), reinterpret_cast<D3D11VertexBuffer*>(pBuffers)->GetBufferOffset()); } void Direct3D11Context::SetIndexBuffer_Impl(ieIndexBuffer* pBuffer) { IE_ASSERT(dynamic_cast<D3D11IndexBuffer*>(pBuffer) != nullptr, "A index buffer passed to renderer with D3D 11 active must be a \"D3D11IndexBuffer\""); m_pDeviceContext->IASetIndexBuffer(reinterpret_cast<D3D11IndexBuffer*>(pBuffer)->GetBufferPtr(), reinterpret_cast<D3D11IndexBuffer*>(pBuffer)->GetFormat(), reinterpret_cast<D3D11IndexBuffer*>(pBuffer)->GetBufferOffset()); } void Direct3D11Context::DrawIndexedInstanced_Impl(uint32_t IndexCountPerInstance, uint32_t NumInstances, uint32_t StartIndexLocation, uint32_t BaseVertexLoaction, uint32_t StartInstanceLocation) { m_pDeviceContext->DrawIndexed(IndexCountPerInstance, StartIndexLocation, BaseVertexLoaction); } void Direct3D11Context::DrawText_Impl(const char* Text) { } void Direct3D11Context::RenderSkySphere_Impl() { m_SkySphere->Render(); } bool Direct3D11Context::CreateSkybox_Impl() { m_SkySphere = new ieD3D11SphereRenderer(); m_SkySphere->Init(10, 20, 20, m_pDevice.Get(), m_pDeviceContext.Get()); return true; } void Direct3D11Context::DestroySkybox_Impl() { if (m_SkySphere) { delete m_pSkySphere; } } void Direct3D11Context::Destroy_Impl() { } bool Direct3D11Context::PostInit_Impl() { return true; } void Direct3D11Context::OnUpdate_Impl(const float DeltaMs) { RETURN_IF_WINDOW_NOT_VISIBLE; static float WorldTime; WorldTime += DeltaMs; // Send Per-Frame Data to GPU m_PerFrameData.Data.DeltaMs = DeltaMs; m_PerFrameData.Data.View = m_pWorldCameraRef->GetViewMatrix(); m_PerFrameData.Data.Projection = m_pWorldCameraRef->GetProjectionMatrix(); m_PerFrameData.Data.CameraPosition = m_pWorldCameraRef->GetPosition(); m_PerFrameData.Data.DeltaMs = DeltaMs; m_PerFrameData.Data.WorldTime = WorldTime; m_PerFrameData.Data.RayTraceEnabled = false; m_PerFrameData.Data.CameraNearZ = m_pWorldCameraRef->GetNearZ(); m_PerFrameData.Data.CameraFarZ = m_pWorldCameraRef->GetFarZ(); m_PerFrameData.Data.CameraExposure = m_pWorldCameraRef->GetExposure(); m_PerFrameData.Data.NumPointLights = (float)m_PointLights.size(); m_PerFrameData.Data.NumDirectionalLights = (m_pWorldDirectionalLight != nullptr) ? 1.0f : 0.0f; m_PerFrameData.Data.NumSpotLights = (float)m_SpotLights.size(); m_PerFrameData.Data.ScreenSize.x = (float)m_pWindowRef->GetWidth(); m_PerFrameData.Data.ScreenSize.y = (float)m_pWindowRef->GetHeight(); m_PerFrameData.SubmitToGPU(); // Send Point Lights to GPU if (m_PointLights.size() == 0) { m_LightData.Data.PointLights[0] = CB_PS_PointLight{}; } else { for (int i = 0; i < m_PointLights.size(); i++) { m_LightData.Data.PointLights[i] = m_PointLights[i]->GetConstantBuffer(); } } // Send Directionl Light to GPU if (m_pWorldDirectionalLight == nullptr) { m_LightData.Data.DirectionalLight = CB_PS_DirectionalLight{}; } else { m_LightData.Data.DirectionalLight = m_pWorldDirectionalLight->GetConstantBuffer(); } // Send Spot Lights to GPU if (m_SpotLights.size() == 0) { m_LightData.Data.SpotLights[0] = CB_PS_SpotLight{}; } else { for (int i = 0; i < m_SpotLights.size(); i++) { m_LightData.Data.SpotLights[i] = m_SpotLights[i]->GetConstantBuffer(); } } m_LightData.SubmitToGPU(); // Send Post-Fx data to GPU if (m_pPostFx) { m_PostFxData.Data = m_pPostFx->GetConstantBuffer(); } else { m_PostFxData.Data = CB_PS_PostFx{}; } m_PostFxData.SubmitToGPU(); } void Direct3D11Context::OnPreFrameRender_Impl() { RETURN_IF_WINDOW_NOT_VISIBLE; m_pDeviceContext->ClearRenderTargetView(m_pRenderTargetView.Get(), m_ClearColor); // Set Persistant Pass Properties m_pDeviceContext->RSSetViewports(1, &m_ScenePassViewPort); m_pDeviceContext->RSSetScissorRects(1, &m_ScenePassScissorRect); m_pDeviceContext->PSSetSamplers(0, 1, m_pPointClamp_SamplerState.GetAddressOf()); m_pDeviceContext->PSSetSamplers(1, 1, m_pLinearWrap_SamplerState.GetAddressOf()); m_DeferredShadingTech.PrepPipelineForRenderPass(); } void Direct3D11Context::OnRender_Impl() { RETURN_IF_WINDOW_NOT_VISIBLE; // TODO Shadow Pass // Geometry Pass m_DeferredShadingTech.BindGeometryPass(); m_pDeviceContext->VSSetConstantBuffers(1, 1, m_PerFrameData.GetAddressOf()); m_pDeviceContext->PSSetConstantBuffers(1, 1, m_PerFrameData.GetAddressOf()); GeometryManager::Render(RenderPassType::RenderPassType_Scene); } void Direct3D11Context::OnEditorRender_Impl() { } void Direct3D11Context::OnMidFrameRender_Impl() { RETURN_IF_WINDOW_NOT_VISIBLE; // Light Pass if (m_pSkyLight) { m_pSkyLight->BindCubeMaps(true); } m_pDeviceContext->PSSetConstantBuffers(2, 1, m_LightData.GetAddressOf()); m_DeferredShadingTech.BindLightPass(); // Sky Pass if (m_pSkySphere) { m_DeferredShadingTech.BindSkyPass(); m_pSkySphere->RenderSky(); } // Transparency Pass if (m_pSkyLight) { m_pSkyLight->BindCubeMaps(false); } m_pDeviceContext->VSSetConstantBuffers(1, 1, m_PerFrameData.GetAddressOf()); m_pDeviceContext->PSSetConstantBuffers(1, 1, m_PerFrameData.GetAddressOf()); m_pDeviceContext->PSSetConstantBuffers(2, 1, m_LightData.GetAddressOf()); m_DeferredShadingTech.BindTransparencyPass(); GeometryManager::Render(RenderPassType::RenderPassType_Transparency); // PostFx Pass m_pDeviceContext->OMSetRenderTargets(1, m_pRenderTargetView.GetAddressOf(), nullptr); m_pDeviceContext->PSSetConstantBuffers(3, 1, m_PostFxData.GetAddressOf()); m_pDeviceContext->PSSetConstantBuffers(1, 1, m_PerFrameData.GetAddressOf()); m_DeferredShadingTech.BindPostFxPass(); } void Direct3D11Context::ExecuteDraw_Impl() { RETURN_IF_WINDOW_NOT_VISIBLE; } void Direct3D11Context::SwapBuffers_Impl() { RETURN_IF_WINDOW_NOT_VISIBLE; UINT PresentFlags = (m_AllowTearing && m_WindowedMode) ? DXGI_PRESENT_ALLOW_TEARING : 0; HRESULT hr = m_pSwapChain->Present(m_pWindowRef->GetIsVsyncEnabled(), PresentFlags); ThrowIfFailed(hr, "Failed to present frame for D3D 11 context."); } void Direct3D11Context::OnWindowResize_Impl() { if (!m_IsMinimized) { if (m_WindowResizeComplete) { m_WindowResizeComplete = false; HRESULT hr = S_OK; m_pRenderTargetView.Reset(); m_pBackBuffer.Reset(); DXGI_SWAP_CHAIN_DESC SwapChainDesc = {}; m_pSwapChain->GetDesc(&SwapChainDesc); hr = m_pSwapChain->ResizeBuffers(m_FrameBufferCount, m_pWindowRef->GetWidth(), m_pWindowRef->GetHeight(), SwapChainDesc.BufferDesc.Format, SwapChainDesc.Flags); ThrowIfFailed(hr, "Failed to resize swap chain buffers for D3D 11 context."); BOOL fullScreenState; m_pSwapChain->GetFullscreenState(&fullScreenState, nullptr); m_WindowedMode = !fullScreenState; UpdateSizeDependentResources(); } } m_WindowVisible = !m_IsMinimized; m_WindowResizeComplete = true; } void Direct3D11Context::OnWindowFullScreen_Impl() { #if defined (IE_PLATFORM_BUILD_WIN32) Win32Window* pWindow = reinterpret_cast<Win32Window*>(m_pWindowRef.get()); HWND& pHWND = pWindow->GetWindowHandleRef(); if (m_FullScreenMode) { SetWindowLong(pHWND, GWL_STYLE, WS_OVERLAPPEDWINDOW); SetWindowPos( pHWND, HWND_NOTOPMOST, pWindow->GetWindowRect().left, pWindow->GetWindowRect().top, pWindow->GetWindowRect().right - pWindow->GetWindowRect().left, pWindow->GetWindowRect().bottom - pWindow->GetWindowRect().top, SWP_FRAMECHANGED | SWP_NOACTIVATE ); ShowWindow(pHWND, SW_NORMAL); } else { GetWindowRect(pHWND, &pWindow->GetWindowRect()); SetWindowLong(pHWND, GWL_STYLE, WS_OVERLAPPEDWINDOW & ~(WS_CAPTION | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SYSMENU | WS_THICKFRAME)); RECT FullscreenWindowRect; try { if (m_pSwapChain) { // Get the settings of the display on which the app's window is currently displayed ComPtr<IDXGIOutput> pOutput; ThrowIfFailed(m_pSwapChain->GetContainingOutput(&pOutput), "Failed to get containing output while switching to fullscreen mode in D3D 12 context."); DXGI_OUTPUT_DESC Desc; ThrowIfFailed(pOutput->GetDesc(&Desc), "Failed to get description from output while switching to fullscreen mode in D3D 12 context."); FullscreenWindowRect = Desc.DesktopCoordinates; } else { // Fallback to EnumDisplaySettings _Implementation throw COMException(NULL, "No Swap chain available", __FILE__, __FUNCTION__, __LINE__); } } catch (COMException& e) { UNREFERENCED_PARAMETER(e); // Get the settings of the primary display DEVMODE DevMode = {}; DevMode.dmSize = sizeof(DEVMODE); EnumDisplaySettings(nullptr, ENUM_CURRENT_SETTINGS, &DevMode); FullscreenWindowRect = { DevMode.dmPosition.x, DevMode.dmPosition.y, DevMode.dmPosition.x + static_cast<LONG>(DevMode.dmPelsWidth), DevMode.dmPosition.y + static_cast<LONG>(DevMode.dmPelsHeight) }; } SetWindowPos( pHWND, HWND_TOPMOST, FullscreenWindowRect.left, FullscreenWindowRect.top, FullscreenWindowRect.right, FullscreenWindowRect.bottom, SWP_FRAMECHANGED | SWP_NOACTIVATE); ShowWindow(pHWND, SW_MAXIMIZE); } m_FullScreenMode = !m_FullScreenMode; #endif // IE_PLATFORM_BUILD_WIN32 } void Direct3D11Context::OnShaderReload_Impl() { m_DeferredShadingTech.ReloadShaders(); } void Direct3D11Context::UpdateSizeDependentResources() { UpdateViewAndScissor(); // Re-Create Render Target View { HRESULT hr; hr = m_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(m_pBackBuffer.GetAddressOf())); ThrowIfFailed(hr, "Failed to get the back buffer from the swapchain for D3D 11 context during window resize."); hr = m_pDevice->CreateRenderTargetView(m_pBackBuffer.Get(), NULL, m_pRenderTargetView.GetAddressOf()); ThrowIfFailed(hr, "Failed to create render target view for D3D 11 context during window resize."); } // Re-Create GBuffer { m_DeferredShadingTech.Destroy(); m_DeferredShadingTech.Init(m_pDevice.Get(), m_pDeviceContext.Get(), m_pWindowRef.get()); } // Recreate Camera Projection Matrix { if (!m_pWorldCameraRef->GetIsOrthographic()) { m_pWorldCameraRef->SetPerspectiveProjectionValues(m_pWorldCameraRef->GetFOV(), static_cast<float>(m_pWindowRef->GetWidth()) / static_cast<float>(m_pWindowRef->GetHeight()), m_pWorldCameraRef->GetNearZ(), m_pWorldCameraRef->GetFarZ()); } } } void Direct3D11Context::UpdateViewAndScissor() { m_ScenePassViewPort.TopLeftX = 0.0f; m_ScenePassViewPort.TopLeftY = 0.0f; m_ScenePassViewPort.Width = static_cast<FLOAT>(m_pWindowRef->GetWidth()); m_ScenePassViewPort.Height = static_cast<FLOAT>(m_pWindowRef->GetHeight()); m_ScenePassScissorRect.left = static_cast<LONG>(m_ScenePassViewPort.TopLeftX); m_ScenePassScissorRect.right = static_cast<LONG>(m_ScenePassViewPort.TopLeftX + m_ScenePassViewPort.Width); m_ScenePassScissorRect.top = static_cast<LONG>(m_ScenePassViewPort.TopLeftY); m_ScenePassScissorRect.bottom = static_cast<LONG>(m_ScenePassViewPort.TopLeftX + m_ScenePassViewPort.Height); } // Initializaion // -------------- void Direct3D11Context::CreateDXGIFactory() { HRESULT hr = ::CreateDXGIFactory1(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(m_pDxgiFactory.GetAddressOf())); ThrowIfFailed(hr, "Failed to create Dxgi Factor for DirectX 11."); } void Direct3D11Context::GetHardwareAdapter(IDXGIFactory1* pFactory, IDXGIAdapter** ppAdapter) { HRESULT hr; ComPtr<IDXGIAdapter> pAdapter; *ppAdapter = nullptr; uint32_t CurrentVideoCardMemory = 0; DXGI_ADAPTER_DESC Desc; for (uint32_t AdapterIndex = 0; DXGI_ERROR_NOT_FOUND != pFactory->EnumAdapters(AdapterIndex, &pAdapter); AdapterIndex++) { Desc = {}; pAdapter->GetDesc(&Desc); // Make sure we get the video card that is not a software adapter // and it has the most video memory. Likly a software adapter if // the device has no system or dedicated video memory. bool IsSoftwareAdapter = ((Desc.DedicatedVideoMemory | Desc.DedicatedSystemMemory) == 0); if ((Desc.DedicatedVideoMemory < CurrentVideoCardMemory) || IsSoftwareAdapter) { continue; } hr = ::D3D11CreateDevice(pAdapter.Get(), D3D_DRIVER_TYPE_UNKNOWN, NULL, NULL, nullptr, 0, D3D11_SDK_VERSION, NULL, NULL, NULL); if (SUCCEEDED(hr)) { CurrentVideoCardMemory = static_cast<uint32_t>(Desc.DedicatedSystemMemory); if (*ppAdapter != nullptr) { (*ppAdapter)->Release(); } *ppAdapter = pAdapter.Detach(); IE_DEBUG_LOG(LogSeverity::Warning, "Found suitable Direct3D 11 graphics hardware: {0}", StringHelper::WideToString(Desc.Description)); } } Desc = {}; (*ppAdapter)->GetDesc(&Desc); IE_DEBUG_LOG(LogSeverity::Warning, "\"{0}\" selected as Direct3D 11 graphics hardware.", StringHelper::WideToString(Desc.Description)); } void Direct3D11Context::CreateDeviceAndSwapChain() { GetHardwareAdapter(m_pDxgiFactory.Get(), &m_pAdapter); UINT DeviceCreateFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; #if defined IE_DEBUG DeviceCreateFlags |= D3D11_CREATE_DEVICE_DEBUG; if (m_DeviceMaxSupportedFeatureLevel >= D3D_FEATURE_LEVEL_11_1) { DeviceCreateFlags |= D3D11_CREATE_DEVICE_DEBUGGABLE; } #endif m_SampleDesc = {}; m_SampleDesc.Count = 1; m_SampleDesc.Quality = 0; // TODO Query for HDR support DXGI_SWAP_CHAIN_DESC SwapChainDesc = { }; SwapChainDesc.BufferDesc.Width = m_pWindowRef->GetWidth(); SwapChainDesc.BufferDesc.Height = m_pWindowRef->GetHeight(); SwapChainDesc.BufferDesc.RefreshRate.Numerator = 60; SwapChainDesc.BufferDesc.RefreshRate.Denominator = 1; SwapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; SwapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; SwapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; SwapChainDesc.SampleDesc = m_SampleDesc; SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; SwapChainDesc.BufferCount = static_cast<UINT>(m_FrameBufferCount); //SwapChainDesc.OutputWindow = reinterpret_cast<Win32Window*>(m_pWindowRef.get())->GetWindowHandleRef(); SwapChainDesc.Windowed = TRUE; SwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; SwapChainDesc.Flags = m_AllowTearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0; #if defined (IE_PLATFORM_BUILD_WIN32) HRESULT hr = ::D3D11CreateDeviceAndSwapChain( m_pAdapter.Get(), D3D_DRIVER_TYPE_UNKNOWN, NULL, DeviceCreateFlags, NULL, 0, D3D11_SDK_VERSION, &SwapChainDesc, &m_pSwapChain, &m_pDevice, NULL, &m_pDeviceContext ); ThrowIfFailed(hr, "Failed to create swapchain for D3D 11 context"); if (m_AllowTearing) { ThrowIfFailed(m_pDxgiFactory->MakeWindowAssociation(reinterpret_cast<Win32Window*>(m_pWindowRef.get())->GetWindowHandleRef(), DXGI_MWA_NO_ALT_ENTER), "Failed to make window association for D3D 11 context."); } #endif // IE_PLATFORM_BUILD_WIN32 } void Direct3D11Context::CreateRTV() { HRESULT hr; hr = m_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(m_pBackBuffer.GetAddressOf())); ThrowIfFailed(hr, "Failed to get the back buffer from the swapchain for D3D 11 context."); hr = m_pDevice->CreateRenderTargetView(m_pBackBuffer.Get(), NULL, m_pRenderTargetView.GetAddressOf()); ThrowIfFailed(hr, "Failed to create render target view for D3D 11 context."); } void Direct3D11Context::CreateConstantBufferViews() { m_PerFrameData.Init(m_pDevice.Get(), m_pDeviceContext.Get()); m_LightData.Init(m_pDevice.Get(), m_pDeviceContext.Get()); m_PostFxData.Init(m_pDevice.Get(), m_pDeviceContext.Get()); } void Direct3D11Context::CreateViewports() { m_ScenePassViewPort = {}; m_ScenePassViewPort.TopLeftX = 0.0f; m_ScenePassViewPort.TopLeftY = 0.0f; m_ScenePassViewPort.Width = static_cast<FLOAT>(m_pWindowRef->GetWidth()); m_ScenePassViewPort.Height = static_cast<FLOAT>(m_pWindowRef->GetHeight()); m_ScenePassViewPort.MinDepth = 0.0f; m_ScenePassViewPort.MaxDepth = 1.0f; } void Direct3D11Context::CreateScissorRect() { m_ScenePassScissorRect.left = 0; m_ScenePassScissorRect.top = 0; m_ScenePassScissorRect.right = m_pWindowRef->GetWidth(); m_ScenePassScissorRect.bottom = m_pWindowRef->GetHeight(); } void Direct3D11Context::CreateSamplers() { D3D11_SAMPLER_DESC SamplerPointClampDesc = {}; SamplerPointClampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT; SamplerPointClampDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; SamplerPointClampDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; SamplerPointClampDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; SamplerPointClampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; SamplerPointClampDesc.MinLOD = 0.0f; SamplerPointClampDesc.MaxLOD = D3D11_FLOAT32_MAX; HRESULT hr = m_pDevice->CreateSamplerState(&SamplerPointClampDesc, m_pPointClamp_SamplerState.GetAddressOf()); ThrowIfFailed(hr, "Failed to create linear wrap sampler for D3D11 context."); D3D11_SAMPLER_DESC SamplerLinearWrapDesc = {}; SamplerLinearWrapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; SamplerLinearWrapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; SamplerLinearWrapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; SamplerLinearWrapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; SamplerLinearWrapDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; SamplerLinearWrapDesc.MinLOD = 0.0f; SamplerLinearWrapDesc.MaxLOD = 9.0f; SamplerLinearWrapDesc.MipLODBias = m_GraphicsSettings.MipLodBias; SamplerLinearWrapDesc.MaxAnisotropy = m_GraphicsSettings.MaxAnisotropy; hr = m_pDevice->CreateSamplerState(&SamplerLinearWrapDesc, m_pLinearWrap_SamplerState.GetAddressOf()); ThrowIfFailed(hr, "Failed to create linear wrap sampler for D3D11 context."); } void Direct3D11Context::LoadAssets() { } }
34.050435
257
0.76439
[ "geometry", "render" ]
550e1cde56d4ce52190173247997fb46974976fb
8,857
cpp
C++
src/3rdparty/khtml/src/svg/SVGMaskElement.cpp
afarcat/QtHtmlView
fff12b6f5c08c2c6db15dd73e4f0b55421827b39
[ "Apache-2.0" ]
null
null
null
src/3rdparty/khtml/src/svg/SVGMaskElement.cpp
afarcat/QtHtmlView
fff12b6f5c08c2c6db15dd73e4f0b55421827b39
[ "Apache-2.0" ]
null
null
null
src/3rdparty/khtml/src/svg/SVGMaskElement.cpp
afarcat/QtHtmlView
fff12b6f5c08c2c6db15dd73e4f0b55421827b39
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) 2004, 2005, 2006, 2008 Nikolas Zimmermann <zimmermann@kde.org> 2004, 2005, 2006, 2007 Rob Buis <buis@kde.org> 2005 Alexander Kellett <lypanov@kde.org> This file is part of the KDE project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #if ENABLE(SVG) #include "SVGMaskElement.h" #include "CSSStyleSelector.h" #include "GraphicsContext.h" #include "ImageBuffer.h" #include "RenderSVGContainer.h" #include "SVGLength.h" #include "SVGNames.h" #include "SVGRenderSupport.h" #include "SVGUnitTypes.h" #include <math.h> #include <wtf/MathExtras.h> #include <wtf/OwnPtr.h> using namespace std; namespace WebCore { SVGMaskElement::SVGMaskElement(const QualifiedName &tagName, Document *doc) : SVGStyledLocatableElement(tagName, doc) , SVGURIReference() , SVGTests() , SVGLangSpace() , SVGExternalResourcesRequired() , m_maskUnits(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) , m_maskContentUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE) , m_x(this, LengthModeWidth) , m_y(this, LengthModeHeight) , m_width(this, LengthModeWidth) , m_height(this, LengthModeHeight) { // Spec: If the attribute is not specified, the effect is as if a value of "-10%" were specified. setXBaseValue(SVGLength(this, LengthModeWidth, "-10%")); setYBaseValue(SVGLength(this, LengthModeHeight, "-10%")); // Spec: If the attribute is not specified, the effect is as if a value of "120%" were specified. setWidthBaseValue(SVGLength(this, LengthModeWidth, "120%")); setHeightBaseValue(SVGLength(this, LengthModeHeight, "120%")); } SVGMaskElement::~SVGMaskElement() { } ANIMATED_PROPERTY_DEFINITIONS(SVGMaskElement, int, Enumeration, enumeration, MaskUnits, maskUnits, SVGNames::maskUnitsAttr, m_maskUnits) ANIMATED_PROPERTY_DEFINITIONS(SVGMaskElement, int, Enumeration, enumeration, MaskContentUnits, maskContentUnits, SVGNames::maskContentUnitsAttr, m_maskContentUnits) ANIMATED_PROPERTY_DEFINITIONS(SVGMaskElement, SVGLength, Length, length, X, x, SVGNames::xAttr, m_x) ANIMATED_PROPERTY_DEFINITIONS(SVGMaskElement, SVGLength, Length, length, Y, y, SVGNames::yAttr, m_y) ANIMATED_PROPERTY_DEFINITIONS(SVGMaskElement, SVGLength, Length, length, Width, width, SVGNames::widthAttr, m_width) ANIMATED_PROPERTY_DEFINITIONS(SVGMaskElement, SVGLength, Length, length, Height, height, SVGNames::heightAttr, m_height) void SVGMaskElement::parseMappedAttribute(MappedAttribute *attr) { if (attr->name() == SVGNames::maskUnitsAttr) { if (attr->value() == "userSpaceOnUse") { setMaskUnitsBaseValue(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE); } else if (attr->value() == "objectBoundingBox") { setMaskUnitsBaseValue(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX); } } else if (attr->name() == SVGNames::maskContentUnitsAttr) { if (attr->value() == "userSpaceOnUse") { setMaskContentUnitsBaseValue(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE); } else if (attr->value() == "objectBoundingBox") { setMaskContentUnitsBaseValue(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX); } } else if (attr->name() == SVGNames::xAttr) { setXBaseValue(SVGLength(this, LengthModeWidth, attr->value())); } else if (attr->name() == SVGNames::yAttr) { setYBaseValue(SVGLength(this, LengthModeHeight, attr->value())); } else if (attr->name() == SVGNames::widthAttr) { setWidthBaseValue(SVGLength(this, LengthModeWidth, attr->value())); } else if (attr->name() == SVGNames::heightAttr) { setHeightBaseValue(SVGLength(this, LengthModeHeight, attr->value())); } else { if (SVGURIReference::parseMappedAttribute(attr)) { return; } if (SVGTests::parseMappedAttribute(attr)) { return; } if (SVGLangSpace::parseMappedAttribute(attr)) { return; } if (SVGExternalResourcesRequired::parseMappedAttribute(attr)) { return; } SVGStyledElement::parseMappedAttribute(attr); } } void SVGMaskElement::svgAttributeChanged(const QualifiedName &attrName) { SVGStyledElement::svgAttributeChanged(attrName); if (!m_masker) { return; } if (attrName == SVGNames::maskUnitsAttr || attrName == SVGNames::maskContentUnitsAttr || attrName == SVGNames::xAttr || attrName == SVGNames::yAttr || attrName == SVGNames::widthAttr || attrName == SVGNames::heightAttr || SVGURIReference::isKnownAttribute(attrName) || SVGTests::isKnownAttribute(attrName) || SVGLangSpace::isKnownAttribute(attrName) || SVGExternalResourcesRequired::isKnownAttribute(attrName) || SVGStyledElement::isKnownAttribute(attrName)) { m_masker->invalidate(); } } void SVGMaskElement::childrenChanged(bool changedByParser, Node *beforeChange, Node *afterChange, int childCountDelta) { SVGStyledElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta); if (!m_masker) { return; } m_masker->invalidate(); } unique_ptr<ImageBuffer> SVGMaskElement::drawMaskerContent(const FloatRect &targetRect, FloatRect &maskDestRect) const { // Determine specified mask size float xValue; float yValue; float widthValue; float heightValue; if (maskUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) { xValue = x().valueAsPercentage() * targetRect.width(); yValue = y().valueAsPercentage() * targetRect.height(); widthValue = width().valueAsPercentage() * targetRect.width(); heightValue = height().valueAsPercentage() * targetRect.height(); } else { xValue = x().value(); yValue = y().value(); widthValue = width().value(); heightValue = height().value(); } IntSize imageSize(lroundf(widthValue), lroundf(heightValue)); clampImageBufferSizeToViewport(document()->renderer(), imageSize); if (imageSize.width() < static_cast<int>(widthValue)) { widthValue = imageSize.width(); } if (imageSize.height() < static_cast<int>(heightValue)) { heightValue = imageSize.height(); } unique_ptr<ImageBuffer> maskImage = ImageBuffer::create(imageSize, false); if (!maskImage.get()) { return maskImage; } maskDestRect = FloatRect(xValue, yValue, widthValue, heightValue); if (maskUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) { maskDestRect.move(targetRect.x(), targetRect.y()); } GraphicsContext *maskImageContext = maskImage->context(); ASSERT(maskImageContext); maskImageContext->save(); maskImageContext->translate(-xValue, -yValue); if (maskContentUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) { maskImageContext->save(); maskImageContext->scale(FloatSize(targetRect.width(), targetRect.height())); } // Render subtree into ImageBuffer for (Node *n = firstChild(); n; n = n->nextSibling()) { SVGElement *elem = 0; if (n->isSVGElement()) { elem = static_cast<SVGElement *>(n); } if (!elem || !elem->isStyled()) { continue; } SVGStyledElement *e = static_cast<SVGStyledElement *>(elem); RenderObject *item = e->renderer(); if (!item) { continue; } renderSubtreeToImage(maskImage.get(), item); } if (maskContentUnits() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) { maskImageContext->restore(); } maskImageContext->restore(); return maskImage; } RenderObject *SVGMaskElement::createRenderer(RenderArena *arena, RenderStyle *) { RenderSVGContainer *maskContainer = new(arena) RenderSVGContainer(this); maskContainer->setDrawsContents(false); return maskContainer; } SVGResource *SVGMaskElement::canvasResource() { if (!m_masker) { m_masker = SVGResourceMasker::create(this); } return m_masker.get(); } } #endif // ENABLE(SVG)
36.29918
164
0.685672
[ "render" ]
550e98c93fd6b829316c0fbb8807e4bf60d59abd
3,098
hpp
C++
include/dctl/util/stopwatch.hpp
sagarpant1/dctl
b858fa139159eff73e8f3eec32da93ba077e0bd3
[ "BSL-1.0" ]
null
null
null
include/dctl/util/stopwatch.hpp
sagarpant1/dctl
b858fa139159eff73e8f3eec32da93ba077e0bd3
[ "BSL-1.0" ]
null
null
null
include/dctl/util/stopwatch.hpp
sagarpant1/dctl
b858fa139159eff73e8f3eec32da93ba077e0bd3
[ "BSL-1.0" ]
1
2020-07-27T14:19:28.000Z
2020-07-27T14:19:28.000Z
#pragma once // Copyright Rein Halbersma 2010-2020. // 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 <cassert> // assert #include <chrono> // duration_cast, steady_clock, milliseconds #include <vector> // vector namespace dctl { namespace util { class Stopwatch { using units = std::chrono::milliseconds; using clock = std::chrono::steady_clock; std::vector<clock::time_point> splits; bool is_running = false; bool invariant() const noexcept { return (!splits.empty() || !is_running) && ( splits.size() != 1 || is_running) ; } public: Stopwatch() noexcept { assert(invariant()); } void start_stop() { if (!is_running) { start(); } else { stop(); } assert(invariant()); } void split_reset() { if (is_running) { split(); } else { reset(); } assert(invariant()); } units elapsed_time() const noexcept { using namespace std::chrono; return is_running ? duration_cast<units>(clock::now() - splits.front()) : split_time() ; } units split_time() const noexcept { using namespace std::chrono; auto const N = splits.size(); switch (N) { case 0: return units::zero(); case 1: return duration_cast<units>(clock::now() - splits.front()); default: return duration_cast<units>(splits.back() - splits.front()); } } units lap_time() const noexcept { using namespace std::chrono; auto const N = splits.size(); switch (N) { case 0: return units::zero(); case 1: return duration_cast<units>(clock::now() - splits[N - 1]); default: return duration_cast<units>(splits[N - 1] - splits[N - 2]); } } private: void start() { assert(!is_running); is_running = true; split(); } void stop() { assert(is_running); split(); is_running = false; } void split() { assert(is_running); splits.push_back(clock::now()); } void reset() { assert(!is_running); splits.clear(); } }; } // namespace util } // namespace dctl
26.033613
85
0.428341
[ "vector" ]
55281fc9fe8566c22016ca9153aaa8e693c42c81
6,300
cpp
C++
HW05_Philip_Mark/stereo_analysis_partA_B.cpp
idungoofed/advanced_cv
5399ad7b1a0e20e8eb9eb6e7ae1e5502be2db9f3
[ "MIT" ]
null
null
null
HW05_Philip_Mark/stereo_analysis_partA_B.cpp
idungoofed/advanced_cv
5399ad7b1a0e20e8eb9eb6e7ae1e5502be2db9f3
[ "MIT" ]
null
null
null
HW05_Philip_Mark/stereo_analysis_partA_B.cpp
idungoofed/advanced_cv
5399ad7b1a0e20e8eb9eb6e7ae1e5502be2db9f3
[ "MIT" ]
null
null
null
/** Author: Mark Philip (msp3430) * * Inspired by: * - https://github.com/sourishg/stereo-calibration/blob/master/calib_intrinsic.cpp * - https://github.com/daviddoria/Examples/blob/master/c%2B%2B/OpenCV/CheckerBoardCalibration/CalibrateAndDisplay.cxx * - https://docs.opencv.org/3.1.0/d4/d94/tutorial_camera_calibration.html */ #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include <string> #include <dirent.h> using namespace cv; using namespace std; /** Transforms 2-D coordinates of a point into hypothetical 3-D points. * * @param boardSize The size of the board. In this case, 8x6 * @param squareSize The size of a square on the board * @return A vector of 3-D points */ std::vector<cv::Point3f> Create3DChessboardCorners(cv::Size boardSize, float squareSize) { std::vector<cv::Point3f> corners; // map the 2-D coords to 3-D coords for (int i = 0; i < boardSize.height; i++) { for (int j = 0; j < boardSize.width; j++) { corners.push_back( cv::Point3f( float(j * squareSize), float(i * squareSize), 0 ) ); } } return corners; } /** Takes an image filename and calculates the camera matrix and distortion coefficients. * * @param imageFileName The path to the image to process * @return True if the image was processed successfully, else false */ bool processImage(char *imageFileName) { // size of the board cv::Size boardSize(8, 6); float squareSize = 1.f; // This is "1 arbitrary unit" // open the image cv::Mat raw_image = cv::imread(imageFileName); if (raw_image.empty()) { std::cerr << "Image not read correctly!" << std::endl; return false; } // downsize image by a factor of 4 Mat image; resize(raw_image, image, raw_image.size() / 4); // retrieve once for multiple uses cv::Size imageSize = image.size(); // array of 2-D image points to be mapped to 3-D points later vector<std::vector<cv::Point2f> > imagePoints(1); // Find the chessboard corners Mat imageGray; // create a grayscale version for use with cornerSubPix() cvtColor(image, imageGray, CV_BGR2GRAY); // get the corners using adaptive thresholding bool found = findChessboardCorners(image, boardSize, imagePoints[0], CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS); if (found) { // if the corners were found, refine the point locations cornerSubPix(imageGray, cv::Mat(imagePoints[0]), cv::Size(5, 5), cv::Size(-1, -1), TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 30, 0.1)); // draw the points on the color image drawChessboardCorners(image, boardSize, cv::Mat(imagePoints[0]), found); // create and fill the array of 3-D image points std::vector<std::vector<cv::Point3f> > objectPoints(1); objectPoints[0] = Create3DChessboardCorners(boardSize, squareSize); // prep params for calibration std::vector<cv::Mat> rotationVectors; std::vector<cv::Mat> translationVectors; cv::Mat distortionCoefficients = cv::Mat::zeros(8, 1, CV_64F); // There are 8 distortion coefficients cv::Mat cameraMatrix = cv::Mat::eye(3, 3, CV_64F); // calibrate! int flags = 0 | CV_CALIB_FIX_K4 | CV_CALIB_FIX_K5; double rms = calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix, distortionCoefficients, rotationVectors, translationVectors, flags); // print the params std::cout << "RMS: " << rms << std::endl; std::cout << "Camera matrix: " << cameraMatrix << std::endl; std::cout << "Distortion coefficients: " << distortionCoefficients << std::endl; // Unmap the image to remove the distortion Mat undistorted, map1, map2; // create maps and remap initUndistortRectifyMap( cameraMatrix, distortionCoefficients, Mat(), getOptimalNewCameraMatrix(cameraMatrix, distortionCoefficients, imageSize, 1, imageSize), imageSize, CV_16SC2, map1, map2 ); remap(image, undistorted, map1, map2, INTER_LINEAR); Mat imageDiff; absdiff(image, undistorted, imageDiff); // show the original and undistorted images, and also the difference between them namedWindow("Original Image", WINDOW_GUI_NORMAL); namedWindow("Undistorted Image", WINDOW_GUI_NORMAL); namedWindow("Differences", WINDOW_GUI_NORMAL); imshow("Original Image", image); imshow("Undistorted Image", undistorted); imshow("Differences", imageDiff); waitKey(0); } return found; } int main(int argc, char *argv[]) { // get all the files in ./IMAGES_02_CALIBRATION/ DIR *dir; struct dirent *ent; bool done = false; // keep processing images until one of them succeeds if ((dir = opendir("./IMAGES_02_CALIBRATION/"))) { while (!done && (ent = readdir(dir))) { // exclude . and .. if (strcmp(ent->d_name, ".\0") && strcmp(ent->d_name, "..\0")) { // create the filename string char *filename = (char *) malloc(sizeof(char) * (25 + strlen(ent->d_name))); filename = strncpy(filename, "./IMAGES_02_CALIBRATION/\0", 25 + strlen(ent->d_name)); filename = strcat(filename, ent->d_name); // process the image printf("Now processing: \"%s\"\n", filename); done = processImage(filename); // free the earlier-malloced filename free(filename); } } closedir(dir); } else { // could not open directory std::cout << "Error! ./IMAGES_02_CALIBRATION/ doesn't exist." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
38.650307
122
0.604286
[ "vector" ]
552d0535311ae5b07c2df61f746d82a9a8c83fdb
27,805
cxx
C++
main/sd/source/ui/func/fuinsfil.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sd/source/ui/func/fuinsfil.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sd/source/ui/func/fuinsfil.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "fuinsfil.hxx" #include <vcl/wrkwin.hxx> #include <sfx2/progress.hxx> #include <editeng/outliner.hxx> #ifndef _EDITENG_HXX #include <editeng/editeng.hxx> #endif #include <svl/stritem.hxx> #include <sfx2/request.hxx> #include <sfx2/app.hxx> #include <vcl/msgbox.hxx> #include <sfx2/printer.hxx> #include <svx/svdorect.hxx> #include <svx/svdundo.hxx> #include <svx/svdoutl.hxx> #include <sfx2/filedlghelper.hxx> #include <sot/formats.hxx> #include <svl/urihelper.hxx> #include <editeng/forbiddencharacterstable.hxx> #include <tools/urlobj.hxx> #include <sfx2/docfile.hxx> #include <sfx2/docfilt.hxx> #include <sfx2/fcontnr.hxx> #include <svx/svdpagv.hxx> #include <svx/dialogs.hrc> #include <com/sun/star/ui/dialogs/XFilterManager.hpp> #include <com/sun/star/ui/dialogs/XFilePicker.hpp> #include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp> #include "sdresid.hxx" #include "drawdoc.hxx" #include "Window.hxx" #include "View.hxx" #include "strings.hrc" #include "stlpool.hxx" #include "glob.hrc" #include "sdpage.hxx" #include "strmname.h" #include "strings.hrc" #include "DrawViewShell.hxx" #include "OutlineViewShell.hxx" #include "DrawDocShell.hxx" #include "GraphicDocShell.hxx" #include "app.hrc" #include "unmovss.hxx" #include "Outliner.hxx" #include "sdabstdlg.hxx" using ::rtl::OUString; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::ui::dialogs; using namespace ::com::sun::star; namespace sd { TYPEINIT1( FuInsertFile, FuPoor ); #define POOL_BUFFER_SIZE (sal_uInt16)32768 #define BASIC_BUFFER_SIZE (sal_uInt16)8192 #define DOCUMENT_BUFFER_SIZE (sal_uInt16)32768 /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuInsertFile::FuInsertFile ( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq) : FuPoor(pViewSh, pWin, pView, pDoc, rReq) { } FunctionReference FuInsertFile::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ) { FunctionReference xFunc( new FuInsertFile( pViewSh, pWin, pView, pDoc, rReq ) ); xFunc->DoExecute(rReq); return xFunc; } void FuInsertFile::DoExecute( SfxRequest& rReq ) { SfxFilterMatcher& rMatcher = SFX_APP()->GetFilterMatcher(); ::std::vector< String > aFilterVector; const SfxItemSet* pArgs = rReq.GetArgs (); FuInsertFile::GetSupportedFilterVector( aFilterVector ); if (!pArgs) { sfx2::FileDialogHelper aFileDialog( WB_OPEN | SFXWB_INSERT | WB_STDMODAL ); Reference< XFilePicker > xFilePicker( aFileDialog.GetFilePicker(), UNO_QUERY ); Reference< XFilterManager > xFilterManager( xFilePicker, UNO_QUERY ); String aOwnCont; String aOtherCont; const SfxFilter* pFilter = NULL; aFileDialog.SetTitle( String( SdResId(STR_DLG_INSERT_PAGES_FROM_FILE ) ) ); if( mpDoc->GetDocumentType() == DOCUMENT_TYPE_IMPRESS ) { aOwnCont = String( RTL_CONSTASCII_USTRINGPARAM( "simpress" ) ); aOtherCont = String( RTL_CONSTASCII_USTRINGPARAM( "sdraw" ) ) ; } else { aOtherCont = String( RTL_CONSTASCII_USTRINGPARAM( "simpress" ) ); aOwnCont = String( RTL_CONSTASCII_USTRINGPARAM( "sdraw" ) ) ; } SfxFilterMatcher aMatch( aOwnCont ); if( xFilterManager.is() ) { // Get filter for current format try { String aExt; String aAllSpec( SdResId( STR_ALL_FILES ) ); xFilterManager->appendFilter( aAllSpec, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "*.*" ) ) ); xFilterManager->setCurrentFilter( aAllSpec ); // set default-filter (<All>) // Get main filter pFilter = SfxFilter::GetDefaultFilterFromFactory( aOwnCont ); if( pFilter ) xFilterManager->appendFilter( pFilter->GetUIName(), pFilter->GetDefaultExtension() ); // get cross filter pFilter = SfxFilter::GetDefaultFilterFromFactory( aOtherCont ); if( pFilter ) { pFilter = aMatch.GetFilter4Extension( pFilter->GetDefaultExtension() ); if ( pFilter ) xFilterManager->appendFilter( pFilter->GetUIName(), pFilter->GetDefaultExtension() ); } // get femplate filter if( mpDoc->GetDocumentType() == DOCUMENT_TYPE_IMPRESS ) pFilter = DrawDocShell::Factory().GetTemplateFilter(); else pFilter = GraphicDocShell::Factory().GetTemplateFilter(); if( pFilter ) xFilterManager->appendFilter( pFilter->GetUIName(), pFilter->GetDefaultExtension() ); // get Powerpoint filter aExt = UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( ".ppt" ) ); pFilter = aMatch.GetFilter4Extension( aExt ); if( pFilter ) xFilterManager->appendFilter( pFilter->GetUIName(), pFilter->GetDefaultExtension() ); // Get other draw/impress filters pFilter = aMatch.GetFilter4ClipBoardId( SOT_FORMATSTR_ID_STARIMPRESS_60, SFX_FILTER_IMPORT, SFX_FILTER_TEMPLATEPATH ); if( pFilter ) xFilterManager->appendFilter( pFilter->GetUIName(), pFilter->GetDefaultExtension() ); pFilter = aMatch.GetFilter4ClipBoardId( SOT_FORMATSTR_ID_STARIMPRESS_60, SFX_FILTER_TEMPLATEPATH ); if( pFilter ) xFilterManager->appendFilter( pFilter->GetUIName(), pFilter->GetDefaultExtension() ); pFilter = aMatch.GetFilter4ClipBoardId( SOT_FORMATSTR_ID_STARDRAW_60, SFX_FILTER_IMPORT, SFX_FILTER_TEMPLATEPATH ); if( pFilter ) xFilterManager->appendFilter( pFilter->GetUIName(), pFilter->GetDefaultExtension() ); pFilter = aMatch.GetFilter4ClipBoardId( SOT_FORMATSTR_ID_STARDRAW_60, SFX_FILTER_TEMPLATEPATH ); if( pFilter ) xFilterManager->appendFilter( pFilter->GetUIName(), pFilter->GetDefaultExtension() ); pFilter = aMatch.GetFilter4ClipBoardId( SOT_FORMATSTR_ID_STARIMPRESS_50, SFX_FILTER_IMPORT, SFX_FILTER_TEMPLATEPATH ); if( pFilter ) xFilterManager->appendFilter( pFilter->GetUIName(), pFilter->GetDefaultExtension() ); pFilter = aMatch.GetFilter4ClipBoardId( SOT_FORMATSTR_ID_STARIMPRESS_50, SFX_FILTER_TEMPLATEPATH ); if( pFilter ) xFilterManager->appendFilter( pFilter->GetUIName(), pFilter->GetDefaultExtension() ); pFilter = aMatch.GetFilter4ClipBoardId( SOT_FORMATSTR_ID_STARDRAW_50, SFX_FILTER_IMPORT, SFX_FILTER_TEMPLATEPATH ); if( pFilter ) xFilterManager->appendFilter( pFilter->GetUIName(), pFilter->GetDefaultExtension() ); pFilter = aMatch.GetFilter4ClipBoardId( SOT_FORMATSTR_ID_STARDRAW_50, SFX_FILTER_TEMPLATEPATH ); if( pFilter ) xFilterManager->appendFilter( pFilter->GetUIName(), pFilter->GetDefaultExtension() ); pFilter = aMatch.GetFilter4ClipBoardId( SOT_FORMATSTR_ID_STARDRAW_40, SFX_FILTER_IMPORT, SFX_FILTER_TEMPLATEPATH ); if( pFilter ) xFilterManager->appendFilter( pFilter->GetUIName(), pFilter->GetDefaultExtension() ); pFilter = aMatch.GetFilter4ClipBoardId( SOT_FORMATSTR_ID_STARDRAW_40, SFX_FILTER_TEMPLATEPATH ); if( pFilter ) xFilterManager->appendFilter( pFilter->GetUIName(), pFilter->GetDefaultExtension() ); pFilter = aMatch.GetFilter4ClipBoardId( SOT_FORMATSTR_ID_STARDRAW, SFX_FILTER_IMPORT, SFX_FILTER_TEMPLATEPATH ); if( pFilter ) xFilterManager->appendFilter( pFilter->GetUIName(), pFilter->GetDefaultExtension() ); pFilter = aMatch.GetFilter4ClipBoardId( SOT_FORMATSTR_ID_STARDRAW, SFX_FILTER_TEMPLATEPATH ); if( pFilter ) xFilterManager->appendFilter( pFilter->GetUIName(), pFilter->GetDefaultExtension() ); // add additional supported filters ::std::vector< String >::const_iterator aIter( aFilterVector.begin() ); while( aIter != aFilterVector.end() ) { if( ( pFilter = rMatcher.GetFilter4Mime( *aIter ) ) != NULL ) xFilterManager->appendFilter( pFilter->GetUIName(), pFilter->GetDefaultExtension() ); ++aIter; } } catch(IllegalArgumentException) { } } if( aFileDialog.Execute() != ERRCODE_NONE ) return; else { aFilterName = aFileDialog.GetCurrentFilter(); aFile = aFileDialog.GetPath(); } } else { SFX_REQUEST_ARG (rReq, pFileName, SfxStringItem, ID_VAL_DUMMY0, sal_False); SFX_REQUEST_ARG (rReq, pFilterName, SfxStringItem, ID_VAL_DUMMY1, sal_False); aFile = pFileName->GetValue (); if( pFilterName ) aFilterName = pFilterName->GetValue (); } mpDocSh->SetWaitCursor( sal_True ); SfxMedium* pMedium = new SfxMedium( aFile, STREAM_READ | STREAM_NOCREATE, sal_False ); const SfxFilter* pFilter = NULL; SFX_APP()->GetFilterMatcher().GuessFilter( *pMedium, &pFilter, SFX_FILTER_IMPORT, SFX_FILTER_NOTINSTALLED | SFX_FILTER_EXECUTABLE ); sal_Bool bDrawMode = mpViewShell && mpViewShell->ISA(DrawViewShell); sal_Bool bInserted = sal_False; if( pFilter ) { pMedium->SetFilter( pFilter ); aFilterName = pFilter->GetFilterName(); if( pMedium->IsStorage() || ( pMedium->GetInStream() && SotStorage::IsStorageFile( pMedium->GetInStream() ) ) ) { if ( pFilter->GetServiceName().EqualsAscii( "com.sun.star.presentation.PresentationDocument" ) || pFilter->GetServiceName().EqualsAscii( "com.sun.star.drawing.DrawingDocument" ) ) { // Draw, Impress or PowerPoint document // the ownership of the Medium is transferred if( bDrawMode ) InsSDDinDrMode( pMedium ); else InsSDDinOlMode( pMedium ); // don't delete Medium here, ownership of pMedium has changed in this case bInserted = sal_True; } } else { sal_Bool bFound = ( ::std::find( aFilterVector.begin(), aFilterVector.end(), pFilter->GetMimeType() ) != aFilterVector.end() ); if( !bFound && ( aFilterName.SearchAscii( "Text" ) != STRING_NOTFOUND || aFilterName.SearchAscii( "Rich" ) != STRING_NOTFOUND || aFilterName.SearchAscii( "RTF" ) != STRING_NOTFOUND || aFilterName.SearchAscii( "HTML" ) != STRING_NOTFOUND ) ) { bFound = sal_True; } if( bFound ) { if( bDrawMode ) InsTextOrRTFinDrMode(pMedium); else InsTextOrRTFinOlMode(pMedium); bInserted = sal_True; delete pMedium; } } } mpDocSh->SetWaitCursor( sal_False ); if( !bInserted ) { ErrorBox aErrorBox( mpWindow, WB_OK, String( SdResId( STR_READ_DATA_ERROR ) ) ); aErrorBox.Execute(); delete pMedium; } } // ----------------------------------------------------------------------------- sal_Bool FuInsertFile::InsSDDinDrMode(SfxMedium* pMedium) { sal_Bool bOK = sal_False; // Liste mit Seitennamen (wenn NULL, dann alle Seiten) List* pBookmarkList = NULL; mpDocSh->SetWaitCursor( sal_False ); SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create(); AbstractSdInsertPagesObjsDlg* pDlg = pFact ? pFact->CreateSdInsertPagesObjsDlg( NULL, mpDoc, pMedium, aFile ) : 0; if( !pDlg ) return sal_False; // Ev. wird eine QueryBox geoeffnet ("Links aktualisieren?"), // daher wird der Dialog der aktuelle DefModalDialogParent ::Window* pDefParent = GetpApp()->GetDefDialogParent(); GetpApp()->SetDefDialogParent(pDlg->GetWindow()); sal_uInt16 nRet = pDlg->Execute(); GetpApp()->SetDefDialogParent(pDefParent); mpDocSh->SetWaitCursor( sal_True ); if( nRet == RET_OK ) { // Zuerst Seiten einfuegen pBookmarkList = pDlg->GetList( 1 ); // Seiten sal_Bool bLink = pDlg->IsLink(); sal_Bool bReplace = sal_False; SdPage* pPage = NULL; ::sd::View* pView = mpViewShell->GetView(); if (pView->ISA(OutlineView)) { pPage = static_cast<OutlineView*>(pView)->GetActualPage(); } else { pPage = static_cast<SdPage*>(pView->GetSdrPageView()->GetPage()); } sal_uInt16 nPos = 0xFFFF; if (pPage && !pPage->IsMasterPage()) { if (pPage->GetPageKind() == PK_STANDARD) { nPos = pPage->GetPageNum() + 2; } else if (pPage->GetPageKind() == PK_NOTES) { nPos = pPage->GetPageNum() + 1; } } sal_Bool bNameOK; List* pObjectBookmarkList = pDlg->GetList( 2 ); // Objekte List* pExchangeList = NULL; // Es werden ausgewaehlte Seiten und/oder ausgewaehlte Objekte oder // alles eingefuegt, wenn pBookmarkList NULL ist! if( pBookmarkList || !pObjectBookmarkList ) { // Um zu gewaehrleisten, dass alle Seitennamen eindeutig sind, werden // die einzufuegenden geprueft und gegebenenfalls in einer Ersatzliste // aufgenommen // bNameOK == sal_False -> Benutzer hat abgebrochen bNameOK = mpView->GetExchangeList( pExchangeList, pBookmarkList, 0 ); if( bNameOK ) bOK = mpDoc->InsertBookmarkAsPage( pBookmarkList, pExchangeList, bLink, bReplace, nPos, sal_False, NULL, sal_True, sal_True, sal_False ); // Loeschen der BookmarkList if( pBookmarkList ) { String* pString = (String*) pBookmarkList->First(); while( pString ) { delete pString; pString = (String*) pBookmarkList->Next(); } delete pBookmarkList; pBookmarkList = NULL; } // Loeschen der ExchangeList if( pExchangeList ) { String* pString = (String*) pExchangeList->First(); while( pString ) { delete pString; pString = (String*) pExchangeList->Next(); } delete pExchangeList; pExchangeList = NULL; } } // Dann Objekte einfuegen //pBookmarkList = pDlg->GetList( 2 ); // Objekte pBookmarkList = pObjectBookmarkList; // Um zu gewaehrleisten... (s.o.) bNameOK = mpView->GetExchangeList( pExchangeList, pBookmarkList, 1 ); if( bNameOK ) bOK = mpDoc->InsertBookmarkAsObject( pBookmarkList, pExchangeList, bLink, NULL, NULL); // Loeschen der BookmarkList if( pBookmarkList ) { String* pString = (String*) pBookmarkList->First(); while( pString ) { delete pString; pString = (String*) pBookmarkList->Next(); } delete pBookmarkList; pBookmarkList = NULL; } // Loeschen der ExchangeList if( pExchangeList ) { String* pString = (String*) pExchangeList->First(); while( pString ) { delete pString; pString = (String*) pExchangeList->Next(); } delete pExchangeList; pExchangeList = NULL; } if( pDlg->IsRemoveUnnessesaryMasterPages() ) mpDoc->RemoveUnnecessaryMasterPages(); } delete pDlg; return (bOK); } // ----------------------------------------------------------------------------- void FuInsertFile::InsTextOrRTFinDrMode(SfxMedium* pMedium) { SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create(); AbstractSdInsertPagesObjsDlg* pDlg = pFact ? pFact->CreateSdInsertPagesObjsDlg(NULL, mpDoc, NULL, aFile ) : 0; if( !pDlg ) return; mpDocSh->SetWaitCursor( sal_False ); sal_uInt16 nRet = pDlg->Execute(); mpDocSh->SetWaitCursor( sal_True ); if( nRet == RET_OK ) { // gewaehltes Dateiformat: Text oder RTF oder HTML (Default ist Text) sal_uInt16 nFormat = EE_FORMAT_TEXT; if( aFilterName.SearchAscii( "Rich") != STRING_NOTFOUND ) nFormat = EE_FORMAT_RTF; else if( aFilterName.SearchAscii( "HTML" ) != STRING_NOTFOUND ) nFormat = EE_FORMAT_HTML; // einen eigenen Outliner erzeugen, denn: // der Dokument-Outliner koennte gerade vom Gliederungsmodus // benutzt werden; // der Draw-Outliner der Drawing Engine koennte zwischendurch // was zeichnen muessen; // der globale Outliner koennte in SdPage::CreatePresObj // benutzt werden // SfxItemPool* pPool = mpDoc->GetDrawOutliner().GetEmptyItemSet().GetPool(); SdrOutliner* pOutliner = new ::sd::Outliner( mpDoc, OUTLINERMODE_TEXTOBJECT ); // pOutliner->SetStyleSheetPool((SfxStyleSheetPool*)mpDoc->GetStyleSheetPool()); // pOutliner->SetEditTextObjectPool(pPool); // pOutliner->SetForbiddenCharsTable( mpDoc->GetForbiddenCharsTable() ); // Referenz-Device setzen pOutliner->SetRefDevice( SD_MOD()->GetRefDevice( *mpDocSh ) ); SdPage* pPage = static_cast<DrawViewShell*>(mpViewShell)->GetActualPage(); aLayoutName = pPage->GetLayoutName(); aLayoutName.Erase(aLayoutName.SearchAscii(SD_LT_SEPARATOR)); pOutliner->SetPaperSize(pPage->GetSize()); SvStream* pStream = pMedium->GetInStream(); DBG_ASSERT( pStream, "Kein InStream!" ); pStream->Seek( 0 ); sal_uLong nErr = pOutliner->Read( *pStream, pMedium->GetBaseURL(), nFormat, mpDocSh->GetHeaderAttributes() ); if (nErr || !pOutliner->GetEditEngine().GetText().Len()) { ErrorBox aErrorBox( mpWindow, (WinBits)WB_OK, String(SdResId(STR_READ_DATA_ERROR))); aErrorBox.Execute(); } else { // ist es eine Masterpage? if (static_cast<DrawViewShell*>(mpViewShell)->GetEditMode() == EM_MASTERPAGE && !pPage->IsMasterPage()) { pPage = (SdPage*)(&(pPage->TRG_GetMasterPage())); } DBG_ASSERT(pPage, "Seite nicht gefunden"); // wenn gerade editiert wird, in dieses Textobjekt einfliessen lassen OutlinerView* pOutlinerView = mpView->GetTextEditOutlinerView(); if( pOutlinerView ) { SdrObject* pObj = mpView->GetTextEditObject(); if( pObj && pObj->GetObjInventor() == SdrInventor && pObj->GetObjIdentifier() == OBJ_TITLETEXT && pOutliner->GetParagraphCount() > 1 ) { // In Titelobjekten darf nur ein Absatz vorhanden sein while ( pOutliner->GetParagraphCount() > 1 ) { Paragraph* pPara = pOutliner->GetParagraph( 0 ); sal_uLong nLen = pOutliner->GetText( pPara, 1 ).Len(); pOutliner->QuickDelete( ESelection( 0, (sal_uInt16) nLen, 1, 0 ) ); pOutliner->QuickInsertLineBreak( ESelection( 0, (sal_uInt16) nLen, 0, (sal_uInt16) nLen ) ); } } } OutlinerParaObject* pOPO = pOutliner->CreateParaObject(); if (pOutlinerView) { pOutlinerView->InsertText(*pOPO); } else { SdrRectObj* pTO = new SdrRectObj(OBJ_TEXT); pTO->SetOutlinerParaObject(pOPO); const bool bUndo = mpView->IsUndoEnabled(); if( bUndo ) mpView->BegUndo(String(SdResId(STR_UNDO_INSERT_TEXTFRAME))); pPage->InsertObject(pTO); // koennte groesser sein als die max. erlaubte Groesse: // falls noetig, die Objektgroesse begrenzen Size aSize(pOutliner->CalcTextSize()); Size aMaxSize = mpDoc->GetMaxObjSize(); aSize.Height() = Min(aSize.Height(), aMaxSize.Height()); aSize.Width() = Min(aSize.Width(), aMaxSize.Width()); aSize = mpWindow->LogicToPixel(aSize); // in der Mitte des Fensters absetzen Size aTemp(mpWindow->GetOutputSizePixel()); Point aPos(aTemp.Width() / 2, aTemp.Height() / 2); aPos.X() -= aSize.Width() / 2; aPos.Y() -= aSize.Height() / 2; aSize = mpWindow->PixelToLogic(aSize); aPos = mpWindow->PixelToLogic(aPos); pTO->SetLogicRect(Rectangle(aPos, aSize)); if (pDlg->IsLink()) { pTO->SetTextLink(aFile, aFilterName, gsl_getSystemTextEncoding() ); } if( bUndo ) { mpView->AddUndo(mpDoc->GetSdrUndoFactory().CreateUndoInsertObject(*pTO)); mpView->EndUndo(); } } } delete pOutliner; } delete pDlg; } // ----------------------------------------------------------------------------- void FuInsertFile::InsTextOrRTFinOlMode(SfxMedium* pMedium) { // gewaehltes Dateiformat: Text oder RTF oder HTML (Default ist Text) sal_uInt16 nFormat = EE_FORMAT_TEXT; if( aFilterName.SearchAscii( "Rich") != STRING_NOTFOUND ) nFormat = EE_FORMAT_RTF; else if( aFilterName.SearchAscii( "HTML" ) != STRING_NOTFOUND ) nFormat = EE_FORMAT_HTML; ::Outliner* pDocliner = static_cast<OutlineView*>(mpView)->GetOutliner(); List* pList = pDocliner->GetView(0)->CreateSelectionList(); Paragraph* pPara = (Paragraph*)pList->First(); // wo soll eingefuegt werden? while( !pDocliner->HasParaFlag( pPara, PARAFLAG_ISPAGE ) ) { pPara = pDocliner->GetParent(pPara); } sal_uLong nTargetPos = pDocliner->GetAbsPos(pPara) + 1; // Layout der Vorgaengerseite uebernehmen sal_uInt16 nPage = 0; pPara = pDocliner->GetParagraph( pDocliner->GetAbsPos( pPara ) - 1 ); while (pPara) { sal_uLong nPos = pDocliner->GetAbsPos( pPara ); if ( pDocliner->HasParaFlag( pPara, PARAFLAG_ISPAGE ) ) nPage++; pPara = pDocliner->GetParagraph( nPos - 1 ); } SdPage* pPage = mpDoc->GetSdPage(nPage, PK_STANDARD); aLayoutName = pPage->GetLayoutName(); aLayoutName.Erase(aLayoutName.SearchAscii(SD_LT_SEPARATOR)); // einen eigenen Outliner erzeugen, denn: // der Dokument-Outliner koennte gerade vom Gliederungsmodus // benutzt werden; // der Draw-Outliner der Drawing Engine koennte zwischendurch // was zeichnen muessen; // der globale Outliner koennte in SdPage::CreatePresObj // benutzt werden ::Outliner* pOutliner = new ::Outliner( &mpDoc->GetItemPool(), OUTLINERMODE_OUTLINEOBJECT ); pOutliner->SetStyleSheetPool((SfxStyleSheetPool*)mpDoc->GetStyleSheetPool()); // Referenz-Device setzen pOutliner->SetRefDevice(SD_MOD()->GetRefDevice( *mpDocSh )); pOutliner->SetPaperSize(Size(0x7fffffff, 0x7fffffff)); SvStream* pStream = pMedium->GetInStream(); DBG_ASSERT( pStream, "Kein InStream!" ); pStream->Seek( 0 ); sal_uLong nErr = pOutliner->Read(*pStream, pMedium->GetBaseURL(), nFormat, mpDocSh->GetHeaderAttributes()); if (nErr || !pOutliner->GetEditEngine().GetText().Len()) { ErrorBox aErrorBox( mpWindow, (WinBits)WB_OK, String(SdResId(STR_READ_DATA_ERROR))); aErrorBox.Execute(); } else { sal_uLong nParaCount = pOutliner->GetParagraphCount(); // fuer Fortschrittsanzeige: Anzahl der Ebene-0-Absaetze sal_uInt16 nNewPages = 0; pPara = pOutliner->GetParagraph( 0 ); while (pPara) { sal_uLong nPos = pOutliner->GetAbsPos( pPara ); if( pOutliner->HasParaFlag( pPara, PARAFLAG_ISPAGE ) ) nNewPages++; pPara = pOutliner->GetParagraph( ++nPos ); } mpDocSh->SetWaitCursor( sal_False ); SfxProgress* pProgress = new SfxProgress( mpDocSh, String( SdResId(STR_CREATE_PAGES)), nNewPages); if( pProgress ) pProgress->SetState( 0, 100 ); nNewPages = 0; pDocliner->GetUndoManager().EnterListAction( String(SdResId(STR_UNDO_INSERT_FILE)), String() ); sal_uLong nSourcePos = 0; SfxStyleSheet* pStyleSheet = pPage->GetStyleSheetForPresObj( PRESOBJ_OUTLINE ); Paragraph* pSourcePara = pOutliner->GetParagraph( 0 ); while (pSourcePara) { sal_uLong nPos = pOutliner->GetAbsPos( pSourcePara ); sal_Int16 nDepth = pOutliner->GetDepth( (sal_uInt16) nPos ); // den letzte Absatz nur uebernehmen, wenn er gefuellt ist if (nSourcePos < nParaCount - 1 || pOutliner->GetText(pSourcePara).Len() > 0) { pDocliner->Insert( pOutliner->GetText(pSourcePara), nTargetPos, nDepth ); String aStyleSheetName( pStyleSheet->GetName() ); aStyleSheetName.Erase( aStyleSheetName.Len()-1, 1 ); aStyleSheetName += String::CreateFromInt32( nDepth <= 0 ? 1 : nDepth+1 ); SfxStyleSheetBasePool* pStylePool = mpDoc->GetStyleSheetPool(); SfxStyleSheet* pOutlStyle = (SfxStyleSheet*) pStylePool->Find( aStyleSheetName, pStyleSheet->GetFamily() ); pDocliner->SetStyleSheet( nTargetPos, pOutlStyle ); } if( pDocliner->HasParaFlag( pSourcePara, PARAFLAG_ISPAGE ) ) { nNewPages++; if( pProgress ) pProgress->SetState( nNewPages ); } pSourcePara = pOutliner->GetParagraph( ++nPos ); nTargetPos++; nSourcePos++; } pDocliner->GetUndoManager().LeaveListAction(); if( pProgress ) delete pProgress; mpDocSh->SetWaitCursor( sal_True ); } delete pOutliner; } // ----------------------------------------------------------------------------- sal_Bool FuInsertFile::InsSDDinOlMode(SfxMedium* pMedium) { OutlineView* pOlView = static_cast<OutlineView*>(mpView); // Outliner-Inhalte ins SdDrawDocument uebertragen pOlView->PrepareClose(); // einlesen wie im Zeichenmodus if (InsSDDinDrMode(pMedium)) { ::Outliner* pOutliner = pOlView->GetViewByWindow(mpWindow)->GetOutliner(); // Benachrichtigungs-Links temporaer trennen Link aOldParagraphInsertedHdl = pOutliner->GetParaInsertedHdl(); pOutliner->SetParaInsertedHdl( Link(NULL, NULL)); Link aOldParagraphRemovingHdl = pOutliner->GetParaRemovingHdl(); pOutliner->SetParaRemovingHdl( Link(NULL, NULL)); Link aOldDepthChangedHdl = pOutliner->GetDepthChangedHdl(); pOutliner->SetDepthChangedHdl( Link(NULL, NULL)); Link aOldBeginMovingHdl = pOutliner->GetBeginMovingHdl(); pOutliner->SetBeginMovingHdl( Link(NULL, NULL)); Link aOldEndMovingHdl = pOutliner->GetEndMovingHdl(); pOutliner->SetEndMovingHdl( Link(NULL, NULL)); Link aOldStatusEventHdl = pOutliner->GetStatusEventHdl(); pOutliner->SetStatusEventHdl(Link(NULL, NULL)); pOutliner->Clear(); pOlView->FillOutliner(); // Links wieder setzen pOutliner->SetParaInsertedHdl(aOldParagraphInsertedHdl); pOutliner->SetParaRemovingHdl(aOldParagraphRemovingHdl); pOutliner->SetDepthChangedHdl(aOldDepthChangedHdl); pOutliner->SetBeginMovingHdl(aOldBeginMovingHdl); pOutliner->SetEndMovingHdl(aOldEndMovingHdl); pOutliner->SetStatusEventHdl(aOldStatusEventHdl); return sal_True; } else return sal_False; } // ----------------------------------------------------------------------------- void FuInsertFile::GetSupportedFilterVector( ::std::vector< String >& rFilterVector ) { SfxFilterMatcher& rMatcher = SFX_APP()->GetFilterMatcher(); const SfxFilter* pSearchFilter = NULL; rFilterVector.clear(); if( ( pSearchFilter = rMatcher.GetFilter4Mime( UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "text/plain" ) ) ) ) != NULL ) rFilterVector.push_back( pSearchFilter->GetMimeType() ); if( ( pSearchFilter = rMatcher.GetFilter4Mime( UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "application/rtf" ) ) ) ) != NULL ) rFilterVector.push_back( pSearchFilter->GetMimeType() ); if( ( pSearchFilter = rMatcher.GetFilter4Mime( UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "text/html" ) ) ) ) != NULL ) rFilterVector.push_back( pSearchFilter->GetMimeType() ); } } // end of namespace sd
33.867235
139
0.667722
[ "vector" ]
5532acc38cc136967489107863d71da456057191
5,011
cpp
C++
transformsystem.cpp
nvpro-samples/gl_cadscene_rendertechniques
70becfc08318c54c2de45f1791e6c7f821144029
[ "Apache-2.0" ]
134
2015-01-09T13:00:56.000Z
2022-02-06T06:23:25.000Z
transformsystem.cpp
nvpro-samples/gl_cadscene_rendertechniques
70becfc08318c54c2de45f1791e6c7f821144029
[ "Apache-2.0" ]
4
2015-08-23T17:44:59.000Z
2019-11-14T14:08:27.000Z
transformsystem.cpp
nvpro-samples/gl_cadscene_rendertechniques
70becfc08318c54c2de45f1791e6c7f821144029
[ "Apache-2.0" ]
38
2015-02-13T22:27:09.000Z
2021-10-16T00:36:26.000Z
/* * Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-FileCopyrightText: Copyright (c) 2014-2021 NVIDIA CORPORATION * SPDX-License-Identifier: Apache-2.0 */ /* Contact ckubisch@nvidia.com (Christoph Kubisch) for feedback */ #include <assert.h> #include "transformsystem.hpp" #include <nvgl/base_gl.hpp> void TransformSystem::process(const NodeTree& nodeTree, Buffer& ids, Buffer& matricesObject, Buffer& matricesWorld ) { glUseProgram(m_programs.transform_leaves); glBindBuffer (GL_SHADER_STORAGE_BUFFER, m_scratchGL); glBufferData (GL_SHADER_STORAGE_BUFFER, sizeof(GLuint)*nodeTree.getNumActiveNodes(),NULL,GL_STREAM_DRAW); #if 0 // APIC hack glTextureBufferEXT(m_texsGL[TEXTURE_IDS], GL_TEXTURE_BUFFER, GL_R32I, ids.buffer); glTextureBufferEXT(m_texsGL[TEXTURE_OBJECT],GL_TEXTURE_BUFFER, GL_RGBA32F, matricesObject.buffer); glTextureBufferEXT(m_texsGL[TEXTURE_WORLD], GL_TEXTURE_BUFFER, GL_RGBA32F, matricesWorld.buffer); #else glTextureBufferRange(m_texsGL[TEXTURE_IDS], GL_R32I, ids.buffer, ids.offset, ids.size); glTextureBufferRange(m_texsGL[TEXTURE_OBJECT], GL_RGBA32F, matricesObject.buffer, matricesObject.offset, matricesObject.size); glTextureBufferRange(m_texsGL[TEXTURE_WORLD], GL_RGBA32F, matricesWorld.buffer, matricesWorld.offset, matricesWorld.size); #endif for (int i = 0; i < TEXTURES; i++){ nvgl::bindMultiTexture(GL_TEXTURE0 + i, GL_TEXTURE_BUFFER, m_texsGL[i]); } matricesWorld.BindBufferRange(GL_SHADER_STORAGE_BUFFER,0); matricesObject.BindBufferRange(GL_SHADER_STORAGE_BUFFER,1); glBindBufferBase(GL_SHADER_STORAGE_BUFFER,2,m_scratchGL); const int maxshaderlevels = 10; int maxlevels = maxshaderlevels; int totalNodes = 0; bool useLeaves = true; int currentDepth = 1; const NodeTree::Level* level = nodeTree.getUsedLevel(currentDepth); // TODO: // // This code lacks a proper heuristic for switching between level and leaves based processing. // One should prefer level if there is enough nodes per level, otherwise descend and gather // many leaves from multiple levels. // while (level){ // dispatch on last level, or if we have reached maxlevels bool willdispatch = currentDepth && (!nodeTree.getUsedLevel(currentDepth+1) || currentDepth+1 % maxlevels == 0); // the last level in leaf mode, must use all level nodes, and not just the leaves of this level // as subsequent leaves operate in level mode const std::vector<NodeTree::nodeID>& nodes = useLeaves && !willdispatch ? level->leaves : level->nodes; if (!nodes.empty()){ glBufferSubData(GL_SHADER_STORAGE_BUFFER,totalNodes*sizeof(GLuint),sizeof(GLuint)*nodes.size(),&nodes[0]); totalNodes += (int)nodes.size(); } currentDepth++; level = nodeTree.getUsedLevel(currentDepth); if (willdispatch){ int groupsize = useLeaves ? m_leavesGroup : m_levelsGroup; if (useLeaves){ glUniform1i(0,totalNodes); glUniform1i(1,1); } else{ glUniform1i(0,totalNodes); } glDispatchCompute((totalNodes+groupsize-1)/groupsize,1,1); glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT | GL_TEXTURE_FETCH_BARRIER_BIT); if (useLeaves){ // switch to per-level mode after first batch of leaves is over (tip of hierarchy) glUseProgram(m_programs.transform_level); useLeaves = false; maxlevels = 1; // assure we dispatch every level } totalNodes = 0; } } glUseProgram(0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER,0,0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER,1,0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER,2,0); for (int i = 0; i < TEXTURES; i++){ nvgl::bindMultiTexture(GL_TEXTURE0 + i, GL_TEXTURE_BUFFER, 0); } } void TransformSystem::init( const Programs &programs ) { m_programs = programs; glCreateBuffers(1,&m_scratchGL); glCreateTextures(GL_TEXTURE_BUFFER, TEXTURES, m_texsGL); } void TransformSystem::deinit() { glDeleteBuffers(1,&m_scratchGL); glDeleteTextures(TEXTURES,m_texsGL); } void TransformSystem::update( const Programs &programs ) { m_programs = programs; GLuint groupsizes[3]; glGetProgramiv(programs.transform_leaves, GL_COMPUTE_WORK_GROUP_SIZE, (GLint*)groupsizes); m_leavesGroup = groupsizes[0]; glGetProgramiv(programs.transform_level, GL_COMPUTE_WORK_GROUP_SIZE, (GLint*)groupsizes); m_levelsGroup = groupsizes[0]; }
34.798611
129
0.735981
[ "vector" ]
5534141f72a5c61a88cbd9ab80890aef8b1d259c
1,176
cpp
C++
Application.cpp
Teeson4/Gong
4104e3389971072b7b43855f8a872d691ecc212e
[ "Apache-2.0" ]
1
2020-06-30T22:47:06.000Z
2020-06-30T22:47:06.000Z
Application.cpp
Teeson4/Gong
4104e3389971072b7b43855f8a872d691ecc212e
[ "Apache-2.0" ]
null
null
null
Application.cpp
Teeson4/Gong
4104e3389971072b7b43855f8a872d691ecc212e
[ "Apache-2.0" ]
null
null
null
#include "Game.h" #include "Timer.h" #define APP_TAG "Application" const int FPS = 60; const int DELAY_TIME = FPS / 1000; int main(int argc, char* args[]) { Timer initTimer; initTimer.start(); if (!g_Game->create()) { Logger::error(APP_TAG, "Failed to create Game."); } else { Logger::info(APP_TAG, "Successfully created Game."); if (!g_Game->init()) { Logger::error(APP_TAG, "Failed to initialize Game."); } else { std::cout << "[Application] (INFO) Done! Successfully initialized in " << initTimer.getTicks() << " ms." << std::endl; initTimer.stop(); float deltaTime = 0; Uint32 ticksCount = 0; while (g_Game->isRunning()) { if(g_Game->isSlowMode()) deltaTime = (SDL_GetTicks() - ticksCount) / 3000.f; else deltaTime = (SDL_GetTicks() - ticksCount) / 1000.f; ticksCount = SDL_GetTicks(); g_Game->input(deltaTime); g_Game->update(deltaTime); g_Game->render(); } } } Logger::info(APP_TAG, "Disposing all resources..."); g_Game->dispose(); Logger::info(APP_TAG, "Successfully disposed and closed game."); return 0; }
19.6
122
0.60034
[ "render" ]
553ad08ef40acee38b060d456720a393246a3750
903
cpp
C++
examples/common/straight_line_measurements.cpp
ThorsteinnJonsson/kalman-cpp
cb4ee483c32f051d4964d46d7f7858ca1f54a8ae
[ "MIT" ]
null
null
null
examples/common/straight_line_measurements.cpp
ThorsteinnJonsson/kalman-cpp
cb4ee483c32f051d4964d46d7f7858ca1f54a8ae
[ "MIT" ]
null
null
null
examples/common/straight_line_measurements.cpp
ThorsteinnJonsson/kalman-cpp
cb4ee483c32f051d4964d46d7f7858ca1f54a8ae
[ "MIT" ]
null
null
null
#include "straight_line_measurements.h" std::vector<Measurement> GenerateStraightLineMeasurements(float meas_var, float process_var, float dt, size_t count) { std::random_device rd{}; std::mt19937 gen{rd()}; std::normal_distribution<float> dist; float pos = 0.0f; float vel = 1.0f; float meas_std = std::sqrt(meas_var); float process_std = std::sqrt(process_var); std::vector<Measurement> measurements; measurements.reserve(count); for (size_t i = 0; i < count; ++i) { Measurement m; float v = vel + dist(gen) * process_std; pos += v * dt; m.ground_truth = pos; m.value = pos + dist(gen) * meas_std; m.timestamp = dt * i; measurements.push_back(m); } return measurements; }
31.137931
76
0.545958
[ "vector" ]
553d81f574f901fe3bb5da04c4e226f84fd304c9
357
cpp
C++
lec_04/recursive_sum.cpp
diable201/Grokking_Algorithms
2597b93a91ec5aabc06f9791b42de03f7d01656b
[ "MIT" ]
1
2020-09-11T10:25:32.000Z
2020-09-11T10:25:32.000Z
lec_04/recursive_sum.cpp
diable201/Grokking_Algorithms
2597b93a91ec5aabc06f9791b42de03f7d01656b
[ "MIT" ]
null
null
null
lec_04/recursive_sum.cpp
diable201/Grokking_Algorithms
2597b93a91ec5aabc06f9791b42de03f7d01656b
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; template <typename T> T recursive_sum(vector<T> arr) { if (arr.empty()) return 0; T last_num = arr.back(); arr.pop_back(); return last_num + recursive_sum(arr); } int main() { vector<int> arr_int = {1, 4, 2, 5, 7}; cout << recursive_sum(arr_int) << "\n"; return 0; }
18.789474
43
0.616246
[ "vector" ]
553e8b035241c7bcea83f4a8b7c17dc4f095da3d
4,184
cpp
C++
common/graph_opts/phi_node_removal.cpp
Sacusa/ALADDIN
45ff9ab7edf84dfa964bc870f0c3634d1a4c55fb
[ "BSD-3-Clause" ]
82
2015-04-12T17:29:48.000Z
2020-06-19T00:33:51.000Z
common/graph_opts/phi_node_removal.cpp
Sacusa/ALADDIN
45ff9ab7edf84dfa964bc870f0c3634d1a4c55fb
[ "BSD-3-Clause" ]
31
2015-05-13T09:43:00.000Z
2020-06-20T16:26:06.000Z
common/graph_opts/phi_node_removal.cpp
Sacusa/ALADDIN
45ff9ab7edf84dfa964bc870f0c3634d1a4c55fb
[ "BSD-3-Clause" ]
47
2015-02-10T02:37:11.000Z
2020-06-04T01:24:01.000Z
#include "phi_node_removal.h" // Phi node removal. // // Phi nodes are useful in static compiler analysis but do not need to be // accounted for during simulation. Remove all phi nodes and attach the phi // node's parent to all of its children. std::string PhiNodeRemoval::getCenteredName(size_t size) { return " Remove PHI and Convert Nodes "; } void PhiNodeRemoval::optimize() { EdgeNameMap edge_to_parid = get(boost::edge_name, graph); std::set<Edge> to_remove_edges; std::vector<NewEdge> to_add_edges; std::unordered_set<ExecNode*> checked_phi_nodes; for (auto node_it = exec_nodes.rbegin(); node_it != exec_nodes.rend(); node_it++) { ExecNode* node = node_it->second; if (!node->has_vertex() || (!node->is_phi_op() && !node->is_convert_op()) || (checked_phi_nodes.find(node) != checked_phi_nodes.end())) continue; Vertex node_vertex = node->get_vertex(); // find its children std::vector<std::pair<ExecNode*, int>> phi_child; out_edge_iter out_edge_it, out_edge_end; for (boost::tie(out_edge_it, out_edge_end) = out_edges(node_vertex, graph); out_edge_it != out_edge_end; ++out_edge_it) { checked_phi_nodes.insert(node); to_remove_edges.insert(*out_edge_it); Vertex v = target(*out_edge_it, graph); phi_child.push_back( std::make_pair(getNodeFromVertex(v), edge_to_parid[*out_edge_it])); } if (phi_child.size() == 0 || boost::in_degree(node_vertex, graph) == 0) continue; if (node->is_phi_op()) { // find its first non-phi ancestor. // phi node can have multiple children, but it can only have one parent. assert(boost::in_degree(node_vertex, graph) == 1); in_edge_iter in_edge_it = in_edges(node_vertex, graph).first; Vertex parent_vertex = source(*in_edge_it, graph); ExecNode* nonphi_ancestor = getNodeFromVertex(parent_vertex); // Search for the first non-phi ancestor of the current phi node. while (nonphi_ancestor->is_phi_op()) { assert(nonphi_ancestor->has_vertex()); Vertex parent_vertex = nonphi_ancestor->get_vertex(); if (boost::in_degree(parent_vertex, graph) == 0) break; to_remove_edges.insert(*in_edge_it); in_edge_it = in_edges(parent_vertex, graph).first; parent_vertex = source(*in_edge_it, graph); nonphi_ancestor = getNodeFromVertex(parent_vertex); } to_remove_edges.insert(*in_edge_it); if (!nonphi_ancestor->is_phi_op()) { // Add dependence between the current phi node's children and its first // non-phi ancestor. for (auto child_it = phi_child.begin(), chil_E = phi_child.end(); child_it != chil_E; ++child_it) { to_add_edges.push_back( { nonphi_ancestor, child_it->first, child_it->second }); } } } else { // convert nodes assert(boost::in_degree(node_vertex, graph) == 1); in_edge_iter in_edge_it = in_edges(node_vertex, graph).first; Vertex parent_vertex = source(*in_edge_it, graph); ExecNode* nonphi_ancestor = getNodeFromVertex(parent_vertex); while (nonphi_ancestor->is_convert_op() || nonphi_ancestor->is_phi_op()) { Vertex parent_vertex = nonphi_ancestor->get_vertex(); if (boost::in_degree(parent_vertex, graph) == 0) break; to_remove_edges.insert(*in_edge_it); in_edge_it = in_edges(parent_vertex, graph).first; parent_vertex = source(*in_edge_it, graph); nonphi_ancestor = getNodeFromVertex(parent_vertex); } to_remove_edges.insert(*in_edge_it); if (!nonphi_ancestor->is_convert_op() && !nonphi_ancestor->is_phi_op()) { for (auto child_it = phi_child.begin(), chil_E = phi_child.end(); child_it != chil_E; ++child_it) { to_add_edges.push_back( { nonphi_ancestor, child_it->first, child_it->second }); } } } std::vector<std::pair<ExecNode*, int>>().swap(phi_child); } updateGraphWithIsolatedEdges(to_remove_edges); updateGraphWithNewEdges(to_add_edges); cleanLeafNodes(); }
41.425743
80
0.6587
[ "vector" ]
553ea5d8af1547712abc82255b76d4b17b80f390
385,088
cpp
C++
hipify-clang/src/Cuda2Hip.cpp
scchan/HIP
2db70fe5fdc701e1eedc73bea1d247cda855ef05
[ "MIT" ]
null
null
null
hipify-clang/src/Cuda2Hip.cpp
scchan/HIP
2db70fe5fdc701e1eedc73bea1d247cda855ef05
[ "MIT" ]
1
2019-04-26T12:23:00.000Z
2019-05-15T14:49:19.000Z
hipify-clang/src/Cuda2Hip.cpp
scchan/HIP
2db70fe5fdc701e1eedc73bea1d247cda855ef05
[ "MIT" ]
null
null
null
/* Copyright (c) 2015-2017 Advanced Micro Devices, Inc. All rights reserved. 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. */ /** * @file Cuda2Hip.cpp * * This file is compiled and linked into clang based hipify tool. */ #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Basic/SourceManager.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/Lex/Lexer.h" #include "clang/Lex/MacroArgs.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/PPCallbacks.h" #include "clang/Lex/Preprocessor.h" #include "clang/Rewrite/Core/Rewriter.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Refactoring.h" #include "clang/Tooling/Tooling.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Signals.h" #include <cstdio> #include <fstream> #include <set> #include <cmath> #include <chrono> #include <iomanip> #include <sstream> using namespace clang; using namespace clang::ast_matchers; using namespace clang::tooling; using namespace llvm; #define DEBUG_TYPE "cuda2hip" #define HIP_UNSUPPORTED -1 enum ConvTypes { CONV_VERSION = 0, CONV_INIT, CONV_DEVICE, CONV_MEM, CONV_KERN, CONV_COORD_FUNC, CONV_MATH_FUNC, CONV_SPECIAL_FUNC, CONV_STREAM, CONV_EVENT, CONV_OCCUPANCY, CONV_CONTEXT, CONV_PEER, CONV_MODULE, CONV_CACHE, CONV_EXEC, CONV_ERROR, CONV_DEF, CONV_TEX, CONV_GL, CONV_GRAPHICS, CONV_SURFACE, CONV_JIT, CONV_D3D9, CONV_D3D10, CONV_D3D11, CONV_VDPAU, CONV_EGL, CONV_THREAD, CONV_OTHER, CONV_INCLUDE, CONV_INCLUDE_CUDA_MAIN_H, CONV_TYPE, CONV_LITERAL, CONV_NUMERIC_LITERAL, CONV_LAST }; const char *counterNames[CONV_LAST] = { "version", "init", "device", "mem", "kern", "coord_func", "math_func", "special_func", "stream", "event", "occupancy", "ctx", "peer", "module", "cache", "exec", "err", "def", "tex", "gl", "graphics", "surface", "jit", "d3d9", "d3d10", "d3d11", "vdpau", "egl", "thread", "other", "include", "include_cuda_main_header", "type", "literal", "numeric_literal"}; enum ApiTypes { API_DRIVER = 0, API_RUNTIME, API_BLAS, API_LAST }; const char *apiNames[API_LAST] = { "CUDA Driver API", "CUDA RT API", "CUBLAS API"}; // Set up the command line options static cl::OptionCategory ToolTemplateCategory("CUDA to HIP source translator options"); static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::cat(ToolTemplateCategory)); static cl::opt<bool> Inplace("inplace", cl::desc("Modify input file inplace, replacing input with hipified output, save backup in .prehip file"), cl::value_desc("inplace"), cl::cat(ToolTemplateCategory)); static cl::opt<bool> NoBackup("no-backup", cl::desc("Don't create a backup file for the hipified source"), cl::value_desc("no-backup"), cl::cat(ToolTemplateCategory)); static cl::opt<bool> NoOutput("no-output", cl::desc("Don't write any translated output to stdout"), cl::value_desc("no-output"), cl::cat(ToolTemplateCategory)); static cl::opt<bool> PrintStats("print-stats", cl::desc("Print translation statistics"), cl::value_desc("print-stats"), cl::cat(ToolTemplateCategory)); static cl::opt<std::string> OutputStatsFilename("o-stats", cl::desc("Output filename for statistics"), cl::value_desc("filename"), cl::cat(ToolTemplateCategory)); static cl::opt<bool> Examine("examine", cl::desc("Combines -no-output and -print-stats options"), cl::value_desc("examine"), cl::cat(ToolTemplateCategory)); static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); namespace { uint64_t countRepsTotal[CONV_LAST] = { 0 }; uint64_t countApiRepsTotal[API_LAST] = { 0 }; uint64_t countRepsTotalUnsupported[CONV_LAST] = { 0 }; uint64_t countApiRepsTotalUnsupported[API_LAST] = { 0 }; std::map<std::string, uint64_t> cuda2hipConvertedTotal; std::map<std::string, uint64_t> cuda2hipUnconvertedTotal; struct hipCounter { StringRef hipName; ConvTypes countType; ApiTypes countApiType; int unsupported; }; struct cuda2hipMap { std::map<StringRef, hipCounter> cuda2hipRename; std::set<StringRef> cudaExcludes; cuda2hipMap() { // Replacement Excludes cudaExcludes = {"CHECK_CUDA_ERROR", "CUDA_SAFE_CALL"}; // Defines cuda2hipRename["__CUDACC__"] = {"__HIPCC__", CONV_DEF, API_RUNTIME}; // CUDA includes cuda2hipRename["cuda.h"] = {"hip/hip_runtime.h", CONV_INCLUDE_CUDA_MAIN_H, API_DRIVER}; cuda2hipRename["cuda_runtime.h"] = {"hip/hip_runtime.h", CONV_INCLUDE_CUDA_MAIN_H, API_RUNTIME}; cuda2hipRename["cuda_runtime_api.h"] = {"hip/hip_runtime_api.h", CONV_INCLUDE, API_RUNTIME}; // HIP includes // TODO: uncomment this when hip/cudacommon.h will be renamed to hip/hipcommon.h //cuda2hipRename["cudacommon.h"] = {"hipcommon.h", CONV_INCLUDE, API_RUNTIME}; // CUBLAS includes cuda2hipRename["cublas.h"] = {"hipblas.h", CONV_INCLUDE, API_BLAS}; cuda2hipRename["cublas_v2.h"] = {"hipblas.h", CONV_INCLUDE, API_BLAS}; // Error codes and return types cuda2hipRename["CUresult"] = {"hipError_t", CONV_TYPE, API_DRIVER}; // cuda2hipRename["cudaError_enum"] = {"hipError_t", CONV_TYPE, API_DRIVER}; cuda2hipRename["cudaError_t"] = {"hipError_t", CONV_TYPE, API_RUNTIME}; cuda2hipRename["cudaError"] = {"hipError_t", CONV_TYPE, API_RUNTIME}; // CUDA Driver API error codes only cuda2hipRename["CUDA_ERROR_INVALID_CONTEXT"] = {"hipErrorInvalidContext", CONV_TYPE, API_DRIVER}; // 201 cuda2hipRename["CUDA_ERROR_CONTEXT_ALREADY_CURRENT"] = {"hipErrorContextAlreadyCurrent", CONV_TYPE, API_DRIVER}; // 202 cuda2hipRename["CUDA_ERROR_ARRAY_IS_MAPPED"] = {"hipErrorArrayIsMapped", CONV_TYPE, API_DRIVER}; // 207 cuda2hipRename["CUDA_ERROR_ALREADY_MAPPED"] = {"hipErrorAlreadyMapped", CONV_TYPE, API_DRIVER}; // 208 cuda2hipRename["CUDA_ERROR_ALREADY_ACQUIRED"] = {"hipErrorAlreadyAcquired", CONV_TYPE, API_DRIVER}; // 210 cuda2hipRename["CUDA_ERROR_NOT_MAPPED"] = {"hipErrorNotMapped", CONV_TYPE, API_DRIVER}; // 211 cuda2hipRename["CUDA_ERROR_NOT_MAPPED_AS_ARRAY"] = {"hipErrorNotMappedAsArray", CONV_TYPE, API_DRIVER}; // 212 cuda2hipRename["CUDA_ERROR_NOT_MAPPED_AS_POINTER"] = {"hipErrorNotMappedAsPointer", CONV_TYPE, API_DRIVER}; // 213 cuda2hipRename["CUDA_ERROR_CONTEXT_ALREADY_IN_USE"] = {"hipErrorContextAlreadyInUse", CONV_TYPE, API_DRIVER}; // 216 cuda2hipRename["CUDA_ERROR_INVALID_SOURCE"] = {"hipErrorInvalidSource", CONV_TYPE, API_DRIVER}; // 300 cuda2hipRename["CUDA_ERROR_FILE_NOT_FOUND"] = {"hipErrorFileNotFound", CONV_TYPE, API_DRIVER}; // 301 cuda2hipRename["CUDA_ERROR_NOT_FOUND"] = {"hipErrorNotFound", CONV_TYPE, API_DRIVER}; // 500 cuda2hipRename["CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING"] = {"hipErrorLaunchIncompatibleTexturing", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 703 cuda2hipRename["CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE"] = {"hipErrorPrimaryContextActive", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 708 cuda2hipRename["CUDA_ERROR_CONTEXT_IS_DESTROYED"] = {"hipErrorContextIsDestroyed", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 709 cuda2hipRename["CUDA_ERROR_NOT_PERMITTED"] = {"hipErrorNotPermitted", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 800 cuda2hipRename["CUDA_ERROR_NOT_SUPPORTED"] = {"hipErrorNotSupported", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 801 // CUDA RT API error code only cuda2hipRename["cudaErrorMissingConfiguration"] = {"hipErrorMissingConfiguration", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 1 cuda2hipRename["cudaErrorPriorLaunchFailure"] = {"hipErrorPriorLaunchFailure", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 5 cuda2hipRename["cudaErrorInvalidDeviceFunction"] = {"hipErrorInvalidDeviceFunction", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 8 cuda2hipRename["cudaErrorInvalidConfiguration"] = {"hipErrorInvalidConfiguration", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 9 cuda2hipRename["cudaErrorInvalidPitchValue"] = {"hipErrorInvalidPitchValue", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 12 cuda2hipRename["cudaErrorInvalidSymbol"] = {"hipErrorInvalidSymbol", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 13 cuda2hipRename["cudaErrorInvalidHostPointer"] = {"hipErrorInvalidHostPointer", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 16 cuda2hipRename["cudaErrorInvalidDevicePointer"] = {"hipErrorInvalidDevicePointer", CONV_TYPE, API_RUNTIME}; // 17 cuda2hipRename["cudaErrorInvalidTexture"] = {"hipErrorInvalidTexture", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 18 cuda2hipRename["cudaErrorInvalidTextureBinding"] = {"hipErrorInvalidTextureBinding", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 19 cuda2hipRename["cudaErrorInvalidChannelDescriptor"] = {"hipErrorInvalidChannelDescriptor", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 20 cuda2hipRename["cudaErrorInvalidMemcpyDirection"] = {"hipErrorInvalidMemcpyDirection", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 21 cuda2hipRename["cudaErrorAddressOfConstant"] = {"hipErrorAddressOfConstant", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 22 cuda2hipRename["cudaErrorTextureFetchFailed"] = {"hipErrorTextureFetchFailed", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 23 cuda2hipRename["cudaErrorTextureNotBound"] = {"hipErrorTextureNotBound", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 24 cuda2hipRename["cudaErrorSynchronizationError"] = {"hipErrorSynchronizationError", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 25 cuda2hipRename["cudaErrorInvalidFilterSetting"] = {"hipErrorInvalidFilterSetting", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 26 cuda2hipRename["cudaErrorInvalidNormSetting"] = {"hipErrorInvalidNormSetting", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 27 cuda2hipRename["cudaErrorMixedDeviceExecution"] = {"hipErrorMixedDeviceExecution", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 28 // Deprecated as of CUDA 4.1 cuda2hipRename["cudaErrorNotYetImplemented"] = {"hipErrorNotYetImplemented", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 31 // Deprecated as of CUDA 3.1 cuda2hipRename["cudaErrorMemoryValueTooLarge"] = {"hipErrorMemoryValueTooLarge", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 32 cuda2hipRename["cudaErrorInsufficientDriver"] = {"hipErrorInsufficientDriver", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 35 cuda2hipRename["cudaErrorSetOnActiveProcess"] = {"hipErrorSetOnActiveProcess", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 36 cuda2hipRename["cudaErrorInvalidSurface"] = {"hipErrorInvalidSurface", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 37 cuda2hipRename["cudaErrorDuplicateVariableName"] = {"hipErrorDuplicateVariableName", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 43 cuda2hipRename["cudaErrorDuplicateTextureName"] = {"hipErrorDuplicateTextureName", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 44 cuda2hipRename["cudaErrorDuplicateSurfaceName"] = {"hipErrorDuplicateSurfaceName", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 45 cuda2hipRename["cudaErrorDevicesUnavailable"] = {"hipErrorDevicesUnavailable", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 46 cuda2hipRename["cudaErrorIncompatibleDriverContext"] = {"hipErrorIncompatibleDriverContext", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 49 cuda2hipRename["cudaErrorDeviceAlreadyInUse"] = {"hipErrorDeviceAlreadyInUse", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 54 cuda2hipRename["cudaErrorLaunchMaxDepthExceeded"] = {"hipErrorLaunchMaxDepthExceeded", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 65 cuda2hipRename["cudaErrorLaunchFileScopedTex"] = {"hipErrorLaunchFileScopedTex", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 66 cuda2hipRename["cudaErrorLaunchFileScopedSurf"] = {"hipErrorLaunchFileScopedSurf", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 67 cuda2hipRename["cudaErrorSyncDepthExceeded"] = {"hipErrorSyncDepthExceeded", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 68 cuda2hipRename["cudaErrorLaunchPendingCountExceeded"] = {"hipErrorLaunchPendingCountExceeded", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 69 cuda2hipRename["cudaErrorNotPermitted"] = {"hipErrorNotPermitted", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 70 cuda2hipRename["cudaErrorNotSupported"] = {"hipErrorNotSupported", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 71 cuda2hipRename["cudaErrorStartupFailure"] = {"hipErrorStartupFailure", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 0x7f // Deprecated as of CUDA 4.1 cuda2hipRename["cudaErrorApiFailureBase"] = {"hipErrorApiFailureBase", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 10000 cuda2hipRename["CUDA_SUCCESS"] = {"hipSuccess", CONV_TYPE, API_DRIVER}; // 0 cuda2hipRename["cudaSuccess"] = {"hipSuccess", CONV_TYPE, API_RUNTIME}; // 0 cuda2hipRename["CUDA_ERROR_INVALID_VALUE"] = {"hipErrorInvalidValue", CONV_TYPE, API_DRIVER}; // 1 cuda2hipRename["cudaErrorInvalidValue"] = {"hipErrorInvalidValue", CONV_TYPE, API_RUNTIME}; // 11 cuda2hipRename["CUDA_ERROR_OUT_OF_MEMORY"] = {"hipErrorMemoryAllocation", CONV_TYPE, API_DRIVER}; // 2 cuda2hipRename["cudaErrorMemoryAllocation"] = {"hipErrorMemoryAllocation", CONV_TYPE, API_RUNTIME}; // 2 cuda2hipRename["CUDA_ERROR_NOT_INITIALIZED"] = {"hipErrorNotInitialized", CONV_TYPE, API_DRIVER}; // 3 cuda2hipRename["cudaErrorInitializationError"] = {"hipErrorInitializationError", CONV_TYPE, API_RUNTIME}; // 3 cuda2hipRename["CUDA_ERROR_DEINITIALIZED"] = {"hipErrorDeinitialized", CONV_TYPE, API_DRIVER}; // 4 // TODO: double check, that these errors match cuda2hipRename["cudaErrorCudartUnloading"] = {"hipErrorDeinitialized", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 29 cuda2hipRename["CUDA_ERROR_PROFILER_DISABLED"] = {"hipErrorProfilerDisabled", CONV_TYPE, API_DRIVER}; // 5 cuda2hipRename["cudaErrorProfilerDisabled"] = {"hipErrorProfilerDisabled", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 55 cuda2hipRename["CUDA_ERROR_PROFILER_NOT_INITIALIZED"] = {"hipErrorProfilerNotInitialized", CONV_TYPE, API_DRIVER}; // 6 // Deprecated as of CUDA 5.0 cuda2hipRename["cudaErrorProfilerNotInitialized"] = {"hipErrorProfilerNotInitialized", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 56 cuda2hipRename["CUDA_ERROR_PROFILER_ALREADY_STARTED"] = {"hipErrorProfilerAlreadyStarted", CONV_TYPE, API_DRIVER}; // 7 // Deprecated as of CUDA 5.0 cuda2hipRename["cudaErrorProfilerAlreadyStarted"] = {"hipErrorProfilerAlreadyStarted", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 57 cuda2hipRename["CUDA_ERROR_PROFILER_ALREADY_STOPPED"] = {"hipErrorProfilerAlreadyStopped", CONV_TYPE, API_DRIVER}; // 8 // Deprecated as of CUDA 5.0 cuda2hipRename["cudaErrorProfilerAlreadyStopped"] = {"hipErrorProfilerAlreadyStopped", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 58 cuda2hipRename["CUDA_ERROR_NO_DEVICE"] = {"hipErrorNoDevice", CONV_TYPE, API_DRIVER}; // 100 cuda2hipRename["cudaErrorNoDevice"] = {"hipErrorNoDevice", CONV_TYPE, API_RUNTIME}; // 38 cuda2hipRename["CUDA_ERROR_INVALID_DEVICE"] = {"hipErrorInvalidDevice", CONV_TYPE, API_DRIVER}; // 101 cuda2hipRename["cudaErrorInvalidDevice"] = {"hipErrorInvalidDevice", CONV_TYPE, API_RUNTIME}; // 10 cuda2hipRename["CUDA_ERROR_INVALID_IMAGE"] = {"hipErrorInvalidImage", CONV_TYPE, API_DRIVER}; // 200 cuda2hipRename["cudaErrorInvalidKernelImage"] = {"hipErrorInvalidImage", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 47 cuda2hipRename["CUDA_ERROR_MAP_FAILED"] = {"hipErrorMapFailed", CONV_TYPE, API_DRIVER}; // 205 // TODO: double check, that these errors match cuda2hipRename["cudaErrorMapBufferObjectFailed"] = {"hipErrorMapFailed", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 14 cuda2hipRename["CUDA_ERROR_UNMAP_FAILED"] = {"hipErrorUnmapFailed", CONV_TYPE, API_DRIVER}; // 206 // TODO: double check, that these errors match cuda2hipRename["cudaErrorUnmapBufferObjectFailed"] = {"hipErrorUnmapFailed", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 15 cuda2hipRename["CUDA_ERROR_NO_BINARY_FOR_GPU"] = {"hipErrorNoBinaryForGpu", CONV_TYPE, API_DRIVER}; // 209 cuda2hipRename["cudaErrorNoKernelImageForDevice"] = {"hipErrorNoBinaryForGpu", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 48 cuda2hipRename["CUDA_ERROR_ECC_UNCORRECTABLE"] = {"hipErrorECCNotCorrectable", CONV_TYPE, API_DRIVER}; // 214 cuda2hipRename["cudaErrorECCUncorrectable"] = {"hipErrorECCNotCorrectable", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 39 cuda2hipRename["CUDA_ERROR_UNSUPPORTED_LIMIT"] = {"hipErrorUnsupportedLimit", CONV_TYPE, API_DRIVER}; // 215 cuda2hipRename["cudaErrorUnsupportedLimit"] = {"hipErrorUnsupportedLimit", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 42 cuda2hipRename["CUDA_ERROR_PEER_ACCESS_UNSUPPORTED"] = {"hipErrorPeerAccessUnsupported", CONV_TYPE, API_DRIVER}; // 217 cuda2hipRename["cudaErrorPeerAccessUnsupported"] = {"hipErrorPeerAccessUnsupported", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 64 cuda2hipRename["CUDA_ERROR_INVALID_PTX"] = {"hipErrorInvalidKernelFile", CONV_TYPE, API_DRIVER}; // 218 cuda2hipRename["cudaErrorInvalidPtx"] = {"hipErrorInvalidKernelFile", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 78 cuda2hipRename["CUDA_ERROR_INVALID_GRAPHICS_CONTEXT"] = {"hipErrorInvalidGraphicsContext", CONV_TYPE, API_DRIVER}; // 219 cuda2hipRename["cudaErrorInvalidGraphicsContext"] = {"hipErrorInvalidGraphicsContext", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 79 cuda2hipRename["CUDA_ERROR_NVLINK_UNCORRECTABLE"] = {"hipErrorNvlinkUncorrectable", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 220 [CUDA 8.0.44] cuda2hipRename["cudaErrorNvlinkUncorrectable"] = {"hipErrorNvlinkUncorrectable", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 80 [CUDA 8.0.44] cuda2hipRename["CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND"] = {"hipErrorSharedObjectSymbolNotFound", CONV_TYPE, API_DRIVER}; // 302 cuda2hipRename["cudaErrorSharedObjectSymbolNotFound"] = {"hipErrorSharedObjectSymbolNotFound", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 40 cuda2hipRename["CUDA_ERROR_SHARED_OBJECT_INIT_FAILED"] = {"hipErrorSharedObjectInitFailed", CONV_TYPE, API_DRIVER}; // 303 cuda2hipRename["cudaErrorSharedObjectInitFailed"] = {"hipErrorSharedObjectInitFailed", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 41 cuda2hipRename["CUDA_ERROR_OPERATING_SYSTEM"] = {"hipErrorOperatingSystem", CONV_TYPE, API_DRIVER}; // 304 cuda2hipRename["cudaErrorOperatingSystem"] = {"hipErrorOperatingSystem", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 63 cuda2hipRename["CUDA_ERROR_INVALID_HANDLE"] = {"hipErrorInvalidResourceHandle", CONV_TYPE, API_DRIVER}; // 400 cuda2hipRename["cudaErrorInvalidResourceHandle"] = {"hipErrorInvalidResourceHandle", CONV_TYPE, API_RUNTIME}; // 33 cuda2hipRename["CUDA_ERROR_NOT_READY"] = {"hipErrorNotReady", CONV_TYPE, API_DRIVER}; // 600 cuda2hipRename["cudaErrorNotReady"] = {"hipErrorNotReady", CONV_TYPE, API_RUNTIME}; // 34 cuda2hipRename["CUDA_ERROR_ILLEGAL_ADDRESS"] = {"hipErrorIllegalAddress", CONV_TYPE, API_DRIVER}; // 700 cuda2hipRename["cudaErrorIllegalAddress"] = {"hipErrorIllegalAddress", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 77 cuda2hipRename["CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES"] = {"hipErrorLaunchOutOfResources", CONV_TYPE, API_DRIVER}; // 701 cuda2hipRename["cudaErrorLaunchOutOfResources"] = {"hipErrorLaunchOutOfResources", CONV_TYPE, API_RUNTIME}; // 7 cuda2hipRename["CUDA_ERROR_LAUNCH_TIMEOUT"] = {"hipErrorLaunchTimeOut", CONV_TYPE, API_DRIVER}; // 702 cuda2hipRename["cudaErrorLaunchTimeout"] = {"hipErrorLaunchTimeOut", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 6 cuda2hipRename["CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED"] = {"hipErrorPeerAccessAlreadyEnabled", CONV_TYPE, API_DRIVER}; // 704 cuda2hipRename["cudaErrorPeerAccessAlreadyEnabled"] = {"hipErrorPeerAccessAlreadyEnabled", CONV_TYPE, API_RUNTIME}; // 50 cuda2hipRename["CUDA_ERROR_PEER_ACCESS_NOT_ENABLED"] = {"hipErrorPeerAccessNotEnabled", CONV_TYPE, API_DRIVER}; // 705 cuda2hipRename["cudaErrorPeerAccessNotEnabled"] = {"hipErrorPeerAccessNotEnabled", CONV_TYPE, API_RUNTIME}; // 51 cuda2hipRename["CUDA_ERROR_ASSERT"] = {"hipErrorAssert", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 710 cuda2hipRename["cudaErrorAssert"] = {"hipErrorAssert", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 59 cuda2hipRename["CUDA_ERROR_TOO_MANY_PEERS"] = {"hipErrorTooManyPeers", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 711 cuda2hipRename["cudaErrorTooManyPeers"] = {"hipErrorTooManyPeers", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 60 cuda2hipRename["CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED"] = {"hipErrorHostMemoryAlreadyRegistered", CONV_TYPE, API_DRIVER}; // 712 cuda2hipRename["cudaErrorHostMemoryAlreadyRegistered"] = {"hipErrorHostMemoryAlreadyRegistered", CONV_TYPE, API_RUNTIME}; // 61 cuda2hipRename["CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED"] = {"hipErrorHostMemoryNotRegistered", CONV_TYPE, API_DRIVER}; // 713 cuda2hipRename["cudaErrorHostMemoryNotRegistered"] = {"hipErrorHostMemoryNotRegistered", CONV_TYPE, API_RUNTIME}; // 62 cuda2hipRename["CUDA_ERROR_HARDWARE_STACK_ERROR"] = {"hipErrorHardwareStackError", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 714 cuda2hipRename["cudaErrorHardwareStackError"] = {"hipErrorHardwareStackError", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 72 cuda2hipRename["CUDA_ERROR_ILLEGAL_INSTRUCTION"] = {"hipErrorIllegalInstruction", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 715 cuda2hipRename["cudaErrorIllegalInstruction"] = {"hipErrorIllegalInstruction", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 73 cuda2hipRename["CUDA_ERROR_MISALIGNED_ADDRESS"] = {"hipErrorMisalignedAddress", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 716 cuda2hipRename["cudaErrorMisalignedAddress"] = {"hipErrorMisalignedAddress", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 74 cuda2hipRename["CUDA_ERROR_INVALID_ADDRESS_SPACE"] = {"hipErrorInvalidAddressSpace", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 717 cuda2hipRename["cudaErrorInvalidAddressSpace"] = {"hipErrorInvalidAddressSpace", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 75 cuda2hipRename["CUDA_ERROR_INVALID_PC"] = {"hipErrorInvalidPc", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 718 cuda2hipRename["cudaErrorInvalidPc"] = {"hipErrorInvalidPc", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 76 cuda2hipRename["CUDA_ERROR_LAUNCH_FAILED"] = {"hipErrorLaunchFailure", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 719 cuda2hipRename["cudaErrorLaunchFailure"] = {"hipErrorLaunchFailure", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 4 cuda2hipRename["CUDA_ERROR_UNKNOWN"] = {"hipErrorUnknown", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 999 cuda2hipRename["cudaErrorUnknown"] = {"hipErrorUnknown", CONV_TYPE, API_RUNTIME}; // 30 ///////////////////////////// CUDA DRIVER API ///////////////////////////// // structs cuda2hipRename["CUDA_ARRAY3D_DESCRIPTOR"] = {"HIP_ARRAY3D_DESCRIPTOR", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_ARRAY_DESCRIPTOR"] = {"HIP_ARRAY_DESCRIPTOR", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_MEMCPY2D"] = {"HIP_MEMCPY2D", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_MEMCPY3D"] = {"HIP_MEMCPY3D", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_MEMCPY3D_PEER"] = {"HIP_MEMCPY3D_PEER", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_POINTER_ATTRIBUTE_P2P_TOKENS"] = {"HIP_POINTER_ATTRIBUTE_P2P_TOKENS", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_RESOURCE_DESC"] = {"HIP_RESOURCE_DESC", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_RESOURCE_VIEW_DESC"] = {"HIP_RESOURCE_VIEW_DESC", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CUipcEventHandle"] = {"hipIpcEventHandle", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CUipcMemHandle"] = {"hipIpcMemHandle", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CUaddress_mode"] = {"hipAddress_mode", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_TR_ADDRESS_MODE_WRAP"] = {"HIP_TR_ADDRESS_MODE_WRAP", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0 cuda2hipRename["CU_TR_ADDRESS_MODE_CLAMP"] = {"HIP_TR_ADDRESS_MODE_CLAMP", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 1 cuda2hipRename["CU_TR_ADDRESS_MODE_MIRROR"] = {"HIP_TR_ADDRESS_MODE_MIRROR", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 2 cuda2hipRename["CU_TR_ADDRESS_MODE_BORDER"] = {"HIP_TR_ADDRESS_MODE_BORDER", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 3 cuda2hipRename["CUarray_cubemap_face"] = {"hipArray_cubemap_face", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_CUBEMAP_FACE_POSITIVE_X"] = {"HIP_CUBEMAP_FACE_POSITIVE_X", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x00 cuda2hipRename["CU_CUBEMAP_FACE_NEGATIVE_X"] = {"HIP_CUBEMAP_FACE_NEGATIVE_X", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 cuda2hipRename["CU_CUBEMAP_FACE_POSITIVE_Y"] = {"HIP_CUBEMAP_FACE_POSITIVE_Y", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 cuda2hipRename["CU_CUBEMAP_FACE_NEGATIVE_Y"] = {"HIP_CUBEMAP_FACE_NEGATIVE_Y", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x03 cuda2hipRename["CU_CUBEMAP_FACE_POSITIVE_Z"] = {"HIP_CUBEMAP_FACE_POSITIVE_Z", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x04 cuda2hipRename["CU_CUBEMAP_FACE_NEGATIVE_Z"] = {"HIP_CUBEMAP_FACE_NEGATIVE_Z", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x05 cuda2hipRename["CUarray_format"] = {"hipArray_format", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_AD_FORMAT_UNSIGNED_INT8"] = {"HIP_AD_FORMAT_UNSIGNED_INT8", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 cuda2hipRename["CU_AD_FORMAT_UNSIGNED_INT16"] = {"HIP_AD_FORMAT_UNSIGNED_INT16", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 cuda2hipRename["CU_AD_FORMAT_UNSIGNED_INT32"] = {"HIP_AD_FORMAT_UNSIGNED_INT32", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x03 cuda2hipRename["CU_AD_FORMAT_SIGNED_INT8"] = {"HIP_AD_FORMAT_SIGNED_INT8", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x08 cuda2hipRename["CU_AD_FORMAT_SIGNED_INT16"] = {"HIP_AD_FORMAT_SIGNED_INT16", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x09 cuda2hipRename["CU_AD_FORMAT_SIGNED_INT32"] = {"HIP_AD_FORMAT_SIGNED_INT32", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x0a cuda2hipRename["CU_AD_FORMAT_HALF"] = {"HIP_AD_FORMAT_HALF", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x10 cuda2hipRename["CU_AD_FORMAT_FLOAT"] = {"HIP_AD_FORMAT_FLOAT", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x20 // Compute mode cuda2hipRename["CUcomputemode"] = {"hipComputemode", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_RUNTIME ANALOGUE (cudaComputeMode) cuda2hipRename["CU_COMPUTEMODE_DEFAULT"] = {"hipComputeModeDefault", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0 // API_RUNTIME ANALOGUE (cudaComputeModeDefault = 0) cuda2hipRename["CU_COMPUTEMODE_EXCLUSIVE"] = {"hipComputeModeExclusive", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 1 // API_RUNTIME ANALOGUE (cudaComputeModeExclusive = 1) cuda2hipRename["CU_COMPUTEMODE_PROHIBITED"] = {"hipComputeModeProhibited", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 2 // API_RUNTIME ANALOGUE (cudaComputeModeProhibited = 2) cuda2hipRename["CU_COMPUTEMODE_EXCLUSIVE_PROCESS"] = {"hipComputeModeExclusiveProcess", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 3 // API_RUNTIME ANALOGUE (cudaComputeModeExclusiveProcess = 3) // unsupported yet by HIP [CUDA 8.0.44] // Memory advise values cuda2hipRename["CUmem_advise"] = {"hipMemAdvise", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_RUNTIME ANALOGUE (cudaComputeMode) // cuda2hipRename["CUmem_advise_enum"] = {"hipMemAdvise", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_MEM_ADVISE_SET_READ_MOSTLY"] = {"hipMemAdviseSetReadMostly", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 1 // API_RUNTIME ANALOGUE (cudaMemAdviseSetReadMostly = 1) cuda2hipRename["CU_MEM_ADVISE_UNSET_READ_MOSTLY"] = {"hipMemAdviseUnsetReadMostly", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 2 // API_RUNTIME ANALOGUE (cudaMemAdviseUnsetReadMostly = 2) cuda2hipRename["CU_MEM_ADVISE_SET_PREFERRED_LOCATION"] = {"hipMemAdviseSetPreferredLocation", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 3 // API_RUNTIME ANALOGUE (cudaMemAdviseSetPreferredLocation = 3) cuda2hipRename["CU_MEM_ADVISE_UNSET_PREFERRED_LOCATION"] = {"hipMemAdviseUnsetPreferredLocation", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 4 // API_RUNTIME ANALOGUE (cudaMemAdviseUnsetPreferredLocation = 4) cuda2hipRename["CU_MEM_ADVISE_SET_ACCESSED_BY"] = {"hipMemAdviseSetAccessedBy", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 5 // API_RUNTIME ANALOGUE (cudaMemAdviseSetAccessedBy = 5) cuda2hipRename["CU_MEM_ADVISE_UNSET_ACCESSED_BY"] = {"hipMemAdviseUnsetAccessedBy", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 6 // API_RUNTIME ANALOGUE (cudaMemAdviseUnsetAccessedBy = 6) // CUmem_range_attribute cuda2hipRename["CUmem_range_attribute"] = {"hipMemRangeAttribute", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_RUNTIME ANALOGUE (cudaMemRangeAttribute) // cuda2hipRename["CUmem_range_attribute_enum"] = {"hipMemRangeAttribute", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_MEM_RANGE_ATTRIBUTE_READ_MOSTLY"] = {"hipMemRangeAttributeReadMostly", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 1 // API_RUNTIME ANALOGUE (cudaMemRangeAttributeReadMostly = 1) cuda2hipRename["CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION"] = {"hipMemRangeAttributePreferredLocation", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 2 // API_RUNTIME ANALOGUE (cudaMemRangeAttributePreferredLocation = 2) cuda2hipRename["CU_MEM_RANGE_ATTRIBUTE_ACCESSED_BY"] = {"hipMemRangeAttributeAccessedBy", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 3 // API_RUNTIME ANALOGUE (cudaMemRangeAttributeAccessedBy = 3) cuda2hipRename["CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION"] = {"hipMemRangeAttributeLastPrefetchLocation", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 4 // API_RUNTIME ANALOGUE (cudaMemRangeAttributeLastPrefetchLocation = 4) // Context flags cuda2hipRename["CUctx_flags"] = {"hipCctx_flags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_CTX_SCHED_AUTO"] = {"HIP_CTX_SCHED_AUTO", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x00 cuda2hipRename["CU_CTX_SCHED_SPIN"] = {"HIP_CTX_SCHED_SPIN", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 cuda2hipRename["CU_CTX_SCHED_YIELD"] = {"HIP_CTX_SCHED_YIELD", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 cuda2hipRename["CU_CTX_SCHED_BLOCKING_SYNC"] = {"HIP_CTX_SCHED_BLOCKING_SYNC", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x04 cuda2hipRename["CU_CTX_BLOCKING_SYNC"] = {"HIP_CTX_BLOCKING_SYNC", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x04 cuda2hipRename["CU_CTX_SCHED_MASK"] = {"HIP_CTX_SCHED_MASK", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x07 cuda2hipRename["CU_CTX_MAP_HOST"] = {"HIP_CTX_MAP_HOST", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x08 cuda2hipRename["CU_CTX_LMEM_RESIZE_TO_MAX"] = {"HIP_CTX_LMEM_RESIZE_TO_MAX", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x10 cuda2hipRename["CU_CTX_FLAGS_MASK"] = {"HIP_CTX_FLAGS_MASK", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x1f // Defines cuda2hipRename["CU_LAUNCH_PARAM_BUFFER_POINTER"] = {"HIP_LAUNCH_PARAM_BUFFER_POINTER", CONV_TYPE, API_DRIVER}; // ((void*)0x01) cuda2hipRename["CU_LAUNCH_PARAM_BUFFER_SIZE"] = {"HIP_LAUNCH_PARAM_BUFFER_SIZE", CONV_TYPE, API_DRIVER}; // ((void*)0x02) cuda2hipRename["CU_LAUNCH_PARAM_END"] = {"HIP_LAUNCH_PARAM_END", CONV_TYPE, API_DRIVER}; // ((void*)0x00) cuda2hipRename["CU_IPC_HANDLE_SIZE"] = {"HIP_LAUNCH_PARAM_END", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 64 cuda2hipRename["CU_MEMHOSTALLOC_DEVICEMAP"] = {"HIP_MEMHOSTALLOC_DEVICEMAP", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 cuda2hipRename["CU_MEMHOSTALLOC_PORTABLE"] = {"HIP_MEMHOSTALLOC_PORTABLE", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 cuda2hipRename["CU_MEMHOSTALLOC_WRITECOMBINED"] = {"HIP_MEMHOSTALLOC_WRITECOMBINED", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x04 cuda2hipRename["CU_MEMHOSTREGISTER_DEVICEMAP"] = {"HIP_MEMHOSTREGISTER_DEVICEMAP", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 cuda2hipRename["CU_MEMHOSTREGISTER_IOMEMORY"] = {"HIP_MEMHOSTREGISTER_IOMEMORY", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x04 cuda2hipRename["CU_MEMHOSTREGISTER_PORTABLE"] = {"HIP_MEMHOSTREGISTER_PORTABLE", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 cuda2hipRename["CU_PARAM_TR_DEFAULT"] = {"HIP_PARAM_TR_DEFAULT", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // -1 cuda2hipRename["CU_STREAM_LEGACY"] = {"HIP_STREAM_LEGACY", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // ((CUstream)0x1) cuda2hipRename["CU_STREAM_PER_THREAD"] = {"HIP_STREAM_PER_THREAD", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // ((CUstream)0x2) cuda2hipRename["CU_TRSA_OVERRIDE_FORMAT"] = {"HIP_TRSA_OVERRIDE_FORMAT", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 cuda2hipRename["CU_TRSF_NORMALIZED_COORDINATES"] = {"HIP_TRSF_NORMALIZED_COORDINATES", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED};// 0x02 cuda2hipRename["CU_TRSF_READ_AS_INTEGER"] = {"HIP_TRSF_READ_AS_INTEGER", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 cuda2hipRename["CU_TRSF_SRGB"] = {"HIP_TRSF_SRGB", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x10 // Deprecated, use CUDA_ARRAY3D_LAYERED cuda2hipRename["CUDA_ARRAY3D_2DARRAY"] = {"HIP_ARRAY3D_LAYERED", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 cuda2hipRename["CUDA_ARRAY3D_CUBEMAP"] = {"HIP_ARRAY3D_CUBEMAP", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x04 cuda2hipRename["CUDA_ARRAY3D_DEPTH_TEXTURE"] = {"HIP_ARRAY3D_DEPTH_TEXTURE", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x10 cuda2hipRename["CUDA_ARRAY3D_LAYERED"] = {"HIP_ARRAY3D_LAYERED", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 cuda2hipRename["CUDA_ARRAY3D_SURFACE_LDST"] = {"HIP_ARRAY3D_SURFACE_LDST", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 cuda2hipRename["CUDA_ARRAY3D_TEXTURE_GATHER"] = {"HIP_ARRAY3D_TEXTURE_GATHER", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x08 cuda2hipRename["CUDA_VERSION"] = {"HIP_VERSION", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 7050 // Types // NOTE: CUdevice might be changed to typedef int in the future. cuda2hipRename["CUdevice"] = {"hipDevice_t", CONV_TYPE, API_DRIVER}; cuda2hipRename["CUdevice_attribute_enum"] = {"hipDeviceAttribute_t", CONV_TYPE, API_DRIVER}; // API_Runtime ANALOGUE (cudaDeviceAttr) cuda2hipRename["CUdevice_attribute"] = {"hipDeviceAttribute_t", CONV_TYPE, API_DRIVER}; // API_Runtime ANALOGUE (cudaDeviceAttr) cuda2hipRename["CUdeviceptr"] = {"hipDeviceptr_t", CONV_TYPE, API_DRIVER}; // CUDA: "The types::CUarray and struct ::cudaArray * represent the same data type and may be used interchangeably by casting the two types between each other." // typedef struct cudaArray *cudaArray_t; // typedef struct CUarray_st *CUarray; cuda2hipRename["CUarray_st"] = {"hipArray", CONV_TYPE, API_DRIVER}; // API_Runtime ANALOGUE (cudaArray) cuda2hipRename["CUarray"] = {"hipArray *", CONV_TYPE, API_DRIVER}; // API_Runtime ANALOGUE (cudaArray_t) // unsupported yet by HIP cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK"] = {"hipDeviceAttributeMaxThreadsPerBlock", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 1 // API_Runtime ANALOGUE (cudaDevAttrMaxThreadsPerBlock = 1) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X"] = {"hipDeviceAttributeMaxBlockDimX", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 2 // API_Runtime ANALOGUE (cudaDevAttrMaxBlockDimX = 2) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y"] = {"hipDeviceAttributeMaxBlockDimY", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 3 // API_Runtime ANALOGUE (cudaDevAttrMaxBlockDimY = 3) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z"] = {"hipDeviceAttributeMaxBlockDimZ", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 4 // API_Runtime ANALOGUE (cudaDevAttrMaxBlockDimZ = 4) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X"] = {"hipDeviceAttributeMaxGridDimX", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 5 // API_Runtime ANALOGUE (cudaDevAttrMaxGridDimX =5) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y"] = {"hipDeviceAttributeMaxGridDimY", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 6 // API_Runtime ANALOGUE (cudaDevAttrMaxGridDimY = 6) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z"] = {"hipDeviceAttributeMaxGridDimZ", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 7 // API_Runtime ANALOGUE (cudaDevAttrMaxGridDimZ - 7) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK"] = {"hipDeviceAttributeMaxSharedMemoryPerBlock", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 8 // API_Runtime ANALOGUE (cudaDevAttrMaxSharedMemoryPerBlock = 8) // Deprecated, use CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK cuda2hipRename["CU_DEVICE_ATTRIBUTE_SHARED_MEMORY_PER_BLOCK"] = {"hipDeviceAttributeMaxSharedMemoryPerBlock", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 8 cuda2hipRename["CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY"] = {"hipDeviceAttributeTotalConstantMemory", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 9 // API_Runtime ANALOGUE (cudaDevAttrTotalConstantMemory = 9) cuda2hipRename["CU_DEVICE_ATTRIBUTE_WARP_SIZE"] = {"hipDeviceAttributeWarpSize", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 10 // API_Runtime ANALOGUE (cudaDevAttrWarpSize = 10) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAX_PITCH"] = {"hipDeviceAttributeMaxPitch", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 11 // API_Runtime ANALOGUE (cudaDevAttrMaxPitch = 11) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK"] = {"hipDeviceAttributeMaxRegistersPerBlock", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 12 // API_Runtime ANALOGUE (cudaDevAttrMaxRegistersPerBlock = 12) cuda2hipRename["CU_DEVICE_ATTRIBUTE_REGISTERS_PER_BLOCK"] = {"hipDeviceAttributeMaxRegistersPerBlock", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 12 cuda2hipRename["CU_DEVICE_ATTRIBUTE_CLOCK_RATE"] = {"hipDeviceAttributeClockRate", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 13 // API_Runtime ANALOGUE (cudaDevAttrMaxRegistersPerBlock = 13) cuda2hipRename["CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT"] = {"hipDeviceAttributeTextureAlignment", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 14 // API_Runtime ANALOGUE (cudaDevAttrTextureAlignment = 14) // Deprecated. Use instead CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT cuda2hipRename["CU_DEVICE_ATTRIBUTE_GPU_OVERLAP"] = {"hipDeviceAttributeAsyncEngineCount", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 15 // API_Runtime ANALOGUE (cudaDevAttrGpuOverlap = 15) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT"] = {"hipDeviceAttributeMultiprocessorCount", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 16 // API_Runtime ANALOGUE (cudaDevAttrMultiProcessorCount = 16) cuda2hipRename["CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT"] = {"hipDeviceAttributeKernelExecTimeout", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 17 // API_Runtime ANALOGUE (cudaDevAttrKernelExecTimeout = 17) cuda2hipRename["CU_DEVICE_ATTRIBUTE_INTEGRATED"] = {"hipDeviceAttributeIntegrated", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 18 // API_Runtime ANALOGUE (cudaDevAttrIntegrated = 18) cuda2hipRename["CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY"] = {"hipDeviceAttributeCanMapHostMemory", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 19 // API_Runtime ANALOGUE (cudaDevAttrCanMapHostMemory = 19) cuda2hipRename["CU_DEVICE_ATTRIBUTE_COMPUTE_MODE"] = {"hipDeviceAttributeComputeMode", CONV_TYPE, API_DRIVER}; // 20 // API_Runtime ANALOGUE (cudaDevAttrComputeMode = 20) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_WIDTH"] = {"hipDeviceAttributeMaxTexture1DWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 21 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture1DWidth = 21) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_WIDTH"] = {"hipDeviceAttributeMaxTexture2DWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 22 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture2DWidth = 22) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_HEIGHT"] = {"hipDeviceAttributeMaxTexture2DHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 23 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture2DHeight = 23) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH"] = {"hipDeviceAttributeMaxTexture3DWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 24 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture3DWidth = 24) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT"] = {"hipDeviceAttributeMaxTexture3DHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 25 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture3DHeight = 25) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH"] = {"hipDeviceAttributeMaxTexture3DDepth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 26 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture3DDepth = 26) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_WIDTH"] = {"hipDeviceAttributeMaxTexture2DLayeredWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 27 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture2DLayeredWidth = 27) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_HEIGHT"] = {"hipDeviceAttributeMaxTexture2DLayeredHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 28 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture2DLayeredHeight = 28) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_LAYERS"] = {"hipDeviceAttributeMaxTexture2DLayeredLayers", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 29 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture2DLayeredLayers = 29) // Deprecated, use CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_WIDTH cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_WIDTH"] = {"hipDeviceAttributeMaxTexture2DLayeredWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 27 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture2DLayeredWidth = 27) // Deprecated, use CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_HEIGHT cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_HEIGHT"] = {"hipDeviceAttributeMaxTexture2DLayeredHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 28 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture2DLayeredHeight = 28) // Deprecated, use CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_LAYERS cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_NUMSLICES"] = {"hipDeviceAttributeMaxTexture2DLayeredLayers", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 29 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture2DLayeredLayers = 29) cuda2hipRename["CU_DEVICE_ATTRIBUTE_SURFACE_ALIGNMENT"] = {"hipDeviceAttributeSurfaceAlignment", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 30 // API_Runtime ANALOGUE (cudaDevAttrSurfaceAlignment = 30) cuda2hipRename["CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS"] = {"hipDeviceAttributeConcurrentKernels", CONV_TYPE, API_DRIVER}; // 31 // API_Runtime ANALOGUE (cudaDevAttrConcurrentKernels = 31) cuda2hipRename["CU_DEVICE_ATTRIBUTE_ECC_ENABLED"] = {"hipDeviceAttributeEccEnabled", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 32 // API_Runtime ANALOGUE (cudaDevAttrEccEnabled = 32) cuda2hipRename["CU_DEVICE_ATTRIBUTE_PCI_BUS_ID"] = {"hipDeviceAttributePciBusId", CONV_TYPE, API_DRIVER}; // 33 // API_Runtime ANALOGUE (cudaDevAttrPciBusId = 33) cuda2hipRename["CU_DEVICE_ATTRIBUTE_PCI_DEVICE_ID"] = {"hipDeviceAttributePciDeviceId", CONV_TYPE, API_DRIVER}; // 34 // API_Runtime ANALOGUE (cudaDevAttrPciDeviceId = 34) cuda2hipRename["CU_DEVICE_ATTRIBUTE_TCC_DRIVER"] = {"hipDeviceAttributeTccDriver", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 35 // API_Runtime ANALOGUE (cudaDevAttrTccDriver = 35) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE"] = {"hipDeviceAttributeMemoryClockRate", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 36 // API_Runtime ANALOGUE (cudaDevAttrMemoryClockRate = 36) cuda2hipRename["CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH"] = {"hipDeviceAttributeMemoryBusWidth", CONV_TYPE, API_DRIVER}; // 37 // API_Runtime ANALOGUE (cudaDevAttrGlobalMemoryBusWidth = 37) cuda2hipRename["CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE"] = {"hipDeviceAttributeL2CacheSize", CONV_TYPE, API_DRIVER}; // 38 // API_Runtime ANALOGUE (cudaDevAttrL2CacheSize = 38) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR"] = {"hipDeviceAttributeMaxThreadsPerMultiProcessor", CONV_TYPE, API_DRIVER}; // 39 // API_Runtime ANALOGUE (cudaDevAttrMaxThreadsPerMultiProcessor = 39) cuda2hipRename["CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT"] = {"hipDeviceAttributeAsyncEngineCount", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 40 // API_Runtime ANALOGUE (cudaDevAttrAsyncEngineCount = 40) cuda2hipRename["CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING"] = {"hipDeviceAttributeUnifiedAddressing", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 41 // API_Runtime ANALOGUE (cudaDevAttrUnifiedAddressing = 41) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_WIDTH"] = {"hipDeviceAttributeMaxTexture1DLayeredWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 42 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture1DLayeredWidth = 42) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_LAYERS"] = {"hipDeviceAttributeMaxTexture1DLayeredLayers", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 43 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture1DLayeredLayers = 43) // deprecated, do not use cuda2hipRename["CU_DEVICE_ATTRIBUTE_CAN_TEX2D_GATHER"] = {"hipDeviceAttributeCanTex2DGather", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 44 // API_Runtime ANALOGUE (no) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_WIDTH"] = {"hipDeviceAttributeMaxTexture2DGatherWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 45 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture2DGatherWidth = 45) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_HEIGHT"] = {"hipDeviceAttributeMaxTexture2DGatherHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 46 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture2DGatherHeight = 46) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH_ALTERNATE"] = {"hipDeviceAttributeMaxTexture3DWidthAlternate", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 47 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture3DWidthAlt = 47) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT_ALTERNATE"] = {"hipDeviceAttributeMaxTexture3DHeightAlternate", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 48 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture3DHeightAlt = 48) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH_ALTERNATE"] = {"hipDeviceAttributeMaxTexture3DDepthAlternate", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 49 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture3DDepthAlt = 49) cuda2hipRename["CU_DEVICE_ATTRIBUTE_PCI_DOMAIN_ID"] = {"hipDeviceAttributePciDomainId", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 50 // API_Runtime ANALOGUE (cudaDevAttrPciDomainId = 50) cuda2hipRename["CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT"] = {"hipDeviceAttributeTexturePitchAlignment", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 51 // API_Runtime ANALOGUE (cudaDevAttrTexturePitchAlignment = 51) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_WIDTH"] = {"hipDeviceAttributeMaxTextureCubemapWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 52 // API_Runtime ANALOGUE (cudaDevAttrMaxTextureCubemapWidth = 52) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_WIDTH"] = {"hipDeviceAttributeMaxTextureCubemapLayeredWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 53 // API_Runtime ANALOGUE (cudaDevAttrMaxTextureCubemapLayeredWidth = 53) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_LAYERS"] = {"hipDeviceAttributeMaxTextureCubemapLayeredLayers", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 54 // API_Runtime ANALOGUE (cudaDevAttrMaxTextureCubemapLayeredLayers = 54) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_WIDTH"] = {"hipDeviceAttributeMaxSurface1DWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 55 // API_Runtime ANALOGUE (cudaDevAttrMaxSurface1DWidth = 55) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_WIDTH"] = {"hipDeviceAttributeMaxSurface2DWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 56 // API_Runtime ANALOGUE (cudaDevAttrMaxSurface2DWidth = 56) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_HEIGHT"] = {"hipDeviceAttributeMaxSurface2DHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 57 // API_Runtime ANALOGUE (cudaDevAttrMaxSurface2DHeight = 57) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_WIDTH"] = {"hipDeviceAttributeMaxSurface3DWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 58 // API_Runtime ANALOGUE (cudaDevAttrMaxSurface3DWidth = 58) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_HEIGHT"] = {"hipDeviceAttributeMaxSurface3DHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 59 // API_Runtime ANALOGUE (cudaDevAttrMaxSurface3DHeight = 59) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_DEPTH"] = {"hipDeviceAttributeMaxSurface3DDepth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 60 // API_Runtime ANALOGUE (cudaDevAttrMaxSurface3DDepth = 60) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_WIDTH"] = {"hipDeviceAttributeMaxSurface1DLayeredWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 61 // API_Runtime ANALOGUE (cudaDevAttrMaxSurface1DLayeredWidth = 61) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_LAYERS"] = {"hipDeviceAttributeMaxSurface1DLayeredLayers", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 62 // API_Runtime ANALOGUE (cudaDevAttrMaxSurface1DLayeredLayers = 62) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_WIDTH"] = {"hipDeviceAttributeMaxSurface2DLayeredWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 63 // API_Runtime ANALOGUE (cudaDevAttrMaxSurface2DLayeredWidth = 63) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_HEIGHT"] = {"hipDeviceAttributeMaxSurface2DLayeredHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 64 // API_Runtime ANALOGUE (cudaDevAttrMaxSurface2DLayeredHeight = 64) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_LAYERS"] = {"hipDeviceAttributeMaxSurface2DLayeredLayers", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 65 // API_Runtime ANALOGUE (cudaDevAttrMaxSurface2DLayeredLayers = 65) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_WIDTH"] = {"hipDeviceAttributeMaxSurfaceCubemapWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 66 // API_Runtime ANALOGUE (cudaDevAttrMaxSurfaceCubemapWidth = 66) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_WIDTH"] = {"hipDeviceAttributeMaxSurfaceCubemapLayeredWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 67 // API_Runtime ANALOGUE (cudaDevAttrMaxSurfaceCubemapLayeredWidth = 67) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_LAYERS"] = {"hipDeviceAttributeMaxSurfaceCubemapLayeredLayers", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 68 // API_Runtime ANALOGUE (cudaDevAttrMaxSurfaceCubemapLayeredLayers = 68) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LINEAR_WIDTH"] = {"hipDeviceAttributeMaxTexture1DLinearWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 69 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture1DLinearWidth = 69) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_WIDTH"] = {"hipDeviceAttributeMaxTexture2DLinearWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 70 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture2DLinearWidth = 70) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_HEIGHT"] = {"hipDeviceAttributeMaxTexture2DLinearHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 71 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture2DLinearHeight = 71) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_PITCH"] = {"hipDeviceAttributeMaxTexture2DLinearPitch", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 72 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture2DLinearPitch = 72) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_WIDTH"] = {"hipDeviceAttributeMaxTexture2DMipmappedWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 73 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture2DMipmappedWidth = 73) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_HEIGHT"] = {"hipDeviceAttributeMaxTexture2DMipmappedHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 74 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture2DMipmappedHeight = 74) cuda2hipRename["CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR"] = {"hipDeviceAttributeComputeCapabilityMajor", CONV_TYPE, API_DRIVER}; // 75 // API_Runtime ANALOGUE (cudaDevAttrComputeCapabilityMajor = 75) cuda2hipRename["CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR"] = {"hipDeviceAttributeComputeCapabilityMinor", CONV_TYPE, API_DRIVER}; // 76 // API_Runtime ANALOGUE (cudaDevAttrComputeCapabilityMinor = 76) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_MIPMAPPED_WIDTH"] = {"hipDeviceAttributeMaxTexture1DMipmappedWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 77 // API_Runtime ANALOGUE (cudaDevAttrMaxTexture1DMipmappedWidth = 77) cuda2hipRename["CU_DEVICE_ATTRIBUTE_STREAM_PRIORITIES_SUPPORTED"] = {"hipDeviceAttributeStreamPrioritiesSupported", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 78 // API_Runtime ANALOGUE (cudaDevAttrStreamPrioritiesSupported = 78) cuda2hipRename["CU_DEVICE_ATTRIBUTE_GLOBAL_L1_CACHE_SUPPORTED"] = {"hipDeviceAttributeGlobalL1CacheSupported", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 79 // API_Runtime ANALOGUE (cudaDevAttrGlobalL1CacheSupported = 79) cuda2hipRename["CU_DEVICE_ATTRIBUTE_LOCAL_L1_CACHE_SUPPORTED"] = {"hipDeviceAttributeLocalL1CacheSupported", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 80 // API_Runtime ANALOGUE (cudaDevAttrLocalL1CacheSupported = 80) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR"] = {"hipDeviceAttributeMaxSharedMemoryPerMultiprocessor", CONV_TYPE, API_DRIVER}; // 81 // API_Runtime ANALOGUE (cudaDevAttrMaxSharedMemoryPerMultiprocessor = 81) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_MULTIPROCESSOR"] = {"hipDeviceAttributeMaxRegistersPerMultiprocessor", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 82 // API_Runtime ANALOGUE (cudaDevAttrMaxRegistersPerMultiprocessor = 82) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY"] = {"hipDeviceAttributeManagedMemory", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 83 // API_Runtime ANALOGUE (cudaDevAttrManagedMemory = 83) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD"] = {"hipDeviceAttributeIsMultiGpuBoard", CONV_TYPE, API_DRIVER}; // 84 // API_Runtime ANALOGUE (cudaDevAttrIsMultiGpuBoard = 84) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD_GROUP_ID"] = {"hipDeviceAttributeMultiGpuBoardGroupId", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 85 // API_Runtime ANALOGUE (cudaDevAttrMultiGpuBoardGroupID = 85) // unsupported yet by HIP [CUDA 8.0.44] cuda2hipRename["CU_DEVICE_ATTRIBUTE_HOST_NATIVE_ATOMIC_SUPPORTED"] = {"hipDeviceAttributeHostNativeAtomicSupported", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 86 // API_Runtime ANALOGUE (cudaDevAttrHostNativeAtomicSupported = 86) cuda2hipRename["CU_DEVICE_ATTRIBUTE_SINGLE_TO_DOUBLE_PRECISION_PERF_RATIO"] = {"hipDeviceAttributeSingleToDoublePrecisionPerfRatio", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 87 // API_Runtime ANALOGUE (cudaDevAttrSingleToDoublePrecisionPerfRatio = 87) cuda2hipRename["CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS"] = {"hipDeviceAttributePageableMemoryAccess", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 88 // API_Runtime ANALOGUE (cudaDevAttrPageableMemoryAccess = 88) cuda2hipRename["CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS"] = {"hipDeviceAttributeConcurrentManagedAccess", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 89 // API_Runtime ANALOGUE (cudaDevAttrConcurrentManagedAccess = 89) cuda2hipRename["CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED"] = {"hipDeviceAttributeComputePreemptionSupported", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 90 // API_Runtime ANALOGUE (cudaDevAttrComputePreemptionSupported = 90) cuda2hipRename["CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM"] = {"hipDeviceAttributeCanUseHostPointerForRegisteredMem", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 91 // API_Runtime ANALOGUE (cudaDevAttrCanUseHostPointerForRegisteredMem = 91) cuda2hipRename["CU_DEVICE_ATTRIBUTE_MAX"] = {"hipDeviceAttributeMax", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 92 // API_Runtime ANALOGUE (no) cuda2hipRename["CUdevprop_st"] = {"hipDeviceProp_t", CONV_TYPE, API_DRIVER}; cuda2hipRename["CUdevprop"] = {"hipDeviceProp_t", CONV_TYPE, API_DRIVER}; // TODO: Analogues enum is needed in HIP. Couldn't map enum to struct hipPointerAttribute_t. // TODO: Do for Pointer Attributes the same as for Device Attributes. // cuda2hipRename["CUpointer_attribute_enum"] = {"hipPointerAttribute_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (no) // cuda2hipRename["CUpointer_attribute"] = {"hipPointerAttribute_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (no) cuda2hipRename["CU_POINTER_ATTRIBUTE_CONTEXT"] = {"hipPointerAttributeContext", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 1 // API_Runtime ANALOGUE (no) cuda2hipRename["CU_POINTER_ATTRIBUTE_MEMORY_TYPE"] = {"hipPointerAttributeMemoryType", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 2 // API_Runtime ANALOGUE (no) cuda2hipRename["CU_POINTER_ATTRIBUTE_DEVICE_POINTER"] = {"hipPointerAttributeDevicePointer", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 3 // API_Runtime ANALOGUE (no) cuda2hipRename["CU_POINTER_ATTRIBUTE_HOST_POINTER"] = {"hipPointerAttributeHostPointer", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 4 // API_Runtime ANALOGUE (no) cuda2hipRename["CU_POINTER_ATTRIBUTE_P2P_TOKENS"] = {"hipPointerAttributeP2pTokens", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 5 // API_Runtime ANALOGUE (no) cuda2hipRename["CU_POINTER_ATTRIBUTE_SYNC_MEMOPS"] = {"hipPointerAttributeSyncMemops", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 6 // API_Runtime ANALOGUE (no) cuda2hipRename["CU_POINTER_ATTRIBUTE_BUFFER_ID"] = {"hipPointerAttributeBufferId", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 7 // API_Runtime ANALOGUE (no) cuda2hipRename["CU_POINTER_ATTRIBUTE_IS_MANAGED"] = {"hipPointerAttributeIsManaged", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 8 // API_Runtime ANALOGUE (no) // pointer to CUfunc_st cuda2hipRename["CUfunction"] = {"hipFunction_t", CONV_TYPE, API_DRIVER}; // TODO: move "typedef struct ihipModuleSymbol_t *hipFunction_t;" from hcc_details to HIP // typedef struct CUfunc_st *CUfunction; // cuda2hipRename["CUfunc_st"] = {"ihipModuleSymbol_t", CONV_TYPE, API_DRIVER}; // typedef struct CUgraphicsResource_st *CUgraphicsResource; cuda2hipRename["CUgraphicsResource"] = {"hipGraphicsResource_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // typedef struct CUmipmappedArray_st *CUmipmappedArray; cuda2hipRename["CUmipmappedArray"] = {"hipMipmappedArray_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // unsupported yet by HIP cuda2hipRename["CUfunction_attribute"] = {"hipFuncAttribute_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CUfunction_attribute_enum"] = {"hipFuncAttribute_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK"] = {"hipFuncAttributeMaxThreadsPerBlocks", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES"] = {"hipFuncAttributeSharedSizeBytes", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES"] = {"hipFuncAttributeConstSizeBytes", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES"] = {"hipFuncAttributeLocalSizeBytes", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_FUNC_ATTRIBUTE_NUM_REGS"] = {"hipFuncAttributeNumRegs", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_FUNC_ATTRIBUTE_PTX_VERSION"] = {"hipFuncAttributePtxVersion", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_FUNC_ATTRIBUTE_BINARY_VERSION"] = {"hipFuncAttributeBinaryVersion", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_FUNC_ATTRIBUTE_CACHE_MODE_CA"] = {"hipFuncAttributeCacheModeCA", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_FUNC_ATTRIBUTE_MAX"] = {"hipFuncAttributeMax", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // enum CUgraphicsMapResourceFlags/CUgraphicsMapResourceFlags_enum cuda2hipRename["CUgraphicsMapResourceFlags"] = {"hipGraphicsMapFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsMapFlags) cuda2hipRename["CUgraphicsMapResourceFlags_enum"] = {"hipGraphicsMapFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsMapFlags) cuda2hipRename["CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE"] = {"hipGraphicsMapFlagsNone", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x00 // API_Runtime ANALOGUE (cudaGraphicsMapFlagsNone = 0) cuda2hipRename["CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY"] = {"hipGraphicsMapFlagsReadOnly", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 // API_Runtime ANALOGUE (cudaGraphicsMapFlagsReadOnly = 1) cuda2hipRename["CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD"] = {"hipGraphicsMapFlagsWriteDiscard", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 // API_Runtime ANALOGUE (cudaGraphicsMapFlagsWriteDiscard = 2) // enum CUgraphicsRegisterFlags/CUgraphicsRegisterFlags_enum cuda2hipRename["CUgraphicsRegisterFlags"] = {"hipGraphicsRegisterFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsRegisterFlags) cuda2hipRename["CUgraphicsRegisterFlags_enum"] = {"hipGraphicsRegisterFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsRegisterFlags) cuda2hipRename["CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE"] = {"hipGraphicsRegisterFlagsNone", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x00 // API_Runtime ANALOGUE (cudaGraphicsRegisterFlagsNone = 0) cuda2hipRename["CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY"] = {"hipGraphicsRegisterFlagsReadOnly", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 // API_Runtime ANALOGUE (cudaGraphicsRegisterFlagsReadOnly = 1) cuda2hipRename["CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD"] = {"hipGraphicsRegisterFlagsWriteDiscard", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 // API_Runtime ANALOGUE (cudaGraphicsRegisterFlagsWriteDiscard = 2) cuda2hipRename["CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST"] = {"hipGraphicsRegisterFlagsSurfaceLoadStore", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x04 // API_Runtime ANALOGUE (cudaGraphicsRegisterFlagsSurfaceLoadStore = 4) cuda2hipRename["CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER"] = {"hipGraphicsRegisterFlagsTextureGather", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x08 // API_Runtime ANALOGUE (cudaGraphicsRegisterFlagsTextureGather = 8) // enum CUoccupancy_flags/CUoccupancy_flags_enum cuda2hipRename["CUoccupancy_flags"] = {"hipOccupancyFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (no) cuda2hipRename["CUoccupancy_flags_enum"] = {"hipOccupancyFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (no) cuda2hipRename["CU_OCCUPANCY_DEFAULT"] = {"hipOccupancyDefault", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x00 // API_Runtime ANALOGUE (cudaOccupancyDefault = 0x0) cuda2hipRename["CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE"] = {"hipOccupancyDisableCachingOverride", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 // API_Runtime ANALOGUE (cudaOccupancyDisableCachingOverride = 0x1) cuda2hipRename["CUfunc_cache_enum"] = {"hipFuncCache", CONV_TYPE, API_DRIVER}; // API_Runtime ANALOGUE (cudaFuncCache) cuda2hipRename["CUfunc_cache"] = {"hipFuncCache", CONV_TYPE, API_DRIVER}; // API_Runtime ANALOGUE (cudaFuncCache) cuda2hipRename["CU_FUNC_CACHE_PREFER_NONE"] = {"hipFuncCachePreferNone", CONV_CACHE, API_DRIVER}; // 0x00 // API_Runtime ANALOGUE (cudaFilterModePoint = 0) cuda2hipRename["CU_FUNC_CACHE_PREFER_SHARED"] = {"hipFuncCachePreferShared", CONV_CACHE, API_DRIVER}; // 0x01 // API_Runtime ANALOGUE (cudaFuncCachePreferShared = 1) cuda2hipRename["CU_FUNC_CACHE_PREFER_L1"] = {"hipFuncCachePreferL1", CONV_CACHE, API_DRIVER}; // 0x02 // API_Runtime ANALOGUE (cudaFuncCachePreferL1 = 2) cuda2hipRename["CU_FUNC_CACHE_PREFER_EQUAL"] = {"hipFuncCachePreferEqual", CONV_CACHE, API_DRIVER}; // 0x03 // API_Runtime ANALOGUE (cudaFuncCachePreferEqual = 3) // enum CUipcMem_flags/CUipcMem_flags_enum cuda2hipRename["CUipcMem_flags"] = {"hipIpcMemFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (no) cuda2hipRename["CUipcMem_flags_enum"] = {"hipIpcMemFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (no) cuda2hipRename["CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS"] = {"hipIpcMemLazyEnablePeerAccess", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x1 // API_Runtime ANALOGUE (cudaIpcMemLazyEnablePeerAccess = 0x01) // enum CUipcMem_flags/CUipcMem_flags_enum cuda2hipRename["CUipcMem_flags"] = {"hipIpcMemFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (no) // JIT // enum CUjit_cacheMode/CUjit_cacheMode_enum cuda2hipRename["CUjit_cacheMode"] = {"hipJitCacheMode", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (no) cuda2hipRename["CUjit_cacheMode_enum"] = {"hipJitCacheMode", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_JIT_CACHE_OPTION_NONE"] = {"hipJitCacheModeOptionNone", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_JIT_CACHE_OPTION_CG"] = {"hipJitCacheModeOptionCG", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_JIT_CACHE_OPTION_CA"] = {"hipJitCacheModeOptionCA", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; // enum CUjit_fallback/CUjit_fallback_enum cuda2hipRename["CUjit_fallback"] = {"hipJitFallback", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (no) cuda2hipRename["CUjit_fallback_enum"] = {"hipJitFallback", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_PREFER_PTX"] = {"hipJitFallbackPreferPtx", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_PREFER_BINARY"] = {"hipJitFallbackPreferBinary", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; // enum CUjit_option/CUjit_option_enum cuda2hipRename["CUjit_option"] = {"hipJitOption", CONV_JIT, API_DRIVER}; // API_Runtime ANALOGUE (no) cuda2hipRename["CUjit_option_enum"] = {"hipJitOption", CONV_JIT, API_DRIVER}; cuda2hipRename["CU_JIT_MAX_REGISTERS"] = {"hipJitOptionMaxRegisters", CONV_JIT, API_DRIVER}; cuda2hipRename["CU_JIT_THREADS_PER_BLOCK"] = {"hipJitOptionThreadsPerBlock", CONV_JIT, API_DRIVER}; cuda2hipRename["CU_JIT_WALL_TIME"] = {"hipJitOptionWallTime", CONV_JIT, API_DRIVER}; cuda2hipRename["CU_JIT_INFO_LOG_BUFFER"] = {"hipJitOptionInfoLogBuffer", CONV_JIT, API_DRIVER}; cuda2hipRename["CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES"] = {"hipJitOptionInfoLogBufferSizeBytes", CONV_JIT, API_DRIVER}; cuda2hipRename["CU_JIT_ERROR_LOG_BUFFER"] = {"hipJitOptionErrorLogBuffer", CONV_JIT, API_DRIVER}; cuda2hipRename["CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES"] = {"hipJitOptionErrorLogBufferSizeBytes", CONV_JIT, API_DRIVER}; cuda2hipRename["CU_JIT_OPTIMIZATION_LEVEL"] = {"hipJitOptionOptimizationLevel", CONV_JIT, API_DRIVER}; cuda2hipRename["CU_JIT_TARGET_FROM_CUCONTEXT"] = {"hipJitOptionTargetFromContext", CONV_JIT, API_DRIVER}; cuda2hipRename["CU_JIT_TARGET"] = {"hipJitOptionTarget", CONV_JIT, API_DRIVER}; cuda2hipRename["CU_JIT_FALLBACK_STRATEGY"] = {"hipJitOptionFallbackStrategy", CONV_JIT, API_DRIVER}; cuda2hipRename["CU_JIT_GENERATE_DEBUG_INFO"] = {"hipJitOptionGenerateDebugInfo", CONV_JIT, API_DRIVER}; cuda2hipRename["CU_JIT_LOG_VERBOSE"] = {"hipJitOptionLogVerbose", CONV_JIT, API_DRIVER}; cuda2hipRename["CU_JIT_GENERATE_LINE_INFO"] = {"hipJitOptionGenerateLineInfo", CONV_JIT, API_DRIVER}; cuda2hipRename["CU_JIT_CACHE_MODE"] = {"hipJitOptionCacheMode", CONV_JIT, API_DRIVER}; // unsupported yet by HIP [CUDA 8.0.44] cuda2hipRename["CU_JIT_NEW_SM3X_OPT"] = {"hipJitOptionSm3xOpt", CONV_JIT, API_DRIVER}; cuda2hipRename["CU_JIT_FAST_COMPILE"] = {"hipJitOptionFastCompile", CONV_JIT, API_DRIVER}; cuda2hipRename["CU_JIT_NUM_OPTIONS"] = {"hipJitOptionNumOptions", CONV_JIT, API_DRIVER}; // enum CUjit_target/CUjit_target_enum cuda2hipRename["CUjit_target"] = {"hipJitTarget", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (no) cuda2hipRename["CUjit_target_enum"] = {"hipJitTarget", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_TARGET_COMPUTE_10"] = {"hipJitTargetCompute10", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_TARGET_COMPUTE_11"] = {"hipJitTargetCompute11", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_TARGET_COMPUTE_12"] = {"hipJitTargetCompute12", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_TARGET_COMPUTE_13"] = {"hipJitTargetCompute13", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_TARGET_COMPUTE_20"] = {"hipJitTargetCompute20", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_TARGET_COMPUTE_21"] = {"hipJitTargetCompute21", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_TARGET_COMPUTE_30"] = {"hipJitTargetCompute30", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_TARGET_COMPUTE_32"] = {"hipJitTargetCompute32", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_TARGET_COMPUTE_35"] = {"hipJitTargetCompute35", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_TARGET_COMPUTE_37"] = {"hipJitTargetCompute37", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_TARGET_COMPUTE_50"] = {"hipJitTargetCompute50", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_TARGET_COMPUTE_52"] = {"hipJitTargetCompute52", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; // unsupported yet by HIP [CUDA 8.0.44] cuda2hipRename["CU_TARGET_COMPUTE_53"] = {"hipJitTargetCompute53", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_TARGET_COMPUTE_60"] = {"hipJitTargetCompute60", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_TARGET_COMPUTE_61"] = {"hipJitTargetCompute61", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_TARGET_COMPUTE_62"] = {"hipJitTargetCompute62", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; // enum CUjitInputType/CUjitInputType_enum cuda2hipRename["CUjitInputType"] = {"hipJitInputType", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (no) cuda2hipRename["CUjitInputType_enum"] = {"hipJitInputType", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_JIT_INPUT_CUBIN"] = {"hipJitInputTypeBin", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_JIT_INPUT_PTX"] = {"hipJitInputTypePtx", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_JIT_INPUT_FATBINARY"] = {"hipJitInputTypeFatBinary", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_JIT_INPUT_OBJECT"] = {"hipJitInputTypeObject", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_JIT_INPUT_LIBRARY"] = {"hipJitInputTypeLibrary", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_JIT_NUM_INPUT_TYPES"] = {"hipJitInputTypeNumInputTypes", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED}; // Limits cuda2hipRename["CUlimit"] = {"hipLimit_t", CONV_TYPE, API_DRIVER}; // API_Runtime ANALOGUE (cudaLimit) cuda2hipRename["CUlimit_enum"] = {"hipLimit_t", CONV_TYPE, API_DRIVER}; // API_Runtime ANALOGUE (cudaLimit) cuda2hipRename["CU_LIMIT_STACK_SIZE"] = {"hipLimitStackSize", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x00 // API_Runtime ANALOGUE (cudaLimitStackSize = 0x00) cuda2hipRename["CU_LIMIT_PRINTF_FIFO_SIZE"] = {"hipLimitPrintfFifoSize", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 // API_Runtime ANALOGUE (cudaLimitPrintfFifoSize = 0x01) cuda2hipRename["CU_LIMIT_MALLOC_HEAP_SIZE"] = {"hipLimitMallocHeapSize", CONV_TYPE, API_DRIVER}; // 0x02 // API_Runtime ANALOGUE (cudaLimitMallocHeapSize = 0x02) cuda2hipRename["CU_LIMIT_DEV_RUNTIME_SYNC_DEPTH"] = {"hipLimitDevRuntimeSyncDepth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x03 // API_Runtime ANALOGUE (cudaLimitDevRuntimeSyncDepth = 0x03) cuda2hipRename["CU_LIMIT_DEV_RUNTIME_PENDING_LAUNCH_COUNT"] = {"hipLimitDevRuntimePendingLaunchCount", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x04 // API_Runtime ANALOGUE (cudaLimitDevRuntimePendingLaunchCount = 0x04) cuda2hipRename["CU_LIMIT_STACK_SIZE"] = {"hipLimitStackSize", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (no) // enum CUmemAttach_flags/CUmemAttach_flags_enum cuda2hipRename["CUmemAttach_flags"] = {"hipMemAttachFlags_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (no) cuda2hipRename["CUmemAttach_flags_enum"] = {"hipMemAttachFlags_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (no) cuda2hipRename["CU_MEM_ATTACH_GLOBAL"] = {"hipMemAttachGlobal", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x1 // API_Runtime ANALOGUE (#define cudaMemAttachGlobal 0x01) cuda2hipRename["CU_MEM_ATTACH_HOST"] = {"hipMemAttachHost", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x2 // API_Runtime ANALOGUE (#define cudaMemAttachHost 0x02) cuda2hipRename["CU_MEM_ATTACH_SINGLE"] = {"hipMemAttachSingle", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x4 // API_Runtime ANALOGUE (#define cudaMemAttachSingle 0x04) // enum CUmemorytype/CUmemorytype_enum cuda2hipRename["CUmemorytype"] = {"hipMemType_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (no - cudaMemoryType is not an analogue) cuda2hipRename["CUmemorytype_enum"] = {"hipMemType_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (no - cudaMemoryType is not an analogue) cuda2hipRename["CU_MEMORYTYPE_HOST"] = {"hipMemTypeHost", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 // API_Runtime ANALOGUE (no) cuda2hipRename["CU_MEMORYTYPE_DEVICE"] = {"hipMemTypeDevice", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 // API_Runtime ANALOGUE (no) cuda2hipRename["CU_MEMORYTYPE_ARRAY"] = {"hipMemTypeArray", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x03 // API_Runtime ANALOGUE (no) cuda2hipRename["CU_MEMORYTYPE_UNIFIED"] = {"hipMemTypeUnified", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x04 // API_Runtime ANALOGUE (no) // enum CUresourcetype cuda2hipRename["CUresourcetype"] = {"hipResourceType", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaResourceType) cuda2hipRename["CUresourcetype_enum"] = {"hipResourceType", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaResourceType) cuda2hipRename["CU_RESOURCE_TYPE_ARRAY"] = {"hipResourceTypeArray", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x00 // API_Runtime ANALOGUE (cudaResourceTypeArray = 0x00) cuda2hipRename["CU_RESOURCE_TYPE_MIPMAPPED_ARRAY"] = {"hipResourceTypeMipmappedArray", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 // API_Runtime ANALOGUE (cudaResourceTypeMipmappedArray = 0x01) cuda2hipRename["CU_RESOURCE_TYPE_LINEAR"] = {"hipResourceTypeLinear", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 // API_Runtime ANALOGUE (cudaResourceTypeLinear = 0x02) cuda2hipRename["CU_RESOURCE_TYPE_PITCH2D"] = {"hipResourceTypePitch2D", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x03 // API_Runtime ANALOGUE (cudaResourceTypePitch2D = 0x03) // enum CUresourceViewFormat/CUresourceViewFormat_enum cuda2hipRename["CUresourceViewFormat"] = {"hipResourceViewFormat", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaResourceViewFormat) cuda2hipRename["CUresourceViewFormat_enum"] = {"hipResourceViewFormat", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaResourceViewFormat) cuda2hipRename["CU_RES_VIEW_FORMAT_NONE"] = {"hipResViewFormatNone", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x00 // API_Runtime ANALOGUE (cudaResViewFormatNone = 0x00) cuda2hipRename["CU_RES_VIEW_FORMAT_UINT_1X8"] = {"hipResViewFormatUnsignedChar1", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 // API_Runtime ANALOGUE (cudaResViewFormatUnsignedChar1 = 0x01) cuda2hipRename["CU_RES_VIEW_FORMAT_UINT_2X8"] = {"hipResViewFormatUnsignedChar2", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 // API_Runtime ANALOGUE (cudaResViewFormatUnsignedChar2 = 0x02) cuda2hipRename["CU_RES_VIEW_FORMAT_UINT_4X8"] = {"hipResViewFormatUnsignedChar4", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x03 // API_Runtime ANALOGUE (cudaResViewFormatUnsignedChar4 = 0x03) cuda2hipRename["CU_RES_VIEW_FORMAT_SINT_1X8"] = {"hipResViewFormatSignedChar1", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x04 // API_Runtime ANALOGUE (cudaResViewFormatSignedChar1 = 0x04) cuda2hipRename["CU_RES_VIEW_FORMAT_SINT_2X8"] = {"hipResViewFormatSignedChar2", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x05 // API_Runtime ANALOGUE (cudaResViewFormatSignedChar2 = 0x05) cuda2hipRename["CU_RES_VIEW_FORMAT_SINT_4X8"] = {"hipResViewFormatSignedChar4", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x06 // API_Runtime ANALOGUE (cudaResViewFormatSignedChar4 = 0x06) cuda2hipRename["CU_RES_VIEW_FORMAT_UINT_1X16"] = {"hipResViewFormatUnsignedShort1", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x07 // API_Runtime ANALOGUE (cudaResViewFormatUnsignedShort1 = 0x07) cuda2hipRename["CU_RES_VIEW_FORMAT_UINT_2X16"] = {"hipResViewFormatUnsignedShort2", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x08 // API_Runtime ANALOGUE (cudaResViewFormatUnsignedShort2 = 0x08) cuda2hipRename["CU_RES_VIEW_FORMAT_UINT_4X16"] = {"hipResViewFormatUnsignedShort4", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x09 // API_Runtime ANALOGUE (cudaResViewFormatUnsignedShort4 = 0x09) cuda2hipRename["CU_RES_VIEW_FORMAT_SINT_1X16"] = {"hipResViewFormatSignedShort1", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x0a // API_Runtime ANALOGUE (cudaResViewFormatSignedShort1 = 0x0a) cuda2hipRename["CU_RES_VIEW_FORMAT_SINT_2X16"] = {"hipResViewFormatSignedShort2", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x0b // API_Runtime ANALOGUE (cudaResViewFormatSignedShort2 = 0x0b) cuda2hipRename["CU_RES_VIEW_FORMAT_SINT_4X16"] = {"hipResViewFormatSignedShort4", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x0c // API_Runtime ANALOGUE (cudaResViewFormatSignedShort4 = 0x0c) cuda2hipRename["CU_RES_VIEW_FORMAT_UINT_1X32"] = {"hipResViewFormatUnsignedInt1", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x0d // API_Runtime ANALOGUE (cudaResViewFormatUnsignedInt1 = 0x0d) cuda2hipRename["CU_RES_VIEW_FORMAT_UINT_2X32"] = {"hipResViewFormatUnsignedInt2", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x0e // API_Runtime ANALOGUE (cudaResViewFormatUnsignedInt2 = 0x0e) cuda2hipRename["CU_RES_VIEW_FORMAT_UINT_4X32"] = {"hipResViewFormatUnsignedInt4", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x0f // API_Runtime ANALOGUE (cudaResViewFormatUnsignedInt4 = 0x0f) cuda2hipRename["CU_RES_VIEW_FORMAT_SINT_1X32"] = {"hipResViewFormatSignedInt1", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x10 // API_Runtime ANALOGUE (cudaResViewFormatSignedInt1 = 0x10) cuda2hipRename["CU_RES_VIEW_FORMAT_SINT_2X32"] = {"hipResViewFormatSignedInt2", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x11 // API_Runtime ANALOGUE (cudaResViewFormatSignedInt2 = 0x11) cuda2hipRename["CU_RES_VIEW_FORMAT_SINT_4X32"] = {"hipResViewFormatSignedInt4", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x12 // API_Runtime ANALOGUE (cudaResViewFormatSignedInt4 = 0x12) cuda2hipRename["CU_RES_VIEW_FORMAT_FLOAT_1X16"] = {"hipResViewFormatHalf1", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x13 // API_Runtime ANALOGUE (cudaResViewFormatHalf1 = 0x13) cuda2hipRename["CU_RES_VIEW_FORMAT_FLOAT_2X16"] = {"hipResViewFormatHalf2", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x14 // API_Runtime ANALOGUE (cudaResViewFormatHalf2 = 0x14) cuda2hipRename["CU_RES_VIEW_FORMAT_FLOAT_4X16"] = {"hipResViewFormatHalf4", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x15 // API_Runtime ANALOGUE (cudaResViewFormatHalf4 = 0x15) cuda2hipRename["CU_RES_VIEW_FORMAT_FLOAT_1X32"] = {"hipResViewFormatFloat1", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x16 // API_Runtime ANALOGUE (cudaResViewFormatFloat1 = 0x16) cuda2hipRename["CU_RES_VIEW_FORMAT_FLOAT_2X32"] = {"hipResViewFormatFloat2", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x17 // API_Runtime ANALOGUE (cudaResViewFormatFloat2 = 0x17) cuda2hipRename["CU_RES_VIEW_FORMAT_FLOAT_4X32"] = {"hipResViewFormatFloat4", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x18 // API_Runtime ANALOGUE (cudaResViewFormatFloat4 = 0x18) cuda2hipRename["CU_RES_VIEW_FORMAT_UNSIGNED_BC1"] = {"hipResViewFormatUnsignedBlockCompressed1", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x19 // API_Runtime ANALOGUE (cudaResViewFormatUnsignedBlockCompressed1 = 0x19) cuda2hipRename["CU_RES_VIEW_FORMAT_UNSIGNED_BC2"] = {"hipResViewFormatUnsignedBlockCompressed2", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x1a // API_Runtime ANALOGUE (cudaResViewFormatUnsignedBlockCompressed2 = 0x1a) cuda2hipRename["CU_RES_VIEW_FORMAT_UNSIGNED_BC3"] = {"hipResViewFormatUnsignedBlockCompressed3", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x1b // API_Runtime ANALOGUE (cudaResViewFormatUnsignedBlockCompressed3 = 0x1b) cuda2hipRename["CU_RES_VIEW_FORMAT_UNSIGNED_BC4"] = {"hipResViewFormatUnsignedBlockCompressed4", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x1c // API_Runtime ANALOGUE (cudaResViewFormatUnsignedBlockCompressed4 = 0x1c) cuda2hipRename["CU_RES_VIEW_FORMAT_SIGNED_BC4"] = {"hipResViewFormatSignedBlockCompressed4", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x1d // API_Runtime ANALOGUE (cudaResViewFormatSignedBlockCompressed4 = 0x1d) cuda2hipRename["CU_RES_VIEW_FORMAT_UNSIGNED_BC5"] = {"hipResViewFormatUnsignedBlockCompressed5", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x1e // API_Runtime ANALOGUE (cudaResViewFormatUnsignedBlockCompressed5 = 0x1e) cuda2hipRename["CU_RES_VIEW_FORMAT_SIGNED_BC5"] = {"hipResViewFormatSignedBlockCompressed5", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x1f // API_Runtime ANALOGUE (cudaResViewFormatSignedBlockCompressed5 = 0x1f) cuda2hipRename["CU_RES_VIEW_FORMAT_UNSIGNED_BC6H"] = {"hipResViewFormatUnsignedBlockCompressed6H", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x20 // API_Runtime ANALOGUE (cudaResViewFormatUnsignedBlockCompressed6H = 0x20) cuda2hipRename["CU_RES_VIEW_FORMAT_SIGNED_BC6H"] = {"hipResViewFormatSignedBlockCompressed6H", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x21 // API_Runtime ANALOGUE (cudaResViewFormatSignedBlockCompressed6H = 0x21) cuda2hipRename["CU_RES_VIEW_FORMAT_UNSIGNED_BC7"] = {"hipResViewFormatUnsignedBlockCompressed7", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 0x22 // API_Runtime ANALOGUE (cudaResViewFormatUnsignedBlockCompressed7 = 0x22) cuda2hipRename["CUsharedconfig"] = {"hipSharedMemConfig", CONV_TYPE, API_DRIVER}; cuda2hipRename["CUsharedconfig_enum"] = {"hipSharedMemConfig", CONV_TYPE, API_DRIVER}; cuda2hipRename["CU_SHARED_MEM_CONFIG_DEFAULT_BANK_SIZE"] = {"hipSharedMemBankSizeDefault", CONV_TYPE, API_DRIVER}; cuda2hipRename["CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE"] = {"hipSharedMemBankSizeFourByte", CONV_TYPE, API_DRIVER}; cuda2hipRename["CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE"] = {"hipSharedMemBankSizeEightByte", CONV_TYPE, API_DRIVER}; cuda2hipRename["CUcontext"] = {"hipCtx_t", CONV_TYPE, API_DRIVER}; // TODO: move "typedef struct ihipCtx_t *hipCtx_t;" from hcc_details to HIP // typedef struct CUctx_st *CUcontext; // cuda2hipRename["CUctx_st"] = {"ihipCtx_t", CONV_TYPE, API_DRIVER}; cuda2hipRename["CUmodule"] = {"hipModule_t", CONV_TYPE, API_DRIVER}; // TODO: move "typedef struct ihipModule_t *hipModule_t;" from hcc_details to HIP // typedef struct CUmod_st *CUmodule; // cuda2hipRename["CUmod_st"] = {"ihipModule_t", CONV_TYPE, API_DRIVER}; cuda2hipRename["CUstream"] = {"hipStream_t", CONV_TYPE, API_DRIVER}; // TODO: move "typedef struct ihipStream_t *hipStream_t;" from hcc_details to HIP // typedef struct CUstream_st *CUstream; // cuda2hipRename["CUstream_st"] = {"ihipStream_t", CONV_TYPE, API_DRIVER}; // typedef void (*hipStreamCallback_t) (hipStream_t stream, hipError_t status, void* userData); // typedef void (CUDA_CB *CUstreamCallback) (CUstream hStream, CUresult status, void* userData) cuda2hipRename["CUstreamCallback"] = {"hipStreamCallback_t", CONV_TYPE, API_DRIVER}; cuda2hipRename["CUsurfObject"] = {"hipSurfaceObject", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // typedef struct CUsurfref_st *CUsurfref; cuda2hipRename["CUsurfref"] = {"hipSurfaceReference_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // cuda2hipRename["CUsurfref_st"] = {"ihipSurfaceReference_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CUtexObject"] = {"hipTextureObject", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // typedef struct CUtexref_st *CUtexref; cuda2hipRename["CUtexref"] = {"hipTextureReference_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // cuda2hipRename["CUtexref_st"] = {"ihipTextureReference_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // Stream Flags enum cuda2hipRename["CUstream_flags"] = {"hipStreamFlags", CONV_TYPE, API_DRIVER}; // cuda2hipRename["CUstream_flags_enum"] = {"hipStreamFlags", CONV_TYPE, API_DRIVER}; cuda2hipRename["CU_STREAM_DEFAULT"] = {"hipStreamDefault", CONV_TYPE, API_DRIVER}; cuda2hipRename["CU_STREAM_NON_BLOCKING"] = {"hipStreamNonBlocking", CONV_TYPE, API_DRIVER}; // unsupported yet by HIP [CUDA 8.0.44] // Flags for ::cuStreamWaitValue32 cuda2hipRename["CUstreamWaitValue_flags"] = {"hipStreamWaitValueFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // cuda2hipRename["CUstreamWaitValue_flags_enum"] = {"hipStreamWaitValueFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_STREAM_WAIT_VALUE_GEQ"] = {"hipStreamWaitValueGeq", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x0 cuda2hipRename["CU_STREAM_WAIT_VALUE_EQ"] = {"hipStreamWaitValueEq", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x1 cuda2hipRename["CU_STREAM_WAIT_VALUE_AND"] = {"hipStreamWaitValueAnd", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x2 cuda2hipRename["CU_STREAM_WAIT_VALUE_FLUSH"] = {"hipStreamWaitValueFlush", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 1<<30 // Flags for ::cuStreamWriteValue32 cuda2hipRename["CUstreamWriteValue_flags"] = {"hipStreamWriteValueFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // cuda2hipRename["CUstreamWriteValue_flags"] = {"hipStreamWriteValueFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_STREAM_WRITE_VALUE_DEFAULT"] = {"hipStreamWriteValueDefault", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x0 cuda2hipRename["CU_STREAM_WRITE_VALUE_NO_MEMORY_BARRIER"] = {"hipStreamWriteValueNoMemoryBarrier", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x1 // Flags for ::cuStreamBatchMemOp cuda2hipRename["CUstreamBatchMemOpType"] = {"hipStreamBatchMemOpType", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // cuda2hipRename["CUstreamBatchMemOpType_enum"] = {"hipStreamBatchMemOpType", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_STREAM_MEM_OP_WAIT_VALUE_32"] = {"hipStreamBatchMemOpWaitValue32", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 1 cuda2hipRename["CU_STREAM_MEM_OP_WRITE_VALUE_32"] = {"hipStreamBatchMemOpWriteValue32", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 2 cuda2hipRename["CU_STREAM_MEM_OP_FLUSH_REMOTE_WRITES"] = {"hipStreamBatchMemOpFlushRemoteWrites", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 3 // Error Handling cuda2hipRename["cuGetErrorName"] = {"hipGetErrorName___", CONV_ERROR, API_DRIVER, HIP_UNSUPPORTED}; // cudaGetErrorName (hipGetErrorName) has different signature cuda2hipRename["cuGetErrorString"] = {"hipGetErrorString___", CONV_ERROR, API_DRIVER, HIP_UNSUPPORTED}; // cudaGetErrorString (hipGetErrorString) has different signature // Init cuda2hipRename["cuInit"] = {"hipInit", CONV_INIT, API_DRIVER}; // Driver cuda2hipRename["cuDriverGetVersion"] = {"hipDriverGetVersion", CONV_VERSION, API_DRIVER}; // Context Management cuda2hipRename["cuCtxCreate_v2"] = {"hipCtxCreate", CONV_CONTEXT, API_DRIVER}; cuda2hipRename["cuCtxDestroy_v2"] = {"hipCtxDestroy", CONV_CONTEXT, API_DRIVER}; cuda2hipRename["cuCtxGetApiVersion"] = {"hipCtxGetApiVersion", CONV_CONTEXT, API_DRIVER}; cuda2hipRename["cuCtxGetCacheConfig"] = {"hipCtxGetCacheConfig", CONV_CONTEXT, API_DRIVER}; cuda2hipRename["cuCtxGetCurrent"] = {"hipCtxGetCurrent", CONV_CONTEXT, API_DRIVER}; cuda2hipRename["cuCtxGetDevice"] = {"hipCtxGetDevice", CONV_CONTEXT, API_DRIVER}; cuda2hipRename["cuCtxGetFlags"] = {"hipCtxGetFlags", CONV_CONTEXT, API_DRIVER}; cuda2hipRename["cuCtxGetLimit"] = {"hipCtxGetLimit", CONV_CONTEXT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuCtxGetSharedMemConfig"] = {"hipCtxGetSharedMemConfig", CONV_CONTEXT, API_DRIVER}; cuda2hipRename["cuCtxGetStreamPriorityRange"] = {"hipCtxGetStreamPriorityRange", CONV_CONTEXT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuCtxPopCurrent_v2"] = {"hipCtxPopCurrent", CONV_CONTEXT, API_DRIVER}; cuda2hipRename["cuCtxPushCurrent_v2"] = {"hipCtxPushCurrent", CONV_CONTEXT, API_DRIVER}; cuda2hipRename["cuCtxSetCacheConfig"] = {"hipCtxSetCacheConfig", CONV_CONTEXT, API_DRIVER}; cuda2hipRename["cuCtxSetCurrent"] = {"hipCtxSetCurrent", CONV_CONTEXT, API_DRIVER}; cuda2hipRename["cuCtxSetLimit"] = {"hipCtxSetLimit", CONV_CONTEXT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuCtxSetSharedMemConfig"] = {"hipCtxSetSharedMemConfig", CONV_CONTEXT, API_DRIVER}; cuda2hipRename["cuCtxSynchronize"] = {"hipCtxSynchronize", CONV_CONTEXT, API_DRIVER}; // Context Management [DEPRECATED] cuda2hipRename["cuCtxAttach"] = {"hipCtxAttach", CONV_CONTEXT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuCtxDetach"] = {"hipCtxDetach", CONV_CONTEXT, API_DRIVER, HIP_UNSUPPORTED}; // Peer Context Memory Access cuda2hipRename["cuCtxEnablePeerAccess"] = {"hipCtxEnablePeerAccess", CONV_PEER, API_DRIVER}; cuda2hipRename["cuCtxDisablePeerAccess"] = {"hipCtxDisablePeerAccess", CONV_PEER, API_DRIVER}; cuda2hipRename["cuDeviceCanAccessPeer"] = {"hipDeviceCanAccessPeer", CONV_PEER, API_DRIVER}; cuda2hipRename["cuDeviceGetP2PAttribute"] = {"hipDeviceGetP2PAttribute", CONV_PEER, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaDeviceGetP2PAttribute) // Primary Context Management cuda2hipRename["cuDevicePrimaryCtxGetState"] = {"hipDevicePrimaryCtxGetState", CONV_CONTEXT, API_DRIVER}; cuda2hipRename["cuDevicePrimaryCtxRelease"] = {"hipDevicePrimaryCtxRelease", CONV_CONTEXT, API_DRIVER}; cuda2hipRename["cuDevicePrimaryCtxReset"] = {"hipDevicePrimaryCtxReset", CONV_CONTEXT, API_DRIVER}; cuda2hipRename["cuDevicePrimaryCtxRetain"] = {"hipDevicePrimaryCtxRetain", CONV_CONTEXT, API_DRIVER}; cuda2hipRename["cuDevicePrimaryCtxSetFlags"] = {"hipDevicePrimaryCtxSetFlags", CONV_CONTEXT, API_DRIVER}; // Device Management cuda2hipRename["cuDeviceGet"] = {"hipGetDevice", CONV_DEVICE, API_DRIVER}; cuda2hipRename["cuDeviceGetName"] = {"hipDeviceGetName", CONV_DEVICE, API_DRIVER}; cuda2hipRename["cuDeviceGetCount"] = {"hipGetDeviceCount", CONV_DEVICE, API_DRIVER}; cuda2hipRename["cuDeviceGetAttribute"] = {"hipDeviceGetAttribute", CONV_DEVICE, API_DRIVER}; cuda2hipRename["cuDeviceGetPCIBusId"] = {"hipDeviceGetPCIBusId", CONV_DEVICE, API_DRIVER}; cuda2hipRename["cuDeviceGetByPCIBusId"] = {"hipDeviceGetByPCIBusId", CONV_DEVICE, API_DRIVER}; cuda2hipRename["cuDeviceTotalMem_v2"] = {"hipDeviceTotalMem", CONV_DEVICE, API_DRIVER}; // Device Management [DEPRECATED] cuda2hipRename["cuDeviceComputeCapability"] = {"hipDeviceComputeCapability", CONV_DEVICE, API_DRIVER}; cuda2hipRename["cuDeviceGetProperties"] = {"hipGetDeviceProperties", CONV_DEVICE, API_DRIVER}; // Module Management cuda2hipRename["cuLinkAddData"] = {"hipLinkAddData", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuLinkAddFile"] = {"hipLinkAddFile", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuLinkComplete"] = {"hipLinkComplete", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuLinkCreate"] = {"hipLinkCreate", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuLinkDestroy"] = {"hipLinkDestroy", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuModuleGetFunction"] = {"hipModuleGetFunction", CONV_MODULE, API_DRIVER}; cuda2hipRename["cuModuleGetGlobal_v2"] = {"hipModuleGetGlobal", CONV_MODULE, API_DRIVER}; cuda2hipRename["cuModuleGetSurfRef"] = {"hipModuleGetSurfRef", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuModuleGetTexRef"] = {"hipModuleGetTexRef", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuModuleLoad"] = {"hipModuleLoad", CONV_MODULE, API_DRIVER}; cuda2hipRename["cuModuleLoadData"] = {"hipModuleLoadData", CONV_MODULE, API_DRIVER}; cuda2hipRename["cuModuleLoadDataEx"] = {"hipModuleLoadDataEx", CONV_MODULE, API_DRIVER}; cuda2hipRename["cuModuleLoadFatBinary"] = {"hipModuleLoadFatBinary", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuModuleUnload"] = {"hipModuleUnload", CONV_MODULE, API_DRIVER}; // unsupported yet by HIP [CUDA 8.0.44] // P2P Attributes cuda2hipRename["CUdevice_P2PAttribute"] = {"hipDeviceP2PAttribute", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaDeviceP2PAttr) // cuda2hipRename["CUdevice_P2PAttribute_enum"] = {"hipDeviceP2PAttribute", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_DEVICE_P2P_ATTRIBUTE_PERFORMANCE_RANK"] = {"hipDeviceP2PAttributePerformanceRank", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 // API_Runtime ANALOGUE (cudaDevP2PAttrPerformanceRank = 0x01) cuda2hipRename["CU_DEVICE_P2P_ATTRIBUTE_ACCESS_SUPPORTED"] = {"hipDeviceP2PAttributeAccessSupported", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 // API_Runtime ANALOGUE (cudaDevP2PAttrAccessSupported = 0x02) cuda2hipRename["CU_DEVICE_P2P_ATTRIBUTE_NATIVE_ATOMIC_SUPPORTED"] = {"hipDeviceP2PAttributeNativeAtomicSupported", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED}; // 0x03 // API_Runtime ANALOGUE (cudaDevP2PAttrNativeAtomicSupported = 0x03) // Events // pointer to CUevent_st cuda2hipRename["CUevent"] = {"hipEvent_t", CONV_TYPE, API_DRIVER}; // ToDo: // cuda2hipRename["CUevent_st"] = {"XXXX", CONV_TYPE, API_DRIVER}; // Event Flags cuda2hipRename["CUevent_flags"] = {"hipEventFlags", CONV_EVENT, API_DRIVER, HIP_UNSUPPORTED}; // ToDo: // cuda2hipRename["CUevent_flags_enum"] = {"hipEventFlags", CONV_EVENT, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_EVENT_DEFAULT"] = {"hipEventDefault", CONV_EVENT, API_DRIVER}; cuda2hipRename["CU_EVENT_BLOCKING_SYNC"] = {"hipEventBlockingSync", CONV_EVENT, API_DRIVER}; cuda2hipRename["CU_EVENT_DISABLE_TIMING"] = {"hipEventDisableTiming", CONV_EVENT, API_DRIVER}; cuda2hipRename["CU_EVENT_INTERPROCESS"] = {"hipEventInterprocess", CONV_EVENT, API_DRIVER}; // Event functions cuda2hipRename["cuEventCreate"] = {"hipEventCreate", CONV_EVENT, API_DRIVER}; cuda2hipRename["cuEventDestroy_v2"] = {"hipEventDestroy", CONV_EVENT, API_DRIVER}; cuda2hipRename["cuEventElapsedTime"] = {"hipEventElapsedTime", CONV_EVENT, API_DRIVER}; cuda2hipRename["cuEventQuery"] = {"hipEventQuery", CONV_EVENT, API_DRIVER}; cuda2hipRename["cuEventRecord"] = {"hipEventRecord", CONV_EVENT, API_DRIVER}; cuda2hipRename["cuEventSynchronize"] = {"hipEventSynchronize", CONV_EVENT, API_DRIVER}; // Execution Control cuda2hipRename["cuFuncGetAttribute"] = {"hipFuncGetAttribute", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuFuncSetCacheConfig"] = {"hipFuncSetCacheConfig", CONV_MODULE, API_DRIVER}; cuda2hipRename["cuFuncSetSharedMemConfig"] = {"hipFuncSetSharedMemConfig", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuLaunchKernel"] = {"hipModuleLaunchKernel", CONV_MODULE, API_DRIVER}; // Execution Control [DEPRECATED] cuda2hipRename["cuFuncSetBlockShape"] = {"hipFuncSetBlockShape", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuFuncSetSharedSize"] = {"hipFuncSetSharedSize", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuLaunch"] = {"hipLaunch", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaLaunch) cuda2hipRename["cuLaunchGrid"] = {"hipLaunchGrid", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuLaunchGridAsync"] = {"hipLaunchGridAsync", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuParamSetf"] = {"hipParamSetf", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuParamSeti"] = {"hipParamSeti", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuParamSetSize"] = {"hipParamSetSize", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuParamSetSize"] = {"hipParamSetSize", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuParamSetv"] = {"hipParamSetv", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED}; // Occupancy cuda2hipRename["cuOccupancyMaxActiveBlocksPerMultiprocessor"] = {"hipOccupancyMaxActiveBlocksPerMultiprocessor", CONV_OCCUPANCY, API_DRIVER}; // API_Runtime ANALOGUE (cudaOccupancyMaxActiveBlocksPerMultiprocessor) cuda2hipRename["cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags"] = {"hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags", CONV_OCCUPANCY, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags) cuda2hipRename["cuOccupancyMaxPotentialBlockSize"] = {"hipOccupancyMaxPotentialBlockSize", CONV_OCCUPANCY, API_DRIVER}; // API_Runtime ANALOGUE (cudaOccupancyMaxPotentialBlockSize) cuda2hipRename["cuOccupancyMaxPotentialBlockSizeWithFlags"] = {"hipOccupancyMaxPotentialBlockSizeWithFlags", CONV_OCCUPANCY, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaOccupancyMaxPotentialBlockSizeWithFlags) // Streams cuda2hipRename["cuStreamAddCallback"] = {"hipStreamAddCallback", CONV_STREAM, API_DRIVER}; cuda2hipRename["cuStreamAttachMemAsync"] = {"hipStreamAttachMemAsync", CONV_STREAM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuStreamCreate"] = {"hipStreamCreate__", CONV_STREAM, API_DRIVER, HIP_UNSUPPORTED}; // Not equal to cudaStreamCreate due to different signatures cuda2hipRename["cuStreamCreateWithPriority"] = {"hipStreamCreateWithPriority", CONV_STREAM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuStreamDestroy_v2"] = {"hipStreamDestroy", CONV_STREAM, API_DRIVER}; cuda2hipRename["cuStreamGetFlags"] = {"hipStreamGetFlags", CONV_STREAM, API_DRIVER}; cuda2hipRename["cuStreamGetPriority"] = {"hipStreamGetPriority", CONV_STREAM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuStreamQuery"] = {"hipStreamQuery", CONV_STREAM, API_DRIVER}; cuda2hipRename["cuStreamSynchronize"] = {"hipStreamSynchronize", CONV_STREAM, API_DRIVER}; cuda2hipRename["cuStreamWaitEvent"] = {"hipStreamWaitEvent", CONV_STREAM, API_DRIVER}; cuda2hipRename["cuStreamWaitValue32"] = {"hipStreamWaitValue32", CONV_STREAM, API_DRIVER, HIP_UNSUPPORTED}; // [CUDA 8.0.44] // no API_Runtime ANALOGUE cuda2hipRename["cuStreamWriteValue32"] = {"hipStreamWriteValue32", CONV_STREAM, API_DRIVER, HIP_UNSUPPORTED}; // [CUDA 8.0.44] // no API_Runtime ANALOGUE cuda2hipRename["cuStreamBatchMemOp"] = {"hipStreamBatchMemOp", CONV_STREAM, API_DRIVER, HIP_UNSUPPORTED}; // [CUDA 8.0.44] // no API_Runtime ANALOGUE // Memory management cuda2hipRename["cuArray3DCreate"] = {"hipArray3DCreate", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuArray3DGetDescriptor"] = {"hipArray3DGetDescriptor", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuArrayCreate"] = {"hipArrayCreate", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuArrayDestroy"] = {"hipArrayDestroy", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuArrayGetDescriptor"] = {"hipArrayGetDescriptor", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuIpcCloseMemHandle"] = {"hipIpcCloseMemHandle", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuIpcGetEventHandle"] = {"hipIpcGetEventHandle", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuIpcGetMemHandle"] = {"hipIpcGetMemHandle", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuIpcOpenEventHandle"] = {"hipIpcOpenEventHandle", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuIpcOpenMemHandle"] = {"hipIpcOpenMemHandle", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemAlloc_v2"] = {"hipMalloc", CONV_MEM, API_DRIVER}; cuda2hipRename["cuMemAllocHost"] = {"hipMemAllocHost", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemAllocManaged"] = {"hipMemAllocManaged", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemAllocPitch"] = {"hipMemAllocPitch__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; // Not equal to cudaMemAllocPitch due to different signatures cuda2hipRename["cuMemcpy"] = {"hipMemcpy__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; // Not equal to cudaMemcpy due to different signatures cuda2hipRename["cuMemcpy2D"] = {"hipMemcpy2D__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; // Not equal to cudaMemcpy2D due to different signatures cuda2hipRename["cuMemcpy2DAsync"] = {"hipMemcpy2DAsync__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; // Not equal to cudaMemcpy2DAsync due to different signatures cuda2hipRename["cuMemcpy2DUnaligned"] = {"hipMemcpy2DUnaligned", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemcpy3D"] = {"hipMemcpy3D__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; // Not equal to cudaMemcpy3D due to different signatures cuda2hipRename["cuMemcpy3DAsync"] = {"hipMemcpy3DAsync__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; // Not equal to cudaMemcpy3DAsync due to different signatures cuda2hipRename["cuMemcpy3DPeer"] = {"hipMemcpy3DPeer__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; // Not equal to cudaMemcpy3DPeer due to different signatures cuda2hipRename["cuMemcpy3DPeerAsync"] = {"hipMemcpy3DPeerAsync__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; // Not equal to cudaMemcpy3DPeerAsync due to different signatures cuda2hipRename["cuMemcpyAsync"] = {"hipMemcpyAsync__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; // Not equal to cudaMemcpyAsync due to different signatures cuda2hipRename["cuMemcpyAtoA"] = {"hipMemcpyAtoA", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemcpyAtoD"] = {"hipMemcpyAtoD", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemcpyAtoH"] = {"hipMemcpyAtoH", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemcpyAtoHAsync"] = {"hipMemcpyAtoHAsync", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemcpyDtoA"] = {"hipMemcpyDtoA", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemcpyDtoD_v2"] = {"hipMemcpyDtoD", CONV_MEM, API_DRIVER}; cuda2hipRename["cuMemcpyDtoDAsync_v2"] = {"hipMemcpyDtoDAsync", CONV_MEM, API_DRIVER}; cuda2hipRename["cuMemcpyDtoH_v2"] = {"hipMemcpyDtoH", CONV_MEM, API_DRIVER}; cuda2hipRename["cuMemcpyDtoHAsync_v2"] = {"hipMemcpyDtoHAsync", CONV_MEM, API_DRIVER}; cuda2hipRename["cuMemcpyHtoA"] = {"hipMemcpyHtoA", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemcpyHtoAAsync"] = {"hipMemcpyHtoAAsync", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemcpyHtoD_v2"] = {"hipMemcpyHtoD", CONV_MEM, API_DRIVER}; cuda2hipRename["cuMemcpyHtoDAsync_v2"] = {"hipMemcpyHtoDAsync", CONV_MEM, API_DRIVER}; cuda2hipRename["cuMemcpyPeerAsync"] = {"hipMemcpyPeerAsync__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; // Not equal to cudaMemcpyPeerAsync due to different signatures cuda2hipRename["cuMemcpyPeer"] = {"hipMemcpyPeer__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; // Not equal to cudaMemcpyPeer due to different signatures cuda2hipRename["cuMemFree_v2"] = {"hipFree", CONV_MEM, API_DRIVER}; cuda2hipRename["cuMemFreeHost"] = {"hipHostFree", CONV_MEM, API_DRIVER}; cuda2hipRename["cuMemGetAddressRange"] = {"hipMemGetAddressRange", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemGetInfo_v2"] = {"hipMemGetInfo", CONV_MEM, API_DRIVER}; cuda2hipRename["cuMemHostAlloc"] = {"hipHostMalloc", CONV_MEM, API_DRIVER}; // API_Runtime ANALOGUE (cudaHostAlloc) cuda2hipRename["cuMemHostGetDevicePointer"] = {"hipMemHostGetDevicePointer", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemHostGetFlags"] = {"hipMemHostGetFlags", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemHostRegister_v2"] = {"hipHostRegister", CONV_MEM, API_DRIVER}; // API_Runtime ANALOGUE (cudaHostAlloc) cuda2hipRename["cuMemHostUnregister"] = {"hipHostUnregister", CONV_MEM, API_DRIVER}; // API_Runtime ANALOGUE (cudaHostUnregister) cuda2hipRename["cuMemsetD16_v2"] = {"hipMemsetD16", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemsetD16Async"] = {"hipMemsetD16Async", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemsetD2D16_v2"] = {"hipMemsetD2D16", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemsetD2D16Async"] = {"hipMemsetD2D16Async", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemsetD2D32_v2"] = {"hipMemsetD2D32", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemsetD2D32Async"] = {"hipMemsetD2D32Async", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemsetD2D8_v2"] = {"hipMemsetD2D8", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemsetD2D8Async"] = {"hipMemsetD2D8Async", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemsetD32_v2"] = {"hipMemset", CONV_MEM, API_DRIVER}; // API_Runtime ANALOGUE (cudaMemset) cuda2hipRename["cuMemsetD32Async"] = {"hipMemsetAsync", CONV_MEM, API_DRIVER}; // API_Runtime ANALOGUE (cudaMemsetAsync) cuda2hipRename["cuMemsetD8_v2"] = {"hipMemsetD8", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMemsetD8Async"] = {"hipMemsetD8Async", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMipmappedArrayCreate"] = {"hipMipmappedArrayCreate", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMipmappedArrayDestroy"] = {"hipMipmappedArrayDestroy", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuMipmappedArrayGetLevel"] = {"hipMipmappedArrayGetLevel", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; // Unified Addressing cuda2hipRename["cuMemPrefetchAsync"] = {"hipMemPrefetchAsync__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; // [CUDA 8.0.44] // no API_Runtime ANALOGUE (cudaMemPrefetchAsync has different signature) cuda2hipRename["cuMemAdvise"] = {"hipMemAdvise", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; // [CUDA 8.0.44] // API_Runtime ANALOGUE (cudaMemAdvise) cuda2hipRename["cuMemRangeGetAttribute"] = {"hipMemRangeGetAttribute", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; // [CUDA 8.0.44] // API_Runtime ANALOGUE (cudaMemRangeGetAttribute) cuda2hipRename["cuMemRangeGetAttributes"] = {"hipMemRangeGetAttributes", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; // [CUDA 8.0.44] // API_Runtime ANALOGUE (cudaMemRangeGetAttributes) cuda2hipRename["cuPointerGetAttribute"] = {"hipPointerGetAttribute", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuPointerGetAttributes"] = {"hipPointerGetAttributes", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuPointerSetAttribute"] = {"hipPointerSetAttribute", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED}; // Texture Reference Mngmnt // Texture reference filtering modes cuda2hipRename["CUfilter_mode"] = {"hipTextureFilterMode", CONV_TEX, API_DRIVER}; // API_Runtime ANALOGUE (cudaTextureFilterMode) // ToDo: // cuda2hipRename["CUfilter_mode"] = {"CUfilter_mode_enum", CONV_TEX, API_DRIVER}; // API_Runtime ANALOGUE (cudaTextureFilterMode) cuda2hipRename["CU_TR_FILTER_MODE_POINT"] = {"hipFilterModePoint", CONV_TEX, API_DRIVER}; // 0 // API_Runtime ANALOGUE (cudaFilterModePoint = 0) cuda2hipRename["CU_TR_FILTER_MODE_LINEAR"] = {"hipFilterModeLinear", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // 1 // API_Runtime ANALOGUE (cudaFilterModeLinear = 1) cuda2hipRename["cuTexRefGetAddress"] = {"hipTexRefGetAddress", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefGetAddressMode"] = {"hipTexRefGetAddressMode", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefGetArray"] = {"hipTexRefGetArray", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefGetBorderColor"] = {"hipTexRefGetBorderColor", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // [CUDA 8.0.44] // no API_Runtime ANALOGUE cuda2hipRename["cuTexRefGetFilterMode"] = {"hipTexRefGetFilterMode", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefGetFlags"] = {"hipTexRefGetFlags", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefGetFormat"] = {"hipTexRefGetFormat", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefGetMaxAnisotropy"] = {"hipTexRefGetMaxAnisotropy", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefGetMipmapFilterMode"] = {"hipTexRefGetMipmapFilterMode", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefGetMipmapLevelBias"] = {"hipTexRefGetMipmapLevelBias", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefGetMipmapLevelClamp"] = {"hipTexRefGetMipmapLevelClamp", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefGetMipmappedArray"] = {"hipTexRefGetMipmappedArray", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefSetAddress"] = {"hipTexRefSetAddress", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefSetAddress2D"] = {"hipTexRefSetAddress2D", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefSetAddressMode"] = {"hipTexRefSetAddressMode", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefSetArray"] = {"hipTexRefSetArray", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefSetBorderColor"] = {"hipTexRefSetBorderColor", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // [CUDA 8.0.44] // no API_Runtime ANALOGUE cuda2hipRename["cuTexRefSetFilterMode"] = {"hipTexRefSetFilterMode", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefSetFlags"] = {"hipTexRefSetFlags", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefSetFormat"] = {"hipTexRefSetFormat", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefSetMaxAnisotropy"] = {"hipTexRefSetMaxAnisotropy", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefSetMipmapFilterMode"] = {"hipTexRefSetMipmapFilterMode", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefSetMipmapLevelBias"] = {"hipTexRefSetMipmapLevelBias", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefSetMipmapLevelClamp"] = {"hipTexRefSetMipmapLevelClamp", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefSetMipmappedArray"] = {"hipTexRefSetMipmappedArray", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // Texture Reference Mngmnt [DEPRECATED] cuda2hipRename["cuTexRefCreate"] = {"hipTexRefCreate", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexRefDestroy"] = {"hipTexRefDestroy", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // Surface Reference Mngmnt cuda2hipRename["cuSurfRefGetArray"] = {"hipSurfRefGetArray", CONV_SURFACE, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuSurfRefSetArray"] = {"hipSurfRefSetArray", CONV_SURFACE, API_DRIVER, HIP_UNSUPPORTED}; // Texture Object Mngmnt cuda2hipRename["cuTexObjectCreate"] = {"hipTexObjectCreate", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexObjectDestroy"] = {"hipTexObjectDestroy", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexObjectGetResourceDesc"] = {"hipTexObjectGetResourceDesc", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexObjectGetResourceViewDesc"] = {"hipTexObjectGetResourceViewDesc", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuTexObjectGetTextureDesc"] = {"hipTexObjectGetTextureDesc", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // Surface Object Mngmnt cuda2hipRename["cuSurfObjectCreate"] = {"hipSurfObjectCreate", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuSurfObjectDestroy"] = {"hipSurfObjectDestroy", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["cuSurfObjectGetResourceDesc"] = {"hipSurfObjectGetResourceDesc", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED}; // Graphics Interoperability cuda2hipRename["cuGraphicsMapResources"] = {"hipGraphicsMapResources", CONV_GRAPHICS, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsMapResources) cuda2hipRename["cuGraphicsResourceGetMappedMipmappedArray"] = {"hipGraphicsResourceGetMappedMipmappedArray", CONV_GRAPHICS, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsResourceGetMappedMipmappedArray) cuda2hipRename["cuGraphicsResourceGetMappedPointer"] = {"hipGraphicsResourceGetMappedPointer", CONV_GRAPHICS, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsResourceGetMappedPointer) cuda2hipRename["cuGraphicsResourceSetMapFlags"] = {"hipGraphicsResourceSetMapFlags", CONV_GRAPHICS, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsResourceSetMapFlags) cuda2hipRename["cuGraphicsSubResourceGetMappedArray"] = {"hipGraphicsSubResourceGetMappedArray", CONV_GRAPHICS, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsSubResourceGetMappedArray) cuda2hipRename["cuGraphicsUnmapResources"] = {"hipGraphicsUnmapResources", CONV_GRAPHICS, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsUnmapResources) cuda2hipRename["cuGraphicsUnregisterResource"] = {"hipGraphicsUnregisterResource", CONV_GRAPHICS, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsUnregisterResource) // Profiler cuda2hipRename["cuProfilerInitialize"] = {"hipProfilerInitialize", CONV_OTHER, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaProfilerInitialize) cuda2hipRename["cuProfilerStart"] = {"hipProfilerStart", CONV_OTHER, API_DRIVER}; // API_Runtime ANALOGUE (cudaProfilerStart) cuda2hipRename["cuProfilerStop"] = {"hipProfilerStop", CONV_OTHER, API_DRIVER}; // API_Runtime ANALOGUE (cudaProfilerStop) // OpenGL Interoperability // enum CUGLDeviceList/CUGLDeviceList_enum cuda2hipRename["CUGLDeviceList"] = {"hipGLDeviceList", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGLDeviceList) // cuda2hipRename["CUGLDeviceList_enum"] = {"hipGLDeviceList", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_GL_DEVICE_LIST_ALL"] = {"HIP_GL_DEVICE_LIST_ALL", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 // API_Runtime ANALOGUE (cudaGLDeviceListAll) cuda2hipRename["CU_GL_DEVICE_LIST_CURRENT_FRAME"] = {"HIP_GL_DEVICE_LIST_CURRENT_FRAME", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 // API_Runtime ANALOGUE (cudaGLDeviceListCurrentFrame) cuda2hipRename["CU_GL_DEVICE_LIST_NEXT_FRAME"] = {"HIP_GL_DEVICE_LIST_NEXT_FRAME", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // 0x03 // API_Runtime ANALOGUE (cudaGLDeviceListNextFrame) cuda2hipRename["cuGLGetDevices"] = {"hipGLGetDevices", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGLGetDevices) cuda2hipRename["cuGraphicsGLRegisterBuffer"] = {"hipGraphicsGLRegisterBuffer", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsGLRegisterBuffer) cuda2hipRename["cuGraphicsGLRegisterImage"] = {"hipGraphicsGLRegisterImage", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsGLRegisterImage) cuda2hipRename["cuWGLGetDevice"] = {"hipWGLGetDevice", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaWGLGetDevice) // OpenGL Interoperability [DEPRECATED] // enum CUGLmap_flags/CUGLmap_flags_enum cuda2hipRename["CUGLmap_flags"] = {"hipGLMapFlags", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGLMapFlags) // cuda2hipRename["CUGLmap_flags_enum"] = {"hipGLMapFlags", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_GL_MAP_RESOURCE_FLAGS_NONE"] = {"HIP_GL_MAP_RESOURCE_FLAGS_NONE", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // 0x00 // API_Runtime ANALOGUE (cudaGLMapFlagsNone) cuda2hipRename["CU_GL_MAP_RESOURCE_FLAGS_READ_ONLY"] = {"HIP_GL_MAP_RESOURCE_FLAGS_READ_ONLY", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 // API_Runtime ANALOGUE (cudaGLMapFlagsReadOnly) cuda2hipRename["CU_GL_MAP_RESOURCE_FLAGS_WRITE_DISCARD"] = {"HIP_GL_MAP_RESOURCE_FLAGS_WRITE_DISCARD", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 // API_Runtime ANALOGUE (cudaGLMapFlagsWriteDiscard) cuda2hipRename["cuGLCtxCreate"] = {"hipGLCtxCreate", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // no API_Runtime ANALOGUE cuda2hipRename["cuGLInit"] = {"hipGLInit", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // no API_Runtime ANALOGUE cuda2hipRename["cuGLMapBufferObject"] = {"hipGLMapBufferObject", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // Not equal to cudaGLMapBufferObject due to different signatures cuda2hipRename["cuGLMapBufferObjectAsync"] = {"hipGLMapBufferObjectAsync", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // Not equal to cudaGLMapBufferObjectAsync due to different signatures cuda2hipRename["cuGLRegisterBufferObject"] = {"hipGLRegisterBufferObject", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGLRegisterBufferObject) cuda2hipRename["cuGLSetBufferObjectMapFlags"] = {"hipGLSetBufferObjectMapFlags", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGLSetBufferObjectMapFlags) cuda2hipRename["cuGLUnmapBufferObject"] = {"hipGLUnmapBufferObject", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGLUnmapBufferObject) cuda2hipRename["cuGLUnmapBufferObjectAsync"] = {"hipGLUnmapBufferObjectAsync", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGLUnmapBufferObjectAsync) cuda2hipRename["cuGLUnregisterBufferObject"] = {"hipGLUnregisterBufferObject", CONV_GL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGLUnregisterBufferObject) // Direct3D 9 Interoperability // enum CUd3d9DeviceList/CUd3d9DeviceList_enum cuda2hipRename["CUd3d9DeviceList"] = {"hipD3D9DeviceList", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D9DeviceList) // cuda2hipRename["CUd3d9DeviceList_enum"] = {"hipD3D9DeviceList", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_D3D9_DEVICE_LIST_ALL"] = {"HIP_D3D9_DEVICE_LIST_ALL", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 // API_Runtime ANALOGUE (cudaD3D9DeviceListAll) cuda2hipRename["CU_D3D9_DEVICE_LIST_CURRENT_FRAME"] = {"HIP_D3D9_DEVICE_LIST_CURRENT_FRAME", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 // API_Runtime ANALOGUE (cudaD3D9DeviceListCurrentFrame) cuda2hipRename["CU_D3D9_DEVICE_LIST_NEXT_FRAME"] = {"HIP_D3D9_DEVICE_LIST_NEXT_FRAME", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // 0x03 // API_Runtime ANALOGUE (cudaD3D9DeviceListNextFrame) cuda2hipRename["cuD3D9CtxCreate"] = {"hipD3D9CtxCreate", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // no API_Runtime ANALOGUE cuda2hipRename["cuD3D9CtxCreateOnDevice"] = {"hipD3D9CtxCreateOnDevice", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // no API_Runtime ANALOGUE cuda2hipRename["cuD3D9GetDevice"] = {"hipD3D9GetDevice", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D9GetDevice) cuda2hipRename["cuD3D9GetDevices"] = {"hipD3D9GetDevices", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D9GetDevices) cuda2hipRename["cuD3D9GetDirect3DDevice"] = {"hipD3D9GetDirect3DDevice", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D9GetDirect3DDevice) cuda2hipRename["cuGraphicsD3D9RegisterResource"] = {"hipGraphicsD3D9RegisterResource", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsD3D9RegisterResource) // Direct3D 9 Interoperability [DEPRECATED] // enum CUd3d9map_flags/CUd3d9map_flags_enum cuda2hipRename["CUd3d9map_flags"] = {"hipD3D9MapFlags", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D9MapFlags) // cuda2hipRename["CUd3d9map_flags_enum"] = {"hipD3D9MapFlags", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_D3D9_MAPRESOURCE_FLAGS_NONE"] = {"HIP_D3D9_MAPRESOURCE_FLAGS_NONE", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // 0x00 // API_Runtime ANALOGUE (cudaD3D9MapFlagsNone) cuda2hipRename["CU_D3D9_MAPRESOURCE_FLAGS_READONLY"] = {"HIP_D3D9_MAPRESOURCE_FLAGS_READONLY", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 // API_Runtime ANALOGUE (cudaD3D9MapFlagsReadOnly) cuda2hipRename["CU_D3D9_MAPRESOURCE_FLAGS_WRITEDISCARD"] = {"HIP_D3D9_MAPRESOURCE_FLAGS_WRITEDISCARD", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 // API_Runtime ANALOGUE (cudaD3D9MapFlagsWriteDiscard) // enum CUd3d9register_flags/CUd3d9register_flags_enum cuda2hipRename["CUd3d9register_flags"] = {"hipD3D9RegisterFlags", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D9RegisterFlags) // cuda2hipRename["CUd3d9register_flags_enum"] = {"hipD3D9RegisterFlags", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_D3D9_REGISTER_FLAGS_NONE"] = {"HIP_D3D9_REGISTER_FLAGS_NONE", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // 0x00 // API_Runtime ANALOGUE (cudaD3D9RegisterFlagsNone) cuda2hipRename["CU_D3D9_REGISTER_FLAGS_ARRAY"] = {"HIP_D3D9_REGISTER_FLAGS_ARRAY", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 // API_Runtime ANALOGUE (cudaD3D9RegisterFlagsArray) cuda2hipRename["cuD3D9MapResources"] = {"hipD3D9MapResources", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D9MapResources) cuda2hipRename["cuD3D9RegisterResource"] = {"hipD3D9RegisterResource", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D9RegisterResource) cuda2hipRename["cuD3D9ResourceGetMappedArray"] = {"hipD3D9ResourceGetMappedArray", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D9ResourceGetMappedArray) cuda2hipRename["cuD3D9ResourceGetMappedPitch"] = {"hipD3D9ResourceGetMappedPitch", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D9ResourceGetMappedPitch) cuda2hipRename["cuD3D9ResourceGetMappedPointer"] = {"hipD3D9ResourceGetMappedPointer", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D9ResourceGetMappedPointer) cuda2hipRename["cuD3D9ResourceGetMappedSize"] = {"hipD3D9ResourceGetMappedSize", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D9ResourceGetMappedSize) cuda2hipRename["cuD3D9ResourceGetSurfaceDimensions"] = {"hipD3D9ResourceGetSurfaceDimensions", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D9ResourceGetSurfaceDimensions) cuda2hipRename["cuD3D9ResourceSetMapFlags"] = {"hipD3D9ResourceSetMapFlags", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D9ResourceSetMapFlags) cuda2hipRename["cuD3D9UnmapResources"] = {"hipD3D9UnmapResources", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D9UnmapResources) cuda2hipRename["cuD3D9UnregisterResource"] = {"hipD3D9UnregisterResource", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D9UnregisterResource) // Direct3D 10 Interoperability // enum CUd3d10DeviceList/CUd3d10DeviceList_enum cuda2hipRename["CUd3d10DeviceList"] = {"hipd3d10DeviceList", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D10DeviceList) // cuda2hipRename["CUd3d10DeviceList_enum"] = {"hipD3D10DeviceList", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_D3D10_DEVICE_LIST_ALL"] = {"HIP_D3D10_DEVICE_LIST_ALL", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 // API_Runtime ANALOGUE (cudaD3D10DeviceListAll) cuda2hipRename["CU_D3D10_DEVICE_LIST_CURRENT_FRAME"] = {"HIP_D3D10_DEVICE_LIST_CURRENT_FRAME", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 // API_Runtime ANALOGUE (cudaD3D10DeviceListCurrentFrame) cuda2hipRename["CU_D3D10_DEVICE_LIST_NEXT_FRAME"] = {"HIP_D3D10_DEVICE_LIST_NEXT_FRAME", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // 0x03 // API_Runtime ANALOGUE (cudaD3D10DeviceListNextFrame) cuda2hipRename["cuD3D10GetDevice"] = {"hipD3D10GetDevice", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D10GetDevice) cuda2hipRename["cuD3D10GetDevices"] = {"hipD3D10GetDevices", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D10GetDevices) cuda2hipRename["cuGraphicsD3D10RegisterResource"] = {"hipGraphicsD3D10RegisterResource", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsD3D10RegisterResource) // Direct3D 10 Interoperability [DEPRECATED] // enum CUd3d10map_flags/CUd3d10map_flags_enum cuda2hipRename["CUd3d10map_flags"] = {"hipD3D10MapFlags", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D10MapFlags) // cuda2hipRename["CUd3d10map_flags_enum"] = {"hipD3D10MapFlags", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_D3D10_MAPRESOURCE_FLAGS_NONE"] = {"HIP_D3D10_MAPRESOURCE_FLAGS_NONE", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // 0x00 // API_Runtime ANALOGUE (cudaD3D10MapFlagsNone) cuda2hipRename["CU_D3D10_MAPRESOURCE_FLAGS_READONLY"] = {"HIP_D3D10_MAPRESOURCE_FLAGS_READONLY", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 // API_Runtime ANALOGUE (cudaD3D10MapFlagsReadOnly) cuda2hipRename["CU_D3D10_MAPRESOURCE_FLAGS_WRITEDISCARD"] = {"HIP_D3D10_MAPRESOURCE_FLAGS_WRITEDISCARD", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 // API_Runtime ANALOGUE (cudaD3D10MapFlagsWriteDiscard) // enum CUd3d10register_flags/CUd3d10register_flags_enum cuda2hipRename["CUd3d10register_flags"] = {"hipD3D10RegisterFlags", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D10RegisterFlags) // cuda2hipRename["CUd3d10register_flags_enum"] = {"hipD3D10RegisterFlags", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_D3D10_REGISTER_FLAGS_NONE"] = {"HIP_D3D10_REGISTER_FLAGS_NONE", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // 0x00 // API_Runtime ANALOGUE (cudaD3D10RegisterFlagsNone) cuda2hipRename["CU_D3D10_REGISTER_FLAGS_ARRAY"] = {"HIP_D3D10_REGISTER_FLAGS_ARRAY", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 // API_Runtime ANALOGUE (cudaD3D10RegisterFlagsArray) cuda2hipRename["cuD3D10CtxCreate"] = {"hipD3D10CtxCreate", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // no API_Runtime ANALOGUE cuda2hipRename["cuD3D10CtxCreateOnDevice"] = {"hipD3D10CtxCreateOnDevice", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // no API_Runtime ANALOGUE cuda2hipRename["cuD3D10GetDirect3DDevice"] = {"hipD3D10GetDirect3DDevice", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D10GetDirect3DDevice) cuda2hipRename["cuD3D10MapResources"] = {"hipD3D10MapResources", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D10MapResources) cuda2hipRename["cuD3D10RegisterResource"] = {"hipD3D10RegisterResource", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D10RegisterResource) cuda2hipRename["cuD3D10ResourceGetMappedArray"] = {"hipD3D10ResourceGetMappedArray", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D10ResourceGetMappedArray) cuda2hipRename["cuD3D10ResourceGetMappedPitch"] = {"hipD3D10ResourceGetMappedPitch", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D10ResourceGetMappedPitch) cuda2hipRename["cuD3D10ResourceGetMappedPointer"] = {"hipD3D10ResourceGetMappedPointer", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D10ResourceGetMappedPointer) cuda2hipRename["cuD3D10ResourceGetMappedSize"] = {"hipD3D10ResourceGetMappedSize", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D10ResourceGetMappedSize) cuda2hipRename["cuD3D10ResourceGetSurfaceDimensions"] = {"hipD3D10ResourceGetSurfaceDimensions", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D10ResourceGetSurfaceDimensions) cuda2hipRename["cuD310ResourceSetMapFlags"] = {"hipD3D10ResourceSetMapFlags", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D10ResourceSetMapFlags) cuda2hipRename["cuD3D10UnmapResources"] = {"hipD3D10UnmapResources", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D10UnmapResources) cuda2hipRename["cuD3D10UnregisterResource"] = {"hipD3D10UnregisterResource", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D10UnregisterResource) // Direct3D 11 Interoperability // enum CUd3d11DeviceList/CUd3d11DeviceList_enum cuda2hipRename["CUd3d11DeviceList"] = {"hipd3d11DeviceList", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D11DeviceList) // cuda2hipRename["CUd3d11DeviceList_enum"] = {"hipD3D11DeviceList", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED}; cuda2hipRename["CU_D3D11_DEVICE_LIST_ALL"] = {"HIP_D3D11_DEVICE_LIST_ALL", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED}; // 0x01 // API_Runtime ANALOGUE (cudaD3D11DeviceListAll) cuda2hipRename["CU_D3D11_DEVICE_LIST_CURRENT_FRAME"] = {"HIP_D3D11_DEVICE_LIST_CURRENT_FRAME", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED}; // 0x02 // API_Runtime ANALOGUE (cudaD3D11DeviceListCurrentFrame) cuda2hipRename["CU_D3D11_DEVICE_LIST_NEXT_FRAME"] = {"HIP_D3D11_DEVICE_LIST_NEXT_FRAME", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED}; // 0x03 // API_Runtime ANALOGUE (cudaD3D11DeviceListNextFrame) cuda2hipRename["cuD3D11GetDevice"] = {"hipD3D11GetDevice", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D11GetDevice) cuda2hipRename["cuD3D11GetDevices"] = {"hipD3D11GetDevices", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D11GetDevices) cuda2hipRename["cuGraphicsD3D11RegisterResource"] = {"hipGraphicsD3D11RegisterResource", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsD3D11RegisterResource) // Direct3D 11 Interoperability [DEPRECATED] cuda2hipRename["cuD3D11CtxCreate"] = {"hipD3D11CtxCreate", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED}; // no API_Runtime ANALOGUE cuda2hipRename["cuD3D11CtxCreateOnDevice"] = {"hipD3D11CtxCreateOnDevice", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED}; // no API_Runtime ANALOGUE cuda2hipRename["cuD3D11GetDirect3DDevice"] = {"hipD3D11GetDirect3DDevice", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaD3D11GetDirect3DDevice) // VDPAU Interoperability cuda2hipRename["cuGraphicsVDPAURegisterOutputSurface"] = {"hipGraphicsVDPAURegisterOutputSurface", CONV_VDPAU, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsVDPAURegisterOutputSurface) cuda2hipRename["cuGraphicsVDPAURegisterVideoSurface"] = {"hipGraphicsVDPAURegisterVideoSurface", CONV_VDPAU, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsVDPAURegisterVideoSurface) cuda2hipRename["cuVDPAUGetDevice"] = {"hipVDPAUGetDevice", CONV_VDPAU, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaVDPAUGetDevice) cuda2hipRename["cuVDPAUCtxCreate"] = {"hipVDPAUCtxCreate", CONV_VDPAU, API_DRIVER, HIP_UNSUPPORTED}; // no API_Runtime ANALOGUE // EGL Interoperability cuda2hipRename["CUeglStreamConnection_st"] = {"hipEglStreamConnection", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaEglStreamConnection) cuda2hipRename["CUeglStreamConnection"] = {"hipEglStreamConnection", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaEglStreamConnection) cuda2hipRename["cuEGLStreamConsumerAcquireFrame"] = {"hipEGLStreamConsumerAcquireFrame", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaEGLStreamConsumerAcquireFrame) cuda2hipRename["cuEGLStreamConsumerConnect"] = {"hipEGLStreamConsumerConnect", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaEGLStreamConsumerConnect) cuda2hipRename["cuEGLStreamConsumerConnectWithFlags"] = {"hipEGLStreamConsumerConnectWithFlags", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaEGLStreamConsumerConnectWithFlags) cuda2hipRename["cuEGLStreamConsumerDisconnect"] = {"hipEGLStreamConsumerDisconnect", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED}; // no API_Runtime ANALOGUE cuda2hipRename["cuEGLStreamConsumerReleaseFrame"] = {"hipEGLStreamConsumerReleaseFrame", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaEGLStreamConsumerReleaseFrame) cuda2hipRename["cuEGLStreamProducerConnect"] = {"hipEGLStreamProducerConnect", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaEGLStreamProducerConnect) cuda2hipRename["cuEGLStreamProducerDisconnect"] = {"hipEGLStreamProducerDisconnect", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaEGLStreamProducerDisconnect) cuda2hipRename["cuEGLStreamProducerPresentFrame"] = {"hipEGLStreamProducerPresentFrame", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaEGLStreamProducerPresentFrame) cuda2hipRename["cuEGLStreamProducerReturnFrame"] = {"hipEGLStreamProducerReturnFrame", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaEGLStreamProducerReturnFrame) cuda2hipRename["cuGraphicsEGLRegisterImage"] = {"hipGraphicsEGLRegisterImage", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsEGLRegisterImage) cuda2hipRename["cuGraphicsResourceGetMappedEglFrame"] = {"hipGraphicsResourceGetMappedEglFrame", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED}; // API_Runtime ANALOGUE (cudaGraphicsResourceGetMappedEglFrame) /////////////////////////////// CUDA RT API /////////////////////////////// // Data types // unsupported yet by HIP [CUDA 8.0.44] cuda2hipRename["cudaDataType_t"] = {"hipDataType_t", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaDataType"] = {"hipDataType_t", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_R_16F"] = {"hipR16F", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_C_16F"] = {"hipC16F", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_R_32F"] = {"hipR32F", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_C_32F"] = {"hipC32F", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_R_64F"] = {"hipR64F", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_C_64F"] = {"hipC64F", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_R_8I"] = {"hipR8I", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_C_8I"] = {"hipC8I", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_R_8U"] = {"hipR8U", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_C_8U"] = {"hipC8U", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_R_32I"] = {"hipR32I", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_C_32I"] = {"hipC32I", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_R_32U"] = {"hipR32U", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["CUDA_C_32U"] = {"hipC32U", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // Library property types // IMPORTANT: no cuda prefix // TO_DO: new matcher is needed // unsupported yet by HIP [CUDA 8.0.44] cuda2hipRename["libraryPropertyType_t"] = {"hipLibraryPropertyType_t", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["libraryPropertyType"] = {"hipLibraryPropertyType_t", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["MAJOR_VERSION"] = {"hipLibraryMajorVersion", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["MINOR_VERSION"] = {"hipLibraryMinorVersion", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["PATCH_LEVEL"] = {"hipLibraryPatchVersion", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // defines cuda2hipRename["cudaMemAttachGlobal"] = {"hipMemAttachGlobal", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 0x01 // API_Driver ANALOGUE (CU_MEM_ATTACH_GLOBAL = 0x1) cuda2hipRename["cudaMemAttachHost"] = {"hipMemAttachHost", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 0x02 // API_Driver ANALOGUE (CU_MEM_ATTACH_HOST = 0x2) cuda2hipRename["cudaMemAttachSingle"] = {"hipMemAttachSingle", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 0x04 // API_Driver ANALOGUE (CU_MEM_ATTACH_SINGLE = 0x4) cuda2hipRename["cudaOccupancyDefault"] = {"hipOccupancyDefault", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 0x00 // API_Driver ANALOGUE (CU_OCCUPANCY_DEFAULT = 0x0) cuda2hipRename["cudaOccupancyDisableCachingOverride"] = {"hipOccupancyDisableCachingOverride", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 0x01 // API_Driver ANALOGUE (CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE = 0x1) cuda2hipRename["cudaStreamCallback_t"] = {"hipStreamCallback_t", CONV_TYPE, API_RUNTIME}; // Error API cuda2hipRename["cudaGetLastError"] = {"hipGetLastError", CONV_ERROR, API_RUNTIME}; cuda2hipRename["cudaPeekAtLastError"] = {"hipPeekAtLastError", CONV_ERROR, API_RUNTIME}; cuda2hipRename["cudaGetErrorName"] = {"hipGetErrorName", CONV_ERROR, API_RUNTIME}; cuda2hipRename["cudaGetErrorString"] = {"hipGetErrorString", CONV_ERROR, API_RUNTIME}; // Arrays cuda2hipRename["cudaArray"] = {"hipArray", CONV_MEM, API_RUNTIME}; // typedef struct cudaArray *cudaArray_t; cuda2hipRename["cudaArray_t"] = {"hipArray_t", CONV_MEM, API_RUNTIME}; // typedef const struct cudaArray *cudaArray_const_t; cuda2hipRename["cudaArray_const_t"] = {"hipArray_const_t", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMipmappedArray_t"] = {"hipMipmappedArray_t", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMipmappedArray_const_t"] = {"hipMipmappedArray_const_t", CONV_MEM, API_RUNTIME}; // memcpy // memcpy structs cuda2hipRename["cudaMemcpy3DParms"] = {"hipMemcpy3DParms", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemcpy3DPeerParms"] = {"hipMemcpy3DPeerParms", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; // memcpy functions cuda2hipRename["cudaMemcpy"] = {"hipMemcpy", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemcpyToArray"] = {"hipMemcpyToArray", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemcpyToSymbol"] = {"hipMemcpyToSymbol", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemcpyToSymbolAsync"] = {"hipMemcpyToSymbolAsync", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemcpyAsync"] = {"hipMemcpyAsync", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemcpy2D"] = {"hipMemcpy2D", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemcpy2DAsync"] = {"hipMemcpy2DAsync", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemcpy2DToArray"] = {"hipMemcpy2DToArray", CONV_MEM, API_RUNTIME}; // unsupported yet by HIP cuda2hipRename["cudaMemcpy2DArrayToArray"] = {"hipMemcpy2DArrayToArray", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaMemcpy2DFromArray"] = {"hipMemcpy2DFromArray", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaMemcpy2DFromArrayAsync"] = {"hipMemcpy2DFromArrayAsync", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaMemcpy2DToArrayAsync"] = {"hipMemcpy2DToArrayAsync", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaMemcpy3D"] = {"hipMemcpy3D", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemcpy3DAsync"] = {"hipMemcpy3DAsync", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaMemcpy3DPeer"] = {"hipMemcpy3DPeer", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaMemcpy3DPeerAsync"] = {"hipMemcpy3DPeerAsync", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaMemcpyArrayToArray"] = {"hipMemcpyArrayToArray", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaMemcpyFromArrayAsync"] = {"hipMemcpyFromArrayAsync", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaMemcpyFromSymbol"] = {"hipMemcpyFromSymbol", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemcpyFromSymbolAsync"] = {"hipMemcpyFromSymbolAsync", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemAdvise"] = {"hipMemAdvise", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; // [CUDA 8.0.44] cuda2hipRename["cudaMemRangeGetAttribute"] = {"hipMemRangeGetAttribute", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; // [CUDA 8.0.44] cuda2hipRename["cudaMemRangeGetAttributes"] = {"hipMemRangeGetAttributes", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; // [CUDA 8.0.44] // unsupported yet by HIP [CUDA 8.0.44] // Memory advise values cuda2hipRename["cudaMemoryAdvise"] = {"hipMemAdvise", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (CUmem_advise) cuda2hipRename["cudaMemAdviseSetReadMostly"] = {"hipMemAdviseSetReadMostly", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 1 // API_Driver ANALOGUE (CU_MEM_ADVISE_SET_READ_MOSTLY = 1) cuda2hipRename["cudaMemAdviseUnsetReadMostly"] = {"hipMemAdviseUnsetReadMostly", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 2 // API_Driver ANALOGUE (CU_MEM_ADVISE_UNSET_READ_MOSTLY = 2) cuda2hipRename["cudaMemAdviseSetPreferredLocation"] = {"hipMemAdviseSetPreferredLocation", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 3 // API_Driver ANALOGUE (CU_MEM_ADVISE_SET_PREFERRED_LOCATION = 3) cuda2hipRename["cudaMemAdviseUnsetPreferredLocation"] = {"hipMemAdviseUnsetPreferredLocation", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 4 // API_Driver ANALOGUE (CU_MEM_ADVISE_UNSET_PREFERRED_LOCATION = 4) cuda2hipRename["cudaMemAdviseSetAccessedBy"] = {"hipMemAdviseSetAccessedBy", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 5 // API_Driver ANALOGUE (CU_MEM_ADVISE_SET_ACCESSED_BY = 5) cuda2hipRename["cudaMemAdviseUnsetAccessedBy"] = {"hipMemAdviseUnsetAccessedBy", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 6 // API_Driver ANALOGUE (CU_MEM_ADVISE_UNSET_ACCESSED_BY = 6) // CUmem_range_attribute cuda2hipRename["cudaMemRangeAttribute"] = {"hipMemRangeAttribute", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (CUmem_range_attribute) cuda2hipRename["cudaMemRangeAttributeReadMostly"] = {"hipMemRangeAttributeReadMostly", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 1 // API_Driver ANALOGUE (CU_MEM_RANGE_ATTRIBUTE_READ_MOSTLY = 1) cuda2hipRename["cudaMemRangeAttributePreferredLocation"] = {"hipMemRangeAttributePreferredLocation", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 2 // API_Driver ANALOGUE (CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION = 2) cuda2hipRename["cudaMemRangeAttributeAccessedBy"] = {"hipMemRangeAttributeAccessedBy", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 3 // API_Driver ANALOGUE (CU_MEM_RANGE_ATTRIBUTE_ACCESSED_BY = 3) cuda2hipRename["cudaMemRangeAttributeLastPrefetchLocation"] = {"hipMemRangeAttributeLastPrefetchLocation", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 4 // API_Driver ANALOGUE (CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION = 4) // memcpy kind cuda2hipRename["cudaMemcpyKind"] = {"hipMemcpyKind", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemcpyHostToHost"] = {"hipMemcpyHostToHost", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemcpyHostToDevice"] = {"hipMemcpyHostToDevice", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemcpyDeviceToHost"] = {"hipMemcpyDeviceToHost", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemcpyDeviceToDevice"] = {"hipMemcpyDeviceToDevice", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemcpyDefault"] = {"hipMemcpyDefault", CONV_MEM, API_RUNTIME}; // memset cuda2hipRename["cudaMemset"] = {"hipMemset", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemsetAsync"] = {"hipMemsetAsync", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemset2D"] = {"hipMemset2D", CONV_MEM, API_RUNTIME}; // unsupported yet by HIP cuda2hipRename["cudaMemset2DAsync"] = {"hipMemset2DAsync", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaMemset3D"] = {"hipMemset3D", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaMemset3DAsync"] = {"hipMemset3DAsync", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; // Memory management cuda2hipRename["cudaMemGetInfo"] = {"hipMemGetInfo", CONV_MEM, API_RUNTIME}; // unsupported yet by HIP cuda2hipRename["cudaArrayGetInfo"] = {"hipArrayGetInfo", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaFreeMipmappedArray"] = {"hipFreeMipmappedArray", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaGetMipmappedArrayLevel"] = {"hipGetMipmappedArrayLevel", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaGetSymbolAddress"] = {"hipGetSymbolAddress", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaGetSymbolSize"] = {"hipGetSymbolSize", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaMemPrefetchAsync"] = {"hipMemPrefetchAsync", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; // [CUDA 8.0.44] // API_Driver ANALOGUE (cuMemPrefetchAsync) // malloc cuda2hipRename["cudaMalloc"] = {"hipMalloc", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMallocHost"] = {"hipHostMalloc", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMallocArray"] = {"hipMallocArray", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMalloc3D"] = {"hipMalloc3D", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaMalloc3DArray"] = {"hipMalloc3DArray", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMallocManaged"] = {"hipMallocManaged", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaMallocMipmappedArray"] = {"hipMallocMipmappedArray", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaMallocPitch"] = {"hipMallocPitch", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaFree"] = {"hipFree", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaFreeHost"] = {"hipHostFree", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaFreeArray"] = {"hipFreeArray", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaHostRegister"] = {"hipHostRegister", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaHostUnregister"] = {"hipHostUnregister", CONV_MEM, API_RUNTIME}; // hipHostAlloc deprecated - use hipHostMalloc instead cuda2hipRename["cudaHostAlloc"] = {"hipHostMalloc", CONV_MEM, API_RUNTIME}; // Memory types cuda2hipRename["cudaMemoryType"] = {"hipMemoryType", CONV_MEM, API_RUNTIME}; // API_Driver ANALOGUE (no - CUmemorytype is not an analogue) cuda2hipRename["cudaMemoryTypeHost"] = {"hipMemoryTypeHost", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemoryTypeDevice"] = {"hipMemoryTypeDevice", CONV_MEM, API_RUNTIME}; // make memory functions cuda2hipRename["make_cudaExtent"] = {"make_hipExtent", CONV_MEM, API_RUNTIME}; cuda2hipRename["make_cudaPitchedPtr"] = {"make_hipPitchedPtr", CONV_MEM, API_RUNTIME}; cuda2hipRename["make_cudaPos"] = {"make_hipPos", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaExtent"] = {"hipExtent", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaPitchedPtr"] = {"hipPitchedPtr", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaPos"] = {"hipPos", CONV_MEM, API_RUNTIME}; // Host Malloc Flags cuda2hipRename["cudaHostAllocDefault"] = {"hipHostMallocDefault", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaHostAllocPortable"] = {"hipHostMallocPortable", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaHostAllocMapped"] = {"hipHostMallocMapped", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaHostAllocWriteCombined"] = {"hipHostMallocWriteCombined", CONV_MEM, API_RUNTIME}; // Host Register Flags cuda2hipRename["cudaHostGetFlags"] = {"hipHostGetFlags", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaHostRegisterDefault"] = {"hipHostRegisterDefault", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaHostRegisterPortable"] = {"hipHostRegisterPortable", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaHostRegisterMapped"] = {"hipHostRegisterMapped", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaHostRegisterIoMemory"] = {"hipHostRegisterIoMemory", CONV_MEM, API_RUNTIME}; // Coordinate Indexing and Dimensions cuda2hipRename["threadIdx.x"] = {"hipThreadIdx_x", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["threadIdx.y"] = {"hipThreadIdx_y", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["threadIdx.z"] = {"hipThreadIdx_z", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["blockIdx.x"] = {"hipBlockIdx_x", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["blockIdx.y"] = {"hipBlockIdx_y", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["blockIdx.z"] = {"hipBlockIdx_z", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["blockDim.x"] = {"hipBlockDim_x", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["blockDim.y"] = {"hipBlockDim_y", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["blockDim.z"] = {"hipBlockDim_z", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["gridDim.x"] = {"hipGridDim_x", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["gridDim.y"] = {"hipGridDim_y", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["gridDim.z"] = {"hipGridDim_z", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["blockIdx.x"] = {"hipBlockIdx_x", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["blockIdx.y"] = {"hipBlockIdx_y", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["blockIdx.z"] = {"hipBlockIdx_z", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["blockDim.x"] = {"hipBlockDim_x", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["blockDim.y"] = {"hipBlockDim_y", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["blockDim.z"] = {"hipBlockDim_z", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["gridDim.x"] = {"hipGridDim_x", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["gridDim.y"] = {"hipGridDim_y", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["gridDim.z"] = {"hipGridDim_z", CONV_COORD_FUNC, API_RUNTIME}; cuda2hipRename["warpSize"] = {"hipWarpSize", CONV_SPECIAL_FUNC, API_RUNTIME}; // Events cuda2hipRename["cudaEvent_t"] = {"hipEvent_t", CONV_TYPE, API_RUNTIME}; cuda2hipRename["cudaEventCreate"] = {"hipEventCreate", CONV_EVENT, API_RUNTIME}; cuda2hipRename["cudaEventCreateWithFlags"] = {"hipEventCreateWithFlags", CONV_EVENT, API_RUNTIME}; cuda2hipRename["cudaEventDestroy"] = {"hipEventDestroy", CONV_EVENT, API_RUNTIME}; cuda2hipRename["cudaEventRecord"] = {"hipEventRecord", CONV_EVENT, API_RUNTIME}; cuda2hipRename["cudaEventElapsedTime"] = {"hipEventElapsedTime", CONV_EVENT, API_RUNTIME}; cuda2hipRename["cudaEventSynchronize"] = {"hipEventSynchronize", CONV_EVENT, API_RUNTIME}; cuda2hipRename["cudaEventQuery"] = {"hipEventQuery", CONV_EVENT, API_RUNTIME}; // Event Flags cuda2hipRename["cudaEventDefault"] = {"hipEventDefault", CONV_EVENT, API_RUNTIME}; cuda2hipRename["cudaEventBlockingSync"] = {"hipEventBlockingSync", CONV_EVENT, API_RUNTIME}; cuda2hipRename["cudaEventDisableTiming"] = {"hipEventDisableTiming", CONV_EVENT, API_RUNTIME}; cuda2hipRename["cudaEventInterprocess"] = {"hipEventInterprocess", CONV_EVENT, API_RUNTIME}; // Streams cuda2hipRename["cudaStream_t"] = {"hipStream_t", CONV_TYPE, API_RUNTIME}; cuda2hipRename["cudaStreamCreate"] = {"hipStreamCreate", CONV_STREAM, API_RUNTIME}; cuda2hipRename["cudaStreamCreateWithFlags"] = {"hipStreamCreateWithFlags", CONV_STREAM, API_RUNTIME}; cuda2hipRename["cudaStreamCreateWithPriority"] = {"hipStreamCreateWithPriority", CONV_STREAM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaStreamDestroy"] = {"hipStreamDestroy", CONV_STREAM, API_RUNTIME}; cuda2hipRename["cudaStreamWaitEvent"] = {"hipStreamWaitEvent", CONV_STREAM, API_RUNTIME}; cuda2hipRename["cudaStreamSynchronize"] = {"hipStreamSynchronize", CONV_STREAM, API_RUNTIME}; cuda2hipRename["cudaStreamGetFlags"] = {"hipStreamGetFlags", CONV_STREAM, API_RUNTIME}; cuda2hipRename["cudaStreamQuery"] = {"hipStreamQuery", CONV_STREAM, API_RUNTIME}; cuda2hipRename["cudaStreamAddCallback"] = {"hipStreamAddCallback", CONV_STREAM, API_RUNTIME}; cuda2hipRename["cudaStreamAttachMemAsync"] = {"hipStreamAttachMemAsync", CONV_STREAM, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaStreamGetPriority"] = {"hipStreamGetPriority", CONV_STREAM, API_RUNTIME, HIP_UNSUPPORTED}; // Stream Flags cuda2hipRename["cudaStreamDefault"] = {"hipStreamDefault", CONV_TYPE, API_RUNTIME}; cuda2hipRename["cudaStreamNonBlocking"] = {"hipStreamNonBlocking", CONV_TYPE, API_RUNTIME}; // Other synchronization cuda2hipRename["cudaDeviceSynchronize"] = {"hipDeviceSynchronize", CONV_DEVICE, API_RUNTIME}; cuda2hipRename["cudaDeviceReset"] = {"hipDeviceReset", CONV_DEVICE, API_RUNTIME}; cuda2hipRename["cudaSetDevice"] = {"hipSetDevice", CONV_DEVICE, API_RUNTIME}; cuda2hipRename["cudaGetDevice"] = {"hipGetDevice", CONV_DEVICE, API_RUNTIME}; cuda2hipRename["cudaGetDeviceCount"] = {"hipGetDeviceCount", CONV_DEVICE, API_RUNTIME}; cuda2hipRename["cudaChooseDevice"] = {"hipChooseDevice", CONV_DEVICE, API_RUNTIME}; // Thread Management cuda2hipRename["cudaThreadExit"] = {"hipDeviceReset", CONV_THREAD, API_RUNTIME}; cuda2hipRename["cudaThreadGetCacheConfig"] = {"hipDeviceGetCacheConfig", CONV_THREAD, API_RUNTIME}; cuda2hipRename["cudaThreadGetLimit"] = {"hipThreadGetLimit", CONV_THREAD, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaThreadSetCacheConfig"] = {"hipDeviceSetCacheConfig", CONV_THREAD, API_RUNTIME}; cuda2hipRename["cudaThreadSetLimit"] = {"hipThreadSetLimit", CONV_THREAD, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaThreadSynchronize"] = {"hipDeviceSynchronize", CONV_THREAD, API_RUNTIME}; // Attributes cuda2hipRename["cudaDeviceGetAttribute"] = {"hipDeviceGetAttribute", CONV_DEVICE, API_RUNTIME}; cuda2hipRename["cudaDeviceAttr"] = {"hipDeviceAttribute_t", CONV_TYPE, API_RUNTIME}; // API_DRIVER ANALOGUE (CUdevice_attribute) cuda2hipRename["cudaDevAttrMaxThreadsPerBlock"] = {"hipDeviceAttributeMaxThreadsPerBlock", CONV_TYPE, API_RUNTIME}; // 1 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK = 1) cuda2hipRename["cudaDevAttrMaxBlockDimX"] = {"hipDeviceAttributeMaxBlockDimX", CONV_TYPE, API_RUNTIME}; // 2 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X = 2) cuda2hipRename["cudaDevAttrMaxBlockDimY"] = {"hipDeviceAttributeMaxBlockDimY", CONV_TYPE, API_RUNTIME}; // 3 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y = 3) cuda2hipRename["cudaDevAttrMaxBlockDimZ"] = {"hipDeviceAttributeMaxBlockDimZ", CONV_TYPE, API_RUNTIME}; // 4 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z = 4) cuda2hipRename["cudaDevAttrMaxGridDimX"] = {"hipDeviceAttributeMaxGridDimX", CONV_TYPE, API_RUNTIME}; // 5 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X = 5) cuda2hipRename["cudaDevAttrMaxGridDimY"] = {"hipDeviceAttributeMaxGridDimY", CONV_TYPE, API_RUNTIME}; // 6 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X = 6) cuda2hipRename["cudaDevAttrMaxGridDimZ"] = {"hipDeviceAttributeMaxGridDimZ", CONV_TYPE, API_RUNTIME}; // 7 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X = 7) cuda2hipRename["cudaDevAttrMaxSharedMemoryPerBlock"] = {"hipDeviceAttributeMaxSharedMemoryPerBlock", CONV_TYPE, API_RUNTIME}; // 8 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK = 8) cuda2hipRename["cudaDevAttrTotalConstantMemory"] = {"hipDeviceAttributeTotalConstantMemory", CONV_TYPE, API_RUNTIME}; // 9 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY =9) cuda2hipRename["cudaDevAttrWarpSize"] = {"hipDeviceAttributeWarpSize", CONV_TYPE, API_RUNTIME}; // 10 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_WARP_SIZE = 10) cuda2hipRename["cudaDevAttrMaxPitch"] = {"hipDeviceAttributeMaxPitch", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 11 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAX_PITCH = 11) cuda2hipRename["cudaDevAttrMaxRegistersPerBlock"] = {"hipDeviceAttributeMaxRegistersPerBlock", CONV_TYPE, API_RUNTIME}; // 12 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK = 12) cuda2hipRename["cudaDevAttrClockRate"] = {"hipDeviceAttributeClockRate", CONV_TYPE, API_RUNTIME}; // 13 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_CLOCK_RATE = 13) cuda2hipRename["cudaDevAttrTextureAlignment"] = {"hipDeviceAttributeTextureAlignment", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 14 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT = 14) // Is not deprecated as CUDA Driver's API analogue CU_DEVICE_ATTRIBUTE_GPU_OVERLAP cuda2hipRename["cudaDevAttrGpuOverlap"] = {"hipDeviceAttributeGpuOverlap", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 15 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_GPU_OVERLAP = 15) cuda2hipRename["cudaDevAttrMultiProcessorCount"] = {"hipDeviceAttributeMultiprocessorCount", CONV_TYPE, API_RUNTIME}; // 16 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT = 16) cuda2hipRename["cudaDevAttrKernelExecTimeout"] = {"hipDeviceAttributeKernelExecTimeout", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 17 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT = 17) cuda2hipRename["cudaDevAttrIntegrated"] = {"hipDeviceAttributeIntegrated", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 18 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_INTEGRATED = 18) cuda2hipRename["cudaDevAttrCanMapHostMemory"] = {"hipDeviceAttributeCanMapHostMemory", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 19 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY = 19) cuda2hipRename["cudaDevAttrComputeMode"] = {"hipDeviceAttributeComputeMode", CONV_TYPE, API_RUNTIME}; // 20 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_COMPUTE_MODE = 20) cuda2hipRename["cudaDevAttrMaxTexture1DWidth"] = {"hipDeviceAttributeMaxTexture1DWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 21 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_WIDTH = 21) cuda2hipRename["cudaDevAttrMaxTexture2DWidth"] = {"hipDeviceAttributeMaxTexture2DWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 22 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_WIDTH = 22) cuda2hipRename["cudaDevAttrMaxTexture2DHeight"] = {"hipDeviceAttributeMaxTexture2DHeight", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 23 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_HEIGHT = 23) cuda2hipRename["cudaDevAttrMaxTexture3DWidth"] = {"hipDeviceAttributeMaxTexture3DWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 24 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH = 24) cuda2hipRename["cudaDevAttrMaxTexture3DHeight"] = {"hipDeviceAttributeMaxTexture3DHeight", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 25 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT = 25) cuda2hipRename["cudaDevAttrMaxTexture3DDepth"] = {"hipDeviceAttributeMaxTexture3DDepth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 26 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH = 26) cuda2hipRename["cudaDevAttrMaxTexture2DLayeredWidth"] = {"hipDeviceAttributeMaxTexture2DLayeredWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 27 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_WIDTH = 27) cuda2hipRename["cudaDevAttrMaxTexture2DLayeredHeight"] = {"hipDeviceAttributeMaxTexture2DLayeredHeight", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 28 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_HEIGHT = 28) cuda2hipRename["cudaDevAttrMaxTexture2DLayeredLayers"] = {"hipDeviceAttributeMaxTexture2DLayeredLayers", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 29 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_LAYERS = 29) cuda2hipRename["cudaDevAttrSurfaceAlignment"] = {"hipDeviceAttributeSurfaceAlignment", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 30 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_SURFACE_ALIGNMENT = 30) cuda2hipRename["cudaDevAttrConcurrentKernels"] = {"hipDeviceAttributeConcurrentKernels", CONV_TYPE, API_RUNTIME}; // 31 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS = 31) cuda2hipRename["cudaDevAttrEccEnabled"] = {"hipDeviceAttributeEccEnabled", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 32 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_ECC_ENABLED = 32) cuda2hipRename["cudaDevAttrPciBusId"] = {"hipDeviceAttributePciBusId", CONV_TYPE, API_RUNTIME}; // 33 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_PCI_BUS_ID = 33) cuda2hipRename["cudaDevAttrPciDeviceId"] = {"hipDeviceAttributePciDeviceId", CONV_TYPE, API_RUNTIME}; // 34 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_PCI_DEVICE_ID = 34) cuda2hipRename["cudaDevAttrTccDriver"] = {"hipDeviceAttributeTccDriver", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 35 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_TCC_DRIVER = 35) cuda2hipRename["cudaDevAttrMemoryClockRate"] = {"hipDeviceAttributeMemoryClockRate", CONV_TYPE, API_RUNTIME}; // 36 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE = 36) cuda2hipRename["cudaDevAttrGlobalMemoryBusWidth"] = {"hipDeviceAttributeMemoryBusWidth", CONV_TYPE, API_RUNTIME}; // 37 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH = 37) cuda2hipRename["cudaDevAttrL2CacheSize"] = {"hipDeviceAttributeL2CacheSize", CONV_TYPE, API_RUNTIME}; // 38 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE = 38) cuda2hipRename["cudaDevAttrMaxThreadsPerMultiProcessor"] = {"hipDeviceAttributeMaxThreadsPerMultiProcessor", CONV_TYPE, API_RUNTIME}; // 39 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR = 39) cuda2hipRename["cudaDevAttrAsyncEngineCount"] = {"hipDeviceAttributeAsyncEngineCount", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 40 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT = 40) cuda2hipRename["cudaDevAttrUnifiedAddressing"] = {"hipDeviceAttributeUnifiedAddressing", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 41 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING = 41) cuda2hipRename["cudaDevAttrMaxTexture1DLayeredWidth"] = {"hipDeviceAttributeMaxTexture1DLayeredWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 42 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_WIDTH = 42) cuda2hipRename["cudaDevAttrMaxTexture1DLayeredLayers"] = {"hipDeviceAttributeMaxTexture1DLayeredLayers", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 43 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_LAYERS = 43) // 44 - no cuda2hipRename["cudaDevAttrMaxTexture2DGatherWidth"] = {"hipDeviceAttributeMaxTexture2DGatherWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 45 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_WIDTH = 45) cuda2hipRename["cudaDevAttrMaxTexture2DGatherHeight"] = {"hipDeviceAttributeMaxTexture2DGatherHeight", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 46 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_HEIGHT = 46) cuda2hipRename["cudaDevAttrMaxTexture3DWidthAlt"] = {"hipDeviceAttributeMaxTexture3DWidthAlternate", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 47 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH_ALTERNATE = 47) cuda2hipRename["cudaDevAttrMaxTexture3DHeightAlt"] = {"hipDeviceAttributeMaxTexture3DHeightAlternate", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 48 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT_ALTERNATE = 48) cuda2hipRename["cudaDevAttrMaxTexture3DDepthAlt"] = {"hipDeviceAttributeMaxTexture3DDepthAlternate", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 49 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH_ALTERNATE = 49) cuda2hipRename["cudaDevAttrPciDomainId"] = {"hipDeviceAttributePciDomainId", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 50 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_PCI_DOMAIN_ID = 50) cuda2hipRename["cudaDevAttrTexturePitchAlignment"] = {"hipDeviceAttributeTexturePitchAlignment", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 51 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT = 51) cuda2hipRename["cudaDevAttrMaxTextureCubemapWidth"] = {"hipDeviceAttributeMaxTextureCubemapWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 52 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_WIDTH = 52) cuda2hipRename["cudaDevAttrMaxTextureCubemapLayeredWidth"] = {"hipDeviceAttributeMaxTextureCubemapLayeredWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 53 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_WIDTH = 53) cuda2hipRename["cudaDevAttrMaxTextureCubemapLayeredLayers"] = {"hipDeviceAttributeMaxTextureCubemapLayeredLayers", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 54 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_LAYERS = 54) cuda2hipRename["cudaDevAttrMaxSurface1DWidth"] = {"hipDeviceAttributeMaxSurface1DWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 55 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_WIDTH = 55) cuda2hipRename["cudaDevAttrMaxSurface2DWidth"] = {"hipDeviceAttributeMaxSurface2DWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 56 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_WIDTH = 56) cuda2hipRename["cudaDevAttrMaxSurface2DHeight"] = {"hipDeviceAttributeMaxSurface2DHeight", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 57 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_HEIGHT = 57) cuda2hipRename["cudaDevAttrMaxSurface3DWidth"] = {"hipDeviceAttributeMaxSurface3DWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 58 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_WIDTH = 58) cuda2hipRename["cudaDevAttrMaxSurface3DHeight"] = {"hipDeviceAttributeMaxSurface3DHeight", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 59 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_HEIGHT = 59) cuda2hipRename["cudaDevAttrMaxSurface3DDepth"] = {"hipDeviceAttributeMaxSurface3DDepth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 60 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_DEPTH = 60) cuda2hipRename["cudaDevAttrMaxSurface1DLayeredWidth"] = {"hipDeviceAttributeMaxSurface1DLayeredWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 61 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_WIDTH = 61) cuda2hipRename["cudaDevAttrMaxSurface1DLayeredLayers"] = {"hipDeviceAttributeMaxSurface1DLayeredLayers", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 62 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_LAYERS = 62) cuda2hipRename["cudaDevAttrMaxSurface2DLayeredWidth"] = {"hipDeviceAttributeMaxSurface2DLayeredWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 63 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_WIDTH = 63) cuda2hipRename["cudaDevAttrMaxSurface2DLayeredHeight"] = {"hipDeviceAttributeMaxSurface2DLayeredHeight", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 64 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_HEIGHT = 64) cuda2hipRename["cudaDevAttrMaxSurface2DLayeredLayers"] = {"hipDeviceAttributeMaxSurface2DLayeredLayers", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 65 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_LAYERS = 65) cuda2hipRename["cudaDevAttrMaxSurfaceCubemapWidth"] = {"hipDeviceAttributeMaxSurfaceCubemapWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 66 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_WIDTH = 66) cuda2hipRename["cudaDevAttrMaxSurfaceCubemapLayeredWidth"] = {"hipDeviceAttributeMaxSurfaceCubemapLayeredWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 67 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_WIDTH = 67) cuda2hipRename["cudaDevAttrMaxSurfaceCubemapLayeredLayers"] = {"hipDeviceAttributeMaxSurfaceCubemapLayeredLayers", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 68 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_LAYERS = 68) cuda2hipRename["cudaDevAttrMaxTexture1DLinearWidth"] = {"hipDeviceAttributeMaxTexture1DLinearWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 69 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LINEAR_WIDTH = 69) cuda2hipRename["cudaDevAttrMaxTexture2DLinearWidth"] = {"hipDeviceAttributeMaxTexture2DLinearWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 70 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_WIDTH = 70) cuda2hipRename["cudaDevAttrMaxTexture2DLinearHeight"] = {"hipDeviceAttributeMaxTexture2DLinearHeight", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 71 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_HEIGHT = 71) cuda2hipRename["cudaDevAttrMaxTexture2DLinearPitch"] = {"hipDeviceAttributeMaxTexture2DLinearPitch", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 72 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_PITCH = 72) cuda2hipRename["cudaDevAttrMaxTexture2DMipmappedWidth"] = {"hipDeviceAttributeMaxTexture2DMipmappedWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 73 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_WIDTH = 73) cuda2hipRename["cudaDevAttrMaxTexture2DMipmappedHeight"] = {"hipDeviceAttributeMaxTexture2DMipmappedHeight", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 74 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_HEIGHT = 74) cuda2hipRename["cudaDevAttrComputeCapabilityMajor"] = {"hipDeviceAttributeComputeCapabilityMajor", CONV_TYPE, API_RUNTIME}; // 75 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR = 75) cuda2hipRename["cudaDevAttrComputeCapabilityMinor"] = {"hipDeviceAttributeComputeCapabilityMinor", CONV_TYPE, API_RUNTIME}; // 76 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR = 76) cuda2hipRename["cudaDevAttrMaxTexture1DMipmappedWidth"] = {"hipDeviceAttributeMaxTexture1DMipmappedWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 77 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_MIPMAPPED_WIDTH = 77) cuda2hipRename["cudaDevAttrStreamPrioritiesSupported"] = {"hipDeviceAttributeStreamPrioritiesSupported", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 78 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_STREAM_PRIORITIES_SUPPORTED = 78) cuda2hipRename["cudaDevAttrGlobalL1CacheSupported"] = {"hipDeviceAttributeGlobalL1CacheSupported", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 79 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_GLOBAL_L1_CACHE_SUPPORTED = 79) cuda2hipRename["cudaDevAttrLocalL1CacheSupported"] = {"hipDeviceAttributeLocalL1CacheSupported", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 80 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_LOCAL_L1_CACHE_SUPPORTED = 80) cuda2hipRename["cudaDevAttrMaxSharedMemoryPerMultiprocessor"] = {"hipDeviceAttributeMaxSharedMemoryPerMultiprocessor", CONV_TYPE, API_RUNTIME}; // 81 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR = 81) cuda2hipRename["cudaDevAttrMaxRegistersPerMultiprocessor"] = {"hipDeviceAttributeMaxRegistersPerMultiprocessor", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 82 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_MULTIPROCESSOR = 82) cuda2hipRename["cudaDevAttrManagedMemory"] = {"hipDeviceAttributeManagedMemory", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 83 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY = 83) cuda2hipRename["cudaDevAttrIsMultiGpuBoard"] = {"hipDeviceAttributeIsMultiGpuBoard", CONV_TYPE, API_RUNTIME}; // 84 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD = 84) cuda2hipRename["cudaDevAttrMultiGpuBoardGroupID"] = {"hipDeviceAttributeMultiGpuBoardGroupID", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 85 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD_GROUP_ID = 85) // unsupported yet by HIP [CUDA 8.0.44] cuda2hipRename["cudaDevAttrHostNativeAtomicSupported"] = {"hipDeviceAttributeHostNativeAtomicSupported", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 86 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_HOST_NATIVE_ATOMIC_SUPPORTED = 86) cuda2hipRename["cudaDevAttrSingleToDoublePrecisionPerfRatio"] = {"hipDeviceAttributeSingleToDoublePrecisionPerfRatio", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 87 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_SINGLE_TO_DOUBLE_PRECISION_PERF_RATIO = 87) cuda2hipRename["cudaDevAttrPageableMemoryAccess"] = {"hipDeviceAttributePageableMemoryAccess", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 88 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS = 88) cuda2hipRename["cudaDevAttrConcurrentManagedAccess"] = {"hipDeviceAttributeConcurrentManagedAccess", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 89 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS = 89) cuda2hipRename["cudaDevAttrComputePreemptionSupported"] = {"hipDeviceAttributeComputePreemptionSupported", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 90 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED = 90) cuda2hipRename["cudaDevAttrCanUseHostPointerForRegisteredMem"] = {"hipDeviceAttributeCanUseHostPointerForRegisteredMem", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 91 // API_DRIVER ANALOGUE (CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM = 91) // Pointer Attributes // struct cudaPointerAttributes cuda2hipRename["cudaPointerAttributes"] = {"hipPointerAttribute_t", CONV_TYPE, API_RUNTIME}; cuda2hipRename["cudaPointerGetAttributes"] = {"hipPointerGetAttributes", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaHostGetDevicePointer"] = {"hipHostGetDevicePointer", CONV_MEM, API_RUNTIME}; // Device cuda2hipRename["cudaDeviceProp"] = {"hipDeviceProp_t", CONV_TYPE, API_RUNTIME}; cuda2hipRename["cudaGetDeviceProperties"] = {"hipGetDeviceProperties", CONV_DEVICE, API_RUNTIME}; cuda2hipRename["cudaDeviceGetPCIBusId"] = {"hipDeviceGetPCIBusId", CONV_DEVICE, API_RUNTIME}; cuda2hipRename["cudaDeviceGetByPCIBusId"] = {"hipDeviceGetByPCIBusId", CONV_DEVICE, API_RUNTIME}; // unsupported yet by HIP cuda2hipRename["cudaDeviceGetStreamPriorityRange"] = {"hipDeviceGetStreamPriorityRange", CONV_DEVICE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaSetValidDevices"] = {"hipSetValidDevices", CONV_DEVICE, API_RUNTIME, HIP_UNSUPPORTED}; // unsupported yet by HIP [CUDA 8.0.44] // P2P Attributes cuda2hipRename["cudaDeviceP2PAttr"] = {"hipDeviceP2PAttribute", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // API_DRIVER ANALOGUE (CUdevice_P2PAttribute) cuda2hipRename["cudaDevP2PAttrPerformanceRank"] = {"hipDeviceP2PAttributePerformanceRank", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 0x01 // API_DRIVER ANALOGUE (CU_DEVICE_P2P_ATTRIBUTE_PERFORMANCE_RANK = 0x01) cuda2hipRename["cudaDevP2PAttrAccessSupported"] = {"hipDeviceP2PAttributeAccessSupported", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 0x02 // API_DRIVER ANALOGUE (CU_DEVICE_P2P_ATTRIBUTE_ACCESS_SUPPORTED = 0x02) cuda2hipRename["cudaDevP2PAttrNativeAtomicSupported"] = {"hipDeviceP2PAttributeNativeAtomicSupported", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 0x03 // API_DRIVER ANALOGUE (CU_DEVICE_P2P_ATTRIBUTE_NATIVE_ATOMIC_SUPPORTED = 0x03) // [CUDA 8.0.44] cuda2hipRename["cudaDeviceGetP2PAttribute"] = {"hipDeviceGetP2PAttribute", CONV_DEVICE, API_RUNTIME, HIP_UNSUPPORTED}; // API_DRIVER ANALOGUE (cuDeviceGetP2PAttribute) // Compute mode cuda2hipRename["cudaComputeMode"] = {"hipComputeMode", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // API_DRIVER ANALOGUE (CUcomputemode) cuda2hipRename["cudaComputeModeDefault"] = {"hipComputeModeDefault", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 0 // API_DRIVER ANALOGUE (CU_COMPUTEMODE_DEFAULT = 0) cuda2hipRename["cudaComputeModeExclusive"] = {"hipComputeModeExclusive", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 1 // API_DRIVER ANALOGUE (CU_COMPUTEMODE_EXCLUSIVE = 1) cuda2hipRename["cudaComputeModeProhibited"] = {"hipComputeModeProhibited", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 2 // API_DRIVER ANALOGUE (CU_COMPUTEMODE_PROHIBITED = 2) cuda2hipRename["cudaComputeModeExclusiveProcess"] = {"hipComputeModeExclusiveProcess", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 3 // API_DRIVER ANALOGUE (CU_COMPUTEMODE_EXCLUSIVE_PROCESS = 3) // Device Flags cuda2hipRename["cudaGetDeviceFlags"] = {"hipGetDeviceFlags", CONV_DEVICE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaSetDeviceFlags"] = {"hipSetDeviceFlags", CONV_DEVICE, API_RUNTIME}; cuda2hipRename["cudaDeviceScheduleAuto"] = {"hipDeviceScheduleAuto", CONV_TYPE, API_RUNTIME}; cuda2hipRename["cudaDeviceScheduleSpin"] = {"hipDeviceScheduleSpin", CONV_TYPE, API_RUNTIME}; cuda2hipRename["cudaDeviceScheduleYield"] = {"hipDeviceScheduleYield", CONV_TYPE, API_RUNTIME}; // deprecated as of CUDA 4.0 and replaced with cudaDeviceScheduleBlockingSync cuda2hipRename["cudaDeviceBlockingSync"] = {"hipDeviceScheduleBlockingSync", CONV_TYPE, API_RUNTIME}; // unsupported yet by HIP cuda2hipRename["cudaDeviceScheduleBlockingSync"] = {"hipDeviceScheduleBlockingSync", CONV_TYPE, API_RUNTIME}; cuda2hipRename["cudaDeviceScheduleMask"] = {"hipDeviceScheduleMask", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaDeviceMapHost"] = {"hipDeviceMapHost", CONV_TYPE, API_RUNTIME}; cuda2hipRename["cudaDeviceLmemResizeToMax"] = {"hipDeviceLmemResizeToMax", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaDeviceMask"] = {"hipDeviceMask", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // Cache config cuda2hipRename["cudaDeviceSetCacheConfig"] = {"hipDeviceSetCacheConfig", CONV_CACHE, API_RUNTIME}; cuda2hipRename["cudaDeviceGetCacheConfig"] = {"hipDeviceGetCacheConfig", CONV_CACHE, API_RUNTIME}; cuda2hipRename["cudaFuncSetCacheConfig"] = {"hipFuncSetCacheConfig", CONV_CACHE, API_RUNTIME}; // Execution control // CUDA function cache configurations cuda2hipRename["cudaFuncCache"] = {"hipFuncCache_t", CONV_CACHE, API_RUNTIME}; // API_Driver ANALOGUE (CUfunc_cache) cuda2hipRename["cudaFuncCachePreferNone"] = {"hipFuncCachePreferNone", CONV_CACHE, API_RUNTIME}; // 0 // API_Driver ANALOGUE (CU_FUNC_CACHE_PREFER_NONE = 0x00) cuda2hipRename["cudaFuncCachePreferShared"] = {"hipFuncCachePreferShared", CONV_CACHE, API_RUNTIME}; // 1 // API_Driver ANALOGUE (CU_FUNC_CACHE_PREFER_SHARED = 0x01) cuda2hipRename["cudaFuncCachePreferL1"] = {"hipFuncCachePreferL1", CONV_CACHE, API_RUNTIME}; // 2 // API_Driver ANALOGUE (CU_FUNC_CACHE_PREFER_L1 = 0x02) cuda2hipRename["cudaFuncCachePreferEqual"] = {"hipFuncCachePreferEqual", CONV_CACHE, API_RUNTIME}; // 3 // API_Driver ANALOGUE (CU_FUNC_CACHE_PREFER_EQUAL = 0x03) // Execution control functions // unsupported yet by HIP cuda2hipRename["cudaFuncAttributes"] = {"hipFuncAttributes", CONV_EXEC, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaFuncGetAttributes"] = {"hipFuncGetAttributes", CONV_EXEC, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaFuncSetSharedMemConfig"] = {"hipFuncSetSharedMemConfig", CONV_EXEC, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaGetParameterBuffer"] = {"hipGetParameterBuffer", CONV_EXEC, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaSetDoubleForDevice"] = {"hipSetDoubleForDevice", CONV_EXEC, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaSetDoubleForHost"] = {"hipSetDoubleForHost", CONV_EXEC, API_RUNTIME, HIP_UNSUPPORTED}; // Execution Control [deprecated since 7.0] // unsupported yet by HIP cuda2hipRename["cudaConfigureCall"] = {"hipConfigureCall", CONV_EXEC, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaLaunch"] = {"hipLaunch", CONV_EXEC, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaSetupArgument"] = {"hipSetupArgument", CONV_EXEC, API_RUNTIME, HIP_UNSUPPORTED}; // Version Management cuda2hipRename["cudaDriverGetVersion"] = {"hipDriverGetVersion", CONV_VERSION, API_RUNTIME}; cuda2hipRename["cudaRuntimeGetVersion"] = {"hipRuntimeGetVersion", CONV_VERSION, API_RUNTIME, HIP_UNSUPPORTED}; // Occupancy cuda2hipRename["cudaOccupancyMaxPotentialBlockSize"] = {"hipOccupancyMaxPotentialBlockSize", CONV_OCCUPANCY, API_RUNTIME}; // unsupported yet by HIP cuda2hipRename["cudaOccupancyMaxPotentialBlockSizeWithFlags"] = {"hipOccupancyMaxPotentialBlockSizeWithFlags", CONV_OCCUPANCY, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaOccupancyMaxActiveBlocksPerMultiprocessor"] = {"hipOccupancyMaxActiveBlocksPerMultiprocessor", CONV_OCCUPANCY, API_RUNTIME}; // unsupported yet by HIP cuda2hipRename["cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags"] = {"hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags", CONV_OCCUPANCY, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaOccupancyMaxPotentialBlockSizeVariableSMem"] = {"hipOccupancyMaxPotentialBlockSizeVariableSMem", CONV_OCCUPANCY, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaOccupancyMaxPotentialBlockSizeVariableSMemWithFlags"] = {"hipOccupancyMaxPotentialBlockSizeVariableSMemWithFlags", CONV_OCCUPANCY, API_RUNTIME, HIP_UNSUPPORTED}; // Peer2Peer cuda2hipRename["cudaDeviceCanAccessPeer"] = {"hipDeviceCanAccessPeer", CONV_PEER, API_RUNTIME}; cuda2hipRename["cudaDeviceDisablePeerAccess"] = {"hipDeviceDisablePeerAccess", CONV_PEER, API_RUNTIME}; cuda2hipRename["cudaDeviceEnablePeerAccess"] = {"hipDeviceEnablePeerAccess", CONV_PEER, API_RUNTIME}; cuda2hipRename["cudaMemcpyPeerAsync"] = {"hipMemcpyPeerAsync", CONV_MEM, API_RUNTIME}; cuda2hipRename["cudaMemcpyPeer"] = {"hipMemcpyPeer", CONV_MEM, API_RUNTIME}; // #define cudaIpcMemLazyEnablePeerAccess 0x01 cuda2hipRename["cudaIpcMemLazyEnablePeerAccess"] = {"hipIpcMemLazyEnablePeerAccess", CONV_TYPE, API_RUNTIME}; // 0x01 // API_Driver ANALOGUE (CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS = 0x1) // Shared memory cuda2hipRename["cudaDeviceSetSharedMemConfig"] = {"hipDeviceSetSharedMemConfig", CONV_DEVICE, API_RUNTIME}; cuda2hipRename["cudaDeviceGetSharedMemConfig"] = {"hipDeviceGetSharedMemConfig", CONV_DEVICE, API_RUNTIME}; // translate deprecated // cuda2hipRename["cudaThreadGetSharedMemConfig"] = {"hipDeviceGetSharedMemConfig", CONV_DEVICE, API_RUNTIME}; // cuda2hipRename["cudaThreadSetSharedMemConfig"] = {"hipDeviceSetSharedMemConfig", CONV_DEVICE, API_RUNTIME}; cuda2hipRename["cudaSharedMemConfig"] = {"hipSharedMemConfig", CONV_TYPE, API_RUNTIME}; cuda2hipRename["cudaSharedMemBankSizeDefault"] = {"hipSharedMemBankSizeDefault", CONV_TYPE, API_RUNTIME}; cuda2hipRename["cudaSharedMemBankSizeFourByte"] = {"hipSharedMemBankSizeFourByte", CONV_TYPE, API_RUNTIME}; cuda2hipRename["cudaSharedMemBankSizeEightByte"] = {"hipSharedMemBankSizeEightByte", CONV_TYPE, API_RUNTIME}; // Limits cuda2hipRename["cudaLimit"] = {"hipLimit_t", CONV_TYPE, API_RUNTIME}; // API_Driver ANALOGUE (CUlimit) cuda2hipRename["cudaLimitStackSize"] = {"hipLimitStackSize", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 0x00 // API_Driver ANALOGUE (CU_LIMIT_STACK_SIZE = 0x00) cuda2hipRename["cudaLimitPrintfFifoSize"] = {"hipLimitPrintfFifoSize", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 0x01 // API_Driver ANALOGUE (CU_LIMIT_PRINTF_FIFO_SIZE = 0x01) cuda2hipRename["cudaLimitMallocHeapSize"] = {"hipLimitMallocHeapSize", CONV_TYPE, API_RUNTIME}; // 0x02 // API_Driver ANALOGUE (CU_LIMIT_MALLOC_HEAP_SIZE = 0x02) cuda2hipRename["cudaLimitDevRuntimeSyncDepth"] = {"hipLimitDevRuntimeSyncDepth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 0x03 // API_Driver ANALOGUE (CU_LIMIT_DEV_RUNTIME_SYNC_DEPTH = 0x03) cuda2hipRename["cudaLimitDevRuntimePendingLaunchCount"] = {"hipLimitDevRuntimePendingLaunchCount", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED}; // 0x04 // API_Driver ANALOGUE (CU_LIMIT_DEV_RUNTIME_PENDING_LAUNCH_COUNT = 0x04) cuda2hipRename["cudaDeviceGetLimit"] = {"hipDeviceGetLimit", CONV_DEVICE, API_RUNTIME}; // Profiler cuda2hipRename["cudaProfilerInitialize"] = {"hipProfilerInitialize", CONV_OTHER, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuProfilerInitialize) cuda2hipRename["cudaProfilerStart"] = {"hipProfilerStart", CONV_OTHER, API_RUNTIME}; // API_Driver ANALOGUE (cuProfilerStart) cuda2hipRename["cudaProfilerStop"] = {"hipProfilerStop", CONV_OTHER, API_RUNTIME}; // API_Driver ANALOGUE (cuProfilerStop) // unsupported yet by HIP cuda2hipRename["cudaOutputMode"] = {"hipOutputMode", CONV_OTHER, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaKeyValuePair"] = {"hipKeyValuePair", CONV_OTHER, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaCSV"] = {"hipCSV", CONV_OTHER, API_RUNTIME, HIP_UNSUPPORTED}; // Texture Reference Management // enums cuda2hipRename["cudaTextureReadMode"] = {"hipTextureReadMode", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaReadModeElementType"] = {"hipReadModeElementType", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaReadModeNormalizedFloat"] = {"hipReadModeNormalizedFloat", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaTextureFilterMode"] = {"hipTextureFilterMode", CONV_TEX, API_RUNTIME}; // API_DRIVER ANALOGUE (CUfilter_mode) cuda2hipRename["cudaFilterModePoint"] = {"hipFilterModePoint", CONV_TEX, API_RUNTIME}; // 0 // API_DRIVER ANALOGUE (CU_TR_FILTER_MODE_POINT = 0) cuda2hipRename["cudaFilterModeLinear"] = {"hipFilterModeLinear", CONV_TEX, API_RUNTIME}; // 1 // API_DRIVER ANALOGUE (CU_TR_FILTER_MODE_POINT = 1) cuda2hipRename["cudaBindTexture"] = {"hipBindTexture", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaUnbindTexture"] = {"hipUnbindTexture", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaBindTexture2D"] = {"hipBindTexture2D", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaBindTextureToArray"] = {"hipBindTextureToArray", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaBindTextureToMipmappedArray"] = {"hipBindTextureToMipmappedArray", CONV_TEX, API_RUNTIME}; // Unsupported yet on NVCC path cuda2hipRename["cudaGetTextureAlignmentOffset"] = {"hipGetTextureAlignmentOffset", CONV_TEX, API_RUNTIME}; // Unsupported yet on NVCC path cuda2hipRename["cudaGetTextureReference"] = {"hipGetTextureReference", CONV_TEX, API_RUNTIME}; // Unsupported yet on NVCC path // Channel cuda2hipRename["cudaChannelFormatKind"] = {"hipChannelFormatKind", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaChannelFormatKindSigned"] = {"hipChannelFormatKindSigned", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaChannelFormatKindUnsigned"] = {"hipChannelFormatKindUnsigned", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaChannelFormatKindFloat"] = {"hipChannelFormatKindFloat", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaChannelFormatKindNone"] = {"hipChannelFormatKindNone", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaChannelFormatDesc"] = {"hipChannelFormatDesc", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaCreateChannelDesc"] = {"hipCreateChannelDesc", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaGetChannelDesc"] = {"hipGetChannelDesc", CONV_TEX, API_RUNTIME}; // Texture Object Management // structs cuda2hipRename["cudaResourceDesc"] = {"hipResourceDesc", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaResourceViewDesc"] = {"hipResourceViewDesc", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaTextureDesc"] = {"hipTextureDesc", CONV_TEX, API_RUNTIME}; cuda2hipRename["surfaceReference"] = {"hipSurfaceReference", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED}; // Left unchanged // cuda2hipRename["textureReference"] = {"textureReference", CONV_TEX, API_RUNTIME}; // typedefs cuda2hipRename["cudaTextureObject_t"] = {"hipTextureObject_t", CONV_TEX, API_RUNTIME}; // enums // enum cudaResourceType cuda2hipRename["cudaResourceType"] = {"hipResourceType", CONV_TEX, API_RUNTIME}; // API_Driver ANALOGUE (CUresourcetype) cuda2hipRename["cudaResourceTypeArray"] = {"hipResourceTypeArray", CONV_TEX, API_RUNTIME}; // 0x00 // API_Driver ANALOGUE (CU_RESOURCE_TYPE_ARRAY = 0x00) cuda2hipRename["cudaResourceTypeMipmappedArray"] = {"hipResourceTypeMipmappedArray", CONV_TEX, API_RUNTIME}; // 0x01 // API_Driver ANALOGUE (CU_RESOURCE_TYPE_MIPMAPPED_ARRAY = 0x01) cuda2hipRename["cudaResourceTypeLinear"] = {"hipResourceTypeLinear", CONV_TEX, API_RUNTIME}; // 0x02 // API_Driver ANALOGUE (CU_RESOURCE_TYPE_LINEAR = 0x02) cuda2hipRename["cudaResourceTypePitch2D"] = {"hipResourceTypePitch2D", CONV_TEX, API_RUNTIME}; // 0x03 // API_Driver ANALOGUE (CU_RESOURCE_TYPE_PITCH2D = 0x03) // enum cudaResourceViewFormat cuda2hipRename["cudaResourceViewFormat"] = {"hipResourceViewFormat", CONV_TEX, API_RUNTIME}; // API_Driver ANALOGUE (CUresourceViewFormat) cuda2hipRename["cudaResViewFormatNone"] = {"hipResViewFormatNone", CONV_TEX, API_RUNTIME}; // 0x00 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_NONE = 0x00) cuda2hipRename["cudaResViewFormatUnsignedChar1"] = {"hipResViewFormatUnsignedChar1", CONV_TEX, API_RUNTIME}; // 0x01 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_UINT_1X8 = 0x01) cuda2hipRename["cudaResViewFormatUnsignedChar2"] = {"hipResViewFormatUnsignedChar2", CONV_TEX, API_RUNTIME}; // 0x02 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_UINT_2X8 = 0x02) cuda2hipRename["cudaResViewFormatUnsignedChar4"] = {"hipResViewFormatUnsignedChar4", CONV_TEX, API_RUNTIME}; // 0x03 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_UINT_4X8 = 0x03) cuda2hipRename["cudaResViewFormatSignedChar1"] = {"hipResViewFormatSignedChar1", CONV_TEX, API_RUNTIME}; // 0x04 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_SINT_1X8 = 0x04) cuda2hipRename["cudaResViewFormatSignedChar2"] = {"hipResViewFormatSignedChar2", CONV_TEX, API_RUNTIME}; // 0x05 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_SINT_2X8 = 0x05) cuda2hipRename["cudaResViewFormatSignedChar4"] = {"hipResViewFormatSignedChar4", CONV_TEX, API_RUNTIME}; // 0x06 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_SINT_4X8 = 0x06) cuda2hipRename["cudaResViewFormatUnsignedShort1"] = {"hipResViewFormatUnsignedShort1", CONV_TEX, API_RUNTIME}; // 0x07 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_UINT_1X16 = 0x07) cuda2hipRename["cudaResViewFormatUnsignedShort2"] = {"hipResViewFormatUnsignedShort2", CONV_TEX, API_RUNTIME}; // 0x08 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_UINT_2X16 = 0x08) cuda2hipRename["cudaResViewFormatUnsignedShort4"] = {"hipResViewFormatUnsignedShort4", CONV_TEX, API_RUNTIME}; // 0x09 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_UINT_4X16 = 0x09) cuda2hipRename["cudaResViewFormatSignedShort1"] = {"hipResViewFormatSignedShort1", CONV_TEX, API_RUNTIME}; // 0x0a // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_SINT_1X16 = 0x0a) cuda2hipRename["cudaResViewFormatSignedShort2"] = {"hipResViewFormatSignedShort2", CONV_TEX, API_RUNTIME}; // 0x0b // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_SINT_2X16 = 0x0b) cuda2hipRename["cudaResViewFormatSignedShort4"] = {"hipResViewFormatSignedShort4", CONV_TEX, API_RUNTIME}; // 0x0c // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_SINT_4X16 = 0x0c) cuda2hipRename["cudaResViewFormatUnsignedInt1"] = {"hipResViewFormatUnsignedInt1", CONV_TEX, API_RUNTIME}; // 0x0d // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_UINT_1X32 = 0x0d) cuda2hipRename["cudaResViewFormatUnsignedInt2"] = {"hipResViewFormatUnsignedInt2", CONV_TEX, API_RUNTIME}; // 0x0e // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_UINT_2X32 = 0x0e) cuda2hipRename["cudaResViewFormatUnsignedInt4"] = {"hipResViewFormatUnsignedInt4", CONV_TEX, API_RUNTIME}; // 0x0f // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_UINT_4X32 = 0x0f) cuda2hipRename["cudaResViewFormatSignedInt1"] = {"hipResViewFormatSignedInt1", CONV_TEX, API_RUNTIME}; // 0x10 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_SINT_1X32 = 0x10) cuda2hipRename["cudaResViewFormatSignedInt2"] = {"hipResViewFormatSignedInt2", CONV_TEX, API_RUNTIME}; // 0x11 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_SINT_2X32 = 0x11) cuda2hipRename["cudaResViewFormatSignedInt4"] = {"hipResViewFormatSignedInt4", CONV_TEX, API_RUNTIME}; // 0x12 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_SINT_4X32 = 0x12) cuda2hipRename["cudaResViewFormatHalf1"] = {"hipResViewFormatHalf1", CONV_TEX, API_RUNTIME}; // 0x13 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_FLOAT_1X16 = 0x13) cuda2hipRename["cudaResViewFormatHalf2"] = {"hipResViewFormatHalf2", CONV_TEX, API_RUNTIME}; // 0x14 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_FLOAT_2X16 = 0x14) cuda2hipRename["cudaResViewFormatHalf4"] = {"hipResViewFormatHalf4", CONV_TEX, API_RUNTIME}; // 0x15 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_FLOAT_4X16 = 0x15) cuda2hipRename["cudaResViewFormatFloat1"] = {"hipResViewFormatFloat1", CONV_TEX, API_RUNTIME}; // 0x16 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_FLOAT_1X32 = 0x16) cuda2hipRename["cudaResViewFormatFloat2"] = {"hipResViewFormatFloat2", CONV_TEX, API_RUNTIME}; // 0x17 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_FLOAT_2X32 = 0x17) cuda2hipRename["cudaResViewFormatFloat4"] = {"hipResViewFormatFloat4", CONV_TEX, API_RUNTIME}; // 0x18 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_FLOAT_4X32 = 0x18) cuda2hipRename["cudaResViewFormatUnsignedBlockCompressed1"] = {"hipResViewFormatUnsignedBlockCompressed1", CONV_TEX, API_RUNTIME}; // 0x19 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_UNSIGNED_BC1 = 0x19) cuda2hipRename["cudaResViewFormatUnsignedBlockCompressed2"] = {"hipResViewFormatUnsignedBlockCompressed2", CONV_TEX, API_RUNTIME}; // 0x1a // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_UNSIGNED_BC2 = 0x1a) cuda2hipRename["cudaResViewFormatUnsignedBlockCompressed3"] = {"hipResViewFormatUnsignedBlockCompressed3", CONV_TEX, API_RUNTIME}; // 0x1b // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_UNSIGNED_BC3 = 0x1b) cuda2hipRename["cudaResViewFormatUnsignedBlockCompressed4"] = {"hipResViewFormatUnsignedBlockCompressed4", CONV_TEX, API_RUNTIME}; // 0x1c // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_UNSIGNED_BC4 = 0x1c) cuda2hipRename["cudaResViewFormatSignedBlockCompressed4"] = {"hipResViewFormatSignedBlockCompressed4", CONV_TEX, API_RUNTIME}; // 0x1d // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_SIGNED_BC4 = 0x1d) cuda2hipRename["cudaResViewFormatUnsignedBlockCompressed5"] = {"hipResViewFormatUnsignedBlockCompressed5", CONV_TEX, API_RUNTIME}; // 0x1e // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_UNSIGNED_BC5 = 0x1e) cuda2hipRename["cudaResViewFormatSignedBlockCompressed5"] = {"hipResViewFormatSignedBlockCompressed5", CONV_TEX, API_RUNTIME}; // 0x1f // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_SIGNED_BC5 = 0x1f) cuda2hipRename["cudaResViewFormatUnsignedBlockCompressed6H"] = {"hipResViewFormatUnsignedBlockCompressed6H", CONV_TEX, API_RUNTIME}; // 0x20 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_UNSIGNED_BC6H = 0x20) cuda2hipRename["cudaResViewFormatSignedBlockCompressed6H"] = {"hipResViewFormatSignedBlockCompressed6H", CONV_TEX, API_RUNTIME}; // 0x21 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_SIGNED_BC6H = 0x21) cuda2hipRename["cudaResViewFormatUnsignedBlockCompressed7"] = {"hipResViewFormatUnsignedBlockCompressed7", CONV_TEX, API_RUNTIME}; // 0x22 // API_Driver ANALOGUE (CU_RES_VIEW_FORMAT_UNSIGNED_BC7 = 0x22) cuda2hipRename["cudaTextureAddressMode"] = {"hipTextureAddressMode", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaAddressModeWrap"] = {"hipAddressModeWrap", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaAddressModeClamp"] = {"hipAddressModeClamp", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaAddressModeMirror"] = {"hipAddressModeMirror", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaAddressModeBorder"] = {"hipAddressModeBorder", CONV_TEX, API_RUNTIME}; // functions cuda2hipRename["cudaCreateTextureObject"] = {"hipCreateTextureObject", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaDestroyTextureObject"] = {"hipDestroyTextureObject", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaGetTextureObjectResourceDesc"] = {"hipGetTextureObjectResourceDesc", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaGetTextureObjectResourceViewDesc"] = {"hipGetTextureObjectResourceViewDesc", CONV_TEX, API_RUNTIME}; cuda2hipRename["cudaGetTextureObjectTextureDesc"] = {"hipGetTextureObjectTextureDesc", CONV_TEX, API_RUNTIME}; // Surface Reference Management // unsupported yet by HIP cuda2hipRename["cudaBindSurfaceToArray"] = {"hipBindSurfaceToArray", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaGetSurfaceReference"] = {"hipGetSurfaceReference", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaSurfaceBoundaryMode"] = {"hipSurfaceBoundaryMode", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaBoundaryModeZero"] = {"hipBoundaryModeZero", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaBoundaryModeClamp"] = {"hipBoundaryModeClamp", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaBoundaryModeTrap"] = {"hipBoundaryModeTrap", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaSurfaceFormatMode"] = {"hipSurfaceFormatMode", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaFormatModeForced"] = {"hipFormatModeForced", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaFormatModeAuto"] = {"hipFormatModeAuto", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED}; // Surface Object Management // unsupported yet by HIP cuda2hipRename["cudaCreateSurfaceObject"] = {"hipCreateSurfaceObject", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaDestroySurfaceObject"] = {"hipDestroySurfaceObject", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaGetSurfaceObjectResourceDesc"] = {"hipGetSurfaceObjectResourceDesc", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED}; // Inter-Process Communications (IPC) // IPC types cuda2hipRename["cudaIpcEventHandle_t"] = {"hipIpcEventHandle_t", CONV_TYPE, API_RUNTIME}; cuda2hipRename["cudaIpcEventHandle_st"] = {"hipIpcEventHandle_t", CONV_TYPE, API_RUNTIME}; cuda2hipRename["cudaIpcMemHandle_t"] = {"hipIpcMemHandle_t", CONV_TYPE, API_RUNTIME}; cuda2hipRename["cudaIpcMemHandle_st"] = {"hipIpcMemHandle_t", CONV_TYPE, API_RUNTIME}; // IPC functions cuda2hipRename["cudaIpcCloseMemHandle"] = {"hipIpcCloseMemHandle", CONV_DEVICE, API_RUNTIME}; cuda2hipRename["cudaIpcGetEventHandle"] = {"hipIpcGetEventHandle", CONV_DEVICE, API_RUNTIME}; cuda2hipRename["cudaIpcGetMemHandle"] = {"hipIpcGetMemHandle", CONV_DEVICE, API_RUNTIME}; cuda2hipRename["cudaIpcOpenEventHandle"] = {"hipIpcOpenEventHandle", CONV_DEVICE, API_RUNTIME}; cuda2hipRename["cudaIpcOpenMemHandle"] = {"hipIpcOpenMemHandle", CONV_DEVICE, API_RUNTIME}; // OpenGL Interoperability cuda2hipRename["cudaGLGetDevices"] = {"hipGLGetDevices", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaGraphicsGLRegisterBuffer"] = {"hipGraphicsGLRegisterBuffer", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaGraphicsGLRegisterImage"] = {"hipGraphicsGLRegisterImage", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaWGLGetDevice"] = {"hipWGLGetDevice", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // Graphics Interoperability cuda2hipRename["cudaGraphicsMapResources"] = {"hipGraphicsMapResources", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGraphicsMapResources) cuda2hipRename["cudaGraphicsResourceGetMappedMipmappedArray"] = {"hipGraphicsResourceGetMappedMipmappedArray", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGraphicsResourceGetMappedMipmappedArray) cuda2hipRename["cudaGraphicsResourceGetMappedPointer"] = {"hipGraphicsResourceGetMappedPointer", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGraphicsResourceGetMappedPointer) cuda2hipRename["cudaGraphicsResourceSetMapFlags"] = {"hipGraphicsResourceSetMapFlags", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGraphicsResourceSetMapFlags) cuda2hipRename["cudaGraphicsSubResourceGetMappedArray"] = {"hipGraphicsSubResourceGetMappedArray", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGraphicsSubResourceGetMappedArray) cuda2hipRename["cudaGraphicsUnmapResources"] = {"hipGraphicsUnmapResources", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGraphicsUnmapResources) cuda2hipRename["cudaGraphicsUnregisterResource"] = {"hipGraphicsUnregisterResource", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGraphicsUnregisterResource) cuda2hipRename["cudaGraphicsCubeFace"] = {"hipGraphicsCubeFace", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaGraphicsCubeFacePositiveX"] = {"hipGraphicsCubeFacePositiveX", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaGraphicsCubeFaceNegativeX"] = {"hipGraphicsCubeFaceNegativeX", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaGraphicsCubeFacePositiveY"] = {"hipGraphicsCubeFacePositiveY", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaGraphicsCubeFaceNegativeY"] = {"hipGraphicsCubeFaceNegativeY", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaGraphicsCubeFacePositiveZ"] = {"hipGraphicsCubeFacePositiveZ", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; cuda2hipRename["cudaGraphicsCubeFaceNegativeZ"] = {"hipGraphicsCubeFaceNegativeZ", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; // enum cudaGraphicsMapFlags cuda2hipRename["cudaGraphicsMapFlags"] = {"hipGraphicsMapFlags", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (CUgraphicsMapResourceFlags) cuda2hipRename["cudaGraphicsMapFlagsNone"] = {"hipGraphicsMapFlagsNone", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; // 0 // API_Driver ANALOGUE (CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE = 0x00) cuda2hipRename["cudaGraphicsMapFlagsReadOnly"] = {"hipGraphicsMapFlagsReadOnly", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; // 1 // API_Driver ANALOGUE (CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY = 0x01) cuda2hipRename["cudaGraphicsMapFlagsWriteDiscard"] = {"hipGraphicsMapFlagsWriteDiscard", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; // 2 // API_Driver ANALOGUE (CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD = 0x02) // enum cudaGraphicsRegisterFlags cuda2hipRename["cudaGraphicsRegisterFlags"] = {"hipGraphicsRegisterFlags", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (CUgraphicsRegisterFlags) cuda2hipRename["cudaGraphicsRegisterFlagsNone"] = {"hipGraphicsRegisterFlagsNone", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; // 0 // API_Driver ANALOGUE (CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE = 0x00) cuda2hipRename["cudaGraphicsRegisterFlagsReadOnly"] = {"hipGraphicsRegisterFlagsReadOnly", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; // 1 // API_Driver ANALOGUE (CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY = 0x01) cuda2hipRename["cudaGraphicsRegisterFlagsWriteDiscard"] = {"hipGraphicsRegisterFlagsWriteDiscard", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; // 2 // API_Driver ANALOGUE (CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD = 0x02) cuda2hipRename["cudaGraphicsRegisterFlagsSurfaceLoadStore"] = {"hipGraphicsRegisterFlagsSurfaceLoadStore", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; // 4 // API_Driver ANALOGUE (CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST = 0x04) cuda2hipRename["cudaGraphicsRegisterFlagsTextureGather"] = {"hipGraphicsRegisterFlagsTextureGather", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED}; // 8 // API_Driver ANALOGUE (CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER = 0x08) // OpenGL Interoperability // enum cudaGLDeviceList cuda2hipRename["cudaGLDeviceList"] = {"hipGLDeviceList", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (CUGLDeviceList) cuda2hipRename["cudaGLDeviceListAll"] = {"HIP_GL_DEVICE_LIST_ALL", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // 0x01 // API_Driver ANALOGUE (CU_GL_DEVICE_LIST_ALL) cuda2hipRename["cudaGLDeviceListCurrentFrame"] = {"HIP_GL_DEVICE_LIST_CURRENT_FRAME", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // 0x02 // API_Driver ANALOGUE (CU_GL_DEVICE_LIST_CURRENT_FRAME) cuda2hipRename["cudaGLDeviceListNextFrame"] = {"HIP_GL_DEVICE_LIST_NEXT_FRAME", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // 0x03 // API_Driver ANALOGUE (CU_GL_DEVICE_LIST_NEXT_FRAME) cuda2hipRename["cudaGLGetDevices"] = {"hipGLGetDevices", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGLGetDevices) cuda2hipRename["cudaGraphicsGLRegisterBuffer"] = {"hipGraphicsGLRegisterBuffer", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGraphicsGLRegisterBuffer) cuda2hipRename["cudaGraphicsGLRegisterImage"] = {"hipGraphicsGLRegisterImage", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGraphicsGLRegisterImage) cuda2hipRename["cudaWGLGetDevice"] = {"hipWGLGetDevice", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuWGLGetDevice) // OpenGL Interoperability [DEPRECATED] // enum cudaGLMapFlags cuda2hipRename["cudaGLMapFlags"] = {"hipGLMapFlags", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (CUGLmap_flags) cuda2hipRename["cudaGLMapFlagsNone"] = {"HIP_GL_MAP_RESOURCE_FLAGS_NONE", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // 0x00 // API_Driver ANALOGUE (CU_GL_MAP_RESOURCE_FLAGS_NONE) cuda2hipRename["cudaGLMapFlagsReadOnly"] = {"HIP_GL_MAP_RESOURCE_FLAGS_READ_ONLY", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // 0x01 // API_Driver ANALOGUE (CU_GL_MAP_RESOURCE_FLAGS_READ_ONLY) cuda2hipRename["cudaGLMapFlagsWriteDiscard"] = {"HIP_GL_MAP_RESOURCE_FLAGS_WRITE_DISCARD", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // 0x02 // API_Driver ANALOGUE (CU_GL_MAP_RESOURCE_FLAGS_WRITE_DISCARD) cuda2hipRename["cudaGLMapBufferObject"] = {"hipGLMapBufferObject__", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // Not equal to cuGLMapBufferObject due to different signatures cuda2hipRename["cudaGLMapBufferObjectAsync"] = {"hipGLMapBufferObjectAsync__", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // Not equal to cuGLMapBufferObjectAsync due to different signatures cuda2hipRename["cudaGLRegisterBufferObject"] = {"hipGLRegisterBufferObject", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGLRegisterBufferObject) cuda2hipRename["cudaGLSetBufferObjectMapFlags"] = {"hipGLSetBufferObjectMapFlags", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGLSetBufferObjectMapFlags) cuda2hipRename["cudaGLSetGLDevice"] = {"hipGLSetGLDevice", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // no API_Driver ANALOGUE cuda2hipRename["cudaGLUnmapBufferObject"] = {"hipGLUnmapBufferObject", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGLUnmapBufferObject) cuda2hipRename["cudaGLUnmapBufferObjectAsync"] = {"hipGLUnmapBufferObjectAsync", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGLUnmapBufferObjectAsync) cuda2hipRename["cudaGLUnregisterBufferObject"] = {"hipGLUnregisterBufferObject", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGLUnregisterBufferObject) // Direct3D 9 Interoperability // enum CUd3d9DeviceList cuda2hipRename["cudaD3D9DeviceList"] = {"hipD3D9DeviceList", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (CUd3d9DeviceList) cuda2hipRename["cudaD3D9DeviceListAll"] = {"HIP_D3D9_DEVICE_LIST_ALL", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // 1 // API_Driver ANALOGUE (CU_D3D9_DEVICE_LIST_ALL) cuda2hipRename["cudaD3D9DeviceListCurrentFrame"] = {"HIP_D3D9_DEVICE_LIST_CURRENT_FRAME", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // 2 // API_Driver ANALOGUE (CU_D3D9_DEVICE_LIST_CURRENT_FRAME) cuda2hipRename["cudaD3D9DeviceListNextFrame"] = {"HIP_D3D9_DEVICE_LIST_NEXT_FRAME", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // 3 // API_Driver ANALOGUE (CU_D3D9_DEVICE_LIST_NEXT_FRAME) cuda2hipRename["cudaD3D9GetDevice"] = {"hipD3D9GetDevice", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D9GetDevice) cuda2hipRename["cudaD3D9GetDevices"] = {"hipD3D9GetDevices", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D9GetDevices) cuda2hipRename["cudaD3D9GetDirect3DDevice"] = {"hipD3D9GetDirect3DDevice", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D9GetDirect3DDevice) cuda2hipRename["cudaD3D9SetDirect3DDevice"] = {"hipD3D9SetDirect3DDevice", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // no API_Driver ANALOGUE cuda2hipRename["cudaGraphicsD3D9RegisterResource"] = {"hipGraphicsD3D9RegisterResource", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGraphicsD3D9RegisterResource) // Direct3D 9 Interoperability [DEPRECATED] // enum cudaD3D9MapFlags cuda2hipRename["cudaD3D9MapFlags"] = {"hipD3D9MapFlags", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (CUd3d9map_flags) cuda2hipRename["cudaD3D9MapFlagsNone"] = {"HIP_D3D9_MAPRESOURCE_FLAGS_NONE", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // 0 // API_Driver ANALOGUE (CU_D3D9_MAPRESOURCE_FLAGS_NONE) cuda2hipRename["cudaD3D9MapFlagsReadOnly"] = {"HIP_D3D9_MAPRESOURCE_FLAGS_READONLY", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // 1 // API_Driver ANALOGUE (CU_D3D9_MAPRESOURCE_FLAGS_READONLY) cuda2hipRename["cudaD3D9MapFlagsWriteDiscard"] = {"HIP_D3D9_MAPRESOURCE_FLAGS_WRITEDISCARD", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // 2 // API_Driver ANALOGUE (CU_D3D9_MAPRESOURCE_FLAGS_WRITEDISCARD) // enum cudaD3D9RegisterFlags cuda2hipRename["cudaD3D9RegisterFlags"] = {"hipD3D9RegisterFlags", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (CUd3d9Register_flags) cuda2hipRename["cudaD3D9RegisterFlagsNone"] = {"HIP_D3D9_REGISTER_FLAGS_NONE", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // 0 // API_Driver ANALOGUE (CU_D3D9_REGISTER_FLAGS_NONE) cuda2hipRename["cudaD3D9RegisterFlagsArray"] = {"HIP_D3D9_REGISTER_FLAGS_ARRAY", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // 1 // API_Driver ANALOGUE (CU_D3D9_REGISTER_FLAGS_ARRAY) cuda2hipRename["cudaD3D9MapResources"] = {"hipD3D9MapResources", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D9MapResources) cuda2hipRename["cudaD3D9RegisterResource"] = {"hipD3D9RegisterResource", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D9RegisterResource) cuda2hipRename["cudaD3D9ResourceGetMappedArray"] = {"hipD3D9ResourceGetMappedArray", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D9ResourceGetMappedArray) cuda2hipRename["cudaD3D9ResourceGetMappedPitch"] = {"hipD3D9ResourceGetMappedPitch", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cudaD3D9ResourceGetMappedPitch) cuda2hipRename["cudaD3D9ResourceGetMappedPointer"] = {"hipD3D9ResourceGetMappedPointer", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D9ResourceGetMappedPointer) cuda2hipRename["cudaD3D9ResourceGetMappedSize"] = {"hipD3D9ResourceGetMappedSize", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D9ResourceGetMappedSize) cuda2hipRename["cudaD3D9ResourceGetSurfaceDimensions"] = {"hipD3D9ResourceGetSurfaceDimensions", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D9ResourceGetSurfaceDimensions) cuda2hipRename["cudaD3D9ResourceSetMapFlags"] = {"hipD3D9ResourceSetMapFlags", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D9ResourceSetMapFlags) cuda2hipRename["cudaD3D9UnmapResources"] = {"hipD3D9UnmapResources", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D9UnmapResources) cuda2hipRename["cudaD3D9UnregisterResource"] = {"hipD3D9UnregisterResource", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D9UnregisterResource) // Direct3D 10 Interoperability // enum cudaD3D10DeviceList cuda2hipRename["cudaD3D10DeviceList"] = {"hipd3d10DeviceList", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (CUd3d10DeviceList) cuda2hipRename["cudaD3D10DeviceListAll"] = {"HIP_D3D10_DEVICE_LIST_ALL", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // 1 // API_Driver ANALOGUE (CU_D3D10_DEVICE_LIST_ALL) cuda2hipRename["cudaD3D10DeviceListCurrentFrame"] = {"HIP_D3D10_DEVICE_LIST_CURRENT_FRAME", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // 2 // API_Driver ANALOGUE (CU_D3D10_DEVICE_LIST_CURRENT_FRAME) cuda2hipRename["cudaD3D10DeviceListNextFrame"] = {"HIP_D3D10_DEVICE_LIST_NEXT_FRAME", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // 3 // API_Driver ANALOGUE (CU_D3D10_DEVICE_LIST_NEXT_FRAME) cuda2hipRename["cudaD3D10GetDevice"] = {"hipD3D10GetDevice", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D10GetDevice) cuda2hipRename["cudaD3D10GetDevices"] = {"hipD3D10GetDevices", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D10GetDevices) cuda2hipRename["cudaGraphicsD3D10RegisterResource"] = {"hipGraphicsD3D10RegisterResource", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGraphicsD3D10RegisterResource) // Direct3D 10 Interoperability [DEPRECATED] // enum cudaD3D10MapFlags cuda2hipRename["cudaD3D10MapFlags"] = {"hipD3D10MapFlags", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (CUd3d10map_flags) cuda2hipRename["cudaD3D10MapFlagsNone"] = {"HIP_D3D10_MAPRESOURCE_FLAGS_NONE", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // 0 // API_Driver ANALOGUE (CU_D3D10_MAPRESOURCE_FLAGS_NONE) cuda2hipRename["cudaD3D10MapFlagsReadOnly"] = {"HIP_D3D10_MAPRESOURCE_FLAGS_READONLY", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // 1 // API_Driver ANALOGUE (CU_D3D10_MAPRESOURCE_FLAGS_READONLY) cuda2hipRename["cudaD3D10MapFlagsWriteDiscard"] = {"HIP_D3D10_MAPRESOURCE_FLAGS_WRITEDISCARD", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // 2 // API_Driver ANALOGUE (CU_D3D10_MAPRESOURCE_FLAGS_WRITEDISCARD) // enum cudaD3D10RegisterFlags cuda2hipRename["cudaD3D10RegisterFlags"] = {"hipD3D10RegisterFlags", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (CUd3d10Register_flags) cuda2hipRename["cudaD3D10RegisterFlagsNone"] = {"HIP_D3D10_REGISTER_FLAGS_NONE", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // 0 // API_Driver ANALOGUE (CU_D3D10_REGISTER_FLAGS_NONE) cuda2hipRename["cudaD3D10RegisterFlagsArray"] = {"HIP_D3D10_REGISTER_FLAGS_ARRAY", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // 1 // API_Driver ANALOGUE (CU_D3D10_REGISTER_FLAGS_ARRAY) cuda2hipRename["cudaD3D10GetDirect3DDevice"] = {"hipD3D10GetDirect3DDevice", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cudaD3D10GetDirect3DDevice) cuda2hipRename["cudaD3D10MapResources"] = {"hipD3D10MapResources", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D10MapResources) cuda2hipRename["cudaD3D10RegisterResource"] = {"hipD3D10RegisterResource", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D10RegisterResource) cuda2hipRename["cudaD3D10ResourceGetMappedArray"] = {"hipD3D10ResourceGetMappedArray", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D10ResourceGetMappedArray) cuda2hipRename["cudaD3D10ResourceGetMappedPitch"] = {"hipD3D10ResourceGetMappedPitch", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cudaD3D10ResourceGetMappedPitch) cuda2hipRename["cudaD3D10ResourceGetMappedPointer"] = {"hipD3D10ResourceGetMappedPointer", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D10ResourceGetMappedPointer) cuda2hipRename["cudaD3D10ResourceGetMappedSize"] = {"hipD3D10ResourceGetMappedSize", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D10ResourceGetMappedSize) cuda2hipRename["cudaD3D10ResourceGetSurfaceDimensions"] = {"hipD3D10ResourceGetSurfaceDimensions", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D10ResourceGetSurfaceDimensions) cuda2hipRename["cudaD3D10ResourceSetMapFlags"] = {"hipD3D10ResourceSetMapFlags", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D10ResourceSetMapFlags) cuda2hipRename["cudaD3D10SetDirect3DDevice"] = {"hipD3D10SetDirect3DDevice", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // no API_Driver ANALOGUE cuda2hipRename["cudaD3D10UnmapResources"] = {"hipD3D10UnmapResources", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D10UnmapResources) cuda2hipRename["cudaD3D10UnregisterResource"] = {"hipD3D10UnregisterResource", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D10UnregisterResource) // Direct3D 11 Interoperability // enum cudaD3D11DeviceList cuda2hipRename["cudaD3D11DeviceList"] = {"hipd3d11DeviceList", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (CUd3d11DeviceList) cuda2hipRename["cudaD3D11DeviceListAll"] = {"HIP_D3D11_DEVICE_LIST_ALL", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED}; // 1 // API_Driver ANALOGUE (CU_D3D11_DEVICE_LIST_ALL) cuda2hipRename["cudaD3D11DeviceListCurrentFrame"] = {"HIP_D3D11_DEVICE_LIST_CURRENT_FRAME", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED}; // 2 // API_Driver ANALOGUE (CU_D3D11_DEVICE_LIST_CURRENT_FRAME) cuda2hipRename["cudaD3D11DeviceListNextFrame"] = {"HIP_D3D11_DEVICE_LIST_NEXT_FRAME", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED}; // 3 // API_Driver ANALOGUE (CU_D3D11_DEVICE_LIST_NEXT_FRAME) cuda2hipRename["cudaD3D11GetDevice"] = {"hipD3D11GetDevice", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D11GetDevice) cuda2hipRename["cudaD3D11GetDevices"] = {"hipD3D11GetDevices", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D11GetDevices) cuda2hipRename["cudaGraphicsD3D11RegisterResource"] = {"hipGraphicsD3D11RegisterResource", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGraphicsD3D11RegisterResource) // Direct3D 11 Interoperability [DEPRECATED] cuda2hipRename["cudaD3D11GetDevice"] = {"hipD3D11GetDevice", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D11GetDevice) cuda2hipRename["cudaD3D11GetDevices"] = {"hipD3D11GetDevices", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuD3D11GetDevices) cuda2hipRename["cudaGraphicsD3D11RegisterResource"] = {"hipGraphicsD3D11RegisterResource", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGraphicsD3D11RegisterResource) // VDPAU Interoperability cuda2hipRename["cudaGraphicsVDPAURegisterOutputSurface"] = {"hipGraphicsVDPAURegisterOutputSurface", CONV_VDPAU, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGraphicsVDPAURegisterOutputSurface) cuda2hipRename["cudaGraphicsVDPAURegisterVideoSurface"] = {"hipGraphicsVDPAURegisterVideoSurface", CONV_VDPAU, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGraphicsVDPAURegisterVideoSurface) cuda2hipRename["cudaVDPAUGetDevice"] = {"hipVDPAUGetDevice", CONV_VDPAU, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuVDPAUGetDevice) cuda2hipRename["cudaVDPAUSetVDPAUDevice"] = {"hipVDPAUSetDevice", CONV_VDPAU, API_RUNTIME, HIP_UNSUPPORTED}; // no API_Driver ANALOGUE // EGL Interoperability cuda2hipRename["cudaEglStreamConnection"] = {"hipEglStreamConnection", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (CUeglStreamConnection) cuda2hipRename["cudaEGLStreamConsumerAcquireFrame"] = {"hipEGLStreamConsumerAcquireFrame", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuEGLStreamConsumerAcquireFrame) cuda2hipRename["cudaEGLStreamConsumerConnect"] = {"hipEGLStreamConsumerConnect", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuEGLStreamConsumerConnect) cuda2hipRename["cudaEGLStreamConsumerConnectWithFlags"] = {"hipEGLStreamConsumerConnectWithFlags", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuEGLStreamConsumerConnectWithFlags) cuda2hipRename["cudaEGLStreamConsumerReleaseFrame"] = {"hipEGLStreamConsumerReleaseFrame", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuEGLStreamConsumerReleaseFrame) cuda2hipRename["cudaEGLStreamProducerConnect"] = {"hipEGLStreamProducerConnect", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuEGLStreamProducerConnect) cuda2hipRename["cudaEGLStreamProducerDisconnect"] = {"hipEGLStreamProducerDisconnect", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuEGLStreamProducerDisconnect) cuda2hipRename["cudaEGLStreamProducerPresentFrame"] = {"hipEGLStreamProducerPresentFrame", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuEGLStreamProducerPresentFrame) cuda2hipRename["cudaEGLStreamProducerReturnFrame"] = {"hipEGLStreamProducerReturnFrame", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuEGLStreamProducerReturnFrame) cuda2hipRename["cudaGraphicsEGLRegisterImage"] = {"hipGraphicsEGLRegisterImage", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGraphicsEGLRegisterImage) cuda2hipRename["cudaGraphicsResourceGetMappedEglFrame"] = {"hipGraphicsResourceGetMappedEglFrame", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED}; // API_Driver ANALOGUE (cuGraphicsResourceGetMappedEglFrame) //---------------------------------------BLAS-------------------------------------// // Blas types cuda2hipRename["cublasHandle_t"] = {"hipblasHandle_t", CONV_TYPE, API_BLAS}; // TODO: dereferencing: typedef struct cublasContext *cublasHandle_t; // cuda2hipRename["cublasContext"] = {"hipblasHandle_t", CONV_TYPE, API_BLAS}; // Blas management functions // unsupported yet by hipblas/hcblas cuda2hipRename["cublasInit"] = {"hipblasInit", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasShutdown"] = {"hipblasShutdown", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasGetVersion"] = {"hipblasGetVersion", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasGetError"] = {"hipblasGetError", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasAlloc"] = {"hipblasAlloc", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasFree"] = {"hipblasFree", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasSetKernelStream"] = {"hipblasSetKernelStream", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasGetAtomicsMode"] = {"hipblasGetAtomicsMode", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasSetAtomicsMode"] = {"hipblasSetAtomicsMode", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // Blas operations cuda2hipRename["cublasOperation_t"] = {"hipblasOperation_t", CONV_TYPE, API_BLAS}; cuda2hipRename["CUBLAS_OP_N"] = {"HIPBLAS_OP_N", CONV_NUMERIC_LITERAL, API_BLAS}; cuda2hipRename["CUBLAS_OP_T"] = {"HIPBLAS_OP_T", CONV_NUMERIC_LITERAL, API_BLAS}; cuda2hipRename["CUBLAS_OP_C"] = {"HIPBLAS_OP_C", CONV_NUMERIC_LITERAL, API_BLAS}; // Blas statuses cuda2hipRename["cublasStatus_t"] = {"hipblasStatus_t", CONV_TYPE, API_BLAS}; cuda2hipRename["CUBLAS_STATUS_SUCCESS"] = {"HIPBLAS_STATUS_SUCCESS", CONV_NUMERIC_LITERAL, API_BLAS}; cuda2hipRename["CUBLAS_STATUS_NOT_INITIALIZED"] = {"HIPBLAS_STATUS_NOT_INITIALIZED", CONV_NUMERIC_LITERAL, API_BLAS}; cuda2hipRename["CUBLAS_STATUS_ALLOC_FAILED"] = {"HIPBLAS_STATUS_ALLOC_FAILED", CONV_NUMERIC_LITERAL, API_BLAS}; cuda2hipRename["CUBLAS_STATUS_INVALID_VALUE"] = {"HIPBLAS_STATUS_INVALID_VALUE", CONV_NUMERIC_LITERAL, API_BLAS}; cuda2hipRename["CUBLAS_STATUS_MAPPING_ERROR"] = {"HIPBLAS_STATUS_MAPPING_ERROR", CONV_NUMERIC_LITERAL, API_BLAS}; cuda2hipRename["CUBLAS_STATUS_EXECUTION_FAILED"] = {"HIPBLAS_STATUS_EXECUTION_FAILED", CONV_NUMERIC_LITERAL, API_BLAS}; cuda2hipRename["CUBLAS_STATUS_INTERNAL_ERROR"] = {"HIPBLAS_STATUS_INTERNAL_ERROR", CONV_NUMERIC_LITERAL, API_BLAS}; cuda2hipRename["CUBLAS_STATUS_NOT_SUPPORTED"] = {"HIPBLAS_STATUS_INTERNAL_ERROR", CONV_NUMERIC_LITERAL, API_BLAS}; // Blas Fill Modes // unsupported yet by hipblas/hcblas cuda2hipRename["cublasFillMode_t"] = {"hipblasFillMode_t", CONV_TYPE, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["CUBLAS_FILL_MODE_LOWER"] = {"HIPBLAS_FILL_MODE_LOWER", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["CUBLAS_FILL_MODE_UPPER"] = {"HIPBLAS_FILL_MODE_UPPER", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED}; // Blas Diag Types // unsupported yet by hipblas/hcblas cuda2hipRename["cublasDiagType_t"] = {"hipblasDiagType_t", CONV_TYPE, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["CUBLAS_DIAG_NON_UNIT"] = {"HIPBLAS_DIAG_NON_UNIT", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["CUBLAS_DIAG_UNIT"] = {"HIPBLAS_DIAG_UNIT", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED}; // Blas Side Modes // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSideMode_t"] = {"hipblasSideMode_t", CONV_TYPE, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["CUBLAS_SIDE_LEFT"] = {"HIPBLAS_SIDE_LEFT", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["CUBLAS_SIDE_RIGHT"] = {"HIPBLAS_SIDE_RIGHT", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED}; // Blas Pointer Modes // unsupported yet by hipblas/hcblas cuda2hipRename["cublasPointerMode_t"] = {"hipblasPointerMode_t", CONV_TYPE, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["CUBLAS_POINTER_MODE_HOST"] = {"HIPBLAS_POINTER_MODE_HOST", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["CUBLAS_POINTER_MODE_DEVICE"] = {"HIPBLAS_POINTER_MODE_DEVICE", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED}; // Blas Atomics Modes // unsupported yet by hipblas/hcblas cuda2hipRename["cublasAtomicsMode_t"] = {"hipblasAtomicsMode_t", CONV_TYPE, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["CUBLAS_ATOMICS_NOT_ALLOWED"] = {"HIPBLAS_ATOMICS_NOT_ALLOWED", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["CUBLAS_ATOMICS_ALLOWED"] = {"HIPBLAS_ATOMICS_ALLOWED", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED}; // Blas Data Type // unsupported yet by hipblas/hcblas cuda2hipRename["cublasDataType_t"] = {"hipblasDataType_t", CONV_TYPE, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["CUBLAS_DATA_FLOAT"] = {"HIPBLAS_DATA_FLOAT", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["CUBLAS_DATA_DOUBLE"] = {"HIPBLAS_DATA_DOUBLE", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["CUBLAS_DATA_HALF"] = {"HIPBLAS_DATA_HALF", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["CUBLAS_DATA_INT8"] = {"HIPBLAS_DATA_INT8", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED}; // Blas1 (v1) Routines cuda2hipRename["cublasCreate"] = {"hipblasCreate", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasDestroy"] = {"hipblasDestroy", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasSetVector"] = {"hipblasSetVector", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasGetVector"] = {"hipblasGetVector", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasSetMatrix"] = {"hipblasSetMatrix", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasGetMatrix"] = {"hipblasGetMatrix", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasGetMatrixAsync"] = {"hipblasGetMatrixAsync", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasSetMatrixAsync"] = {"hipblasSetMatrixAsync", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // NRM2 // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSnrm2"] = {"hipblasSnrm2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDnrm2"] = {"hipblasDnrm2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasScnrm2"] = {"hipblasScnrm2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDznrm2"] = {"hipblasDznrm2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // DOT cuda2hipRename["cublasSdot"] = {"hipblasSdot", CONV_MATH_FUNC, API_BLAS}; // there is no such a function in CUDA cuda2hipRename["cublasSdotBatched"] = {"hipblasSdotBatched",CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasDdot"] = {"hipblasDdot", CONV_MATH_FUNC, API_BLAS}; // there is no such a function in CUDA cuda2hipRename["cublasDdotBatched"] = {"hipblasDdotBatched", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasCdotu"] = {"hipblasCdotu", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCdotc"] = {"hipblasCdotc", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZdotu"] = {"hipblasZdotu", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZdotc"] = {"hipblasZdotc", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SCAL cuda2hipRename["cublasSscal"] = {"hipblasSscal", CONV_MATH_FUNC, API_BLAS}; // there is no such a function in CUDA cuda2hipRename["cublasSscalBatched"] = {"hipblasSscalBatched", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasDscal"] = {"hipblasDscal", CONV_MATH_FUNC, API_BLAS}; // there is no such a function in CUDA cuda2hipRename["cublasDscalBatched"] = {"hipblasDscalBatched", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasCscal"] = {"hipblasCscal", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCsscal"] = {"hipblasCsscal", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZscal"] = {"hipblasZscal", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZdscal"] = {"hipblasZdscal", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // AXPY cuda2hipRename["cublasSaxpy"] = {"hipblasSaxpy", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasSaxpyBatched"] = {"hipblasSaxpyBatched", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasDaxpy"] = {"hipblasDaxpy", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasCaxpy"] = {"hipblasCaxpy", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZaxpy"] = {"hipblasZaxpy", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // COPY cuda2hipRename["cublasScopy"] = {"hipblasScopy", CONV_MATH_FUNC, API_BLAS}; // there is no such a function in CUDA cuda2hipRename["cublasScopyBatched"] = {"hipblasScopyBatched", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasDcopy"] = {"hipblasDcopy", CONV_MATH_FUNC, API_BLAS}; // there is no such a function in CUDA cuda2hipRename["cublasDcopyBatched"] = {"hipblasDcopyBatched", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasCcopy"] = {"hipblasCcopy", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZcopy"] = {"hipblasZcopy", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SWAP // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSswap"] = {"hipblasSswap", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDswap"] = {"hipblasDswap", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCswap"] = {"hipblasCswap", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZswap"] = {"hipblasZswap", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // AMAX // unsupported yet by hipblas/hcblas cuda2hipRename["cublasIsamax"] = {"hipblasIsamax", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasIdamax"] = {"hipblasIdamax", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasIcamax"] = {"hipblasIcamax", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasIzamax"] = {"hipblasIzamax", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // AMIN // unsupported yet by hipblas/hcblas cuda2hipRename["cublasIsamin"] = {"hipblasIsamin", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasIdamin"] = {"hipblasIdamin", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasIcamin"] = {"hipblasIcamin", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasIzamin"] = {"hipblasIzamin", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // ASUM cuda2hipRename["cublasSasum"] = {"hipblasSasum", CONV_MATH_FUNC, API_BLAS}; // there is no such a function in CUDA cuda2hipRename["cublasSasumBatched"] = {"hipblasSasumBatched", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasDasum"] = {"hipblasDasum", CONV_MATH_FUNC, API_BLAS}; // there is no such a function in CUDA cuda2hipRename["cublasDasumBatched"] = {"hipblasDasumBatched", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasScasum"] = {"hipblasScasum", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDzasum"] = {"hipblasDzasum", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // ROT // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSrot"] = {"hipblasSrot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDrot"] = {"hipblasDrot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCrot"] = {"hipblasCrot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCsrot"] = {"hipblasCsrot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZrot"] = {"hipblasZrot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZdrot"] = {"hipblasZdrot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // ROTG // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSrotg"] = {"hipblasSrotg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDrotg"] = {"hipblasDrotg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCrotg"] = {"hipblasCrotg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZrotg"] = {"hipblasZrotg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // ROTM // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSrotm"] = {"hipblasSrotm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDrotm"] = {"hipblasDrotm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // ROTMG // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSrotmg"] = {"hipblasSrotmg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDrotmg"] = {"hipblasDrotmg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // GEMV cuda2hipRename["cublasSgemv"] = {"hipblasSgemv", CONV_MATH_FUNC, API_BLAS}; // there is no such a function in CUDA cuda2hipRename["cublasSgemvBatched"] = {"hipblasSgemvBatched", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasDgemv"] = {"hipblasDgemv", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasCgemv"] = {"hipblasCgemv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZgemv"] = {"hipblasZgemv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // GBMV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSgbmv"] = {"hipblasSgbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDgbmv"] = {"hipblasDgbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCgbmv"] = {"hipblasCgbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZgbmv"] = {"hipblasZgbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TRMV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStrmv"] = {"hipblasStrmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtrmv"] = {"hipblasDtrmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtrmv"] = {"hipblasCtrmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtrmv"] = {"hipblasZtrmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TBMV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStbmv"] = {"hipblasStbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtbmv"] = {"hipblasDtbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtbmv"] = {"hipblasCtbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtbmv"] = {"hipblasZtbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TPMV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStpmv"] = {"hipblasStpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtpmv"] = {"hipblasDtpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtpmv"] = {"hipblasCtpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtpmv"] = {"hipblasZtpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TRSV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStrsv"] = {"hipblasStrsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtrsv"] = {"hipblasDtrsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtrsv"] = {"hipblasCtrsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtrsv"] = {"hipblasZtrsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TPSV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStpsv"] = {"hipblasStpsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtpsv"] = {"hipblasDtpsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtpsv"] = {"hipblasCtpsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtpsv"] = {"hipblasZtpsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TBSV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStbsv"] = {"hipblasStbsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtbsv"] = {"hipblasDtbsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtbsv"] = {"hipblasCtbsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtbsv"] = {"hipblasZtbsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SYMV/HEMV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSsymv"] = {"hipblasSsymv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDsymv"] = {"hipblasDsymv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCsymv"] = {"hipblasCsymv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZsymv"] = {"hipblasZsymv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasChemv"] = {"hipblasChemv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZhemv"] = {"hipblasZhemv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SBMV/HBMV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSsbmv"] = {"hipblasSsbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDsbmv"] = {"hpiblasDsbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasChbmv"] = {"hipblasChbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZhbmv"] = {"hipblasZhbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SPMV/HPMV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSspmv"] = {"hipblasSspmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDspmv"] = {"hipblasDspmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasChpmv"] = {"hipblasChpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZhpmv"] = {"hipblasZhpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // GER cuda2hipRename["cublasSger"] = {"hipblasSger", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasDger"] = {"hipblasDger", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasCgeru"] = {"hipblasCgeru", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCgerc"] = {"hipblasCgerc", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZgeru"] = {"hipblasZgeru", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZgerc"] = {"hipblasZgerc", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SYR/HER // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSsyr"] = {"hipblasSsyr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDsyr"] = {"hipblasDsyr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCher"] = {"hipblasCher", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZher"] = {"hipblasZher", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SPR/HPR // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSspr"] = {"hipblasSspr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDspr"] = {"hipblasDspr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasChpr"] = {"hipblasChpr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZhpr"] = {"hipblasZhpr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SYR2/HER2 // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSsyr2"] = {"hipblasSsyr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDsyr2"] = {"hipblasDsyr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCher2"] = {"hipblasCher2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZher2"] = {"hipblasZher2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SPR2/HPR2 // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSspr2"] = {"hipblasSspr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDspr2"] = {"hipblasDspr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasChpr2"] = {"hipblasChpr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZhpr2"] = {"hipblasZhpr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // Blas3 (v1) Routines // GEMM cuda2hipRename["cublasSgemm"] = {"hipblasSgemm", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasDgemm"] = {"hipblasDgemm", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasCgemm"] = {"hipblasCgemm", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasZgemm"] = {"hipblasZgemm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // BATCH GEMM cuda2hipRename["cublasSgemmBatched"] = {"hipblasSgemmBatched", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasDgemmBatched"] = {"hipblasDgemmBatched", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasCgemmBatched"] = {"hipblasCgemmBatched", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasZgemmBatched"] = {"hipblasZgemmBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SYRK // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSsyrk"] = {"hipblasSsyrk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDsyrk"] = {"hipblasDsyrk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCsyrk"] = {"hipblasCsyrk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZsyrk"] = {"hipblasZsyrk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // HERK // unsupported yet by hipblas/hcblas cuda2hipRename["cublasCherk"] = {"hipblasCherk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZherk"] = {"hipblasZherk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SYR2K // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSsyr2k"] = {"hipblasSsyr2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDsyr2k"] = {"hipblasDsyr2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCsyr2k"] = {"hipblasCsyr2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZsyr2k"] = {"hipblasZsyr2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SYRKX - eXtended SYRK // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSsyrkx"] = {"hipblasSsyrkx", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDsyrkx"] = {"hipblasDsyrkx", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCsyrkx"] = {"hipblasCsyrkx", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZsyrkx"] = {"hipblasZsyrkx", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // HER2K // unsupported yet by hipblas/hcblas cuda2hipRename["cublasCher2k"] = {"hipblasCher2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZher2k"] = {"hipblasZher2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // HERKX - eXtended HERK // unsupported yet by hipblas/hcblas cuda2hipRename["cublasCherkx"] = {"hipblasCherkx", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZherkx"] = {"hipblasZherkx", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SYMM // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSsymm"] = {"hipblasSsymm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDsymm"] = {"hipblasDsymm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCsymm"] = {"hipblasCsymm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZsymm"] = {"hipblasZsymm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // HEMM // unsupported yet by hipblas/hcblas cuda2hipRename["cublasChemm"] = {"hipblasChemm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZhemm"] = {"hipblasZhemm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TRSM // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStrsm"] = {"hipblasStrsm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtrsm"] = {"hipblasDtrsm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtrsm"] = {"hipblasCtrsm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtrsm"] = {"hipblasZtrsm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TRSM - Batched Triangular Solver // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStrsmBatched"] = {"hipblasStrsmBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtrsmBatched"] = {"hipblasDtrsmBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtrsmBatched"] = {"hipblasCtrsmBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtrsmBatched"] = {"hipblasZtrsmBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TRMM // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStrmm"] = {"hipblasStrmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtrmm"] = {"hipblasDtrmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtrmm"] = {"hipblasCtrmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtrmm"] = {"hipblasZtrmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // ------------------------ CUBLAS BLAS - like extension (cublas_api.h) // GEAM // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSgeam"] = {"hipblasSgeam", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDgeam"] = {"hipblasDgeam", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCgeam"] = {"hipblasCgeam", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZgeam"] = {"hipblasZgeam", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // GETRF - Batched LU // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSgetrfBatched"] = {"hipblasSgetrfBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDgetrfBatched"] = {"hipblasDgetrfBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCgetrfBatched"] = {"hipblasCgetrfBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZgetrfBatched"] = {"hipblasZgetrfBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // Batched inversion based on LU factorization from getrf // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSgetriBatched"] = {"hipblasSgetriBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDgetriBatched"] = {"hipblasDgetriBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCgetriBatched"] = {"hipblasCgetriBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZgetriBatched"] = {"hipblasZgetriBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // Batched solver based on LU factorization from getrf // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSgetrsBatched"] = {"hipblasSgetrsBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDgetrsBatched"] = {"hipblasDgetrsBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCgetrsBatched"] = {"hipblasCgetrsBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZgetrsBatched"] = {"hipblasZgetrsBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TRSM - Batched Triangular Solver // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStrsmBatched"] = {"hipblasStrsmBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtrsmBatched"] = {"hipblasDtrsmBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtrsmBatched"] = {"hipblasCtrsmBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtrsmBatched"] = {"hipblasZtrsmBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // MATINV - Batched // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSmatinvBatched"] = {"hipblasSmatinvBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDmatinvBatched"] = {"hipblasDmatinvBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCmatinvBatched"] = {"hipblasCmatinvBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZmatinvBatched"] = {"hipblasZmatinvBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // Batch QR Factorization // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSgeqrfBatched"] = {"hipblasSgeqrfBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDgeqrfBatched"] = {"hipblasDgeqrfBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCgeqrfBatched"] = {"hipblasCgeqrfBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZgeqrfBatched"] = {"hipblasZgeqrfBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // Least Square Min only m >= n and Non-transpose supported // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSgelsBatched"] = {"hipblasSgelsBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDgelsBatched"] = {"hipblasDgelsBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCgelsBatched"] = {"hipblasCgelsBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZgelsBatched"] = {"hipblasZgelsBatched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // DGMM // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSdgmm"] = {"hipblasSdgmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDdgmm"] = {"hipblasDdgmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCdgmm"] = {"hipblasCdgmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZdgmm"] = {"hipblasZdgmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TPTTR - Triangular Pack format to Triangular format // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStpttr"] = {"hipblasStpttr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtpttr"] = {"hipblasDtpttr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtpttr"] = {"hipblasCtpttr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtpttr"] = {"hipblasZtpttr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TRTTP - Triangular format to Triangular Pack format // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStrttp"] = {"hipblasStrttp", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtrttp"] = {"hipblasDtrttp", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtrttp"] = {"hipblasCtrttp", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtrttp"] = {"hipblasZtrttp", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // Blas2 (v2) Routines cuda2hipRename["cublasCreate_v2"] = {"hipblasCreate", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasDestroy_v2"] = {"hipblasDestroy", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasGetVersion_v2"] = {"hipblasGetVersion", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasSetStream_v2"] = {"hipblasSetStream", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasGetStream_v2"] = {"hipblasGetStream", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasGetPointerMode_v2"] = {"hipblasGetPointerMode", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasSetPointerMode_v2"] = {"hipblasSetPointerMode", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // GEMV cuda2hipRename["cublasSgemv_v2"] = {"hipblasSgemv", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasDgemv_v2"] = {"hipblasDgemv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCgemv_v2"] = {"hipblasCgemv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZgemv_v2"] = {"hipblasZgemv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // GBMV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSgbmv_v2"] = {"hipblasSgbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDgbmv_v2"] = {"hipblasDgbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCgbmv_v2"] = {"hipblasCgbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZgbmv_v2"] = {"hipblasZgbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TRMV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStrmv_v2"] = {"hipblasStrmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtrmv_v2"] = {"hipblasDtrmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtrmv_v2"] = {"hipblasCtrmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtrmv_v2"] = {"hipblasZtrmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TBMV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStbmv_v2"] = {"hipblasStbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtbmv_v2"] = {"hipblasDtbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtbmv_v2"] = {"hipblasCtbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtbmv_v2"] = {"hipblasZtbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TPMV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStpmv_v2"] = {"hipblasStpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtpmv_v2"] = {"hipblasDtpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtpmv_v2"] = {"hipblasCtpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtpmv_v2"] = {"hipblasZtpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TRSV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStrsv_v2"] = {"hipblasStrsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtrsv_v2"] = {"hipblasDtrsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtrsv_v2"] = {"hipblasCtrsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtrsv_v2"] = {"hipblasZtrsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TPSV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStpsv_v2"] = {"hipblasStpsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtpsv_v2"] = {"hipblasDtpsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtpsv_v2"] = {"hipblasCtpsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtpsv_v2"] = {"hipblasZtpsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TBSV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStbsv_v2"] = {"hipblasStbsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtbsv_v2"] = {"hipblasDtbsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtbsv_v2"] = {"hipblasCtbsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtbsv_v2"] = {"hipblasZtbsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SYMV/HEMV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSsymv_v2"] = {"hipblasSsymv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDsymv_v2"] = {"hipblasDsymv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCsymv_v2"] = {"hipblasCsymv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZsymv_v2"] = {"hipblasZsymv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasChemv_v2"] = {"hipblasChemv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZhemv_v2"] = {"hipblasZhemv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SBMV/HBMV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSsbmv_v2"] = {"hipblasSsbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDsbmv_v2"] = {"hpiblasDsbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasChbmv_v2"] = {"hipblasChbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZhbmv_v2"] = {"hipblasZhbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SPMV/HPMV // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSspmv_v2"] = {"hipblasSspmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDspmv_v2"] = {"hipblasDspmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasChpmv_v2"] = {"hipblasChpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZhpmv_v2"] = {"hipblasZhpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // GER cuda2hipRename["cublasSger_v2"] = {"hipblasSger", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasDger_v2"] = {"hipblasDger", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCgeru_v2"] = {"hipblasCgeru", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCgerc_v2"] = {"hipblasCgerc", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZgeru_v2"] = {"hipblasZgeru", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZgerc_v2"] = {"hipblasZgerc", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SYR/HER // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSsyr_v2"] = {"hipblasSsyr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDsyr_v2"] = {"hipblasDsyr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCsyr_v2"] = {"hipblasCsyr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZsyr_v2"] = {"hipblasZsyr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCher_v2"] = {"hipblasCher", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZher_v2"] = {"hipblasZher", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SPR/HPR // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSspr_v2"] = {"hipblasSspr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDspr_v2"] = {"hipblasDspr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasChpr_v2"] = {"hipblasChpr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZhpr_v2"] = {"hipblasZhpr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SYR2/HER2 // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSsyr2_v2"] = {"hipblasSsyr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDsyr2_v2"] = {"hipblasDsyr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCsyr2_v2"] = {"hipblasCsyr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZsyr2_v2"] = {"hipblasZsyr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCher2_v2"] = {"hipblasCher2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZher2_v2"] = {"hipblasZher2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SPR2/HPR2 // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSspr2_v2"] = {"hipblasSspr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDspr2_v2"] = {"hipblasDspr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasChpr2_v2"] = {"hipblasChpr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZhpr2_v2"] = {"hipblasZhpr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // Blas3 (v2) Routines // GEMM cuda2hipRename["cublasSgemm_v2"] = {"hipblasSgemm", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasDgemm_v2"] = {"hipblasDgemm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCgemm_v2"] = {"hipblasCgemm", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasZgemm_v2"] = {"hipblasZgemm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; //IO in FP16 / FP32, computation in float // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSgemmEx"] = {"hipblasSgemmEx", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SYRK // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSsyrk_v2"] = {"hipblasSsyrk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDsyrk_v2"] = {"hipblasDsyrk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCsyrk_v2"] = {"hipblasCsyrk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZsyrk_v2"] = {"hipblasZsyrk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // HERK // unsupported yet by hipblas/hcblas cuda2hipRename["cublasCherk_v2"] = {"hipblasCherk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZherk_v2"] = {"hipblasZherk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SYR2K // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSsyr2k_v2"] = {"hipblasSsyr2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDsyr2k_v2"] = {"hipblasDsyr2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCsyr2k_v2"] = {"hipblasCsyr2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZsyr2k_v2"] = {"hipblasZsyr2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // HER2K // unsupported yet by hipblas/hcblas cuda2hipRename["cublasCher2k_v2"] = {"hipblasCher2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZher2k_v2"] = {"hipblasZher2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SYMM // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSsymm_v2"] = {"hipblasSsymm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDsymm_v2"] = {"hipblasDsymm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCsymm_v2"] = {"hipblasCsymm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZsymm_v2"] = {"hipblasZsymm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // HEMM // unsupported yet by hipblas/hcblas cuda2hipRename["cublasChemm_v2"] = {"hipblasChemm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZhemm_v2"] = {"hipblasZhemm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TRSM // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStrsm_v2"] = {"hipblasStrsm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtrsm_v2"] = {"hipblasDtrsm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtrsm_v2"] = {"hipblasCtrsm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtrsm_v2"] = {"hipblasZtrsm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // TRMM // unsupported yet by hipblas/hcblas cuda2hipRename["cublasStrmm_v2"] = {"hipblasStrmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDtrmm_v2"] = {"hipblasDtrmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCtrmm_v2"] = {"hipblasCtrmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZtrmm_v2"] = {"hipblasZtrmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // NRM2 // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSnrm2_v2"] = {"hipblasSnrm2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDnrm2_v2"] = {"hipblasDnrm2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasScnrm2_v2"] = {"hipblasScnrm2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDznrm2_v2"] = {"hipblasDznrm2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // DOT cuda2hipRename["cublasSdot_v2"] = {"hipblasSdot", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasDdot_v2"] = {"hipblasDdot", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasCdotu_v2"] = {"hipblasCdotu", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCdotc_v2"] = {"hipblasCdotc", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZdotu_v2"] = {"hipblasZdotu", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZdotc_v2"] = {"hipblasZdotc", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SCAL cuda2hipRename["cublasSscal_v2"] = {"hipblasSscal", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasDscal_v2"] = {"hipblasDscal", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasCscal_v2"] = {"hipblasCscal", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCsscal_v2"] = {"hipblasCsscal", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZscal_v2"] = {"hipblasZscal", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZdscal_v2"] = {"hipblasZdscal", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // AXPY cuda2hipRename["cublasSaxpy_v2"] = {"hipblasSaxpy", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasDaxpy_v2"] = {"hipblasDaxpy", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasCaxpy_v2"] = {"hipblasCaxpy", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZaxpy_v2"] = {"hipblasZaxpy", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // COPY cuda2hipRename["cublasScopy_v2"] = {"hipblasScopy", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasDcopy_v2"] = {"hipblasDcopy", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasCcopy_v2"] = {"hipblasCcopy", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZcopy_v2"] = {"hipblasZcopy", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // SWAP // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSswap_v2"] = {"hipblasSswap", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDswap_v2"] = {"hipblasDswap", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCswap_v2"] = {"hipblasCswap", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZswap_v2"] = {"hipblasZswap", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // AMAX // unsupported yet by hipblas/hcblas cuda2hipRename["cublasIsamax_v2"] = {"hipblasIsamax", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasIdamax_v2"] = {"hipblasIdamax", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasIcamax_v2"] = {"hipblasIcamax", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasIzamax_v2"] = {"hipblasIzamax", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // AMIN // unsupported yet by hipblas/hcblas cuda2hipRename["cublasIsamin_v2"] = {"hipblasIsamin", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasIdamin_v2"] = {"hipblasIdamin", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasIcamin_v2"] = {"hipblasIcamin", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasIzamin_v2"] = {"hipblasIzamin", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // ASUM cuda2hipRename["cublasSasum_v2"] = {"hipblasSasum", CONV_MATH_FUNC, API_BLAS}; cuda2hipRename["cublasDasum_v2"] = {"hipblasDasum", CONV_MATH_FUNC, API_BLAS}; // unsupported yet by hipblas/hcblas cuda2hipRename["cublasScasum_v2"] = {"hipblasScasum", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDzasum_v2"] = {"hipblasDzasum", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // ROT // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSrot_v2"] = {"hipblasSrot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDrot_v2"] = {"hipblasDrot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCrot_v2"] = {"hipblasCrot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCsrot_v2"] = {"hipblasCsrot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZrot_v2"] = {"hipblasZrot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZdrot_v2"] = {"hipblasZdrot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // ROTG // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSrotg_v2"] = {"hipblasSrotg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDrotg_v2"] = {"hipblasDrotg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasCrotg_v2"] = {"hipblasCrotg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasZrotg_v2"] = {"hipblasZrotg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // ROTM // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSrotm_v2"] = {"hipblasSrotm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDrotm_v2"] = {"hipblasDrotm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; // ROTMG // unsupported yet by hipblas/hcblas cuda2hipRename["cublasSrotmg_v2"] = {"hipblasSrotmg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; cuda2hipRename["cublasDrotmg_v2"] = {"hipblasDrotmg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED}; } }; StringRef unquoteStr(StringRef s) { if (s.size() > 1 && s.front() == '"' && s.back() == '"') return s.substr(1, s.size() - 2); return s; } class Cuda2Hip { public: Cuda2Hip(Replacements *R, const std::string &srcFileName) : Replace(R), mainFileName(srcFileName) {} uint64_t countReps[CONV_LAST] = { 0 }; uint64_t countApiReps[API_LAST] = { 0 }; uint64_t countRepsUnsupported[CONV_LAST] = { 0 }; uint64_t countApiRepsUnsupported[API_LAST] = { 0 }; std::map<std::string, uint64_t> cuda2hipConverted; std::map<std::string, uint64_t> cuda2hipUnconverted; std::set<unsigned> LOCs; enum msgTypes { HIPIFY_ERROR = 0, HIPIFY_WARNING }; std::string getMsgType(msgTypes type) { switch (type) { case HIPIFY_ERROR: return "error"; default: case HIPIFY_WARNING: return "warning"; } } protected: struct cuda2hipMap N; Replacements *Replace; std::string mainFileName; virtual void insertReplacement(const Replacement &rep, const FullSourceLoc &fullSL) { Replace->insert(rep); if (PrintStats) { LOCs.insert(fullSL.getExpansionLineNumber()); } } void insertHipHeaders(Cuda2Hip *owner, const SourceManager &SM) { if (owner->countReps[CONV_INCLUDE_CUDA_MAIN_H] == 0 && countReps[CONV_INCLUDE_CUDA_MAIN_H] == 0 && Replace->size() > 0) { std::string repName = "#include <hip/hip_runtime.h>"; hipCounter counter = { repName, CONV_INCLUDE_CUDA_MAIN_H, API_RUNTIME }; updateCounters(counter, repName); SourceLocation sl = SM.getLocForStartOfFile(SM.getMainFileID()); FullSourceLoc fullSL(sl, SM); Replacement Rep(SM, sl, 0, repName + "\n"); insertReplacement(Rep, fullSL); } } void printHipifyMessage(const SourceManager &SM, const SourceLocation &sl, const std::string &message, msgTypes msgType = HIPIFY_WARNING) { FullSourceLoc fullSL(sl, SM); llvm::errs() << "[HIPIFY] " << getMsgType(msgType) << ": " << mainFileName << ":" << fullSL.getExpansionLineNumber() << ":" << fullSL.getExpansionColumnNumber() << ": " << message << "\n"; } void updateCountersExt(const hipCounter &counter, const std::string &cudaName) { std::map<std::string, uint64_t> *map = &cuda2hipConverted; std::map<std::string, uint64_t> *mapTotal = &cuda2hipConvertedTotal; if (counter.unsupported) { map = &cuda2hipUnconverted; mapTotal = &cuda2hipUnconvertedTotal; } auto found = map->find(cudaName); if (found == map->end()) { map->insert(std::pair<std::string, uint64_t>(cudaName, 1)); } else { found->second++; } auto foundT = mapTotal->find(cudaName); if (foundT == mapTotal->end()) { mapTotal->insert(std::pair<std::string, uint64_t>(cudaName, 1)); } else { foundT->second++; } } virtual void updateCounters(const hipCounter &counter, const std::string &cudaName) { if (!PrintStats) { return; } updateCountersExt(counter, cudaName); if (counter.unsupported) { countRepsUnsupported[counter.countType]++; countRepsTotalUnsupported[counter.countType]++; countApiRepsUnsupported[counter.countApiType]++; countApiRepsTotalUnsupported[counter.countApiType]++; } else { countReps[counter.countType]++; countRepsTotal[counter.countType]++; countApiReps[counter.countApiType]++; countApiRepsTotal[counter.countApiType]++; } } void processString(StringRef s, SourceManager &SM, SourceLocation start) { size_t begin = 0; while ((begin = s.find("cu", begin)) != StringRef::npos) { const size_t end = s.find_first_of(" ", begin + 4); StringRef name = s.slice(begin, end); const auto found = N.cuda2hipRename.find(name); if (found != N.cuda2hipRename.end()) { StringRef repName = found->second.hipName; hipCounter counter = {"", CONV_LITERAL, API_RUNTIME, found->second.unsupported}; updateCounters(counter, name.str()); if (!counter.unsupported) { SourceLocation sl = start.getLocWithOffset(begin + 1); Replacement Rep(SM, sl, name.size(), repName); FullSourceLoc fullSL(sl, SM); insertReplacement(Rep, fullSL); } } else { // std::string msg = "the following reference is not handled: '" + name.str() + "' [string literal]."; // printHipifyMessage(SM, start, msg); } if (end == StringRef::npos) { break; } begin = end + 1; } } }; class Cuda2HipCallback; class HipifyPPCallbacks : public PPCallbacks, public SourceFileCallbacks, public Cuda2Hip { public: HipifyPPCallbacks(Replacements *R, const std::string &mainFileName) : Cuda2Hip(R, mainFileName), SeenEnd(false), _sm(nullptr), _pp(nullptr) {} virtual bool handleBeginSource(CompilerInstance &CI, StringRef Filename) override { Preprocessor &PP = CI.getPreprocessor(); SourceManager &SM = CI.getSourceManager(); setSourceManager(&SM); PP.addPPCallbacks(std::unique_ptr<HipifyPPCallbacks>(this)); PP.Retain(); setPreprocessor(&PP); return true; } virtual void handleEndSource() override; virtual void InclusionDirective(SourceLocation hash_loc, const Token &include_token, StringRef file_name, bool is_angled, CharSourceRange filename_range, const FileEntry *file, StringRef search_path, StringRef relative_path, const clang::Module *imported) override { if (_sm->isWrittenInMainFile(hash_loc)) { if (is_angled) { const auto found = N.cuda2hipRename.find(file_name); if (found != N.cuda2hipRename.end()) { updateCounters(found->second, file_name.str()); if (!found->second.unsupported) { StringRef repName = found->second.hipName; DEBUG(dbgs() << "Include file found: " << file_name << "\n" << "SourceLocation: " << filename_range.getBegin().printToString(*_sm) << "\n" << "Will be replaced with " << repName << "\n"); SourceLocation sl = filename_range.getBegin(); SourceLocation sle = filename_range.getEnd(); const char *B = _sm->getCharacterData(sl); const char *E = _sm->getCharacterData(sle); SmallString<128> tmpData; Replacement Rep(*_sm, sl, E - B, Twine("<" + repName + ">").toStringRef(tmpData)); FullSourceLoc fullSL(sl, *_sm); insertReplacement(Rep, fullSL); } } else { // llvm::outs() << "[HIPIFY] warning: the following reference is not handled: '" << file_name << "' [inclusion directive].\n"; } } } } virtual void MacroDefined(const Token &MacroNameTok, const MacroDirective *MD) override { if (_sm->isWrittenInMainFile(MD->getLocation()) && MD->getKind() == MacroDirective::MD_Define) { for (auto T : MD->getMacroInfo()->tokens()) { if (T.isAnyIdentifier()) { StringRef name = T.getIdentifierInfo()->getName(); const auto found = N.cuda2hipRename.find(name); if (found != N.cuda2hipRename.end()) { updateCounters(found->second, name.str()); if (!found->second.unsupported) { StringRef repName = found->second.hipName; SourceLocation sl = T.getLocation(); DEBUG(dbgs() << "Identifier " << name << " found in definition of macro " << MacroNameTok.getIdentifierInfo()->getName() << "\n" << "will be replaced with: " << repName << "\n" << "SourceLocation: " << sl.printToString(*_sm) << "\n"); Replacement Rep(*_sm, sl, name.size(), repName); FullSourceLoc fullSL(sl, *_sm); insertReplacement(Rep, fullSL); } } else { // llvm::outs() << "[HIPIFY] warning: the following reference is not handled: '" << name << "' [macro].\n"; } } } } } virtual void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD, SourceRange Range, const MacroArgs *Args) override { if (_sm->isWrittenInMainFile(MacroNameTok.getLocation())) { for (unsigned int i = 0; Args && i < MD.getMacroInfo()->getNumArgs(); i++) { std::vector<Token> toks; // Code below is a kind of stolen from 'MacroArgs::getPreExpArgument' // to workaround the 'const' MacroArgs passed into this hook. const Token *start = Args->getUnexpArgument(i); size_t len = Args->getArgLength(start) + 1; #if (LLVM_VERSION_MAJOR >= 3) && (LLVM_VERSION_MINOR >= 9) _pp->EnterTokenStream(ArrayRef<Token>(start, len), false); #else _pp->EnterTokenStream(start, len, false, false); #endif do { toks.push_back(Token()); Token &tk = toks.back(); _pp->Lex(tk); } while (toks.back().isNot(tok::eof)); _pp->RemoveTopOfLexerStack(); // end of stolen code for (auto tok : toks) { if (tok.isAnyIdentifier()) { StringRef name = tok.getIdentifierInfo()->getName(); const auto found = N.cuda2hipRename.find(name); if (found != N.cuda2hipRename.end()) { updateCounters(found->second, name.str()); if (!found->second.unsupported) { StringRef repName = found->second.hipName; DEBUG(dbgs() << "Identifier " << name << " found as an actual argument in expansion of macro " << MacroNameTok.getIdentifierInfo()->getName() << "\n" << "will be replaced with: " << repName << "\n"); size_t length = name.size(); SourceLocation sl = tok.getLocation(); if (_sm->isMacroBodyExpansion(sl)) { LangOptions DefaultLangOptions; SourceLocation sl_macro = _sm->getExpansionLoc(sl); SourceLocation sl_end = Lexer::getLocForEndOfToken(sl_macro, 0, *_sm, DefaultLangOptions); length = _sm->getCharacterData(sl_end) - _sm->getCharacterData(sl_macro); name = StringRef(_sm->getCharacterData(sl_macro), length); sl = sl_macro; } Replacement Rep(*_sm, sl, length, repName); FullSourceLoc fullSL(sl, *_sm); insertReplacement(Rep, fullSL); } } else { // llvm::outs() << "[HIPIFY] warning: the following reference is not handled: '" << name << "' [macro expansion].\n"; } } else if (tok.isLiteral()) { SourceLocation sl = tok.getLocation(); if (_sm->isMacroBodyExpansion(sl)) { LangOptions DefaultLangOptions; SourceLocation sl_macro = _sm->getExpansionLoc(sl); SourceLocation sl_end = Lexer::getLocForEndOfToken(sl_macro, 0, *_sm, DefaultLangOptions); size_t length = _sm->getCharacterData(sl_end) - _sm->getCharacterData(sl_macro); StringRef name = StringRef(_sm->getCharacterData(sl_macro), length); const auto found = N.cuda2hipRename.find(name); if (found != N.cuda2hipRename.end()) { updateCounters(found->second, name.str()); if (!found->second.unsupported) { StringRef repName = found->second.hipName; sl = sl_macro; Replacement Rep(*_sm, sl, length, repName); FullSourceLoc fullSL(sl, *_sm); insertReplacement(Rep, fullSL); } } else { // llvm::outs() << "[HIPIFY] warning: the following reference is not handled: '" << name << "' [literal macro expansion].\n"; } } else { if (tok.is(tok::string_literal)) { StringRef s(tok.getLiteralData(), tok.getLength()); processString(unquoteStr(s), *_sm, tok.getLocation()); } } } } } } } void EndOfMainFile() override {} bool SeenEnd; void setSourceManager(SourceManager *sm) { _sm = sm; } void setPreprocessor(Preprocessor *pp) { _pp = pp; } void setMatch(Cuda2HipCallback *match) { Match = match; } private: SourceManager *_sm; Preprocessor *_pp; Cuda2HipCallback *Match; }; class Cuda2HipCallback : public MatchFinder::MatchCallback, public Cuda2Hip { private: void convertKernelDecl(const FunctionDecl *kernelDecl, const MatchFinder::MatchResult &Result) { SourceManager *SM = Result.SourceManager; LangOptions DefaultLangOptions; SmallString<40> XStr; raw_svector_ostream OS(XStr); SourceLocation sl = kernelDecl->getNameInfo().getEndLoc(); SourceLocation kernelArgListStart = Lexer::findLocationAfterToken(sl, tok::l_paren, *SM, DefaultLangOptions, true); DEBUG(dbgs() << kernelArgListStart.printToString(*SM)); if (kernelDecl->getNumParams() > 0) { const ParmVarDecl *pvdFirst = kernelDecl->getParamDecl(0); const ParmVarDecl *pvdLast = kernelDecl->getParamDecl(kernelDecl->getNumParams() - 1); SourceLocation kernelArgListStart(pvdFirst->getLocStart()); SourceLocation kernelArgListEnd(pvdLast->getLocEnd()); SourceLocation stop = Lexer::getLocForEndOfToken(kernelArgListEnd, 0, *SM, DefaultLangOptions); size_t repLength = SM->getCharacterData(stop) - SM->getCharacterData(kernelArgListStart); OS << StringRef(SM->getCharacterData(kernelArgListStart), repLength); Replacement Rep0(*(Result.SourceManager), kernelArgListStart, repLength, OS.str()); FullSourceLoc fullSL(sl, *(Result.SourceManager)); insertReplacement(Rep0, fullSL); } } bool cudaCall(const MatchFinder::MatchResult &Result) { if (const CallExpr *call = Result.Nodes.getNodeAs<CallExpr>("cudaCall")) { const FunctionDecl *funcDcl = call->getDirectCallee(); std::string name = funcDcl->getDeclName().getAsString(); SourceManager *SM = Result.SourceManager; SourceLocation sl = call->getLocStart(); const auto found = N.cuda2hipRename.find(name); if (found != N.cuda2hipRename.end()) { if (!found->second.unsupported) { StringRef repName = found->second.hipName; size_t length = name.size(); bool bReplace = true; if (SM->isMacroArgExpansion(sl)) { sl = SM->getImmediateSpellingLoc(sl); } else if (SM->isMacroBodyExpansion(sl)) { LangOptions DefaultLangOptions; SourceLocation sl_macro = SM->getExpansionLoc(sl); SourceLocation sl_end = Lexer::getLocForEndOfToken(sl_macro, 0, *SM, DefaultLangOptions); length = SM->getCharacterData(sl_end) - SM->getCharacterData(sl_macro); StringRef macroName = StringRef(SM->getCharacterData(sl_macro), length); if (N.cudaExcludes.end() != N.cudaExcludes.find(macroName)) { bReplace = false; } else { sl = sl_macro; } } if (bReplace) { updateCounters(found->second, name); Replacement Rep(*SM, sl, length, repName); FullSourceLoc fullSL(sl, *SM); insertReplacement(Rep, fullSL); } } else { updateCounters(found->second, name); } } else { std::string msg = "the following reference is not handled: '" + name + "' [function call]."; printHipifyMessage(*SM, sl, msg); } return true; } return false; } bool cudaLaunchKernel(const MatchFinder::MatchResult &Result) { StringRef refName = "cudaLaunchKernel"; if (const CUDAKernelCallExpr *launchKernel = Result.Nodes.getNodeAs<CUDAKernelCallExpr>(refName)) { SmallString<40> XStr; raw_svector_ostream OS(XStr); StringRef calleeName; const FunctionDecl *kernelDecl = launchKernel->getDirectCallee(); if (kernelDecl) { calleeName = kernelDecl->getName(); convertKernelDecl(kernelDecl, Result); } else { const Expr *e = launchKernel->getCallee(); if (const UnresolvedLookupExpr *ule = dyn_cast<UnresolvedLookupExpr>(e)) { calleeName = ule->getName().getAsIdentifierInfo()->getName(); owner->addMatcher(functionTemplateDecl(hasName(calleeName)) .bind("unresolvedTemplateName"), this); } } XStr.clear(); if (calleeName.find(',') != StringRef::npos) { SmallString<128> tmpData; calleeName = Twine("(" + calleeName + ")").toStringRef(tmpData); } OS << "hipLaunchKernelGGL(" << calleeName << ","; const CallExpr *config = launchKernel->getConfig(); DEBUG(dbgs() << "Kernel config arguments:" << "\n"); SourceManager *SM = Result.SourceManager; LangOptions DefaultLangOptions; for (unsigned argno = 0; argno < config->getNumArgs(); argno++) { const Expr *arg = config->getArg(argno); if (!isa<CXXDefaultArgExpr>(arg)) { const ParmVarDecl *pvd = config->getDirectCallee()->getParamDecl(argno); SourceLocation sl(arg->getLocStart()); SourceLocation el(arg->getLocEnd()); SourceLocation stop = Lexer::getLocForEndOfToken(el, 0, *SM, DefaultLangOptions); StringRef outs(SM->getCharacterData(sl), SM->getCharacterData(stop) - SM->getCharacterData(sl)); DEBUG(dbgs() << "args[ " << argno << "]" << outs << " <" << pvd->getType().getAsString() << ">\n"); if (pvd->getType().getAsString().compare("dim3") == 0) { OS << " dim3(" << outs << "),"; } else { OS << " " << outs << ","; } } else { OS << " 0,"; } } for (unsigned argno = 0; argno < launchKernel->getNumArgs(); argno++) { const Expr *arg = launchKernel->getArg(argno); SourceLocation sl(arg->getLocStart()); SourceLocation el(arg->getLocEnd()); SourceLocation stop = Lexer::getLocForEndOfToken(el, 0, *SM, DefaultLangOptions); std::string outs(SM->getCharacterData(sl), SM->getCharacterData(stop) - SM->getCharacterData(sl)); DEBUG(dbgs() << outs << "\n"); OS << " " << outs << ","; } XStr.pop_back(); OS << ")"; size_t length = SM->getCharacterData(Lexer::getLocForEndOfToken( launchKernel->getLocEnd(), 0, *SM, DefaultLangOptions)) - SM->getCharacterData(launchKernel->getLocStart()); Replacement Rep(*SM, launchKernel->getLocStart(), length, OS.str()); FullSourceLoc fullSL(launchKernel->getLocStart(), *SM); insertReplacement(Rep, fullSL); hipCounter counter = {"hipLaunchKernelGGL", CONV_KERN, API_RUNTIME}; updateCounters(counter, refName.str()); return true; } return false; } bool cudaBuiltin(const MatchFinder::MatchResult &Result) { if (const MemberExpr *threadIdx = Result.Nodes.getNodeAs<MemberExpr>("cudaBuiltin")) { if (const OpaqueValueExpr *refBase = dyn_cast<OpaqueValueExpr>(threadIdx->getBase())) { if (const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(refBase->getSourceExpr())) { SourceLocation sl = threadIdx->getLocStart(); SourceManager *SM = Result.SourceManager; StringRef name = declRef->getDecl()->getName(); StringRef memberName = threadIdx->getMemberDecl()->getName(); size_t pos = memberName.find_first_not_of("__fetch_builtin_"); memberName = memberName.slice(pos, memberName.size()); SmallString<128> tmpData; name = Twine(name + "." + memberName).toStringRef(tmpData); const auto found = N.cuda2hipRename.find(name); if (found != N.cuda2hipRename.end()) { updateCounters(found->second, name.str()); if (!found->second.unsupported) { StringRef repName = found->second.hipName; Replacement Rep(*SM, sl, name.size(), repName); FullSourceLoc fullSL(sl, *SM); insertReplacement(Rep, fullSL); } } else { std::string msg = "the following reference is not handled: '" + name.str() + "' [builtin]."; printHipifyMessage(*SM, sl, msg); } } } return true; } return false; } bool cudaEnumConstantRef(const MatchFinder::MatchResult &Result) { if (const DeclRefExpr *enumConstantRef = Result.Nodes.getNodeAs<DeclRefExpr>("cudaEnumConstantRef")) { StringRef name = enumConstantRef->getDecl()->getName(); SourceLocation sl = enumConstantRef->getLocStart(); SourceManager *SM = Result.SourceManager; const auto found = N.cuda2hipRename.find(name); if (found != N.cuda2hipRename.end()) { updateCounters(found->second, name.str()); if (!found->second.unsupported) { StringRef repName = found->second.hipName; Replacement Rep(*SM, sl, name.size(), repName); FullSourceLoc fullSL(sl, *SM); insertReplacement(Rep, fullSL); } } else { std::string msg = "the following reference is not handled: '" + name.str() + "' [enum constant ref]."; printHipifyMessage(*SM, sl, msg); } return true; } return false; } bool cudaEnumDecl(const MatchFinder::MatchResult &Result) { if (const VarDecl *enumDecl = Result.Nodes.getNodeAs<VarDecl>("cudaEnumDecl")) { std::string name = enumDecl->getType()->getAsTagDecl()->getNameAsString(); QualType QT = enumDecl->getType().getUnqualifiedType(); std::string name_unqualified = QT.getAsString(); if ((name_unqualified.find(' ') == std::string::npos && name.find(' ') == std::string::npos) || name.empty()) { name = name_unqualified; } // Workaround for enum VarDecl as param decl, declared with enum type specifier // Example: void func(enum cudaMemcpyKind kind); //------------------------------------------------- SourceManager *SM = Result.SourceManager; SourceLocation sl(enumDecl->getLocStart()); SourceLocation end(enumDecl->getLocEnd()); size_t repLength = SM->getCharacterData(end) - SM->getCharacterData(sl); StringRef sfull = StringRef(SM->getCharacterData(sl), repLength); size_t offset = sfull.find(name); if (offset > 0) { sl = sl.getLocWithOffset(offset); } //------------------------------------------------- const auto found = N.cuda2hipRename.find(name); if (found != N.cuda2hipRename.end()) { updateCounters(found->second, name); if (!found->second.unsupported) { StringRef repName = found->second.hipName; Replacement Rep(*SM, sl, name.size(), repName); FullSourceLoc fullSL(sl, *SM); insertReplacement(Rep, fullSL); } } else { std::string msg = "the following reference is not handled: '" + name + "' [enum constant decl]."; printHipifyMessage(*SM, sl, msg); } return true; } return false; } bool cudaEnumVarPtr(const MatchFinder::MatchResult &Result) { if (const VarDecl *enumVarPtr = Result.Nodes.getNodeAs<VarDecl>("cudaEnumVarPtr")) { const Type *t = enumVarPtr->getType().getTypePtrOrNull(); if (t) { QualType QT = t->getPointeeType(); std::string name = QT.getAsString(); QT = enumVarPtr->getType().getUnqualifiedType(); std::string name_unqualified = QT.getAsString(); if ((name_unqualified.find(' ') == std::string::npos && name.find(' ') == std::string::npos) || name.empty()) { name = name_unqualified; } // Workaround for enum VarDecl as param decl, declared with enum type specifier // Example: void func(enum cudaMemcpyKind kind); //------------------------------------------------- SourceManager *SM = Result.SourceManager; TypeLoc TL = enumVarPtr->getTypeSourceInfo()->getTypeLoc(); SourceLocation sl(TL.getUnqualifiedLoc().getLocStart()); SourceLocation end(TL.getUnqualifiedLoc().getLocEnd()); size_t repLength = SM->getCharacterData(end) - SM->getCharacterData(sl); StringRef sfull = StringRef(SM->getCharacterData(sl), repLength); size_t offset = sfull.find(name); if (offset > 0) { sl = sl.getLocWithOffset(offset); } //------------------------------------------------- const auto found = N.cuda2hipRename.find(name); if (found != N.cuda2hipRename.end()) { updateCounters(found->second, name); if (!found->second.unsupported) { StringRef repName = found->second.hipName; Replacement Rep(*SM, sl, name.size(), repName); FullSourceLoc fullSL(sl, *SM); insertReplacement(Rep, fullSL); } } else { std::string msg = "the following reference is not handled: '" + name + "' [enum var ptr]."; printHipifyMessage(*SM, sl, msg); } } return true; } return false; } bool cudaTypedefVar(const MatchFinder::MatchResult &Result) { if (const VarDecl *typedefVar = Result.Nodes.getNodeAs<VarDecl>("cudaTypedefVar")) { QualType QT = typedefVar->getType(); if (QT->isArrayType()) { QT = QT.getTypePtr()->getAsArrayTypeUnsafe()->getElementType(); } QT = QT.getUnqualifiedType(); std::string name = QT.getAsString(); SourceLocation sl = typedefVar->getLocStart(); SourceManager *SM = Result.SourceManager; const auto found = N.cuda2hipRename.find(name); if (found != N.cuda2hipRename.end()) { updateCounters(found->second, name); if (!found->second.unsupported) { StringRef repName = found->second.hipName; Replacement Rep(*SM, sl, name.size(), repName); FullSourceLoc fullSL(sl, *SM); insertReplacement(Rep, fullSL); } } else { std::string msg = "the following reference is not handled: '" + name + "' [typedef var]."; printHipifyMessage(*SM, sl, msg); } return true; } return false; } bool cudaTypedefVarPtr(const MatchFinder::MatchResult &Result) { if (const VarDecl *typedefVarPtr = Result.Nodes.getNodeAs<VarDecl>("cudaTypedefVarPtr")) { const Type *t = typedefVarPtr->getType().getTypePtrOrNull(); if (t) { SourceManager *SM = Result.SourceManager; TypeLoc TL = typedefVarPtr->getTypeSourceInfo()->getTypeLoc(); SourceLocation sl = TL.getUnqualifiedLoc().getLocStart(); QualType QT = t->getPointeeType(); QT = QT.getUnqualifiedType(); std::string name = QT.getAsString(); const auto found = N.cuda2hipRename.find(name); if (found != N.cuda2hipRename.end()) { updateCounters(found->second, name); if (!found->second.unsupported) { StringRef repName = found->second.hipName; Replacement Rep(*SM, sl, name.size(), repName); FullSourceLoc fullSL(sl, *SM); insertReplacement(Rep, fullSL); } } else { std::string msg = "the following reference is not handled: '" + name + "' [typedef var ptr]."; printHipifyMessage(*SM, sl, msg); } } return true; } return false; } bool cudaStructVar(const MatchFinder::MatchResult &Result) { if (const VarDecl *structVar = Result.Nodes.getNodeAs<VarDecl>("cudaStructVar")) { QualType QT = structVar->getType(); // ToDo: find case-studies with types other than Struct. if (QT->isStructureType()) { std::string name = QT.getTypePtr()->getAsStructureType()->getDecl()->getNameAsString(); TypeLoc TL = structVar->getTypeSourceInfo()->getTypeLoc(); SourceLocation sl = TL.getUnqualifiedLoc().getLocStart(); SourceManager *SM = Result.SourceManager; const auto found = N.cuda2hipRename.find(name); if (found != N.cuda2hipRename.end()) { updateCounters(found->second, name); if (!found->second.unsupported) { StringRef repName = found->second.hipName; Replacement Rep(*SM, sl, name.size(), repName); FullSourceLoc fullSL(sl, *SM); insertReplacement(Rep, fullSL); } } else { std::string msg = "the following reference is not handled: '" + name + "' [struct var]."; printHipifyMessage(*SM, sl, msg); } } return true; } return false; } bool cudaStructVarPtr(const MatchFinder::MatchResult &Result) { if (const VarDecl *structVarPtr = Result.Nodes.getNodeAs<VarDecl>("cudaStructVarPtr")) { const Type *t = structVarPtr->getType().getTypePtrOrNull(); if (t) { TypeLoc TL = structVarPtr->getTypeSourceInfo()->getTypeLoc(); SourceLocation sl = TL.getUnqualifiedLoc().getLocStart(); SourceManager *SM = Result.SourceManager; StringRef name = t->getPointeeCXXRecordDecl()->getName(); const auto found = N.cuda2hipRename.find(name); if (found != N.cuda2hipRename.end()) { updateCounters(found->second, name.str()); if (!found->second.unsupported) { StringRef repName = found->second.hipName; Replacement Rep(*SM, sl, name.size(), repName); FullSourceLoc fullSL(sl, *SM); insertReplacement(Rep, fullSL); } } else { std::string msg = "the following reference is not handled: '" + name.str() + "' [struct var ptr]."; printHipifyMessage(*SM, sl, msg); } } return true; } return false; } bool cudaStructSizeOf(const MatchFinder::MatchResult &Result) { if (const UnaryExprOrTypeTraitExpr *expr = Result.Nodes.getNodeAs<UnaryExprOrTypeTraitExpr>("cudaStructSizeOf")) { TypeSourceInfo *typeInfo = expr->getArgumentTypeInfo(); TypeLoc TL = typeInfo->getTypeLoc(); SourceLocation sl = TL.getUnqualifiedLoc().getLocStart(); SourceManager *SM = Result.SourceManager; QualType QT = typeInfo->getType().getUnqualifiedType(); const Type *type = QT.getTypePtr(); CXXRecordDecl *rec = type->getAsCXXRecordDecl(); if (!rec) { return false; } StringRef name = rec->getName(); const auto found = N.cuda2hipRename.find(name); if (found != N.cuda2hipRename.end()) { updateCounters(found->second, name.str()); if (!found->second.unsupported) { StringRef repName = found->second.hipName; Replacement Rep(*SM, sl, name.size(), repName); FullSourceLoc fullSL(sl, *SM); insertReplacement(Rep, fullSL); } } else { std::string msg = "the following reference is not handled: '" + name.str() + "' [struct sizeof]."; printHipifyMessage(*SM, sl, msg); } return true; } return false; } bool cudaNewOperatorDecl(const MatchFinder::MatchResult &Result) { if (const auto *newOperator = Result.Nodes.getNodeAs<CXXNewExpr>("cudaNewOperatorDecl")) { const Type *t = newOperator->getType().getTypePtrOrNull(); if (t) { SourceManager *SM = Result.SourceManager; TypeLoc TL = newOperator->getAllocatedTypeSourceInfo()->getTypeLoc(); SourceLocation sl = TL.getUnqualifiedLoc().getLocStart(); QualType QT = t->getPointeeType(); std::string name = QT.getAsString(); const auto found = N.cuda2hipRename.find(name); if (found != N.cuda2hipRename.end()) { updateCounters(found->second, name); if (!found->second.unsupported) { StringRef repName = found->second.hipName; Replacement Rep(*SM, sl, name.size(), repName); FullSourceLoc fullSL(sl, *SM); insertReplacement(Rep, fullSL); } } else { std::string msg = "the following reference is not handled: '" + name + "' [new operator]."; printHipifyMessage(*SM, sl, msg); } } } return false; } bool cudaFunctionReturn(const MatchFinder::MatchResult &Result) { if (const auto *ret = Result.Nodes.getNodeAs<FunctionDecl>("cudaFunctionReturn")) { QualType QT = ret->getReturnType(); SourceManager *SM = Result.SourceManager; SourceRange sr = ret->getReturnTypeSourceRange(); SourceLocation sl = sr.getBegin(); std::string name = QT.getAsString(); if (QT.getTypePtr()->isEnumeralType()) { name = QT.getTypePtr()->getAs<EnumType>()->getDecl()->getNameAsString(); } const auto found = N.cuda2hipRename.find(name); if (found != N.cuda2hipRename.end()) { updateCounters(found->second, name); if (!found->second.unsupported) { StringRef repName = found->second.hipName; Replacement Rep(*SM, sl, name.size(), repName); FullSourceLoc fullSL(sl, *SM); insertReplacement(Rep, fullSL); } } else { std::string msg = "the following reference is not handled: '" + name + "' [function return]."; printHipifyMessage(*SM, sl, msg); } } return false; } bool cudaSharedIncompleteArrayVar(const MatchFinder::MatchResult &Result) { StringRef refName = "cudaSharedIncompleteArrayVar"; if (const VarDecl *sharedVar = Result.Nodes.getNodeAs<VarDecl>(refName)) { // Example: extern __shared__ uint sRadix1[]; if (sharedVar->hasExternalFormalLinkage()) { QualType QT = sharedVar->getType(); std::string typeName; if (QT->isIncompleteArrayType()) { const ArrayType *AT = QT.getTypePtr()->getAsArrayTypeUnsafe(); QT = AT->getElementType(); if (QT.getTypePtr()->isBuiltinType()) { QT = QT.getCanonicalType(); const BuiltinType *BT = dyn_cast<BuiltinType>(QT); if (BT) { LangOptions LO; LO.CUDA = true; PrintingPolicy policy(LO); typeName = BT->getName(policy); } } else { typeName = QT.getAsString(); } } if (!typeName.empty()) { SourceLocation slStart = sharedVar->getLocStart(); SourceLocation slEnd = sharedVar->getLocEnd(); SourceManager *SM = Result.SourceManager; size_t repLength = SM->getCharacterData(slEnd) - SM->getCharacterData(slStart) + 1; std::string varName = sharedVar->getNameAsString(); std::string repName = "HIP_DYNAMIC_SHARED(" + typeName + ", " + varName + ")"; Replacement Rep(*SM, slStart, repLength, repName); FullSourceLoc fullSL(slStart, *SM); insertReplacement(Rep, fullSL); hipCounter counter = { "HIP_DYNAMIC_SHARED", CONV_MEM, API_RUNTIME }; updateCounters(counter, refName.str()); } } return true; } return false; } bool cudaParamDecl(const MatchFinder::MatchResult &Result) { if (const ParmVarDecl *paramDecl = Result.Nodes.getNodeAs<ParmVarDecl>("cudaParamDecl")) { QualType QT = paramDecl->getOriginalType().getUnqualifiedType(); std::string name = QT.getAsString(); const Type *t = QT.getTypePtr(); if (t->isStructureOrClassType()) { name = t->getAsCXXRecordDecl()->getName(); } TypeLoc TL = paramDecl->getTypeSourceInfo()->getTypeLoc(); SourceLocation sl = TL.getUnqualifiedLoc().getLocStart(); SourceManager *SM = Result.SourceManager; const auto found = N.cuda2hipRename.find(name); if (found != N.cuda2hipRename.end()) { updateCounters(found->second, name); if (!found->second.unsupported) { StringRef repName = found->second.hipName; Replacement Rep(*SM, sl, name.size(), repName); FullSourceLoc fullSL(sl, *SM); insertReplacement(Rep, fullSL); } } else { std::string msg = "the following reference is not handled: '" + name + "' [param decl]."; printHipifyMessage(*SM, sl, msg); } return true; } return false; } bool cudaParamDeclPtr(const MatchFinder::MatchResult &Result) { if (const ParmVarDecl *paramDeclPtr = Result.Nodes.getNodeAs<ParmVarDecl>("cudaParamDeclPtr")) { const Type *pt = paramDeclPtr->getType().getTypePtrOrNull(); if (pt) { TypeLoc TL = paramDeclPtr->getTypeSourceInfo()->getTypeLoc(); SourceLocation sl = TL.getUnqualifiedLoc().getLocStart(); SourceManager *SM = Result.SourceManager; QualType QT = pt->getPointeeType(); const Type *t = QT.getTypePtr(); StringRef name = t->isStructureOrClassType() ? t->getAsCXXRecordDecl()->getName() : StringRef(QT.getAsString()); const auto found = N.cuda2hipRename.find(name); if (found != N.cuda2hipRename.end()) { updateCounters(found->second, name.str()); if (!found->second.unsupported) { StringRef repName = found->second.hipName; Replacement Rep(*SM, sl, name.size(), repName); FullSourceLoc fullSL(sl, *SM); insertReplacement(Rep, fullSL); } } else { std::string msg = "the following reference is not handled: '" + name.str() + "' [param decl ptr]."; printHipifyMessage(*SM, sl, msg); } } return true; } return false; } bool unresolvedTemplateName(const MatchFinder::MatchResult &Result) { if (const FunctionTemplateDecl *templateDecl = Result.Nodes.getNodeAs<FunctionTemplateDecl>("unresolvedTemplateName")) { FunctionDecl *kernelDecl = templateDecl->getTemplatedDecl(); convertKernelDecl(kernelDecl, Result); return true; } return false; } bool stringLiteral(const MatchFinder::MatchResult &Result) { if (const StringLiteral *sLiteral = Result.Nodes.getNodeAs<StringLiteral>("stringLiteral")) { if (sLiteral->getCharByteWidth() == 1) { StringRef s = sLiteral->getString(); SourceManager *SM = Result.SourceManager; processString(s, *SM, sLiteral->getLocStart()); } return true; } return false; } public: Cuda2HipCallback(Replacements *Replace, ast_matchers::MatchFinder *parent, HipifyPPCallbacks *PPCallbacks, const std::string &mainFileName) : Cuda2Hip(Replace, mainFileName), owner(parent), PP(PPCallbacks) { PP->setMatch(this); } void run(const MatchFinder::MatchResult &Result) override { do { if (cudaCall(Result)) break; if (cudaBuiltin(Result)) break; if (cudaEnumConstantRef(Result)) break; if (cudaEnumDecl(Result)) break; if (cudaEnumVarPtr(Result)) break; if (cudaTypedefVar(Result)) break; if (cudaTypedefVarPtr(Result)) break; if (cudaStructVar(Result)) break; if (cudaStructVarPtr(Result)) break; if (cudaStructSizeOf(Result)) break; if (cudaParamDecl(Result)) break; if (cudaParamDeclPtr(Result)) break; if (cudaLaunchKernel(Result)) break; if (cudaNewOperatorDecl(Result)) break; if (cudaFunctionReturn(Result)) break; if (cudaSharedIncompleteArrayVar(Result)) break; if (stringLiteral(Result)) break; if (unresolvedTemplateName(Result)) break; break; } while (false); insertHipHeaders(PP, *Result.SourceManager); } private: ast_matchers::MatchFinder *owner; HipifyPPCallbacks *PP; }; void HipifyPPCallbacks::handleEndSource() { insertHipHeaders(Match, *_sm); } } // end anonymous namespace void addAllMatchers(ast_matchers::MatchFinder &Finder, Cuda2HipCallback *Callback) { Finder.addMatcher(callExpr(isExpansionInMainFile(), callee(functionDecl(matchesName("cu.*")))) .bind("cudaCall"), Callback); Finder.addMatcher(cudaKernelCallExpr(isExpansionInMainFile()).bind("cudaLaunchKernel"), Callback); Finder.addMatcher(memberExpr(isExpansionInMainFile(), hasObjectExpression(hasType(cxxRecordDecl( matchesName("__cuda_builtin_"))))) .bind("cudaBuiltin"), Callback); Finder.addMatcher(declRefExpr(isExpansionInMainFile(), to(enumConstantDecl( matchesName("cu.*|CU.*")))) .bind("cudaEnumConstantRef"), Callback); Finder.addMatcher(varDecl(isExpansionInMainFile(), hasType(enumDecl())) .bind("cudaEnumDecl"), Callback); Finder.addMatcher(varDecl(isExpansionInMainFile(), hasType(pointsTo(enumDecl( matchesName("cu.*|CU.*"))))) .bind("cudaEnumVarPtr"), Callback); Finder.addMatcher(varDecl(isExpansionInMainFile(), hasType(typedefDecl(matchesName("cu.*|CU.*")))) .bind("cudaTypedefVar"), Callback); // Array of elements of typedef type. Example: // cudaStream_t streams[2]; Finder.addMatcher(varDecl(isExpansionInMainFile(), hasType(arrayType(hasElementType(typedefType( hasDeclaration(typedefDecl(matchesName("cu.*|CU.*")))))))) .bind("cudaTypedefVar"), Callback); // Pointer to typedef type. Examples: // 1. // cudaEvent_t *event = NULL; // typedef __device_builtin__ struct CUevent_st *cudaEvent_t; // 2. // CUevent *event = NULL; // typedef struct CUevent_st *CUevent; Finder.addMatcher(varDecl(isExpansionInMainFile(), hasType(pointsTo(typedefDecl( matchesName("cu.*|CU.*"))))) .bind("cudaTypedefVarPtr"), Callback); Finder.addMatcher(varDecl(isExpansionInMainFile(), hasType(cxxRecordDecl(matchesName("cu.*|CU.*")))) .bind("cudaStructVar"), Callback); Finder.addMatcher(varDecl(isExpansionInMainFile(), hasType(pointsTo(cxxRecordDecl( matchesName("cu.*|CU.*"))))) .bind("cudaStructVarPtr"), Callback); Finder.addMatcher(parmVarDecl(isExpansionInMainFile(), hasType(namedDecl(matchesName("cu.*|CU.*")))) .bind("cudaParamDecl"), Callback); Finder.addMatcher(parmVarDecl(isExpansionInMainFile(), hasType(pointsTo(namedDecl( matchesName("cu.*|CU.*"))))) .bind("cudaParamDeclPtr"), Callback); Finder.addMatcher(expr(isExpansionInMainFile(), sizeOfExpr(hasArgumentOfType( recordType(hasDeclaration(cxxRecordDecl(matchesName("cu.*|CU.*"))))))) .bind("cudaStructSizeOf"), Callback); Finder.addMatcher(stringLiteral(isExpansionInMainFile()).bind("stringLiteral"), Callback); Finder.addMatcher(varDecl(isExpansionInMainFile(), allOf( hasAttr(attr::CUDAShared), hasType(incompleteArrayType()))) .bind("cudaSharedIncompleteArrayVar"), Callback); // Example: // CUjit_option *jitOptions = new CUjit_option[jitNumOptions]; // hipJitOption *jitOptions = new hipJitOption[jitNumOptions]; Finder.addMatcher(cxxNewExpr(isExpansionInMainFile(), hasType(pointsTo(namedDecl(matchesName("cu.*|CU.*"))))) .bind("cudaNewOperatorDecl"), Callback); // Examples: // 1. // cudaStream_t cuda_memcpy_stream(...) // 2. // template<typename System1, typename System2> cudaMemcpyKind cuda_memcpy_kind(...) Finder.addMatcher(functionDecl(isExpansionInMainFile(), returns(hasDeclaration(namedDecl(matchesName("cu.*|CU.*"))))) .bind("cudaFunctionReturn"), Callback); } int64_t printStats(const std::string &csvFile, const std::string &srcFile, HipifyPPCallbacks &PPCallbacks, Cuda2HipCallback &Callback, uint64_t replacedBytes, uint64_t totalBytes, unsigned totalLines, const std::chrono::steady_clock::time_point &start) { std::ofstream csv(csvFile, std::ios::app); int64_t sum = 0, sum_interm = 0; std::string str; const std::string hipify_info = "[HIPIFY] info: ", separator = ";"; for (int i = 0; i < CONV_LAST; i++) { sum += Callback.countReps[i] + PPCallbacks.countReps[i]; } int64_t sum_unsupported = 0; for (int i = 0; i < CONV_LAST; i++) { sum_unsupported += Callback.countRepsUnsupported[i] + PPCallbacks.countRepsUnsupported[i]; } if (sum > 0 || sum_unsupported > 0) { str = "file \'" + srcFile + "\' statistics:\n"; llvm::outs() << "\n" << hipify_info << str; csv << "\n" << str; str = "CONVERTED refs count"; llvm::outs() << " " << str << ": " << sum << "\n"; csv << "\n" << str << separator << sum << "\n"; str = "UNCONVERTED refs count"; llvm::outs() << " " << str << ": " << sum_unsupported << "\n"; csv << str << separator << sum_unsupported << "\n"; str = "CONVERSION %"; long conv = 100 - std::lround(double(sum_unsupported*100)/double(sum + sum_unsupported)); llvm::outs() << " " << str << ": " << conv << "%\n"; csv << str << separator << conv << "%\n"; str = "REPLACED bytes"; llvm::outs() << " " << str << ": " << replacedBytes << "\n"; csv << str << separator << replacedBytes << "\n"; str = "TOTAL bytes"; llvm::outs() << " " << str << ": " << totalBytes << "\n"; csv << str << separator << totalBytes << "\n"; str = "CHANGED lines of code"; unsigned changedLines = Callback.LOCs.size() + PPCallbacks.LOCs.size(); llvm::outs() << " " << str << ": " << changedLines << "\n"; csv << str << separator << changedLines << "\n"; str = "TOTAL lines of code"; llvm::outs() << " " << str << ": " << totalLines << "\n"; csv << str << separator << totalLines << "\n"; if (totalBytes > 0) { str = "CODE CHANGED (in bytes) %"; conv = std::lround(double(replacedBytes * 100) / double(totalBytes)); llvm::outs() << " " << str << ": " << conv << "%\n"; csv << str << separator << conv << "%\n"; } if (totalLines > 0) { str = "CODE CHANGED (in lines) %"; conv = std::lround(double(changedLines * 100) / double(totalLines)); llvm::outs() << " " << str << ": " << conv << "%\n"; csv << str << separator << conv << "%\n"; } typedef std::chrono::duration<double, std::milli> duration; duration elapsed = std::chrono::steady_clock::now() - start; str = "TIME ELAPSED s"; std::stringstream stream; stream << std::fixed << std::setprecision(2) << elapsed.count() / 1000; llvm::outs() << " " << str << ": " << stream.str() << "\n"; csv << str << separator << stream.str() << "\n"; } if (sum > 0) { llvm::outs() << hipify_info << "CONVERTED refs by type:\n"; csv << "\nCUDA ref type" << separator << "Count\n"; for (int i = 0; i < CONV_LAST; i++) { sum_interm = Callback.countReps[i] + PPCallbacks.countReps[i]; if (0 == sum_interm) { continue; } llvm::outs() << " " << counterNames[i] << ": " << sum_interm << "\n"; csv << counterNames[i] << separator << sum_interm << "\n"; } llvm::outs() << hipify_info << "CONVERTED refs by API:\n"; csv << "\nCUDA API" << separator << "Count\n"; for (int i = 0; i < API_LAST; i++) { llvm::outs() << " " << apiNames[i] << ": " << Callback.countApiReps[i] + PPCallbacks.countApiReps[i] << "\n"; csv << apiNames[i] << separator << Callback.countApiReps[i] + PPCallbacks.countApiReps[i] << "\n"; } for (const auto & it : PPCallbacks.cuda2hipConverted) { const auto found = Callback.cuda2hipConverted.find(it.first); if (found == Callback.cuda2hipConverted.end()) { Callback.cuda2hipConverted.insert(std::pair<std::string, uint64_t>(it.first, 1)); } else { found->second += it.second; } } llvm::outs() << hipify_info << "CONVERTED refs by names:\n"; csv << "\nCUDA ref name" << separator << "Count\n"; for (const auto & it : Callback.cuda2hipConverted) { llvm::outs() << " " << it.first << ": " << it.second << "\n"; csv << it.first << separator << it.second << "\n"; } } if (sum_unsupported > 0) { str = "UNCONVERTED refs by type:"; llvm::outs() << hipify_info << str << "\n"; csv << "\nUNCONVERTED CUDA ref type" << separator << "Count\n"; for (int i = 0; i < CONV_LAST; i++) { sum_interm = Callback.countRepsUnsupported[i] + PPCallbacks.countRepsUnsupported[i]; if (0 == sum_interm) { continue; } llvm::outs() << " " << counterNames[i] << ": " << sum_interm << "\n"; csv << counterNames[i] << separator << sum_interm << "\n"; } llvm::outs() << hipify_info << "UNCONVERTED refs by API:\n"; csv << "\nUNCONVERTED CUDA API" << separator << "Count\n"; for (int i = 0; i < API_LAST; i++) { llvm::outs() << " " << apiNames[i] << ": " << Callback.countApiRepsUnsupported[i] + PPCallbacks.countApiRepsUnsupported[i] << "\n"; csv << apiNames[i] << separator << Callback.countApiRepsUnsupported[i] + PPCallbacks.countApiRepsUnsupported[i] << "\n"; } for (const auto & it : PPCallbacks.cuda2hipUnconverted) { const auto found = Callback.cuda2hipUnconverted.find(it.first); if (found == Callback.cuda2hipUnconverted.end()) { Callback.cuda2hipUnconverted.insert(std::pair<std::string, uint64_t>(it.first, 1)); } else { found->second += it.second; } } llvm::outs() << hipify_info << "UNCONVERTED refs by names:\n"; csv << "\nUNCONVERTED CUDA ref name" << separator << "Count\n"; for (const auto & it : Callback.cuda2hipUnconverted) { llvm::outs() << " " << it.first << ": " << it.second << "\n"; csv << it.first << separator << it.second << "\n"; } } csv.close(); return sum; } void printAllStats(const std::string &csvFile, int64_t totalFiles, int64_t convertedFiles, uint64_t replacedBytes, uint64_t totalBytes, unsigned changedLines, unsigned totalLines, const std::chrono::steady_clock::time_point &start) { std::ofstream csv(csvFile, std::ios::app); int64_t sum = 0, sum_interm = 0; std::string str; const std::string hipify_info = "[HIPIFY] info: ", separator = ";"; for (int i = 0; i < CONV_LAST; i++) { sum += countRepsTotal[i]; } int64_t sum_unsupported = 0; for (int i = 0; i < CONV_LAST; i++) { sum_unsupported += countRepsTotalUnsupported[i]; } if (sum > 0 || sum_unsupported > 0) { str = "TOTAL statistics:\n"; llvm::outs() << "\n" << hipify_info << str; csv << "\n" << str; str = "CONVERTED files"; llvm::outs() << " " << str << ": " << convertedFiles << "\n"; csv << "\n" << str << separator << convertedFiles << "\n"; str = "PROCESSED files"; llvm::outs() << " " << str << ": " << totalFiles << "\n"; csv << str << separator << totalFiles << "\n"; str = "CONVERTED refs count"; llvm::outs() << " " << str << ": " << sum << "\n"; csv << str << separator << sum << "\n"; str = "UNCONVERTED refs count"; llvm::outs() << " " << str << ": " << sum_unsupported << "\n"; csv << str << separator << sum_unsupported << "\n"; str = "CONVERSION %"; long conv = 100 - std::lround(double(sum_unsupported * 100) / double(sum + sum_unsupported)); llvm::outs() << " " << str << ": " << conv << "%\n"; csv << str << separator << conv << "%\n"; str = "REPLACED bytes"; llvm::outs() << " " << str << ": " << replacedBytes << "\n"; csv << str << separator << replacedBytes << "\n"; str = "TOTAL bytes"; llvm::outs() << " " << str << ": " << totalBytes << "\n"; csv << str << separator << totalBytes << "\n"; str = "CHANGED lines of code"; llvm::outs() << " " << str << ": " << changedLines << "\n"; csv << str << separator << changedLines << "\n"; str = "TOTAL lines of code"; llvm::outs() << " " << str << ": " << totalLines << "\n"; csv << str << separator << totalLines << "\n"; if (totalBytes > 0) { str = "CODE CHANGED (in bytes) %"; conv = std::lround(double(replacedBytes * 100) / double(totalBytes)); llvm::outs() << " " << str << ": " << conv << "%\n"; csv << str << separator << conv << "%\n"; } if (totalLines > 0) { str = "CODE CHANGED (in lines) %"; conv = std::lround(double(changedLines * 100) / double(totalLines)); llvm::outs() << " " << str << ": " << conv << "%\n"; csv << str << separator << conv << "%\n"; } typedef std::chrono::duration<double, std::milli> duration; duration elapsed = std::chrono::steady_clock::now() - start; str = "TIME ELAPSED s"; std::stringstream stream; stream << std::fixed << std::setprecision(2) << elapsed.count() / 1000; llvm::outs() << " " << str << ": " << stream.str() << "\n"; csv << str << separator << stream.str() << "\n"; } if (sum > 0) { llvm::outs() << hipify_info << "CONVERTED refs by type:\n"; csv << "\nCUDA ref type" << separator << "Count\n"; for (int i = 0; i < CONV_LAST; i++) { sum_interm = countRepsTotal[i]; if (0 == sum_interm) { continue; } llvm::outs() << " " << counterNames[i] << ": " << sum_interm << "\n"; csv << counterNames[i] << separator << sum_interm << "\n"; } llvm::outs() << hipify_info << "CONVERTED refs by API:\n"; csv << "\nCUDA API" << separator << "Count\n"; for (int i = 0; i < API_LAST; i++) { llvm::outs() << " " << apiNames[i] << ": " << countApiRepsTotal[i] << "\n"; csv << apiNames[i] << separator << countApiRepsTotal[i] << "\n"; } llvm::outs() << hipify_info << "CONVERTED refs by names:\n"; csv << "\nCUDA ref name" << separator << "Count\n"; for (const auto & it : cuda2hipConvertedTotal) { llvm::outs() << " " << it.first << ": " << it.second << "\n"; csv << it.first << separator << it.second << "\n"; } } if (sum_unsupported > 0) { str = "UNCONVERTED refs by type:"; llvm::outs() << hipify_info << str << "\n"; csv << "\nUNCONVERTED CUDA ref type" << separator << "Count\n"; for (int i = 0; i < CONV_LAST; i++) { sum_interm = countRepsTotalUnsupported[i]; if (0 == sum_interm) { continue; } llvm::outs() << " " << counterNames[i] << ": " << sum_interm << "\n"; csv << counterNames[i] << separator << sum_interm << "\n"; } llvm::outs() << hipify_info << "UNCONVERTED refs by API:\n"; csv << "\nUNCONVERTED CUDA API" << separator << "Count\n"; for (int i = 0; i < API_LAST; i++) { llvm::outs() << " " << apiNames[i] << ": " << countApiRepsTotalUnsupported[i] << "\n"; csv << apiNames[i] << separator << countApiRepsTotalUnsupported[i] << "\n"; } llvm::outs() << hipify_info << "UNCONVERTED refs by names:\n"; csv << "\nUNCONVERTED CUDA ref name" << separator << "Count\n"; for (const auto & it : cuda2hipUnconvertedTotal) { llvm::outs() << " " << it.first << ": " << it.second << "\n"; csv << it.first << separator << it.second << "\n"; } } csv.close(); } int main(int argc, const char **argv) { auto start = std::chrono::steady_clock::now(); auto begin = start; #if (LLVM_VERSION_MAJOR >= 3) && (LLVM_VERSION_MINOR >= 9) llvm::sys::PrintStackTraceOnErrorSignal(StringRef()); #else llvm::sys::PrintStackTraceOnErrorSignal(); #endif CommonOptionsParser OptionsParser(argc, argv, ToolTemplateCategory, llvm::cl::OneOrMore); std::vector<std::string> fileSources = OptionsParser.getSourcePathList(); std::string dst = OutputFilename; if (!dst.empty() && fileSources.size() > 1) { llvm::errs() << "[HIPIFY] conflict: -o and multiple source files are specified.\n"; return 1; } if (NoOutput) { if (Inplace) { llvm::errs() << "[HIPIFY] conflict: both -no-output and -inplace options are specified.\n"; return 1; } if (!dst.empty()) { llvm::errs() << "[HIPIFY] conflict: both -no-output and -o options are specified.\n"; return 1; } } if (Examine) { NoOutput = PrintStats = true; } int Result = 0; std::string csv; if (!OutputStatsFilename.empty()) { csv = OutputStatsFilename; } else { csv = "hipify_stats.csv"; } size_t filesTranslated = fileSources.size(); uint64_t repBytesTotal = 0; uint64_t bytesTotal = 0; unsigned changedLinesTotal = 0; unsigned linesTotal = 0; if (PrintStats && filesTranslated > 1) { std::remove(csv.c_str()); } for (const auto & src : fileSources) { if (dst.empty()) { dst = src; if (!Inplace) { size_t pos = dst.rfind("."); if (pos != std::string::npos && pos + 1 < dst.size()) { dst = dst.substr(0, pos) + ".hip." + dst.substr(pos + 1, dst.size() - pos - 1); } else { dst += ".hip.cu"; } } } else { if (Inplace) { llvm::errs() << "[HIPIFY] conflict: both -o and -inplace options are specified.\n"; return 1; } dst += ".hip"; } // backup source file since tooling may change "inplace" if (!NoBackup || !Inplace) { std::ifstream source(src, std::ios::binary); std::ofstream dest(Inplace ? dst + ".prehip" : dst, std::ios::binary); dest << source.rdbuf(); source.close(); dest.close(); } RefactoringTool Tool(OptionsParser.getCompilations(), dst); ast_matchers::MatchFinder Finder; HipifyPPCallbacks PPCallbacks(&Tool.getReplacements(), src); Cuda2HipCallback Callback(&Tool.getReplacements(), &Finder, &PPCallbacks, src); addAllMatchers(Finder, &Callback); auto action = newFrontendActionFactory(&Finder, &PPCallbacks); std::vector<const char*> compilationStages; compilationStages.push_back("--cuda-host-only"); Tool.appendArgumentsAdjuster(getInsertArgumentAdjuster(compilationStages[0], ArgumentInsertPosition::BEGIN)); Tool.appendArgumentsAdjuster(getInsertArgumentAdjuster("-std=c++11")); #if defined(HIPIFY_CLANG_RES) Tool.appendArgumentsAdjuster(getInsertArgumentAdjuster("-resource-dir=" HIPIFY_CLANG_RES)); #endif Tool.appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster()); Result += Tool.run(action.get()); Tool.clearArgumentsAdjusters(); LangOptions DefaultLangOptions; IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts); DiagnosticsEngine Diagnostics(IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts, &DiagnosticPrinter, false); uint64_t repBytes = 0; uint64_t bytes = 0; unsigned lines = 0; SourceManager SM(Diagnostics, Tool.getFiles()); if (PrintStats) { DEBUG(dbgs() << "Replacements collected by the tool:\n"); for (const auto &r : Tool.getReplacements()) { DEBUG(dbgs() << r.toString() << "\n"); repBytes += r.getLength(); } std::ifstream src_file(dst, std::ios::binary | std::ios::ate); src_file.clear(); src_file.seekg(0); lines = std::count(std::istreambuf_iterator<char>(src_file), std::istreambuf_iterator<char>(), '\n'); bytes = src_file.tellg(); } Rewriter Rewrite(SM, DefaultLangOptions); if (!Tool.applyAllReplacements(Rewrite)) { DEBUG(dbgs() << "Skipped some replacements.\n"); } if (!NoOutput) { Result += Rewrite.overwriteChangedFiles(); } if (!Inplace && !NoOutput) { size_t pos = dst.rfind("."); if (pos != std::string::npos) { rename(dst.c_str(), dst.substr(0, pos).c_str()); } } if (NoOutput) { remove(dst.c_str()); } if (PrintStats) { if (fileSources.size() == 1) { if (OutputStatsFilename.empty()) { csv = dst + ".csv"; } std::remove(csv.c_str()); } if (0 == printStats(csv, src, PPCallbacks, Callback, repBytes, bytes, lines, start)) { filesTranslated--; } start = std::chrono::steady_clock::now(); repBytesTotal += repBytes; bytesTotal += bytes; changedLinesTotal += PPCallbacks.LOCs.size() + Callback.LOCs.size(); linesTotal += lines; } dst.clear(); } if (PrintStats && fileSources.size() > 1) { printAllStats(csv, fileSources.size(), filesTranslated, repBytesTotal, bytesTotal, changedLinesTotal, linesTotal, begin); } return Result; }
89.017106
262
0.655481
[ "object", "vector" ]
55456c6f966e2f7e3458c2ef74fd5e97b2f79bcd
15,711
cpp
C++
render/samples/Texture/src/App.cpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
17
2019-02-12T14:40:06.000Z
2021-12-21T12:54:17.000Z
render/samples/Texture/src/App.cpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
null
null
null
render/samples/Texture/src/App.cpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
2
2019-02-21T10:07:42.000Z
2020-05-08T19:49:10.000Z
#include "App.hpp" #include <storm/log/LogHandler.hpp> #include <storm/window/Window.hpp> #include <storm/image/Image.hpp> #include <storm/render/core/Instance.hpp> #include <storm/render/core/PhysicalDevice.hpp> #include <storm/render/core/PhysicalDeviceInfo.hpp> #include <storm/render/core/WindowSurface.hpp> #include <storm/render/resource/Sampler.hpp> #include <storm/render/resource/Texture.hpp> using namespace storm; using log::operator""_module; using namespace std::literals; struct MeshVertex { core::Vector2f position; core::Vector2f uv; }; static constexpr auto TEXTURE_WIDTH = 250.f; static constexpr auto TEXTURE_HEIGHT = 216.f; static constexpr auto WINDOW_TITLE = "StormKit Texture Example"; static constexpr auto LOG_MODULE = "Texture"_module; static constexpr auto MESH_VERTICES = std::array { MeshVertex { .position = { 0.f, 0.f }, .uv = { 0.f, 0.f } }, MeshVertex { .position = { 0.f, TEXTURE_HEIGHT }, .uv = { 0.f, 1.f } }, MeshVertex { .position = { TEXTURE_WIDTH, 0.f }, .uv = { 1.f, 0.f } }, MeshVertex { .position = { TEXTURE_WIDTH, TEXTURE_HEIGHT }, .uv = { 1.f, 1.f } }, }; static constexpr auto MESH_VERTEX_BUFFER_SIZE = sizeof(MeshVertex) * std::size(MESH_VERTICES); static constexpr auto MESH_VERTEX_BINDING_DESCRIPTIONS = std::array { render::VertexBindingDescription { .binding = 0, .stride = sizeof(MeshVertex) } }; static constexpr auto MESH_VERTEX_ATTRIBUTE_DESCRIPTIONS = std::array { render::VertexInputAttributeDescription { .location = 0, .binding = 0, .format = render::Format::Float2, .offset = offsetof(MeshVertex, position) }, render::VertexInputAttributeDescription { .location = 1, .binding = 0, .format = render::Format::Float2, .offset = offsetof(MeshVertex, uv) } }; static constexpr auto CAMERA_BUFFER_SIZE = sizeof(Camera); static constexpr auto MODEL_BUFFER_SIZE = sizeof(core::Matrix); static const auto VERTEX_SHADER_DATA = std::vector<core::UInt32> { #include "vertex.vert.spv.hpp" }; static const auto FRAGMENT_SHADER_DATA = std::vector<core::UInt32> { #include "fragment.frag.spv.hpp" }; App::App() { doInitWindow(); doInitBaseRenderObjects(); doInitMeshRenderObjects(); } App::~App() { log::LogHandler::ilog(LOG_MODULE, "Cleaning"); m_device->waitIdle(); m_frame_datas.clear(); } void App::run([[maybe_unused]] const int argc, [[maybe_unused]] const char **argv) { while (m_window->isOpen()) { auto event = window::Event {}; while (m_window->pollEvent(event)) { if (event.type == window::EventType::Closed) m_window->close(); else if (event.type == window::EventType::KeyReleased && event.key_event.key == window::Key::Escape) m_window->close(); } auto frame = m_surface->acquireNextFrame(); auto &frame_data = m_frame_datas[frame.texture_index]; frame_data.commandbuffer.submit(core::makeConstObserverArray(frame.texture_available), core::makeConstObserverArray(frame.render_finished), frame.in_flight); m_surface->present(frame); } } void App::doInitWindow() { // First we create the window const auto window_style = window::WindowStyle::Close; m_window = std::make_unique<window::Window>(WINDOW_TITLE, window::VideoSettings { .size = { 800u, 600u } }, window_style); } void App::doInitBaseRenderObjects() { // We create an instance and initialize device on best available GPU m_instance = std::make_unique<render::Instance>(); log::LogHandler::ilog(LOG_MODULE, "Render backend successfully initialized"); log::LogHandler::ilog(LOG_MODULE, "Using StormKit {}.{}.{} {} {}", STORMKIT_MAJOR_VERSION, STORMKIT_MINOR_VERSION, STORMKIT_PATCH_VERSION, STORMKIT_GIT_BRANCH, STORMKIT_GIT_COMMIT_HASH); m_surface = m_instance->createWindowSurfacePtr(*m_window); const auto &physical_device = m_instance->pickPhysicalDevice(*m_surface); const auto &physical_device_info = physical_device.info(); log::LogHandler::ilog(LOG_MODULE, "Using physical device {}", physical_device_info.device_name); log::LogHandler::ilog(LOG_MODULE, "{}", physical_device_info); m_device = physical_device.createLogicalDevicePtr(); log::LogHandler::ilog(LOG_MODULE, "Device successfully created"); // We initialize the surface (it will acquire images and init all surface default parameters m_surface->initialize(*m_device); log::LogHandler::ilog(LOG_MODULE, "Device successfully initialized with {} image(s)", m_surface->textureCount()); m_queue = core::makeConstObserver(m_device->graphicsQueue()); for (const auto &texture : m_surface->textures()) m_surface_views.emplace_back(texture.createView()); } void App::doInitMeshRenderObjects() { const auto surface_extent = core::Extentf { m_surface->extent() }; const auto buffering_count = m_surface->bufferingCount(); // The window center const auto quad_position = core::Vector3f { surface_extent.width / 2.f - TEXTURE_WIDTH / 2.f, surface_extent.height / 2.f - TEXTURE_HEIGHT / 2.f, 0.f }; m_camera = { .projection = core::ortho(0.f, surface_extent.width, surface_extent.height, 0.f), .view = core::Matrix { 1.f } }; m_model = core::translate(core::Matrix { 1.f }, quad_position); // We load our triangle shaders m_vertex_shader = m_device->createShaderPtr(VERTEX_SHADER_DATA, render::ShaderStage::Vertex); log::LogHandler::ilog(LOG_MODULE, "Vertex shader loaded"); m_fragment_shader = m_device->createShaderPtr(FRAGMENT_SHADER_DATA, render::ShaderStage::Fragment); log::LogHandler::ilog(LOG_MODULE, "Fragment shader loaded"); // We need to indicate to the pipeline how we pass data to the shader, first we need two // descriptor layout, on per frame and on per mesh m_per_frame_descriptor_set_layout = m_device->createDescriptorSetLayoutPtr(); m_per_frame_descriptor_set_layout->addBinding({ .binding = 0, .type = render::DescriptorType::Uniform_Buffer, .stages = render::ShaderStage::Vertex, .descriptor_count = 1 }); m_per_frame_descriptor_set_layout->bake(); m_per_mesh_descriptor_set_layout = m_device->createDescriptorSetLayoutPtr(); m_per_mesh_descriptor_set_layout->addBinding({ .binding = 0, .type = render::DescriptorType::Uniform_Buffer, .stages = render::ShaderStage::Vertex, .descriptor_count = 1 }); m_per_mesh_descriptor_set_layout->addBinding( { .binding = 1, .type = render::DescriptorType::Combined_Texture_Sampler, .stages = render::ShaderStage::Fragment, .descriptor_count = 1 }); m_per_mesh_descriptor_set_layout->bake(); // Next we need two pool (per frame and per mesh) to allocate descriptors m_per_frame_descriptor_pool = m_device->createDescriptorPoolPtr({ { render::DescriptorType::Uniform_Buffer, 1 } }, 1); m_per_mesh_descriptor_pool = m_device->createDescriptorPoolPtr({ { render::DescriptorType::Uniform_Buffer, 1 }, { render::DescriptorType::Combined_Texture_Sampler, 1 } }, 2); // We need to create a render pass, the render pass describe how the framebuffer will look auto description = render::RenderPassDescription { .attachments = { { .format = m_surface->pixelFormat() } }, .subpasses = { { .bind_point = render::PipelineBindPoint::Graphics, .attachment_refs = { { .attachment_id = 0u } } } } }; m_render_pass = m_device->createRenderPassPtr(std::move(description)); log::LogHandler::ilog(LOG_MODULE, "Renderpass successfully created"); // We create a pipeline, the pipeline describe all the fixed function parameters and the shaders // wich will be bound m_pipeline = m_device->createGraphicsPipelinePtr(); const auto state = render::GraphicsPipelineState { .input_assembly_state = { .topology = render::PrimitiveTopology::Triangle_Strip }, .viewport_state = { .viewports = { render::Viewport { .position = { 0.f, 0.f }, .extent = surface_extent, .depth = { 0.f, 1.f } } }, .scissors = { render::Scissor { .offset = { 0, 0 }, .extent = surface_extent } } }, .color_blend_state = { .attachments = { { .blend_enable = true, .src_color_blend_factor = render::BlendFactor::Src_Alpha, .dst_color_blend_factor = render::BlendFactor::One_Minus_Src_Alpha, .src_alpha_blend_factor = render::BlendFactor::Src_Alpha, .dst_alpha_blend_factor = render::BlendFactor::One_Minus_Src_Alpha, .alpha_blend_operation = render::BlendOperation::Add } } }, .shader_state = { .shaders = core::makeConstObserverArray(m_vertex_shader, m_fragment_shader) }, .vertex_input_state = { .binding_descriptions = MESH_VERTEX_BINDING_DESCRIPTIONS, .input_attribute_descriptions = MESH_VERTEX_ATTRIBUTE_DESCRIPTIONS }, .layout = { .descriptor_set_layouts = core::makeConstObserverArray(m_per_frame_descriptor_set_layout, m_per_mesh_descriptor_set_layout) } }; m_pipeline->setState(std::move(state)); m_pipeline->setRenderPass(*m_render_pass); m_pipeline->build(); log::LogHandler::ilog(LOG_MODULE, "engine pipeline successfully created"); // We create our mesh data, we only need a vertex buffer m_vertex_buffer = m_device->createVertexBufferPtr(MESH_VERTEX_BUFFER_SIZE); m_vertex_buffer->upload<MeshVertex>(MESH_VERTICES); log::LogHandler::ilog(LOG_MODULE, "{} bytes uploaded to vertex buffer", MESH_VERTEX_BUFFER_SIZE); // We allocate the set and prepare data m_camera_set = m_per_frame_descriptor_pool->allocateDescriptorSetPtr(*m_per_frame_descriptor_set_layout); m_camera_buffer = m_device->createUniformBufferPtr(CAMERA_BUFFER_SIZE); m_camera_buffer->upload<Camera>({ &m_camera, 1 }); m_camera_buffer->flush(0, CAMERA_BUFFER_SIZE); log::LogHandler::ilog(LOG_MODULE, "{} bytes uploaded to camera buffer", CAMERA_BUFFER_SIZE); m_camera_set->update(render::DescriptorStaticArray<1> { render::BufferDescriptor { .binding = 0, .buffer = core::makeConstObserver(m_camera_buffer), .range = CAMERA_BUFFER_SIZE } }); m_mesh_data_set = m_per_mesh_descriptor_pool->allocateDescriptorSetPtr(*m_per_mesh_descriptor_set_layout); m_model_buffer = m_device->createUniformBufferPtr(MODEL_BUFFER_SIZE); m_model_buffer->upload<core::Matrix>({ &m_model, 1 }); m_model_buffer->flush(0, MODEL_BUFFER_SIZE); log::LogHandler::ilog(LOG_MODULE, "{} bytes uploaded to model buffer", MODEL_BUFFER_SIZE); m_image = std::make_unique<image::Image>( image::Image { EXAMPLES_DATA_DIR "textures/texture.png", image::Image::Codec::PNG } .toFormat(image::Image::Format::RGBA8_UNorm) .flipY()); m_texture = m_device->createTexturePtr(m_image->extent()); m_texture->loadFromImage(*m_image); m_texture_view = m_texture->createViewPtr(); m_sampler = m_device->createSamplerPtr(); m_mesh_data_set->update(render::DescriptorStaticArray<2> { render::BufferDescriptor { .binding = 0, .buffer = core::makeConstObserver(m_model_buffer), .range = MODEL_BUFFER_SIZE }, render::TextureDescriptor { .binding = 1, .layout = render::TextureLayout::Shader_Read_Only_Optimal, .texture_view = core::makeConstObserver(m_texture_view), .sampler = core::makeConstObserver(m_sampler) } }); // Finally we create per frame data, we need a commandbuffer and a framebuffer by frame to avoid // waiting the GPU m_frame_datas.reserve(buffering_count); for (auto i = 0u; i < buffering_count; ++i) { const auto &texture_view = m_surface_views[i]; auto frame = Frame { .framebuffer = m_render_pass->createFramebuffer(surface_extent, { core::makeConstObserver(texture_view) }), .commandbuffer = m_queue->createCommandBuffer() }; frame.commandbuffer.begin(); frame.commandbuffer.beginRenderPass(*m_render_pass, frame.framebuffer); frame.commandbuffer.bindGraphicsPipeline(*m_pipeline); frame.commandbuffer.bindDescriptorSets(*m_pipeline, { *m_camera_set, *m_mesh_data_set }); frame.commandbuffer.bindVertexBuffers({ *m_vertex_buffer }, { 0 }); frame.commandbuffer.draw(gsl::narrow_cast<core::Int32>(std::size(MESH_VERTICES))); frame.commandbuffer.endRenderPass(); frame.commandbuffer.end(); frame.commandbuffer.build(); m_frame_datas.emplace_back(std::move(frame)); log::LogHandler::ilog(LOG_MODULE, "Frame {} CommandBuffer and Framebuffer successfully created", i); } }
49.87619
101
0.570556
[ "mesh", "render", "vector", "model" ]
554682db290f1024ea6e2f9a21c9ee15c0d3311c
3,065
cpp
C++
Player.cpp
leguims/Quoridor
1134d35a0943beda365baa33a991916fce859bda
[ "Apache-2.0" ]
1
2018-07-05T07:59:09.000Z
2018-07-05T07:59:09.000Z
Player.cpp
leguims/Quoridor
1134d35a0943beda365baa33a991916fce859bda
[ "Apache-2.0" ]
1
2018-07-05T08:10:51.000Z
2018-07-06T22:38:45.000Z
Player.cpp
leguims/Quoridor
1134d35a0943beda365baa33a991916fce859bda
[ "Apache-2.0" ]
null
null
null
#include "Player.h" #include <vector> #include <string> #include <iostream> #include <random> Player::Player(const PlayerName & name, const Color & color, const BoardPosition & startPosition) : name_{ name }, color_{ color }, walls_{ 10 }, startPosition_{ startPosition }, arrivalPosition_{} { } Move Player::getNextMove(const unsigned int round, const Board &board, const std::vector<PawnPosition>& pawns, const std::vector<WallPosition>& walls) const { // https://quoridorstrats.files.wordpress.com/2014/09/game-full-with-notation1.png // Only legal moves. std::vector<std::string> move_list{ "e2", "e8", "e3", "e7", "e4", "e6", "e3h", "g6v", "e5", "e4", "e6", "d4", "c3h", "a3h", "e7", "e7h", "d6v", "d4v" }; if ((2 * round) > move_list.size()) return Move(); else return startPosition() == BoardPosition("e1") ? Move(move_list[(round - 1) * 2]) : Move(move_list[(round - 1) * 2 + 1]); } Move IA_linear::getNextMove(const unsigned int round, const Board & board, const std::vector<PawnPosition>& pawns, const std::vector<WallPosition>& walls) const { if (round == 1) std::cout << name() << " is playing his first move with 'IA_linear'." << std::endl; if ((2 * round) > move_list_.size()) return Move(); else return startPosition() == BoardPosition("e1") ? Move(move_list_[(round - 1) * 2]) : Move(move_list_[(round - 1) * 2 + 1]); } Move IA_random_pawn::getNextMove(const unsigned int round, const Board & board, const std::vector<PawnPosition>& pawns, const std::vector<WallPosition>& walls) const { std::random_device rd; //Will be used to obtain a seed for the random number engine std::mt19937_64 gen(rd()); //Standard mersenne_twister_engine seeded with rd() std::uniform_int_distribution<int> dis(1, 5); // 5 moves max for pawn auto random = dis(gen); while (random > pawns.size()) random = dis(gen); //std::cout << random << " "; return pawns[random - 1]; } Move IA_random_wall_pawn::getNextMove(const unsigned int round, const Board & board, const std::vector<PawnPosition>& pawns, const std::vector<WallPosition>& walls) const { std::random_device rd; //Will be used to obtain a seed for the random number engine std::mt19937_64 gen(rd()); //Standard mersenne_twister_engine seeded with rd() std::uniform_int_distribution<int> dis_5(1, 5); // 5 moves max for pawn std::uniform_int_distribution<int> dis_128(1, 128); // 5 moves max for pawn std::bernoulli_distribution dis_bool(0.5); // Bool 50% true if (dis_bool(gen) || walls.empty()) { auto random = dis_5(gen); while (random > pawns.size()) random = dis_5(gen); //std::cout << random << " "; return pawns[random - 1]; } else { auto random = dis_128(gen); while (random > walls.size()) random = dis_128(gen); //std::cout << random << " "; return walls[random - 1]; } }
36.488095
170
0.620881
[ "vector" ]
554743b39162c093154164970e4a3c49325e2897
1,071
hpp
C++
src/pushButton.hpp
NickCis/nodeQt
689c084cce0fd3570daeb531ecb5807ae6d377e0
[ "Unlicense" ]
2
2018-09-29T07:50:06.000Z
2020-03-18T21:25:44.000Z
src/pushButton.hpp
NickCis/nodeQt
689c084cce0fd3570daeb531ecb5807ae6d377e0
[ "Unlicense" ]
null
null
null
src/pushButton.hpp
NickCis/nodeQt
689c084cce0fd3570daeb531ecb5807ae6d377e0
[ "Unlicense" ]
null
null
null
#ifndef PUSHBUTTON_HPP #define PUSHBUTTON_HPP #include <node/v8.h> #include <node/node.h> #include <QPushButton> #include "Widget.hpp" #include "QtAction.hpp" //TODO: sacar stdio.h #include <stdio.h> class PushButton : public node::ObjectWrap { public: static v8::Persistent<v8::FunctionTemplate> constructor; static void Init(v8::Handle<v8::Object> target); //static Handle<Value> GetOnClick(Local<String> name, const AccessorInfo& info); //static void SetOnClick(Local<String> name, Local<Value> value, const AccessorInfo& info); protected: PushButton(QString label); static v8::Handle<v8::Value> New(const v8::Arguments& args); static v8::Handle<v8::Value> Label(const v8::Arguments& args); static v8::Handle<v8::Value> resize(const v8::Arguments& args); static v8::Handle<v8::Value> show(const v8::Arguments& args); static v8::Handle<v8::Value> Callback(const v8::Arguments& args); // Your own object variables here QString ButtonLabel; QPushButton* qwidget; ActionSlot *qaCallback; //Persistent<Function> onClick; }; #endif
26.775
93
0.730159
[ "object" ]
555d3208f190467a4bebfbaa7a7d822cb0d7a414
814
cpp
C++
Sid's Levels/Level - 3/Arrays/Rain.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
14
2021-08-22T18:21:14.000Z
2022-03-08T12:04:23.000Z
Sid's Levels/Level - 3/Arrays/Rain.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
1
2021-10-17T18:47:17.000Z
2021-10-17T18:47:17.000Z
Sid's Levels/Level - 3/Arrays/Rain.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
5
2021-09-01T08:21:12.000Z
2022-03-09T12:13:39.000Z
class Solution { public: int trap(vector<int>& height) { //OM GAN GANAPATHAYE NAMO NAMAH //JAI SHRI RAM //JAI BAJRANGBALI //AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA vector<int> left(height.size()), right(height.size()); int maxLeft = INT_MIN, maxRight = INT_MIN; for(int i = 0; i < height.size(); i++) { maxRight = max(maxRight, height[i]); right[i] = maxRight; } for(int i = height.size() - 1; i >= 0; i--) { maxLeft = max(maxLeft, height[i]); left[i] = maxLeft; } int sum = 0; for(int i = 0; i < height.size(); i++) { sum += (min(left[i], right[i]) - height[i]); } return sum; } };
29.071429
73
0.479115
[ "vector" ]
556a44c5a232f43f4c5e4fed557b4fe3f33a0740
2,963
hpp
C++
include/paddyutils/functions/getIntersection.hpp
paddy74/paddyutils
e2be1cbee56fffbb225588b391d4efac2a287a1c
[ "MIT" ]
null
null
null
include/paddyutils/functions/getIntersection.hpp
paddy74/paddyutils
e2be1cbee56fffbb225588b391d4efac2a287a1c
[ "MIT" ]
null
null
null
include/paddyutils/functions/getIntersection.hpp
paddy74/paddyutils
e2be1cbee56fffbb225588b391d4efac2a287a1c
[ "MIT" ]
null
null
null
#pragma once #include <unordered_set> namespace paddyutils { /** * @brief Get the intersecting terms of two sets * * @tparam T * @param a * @param b * @return std::list<T> */ template <typename T> std::set<T> getIntersection(std::set<T> const & a, std::set<T> const & b) { std::set<T> interLst; std::set_intersection( a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(interLst)); return interLst; } /** * @brief Get the intersecting terms of two lists * * @tparam T * @param a * @param b * @return std::list<T> */ template <typename T> std::list<T> getIntersection(std::list<T> const & a, std::list<T> const & b) { std::list<T> interLst; std::set_intersection( a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(interLst)); return interLst; } /** * @brief Get the intersecting terms of two vectors * * @tparam T * @param a * @param b * @return std::list<T> */ template <typename T> std::vector<T> getIntersection( std::vector<T> const & a, std::vector<T> const & b) { std::vector<T> interLst; std::set_intersection( a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(interLst)); return interLst; } /** * @brief Get the intersection of two `unordered_set` instances. * * @tparam KEY_T * @tparam VALUE_T * @param a The maps whose values are kept. * @param b * @return std::unordered_map<KEY_T, VALUE_T> */ template <typename T> std::unordered_set<T> getIntersection( std::unordered_set<T> const & a, std::unordered_set<T> const & b) { std::unordered_set<T> interSet; // Loop over smaller set to improve speed if (a.size() <= b.size()) { for (auto const & item : a) { if (b.find(item) != b.end()) interSet.insert(item); } } else // a.size() > b.size() { for (auto const & item : b) { if (a.find(item) != a.end()) interSet.insert(item); } } return interSet; } /** * @brief Get the intersecting keys of two maps whose values are of `mapA`. * * @tparam KEY_T * @tparam VALUE_T * @param a The maps whose values are kept. * @param b * @return std::unordered_map<KEY_T, VALUE_T> */ template <typename KEY_T, typename VALUE_T> std::unordered_map<KEY_T, VALUE_T> getKeyIntersection( std::unordered_map<KEY_T, VALUE_T> const & a, std::unordered_map<KEY_T, VALUE_T> const & b) { std::unordered_map<KEY_T, VALUE_T> interMap; // Loop over smaller map to improve speed if (a.size() <= b.size()) { for (auto const & pair : a) { if (b.find(pair.first) != b.end()) interMap.insert(pair); } } else // a.size > b.size() { for (auto const & pair : b) { auto const & apairItr = a.find(pair.first); if (apairItr != a.end()) interMap.insert(*apairItr); } } return interMap; } } // namespace paddyutils
21.786765
78
0.591968
[ "vector" ]
556a675fab1de24a03e167b24647fb5d293a8a69
10,813
cpp
C++
Simulink/RS232_SynchB_Buffer.cpp
LeonardoDaga/RS232_For_Matlab
ec4a2c0d9b229d9ac561493d15b4508227d712de
[ "MIT" ]
null
null
null
Simulink/RS232_SynchB_Buffer.cpp
LeonardoDaga/RS232_For_Matlab
ec4a2c0d9b229d9ac561493d15b4508227d712de
[ "MIT" ]
null
null
null
Simulink/RS232_SynchB_Buffer.cpp
LeonardoDaga/RS232_For_Matlab
ec4a2c0d9b229d9ac561493d15b4508227d712de
[ "MIT" ]
1
2021-11-30T19:54:09.000Z
2021-11-30T19:54:09.000Z
/* * File : RS232_Read.c */ #define S_FUNCTION_NAME RS232_SynchB_Buffer #define S_FUNCTION_LEVEL 2 #include <stdio.h> #include <ctype.h> #include "simstruc.h" #include "RS232.h" // INPUT ARGUMENTS #define NUMBER_OF_ARGS 5 #define SYNCHSIZE (int)(*mxGetPr(ssGetSFcnParam(S,0))) #define MASK ssGetSFcnParam(S,1) #define VALUE ssGetSFcnParam(S,2) #define SAMP_TIME_ARG ssGetSFcnParam(S,3) #define STEP_ALLOC (int)(*mxGetPr(ssGetSFcnParam(S,4))) #define TMPSIZE 128 #define NO_P_WORKS 2 #define NO_I_WORKS 3 static char_T msg[256]; static void ResizeBuffer(SimStruct *S, T_Buffer* buffer, int i_NeedSize); /***************************************************************************** +FUNCTION: GetHexParam /****************************************************************************/ int GetHexParam(const struct mxArray_tag * vParam, int* i_Value) { char* c_String=(char *)calloc(mxGetN(vParam)+1,sizeof(char)); if (c_String==NULL) { printf("Error in RS232_CheckB_Buffer (mdlStart.1) : could not allocate memory\n"); return 0; } mxGetString(vParam, c_String, (int)mxGetN(vParam)+1); int iscan = sscanf(c_String, "%x", i_Value); free(c_String); return iscan; } /***************************************************************************** +FUNCTION: GetHexParam /****************************************************************************/ bool checkSynch(char* c_P, int i_Mask, int i_Value, int i_SyncSize) { int val = 0; char* c_val = (char*)&val; for (int i=0; i<i_SyncSize; i++) { c_val[i] = c_P[i_SyncSize - i - 1]; } return ((val & i_Mask) == i_Value); } /***************************************************************************** +FUNCTION: mdlInitializeSizes +DESCRIPTION: Setup sizes of the various vectors. +PARAMETERS: SimStruct *S +RETURN: static void *******************************************************************************/ static void mdlInitializeSizes(SimStruct *S) { #ifdef MATLAB_MEX_FILE ssSetNumSFcnParams(S, NUMBER_OF_ARGS); if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) { sprintf(msg, "Error in RS232_SynchB_Buffer: \n"); sprintf(&msg[strlen(msg)], "Wrong number of input arguments passed.\n%d arguments are expected\n", NUMBER_OF_ARGS); ssSetErrorStatus(S,msg); return; } #endif if (STEP_ALLOC <= 16) { sprintf(msg, "Error in RS232_SynchB_Buffer: \n"); sprintf(&msg[strlen(msg)], "Allocation step too small: %d.\n", STEP_ALLOC); ssSetErrorStatus(S,msg); return; } // Input port if (!ssSetNumInputPorts(S, 3)) return; ssSetInputPortWidth(S, 0, 1); /* Width of input port 1 (index 0) */ ssSetInputPortWidth(S, 1, 1); /* Width of input port 2 (index 1) */ ssSetInputPortWidth(S, 2, 1); /* Width of input port 3 (index 2) */ ssSetInputPortDirectFeedThrough(S, 0, 1); ssSetInputPortDirectFeedThrough(S, 1, 1); ssSetInputPortDirectFeedThrough(S, 2, 1); ssSetInputPortDataType(S, 0, SS_INT32); /* Type of input PORT 1 (index 0) */ ssSetInputPortDataType(S, 1, SS_INT32); /* Type of input PORT 2 (index 0) */ ssSetInputPortDataType(S, 2, SS_POINTER); /* Type of input PORT 3 (index 0) */ // Output port if (!ssSetNumOutputPorts(S, 2)) return; ssSetOutputPortWidth(S, 0, 1); /* Width of output port 1 (index 0) */ ssSetOutputPortWidth(S, 1, 1); /* Width of output port 2 (index 1) */ ssSetOutputPortDataType(S, 0, SS_INT32); /* Type of output PORT 1 (index 0) */ ssSetOutputPortDataType(S, 1, SS_INT32); /* Type of output PORT 2 (index 0) */ ssSetNumSampleTimes(S, 0); ssSetNumPWork(S, NO_P_WORKS); /* number of pointer work vector elements*/ ssSetNumIWork(S, NO_I_WORKS); /* number of integer work vector elements*/ } /***************************************************************************** +FUNCTION: mdlInitializeSampleTimes +DESCRIPTION: Specifiy that we inherit our sample time from the driving block. +PARAMETERS: SimStruct *S +RETURN: static void *******************************************************************************/ static void mdlInitializeSampleTimes(SimStruct *S) { ssSetSampleTime(S, 0, mxGetPr(SAMP_TIME_ARG)[0]); if (mxGetN((SAMP_TIME_ARG))==1) { ssSetOffsetTime(S, 0, 0.0); } else { ssSetOffsetTime(S, 0, mxGetPr(SAMP_TIME_ARG)[1]); } } /***************************************************************************** +FUNCTION: mdlStart +DESCRIPTION: Routine used to initialize data +PARAMETERS: SimStruct *S +RETURN: static void *******************************************************************************/ #define MDL_START /* Change to #undef to remove function */ static void mdlStart(SimStruct *S) { int i_rdStat = 0; ssSetIWorkValue(S,0,i_rdStat); // Set the first element int i_Mask = 0; int i_Value = 0; if (!GetHexParam(MASK, &i_Mask)) { printf("Error in RS232_CheckB_Buffer (mdlStart.1) : Mask parameter is not valid\n"); return; } if (!GetHexParam(VALUE, &i_Value)) { printf("Error in RS232_CheckB_Buffer (mdlStart.2) : Value parameter is not valid\n"); return; } ssSetIWorkValue(S,1,i_Mask); ssSetIWorkValue(S,2,i_Value); } /***************************************************************************** +FUNCTION: mdlOutputs +DESCRIPTION: +PARAMETERS: SimStruct *S int_T tid +RETURN: static void *******************************************************************************/ static void mdlOutputs(SimStruct *S, int_T tid) { int *y0 = (int*)ssGetOutputPortSignal(S,0); int *y1 = (int*)ssGetOutputPortSignal(S,1); int **u0 = (int**)ssGetInputPortSignalPtrs(S,0); int **u1 = (int**)ssGetInputPortSignalPtrs(S,1); int **u2 = (int**)ssGetInputPortSignalPtrs(S,2); int i_len; int i_outStat = 0; Addr64 hPort = *u0; int i_inStat = (int)(*u1[0]); T_Buffer* buff = (T_Buffer*)Addr64(*u2).addr; y0[0] = hPort.iaddr[0]; y0[1] = hPort.iaddr[1]; y1[0] = i_outStat; // Synch handle validity if (hPort.addr == 0) { printf("RS232 Synch Binary Buffer error: choosen COM-port not initialized\n"); return; } // Get the previous internal read status int i_rdStat = ssGetIWorkValue(S,0); // If this condition is valid, the previous block (a read or setup block) // completed its work or this block, after activated, didn't received // all the expected character. Then skip the actual operation. if ((!i_inStat)&&(!i_rdStat)) return; // Synching the actual length of the queue i_len = RS232InQueue(hPort); // i_len = 128; // printf( "Queue length: %d\n" , i_len); ResizeBuffer(S, buff, i_len + buff->i_Fill); if (buff->c_Buffer == NULL) { printf("RS232 Synch Binary Buffer error: error managing buffers\n"); buff->i_Fill = 0; i_rdStat = 0; ssSetIWorkValue(S,0,i_rdStat); return; } if (i_len != 0) { /* FILE* stream; if( (stream = fopen( "clust.dat", "r" )) == NULL ) { printf( "The file 'data' was not opened\n" ); return; } else { printf( "The file 'data' was opened\n" ); } fread(&buff->c_Buffer[buff->i_Fill], sizeof(char), i_len, stream); fclose(stream); */ RS232Read(hPort, &buff->c_Buffer[buff->i_Fill], i_len); buff->i_Read += i_len; } buff->i_Fill += i_len; buff->c_Buffer[buff->i_Fill]=0; // Null-terminate the buffer int i_SyncSize = SYNCHSIZE; // printf("SyncSize = %d\n", i_SyncSize); // If the total message is greater then the message terminator, look for the // terminator if (buff->i_Fill >= i_SyncSize) { int i_Mask = ssGetIWorkValue(S,1); int i_Value = ssGetIWorkValue(S,2); char* c_P = buff->c_Buffer; char* c_End = buff->c_Buffer + buff->i_Fill - SYNCHSIZE; //printf("totSize = %d\n", (int)totSize); //printf("c_P = %x\n", (int)c_P); while (c_P < c_End) { if (checkSynch(c_P, i_Mask, i_Value, i_SyncSize)) { // if synchro found i_outStat = 1; // Read done i_rdStat = 0; // End looking for a synch ssSetIWorkValue(S,0,i_rdStat); break; } c_P++; } int totSize = c_P - buff->c_Buffer; // Calculate the remaining qty of chars and // update the buff->i_Fill: buff->i_Fill = buff->i_Fill - totSize; memmove(buff->c_Buffer, // Start of the buffer buff->c_Buffer + totSize, // The end of last message buff->i_Fill); // the remaining qty of chars buff->c_Buffer[buff->i_Fill]=0; // Null-terminate the buffer } else { i_outStat = 0; // Read not done //printf("readb buf short: i_outStat = %d, %d, |%s| \n", hPort, i_outStat, buff->c_Buffer); i_rdStat = 1; // Still looking for a synch ssSetIWorkValue(S,0,i_rdStat); } y0[0] = hPort.iaddr[0]; y0[1] = hPort.iaddr[1]; y1[0] = i_outStat; } /***************************************************************************** +FUNCTION: ResizeBuffer *******************************************************************************/ static void ResizeBuffer(SimStruct *S, T_Buffer* buffer, int i_NeedSize) { if (buffer == NULL) return; if (i_NeedSize >= buffer->i_Size) { if (buffer->c_Buffer == NULL) { buffer->c_Buffer = (char*)malloc(STEP_ALLOC); buffer->i_Size = STEP_ALLOC; printf("Allocated memory\n"); if (buffer->c_Buffer == NULL) { printf("RS232 Synch Binary Buffer error: could not allocate memory\n"); buffer->i_Size = 0; } } else { int newSize = buffer->i_Size; while (newSize <= i_NeedSize) { newSize += STEP_ALLOC; } buffer->c_Buffer = (char*)realloc(buffer->c_Buffer, newSize); buffer->i_Size = newSize; printf("Required size is %d\n", i_NeedSize); printf("Allocated size is %d\n", buffer->i_Size); if (buffer->c_Buffer == NULL) { printf("RS232 Synch Binary Buffer error: could not allocate memory\n"); buffer->i_Size = 0; } } } else if ((i_NeedSize < buffer->i_Size - STEP_ALLOC)&&(i_NeedSize > 0)) { buffer->c_Buffer = (char*)realloc(buffer->c_Buffer, buffer->i_Size - STEP_ALLOC); buffer->i_Size -= STEP_ALLOC; printf("Required size is %d\n", i_NeedSize); printf("Reduced size is %d\n", buffer->i_Size); if (buffer->c_Buffer == NULL) { printf("RS232 Synch Binary Buffer error: could not allocate memory\n"); buffer->i_Size = 0; } } else { } } /***************************************************************************** +FUNCTION: mdlTerminate +DESCRIPTION: No termination needed, but we are required to have this routine. Function to perform housekeeping at execution termination +PARAMETERS: SimStruct *S +RETURN: static void *******************************************************************************/ static void mdlTerminate(SimStruct *S) { } #ifdef MATLAB_MEX_FILE /* Is this file being compiled as a MEX-file? */ #include "simulink.c" /* MEX-file interface mechanism */ #else #include "cg_sfun.h" /* Code generation registration function */ #endif
26.055422
93
0.592712
[ "vector" ]
556fe5270ef874343fc6e3ee5ee9623741885072
65,952
cpp
C++
AprilTagTrackers/Tracker.cpp
funnbot/April-Tag-VR-FullBody-Tracker
8720cab49f5241446d9383134fd9507b70c431c0
[ "MIT" ]
null
null
null
AprilTagTrackers/Tracker.cpp
funnbot/April-Tag-VR-FullBody-Tracker
8720cab49f5241446d9383134fd9507b70c431c0
[ "MIT" ]
null
null
null
AprilTagTrackers/Tracker.cpp
funnbot/April-Tag-VR-FullBody-Tracker
8720cab49f5241446d9383134fd9507b70c431c0
[ "MIT" ]
null
null
null
#include "Tracker.h" #include "AprilTagWrapper.h" #include "Connection.h" #include "Debug.h" #include "Helpers.h" #include <opencv2/aruco.hpp> #include <opencv2/aruco/charuco.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/videoio.hpp> #include <algorithm> #include <array> #include <exception> #include <iostream> #include <mutex> #include <random> #include <sstream> #include <vector> #ifdef ATT_ENABLE_PS3EYE #include "PSEyeVideoCapture.h" #endif namespace { // Create a grid in front of the camera for visualization purposes. std::vector<std::vector<cv::Point3f>> createXyGridLines( const int gridSizeX, // Number of units from leftmost to rightmost line. const int gridSizeY, // Number of units from top to bottom line. const int gridSubdivision, // Number of segments per line. const float z) // Z-coord of grid. { std::vector<std::vector<cv::Point3f>> gridLines(gridSizeX + gridSizeY + 2); for (int i = 0; i <= gridSizeX; ++i) { auto& verticalLine = gridLines[i]; verticalLine.reserve(gridSizeY * gridSubdivision + 1); const float x = float(i) - float(gridSizeX) * 0.5f; for (int j = 0; j <= gridSizeY * gridSubdivision; ++j) { const float y = float(j) / float(gridSubdivision) - float(gridSizeY) * 0.5f; verticalLine.push_back(cv::Point3f(x, y, z)); } } for (int i = 0; i <= gridSizeY; ++i) { auto& horizontalLine = gridLines[gridSizeX + 1 + i]; horizontalLine.reserve(gridSizeX * gridSubdivision + 1); const float y = float(i) - float(gridSizeY) * 0.5f; for (int j = 0; j <= gridSizeX * gridSubdivision; ++j) { const float x = float(j) / float(gridSubdivision) - float(gridSizeX) * 0.5f; horizontalLine.push_back(cv::Point3f(x, y, z)); } } return gridLines; } void previewCalibration( cv::Mat& drawImg, const cv::Mat1d& cameraMatrix, const cv::Mat1d& distCoeffs, const cv::Mat1d& stdDeviationsIntrinsics, const std::vector<double>& perViewErrors, const std::vector<std::vector<cv::Point2f>>& allCharucoCorners, const std::vector<std::vector<int>>& allCharucoIds) { if (!cameraMatrix.empty()) { const float gridZ = 10.0f; const float width = static_cast<float>(drawImg.cols); const float height = static_cast<float>(drawImg.rows); const float fx = static_cast<float>(cameraMatrix(0, 0)); const float fy = static_cast<float>(cameraMatrix(1, 1)); const int gridSizeX = static_cast<int>(std::round(gridZ * width / fx)); const int gridSizeY = static_cast<int>(std::round(gridZ * height / fy)); const std::vector<std::vector<cv::Point3f>> gridLinesInCamera = createXyGridLines(gridSizeX, gridSizeY, 10, gridZ); std::vector<cv::Point2f> gridLineInImage; // Will be populated by cv::projectPoints. // The generator is static to avoid starting over with the same seed every time. static std::default_random_engine generator; std::normal_distribution<double> unitGaussianDistribution(0.0, 1.0); cv::Mat1d sampleCameraMatrix = cameraMatrix.clone(); cv::Mat1d sampleDistCoeffs = distCoeffs.clone(); if (!stdDeviationsIntrinsics.empty()) { ATASSERT("", sampleDistCoeffs.total() + 4 <= stdDeviationsIntrinsics.total()); sampleCameraMatrix(0, 0) += unitGaussianDistribution(generator) * stdDeviationsIntrinsics(0); sampleCameraMatrix(1, 1) += unitGaussianDistribution(generator) * stdDeviationsIntrinsics(1); sampleCameraMatrix(0, 2) += unitGaussianDistribution(generator) * stdDeviationsIntrinsics(2); sampleCameraMatrix(1, 2) += unitGaussianDistribution(generator) * stdDeviationsIntrinsics(3); for (int i = 0; i < sampleDistCoeffs.total(); ++i) { sampleDistCoeffs(i) += unitGaussianDistribution(generator) * stdDeviationsIntrinsics(i + 4); } } for (const auto& gridLineInCamera : gridLinesInCamera) { cv::projectPoints(gridLineInCamera, cv::Vec3f::zeros(), cv::Vec3f::zeros(), sampleCameraMatrix, sampleDistCoeffs, gridLineInImage); for (size_t j = 1; j < gridLineInImage.size(); ++j) { const auto p1 = gridLineInImage[j - 1]; const auto p2 = gridLineInImage[j]; cv::line(drawImg, p1, p2, cv::Scalar(127, 127, 127), 2, cv::LineTypes::LINE_AA); } } } if (allCharucoCorners.size() > 0) { // Draw all corners that we have so far cv::Mat colorsFromErrors; if (!perViewErrors.empty()) { cv::Mat(perViewErrors).convertTo(colorsFromErrors, CV_8UC1, 255.0, 0.0); cv::applyColorMap(colorsFromErrors, colorsFromErrors, cv::COLORMAP_VIRIDIS); } for (int i = 0; i < allCharucoCorners.size(); ++i) { const auto& charucoCorners = allCharucoCorners[i]; cv::Scalar color(200, 100, 0); if (colorsFromErrors.total() > i) { color = colorsFromErrors.at<cv::Vec3b>(i); } for (const auto& point : charucoCorners) { cv::circle(drawImg, point, 4, color, cv::FILLED); } } } } inline void previewCalibration(cv::Mat& drawImg, const CalibrationConfig& calibConfig) { previewCalibration( drawImg, calibConfig.camMat, calibConfig.distCoeffs, calibConfig.stdDeviationsIntrinsics, calibConfig.perViewErrors, calibConfig.allCharucoCorners, calibConfig.allCharucoIds); } } // namespace Tracker::Tracker(UserConfig& _userConfig, CalibrationConfig& _calibConfig, ArucoConfig& _arucoConfig, const Localization& _lc) : connection(std::make_unique<Connection>(_userConfig)), user_config(_userConfig), calib_config(_calibConfig), aruco_config(_arucoConfig), lc(_lc) { if (!calib_config.trackers.empty()) { trackers = calib_config.trackers; trackersCalibrated = true; } SetWorldTransform(user_config.manualCalib.GetAsReal()); } void Tracker::StartCamera(std::string id, int apiPreference) { if (cameraRunning) { cameraRunning = false; mainThreadRunning = false; // cameraThread.join(); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); return; } if (id.length() <= 2) // if camera address is a single character, try to open webcam { int i = std::stoi(id); // convert to int #if OS_LINUX // On Linux cv::VideoCapture does not work when GStreamer backend is used and // camera is set to MJPG pixel format. As a work around we manually setup the // GStreamer pipeline with suitable decoding before feeding the stream into // application. if ((apiPreference == cv::CAP_ANY) || (apiPreference == cv::CAP_GSTREAMER)) { std::stringstream ss; ss << "v4l2src device=/dev/video" << id << " ! image/jpeg"; if (user_config.camWidth != 0) ss << ",width=" << user_config.camWidth; if (user_config.camHeight != 0) ss << ",height=" << user_config.camHeight; ss << ",framerate=" << user_config.camFps << "/1"; ss << " ! jpegdec ! video/x-raw,format=I420 ! videoconvert ! appsink"; cap = cv::VideoCapture(ss.str(), apiPreference); } else #endif #if ATT_ENABLE_PS3EYE if (apiPreference == 9100) { cap = PSEyeVideoCapture(i); } else #endif { cap = cv::VideoCapture(i, apiPreference); } } else { // if address is longer, we try to open it as an ip address cap = cv::VideoCapture(id, apiPreference); } if (!cap.isOpened()) { gui->ShowPopup(lc.TRACKER_CAMERA_START_ERROR, PopupStyle::Error); return; } // On Linux and when GStreamer backend is used we already setup the camera pixel format, // width, height and FPS above when the GStreamer pipeline was created. #if OS_LINUX if ((apiPreference != cv::CAP_ANY) && (apiPreference != cv::CAP_GSTREAMER)) #endif { // cap.set(cv::CAP_PROP_FOURCC, cv::VideoWriter::fourcc('m', 'j', 'p', 'g')); // cap.set(cv::CAP_PROP_FOURCC, cv::VideoWriter::fourcc('M', 'J', 'P', 'G')); if (user_config.camWidth != 0) cap.set(cv::CAP_PROP_FRAME_WIDTH, user_config.camWidth); if (user_config.camHeight != 0) cap.set(cv::CAP_PROP_FRAME_HEIGHT, user_config.camHeight); cap.set(cv::CAP_PROP_FPS, user_config.camFps); } if (user_config.cameraSettings) cap.set(cv::CAP_PROP_SETTINGS, 1); if (user_config.settingsParameters) { cap.set(cv::CAP_PROP_AUTOFOCUS, 0); cap.set(cv::CAP_PROP_AUTO_EXPOSURE, user_config.cameraAutoexposure); cap.set(cv::CAP_PROP_EXPOSURE, user_config.cameraExposure); cap.set(cv::CAP_PROP_GAIN, user_config.cameraGain); } double codec = 0x47504A4D; // code by FPaul. Should use MJPEG codec to enable fast framerates. cap.set(cv::CAP_PROP_FOURCC, codec); cameraRunning = true; cameraThread = std::thread(&Tracker::CameraLoop, this); cameraThread.detach(); } void Tracker::StartCamera() { StartCamera(user_config.cameraAddr, user_config.cameraApiPreference); } void Tracker::CameraLoop() { bool rotate = false; int rotateFlag = -1; bool mirror = false; if (user_config.rotateCl >= 0) { rotate = true; rotateFlag = user_config.rotateCl; } if (user_config.mirrorCam) { mirror = true; } cv::Mat img; cv::Mat drawImg; double fps = 0; auto last_preview_time = std::chrono::steady_clock::now(); last_frame_time = std::chrono::steady_clock::now(); bool frame_visible = false; gui->SetStatus(true, StatusItem::Camera); while (cameraRunning) { if (!cap.read(img) || img.empty()) { gui->ShowPopup(lc.TRACKER_CAMERA_ERROR, PopupStyle::Error); cameraRunning = false; break; } auto curtime = std::chrono::steady_clock::now(); fps = 0.95 * fps + 0.05 / std::chrono::duration<double>(curtime - last_frame_time).count(); last_frame_time = curtime; if (rotate) { cv::rotate(img, img, rotateFlag); } if (mirror) { cv::flip(img, img, 1); } // Ensure that preview isnt shown more than 60 times per second. // In some cases opencv will return a solid color image without any blocking delay (unlike a camera locked to a framerate), // and we would just be drawing fps text on nothing. double timeSinceLast = std::chrono::duration<double>(curtime - last_preview_time).count(); if (timeSinceLast > 0.015) { if (gui->IsPreviewVisible(PreviewId::Camera)) { last_preview_time = std::chrono::steady_clock::now(); img.copyTo(drawImg); cv::putText(drawImg, std::to_string(static_cast<int>(std::ceil(fps))), cv::Point(10, 60), cv::FONT_HERSHEY_SIMPLEX, 2, cv::Scalar(0, 255, 0), 2); std::string resolution = std::to_string(img.cols) + "x" + std::to_string(img.rows); cv::putText(drawImg, resolution, cv::Point(10, 120), cv::FONT_HERSHEY_SIMPLEX, 2, cv::Scalar(0, 255, 0), 2); if (previewCameraCalibration) previewCalibration(drawImg, calib_config); gui->UpdatePreview(drawImg, PreviewId::Camera); } } { std::lock_guard<std::mutex> lock(cameraImageMutex); // Swap avoids copying the pixel buffer. It only swaps pointers and metadata. // The pixel buffer from cameraImage can be reused if the size and format matches. cv::swap(img, cameraImage); // TODO: does opencv really care if img.read is called on the wrong size of matrix? if (img.size() != cameraImage.size() || img.flags != cameraImage.flags) { img.release(); } imageReady = true; } if (connection->PollQuitEvent()) mainThreadRunning = false; HandleConnectionErrors(); } cap.release(); gui->SetStatus(false, StatusItem::Camera); } void Tracker::CopyFreshCameraImageTo(cv::Mat& image) { /// TODO: replace with std::condition_variable // Sleep happens between each iteration when the mutex is not locked. for (;; std::this_thread::sleep_for(std::chrono::milliseconds(1))) { std::lock_guard<std::mutex> lock(cameraImageMutex); if (imageReady) { imageReady = false; // Swap metadata and pointers to pixel buffers. cv::swap(image, cameraImage); // We don't want to overwrite shared data so release the image unless we are the only user of it. if (!(cameraImage.u && cameraImage.u->refcount == 1)) { cameraImage.release(); } return; } } } void Tracker::StartCameraCalib() { if (mainThreadRunning) { mainThreadRunning = false; return; } if (!cameraRunning) { gui->ShowPopup(lc.TRACKER_CAMERA_NOTRUNNING, PopupStyle::Error); mainThreadRunning = false; return; } mainThreadRunning = true; if (!user_config.chessboardCalib) { mainThread = std::thread(&Tracker::CalibrateCameraCharuco, this); } else { mainThread = std::thread(&Tracker::CalibrateCamera, this); } mainThread.detach(); } /// function to calibrate our camera void Tracker::CalibrateCameraCharuco() { cv::Mat image; cv::Mat gray; cv::Mat drawImg; cv::Ptr<cv::aruco::Dictionary> dictionary = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_4X4_50); cv::Ptr<cv::aruco::DetectorParameters> params = cv::aruco::DetectorParameters::create(); // generate and show our charuco board that will be used for calibration cv::Ptr<cv::aruco::CharucoBoard> board = cv::aruco::CharucoBoard::create(8, 7, 0.04f, 0.02f, dictionary); cv::Mat boardImage; // set our detectors marker border bits to 1 since thats what charuco uses params->markerBorderBits = 1; // int framesSinceLast = -2 * user_config.camFps; auto timeOfLast = std::chrono::steady_clock::now(); bool promptSaveCalib = false; gui->ShowPrompt(lc.TRACKER_CAMERA_CALIBRATION_INSTRUCTIONS, [&](bool pressedOk) { promptSaveCalib = pressedOk; mainThreadRunning = false; }); cv::Mat cameraMatrix, distCoeffs, R, T; cv::Mat1d stdDeviationsIntrinsics, stdDeviationsExtrinsics; std::vector<double> perViewErrors; std::vector<std::vector<cv::Point2f>> allCharucoCorners; std::vector<std::vector<int>> allCharucoIds; cv::Mat outImg; std::vector<int> markerIds; std::vector<std::vector<cv::Point2f>> markerCorners; std::vector<std::vector<cv::Point2f>> rejectedCorners; auto preview = gui->CreatePreviewControl(); int picsTaken = 0; while (mainThreadRunning && cameraRunning) { CopyFreshCameraImageTo(image); int cols, rows; if (image.cols > image.rows) { cols = image.cols * drawImgSize / image.rows; rows = drawImgSize; } else { cols = drawImgSize; rows = image.rows * drawImgSize / image.cols; } image.copyTo(drawImg); cv::putText(drawImg, std::to_string(picsTaken), cv::Point(10, 30), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(255, 255, 255)); previewCalibration( drawImg, cameraMatrix, distCoeffs, stdDeviationsIntrinsics, perViewErrors, allCharucoCorners, allCharucoIds); // check the highest per view error and remove it if its higher than 1px. if (perViewErrors.size() > 10) { double maxPerViewError = 0; int maxPerViewErrorIdx = 0; for (int i = 0; i < perViewErrors.size(); i++) { if (perViewErrors[i] > maxPerViewError) { maxPerViewError = perViewErrors[i]; maxPerViewErrorIdx = i; } } if (maxPerViewError > 1) { perViewErrors.erase(perViewErrors.begin() + maxPerViewErrorIdx); allCharucoCorners.erase(allCharucoCorners.begin() + maxPerViewErrorIdx); allCharucoIds.erase(allCharucoIds.begin() + maxPerViewErrorIdx); // recalibrate camera without the problematic frame cv::aruco::calibrateCameraCharuco(allCharucoCorners, allCharucoIds, board, cv::Size(image.rows, image.cols), cameraMatrix, distCoeffs, R, T, stdDeviationsIntrinsics, stdDeviationsExtrinsics, perViewErrors, cv::CALIB_USE_LU); picsTaken--; } } cvtColor(image, gray, cv::COLOR_BGR2GRAY); cv::aruco::detectMarkers(gray, dictionary, markerCorners, markerIds, params, rejectedCorners); // TODO: If markers are detected, the image gets updated, and then the calibration timer below // captures another image, in the time before the opencv loop updates the preview on screen, // then the masked out tags will still be visible, it probably won't effect much though. for (const auto& corners : markerCorners) { ATASSERT("A square has four corners.", corners.size() == 4); const std::array<cv::Point, 4> points = {corners[0], corners[1], corners[2], corners[3]}; // much faster than fillPoly, and we know they will be convex cv::fillConvexPoly(drawImg, points.data(), points.size(), cv::Scalar::all(255)); } cv::resize(drawImg, outImg, cv::Size(cols, rows)); preview.Update(outImg); // if more than one second has passed since last calibration image, add current frame to calibration images // framesSinceLast++; if (std::chrono::duration<double>(std::chrono::steady_clock::now() - timeOfLast).count() > 1) { // framesSinceLast = 0; timeOfLast = std::chrono::steady_clock::now(); // if any button was pressed // detect our markers cv::aruco::refineDetectedMarkers(gray, board, markerCorners, markerIds, rejectedCorners); if (markerIds.size() > 0) { // if markers were found, try to add calibration data std::vector<cv::Point2f> charucoCorners; std::vector<int> charucoIds; // using data from aruco detection we refine the search of chessboard corners for higher accuracy cv::aruco::interpolateCornersCharuco(markerCorners, markerIds, gray, board, charucoCorners, charucoIds); if (charucoIds.size() > 15) { // if corners were found, we draw them // cv::aruco::drawDetectedCornersCharuco(drawImg, charucoCorners, charucoIds); // we then add our corners to the array allCharucoCorners.push_back(charucoCorners); allCharucoIds.push_back(charucoIds); picsTaken++; if (picsTaken >= 3) { try { // Calibrate camera using our data cv::aruco::calibrateCameraCharuco(allCharucoCorners, allCharucoIds, board, cv::Size(image.rows, image.cols), cameraMatrix, distCoeffs, R, T, stdDeviationsIntrinsics, stdDeviationsExtrinsics, perViewErrors, cv::CALIB_USE_LU); } catch (const cv::Exception& e) { ATERROR("cv::aruco::calibrateCameraCharuco exception: " << e.what()); } size_t curI = perViewErrors.size(); } } } } } mainThreadRunning = false; if (promptSaveCalib) { if (cameraMatrix.empty()) { gui->ShowPopup(lc.TRACKER_CAMERA_CALIBRATION_NOTDONE, PopupStyle::Warning); } else { // some checks of the camera calibration values. The thresholds should be adjusted to prevent any false negatives // // this was before bad frames were being removed, and should no longer be necessary and is commented out since it caused too many false negatives /* double avgPerViewError = 0; double maxPerViewError = 0; for (int i = 0; i < perViewErrors.size(); i++) { avgPerViewError += perViewErrors[i]; if (perViewErrors[i] > maxPerViewError) maxPerViewError = perViewErrors[i]; } avgPerViewError /= perViewErrors.size(); if (avgPerViewError > 0.5) //a big reprojection error indicates that calibration wasnt done properly { wxMessageDialog dial(NULL, wxT("WARNING:\nThe avarage reprojection error is over 0.5 pixel. This usualy indicates a bad calibration."), wxT("Warning"), wxOK | wxICON_ERROR); dial.ShowModal(); } if (maxPerViewError > 10) //having one reprojection error very high indicates that one frame had missdetections { wxMessageDialog dial(NULL, wxT("WARNING:\nOne or more reprojection errors are over 10 pixels. This usualy indicates something went wrong during calibration."), wxT("Warning"), wxOK | wxICON_ERROR); dial.ShowModal(); } volatile double test = stdDeviationsIntrinsics.at<double>(0); test = stdDeviationsIntrinsics.at<double>(1); test = stdDeviationsIntrinsics.at<double>(2); test = stdDeviationsIntrinsics.at<double>(3); if (stdDeviationsIntrinsics.at<double>(0) > 5 || stdDeviationsIntrinsics.at<double>(1) > 5) //high uncertiancy is bad { wxMessageDialog dial(NULL, wxT("WARNING:\nThe calibration grid doesnt seem very stable. This usualy indicates a bad calibration."), wxT("Warning"), wxOK | wxICON_ERROR); dial.ShowModal(); } */ // Save calibration to our global params cameraMatrix and distCoeffs calib_config.camMat = cameraMatrix; calib_config.distCoeffs = distCoeffs; calib_config.stdDeviationsIntrinsics = stdDeviationsIntrinsics; calib_config.perViewErrors = perViewErrors; calib_config.allCharucoCorners = allCharucoCorners; calib_config.allCharucoIds = allCharucoIds; calib_config.Save(); gui->ShowPopup(lc.TRACKER_CAMERA_CALIBRATION_COMPLETE, PopupStyle::Info); } } } void Tracker::CalibrateCamera() { // old calibration function, only still here for legacy reasons. int CHECKERBOARD[2]{7, 7}; int blockSize = 125; int imageSizeX = blockSize * (CHECKERBOARD[0] + 1); int imageSizeY = blockSize * (CHECKERBOARD[1] + 1); cv::Mat chessBoard(imageSizeX, imageSizeY, CV_8UC3, cv::Scalar::all(0)); unsigned char color = 0; for (int i = 0; i < imageSizeX - 1; i = i + blockSize) { if (CHECKERBOARD[1] % 2 == 1) color = ~color; for (int j = 0; j < imageSizeY - 1; j = j + blockSize) { cv::Mat ROI = chessBoard(cv::Rect(j, i, blockSize, blockSize)); ROI.setTo(cv::Scalar::all(color)); color = ~color; } } // cv::namedWindow("Chessboard", cv::WINDOW_KEEPRATIO); // imshow("Chessboard", chessBoard); // cv::imwrite("chessboard.png", chessBoard); std::vector<std::vector<cv::Point3f>> objpoints; std::vector<std::vector<cv::Point2f>> imgpoints; std::vector<cv::Point3f> objp; for (int i{0}; i < CHECKERBOARD[0]; i++) { for (int j{0}; j < CHECKERBOARD[1]; j++) { objp.push_back(cv::Point3f(static_cast<float>(j), static_cast<float>(i), 0)); } } std::vector<cv::Point2f> corner_pts; bool success; cv::Mat image; cv::Mat outImg; int i = 0; int framesSinceLast = -100; int picNum = user_config.cameraCalibSamples; while (i < picNum) { if (!mainThreadRunning || !cameraRunning) { return; } CopyFreshCameraImageTo(image); cv::putText(image, std::to_string(i) + "/" + std::to_string(picNum), cv::Point(10, 30), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(255, 255, 255)); int cols, rows; if (image.cols > image.rows) { cols = image.cols * drawImgSize / image.rows; rows = drawImgSize; } else { cols = drawImgSize; rows = image.rows * drawImgSize / image.cols; } framesSinceLast++; if (framesSinceLast > 50) { framesSinceLast = 0; cv::cvtColor(image, image, cv::COLOR_BGR2GRAY); success = findChessboardCorners(image, cv::Size(CHECKERBOARD[0], CHECKERBOARD[1]), corner_pts); if (success) { i++; cv::TermCriteria criteria(cv::TermCriteria::EPS | cv::TermCriteria::MAX_ITER, 30, 0.001); cornerSubPix(image, corner_pts, cv::Size(11, 11), cv::Size(-1, -1), criteria); drawChessboardCorners(image, cv::Size(CHECKERBOARD[0], CHECKERBOARD[1]), corner_pts, success); objpoints.push_back(objp); imgpoints.push_back(corner_pts); } std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } cv::resize(image, outImg, cv::Size(cols, rows)); gui->UpdatePreview(outImg); } cv::Mat cameraMatrix, distCoeffs, R, T; calibrateCamera(objpoints, imgpoints, cv::Size(image.rows, image.cols), cameraMatrix, distCoeffs, R, T); calib_config.camMat = cameraMatrix; calib_config.distCoeffs = distCoeffs; calib_config.Save(); mainThreadRunning = false; gui->ShowPopup("Calibration complete.", PopupStyle::Info); } void Tracker::StartTrackerCalib() { // check that no other process is running on main thread, check that camera is running and calibrated if (mainThreadRunning) { mainThreadRunning = false; return; } if (!cameraRunning) { gui->ShowPopup(lc.TRACKER_CAMERA_NOTRUNNING, PopupStyle::Error); mainThreadRunning = false; return; } if (calib_config.camMat.empty()) { gui->ShowPopup(lc.TRACKER_CAMERA_NOTCALIBRATED, PopupStyle::Error); mainThreadRunning = false; return; } // start tracker calibration on another thread mainThreadRunning = true; mainThread = std::thread(&Tracker::CalibrateTracker, this); mainThread.detach(); gui->ShowPrompt(lc.TRACKER_TRACKER_CALIBRATION_INSTRUCTIONS, [&](bool) { mainThreadRunning = false; }); } void Tracker::StartConnection() { connection->StartConnection(); gui->SetStatus(true, StatusItem::Driver); } void Tracker::HandleConnectionErrors() { using Code = Connection::ErrorCode; Code code = connection->GetAndResetErrorState(); if (code == Code::OK) return; gui->SetStatus(false, StatusItem::Driver); if (code == Code::ALREADY_WAITING) gui->ShowPopup("Already waiting for a connection.", PopupStyle::Error); else if (code == Code::ALREADY_CONNECTED) gui->ShowPopup("Connection closed.", PopupStyle::Info); else if (code == Code::CLIENT_ERROR) gui->ShowPopup(lc.CONNECT_CLIENT_ERROR + connection->GetErrorMsg(), PopupStyle::Error); else if (code == Code::BINDINGS_MISSING) gui->ShowPopup(lc.CONNECT_BINDINGS_ERROR, PopupStyle::Error); else if (code == Code::DRIVER_ERROR) gui->ShowPopup(lc.CONNECT_DRIVER_ERROR, PopupStyle::Error); else if (code == Code::DRIVER_MISMATCH) gui->ShowPopup(lc.CONNECT_DRIVER_MISSMATCH_1 + connection->GetErrorMsg() + lc.CONNECT_DRIVER_MISSMATCH_2 + user_config.driver_version.ToString(), PopupStyle::Error); else // if (code == Code::SOMETHING_WRONG) gui->ShowPopup(lc.CONNECT_SOMETHINGWRONG, PopupStyle::Error); } void Tracker::SetWorldTransform(const ManualCalib::Real& calib) { cv::Matx33d rmat = EulerAnglesToRotationMatrix(calib.angleOffset); wtransform = cv::Affine3d(rmat, calib.posOffset); wrotation = cv::Quatd::createFromRotMat(rmat).normalize(); wscale = calib.scale; } void Tracker::Start() { // check that no other process is running on main thread, check that camera is running and calibrated, check that trackers are calibrated if (mainThreadRunning) { mainThreadRunning = false; gui->SetStatus(false, StatusItem::Tracker); return; } if (!cameraRunning) { gui->ShowPopup(lc.TRACKER_CAMERA_NOTRUNNING, PopupStyle::Error); mainThreadRunning = false; return; } if (calib_config.camMat.empty()) { gui->ShowPopup(lc.TRACKER_CAMERA_NOTCALIBRATED, PopupStyle::Error); mainThreadRunning = false; return; } if (!trackersCalibrated) { gui->ShowPopup(lc.TRACKER_TRACKER_NOTCALIBRATED, PopupStyle::Error); mainThreadRunning = false; return; } if (connection->status != connection->CONNECTED) { gui->ShowPopup(lc.TRACKER_STEAMVR_NOTCONNECTED, PopupStyle::Error); mainThreadRunning = false; return; } gui->SetStatus(true, StatusItem::Tracker); // start detection on another thread mainThreadRunning = true; mainThread = std::thread(&Tracker::MainLoop, this); mainThread.detach(); } void Tracker::Stop() { mainThreadRunning = false; cameraRunning = false; /// TODO: join threads instead of sleeping std::this_thread::sleep_for(std::chrono::seconds(1)); } void Tracker::UpdateConfig() { if (connection->status == Connection::CONNECTED) { connection->Send("settings 120 " + std::to_string(user_config.smoothingFactor) + " " + std::to_string(user_config.additionalSmoothing)); } } void Tracker::CalibrateTracker() { // initialize all parameters needed for tracker calibration std::vector<std::vector<int>> boardIds; std::vector<std::vector<std::vector<cv::Point3f>>> boardCorners; std::vector<bool> boardFound; // making a marker model of our markersize for later use std::vector<cv::Point3f> modelMarker; double markerSize = user_config.markerSize*0.01; //markerSize is in centimeters, but we need it in meters modelMarker.push_back(cv::Point3f(-markerSize / 2.f, markerSize / 2.f, 0)); modelMarker.push_back(cv::Point3f(markerSize / 2.f, markerSize / 2.f, 0)); modelMarker.push_back(cv::Point3f(markerSize / 2.f, -markerSize / 2.f, 0)); modelMarker.push_back(cv::Point3f(-markerSize / 2.f, -markerSize / 2.f, 0)); AprilTagWrapper april{user_config, aruco_config}; int markersPerTracker = user_config.markersPerTracker; int trackerNum = user_config.trackerNum; std::vector<cv::Vec3d> boardRvec, boardTvec; // add main marker to every tracker for (int i = 0; i < trackerNum; i++) { std::vector<int> curBoardIds; std::vector<std::vector<cv::Point3f>> curBoardCorners; curBoardIds.push_back(i * markersPerTracker); curBoardCorners.push_back(modelMarker); boardIds.push_back(curBoardIds); boardCorners.push_back(curBoardCorners); boardFound.push_back(false); boardRvec.push_back(cv::Vec3d()); boardTvec.push_back(cv::Vec3d()); } cv::Mat image; cv::Mat outImg; cv::Ptr<cv::aruco::Dictionary> dictionary = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_4X4_50); std::vector<int> idsList; std::vector<std::vector<std::vector<cv::Point3f>>> cornersList; // reset current tracker calibration data // TODO: Don't reset if user clicks cancel trackers.clear(); auto preview = gui->CreatePreviewControl(); // run loop until we stop it while (cameraRunning && mainThreadRunning) { CopyFreshCameraImageTo(image); std::chrono::steady_clock::time_point start; // clock for timing of detection start = std::chrono::steady_clock::now(); // detect and draw all markers on image std::vector<int> ids; std::vector<std::vector<cv::Point2f>> corners; std::vector<cv::Point2f> centers; april.detectMarkers(image, &corners, &ids, &centers, trackers); if (showTimeProfile) { april.drawTimeProfile(image, cv::Point(10, 60)); } cv::aruco::drawDetectedMarkers(image, corners, cv::noArray(), cv::Scalar(255, 0, 0)); // draw all markers blue. We will overwrite this with other colors for markers that are part of any of the trackers that we use // estimate pose of our markers std::vector<cv::Vec3d> rvecs, tvecs; cv::aruco::estimatePoseSingleMarkers(corners, static_cast<float>(markerSize), calib_config.camMat, calib_config.distCoeffs, rvecs, tvecs); float maxDist = static_cast<float>(user_config.trackerCalibDistance); for (int i = 0; i < boardIds.size(); i++) // for each of the trackers { cv::Ptr<cv::aruco::Board> arBoard = cv::aruco::Board::create(boardCorners[i], dictionary, boardIds[i]); // create an aruco board object made out of already added markers to current tracker try { if (cv::aruco::estimatePoseBoard(corners, ids, arBoard, calib_config.camMat, calib_config.distCoeffs, boardRvec[i], boardTvec[i], false) > 0) // try to estimate current trackers pose { cv::aruco::drawAxis(image, calib_config.camMat, calib_config.distCoeffs, boardRvec[i], boardTvec[i], 0.1f); // if found, draw axis and mark it found boardFound[i] = true; } else { boardFound[i] = false; // else, if none of the markers for this tracker are visible, mark it not found } } catch (const std::exception& e) // on weird images or calibrations, we get an error. This should usualy only happen on bad camera calibrations, or in very rare cases { ATERROR("cv::aruco::estimatePoseBoard exception: " << e.what()); gui->ShowPopup(lc.TRACKER_CALIBRATION_SOMETHINGWRONG, PopupStyle::Error); mainThreadRunning = false; return; } std::string testStr = std::to_string(boardTvec[i][0]) + " " + std::to_string(boardTvec[i][1]) + " " + std::to_string(boardTvec[i][2]); bool foundMarkerToCalibrate = false; for (int j = 0; j < ids.size(); j++) // check all of the found markers { if (ids[j] >= i * markersPerTracker && ids[j] < (i + 1) * markersPerTracker) // if marker is part of current tracker (usualy, 0 is 0-44, 1 is 45-89 etc) { bool markerInBoard = false; for (int k = 0; k < boardIds[i].size(); k++) // check if marker is already part of the tracker { if (boardIds[i][k] == ids[j]) { markerInBoard = true; break; } } if (markerInBoard == true) // if it is, draw it green and continue to next marker { drawMarker(image, corners[j], cv::Scalar(0, 255, 0)); continue; } if (boardFound[i]) // if it isnt part of the current tracker, but the tracker was detected, we will attempt to add it { if (sqrt(tvecs[j][0] * tvecs[j][0] + tvecs[j][1] * tvecs[j][1] + tvecs[j][2] * tvecs[j][2]) > maxDist) // if marker is too far away from camera, we just paint it purple as adding it could have too much error { drawMarker(image, corners[j], cv::Scalar(255, 0, 255)); continue; } drawMarker(image, corners[j], cv::Scalar(0, 255, 255)); // start adding marker, mark that by painting it yellow if (foundMarkerToCalibrate) // only calibrate one marker at a time, so continue loop if this is the second marker found continue; foundMarkerToCalibrate = true; std::vector<cv::Point3f> marker; transformMarkerSpace(modelMarker, boardRvec[i], boardTvec[i], rvecs[j], tvecs[j], &marker); // transform marker points to the coordinate system of the tracker int listIndex = -1; for (int k = 0; k < idsList.size(); k++) // check whether the idsList and cornersList already contains data for this marker { if (idsList[k] == ids[j]) { listIndex = k; } } if (listIndex < 0) // if not, add and initialize it { listIndex = static_cast<int>(idsList.size()); idsList.push_back(ids[j]); cornersList.push_back(std::vector<std::vector<cv::Point3f>>()); } cornersList[listIndex].push_back(marker); // add the current marker corners to the list if (cornersList[listIndex].size() > 50) // if we have 50 recorded instances in the list for current marker, we can add it to the tracker { std::vector<cv::Point3f> medianMarker; getMedianMarker(cornersList[listIndex], &medianMarker); // calculate median position of each corner to get rid of outliers boardIds[i].push_back(ids[j]); // add the marker to the tracker boardCorners[i].push_back(medianMarker); } } else { drawMarker(image, corners[j], cv::Scalar(0, 0, 255)); } } } } // resize image, then show it int cols, rows; if (image.cols > image.rows) { cols = image.cols * drawImgSize / image.rows; rows = drawImgSize; } else { cols = drawImgSize; rows = image.rows * drawImgSize / image.cols; } cv::resize(image, outImg, cv::Size(cols, rows)); gui->UpdatePreview(outImg); } // when done calibrating, save the trackers to parameters for (int i = 0; i < boardIds.size(); i++) { cv::Ptr<cv::aruco::Board> arBoard = cv::aruco::Board::create(boardCorners[i], dictionary, boardIds[i]); trackers.push_back(arBoard); } calib_config.trackers = trackers; calib_config.Save(); trackersCalibrated = true; mainThreadRunning = false; } void Tracker::MainLoop() { size_t trackerNum = connection->connectedTrackers.size(); int numOfPrevValues = user_config.numOfPrevValues; SetWorldTransform(user_config.manualCalib.GetAsReal()); // these variables are used to save detections of apriltags, so we dont define them every frame std::vector<int> ids; std::vector<std::vector<cv::Point2f>> corners; std::vector<cv::Point2f> centers; cv::Mat image, drawImg, outImg, ycc, gray, cr; cv::Mat prevImg; // setup all variables that need to be stored for each tracker and initialize them std::vector<TrackerStatus> trackerStatus = std::vector<TrackerStatus>(trackerNum, TrackerStatus()); for (int i = 0; i < trackerStatus.size(); i++) { trackerStatus[i].boardFound = false; trackerStatus[i].boardRvec = cv::Vec3d(0, 0, 0); trackerStatus[i].boardTvec = cv::Vec3d(0, 0, 0); trackerStatus[i].prevLocValues = std::vector<std::vector<double>>(7, std::vector<double>()); } // previous values, used for moving median to remove any outliers. std::vector<double> prevLocValuesX; // the X axis, it is simply numbers 0-10 (or the amount of previous values we have) for (int j = 0; j < numOfPrevValues; j++) { prevLocValuesX.push_back(j); } AprilTagWrapper april{user_config, aruco_config}; int framesSinceLastSeen = 0; int framesToCheckAll = 20; // calculate position of camera from calibration data and send its position to steamvr cv::Vec3d stationPos = wtransform.translation(); CoordTransformOVR(stationPos); cv::Quatd stationQ = cv::Quatd(0, 0, 1, 0) * (wrotation * cv::Quatd(1, 0, 0, 0)); connection->SendStation(0, stationPos[0], stationPos[1], stationPos[2], stationQ[0], stationQ[1], stationQ[2], stationQ[3]); // initialize variables for playspace calibration bool calibControllerPosActive = false; bool calibControllerAngleActive = false; auto calibControllerLastPress = std::chrono::steady_clock::now(); /// offset of controller to virtual camera, set when button is pressed cv::Vec3d calibControllerPosOffset = {0, 0, 0}; /// (pitch, yaw) in radians, 3rd component is distance cv::Vec3d calibControllerAngleOffset = {0, 0, 0}; std::vector<cv::Ptr<cv::aruco::Board>> trackers; std::vector<std::vector<int>> boardIds; std::vector<std::vector<std::vector<cv::Point3f>>> boardCorners; // by default, trackers have the center at the center of the main marker. If "Use centers of trackers" is checked, we move it to the center of all marker corners. if (user_config.trackerCalibCenters) { for (int i = 0; i < this->trackers.size(); i++) { boardCorners.push_back(this->trackers[i]->objPoints); boardIds.push_back(this->trackers[i]->ids); cv::Point3f boardCenter = cv::Point3f(0, 0, 0); int numOfCorners = 0; for (int j = 0; j < boardCorners[i].size(); j++) { for (int k = 0; k < boardCorners[i][j].size(); k++) { boardCenter.x += boardCorners[i][j][k].x; boardCenter.y += boardCorners[i][j][k].y; boardCenter.z += boardCorners[i][j][k].z; numOfCorners++; } } boardCenter /= numOfCorners; for (int j = 0; j < boardCorners[i].size(); j++) { for (int k = 0; k < boardCorners[i][j].size(); k++) { boardCorners[i][j][k] -= boardCenter; } } cv::Ptr<cv::aruco::Board> arBoard = cv::aruco::Board::create(boardCorners[i], cv::aruco::getPredefinedDictionary(cv::aruco::DICT_4X4_50), boardIds[i]); trackers.push_back(arBoard); } } else { trackers = this->trackers; } while (mainThreadRunning && cameraRunning) // run detection until camera is stopped or the start/stop button is pressed again { CopyFreshCameraImageTo(image); // shallow copy, gray will be cloned from image and used for detection, // so drawing can happen on color image without clone. drawImg = image; april.convertToSingleChannel(image, gray); std::chrono::steady_clock::time_point start, end; // for timing our detection start = std::chrono::steady_clock::now(); bool circularWindow = user_config.circularWindow; // if any tracker was lost for longer than 20 frames, mark circularWindow as false for (int i = 0; i < trackerNum; i++) { if (!trackerStatus[i].boardFound) { framesSinceLastSeen++; if (framesSinceLastSeen > framesToCheckAll) circularWindow = false; break; } } if (!circularWindow) framesSinceLastSeen = 0; for (int i = 0; i < trackerNum; i++) { double frameTime = std::chrono::duration<double>(std::chrono::steady_clock::now() - last_frame_time).count(); std::string word; std::istringstream ret = connection->Send("gettrackerpose " + std::to_string(i) + " " + std::to_string(-frameTime - user_config.camLatency)); ret >> word; if (word != "trackerpose") { continue; } // first three variables are a position vector int idx; double a; double b; double c; // second four are rotation quaternion double qw; double qx; double qy; double qz; // last is if pose is valid: 0 is valid, 1 is late (hasnt been updated for more than 0.2 secs), -1 means invalid and is only zeros int tracker_pose_valid; // read to our variables ret >> idx; ret >> a; ret >> b; ret >> c; ret >> qw; ret >> qx; ret >> qy; ret >> qz; ret >> tracker_pose_valid; cv::Vec3d rpos{a, b, c}; CoordTransformOVR(rpos); // transform boards position from steamvr space to camera space based on our calibration data rpos = wtransform.inv() * rpos; std::vector<cv::Point3d> point; point.push_back(cv::Point3d(rpos[0], rpos[1], rpos[2])); point.push_back(cv::Point3d(trackerStatus[i].boardTvec)); std::vector<cv::Point2d> projected; cv::Vec3d rvec, tvec; // project point from position of tracker in camera 3d space to 2d camera pixel space, and draw a dot there cv::projectPoints(point, rvec, tvec, calib_config.camMat, calib_config.distCoeffs, projected); cv::circle(drawImg, projected[0], 5, cv::Scalar(0, 0, 255), 2, 8, 0); if (tracker_pose_valid == 0) // if the pose from steamvr was valid, save the predicted position and rotation { cv::Quatd q{qw, qx, qy, qz}; /// TODO: What is this? q = wrotation.inv(cv::QUAT_ASSUME_UNIT) * cv::Quatd(0, 0, 1, 0).inv(cv::QUAT_ASSUME_UNIT) * q.normalize() * cv::Quatd(0, 0, 1, 0).inv(cv::QUAT_ASSUME_UNIT); cv::Vec3d rvec = q.toRotVec(); cv::Vec3d tvec{rpos[0], rpos[1], rpos[2]}; cv::aruco::drawAxis(drawImg, calib_config.camMat, calib_config.distCoeffs, rvec, tvec, 0.10f); if (!trackerStatus[i].boardFound) // if tracker was found in previous frame, we use that position for masking. If not, we use position from driver for masking. { trackerStatus[i].maskCenter = projected[0]; } else { trackerStatus[i].maskCenter = projected[1]; } trackerStatus[i].boardFound = true; trackerStatus[i].boardFoundDriver = true; trackerStatus[i].boardTvec = tvec; trackerStatus[i].boardTvecDriver = tvec; trackerStatus[i].boardRvec = rvec; } else { if (trackerStatus[i].boardFound) // if pose is not valid, set everything based on previous known position { trackerStatus[i].maskCenter = projected[1]; } trackerStatus[i].boardFoundDriver = false; // do we really need to do this? might be unnecessary } } // define our mask image. We want to create an image where everything but circles around predicted tracker positions will be black to speed up detection. cv::Mat mask = cv::Mat::zeros(gray.size(), gray.type()); cv::Mat dstImage = cv::Mat::zeros(gray.size(), gray.type()); int size = static_cast<int>(std::trunc(gray.rows * user_config.searchWindow)); bool doMasking = false; for (int i = 0; i < trackerNum; i++) // calculate the needed masks for every tracker { if (trackerStatus[i].maskCenter.x <= 0 || trackerStatus[i].maskCenter.y <= 0 || trackerStatus[i].maskCenter.x >= image.cols || trackerStatus[i].maskCenter.y >= image.rows) { trackerStatus[i].boardFound = false; // if detected tracker is out of view of the camera, we mark it as not found, as either the prediction is wrong or we wont see it anyway continue; } doMasking = true; if (circularWindow) // if circular window is set mask a circle around the predicted tracker point { cv::circle(mask, trackerStatus[i].maskCenter, size, cv::Scalar(255, 0, 0), -1, 8, 0); cv::circle(drawImg, trackerStatus[i].maskCenter, size, cv::Scalar(255, 0, 0), 2, 8, 0); } else // if not, mask a vertical strip top to bottom. This happens every 20 frames if a tracker is lost. { int maskCenter = static_cast<int>(std::trunc(trackerStatus[i].maskCenter.x)); rectangle(mask, cv::Point(maskCenter - size, 0), cv::Point(maskCenter + size, image.rows), cv::Scalar(255, 0, 0), -1); rectangle(drawImg, cv::Point(maskCenter - size, 0), cv::Point(maskCenter + size, image.rows), cv::Scalar(255, 0, 0), 3); } } // using copyTo with masking creates the image where everything but the locations where trackers are predicted to be is black if (doMasking) { gray.copyTo(dstImage, mask); gray = dstImage; } if (manualRecalibrate) // playspace calibration loop { int inputButton = connection->GetButtonStates(); ManualCalib::Real calib = gui->GetManualCalib(); double timeSincePress = std::chrono::duration<double>(start - calibControllerLastPress).count(); if (timeSincePress > 60) // we exit playspace calibration after 60 seconds of no input detected, to try to prevent accidentaly ruining calibration { gui->SetManualCalibVisible(false); } if (inputButton == 1) // logic for position button { // to prevent accidental double presses, 0.2 seconds must pass between presses. double timeSincePress = std::chrono::duration<double>(start - calibControllerLastPress).count(); if (timeSincePress >= 0.2) { if (!calibControllerPosActive) // if position calibration is inactive, set it to active and calculate offsets between the camera and controller { calibControllerPosActive = true; Pose pose = connection->GetControllerPose(); calibControllerPosOffset = pose.position - calib.posOffset; RotateVecByQuat(calibControllerPosOffset, pose.rotation.inv(cv::QUAT_ASSUME_UNIT)); } else // else, deactivate it { calibControllerPosActive = false; } } calibControllerLastPress = std::chrono::steady_clock::now(); } else if (inputButton == 2) // logic for rotation button { // to prevent accidental double presses, 0.2 seconds must pass between presses. double timeSincePress = std::chrono::duration<double>(start - calibControllerLastPress).count(); if (timeSincePress >= 0.2) { if (!calibControllerAngleActive) // if rotation calibration is inactive, set it to active and calculate angle offsets and distance { calibControllerAngleActive = true; Pose pose = connection->GetControllerPose(); cv::Vec2d angle = EulerAnglesFromPos(pose.position, calib.posOffset); double distance = Distance(pose.position, calib.posOffset); calibControllerAngleOffset[0] = angle[0] - calib.angleOffset[0]; calibControllerAngleOffset[1] = angle[1] - calib.angleOffset[1]; calibControllerAngleOffset[2] = distance/calib.scale; } else // else, deactivate it { calibControllerAngleActive = false; } } calibControllerLastPress = std::chrono::steady_clock::now(); } if (calibControllerPosActive) // while position calibration is active, apply the camera to controller offset to X, Y and Z values { Pose pose = connection->GetControllerPose(); RotateVecByQuat(calibControllerPosOffset, pose.rotation); calib.posOffset[0] = pose.position[0] - calibControllerPosOffset[0]; if (!lockHeightCalib) { calib.posOffset[1] = pose.position[1] - calibControllerPosOffset[1]; } calib.posOffset[2] = pose.position[2] - calibControllerPosOffset[2]; RotateVecByQuat(calibControllerPosOffset, pose.rotation.inv(cv::QUAT_ASSUME_UNIT)); } if (calibControllerAngleActive) // while rotation calibration is active, apply the camera to controller angle offsets to A, B, C values, and apply the calibScale based on distance from camera { Pose pose = connection->GetControllerPose(); cv::Vec2d angle = EulerAnglesFromPos(pose.position, calib.posOffset); double distance = Distance(pose.position, calib.posOffset); calib.angleOffset[1] = angle[1] - calibControllerAngleOffset[1]; if (!lockHeightCalib) // if height is locked, do not calibrate up/down rotation or scale { calib.angleOffset[0] = angle[0] - calibControllerAngleOffset[0]; calib.scale = distance / calibControllerAngleOffset[2]; } } // check that camera is facing correct direction. 90 degrees mean looking straight down, 270 is straight up. This ensures its not upside down. if (calib.angleOffset[0] < 91 * DEG_2_RAD) calib.angleOffset[0] = 91 * DEG_2_RAD; else if (calib.angleOffset[0] > 269 * DEG_2_RAD) calib.angleOffset[0] = 269 * DEG_2_RAD; if (calibControllerAngleActive || calibControllerPosActive) { // update the calib in the gui as it wont be modified anymore gui->SetManualCalib(calib); } // update the pre calculated calibration transformations SetWorldTransform(gui->GetManualCalib()); cv::Vec3d stationPos = wtransform.translation(); CoordTransformOVR(stationPos); // rotate y axis by 180 degrees, aka, reflect across xz plane cv::Quatd stationQ = cv::Quatd(0, 0, 1, 0) * wrotation; // move the camera in steamvr to new calibration connection->SendStation(0, stationPos[0], stationPos[1], stationPos[2], stationQ.w, stationQ.x, stationQ.y, stationQ.z); } else { calibControllerLastPress = std::chrono::steady_clock::now(); } april.detectMarkers(gray, &corners, &ids, &centers, trackers); for (int i = 0; i < trackerNum; ++i) { // estimate the pose of current board try { trackerStatus[i].boardTvec /= wscale; if (cv::aruco::estimatePoseBoard(corners, ids, trackers[connection->connectedTrackers[i].TrackerId], calib_config.camMat, calib_config.distCoeffs, trackerStatus[i].boardRvec, trackerStatus[i].boardTvec, trackerStatus[i].boardFound && user_config.usePredictive) <= 0) { for (int j = 0; j < 6; j++) { // remove first of the previously saved values if (trackerStatus[i].prevLocValues[j].size() > 0) trackerStatus[i].prevLocValues[j].erase(trackerStatus[i].prevLocValues[j].begin()); } trackerStatus[i].boardFound = false; continue; } } catch (const std::exception& e) { // on rare occasions, detection crashes. Should be very rare and indicate something wrong with camera or tracker calibration ATERROR("cv::aruco::estimatePoseBoard exception: " << e.what()); gui->ShowPopup(lc.TRACKER_DETECTION_SOMETHINGWRONG, PopupStyle::Error); mainThreadRunning = false; return; } trackerStatus[i].boardFound = true; trackerStatus[i].boardTvec *= wscale; if (user_config.depthSmoothing > 0 && trackerStatus[i].boardFoundDriver && !manualRecalibrate) { // depth estimation is noisy, so try to smooth it more, especialy if using multiple cameras // if position is close to the position predicted by the driver, take the depth of the driver. // if error is big, take the calculated depth // error threshold is defined in the params as depth smoothing double distDriver = Length(trackerStatus[i].boardTvecDriver); double distPredict = Length(trackerStatus[i].boardTvec); cv::Vec3d normPredict = trackerStatus[i].boardTvec / distPredict; double dist = std::abs(distPredict - distDriver); dist = dist / user_config.depthSmoothing + 0.1; if (dist > 1) dist = 1; double distFinal = (dist)*distPredict + (1 - dist) * distDriver; trackerStatus[i].boardTvec = normPredict * distFinal; // trackerStatus[i].boardTvec[2] = (dist) * trackerStatus[i].boardTvec[2] + (1-dist) * trackerStatus[i].boardTvecDriver[2]; } double posValues[6] = { trackerStatus[i].boardTvec[0], trackerStatus[i].boardTvec[1], trackerStatus[i].boardTvec[2], trackerStatus[i].boardRvec[0], trackerStatus[i].boardRvec[1], trackerStatus[i].boardRvec[2]}; for (int j = 0; j < 6; j++) { // push new values into previous values list end and remove the one on beggining trackerStatus[i].prevLocValues[j].push_back(posValues[j]); if (trackerStatus[i].prevLocValues[j].size() > numOfPrevValues) { trackerStatus[i].prevLocValues[j].erase(trackerStatus[i].prevLocValues[j].begin()); } std::vector<double> valArray(trackerStatus[i].prevLocValues[j]); // sort(valArray.begin(), valArray.end()); // posValues[j] = valArray[valArray.size() / 2]; posValues[j] = valArray[valArray.size() - 1]; } // save fitted values back to our variables trackerStatus[i].boardTvec[0] = posValues[0]; trackerStatus[i].boardTvec[1] = posValues[1]; trackerStatus[i].boardTvec[2] = posValues[2]; trackerStatus[i].boardRvec[0] = posValues[3]; trackerStatus[i].boardRvec[1] = posValues[4]; trackerStatus[i].boardRvec[2] = posValues[5]; cv::Vec3d rpos = trackerStatus[i].boardTvec; // transform boards position based on our calibration data rpos = wtransform * rpos; CoordTransformOVR(rpos); // convert rodriguez rotation to quaternion cv::Quatd q = cv::Quatd::createFromRvec(trackerStatus[i].boardRvec); // cv::aruco::drawAxis(drawImg, user_config.camMat, user_config.distCoeffs, boardRvec[i], boardTvec[i], 0.05); q = cv::Quatd{0, 0, 1, 0} * (wrotation * q) * cv::Quatd{0, 0, 1, 0}; double factor = user_config.smoothingFactor; if (factor < 0) factor = 0; else if (factor >= 1) factor = 0.99; end = std::chrono::steady_clock::now(); double frameTime = std::chrono::duration<double>(end - last_frame_time).count(); // send all the values // frame time is how much time passed since frame was acquired. if (!multicamAutocalib) connection->SendTracker(connection->connectedTrackers[i].DriverId, rpos[0], rpos[1], rpos[2], q.w, q.x, q.y, q.z, -frameTime - user_config.camLatency, factor); else if (trackerStatus[i].boardFoundDriver) { // if calibration refinement with multiple cameras is active, do not send calculated poses to driver. // instead, refine the calibration data with gradient descent // the error is the diffrence of the detected trackers position to the estimated trackers position // numerical derivatives are then calculated to see how X,Y,Z, A,B, scale data affects the error in position // calibration values are then slightly changed in the estimated direction in order to reduce error. // after a couple of seconds, the calibration data should converge cv::Vec3d pos = trackerStatus[i].boardTvec; cv::Vec2d angles = EulerAnglesFromPos(pos); double length = Length(pos); cv::Vec3d driverPos = trackerStatus[i].boardTvecDriver; cv::Vec2d driverAngles = EulerAnglesFromPos(driverPos); double driverLength = Length(driverPos); pos = wtransform * pos; driverPos = wtransform * driverPos; CoordTransformOVR(pos); CoordTransformOVR(driverPos); double dX = (pos[0] - driverPos[0]) * 0.1; double dY = -(pos[1] - driverPos[1]) * 0.1; double dZ = (pos[2] - driverPos[2]) * 0.1; if (abs(dX) > 0.01) dX = 0.1 * (dX / abs(dX)); if (abs(dY) > 0.1) dY = 0.1 * (dY / abs(dY)); if (abs(dZ) > 0.1) dZ = 0.1 * (dZ / abs(dZ)); ManualCalib::Real calib = gui->GetManualCalib(); calib.posOffset += cv::Vec3d(dX, dY, dZ); calib.angleOffset += cv::Vec3d(angles[0] - driverAngles[0], angles[1] - driverAngles[1]) * 0.1; calib.scale -= (1 - (driverLength / length)) * 0.1; gui->SetManualCalib(calib); SetWorldTransform(calib); } } // draw and display the detections if (ids.size() > 0) cv::aruco::drawDetectedMarkers(drawImg, corners, ids); end = std::chrono::steady_clock::now(); double frameTime = std::chrono::duration<double>(end - start).count(); if (gui->IsPreviewVisible()) { int cols, rows; if (image.cols > image.rows) { cols = image.cols * drawImgSize / image.rows; rows = drawImgSize; } else { cols = drawImgSize; rows = image.rows * drawImgSize / image.cols; } cv::resize(drawImg, outImg, cv::Size(cols, rows)); cv::putText(outImg, std::to_string(frameTime).substr(0, 5), cv::Point(10, 30), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(255, 255, 255)); if (showTimeProfile) { april.drawTimeProfile(outImg, cv::Point(10, 60)); } gui->UpdatePreview(outImg); } // time of marker detection } }
40.190128
282
0.580043
[ "object", "vector", "model", "transform", "3d", "solid" ]
55724e65ddac45f2c5ea68eaba5cb2f7ba518be6
4,742
cpp
C++
src/bounce/dynamics/shapes/mesh_shape.cpp
demiurgestudios/bounce
9f8dcae52a074ba76088da9c94471366f6e4ca8f
[ "Zlib" ]
26
2020-02-10T19:28:00.000Z
2021-09-23T22:36:37.000Z
src/bounce/dynamics/shapes/mesh_shape.cpp
demiurgestudios/bounce
9f8dcae52a074ba76088da9c94471366f6e4ca8f
[ "Zlib" ]
null
null
null
src/bounce/dynamics/shapes/mesh_shape.cpp
demiurgestudios/bounce
9f8dcae52a074ba76088da9c94471366f6e4ca8f
[ "Zlib" ]
7
2020-01-22T20:42:33.000Z
2021-02-25T02:34:54.000Z
/* * Copyright (c) 2016-2019 Irlan Robson https://irlanrobson.github.io * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <bounce/dynamics/shapes/mesh_shape.h> #include <bounce/collision/shapes/mesh.h> b3MeshShape::b3MeshShape() { m_type = e_meshShape; m_radius = B3_HULL_RADIUS; m_mesh = NULL; } b3MeshShape::~b3MeshShape() { } void b3MeshShape::Swap(const b3MeshShape& other) { m_radius = other.m_radius; m_mesh = other.m_mesh; } void b3MeshShape::ComputeMass(b3MassData* massData, float32 density) const { B3_NOT_USED(density); u32 n = m_mesh->vertexCount; b3Vec3 c(0.0f, 0.0f, 0.0f); for (u32 i = 0; i < n; ++i) { c += m_mesh->vertices[i]; } if (n > 0) { c = 1.0f / float32(n) * c; } massData->center = c; massData->mass = 0.0f; massData->I.SetZero(); } void b3MeshShape::ComputeAABB(b3AABB3* output, const b3Transform& xf) const { output->Set(m_mesh->vertices, m_mesh->vertexCount, xf); output->Extend(m_radius); } void b3MeshShape::ComputeAABB(b3AABB3* output, const b3Transform& xf, u32 index) const { B3_ASSERT(index < m_mesh->triangleCount); const b3Triangle* triangle = m_mesh->triangles + index; b3Vec3 v1 = b3Mul(xf, m_mesh->vertices[triangle->v1]); b3Vec3 v2 = b3Mul(xf, m_mesh->vertices[triangle->v2]); b3Vec3 v3 = b3Mul(xf, m_mesh->vertices[triangle->v3]); output->m_lower = b3Min(b3Min(v1, v2), v3); output->m_upper = b3Max(b3Max(v1, v2), v3); output->Extend(m_radius); } bool b3MeshShape::TestSphere(const b3Sphere& sphere, const b3Transform& xf) const { B3_NOT_USED(sphere); B3_NOT_USED(xf); return false; } bool b3MeshShape::TestSphere(b3TestSphereOutput* output, const b3Sphere& sphere, const b3Transform& xf) const { B3_NOT_USED(output); B3_NOT_USED(sphere); B3_NOT_USED(xf); return false; } bool b3MeshShape::TestSphere(b3TestSphereOutput* output, const b3Sphere& sphere, const b3Transform& xf, u32 index) const { B3_NOT_USED(output); B3_NOT_USED(sphere); B3_NOT_USED(xf); B3_NOT_USED(index); return false; } bool b3MeshShape::RayCast(b3RayCastOutput* output, const b3RayCastInput& input, const b3Transform& xf, u32 index) const { B3_ASSERT(index < m_mesh->triangleCount); b3Triangle* triangle = m_mesh->triangles + index; b3Vec3 v1 = m_mesh->vertices[triangle->v1]; b3Vec3 v2 = m_mesh->vertices[triangle->v2]; b3Vec3 v3 = m_mesh->vertices[triangle->v3]; // Put the ray into the mesh's frame of reference. b3Vec3 p1 = b3MulT(xf, input.p1); b3Vec3 p2 = b3MulT(xf, input.p2); b3RayCastInput subInput; subInput.p1 = p1; subInput.p2 = p2; subInput.maxFraction = input.maxFraction; b3RayCastOutput subOutput; if (b3RayCast(&subOutput, &subInput, v1, v2, v3)) { output->fraction = subOutput.fraction; output->normal = xf.rotation * subOutput.normal; return true; } return false; } struct b3MeshShapeRayCastCallback { float32 Report(const b3RayCastInput& subInput, u32 proxyId) { B3_NOT_USED(subInput); u32 childIndex = mesh->m_mesh->tree.GetUserData(proxyId); b3RayCastOutput childOutput; if (mesh->RayCast(&childOutput, input, xf, childIndex)) { // Track minimum time of impact to require less memory. if (childOutput.fraction < output.fraction) { hit = true; output = childOutput; } } return 1.0f; } b3RayCastInput input; const b3MeshShape* mesh; b3Transform xf; bool hit; b3RayCastOutput output; }; bool b3MeshShape::RayCast(b3RayCastOutput* output, const b3RayCastInput& input, const b3Transform& xf) const { b3MeshShapeRayCastCallback callback; callback.input = input; callback.mesh = this; callback.xf = xf; callback.hit = false; callback.output.fraction = B3_MAX_FLOAT; b3RayCastInput subInput; subInput.p1 = b3MulT(xf, input.p1); subInput.p2 = b3MulT(xf, input.p2); subInput.maxFraction = input.maxFraction; m_mesh->tree.RayCast(&callback, subInput); output->fraction = callback.output.fraction; output->normal = callback.output.normal; return callback.hit; }
26.640449
120
0.732813
[ "mesh" ]
5575ea3a270bdc4c89991706745e26cba53a3418
1,980
cpp
C++
cpp/include/string/suffix_array.cpp
torotoki/competitive-library
4c0772c2da245adad9d1ea2bc6fc2b65a4b670de
[ "MIT" ]
3
2017-04-09T10:12:31.000Z
2019-02-11T03:11:27.000Z
cpp/include/string/suffix_array.cpp
torotoki/competitive-library
4c0772c2da245adad9d1ea2bc6fc2b65a4b670de
[ "MIT" ]
null
null
null
cpp/include/string/suffix_array.cpp
torotoki/competitive-library
4c0772c2da245adad9d1ea2bc6fc2b65a4b670de
[ "MIT" ]
1
2019-11-29T06:11:10.000Z
2019-11-29T06:11:10.000Z
struct SuffixArray { struct SAComp { const int h; const vector<int> &g; SAComp(int h, vector<int> &g) : h(h), g(g) {;} bool operator() (int a, int b) { return a != b && (g[a] != g[b] ? g[a] < g[b] : g[a + h] < g[b + h]); } }; int n; char *str; vector<int> sa, lcp; SuffixArray(const string &t) : n(t.size()), sa(n+1), lcp(n+1) { str = new char[n+1]; strcpy(str, t.c_str()); // build SA vector<int> g(n+1, 0), b(n+1, 0); for (int i = 0; i <= n; ++i) { sa[i] = i; g[i] = str[i]; } sort(begin(sa), end(sa), SAComp(0, g)); for (int h = 1; b[n] != n; h *= 2) { SAComp comp(h, g); sort(sa.begin(), sa.end(), comp); for (int i = 0; i < n; ++i) b[i+1] = b[i] + comp(sa[i], sa[i+1]); for (int i = 0; i <= n; ++i) g[sa[i]] = b[i]; } // build LCP int h = 0; for (int i = 0; i <= n; ++i) b[sa[i]] = i; for (int i = 0; i <= n; ++i) { if (b[i]) { for (int j = sa[b[i]-1]; j+h<n && i+h<n && str[j+h] == str[i+h]; ++h); lcp[b[i]] = h; } else { lcp[b[i]] = -1; } if (h > 0) --h; } } ~SuffixArray() { delete []str; } int find(string t) { int m = t.size(); char p[m+1]; strcpy(p, t.c_str()); int left = -1, right = n + 1; while (left + 1 < right) { int mid = (left + right) / 2; if (strncmp(str + sa[mid], p, m) < 0) left = mid; else right = mid; } return strncmp(str + sa[right], p, m) == 0 ? sa[right] : -1; } }; class LCP { int n; vector<int> mapsto; SegmentTree<int,min> seg; public: LCP(const string &str) : n(str.size()), mapsto(n), seg(n, inf<int>) { SuffixArray sa(str); for (int i = 0; i < n; ++i) mapsto[sa.sa[i+1]] = i; for (int i = 0; i < n-1; ++i) seg.update(i, sa.lcp[i+2]); } int query(int i, int j) { if (i == j) return n - i; i = mapsto[i]; j = mapsto[j]; return seg.find(min(i, j), max(i, j)); } };
25.384615
78
0.441414
[ "vector" ]
534e10108eca53c02e31c3f88d6f3ae2a6fd24c8
498
hpp
C++
iOS/G3MApp/G3MApp/G3M3DLandDemoScene.hpp
glob3mobile/g3m
2b2c6422f05d13e0855b1dbe4e0afed241184193
[ "BSD-2-Clause" ]
70
2015-02-06T14:39:14.000Z
2022-01-07T08:32:48.000Z
iOS/G3MApp/G3MApp/G3M3DLandDemoScene.hpp
glob3mobile/g3m
2b2c6422f05d13e0855b1dbe4e0afed241184193
[ "BSD-2-Clause" ]
118
2015-01-21T10:18:00.000Z
2018-10-16T15:00:57.000Z
iOS/G3MApp/G3MApp/G3M3DLandDemoScene.hpp
glob3mobile/g3m
2b2c6422f05d13e0855b1dbe4e0afed241184193
[ "BSD-2-Clause" ]
41
2015-01-10T22:29:27.000Z
2021-06-08T11:56:16.000Z
// // G3M3DLandDemoScene.hpp // G3MApp // // Created by Diego Gomez Deck on 10/4/16. // #ifndef G3M3DLandDemoScene_hpp #define G3M3DLandDemoScene_hpp #include "G3MDemoScene.hpp" class G3M3DLandDemoScene : public G3MDemoScene { protected: void rawActivate(const G3MContext* context); void rawSelectOption(const std::string& option, int optionIndex); public: G3M3DLandDemoScene(G3MDemoModel* model) : G3MDemoScene(model, "3D Land", "", -1) { } }; #endif
16.6
49
0.692771
[ "model", "3d" ]
53522bcb9e3fdfb8938bda3f5f1404a3f3771a0e
1,908
hh
C++
src/bugengine/introspect/api/bugengine/introspect/node/object.hh
bugengine/BugEngine
1b3831d494ee06b0bd74a8227c939dd774b91226
[ "BSD-3-Clause" ]
4
2015-05-13T16:28:36.000Z
2017-05-24T15:34:14.000Z
src/bugengine/introspect/api/bugengine/introspect/node/object.hh
bugengine/BugEngine
1b3831d494ee06b0bd74a8227c939dd774b91226
[ "BSD-3-Clause" ]
null
null
null
src/bugengine/introspect/api/bugengine/introspect/node/object.hh
bugengine/BugEngine
1b3831d494ee06b0bd74a8227c939dd774b91226
[ "BSD-3-Clause" ]
1
2017-03-21T08:28:07.000Z
2017-03-21T08:28:07.000Z
/* BugEngine <bugengine.devel@gmail.com> see LICENSE for detail */ #ifndef BE_INTROSPECT_NODE_OBJECT_HH_ #define BE_INTROSPECT_NODE_OBJECT_HH_ /**************************************************************************************************/ #include <bugengine/introspect/stdafx.h> #include <bugengine/introspect/node/node.hh> #include <bugengine/introspect/introspectionhint.hh> #include <bugengine/meta/engine/methodinfo.script.hh> namespace BugEngine { namespace Meta { namespace AST { class Reference; class Parameter; class IntrospectionHint; class be_api(INTROSPECT) Object : public Node { private: const ref< Reference > m_className; const minitl::vector< ref< Parameter > > m_parameters; minitl::vector< ArgInfo > m_arguments; ref< IntrospectionHint > m_introspectionHint; private: bool resolveInternal(DbContext & context); protected: virtual minitl::tuple< raw< const Meta::Method >, bool > getCall(DbContext & context) const override; virtual ConversionCost distance(const Type& type) const override; virtual bool doResolve(DbContext & context) override; virtual ref< Node > getProperty(DbContext & context, const inamespace& propertyName) const override; virtual void doEval(const Type& expectedType, Value& result) const override; virtual void doVisit(Node::Visitor & visitor) const override; public: Object(ref< Reference > className, const minitl::vector< ref< Parameter > >& parameters); ~Object(); Type getType() const; bool getPropertyType(DbContext & context, const istring propertyName, Type& propertyType) const; weak< const Parameter > getParameter(const istring name) const; }; }}} // namespace BugEngine::Meta::AST /**************************************************************************************************/ #endif
35.333333
100
0.642558
[ "object", "vector" ]
5363ac2e480a553846680aa14bce44e118026146
4,532
cpp
C++
src/Hum2D/SFML/SFMLPlugin.cpp
Galbar/Hummingbird2D-SFML
a48ab0056f9db4f5862eeb9c7d4e5c59b9834129
[ "MIT" ]
null
null
null
src/Hum2D/SFML/SFMLPlugin.cpp
Galbar/Hummingbird2D-SFML
a48ab0056f9db4f5862eeb9c7d4e5c59b9834129
[ "MIT" ]
null
null
null
src/Hum2D/SFML/SFMLPlugin.cpp
Galbar/Hummingbird2D-SFML
a48ab0056f9db4f5862eeb9c7d4e5c59b9834129
[ "MIT" ]
null
null
null
#include <map> #include "Hum2D/Hum2D.hpp" #include "SFMLPlugin.hpp" #include "Drawable.hpp" using namespace h2d; SFMLPlugin::SFMLPlugin(int window_width, int window_height, std::string window_title): p_window_width(window_width), p_window_height(window_height), p_window_title(window_title) {} SFMLPlugin::~SFMLPlugin() {} sf::RenderWindow& SFMLPlugin::window() { return *p_window; } const sf::RenderWindow& SFMLPlugin::window() const { return *p_window; } void SFMLPlugin::gameStart() { p_window = new sf::RenderWindow(sf::VideoMode(p_window_width, p_window_height), p_window_title); } void SFMLPlugin::preFixedUpdate() { p_sound_manager.clearSounds(); p_input.update(); sf::Event event; while (p_window->pollEvent(event)) { if (event.type == sf::Event::Closed) { p_window->close(); game().setRunning(false); } p_input.handleEvent(event); p_event_list.push_back(event); } } void SFMLPlugin::postFixedUpdate() { p_event_list.clear(); } void SFMLPlugin::postUpdate() { p_window->clear(); std::multimap<double, std::pair<const sf::Drawable*, const sf::Shader*>> draw_order; for (Drawable* drawable : p_drawable_set) { sf::Drawable* sf_drawable = drawable->sfDrawable(); sf::Transformable* sf_transform = drawable->sfTransformable(); Transformation drawable_transform = drawable->transform(); if (sf_transform != nullptr) { const Kinematic* kinematic = p_drawable_kinematic[drawable]; const Transformation* actor_transform; if (kinematic != nullptr) { actor_transform = new Transformation(kinematic->simulate(game().fixedUpdateLag())); } else { actor_transform = &drawable->actor().transform(); } drawable_transform.x += actor_transform->x; drawable_transform.y += actor_transform->y; drawable_transform.z += actor_transform->z; drawable_transform.rotation += actor_transform->rotation; drawable_transform.scale_x *= actor_transform->scale_x; drawable_transform.scale_y *= actor_transform->scale_y; sf_transform->setPosition(drawable_transform.x, drawable_transform.y); sf_transform->setRotation(drawable_transform.rotation); sf_transform->setScale(drawable_transform.scale_x, drawable_transform.scale_y); if (kinematic != nullptr) { delete actor_transform; } } draw_order.insert(std::make_pair(drawable_transform.z, std::make_pair(sf_drawable, drawable->shader()))); } for (auto it = draw_order.begin(); it != draw_order.end(); ++it) { std::pair<const sf::Drawable*, const sf::Shader*>& data = it->second; if (data.second == nullptr) { p_window->draw(*data.first); } else { p_window->draw(*data.first, data.second); } } p_window->display(); } void SFMLPlugin::gameEnd() { p_window->close(); delete p_window; p_window = nullptr; } const std::vector<sf::Event> SFMLPlugin::getEvents() const { return p_event_list; } const InputHandler& SFMLPlugin::input() const { return p_input; } InputHandler& SFMLPlugin::input() { return p_input; } TextureManager& SFMLPlugin::textures() { return p_texture_manager; } const TextureManager& SFMLPlugin::textures() const { return p_texture_manager; } SpriteAnimationManager& SFMLPlugin::spriteAnimations() { return p_sprite_animation_manager; } const SpriteAnimationManager& SFMLPlugin::spriteAnimations() const { return p_sprite_animation_manager; } SoundManager& SFMLPlugin::sounds() { return p_sound_manager; } const SoundManager& SFMLPlugin::sounds() const { return p_sound_manager; } MusicManager& SFMLPlugin::music() { return p_music_manager; } const MusicManager& SFMLPlugin::music() const { return p_music_manager; } void SFMLPlugin::addDrawable(Drawable* drawable) { p_drawable_set.insert(drawable); try { p_drawable_kinematic[drawable] = drawable->actor().getBehavior<Kinematic>(); } catch (exception::BehaviorNotFound e) { p_drawable_kinematic[drawable] = nullptr; } } void SFMLPlugin::removeDrawable(Drawable* drawable) { p_drawable_set.erase(drawable); p_drawable_kinematic.erase(drawable); }
24.365591
113
0.654898
[ "vector", "transform" ]
53668cb2d91a40a8bdeb14580c743cbf46086afa
6,548
cpp
C++
src/call.cpp
apfeltee/ici
52019325f18c664060484e9ff400df650c430d66
[ "MIT" ]
null
null
null
src/call.cpp
apfeltee/ici
52019325f18c664060484e9ff400df650c430d66
[ "MIT" ]
null
null
null
src/call.cpp
apfeltee/ici
52019325f18c664060484e9ff400df650c430d66
[ "MIT" ]
null
null
null
#define ICI_CORE #include "priv.h" namespace ici { int callv(Object* subject, Object* callable, const char* types, va_list va) { long nargs; long arg; Object* member_obj; Object* ret_obj; char ret_type; char* ret_ptr; ptrdiff_t os_depth; OpCode* call_op; if(types[0] != '\0' && types[1] == '@') { member_obj = va_arg(va, Object*); types += 2; } else { member_obj = nullptr; } if(types[0] != '\0' && types[1] == '=') { ret_type = types[0]; ret_ptr = va_arg(va, char*); types += 2; } else { ret_type = '\0'; ret_ptr = nullptr; } os_depth = g_opstack.a_top - g_opstack.a_base; /* * We include an extra 80 in our push_check, see start of evaluate(). */ nargs = strlen(types); if(g_opstack.push_check(nargs + 80)) { return 1; } for(arg = 0; arg < nargs; ++arg) { g_opstack.push(null); } for(arg = -1; arg >= -nargs; arg--) { switch(*types++) { case 'o': g_opstack.a_top[arg] = va_arg(va, Object*); break; case 'i': if((g_opstack.a_top[arg] = createIntNum(va_arg(va, long))) == nullptr) { goto fail; } g_opstack.a_top[arg]->decref(); break; case 'q': g_opstack.a_top[arg] = &o_quote; nargs--; break; case 's': if((g_opstack.a_top[arg] = String::create(va_arg(va, char*))) == nullptr) { goto fail; } g_opstack.a_top[arg]->decref(); break; case 'f': if((g_opstack.a_top[arg] = createFloatNum(va_arg(va, double))) == nullptr) { goto fail; } g_opstack.a_top[arg]->decref(); break; default: setError("error in function call"); goto fail; } } if(member_obj != nullptr) { g_opstack.push(member_obj); nargs++; } /* * Push the number of actual args, followed by the function * itself onto the operand stack. */ { auto no = createIntNum(nargs); if(!no) goto fail; g_opstack.push(no, with_decref); } if(subject != nullptr) { g_opstack.push(subject); } g_opstack.push(callable); os_depth = (g_opstack.a_top - g_opstack.a_base) - os_depth; call_op = subject != nullptr ? &o_method_call : &o_call; if((ret_obj = evaluate(call_op, os_depth)) == nullptr) { goto fail; } switch(ret_type) { case '\0': ret_obj->decref(); break; case 'o': *(Object**)ret_ptr = ret_obj; break; case 'i': if(!ret_obj->isIntNum()) { goto typeclash; } *(long*)ret_ptr = ret_obj->toIntNum()->i_value; ret_obj->decref(); break; case 'f': if(!ret_obj->isFloatNum()) { goto typeclash; } *(double*)ret_ptr = ret_obj->toFloatNum()->f_value; ret_obj->decref(); break; case 's': if(!ret_obj->isString()) { goto typeclash; } *(const char**)ret_ptr = ret_obj->toStringObject()->cstr(); ret_obj->decref(); break; default: typeclash: ret_obj->decref(); setError("incorrect return type"); goto fail; } return 0; fail: return 1; } int callv(String* func_name, const char* types, va_list va) { Object* func_obj; Object* member_obj; func_obj = nullptr; if(types[0] != '\0' && types[1] == '@') { va_list tmp; va_copy(tmp, va); member_obj = va_arg(tmp, Object*); if((func_obj = member_obj->fetch(func_name)) == null) { return setError("\"%s\" undefined in Object", func_name->cstr()); } va_end(tmp); } else if((func_obj = currentScope()->fetch(func_name)) == null) { return setError("\"%s\" undefined", func_name->cstr()); } return callv((Object*)nullptr, func_obj, types, va); } int call(Object* callable, const char* types, ...) { va_list va; int result; va_start(va, types); result = callv((Object*)nullptr, callable, types, va); va_end(va); return result; } int call_method(Object* inst, String* mname, const char* types, ...) { va_list va; int result; va_start(va, types); result = callv(inst, mname, types, va); va_end(va); return result; } int call(String* func_name, const char* types, ...) { Object* func_obj; Object* member_obj; va_list va; int result; func_obj = nullptr; if(types[0] != '\0' && types[1] == '@') { va_start(va, types); member_obj = va_arg(va, Object*); if((func_obj = member_obj->fetch(func_name)) == null) { return setError("\"%s\" undefined in Object", func_name->cstr()); } } else if((func_obj = currentScope()->fetch(func_name)) == null) { return setError("\"%s\" undefined", func_name->cstr()); } va_start(va, types); result = callv((Object*)nullptr, func_obj, types, va); va_end(va); return result; } }// namespace ici
26.192
94
0.420892
[ "object" ]
537941904e8121a3a5ef9aefce27c1ee37aac859
533
cpp
C++
04. Computation/Dislicked_Words_Bleep/Source.cpp
Dominent/Programming-Principles-and-Practice
664ab5246dc4197584fa2b1a86ea3c8b800d5de4
[ "MIT" ]
null
null
null
04. Computation/Dislicked_Words_Bleep/Source.cpp
Dominent/Programming-Principles-and-Practice
664ab5246dc4197584fa2b1a86ea3c8b800d5de4
[ "MIT" ]
null
null
null
04. Computation/Dislicked_Words_Bleep/Source.cpp
Dominent/Programming-Principles-and-Practice
664ab5246dc4197584fa2b1a86ea3c8b800d5de4
[ "MIT" ]
null
null
null
// Write a program that "bleeps" out words you dislike. #include <iostream> #include <vector> #include <string> using namespace std; int main(int argc, char* argv[]) { vector<string> words; cout << "Enter words: "; for (string word; cin >> word;) { words.push_back(word); } string dislicked_words[] = { "Broccoli", "Papper", "Tomatoes", "Cucumber" }; for (string word : words) { for (string dislicked_word : dislicked_words) { if(word == dislicked_word) { cout << "Bleep\n"; } } } return 0; }
15.228571
78
0.626642
[ "vector" ]
537b33a7cd835484f2cf23ec314dc7b71cd6e0a2
1,812
cpp
C++
SoftRendering/Grid.cpp
RIVER1016/SoftRendering
1dec26cb4551c1978df0f17a1123da6107de1837
[ "MIT" ]
null
null
null
SoftRendering/Grid.cpp
RIVER1016/SoftRendering
1dec26cb4551c1978df0f17a1123da6107de1837
[ "MIT" ]
1
2020-03-21T11:42:54.000Z
2020-03-21T11:44:08.000Z
SoftRendering/Grid.cpp
RIVER1016/SoftRendering
1dec26cb4551c1978df0f17a1123da6107de1837
[ "MIT" ]
null
null
null
#pragma once #include "Grid.h" #include <windows.h> #include <math.h> #define PI 3.1415926f void GridBuffer::init( Device* d, const Vector& origin, const float& s, const int& w, const int& h ) { device = d; width = w + 1; height = h + 1; side = s; Vector** gb; gb = new Vector *[width]; for ( int j = 0; j < width; j ++ ) { gb[j] = new Vector [height]; } for ( int i = 0; i < width; i ++ ) { for ( int j = 0; j < height; j ++ ) { Vector g = origin + Vector( i * side, 0.f, j * side ); gb[i][j] = g; } } gridBuffer = gb; } void GridBuffer::setUp( const float& u ) { for ( int i = 0; i < width; i ++ ) { for ( int j = 0; j < height; j ++ ) { gridBuffer[i][j].y = u; } } } void GridBuffer::draw( ) { for ( int i = 0; i < width - 1; i ++ ) { for( int j = 0; j < height; j ++ ) { Vector bottom = gridBuffer[i][j]; Vector bottomL = gridBuffer[i + 1][j]; Vector top = gridBuffer[i + 1][j + 1]; Vector topR = gridBuffer[i][j + 1]; Vector green = Vector( 0.f, 1.f, 0.f ); Vertex p1 = Vertex( bottom, green, Vector( ) ); Vertex p2 = Vertex( bottomL, green, Vector( ) ); Vertex p3 = Vertex( topR, green, Vector( ) ); Vertex p4 = Vertex( top, green, Vector( ) ); device->drawLine3D( p1, p2 ); device->drawLine3D( p2, p4 ); device->drawLine3D( p1, p3 ); device->drawLine3D( p3, p4 ); } } } void GridBuffer::setCircleUp( ) { float r = 1.f; for ( int i = 0; i < width; i ++ ) { r = 0.f; for ( int j = 0; j < height; j ++ ) { float div = ( float )j / ( float )height; float y = 2.f * sin( div * PI ); gridBuffer[i][j].y = y; } } } void GridBuffer::setRandomUp( ) { for ( int i = 0; i < width; i ++ ) { for ( int j = 0; j < height; j ++ ) { int y = rand( ) % 3; gridBuffer[i][j].y = ( float )y; } } }
20.133333
100
0.524283
[ "vector" ]
537b600cd7547ba0b7f779f1625c1bc7a0e18fa7
681
cpp
C++
Codeforces/Codeforces Round 280 (Div 2)/Vanya and Lanterns.cpp
UtkarshPathrabe/Competitive-Coding
ba322fbb1b88682d56a9b80bdd92a853f1caa84e
[ "MIT" ]
13
2021-09-02T07:30:02.000Z
2022-03-22T19:32:03.000Z
Codeforces/Codeforces Round 280 (Div 2)/Vanya and Lanterns.cpp
UtkarshPathrabe/Competitive-Coding
ba322fbb1b88682d56a9b80bdd92a853f1caa84e
[ "MIT" ]
null
null
null
Codeforces/Codeforces Round 280 (Div 2)/Vanya and Lanterns.cpp
UtkarshPathrabe/Competitive-Coding
ba322fbb1b88682d56a9b80bdd92a853f1caa84e
[ "MIT" ]
3
2021-08-24T16:06:22.000Z
2021-09-17T15:39:53.000Z
/* Author: Utkarsh Pathrabe * Question can be found at http://codeforces.com/contest/492/problem/B * Algorithms: Math and Sorting */ #include <bits/stdc++.h> using namespace std; vector <double> pos; vector <double>::iterator it; int main(void) { int n; double l, d, maximum, prev, a; scanf("%d %lf", &n, &l); for(int i = 0; i < n; i++) { scanf("%lf", &a); pos.push_back(a); } sort(pos.begin(), pos.end()); it = pos.begin(); prev = 0 - *(it); maximum = (*(it)) * 2; for(; it != pos.end(); it++) { maximum = max(maximum, *(it) - prev); prev = *(it); } maximum = max(maximum, (l - prev) * 2); d = (double) maximum / 2.0; printf("%lf\n", d); return 0; }
20.029412
72
0.572687
[ "vector" ]
538a28ab597d3f7a13f43e32db05156b9c2cd89e
1,605
hpp
C++
model_polyfit.hpp
naughtysucker/naughty_polyfit
7923db70cd2717e4575e921b4f7700c312bd6ef5
[ "Apache-2.0" ]
null
null
null
model_polyfit.hpp
naughtysucker/naughty_polyfit
7923db70cd2717e4575e921b4f7700c312bd6ef5
[ "Apache-2.0" ]
null
null
null
model_polyfit.hpp
naughtysucker/naughty_polyfit
7923db70cd2717e4575e921b4f7700c312bd6ef5
[ "Apache-2.0" ]
null
null
null
/* ***************************************************************************** * @ Encoding: UTF-8 * @ File Name: model_polyfit.hpp * @ Author: gengjinhong * @ Email: 2560295278@qq.com * @ Created Time: 2021-Nov-02(Tuesday) 14:41:42 * @ SPDX-License-Identifier: Apache-2.0 * *****************************************************************************/ #ifndef MODEL_POLYFIT_HPP #define MODEL_POLYFIT_HPP #include "model_base.hpp" #include "naughty_random_descent.hpp" #include <cassert> #include "Eigen/Core" #include "Eigen/Dense" namespace naughty { class model_polyfit : public model_base { private: std::vector<std::pair<double, double>> m_points; size_t m_dimension; std::random_device m_random_device; std::default_random_engine m_random_engine{m_random_device()}; std::uniform_int_distribution<> m_random_int_distribution; public: model_polyfit(size_t); size_t get_dimension() override; double loss(const std::vector<double>&) override; std::vector<std::pair<double, double>> get_init_limits() override; std::vector<double> get_init_steps() override; std::vector<double> get_step_increase_rate() override; std::vector<double> get_step_decrease_rate() override; int32_t set_points(const std::vector<std::pair<double, double>>& points); double polyfit_func(std::vector<double> vars, double x); double polyfit_calculate_offset(std::vector<double> vars); std::vector<std::pair<double, double>> get_average_limits(std::vector<std::vector<double>> vars); std::vector<double> get_result(std::vector<std::pair<double, double>> xys); }; } #endif
29.181818
99
0.672274
[ "vector" ]
538b8175febbd1fd5da1abe5072ad03e7c36693e
306
cpp
C++
CodeChef/Beginner/CHEFDETE.cpp
nsudhanva/Competetive
d9e93fdeefaa4e422a2101db41a7ab0a5676e9da
[ "Unlicense" ]
null
null
null
CodeChef/Beginner/CHEFDETE.cpp
nsudhanva/Competetive
d9e93fdeefaa4e422a2101db41a7ab0a5676e9da
[ "Unlicense" ]
null
null
null
CodeChef/Beginner/CHEFDETE.cpp
nsudhanva/Competetive
d9e93fdeefaa4e422a2101db41a7ab0a5676e9da
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> a(n); vector<bool> r(n + 1, false); for (int i = 0; i < n; ++i) { cin >> a[i]; r[a[i]] = true; } for (int i = 0; i < n + 1; ++i) { if(r[i] == false){ cout << i << " "; } } cout << endl; }
10.928571
32
0.437908
[ "vector" ]
53937de7ac2c98b162630f588b770a0572d94286
32,802
cpp
C++
Source/JavaScriptCore/runtime/JSONObject.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/JavaScriptCore/runtime/JSONObject.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/JavaScriptCore/runtime/JSONObject.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2009-2020 Apple Inc. All rights reserved. * Copyright (C) 2020 Alexey Shvayka <shvaikalesh@gmail.com>. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "JSONObject.h" #include "ArrayConstructor.h" #include "BigIntObject.h" #include "BooleanObject.h" #include "JSArrayInlines.h" #include "JSCInlines.h" #include "LiteralParser.h" #include "ObjectConstructor.h" #include "PropertyNameArray.h" #include "VMInlines.h" #include <wtf/text/StringBuilder.h> namespace JSC { STATIC_ASSERT_IS_TRIVIALLY_DESTRUCTIBLE(JSONObject); EncodedJSValue JSC_HOST_CALL JSONProtoFuncParse(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL JSONProtoFuncStringify(JSGlobalObject*, CallFrame*); } #include "JSONObject.lut.h" namespace JSC { JSONObject::JSONObject(VM& vm, Structure* structure) : JSNonFinalObject(vm, structure) { } void JSONObject::finishCreation(VM& vm) { Base::finishCreation(vm); ASSERT(inherits(vm, info())); JSC_TO_STRING_TAG_WITHOUT_TRANSITION(); } // PropertyNameForFunctionCall objects must be on the stack, since the JSValue that they create is not marked. class PropertyNameForFunctionCall { public: PropertyNameForFunctionCall(const Identifier&); PropertyNameForFunctionCall(unsigned); JSValue value(JSGlobalObject*) const; private: const Identifier* m_identifier; unsigned m_number; mutable JSValue m_value; }; class Stringifier { WTF_MAKE_NONCOPYABLE(Stringifier); WTF_FORBID_HEAP_ALLOCATION; public: Stringifier(JSGlobalObject*, JSValue replacer, JSValue space); JSValue stringify(JSValue); private: class Holder { public: enum RootHolderTag { RootHolder }; Holder(JSGlobalObject*, JSObject*); Holder(RootHolderTag, JSObject*); JSObject* object() const { return m_object; } bool isArray() const { return m_isArray; } bool appendNextProperty(Stringifier&, StringBuilder&); private: JSObject* m_object; const bool m_isJSArray; const bool m_isArray; unsigned m_index { 0 }; unsigned m_size { 0 }; RefPtr<PropertyNameArrayData> m_propertyNames; }; friend class Holder; JSValue toJSON(JSValue, const PropertyNameForFunctionCall&); enum StringifyResult { StringifyFailed, StringifySucceeded, StringifyFailedDueToUndefinedOrSymbolValue }; StringifyResult appendStringifiedValue(StringBuilder&, JSValue, const Holder&, const PropertyNameForFunctionCall&); bool willIndent() const; void indent(); void unindent(); void startNewLine(StringBuilder&) const; bool isCallableReplacer() const { return m_replacerCallData.type != CallData::Type::None; } JSGlobalObject* const m_globalObject; JSValue m_replacer; bool m_usingArrayReplacer { false }; PropertyNameArray m_arrayReplacerPropertyNames; CallData m_replacerCallData; String m_gap; MarkedArgumentBuffer m_objectStack; Vector<Holder, 16, UnsafeVectorOverflow> m_holderStack; String m_repeatedGap; String m_indent; }; // ------------------------------ helper functions -------------------------------- static inline JSValue unwrapBoxedPrimitive(JSGlobalObject* globalObject, JSValue value) { VM& vm = globalObject->vm(); if (!value.isObject()) return value; JSObject* object = asObject(value); if (object->inherits<NumberObject>(vm)) return jsNumber(object->toNumber(globalObject)); if (object->inherits<StringObject>(vm)) return object->toString(globalObject); if (object->inherits<BooleanObject>(vm) || object->inherits<BigIntObject>(vm)) return jsCast<JSWrapperObject*>(object)->internalValue(); // Do not unwrap SymbolObject to Symbol. It is not performed in the spec. // http://www.ecma-international.org/ecma-262/6.0/#sec-serializejsonproperty return value; } static inline String gap(JSGlobalObject* globalObject, JSValue space) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); const unsigned maxGapLength = 10; space = unwrapBoxedPrimitive(globalObject, space); RETURN_IF_EXCEPTION(scope, { }); // If the space value is a number, create a gap string with that number of spaces. if (space.isNumber()) { double spaceCount = space.asNumber(); int count; if (spaceCount > maxGapLength) count = maxGapLength; else if (!(spaceCount > 0)) count = 0; else count = static_cast<int>(spaceCount); char spaces[maxGapLength]; for (int i = 0; i < count; ++i) spaces[i] = ' '; return String(spaces, count); } // If the space value is a string, use it as the gap string, otherwise use no gap string. String spaces = space.getString(globalObject); RETURN_IF_EXCEPTION(scope, { }); if (spaces.length() <= maxGapLength) return spaces; return spaces.substringSharingImpl(0, maxGapLength); } // ------------------------------ PropertyNameForFunctionCall -------------------------------- inline PropertyNameForFunctionCall::PropertyNameForFunctionCall(const Identifier& identifier) : m_identifier(&identifier) { } inline PropertyNameForFunctionCall::PropertyNameForFunctionCall(unsigned number) : m_identifier(nullptr) , m_number(number) { } JSValue PropertyNameForFunctionCall::value(JSGlobalObject* globalObject) const { if (!m_value) { VM& vm = globalObject->vm(); if (m_identifier) m_value = jsString(vm, m_identifier->string()); else { if (m_number <= 9) return vm.smallStrings.singleCharacterString(m_number + '0'); m_value = jsNontrivialString(vm, vm.numericStrings.add(m_number)); } } return m_value; } // ------------------------------ Stringifier -------------------------------- Stringifier::Stringifier(JSGlobalObject* globalObject, JSValue replacer, JSValue space) : m_globalObject(globalObject) , m_replacer(replacer) , m_arrayReplacerPropertyNames(globalObject->vm(), PropertyNameMode::Strings, PrivateSymbolMode::Exclude) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); if (m_replacer.isObject()) { JSObject* replacerObject = asObject(m_replacer); m_replacerCallData = getCallData(vm, replacerObject); if (m_replacerCallData.type == CallData::Type::None) { bool isArrayReplacer = JSC::isArray(globalObject, replacerObject); RETURN_IF_EXCEPTION(scope, ); if (isArrayReplacer) { m_usingArrayReplacer = true; uint64_t length = static_cast<uint64_t>(toLength(globalObject, replacerObject)); RETURN_IF_EXCEPTION(scope, ); for (uint64_t index = 0; index < length; ++index) { JSValue name; if (isJSArray(replacerObject) && replacerObject->canGetIndexQuickly(index)) name = replacerObject->getIndexQuickly(static_cast<uint32_t>(index)); else { name = replacerObject->get(globalObject, index); RETURN_IF_EXCEPTION(scope, ); } if (name.isObject()) { auto* nameObject = jsCast<JSObject*>(name); if (!nameObject->inherits<NumberObject>(vm) && !nameObject->inherits<StringObject>(vm)) continue; } else if (!name.isNumber() && !name.isString()) continue; JSString* propertyNameString = name.toString(globalObject); RETURN_IF_EXCEPTION(scope, ); auto propertyName = propertyNameString->toIdentifier(globalObject); RETURN_IF_EXCEPTION(scope, ); m_arrayReplacerPropertyNames.add(WTFMove(propertyName)); } } } } scope.release(); m_gap = gap(globalObject, space); } JSValue Stringifier::stringify(JSValue value) { VM& vm = m_globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); PropertyNameForFunctionCall emptyPropertyName(vm.propertyNames->emptyIdentifier); // If the replacer is not callable, root object wrapper is non-user-observable. // We can skip creating this wrapper object. JSObject* object = nullptr; if (isCallableReplacer()) { object = constructEmptyObject(m_globalObject); object->putDirect(vm, vm.propertyNames->emptyIdentifier, value); } StringBuilder result(StringBuilder::OverflowHandler::RecordOverflow); Holder root(Holder::RootHolder, object); auto stringifyResult = appendStringifiedValue(result, value, root, emptyPropertyName); RETURN_IF_EXCEPTION(scope, jsUndefined()); if (UNLIKELY(result.hasOverflowed())) { throwOutOfMemoryError(m_globalObject, scope); return jsUndefined(); } if (UNLIKELY(stringifyResult != StringifySucceeded)) return jsUndefined(); RELEASE_AND_RETURN(scope, jsString(vm, result.toString())); } ALWAYS_INLINE JSValue Stringifier::toJSON(JSValue baseValue, const PropertyNameForFunctionCall& propertyName) { VM& vm = m_globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); scope.assertNoException(); JSValue toJSONFunction = baseValue.get(m_globalObject, vm.propertyNames->toJSON); RETURN_IF_EXCEPTION(scope, { }); auto callData = getCallData(vm, toJSONFunction); if (callData.type == CallData::Type::None) return baseValue; MarkedArgumentBuffer args; args.append(propertyName.value(m_globalObject)); ASSERT(!args.hasOverflowed()); RELEASE_AND_RETURN(scope, call(m_globalObject, asObject(toJSONFunction), callData, baseValue, args)); } // We clamp recursion well beyond anything reasonable. constexpr unsigned maximumSideStackRecursion = 40000; Stringifier::StringifyResult Stringifier::appendStringifiedValue(StringBuilder& builder, JSValue value, const Holder& holder, const PropertyNameForFunctionCall& propertyName) { VM& vm = m_globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); // Recursion is avoided by !holderStackWasEmpty check and do/while loop at the end of this method. // We're having this recursion check here as a fail safe in case the code // below get modified such that recursion is no longer avoided. if (UNLIKELY(!vm.isSafeToRecurseSoft())) { throwStackOverflowError(m_globalObject, scope); return StringifyFailed; } // Call the toJSON function. if (value.isObject() || value.isBigInt()) { value = toJSON(value, propertyName); RETURN_IF_EXCEPTION(scope, StringifyFailed); } // Call the replacer function. if (isCallableReplacer()) { MarkedArgumentBuffer args; args.append(propertyName.value(m_globalObject)); args.append(value); ASSERT(!args.hasOverflowed()); ASSERT(holder.object()); value = call(m_globalObject, m_replacer, m_replacerCallData, holder.object(), args); RETURN_IF_EXCEPTION(scope, StringifyFailed); } if ((value.isUndefined() || value.isSymbol()) && !holder.isArray()) return StringifyFailedDueToUndefinedOrSymbolValue; if (value.isNull()) { builder.appendLiteral("null"); return StringifySucceeded; } value = unwrapBoxedPrimitive(m_globalObject, value); RETURN_IF_EXCEPTION(scope, StringifyFailed); if (value.isBoolean()) { if (value.isTrue()) builder.appendLiteral("true"); else builder.appendLiteral("false"); return StringifySucceeded; } if (value.isString()) { const String& string = asString(value)->value(m_globalObject); RETURN_IF_EXCEPTION(scope, StringifyFailed); builder.appendQuotedJSONString(string); return StringifySucceeded; } if (value.isNumber()) { if (value.isInt32()) builder.appendNumber(value.asInt32()); else { double number = value.asNumber(); if (!std::isfinite(number)) builder.appendLiteral("null"); else builder.appendNumber(number); } return StringifySucceeded; } if (value.isBigInt()) { throwTypeError(m_globalObject, scope, "JSON.stringify cannot serialize BigInt."_s); return StringifyFailed; } if (!value.isObject()) return StringifyFailed; JSObject* object = asObject(value); if (object->isCallable(vm)) { if (holder.isArray()) { builder.appendLiteral("null"); return StringifySucceeded; } return StringifyFailedDueToUndefinedOrSymbolValue; } if (UNLIKELY(builder.hasOverflowed())) return StringifyFailed; // Handle cycle detection, and put the holder on the stack. for (unsigned i = 0; i < m_holderStack.size(); i++) { if (m_holderStack[i].object() == object) { throwTypeError(m_globalObject, scope, "JSON.stringify cannot serialize cyclic structures."_s); return StringifyFailed; } } if (UNLIKELY(m_holderStack.size() >= maximumSideStackRecursion)) { throwStackOverflowError(m_globalObject, scope); return StringifyFailed; } bool holderStackWasEmpty = m_holderStack.isEmpty(); m_holderStack.append(Holder(m_globalObject, object)); m_objectStack.appendWithCrashOnOverflow(object); RETURN_IF_EXCEPTION(scope, StringifyFailed); if (!holderStackWasEmpty) return StringifySucceeded; do { while (m_holderStack.last().appendNextProperty(*this, builder)) RETURN_IF_EXCEPTION(scope, StringifyFailed); RETURN_IF_EXCEPTION(scope, StringifyFailed); if (UNLIKELY(builder.hasOverflowed())) return StringifyFailed; m_holderStack.removeLast(); m_objectStack.removeLast(); } while (!m_holderStack.isEmpty()); return StringifySucceeded; } inline bool Stringifier::willIndent() const { return !m_gap.isEmpty(); } inline void Stringifier::indent() { // Use a single shared string, m_repeatedGap, so we don't keep allocating new ones as we indent and unindent. unsigned newSize = m_indent.length() + m_gap.length(); if (newSize > m_repeatedGap.length()) m_repeatedGap = makeString(m_repeatedGap, m_gap); ASSERT(newSize <= m_repeatedGap.length()); m_indent = m_repeatedGap.substringSharingImpl(0, newSize); } inline void Stringifier::unindent() { ASSERT(m_indent.length() >= m_gap.length()); m_indent = m_repeatedGap.substringSharingImpl(0, m_indent.length() - m_gap.length()); } inline void Stringifier::startNewLine(StringBuilder& builder) const { if (m_gap.isEmpty()) return; builder.append('\n'); builder.append(m_indent); } inline Stringifier::Holder::Holder(JSGlobalObject* globalObject, JSObject* object) : m_object(object) , m_isJSArray(isJSArray(object)) , m_isArray(JSC::isArray(globalObject, object)) { } inline Stringifier::Holder::Holder(RootHolderTag, JSObject* object) : m_object(object) , m_isJSArray(false) , m_isArray(false) { } bool Stringifier::Holder::appendNextProperty(Stringifier& stringifier, StringBuilder& builder) { ASSERT(m_index <= m_size); JSGlobalObject* globalObject = stringifier.m_globalObject; VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); // First time through, initialize. if (!m_index) { if (m_isArray) { uint64_t length = static_cast<uint64_t>(toLength(globalObject, m_object)); RETURN_IF_EXCEPTION(scope, false); if (UNLIKELY(length > std::numeric_limits<uint32_t>::max())) { throwOutOfMemoryError(globalObject, scope); return false; } m_size = static_cast<uint32_t>(length); RETURN_IF_EXCEPTION(scope, false); builder.append('['); } else { if (stringifier.m_usingArrayReplacer) m_propertyNames = stringifier.m_arrayReplacerPropertyNames.data(); else { PropertyNameArray objectPropertyNames(vm, PropertyNameMode::Strings, PrivateSymbolMode::Exclude); m_object->methodTable(vm)->getOwnPropertyNames(m_object, globalObject, objectPropertyNames, EnumerationMode()); RETURN_IF_EXCEPTION(scope, false); m_propertyNames = objectPropertyNames.releaseData(); } m_size = m_propertyNames->propertyNameVector().size(); builder.append('{'); } stringifier.indent(); } if (UNLIKELY(builder.hasOverflowed())) return false; // Last time through, finish up and return false. if (m_index == m_size) { stringifier.unindent(); if (m_size && builder[builder.length() - 1] != '{') stringifier.startNewLine(builder); builder.append(m_isArray ? ']' : '}'); return false; } // Handle a single element of the array or object. unsigned index = m_index++; unsigned rollBackPoint = 0; StringifyResult stringifyResult; if (m_isArray) { // Get the value. JSValue value; if (m_isJSArray && m_object->canGetIndexQuickly(index)) value = m_object->getIndexQuickly(index); else { value = m_object->get(globalObject, index); RETURN_IF_EXCEPTION(scope, false); } // Append the separator string. if (index) builder.append(','); stringifier.startNewLine(builder); // Append the stringified value. stringifyResult = stringifier.appendStringifiedValue(builder, value, *this, index); ASSERT(stringifyResult != StringifyFailedDueToUndefinedOrSymbolValue); } else { // Get the value. Identifier& propertyName = m_propertyNames->propertyNameVector()[index]; JSValue value = m_object->get(globalObject, propertyName); RETURN_IF_EXCEPTION(scope, false); rollBackPoint = builder.length(); // Append the separator string. if (builder[rollBackPoint - 1] != '{') builder.append(','); stringifier.startNewLine(builder); // Append the property name. builder.appendQuotedJSONString(propertyName.string()); builder.append(':'); if (stringifier.willIndent()) builder.append(' '); // Append the stringified value. stringifyResult = stringifier.appendStringifiedValue(builder, value, *this, propertyName); } RETURN_IF_EXCEPTION(scope, false); // From this point on, no access to the this pointer or to any members, because the // Holder object may have moved if the call to stringify pushed a new Holder onto // m_holderStack. switch (stringifyResult) { case StringifyFailed: builder.appendLiteral("null"); break; case StringifySucceeded: break; case StringifyFailedDueToUndefinedOrSymbolValue: // This only occurs when get an undefined value or a symbol value for // an object property. In this case we don't want the separator and // property name that we already appended, so roll back. builder.resize(rollBackPoint); break; } return true; } // ------------------------------ JSONObject -------------------------------- const ClassInfo JSONObject::s_info = { "JSON", &JSNonFinalObject::s_info, &jsonTable, nullptr, CREATE_METHOD_TABLE(JSONObject) }; /* Source for JSONObject.lut.h @begin jsonTable parse JSONProtoFuncParse DontEnum|Function 2 stringify JSONProtoFuncStringify DontEnum|Function 3 @end */ // ECMA 15.8 class Walker { WTF_MAKE_NONCOPYABLE(Walker); WTF_FORBID_HEAP_ALLOCATION; public: Walker(JSGlobalObject* globalObject, JSObject* function, CallData callData) : m_globalObject(globalObject) , m_function(function) , m_callData(callData) { } JSValue walk(JSValue unfiltered); private: JSValue callReviver(JSObject* thisObj, JSValue property, JSValue unfiltered) { MarkedArgumentBuffer args; args.append(property); args.append(unfiltered); ASSERT(!args.hasOverflowed()); return call(m_globalObject, m_function, m_callData, thisObj, args); } friend class Holder; JSGlobalObject* m_globalObject; JSObject* m_function; CallData m_callData; }; enum WalkerState { StateUnknown, ArrayStartState, ArrayStartVisitMember, ArrayEndVisitMember, ObjectStartState, ObjectStartVisitMember, ObjectEndVisitMember }; NEVER_INLINE JSValue Walker::walk(JSValue unfiltered) { VM& vm = m_globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); Vector<PropertyNameArray, 16, UnsafeVectorOverflow> propertyStack; Vector<uint32_t, 16, UnsafeVectorOverflow> indexStack; MarkedArgumentBuffer markedStack; Vector<unsigned, 16, UnsafeVectorOverflow> arrayLengthStack; Vector<WalkerState, 16, UnsafeVectorOverflow> stateStack; WalkerState state = StateUnknown; JSValue inValue = unfiltered; JSValue outValue = jsNull(); while (1) { switch (state) { arrayStartState: case ArrayStartState: { ASSERT(inValue.isObject()); ASSERT(isArray(m_globalObject, inValue)); EXCEPTION_ASSERT(!scope.exception()); if (UNLIKELY(markedStack.size() >= maximumSideStackRecursion)) return throwStackOverflowError(m_globalObject, scope); JSObject* array = asObject(inValue); markedStack.appendWithCrashOnOverflow(array); uint64_t length = static_cast<uint64_t>(toLength(m_globalObject, array)); RETURN_IF_EXCEPTION(scope, { }); if (UNLIKELY(length > std::numeric_limits<uint32_t>::max())) { throwOutOfMemoryError(m_globalObject, scope); return { }; } RETURN_IF_EXCEPTION(scope, { }); arrayLengthStack.append(static_cast<uint32_t>(length)); indexStack.append(0); } arrayStartVisitMember: FALLTHROUGH; case ArrayStartVisitMember: { JSObject* array = asObject(markedStack.last()); uint32_t index = indexStack.last(); unsigned arrayLength = arrayLengthStack.last(); if (index == arrayLength) { outValue = array; markedStack.removeLast(); arrayLengthStack.removeLast(); indexStack.removeLast(); break; } if (isJSArray(array) && array->canGetIndexQuickly(index)) inValue = array->getIndexQuickly(index); else { inValue = array->get(m_globalObject, index); RETURN_IF_EXCEPTION(scope, { }); } if (inValue.isObject()) { stateStack.append(ArrayEndVisitMember); goto stateUnknown; } else outValue = inValue; FALLTHROUGH; } case ArrayEndVisitMember: { JSObject* array = asObject(markedStack.last()); JSValue filteredValue = callReviver(array, jsString(vm, String::number(indexStack.last())), outValue); RETURN_IF_EXCEPTION(scope, { }); if (filteredValue.isUndefined()) array->methodTable(vm)->deletePropertyByIndex(array, m_globalObject, indexStack.last()); else array->putDirectIndex(m_globalObject, indexStack.last(), filteredValue, 0, PutDirectIndexShouldNotThrow); RETURN_IF_EXCEPTION(scope, { }); indexStack.last()++; goto arrayStartVisitMember; } objectStartState: case ObjectStartState: { ASSERT(inValue.isObject()); ASSERT(!isJSArray(inValue)); if (UNLIKELY(markedStack.size() >= maximumSideStackRecursion)) return throwStackOverflowError(m_globalObject, scope); JSObject* object = asObject(inValue); markedStack.appendWithCrashOnOverflow(object); indexStack.append(0); propertyStack.append(PropertyNameArray(vm, PropertyNameMode::Strings, PrivateSymbolMode::Exclude)); object->methodTable(vm)->getOwnPropertyNames(object, m_globalObject, propertyStack.last(), EnumerationMode()); RETURN_IF_EXCEPTION(scope, { }); } objectStartVisitMember: FALLTHROUGH; case ObjectStartVisitMember: { JSObject* object = jsCast<JSObject*>(markedStack.last()); uint32_t index = indexStack.last(); PropertyNameArray& properties = propertyStack.last(); if (index == properties.size()) { outValue = object; markedStack.removeLast(); indexStack.removeLast(); propertyStack.removeLast(); break; } inValue = object->get(m_globalObject, properties[index]); // The holder may be modified by the reviver function so any lookup may throw RETURN_IF_EXCEPTION(scope, { }); if (inValue.isObject()) { stateStack.append(ObjectEndVisitMember); goto stateUnknown; } else outValue = inValue; FALLTHROUGH; } case ObjectEndVisitMember: { JSObject* object = jsCast<JSObject*>(markedStack.last()); Identifier prop = propertyStack.last()[indexStack.last()]; JSValue filteredValue = callReviver(object, jsString(vm, prop.string()), outValue); RETURN_IF_EXCEPTION(scope, { }); if (filteredValue.isUndefined()) JSCell::deleteProperty(object, m_globalObject, prop); else { unsigned attributes; PropertyOffset offset = object->getDirectOffset(vm, prop, attributes); if (LIKELY(offset != invalidOffset && attributes == static_cast<unsigned>(PropertyAttribute::None))) object->putDirect(vm, offset, filteredValue); else { PropertyDescriptor descriptor(filteredValue, static_cast<unsigned>(PropertyAttribute::None)); bool shouldThrow = false; object->methodTable(vm)->defineOwnProperty(object, m_globalObject, prop, descriptor, shouldThrow); } } RETURN_IF_EXCEPTION(scope, { }); indexStack.last()++; goto objectStartVisitMember; } stateUnknown: case StateUnknown: if (!inValue.isObject()) { outValue = inValue; break; } bool valueIsArray = isArray(m_globalObject, inValue); RETURN_IF_EXCEPTION(scope, { }); if (valueIsArray) goto arrayStartState; goto objectStartState; } if (stateStack.isEmpty()) break; state = stateStack.last(); stateStack.removeLast(); } JSObject* finalHolder = constructEmptyObject(m_globalObject); finalHolder->putDirect(vm, vm.propertyNames->emptyIdentifier, outValue); RELEASE_AND_RETURN(scope, callReviver(finalHolder, jsEmptyString(vm), outValue)); } // ECMA-262 v5 15.12.2 EncodedJSValue JSC_HOST_CALL JSONProtoFuncParse(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); auto* string = callFrame->argument(0).toString(globalObject); RETURN_IF_EXCEPTION(scope, { }); auto viewWithString = string->viewWithUnderlyingString(globalObject); RETURN_IF_EXCEPTION(scope, { }); StringView view = viewWithString.view; JSValue unfiltered; if (view.is8Bit()) { LiteralParser<LChar> jsonParser(globalObject, view.characters8(), view.length(), StrictJSON); unfiltered = jsonParser.tryLiteralParse(); EXCEPTION_ASSERT(!scope.exception() || !unfiltered); if (!unfiltered) { RETURN_IF_EXCEPTION(scope, { }); return throwVMError(globalObject, scope, createSyntaxError(globalObject, jsonParser.getErrorMessage())); } } else { LiteralParser<UChar> jsonParser(globalObject, view.characters16(), view.length(), StrictJSON); unfiltered = jsonParser.tryLiteralParse(); EXCEPTION_ASSERT(!scope.exception() || !unfiltered); if (!unfiltered) { RETURN_IF_EXCEPTION(scope, { }); return throwVMError(globalObject, scope, createSyntaxError(globalObject, jsonParser.getErrorMessage())); } } if (callFrame->argumentCount() < 2) return JSValue::encode(unfiltered); JSValue function = callFrame->uncheckedArgument(1); auto callData = getCallData(vm, function); if (callData.type == CallData::Type::None) return JSValue::encode(unfiltered); scope.release(); Walker walker(globalObject, asObject(function), callData); return JSValue::encode(walker.walk(unfiltered)); } // ECMA-262 v5 15.12.3 EncodedJSValue JSC_HOST_CALL JSONProtoFuncStringify(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); Stringifier stringifier(globalObject, callFrame->argument(1), callFrame->argument(2)); RETURN_IF_EXCEPTION(scope, { }); RELEASE_AND_RETURN(scope, JSValue::encode(stringifier.stringify(callFrame->argument(0)))); } JSValue JSONParse(JSGlobalObject* globalObject, const String& json) { if (json.isNull()) return JSValue(); if (json.is8Bit()) { LiteralParser<LChar> jsonParser(globalObject, json.characters8(), json.length(), StrictJSON); return jsonParser.tryLiteralParse(); } LiteralParser<UChar> jsonParser(globalObject, json.characters16(), json.length(), StrictJSON); return jsonParser.tryLiteralParse(); } String JSONStringify(JSGlobalObject* globalObject, JSValue value, JSValue space) { VM& vm = globalObject->vm(); auto throwScope = DECLARE_THROW_SCOPE(vm); Stringifier stringifier(globalObject, jsNull(), space); RETURN_IF_EXCEPTION(throwScope, { }); JSValue result = stringifier.stringify(value); if (UNLIKELY(throwScope.exception()) || result.isUndefinedOrNull()) return String(); return result.getString(globalObject); } String JSONStringify(JSGlobalObject* globalObject, JSValue value, unsigned indent) { return JSONStringify(globalObject, value, jsNumber(indent)); } } // namespace JSC
37.317406
174
0.640266
[ "object", "vector" ]
539a512175496980541483a9532441613db8ea2a
1,154
hpp
C++
include/natalie/range_value.hpp
MiguelBel/natalie
8439d45982b0edb14e51cd1958a865bb7f540b2d
[ "MIT" ]
1
2021-11-17T22:01:36.000Z
2021-11-17T22:01:36.000Z
include/natalie/range_value.hpp
jcs/natalie
36dae5954b80be2af107840de2b1c76b69bf6ac0
[ "MIT" ]
null
null
null
include/natalie/range_value.hpp
jcs/natalie
36dae5954b80be2af107840de2b1c76b69bf6ac0
[ "MIT" ]
null
null
null
#pragma once #include <assert.h> #include "natalie/class_value.hpp" #include "natalie/forward.hpp" #include "natalie/global_env.hpp" #include "natalie/macros.hpp" #include "natalie/value.hpp" namespace Natalie { struct RangeValue : Value { RangeValue(Env *env) : Value { Value::Type::Range, env->Object()->const_fetch("Range")->as_class() } { } RangeValue(Env *env, ClassValue *klass) : Value { Value::Type::Range, klass } { } RangeValue(Env *env, Value *begin, Value *end, bool exclude_end) : Value { Value::Type::Range, env->Object()->const_fetch("Range")->as_class() } , m_begin { begin } , m_end { end } , m_exclude_end { exclude_end } { } Value *begin() { return m_begin; } Value *end() { return m_end; } bool exclude_end() { return m_exclude_end; } Value *initialize(Env *, Value *, Value *, Value *); Value *to_a(Env *); Value *each(Env *, Block *); Value *inspect(Env *); Value *eq(Env *, Value *); Value *eqeqeq(Env *, Value *); private: Value *m_begin { nullptr }; Value *m_end { nullptr }; bool m_exclude_end { false }; }; }
26.227273
91
0.610919
[ "object" ]
53a69715b66d3d54a90feaf3a326735e3ec1f1bb
8,571
cpp
C++
L1P2/L1P2.cpp
peterekepeter/bitlab
074ceee9ac468f93d1b938ca11eaefdbf7ec1637
[ "MIT" ]
null
null
null
L1P2/L1P2.cpp
peterekepeter/bitlab
074ceee9ac468f93d1b938ca11eaefdbf7ec1637
[ "MIT" ]
null
null
null
L1P2/L1P2.cpp
peterekepeter/bitlab
074ceee9ac468f93d1b938ca11eaefdbf7ec1637
[ "MIT" ]
null
null
null
#include <vector> #include <stdio.h> #include <time.h> inline unsigned char bitcount(int x) { unsigned char acc = 0; while(x) acc+=x&1, x>>=1; return acc; } unsigned char btc_table[65536]; inline unsigned char bitc(const unsigned char x) { return btc_table[x]; } inline unsigned char bitc(const char x) { return btc_table[unsigned char(x)]; } inline unsigned char bitc(const unsigned short x) { return btc_table[x]; } inline unsigned char bitc(const short x) { return btc_table[unsigned short(x)]; } inline unsigned char bitc(const unsigned x) { return btc_table[x>>16] + btc_table[x&65535]; } inline unsigned char bitc(const int x) { return bitc(unsigned(x)); } inline unsigned char bitc(const unsigned long long x) { return btc_table[x&65535]+btc_table[(x>>16)&65535]+btc_table[(x>>32)&65535]+btc_table[x>>48]; } inline unsigned char bitc(const long long x) { return bitc((unsigned long long) x); } int bitcount_A(const void* data, size_t size) { int acc = 0; auto byteptr = (unsigned char*) data; for (int i=0; i<size; i++) { acc += bitcount(byteptr[i]); } return acc; } int bitcount_B(const void* data, size_t size) { auto ptr = (unsigned char*) data; int acc = 0; while (size--) acc += bitc(*ptr++); return acc; } int bitcount_C(const void* data, size_t size) { int acc = 0; auto byteptr = (unsigned char*) data; auto ptr = (unsigned short*) data; auto count = size >> 1; while (count--) acc += bitc(*ptr++); if (size&1) acc += bitc(byteptr[size-1]); return acc; } int bitcount_D(const void* data, size_t size) { int acc = 0; auto byteptr = (unsigned char*) data; auto ptr = (unsigned*) data; auto count = size >> 2; while (count--) acc += bitc(*ptr++); switch (size&3) { case 3: acc += bitc(byteptr[size-3]); case 2: acc += bitc(byteptr[size-2]); case 1: acc += bitc(byteptr[size-1]); } return acc; } int bitcount_E(const void* data, size_t size) { int acc = 0; auto byteptr = (unsigned char*) data; auto ptr = (unsigned long long*) data; auto count = size >> 3; while (count--) acc += bitc(*ptr++); switch (size&7) { case 7: acc += bitc(byteptr[size-7]); case 6: acc += bitc(byteptr[size-6]); case 5: acc += bitc(byteptr[size-5]); case 4: acc += bitc(byteptr[size-4]); case 3: acc += bitc(byteptr[size-3]); case 2: acc += bitc(byteptr[size-2]); case 1: acc += bitc(byteptr[size-1]); } return acc; } int bitcount_E2(const void* data, size_t size) { int acc = 0,i=0; auto byteptr = (unsigned char*) data; auto ptr = (unsigned long long*) data; auto count = size >> 3; while (count--) { acc += bitc(ptr[i++]); } switch (size&7) { case 7: acc += bitc(byteptr[size-7]); case 6: acc += bitc(byteptr[size-6]); case 5: acc += bitc(byteptr[size-5]); case 4: acc += bitc(byteptr[size-4]); case 3: acc += bitc(byteptr[size-3]); case 2: acc += bitc(byteptr[size-2]); case 1: acc += bitc(byteptr[size-1]); } return acc; } int bitcount_F(const void* data, size_t size) { int acc = 0; auto byteptr = (unsigned char*) data; auto ptr = (unsigned*) data; auto count = size >> 2; while (count--) { auto val = *ptr++; unsigned char a = bitc(val&255); unsigned char b = bitc((val>>8)&255); unsigned char c = bitc((val>>16)&255); unsigned char d = bitc((val>>24)); acc += a + b + c + d; } switch (size&3) { case 3: acc += bitc(byteptr[size-3]); case 2: acc += bitc(byteptr[size-2]); case 1: acc += bitc(byteptr[size-1]); } return acc; } int bitcount_G(const void* data, size_t size) { const void *d = data; int s = size; int r; void *lut = btc_table; _asm{ push esi push ebx mov esi,d mov ecx,s mov ebx,lut xor edx,edx xor eax,eax _for: lodsb xlatb add edx,eax loop _for pop ebx pop esi mov r,edx } return r; } int bitcount_G2(const void* data, size_t size) { const void *d = data; int s = size; int r; void *lut = btc_table; _asm{ push esi push ebx mov ecx, d mov eax, s mov ebx, lut xor esi,esi _for: movzx edx,byte ptr [ecx] ; lodsb movzx edx,byte ptr [ebx+edx] ; xlat add esi,edx inc ecx dec eax jne _for mov r,esi pop ebx pop esi } return r; } void genTable() { for (int i=0; i<65536; i++) btc_table[i]=bitcount(i); } double entropy(int o, int t) { auto z = t-o; auto ot = (o/(double)t); auto zt = (z/(double)t); return -ot*log(ot)-zt*log(zt); } int main(int argc, char** argv) { genTable(); auto machine_speed_ghz = 1.3; auto n = 1000000000/8 - 1; //auto n = 100000000/8 - 1; unsigned char* data = new unsigned char[n]; for (int i=0; i<n; i++) data[i] = rand()&255; { auto time_start = clock(); auto result = bitcount_G(data, n); auto runtime = clock() - time_start; printf("\nmethod G\n result %d\n runtime %ldms\n %f bits/clock\n entropy %f\n", result, runtime, n*8000.0/runtime/1e9/machine_speed_ghz, entropy(result,n*8)); } { auto time_start = clock(); auto result = bitcount_G2(data, n); auto runtime = clock() - time_start; printf("\nmethod G2\n result %d\n runtime %ldms\n %f bits/clock\n entropy %f\n", result, runtime, n*8000.0/runtime/1e9/machine_speed_ghz, entropy(result,n*8)); } { auto time_start = clock(); auto result = bitcount_A(data, n); auto runtime = clock() - time_start; printf("\nmethod A\n result %d\n runtime %ldms\n %f bits/clock\n entropy %f\n", result, runtime, n*1000.0/runtime/1e9/machine_speed_ghz, entropy(result,n*8)); } { auto time_start = clock(); auto result = bitcount_B(data, n); auto runtime = clock() - time_start; printf("\nmethod B\n result %d\n runtime %ldms\n %f bits/clock\n entropy %f\n", result, runtime, n*8000.0/runtime/1e9/machine_speed_ghz, entropy(result,n*8)); } { auto time_start = clock(); auto result = bitcount_C(data, n); auto runtime = clock() - time_start; printf("\nmethod C\n result %d\n runtime %ldms\n %f bits/clock\n entropy %f\n", result, runtime, n*8000.0/runtime/1e9/machine_speed_ghz, entropy(result,n*8)); } { auto time_start = clock(); auto result = bitcount_D(data, n); auto runtime = clock() - time_start; printf("\nmethod D\n result %d\n runtime %ldms\n %f bits/clock\n entropy %f\n", result, runtime, n*8000.0/runtime/1e9/machine_speed_ghz, entropy(result,n*8)); } { auto time_start = clock(); auto result = bitcount_E(data, n); auto runtime = clock() - time_start; printf("\nmethod E\n result %d\n runtime %ldms\n %f bits/clock\n entropy %f\n", result, runtime, n*8000.0/runtime/1e9/machine_speed_ghz, entropy(result,n*8)); } { auto time_start = clock(); auto result = bitcount_E2(data, n); auto runtime = clock() - time_start; printf("\nmethod E2\n result %d\n runtime %ldms\n %f bits/clock\n entropy %f\n", result, runtime, n*8000.0/runtime/1e9/machine_speed_ghz, entropy(result,n*8)); } { auto time_start = clock(); auto result = bitcount_F(data, n); auto runtime = clock() - time_start; printf("\nmethod F\n result %d\n runtime %ldms\n %f bits/clock\n entropy %f\n", result, runtime, n*8000.0/runtime/1e9/machine_speed_ghz, entropy(result,n*8)); } delete[] data; return 0; };
28.57
151
0.53541
[ "vector" ]
53aca4145b4186f0fea3cdcf3dd2056ea45b105a
13,958
cpp
C++
tools/multi_conv_layer.cpp
graphcore/poplibs
3fe5a3ecafe995eddb72675d1b4a7af8a622009e
[ "MIT" ]
95
2020-07-06T17:11:23.000Z
2022-03-12T14:42:28.000Z
tools/multi_conv_layer.cpp
graphcore/poplibs
3fe5a3ecafe995eddb72675d1b4a7af8a622009e
[ "MIT" ]
null
null
null
tools/multi_conv_layer.cpp
graphcore/poplibs
3fe5a3ecafe995eddb72675d1b4a7af8a622009e
[ "MIT" ]
14
2020-07-15T12:32:57.000Z
2022-01-26T14:58:45.000Z
// Copyright (c) 2020 Graphcore Ltd. All rights reserved. #include "poplin/MultiConvolution.hpp" #include <boost/assign/list_of.hpp> #include <boost/optional.hpp> #include <boost/program_options.hpp> #include <boost/version.hpp> #include <iostream> #include <poplibs_support/TestDevice.hpp> #include <poplibs_support/VectorUtils.hpp> #include <poplibs_test/Check.hpp> #include <poplibs_test/Convolution.hpp> #include <poplibs_test/Util.hpp> #include <poplin/ConvUtil.hpp> #include <poplin/codelets.hpp> #include <popops/codelets.hpp> #include <sstream> using namespace poplibs_support; int main(int argc, char **argv) try { namespace po = boost::program_options; DeviceType deviceType; boost::optional<unsigned> tilesPerIPU; std::vector<std::string> convs; bool reportPlan; bool bwdPass; bool enableConvolutionReuse; po::options_description desc("Options"); // clang-format off desc.add_options() ("help,h", "produce help message") ("compile-only", "Stop after compilation; don't run the program") ("device-type", po::value<DeviceType>(&deviceType)->default_value(DeviceType::IpuModel2), deviceTypeHelp) ("profile", "Output profiling report to standard output") ("ignore-data", "Don't upload and download the results from the device. " "Note that this means the result is not validated against the model.") ("tiles-per-ipu", po::value(&tilesPerIPU), "Number of tiles per IPU") ("conv", po::value<std::vector<std::string>>(&convs) ->default_value(boost::assign::list_of(""), "")->composing(), "parameters for a convolution used in the multiconv") ("bwd", po::value<bool>(&bwdPass)->default_value(false), "Backward pass") ("enable-convolution-reuse", po::value<bool>(&enableConvolutionReuse)->default_value(true), "Apply optimization to reuse the forward convolution in the backward pass") ("report-plan", po::value<bool>(&reportPlan)->default_value(false), "Display plan") ; // clang-format on po::variables_map vm; try { const po::positional_options_description p; po::store( po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << "\n"; return 1; } } catch (const boost::program_options::error &e) { std::cerr << e.what() << std::endl; return 1; } const bool profile = deviceType != DeviceType::Cpu && vm.count("profile"); const bool ignoreData = vm.count("ignore-data"); std::cout << "got " << convs.size() << " convs" << std::endl; const unsigned numIPUs = 1; const bool compileIPUCode = true; auto device = tilesPerIPU ? createTestDevice(deviceType, numIPUs, *tilesPerIPU, compileIPUCode) : createTestDeviceFullSize(deviceType, numIPUs, compileIPUCode); const auto &target = device.getTarget(); poplar::Graph graph(target); poplin::addCodelets(graph); popops::addCodelets(graph); poplin::PlanningCache cache; poplar::program::Sequence uploadProg, prog, downloadProg; const poplar::OptionFlags multiConvOptions; const std::vector<poplar::OptionFlags> options(convs.size()); std::vector<poplin::ConvParams> fwdParams; std::vector<poplin::ConvParams> bwdParams; for (const auto &conv : convs) { std::stringstream ss; ss << conv; poplin::ConvParams p; ss >> p; bwdParams.push_back(getGradientParams(p)); fwdParams.push_back(std::move(p)); } auto &params = bwdPass ? bwdParams : fwdParams; if (reportPlan) { for (unsigned i = 0; i < params.size(); ++i) { std::cout << "Convolution parameters:\n" " Batch size: " << params[i].batchSize << "\n" " Kernel:" << params[i].kernelShape << "\n" " Stride:" << params[i].outputTransform.stride << "\n" " Padding Lower: " << params[i].inputTransform.paddingLower << "\n" " Padding Upper: " << params[i].inputTransform.paddingUpper << "\n" " Group size: " << params[i].numConvGroups << "\n" " Input: " << params[i].inputChannelsPerConvGroup << "x" << params[i].inputFieldShape << "\n" " Output: " << params[i].outputChannelsPerConvGroup << "\n"; std::cout << "Plan:\n"; poplin::reportPlanInfo(std::cout, graph, params[i], options[i], &cache); } } std::vector<poplin::multiconv::CreateTensorArgs> createInputArgs; std::vector<poplin::multiconv::CreateTensorArgs> createWeightsArgs; for (unsigned i = 0; i < params.size(); ++i) { createInputArgs.push_back( {params[i], options[i], "convInput_" + std::to_string(i)}); } std::vector<poplin::multiconv::ConvolutionArgs> convolutionArgs; std::vector<poplar::Tensor> outs; if (bwdPass && enableConvolutionReuse) { // Create weight arguments in forward pass for (unsigned i = 0; i < params.size(); ++i) { createWeightsArgs.push_back( {fwdParams[i], options[i], "convFwdWeights_" + std::to_string(i)}); } // Create forward pass weights std::vector<poplar::Tensor> fwdWeights; for (unsigned i = 0; i < params.size(); ++i) { auto weights = poplin::multiconv::createWeights( graph, createWeightsArgs, i, multiConvOptions, &cache); fwdWeights.push_back(weights); } // Create weight arguments in backward pass std::vector<poplin::multiconv::CreateTensorArgs> createBwdWeightsArgs; for (unsigned i = 0; i < params.size(); ++i) { createBwdWeightsArgs.push_back( {params[i], options[i], "convBwdWeights_" + std::to_string(i)}); } // Create inputs and weights for backward pass for (unsigned i = 0; i < params.size(); ++i) { auto input = poplin::multiconv::createInput(graph, createInputArgs, i, multiConvOptions, &cache); auto bwdWeights = poplin::multiconv::createWeights( graph, createBwdWeightsArgs, i, multiConvOptions, &cache); convolutionArgs.push_back( {std::move(input), std::move(bwdWeights), params[i], options[i]}); } poplin::multiconv::weightsTransposeChansFlipXY( graph, convolutionArgs, fwdWeights, prog, multiConvOptions, "bwd", &cache); outs = poplin::multiconv::convolution(graph, convolutionArgs, false, prog, "multiConv", multiConvOptions); // Use the weights in the arrangement of the Fwd pass for (unsigned i = 0; i < params.size(); ++i) { convolutionArgs[i].weights = fwdWeights[i]; } } else { for (unsigned i = 0; i < params.size(); ++i) { createWeightsArgs.push_back( {params[i], options[i], "convWeights_" + std::to_string(i)}); } for (unsigned i = 0; i < params.size(); ++i) { auto input = poplin::multiconv::createInput(graph, createInputArgs, i, multiConvOptions, &cache); auto weights = poplin::multiconv::createWeights( graph, createWeightsArgs, i, multiConvOptions, &cache); convolutionArgs.push_back( {std::move(input), std::move(weights), params[i], options[i]}); } bool transposeAndFlipWeights = bwdPass ? true : false; outs = poplin::multiconv::convolution(graph, convolutionArgs, transposeAndFlipWeights, prog, "multiConv", multiConvOptions); } std::vector<std::pair<std::string, char *>> tmap; std::vector<std::unique_ptr<char[]>> rawHostInputs, rawHostWeights, rawHostOutputs; if (!ignoreData) { for (unsigned i = 0; i < convolutionArgs.size(); ++i) { auto rawHostInput = poplibs_test::util::allocateHostMemoryForTensor( convolutionArgs[i].inputs, createInputArgs[i].name, graph, uploadProg, boost::none, tmap); rawHostInputs.push_back(std::move(rawHostInput)); auto rawHostWeight = poplibs_test::util::allocateHostMemoryForTensor( convolutionArgs[i].weights, createWeightsArgs[i].name, graph, uploadProg, boost::none, tmap); rawHostWeights.push_back(std::move(rawHostWeight)); auto rawHostOutput = poplibs_test::util::allocateHostMemoryForTensor( outs[i], "output_" + std::to_string(i), graph, boost::none, downloadProg, tmap); rawHostOutputs.push_back(std::move(rawHostOutput)); } } const poplar::OptionFlags engineOptions; poplar::Engine engine(graph, {uploadProg, prog, downloadProg}, engineOptions); if (vm.count("compile-only")) return 0; std::vector<boost::multi_array<double, 3>> hostInputs; std::vector<boost::multi_array<double, 4>> hostWeights; std::vector<boost::multi_array<double, 3>> modelOutputs; if (!ignoreData) { poplibs_test::util::attachStreams(engine, tmap); std::mt19937 randomEngine; for (unsigned i = 0; i < convolutionArgs.size(); ++i) { const auto &p = createInputArgs[i].params; const auto inChannels = p.inputChannelsPerConvGroup * p.numConvGroups; const auto outChannels = p.outputChannelsPerConvGroup * p.numConvGroups; hostInputs.emplace_back( boost::extents[p.batchSize][inChannels][product(p.inputFieldShape)]); poplibs_test::util::writeRandomBinaryValues( target, p.inputType, hostInputs.back(), -1.0, 1.0, randomEngine); poplibs_test::util::copy(target, hostInputs.back(), p.inputType, rawHostInputs[i].get()); hostWeights.emplace_back( boost::extents[p.numConvGroups][p.outputChannelsPerConvGroup] [p.inputChannelsPerConvGroup][product(p.kernelShape)]); poplibs_test::util::writeRandomBinaryValues( target, p.inputType, hostWeights.back(), -1.0, 1.0, randomEngine); poplibs_test::util::copy(target, hostWeights.back(), p.inputType, rawHostWeights[i].get()); // build a reference model to validate against boost::multi_array<double, 1> biases(boost::extents[outChannels]); std::fill(biases.data(), biases.data() + biases.num_elements(), 0.0); const auto outFieldShape = p.getOutputFieldShape(); modelOutputs.emplace_back( boost::extents[p.batchSize][outChannels][product(outFieldShape)]); if (!bwdPass) { poplibs_test::conv::convolution( vectorConvert<unsigned>(p.inputFieldShape), p.inputTransform.truncationLower, p.inputTransform.truncationUpper, p.inputTransform.dilation, p.inputTransform.paddingLower, p.inputTransform.paddingUpper, p.inputTransform.flip, vectorConvert<unsigned>(p.kernelShape), p.kernelTransform.truncationLower, p.kernelTransform.truncationUpper, p.kernelTransform.dilation, p.kernelTransform.paddingLower, p.kernelTransform.paddingUpper, p.kernelTransform.flip, p.outputTransform.truncationLower, p.outputTransform.truncationUpper, p.outputTransform.stride, p.outputTransform.paddingLower, p.outputTransform.paddingUpper, hostInputs.back(), hostWeights.back(), biases, modelOutputs.back()); } else { const auto inputFieldShape = p.getOutputFieldShape(); const auto &fwdP = fwdParams[i]; poplibs_test::conv::convolutionBackward( vectorConvert<unsigned>(inputFieldShape), fwdP.inputTransform.truncationLower, fwdP.inputTransform.truncationUpper, fwdP.inputTransform.dilation, fwdP.inputTransform.paddingLower, fwdP.inputTransform.paddingUpper, fwdP.inputTransform.flip, vectorConvert<unsigned>(p.kernelShape), fwdP.kernelTransform.truncationLower, fwdP.kernelTransform.truncationUpper, fwdP.kernelTransform.dilation, fwdP.kernelTransform.paddingLower, fwdP.kernelTransform.paddingUpper, fwdP.kernelTransform.flip, fwdP.outputTransform.truncationLower, fwdP.outputTransform.truncationUpper, fwdP.outputTransform.stride, fwdP.outputTransform.paddingLower, fwdP.outputTransform.paddingUpper, hostInputs.back(), hostWeights.back(), modelOutputs.back()); } } } device.bind([&](const poplar::Device &d) { engine.load(d); if (!ignoreData) { // upload engine.run(0); } // convolve engine.run(1); if (!ignoreData) { // download engine.run(2); } }); bool matchesModel = true; if (!ignoreData) { for (unsigned i = 0; i < convolutionArgs.size(); ++i) { const auto &p = convolutionArgs[i].params; const auto outFieldShape = p.getOutputFieldShape(); const auto outChannels = p.outputChannelsPerConvGroup * p.numConvGroups; boost::multi_array<double, 3> hostOutput( boost::extents[p.batchSize][outChannels][product(outFieldShape)]); poplibs_test::util::copy(target, p.outputType, rawHostOutputs[i].get(), hostOutput); const auto tolerance = 0.0; matchesModel &= poplibs_test::util::checkIsClose( "conv_" + std::to_string(i), hostOutput, modelOutputs[i], tolerance, tolerance); } } if (profile) { engine.printProfileSummary(std::cout, {{"showExecutionSteps", "true"}}); } if (!matchesModel) { std::cerr << "Validation failed\n"; return 1; } return 0; } catch (const poplar::graph_memory_allocation_error &e) { std::cerr << e.what() << std::endl; // this exit code has been marked as a "skip" for ctest. return 77; }
38.772222
80
0.634475
[ "vector", "model" ]
53acefa9354b0a9050bfd8d6eaa50c44be4770ec
1,022
cc
C++
cpp/leetcode/22.generate-parentheses.cc
liubang/laboratory
747f239a123cd0c2e5eeba893b9a4d1536555b1e
[ "MIT" ]
3
2021-03-03T13:18:23.000Z
2022-02-09T07:49:24.000Z
cpp/leetcode/22.generate-parentheses.cc
liubang/laboratory
747f239a123cd0c2e5eeba893b9a4d1536555b1e
[ "MIT" ]
null
null
null
cpp/leetcode/22.generate-parentheses.cc
liubang/laboratory
747f239a123cd0c2e5eeba893b9a4d1536555b1e
[ "MIT" ]
1
2021-03-29T15:21:42.000Z
2021-03-29T15:21:42.000Z
#include <gtest/gtest.h> #include <string> #include <vector> namespace { class Solution { public: std::vector<std::string> generateParenthesis(int n) { std::vector<std::string> ret; std::string str; gen(ret, str, 0, 0, n); return ret; } private: void gen(std::vector<std::string>& ret, std::string& str, int open, int close, int n) { if (str.length() == n * 2) { ret.push_back(str); return; } if (open < n) { str.push_back('('); gen(ret, str, open + 1, close, n); str.pop_back(); } if (close < open) { str.push_back(')'); gen(ret, str, open, close + 1, n); str.pop_back(); } } }; } // namespace TEST(Leetcode, generate_parentheses) { Solution s; { std::vector<std::string> exps = { "((()))", "(()())", "(())()", "()(())", "()()()", }; EXPECT_EQ(exps, s.generateParenthesis(3)); } { std::vector<std::string> exps = {"()"}; EXPECT_EQ(exps, s.generateParenthesis(1)); } }
20.039216
80
0.521526
[ "vector" ]
53b1aa053e68573f0bb7b3547856f4a9cab834a3
2,124
cpp
C++
Common_elements.cpp
shalini264/Coding-problem-solutions
77e8b12b771d24e62f4268d6ba8f29f592770bd9
[ "MIT" ]
4
2021-07-11T20:13:56.000Z
2022-02-19T17:22:42.000Z
Common_elements.cpp
shalini264/long-challenge-solutions-in-my-way
77e8b12b771d24e62f4268d6ba8f29f592770bd9
[ "MIT" ]
null
null
null
Common_elements.cpp
shalini264/long-challenge-solutions-in-my-way
77e8b12b771d24e62f4268d6ba8f29f592770bd9
[ "MIT" ]
null
null
null
class Solution { public: vector <int> commonElements (int A[], int B[], int C[], int n1, int n2, int n3) { vector<int>ans; int i=0,j=0,k=0; while(i<n1&&j<n2&&k<n3) { if(A[i]<B[j]&&A[i]<C[k]) { i++; } else if(A[i]<=B[j]&&A[i]<C[k]) { i++; } else if(A[i]<B[j]&&A[i]<=C[k]) { i++; } else if(B[j]<A[i]&&B[j]<C[k]) { j++; } else if(B[j]<=A[i]&&B[j]<C[k]) { j++; } else if(B[j]<A[i]&&B[j]<=C[k]) { j++; } else if(C[k]<A[i]&&C[k]<B[j]) { k++; } else if(C[k]<=A[i]&&C[k]<B[j]) { k++; } else if(C[k]<A[i]&&C[k]<=B[j]) { k++; } else if(A[i]==B[j]&&B[j]==C[k]) { ans.push_back(A[i]); i++; } } ans.erase(unique(ans.begin(),ans.end()),ans.end()); return ans; } }; int main () { int t; cin >> t; while (t--) { int n1, n2, n3; cin >> n1 >> n2 >> n3; int A[n1]; int B[n2]; int C[n3]; for (int i = 0; i < n1; i++) cin >> A[i]; for (int i = 0; i < n2; i++) cin >> B[i]; for (int i = 0; i < n3; i++) cin >> C[i]; Solution ob; vector <int> res = ob.commonElements (A, B, C, n1, n2, n3); if (res.size () == 0) cout << -1; for (int i = 0; i < res.size (); i++) cout << res[i] << " "; cout << endl; } }
24.413793
86
0.240113
[ "vector" ]
53b63285ece672d766a5fa21167c5c95ecc8552b
90,594
cpp
C++
src/ir.cpp
octurion/shapes-compiler
d5f165f457ad876b827ac64a1b0da6f6f718bbef
[ "MIT" ]
1
2022-03-29T04:28:00.000Z
2022-03-29T04:28:00.000Z
src/ir.cpp
octurion/shapes-compiler
d5f165f457ad876b827ac64a1b0da6f6f718bbef
[ "MIT" ]
null
null
null
src/ir.cpp
octurion/shapes-compiler
d5f165f457ad876b827ac64a1b0da6f6f718bbef
[ "MIT" ]
null
null
null
#include "ast.h" #include "ir.h" #include <llvm/ADT/None.h> #include <llvm/Analysis/TypeBasedAliasAnalysis.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/GenericValue.h> #include <llvm/ExecutionEngine/Interpreter.h> #include <llvm/IR/AssemblyAnnotationWriter.h> #include <llvm/IR/BasicBlock.h> #include <llvm/IR/Function.h> #include <llvm/IR/IRBuilder.h> #include <llvm/IR/LegacyPassManager.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/MDBuilder.h> #include <llvm/IR/Module.h> #include <llvm/IR/Type.h> #include <llvm/IR/Verifier.h> #include <llvm/Passes/PassBuilder.h> #include <llvm/Support/FileSystem.h> #include <llvm/Support/TargetRegistry.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Target/TargetMachine.h> #include <llvm/Target/TargetOptions.h> #include <sstream> #include <string> #include <unordered_map> #include <cstdio> #include <cstdlib> namespace Ir { ClassSpecialization ClassSpecialization::specialize( const Ast::Class& clazz, const std::vector<Ast::PoolParameter>& params) const { const auto& pools = m_class->pools(); std::unordered_map<const Ast::Pool*, const Ast::Layout*> mapping; for (size_t i = 0; i < m_pool_param_types.size(); i++) { const Ast::Pool& pool = pools[i]; mapping[&pool] = m_pool_param_types[i]; } std::vector<const Ast::Layout*> param_types; for (const auto& e: params) { const auto* pool_ref = mpark::get_if<Ast::PoolRef>(&e); if (pool_ref == nullptr) { param_types.push_back(nullptr); continue; } const Ast::Pool& pool = pool_ref->pool(); const auto* as_layout = mpark::get_if<Ast::LayoutType>(&pool.type()); if (as_layout != nullptr) { param_types.push_back(&as_layout->layout()); continue; } auto it = mapping.find(&pool); assert_msg(it != mapping.end(), "Could not find pool"); param_types.push_back(it->second); } return ClassSpecialization(clazz, std::move(param_types)); } std::ostream& operator<<(std::ostream& os, const ClassSpecialization& specialization) { const auto& class_name = specialization.clazz().name(); os << specialization.pool_param_types().size() << "C" << class_name.length() << class_name; for (const auto* e: specialization.pool_param_types()) { if (e == nullptr) { os << "N"; } else { os << e->name().length() << e->name(); } } return os; } struct StandaloneSpecializationInfo { llvm::StructType* type = nullptr; llvm::MDNode* tbaa_type = nullptr; llvm::MDNode* tbaa_ptr_type = nullptr; llvm::Function* ctor = nullptr; }; struct PoolSpecializationInfo { llvm::StructType* pool_type = nullptr; llvm::MDNode* pool_tbaa_ptr_type = nullptr; llvm::MDNode* pool_tbaa_type = nullptr; std::vector<llvm::StructType*> cluster_types; std::vector<llvm::MDNode*> cluster_tbaa_types; std::vector<llvm::MDNode*> cluster_tbaa_ptr_types; llvm::Function* pool_alloc = nullptr; llvm::Function* pool_free = nullptr; llvm::Function* obj_ctor = nullptr; }; struct SpecializationInfo { mpark::variant<StandaloneSpecializationInfo, PoolSpecializationInfo> type_info; std::unordered_map<const Ast::Method*, llvm::Function*> funcs; }; struct MethodCodegenState; class LLVMExpr { llvm::IRBuilder<>* m_builder = nullptr; llvm::Value* m_value = nullptr; llvm::MDNode* m_tbaa_metadata = nullptr; bool m_lvalue = false; public: LLVMExpr() = default; LLVMExpr( llvm::IRBuilder<>* builder, llvm::Value* value, llvm::MDNode* tbaa_metadata, bool lvalue) : m_builder(builder) , m_value(value) , m_tbaa_metadata(tbaa_metadata) , m_lvalue(lvalue) {} llvm::Value* value() const { return m_value; } llvm::MDNode* tbaa_metadata() const { return m_tbaa_metadata; } bool lvalue() const { return m_lvalue; } llvm::Value* to_rvalue() const { if (!m_lvalue) { return m_value; } auto* insn = m_builder->CreateLoad(m_value); if (m_tbaa_metadata != nullptr) { insn->setMetadata(llvm::LLVMContext::MD_tbaa, m_tbaa_metadata); } return insn; } }; class Codegen::Impl { llvm::LLVMContext m_ctx; const llvm::Target* m_target = nullptr; llvm::TargetMachine* m_target_machine = nullptr; std::unique_ptr<llvm::Module> m_mod = nullptr; llvm::Type* m_void = nullptr; llvm::Type* m_null = nullptr; llvm::Type* m_i1 = nullptr; llvm::Type* m_i8 = nullptr; llvm::Type* m_i16 = nullptr; llvm::Type* m_i32 = nullptr; llvm::Type* m_i64 = nullptr; llvm::Type* m_f32 = nullptr; llvm::Type* m_f64 = nullptr; llvm::Type* m_intptr = nullptr; llvm::MDNode* m_tbaa_root = nullptr; llvm::MDNode* m_tbaa_bool = nullptr; llvm::MDNode* m_tbaa_i8 = nullptr; llvm::MDNode* m_tbaa_u8 = nullptr; llvm::MDNode* m_tbaa_i16 = nullptr; llvm::MDNode* m_tbaa_u16 = nullptr; llvm::MDNode* m_tbaa_i32 = nullptr; llvm::MDNode* m_tbaa_u32 = nullptr; llvm::MDNode* m_tbaa_i64 = nullptr; llvm::MDNode* m_tbaa_u64 = nullptr; llvm::MDNode* m_tbaa_f32 = nullptr; llvm::MDNode* m_tbaa_f64 = nullptr; llvm::MDNode* m_tbaa_intptr = nullptr; llvm::FunctionType* m_malloc_type = nullptr; llvm::Function* m_malloc = nullptr; llvm::FunctionType* m_realloc_type = nullptr; llvm::Function* m_realloc = nullptr; llvm::FunctionType* m_free_type = nullptr; llvm::Function* m_free = nullptr; std::unordered_map<ClassSpecialization, SpecializationInfo> m_specialization_info; void generate_specializations(const Ast::Class& clazz); void generate_specializations_impl( const Ast::Class& clazz, std::vector<const Ast::Layout*>& curr_layouts); llvm::Type* type_of( const Ast::NoneType& type, const ClassSpecialization& specialization); llvm::Type* type_of( const Ast::LayoutType& type, const ClassSpecialization& specialization); llvm::Type* type_of( const Ast::BoundType& type, const ClassSpecialization& specialization); llvm::Type* type_of( const Ast::PoolType& type, const ClassSpecialization& specialization); llvm::Type* type_of( const Ast::ObjectType& type, const ClassSpecialization& specialization); llvm::Type* type_of( const Ast::PrimitiveType& type, const ClassSpecialization&); llvm::Type* type_of( const Ast::NullptrType&, const ClassSpecialization&); llvm::Type* type_of( const Ast::VoidType&, const ClassSpecialization&); llvm::Type* type_of( const Ast::Type& type, const ClassSpecialization& specialization); llvm::MDNode* tbaa_type_of( const Ast::Type& type, const ClassSpecialization& specialization); llvm::MDNode* tbaa_type_of( const Ast::PrimitiveType& type, const ClassSpecialization& specialization); llvm::MDNode* tbaa_type_of( const Ast::ObjectType& type, const ClassSpecialization& specialization); llvm::MDNode* tbaa_type_of( const Ast::VoidType& type, const ClassSpecialization& specialization); llvm::MDNode* tbaa_type_of( const Ast::NullptrType& type, const ClassSpecialization& specialization); llvm::Constant* zero( const Ast::ObjectType& type, const ClassSpecialization& specialization); llvm::Constant* zero( const Ast::PrimitiveType& type, const ClassSpecialization& specialization); llvm::Constant* zero(const Ast::NullptrType&, const ClassSpecialization&); llvm::Constant* zero(const Ast::VoidType&, const ClassSpecialization&); llvm::Constant* zero( const Ast::Type& type, const ClassSpecialization& specialization); void visit(const Ast::Stmt& stmt, MethodCodegenState& state); void visit(const Ast::Assignment& e, MethodCodegenState& state); void visit(const Ast::OpAssignment& e, MethodCodegenState& state); void visit(const Ast::If& e, MethodCodegenState& state); void visit(const Ast::While& e, MethodCodegenState& state); void visit(const Ast::ForeachRange& e, MethodCodegenState& state); void visit(const Ast::ForeachPool& e, MethodCodegenState& state); void visit(const Ast::ExprStmt& e, MethodCodegenState& state); void visit(const Ast::Break& e, MethodCodegenState& state); void visit(const Ast::Continue& e, MethodCodegenState& state); void visit(const Ast::Return& e, MethodCodegenState& state); LLVMExpr visit(const Ast::Expr& e, MethodCodegenState& state); LLVMExpr visit(const Ast::InvalidExpr& e, MethodCodegenState& state); LLVMExpr visit(const Ast::IntegerConst& e, MethodCodegenState& state); LLVMExpr visit(const Ast::DoubleConst& e, MethodCodegenState& state); LLVMExpr visit(const Ast::BooleanConst& e, MethodCodegenState& state); LLVMExpr visit(const Ast::NullExpr& e, MethodCodegenState& state); LLVMExpr visit(const Ast::ThisExpr& e, MethodCodegenState& state); LLVMExpr visit(const Ast::CastExpr& e, MethodCodegenState& state); LLVMExpr visit(const Ast::UnaryExpr& e, MethodCodegenState& state); LLVMExpr visit(const Ast::BinaryExpr& e, MethodCodegenState& state); LLVMExpr visit(const Ast::VariableExpr& e, MethodCodegenState& state); LLVMExpr visit(const Ast::PoolIndexExpr& e, MethodCodegenState& state); LLVMExpr visit(const Ast::MethodCall& e, MethodCodegenState& state); LLVMExpr visit(const Ast::FieldAccess& e, MethodCodegenState& state); LLVMExpr visit(const Ast::NewExpr& e, MethodCodegenState& state); void generate_llvm_types(); void generate_llvm_function_decls(); void generate_llvm_functions(); public: bool ir(const Ast::Program& ast); bool emit(const char* llvm_bitcode_filename, const char* object_filename); bool emit_header(const char* header_file_name) const; llvm::Function* find_method(const ClassSpecialization& spec, const Ast::Method& m) const; llvm::Function* constructor(const ClassSpecialization& spec) const; llvm::Function* pool_constructor(const ClassSpecialization& spec) const; std::unique_ptr<llvm::Module> get_module(); }; static const char* const PRIMITIVE_FFI_TYPE_NAMES[] = { "bool", // PrimitiveType::BOOL "int8_t", // PrimitiveType::I8 "uint8_t", // PrimitiveType::U8 "int16_t", // PrimitiveType::I16 "uint16_t", // PrimitiveType::U16 "int32_t", // PrimitiveType::I32 "uint32_t", // PrimitiveType::U32 "int64_t", // PrimitiveType::I64 "uint64_t", // PrimitiveType::U64 "float", // PrimitiveType::F32 "double", // PrimitiveType::F64 }; std::string create_method_name( const ClassSpecialization& specialization, const Ast::Method& method) { std::ostringstream os; os << "_shapes" << specialization << "_M" << method.name().length() << method.name(); return os.str(); } std::string create_pool_ctor_name(const ClassSpecialization& specialization) { std::ostringstream os; os << "_shapes" << specialization << "_P"; return os.str(); } std::string create_pool_dtor_name(const ClassSpecialization& specialization) { std::ostringstream os; os << "_shapes" << specialization << "_D"; return os.str(); } std::string create_ctor_name(const ClassSpecialization& specialization) { std::ostringstream os; os << "_shapes" << specialization << "_C"; return os.str(); } std::string create_pool_name(const ClassSpecialization& specialization) { std::ostringstream os; os << "struct.pool." << specialization; return os.str(); } std::string create_ffi_pool_name(const ClassSpecialization& specialization) { std::ostringstream os; os << "shapes_pool_" << specialization; return os.str(); } static std::string create_tbaa_pool_name(const ClassSpecialization& specialization) { std::ostringstream os; os << "_tbaa_pool" << specialization; return os.str(); } static std::string create_tbaa_pool_ptr_name(const ClassSpecialization& specialization) { std::ostringstream os; os << "_tbaa_pool_ptr" << specialization; return os.str(); } std::string create_cluster_name(const ClassSpecialization& specialization, size_t idx) { std::ostringstream os; os << "struct.cluster." << idx << "." << specialization; return os.str(); } std::string create_ffi_cluster_name(const ClassSpecialization& specialization, size_t idx) { std::ostringstream os; os << "_shapes_cluster_" << idx << "_" << specialization; return os.str(); } static std::string create_tbaa_cluster_name(const ClassSpecialization& specialization, size_t idx) { std::ostringstream os; os << "_tbaa_cluster" << idx << "_" << specialization; return os.str(); } static std::string create_tbaa_cluster_ptr_name(const ClassSpecialization& specialization, size_t idx) { std::ostringstream os; os << "_tbaa_cluster_ptr" << idx << "_" << specialization; return os.str(); } std::string create_class_name(const ClassSpecialization& specialization) { std::ostringstream os; os << "struct." << specialization; return os.str(); } std::string create_ffi_class_name(const ClassSpecialization& specialization) { std::ostringstream os; os << "shapes_" << specialization; return os.str(); } static std::string create_tbaa_class_name(const ClassSpecialization& specialization) { std::ostringstream os; os << "_tbaa_class" << specialization; return os.str(); } static std::string create_tbaa_class_ptr_name(const ClassSpecialization& specialization) { std::ostringstream os; os << "_tbaa_class_ptr" << specialization; return os.str(); } void init_llvm() { LLVMInitializeX86TargetInfo(); LLVMInitializeX86Target(); LLVMInitializeX86TargetMC(); LLVMInitializeX86AsmParser(); LLVMInitializeX86AsmPrinter(); auto* pass_registry = llvm::PassRegistry::getPassRegistry(); llvm::initializeCore(*pass_registry); llvm::initializeCodeGen(*pass_registry); llvm::initializeLoopStrengthReducePass(*pass_registry); llvm::initializeGlobalISel(*pass_registry); } void Codegen::Impl::generate_specializations_impl( const Ast::Class& clazz, std::vector<const Ast::Layout*>& curr_layouts) { auto idx = curr_layouts.size(); if (idx == clazz.pools().size()) { m_specialization_info.emplace( ClassSpecialization(clazz, curr_layouts), SpecializationInfo()); return; } curr_layouts.emplace_back(nullptr); generate_specializations_impl(clazz, curr_layouts); const Ast::Pool& idx_pool = clazz.pools()[idx]; const auto& layouts = Ast::for_class(idx_pool.type()).layouts(); for (const auto& e: layouts) { auto& back = curr_layouts.back(); back = &e.get(); generate_specializations_impl(clazz, curr_layouts); } curr_layouts.pop_back(); } struct LLVMTypeFunctor { llvm::Type* operator()(const StandaloneSpecializationInfo& info) const { return info.type; } llvm::Type* operator()(const PoolSpecializationInfo& info) const { return info.pool_type; } }; llvm::Type* Codegen::Impl::type_of(const Ast::PoolType& type, const ClassSpecialization& specialization) { return mpark::visit([this, &specialization](const auto& e) { return this->type_of(e, specialization); }, type); } llvm::Type* Codegen::Impl::type_of(const Ast::NoneType&, const ClassSpecialization&) { return nullptr; } llvm::Type* Codegen::Impl::type_of(const Ast::LayoutType& type, const ClassSpecialization& specialization) { auto new_spec = specialization.specialize_type(type); return mpark::visit( LLVMTypeFunctor(), m_specialization_info[new_spec].type_info); } llvm::Type* Codegen::Impl::type_of(const Ast::BoundType& type, const ClassSpecialization& specialization) { auto new_spec = specialization.specialize_type(type); auto* as_pool = mpark::get_if<PoolSpecializationInfo>(&m_specialization_info[new_spec].type_info); if (as_pool == nullptr) { return nullptr; } return as_pool->pool_type; } void Codegen::Impl::generate_specializations(const Ast::Class& clazz) { std::vector<const Ast::Layout*> curr_layouts; generate_specializations_impl(clazz, curr_layouts); } llvm::Type* Codegen::Impl::type_of(const Ast::NullptrType&, const ClassSpecialization&) { unreachable("Null pointers do not have an LLVM type"); } llvm::Type* Codegen::Impl::type_of(const Ast::VoidType&, const ClassSpecialization&) { return m_void; } llvm::Type* Codegen::Impl::type_of(const Ast::ObjectType& type, const ClassSpecialization& specialization) { auto new_spec = specialization.specialize_type(type); const auto* as_standalone = mpark::get_if<StandaloneSpecializationInfo>( &m_specialization_info[new_spec].type_info); if (as_standalone != nullptr) { return as_standalone->type->getPointerTo(); } return m_intptr; } llvm::Type* Codegen::Impl::type_of(const Ast::PrimitiveType& type, const ClassSpecialization&) { switch (type) { case Ast::PrimitiveType::BOOL: return m_i1; case Ast::PrimitiveType::I8: case Ast::PrimitiveType::U8: return m_i8; case Ast::PrimitiveType::I16: case Ast::PrimitiveType::U16: return m_i16; case Ast::PrimitiveType::I32: case Ast::PrimitiveType::U32: return m_i32; case Ast::PrimitiveType::I64: case Ast::PrimitiveType::U64: return m_i64; case Ast::PrimitiveType::F32: return m_f32; case Ast::PrimitiveType::F64: return m_f64; default: unreachable("Did you introduce an additional case?"); } } llvm::Type* Codegen::Impl::type_of(const Ast::Type& type, const ClassSpecialization& specialization) { return mpark::visit([this, &specialization](const auto& e){ return this->type_of(e, specialization); }, type); } llvm::MDNode* Codegen::Impl::tbaa_type_of(const Ast::Type& type, const ClassSpecialization& specialization) { return mpark::visit([this, &specialization](const auto& e){ return this->tbaa_type_of(e, specialization); }, type); } llvm::MDNode* Codegen::Impl::tbaa_type_of(const Ast::PrimitiveType& type, const ClassSpecialization&) { switch (type) { case Ast::PrimitiveType::BOOL: return m_tbaa_bool; case Ast::PrimitiveType::I8: return m_tbaa_i8; case Ast::PrimitiveType::U8: return m_tbaa_u8; case Ast::PrimitiveType::U16: return m_tbaa_i16; case Ast::PrimitiveType::I16: return m_tbaa_u16; case Ast::PrimitiveType::I32: return m_tbaa_i32; case Ast::PrimitiveType::U32: return m_tbaa_u32; case Ast::PrimitiveType::I64: return m_tbaa_i64; case Ast::PrimitiveType::U64: return m_tbaa_u64; case Ast::PrimitiveType::F32: return m_tbaa_f32; case Ast::PrimitiveType::F64: return m_tbaa_f64; default: unreachable("Did you introduce an additional case?"); } } llvm::MDNode* Codegen::Impl::tbaa_type_of(const Ast::ObjectType& type, const ClassSpecialization& specialization) { auto new_spec = specialization.specialize_type(type); const auto* as_standalone = mpark::get_if<StandaloneSpecializationInfo>( &m_specialization_info[new_spec].type_info); const auto* as_pool = mpark::get_if<PoolSpecializationInfo>( &m_specialization_info[new_spec].type_info); if (as_standalone != nullptr) { return as_standalone->tbaa_ptr_type; } assert_msg(as_pool != nullptr, "Neither an object nor a pool?"); return as_pool->pool_tbaa_ptr_type; } llvm::MDNode* Codegen::Impl::tbaa_type_of(const Ast::VoidType&, const ClassSpecialization&) { unreachable("`void` has no TBAA type"); } llvm::MDNode* Codegen::Impl::tbaa_type_of(const Ast::NullptrType&, const ClassSpecialization&) { unreachable("`nullptr` has no TBAA type"); } llvm::Constant* Codegen::Impl::zero(const Ast::ObjectType& type, const ClassSpecialization& specialization) { auto new_spec = specialization.specialize_type(type); const auto* as_standalone = mpark::get_if<StandaloneSpecializationInfo>( &m_specialization_info[new_spec].type_info); if (as_standalone != nullptr) { return llvm::ConstantPointerNull::get(as_standalone->type->getPointerTo()); } return llvm::ConstantInt::get(m_intptr, -1ull, true); } llvm::Constant* Codegen::Impl::zero(const Ast::PrimitiveType& type, const ClassSpecialization& spec) { if (Ast::is_floating_point(type)) { return llvm::ConstantFP::get(type_of(type, spec), 0.0); } return llvm::ConstantInt::get(type_of(type, spec), 0); } llvm::Constant* Codegen::Impl::zero(const Ast::NullptrType&, const ClassSpecialization&) { unreachable("Null pointers require an explicit check for them"); } llvm::Constant* Codegen::Impl::zero(const Ast::VoidType&, const ClassSpecialization&) { unreachable("Null pointers have no initial value!"); } llvm::Constant* Codegen::Impl::zero(const Ast::Type& type, const ClassSpecialization& specialization) { return mpark::visit([this, &specialization](const auto& e){ return this->zero(e, specialization); }, type); } void Codegen::Impl::generate_llvm_types() { llvm::MDBuilder tbaa_builder(m_ctx); for (auto& e: m_specialization_info) { const auto& spec = e.first; auto& info = e.second; if (spec.is_pooled_type()) { PoolSpecializationInfo pool_info; pool_info.pool_type = llvm::StructType::create(m_ctx, create_pool_name(spec)); pool_info.pool_tbaa_ptr_type = tbaa_builder.createTBAAScalarTypeNode( create_tbaa_pool_ptr_name(spec), m_tbaa_root); info.type_info = std::move(pool_info); } else { StandaloneSpecializationInfo standalone_info; standalone_info.type = llvm::StructType::create(m_ctx, create_class_name(spec)); standalone_info.tbaa_ptr_type = tbaa_builder.createTBAAScalarTypeNode( create_tbaa_class_ptr_name(spec), m_tbaa_root); info.type_info = std::move(standalone_info); } } for (auto& e: m_specialization_info) { const auto& spec = e.first; auto& info = e.second; const auto& data_layout = m_mod->getDataLayout(); llvm::MDBuilder tbaa_builder(m_ctx); const auto* layout = spec.first_pool_param_spec(); if (layout != nullptr) { auto* pool_info = mpark::get_if<PoolSpecializationInfo>(&info.type_info); assert_msg(pool_info != nullptr, "Not a pool type?"); const auto& clusters = layout->clusters(); for (size_t i = 0; i < clusters.size(); i++) { const auto& cluster = clusters[i]; std::vector<llvm::Type*> cluster_fields; for (const Ast::Field* e: cluster.fields()) { auto* type = type_of(e->type(), spec); cluster_fields.push_back(type); } auto* cluster_type = llvm::StructType::create( m_ctx, cluster_fields, create_cluster_name(spec, i)); pool_info->cluster_types.push_back(cluster_type); const auto& cluster_layout = data_layout.getStructLayout(cluster_type); std::vector<std::pair<llvm::MDNode*, uint64_t>> tbaa_fields; for (size_t j = 0; j < cluster.fields().size(); j++) { const Ast::Field* e = cluster.fields()[j]; auto* tbaa_type = tbaa_type_of(e->type(), spec); tbaa_fields.emplace_back( tbaa_type, cluster_layout->getElementOffset(j)); } auto* tbaa_cluster = tbaa_builder.createTBAAStructTypeNode( create_tbaa_cluster_name(spec, i), tbaa_fields); pool_info->cluster_tbaa_types.push_back(tbaa_cluster); } std::vector<llvm::Type*> pool_fields { m_intptr, m_intptr }; for (const auto& e: pool_info->cluster_types) { pool_fields.push_back(e->getPointerTo()); } pool_info->pool_type->setBody(pool_fields); std::vector<std::pair<llvm::MDNode*, uint64_t>> tbaa_fields; const auto& pool_layout = data_layout.getStructLayout(pool_info->pool_type); tbaa_fields.emplace_back( m_tbaa_intptr, pool_layout->getElementOffset(0)); tbaa_fields.emplace_back( m_tbaa_intptr, pool_layout->getElementOffset(1)); for (size_t i = 0; i < layout->clusters().size(); i++) { auto* tbaa_ptr_type = tbaa_builder.createTBAAScalarTypeNode( create_tbaa_cluster_ptr_name(spec, i), m_tbaa_root); pool_info->cluster_tbaa_ptr_types.push_back(tbaa_ptr_type); tbaa_fields.emplace_back( tbaa_ptr_type, pool_layout->getElementOffset(i + 2)); } pool_info->pool_tbaa_type = tbaa_builder.createTBAAStructTypeNode( create_tbaa_pool_name(spec), tbaa_fields); } else { auto* standalone_info = mpark::get_if<StandaloneSpecializationInfo>(&info.type_info); assert_msg(standalone_info != nullptr, "Not a standalone type?"); const auto& ast_fields = spec.clazz().fields(); std::vector<llvm::Type*> fields; for (const Ast::Field& e: ast_fields) { auto* type = type_of(e.type(), spec); fields.push_back(type); } standalone_info->type->setBody(fields); const auto& struct_layout = data_layout.getStructLayout(standalone_info->type); std::vector<std::pair<llvm::MDNode*, uint64_t>> tbaa_fields; for (size_t i = 0; i < ast_fields.size(); i++) { const Ast::Field& field = ast_fields[i]; auto* tbaa_type = tbaa_type_of(field.type(), spec); tbaa_fields.emplace_back( tbaa_type, struct_layout->getElementOffset(i)); } standalone_info->tbaa_type = tbaa_builder.createTBAAStructTypeNode( create_tbaa_class_name(spec), tbaa_fields); } } } void Codegen::Impl::generate_llvm_function_decls() { for (auto& e: m_specialization_info) { const auto& specialization = e.first; auto& info = e.second; std::vector<llvm::Type*> pool_params; for (const Ast::Pool& pool: specialization.clazz().pools()) { auto* type = type_of(pool.type(), specialization); if (type == nullptr) { continue; } pool_params.push_back(type->getPointerTo()); } for (const Ast::Method& method: specialization.clazz().methods()) { std::vector<llvm::Type*> params; // this parameter params.push_back(type_of( specialization.clazz().this_object_type(), specialization)); // Actual function parameters for (const auto& e: method.params()) { params.push_back(type_of(e.type(), specialization)); } params.insert(params.end(), pool_params.begin(), pool_params.end()); auto* ret_type = type_of(method.return_type(), specialization); auto* func_type = llvm::FunctionType::get(ret_type, params, false); auto* func = llvm::Function::Create( func_type, llvm::GlobalValue::ExternalLinkage, create_method_name(specialization, method), m_mod.get()); func->addFnAttr(llvm::Attribute::NoUnwind); info.funcs[&method] = func; } const auto& data_layout = m_mod->getDataLayout(); llvm::MDBuilder tbaa_builder(m_ctx); auto* as_standalone = mpark::get_if<StandaloneSpecializationInfo>( &info.type_info); if (as_standalone != nullptr) { auto* ctor_func_type = llvm::FunctionType::get( as_standalone->type->getPointerTo(), {}, false); as_standalone->ctor = llvm::Function::Create( ctor_func_type, llvm::GlobalValue::ExternalLinkage, create_ctor_name(specialization), m_mod.get()); as_standalone->ctor->setReturnDoesNotAlias(); as_standalone->ctor->addFnAttr(llvm::Attribute::NoUnwind); auto* bb = llvm::BasicBlock::Create(m_ctx, "entry", as_standalone->ctor); llvm::IRBuilder<> builder(bb); auto* class_ptr_type = as_standalone->type->getPointerTo(); auto* size = llvm::ConstantInt::get( data_layout.getIntPtrType(m_ctx), data_layout.getStructLayout(as_standalone->type)->getSizeInBytes()); auto* malloc_ptr = builder.CreateCall(m_malloc, {size}); auto* retval = builder.CreatePointerCast(malloc_ptr, class_ptr_type); const auto* struct_layout = data_layout.getStructLayout(as_standalone->type); const auto& fields = specialization.clazz().fields(); for (size_t i = 0; i < fields.size(); i++) { const Ast::Field& e = fields[i]; auto* field_ptr = builder.CreateStructGEP(as_standalone->type, retval, i); auto* val = zero(e.type(), specialization); auto* insn = builder.CreateStore(val, field_ptr); auto* tbaa_field_type = tbaa_type_of(e.type(), specialization); auto* field_tbaa_node = tbaa_builder.createTBAAStructTagNode( as_standalone->tbaa_type, tbaa_field_type, struct_layout->getElementOffset(i)); insn->setMetadata(llvm::LLVMContext::MD_tbaa, field_tbaa_node); } builder.CreateRet(retval); continue; } auto* as_pool = mpark::get_if<PoolSpecializationInfo>(&info.type_info); if (as_pool != nullptr) { auto* layout = specialization.first_pool_param_spec(); assert_msg(layout != nullptr, "Pool with no layout?"); auto* pool_ctor_type = llvm::FunctionType::get( m_void, {as_pool->pool_type->getPointerTo()}, false); as_pool->pool_alloc = llvm::Function::Create( pool_ctor_type, llvm::GlobalValue::ExternalLinkage, create_pool_ctor_name(specialization), m_mod.get()); as_pool->pool_alloc->addFnAttr(llvm::Attribute::NoUnwind); { auto* bb = llvm::BasicBlock::Create(m_ctx, "entry", as_pool->pool_alloc); llvm::IRBuilder<> builder(bb); assert_msg( !as_pool->pool_alloc->arg_empty(), "Pool constructor has no arguments?"); auto* pool_ptr = as_pool->pool_alloc->arg_begin(); auto* size_ptr = builder.CreateStructGEP(as_pool->pool_type, pool_ptr, 0); const auto* pool_layout = data_layout.getStructLayout(as_pool->pool_type); auto* size_tbaa_node = tbaa_builder.createTBAAStructTagNode( as_pool->pool_tbaa_type, m_tbaa_intptr, pool_layout->getElementOffset(0)); auto* size_insn = builder.CreateStore( llvm::ConstantInt::get(m_intptr, 0), size_ptr); size_insn->setMetadata(llvm::LLVMContext::MD_tbaa, size_tbaa_node); auto* capacity_ptr = builder.CreateStructGEP(as_pool->pool_type, pool_ptr, 1); auto* capacity_tbaa_node = tbaa_builder.createTBAAStructTagNode( as_pool->pool_tbaa_type, m_tbaa_intptr, pool_layout->getElementOffset(1)); auto* capacity_insn = builder.CreateStore( llvm::ConstantInt::get(m_intptr, 0), capacity_ptr); capacity_insn->setMetadata(llvm::LLVMContext::MD_tbaa, capacity_tbaa_node); for (size_t i = 0; i < as_pool->cluster_types.size(); i++) { auto* ptr_type = as_pool->cluster_types[i]->getPointerTo(); auto* cluster_ptr = builder.CreateStructGEP( as_pool->pool_type, pool_ptr, i + 2); auto* cluster_tbaa_node = tbaa_builder.createTBAAStructTagNode( as_pool->pool_tbaa_type, as_pool->cluster_tbaa_ptr_types[i], pool_layout->getElementOffset(i + 2)); auto* store_insn = builder.CreateStore( llvm::Constant::getNullValue(ptr_type), cluster_ptr); store_insn->setMetadata( llvm::LLVMContext::MD_tbaa, cluster_tbaa_node); } builder.CreateRetVoid(); } auto* pool_dtor_type = llvm::FunctionType::get( m_void, {as_pool->pool_type->getPointerTo()}, false); as_pool->pool_free = llvm::Function::Create( pool_dtor_type, llvm::GlobalValue::ExternalLinkage, create_pool_dtor_name(specialization), m_mod.get()); as_pool->pool_free->addFnAttr(llvm::Attribute::NoUnwind); { auto* bb = llvm::BasicBlock::Create(m_ctx, "entry", as_pool->pool_free); llvm::IRBuilder<> builder(bb); llvm::MDBuilder tbaa_builder(m_ctx); assert_msg( !as_pool->pool_free->arg_empty(), "Pool destructor has no arguments?"); auto* pool_ptr = as_pool->pool_free->arg_begin(); const auto* pool_layout = data_layout.getStructLayout(as_pool->pool_type); for (size_t i = 0; i < as_pool->cluster_types.size(); i++) { auto* cluster_type = as_pool->cluster_types[i]; auto* cluster_ptr_type = cluster_type->getPointerTo(); auto* cluster_ptr_field = builder.CreateStructGEP( as_pool->pool_type, pool_ptr, i + 2); auto* cluster_ptr = builder.CreateLoad( cluster_ptr_type, cluster_ptr_field, "cluster_ptr"); auto* cluster_tbaa_node = tbaa_builder.createTBAAStructTagNode( as_pool->pool_tbaa_type, as_pool->cluster_tbaa_ptr_types[i], pool_layout->getElementOffset(i + 2)); cluster_ptr->setMetadata( llvm::LLVMContext::MD_tbaa, cluster_tbaa_node); auto* cluster_ptr_cast = builder.CreatePointerCast( cluster_ptr, m_i8->getPointerTo()); builder.CreateCall(m_free_type, m_free, {cluster_ptr_cast}); } builder.CreateRetVoid(); } auto* alloc_func_type = llvm::FunctionType::get( m_intptr, {as_pool->pool_type->getPointerTo()}, false); as_pool->obj_ctor = llvm::Function::Create( alloc_func_type, llvm::GlobalValue::ExternalLinkage, create_ctor_name(specialization), m_mod.get()); as_pool->obj_ctor->addFnAttr(llvm::Attribute::NoUnwind); auto* bb_entry = llvm::BasicBlock::Create( m_ctx, "entry", as_pool->obj_ctor); auto* bb_call_realloc = llvm::BasicBlock::Create( m_ctx, "call_realloc", as_pool->obj_ctor); auto* bb_alloc = llvm::BasicBlock::Create( m_ctx, "alloc", as_pool->obj_ctor); assert_msg( !as_pool->obj_ctor->arg_empty(), "Pool object constructor has no arguments?"); auto* pool_ptr = as_pool->obj_ctor->arg_begin(); llvm::Value* size_ptr; llvm::Value* capacity_ptr; llvm::Instruction* size; llvm::Instruction* capacity; llvm::IRBuilder<> builder(bb_entry); size_ptr = builder.CreateStructGEP(as_pool->pool_type, pool_ptr, 0, "size_ptr"); const auto* pool_layout = data_layout.getStructLayout(as_pool->pool_type); auto* size_tbaa_node = tbaa_builder.createTBAAStructTagNode( as_pool->pool_tbaa_type, m_tbaa_intptr, pool_layout->getElementOffset(0)); size = builder.CreateLoad(size_ptr, "size"); size->setMetadata(llvm::LLVMContext::MD_tbaa, size_tbaa_node); capacity_ptr = builder.CreateStructGEP(as_pool->pool_type, pool_ptr, 1, "capacity_ptr"); auto* capacity_tbaa_node = tbaa_builder.createTBAAStructTagNode( as_pool->pool_tbaa_type, m_tbaa_intptr, pool_layout->getElementOffset(1)); capacity = builder.CreateLoad(capacity_ptr, "capacity"); capacity->setMetadata(llvm::LLVMContext::MD_tbaa, capacity_tbaa_node); auto* filled = builder.CreateICmpEQ(size, capacity); builder.CreateCondBr(filled, bb_call_realloc, bb_alloc); builder.SetInsertPoint(bb_call_realloc); auto* new_cap = builder.CreateShl(capacity, 1, "capacity_2x"); auto* new_cap_nonzero = builder.CreateICmpNE( new_cap, llvm::ConstantInt::get(m_intptr, 0)); new_cap = builder.CreateSelect( new_cap_nonzero, new_cap, llvm::ConstantInt::get(m_intptr, 1), "new_capacity"); auto* store_cap_insn = builder.CreateStore(new_cap, capacity_ptr); store_cap_insn->setMetadata(llvm::LLVMContext::MD_tbaa, capacity_tbaa_node); const auto& cluster_types = as_pool->cluster_types; for (size_t i = 0; i < cluster_types.size(); i++) { auto* cluster_type = cluster_types[i]; auto* cluster_ptr_type = cluster_type->getPointerTo(); auto* member_ptr = builder.CreateStructGEP( as_pool->pool_type, pool_ptr, i + 2); auto* cluster_tbaa_node = tbaa_builder.createTBAAStructTagNode( as_pool->pool_tbaa_type, as_pool->cluster_tbaa_ptr_types[i], pool_layout->getElementOffset(i + 2)); auto* old_ptr = builder.CreateLoad(member_ptr); old_ptr->setMetadata(llvm::LLVMContext::MD_tbaa, cluster_tbaa_node); auto* old_ptr_cast = builder.CreatePointerCast(old_ptr, m_i8->getPointerTo()); const auto& data_layout = m_mod->getDataLayout(); const auto* cluster_layout = data_layout.getStructLayout(cluster_type); auto* cluster_size = llvm::ConstantInt::get( data_layout.getIntPtrType(m_ctx), cluster_layout->getSizeInBytes()); auto* new_size = builder.CreateMul(new_cap, cluster_size); auto* realloc = builder.CreateCall( m_realloc, {old_ptr_cast, new_size}); auto* store_insn = builder.CreateStore( builder.CreatePointerCast(realloc, cluster_ptr_type), member_ptr); store_insn->setMetadata(llvm::LLVMContext::MD_tbaa, cluster_tbaa_node); } builder.CreateBr(bb_alloc); builder.SetInsertPoint(bb_alloc); auto* new_idx = size; auto* store_size_insn = builder.CreateStore( builder.CreateNUWAdd(size, llvm::ConstantInt::get(m_intptr, 1)), builder.CreateStructGEP(as_pool->pool_type, pool_ptr, 0)); store_size_insn->setMetadata(llvm::LLVMContext::MD_tbaa, size_tbaa_node); const auto& clusters = layout->clusters(); for (size_t i = 0; i < clusters.size(); i++) { const auto& fields = clusters[i].fields(); auto* cluster_tbaa_node = tbaa_builder.createTBAAStructTagNode( as_pool->pool_tbaa_type, as_pool->cluster_tbaa_ptr_types[i], pool_layout->getElementOffset(i + 2)); auto* cluster_ptr = builder.CreateStructGEP( as_pool->pool_type, pool_ptr, i + 2); auto* cluster = builder.CreateLoad(cluster_ptr); cluster->setMetadata(llvm::LLVMContext::MD_tbaa, cluster_tbaa_node); auto* offset_ptr = builder.CreateInBoundsGEP(cluster, new_idx); for (size_t j = 0; j < fields.size(); j++) { auto* cluster_layout = data_layout.getStructLayout(as_pool->cluster_types[i]); auto* tbaa_field_type = tbaa_type_of( fields[j]->type(), specialization); auto* record_tbaa_node = tbaa_builder.createTBAAStructTagNode( as_pool->cluster_tbaa_types[i], tbaa_field_type, cluster_layout->getElementOffset(j)); auto* init_value = zero(fields[j]->type(), specialization); auto* field_ptr = builder.CreateStructGEP( as_pool->cluster_types[i], offset_ptr, j); auto* record_store_insn = builder.CreateStore(init_value, field_ptr); record_store_insn->setMetadata( llvm::LLVMContext::MD_tbaa, record_tbaa_node); } } builder.CreateRet(new_idx); continue; } unreachable("Neither standalone nor pooled?"); } } struct LoopStackEntry { llvm::BasicBlock* loop_continue; llvm::BasicBlock* loop_break; }; struct MethodCodegenState { ClassSpecialization spec; const Ast::Method* method = nullptr; llvm::Function* llvm_func = nullptr; llvm::IRBuilder<>* builder = nullptr; std::unordered_map<const Ast::Variable*, llvm::Value*> local_vars; std::unordered_map<const Ast::Pool*, llvm::Value*> local_pools; std::vector<LoopStackEntry> loop_stack; MethodCodegenState() = default; MethodCodegenState(const MethodCodegenState&) = delete; MethodCodegenState& operator=(const MethodCodegenState&) = delete; }; void Codegen::Impl::generate_llvm_functions() { for (auto& e: m_specialization_info) { const auto& spec = e.first; for (auto& func: e.second.funcs) { const auto& method = *func.first; auto* llvm_func = func.second; MethodCodegenState state; state.spec = spec; state.method = &method; state.llvm_func = llvm_func; auto* bb = llvm::BasicBlock::Create(m_ctx, "entry", llvm_func); llvm::IRBuilder<> builder(bb); state.builder = &builder; const auto& params = method.params(); for (const auto& var: params) { auto* value = builder.CreateAlloca( type_of(var.type(), spec), nullptr, var.name()); state.local_vars[&var] = value; } for (const auto& var: method.vars()) { auto* value = builder.CreateAlloca( type_of(var.type(), spec), nullptr, var.name()); state.local_vars[&var] = value; } for (const auto& pool: method.pools()) { auto* value = builder.CreateAlloca( type_of(pool.type(), spec), nullptr, pool.name()); state.local_pools[&pool] = value; } auto it = llvm_func->arg_begin() + params.size() + 1; const auto& class_params = spec.clazz().pools(); const auto& spec_params = spec.pool_param_types(); for (size_t i = 0; i < class_params.size(); i++) { if (spec_params[i] != nullptr) { const Ast::Pool& pool = class_params[i]; state.local_pools[&pool] = it++; } } for (size_t i = 0; i < params.size(); i++) { builder.CreateStore( llvm_func->arg_begin() + i + 1, state.local_vars[&params[i]]); } for (const auto& var: method.vars()) { builder.CreateStore(zero(var.type(), spec), state.local_vars[&var]); } for (const auto& pool: method.pools()) { const auto* as_pool_type = mpark::get_if<Ast::LayoutType>(&pool.type()); assert_msg( as_pool_type != nullptr, "Local pool has no layout type?"); auto new_spec = spec.specialize_type(*as_pool_type); const auto& type_info = m_specialization_info[new_spec].type_info; const auto* as_pool = mpark::get_if<PoolSpecializationInfo>(&type_info); assert_msg( as_pool != nullptr, "Not a pool specialization?"); builder.CreateCall(as_pool->pool_alloc, {state.local_pools[&pool]}); } for (const auto& stmt: method.body()) { visit(stmt, state); } if (mpark::holds_alternative<Ast::VoidType>(method.return_type())) { builder.CreateRetVoid(); continue; } const auto* as_primitive = mpark::get_if<Ast::PrimitiveType>(&method.return_type()); if (as_primitive != nullptr) { builder.CreateRet(zero(*as_primitive, state.spec)); continue; } const auto* as_object = mpark::get_if<Ast::ObjectType>(&method.return_type()); if (as_object != nullptr) { builder.CreateRet(zero(*as_object, state.spec)); continue; } unreachable("Null return type?"); } } } LLVMExpr Codegen::Impl::visit(const Ast::Expr& e, MethodCodegenState& state) { return mpark::visit([this, &state](const auto& e) { return this->visit(e, state); }, e); } LLVMExpr Codegen::Impl::visit(const Ast::InvalidExpr&, MethodCodegenState&) { unreachable("AST should have no invalid expression nodes"); } void Codegen::Impl::visit(const Ast::Assignment& e, MethodCodegenState& state) { auto lhs = visit(e.lhs(), state); llvm::Value* rhs_value; if (mpark::holds_alternative<Ast::NullExpr>(e.rhs())) { rhs_value = zero(Ast::expr_type(e.lhs()), state.spec); } else { auto rhs = visit(e.rhs(), state); rhs_value = rhs.to_rvalue(); } auto* insn = state.builder->CreateStore(rhs_value, lhs.value()); insn->setMetadata(llvm::LLVMContext::MD_tbaa, lhs.tbaa_metadata()); } void Codegen::Impl::visit(const Ast::OpAssignment& e, MethodCodegenState& state) { auto lhs = visit(e.lhs(), state); auto* lhs_value = lhs.to_rvalue(); auto* rhs_value = visit(e.rhs(), state).to_rvalue(); auto type = Ast::expr_type(e.lhs()); auto rhs_type = Ast::expr_type(e.lhs()); const auto* as_primitive = mpark::get_if<Ast::PrimitiveType>(&type); assert_msg(as_primitive != nullptr, "Must be a primitive type"); bool is_floating_point = Ast::is_floating_point(*as_primitive); llvm::Value* value; switch (e.op()) { case Ast::BinOp::PLUS: { value = is_floating_point ? state.builder->CreateFAdd(lhs_value, rhs_value) : state.builder->CreateAdd(lhs_value, rhs_value); break; } case Ast::BinOp::MINUS: { value = is_floating_point ? state.builder->CreateFSub(lhs_value, rhs_value) : state.builder->CreateSub(lhs_value, rhs_value); break; } case Ast::BinOp::TIMES: { value = is_floating_point ? state.builder->CreateFMul(lhs_value, rhs_value) : state.builder->CreateMul(lhs_value, rhs_value); break; } case Ast::BinOp::DIV: { if (is_floating_point) { value = state.builder->CreateFDiv(lhs_value, rhs_value); } else if (Ast::is_signed_integer(*as_primitive)) { value = state.builder->CreateSDiv(lhs_value, rhs_value); } else { value = state.builder->CreateUDiv(lhs_value, rhs_value); } break; } case Ast::BinOp::AND: { value = state.builder->CreateAnd(lhs_value, rhs_value); break; } case Ast::BinOp::OR: { value = state.builder->CreateOr(lhs_value, rhs_value); break; } case Ast::BinOp::XOR: { value = state.builder->CreateXor(lhs_value, rhs_value); break; } case Ast::BinOp::SHL: { const auto* rhs_as_primitive = mpark::get_if<Ast::PrimitiveType>(&type); assert_msg(rhs_as_primitive != nullptr, "Must be a primitive type"); bool rhs_is_unsigned = Ast::is_unsigned_integer(*rhs_as_primitive); // LLVM requires shift operands to be of the same type auto* shift_amount = rhs_is_unsigned ? state.builder->CreateZExtOrTrunc(rhs_value, lhs_value->getType()) : state.builder->CreateSExtOrTrunc(rhs_value, lhs_value->getType()); value = state.builder->CreateShl(lhs_value, shift_amount); break; } case Ast::BinOp::SHR: { const auto* rhs_as_primitive = mpark::get_if<Ast::PrimitiveType>(&type); assert_msg(rhs_as_primitive != nullptr, "Must be a primitive type"); bool rhs_is_unsigned = Ast::is_unsigned_integer(*rhs_as_primitive); // LLVM requires shift operands to be of the same type auto* shift_amount = rhs_is_unsigned ? state.builder->CreateZExtOrTrunc(rhs_value, lhs_value->getType()) : state.builder->CreateSExtOrTrunc(rhs_value, lhs_value->getType()); value = Ast::is_signed_integer(*as_primitive) ? state.builder->CreateAShr(lhs_value, shift_amount) : state.builder->CreateLShr(lhs_value, shift_amount); break; } default: unreachable("Not applicable to op-assign statements"); } auto* insn = state.builder->CreateStore(value, lhs.value()); insn->setMetadata(llvm::LLVMContext::MD_tbaa, lhs.tbaa_metadata()); } void Codegen::Impl::visit(const Ast::Stmt& stmt, MethodCodegenState& state) { mpark::visit([this, &state](const auto& e) { this->visit(e, state); }, stmt); } void Codegen::Impl::visit(const Ast::If& e, MethodCodegenState& state) { auto* cond_value = visit(e.cond(), state).to_rvalue(); cond_value->setName("cond"); auto* then_bb = llvm::BasicBlock::Create(m_ctx, "if_then", state.llvm_func); auto* else_bb = llvm::BasicBlock::Create(m_ctx, "if_else", state.llvm_func); state.builder->CreateCondBr(cond_value, then_bb, else_bb); auto* next_bb = llvm::BasicBlock::Create(m_ctx, "if_fini", state.llvm_func); state.builder->SetInsertPoint(then_bb); for (const auto& stmt: e.then_stmts()) { visit(stmt, state); } state.builder->CreateBr(next_bb); state.builder->SetInsertPoint(else_bb); for (const auto& stmt: e.else_stmts()) { visit(stmt, state); } state.builder->CreateBr(next_bb); state.builder->SetInsertPoint(next_bb); } void Codegen::Impl::visit(const Ast::While& e, MethodCodegenState& state) { auto* header_bb = llvm::BasicBlock::Create(m_ctx, "while_header", state.llvm_func); auto* body_bb = llvm::BasicBlock::Create(m_ctx, "while_body", state.llvm_func); auto* exit_bb = llvm::BasicBlock::Create(m_ctx, "while_exit", state.llvm_func); LoopStackEntry entry; entry.loop_continue = header_bb; entry.loop_break = exit_bb; state.loop_stack.push_back(entry); state.builder->CreateBr(header_bb); state.builder->SetInsertPoint(header_bb); auto cond = visit(e.cond(), state); auto* cond_value = cond.to_rvalue(); cond_value->setName("cond"); state.builder->CreateCondBr(cond_value, body_bb, exit_bb); state.builder->SetInsertPoint(body_bb); for (const auto& stmt: e.body()) { visit(stmt, state); } state.builder->CreateBr(header_bb); state.builder->SetInsertPoint(exit_bb); state.loop_stack.pop_back(); } void Codegen::Impl::visit(const Ast::ForeachRange& e, MethodCodegenState& state) { auto type = Ast::expr_type(e.range_begin()); const auto* as_primitive = mpark::get_if<Ast::PrimitiveType>(&type); assert_msg(as_primitive != nullptr, "Range loop needs primitives"); bool is_signed = Ast::is_signed_integer(*as_primitive); auto* range_begin = visit(e.range_begin(), state).to_rvalue(); auto* range_end = visit(e.range_end(), state).to_rvalue(); range_begin->setName("range_begin"); range_end->setName("range_end"); auto* var = state.local_vars[&e.var()]; assert_msg(var != nullptr, "No LLVM variable for loop"); auto* init_bb = llvm::BasicBlock::Create(m_ctx, "foreach_range_init", state.llvm_func); auto* exit_bb = llvm::BasicBlock::Create(m_ctx, "foreach_range_exit", state.llvm_func); auto* cond_bb = llvm::BasicBlock::Create(m_ctx, "foreach_range_cond", state.llvm_func); auto* body_bb = llvm::BasicBlock::Create(m_ctx, "foreach_range_body", state.llvm_func); auto* update_bb = llvm::BasicBlock::Create(m_ctx, "foreach_range_update", state.llvm_func); auto* initial_cond = is_signed ? state.builder->CreateICmpSLT(range_begin, range_end, "foreach_initial_cond") : state.builder->CreateICmpULT(range_begin, range_end, "foreach_initial_cond"); state.builder->CreateCondBr(initial_cond, init_bb, exit_bb); state.builder->SetInsertPoint(init_bb); state.builder->CreateStore(range_begin, var); state.builder->CreateBr(cond_bb); state.builder->SetInsertPoint(cond_bb); auto* var_value = state.builder->CreateLoad(var); auto* cond = is_signed ? state.builder->CreateICmpSLT(var_value, range_end, "foreach_cond") : state.builder->CreateICmpULT(var_value, range_end, "foreach_cond"); state.builder->CreateCondBr(cond, body_bb, exit_bb); LoopStackEntry entry; entry.loop_continue = update_bb; entry.loop_break = exit_bb; state.loop_stack.push_back(entry); state.builder->SetInsertPoint(body_bb); for (const auto& stmt: e.body()) { visit(stmt, state); } state.builder->CreateBr(update_bb); state.builder->SetInsertPoint(update_bb); auto* const_one = llvm::ConstantInt::get(var_value->getType(), 1); auto* new_var_value = is_signed ? state.builder->CreateNSWAdd(var_value, const_one, "new_var_value") : state.builder->CreateNUWAdd(var_value, const_one, "new_var_value"); state.builder->CreateStore(new_var_value, var); state.builder->CreateBr(cond_bb); state.loop_stack.pop_back(); state.builder->SetInsertPoint(exit_bb); } void Codegen::Impl::visit(const Ast::ForeachPool& e, MethodCodegenState& state) { const auto& pool_type = e.pool().type(); if (mpark::holds_alternative<Ast::NoneType>(pool_type)) { return; } const auto* as_layout = mpark::get_if<Ast::LayoutType>(&pool_type); const auto* as_bound = mpark::get_if<Ast::BoundType>(&pool_type); auto pool_spec = as_layout ? state.spec.specialize_type(*as_layout) : state.spec.specialize_type(*as_bound); const auto& type_info = m_specialization_info[pool_spec].type_info; const auto* pool_info = mpark::get_if<PoolSpecializationInfo>(&type_info); if (pool_info == nullptr) { return; } auto* pool = state.local_pools[&e.pool()]; assert_msg(pool != nullptr, "Missing pool variable?"); auto* var = state.local_vars[&e.var()]; assert_msg(var != nullptr, "No LLVM variable for loop"); auto* cond_bb = llvm::BasicBlock::Create(m_ctx, "foreach_pool_cond", state.llvm_func); auto* body_bb = llvm::BasicBlock::Create(m_ctx, "foreach_pool_body", state.llvm_func); auto* update_bb = llvm::BasicBlock::Create(m_ctx, "foreach_pool_update", state.llvm_func); auto* exit_bb = llvm::BasicBlock::Create(m_ctx, "foreach_pool_exit", state.llvm_func); state.builder->CreateStore(llvm::ConstantInt::get(m_intptr, 0), var); state.builder->CreateBr(cond_bb); state.builder->SetInsertPoint(cond_bb); llvm::MDBuilder tbaa_builder(m_ctx); const auto& data_layout = m_mod->getDataLayout(); const auto* pool_layout = data_layout.getStructLayout(pool_info->pool_type); auto* size_tbaa_node = tbaa_builder.createTBAAStructTagNode( pool_info->pool_tbaa_type, m_tbaa_intptr, pool_layout->getElementOffset(0)); auto* var_value = state.builder->CreateLoad(var); auto* size_ptr = state.builder->CreateStructGEP(pool, 0, "size_ptr"); auto* size = state.builder->CreateLoad(size_ptr, "size"); size->setMetadata(llvm::LLVMContext::MD_tbaa, size_tbaa_node); auto* cond = state.builder->CreateICmpULT(var_value, size, "initial_cond"); state.builder->CreateCondBr(cond, body_bb, exit_bb); LoopStackEntry entry; entry.loop_continue = update_bb; entry.loop_break = exit_bb; state.loop_stack.push_back(entry); state.builder->SetInsertPoint(body_bb); for (const auto& stmt: e.body()) { visit(stmt, state); } state.builder->CreateBr(update_bb); state.builder->SetInsertPoint(update_bb); auto* const_one = llvm::ConstantInt::get(var_value->getType(), 1); auto* new_var_value = state.builder->CreateNUWAdd(var_value, const_one, "new_idx"); state.builder->CreateStore(new_var_value, var); state.builder->CreateBr(cond_bb); state.loop_stack.pop_back(); state.builder->SetInsertPoint(exit_bb); } void Codegen::Impl::visit(const Ast::ExprStmt& e, MethodCodegenState& state) { if (mpark::holds_alternative<Ast::NullExpr>(e.expr())) { return; } visit(e.expr(), state); } void Codegen::Impl::visit(const Ast::Break&, MethodCodegenState& state) { assert_msg(!state.loop_stack.empty(), "Must be inside loop"); auto& entry = state.loop_stack.back(); state.builder->CreateBr(entry.loop_break); auto* bb = llvm::BasicBlock::Create(m_ctx, "post_break", state.llvm_func); state.builder->SetInsertPoint(bb); } void Codegen::Impl::visit(const Ast::Continue&, MethodCodegenState& state) { assert_msg(!state.loop_stack.empty(), "Must be inside loop"); auto& entry = state.loop_stack.back(); state.builder->CreateBr(entry.loop_continue); auto* bb = llvm::BasicBlock::Create(m_ctx, "post_continue", state.llvm_func); state.builder->SetInsertPoint(bb); } void Codegen::Impl::visit(const Ast::Return& e, MethodCodegenState& state) { if (e.expr() == nullptr) { state.builder->CreateRetVoid(); } else if (mpark::holds_alternative<Ast::NullExpr>(*e.expr())) { auto* as_obj_type = mpark::get_if<Ast::ObjectType>(&state.method->return_type()); state.builder->CreateRet(zero(*as_obj_type, state.spec)); } else { auto* value = visit(*e.expr(), state).to_rvalue(); state.builder->CreateRet(value); } auto* new_bb = llvm::BasicBlock::Create(m_ctx, "after_ret", state.llvm_func); state.builder->SetInsertPoint(new_bb); } LLVMExpr Codegen::Impl::visit(const Ast::IntegerConst& e, MethodCodegenState& state) { auto* value = llvm::ConstantInt::get(type_of(e.type(), state.spec), e.value()); return LLVMExpr(state.builder, value, nullptr, false); } LLVMExpr Codegen::Impl::visit(const Ast::DoubleConst& e, MethodCodegenState& state) { auto* value = llvm::ConstantFP::get(type_of(e.type(), state.spec), e.value()); return LLVMExpr(state.builder, value, nullptr, false); } LLVMExpr Codegen::Impl::visit(const Ast::BooleanConst& e, MethodCodegenState& state) { auto* value = llvm::ConstantInt::get(m_i1, e.value()); return LLVMExpr(state.builder, value, nullptr, false); } LLVMExpr Codegen::Impl::visit(const Ast::NullExpr&, MethodCodegenState&) { unreachable("You must check explicitly for null expressions"); } LLVMExpr Codegen::Impl::visit(const Ast::ThisExpr&, MethodCodegenState& state) { return LLVMExpr(state.builder, state.llvm_func->arg_begin(), nullptr, false); } LLVMExpr Codegen::Impl::visit(const Ast::CastExpr& e, MethodCodegenState& state) { auto* value = visit(e.expr(), state).to_rvalue(); auto type = Ast::expr_type(e.expr()); auto dest_type = e.type(); auto* src_type = mpark::get_if<Ast::PrimitiveType>(&type); assert_msg(src_type != nullptr, "Not a primitive type?"); auto llvm_dest_type = type_of(dest_type, state.spec); auto llvm_src_type = type_of(*src_type, state.spec); // Anything to boolean: Check if non-zero if (Ast::is_boolean(dest_type)) { if (Ast::is_floating_point(*src_type)) { auto* zero = llvm::ConstantFP::get(llvm_src_type, 0.0); auto* cast_val = state.builder->CreateFCmpUNE(value, zero); return LLVMExpr(state.builder, cast_val, nullptr, false); } auto* zero = llvm::ConstantInt::get(llvm_src_type, 0); auto* cast_val = state.builder->CreateICmpNE(value, zero); return LLVMExpr(state.builder, cast_val, nullptr, false); } // Boolean to anything if (Ast::is_boolean(*src_type)) { if (Ast::is_floating_point(dest_type)) { auto* cast_val = state.builder->CreateSelect(value, llvm::ConstantFP::get(llvm_dest_type, 1.0), llvm::ConstantFP::get(llvm_dest_type, 0.0)); return LLVMExpr(state.builder, cast_val, nullptr, false); } auto* cast_val = state.builder->CreateSelect(value, llvm::ConstantInt::get(llvm_dest_type, 1), llvm::ConstantInt::get(llvm_dest_type, 0)); return LLVMExpr(state.builder, cast_val, nullptr, false); } // Anything to float if (Ast::is_floating_point(dest_type)) { if (Ast::is_floating_point(*src_type)) { auto* cast_val = state.builder->CreateFPCast(value, llvm_dest_type); return LLVMExpr(state.builder, cast_val, nullptr, false); } if (Ast::is_signed_integer(*src_type)) { auto* cast_val = state.builder->CreateSIToFP(value, llvm_dest_type); return LLVMExpr(state.builder, cast_val, nullptr, false); } if (Ast::is_unsigned_integer(*src_type)) { auto* cast_val = state.builder->CreateUIToFP(value, llvm_dest_type); return LLVMExpr(state.builder, cast_val, nullptr, false); } } // Float to anything if (Ast::is_floating_point(*src_type)) { // Float to float has been already handled if (Ast::is_signed_integer(dest_type)) { auto* cast_val = state.builder->CreateFPToSI(value, llvm_dest_type); return LLVMExpr(state.builder, cast_val, nullptr, false); } if (Ast::is_unsigned_integer(dest_type)) { auto* cast_val = state.builder->CreateFPToUI(value, llvm_dest_type); return LLVMExpr(state.builder, cast_val, nullptr, false); } } // Int truncation or bitcast if (llvm_dest_type->getScalarSizeInBits() <= llvm_src_type->getScalarSizeInBits()) { auto* cast_val = state.builder->CreateTruncOrBitCast(value, llvm_dest_type); return LLVMExpr(state.builder, cast_val, nullptr, false); } if (Ast::is_signed_integer(*src_type)) { auto* cast_val = state.builder->CreateSExt(value, llvm_dest_type); return LLVMExpr(state.builder, cast_val, nullptr, false); } else { auto* cast_val = state.builder->CreateZExt(value, llvm_dest_type); return LLVMExpr(state.builder, cast_val, nullptr, false); } } LLVMExpr Codegen::Impl::visit(const Ast::UnaryExpr& e, MethodCodegenState& state) { auto* value = visit(e.expr(), state).to_rvalue(); auto type = Ast::expr_type(e.expr()); auto* src_type = mpark::get_if<Ast::PrimitiveType>(&type); assert_msg(src_type != nullptr, "Not a primitive type?"); switch (e.op()) { case Ast::UnOp::PLUS: { return LLVMExpr(state.builder, value, nullptr, false); } case Ast::UnOp::MINUS: { if (Ast::is_floating_point(*src_type)) { return LLVMExpr(state.builder, state.builder->CreateFNeg(value), nullptr, false); } return LLVMExpr(state.builder, state.builder->CreateNeg(value), nullptr, false); } case Ast::UnOp::NOT: { assert_msg(!Ast::is_floating_point(*src_type), "Can't be a float"); return LLVMExpr(state.builder, state.builder->CreateNot(value), nullptr, false); } default: unreachable("Did you introduce an additional case?"); } } LLVMExpr Codegen::Impl::visit(const Ast::BinaryExpr& e, MethodCodegenState& state) { if (e.op() == Ast::BinOp::EQ || e.op() == Ast::BinOp::NE) { auto lhs_type = Ast::expr_type(e.lhs()); auto rhs_type = Ast::expr_type(e.rhs()); auto int_predicate = e.op() == Ast::BinOp::EQ ? llvm::CmpInst::ICMP_EQ : llvm::CmpInst::ICMP_NE; const auto* as_primitive = mpark::get_if<Ast::PrimitiveType>(&lhs_type); if (as_primitive != nullptr) { auto* lhs_value = visit(e.lhs(), state).to_rvalue(); auto* rhs_value = visit(e.rhs(), state).to_rvalue(); if (Ast::is_floating_point(*as_primitive)) { auto float_predicate = e.op() == Ast::BinOp::EQ ? llvm::CmpInst::FCMP_UEQ : llvm::CmpInst::FCMP_UNE; auto* value = state.builder->CreateFCmp( float_predicate, lhs_value, rhs_value); return LLVMExpr(state.builder, value, nullptr, false); } auto* value = state.builder->CreateICmp(int_predicate, lhs_value, rhs_value); return LLVMExpr(state.builder, value, nullptr, false); } const auto* as_lhs_obj = mpark::get_if<Ast::ObjectType>(&lhs_type); const auto* as_rhs_obj = mpark::get_if<Ast::ObjectType>(&rhs_type); const auto& obj_type = as_lhs_obj != nullptr ? *as_lhs_obj : *as_rhs_obj; auto* nullptr_value = zero(obj_type, state.spec); auto* lhs_value = mpark::holds_alternative<Ast::NullptrType>(lhs_type) ? nullptr_value : visit(e.lhs(), state).to_rvalue(); auto* rhs_value = mpark::holds_alternative<Ast::NullptrType>(rhs_type) ? nullptr_value : visit(e.rhs(), state).to_rvalue(); if (lhs_value->getType()->isIntegerTy()) { auto* value = state.builder->CreateICmp( int_predicate, lhs_value, rhs_value); return LLVMExpr(state.builder, value, nullptr, false); } else { auto lhs_intptr = state.builder->CreatePtrToInt(lhs_value, m_intptr); auto rhs_intptr = state.builder->CreatePtrToInt(rhs_value, m_intptr); auto* value = state.builder->CreateICmp( int_predicate, lhs_intptr, rhs_intptr); return LLVMExpr(state.builder, value, nullptr, false); } } auto* lhs_value = visit(e.lhs(), state).to_rvalue(); if (e.op() == Ast::BinOp::LAND || e.op() == Ast::BinOp::LOR) { auto* curr_bb = state.builder->GetInsertBlock(); auto* else_bb = llvm::BasicBlock::Create(m_ctx, "short_circuit", state.llvm_func); auto* next_bb = llvm::BasicBlock::Create(m_ctx, "short_circuit_end", state.llvm_func); if (e.op() == Ast::BinOp::LAND) { state.builder->CreateCondBr(lhs_value, else_bb, next_bb); } else { state.builder->CreateCondBr(lhs_value, next_bb, else_bb); } state.builder->SetInsertPoint(else_bb); auto* rhs_value = visit(e.rhs(), state).to_rvalue(); state.builder->CreateBr(next_bb); state.builder->SetInsertPoint(next_bb); auto* phi = state.builder->CreatePHI(m_i1, 2); if (e.op() == Ast::BinOp::LAND) { phi->addIncoming(rhs_value, else_bb); phi->addIncoming(lhs_value, curr_bb); } else { phi->addIncoming(lhs_value, curr_bb); phi->addIncoming(rhs_value, else_bb); } return LLVMExpr(state.builder, phi, nullptr, false); } auto* rhs_value = visit(e.rhs(), state).to_rvalue(); auto lhs_type = Ast::expr_type(e.lhs()); const auto* as_primitive = mpark::get_if<Ast::PrimitiveType>(&lhs_type); assert_msg( as_primitive != nullptr, "Remaining binary expression kinds operate on primitives"); bool is_floating_point = Ast::is_floating_point(*as_primitive); bool is_signed = Ast::is_signed_integer(*as_primitive); llvm::Value* value; switch (e.op()) { case Ast::BinOp::EQ: case Ast::BinOp::NE: unreachable("Must be handled specifically for pointer equality"); case Ast::BinOp::LAND: case Ast::BinOp::LOR: unreachable("Must be handled specifically for short circuiting"); case Ast::BinOp::PLUS: { if (is_floating_point) { value = state.builder->CreateFAdd(lhs_value, rhs_value); return LLVMExpr(state.builder, value, nullptr, false); } value = state.builder->CreateAdd(lhs_value, rhs_value); return LLVMExpr(state.builder, value, nullptr, false); } case Ast::BinOp::MINUS: { if (is_floating_point) { value = state.builder->CreateFSub(lhs_value, rhs_value); return LLVMExpr(state.builder, value, nullptr, false); } value = state.builder->CreateSub(lhs_value, rhs_value); return LLVMExpr(state.builder, value, nullptr, false); } case Ast::BinOp::TIMES: { if (is_floating_point) { value = state.builder->CreateFMul(lhs_value, rhs_value); return LLVMExpr(state.builder, value, nullptr, false); } value = state.builder->CreateMul(lhs_value, rhs_value); return LLVMExpr(state.builder, value, nullptr, false); } case Ast::BinOp::DIV: { if (is_floating_point) { value = state.builder->CreateFDiv(lhs_value, rhs_value); return LLVMExpr(state.builder, value, nullptr, false); } else if (is_signed) { value = state.builder->CreateSDiv(lhs_value, rhs_value); return LLVMExpr(state.builder, value, nullptr, false); } else { value = state.builder->CreateUDiv(lhs_value, rhs_value); return LLVMExpr(state.builder, value, nullptr, false); } } case Ast::BinOp::AND: { value = state.builder->CreateAnd(lhs_value, rhs_value); break; } case Ast::BinOp::OR: { value = state.builder->CreateOr(lhs_value, rhs_value); break; } case Ast::BinOp::XOR: { value = state.builder->CreateXor(lhs_value, rhs_value); break; } case Ast::BinOp::SHL: { auto rhs_type = Ast::expr_type(e.rhs()); const auto* as_rhs_primitive = mpark::get_if<Ast::PrimitiveType>(&rhs_type); assert_msg( as_rhs_primitive != nullptr, "Shift amount should be a primitive type"); assert_msg( Ast::is_integer(*as_rhs_primitive), "Shift amount should be an integer type"); auto* shift_amount = Ast::is_signed_integer(*as_rhs_primitive) ? state.builder->CreateSExtOrTrunc(rhs_value, lhs_value->getType(), "shift_amt") : state.builder->CreateZExtOrTrunc(rhs_value, lhs_value->getType(), "shift_amt"); value = state.builder->CreateShl(lhs_value, shift_amount); break; } case Ast::BinOp::SHR: { auto rhs_type = Ast::expr_type(e.rhs()); const auto* as_rhs_primitive = mpark::get_if<Ast::PrimitiveType>(&rhs_type); assert_msg( as_rhs_primitive != nullptr, "Shift amount should be a primitive type"); assert_msg( Ast::is_integer(*as_rhs_primitive), "Shift amount should be an integer type"); auto* shift_amount = Ast::is_signed_integer(*as_rhs_primitive) ? state.builder->CreateSExtOrTrunc(rhs_value, lhs_value->getType(), "shift_amt") : state.builder->CreateZExtOrTrunc(rhs_value, lhs_value->getType(), "shift_amt"); value = is_signed ? state.builder->CreateAShr(lhs_value, shift_amount) : state.builder->CreateLShr(lhs_value, shift_amount); break; } case Ast::BinOp::LE: case Ast::BinOp::LT: case Ast::BinOp::GE: case Ast::BinOp::GT: { llvm::ICmpInst::Predicate int_pred; llvm::ICmpInst::Predicate uint_pred; llvm::ICmpInst::Predicate float_pred; if (e.op() == Ast::BinOp::LE) { int_pred = llvm::ICmpInst::ICMP_SLE; uint_pred = llvm::ICmpInst::ICMP_ULE; float_pred = llvm::ICmpInst::FCMP_ULE; } else if (e.op() == Ast::BinOp::LT) { int_pred = llvm::ICmpInst::ICMP_SLT; uint_pred = llvm::ICmpInst::ICMP_ULT; float_pred = llvm::ICmpInst::FCMP_ULT; } else if (e.op() == Ast::BinOp::GE) { int_pred = llvm::ICmpInst::ICMP_SGE; uint_pred = llvm::ICmpInst::ICMP_UGE; float_pred = llvm::ICmpInst::FCMP_UGE; } else { int_pred = llvm::ICmpInst::ICMP_SGT; uint_pred = llvm::ICmpInst::ICMP_UGT; float_pred = llvm::ICmpInst::FCMP_UGT; } if (is_floating_point) { value = state.builder->CreateFCmp(float_pred, lhs_value, rhs_value); } else if (is_signed) { value = state.builder->CreateICmp(int_pred, lhs_value, rhs_value); } else { value = state.builder->CreateICmp(uint_pred, lhs_value, rhs_value); } break; } } return LLVMExpr(state.builder, value, nullptr, false); } LLVMExpr Codegen::Impl::visit(const Ast::VariableExpr& e, MethodCodegenState& state) { auto* value = state.local_vars[&e.var()]; assert_msg(value != nullptr, "Local variable does not exist? O_o"); return LLVMExpr(state.builder, value, nullptr, true); } LLVMExpr Codegen::Impl::visit(const Ast::PoolIndexExpr& e, MethodCodegenState& state) { auto* index = visit(e.index(), state).to_rvalue(); auto type = e.type(); auto obj_type = mpark::get<Ast::ObjectType>(type); auto pool_spec = state.spec.specialize_type(obj_type); if (!pool_spec.is_pooled_type()) { return LLVMExpr(state.builder, zero(type, pool_spec), nullptr, false); } const auto& type_info = m_specialization_info[pool_spec].type_info; const auto& as_pool = mpark::get<PoolSpecializationInfo>(type_info); auto* pool = state.local_pools[&e.pool()]; assert_msg(pool != nullptr, "Local pool variable does not exist? O_o"); llvm::MDBuilder tbaa_builder(m_ctx); const auto& data_layout = m_mod->getDataLayout(); const auto* pool_layout = data_layout.getStructLayout(as_pool.pool_type); auto* size_tbaa_node = tbaa_builder.createTBAAStructTagNode( as_pool.pool_tbaa_type, m_tbaa_intptr, pool_layout->getElementOffset(0)); auto* size_ptr = state.builder->CreateStructGEP(pool, 0, "size_ptr"); auto* size = state.builder->CreateLoad(size_ptr, "size"); size->setMetadata(llvm::LLVMContext::MD_tbaa, size_tbaa_node); auto index_type = Ast::expr_type(e.index()); const auto& as_primitive = mpark::get<Ast::PrimitiveType>(index_type); llvm::Value* cond; llvm::Value* actual_index; if (Ast::is_signed_integer(as_primitive)) { actual_index = state.builder->CreateSExtOrTrunc(index, m_intptr); auto* lhs_cond = state.builder->CreateICmpSGE( actual_index, llvm::ConstantInt::get(m_intptr, 0), "lhs_cond"); auto* rhs_cond = state.builder->CreateICmpULT(actual_index, size, "rhs_cond"); cond = state.builder->CreateAnd(lhs_cond, rhs_cond, "cond"); } else { actual_index = state.builder->CreateZExtOrTrunc(index, m_intptr); cond = state.builder->CreateICmpULT(actual_index, size, "cond"); } auto* value = state.builder->CreateSelect( cond, actual_index, zero(type, pool_spec), "index"); return LLVMExpr(state.builder, value, nullptr, false); } LLVMExpr Codegen::Impl::visit(const Ast::MethodCall& e, MethodCodegenState& state) { std::vector<llvm::Value*> llvm_args; auto* this_value = visit(e.this_expr(), state).to_rvalue(); llvm_args.push_back(this_value); for (size_t i = 0; i < e.args().size(); i++) { const auto& arg = e.args()[i]; if (mpark::holds_alternative<Ast::NullExpr>(arg)) { const auto& arg_type = e.method().params()[i].type(); auto* obj_type = mpark::get_if<Ast::ObjectType>(&arg_type); assert_msg(obj_type != nullptr, "Should be an object type"); llvm_args.push_back(zero(*obj_type, state.spec)); continue; } auto* llvm_arg = visit(arg, state).to_rvalue(); llvm_args.push_back(llvm_arg); } auto this_type = Ast::expr_type(e.this_expr()); auto* this_obj_type = mpark::get_if<Ast::ObjectType>(&this_type); assert_msg(this_obj_type != nullptr, "Type of `this` hould be an object type"); for (size_t i = 0; i < this_obj_type->num_params(); i++) { const auto& params = this_obj_type->params(); const auto* maybe_pool = mpark::get_if<Ast::PoolRef>(&params[i]); if (maybe_pool == nullptr) { continue; } const Ast::Pool& pool = maybe_pool->pool(); auto* value = state.local_pools[&pool]; if (value == nullptr) { continue; } llvm_args.push_back(value); } auto new_spec = state.spec.specialize_type(*this_obj_type); auto* func = m_specialization_info[new_spec].funcs[&e.method()]; auto* value = state.builder->CreateCall(func, llvm_args); return LLVMExpr(state.builder, value, nullptr, false); } LLVMExpr Codegen::Impl::visit(const Ast::FieldAccess& e, MethodCodegenState& state) { auto* value = visit(e.expr(), state).to_rvalue(); const auto& data_layout = m_mod->getDataLayout(); llvm::MDBuilder tbaa_builder(m_ctx); auto type = Ast::expr_type(e.expr()); auto* as_obj_type = mpark::get_if<Ast::ObjectType>(&type); assert_msg(as_obj_type != nullptr, "No object type for field access?"); auto new_spec = state.spec.specialize_type(*as_obj_type); auto& info = m_specialization_info[new_spec]; auto* as_pool = mpark::get_if<PoolSpecializationInfo>(&info.type_info); auto* as_obj = mpark::get_if<StandaloneSpecializationInfo>(&info.type_info); assert_msg(as_pool != nullptr || as_obj != nullptr, "Forgot a case?"); if (as_pool != nullptr) { const auto* layout = new_spec.first_pool_param_spec(); assert_msg(layout != nullptr, "Not a pool type?"); const auto* indices = layout->field_pos(e.field()); assert_msg(indices != nullptr, "Field not in layout?"); const auto& pool_param = as_obj_type->params().front(); const auto* pool_ref = mpark::get_if<Ast::PoolRef>(&pool_param); assert_msg(pool_ref != nullptr, "Pool is null?"); const Ast::Pool& pool = pool_ref->pool(); auto* llvm_pool = state.local_pools[&pool]; assert_msg(llvm_pool != nullptr, "LLVM pool is null?"); const auto* pool_layout = data_layout.getStructLayout(as_pool->pool_type); auto* pool_tbaa_node = tbaa_builder.createTBAAStructTagNode( as_pool->pool_tbaa_type, as_pool->cluster_tbaa_ptr_types[indices->cluster_idx], pool_layout->getElementOffset(indices->cluster_idx + 2)); auto* cluster_ptr_ref = state.builder->CreateStructGEP( as_pool->pool_type, llvm_pool, indices->cluster_idx + 2); auto* cluster_type = as_pool->cluster_types[indices->cluster_idx]; auto* cluster_ptr = state.builder->CreateLoad( cluster_type->getPointerTo(), cluster_ptr_ref); cluster_ptr->setMetadata(llvm::LLVMContext::MD_tbaa, pool_tbaa_node); const auto* cluster_layout = data_layout.getStructLayout( as_pool->cluster_types[indices->cluster_idx]); auto* record_ptr = state.builder->CreateInBoundsGEP( cluster_type, cluster_ptr, value); auto* field_ptr = state.builder->CreateStructGEP( cluster_type, record_ptr, indices->pos); auto* tbaa_field_type = tbaa_type_of(e.type(), state.spec); auto* cluster_tbaa_node = tbaa_builder.createTBAAStructTagNode( as_pool->cluster_tbaa_types[indices->cluster_idx], tbaa_field_type, cluster_layout->getElementOffset(indices->pos)); return LLVMExpr(state.builder, field_ptr, cluster_tbaa_node, true); } auto idx = new_spec.clazz().index_of(e.field()); assert_msg(idx != (size_t)-1, "Field not belonging to class?"); auto* tbaa_field_type = tbaa_type_of(e.type(), state.spec); const auto* layout = data_layout.getStructLayout(as_obj->type); auto* tbaa_node = tbaa_builder.createTBAAStructTagNode( as_obj->tbaa_type, tbaa_field_type, layout->getElementOffset(idx)); auto* field_ptr = state.builder->CreateStructGEP(as_obj->type, value, idx); return LLVMExpr(state.builder, field_ptr, tbaa_node, true); } LLVMExpr Codegen::Impl::visit(const Ast::NewExpr& e, MethodCodegenState& state) { auto new_spec = state.spec.specialize_type(e.type()); auto& info = m_specialization_info[new_spec]; auto* as_pool = mpark::get_if<PoolSpecializationInfo>(&info.type_info); if (as_pool != nullptr) { const auto* maybe_pool = mpark::get_if<Ast::PoolRef>(&e.type().params().front()); assert_msg(maybe_pool != nullptr, "Should have a pool parameter"); const Ast::Pool& pool = maybe_pool->pool(); auto* llvm_pool = state.local_pools[&pool]; assert_msg(llvm_pool != nullptr, "No LLVM pointer to pool?"); auto* retval = state.builder->CreateCall(as_pool->obj_ctor, {llvm_pool}); return LLVMExpr(state.builder, retval, nullptr, false); } auto* as_obj = mpark::get_if<StandaloneSpecializationInfo>(&info.type_info); assert_msg(as_obj != nullptr, "Should be an object"); auto* retval = state.builder->CreateCall(as_obj->ctor); return LLVMExpr(state.builder, retval, nullptr, false); } bool Codegen::Impl::ir(const Ast::Program& ast) { Codegen::Impl state; std::string error; m_target = llvm::TargetRegistry::lookupTarget("x86_64-pc-linux-gnu", error); if (m_target == nullptr) { fprintf(stderr, "Error while creating LLVM target machine: %s", error.c_str()); return false; } m_target_machine = m_target->createTargetMachine( "x86_64-pc-linux-gnu", "generic", "", llvm::TargetOptions(), llvm::Reloc::PIC_, llvm::CodeModel::Small, llvm::CodeGenOpt::Aggressive); m_void = llvm::Type::getVoidTy(m_ctx); m_null = m_void->getPointerTo(); m_i1 = llvm::Type::getInt1Ty(m_ctx); m_i8 = llvm::Type::getInt8Ty(m_ctx); m_i16 = llvm::Type::getInt16Ty(m_ctx); m_i32 = llvm::Type::getInt32Ty(m_ctx); m_i64 = llvm::Type::getInt64Ty(m_ctx); m_f32 = llvm::Type::getFloatTy(m_ctx); m_f64 = llvm::Type::getDoubleTy(m_ctx); m_mod.reset(new llvm::Module("shapes", m_ctx)); m_mod->setDataLayout(m_target_machine->createDataLayout()); m_mod->setTargetTriple("x86_64-pc-linux-gnu"); const auto& data_layout = m_mod->getDataLayout(); m_intptr = data_layout.getIntPtrType(m_ctx); m_malloc_type = llvm::FunctionType::get( m_i8->getPointerTo(), {m_intptr}, false); m_malloc = llvm::Function::Create( m_malloc_type, llvm::GlobalValue::ExternalLinkage, "malloc", m_mod.get()); m_malloc->setReturnDoesNotAlias(); m_malloc->addFnAttr(llvm::Attribute::NoUnwind); m_realloc_type = llvm::FunctionType::get( m_i8->getPointerTo(), {m_i8->getPointerTo(), m_intptr}, false); m_realloc = llvm::Function::Create( m_realloc_type, llvm::GlobalValue::ExternalLinkage, "realloc", m_mod.get()); m_realloc->setReturnDoesNotAlias(); m_realloc->addFnAttr(llvm::Attribute::NoUnwind); m_free_type = llvm::FunctionType::get( m_void, {m_i8->getPointerTo()}, false); m_free = llvm::Function::Create( m_free_type, llvm::GlobalValue::ExternalLinkage, "free", m_mod.get()); m_free->addFnAttr(llvm::Attribute::NoUnwind); llvm::MDBuilder tbaa_builder(m_ctx); m_tbaa_root = tbaa_builder.createTBAARoot("shapes_tbaa_root"); m_tbaa_bool = tbaa_builder.createTBAAScalarTypeNode("bool", m_tbaa_root); m_tbaa_i8 = tbaa_builder.createTBAAScalarTypeNode("i8", m_tbaa_root); m_tbaa_u8 = tbaa_builder.createTBAAScalarTypeNode("u8", m_tbaa_root); m_tbaa_i16 = tbaa_builder.createTBAAScalarTypeNode("i16", m_tbaa_root); m_tbaa_u16 = tbaa_builder.createTBAAScalarTypeNode("u16", m_tbaa_root); m_tbaa_i32 = tbaa_builder.createTBAAScalarTypeNode("i32", m_tbaa_root); m_tbaa_u32 = tbaa_builder.createTBAAScalarTypeNode("u32", m_tbaa_root); m_tbaa_i64 = tbaa_builder.createTBAAScalarTypeNode("i64", m_tbaa_root); m_tbaa_u64 = tbaa_builder.createTBAAScalarTypeNode("u64", m_tbaa_root); m_tbaa_f32 = tbaa_builder.createTBAAScalarTypeNode("f32", m_tbaa_root); m_tbaa_f64 = tbaa_builder.createTBAAScalarTypeNode("f64", m_tbaa_root); m_tbaa_intptr = tbaa_builder.createTBAAScalarTypeNode("intptr", m_tbaa_root); for (const Ast::Class& e: ast.ordered_classes()) { generate_specializations(e); } generate_llvm_types(); generate_llvm_function_decls(); generate_llvm_functions(); llvm::verifyModule(*m_mod, &llvm::errs()); return true; } bool Codegen::Impl::emit( const char* llvm_bitcode_filename, const char* object_filename) { auto opt_level = llvm::PassBuilder::OptimizationLevel::O3; llvm::PassBuilder pass_builder(m_target_machine); llvm::FunctionAnalysisManager fam; llvm::LoopAnalysisManager lam; llvm::CGSCCAnalysisManager cam; llvm::ModuleAnalysisManager mam; fam.registerPass([&] { return pass_builder.buildDefaultAAPipeline(); }); pass_builder.registerFunctionAnalyses(fam); pass_builder.registerLoopAnalyses(lam); pass_builder.registerCGSCCAnalyses(cam); pass_builder.registerModuleAnalyses(mam); pass_builder.crossRegisterProxies(lam, fam, cam, mam); auto func_simplification_pass = llvm::createModuleToFunctionPassAdaptor( pass_builder.buildFunctionSimplificationPipeline( opt_level, llvm::PassBuilder::ThinLTOPhase::None)); llvm::ModulePassManager func_simplification_manager; func_simplification_manager.addPass(std::move(func_simplification_pass)); func_simplification_manager.run(*m_mod, mam); auto mod_simplification_manager = pass_builder.buildModuleSimplificationPipeline( opt_level, llvm::PassBuilder::ThinLTOPhase::None); mod_simplification_manager.run(*m_mod, mam); auto mod_opt_manager = pass_builder.buildModuleOptimizationPipeline(opt_level); mod_opt_manager.run(*m_mod, mam); std::error_code EC; llvm::raw_fd_ostream object_code(object_filename, EC, llvm::sys::fs::OF_None); llvm::raw_fd_ostream llvm_bitcode(llvm_bitcode_filename, EC, llvm::sys::fs::OF_None); llvm_bitcode << *m_mod; llvm::legacy::PassManager legacy_pm; m_target_machine->addPassesToEmitFile( legacy_pm, object_code, nullptr, llvm::TargetMachine::CGFT_ObjectFile); legacy_pm.run(*m_mod); return true; } bool Codegen::Impl::emit_header(const char* header_file_name) const { FILE* out = fopen(header_file_name, "w"); if (out == nullptr) { perror(header_file_name); return false; } fprintf(out, "#include <stdint.h>\n"); fprintf(out, "\n"); fprintf(out, "/*\n"); fprintf(out, " * WARNING: Header file generated by the Shapes compiler.\n"); fprintf(out, " *\n"); fprintf(out, " * Any changes to this file will be lost when recompiling!\n"); fprintf(out, " */\n"); fprintf(out, "\n"); for (const auto& e: m_specialization_info) { const auto& spec = e.first; std::string name; if (spec.is_pooled_type()) { name = create_ffi_pool_name(spec); } else { name = create_ffi_class_name(spec); } fprintf(out, "struct %s;\n", name.c_str()); } fprintf(out, "\n"); for (const auto& e: m_specialization_info) { const auto& spec = e.first; if (spec.is_pooled_type()) { const auto* layout = spec.first_pool_param_spec(); const auto& clusters = layout->clusters(); for (size_t i = 0; i < clusters.size(); i++) { auto cluster_name = create_ffi_cluster_name(spec, i); fprintf(out, "struct %s {\n", cluster_name.c_str()); const auto& cluster = clusters[i]; for (const Ast::Field* field: cluster.fields()) { const auto* as_object = mpark::get_if<Ast::ObjectType>(&field->type()); if (as_object != nullptr) { auto new_spec = spec.specialize_type(*as_object); if (new_spec.is_pooled_type()) { fprintf(out, "\tuintptr_t %s;\n", field->name().c_str()); } else { fprintf(out, "\tstruct %s* %s;\n", create_ffi_class_name(new_spec).c_str(), field->name().c_str()); } continue; } const auto* as_primitive = mpark::get_if<Ast::PrimitiveType>(&field->type()); assert_msg(as_primitive != nullptr, "Forgot to handle a case?"); const auto* type_name = PRIMITIVE_FFI_TYPE_NAMES[(size_t)*as_primitive]; fprintf(out, "\t%s %s;\n", type_name, field->name().c_str()); } fprintf(out, "};\n"); } auto name = create_ffi_pool_name(spec); fprintf(out, "struct %s {\n", name.c_str()); fprintf(out, "\tuintptr_t size;\n"); fprintf(out, "\tuintptr_t capacity;\n"); for (size_t i = 0; i < clusters.size(); i++) { auto cluster_name = create_ffi_cluster_name(spec, i); fprintf(out, "\tstruct %s* cluster%zu;\n", cluster_name.c_str(), i); } fprintf(out, "};\n"); } else { auto name = create_ffi_class_name(spec); fprintf(out, "struct %s {\n", name.c_str()); for (const Ast::Field& field: spec.clazz().fields()) { const auto* as_object = mpark::get_if<Ast::ObjectType>(&field.type()); if (as_object != nullptr) { auto new_spec = spec.specialize_type(*as_object); if (new_spec.is_pooled_type()) { fprintf(out, "\tuintptr_t %s;\n", field.name().c_str()); } else { fprintf(out, "\tstruct %s* %s;\n", create_ffi_class_name(new_spec).c_str(), field.name().c_str()); } continue; } const auto* as_primitive = mpark::get_if<Ast::PrimitiveType>(&field.type()); assert_msg(as_primitive != nullptr, "Forgot to handle a case?"); const auto* type_name = PRIMITIVE_FFI_TYPE_NAMES[(size_t)*as_primitive]; fprintf(out, "\t%s %s;\n", type_name, field.name().c_str()); } fprintf(out, "};\n"); } } fprintf(out, "\n"); fprintf(out, "#ifdef __cplusplus\n"); fprintf(out, "extern \"C\" {\n"); fprintf(out, "#endif // __cplusplus\n"); fprintf(out, "\n"); for (const auto& e: m_specialization_info) { const auto& spec = e.first; if (spec.is_pooled_type()) { auto pool_name = create_ffi_pool_name(spec); fprintf(out, "void %s(struct %s*);\n", create_pool_ctor_name(spec).c_str(), pool_name.c_str()); fprintf(out, "void %s(struct %s*);\n", create_pool_dtor_name(spec).c_str(), pool_name.c_str()); fprintf(out, "uintptr_t %s(struct %s*);\n", create_ctor_name(spec).c_str(), pool_name.c_str()); } else { auto class_name = create_ffi_class_name(spec); fprintf(out, "struct %s* %s(void);\n", class_name.c_str(), create_ctor_name(spec).c_str()); } fprintf(out, "\n"); std::vector<std::pair<std::string, std::string>> pool_names; for (const Ast::Pool& pool: spec.clazz().pools()) { if (mpark::holds_alternative<Ast::NoneType>(pool.type())) { continue; } const auto* as_layout = mpark::get_if<Ast::LayoutType>(&pool.type()); const auto* as_bound = mpark::get_if<Ast::BoundType>(&pool.type()); assert_msg(as_layout != nullptr || as_bound != nullptr, "Forgot a case?"); auto type = as_layout != nullptr ? spec.specialize_type(*as_layout) : spec.specialize_type(*as_bound); if (!type.is_pooled_type()) { continue; } pool_names.emplace_back(create_ffi_pool_name(type), pool.name()); } for (const Ast::Method& m: spec.clazz().methods()) { const auto& return_type = m.return_type(); if (mpark::holds_alternative<Ast::VoidType>(return_type)) { fprintf(out, "void"); } else if (mpark::holds_alternative<Ast::PrimitiveType>(return_type)) { const auto& as_primitive = mpark::get<Ast::PrimitiveType>(return_type); fprintf(out, "%s", PRIMITIVE_FFI_TYPE_NAMES[(size_t)as_primitive]); } else { const auto* as_object = mpark::get_if<Ast::ObjectType>(&return_type); assert_msg(as_object != nullptr, "Missing case?"); auto new_spec = spec.specialize_type(*as_object); if (new_spec.is_pooled_type()) { fprintf(out, "uintptr_t"); } else { fprintf(out, "struct %s*", create_ffi_class_name(new_spec).c_str()); } } auto name = create_method_name(spec, m); fprintf(out, " %s(", name.c_str()); if (spec.is_pooled_type()) { fprintf(out, "uintptr_t self"); } else { fprintf(out, "struct %s* self", create_ffi_class_name(spec).c_str()); } for (const auto& e: m.params()) { const auto* as_primitive = mpark::get_if<Ast::PrimitiveType>(&e.type()); if (as_primitive != nullptr) { fprintf(out, ", %s param_%s", PRIMITIVE_FFI_TYPE_NAMES[(size_t)*as_primitive], e.name().c_str()); continue; } const auto* as_object = mpark::get_if<Ast::ObjectType>(&e.type()); assert_msg(as_object != nullptr, "Missing case?"); auto new_spec = spec.specialize_type(*as_object); if (new_spec.is_pooled_type()) { fprintf(out, ", uintptr_t param_%s", e.name().c_str()); } else { fprintf(out, ", struct %s* param_%s", create_ffi_class_name(new_spec).c_str(), e.name().c_str()); } } for (const auto& e: pool_names) { const auto& type = e.first; const auto& name = e.second; fprintf(out, ", struct %s* pool_%s", type.c_str(), name.c_str()); } fprintf(out, ");\n"); } if (!spec.clazz().methods().empty()) { fprintf(out, "\n"); } } fprintf(out, "#ifdef __cplusplus\n"); fprintf(out, "}\n"); fprintf(out, "#endif // __cplusplus\n"); fclose(out); return true; } llvm::Function* Codegen::Impl::find_method(const ClassSpecialization& spec, const Ast::Method& m) const { auto spec_it = m_specialization_info.find(spec); if (spec_it == m_specialization_info.end()) { return nullptr; } const auto& mapping = spec_it->second.funcs; auto method_it = mapping.find(&m); return (method_it != mapping.end()) ? method_it->second : nullptr; } llvm::Function* Codegen::Impl::constructor(const ClassSpecialization& spec) const { auto it = m_specialization_info.find(spec); if (it == m_specialization_info.end()) { return nullptr; } struct Functor { llvm::Function* operator()(const StandaloneSpecializationInfo& info) { return info.ctor; } llvm::Function* operator()(const PoolSpecializationInfo& info) { return info.obj_ctor; } }; return mpark::visit(Functor(), it->second.type_info); } llvm::Function* Codegen::Impl::pool_constructor(const ClassSpecialization& spec) const { auto it = m_specialization_info.find(spec); if (it == m_specialization_info.end()) { return nullptr; } const auto* as_pool = mpark::get_if<PoolSpecializationInfo>(&it->second.type_info); if (as_pool == nullptr) { return nullptr; } return as_pool->pool_alloc; } Codegen::Codegen() {} Codegen::~Codegen() {} bool Codegen::ir(const Ast::Program& ast) { if (m_impl != nullptr) { return false; } m_impl.reset(new Codegen::Impl); return m_impl->ir(ast); } bool Codegen::emit(const char* llvm_bitcode_filename, const char* object_filename) { return m_impl->emit(llvm_bitcode_filename, object_filename); } std::unique_ptr<llvm::Module> Codegen::Impl::get_module() { return std::move(m_mod); } std::unique_ptr<llvm::Module> Codegen::get_module() { return m_impl->get_module(); } bool Codegen::emit_header(const char* header_file_name) const { return m_impl->emit_header(header_file_name); } llvm::Function* Codegen::find_method(const ClassSpecialization& spec, const Ast::Method& m) const { return m_impl->find_method(spec, m); } class CodegenInterpreter::Impl { const Codegen* m_codegen; llvm::ExecutionEngine* m_engine; public: void init(Codegen& codegen); llvm::GenericValue run_function(llvm::Function* func, std::vector<llvm::GenericValue> values); llvm::Function* find_method(const ClassSpecialization& spec, const Ast::Method& m) const; llvm::Function* constructor(const ClassSpecialization& spec) const; llvm::Function* pool_constructor(const ClassSpecialization& spec) const; }; llvm::Function* Codegen::constructor(const ClassSpecialization& spec) const { return m_impl->constructor(spec); } llvm::Function* Codegen::pool_constructor(const ClassSpecialization& spec) const { return m_impl->pool_constructor(spec); } void CodegenInterpreter::Impl::init(Codegen& codegen) { m_codegen = &codegen; std::string error_msg; llvm::EngineBuilder builder(codegen.get_module()); builder.setErrorStr(&error_msg); builder.setEngineKind(llvm::EngineKind::Interpreter); builder.setVerifyModules(true); m_engine = builder.create(); if (!error_msg.empty()) { fprintf(stderr, "Interpreter error message: %s\n", error_msg.c_str()); } assert_msg(m_engine != nullptr, "Engine was not created? O_o"); m_engine->addGlobalMapping("malloc", (uint64_t) &malloc); m_engine->addGlobalMapping("realloc", (uint64_t) &realloc); m_engine->addGlobalMapping("free", (uint64_t) &free); m_engine->finalizeObject(); } llvm::GenericValue CodegenInterpreter::Impl::run_function( llvm::Function* func, std::vector<llvm::GenericValue> values) { return m_engine->runFunction(func, values); } llvm::Function* CodegenInterpreter::Impl::find_method(const ClassSpecialization& spec, const Ast::Method& m) const { return m_codegen->find_method(spec, m); } llvm::Function* CodegenInterpreter::Impl::constructor(const ClassSpecialization& spec) const { return m_codegen->constructor(spec); } llvm::Function* CodegenInterpreter::Impl::pool_constructor(const ClassSpecialization& spec) const { return m_codegen->pool_constructor(spec); } CodegenInterpreter::CodegenInterpreter() : m_impl(new CodegenInterpreter::Impl) { } CodegenInterpreter::~CodegenInterpreter() {} void CodegenInterpreter::init(Codegen& codegen) { m_impl->init(codegen); } llvm::GenericValue CodegenInterpreter::run_function( llvm::Function* func, std::vector<llvm::GenericValue> values) { return m_impl->run_function(func, values); } llvm::Function* CodegenInterpreter::find_method(const ClassSpecialization& spec, const Ast::Method& m) const { return m_impl->find_method(spec, m); } llvm::Function* CodegenInterpreter::constructor(const ClassSpecialization& spec) const { return m_impl->constructor(spec); } llvm::Function* CodegenInterpreter::pool_constructor(const ClassSpecialization& spec) const { return m_impl->pool_constructor(spec); } } // namespace Ir template<typename T> static inline void hash_combine(std::size_t& seed, T&& v) { using Type = std::remove_cv_t<std::remove_reference_t<T>>; std::hash<Type> hasher; seed ^= hasher(std::forward<T>(v)) + 0x9e3779b9u + (seed<<6) + (seed>>2); } size_t std::hash<Ir::ClassSpecialization>::operator()( const Ir::ClassSpecialization& specialization) const { size_t hash = std::hash<const Ast::Class*>{}(&specialization.clazz()); for (const auto& e: specialization.pool_param_types()) { hash_combine(hash, e); } return hash; }
31.532892
113
0.716736
[ "object", "vector" ]
53b875f5cdbd0b230941cc5e42334e44dbfe3aa5
7,580
cpp
C++
src/engine/editor_extensions/src/choose_asset_window.cpp
code-disaster/halley
5c85c889b76c69c6bdef6f4801c6aba282b7af80
[ "Apache-2.0" ]
1
2021-12-12T23:07:30.000Z
2021-12-12T23:07:30.000Z
src/engine/editor_extensions/src/choose_asset_window.cpp
code-disaster/halley
5c85c889b76c69c6bdef6f4801c6aba282b7af80
[ "Apache-2.0" ]
null
null
null
src/engine/editor_extensions/src/choose_asset_window.cpp
code-disaster/halley
5c85c889b76c69c6bdef6f4801c6aba282b7af80
[ "Apache-2.0" ]
1
2022-01-03T22:49:47.000Z
2022-01-03T22:49:47.000Z
#include "choose_asset_window.h" #include "halley/core/input/input_keyboard.h" #include "halley/ui/ui_anchor.h" #include "halley/ui/widgets/ui_list.h" #include "halley/utils/algorithm.h" #include "halley/ui/widgets/ui_image.h" #include "halley/ui/ui_factory.h" using namespace Halley; ChooseAssetWindow::ChooseAssetWindow(UIFactory& factory, Callback callback, bool canShowBlank, UISizerType orientation, int nColumns) : UIWidget("choose_asset_window", {}, UISizer()) , factory(factory) , callback(std::move(callback)) , orientation(orientation) , nColumns(nColumns) , fuzzyMatcher(false, 100) , canShowBlank(canShowBlank) { highlightCol = factory.getColourScheme()->getColour("ui_stringMatchText"); factory.loadUI(*this, "halley/choose_asset_window"); setModal(true); setAnchor(UIAnchor()); } ChooseAssetWindow::~ChooseAssetWindow() = default; void ChooseAssetWindow::onAddedToRoot(UIRoot& root) { root.setFocus(getWidget("search")); root.registerKeyPressListener(getWidget("options"), 2); root.registerKeyPressListener(shared_from_this(), 1); } void ChooseAssetWindow::setAssetIds(std::vector<String> ids, String defaultOption) { setAssetIds(std::move(ids), {}, std::move(defaultOption)); } void ChooseAssetWindow::setAssetIds(std::vector<String> _ids, std::vector<String> _names, String _defaultOption) { origIds = std::move(_ids); origNames = std::move(_names); defaultOption = std::move(_defaultOption); if (origNames.empty()) { origNames = origIds; } if (origNames.size() != origIds.size()) { throw Exception("Names and ids must have same length", HalleyExceptions::UI); } setCategoryFilter(""); } void ChooseAssetWindow::setCategoryFilter(const String& filterId) { if (filterId.isEmpty()) { ids = origIds; names = origNames; } else { const auto filterIter = std_ex::find_if(categoryFilters, [&] (const auto& f) { return f.id == filterId; }); if (filterIter != categoryFilters.end()) { const auto& curFilter = *filterIter; ids.clear(); names.clear(); for (size_t i = 0; i < origIds.size(); ++i) { if (curFilter.matches(origIds[i])) { ids.push_back(origIds[i]); names.push_back(origNames[i]); } } } else { ids = origIds; names = origNames; } } fuzzyMatcher.clear(); for (size_t i = 0; i < ids.size(); ++i) { fuzzyMatcher.addString(names[i], ids[i]); } populateList(); onCategorySet(filterId); } void ChooseAssetWindow::populateList() { options->clear(); const bool hasFilter = !filter.isEmpty(); const bool forceText = hasFilter; if (forceText) { options->setOrientation(UISizerType::Vertical, 1); } else { options->setOrientation(orientation, nColumns); } if (hasFilter) { for (const auto& r: fuzzyMatcher.match(filter)) { addItem(r.getId(), r.getString(), r.getMatchPositions()); } } else if (canShowAll()) { if (canShowBlank) { options->addTextItem("", LocalisedString::fromHardcodedString("[Empty]")); } std::vector<std::pair<String, String>> items; for (size_t i = 0; i < ids.size(); ++i) { items.emplace_back(ids[i], names[i]); } sortItems(items); for (auto& item: items) { addItem(item.first, item.second); } } options->layout(); if (hasFilter) { options->setSelectedOption(0); } else { options->setSelectedOptionId(defaultOption); } } void ChooseAssetWindow::addItem(const String& id, const String& name, gsl::span<const std::pair<uint16_t, uint16_t>> matchPositions) { const bool hasSearch = !matchPositions.empty(); // Make icon auto icon = makeIcon(id, hasSearch); // Make label auto label = options->makeLabel("", getItemLabel(id, name, hasSearch)); auto labelCol = label->getColour(); if (!matchPositions.empty()) { std::vector<ColourOverride> overrides; for (const auto& p: matchPositions) { overrides.emplace_back(p.first, highlightCol); overrides.emplace_back(p.first + p.second, labelCol); } label->getTextRenderer().setColourOverride(overrides); } options->addItem(id, makeItemSizer(std::move(icon), std::move(label), hasSearch), 1); } std::shared_ptr<UISizer> ChooseAssetWindow::makeItemSizer(std::shared_ptr<UIImage> icon, std::shared_ptr<UILabel> label, bool hasSearch) { auto sizer = std::make_shared<UISizer>(); if (icon) { sizer->add(icon, 0, Vector4f(0, 0, 4, 0)); } sizer->add(label, 0); return sizer; } std::shared_ptr<UISizer> ChooseAssetWindow::makeItemSizerBigIcon(std::shared_ptr<UIImage> icon, std::shared_ptr<UILabel> label) { auto sizer = std::make_shared<UISizer>(UISizerType::Vertical); if (icon) { sizer->add(icon, 0, Vector4f(0, 0, 4, 0), UISizerAlignFlags::CentreHorizontal); } sizer->add(label, 0, {}, UISizerAlignFlags::CentreHorizontal); return sizer; } void ChooseAssetWindow::onCategorySet(const String& id) { } void ChooseAssetWindow::sortItems(std::vector<std::pair<String, String>>& items) { sortItemsByName(items); } void ChooseAssetWindow::sortItemsByName(std::vector<std::pair<String, String>>& items) { std::sort(items.begin(), items.end(), [=] (const auto& a, const auto& b) { return a.second < b.second; }); } void ChooseAssetWindow::sortItemsById(std::vector<std::pair<String, String>>& items) { std::sort(items.begin(), items.end(), [=] (const auto& a, const auto& b) { return a.first < b.first; }); } void ChooseAssetWindow::setCategoryFilters(std::vector<AssetCategoryFilter> filters, const String& defaultOption) { categoryFilters = std::move(filters); getWidget("tabsContainer")->setActive(true); auto tabs = getWidgetAs<UIList>("tabs"); tabs->addTextItemAligned("", LocalisedString::fromHardcodedString("All")); for (const auto& filter: categoryFilters) { auto item = tabs->addTextIconItem(filter.id, filter.showName ? filter.name : LocalisedString(), filter.icon, -1, {}, UISizerAlignFlags::Centre, filter.name); } bindData("tabs", defaultOption, [=] (const String& id) { setCategoryFilter(id); }); setCategoryFilter(defaultOption); } void ChooseAssetWindow::setUserFilter(const String& str) { if (filter != str) { filter = str; populateList(); } } void ChooseAssetWindow::setTitle(LocalisedString title) { getWidgetAs<UILabel>("title")->setText(std::move(title)); } bool ChooseAssetWindow::onKeyPress(KeyboardKeyPress key) { if (key.is(KeyCode::Enter)) { accept(); return true; } if (key.is(KeyCode::Esc)) { cancel(); return true; } return false; } bool ChooseAssetWindow::canShowAll() const { return true; } std::shared_ptr<UIImage> ChooseAssetWindow::makeIcon(const String& id, bool hasSearch) { return {}; } UIFactory& ChooseAssetWindow::getFactory() const { return factory; } void ChooseAssetWindow::onMakeUI() { options = getWidgetAs<UIList>("options"); setHandle(UIEventType::ButtonClicked, "ok", [=] (const UIEvent& event) { accept(); }); setHandle(UIEventType::ButtonClicked, "cancel", [=](const UIEvent& event) { cancel(); }); setHandle(UIEventType::TextChanged, "search", [=](const UIEvent& event) { setUserFilter(event.getStringData()); }); setHandle(UIEventType::TextSubmit, "search", [=](const UIEvent& event) { accept(); }); setChildLayerAdjustment(10); } LocalisedString ChooseAssetWindow::getItemLabel(const String& id, const String& name, bool hasSearch) { return LocalisedString::fromUserString(name); } void ChooseAssetWindow::accept() { const auto id = getWidgetAs<UIList>("options")->getSelectedOptionId(); if (canShowBlank || !id.isEmpty()) { if (callback) { callback(id); destroy(); } callback = {}; } } void ChooseAssetWindow::cancel() { callback({}); destroy(); }
24.690554
159
0.703958
[ "vector" ]
53b99576015353e4e2baf9a5bc46523eb73d69c8
9,266
cpp
C++
catkin_ws/src/statek_nav/src/mpc.cpp
Tai-Min/Statek-UAV
932219cde0707cd2cf288e467226a21b8c24d19e
[ "MIT" ]
null
null
null
catkin_ws/src/statek_nav/src/mpc.cpp
Tai-Min/Statek-UAV
932219cde0707cd2cf288e467226a21b8c24d19e
[ "MIT" ]
null
null
null
catkin_ws/src/statek_nav/src/mpc.cpp
Tai-Min/Statek-UAV
932219cde0707cd2cf288e467226a21b8c24d19e
[ "MIT" ]
null
null
null
#include "../include/mpc.hpp" #include <cppad/ipopt/solve.hpp> #include <Eigen/Core> #include <tf/transform_broadcaster.h> #include <tf2_ros/transform_broadcaster.h> #include <tf2_ros/transform_listener.h> #include <tf2/transform_datatypes.h> #include <chrono> #include <iostream> using namespace std; MPC::MPC(double _horizonDurationForward, double _horizonSamplingForward, double _horizonDurationRotate, double _horizonSamplingRotate, const Constraints &_constraints, const CostWeights &_weights, const double _goalArea, const std::string &_solverOptions) : horizonSamplingForward(_horizonSamplingForward), horizonDurationForward(_horizonDurationForward), horizonSamplingRotate(_horizonSamplingRotate), horizonDurationRotate(_horizonDurationRotate), constraints(_constraints), weights(_weights), goalArea(_goalArea), solverOptions(_solverOptions), tfThread(&MPC::tfThreadFcn, this) { } MPC::~MPC() { stopTfThread = true; tfThread.join(); } void MPC::tfThreadFcn() { auto previousTfTime = std::chrono::steady_clock::now(); while (!stopTfThread) { auto now = std::chrono::steady_clock::now(); // Check for tf timeouts to stop the controller. auto tfElapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - previousTfTime).count(); if (tfElapsed > 3000) tfReceived = false; // Get location of the robot on local map. bool ok = false; geometry_msgs::TransformStamped robotTransform = getTransform("statek/earth", "statek/base_footprint", ok); if (ok) { tfReceived = true; // Tf received so allow MPC to work. previousTfTime = std::chrono::steady_clock::now(); // Convert orientation to tf quaternion. tf::Quaternion quat; tf::quaternionMsgToTF(robotTransform.transform.rotation, quat); // Convert orientation to RPY angles. double temp1, temp2, theta; tf::Matrix3x3(quat).getRPY(temp1, temp2, theta); theta = wrapToPi(theta); // Set current state. const std::lock_guard<std::mutex> lck(stateMtx); state = {robotTransform.transform.translation.x, robotTransform.transform.translation.y, theta, 0, 0, -1}; // Get cross track error and orientation error. findCteOe(state, 0); } } } double MPC::wrapToPi(double angle) { // Whiles because fmod works strange? if (angle > M_PI) angle -= M_PI; if (angle < -M_PI) angle += M_PI; if (angle == -M_PI) angle = M_PI; return angle; } double MPC::distancePointLine(double x0, double y0, double x1, double y1, double x2, double y2) { return fabs((x2 - x1) * (y1 - y0) - (x1 - x0) * (y2 - y1)) / sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)); } void MPC::findCteOe(State &_state, int lastIdx) const { int bestIdx = -1; _state.cte = std::numeric_limits<double>::max(); for (int i = lastIdx; i < path.size(); i++) { double currentCte = distancePointLine(_state.x, _state.y, path[i].x0, path[i].y0, path[i].x1, path[i].y1); if (currentCte < _state.cte) { _state.cte = currentCte; bestIdx = i; } } if (bestIdx >= 0) { double distanceToEnd = sqrt(pow(_state.x - path[bestIdx].x1, 2) + pow(_state.y - path[bestIdx].y1, 2)); // If distance of the vehicle and end of best segment is less than some limiting value // then we'd rather care for next segment if there is one. if (distanceToEnd < goalArea && bestIdx < path.size() - 1) { bestIdx++; _state.cte = distancePointLine(_state.x, _state.y, path[bestIdx].x0, path[bestIdx].y0, path[bestIdx].x1, path[bestIdx].y1); } _state.oe = wrapToPi(path[bestIdx].angle - _state.yaw); } _state.cteIdx = bestIdx; } geometry_msgs::TransformStamped MPC::getTransform(const std::string &targetFrame, const std::string &sourceFrame, bool &ok) { static tf2_ros::Buffer tfBuffer; static tf2_ros::TransformListener transformListener(tfBuffer); geometry_msgs::TransformStamped result; if (targetFrame == "" || sourceFrame == "") { ok = false; return result; } // Fixes extrapolation into the future in Rviz if run remotely. ros::Time now = ros::Time::now(); ok = tfBuffer.canTransform(targetFrame, sourceFrame, now, ros::Duration(10.0)); if (!ok) return result; ok = true; try { result = tfBuffer.lookupTransform(targetFrame, sourceFrame, now); } catch (tf::TransformException ex) { ok = false; } return result; } MPC::Control MPC::update() { auto startFcn = chrono::steady_clock::now(); if (!tfReceived || !path.size()) return {0, 0, {}, true}; { const std::lock_guard<std::mutex> lckOe(stateMtx); // Calculace current prediction horizon depending on oe. // Use simple linear equation to do that. horizonSampling = abs(state.oe) * (horizonSamplingRotate - horizonSamplingForward) / M_PI + horizonSamplingForward; horizonDuration = abs(state.oe) * (horizonDurationRotate - horizonDurationForward) / M_PI + horizonDurationForward; N = horizonDuration / horizonSampling; } int numVars = numInputs * (N - 1); angularVelocityStart = linearVelocityStart + N - 1; // Initial state of variables. Dvector vars(numVars); for (int i = 0; i < numVars; i++) { vars[i] = 0; } // Constraints for variables. Dvector varsLowerConstraints(numVars); Dvector varsUpperConstraints(numVars); for (int i = linearVelocityStart; i < angularVelocityStart; i++) { varsLowerConstraints[i] = constraints.linearMin; varsUpperConstraints[i] = constraints.linearMax; } for (int i = angularVelocityStart; i < numVars; i++) { varsLowerConstraints[i] = constraints.angularMin; varsUpperConstraints[i] = constraints.angularMax; } // Constraints for constraint equations g(x). Dvector stateLowerConstraints(0); Dvector stateUpperConstraints(0); // MPC evaluation. FG_eval evalFcn(this); CppAD::ipopt::solve_result<Dvector> solution; const std::lock_guard<std::mutex> lckOpti(stateMtx); try { CppAD::ipopt::solve<Dvector, FG_eval>( solverOptions, vars, varsLowerConstraints, varsUpperConstraints, varsLowerConstraints, varsUpperConstraints, evalFcn, solution); } catch (...) { return {0, 0, {}, true}; } /*if (solution.status != CppAD::ipopt::solve_result<Dvector>::success) { return {0, 0, {}, true}; }*/ Control control; control.success = true; // Apply first set of controls. control.linearVelocity = solution.x[linearVelocityStart]; control.angularVelocity = solution.x[angularVelocityStart]; // Copy state trajectory. control.stateTrajectory = evalFcn.evalControl(solution.x, state); auto endFcn = chrono::steady_clock::now(); //ROS_WARN("MPC update elapsed time in milliseconds: %ldms.\n---", chrono::duration_cast<chrono::milliseconds>(endFcn - startFcn).count()); return control; } void MPC::onNewPath(const nav_msgs::Path::ConstPtr &pathMsg) { if (!pathMsg->poses.size()) return; // If previous and current paths were not a straight line // but a bunch of segments, then check whether it is necessary to update it. // This prevents vehicle from being stuck in front of an obstacle // when map changes rapidly fron one side of this obstacle to another. if (path.size() > 1 && pathMsg->poses.size() > 2) { double distanceToGoal; double distanceTravelled; { const std::lock_guard<std::mutex> lckOpti(stateMtx); distanceToGoal = sqrt(pow(path[0].x1 - state.x, 2) + pow(path[0].y1 - state.y, 2)); distanceTravelled = sqrt(pow(onMapState.x - state.x, 2) + pow(onMapState.y - state.y, 2)); } // Ignore path if the vehicle haven't achieved subgoal // or travelled a bit or some time passed. if (distanceToGoal > goalArea || distanceTravelled < 0.2) return; } path.clear(); // Translate path message into Path data type. for (int i = 0; i < pathMsg->poses.size() - 1; i++) { PathSegment segment; segment.x0 = pathMsg->poses[i].pose.position.x; segment.y0 = pathMsg->poses[i].pose.position.y; segment.x1 = pathMsg->poses[i + 1].pose.position.x; segment.y1 = pathMsg->poses[i + 1].pose.position.y; segment.angle = wrapToPi(atan2(segment.y1 - segment.y0, segment.x1 - segment.x0)); path.push_back(segment); } const std::lock_guard<std::mutex> lckOpti(stateMtx); onMapState = state; } void MPC::onNewInputs(const geometry_msgs::TwistStamped::ConstPtr &currentInputs) { inputs.linearVelocity = currentInputs->twist.linear.x; inputs.angularVelocity = currentInputs->twist.angular.z; }
31.624573
143
0.633607
[ "transform" ]
53bfc34d16878bf1a66278b32b17cb18c0598de9
45,539
hpp
C++
src/lib/LoadManager.hpp
Sourin-chatterjee/SpinParser
23fa90c327b8a4543e5afac1b64d18df40975182
[ "MIT" ]
18
2021-06-03T16:03:02.000Z
2022-02-28T00:48:53.000Z
src/lib/LoadManager.hpp
Sourin-chatterjee/SpinParser
23fa90c327b8a4543e5afac1b64d18df40975182
[ "MIT" ]
3
2021-10-08T15:51:51.000Z
2022-03-31T22:20:01.000Z
src/lib/LoadManager.hpp
Sourin-chatterjee/SpinParser
23fa90c327b8a4543e5afac1b64d18df40975182
[ "MIT" ]
2
2022-02-10T17:15:05.000Z
2022-02-11T19:54:27.000Z
/** * @file LoadManager.hpp * @author Finn Lasse Buessen * @brief Implementation of an automatic hybrid OpenMP / MPI load balancer. * * @copyright Copyright (c) 2020 */ #pragma once #include <vector> #include <functional> #include <thread> #include <mutex> #include <boost/date_time.hpp> #include "lib/Log.hpp" #include "lib/Exception.hpp" #ifndef DISABLE_MPI #include "mpi.h" #endif #ifndef DISABLE_OMP #include "omp.h" #endif #define HMP_CHUNK_PROPERTY_STACK 0 ///< Memory offset of the stack id in the chunk properties. #define HMP_CHUNK_PROPERTY_BEGIN 1 ///< Memory offset of the workload begin in the chunk properties. #define HMP_CHUNK_PROPERTY_END 2 ///< Memory offset of the workload end in the chunk properties. #ifndef DISABLE_MPI #define HMP_MPI_ENABLED ///< Defined, if MPI parallelization is enabled. #define HMP_ENABLE_IF_MPI(X) X ///< Print argument if MPI parallelization is enabled. #define HMP_DISABLE_IF_MPI(X) ///< Do not print argument if MPI parallelization is enabled. #define HMP_APPEND_IF_MPI(X) ,X ///< Append argument if MPI parallelizatino is enabled. #else #define HMP_ENABLE_IF_MPI(X) ///< Print argument if MPI parallelization is enabled. #define HMP_DISABLE_IF_MPI(X) X ///< Do not print argument if MPI parallelization is enabled. #define HMP_APPEND_IF_MPI(X) ///< Append argument if MPI parallelizatino is enabled. #endif namespace HMP { class LoadManager; typedef int StackIdentifier; ///< DataStack identifier. /** * @brief Common load manager interface for both, the MPI server rank and slave ranks. * @details This class provides an implementation of an automatic load balancing scheme for hybrid shared/distributed memory parallelization. * Intra-node parallelization is implemented via OpenMP. Inter-node parallelization is implemented via MPI. * A LoadManager instance is created on every MPI rank by calling the LoadManager::newLoadManager routine; * This will create a LoadManagerMaster instance on the designated MPI master rank, and LoadManagerSlave instances on all remaining ranks. * The work load is registered with the LoadManager in the form of DataStacks. Each data stack is associated with an array of numbers * and with a functional description (referred to as calculators) on how to perform computations on the individual array entries. * Different types of data stack exist with different calculator properties, see DataStackBase::StackType for more information. * The LoadManager interface provides functions to create and register the different stack types with the LoadManager. * * The role of the LoadManagerMaster is to break down the collective computation of all array entries into smaller chunks of work, * to distribute them either locally or across multiple MPI ranks, and to retrieve the result on the master rank. * In order to execute the calculators on a specific stack, the LoadManager provides the LoadManager::calculate interface. * In order to make the results available also on other MPI ranks, the LoadManager::broadcast interface is provided. * Various different types of data stacks exist, see the appropriate member functions for adding new stacks. * * @see LoadManager::newLoadManager * @see LoadManager::calculate * @see LoadManager::broadcast */ class LoadManager { protected: /** * @brief Abstract base class for DataStack types. * @details This abstract type does not actually store data or prescriptions for calculations. * It merely specifies the virtual interface for inheritance. Subclasses should then implement data storage and calculators, see concrete implementations for more details. * * @see DataStack */ struct DataStackBase { /** * @brief List to identify the different traits of DataStack. */ enum struct StackType { /** * @brief Explicit DataStack * @details An explicit DataStack contains an explicit calculator, i.e. a function with a single integer as an argument, and a non-void return type. * When the calculator is invoked, its return value is written to the data element whose position is specified by the integer argument. * @see LoadManager::addMasterStackExplicit */ Explicit, /** * @brief Implicit DataStack * @details An implicit DataStack contains an implicit calculator, i.e. a function with a single integer as an argument, and a void return type. * When the calculator is invoked, it is passed the index of a data element stored in the stack. The calculator is expected to modify that element. * @see LoadManager::addMasterStackImplicit */ Implicit, /** * @brief Slave DataStack * @details A slave DataStack does not contain a calculator. Instead, it is associated with an implicit data stack. * The data storage is expected to have the same size as the associated implicit stack, and the associated stack's implicit calculator is expected to modify also the slave stack's element with the corresponding index. * Whenever data of the associated implicit stack is communicated between different MPI ranks, the corresponding slave stack data is also communicated. * @see LoadManager::addSlaveStack */ Slave, /** * @brief Passive DataStack * @details A passive DataStack does not contain a calculator. Changes to its data can only be made on the MPI server rank and need to be manually broadcasted. * @see LoadManager::addPassiveStack */ Passive }; /** * @brief Internal message tags for MPI communication. */ enum struct MessageTag { Chunk, ///< MPI message contains Chunk information ChunkReturn, ///< MPI message contains the result of a chunk computation }; /** * @brief Virtual destructor. */ virtual ~DataStackBase() {}; /** * @brief Virtual function to apply an internal calculator to the n-th value stored in the stack. * * @param n Specifies the index to which the calculator should be applied. */ virtual void applyCalculator(const int n) {}; #ifdef HMP_MPI_ENABLED /** * @brief Virtual function to send a data block to a DataStack on a different MPI rank, typically the server rank. * * @param offset Offset to the beginning of the data block to be sent, measured in number of entries (or number of entry tuples, if DataStackBase::typeMultiplicity is greater than one). * @param count Number of entries to be sent. * @param serverRank Receiver's MPI rank, typically the server rank. * @param communicator The MPI communicator used for communication. */ virtual void send(const int offset, const int count, const int serverRank, const MPI_Comm communicator) const {}; /** * @brief Virtual function to asynchronously receive a data block from a different MPI rank. * * @param[in] offset Offset to the beginning of the data block to be received, measured in number of entries (or number of entry tuples, if DataStackBase::typeMultiplicity is greater than one). * @param[in] count Number of entries to be received. * @param[in] rank Sender's MPI rank. * @param[in] communicator The MPI communicator used for communication. * @param[out] request MPI request object for the communication; Should be used to determine whether the non-blocking receive has been completed. */ virtual void receive(const int offset, const int count, const int rank, const MPI_Comm communicator, MPI_Request &request) {}; /** * @brief Virtual function to broadcast a data block from the server rank to all other MPI ranks. * * @param serverRank The MPI rank to take the role of the sender. * @param communicator The MPI communicator used for communication. */ virtual void broadcast(const int serverRank, const MPI_Comm communicator) {}; #endif StackType type; ///< Specifies the trait of the stack @see StackType. StackIdentifier master; ///< Specifies the id of an associated stack. Only relevant for slave stacks, otherwise set to -1. @see StackType::Slave int size; ///< Number of elements (or tuples of elements if DataStackBase::typeMultiplicity is greater than one) stored in the stack. int typeMultiplicity; ///< Multiplicity of each element. Cannot be greater than one for explicit stacks. If greater than one, the data stack is assumed to consist of tuples of fundamental data types. Element indexing then refers to the tuples, not the fundamental data types. int recommendedChunkSizeMultiple; ///< When breaking the data stack down into smaller work chunks, attempt to form chunks whose size is a multiple of the given value. This is helpful if calculators vary in runtime, but can be joined to groups whose collective runtime is expected to be constant. int recommendedChunksPerRank; ///< When breaking the data stack down into smaller work chunks, attempt to form approximately the specified number of chunks per MPI rank. bool autoBroadcast; ///< If set to true, modifications to the stack's data that are a consequence of the onvication of calculators are automatically communicated across all MPI ranks. If set to false, they are only sent to the MPI server rank. }; /** * @brief Concrete derivation of DataStackBase, managing an array of fundamental data types (or tuples thereof, if DataStackBase::typeMultiplicity is greater than one). * * @tparam StackT The fundamental data type stored in the internal data array. */ template <class StackT> struct DataStack : public DataStackBase { friend class LoadManager; protected: /** * @brief Construct a new Data Stack object. * * @see LoadManager::addMasterStackExplicit * @see LoadManager::addMasterStackImplicit * @see LoadManager::addSlaveStack * @see LoadManager::addPassiveStack */ DataStack() {} /** * @brief Invoke internal calculator and write result to the data array at the specified index. * * @param i Index of the element to which the result is written. */ void applyCalculator(const int i) override { if (type == StackType::Implicit) implicitCalculator(i); else if (type == StackType::Explicit) data[i] = explicitCalculator(i); } #ifdef HMP_MPI_ENABLED /** * @brief Send a data block to a different MPI rank, typically the server rank. * * @param offset Id of the first element of the data block to be sent, measured in number of entries (or number of entry tuples, if DataStackBase::typeMultiplicity is greater than one). * @param count Number of elements (or element tuples) to be sent. * @param serverRank Receiver's MPI rank, typically the server rank. * @param communicator The MPI communicator used for communication. */ void send(const int offset, const int count, const int serverRank, const MPI_Comm communicator) const override { MPI_Send(static_cast<void *>(data + typeMultiplicity * offset), typeMultiplicity *count * sizeof(StackT), MPI_BYTE, serverRank, static_cast<int>(MessageTag::ChunkReturn), communicator); } /** * @brief Asynchronously receive a data block from a different MPI rank. * * @param[in] offset Id of the first element of the data block to be received, measured in number of entries (or number of entry tuples, if DataStackBase::typeMultiplicity is greater than one). * @param[in] count Number of elements (or element tuples) to be received. * @param[in] rank Sender's MPI rank. * @param[in] communicator The MPI communicator used for communication. * @param[out] request MPI request object for the communication; Should be used to determine whether the non-blocking receive has been completed. */ void receive(const int offset, const int count, const int rank, const MPI_Comm communicator, MPI_Request &request) override { MPI_Irecv(static_cast<void *>(data + typeMultiplicity * offset), typeMultiplicity *count * sizeof(StackT), MPI_BYTE, rank, static_cast<int>(MessageTag::ChunkReturn), communicator, &request); } /** * @brief Broadcast a data block from the server rank to all other MPI ranks. * * @param serverRank The MPI rank to take the role of the sender. * @param communicator The MPI communicator used for communication. */ void broadcast(const int serverRank, const MPI_Comm communicator) override { MPI_Bcast(static_cast<void *>(data), typeMultiplicity * size * sizeof(StackT), MPI_BYTE, serverRank, communicator); } #endif std::function<StackT(int)> explicitCalculator; ///< Explicit calculator. Only relevant if DataStackBase::type is set to StackType::Explicit. std::function<void(int)> implicitCalculator; ///< Implicit calculator. Only relevant if DataStackBase::type is set to StackType::Implicit. StackT *data; ///< Internal data array. }; /** * @brief Definition of a small chunk of work. Used to communicate workload between different LoadManager instances. */ struct Chunk { public: ///Construct an empty work chunk Chunk() { properties[HMP_CHUNK_PROPERTY_STACK] = -1; properties[HMP_CHUNK_PROPERTY_BEGIN] = 0; properties[HMP_CHUNK_PROPERTY_END] = 0; }; /** * @brief Construct a work chunk for a specific workload. * * @param stackId Id of the stack that the work should be performed on. * @param begin Index of the first element whose calculator should be invoked. * @param end Index of the last element whose calculator should be invoked. */ Chunk(const int stackId, const int begin, const int end) { properties[HMP_CHUNK_PROPERTY_STACK] = stackId; properties[HMP_CHUNK_PROPERTY_BEGIN] = begin; properties[HMP_CHUNK_PROPERTY_END] = end; } ///Check of the workload is empty bool isVoid() const { return (properties[HMP_CHUNK_PROPERTY_STACK] == -1); } ///Comparison operator bool operator==(const Chunk &rhs) const { return (properties[HMP_CHUNK_PROPERTY_STACK] == rhs.properties[HMP_CHUNK_PROPERTY_STACK]) && (properties[HMP_CHUNK_PROPERTY_BEGIN] == rhs.properties[HMP_CHUNK_PROPERTY_BEGIN]) && (properties[HMP_CHUNK_PROPERTY_END] == rhs.properties[HMP_CHUNK_PROPERTY_END]); } ///Negative comparison operator bool operator!=(const Chunk &rhs) const { return !this->operator==(rhs); } int properties[3]; ///< Workload specification. First value describes the stack id, second value describes the first element of the workload, and the third value the last element of the workload. }; public: ///Destroy the LoadManager object virtual ~LoadManager() { HMP_ENABLE_IF_MPI(MPI_Comm_free(&_communicator)); while (_stacks.size() > 0) { delete _stacks.back(); _stacks.pop_back(); } } /** * @brief Create an explicit data stack and attach it to the LoadManager. * * @tparam StackT The fundamental data type of the DataStack to be created. * @param data Data array on which the stack operates. The allocated size should be at least size * typeof(StackT). * @param size Number of elements in the stack. * @param calculator Calculator object associated with the stack. * @param recommendedChunkSizeMultiple Suggested quantization of elements per work chunk. * @param recommendedChunksPerRank Suggested number of work chunks per MPI rank. * @param autoBroadcast Enable or disable auto broadcast. * @return StackIdentifier Id of the newly generated stack as registered with the LoadManager. * * @see DataStackBase::StackType::Explicit * @see DataStack */ template <class StackT> StackIdentifier addMasterStackExplicit(StackT *const data, const int size, const std::function<StackT(int)> &calculator, const int recommendedChunkSizeMultiple = 1, const int recommendedChunksPerRank = 10, const bool autoBroadcast = false) { DataStack<StackT> *ds = new DataStack<StackT>(); ds->type = DataStackBase::StackType::Explicit; ds->master = -1; ds->size = size; ds->typeMultiplicity = 1; ds->recommendedChunkSizeMultiple = recommendedChunkSizeMultiple; ds->recommendedChunksPerRank = recommendedChunksPerRank; ds->autoBroadcast = autoBroadcast; ds->explicitCalculator = calculator; ds->data = data; return _registerStack(ds); } /** * @brief Create an implicit data stack and attach it to the LoadManager. * * @tparam StackT The fundamental data type of the DataStack to be created. * @param data Data array on which the stack operates. The allocated size should be at least size * typeMultiplicity * typeof(StackT). * @param size Number of elements (or element tuples) in the stack. * @param calculator Calculator object associated with the stack. * @param typeMultiplicity Element tuple size. * @param recommendedChunkSizeMultiple Suggested quantization of elements per work chunk. * @param recommendedChunksPerRank Suggested number of work chunks per MPI rank. * @param autoBroadcast Enable or disable auto broadcast. * @return StackIdentifier Id of the newly generated stack as registered with the LoadManager. * * @see DataStackBase::StackType::Implicit * @see DataStack */ template <class StackT> StackIdentifier addMasterStackImplicit(StackT *const data, const int size, const std::function<void(int)> &calculator, const int typeMultiplicity = 1, const int recommendedChunkSizeMultiple = 1, const int recommendedChunksPerRank = 10, const bool autoBroadcast = false) { DataStack<StackT> *ds = new DataStack<StackT>(); ds->type = DataStackBase::StackType::Implicit; ds->master = -1; ds->size = size; ds->typeMultiplicity = typeMultiplicity; ds->recommendedChunkSizeMultiple = recommendedChunkSizeMultiple; ds->recommendedChunksPerRank = recommendedChunksPerRank; ds->autoBroadcast = autoBroadcast; ds->implicitCalculator = calculator; ds->data = data; return _registerStack(ds); } /** * @brief Create a slave data stack and attach it to the LoadManager. * * @tparam StackT The fundamental data type of the DataStack to be created. * @param data Data array on which the stack operates. The allocated size should be at least size * typeMultiplicity * typeof(StackT). * @param size Number of elements (or element tuples) in the stack. * @param master Stack id of the associated implicit master stack. * @param typeMultiplicity Element tuple size. * @return StackIdentifier Id of the newly generated stack as registered with the LoadManager. * * @see DataStackBase::StackType::Slave * @see DataStack */ template <class StackT> StackIdentifier addSlaveStack(StackT *const data, const int size, const StackIdentifier master, const int typeMultiplicity = 1) { DataStack<StackT> *ds = new DataStack<StackT>(); ds->type = DataStackBase::StackType::Slave; ds->master = master; ds->size = size; ds->typeMultiplicity = typeMultiplicity; ds->autoBroadcast = false; ds->data = data; return _registerStack(ds); } /** * @brief Create a passive data stack and attach it to the LoadManager. * * @tparam StackT The fundamental data type of the DataStack to be created. * @param data Data array on which the stack operates. The allocated size should be at least size * typeMultiplicity * typeof(StackT). * @param size Number of elements (or element tuples) in the stack. * @return StackIdentifier Id of the newly generated stack as registered with the LoadManager. * * @see DataStackBase::StackType::Passive * @see DataStack */ template <class StackT> StackIdentifier addPassiveStack(StackT *const data, const int size) { DataStack<StackT> *ds = new DataStack<StackT>(); ds->type = DataStackBase::StackType::Passive; ds->master = -1; ds->size = size; ds->typeMultiplicity = 1; ds->autoBroadcast = false; ds->data = data; return _registerStack(ds); } /** * @brief Calculate a list of stacks, where the stack identifiers are provided in list form. * * @param stackIds Pointer to the first StackIdentifier. * @param size Number of stacks. */ virtual void calculate(const StackIdentifier *stackIds, const int size) = 0; /** * @brief Calculate a list of stacks, where the stack identifiers are provided in initializer list form. * * @param stackIds Initializer list of StackIdentifiers. */ void calculate(const std::initializer_list<StackIdentifier> &stackIds) { calculate(stackIds.begin(), int(stackIds.size())); } /** * @brief Calculate a single stack. * * @param stackId StackIdentifier of the stack to be calculated. */ void calculate(const StackIdentifier stackId) { calculate({ stackId }); } /** * @brief Calculate all stacks. */ void calculateAll() { std::vector<StackIdentifier> all(_stacks.size()); for (StackIdentifier i = 0; i < StackIdentifier(_stacks.size()); ++i) all[i] = i; calculate(all.data(), int(all.size())); } /** * @brief Broadcast a list of stacks, where the stack identifiers are provided in list form. * * @param stackIds Pointer to the first StackIdentifier. * @param size Number of stacks. */ void broadcast(const StackIdentifier *stackIds, const int size) { #ifdef HMP_MPI_ENABLED for (int i = 0; i < size; ++i) { for (StackIdentifier s = 0; s < StackIdentifier(_stacks.size()); ++s) { if (s == stackIds[i] || _stacks[s]->master == stackIds[i]) _stacks[s]->broadcast(_serverRank, _communicator); } } #endif } /** * @brief Broadcast a list of stacks, where the stack identifiers are provided in initializer list form. * * @param stackIds Initializer list of StackIdentifiers. */ void broadcast(const std::initializer_list<StackIdentifier> &stackIds) { broadcast(stackIds.begin(), int(stackIds.size())); } /** * @brief Broadcast a single stack. * * @param stackId StackIdentifier of the stack to be broadcasted. */ void broadcast(const StackIdentifier stackId) { broadcast({ stackId }); } /** * @brief Broadcast all stacks. */ void broadcastAll() { std::vector<StackIdentifier> all(_stacks.size()); for (StackIdentifier i = 0; i < StackIdentifier(_stacks.size()); ++i) all[i] = i; broadcast(all.data(), int(all.size())); } /** * @brief Virtual implementation to print runtime statistics, including information on the efficiency of LoadManager instances running on different MPI ranks. */ virtual void printRuntimeStatistics() const {} protected: /** * @brief Construct a new Load Manager object * * @param serverRank The MPI rank to take on the master role. * @param communicator The MPI communicator to operate on. */ LoadManager(const int serverRank HMP_APPEND_IF_MPI(const MPI_Comm communicator)) { HMP_ENABLE_IF_MPI(MPI_Comm_dup(communicator, &_communicator)); HMP_ENABLE_IF_MPI(MPI_Comm_size(_communicator, &_commSize)); HMP_DISABLE_IF_MPI(_commSize = 1); HMP_ENABLE_IF_MPI(MPI_Comm_rank(_communicator, &_rank)); HMP_DISABLE_IF_MPI(_rank = 0); if (serverRank >= _commSize) throw Exception(Exception::Type::MpiError, "Server rank must not exceed communicator size."); else _serverRank = serverRank; } /** * @brief Register a DataStackBase with the LoadManager. By registering the stack, the LoadManager assumes responsibility to synchronize data between MPI ranks as necessary. * * @param stack The stack to be registered. * @return StackIdentifier Unique identifier of the newly registered stack; Used e.g. for LoadManager::calculate calls. */ virtual StackIdentifier _registerStack(DataStackBase *stack) { //If stack is a slave stack, check that the type multiplicity matches the type multiplicity of the master if (stack->type == DataStackBase::StackType::Slave && stack->typeMultiplicity != _stacks[stack->master]->typeMultiplicity) throw Exception(Exception::Type::ArgumentError, "Stack type multiplicity of slave stack does not match type multiplicity of associated master stack."); _stacks.push_back(stack); return StackIdentifier(_stacks.size() - 1); } /** * @brief Calculate the workload defined by a specific chunk. * * @param chunk Provides the workload definition. */ void _calculateChunk(const Chunk &chunk) { #ifndef DISABLE_OMP #pragma omp parallel for schedule(guided) #endif for (int i = chunk.properties[HMP_CHUNK_PROPERTY_BEGIN]; i < chunk.properties[HMP_CHUNK_PROPERTY_END]; ++i) _stacks[chunk.properties[HMP_CHUNK_PROPERTY_STACK]]->applyCalculator(i); } std::vector<DataStackBase *> _stacks; ///< List of all registered stacks. int _serverRank; ///< Designated MPI master rank. int _rank; ///< MPI rank of the current LoadManager instance. int _commSize; ///< MPI communicator size. HMP_ENABLE_IF_MPI(MPI_Comm _communicator); ///< MPI communicator to operate on. }; /** * @brief LoadManager master implementation, which is responsible for distributing work and synchronizing data. * * @see LoadManager */ class LoadManagerMaster : public LoadManager { friend LoadManager *newLoadManager(const int serverRank HMP_APPEND_IF_MPI(const MPI_Comm communicator)); public: /** * @brief Calculate a list of stacks, where the stack identifiers are provided in list form. * * @param stackIds Pointer to the first StackIdentifier. * @param size Number of stacks. */ virtual void calculate(const StackIdentifier *stackIds, const int size) override { //reset calculation runtime statistics for (int i = 0; i < _commSize; ++i) { for (StackIdentifier s = 0; s < StackIdentifier(_stacks.size()); ++s) { _currentCalculationComputeTimeBuffer[i * _stacks.size() + s] = 0.0f; _currentCalculationWorkDone[i][s] = 0; _currentCalculationTime[i][s] = 0.0f; } } boost::posix_time::ptime tic = boost::posix_time::microsec_clock::local_time(); //init chunk spawner _initChunkSpawner(stackIds, size); //spawn local worker std::thread *t = new std::thread([&]() { this->_runLocalClient(); }); #ifdef HMP_MPI_ENABLED //issue initial chunks for (int i = 0; i < _commSize; ++i) if (i != _serverRank) _issueChunk(i); //collect results and issue consecutive chunks int receiveFlag; MPI_Status receiveStatus; for (;;) { begin: for (int rank = 0; rank < _commSize; ++rank) { if (rank == _serverRank || _pendingRequests[rank] == MPI_REQUEST_NULL) continue; MPI_Test(_pendingRequests + rank, &receiveFlag, &receiveStatus); if (receiveFlag == 1) { _despawnChunk(rank); _issueChunk(receiveStatus.MPI_SOURCE); } } for (int rank = 0; rank < _commSize; ++rank) if (_pendingRequests[rank] != MPI_REQUEST_NULL) goto begin; break; } #endif //join local worker t->join(); //broadcast result for (int s = 0; s < size; ++s) { if (_stacks[stackIds[s]]->autoBroadcast) broadcast(stackIds[s]); } //gather runtime statistics HMP_ENABLE_IF_MPI(MPI_Gather(MPI_IN_PLACE, int(_stacks.size()), MPI_FLOAT, _currentCalculationComputeTimeBuffer.data(), int(_stacks.size()), MPI_FLOAT, _serverRank, _communicator)); for (int i = 0; i < _commSize; ++i) { for (StackIdentifier s = 0; s < StackIdentifier(_stacks.size()); ++s) { _totalComputeTime[i][s] += _currentCalculationComputeTimeBuffer[i * _stacks.size() + s]; } } boost::posix_time::ptime toc = boost::posix_time::microsec_clock::local_time(); _totalCalculationTime += float((toc - tic).total_milliseconds()); } /** * @brief Print runtime statistics, including information on the efficiency of LoadManager instances running on different MPI ranks. */ void printRuntimeStatistics() const override { Log::log << Log::LogLevel::Debug << "LoadManager total time spent in calculate() calls is " << _totalCalculationTime << "ms" << Log::endl; for (int i = 0; i < _commSize; ++i) { float timePerRank = 0.0; for (StackIdentifier j = 0; j < StackIdentifier(_stacks.size()); ++j) timePerRank += _totalComputeTime[i][j]; Log::log << Log::LogLevel::Debug << "LoadManager (rank " << i << ") active computing time was " << std::setiosflags(std::ios::fixed) << std::setprecision(0) << timePerRank << "ms (Efficiency: " << std::setprecision(1) << 100.0f * timePerRank / _totalCalculationTime << "%)" << Log::endl; for (StackIdentifier j = 0; j < StackIdentifier(_stacks.size()); ++j) Log::log << Log::LogLevel::Debug << "\t active computing time on stack " << j << " was " << _totalComputeTime[i][j] << "ms" << Log::endl; } } protected: /** * @brief Construct a new LoadManagerMaster object * * @param serverRank The MPI rank to take on the master role. * @param communicator The MPI communicator used for communication. */ LoadManagerMaster(const int serverRank HMP_APPEND_IF_MPI(const MPI_Comm communicator)) : LoadManager(serverRank HMP_APPEND_IF_MPI(communicator)) { _totalCalculationTime = 0.0f; _totalComputeTime = new std::vector<float>[_commSize]; _currentCalculationWorkDone = new std::vector<int>[_commSize]; _currentCalculationTime = new std::vector<float>[_commSize]; _currentCalculationChunkSpawntime = new boost::posix_time::ptime[_commSize]; _currentCalculationChunkSpawned = new Chunk[_commSize]; #ifdef HMP_MPI_ENABLED _pendingRequests = new MPI_Request[_commSize]; for (int i = 0; i < _commSize; ++i) _pendingRequests[i] = MPI_REQUEST_NULL; #endif } /** * @brief Destroy the LoadManagerMaster object */ ~LoadManagerMaster() { delete[] _totalComputeTime; delete[] _currentCalculationWorkDone; delete[] _currentCalculationTime; delete[] _currentCalculationChunkSpawntime; delete[] _currentCalculationChunkSpawned; HMP_ENABLE_IF_MPI(delete[] _pendingRequests); } /** * @brief Register a DataStackBase with the LoadManager. By registering the stack, the LoadManager assumes responsibility to synchronize data between MPI ranks as necessary. * * @param stack The stack to be registered. * @return StackIdentifier Unique identifier of the newly registered stack; Used e.g. for LoadManager::calculate calls. */ virtual StackIdentifier _registerStack(DataStackBase *stack) override { StackIdentifier identifier = LoadManager::_registerStack(stack); for (int i = 0; i < _commSize; ++i) { _totalComputeTime[i].push_back(0.0f); _currentCalculationWorkDone[i].push_back(0); _currentCalculationTime[i].push_back(0.0f); } _currentCalculationComputeTimeBuffer.resize(_commSize * _stacks.size()); _currentCalculationStackMask.resize(_stacks.size()); _currentCalculationStackProgress.resize(_stacks.size()); return identifier; } /** * @brief Worker loop to run calculators locally. */ void _runLocalClient() { for (;;) { //get chunk Chunk c = _spawnChunk(_serverRank); if (c.isVoid()) break; boost::posix_time::ptime tic = boost::posix_time::microsec_clock::local_time(); _calculateChunk(c); boost::posix_time::ptime toc = boost::posix_time::microsec_clock::local_time(); _currentCalculationComputeTimeBuffer[c.properties[HMP_CHUNK_PROPERTY_STACK]] += (toc - tic).total_milliseconds(); _despawnChunk(_serverRank); } } /** * @brief Prepare the chunk spawner, i.e. the routine responsible for breaking down workload into smaller chunsk, for the execution of calculators on the specified list of stacks. * * @param stackIds Pointer to the first StackIdentifier to be calculated. * @param size Number of StackIdentifiers to be calculated. */ void _initChunkSpawner(const StackIdentifier *stackIds, const int size) { //reset calculation statistics for (int i = 0; i < _commSize; ++i) { for (StackIdentifier s = 0; s < StackIdentifier(_stacks.size()); ++s) { _currentCalculationWorkDone[i][s] = 0; _currentCalculationTime[i][s] = 0.0f; } } for (StackIdentifier s = 0; s < StackIdentifier(_stacks.size()); ++s) { _currentCalculationStackMask[s] = false; _currentCalculationStackProgress[s] = 0; } //enable selected stacks for (int i = 0; i < size; ++i) _currentCalculationStackMask[stackIds[i]] = true; } /** * @brief Prepare the chunk spawner, i.e. the routine responsible for breaking down workload into smaller chunsk, for the execution of calculators on the specified initializer list of stacks. * * @param stackIds Initializer list of the stacks to be calculated. */ void _initChunkSpawner(const std::initializer_list<StackIdentifier> &stackIds) { _initChunkSpawner(stackIds.begin(), int(stackIds.size())); } /** * @brief The chunk spawner routine, which is responsible for breaking down the overall workload of calculator executions into smaller chunks of workload. * The algorithm to spawn a chunk and determine its workload is as follows: * 1. Choose a stack that has not finished computing. * 2. Determine the maximum chunk size according to the stack's recommended number of chunks per rank. * 3. Round up that number to be a multiple of the recommended chunk size. * 4. Determine chunk size according to relative computing power of the different ranks, based on performance on previous chunks. * 5. Clip chunk size to minimum of 100ms expected return time and maximum as determined before. * * @param rank MPI rank for which the workload chunk is being requested. * @return Chunk Definition of the workload. */ Chunk _spawnChunk(const int rank) { std::lock_guard<std::mutex> lock(_currentCalculationChunkSpawnerLock); Chunk c; for (StackIdentifier s = 0; s < StackIdentifier(_stacks.size()); ++s) { //skip inactive and completed stacks if (!_currentCalculationStackMask[s] || _currentCalculationStackProgress[s] >= _stacks[s]->size) continue; //determine max chunk size int maximumWorkShare = int(_stacks[s]->size / (_stacks[s]->recommendedChunksPerRank * _commSize)); maximumWorkShare = (int(maximumWorkShare / _stacks[s]->recommendedChunkSizeMultiple) + 1) * _stacks[s]->recommendedChunkSizeMultiple; if (maximumWorkShare < 1) maximumWorkShare = 1; //determine dynamic chunk size according to compute power float myComputePower = _currentCalculationWorkDone[rank][s] / _currentCalculationTime[rank][s]; float totalComputePower = 0; for (int i = 0; i < _commSize; ++i) for (StackIdentifier j = 0; j < StackIdentifier(_stacks.size()); ++j) totalComputePower += _currentCalculationWorkDone[i][j] / _currentCalculationTime[i][j]; int newCurrentCalculationProgress; if (std::isfinite(myComputePower) && std::isfinite(totalComputePower)) { //factor in amount of remaining work int remainingWork = int(_stacks[s]->size - _currentCalculationStackProgress[s]); int myWorkShare = int((myComputePower / totalComputePower) * remainingWork); myWorkShare = (int(myWorkShare / _stacks[s]->recommendedChunkSizeMultiple) + 1) * _stacks[s]->recommendedChunkSizeMultiple; //clip to min/max chunk size int minumumWorkTime = 100; int minimumWorkShare = int(myComputePower * minumumWorkTime); if (minimumWorkShare < 1) minimumWorkShare = 1; if (myWorkShare < minimumWorkShare) myWorkShare = minimumWorkShare; if (myWorkShare > maximumWorkShare) myWorkShare = maximumWorkShare; newCurrentCalculationProgress = _currentCalculationStackProgress[s] + myWorkShare; } else newCurrentCalculationProgress = _currentCalculationStackProgress[s] + maximumWorkShare; //clip chunk to stack size if (newCurrentCalculationProgress >= _stacks[s]->size) newCurrentCalculationProgress = _stacks[s]->size; //write chunk parameters _currentCalculationWorkDone[rank][s] += newCurrentCalculationProgress - _currentCalculationStackProgress[s]; c.properties[HMP_CHUNK_PROPERTY_STACK] = s; c.properties[HMP_CHUNK_PROPERTY_BEGIN] = decltype(c.properties[HMP_CHUNK_PROPERTY_BEGIN])(_currentCalculationStackProgress[s]); c.properties[HMP_CHUNK_PROPERTY_END] = decltype(c.properties[HMP_CHUNK_PROPERTY_END])(newCurrentCalculationProgress); Log::log << Log::LogLevel::Debug << "LoadManager spawned chunk (stack " << s << ", from " << _currentCalculationStackProgress[s] << ", to " << newCurrentCalculationProgress << ", rank " << rank << ")" << Log::endl; //return chunk _currentCalculationStackProgress[s] = newCurrentCalculationProgress; break; } _currentCalculationChunkSpawntime[rank] = boost::posix_time::microsec_clock::local_time(); _currentCalculationChunkSpawned[rank] = c; return c; } /** * @brief Send a workload chunk to a specified MPI rank. * * @param rank Receiver's MPI rank. */ void _issueChunk(const int rank) { #ifdef HMP_MPI_ENABLED Chunk c = _spawnChunk(rank); MPI_Send(&c.properties, 3, MPI_INT, rank, static_cast<int>(DataStackBase::MessageTag::Chunk), _communicator); if (!c.isVoid()) { for (StackIdentifier i = 0; i < StackIdentifier(_stacks.size()); ++i) { //we may expect to receive data from additional slave stacks; due to MPI's non-overtaking policy, it is sufficient to only store the most recent request per rank if (i == c.properties[HMP_CHUNK_PROPERTY_STACK] || _stacks[i]->master == c.properties[HMP_CHUNK_PROPERTY_STACK]) _stacks[i]->receive(c.properties[HMP_CHUNK_PROPERTY_BEGIN], c.properties[HMP_CHUNK_PROPERTY_END] - c.properties[HMP_CHUNK_PROPERTY_BEGIN], rank, _communicator, _pendingRequests[rank]); } } else _pendingRequests[rank] = MPI_REQUEST_NULL; #endif } /** * @brief Mark a workload chunk as completed. Relevant only for runtime statistics information. * * @param rank MPI rank which had completed the workload. */ void _despawnChunk(const int rank) { float chunktime = float((boost::posix_time::microsec_clock::local_time() - _currentCalculationChunkSpawntime[rank]).total_milliseconds()); std::lock_guard<std::mutex> lock(_currentCalculationChunkSpawnerLock); _currentCalculationTime[rank][_currentCalculationChunkSpawned[rank].properties[HMP_CHUNK_PROPERTY_STACK]] += chunktime; } float _totalCalculationTime; ///< Accumulated time in milliseconds which has been spent on calculate() calls over the lifetime of the LoadManager instance. std::vector<float> *_totalComputeTime; ///< _totalComputeTime[rank][stack] is the accumulated time in milliseconds which MPI rank `rank` spent computing on `stack`. std::vector<int> *_currentCalculationWorkDone; ///< _currentCalculationWorkDone[rank][stack] is the number of calculations which have been performed by MPI rank `rank` on `stack` in the current calculate() call. std::vector<float> *_currentCalculationTime; ///< _currentCalculationTime[rank][stack] is the time in milliseconds spent by MPI rank `rank` until returning chunk result for `stack` in the current calculate() call. boost::posix_time::ptime *_currentCalculationChunkSpawntime; ///< _currentCalculationChunkSpawntime[rank] specifies time at which the most recent chunk has been issued to MPI rank `rank` in the current calculate() call. Chunk *_currentCalculationChunkSpawned; ///< _currentCalculationChunkSpawned[rank] stores the most recent chunk generated for MPI rank `rank` in the current calculate() call. std::vector<float> _currentCalculationComputeTimeBuffer; ///< _currentCalculationComputeTimeBuffer[rank*_stacks.size()+stack] is a buffer for the time in milliseconds spent on computing `stack` in the current calculate() call. std::vector<bool> _currentCalculationStackMask; ///< _currentCalculationStackMask[stack] specifies whether `stack` should be computed in the current calculate() call. std::vector<int> _currentCalculationStackProgress; ///< _currentCalculationStackProgress[stack] specifies the current progress (pointer to the next unissued value) which has already been issued for computation in the current calculate() call. std::mutex _currentCalculationChunkSpawnerLock; ///< Lock to synchronize chunk spawning for remote calculations and for local worker threads. HMP_ENABLE_IF_MPI(MPI_Request *_pendingRequests); ///< MPI request objects associated with the return values for workload chunks that have been issued. }; /** * @brief LoadManager slave implementation, responsible for receiving and executing workload chunks form a LoadManagerMaster implementation. * * @see LoadManager */ class LoadManagerSlave : public LoadManager { friend LoadManager *newLoadManager(const int serverRank HMP_APPEND_IF_MPI(const MPI_Comm communicator)); public: /** * @brief Calculate a list of stacks, where the stack identifiers are provided in list form. * * @param stackIds Pointer to the first StackIdentifier. * @param size Number of stacks. */ virtual void calculate(const StackIdentifier *stackIds, const int size) override { #ifdef HMP_MPI_ENABLED memset(_currentCalculationComputeTimeBuffer.data(), 0, _currentCalculationComputeTimeBuffer.size() * sizeof(float)); Chunk c; for (;;) { //receive chunk _waitChunk(c); if (c.isVoid()) break; //compute chunk boost::posix_time::ptime tic = boost::posix_time::microsec_clock::local_time(); _calculateChunk(c); boost::posix_time::ptime toc = boost::posix_time::microsec_clock::local_time(); _currentCalculationComputeTimeBuffer[c.properties[HMP_CHUNK_PROPERTY_STACK]] += (toc - tic).total_milliseconds(); //return chunk _returnChunk(c); } //broadcast result for (int s = 0; s < size; ++s) { if (_stacks[stackIds[s]]->autoBroadcast) broadcast(stackIds[s]); } //gather compute time statistics MPI_Gather(_currentCalculationComputeTimeBuffer.data(), int(_currentCalculationComputeTimeBuffer.size()), MPI_FLOAT, nullptr, int(_currentCalculationComputeTimeBuffer.size()), MPI_FLOAT, _serverRank, _communicator); #endif } protected: /** * @brief Construct a new LoadManagerSlave object * * @param serverRank The MPI rank to take on the master role. * @param communicator The MPI communicator used for communication. */ LoadManagerSlave(const int serverRank HMP_APPEND_IF_MPI(const MPI_Comm communicator)) : LoadManager(serverRank HMP_APPEND_IF_MPI(communicator)) {} /** * @brief Register a DataStackBase with the LoadManager. By registering the stack, the LoadManager assumes responsibility to synchronize data between MPI ranks as necessary. * * @param stack The stack to be registered. * @return StackIdentifier Unique identifier of the newly registered stack; Used e.g. for LoadManager::calculate calls. */ virtual StackIdentifier _registerStack(DataStackBase *stack) override { StackIdentifier identifier = LoadManager::_registerStack(stack); _currentCalculationComputeTimeBuffer.resize(_stacks.size()); return identifier; } /** * @brief Wait until a workload chunk has been received from a LoadManagerMaster instance. * * @param[out] chunk The workload definition which has been received. */ void _waitChunk(Chunk &chunk) const { #ifdef HMP_MPI_ENABLED MPI_Status status; MPI_Recv(&chunk.properties, 3, MPI_INT, _serverRank, static_cast<int>(DataStackBase::MessageTag::Chunk), _communicator, &status); #endif } /** * @brief Return the result of the workload defined by a specific chunk. * * @param chunk The workload definition whose results are to be returned. */ void _returnChunk(const Chunk &chunk) const { #ifdef HMP_MPI_ENABLED for (int i = 0; i < int(_stacks.size()); ++i) { if (i == chunk.properties[HMP_CHUNK_PROPERTY_STACK] || _stacks[i]->master == chunk.properties[HMP_CHUNK_PROPERTY_STACK]) _stacks[i]->send(chunk.properties[HMP_CHUNK_PROPERTY_BEGIN], chunk.properties[HMP_CHUNK_PROPERTY_END] - chunk.properties[HMP_CHUNK_PROPERTY_BEGIN], _serverRank, _communicator); } #endif } std::vector<float> _currentCalculationComputeTimeBuffer; ///< _currentCalculationComputeTimeBuffer[stack] is a buffer for the time in milliseconds spent on computing `stack` in the current calculate() call. }; /** * @brief Create a new LoadManager instance. * If the current MPI rank is the designated master rank, returns a LoadManagerMaster instance, otherwise returns a LoadManagerSlave instance. * * @param serverRank MPI rank to assume the master role. * @param communicator The MPI communicator to operate on. * @return LoadManager* Newly generated LoadManager instance. */ inline LoadManager *newLoadManager(const int serverRank = 0 HMP_APPEND_IF_MPI(const MPI_Comm communicator = MPI_COMM_WORLD)) { int myRank; HMP_ENABLE_IF_MPI(MPI_Comm_rank(communicator, &myRank)); HMP_DISABLE_IF_MPI(myRank = 0); if (myRank == serverRank) return new LoadManagerMaster(serverRank HMP_APPEND_IF_MPI(communicator)); else return new LoadManagerSlave(serverRank HMP_APPEND_IF_MPI(communicator)); }; } //namespace HMP #undef HMP_CHUNK_PROPERTY_STACK #undef HMP_CHUNK_PROPERTY_BEGIN #undef HMP_CHUNK_PROPERTY_END #undef HMP_MPI_ENABLED #undef HMP_ENABLE_IF_MPI #undef HMP_DISABLE_IF_MPI #undef HMP_APPEND_IF_MPI
44.084221
302
0.724017
[ "object", "vector" ]
53c61a58457010089a0b0b4fedf1e6336e2b2437
6,814
cpp
C++
Chapter12/12.VulkanProject/VulkanProject/Tools.cpp
sonvt1710/CPP-Game-Development-By-Example
0f237e8827680ca5d426e225ba23619c8b586eeb
[ "MIT" ]
75
2019-06-21T07:04:49.000Z
2022-03-22T17:55:28.000Z
Chapter12/12.VulkanProject/VulkanProject/Tools.cpp
sonvt1710/CPP-Game-Development-By-Example
0f237e8827680ca5d426e225ba23619c8b586eeb
[ "MIT" ]
1
2020-09-06T10:51:55.000Z
2020-09-11T12:29:18.000Z
Chapter12/12.VulkanProject/VulkanProject/Tools.cpp
sonvt1710/CPP-Game-Development-By-Example
0f237e8827680ca5d426e225ba23619c8b586eeb
[ "MIT" ]
41
2019-06-18T10:37:38.000Z
2022-03-28T15:22:34.000Z
#include "Tools.h" #include "VulkanContext.h" namespace vkTools { VkImageView createImageView(VkImage image, VkFormat format, VkImageAspectFlags aspectFlags) { VkImageViewCreateInfo viewInfo = {}; viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; viewInfo.image = image; viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; viewInfo.format = format; //// subrange what is the purpose of the image and //// what part of the image should be accessed viewInfo.subresourceRange.aspectMask = aspectFlags; viewInfo.subresourceRange.baseMipLevel = 0; viewInfo.subresourceRange.levelCount = 1; //// multiple layers is for stereoscopic 3D applications viewInfo.subresourceRange.baseArrayLayer = 0; viewInfo.subresourceRange.layerCount = 1; VkImageView imageView; if (vkCreateImageView(VulkanContext::getInstance()->getDevice()->logicalDevice, &viewInfo, nullptr, &imageView) != VK_SUCCESS) { throw std::runtime_error("failed to create texture image view !"); } return imageView; } uint32_t findMemoryTypeIndex(uint32_t typeFilter, VkMemoryPropertyFlags properties) { //-- Properties has two arrays -- memory types and memory heaps //-- Heaps - are distinct memory resources like dedcated VRAM and Swap Space RAM for when VRAM runs out //-- Different memory exist in these heaps VkPhysicalDeviceMemoryProperties memProperties; vkGetPhysicalDeviceMemoryProperties(VulkanContext::getInstance()->getDevice()->physicalDevice, &memProperties); //-- We are just concerned with the type //-- Passed in with typefilter for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) { // As we also want to write to the memory if ((typeFilter & (1 << i)) && // if this memory type is suitable to certex buffer (memProperties.memoryTypes[i].propertyFlags & // memory types also specify heap and property properties) // The properties define special features of the memory, like being able to map it so we can write to it from the CPU == properties) { return i; } } throw std::runtime_error("failed to find suitable memory type!"); } // -- Create Buffer void createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer &buffer, // output VkDeviceMemory& bufferMemory) { // output VkBufferCreateInfo bufferInfo = {}; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.size = size; bufferInfo.usage = usage;// can specify multiple purposes with bitwise operation // like the swap chain the buffer can be shared between different queues like ghraphics and compute // Here it is exclusive to graphics bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; if (vkCreateBuffer(VulkanContext::getInstance()->getDevice()->logicalDevice, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) { throw std::runtime_error(" failed to create vertex buffer "); } //-- Get Memory requirements for the vertexBuffer VkMemoryRequirements memrequirements; vkGetBufferMemoryRequirements(VulkanContext::getInstance()->getDevice()->logicalDevice, buffer, &memrequirements); //-- Memory Allocation VkMemoryAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memrequirements.size; allocInfo.memoryTypeIndex = findMemoryTypeIndex(memrequirements.memoryTypeBits, properties); //VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | // can we map memory so that we can write it from CPU //VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); // Memory is a coherent bit if (vkAllocateMemory(VulkanContext::getInstance()->getDevice()->logicalDevice, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS) { throw std::runtime_error("failed to allocate vertex buffer memory"); } //-- memory allocation was successful so now we can bind the buffer to the memory vkBindBufferMemory(VulkanContext::getInstance()->getDevice()->logicalDevice, buffer, bufferMemory, 0); } // -- Copy Buffer // Helpers for creating and beging command buffer VkCommandBuffer beginSingleTimeCommands(VkCommandPool commandPool) { //-- Alloc Command buffer VkCommandBufferAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandPool = commandPool; allocInfo.commandBufferCount = 1; VkCommandBuffer commandBuffer; vkAllocateCommandBuffers(VulkanContext::getInstance()->getDevice()->logicalDevice, &allocInfo, &commandBuffer); //-- Record command buffer VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; //start recording vkBeginCommandBuffer(commandBuffer, &beginInfo); return commandBuffer; } void endSingleTimeCommands(VkCommandBuffer commandBuffer, VkCommandPool commandPool) { //-- End recording vkEndCommandBuffer(commandBuffer); //-- Execute the Command Buffer to complete the transfer VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; vkQueueSubmit(VulkanContext::getInstance()->getDevice()->graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE); vkQueueWaitIdle(VulkanContext::getInstance()->getDevice()->graphicsQueue); vkFreeCommandBuffers(VulkanContext::getInstance()->getDevice()->logicalDevice, commandPool, 1, &commandBuffer); } void copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size) { // Create Command Pool VkCommandPool commandPool; QueueFamilyIndices qFamilyIndices = VulkanContext::getInstance()->getDevice()->getQueueFamiliesIndicesOfCurrentDevice(); VkCommandPoolCreateInfo cpInfo = {}; cpInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; cpInfo.queueFamilyIndex = qFamilyIndices.graphicsFamily; cpInfo.flags = 0; if (vkCreateCommandPool(VulkanContext::getInstance()->getDevice()->logicalDevice, &cpInfo, nullptr, &commandPool) != VK_SUCCESS) { throw std::runtime_error(" failed to create command pool !!"); } //-- Memory transfer is done through command buffers // Allocate command buffer and start recording VkCommandBuffer commandBuffer = beginSingleTimeCommands(commandPool); //-- Copy the buffer VkBufferCopy copyregion = {}; copyregion.srcOffset = 0; copyregion.dstOffset = 0; copyregion.size = size; vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &copyregion); // End recording and Execute command buffer and free command buffer endSingleTimeCommands(commandBuffer, commandPool); vkDestroyCommandPool(VulkanContext::getInstance()->getDevice()->logicalDevice, commandPool, nullptr); } }
34.241206
134
0.764309
[ "3d" ]
53d2ec6bd1fbd131f58512298674328e29eb7e82
1,328
cpp
C++
bcc/abc.cpp
thekaigonzalez/SymbolSearch
54ed7ba70aaf295c42435b734e63fc48fef862a5
[ "MIT" ]
1
2021-07-25T16:55:13.000Z
2021-07-25T16:55:13.000Z
bcc/abc.cpp
thekaigonzalez/SymbolSearch
54ed7ba70aaf295c42435b734e63fc48fef862a5
[ "MIT" ]
null
null
null
bcc/abc.cpp
thekaigonzalez/SymbolSearch
54ed7ba70aaf295c42435b734e63fc48fef862a5
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <fstream> void Run_Point(const char *, const char *); /* implemented */ int main(int argc, char** argv) { try { std::string Fname_BASE = argv[1]; std::string Fname_NEW = argv[2]; if (Fname_BASE == "-f") { std::cout << "Opening file " << Fname_NEW << std::endl; if (std::ifstream(Fname_NEW)) { std::cout << "Interactive Terminal" << std::endl; std::cout << "In file " << Fname_NEW << std::endl; std::cout << "You can type an entry point to run it.\nOr type .abort to exit.\nIf you run a entry that doesn't exist, it will throw a segmentation fault. Be careful!" << std::endl; while (true) { std::cout << ">> "; std::string epoint; getline(std::cin, epoint); Run_Point(Fname_NEW.c_str(), epoint.c_str()); } } } else if (Fname_BASE == "-vF") { } } //not the best way... but works! catch (const std::exception&) { std::cout << "1 or more arguments are invalid" << std::endl; std::cout << "\nUsage: bcc -f filename" << std::endl; } }
31.619048
196
0.486446
[ "vector" ]
53d39ff48c9985300a687ed6f95682b0042ca486
15,913
cpp
C++
low-can-binding/utils/openxc-utils.cpp
redpesk-common/canbus-binding
031ebb8657e66129936ba9079faa58e369f97de1
[ "Apache-2.0" ]
null
null
null
low-can-binding/utils/openxc-utils.cpp
redpesk-common/canbus-binding
031ebb8657e66129936ba9079faa58e369f97de1
[ "Apache-2.0" ]
null
null
null
low-can-binding/utils/openxc-utils.cpp
redpesk-common/canbus-binding
031ebb8657e66129936ba9079faa58e369f97de1
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2015, 2016 "IoT.bzh" * Author "Romain Forlot" <romain.forlot@iot.bzh> * Author "Loic Collignon" <loic.collignon@iot.bzh> * * 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 <low-can/binding/application.hpp> #include <low-can/can/can-decoder.hpp> #include <low-can/utils/openxc-utils.hpp> #include "converter.hpp" /// /// @brief Build a specific VehicleMessage containing a DiagnosticResponse. /// /// @param[in] request - Original request use to retrieve decoder and callback /// @param[in] response - Response to the request that will be decoded if decoder set /// and put into the DiagnosticResponse of the VehicleMessage. /// @param[in] parsed_value - raw parsed value of the payload from CAN message /// /// @return a vehicle message including simple message that will be convert into /// a JSON object before being pushed to the subscribers /// const openxc_VehicleMessage build_VehicleMessage(active_diagnostic_request_t* request, const DiagnosticResponse& response, float parsed_value) { openxc_VehicleMessage message; ::memset(&message, 0, sizeof(message)); application_t& app = application_t::instance(); message.has_type = true; message.type = openxc_VehicleMessage_Type::openxc_VehicleMessage_Type_DIAGNOSTIC; message.has_diagnostic_response = true; message.diagnostic_response.has_bus = true; message.diagnostic_response.bus = app.get_can_bus_manager().get_can_device_index( app.get_diagnostic_manager().get_bus_name()); message.diagnostic_response.has_message_id = true; if(request->get_id() != OBD2_FUNCTIONAL_BROADCAST_ID) { message.diagnostic_response.message_id = response.arbitration_id - DIAGNOSTIC_RESPONSE_ARBITRATION_ID_OFFSET; } else { // must preserve responding arb ID for responses to functional broadcast // requests, as they are the actual module address and not just arb ID + // 8. message.diagnostic_response.message_id = response.arbitration_id; } message.diagnostic_response.has_mode = true; message.diagnostic_response.mode = response.mode; message.diagnostic_response.has_pid = response.has_pid; if(message.diagnostic_response.has_pid) message.diagnostic_response.pid = response.pid; message.diagnostic_response.has_success = true; message.diagnostic_response.success = response.success; message.diagnostic_response.has_negative_response_code = !response.success; message.diagnostic_response.negative_response_code = response.negative_response_code; if(response.payload_length > 0) { if(request->get_decoder() != nullptr) { message.diagnostic_response.has_value = true; message.diagnostic_response.value = parsed_value; } else { message.diagnostic_response.has_payload = true; ::memcpy(message.diagnostic_response.payload.bytes, response.payload, response.payload_length); message.diagnostic_response.payload.size = response.payload_length; } } return message; } /// /// @brief Build a specific VehicleMessage containing a SimpleMessage with associated timestamp /// /// @param[in] message - simple message to include into openxc_VehicleMessage /// @param[in] timestamp - timestamp from ioctl when reading the socket /// /// @return a vehicle message including simple message that will be convert into /// a JSON object before being pushed to the subscribers /// const openxc_VehicleMessage build_VehicleMessage(const openxc_SimpleMessage& message, uint64_t timestamp) { openxc_VehicleMessage v; ::memset(&v, 0, sizeof(v)); v.has_type = true, v.type = openxc_VehicleMessage_Type::openxc_VehicleMessage_Type_SIMPLE; v.has_simple_message = true; v.simple_message = message; v.has_timestamp = true; v.timestamp = timestamp; return v; } /// /// @brief Build a specific VehicleMessage containing a SimpleMessage. /// /// @param[in] message - simple message to include into openxc_VehicleMessage /// /// @return a vehicle message including simple message that will be convert into /// a JSON object before being pushed to the subscribers /// const openxc_VehicleMessage build_VehicleMessage(const openxc_SimpleMessage& message) { openxc_VehicleMessage v; ::memset(&v, 0, sizeof(v)); v.has_type = true, v.type = openxc_VehicleMessage_Type::openxc_VehicleMessage_Type_SIMPLE; v.has_simple_message = true; v.simple_message = message; v.has_timestamp = true; v.timestamp = system_time_us(); return v; } /// /// @brief Build an empty VehicleMessage that isn't usable by at least the struct /// is initialized for the most part and can be use to check a false return value. /// /// @return A VehicleMessage with all boolean value to false. /// openxc_VehicleMessage build_VehicleMessage() { openxc_VehicleMessage v; ::memset(&v, 0, sizeof(v)); return v; } bool is_valid(const openxc_VehicleMessage& v) { if (v.has_type == false && v.has_can_message == false && v.has_simple_message == false && v.has_diagnostic_response == false && v.has_control_command == false && v.has_command_response == false && v.has_timestamp == false) return false; return true; } /// /// @brief Build an openxc_SimpleMessage associating a name to an openxc_DynamicField /// /// @param[in] name - const string reference name to assign to the created SimpleMessage /// this will set has_name member to true and assign name to the name member. Maximum size for name is /// set to 100 char. /// @param[in] value - const reference with DynamicField to assign to SimpleMessage /// value. /// /// @return an openxc_SimpleMessage struct initialized with name and value provided. /// const openxc_SimpleMessage build_SimpleMessage(const std::string& name, const openxc_DynamicField& value) { openxc_SimpleMessage s; s.has_name = true; ::strncpy(s.name, name.c_str(), 99); s.has_value = true; s.value = value; return s; } /// @brief Build an openxc_DynamicField with a json object /// /// @param[in] value - const json_object pointer to assign to convert in an /// openxc_DynamicField. /// /// @return openxc_DynamicField initialized with a json object. /// const openxc_DynamicField build_DynamicField(json_object* value) { switch(json_object_get_type(value)) { case json_type_string: return build_DynamicField(json_object_get_string(value)); case json_type_double: return build_DynamicField(json_object_get_double(value)); case json_type_int: return build_DynamicField(json_object_get_double(value)); case json_type_boolean: return build_DynamicField((bool)json_object_get_boolean(value)); default: openxc_DynamicField d; ::memset(&d, 0, sizeof(openxc_DynamicField)); return d; } } const openxc_DynamicField build_DynamicField(std::vector<uint8_t> &array) { openxc_DynamicField d; d.has_type = true; d.type = openxc_DynamicField_Type_BYTES; d.has_string_value = false; d.has_numeric_value = false; d.has_boolean_value = false; d.has_bytes_value = true; d.error = false; size_t size = array.size(); if(size > 2040) { AFB_ERROR("Error to generate array dynamic field, too large data"); return d; } else { d.length_array = (uint32_t) size; } for(int i=0;i<size;i++) d.bytes_value[i] = array[i]; return d; } /// /// @brief Build an openxc_DynamicField with a string value /// /// @param[in] value - const string reference value to assign to builded /// openxc_DynamicField. /// /// @return openxc_DynamicField initialized with a string value. /// const openxc_DynamicField build_DynamicField(const char* value) { openxc_DynamicField d; d.has_type = true; d.type = openxc_DynamicField_Type_STRING; d.has_string_value = true; d.has_numeric_value = false; d.has_boolean_value = false; d.has_bytes_value = false; d.has_json_value = false; ::strncpy(d.string_value, value, 99); d.error = false; return d; } /// /// @brief Build an openxc_DynamicField with a string value /// /// @param[in] value - const string reference value to assign to builded /// openxc_DynamicField. /// /// @return openxc_DynamicField initialized with a string value. /// const openxc_DynamicField build_DynamicField(const std::string& value) { return build_DynamicField(value.c_str()); } /// /// @fn openxc_DynamicField build_DynamicField(double value); /// /// @brief Build an openxc_DynamicField with a double value /// /// @param[in] value - double value to assign to builded openxc_DynamicField. /// /// @return openxc_DynamicField initialized with a double value. /// const openxc_DynamicField build_DynamicField(double value) { openxc_DynamicField d; d.has_type = true; d.type = openxc_DynamicField_Type_NUM; d.has_string_value = false; d.has_numeric_value = true; d.has_boolean_value = false; d.has_bytes_value = false; d.has_json_value = false; d.numeric_value = value; d.error = false; return d; } /// /// @brief Build an openxc_DynamicField with a boolean value /// /// @param[in] value - boolean value to assign to builded openxc_DynamicField. /// /// @return openxc_DynamicField initialized with a boolean value. /// const openxc_DynamicField build_DynamicField(bool value) { openxc_DynamicField d; d.has_type = true; d.type = openxc_DynamicField_Type_BOOL; d.has_string_value = false; d.has_numeric_value = false; d.has_boolean_value = true; d.has_bytes_value = false; d.has_json_value = false; d.boolean_value = value; d.error = false; return d; } /// /// @brief Build an openxc_DynamicField with a json value /// /// @param[in] value - json value to assign to builded openxc_DynamicField. /// /// @return openxc_DynamicField initialized with a json value. /// const openxc_DynamicField build_DynamicField_json(json_object *value) { openxc_DynamicField d; d.has_type = true; d.type = openxc_DynamicField_Type_JSON; d.has_string_value = false; d.has_numeric_value = false; d.has_boolean_value = false; d.has_bytes_value = false; d.has_json_value = true; d.json_value = value; d.error = false; return d; } const openxc_DynamicField build_DynamicField_error() { openxc_DynamicField d; d.has_type = false; d.has_string_value = false; d.has_numeric_value = false; d.has_boolean_value = false; d.has_bytes_value = false; d.has_json_value = false; d.error = true; return d; } const openxc_DynamicField generate_openxc_DynamicField_from_message(std::shared_ptr<message_definition_t> messages_definition, std::shared_ptr<message_t> message, bool &send) { openxc_DynamicField ret = build_DynamicField_json(json_object_new_array()); openxc_DynamicField dynamicField_tmp; json_object *signal_json_tmp; for (std::shared_ptr<signal_t> sig : messages_definition->get_signals()) { signal_json_tmp = json_object_new_object(); dynamicField_tmp = decoder_t::translate_signal(*sig, message, &send); if (!dynamicField_tmp.error) // Not Error Match { if (dynamicField_tmp.has_type) { json_object_object_add(signal_json_tmp, sig->get_name().c_str(), jsonify_DynamicField(dynamicField_tmp)); if (sig != nullptr && sig->get_unit() != "") json_object_object_add(signal_json_tmp, "unit", json_object_new_string(sig->get_unit().c_str())); json_object_array_add(ret.json_value, signal_json_tmp); } send = true; } else // Error Match { send = false; break; } } return ret; } int get_bool_from_DynamicField(const openxc_VehicleMessage& v_msg, bool* ret) { if(v_msg.has_simple_message && v_msg.simple_message.has_value && v_msg.simple_message.value.has_boolean_value) { *ret = v_msg.simple_message.value.boolean_value; return 0; } return -1; } double get_numerical_from_DynamicField(const openxc_VehicleMessage& v_msg) { return (v_msg.has_simple_message && v_msg.simple_message.has_value && v_msg.simple_message.value.has_numeric_value) ? v_msg.simple_message.value.numeric_value : -1.0; } const std::string get_string_from_DynamicField(const openxc_VehicleMessage& v_msg) { return (v_msg.has_simple_message && v_msg.simple_message.has_value && v_msg.simple_message.value.has_string_value) ? v_msg.simple_message.value.string_value : ""; } /// /// @brief Extract the simple message value from an openxc_VehicleMessage /// and return it. If there isn't SimpleMessage in the VehicleMessage then /// returned value will be a SimpleMessage with all field set at false. /// DynamicField from SimpleMessage will be boolean DynamicField set to false too. /// /// @param[in] v_msg - const reference to openxc_VehicleMessage /// /// @return A simpleMessage from the provided VehicleMessage. /// const openxc_SimpleMessage get_simple_message(const openxc_VehicleMessage& v_msg) { if (v_msg.has_simple_message) return v_msg.simple_message; openxc_SimpleMessage s_msg = { false, "", false, build_DynamicField(false), false, build_DynamicField(false)}; return s_msg; } /// /// @brief Make a JSON object from a DynamicField /// /// @param[in] field - openxc_DynamicField struct to convert into /// a json object. /// @param[out] value - pointer to the object to set up. /// json_object* jsonify_DynamicField(const openxc_DynamicField& field) { if(field.has_numeric_value) return json_object_new_double(field.numeric_value); else if(field.has_boolean_value) return json_object_new_boolean(field.boolean_value); else if(field.has_string_value) return json_object_new_string(field.string_value); else if(field.has_bytes_value) return json_object_new_string(converter_t::to_hex(field.bytes_value, field.length_array).c_str()); else if(field.has_json_value) return json_object_get(field.json_value); return nullptr; } /// /// @brief Make a JSON object from a SimpleMessage /// /// @param[in] s_msg - const reference to an openxc_SimpleMessage /// struct to convert into a json object. /// @param[out] json - pointer with the DynamicField converted into json object /// /// @return True if SimpleMessage has been transformed into json object /// and false if not. In such case, a json object is returned { "error": "error msg"} /// bool jsonify_simple(const openxc_SimpleMessage& s_msg, json_object* json) { if(s_msg.has_name) { json_object_object_add(json, s_msg.name, jsonify_DynamicField(s_msg.value)); return true; } json_object_object_add(json, "error", json_object_new_string("openxc_SimpleMessage doesn't have name'")); return false; } /// /// @brief Make a JSON object from a VehicleMessage /// /// @param[in] v_msg - const reference to an openxc_VehicleMessage /// struct to convert into a json object. /// @param[in] sig - signal reference to the subscription of openxc_VehicleMessage, /// to get more informations about it /// @param[out] json - pointer with the DynamicField converted into json object /// /// @return True if VehicleMessage has been transformed into json object /// and false if not. In such case, a json object is returned { "error": "error msg"} /// bool jsonify_vehicle(const openxc_VehicleMessage& v_msg, std::shared_ptr<signal_t> sig, json_object* json) { if(sig) json_object_object_add(json,"id", json_object_new_int(sig->get_message()->get_id())); if(jsonify_simple(get_simple_message(v_msg), json)) { if(sig && sig->get_unit() != "") json_object_object_add(json, "unit", json_object_new_string(sig->get_unit().c_str())); if(v_msg.has_timestamp) json_object_object_add(json, "timestamp", json_object_new_int64(v_msg.timestamp)); return true; } json_object_object_add(json, "error", json_object_new_string("openxc_SimpleMessage doesn't have name'")); return false; }
30.720077
174
0.755294
[ "object", "vector" ]
53d75ffc99b22e70a58c7be5df89e256f70b96cf
14,981
cc
C++
src/attributes/CurveAttributes.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
41
2018-12-07T23:10:50.000Z
2022-02-19T03:01:49.000Z
src/attributes/CurveAttributes.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
59
2019-01-04T15:43:30.000Z
2022-03-31T09:48:15.000Z
src/attributes/CurveAttributes.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
13
2019-01-07T14:36:33.000Z
2021-09-06T14:48:36.000Z
/****************************** LICENSE ******************************* * (C) Copyright 1996-2017 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. ******************************* LICENSE *******************************/ /*! \\file CurveAttributes.h \\brief Definition of Curve Attributes class. This file is automatically generated. Do Not Edit! */ #include "CurveAttributes.h" #include "MagicsParameter.h" #include "ParameterSettings.h" using namespace magics; CurveAttributes::CurveAttributes(): line_(ParameterManager::getBool("graph_line")), thickness_(ParameterManager::getInt("graph_line_thickness")), symbol_(ParameterManager::getBool("graph_symbol")), symbol_marker_(ParameterManager::getInt("graph_symbol_marker_index")), symbol_height_(ParameterManager::getDouble("graph_symbol_height")), outline_(ParameterManager::getBool("graph_symbol_outline")), outline_thickness_(ParameterManager::getInt("graph_symbol_outline_thickness")), x_below_(ParameterManager::getDouble("graph_x_suppress_below")), x_above_(ParameterManager::getDouble("graph_x_suppress_above")), y_below_(ParameterManager::getDouble("graph_y_suppress_below")), y_above_(ParameterManager::getDouble("graph_y_suppress_above")), missing_mode_(ParameterManager::getString("graph_missing_data_mode")), missing_thickness_(ParameterManager::getInt("graph_missing_data_thickness")), plot_method_(ParameterManager::getString("graph_curve_method")), style_setting_(ParameterManager::getString("graph_style_setting")), style_key_(ParameterManager::getString("graph_line_style_variable_name")), style_keys_(ParameterManager::getStringArray("graph_line_style_value_list")), style_list_(ParameterManager::getStringArray("graph_line_style_list")), colour_key_(ParameterManager::getString("graph_colour_variable_name")), colour_keys_(ParameterManager::getStringArray("graph_colour_value_list")), colour_list_(ParameterManager::getStringArray("graph_colour_list")), thickness_key_(ParameterManager::getString("graph_thickness_variable_name")), thickness_keys_(ParameterManager::getStringArray("graph_thickness_value_list")), thickness_list_(ParameterManager::getIntArray("graph_thickness_list")) , style_(MagTranslator<string, LineStyle>().magics("graph_line_style")), colour_(MagTranslator<string, Colour>().magics("graph_line_colour")), symbol_colour_(MagTranslator<string, Colour>().magics("graph_symbol_colour")), outline_colour_(MagTranslator<string, Colour>().magics("graph_symbol_outline_colour")), outline_style_(MagTranslator<string, LineStyle>().magics("graph_symbol_outline_style")), missing_style_(MagTranslator<string, LineStyle>().magics("graph_missing_data_style")), missing_colour_(MagTranslator<string, Colour>().magics("graph_missing_data_colour")), style_policy_(MagTranslator<string, ListPolicy>().magics("graph_line_style_list_policy")), colour_policy_(MagTranslator<string, ListPolicy>().magics("graph_colour_list_policy")), thickness_policy_(MagTranslator<string, ListPolicy>().magics("graph_thickness_list_policy")) { } CurveAttributes::~CurveAttributes() { } void CurveAttributes::set(const std::map<string, string>& params) { vector<string> prefix(1); int i = 0; prefix[i++] = ""; setAttribute(prefix, "graph_line", line_, params); setAttribute(prefix, "graph_line_thickness", thickness_, params); setAttribute(prefix, "graph_symbol", symbol_, params); setAttribute(prefix, "graph_symbol_marker_index", symbol_marker_, params); setAttribute(prefix, "graph_symbol_height", symbol_height_, params); setAttribute(prefix, "graph_symbol_outline", outline_, params); setAttribute(prefix, "graph_symbol_outline_thickness", outline_thickness_, params); setAttribute(prefix, "graph_x_suppress_below", x_below_, params); setAttribute(prefix, "graph_x_suppress_above", x_above_, params); setAttribute(prefix, "graph_y_suppress_below", y_below_, params); setAttribute(prefix, "graph_y_suppress_above", y_above_, params); setAttribute(prefix, "graph_missing_data_mode", missing_mode_, params); setAttribute(prefix, "graph_missing_data_thickness", missing_thickness_, params); setAttribute(prefix, "graph_curve_method", plot_method_, params); setAttribute(prefix, "graph_style_setting", style_setting_, params); setAttribute(prefix, "graph_line_style_variable_name", style_key_, params); setAttribute(prefix, "graph_line_style_value_list", style_keys_, params); setAttribute(prefix, "graph_line_style_list", style_list_, params); setAttribute(prefix, "graph_colour_variable_name", colour_key_, params); setAttribute(prefix, "graph_colour_value_list", colour_keys_, params); setAttribute(prefix, "graph_colour_list", colour_list_, params); setAttribute(prefix, "graph_thickness_variable_name", thickness_key_, params); setAttribute(prefix, "graph_thickness_value_list", thickness_keys_, params); setAttribute(prefix, "graph_thickness_list", thickness_list_, params); setAttribute(prefix, "graph_line_style", style_, params); setMember(prefix, "graph_line_colour", colour_, params); setMember(prefix, "graph_symbol_colour", symbol_colour_, params); setMember(prefix, "graph_symbol_outline_colour", outline_colour_, params); setAttribute(prefix, "graph_symbol_outline_style", outline_style_, params); setAttribute(prefix, "graph_missing_data_style", missing_style_, params); setMember(prefix, "graph_missing_data_colour", missing_colour_, params); setAttribute(prefix, "graph_line_style_list_policy", style_policy_, params); setAttribute(prefix, "graph_colour_list_policy", colour_policy_, params); setAttribute(prefix, "graph_thickness_list_policy", thickness_policy_, params); } void CurveAttributes::copy(const CurveAttributes& other) { line_ = other.line_; thickness_ = other.thickness_; symbol_ = other.symbol_; symbol_marker_ = other.symbol_marker_; symbol_height_ = other.symbol_height_; outline_ = other.outline_; outline_thickness_ = other.outline_thickness_; x_below_ = other.x_below_; x_above_ = other.x_above_; y_below_ = other.y_below_; y_above_ = other.y_above_; missing_mode_ = other.missing_mode_; missing_thickness_ = other.missing_thickness_; plot_method_ = other.plot_method_; style_setting_ = other.style_setting_; style_key_ = other.style_key_; style_keys_ = other.style_keys_; style_list_ = other.style_list_; colour_key_ = other.colour_key_; colour_keys_ = other.colour_keys_; colour_list_ = other.colour_list_; thickness_key_ = other.thickness_key_; thickness_keys_ = other.thickness_keys_; thickness_list_ = other.thickness_list_; style_ = other.style_; colour_ = unique_ptr<Colour>(other.colour_->clone()); symbol_colour_ = unique_ptr<Colour>(other.symbol_colour_->clone()); outline_colour_ = unique_ptr<Colour>(other.outline_colour_->clone()); outline_style_ = other.outline_style_; missing_style_ = other.missing_style_; missing_colour_ = unique_ptr<Colour>(other.missing_colour_->clone()); style_policy_ = other.style_policy_; colour_policy_ = other.colour_policy_; thickness_policy_ = other.thickness_policy_; } bool CurveAttributes::accept(const string& node) { if ( magCompare(node, "") ) return true; return false; } void CurveAttributes::set(const XmlNode& node) { bool apply = false; if ( this->accept(node.name()) == false ) return; if ( magCompare(node.name(), "") ) apply = true; if ( apply ) set(node.attributes()); else { } for (auto &elt : node.elements()) { } } void CurveAttributes::print(ostream& out) const { out << "Attributes["; out << " line = " << line_; out << " thickness = " << thickness_; out << " symbol = " << symbol_; out << " symbol_marker = " << symbol_marker_; out << " symbol_height = " << symbol_height_; out << " outline = " << outline_; out << " outline_thickness = " << outline_thickness_; out << " x_below = " << x_below_; out << " x_above = " << x_above_; out << " y_below = " << y_below_; out << " y_above = " << y_above_; out << " missing_mode = " << missing_mode_; out << " missing_thickness = " << missing_thickness_; out << " plot_method = " << plot_method_; out << " style_setting = " << style_setting_; out << " style_key = " << style_key_; out << " style_keys = " << style_keys_; out << " style_list = " << style_list_; out << " colour_key = " << colour_key_; out << " colour_keys = " << colour_keys_; out << " colour_list = " << colour_list_; out << " thickness_key = " << thickness_key_; out << " thickness_keys = " << thickness_keys_; out << " thickness_list = " << thickness_list_; out << " style = " << style_; out << " colour = " << *colour_; out << " symbol_colour = " << *symbol_colour_; out << " outline_colour = " << *outline_colour_; out << " outline_style = " << outline_style_; out << " missing_style = " << missing_style_; out << " missing_colour = " << *missing_colour_; out << " style_policy = " << style_policy_; out << " colour_policy = " << colour_policy_; out << " thickness_policy = " << thickness_policy_; out << "]" << "\n"; } void CurveAttributes::toxml(ostream& out) const { out << "\"\""; out << ", \"graph_line\":"; niceprint(out,line_); out << ", \"graph_line_thickness\":"; niceprint(out,thickness_); out << ", \"graph_symbol\":"; niceprint(out,symbol_); out << ", \"graph_symbol_marker_index\":"; niceprint(out,symbol_marker_); out << ", \"graph_symbol_height\":"; niceprint(out,symbol_height_); out << ", \"graph_symbol_outline\":"; niceprint(out,outline_); out << ", \"graph_symbol_outline_thickness\":"; niceprint(out,outline_thickness_); out << ", \"graph_x_suppress_below\":"; niceprint(out,x_below_); out << ", \"graph_x_suppress_above\":"; niceprint(out,x_above_); out << ", \"graph_y_suppress_below\":"; niceprint(out,y_below_); out << ", \"graph_y_suppress_above\":"; niceprint(out,y_above_); out << ", \"graph_missing_data_mode\":"; niceprint(out,missing_mode_); out << ", \"graph_missing_data_thickness\":"; niceprint(out,missing_thickness_); out << ", \"graph_curve_method\":"; niceprint(out,plot_method_); out << ", \"graph_style_setting\":"; niceprint(out,style_setting_); out << ", \"graph_line_style_variable_name\":"; niceprint(out,style_key_); out << ", \"graph_line_style_value_list\":"; niceprint(out,style_keys_); out << ", \"graph_line_style_list\":"; niceprint(out,style_list_); out << ", \"graph_colour_variable_name\":"; niceprint(out,colour_key_); out << ", \"graph_colour_value_list\":"; niceprint(out,colour_keys_); out << ", \"graph_colour_list\":"; niceprint(out,colour_list_); out << ", \"graph_thickness_variable_name\":"; niceprint(out,thickness_key_); out << ", \"graph_thickness_value_list\":"; niceprint(out,thickness_keys_); out << ", \"graph_thickness_list\":"; niceprint(out,thickness_list_); out << ", \"graph_line_style\":"; niceprint(out, style_); out << ", \"graph_line_colour\":"; niceprint(out, *colour_); out << ", \"graph_symbol_colour\":"; niceprint(out, *symbol_colour_); out << ", \"graph_symbol_outline_colour\":"; niceprint(out, *outline_colour_); out << ", \"graph_symbol_outline_style\":"; niceprint(out, outline_style_); out << ", \"graph_missing_data_style\":"; niceprint(out, missing_style_); out << ", \"graph_missing_data_colour\":"; niceprint(out, *missing_colour_); out << ", \"graph_line_style_list_policy\":"; niceprint(out, style_policy_); out << ", \"graph_colour_list_policy\":"; niceprint(out, colour_policy_); out << ", \"graph_thickness_list_policy\":"; niceprint(out, thickness_policy_); } static MagicsParameter<string> graph_line("graph_line", "on"); static MagicsParameter<int> graph_line_thickness("graph_line_thickness", 1); static MagicsParameter<string> graph_symbol("graph_symbol", "off"); static MagicsParameter<int> graph_symbol_marker_index("graph_symbol_marker_index", 3); static MagicsParameter<double> graph_symbol_height("graph_symbol_height", 0.2); static MagicsParameter<string> graph_symbol_outline("graph_symbol_outline", "off"); static MagicsParameter<int> graph_symbol_outline_thickness("graph_symbol_outline_thickness", 1); static MagicsParameter<double> graph_x_suppress_below("graph_x_suppress_below", LLONG_MIN); static MagicsParameter<double> graph_x_suppress_above("graph_x_suppress_above", LLONG_MAX); static MagicsParameter<double> graph_y_suppress_below("graph_y_suppress_below", LLONG_MIN); static MagicsParameter<double> graph_y_suppress_above("graph_y_suppress_above", LLONG_MAX); static MagicsParameter<string> graph_missing_data_mode("graph_missing_data_mode", "ignore"); static MagicsParameter<int> graph_missing_data_thickness("graph_missing_data_thickness", 1); static MagicsParameter<string> graph_curve_method("graph_curve_method", "straight"); static MagicsParameter<string> graph_style_setting("graph_style_setting", "simple"); static MagicsParameter<string> graph_line_style_variable_name("graph_line_style_variable_name", ""); static MagicsParameter<stringarray> graph_line_style_value_list("graph_line_style_value_list", stringarray()); static MagicsParameter<stringarray> graph_line_style_list("graph_line_style_list", stringarray()); static MagicsParameter<string> graph_colour_variable_name("graph_colour_variable_name", ""); static MagicsParameter<stringarray> graph_colour_value_list("graph_colour_value_list", stringarray()); static MagicsParameter<stringarray> graph_colour_list("graph_colour_list", stringarray()); static MagicsParameter<string> graph_thickness_variable_name("graph_thickness_variable_name", ""); static MagicsParameter<stringarray> graph_thickness_value_list("graph_thickness_value_list", stringarray()); static MagicsParameter<intarray> graph_thickness_list("graph_thickness_list", intarray()); static MagicsParameter<string> graph_line_style("graph_line_style", "solid"); static MagicsParameter<string> graph_line_colour("graph_line_colour", "blue"); static MagicsParameter<string> graph_symbol_colour("graph_symbol_colour", "red"); static MagicsParameter<string> graph_symbol_outline_colour("graph_symbol_outline_colour", "black"); static MagicsParameter<string> graph_symbol_outline_style("graph_symbol_outline_style", "solid"); static MagicsParameter<string> graph_missing_data_style("graph_missing_data_style", "dash"); static MagicsParameter<string> graph_missing_data_colour("graph_missing_data_colour", "red"); static MagicsParameter<string> graph_line_style_list_policy("graph_line_style_list_policy", "lastone"); static MagicsParameter<string> graph_colour_list_policy("graph_colour_list_policy", "lastone"); static MagicsParameter<string> graph_thickness_list_policy("graph_thickness_list_policy", "lastone");
44.322485
110
0.759228
[ "vector", "solid" ]
53d7812b1c27e18b7f95bbde97a97892a30f5a85
3,263
cpp
C++
tests/Unit/Evolution/Systems/NewtonianEuler/Subcell/Test_InitialDataTci.cpp
nilsvu/spectre
1455b9a8d7e92db8ad600c66f54795c29c3052ee
[ "MIT" ]
117
2017-04-08T22:52:48.000Z
2022-03-25T07:23:36.000Z
tests/Unit/Evolution/Systems/NewtonianEuler/Subcell/Test_InitialDataTci.cpp
GitHimanshuc/spectre
4de4033ba36547113293fe4dbdd77591485a4aee
[ "MIT" ]
3,177
2017-04-07T21:10:18.000Z
2022-03-31T23:55:59.000Z
tests/Unit/Evolution/Systems/NewtonianEuler/Subcell/Test_InitialDataTci.cpp
geoffrey4444/spectre
9350d61830b360e2d5b273fdd176dcc841dbefb0
[ "MIT" ]
85
2017-04-07T19:36:13.000Z
2022-03-01T10:21:00.000Z
// Distributed under the MIT License. // See LICENSE.txt for details. #include "Framework/TestingFramework.hpp" #include <cstddef> #include "DataStructures/DataVector.hpp" #include "DataStructures/Tensor/Tensor.hpp" #include "DataStructures/Variables.hpp" #include "Evolution/DgSubcell/Mesh.hpp" #include "Evolution/DgSubcell/Tags/Inactive.hpp" #include "Evolution/Systems/NewtonianEuler/Subcell/InitialDataTci.hpp" #include "NumericalAlgorithms/Spectral/Mesh.hpp" #include "NumericalAlgorithms/Spectral/Spectral.hpp" namespace { template <typename Tag> using Inactive = evolution::dg::subcell::Tags::Inactive<Tag>; template <size_t Dim> void test() { using MassDensityCons = NewtonianEuler::Tags::MassDensityCons; using EnergyDensity = NewtonianEuler::Tags::EnergyDensity; using MomentumDensity = NewtonianEuler::Tags::MomentumDensity<Dim>; using ConsVars = Variables<tmpl::list<MassDensityCons, MomentumDensity, EnergyDensity>>; using InactiveConsVars = Variables<tmpl::list<Inactive<MassDensityCons>, Inactive<MomentumDensity>, Inactive<EnergyDensity>>>; const Mesh<Dim> dg_mesh{5, Spectral::Basis::Legendre, Spectral::Quadrature::GaussLobatto}; const Mesh<Dim> subcell_mesh = evolution::dg::subcell::fd::mesh(dg_mesh); ConsVars dg_vars{dg_mesh.number_of_grid_points(), 1.0}; Scalar<DataVector> dg_pressure{dg_mesh.number_of_grid_points(), 1.0}; const double delta0 = 1.0e-4; const double epsilon = 1.0e-3; const double exponent = 4.0; { INFO("TCI is happy"); const InactiveConsVars subcell_vars{subcell_mesh.number_of_grid_points(), 1.0}; CHECK_FALSE(NewtonianEuler::subcell::DgInitialDataTci<Dim>::apply( dg_vars, subcell_vars, delta0, epsilon, exponent, dg_mesh, dg_pressure)); } { INFO("Two mesh RDMP fails"); const InactiveConsVars subcell_vars{subcell_mesh.number_of_grid_points(), 2.0}; CHECK(NewtonianEuler::subcell::DgInitialDataTci<Dim>::apply( dg_vars, subcell_vars, delta0, epsilon, exponent, dg_mesh, dg_pressure)); } { INFO("Persson TCI mass density fails"); const InactiveConsVars subcell_vars{subcell_mesh.number_of_grid_points(), 1.0}; get(get<MassDensityCons>(dg_vars))[dg_mesh.number_of_grid_points() / 2] += 2.0e10; CHECK(NewtonianEuler::subcell::DgInitialDataTci<Dim>::apply( dg_vars, subcell_vars, 1.0e100, epsilon, exponent, dg_mesh, dg_pressure)); get(get<MassDensityCons>(dg_vars))[dg_mesh.number_of_grid_points() / 2] = 1.0; } { INFO("Persson TCI pressure fails"); const InactiveConsVars subcell_vars{subcell_mesh.number_of_grid_points(), 1.0}; get(dg_pressure)[dg_mesh.number_of_grid_points() / 2] *= 2.0; CHECK(NewtonianEuler::subcell::DgInitialDataTci<Dim>::apply( dg_vars, subcell_vars, 1.0e100, epsilon, exponent, dg_mesh, dg_pressure)); } } } // namespace SPECTRE_TEST_CASE( "Unit.Evolution.Systems.NewtonianEuler.Subcell.InitialDataTci", "[Unit][Evolution]") { test<1>(); test<2>(); test<3>(); }
35.857143
80
0.682194
[ "mesh" ]
53da22e7aeeb4e61f6b08ee857bd0a07d09312da
400
cpp
C++
src/frontal_demo.cpp
ivision-ufba/depth-face-detection
f70441eb9e72fa3f509458ffc202648c2f3e27d1
[ "MIT" ]
15
2017-11-01T11:39:32.000Z
2021-04-02T02:42:59.000Z
src/frontal_demo.cpp
ivision-ufba/depth-face-detection
f70441eb9e72fa3f509458ffc202648c2f3e27d1
[ "MIT" ]
6
2017-07-26T17:55:27.000Z
2020-11-15T22:04:35.000Z
src/frontal_demo.cpp
ivision-ufba/depth-face-detection
f70441eb9e72fa3f509458ffc202648c2f3e27d1
[ "MIT" ]
5
2018-05-09T13:42:17.000Z
2020-01-17T06:22:59.000Z
#include <opencv2/highgui.hpp> #include "abs.hpp" #include "face_detector.hpp" /* Demonstration of frontal depth face detection for a point cloud */ int main(const int argc, char** const argv) { std::vector<cv::Point3d> points; // read point cloud into points // coordinates must be in milimeters // detect faces FaceDetector detector; auto dets = detector.detect_frontal(points); }
22.222222
69
0.725
[ "vector" ]
53dfc99bd7367e45a39cbd6c5a4ab2cd78912d3e
61,907
cpp
C++
klustakwik-0.3.0.rc3/klustakwik.cpp
HasenstaubLab/KlustaKwik-Interface
1ae27c99ee16bdc0137ac76d35afc6bc36524436
[ "MIT" ]
null
null
null
klustakwik-0.3.0.rc3/klustakwik.cpp
HasenstaubLab/KlustaKwik-Interface
1ae27c99ee16bdc0137ac76d35afc6bc36524436
[ "MIT" ]
null
null
null
klustakwik-0.3.0.rc3/klustakwik.cpp
HasenstaubLab/KlustaKwik-Interface
1ae27c99ee16bdc0137ac76d35afc6bc36524436
[ "MIT" ]
null
null
null
// MaskedKlustaKwik2.C // // Fast clustering using the CEM algorithm with Masks. #ifndef VERSION #define VERSION "0.3.0-nogit" #endif // Disable some Visual Studio warnings #define _CRT_SECURE_NO_WARNINGS #include "klustakwik.h" #define _USE_MATH_DEFINES #include<math.h> #ifdef _OPENMP #include<omp.h> #endif // GLOBAL VARIABLES FILE *Distfp; integer global_numiterations = 0; scalar iteration_metric2 = (scalar)0; scalar iteration_metric3 = (scalar)0; clock_t Clock0; scalar timesofar; // Does a memory check (should only be called for first instance of KK) void KK::MemoryCheck() { long long NP = (long long)nPoints; long long MPC = (long long)MaxPossibleClusters; long long ND = (long long)nDims; vector<MemoryUsage> usages; #ifdef STORE_DATA_AS_INTEGER usages.push_back(MemoryUsage("Data", "data_int", sizeof(data_int), NP*ND, "nPoints*nDims", 2, 3)); #else usages.push_back(MemoryUsage("Data", "scalar", sizeof(scalar), NP*ND, "nPoints*nDims", 2, 3)); #endif #ifdef COMPUTED_BINARY_MASK if (!UseDistributional) usages.push_back(MemoryUsage("Masks", "char", sizeof(char), NP*ND, "nPoints*nDims", 2, 3)); #else usages.push_back(MemoryUsage("Masks", "char", sizeof(char), NP*ND, "nPoints*nDims", 2, 3)); #endif #ifdef STORE_FLOAT_MASK_AS_CHAR usages.push_back(MemoryUsage("CharFloatMasks", "char", sizeof(char), NP*ND, "nPoints*nDims", 2, 3)); #else usages.push_back(MemoryUsage("FloatMasks", "scalar", sizeof(scalar), NP*ND, "nPoints*nDims", 2, 3)); #endif if (UseDistributional) usages.push_back(MemoryUsage("Cov", "scalar", sizeof(scalar), MPC*ND*ND, "MaxPossibleClusters*nDims*nDims", 0, 3)); else usages.push_back(MemoryUsage("Cov", "scalar", sizeof(scalar), MPC*ND*ND, "MaxPossibleClusters*nDims*nDims", 2, 3)); usages.push_back(MemoryUsage("LogP", "scalar", sizeof(scalar), MPC*NP, "MaxPossibleClusters*nPoints", 2, 3)); usages.push_back(MemoryUsage("AllVector2Mean", "scalar", sizeof(scalar), NP*ND, "nPoints*nDims", 2, 3)); #ifndef COMPUTED_CORRECTION_TERM if (UseDistributional) usages.push_back(MemoryUsage("CorrectionTerm", "scalar", sizeof(scalar), NP*ND, "nPoints*nDims", 2, 3)); #endif check_memory_usage(usages, RamLimitGB, nPoints, nDims, MaxPossibleClusters); } template<class T> inline void resize_and_fill_with_zeros(vector<T> &x, integer newsize) { if (x.size() == 0) { x.resize((uinteger)newsize); return; } if (x.size() > (uinteger)newsize) { fill(x.begin(), x.end(), (T)0); x.resize((uinteger)newsize); } else { x.resize((uinteger)newsize); fill(x.begin(), x.end(), (T)0); } } // Sets storage for KK class. Needs to have nDims and nPoints defined void KK::AllocateArrays() { nDims2 = nDims*nDims; NoisePoint = 1; // Ensures that the mixture weight for the noise cluster never gets to zero // Set sizes for arrays resize_and_fill_with_zeros(Data, nPoints * nDims); //SNK #ifdef COMPUTED_BINARY_MASK if(!UseDistributional) resize_and_fill_with_zeros(Masks, nPoints * nDims); #else resize_and_fill_with_zeros(Masks, nPoints * nDims); #endif #ifdef STORE_FLOAT_MASK_AS_CHAR resize_and_fill_with_zeros(CharFloatMasks, nPoints * nDims); #else resize_and_fill_with_zeros(FloatMasks, nPoints * nDims); #endif resize_and_fill_with_zeros(UnMaskDims, nPoints); //SNK Number of unmasked dimensions for each data point when using float masks $\sum m_i$ resize_and_fill_with_zeros(Weight, MaxPossibleClusters); resize_and_fill_with_zeros(Mean, MaxPossibleClusters*nDims); if (!UseDistributional) resize_and_fill_with_zeros(Cov, MaxPossibleClusters*nDims2); resize_and_fill_with_zeros(LogP, MaxPossibleClusters*nPoints); resize_and_fill_with_zeros(Class, nPoints); resize_and_fill_with_zeros(OldClass, nPoints); resize_and_fill_with_zeros(Class2, nPoints); resize_and_fill_with_zeros(BestClass, nPoints); resize_and_fill_with_zeros(ClassAlive, MaxPossibleClusters); resize_and_fill_with_zeros(AliveIndex, MaxPossibleClusters); resize_and_fill_with_zeros(ClassPenalty, MaxPossibleClusters); resize_and_fill_with_zeros(nClassMembers, MaxPossibleClusters); if(UseDistributional) { #ifndef COMPUTED_CORRECTION_TERM resize_and_fill_with_zeros(CorrectionTerm, nPoints * nDims); #endif resize_and_fill_with_zeros(ClusterMask, MaxPossibleClusters*nDims); } } // recompute index of alive clusters (including 0, the noise cluster) // should be called after anything that changes ClassAlive void KK::Reindex() { integer c; AliveIndex[0] = 0; nClustersAlive=1; for(c=1;c<MaxPossibleClusters;c++) { if (ClassAlive[c]) { AliveIndex[nClustersAlive] = c; nClustersAlive++; } } } // Penalty for standard CEM // Penalty(nAlive) returns the complexity penalty for that many clusters // bearing in mind that cluster 0 has no free params except p. scalar KK::Penalty(integer n) { integer nParams; if(n==1) return 0; nParams = (nDims*(nDims+1)/2 + nDims + 1)*(n-1); // each has cov, mean, &p scalar p = penaltyK*(scalar)(nParams) // AIC units (Spurious factor of 2 removed from AIC units on 09.07.13) +penaltyKLogN*((scalar)nParams*(scalar)log((scalar)nPoints)/2); // BIC units return p; } // Penalties for Masked CEM void KK::ComputeClassPenalties() { if(UseDistributional==0) // This function must only be called in Use Distributional mode { // Output("Caught in ComputeClassPenalties"); return; } // Output("ComputeClassPenalties: Correct if UseDistributional only"); for(integer c=0; c<MaxPossibleClusters; c++) ClassPenalty[c] = (scalar)0; // compute sum of nParams for each vector<integer> NumberInClass(MaxPossibleClusters); for(integer p=0; p<nPoints; p++) { integer c = Class[p]; NumberInClass[c]++; // integer n = UnmaskedInd[p+1]-UnmaskedInd[p]; // num unmasked dimensions scalar n = UnMaskDims[p]; scalar nParams = n*(n+1)/2+n+1; ClassPenalty[c] += nParams; } // compute mean nParams for each cluster for(integer c=0; c<MaxPossibleClusters; c++) if(NumberInClass[c]>0) ClassPenalty[c] /= (scalar)NumberInClass[c]; // compute penalty for each cluster for(integer c=0; c<MaxPossibleClusters; c++) { scalar nParams = ClassPenalty[c]; ClassPenalty[c] = penaltyK*(scalar)(nParams*2) +penaltyKLogN*((scalar)nParams*(scalar)log((scalar)nPoints)/2); } } // Compute the cluster masks (i.e. the sets of features which are masked/unmasked // for the whole cluster). Used by M-step and E-step void KK::ComputeClusterMasks() { Reindex(); // Initialise cluster mask to 0 for(integer i=0; i<nDims*MaxPossibleClusters; i++) ClusterMask[i] = 0; // Compute cluster mask for(integer p=0; p<nPoints; p++) { integer c = Class[p]; for (integer i = 0; i < nDims; i++) { #ifdef STORE_FLOAT_MASK_AS_CHAR ClusterMask[c*nDims + i] += (scalar)(CharFloatMasks[p*nDims + i]/(scalar)255.0); #else ClusterMask[c*nDims + i] += FloatMasks[p*nDims + i]; #endif } } // Compute the set of masked/unmasked features for each cluster // reset all the subvectors to empty ClusterUnmaskedFeatures.clear(); ClusterUnmaskedFeatures.resize(MaxPossibleClusters); ClusterMaskedFeatures.clear(); ClusterMaskedFeatures.resize(MaxPossibleClusters); // fill them in for (integer cc = 0; cc<nClustersAlive; cc++) { integer c = AliveIndex[cc]; vector<integer> &CurrentUnmasked = ClusterUnmaskedFeatures[c]; vector<integer> &CurrentMasked = ClusterMaskedFeatures[c]; for (integer i = 0; i < nDims; i++) { if (ClusterMask[c*nDims + i]>=PointsForClusterMask) CurrentUnmasked.push_back(i); else CurrentMasked.push_back(i); } if (Verbose>=2) { Output("Cluster mask: cluster %d unmasked %d iterations %d/%d init type %d.\n", (int)cc, (int)CurrentUnmasked.size(), (int)numiterations, (int)global_numiterations, (int)init_type); } } } // M-step: Calculate mean, cov, and weight for each living class // also deletes any classes with fewer points than nDim void KK::MStep() { integer p, c, cc, i, j; vector<scalar> Vec2Mean(nDims); // clear arrays memset((void*)&nClassMembers.front(), 0, MaxPossibleClusters*sizeof(integer)); memset((void*)&Mean.front(), 0, MaxPossibleClusters*nDims*sizeof(scalar)); if (!UseDistributional) memset((void*)&Cov.front(), 0, MaxPossibleClusters*nDims2*sizeof(scalar)); // NOTE: memset commands above replace the code below: // for(c=0; c<MaxPossibleClusters; c++) { // nClassMembers[c] = 0; // for(i=0; i<nDims; i++) Mean[c*nDims + i] = 0; // } if (Debug) { Output("Entering Unmasked Mstep \n");} // Accumulate total number of points in each class for (p=0; p<nPoints; p++) nClassMembers[Class[p]]++; // check for any dead classes if(UseDistributional) { for (integer cc=0; cc<nClustersAlive; cc++) { integer c = AliveIndex[cc]; if (Debug){Output("DistributionalMstep: Class %d contains %d members \n", (int)c, (int)nClassMembers[c]);} if (c>0 && nClassMembers[c]<1)//nDims) { ClassAlive[c]=0; if (Debug) {Output("UnmaskedMstep_dist: Deleted class %d: no members\n", (int)c);} } } } else { for (cc=0; cc<nClustersAlive; cc++) { c = AliveIndex[cc]; if (Debug) {Output("Mstep: Class %d contains %d members \n", (int)c, (int)nClassMembers[c]);} if (c>0 && nClassMembers[c]<=nDims) { ClassAlive[c]=0; if (Debug) {Output("Deleted class %d: not enough members\n", (int)c);} } } } Reindex(); // Normalize by total number of points to give class weight // Also check for dead classes if(UseDistributional) { for (cc=0; cc<nClustersAlive; cc++) { c = AliveIndex[cc]; //Output("DistributionalMstep: PriorPoint on weights "); // add "noise point" to make sure Weight for noise cluster never gets to zero if(c==0) { Weight[c] = ((scalar)nClassMembers[c]+NoisePoint) / (nPoints+NoisePoint+priorPoint*(nClustersAlive-1)); } else { Weight[c] = ((scalar)nClassMembers[c]+priorPoint) / (nPoints+NoisePoint+priorPoint*(nClustersAlive-1)); } } } else // For Original KlustaKwik, Classical EM { for (cc=0; cc<nClustersAlive; cc++) { c = AliveIndex[cc]; // add "noise point" to make sure Weight for noise cluster never gets to zero if(c==0) { Weight[c] = ((scalar)nClassMembers[c]+NoisePoint) / (nPoints+NoisePoint); } else { Weight[c] = ((scalar)nClassMembers[c]) / (nPoints+NoisePoint); } } } Reindex(); // Accumulate sums for mean calculation for (p=0; p<nPoints; p++) { c = Class[p]; for(i=0; i<nDims; i++) { Mean[c*nDims + i] += GetData(p, i); } } // and normalize for (cc=0; cc<nClustersAlive; cc++) { c = AliveIndex[cc]; for (i=0; i<nDims; i++) Mean[c*nDims + i] /= nClassMembers[c]; } // Covariance matrix is quite big, and won't fit in the L1d cache // (which is 16 or 32 k usually, corresponding to a matrix of about 64x64 or 90x90) // so can probably improve performance by doing some sort of blocking here // Accumulate sums for covariance calculation // for (p=0; p<nPoints; p++) // { // c = Class[p]; // // calculate distance from mean // for(i=0; i<nDims; i++) // Vec2Mean[i] = Data[p*nDims + i] - Mean[c*nDims + i]; // for(i=0; i<nDims; i++) // for(j=i; j<nDims; j++) // Cov[c*nDims2 + i*nDims + j] += Vec2Mean[i] * Vec2Mean[j]; // } if ((integer)AllVector2Mean.size() < nPoints*nDims) { //mem.add((nPoints*nDims-AllVector2Mean.size())*sizeof(scalar)); AllVector2Mean.resize(nPoints*nDims); } vector< vector<integer> > PointsInClass(MaxPossibleClusters); for(p=0; p<nPoints; p++) { c = Class[p]; PointsInClass[c].push_back(p); for (i = 0; i < nDims; i++) AllVector2Mean[p*nDims + i] = GetData(p, i) - Mean[c*nDims + i]; } if (UseDistributional) { // Compute the cluster masks, used below to optimise the computation ComputeClusterMasks(); // Empty the dynamic covariance matrices (we will fill it up as we go) DynamicCov.clear(); for (cc = 0; cc < nClustersAlive; cc++) { c = AliveIndex[cc]; vector<integer> &CurrentUnmasked = ClusterUnmaskedFeatures[c]; vector<integer> &CurrentMasked = ClusterMaskedFeatures[c]; DynamicCov.push_back(BlockPlusDiagonalMatrix(CurrentMasked, CurrentUnmasked)); } #pragma omp parallel for schedule(dynamic) for (integer cc = 0; cc<nClustersAlive; cc++) { const integer c = AliveIndex[cc]; const vector<integer> &PointsInThisClass = PointsInClass[c]; const integer NumPointsInThisClass = PointsInThisClass.size(); const vector<integer> &CurrentUnmasked = ClusterUnmaskedFeatures[c]; //const vector<integer> &CurrentMasked = ClusterMaskedFeatures[c]; BlockPlusDiagonalMatrix &CurrentCov = DynamicCov[cc]; if (CurrentUnmasked.size() > 0) { const integer npoints = (integer)PointsInThisClass.size(); const integer nunmasked = (integer)CurrentUnmasked.size(); if (npoints > 0 && nunmasked > 0) { const integer * __restrict pitc = &(PointsInThisClass[0]); const integer * __restrict cu = &(CurrentUnmasked[0]); for (integer q = 0; q < npoints; q++) { const integer p = pitc[q]; const scalar * __restrict av2mp = &(AllVector2Mean[p*nDims]); for (integer ii = 0; ii < nunmasked; ii++) { const integer i = cu[ii]; const scalar av2mp_i = av2mp[i]; scalar * __restrict row = &(CurrentCov.Block[ii*nunmasked]); for (integer jj = 0; jj < nunmasked; jj++) { const integer j = cu[jj]; //Cov[c*nDims2 + i*nDims + j] += AllVector2Mean[p*nDims + i] * AllVector2Mean[p*nDims + j]; row[jj] += av2mp_i * av2mp[j]; } } } } } // for (integer ii = 0; ii<CurrentCov.NumUnmasked; ii++) { const integer i = (*CurrentCov.Unmasked)[ii]; scalar ccf = 0.0; // class correction factor for (integer q = 0; q<NumPointsInThisClass; q++) { const integer p = PointsInThisClass[q]; #ifdef COMPUTED_CORRECTION_TERM ccf += GetCorrectionTerm(p, i); #else ccf += CorrectionTerm[p*nDims + i]; #endif } CurrentCov.Block[ii*CurrentCov.NumUnmasked + ii] += ccf; } for (integer ii = 0; ii<CurrentCov.NumMasked; ii++) { const integer i = (*CurrentCov.Masked)[ii]; scalar ccf = 0.0; // class correction factor for (integer q = 0; q<NumPointsInThisClass; q++) { const integer p = PointsInThisClass[q]; #ifdef COMPUTED_CORRECTION_TERM ccf += GetCorrectionTerm(p, i); #else ccf += CorrectionTerm[p*nDims + i]; #endif } CurrentCov.Diagonal[ii] += ccf; } // for (integer ii = 0; ii < CurrentCov.NumUnmasked; ii++) CurrentCov.Block[ii*CurrentCov.NumUnmasked + ii] += priorPoint*NoiseVariance[(*CurrentCov.Unmasked)[ii]]; for (integer ii = 0; ii < CurrentCov.NumMasked; ii++) CurrentCov.Diagonal[ii] += priorPoint*NoiseVariance[(*CurrentCov.Masked)[ii]]; // const scalar factor = 1.0 / (nClassMembers[c] + priorPoint - 1); for (i = 0; i < (integer)CurrentCov.Block.size(); i++) CurrentCov.Block[i] *= factor; for (i = 0; i < (integer)CurrentCov.Diagonal.size(); i++) CurrentCov.Diagonal[i] *= factor; } } if (UseDistributional) { // // Compute the cluster masks, used below to optimise the computation // ComputeClusterMasks(); // // Empty the dynamic covariance matrices (we will fill it up as we go) // DynamicCov.clear(); // // for (cc = 0; cc < nClustersAlive; cc++) // { // c = AliveIndex[cc]; // vector<integer> &PointsInThisClass = PointsInClass[c]; // vector<integer> &CurrentUnmasked = ClusterUnmaskedFeatures[c]; // vector<integer> &CurrentMasked = ClusterMaskedFeatures[c]; // DynamicCov.push_back(BlockPlusDiagonalMatrix(CurrentMasked, CurrentUnmasked)); // } // //#pragma omp parallel for // for (integer cc = 0; cc<nClustersAlive; cc++) // { // integer c = AliveIndex[cc]; // vector<integer> &PointsInThisClass = PointsInClass[c]; // vector<integer> &CurrentUnmasked = ClusterUnmaskedFeatures[c]; // vector<integer> &CurrentMasked = ClusterMaskedFeatures[c]; // //DynamicCov.push_back(BlockPlusDiagonalMatrix(CurrentMasked, CurrentUnmasked)); // BlockPlusDiagonalMatrix &CurrentCov = DynamicCov[cc]; // if (CurrentUnmasked.size() == 0) // continue; // // //// Correct version for dynamic cov matrix // //for (integer q = 0; q < (integer)PointsInThisClass.size(); q++) // //{ // // p = PointsInThisClass[q]; // // for (integer ii = 0; ii < (integer)CurrentUnmasked.size(); ii++) // // { // // i = CurrentUnmasked[ii]; // // for (integer jj = 0; jj < (integer)CurrentUnmasked.size(); jj++) // // { // // j = CurrentUnmasked[jj]; // // //Cov[c*nDims2 + i*nDims + j] += AllVector2Mean[p*nDims + i] * AllVector2Mean[p*nDims + j]; // // CurrentCov.Block[ii*CurrentCov.NumUnmasked + jj] += AllVector2Mean[p*nDims + i] * AllVector2Mean[p*nDims + j]; // // } // // } // //} // // Fast version for dynamic cov matrix // const integer npoints = (integer)PointsInThisClass.size(); // const integer nunmasked = (integer)CurrentUnmasked.size(); // if (npoints > 0 && nunmasked > 0) // { // const integer * __restrict pitc = &(PointsInThisClass[0]); // const integer * __restrict cu = &(CurrentUnmasked[0]); // for (integer q = 0; q < npoints; q++) // { // const integer p = pitc[q]; // const scalar * __restrict av2mp = &(AllVector2Mean[p*nDims]); // for (integer ii = 0; ii < nunmasked; ii++) // { // const integer i = cu[ii]; // const scalar av2mp_i = av2mp[i]; // scalar * __restrict row = &(CurrentCov.Block[ii*nunmasked]); // for (integer jj = 0; jj < nunmasked; jj++) // { // const integer j = cu[jj]; // //Cov[c*nDims2 + i*nDims + j] += AllVector2Mean[p*nDims + i] * AllVector2Mean[p*nDims + j]; // row[jj] += av2mp_i * av2mp[j]; // } // } // } // } // // // Correct version // //for (integer q = 0; q < (integer)PointsInThisClass.size(); q++) // //{ // // p = PointsInThisClass[q]; // // for (integer ii = 0; ii < (integer)CurrentUnmasked.size(); ii++) // // { // // i = CurrentUnmasked[ii]; // // for (integer jj = 0; jj < (integer)CurrentUnmasked.size(); jj++) // // { // // j = CurrentUnmasked[jj]; // // Cov[c*nDims2 + i*nDims + j] += AllVector2Mean[p*nDims + i] * AllVector2Mean[p*nDims + j]; // // } // // } // //} // // Faster version (equivalent) // // Doesn't make any use of cache structure, but no need to upgrade now because // // we will move to a sparse block matrix structure that will make this more // // natural // /* // const integer * __restrict cu = &(CurrentUnmasked[0]); // const integer ncu = (integer)CurrentUnmasked.size(); // scalar * __restrict cov_c = &(Cov[c*nDims2]); // const integer * __restrict pitc = &(PointsInThisClass[0]); // const integer npitc = (integer)PointsInThisClass.size(); // const scalar * __restrict av2m = &(AllVector2Mean[0]); // for (integer q = 0; q < npitc; q++) // { // const integer p = pitc[q]; // const scalar * __restrict av2m_p = av2m + p*nDims; // for (integer ii = 0; ii < ncu; ii++) // { // const integer i = cu[ii]; // const scalar av2m_p_i = av2m_p[i]; // scalar * __restrict cov_c_i = cov_c + i*nDims; // for (integer jj = 0; jj < ncu; jj++) // { // const integer j = cu[jj]; // cov_c_i[j] += av2m_p_i*av2m_p[j]; // //Cov[c*nDims2 + i*nDims + j] += AllVector2Mean[p*nDims + i] * AllVector2Mean[p*nDims + j]; // } // } // } // */ // } } else { // I think this code gives wrong results (but only slightly) (DFMG: 2014/10/13) for (c = 0; c < MaxPossibleClusters; c++) { vector<integer> &PointsInThisClass = PointsInClass[c]; SafeArray<scalar> safeCov(Cov, c*nDims2, "safeCovMStep"); for (integer iblock = 0; iblock < nDims; iblock += COVARIANCE_BLOCKSIZE) { for (integer jblock = iblock; jblock < nDims; jblock += COVARIANCE_BLOCKSIZE) { for (integer q = 0; q < (integer)PointsInThisClass.size(); q++) { p = PointsInThisClass[q]; scalar *cv2m = &AllVector2Mean[p*nDims]; for (i = iblock; i < MIN(nDims, iblock + COVARIANCE_BLOCKSIZE); i++) { scalar cv2mi = cv2m[i]; integer jstart; if (jblock != iblock) jstart = jblock; else jstart = i; scalar *covptr = &safeCov[i*nDims + jstart]; scalar *cv2mjptr = &cv2m[jstart]; //scalar *cv2mjend = cv2m+MIN(nDims, jblock+COVARIANCE_BLOCKSIZE); //for(j=jstart; j<MIN(nDims, jblock+COVARIANCE_BLOCKSIZE); j++) //for(; cv2mjptr!=cv2mjend;) for (j = MIN(nDims, jblock + COVARIANCE_BLOCKSIZE) - jstart; j; j--) *covptr++ += cv2mi*(*cv2mjptr++); } } } } } } // and normalize if(!UseDistributional) { //For original KlustaKwik classical EM for (cc=0; cc<nClustersAlive; cc++) { c = AliveIndex[cc]; for(i=0; i<nDims; i++) for(j=i; j<nDims; j++) Cov[c*nDims2 + i*nDims + j] /= (nClassMembers[c]-1); } } // That's it! // Diagnostics if (Debug) { for (cc=0; cc<nClustersAlive; cc++) { c = AliveIndex[cc]; Output("Class %d - Weight %.2g\n", (int)c, Weight[c]); Output("Mean: "); MatPrint(stdout, &Mean.front() + c*nDims, 1, nDims); if (!UseDistributional) { Output("\nCov:\n"); MatPrint(stdout, &Cov.front() + c*nDims2, nDims, nDims); } Output("\n"); } } } // E-step. Calculate Log Probs for each point to belong to each living class // will delete a class if covariance matrix is singular // also counts number of living classes void KK::EStep() { integer p, c, cc, i; integer nSkipped; scalar LogRootDet; // log of square root of covariance determinant scalar correction_factor = (scalar)1; // for partial correction in distributional step //scalar InverseClusterNorm; vector<scalar> Chol(nDims2); // to store choleski decomposition vector<scalar> Vec2Mean(nDims); // stores data point minus class mean vector<scalar> Root(nDims); // stores result of Chol*Root = Vec vector<scalar> InvCovDiag; if(UseDistributional) InvCovDiag.resize(nDims); SafeArray<scalar> safeChol(Chol, "safeChol"); SafeArray<scalar> safeVec2Mean(Vec2Mean, "safeVec2Mean"); SafeArray<scalar> safeRoot(Root, "safeRoot"); SafeArray<scalar> safeInvCovDiag(InvCovDiag, "safeInvCovDiag"); nSkipped = 0; if (Debug) {Output("Entering Unmasked Estep \n");} // start with cluster 0 - uniform distribution over space // because we have normalized all dims to 0...1, density will be 1. vector<integer> NumberInClass(MaxPossibleClusters); // For finding number of points in each class for (p=0; p<nPoints; p++) { LogP[p*MaxPossibleClusters + 0] = (float)-log(Weight[0]); integer ccc = Class[p]; NumberInClass[ccc]++; } BlockPlusDiagonalMatrix *CurrentCov; BlockPlusDiagonalMatrix *CholBPD = NULL; for (cc = 1; cc<nClustersAlive; cc++) { c = AliveIndex[cc]; // calculate cholesky decomposition for class c integer chol_return; if (UseDistributional) { CurrentCov = &(DynamicCov[cc]); if (CholBPD) { delete CholBPD; CholBPD = NULL; } CholBPD = new BlockPlusDiagonalMatrix(*(CurrentCov->Masked), *(CurrentCov->Unmasked)); chol_return = BPDCholesky(*CurrentCov, *CholBPD); //if (MinMaskOverlap>0) //{ // // compute the norm of the cluster mask (used for skipping points) // const scalar * __restrict cm = &(ClusterMask[c*nDims]); // scalar ClusterNorm = 0.0; // for (i = 0; i < nDims; i++) // { // scalar m = cm[i]; // //if (m > ClusterNorm) // // ClusterNorm = m; // ClusterNorm += m*m; // } // //InverseClusterNorm = 1.0 / ClusterNorm; // InverseClusterNorm = 1.0 / sqrt(ClusterNorm); // //InverseClusterNorm = sqrt((scalar)nDims) / sqrt(ClusterNorm); //} } else { SafeArray<scalar> safeCov(Cov, c*nDims2, "safeCov"); chol_return = Cholesky(safeCov, safeChol, nDims); } if(chol_return) { // If Cholesky returns 1, it means the matrix is not positive definite. // So kill the class. // Cholesky is defined in linalg.cpp Output("Unmasked E-step: Deleting class %d (%d points): covariance matrix is singular \n", (int)c, (int)NumberInClass[c]); ClassAlive[c] = 0; continue; } // LogRootDet is given by log of product of diagonal elements if (UseDistributional) { LogRootDet = 0; for (integer ii = 0; ii < CholBPD->NumUnmasked; ii++) LogRootDet += log(CholBPD->Block[ii*CholBPD->NumUnmasked + ii]); for (integer ii = 0; ii < CholBPD->NumMasked; ii++) LogRootDet += log(CholBPD->Diagonal[ii]); } else { LogRootDet = 0; for (i = 0; i < nDims; i++) LogRootDet += log(Chol[i*nDims + i]); } // if distributional E step, compute diagonal of inverse of cov matrix if(UseDistributional) { vector<scalar> BasisVector(nDims); SafeArray<scalar> safeBasisVector(BasisVector, "BasisVector"); for(integer i=0; i<nDims; i++) safeBasisVector[i] = (scalar)0; for(integer i=0; i<nDims; i++) { safeBasisVector[i] = (scalar)1; // calculate Root vector - by Chol*Root = BasisVector BPDTriSolve(*CholBPD, safeBasisVector, safeRoot); // add half of Root vector squared to log p scalar Sii = (scalar)0; for(integer j=0; j<nDims; j++) Sii += Root[j]*Root[j]; safeInvCovDiag[i] = Sii; safeBasisVector[i] = (scalar)0; } } #pragma omp parallel for schedule(dynamic) firstprivate(Vec2Mean, Root) default(shared) for(integer p=0; p<nPoints; p++) { // to save time -- only recalculate if the last one was close if ( !FullStep && (Class[p] == OldClass[p]) && (LogP[p*MaxPossibleClusters+c] - LogP[p*MaxPossibleClusters+Class[p]] > DistThresh) ) { #pragma omp atomic nSkipped++; continue; } // to save time, skip points with mask overlap below threshold if (MinMaskOverlap > 0) { // compute dot product of point mask with cluster mask #ifdef STORE_FLOAT_MASK_AS_CHAR const unsigned char * __restrict CharPointMask = &(CharFloatMasks[p*nDims]); #else const scalar * __restrict PointMask = &(FloatMasks[p*nDims]); #endif //const scalar * __restrict cm = &(ClusterMask[c*nDims]); scalar dotprod = 0.0; //// InverseClusterNorm is computed above, uncomment it if you uncomment any of this //for (i = 0; i < nDims; i++) //{ // dotprod += cm[i] * PointMask[i] * InverseClusterNorm; // if (dotprod >= MinMaskOverlap) // break; //} const integer NumUnmasked = CurrentCov->NumUnmasked; if (NumUnmasked) { const integer * __restrict cu = &((*(CurrentCov->Unmasked))[0]); for (integer ii = 0; ii < NumUnmasked; ii++) { const integer i = cu[ii]; #ifdef STORE_FLOAT_MASK_AS_CHAR dotprod += CharPointMask[i]/(scalar)255.0; #else dotprod += PointMask[i]; #endif if (dotprod >= MinMaskOverlap) break; } } //dotprod *= InverseClusterNorm; if (dotprod < MinMaskOverlap) { #pragma omp atomic nSkipped++; continue; } } SafeArray<scalar> safeVec2Mean(Vec2Mean, "safeVec2Mean"); SafeArray<scalar> safeRoot(Root, "safeRoot"); // Compute Mahalanobis distance scalar Mahal = 0; // calculate data minus class mean //for (i = 0; i<nDims; i++) // Vec2Mean[i] = Data[p*nDims + i] - Mean[c*nDims + i]; restricted_data_pointer Data_p = &(Data[p*nDims]); scalar * __restrict Mean_c = &(Mean[c*nDims]); scalar * __restrict v2m = &(Vec2Mean[0]); for (i = 0; i < nDims; i++) v2m[i] = get_data_from_pointer(Data_p, i) - Mean_c[i]; // calculate Root vector - by Chol*Root = Vec2Mean if (UseDistributional) BPDTriSolve(*CholBPD, safeVec2Mean, safeRoot); else TriSolve(safeChol, safeVec2Mean, safeRoot, nDims); // add half of Root vector squared to log p for(i=0; i<nDims; i++) Mahal += Root[i]*Root[i]; // if distributional E step, add correction term if (UseDistributional) { const scalar * __restrict icd = &(InvCovDiag[0]); scalar subMahal = 0.0; #ifdef COMPUTED_CORRECTION_TERM #ifdef STORE_FLOAT_MASK_AS_CHAR const unsigned char * __restrict ptr_char_w = &(CharFloatMasks[p*nDims]); #else const scalar * __restrict ptr_w = &(FloatMasks[p*nDims]); #endif const scalar * __restrict ptr_nu = &(NoiseMean[0]); const scalar * __restrict ptr_sigma2 = &(NoiseVariance[0]); restricted_data_pointer ptr_y = &(Data[p*nDims]); for (i = 0; i < nDims; i++) { #ifdef STORE_FLOAT_MASK_AS_CHAR const scalar w = ptr_char_w[i]/(scalar)255.0; #else const scalar w = ptr_w[i]; #endif const scalar nu = ptr_nu[i]; const scalar sigma2 = ptr_sigma2[i]; const scalar y = get_data_from_pointer(ptr_y, i); scalar eta; if(w==(scalar)0.0) { const scalar z = nu*nu+sigma2; eta = z-y*y; } else { const scalar x = (y-(1-w)*nu)/w; const scalar z = w*x*x+(1-w)*(nu*nu+sigma2); eta = z-y*y; } subMahal += eta * icd[i]; } #else const scalar * __restrict ctp = &(CorrectionTerm[p*nDims]); for (i = 0; i < nDims; i++) subMahal += ctp[i] * icd[i]; #endif Mahal += subMahal*correction_factor; } // Score is given by Mahal/2 + log RootDet - log weight LogP[p*MaxPossibleClusters + c] = Mahal/2 + LogRootDet - log(Weight[c]) + (0.5*log(2 * M_PI))*nDims; } // for(p=0; p<nPoints; p++) } // for(cc=1; cc<nClustersAlive; cc++) if (CholBPD) delete CholBPD; } // Choose best class for each point (and second best) out of those living void KK::CStep(bool allow_assign_to_noise) { integer p, c, cc, TopClass, SecondClass; integer ccstart = 0; if(!allow_assign_to_noise) ccstart = 1; scalar ThisScore, BestScore, SecondScore; for (p=0; p<nPoints; p++) { OldClass[p] = Class[p]; BestScore = HugeScore; SecondScore = HugeScore; TopClass = SecondClass = 0; for (cc=ccstart; cc<nClustersAlive; cc++) { c = AliveIndex[cc]; ThisScore = LogP[p*MaxPossibleClusters + c]; if (ThisScore < BestScore) { SecondClass = TopClass; TopClass = c; SecondScore = BestScore; BestScore = ThisScore; } else if (ThisScore < SecondScore) { SecondClass = c; SecondScore = ThisScore; } } Class[p] = TopClass; Class2[p] = SecondClass; } } // Sometimes deleting a cluster will improve the score, when you take into account // the BIC. This function sees if this is the case. It will not delete more than // one cluster at a time. void KK::ConsiderDeletion() { integer c, p, CandidateClass=0; scalar Loss, DeltaPen; vector<scalar> DeletionLoss(MaxPossibleClusters); // the increase in log P by deleting the cluster if (Debug) Output(" Entering ConsiderDeletion: "); for(c=1; c<MaxPossibleClusters; c++) { if (ClassAlive[c]) DeletionLoss[c] = 0; else DeletionLoss[c] = HugeScore; // don't delete classes that are already there } // compute losses by deleting clusters vector<integer> NumberInClass(MaxPossibleClusters); for(p=0; p<nPoints; p++) { DeletionLoss[Class[p]] += LogP[p*MaxPossibleClusters + Class2[p]] - LogP[p*MaxPossibleClusters + Class[p]]; integer ccc = Class[p]; NumberInClass[ccc]++; // For computing number of points in each class } // find class with smallest increase in total score Loss = HugeScore; if (UseDistributional) //For UseDistribution, we use the ClusterPenalty { for(c=1; c<MaxPossibleClusters; c++) { if ((DeletionLoss[c]-ClassPenalty[c])<Loss) { Loss = DeletionLoss[c]-ClassPenalty[c]; CandidateClass = c; } } }// or in the case of fixed penalty find class with least to lose else { for(c=1; c<MaxPossibleClusters; c++) { if (DeletionLoss[c]<Loss) { Loss = DeletionLoss[c]; CandidateClass = c; } } } // what is the change in penalty? if(UseDistributional) //For the distributional algorithm we need to use the ClusterPenalty DeltaPen = ClassPenalty[CandidateClass]; else DeltaPen = Penalty(nClustersAlive) - Penalty(nClustersAlive-1); //Output("cand Class %d would lose " SCALARFMT " gain is " SCALARFMT "\n", (int)CandidateClass, Loss, DeltaPen); // is it worth it? //06/12/12 fixing bug introduced which considered DeltaPen twice! if (UseDistributional) //For the distributional algorithm we need to use the ClusterPenalty { if (Loss<0) { Output("Deleting Class %d (%d points): Lose " SCALARFMT " but Gain " SCALARFMT "\n", (int)CandidateClass, (int)NumberInClass[CandidateClass], DeletionLoss[CandidateClass], DeltaPen); // set it to dead ClassAlive[CandidateClass] = 0; // re-allocate all of its points for(p=0;p<nPoints; p++) if(Class[p]==CandidateClass) Class[p] = Class2[p]; // recompute class penalties ComputeClassPenalties(); } } else { if (Loss<DeltaPen) { Output("Deleting Class %d (%d points): Lose " SCALARFMT " but Gain " SCALARFMT "\n", (int)CandidateClass, (int)NumberInClass[CandidateClass], DeletionLoss[CandidateClass], DeltaPen); // set it to dead ClassAlive[CandidateClass] = 0; // re-allocate all of its points for(p=0;p<nPoints; p++) if(Class[p]==CandidateClass) Class[p] = Class2[p]; // recompute class penalties ComputeClassPenalties(); } } Reindex(); } // LoadClu(CluFile) void KK::LoadClu(char *CluFile) { FILE *fp; integer p, c; int val; // read in from %d integer status; fp = fopen_safe(CluFile, "r"); status = fscanf(fp, "%d", &nStartingClusters); nClustersAlive = nStartingClusters;// -1; for(c=0; c<MaxPossibleClusters; c++) ClassAlive[c]=(c<nStartingClusters); for(p=0; p<nPoints; p++) { status = fscanf(fp, "%d", &val); if (status==EOF) Error("Error reading cluster file"); Class[p] = val-1; } } // for each cluster, try to split it in two. if that improves the score, do it. // returns 1 if split was successful integer KK::TrySplits() { integer c, cc, c2, p, p2, DidSplit = 0; scalar Score, NewScore, UnsplitScore, SplitScore; integer UnusedCluster; //KK K2; // second KK structure for sub-clustering //KK K3; // third one for comparison if(nClustersAlive>=MaxPossibleClusters-1) { Output("Won't try splitting - already at maximum number of clusters\n"); return 0; } // set up K3 and remember to add the masks //KK K3(*this); if (!AlwaysSplitBimodal) { if (KK_split == NULL) { KK_split = new KK(*this); } else { // We have to clear these to bypass the debugging checks // in precomputations.cpp KK_split->Unmasked.clear(); KK_split->UnmaskedInd.clear(); KK_split->SortedMaskChange.clear(); KK_split->SortedIndices.clear(); // now we treat it as empty KK_split->ConstructFrom(*this); } } //KK &K3 = *KK_split; #define K3 (*KK_split) Output("Compute initial score before splitting: "); Score = ComputeScore(); // loop thu clusters, trying to split for (cc=1; cc<nClustersAlive; cc++) { c = AliveIndex[cc]; // set up K2 structure to contain points of this cluster only vector<integer> SubsetIndices; for(p=0; p<nPoints; p++) if(Class[p]==c) SubsetIndices.push_back(p); if(SubsetIndices.size()==0) continue; if (K2_container) { // We have to clear these to bypass the debugging checks // in precomputations.cpp K2_container->Unmasked.clear(); K2_container->UnmaskedInd.clear(); K2_container->SortedMaskChange.clear(); K2_container->SortedIndices.clear(); //K2_container->AllVector2Mean.clear(); // now we treat it as empty K2_container->ConstructFrom(*this, SubsetIndices); } else { K2_container = new KK(*this, SubsetIndices); } //KK K2(*this, SubsetIndices); KK &K2 = *K2_container; // find an unused cluster UnusedCluster = -1; for(c2=1; c2<MaxPossibleClusters; c2++) { if (!ClassAlive[c2]) { UnusedCluster = c2; break; } } if (UnusedCluster==-1) { Output("No free clusters, abandoning split"); return DidSplit; } // do it if (Verbose >= 1) Output("\n Trying to split cluster %d (%d points) \n", (int)c, (int)K2.nPoints); K2.nStartingClusters=2; // (2 = 1 clusters + 1 unused noise cluster) UnsplitScore = K2.CEM(NULL, 0, 1, false); K2.nStartingClusters=3; // (3 = 2 clusters + 1 unused noise cluster) SplitScore = K2.CEM(NULL, 0, 1, false); // Fix by Michaël Zugaro: replace next line with following two lines // if(SplitScore<UnsplitScore) { if(K2.nClustersAlive<2) Output("\n Split failed - leaving alone\n"); if((SplitScore<UnsplitScore)&&(K2.nClustersAlive>=2)) { if (AlwaysSplitBimodal) { DidSplit = 1; Output("\n We are always splitting bimodal clusters so it's getting split into cluster %d.\n", (int)UnusedCluster); p2 = 0; for (p = 0; p < nPoints; p++) { if (Class[p] == c) { if (K2.Class[p2] == 1) Class[p] = c; else if (K2.Class[p2] == 2) Class[p] = UnusedCluster; else Error("split should only produce 2 clusters\n"); p2++; } ClassAlive[Class[p]] = 1; } } else { // will splitting improve the score in the whole data set? // assign clusters to K3 for (c2 = 0; c2 < MaxPossibleClusters; c2++) K3.ClassAlive[c2] = 0; // Output("%d Points in class %d in KKobject K3 ", (int)c2, (int)K3.nClassMembers[c2]); p2 = 0; for (p = 0; p < nPoints; p++) { if (Class[p] == c) { if (K2.Class[p2] == 1) K3.Class[p] = c; else if (K2.Class[p2] == 2) K3.Class[p] = UnusedCluster; else Error("split should only produce 2 clusters\n"); p2++; } else K3.Class[p] = Class[p]; K3.ClassAlive[K3.Class[p]] = 1; } K3.Reindex(); // compute scores K3.MStep(); K3.EStep(); //Output("About to compute K3 class penalties"); if (UseDistributional) K3.ComputeClassPenalties(); //SNK Fixed bug: Need to compute the cluster penalty properly, cluster penalty is only used in UseDistributional mode NewScore = K3.ComputeScore(); Output("\nSplitting cluster %d changes total score from " SCALARFMT " to " SCALARFMT "\n", (int)c, Score, NewScore); if (NewScore < Score) { DidSplit = 1; Output("\n So it's getting split into cluster %d.\n", (int)UnusedCluster); // so put clusters from K3 back into main KK struct (K1) for (c2 = 0; c2 < MaxPossibleClusters; c2++) ClassAlive[c2] = K3.ClassAlive[c2]; for (p = 0; p < nPoints; p++) Class[p] = K3.Class[p]; } else { Output("\n So it's not getting split.\n"); } } } } return DidSplit; #undef K3 } // ComputeScore() - computes total score. Requires M, E, and C steps to have been run scalar KK::ComputeScore() { integer p; // integer debugadd; scalar penalty = (scalar)0; if(UseDistributional) // For distributional algorithm we require the cluster penalty for(integer c=0; c<MaxPossibleClusters; c++) penalty += ClassPenalty[c]; else penalty = Penalty(nClustersAlive); scalar Score = penalty; for(p=0; p<nPoints; p++) { //debugadd = LogP[p*MaxPossibleClusters + Class[p]]; Score += LogP[p*MaxPossibleClusters + Class[p]]; // Output("point %d: cumulative score " SCALARFMT " adding" SCALARFMT "\n", (int)p, Score, debugadd); } //Error("Score: " SCALARFMT " Penalty: " SCALARFMT "\n", Score, penalty); Output(" Score: Raw " SCALARFMT " + Penalty " SCALARFMT " = " SCALARFMT "\n", Score-penalty, penalty, Score); if (Debug) { integer c, cc; scalar tScore; for(cc=0; cc<nClustersAlive; cc++) { c = AliveIndex[cc]; tScore = 0; for(p=0; p<nPoints; p++) if(Class[p]==c) tScore += LogP[p*MaxPossibleClusters + Class[p]]; Output("class %d has subscore " SCALARFMT "\n", c, tScore); } } return Score; } // Initialise starting conditions randomly void KK::StartingConditionsRandom() { // initialize data to random if(nStartingClusters>1) for(integer p=0; p<nPoints; p++) // No points are put in the noise cluster to begin Class[p] = irand(1, nStartingClusters-1); else for(integer p=0; p<nPoints; p++) //If there is only one cluster, put all the points in the noise cluster Class[p] = 0; for(integer c=0; c<MaxPossibleClusters; c++) ClassAlive[c] = (c<nStartingClusters); if (SplitInfo == 1) Output("\tSP: Assigned %d initial classes randomly.\n", (int)nStartingClusters); } // Initialise starting conditions by selecting unique masks at random void KK::StartingConditionsFromMasks() { integer nClusters2start=0; //SNK To replace nStartingClusters within this variable only //if (Debug) // Output("StartingConditionsFromMasks: "); Output("Starting initial clusters from distinct float masks \n "); if(nStartingClusters<=1) // If only 1 starting clutser has been requested, assign all the points to cluster 0 { for(integer p=0; p<nPoints; p++) Class[p] = 0; } else { integer num_masks = 0; for(integer p=0; p<nPoints; p++) num_masks += (integer)SortedMaskChange[p]; if((nStartingClusters-1)>num_masks) { Error("Not enough masks (%d) to generate starting clusters (%d), " "so starting with (%d) clusters instead.\n", (int)num_masks, (int)nStartingClusters, (int)(num_masks + 1)); nClusters2start = num_masks+1; //return; } else { nClusters2start = nStartingClusters; } // Construct the set of all masks vector<bool> MaskUsed; vector<integer> MaskIndex(nPoints); vector<integer> MaskPointIndex; integer current_mask_index = -1; for(integer q=0; q<nPoints; q++) { integer p = SortedIndices[q]; if(q==0 || SortedMaskChange[p]) { current_mask_index++; MaskUsed.push_back(false); MaskPointIndex.push_back(p); } MaskIndex[p] = current_mask_index; } // Select points at random until we have enough masks integer masks_found = 0; vector<integer> MaskIndexToUse; vector<integer> FoundMaskIndex(num_masks); while(masks_found<nClusters2start-1) { integer p = irand(0, nPoints-1); integer mask_index = MaskIndex[p]; if(!MaskUsed[mask_index]) { MaskIndexToUse.push_back(mask_index); MaskUsed[mask_index] = true; FoundMaskIndex[mask_index] = masks_found; masks_found++; } } // Assign points to clusters based on masks for(integer p=0; p<nPoints; p++) { if(MaskUsed[MaskIndex[p]]) // we included this points mask Class[p] = FoundMaskIndex[MaskIndex[p]]+1; // so assign class to mask index else // this points mask not included { // so find closest match integer closest_index = 0; integer distance = nDims+1; vector<integer> possibilities; for(integer mi=0; mi<nClusters2start-1; mi++) { integer mip = MaskPointIndex[MaskIndexToUse[mi]]; // compute mask distance integer curdistance = 0; for(integer i=0; i<nDims; i++) if(GetMasks(p*nDims+i)!=GetMasks(mip*nDims+i)) curdistance++; if(curdistance<distance) { possibilities.clear(); distance = curdistance; } if(curdistance==distance) possibilities.push_back(mi); } if((MaskStarts > 0) ||AssignToFirstClosestMask) closest_index = possibilities[0]; else closest_index = possibilities[irand(0, possibilities.size()-1)]; Class[p] = closest_index+1; } } // print some info Output("Assigned %d initial classes from %d unique masks.\n", (int)nClusters2start, (int)num_masks); // Dump initial random classes to a file - knowledge of maskstart configuration may be useful // TODO: remove this for final version - SNK: actually it is a nice idea to keep this char fname[STRLEN]; FILE *fp; sprintf(fname, "%s.initialclusters.%d.clu.%d", FileBase, (int)nClusters2start, (int)ElecNo); fp = fopen_safe(fname, "w"); fprintf(fp, "%d\n", (int)nClusters2start); for(integer p=0; p<nPoints; p++) fprintf(fp, "%d\n", (int)Class[p]); fclose(fp); } for(integer c=0; c<MaxPossibleClusters; c++) ClassAlive[c] = (c<nClusters2start); } // CEM(StartFile) - Does a whole CEM algorithm from a random start or masked start // whereby clusters are assigned according to the similarity of their masks // optional start file loads this cluster file to start iteration // if Recurse is 0, it will not try and split. // if InitRand is 0, use cluster assignments already in structure scalar KK::CEM(char *CluFile, integer Recurse, integer InitRand, bool allow_assign_to_noise) { integer p; integer nChanged; integer Iter; vector<integer> OldClass(nPoints); scalar Score, OldScore; integer LastStepFull; // stores whether the last step was a full one integer DidSplit; if (Debug) { Output("Entering CEM \n"); } if (CluFile && *CluFile) LoadClu(CluFile); else if (InitRand) { // initialize data to random if((MaskStarts||UseMaskedInitialConditions) && (UseDistributional) && Recurse) StartingConditionsFromMasks(); else StartingConditionsRandom(); } // set all classes to alive Reindex(); // main loop Iter = 0; FullStep = 1; Score = 0.0; do { // Store old classifications for(p=0; p<nPoints; p++) OldClass[p] = Class[p]; // M-step - calculate class weights, means, and covariance matrices for each class MStep(); // E-step - calculate scores for each point to belong to each class EStep(); // dump distances if required if (DistDump) MatPrint(Distfp, &LogP.front(), DistDump, MaxPossibleClusters); // C-step - choose best class for each CStep(allow_assign_to_noise); // Compute class penalties ComputeClassPenalties(); // Would deleting any classes improve things? if(Recurse) ConsiderDeletion(); // Calculate number changed nChanged = 0; for(p=0; p<nPoints; p++) nChanged += (OldClass[p] != Class[p]); //Compute elapsed time timesofar = (clock()-Clock0)/(scalar) CLOCKS_PER_SEC; //Output("\nTime so far" SCALARFMT " seconds.\n", timesofar); //Write start of output to klg file if(Verbose>=1) { if(Recurse==0) Output("\t\tSP:"); if ((Recurse!=0)||(SplitInfo==1&&Recurse==0)) Output("Iteration %d%c (" SCALARFMT " sec): %d clusters\n", (int)Iter, FullStep ? 'F' : 'Q', timesofar, (int)nClustersAlive); } // Calculate score OldScore = Score; Score = ComputeScore(); //Finish output to klg file with Score already returned via the ComputeScore() function if(Verbose>=1) { Output(" nChanged %d\n", (int)nChanged); } //if(Verbose>=1) //{ // if(Recurse==0) Output("\t"); // Output(" Iteration %d%c: %d clusters Score %.7g nChanged %d\n", // (int)Iter, FullStep ? 'F' : 'Q', (int)nClustersAlive, Score, (int)nChanged); //} Iter++; numiterations++; global_numiterations++; iteration_metric2 += (scalar)(nDims*nDims)*(scalar)(nPoints); iteration_metric3 += (scalar)(nDims*nDims)*(scalar)(nDims*nPoints); if (Debug) { for(p=0;p<nPoints;p++) BestClass[p] = Class[p]; SaveOutput(); Output("Press return"); getchar(); } // Next step a full step? LastStepFull = FullStep; FullStep = ( nChanged>ChangedThresh*nPoints || nChanged == 0 || Iter%FullStepEvery==0 || Score > OldScore // SNK: Resurrected //SNK Score decreases ARE because of quick steps! ) ; if (Iter>MaxIter) { Output("Maximum iterations exceeded\n"); break; } //Save a temporary clu file when not splitting if ((SaveTempCluEveryIter && Recurse) && (OldScore> Score)) { SaveTempOutput(); //SNK Saves a temporary output clu file on each iteration Output("Writing temp clu file \n"); Output("Because OldScore, %f, is greater than current (better) Score,%f \n ", OldScore, Score); } // try splitting //integer mod = (abs(Iter-SplitFirst))%SplitEvery; //Output("\n Iter mod SplitEvery = %d\n",(int)mod); //Output("Iter-SplitFirst %d \n",(int)(Iter-SplitFirst)); if ((Recurse && SplitEvery>0) && ( Iter==SplitFirst ||( Iter>=SplitFirst+1 && (Iter-SplitFirst)%SplitEvery==SplitEvery-1 ) || (nChanged==0 && LastStepFull) ) ) { if (OldScore> Score) //This should be trivially true for the first run of KlustaKwik { SaveTempOutput(); //SNK Saves a temporary output clu file before each split Output("Writing temp clu file \n"); Output("Because OldScore, %f, is greater than current (better) Score,%f \n ", OldScore, Score); } DidSplit = TrySplits(); } else DidSplit = 0; } while (nChanged > 0 || !LastStepFull || DidSplit); if (DistDump) fprintf(Distfp, "\n"); return Score; } // does the two-step clustering algorithm: // first make a subset of the data, to SubPoints points // then run CEM on this // then use these clusters to do a CEM on the full data // It calls CEM whenever there is no initialization clu file (i.e. the most common usage) scalar KK::Cluster(char *StartCluFile=NULL) { if (Debug) { Output("Entering Cluster \n"); } if (Subset<=1) { // don't subset Output("------ Clustering full data set of %d points ------\n", (int)nPoints); return CEM(NULL, 1, 1); } // otherwise run on a subset of points integer sPoints = nPoints/Subset; // number of subset points - integer division will round down vector<integer> SubsetIndices(sPoints); for (integer i=0; i<sPoints; i++) // choose point to include, evenly spaced plus a random offset SubsetIndices[i] = Subset*i + irand(0, Subset-1); KK KKSub = KK(*this, SubsetIndices); // run CEM algorithm on KKSub Output("------ Running on subset of %d points ------\n", (int)sPoints); KKSub.CEM(NULL, 1, 1); // now copy cluster shapes from KKSub to main KK Weight = KKSub.Weight; Mean = KKSub.Mean; Cov = KKSub.Cov; DynamicCov = KKSub.DynamicCov; ClassAlive = KKSub.ClassAlive; nClustersAlive = KKSub.nClustersAlive; AliveIndex = KKSub.AliveIndex; // Run E and C steps on full data set Output("------ Evaluating fit on full set of %d points ------\n", (int)nPoints); if(UseDistributional) ComputeClusterMasks(); // needed by E-step normally computed by M-step EStep(); CStep(); // compute score on full data set and leave return ComputeScore(); } // Initialise by loading data from files KK::KK(char *FileBase, integer ElecNo, char *UseFeatures, scalar PenaltyK, scalar PenaltyKLogN, integer PriorPoint) { KK_split = NULL; K2_container = NULL; penaltyK = PenaltyK; penaltyKLogN = PenaltyKLogN; LoadData(FileBase, ElecNo, UseFeatures); priorPoint = PriorPoint; //NOTE: penaltyK, penaltyKlogN, priorPoint, lower case versions of global variable PenaltyK PenaltyKLogN and PriorPoint DoInitialPrecomputations();//Now DoPrecomputations is only invoked in the initialization numiterations = 0; init_type = 0; } // This function is used by both of the constructors below, it initialises // the data from a source KK object with a subset of the indices. void KK::ConstructFrom(const KK &Source, const vector<integer> &Indices) { KK_split = NULL; K2_container = NULL; nDims = Source.nDims; nDims2 = nDims*nDims; nPoints = Indices.size(); penaltyK = Source.penaltyK; penaltyKLogN = Source.penaltyKLogN; priorPoint = Source.priorPoint; nStartingClusters = Source.nStartingClusters; NoisePoint = Source.NoisePoint; FullStep = Source.FullStep; nClustersAlive = Source.nClustersAlive; numiterations = Source.numiterations; AllocateArrays(); // Set storage for all the arrays such as Data, FloatMasks, Weight, Mean, Cov, etc. if (Debug) { Output("Entering ConstructFrom: \n"); } // fill with a subset of points for (integer p=0; p<nPoints; p++) { integer psource = Indices[p]; //copy data and masks for (integer d=0; d<nDims; d++) Data[p*nDims + d] = Source.Data[psource*nDims + d]; if(Source.Masks.size()>0) { for (integer d=0; d<nDims; d++) Masks[p*nDims + d] = Source.Masks[psource*nDims + d]; } if(UseDistributional) { for (integer d=0; d<nDims; d++) { #ifdef STORE_FLOAT_MASK_AS_CHAR CharFloatMasks[p*nDims + d] = Source.CharFloatMasks[psource*nDims + d]; #else FloatMasks[p*nDims + d] = Source.FloatMasks[psource*nDims + d]; #endif } } UnMaskDims[p] = Source.UnMaskDims[psource]; } //Output(" Printing Source.NoiseVariance[2] = %f",Source.NoiseVariance[2]); if(UseDistributional) { NoiseMean.resize(nDims); NoiseVariance.resize(nDims); nMasked.resize(nDims); for (integer d=0; d<nDims;d++) { NoiseMean[d] = Source.NoiseMean[d]; NoiseVariance[d] = Source.NoiseVariance[d]; nMasked[d] = Source.nMasked[d]; } } DoPrecomputations(); //Output(" Printing Source.NoiseMean[2] = %f",NoiseVariance[2]); numiterations = 0; } void KK::ConstructFrom(const KK &Source) { vector<integer> Indices(Source.nPoints); for (integer i = 0; i<Source.nPoints; i++) Indices[i] = i; ConstructFrom(Source, Indices); } KK::KK(const KK &Source, const vector<integer> &Indices) { ConstructFrom(Source, Indices); init_type = 2; } // If we don't specify an index subset, use everything. KK::KK(const KK &Source) { ConstructFrom(Source); init_type = 1; } KK::~KK() { if (KK_split) delete KK_split; KK_split = NULL; if (K2_container) delete K2_container; K2_container = NULL; } // Main loop int main(int argc, char **argv) { scalar Score; scalar BestScore = HugeScore; integer p, i; SetupParams((integer)argc, argv); // This function is defined in parameters.cpp Output("Starting KlustaKwik. Version: %s\n", VERSION); if (RamLimitGB == 0.0) { RamLimitGB = (1.0*total_physical_memory()) / (1024.0*1024.0*1024.0); Output("Setting RAM limit to total physical memory, %.2f GB.\n", (double)RamLimitGB); } else if (RamLimitGB < 0.0) { RamLimitGB = 1e20; Output("WARNING: You have chosen not to set a RAM limit, this may cause problems.\n"); } //clock_t Clock0 = clock(); Clock0 = clock(); #ifdef _OPENMP double start_time = omp_get_wtime(); #endif // The main KK object, loads the data and does some precomputations KK K1(FileBase, ElecNo, UseFeatures, PenaltyK, PenaltyKLogN, PriorPoint); if(UseDistributional && SaveSorted) //Bug fix (Classical KK would terminate here) K1.SaveSortedData(); // Seed random number generator srand((unsigned int)RandomSeed); // open distance dump file if required if (DistDump) Distfp = fopen("DISTDUMP", "w"); // start with provided file, if required if (*StartCluFile) { Output("\nStarting from cluster file %s\n", StartCluFile); scalar iterationtime = (scalar)clock(); BestScore = K1.CEM(StartCluFile, 1, 1); //Main computation iterationtime = (clock()-iterationtime)/(scalar) CLOCKS_PER_SEC; Output("Time taken for this iteration:" SCALARFMT " seconds.\n", iterationtime); Output(" %d->%d Clusters: Score " SCALARFMT "\n\n", (int)K1.nStartingClusters, (int)K1.nClustersAlive, BestScore); for(p=0; p<K1.nPoints; p++) K1.BestClass[p] = K1.Class[p]; K1.SaveOutput(); } else { // loop through numbers of clusters ... for(K1.nStartingClusters=(int)MinClusters; K1.nStartingClusters<=(int)MaxClusters; K1.nStartingClusters++) for(i=0; i<nStarts; i++) { // do CEM iteration Output("\nStarting from %d clusters...\n", (int)K1.nStartingClusters); scalar iterationtime = (scalar)clock(); Score = K1.Cluster(); //Main computation iterationtime = (clock()-iterationtime)/(scalar) CLOCKS_PER_SEC; Output("Time taken for this iteration:" SCALARFMT " seconds.\n", iterationtime); Output(" %d->%d Clusters: Score " SCALARFMT ", best is " SCALARFMT "\n", (int)K1.nStartingClusters, (int)K1.nClustersAlive, Score, BestScore); if (Score < BestScore) { Output("THE BEST YET!\n"); // New best classification found BestScore = Score; for(p=0; p<K1.nPoints; p++) K1.BestClass[p] = K1.Class[p]; K1.SaveOutput(); } Output("\n"); } } K1.SaveOutput(); #ifdef _OPENMP scalar tottime = omp_get_wtime() - start_time; #else scalar tottime = (clock() - Clock0) / (scalar)CLOCKS_PER_SEC; #endif Output("Main iterations: %d (time per iteration =" SCALARFMT " ms)\n", (int)K1.numiterations, 1e3*tottime/K1.numiterations); Output("Total iterations: %d (time per iteration =" SCALARFMT " ms)\n", (int)global_numiterations, 1e3*tottime/global_numiterations); Output("\nDef. Iteration metric 2:\nIteration_metric2 += (scalar)(nDims*nDims)*(scalar)(nPoints)\n"); Output("Iterations metric 2: " SCALARFMT " (time per metric unit =" SCALARFMT "ns)\n", iteration_metric2, 1e9*tottime/iteration_metric2); Output("\nDef. Iteration metric 3:\nIteration_metric3 += (scalar)(nDims*nDims)*(scalar)(nDims*nPoints)\n"); Output("Iterations metric 3: " SCALARFMT " (time per metric unit=" SCALARFMT "ps)\n", iteration_metric3, 1e12*tottime/iteration_metric3); Output("\nThat took " SCALARFMT " seconds.\n", tottime); if (DistDump) fclose(Distfp); return 0; }
32.755026
185
0.60557
[ "object", "vector" ]
53e4e087ebdb98c04cac270a4086d4d529ff0a07
6,833
cpp
C++
2017/07/main.cpp
adrian-stanciu/adventofcode
47b3d12226b0c71fff485ef140cd7731c9a5d72f
[ "MIT" ]
null
null
null
2017/07/main.cpp
adrian-stanciu/adventofcode
47b3d12226b0c71fff485ef140cd7731c9a5d72f
[ "MIT" ]
null
null
null
2017/07/main.cpp
adrian-stanciu/adventofcode
47b3d12226b0c71fff485ef140cd7731c9a5d72f
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <regex> #include <sstream> #include <string> #include <vector> #include <unordered_map> #include <unordered_set> struct Program { std::string name; long weight; std::vector<std::string> children; mutable long total_weight; Program(std::string&& name, long weight, std::vector<std::string>&& children) : name(std::move(name)) , weight(weight) , children(std::move(children)) , total_weight(0) {} friend std::ostream& operator<<(std::ostream& out, const Program& p) { out << p.name << " " << p.weight; for (auto& child : p.children) out << " " << child; return out; } }; auto read_programs() { std::unordered_map<std::string, Program> programs; std::string line; while (getline(std::cin, line)) { static const std::regex leaf_re{R"(([a-z]+) \(([1-9][0-9]*)\))"}; static const std::regex inter_re{R"(([a-z]+) \(([1-9][0-9]*)\) -> (.+))"}; std::string name; long weight; std::vector<std::string> children; std::smatch matched; if (regex_match(line, matched, leaf_re)) { name = matched[1].str(); weight = strtol(matched[2].str().data(), nullptr, 10); } else if (regex_match(line, matched, inter_re)) { name = matched[1].str(); weight = strtol(matched[2].str().data(), nullptr, 10); std::stringstream ss(matched[3].str()); std::string child; while (ss >> child) { if (child.back() == ',') child.pop_back(); children.push_back(std::move(child)); } } else continue; std::string key(name); programs.emplace(std::piecewise_construct, forward_as_tuple(std::move(key)), forward_as_tuple(std::move(name), weight, std::move(children))); } return programs; } std::string root_program(const std::unordered_map<std::string, Program>& programs) { std::unordered_set<std::string> unique_programs; for (auto& p : programs) unique_programs.insert(p.first); for (auto& p : programs) for (auto& child : p.second.children) { auto it = unique_programs.find(child); if (it != unique_programs.end()) unique_programs.erase(it); } if (unique_programs.size() == 1) return *unique_programs.begin(); else return ""; } const Program& get_program(const std::string& root, const std::unordered_map<std::string, Program>& programs) { auto it = programs.find(root); return it->second; } long compute_total_weight(const std::string& root, std::unordered_map<std::string, Program>& programs) { auto& p = get_program(root, programs); auto children_weight = 0L; for (auto& child : p.children) children_weight += compute_total_weight(child, programs); p.total_weight = p.weight + children_weight; return p.total_weight; } long get_maj_weight(const std::vector<std::string>& children, const std::unordered_map<std::string, Program>& programs) { if (children.size() == 0) return 0; auto& child = get_program(children[0], programs); auto maj_weight = child.total_weight; size_t maj_count = 1; for (size_t i = 1; i < children.size(); ++i) { auto& child = get_program(children[i], programs); if (child.total_weight == maj_weight) { ++maj_count; } else { --maj_count; if (maj_count == 0) { maj_weight = child.total_weight; maj_count = 1; } } } return maj_weight; } bool children_have_same_total_weight(const Program& parent, const std::unordered_map<std::string, Program>& programs) { if (parent.children.size() == 0) return true; auto& child = get_program(parent.children[0], programs); auto needed_weight = child.total_weight; for (size_t i = 1; i < parent.children.size(); ++i) { auto& child = get_program(parent.children[i], programs); if (child.total_weight != needed_weight) return false; } return true; } long find_correct_weight(const Program& p, const std::unordered_map<std::string, Program>& programs, long needed_weight) { // one child has a total weight different from than of other children // because a node cannot hide wrong weights in his subtree // (it is guaranteed that only one node has wrong weight) if (p.children.size() > 2) { auto maj_weight = get_maj_weight(p.children, programs); for (const auto& c : p.children) { auto& child = get_program(c, programs); if (child.total_weight != maj_weight) return find_correct_weight(child, programs, maj_weight); } } else if (p.children.size() == 2) { auto& child1 = get_program(p.children[0], programs); auto& child2 = get_program(p.children[1], programs); if (child1.total_weight != child2.total_weight) { // which child has wrong total weight? ... check both if (!children_have_same_total_weight(child1, programs)) return find_correct_weight(child1, programs, child2.total_weight); if (!children_have_same_total_weight(child2, programs)) return find_correct_weight(child2, programs, child1.total_weight); auto child_correct_total_weight = (needed_weight - p.weight) / 2; if (child1.total_weight != child_correct_total_weight) { std::cout << child1.name << " has a wrong weight of " << child1.weight << "\n"; return child1.weight + (child_correct_total_weight - child1.total_weight); } else if (child2.total_weight != child_correct_total_weight) { std::cout << child2.name << " has a wrong weight of " << child2.weight << "\n"; return child2.weight + (child_correct_total_weight - child2.total_weight); } } } else if (p.children.size() == 1) { // ambiguous: who has a wrong weight? parent or child? ... assume parent } // no children or all children have the same total weight std::cout << p.name << " has a wrong weight of " << p.weight << "\n"; return p.weight + (needed_weight - p.total_weight); } int main() { auto programs = read_programs(); auto root = root_program(programs); std::cout << root << "\n"; compute_total_weight(root, programs); auto& p = get_program(root, programs); std::cout << find_correct_weight(p, programs, p.total_weight) << "\n"; return 0; }
30.779279
95
0.593151
[ "vector" ]
53e51811c7e0fadefd209e113159b44deee2256d
746
cpp
C++
src/state/PLCR.cpp
UmbrellaSampler/carnd-term3-1_path_planning
5d3828753b0ecde20aa4a7ba7d0ef16e21acdea7
[ "MIT" ]
null
null
null
src/state/PLCR.cpp
UmbrellaSampler/carnd-term3-1_path_planning
5d3828753b0ecde20aa4a7ba7d0ef16e21acdea7
[ "MIT" ]
null
null
null
src/state/PLCR.cpp
UmbrellaSampler/carnd-term3-1_path_planning
5d3828753b0ecde20aa4a7ba7d0ef16e21acdea7
[ "MIT" ]
null
null
null
// // Created by uwe_e on 03.02.2020. // #include "PLCR.h" #include "trajectory_tools.h" #include "KeepLane.h" #include "LCR.h" std::vector<std::unique_ptr<State>> PLCR::Next_States(std::shared_ptr<Model> model) { Append_Self_To_Last_Models(); std::vector<std::unique_ptr<State>> states; states.emplace_back(std::make_unique<KeepLane>(map_waypoints_, model, lane_, last_models_)); states.emplace_back(std::make_unique<PLCR>(map_waypoints_, model, lane_, last_models_)); states.emplace_back(std::make_unique<LCR>(map_waypoints_, model, lane_, last_models_)); return states; } double PLCR::Cost() const { return PLC::Cost(lane_ + 1); } std::string PLCR::Name() const { return "PLCR"; }
26.642857
97
0.686327
[ "vector", "model" ]
53e6dc4405b001d575ad54b93174a5ae6846be5a
5,329
cpp
C++
Code/BBearEditor/Engine/Lighting/GameObject/BBLight.cpp
lishangdian/BBearEditor-2.0
1f4b463ef756ed36cc15d10abae822efc400c4d7
[ "MIT" ]
1
2021-09-01T08:19:34.000Z
2021-09-01T08:19:34.000Z
Code/BBearEditor/Engine/Lighting/GameObject/BBLight.cpp
lishangdian/BBearEditor-2.0
1f4b463ef756ed36cc15d10abae822efc400c4d7
[ "MIT" ]
null
null
null
Code/BBearEditor/Engine/Lighting/GameObject/BBLight.cpp
lishangdian/BBearEditor-2.0
1f4b463ef756ed36cc15d10abae822efc400c4d7
[ "MIT" ]
null
null
null
#include "BBLight.h" #include "Utils/BBUtils.h" #include "3D/BBIcon.h" #include "Render/BBCamera.h" #include "3D/BBLightIndicator.h" #include "Render/BBRenderPass.h" BBLight::BBLight(BBScene *pScene) : BBLight(pScene, QVector3D(0, 0, 0), QVector3D(0, 0, 0), QVector3D(1, 1, 1)) { } BBLight::BBLight(BBScene *pScene, const QVector3D &position, const QVector3D &rotation, const QVector3D &scale) : BBGameObject(position, rotation, scale) { m_eType = Directional; m_pScene = pScene; // no need to rotate m_pIcon = new BBIcon(position, QVector3D(0, 0, 0), scale); // default setDiffuseColor(0.976f, 0.804f, 0.678f, 1.0f); setHomogeneousPosition(position, 1.0f); // m_Setting0[0] : there is a light m_Setting0[0] = 1.0f; // m_Setting0[1] : Intensity setIntensity(1.0f); } BBLight::~BBLight() { BB_SAFE_DELETE(m_pIcon); BB_SAFE_DELETE(m_pIndicator); } void BBLight::setPosition(const QVector3D &position, bool bUpdateLocalTransform) { BBGameObject::setPosition(position, bUpdateLocalTransform); m_pIcon->setPosition(position, bUpdateLocalTransform); m_pIndicator->setPosition(position, bUpdateLocalTransform); setHomogeneousPosition(position, 1.0f); } void BBLight::setRotation(int nAngle, const QVector3D &axis, bool bUpdateLocalTransform) { BBGameObject::setRotation(nAngle, axis, bUpdateLocalTransform); m_pIndicator->setRotation(nAngle, axis, bUpdateLocalTransform); } void BBLight::setRotation(const QVector3D &rotation, bool bUpdateLocalTransform) { BBGameObject::setRotation(rotation, bUpdateLocalTransform); m_pIndicator->setRotation(rotation, bUpdateLocalTransform); } void BBLight::setVisibility(bool bVisible) { BBGameObject::setVisibility(bVisible); m_pIndicator->setVisibility(bVisible); } void BBLight::init(const QString &path) { BBGameObject::init(path); m_pIcon->init(BB_PATH_RESOURCE_ICON() + path.split('.')[0] + " white.png"); m_pIndicator->init(); } void BBLight::render(BBCamera *pCamera) { // face camera QVector3D dir = pCamera->getPosition() - pCamera->getViewCenter(); QQuaternion rot = QQuaternion::fromDirection(dir, QVector3D(0, 1, 0)); m_pIcon->setRotation(rot, false); m_pIcon->render(pCamera); m_pIndicator->render(pCamera); } void BBLight::insertInRenderQueue(BBRenderQueue *pQueue) { m_pIcon->insertInRenderQueue(pQueue); m_pIndicator->insertInRenderQueue(pQueue); } void BBLight::removeFromRenderQueue(BBRenderQueue *pQueue) { m_pIcon->removeFromRenderQueue(pQueue); m_pIndicator->removeFromRenderQueue(pQueue); } bool BBLight::hit(const BBRay &ray, float &fDistance) { return m_pIcon->hit(ray, fDistance); } bool BBLight::belongToSelectionRegion(const BBFrustum &frustum) { return m_pIcon->belongToSelectionRegion(frustum); } void BBLight::setRenderPass(BBRenderPass *pRenderPass) { pRenderPass->setVector4(LOCATION_LIGHT_POSITION, m_HomogeneousPosition); pRenderPass->setVector4(LOCATION_LIGHT_COLOR, m_Diffuse); pRenderPass->setVector4(LOCATION_LIGHT_SETTINGS(0), m_Setting0); pRenderPass->setVector4(LOCATION_LIGHT_SETTINGS(1), m_Setting1); pRenderPass->setVector4(LOCATION_LIGHT_SETTINGS(2), m_Setting2); } BBCamera* BBLight::getLightSpaceCamera(int nLightPosX, int nLightPosZ) { // todo 透视投影 } void BBLight::setAmbientColor(float r, float g, float b, float a) { m_Ambient[0] = r; m_Ambient[1] = g; m_Ambient[2] = b; m_Ambient[3] = a; } void BBLight::setDiffuseColor(float r, float g, float b, float a) { m_Diffuse[0] = r; m_Diffuse[1] = g; m_Diffuse[2] = b; m_Diffuse[3] = a; } void BBLight::setSpecularColor(float r, float g, float b, float a) { m_Specular[0] = r; m_Specular[1] = g; m_Specular[2] = b; m_Specular[3] = a; } void BBLight::setSetting0(float x, float y, float z, float w) { m_Setting0[0] = x; m_Setting0[1] = y; m_Setting0[2] = z; m_Setting0[3] = w; } void BBLight::setSetting1(float x, float y, float z, float w) { m_Setting1[0] = x; m_Setting1[1] = y; m_Setting1[2] = z; m_Setting1[3] = w; } void BBLight::setSetting2(float x, float y, float z, float w) { m_Setting2[0] = x; m_Setting2[1] = y; m_Setting2[2] = z; m_Setting2[3] = w; } void BBLight::setHomogeneousPosition(const QVector3D &value, float w) { m_HomogeneousPosition[0] = value.x(); m_HomogeneousPosition[1] = value.y(); m_HomogeneousPosition[2] = value.z(); m_HomogeneousPosition[3] = w; } //void SpotLightIndicator::setSpotAngle(float angle) //{ // //angle是cutoff * 2 // float radius = tan(angle / 2 / 180 * 3.14); // for (int i = 0; i < 24; i++) // { // float c = radius * cosf(0.261799f * i); // float s = radius * sinf(0.261799f * i); // mVertexBuffer->setPosition(i, c, -1.0f, s); // } //} //void SpotLight::setSpotAngle(float angle) //{ // spotAngle = angle; // //指示器变换角度 // SpotLightIndicator *indicator = (SpotLightIndicator*)mIndicator; // indicator->setSpotAngle(angle); // mScene->updateSpotLightOption(); //} //void SpotLight::setLightDirection() //{ // //旋转矩阵 // QMatrix4x4 matrix; // matrix.rotate(mQuaternion); // //转化为方向向量 不旋转时方向默认向下 // lightDirection = matrix * QVector4D(0.0f, -1.0f, 0.0f, 1.0f); //}
25.620192
111
0.688497
[ "render", "3d" ]
53eb5f044e0a6b01d960d9a5e46d19ae10c4c865
593
hpp
C++
include/ball.hpp
core-exe/NonEuclideanRayTracing
4316fa118af6b29c86c99bd4d863dfba1f089c7c
[ "MIT" ]
1
2021-12-02T06:25:54.000Z
2021-12-02T06:25:54.000Z
include/ball.hpp
core-exe/NonEuclideanRayTracing
4316fa118af6b29c86c99bd4d863dfba1f089c7c
[ "MIT" ]
null
null
null
include/ball.hpp
core-exe/NonEuclideanRayTracing
4316fa118af6b29c86c99bd4d863dfba1f089c7c
[ "MIT" ]
null
null
null
# pragma once # include <vecmath.h> # include <functional> # include "object.hpp" using namespace std; class Ball: public Object3{ public: float rad, phi; Vector3f o, v1, v2, v3; function<bool(Vector3f)> pass; float minimal_dt = 3e-5; Ball(){} Ball( float _rad, Vector3f _o, Texture* _texture, Vector3f _v1 = Vector3f(1, 0, 0), Vector3f _v2 = Vector3f(0, 1, 0), function<bool(Vector3f)> _pass = [](Vector3f pos)->bool{return false;} ); ~Ball(){} bool intersect(Ray4 ray_in, float dt_max, Hit4& hit); };
22.807692
78
0.595278
[ "object" ]
53f54045ac53e09e453f7255cf9d82d968e3e9af
1,965
cpp
C++
SDKs/CryCode/3.8.1/CryEngine/CryAction/Network/ExplosiveObjectState.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
4
2017-12-18T20:10:16.000Z
2021-02-07T21:21:24.000Z
SDKs/CryCode/3.8.1/CryEngine/CryAction/Network/ExplosiveObjectState.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
null
null
null
SDKs/CryCode/3.8.1/CryEngine/CryAction/Network/ExplosiveObjectState.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
3
2019-03-11T21:36:15.000Z
2021-02-07T21:21:26.000Z
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2007. ------------------------------------------------------------------------- $Id$ $DateTime$ Description: network breakability: state of an object pre-explosion ------------------------------------------------------------------------- History: - 22/01/2007 10:34 : Created by Craig Tiller *************************************************************************/ #include "StdAfx.h" #include "ExplosiveObjectState.h" #include "ObjectSelector.h" #include "DebugBreakage.h" #include "CryAction.h" #include "GameContext.h" void SDeclareExplosiveObjectState::SerializeWith( TSerialize ser ) { LOGBREAK("SDeclareExplosiveObjectState: %s", ser.IsReading() ? "Reading:" : "Writing"); ser.Value("breakId", breakId, 'brId'); ser.Value("isEnt", isEnt); if (isEnt) { if (ser.IsWriting()) CRY_ASSERT(CCryAction::GetCryAction()->GetGameContext()->GetNetContext()->IsBound(entId)); ser.Value("entid", entId, 'eid'); ser.Value("entpos", entPos); ser.Value("entrot", entRot); ser.Value("entscale", entScale); } else { ser.Value("eventPos", eventPos); ser.Value("hash", hash); } } bool ExplosiveObjectStateFromPhysicalEntity( SExplosiveObjectState& s, IPhysicalEntity * pPEnt) { bool ok = false; switch (pPEnt->GetiForeignData()) { case PHYS_FOREIGN_ID_ENTITY: if (IEntity * pEnt = (IEntity *) pPEnt->GetForeignData(PHYS_FOREIGN_ID_ENTITY)) { s.isEnt = true; s.entId = pEnt->GetId(); s.entPos = pEnt->GetWorldPos(); s.entRot = pEnt->GetWorldRotation(); s.entScale = pEnt->GetScale(); ok = true; } break; case PHYS_FOREIGN_ID_STATIC: if (IRenderNode * rn = (IRenderNode*)pPEnt->GetForeignData(PHYS_FOREIGN_ID_STATIC)) { s.isEnt = false; s.eventPos = rn->GetBBox().GetCenter(); s.hash = CObjectSelector::CalculateHash(rn); ok = true; } break; } return ok; }
28.071429
95
0.587786
[ "object" ]
53f7f5448e1f2ebab0a64a29ae2bb3d4a8ab26fc
11,371
hpp
C++
graphblas/backend/cuda/sparse_vector.hpp
BenBrock/graphblast
c4909e115740e94ab65458a7e1177cbc76b1828d
[ "Apache-2.0" ]
155
2019-01-19T12:15:12.000Z
2022-03-21T02:59:03.000Z
graphblas/backend/cuda/sparse_vector.hpp
BenBrock/graphblast
c4909e115740e94ab65458a7e1177cbc76b1828d
[ "Apache-2.0" ]
16
2019-05-02T19:29:57.000Z
2021-06-30T07:22:57.000Z
graphblas/backend/cuda/sparse_vector.hpp
BenBrock/graphblast
c4909e115740e94ab65458a7e1177cbc76b1828d
[ "Apache-2.0" ]
20
2019-06-10T17:36:41.000Z
2022-03-23T19:48:26.000Z
#ifndef GRAPHBLAS_BACKEND_CUDA_SPARSE_VECTOR_HPP_ #define GRAPHBLAS_BACKEND_CUDA_SPARSE_VECTOR_HPP_ #include <cuda.h> #include <cuda_runtime.h> #include <vector> #include <iostream> #include <unordered_set> #include <algorithm> #include "graphblas/types.hpp" #include "graphblas/util.hpp" namespace graphblas { namespace backend { template <typename T> class DenseVector; template <typename T> class SparseVector { public: SparseVector() : nsize_(0), nvals_(0), h_ind_(NULL), h_val_(NULL), d_ind_(NULL), d_val_(NULL), need_update_(0) {} explicit SparseVector(Index nsize) : nsize_(nsize), nvals_(0), h_ind_(NULL), h_val_(NULL), d_ind_(NULL), d_val_(NULL), need_update_(0) { allocate(); } // Need to write Default Destructor ~SparseVector(); // C API Methods Info nnew(Index nsize); Info dup(const SparseVector* rhs); Info clear(); inline Info size(Index* nsize_t) const; inline Info nvals(Index* nvals_t) const; template <typename BinaryOpT> Info build(const std::vector<Index>* indices, const std::vector<T>* values, Index nvals, BinaryOpT dup); Info build(const std::vector<T>* values, Index nvals); Info build(Index* indices, T* values, Index nvals); Info setElement(T val, Index index); Info extractElement(T* val, Index index); Info extractTuples(std::vector<Index>* indices, std::vector<T>* values, Index* n); // handy methods const T& operator[](Index ind); Info resize(Index nsize); Info fill(Index vals); Info print(bool force_update = false); Info countUnique(Index* count); Info allocateCpu(); Info allocateGpu(); Info allocate(); Info cpuToGpu(); Info gpuToCpu(bool force_update = false); Info swap(SparseVector* rhs); private: Index nsize_; // 5 ways to set: (1) Vector (2) nnew (3) dup (4) resize // (5) allocate Index nvals_; // 4 ways to set: (1) Vector (2) dup (3) build (4) resize Index* h_ind_; T* h_val_; Index* d_ind_; T* d_val_; bool need_update_; // set to true by changing SparseVector // set to false by gpuToCpu() }; template <typename T> SparseVector<T>::~SparseVector() { if (h_ind_ != NULL) free(h_ind_); if (h_val_ != NULL) free(h_val_); if (d_ind_ != NULL) CUDA_CALL(cudaFree(d_ind_)); if (d_ind_ != NULL) CUDA_CALL(cudaFree(d_val_)); } template <typename T> Info SparseVector<T>::nnew(Index nsize) { nsize_ = nsize; CHECK(allocate()); return GrB_SUCCESS; } template <typename T> Info SparseVector<T>::dup(const SparseVector* rhs) { nvals_ = rhs->nvals_; nsize_ = rhs->nsize_; if (d_ind_ == NULL && h_ind_ == NULL && d_val_ == NULL && h_val_ == NULL) CHECK(allocate()); CUDA_CALL(cudaMemcpy(d_ind_, rhs->d_ind_, nsize_*sizeof(Index), cudaMemcpyDeviceToDevice)); CUDA_CALL(cudaMemcpy(d_val_, rhs->d_val_, nsize_*sizeof(T), cudaMemcpyDeviceToDevice)); need_update_ = true; return GrB_SUCCESS; } template <typename T> Info SparseVector<T>::clear() { nvals_ = 0; return GrB_SUCCESS; } template <typename T> inline Info SparseVector<T>::size(Index* nsize_t) const { *nsize_t = nsize_; return GrB_SUCCESS; } template <typename T> inline Info SparseVector<T>::nvals(Index* nvals_t) const { *nvals_t = nvals_; return GrB_SUCCESS; } template <typename T> template <typename BinaryOpT> Info SparseVector<T>::build(const std::vector<Index>* indices, const std::vector<T>* values, Index nvals, BinaryOpT dup) { if (nvals > nsize_) { std::cout << "SpVec Build with indices greater than nsize_\n"; std::cout << "Error: Feature not implemented yet!\n"; return GrB_PANIC; } if (nvals_ > 0) return GrB_OUTPUT_NOT_EMPTY; if (h_ind_ == NULL || h_val_ == NULL || d_ind_ == NULL || d_val_ == NULL) { std::cout << "Error: SpVec Uninitialized object!\n"; return GrB_UNINITIALIZED_OBJECT; } nvals_ = nvals; for (Index i = 0; i < nvals; i++) { h_ind_[i] = (*indices)[i]; h_val_[i] = (*values) [i]; } CHECK(cpuToGpu()); return GrB_SUCCESS; } template <typename T> Info SparseVector<T>::build(const std::vector<T>* values, Index nvals) { std::cout << "Sparse Build with dense input\n"; std::cout << "Error: Feature not implemented yet!\n"; return GrB_SUCCESS; } template <typename T> Info SparseVector<T>::build(Index* indices, T* values, Index nvals) { d_ind_ = indices; d_val_ = values; nvals_ = nvals; need_update_ = true; CHECK(allocateCpu()); return GrB_SUCCESS; } template <typename T> Info SparseVector<T>::setElement(T val, Index index) { CHECK(gpuToCpu()); h_ind_[nvals_] = index; h_val_[nvals_] = val; nvals_++; CHECK(cpuToGpu()); return GrB_SUCCESS; } template <typename T> Info SparseVector<T>::extractElement(T* val, Index index) { return GrB_SUCCESS; } template <typename T> Info SparseVector<T>::extractTuples(std::vector<Index>* indices, std::vector<T>* values, Index* n) { CHECK(gpuToCpu()); indices->clear(); values->clear(); if (*n > nvals_) { std::cout << *n << " > " << nvals_ << std::endl; std::cout << "Error: *n > nvals!\n"; return GrB_UNINITIALIZED_OBJECT; } else if (*n < nvals_) { std::cout << *n << " < " << nvals_ << std::endl; std::cout << "Error: *n < nvals!\n"; return GrB_INSUFFICIENT_SPACE; } for (Index i = 0; i < *n; i++) { indices->push_back(h_ind_[i]); values->push_back(h_val_[i]); } return GrB_SUCCESS; } // If ind is found, then return the value at that ind // Else if ind is not found, return 0 of type T template <typename T> const T& SparseVector<T>::operator[](Index ind) { gpuToCpu(); if (ind >= nvals_) std::cout << "Error: Spvec Index out of bounds!\n"; for (Index i = 0; i < nvals_; i++) if (h_ind_[i] == ind) return h_val_[i]; return T(0); } // Clears and reallocates from nsize_ x 1 to nsize x 1 template <typename T> Info SparseVector<T>::resize(Index nsize) { Index* h_temp_ind = h_ind_; T* h_temp_val = h_val_; Index* d_temp_ind = d_ind_; T* d_temp_val = d_val_; // Compute how much to copy Index to_copy = min(nsize, nvals_); nsize_ = nsize; h_ind_ = reinterpret_cast<Index*>(malloc( nsize_*sizeof(Index))); h_val_ = reinterpret_cast<T*>(malloc( (nsize_+1)*sizeof(T))); if (h_temp_ind != NULL) memcpy(h_ind_, h_temp_ind, to_copy*sizeof(Index)); if (h_temp_val != NULL) memcpy(h_val_, h_temp_val, to_copy*sizeof(T)); CUDA_CALL(cudaMalloc(&d_ind_, nsize_*sizeof(Index))); CUDA_CALL(cudaMalloc(&d_val_, (nsize_+1)*sizeof(T))); printMemory("SpVec"); if (d_temp_ind != NULL) CUDA_CALL(cudaMemcpy(d_ind_, d_temp_ind, to_copy*sizeof(Index), cudaMemcpyDeviceToDevice)); if (d_temp_val != NULL) CUDA_CALL(cudaMemcpy(d_val_, d_temp_val, to_copy*sizeof(T), cudaMemcpyDeviceToDevice)); nvals_ = to_copy; free(h_temp_ind); free(h_temp_val); CUDA_CALL(cudaFree(d_temp_ind)); CUDA_CALL(cudaFree(d_temp_val)); return GrB_SUCCESS; } template <typename T> Info SparseVector<T>::fill(Index nvals) { for (Index i = 0; i < nvals; i++) h_val_[i] = i; CHECK(cpuToGpu()); return GrB_SUCCESS; } template <typename T> Info SparseVector<T>::print(bool force_update) { CUDA_CALL(cudaDeviceSynchronize()); CHECK(gpuToCpu(force_update)); printArray("ind", h_ind_, std::min(nvals_, 40)); printArray("val", h_val_, std::min(nvals_, 40)); if (nvals_ == 0) std::cout << "Error: SparseVector is empty!\n"; return GrB_SUCCESS; } // Count number of unique numbers template <typename T> Info SparseVector<T>::countUnique(Index* count) { CHECK(gpuToCpu()); std::unordered_set<Index> unique; for (Index block = 0; block < nvals_; block++) { if (unique.find(h_val_[block]) == unique.end()) { unique.insert(h_val_[block]); } } *count = unique.size(); return GrB_SUCCESS; } template <typename T> Info SparseVector<T>::allocateCpu() { // Host malloc if (nsize_ != 0 && h_ind_ == NULL && h_val_ == NULL) { h_ind_ = reinterpret_cast<Index*>(malloc(nsize_*sizeof(Index))); h_val_ = reinterpret_cast<T*>(malloc((nsize_+1)*sizeof(T))); } else { // std::cout << "Error: SpVec Host allocation unsuccessful!\n"; } if (nsize_ != 0 && (h_ind_ == NULL || h_val_ == NULL)) { std::cout << "Error: SpVec Out of memory!\n"; // return GrB_OUT_OF_MEMORY; } return GrB_SUCCESS; } template <typename T> Info SparseVector<T>::allocateGpu() { // GPU malloc if (nsize_ != 0 && d_ind_ == NULL && d_val_ == NULL) { CUDA_CALL(cudaMalloc(&d_ind_, nsize_*sizeof(Index))); CUDA_CALL(cudaMalloc(&d_val_, (nsize_+1)*sizeof(T))); printMemory("d_ind, d_val"); } else { // std::cout << "Error: SpVec Device allocation unsuccessful!\n"; } if (nsize_ != 0 && (d_ind_ == NULL || d_val_ == NULL)) { std::cout << "Error: SpVec Out of memory!\n"; // return GrB_OUT_OF_MEMORY; } return GrB_SUCCESS; } // Allocate just enough (different from CPU impl since kcap_ratio=1.) template <typename T> Info SparseVector<T>::allocate() { CHECK(allocateCpu()); CHECK(allocateGpu()); return GrB_SUCCESS; } // Copies graph to GPU template <typename T> Info SparseVector<T>::cpuToGpu() { CUDA_CALL(cudaMemcpy(d_ind_, h_ind_, nvals_*sizeof(Index), cudaMemcpyHostToDevice)); CUDA_CALL(cudaMemcpy(d_val_, h_val_, nvals_*sizeof(T), cudaMemcpyHostToDevice)); return GrB_SUCCESS; } // Copies graph to CPU template <typename T> Info SparseVector<T>::gpuToCpu(bool force_update) { if (need_update_ || force_update) { CUDA_CALL(cudaMemcpy(h_ind_, d_ind_, nvals_*sizeof(Index), cudaMemcpyDeviceToHost)); CUDA_CALL(cudaMemcpy(h_val_, d_val_, nvals_*sizeof(T), cudaMemcpyDeviceToHost)); } need_update_ = false; return GrB_SUCCESS; } template <typename T> Info SparseVector<T>::swap(SparseVector* rhs) { // NOLINT(build/include_what_you_use) // Change member scalars Index temp_nsize = nsize_; Index temp_nvals = nvals_; nsize_ = rhs->nsize_; nvals_ = rhs->nvals_; rhs->nsize_ = temp_nsize; rhs->nvals_ = temp_nvals; // Change CPU pointers Index* temp_ind_ = h_ind_; T* temp_val_ = h_val_; h_ind_ = rhs->h_ind_; h_val_ = rhs->h_val_; rhs->h_ind_ = temp_ind_; rhs->h_val_ = temp_val_; // Change GPU pointers temp_ind_ = d_ind_; temp_val_ = d_val_; d_ind_ = rhs->d_ind_; d_val_ = rhs->d_val_; rhs->d_ind_ = temp_ind_; rhs->d_val_ = temp_val_; bool temp_update = need_update_; need_update_ = rhs->need_update_; rhs->need_update_ = temp_update; return GrB_SUCCESS; } } // namespace backend } // namespace graphblas #endif // GRAPHBLAS_BACKEND_CUDA_SPARSE_VECTOR_HPP_
27.203349
86
0.628265
[ "object", "vector" ]
d87eebcadf3dd9be67e057d7a64bf59749aeaa76
2,525
cpp
C++
beta versions/MultiplicadorMatrices.cpp
tec-csf/tc2017-pf-primavera-2020-equipo-4-1
111f53acb1c7f3e0bebd112ed0bdda9ab0df5174
[ "MIT" ]
null
null
null
beta versions/MultiplicadorMatrices.cpp
tec-csf/tc2017-pf-primavera-2020-equipo-4-1
111f53acb1c7f3e0bebd112ed0bdda9ab0df5174
[ "MIT" ]
null
null
null
beta versions/MultiplicadorMatrices.cpp
tec-csf/tc2017-pf-primavera-2020-equipo-4-1
111f53acb1c7f3e0bebd112ed0bdda9ab0df5174
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <time.h> #include <omp.h> #include <limits.h> #include <math.h> #include <unistd.h> #define NCORES 3 using namespace std; /* En memoria de: * vector<tuple<vector<vector<int>>,int>> */ vector<vector<vector<int>>> list; vector<vector<int>> generarMatriz(int n, int m) { vector<vector<int>> vec(n, vector<int> (m,0)); cout<<"***filas: "<<vec.size()<<"\tcolumnas: "<<vec[0].size()<<endl; for (int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { vec[i][j] = rand() % 9; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++){ cout<< vec[i][j]<< " "; } cout<< "\n"; } cout<< "\n"; return vec; } void multiplicar(vector<vector<int>> A, vector<vector<int>> B) { vector<vector<int>> C(A.size(), vector<int> (B[0].size(),0)); omp_set_num_threads(NCORES); #pragma omp parallel for for(int i=0; i<A.size(); i++) { printf("hilo: %d\n", omp_get_thread_num()); for(int j=0; j<B[0].size(); j++) { for(int k=0; k<A[0].size(); k++) { C[i][j]+=A[i][k]*B[k][j]; } } } for (int i = 0; i < C.size(); i++) { for (int j = 0; j < C[0].size(); j++){ cout<< C[i][j]<< " "; } cout<< "\n"; } } void emparejar() { bool flag = true; for(int i = 0; i < list.size()-1; i++) { cout<<list[i][0].size()<<" X "<<list.back().size()<<endl; if (list[i][0].size()==list.back().size()) { if(list.size()>1) { cout<<"La primera y última matriz de la cola son compatibles"<<endl; multiplicar(list[i], list.back()); cout<<"multiplicó"<<endl; list.erase(list.begin()+i); list.pop_back(); cout<<"eliminó"<<endl; flag = false; break; } } else if (flag) { cout<<"NO hay matrices compatibles"<<endl; } } cout<<"COLA: "<<list.size()<<endl<<endl; } int main() { //deque<vector<vector<int>>> list; srand(time(NULL)); for(int i = 0; i < 100; i++) { list.push_back(generarMatriz(rand() % 8 + 2,(rand() % 8 + 2))); emparejar(); } return 0; }
24.047619
85
0.423762
[ "vector" ]
d88b2c6630b7400850e59aca5230bbbeb828efcb
5,218
hpp
C++
OpenNI2-FreenectDriver/src/ColorStream.hpp
boehm-e/kinect_led
d14ca53b3c3a26f9c8f47a557f5c97973519fd47
[ "Apache-2.0" ]
10
2020-03-09T02:31:01.000Z
2021-12-14T18:29:27.000Z
OpenNI2-FreenectDriver/src/ColorStream.hpp
boehm-e/kinect_led
d14ca53b3c3a26f9c8f47a557f5c97973519fd47
[ "Apache-2.0" ]
null
null
null
OpenNI2-FreenectDriver/src/ColorStream.hpp
boehm-e/kinect_led
d14ca53b3c3a26f9c8f47a557f5c97973519fd47
[ "Apache-2.0" ]
1
2018-06-23T04:58:30.000Z
2018-06-23T04:58:30.000Z
#pragma once #include <algorithm> // for transform() #include <cmath> // for M_PI #include "libfreenect.hpp" #include "Driver/OniDriverAPI.h" #include "VideoStream.hpp" namespace FreenectDriver { class ColorStream : public VideoStream { public: static constexpr OniSensorType SENSOR_TYPE = ONI_SENSOR_COLOR; // from NUI library & converted to radians static constexpr float DIAGONAL_FOV = 73.9 * (M_PI / 180); static constexpr float HORIZONTAL_FOV = 62 * (M_PI / 180); static constexpr float VERTICAL_FOV = 48.6 * (M_PI / 180); private: typedef std::map< OniVideoMode, std::pair<freenect_video_format, freenect_resolution> > FreenectVideoModeMap; static FreenectVideoModeMap getSupportedVideoModes(); OniStatus setVideoMode(OniVideoMode requested_mode); void populateFrame(void* data, OniFrame* frame) const; bool auto_white_balance; bool auto_exposure; public: ColorStream(Freenect::FreenectDevice* pDevice); //~ColorStream() { } static OniSensorInfo getSensorInfo() { FreenectVideoModeMap supported_modes = getSupportedVideoModes(); OniVideoMode* modes = new OniVideoMode[supported_modes.size()]; std::transform(supported_modes.begin(), supported_modes.end(), modes, ExtractKey()); OniSensorInfo sensors = { SENSOR_TYPE, static_cast<int>(supported_modes.size()), modes }; return sensors; } // from StreamBase OniBool isPropertySupported(int propertyId) { switch(propertyId) { default: return VideoStream::isPropertySupported(propertyId); case ONI_STREAM_PROPERTY_HORIZONTAL_FOV: case ONI_STREAM_PROPERTY_VERTICAL_FOV: case ONI_STREAM_PROPERTY_AUTO_WHITE_BALANCE: case ONI_STREAM_PROPERTY_AUTO_EXPOSURE: return true; } } OniStatus getProperty(int propertyId, void* data, int* pDataSize) { switch (propertyId) { default: return VideoStream::getProperty(propertyId, data, pDataSize); case ONI_STREAM_PROPERTY_HORIZONTAL_FOV: // float (radians) { if (*pDataSize != sizeof(float)) { LogError("Unexpected size for ONI_STREAM_PROPERTY_HORIZONTAL_FOV"); return ONI_STATUS_ERROR; } *(static_cast<float*>(data)) = HORIZONTAL_FOV; return ONI_STATUS_OK; } case ONI_STREAM_PROPERTY_VERTICAL_FOV: // float (radians) { if (*pDataSize != sizeof(float)) { LogError("Unexpected size for ONI_STREAM_PROPERTY_VERTICAL_FOV"); return ONI_STATUS_ERROR; } *(static_cast<float*>(data)) = VERTICAL_FOV; return ONI_STATUS_OK; } // camera case ONI_STREAM_PROPERTY_AUTO_WHITE_BALANCE: // OniBool { if (*pDataSize != sizeof(OniBool)) { LogError("Unexpected size for ONI_STREAM_PROPERTY_AUTO_WHITE_BALANCE"); return ONI_STATUS_ERROR; } *(static_cast<OniBool*>(data)) = auto_white_balance; return ONI_STATUS_OK; } case ONI_STREAM_PROPERTY_AUTO_EXPOSURE: // OniBool { if (*pDataSize != sizeof(OniBool)) { LogError("Unexpected size for ONI_STREAM_PROPERTY_AUTO_EXPOSURE"); return ONI_STATUS_ERROR; } *(static_cast<OniBool*>(data)) = auto_exposure; return ONI_STATUS_OK; } } } OniStatus setProperty(int propertyId, const void* data, int dataSize) { switch (propertyId) { default: return VideoStream::setProperty(propertyId, data, dataSize); // camera case ONI_STREAM_PROPERTY_AUTO_WHITE_BALANCE: // OniBool { if (dataSize != sizeof(OniBool)) { LogError("Unexpected size for ONI_STREAM_PROPERTY_AUTO_WHITE_BALANCE"); return ONI_STATUS_ERROR; } auto_white_balance = *(static_cast<const OniBool*>(data)); int ret = device->setFlag(FREENECT_AUTO_WHITE_BALANCE, auto_white_balance); return (ret == 0) ? ONI_STATUS_OK : ONI_STATUS_ERROR; } case ONI_STREAM_PROPERTY_AUTO_EXPOSURE: // OniBool { if (dataSize != sizeof(OniBool)) { LogError("Unexpected size for ONI_STREAM_PROPERTY_AUTO_EXPOSURE"); return ONI_STATUS_ERROR; } auto_exposure = *(static_cast<const OniBool*>(data)); int ret = device->setFlag(FREENECT_AUTO_WHITE_BALANCE, auto_exposure); return (ret == 0) ? ONI_STATUS_OK : ONI_STATUS_ERROR; } case ONI_STREAM_PROPERTY_MIRRORING: // OniBool { if (dataSize != sizeof(OniBool)) { LogError("Unexpected size for ONI_STREAM_PROPERTY_MIRRORING"); return ONI_STATUS_ERROR; } mirroring = *(static_cast<const OniBool*>(data)); int ret = device->setFlag(FREENECT_MIRROR_VIDEO, mirroring); return (ret == 0) ? ONI_STATUS_OK : ONI_STATUS_ERROR; } } } }; }
33.235669
113
0.623419
[ "transform" ]
d890078196762d2cbc447f121602b16cb5832800
5,502
cpp
C++
calib/main/main.cpp
Yihua-Ni/Tools
b40c24b0b2a7025f13182fc5ed5bfcf63b389585
[ "MIT" ]
null
null
null
calib/main/main.cpp
Yihua-Ni/Tools
b40c24b0b2a7025f13182fc5ed5bfcf63b389585
[ "MIT" ]
null
null
null
calib/main/main.cpp
Yihua-Ni/Tools
b40c24b0b2a7025f13182fc5ed5bfcf63b389585
[ "MIT" ]
null
null
null
#include "InitParam/params_init.h" #include "calib/calib.h" #include <iostream> #include <vector> #include <string> int main() { /*1 参数初始化*/ std::string configFile = "/home/minieye/桌面/calib/parameter/vls128.txt" ; INIT init(configFile); std::cout << "参数配置文件输入完成!" << std::endl; /*2 载入标定用图片*/ std::vector<std::string> img_files; init.GetFile(init.srcImg_path, img_files); std::cout << "载入标定用图片:" << img_files.size() << std::endl; for(int i = 0; i < (int)img_files.size(); i++){ //验证文件顺序是否正确 std::cout << img_files[i] << std::endl; } /*3 载入标定用点云数据*/ std::vector<std::string> csv_files; init.GetFile(init.srclidarPoints_path, csv_files); std::cout << "载入标定用点云数据:" << csv_files.size() << std::endl; /*4 图像 点云数据匹配*/ init.FileMatch(init.log_txt_path, img_files, csv_files); CALIB calib; /* 5 循环读取图像和点云数据,并提取对应特征 */ int success_(0), fail_(0); //用来记录图像和激光点云对应特征提取成功的帧数 for(int i = 0; i < (int)img_files.size(); i++) { /* 5.1读取图像文件 */ cv::Mat img = calib.ReadImg(img_files[i], init.srcImg_path); /* 5.2读取csv文件 */ pcl::PointCloud<PointXYZIR>::Ptr laserCloudIn = calib.ReadCsv(init.srclidarPoints_path, init.need_csv_files[i]) ; // std::cout << "读入点云数据" << std::endl; // calib.visualize_pcd(laserCloudIn); // 查看录入的点云数据 /* 5.3图像特征提取 */ std::vector<cv::Point2f> img_board_coenerAndCenter = calib.GetImgFeature(img, init.grid_size, init.square_length, init.board_dimension, init.cameramat, init.distcoeff); /* 5.4点云特征提取 */ //calib.GetLidarFeature(laserCloudIn, init.x_range_point_filter, init.y_range_point_filter, init.z_range_point_filter, init.plane_line_dist_threshold, init.lidar_ring_count, init.line_fit2real_dist); //std::cout << calib.all_lidar_board_coenerAndCenter.size() <<std::endl; //std::cout << calib.all_img_board_coenerAndCenter.size() <<std::endl; if(!img_board_coenerAndCenter.empty()) { if(calib.GetLidarFeature(laserCloudIn, init.x_range_point_filter, init.y_range_point_filter, init.z_range_point_filter, init.plane_line_dist_threshold, init.lidar_ring_count, init.line_fit2real_dist)) { std::cout << img_files[i] << " 和 " << init.need_csv_files[i] << "对应特征提取成功!" << std::endl; success_ ++; calib.all_img_board_coenerAndCenter.insert(calib.all_img_board_coenerAndCenter.end(), img_board_coenerAndCenter.begin(), img_board_coenerAndCenter.end()); calib.all_lidar_board_coenerAndCenter.insert(calib.all_lidar_board_coenerAndCenter.end(), calib.lidar_board_coenerAndCenter.begin(), calib.lidar_board_coenerAndCenter.end()); for(int i = 0; i < calib.lidar_board_coenerAndCenter.size() ; i ++) { std::cout << calib.lidar_board_coenerAndCenter[i] << std::endl; } std::cout << "img_board_coenerAndCenter size: " << img_board_coenerAndCenter.size() << std::endl; std::cout << "lidar_board_coenerAndCenter size: " << calib.lidar_board_coenerAndCenter.size() << std::endl; img_board_coenerAndCenter.clear(); //清空数据,等待下一组数据的录入 calib.lidar_board_coenerAndCenter.clear(); //清空数据,等待下一组数据的录入 } else { std::cout << img_files[i] << " 和 " << init.need_csv_files[i] << "对应特征提取失败!" << endl; fail_++; img_board_coenerAndCenter.clear(); //清空数据,等待下一组数据的录入 calib.lidar_board_coenerAndCenter.clear(); //清空数据,等待下一组数据的录入 continue; } } }; std::cout << "用于对应特征提取的图像和点云组数为:" << success_ + fail_ << std::endl; std::cout << "图像和激光点云对应特征提取成功组数:" << success_ << std::endl; std::cout << "图像和激光点云对应特征提取失败组数:" << fail_ << std::endl; /* 6 求解camera和lidar的外参 */ std::cout << "all_lidar_board_coenerAndCenter size:" << calib.all_lidar_board_coenerAndCenter.size() <<std::endl; std::cout << "all_img_board_coenerAndCenter size " << calib.all_img_board_coenerAndCenter.size() <<std::endl; cv::solvePnP(calib.all_lidar_board_coenerAndCenter, calib.all_img_board_coenerAndCenter, init.cameramat, init.distcoeff, calib.R_camToLidar, calib.T_camToLidar, false, cv::SOLVEPNP_EPNP); // pnp模型求R,T cv::solvePnP(calib.all_lidar_board_coenerAndCenter, calib.all_img_board_coenerAndCenter, init.cameramat, init.distcoeff, calib.R_camToLidar, calib.T_camToLidar, true, cv::SOLVEPNP_ITERATIVE); // pnp模型求R,T cv::Mat r; cv::Rodrigues(calib.R_camToLidar, r); // R 为旋转向量形式,用 Rodrigues 公式转换为矩阵 std::cout << "lidar 到 camera 的外参 R:" << std::endl << calib.R_camToLidar << std::endl; std::cout << "lidar 到 camera 的外参 T:" << std::endl << calib.T_camToLidar << std::endl; /*7 camera-lidar外参标定结果保留 */ ofstream fout((init.calibration_result_path + "camera_lidar_calibration_result.txt").c_str(), ios::out | ios::trunc); fout << calib.R_camToLidar << std::endl; fout << calib.T_camToLidar << std::endl; std::cout << "calib.chessBoard_lidar_points size:" << calib.chessBoard_lidar_points.size() << std::endl; std::cout << "img_files size:" << img_files.size() <<std::endl; /*8 将标定板点云按照对应关系映射到图像上*/ calib.Project3DPoints(calib.chessBoard_lidar_points, calib.R_camToLidar, calib.T_camToLidar, init.srcImg_path, init.cameramat, init.distcoeff, img_files, init.img_projection_path); return 1; }
48.690265
212
0.658306
[ "vector" ]
d893612994cef411d803f681e21682f867ac0cbd
1,199
cpp
C++
src/Tile.cpp
ScaredStorm/SpaceGame
136df0e173b07ebc3f6a0b7c2370edeb7c120af8
[ "MIT" ]
null
null
null
src/Tile.cpp
ScaredStorm/SpaceGame
136df0e173b07ebc3f6a0b7c2370edeb7c120af8
[ "MIT" ]
null
null
null
src/Tile.cpp
ScaredStorm/SpaceGame
136df0e173b07ebc3f6a0b7c2370edeb7c120af8
[ "MIT" ]
null
null
null
#include "Tile.h" Tile::Tile(Vector2 position, TileType type) : _position(position.x, position.y) { _col.r = 255; _col.g = 255; _col.b = 255; _col.a = 255; _type = type; } Tile::Tile(int x, int y, TileType type) : _position(Vector2(x, y)) { _col.r = 255; _col.g = 255; _col.b = 255; _col.a = 255; _type = type; } Tile::Tile(int x, int y, SDL_Color color, TileType type) : _position(Vector2(x, y)) { _col = color; _type = type; } Tile::~Tile() { } void Tile::setColor(SDL_Color color) { _col = color; } void Tile::setColor(Uint8 r, Uint8 g, Uint8 b) { _col.r = r; _col.g = g; _col.b = b; _col.a = 255; } void Tile::setType(TileType type) { _type = type; } void Tile::render(TextureManager &manager, SDL_Renderer *renderer, Camera &camera) { Vector2 calculatedPos = Vector2(_position.x - camera.getX(), _position.y - camera.getY()); if(_type == TYPE_NORMAL) { manager.renderTexture("Tile", calculatedPos, Vector2(64, 32), renderer); //manager.renderTextureColor("Tile", calculatedPos, Vector2(64, 32), renderer, {255,0,255,255}); } }
16.652778
105
0.585488
[ "render" ]
d89cb28acb0271f4a0e6500601a7f7286cf7b6f7
4,283
cc
C++
C++/diTauMLMassInterface.cc
lucastorterotot/DiTau_ML_mass
7870a9184a5b6595b3985ad78f114a0e8a9023cc
[ "MIT" ]
null
null
null
C++/diTauMLMassInterface.cc
lucastorterotot/DiTau_ML_mass
7870a9184a5b6595b3985ad78f114a0e8a9023cc
[ "MIT" ]
null
null
null
C++/diTauMLMassInterface.cc
lucastorterotot/DiTau_ML_mass
7870a9184a5b6595b3985ad78f114a0e8a9023cc
[ "MIT" ]
null
null
null
/*### --- C++ interface to DiTau_ML_mass --- https://github.com/lucastorterotot/DiTau_ML_mass --- Davide Zuolo (University and INFN Milano - Bicocca) --- March 2021 ###*/ #include "../interface/diTauMLMassInterface.h" namespace ditauMLMass { diTauMLMass::diTauMLMass(const std::string & model) { nn_desc.graph.reset(tensorflow::loadMetaGraph(model)); nn_desc.session = tensorflow::createSession(nn_desc.graph.get(), model); nn_desc.input_layer = "serving_default_dense_1_input:0"; nn_desc.output_layer = "StatefulPartitionedCall:0"; } float diTauMLMass::GetScore(const double tau1_pt_reco, const double tau1_eta_reco, const double tau1_phi_reco, const double tau2_pt_reco, const double tau2_eta_reco, const double tau2_phi_reco, const double jet1_pt_reco, const double jet1_eta_reco, const double jet1_phi_reco, const double jet2_pt_reco, const double jet2_eta_reco, const double jet2_phi_reco, const double remaining_jets_pt_reco, const double remaining_jets_eta_reco, const double remaining_jets_phi_reco, const int remaining_jets_N_reco, const double MET_pt_reco, const double MET_phi_reco, const double MET_covXX_reco, const double MET_covXY_reco, const double MET_covYY_reco, const double mT1_reco, const double mT2_reco, const double mTtt_reco, const double mTtot_reco, const int PU_npvsGood_reco, const int N_neutrinos_reco ) { tensorflow::Tensor x(tensorflow::DT_FLOAT, tensorflow::TensorShape{1, diTauMLMass::n_variables}); x.flat<float>().setZero(); x.tensor<float, 2>()(0, InputVars::vars::tau1_pt_reco) = tau1_pt_reco; x.tensor<float, 2>()(0, InputVars::vars::tau1_eta_reco) = tau1_eta_reco; x.tensor<float, 2>()(0, InputVars::vars::tau1_phi_reco) = tau1_phi_reco; x.tensor<float, 2>()(0, InputVars::vars::tau2_pt_reco) = tau2_pt_reco; x.tensor<float, 2>()(0, InputVars::vars::tau2_eta_reco) = tau2_eta_reco; x.tensor<float, 2>()(0, InputVars::vars::tau2_phi_reco) = tau2_phi_reco; x.tensor<float, 2>()(0, InputVars::vars::jet1_pt_reco) = jet1_pt_reco; x.tensor<float, 2>()(0, InputVars::vars::jet1_eta_reco) = jet1_eta_reco; x.tensor<float, 2>()(0, InputVars::vars::jet1_phi_reco) = jet1_phi_reco; x.tensor<float, 2>()(0, InputVars::vars::jet2_pt_reco) = jet2_pt_reco; x.tensor<float, 2>()(0, InputVars::vars::jet2_eta_reco) = jet2_eta_reco; x.tensor<float, 2>()(0, InputVars::vars::jet2_phi_reco) = jet2_phi_reco; x.tensor<float, 2>()(0, InputVars::vars::remaining_jets_pt_reco) = remaining_jets_pt_reco; x.tensor<float, 2>()(0, InputVars::vars::remaining_jets_eta_reco) = remaining_jets_eta_reco; x.tensor<float, 2>()(0, InputVars::vars::remaining_jets_phi_reco) = remaining_jets_phi_reco; x.tensor<float, 2>()(0, InputVars::vars::remaining_jets_N_reco) = remaining_jets_N_reco; x.tensor<float, 2>()(0, InputVars::vars::MET_pt_reco) = MET_pt_reco; x.tensor<float, 2>()(0, InputVars::vars::MET_phi_reco) = MET_phi_reco; x.tensor<float, 2>()(0, InputVars::vars::MET_covXX_reco) = MET_covXX_reco; x.tensor<float, 2>()(0, InputVars::vars::MET_covXY_reco) = MET_covXY_reco; x.tensor<float, 2>()(0, InputVars::vars::MET_covYY_reco) = MET_covYY_reco; x.tensor<float, 2>()(0, InputVars::vars::mT1_reco) = mT1_reco; x.tensor<float, 2>()(0, InputVars::vars::mT2_reco) = mT2_reco; x.tensor<float, 2>()(0, InputVars::vars::mTtt_reco) = mTtt_reco; x.tensor<float, 2>()(0, InputVars::vars::mTtot_reco) = mTtot_reco; x.tensor<float, 2>()(0, InputVars::vars::PU_npvsGood_reco) = PU_npvsGood_reco; x.tensor<float, 2>()(0, InputVars::vars::N_neutrinos_reco) = N_neutrinos_reco; std::vector<tensorflow::Tensor> pred_vec; tensorflow::run(nn_desc.session, { { nn_desc.input_layer, x } },{ nn_desc.output_layer }, &pred_vec); return pred_vec.at(0).matrix<float>()(0); } diTauMLMass::~diTauMLMass() { tensorflow::closeSession(nn_desc.session); } }// namespace ditauMLMass
59.486111
193
0.671725
[ "vector", "model" ]
d8a1437ddc880170226fdb98c8e56f4b7392ee1d
653
hpp
C++
src/ILovePerlin.hpp
digitalhappens/ILovePerlin
574f6b5c8b23edc76edff5856e1352589aebc12b
[ "MIT" ]
2
2020-02-11T22:38:17.000Z
2020-07-06T21:04:32.000Z
src/ILovePerlin.hpp
digitalhappens/ILovePerlin
574f6b5c8b23edc76edff5856e1352589aebc12b
[ "MIT" ]
2
2020-02-07T03:41:10.000Z
2021-05-10T08:33:03.000Z
src/ILovePerlin.hpp
digitalhappens/ILovePerlin
574f6b5c8b23edc76edff5856e1352589aebc12b
[ "MIT" ]
null
null
null
#include "rack.hpp" #include <time.h> #include <iostream> #ifdef ARCH_MAC #include <mach/clock.h> #include <mach/mach.h> #include <mach/mach_time.h> #include <mach/clock_types.h> #endif #ifdef ARCH_LIN #include <string.h> #endif using namespace rack; // Forward-declare the Plugin, defined in Template.cpp extern Plugin *pluginInstance; //namespace ILovePerlin{ /* #ifdef TARGET_OSX static clock_serv_t cs; #endif static void init(); float getTimef(); static void getMonotonicTime(uint64_t & seconds, uint64_t & nanos); */ //}; // Forward-declare each Model, defined in each module source file extern Model *modelPerlinOne;
15.547619
71
0.724349
[ "model" ]