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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ceca5cb9744b63143c53b45e30cb5688f81de012 | 3,518 | cpp | C++ | src/FusionEKF.cpp | Shubhranshu153/EKF | e2fe73b246b524b16f34648a9dd2a39081ad8db4 | [
"MIT"
] | null | null | null | src/FusionEKF.cpp | Shubhranshu153/EKF | e2fe73b246b524b16f34648a9dd2a39081ad8db4 | [
"MIT"
] | null | null | null | src/FusionEKF.cpp | Shubhranshu153/EKF | e2fe73b246b524b16f34648a9dd2a39081ad8db4 | [
"MIT"
] | null | null | null | #include "FusionEKF.h"
#include <iostream>
#include "Eigen/Dense"
#include "tools.h"
using Eigen::MatrixXd;
using Eigen::VectorXd;
using std::cout;
using std::endl;
using std::vector;
/**
* Constructor.
*/
FusionEKF::FusionEKF() {
is_initialized_ = false;
// initializing matrices
R_laser_ = MatrixXd(2, 2);
R_radar_ = MatrixXd(3, 3);
H_laser_ = MatrixXd(2, 4);
Hj_ = MatrixXd(3, 4);
//measurement covariance matrix - laser
R_laser_ << 0.0225, 0,
0, 0.0225;
//measurement covariance matrix - radar
R_radar_ << 0.09, 0, 0,
0, 0.0009, 0,
0, 0, 0.09;
/**
* TODO: Finish initializing the FusionEKF.
* TODO: Set the process and measurement noises
*/
P = MatrixXd(4, 4);
/*Tune the values to optimize errors*/
P << 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1000, 0,
0, 0, 0, 1000;
H_laser_ << 1, 0, 0, 0,
0, 1, 0, 0;
// state transition matrix (initially Δt is 0)
F=MatrixXd(4, 4);
F << 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1;
// process covariance matrix (initially Δt is 0, hence Q consists of 0's;
MatrixXd Q(4, 4);
Q<< 0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0;
noise_ax=9.0;
noise_ay=9.0;
}
/**
* Destructor.
*/
FusionEKF::~FusionEKF() {}
void FusionEKF::ProcessMeasurement(const MeasurementPackage &measurement_pack) {
/**
* Initialization
*/
if (!is_initialized_) {
ekf_.x_ = VectorXd(4);
ekf_.x_ << 1, 1, 1, 1;
previous_timestamp_=measurement_pack.timestamp_;
Eigen::VectorXd x_=VectorXd(4);
if (measurement_pack.sensor_type_ == MeasurementPackage::RADAR) {
double rho = measurement_pack.raw_measurements_[0];
double phi = measurement_pack.raw_measurements_[1];
double px = rho * cos(phi);
double py = rho * sin(phi);
// initial state in case the first measurement comes from radar sensor
x_ << px,py,0,0; // We dont know phi_dot so we cant predict velocity in cartisan
ekf_.Init(x_, P, F, H_laser_, R_radar_, Q);
}
else if (measurement_pack.sensor_type_ == MeasurementPackage::LASER) {
x_ << measurement_pack.raw_measurements_[0],measurement_pack.raw_measurements_[1],0.0,0.0; // we have no info about the velocity for lidar measurement
ekf_.Init(x_, P, F, H_laser_, R_laser_, Q);
}
is_initialized_ = true;
return;
}
double dt = ( measurement_pack.timestamp_ - previous_timestamp_) / 1000000.0; //dt - expressed in seconds
previous_timestamp_ = measurement_pack.timestamp_;
ekf_.F_(0, 2) = dt;
ekf_.F_(1, 3) = dt;
double dt_2=dt*dt;
double dt_3=dt*dt*dt;
double dt_4=dt*dt*dt*dt;
// update the process covariance matrix
ekf_.Q_ = MatrixXd(4, 4);
ekf_.Q_ << (dt_4/4)*noise_ax, 0.0, (dt_3/2)*noise_ax, 0.0,
0.0, (dt_4/4)*noise_ay, 0.0, (dt_3/2)*noise_ay,
(dt_3/2)*noise_ax, 0.0, dt_2*noise_ax, 0.0,
0.0, (dt_3/2)*noise_ay, 0.0, dt_2*noise_ay;
ekf_.Predict();
if (measurement_pack.sensor_type_ == MeasurementPackage::RADAR) {
ekf_.R_= R_radar_;
ekf_.UpdateEKF(measurement_pack.raw_measurements_);
} else {
ekf_.R_= R_laser_;
ekf_.Update(measurement_pack.raw_measurements_);
}
// print the output
cout << "x_ = " << ekf_.x_ << endl;
cout << "P_ = " << ekf_.P_ << endl;
}
| 22.696774 | 160 | 0.587265 | [
"vector"
] |
cecf10467b515b45e6dbd2386931b3d6a2587e06 | 1,353 | cpp | C++ | codeforces/1208b.cpp | sogapalag/problems | 0ea7d65448e1177f8b3f81124a82d187980d659c | [
"MIT"
] | 1 | 2020-04-04T14:56:12.000Z | 2020-04-04T14:56:12.000Z | codeforces/1208b.cpp | sogapalag/problems | 0ea7d65448e1177f8b3f81124a82d187980d659c | [
"MIT"
] | null | null | null | codeforces/1208b.cpp | sogapalag/problems | 0ea7d65448e1177f8b3f81124a82d187980d659c | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
template <typename T=int>
struct Compress {
map<T, int> id;
vector<T> num;
inline int get_id(T x) {
if (!id.count(x)) {
id[x] = num.size();
num.emplace_back(x);
}
return id[x];
}
inline int get_num(int i) {
assert(0 <= i && i < num.size());
return num[i];
}
};
void solve() {
int n; cin >> n;
vector<int> a(n);
Compress<int> c;
for (int i = 0; i < n; i++) {
int x; cin >> x;
a[i] = c.get_id(x);
}
int sz = c.num.size();
if (sz == n) {
cout << 0; return;
}
vector<int> pre(n, -1);
vector<int> las(n, -1);
for (int i = 0; i < n; i++) {
pre[i] = las[a[i]];
las[a[i]] = i;
}
vector<int> rig(n, -2), ht(n, -1);
int R = -1;
for (int i = n-1; i >= 0; i--) {
if (rig[a[i]] == -1) rig[a[i]] = i;
if (ht[a[i]] == -1) ht[a[i]] = i, rig[a[i]]++;
R = max(R, rig[a[i]]);
}
int r = -1;
int res = n;
for (int i = 0; i < n; i++) {
r = max(r, R);
res = min(res, r - i + 1);
//
r = max(r, ht[a[i]]);
if (pre[i] != -1) break;
}
cout << res;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
cout << endl;
}
| 20.5 | 54 | 0.405765 | [
"vector"
] |
cee13fe7b8805d1914d0ee003c81fe65cc19db68 | 2,856 | hpp | C++ | tests/program_options.hpp | LinerSu/crab | 8f3516f4b4765f4a093bb3c3a94ac2daa174130c | [
"Apache-2.0"
] | 152 | 2016-02-28T06:04:02.000Z | 2022-03-30T10:44:56.000Z | tests/program_options.hpp | LinerSu/crab | 8f3516f4b4765f4a093bb3c3a94ac2daa174130c | [
"Apache-2.0"
] | 43 | 2017-07-03T06:25:19.000Z | 2022-03-23T21:09:32.000Z | tests/program_options.hpp | LinerSu/crab | 8f3516f4b4765f4a093bb3c3a94ac2daa174130c | [
"Apache-2.0"
] | 28 | 2015-11-22T15:51:52.000Z | 2022-01-30T00:46:57.000Z | #pragma once
#include <boost/program_options.hpp>
#include <crab/support/debug.hpp>
#include <crab/support/stats.hpp>
#include <crab/domains/abstract_domain_params.hpp>
#include <iostream>
namespace crab_tests {
int parse_user_options(int argc, char **argv, bool &stats_enabled) {
boost::program_options::options_description po("Test Options");
po.add_options()("help", "Print help message and exit");
po.add_options()("log",
boost::program_options::value<std::vector<std::string>>(),
"Enable specified log level");
po.add_options()("domain-param",
boost::program_options::value<std::vector<std::string>>(),
"Set abstract domain parameter: arg must be \"param=val\"");
po.add_options()("display-domain-params",
"Display abstract domain parameter values");
po.add_options()("verbose", boost::program_options::value<unsigned>(),
"Enable verbosity level");
po.add_options()("stats", boost::program_options::bool_switch(&stats_enabled),
"Enable stats");
po.add_options()("disable-warnings", "Disable warning messages");
po.add_options()("sanity", "Enable sanity checks");
boost::program_options::options_description cmmdline_options;
cmmdline_options.add(po);
boost::program_options::variables_map vm;
boost::program_options::positional_options_description p;
boost::program_options::store(
boost::program_options::command_line_parser(argc, argv)
.options(cmmdline_options)
.positional(p)
.run(),
vm);
boost::program_options::notify(vm);
if (vm.count("help")) {
std::cout << po << "n";
return 0;
}
if (vm.count("log")) {
std::vector<std::string> loggers = vm["log"].as<std::vector<std::string>>();
for (unsigned int i = 0; i < loggers.size(); i++)
crab::CrabEnableLog(loggers[i]);
}
if (vm.count("domain-param")) {
std::vector<std::string> parameters = vm["domain-param"].as<std::vector<std::string>>();
std::string delimiter("=");
for (unsigned int i = 0; i < parameters.size(); i++) {
std::string s = parameters[i];
int pos = s.find(delimiter);
std::string param = s.substr(0, pos);
std::string val = s.substr(pos+delimiter.length());
crab::domains::crab_domain_params_man::get().set_param(param, val);
}
}
// print after set all domain-param
if (vm.count("display-domain-params")) {
crab::domains::crab_domain_params_man::get().write(crab::outs());
}
if (vm.count("verbose")) {
crab::CrabEnableVerbosity(vm["verbose"].as<unsigned>());
}
if (vm.count("disable-warnings")) {
crab::CrabEnableWarningMsg(false);
}
if (vm.count("sanity")) {
crab::CrabEnableSanityChecks(true);
}
crab::CrabEnableStats();
return 1;
}
} // namespace crab_tests
| 35.7 | 92 | 0.646359 | [
"vector"
] |
ceec701de45f39f7ba9bdfcb0fa49e349626790b | 637 | cpp | C++ | OddOccurencesInArray/C++/OddOccurencesInArray.cpp | ArturMarekNowak/Random-Algorithms-Repository | bda0e18bed68d3ab1b61b445e693a5c3c03a1179 | [
"MIT"
] | 1 | 2022-02-12T14:57:48.000Z | 2022-02-12T14:57:48.000Z | OddOccurencesInArray/C++/OddOccurencesInArray.cpp | ArturMarekNowak/Random-Algorithms-Repository | bda0e18bed68d3ab1b61b445e693a5c3c03a1179 | [
"MIT"
] | null | null | null | OddOccurencesInArray/C++/OddOccurencesInArray.cpp | ArturMarekNowak/Random-Algorithms-Repository | bda0e18bed68d3ab1b61b445e693a5c3c03a1179 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
template <typename T>
T OddOccurencesInsomeVecrray(std::vector<T> & someVec)
{
sort(someVec.begin(), someVec.end());
if(someVec.size() % 2 == 0)
{
for(int i = 0; i < someVec.size() - 2; i += 2)
if(someVec[i] != someVec[i + 1])
return someVec[i];
}
else
{
for(int i = 0; i < someVec.size() - 2; i += 2)
if(someVec[i] != someVec[i + 1])
return someVec[i];
return someVec[someVec.size() - 1];
}
return 0;
}
int main()
{
std::vector<int> vecOne = {9, 3, 9, 3, 9, 7, 9};
std::cout << OddOccurencesInsomeVecrray(vecOne) << std::endl;
return 0;
}
| 18.735294 | 62 | 0.594976 | [
"vector"
] |
ceed834f3f06044fa419e5e7340c51a8891f87e6 | 45,329 | cpp | C++ | cpp-restsdk/api/WlmApi.cpp | thracesystems/powermeter-api | 7bdab034ff916ee49e986de88f157bd044e981c1 | [
"Apache-2.0"
] | null | null | null | cpp-restsdk/api/WlmApi.cpp | thracesystems/powermeter-api | 7bdab034ff916ee49e986de88f157bd044e981c1 | [
"Apache-2.0"
] | null | null | null | cpp-restsdk/api/WlmApi.cpp | thracesystems/powermeter-api | 7bdab034ff916ee49e986de88f157bd044e981c1 | [
"Apache-2.0"
] | null | null | null | /**
* PowerMeter API
* API
*
* The version of the OpenAPI document: 2021.4.1
*
* NOTE: This class is auto generated by OpenAPI-Generator 4.3.1.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "WlmApi.h"
#include "IHttpBody.h"
#include "JsonBody.h"
#include "MultipartFormData.h"
#include <unordered_set>
#include <boost/algorithm/string/replace.hpp>
namespace powermeter {
namespace api {
using namespace powermeter::model;
WlmApi::WlmApi( std::shared_ptr<const ApiClient> apiClient )
: m_ApiClient(apiClient)
{
}
WlmApi::~WlmApi()
{
}
pplx::task<std::shared_ptr<WLMVersion>> WlmApi::wlmCommitCreate(int32_t wlmid, std::shared_ptr<WLMVersion> data) const
{
// verify the required parameter 'data' is set
if (data == nullptr)
{
throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'data' when calling WlmApi->wlmCommitCreate"));
}
std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
utility::string_t localVarPath = utility::conversions::to_string_t("/wlm/{wlmid}/commit/");
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("wlmid") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(wlmid));
std::map<utility::string_t, utility::string_t> localVarQueryParams;
std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
std::map<utility::string_t, utility::string_t> localVarFormParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;
std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
utility::string_t localVarResponseHttpContentType;
// use JSON if possible
if ( localVarResponseHttpContentTypes.size() == 0 )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// JSON
else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(400, utility::conversions::to_string_t("WlmApi->wlmCommitCreate does not produce any supported media type"));
}
localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;
std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
std::shared_ptr<IHttpBody> localVarHttpBody;
utility::string_t localVarRequestHttpContentType;
// use JSON if possible
if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
web::json::value localVarJson;
localVarJson = ModelBase::toJson(data);
localVarHttpBody = std::shared_ptr<IHttpBody>( new JsonBody( localVarJson ) );
}
// multipart formdata
else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
std::shared_ptr<MultipartFormData> localVarMultipart(new MultipartFormData);
if(data.get())
{
data->toMultipart(localVarMultipart, utility::conversions::to_string_t("data"));
}
localVarHttpBody = localVarMultipart;
localVarRequestHttpContentType += utility::conversions::to_string_t("; boundary=") + localVarMultipart->getBoundary();
}
else
{
throw ApiException(415, utility::conversions::to_string_t("WlmApi->wlmCommitCreate does not consume any supported media type"));
}
// authentication (Basic) required
{
utility::string_t localVarApiKey = localVarApiConfiguration->getApiKey(utility::conversions::to_string_t("Authorization"));
if ( localVarApiKey.size() > 0 )
{
localVarHeaderParams[utility::conversions::to_string_t("Authorization")] = localVarApiKey;
}
}
return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("POST"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
.then([=](web::http::http_response localVarResponse)
{
if (m_ApiClient->getResponseHandler())
{
m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
}
// 1xx - informational : OK
// 2xx - successful : OK
// 3xx - redirection : OK
// 4xx - client error : not OK
// 5xx - client error : not OK
if (localVarResponse.status_code() >= 400)
{
throw ApiException(localVarResponse.status_code()
, utility::conversions::to_string_t("error calling wlmCommitCreate: ") + localVarResponse.reason_phrase()
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
// check response content type
if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
{
utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
{
throw ApiException(500
, utility::conversions::to_string_t("error calling wlmCommitCreate: unexpected response type: ") + localVarContentType
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
}
return localVarResponse.extract_string();
})
.then([=](utility::string_t localVarResponse)
{
std::shared_ptr<WLMVersion> localVarResult(new WLMVersion());
if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json"))
{
web::json::value localVarJson = web::json::value::parse(localVarResponse);
ModelBase::fromJson(localVarJson, localVarResult);
}
// else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data"))
// {
// TODO multipart response parsing
// }
else
{
throw ApiException(500
, utility::conversions::to_string_t("error calling wlmCommitCreate: unsupported response type"));
}
return localVarResult;
});
}
pplx::task<std::shared_ptr<WireLoad>> WlmApi::wlmCreate(int32_t wlmid, std::shared_ptr<WireLoad> data) const
{
// verify the required parameter 'data' is set
if (data == nullptr)
{
throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'data' when calling WlmApi->wlmCreate"));
}
std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
utility::string_t localVarPath = utility::conversions::to_string_t("/wlm/{wlmid}/");
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("wlmid") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(wlmid));
std::map<utility::string_t, utility::string_t> localVarQueryParams;
std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
std::map<utility::string_t, utility::string_t> localVarFormParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;
std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
utility::string_t localVarResponseHttpContentType;
// use JSON if possible
if ( localVarResponseHttpContentTypes.size() == 0 )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// JSON
else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(400, utility::conversions::to_string_t("WlmApi->wlmCreate does not produce any supported media type"));
}
localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;
std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
std::shared_ptr<IHttpBody> localVarHttpBody;
utility::string_t localVarRequestHttpContentType;
// use JSON if possible
if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
web::json::value localVarJson;
localVarJson = ModelBase::toJson(data);
localVarHttpBody = std::shared_ptr<IHttpBody>( new JsonBody( localVarJson ) );
}
// multipart formdata
else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
std::shared_ptr<MultipartFormData> localVarMultipart(new MultipartFormData);
if(data.get())
{
data->toMultipart(localVarMultipart, utility::conversions::to_string_t("data"));
}
localVarHttpBody = localVarMultipart;
localVarRequestHttpContentType += utility::conversions::to_string_t("; boundary=") + localVarMultipart->getBoundary();
}
else
{
throw ApiException(415, utility::conversions::to_string_t("WlmApi->wlmCreate does not consume any supported media type"));
}
// authentication (Basic) required
{
utility::string_t localVarApiKey = localVarApiConfiguration->getApiKey(utility::conversions::to_string_t("Authorization"));
if ( localVarApiKey.size() > 0 )
{
localVarHeaderParams[utility::conversions::to_string_t("Authorization")] = localVarApiKey;
}
}
return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("POST"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
.then([=](web::http::http_response localVarResponse)
{
if (m_ApiClient->getResponseHandler())
{
m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
}
// 1xx - informational : OK
// 2xx - successful : OK
// 3xx - redirection : OK
// 4xx - client error : not OK
// 5xx - client error : not OK
if (localVarResponse.status_code() >= 400)
{
throw ApiException(localVarResponse.status_code()
, utility::conversions::to_string_t("error calling wlmCreate: ") + localVarResponse.reason_phrase()
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
// check response content type
if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
{
utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
{
throw ApiException(500
, utility::conversions::to_string_t("error calling wlmCreate: unexpected response type: ") + localVarContentType
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
}
return localVarResponse.extract_string();
})
.then([=](utility::string_t localVarResponse)
{
std::shared_ptr<WireLoad> localVarResult(new WireLoad());
if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json"))
{
web::json::value localVarJson = web::json::value::parse(localVarResponse);
ModelBase::fromJson(localVarJson, localVarResult);
}
// else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data"))
// {
// TODO multipart response parsing
// }
else
{
throw ApiException(500
, utility::conversions::to_string_t("error calling wlmCreate: unsupported response type"));
}
return localVarResult;
});
}
pplx::task<void> WlmApi::wlmDataCreate(int32_t wlmid, int32_t dataid) const
{
std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
utility::string_t localVarPath = utility::conversions::to_string_t("/wlm/{wlmid}/data/{dataid}/");
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("wlmid") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(wlmid));
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("dataid") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(dataid));
std::map<utility::string_t, utility::string_t> localVarQueryParams;
std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
std::map<utility::string_t, utility::string_t> localVarFormParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;
std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
utility::string_t localVarResponseHttpContentType;
// use JSON if possible
if ( localVarResponseHttpContentTypes.size() == 0 )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// JSON
else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(400, utility::conversions::to_string_t("WlmApi->wlmDataCreate does not produce any supported media type"));
}
localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;
std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
std::shared_ptr<IHttpBody> localVarHttpBody;
utility::string_t localVarRequestHttpContentType;
// use JSON if possible
if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(415, utility::conversions::to_string_t("WlmApi->wlmDataCreate does not consume any supported media type"));
}
// authentication (Basic) required
{
utility::string_t localVarApiKey = localVarApiConfiguration->getApiKey(utility::conversions::to_string_t("Authorization"));
if ( localVarApiKey.size() > 0 )
{
localVarHeaderParams[utility::conversions::to_string_t("Authorization")] = localVarApiKey;
}
}
return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("POST"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
.then([=](web::http::http_response localVarResponse)
{
if (m_ApiClient->getResponseHandler())
{
m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
}
// 1xx - informational : OK
// 2xx - successful : OK
// 3xx - redirection : OK
// 4xx - client error : not OK
// 5xx - client error : not OK
if (localVarResponse.status_code() >= 400)
{
throw ApiException(localVarResponse.status_code()
, utility::conversions::to_string_t("error calling wlmDataCreate: ") + localVarResponse.reason_phrase()
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
// check response content type
if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
{
utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
{
throw ApiException(500
, utility::conversions::to_string_t("error calling wlmDataCreate: unexpected response type: ") + localVarContentType
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
}
return localVarResponse.extract_string();
})
.then([=](utility::string_t localVarResponse)
{
return void();
});
}
pplx::task<std::shared_ptr<WireLoad>> WlmApi::wlmDataRead(int32_t wlmid, int32_t dataid) const
{
std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
utility::string_t localVarPath = utility::conversions::to_string_t("/wlm/{wlmid}/data/{dataid}/");
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("wlmid") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(wlmid));
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("dataid") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(dataid));
std::map<utility::string_t, utility::string_t> localVarQueryParams;
std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
std::map<utility::string_t, utility::string_t> localVarFormParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;
std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
utility::string_t localVarResponseHttpContentType;
// use JSON if possible
if ( localVarResponseHttpContentTypes.size() == 0 )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// JSON
else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(400, utility::conversions::to_string_t("WlmApi->wlmDataRead does not produce any supported media type"));
}
localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;
std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
std::shared_ptr<IHttpBody> localVarHttpBody;
utility::string_t localVarRequestHttpContentType;
// use JSON if possible
if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(415, utility::conversions::to_string_t("WlmApi->wlmDataRead does not consume any supported media type"));
}
// authentication (Basic) required
{
utility::string_t localVarApiKey = localVarApiConfiguration->getApiKey(utility::conversions::to_string_t("Authorization"));
if ( localVarApiKey.size() > 0 )
{
localVarHeaderParams[utility::conversions::to_string_t("Authorization")] = localVarApiKey;
}
}
return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("GET"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
.then([=](web::http::http_response localVarResponse)
{
if (m_ApiClient->getResponseHandler())
{
m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
}
// 1xx - informational : OK
// 2xx - successful : OK
// 3xx - redirection : OK
// 4xx - client error : not OK
// 5xx - client error : not OK
if (localVarResponse.status_code() >= 400)
{
throw ApiException(localVarResponse.status_code()
, utility::conversions::to_string_t("error calling wlmDataRead: ") + localVarResponse.reason_phrase()
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
// check response content type
if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
{
utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
{
throw ApiException(500
, utility::conversions::to_string_t("error calling wlmDataRead: unexpected response type: ") + localVarContentType
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
}
return localVarResponse.extract_string();
})
.then([=](utility::string_t localVarResponse)
{
std::shared_ptr<WireLoad> localVarResult(new WireLoad());
if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json"))
{
web::json::value localVarJson = web::json::value::parse(localVarResponse);
ModelBase::fromJson(localVarJson, localVarResult);
}
// else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data"))
// {
// TODO multipart response parsing
// }
else
{
throw ApiException(500
, utility::conversions::to_string_t("error calling wlmDataRead: unsupported response type"));
}
return localVarResult;
});
}
pplx::task<std::shared_ptr<WireLoad>> WlmApi::wlmDataUpdate(int32_t wlmid, int32_t dataid, std::shared_ptr<WireLoad> data) const
{
// verify the required parameter 'data' is set
if (data == nullptr)
{
throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'data' when calling WlmApi->wlmDataUpdate"));
}
std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
utility::string_t localVarPath = utility::conversions::to_string_t("/wlm/{wlmid}/data/{dataid}/");
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("wlmid") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(wlmid));
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("dataid") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(dataid));
std::map<utility::string_t, utility::string_t> localVarQueryParams;
std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
std::map<utility::string_t, utility::string_t> localVarFormParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;
std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
utility::string_t localVarResponseHttpContentType;
// use JSON if possible
if ( localVarResponseHttpContentTypes.size() == 0 )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// JSON
else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(400, utility::conversions::to_string_t("WlmApi->wlmDataUpdate does not produce any supported media type"));
}
localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;
std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
std::shared_ptr<IHttpBody> localVarHttpBody;
utility::string_t localVarRequestHttpContentType;
// use JSON if possible
if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
web::json::value localVarJson;
localVarJson = ModelBase::toJson(data);
localVarHttpBody = std::shared_ptr<IHttpBody>( new JsonBody( localVarJson ) );
}
// multipart formdata
else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
std::shared_ptr<MultipartFormData> localVarMultipart(new MultipartFormData);
if(data.get())
{
data->toMultipart(localVarMultipart, utility::conversions::to_string_t("data"));
}
localVarHttpBody = localVarMultipart;
localVarRequestHttpContentType += utility::conversions::to_string_t("; boundary=") + localVarMultipart->getBoundary();
}
else
{
throw ApiException(415, utility::conversions::to_string_t("WlmApi->wlmDataUpdate does not consume any supported media type"));
}
// authentication (Basic) required
{
utility::string_t localVarApiKey = localVarApiConfiguration->getApiKey(utility::conversions::to_string_t("Authorization"));
if ( localVarApiKey.size() > 0 )
{
localVarHeaderParams[utility::conversions::to_string_t("Authorization")] = localVarApiKey;
}
}
return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("PUT"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
.then([=](web::http::http_response localVarResponse)
{
if (m_ApiClient->getResponseHandler())
{
m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
}
// 1xx - informational : OK
// 2xx - successful : OK
// 3xx - redirection : OK
// 4xx - client error : not OK
// 5xx - client error : not OK
if (localVarResponse.status_code() >= 400)
{
throw ApiException(localVarResponse.status_code()
, utility::conversions::to_string_t("error calling wlmDataUpdate: ") + localVarResponse.reason_phrase()
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
// check response content type
if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
{
utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
{
throw ApiException(500
, utility::conversions::to_string_t("error calling wlmDataUpdate: unexpected response type: ") + localVarContentType
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
}
return localVarResponse.extract_string();
})
.then([=](utility::string_t localVarResponse)
{
std::shared_ptr<WireLoad> localVarResult(new WireLoad());
if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json"))
{
web::json::value localVarJson = web::json::value::parse(localVarResponse);
ModelBase::fromJson(localVarJson, localVarResult);
}
// else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data"))
// {
// TODO multipart response parsing
// }
else
{
throw ApiException(500
, utility::conversions::to_string_t("error calling wlmDataUpdate: unsupported response type"));
}
return localVarResult;
});
}
pplx::task<std::shared_ptr<WLMModel>> WlmApi::wlmRead(int32_t wlmid) const
{
std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
utility::string_t localVarPath = utility::conversions::to_string_t("/wlm/{wlmid}/");
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("wlmid") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(wlmid));
std::map<utility::string_t, utility::string_t> localVarQueryParams;
std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
std::map<utility::string_t, utility::string_t> localVarFormParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;
std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
utility::string_t localVarResponseHttpContentType;
// use JSON if possible
if ( localVarResponseHttpContentTypes.size() == 0 )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// JSON
else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(400, utility::conversions::to_string_t("WlmApi->wlmRead does not produce any supported media type"));
}
localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;
std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
std::shared_ptr<IHttpBody> localVarHttpBody;
utility::string_t localVarRequestHttpContentType;
// use JSON if possible
if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(415, utility::conversions::to_string_t("WlmApi->wlmRead does not consume any supported media type"));
}
// authentication (Basic) required
{
utility::string_t localVarApiKey = localVarApiConfiguration->getApiKey(utility::conversions::to_string_t("Authorization"));
if ( localVarApiKey.size() > 0 )
{
localVarHeaderParams[utility::conversions::to_string_t("Authorization")] = localVarApiKey;
}
}
return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("GET"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
.then([=](web::http::http_response localVarResponse)
{
if (m_ApiClient->getResponseHandler())
{
m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
}
// 1xx - informational : OK
// 2xx - successful : OK
// 3xx - redirection : OK
// 4xx - client error : not OK
// 5xx - client error : not OK
if (localVarResponse.status_code() >= 400)
{
throw ApiException(localVarResponse.status_code()
, utility::conversions::to_string_t("error calling wlmRead: ") + localVarResponse.reason_phrase()
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
// check response content type
if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
{
utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
{
throw ApiException(500
, utility::conversions::to_string_t("error calling wlmRead: unexpected response type: ") + localVarContentType
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
}
return localVarResponse.extract_string();
})
.then([=](utility::string_t localVarResponse)
{
std::shared_ptr<WLMModel> localVarResult(new WLMModel());
if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json"))
{
web::json::value localVarJson = web::json::value::parse(localVarResponse);
ModelBase::fromJson(localVarJson, localVarResult);
}
// else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data"))
// {
// TODO multipart response parsing
// }
else
{
throw ApiException(500
, utility::conversions::to_string_t("error calling wlmRead: unsupported response type"));
}
return localVarResult;
});
}
pplx::task<std::vector<std::shared_ptr<WLMVersion>>> WlmApi::wlmVersionList(utility::string_t wlmid, int32_t pcbid) const
{
std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
utility::string_t localVarPath = utility::conversions::to_string_t("/wlm/{wlmid}/version/");
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("wlmid") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(wlmid));
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("pcbid") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(pcbid));
std::map<utility::string_t, utility::string_t> localVarQueryParams;
std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
std::map<utility::string_t, utility::string_t> localVarFormParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;
std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
utility::string_t localVarResponseHttpContentType;
// use JSON if possible
if ( localVarResponseHttpContentTypes.size() == 0 )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// JSON
else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(400, utility::conversions::to_string_t("WlmApi->wlmVersionList does not produce any supported media type"));
}
localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;
std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
std::shared_ptr<IHttpBody> localVarHttpBody;
utility::string_t localVarRequestHttpContentType;
// use JSON if possible
if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(415, utility::conversions::to_string_t("WlmApi->wlmVersionList does not consume any supported media type"));
}
// authentication (Basic) required
{
utility::string_t localVarApiKey = localVarApiConfiguration->getApiKey(utility::conversions::to_string_t("Authorization"));
if ( localVarApiKey.size() > 0 )
{
localVarHeaderParams[utility::conversions::to_string_t("Authorization")] = localVarApiKey;
}
}
return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("GET"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
.then([=](web::http::http_response localVarResponse)
{
if (m_ApiClient->getResponseHandler())
{
m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
}
// 1xx - informational : OK
// 2xx - successful : OK
// 3xx - redirection : OK
// 4xx - client error : not OK
// 5xx - client error : not OK
if (localVarResponse.status_code() >= 400)
{
throw ApiException(localVarResponse.status_code()
, utility::conversions::to_string_t("error calling wlmVersionList: ") + localVarResponse.reason_phrase()
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
// check response content type
if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
{
utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
{
throw ApiException(500
, utility::conversions::to_string_t("error calling wlmVersionList: unexpected response type: ") + localVarContentType
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
}
return localVarResponse.extract_string();
})
.then([=](utility::string_t localVarResponse)
{
std::vector<std::shared_ptr<WLMVersion>> localVarResult;
if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json"))
{
web::json::value localVarJson = web::json::value::parse(localVarResponse);
for( auto& localVarItem : localVarJson.as_array() )
{
std::shared_ptr<WLMVersion> localVarItemObj;
ModelBase::fromJson(localVarItem, localVarItemObj);
localVarResult.push_back(localVarItemObj);
}
}
// else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data"))
// {
// TODO multipart response parsing
// }
else
{
throw ApiException(500
, utility::conversions::to_string_t("error calling wlmVersionList: unsupported response type"));
}
return localVarResult;
});
}
}
}
| 45.926039 | 221 | 0.694699 | [
"vector",
"model"
] |
cef02c54b1de1b40502475709941f0e427363526 | 12,192 | cpp | C++ | TEST/test_is.cpp | SammyB428/WFC | 64aee7c7953e38c8a418ba9530339e8f4faac046 | [
"BSD-2-Clause"
] | 1 | 2021-03-29T06:09:19.000Z | 2021-03-29T06:09:19.000Z | TEST/test_is.cpp | SammyB428/WFC | 64aee7c7953e38c8a418ba9530339e8f4faac046 | [
"BSD-2-Clause"
] | null | null | null | TEST/test_is.cpp | SammyB428/WFC | 64aee7c7953e38c8a418ba9530339e8f4faac046 | [
"BSD-2-Clause"
] | null | null | null | /*
** Author: Samuel R. Blackburn
** Internet: wfc@pobox.com
**
** Copyright, 2000-2016, Samuel R. Blackburn
**
** "You can get credit for something or get it done, but not both."
** Dr. Richard Garwin
**
** BSD License follows.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** Redistributions of source code must retain the above copyright notice,
** this list of conditions and the following disclaimer. Redistributions
** in binary form must reproduce the above copyright notice, this list
** of conditions and the following disclaimer in the documentation and/or
** other materials provided with the distribution. Neither the name of
** the WFC nor the names of its contributors may be used to endorse or
** promote products derived from this software without specific prior
** written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// SPDX-License-Identifier: BSD-2-Clause
#include "test.h"
#pragma hdrstop
#if defined( _DEBUG ) && defined( _INC_CRTDBG )
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#define new DEBUG_NEW
#endif // _DEBUG
_Check_return_ bool test_is( _Out_ std::string& class_name, _Out_ int& test_number_that_failed ) noexcept
{
class_name.assign(STRING_VIEW("test_is"));
auto good_plain_ascii_guid = STRING_VIEW("0AEE2A9F-BCBB-11d0-8C72-00C04FC2B085");
auto good_plain_wide_guid = WSTRING_VIEW(L"0aee2A9F-BCBB-11d0-8C72-00C04FC2B085");
auto good_curly_ascii_guid = STRING_VIEW("{0AEE2A9F-BCBB-11d0-8C72-00C04FC2B085}");
auto good_curly_wide_guid = WSTRING_VIEW(L"{0aee2A9F-BCBB-11d0-8C72-00C04FC2B085}");
auto bad1_plain_ascii_guid = STRING_VIEW("0AEE2A9F-BCBB-11d0-8C72 00C04FC2B085");
auto bad1_plain_wide_guid = WSTRING_VIEW(L"0aee2A9F-BCBB-11d0-8C72 00C04FC2B085");
auto bad1_curly_ascii_guid = STRING_VIEW("{0AEE2A9F-BCBB-11d0-8C72 00C04FC2B085}");
auto bad1_curly_wide_guid = WSTRING_VIEW(L"{0aee2A9F-BCBB-11d0-8C72 00C04FC2B085}");
auto bad2_plain_ascii_guid = STRING_VIEW("0AEE2A9F-BCBB-11d0-8C72-00C04FC2B08O");
auto bad2_plain_wide_guid = WSTRING_VIEW(L"0aee2A9F-BCBB-11d0-8C72-00C04FC2B08O");
auto bad2_curly_ascii_guid = STRING_VIEW("{0AEE2A9F-BCBB-11d0-8C72-00C04FC2B08O}");
auto bad2_curly_wide_guid = WSTRING_VIEW(L"{0aee2A9F-BCBB-11d0-8C72-00C04FC2B08O}");
if (Win32FoundationClasses::wfc_is_guid( good_plain_ascii_guid ) == false )
{
class_name.assign(STRING_VIEW("wfc_is_guid( ascii )"));
test_number_that_failed = 1;
return( failure() );
}
if (Win32FoundationClasses::wfc_is_guid( bad1_plain_ascii_guid ) == true )
{
class_name.assign(STRING_VIEW("wfc_is_guid( ascii )"));
test_number_that_failed = 2;
return( failure() );
}
if (Win32FoundationClasses::wfc_is_guid( bad2_plain_ascii_guid ) == true )
{
class_name.assign(STRING_VIEW("wfc_is_guid( ascii )"));
test_number_that_failed = 3;
return( failure() );
}
if (Win32FoundationClasses::wfc_is_guid( good_plain_wide_guid ) == false )
{
class_name.assign(STRING_VIEW("wfc_is_guid( unicode )"));
test_number_that_failed = 4;
return( failure() );
}
if (Win32FoundationClasses::wfc_is_guid( bad1_plain_wide_guid ) == true )
{
class_name.assign(STRING_VIEW("wfc_is_guid( unicode )"));
test_number_that_failed = 5;
return( failure() );
}
if (Win32FoundationClasses::wfc_is_guid( bad2_plain_wide_guid ) == true )
{
class_name.assign(STRING_VIEW("wfc_is_guid( unicode )"));
test_number_that_failed = 6;
return( failure() );
}
if (Win32FoundationClasses::wfc_is_guid_with_curlies( good_curly_ascii_guid ) == false )
{
class_name.assign(STRING_VIEW("wfc_is_guid_with_curlies( ascii )"));
test_number_that_failed = 7;
return( failure() );
}
if (Win32FoundationClasses::wfc_is_guid_with_curlies( bad1_curly_ascii_guid ) == true )
{
class_name.assign(STRING_VIEW("wfc_is_guid_with_curlies( ascii )"));
test_number_that_failed = 8;
return( failure() );
}
if (Win32FoundationClasses::wfc_is_guid_with_curlies( bad2_curly_ascii_guid ) == true )
{
class_name.assign(STRING_VIEW("wfc_is_guid_with_curlies( ascii )"));
test_number_that_failed = 9;
return( failure() );
}
if (Win32FoundationClasses::wfc_is_guid_with_curlies( good_curly_wide_guid ) == false )
{
class_name.assign(STRING_VIEW("wfc_is_guid_with_curlies( unicode )"));
test_number_that_failed = 10;
return( failure() );
}
if (Win32FoundationClasses::wfc_is_guid_with_curlies( bad1_curly_wide_guid ) == true )
{
class_name.assign(STRING_VIEW("wfc_is_guid_with_curlies( unicode )"));
test_number_that_failed = 11;
return( failure() );
}
if (Win32FoundationClasses::wfc_is_guid_with_curlies( bad2_curly_wide_guid ) == true )
{
class_name.assign(STRING_VIEW("wfc_is_guid_with_curlies( unicode2 )"));
test_number_that_failed = 12;
return( failure() );
}
if (Win32FoundationClasses::wfc_find_curly_guid( reinterpret_cast<uint8_t const *>(good_curly_ascii_guid.data()), good_curly_ascii_guid.length() ) not_eq 0 )
{
class_name.assign(STRING_VIEW("wfc_find_curly_guid()"));
test_number_that_failed = 13;
return( failure() );
}
if (Win32FoundationClasses::wfc_find_wide_curly_guid( reinterpret_cast<uint8_t const *>(good_curly_wide_guid.data()), good_curly_wide_guid.length() * sizeof( wchar_t ) ) not_eq 0 )
{
class_name.assign(STRING_VIEW("wfc_find_wide_curly_guid()"));
test_number_that_failed = 14;
return( failure() );
}
if (Win32FoundationClasses::is_bad_handle( (HANDLE) NULL ) == false )
{
class_name.assign(STRING_VIEW("NULL is not a valid handle"));
test_number_that_failed = 15;
return( failure() );
}
if (Win32FoundationClasses::is_bad_handle( (HANDLE) INVALID_HANDLE_VALUE ) == false )
{
class_name.assign(STRING_VIEW("INVALID_HANDLE_VALUE is not a valid handle"));
test_number_that_failed = 16;
return( failure() );
}
if (Win32FoundationClasses::round_down_to_a_multiple_of(1025, 512) not_eq 1024)
{
class_name.assign(STRING_VIEW("round_down_to_a_multiple_of"));
test_number_that_failed = 17;
return(failure());
}
if (Win32FoundationClasses::round_down_to_a_multiple_of(512, 512) not_eq 512)
{
class_name.assign(STRING_VIEW("round_down_to_a_multiple_of"));
test_number_that_failed = 18;
return(failure());
}
if (Win32FoundationClasses::round_down_to_a_multiple_of(1023, 512) not_eq 512)
{
class_name.assign(STRING_VIEW("round_down_to_a_multiple_of"));
test_number_that_failed = 19;
return(failure());
}
if (Win32FoundationClasses::round_down_to_a_multiple_of(1024, 512) not_eq 1024)
{
class_name.assign(STRING_VIEW("round_down_to_a_multiple_of"));
test_number_that_failed = 20;
return(failure());
}
if (Win32FoundationClasses::round_down_to_a_multiple_of(1024, 0) not_eq 0)
{
class_name.assign(STRING_VIEW("round_down_to_a_multiple_of"));
test_number_that_failed = 21;
return(failure());
}
if (Win32FoundationClasses::round_down_to_a_multiple_of(511, 512) not_eq 0)
{
class_name.assign(STRING_VIEW("round_down_to_a_multiple_of()"));
test_number_that_failed = 22;
return(failure());
}
if (Win32FoundationClasses::wfc_is_dotted_ip_address(STRING_VIEW("1.1.1.1")) == false)
{
class_name.assign(STRING_VIEW("wfc_is_dotted_ip_address()"));
test_number_that_failed = 23;
return(failure());
}
if (Win32FoundationClasses::wfc_is_dotted_ip_address(STRING_VIEW("1.11.111.256")) == true)
{
class_name.assign(STRING_VIEW("wfc_is_dotted_ip_address()"));
test_number_that_failed = 24;
return(failure());
}
if (Win32FoundationClasses::wfc_is_dotted_ip_address(WSTRING_VIEW(L"1.1.1.1")) == false)
{
class_name.assign(STRING_VIEW("wfc_is_dotted_ip_address()"));
test_number_that_failed = 25;
return(failure());
}
if (Win32FoundationClasses::wfc_is_dotted_ip_address(WSTRING_VIEW(L"1.11.111.256")) == true)
{
class_name.assign(STRING_VIEW("wfc_is_dotted_ip_address()"));
test_number_that_failed = 26;
return(failure());
}
std::filesystem::path p;
p.append(L"AA");
p.append(L"BB");
p.append(L"CC");
std::wstring test_string;
Win32FoundationClasses::format(test_string, L"%s.txt", p);
if (test_string.compare(WSTRING_VIEW(L"AA\\BB\\CC.txt")) not_eq I_AM_EQUAL_TO_THAT)
{
test_number_that_failed = 27;
return(failure());
}
wchar_t const* ss = L"12,34,56,78,";
std::vector<std::wstring_view> views;
Win32FoundationClasses::split_view(ss, wcslen(ss), ',', views);
if (views.size() not_eq 5)
{
test_number_that_failed = 28;
return(failure());
}
if (views[4].empty() == false)
{
test_number_that_failed = 29;
return(failure());
}
if (views[0].compare(WSTRING_VIEW(L"12")) not_eq I_AM_EQUAL_TO_THAT)
{
test_number_that_failed = 30;
return(failure());
}
if (views[1].compare(WSTRING_VIEW(L"34")) not_eq I_AM_EQUAL_TO_THAT)
{
test_number_that_failed = 31;
return(failure());
}
if (views[2].compare(WSTRING_VIEW(L"56")) not_eq I_AM_EQUAL_TO_THAT)
{
test_number_that_failed = 32;
return(failure());
}
if (views[3].compare(WSTRING_VIEW(L"78")) not_eq I_AM_EQUAL_TO_THAT)
{
test_number_that_failed = 33;
return(failure());
}
ss = L"78,56,34,12";
Win32FoundationClasses::split_view(ss, wcslen(ss), ',', views);
if (views.size() not_eq 4)
{
test_number_that_failed = 34;
return(failure());
}
if (views[0].compare(WSTRING_VIEW(L"78")) not_eq I_AM_EQUAL_TO_THAT)
{
test_number_that_failed = 35;
return(failure());
}
if (views[1].compare(WSTRING_VIEW(L"56")) not_eq I_AM_EQUAL_TO_THAT)
{
test_number_that_failed = 36;
return(failure());
}
if (views[2].compare(WSTRING_VIEW(L"34")) not_eq I_AM_EQUAL_TO_THAT)
{
test_number_that_failed = 37;
return(failure());
}
if (views[3].compare(WSTRING_VIEW(L"12")) not_eq I_AM_EQUAL_TO_THAT)
{
test_number_that_failed = 38;
return(failure());
}
std::vector<std::string_view> ascii_views;
Win32FoundationClasses::split("A|B|C|", '|', ascii_views);
if (ascii_views.size() not_eq 4)
{
test_number_that_failed = 39;
return(failure());
}
if (ascii_views[0].compare(STRING_VIEW("A")) not_eq I_AM_EQUAL_TO_THAT)
{
test_number_that_failed = 40;
return(failure());
}
if (ascii_views[1].compare(STRING_VIEW("B")) not_eq I_AM_EQUAL_TO_THAT)
{
test_number_that_failed = 41;
return(failure());
}
if (ascii_views[2].compare(STRING_VIEW("C")) not_eq I_AM_EQUAL_TO_THAT)
{
test_number_that_failed = 42;
return(failure());
}
if (ascii_views[3].empty() == false)
{
test_number_that_failed = 43;
return(failure());
}
test_number_that_failed = 43;
return( true );
}
| 32.168865 | 183 | 0.689304 | [
"vector"
] |
300236c2e16d5e57d1e1303275973619154f0650 | 4,940 | cpp | C++ | test/test_obj_parser.cpp | chellmuth/gpu-motunui | 1369c98408c4c59bfddff45ae00281f6463527ec | [
"MIT"
] | 139 | 2020-10-05T16:33:28.000Z | 2022-03-30T06:48:29.000Z | test/test_obj_parser.cpp | chellmuth/gpu-motunui | 1369c98408c4c59bfddff45ae00281f6463527ec | [
"MIT"
] | 1 | 2020-10-20T15:40:21.000Z | 2020-10-21T16:36:17.000Z | test/test_obj_parser.cpp | chellmuth/gpu-motunui | 1369c98408c4c59bfddff45ae00281f6463527ec | [
"MIT"
] | 5 | 2020-10-20T13:52:31.000Z | 2021-09-27T13:19:20.000Z | #include <memory>
#include <sstream>
#include <string>
#include <vector>
#include <catch2/catch.hpp>
#include <moana/parsers/obj_parser.hpp>
using namespace moana;
static std::string obj1 = R"(
g default
v 0 1 2
v 3 4 5
v 6 7 8
v 9 10 11
vn 12 13 14
vn 15 16 17
vn 18 19 20
vn 20 21 22
s 1
g mesh_name
usemtl custom_mtl
f 1//4 2//3 3//2 4//1
)";
TEST_CASE("parse a simple obj", "[obj]") {
const std::vector<std::string> mtlLookup = { "custom_mtl" };
ObjParser parser(
std::make_unique<std::istringstream>(obj1),
mtlLookup
);
auto records = parser.parse();
REQUIRE(records.size() == 1);
auto record = records[0];
std::vector<float> expectedVertices = {
0.f, 1.f, 2.f,
3.f, 4.f, 5.f,
6.f, 7.f, 8.f,
9.f, 10.f, 11.f
};
REQUIRE(record.vertices == expectedVertices);
std::vector<int> expectedVertexIndices = {
0, 1, 2,
0, 2, 3,
};
REQUIRE(record.vertexIndices == expectedVertexIndices);
std::vector<float> expectedNormals = {
12.f, 13.f, 14.f,
15.f, 16.f, 17.f,
18.f, 19.f, 20.f,
20.f, 21.f, 22.f,
};
REQUIRE(record.normals == expectedNormals);
std::vector<int> expectedNormalIndices = {
3, 2, 1,
3, 1, 0,
};
REQUIRE(record.normalIndices == expectedNormalIndices);
REQUIRE(record.indexTripletCount == 2);
REQUIRE(record.materialIndex == 0);
REQUIRE(!record.hidden);
}
static std::string obj2 = R"(
g default
v 0 1 2
v 3 4 5
v 6 7 8
v 9 10 11
vn 12 13 14
vn 15 16 17
vn 18 19 20
vn 20 21 22
s 1
g mesh_name1
usemtl custom_mtl
f 1//4 2//3 3//2 4//1
g default
v 23 24 25
v 26 27 28
v 29 30 31
v 32 33 34
vn 35 36 37
vn 38 39 40
vn 41 42 43
vn 44 45 46
s 1
g mesh_name2
usemtl custom_mtl
f 5//8 6//7 7//6 8//5
)";
TEST_CASE("parse an obj with two meshes", "[obj]") {
const std::vector<std::string> mtlLookup = { "custom_mtl" };
ObjParser parser(
std::make_unique<std::istringstream>(obj2),
mtlLookup
);
auto records = parser.parse();
REQUIRE(records.size() == 2);
{
auto record = records[0];
std::vector<float> expectedVertices = {
0.f, 1.f, 2.f,
3.f, 4.f, 5.f,
6.f, 7.f, 8.f,
9.f, 10.f, 11.f
};
REQUIRE(record.vertices == expectedVertices);
std::vector<int> expectedVertexIndices = {
0, 1, 2,
0, 2, 3,
};
REQUIRE(record.vertexIndices == expectedVertexIndices);
std::vector<float> expectedNormals = {
12.f, 13.f, 14.f,
15.f, 16.f, 17.f,
18.f, 19.f, 20.f,
20.f, 21.f, 22.f,
};
REQUIRE(record.normals == expectedNormals);
std::vector<int> expectedNormalIndices = {
3, 2, 1,
3, 1, 0,
};
REQUIRE(record.normalIndices == expectedNormalIndices);
REQUIRE(record.indexTripletCount == 2);
REQUIRE(record.materialIndex == 0);
REQUIRE(!record.hidden);
}
{
auto record = records[1];
std::vector<float> expectedVertices = {
23.f, 24.f, 25.f,
26.f, 27.f, 28.f,
29.f, 30.f, 31.f,
32.f, 33.f, 34.f,
};
REQUIRE(record.vertices == expectedVertices);
std::vector<int> expectedVertexIndices = {
0, 1, 2,
0, 2, 3,
};
REQUIRE(record.vertexIndices == expectedVertexIndices);
std::vector<float> expectedNormals = {
35.f, 36.f, 37.f,
38.f, 39.f, 40.f,
41.f, 42.f, 43.f,
44.f, 45.f, 46.f,
};
REQUIRE(record.normals == expectedNormals);
std::vector<int> expectedNormalIndices = {
3, 2, 1,
3, 1, 0,
};
REQUIRE(record.normalIndices == expectedNormalIndices);
REQUIRE(record.indexTripletCount == 2);
REQUIRE(record.materialIndex == 0);
REQUIRE(!record.hidden);
}
}
static std::string obj3 = R"(
g default
v 0 1 2
v 3 4 5
v 6 7 8
v 9 10 11
vn 12 13 14
vn 15 16 17
vn 18 19 20
vn 20 21 22
s 1
g mesh_name
usemtl hidden
f 1//4 2//3 3//2 4//1
)";
TEST_CASE("skip hidden meshes", "[obj]") {
const std::vector<std::string> mtlLookup = {};
ObjParser parser(
std::make_unique<std::istringstream>(obj3),
mtlLookup
);
auto records = parser.parse();
REQUIRE(records.size() == 0);
}
static std::string obj4 = R"(
g default
v 0 1 2
v 3 4 5
v 6 7 8
v 9 10 11
vn 12 13 14
vn 15 16 17
vn 18 19 20
vn 20 21 22
s 1
g mesh_name
f 1//4 2//3 3//2 4//1
)";
TEST_CASE("mark shadow meshes hidden (no usemtl)", "[obj]") {
const std::vector<std::string> mtlLookup = {};
ObjParser parser(
std::make_unique<std::istringstream>(obj4),
mtlLookup
);
auto records = parser.parse();
REQUIRE(records.size() == 0);
}
| 20.843882 | 64 | 0.554251 | [
"vector"
] |
30098d92c6ad58840778bb3fce5127aba1e443b4 | 3,758 | cc | C++ | tf_adapter/kernels/aicore/npu_mixed_precesion_ops.cc | fujingguo/tf_adapter_npu | 96e796fca0359b984a8504f920844ae572b5d30e | [
"Apache-2.0"
] | null | null | null | tf_adapter/kernels/aicore/npu_mixed_precesion_ops.cc | fujingguo/tf_adapter_npu | 96e796fca0359b984a8504f920844ae572b5d30e | [
"Apache-2.0"
] | null | null | null | tf_adapter/kernels/aicore/npu_mixed_precesion_ops.cc | fujingguo/tf_adapter_npu | 96e796fca0359b984a8504f920844ae572b5d30e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) Huawei Technologies Co., Ltd. 2019-2020. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tensorflow/core/framework/bounds_check.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
namespace tensorflow {
// Mixed-precisions training
class NpuAllocFloatStatusOp : public tensorflow::OpKernel {
public:
explicit NpuAllocFloatStatusOp(tensorflow::OpKernelConstruction *context) : OpKernel(context) {}
~NpuAllocFloatStatusOp() override = default;
void Compute(tensorflow::OpKernelContext *context) override {
Tensor *output_tensor = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({1}), &output_tensor));
// Set the float_status tensor to be 0
auto flat = output_tensor->flat<float>();
flat(0) = 0.0;
}
};
REGISTER_KERNEL_BUILDER(Name("NpuAllocFloatStatus").Device(tensorflow::DEVICE_CPU), NpuAllocFloatStatusOp);
class NpuGetFloatStatusOp : public tensorflow::OpKernel {
public:
explicit NpuGetFloatStatusOp(tensorflow::OpKernelConstruction *context) : OpKernel(context) {}
~NpuGetFloatStatusOp() override = default;
void Compute(tensorflow::OpKernelContext *context) override {
// Grab the input tensor
const Tensor &input_tensor = context->input(0);
// Create an output tensor
Tensor *output_tensor = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, input_tensor.shape(), &output_tensor));
// Set the float_status tensor to be 0
auto flat = output_tensor->flat<float>();
// For testing
flat(0) = 0.0;
}
};
REGISTER_KERNEL_BUILDER(Name("NpuGetFloatStatus").Device(tensorflow::DEVICE_CPU), NpuGetFloatStatusOp);
class NpuGetFloatStatusV2Op : public OpKernel {
public:
explicit NpuGetFloatStatusV2Op(OpKernelConstruction *context) : OpKernel(context) {}
~NpuGetFloatStatusV2Op() override = default;
void Compute(OpKernelContext *context) override {
LOG(INFO) << "NpuGetFloatStatusV2 Compute";
}
};
REGISTER_KERNEL_BUILDER(Name("NpuGetFloatStatusV2").Device(DEVICE_CPU), NpuGetFloatStatusV2Op);
class NpuClearFloatStatusOp : public OpKernel {
public:
explicit NpuClearFloatStatusOp(OpKernelConstruction *context) : OpKernel(context) {}
~NpuClearFloatStatusOp() override = default;
void Compute(OpKernelContext *context) override {
// Grab the input tensor
const Tensor &input_tensor = context->input(0);
auto input = input_tensor.flat<float>();
// Create an output tensor
Tensor *output_tensor = nullptr;
// Clear the status
auto flat = output_tensor->flat<float>();
// For testing
for (int i = 0; i < input.size(); i++) { flat(i) = 0.0; }
}
};
REGISTER_KERNEL_BUILDER(Name("NpuClearFloatStatus").Device(DEVICE_CPU), NpuClearFloatStatusOp);
class NpuClearFloatStatusV2Op : public OpKernel {
public:
explicit NpuClearFloatStatusV2Op(OpKernelConstruction *context) : OpKernel(context) {}
~NpuClearFloatStatusV2Op() override = default;
void Compute(OpKernelContext *context) override {
LOG(INFO) << "NpuClearFloatStatusV2 Compute";
}
};
REGISTER_KERNEL_BUILDER(Name("NpuClearFloatStatusV2").Device(DEVICE_CPU), NpuClearFloatStatusV2Op);
} // namespace tensorflow
| 38.346939 | 107 | 0.749601 | [
"shape"
] |
30148487fff3ae4d7cfb96d2974a4f3befaac935 | 853 | cpp | C++ | celebrity_problem.cpp | ujjaldas1997/Competitive-programming | f8526161b3b14056633ec290b0c65ba762e8552e | [
"MIT"
] | null | null | null | celebrity_problem.cpp | ujjaldas1997/Competitive-programming | f8526161b3b14056633ec290b0c65ba762e8552e | [
"MIT"
] | null | null | null | celebrity_problem.cpp | ujjaldas1997/Competitive-programming | f8526161b3b14056633ec290b0c65ba762e8552e | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int getId(vector<vector<int>> M)
{
//Your code here
int n = M.size();
if (n == 1)
return -1;
int i = 0, C = 1;
while (i < n and C < n) {
if (M[i][C])
i = max (C + 1, i + 1);
else
C = max (C + 1, i + 1);
}
for (int j = 0; j < n; ++j) {
if (C < n and j != C and !M[j][C])
return -1;
if (i < n and j != i and !M[j][i])
return -1;
}
return C >= n ? i : C;
}
int main()
{
vector<vector<int>> M{{0, 1, 1, 0, 0, 0},
{1, 0, 1, 1, 0, 1},
{0, 0, 0, 0, 0, 0},
{1, 0, 1, 0, 1, 0},
{1, 0, 1, 1, 0, 0},
{1, 1, 1, 1, 1, 0}};
cout << getId(M);
return 0;
}
| 23.054054 | 46 | 0.321219 | [
"vector"
] |
3018c3c05247f51a6206219e944a74b720183abe | 39,799 | cpp | C++ | src/module_functions.cpp | Robo-Wunderkind/RoboWunderkinduino | 09a01b6e417b6a8196fe152c592bf13c227d909b | [
"Apache-2.0"
] | 3 | 2022-02-08T18:38:03.000Z | 2022-02-08T19:53:01.000Z | src/module_functions.cpp | Robo-Wunderkind/RoboWunduino | 09a01b6e417b6a8196fe152c592bf13c227d909b | [
"Apache-2.0"
] | null | null | null | src/module_functions.cpp | Robo-Wunderkind/RoboWunduino | 09a01b6e417b6a8196fe152c592bf13c227d909b | [
"Apache-2.0"
] | null | null | null | /*
* modules.c
* ---------- GENERAL DESCRIPTION: ----------
*
* set module parameters, read modules sensorvalues, set/reset actions and triggers.
*/
#include "i2c_bus.h"
#include "module_handler.h"
#include "module_functions.h"
static uint8_t matrix_data_string[33];
static uint8_t matrix_string_add = 0;
bool fetch_uuid(uint8_t address, uint8_t* UUID_data)
{
uint8_t message_bytes = 32;
uint8_t data_rd[message_bytes];
uint8_t i2c_write_data[8];
i2c_write_data[0] = CMD_GET_UUID;
for(uint8_t i = 0; i < UUID_LEN; i++)
{
i2c_write_data[1] = i;
i2c_write_module(address, i2c_write_data, 8);
i2c_read_module_data(address, data_rd, 32);
UUID_data[i] = data_rd[25];
}
return true;
}
bool write_to_module(uint8_t module_type, uint8_t address, uint8_t module_index, uint8_t *data, uint8_t size_d)
{
if (check_if_attached_from_index(module_type, module_index))
{
return i2c_write_module(address, data, size_d);
}
else
{
printf("Can`t send I2C-command, address 0X%02X not attached, index %d\n", address, module_index);
}
return false;
}
uint8_t get_eeprom_module_id(uint8_t address)
{
uint8_t message_bytes = 25;
uint8_t data_rd[message_bytes];
if(i2c_read_module_data(address, data_rd, message_bytes) != 0) return data_rd[24];
else return 0xff;
}
bool set_eeprom_module_id(uint8_t address, uint8_t id)
{
uint8_t message_bytes = 3;
uint8_t data[message_bytes];
data[0] = 0x20;
data[1] = id;
vTaskDelay(100 / portTICK_PERIOD_MS);
i2c_write_module(address, data, message_bytes);
vTaskDelay(100 / portTICK_PERIOD_MS);
if(get_eeprom_module_id(address) == id)
{
//printf("I2C: Assigned new eeprom id to: %d\n", id);
return true;
}
else
{
//printf("I2C: Failed to assign new eeprom id to: %d\n", id);
return false;
}
}
bool set_zero_servo(uint8_t module_index)
{
uint8_t data[2];
data[0] = 0x12;
return write_to_module(MODULE_SERVO, (SERVO1_ADD + module_index), module_index, data, 2);
}
bool lock_hinge(uint8_t module_index)
{
uint8_t data[2];
data[0] = 0x12;
data[1] = 0x00;
return write_to_module(MODULE_HINGE, (HINGE1_ADD + module_index), module_index, data, 2);
}
bool set_hinge_torque(uint8_t module_index, int8_t speed)
{
uint8_t data[3];
float pwm = ((float)-speed/100.0)*127;
data[0] = 0x10;
data[1] = (int8_t)pwm;
return write_to_module(MODULE_HINGE, (HINGE1_ADD + module_index), module_index, data, 3);
}
bool set_hinge_position(uint8_t module_index, int8_t angle)
{
uint8_t data[3];
uint8_t set_angle = 0;
set_angle = angle + 90;
data[0] = 0x11;
data[1] = set_angle;
return write_to_module(MODULE_HINGE, (HINGE1_ADD + module_index), module_index, data, 3);
}
bool lock_claw(uint8_t module_index)
{
uint8_t data[2];
data[0] = 0x12;
data[1] = 0x00;
return write_to_module(MODULE_CLAW, (CLAW1_ADD + module_index), module_index, data, 2);
}
bool set_claw_torque(uint8_t module_index, int8_t speed)
{
uint8_t data[3];
float pwm = ((float)-speed/100.0)*127;
data[0] = 0x10;
data[1] = (int8_t)pwm;
return write_to_module(MODULE_CLAW, (CLAW1_ADD + module_index), module_index, data, 3);
}
bool claw_open_close(uint8_t module_index, bool open_close)
{
uint8_t data[3];
if(open_close) data[0] = 0x14;
else data[0] = 0x13;
data[1] = 100;
return write_to_module(MODULE_CLAW, (CLAW1_ADD + module_index), module_index, data, 3);
}
bool set_motor_pwm(uint8_t module_index, int8_t speed)
{
uint8_t data[3];
float pwm = ((float)speed/100.0)*127;
data[0] = 0x10;
data[1] = (int8_t)pwm;
return write_to_module(MODULE_MOTOR, (MOTOR1_ADD + module_index), module_index, data, 3);
}
bool set_motor_speed(uint8_t module_index, int8_t speed)
{
uint8_t data[6];
uint8_t wheel_diameterHSB = WHEEL_DIAMETER >> 8;
uint8_t wheel_diameterLSB = WHEEL_DIAMETER >> 0;
int16_t speed_ticks = (MAXVEL*(speed/100.0));
if(speed_ticks < MINVEL && speed_ticks > 0) speed_ticks = MINVEL;
if(speed_ticks > -MINVEL && speed_ticks < 0) speed_ticks = -MINVEL;
int8_t speed_HSB = speed_ticks >> 8;
int8_t speed_LSB = speed_ticks >> 0;
data[0] = 0x13;
data[1] = speed_HSB;
data[2] = speed_LSB;
data[3] = wheel_diameterHSB;
data[4] = wheel_diameterLSB;
return write_to_module(MODULE_MOTOR, (MOTOR1_ADD + module_index), module_index, data, 6);
}
bool set_motor_angle(uint8_t module_index, int16_t angle, uint8_t direction)
{
uint8_t data[8];
angle*=1.04;
int16_t speed = 150;
if(direction == 0) speed *= -1;
data[0] = 0x15;
data[1] = (int8_t)(speed >> 8);
data[2] = (int8_t)(speed >> 0);
data[3] = 0;
data[4] = 0x59;
data[5] = (int8_t)(angle >> 8);
data[6] = (int8_t)(angle >> 0);
return write_to_module(MODULE_MOTOR, (MOTOR1_ADD + module_index), module_index, data, 8);
}
bool adjust_motor_speed(uint8_t module_index, uint8_t speedHSB, uint8_t speedLSB, uint8_t wheel_diameterHSB, uint8_t wheel_diameterLSB)
{
uint8_t data[6];
int16_t speed = ((int16_t)speedHSB << 8 | (int16_t)speedLSB);
speed = speed * MOTOR_SPEED_CONVERSION_RATE;
data[0] = 0x16;
data[1] = (int8_t)(speed >> 8);
data[2] = (int8_t)(speed >> 0);
data[3] = wheel_diameterHSB;
data[4] = wheel_diameterLSB;
return write_to_module(MODULE_MOTOR, (MOTOR1_ADD + module_index), module_index, data, 6);
}
bool set_servo_position(uint8_t module_index, int8_t position)
{
uint8_t data[4];
uint16_t unsigned_pos = position * 1.5f + 120;
unsigned_pos = (unsigned_pos * (-1)) + 300;
//printf("Setting Servo to: %d\n", unsigned_pos);
data[0] = 0x10;
data[1] = (uint8_t)(unsigned_pos >> 8);
data[2] = (uint8_t)(unsigned_pos >> 0);
return write_to_module(MODULE_SERVO, (SERVO1_ADD + module_index), module_index, data, 4);
}
bool set_rgb_color(uint8_t module_index, uint8_t r, uint8_t g, uint8_t b)
{
uint8_t data[6];
data[0] = 0x10;
data[1] = r;
data[2] = g;
data[3] = b;
data[4] = 0;
return write_to_module(MODULE_RGB, (RGB1_ADD + module_index), module_index, data, 6);
}
bool calibrate_linetracker(uint8_t module_index)
{
uint8_t data[2];
data[0] = 0x13;
return write_to_module(MODULE_LINETRACKER, (LINETRACKER1_ADD + module_index), module_index, data, 2);
}
bool set_matrix_leds(uint8_t module_index, uint64_t leds)
{
uint8_t data[18];
data[0] = 0x10;
data[2] = (uint8_t)(leds >> 32);
data[4] = (uint8_t)(leds >> 40);
data[6] = (uint8_t)(leds >> 48);
data[8] = (uint8_t)(leds >> 56);
data[10] = (uint8_t)(leds >> 0);
data[12] = (uint8_t)(leds >> 8);
data[14] = (uint8_t)(leds >> 16);
data[16] = (uint8_t)(leds >> 24);
data[2] = ((data[2] & 0x0F)<<4 | (data[2] & 0xF0)>>4);
data[4] = ((data[4] & 0x0F)<<4 | (data[4] & 0xF0)>>4);
data[6] = ((data[6] & 0x0F)<<4 | (data[6] & 0xF0)>>4);
data[8] = ((data[8] & 0x0F)<<4 | (data[8] & 0xF0)>>4);
data[10] = ((data[10] & 0x0F)<<4 | (data[10] & 0xF0)>>4);
data[12] = ((data[12] & 0x0F)<<4 | (data[12] & 0xF0)>>4);
data[14] = ((data[14] & 0x0F)<<4 | (data[14] & 0xF0)>>4);
data[16] = ((data[16] & 0x0F)<<4 | (data[16] & 0xF0)>>4);
data[1] = 0;
data[3] = 0;
data[5] = 0;
data[7] = 0;
data[9] = 0;
data[11] = 0;
data[13] = 0;
data[15] = 0;
return write_to_module(MODULE_MATRIX, (MATRIX1_ADD + module_index), module_index, data, 18);
}
/*
================================================================== READ FUNCTIONS =============================================================================
*/
bool read_ultrasonic_distance(uint8_t module_index, float *distance_cm)
{
uint8_t message_bytes = 13;
uint8_t data_rd[message_bytes];
if (i2c_read_module_data(ULTRASONIC1_ADD + module_index, data_rd, message_bytes) != 0)
{
i2c_read_module_data(ULTRASONIC1_ADD + module_index, data_rd, message_bytes);
if(data_rd[1] == 255 && data_rd[2] == 255) return 255;
uint16_t distance = ((uint16_t)data_rd[1] << 8) | (uint16_t)data_rd[2];
*distance_cm = distance * ULTRASONIC_DISTANCE_CONVERSION_RATE;
return true;
}
else
{
//printf("Can`t send I2C-command, ultrasonic %d not attached\n", module_index + 1);
*distance_cm = 0;
return false;
}
}
bool read_ultrasonic_volume(uint8_t module_index, float *vol)
{
uint8_t message_bytes = 13;
uint8_t data_rd[message_bytes];
if (i2c_read_module_data(ULTRASONIC1_ADD + module_index, data_rd, message_bytes) != 0)
{
uint16_t volume = 0;
uint8_t data_rd[message_bytes];
for (uint8_t i = 0; i < 5; i++)
{
i2c_read_module_data(ULTRASONIC1_ADD + module_index, data_rd, message_bytes);
volume += ((uint16_t)data_rd[4] << 8) | data_rd[5];
}
volume /= 5;
*vol = volume * SOUNDLEVEL_CONVERSION_RATE;
return true;
}
else
{
//printf("Can`t send I2C-command, ultrasonic %d not attached\n", module_index + 1);
*vol = 0;
return false;
}
}
bool read_motor_distance(uint8_t module_index, float *distance_in_cm)
{
uint8_t message_bytes = 6;
uint8_t data_rd[message_bytes];
if (i2c_read_module_data(MOTOR1_ADD + module_index, data_rd, message_bytes) != 0)
{
uint32_t distance = (data_rd[1] << 24) | (data_rd[2] << 16) | (data_rd[3] << 8) | data_rd[4];
*distance_in_cm = distance;
return true;
}
else
{
//printf("Can`t send I2C-command, motor %d not attached\n", module_index + 1);
*distance_in_cm = 0;
return false;
}
}
bool read_pir_state(uint8_t module_index, uint8_t *pir_state)
{
uint8_t message_bytes = 3;
uint8_t data_rd[message_bytes];
if (i2c_read_module_data(PIR1_ADD + module_index, data_rd, message_bytes) != 0)
{
*pir_state = data_rd[1];
return true;
}
else
{
//printf("Can`t send I2C-command, pir %d not attached\n", module_index + 1);
*pir_state = 0;
return false;
}
}
bool read_claw_proximity(uint8_t module_index, uint8_t *prox_state)
{
uint8_t message_bytes = 16;
uint8_t data_rd[message_bytes];
if (i2c_read_module_data(CLAW1_ADD + module_index, data_rd, message_bytes) != 0)
{
*prox_state = data_rd[13];
return true;
}
else
{
//printf("Can`t send I2C-command, claw %d not attached\n", module_index + 1);
*prox_state = 0;
return false;
}
}
bool read_knob(uint8_t module_index, uint16_t *knob_reading)
{
uint8_t message_bytes = 4;
uint8_t data_rd[message_bytes];
if (i2c_read_module_data(KNOB1_ADD + module_index, data_rd, message_bytes) != 0)
{
*knob_reading = ((uint16_t)data_rd[1] << 8) | data_rd[2];
return true;
}
else
{
//printf("Unable to send I2C-command, knob %d not attached\n", module_index + 1);
*knob_reading = 0;
return false;
}
}
bool read_lightsensor(uint8_t module_index, float *light)
{
uint8_t message_bytes = 4;
uint8_t data_rd[message_bytes];
if (i2c_read_module_data(LIGHTSENSOR1_ADD + module_index, data_rd, message_bytes) != 0)
{
uint16_t lightlevel = ((uint16_t)data_rd[1] << 8) | data_rd[2];
*light = (float)lightlevel * LIGHTLEVEL_CONVERSION_RATE;
return true;
}
else
{
printf("Unable to send I2C-command, lightsensor %d not attached\n", module_index + 1);
*light = 0;
return false;
}
}
bool read_button_state(uint8_t module_index, uint8_t *button_state)
{
uint8_t message_bytes = 5;
uint8_t data_rd[message_bytes];
if (i2c_read_module_data(BUTTON1_ADD + module_index, data_rd, message_bytes) != 0)
{
*button_state = data_rd[1];
return true;
}
else
{
printf("Unable to send I2C-command, button %d not attached\n", module_index + 1);
*button_state = 0;
return false;
}
}
bool read_claw_potentiometer(uint8_t module_index, uint16_t *potentiometer)
{
uint8_t message_bytes = 16;
if (check_if_attached_from_index(CLAW, module_index))
{
uint8_t data_rd[message_bytes];
i2c_read_module_data(CLAW1_ADD + module_index, data_rd, message_bytes);
*potentiometer = ((uint16_t)data_rd[1] << 8) | data_rd[2];
return true;
}
else
{
//printf("Unable to send I2C-command, claw %d not attached\n", module_index + 1);
*potentiometer = 0;
return false;
}
}
bool read_linetracker_sensorvalues(uint8_t module_index, linetracker_sensorvalues *values, uint16_t sensor_saturation)
{
uint8_t message_bytes = 19;
uint8_t data_rd[message_bytes];
if ( i2c_read_module_data(LINETRACKER1_ADD + module_index, data_rd, message_bytes) != 0)
{
for (uint8_t i = 0; i < message_bytes; i++)
{
data_rd[i] = 0;
}
if((data_rd[1] << 8 | data_rd[2]) < sensor_saturation && (data_rd[3] << 8 | data_rd[4]) < sensor_saturation && (data_rd[5] << 8 | data_rd[6]) < sensor_saturation)
{
values->l = data_rd[1] << 8 | data_rd[2];
values->c = data_rd[3] << 8 | data_rd[4];
values->r = data_rd[5] << 8 | data_rd[6];
}
values->edge_l = data_rd[7];
values->edge_c = data_rd[8];
values->edge_r = data_rd[9];
values->bin_l = data_rd[16];
values->bin_c = data_rd[17];
values->bin_r = data_rd[18];
return true;
}
else
{
//printf("Unable to send I2C-command, linetracker %d not attached\n", module_index + 1);
return false;
}
}
bool read_gyro(uint8_t module_index, float *gyrox, float *gyroy, float *gyroz)
{
uint8_t message_bytes = 21;
uint8_t data_rd[message_bytes];
if (i2c_read_module_data(ACCELEROMETER1_ADD + module_index, data_rd, message_bytes) != 0)
{
int16_t x = (((uint16_t)data_rd[7]<<8) | data_rd[8]);
int16_t y = (((uint16_t)data_rd[9]<<8) | data_rd[10]);
int16_t z = (((uint16_t)data_rd[11]<<8) | data_rd[12]);
*gyrox = (float)x/GYROSCOPE_SENSITIVITY;
*gyroy = (float)y/GYROSCOPE_SENSITIVITY;
*gyroz = (float)z/GYROSCOPE_SENSITIVITY;
return true;
}
else
{
*gyrox = 0;
*gyroy = 0;
*gyroz = 0;
return false;
}
}
bool read_accelerometer_values(uint8_t module_index, float *accx, float *accy, float *accz)
{
uint8_t message_bytes = 21;
uint8_t data_rd[message_bytes];
if (i2c_read_module_data(ACCELEROMETER1_ADD + module_index, data_rd, message_bytes) != 0)
{
int16_t x = (((uint16_t)data_rd[1]<<8) | data_rd[2]);
int16_t y = (((uint16_t)data_rd[3]<<8) | data_rd[4]);
int16_t z = (((uint16_t)data_rd[5]<<8) | data_rd[6]);
*accx = (float)x/ACC_4G_CONV_G;
*accy = (float)y/ACC_4G_CONV_G;
*accz = (float)z/ACC_4G_CONV_G;
return true;
}
else
{
*accx = 0;
*accy = 0;
*accz = 0;
return false;
}
}
bool read_accelerometer_state(uint8_t module_index)
{
uint8_t message_bytes = 21;
uint8_t data_rd[message_bytes];
uint8_t acc_values = 0;
if (i2c_read_module_data(ACCELEROMETER1_ADD + module_index, data_rd, message_bytes) != 0)
{
if (data_rd[19] == 1) acc_values |= (1U << 0);
if (data_rd[18] == 1) acc_values |= (1U << 1);
if (data_rd[20] == 1) acc_values |= (1U << 2);
return acc_values;
}
else
{
//printf("Unable to send I2C-command, accelerometer %d not attached\n", module_index + 1);
return false;
}
}
int32_t twos_comp(uint32_t num, uint8_t bits)
{
int32_t power = pow(2, bits);
if(num > power/2.0) num = num - power;
return num;
}
bool read_gas_sensor(uint8_t module_index, uint16_t *tvoc, uint16_t *eco2, uint16_t *h2, uint16_t *ethanol)
{
uint8_t message_bytes = 14;
uint8_t data_rd[message_bytes];
if (i2c_read_module_data(WEATHER1_ADD + module_index, data_rd, message_bytes) != 0)
{
*tvoc = (((uint16_t)data_rd[5]<<8) | data_rd[6]);
*tvoc = twos_comp((int32_t)*tvoc, 16);
*eco2 = (((uint16_t)data_rd[7]<<8) | data_rd[8]);
*eco2 = twos_comp((int32_t)*eco2, 16);
*h2 = (((uint16_t)data_rd[9]<<8) | data_rd[10]);
*h2 = twos_comp((int32_t)*h2, 16);
*ethanol = (((uint16_t)data_rd[11]<<8) | data_rd[12]);
*ethanol = twos_comp((int32_t)*ethanol, 16);
return true;
}
else
{
//printf("Unable to send I2C-command, weather %d not attached\n", module_index + 1);
*tvoc = 0;
*eco2 = 0;
*h2 = 0;
*ethanol = 0;
return false;
}
}
bool read_analog_TempHum(uint8_t module_index, uint16_t *temperature, uint16_t *humidity)
{
uint8_t message_bytes = 6;
uint8_t data_rd[message_bytes];
if (i2c_read_module_data(WEATHER1_ADD + module_index, data_rd, message_bytes) != 0)
{
*humidity = (((uint16_t)data_rd[1]<<8) | data_rd[2]);
*temperature = (((uint16_t)data_rd[3]<<8) | data_rd[4]);
return true;
}
else
{
//printf("Unable to send I2C-command, weather %d not attached\n", module_index + 1);
*humidity = 0;
*temperature = 0;
return false;
}
}
bool read_spl_coef(uint8_t module_index, int16_t *c0, int16_t *c1, int32_t *c00, int16_t *c01, int32_t *c10, int16_t *c11, int16_t *c20, int16_t *c21, int16_t *c30)
{
uint8_t message_bytes = 38;
uint8_t data_rd[message_bytes];
if (i2c_read_module_data(WEATHER1_ADD + module_index, data_rd, message_bytes) != 0)
{
*c0 = (((uint16_t)data_rd[19]<<4) | ((uint16_t)data_rd[20]>>4));
*c0 = twos_comp((uint32_t)*c0, 12);
*c1 = (((uint16_t)data_rd[20]&0xF) << 8) | (uint16_t)data_rd[21];
*c1 = twos_comp((uint32_t)*c1, 12);
*c00 = ((uint32_t)data_rd[22] << 12) | ((uint32_t)data_rd[23] << 4) | ((uint32_t)data_rd[24] >> 4);
*c00 = twos_comp((uint32_t)*c00, 20);
*c10 = (((uint32_t)data_rd[24]&0xF) << 16) | ((uint32_t)data_rd[25] << 8) | ((uint32_t)data_rd[26]);
*c10 = twos_comp((uint32_t)*c10, 20);
*c01 = ((uint16_t)data_rd[27] << 8) | (uint16_t)data_rd[28];
*c01 = twos_comp((uint32_t)*c01, 16);
*c11 = ((uint16_t)data_rd[29] << 8) | (uint16_t)data_rd[30];
*c11 = twos_comp((uint32_t)*c11, 16);
*c20 = ((uint16_t)data_rd[31] << 8) | (uint16_t)data_rd[32];
*c20 = twos_comp((uint32_t)*c20, 16);
*c21 = ((uint16_t)data_rd[33] << 8) | (uint16_t)data_rd[34];
*c21 = twos_comp((uint32_t)*c21, 16);
*c30 = ((uint16_t)data_rd[35] << 8) | (uint16_t)data_rd[36];
*c30 = twos_comp((uint32_t)*c30, 16);
/*
for(uint8_t i = 0; i < 18; i ++)
{
printf("Byte %d = %d \n", 19+i, data_rd[19+i]);
}
printf("C0 = %d\n C1 = %d\n C00 = %d\n C10 = %d\n C01 = %d\n C11 = %d\n C20 = %d\n C21 = %d\n C30 = %d\n", *c0, *c1, *c00, *c10, *c01, *c11, *c20, *c21, *c30);
*/
return true;
}
else
{
//printf("Unable to send I2C-command, weather %d not attached\n", module_index + 1);
*c0 = 0;
*c1 = 0;
*c00 = 0;
*c10 = 0;
*c01 = 0;
*c11 = 0;
*c20 = 0;
*c21 = 0;
*c30 = 0;
return false;
}
}
bool read_spl(uint8_t module_index, float *temperature_sc, float *pressure_sc)
{
uint8_t message_bytes = 22;
uint8_t data_rd[message_bytes];
int32_t temperature_in = 0;
int32_t pressure_in = 0;
//float SPL_SC[8] = {524288.0, 1572864.0, 3670016.0, 7864320.0, 253952.0, 516096.0, 1040384.0, 2088960.0};
if (i2c_read_module_data(WEATHER1_ADD + module_index, data_rd, message_bytes) != 0)
{
temperature_in = ((uint32_t)data_rd[13]<<16) | ((uint32_t)data_rd[14]<<8) | (uint32_t)data_rd[15];
*temperature_sc = twos_comp((uint32_t)temperature_in, 24);
pressure_in = ((uint32_t)data_rd[16]<<16) | ((uint32_t)data_rd[17]<<8) | (uint32_t)data_rd[18];
pressure_in = twos_comp((uint32_t)pressure_in, 24);
*temperature_sc = ((float)temperature_in)/7864320.0;
*pressure_sc = ((float)pressure_in)/7864320.0;
return true;
}
else
{
//printf("Unable to send I2C-command, weather %d not attached\n", module_index + 1);
*temperature_sc = 0;
*pressure_sc = 0;
return false;
}
}
//================================================================== SET ACTION FUNCTIONS =============================================================================
bool set_motor_action(uint8_t module_index, int8_t speed, uint8_t wheel_diameterHSB, uint8_t wheel_diameterLSB, uint8_t distanceHSB, uint8_t distanceLSB)
{
uint8_t data[8];
int16_t distance = ((int16_t)distanceHSB << 8 | (int16_t)distanceLSB);
int16_t speed_ticks = (MAXVEL*(speed/100.0));
if(speed_ticks < MINVEL && speed_ticks > 0) speed_ticks = MINVEL;
if(speed_ticks > -MINVEL && speed_ticks < 0) speed_ticks = -MINVEL;
int8_t speed_HSB = speed_ticks >> 8;
int8_t speed_LSB = speed_ticks >> 0;
data[0] = 0x14;
data[1] = (int8_t)(speed_ticks >> 8);
data[2] = (int8_t)(speed_ticks >> 0);
data[3] = wheel_diameterHSB;
data[4] = wheel_diameterLSB;
data[5] = (int8_t)(distance >> 8);
data[6] = (int8_t)(distance >> 0);
return write_to_module(MODULE_MOTOR, (MOTOR1_ADD + module_index), module_index, data, 8);
}
bool set_claw_action(uint8_t module_index, bool open_close)
{
uint8_t data[4];
if(open_close) data[0] = 0x13;
else data[0] = 0x14;
data[1] = 0x64;
return write_to_module(MODULE_CLAW, (CLAW1_ADD + module_index), module_index, data, 4);
}
bool set_servo_action(uint8_t module_index, uint8_t positionHSB, uint8_t positionLSB)
{
uint8_t data[4];
int16_t signed_pos = - ((int16_t)positionHSB << 8 | (int16_t)positionLSB);
signed_pos += 180;
data[0] = 0x10;
data[1] = (int8_t)(signed_pos >> 8);
data[2] = (int8_t)(signed_pos >> 0);
return write_to_module(MODULE_SERVO, (SERVO1_ADD + module_index), module_index, data, 4);
}
bool set_rgb_action(uint8_t module_index, uint8_t r, uint8_t g, uint8_t b, uint8_t timeHSB, uint8_t timeLSB, uint8_t blinks , uint8_t pulse)
{
uint8_t data[9];
data[1] = r;
data[2] = g;
data[3] = b;
data[4] = 0;
data[5] = timeHSB;
data[6] = timeLSB;
if(pulse == 1 && blinks > 0)
{
data[0] = 0x14;
data[4] = timeHSB;
data[5] = timeLSB;
data[6] = blinks;
}
else if (blinks == 0)
{
data[0] = 0x11;
data[7] = 0;
}
else
{
data[0] = 0x12;
data[7] = blinks;
}
return write_to_module(MODULE_RGB, (RGB1_ADD + module_index), module_index, data, 9);
}
bool set_matrix_action(uint8_t module_index, uint64_t leds, uint8_t timeHSB, uint8_t timeLSB)
{
uint8_t data[20];
data[0] = 0x11;
data[2] = (uint8_t)(leds >> 32);
data[4] = (uint8_t)(leds >> 40);
data[6] = (uint8_t)(leds >> 48);
data[8] = (uint8_t)(leds >> 56);
data[10] = (uint8_t)(leds >> 0);
data[12] = (uint8_t)(leds >> 8);
data[14] = (uint8_t)(leds >> 16);
data[16] = (uint8_t)(leds >> 24);
data[2] = ((data[2] & 0x0F)<<4 | (data[2] & 0xF0)>>4);
data[4] = ((data[4] & 0x0F)<<4 | (data[4] & 0xF0)>>4);
data[6] = ((data[6] & 0x0F)<<4 | (data[6] & 0xF0)>>4);
data[8] = ((data[8] & 0x0F)<<4 | (data[8] & 0xF0)>>4);
data[10] = ((data[10] & 0x0F)<<4 | (data[10] & 0xF0)>>4);
data[12] = ((data[12] & 0x0F)<<4 | (data[12] & 0xF0)>>4);
data[14] = ((data[14] & 0x0F)<<4 | (data[14] & 0xF0)>>4);
data[16] = ((data[16] & 0x0F)<<4 | (data[16] & 0xF0)>>4);
data[1] = 0;
data[3] = 0;
data[5] = 0;
data[7] = 0;
data[9] = 0;
data[11] = 0;
data[13] = 0;
data[15] = 0;
data[17] = timeHSB;
data[18] = timeLSB;
return write_to_module(MODULE_MATRIX, (MATRIX1_ADD + module_index), module_index, data, 20);
}
bool matrix_set_string(void)
{
uint8_t modules_enum = modules_address_to_enum(matrix_string_add);
if (check_if_module_attached(modules_enum))
{
i2c_write_module(matrix_string_add, matrix_data_string, matrix_data_string[4] + 5);
}
//else printf("Can`t send I2C-command, matrix %d not attached\n", (matrix_string_add - MATRIX1_ADD));
matrix_string_add = 0;
for (uint8_t i = 0; i < 32; i++)
{
matrix_data_string[i] = 0;
}
return true;
}
bool set_matrix_string_action_0(uint8_t module_index, uint8_t text_orientation, uint8_t repeats, uint8_t scrolling_rate, uint8_t string_length, uint8_t *string)
{
matrix_string_add = MATRIX1_ADD + module_index;
uint8_t s_rate = 0;
s_rate = scrolling_rate * 24;
s_rate = 255 - s_rate;
matrix_data_string[0] = 0x12;
if (text_orientation == 1) matrix_data_string[1] = 3;
else if (text_orientation == 3) matrix_data_string[1] = 1;
else matrix_data_string[1] = text_orientation;
if (repeats > 10) matrix_data_string[2] = 255;
else matrix_data_string[2] = repeats;
matrix_data_string[3] = s_rate;
matrix_data_string[4] = string_length;
for (uint8_t i = 0; ((i < string_length) && (i < 11)); i++)
{
if ((string[i] >= ' ') && (string[i] <= '~')) matrix_data_string[i + 5] = string[i]; // char is between 0 ('space') and 126 ('~')
else matrix_data_string[i + 5] = '?';
}
if (string_length <= 11) matrix_set_string();
return true;
}
bool set_matrix_string_action_1(uint8_t string_length, uint8_t *string)
{
for (uint8_t i = 0; ((i < string_length) && (i < 32)) ; i++)
{
if ((string[i] >= ' ') && (string[i] <= '~')) matrix_data_string[i + 16] = string[i]; // char is between 0 ('space') and 126 ('~')
else matrix_data_string[i + 16] = '?';
}
return matrix_set_string();
}
bool set_animation(uint8_t module_index, uint8_t animation_num, uint8_t repeats, uint8_t reverse, uint8_t orientation, uint8_t num_frames, uint8_t frame_rateH, uint8_t frame_rateL)
{ // forward only, reverse = 0: forward and backward reverse = 1. num_frames only for custom animations (255)
uint8_t data[9];
data[0] = 0x13;
data[1] = animation_num;
data[2] = repeats;
data[3] = reverse;
data[4] = orientation;
if (animation_num == 255){ // custom case
data[5] = num_frames;
data[6] = frame_rateH;
data[7] = frame_rateL;
}
else{ // pre-programmed
data[5] = 0;
data[6] = 0;
data[7] = 0;
}
return write_to_module(MODULE_DISPLAY,(DISPLAY1_ADD + module_index), module_index, data, 9);
}
bool set_display_image(uint8_t module_index, uint8_t image, uint8_t orientation, uint8_t delayH, uint8_t delayL)
{
uint8_t data[6];
data[0] = 0x10;
data[1] = image;
data[2] = orientation;
data[3] = delayH;
data[4] = delayL;
return write_to_module(MODULE_DISPLAY,(DISPLAY1_ADD + module_index), module_index, data, 6);
}
bool load_custom_display_image(uint8_t module_index, uint8_t frame_half, uint8_t rows[])
{
uint8_t data[19];
data[0] = 0x11;
data[1] = frame_half;
if(frame_half == 1 || frame_half == 2)
{
for(int i = 0; i < 16; i++)
{
data[i+2] = rows[i];
}
}
return write_to_module(MODULE_DISPLAY,(DISPLAY1_ADD + module_index), module_index, data, 19);
}
bool set_custom_display_text(uint8_t module_index, uint8_t orientation, uint8_t total_length, uint8_t scrolling_rateH, uint8_t scrolling_rateL)
{
uint8_t data[6];
data[0] = 0x12;
data[1] = orientation;
data[2] = total_length;
data[3] = scrolling_rateH;
data[4] = scrolling_rateL;
//printf("Orientation set: %d\n", orientation);
//printf("Total Length set: %d\n", total_length);
return write_to_module(MODULE_DISPLAY,(DISPLAY1_ADD + module_index), module_index, data, 6);
}
bool load_custom_display_animation(uint8_t module_index, uint8_t frame_index, uint8_t frame_half, uint8_t frame_rows[])
{
if(frame_index >= 5)
{
//printf("Frame Index Overflow\n");
return false;
}
uint8_t data[20];
data[0] = 0x17;
data[1] = frame_index;
data[2] = frame_half;
//printf("frame_index: %d\n", frame_index);
//printf("frame_half: %d\n", frame_half);
if(frame_half == 1 || frame_half == 2){
for(int i = 0; i < 16; i++)
{
data[i+3] = frame_rows[i];
}
}
return write_to_module(MODULE_DISPLAY,(DISPLAY1_ADD + module_index), module_index, data, 20);
}
bool load_custom_text(uint8_t module_index, char chars[], uint8_t starting_index, uint8_t length)
{
uint8_t data[length + 4];
data[0] = 0x18;
data[1] = starting_index;
data[2] = length;
printf("%s\n", chars);
for(int i = 0; i < length; i++)
{
data[i+3] = chars[i];
}
return write_to_module(MODULE_DISPLAY,(DISPLAY1_ADD + module_index), module_index, data, 20);
}
/*
================================================================== TRIGGER FUNCTIONS =============================================================================
*/
bool set_distance_trigger(uint8_t module_index, uint8_t condition, uint8_t distance_in_cm)
{
uint8_t data[5];
uint16_t converted_distance = distance_in_cm / ULTRASONIC_DISTANCE_CONVERSION_RATE;
data[0] = 0x13;
data[1] = (uint8_t)(converted_distance >> 8);
data[2] = (uint8_t)(converted_distance >> 0);
if (condition == 0) data[3] = 2; // less than
else data[3] = 1; // more than
return write_to_module(MODULE_ULTRASONIC, (ULTRASONIC1_ADD + module_index), module_index, data, 5);
}
bool set_soundlevel_trigger(uint8_t module_index, uint8_t condition, uint8_t soundlevel)
{
uint8_t data[5];
uint16_t soundlevel_full = soundlevel / SOUNDLEVEL_CONVERSION_RATE;
data[0] = 0x14;
data[1] = (uint8_t)(soundlevel_full >> 8);
data[2] = (uint8_t)(soundlevel_full >> 0);
if (condition == 0) data[3] = 2; // less than
else data[3] = 1; // more than
return write_to_module(MODULE_ULTRASONIC, (ULTRASONIC1_ADD + module_index), module_index, data, 5);
}
bool set_claw_trigger(uint8_t module_index, int8_t condition)
{
uint8_t data[3];
data[0] = 0x15;
if (condition == 0) data[1] = 1; // OBJECT DETECTED
else if (condition == 1) data[1] = 2; // OBJECT ABSENSE
return write_to_module(MODULE_CLAW, (CLAW1_ADD + module_index), module_index, data, 3);
}
bool set_button_trigger(uint8_t module_index, int8_t condition)
{
uint8_t data[4];
if (condition > 0) // clicked x times
{
data[0] = 0x10;
data[1] = 6;
data[2] = condition; // condition holds number of clicks
}
else
{
data[0] = 0x10;
if (condition == 0) data[1] = 1; // pressed
else data[1] = 3; // released
}
return write_to_module(MODULE_BUTTON, (BUTTON1_ADD + module_index), module_index, data, 4);
}
bool set_light_trigger(uint8_t module_index, uint8_t condition, uint16_t lightlevel)
{
uint8_t data[5];
uint16_t lightlevel_full = lightlevel / LIGHTLEVEL_CONVERSION_RATE;
data[0] = 0x10;
data[1] = (uint8_t)(lightlevel_full >> 8);
data[2] = (uint8_t)(lightlevel_full >> 0);
if (condition == 0) data[3] = 2; // less than
else data[3] = 1; // more than
return write_to_module(MODULE_LIGHTSENSOR, (LIGHTSENSOR1_ADD + module_index), module_index, data, 5);
}
bool set_motion_trigger(uint8_t module_index, uint8_t condition)
{
uint8_t data[3];
data[0] = 0x10;
if (condition == 0) data[1] = 5; // motion
else if (condition == 1) data[1] = 4; // no motion
return write_to_module(MODULE_PIR, (PIR1_ADD + module_index), module_index, data, 3);
}
bool set_accelerometer_trigger(uint8_t module_index, uint8_t condition)
{
uint8_t data[3];
data[0] = 0x11;
if (condition == 0) data[1] = 1; // put down
else if (condition == 1) data[1] = 0; // pick up
else data[1] = 2; // movement/tilt in any direction
return write_to_module(MODULE_ACCELEROMETER, (ACCELEROMETER1_ADD + module_index), module_index, data, 3);
}
bool set_linetracker_trigger(uint8_t module_index, uint8_t condition)
{
uint8_t data[3];
data[0] = 0x15;
if (condition == 1) data[1] = 2; // no object in front of the sensor
else data[1] = 1; // object in front of the sensor
return write_to_module(MODULE_LINETRACKER, (LINETRACKER1_ADD + module_index), module_index, data, 3);
}
/*
void reset_module_i2c(uint8_t module_type, uint8_t address, uint8_t module_index, uint8_t *data)
{
uint8_t modules_enum = modules_type_and_index_to_enum(module_type, module_index);
if (check_if_module_attached(modules_enum))
{
i2c_write_module(address, data, sizeof(data));
}
else printf("Can`t send I2C-command, address %d not attached\n", address);
}
*/
bool reset_claw_trigger(uint8_t module_index)
{
uint8_t data[3];
data[0] = 0x15;
data[1] = 0x00;
return write_to_module(MODULE_CLAW, (CLAW1_ADD + module_index), module_index, data, 3);
}
bool reset_linetracker_trigger(uint8_t module_index)
{
uint8_t data[3];
data[0] = 0x16;
data[1] = 0x00;
return write_to_module(MODULE_LINETRACKER, (LINETRACKER1_ADD + module_index), module_index, data, 3);
}
bool reset_motor_encoder(uint8_t module_index)
{
uint8_t data[2];
data[0] = 0x12;
data[1] = 0x00;
return write_to_module(MODULE_MOTOR, (MOTOR1_ADD + module_index), module_index, data, 2);
}
bool reset_system(uint8_t module_index)
{
return true;
}
bool reset_mod(uint8_t module_index)
{
return true;
}
bool reset_motor(uint8_t module_index)
{
set_motor_pwm((module_index), 0);
set_drive_action_status(0);
return true;
}
bool reset_rgb(uint8_t module_index)
{
uint8_t data[2];
data[0] = 0x13;
data[1] = 0x00;
return write_to_module(MODULE_RGB, (RGB1_ADD + module_index), module_index, data, 2);
}
bool reset_claw(uint8_t module_index)
{
lock_claw(module_index);
return reset_claw_trigger(module_index);
}
bool reset_servo(uint8_t module_index)
{
//nothing
return true;
}
bool reset_servo_proper(uint8_t module_index)
{
//nothing
return true;
}
bool reset_matrix(uint8_t module_index)
{
set_matrix_action((module_index), 0, 0, 0);
set_matrix_leds((module_index), 0);
return true;
}
bool reset_button(uint8_t module_index)
{
return set_button_trigger((module_index), 0);
}
bool reset_pir(uint8_t module_index)
{
return set_motion_trigger((module_index), 0);
}
bool reset_accelerometer(uint8_t module_index)
{
uint8_t data[2];
data[0] = 0x10;
return write_to_module(MODULE_ACCELEROMETER, (ACCELEROMETER1_ADD + module_index), module_index, data, 2);
}
bool reset_ultrasonic(uint8_t module_index)
{
set_soundlevel_trigger((module_index), 0, 0);
return set_distance_trigger((module_index), 0, 0);
}
bool reset_lightsensor(uint8_t module_index)
{
return set_light_trigger((module_index), 0, 0);
}
bool reset_linetracker(uint8_t module_index)
{
return reset_linetracker_trigger(module_index);
}
bool reset_display(uint8_t module_index)
{
uint8_t data[2];
data[0] = 0x16;
data[1] = 0x00;
return write_to_module(MODULE_DISPLAY, (DISPLAY1_ADD + module_index), module_index, data, 2);
}
bool reset_hinge(uint8_t module_index)
{
return lock_hinge(module_index);
}
bool reset_knob(uint8_t module_index)
{
uint8_t data[3];
data[0] = 0x11;
data[1] = 0x00;
return write_to_module(MODULE_KNOB, (KNOB1_ADD + module_index), module_index, data, 3);
}
bool reset_weather(uint8_t module_index)
{
return true;
}
bool check_mod(uint8_t address, uint8_t enumm, int8_t action_id1, int8_t action_id2)
{
return true;
}
bool check_system(uint8_t address, uint8_t enumm, int8_t action_id1, int8_t action_id2)
{
return true;
}
bool check_motors(uint8_t address, uint8_t enumm, int8_t action_id1, int8_t action_id2)
{
uint8_t data_rd[14] = {0};
i2c_read_module_data(address, data_rd, 14);
if ((data_rd[7] == 0) && (data_rd[8] == 0) && (data_rd[9] == 0) && (data_rd[10] == 0) && (data_rd[11] == 0))
{
//printf("Motor %02X completed action %d\n", address, action_id1);
reset_modules_action_or_trigger(enumm, MODULES_FIRST_ACTION_OR_TRIGGER);
reset_drive_motors(action_id1);
return true;
}
else return false;
}
bool check_servos(uint8_t address, uint8_t enumm, int8_t action_id1, int8_t action_id2)
{
uint8_t data_rd[7] = {0};
i2c_read_module_data(address, data_rd, 7);
if (data_rd[6] == 0) return reset_modules_action_or_trigger(enumm, MODULES_FIRST_ACTION_OR_TRIGGER);
else return false;
}
bool check_rgbs(uint8_t address, uint8_t enumm, int8_t action_id1, int8_t action_id2)
{
uint8_t data_rd[6] = {0};
i2c_read_module_data(address, data_rd, 6);
if (data_rd[5] == 0) return reset_modules_action_or_trigger(enumm, MODULES_FIRST_ACTION_OR_TRIGGER);
else return false;
}
bool check_matrices(uint8_t address, uint8_t enumm, int8_t action_id1, int8_t action_id2)
{
uint8_t data_rd[22] = {0};
i2c_read_module_data(address, data_rd, 21);
if (data_rd[20] == 0) return reset_modules_action_or_trigger(enumm, MODULES_FIRST_ACTION_OR_TRIGGER);
else return false;
}
bool check_buttons(uint8_t address, uint8_t enumm, int8_t action_id1, int8_t action_id2)
{
uint8_t data_rd[3] = {0};
i2c_read_module_data(address, data_rd, 3);
if (data_rd[2] != 0) return reset_modules_action_or_trigger(enumm, MODULES_FIRST_ACTION_OR_TRIGGER);
else return false;
}
bool check_pirs(uint8_t address, uint8_t enumm, int8_t action_id1, int8_t action_id2)
{
uint8_t data_rd[8] = {0};
i2c_read_module_data(address, data_rd, 8);
if (data_rd[7] != 0) return reset_modules_action_or_trigger(enumm, MODULES_FIRST_ACTION_OR_TRIGGER);
else return false;
}
bool check_accelerometers(uint8_t address, uint8_t enumm, int8_t action_id1, int8_t action_id2)
{
uint8_t data_rd[18] = {0};
i2c_read_module_data(address, data_rd, 18);
if ((data_rd[15] != 0) || (data_rd[16] != 0) || (data_rd[17] != 0)) return reset_modules_action_or_trigger(enumm, MODULES_FIRST_ACTION_OR_TRIGGER);
}
bool check_ultrasonics(uint8_t address, uint8_t enumm, int8_t action_id1, int8_t action_id2)
{
uint8_t data_rd[12] = {0};
i2c_read_module_data(address, data_rd, 12);
if (action_id1 != ACTION_NOT_SET)
{
if (data_rd[10] != 0) return reset_modules_action_or_trigger(enumm, MODULES_FIRST_ACTION_OR_TRIGGER);
}
if (action_id2 != ACTION_NOT_SET)
{
if (data_rd[11] != 0) return reset_modules_action_or_trigger(enumm, MODULES_SECOND_ACTION_OR_TRIGGER);
}
return false;
}
bool check_lightsensors(uint8_t address, uint8_t enumm, int8_t action_id1, int8_t action_id2)
{
uint8_t data_rd[5] = {0};
i2c_read_module_data(address, data_rd, 5);
if (data_rd[3] != 0) return reset_modules_action_or_trigger(enumm, MODULES_FIRST_ACTION_OR_TRIGGER);
else return false;
}
bool check_linetrackers(uint8_t address, uint8_t enumm, int8_t action_id1, int8_t action_id2)
{
uint8_t data_rd[18] = {0};
i2c_read_module_data(address, data_rd, 18);
if (action_id1 != ACTION_NOT_SET)
{
if ((data_rd[13] != 0 ) || (data_rd[14] != 0 ) || (data_rd[15] != 0 ))
return reset_modules_action_or_trigger(enumm, MODULES_FIRST_ACTION_OR_TRIGGER);
}
/*
if (action_id2 != ACTION_NOT_SET)
{
if (get_linetracker_action_status() == 0)
reset_modules_action_or_trigger(enumm, MODULES_SECOND_ACTION_OR_TRIGGER);
}
*/
return false;
}
bool check_servo2s(uint8_t address, uint8_t enumm, int8_t action_id1, int8_t action_id2)
{
//none yet
return true;
}
bool check_displays(uint8_t address, uint8_t enumm, int8_t action_id1, int8_t action_id2)
{
uint8_t data_rd[3] = {0};
i2c_read_module_data(address, data_rd, 3);
if (data_rd[1] == 0) return reset_modules_action_or_trigger(enumm, MODULES_FIRST_ACTION_OR_TRIGGER);
else return false;
}
bool check_hinges(uint8_t address, uint8_t enumm, int8_t action_id1, int8_t action_id2)
{
uint8_t data_rd[12] = {0};
i2c_read_module_data(address, data_rd, 12);
if (data_rd[7] == 0) return reset_modules_action_or_trigger(enumm, MODULES_FIRST_ACTION_OR_TRIGGER);
else return false;
}
bool check_claws(uint8_t address, uint8_t enumm, int8_t action_id1, int8_t action_id2)
{
uint8_t data_rd[12] = {0};
i2c_read_module_data(address, data_rd, 12);
if (action_id1 != ACTION_NOT_SET)
{
if (data_rd[10] == 0) return reset_modules_action_or_trigger(enumm, MODULES_FIRST_ACTION_OR_TRIGGER);
}
if (action_id2 != ACTION_NOT_SET)
{
if (data_rd[9] != 0) return reset_modules_action_or_trigger(enumm, MODULES_SECOND_ACTION_OR_TRIGGER);
}
return false;
}
bool check_knobs(uint8_t address, uint8_t enumm, int8_t action_id1, int8_t action_id2)
{
uint8_t data_rd[12] = {0};
i2c_read_module_data(address, data_rd, 12);
if (data_rd[4] == 0) return reset_modules_action_or_trigger(enumm, MODULES_FIRST_ACTION_OR_TRIGGER);
else return false;
}
bool check_weather(uint8_t address, uint8_t enumm, int8_t action_id1, int8_t action_id2)
{
return false;
}
| 29.634401 | 181 | 0.666399 | [
"object"
] |
301dfb722500f8c7e42e44d8fa04c81cf642ff46 | 10,476 | cpp | C++ | apps/pagerank/pagerankapp.cpp | Lcrypto/graphlab | 4e525282d1c093bb8ad38e8941b87c86d6ad7ded | [
"BSD-3-Clause"
] | 26 | 2016-04-18T19:14:39.000Z | 2022-01-22T16:40:22.000Z | apps/pagerank/pagerankapp.cpp | Lcrypto/graphlab | 4e525282d1c093bb8ad38e8941b87c86d6ad7ded | [
"BSD-3-Clause"
] | null | null | null | apps/pagerank/pagerankapp.cpp | Lcrypto/graphlab | 4e525282d1c093bb8ad38e8941b87c86d6ad7ded | [
"BSD-3-Clause"
] | 21 | 2015-07-08T03:00:37.000Z | 2021-07-27T00:22:23.000Z | /*
* \author akyrola
*/
#include <cmath>
#include <cstdio>
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <graphlab.hpp>
#include "pagerankapp.hpp"
#include <graphlab/macros_def.hpp>
using namespace graphlab;
size_t memory_writes = 0;
size_t memory_reads = 0;
#define TARGET_PRECISION 1e-30
#define RANDOM_SUMRESIDUALS 1
#define SUMRESIDUALS 2
#define DEGREERESIDUALSWITHMULTIPLE 3
#define DEGREERESIDUALSNOMULTIPLE 4
bool DISABLE_ADD_TASKS = false;
int TASK_SCHEDULING_TYPE = RANDOM_SUMRESIDUALS;
float jumpweight = 0.1;
pagerank_graph * __g;
const size_t NUM_VERTICES = 1;
const size_t RANDOM_JUMP_WEIGHT = 2;
gl_types::imonitor * _listener(NULL);
//void threshold_limit_scheduler(gl_types::set_scheduler &sched);
/**** GLOBAL CONVERGENCE CALCULATOR ****/
// Calculates |Ax-x|_1
double l1_residual(gl_types::graph &g) {
unsigned int n = g.num_vertices();
double l1res = 0.0;
double l1inf = 0.0;
double l1norm = 0.0;
for(vertex_id_t vid=0; vid<n; vid++) {
vertex_data vdata = g.vertex_data(vid);
/* Calculate Ax_i */
double x = vdata.value * vdata.selfweight;
foreach(edge_id_t eid, g.in_edge_ids(vid)) {
edge_data edata = g.edge_data(eid);
x += edata.weight * edata.srcvalue;
}
// compute the jumpweight
x=jumpweight/n + (1- jumpweight)*x;
l1norm+=x;
l1res += std::fabs(x-vdata.value);
l1inf = std::max(std::fabs(x-vdata.value), l1inf);
if (std::fabs(x-vdata.value) > 1e-4) {
//printf("%lf, %lf => %lf\n", std::fabs(x-vdata->value),vdata->value,x);
}
}
printf("L1 norm = %lf\n", l1norm);
printf("|A-x|_inf = %lf\n", log(l1inf/l1norm));
return log(l1res/l1norm);
}
void pagerankapp::loadGraph(std::string filename) {
// if this is a text file
if (filename.substr(filename.length()-3,3)=="txt") {
std::ifstream fin(filename.c_str());
size_t edgecount = 0;
while(fin.good()) {
// read a line. if it begins with '#' it is a comment
std::string line;
std::getline(fin, line);
if (line[0] == '#') {
std::cout << line << std::endl;
continue;
}
// read the vertices
std::stringstream s(line);
size_t srcv, destv;
s >> srcv >> destv;
// make sure we have all the vertices we need
while (g.num_vertices() <= srcv || g.num_vertices() <= destv) {
vertex_data v;
v.value = 1.0;
v.selfweight = 0.0;
g.add_vertex(v);
}
// add the edge. BUT
// The graph has multiedges, AND selfedges.. this is unbelievably annoying
if (srcv == destv) {
// selfedge
vertex_data& v = g.vertex_data(srcv);
// we use selfweight temporarily to store the number of self edges
v.selfweight += 1.0;
}
else {
// check if the edge already exists
std::pair<bool, edge_id_t> edgefind = g.find(srcv, destv);
if (edgefind.first) {
edge_data& edata = g.edge_data(edgefind.first);
// if it does, increment the weight
edata.weight += 1.0;
}
else {
edge_data e;
e.srcvalue = 1.0;
// we use weight temporarily as a counter
e.weight = 1.0;
e.residual = 0.0;
g.add_edge(srcv, destv, e);
}
}
++edgecount;
if (edgecount % 1000000 == 0) {
std::cout << edgecount << " Edges inserted" << std::endl;
}
}
// now we have to go through the edges again and figure out the
// weights
for (vertex_id_t i = 0;i < g.num_vertices(); ++i) {
vertex_data& v = g.vertex_data(i);
// count the effective number of out edges
double weight = 0;
foreach(edge_id_t e, g.out_edge_ids(i)){
edge_data edata = g.edge_data(e);
weight += edata.weight;
}
// remember to count selfweights
weight += v.selfweight;
if (weight == 0) continue;
// now the weights should all be scaled to 1
foreach(edge_id_t e, g.out_edge_ids(i)) {
edge_data& edata = g.edge_data(e);
edata.weight /= weight;
}
v.selfweight /= weight;
}
g.finalize();
} else {
g.load(filename);
}
}
pagerankapp::pagerankapp(std::string ifile, std::string bfile, bool optimize) {
inputfile = ifile;
binoutfile = bfile;
graphoptimize=optimize;
}
pagerankapp::~pagerankapp() {
delete graphlab;
}
void pagerankapp::start() {
loadGraph(inputfile);
if (binoutfile.length() > 0) {
g.save(binoutfile);
}
std::cout << "Graph has " << g.num_vertices() << " vertices and "
<< g.num_edges() << " edges." <<std::endl;
const size_t NUM_VERTICES = 1;
const size_t RANDOM_JUMP_WEIGHT = 2;
size_t numv = g.num_vertices();
// Set register shared data
gl_types::thread_shared_data sdm;
sdm.set_constant(NUM_VERTICES, numv);
sdm.set_constant(RANDOM_JUMP_WEIGHT, jumpweight);
graphlab = create_engine(&g, NULL);
// Hack
__g = &g;
if (opts.extra == "indegree_multiple") {
printf(" ==== Using indegree multiple in residual computation ====\n");
TASK_SCHEDULING_TYPE = DEGREERESIDUALSWITHMULTIPLE;
} else if (opts.extra == "simple_residual") {
printf(" ==== Using simple degree residuals ====\n");
TASK_SCHEDULING_TYPE = DEGREERESIDUALSNOMULTIPLE;
}
// register shared data
graphlab->set_shared_data_manager(&sdm);
_listener = this->listener;
for(vertex_id_t vid=0; vid<g.num_vertices(); vid+=100000) {
vertex_data vdata = g.vertex_data(vid);
printf("%d, log:%lf\n ", vid, log(vdata.value));
}
timer t2;
t2.start();
if (typeid(*graphlab) == typeid(synchronous_engine<gl_types::graph>)) {
((synchronous_engine<gl_types::graph>*)(graphlab))->
set_update_function(pagerank_function);
} else {
graphlab->get_scheduler().set_option(scheduler_options::UPDATE_FUNCTION,
(void*)pagerank_function);
// graphlab->get_scheduler().set_update_function(pagerank_function);
// Removed by Aapo: this will not use the sorting. TODO: use sorting
/* for (size_t i = 0;i < g.num_vertices(); ++i) {
if (g.in_edge_ids(i).size() > 0 || g.out_edge_ids(i).size() > 0 ) {
graphlab->get_scheduler().add_task(update_task(i, pagerank_function), 1000.0);
++numvertices;
}
}
std::cout << "Effective num vertices = " << numvertices << std::endl;
*/
// Special handling for set scheduler.
// if (opts.scheduler == "set") {
// DISABLE_ADD_TASKS = true;
//
// /* Set residuals to quick start set scheduler */
// for (size_t i = 0;i < g.num_vertices(); ++i) {
// if (g.in_edge_ids(i).size() > 0) {
// edge_data * edata =
// g.edge_data(g.in_edge_ids(i)[0]).as_ptr<edge_data>();
// edata->residual = 1000.0;
// }
// }
// ((gl_types::set_scheduler&)graphlab->get_scheduler()).
// begin_schedule(threshold_limit_scheduler);
// }
graphlab->get_scheduler().add_task_to_all(pagerank_function, 1000.0);
}
// if (opts.scheduler == "linear_twophase") {
// std::cout << "Use twophase threshold scheduler, main threshold=" << TARGET_PRECISION << std::endl;
// TASK_SCHEDULING_TYPE = SUMRESIDUALS;
// /* Set higher thresholds that are 1e-4*outdegree. I.e, lower outdegree vertices will be scheduled
// earlier. */
// for (size_t i = 0; i < g.num_vertices(); ++i) {
// if (g.out_edge_ids(i).size() > 0)
// ((linear_twophase_scheduler&)graphlab->get_scheduler()).
// set_vertex_higher_threshold(i, TARGET_PRECISION*g.out_edge_ids(i).size());
// }
// ((linear_twophase_scheduler&) graphlab->get_scheduler()).set_threshold(TARGET_PRECISION);
// std::cout << "Succesfully set vertex-specific lower thresholds" << std::endl;
// }
// if (opts.scheduler == "linear_threshold") {
// std::cout << "Use linear threshold scheduler = sum residuals" << std::endl;
// assert(TASK_SCHEDULING_TYPE == RANDOM_SUMRESIDUALS);
// TASK_SCHEDULING_TYPE = SUMRESIDUALS;
// ((linear_threshold_scheduler&) graphlab->get_scheduler()).set_threshold(TARGET_PRECISION);
// }
printf("Add tasks: %lf\n", t2.current_time());
timer t;
t.start();
/* Start */
exec_status status = graphlab->start();
float runtime = t.current_time();
printf("Finished in %lf (status: %d)\n", runtime, (int)status);
/* Output in Matlab copypasteable format */
for(vertex_id_t vid=0; vid<g.num_vertices(); vid+=100000) {
vertex_data vdata = g.vertex_data(vid);
printf("%d, log:%lf\n ", vid, log(vdata.value));
}
printf("Runtime %f\n", runtime);
/* Output l1 residual for benchmark */
write_benchmark_value("residual", l1_residual(g));
write_benchmark_value("memory_writes_mb", memory_writes * 1.0 / 1024.0/1024.0);
write_benchmark_value("memory_reads_mb", memory_reads * 1.0 / 1024.0/1024.0);
}
/**** SET SCHEDULER STUFF ****/
bool compute_vertex_priority(graphlab::vertex_id_t v,
gl_types::iscope& scope,
bool& reschedule) {
// Get the vertex data
float sumresidual = 0.0;
foreach(graphlab::edge_id_t edgeid, scope.in_edge_ids()) {
//Sum residuals of each edge
const edge_data edata =
scope.edge_data(edgeid);
sumresidual =+ edata.residual;
}
return (sumresidual >= TARGET_PRECISION);
}
// void threshold_limit_scheduler(gl_types::set_scheduler &sched) {
// // All sets must be created before scheduling calls
// printf("==== Set Scheduler =====\n");
// gl_types::ivertex_set &vs1 = sched.attach(gl_types::rvset(compute_vertex_priority),sched.root_set());
// sched.init();
// sched.execute_rep(vs1, pagerank_function);
// }
/**** ANALYZER FUNCTIONS ****/
/* Writes current graph L1 norm and max value */
std::vector<double> pagerankdumper(gl_types::graph &g) {
double l1res = l1_residual(g);
std::vector<double> v;
v.push_back(l1res);
return v;
}
/* Used with analyzer_listener */
global_dumper pagerankapp::dump_function() {
// return pagerankdumper;
return NULL;
}
std::vector<std::string> pagerankapp::dump_headers() {
std::vector<std::string> h;
h.push_back("l1_residual");
return h;
}
int pagerankapp::dump_frequency() {
return 200000; // Every 200000 updates
}
| 28.622951 | 111 | 0.622089 | [
"vector"
] |
301f49934b66ba9bcf588225c2d4cb19e9b1b95f | 15,827 | cpp | C++ | src/nanoforth_asm.cpp | chochain/nanoFORTH | bdda77f602cf6d5da5e91466e4c36048a06ea809 | [
"MIT"
] | 3 | 2021-07-10T02:12:46.000Z | 2022-03-05T18:36:43.000Z | src/nanoforth_asm.cpp | chochain/nanoFORTH | bdda77f602cf6d5da5e91466e4c36048a06ea809 | [
"MIT"
] | null | null | null | src/nanoforth_asm.cpp | chochain/nanoFORTH | bdda77f602cf6d5da5e91466e4c36048a06ea809 | [
"MIT"
] | null | null | null | /**
* @file nanoforth_asm.cpp
* @brief nanoForth Assmebler implementation
*
* ####Assembler Memory Map:
*
* @code
* mem[...dic_sz...[...stk_sz...]
* | |
* +-dic--> <--rp-+
* @endcode
*/
#include "nanoforth_asm.h"
#if ARDUINO
#include <EEPROM.h>
#endif //ARDUINO
///
///@name nanoForth built-in vocabularies
///
/// @var CMD
/// @brief words for interpret mode.
/// @var JMP (note: ; is hardcoded at position 0, do not change it)
/// @brief words for branching op in compile mode.
/// @var PRM
/// @brief primitive words (45 allocated, 64 max).
/// @var PMX
/// @brief loop control opcodes
///
///@{
PROGMEM const char CMD[] = "\x06" \
": " "VAR" "CST" "FGT" "DMP" "BYE";
PROGMEM const char JMP[] = "\x0b" \
"; " "IF " "ELS" "THN" "BGN" "UTL" "WHL" "RPT" "FOR" "NXT" \
"I ";
PROGMEM const char PRM[] = "\x31" \
"DRP" "DUP" "SWP" "OVR" "ROT" "+ " "- " "* " "/ " "MOD" \
"NEG" "AND" "OR " "XOR" "NOT" "= " "< " "> " "<= " ">= " \
"<> " "@ " "! " "C@ " "C! " "KEY" "EMT" "CR " ". " ".\" "\
">R " "R> " "WRD" "HRE" "CEL" "ALO" "SAV" "LD " "TRC" "CLK" \
"D+ " "D- " "DNG" "DLY" "IN " "AIN" "OUT" "PWM" "PIN";
PROGMEM const char PMX[] = "\x4" \
"FOR" "NXT" "BRK" "I ";
constexpr U16 OP_SEMI = 0; /**< semi-colon, end of function definition */
///@}
///
///@name Branching
///@{
#define JMP000(p,j) SET16(p, (j)<<8)
#define JMPSET(idx, p1) do { \
U8 *p = PTR(idx); \
U8 f8 = *(p); \
U16 a = IDX(p1); \
SET16(p, (a | (U16)f8<<8)); \
} while(0)
#define JMPBCK(idx, f) SET16(here, (idx) | ((f)<<8))
///@}
///
///@name Stack Ops (note: rp grows downward)
///@{
#define RPUSH(a) (*(rp++)=(U16)(a)) /**< push address onto return stack */
#define RPOP() (*(--rp)) /**< pop address from return stack */
///@}
///
///@name Dictionary Index <=> Pointer Converter
///@{
#define PTR(n) ((U8*)dic + (n)) /**< convert dictionary index to a memory pointer */
#define IDX(p) ((U16)((U8*)(p) - dic)) /**< convert memory pointer to a dictionary index */
///@}
///
///> Assembler Object initializer
///
N4Asm::N4Asm(U8 *mem) : dic(mem)
{
reset();
}
///
///> reset internal pointers (called by VM::reset)
///
void N4Asm::reset()
{
here = dic; // rewind to dictionary base
last = PTR(0xffff); // -1
tab = 0;
set_trace(0);
}
///
///> parse given token into actionable item
///
N4OP N4Asm::parse_token(U8 *tkn, U16 *rst, U8 run)
{
if (query(tkn, rst)) return TKN_DIC; /// * DIC - is a word in dictionary? [adr(2),name(3)]
if (find(tkn, run ? CMD : JMP, rst)) return TKN_IMM; /// * IMM - is a immediate word?
if (find(tkn, PRM, rst)) return TKN_PRM; /// * PRM - is a primitives?
if (number(tkn, (S16*)rst)) return TKN_NUM; /// * NUM - is a number literal?
return TKN_ERR; /// * ERR - unknown token
}
///
///> create word onto dictionary
///
void N4Asm::compile(U16 *rp0)
{
rp = rp0; // set return stack pointer
U8 *l0 = last, *h0 = here;
U8 *p0 = here;
U8 trc = is_tracing();
_do_header(); /// **fetch token, create name field linked to previous word**
for (U8 *tkn=p0; tkn;) { ///> loop til token exausted (tkn==NULL)
U16 tmp;
if (trc) d_mem(dic, p0, (U16)(here-p0), 0); ///>> trace assember progress if enabled
tkn = token();
p0 = here; // keep current top of dictionary (for memdump)
switch(parse_token(tkn, &tmp, 0)) { ///>> **determinie type of operation, and keep opcode in tmp**
case TKN_IMM: ///>> an immediate command?
if (tmp==OP_SEMI) { /// * handle return i.e. ; (semi-colon)
SET8(here, PFX_RET); // terminate COLON definitions, or
tkn = NULL; // clear token to exit compile mode
}
else _do_branch(tmp); /// * add branching opcode
break;
case TKN_DIC: ///>> a dictionary word? [addr + adr(2) + name(3)]
JMPBCK(tmp+2+3, PFX_CALL); /// * call subroutine
break;
case TKN_PRM: ///>> a built-in primitives?
SET8(here, PFX_PRM | (U8)tmp); /// * add found primitive opcode
if (tmp==I_DQ) _do_str(); /// * do extra, if it's a ." (dot_string) command
break;
case TKN_NUM: ///>> a literal (number)?
if (tmp < 128) {
SET8(here, (U8)tmp); /// * 1-byte literal, or
}
else {
SET8(here, PFX_PRM | I_LIT);/// * 3-byte literal
SET16(here, tmp);
}
break;
default: ///>> then, token type not found
flash("?? ");
last = l0; /// * restore last, here pointers
here = h0;
token(TIB_CLR);
tkn = NULL; /// * bail, terminate loop!
}
}
///> debug memory dump
if (trc && last>l0) d_mem(dic, last, (U16)(here-last), ' ');
}
///
///> create a variable on dictionary
/// * note: 8 or 10-byte per variable
///
void N4Asm::variable()
{
_do_header(); /// **fetch token, create name field linked to previous word**
U8 tmp = IDX(here+2); // address to variable storage
if (tmp < 128) { ///> handle 1-byte address + RET(1)
SET8(here, (U8)tmp);
}
else {
tmp += 2; ///> or, extra bytes for 16-bit address
SET8(here, PFX_PRM | I_LIT);
SET16(here, tmp);
}
SET8(here, PFX_RET);
SET16(here, 0); /// add actual literal storage area
}
///
///> create a constant on dictionary
/// * note: 8 or 10-byte per variable
///
void N4Asm::constant(S16 v)
{
_do_header(); /// **fetch token, create name field linked to previous word**
if (v < 128) { ///> handle 1-byte constant
SET8(here, (U8)v);
}
else {
SET8(here, PFX_PRM | I_LIT); ///> or, constant stored as 3-byte literal
SET16(here, v);
}
SET8(here, PFX_RET);
}
///
///> scan the keyword through dictionary linked-list
/// @return
/// 1 - token found<br/>
/// 0 - token not found
///
U8 N4Asm::query(U8 *tkn, U16 *adr)
{
for (U8 *p=last; p!=PTR(0xffff); p=PTR(GET16(p))) {
if (uc(p[2])==uc(tkn[0]) &&
uc(p[3])==uc(tkn[1]) &&
(p[3]==' ' || uc(p[4])==uc(tkn[2]))) {
*adr = IDX(p);
return 1;
}
}
return 0;
}
///
///> display words in dictionary
///
constexpr U8 WORDS_PER_ROW = 20; ///< words per row when showing dictionary
void N4Asm::words()
{
U8 trc = is_tracing();
U8 n = 0, wpr = WORDS_PER_ROW >> (trc ? 1 : 0);
for (U8 *p=last; p!=PTR(0xffff); p=PTR(GET16(p))) { /// **from last, loop through dictionary**
if (trc) { d_adr(IDX(p)); d_chr(':'); } ///>> optionally show address
d_chr(p[2]); d_chr(p[3]); d_chr(p[4]); d_chr(' '); ///>> 3-char name + space
if ((++n%wpr)==0) d_chr('\n'); ///>> linefeed for every WORDS_PER_ROW
}
_list_voc(); ///> list built-in vocabularies
}
///
///> drop words from the dictionary
///
void N4Asm::forget()
{
U16 adr;
if (!query(token(), &adr)) { /// check if token is in dictionary
flash("?! "); /// * not found, bail
return;
}
///
/// word found, rollback here
///
U8 *p = PTR(adr); // address of word
last = PTR(GET16(p)); /// * reset last word address
here = p; /// * reset current pointer
}
///
///> persist dictionary from RAM into EEPROM
///
constexpr U16 N4_SIG = (((U16)'N'<<8)+(U16)'4'); ///< EEPROM signature
constexpr U16 ROM_HDR = 6; ///< EEPROM header size
void N4Asm::save()
{
U8 trc = is_tracing();
U16 here_i = IDX(here);
if (trc) flash("dic>>ROM ");
#if ARDUINO
U16 last_i = IDX(last);
///
/// verify EEPROM capacity to hold user dictionary
///
if ((ROM_HDR + here_i) > EEPROM.length()) {
flash("ERROR: dictionary larger than EEPROM");
return;
}
///
/// create EEPROM dictionary header
///
EEPROM.update(0, N4_SIG>>8); EEPROM.update(1, N4_SIG&0xff);
EEPROM.update(2, last_i>>8); EEPROM.update(3, last_i&0xff);
EEPROM.update(4, here_i>>8); EEPROM.update(5, here_i&0xff);
///
/// copy user dictionary into EEPROM byte-by-byte
///
U8 *p = dic;
for (int i=0; i<here_i; i++) {
EEPROM.update(ROM_HDR+i, *p++);
}
#endif //ARDUINO
if (trc) {
d_num(here_i);
flash(" bytes saved\n");
}
}
///
///> restore dictionary from EEPROM into RAM
///
void N4Asm::load()
{
U8 trc = is_tracing();
if (trc) flash("dic<<ROM ");
#if ARDUINO
///
/// validate EEPROM contains user dictionary (from previous run)
///
U16 n4 = ((U16)EEPROM.read(0)<<8) + EEPROM.read(1);
if (n4 != N4_SIG) return; // not intialized yet
///
/// retrieve metadata (sizes) of user dicationary
///
U16 last_i = ((U16)EEPROM.read(2)<<8) + EEPROM.read(3);
U16 here_i = ((U16)EEPROM.read(4)<<8) + EEPROM.read(5);
///
/// retrieve user dictionary byte-by-byte into memory
///
U8 *p = dic;
for (int i=0; i<here_i; i++) {
*p++ = EEPROM.read(ROM_HDR+i);
}
///
/// adjust user dictionary pointers
///
last = PTR(last_i);
here = PTR(here_i);
if (trc) {
d_num(here_i);
flash(" bytes loaded\n");
}
#endif //ARDUINO
}
///
///> execution tracer (debugger, can be modified into single-stepper)
///
void N4Asm::trace(U16 a, U8 ir)
{
if (!is_tracing()) return; ///> check tracing flag
d_adr(a); // opcode address
U8 *p, op = ir & CTL_BITS;
switch (op) {
case 0xc0: ///> is a jump instruction?
a = GET16(PTR(a)) & ADR_MASK; // target address
switch (ir & JMP_MASK) { // get branching opcode
case PFX_CALL: // 0xc0 CALL word call
d_chr(':');
p = PTR(a)-3; // backtrack 3-byte (name field)
d_chr(*p++); d_chr(*p++); d_chr(*p);
flash("\n....");
for (int i=0, n=++tab; i<n; i++) { // indentation per call-depth
flash(" ");
}
break;
case PFX_RET: // 0xd0 RET return
d_chr(';');
tab -= tab ? 1 : 0;
break;
case PFX_CDJ: d_chr('?'); d_adr(a); break; // 0xe0 CDJ conditional jump
case PFX_UDJ: d_chr('j'); d_adr(a); break; // 0xf0 UDJ unconditional jump
}
break;
case 0x80: ///> is a primitive?
op = ir & PRM_MASK; // capture primitive opcode
switch (op) {
case I_LIT: // 3-byte literal (i.e. 16-bit signed integer)
d_chr('#');
p = PTR(a)+1; // address to the 16-bit number
a = GET16(p); // fetch the number (reuse a, bad, but to save)
d_u8(a>>8); d_u8(a&0xff);
break;
case I_DQ: // print string
d_chr('"');
p = PTR(a)+1; // address to string header
d_str(p); // print the string to console
break;
default: // other opcodes
d_chr('_');
U8 ci = op >= I_FOR; // loop controller flag
d_name(ci ? op-I_FOR : op, ci ? PMX : PRM, 0);
}
break;
default: ///> and a number (i.e. 1-byte literal)
d_chr('#'); d_u8(ir);
}
d_chr(' ');
}
///
///> create name field with link back to previous word
///
void N4Asm::_do_header()
{
U8 *tkn = token(); ///#### fetch one token from console
U16 tmp = IDX(last); // link to previous word
last = here; ///#### create 3-byte name field
SET16(here, tmp); // pointer to previous word
SET8(here, tkn[0]); // store token into 3-byte name field
SET8(here, tkn[1]);
SET8(here, tkn[1]!=' ' ? tkn[2] : ' ');
}
///
///> create branching for instructions
///>> f IF...THN, f IF...ELS...THN
///>> BGN...f UTL, BGN...f WHL...RPT, BGN...f WHL...f UTL
///>> n1 n0 FOR...NXT
///
void N4Asm::_do_branch(U8 op)
{
switch (op) {
case 1: /* IF */
RPUSH(IDX(here)); // save current here A1
JMP000(here, PFX_CDJ); // alloc addr with jmp_flag
break;
case 2: /* ELS */
JMPSET(RPOP(), here+2); // update A1 with next addr
RPUSH(IDX(here)); // save current here A2
JMP000(here, PFX_UDJ); // alloc space with jmp_flag
break;
case 3: /* THN */
JMPSET(RPOP(), here); // update A2 with current addr
break;
case 4: /* BGN */
RPUSH(IDX(here)); // save current here A1
break;
case 5: /* UTL */
JMPBCK(RPOP(), PFX_CDJ); // conditional jump back to A1
break;
case 6: /* WHL */
RPUSH(IDX(here)); // save WHILE addr A2
JMP000(here, PFX_CDJ); // allocate branch addr A2 with jmp flag
break;
case 7: /* RPT */
JMPSET(RPOP(), here+2); // update A2 with next addr
JMPBCK(RPOP(), PFX_UDJ); // unconditional jump back to A1
break;
case 8: /* FOR */
RPUSH(IDX(here+1)); // save current addr A1
SET8(here, PFX_PRM | I_FOR); // encode FOR opcode
break;
case 9: /* NXT */
SET8(here, PFX_PRM | I_NXT); // encode NXT opcode
JMPBCK(RPOP(), PFX_CDJ); // conditionally jump back to A1
SET8(here, PFX_PRM | I_BRK); // encode BRK opcode
break;
case 10: /* I */
SET8(here, PFX_PRM | I_I); // fetch loop counter
break;
}
}
///
///> display the opcode name
///
void N4Asm::_do_str()
{
U8 *p0 = token(); // get string from input buffer
U8 sz = 0;
for (U8 *p=p0; *p!='"'; p++, sz++);
SET8(here, sz);
for (int i=0; i<sz; i++) SET8(here, *p0++);
}
///
///> list words in built-in vocabularies
///
void N4Asm::_list_voc()
{
const char *lst[] PROGMEM = { PRM, JMP, CMD }; // list of built-in primitives
for (U8 i=0, n=0; i<3; i++) {
#if ARDUINO
U8 sz = pgm_read_byte(reinterpret_cast<PGM_P>(lst[i]));
#else
U8 sz = *(lst[i]);
#endif //ARDUINO
while (sz--) {
d_chr(n++%WORDS_PER_ROW ? ' ' : '\n');
d_name(sz, lst[i], 1);
}
}
d_chr('\n');
}
| 34.036559 | 110 | 0.463512 | [
"object"
] |
3022625e270c29996f49b0c0a2b7d38a3002500c | 8,352 | cpp | C++ | turtlebot3_autorace_camera/src/nodelet/projection_nodelet.cpp | ygjukim/turtlebot3_autorace | 1b945c087d0e8874ad8c8ec54791ff3a6b482fa7 | [
"Apache-2.0"
] | null | null | null | turtlebot3_autorace_camera/src/nodelet/projection_nodelet.cpp | ygjukim/turtlebot3_autorace | 1b945c087d0e8874ad8c8ec54791ff3a6b482fa7 | [
"Apache-2.0"
] | null | null | null | turtlebot3_autorace_camera/src/nodelet/projection_nodelet.cpp | ygjukim/turtlebot3_autorace | 1b945c087d0e8874ad8c8ec54791ff3a6b482fa7 | [
"Apache-2.0"
] | null | null | null | #include <boost/version.hpp>
#if ((BOOST_VERSION / 100) % 1000) >= 53
#include <boost/thread/lock_guard.hpp>
#endif
#include <ros/ros.h>
#include <nodelet/nodelet.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <dynamic_reconfigure/server.h>
#include <turtlebot3_autorace_camera/ImageProjectionParamsConfig.h>
namespace image_projection {
class ImageProjectionNodelet : public nodelet::Nodelet
{
// ROS communication
boost::shared_ptr<image_transport::ImageTransport> it_;
boost::mutex connect_mutex_;
image_transport::Publisher pub_project_;
image_transport::Publisher pub_calibrate_;
image_transport::Subscriber sub_image_;
int queue_size_;
// Dynamic reconfigure
boost::recursive_mutex config_mutex_;
typedef turtlebot3_autorace_camera::ImageProjectionParamsConfig Config;
typedef dynamic_reconfigure::Server<Config> ReconfigureServer;
boost::shared_ptr<ReconfigureServer> reconfigure_server_;
// Config config_;
// Parameters
bool is_calibration_mode; // unused in nodelet
int top_x, top_y, bottom_x, bottom_y;
virtual void onInit();
void connectCB();
void disconnectCB();
void imageCB(const sensor_msgs::ImageConstPtr& image_msg);
void configCB(Config &config, uint32_t level);
};
void ImageProjectionNodelet::onInit()
{
// Get NodeHandles
ros::NodeHandle &nh = getNodeHandle();
ros::NodeHandle &private_nh = getPrivateNodeHandle();
it_.reset(new image_transport::ImageTransport(nh));
// Read parameters
private_nh.param("queue_size", queue_size_, 5);
private_nh.param("is_extrinsic_camera_calibration_mode", is_calibration_mode, false);
NODELET_INFO("[Image Projection] queue_size = %d", queue_size_);
NODELET_INFO("[Image Projection] is_calibration_mode = %s", (is_calibration_mode?"True":"False"));
private_nh.param("camera/extrinsic_camera_calibration/top_x", top_x, 75);
private_nh.param("camera/extrinsic_camera_calibration/top_y", top_y, 35);
private_nh.param("camera/extrinsic_camera_calibration/bottom_x", bottom_x, 165);
private_nh.param("camera/extrinsic_camera_calibration/bottom_y", bottom_y, 120);
NODELET_INFO("[Image Projection] top_x: %d, top_y: %d, bottom_x: %d, bottom_y: %d",
top_x, top_y, bottom_x, bottom_y);
// Set up dynamic reconfigure
if (is_calibration_mode) {
reconfigure_server_.reset(new ReconfigureServer(config_mutex_, private_nh));
ReconfigureServer::CallbackType f = boost::bind(&ImageProjectionNodelet::configCB, this, _1, _2);
reconfigure_server_->setCallback(f);
}
// Initialize image-transport publisher
// Monitor whether anyone is subscribed to the output
image_transport::SubscriberStatusCallback connect_cb = boost::bind(&ImageProjectionNodelet::connectCB, this);
image_transport::SubscriberStatusCallback disconnect_cb = boost::bind(&ImageProjectionNodelet::disconnectCB, this);
// Make sure we don't enter connectCb() between advertising and assigning to pub_rect_
boost::lock_guard<boost::mutex> lock(connect_mutex_);
pub_project_ = it_->advertise("image_output", 1, connect_cb, disconnect_cb);
pub_calibrate_ = it_->advertise("image_calib", 1, connect_cb, disconnect_cb);
}
void ImageProjectionNodelet::connectCB()
{
boost::lock_guard<boost::mutex> lock(connect_mutex_);
if (!sub_image_) {
NODELET_INFO("[Image Projection] Activate image subscriber...");
image_transport::TransportHints hints("raw", ros::TransportHints(), getPrivateNodeHandle());
sub_image_ = it_->subscribe("image_input", queue_size_, &ImageProjectionNodelet::imageCB, this, hints);
}
}
void ImageProjectionNodelet::disconnectCB()
{
boost::lock_guard<boost::mutex> lock(connect_mutex_);
if (pub_project_.getNumSubscribers() == 0) {
if ((is_calibration_mode == false) ||
(is_calibration_mode == true && pub_calibrate_.getNumSubscribers() == 0))
{
NODELET_INFO("[Image Projection] Shutdown image subscriber...");
sub_image_.shutdown();
}
}
}
void ImageProjectionNodelet::imageCB(const sensor_msgs::ImageConstPtr& image_msg)
{
int hist_size = 255;
double min_gray, max_gray;
double alpha = 0, beta = 0;
cv_bridge::CvImagePtr cv_ptr;
try {
cv_ptr = cv_bridge::toCvCopy(image_msg, "bgr8");
}
catch (cv_bridge::Exception& e) {
NODELET_ERROR("cv_bridge exception: %s", e.what());
return;
}
const cv::Mat cv_image_origin = cv_ptr->image;
// {
// boost::lock_guard<boost::recursive_mutex> lock(config_mutex_);
// top_x = config_.top_x;
// top_y = config_.top_y;
// bottom_x = config_.bottom_x;
// bottom_y = config_.bottom_y;
// }
if (is_calibration_mode) {
cv::Mat cv_image_calib;
cv_image_origin.copyTo(cv_image_calib);
cv::Scalar color = cv::Scalar(0, 0, 255);
int thichness = 1;
cv::line(cv_image_calib, cv::Point(160 - top_x, 180 - top_y), cv::Point(160 + top_x, 180 - top_y), color, thichness);
cv::line(cv_image_calib, cv::Point(160 - bottom_x, 120 + bottom_y), cv::Point(160 + bottom_x, 120 + bottom_y), color, thichness);
cv::line(cv_image_calib, cv::Point(160 + bottom_x, 120 + bottom_y), cv::Point(160 + top_x, 180 - top_y), color, thichness);
cv::line(cv_image_calib, cv::Point(160 - bottom_x, 120 + bottom_y), cv::Point(160 - top_x, 180 - top_y), color, thichness);
sensor_msgs::ImagePtr calib_msg = cv_bridge::CvImage(image_msg->header, "bgr8", cv_image_calib).toImageMsg();
pub_calibrate_.publish(calib_msg);
}
// cv_image_origin.copyTo(cv_image_projected);
// adding Gaussian blur to the image of original
// cv::GaussianBlur(cv_image_projected, cv_image_projected, cv::Size(5, 5), 0);
cv::GaussianBlur(cv_image_origin, cv_image_origin, cv::Size(5, 5), 0);
// homography transform process
// selecting 4 points from the original image
std::vector<cv::Point2f> pts_src;
pts_src.push_back(cv::Point2f(160 - top_x, 180 - top_y));
pts_src.push_back(cv::Point2f(160 + top_x, 180 - top_y));
pts_src.push_back(cv::Point2f(160 + bottom_x, 120 + bottom_y));
pts_src.push_back(cv::Point2f(160 - bottom_x, 120 + bottom_y));
// selecting 4 points from image that will be transformed
std::vector<cv::Point> pts_dst;
pts_dst.push_back(cv::Point2f(200, 0));
pts_dst.push_back(cv::Point2f(800, 0));
pts_dst.push_back(cv::Point2f(800, 600));
pts_dst.push_back(cv::Point2f(200, 600));
// finding homography matrix
cv::Mat h = cv::findHomography(pts_src, pts_dst);
// homography process
cv::Mat cv_image_projected;
cv::warpPerspective(cv_image_origin, cv_image_projected, h, cv::Size(1000, 600));
// fill the empty space with black triangles on left and right side of bottom
cv::Point triangles[][3] = {
{ cv::Point(0, 599), cv::Point(0, 340), cv::Point(200, 599)},
{ cv::Point(999, 599), cv::Point(999, 340), cv::Point(799, 599)},
};
const cv::Point* ppt[2] = { triangles[0], triangles[1] };
int npts[2] = { 3, 3 };
cv::Scalar black = cv::Scalar(0, 0, 0);
cv::fillPoly(cv_image_projected, ppt, npts, 2, black);
sensor_msgs::ImagePtr projected_msg = cv_bridge::CvImage(image_msg->header, "bgr8", cv_image_projected).toImageMsg();
pub_project_.publish(projected_msg);
}
void ImageProjectionNodelet::configCB(Config &config, uint32_t level)
{
NODELET_INFO("[Image Projection] Extrinsic Camera Calibration parameter reconfigured to");
NODELET_INFO("top_x: %d, top_y: %d, bottom_x: %d, bottom_y: %d",
config.top_x, config.top_y, config.bottom_x, config.bottom_y);
boost::lock_guard<boost::recursive_mutex> lock(config_mutex_);
// config_ = config;
top_x = config.top_x;
top_y = config.top_y;
bottom_x = config.bottom_x;
bottom_y = config.bottom_y;
}
} // image_project namespace
// Register nodelet
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(image_projection::ImageProjectionNodelet, nodelet::Nodelet) | 40.153846 | 137 | 0.694325 | [
"vector",
"transform"
] |
3022c68d6ce5752b2ec542375bc34b6d2fb540f5 | 45,146 | cpp | C++ | src/ddgi.cpp | rohankumardubey/HybridRendering | 509f768cddb705afd26a639e3440240357b6b009 | [
"MIT"
] | 224 | 2020-04-20T03:42:54.000Z | 2022-01-04T16:08:48.000Z | src/ddgi.cpp | rohankumardubey/HybridRendering | 509f768cddb705afd26a639e3440240357b6b009 | [
"MIT"
] | 7 | 2020-02-17T10:33:15.000Z | 2021-12-09T21:58:16.000Z | src/ddgi.cpp | rohankumardubey/HybridRendering | 509f768cddb705afd26a639e3440240357b6b009 | [
"MIT"
] | 13 | 2020-07-03T13:39:52.000Z | 2021-12-11T08:50:42.000Z | #include "ddgi.h"
#include "utilities.h"
#include "g_buffer.h"
#include <stdexcept>
#include <logger.h>
#include <profiler.h>
#include <imgui.h>
#include <macros.h>
#include <gtc/quaternion.hpp>
#define _USE_MATH_DEFINES
#include <math.h>
// -----------------------------------------------------------------------------------------------------------------------------------
struct DDGIUniforms
{
glm::vec3 grid_start_position;
glm::vec3 grid_step;
glm::ivec3 probe_counts;
float max_distance;
float depth_sharpness;
float hysteresis;
float normal_bias;
float energy_preservation;
int irradiance_probe_side_length;
int irradiance_texture_width;
int irradiance_texture_height;
int depth_probe_side_length;
int depth_texture_width;
int depth_texture_height;
int rays_per_probe;
int visibility_test;
};
// -----------------------------------------------------------------------------------------------------------------------------------
struct RayTracePushConstants
{
glm::mat4 random_orientation;
uint32_t num_frames;
uint32_t infinite_bounces;
float gi_intensity;
};
// -----------------------------------------------------------------------------------------------------------------------------------
struct ProbeUpdatePushConstants
{
uint32_t first_frame;
};
// -----------------------------------------------------------------------------------------------------------------------------------
struct SampleProbeGridPushConstants
{
int g_buffer_mip;
float gi_intensity;
};
// -----------------------------------------------------------------------------------------------------------------------------------
DDGI::DDGI(std::weak_ptr<dw::vk::Backend> backend, CommonResources* common_resources, GBuffer* g_buffer, RayTraceScale scale) :
m_backend(backend), m_common_resources(common_resources), m_g_buffer(g_buffer), m_scale(scale)
{
auto vk_backend = m_backend.lock();
float scale_divisor = powf(2.0f, float(scale));
m_width = vk_backend->swap_chain_extents().width / scale_divisor;
m_height = vk_backend->swap_chain_extents().height / scale_divisor;
m_g_buffer_mip = static_cast<uint32_t>(scale);
m_random_generator = std::mt19937(m_random_device());
m_random_distribution_zo = std::uniform_real_distribution<float>(0.0f, 1.0f);
m_random_distribution_no = std::uniform_real_distribution<float>(-1.0f, 1.0f);
create_descriptor_sets();
create_pipelines();
}
// -----------------------------------------------------------------------------------------------------------------------------------
DDGI::~DDGI()
{
}
// -----------------------------------------------------------------------------------------------------------------------------------
void DDGI::render(dw::vk::CommandBuffer::Ptr cmd_buf)
{
DW_SCOPED_SAMPLE("DDGI", cmd_buf);
// If the scene has changed re-initialize the probe grid
if (m_last_scene_id != m_common_resources->current_scene()->id())
initialize_probe_grid();
update_properties_ubo();
ray_trace(cmd_buf);
probe_update(cmd_buf);
sample_probe_grid(cmd_buf);
m_first_frame = false;
m_ping_pong = !m_ping_pong;
}
// -----------------------------------------------------------------------------------------------------------------------------------
void DDGI::gui()
{
ImGui::Text("Grid Size: [%i, %i, %i]", m_probe_grid.probe_counts.x, m_probe_grid.probe_counts.y, m_probe_grid.probe_counts.z);
ImGui::Text("Probe Count: %i", m_probe_grid.probe_counts.x * m_probe_grid.probe_counts.y * m_probe_grid.probe_counts.z);
ImGui::Checkbox("Visibility Test", &m_probe_grid.visibility_test);
ImGui::Checkbox("Infinite Bounces", &m_ray_trace.infinite_bounces);
if (ImGui::InputInt("Rays Per Probe", &m_ray_trace.rays_per_probe))
recreate_probe_grid_resources();
if (ImGui::InputFloat("Probe Distance", &m_probe_grid.probe_distance))
initialize_probe_grid();
ImGui::InputFloat("Hysteresis", &m_probe_update.hysteresis);
ImGui::SliderFloat("Infinite Bounce Intensity", &m_ray_trace.infinite_bounce_intensity, 0.0f, 10.0f);
ImGui::SliderFloat("GI Intensity", &m_sample_probe_grid.gi_intensity, 0.0f, 10.0f);
ImGui::SliderFloat("Normal Bias", &m_probe_update.normal_bias, 0.0f, 10.0f);
ImGui::InputFloat("Depth Sharpness", &m_probe_update.depth_sharpness);
}
// -----------------------------------------------------------------------------------------------------------------------------------
dw::vk::DescriptorSet::Ptr DDGI::output_ds()
{
return m_sample_probe_grid.read_ds;
}
// -----------------------------------------------------------------------------------------------------------------------------------
dw::vk::DescriptorSet::Ptr DDGI::current_read_ds()
{
return m_probe_grid.read_ds[static_cast<uint32_t>(!m_ping_pong)];
}
// -----------------------------------------------------------------------------------------------------------------------------------
uint32_t DDGI::current_ubo_offset()
{
auto vk_backend = m_backend.lock();
return m_probe_grid.properties_ubo_size * vk_backend->current_frame_idx();
}
// -----------------------------------------------------------------------------------------------------------------------------------
void DDGI::initialize_probe_grid()
{
// Get the min and max extents of the scene.
glm::vec3 min_extents = m_common_resources->current_scene()->min_extents();
glm::vec3 max_extents = m_common_resources->current_scene()->max_extents();
// Compute the scene length.
glm::vec3 scene_length = max_extents - min_extents;
// Compute the number of probes along each axis.
// Add 2 more probes to fully cover scene.
m_probe_grid.probe_counts = glm::ivec3(scene_length / m_probe_grid.probe_distance) + glm::ivec3(2);
m_probe_grid.grid_start_position = min_extents;
m_probe_update.max_distance = m_probe_grid.probe_distance * 1.5f;
// Assign current scene ID
m_last_scene_id = m_common_resources->current_scene()->id();
recreate_probe_grid_resources();
}
// -----------------------------------------------------------------------------------------------------------------------------------
void DDGI::create_images()
{
auto backend = m_backend.lock();
uint32_t total_probes = m_probe_grid.probe_counts.x * m_probe_grid.probe_counts.y * m_probe_grid.probe_counts.z;
// Ray Trace
{
m_ray_trace.radiance_image = dw::vk::Image::create(backend, VK_IMAGE_TYPE_2D, m_ray_trace.rays_per_probe, total_probes, 1, 1, 1, VK_FORMAT_R16G16B16A16_SFLOAT, VMA_MEMORY_USAGE_GPU_ONLY, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_SAMPLE_COUNT_1_BIT);
m_ray_trace.radiance_image->set_name("DDGI Ray Trace Radiance");
m_ray_trace.radiance_view = dw::vk::ImageView::create(backend, m_ray_trace.radiance_image, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_COLOR_BIT);
m_ray_trace.radiance_view->set_name("DDGI Ray Trace Radiance");
m_ray_trace.direction_depth_image = dw::vk::Image::create(backend, VK_IMAGE_TYPE_2D, m_ray_trace.rays_per_probe, total_probes, 1, 1, 1, VK_FORMAT_R16G16B16A16_SFLOAT, VMA_MEMORY_USAGE_GPU_ONLY, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_SAMPLE_COUNT_1_BIT);
m_ray_trace.direction_depth_image->set_name("DDGI Ray Trace Direction Depth");
m_ray_trace.direction_depth_view = dw::vk::ImageView::create(backend, m_ray_trace.direction_depth_image, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_COLOR_BIT);
m_ray_trace.direction_depth_view->set_name("DDGI Ray Trace Direction Depth");
}
// Probe Grid
{
// 1-pixel of padding surrounding each probe, 1-pixel padding surrounding entire texture for alignment.
const int irradiance_width = (m_probe_grid.irradiance_oct_size + 2) * m_probe_grid.probe_counts.x * m_probe_grid.probe_counts.y + 2;
const int irradiance_height = (m_probe_grid.irradiance_oct_size + 2) * m_probe_grid.probe_counts.z + 2;
const int depth_width = (m_probe_grid.depth_oct_size + 2) * m_probe_grid.probe_counts.x * m_probe_grid.probe_counts.y + 2;
const int depth_height = (m_probe_grid.depth_oct_size + 2) * m_probe_grid.probe_counts.z + 2;
for (int i = 0; i < 2; i++)
{
m_probe_grid.irradiance_image[i] = dw::vk::Image::create(backend, VK_IMAGE_TYPE_2D, irradiance_width, irradiance_height, 1, 1, 1, VK_FORMAT_R16G16B16A16_SFLOAT, VMA_MEMORY_USAGE_GPU_ONLY, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_SAMPLE_COUNT_1_BIT);
m_probe_grid.irradiance_image[i]->set_name("DDGI Irradiance Probe Grid " + std::to_string(i));
m_probe_grid.irradiance_view[i] = dw::vk::ImageView::create(backend, m_probe_grid.irradiance_image[i], VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_COLOR_BIT);
m_probe_grid.irradiance_view[i]->set_name("DDGI Irradiance Probe Grid " + std::to_string(i));
m_probe_grid.depth_image[i] = dw::vk::Image::create(backend, VK_IMAGE_TYPE_2D, depth_width, depth_height, 1, 1, 1, VK_FORMAT_R16G16_SFLOAT, VMA_MEMORY_USAGE_GPU_ONLY, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_SAMPLE_COUNT_1_BIT);
m_probe_grid.depth_image[i]->set_name("DDGI Depth Probe Grid " + std::to_string(i));
m_probe_grid.depth_view[i] = dw::vk::ImageView::create(backend, m_probe_grid.depth_image[i], VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_COLOR_BIT);
m_probe_grid.depth_view[i]->set_name("DDGI Depth Probe Grid " + std::to_string(i));
}
}
// Sample Probe Grid
{
m_sample_probe_grid.image = dw::vk::Image::create(backend, VK_IMAGE_TYPE_2D, m_width, m_height, 1, 1, 1, VK_FORMAT_R16G16B16A16_SFLOAT, VMA_MEMORY_USAGE_GPU_ONLY, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT, VK_SAMPLE_COUNT_1_BIT);
m_sample_probe_grid.image->set_name("DDGI Sample Probe Grid");
m_sample_probe_grid.image_view = dw::vk::ImageView::create(backend, m_sample_probe_grid.image, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_COLOR_BIT);
m_sample_probe_grid.image_view->set_name("DDGI Sample Probe Grid");
}
}
// -----------------------------------------------------------------------------------------------------------------------------------
void DDGI::create_buffers()
{
auto backend = m_backend.lock();
m_probe_grid.properties_ubo_size = backend->aligned_dynamic_ubo_size(sizeof(DDGIUniforms));
m_probe_grid.properties_ubo = dw::vk::Buffer::create(backend, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, m_probe_grid.properties_ubo_size * dw::vk::Backend::kMaxFramesInFlight, VMA_MEMORY_USAGE_CPU_TO_GPU, VMA_ALLOCATION_CREATE_MAPPED_BIT);
}
// -----------------------------------------------------------------------------------------------------------------------------------
void DDGI::create_descriptor_sets()
{
auto backend = m_backend.lock();
// Ray Trace
{
dw::vk::DescriptorSetLayout::Desc desc;
desc.add_binding(0, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_RAYGEN_BIT_KHR | VK_SHADER_STAGE_COMPUTE_BIT | VK_SHADER_STAGE_FRAGMENT_BIT);
desc.add_binding(1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_RAYGEN_BIT_KHR | VK_SHADER_STAGE_COMPUTE_BIT | VK_SHADER_STAGE_FRAGMENT_BIT);
m_ray_trace.write_ds_layout = dw::vk::DescriptorSetLayout::create(backend, desc);
}
{
dw::vk::DescriptorSetLayout::Desc desc;
desc.add_binding(0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_RAYGEN_BIT_KHR | VK_SHADER_STAGE_COMPUTE_BIT | VK_SHADER_STAGE_FRAGMENT_BIT);
desc.add_binding(1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_RAYGEN_BIT_KHR | VK_SHADER_STAGE_COMPUTE_BIT | VK_SHADER_STAGE_FRAGMENT_BIT);
m_ray_trace.read_ds_layout = dw::vk::DescriptorSetLayout::create(backend, desc);
}
{
m_ray_trace.write_ds = backend->allocate_descriptor_set(m_ray_trace.write_ds_layout);
m_ray_trace.read_ds = backend->allocate_descriptor_set(m_ray_trace.read_ds_layout);
}
// Probe Grid
{
dw::vk::DescriptorSetLayout::Desc desc;
desc.add_binding(0, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR | VK_SHADER_STAGE_COMPUTE_BIT | VK_SHADER_STAGE_FRAGMENT_BIT);
desc.add_binding(1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR | VK_SHADER_STAGE_COMPUTE_BIT | VK_SHADER_STAGE_FRAGMENT_BIT);
m_probe_grid.write_ds_layout = dw::vk::DescriptorSetLayout::create(backend, desc);
}
for (int i = 0; i < 2; i++)
{
m_probe_grid.write_ds[i] = backend->allocate_descriptor_set(m_probe_grid.write_ds_layout);
m_probe_grid.read_ds[i] = backend->allocate_descriptor_set(m_common_resources->ddgi_read_ds_layout);
}
// Sample Probe Grid
{
m_sample_probe_grid.write_ds = backend->allocate_descriptor_set(m_common_resources->storage_image_ds_layout);
m_sample_probe_grid.write_ds->set_name("DDGI Sample Probe Grid");
m_sample_probe_grid.read_ds = backend->allocate_descriptor_set(m_common_resources->combined_sampler_ds_layout);
m_sample_probe_grid.read_ds->set_name("DDGI Sample Probe Grid");
}
}
// -----------------------------------------------------------------------------------------------------------------------------------
void DDGI::write_descriptor_sets()
{
auto backend = m_backend.lock();
// Ray Trace Write
{
std::vector<VkDescriptorImageInfo> image_infos;
std::vector<VkWriteDescriptorSet> write_datas;
VkWriteDescriptorSet write_data;
image_infos.reserve(2);
write_datas.reserve(2);
{
VkDescriptorImageInfo storage_image_info;
storage_image_info.sampler = VK_NULL_HANDLE;
storage_image_info.imageView = m_ray_trace.radiance_view->handle();
storage_image_info.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
image_infos.push_back(storage_image_info);
DW_ZERO_MEMORY(write_data);
write_data.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write_data.descriptorCount = 1;
write_data.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
write_data.pImageInfo = &image_infos.back();
write_data.dstBinding = 0;
write_data.dstSet = m_ray_trace.write_ds->handle();
write_datas.push_back(write_data);
}
{
VkDescriptorImageInfo storage_image_info;
storage_image_info.sampler = VK_NULL_HANDLE;
storage_image_info.imageView = m_ray_trace.direction_depth_view->handle();
storage_image_info.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
image_infos.push_back(storage_image_info);
DW_ZERO_MEMORY(write_data);
write_data.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write_data.descriptorCount = 1;
write_data.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
write_data.pImageInfo = &image_infos.back();
write_data.dstBinding = 1;
write_data.dstSet = m_ray_trace.write_ds->handle();
write_datas.push_back(write_data);
}
vkUpdateDescriptorSets(backend->device(), write_datas.size(), write_datas.data(), 0, nullptr);
}
// Ray Trace Read
{
std::vector<VkDescriptorImageInfo> image_infos;
std::vector<VkWriteDescriptorSet> write_datas;
VkWriteDescriptorSet write_data;
image_infos.reserve(2);
write_datas.reserve(2);
{
VkDescriptorImageInfo sampler_image_info;
sampler_image_info.sampler = backend->nearest_sampler()->handle();
sampler_image_info.imageView = m_ray_trace.radiance_view->handle();
sampler_image_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
image_infos.push_back(sampler_image_info);
DW_ZERO_MEMORY(write_data);
write_data.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write_data.descriptorCount = 1;
write_data.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
write_data.pImageInfo = &image_infos.back();
write_data.dstBinding = 0;
write_data.dstSet = m_ray_trace.read_ds->handle();
write_datas.push_back(write_data);
}
{
VkDescriptorImageInfo sampler_image_info;
sampler_image_info.sampler = backend->nearest_sampler()->handle();
sampler_image_info.imageView = m_ray_trace.direction_depth_view->handle();
sampler_image_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
image_infos.push_back(sampler_image_info);
DW_ZERO_MEMORY(write_data);
write_data.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write_data.descriptorCount = 1;
write_data.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
write_data.pImageInfo = &image_infos.back();
write_data.dstBinding = 1;
write_data.dstSet = m_ray_trace.read_ds->handle();
write_datas.push_back(write_data);
}
vkUpdateDescriptorSets(backend->device(), write_datas.size(), write_datas.data(), 0, nullptr);
}
// Probe Grid Write
for (int i = 0; i < 2; i++)
{
std::vector<VkDescriptorImageInfo> image_infos;
std::vector<VkWriteDescriptorSet> write_datas;
VkWriteDescriptorSet write_data;
image_infos.reserve(2);
write_datas.reserve(2);
{
VkDescriptorImageInfo storage_image_info;
storage_image_info.sampler = VK_NULL_HANDLE;
storage_image_info.imageView = m_probe_grid.irradiance_view[i]->handle();
storage_image_info.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
image_infos.push_back(storage_image_info);
DW_ZERO_MEMORY(write_data);
write_data.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write_data.descriptorCount = 1;
write_data.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
write_data.pImageInfo = &image_infos.back();
write_data.dstBinding = 0;
write_data.dstSet = m_probe_grid.write_ds[i]->handle();
write_datas.push_back(write_data);
}
{
VkDescriptorImageInfo storage_image_info;
storage_image_info.sampler = VK_NULL_HANDLE;
storage_image_info.imageView = m_probe_grid.depth_view[i]->handle();
storage_image_info.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
image_infos.push_back(storage_image_info);
DW_ZERO_MEMORY(write_data);
write_data.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write_data.descriptorCount = 1;
write_data.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
write_data.pImageInfo = &image_infos.back();
write_data.dstBinding = 1;
write_data.dstSet = m_probe_grid.write_ds[i]->handle();
write_datas.push_back(write_data);
}
vkUpdateDescriptorSets(backend->device(), write_datas.size(), write_datas.data(), 0, nullptr);
}
// Probe Grid Read
for (int i = 0; i < 2; i++)
{
std::vector<VkDescriptorBufferInfo> buffer_infos;
std::vector<VkDescriptorImageInfo> image_infos;
std::vector<VkWriteDescriptorSet> write_datas;
VkWriteDescriptorSet write_data;
image_infos.reserve(2);
write_datas.reserve(3);
{
VkDescriptorImageInfo sampler_image_info;
sampler_image_info.sampler = backend->bilinear_sampler()->handle();
sampler_image_info.imageView = m_probe_grid.irradiance_view[i]->handle();
sampler_image_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
image_infos.push_back(sampler_image_info);
DW_ZERO_MEMORY(write_data);
write_data.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write_data.descriptorCount = 1;
write_data.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
write_data.pImageInfo = &image_infos.back();
write_data.dstBinding = 0;
write_data.dstSet = m_probe_grid.read_ds[i]->handle();
write_datas.push_back(write_data);
}
{
VkDescriptorImageInfo sampler_image_info;
sampler_image_info.sampler = backend->bilinear_sampler()->handle();
sampler_image_info.imageView = m_probe_grid.depth_view[i]->handle();
sampler_image_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
image_infos.push_back(sampler_image_info);
DW_ZERO_MEMORY(write_data);
write_data.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write_data.descriptorCount = 1;
write_data.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
write_data.pImageInfo = &image_infos.back();
write_data.dstBinding = 1;
write_data.dstSet = m_probe_grid.read_ds[i]->handle();
write_datas.push_back(write_data);
}
{
VkDescriptorBufferInfo buffer_info;
buffer_info.range = sizeof(DDGIUniforms);
buffer_info.offset = 0;
buffer_info.buffer = m_probe_grid.properties_ubo->handle();
buffer_infos.push_back(buffer_info);
DW_ZERO_MEMORY(write_data);
write_data.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write_data.descriptorCount = 1;
write_data.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
write_data.pBufferInfo = &buffer_infos.back();
write_data.dstBinding = 2;
write_data.dstSet = m_probe_grid.read_ds[i]->handle();
write_datas.push_back(write_data);
}
vkUpdateDescriptorSets(backend->device(), write_datas.size(), write_datas.data(), 0, nullptr);
}
// Sample Probe Grid write
{
VkDescriptorImageInfo storage_image_info;
storage_image_info.sampler = VK_NULL_HANDLE;
storage_image_info.imageView = m_sample_probe_grid.image_view->handle();
storage_image_info.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
VkWriteDescriptorSet write_data;
DW_ZERO_MEMORY(write_data);
write_data.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write_data.descriptorCount = 1;
write_data.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
write_data.pImageInfo = &storage_image_info;
write_data.dstBinding = 0;
write_data.dstSet = m_sample_probe_grid.write_ds->handle();
vkUpdateDescriptorSets(backend->device(), 1, &write_data, 0, nullptr);
}
// Sample Probe Grid read
{
VkDescriptorImageInfo sampler_image_info;
sampler_image_info.sampler = backend->bilinear_sampler()->handle();
sampler_image_info.imageView = m_sample_probe_grid.image_view->handle();
sampler_image_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
VkWriteDescriptorSet write_data;
DW_ZERO_MEMORY(write_data);
write_data.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write_data.descriptorCount = 1;
write_data.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
write_data.pImageInfo = &sampler_image_info;
write_data.dstBinding = 0;
write_data.dstSet = m_sample_probe_grid.read_ds->handle();
vkUpdateDescriptorSets(backend->device(), 1, &write_data, 0, nullptr);
}
}
// -----------------------------------------------------------------------------------------------------------------------------------
void DDGI::create_pipelines()
{
auto vk_backend = m_backend.lock();
// Ray Trace
{
// ---------------------------------------------------------------------------
// Create shader modules
// ---------------------------------------------------------------------------
dw::vk::ShaderModule::Ptr rgen = dw::vk::ShaderModule::create_from_file(vk_backend, "shaders/gi_ray_trace.rgen.spv");
dw::vk::ShaderModule::Ptr rchit = dw::vk::ShaderModule::create_from_file(vk_backend, "shaders/gi_ray_trace.rchit.spv");
dw::vk::ShaderModule::Ptr rmiss = dw::vk::ShaderModule::create_from_file(vk_backend, "shaders/gi_ray_trace.rmiss.spv");
dw::vk::ShaderBindingTable::Desc sbt_desc;
sbt_desc.add_ray_gen_group(rgen, "main");
sbt_desc.add_hit_group(rchit, "main");
sbt_desc.add_miss_group(rmiss, "main");
m_ray_trace.sbt = dw::vk::ShaderBindingTable::create(vk_backend, sbt_desc);
dw::vk::RayTracingPipeline::Desc desc;
desc.set_max_pipeline_ray_recursion_depth(1);
desc.set_shader_binding_table(m_ray_trace.sbt);
// ---------------------------------------------------------------------------
// Create pipeline layout
// ---------------------------------------------------------------------------
dw::vk::PipelineLayout::Desc pl_desc;
pl_desc.add_descriptor_set_layout(m_common_resources->current_scene()->descriptor_set_layout());
pl_desc.add_descriptor_set_layout(m_ray_trace.write_ds_layout);
pl_desc.add_descriptor_set_layout(m_common_resources->per_frame_ds_layout);
pl_desc.add_descriptor_set_layout(m_common_resources->skybox_ds_layout);
pl_desc.add_descriptor_set_layout(m_common_resources->ddgi_read_ds_layout);
pl_desc.add_push_constant_range(VK_SHADER_STAGE_RAYGEN_BIT_KHR | VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR, 0, sizeof(RayTracePushConstants));
m_ray_trace.pipeline_layout = dw::vk::PipelineLayout::create(vk_backend, pl_desc);
desc.set_pipeline_layout(m_ray_trace.pipeline_layout);
m_ray_trace.pipeline = dw::vk::RayTracingPipeline::create(vk_backend, desc);
}
// Probe Update
{
dw::vk::PipelineLayout::Desc desc;
desc.add_descriptor_set_layout(m_probe_grid.write_ds_layout);
desc.add_descriptor_set_layout(m_common_resources->ddgi_read_ds_layout);
desc.add_descriptor_set_layout(m_ray_trace.read_ds_layout);
desc.add_push_constant_range(VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(ProbeUpdatePushConstants));
m_probe_update.pipeline_layout = dw::vk::PipelineLayout::create(vk_backend, desc);
m_probe_update.pipeline_layout->set_name("Probe Update Pipeline Layout");
dw::vk::ComputePipeline::Desc comp_desc;
comp_desc.set_pipeline_layout(m_probe_update.pipeline_layout);
std::string shaders[] = {
"shaders/gi_irradiance_probe_update.comp.spv",
"shaders/gi_depth_probe_update.comp.spv"
};
for (int i = 0; i < 2; i++)
{
dw::vk::ShaderModule::Ptr module = dw::vk::ShaderModule::create_from_file(vk_backend, shaders[i]);
comp_desc.set_shader_stage(module, "main");
m_probe_update.pipeline[i] = dw::vk::ComputePipeline::create(vk_backend, comp_desc);
}
}
// Probe Border Update
{
dw::vk::PipelineLayout::Desc desc;
desc.add_descriptor_set_layout(m_probe_grid.write_ds_layout);
m_border_update.pipeline_layout = dw::vk::PipelineLayout::create(vk_backend, desc);
m_border_update.pipeline_layout->set_name("Border Update Pipeline Layout");
dw::vk::ComputePipeline::Desc comp_desc;
comp_desc.set_pipeline_layout(m_border_update.pipeline_layout);
std::string shaders[] = {
"shaders/gi_irradiance_border_update.comp.spv",
"shaders/gi_depth_border_update.comp.spv"
};
for (int i = 0; i < 2; i++)
{
dw::vk::ShaderModule::Ptr module = dw::vk::ShaderModule::create_from_file(vk_backend, shaders[i]);
comp_desc.set_shader_stage(module, "main");
m_border_update.pipeline[i] = dw::vk::ComputePipeline::create(vk_backend, comp_desc);
}
}
// Sample Probe Grid Update
{
dw::vk::PipelineLayout::Desc desc;
desc.add_descriptor_set_layout(m_common_resources->storage_image_ds_layout);
desc.add_descriptor_set_layout(m_common_resources->ddgi_read_ds_layout);
desc.add_descriptor_set_layout(m_g_buffer->ds_layout());
desc.add_descriptor_set_layout(m_common_resources->per_frame_ds_layout);
desc.add_push_constant_range(VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(SampleProbeGridPushConstants));
m_sample_probe_grid.pipeline_layout = dw::vk::PipelineLayout::create(vk_backend, desc);
m_sample_probe_grid.pipeline_layout->set_name("Sample Probe Grid Pipeline Layout");
dw::vk::ComputePipeline::Desc comp_desc;
comp_desc.set_pipeline_layout(m_sample_probe_grid.pipeline_layout);
dw::vk::ShaderModule::Ptr module = dw::vk::ShaderModule::create_from_file(vk_backend, "shaders/gi_sample_probe_grid.comp.spv");
comp_desc.set_shader_stage(module, "main");
m_sample_probe_grid.pipeline = dw::vk::ComputePipeline::create(vk_backend, comp_desc);
}
}
// -----------------------------------------------------------------------------------------------------------------------------------
void DDGI::recreate_probe_grid_resources()
{
auto backend = m_backend.lock();
backend->wait_idle();
m_first_frame = true;
create_images();
create_buffers();
write_descriptor_sets();
}
// -----------------------------------------------------------------------------------------------------------------------------------
void DDGI::update_properties_ubo()
{
auto backend = m_backend.lock();
DDGIUniforms ubo;
ubo.grid_start_position = m_probe_grid.grid_start_position;
ubo.grid_step = glm::vec3(m_probe_grid.probe_distance);
ubo.probe_counts = m_probe_grid.probe_counts;
ubo.max_distance = m_probe_update.max_distance;
ubo.depth_sharpness = m_probe_update.depth_sharpness;
ubo.hysteresis = m_probe_update.hysteresis;
ubo.normal_bias = m_probe_update.normal_bias;
ubo.energy_preservation = m_probe_grid.recursive_energy_preservation;
ubo.irradiance_probe_side_length = m_probe_grid.irradiance_oct_size;
ubo.irradiance_texture_width = m_probe_grid.irradiance_image[0]->width();
ubo.irradiance_texture_height = m_probe_grid.irradiance_image[0]->height();
ubo.depth_probe_side_length = m_probe_grid.depth_oct_size;
ubo.depth_texture_width = m_probe_grid.depth_image[0]->width();
ubo.depth_texture_height = m_probe_grid.depth_image[0]->height();
ubo.rays_per_probe = m_ray_trace.rays_per_probe;
ubo.visibility_test = (int32_t)m_probe_grid.visibility_test;
uint8_t* ptr = (uint8_t*)m_probe_grid.properties_ubo->mapped_ptr();
memcpy(ptr + m_probe_grid.properties_ubo_size * backend->current_frame_idx(), &ubo, sizeof(DDGIUniforms));
}
// -----------------------------------------------------------------------------------------------------------------------------------
void DDGI::ray_trace(dw::vk::CommandBuffer::Ptr cmd_buf)
{
DW_SCOPED_SAMPLE("Ray Trace", cmd_buf);
auto backend = m_backend.lock();
VkImageSubresourceRange subresource_range = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
uint32_t read_idx = static_cast<uint32_t>(!m_ping_pong);
if (m_first_frame)
{
dw::vk::utilities::set_image_layout(
cmd_buf->handle(),
m_probe_grid.irradiance_image[read_idx]->handle(),
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
subresource_range);
dw::vk::utilities::set_image_layout(
cmd_buf->handle(),
m_probe_grid.depth_image[read_idx]->handle(),
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
subresource_range);
}
{
std::vector<VkImageMemoryBarrier> image_barriers = {
image_memory_barrier(m_ray_trace.radiance_image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, subresource_range, VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_SHADER_WRITE_BIT),
image_memory_barrier(m_ray_trace.direction_depth_image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, subresource_range, VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_SHADER_WRITE_BIT)
};
pipeline_barrier(cmd_buf, {}, image_barriers, {}, VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR, VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR);
}
vkCmdBindPipeline(cmd_buf->handle(), VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, m_ray_trace.pipeline->handle());
RayTracePushConstants push_constants;
push_constants.random_orientation = glm::mat4_cast(glm::angleAxis(m_random_distribution_zo(m_random_generator) * (float(M_PI) * 2.0f), glm::normalize(glm::vec3(m_random_distribution_no(m_random_generator), m_random_distribution_no(m_random_generator), m_random_distribution_no(m_random_generator)))));
push_constants.num_frames = m_common_resources->num_frames;
push_constants.infinite_bounces = m_ray_trace.infinite_bounces && !m_first_frame ? 1u : 0u;
push_constants.gi_intensity = m_ray_trace.infinite_bounce_intensity;
vkCmdPushConstants(cmd_buf->handle(), m_ray_trace.pipeline_layout->handle(), VK_SHADER_STAGE_RAYGEN_BIT_KHR | VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR, 0, sizeof(push_constants), &push_constants);
const uint32_t dynamic_offsets[] = {
m_common_resources->ubo_size * backend->current_frame_idx(),
m_probe_grid.properties_ubo_size * backend->current_frame_idx()
};
VkDescriptorSet descriptor_sets[] = {
m_common_resources->current_scene()->descriptor_set()->handle(),
m_ray_trace.write_ds->handle(),
m_common_resources->per_frame_ds->handle(),
m_common_resources->current_skybox_ds->handle(),
m_probe_grid.read_ds[static_cast<uint32_t>(!m_ping_pong)]->handle(),
};
vkCmdBindDescriptorSets(cmd_buf->handle(), VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, m_ray_trace.pipeline_layout->handle(), 0, 5, descriptor_sets, 2, dynamic_offsets);
auto& rt_pipeline_props = backend->ray_tracing_pipeline_properties();
VkDeviceSize group_size = dw::vk::utilities::aligned_size(rt_pipeline_props.shaderGroupHandleSize, rt_pipeline_props.shaderGroupBaseAlignment);
VkDeviceSize group_stride = group_size;
const VkStridedDeviceAddressRegionKHR raygen_sbt = { m_ray_trace.pipeline->shader_binding_table_buffer()->device_address(), group_stride, group_size };
const VkStridedDeviceAddressRegionKHR miss_sbt = { m_ray_trace.pipeline->shader_binding_table_buffer()->device_address() + m_ray_trace.sbt->miss_group_offset(), group_stride, group_size };
const VkStridedDeviceAddressRegionKHR hit_sbt = { m_ray_trace.pipeline->shader_binding_table_buffer()->device_address() + m_ray_trace.sbt->hit_group_offset(), group_stride, group_size };
const VkStridedDeviceAddressRegionKHR callable_sbt = { 0, 0, 0 };
uint32_t num_total_probes = m_probe_grid.probe_counts.x * m_probe_grid.probe_counts.y * m_probe_grid.probe_counts.z;
vkCmdTraceRaysKHR(cmd_buf->handle(), &raygen_sbt, &miss_sbt, &hit_sbt, &callable_sbt, m_ray_trace.rays_per_probe, num_total_probes, 1);
{
std::vector<VkImageMemoryBarrier> image_barriers = {
image_memory_barrier(m_ray_trace.radiance_image, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT),
image_memory_barrier(m_ray_trace.direction_depth_image, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT)
};
pipeline_barrier(cmd_buf, {}, image_barriers, {}, VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
}
}
// -----------------------------------------------------------------------------------------------------------------------------------
void DDGI::probe_update(dw::vk::CommandBuffer::Ptr cmd_buf)
{
DW_SCOPED_SAMPLE("Probe Update", cmd_buf);
VkImageSubresourceRange subresource_range = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
uint32_t write_idx = static_cast<uint32_t>(m_ping_pong);
{
std::vector<VkImageMemoryBarrier> image_barriers = {
image_memory_barrier(m_probe_grid.irradiance_image[write_idx], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, subresource_range, VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_SHADER_WRITE_BIT),
image_memory_barrier(m_probe_grid.depth_image[write_idx], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, subresource_range, VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_SHADER_WRITE_BIT)
};
pipeline_barrier(cmd_buf, {}, image_barriers, {}, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
}
probe_update(cmd_buf, true);
probe_update(cmd_buf, false);
{
std::vector<VkMemoryBarrier> memory_barriers = {
memory_barrier(VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT)
};
pipeline_barrier(cmd_buf, memory_barriers, {}, {}, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
}
border_update(cmd_buf);
{
std::vector<VkImageMemoryBarrier> image_barriers = {
image_memory_barrier(m_probe_grid.irradiance_image[write_idx], VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT),
image_memory_barrier(m_probe_grid.depth_image[write_idx], VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT)
};
pipeline_barrier(cmd_buf, {}, image_barriers, {}, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR);
}
}
// -----------------------------------------------------------------------------------------------------------------------------------
void DDGI::probe_update(dw::vk::CommandBuffer::Ptr cmd_buf, bool is_irradiance)
{
DW_SCOPED_SAMPLE(is_irradiance ? "Irradiance" : "Depth", cmd_buf);
auto backend = m_backend.lock();
VkPipeline pipeline = m_probe_update.pipeline[1]->handle();
if (is_irradiance)
pipeline = m_probe_update.pipeline[0]->handle();
vkCmdBindPipeline(cmd_buf->handle(), VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
ProbeUpdatePushConstants push_constants;
push_constants.first_frame = (uint32_t)m_first_frame;
vkCmdPushConstants(cmd_buf->handle(), m_probe_update.pipeline_layout->handle(), VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push_constants), &push_constants);
uint32_t read_idx = static_cast<uint32_t>(!m_ping_pong);
uint32_t write_idx = static_cast<uint32_t>(m_ping_pong);
VkDescriptorSet descriptor_sets[] = {
m_probe_grid.write_ds[write_idx]->handle(),
m_probe_grid.read_ds[read_idx]->handle(),
m_ray_trace.read_ds->handle()
};
const uint32_t dynamic_offsets[] = {
m_probe_grid.properties_ubo_size * backend->current_frame_idx()
};
vkCmdBindDescriptorSets(cmd_buf->handle(), VK_PIPELINE_BIND_POINT_COMPUTE, m_probe_update.pipeline_layout->handle(), 0, 3, descriptor_sets, 1, dynamic_offsets);
const uint32_t dispatch_x = static_cast<uint32_t>(m_probe_grid.probe_counts.x * m_probe_grid.probe_counts.y);
const uint32_t dispatch_y = static_cast<uint32_t>(m_probe_grid.probe_counts.z);
vkCmdDispatch(cmd_buf->handle(), dispatch_x, dispatch_y, 1);
}
// -----------------------------------------------------------------------------------------------------------------------------------
void DDGI::border_update(dw::vk::CommandBuffer::Ptr cmd_buf)
{
DW_SCOPED_SAMPLE("Border Update", cmd_buf);
border_update(cmd_buf, true);
border_update(cmd_buf, false);
}
// -----------------------------------------------------------------------------------------------------------------------------------
void DDGI::border_update(dw::vk::CommandBuffer::Ptr cmd_buf, bool is_irradiance)
{
DW_SCOPED_SAMPLE(is_irradiance ? "Irradiance" : "Depth", cmd_buf);
auto backend = m_backend.lock();
VkPipeline pipeline = m_border_update.pipeline[1]->handle();
if (is_irradiance)
pipeline = m_border_update.pipeline[0]->handle();
vkCmdBindPipeline(cmd_buf->handle(), VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
uint32_t write_idx = static_cast<uint32_t>(m_ping_pong);
VkDescriptorSet descriptor_sets[] = {
m_probe_grid.write_ds[write_idx]->handle()
};
vkCmdBindDescriptorSets(cmd_buf->handle(), VK_PIPELINE_BIND_POINT_COMPUTE, m_border_update.pipeline_layout->handle(), 0, 1, descriptor_sets, 0, nullptr);
const uint32_t dispatch_x = static_cast<uint32_t>(m_probe_grid.probe_counts.x * m_probe_grid.probe_counts.y);
const uint32_t dispatch_y = static_cast<uint32_t>(m_probe_grid.probe_counts.z);
vkCmdDispatch(cmd_buf->handle(), dispatch_x, dispatch_y, 1);
}
// -----------------------------------------------------------------------------------------------------------------------------------
void DDGI::sample_probe_grid(dw::vk::CommandBuffer::Ptr cmd_buf)
{
DW_SCOPED_SAMPLE("Sample Probe Grid", cmd_buf);
auto backend = m_backend.lock();
VkImageSubresourceRange subresource_range = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
{
std::vector<VkImageMemoryBarrier> image_barriers = {
image_memory_barrier(m_sample_probe_grid.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, subresource_range, VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_SHADER_WRITE_BIT)
};
pipeline_barrier(cmd_buf, {}, image_barriers, {}, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
}
vkCmdBindPipeline(cmd_buf->handle(), VK_PIPELINE_BIND_POINT_COMPUTE, m_sample_probe_grid.pipeline->handle());
SampleProbeGridPushConstants push_constants;
push_constants.g_buffer_mip = m_g_buffer_mip;
push_constants.gi_intensity = m_sample_probe_grid.gi_intensity;
vkCmdPushConstants(cmd_buf->handle(), m_sample_probe_grid.pipeline_layout->handle(), VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push_constants), &push_constants);
const uint32_t dynamic_offsets[] = {
m_probe_grid.properties_ubo_size * backend->current_frame_idx(),
m_common_resources->ubo_size * backend->current_frame_idx()
};
VkDescriptorSet descriptor_sets[] = {
m_sample_probe_grid.write_ds->handle(),
m_probe_grid.read_ds[static_cast<uint32_t>(m_ping_pong)]->handle(),
m_g_buffer->output_ds()->handle(),
m_common_resources->per_frame_ds->handle()
};
vkCmdBindDescriptorSets(cmd_buf->handle(), VK_PIPELINE_BIND_POINT_COMPUTE, m_sample_probe_grid.pipeline_layout->handle(), 0, 4, descriptor_sets, 2, dynamic_offsets);
const int NUM_THREADS_X = 32;
const int NUM_THREADS_Y = 32;
vkCmdDispatch(cmd_buf->handle(), static_cast<uint32_t>(ceil(float(m_sample_probe_grid.image->width()) / float(NUM_THREADS_X))), static_cast<uint32_t>(ceil(float(m_sample_probe_grid.image->height()) / float(NUM_THREADS_Y))), 1);
{
std::vector<VkImageMemoryBarrier> image_barriers = {
image_memory_barrier(m_sample_probe_grid.image, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT)
};
pipeline_barrier(cmd_buf, {}, image_barriers, {}, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
}
}
// ----------------------------------------------------------------------------------------------------------------------------------- | 43.746124 | 305 | 0.651287 | [
"render",
"vector"
] |
302303ab5426b4051bed49bec06bdeaa6e4ded5b | 24,799 | cc | C++ | nflogdata.cc | ryancdotorg/python-nflogr | fbb2623ac310180c700c94b1f4a2dfcefa7ed683 | [
"MIT"
] | 1 | 2021-08-07T23:33:34.000Z | 2021-08-07T23:33:34.000Z | nflogdata.cc | ryancdotorg/python-nflogr | fbb2623ac310180c700c94b1f4a2dfcefa7ed683 | [
"MIT"
] | null | null | null | nflogdata.cc | ryancdotorg/python-nflogr | fbb2623ac310180c700c94b1f4a2dfcefa7ed683 | [
"MIT"
] | null | null | null | /* Copyright 2021 Ryan Castellucci, MIT License */
#include <Python.h>
#include <pytime.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <endian.h>
#include <netinet/in.h>
#include <net/if.h>
extern "C" {
#include <libnetfilter_log/libnetfilter_log.h>
#include <libnfnetlink/linux_nfnetlink_compat.h>
}
#include "nflogr.h"
#include "nflogdata.h"
// internal nflogdataobject
typedef struct {
PyObject_HEAD
uint16_t proto;
uint16_t hwtype;
uint32_t nfmark;
double timestamp;
PyObject *indev;
PyObject *physindev;
PyObject *outdev;
PyObject *physoutdev;
PyObject *uid;
PyObject *gid;
PyObject *hwaddr;
PyObject *hwhdr;
PyObject *payload;
PyObject *prefix;
PyObject *raw;
PyObject *devnames;
} nflogdataobject;
typedef struct {
PyObject_HEAD
nflogdataobject *nd;
int n;
} nflogdataiter;
static PyObject * _NfadAsTuple(struct nflog_data *nfad);
static struct nflog_data * _TupleAsNfad(PyObject *tup);
static PyObject * _PyLong_AsBigEndian(PyObject *pylong, unsigned char width);
static PyObject * _ull_AsBigEndian(unsigned long long val, unsigned char width);
static void nd_dealloc(nflogdataobject *nd) {
Py_XDECREF(nd->indev);
Py_XDECREF(nd->physindev);
Py_XDECREF(nd->outdev);
Py_XDECREF(nd->physoutdev);
Py_XDECREF(nd->uid);
Py_XDECREF(nd->gid);
Py_XDECREF(nd->hwhdr);
Py_XDECREF(nd->payload);
Py_XDECREF(nd->prefix);
Py_XDECREF(nd->raw);
Py_XDECREF(nd->devnames);
PyObject_Del(nd);
}
// wraps if_indextoname with fallback behaviour for failure
static PyObject * _if_indextoname(uint32_t idx) {
char buf[IF_NAMESIZE] = {0};
if (!if_indextoname(idx, buf)) {
snprintf(buf, sizeof(buf), "unkn/%u", idx);
}
return Py_BuildValue("s", buf);
}
// look up device name from index with mock support
static PyObject * _devname(nflogdataobject *nd, uint32_t idx) {
if (idx) {
PyObject *devname;
// if devnames is non-null, check there first
if (nd->devnames) {
PyObject *devidx;
if (!(devidx = Py_BuildValue("k", idx))) { return NULL; }
if ((devname = PyDict_GetItem(nd->devnames, devidx))) {
// found
Py_INCREF(devname);
} else {
// not found, ask the system and save
devname = _if_indextoname(idx);
if (PyDict_SetItem(nd->devnames, devidx, devname) != 0) {
Py_DECREF(devname);
Py_DECREF(devidx);
return NULL;
}
}
Py_DECREF(devidx);
} else {
devname = _if_indextoname(idx);
}
return devname;
} else {
Py_RETURN_NONE;
}
}
PyObject * new_nflogdataobject(struct nflog_data *nfad, PyObject *devnames) {
nflogdataobject *nd = PyObject_New(nflogdataobject, &NflogDatatype);
if (!nd) { return NULL; }
nd->hwtype = nflog_get_hwtype(nfad);
nd->nfmark = nflog_get_nfmark(nfad);
// proto
struct nfulnl_msg_packet_hdr *ph = nflog_get_msg_packet_hdr(nfad);
nd->proto = ph ? ntohs(ph->hw_protocol) : 0;
// timestamp
_PyTime_t tp;
struct timeval tv;
if (nflog_get_timestamp(nfad, &tv) != 0) {
PyErr_SetString(NflogError, "no timestamp data");
nd_dealloc(nd);
return NULL;
}
if (_PyTime_FromTimeval(&tp, &tv) != 0) {
nd_dealloc(nd);
return NULL;
}
nd->timestamp = _PyTime_AsSecondsDouble(tp);
// internal values
if ((nd->devnames = devnames)) {
nd->raw = _NfadAsTuple(nfad);
} else {
nd->raw = Py_None;
Py_INCREF(Py_None);
}
// devs
nd->indev = _devname(nd, nflog_get_indev(nfad));
nd->physindev = _devname(nd, nflog_get_physindev(nfad));
nd->outdev = _devname(nd, nflog_get_outdev(nfad));
nd->physoutdev = _devname(nd, nflog_get_physoutdev(nfad));
// uid/gid
uint32_t id;
if (nflog_get_uid(nfad, &id) == 0) {
if (!(nd->uid = Py_BuildValue("k", id))) {
nd_dealloc(nd);
return NULL;
}
} else {
nd->uid = Py_None;
Py_INCREF(Py_None);
}
if (nflog_get_gid(nfad, &id) == 0) {
if (!(nd->gid = Py_BuildValue("k", id))) {
nd_dealloc(nd);
return NULL;
}
} else {
nd->gid = Py_None;
Py_INCREF(Py_None);
}
// hwaddr
struct nfulnl_msg_packet_hw *hw = nflog_get_packet_hw(nfad);
if (hw) {
if (!(nd->hwaddr = Py_BuildValue("y#", hw->hw_addr, ntohs(hw->hw_addrlen)))) {
nd_dealloc(nd);
return NULL;
}
} else {
nd->hwaddr = Py_None;
Py_INCREF(Py_None);
}
char *hwhdr = nflog_get_msg_packet_hwhdr(nfad);
size_t hwhdr_sz = nflog_get_msg_packet_hwhdrlen(nfad);
if (!(nd->hwhdr = Py_BuildValue("y#", hwhdr, hwhdr_sz))) {
nd_dealloc(nd);
return NULL;
}
char *payload;
int payload_sz = nflog_get_payload(nfad, &payload);
if (!(nd->payload = Py_BuildValue("y#", payload, payload_sz))) {
nd_dealloc(nd);
return NULL;
}
char *prefix = nflog_get_prefix(nfad);
if (!(nd->prefix = Py_BuildValue("s", prefix))) {
nd_dealloc(nd);
return NULL;
}
return (PyObject *)nd;
}
static PyObject * nd_get_proto(nflogdataobject *nd, void *) {
return Py_BuildValue("H", nd->proto);
}
static PyObject * nd_get_hwtype(nflogdataobject *nd, void *) {
return Py_BuildValue("H", nd->hwtype);
}
static PyObject * nd_get_nfmark(nflogdataobject *nd, void *) {
return Py_BuildValue("k", nd->nfmark);
}
static PyObject * nd_get_timestamp(nflogdataobject *nd, void *) {
return PyFloat_FromDouble(nd->timestamp);
}
static PyObject * nd_get_indev(nflogdataobject *nd, void *) {
Py_INCREF(nd->indev);
return nd->indev;
}
static PyObject * nd_get_physindev(nflogdataobject *nd, void *) {
Py_INCREF(nd->physindev);
return nd->physindev;
}
static PyObject * nd_get_outdev(nflogdataobject *nd, void *) {
Py_INCREF(nd->outdev);
return nd->outdev;
}
static PyObject * nd_get_physoutdev(nflogdataobject *nd, void *) {
Py_INCREF(nd->physoutdev);
return nd->physoutdev;
}
static PyObject * nd_get_uid(nflogdataobject *nd, void *) {
Py_INCREF(nd->uid);
return nd->uid;
}
static PyObject * nd_get_gid(nflogdataobject *nd, void *) {
Py_INCREF(nd->gid);
return nd->gid;
}
static PyObject * nd_get_hwaddr(nflogdataobject *nd, void *) {
Py_INCREF(nd->hwaddr);
return nd->hwaddr;
}
static PyObject * nd_get_hwhdr(nflogdataobject *nd, void *) {
Py_INCREF(nd->hwhdr);
return nd->hwhdr;
}
static PyObject * nd_get_payload(nflogdataobject *nd, void *) {
Py_INCREF(nd->payload);
return nd->payload;
}
static PyObject * nd_get_prefix(nflogdataobject *nd, void *) {
Py_INCREF(nd->prefix);
return nd->prefix;
}
// all getters return new references
static PyGetSetDef nd_getset[] = {
{"proto", (getter)nd_get_proto, NULL, NULL, NULL},
{"hwtype", (getter)nd_get_hwtype, NULL, NULL, NULL},
{"nfmark", (getter)nd_get_nfmark, NULL, NULL, NULL},
{"timestamp", (getter)nd_get_timestamp, NULL, NULL, NULL},
{"indev", (getter)nd_get_indev, NULL, NULL, NULL},
{"physindev", (getter)nd_get_physindev, NULL, NULL, NULL},
{"outdev", (getter)nd_get_outdev, NULL, NULL, NULL},
{"physoutdev", (getter)nd_get_physoutdev, NULL, NULL, NULL},
{"uid", (getter)nd_get_uid, NULL, NULL, NULL},
{"gid", (getter)nd_get_gid, NULL, NULL, NULL},
{"hwaddr", (getter)nd_get_hwaddr, NULL, NULL, NULL},
{"hwhdr", (getter)nd_get_hwhdr, NULL, NULL, NULL},
{"payload", (getter)nd_get_payload, NULL, NULL, NULL},
{"prefix", (getter)nd_get_prefix, NULL, NULL, NULL},
{NULL}
};
// generate serialization structures for device names, returns -1 on failure
static int _set_dev(
PyObject *devnames, PyObject *raw, PyObject *ifnames[], PyObject *dev,
int ifcount, Py_ssize_t n
) {
if (dev == Py_None) { return 0; }
// loop over ifnames looking for a matching name
int i = 0, rv;
for (;;) {
if (i > ifcount) {
PyErr_SetString(PyExc_RuntimeError, "too many interfaces!?");
return -1;
} else if (i == ifcount) {
ifnames[i] = dev;
break;
} else if ((rv = PyUnicode_Compare(ifnames[i], dev)) == 0) {
break;
} else if (rv == -1 && _GIL_PyErr_Occurred()) {
return -1;
}
++i;
}
i = i + 1; // device indexes start at 1
// save the results
PyObject *item, *devidx;
if (!(item = _ull_AsBigEndian(i, 4))) { return -1; }
PyTuple_SET_ITEM(raw, n, item);
if (!(devidx = Py_BuildValue("k", i))) { return -1; }
if (PyDict_SetItem(devnames, devidx, dev) != 0) { return -1; }
Py_INCREF(dev);
return i;
}
// get raw data, aliased as __getnewargs to enable pickling
PyDoc_STRVAR(nd__get_raw_doc,
"_get_raw($self, useraw=None, /)\n"
"--\n\n"
"INTENDED FOR DEBUGGING/TESTING ONLY!\n\n"
"get raw data, can be passed to pass to __new__ to recreate this object\n"
"\nArgs:\n"
" useraw (Union[bool, None]): Whether saved raw data should be used.\n"
" Defaults to None, which means 'use if available'.\n If False, a raw\n"
" data structure will be synthesized regardless of whether the original\n"
" is available. If True, then None will be returned if raw data wasn't\n"
" saved at instantiation.\n"
"\nReturns:\n"
" Tuple[Dict[int, str], Tuple[Union[bytes, None]]]: a raw data structure\n"
"\n"
);
static PyObject * nd__get_raw(nflogdataobject *nd, PyObject *args) {
PyObject *pyuseraw = Py_None;
if (!PyArg_ParseTuple(args, "|O:_get_raw", &pyuseraw)) { return NULL; }
return nd__get_raw_impl((PyObject *)nd, pyuseraw);
}
PyObject * nd__get_raw_impl(PyObject *o, PyObject *pyuseraw) {
nflogdataobject *nd = (nflogdataobject *)o;
// by default, use the raw data if it exists
int useraw = !!(nd->devnames);
PyObject *ret, *devnames, *raw, *item;
if (_nflogr_tristate(pyuseraw, &useraw) != 0) { return NULL; }
if (!(ret = PyTuple_New(2))) { return NULL; }
if (useraw) {
if (!(nd->devnames)) {
Py_DECREF(ret);
Py_RETURN_NONE;
}
Py_INCREF(nd->devnames);
PyTuple_SET_ITEM(ret, 0, nd->devnames);
Py_INCREF(nd->raw);
PyTuple_SET_ITEM(ret, 1, nd->raw);
return ret;
}
// not using raw data, so generate a struct from the data we saved
// XXX THIS WILL NOT MATCH EXACTLY!
if (!(devnames = PyDict_New())) {
Py_DECREF(ret);
return NULL;
}
if (!(raw = PyTuple_New(NFULA_MAX))) {
Py_DECREF(devnames);
Py_DECREF(ret);
return NULL;
}
// NFULA_PACKET_HDR - construct from nd->proto
if (nd->proto) {
char packet_hdr[4];
packet_hdr[0] = ((nd->proto) >> 8) & 255;
packet_hdr[1] = (nd->proto) & 255;
if (!(item = Py_BuildValue("y#", packet_hdr, 4))) { goto nd__get_raw_cleanup; }
PyTuple_SET_ITEM(raw, NFULA_PACKET_HDR-1, item);
}
// NFULA_MARK - construct from nd->nfmark
if (!(item = _ull_AsBigEndian(nd->nfmark, 4))) { goto nd__get_raw_cleanup; }
PyTuple_SET_ITEM(raw, NFULA_MARK-1, item);
{
// NFULA_TIMESTAMP - construct from nd->timestamp
struct nfulnl_msg_packet_timestamp uts;
double sec = nd->timestamp;
uint64_t usec = ((0.0000005 + sec) - ((uint64_t)sec)) * 1000000.0;
if (usec > 999999) { usec = 999999; } // just in case...
uts.sec = htobe64(sec);
uts.usec = htobe64(usec);
if (!(item = Py_BuildValue("y#", (char *)(&uts), sizeof(uts)))) {
goto nd__get_raw_cleanup;
}
PyTuple_SET_ITEM(raw, NFULA_TIMESTAMP-1, item);
}
{
// NFULA_IFINDEX_INDEV - construct from nd->indev + ifnames
// NFULA_IFINDEX_PHYSINDEV - construct from nd->physindev + ifnames
// NFULA_IFINDEX_OUTDEV - construct from nd->outdev + ifnames
// NFULA_IFINDEX_PHYSOUTDEV - construct from nd->physoutdev + ifnames
int ifcount = 0;
PyObject *ifnames[4];
if ((ifcount = _set_dev(
devnames, raw, ifnames, nd->indev, ifcount, NFULA_IFINDEX_INDEV-1)
) < 0) { goto nd__get_raw_cleanup; }
if ((ifcount = _set_dev(
devnames, raw, ifnames, nd->physindev, ifcount, NFULA_IFINDEX_PHYSINDEV-1)
) < 0) { goto nd__get_raw_cleanup; }
if ((ifcount = _set_dev(
devnames, raw, ifnames, nd->outdev, ifcount, NFULA_IFINDEX_OUTDEV-1)
) < 0) { goto nd__get_raw_cleanup; }
if ((ifcount = _set_dev(
devnames, raw, ifnames, nd->physoutdev, ifcount, NFULA_IFINDEX_PHYSOUTDEV-1)
) < 0) { goto nd__get_raw_cleanup; }
}
if (nd->hwaddr != Py_None) {
// NFULA_HWADDR - construct from nd->hwaddr
struct nfulnl_msg_packet_hw hw;
memset(&hw, 0, sizeof(hw));
char *hwaddr_data;
Py_ssize_t hwaddr_size;
if (PyBytes_AsStringAndSize(nd->hwaddr, &hwaddr_data, &hwaddr_size) != 0) {
goto nd__get_raw_cleanup;
} else if (hwaddr_size > (Py_ssize_t)sizeof(hw.hw_addr)) {
PyErr_SetString(PyExc_ValueError, "hwaddr too large");
goto nd__get_raw_cleanup;
}
hw.hw_addrlen = hwaddr_size;
memcpy(hw.hw_addr, hwaddr_data, hwaddr_size);
if (!(item = Py_BuildValue("y#", &hw, sizeof(hw)))) { goto nd__get_raw_cleanup; }
PyTuple_SET_ITEM(raw, NFULA_HWADDR-1, item);
}
{
// NFULA_PAYLOAD - construct from nd->payload
// nflog_get_payload discards NFA_LENGTH(0) bytes, so we need to add padding
char *payload_data, *payload_pad;
Py_ssize_t payload_size;
if (PyBytes_AsStringAndSize(nd->payload, &payload_data, &payload_size) != 0) {
goto nd__get_raw_cleanup;
}
if (!(payload_pad = (char *)calloc(1, payload_size + NFA_LENGTH(0)))) {
PyErr_NoMemory();
goto nd__get_raw_cleanup;
}
memcpy(payload_pad, payload_data, payload_size);
if (!(item = Py_BuildValue("y#", payload_pad, payload_size + NFA_LENGTH(0)))) {
goto nd__get_raw_cleanup;
}
PyTuple_SET_ITEM(raw, NFULA_PAYLOAD-1, item);
}
{
// NFULA_PREFIX - construction from nd->prefix
Py_ssize_t pfxlen;
char *pfxstr;
if (!(pfxstr = (char *)PyUnicode_AsUTF8AndSize(nd->prefix, &pfxlen))) {
goto nd__get_raw_cleanup;
}
if (!(item = Py_BuildValue("y#", pfxstr, pfxlen + 1))) { goto nd__get_raw_cleanup; }
PyTuple_SET_ITEM(raw, NFULA_PREFIX-1, item);
}
// NFULA_UID - construct from nd->uid
if (!(item = _PyLong_AsBigEndian(nd->uid, 4))) { goto nd__get_raw_cleanup; }
PyTuple_SET_ITEM(raw, NFULA_UID-1, item);
// NFULA_SEQ - not supported
// NFULA_SEQ_GLOBAL - not supported
// NFULA_GID - construct from nd->gid
if (!(item = _PyLong_AsBigEndian(nd->gid, 4))) { goto nd__get_raw_cleanup; }
PyTuple_SET_ITEM(raw, NFULA_GID-1, item);
// NFULA_HWTYPE - construct from nd->hwtype
if (!(item = _ull_AsBigEndian(nd->hwtype, 2))) { goto nd__get_raw_cleanup; }
PyTuple_SET_ITEM(raw, NFULA_HWTYPE-1, item);
// NFULA_HWHEADER - construct from nd->hwhdr
Py_INCREF(nd->hwhdr);
PyTuple_SET_ITEM(raw, NFULA_HWHEADER-1, nd->hwhdr);
// NFULA_HWLEN - construct from nd->hwhdr
if (!(item = _ull_AsBigEndian(PyBytes_Size(nd->hwhdr), 2))) { goto nd__get_raw_cleanup; }
PyTuple_SET_ITEM(raw, NFULA_HWLEN-1, item);
// set any remaining values in the tuple to `None`
for (int i = 0; i < NFULA_MAX; ++i) {
if (!(item = PyTuple_GET_ITEM(raw, i))) {
Py_INCREF(Py_None);
PyTuple_SET_ITEM(raw, i, Py_None);
}
}
PyTuple_SET_ITEM(ret, 0, devnames);
PyTuple_SET_ITEM(ret, 1, raw);
return ret;
nd__get_raw_cleanup:
Py_DECREF(raw);
Py_DECREF(devnames);
Py_DECREF(ret);
return NULL;
}
static PyMethodDef nd_methods[] = {
{"_get_raw", (PyCFunction) nd__get_raw, METH_VARARGS, nd__get_raw_doc},
{"__getnewargs__", (PyCFunction) nd__get_raw, METH_VARARGS, PyDoc_STR(
"__getnewargs__($self, /)\n"
"--\n\n"
)},
{NULL, NULL}
};
struct nflog_data {
struct nfattr **nfa;
};
static PyObject * _NfadAsTuple(struct nflog_data *nfad) {
PyObject *tup = PyTuple_New(NFULA_MAX);
if (!tup) { return NULL; }
struct nfattr *nfa;
int i;
for (i = 0; i < NFULA_MAX; ++i) {
nfa = nfad->nfa[i];
if (nfa) {
PyObject *bytes;
// the l3 payload has to have padding because of reasons :-/
int len = nfa->nfa_len - (i == (NFULA_PAYLOAD-1) ? 0 : NFA_LENGTH(0));
if (!(bytes = Py_BuildValue("y#", (((char *)(nfa)) + NFA_LENGTH(0)), len))) {
return NULL;
}
PyTuple_SET_ITEM(tup, i, bytes);
} else {
Py_INCREF(Py_None);
PyTuple_SET_ITEM(tup, i, Py_None);
}
}
return tup;
}
static struct nflog_data * _TupleAsNfad(PyObject *tup) {
int i, alignto = 4;
PyObject *bytes;
Py_ssize_t sz = sizeof(void *) * __NFULA_MAX, off = sz;
Py_ssize_t len, n = PyTuple_Size(tup);
char *buf;
// first loop - calculate size required
for (i = 0; i < NFULA_MAX && i < n; ++i) {
bytes = PyTuple_GetItem(tup, i);
if (!bytes) {
return NULL;
} else if (bytes == Py_None) {
continue;
} else if (!PyBytes_Check(bytes)) {
PyErr_SetString(PyExc_TypeError, "tuple memeber not bytes or None");
return NULL;
} else if ((len = PyBytes_Size(bytes)) > 65535) {
PyErr_SetString(PyExc_ValueError, "tuple members must be at most 65535 bytes");
return NULL;
}
sz += (4 + PyBytes_Size(bytes) + alignto - 1) & ~(alignto - 1);
}
char *nfad = (char *)malloc(sz);
if (!nfad) {
PyErr_NoMemory();
return NULL;
}
// set nfa pointer
((char **)nfad)[0] = nfad + sizeof(void *);
i = 0; // second loop - copy data
while (i < NFULA_MAX) {
// if the tuple is short, the remaining pointers still need to be null
bytes = i < n ? PyTuple_GetItem(tup, i) : Py_None; ++i;
if (bytes == Py_None) {
((char **)nfad)[i] = NULL;
continue;
}
// this says `String` but per the docs null bytes are fine as of Python 3.5
if (PyBytes_AsStringAndSize(bytes, &buf, &len) != 0) { return NULL; }
((char **)nfad)[i] = nfad + off;
memcpy(nfad + off + 0, &len, 2);
memcpy(nfad + off + 2, &i, 2);
memcpy(nfad + off + 4, buf, len);
off += (4 + len + alignto - 1) & ~(alignto - 1);
}
return (struct nflog_data *)nfad;
}
static PyObject * _PyLong_AsBigEndian(PyObject *pylong, unsigned char width) {
if (pylong == Py_None) { Py_RETURN_NONE; }
unsigned long long val = PyLong_AsUnsignedLong(pylong);
if (val == ((unsigned long long)-1) && _GIL_PyErr_Occurred()) { return NULL; }
return _ull_AsBigEndian(val, width);
}
static PyObject * _ull_AsBigEndian(unsigned long long val, unsigned char width) {
char buf[8];
int p = 0;
switch (width) {
case 8:
buf[p++] = (val >> 56) & 255;
buf[p++] = (val >> 48) & 255;
buf[p++] = (val >> 40) & 255;
buf[p++] = (val >> 32) & 255;
case 4:
buf[p++] = (val >> 24) & 255;
buf[p++] = (val >> 16) & 255;
case 2:
buf[p++] = (val >> 8) & 255;
case 1:
buf[p++] = val & 255;
break;
default:
PyErr_SetString(PyExc_ValueError, "width must be 8, 4, 2 or 1");
return NULL;
}
PyObject *bytes = Py_BuildValue("y#", buf, width);
if (!bytes) { return NULL; }
return bytes;
}
PyObject * nd__iter__(nflogdataobject *nd) {
if (PyType_Ready(&NflogDataItertype) != 0) { return NULL; }
nflogdataiter *iter = PyObject_New(nflogdataiter, &NflogDataItertype);
if (!iter) { return NULL; }
iter->nd = nd;
iter->n = 0;
Py_INCREF(nd);
return (PyObject *)iter;
}
PyObject * nd__str__(nflogdataobject *nd) {
// basically equivalent to dict(nd)
PyObject *dict = PyDict_New();
if (!dict) { return NULL; }
if (PyDict_MergeFromSeq2(dict, (PyObject *)nd, 0) != 0) {
Py_DECREF(dict);
return NULL;
}
// format the dict with the name of the type
PyObject *repr = PyUnicode_FromFormat("<%s %S>", _PyType_Name(Py_TYPE(nd)), dict);
Py_DECREF(dict);
return repr;
}
PyObject * nd__repr__(nflogdataobject *nd) {
if (nd->raw == Py_None) { return nd__str__(nd); }
return PyUnicode_FromFormat("%s(%R, %R)", _PyType_Name(Py_TYPE(nd)), nd->devnames, nd->raw);
}
PyObject * nd__new__(PyTypeObject *subtype, PyObject *args, PyObject *) {
PyObject *dict, *tup;
if (!PyArg_ParseTuple(args, "OO:__new__", &dict, &tup)) { return NULL; }
if (!PyDict_Check(dict) || !PyTuple_Check(tup)) {
PyErr_SetString(PyExc_TypeError, "arguments must be (dict, tuple)");
return NULL;
}
// nflog_handle_packet normally takes care of freeing the nflog_data struct
// after creating it and sending it to the callback, and since we're creating
// the struct outselves here, we also need to free it ourselves.
struct nflog_data *nfad = _TupleAsNfad(tup);
if (!nfad) { return NULL; }
Py_INCREF(dict);
PyObject *nd = new_nflogdataobject(nfad, dict);
free(nfad);
return nd;
}
PyTypeObject NflogDatatype {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"nflogr.NflogData", /* tp_name */
sizeof(nflogdataobject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)nd_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
(reprfunc)nd__repr__, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
(reprfunc)nd__str__, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
NULL, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
(getiterfunc)nd__iter__, /* tp_iter */
0, /* tp_iternext */
nd_methods, /* tp_methods */
0, /* tp_members */
nd_getset, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
(newfunc)nd__new__, /* tp_new */
};
// iterator helper class
static void ndi_dealloc(nflogdataiter *ndi) {
Py_DECREF(ndi->nd);
PyObject_Del(ndi);
}
PyObject * ndi__iter__(nflogdataiter *ndi) {
Py_INCREF(ndi);
return (PyObject *)ndi;
}
PyObject * ndi__next__(nflogdataiter *ndi) {
char *name;
getter *get;
PyObject *val;
do {
name = (char *)(nd_getset[ndi->n].name);
get = &(nd_getset[ndi->n].get);
if (!name) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
ndi->n += 1;
// skip over attributes starting with an underscore
} while (name[0] == '_');
// call the getter, passing along any failures
if (!(val = (*get)((PyObject *)(ndi->nd), NULL))) {
return NULL;
}
return Py_BuildValue("(sN)", name, val);
}
PyTypeObject NflogDataItertype {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"nflogr.NflogDataIter", /* tp_name */
sizeof(nflogdataiter), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)ndi_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
NULL, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
(getiterfunc)ndi__iter__, /* tp_iter */
(iternextfunc)ndi__next__, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
};
/* vim: set ts=2 sw=2 et ai si: */
| 29.628435 | 94 | 0.600387 | [
"object"
] |
3023152b9ed4cfa8787c043b5396162888d03407 | 10,403 | cpp | C++ | libgputk/gputkSolution.cpp | xlmentx/Parallel-Computing | 0785f18afaabd5daf2efd89607f643845a07b3c0 | [
"MIT"
] | null | null | null | libgputk/gputkSolution.cpp | xlmentx/Parallel-Computing | 0785f18afaabd5daf2efd89607f643845a07b3c0 | [
"MIT"
] | null | null | null | libgputk/gputkSolution.cpp | xlmentx/Parallel-Computing | 0785f18afaabd5daf2efd89607f643845a07b3c0 | [
"MIT"
] | null | null | null |
#include "gputk.h"
char *solutionJSON = nullptr;
static string _solution_correctQ("");
static void _onUnsameImageFunction(string str) {
_solution_correctQ = str;
}
template <typename T>
static gpuTKBool gpuTKSolution_listCorrectQ(const char *expectedOutputFile,
gpuTKSolution_t sol, const char *type) {
gpuTKBool res;
T *expectedData;
int expectedRows, expectedColumns;
expectedData = (T *)gpuTKImport(expectedOutputFile, &expectedRows,
&expectedColumns, type);
if (expectedData == nullptr) {
_solution_correctQ = "Failed to open expected output file.";
res = gpuTKFalse;
} else if (expectedRows != gpuTKSolution_getRows(sol)) {
gpuTKLog(TRACE, "Number of rows in the solution is ",
gpuTKSolution_getRows(sol), ". Expected number of rows is ",
expectedRows, ".");
_solution_correctQ =
"The number of rows in the solution did not match "
"that of the expected results.";
res = gpuTKFalse;
} else if (expectedColumns != gpuTKSolution_getColumns(sol)) {
gpuTKLog(TRACE, "Number of columns in the solution is ",
gpuTKSolution_getColumns(sol), ". Expected number of columns is ",
expectedColumns, ".");
_solution_correctQ = "The number of columns in the solution did not "
"match that of the expected results.";
res = gpuTKFalse;
} else {
int ii, jj, idx;
T *solutionData;
solutionData = (T *)gpuTKSolution_getData(sol);
if (gpuTKSolution_getType(sol) == "integral_vector/sorted") {
gpuTKSort(solutionData, expectedRows * expectedColumns);
}
for (ii = 0; ii < expectedRows; ii++) {
for (jj = 0; jj < expectedColumns; jj++) {
idx = ii * expectedColumns + jj;
if (gpuTKUnequalQ(expectedData[idx], solutionData[idx])) {
string str;
if (expectedColumns == 1) {
str = gpuTKString(
"The solution did not match the expected results at row ",
ii, ". Expecting ", expectedData[idx], " but got ",
solutionData[idx], ".");
} else {
str = gpuTKString("The solution did not match the expected "
"results at column ",
jj, " and row ", ii, ". Expecting ",
expectedData[idx], " but got ",
solutionData[idx], ".");
}
_solution_correctQ = str;
res = gpuTKFalse;
goto matrixCleanup;
}
}
}
res = gpuTKTrue;
matrixCleanup:
if (expectedData != nullptr) {
gpuTKFree(expectedData);
}
}
return res;
}
static gpuTKBool gpuTKSolution_correctQ(char *expectedOutputFile,
gpuTKSolution_t sol) {
if (expectedOutputFile == nullptr) {
_solution_correctQ = "Failed to determined the expected output file.";
return gpuTKFalse;
} else if (!gpuTKFile_existsQ(expectedOutputFile)) {
_solution_correctQ =
gpuTKString("The file ", expectedOutputFile, " does not exist.");
return gpuTKFalse;
} else if (gpuTKString_sameQ(gpuTKSolution_getType(sol), "image")) {
gpuTKBool res;
gpuTKImage_t solutionImage = nullptr;
gpuTKImage_t expectedImage = gpuTKImport(expectedOutputFile);
if (expectedImage == nullptr) {
_solution_correctQ = "Failed to open expected output file.";
res = gpuTKFalse;
} else if (gpuTKImage_getWidth(expectedImage) !=
gpuTKSolution_getWidth(sol)) {
_solution_correctQ =
"The image width of the expected image does not "
"match that of the solution.";
res = gpuTKFalse;
} else if (gpuTKImage_getHeight(expectedImage) !=
gpuTKSolution_getHeight(sol)) {
_solution_correctQ =
"The image height of the expected image does not "
"match that of the solution.";
res = gpuTKFalse;
} else if (gpuTKImage_getChannels(expectedImage) !=
gpuTKSolution_getChannels(sol)) {
_solution_correctQ =
"The image channels of the expected image does not "
"match that of the solution.";
res = gpuTKFalse;
} else {
solutionImage = (gpuTKImage_t)gpuTKSolution_getData(sol);
gpuTKAssert(solutionImage != nullptr);
res = gpuTKImage_sameQ(solutionImage, expectedImage,
_onUnsameImageFunction);
}
if (expectedImage != nullptr) {
gpuTKImage_delete(expectedImage);
}
return res;
} else if (gpuTKString_sameQ(gpuTKSolution_getType(sol), "histogram")) {
return gpuTKSolution_listCorrectQ<unsigned char>(expectedOutputFile, sol,
"Integer");
} else if (gpuTKString_sameQ(gpuTKSolution_getType(sol), "integral_vector/sorted") ||
gpuTKString_sameQ(gpuTKSolution_getType(sol), "integral_vector")) {
return gpuTKSolution_listCorrectQ<int>(expectedOutputFile, sol,
"Integer");
} else if (gpuTKString_sameQ(gpuTKSolution_getType(sol), "vector") ||
gpuTKString_sameQ(gpuTKSolution_getType(sol), "matrix")) {
return gpuTKSolution_listCorrectQ<gpuTKReal_t>(expectedOutputFile, sol,
"Real");
} else {
gpuTKAssert(gpuTKFalse);
return gpuTKFalse;
}
}
gpuTKBool gpuTKSolution(char *expectedOutputFile, char *outputFile, char *type0,
void *data, int rows, int columns, int depth) {
char *type;
gpuTKBool res;
gpuTKSolution_t sol;
if (expectedOutputFile == nullptr || data == nullptr || type0 == nullptr) {
gpuTKLog(ERROR, "Failed to grade solution, %s %s %s", expectedOutputFile, data, type0);
return gpuTKFalse;
}
type = gpuTKString_toLower(type0);
if (_solution_correctQ != "") {
_solution_correctQ = "";
}
gpuTKSolution_setOutputFile(sol, outputFile);
gpuTKSolution_setId(sol, uuid());
gpuTKSolution_setSessionId(sol, sessionId());
gpuTKSolution_setType(sol, type);
gpuTKSolution_setData(sol, data);
gpuTKSolution_setRows(sol, rows);
gpuTKSolution_setColumns(sol, columns);
gpuTKSolution_setDepth(sol, depth);
res = gpuTKSolution_correctQ(expectedOutputFile, sol);
if (outputFile != nullptr) {
if (gpuTKString_sameQ(type, "image")) {
gpuTKImage_t inputImage = (gpuTKImage_t)data;
gpuTKImage_t img = gpuTKImage_new(gpuTKImage_getWidth(inputImage),
gpuTKImage_getHeight(inputImage),
gpuTKImage_getChannels(inputImage));
memcpy(gpuTKImage_getData(img), gpuTKImage_getData(inputImage),
rows * columns * depth * sizeof(gpuTKReal_t));
gpuTKExport(outputFile, img);
gpuTKImage_delete(img);
} else if (gpuTKString_sameQ(type, "integral_vector/sort")) {
gpuTKSort((int *)data, rows*columns);
gpuTKExport(outputFile, (int *)data, rows, columns);
} else if (gpuTKString_sameQ(type, "integral_vector")) {
gpuTKExport(outputFile, (int *)data, rows, columns);
} else if (gpuTKString_sameQ(type, "vector") ||
gpuTKString_sameQ(type, "matrix")) {
gpuTKExport(outputFile, (gpuTKReal_t *)data, rows, columns);
} else if (gpuTKString_sameQ(type, "histogram")) {
gpuTKExport(outputFile, (unsigned char *)data, rows, columns);
} else if (gpuTKString_sameQ(type, "text")) {
gpuTKExport_text(outputFile, (unsigned char *)data, rows * columns);
}
}
gpuTKFree(type);
return res;
}
gpuTKBool gpuTKSolution(char *expectedOutputFile, char *outputFile, char *type0,
void *data, int rows, int columns) {
return gpuTKSolution(expectedOutputFile, outputFile, type0, data, rows,
columns, 1);
}
gpuTKBool gpuTKSolution(gpuTKArg_t arg, void *data, int rows, int columns,
int depth) {
char *type;
gpuTKBool res;
char *expectedOutputFile;
char *outputFile;
stringstream ss;
expectedOutputFile = gpuTKArg_getExpectedOutputFile(arg);
outputFile = gpuTKArg_getOutputFile(arg);
type = gpuTKArg_getType(arg);
gpuTKAssert(type != nullptr);
gpuTKAssert(expectedOutputFile != nullptr);
gpuTKAssert(outputFile != nullptr);
res = gpuTKSolution(expectedOutputFile, outputFile, type, data, rows,
columns, depth);
if (GPUTK_USE_JSON11) {
json11::Json json;
if (res) {
#ifndef JSON_OUTPUT
printf("The solution is correct\n");
#endif
json = json11::Json::object{{"correctq", true},
{"message", "The solution is correct"}};
} else {
#ifndef JSON_OUTPUT
printf("The solution is NOT correct\n");
#endif
json = json11::Json::object{{"correctq", false},
{"message", _solution_correctQ}};
}
#ifdef gpuTKLogger_printOnLog
if (gpuTKLogger_printOnLog) {
json11::Json e =
json11::Json::object{{"type", "solution"}, {"data", json}};
std::cout << e.dump() << std::endl;
}
#endif /* gpuTKLogger_printOnLog */
solutionJSON = gpuTKString_duplicate(json.string_value());
} else {
if (res) {
#ifndef JSON_OUTPUT
printf("Solution is correct\n");
#endif
ss << "{\n";
ss << gpuTKString_quote("correctq") << ": true,\n";
ss << gpuTKString_quote("message") << ": "
<< gpuTKString_quote("Solution is correct.") << "\n";
ss << "}";
} else {
#ifndef JSON_OUTPUT
printf("Solution is NOT correct\n");
#endif
ss << "{\n";
ss << gpuTKString_quote("correctq") << ": false,\n";
ss << gpuTKString_quote("message") << ": "
<< gpuTKString_quote(_solution_correctQ) << "\n";
ss << "}";
}
solutionJSON = gpuTKString_duplicate(ss.str());
}
return res;
}
gpuTKBool gpuTKSolution(gpuTKArg_t arg, void *data, int rows, int columns) {
return gpuTKSolution(arg, data, rows, columns, 1);
}
EXTERN_C gpuTKBool gpuTKSolution(gpuTKArg_t arg, void *data, int rows) {
return gpuTKSolution(arg, data, rows, 1);
}
gpuTKBool gpuTKSolution(gpuTKArg_t arg, gpuTKImage_t img) {
return gpuTKSolution(arg, img, gpuTKImage_getHeight(img),
gpuTKImage_getWidth(img), gpuTKImage_getChannels(img));
}
| 36.121528 | 91 | 0.624531 | [
"object",
"vector"
] |
302359217e363bdb8aefe9abbab3a58f12bf2e13 | 2,122 | cpp | C++ | gearoenix/dx11/buffer/gx-dx11-buf-mesh.cpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 35 | 2018-01-07T02:34:38.000Z | 2022-02-09T05:19:03.000Z | gearoenix/dx11/buffer/gx-dx11-buf-mesh.cpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 111 | 2017-09-20T09:12:36.000Z | 2020-12-27T12:52:03.000Z | gearoenix/dx11/buffer/gx-dx11-buf-mesh.cpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 5 | 2020-02-11T11:17:37.000Z | 2021-01-08T17:55:43.000Z | #include "gx-dx11-buf-mesh.hpp"
#ifdef GX_USE_DIRECTX11
#include "../../core/gx-cr-static.hpp"
#include "../../system/gx-sys-log.hpp"
#include "../../system/stream/gx-sys-stm-stream.hpp"
#include "../dx11-check.hpp"
#include "../dx11-engine.hpp"
gearoenix::dx11::buffer::Mesh::Mesh(
unsigned int vec, system::stream::Stream* format,
Engine* e, core::sync::EndCaller<core::sync::EndCallerIgnore> c)
: render::buffer::Mesh(e)
, stride(vec * sizeof(core::Real))
{
core::Count cnt;
format->read(cnt);
core::Count vsec = cnt * vec;
std::vector<core::Real> vd((size_t)vsec);
unsigned int vs = (unsigned int)(vsec * sizeof(core::Real));
for (core::Count i = 0; i < vsec; ++i) {
format->read(vd[(size_t)i]);
}
format->read(cnt);
ic = (unsigned int)cnt;
std::vector<std::uint32_t> idata((size_t)cnt);
for (core::Count i = 0; i < cnt; ++i)
format->read(idata[(size_t)i]);
unsigned int is = (unsigned int)(cnt * sizeof(std::uint32_t));
ID3D11Device* dev = e->get_device();
D3D11_BUFFER_DESC desc;
D3D11_SUBRESOURCE_DATA buf_data;
GX_SET_ZERO(desc);
GX_SET_ZERO(buf_data);
desc.Usage = D3D11_USAGE_IMMUTABLE;
desc.ByteWidth = vs;
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
buf_data.pSysMem = vd.data();
GXHRCHK(dev->CreateBuffer(&desc, &buf_data, &vb))
desc.Usage = D3D11_USAGE_IMMUTABLE;
desc.ByteWidth = is;
desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
buf_data.pSysMem = idata.data();
GXHRCHK(dev->CreateBuffer(&desc, &buf_data, &ib));
}
gearoenix::dx11::buffer::Mesh::~Mesh()
{
vb->Release();
ib->Release();
}
void gearoenix::dx11::buffer::Mesh::bind()
{
const unsigned int offset = 0;
ID3D11DeviceContext* ctx = static_cast<Engine*>(engine)->get_context();
ctx->IASetVertexBuffers(0, 1, &vb, &stride, &offset);
ctx->IASetIndexBuffer(ib, DXGI_FORMAT_R32_UINT, 0);
ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}
void gearoenix::dx11::buffer::Mesh::draw()
{
static_cast<Engine*>(engine)->get_context()->DrawIndexed(ic, 0, 0);
}
#endif
| 31.671642 | 75 | 0.656927 | [
"mesh",
"render",
"vector"
] |
6f79e0a52ab04b9fb24dfef39065d2ab9149aabe | 21,720 | cpp | C++ | Microsoft/SAMPLES/xrt/xrtobj32/xrtobj32.cpp | tig/Tigger | 8e06d117a5b520c5fc9e37a710bf17aa51a9958c | [
"MIT",
"Unlicense"
] | 1 | 2021-08-02T01:36:43.000Z | 2021-08-02T01:36:43.000Z | Microsoft/SAMPLES/xrt/xrtobj32/xrtobj32.cpp | mdileep/Tigger | 8e06d117a5b520c5fc9e37a710bf17aa51a9958c | [
"MIT",
"Unlicense"
] | null | null | null | Microsoft/SAMPLES/xrt/xrtobj32/xrtobj32.cpp | mdileep/Tigger | 8e06d117a5b520c5fc9e37a710bf17aa51a9958c | [
"MIT",
"Unlicense"
] | 1 | 2022-01-04T21:13:01.000Z | 2022-01-04T21:13:01.000Z | // xrtobj32.cpp
//
// This is the WinMain module for a WOSA/XRT compliant Data Object.
//
// Copyright (c) 1993 Microsoft Corporation, All Rights Reserved.
//
// Charlie Kindel, Program Manager
// Microsoft Vertical Developer Relations
// October 29, 1993
//
// Internet : ckindel@microsoft.com
// CompuServe : >INTERNET:ckindel@microsoft.com
//
// Revisions:
// October 29, 1993 cek Created
//
// -------------------------------------------------------------------------
//
// Notes:
//
// This application implements a very simple COM object that supports
// the basic interfaces required for Uniform Data Transfer (i.e.
// IDataObject, IEnumFORMATETC).
//
// If this application is started with /Embedding on the command line
// then the application will exit once all refcounts on interfaces go
// to zero. If the application is started without /Embedding, user action
// is required to shut the program down (i.e. ALT-F4).
//
// The structure of this program is as thus:
//
// There is a main window ("fnMainWnd") which contains several child windows:
//
// A listbox showing the current data set
// A box that shows status information such as the refcounts on the
// various interfaces
// A menu with File.Exit, Options.Update Speed...,
// Options.Market Simulation, and Help.About...
//
// TODO: Dialog boxes not implemented yet.
//
// When the main window is created a timer is started (WM_TIMER style) using
// an update rate as specified in XRTOBJ32.INI. This update rate can
// be changed using the Options.Update Speed... menu command (which pops up
// a dialog and saves the chages to XRTOBJ32.INI).
//
// At startup, a list of instruments (Ticker Symbol, Last Price, and
// Last Volume) is read from XRTOBJ32.INI into an array of XRTSTOCK
// structures.
//
// On each WM_TIMER message each XRTSTOCK element is randomly changed.
// The 'randomizer' code is only semi-random. Variables specify
// whether the stock prices should increase or decrease (allowing
// simulation of an increasing or decreasing market).
//
// The XRTSTOCK structure contains a member that allows code to determine
// whether informaiton in the structure has changed since the last look.
//
// After the WM_TIMER code has finished updating the list of
// stocks, it notifies the IDataObject implementation
// essentially saying "Hey! Data has changed!". The IDataObject
// implementation then attempts to call the OnDataChange member
// of an IAdviseSink pointer it should have gotten via IDataObject::
// DAdvise. The IDataObject code fills a memory buffer with
// data and calls IAdviseSink::OnDataChange() with that data.
// Depending on which clipboard format was specified the
// data either represents a snapshot of the entire data set
// (CF_TEXT) or the set of data points that changed since
// the last OnDataChange was sent (CF_XRTMARKETDATA).
//
// The IDataObject code resets the member in the XRTSTOCK array
// that indicates changed data before it returns.
//
// So in effect what this application does is provide a simulation
// of a stock market data feed. The receiving end (IAdviseSink)
// can look at the data that comes across and treat each stock item
// as an individual 'trade'.
//
//
#include "precomp.h"
#include "resource.h"
#include "clsid.h"
#include "xrtobj32.h"
#include "object.h"
#include "simobj.h"
#include "debug.h"
// Forward function prototypes
BOOL InitApplication( HINSTANCE hInst ) ;
BOOL WINAPI DoAboutBox( VOID ) ;
// Used by the Assert macros in DEBUG.H and the code in
// the debug OLE2.DLL
ASSERTDATA
// Standard app globals
HINSTANCE g_hInst = NULL ;
HWND g_hwndMain = NULL ;
LPTSTR g_pszCmdLine = NULL ;
// Class factory related globals
LPCLASSFACTORY g_pIClassFactory = NULL ;
DWORD g_cLock = 0L ; // Lock count
DWORD g_cObj = 0L ; // Number of alive objects
DWORD g_dwRegCO = 0L ;
// Simulation globals
CSimulation* g_pSimObj = NULL ;
#define MARKET_TIMEOUT 250
#define UPDATE_TIMEOUT 500
UINT g_uiTimeoutMarket = MARKET_TIMEOUT ;
UINT g_uiTimeoutUpdate = UPDATE_TIMEOUT ;
// Simple minded way of keeping track of the objects we've
// created. The following is an array of object pointers that
// is initallialy set to all NULLs. Each time we create an
// object we store it's pointer in this array; when it's deleted
// we search for it's pointer and NULL it out
//
// Note in future versions this will be replaced with a listbox
// that will show visually the objects that have been created
//
#define MAX_OBJECTS 16
CStocksObject* g_rgpObj[MAX_OBJECTS] ;
// Applicaiton WinMain
//
// Standard WinMain stuff. InitApplication, register classes and with
// OLE, create window, message loop...
//
int PASCAL WinMain (HINSTANCE hInst, HINSTANCE hPrev, LPSTR p, int nCmdShow)
{
g_hInst = hInst ;
#ifdef WIN32
g_pszCmdLine = GetCommandLine() ;
#else
g_pszCmdLine = pszCmdLine ;
#endif
// Gotta do this for OLE
SetMessageQueue( 96 ) ;
// Initialize Application (register wnd classes etc...)
if (!InitApplication( hInst ))
{
AssertSz( 0, L"InitApplication failed\r\n" ) ;
return 0 ;
}
if (FAILED(OleInitialize(NULL)))
{
AssertSz(0, L"OleInitialize failed\r\n" ) ;
return 0 ;
}
// Read our settings from the INI file
//
g_uiTimeoutMarket = GetPrivateProfileInt( L"Simulation", L"MarketTimeout", MARKET_TIMEOUT, L"XRTOBJ32.INI" ) ;
g_uiTimeoutUpdate = GetPrivateProfileInt( L"Simulation", L"UpdateTimeout", UPDATE_TIMEOUT, L"XRTOBJ32.INI" ) ;
// We save the window position on shutdown. Read it here.
//
int x = GetPrivateProfileInt( L"Config", L"x", CW_USEDEFAULT, L"XRTOBJ32.INI" ) ;
int y = GetPrivateProfileInt( L"Config", L"y", CW_USEDEFAULT, L"XRTOBJ32.INI" ) ;
int cx = GetPrivateProfileInt( L"Config", L"cx", CW_USEDEFAULT, L"XRTOBJ32.INI" ) ;
int cy = GetPrivateProfileInt( L"Config", L"cy", CW_USEDEFAULT, L"XRTOBJ32.INI" ) ;
BOOL fMin = GetPrivateProfileInt( L"Config", L"Min", FALSE, L"XRTOBJ32.INI" ) ;
// Create our window
#ifdef WIN32
#define SZ_TITLE L"Simple Stocks-R-Us XRT Data Object (32 bit)"
#else
#define SZ_TITLE L"Simple Stocks-R-Us XRT Data Object (16 bit)"
#endif
g_hwndMain = CreateWindow ( L"XRTOBJ32.MainWnd", SZ_TITLE,
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
x,y,cx,cy, NULL, NULL, g_hInst, NULL ) ;
// Create our class factory interface
g_pIClassFactory = new CImpIClassFactory ;
if (g_pIClassFactory == NULL)
{
AssertSz( 0, L"new CXRTClassFactory failed\r\n" ) ;
goto BailOut ;
}
g_pIClassFactory->AddRef() ;
// Register our class object
//
HRESULT hr ;
hr = CoRegisterClassObject( CLSID_StocksRUsStockQuotes, (LPUNKNOWN)g_pIClassFactory,
CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE, &g_dwRegCO ) ;
if (FAILED(hr))
{
AssertSz( 0, L"CoRegisterClassObject failed\r\n" ) ;
goto BailOut ;
}
if (lstrcmpi( g_pszCmdLine, L"/Embedding" ) == 0)
nCmdShow = SW_MINIMIZE ;
if (fMin == TRUE)
nCmdShow = SW_MINIMIZE ;
ShowWindow( g_hwndMain, nCmdShow ) ;
UpdateWindow( g_hwndMain ) ;
// message loop
//
MSG msg ;
while (GetMessage (&msg, NULL, 0, 0))
{
TranslateMessage( &msg ) ;
DispatchMessage( &msg ) ;
}
if (g_dwRegCO != 0)
CoRevokeClassObject( g_dwRegCO ) ;
if (g_pIClassFactory)
g_pIClassFactory->Release() ;
BailOut:
OleUninitialize() ;
return 0 ;
}
// Window procedure for the main application window
//
LRESULT CALLBACK fnMainWnd( HWND hwnd, UINT uiMsg, WPARAM wParam, LPARAM lParam )
{
#define TIMER_MARKETRATE 1
#define TIMER_UPDATERATE 2
static UINT uiTimer1 = 0 ;
static UINT uiTimer2 = 0 ;
switch( uiMsg )
{
case WM_CREATE:
{
for (int i = 0 ; i < MAX_OBJECTS ; i++)
g_rgpObj[i] = NULL ;
// Create an instance of our market simulation object. This object
// is a self contained simple market simulation. It is driven by
// it's ::OnTick method which is called in the WM_TIMER case below
//
g_pSimObj = new CSimulation ;
if (g_pSimObj == NULL)
return -1 ;
// Create two timers:
// One for the market update rate (ie how fast the market
// simulation runs).
// And one for the upadate rate (ie how often IAdviseSink::OnDataChange
// notifications are generated.
//
uiTimer1 = SetTimer( hwnd, TIMER_MARKETRATE, g_uiTimeoutMarket, NULL ) ;
uiTimer2 = SetTimer( hwnd, TIMER_UPDATERATE, g_uiTimeoutUpdate, NULL ) ;
}
break ;
case WM_TIMER:
{
UINT wTimerID = wParam ;
switch (wTimerID)
{
case TIMER_MARKETRATE:
// Make the simulation generate data
//
g_pSimObj->OnTick() ;
break ;
case TIMER_UPDATERATE:
// Notify all instances of CStocksObject
//
// TODO: Re-implement code to manage list of instanced objects
// There's a listbox where the Itemdata is a pointer to
// the object.
//
for (int i = 0 ; i < MAX_OBJECTS ; i++)
{
if (g_rgpObj[i] != NULL)
g_rgpObj[i]->OnUpdateTick() ;
}
break ;
}
}
break ;
case WM_COMMAND:
{
#ifdef WIN32
WORD wNotifyCode = HIWORD(wParam);
WORD wID = LOWORD(wParam);
HWND hwndCtl = (HWND) lParam;
#else
WORD wNotifyCode = HIWORD(lParam) ;
WORD wID = wParam ;
HWND hwndCtl = (HWND)LOWORD(lParam) ;
#endif
switch (wID)
{
case ID_OPTIONS_UPDATESPEED:
// Pop up dialog that allows the update speed to
// be changed
//
// TODO: Implement dialog
//
if (uiTimer1)
KillTimer( hwnd, TIMER_UPDATERATE ) ;
uiTimer1 = SetTimer( hwnd, TIMER_UPDATERATE, g_uiTimeoutUpdate, NULL ) ;
break ;
case ID_OPTIONS_MARKETSIMULATION:
// Popup dialog that allows simulation parameters to
// be changed
//
// TODO: Implement dialog
//
if (uiTimer2)
KillTimer( hwnd, TIMER_MARKETRATE ) ;
uiTimer2 = SetTimer( hwnd, TIMER_MARKETRATE, g_uiTimeoutMarket, NULL ) ;
break ;
case ID_HELP_ABOUT:
DoAboutBox() ;
break ;
case ID_FILE_EXIT:
SendMessage( hwnd, WM_CLOSE, 0, 0L ) ;
break ;
}
}
break ;
case WM_PAINT:
{
TEXTMETRIC tm ;
PAINTSTRUCT ps ;
if (!BeginPaint( hwnd, &ps ))
return FALSE ;
GetTextMetrics( ps.hdc, &tm ) ;
// Real simple code to display the latest simulation
// data.
//
if (g_pSimObj)
{
PXRTSTOCKS pData = g_pSimObj->GetData() ;
int cy = 4 ;
RECT rc ;
TCHAR szBuf[1024*16] ;
TCHAR szItem[64] ;
PXRTSTOCK pQuote ;
GetClientRect( hwnd, &rc ) ;
szBuf[0] = '\0' ;
for (UINT i = 0 ; i < pData->cStocks ; i++)
{
pQuote = &pData->rgStocks[i] ;
if (pQuote->uiMembers)
{
wsprintf( szItem, L"%s\t%lu.%02lu\t%lu.%02lu\t%lu.%02lu\t%lu\n",
(LPTSTR)pQuote->szSymbol,
pQuote->ulHigh/1000L, pQuote->ulHigh%1000L,
pQuote->ulLow/1000L, pQuote->ulLow%1000L,
pQuote->ulLast/1000L, pQuote->ulLast%1000L,
pQuote->ulVolume
) ;
lstrcat( szBuf, szItem ) ;
}
}
DrawText( ps.hdc, szBuf, -1, &rc, DT_EXPANDTABS ) ;
}
EndPaint( hwnd, &ps ) ;
}
break ;
case WM_DESTROY:
if (g_pSimObj)
delete g_pSimObj ;
if (!IsIconic( hwnd ))
{
RECT rc ;
TCHAR szBuf[32] ;
GetWindowRect( hwnd, &rc ) ;
wsprintf( szBuf, L"%d", rc.left ) ;
WritePrivateProfileString( L"Config", L"x", szBuf, L"XRTOBJ32.INI" ) ;
wsprintf( szBuf, L"%d", rc.top ) ;
WritePrivateProfileString( L"Config", L"y", szBuf, L"XRTOBJ32.INI" ) ;
wsprintf( szBuf, L"%d", rc.right - rc.left ) ;
WritePrivateProfileString( L"Config", L"cx", szBuf, L"XRTOBJ32.INI" ) ;
wsprintf( szBuf, L"%d", rc.bottom - rc.top) ;
WritePrivateProfileString( L"Config", L"cy", szBuf, L"XRTOBJ32.INI" ) ;
WritePrivateProfileString( L"Config", L"Min", L"0", L"XRTOBJ32.INI" ) ;
}
else
{
WritePrivateProfileString( L"Config", L"Min", L"1", L"XRTOBJ32.INI" ) ;
}
if (uiTimer1) KillTimer( hwnd, TIMER_MARKETRATE ) ;
if (uiTimer2) KillTimer( hwnd, TIMER_UPDATERATE ) ;
PostQuitMessage( 0 ) ;
break ;
default:
return DefWindowProc( hwnd, uiMsg, wParam, lParam ) ;
}
return 0L ;
} // fnMainWnd()
// InitApplicaiton
//
// Initialize our application stuff including
// Window classes
//
BOOL InitApplication( HINSTANCE hInst )
{
WNDCLASS wc ;
wc.style = 0L ;
wc.lpfnWndProc = fnMainWnd ;
wc.cbClsExtra = 0 ;
wc.cbWndExtra = 0 ;
wc.hInstance = hInst ;
wc.hIcon = LoadIcon( hInst,
MAKEINTRESOURCE( IDI_XRTOBJ ) ) ;
wc.hCursor = LoadCursor( NULL, IDC_ARROW ) ;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1) ;
wc.lpszMenuName = MAKEINTRESOURCE( ID_MENU ) ;
wc.lpszClassName = L"XRTOBJ32.MainWnd" ;
if (!RegisterClass (&wc))
return FALSE ;
return TRUE ;
}
// Implement About Box
//
BOOL CALLBACK fnAbout( HWND hDlg, UINT wMsg, WPARAM wParam, LPARAM lParam) ;
BOOL WINAPI DoAboutBox( VOID )
{
DLGPROC lpfnDlgProc ;
(FARPROC)lpfnDlgProc = MakeProcInstance( (FARPROC)fnAbout, g_hInst ) ;
DialogBox( g_hInst,
MAKEINTRESOURCE( IDD_ABOUT ),
g_hwndMain,
lpfnDlgProc ) ;
FreeProcInstance( (FARPROC)lpfnDlgProc ) ;
return TRUE ;
}
BOOL CALLBACK fnAbout( HWND hDlg, UINT wMsg, WPARAM wParam, LPARAM lParam )
{
switch (wMsg)
{
case WM_INITDIALOG:
// TODO: Dynamicaly set version number in about box
//
break ;
case WM_COMMAND:
{
#ifdef WIN32
WORD wNotifyCode = HIWORD(wParam);
WORD wID = LOWORD(wParam);
HWND hwndCtl = (HWND) lParam;
#else
WORD wNotifyCode = HIWORD(lParam) ;
WORD wID = wParam ;
HWND hwndCtl = (HWND)LOWORD(lParam) ;
#endif
switch (wID)
{
case IDOK:
case IDCANCEL:
EndDialog (hDlg, wID) ;
break ;
default :
return FALSE ;
}
break ;
}
break ;
}
return FALSE ;
}
// IClassFactory Implementation
// CImpIClassFactory::CImpIClassFactory
// CImpIClassFactory::~CImpIClassFactory
//
//
CImpIClassFactory::CImpIClassFactory(void)
{
m_cRef=0L;
return;
}
CImpIClassFactory::~CImpIClassFactory(void)
{
return ;
}
// CImpIClassFactory::QueryInterface
// CImpIClassFactory::AddRef
// CImpIClassFactory::Release
//
// Purpose:
// IUnknown members for CImpIClassFactory object.
//
STDMETHODIMP CImpIClassFactory::QueryInterface( REFIID riid, LPVOID FAR *ppv )
{
*ppv = NULL ;
//Any interface on this object is the object pointer.
if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IClassFactory))
*ppv = (LPVOID)this;
// If we actually assign an interface to ppv we need to AddRef it
// since we're returning a new pointer.
//
if (NULL != *ppv)
{
((LPUNKNOWN)*ppv)->AddRef();
return NOERROR;
}
return ResultFromScode(E_NOINTERFACE);
}
STDMETHODIMP_(ULONG) CImpIClassFactory::AddRef(void)
{
return ++m_cRef;
}
STDMETHODIMP_(ULONG) CImpIClassFactory::Release(void)
{
ULONG cRefT;
cRefT=--m_cRef;
//Free the object if the reference and lock counts are zero.
//
if (0L == m_cRef && 0L == g_cLock)
delete this;
return cRefT;
}
// CImpIClassFactory::CreateInstance
//
// Purpose:
// Instantiates an object supported by this class factory. That
// object must at least support IUnknown.
//
// Derived classes should override this function.
//
// Parameters:
// punkOuter LPUNKNOWN to the controlling IUnknown if we are
// being used in an aggregation.
// riid REFIID identifying the interface the caller desires
// to have for the new object.
// ppvObj LPVOID FAR * in which to store the desired interface
// pointer for the new object.
//
// Return Value:
// HRESULT NOERROR if successful, otherwise contains E_NOINTERFACE
// if we cannot support the requested interface.
//
STDMETHODIMP CImpIClassFactory::CreateInstance(LPUNKNOWN punkOuter,
REFIID riid, LPVOID FAR *ppvObj)
{
HRESULT hr ;
*ppvObj = NULL ;
hr = ResultFromScode(E_OUTOFMEMORY) ;
// Verify that if there is a controlling unknown it's asking for
// IUnknown
if (NULL != punkOuter && !IsEqualIID( riid, IID_IUnknown ))
return ResultFromScode( E_NOINTERFACE ) ;
// Create an instance of the object. Pass it the controlling
// unknown and a pointer to the function it should call when
// the object has been created/destroyed
//
CStocksObject* pObj ;
pObj = new CStocksObject( punkOuter, ObjectCreated ) ;
if (pObj == NULL)
return hr ;
if (pObj->Init())
hr = pObj->QueryInterface( riid, ppvObj ) ;
if (FAILED(hr))
delete pObj ;
return hr ;
}
// This function is called by the constructor and destructor of
// the CStocksObject class.
//
void WINAPI ObjectCreated( CStocksObject* pObj, BOOL fCreated )
{
if (fCreated)
{
for (int i = 0 ; i < MAX_OBJECTS ; i++)
{
if (g_rgpObj[i] == NULL)
{
g_rgpObj[i] = pObj ;
break ;
}
}
g_cObj++ ;
}
else
{
for (int i = 0 ; i < MAX_OBJECTS ; i++)
{
if (g_rgpObj[i] == pObj)
{
g_rgpObj[i] = NULL ;
break ;
}
}
g_cObj-- ;
}
if (g_cObj == 0 && g_cLock == 0 && IsWindow( g_hwndMain ))
{
PostMessage( g_hwndMain, WM_CLOSE, 0, 0 ) ;
}
return ;
}
// CImpIClassFactory::LockServer
//
// Purpose:
// Increments or decrements the lock count of the serving IClassFactory
// object. When the lock count is zero and the reference count is zero
// we get rid of this object.
//
// DLL objects should override this to affect their DLL ref count.
//
// Parameters:
// fLock BOOL specifying whether to increment or decrement the
// lock count.
//
// Return Value:
// HRESULT NOERROR always.
//
STDMETHODIMP CImpIClassFactory::LockServer(BOOL fLock)
{
if (fLock)
g_cLock++ ;
else
g_cLock-- ;
if (m_cRef == 0 && g_cLock == 0 && IsWindow( g_hwndMain ))
{
PostMessage( g_hwndMain, WM_CLOSE, 0, 0 ) ;
}
return NOERROR;
}
| 30.808511 | 115 | 0.548895 | [
"object"
] |
6f80ef6fa7f263549ca7f989512585a9e31d15a7 | 4,005 | cpp | C++ | function.cpp | fabsgc/gestnotes | 61e8ff8a42e9f5954a57489f7103937f5ce36863 | [
"MIT"
] | null | null | null | function.cpp | fabsgc/gestnotes | 61e8ff8a42e9f5954a57489f7103937f5ce36863 | [
"MIT"
] | null | null | null | function.cpp | fabsgc/gestnotes | 61e8ff8a42e9f5954a57489f7103937f5ce36863 | [
"MIT"
] | null | null | null | /*\
| ------------------------------------------------------
| @file : function.cpp
| @author : Fabien Beaujean, Luc Lorentz
| @description : Petite bibliothèque de fonctions souvent utilisées dans l'application
| ------------------------------------------------------
\*/
#include "function.hpp"
std::vector<std::string> splitString(std::string input, std::string delimiter)
{
std::vector<std::string> output;
char *pch;
char *str = strdup(input.c_str());
pch = strtok (str, delimiter.c_str());
while (pch != NULL)
{
output.push_back(pch);
pch = strtok (NULL, delimiter.c_str());
}
free(str);
return output;
}
std::map<int,std::string> splitString2(std::string input, std::string delimiter)
{
std::map<int,std::string> output;
char *pch;
char *str = strdup(input.c_str());
pch = strtok (str, delimiter.c_str());
int i = 0;
while (pch != NULL)
{
output[i] = pch;
pch = strtok (NULL, delimiter.c_str());
i++;
}
free(str);
return output;
}
std::string redirect(std::string name)
{
return "Status: 302 Moved\r\nLocation: " + name + "\r\n\r\n";
}
std::string redirect404()
{
return "Content-type: text/html;charset=UTF-8\r\nStatus: 404 Not found\r\n\r\n";
}
std::string redirect200()
{
return "Content-type:text/html;charset=UTF-8\r\n\r\n";
}
bool fileExist(std::string path)
{
std::ifstream f(path);
if (f.good())
{
f.close();
return true;
}
else
{
f.close();
return false;
}
}
std::string fileGetContent(std::string path)
{
std::string output = "", line = "";
std::ifstream f(path);
if (f.good())
{
while ( getline (f,line) )
{
output += line + "\n";
}
}
f.close();
return output;
}
void filePutContent(std::string path, std::string value)
{
std::ofstream file(path.c_str());
if(file)
{
file << value;
}
}
std::string escape(std::string const &s)
{
std::size_t n = s.length();
std::string escaped;
escaped.reserve(n * 2); // pessimistic preallocation
for (std::size_t i = 0; i < n; ++i) {
if (s[i] == '\\' || s[i] == '\'')
escaped += '\\';
escaped += s[i];
}
return escaped;
}
std::string htmlSpecialChars(std::string const &s)
{
std::size_t n = s.length();
std::string escaped;
escaped.reserve(n * 2); // pessimistic preallocation
for (std::size_t i = 0; i < n; ++i) {
if (s[i] == '>')
{
escaped += ">";
}
else if (s[i] == '<')
{
escaped += "<";
}
else
{
escaped += s[i];
}
}
return escaped;
}
std::string genRandom(const int len)
{
srand(time(NULL));
std::string s;
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i)
{
s += var2Str(alphanum[rand() % (sizeof(alphanum) - 1)]);
}
return s;
}
std::string replaceBy(std::string input, std::string what, std::string by)
{
std::regex regReplace("(" + what + ")");
return std::regex_replace (input, regReplace, by);
}
bool str2Bool(std::string x)
{
std::transform(x.begin(), x.end(), x.begin(), ::tolower);
std::istringstream is(x);
bool b;
is >> std::boolalpha >> b;
return b;
}
bool bin2Bool(std::string x)
{
if(x == "0")
{
return false;
}
else
{
return true;
}
}
int bool2bin(bool x)
{
if(x == true)
{
return 1;
}
else
{
return 0;
}
}
std::string getSha1(std::string str)
{
unsigned char result[20];
char hexstring[41];
sha1::calc(str.c_str(), str.length(), result); // 10 is the length of the string
sha1::toHexString(result, hexstring);
return var2Str(hexstring);
}
| 18.981043 | 87 | 0.52035 | [
"vector",
"transform"
] |
6f89e667307d0b103fbcaa2d95b8c63aea0b2e21 | 5,937 | cpp | C++ | pcl__/outofcore/src/visualization/camera.cpp | avinfinity/UnmanagedCodeSnippets | 2bd848db88d7b271209ad30017c8f62307319be3 | [
"MIT"
] | 2 | 2019-04-10T14:04:52.000Z | 2019-05-29T03:41:58.000Z | software/SLAM/ygz_slam_ros/Thirdparty/PCL/outofcore/src/visualization/camera.cpp | glider54321/GAAS | 5c3b8c684e72fdf7f62c5731a260021e741069e7 | [
"BSD-3-Clause"
] | null | null | null | software/SLAM/ygz_slam_ros/Thirdparty/PCL/outofcore/src/visualization/camera.cpp | glider54321/GAAS | 5c3b8c684e72fdf7f62c5731a260021e741069e7 | [
"BSD-3-Clause"
] | 1 | 2021-12-20T06:54:41.000Z | 2021-12-20T06:54:41.000Z | // C++
#include <iostream>
#include <string>
// PCL - visualziation
#include <pcl/visualization/common/common.h>
// PCL - outofcore
#include <pcl/outofcore/visualization/camera.h>
#include <pcl/outofcore/visualization/object.h>
// VTK
#include <vtkActor.h>
#include <vtkCamera.h>
#include <vtkCameraActor.h>
#include <vtkHull.h>
#include <vtkPlanes.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkSmartPointer.h>
// Operators
// -----------------------------------------------------------------------------
Camera::Camera (std::string name) :
Object (name), display_ (false)
{
camera_ = vtkSmartPointer<vtkCamera>::New ();
camera_->SetClippingRange(0.0001, 100000);
camera_actor_ = vtkSmartPointer<vtkCameraActor>::New ();
camera_actor_->SetCamera (camera_);
camera_actor_->GetProperty ()->SetLighting (0);
camera_actor_->GetProperty ()->SetLineStipplePattern (1010101010);
for (int i = 0; i < 24; i++)
frustum_[i] = 0;
hull_actor_ = vtkSmartPointer<vtkActor>::New ();
vtkSmartPointer<vtkPolyDataMapper> hull_mapper = vtkSmartPointer<vtkPolyDataMapper>::New ();
hull_actor_->SetMapper (hull_mapper);
hull_actor_->GetProperty ()->SetLighting (0);
hull_actor_->GetProperty ()->SetColor (1.0, 0.0, 0.0);
hull_actor_->GetProperty ()->SetOpacity (0.25);
}
Camera::Camera (std::string name, vtkSmartPointer<vtkCamera> camera) :
Object (name), display_ (false)
{
camera_ = camera;
camera_->SetClippingRange(0.0001, 100000);
camera_actor_ = vtkSmartPointer<vtkCameraActor>::New ();
camera_actor_->SetCamera (camera_);
camera_actor_->GetProperty ()->SetLighting (0);
for (int i = 0; i < 24; i++)
frustum_[i] = 0;
hull_actor_ = vtkSmartPointer<vtkActor>::New ();
vtkSmartPointer<vtkPolyDataMapper> hull_mapper = vtkSmartPointer<vtkPolyDataMapper>::New ();
hull_actor_->SetMapper (hull_mapper);
hull_actor_->GetProperty ()->SetLighting (0);
hull_actor_->GetProperty ()->SetColor (1.0, 0.0, 0.0);
hull_actor_->GetProperty ()->SetOpacity (0.25);
prevUp_[0] = prevUp_[1] = prevUp_[2] = 0;
prevFocal_[0] = prevFocal_[1] = prevFocal_[2] = 0;
prevPos_[0] = prevPos_[1] = prevPos_[2] = 0;
}
//std::ostream & operator<<(std::ostream &os, const Camera& camera)
//{
// return os << camera.getName();
//}
// Methods
// -----------------------------------------------------------------------------
void
//Camera::computeFrustum(double aspect)
Camera::computeFrustum ()
{
// The planes array contains six plane equations of the form (Ax+By+Cz+D=0), the first four values are (A,B,C,D)
// which repeats for each of the planes. The planes are given in the following order: -x,+x,-y,+y,-z,+z.
//camera_->GetFrustumPlanes(aspect, frustum_);
pcl::visualization::getViewFrustum (getViewProjectionMatrix (), frustum_);
// vtkSmartPointer<vtkHull> hull = vtkSmartPointer<vtkHull>::New ();
// vtkSmartPointer<vtkPlanes> planes = vtkSmartPointer<vtkPlanes>::New ();
// vtkSmartPointer<vtkPolyData> hullData = vtkSmartPointer<vtkPolyData>::New ();
//
// planes->SetFrustumPlanes (frustum_);
// hull->SetPlanes (planes);
// hull->GenerateHull (hullData, -200, 200, -200, 200, -200, 200);
//
// vtkSmartPointer<vtkPolyDataMapper> hull_mapper = static_cast<vtkPolyDataMapper*> (hull_actor_->GetMapper ());
//
//#if VTK_MAJOR_VERSION < 6
// hull_mapper->SetInput (hullData);
//#else
// hull_mapper->SetInputData(hullData);
//#endif
//
// hull_actor_->SetMapper (hull_mapper);
}
void
Camera::printFrustum ()
{
for (int i = 0; i < 6; i++)
{
std::cout << frustum_[(i * 4)] << "x + " << frustum_[(i * 4) + 1] << "y + " << frustum_[(i * 4) + 2] << "z + "
<< frustum_[(i * 4) + 3] << std::endl;
}
}
void
Camera::render (vtkRenderer* renderer)
{
vtkSmartPointer<vtkCamera> active_camera = renderer->GetActiveCamera ();
// if (camera_.GetPointer() != active_camera.GetPointer())
// {
// if (display_)
// {
// renderer->AddActor (camera_actor_);
// renderer->AddActor (hull_actor_);
// }
// else
// {
// renderer->RemoveActor (camera_actor_);
// renderer->RemoveActor (hull_actor_);
// }
// return;
// }
// Reset clipping range
setClippingRange();
double *up = active_camera->GetViewUp ();
double *focal = active_camera->GetFocalPoint ();
double *pos = active_camera->GetPosition ();
bool viewpointChanged = false;
// Check up vector
if (up[0] != prevUp_[0] || up[1] != prevUp_[1] || up[2] != prevUp_[2])
viewpointChanged = true;
// Check focal point
if (focal[0] != prevFocal_[0] || focal[1] != prevFocal_[1] || focal[2] != prevFocal_[2])
viewpointChanged = true;
// Check position
if (pos[0] != prevPos_[0] || pos[1] != prevPos_[1] || pos[2] != prevPos_[2])
viewpointChanged = true;
// Break loop if the viewpoint hasn't changed
if (viewpointChanged)
{
prevUp_[0] = up[0];
prevUp_[1] = up[1];
prevUp_[2] = up[2];
prevFocal_[0] = focal[0];
prevFocal_[1] = focal[1];
prevFocal_[2] = focal[2];
prevPos_[0] = pos[0];
prevPos_[1] = pos[1];
prevPos_[2] = pos[2];
// std::cout << "View Changed" << std::endl;
// std::cout << "Up: <" << up[0] << ", " << up[1] << ", " << up[2] << ">" << std::endl;
// std::cout << "Focal: <" << focal[0] << ", " << focal[1] << ", " << focal[2] << ">" << std::endl;
// std::cout << "Pos: <" << pos[0] << ", " << pos[1] << ", " << pos[2] << ">" << std::endl;
{
renderer->ComputeAspect ();
double *aspect = renderer->GetAspect ();
projection_matrix_ = pcl::visualization::vtkToEigen (active_camera->GetProjectionTransformMatrix (aspect[0] / aspect[1], 0.0, 1.0));
model_view_matrix_ = pcl::visualization::vtkToEigen (active_camera->GetModelViewTransformMatrix ());
//computeFrustum (renderer->GetTiledAspectRatio());
computeFrustum ();
}
}
Object::render(renderer);
}
| 30.761658 | 138 | 0.626411 | [
"render",
"object",
"vector"
] |
6f94059037cd12b59c9ae1ef4070bda725b3ea05 | 1,203 | cpp | C++ | lightoj/1111 - Best Picnic Ever dfs bfs .cpp | priojeetpriyom/competitive-programming | 0024328972d4e14c04c0fd5d6dd3cdf131d84f9d | [
"MIT"
] | 1 | 2021-11-22T02:26:43.000Z | 2021-11-22T02:26:43.000Z | lightoj/1111 - Best Picnic Ever dfs bfs .cpp | priojeetpriyom/competitive-programming | 0024328972d4e14c04c0fd5d6dd3cdf131d84f9d | [
"MIT"
] | null | null | null | lightoj/1111 - Best Picnic Ever dfs bfs .cpp | priojeetpriyom/competitive-programming | 0024328972d4e14c04c0fd5d6dd3cdf131d84f9d | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int kk[111], vis[1011], cnt[1011];
vector<int> conn [1011];
int t, n, m ,k, u, v;
void dfs(int u, int col) {
int len = conn[u].size();
vis[u] = col;
cnt[u]++;
for(int i=0; i<len; i++) {
if(vis[ conn[u][i] ]!= col) {
dfs(conn[u][i], col);
}
}
}
int calc() {
for(int i=1; i<=k; i++) {
dfs(kk[i], i);
}
int ans=0;
for(int i=1; i<=n; i++) {
if(cnt[i]==k) ans++;
}
return ans;
}
int main()
{
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
std::ios_base::sync_with_stdio(false);
cin.tie(0);
scanf("%d", &t);
for(int tc=1; tc<=t; tc++) {
for(int i=1; i<=n; i++) {
cnt[i] = vis[i]=0;
conn[i].clear();
}
scanf("%d %d %d", &k, &n, &m);
for(int i=1; i<=k; i++) scanf("%d", &kk[i]);
for(int i=0; i<m; i++) {
scanf("%d %d",&u, &v);
conn[u].push_back(v);
}
printf("Case %d: %d\n",tc, calc());
}
return 0;
}
| 16.708333 | 53 | 0.389027 | [
"vector"
] |
6fa55d1d4de8f773eaf24f5c459ec6c6c6828593 | 5,067 | cpp | C++ | test/Grammar_test.cpp | piller-imre/exprail-fltk | 361615996922a53a2c19c6593afb57263e1a42b0 | [
"MIT"
] | null | null | null | test/Grammar_test.cpp | piller-imre/exprail-fltk | 361615996922a53a2c19c6593afb57263e1a42b0 | [
"MIT"
] | null | null | null | test/Grammar_test.cpp | piller-imre/exprail-fltk | 361615996922a53a2c19c6593afb57263e1a42b0 | [
"MIT"
] | null | null | null | #include "Grammar.h"
#include <gtest/gtest.h>
TEST(Grammar_test, EmptyGrammar)
{
Grammar grammar;
std::vector<std::string> expressionOrder = grammar.getExpressionOrder();
ASSERT_EQ(expressionOrder.size(), 0);
}
TEST(Grammar_test, SingleExpressionGrammar)
{
Grammar grammar;
grammar.addExpression("single", Expression());
std::vector<std::string> expressionOrder = grammar.getExpressionOrder();
ASSERT_EQ(expressionOrder.size(), 1);
ASSERT_EQ(expressionOrder[0], "single");
}
TEST(Grammar_test, ThreeExpressionGrammar)
{
Grammar grammar;
grammar.addExpression("first", Expression());
grammar.addExpression("second", Expression());
grammar.addExpression("third", Expression());
std::vector<std::string> expressionOrder = grammar.getExpressionOrder();
ASSERT_EQ(expressionOrder.size(), 3);
ASSERT_EQ(expressionOrder[0], "first");
ASSERT_EQ(expressionOrder[1], "second");
ASSERT_EQ(expressionOrder[2], "third");
}
TEST(Grammar_test, MoveSingleExpressionDown)
{
Grammar grammar;
grammar.addExpression("first", Expression());
grammar.moveExpressionDown("first");
std::vector<std::string> expressionOrder = grammar.getExpressionOrder();
ASSERT_EQ(expressionOrder.size(), 1);
ASSERT_EQ(expressionOrder[0], "first");
}
TEST(Grammar_test, MoveSingleExpressionUp)
{
Grammar grammar;
grammar.addExpression("first", Expression());
grammar.moveExpressionUp("first");
std::vector<std::string> expressionOrder = grammar.getExpressionOrder();
ASSERT_EQ(expressionOrder.size(), 1);
ASSERT_EQ(expressionOrder[0], "first");
}
TEST(Grammar_test, MoveExpressionDown)
{
Grammar grammar;
grammar.addExpression("first", Expression());
grammar.addExpression("second", Expression());
grammar.addExpression("third", Expression());
std::vector<std::string> expressionOrder;
grammar.moveExpressionDown("first");
expressionOrder = grammar.getExpressionOrder();
ASSERT_EQ(expressionOrder.size(), 3);
ASSERT_EQ(expressionOrder[0], "second");
ASSERT_EQ(expressionOrder[1], "first");
ASSERT_EQ(expressionOrder[2], "third");
grammar.moveExpressionDown("first");
expressionOrder = grammar.getExpressionOrder();
ASSERT_EQ(expressionOrder.size(), 3);
ASSERT_EQ(expressionOrder[0], "second");
ASSERT_EQ(expressionOrder[1], "third");
ASSERT_EQ(expressionOrder[2], "first");
}
TEST(Grammar_test, MoveExpressionUp)
{
Grammar grammar;
grammar.addExpression("first", Expression());
grammar.addExpression("second", Expression());
grammar.addExpression("third", Expression());
std::vector<std::string> expressionOrder;
grammar.moveExpressionUp("second");
expressionOrder = grammar.getExpressionOrder();
ASSERT_EQ(expressionOrder.size(), 3);
ASSERT_EQ(expressionOrder[0], "second");
ASSERT_EQ(expressionOrder[1], "first");
ASSERT_EQ(expressionOrder[2], "third");
grammar.moveExpressionUp("third");
expressionOrder = grammar.getExpressionOrder();
ASSERT_EQ(expressionOrder.size(), 3);
ASSERT_EQ(expressionOrder[0], "second");
ASSERT_EQ(expressionOrder[1], "third");
ASSERT_EQ(expressionOrder[2], "first");
}
TEST(Grammar_test, MoveMissingExpressionDown)
{
Grammar grammar;
grammar.addExpression("first", Expression());
try {
grammar.moveExpressionDown("second");
FAIL() << "An exception has not thrown!";
}
catch (const std::runtime_error& error) {
ASSERT_STREQ(error.what(), "The expression 'second' is missing!");
}
catch (...) {
FAIL() << "Unexpected exception type!";
}
}
TEST(Grammar_test, MoveMissingExpressionUp)
{
Grammar grammar;
grammar.addExpression("first", Expression());
try {
grammar.moveExpressionUp("second");
FAIL() << "An exception has not thrown!";
}
catch (const std::runtime_error& error) {
ASSERT_STREQ(error.what(), "The expression 'second' is missing!");
}
catch (...) {
FAIL() << "Unexpected exception type!";
}
}
TEST(Grammar_test, RenamingInExpressionOrder)
{
Grammar grammar;
grammar.addExpression("first", Expression());
grammar.addExpression("second", Expression());
grammar.addExpression("third", Expression());
grammar.renameExpression("third", "last");
std::vector<std::string> expressionOrder = grammar.getExpressionOrder();
ASSERT_EQ(expressionOrder.size(), 3);
ASSERT_EQ(expressionOrder[0], "first");
ASSERT_EQ(expressionOrder[1], "second");
ASSERT_EQ(expressionOrder[2], "last");
}
TEST(Grammar_test, RemoveFromExpressionOrder)
{
Grammar grammar;
grammar.addExpression("first", Expression());
grammar.addExpression("second", Expression());
grammar.addExpression("third", Expression());
grammar.removeExpression("first");
grammar.removeExpression("third");
std::vector<std::string> expressionOrder = grammar.getExpressionOrder();
ASSERT_EQ(expressionOrder.size(), 1);
ASSERT_EQ(expressionOrder[0], "second");
}
| 32.902597 | 76 | 0.696467 | [
"vector"
] |
6facf83907af7ac46063af5a5ca41ff30dd95b76 | 2,929 | cpp | C++ | VS2019_CV411/KinectV2_OpenCVdetect3/KinectV2/main.cpp | YoshihisaNitta/NtKinect | 9a70d3a57573caeb759467f1d112da9ad0850ce2 | [
"MIT"
] | 21 | 2017-10-20T20:25:39.000Z | 2021-05-11T03:06:30.000Z | VS2019_CV411/KinectV2_OpenCVdetect3/KinectV2/main.cpp | YoshihisaNitta/NtKinect | 9a70d3a57573caeb759467f1d112da9ad0850ce2 | [
"MIT"
] | 2 | 2019-08-26T07:17:22.000Z | 2021-11-30T07:33:57.000Z | VS2019_CV411/KinectV2_OpenCVdetect3/KinectV2/main.cpp | YoshihisaNitta/NtKinect | 9a70d3a57573caeb759467f1d112da9ad0850ce2 | [
"MIT"
] | 8 | 2017-10-06T19:04:42.000Z | 2021-04-02T11:06:38.000Z | /*
* Copyright (c) 2016-2019 Yoshihisa Nitta
* Released under the MIT license
* http://opensource.org/licenses/mit-license.php
*/
/* http://nw.tsuda.ac.jp/lec/kinect2/ */
#include <iostream>
#include <sstream>
#include "NtKinect.h"
using namespace std;
void doJob() {
NtKinect kinect;
string path = "";
string cascadeName = "haarcascade_frontalface_alt.xml";
string cascadeName2 = "haarcascade_eye.xml";
string cascadeName3 = "haarcascade_smile.xml";
cv::CascadeClassifier cascade, cascade2, cascade3;
if (!cascade.load(path + cascadeName)) throw runtime_error(cascadeName + " not found");
if (!cascade2.load(path + cascadeName2)) throw runtime_error(cascadeName2 + " not found");
if (!cascade3.load(path + cascadeName3)) throw runtime_error(cascadeName3 + " not found");
cv::VideoCapture cap(0);
if (!cap.isOpened()) throw runtime_error("VideoCapture open failed");
cv::Mat image;
cv::Mat gray;
while (1) {
kinect.setRGB(image);
cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);
equalizeHist(gray, gray);
vector<cv::Rect> founds, founds2, founds3;
cascade.detectMultiScale(gray, founds, 1.1, 2, 0 | cv::CASCADE_SCALE_IMAGE, cv::Size(30, 30));
for (auto faceRect: founds) {
cv::rectangle(image, faceRect, cv::Scalar(0, 0, 255), 2);
cv::Mat roi = gray(faceRect);
cascade2.detectMultiScale(roi, founds2, 1.1, 2, 0 | cv::CASCADE_SCALE_IMAGE, cv::Size(30, 30));
for (auto eyeRect: founds2) {
cv::Rect rect(faceRect.x + eyeRect.x, faceRect.y + eyeRect.y, eyeRect.width, eyeRect.height);
cv::rectangle(image, rect, cv::Scalar(0, 255, 0), 2);
}
cv::Rect halfRect = faceRect;
halfRect.y += faceRect.height/2;
halfRect.height = faceRect.height/2 - 1; // under half of face
cv::Mat roi2 = gray(halfRect);
cascade3.detectMultiScale(roi2, founds3, 1.1, 0, 0 | cv::CASCADE_SCALE_IMAGE, cv::Size(30, 30));
const int smile_neighbors = (int)founds3.size();
static int max_neighbors=-1;
static int min_neighbors=-1;
if (min_neighbors == -1) min_neighbors = smile_neighbors;
max_neighbors = MAX(max_neighbors, smile_neighbors);
float intensityZeroOne = ((float)smile_neighbors - min_neighbors) / (max_neighbors - min_neighbors + 1);
cv::Rect meter(faceRect.x, faceRect.y-20, (int)100*intensityZeroOne, 20);
cv::rectangle(image, meter, cv::Scalar(255, 0, 0), -1);
cv::Rect meterFull(faceRect.x, faceRect.y-20, 100, 20);
cv::rectangle(image, meterFull, cv::Scalar(255, 0, 0), 1);
}
cv::imshow("video", image);
auto key = cv::waitKey(1);
if (key == 'q') break;
}
cv::destroyAllWindows();
}
int main(int argc, char** argv) {
try {
doJob();
}
catch (exception& ex) {
cout << ex.what() << endl;
string s;
cin >> s;
}
return 0;
}
| 37.551282 | 111 | 0.637078 | [
"vector"
] |
6fb0022f21b60ae2942284fc535d1911e46fb1e0 | 982 | cc | C++ | leetcode/leetcode_241.cc | math715/arts | ff73ccb7d67f7f7c87150204e15aeb46047f0e02 | [
"MIT"
] | null | null | null | leetcode/leetcode_241.cc | math715/arts | ff73ccb7d67f7f7c87150204e15aeb46047f0e02 | [
"MIT"
] | null | null | null | leetcode/leetcode_241.cc | math715/arts | ff73ccb7d67f7f7c87150204e15aeb46047f0e02 | [
"MIT"
] | null | null | null | #include <vector>
#include <string>
#include <iostream>
using namespace std;
vector<int> diffWaysToCompute(string input) {
vector<int> res;
for (int i = 0; i < input.size(); ++i) {
char op = input[i];
if (input[i] == '+' || input[i] == '-' || input[i] == '*') {
auto left = diffWaysToCompute(input.substr(0, i));
auto right = diffWaysToCompute(input.substr(i+1));
for (auto l : left) {
for (auto r : right) {
if (op == '+') {
res.push_back(l + r);
} else if (op == '-') {
res.push_back(l - r);
} else {
res.push_back(l * r);
}
}
}
}
}
if (res.empty()) {
int value = stoi(input);
res.push_back(value);
return res;
}
return res;
}
int main() {
{
auto vs = diffWaysToCompute("2-1-1");
for (auto v : vs) {
std::cerr << v << " ";
}
std::cerr << std::endl;
}
{
auto vs = diffWaysToCompute("2*3-4*5");
for (auto v : vs) {
std::cerr << v << " ";
}
std::cerr << std::endl;
}
return 0;
}
| 19.64 | 62 | 0.520367 | [
"vector"
] |
6fb8b52c1b5f6c2d33abae3cf8e813926c340b31 | 20,887 | cpp | C++ | tests/main.cpp | nekipelov/cborcpp | 8d9d289cd855d80c2d9c9bb97fa1c8e3c59a0a92 | [
"MIT"
] | 2 | 2015-01-11T01:22:10.000Z | 2020-03-12T12:36:16.000Z | tests/main.cpp | nekipelov/cborcpp | 8d9d289cd855d80c2d9c9bb97fa1c8e3c59a0a92 | [
"MIT"
] | null | null | null | tests/main.cpp | nekipelov/cborcpp | 8d9d289cd855d80c2d9c9bb97fa1c8e3c59a0a92 | [
"MIT"
] | 2 | 2015-12-26T05:24:09.000Z | 2020-03-12T12:36:17.000Z | #define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include <stdio.h>
#include <boost/test/unit_test.hpp>
#include <math.h>
#include "../src/cborcpp.h"
#include "../src/cborvalue.h"
template<size_t N>
std::vector<char> toVector(const char (&ptr)[N])
{
if( N > 1 )
return std::vector<char>(ptr, ptr + N - 1);
else
return std::vector<char>();
}
CborValue decode(const std::vector<char> &data)
{
return cborRead(data);
}
template<typename T>
std::vector<char> encode(const T &value)
{
return cborWrite(value);
}
std::ostream & operator << (std::ostream &stream, const CborValue &v)
{
stream << v.inspect();
return stream;
}
BOOST_AUTO_TEST_CASE( PositiveNumbers )
{
BOOST_CHECK_EQUAL(0, decode(toVector("\x00")));
BOOST_CHECK_EQUAL(1, decode(toVector("\x01")));
BOOST_CHECK_EQUAL(10, decode(toVector("\x0A")));
BOOST_CHECK_EQUAL(24, decode(toVector("\x18\x18")));
BOOST_CHECK_EQUAL(25, decode(toVector("\x18\x19")));
BOOST_CHECK_EQUAL(255, decode(toVector("\x18\xFF")));
BOOST_CHECK_EQUAL(256, decode(toVector("\x19\x01\x00")));
BOOST_CHECK_EQUAL(65535, decode(toVector("\x19\xFF\xFF")));
BOOST_CHECK_EQUAL(65536, decode(toVector("\x1A\x00\x01\x00\x00")));
BOOST_CHECK_EQUAL(static_cast<uint64_t>(4294967295ULL), decode(toVector("\x1A\xFF\xFF\xFF\xFF")));
BOOST_CHECK_EQUAL(static_cast<uint64_t>(4294967296ULL), decode(toVector("\x1B\x00\x00\x00\x01\x00\x00\x00\x00")));
BOOST_CHECK_EQUAL(1000000, decode(toVector("\x1a\x00\x0f\x42\x40")));
BOOST_CHECK_EQUAL(static_cast<uint64_t>(1000000000000ULL), decode(toVector("\x1b\x00\x00\x00\xe8\xd4\xa5\x10\x00")));
BOOST_CHECK_EQUAL(static_cast<uint64_t>(18446744073709551615ULL), decode(toVector("\x1b\xff\xff\xff\xff\xff\xff\xff\xff")));
BOOST_VERIFY(encode(0) == toVector("\x00"));
BOOST_VERIFY(encode(1) == toVector("\x01"));
BOOST_VERIFY(encode(10) == toVector("\x0A"));
BOOST_VERIFY(encode(24) == toVector("\x18\x18"));
BOOST_VERIFY(encode(25) == toVector("\x18\x19"));
BOOST_VERIFY(encode(255) == toVector("\x18\xFF"));
BOOST_VERIFY(encode(256) == toVector("\x19\x01\x00"));
BOOST_VERIFY(encode(65535) == toVector("\x19\xFF\xFF"));
BOOST_VERIFY(encode(65536) == toVector("\x1A\x00\x01\x00\x00"));
BOOST_VERIFY(encode(static_cast<uint64_t>(4294967295ULL)) == toVector("\x1A\xFF\xFF\xFF\xFF"));
BOOST_VERIFY(encode(static_cast<uint64_t>(4294967296ULL)) == toVector("\x1B\x00\x00\x00\x01\x00\x00\x00\x00"));
BOOST_VERIFY(encode(1000000) == toVector("\x1a\x00\x0f\x42\x40"));
BOOST_VERIFY(encode(static_cast<uint64_t>(1000000000000ULL)) == toVector("\x1b\x00\x00\x00\xe8\xd4\xa5\x10\x00"));
BOOST_VERIFY(encode(static_cast<uint64_t>(18446744073709551615ULL)) == toVector("\x1b\xff\xff\xff\xff\xff\xff\xff\xff"));
}
BOOST_AUTO_TEST_CASE( NegativeNumbers )
{
BOOST_CHECK_EQUAL(-16, decode(toVector("\x2F")));
BOOST_CHECK_EQUAL(-1, decode(toVector("\x20")));
BOOST_CHECK_EQUAL(-10, decode(toVector("\x29")));
BOOST_CHECK_EQUAL(-24, decode(toVector("\x37")));
BOOST_CHECK_EQUAL(-25, decode(toVector("\x38\x18")));
BOOST_CHECK_EQUAL(-250, decode(toVector("\x38\xF9")));
BOOST_CHECK_EQUAL(-256, decode(toVector("\x38\xFF")));
BOOST_CHECK_EQUAL(-65535, decode(toVector("\x39\xFF\xFE")));
BOOST_CHECK_EQUAL(-65536, decode(toVector("\x39\xFF\xFF")));
BOOST_CHECK_EQUAL(static_cast<int64_t>(-4294967295LL), decode(toVector("\x3A\xFF\xFF\xFF\xFE")));
BOOST_CHECK_EQUAL(static_cast<int64_t>(-4294967296LL), decode(toVector("\x3A\xFF\xFF\xFF\xFF")));
{
// -18446744073709551616LL too big for 64-bit integer. This value must
// be writed as BigInteger. But encoded as 64-bit integer.
CborValue::BigInteger bitInteger;
bitInteger.positive = false;
const char value[] = {0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
bitInteger.bigint.assign(value, value + sizeof(value));
BOOST_CHECK_EQUAL(CborValue(bitInteger), decode(toVector("\x3b\xff\xff\xff\xff\xff\xff\xff\xff")));
BOOST_VERIFY(encode(bitInteger) == toVector("\x3b\xff\xff\xff\xff\xff\xff\xff\xff"));
}
BOOST_VERIFY(encode(-16) == toVector("\x2F"));
BOOST_VERIFY(encode(-1) == toVector("\x20"));
BOOST_VERIFY(encode(-10) == toVector("\x29"));
BOOST_VERIFY(encode(-24) == toVector("\x37"));
BOOST_VERIFY(encode(-25) == toVector("\x38\x18"));
BOOST_VERIFY(encode(-250) == toVector("\x38\xF9"));
BOOST_VERIFY(encode(-256) == toVector("\x38\xFF"));
BOOST_VERIFY(encode(-65535) == toVector("\x39\xFF\xFE"));
BOOST_VERIFY(encode(-65536) == toVector("\x39\xFF\xFF"));
BOOST_VERIFY(encode(static_cast<int64_t>(-4294967295LL)) == toVector("\x3A\xFF\xFF\xFF\xFE"));
BOOST_VERIFY(encode(static_cast<int64_t>(-4294967296LL)) == toVector("\x3A\xFF\xFF\xFF\xFF"));
}
BOOST_AUTO_TEST_CASE( FloatNumbers )
{
// Decoder
BOOST_CHECK_EQUAL(0.0, decode(toVector("\xf9\x00\x00")));
BOOST_CHECK_EQUAL(-0.0, decode(toVector("\xf9\x80\x00")));
BOOST_CHECK_EQUAL(1.0, decode(toVector("\xf9\x3c\x00")));
BOOST_CHECK_EQUAL(1.1, decode(toVector("\xfb\x3f\xf1\x99\x99\x99\x99\x99\x9a")));
BOOST_CHECK_EQUAL(1.5, decode(toVector("\xf9\x3e\x00")));
BOOST_CHECK_EQUAL(65504.0, decode(toVector("\xf9\x7b\xff")));
BOOST_CHECK_EQUAL(100000.0, decode(toVector("\xfa\x47\xc3\x50\x00")));
BOOST_CHECK_EQUAL(3.4028234663852886e+38, decode(toVector("\xfa\x7f\x7f\xff\xff")));
BOOST_CHECK_EQUAL(1.0e+300, decode(toVector("\xfb\x7e\x37\xe4\x3c\x88\x00\x75\x9c")));
BOOST_CHECK_EQUAL(5.960464477539063e-8, decode(toVector("\xf9\x00\x01")));
BOOST_CHECK_EQUAL(0.00006103515625, decode(toVector("\xf9\x04\x00")));
BOOST_CHECK_EQUAL(-4.0, decode(toVector("\xf9\xc4\x00")));
BOOST_CHECK_EQUAL(-4.1, decode(toVector("\xfb\xc0\x10\x66\x66\x66\x66\x66\x66")));
BOOST_CHECK( isinf(decode(toVector("\xf9\x7c\x00")).toDouble()) );
BOOST_CHECK( isnan(decode(toVector("\xf9\x7e\x00")).toDouble()) );
BOOST_CHECK( isinf(decode(toVector("\xf9\xfc\x00")).toDouble()) );
BOOST_CHECK( isinf(decode(toVector("\xfa\x7f\x80\x00\x00")).toDouble()) );
BOOST_CHECK( isnan(decode(toVector("\xfa\x7f\xc0\x00\x00")).toDouble()) );
BOOST_CHECK( isinf(decode(toVector("\xfa\xff\x80\x00\x00")).toDouble()) );
BOOST_CHECK( isinf(decode(toVector("\xfb\x7f\xf0\x00\x00\x00\x00\x00\x00")).toDouble()) );
BOOST_CHECK( isnan(decode(toVector("\xfb\x7f\xf8\x00\x00\x00\x00\x00\x00")).toDouble()) );
BOOST_CHECK( isinf(decode(toVector("\xfb\xff\xf0\x00\x00\x00\x00\x00\x00")).toDouble()) );
// Encoder
BOOST_CHECK(encode(0.0) == toVector("\xf9\x00\x00"));
BOOST_CHECK(encode(-0.0) == toVector("\xf9\x80\x00"));
BOOST_CHECK(encode(1.0) == toVector("\xf9\x3c\x00"));
BOOST_CHECK(encode(1.1) == toVector("\xfb\x3f\xf1\x99\x99\x99\x99\x99\x9a"));
BOOST_CHECK(encode(1.5) == toVector("\xf9\x3e\x00"));
BOOST_CHECK(encode(65504.0) == toVector("\xf9\x7b\xff"));
BOOST_CHECK(encode(100000.0) == toVector("\xfa\x47\xc3\x50\x00"));
BOOST_CHECK(encode(3.4028234663852886e+38) == toVector("\xfa\x7f\x7f\xff\xff"));
BOOST_CHECK(encode(1.0e+300) == toVector("\xfb\x7e\x37\xe4\x3c\x88\x00\x75\x9c"));
BOOST_CHECK(encode(5.960464477539063e-8) == toVector("\xf9\x00\x01"));
BOOST_CHECK(encode(0.00006103515625) == toVector("\xf9\x04\x00"));
BOOST_CHECK(encode(-4.0) == toVector("\xf9\xc4\x00"));
BOOST_CHECK(encode(-4.1) == toVector("\xfb\xc0\x10\x66\x66\x66\x66\x66\x66"));
BOOST_CHECK(encode(std::numeric_limits<float>::infinity()) == toVector("\xf9\x7c\x00"));
BOOST_CHECK(encode(std::numeric_limits<float>::quiet_NaN()) == toVector("\xf9\x7e\x00"));
BOOST_CHECK(encode(-std::numeric_limits<float>::infinity()) == toVector("\xf9\xfc\x00"));
BOOST_CHECK(encode(std::numeric_limits<double>::infinity()) == toVector("\xf9\x7c\x00"));
BOOST_CHECK(encode(std::numeric_limits<double>::quiet_NaN()) == toVector("\xf9\x7e\x00"));
BOOST_CHECK(encode(-std::numeric_limits<double>::infinity()) == toVector("\xf9\xfc\x00"));
}
BOOST_AUTO_TEST_CASE( BigNumbers )
{
{
// 18446744073709551617
const char bigNumData [] = "\x01\x00\x00\x00\x00\x00\x00\x00\x01";
const std::vector<char> bigNumBuf(bigNumData, bigNumData + sizeof(bigNumData) - 1);
const char encoded[] = "\xc2\x49\x01\x00\x00\x00\x00\x00\x00\x00\x01";
CborValue::BigInteger bigInteger;
bigInteger.positive = true;
bigInteger.bigint = bigNumBuf;
BOOST_CHECK_EQUAL(CborValue(bigInteger), decode(toVector(encoded)));
BOOST_CHECK(encode(CborValue(bigInteger)) == toVector(encoded));
}
{
// -18446744073709551617
const char bigNumData [] = "\x01\x00\x00\x00\x00\x00\x00\x00\x01";
const std::vector<char> bigNumBuf(bigNumData, bigNumData + sizeof(bigNumData) - 1);
const char encoded[] = "\xc3\x49\x01\x00\x00\x00\x00\x00\x00\x00\x00";
CborValue::BigInteger bigInteger;
bigInteger.positive = false;
bigInteger.bigint = bigNumBuf;
BOOST_CHECK_EQUAL(CborValue(bigInteger), decode(toVector(encoded)));
BOOST_CHECK(encode(CborValue(bigInteger)) == toVector(encoded));
}
}
BOOST_AUTO_TEST_CASE( SimpleValues )
{
BOOST_CHECK_EQUAL(false, decode(toVector("\xf4")).toBool());
BOOST_CHECK_EQUAL(true, decode(toVector("\xf5")).toBool());
BOOST_CHECK(decode(toVector("\xf6")).type() == CborValue::NullType);
BOOST_CHECK(decode(toVector("\xf7")).type() == CborValue::UndefinedType);
BOOST_CHECK(encode(CborValue(false)) == toVector("\xf4"));
BOOST_CHECK(encode(CborValue(true)) == toVector("\xf5"));
BOOST_CHECK(encode(CborValue(CborValue::NullTag())) == toVector("\xf6"));
BOOST_CHECK(encode(CborValue(CborValue::UndefinedTag())) == toVector("\xf7"));
// | simple(16) | 0xf0 |
// | | |
// | simple(24) | 0xf818 |
// | | |
// | simple(255) | 0xf8ff |
// | | |
}
BOOST_AUTO_TEST_CASE( TaggedValues )
{
// | 0("2013-03-21T20:04:00Z") | 0xc074323031332d30332d32315432303a |
// | | 30343a30305a |
// | | |
// | 1(1363896240) | 0xc11a514b67b0 |
// | | |
// | 1(1363896240.5) | 0xc1fb41d452d9ec200000 |
// | | |
// | 23(h'01020304') | 0xd74401020304 |
// | | |
// | 24(h'6449455446') | 0xd818456449455446 |
// | | |
// | 32("http://www.example.com") | 0xd82076687474703a2f2f7777772e6578 |
// | | 616d706c652e636f6d |
// | | |
// | h'' | 0x40 |
// | | |
// | h'01020304' | 0x4401020304 |
}
BOOST_AUTO_TEST_CASE( StringValues )
{
// strings
BOOST_CHECK_EQUAL("hello world!", decode(toVector("\x6C\x68\x65\x6C\x6C\x6F\x20\x77\x6F\x72\x6C\x64\x21")));
BOOST_CHECK_EQUAL("", decode(toVector("\x60")));
BOOST_CHECK_EQUAL("a", decode(toVector("\x61\x61")));
BOOST_CHECK_EQUAL("IETF", decode(toVector("\x64\x49\x45\x54\x46")));
BOOST_CHECK_EQUAL("\"\\", decode(toVector("\x62\x22\x5c")));
BOOST_CHECK(encode("hello world!") == toVector("\x6C\x68\x65\x6C\x6C\x6F\x20\x77\x6F\x72\x6C\x64\x21"));
BOOST_CHECK(encode("") == toVector("\x60"));
BOOST_CHECK(encode("a") == toVector("\x61\x61"));
BOOST_CHECK(encode("IETF") == toVector("\x64\x49\x45\x54\x46"));
BOOST_CHECK(encode("\"\\") == toVector("\x62\x22\x5c"));
BOOST_CHECK(encode("\u00fc") == toVector("\x62\xc3\xbc"));
BOOST_CHECK(encode("\u6c34") == toVector("\x63\xe6\xb0\xb4"));
// | "\ud800\udd51" | 0x64f0908591 |
}
BOOST_AUTO_TEST_CASE( MapsAndArrayValues )
{
BOOST_CHECK_EQUAL(std::vector<CborValue>(), decode(toVector("\x80")));
BOOST_CHECK(encode(std::vector<CborValue>()) == toVector("\x80"));
{
std::vector<CborValue> arr;
arr.push_back(1);
arr.push_back(2);
arr.push_back(3);
BOOST_CHECK_EQUAL(arr, decode(toVector("\x83\x01\x02\x03")));
BOOST_CHECK(encode(arr) == toVector("\x83\x01\x02\x03"));
}
{
std::vector<CborValue> arr1;
std::vector<CborValue> arr2;
std::vector<CborValue> arr;
arr1.push_back(2);
arr1.push_back(3);
arr2.push_back(4);
arr2.push_back(5);
arr.push_back(1);
arr.push_back(arr1);
arr.push_back(arr2);
BOOST_CHECK_EQUAL(arr, decode(toVector("\x83\x01\x82\x02\x03\x82\x04\x05")));
BOOST_CHECK(encode(arr) == toVector("\x83\x01\x82\x02\x03\x82\x04\x05"));
}
{
std::vector<CborValue> arr;
for(int i = 1; i <= 25; ++i)
arr.push_back(i);
std::vector<char> data = toVector("\x98\x19\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c"
"\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x18\x18\x19");
BOOST_CHECK_EQUAL(arr, decode(data));
BOOST_CHECK(encode(arr) == data);
}
{
std::map<CborValue, CborValue> emptyMap;
BOOST_CHECK_EQUAL(emptyMap, decode(toVector("\xa0")));
BOOST_CHECK(encode(emptyMap) == toVector("\xa0"));
}
{
std::map<CborValue, CborValue> map;
map[CborValue(1)] = CborValue(2);
map[CborValue(3)] = CborValue(4);
BOOST_CHECK_EQUAL(map, decode(toVector("\xa2\x01\x02\x03\x04")));
BOOST_CHECK(encode(map) == toVector("\xa2\x01\x02\x03\x04"));
}
{
std::vector<CborValue> arr;
std::map<CborValue, CborValue> map;
arr.push_back(2);
arr.push_back(3);
map.insert(std::make_pair(CborValue("a"), CborValue(1)));
map.insert(std::make_pair(CborValue("b"), arr));
BOOST_CHECK_EQUAL(map, decode(toVector("\xa2\x61\x61\x01\x61\x62\x82\x02\x03")));
BOOST_CHECK(encode(map) == toVector("\xa2\x61\x61\x01\x61\x62\x82\x02\x03"));
}
{
std::map<CborValue, CborValue> map;
std::vector<CborValue> array;
map[CborValue("b")] = CborValue("c");
array.push_back("a");
array.push_back(map);
BOOST_CHECK_EQUAL(array, decode(toVector("\x82\x61\x61\xa1\x61\x62\x61\x63")));
BOOST_CHECK(encode(array) == toVector("\x82\x61\x61\xa1\x61\x62\x61\x63"));
}
{
std::map<CborValue, CborValue> map;
map[CborValue("a")] = CborValue("A");
map[CborValue("b")] = CborValue("B");
map[CborValue("c")] = CborValue("C");
map[CborValue("d")] = CborValue("D");
map[CborValue("e")] = CborValue("E");
std::vector<char> data = toVector("\xa5\x61\x61\x61\x41\x61\x62\x61\x42\x61\x63"
"\x61\x43\x61\x64\x61\x44\x61\x65\x61\x45");
BOOST_CHECK_EQUAL(map, decode(data));
BOOST_CHECK(encode(map) == data);
}
// | [_ ] | 0x9fff |
// | | |
// | [_ 1, [2, 3], [_ 4, 5]] | 0x9f018202039f0405ffff |
// | | |
// | [_ 1, [2, 3], [4, 5]] | 0x9f01820203820405ff |
// | | |
// | [1, [2, 3], [_ 4, 5]] | 0x83018202039f0405ff |
// | | |
// | [1, [_ 2, 3], [4, 5]] | 0x83019f0203ff820405 |
// | | |
// | [_ 1, 2, 3, 4, 5, 6, 7, 8, | 0x9f0102030405060708090a0b0c0d0e0f |
// | 9, 10, 11, 12, 13, 14, 15, | 101112131415161718181819ff |
// | 16, 17, 18, 19, 20, 21, 22, | |
// | 23, 24, 25] | |
// | | |
// | {_ "a": 1, "b": [_ 2, 3]} | 0xbf61610161629f0203ffff |
// | | |
}
BOOST_AUTO_TEST_CASE( BinaryString )
{
{
const char binaryData[] = "\0binary string\0";
std::vector<char> binaryBuf(binaryData, binaryData + sizeof(binaryData) - 1);
const char encoded[] = "\x4F\x00\x62\x69\x6E\x61\x72\x79"
"\x20\x73\x74\x72\x69\x6E\x67\x0";
BOOST_CHECK(encode(binaryBuf) == toVector(encoded));
BOOST_CHECK(binaryBuf == decode(toVector(encoded)));
}
// | | |
// | (_ h'0102', h'030405') | 0x5f42010243030405ff |
// | | |
// | (_ "strea", "ming") | 0x7f657374726561646d696e67ff |
// | | |
}
BOOST_AUTO_TEST_CASE( Interface )
{
{
std::map<CborValue, CborValue> map;
map[CborValue("a")] = CborValue("A");
map[CborValue("b")] = CborValue("B");
map[CborValue("c")] = CborValue("C");
CborValue value(map);
BOOST_CHECK(value.size() == 3);
BOOST_CHECK(value.hasMember("a"));
BOOST_CHECK(value.hasMember("b"));
BOOST_CHECK(value.hasMember("c"));
BOOST_CHECK(value.hasMember("A") == false );
BOOST_CHECK(value.hasMember("B") == false );
BOOST_CHECK(value.hasMember("C") == false );
BOOST_CHECK(value.member("a") == CborValue("A"));
BOOST_CHECK(value.member("b") == CborValue("B"));
BOOST_CHECK(value.member("c") == CborValue("C"));
}
{
std::vector<CborValue> arr;
arr.push_back(CborValue("a"));
arr.push_back(CborValue("b"));
arr.push_back(CborValue(1));
arr.push_back(CborValue(2));
CborValue value(arr);
BOOST_CHECK(value.size() == 4);
BOOST_CHECK(value.at(0) == CborValue("a"));
BOOST_CHECK(value.at(1) == CborValue("b"));
BOOST_CHECK(value.at(2) == CborValue(1));
BOOST_CHECK(value.at(3) == CborValue(2));
}
{
std::map<CborValue, CborValue> map;
map[CborValue("a")] = CborValue("A");
map[CborValue("b")] = CborValue("B");
CborValue cborMap(map);
CborValue::Iterator it(cborMap);
BOOST_CHECK(it.hasNext() == true);
BOOST_CHECK(it.hasPrev() == false);
BOOST_CHECK(it.next() == CborValue("A"));
BOOST_CHECK(it.key() == CborValue("a"));
BOOST_CHECK(it.value() == CborValue("A"));
BOOST_CHECK(it.next() == CborValue("B"));
BOOST_CHECK(it.hasNext() == false);
BOOST_CHECK(it.hasPrev() == true);
BOOST_CHECK(it.key() == CborValue("b"));
BOOST_CHECK(it.value() == CborValue("B"));
}
{
std::vector<CborValue> arr;
arr.push_back(CborValue("A"));
arr.push_back(CborValue("B"));
CborValue cborArr(arr);
CborValue::Iterator it(cborArr);
BOOST_CHECK(it.hasNext() == true);
BOOST_CHECK(it.hasPrev() == false);
BOOST_CHECK(it.next() == CborValue("A"));
BOOST_CHECK(it.key() == CborValue(0));
BOOST_CHECK(it.value() == CborValue("A"));
BOOST_CHECK(it.next() == CborValue("B"));
BOOST_CHECK(it.hasNext() == false);
BOOST_CHECK(it.hasPrev() == true);
BOOST_CHECK(it.key() == CborValue(1));
BOOST_CHECK(it.value() == CborValue("B"));
}
}
| 42.539715 | 128 | 0.550007 | [
"vector"
] |
6fc3c828ee522281726f50afeb83b972ed0b137c | 4,367 | cpp | C++ | src/FusionUKF.cpp | mkleung-dev/CarND-Extended-Kalman-Filter-Project | 37db986ee91985ccc926fc02ca852c4337373750 | [
"MIT"
] | null | null | null | src/FusionUKF.cpp | mkleung-dev/CarND-Extended-Kalman-Filter-Project | 37db986ee91985ccc926fc02ca852c4337373750 | [
"MIT"
] | null | null | null | src/FusionUKF.cpp | mkleung-dev/CarND-Extended-Kalman-Filter-Project | 37db986ee91985ccc926fc02ca852c4337373750 | [
"MIT"
] | null | null | null | #include "FusionUKF.h"
#include <iostream>
#include "Eigen/Dense"
#include "tools.h"
using Eigen::MatrixXd;
using Eigen::VectorXd;
using std::cout;
using std::endl;
using std::vector;
/**
* Constructor.
*/
FusionUKF::FusionUKF(bool bUseLaser, bool bUseRadar) : FusionKF(bUseLaser, bUseRadar) {
// initializing matrices
R_laser_ = MatrixXd(2, 2);
R_radar_ = MatrixXd(3, 3);
//measurement covariance matrix - laser
R_laser_ << 0.0225, 0,
0, 0.0225;
//measurement covariance matrix - radar
R_radar_ << 0.09, 0, 0,
0, 0.0009, 0,
0, 0, 0.09;
/**
* Finish initializing the FusionUKF.
* Set the process and measurement noises
*/
ukf_ = UnscentedKalmanFilter();
/**
* Proces Noise Q (2 x 2):
* longitudinal acceleration noise, 0
* 0, yaw acceleration noise
* longitudinal acceleration noise: Range +- 4 m/s^2
* yaw acceleration noise: Range +- 0.6 rad/s^2
*/
ukf_.Q_ = MatrixXd(2, 2);
ukf_.Q_ << 4, 0,
0, 0.09;
}
/**
* Destructor.
*/
FusionUKF::~FusionUKF() {}
void FusionUKF::ProcessMeasurement(const MeasurementPackage &measurement_pack) {
/**
* Initialization
*/
if (!is_initialized_) {
/**
* Initialize the state ukf_.x_ with the first measurement.
* Create the covariance matrix.
* You'll need to convert radar from polar to cartesian coordinates.
*/
// first measurement
// px, py, velocity, angle, angular velocity;
ukf_.x_ = VectorXd(5);
ukf_.x_ << 1, 1, 1, 1, 1;
ukf_.P_ = MatrixXd(5, 5);
ukf_.P_ << 1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1;
if (measurement_pack.sensor_type_ == MeasurementPackage::RADAR) {
// Convert radar from polar to cartesian coordinates
// and initialize state.
ukf_.x_ << measurement_pack.raw_measurements_[0] * cos(measurement_pack.raw_measurements_[1]),
measurement_pack.raw_measurements_[0] * sin(measurement_pack.raw_measurements_[1]),
0,
0,
0;
}
else if (measurement_pack.sensor_type_ == MeasurementPackage::LASER) {
// Initialize state.
ukf_.x_ << measurement_pack.raw_measurements_[0],
measurement_pack.raw_measurements_[1],
0,
0,
0;
}
previous_timestamp_ = measurement_pack.timestamp_;
// done initializing, no need to predict or update
is_initialized_ = true;
return;
}
if (!bUseRadar_ && measurement_pack.sensor_type_ == MeasurementPackage::RADAR) {
return;
}
if (!bUseLaser_ && measurement_pack.sensor_type_ == MeasurementPackage::LASER) {
return;
}
/**
* Prediction
*/
/**
* Update the state transition matrix F according to the new elapsed time.
* Time is measured in seconds.
* Update the process noise covariance matrix.
* Use noise_ax = 9 and noise_ay = 9 for your Q matrix.
*/
float dt = (measurement_pack.timestamp_ - previous_timestamp_) / 1000000.0;
ukf_.delta_t_ = dt;
ukf_.Predict();
/**
* Update
*/
/**
* - Use the sensor type to perform the update step.
* - Update the state and covariance matrices.
*/
if (measurement_pack.sensor_type_ == MeasurementPackage::RADAR) {
// Radar updates
ukf_.R_ = R_radar_;
ukf_.UpdateByRadarMeasurement(measurement_pack.raw_measurements_);
} else {
// Laser updates
ukf_.R_ = R_laser_;
ukf_.UpdateByLaserMeasurement(measurement_pack.raw_measurements_);
}
previous_timestamp_ = measurement_pack.timestamp_;
// print the output
cout << "x_ = " << endl << ukf_.x_ << endl;
cout << "P_ = " << endl << ukf_.P_ << endl;
}
/**
* Return the estimated position x.
*/
float FusionUKF::GetPx() {
return ukf_.x_(0);
}
/**
* Return the estimated position y.
*/
float FusionUKF::GetPy() {
return ukf_.x_(1);
}
/**
* Return the estimated velocity x.
*/
float FusionUKF::GetVx() {
return ukf_.x_(2) * cos(ukf_.x_(3));
}
/**
* Return the estimated velocity y.
*/
float FusionUKF::GetVy() {
return ukf_.x_(2) * sin(ukf_.x_(3));
}
| 25.538012 | 100 | 0.592627 | [
"vector"
] |
6fc3e0564dd9a19f6c62b7919c4508192e0faa2d | 5,896 | hpp | C++ | include/core/Reference.hpp | skimmy/lib-bio | 221d97f3aa37a3d276c21ade7c83d1aba4558c89 | [
"Apache-2.0"
] | null | null | null | include/core/Reference.hpp | skimmy/lib-bio | 221d97f3aa37a3d276c21ade7c83d1aba4558c89 | [
"Apache-2.0"
] | 1 | 2015-10-06T13:03:30.000Z | 2015-10-06T13:03:30.000Z | include/core/Reference.hpp | skimmy/lib-bio | 221d97f3aa37a3d276c21ade7c83d1aba4558c89 | [
"Apache-2.0"
] | 2 | 2015-11-05T11:20:06.000Z | 2019-04-04T14:26:44.000Z | #ifndef REFERENCE_H
#define REFERENCE_H
#include <core/Sequence.h>
#include <core/KMer.hpp>
#include <memory>
#include <cstring>
#include <list>
/**
* \brief This class represents a \e refernce sequence from the
* genomic point of view.
*
* References are genomic sequence (and therefore this class is
* of Sequence type) and are usually used to represent known DNA
* and or RNA sequences (less frequently there are other type of
* sequences like proteic. amino acis, ...).
*
* This class is used to define a DNA biological sequence (although
* it may be used also in other cases).
*
* \sa Sequence
*/
class Reference : public Sequence {
public:
// -------------------------- STATIC FACTORY METHODS -------------------------
static unique_ptr<Reference> createFromString(const string& s);
// ----------------------- CONSTRUCTORS AND DESTRUCTOR ----------------------
/**
* \brief Creates an empty Reference object
*
* \sa Reference(const string& sequence)
* \sa Reference(const char* sequence, size_t n)
* \sa Reference(const Reference& other)
*/
Reference();
/**
* \brief Creates a Reference object from astandard \c string.
*
* This constructor implicitally assumes that the reference is
* stored as a string character, the conversion is perfomed
* via the <tt>c_str()</tt> method of \c string .
* The size of the reference is infered from the length of the
* passed string.
*
* \param sequence The string containing the reference
*
* \sa Reference(const Reference& other)
* \sa Reference(const char* sequence, size_t n)
* \sa Reference()
*/
Reference(const string& sequence);
/**
* \brief Createsa a Reference object from a standard C string
*
* This constructor uses the input \c char pointer to create
* a new Reference object with the given lenght. Input pointer
* should refere to an array with at least the indicated number
* of characters otherwise unpredictable behavior may arise.
*
* \param sequence The pointer to the sequence
* \param n The length of the referenceto be created
*
* \sa Reference(const string& sequence)
* \sa Reference()
* \sa Reference(const Reference& other)
*/
Reference(const char* sequence, size_t n);
/**
* \brief Creates a copy of the given Reference object
*
* \param other The Reference object to be copied
*
* \sa Reference(const string& sequence)
* \sa Reference(const char* sequence, size_t n)
* \sa Reference()
*/
Reference(const Reference& other);
~Reference();
// ---------------------------- GET AND SET METHODS ----------------------------
/**
* \brief Returns the list of all k-mers of the stored seuqence.
*
* This method creates and returns a standard \c list object
* containing all the k-mers (i.e. k long substrings) of the
* stored reference. The list is templated with KMer class and,
* therefore, programmer should use this (preferred) class to
* manage k-mers
*
* The length of the returned substrings (i.e. \c k ) is controlled
* by the passed parameter. If \f$ n \f$ is the length of the
* reference, than the returned list contains exactly \f$ n - k + \f$
* elements. Note that for efficiency and semantic reasons, the
* returned list is <b>not a set</b> and therefore duplicated
* k-mers are include as well. On the other hand this could be
* usefull to maintain the reference to the 'source' of the k-mer
* since the method guarantees that i-th returned element is
* exactly the i-th k-mer of the reference (i.e. is the k long
* substrings starting at position i of the reference).
*
* \param k The length of the returned substring
* \return A \c list standard object containing all k-mers as
* KMer objects
*
* \sa KMers
*/
list<KMer> getKMerList(size_t k);
// ---------------------------------------------------------
// CONVERSION METHODS
// ---------------------------------------------------------
/**
* \brief Converts the interal sequence into a color space
* sequence
*
* This method should be called only if necessary because it
* requires creation of two new \c string object (to be passed
* to the ColorAlphabet::basesToColors() method) used as
* temporary container. For long sequences this operation may
* sensibly slow down program execution.
*
* \param primer The \e primer character to initialize deconding
* \return A referenced copy of the acutal Reference object (after
* its conversion to color space representation)
*
* \sa toBases()
*/
Reference& toColors(char primer);
/**
* \brief Converts the interal sequence into a base space
* sequence
*
* This method should be called only if necessary because it
* requires creation of two new \c string object (to be passed
* to the ColorAlphabet::colorsToBases() method) used as
* temporary container. For long sequences this operation may
* sensibly slow down program execution.
*
* \param primer The \e primer character to initialize deconding
* \return A referenced copy of the acutal Reference object (after
* its conversion to base space representation)
*
* \sa toColors()
*/
Reference& toBases(char primer);
// ---------------------------------------------------------
// 'SEQUENCE' OVERRIDE METHODS
// ---------------------------------------------------------
const void* getSequence() const;
size_t getSequenceLength() const;
size_t getElementSize() const;
size_t getByteCount() const;
char getBaseAt(size_t i) const;
// IOSTREAM
friend ostream& operator<< (ostream& os, const Reference& ref);
private:
// -------------------- UTILITY METHODS --------------------
void init(size_t n);
char* sequence;
size_t length;
};
#endif
| 33.691429 | 82 | 0.637212 | [
"object"
] |
6fd537b2be9c753982badfab0671203d9da56711 | 1,026 | hpp | C++ | source/qt_creator_plugin/editor_widget.hpp | Panzerschrek/U-00DC-Sprache | eb677a66d178985433a62eb6b8a50ce2cdb14b1a | [
"BSD-3-Clause"
] | 45 | 2016-06-21T22:28:43.000Z | 2022-03-26T12:21:46.000Z | source/qt_creator_plugin/editor_widget.hpp | Panzerschrek/U-00DC-Sprache | eb677a66d178985433a62eb6b8a50ce2cdb14b1a | [
"BSD-3-Clause"
] | 6 | 2020-07-12T18:00:10.000Z | 2021-11-30T11:20:14.000Z | source/qt_creator_plugin/editor_widget.hpp | Panzerschrek/U-00DC-Sprache | eb677a66d178985433a62eb6b8a50ce2cdb14b1a | [
"BSD-3-Clause"
] | 5 | 2019-09-03T17:20:34.000Z | 2022-01-30T15:10:21.000Z | #pragma once
#include <QComboBox>
#include <QTimer>
#include <QTreeView>
#include <plugins/texteditor/texteditor.h>
#include "program_model.hpp"
#include "outline_widget_model.hpp"
namespace U
{
namespace QtCreatorPlugin
{
class OutlineTreeViewComboBox : public QComboBox
{
Q_OBJECT
public:
explicit OutlineTreeViewComboBox( QWidget* parent = nullptr );
virtual bool eventFilter( QObject* object, QEvent* event ) override;
virtual void hidePopup() override;
private:
QTreeView view_;
bool skip_next_hide_= false;
};
class EditorWidget final : public TextEditor::TextEditorWidget
{
Q_OBJECT
public:
EditorWidget();
private:
virtual void finalizeInitialization() override;
private:
void OnTextChanged();
void OnTimerExpired();
void OnItemActivated();
void OnCursorPositionChanged();
private:
QTimer timer_;
OutlineTreeViewComboBox combo_box_;
OutlineWidgetModel combo_box_model_;
ProgramModelPtr program_model_;
bool block_cursor_sync_= false;
};
} // namespace QtCreatorPlugin
} // namespace U
| 17.389831 | 69 | 0.783626 | [
"object"
] |
6fd98ec75b5fc7d232fe4285932b42877a724823 | 606 | cpp | C++ | Interface/PowerCycles.cpp | AcubeSAT/rtb-software | 906425dea139d454bdee731a62a47d9d8602f744 | [
"MIT"
] | null | null | null | Interface/PowerCycles.cpp | AcubeSAT/rtb-software | 906425dea139d454bdee731a62a47d9d8602f744 | [
"MIT"
] | null | null | null | Interface/PowerCycles.cpp | AcubeSAT/rtb-software | 906425dea139d454bdee731a62a47d9d8602f744 | [
"MIT"
] | null | null | null | #include "PowerCycles.h"
#include "Clock.h"
#include "main.h"
void PowerCycles::logPowerCycle(const std::string &state) {
{
const std::lock_guard lock(timeLogMutex);
timeLog.push_back(Event {
currentDatetimeMilliseconds().str(),
formatDuration(std::chrono::milliseconds(microcontrollerClock.load())).str(),
currentExperimentTime().str(),
currentDatetimeMillisecondsUNIX().count() / 1000.0,
state,
});
}
csv->addCSVentry("powercycle", std::vector<std::string>{
state
});
}
| 28.857143 | 93 | 0.585809 | [
"vector"
] |
6ff1b6f59aa933c79dc69de326838fc40c60be33 | 23,602 | cpp | C++ | src/movingobject.cpp | yds12/agl2 | 1cdaee9363792f8a79eb6a97e429999909110637 | [
"MIT"
] | null | null | null | src/movingobject.cpp | yds12/agl2 | 1cdaee9363792f8a79eb6a97e429999909110637 | [
"MIT"
] | null | null | null | src/movingobject.cpp | yds12/agl2 | 1cdaee9363792f8a79eb6a97e429999909110637 | [
"MIT"
] | null | null | null | #include "agl/movingobject.h"
void AGL::MovingObject::move(AGL::Vector2 &constantSpeed, vector<AGL::IPhysicalObject*> &obstacles, bool modifySpeed)
{
// calcula posição final
Vector2 finalPosition = *position + constantSpeed;
float xVar = finalPosition.x - position->x;
float yVar = finalPosition.y - position->y;
// PARA MOVER PRECISA CHECAR COLISÃO
for (int i = 0; i < obstacles.size(); i++)
{
if (!obstacles[i]->solid) continue;
IPhysicalObject* obstacle = obstacles[i];
FloatRectangle obstacleBounds = obstacle->getPhysicalBounds();
if (constantSpeed.x == 0) // X NULO
{
if (constantSpeed.y == 0) // X NULO E Y NULO
break;
else if (constantSpeed.y > 0) // X NULO E Y POSITIVO
{
FloatRectangle moveRec(position->x, position->y, physicalSize->x, physicalSize->y + yVar);
if (obstacleBounds.intersects(moveRec) && position->y + physicalSize->y <= obstacle->position->y)
{
// vai limitar Y
constantSpeed.y = 0;
position->y = obstacle->position->y - physicalSize->y;
bottom = obstacle;
}
}
else // X NULO E Y NEGATIVO
{
FloatRectangle moveRec(position->x, position->y + yVar, physicalSize->x, physicalSize->y - yVar);
if (obstacleBounds.intersects(moveRec) && !obstacle->isPassable)
{
// vai limitar Y
constantSpeed.y = 0;
position->y = obstacle->position->y + obstacle->physicalSize->y;
top = obstacle;
}
}
}
else if (constantSpeed.x > 0) // X POSITIVO
{
if (constantSpeed.y == 0) // X POSITIVO E Y NULO
{
FloatRectangle moveRec(position->x, position->y, physicalSize->x + xVar, physicalSize->y);
if (obstacleBounds.intersects(moveRec) && !obstacle->isPassable)
{
// vai limitar X
constantSpeed.x = 0;
position->x = obstacle->position->x - physicalSize->x;
right = obstacle;
}
}
else if (constantSpeed.y > 0) // X POSITIVO E Y POSITIVO
{
FloatRectangle moveRec(position->x, position->y, physicalSize->x + xVar, physicalSize->y + yVar);
if (obstacleBounds.intersects(moveRec))
{
if (obstacle->position->x >= position->x + physicalSize->x)
{
// possivel limitar X
if (obstacle->position->y >= position->y + physicalSize->y)
{
// possivel limitar Y também, verificar qual limita
float timeX = (obstacle->position->x - position->x + physicalSize->x) / constantSpeed.x;
float timeY = (obstacle->position->y - position->y + physicalSize->y) / constantSpeed.y;
if (timeX >= timeY && !obstacle->isPassable)
{
// vai limitar X
constantSpeed.x = 0;
position->x = obstacle->position->x - physicalSize->x;
right = obstacle;
}
else if (position->y + physicalSize->y <= obstacle->position->y)
{
// vai limitar Y
constantSpeed.y = 0;
position->y = obstacle->position->y - physicalSize->y;
bottom = obstacle;
}
}
else if (!obstacle->isPassable)
{
// vai limitar X
constantSpeed.x = 0;
position->x = obstacle->position->x - physicalSize->x;
right = obstacle;
}
}
else if (position->y + physicalSize->y <= obstacle->position->y)
{
// vai limitar Y
constantSpeed.y = 0;
position->y = obstacle->position->y - physicalSize->y;
bottom = obstacle;
}
}
}
else // X POSITIVO E Y NEGATIVO
{
FloatRectangle moveRec(position->x, position->y + yVar, physicalSize->x + xVar, physicalSize->y - yVar);
if (obstacleBounds.intersects(moveRec) && !obstacle->isPassable)
{
if (obstacle->position->x >= position->x + physicalSize->x)
{
// possivel limitar X
if (obstacle->position->y + obstacle->physicalSize->y <= position->y)
{
// possivel limitar Y também, verificar qual limita
float timeX = (obstacle->position->x - position->x + physicalSize->x) / constantSpeed.x;
float timeY = (obstacle->position->y + obstacle->physicalSize->y - position->y) / constantSpeed.y;
if (timeX >= timeY)
{
// vai limitar X
constantSpeed.x = 0;
position->x = obstacle->position->x - physicalSize->x;
right = obstacle;
}
else
{
// vai limitar Y
constantSpeed.y = 0;
position->y = obstacle->position->y + obstacle->physicalSize->y;
top = obstacle;
}
}
else if (!obstacle->isPassable)
{
// vai limitar X
constantSpeed.x = 0;
position->x = obstacle->position->x - physicalSize->x;
right = obstacle;
}
}
else
{
// vai limitar Y
constantSpeed.y = 0;
position->y = obstacle->position->y + obstacle->physicalSize->y;
top = obstacle;
}
}
}
}
else // X NEGATIVO
{
if (constantSpeed.y == 0) // X NEGATIVO E Y NULO
{
FloatRectangle moveRec(position->x + xVar, position->y, physicalSize->x - xVar, physicalSize->y);
if (obstacleBounds.intersects(moveRec) && !obstacle->isPassable)
{
// vai limitar X
constantSpeed.x = 0;
position->x = obstacle->position->x + obstacle->physicalSize->x;
left = obstacle;
}
}
else if (constantSpeed.y > 0) // X NEGATIVO E Y POSITIVO
{
FloatRectangle moveRec(position->x + xVar, position->y, physicalSize->x - xVar, physicalSize->y + yVar);
if (obstacleBounds.intersects(moveRec))
{
if (obstacle->position->x + obstacle->physicalSize->x <= position->x)
{
// possivel limitar X
if (obstacle->position->y >= position->y + physicalSize->y)
{
// possivel limitar Y também, verificar qual limita
float timeX = (obstacle->position->x + obstacle->physicalSize->x - position->x) / constantSpeed.x;
float timeY = (obstacle->position->y - position->y + physicalSize->y) / constantSpeed.y;
if (timeX >= timeY && !obstacle->isPassable)
{
// vai limitar X
constantSpeed.x = 0;
position->x = obstacle->position->x + obstacle->physicalSize->x;
left = obstacle;
}
else if (position->y + physicalSize->y <= obstacle->position->y)
{
// vai limitar Y
constantSpeed.y = 0;
position->y = obstacle->position->y - physicalSize->y;
bottom = obstacle;
}
}
else if (!obstacle->isPassable)
{
// vai limitar X
constantSpeed.x = 0;
position->x = obstacle->position->x + obstacle->physicalSize->x;
left = obstacle;
}
}
else if (position->y + physicalSize->y <= obstacle->position->y)
{
// vai limitar Y
constantSpeed.y = 0;
position->y = obstacle->position->y - physicalSize->y;
bottom = obstacle;
}
}
}
else // X NEGATIVO E Y NEGATIVO
{
FloatRectangle moveRec(position->x + xVar, position->y + yVar, physicalSize->x - xVar, physicalSize->y - yVar);
if (obstacleBounds.intersects(moveRec) && !obstacle->isPassable)
{
if (obstacle->position->x + obstacle->physicalSize->x <= position->x)
{
// possivel limitar X
if (obstacle->position->y + obstacle->physicalSize->y <= position->y)
{
// possivel limitar Y também, verificar qual limita
float timeX = (obstacle->position->x + obstacle->physicalSize->x - position->x) / constantSpeed.x;
float timeY = (obstacle->position->y + obstacle->physicalSize->y - position->y) / constantSpeed.y;
if (timeX >= timeY)
{
// vai limitar X
constantSpeed.x = 0;
position->x = obstacle->position->x + obstacle->physicalSize->x;
left = obstacle;
}
else
{
// vai limitar Y
constantSpeed.y = 0;
position->y = obstacle->position->y + obstacle->physicalSize->y;
top = obstacle;
}
}
else if (!obstacle->isPassable)
{
// vai limitar X
constantSpeed.x = 0;
position->x = obstacle->position->x + obstacle->physicalSize->x;
left = obstacle;
}
}
else
{
// vai limitar Y
constantSpeed.y = 0;
position->y = obstacle->position->y + obstacle->physicalSize->y;
top = obstacle;
}
}
}
}
}
// nenhuma colisão, seta posição final
Vector2 newPos(position->x + constantSpeed.x, position->y + constantSpeed.y);
*position = newPos;
if (modifySpeed)
*speed = constantSpeed;
Vector2 zero(0, 0);
*storedForce = zero;
}
AGL::Vector2 AGL::MovingObject::getAcceleration()
{
return *acceleration;
}
AGL::Vector2 AGL::MovingObject::getSpeed()
{
return *speed;
}
bool AGL::MovingObject::collidesOnTop()
{
return top != NULL;
}
bool AGL::MovingObject::collidesOnRight()
{
return right != NULL;
}
bool AGL::MovingObject::collidesOnBottom()
{
return bottom != NULL;
}
bool AGL::MovingObject::collidesOnLeft()
{
return left != NULL;
}
AGL::IPhysicalObject* AGL::MovingObject::getObjectOnTop()
{
return top;
}
AGL::IPhysicalObject* AGL::MovingObject::getObjectOnRight()
{
return right;
}
AGL::IPhysicalObject* AGL::MovingObject::getObjectOnBottom()
{
return bottom;
}
AGL::IPhysicalObject* AGL::MovingObject::getObjectOnLeft()
{
return left;
}
AGL::MovingObject::MovingObject() : AGL::IPhysicalObject()
{
top = NULL;
right = NULL;
bottom = NULL;
left = NULL;
path = NULL;
storedForce = new Vector2(0, 0);
speed = new Vector2(0, 0);
acceleration = new Vector2(0, 0);
}
AGL::MovingObject::MovingObject(AGL::Vector2 &position) : AGL::IPhysicalObject(position)
{
top = NULL;
right = NULL;
bottom = NULL;
left = NULL;
path = NULL;
storedForce = new Vector2(0, 0);
speed = new Vector2(0, 0);
acceleration = new Vector2(0, 0);
}
AGL::MovingObject::MovingObject(AGL::Vector2 &position, AGL::IntVector2 &physicalSize) : AGL::IPhysicalObject(position, physicalSize)
{
top = NULL;
right = NULL;
bottom = NULL;
left = NULL;
path = NULL;
storedForce = new Vector2(0, 0);
speed = new Vector2(0, 0);
acceleration = new Vector2(0, 0);
}
AGL::MovingObject::MovingObject(AGL::Vector2 &position, AGL::Image* image) : AGL::IPhysicalObject(image, position)
{
top = NULL;
right = NULL;
bottom = NULL;
left = NULL;
path = NULL;
storedForce = new Vector2(0, 0);
speed = new Vector2(0, 0);
acceleration = new Vector2(0, 0);
}
AGL::MovingObject::MovingObject(Drawer* drawer, AGL::Vector2 &position, AGL::Image* image) : AGL::IPhysicalObject(drawer, image, position)
{
top = NULL;
right = NULL;
bottom = NULL;
left = NULL;
path = NULL;
storedForce = new Vector2(0, 0);
speed = new Vector2(0, 0);
acceleration = new Vector2(0, 0);
}
void AGL::MovingObject::move(AGL::Vector2 &forces, vector<AGL::IPhysicalObject*> &obstacles)
{
vector<AGL::Ramp*> ramps;
move(forces, obstacles, ramps);
}
void AGL::MovingObject::move(AGL::Vector2 &forces, vector<AGL::IPhysicalObject*> &obstacles, vector<AGL::Ramp*> &ramps)
{
forces += *storedForce;
// Inicialmente já checa colisões existentes
top = NULL;
right = NULL;
bottom = NULL;
left = NULL;
for (int i = 0; i < obstacles.size(); i++)
{
if (!obstacles[i]->solid) continue;
IPhysicalObject* obstacle = obstacles[i];
// acima
if ((obstacle->position->y + obstacle->physicalSize->y == position->y) &&
(position->x + physicalSize->x > obstacle->position->x && obstacle->position->x + obstacle->physicalSize->x > position->x) &&
!obstacle->isPassable)
top = obstacle;
// direita
if ((obstacle->position->x == position->x + physicalSize->x) &&
(position->y + physicalSize->y > obstacle->position->y && obstacle->position->y + obstacle->physicalSize->y > position->y))
right = obstacle;
// abaixo
if ((obstacle->position->y == position->y + physicalSize->y) &&
(position->x + physicalSize->x > obstacle->position->x && obstacle->position->x + obstacle->physicalSize->x > position->x))
bottom = obstacle;
// esquerda
if ((obstacle->position->x + obstacle->physicalSize->x == position->x) &&
(position->y + physicalSize->y > obstacle->position->y && obstacle->position->y + obstacle->physicalSize->y > position->y))
left = obstacle;
}
// abaixo (rampa)
Vector2 feet(position->x + (float)physicalSize->x / 2, position->y + physicalSize->y);
for (int i = 0; i < ramps.size(); i++)
{
Ramp* ramp = ramps[i];
if (feet.x > ramp->position->x && feet.x < ramp->position->x + ramp->physicalSize->x &&
feet.y > ramp->position->y && feet.y <= ramp->position->y + ramp->physicalSize->y) // tá dentro
{
float feetY = ramp->getY(feet.x);
if (feet.y == feetY)
{
bottom = ramp;
speed->y = 0;
break;
}
}
}
// Caso haja colisões iniciais, não permite a existência de forças
if (forces.x < 0 && collidesOnLeft())
forces.x = 0;
else if (forces.x > 0 && collidesOnRight())
forces.x = 0;
if (forces.y < 0 && collidesOnTop())
forces.y = 0;
else if (forces.y > 0 && collidesOnBottom())
forces.y = 0;
// Calcula aceleração
acceleration->x = forces.x / mass;
acceleration->y = (speed->y > PhysicalEnvironment::maxFallSpeed || collidesOnBottom() ?
0 : PhysicalEnvironment::gravity) + (forces.y / mass);
// Calcula velocidade
if ((acceleration->x > 0 && speed->x < 0 && acceleration->x > -speed->x) || (acceleration->x < 0 && speed->x > 0 && -acceleration->x > speed->x))
speed->x = 0;
else
speed->x += acceleration->x;
if ((acceleration->y > 0 && speed->y < 0 && acceleration->y > -speed->y) || (acceleration->y < 0 && speed->y > 0 && -acceleration->y > speed->y))
speed->y = 0;
else
speed->y += acceleration->y;
move(*speed, obstacles, true);
Vector2 feet2(position->x + (float)physicalSize->x / 2, position->y + physicalSize->y);
for (int i = 0; i < ramps.size(); i++)
{
Ramp* ramp = ramps[i];
if (feet2.x > ramp->position->x && feet2.x < ramp->position->x + ramp->physicalSize->x &&
feet2.y > ramp->position->y && feet2.y <= ramp->position->y + ramp->physicalSize->y) // tá dentro
{
float feetY = ramp->getY(feet2.x);
if (feet2.y > feetY - PhysicalEnvironment::rampAdherence && speed->y >= 0)
{
if (ramp->isLeftToRight() && feet2.x >= ramp->position->x + ramp->physicalSize->x - speed->x - PhysicalEnvironment::rampAdjustment)
position->y = ramp->position->y - physicalSize->y;
else if (!ramp->isLeftToRight() && feet2.x <= ramp->position->x - speed->x + PhysicalEnvironment::rampAdjustment)
position->y = ramp->position->y - physicalSize->y;
else
position->y = feetY - physicalSize->y;
float ratio = (float)ramp->physicalSize->y / (float)ramp->physicalSize->x;
if (ratio > PhysicalEnvironment::rampSlipTangent) // quando a rampa é inclinada demais, o cara tende a escorregar
{
Vector2 ff(ratio * ratio * (ramp->isLeftToRight() ? -PhysicalEnvironment::rampSlipForce : PhysicalEnvironment::rampSlipForce), 0);
storedForce->x += ff.x;
storedForce->y += ff.y;
}
break;
}
}
}
}
void AGL::MovingObject::moveFixed(float rotation, float speed)
{
float xVar = (float)(speed * cos(rotation));
float yVar = (float)(speed * sin(rotation));
position->x += xVar;
position->y += yVar;
}
void AGL::MovingObject::moveFixed(float rotation, float speed, vector<AGL::IPhysicalObject*> &obstacles, vector<AGL::Ramp*> &ramps)
{
float xVar = (float)(speed * cos(rotation));
float yVar = (float)(speed * sin(rotation));
Vector2 constSpeed(xVar, yVar);
move(constSpeed, obstacles, false);
Vector2 center(position->x + (float)physicalSize->x / 2, position->y + (float)physicalSize->y / 2);
for (int i = 0; i < ramps.size(); i++)
{
Ramp* ramp = ramps[i];
if (center.x > ramp->position->x && center.x < ramp->position->x + ramp->physicalSize->x &&
center.y > ramp->position->y && center.y <= ramp->position->y + ramp->physicalSize->y) // tá dentro
{
if (center.y >= ramp->getY(center.x))
bottom = ramp;
}
}
}
void AGL::MovingObject::moveTowards(AGL::Vector2 &aim, float absoluteSpeed)
{
Vector2 zero(0, 0);
if (*speed != zero) // já está em movimento
{
if ((speed->x < 0 && position->x + speed->x <= aim.x) || (speed->x >= 0 && position->x + speed->x >= aim.x))
position->x = aim.x;
else
position->x = position->x + speed->x;
if ((speed->y < 0 && position->y + speed->y <= aim.y) || (speed->y >= 0 && position->y + speed->y >= aim.y))
position->y = aim.y;
else
position->y += speed->y;
if (position->x == aim.x && position->y == aim.y)
*speed = zero;
}
else // iniciou o movimento agora
{
float xD = aim.x - position->x;
float yD = aim.y - position->y;
double distance = sqrt(xD * xD + yD * yD);
speed->x = xD / (float)(distance / absoluteSpeed);
speed->y = yD / (float)(distance / absoluteSpeed);
}
}
void AGL::MovingObject::patrol(AGL::Vector2 &aim, float absoluteSpeed)
{
Vector2 zero(0, 0);
if (*speed == zero)
{
if (path == NULL)
{
path = new vector<Vector2>;
path->push_back(*position);
path->push_back(aim);
goingToPath = 0;
}
if (goingToPath == 0)
goingToPath = 1;
else
goingToPath = 0;
}
moveTowards((*path)[goingToPath], absoluteSpeed);
}
void AGL::MovingObject::followClosedPath(vector<AGL::Vector2> &points, float absoluteSpeed)
{
Vector2 zero(0, 0);
if (*speed == zero)
{
if (path == NULL)
{
path = new vector<Vector2>;
for(int i = 0; i < points.size(); i++)
path->push_back(points[i]);
goingToPath = 0;
}
if (goingToPath < path->size() - 1)
goingToPath++;
else
goingToPath = 0;
}
moveTowards((*path)[goingToPath], absoluteSpeed);
}
void AGL::MovingObject::followOpenPath(vector<AGL::Vector2> &points, float absoluteSpeed)
{
Vector2 zero(0, 0);
if (*speed == zero)
{
if (path == NULL)
{
path = new vector<Vector2>;
for(int i = 0; i < points.size(); i++)
path->push_back(points[i]);
goingToPath = 0;
}
if (reversePath)
{
if (goingToPath != 0)
goingToPath--;
else
{
reversePath = false;
goingToPath++;
}
}
else
{
if (goingToPath < path->size() - 1)
goingToPath++;
else
{
reversePath = true;
goingToPath--;
}
}
}
moveTowards((*path)[goingToPath], absoluteSpeed);
}
void AGL::MovingObject::stop()
{
Vector2 zero(0, 0);
*acceleration = zero;
*speed = zero;
delete path;
path = NULL;
}
void AGL::MovingObject::moveElevatorTowards(AGL::Vector2 &aim, float absoluteSpeed, vector<AGL::MovingObject*> &sprites, vector<AGL::IPhysicalObject*> &obstacles)
{
Vector2 zero(0, 0);
if (*speed != zero) // já está em movimento
{
vector<MovingObject*> passengers;
if (isElevator)
{
for (int i = 0; i < sprites.size(); i++)
{
MovingObject* passenger = sprites[i];
if (position->x + physicalSize->x > passenger->position->x && passenger->position->x + passenger->physicalSize->x > position->x)
{
float feet = passenger->position->y + passenger->physicalSize->y;
if (feet == position->y) // está exatamente sobre o elevador
passengers.push_back(passenger);
else if (position->y > feet && position->y + speed->y < feet) // o elevador vai pegá-lo com o movimento do elevador
{
passenger->position->y = position->y - passenger->physicalSize->y;
passengers.push_back(passenger);
}
}
}
}
if ((speed->x < 0 && position->x + speed->x <= aim.x) || (speed->x > 0 && position->x + speed->x >= aim.x))
{
float prevX = position->x;
position->x = aim.x;
if ((speed->y < 0 && position->y + speed->y <= aim.y) || (speed->y > 0 && position->y + speed->y >= aim.y))
{
float prevY = position->y;
position->y = aim.y;
Vector2 cs(aim.x - prevX, aim.y - prevY);
for (int i = 0; i < passengers.size(); i++)
passengers[i]->move(cs, obstacles, false);
}
else if (speed->y != 0)
{
position->y += speed->y;
Vector2 cs(aim.x - prevX, speed->y);
for (int i = 0; i < passengers.size(); i++)
passengers[i]->move(cs, obstacles, false);
}
else
{
Vector2 cs(aim.x - prevX, 0);
for (int i = 0; i < passengers.size(); i++)
passengers[i]->move(cs, obstacles, false);
}
}
else if (speed->x != 0)
{
if ((speed->y < 0 && position->y + speed->y <= aim.y) || (speed->y > 0 && position->y + speed->y >= aim.y))
{
float prevY = position->y;
position->y = aim.y;
Vector2 cs(speed->x, aim.y - prevY);
for (int i = 0; i < passengers.size(); i++)
passengers[i]->move(cs, obstacles, false);
}
else if (speed->y != 0)
{
position->y += speed->y;
Vector2 cs(speed->x, speed->y);
for (int i = 0; i < passengers.size(); i++)
passengers[i]->move(cs, obstacles, false);
}
else
{
Vector2 cs(speed->x, 0);
for (int i = 0; i < passengers.size(); i++)
passengers[i]->move(cs, obstacles, false);
}
position->x += speed->x;
}
else
{
if ((speed->y < 0 && position->y + speed->y <= aim.y) || (speed->y > 0 && position->y + speed->y >= aim.y))
{
float prevY = position->y;
position->y = aim.y;
Vector2 cs(0, aim.y - prevY);
for (int i = 0; i < passengers.size(); i++)
passengers[i]->move(cs, obstacles, false);
}
else if (speed->y != 0)
{
position->y += speed->y;
Vector2 cs(0, speed->y);
for (int i = 0; i < passengers.size(); i++)
passengers[i]->move(cs, obstacles, false);
}
}
if (position->x == aim.x && position->y == aim.y)
*speed = zero;
}
else // iniciou o movimento agora
{
float xD = aim.x - position->x;
float yD = aim.y - position->y;
double distance = sqrt(xD * xD + yD * yD);
speed->x = (float)(xD / distance * absoluteSpeed);
speed->y = (float)(yD / distance * absoluteSpeed);
}
}
void AGL::MovingObject::patrolElevator(AGL::Vector2 &aim, float absoluteSpeed, vector<AGL::MovingObject*> &sprites, vector<AGL::IPhysicalObject*> &obstacles)
{
Vector2 zero(0, 0);
if (*speed == zero)
{
if (path == NULL)
{
path = new vector<Vector2>;
path->push_back(*position);
path->push_back(aim);
goingToPath = 0;
}
if (goingToPath == 0)
goingToPath = 1;
else
goingToPath = 0;
}
moveElevatorTowards((*path)[goingToPath], absoluteSpeed, sprites, obstacles);
}
void AGL::MovingObject::followElevatorClosedPath(vector<AGL::Vector2> &points, float absoluteSpeed, vector<AGL::MovingObject*> &sprites, vector<AGL::IPhysicalObject*> &obstacles)
{
Vector2 zero(0, 0);
if (*speed == zero)
{
if (path == NULL)
{
path = new vector<Vector2>;
for(int i = 0; i < points.size(); i++)
path->push_back(points[i]);
goingToPath = 0;
}
if (goingToPath < path->size() - 1)
goingToPath++;
else
goingToPath = 0;
}
moveElevatorTowards((*path)[goingToPath], absoluteSpeed, sprites, obstacles);
}
void AGL::MovingObject::followElevatorOpenPath(vector<AGL::Vector2> &points, float absoluteSpeed, vector<AGL::MovingObject*> &sprites, vector<AGL::IPhysicalObject*> &obstacles)
{
Vector2 zero(0, 0);
if (*speed == zero)
{
if (path == NULL)
{
path = new vector<Vector2>;
for(int i = 0; i < points.size(); i++)
path->push_back(points[i]);
goingToPath = 0;
}
if (reversePath)
{
if (goingToPath != 0)
goingToPath--;
else
{
reversePath = false;
goingToPath++;
}
}
else
{
if (goingToPath < path->size() - 1)
goingToPath++;
else
{
reversePath = true;
goingToPath--;
}
}
}
moveElevatorTowards((*path)[goingToPath], absoluteSpeed, sprites, obstacles);
}
| 26.790011 | 178 | 0.605627 | [
"vector",
"solid"
] |
b501d3295a82a71544373b23cbbc4ddf6a088f18 | 4,576 | cpp | C++ | src/analysis/processing/qgsalgorithmreverselinedirection.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | src/analysis/processing/qgsalgorithmreverselinedirection.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | src/analysis/processing/qgsalgorithmreverselinedirection.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | 1 | 2021-12-25T08:40:30.000Z | 2021-12-25T08:40:30.000Z | /***************************************************************************
qgsalgorithmreverselinedirection.cpp
------------------------------------
begin : July 2018
copyright : (C) 2018 by Nyall Dawson
email : nyall dot dawson at gmail dot com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsalgorithmreverselinedirection.h"
#include "qgscurve.h"
#include "qgsgeometrycollection.h"
///@cond PRIVATE
QString QgsReverseLineDirectionAlgorithm ::name() const
{
return QStringLiteral( "reverselinedirection" );
}
QString QgsReverseLineDirectionAlgorithm ::displayName() const
{
return QObject::tr( "Reverse line direction" );
}
QStringList QgsReverseLineDirectionAlgorithm ::tags() const
{
return QObject::tr( "swap,reverse,switch,flip,linestring,orientation" ).split( ',' );
}
QString QgsReverseLineDirectionAlgorithm ::group() const
{
return QObject::tr( "Vector geometry" );
}
QString QgsReverseLineDirectionAlgorithm ::groupId() const
{
return QStringLiteral( "vectorgeometry" );
}
QString QgsReverseLineDirectionAlgorithm ::outputName() const
{
return QObject::tr( "Reversed" );
}
QString QgsReverseLineDirectionAlgorithm ::shortHelpString() const
{
return QObject::tr( "This algorithm reverses the direction of curve or LineString geometries." );
}
QString QgsReverseLineDirectionAlgorithm::shortDescription() const
{
return QObject::tr( "Reverses the direction of curve or LineString geometries." );
}
QgsReverseLineDirectionAlgorithm *QgsReverseLineDirectionAlgorithm ::createInstance() const
{
return new QgsReverseLineDirectionAlgorithm();
}
QgsProcessing::SourceType QgsReverseLineDirectionAlgorithm::outputLayerType() const
{
return QgsProcessing::TypeVectorLine;
}
QList<int> QgsReverseLineDirectionAlgorithm::inputLayerTypes() const
{
return QList<int>() << QgsProcessing::TypeVectorLine;
}
QgsProcessingFeatureSource::Flag QgsReverseLineDirectionAlgorithm ::sourceFlags() const
{
// this algorithm doesn't care about invalid geometries
return QgsProcessingFeatureSource::FlagSkipGeometryValidityChecks;
}
QgsFeatureList QgsReverseLineDirectionAlgorithm ::processFeature( const QgsFeature &f, QgsProcessingContext &, QgsProcessingFeedback * )
{
QgsFeature feature = f;
if ( feature.hasGeometry() )
{
const QgsGeometry geom = feature.geometry();
if ( !geom.isMultipart() )
{
const QgsCurve *curve = qgsgeometry_cast< const QgsCurve * >( geom.constGet() );
if ( curve )
{
std::unique_ptr< QgsCurve > reversed( curve->reversed() );
if ( !reversed )
{
// can this even happen?
throw QgsProcessingException( QObject::tr( "Error reversing line" ) );
}
const QgsGeometry outGeom( std::move( reversed ) );
feature.setGeometry( outGeom );
}
}
else
{
std::unique_ptr< QgsAbstractGeometry > dest( geom.constGet()->createEmptyWithSameType() );
const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( geom.constGet() );
QgsGeometryCollection *destCollection = qgsgeometry_cast< QgsGeometryCollection * >( dest.get() );
for ( int i = 0; i < collection->numGeometries(); ++i )
{
const QgsCurve *curve = qgsgeometry_cast< const QgsCurve *>( collection->geometryN( i ) );
if ( curve )
{
std::unique_ptr< QgsCurve > reversed( curve->reversed() );
if ( !reversed )
{
// can this even happen?
throw QgsProcessingException( QObject::tr( "Error reversing line" ) );
}
destCollection->addGeometry( reversed.release() );
}
}
const QgsGeometry outGeom( std::move( dest ) );
feature.setGeometry( outGeom );
}
}
return QgsFeatureList() << feature;
}
///@endcond
| 34.406015 | 136 | 0.605551 | [
"geometry",
"vector"
] |
b50733a2302e45e8d240713e5a537fc620061cfe | 7,196 | cpp | C++ | Shared/HoloLensForCV/DeviceReceiver.cpp | nicolas-schreiber/HoloLensForCV | 5aff81c7d9f7e208bac76cb54cb977b8e3b96d57 | [
"MIT"
] | 5 | 2020-03-20T12:10:54.000Z | 2022-03-07T10:33:16.000Z | Shared/HoloLensForCV/DeviceReceiver.cpp | nicolas-schreiber/HoloLensForCV | 5aff81c7d9f7e208bac76cb54cb977b8e3b96d57 | [
"MIT"
] | null | null | null | Shared/HoloLensForCV/DeviceReceiver.cpp | nicolas-schreiber/HoloLensForCV | 5aff81c7d9f7e208bac76cb54cb977b8e3b96d57 | [
"MIT"
] | 6 | 2020-05-20T16:53:38.000Z | 2022-03-07T10:32:57.000Z | #include "pch.h"
#include "DeviceReceiver.h"
using namespace Windows::Foundation::Collections;
namespace HoloLensForCV
{
DeviceReceiver::DeviceReceiver(
_In_ Windows::Networking::Sockets::StreamSocket^ streamSocket)
: _streamSocket(streamSocket)
{
_reader = ref new Windows::Storage::Streams::DataReader(
_streamSocket->InputStream);
_reader->UnicodeEncoding =
Windows::Storage::Streams::UnicodeEncoding::Utf8;
_reader->ByteOrder =
Windows::Storage::Streams::ByteOrder::LittleEndian;
dbg::trace(L"DeviceReceiver::DeviceReceiver: created data reader.");
}
Concurrency::task<DesktopStreamerHeader^>
DeviceReceiver::ReceiveDataHeaderAsync()
{
return concurrency::create_task(
_reader->LoadAsync(
DesktopStreamerHeader::ProtocolHeaderLength)
).then([this](concurrency::task<unsigned int> headerBytesLoadedTaskResult)
{
//
// Make sure that we have received exactly the number of bytes we have
// asked for. Doing so will also implicitly check for the possible exceptions
// that could have been thrown in the async call chain.
//
const uint32_t headerBytesLoaded = headerBytesLoadedTaskResult.get();
if (DesktopStreamerHeader::ProtocolHeaderLength != headerBytesLoaded)
{
dbg::trace(
L"DeviceReceiver::ReceiveDataHeaderAsync: expected data of size %i bytes, got %i bytes",
DesktopStreamerHeader::ProtocolHeaderLength,
headerBytesLoaded);
throw ref new Platform::FailureException();
}
DesktopStreamerHeader^ header;
DesktopStreamerHeader::Read(
_reader,
&header);
dbg::trace(
L"DeviceReceiver::ReceiveAsync: seeing %i bounding boxes of size %i",
header->NumberOfBoxes,
header->BoxSize);
return header;
});
}
//Concurrency::task<Windows::Foundation::Collections::IVector<YoloRuntime::BoundingBox^>^>
Concurrency::task<IVector<uint8_t>^>
DeviceReceiver::ReceiveDataAsync(DesktopStreamerHeader^ header)
{
return concurrency::create_task(
_reader->LoadAsync(
// uint8_t size = 1
header->BoxSize * header->NumberOfBoxes * sizeof(uint8_t))).
then([this, header](concurrency::task<unsigned int> bytesLoadedTaskResult)
{
//
// Make sure that we have received exactly the number of bytes we have
// asked for. Doing so will also implicitly check for the possible exceptions
// that could have been thrown in the async call chain.
//
const size_t bytesLoaded = bytesLoadedTaskResult.get();
if (header->BoxSize * header->NumberOfBoxes != bytesLoaded)
{
dbg::trace(
L"DeviceReceiver::ReceiveDataAsync: expected data of %i bytes, got %i bytes",
header->BoxSize * header->NumberOfBoxes,
bytesLoaded);
throw ref new Platform::FailureException();
}
// Iterate across input vector and fill bounding box struct
int numBoxes = (int)header->NumberOfBoxes;
int boxSize = (int)header->BoxSize;
// Read from incoming stream writer to data buffer array
// of same size as input data (allocate the memory)
// https://github.com/microsoft/Windows-universal-samples/blob/master/Samples/DataReaderWriter/cpp/Scenario2_ReadBytes.xaml.cpp
// Getting null data from stream
Platform::Array<uint8_t>^ data = ref new Platform::Array<uint8_t>(numBoxes * boxSize);
_reader->ReadBytes(data);
dbg::trace(L"DeviceReceiver::ReceiveDataAsync: read in data stream, found %i bounding box(es) and data of size %i.",
header->NumberOfBoxes,
data->Length);
// Process the data to create bounding boxes in C# environment
//https://social.msdn.microsoft.com/Forums/vstudio/en-US/6b2525c3-5da2-4899-8b75-64b218234ea6/how-to-return-array-using-iasyncoperation-in-winrt?forum=wpdevelop
IVector<uint8_t>^ dataVec =
ref new Platform::Collections::Vector<uint8_t>(data->Data, data->Length);
return dataVec;
});
}
//Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVector<YoloRuntime::BoundingBox^>^>^
Windows::Foundation::IAsyncOperation<IVector<uint8_t>^>^
DeviceReceiver::ReceiveAsync()
{
return concurrency::create_async(
[this]()
{
return ReceiveDataHeaderAsync().then(
[this](concurrency::task<DesktopStreamerHeader^> header)
{;
return ReceiveDataAsync(header.get());
});
});
}
// Helper method to get vector data from buffer stream
std::vector<uint8_t> DeviceReceiver::GetData(
Windows::Storage::Streams::IBuffer^ buf)
{
auto reader = ::Windows::Storage::Streams::DataReader::FromBuffer(buf);
std::vector<uint8_t> data(reader->UnconsumedBufferLength);
if (!data.empty())
reader->ReadBytes(
::Platform::ArrayReference<unsigned char>(
&data[0], (unsigned int)data.size()));
return data;
}
void InteropDeviceReceiver::ReceiverLoop(
DeviceReceiver^ receiver)
{
dbg::trace(
L"InteropDeviceReceiver::ReceiverLoop: creating receive task");
concurrency::create_task(
receiver->ReceiveAsync()).then(
[this, receiver](
concurrency::task<IVector<uint8_t>^>
dataTask)
{
float boxSize = 6.0f;
// Receive object
IVector<uint8_t>^ data =
dataTask.get();
dbg::trace(
L"InteropDeviceReceiver::ReceiverLoop: receiving %i boxes",
(int)(data->Size / boxSize));
// Cache the results for access in c# env
_dataVector = data;
ReceiverLoop(
receiver);
});
}
// Expose the bounding box information to c# client
IVector<uint8_t>^
InteropDeviceReceiver::GetBoundingBoxResults()
{
return _dataVector;
}
void InteropDeviceReceiver::ConnectSocket_Click(
Platform::String^ ipAddress,
Platform::String^ hostId)
{
_dataVector = ref new Platform::Collections::Vector<uint8_t>();
//
// By default 'HostNameForConnect' is disabled and host name validation is not required. When enabling the
// text box validating the host name is required since it was received from an untrusted source
// (user input). The host name is validated by catching ArgumentExceptions thrown by the HostName
// constructor for invalid input.
//
Windows::Networking::HostName^ hostName;
try
{
hostName = ref new Windows::Networking::HostName(ipAddress);
}
catch (Platform::Exception^)
{
return;
}
Windows::Networking::Sockets::StreamSocket^ dataSocket =
ref new Windows::Networking::Sockets::StreamSocket();
dataSocket->Control->KeepAlive = true;
#if DBG_ENABLE_INFORMATIONAL_LOGGING
dbg::trace(
L"DeviceReceiver::ConnectSocket_Click: data sender created");
#endif /* DBG_ENABLE_INFORMATIONAL_LOGGING */
//
// Save the socket, so subsequent steps can use it.
//
concurrency::create_task(
dataSocket->ConnectAsync(hostName, hostId)
).then(
[this, dataSocket]()
{
#if DBG_ENABLE_INFORMATIONAL_LOGGING
dbg::trace(
L"DeviceReceiver::ConnectSocket_Click: server connection established");
#endif /* DBG_ENABLE_INFORMATIONAL_LOGGING */
_receiver = ref new HoloLensForCV::DeviceReceiver(
dataSocket);
ReceiverLoop(
_receiver);
});
}
} | 30.491525 | 164 | 0.697749 | [
"object",
"vector"
] |
b51217d56609cd54d761049decc083e14b7858be | 730 | cpp | C++ | AtCoder/arc021/a/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | AtCoder/arc021/a/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | 1 | 2021-10-19T08:47:23.000Z | 2022-03-07T05:23:56.000Z | AtCoder/arc021/a/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, -1, 0, 1};
int main() {
vector<vector<int>> v(4, vector<int>(4, 0));
for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) cin >> v[i][j];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 4; k++) {
int nx = j + dx[k], ny = i + dy[k];
if (0 <= nx && nx <= 3 && 0 <= ny && ny <= 3 &&
v[ny][nx] == v[i][j]) {
cout << "CONTINUE" << endl;
return 0;
}
}
}
}
cout << "GAMEOVER" << endl;
return 0;
} | 30.416667 | 75 | 0.365753 | [
"vector"
] |
b514f84e34de5e2379c08d7088b30975520104e5 | 12,080 | cpp | C++ | user/duo.cpp | techno-cat/logue-user-osc-duo | 058ae44c5bf9b37323cabcff1119451088e35992 | [
"MIT"
] | 2 | 2020-05-13T14:32:24.000Z | 2020-10-07T18:46:43.000Z | user/duo.cpp | techno-cat/logue-user-osc-duo | 058ae44c5bf9b37323cabcff1119451088e35992 | [
"MIT"
] | null | null | null | user/duo.cpp | techno-cat/logue-user-osc-duo | 058ae44c5bf9b37323cabcff1119451088e35992 | [
"MIT"
] | 1 | 2020-05-13T14:32:26.000Z | 2020-05-13T14:32:26.000Z | /*
Copyright 2019 Tomoaki Itoh
This software is released under the MIT License, see LICENSE.txt.
//*/
#include "userosc.h"
#include "LCWPitchTable.h"
#include "LCWAntiAliasingTable.h"
#include "LCWOscWaveSource.h"
#include "LCWClipCurveTable.h"
#define LCW_OSC_TIMER_BITS (LCW_PITCH_DELTA_VALUE_BITS)
#define LCW_OSC_TIMER_MAX (1 << LCW_OSC_TIMER_BITS)
#define LCW_OSC_TIMER_MASK ((LCW_OSC_TIMER_MAX) - 1)
#define LCW_OSC_FRAC_BITS (LCW_OSC_TIMER_BITS - LCW_OSC_TABLE_BITS)
#define LCW_OSC_FRAC_MAX (1 << LCW_OSC_FRAC_BITS)
#define LCW_OSC_FRAC_MASK ((LCW_OSC_FRAC_MAX) - 1)
#define LCW_PORTA_TABLE_SIZE (101)
// s7.24
static const int32_t portaTable[LCW_PORTA_TABLE_SIZE] = {
0x008C8C2D, // [ 0] 0.549014, 0.0002(sec), n: 11
0x00CC0BE8, // [ 1] 0.797057, 0.0006(sec), n: 30
0x00DBFAB5, // [ 2] 0.859294, 0.0009(sec), n: 45
0x00E506F4, // [ 3] 0.894637, 0.0013(sec), n: 62
0x00EAF328, // [ 4] 0.917773, 0.0017(sec), n: 80
0x00EF1ED1, // [ 5] 0.934064, 0.0021(sec), n: 101
0x00F2322B, // [ 6] 0.946078, 0.0026(sec), n: 124
0x00F48A00, // [ 7] 0.955231, 0.0031(sec), n: 150
0x00F65E47, // [ 8] 0.962376, 0.0038(sec), n: 180
0x00F7D2F2, // [ 9] 0.968063, 0.0044(sec), n: 212
0x00F90030, // [ 10] 0.972659, 0.0052(sec), n: 249
0x00F9F6DF, // [ 11] 0.976423, 0.0060(sec), n: 289
0x00FAC31D, // [ 12] 0.979540, 0.0070(sec), n: 334
0x00FB6DD5, // [ 13] 0.982145, 0.0080(sec), n: 383
0x00FBFDB6, // [ 14] 0.984340, 0.0091(sec), n: 437
0x00FC77DC, // [ 15] 0.986204, 0.0104(sec), n: 497
0x00FCE03D, // [ 16] 0.987797, 0.0117(sec), n: 562
0x00FD39F4, // [ 17] 0.989166, 0.0132(sec), n: 634
0x00FD8778, // [ 18] 0.990348, 0.0148(sec), n: 712
0x00FDCAC6, // [ 19] 0.991375, 0.0166(sec), n: 797
0x00FE0576, // [ 20] 0.992271, 0.0185(sec), n: 890
0x00FE38D9, // [ 21] 0.993055, 0.0206(sec), n: 991
0x00FE6601, // [ 22] 0.993744, 0.0229(sec), n: 1100
0x00FE8DD3, // [ 23] 0.994352, 0.0254(sec), n: 1219
0x00FEB10D, // [ 24] 0.994889, 0.0281(sec), n: 1348
0x00FED04F, // [ 25] 0.995366, 0.0310(sec), n: 1487
0x00FEEC1F, // [ 26] 0.995790, 0.0341(sec), n: 1637
0x00FF04EE, // [ 27] 0.996169, 0.0375(sec), n: 1799
0x00FF1B1E, // [ 28] 0.996508, 0.0411(sec), n: 1974
0x00FF2F01, // [ 29] 0.996811, 0.0451(sec), n: 2162
0x00FF40DF, // [ 30] 0.997084, 0.0493(sec), n: 2365
0x00FF50F4, // [ 31] 0.997329, 0.0538(sec), n: 2582
0x00FF5F75, // [ 32] 0.997550, 0.0587(sec), n: 2816
0x00FF6C90, // [ 33] 0.997750, 0.0639(sec), n: 3067
0x00FF786D, // [ 34] 0.997931, 0.0695(sec), n: 3335
0x00FF832F, // [ 35] 0.998095, 0.0755(sec), n: 3623
0x00FF8CF4, // [ 36] 0.998245, 0.0819(sec), n: 3931
0x00FF95D7, // [ 37] 0.998380, 0.0888(sec), n: 4260
0x00FF9DEF, // [ 38] 0.998504, 0.0961(sec), n: 4612
0x00FFA551, // [ 39] 0.998616, 0.1039(sec), n: 4988
0x00FFAC10, // [ 40] 0.998719, 0.1123(sec), n: 5389
0x00FFB23B, // [ 41] 0.998813, 0.1212(sec), n: 5817
0x00FFB7E1, // [ 42] 0.998900, 0.1307(sec), n: 6273
0x00FFBD0F, // [ 43] 0.998979, 0.1408(sec), n: 6759
0x00FFC1D0, // [ 44] 0.999051, 0.1516(sec), n: 7276
0x00FFC62E, // [ 45] 0.999118, 0.1630(sec), n: 7826
0x00FFCA33, // [ 46] 0.999179, 0.1752(sec), n: 8411
0x00FFCDE6, // [ 47] 0.999236, 0.1882(sec), n: 9032
0x00FFD14F, // [ 48] 0.999288, 0.2019(sec), n: 9692
0x00FFD475, // [ 49] 0.999336, 0.2165(sec), n: 10393
0x00FFD75D, // [ 50] 0.999380, 0.2320(sec), n: 11136
0x00FFDA0C, // [ 51] 0.999421, 0.2484(sec), n: 11924
0x00FFDC88, // [ 52] 0.999459, 0.2658(sec), n: 12760
0x00FFDED5, // [ 53] 0.999494, 0.2843(sec), n: 13645
0x00FFE0F7, // [ 54] 0.999526, 0.3038(sec), n: 14583
0x00FFE2F1, // [ 55] 0.999557, 0.3245(sec), n: 15576
0x00FFE4C7, // [ 56] 0.999585, 0.3464(sec), n: 16626
0x00FFE67B, // [ 57] 0.999611, 0.3695(sec), n: 17736
0x00FFE811, // [ 58] 0.999635, 0.3940(sec), n: 18911
0x00FFE98A, // [ 59] 0.999657, 0.4198(sec), n: 20151
0x00FFEAE9, // [ 60] 0.999678, 0.4471(sec), n: 21462
0x00FFEC30, // [ 61] 0.999698, 0.4760(sec), n: 22846
0x00FFED61, // [ 62] 0.999716, 0.5064(sec), n: 24307
0x00FFEE7D, // [ 63] 0.999733, 0.5385(sec), n: 25848
0x00FFEF86, // [ 64] 0.999749, 0.5724(sec), n: 27474
0x00FFF07E, // [ 65] 0.999763, 0.6081(sec), n: 29188
0x00FFF165, // [ 66] 0.999777, 0.6457(sec), n: 30995
0x00FFF23E, // [ 67] 0.999790, 0.6854(sec), n: 32899
0x00FFF308, // [ 68] 0.999802, 0.7272(sec), n: 34904
0x00FFF3C5, // [ 69] 0.999813, 0.7712(sec), n: 37015
0x00FFF477, // [ 70] 0.999824, 0.8175(sec), n: 39237
0x00FFF51D, // [ 71] 0.999834, 0.8662(sec), n: 41576
0x00FFF5B8, // [ 72] 0.999843, 0.9174(sec), n: 44036
0x00FFF64A, // [ 73] 0.999852, 0.9713(sec), n: 46623
0x00FFF6D3, // [ 74] 0.999860, 1.0280(sec), n: 49342
0x00FFF754, // [ 75] 0.999868, 1.0875(sec), n: 52201
0x00FFF7CD, // [ 76] 0.999875, 1.1501(sec), n: 55204
0x00FFF83E, // [ 77] 0.999882, 1.2158(sec), n: 58359
0x00FFF8A9, // [ 78] 0.999888, 1.2848(sec), n: 61672
0x00FFF90D, // [ 79] 0.999894, 1.3573(sec), n: 65149
0x00FFF96C, // [ 80] 0.999900, 1.4333(sec), n: 68800
0x00FFF9C4, // [ 81] 0.999905, 1.5131(sec), n: 72630
0x00FFFA18, // [ 82] 0.999910, 1.5968(sec), n: 76647
0x00FFFA67, // [ 83] 0.999915, 1.6846(sec), n: 80861
0x00FFFAB1, // [ 84] 0.999919, 1.7766(sec), n: 85278
0x00FFFAF7, // [ 85] 0.999923, 1.8731(sec), n: 89909
0x00FFFB39, // [ 86] 0.999927, 1.9742(sec), n: 94761
0x00FFFB77, // [ 87] 0.999931, 2.0801(sec), n: 99846
0x00FFFBB2, // [ 88] 0.999934, 2.1911(sec), n:105171
0x00FFFBEA, // [ 89] 0.999938, 2.3073(sec), n:110748
0x00FFFC1E, // [ 90] 0.999941, 2.4289(sec), n:116586
0x00FFFC4F, // [ 91] 0.999944, 2.5562(sec), n:122698
0x00FFFC7E, // [ 92] 0.999946, 2.6895(sec), n:129094
0x00FFFCAB, // [ 93] 0.999949, 2.8289(sec), n:135786
0x00FFFCD4, // [ 94] 0.999952, 2.9747(sec), n:142786
0x00FFFCFC, // [ 95] 0.999954, 3.1272(sec), n:150107
0x00FFFD21, // [ 96] 0.999956, 3.2867(sec), n:157762
0x00FFFD45, // [ 97] 0.999958, 3.4534(sec), n:165764
0x00FFFD66, // [ 98] 0.999960, 3.6277(sec), n:174128
0x00FFFD86, // [ 99] 0.999962, 3.8098(sec), n:182868
0x00FFFDA4 // [100] 0.999964, 4.0000(sec), n:192000
};
static struct {
int16_t shape = 0; // = shape, [-0x400 .. +0x400]
uint16_t mixRatio = 0; // = shiftshape, [0 .. 0x400]
uint16_t wave = 0; // [0 .. 2]
int16_t note = 0; // [-24 .. +24]
uint16_t portament = 0; // [0 .. 100]
} s_param;
static struct {
uint32_t timer1 = 0;
uint32_t timer2 = 0;
int32_t pitch1 = 0; // s7.24
int32_t pitch2 = 0; // s7.24
int32_t shape_lfo = 0;
} s_state;
static const LCWOscWaveSource *s_waveSources[] = {
&gLcwOscTriSource,
&gLcwOscPulseSource,
&gLcwOscSawSource
};
// return s5.10
__fast_inline int16_t param_val_to_q10(uint16_t val)
{
float valf = param_val_to_f32(val);
valf = (valf <= 0.49f) ? 1.02040816326530612244f * valf : (valf >= 0.51f) ? 0.5f + 1.02f * (valf-0.51f) : 0.5f;
return (int16_t)(0x800 * clip01f(valf)) - 0x400;
}
// return s15.16
__fast_inline int32_t myLookUp(
int32_t t, int32_t dt, const LCWOscWaveSource *src)
{
// 桁溢れ対策として、q16に変換
uint32_t dt0 = dt >> (LCW_OSC_TIMER_BITS - 16);
int32_t tmp[] = { 0, 0 };
for (int32_t i=0; i<src->count; i++) {
const int16_t *p = src->tables[i];
// AAテーブルはdt=0.5までしか定義されていない
uint32_t j = (dt0 * src->factors[i]) >> (16 - (LCW_AA_TABLE_BITS + 1));
if ( (uint32_t)LCW_AA_TABLE_SIZE <= j ) {
break;
}
int32_t gain = gLcwAntiAiliasingTable[j];
uint32_t t0 = t >> LCW_OSC_FRAC_BITS;
uint32_t t1 = (t0 + 1) & LCW_OSC_TABLE_MASK;
// s15.16
tmp[0] += ( (p[t0] * gain) >> (14 + LCW_AA_VALUE_BITS - 16) );
tmp[1] += ( (p[t1] * gain) >> (14 + LCW_AA_VALUE_BITS - 16) );
}
// 端数14bitで補間
const int32_t diff = tmp[1] - tmp[0];
int32_t delta = (t & LCW_OSC_FRAC_MASK) >> (LCW_OSC_FRAC_BITS - 14);
return tmp[0] + ((diff * delta) >> 14);
}
// inout/dst s7.24
// factor s7.24
__fast_inline void convergePitch(
int32_t *inout, int32_t dst, int32_t portaParam)
{
int32_t diff = dst - *inout;
if ( diff < 0 ) {
*inout = dst + (int32_t)( ((int64_t)-diff * portaParam) >> 24 );
}
else {
*inout = dst - (int32_t)( ((int64_t)diff * portaParam) >> 24 );
}
}
// in/return : s7.24
__fast_inline int32_t lookupClipCurve(int32_t x)
{
const int32_t x2 = ( x < 0 ) ? -x : x;
const int32_t i = x2 >> (LCW_CLIP_CURVE_VALUE_BITS - LCW_CLIP_CURVE_FRAC_BITS);
int32_t ret;
if ( i < (LCW_CLIP_CURVE_TABLE_SIZE - 1) ) {
const uint32_t frac = (uint32_t)x2 & (0x00FFFFFF >> LCW_CLIP_CURVE_VALUE_BITS);
const int32_t val = gLcwClipCurveTable[i];
const int32_t diff = gLcwClipCurveTable[i+1] - val;
const int64_t tmp = (int64_t)frac * diff;
ret = val + (tmp >> (LCW_CLIP_CURVE_VALUE_BITS - LCW_CLIP_CURVE_FRAC_BITS));
}
else {
ret = gLcwClipCurveTable[LCW_CLIP_CURVE_TABLE_SIZE - 1];
}
return ( x < 0 ) ? -ret : ret;
}
void OSC_INIT(uint32_t platform, uint32_t api)
{
s_param.shape = 0;
s_param.mixRatio = 0;
s_param.wave = 0;
s_state.timer1 = 0;
s_state.timer2 = 0;
s_state.pitch1 =
s_state.pitch2 = (LCW_NOTE_NO_A4 << 24) / 12;
s_state.shape_lfo = 0;
}
#define LCW_PITCH_DETUNE_RANGE ((1 << 20) / 18) // memo: 50centだと物足りない
void OSC_CYCLE(const user_osc_param_t * const params,
int32_t *yn,
const uint32_t frames)
{
// s11.20に拡張してから、整数部がoctaveになるように加工
int32_t pitch = (int32_t)params->pitch << 12;
pitch = (pitch - (LCW_NOTE_NO_A4 << 20)) / 12;
int32_t detune = ((int32_t)s_param.shape * LCW_PITCH_DETUNE_RANGE) >> 10;
detune += ((int32_t)s_param.note << 20) / 12;
int32_t lfo_delta = (params->shape_lfo - s_state.shape_lfo) / (int32_t)frames;
// s11.20 -> s7.24
pitch <<= 4;
detune <<= 4;
// Temporaries.
uint32_t t1 = s_state.timer1;
uint32_t t2 = s_state.timer2;
int32_t pitch1 = s_state.pitch1;
int32_t pitch2 = s_state.pitch2;
int32_t shape_lfo = s_state.shape_lfo;
q31_t * __restrict y = (q31_t *)yn;
const q31_t * y_e = y + frames;
// Main Mix/Sub Mix, 8bit(= [0-256])
const int32_t subVol = s_param.mixRatio >> 2;
const int32_t mainVol = clipmaxi32( 0x160 - subVol, 0x100 );
const int32_t portaParam = portaTable[s_param.portament];
const LCWOscWaveSource *src = s_waveSources[s_param.wave];
for (; y != y_e; ) {
// portament
convergePitch(&pitch1, pitch, portaParam);
convergePitch(&pitch2, pitch + detune, portaParam);
// input: s7.24 -> s15.16
const uint32_t dt1 = pitch_to_timer_delta( pitch1 >> 8 );
const uint32_t dt2 = pitch_to_timer_delta( (pitch2 + (shape_lfo >> 8)) >> 8 );
// s15.16 -> s11.20
// x 0.9375(= 15/16)
int32_t out1 = myLookUp(t1, dt1, src) * 15;
int32_t out2 = myLookUp(t2, dt2, src) * 15;
// s11.20 -> s3.28 -> s7.24
int32_t out = (out1 * mainVol) + (out2 * subVol);
out = lookupClipCurve( out >> 4 );
// s7.24 -> q31
*(y++) = (q31_t)(out << (31 - 24));
t1 = (t1 + dt1) & LCW_OSC_TIMER_MASK;
t2 = (t2 + dt2) & LCW_OSC_TIMER_MASK;
shape_lfo += lfo_delta;
}
s_state.timer1 = t1;
s_state.timer2 = t2;
s_state.pitch1 = pitch1;
s_state.pitch2 = pitch2;
s_state.shape_lfo = params->shape_lfo;
}
void OSC_NOTEON(const user_osc_param_t * const params)
{
return;
}
void OSC_NOTEOFF(const user_osc_param_t * const params)
{
return;
}
void OSC_PARAM(uint16_t index, uint16_t value)
{
switch (index) {
case k_user_osc_param_shape:
s_param.shape = param_val_to_q10(value);
break;
case k_user_osc_param_shiftshape:
s_param.mixRatio = (uint16_t)clipmaxu32(value, 0x400);
break;
case k_user_osc_param_id1:
s_param.wave = (uint16_t)clipmaxu32(value, 2);
break;
case k_user_osc_param_id2:
s_param.note = (int16_t)clipmaxu32(value, 48) - 24;
break;
case k_user_osc_param_id3:
s_param.portament = (uint16_t)clipmaxu32(value, LCW_PORTA_TABLE_SIZE - 1);
break;
default:
break;
}
}
| 36.059701 | 113 | 0.621772 | [
"shape"
] |
dde79e32f388ae81c711eb419aa47aa00f72c07e | 4,713 | cc | C++ | src/Validation/listSingletonMates.cc | sagrudd/amos | 47643a1d238bff83421892cb74daaf6fff8d9548 | [
"Artistic-1.0"
] | 10 | 2015-03-20T18:25:56.000Z | 2020-06-02T22:00:08.000Z | src/Validation/listSingletonMates.cc | sagrudd/amos | 47643a1d238bff83421892cb74daaf6fff8d9548 | [
"Artistic-1.0"
] | 5 | 2015-05-14T17:51:20.000Z | 2020-07-19T04:17:47.000Z | src/Validation/listSingletonMates.cc | sagrudd/amos | 47643a1d238bff83421892cb74daaf6fff8d9548 | [
"Artistic-1.0"
] | 10 | 2015-05-17T16:01:23.000Z | 2020-05-20T08:13:43.000Z | #include "foundation_AMOS.hh"
#include <iostream>
#include <cassert>
#include <unistd.h>
#include <map>
#include <cmath>
#include "DataStore.hh"
#include "Insert.hh"
#include "InsertStats.hh"
using namespace std;
using namespace AMOS;
typedef HASHMAP::hash_map<ID_t, Tile_t *> SeqTileMap_t;
int FRAGMENTSTRLEN = 3;
int m_verbose = 0;
DataStore * m_datastore;
int m_connectMates = 1;
typedef std::vector<Insert *> InsertList_t;
InsertList_t m_inserts;
//=============================================================== Globals ====//
string OPT_BankName; // bank name parameter
bool OPT_BankSpy = false; // read or read-only spy
//========================================================== Fuction Decs ====//
//----------------------------------------------------- ParseArgs --------------
//! \brief Sets the global OPT_% values from the command line arguments
//!
//! \return void
//!
void ParseArgs (int argc, char ** argv);
//----------------------------------------------------- PrintHelp --------------
//! \brief Prints help information to cerr
//!
//! \param s The program name, i.e. argv[0]
//! \return void
//!
void PrintHelp (const char * s);
//----------------------------------------------------- PrintUsage -------------
//! \brief Prints usage information to cerr
//!
//! \param s The program name, i.e. argv[0]
//! \return void
//!
void PrintUsage (const char * s);
void processInserts()
{
map <string, InsertStats *>::iterator fi;
vector<Insert *>::iterator i;
for (i = m_inserts.begin();
i != m_inserts.end();
i++)
{
if ((*i)->m_state == Insert::SingletonMate || (*i)->m_state == Insert::LinkingMate)
{
cout << (*i)->m_acontig << " "
<< m_datastore->read_bank.lookupEID((*i)->m_aid) << " "
<< m_datastore->read_bank.lookupEID((*i)->m_bid) << " "
<< (char)(*i)->m_state << endl;
}
delete (*i);
}
m_inserts.clear();
}
//========================================================= Function Defs ====//
int main (int argc, char ** argv)
{
int exitcode = EXIT_SUCCESS;
Read_t red;
Fragment_t frg;
Library_t lib;
Scaffold_t scaff;
Contig_t contig;
//-- Parse the command line arguments
ParseArgs (argc, argv);
//-- BEGIN: MAIN EXCEPTION CATCH
try {
m_datastore = new DataStore();
m_datastore->openBank(OPT_BankName);
map <string, InsertStats *>::iterator fi;
if (m_datastore->scaffold_bank.isOpen())
{
cerr << "Processing scaffolds... ";
m_datastore->scaffold_bank.seekg(1);
while (m_datastore->scaffold_bank >> scaff)
{
vector <Tile_t> rtiling;
m_datastore->mapReadsToScaffold(scaff, rtiling, 1);
m_datastore->calculateInserts(rtiling, m_inserts, m_connectMates, 1);
processInserts();
}
}
else
{
cerr << "Processing contigs... ";
m_datastore->contig_bank.seekg(1);
while (m_datastore->contig_bank >> contig)
{
m_datastore->calculateInserts(contig.getReadTiling(), m_inserts, m_connectMates, 1);
processInserts();
}
}
}
catch (const Exception_t & e) {
cerr << "FATAL: " << e . what( ) << endl
<< " there has been a fatal error, abort" << endl;
exitcode = EXIT_FAILURE;
}
//-- END: MAIN EXCEPTION CATCH
return exitcode;
}
//------------------------------------------------------------- ParseArgs ----//
void ParseArgs (int argc, char ** argv)
{
int ch, errflg = 0;
optarg = NULL;
while ( !errflg && ((ch = getopt (argc, argv, "hsdvf:")) != EOF) )
switch (ch)
{
case 'h': PrintHelp (argv[0]); exit (EXIT_SUCCESS); break;
case 's': OPT_BankSpy = true; break;
case 'v': PrintBankVersion (argv[0]); exit (EXIT_SUCCESS); break;
default:
errflg ++;
}
if (errflg > 0 || optind != argc - 1)
{
PrintUsage (argv[0]);
cerr << "Try '" << argv[0] << " -h' for more information.\n";
exit (EXIT_FAILURE);
}
OPT_BankName = argv [optind ++];
}
//------------------------------------------------------------- PrintHelp ----//
void PrintHelp (const char * s)
{
PrintUsage (s);
cerr
<< "Output:\n"
<< "contigiid placedread missingmate type\n"
<< "\n"
<< "Options:\n"
<< "-h Display help information\n"
<< "-s Disregard bank locks and write permissions (spy mode)\n"
<< "-v Display the compatible bank version\n"
<< endl;
return;
}
//------------------------------------------------------------ PrintUsage ----//
void PrintUsage (const char * s)
{
cerr
<< "\nUSAGE: " << s << " [options] <bank path>\n\n";
return;
}
| 22.990244 | 92 | 0.520475 | [
"vector"
] |
ddebe76ef4a5952803a48d87e97a74779915224c | 53,294 | cpp | C++ | sdl1/cannonball/src/main/engine/oferrari.cpp | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | sdl1/cannonball/src/main/engine/oferrari.cpp | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | sdl1/cannonball/src/main/engine/oferrari.cpp | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | /***************************************************************************
Ferrari Rendering & Handling Code.
Much of the handling code is very messy. As such, the translated code
isn't great as I tried to focus on accuracy rather than refactoring.
A good example of the randomness is a routine I've named
do_sound_score_slip()
which performs everything from updating the score, setting the audio
engine tone, triggering smoke effects etc. in an interwoven fashion.
The Ferrari sprite has different properties to other game objects
As there's only one of them, I've rolled the additional variables into
this class.
Copyright Chris White.
See license.txt for more details.
***************************************************************************/
#include "engine/oanimseq.hpp"
#include "engine/oattractai.hpp"
#include "engine/obonus.hpp"
#include "engine/ocrash.hpp"
#include "engine/ohud.hpp"
#include "engine/oinputs.hpp"
#include "engine/olevelobjs.hpp"
#include "engine/ooutputs.hpp"
#include "engine/ostats.hpp"
#include "engine/outils.hpp"
#include "engine/oferrari.hpp"
OFerrari oferrari;
OFerrari::OFerrari(void)
{
}
OFerrari::~OFerrari(void)
{
}
void OFerrari::init(oentry *f, oentry *p1, oentry *p2, oentry *s)
{
state = FERRARI_SEQ1;
spr_ferrari = f;
spr_pass1 = p1;
spr_pass2 = p2;
spr_shadow = s;
spr_ferrari->control |= OSprites::ENABLE;
spr_pass1->control |= OSprites::ENABLE;
spr_pass2->control |= OSprites::ENABLE;
spr_shadow->control |= OSprites::ENABLE;
state = 0;
counter = 0;
steering_old = 0;
road_width_old = 0;
car_state = CAR_NORMAL;
auto_brake = false;
torque_index = 0;
torque = 0;
revs = 0;
rev_shift = 0;
wheel_state = WHEELS_ON;
wheel_traction = TRACTION_ON;
is_slipping = 0;
slip_sound = 0;
car_inc_old = 0;
car_x_diff = 0;
rev_stop_flag = 0;
revs_post_stop = 0;
acc_post_stop = 0;
rev_pitch1 = 0;
rev_pitch2 = 0;
sprite_ai_counter = 0;
sprite_ai_curve = 0;
sprite_ai_x = 0;
sprite_ai_steer = 0;
sprite_car_x_bak = 0;
sprite_wheel_state= 0;
sprite_slip_copy = 0;
wheel_pal = 0;
sprite_pass_y = 0;
wheel_frame_reset = 0;
wheel_counter = 0;
road_width_old = 0;
accel_value = 0;
accel_value_bak = 0;
brake_value = 0;
gear_value = false;
gear_bak = false;
brake_subtract = 0;
gear_counter = 0;
rev_adjust = 0;
gear_smoke = 0;
gfx_smoke = 0;
cornering = 0;
cornering_old = 0;
car_ctrl_active = true;
}
// Reset all values relating to car speed, revs etc.
// Source: 0x61F2
void OFerrari::reset_car()
{
rev_shift = 1; // Set normal rev shift value
ocrash.spin_control2 = 0;
revs = 0;
oinitengine.car_increment = 0;
gear_value = 0;
gear_bak = 0;
rev_adjust = 0;
car_inc_old = 0;
torque = 0x1000;
torque_index = 0x1F;
rev_stop_flag = 0;
oinitengine.ingame_engine = false;
oinitengine.ingame_counter = 0x1E; // Set ingame counter (time until we hand control to user)
slip_sound = sound::STOP_SLIP;
acc_adjust1 =
acc_adjust2 =
acc_adjust3 = 0;
brake_adjust1 =
brake_adjust2 =
brake_adjust3 = 0;
auto_brake = false;
counter = 0;
is_slipping = 0; // Denote not slipping/skidding
}
void OFerrari::tick()
{
switch (state)
{
case FERRARI_SEQ1:
oanimseq.ferrari_seq();
oanimseq.anim_seq_intro(&oanimseq.anim_pass1);
oanimseq.anim_seq_intro(&oanimseq.anim_pass2);
break;
case FERRARI_SEQ2:
oanimseq.anim_seq_intro(&oanimseq.anim_ferrari);
oanimseq.anim_seq_intro(&oanimseq.anim_pass1);
oanimseq.anim_seq_intro(&oanimseq.anim_pass2);
break;
case FERRARI_INIT:
if (spr_ferrari->control & OSprites::ENABLE)
if (outrun.tick_frame)
init_ingame();
break;
case FERRARI_LOGIC:
if (spr_ferrari->control & OSprites::ENABLE)
{
if (outrun.tick_frame)
logic();
else
draw_sprite(spr_ferrari);
}
if (spr_pass1->control & OSprites::ENABLE)
{
if (outrun.tick_frame)
set_passenger_sprite(spr_pass1);
else
draw_sprite(spr_pass1);
}
if (spr_pass2->control & OSprites::ENABLE)
{
if (outrun.tick_frame)
set_passenger_sprite(spr_pass2);
else
draw_sprite(spr_pass2);
}
break;
// Ferrari End Sequence Logic
case FERRARI_END_SEQ:
oanimseq.tick_end_seq();
break;
}
}
// Initalize Ferrari Start Sequence
//
// Source: 6036
//
// Note the remainder of this block is handled in oanimseq.ferrari_seq
void OFerrari::init_ingame()
{
// turn_off:
car_state = CAR_NORMAL;
state = FERRARI_LOGIC;
spr_ferrari->reload = 0;
spr_ferrari->counter = 0;
sprite_ai_counter = 0;
sprite_ai_curve = 0;
sprite_ai_x = 0;
sprite_ai_steer = 0;
sprite_car_x_bak = 0;
sprite_wheel_state = 0;
// Passengers
// move.l #SetPassengerSprite,$42(a5)
spr_pass1->reload = 0;
spr_pass1->counter = 0;
spr_pass1->xw1 = 0;
// move.l #SetPassengerSprite,$82(a5)
spr_pass2->reload = 0;
spr_pass2->counter = 0;
spr_pass2->xw1 = 0;
}
// Source: 9C84
void OFerrari::logic()
{
switch (obonus.bonus_control)
{
// Not Bonus Mode
case OBonus::BONUS_DISABLE:
ferrari_normal();
break;
case OBonus::BONUS_INIT:
rev_shift = 2; // Set Double Rev Shift Value
obonus.bonus_control = OBonus::BONUS_TICK;
case OBonus::BONUS_TICK:
oattractai.check_road_bonus();
oattractai.set_steering_bonus();
// Accelerate Car
if (oinitengine.rd_split_state == 0 || (oroad.road_pos >> 16) <= 0x163)
{
oinputs.acc_adjust = 0xFF;
oinputs.brake_adjust = 0;
setup_ferrari_bonus_sprite();
return;
}
else // init_end_anim
{
rev_shift = 1;
obonus.bonus_control = OBonus::BONUS_SEQ0;
// note fall through!
}
case OBonus::BONUS_SEQ0:
if ((oroad.road_pos >> 16) < 0x18E)
{
init_end_seq();
return;
}
obonus.bonus_control = OBonus::BONUS_SEQ1;
// fall through
case OBonus::BONUS_SEQ1:
if ((oroad.road_pos >> 16) < 0x18F)
{
init_end_seq();
return;
}
obonus.bonus_control = OBonus::BONUS_SEQ2;
case OBonus::BONUS_SEQ2:
if ((oroad.road_pos >> 16) < 0x190)
{
init_end_seq();
return;
}
obonus.bonus_control = OBonus::BONUS_SEQ3;
case OBonus::BONUS_SEQ3:
if ((oroad.road_pos >> 16) < 0x191)
{
init_end_seq();
return;
}
else
{
oferrari.car_ctrl_active = false; // -1
oinitengine.car_increment = 0;
obonus.bonus_control = OBonus::BONUS_END;
}
case OBonus::BONUS_END:
oinputs.acc_adjust = 0;
oinputs.brake_adjust = 0xFF;
do_end_seq();
break;
/*default:
std::cout << "Need to finish OFerrari:logic()" << std::endl;
break;*/
}
}
// Ferrari - Normal Game Logic (Non-Bonus Mode Code)
//
// Source: 0x9CB4
void OFerrari::ferrari_normal()
{
if (FORCE_AI && outrun.game_state == GS_INGAME)
{
oattractai.tick_ai_enhanced();
setup_ferrari_sprite();
return;
}
switch (outrun.game_state)
{
// Attract Mode: Process AI Code and fall through
case GS_INIT:
case GS_ATTRACT:
if (config.engine.new_attract)
oattractai.tick_ai_enhanced();
else
oattractai.tick_ai();
setup_ferrari_sprite();
break;
case GS_INIT_BEST1:
case GS_BEST1:
case GS_INIT_LOGO:
case GS_LOGO:
case GS_INIT_GAME:
case GS_INIT_GAMEOVER:
case GS_GAMEOVER:
oinputs.brake_adjust = 0;
case GS_START1:
case GS_START2:
case GS_START3:
oinputs.steering_adjust = 0;
case GS_INGAME:
case GS_INIT_BONUS:
case GS_BONUS:
case GS_INIT_MAP:
case GS_MAP:
setup_ferrari_sprite();
break;
case GS_INIT_MUSIC:
case GS_MUSIC:
return;
/*default:
std::cout << "Need to finish OFerrari:ferrari_normal()" << std::endl;
break;*/
}
}
// Setup Ferrari Sprite Object
//
// Source: 0x9D30
void OFerrari::setup_ferrari_sprite()
{
spr_ferrari->y = 221; // Set Default Ferrari Y
// Test Collision With Other Sprite Object
if (olevelobjs.collision_sprite)
{
if (ocrash.coll_count1 == ocrash.coll_count2)
{
ocrash.coll_count1++;
olevelobjs.collision_sprite = 0;
ocrash.crash_state = 0;
}
}
// Setup Default Ferrari Properties
spr_ferrari->x = 0;
spr_ferrari->zoom = 0x7F;
spr_ferrari->draw_props = oentry::BOTTOM ; // Anchor Bottom
spr_ferrari->shadow = 3;
spr_ferrari->width = 0;
spr_ferrari->priority = spr_ferrari->road_priority = 0x1FD;
// Set Ferrari H-Flip Based On Steering & Speed
int16_t d4 = oinputs.steering_adjust;
// If steering close to centre clear d4 to ignore h-flip of Ferrari
if (d4 >= -8 && d4 <= 7)
d4 = 0;
// If speed to slow clear d4 to ignore h-flip of Ferrari
if (oinitengine.car_increment >> 16 < 0x14)
d4 = 0;
// cont2:
d4 >>= 2; // increase change of being close to zero and no h-flip occurring
int16_t x_off = 0;
// ------------------------------------------------------------------------
// Not Skidding
// ------------------------------------------------------------------------
if (!ocrash.skid_counter)
{
if (d4 >= 0)
spr_ferrari->control &= ~OSprites::HFLIP;
else
spr_ferrari->control |= OSprites::HFLIP;
// 0x9E4E not_skidding:
// Calculate change in road y, so we can determine incline frame for ferrari
int16_t y = oroad.road_y[oroad.road_p0 + (0x3D0 / 2)] - oroad.road_y[oroad.road_p0 + (0x3E0 / 2)];
// Converts y difference to a frame value (this is for when on an incline)
int16_t incline_frame_offset = 0;
if (y >= 0x12) incline_frame_offset += 8;
if (y >= 0x13) incline_frame_offset += 8;
// Get abs version of ferrari turn
int16_t turn_frame_offset = 0;
int16_t d2 = d4;
if (d2 < 0) d2 = -d2;
if (d2 >= 0x12) turn_frame_offset += 0x18;
if (d2 >= 0x1E) turn_frame_offset += 0x18;
// Set Ferrari Sprite Properties
uint32_t offset = outrun.adr.sprite_ferrari_frames + turn_frame_offset + incline_frame_offset;
spr_ferrari->addr = roms.rom0p->read32(offset); // Set Ferrari Frame Address
sprite_pass_y = roms.rom0p->read16(offset + 4); // Set Passenger Y Offset
x_off = roms.rom0p->read16(offset + 6); // Set Ferrari Sprite X Offset
if (d4 < 0) x_off = -x_off;
}
// ------------------------------------------------------------------------
// Skidding
// ------------------------------------------------------------------------
else
{
int16_t skid_counter = ocrash.skid_counter;
if (skid_counter < 0)
{
spr_ferrari->control |= OSprites::HFLIP;
skid_counter = -skid_counter; // Needs to be positive
}
else
spr_ferrari->control &= ~OSprites::HFLIP;
int16_t frame = 0;
if (skid_counter >= 3) frame += 8;
if (skid_counter >= 6) frame += 8;
if (skid_counter >= 12) frame += 8;
// Calculate incline
int16_t y = oroad.road_y[oroad.road_p0 + (0x3D0 / 2)] - oroad.road_y[oroad.road_p0 + (0x3E0 / 2)];
int16_t incline_frame_offset = 0;
if (y >= 0x12) incline_frame_offset += 0x20;
if (y >= 0x13) incline_frame_offset += 0x20;
uint32_t offset = outrun.adr.sprite_skid_frames + frame + incline_frame_offset;
spr_ferrari->addr = roms.rom0p->read32(offset); // Set Ferrari Frame Address
sprite_pass_y = roms.rom0p->read16(offset + 4); // Set Passenger Y Offset
x_off = roms.rom0p->read16(offset + 6); // Set Ferrari Sprite X Offset
wheel_traction = TRACTION_OFF; // Both wheels have lost traction
if (ocrash.skid_counter >= 0) x_off = -x_off;
}
spr_ferrari->x += x_off;
shake();
set_ferrari_palette();
draw_sprite(spr_ferrari);
}
// Bonus Mode: Setup Ferrari Sprite Details
//
// Source: 0xA212
void OFerrari::setup_ferrari_bonus_sprite()
{
// Setup Default Ferrari Properties
spr_ferrari->y = 221;
//spr_ferrari->x = 0; not really needed as set below
spr_ferrari->priority = spr_ferrari->road_priority = 0x1FD;
if (oinputs.steering_adjust > 0)
spr_ferrari->control &= ~OSprites::HFLIP;
else
spr_ferrari->control |= OSprites::HFLIP;
// Get abs version of ferrari turn
int16_t turn_frame_offset = 0;
int16_t d2 = oinputs.steering_adjust >> 2;
if (d2 < 0) d2 = -d2;
if (d2 >= 0x4) turn_frame_offset += 0x18;
if (d2 >= 0x8) turn_frame_offset += 0x18;
// Set Ferrari Sprite Properties
uint32_t offset = outrun.adr.sprite_ferrari_frames + turn_frame_offset + 8; // 8 denotes the 'level' frames, no slope.
spr_ferrari->addr = roms.rom0p->read32(offset); // Set Ferrari Frame Address
sprite_pass_y = roms.rom0p->read16(offset + 4); // Set Passenger Y Offset
int16_t x_off = roms.rom0p->read16(offset + 6); // Set Ferrari Sprite X Offset
if (oinputs.steering_adjust < 0) x_off = -x_off;
spr_ferrari->x = x_off;
set_ferrari_palette();
//osprites.map_palette(spr_ferrari);
//osprites.do_spr_order_shadows(spr_ferrari);
draw_sprite(spr_ferrari);
}
// Source: 0xA1CE
void OFerrari::init_end_seq()
{
// AI for remainder
oattractai.check_road_bonus();
oattractai.set_steering_bonus();
// Brake Car!
oinputs.acc_adjust = 0;
oinputs.brake_adjust = 0xFF;
do_end_seq();
}
// Drive Ferrari to the side during end sequence
//
// Source: 0xA298
void OFerrari::do_end_seq()
{
spr_ferrari->y = 221;
spr_ferrari->priority = spr_ferrari->road_priority = 0x1FD;
// Set Ferrari Frame
// +0 [Long]: Address of frame
// +4 [Byte]: Passenger Offset (always 0!)
// +5 [Byte]: Ferrari X Change
// +6 [Byte]: Sprite Colour Palette
// +7 [Byte]: H-Flip
uint32_t addr = outrun.adr.anim_ferrari_frames + ((obonus.bonus_control - 0xC) << 1);
spr_ferrari->addr = roms.rom0p->read32(addr);
sprite_pass_y = roms.rom0p->read8(4 + addr); // Set Passenger Y Offset
spr_ferrari->x = roms.rom0p->read8(5 + addr);
spr_ferrari->pal_src = roms.rom0p->read8(6 + addr);
spr_ferrari->control = roms.rom0p->read8(7 + addr) | (spr_ferrari->control & 0xFE); // HFlip
osprites.map_palette(spr_ferrari);
osprites.do_spr_order_shadows(spr_ferrari);
}
// - Update Car Palette To Adjust Brake Lamp
// - Also Control Speed at which wheels spin through palette adjustment
//
// Source: 0x9F7C
void OFerrari::set_ferrari_palette()
{
uint8_t pal;
// Denote palette for brake light
if (oinputs.brake_adjust >= OInputs::BRAKE_THRESHOLD1)
{
outrun.outputs->set_digital(OOutputs::D_BRAKE_LAMP);
pal = 2;
}
else
{
outrun.outputs->clear_digital(OOutputs::D_BRAKE_LAMP);
pal = 0;
}
// Car Moving
if (oinitengine.car_increment >> 16 != 0)
{
int16_t car_increment = 5 - (oinitengine.car_increment >> 21);
if (car_increment < 0) car_increment = 0;
wheel_frame_reset = car_increment;
// Increment wheel palette offset (to move wheels)
if (wheel_counter <= 0)
{
wheel_counter = wheel_frame_reset;
wheel_pal++;
}
else
wheel_counter--;
}
spr_ferrari->pal_src = pal + 2 + (wheel_pal & 1);
}
// Set Ferrari X Position
//
// - Reads steering value
// - Converts to a practical change in x position
// - There are a number of special cases, as you will see by looking at the code
//
// In use:
//
// d0 = Amount to adjust car x position by
//
// Source: 0xC1B2
void OFerrari::set_ferrari_x()
{
int16_t steering = oinputs.steering_adjust;
// Hack to reduce the amount you can steer left and right at the start of Stage 1
// The amount you can steer increases as you approach road position 0x7F
if (ostats.cur_stage == 0 && oinitengine.rd_split_state == 0 && (oroad.road_pos >> 16) <= 0x7F)
{
steering = (steering * (oroad.road_pos >> 16)) >> 7;
}
steering -= steering_old;
if (steering > 0x40) steering = 0x40;
else if (steering < -0x40) steering = -0x40;
steering_old += steering;
steering = steering_old;
// This block of code reduces the amount the player
// can steer left and right, when below a particular speed
if (wheel_state == OFerrari::WHEELS_ON && (oinitengine.car_increment >> 16) <= 0x7F)
{
steering = (steering * (oinitengine.car_increment >> 16)) >> 7;
}
// Check Road Curve And Adjust X Value Accordingly
// This effectively makes it harder to steer into sharp corners
int16_t road_curve = oinitengine.road_curve;
if (road_curve)
{
road_curve -= 0x40;
if (road_curve < 0)
{
int16_t diff_from_max = (MAX_SPEED >> 17) - (oinitengine.car_increment >> 16);
if (diff_from_max < 0)
{
int16_t curve = diff_from_max * road_curve;
int32_t result = (int32_t) steering * (0x24C0 - curve);
steering = result / 0x24C0;
}
}
}
steering >>= 3;
int16_t steering2 = steering;
steering >>= 2;
steering += steering2;
steering = -steering;
// Return if car is not moving
if (outrun.game_state == GS_INGAME && oinitengine.car_increment >> 16 == 0)
{
// Hack so car is centered if we want to bypass countdown sequence
int16_t road_width_change = (oroad.road_width >> 16) - road_width_old;
road_width_old = (oroad.road_width >> 16);
if (oinitengine.car_x_pos < 0)
road_width_change = -road_width_change;
oinitengine.car_x_pos += road_width_change;
// End of Hack
return;
}
oinitengine.car_x_pos += steering;
int16_t road_width_change = (oroad.road_width >> 16) - road_width_old;
road_width_old = (oroad.road_width >> 16);
if (oinitengine.car_x_pos < 0)
road_width_change = -road_width_change;
oinitengine.car_x_pos += road_width_change;
}
// Ensure car does not stray too far from sides of road
// There are three parts to this function:
// a. Normal Road
// b. Road Split
// c. Dual Lanes
//
// Source: 0xC2B0
void OFerrari::set_ferrari_bounds()
{
// d0 = road_width
// d2 = car_x_pos
int16_t road_width16 = oroad.road_width >> 16;
int16_t d1 = 0;
// Road Split Both Lanes
if (oinitengine.rd_split_state == 4)
{
if (oinitengine.car_x_pos < 0)
road_width16 = -road_width16;
d1 = road_width16 + 0x140;
road_width16 -= 0x140;
}
// One Lane
else if (road_width16 <= 0xFF)
{
road_width16 += OFFROAD_BOUNDS;
d1 = road_width16;
road_width16 = -road_width16;
}
// Two Lanes - road_two_lanes:
else
{
if (oinitengine.car_x_pos < 0)
road_width16 = -road_width16;
d1 = road_width16 + OFFROAD_BOUNDS;
road_width16 -= OFFROAD_BOUNDS;
}
// Set Bounds
if (oinitengine.car_x_pos < road_width16)
oinitengine.car_x_pos = road_width16;
else if (oinitengine.car_x_pos > d1)
oinitengine.car_x_pos = d1;
oroad.car_x_bak = oinitengine.car_x_pos;
oroad.road_width_bak = oroad.road_width >> 16;
}
// Check Car Is Still On Road
//
// Source: 0xBFDC
void OFerrari::check_wheels()
{
wheel_state = WHEELS_ON;
wheel_traction = TRACTION_ON;
uint16_t road_width = oroad.road_width >> 16;
switch (oroad.road_ctrl)
{
case ORoad::ROAD_OFF: // Both Roads Off
return;
// Single Road
case ORoad::ROAD_R0: // Road 0
case ORoad::ROAD_R1: // Road 1
case ORoad::ROAD_R0_SPLIT: // Road 0 (Road Split.)
case ORoad::ROAD_R1_SPLIT: // Road 1 (Road Split. Invert Road 1)
{
int16_t x = oinitengine.car_x_pos;
if (oroad.road_ctrl == ORoad::ROAD_R0_SPLIT)
x -= road_width;
else
x += road_width;
if (oroad.road_ctrl == ORoad::ROAD_R0_SPLIT || oroad.road_ctrl == ORoad::ROAD_R1_SPLIT)
{
if (x > -0xD4 && x <= 0xD4) return;
else if (x < -0x104 || x > 0x104) set_wheels(WHEELS_OFF);
else if (x > 0xD4 && x <= 0x104) set_wheels(WHEELS_LEFT_OFF);
else if (x <= 0xD4 && x >= -0x104) set_wheels(WHEELS_RIGHT_OFF);
}
else
{
if (x > -0xD4 && x <= 0xD4) return;
else if (x < -0x104 || x > 0x104) set_wheels(WHEELS_OFF);
else if (x > 0xD4 && x <= 0x104) set_wheels(WHEELS_RIGHT_OFF);
else if (x <= 0xD4 && x >= -0x104) set_wheels(WHEELS_LEFT_OFF);
}
}
break;
// Both Roads
case ORoad::ROAD_BOTH_P0: // Both Roads (Road 0 Priority) [DEFAULT]
case ORoad::ROAD_BOTH_P1: // Both Roads (Road 1 Priority)
case ORoad::ROAD_BOTH_P0_INV: // Both Roads (Road 0 Priority) (Road Split. Invert Road 1)
case ORoad::ROAD_BOTH_P1_INV: // Both Roads (Road 1 Priority) (Road Split. Invert Road 1)
{
int16_t x = oinitengine.car_x_pos;
if (road_width > 0xFF)
{
if (x < 0)
x += road_width;
else
x -= road_width;
if (x < -0x104 || x > 0x104) set_wheels(WHEELS_OFF);
else if (x < -0xD4) set_wheels(WHEELS_RIGHT_OFF);
else if (x > 0xD4) set_wheels(WHEELS_LEFT_OFF);
}
else
{
road_width += 0x104;
if (x >= 0)
{
if (x > road_width) set_wheels(WHEELS_OFF);
else if (x > road_width - 0x30) set_wheels(WHEELS_LEFT_OFF);
}
else
{
x = -x;
if (x > road_width) set_wheels(WHEELS_OFF);
else if (x > road_width - 0x30) set_wheels(WHEELS_RIGHT_OFF);
}
}
}
break;
}
}
void OFerrari::set_wheels(uint8_t new_state)
{
wheel_state = new_state;
wheel_traction = (new_state == WHEELS_OFF) ? 2 : 1;
}
// Adjusts the x-position of the car based on the curve.
// This effectively stops the user driving through the courses in a straight line.
// (sticks the car to the track).
//
// Source: 0xBF6E
void OFerrari::set_curve_adjust()
{
int16_t x_diff = oroad.road_x[170] - oroad.road_x[511];
// Invert x diff when taking roadsplit
if (oinitengine.rd_split_state && oinitengine.car_x_pos < 0)
x_diff = -x_diff;
x_diff >>= 6;
if (x_diff)
{
x_diff *= (oinitengine.car_increment >> 16);
x_diff /= 0xDC;
x_diff <<= 1;
oinitengine.car_x_pos += x_diff;
}
}
// Draw Shadow below Ferrari
//
// Source: 0xA7BC
void OFerrari::draw_shadow()
{
if (spr_shadow->control & OSprites::ENABLE)
{
if (outrun.game_state == GS_MUSIC) return;
if (outrun.tick_frame)
{
spr_shadow->road_priority = spr_ferrari->road_priority - 1;
spr_shadow->x = spr_ferrari->x;
spr_shadow->y = 222;
spr_shadow->zoom = 0x99;
spr_shadow->draw_props = 8;
spr_shadow->addr = outrun.adr.shadow_data;
}
if (oroad.get_view_mode() != ORoad::VIEW_INCAR)
osprites.do_spr_order_shadows(spr_shadow);
}
}
// Set Passenger Sprite X/Y Position.
//
// Routine is used separately for both male and female passengers.
//
// In use:
// a1 = Passenger XY offset table
// a5 = Passenger 1 / Passenger 2 Sprite
// a6 = Car Sprite
//
// Memory locations:
// 62F00 = Car
// 62F40 = Passenger 1 (Man)
// 62F80 = Passenger 2 (Girl)
//
// Source: A568
void OFerrari::set_passenger_sprite(oentry* sprite)
{
sprite->road_priority = spr_ferrari->road_priority;
sprite->priority = spr_ferrari->priority + 1;
uint16_t frame = sprite_pass_y << 3;
// Is this a bug in the original? Note that by negating HFLIP check the passengers
// shift right a few pixels on acceleration.
if ((oinitengine.car_increment >> 16 >= 0x14) && !(spr_ferrari->control & OSprites::HFLIP))
frame += 4;
// --------------------------------------------------------------------------------------------
// Set Palette
// --------------------------------------------------------------------------------------------
uint8_t pal = 0;
// Test for car collision frame
if (sprite_pass_y == 9)
{
// Set Brown/Blonde Palette depending on whether man or woman
if (sprite == spr_pass1) pal = 0xA;
else pal = 0x8;
}
else
{
if (sprite == spr_pass1) pal = 0x2D;
else pal = 0x2E;
}
// --------------------------------------------------------------------------------------------
// Set X/Y Position
// --------------------------------------------------------------------------------------------
sprite->pal_src = pal;
uint32_t offset_table = ((sprite == spr_pass1) ? PASS1_OFFSET : PASS2_OFFSET) + frame;
sprite->x = spr_ferrari->x + roms.rom0.read16(&offset_table);
sprite->y = spr_ferrari->y + roms.rom0.read16(offset_table);
sprite->zoom = 0x7F;
sprite->draw_props = 8;
sprite->shadow = 3;
sprite->width = 0;
set_passenger_frame(sprite);
draw_sprite(sprite);
}
// Set Passenger Sprite Frame
//
// - Set the appropriate male/female frame
// - Uses the car's speed to set the hair frame
// - Also handles skid case
//
// Source: 0xA632
void OFerrari::set_passenger_frame(oentry* sprite)
{
uint32_t addr = outrun.adr.sprite_pass_frames;
if (sprite == spr_pass2) addr += 4; // Female frames
uint16_t inc = oinitengine.car_increment >> 16;
// Car is moving
// Use adjusted increment/speed of car as reload value for sprite counter (to ultimately set hair frame)
if (inc != 0)
{
if (inc > 0xFF) inc = 0xFF;
inc >>= 5;
int16_t counter = 9 - inc;
if (counter < 0) counter = 0;
sprite->reload = counter;
if (sprite->counter <= 0)
{
sprite->counter = sprite->reload;
sprite->xw1++; // Reuse this as a personal tick counter to flick between hair frames
}
else
sprite->counter--;
inc = (sprite->xw1 & 1) << 3;
}
// Check Skid
if (sprite->pass_props >= 9)
{
// skid left
if (ocrash.skid_counter > 0)
{
sprite->addr = (sprite == spr_pass1) ?
outrun.adr.sprite_pass1_skidl : outrun.adr.sprite_pass2_skidl;
}
// skid right
else
{
sprite->addr = (sprite == spr_pass1) ?
outrun.adr.sprite_pass1_skidr : outrun.adr.sprite_pass2_skidr;
}
}
else
sprite->addr = roms.rom0p->read32(addr + inc);
}
// ------------------------------------------------------------------------------------------------
// CAR HANDLING ROUTINES
// ------------------------------------------------------------------------------------------------
// Main routine handling car speed, revs, torque
//
// Source: 0x6288
void OFerrari::move()
{
if (car_ctrl_active)
{
// Auto braking if necessary
if (outrun.game_state != GS_ATTRACT && auto_brake)
oinputs.acc_adjust = 0;
// Set Gear For Demo Mode
if (FORCE_AI ||
outrun.game_state == GS_ATTRACT || outrun.game_state == GS_BONUS ||
config.controls.gear == config.controls.GEAR_AUTO)
{
// demo_mode_gear
oinputs.gear = (oinitengine.car_increment >> 16 > 0xA0);
}
gfx_smoke = 0;
// --------------------------------------------------------------------
// CRASH CODE - Slow Car
// --------------------------------------------------------------------
if (ocrash.crash_counter && ocrash.spin_control1 <= 0)
{
oinitengine.car_increment = (oinitengine.car_increment & 0xFFFF) | ((((oinitengine.car_increment >> 16) * 31) >> 5) << 16);
revs = 0;
gear_value = 0;
gear_bak = 0;
gear_smoke = 0;
torque = 0x1000;
}
// --------------------------------------------------------------------
// NO CRASH
// --------------------------------------------------------------------
else
{
if (car_state >= 0) car_state = CAR_NORMAL; // No crash - Clear smoke from wheels
// check_time_expired:
// 631E: Clear acceleration value if time out
if ((ostats.time_counter & 0xFF) == 0)
oinputs.acc_adjust = 0;
// --------------------------------------------------------------------
// Do Car Acceleration / Revs / Torque
// Note: Torque gets set based on gear car is in
// --------------------------------------------------------------------
// do_acceleration:
car_acc_brake();
int32_t d2 = revs / torque;
if (!oinitengine.ingame_engine)
{
tick_engine_disabled(d2);
}
else
{
int16_t d1 = torque_index;
if (gear_counter == 0)
do_gear_torque(d1);
}
// set_torque:
int16_t new_torque = torque_lookup[torque_index];
torque = new_torque;
d2 = (int32_t) (d2 & 0xFFFF) * new_torque; // unsigned multiply
int32_t accel_copy = accel_value << 16;
int32_t rev_adjust_new = 0;
if (gear_counter != 0)
rev_adjust_new = tick_gear_change(d2 >> 16);
// Compare Accelerator To Proposed New Speed
//
// d0 = Desired Accelerator Value [accel_copy]
// d1 = Torque Value [new_torque]
// d2 = Proposed New Rev Value [d2]
// d4 = Rev Adjustment (due to braking / off road etc / revs being higher than desired) [rev_adjust]
else if (d2 != accel_copy)
{
if (accel_copy >= d2)
rev_adjust_new = get_speed_inc_value(new_torque, d2);
else
rev_adjust_new = get_speed_dec_value(new_torque);
}
// test_smoke:
if (gear_smoke)
rev_adjust_new = tick_smoke(); // Note this also changes the speed [stored in d4]
// cont2:
set_brake_subtract(); // Calculate brake value to subtract from revs
finalise_revs(d2, rev_adjust_new); // Subtract calculated value from revs
convert_revs_speed(new_torque, d2); // d2 is converted from revs to speed
// Ingame Control Not Active. Clear Car Speed
if (!oinitengine.ingame_engine)
{
oinitengine.car_increment = 0;
car_inc_old = 0;
}
// Set New Car Speed to car_increment
else if (outrun.game_state != GS_BONUS)
{
int16_t diff = car_inc_old - (d2 >> 16); // Old Speed - New Speed
// Car is moving
if (diff != 0)
{
// Car Speeding Up (New Speed is faster)
if (diff < 0)
{
diff = -diff;
uint8_t adjust = 2;
if (oinitengine.car_increment >> 16 <= 0x28)
adjust >>= 1;
if (diff > 2)
d2 = (car_inc_old + adjust) << 16;
}
// Car Slowing Down
else if (diff > 0)
{
uint8_t adjust = 2;
if (brake_subtract)
adjust <<= 2;
if (diff > adjust)
d2 = (car_inc_old - adjust) << 16;
}
}
oinitengine.car_increment = d2;
}
else
oinitengine.car_increment = d2;
} // end crash if/else block
// move_car_rev:
update_road_pos();
ohud.draw_rev_counter();
} // end car_ctrl_active
// Check whether we want to play slip sound
// check_slip
if (gfx_smoke)
{
car_state = CAR_SMOKE; // Set smoke from car wheels
if (oinitengine.car_increment >> 16)
{
if (slip_sound == sound::STOP_SLIP)
osoundint.queue_sound(slip_sound = sound::INIT_SLIP);
}
else
osoundint.queue_sound(slip_sound = sound::STOP_SLIP);
}
// no_smoke:
else
{
if (slip_sound != sound::STOP_SLIP)
osoundint.queue_sound(slip_sound = sound::STOP_SLIP);
}
// move_car
car_inc_old = oinitengine.car_increment >> 16;
counter++;
// During Countdown: Clear Car Speed
if (outrun.game_state == GS_START1 || outrun.game_state == GS_START2 || outrun.game_state == GS_START3)
{
oinitengine.car_increment = 0;
car_inc_old = 0;
}
}
// Handle revs/torque when in-game engine disabled
//
// Source: 0x6694
void OFerrari::tick_engine_disabled(int32_t &d2)
{
torque_index = 0;
// Crash taking place - do counter and set game engine when expired
if (ocrash.coll_count1)
{
olevelobjs.spray_counter = 0;
if (--oinitengine.ingame_counter != 0)
return;
}
else if (outrun.game_state != GS_ATTRACT && outrun.game_state != GS_INGAME)
return;
// Switch back to in-game engine mode
oinitengine.ingame_engine = true;
torque = 0x1000;
// Use top word of revs for lookup
int16_t lookup = (revs >> 16);
if (lookup > 0xFF) lookup = 0xFF;
torque_index = (0x30 - rev_inc_lookup[lookup]) >> 2;
int16_t acc = accel_value - 0x10;
if (acc < 0) acc = 0;
acc_post_stop = acc;
revs_post_stop = lookup;
// Clear bottom word of d2 and swap
d2 = d2 << 16;
//lookup -= 0x10;
//if (lookup < 0) lookup = 0;
rev_stop_flag = 14;
}
// - Convert the already processed accleration inputs into a meaningful value for both ACC and BRAKE
// - Adjust acceleration based on number of wheels on road
// - Adjust acceleration if car skidding or spinning
//
// Source: 0x6524
void OFerrari::car_acc_brake()
{
// ------------------------------------------------------------------------
// Acceleration
// ------------------------------------------------------------------------
int16_t acc1 = oinputs.acc_adjust;
int16_t acc2 = oinputs.acc_adjust;
acc1 += acc_adjust1 + acc_adjust2 + acc_adjust3;
acc1 >>= 2;
acc_adjust3 = acc_adjust2;
acc_adjust2 = acc_adjust1;
acc_adjust1 = acc2;
if (!oinitengine.ingame_engine)
{
acc2 -= accel_value_bak;
if (acc2 < 0) acc2 = -acc2;
if (acc2 < 8)
acc1 = accel_value_bak;
}
// test_skid_spin:
// Clear acceleration on skid
if (ocrash.spin_control1 > 0 || ocrash.skid_counter)
acc1 = 0;
// Adjust speed when offroad
else if (wheel_state != WHEELS_ON)
{
if (gear_value)
acc1 = (acc1 * 3) / 10;
else
acc1 = (acc1 * 6) / 10;
// If only one wheel off road, increase acceleration by a bit more than if both wheels off-road
if (wheel_state != WHEELS_OFF)
acc1 = (acc1 << 1) + (acc1 >> 1);
}
// finalise_acc_value:
accel_value = acc1;
accel_value_bak = acc1;
// ------------------------------------------------------------------------
// Brake
// ------------------------------------------------------------------------
int16_t brake1 = oinputs.brake_adjust;
int16_t brake2 = oinputs.brake_adjust;
brake1 += brake_adjust1 + brake_adjust2 + brake_adjust3;
brake1 >>= 2;
brake_adjust3 = brake_adjust2;
brake_adjust2 = brake_adjust1;
brake_adjust1 = brake2;
brake_value = brake1;
// ------------------------------------------------------------------------
// Gears
// ------------------------------------------------------------------------
gear_bak = gear_value;
gear_value = oinputs.gear;
}
// Do Gear Changes & Torque Index Settings
//
// Source: 0x6948
void OFerrari::do_gear_torque(int16_t &d1)
{
if (oinitengine.ingame_engine)
{
d1 = torque_index;
if (gear_value)
do_gear_high(d1);
else
do_gear_low(d1);
}
torque_index = (uint8_t) d1;
// Backup gear value for next iteration (so we can tell when gear has recently changed)
gear_bak = gear_value;
}
void OFerrari::do_gear_low(int16_t &d1)
{
// Recent Shift from high to low
if (gear_bak)
{
gear_value = false;
gear_counter = 4;
return;
}
// Low Gear - Show Smoke When Accelerating From Standstill
if (oinitengine.car_increment >> 16 < 0x50 && accel_value - 0xE0 >= 0)
gfx_smoke++;
// Adjust Torque Index
if (d1 == 0x10) return;
else if (d1 < 0x10)
{
d1++;
return;
}
d1 -= 4;
if (d1 < 0x10)
d1 = 0x10;
}
void OFerrari::do_gear_high(int16_t &d1)
{
// Change from Low Gear to High Gear
if (!gear_bak)
{
gear_value = true;
gear_counter = 4;
return;
}
// Increment torque until it reaches 0x1F
if (d1 == 0x1F) return;
d1++;
}
// Source: 0x6752
int32_t OFerrari::tick_gear_change(int16_t rem)
{
gear_counter--;
rev_adjust = rev_adjust - (rev_adjust >> 4);
// Setup smoke when gear counter hits zero
if (gear_counter == 0)
{
rem -= 0xE0;
if (rem < 0) return rev_adjust;
int16_t acc = accel_value - 0xE0;
if (acc < 0) return rev_adjust;
gear_smoke = acc;
}
return rev_adjust;
}
// Set value to increment speed by, when revs lower than acceleration
//
// Inputs:
//
// d1 = Torque Value [new_torque]
// d2 = Proposed new increment value [new_rev]
//
// Outputs: d4 [Rev Adjustment]
//
// Source: 679C
int32_t OFerrari::get_speed_inc_value(uint16_t new_torque, uint32_t new_rev)
{
// Use Top Word Of Revs For Table Lookup. Cap At 0xFF Max
uint16_t lookup = (new_rev >> 16);
if (lookup > 0xFF) lookup = 0xFF;
uint32_t rev_adjust = rev_inc_lookup[lookup]; // d4
// Double adjustment if car moving slowly
if (oinitengine.car_increment >> 16 <= 0x14)
rev_adjust <<= 1;
rev_adjust = ((new_torque * new_torque) >> 12) * rev_adjust;
if (!oinitengine.ingame_engine) return rev_adjust;
return rev_adjust << rev_shift;
}
// Set value to decrement speed by, when revs higher than acceleration
//
// Inputs:
//
// d1 = Torque Value [new_torque]
//
// Outputs: d4 [Rev Adjustment]
//
// Source: 67E4
int32_t OFerrari::get_speed_dec_value(uint16_t new_torque)
{
int32_t new_rev = -((0x440 * new_torque) >> 4);
if (wheel_state == WHEELS_ON) return new_rev;
return new_rev << 2;
}
// - Reads Brake Value
// - Translates Into A Value To Subtract From Car Speed
// - Also handles setting smoke on wheels during brake/skid
// Source: 0x6A10
void OFerrari::set_brake_subtract()
{
int32_t d6 = 0;
const int32_t DEC = -0x8800; // Base value to subtract from acceleration burst
// Not skidding or spinning
if (ocrash.skid_counter == 0 && ocrash.spin_control1 == 0)
{
if (brake_value < OInputs::BRAKE_THRESHOLD1)
{
brake_subtract = d6;
return;
}
else if (brake_value < OInputs::BRAKE_THRESHOLD2)
{
brake_subtract = d6 + DEC;
return;
}
else if (brake_value < OInputs::BRAKE_THRESHOLD3)
{
brake_subtract = d6 + (DEC * 3);
return;
}
else if (brake_value < OInputs::BRAKE_THRESHOLD4)
{
brake_subtract = d6 + (DEC * 5);
return;
}
}
// check_smoke
if (oinitengine.car_increment >> 16 > 0x28)
gfx_smoke++;
brake_subtract = d6 + (DEC * 9);
}
// - Finalise rev value, taking adjustments into account
//
// Inputs:
//
// d2 = Current Revs
// d4 = Rev Adjustment
//
// Outputs:
//
// d2 = New rev value
//
// Source: 0x67FC
void OFerrari::finalise_revs(int32_t &d2, int32_t rev_adjust_new)
{
rev_adjust_new += brake_subtract;
if (rev_adjust_new < -0x44000) rev_adjust_new = -0x44000;
d2 += rev_adjust_new;
rev_adjust = rev_adjust_new;
if (d2 > 0x13C0000) d2 = 0x13C0000;
else if (d2 < 0) d2 = 0;
}
// Convert revs to final speed value
// Set correct pitch for sound fx
//
// Note - main problem seems to be that the revs fed to this routine are wrong in the first place on restart
// rev_stop_flag, revs_post_stop, accel_value and acc_post_stop seem ok?
//
// Source: 0x6838
void OFerrari::convert_revs_speed(int32_t new_torque, int32_t &d2)
{
revs = d2;
int32_t d3 = d2;
if (d3 < 0x1F0000) d3 = 0x1F0000;
int16_t revs_top = d3 >> 16;
// Check whether we're switching back to ingame engine (after disabling user control of car)
if (rev_stop_flag)
{
if (revs_top >= revs_post_stop)
{
rev_stop_flag = 0;
}
else
{
if (accel_value < acc_post_stop)
revs_post_stop -= rev_stop_flag;
// cont1:
int16_t d5 = revs_post_stop >> 1;
int16_t d4 = rev_stop_flag;
if (revs_top >= d5)
{
d5 >>= 1;
d4 >>= 1;
if (revs_top >= d5)
d4 >>= 1;
}
// 689c
revs_post_stop -= d4;
if (revs_post_stop < 0x1F) revs_post_stop = 0x1F;
revs_top = revs_post_stop;
}
}
// setup_pitch_fx:
rev_pitch1 = (revs_top * 0x1A90) >> 8;
// Setup New Car Increment Speed
d2 = ((d2 >> 16) * 0x1A90) >> 8;
d2 = (d2 << 16) >> 4;
/*if (!new_torque)
{
std::cout << "convert_revs_speed error!" << std::endl;
}*/
d2 = (d2 / new_torque) * 0x480;
if (d2 < 0) d2 = 0;
else if (d2 > MAX_SPEED) d2 = MAX_SPEED;
}
// Update road_pos, taking road_curve into account
//
// Source: 0x6ABA
void OFerrari::update_road_pos()
{
uint32_t car_inc = CAR_BASE_INC;
// Bendy Roads
if (oinitengine.road_type > OInitEngine::ROAD_STRAIGHT)
{
int32_t x = oinitengine.car_x_pos;
if (oinitengine.road_type == OInitEngine::ROAD_RIGHT)
x = -x;
x = (x / 0x28) + oinitengine.road_curve;
car_inc = (car_inc * x) / oinitengine.road_curve;
}
car_inc *= oinitengine.car_increment >> 16;
oroad.road_pos_change = car_inc;
oroad.road_pos += car_inc;
}
// Decrement Smoke Counter
// Source: 0x666A
int32_t OFerrari::tick_smoke()
{
gear_smoke--;
int32_t r = rev_adjust - (rev_adjust >> 4);
if (gear_smoke >= 8) gfx_smoke++; // Trigger smoke
return r;
}
// Calculate car score and sound. Strange combination, but there you go!
//
// Source: 0xBD78
void OFerrari::do_sound_score_slip()
{
// ------------------------------------------------------------------------
// ENGINE PITCH SOUND
// ------------------------------------------------------------------------
uint16_t engine_pitch = 0;
// Do Engine Rev
if (outrun.game_state >= GS_START1 && outrun.game_state <= GS_INGAME)
{
engine_pitch = rev_pitch2 + (rev_pitch2 >> 1);
}
osoundint.engine_data[sound::ENGINE_PITCH_H] = engine_pitch >> 8;
osoundint.engine_data[sound::ENGINE_PITCH_L] = engine_pitch & 0xFF;
// Curved Road
if (oinitengine.road_type != OInitEngine::ROAD_STRAIGHT)
{
int16_t steering = oinputs.steering_adjust;
if (steering < 0) steering = -steering;
// Hard turn
if (steering >= 0x70)
{
// Move Left
if (oinitengine.car_x_pos > oinitengine.car_x_old)
cornering = (oinitengine.road_type == OInitEngine::ROAD_LEFT) ? 0 : -1;
// Straight
else if (oinitengine.car_x_pos == oinitengine.car_x_old)
cornering = 0;
// Move Right
else
cornering = (oinitengine.road_type == OInitEngine::ROAD_RIGHT) ? 0 : -1;
}
else
cornering = 0;
}
else
cornering = 0;
// update_score:
car_x_diff = oinitengine.car_x_pos - oinitengine.car_x_old;
oinitengine.car_x_old = oinitengine.car_x_pos;
if (outrun.game_state == GS_ATTRACT)
return;
// Wheels onroad - Convert Speed To Score
if (wheel_state == WHEELS_ON)
{
ostats.convert_speed_score(oinitengine.car_increment >> 16);
}
// 0xBE6E
if (!sprite_slip_copy)
{
if (ocrash.skid_counter)
{
is_slipping = -1;
osoundint.queue_sound(sound::INIT_SLIP);
}
}
// 0xBE94
else
{
if (!ocrash.skid_counter)
{
is_slipping = 0;
osoundint.queue_sound(sound::STOP_SLIP);
}
}
// 0xBEAC
sprite_slip_copy = ocrash.skid_counter;
// ------------------------------------------------------------------------
// Switch to cornering. Play Slip Sound. Init Smoke
// ------------------------------------------------------------------------
if (!ocrash.skid_counter)
{
// 0xBEBE: Initalize Slip
if (!cornering_old)
{
if (cornering)
{
is_slipping = -1;
osoundint.queue_sound(sound::INIT_SLIP);
}
}
// 0xBEE4: Stop Cornering
else
{
if (!cornering)
{
is_slipping = 0;
osoundint.queue_sound(sound::STOP_SLIP);
}
}
}
// check_wheels:
cornering_old = cornering;
if (sprite_wheel_state)
{
// If previous wheels on-road & current wheels off-road - play safety zone sound
if (!wheel_state)
osoundint.queue_sound(sound::STOP_SAFETYZONE);
}
// Stop Safety Sound
else
{
if (wheel_state)
osoundint.queue_sound(sound::INIT_SAFETYZONE);
}
sprite_wheel_state = wheel_state;
}
// Shake Ferrari by altering XY Position when wheels are off-road
//
// Source: 0x9FEE
void OFerrari::shake()
{
if (outrun.game_state != GS_INGAME && outrun.game_state != GS_ATTRACT) return;
if (wheel_traction == TRACTION_ON) return; // Return if both wheels have traction
int8_t traction = wheel_traction - 1;
int16_t rnd = outils::random();
spr_ferrari->counter++;
uint16_t car_inc = oinitengine.car_increment >> 16; // [d5]
if (car_inc <= 0xA) return; // Do not shake car at low speeds
if (car_inc <= (0x3C >> traction))
{
rnd &= 3;
if (rnd != 0) return;
}
else if (car_inc <= (0x78 >> traction))
{
rnd &= 1;
if (rnd != 0) return;
}
if (rnd < 0) spr_ferrari->y--;
else spr_ferrari->y++;
rnd &= 1;
if (!(spr_ferrari->counter & BIT_1))
rnd = -rnd;
spr_ferrari->x += rnd; // Increment Ferrari X by 1 or -1
}
// Perform Skid (After Car Has Collided With Another Vehicle)
//
// Source: 0xBFB4
void OFerrari::do_skid()
{
if (!ocrash.skid_counter) return;
if (ocrash.skid_counter > 0)
{
ocrash.skid_counter--;
oinitengine.car_x_pos += OCrash::SKID_X_ADJ;
}
else
{
ocrash.skid_counter++;
oinitengine.car_x_pos -= OCrash::SKID_X_ADJ;
}
}
void OFerrari::draw_sprite(oentry* sprite)
{
if (oroad.get_view_mode() != ORoad::VIEW_INCAR)
{
osprites.map_palette(sprite);
osprites.do_spr_order_shadows(sprite);
}
}
// Rev Lookup Table. 255 Values.
// Used to provide rev adjustment. Note that values tail off at higher speeds.
const uint8_t OFerrari::rev_inc_lookup[] =
{
0x14, 0x14, 0x14, 0x14, 0x15, 0x15, 0x15, 0x15, 0x16, 0x16, 0x16, 0x16, 0x17, 0x17, 0x17, 0x17,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19,
0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19,
0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A,
0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A,
0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B,
0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1D, 0x1D, 0x1D, 0x1D, 0x1D, 0x1D, 0x1D, 0x1D,
0x1E, 0x1E, 0x1E, 0x1E, 0x1E, 0x1E, 0x1E, 0x1E, 0x1F, 0x1F, 0x1F, 0x1F, 0x20, 0x20, 0x20, 0x20,
0x21, 0x21, 0x22, 0x22, 0x23, 0x23, 0x24, 0x24, 0x25, 0x25, 0x26, 0x26, 0x27, 0x27, 0x28, 0x28,
0x29, 0x29, 0x2A, 0x2A, 0x2B, 0x2B, 0x2B, 0x2C, 0x2C, 0x2C, 0x2D, 0x2D, 0x2D, 0x2E, 0x2E, 0x2E,
0x2F, 0x2F, 0x2F, 0x2F, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x2F, 0x2F, 0x2F, 0x2F,
0x2E, 0x2E, 0x2E, 0x2D, 0x2D, 0x2D, 0x2C, 0x2C, 0x2B, 0x2B, 0x2A, 0x2A, 0x29, 0x29, 0x28, 0x28,
0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1F, 0x1E, 0x1D, 0x1C, 0x1B, 0x1A, 0x19, 0x18,
0x17, 0x15, 0x13, 0x11, 0x0F, 0x0D, 0x0B, 0x0A, 0x09, 0x09, 0x08, 0x08, 0x07, 0x07, 0x06, 0x06,
0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x03, 0x03, 0x03, 0x02, 0x02, 0x02, 0x01, 0x01, 0x01, 0x01
};
const uint16_t OFerrari::torque_lookup[] =
{
0x2600, // Offset 0x00 - Start line
0x243C, // ..
0x2278, // values only used when pulling away from start line
0x20B4,
0x1EF0,
0x1D2C,
0x1B68,
0x19A4,
0x17E0,
0x161C,
0x1458,
0x1294,
0x10D0,
0xF0C,
0xD48,
0xB84,
0x9BB, // Offset 0x10 - Low Gear
0x983, // ..
0x94B, // .. in between these values
0x913, // .. is the lookup as we shift between
0x8DB, // .. the two gears
0x8A3, // ..
0x86B,
0x833,
0x7FB,
0x7C2,
0x789,
0x750,
0x717,
0x6DE,
0x6A5,
0x66C, // Offset 0x1F - High Gear
}; | 29.7068 | 135 | 0.540943 | [
"object"
] |
ddf28efc3e7bf7fd346254d294aba1e7a607e259 | 8,879 | cpp | C++ | RayTracer/src/Structure/SAHBVHStructure.cpp | mathiasgam/ManyLightsWarmup | 0fdb298f2fbb67bb50a0aa14ae5f7e01f8272e22 | [
"MIT"
] | 1 | 2020-06-28T11:42:47.000Z | 2020-06-28T11:42:47.000Z | RayTracer/src/Structure/SAHBVHStructure.cpp | mathiasgam/ManyLightsWarmup | 0fdb298f2fbb67bb50a0aa14ae5f7e01f8272e22 | [
"MIT"
] | null | null | null | RayTracer/src/Structure/SAHBVHStructure.cpp | mathiasgam/ManyLightsWarmup | 0fdb298f2fbb67bb50a0aa14ae5f7e01f8272e22 | [
"MIT"
] | 1 | 2021-09-25T12:18:30.000Z | 2021-09-25T12:18:30.000Z | #include "SAHBVHStructure.h"
#include <limits>
#include <iostream>
SAHBVHStructure::~SAHBVHStructure()
{
}
void SAHBVHStructure::init(const std::vector<const Geometry*>& geometry, const std::vector<const Plane*>& _planes)
{
nodes.clear();
primitives.clear();
objects.clear();
std::cout << "Loading objects: ";
std::vector<Primitive_Fat> primitives_build(0);
for (auto& object : geometry) {
objects.push_back(object);
}
for (auto& plane : _planes) {
planes.push_back(plane);
}
std::cout << "" << objects.size() << " loaded\n";
std::cout << "Collecting primitives\n";
// Collect all the primitives in the objects
for (unsigned int i = 0; i < objects.size(); i++) {
const Geometry& object = *objects[i];
const unsigned int object_size = object.num_primitives();
for (unsigned int j = 0; j < object_size; j++) {
Primitive_Fat p = {};
p.object = i;
p.index = j;
p.bbox = object.get_bbox(j);
p.center = object.get_bbox(j).center();
//std::cout << "object: " << object.get_bbox(j) << " bbox: " << p.bbox << "\n";
primitives_build.push_back(p);
}
}
std::cout << "Building BVH structure\n";
// recursively construct the binary search tree
root_index = build(primitives_build, 0, static_cast<unsigned int>(primitives_build.size()));
std::cout << "Precomputing bbox centers\n";
auto num_nodes = nodes.size();
centers.resize(num_nodes);
for (int i = 0; i < num_nodes; i++) {
centers[i] = nodes[i].bbox.center();
}
std::cout << "Reducing primitive size\n";
// reduce the build primitives to search primitives
primitives.resize(primitives_build.size());
for (int i = 0; i < primitives_build.size(); i++) {
Primitive_Fat& p = primitives_build[i];
primitives[i].index = p.index;
primitives[i].object = p.object;
}
recalculate_bboxes(root_index);
}
bool SAHBVHStructure::closest_hit(Ray& ray, HitInfo& hit) const
{
Vec3f dirfrac = Vec3f(1.0f / ray.direction[0], 1.0f / ray.direction[1], 1.0f / ray.direction[2]);
bool hashit = closest_plane(ray, hit, dirfrac);
if (closest_hit_recurse(ray, hit, root_index, dirfrac))
hashit = true;
return hashit;
}
bool SAHBVHStructure::any_hit(Ray& ray) const
{
Vec3f dirfrac = Vec3f(1.0f / ray.direction[0], 1.0f / ray.direction[1], 1.0f / ray.direction[2]);
if (any_plane(ray, dirfrac))
return true;
return any_hit_recurse(ray, root_index, dirfrac);
}
void SAHBVHStructure::print()
{
for (int i = 0; i < nodes.size(); i++) {
BVHNode& node = nodes[i];
if (node.type != NodeType::leaf) {
std::cout << "node: " << i << ", type: " << node.type << ", (" << node.leftChild << "," << node.rightChild << ") " << node.bbox << "\n";
}
else {
std::cout << "node: " << i << ", type: leaf(" << node.leftChild << "," << node.rightChild << ") " << node.bbox << "\n";
}
}
}
bool SAHBVHStructure::closest_hit_recurse(Ray &ray, HitInfo &hit, unsigned int i, const Vec3f& dirfrac) const
{
hit.trace_depth++;
const BVHNode& node = nodes[i];
//std::cout << "node: " << i << ", type: " << node.type << ", depth: " << hit.trace_depth << "\n";
bool hashit = false;
if (node.bbox.intersect(ray)) {
if (node.type == leaf) {
for (unsigned int j = node.leftChild; j < node.rightChild; j++) {
const Primitive p = primitives[j];
if (objects[p.object]->intersect(ray, hit, p.index)) {
hashit = true;
ray.t_max = hit.t;
}
}
}
else {
// find the approximate distance to the left and right bbox
float left_dist = dot(centers[node.leftChild] - ray.center, ray.direction);
float right_dist = dot(centers[node.rightChild] - ray.center, ray.direction);
// start search in the closest one
if (left_dist < right_dist) {
if (closest_hit_recurse(ray, hit, node.leftChild, dirfrac))
hashit = true;
if (closest_hit_recurse(ray, hit, node.rightChild, dirfrac))
hashit = true;
}
else {
if (closest_hit_recurse(ray, hit, node.rightChild, dirfrac))
hashit = true;
if (closest_hit_recurse(ray, hit, node.leftChild, dirfrac))
hashit = true;
}
}
}
return hashit;
}
bool SAHBVHStructure::any_hit_recurse(Ray &ray, unsigned int i, const Vec3f& dirfrac) const
{
const BVHNode& node = nodes[i];
if (node.bbox.intersect(ray)) {
if (node.type == leaf) {
for (unsigned int j = node.leftChild; j < node.rightChild; j++) {
const Primitive& p = primitives[j];
if (objects[p.object]->intersect(ray, p.index)) {
return true;
}
}
}
else {
if (any_hit_recurse(ray, node.leftChild, dirfrac))
return true;
if (any_hit_recurse(ray, node.rightChild, dirfrac))
return true;
}
}
return false;
}
bool SAHBVHStructure::closest_plane(Ray &ray, HitInfo &hit, Vec3f& dirfrac) const
{
bool hashit = false;
for (int i = 0; i < planes.size(); i++){
if (planes[i]->intersect(ray, hit, dirfrac)) {
hashit = true;
ray.t_max = hit.t;
}
}
return hashit;
}
bool SAHBVHStructure::any_plane(Ray &ray, Vec3f& dirfrac) const
{
for (auto& plane : planes) {
if (plane->intersect(ray, dirfrac)) {
return true;
}
}
return false;
}
AABB SAHBVHStructure::recalculate_bboxes(unsigned int index)
{
AABB bbox = AABB();
const BVHNode& node = nodes[index];
if (node.type == leaf) {
for (unsigned int i = node.leftChild; i < node.rightChild; i++) {
Primitive& primitive = primitives[i];
bbox.add_bbox(objects[primitive.object]->get_bbox(primitive.index));
}
}
else {
bbox.add_bbox(recalculate_bboxes(node.leftChild));
bbox.add_bbox(recalculate_bboxes(node.rightChild));
}
nodes[index].bbox = bbox;
return bbox;
}
void SAHBVHStructure::swap(Primitive_Fat & left, Primitive_Fat & right)
{
Primitive_Fat tmp = left;
left = right;
right = tmp;
}
unsigned int SAHBVHStructure::build(std::vector<Primitive_Fat>& fat_primitives, unsigned int start, unsigned int end)
{
// create node in the vector
unsigned int num = end - start;
unsigned int index = static_cast<unsigned int>(nodes.size());
{
BVHNode n;
nodes.push_back(n);
}
nodes[index].bbox = AABB();
AABB centroid_box = AABB();
for (unsigned int i = start; i < end; i++) {
nodes[index].bbox.add_bbox(fat_primitives[i].bbox);
centroid_box.add_point(fat_primitives[i].center);
}
if (num <= 4) {
nodes[index].type = leaf;
nodes[index].leftChild = start;
nodes[index].rightChild = end;
return index;
}
float min_cost = std::numeric_limits<float>::max();
float min_split;
int min_axis = 0;
int left_num = 0, right_num = 0;
const int TESTS = 8;
// find best combo of axis and split.
for (int axis = 0; axis < 3; axis++) {
for (int j = 0; j < TESTS; j++) {
AABB _left_bbox;
AABB _right_bbox;
float max_corner = centroid_box.p_max[axis];
float min_corner = centroid_box.p_min[axis];
float split = (max_corner - min_corner)*j / static_cast<float>(TESTS) + min_corner;
//float split = centroid_box.center()[axis];
_left_bbox.p_max[axis] = split;
_right_bbox.p_min[axis] = split;
int num_left = 0;
int num_right = 0;
for (unsigned int k = start; k < end; k++) {
if (fat_primitives[k].center[axis] <= split) {
_left_bbox.add_bbox(fat_primitives[k].bbox);
num_left++;
}
else {
_right_bbox.add_bbox(fat_primitives[k].bbox);
num_right++;
}
}
//std::cout << "left: " << num_left << " right: " << num_right << "\n";
if (num_left < 1 || num_right < 1) {
continue;
}
float p = (split - min_corner) / (max_corner - min_corner);
float cost = p * num_left * _left_bbox.area() + (1.0f-p) * num_right * _right_bbox.area();
if (cost < min_cost) {
min_cost = cost;
min_split = split;
min_axis = axis;
left_num = num_left;
right_num = num_right;
nodes[index].type = static_cast<NodeType>(axis);
}
}
}
//std::cout << "min_split: " << min_split << " left: " << left_num << " right: " << right_num << "\n";
//std::cout << "index: " << index << " num: " << num << " start: " << start << " split: " << min_split << "\n";
//std::cout << "min cost: " << min_cost << ", split: " << min_split << "\n";
//std::cout << "sorting\n";
// swap elements on the left and right to the split
unsigned int x = start, y = end-1;
while (x < y)
{
//std::cout << "1x,y: " << x << "," << y << "\n";
if (fat_primitives[x].center[min_axis] <= min_split) {
x++;
}
else {
while (x < y)
{
//std::cout << "2x,y: " << x << "," << y << "\n";
if (fat_primitives[y].center[min_axis] <= min_split) {
//std::cout << "swap\n";
swap(fat_primitives[x], fat_primitives[y]);
break;
}
y--;
}
}
}
//std::cout << "x: " << x << " left: " << (x - start) << " right: " << (end - x) << "\n";
nodes[index].leftChild = build(fat_primitives, start, x);
nodes[index].rightChild = build(fat_primitives, x, end);
// std::cout << "(" << node.leftChild << "," << node.rightChild << ")";
return index;
}
| 26.743976 | 139 | 0.626872 | [
"geometry",
"object",
"vector"
] |
ddf30920a1d24a14928782a5e4a0f81d535556a5 | 14,260 | cpp | C++ | module/scheduler_components/worker.cpp | manas11/SLOG | a754cbc1c4fa8bdb09a79c5259a31d550da5f15d | [
"MIT"
] | null | null | null | module/scheduler_components/worker.cpp | manas11/SLOG | a754cbc1c4fa8bdb09a79c5259a31d550da5f15d | [
"MIT"
] | null | null | null | module/scheduler_components/worker.cpp | manas11/SLOG | a754cbc1c4fa8bdb09a79c5259a31d550da5f15d | [
"MIT"
] | null | null | null | #include "module/scheduler_components/worker.h"
#if defined(REMASTER_PROTOCOL_SIMPLE) || defined(REMASTER_PROTOCOL_PER_KEY)
#include "module/scheduler_components/remaster_manager.h"
#endif /* defined(REMASTER_PROTOCOL_SIMPLE) || defined(REMASTER_PROTOCOL_PER_KEY) */
#include <thread>
#include <glog/logging.h>
#include "common/proto_utils.h"
#include "module/scheduler.h"
namespace slog {
using internal::Request;
using internal::Response;
Worker::Worker(
const ConfigurationPtr& config,
const std::shared_ptr<Broker>& broker,
Channel channel,
const shared_ptr<Storage<Key, Record>>& storage,
int poll_timeout_ms)
: NetworkedModule(
"Worker-" + std::to_string(channel), broker, channel, poll_timeout_ms),
config_(config),
storage_(storage),
// TODO: change this dynamically based on selected experiment
commands_(new KeyValueCommands()) {}
void Worker::HandleInternalRequest(ReusableRequest&& req, MachineId) {
std::optional<TxnId> txn_id = {};
bool valid_request = true;
switch (req.get()->type_case()) {
case Request::kWorker: {
txn_id = ProcessWorkerRequest(req.get()->worker());
break;
}
case Request::kRemoteReadResult: {
txn_id = ProcessRemoteReadResult(req.get()->remote_read_result());
break;
}
default:
valid_request = false;
break;
}
if (valid_request) {
if (txn_id) {
AdvanceTransaction(*txn_id);
}
} else {
LOG(FATAL) << "Invalid request for worker";
}
}
std::optional<TxnId> Worker::ProcessWorkerRequest(const internal::WorkerRequest& worker_request) {
auto txn_holder = reinterpret_cast<TransactionHolder*>(worker_request.txn_holder_ptr());
auto txn = txn_holder->transaction();
auto txn_id = txn->internal().id();
auto local_partition = config_->local_partition();
RecordTxnEvent(
config_,
txn->mutable_internal(),
TransactionEvent::ENTER_WORKER);
// Create a state for the new transaction
auto [iter, ok] = txn_states_.emplace(
std::piecewise_construct,
std::forward_as_tuple(txn_id),
std::forward_as_tuple(txn_holder));
CHECK(ok) << "Transaction " << txn_id << " has already been dispatched to this worker";
if (txn->status() == TransactionStatus::ABORTED) {
iter->second.phase = TransactionState::Phase::PRE_ABORT;
} else {
iter->second.phase = TransactionState::Phase::READ_LOCAL_STORAGE;
// Remove keys that will be filled in later by remote partitions.
// They are removed at this point so that the next phase will only
// read the local keys from local storage.
auto itr = txn->mutable_read_set()->begin();
while (itr != txn->mutable_read_set()->end()) {
const auto& key = itr->first;
auto partition = config_->partition_of_key(key);
if (partition != local_partition) {
itr = txn->mutable_read_set()->erase(itr);
} else {
itr++;
}
}
itr = txn->mutable_write_set()->begin();
while (itr != txn->mutable_write_set()->end()) {
const auto& key = itr->first;
auto partition = config_->partition_of_key(key);
if (partition != local_partition) {
itr = txn->mutable_write_set()->erase(itr);
} else {
itr++;
}
}
}
VLOG(3) << "Initialized state for txn " << txn_id;
return txn_id;
}
std::optional<TxnId> Worker::ProcessRemoteReadResult(const internal::RemoteReadResult& read_result) {
auto txn_id = read_result.txn_id();
if (txn_states_.count(txn_id) == 0) {
VLOG(1) << "Transaction " << txn_id << " does not exist for remote read result";
return {};
}
auto& state = txn_states_[txn_id];
auto txn = state.txn_holder->transaction();
if (txn->status() != TransactionStatus::ABORTED) {
if (read_result.will_abort()) {
// TODO: optimize by returning an aborting transaction to the scheduler immediately.
// later remote reads will need to be garbage collected.
txn->set_status(TransactionStatus::ABORTED);
} else {
// Apply remote reads. After this point, the transaction has all the data it needs to
// execute the code.
for (const auto& key_value : read_result.reads()) {
(*txn->mutable_read_set())[key_value.first] = key_value.second;
}
}
}
state.remote_reads_waiting_on -= 1;
// Move the transaction to a new phase if all remote reads arrive
if (state.remote_reads_waiting_on == 0) {
if (state.phase == TransactionState::Phase::WAIT_REMOTE_READ) {
state.phase = TransactionState::Phase::EXECUTE;
VLOG(3) << "Execute txn " << txn_id << " after receving all remote read results";
}
else {
LOG(FATAL) << "Invalid phase";
}
}
return txn_id;
}
void Worker::AdvanceTransaction(TxnId txn_id) {
auto& state = txn_states_[txn_id];
switch (state.phase) {
case TransactionState::Phase::READ_LOCAL_STORAGE:
ReadLocalStorage(txn_id);
[[fallthrough]];
case TransactionState::Phase::WAIT_REMOTE_READ:
if (state.phase == TransactionState::Phase::WAIT_REMOTE_READ) {
// The only way to get out of this phase is through remote messages
break;
}
[[fallthrough]];
case TransactionState::Phase::EXECUTE:
if (state.phase == TransactionState::Phase::EXECUTE) {
Execute(txn_id);
}
[[fallthrough]];
case TransactionState::Phase::COMMIT:
if (state.phase == TransactionState::Phase::COMMIT) {
Commit(txn_id);
}
[[fallthrough]];
case TransactionState::Phase::FINISH:
case TransactionState::Phase::PRE_ABORT:
if (state.phase == TransactionState::Phase::FINISH) {
Finish(txn_id);
} else if (state.phase == TransactionState::Phase::PRE_ABORT) {
PreAbort(txn_id);
}
// Never fallthrough after this point because Finish and PreAbort
// has already destroyed the state object
break;
}
}
void Worker::ReadLocalStorage(TxnId txn_id) {
auto& state = txn_states_[txn_id];
auto txn_holder = state.txn_holder;
auto txn = txn_holder->transaction();
auto will_abort = false;
#if defined(REMASTER_PROTOCOL_SIMPLE) || defined(REMASTER_PROTOCOL_PER_KEY)
switch(RemasterManager::CheckCounters(txn_holder, storage_)) {
case VerifyMasterResult::VALID: {
break;
}
case VerifyMasterResult::ABORT: {
will_abort = true;
break;
}
case VerifyMasterResult::WAITING: {
LOG(ERROR) << "Transaction " << txn_id << " was sent to worker with a high counter";
break;
}
default:
LOG(ERROR) << "Unrecognized check counter result";
break;
}
#else
// Check whether the store master metadata matches with the information
// stored in the transaction
// TODO: this loop can be merged with the one below to avoid
// duplicate access to the storage
for (auto& key_pair : txn->internal().master_metadata()) {
auto& key = key_pair.first;
auto txn_master = key_pair.second.master();
Record record;
bool found = storage_->Read(key, record);
if (found) {
if (txn_master != record.metadata.master) {
will_abort = true;
break;
}
}
}
#endif /* defined(REMASTER_PROTOCOL_SIMPLE) || defined(REMASTER_PROTOCOL_PER_KEY) */
if (will_abort) {
txn->set_status(TransactionStatus::ABORTED);
} else {
// If not abort due to remastering, read from local storage
for (auto& key_value : *txn->mutable_read_set()) {
Record record;
storage_->Read(key_value.first, record);
key_value.second = record.value;
}
for (auto& key_value : *txn->mutable_write_set()) {
Record record;
storage_->Read(key_value.first, record);
key_value.second = record.value;
}
}
NotifyOtherPartitions(txn_id);
// TODO: if will_abort == true, we can immediate jump to the FINISH phased.
// To do this, we need to removing the CHECK at the start of ProcessRemoteReadResult
// because we no longer require an aborted txn to receive all remote reads
// before moving on.
// Set the number of remote reads that this partition needs to wait for
state.remote_reads_waiting_on = 0;
if (txn_holder->active_partitions().count(config_->local_partition()) > 0) {
// Active partition needs remote reads from all partitions
state.remote_reads_waiting_on = txn_holder->involved_partitions().size() - 1;
}
if (state.remote_reads_waiting_on == 0) {
VLOG(3) << "Execute txn " << txn_id << " without remote reads";
state.phase = TransactionState::Phase::EXECUTE;
} else {
VLOG(3) << "Defer executing txn " << txn_id << " until having enough remote reads";
state.phase = TransactionState::Phase::WAIT_REMOTE_READ;
}
}
void Worker::Execute(TxnId txn_id) {
auto& state = txn_states_[txn_id];
auto txn = state.txn_holder->transaction();
switch (txn->procedure_case()) {
case Transaction::ProcedureCase::kCode: {
if (txn->status() == TransactionStatus::ABORTED) {
break;
}
// Execute the transaction code
commands_->Execute(*txn);
break;
}
case Transaction::ProcedureCase::kRemaster:
txn->set_status(TransactionStatus::COMMITTED);
break;
default:
LOG(FATAL) << "Procedure is not set";
}
state.phase = TransactionState::Phase::COMMIT;
}
void Worker::Commit(TxnId txn_id) {
auto& state = txn_states_[txn_id];
auto txn = state.txn_holder->transaction();
switch (txn->procedure_case()) {
case Transaction::ProcedureCase::kCode: {
// Apply all writes to local storage if the transaction is not aborted
if (txn->status() != TransactionStatus::COMMITTED) {
break;
}
auto& master_metadata = txn->internal().master_metadata();
for (const auto& key_value : txn->write_set()) {
const auto& key = key_value.first;
if (config_->key_is_in_local_partition(key)) {
const auto& value = key_value.second;
Record record;
bool found = storage_->Read(key_value.first, record);
if (!found) {
CHECK(master_metadata.contains(key))
<< "Master metadata for key \"" << key << "\" is missing";
record.metadata = master_metadata.at(key);
}
record.value = value;
storage_->Write(key, record);
}
}
for (const auto& key : txn->delete_set()) {
if (config_->key_is_in_local_partition(key)) {
storage_->Delete(key);
}
}
break;
}
case Transaction::ProcedureCase::kRemaster: {
const auto& key = txn->write_set().begin()->first;
if (config_->key_is_in_local_partition(key)) {
auto txn_key_metadata = txn->internal().master_metadata().at(key);
Record record;
bool found = storage_->Read(key, record);
if (!found) {
// TODO: handle case where key is deleted
LOG(FATAL) << "Remastering key that does not exist: " << key;
}
record.metadata = Metadata(txn->remaster().new_master(), txn_key_metadata.counter() + 1);
storage_->Write(key, record);
}
break;
}
default:
LOG(FATAL) << "Procedure is not set";
}
state.phase = TransactionState::Phase::FINISH;
}
void Worker::Finish(TxnId txn_id) {
auto txn = txn_states_[txn_id].txn_holder->transaction();
RecordTxnEvent(
config_,
txn->mutable_internal(),
TransactionEvent::EXIT_WORKER);
// This must happen before the sending to scheduler below. Otherwise,
// the scheduler may destroy the transaction holder before we can
// send the transaction to the server.
SendToCoordinatingServer(txn_id);
// Notify the scheduler that we're done
auto res = AcquireResponse();
res.get()->mutable_worker()->set_txn_id(txn_id);
Send(*res.get(), kSchedulerChannel);
// Done with this txn. Remove it from the state map
txn_states_.erase(txn_id);
VLOG(3) << "Finished with txn " << txn_id;
}
void Worker::PreAbort(TxnId txn_id) {
NotifyOtherPartitions(txn_id);
auto& state = txn_states_[txn_id];
auto txn = state.txn_holder->transaction();
RecordTxnEvent(
config_,
txn->mutable_internal(),
TransactionEvent::EXIT_WORKER);
SendToCoordinatingServer(txn_id);
// The worker owns this holder for the case of pre-
// aborted txn so it must delete it
delete state.txn_holder;
state.txn_holder = nullptr;
txn_states_.erase(txn_id);
VLOG(3) << "Finished with txn " << txn_id;
}
void Worker::NotifyOtherPartitions(TxnId txn_id) {
auto& state = txn_states_[txn_id];
auto txn_holder = state.txn_holder;
if (txn_holder->active_partitions().empty()) {
return;
}
auto txn = txn_holder->transaction();
auto local_partition = config_->local_partition();
auto local_replica = config_->local_replica();
auto aborted = txn->status() == TransactionStatus::ABORTED;
// Send abort result and local reads to all remote active partitions
auto request = AcquireRequest();
auto rrr = request.get()->mutable_remote_read_result();
rrr->set_txn_id(txn_id);
rrr->set_partition(local_partition);
rrr->set_will_abort(aborted);
if (!aborted) {
auto reads_to_be_sent = rrr->mutable_reads();
for (auto& key_value : txn->read_set()) {
(*reads_to_be_sent)[key_value.first] = key_value.second;
}
}
for (auto p : txn_holder->active_partitions()) {
if (p != local_partition) {
auto machine_id = config_->MakeMachineId(local_replica, p);
Send(*request.get(), kSchedulerChannel, std::move(machine_id));
}
}
}
void Worker::SendToCoordinatingServer(TxnId txn_id) {
auto& state = txn_states_[txn_id];
auto txn_holder = state.txn_holder;
auto txn = txn_holder->transaction();
// Send the txn back to the coordinating server
auto req = AcquireRequest();
auto completed_sub_txn = req.get()->mutable_completed_subtxn();
completed_sub_txn->set_allocated_txn(txn);
completed_sub_txn->set_partition(config_->local_partition());
for (auto p : txn_holder->involved_partitions()) {
completed_sub_txn->add_involved_partitions(p);
}
Send(*req.get(), kServerChannel, txn->internal().coordinating_server());
completed_sub_txn->release_txn();
}
} // namespace slog | 32.482916 | 101 | 0.664165 | [
"object"
] |
ddf42fe4e0705705e542ee7aaaba7503d1281fb1 | 5,268 | cpp | C++ | Projet Piscine ING2/arrete.cpp | clemoctohub/Projet-ING2-Piscine | 4de3ceb0608a35b41082a4e46401d75cab501a0f | [
"MIT"
] | null | null | null | Projet Piscine ING2/arrete.cpp | clemoctohub/Projet-ING2-Piscine | 4de3ceb0608a35b41082a4e46401d75cab501a0f | [
"MIT"
] | null | null | null | Projet Piscine ING2/arrete.cpp | clemoctohub/Projet-ING2-Piscine | 4de3ceb0608a35b41082a4e46401d75cab501a0f | [
"MIT"
] | null | null | null | #include "arrete.h"
#include <iostream>
#include <string>
#include "math.h"
#include <cmath>
#include <vector>
Arrete::Arrete(Sommet* s1, Sommet* s2, int indice, int poids)
:m_s1{s1},m_s2{s2},m_indice{indice},m_poids{poids}
{
}
void Arrete::afficher(Svgfile &svgout, int orientation) /// recoit le fichier svg afin de faire l'affichage dedans ainsi que l'orientation
{
std::cout<<m_indice<<"/ sommet 1 :"<<m_s1->GetIndice()<<" / sommet 2 : "<<m_s2->GetIndice()<<" / poids : "<<m_poids<<std::endl;
if (orientation==0) /// si le graphe n'est pas oriente
{
svgout.addLine(m_s1->GetX()*100, m_s1->GetY()*100, m_s2->GetX()*100, m_s2->GetY()*100, "blue"); /// on dessine l'arete
}
else /// si le graphe est oriente
{
svgout.addLine(m_s1->GetX()*100, m_s1->GetY()*100, m_s2->GetX()*100, m_s2->GetY()*100, "blue"); /// on dessine l'arete
double x2,y2,angle=0;
x2=(m_s2->GetX()*100)-(m_s1->GetX()*100); /// on "deplace" le vecteur de l'arete pour le mettre a 0
y2=(m_s2->GetY()*100)-(m_s1->GetY()*100);
angle=acos((100*x2)/(100*sqrt(x2*x2+y2*y2))); /// on calcule l'angle entre le vecteur et l'axe des abcisses
angle=angle-3.14159265359; /// on enleve pi afin de calculer l'angle complementaire de ce dernier
if (y2<0) /// si l'arete est orientee vers le haut
{
angle=-angle; /// on prend l'inverse de son angle
}
///pour les valeurs des 2 points manquant du triangle pour dessiner la fleche, on enleve/rajoute un peut de valeur a l'angle afin d'avoir l'ecart entre les 2 points
svgout.addTriangle(m_s2->GetX()*100, m_s2->GetY()*100, (m_s2->GetX()*100)+12*cos(angle-3.14159265359/8), (m_s2->GetY()*100)+12*sin(angle-3.14159265359/8), (m_s2->GetX()*100)+12*cos(angle+3.14159265359/8), (m_s2->GetY()*100)+12*sin(angle+3.14159265359/8), "blue");
}
}
void Arrete::afficher() ///affiche seulement le poids
{
std::cout<<m_poids<<std::endl;
}
void Arrete::afficherIndice() ///affiche l'ensemble des indices d'une arete
{
std::cout<<m_indice<<"/ sommet 1 :"<<m_s1->GetIndice()<<" / sommet 2 : "<<m_s2->GetIndice()<<" / poids : "<<m_poids<<std::endl;
}
void Arrete::set_poids(int poids) ///change le poids
{
m_poids = poids;
}
void Arrete::set_indice(int indice)///modifie l'indice d'une arete
{
m_indice = indice;
}
int Arrete::calculdegre(Sommet* sommet, int orientation)
{
if (orientation == 0) /// si le graphe est oriente ou non, le calcul de degre ne se fait pas de la meme maniere
{
if (m_s1->GetIndice()==sommet->GetIndice() || m_s2->GetIndice()==sommet->GetIndice()) /// si le graphe n'est pas oriente, on ajoute un degre a chaque fois que l'un des deux sommets d'une arete est le meme que le sommet en question
return 1;
else
return 0;
}
if (orientation == 1)
{
if (m_s1->GetIndice()==sommet->GetIndice()) /// si le graphe est oriente, on ajoute un degres a chaque fois que le sommet d'arrive (le deuxieme) est le meme que le sommet en question
return 1;
else
return 0;
} /// si la methode return 1, on ajoute un degre, si elle return 0, on n'en ajoute pas
return 0;
}
bool Arrete::check_Sommets(Sommet* s1,Sommet* s2,int orientation) /// permet de verifier l'existance d'une arete
{
if(orientation==0) /// si le graphe n'est pas oriente
{ ///on verifie si l'arete qui appelle ce ssprg relie bien les deux sommets envoye. Dans ce cas on verifie le tableau d'adjacence dans les deux sens
if((s1->GetIndice()==m_s1->GetIndice() && s2->GetIndice()==m_s2->GetIndice())
|| (s1->GetIndice()==m_s2->GetIndice() && s2->GetIndice()==m_s1->GetIndice()))
return true;
else return false;
}
else if(orientation==1) /// si le graphe est oriente
{///on fait la meme chose mais on verifie dans un seul sens car l'arete ne va que dans un sens
if(s1->GetIndice()==m_s1->GetIndice() && s2->GetIndice()==m_s2->GetIndice())
return true;
else return false;
}
return true;
}
void Arrete::effacer_adj(std::vector <int> m_adjacent[100]) /// efface les adjacents d'une arete
{
for(size_t i=0; i<m_adjacent[m_s1->GetIndice()].size(); ++i)
if(m_adjacent[m_s1->GetIndice()][i]==m_s2->GetIndice())
m_adjacent[m_s1->GetIndice()].erase(m_adjacent[m_s1->GetIndice()].begin()+i);
for(size_t i=0; i<m_adjacent[m_s2->GetIndice()].size(); ++i)
if(m_adjacent[m_s2->GetIndice()][i]==m_s1->GetIndice())
m_adjacent[m_s2->GetIndice()].erase(m_adjacent[m_s2->GetIndice()].begin()+i);
}
void Arrete::add_adjacent(std::vector <int> m_adjacent[100],Arrete* aretes) /// ajoute les adjacents lorsqu'il y a une arete
{
for(size_t i=0; i<m_adjacent[m_s1->GetIndice()].size(); ++i)
if(m_adjacent[m_s1->GetIndice()][i]==m_s2->GetIndice())
m_adjacent[m_s1->GetIndice()].insert(m_adjacent[m_s1->GetIndice()].begin()+i,aretes->get_indice());
for(size_t i=0; i<m_adjacent[m_s2->GetIndice()].size(); ++i)
if(m_adjacent[m_s2->GetIndice()][i]==m_s1->GetIndice())
m_adjacent[m_s2->GetIndice()].insert(m_adjacent[m_s2->GetIndice()].begin()+i,aretes->get_indice());
}
| 45.413793 | 271 | 0.636674 | [
"vector"
] |
ddffa67a91cf4689cf4c0ffb17e83987ca13f92b | 779 | cpp | C++ | algorithms/cpp/150.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | 3 | 2016-10-01T10:15:09.000Z | 2017-07-09T02:53:36.000Z | algorithms/cpp/150.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | null | null | null | algorithms/cpp/150.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <stack>
using namespace std;
class Solution
{
public:
int evalRPN(vector<string>& tokens)
{
stack<int> s;
for ( auto item : tokens )
{
if ( item.size() > 1 || isdigit(item[0]) )
s.push(stoi(item));
else
{
int b = s.top(); s.pop();
int a = s.top(); s.pop();
switch ( item[0] )
{
case '+': s.push(a+b); break;
case '-': s.push(a-b); break;
case '*': s.push(a*b); break;
case '/': s.push(a/b); break;
}
}
}
return s.top();
}
};
int main()
{
return 0;
}
| 21.054054 | 54 | 0.376123 | [
"vector"
] |
fb01ff6c67e84ea476e3d62ad876012f189a0107 | 1,408 | hpp | C++ | implementations/Metal/renderpass.hpp | rsayers/abstract-gpu | 48176fcb88bde7d56de662c9e49d3d0e562819e1 | [
"MIT"
] | 41 | 2016-03-25T18:14:37.000Z | 2022-01-20T11:16:52.000Z | implementations/Metal/renderpass.hpp | rsayers/abstract-gpu | 48176fcb88bde7d56de662c9e49d3d0e562819e1 | [
"MIT"
] | 4 | 2016-05-05T22:08:01.000Z | 2021-12-10T13:06:55.000Z | implementations/Metal/renderpass.hpp | rsayers/abstract-gpu | 48176fcb88bde7d56de662c9e49d3d0e562819e1 | [
"MIT"
] | 9 | 2016-05-23T01:51:25.000Z | 2021-08-21T15:32:37.000Z | #ifndef AGPU_METAL_RENDERPASS_HPP
#define AGPU_METAL_RENDERPASS_HPP
#include "device.hpp"
#include <vector>
namespace AgpuMetal
{
class AMtlRenderPass : public agpu::renderpass
{
public:
AMtlRenderPass(const agpu::device_ref &device);
~AMtlRenderPass();
static agpu::renderpass_ref create(const agpu::device_ref &device, agpu_renderpass_description *description);
MTLRenderPassDescriptor *createDescriptor(const agpu::framebuffer_ref &framebuffer);
virtual agpu_error setDepthStencilClearValue(agpu_depth_stencil_value value) override;
virtual agpu_error setColorClearValue(agpu_uint attachment_index, agpu_color4f value) override;
virtual agpu_error setColorClearValueFrom(agpu_uint attachment_index, agpu_color4f *value) override;
virtual agpu_error getColorAttachmentFormats(agpu_uint* color_attachment_count, agpu_texture_format* formats) override;
virtual agpu_texture_format getDepthStencilAttachmentFormat() override;
virtual agpu_uint getSampleCount() override;
virtual agpu_uint getSampleQuality() override;
agpu::device_ref device;
bool hasDepthStencil;
bool hasStencil;
agpu_renderpass_depth_stencil_description depthStencil;
std::vector<agpu_renderpass_color_attachment_description> colorAttachments;
agpu_uint sampleCount;
agpu_uint sampleQuality;
};
} // End of namespace AgpuMetal
#endif //AGPU_METAL_RENDERPASS_HPP
| 36.102564 | 123 | 0.814631 | [
"vector"
] |
fb02dfbe7219a1762ecfa7e08d862f988c0f18a4 | 2,908 | cpp | C++ | samples/cpp/mao/90_SurfDescriptorExtractor.cpp | chenghyang2001/opencv-2.4.11 | 020af901059236c702da580048d25e9fe082e8f8 | [
"BSD-3-Clause"
] | null | null | null | samples/cpp/mao/90_SurfDescriptorExtractor.cpp | chenghyang2001/opencv-2.4.11 | 020af901059236c702da580048d25e9fe082e8f8 | [
"BSD-3-Clause"
] | null | null | null | samples/cpp/mao/90_SurfDescriptorExtractor.cpp | chenghyang2001/opencv-2.4.11 | 020af901059236c702da580048d25e9fe082e8f8 | [
"BSD-3-Clause"
] | 1 | 2020-07-22T07:08:24.000Z | 2020-07-22T07:08:24.000Z |
#include <stdio.h>
//---------------------------------【頭文件、命名空間包含部分】----------------------------
// 描述:包含程序所使用的頭文件和命名空間
//------------------------------------------------------------------------------------------------
#include "opencv2/core/core.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/nonfree/nonfree.hpp>
#include<opencv2/legacy/legacy.hpp>
#include <iostream>
using namespace cv;
using namespace std;
//-----------------------------------【全局函數宣告部分】--------------------------------------
// 描述:全局函數的宣告
//-----------------------------------------------------------------------------------------------
static void ShowHelpText( );//輸出說明文字
//-----------------------------------【main( )函數】--------------------------------------------
// 描述:控制臺應用程序的入口函數,我們的程序從這里開始執行
//-----------------------------------------------------------------------------------------------
int main( )
{
//【0】改變console字體顏色
system("color 1F");
//【0】顯示歡迎和說明文字
ShowHelpText( );
//【1】載入素材圖
Mat srcImage1 = imread("/home/peter/opencv-2.4.11/samples/cpp/mao/1.jpg",1);
// Mat srcImage2 = imread("2.jpg",1);
Mat srcImage2 = imread("/home/peter/opencv-2.4.11/samples/cpp/mao/2.jpg",1);
if( !srcImage1.data || !srcImage2.data )
{ printf("讀取圖形錯誤,請確定目錄下是否有imread函數指定的圖形存在~! \n"); return false; }
//【2】使用SURF算子檢測關鍵點
int minHessian = 700;//SURF算法中的hessian閾值
SurfFeatureDetector detector( minHessian );//定義一個SurfFeatureDetector(SURF) 特徵檢測類別對象
std::vector<KeyPoint> keyPoint1, keyPoints2;//vector模板類別,存放任意類別型的動態數組
//【3】使用detect函數檢測出SURF特徵關鍵點,儲存在vector宿主中
detector.detect( srcImage1, keyPoint1 );
detector.detect( srcImage2, keyPoints2 );
//【4】計算描述表(特徵向量)
SurfDescriptorExtractor extractor;
Mat descriptors1, descriptors2;
extractor.compute( srcImage1, keyPoint1, descriptors1 );
extractor.compute( srcImage2, keyPoints2, descriptors2 );
//【5】使用BruteForce進行比對
// 實例化一個比對器
BruteForceMatcher< L2<float> > matcher;
std::vector< DMatch > matches;
//比對兩幅圖中的描述子(descriptors)
matcher.match( descriptors1, descriptors2, matches );
//【6】繪製從兩個圖像中比對出的關鍵點
Mat imgMatches;
drawMatches( srcImage1, keyPoint1, srcImage2, keyPoints2, matches, imgMatches );//進行繪製
//【7】顯示效果圖
imshow("比對圖", imgMatches );
moveWindow("比對圖", 100,100 );
waitKey(0);
return 0;
}
//-----------------------------------【ShowHelpText( )函數】----------------------------------
// 描述:輸出一些說明訊息
//----------------------------------------------------------------------------------------------
static void ShowHelpText()
{
//輸出歡迎訊息和OpenCV版本
printf("\n\n\t\t\t非常感謝購買《OpenCV3程式設計入門》一書!\n");
printf("\n\n\t\t\t此為本書OpenCV2版的第90個配套範例程序\n");
printf("\n\n\t\t\t 現在使用的OpenCV版本為:" CV_VERSION );
printf("\n\n ----------------------------------------------------------------------------\n");
//輸出說明訊息
printf( "\n\n\n\t歡迎來到【SURF特徵描述】範例程序\n\n");
}
| 32.311111 | 98 | 0.528198 | [
"vector"
] |
fb0e2a79e3a7b446e5d4b7cc98c2c1cd2044e7d9 | 971 | cpp | C++ | codeforces/round-292/div-2/drazil_and_his_happy_friends.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-07-16T01:46:38.000Z | 2020-07-16T01:46:38.000Z | codeforces/round-292/div-2/drazil_and_his_happy_friends.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | null | null | null | codeforces/round-292/div-2/drazil_and_his_happy_friends.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-05-27T14:30:43.000Z | 2020-05-27T14:30:43.000Z | #include <algorithm>
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
using namespace std;
inline
void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
int main()
{
use_io_optimizations();
unsigned int boys;
unsigned int girls;
cin >> boys >> girls;
unsigned int gcd {__gcd(boys, girls)};
vector<bool> happy(gcd);
unsigned int happy_boys;
cin >> happy_boys;
for (unsigned int i {0}; i < happy_boys; ++i)
{
unsigned int boy;
cin >> boy;
happy[boy % gcd] = true;
}
unsigned int happy_girls;
cin >> happy_girls;
for (unsigned int i {0}; i < happy_girls; ++i)
{
unsigned int girl;
cin >> girl;
happy[girl % gcd] = true;
}
for (auto is_happy : happy)
{
if (!is_happy)
{
cout << "No\n";
return 0;
}
}
cout << "Yes\n";
return 0;
}
| 15.66129 | 50 | 0.53862 | [
"vector"
] |
fb1af992f3e534e201c1a5a21a8c6bccbd5ffd22 | 1,718 | cpp | C++ | Dynamic_Programming/array_description.cpp | DannyAntonelli/CSES-Problem-Set | 599b5efb2d7efb9b7e1bfde3142702dc5d0c3988 | [
"MIT"
] | null | null | null | Dynamic_Programming/array_description.cpp | DannyAntonelli/CSES-Problem-Set | 599b5efb2d7efb9b7e1bfde3142702dc5d0c3988 | [
"MIT"
] | null | null | null | Dynamic_Programming/array_description.cpp | DannyAntonelli/CSES-Problem-Set | 599b5efb2d7efb9b7e1bfde3142702dc5d0c3988 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define RFOR(i, a, b) for (int i = (a); i > (b); --i)
#define ALL(x) x.begin(), x.end()
#define F first
#define S second
#define PB push_back
#define MP make_pair
using namespace std;
using ll = long long;
using ld = long double;
typedef vector<int> vi;
typedef pair<int, int> pi;
void fast_io() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
int dp[100000][101];
int main() {
fast_io();
const int MOD = 1e9 + 7;
int n, m;
cin >> n >> m;
vi x(n);
FOR (i, 0, n) cin >> x[i];
if (x[0]) {
dp[0][x[0]] = 1;
}
else {
FOR (i, 1, m+1) dp[0][i] = 1;
}
FOR (i, 1, n) {
if (x[i]) {
dp[i][x[i]] += dp[i-1][x[i]];
dp[i][x[i]] %= MOD;
if (x[i] - 1 > 0) {
dp[i][x[i]] += dp[i-1][x[i]-1];
dp[i][x[i]] %= MOD;
}
if (x[i] + 1 <= m) {
dp[i][x[i]] += dp[i-1][x[i]+1];
dp[i][x[i]] %= MOD;
}
}
else {
FOR (j, 1, m+1) {
if (dp[i-1][j]) {
dp[i][j] += dp[i-1][j];
dp[i][j] %= MOD;
if (j - 1 > 0) {
dp[i][j-1] += dp[i-1][j];
dp[i][j-1] %= MOD;
}
if (j + 1 <= m) {
dp[i][j+1] += dp[i-1][j];
dp[i][j+1] %= MOD;
}
}
}
}
}
int res = 0;
FOR (i, 0, m+1) res = (res + dp[n-1][i]) % MOD;
cout << res;
return 0;
} | 21.475 | 53 | 0.331781 | [
"vector"
] |
fb1e363a65c27c45f59051c123b134e739ca231f | 2,416 | cpp | C++ | Examples/Basics/Offscreen/Scene/OffscreenScene.cpp | SuperflyJon/VulkanPlayground | 891b88227b66fc1e933ff77c1603e5d685d89047 | [
"MIT"
] | 2 | 2021-01-25T16:59:56.000Z | 2021-02-14T21:11:05.000Z | Examples/Basics/Offscreen/Scene/OffscreenScene.cpp | SuperflyJon/VulkanPlayground | 891b88227b66fc1e933ff77c1603e5d685d89047 | [
"MIT"
] | null | null | null | Examples/Basics/Offscreen/Scene/OffscreenScene.cpp | SuperflyJon/VulkanPlayground | 891b88227b66fc1e933ff77c1603e5d685d89047 | [
"MIT"
] | 1 | 2021-04-23T10:20:53.000Z | 2021-04-23T10:20:53.000Z | #include <VulkanPlayground\Includes.h>
class OffscreenSceneApp : public VulkanApplication3DLight
{
std::vector<float> quadVertices = {
-10.0f, 0.0f, -10.0f, 0.0f, 1.0f, 10.0f, 0.0f, 10.0f, 1.0f, 0.0f, 10.0f, 0.0f, -10.0f, 1.0f, 1.0f,
10.0f, 0.0f, 10.0f, 1.0f, 0.0f, -10.0f, 0.0f, -10.0f, 0.0f, 1.0f, -10.0f, 0.0f, 10.0f, 0.0f, 0.0f };
void ResetScene() override
{
CalcPositionMatrix({ 0.0f, 180.0f, 0.0f }, { -1.2f, -1.4f, 0 }, 0, 30, model.GetModelSize());
SetupLighting({ -1.7f, 0.5f, 1.0f }, 0.2f, 0.4f, 0.7f, 32.0f, model.GetModelSize());
}
void SetupObjects(VulkanSystem& system, RenderPass& renderPass, VkExtent2D workingExtent) override
{
model.SetTranslation({ 0, (10.0f / 2.0f) * .95f, 0 }); // Move dragon up so it's on the y axis
model.LoadToGpu(system, VulkanPlayground::GetModelFile("Basics", "chinesedragon.dae"), Attribs::PosNormCol);
system.CreateGpuBuffer(system, planeBuffer, quadVertices, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, "Vertices");
descriptor.AddUniformBuffer(system, 0, mvpUBO, "MVP");
descriptor.AddUniformBuffer(system, 2, lightUBO, "Lighting", VK_SHADER_STAGE_FRAGMENT_BIT);
CreateDescriptor(system, descriptor, "Main");
pipeline.SetupVertexDescription(Attribs::PosNormCol);
pipeline.LoadShader(system, "offScene");
CreatePipeline(system, renderPass, pipeline, descriptor, workingExtent, "Main");
planeDescriptor.AddUniformBuffer(system, 0, mvpUBO, "MVP");
planeDescriptor.AddTexture(system, 1, texture, VulkanPlayground::GetModelFile("Basics", "darkmetal_bc3_unorm.ktx"), VK_FORMAT_BC3_UNORM_BLOCK);
CreateDescriptor(system, planeDescriptor, "Plane");
planePipeline.SetupVertexDescription(Attribs::PosTex);
planePipeline.LoadShader(system, "quad");
CreatePipeline(system, renderPass, planePipeline, planeDescriptor, workingExtent, "Plane");
};
void DrawScene(VkCommandBuffer commandBuffer) override
{
pipeline.Bind(commandBuffer, descriptor);
model.Draw(commandBuffer);
planePipeline.Bind(commandBuffer, planeDescriptor.GetDescriptorSet());
vkCmdBindVertexBuffers(commandBuffer, 0, 1, &planeBuffer.GetBuffer(), VulkanPlayground::zeroOffset);
vkCmdDraw(commandBuffer, Attribs::NumVertices(quadVertices, Attribs::PosTex), 1, 0, 0);
}
private:
Model model;
Buffer planeBuffer;
Descriptor descriptor, planeDescriptor;
Pipeline pipeline, planePipeline;
Texture texture;
};
DECLARE_APP(OffscreenScene)
| 42.385965 | 145 | 0.737997 | [
"vector",
"model"
] |
fb337ac8748817a47ee0021f273e8f81c48c88f5 | 6,990 | cpp | C++ | lib/render/DVRLookup.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | lib/render/DVRLookup.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | lib/render/DVRLookup.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | //--DVRLookup.h --------------------------------------------------------------
//
// Copyright (C) 2005 Kenny Gruchalla. All rights reserved.
//
// A derived DVRTexture3d providing a pixel map for the color lookup.
//
//----------------------------------------------------------------------------
#include <GL/glew.h>
#ifdef Darwin
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#else
#include <GL/gl.h>
#include <GL/glu.h>
#endif
#include <qgl.h>
#include "DVRLookup.h"
#include "TextureBrick.h"
using namespace VAPoR;
//----------------------------------------------------------------------------
// Constructor
//----------------------------------------------------------------------------
DVRLookup::DVRLookup(GLenum type, int nthreads) :
DVRTexture3d(GL_RGBA, GL_COLOR_INDEX, type, nthreads),
_colormap(NULL)
{
switch (type) {
case GL_UNSIGNED_BYTE:
case GL_BYTE:
_colormapsize = 256;
break;
case GL_UNSIGNED_SHORT:
case GL_SHORT:
_colormapsize = 256*2;
break;
case GL_UNSIGNED_INT:
case GL_INT:
case GL_FLOAT:
_colormapsize = 256*4;
break;
default:
assert(type == GL_UNSIGNED_BYTE);
break;
}
if (GLEW_NV_fragment_program)
{
_maxTexture /= 4;
}
}
//----------------------------------------------------------------------------
// Destructor
//----------------------------------------------------------------------------
DVRLookup::~DVRLookup()
{
}
//----------------------------------------------------------------------------
//
//----------------------------------------------------------------------------
int DVRLookup::GraphicsInit()
{
initColormap();
return 0;
}
//----------------------------------------------------------------------------
//
//----------------------------------------------------------------------------
int DVRLookup::SetRegion(const RegularGrid *rg, const float range[2], int num)
{
//
// Construct the color mapping
//
glPixelMapfv(GL_PIXEL_MAP_I_TO_R, _colormapsize, _colormap+0*_colormapsize);
glPixelMapfv(GL_PIXEL_MAP_I_TO_G, _colormapsize, _colormap+1*_colormapsize);
glPixelMapfv(GL_PIXEL_MAP_I_TO_B, _colormapsize, _colormap+2*_colormapsize);
glPixelMapfv(GL_PIXEL_MAP_I_TO_A, _colormapsize, _colormap+3*_colormapsize);
glPixelTransferi(GL_MAP_COLOR, GL_TRUE);
//
// Initialize the geometry extents & texture
//
return DVRTexture3d::SetRegion(rg, range, num);
}
//----------------------------------------------------------------------------
//
//----------------------------------------------------------------------------
void DVRLookup::loadTexture(TextureBrick *brick)
{
glBindTexture(GL_TEXTURE_3D, brick->handle());
brick->load();
printOpenGLError();
}
//----------------------------------------------------------------------------
//
//----------------------------------------------------------------------------
int DVRLookup::Render()
{
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_LINE);
glEnable(GL_TEXTURE_3D);
glPixelTransferi(GL_MAP_COLOR, GL_TRUE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
calculateSampling();
renderBricks();
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_3D);
glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
return 0;
}
//----------------------------------------------------------------------------
// Set the color table used to render the volume without any opacity
// correction.
//----------------------------------------------------------------------------
void DVRLookup::SetCLUT(const float ctab[256][4])
{
for (int i=0; i<256; i++) {
int len = _colormapsize / 256;
for (int j=0; j<len; j++) {
_colormap[i*len + j + (0*_colormapsize)] = ctab[i][0];
_colormap[i*len + j + (1*_colormapsize)] = ctab[i][1];
_colormap[i*len + j + (2*_colormapsize)] = ctab[i][2];
_colormap[i*len + j + (3*_colormapsize)] = ctab[i][3];
}
}
//
// Construct the color mapping
//
glPixelMapfv(GL_PIXEL_MAP_I_TO_R, _colormapsize, _colormap+0*_colormapsize);
glPixelMapfv(GL_PIXEL_MAP_I_TO_G, _colormapsize, _colormap+1*_colormapsize);
glPixelMapfv(GL_PIXEL_MAP_I_TO_B, _colormapsize, _colormap+2*_colormapsize);
glPixelMapfv(GL_PIXEL_MAP_I_TO_A, _colormapsize, _colormap+3*_colormapsize);
glPixelTransferi(GL_MAP_COLOR, GL_TRUE);
//
// Reload the 3D texture to pickup the colormap.
// Is there a better (i.e., faster) way to do this?
//
for (int i=0; i<_bricks.size(); i++)
{
loadTexture(_bricks[i]);
}
glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
printOpenGLError();
glFlush();
}
//----------------------------------------------------------------------------
// Set the color table used to render the volume applying an opacity
// correction.
//----------------------------------------------------------------------------
void DVRLookup::SetOLUT(const float atab[256][4], const int numRefinements)
{
//
// Compute the sampling distance and rate
//
calculateSampling();
//
// Calculate opacity correction. Delta is 1 for the fineest refinement,
// multiplied by 2^n (the sampling distance)
//
double delta = 2.0/_samplingRate * (double)(1<<numRefinements);
for(int i=0; i<256; i++)
{
double opac = atab[i][3];
opac = 1.0 - pow((1.0 - opac), delta);
if (opac > 1.0)
{
opac = 1.0;
}
int len = _colormapsize / 256;
for (int j=0; j<len; j++) {
_colormap[i*len + j + (0*_colormapsize)] = atab[i][0];
_colormap[i*len + j + (1*_colormapsize)] = atab[i][1];
_colormap[i*len + j + (2*_colormapsize)] = atab[i][2];
_colormap[i*len + j + (3*_colormapsize)] = opac;
}
}
//
// Construct the color mapping
//
glPixelMapfv(GL_PIXEL_MAP_I_TO_R, _colormapsize, _colormap+0*_colormapsize);
glPixelMapfv(GL_PIXEL_MAP_I_TO_G, _colormapsize, _colormap+1*_colormapsize);
glPixelMapfv(GL_PIXEL_MAP_I_TO_B, _colormapsize, _colormap+2*_colormapsize);
glPixelMapfv(GL_PIXEL_MAP_I_TO_A, _colormapsize, _colormap+3*_colormapsize);
glPixelTransferi(GL_MAP_COLOR, GL_TRUE);
//
// Reload the 3D texture to pickup the colormap.
// Is there a better (i.e., faster) way to do this?
//
for (int i=0; i<_bricks.size(); i++)
{
loadTexture(_bricks[i]);
}
glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
printOpenGLError();
glFlush();
}
//----------------------------------------------------------------------------
// Initalize the the 1D colormap
//----------------------------------------------------------------------------
void DVRLookup::initColormap()
{
//
// Create the colormap table
//
_colormap = new float[_colormapsize*4];
glPixelMapfv(GL_PIXEL_MAP_I_TO_R, _colormapsize, _colormap+0*_colormapsize);
glPixelMapfv(GL_PIXEL_MAP_I_TO_G, _colormapsize, _colormap+1*_colormapsize);
glPixelMapfv(GL_PIXEL_MAP_I_TO_B, _colormapsize, _colormap+2*_colormapsize);
glPixelMapfv(GL_PIXEL_MAP_I_TO_A, _colormapsize, _colormap+3*_colormapsize);
glFlush();
}
| 26.781609 | 78 | 0.544635 | [
"geometry",
"render",
"3d"
] |
fb36cb91fe5b2f78db62a71aa4017eb64fff00df | 16,678 | cpp | C++ | performance/main.cpp | bovine/metaf | 887f40a4ef0001464c374cdd442a1a14b988417f | [
"MIT"
] | null | null | null | performance/main.cpp | bovine/metaf | 887f40a4ef0001464c374cdd442a1a14b988417f | [
"MIT"
] | null | null | null | performance/main.cpp | bovine/metaf | 887f40a4ef0001464c374cdd442a1a14b988417f | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2018-2020 Nick Naumenko (https://gitlab.com/nnaumenko)
* All rights reserved.
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#include "metaf.hpp"
#include "testdata_real.h"
#include <iostream>
#include <chrono>
#include <algorithm>
#include <utility>
#include <functional>
#include <regex>
#include <sstream>
using namespace std;
///////////////////////////////////////////////////////////////////////////////
/// Get an index from type included in variant type at compile time.
/// @tparam V Variant type to search for index.
/// @tparam T Type which index must be returned.
/// @return Index of type T in variant V; or variant size if V does not contain T.
template<typename V, typename T, size_t I = 0>
constexpr size_t variant_index() {
if constexpr (I >= variant_size_v<V>) {
return variant_size_v<V>;
} else {
if constexpr (is_same_v<variant_alternative_t<I, V>, T>) {
return I;
} else {
return variant_index<V, T, I + 1>();
}
}
}
///////////////////////////////////////////////////////////////////////////////
/// @details MUST be modified accordingly if Group is modified
/// @param index Value obtained from index() method of Group variant.
/// @return Name of the group in human-readable form.
string_view groupName (size_t index) {
switch (index) {
case variant_index<metaf::Group, metaf::FixedGroup>():
return "FixedGroup";
case variant_index<metaf::Group, metaf::LocationGroup>():
return "LocationGroup";
case variant_index<metaf::Group, metaf::ReportTimeGroup>():
return "ReportTimeGroup";
case variant_index<metaf::Group, metaf::TrendGroup>():
return "TrendGroup";
case variant_index<metaf::Group, metaf::WindGroup>():
return "WindGroup";
case variant_index<metaf::Group, metaf::VisibilityGroup>():
return "VisibilityGroup";
case variant_index<metaf::Group, metaf::CloudGroup>():
return "CloudGroup";
case variant_index<metaf::Group, metaf::WeatherGroup>():
return "WeatherGroup";
case variant_index<metaf::Group, metaf::TemperatureGroup>():
return "TemperatureGroup";
case variant_index<metaf::Group, metaf::TemperatureForecastGroup>():
return "TemperatureForecastGroup";
case variant_index<metaf::Group, metaf::PressureGroup>():
return "PressureGroup";
case variant_index<metaf::Group, metaf::RunwayVisualRangeGroup>():
return "RunwayVisualRangeGroup";
case variant_index<metaf::Group, metaf::RunwayStateGroup>():
return "RunwayStateGroup";
case variant_index<metaf::Group, metaf::SecondaryLocationGroup>():
return "SecondaryLocationGroup";
case variant_index<metaf::Group, metaf::RainfallGroup>():
return "RainfallGroup";
case variant_index<metaf::Group, metaf::SeaSurfaceGroup>():
return "SeaSurfaceGroup";
case variant_index<metaf::Group, metaf::ColourCodeGroup>():
return "ColourCodeGroup";
case variant_index<metaf::Group, metaf::MinMaxTemperatureGroup>():
return "MinMaxTemperatureGroup";
case variant_index<metaf::Group, metaf::PrecipitationGroup>():
return "PrecipitationGroup";
case variant_index<metaf::Group, metaf::LayerForecastGroup>():
return "LayerForecastGroup";
case variant_index<metaf::Group, metaf::PressureTendencyGroup>():
return "PressureTendencyGroup";
case variant_index<metaf::Group, metaf::CloudTypesGroup>():
return "CloudTypesGroup";
case variant_index<metaf::Group, metaf::CloudLayersGroup>():
return "CloudLayersGroup";
case variant_index<metaf::Group, metaf::LightningGroup>():
return "LightningGroup";
case variant_index<metaf::Group, metaf::VicinityGroup>():
return "VicinityGroup";
case variant_index<metaf::Group, metaf::MiscGroup>():
return "MiscGroup";
case variant_index<metaf::Group, metaf::UnknownGroup>():
return "UnknownGroup";
default: return "UNDEFINED";
}
}
///////////////////////////////////////////////////////////////////////////////
/// Performance checker. Runs process() and displays performance stats.
class PerformanceCheckerBase {
public:
void run(ostream & output);
protected:
string_view getItemName() { return itemName; }
void setItemName(string_view name) { itemName = name; }
virtual int process() = 0;
private:
string_view itemName = "item";
};
void PerformanceCheckerBase::run(ostream & output) {
auto beginTime = chrono::system_clock::now();
auto itemCount = this->process();
auto endTime = chrono::system_clock::now();
if (!itemCount) {
output << "Test failed.\n";
return;
}
auto totalTime = chrono::microseconds(endTime - beginTime);
auto averageTimePerItem = chrono::microseconds(totalTime / itemCount);
if (totalTime.count()) {
output << totalTime.count() << " microseconds, ";
} else {
output << "<1 microsecond, ";
}
output << itemCount << " " << getItemName() << "s, ";
if (averageTimePerItem.count()) {
output << averageTimePerItem.count() << " microseconds per " << getItemName() << ", ";
} else {
output << "<1 microsecond per " << getItemName() << ", ";
}
static const auto microsecondsPerSecond = chrono::microseconds(chrono::seconds(1)).count();
if (averageTimePerItem.count()) {
output << microsecondsPerSecond / averageTimePerItem.count();
output << " " << getItemName() << "s per second";
} else {
output << ">" << microsecondsPerSecond << " " << getItemName() << "s per second";
}
output << "\n";
}
///////////////////////////////////////////////////////////////////////////////
/// Parses all METAR and TAF reports from testdata_real.cpp and displays
/// performance stats of parsing entire report.
class ParserPerformanceChecker : public PerformanceCheckerBase {
public:
ParserPerformanceChecker() { setItemName("report"); }
protected:
virtual int process();
};
int ParserPerformanceChecker::process() {
auto reportCount = 0;
for (const auto & data : testdata::realDataSet) {
if (!data.metar.empty()) {
metaf::Parser::parse(data.metar);
reportCount++;
}
if (!data.taf.empty()) {
metaf::Parser::parse(data.taf);
reportCount++;
}
}
return reportCount;
}
///////////////////////////////////////////////////////////////////////////////
/// Parses a number of groups and displays performance stats.
class GroupPerformanceChecker : public PerformanceCheckerBase {
public:
GroupPerformanceChecker(const vector<pair<string, metaf::ReportPart>> & srcs,
size_t idx) : sources(&srcs), index(idx) {setItemName("group"); }
protected:
virtual int process();
private:
const vector<pair<string, metaf::ReportPart>> * sources = nullptr;
size_t index = 0;
};
int GroupPerformanceChecker::process() {
int groupCount = 0;
static const auto testRepetitions = 300;
for (auto i = 0; i < testRepetitions; i++) {
for (auto src : *sources) {
const auto parseResult =
metaf::GroupParser::parse(get<string>(src),
get<metaf::ReportPart>(src),
metaf::missingMetadata);
(void)parseResult;
(void)index;
//if (parseResult.index() != index) return 0;
groupCount++;
}
}
return groupCount;
}
///////////////////////////////////////////////////////////////////////////////
/// Splits METAR or TAF report into individual groups and saves group string
/// along with associated report parts. The strings associated with a certain
/// group type can be acquired for use in tests.
class GroupsTestSet {
public:
GroupsTestSet();
size_t size() { return testSet.size(); }
const vector<pair<string, metaf::ReportPart>> & groupSet(size_t index) {
return testSet.at(index);
}
size_t totalGroups() {
auto count = 0;
for (const auto gs : testSet) { count += gs.size(); }
return count;
}
void displayStats(ostream & output);
void runPerformanceTests(ostream & output);
private:
vector <vector<pair<string, metaf::ReportPart>>> testSet;
void getGroupsFromReport(const std::string & report);
};
GroupsTestSet::GroupsTestSet() {
testSet.resize(variant_size_v<metaf::Group>);
for (const auto & data : testdata::realDataSet) {
if (!data.metar.empty()) getGroupsFromReport(data.metar);
if (!data.taf.empty()) getGroupsFromReport(data.taf);
}
}
void GroupsTestSet::getGroupsFromReport(const std::string & report)
{
const auto parseResult = metaf::Parser::parse(report);
for (const auto gr : parseResult.groups) {
std::istringstream iss(gr.rawString);
std::vector<std::string> individualGroups(
std::istream_iterator<std::string>{iss},
std::istream_iterator<std::string>());
for (const auto grstr : individualGroups) {
auto resultPair = make_pair(grstr, gr.reportPart);
const auto index = gr.group.index();
testSet.at(index).push_back(resultPair);
}
}
}
void GroupsTestSet::displayStats(ostream & output) {
output << "Group statistics\n";
for (auto i=0u; i<size(); i++) {
output << groupName(i) << ": " << groupSet(i).size() << " groups";
output << " (" << (100.0 * groupSet(i).size() / totalGroups()) << "%)";
output << "\n";
}
output << "Total: " << totalGroups() << " groups\n";
}
void GroupsTestSet::runPerformanceTests(ostream & output) {
for (auto i=0u; i<size(); i++) {
output << "Checking performance of " << groupName(i) << "\n";
GroupPerformanceChecker checker(groupSet(i), i);
checker.run(output);
output << "\n";
}
}
///////////////////////////////////////////////////////////////////////////////
void addGroup(const string & group, vector< pair<int, string> > & dst) {
for (auto i=0u; i<dst.size(); i++) {
if (get<string>(dst[i]) == group) {
//found group in dst, increment counter
auto count = get<int>(dst[i]);
auto temp = make_pair(++count, get<string>(dst[i]));
swap(dst[i], temp);
return;
}
}
//group not found in dst, add
dst.push_back(make_pair(1, group));
}
int addPlainTextGroups(const metaf::ParseResult & src, vector< pair<int, string> > & dst){
auto count = 0;
for (const auto & gr : src.groups) {
if (holds_alternative<metaf::UnknownGroup>(gr.group)) {
std::istringstream iss(gr.rawString);
std::istream_iterator<std::string> iter(iss);
while (iter != std::istream_iterator<std::string>()) {
addGroup(*iter, dst);
iter++;
count++;
}
}
}
return count;
}
void printFlaggedGroups(vector< pair<int, string> > flaggedGroups) {
cout << "Groups not recognised by parser, sorted by occurrence frequency:" << endl;
static const string occurredHeader = "Occurred";
static const string groupHeader = "Group text";
static const string separator = " ";
cout << occurredHeader << separator << groupHeader << endl;
for (const auto & data : flaggedGroups) {
static const auto minCountSize = occurredHeader.length();
string count = to_string(get<int>(data));
if (count.length() < minCountSize) {
count = string(minCountSize - count.length(), ' ') + count;
}
cout << count << separator << get<string>(data) << endl;
}
cout << endl;
}
void printFlaggedReports(vector< pair<int, string> > flaggedReports) {
cout << "Reports which contain groups not recognised by parser, sorted by number or groups:" << endl;
for (const auto & data : flaggedReports) {
cout << "Unrecognised groups: " << get<int>(data) << endl;
cout << "Report: " << get<string>(data) << endl << endl;
}
cout << endl;
}
void printGroupStats(int total, int unrecognised, const string & type) {
const auto recognised = total - unrecognised;
cout << "Total " << total << " " << type << " groups, ";
cout << unrecognised << " groups not recognised, ";
cout << recognised << " groups parsed successfully" << endl;
static const float roundingFactor = 100.0; //round to 2 digits after decimal point
const float unrecognisedPercent =
static_cast<int>((unrecognised * 100.0 / total) * roundingFactor) / roundingFactor;
const float recognisedPercent =
static_cast<int>((recognised * 100.0 / total) * roundingFactor) / roundingFactor;
cout << unrecognisedPercent << " % not recognised, ";
cout << recognisedPercent << " % parsed successfully";
cout << endl << endl;
}
void checkRecognisedGroups() {
cout << "Detecting non-recognised groups in testdata::realDataSet" << endl;
vector< pair<int, string> > flaggedGroups;
vector< pair<int, string> > flaggedReports;
auto metarTotalGroupCount = 0;
auto tafTotalGroupCount = 0;
auto metarUnrecognisedGroupCount = 0;
auto tafUnrecognisedGroupCount = 0;
for (const auto & data : testdata::realDataSet) {
if (!data.metar.empty()) {
const auto parseResult = metaf::Parser::parse(data.metar);
auto count = addPlainTextGroups(parseResult, flaggedGroups);
if (count) flaggedReports.push_back(make_pair(count, data.metar));
metarTotalGroupCount += parseResult.groups.size();
metarUnrecognisedGroupCount += count;
}
if (!data.taf.empty()) {
const auto parseResult = metaf::Parser::parse(data.taf);
auto count = addPlainTextGroups(parseResult, flaggedGroups);
if (count) flaggedReports.push_back(make_pair(count, data.taf));
tafTotalGroupCount += parseResult.groups.size();
tafUnrecognisedGroupCount += count;
}
}
printGroupStats(metarTotalGroupCount, metarUnrecognisedGroupCount, "METAR");
printGroupStats(tafTotalGroupCount, tafUnrecognisedGroupCount, "TAF");
sort(flaggedGroups.begin(), flaggedGroups.end(), greater< pair<int, string> >());
sort(flaggedReports.begin(), flaggedReports.end(), greater< pair<int, string> >());
printFlaggedGroups(flaggedGroups);
printFlaggedReports(flaggedReports);
}
///////////////////////////////////////////////////////////////////////////////
void printSize(string_view name, size_t size) {
cout << "Size of " << name << ' ' << size << endl;
}
void printDataSize(){
cout << "Data type sizes:" << endl;
printSize("Runway", sizeof(metaf::Runway));
printSize("MetafTime", sizeof(metaf::MetafTime));
printSize("Temperature", sizeof(metaf::Temperature));
printSize("Speed", sizeof(metaf::Speed));
printSize("Distance", sizeof(metaf::Distance));
printSize("Direction", sizeof(metaf::Direction));
printSize("Pressure", sizeof(metaf::Pressure));
printSize("Precipitation", sizeof(metaf::Precipitation));
printSize("SurfaceFriction", sizeof(metaf::SurfaceFriction));
printSize("WaveHeight", sizeof(metaf::WaveHeight));
printSize("WeatherPhenomena", sizeof(metaf::WeatherPhenomena));
cout << endl;
printSize("Group", sizeof(metaf::Group));
cout << endl;
cout << "Group sizes:" << endl;
printSize(groupName(0), sizeof(variant_alternative_t<0, metaf::Group>));
printSize(groupName(1), sizeof(variant_alternative_t<1, metaf::Group>));
printSize(groupName(2), sizeof(variant_alternative_t<2, metaf::Group>));
printSize(groupName(3), sizeof(variant_alternative_t<3, metaf::Group>));
printSize(groupName(4), sizeof(variant_alternative_t<4, metaf::Group>));
printSize(groupName(5), sizeof(variant_alternative_t<5, metaf::Group>));
printSize(groupName(6), sizeof(variant_alternative_t<6, metaf::Group>));
printSize(groupName(7), sizeof(variant_alternative_t<7, metaf::Group>));
printSize(groupName(8), sizeof(variant_alternative_t<8, metaf::Group>));
printSize(groupName(9), sizeof(variant_alternative_t<9, metaf::Group>));
printSize(groupName(10), sizeof(variant_alternative_t<10, metaf::Group>));
printSize(groupName(11), sizeof(variant_alternative_t<11, metaf::Group>));
printSize(groupName(12), sizeof(variant_alternative_t<12, metaf::Group>));
printSize(groupName(13), sizeof(variant_alternative_t<13, metaf::Group>));
printSize(groupName(14), sizeof(variant_alternative_t<14, metaf::Group>));
printSize(groupName(15), sizeof(variant_alternative_t<15, metaf::Group>));
printSize(groupName(16), sizeof(variant_alternative_t<16, metaf::Group>));
printSize(groupName(17), sizeof(variant_alternative_t<17, metaf::Group>));
printSize(groupName(18), sizeof(variant_alternative_t<18, metaf::Group>));
cout << endl;
}
int main(int argc, char ** argv) {
(void) argc; (void) argv;
{
cout << "Checking parser performance\n";
ParserPerformanceChecker checker;
checker.run(cout);
cout << "\n";
}
{
cout << "Checking group performance\n";
GroupsTestSet groupsTestSet;
groupsTestSet.displayStats(cout);
cout << "\n";
groupsTestSet.runPerformanceTests(cout);
cout << "\n";
}
checkRecognisedGroups();
printDataSize();
} | 35.485106 | 103 | 0.659192 | [
"vector"
] |
fb376e0a1db84e996cc19451b25224d749f55027 | 1,647 | cpp | C++ | Olympiad Solutions/URI/2470.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | Olympiad Solutions/URI/2470.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | Olympiad Solutions/URI/2470.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | // Ivan Carvalho
// Solution to https://www.urionlinejudge.com.br/judge/problems/view/2470
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
#define MAXN 50500
#define MAXL 21
int pai[MAXN],nivel[MAXN],carta[MAXN],par[MAXN],n,resposta,acessado[MAXN];
int ancestral[MAXN][MAXL];
vector<int> lista[MAXN];
void dfs(int u){
for(int i=0;i<lista[u].size();i++){
int v = lista[u][i];
if (nivel[v]==-1){
nivel[v] = nivel[u]+1;
pai[v]=u;
dfs(v);
}
}
}
int LCA(int u, int v){
if(nivel[u] < nivel[v]) swap(u,v);
for(int i = MAXL - 1;i >= 0;i--){
if(ancestral[u][i] != -1 && nivel[ancestral[u][i]] >= nivel[v]){
u = ancestral[u][i];
}
}
if(u == v) return u;
for(int i = MAXL - 1;i >= 0;i--){
if(ancestral[u][i] != ancestral[v][i] && ancestral[u][i] != -1){
u = ancestral[u][i];
v = ancestral[v][i];
}
}
return pai[u];
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++){
int x;
scanf("%d",&x);
if (carta[x]){
par[i] = carta[x];
par[carta[x]]=i;
}
carta[x]=i;
}
for(int i=1;i<n;i++){
int a,b;
scanf("%d %d",&a,&b);
lista[a].push_back(b);
lista[b].push_back(a);
}
memset(pai,-1,sizeof(pai));
memset(nivel,-1,sizeof(nivel));
nivel[1]=0;
dfs(1);
for(int i=1;i<=n;i++) ancestral[i][0] = pai[i];
for(int j = 1;j < MAXL;j++){
for(int i=1;i<=n;i++){
if(ancestral[i][j-1] != -1){
ancestral[i][j] = ancestral[ancestral[i][j-1]][j-1];
}
}
}
for(int i=1;i<=n;i++){
if (acessado[i]) continue;
resposta += nivel[i] + nivel[par[i]] - 2 * nivel[LCA(i,par[i])];
acessado[i]=1;
acessado[par[i]]=1;
}
printf("%d\n",resposta);
}
| 21.671053 | 74 | 0.55677 | [
"vector"
] |
fb3919af9ce97cd214a7300f5bf39fd425ba0d32 | 45,919 | cpp | C++ | vnpy/api/tora/vntora/generated_files/generated_functions_5.cpp | Readme-Guru/vnpy | 743ec0f61591688319abd147f55de1b78145048a | [
"MIT"
] | 323 | 2015-11-21T14:45:29.000Z | 2022-03-16T08:54:37.000Z | vnpy/api/tora/vntora/generated_files/generated_functions_5.cpp | Readme-Guru/vnpy | 743ec0f61591688319abd147f55de1b78145048a | [
"MIT"
] | 9 | 2017-03-21T08:26:21.000Z | 2021-08-23T06:41:17.000Z | vnpy/api/tora/vntora/generated_files/generated_functions_5.cpp | Readme-Guru/vnpy | 743ec0f61591688319abd147f55de1b78145048a | [
"MIT"
] | 148 | 2016-09-26T03:25:39.000Z | 2022-02-06T14:43:48.000Z | #include "config.h"
#include <iostream>
#include <string>
#include <pybind11/pybind11.h>
#include <autocxxpy/autocxxpy.hpp>
#include "module.hpp"
#include "wrappers.hpp"
#include "generated_functions.h"
#include "TORATstpMdApi.h"
#include "TORATstpTraderApi.h"
#include "TORATstpUserApiDataType.h"
#include "TORATstpUserApiStruct.h"
void generate_class_CTORATstpQryConversionBondInfoField(pybind11::object & parent)
{
pybind11::class_<CTORATstpQryConversionBondInfoField> c(parent, "CTORATstpQryConversionBondInfoField");
if constexpr (std::is_default_constructible_v<CTORATstpQryConversionBondInfoField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryConversionBondInfoField, "ExchangeID", ExchangeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryConversionBondInfoField, "SecurityID", SecurityID);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpQryConversionBondInfoField, c);
module_vntora::objects.emplace("CTORATstpQryConversionBondInfoField", c);
}
void generate_class_CTORATstpConversionBondInfoField(pybind11::object & parent)
{
pybind11::class_<CTORATstpConversionBondInfoField> c(parent, "CTORATstpConversionBondInfoField");
if constexpr (std::is_default_constructible_v<CTORATstpConversionBondInfoField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpConversionBondInfoField, "ExchangeID", ExchangeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpConversionBondInfoField, "MarketID", MarketID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpConversionBondInfoField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpConversionBondInfoField, "ConvertOrderID", ConvertOrderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpConversionBondInfoField, "ConvertPrice", ConvertPrice);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpConversionBondInfoField, "ConvertVolUnit", ConvertVolUnit);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpConversionBondInfoField, "ConvertVolMax", ConvertVolMax);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpConversionBondInfoField, "ConvertVolMin", ConvertVolMin);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpConversionBondInfoField, "BeginDate", BeginDate);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpConversionBondInfoField, "EndDate", EndDate);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpConversionBondInfoField, "IsSupportCancel", IsSupportCancel);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpConversionBondInfoField, c);
module_vntora::objects.emplace("CTORATstpConversionBondInfoField", c);
}
void generate_class_CTORATstpQryBondPutbackInfoField(pybind11::object & parent)
{
pybind11::class_<CTORATstpQryBondPutbackInfoField> c(parent, "CTORATstpQryBondPutbackInfoField");
if constexpr (std::is_default_constructible_v<CTORATstpQryBondPutbackInfoField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryBondPutbackInfoField, "ExchangeID", ExchangeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryBondPutbackInfoField, "SecurityID", SecurityID);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpQryBondPutbackInfoField, c);
module_vntora::objects.emplace("CTORATstpQryBondPutbackInfoField", c);
}
void generate_class_CTORATstpBondPutbackInfoField(pybind11::object & parent)
{
pybind11::class_<CTORATstpBondPutbackInfoField> c(parent, "CTORATstpBondPutbackInfoField");
if constexpr (std::is_default_constructible_v<CTORATstpBondPutbackInfoField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpBondPutbackInfoField, "ExchangeID", ExchangeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpBondPutbackInfoField, "MarketID", MarketID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpBondPutbackInfoField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpBondPutbackInfoField, "PutbackOrderID", PutbackOrderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpBondPutbackInfoField, "PutbackPrice", PutbackPrice);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpBondPutbackInfoField, "PutbackVolUnit", PutbackVolUnit);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpBondPutbackInfoField, "PutbackVolMax", PutbackVolMax);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpBondPutbackInfoField, "PutbackVolMin", PutbackVolMin);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpBondPutbackInfoField, "BeginDate", BeginDate);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpBondPutbackInfoField, "EndDate", EndDate);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpBondPutbackInfoField, "IsSupportCancel", IsSupportCancel);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpBondPutbackInfoField, c);
module_vntora::objects.emplace("CTORATstpBondPutbackInfoField", c);
}
void generate_class_CTORATstpQryStandardBondPositionField(pybind11::object & parent)
{
pybind11::class_<CTORATstpQryStandardBondPositionField> c(parent, "CTORATstpQryStandardBondPositionField");
if constexpr (std::is_default_constructible_v<CTORATstpQryStandardBondPositionField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryStandardBondPositionField, "InvestorID", InvestorID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryStandardBondPositionField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryStandardBondPositionField, "ExchangeID", ExchangeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryStandardBondPositionField, "MarketID", MarketID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryStandardBondPositionField, "ShareholderID", ShareholderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryStandardBondPositionField, "BusinessUnitID", BusinessUnitID);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpQryStandardBondPositionField, c);
module_vntora::objects.emplace("CTORATstpQryStandardBondPositionField", c);
}
void generate_class_CTORATstpStandardBondPositionField(pybind11::object & parent)
{
pybind11::class_<CTORATstpStandardBondPositionField> c(parent, "CTORATstpStandardBondPositionField");
if constexpr (std::is_default_constructible_v<CTORATstpStandardBondPositionField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpStandardBondPositionField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpStandardBondPositionField, "InvestorID", InvestorID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpStandardBondPositionField, "BusinessUnitID", BusinessUnitID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpStandardBondPositionField, "ExchangeID", ExchangeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpStandardBondPositionField, "MarketID", MarketID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpStandardBondPositionField, "ShareholderID", ShareholderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpStandardBondPositionField, "TradingDay", TradingDay);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpStandardBondPositionField, "AvailablePosition", AvailablePosition);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpStandardBondPositionField, "AvailablePosFrozen", AvailablePosFrozen);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpStandardBondPositionField, "TotalPosition", TotalPosition);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpStandardBondPositionField, c);
module_vntora::objects.emplace("CTORATstpStandardBondPositionField", c);
}
void generate_class_CTORATstpQryDesignationRegistrationField(pybind11::object & parent)
{
pybind11::class_<CTORATstpQryDesignationRegistrationField> c(parent, "CTORATstpQryDesignationRegistrationField");
if constexpr (std::is_default_constructible_v<CTORATstpQryDesignationRegistrationField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryDesignationRegistrationField, "InvestorID", InvestorID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryDesignationRegistrationField, "ShareholderID", ShareholderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryDesignationRegistrationField, "OrderSysID", OrderSysID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryDesignationRegistrationField, "InsertTimeStart", InsertTimeStart);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryDesignationRegistrationField, "InsertTimeEnd", InsertTimeEnd);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryDesignationRegistrationField, "BusinessUnitID", BusinessUnitID);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpQryDesignationRegistrationField, c);
module_vntora::objects.emplace("CTORATstpQryDesignationRegistrationField", c);
}
void generate_class_CTORATstpDesignationRegistrationField(pybind11::object & parent)
{
pybind11::class_<CTORATstpDesignationRegistrationField> c(parent, "CTORATstpDesignationRegistrationField");
if constexpr (std::is_default_constructible_v<CTORATstpDesignationRegistrationField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpDesignationRegistrationField, "InvestorID", InvestorID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpDesignationRegistrationField, "UserID", UserID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpDesignationRegistrationField, "DesignationType", DesignationType);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpDesignationRegistrationField, "OrderLocalID", OrderLocalID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpDesignationRegistrationField, "ShareholderID", ShareholderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpDesignationRegistrationField, "PbuID", PbuID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpDesignationRegistrationField, "OrderSubmitStatus", OrderSubmitStatus);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpDesignationRegistrationField, "TradingDay", TradingDay);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpDesignationRegistrationField, "OrderSysID", OrderSysID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpDesignationRegistrationField, "OrderStatus", OrderStatus);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpDesignationRegistrationField, "InsertDate", InsertDate);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpDesignationRegistrationField, "InsertTime", InsertTime);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpDesignationRegistrationField, "StatusMsg", StatusMsg);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpDesignationRegistrationField, "BusinessUnitID", BusinessUnitID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpDesignationRegistrationField, "AccountID", AccountID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpDesignationRegistrationField, "CurrencyID", CurrencyID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpDesignationRegistrationField, "DepartmentID", DepartmentID);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpDesignationRegistrationField, c);
module_vntora::objects.emplace("CTORATstpDesignationRegistrationField", c);
}
void generate_class_CTORATstpQryCustodyTransferField(pybind11::object & parent)
{
pybind11::class_<CTORATstpQryCustodyTransferField> c(parent, "CTORATstpQryCustodyTransferField");
if constexpr (std::is_default_constructible_v<CTORATstpQryCustodyTransferField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCustodyTransferField, "InvestorID", InvestorID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCustodyTransferField, "ShareholderID", ShareholderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCustodyTransferField, "OrderSysID", OrderSysID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCustodyTransferField, "InsertTimeStart", InsertTimeStart);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCustodyTransferField, "InsertTimeEnd", InsertTimeEnd);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCustodyTransferField, "BusinessUnitID", BusinessUnitID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCustodyTransferField, "SecurityID", SecurityID);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpQryCustodyTransferField, c);
module_vntora::objects.emplace("CTORATstpQryCustodyTransferField", c);
}
void generate_class_CTORATstpCustodyTransferField(pybind11::object & parent)
{
pybind11::class_<CTORATstpCustodyTransferField> c(parent, "CTORATstpCustodyTransferField");
if constexpr (std::is_default_constructible_v<CTORATstpCustodyTransferField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "InvestorID", InvestorID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "UserID", UserID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "CustodyTransferType", CustodyTransferType);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "OrderLocalID", OrderLocalID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "ShareholderID", ShareholderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "PbuID", PbuID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "OrderSubmitStatus", OrderSubmitStatus);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "TradingDay", TradingDay);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "OrderSysID", OrderSysID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "OrderStatus", OrderStatus);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "InsertDate", InsertDate);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "InsertTime", InsertTime);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "StatusMsg", StatusMsg);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "BusinessUnitID", BusinessUnitID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "AccountID", AccountID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "CurrencyID", CurrencyID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "DepartmentID", DepartmentID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "TransfereePbuID", TransfereePbuID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "OrignalOrderLocalID", OrignalOrderLocalID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "VolumeTotalOriginal", VolumeTotalOriginal);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "CancelTime", CancelTime);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "ActiveTraderID", ActiveTraderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCustodyTransferField, "ActiveUserID", ActiveUserID);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpCustodyTransferField, c);
module_vntora::objects.emplace("CTORATstpCustodyTransferField", c);
}
void generate_class_CTORATstpQrySpecialMarketDataField(pybind11::object & parent)
{
pybind11::class_<CTORATstpQrySpecialMarketDataField> c(parent, "CTORATstpQrySpecialMarketDataField");
if constexpr (std::is_default_constructible_v<CTORATstpQrySpecialMarketDataField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQrySpecialMarketDataField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQrySpecialMarketDataField, "ExchangeID", ExchangeID);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpQrySpecialMarketDataField, c);
module_vntora::objects.emplace("CTORATstpQrySpecialMarketDataField", c);
}
void generate_class_CTORATstpSpecialMarketDataField(pybind11::object & parent)
{
pybind11::class_<CTORATstpSpecialMarketDataField> c(parent, "CTORATstpSpecialMarketDataField");
if constexpr (std::is_default_constructible_v<CTORATstpSpecialMarketDataField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpSpecialMarketDataField, "TradingDay", TradingDay);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpSpecialMarketDataField, "ExchangeID", ExchangeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpSpecialMarketDataField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpSpecialMarketDataField, "SecurityName", SecurityName);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpSpecialMarketDataField, "MovingAvgPrice", MovingAvgPrice);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpSpecialMarketDataField, "MovingAvgPriceSamplingNum", MovingAvgPriceSamplingNum);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpSpecialMarketDataField, "UpdateTime", UpdateTime);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpSpecialMarketDataField, "UpdateMillisec", UpdateMillisec);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpSpecialMarketDataField, c);
module_vntora::objects.emplace("CTORATstpSpecialMarketDataField", c);
}
void generate_class_CTORATstpQryPrematurityRepoOrderField(pybind11::object & parent)
{
pybind11::class_<CTORATstpQryPrematurityRepoOrderField> c(parent, "CTORATstpQryPrematurityRepoOrderField");
if constexpr (std::is_default_constructible_v<CTORATstpQryPrematurityRepoOrderField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryPrematurityRepoOrderField, "InvestorID", InvestorID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryPrematurityRepoOrderField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryPrematurityRepoOrderField, "ExchangeID", ExchangeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryPrematurityRepoOrderField, "MarketID", MarketID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryPrematurityRepoOrderField, "ShareholderID", ShareholderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryPrematurityRepoOrderField, "BusinessUnitID", BusinessUnitID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryPrematurityRepoOrderField, "OrderLocalID", OrderLocalID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryPrematurityRepoOrderField, "ProductID", ProductID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryPrematurityRepoOrderField, "SecurityType", SecurityType);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryPrematurityRepoOrderField, "Direction", Direction);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryPrematurityRepoOrderField, "TradeID", TradeID);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpQryPrematurityRepoOrderField, c);
module_vntora::objects.emplace("CTORATstpQryPrematurityRepoOrderField", c);
}
void generate_class_CTORATstpPrematurityRepoOrderField(pybind11::object & parent)
{
pybind11::class_<CTORATstpPrematurityRepoOrderField> c(parent, "CTORATstpPrematurityRepoOrderField");
if constexpr (std::is_default_constructible_v<CTORATstpPrematurityRepoOrderField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "ExchangeID", ExchangeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "MarketID", MarketID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "InvestorID", InvestorID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "ShareholderID", ShareholderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "BusinessUnitID", BusinessUnitID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "TradeDay", TradeDay);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "ExpireDay", ExpireDay);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "OrderLocalID", OrderLocalID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "SecurityName", SecurityName);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "ProductID", ProductID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "SecurityType", SecurityType);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "Direction", Direction);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "VolumeTraded", VolumeTraded);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "Price", Price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "Turnover", Turnover);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "TradeID", TradeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "RepoTotalMoney", RepoTotalMoney);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpPrematurityRepoOrderField, "InterestAmount", InterestAmount);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpPrematurityRepoOrderField, c);
module_vntora::objects.emplace("CTORATstpPrematurityRepoOrderField", c);
}
void generate_class_CTORATstpQryShareholderParamField(pybind11::object & parent)
{
pybind11::class_<CTORATstpQryShareholderParamField> c(parent, "CTORATstpQryShareholderParamField");
if constexpr (std::is_default_constructible_v<CTORATstpQryShareholderParamField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryShareholderParamField, "MarketID", MarketID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryShareholderParamField, "ShareholderID", ShareholderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryShareholderParamField, "TradingCodeClass", TradingCodeClass);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryShareholderParamField, "ProductID", ProductID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryShareholderParamField, "SecurityType", SecurityType);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryShareholderParamField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryShareholderParamField, "ParamType", ParamType);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryShareholderParamField, "ExchangeID", ExchangeID);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpQryShareholderParamField, c);
module_vntora::objects.emplace("CTORATstpQryShareholderParamField", c);
}
void generate_class_CTORATstpShareholderParamField(pybind11::object & parent)
{
pybind11::class_<CTORATstpShareholderParamField> c(parent, "CTORATstpShareholderParamField");
if constexpr (std::is_default_constructible_v<CTORATstpShareholderParamField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpShareholderParamField, "ExchangeID", ExchangeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpShareholderParamField, "MarketID", MarketID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpShareholderParamField, "ShareholderID", ShareholderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpShareholderParamField, "TradingCodeClass", TradingCodeClass);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpShareholderParamField, "ProductID", ProductID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpShareholderParamField, "SecurityType", SecurityType);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpShareholderParamField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpShareholderParamField, "ParamType", ParamType);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpShareholderParamField, "ParamValue", ParamValue);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpShareholderParamField, c);
module_vntora::objects.emplace("CTORATstpShareholderParamField", c);
}
void generate_class_CTORATstpQryPeripheryPositionTransferDetailField(pybind11::object & parent)
{
pybind11::class_<CTORATstpQryPeripheryPositionTransferDetailField> c(parent, "CTORATstpQryPeripheryPositionTransferDetailField");
if constexpr (std::is_default_constructible_v<CTORATstpQryPeripheryPositionTransferDetailField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryPeripheryPositionTransferDetailField, "InvestorID", InvestorID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryPeripheryPositionTransferDetailField, "ShareholderID", ShareholderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryPeripheryPositionTransferDetailField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryPeripheryPositionTransferDetailField, "TransferDirection", TransferDirection);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryPeripheryPositionTransferDetailField, "BusinessUnitID", BusinessUnitID);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpQryPeripheryPositionTransferDetailField, c);
module_vntora::objects.emplace("CTORATstpQryPeripheryPositionTransferDetailField", c);
}
void generate_class_CTORATstpQryInvestorCondOrderLimitParamField(pybind11::object & parent)
{
pybind11::class_<CTORATstpQryInvestorCondOrderLimitParamField> c(parent, "CTORATstpQryInvestorCondOrderLimitParamField");
if constexpr (std::is_default_constructible_v<CTORATstpQryInvestorCondOrderLimitParamField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryInvestorCondOrderLimitParamField, "InvestorID", InvestorID);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpQryInvestorCondOrderLimitParamField, c);
module_vntora::objects.emplace("CTORATstpQryInvestorCondOrderLimitParamField", c);
}
void generate_class_CTORATstpInvestorCondOrderLimitParamField(pybind11::object & parent)
{
pybind11::class_<CTORATstpInvestorCondOrderLimitParamField> c(parent, "CTORATstpInvestorCondOrderLimitParamField");
if constexpr (std::is_default_constructible_v<CTORATstpInvestorCondOrderLimitParamField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpInvestorCondOrderLimitParamField, "InvestorID", InvestorID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpInvestorCondOrderLimitParamField, "MaxCondOrderLimitCnt", MaxCondOrderLimitCnt);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpInvestorCondOrderLimitParamField, "CurrCondOrderCnt", CurrCondOrderCnt);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpInvestorCondOrderLimitParamField, c);
module_vntora::objects.emplace("CTORATstpInvestorCondOrderLimitParamField", c);
}
void generate_class_CTORATstpQryCondOrderField(pybind11::object & parent)
{
pybind11::class_<CTORATstpQryCondOrderField> c(parent, "CTORATstpQryCondOrderField");
if constexpr (std::is_default_constructible_v<CTORATstpQryCondOrderField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCondOrderField, "InvestorID", InvestorID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCondOrderField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCondOrderField, "ExchangeID", ExchangeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCondOrderField, "ShareholderID", ShareholderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCondOrderField, "CondOrderID", CondOrderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCondOrderField, "InsertTimeStart", InsertTimeStart);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCondOrderField, "InsertTimeEnd", InsertTimeEnd);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCondOrderField, "BusinessUnitID", BusinessUnitID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCondOrderField, "BInfo", BInfo);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCondOrderField, "SInfo", SInfo);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCondOrderField, "IInfo", IInfo);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpQryCondOrderField, c);
module_vntora::objects.emplace("CTORATstpQryCondOrderField", c);
}
void generate_class_CTORATstpCondOrderField(pybind11::object & parent)
{
pybind11::class_<CTORATstpCondOrderField> c(parent, "CTORATstpCondOrderField");
if constexpr (std::is_default_constructible_v<CTORATstpCondOrderField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "ExchangeID", ExchangeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "InvestorID", InvestorID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "BusinessUnitID", BusinessUnitID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "ShareholderID", ShareholderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "Direction", Direction);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "OrderPriceType", OrderPriceType);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "OrderVolumeType", OrderVolumeType);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "TimeCondition", TimeCondition);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "VolumeCondition", VolumeCondition);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "LimitPrice", LimitPrice);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "VolumeTotalOriginal", VolumeTotalOriginal);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "CombOffsetFlag", CombOffsetFlag);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "CombHedgeFlag", CombHedgeFlag);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "CondOrderRef", CondOrderRef);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "AccountID", AccountID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "UserID", UserID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "RequestID", RequestID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "IPAddress", IPAddress);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "MacAddress", MacAddress);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "CondOrderID", CondOrderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "TerminalInfo", TerminalInfo);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "BInfo", BInfo);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "SInfo", SInfo);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "IInfo", IInfo);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "Operway", Operway);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "CondCheck", CondCheck);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "ContingentCondition", ContingentCondition);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "ConditionPrice", ConditionPrice);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "PriceTicks", PriceTicks);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "VolumeMultiple", VolumeMultiple);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "RelativeFrontID", RelativeFrontID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "RelativeSessionID", RelativeSessionID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "RelativeParam", RelativeParam);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "AppendContingentCondition", AppendContingentCondition);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "AppendConditionPrice", AppendConditionPrice);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "AppendRelativeFrontID", AppendRelativeFrontID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "AppendRelativeSessionID", AppendRelativeSessionID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "AppendRelativeParam", AppendRelativeParam);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "TradingDay", TradingDay);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "CondOrderStatus", CondOrderStatus);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "InsertDate", InsertDate);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "InsertTime", InsertTime);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "CancelTime", CancelTime);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "CancelUser", CancelUser);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "FrontID", FrontID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "SessionID", SessionID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "UserProductInfo", UserProductInfo);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "StatusMsg", StatusMsg);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "DepartmentID", DepartmentID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "ProperCtrlBusinessType", ProperCtrlBusinessType);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "ProperCtrlPassFlag", ProperCtrlPassFlag);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "ActiveDate", ActiveDate);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderField, "ActiveTime", ActiveTime);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpCondOrderField, c);
module_vntora::objects.emplace("CTORATstpCondOrderField", c);
}
void generate_class_CTORATstpQryCondOrderActionField(pybind11::object & parent)
{
pybind11::class_<CTORATstpQryCondOrderActionField> c(parent, "CTORATstpQryCondOrderActionField");
if constexpr (std::is_default_constructible_v<CTORATstpQryCondOrderActionField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCondOrderActionField, "InvestorID", InvestorID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCondOrderActionField, "ExchangeID", ExchangeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCondOrderActionField, "ShareholderID", ShareholderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCondOrderActionField, "BInfo", BInfo);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCondOrderActionField, "SInfo", SInfo);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryCondOrderActionField, "IInfo", IInfo);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpQryCondOrderActionField, c);
module_vntora::objects.emplace("CTORATstpQryCondOrderActionField", c);
}
void generate_class_CTORATstpCondOrderActionField(pybind11::object & parent)
{
pybind11::class_<CTORATstpCondOrderActionField> c(parent, "CTORATstpCondOrderActionField");
if constexpr (std::is_default_constructible_v<CTORATstpCondOrderActionField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "ExchangeID", ExchangeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "RequestID", RequestID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "CondOrderActionRef", CondOrderActionRef);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "CondOrderRef", CondOrderRef);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "FrontID", FrontID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "SessionID", SessionID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "CondOrderID", CondOrderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "ActionFlag", ActionFlag);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "InvestorID", InvestorID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "UserID", UserID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "CancelCondOrderID", CancelCondOrderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "IPAddress", IPAddress);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "MacAddress", MacAddress);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "TerminalInfo", TerminalInfo);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "BInfo", BInfo);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "SInfo", SInfo);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "IInfo", IInfo);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "Operway", Operway);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "BusinessUnitID", BusinessUnitID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "ShareholderID", ShareholderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "ActionDate", ActionDate);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpCondOrderActionField, "ActionTime", ActionTime);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpCondOrderActionField, c);
module_vntora::objects.emplace("CTORATstpCondOrderActionField", c);
}
void generate_class_CTORATstpQryBrokerUserRoleField(pybind11::object & parent)
{
pybind11::class_<CTORATstpQryBrokerUserRoleField> c(parent, "CTORATstpQryBrokerUserRoleField");
if constexpr (std::is_default_constructible_v<CTORATstpQryBrokerUserRoleField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryBrokerUserRoleField, "RoleID", RoleID);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpQryBrokerUserRoleField, c);
module_vntora::objects.emplace("CTORATstpQryBrokerUserRoleField", c);
}
void generate_class_CTORATstpBrokerUserRoleField(pybind11::object & parent)
{
pybind11::class_<CTORATstpBrokerUserRoleField> c(parent, "CTORATstpBrokerUserRoleField");
if constexpr (std::is_default_constructible_v<CTORATstpBrokerUserRoleField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpBrokerUserRoleField, "RoleID", RoleID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpBrokerUserRoleField, "RoleDescription", RoleDescription);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpBrokerUserRoleField, "Functions", Functions);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpBrokerUserRoleField, c);
module_vntora::objects.emplace("CTORATstpBrokerUserRoleField", c);
}
void generate_class_CTORATstpQryBrokerUserRoleAssignmentField(pybind11::object & parent)
{
pybind11::class_<CTORATstpQryBrokerUserRoleAssignmentField> c(parent, "CTORATstpQryBrokerUserRoleAssignmentField");
if constexpr (std::is_default_constructible_v<CTORATstpQryBrokerUserRoleAssignmentField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryBrokerUserRoleAssignmentField, "UserID", UserID);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpQryBrokerUserRoleAssignmentField, c);
module_vntora::objects.emplace("CTORATstpQryBrokerUserRoleAssignmentField", c);
}
void generate_class_CTORATstpBrokerUserRoleAssignmentField(pybind11::object & parent)
{
pybind11::class_<CTORATstpBrokerUserRoleAssignmentField> c(parent, "CTORATstpBrokerUserRoleAssignmentField");
if constexpr (std::is_default_constructible_v<CTORATstpBrokerUserRoleAssignmentField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpBrokerUserRoleAssignmentField, "UserID", UserID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpBrokerUserRoleAssignmentField, "RoleID", RoleID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpBrokerUserRoleAssignmentField, "RoleDescription", RoleDescription);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpBrokerUserRoleAssignmentField, c);
module_vntora::objects.emplace("CTORATstpBrokerUserRoleAssignmentField", c);
}
void generate_class_CTORATstpQryTradingNoticeField(pybind11::object & parent)
{
pybind11::class_<CTORATstpQryTradingNoticeField> c(parent, "CTORATstpQryTradingNoticeField");
if constexpr (std::is_default_constructible_v<CTORATstpQryTradingNoticeField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryTradingNoticeField, "InvestorID", InvestorID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryTradingNoticeField, "InsertDateStart", InsertDateStart);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryTradingNoticeField, "InsertDateEnd", InsertDateEnd);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryTradingNoticeField, "InsertTimeStart", InsertTimeStart);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryTradingNoticeField, "InsertTimeEnd", InsertTimeEnd);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpQryTradingNoticeField, c);
module_vntora::objects.emplace("CTORATstpQryTradingNoticeField", c);
}
void generate_class_CTORATstpQryIPONumberResultField(pybind11::object & parent)
{
pybind11::class_<CTORATstpQryIPONumberResultField> c(parent, "CTORATstpQryIPONumberResultField");
if constexpr (std::is_default_constructible_v<CTORATstpQryIPONumberResultField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryIPONumberResultField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryIPONumberResultField, "ExchangeID", ExchangeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryIPONumberResultField, "ShareholderID", ShareholderID);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpQryIPONumberResultField, c);
module_vntora::objects.emplace("CTORATstpQryIPONumberResultField", c);
}
void generate_class_CTORATstpIPONumberResultField(pybind11::object & parent)
{
pybind11::class_<CTORATstpIPONumberResultField> c(parent, "CTORATstpIPONumberResultField");
if constexpr (std::is_default_constructible_v<CTORATstpIPONumberResultField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpIPONumberResultField, "ExchangeID", ExchangeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpIPONumberResultField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpIPONumberResultField, "Day", Day);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpIPONumberResultField, "SecurityName", SecurityName);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpIPONumberResultField, "ShareholderID", ShareholderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpIPONumberResultField, "SecurityType", SecurityType);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpIPONumberResultField, "BeginNumberID", BeginNumberID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpIPONumberResultField, "Volume", Volume);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpIPONumberResultField, c);
module_vntora::objects.emplace("CTORATstpIPONumberResultField", c);
}
void generate_class_CTORATstpQryIPOMatchNumberResultField(pybind11::object & parent)
{
pybind11::class_<CTORATstpQryIPOMatchNumberResultField> c(parent, "CTORATstpQryIPOMatchNumberResultField");
if constexpr (std::is_default_constructible_v<CTORATstpQryIPOMatchNumberResultField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryIPOMatchNumberResultField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryIPOMatchNumberResultField, "ExchangeID", ExchangeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryIPOMatchNumberResultField, "ShareholderID", ShareholderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpQryIPOMatchNumberResultField, "MatchNumberID", MatchNumberID);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpQryIPOMatchNumberResultField, c);
module_vntora::objects.emplace("CTORATstpQryIPOMatchNumberResultField", c);
}
void generate_class_CTORATstpIPOMatchNumberResultField(pybind11::object & parent)
{
pybind11::class_<CTORATstpIPOMatchNumberResultField> c(parent, "CTORATstpIPOMatchNumberResultField");
if constexpr (std::is_default_constructible_v<CTORATstpIPOMatchNumberResultField>)
c.def(pybind11::init<>());
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpIPOMatchNumberResultField, "ExchangeID", ExchangeID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpIPOMatchNumberResultField, "SecurityID", SecurityID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpIPOMatchNumberResultField, "Day", Day);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpIPOMatchNumberResultField, "SecurityName", SecurityName);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpIPOMatchNumberResultField, "ShareholderID", ShareholderID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpIPOMatchNumberResultField, "SecurityType", SecurityType);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpIPOMatchNumberResultField, "MatchNumberID", MatchNumberID);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpIPOMatchNumberResultField, "Volume", Volume);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpIPOMatchNumberResultField, "Price", Price);
c.AUTOCXXPY_DEF_PROPERTY(tag_vntora, CTORATstpIPOMatchNumberResultField, "Amout", Amout);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpIPOMatchNumberResultField, c);
module_vntora::objects.emplace("CTORATstpIPOMatchNumberResultField", c);
}
| 80.84331 | 133 | 0.827457 | [
"object"
] |
fb4199b2304495a3f51e11fd02266ea2c8d62c70 | 2,877 | cpp | C++ | SensorLibrary/src/Recorder.cpp | MAMEM/SensorLib | 570b25a6d6ab8b166b541731b2d290da34043f58 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | SensorLibrary/src/Recorder.cpp | MAMEM/SensorLib | 570b25a6d6ab8b166b541731b2d290da34043f58 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | SensorLibrary/src/Recorder.cpp | MAMEM/SensorLib | 570b25a6d6ab8b166b541731b2d290da34043f58 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null |
#include "Recorder.h"
#include <experimental/filesystem>
namespace SensorLib {
Recorder::Recorder() {
}
Recorder::~Recorder() {
for (size_t i = 0 ; i < currentRecordings.size(); i++)
{
delete currentRecordings[i];
}
currentRecordings.clear();
}
/*
void Recorder::startRecording(const std::string filename, std::vector<Sensor*> sensors) {
std::vector<lsl::stream_info> streamsToRecord;
for (size_t i = 0; i < sensors.size(); i++) {
if (sensors[i]->getStatus() == STREAMING) {
lsl::stream_info streaminfo = sensors[i]->getStreamInfo();
if (&streaminfo != NULL) {
std::cout << "Recorder: Selected " << sensors[i]->name << "stream for recording" << std::endl;
streamsToRecord.push_back(streaminfo);
}
}
}
std::vector<std::string> watchfor;
std::map<std::string, int> syncOptions;
std::cout << "Recorder: started recording " << streamsToRecord.size() << " stream(s)" << std::endl;
//recording *result = new recording(filename, streamsToRecord);
/*
if (streamsToRecord.size() > 0) {
currentRecording = new recording(filename, streamsToRecord, watchfor, syncOptions, true);
}
*/
/*
for (size_t i = 0; i < streamsToRecord.size() > 0; i++) {
std::time_t t = std::time(0);
std::ostringstream ss;
ss << "../data/" << streamsToRecord[i].name()<< "_" << t << ".xdf";
std::vector<lsl::stream_info> streamToRecord;
streamToRecord.push_back(streamsToRecord[i]);
const std::string filename2 = ss.str();
currentRecordings.push_back(new recording(filename2, streamToRecord, watchfor, syncOptions, true));
}
}
*/
recording* Recorder::startRecording(Sensor* sensor)
{
std::vector<lsl::stream_info> streamToRecord;
lsl::stream_info streaminfo = sensor->getStreamInfo();
if (&streaminfo != NULL) {
std::cout << "Recorder: startRecording " << sensor->name << std::endl;
streamToRecord.push_back(streaminfo);
}
std::vector<std::string> watchfor;
std::map<std::string, int> syncOptions;
std::time_t t = std::time(0);
std::ostringstream ss;
//ss << ../data/ << streamToRecord[0].name() << "_" << t << ".xdf";
//ss << "C:\\Users\\MAMEM\\Documents\\" << streamToRecord[0].name() << "_" << t << ".xdf";
const std::string currentDirectory = std::experimental::filesystem::current_path().generic_string();
ss << "C://sensordata/" << streamToRecord[0].name() << "_" << t << ".xdf";
const std::string filename = ss.str();
return new recording(filename, streamToRecord, watchfor, syncOptions, true);
//currentRecordings.push_back(new recording(filename, streamToRecord, watchfor, syncOptions, true));
}
void Recorder::stopRecording() {
std::cout << "Recorder: stopped recording" << std::endl;
for (size_t i = 0; i < currentRecordings.size(); i++)
{
delete currentRecordings[i];
}
currentRecordings.clear();
}
void Recorder::recordessr() {
}
} | 32.693182 | 102 | 0.654849 | [
"vector"
] |
fb4682496857db5b466ca2154b317bfee92caf0d | 12,555 | cpp | C++ | src/systems/attack-system.cpp | guillaume-haerinck/imac-tower-defense | 365a32642ea0d3ad8b2b7d63347d585c44d9f670 | [
"MIT"
] | 44 | 2019-06-06T21:33:30.000Z | 2022-03-26T06:18:23.000Z | src/systems/attack-system.cpp | guillaume-haerinck/imac-tower-defense | 365a32642ea0d3ad8b2b7d63347d585c44d9f670 | [
"MIT"
] | 1 | 2019-09-27T12:04:52.000Z | 2019-09-29T13:30:42.000Z | src/systems/attack-system.cpp | guillaume-haerinck/imac-tower-defense | 365a32642ea0d3ad8b2b7d63347d585c44d9f670 | [
"MIT"
] | 8 | 2019-07-26T16:44:26.000Z | 2020-11-24T17:56:18.000Z | #include "attack-system.hpp"
#include <math.h>
#include <spdlog/spdlog.h>
#include "core/tags.hpp"
#include "core/maths.hpp"
#include "core/constants.hpp"
#include "components/targeting.hpp"
#include "components/shoot-at.hpp"
#include "components/shoot-laser.hpp"
#include "components/health.hpp"
#include "components/shake.hpp"
#include "components/velocity.hpp"
#include "components/tint-colour.hpp"
#include "events/entity-damaged.hpp"
#include "events/laser-particle-dead.hpp"
#include "services/locator.hpp"
#include "services/debug-draw/i-debug-draw.hpp"
#include "services/random/i-random.hpp"
#include "services/helper/i-helper.hpp"
#include "components/animated.hpp"
#include <SDL2/SDL.h>
AttackSystem::AttackSystem(entt::DefaultRegistry& registry, EventEmitter& emitter) : ISystem(registry, emitter), m_projectileFactory(registry), m_vfxFactory(registry) {
m_emitter.on<evnt::LaserParticleDead>([this](const evnt::LaserParticleDead & event, EventEmitter & emitter) {
IRandom& randomService = entt::ServiceLocator<IRandom>::ref();
if (randomService.random() < 0.1) {
this->trySpawnLaserParticle(event.position, 1);
this->trySpawnLaserParticle(event.position, 1);
}
});
}
void AttackSystem::update(float deltatime) {
// Look at target
m_registry.view<cmpt::Targeting, cmpt::Transform , targetingTag::LookAt>().each([this](auto entity, cmpt::Targeting & targeting, cmpt::Transform & transform, auto) {
if ( m_registry.valid(targeting.targetId) ) {
glm::vec2 direction = m_registry.get<cmpt::Transform>(targeting.targetId).position - transform.position;
transform.rotation = atan2(direction.y, direction.x);
}
});
// Shoot a projectile at target
m_registry.view<cmpt::Targeting, cmpt::ShootAt>().each([this](auto entity, cmpt::Targeting & targeting, cmpt::ShootAt & shootAt) {
if (m_registry.valid(targeting.targetId) ) {
if (shootAt.timer == shootAt.loadingTime) {
IHelper& helper = entt::ServiceLocator<IHelper>::ref();
if (m_registry.has<projectileType::Slow>(entity)) {
m_projectileFactory.createSlow(helper.getPosition(entity), targeting.targetId);
}
if (m_registry.has<projectileType::Damage>(entity)) {
m_projectileFactory.createDamage(helper.getPosition(entity), targeting.targetId);
}
shootAt.timer = 0;
}
else {
shootAt.timer++;
}
}
});
// Pick a new target if current one is out of range or dead
m_registry.view<cmpt::Transform, cmpt::Targeting, entityTag::Tower>().each([this,deltatime](auto entity1, cmpt::Transform & transform1, cmpt::Targeting & targeting,auto) {
if (!m_registry.has<stateTag::IsBeingControlled>(entity1)) {
//Damage towers
if (m_registry.has<projectileType::Damage>(entity1)) {
if (!m_registry.valid(targeting.targetId) || !this->isInRange(transform1, targeting.targetingRange, targeting.targetId)) {
targeting.targetId = -1;
m_registry.view<cmpt::Transform, cmpt::Hitbox, entityTag::Enemy>().each([this, entity1, transform1, &targeting](auto entity2, cmpt::Transform & transform2, cmpt::Hitbox & enemyHitbox, auto) {
if (this->isInRange(transform1, targeting.targetingRange, transform2, enemyHitbox.radius)) {
targeting.targetId = entity2;
}
});
}
}
//Slow towers pick a new target once they have slowed the current one
else if (m_registry.has<projectileType::Slow>(entity1)) {
if (!m_registry.valid(targeting.targetId) || !this->isInRange(transform1, targeting.targetingRange, targeting.targetId) || m_registry.get<cmpt::Velocity>(targeting.targetId).velMultiplier < 0.999) {
float maxVelMult = 0;
targeting.targetId = -1;
m_registry.view<cmpt::Transform, cmpt::Hitbox, entityTag::Enemy>().each([this, deltatime, entity1, transform1, &targeting, &maxVelMult](auto entity2, cmpt::Transform & transform2, cmpt::Hitbox & enemyHitbox, auto) {
if (this->isInRange(transform1, targeting.targetingRange, transform2, enemyHitbox.radius)) {
cmpt::Velocity& velocity = m_registry.get<cmpt::Velocity>(entity2);
float velMult = deltatime * velocity.velocity*imaths::rangeMapping(velocity.multiplierAge, 0, velocity.multiplierLifespan, velocity.velMultiplier, 1);;
if (velMult > maxVelMult) {
targeting.targetId = entity2;
maxVelMult = velMult;
}
}
});
}
}
}
});
// Shoot laser
glLineWidth(LASER_WIDTH);
m_registry.view<cmpt::ShootLaser, cmpt::Transform>().each([this, deltatime](auto entity, cmpt::ShootLaser & laser, cmpt::Transform & transform) {
IHelper& helper = entt::ServiceLocator<IHelper>::ref();
glm::vec3 col = laser.col;
if (helper.mouseIsOn(entity)) {
col *= 0.5;
}
this->shootLaser(helper.getPositionTowerTip(entity), transform.rotation, 31, entity, deltatime, !laser.isActiv,col,helper.getAlpha(entity));
});
glLineWidth(1);
}
/* ---------------------------- PRIVATE METHODS ------------------------------- */
void AttackSystem::shootLaser(glm::vec2 pos, float agl, int nbBounce , unsigned int launcherId, float deltatime, bool isTransparent, glm::vec3 col, float launcherAlpha) {
IHelper& helper = entt::ServiceLocator<IHelper>::ref();
glm::vec2 unitDirVector = glm::vec2(cos(agl), sin(agl));
glm::vec2 posPlusUnitVector = pos + unitDirVector;
glm::vec2 laserEnd;
float surfaceAngle;
std::uint32_t nextLauncherId = entt::null;
float t = std::numeric_limits<float>::infinity();
bool mirrorIsBeingControlled = false;
bool arrivedOnMirrorEdge = false;
//Mirrors
m_registry.view<cmpt::Transform, cmpt::Hitbox, entityTag::Mirror>().each([this,&nextLauncherId,&laserEnd,&surfaceAngle,&t,pos, unitDirVector, posPlusUnitVector, &mirrorIsBeingControlled, &helper, &arrivedOnMirrorEdge, launcherId](auto mirror, cmpt::Transform & mirrorTransform, cmpt::Hitbox& trigger, auto) {
if (mirror != launcherId) { //Cannot bounce on the same mirror twice in a row to prevent bugs
glm::vec2 mirrorPos = helper.getPosition(mirror);
glm::vec2 mirrorDir = glm::vec2(cos(mirrorTransform.rotation), sin(mirrorTransform.rotation));
glm::vec2 inter = imaths::segmentsIntersection(pos, posPlusUnitVector, mirrorPos - trigger.radius*mirrorDir, mirrorPos + trigger.radius*mirrorDir);
if (0 <= inter.x && inter.x < t && 0 <= inter.y && inter.y <= 1) {
t = inter.x;
laserEnd = pos + t * unitDirVector;
surfaceAngle = mirrorTransform.rotation;
mirrorIsBeingControlled = m_registry.has<stateTag::IsBeingControlled>(mirror) || m_registry.has<positionTag::IsOnHoveredTile>(mirror);
nextLauncherId = mirror;
arrivedOnMirrorEdge = false;
}
else { //Check if they were actually aligned
if (inter.x == std::numeric_limits<float>::infinity()) { //The were parallel.
glm::vec2 mirrorPt1 = mirrorPos + MIRROR_RADIUS * mirrorDir;
glm::vec2 mirrorPt2 = mirrorPos - MIRROR_RADIUS * mirrorDir;
glm::vec2 dir1 = mirrorPt1 - pos;
glm::vec2 dir2 = mirrorPt2 - pos;
if (dir1.x*unitDirVector.x + dir2.y*unitDirVector.y > 0) { //The mirror is in the right direction
if (abs(dir1.x*dir2.y - dir2.x*dir1.y) < 20) { //The were aligned
float dSq1 = dir1.x*dir1.x + dir1.y*dir1.y;
float dSq2 = dir2.x*dir2.x + dir2.y*dir2.y;
float minDist = sqrt(imaths::min(dSq1, dSq2));
if (t > minDist) { //Closer than current end found
t = minDist;
laserEnd = pos + t * unitDirVector;
mirrorIsBeingControlled = m_registry.has<stateTag::IsBeingControlled>(mirror) || m_registry.has<positionTag::IsOnHoveredTile>(mirror);
nextLauncherId = mirror;
arrivedOnMirrorEdge = true;
}
}
}
}
}
}
});
if (t == std::numeric_limits<float>::infinity()) {
nbBounce = 0;
//Walls
glm::vec2 tlCorner = glm::vec2(0, PROJ_HEIGHT);
glm::vec2 trCorner = glm::vec2(PROJ_WIDTH_RAT, PROJ_HEIGHT);
glm::vec2 brCorner = glm::vec2(PROJ_WIDTH_RAT, 0);
glm::vec2 blCorner = glm::vec2(0, 0);
glm::vec2 topInter = imaths::segmentsIntersection(pos, posPlusUnitVector, tlCorner, trCorner);
glm::vec2 rightInter = imaths::segmentsIntersection(pos, posPlusUnitVector, trCorner, brCorner);
glm::vec2 botInter = imaths::segmentsIntersection(pos, posPlusUnitVector, brCorner, blCorner);
glm::vec2 leftInter = imaths::segmentsIntersection(pos, posPlusUnitVector, blCorner, tlCorner);
if (0 <= topInter.y && topInter.y <= 1 && topInter.x >= 0) {
laserEnd = tlCorner + topInter.y * (trCorner - tlCorner);
surfaceAngle = 0;
}
if (0 <= rightInter.y && rightInter.y <= 1 && rightInter.x >= 0) {
laserEnd = trCorner + rightInter.y * (brCorner - trCorner);
surfaceAngle = imaths::TAU / 4;
}
if (0 <= botInter.y && botInter.y <= 1 && botInter.x >= 0) {
laserEnd = brCorner + botInter.y * (blCorner - brCorner);
surfaceAngle = 0;
}
if (0 <= leftInter.y && leftInter.y <= 1 && leftInter.x >= 0) {
laserEnd = blCorner + leftInter.y * (tlCorner - blCorner);
surfaceAngle = imaths::TAU / 4;
}
}
else { //Effect on mirror bounce
if (!mirrorIsBeingControlled && !isTransparent) {
//this->trySpawnLaserParticle(laserEnd, deltatime);
glowOnMirror(laserEnd);
}
}
//Damage entities
float laserLength = sqrt((pos.x - laserEnd.x)*(pos.x - laserEnd.x) + (pos.y - laserEnd.y)*(pos.y - laserEnd.y));
glm::vec2 normal = glm::vec2(laserEnd.y - pos.y, pos.x - laserEnd.x);
normal /= glm::length(normal);
m_registry.view<cmpt::Transform, cmpt::Hitbox, cmpt::Health>().each([this, normal, launcherId, pos, laserEnd, laserLength, deltatime, isTransparent, &helper](auto entity, cmpt::Transform & targetTransform, cmpt::Hitbox& targetTrigger, cmpt::Health& targetHealth) {
glm::vec2 entityPos = helper.getPosition(entity);
float orthoComp = abs(normal.x*(entityPos.x - pos.x) + normal.y*(entityPos.y - pos.y));
float colinComp = ((laserEnd.x - pos.x)*(entityPos.x - pos.x) + (laserEnd.y - pos.y)*(entityPos.y - pos.y)) / laserLength;
if (0 <= colinComp && colinComp <= laserLength && orthoComp < targetTrigger.radius && launcherId != entity) {
if (m_registry.has<entityTag::Tower>(entity)) {
m_registry.accommodate<cmpt::TintColour>(entity, glm::vec4(1, 0.4, 0.047, 0.55*(sin(SDL_GetTicks()*0.006) + 1)), true);
}
if (!isTransparent && !m_registry.has<stateTag::IsBeingControlled>(entity) && !m_registry.has<cmpt::Animated>(entity)) {
m_emitter.publish<evnt::EntityDamaged>(entity, LASER_DAMAGE_PER_SECOND*deltatime);
this->trySpawnLaserParticle(targetTransform.position, deltatime);
}
}
});
IDebugDraw & debugDraw = locator::debugDraw::ref();
float alpha = isTransparent ? 0.25 : 1;
launcherAlpha *= helper.getAlpha(launcherId);
alpha *= launcherAlpha;
debugDraw.setColor(col.r,col.g,col.b, alpha);
debugDraw.line(pos.x, pos.y, laserEnd.x, laserEnd.y, BasicShaderType::LASER);
if (nbBounce > 0) {
if (!arrivedOnMirrorEdge) {
shootLaser(laserEnd - unitDirVector * 0.001f, 2 * surfaceAngle - agl, nbBounce - 1, nextLauncherId, deltatime, isTransparent || mirrorIsBeingControlled, col, launcherAlpha);
}
else {
shootLaser(laserEnd - unitDirVector * 0.001f, agl + imaths::TAU/10, nbBounce - 1, nextLauncherId, deltatime, isTransparent || mirrorIsBeingControlled, col, launcherAlpha);
shootLaser(laserEnd - unitDirVector * 0.001f, agl - imaths::TAU/10, nbBounce - 1, nextLauncherId, deltatime, isTransparent || mirrorIsBeingControlled, col, launcherAlpha);
}
}
}
void AttackSystem::trySpawnLaserParticle(glm::vec2 pos, float deltatime) {
IRandom& randomService = entt::ServiceLocator<IRandom>::ref();
if (randomService.random() < 12 * deltatime) {
m_vfxFactory.createLaserParticle(pos, randomService.random(imaths::TAU));
}
}
void AttackSystem::glowOnMirror(glm::vec2 pos) {
IDebugDraw & debugDraw = locator::debugDraw::ref();
IRandom & random = locator::random::ref();
debugDraw.setColor(122, 249, 237,1.0);
debugDraw.circleWithGlow(pos.x, pos.y, 4+2*0.5*random.noise(SDL_GetTicks()*0.0005));
}
bool AttackSystem::isInRange(cmpt::Transform transform1, float radius1, cmpt::Transform transform2, float radius2) {
const glm::vec2 deltaPos = transform2.position - transform1.position;
const float distanceSq = deltaPos.x * deltaPos.x + deltaPos.y * deltaPos.y;
const float radii = radius1 + radius2;
return distanceSq <= radii * radii;
}
bool AttackSystem::isInRange(cmpt::Transform transform1, float radius1, unsigned int targetId) {
cmpt::Transform transform2 = m_registry.get<cmpt::Transform>(targetId);
float radius2 = m_registry.get<cmpt::Hitbox>(targetId).radius;
return isInRange(transform1, radius1, transform2, radius2);
} | 47.377358 | 309 | 0.705217 | [
"transform"
] |
fb5ebaa52863fbec35158986b6583009a3559c47 | 617 | cpp | C++ | chap10/Exer10_27.cpp | sjbarigye/CPP_Primer | d9d31a73a45ca46909bae104804fc9503ab242f2 | [
"Apache-2.0"
] | 50 | 2016-01-08T14:28:53.000Z | 2022-01-21T12:55:00.000Z | chap10/Exer10_27.cpp | sjbarigye/CPP_Primer | d9d31a73a45ca46909bae104804fc9503ab242f2 | [
"Apache-2.0"
] | 2 | 2017-06-05T16:45:20.000Z | 2021-04-17T13:39:24.000Z | chap10/Exer10_27.cpp | sjbarigye/CPP_Primer | d9d31a73a45ca46909bae104804fc9503ab242f2 | [
"Apache-2.0"
] | 18 | 2016-08-17T15:23:51.000Z | 2022-03-26T18:08:43.000Z | #include <iostream>
#include <list>
#include <vector>
#include <algorithm>
#include <iterator>
using std::cout;
using std::endl;
using std::list;
using std::vector;
int main()
{
vector<int> ivec = { 1, 2, 4, 4, 90, 2, 32, 1, 20, -20, 42};
list<int> ilst;
// if not sort at first, the unique_copy doesn't work, because it only works on adjacent elements
sort(ivec.begin(), ivec.end());
unique_copy(ivec.cbegin(), ivec.cend(), back_inserter(ilst));
for(auto i : ivec)
cout << i << " ";
cout << endl;
for(auto i : ilst)
cout << i << " ";
cout << endl;
return 0;
}
| 24.68 | 101 | 0.593193 | [
"vector"
] |
fb61813ee96cb43e37cb0eab4722e274b2a8256c | 6,772 | cpp | C++ | src/linux_parser.cpp | carlasailer/CppND-System-Monitor | 3cdf4b456d88aa6a6e03a0e5510ac3500cc59a06 | [
"MIT"
] | null | null | null | src/linux_parser.cpp | carlasailer/CppND-System-Monitor | 3cdf4b456d88aa6a6e03a0e5510ac3500cc59a06 | [
"MIT"
] | null | null | null | src/linux_parser.cpp | carlasailer/CppND-System-Monitor | 3cdf4b456d88aa6a6e03a0e5510ac3500cc59a06 | [
"MIT"
] | null | null | null | #include <dirent.h>
#include <unistd.h>
#include <sstream>
#include <string>
#include <vector>
#include <iostream>
#include <experimental/filesystem>
#include "linux_parser.h"
using std::stof;
using std::string;
using std::to_string;
using std::vector;
// generic functions for parsing
template <typename T>
T findValueByKey (string const &keyFilter, string const &file) {
string line, key;
T value;
std::ifstream stream(LinuxParser::kProcDirectory + file);
if (stream.is_open()) {
while (std::getline(stream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == keyFilter) {
return value;
}
}
}
}
return value;
};
template <typename T>
T getValueOfFile( string const &file) {
string line;
T value;
std::ifstream stream(LinuxParser::kProcDirectory + file);
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> value;
}
return value;
};
// helper function to determine whether string is only digits
bool LinuxParser::is_number(const std::string& s) {
std::string::const_iterator it = s.begin();
while (it != s.end() && std::isdigit(*it)) ++it;
return !s.empty() && it == s.end();
}
// Read and return the system OS info
string LinuxParser::OperatingSystem() {
string line;
string key;
string value;
std::ifstream filestream(kOSPath);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::replace(line.begin(), line.end(), ' ', '_');
std::replace(line.begin(), line.end(), '=', ' ');
std::replace(line.begin(), line.end(), '"', ' ');
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "PRETTY_NAME") {
std::replace(value.begin(), value.end(), '_', ' ');
return value;
}
}
}
}
return value;
}
// Read and return the Kernel info
string LinuxParser::Kernel() {
string os, kernel, version;
string line;
std::ifstream stream(kProcDirectory + kVersionFilename);
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> os >> version >> kernel;
}
return kernel;
}
// Read and return Pids
vector<int> LinuxParser::Pids() {
vector<int> pids;
DIR* directory = opendir(kProcDirectory.c_str());
struct dirent* file;
while ((file = readdir(directory)) != nullptr) {
// Is this a directory?
if (file->d_type == DT_DIR) {
// Is every character of the name a digit?
string filename(file->d_name);
if (std::all_of(filename.begin(), filename.end(), isdigit)) {
int pid = stoi(filename);
pids.emplace_back(pid);
}
}
}
closedir(directory);
return pids;
}
// Read and return the system memory utilization
float LinuxParser::MemoryUtilization() {
float memTotal = findValueByKey<float>(filterMemTotalString, kMeminfoFilename);
float memFree = findValueByKey<float>(filterMemFreeString, kMeminfoFilename);
float buffers = findValueByKey<float>(filterBufferString, kMeminfoFilename);
float cached = findValueByKey<float>(filterCachedString, kMeminfoFilename);
return ((memTotal - memFree - buffers - cached) / memTotal);
}
// Read and return the system uptime
long LinuxParser::UpTime() {
return long(getValueOfFile<long>(kUptimeFilename));
}
// Read and return CPU utilization
vector<string> LinuxParser::CpuUtilization() {
string line;
vector<string> times{};
// read from proc stat file
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()) {
filestream.ignore(5, ' ');
//write each item after cpu into a vector
for (string time; filestream >> time; times.emplace_back(time));
}
return times;
}
// Read and return the total number of processes
int LinuxParser::TotalProcesses() {
return findValueByKey<int>(filterProcesses, kStatFilename);
}
// Read and return the number of running processes
int LinuxParser::RunningProcesses() {
return findValueByKey<int>(filterRunningProcesses, kStatFilename);
}
// Read and return the command associated with a process
string LinuxParser::Command(int pid) {
return string(getValueOfFile<string>(std::to_string(pid) + kCmdlineFilename));
}
// Read and return the memory used by a process
string LinuxParser::Ram(int pid) {
string value;
// use VmRSS instead of VmSize to get exact physical memory instead of all virtual memory
double ram = findValueByKey<double>(filterProcMem, std::to_string(pid) + kStatusFilename);
//convert from kB to MB
ram *= 0.001;
//format to be displayed with two decimals
value = std::to_string(ram);
value = value.substr(0, value.size()-4);
return value;
}
// Read and return the user ID associated with a process
string LinuxParser::Uid(int pid) {
return findValueByKey<string>(filterUID, std::to_string(pid) + kStatusFilename);
}
// Read and return the user associated with a process
string LinuxParser::User(int pid) {
string line;
string name{" "};
string password;
string uid;
// get the user id associated with the process
string find_uid = LinuxParser::Uid(pid);
// use the uid to find the user name
std::ifstream filestream(kPasswordPath);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::replace(line.begin(), line.end(), ':', ' ');
std::istringstream linestream(line);
while(linestream >> name >> password >> uid) {
if (uid == find_uid) { return name; }
}
}
}
return name;
}
// Read and return the uptime of a process
long LinuxParser::UpTime(int pid) {
string line;
string value{};
int position = 22;
float uptime{0.0f};
// access the uptime file for the process
std::ifstream filestream(kProcDirectory + std::to_string(pid) + kStatFilename);
if (filestream.is_open()) {
std::getline(filestream, line);
std::istringstream linestream(line);
for (auto i = 0; i < position; i++) {
linestream >> value;
}
}
//convert lock ticks to seconds
if (LinuxParser::is_number(value)) {
uptime = std::stof(value) / sysconf(_SC_CLK_TCK);
//substract process uptime from system uptime
return (LinuxParser::UpTime() - uptime);
}
else { return uptime; }
}
// Read and return the CPU times for the process
vector<string> LinuxParser::CpuUtilization(int pid) {
string line;
vector<string> times{};
// read from proc stat file
std::ifstream filestream(kProcDirectory + std::to_string(pid) + kStatFilename);
if (filestream.is_open()) {
for (string time; filestream >> time; times.emplace_back(time));
}
return times;
} | 27.640816 | 92 | 0.668636 | [
"vector"
] |
fb6b17fc17b561898a7fb5dd34758f793425c00b | 12,675 | cpp | C++ | Code/Cpp_files/pagerank_driver.cpp | SotirisTsioutsiouliklis/FairLaR | 2cec72a671559d4cf96bc2c7ea919fda4b359575 | [
"MIT"
] | null | null | null | Code/Cpp_files/pagerank_driver.cpp | SotirisTsioutsiouliklis/FairLaR | 2cec72a671559d4cf96bc2c7ea919fda4b359575 | [
"MIT"
] | null | null | null | Code/Cpp_files/pagerank_driver.cpp | SotirisTsioutsiouliklis/FairLaR | 2cec72a671559d4cf96bc2c7ea919fda4b359575 | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <vector>
#include "graph.hpp"
#include "pagerank.hpp"
//#include <omp.h>
static bool get_options(const int argc, char ** const argv, double &jump_prob,
std::string &personalize_filename, personalization_t &personalize_type,
int &personalize_extra, std::string &comm_percentage_filename, bool &top_k, int &k)
{
if (argc == 1)
{
personalize_type = personalization_t::NO_PERSONALIZATION;
jump_prob = 0.15;
}
else if ((argc == 3) || (argc == 4))
{
if (!std::strcmp(argv[1], "-pn"))
{
jump_prob = 0.15;
personalize_type = personalization_t::NODE_PERSONALIZATION;
personalize_extra = std::atoi(argv[2]);
}
else if (!std::strcmp(argv[1], "-c"))
{
jump_prob = 0.15;
personalize_type = personalization_t::NO_PERSONALIZATION;
comm_percentage_filename = argv[2];
}
else if (!std::strcmp(argv[1], "-tk"))
{
top_k = true;
k = std::atoi(argv[2]);
personalize_type = personalization_t::NO_PERSONALIZATION;
jump_prob = 0.15;
}
else
goto error;
}
else if (argc == 5)
{
if (!std::strcmp(argv[1], "-tk") && !std::strcmp(argv[3], "-c")) {
top_k = true;
k = std::atoi(argv[2]);
jump_prob = 0.15;
personalize_type = personalization_t::NO_PERSONALIZATION;
comm_percentage_filename = argv[4];
} else if (!std::strcmp(argv[1], "-pn") && !std::strcmp(argv[3], "-c")) {
jump_prob = 0.15;
personalize_type = personalization_t::NODE_PERSONALIZATION;
personalize_extra = std::atoi(argv[2]);
comm_percentage_filename = argv[4];
} else {
goto error;
}
}
else
{
goto error;
}
return true;
error:
std::cerr << "Usage: " << argv[0] << " [options]\n"
"Options:\n"
"-pn <node_id>\t\t\tnode id for node personalization\n"
"-c <comm_percent_filename> \tfilename for custom community percentage\n"
"-tk <K for fairness in top k> \tprovide integer > 0, < number of nodes" << std::endl;
return false;
}
static std::string get_local_header(const bool is_local)
{
if (is_local)
return "\t|\tin_n0\t\%in_n0\tout_n0\t\%out_n0\tin_n1\t\%in_n1\tout_n1\t\%out_n1\t"
"in_neighbors_of_community_i\t\%in_neighbors_of_community_i\t"
"out_neighbors_of_community_i\t\%out_neighbors_of_community_i...";
else
return "";
}
static std::string get_local_neighbors(const bool is_local, const int node_id, graph &g)
{
if (!is_local)
return "";
std::string result = "\t\t|";
const int ncommunities = g.get_num_communities();
const int n_in_neighbors = g.get_in_degree(node_id);
const int n_out_neighbors = g.get_out_degree(node_id);
for (int community = 0; community < ncommunities; ++community)
{
int nsame_in_neighbors = g.count_in_neighbors_with_community(node_id, community);
int in_percentage = (n_in_neighbors == 0) ? 0 : nsame_in_neighbors / (double)n_in_neighbors * 100;
int nsame_out_neighbors = g.count_out_neighbors_with_community(node_id, community);
int out_percentage = (n_out_neighbors == 0) ? 0 : nsame_out_neighbors / (double)n_out_neighbors * 100;
result.append("\t");
result.append(std::to_string(nsame_in_neighbors));
result.append("\t(");
result.append(std::to_string(in_percentage));
result.append("\%)\t");
result.append(std::to_string(nsame_out_neighbors));
result.append("\t(");
result.append(std::to_string(out_percentage));
result.append("\%)");
}
return result;
}
static void save_pagerank(std::string filename_prefix, pagerank_v &pagerankv, graph &g,
pagerank_algorithms &algs, std::ofstream &out_summary)
{
bool is_local = (filename_prefix == "local");
bool is_pagerank = (filename_prefix == "pagerank");
//std::ofstream outfile_rank;
//outfile_rank.open("out_" + filename_prefix + "_rank.txt");
//std::ofstream outfile_pro_pos;
//outfile_pro_pos.open("out_" + filename_prefix + "_pos.txt");
std::ofstream outfile_pagerank;
outfile_pagerank.open("out_" + filename_prefix + "_pagerank.txt");
for (const auto &node : pagerankv) {
outfile_pagerank << node.pagerank << std::endl;
}
//std::ofstream outfile_label_ranking;
////outfile_label_ranking.open("out_" + filename_prefix + "_label_ranking.txt");
//std::ofstream outfile_sums;
//outfile_sums.open("out_" + filename_prefix + "_sums.txt");
//std::ofstream outfile_sums_perc;
//outfile_sums_perc.open("out_" + filename_prefix + "_sums_prec.txt");
algs.sort_pagerank_vector(pagerankv);
//for (int node = 0; node < g.get_num_nodes(); ++node)
//if (g.get_community(node) == 1)
//outfile_pro_pos << node << std::endl;
//outfile_rank << std::fixed;
//outfile_rank << std::setprecision(9);
//outfile_rank << "# node\tpagerank\tcommunity" << get_local_header(is_local) << std::endl;
//outfile_sums << std::fixed;
//outfile_sums << std::setprecision(9);
//outfile_sums << "# range\t\tcommunity_0\tcommunity_1\tcommunity_i..." << std::endl;
//outfile_sums_perc << std::fixed;
//outfile_sums_perc << std::setprecision(9);
//outfile_sums_perc << "# range\t\tcommunity_0\tcommunity_1\tcommunity_i..." << std::endl;
std::vector<double> pagerank_sum(g.get_num_communities());
double sum_pagerank = 0.0; // sum of pagerank for all communities so far
int i;
for (i = 0; i < g.get_num_nodes(); ++i)
{
const auto &node = pagerankv[i];
pagerank_sum[g.get_community(node.node_id)] += node.pagerank;
sum_pagerank += pagerankv[i].pagerank;
//outfile_rank << node.node_id << "\t" << node.pagerank << "\t" << g.get_community(node.node_id)
// << get_local_neighbors(is_local, node.node_id, g) << std::endl;
//outfile_label_ranking << g.get_community(node.node_id) << std::endl;
if ((i > 0) && ((i + 1) % 10 == 0))
{
//outfile_sums << "1-" << i + 1 << "\t";
//outfile_sums_perc << "1-" << i + 1 << "\t";
for (int community = 0; community < g.get_num_communities(); ++community)
{
//outfile_sums << "\t" << pagerank_sum[community];
//outfile_sums_perc << "\t" << pagerank_sum[community] / sum_pagerank;
}
//outfile_sums << std::endl;
//outfile_sums_perc << std::endl;
}
}
if (g.get_num_nodes() % 10 != 0)
{
//outfile_sums << "1-" << i;
//outfile_sums_perc << "1-" << i;
for (int community = 0; community < g.get_num_communities(); ++community)
{
//outfile_sums << "\t" << pagerank_sum[community];
//outfile_sums_perc << "\t" << pagerank_sum[community] / sum_pagerank;
}
//outfile_sums << std::endl;
//outfile_sums_perc << std::endl;
}
for (int community = 0; community < g.get_num_communities(); ++community)
{
std::cout << "Community: " << community << ", Pagerank: " << pagerank_sum[community] << std::endl;
out_summary << "Community: " << community << ", Pagerank: " << pagerank_sum[community] << std::endl;
}
//outfile_rank.close();
//outfile_pro_pos.close();
outfile_pagerank.close();
//outfile_label_ranking.close();
//outfile_sums.close();
//outfile_sums_perc.close();
algs.save_local_metrics(filename_prefix, pagerankv, is_pagerank);
}
static void print_preamble(std::ofstream &out_summary, graph &g)
{
std::cout << "Number of nodes: " << g.get_num_nodes() << std::endl;
out_summary << "Number of nodes: " << g.get_num_nodes() << std::endl;
std::cout << "Number of edges: " << g.get_num_edges() << "\n" << std::endl;
out_summary << "Number of edges: " << g.get_num_edges() << "\n" << std::endl;
for (int community = 0; community < g.get_num_communities(); ++community) {
std::cout << "Community " << community << ": " << g.get_community_size(community) <<
" nodes (" << g.get_community_size(community) / (double)g.get_num_nodes() * 100 << "%)" << std::endl;
out_summary << "Community " << community << ": " << g.get_community_size(community) <<
" nodes (" << g.get_community_size(community) / (double)g.get_num_nodes() * 100 << "%)" << std::endl;
}
}
static void print_algo_info(std::string algo_name, std::ofstream &out_summary,
personalization_t &personalize_type, double jump_prob, int extra_info)
{
std::string personalize_type_s = "";
if (personalize_type == personalization_t::ATTRIBUTE_PERSONALIZATION)
{
personalize_type_s = "attribute personalization (";
personalize_type_s += std::to_string(extra_info);
personalize_type_s += ") ";
}
else if (personalize_type == personalization_t::NODE_PERSONALIZATION)
{
personalize_type_s = "node personalization (";
personalize_type_s += std::to_string(extra_info);
personalize_type_s += ") ";
}
std::cout << "\nRunning " << personalize_type_s << algo_name <<
" with jump probability = " << jump_prob << " ..." << std::endl;
out_summary << "\nRunning " << personalize_type_s << algo_name <<
" with jump probability = " << jump_prob << " ..." << std::endl;
}
int main(int argc, char **argv)
{
// Define number of threads to use.
//omp_set_num_threads(10);
double jump_prob;
std::string personalize_filename, comm_percentage_filename = "";
personalization_t personalize_type;
int personalize_extra = 0;
bool topk = false; // If -tk is provided.
int k = 0; // The K for topk.
if (!get_options(argc, argv, jump_prob, personalize_filename, personalize_type,
personalize_extra, comm_percentage_filename, topk, k))
return 1;
std::ofstream out_summary("summary.txt");
graph g("out_graph.txt", "out_community.txt");
//Sotiris Tsiou Separate topk alforithms from total.
if (topk)
{
if (comm_percentage_filename != "")
g.load_community_percentage(comm_percentage_filename);
pagerank_algorithms algs(g);
algs.set_personalization_type(personalize_type, personalize_extra);
print_preamble(out_summary, g);
//Call pure pagerank.
print_algo_info("Pagerank", out_summary, personalize_type, jump_prob, personalize_extra);
pagerank_v pagerankv = algs.get_pagerank(1 - jump_prob);
save_pagerank("pagerank", pagerankv, g, algs, out_summary);
print_algo_info("lfpr neighborhood topk", out_summary, personalize_type, jump_prob, personalize_extra);
pagerankv = algs.get_lfprn_topk(k, 1 - jump_prob);
save_pagerank("lfpr_n_topk", pagerankv, g, algs, out_summary);
print_algo_info("lfpr uniform topk", out_summary, personalize_type, jump_prob, personalize_extra);
pagerankv = algs.get_lfpru_topk(k, 1 - jump_prob);
save_pagerank("lfpr_u_topk", pagerankv, g, algs, out_summary);
print_algo_info("lfpr proportional topk", out_summary, personalize_type, jump_prob, personalize_extra);
pagerankv = algs.get_lfprp_topk(k, 1 - jump_prob);
save_pagerank("lfpr_p_topk", pagerankv, g, algs, out_summary);
print_algo_info("lfpru hybrid topk", out_summary, personalize_type, jump_prob, personalize_extra);
pagerankv = algs.get_lfprhu_topk(k, 1 - jump_prob);
save_pagerank("lfpr_hu_topk", pagerankv, g, algs, out_summary);
print_algo_info("lfprn hybrid topk", out_summary, personalize_type, jump_prob, personalize_extra);
pagerankv = algs.get_lfprhn_topk(k, 1 - jump_prob);
save_pagerank("lfpr_hn_topk", pagerankv, g, algs, out_summary);
} else
{
if (personalize_type == personalization_t::ATTRIBUTE_PERSONALIZATION)
g.load_attributes(personalize_filename);
if (comm_percentage_filename != "")
g.load_community_percentage(comm_percentage_filename);
pagerank_algorithms algs(g);
algs.set_personalization_type(personalize_type, personalize_extra);
print_preamble(out_summary, g);
print_algo_info("Pagerank", out_summary, personalize_type, jump_prob, personalize_extra);
pagerank_v pagerankv = algs.get_pagerank(1 - jump_prob);
save_pagerank("pagerank", pagerankv, g, algs, out_summary);
print_algo_info("global uniform Pagerank", out_summary, personalize_type, jump_prob, personalize_extra);
pagerankv = algs.get_global_uniform_fair_pagerank(1 - jump_prob);
save_pagerank("global_uniform", pagerankv, g, algs, out_summary);
print_algo_info("global proportional Pagerank", out_summary, personalize_type, jump_prob, personalize_extra);
pagerankv = algs.get_global_proportional_fair_pagerank(1 - jump_prob);
save_pagerank("global_proportional", pagerankv, g, algs, out_summary);
print_algo_info("lfpr uniform", out_summary, personalize_type, jump_prob, personalize_extra);
pagerankv = algs.get_step_uniform_fair_pagerank(1 - jump_prob);
save_pagerank("lfpr_u", pagerankv, g, algs, out_summary);
print_algo_info("lfpr proportional", out_summary, personalize_type, jump_prob, personalize_extra);
pagerankv = algs.get_step_proportional_fair_pagerank(1 - jump_prob);
save_pagerank("lfpr_p", pagerankv, g, algs, out_summary);
print_algo_info("local neighborhood", out_summary, personalize_type, jump_prob, personalize_extra);
pagerankv = algs.get_local_fair_pagerank(1 - jump_prob);
save_pagerank("lfpr_n", pagerankv, g, algs, out_summary);
}
}
| 37.723214 | 111 | 0.708955 | [
"vector"
] |
fb75e8667a6bdf3d001f082e64f6a8e8e7f5b1c7 | 2,454 | hpp | C++ | libEPLViz/src/mainWidgets/cycleCommand/CycleCommandsModel.hpp | epl-viz/EPL-Viz | 80d790110113f83da6845ce124997d13bfd45270 | [
"BSD-3-Clause"
] | 3 | 2017-01-23T13:29:21.000Z | 2021-03-08T17:40:42.000Z | libEPLViz/src/mainWidgets/cycleCommand/CycleCommandsModel.hpp | epl-viz/EPL-Viz | 80d790110113f83da6845ce124997d13bfd45270 | [
"BSD-3-Clause"
] | 4 | 2017-03-26T12:56:08.000Z | 2017-08-18T20:32:37.000Z | libEPLViz/src/mainWidgets/cycleCommand/CycleCommandsModel.hpp | epl-viz/EPL-Viz | 80d790110113f83da6845ce124997d13bfd45270 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2017, EPL-Vizards
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the EPL-Vizards nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL EPL-Vizards 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.
*/
/*!
* \file CycleCommandsModel.hpp
* Adapted from https://doc.qt.io/qt-5/qtwidgets-itemviews-editabletreemodel-example.html
*/
#pragma once
#include "BaseModel.hpp"
#include "CyCoTreeItem.hpp"
#include "TreeModelBase.hpp"
#include <QAbstractItemModel>
#include <QTreeView>
namespace EPL_Viz {
class CycleCommandsModel : public TreeModelBase, public BaseModel {
Q_OBJECT
private:
std::vector<EPL_DataCollect::Packet> currentPackets;
bool hasChanged = false;
protected:
void init() override;
void update() override;
void updateWidget() override;
public:
CycleCommandsModel(MainWindow *mw, QTreeView *widget);
CycleCommandsModel() = delete;
~CycleCommandsModel();
QString getName() override { return "CycleCommandsModel"; }
private slots:
void changeSelection(QModelIndex index);
signals:
void packetChanged(uint64_t);
};
}
| 38.34375 | 89 | 0.745314 | [
"vector"
] |
65343c6fb519f94d4f3eeeb9698c9fbce195c896 | 2,543 | cpp | C++ | AAAAnimation/player/ascii_player_thread.cpp | ppodds/AAAAnimation | a3494ac6de7ff1c16ccdb008282ade538410f764 | [
"MIT"
] | 17 | 2021-12-29T15:03:25.000Z | 2022-01-13T08:21:34.000Z | AAAAnimation/player/ascii_player_thread.cpp | ppodds/AAAAnimation | a3494ac6de7ff1c16ccdb008282ade538410f764 | [
"MIT"
] | null | null | null | AAAAnimation/player/ascii_player_thread.cpp | ppodds/AAAAnimation | a3494ac6de7ff1c16ccdb008282ade538410f764 | [
"MIT"
] | 2 | 2021-12-31T06:54:52.000Z | 2022-01-01T21:22:37.000Z | #include "ascii_player_thread.h"
#include <iostream>
#include "../ffmpeg/video_decoder.h"
#include "../console/console_controller.h"
#include "../transform.h"
#include "../utils.h"
#include <QThread>
AsciiPlayerThread::AsciiPlayerThread()
{
}
AsciiPlayerThread::AsciiPlayerThread(std::string file_path)
{
this->file_path = file_path;
this->position = 0;
}
void AsciiPlayerThread::run()
{
// stdout buffer
char* buf = new char[1024 * 256];
// set stdout buffer, I guess it would speed up program output
setbuf(stdout, buf);
// VideoDecoder instance
VideoDecoder video_decoder = VideoDecoder(file_path);
// ConsoleController instance
ConsoleController console_controller;
// set console mode to enable virtual terminal processing
console_controller.set_console_mode();
// set console font size, family... etc.
console_controller.set_console_font();
// set console screen buffer size and window size
console_controller.set_console_screen_buffer(video_decoder.get_video_width(), video_decoder.get_video_height());
// the latest frame which decoded by decoder
AVFrame* frame = video_decoder.next_frame();
// ascii frame which should be output
unsigned char* arr = nullptr;
// video timebase represent as a rational
AVRational timebase_rational = video_decoder.get_video_timebase();
// timebase in second
float timebase = (float)timebase_rational.num / (float)timebase_rational.den;
while (frame != nullptr) {
// the time which frame should be played in ms
float play_time = frame->pts * timebase * 1000;
// only calculate when this frame is a video frame and this frame is not too late to play
if (frame->pict_type != AV_PICTURE_TYPE_NONE && position <= play_time)
{
// video height
int height = frame->height;
// video width
int width = frame->width;
// initialize ascii frame buffer
if (arr == nullptr)
arr = new unsigned char[(long long)height * (width + 1)]();
// calculate ascii frame from video's luminance
transform(frame->data[0], arr, width, height, frame->linesize[0]);
// check time again
// wait until the proper time and play this frame
wait_until_smaller(play_time - 150, &position); // 150ms offset to avoid drop too many frames
// output ascii frame
std::cout << arr;
// set cursur position to left top
console_controller.top();
}
// get next frame from decoder
frame = video_decoder.next_frame();
}
// release memory
delete[] arr;
delete[] buf;
}
void AsciiPlayerThread::setPosition(qint64 position)
{
this->position = position;
} | 33.025974 | 113 | 0.731026 | [
"transform"
] |
653b7152f54fa4fe61630c83c051691012aca414 | 8,508 | cpp | C++ | src/galview/GuiFunctions.cpp | ranjeethmahankali/GeomAlgoLib | 21f1374f5a6adf8daa207999a4354ecad5254b5f | [
"Apache-2.0"
] | 9 | 2020-06-03T10:27:01.000Z | 2021-06-03T16:18:35.000Z | src/galview/GuiFunctions.cpp | ranjeethmahankali/GeomAlgoLib | 21f1374f5a6adf8daa207999a4354ecad5254b5f | [
"Apache-2.0"
] | null | null | null | src/galview/GuiFunctions.cpp | ranjeethmahankali/GeomAlgoLib | 21f1374f5a6adf8daa207999a4354ecad5254b5f | [
"Apache-2.0"
] | 2 | 2020-03-18T05:20:13.000Z | 2021-02-17T17:15:07.000Z | #include <galcore/Types.h>
#include <galcore/Util.h>
#include <galfunc/Functions.h>
#include <galfunc/TypeHelper.h>
#include <galview/AnnotationsView.h>
#include <galview/Context.h>
#include <galview/GuiFunctions.h>
#include <galview/Views.h>
#include <galview/Widget.h>
#include <cstdint>
#include <iostream>
#include <memory>
#include <sstream>
namespace gal {
namespace viewfunc {
static view::Panel* sInputPanel = nullptr;
static view::Panel* sOutputPanel = nullptr;
static std::vector<std::function<void()>> sOutputCallbacks;
static std::unordered_map<std::string, const view::CheckBox&> sShowCheckboxes;
/**
* @brief Gets the visibility checkbox from the output panel with the given name.
* If a checkbox with the given name doesn't exist, one will be added.
* @param name the unique name that identifies the checkbox.
*/
static const view::CheckBox& getCheckBox(const std::string name)
{
auto match = sShowCheckboxes.find(name);
if (match != sShowCheckboxes.end()) {
return match->second;
}
auto pair =
sShowCheckboxes.emplace(name, *(outputPanel().newWidget<view::CheckBox>(name, true)));
return pair.first->second;
}
void initPanels(view::Panel& inputs, view::Panel& outputs)
{
sInputPanel = &inputs;
sOutputPanel = &outputs;
}
view::Panel& inputPanel()
{
return *sInputPanel;
}
view::Panel& outputPanel()
{
return *sOutputPanel;
}
void evalOutputs()
{
for (auto& cbfn : sOutputCallbacks) {
cbfn();
}
}
void unloadAllOutputs()
{
std::cout << "Unloading all output data...\n";
sOutputCallbacks.clear();
sInputPanel->clear();
sOutputPanel->clear();
}
// TODO: TagsFunc
// TODO: GlyphsFunc
struct TextFieldFunc : public gal::func::TVariable<std::string>,
public gal::view::TextInput
{
public:
using PyOutputType = typename gal::func::TVariable<std::string>::PyOutputType;
TextFieldFunc(const std::string& label)
: gal::func::TVariable<std::string>("")
, gal::view::TextInput(label, "") {};
private:
using gal::view::TextInput::addHandler;
protected:
void handleChanges() override
{
if (isEdited())
this->set(this->mValue);
clearEdited();
}
};
// Simple functions that are not part of the functional system.
void py_set2dMode(bool flag)
{
gal::view::Context::get().set2dMode(flag);
};
void py_useOrthoCam()
{
gal::view::Context::get().setOrthographic();
}
void py_usePerspectiveCam()
{
gal::view::Context::get().setPerspective();
}
typename TextFieldFunc::PyOutputType py_textField(const std::string& label)
{
auto fn = gal::func::store::makeFunction<TextFieldFunc>(label);
inputPanel().addWidget(std::dynamic_pointer_cast<gal::view::Widget>(fn));
return fn->pythonOutputRegs();
};
// TODO: py_tags
// TODO: py_glyphs
void py_loadGlyphs(const boost::python::list& lst)
{
std::vector<std::pair<std::string, std::string>> pairs;
gal::func::Converter<boost::python::list, decltype(pairs)>::assign(lst, pairs);
std::vector<std::pair<std::string, fs::path>> pairs2(pairs.size());
std::transform(pairs.begin(),
pairs.end(),
pairs2.begin(),
[](const std::pair<std::string, std::string>& p) {
return std::make_pair(p.first, fs::path(p.second));
});
gal::view::loadGlyphs(pairs2);
}
int32_t py_glyphIndex(const std::string& str)
{
return int32_t(gal::view::getGlyphIndex(str));
}
/**
* @brief Function that adds the given object to the 3d scene, if it is a drawable object.
* The output type of the function is the draw-id of the object added to the scene.
*
* @tparam T The object to be drawn.
*/
template<typename T>
struct ShowFunc : public func::TFunction<const func::data::Tree<T>, uint64_t>
{
static_assert(TypeInfo<T>::value, "Unknown type");
using BaseT = func::TFunction<const func::data::Tree<T>, uint64_t>;
using PyOutputType = typename BaseT::PyOutputType;
ShowFunc(const std::string& label,
const bool* visibilityFlag,
const func::Register<T>& reg)
: BaseT(
[visibilityFlag](const func::data::Tree<T>& objs, uint64_t& id) {
if constexpr (view::Drawable<T>::value) {
id = view::Views::add<T>(objs.values(), visibilityFlag, id);
}
else {
std::cerr << TypeInfo<T>::name() << " is not a drawable type\n";
}
},
std::make_tuple(reg))
{
auto& tree = std::get<0>(this->mOutputs);
tree.resize(1);
tree.value(0) = 0;
}
virtual ~ShowFunc() = default;
};
/**
* @brief
*
* @tparam T The type of object to be added to the scene.
* @param label The name of the object. This will be the label of the checkbox that
* controls the visibility of the object.
*
* @param reg The register that contains the object to be drawn.
* @return Register that contains the draw-id of the object added to the scene.
*/
template<typename T>
typename ShowFunc<T>::PyOutputType py_show(const std::string& label,
const func::Register<T>& reg)
{
std::shared_ptr<ShowFunc<T>> sfn = gal::func::store::makeFunction<ShowFunc<T>>(
label, getCheckBox(label).checkedPtr(), reg);
auto fn = std::dynamic_pointer_cast<func::Function>(sfn);
func::store::addFunction(fn);
const func::Function* ptr = fn.get();
sOutputCallbacks.push_back([ptr]() { ptr->update(); });
return sfn->pythonOutputRegs();
}
/**
* @brief Prints the given object to the output panel.
*
* @tparam T The type of the object to be printed.
*/
template<typename T>
struct PrintFunc : public func::TFunction<const func::data::Tree<T>, uint8_t>,
public view::Text
{
using BaseT = func::TFunction<const func::data::Tree<T>, uint8_t>;
using PyOutputType = typename BaseT::PyOutputType;
std::string mLabel;
std::stringstream mStream;
PrintFunc(const std::string& label, const func::Register<T>& reg)
: mLabel(label)
, view::Text("")
, BaseT(
[this](const func::data::Tree<T>& obj, uint8_t& success) {
mStream.clear();
mStream.str("");
mStream << mLabel << ": \n" << obj;
this->mValue = mStream.str();
success = 1;
},
std::make_tuple(reg)) {};
virtual ~PrintFunc() = default;
};
/**
* @brief Prints the object to the output panel.
*
* @tparam T The type of the object to be printed.
* @param label The label to be used in the output panel.
* @param reg The register containing the object.
* @return A boolean register indicating success status.
*/
template<typename T>
typename PrintFunc<T>::PyOutputType py_print(const std::string& label,
const func::Register<T>& reg)
{
std::shared_ptr<PrintFunc<T>> pfn =
gal::func::store::makeFunction<PrintFunc<T>>(label, reg);
auto fn = std::dynamic_pointer_cast<func::Function>(pfn);
func::store::addFunction(fn);
const func::Function* ptr = fn.get();
sOutputCallbacks.push_back([ptr]() { ptr->update(); });
outputPanel().addWidget(std::dynamic_pointer_cast<view::Widget>(pfn));
return pfn->pythonOutputRegs();
}
namespace python {
using namespace boost::python;
template<typename T>
struct defOutputFuncs : public gal::func::python::defClass<T>
{
using BaseType = gal::func::python::defClass<T>;
static void invoke()
{
def("show", py_show<T>);
def("print", py_print<T>);
}
};
} // namespace python
} // namespace viewfunc
} // namespace gal
#define GAL_DEF_PY_FN(fnName) def(#fnName, py_##fnName);
BOOST_PYTHON_MODULE(pygalview)
{
using namespace boost::python;
using namespace gal::viewfunc;
using namespace gal::viewfunc::python;
// Sliders for float input
def("sliderf32", gal::viewfunc::py_slider<float>);
def("slideri32", gal::viewfunc::py_slider<int32_t>);
def("sliderVec3", gal::viewfunc::py_slider<glm::vec3>);
def("sliderVec2", gal::viewfunc::py_slider<glm::vec2>);
gal::func::typemanager::invoke<defOutputFuncs>();
// Text fields for string inputs
GAL_DEF_PY_FN(textField);
// Viewer annotations
// GAL_DEF_PY_FN(tags);
// GAL_DEF_PY_FN(glyphs);
GAL_DEF_PY_FN(loadGlyphs);
GAL_DEF_PY_FN(glyphIndex);
// Viewer controls.
GAL_DEF_PY_FN(set2dMode);
GAL_DEF_PY_FN(useOrthoCam);
GAL_DEF_PY_FN(usePerspectiveCam);
};
| 28.550336 | 90 | 0.647978 | [
"object",
"vector",
"transform",
"3d"
] |
653f834688dab462092359bab5b63abcbc09a645 | 1,820 | cpp | C++ | Examples/Cpp/source/Exchange_EWS/SendEmailToPrivateDistributionList.cpp | kashifiqb/Aspose.Email-for-C | 96684cb6ed9f4e321a00c74ca219440baaef8ba8 | [
"MIT"
] | 4 | 2019-12-01T16:19:12.000Z | 2022-03-28T18:51:42.000Z | Examples/Cpp/source/Exchange_EWS/SendEmailToPrivateDistributionList.cpp | kashifiqb/Aspose.Email-for-C | 96684cb6ed9f4e321a00c74ca219440baaef8ba8 | [
"MIT"
] | 1 | 2022-02-15T01:02:15.000Z | 2022-02-15T01:02:15.000Z | Examples/Cpp/source/Exchange_EWS/SendEmailToPrivateDistributionList.cpp | kashifiqb/Aspose.Email-for-C | 96684cb6ed9f4e321a00c74ca219440baaef8ba8 | [
"MIT"
] | 5 | 2017-09-27T14:43:20.000Z | 2021-11-16T06:47:11.000Z | #include "Examples.h"
#include <system/string.h>
#include <system/shared_ptr.h>
#include <system/object.h>
#include <system/exceptions.h>
#include <system/console.h>
#include <system/array.h>
#include <net/network_credential.h>
#include <MailMessage.h>
#include <MailAddress.h>
#include <Clients/Exchange/WebService/EWSClient/IEWSClient.h>
#include <Clients/Exchange/WebService/EWSClient/EWSClient.h>
#include <Clients/Exchange/ExchangeDistributionList.h>
using namespace System;
using namespace Aspose::Email;
using namespace Aspose::Email::Clients::Exchange;
using namespace Aspose::Email::Clients::Exchange::WebService;
void SendEmailToPrivateDistributionList()
{
try
{
// Set mailboxURI, Username, password, domain information
System::String mailboxUri = u"https://ex2010/ews/exchange.asmx";
System::String username = u"test.exchange";
System::String password = u"pwd";
System::String domain = u"ex2010.local";
System::SharedPtr<System::Net::NetworkCredential> credentials = System::MakeObject<System::Net::NetworkCredential>(username, password, domain);
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser());
System::ArrayPtr<System::SharedPtr<ExchangeDistributionList>> distributionLists = client->ListDistributionLists();
System::SharedPtr<MailAddress> distributionListAddress = distributionLists[0]->ToMailAddress();
System::SharedPtr<MailMessage> message = System::MakeObject<MailMessage>(System::MakeObject<MailAddress>(u"from@host.com"), distributionListAddress);
message->set_Subject(u"sendToPrivateDistributionList");
client->Send(message);
}
catch (System::Exception& ex)
{
System::Console::WriteLine(ex->get_Message());
}
}
| 41.363636 | 157 | 0.728571 | [
"object"
] |
6545b6fadb65e13e776487d5b1509e9cf4989b1a | 3,368 | cpp | C++ | packages/facilities/common/src/fsm.cpp | Falcons-Robocup/code | 2281a8569e7f11cbd3238b7cc7341c09e2e16249 | [
"Apache-2.0"
] | 2 | 2021-01-15T13:27:19.000Z | 2021-08-04T08:40:52.000Z | packages/facilities/common/src/fsm.cpp | Falcons-Robocup/code | 2281a8569e7f11cbd3238b7cc7341c09e2e16249 | [
"Apache-2.0"
] | null | null | null | packages/facilities/common/src/fsm.cpp | Falcons-Robocup/code | 2281a8569e7f11cbd3238b7cc7341c09e2e16249 | [
"Apache-2.0"
] | 5 | 2018-05-01T10:39:31.000Z | 2022-03-25T03:02:35.000Z | // Copyright 2015-2018 Tim Kouters (Falcons)
// SPDX-License-Identifier: Apache-2.0
/**
* File: fsm.cpp
* Author: Jan Feitsma
* Creation: 2014-12-27
* Description: FiniteStateMachine implementations.
*
*
*/
#include "ext/fsm.hpp"
#include "tracing.hpp"
State::State(int i, std::string s)
{
id = i;
name = s;
entryAction = 0;
exitAction = 0;
TRACE("registered state %d with name %s", i, s.c_str());
}
Transition::Transition(int from, int to, boost::function<bool()> cond)
{
fromState = from;
toState = to;
condition = cond;
TRACE("registered statetransition between %d and %d", from, to);
}
FiniteStateMachine::FiniteStateMachine()
{
TRACEF();
reset();
}
FiniteStateMachine::~FiniteStateMachine()
{
TRACEF();
destroy();
}
void FiniteStateMachine::destroy()
{
TRACEF();
reset();
}
void FiniteStateMachine::reset()
{
TRACEF();
m_current_state = 0;
m_states.clear();
m_transitions.clear();
m_state2idx.clear();
}
void FiniteStateMachine::registerState(std::string statename)
{
TRACE("statename=%s", statename.c_str());
if (hasState(statename))
{
TRACE("already exists");
return;
}
int id = m_states.size();
TRACE("assigning id=%d", id);
m_states.push_back(State(id, statename));
m_state2idx[statename] = id;
// add empty transition list
m_transitions.push_back(std::vector<Transition>());
}
bool FiniteStateMachine::hasState(std::string statename) const
{
return m_state2idx.count(statename);
}
std::string FiniteStateMachine::getCurrentState() const
{
return m_states[m_current_state].name;
}
std::vector<State> const & FiniteStateMachine::getStates() const
{
return m_states;
}
void FiniteStateMachine::registerTransition(std::string from, std::string to, boost::function<bool()> transitionCondition)
{
TRACEF("from=%s to=%s", from.c_str(), to.c_str());
// register if not existing
registerState(from);
registerState(to);
m_transitions[m_state2idx[from]].push_back(Transition(m_state2idx[from], m_state2idx[to], transitionCondition));
}
void FiniteStateMachine::registerEntryAction(std::string state_name, boost::function<void(void)> action)
{
TRACEF("start state_name%s", state_name.c_str());
registerState(state_name);
m_states[m_state2idx[state_name]].entryAction = action;
}
void FiniteStateMachine::registerExitAction(std::string state_name, boost::function<void(void)> action)
{
TRACEF("start state_name%s", state_name.c_str());
registerState(state_name);
m_states[m_state2idx[state_name]].exitAction = action;
}
void FiniteStateMachine::iterate()
{
TRACEF("start");
// check if FSM has been initialized, i.e. if states have been defined
if (!m_states.size()) return;
TRACE("current state %s (%d)", m_states[m_current_state].name.c_str(), m_current_state);
// check conditions
TRACE("checking %d conditions", (int)m_transitions[m_current_state].size());
for (int i = 0; i < (int)m_transitions[m_current_state].size(); ++i)
{
if (m_transitions[m_current_state][i].condition())
{
int newState = m_transitions[m_current_state][i].toState;
TRACE("transition i=%d: changing state to %s (%d)", i, m_states[newState].name.c_str(), newState);
if (m_states[m_current_state].exitAction) m_states[m_current_state].exitAction();
m_current_state = newState;
if (m_states[m_current_state].entryAction) m_states[m_current_state].entryAction();
break;
}
}
}
| 24.230216 | 122 | 0.721496 | [
"vector"
] |
65461d013f600771ef2e13dcaa30a3359ba6a92e | 3,343 | cpp | C++ | src/server/PipelineManager.cpp | rsennrich/SLT.KIT | 36884fe4913e6b0eca0e9621c4d7e081212d1910 | [
"MIT"
] | 21 | 2018-08-07T18:02:31.000Z | 2022-03-15T15:49:51.000Z | src/server/PipelineManager.cpp | rsennrich/SLT.KIT | 36884fe4913e6b0eca0e9621c4d7e081212d1910 | [
"MIT"
] | 2 | 2018-06-13T07:39:11.000Z | 2019-03-21T07:29:01.000Z | src/server/PipelineManager.cpp | rsennrich/SLT.KIT | 36884fe4913e6b0eca0e9621c4d7e081212d1910 | [
"MIT"
] | 19 | 2018-08-07T18:27:48.000Z | 2021-12-30T05:41:17.000Z | #include "PipelineManager.h"
PipelineManager::PipelineManager(xml_node<> * n) {
init(n);
}
PipelineManager::PipelineManager(const char * filename) {
ifstream myfile(filename);
vector<char> * xmlFile = new vector<char>((istreambuf_iterator<char>(myfile)), istreambuf_iterator<char>( ));
xmlFile->push_back('\0');
updateServices = false;
xml_document<> * xmlDoc = new xml_document<>; // character type defaults to char
xmlDoc->parse<0>((&(*xmlFile)[0])); // 0 means default parse flags
init(xmlDoc->first_node());
delete xmlFile;
delete xmlDoc;
}
PipelineManager::~PipelineManager() {
delete service;
delete connection;
delete data;
}
void PipelineManager::init(xml_node<> * desc) {
translator = NULL;
updator = NULL;
for (xml_node<> * node = desc->first_node(); node ; node = node->next_sibling()) {
if (strcmp(node->name(), "service") == 0) {
service = ServiceFactory::createService(node,Service::getRoot());
}else if (strcmp(node->name(), "connection") == 0) {
connection = ConnectionFactory::createConnection(node,this);
}else if (strcmp(node->name(), "data") == 0) {
data = DataFlow::create(node);
}else if (strcmp(node->name(), "updateServices") == 0) {
updateServices = string(trim(node->value())).compare("1") == 0;
}
}
if(updateServices) {
service->updateServices();
}
}
void PipelineManager::start() {
connection->start();
}
void PipelineManager::onlyInput(const Segment & in) {
data->input(in);
cout << "Input:" << in.text << endl;
}
void PipelineManager::input(const Segment & in) {
data->input(in);
cout << "Input:" << in.text << endl;
accesstranslator.lock();
cout << "Check translator:" << translator << endl;
if(translator == NULL) {
cout << "Start translator" << endl;
vector<Segment> d = data->getData();
translator = new thread([=] { process(d);});
}else {
cout << "Translator still running -> No new translation" << endl;
}
accesstranslator.unlock();
}
void PipelineManager::update() {
service->updateServices();
accessUpdator.lock();
updator = NULL;
accessUpdator.unlock();
}
void PipelineManager::process(vector<Segment> segments) {
if(updateServices) {
accessUpdator.lock();
if(updator == NULL) {
updator = new thread([=] {update();});
}
accessUpdator.unlock();
}
data->process(segments,service);
cout << "Data translationed" << endl;
accesstranslator.lock();
cout << "Reset translator ..." << endl;
translator = NULL;
cout << "Reset Done" << translator << endl;
accesstranslator.unlock();
connection->send(segments);
cout << "Data send" << endl;
}
void PipelineManager::markFinal() {
data->markFinal();
}
void PipelineManager::clear() {
data->clear();
}
void PipelineManager::finalize() {
//generate Translation
accesstranslator.lock();
if(translator == NULL) {
cout << "Start translator" << endl;
vector<Segment> d = data->getData();
translator = new thread([=] { process(d); } );
}else {
cout << "Translator still running -> No new translation" << endl;
}
accesstranslator.unlock();
}
| 21.567742 | 113 | 0.605145 | [
"vector"
] |
65464e090f7e278a572d955f6e5a093ddf01dbb7 | 2,237 | hpp | C++ | octopus/io/multi_writer.hpp | STEllAR-GROUP/octopus | a1f910d63380e4ebf91198ac2bc2896505ce6146 | [
"BSL-1.0"
] | 4 | 2016-01-30T14:47:21.000Z | 2017-11-19T19:03:19.000Z | octopus/io/multi_writer.hpp | STEllAR-GROUP/octopus | a1f910d63380e4ebf91198ac2bc2896505ce6146 | [
"BSL-1.0"
] | null | null | null | octopus/io/multi_writer.hpp | STEllAR-GROUP/octopus | a1f910d63380e4ebf91198ac2bc2896505ce6146 | [
"BSL-1.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2012 Bryce Adelstein-Lelbach
//
// 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)
////////////////////////////////////////////////////////////////////////////////
#if !defined(OCTOPUS_F255A1F0_667F_4FED_8AD0_495BF1DD0284)
#define OCTOPUS_F255A1F0_667F_4FED_8AD0_495BF1DD0284
#include <octopus/io/writer.hpp>
#include <boost/serialization/vector.hpp>
namespace octopus
{
struct multi_writer : writer_base
{
private:
std::vector<writer> writers_;
public:
multi_writer() : writers_() {}
multi_writer(multi_writer const& other)
: writers_(other.writers_)
{}
multi_writer(BOOST_RV_REF(multi_writer) other)
: writers_(other.writers_)
{}
multi_writer(std::vector<writer> const& writers)
: writers_(writers)
{}
multi_writer(BOOST_RV_REF(std::vector<writer>) writers)
: writers_(writers)
{}
void add_writer(writer const& w)
{
writers_.push_back(w);
}
void add_writer(BOOST_RV_REF(writer) w)
{
writers_.push_back(w);
}
void begin_epoch(octree_server& e, double time)
{
for (boost::uint64_t i = 0; i < writers_.size(); ++i)
writers_[i].begin_epoch(e, time);
}
void end_epoch(octree_server& e)
{
for (boost::uint64_t i = 0; i < writers_.size(); ++i)
writers_[i].end_epoch(e);
}
// IMPLEMENT: Do actual I/O in a separate OS-thread.
void operator()(octree_server& e)
{
for (boost::uint64_t i = 0; i < writers_.size(); ++i)
writers_[i](e);
}
writer_base* clone() const
{
return new multi_writer(writers_);
}
template <typename Archive>
void serialize(Archive& ar, const unsigned int)
{
ar & hpx::util::base_object_nonvirt<writer_base>(*this);
ar & writers_;
}
};
}
BOOST_CLASS_EXPORT_GUID(octopus::multi_writer, "multi_writer")
BOOST_CLASS_TRACKING(octopus::multi_writer, boost::serialization::track_never)
#endif // OCTOPUS_F255A1F0_667F_4FED_8AD0_495BF1DD0284
| 24.582418 | 80 | 0.607063 | [
"vector"
] |
654c2fb7dcb110903bae079431ca81b4104cb425 | 7,430 | cc | C++ | src/mem/spm_mem.cc | markoshorro/gem5-spm | e3de640bf071ab9f64f4e96763a5c75c9cc50350 | [
"BSD-3-Clause"
] | 6 | 2016-11-15T06:14:09.000Z | 2020-05-07T01:05:33.000Z | src/mem/spm_mem.cc | markoshorro/gem5-spm | e3de640bf071ab9f64f4e96763a5c75c9cc50350 | [
"BSD-3-Clause"
] | 3 | 2018-09-04T20:59:37.000Z | 2019-12-05T14:09:02.000Z | src/mem/spm_mem.cc | UDC-GAC/gem5-spm | e3de640bf071ab9f64f4e96763a5c75c9cc50350 | [
"BSD-3-Clause"
] | 4 | 2021-05-04T02:16:56.000Z | 2021-11-03T03:56:17.000Z | /*
* Copyright (c) 2015. Markos Horro
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Markos Horro
*
*/
#include "base/random.hh"
#include "mem/spm_mem.hh"
#include "debug/Drain.hh"
#include "sim/system.hh"
using namespace std;
void
ScratchpadMemory::regStats()
{
using namespace Stats;
AbstractMemory::regStats();
System *system = (AbstractMemory::system());
readEnergy
.name(name() + ".energy_read")
.desc("Total energy reading (pJ)")
.precision(0)
.prereq(AbstractMemory::numReads)
.flags(total | nozero | nonan)
;
for (int i = 0; i < system->maxMasters(); i++) {
readEnergy.subname(i, system->getMasterName(i));
}
writeEnergy
.name(name() + ".energy_write")
.desc("Total energy writting (pJ)")
.precision(0)
.prereq(AbstractMemory::numWrites)
.flags(total | nozero | nonan)
;
for (int i = 0; i < system->maxMasters(); i++) {
writeEnergy.subname(i, system->getMasterName(i));
}
overheadEnergy
.name(name() + ".energy_overhead")
.desc("Other energy (pJ)")
.precision(0)
.prereq(AbstractMemory::numOther)
.flags(total | nozero | nonan)
;
for (int i = 0; i < system->maxMasters(); i++) {
overheadEnergy.subname(i, system->getMasterName(i));
}
totalEnergy
.name(name() + ".energy_total")
.desc("Total energy (pJ)")
.precision(0)
.prereq(overheadEnergy)
.flags(total | nozero | nonan)
;
for (int i = 0; i < system->maxMasters(); i++) {
totalEnergy.subname(i, system->getMasterName(i));
}
averageEnergy
.name(name() + ".energy_average")
.desc("Average energy (pJ)")
.precision(0)
.prereq(totalEnergy)
.flags(total | nozero | nonan)
;
for (int i = 0; i < system->maxMasters(); i++) {
averageEnergy.subname(i, system->getMasterName(i));
}
// Trying to implement a energy model...
readEnergy = AbstractMemory::numReads * energy_read;
writeEnergy = AbstractMemory::numWrites * energy_write;
overheadEnergy = AbstractMemory::numOther * energy_overhead;
totalEnergy = readEnergy + writeEnergy + overheadEnergy;
averageEnergy = (energy_overhead==0) ? totalEnergy / 2 : totalEnergy / 3 ;
}
ScratchpadMemory::ScratchpadMemory(const ScratchpadMemoryParams* p) :
SimpleMemory(p),
latency_write(p->latency_write), latency_write_var(p->latency_write_var),
energy_read(p->energy_read), energy_write(p->energy_write),
energy_overhead(p->energy_overhead)
{
}
Tick
ScratchpadMemory::recvAtomic(PacketPtr pkt)
{
access(pkt);
return pkt->memInhibitAsserted() ? 0 : ((pkt->isRead()) ? getLatency() : getWriteLatency());
}
bool
ScratchpadMemory::recvTimingReq(PacketPtr pkt)
{
/// @todo temporary hack to deal with memory corruption issues until
/// 4-phase transactions are complete
for (int x = 0; x < pendingDelete.size(); x++)
delete pendingDelete[x];
pendingDelete.clear();
if (pkt->memInhibitAsserted()) {
// snooper will supply based on copy of packet
// still target's responsibility to delete packet
pendingDelete.push_back(pkt);
return true;
}
// we should never get a new request after committing to retry the
// current one, the bus violates the rule as it simply sends a
// retry to the next one waiting on the retry list, so simply
// ignore it
if (retryReq)
return false;
// if we are busy with a read or write, remember that we have to
// retry
if (isBusy) {
retryReq = true;
return false;
}
// @todo someone should pay for this
pkt->headerDelay = pkt->payloadDelay = 0;
// update the release time according to the bandwidth limit, and
// do so with respect to the time it takes to finish this request
// rather than long term as it is the short term data rate that is
// limited for any real memory
// only look at reads and writes when determining if we are busy,
// and for how long, as it is not clear what to regulate for the
// other types of commands
if (pkt->isRead() || pkt->isWrite()) {
// calculate an appropriate tick to release to not exceed
// the bandwidth limit
Tick duration = pkt->getSize() * bandwidth;
// only consider ourselves busy if there is any need to wait
// to avoid extra events being scheduled for (infinitely) fast
// memories
if (duration != 0) {
schedule(releaseEvent, curTick() + duration);
isBusy = true;
}
}
// go ahead and deal with the packet and put the response in the
// queue if there is one
bool needsResponse = pkt->needsResponse();
recvAtomic(pkt);
// turn packet around to go back to requester if response expected
if (needsResponse) {
// recvAtomic() should already have turned packet into
// atomic response
assert(pkt->isResponse());
// to keep things simple (and in order), we put the packet at
// the end even if the latency suggests it should be sent
// before the packet(s) before it.
// Difference between read/write latencies
Tick totLat = ((pkt->isRead()) ? getLatency() : 0) + ((pkt->isWrite()) ? getWriteLatency() : 0);
packetQueue.push_back(DeferredPacket(pkt, curTick() + totLat));
if (!retryResp && !dequeueEvent.scheduled())
schedule(dequeueEvent, packetQueue.back().tick);
} else {
pendingDelete.push_back(pkt);
}
return true;
}
Tick
ScratchpadMemory::getWriteLatency() const
{
return latency_write +
(latency_write_var ? random_mt.random<Tick>(0, latency_write_var) : 0);
}
ScratchpadMemory*
ScratchpadMemoryParams::create()
{
return new ScratchpadMemory(this);
}
| 33.926941 | 97 | 0.659354 | [
"model"
] |
65504be186c8bfc94e2a1df713f8343e9969fe67 | 1,745 | hpp | C++ | include/metall/container/experimental/json/json_fwd.hpp | dice-group/metall | 1b899e7d28264ecf937cf848e934eccadc581783 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 37 | 2019-07-03T05:48:42.000Z | 2022-03-10T20:41:53.000Z | include/metall/container/experimental/json/json_fwd.hpp | dice-group/metall | 1b899e7d28264ecf937cf848e934eccadc581783 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 19 | 2019-05-29T07:56:45.000Z | 2022-02-02T07:13:46.000Z | include/metall/container/experimental/json/json_fwd.hpp | dice-group/metall | 1b899e7d28264ecf937cf848e934eccadc581783 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 12 | 2019-06-11T21:56:37.000Z | 2022-01-20T15:51:28.000Z | // Copyright 2021 Lawrence Livermore National Security, LLC and other Metall Project Developers.
// See the top-level COPYRIGHT file for details.
//
// SPDX-License-Identifier: (Apache-2.0 OR MIT)
#ifndef METALL_CONTAINER_EXPERIMENT_JSON_JSON_FWD_HPP
#define METALL_CONTAINER_EXPERIMENT_JSON_JSON_FWD_HPP
#include <variant>
/// \namespace metall::container::experimental
/// \brief Namespace for Metall containers in an experimental phase.
namespace metall::container::experimental {}
/// \namespace metall::container::experimental::json
/// \brief Namespace for Metall JSON container, which is in an experimental phase.
namespace metall::container::experimental::json {}
namespace metall::container::experimental::json {
#if !defined(DOXYGEN_SKIP)
// Forward declaration
template <typename allocator_type>
class value;
template <typename allocator_type>
class array;
template <typename char_type, typename char_traits, typename _allocator_type>
class key_value_pair;
template <typename T, typename allocator_type>
inline value<allocator_type> value_from(T &&, const allocator_type& allocator = allocator_type());
template <typename T, typename allocator_type>
inline T value_to(const value<allocator_type>&);
template <typename allocator_type>
class indexed_object;
template <typename allocator_type>
class compact_object;
#endif // DOXYGEN_SKIP
/// \brief JSON null.
using null_type = std::monostate;
/// \brief JSON object.
/// An object is a table key and value pairs.
/// The order of key-value pairs depends on the implementation.
template <typename allocator_type>
using object = compact_object<allocator_type>;
} // namespace metall::container::experimental::json
#endif //METALL_CONTAINER_EXPERIMENT_JSON_JSON_FWD_HPP
| 29.576271 | 98 | 0.794269 | [
"object"
] |
65534b66ce4eaaeff8d3bd258fbee1f2ac40c993 | 9,607 | cpp | C++ | ext/DRAMSim2/CommandQueueTP.cpp | aferr/TimingCompartments | 8c826a55fd5ed95b24a13489d97cb62a9586ee25 | [
"BSD-3-Clause"
] | null | null | null | ext/DRAMSim2/CommandQueueTP.cpp | aferr/TimingCompartments | 8c826a55fd5ed95b24a13489d97cb62a9586ee25 | [
"BSD-3-Clause"
] | 4 | 2015-01-13T18:27:31.000Z | 2015-01-13T18:27:57.000Z | ext/DRAMSim2/CommandQueueTP.cpp | aferr/TimingCompartments | 8c826a55fd5ed95b24a13489d97cb62a9586ee25 | [
"BSD-3-Clause"
] | 1 | 2021-07-05T18:05:54.000Z | 2021-07-05T18:05:54.000Z | #include "CommandQueueTP.h"
using namespace DRAMSim;
CommandQueueTP::CommandQueueTP(vector< vector<BankState> > &states,
ostream &dramsim_log_, unsigned tpTurnLength_,
int num_pids_, bool fixAddr_,
bool diffPeriod_, int p0Period_, int p1Period_, int offset_,
bool partitioning_):
CommandQueue(states,dramsim_log_,num_pids_)
{
fixAddr = fixAddr_;
tpTurnLength = tpTurnLength_;
diffPeriod = diffPeriod_;
p0Period = p0Period_;
p1Period = p1Period_;
offset = offset_;
partitioning = partitioning_;
#ifdef DEBUG_TP
cout << "TP Debugging is on." <<endl;
#endif
}
void CommandQueueTP::enqueue(BusPacket *newBusPacket)
{
unsigned rank = newBusPacket->rank;
unsigned pid = newBusPacket->threadID;
queues[rank][pid].push_back(newBusPacket);
#ifdef DEBUG_TP
if(newBusPacket->physicalAddress == interesting)
cout << "Enqueued interesting @ "<< currentClockCycle <<endl;
#endif /*DEBUG_TP*/
if (queues[rank][pid].size()>CMD_QUEUE_DEPTH)
{
ERROR("== Error - Enqueued more than allowed in command queue");
ERROR(" Need to call .hasRoomFor(int "
"numberToEnqueue, unsigned rank, unsigned bank) first");
exit(0);
}
pid_last_pop = 0;
last_pid = 0;
}
bool CommandQueueTP::hasRoomFor(unsigned numberToEnqueue, unsigned rank,
unsigned bank, unsigned pid)
{
vector<BusPacket *> &queue = getCommandQueue(rank, pid);
return (CMD_QUEUE_DEPTH - queue.size() >= numberToEnqueue);
}
bool CommandQueueTP::isEmpty(unsigned rank)
{
for(int i=0; i<num_pids; i++)
if(!queues[rank][i].empty()) return false;
return true;
}
vector<BusPacket *> &CommandQueueTP::getCommandQueue(unsigned rank, unsigned
pid)
{
return queues[rank][pid];
}
void CommandQueueTP::refreshPopClosePage(BusPacket **busPacket, bool &
sendingREF)
{
bool foundActiveOrTooEarly = false;
//look for an open bank
for (size_t b=0;b<NUM_BANKS;b++)
{
vector<BusPacket *> &queue = getCommandQueue(refreshRank,getCurrentPID());
//checks to make sure that all banks are idle
if (bankStates[refreshRank][b].currentBankState == RowActive)
{
foundActiveOrTooEarly = true;
#ifdef DEBUG_TP
cout << "TooEarly because row is active with pid " << getCurrentPID()
<< " at time " << currentClockCycle <<endl;
bankStates[refreshRank][b].print();
print();
#endif /*DEBUG_TP*/
//if the bank is open, make sure there is nothing else
// going there before we close it
for (size_t j=0;j<queue.size();j++)
{
BusPacket *packet = queue[j];
if (packet->row ==
bankStates[refreshRank][b].openRowAddress &&
packet->bank == b)
{
if (packet->busPacketType != ACTIVATE &&
isIssuable(packet))
{
*busPacket = packet;
queue.erase(queue.begin() + j);
sendingREF = true;
}
break;
}
}
break;
}
// NOTE: checks nextActivate time for each bank to make sure tRP
// is being
// satisfied. the next ACT and next REF can be issued
// at the same
// point in the future, so just use nextActivate field
// instead of
// creating a nextRefresh field
else if (bankStates[refreshRank][b].nextActivate >
currentClockCycle)
{
foundActiveOrTooEarly = true;
#ifdef DEBUG_TP
cout << "TooEarly because nextActivate is "
<<bankStates[refreshRank][b].nextActivate
<< " at time " << currentClockCycle <<endl;
#endif /*DEBUG_TP*/
break;
}
//}
}
//if there are no open banks and timing has been met, send out the refresh
// reset flags and rank pointer
if (!foundActiveOrTooEarly && bankStates[refreshRank][0].currentBankState
!= PowerDown)
{
*busPacket = new BusPacket(REFRESH, 0, 0, 0, refreshRank, 0, 0,
dramsim_log);
#ifdef DEBUG_TP
// PRINTN("Refresh at " << currentClockCycle << " for rank "
// << refreshRank << endl);
#endif /*DEBUG_TP*/
refreshRank = -1;
refreshWaiting = false;
sendingREF = true;
}
}
bool CommandQueueTP::normalPopClosePage(BusPacket **busPacket, bool
&sendingREF)
{
bool foundIssuable = false;
unsigned startingRank = nextRank;
unsigned startingBank = nextBank;
if(pid_last_pop!= getCurrentPID()){
last_pid = pid_last_pop;
}
pid_last_pop = getCurrentPID();
while(true)
{
//Only get the queue for the PID with the current turn.
vector<BusPacket *> &queue = getCommandQueue(nextRank, getCurrentPID());
vector<BusPacket *> &queue_last = getCommandQueue(nextRank, last_pid);
if (false && !((nextRank == refreshRank) && refreshWaiting) &&
!queue_last.empty())
{
//search from beginning to find first issuable bus packet
for (size_t i=0; i<queue_last.size(); i++)
{
if (isIssuable(queue_last[i]))
{
if(queue_last[i]->busPacketType==ACTIVATE){
continue;
}
// Make sure a read/write that hasn't been activated yet
// isn't removed.
if (i>0 && queue_last[i-1]->busPacketType==ACTIVATE &&
queue_last[i-1]->physicalAddress ==
queue_last[i]->physicalAddress){
continue;
}
*busPacket = queue_last[i];
queue_last.erase(queue_last.begin()+i);
foundIssuable = true;
break;
}
}
}
if(!(false && foundIssuable)){
if (!queue.empty() && !((nextRank == refreshRank) && refreshWaiting))
{
//search from beginning to find first issuable bus packet
for (size_t i=0;i<queue.size();i++)
{
if (isIssuable(queue[i]))
{
if(queue[i]->busPacketType==ACTIVATE){
if(isBufferTime()) continue;
}
//check to make sure we aren't removing a read/write that
//is paired with an activate
if (i>0 && queue[i-1]->busPacketType==ACTIVATE &&
queue[i-1]->physicalAddress ==
queue[i]->physicalAddress){
continue;
}
*busPacket = queue[i];
queue.erase(queue.begin()+i);
foundIssuable = true;
break;
}
}
}
}
//if we found something, break out of do-while
if (foundIssuable) break;
nextRankAndBank(nextRank, nextBank);
if (startingRank == nextRank && startingBank == nextBank)
{
break;
}
}
return foundIssuable;
}
void CommandQueueTP::print()
{
PRINT("\n== Printing Timing Partitioning Command Queue" );
for (size_t i=0;i<NUM_RANKS;i++)
{
PRINT(" = Rank " << i );
for (int j=0;j<num_pids;j++)
{
PRINT(" PID "<< j << " size : " << queues[i][j].size() );
for (size_t k=0;k<queues[i][j].size();k++)
{
PRINTN(" " << k << "]");
queues[i][j][k]->print();
}
}
}
}
unsigned CommandQueueTP::getCurrentPID(){
unsigned ccc_ = currentClockCycle - offset;
unsigned schedule_time = ccc_ % (p0Period + (num_pids-1) * p1Period);
if( schedule_time < p0Period ) return 0;
return (schedule_time - p0Period) / p1Period + 1;
}
bool CommandQueueTP::isBufferTime(){
unsigned ccc_ = currentClockCycle - offset;
unsigned current_tc = getCurrentPID();
unsigned schedule_length = p0Period + p1Period * (num_pids - 1);
unsigned schedule_start = ccc_ - ( ccc_ % schedule_length );
unsigned turn_start = current_tc == 0 ?
schedule_start :
schedule_start + p0Period + p1Period * (current_tc-1);
unsigned turn_end = current_tc == 0 ?
turn_start + p0Period :
turn_start + p1Period;
// Time between refreshes to ANY rank.
unsigned refresh_period = REFRESH_PERIOD/NUM_RANKS/tCK;
unsigned next_refresh = ccc_ + refresh_period - (ccc_ % refresh_period);
unsigned tlength = current_tc == 0 ? p0Period : p1Period;
//TODO It returns a bool you tool
unsigned deadtime = (turn_start <= next_refresh && next_refresh < turn_end) ?
refresh_deadtime( tlength ) :
normal_deadtime( tlength );
return ccc_ >= (turn_end - deadtime);
}
#ifdef DEBUG_TP
bool CommandQueueTP::hasInteresting(){
vector<BusPacket *> &queue = getCommandQueue(nextRank, 1);
for(size_t i=0; i<queue.size(); i++){
if (queue[i]->physicalAddress == interesting)
return true;
}
return false;
}
#endif /*DEBUG_TP*/
| 31.601974 | 82 | 0.545019 | [
"vector"
] |
65539c6b45ce1749a84c4689413bbf93922f4300 | 3,446 | cpp | C++ | src/0.3.7-R3-1/CObject.cpp | DarkP1xel/SAMP-API | 0d43a3603239f2f4bc65b8305ffc72177386cc29 | [
"MIT"
] | 7 | 2019-09-23T10:19:40.000Z | 2021-07-25T06:17:27.000Z | src/0.3.7-R3-1/CObject.cpp | DarkP1xel/SAMP-API | 0d43a3603239f2f4bc65b8305ffc72177386cc29 | [
"MIT"
] | null | null | null | src/0.3.7-R3-1/CObject.cpp | DarkP1xel/SAMP-API | 0d43a3603239f2f4bc65b8305ffc72177386cc29 | [
"MIT"
] | 1 | 2021-04-11T17:13:00.000Z | 2021-04-11T17:13:00.000Z | /*
This is a SAMP (0.3.7-R3) API project file.
Developer: LUCHARE <luchare.dev@gmail.com>
See more here https://github.com/LUCHARE/SAMP-API
Copyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.
*/
#include "CObject.h"
SAMP::CObject::CObject(int nModel, CVector position, CVector rotation, float fDrawDistance, int a10, char a11, char a12) {
((void(__thiscall *)(CObject *, int, CVector, CVector, float, int, char, char))SAMP_ADDROF(0xA8880))(this, nModel, position, rotation, fDrawDistance, a10, a11, a12);
}
float SAMP::CObject::GetDistance(const CMatrix *pMatrix) {
return ((float(__thiscall *)(CObject *, const CMatrix *))SAMP_ADDROF(0xA7730))(this, pMatrix);
}
void SAMP::CObject::Stop() {
((void(__thiscall *)(CObject *))SAMP_ADDROF(0xA77A0))(this);
}
void SAMP::CObject::SetRotation(const CVector *pVector) {
((void(__thiscall *)(CObject *, const CVector *))SAMP_ADDROF(0xA7810))(this, pVector);
}
void SAMP::CObject::SetAttachedToVehicle(ID nId, const CVector *pOffset, const CVector *pRotation) {
((void(__thiscall *)(CObject *, ID, const CVector *, const CVector *))SAMP_ADDROF(0xA7880))(this, nId, pOffset, pRotation);
}
void SAMP::CObject::SetAttachedToObject(ID nId, const CVector *pOffset, const CVector *pRotation, char a5) {
((void(__thiscall *)(CObject *, ID, const CVector *, const CVector *, char))SAMP_ADDROF(0xA7910))(this, nId, pOffset, pRotation, a5);
}
void SAMP::CObject::AttachToVehicle(CVehicle *pVehicle) {
((void(__thiscall *)(CObject *, CVehicle *))SAMP_ADDROF(0xA79B0))(this, pVehicle);
}
void SAMP::CObject::AttachToObject(CObject *pObject) {
((void(__thiscall *)(CObject *, CObject *))SAMP_ADDROF(0xA7A30))(this, pObject);
}
void SAMP::CObject::Rotate(CVector vector) {
((void(__thiscall *)(CObject *, CVector))SAMP_ADDROF(0xA7B30))(this, vector);
}
BOOL SAMP::CObject::AttachedToMovingEntity() {
return ((BOOL(__thiscall *)(CObject *))SAMP_ADDROF(0xA7C30))(this);
}
void SAMP::CObject::SetMaterial(int nModel, int nIndex, const char *szTxd, const char *szTexture, D3DCOLOR color) {
((void(__thiscall *)(CObject *, int, int, const char *, const char *, D3DCOLOR))SAMP_ADDROF(0xA7CA0))(this, nModel, nIndex, szTxd, szTexture, color);
}
void SAMP::CObject::SetMaterialText(int nIndex, const char *szText, char nMaterialSize, const char *szFont, char nFontSize, bool bBold, D3DCOLOR fontColor, D3DCOLOR backgroundColor, char align) {
((void(__thiscall *)(CObject *, int, const char *, char, const char *, char, bool, D3DCOLOR, D3DCOLOR, char))SAMP_ADDROF(0xA7E20))(this, nIndex, szText, nMaterialSize, szFont, nFontSize, bBold, fontColor, backgroundColor, align);
}
bool SAMP::CObject::GetMaterialSize(int nSize, int *x, int *y) {
return ((bool(__thiscall *)(CObject *, int, int *, int *))SAMP_ADDROF(0xA83F0))(this, nSize, x, y);
}
void SAMP::CObject::Render() {
((void(__thiscall *)(CObject *))SAMP_ADDROF(0xA86D0))(this);
}
void SAMP::CObject::Process(float fElapsedTime) {
((void(__thiscall *)(CObject *, float))SAMP_ADDROF(0xA8DC0))(this, fElapsedTime);
}
void SAMP::CObject::ConstructMaterialText() {
((void(__thiscall *)(CObject *))SAMP_ADDROF(0xA9650))(this);
}
void SAMP::CObject::Draw() {
((void(__thiscall *)(CObject *))SAMP_ADDROF(0xA9700))(this);
}
void SAMP::CObject::ShutdownMaterialText() {
((void(__thiscall *)(CObject *))SAMP_ADDROF(0xA8640))(this);
}
| 41.02381 | 231 | 0.701103 | [
"render",
"vector"
] |
655daaf7924ac7eb00ab111d1233f9b489178fcd | 1,848 | hpp | C++ | sdk/sdk/share/httpserver/httpserver/string_utilities.hpp | doyaGu/C0501Q_HWJL01 | 07a71328bd9038453cbb1cf9c276a3dd1e416d63 | [
"MIT"
] | 1 | 2021-10-09T08:05:50.000Z | 2021-10-09T08:05:50.000Z | sdk/sdk/share/httpserver/httpserver/string_utilities.hpp | doyaGu/C0501Q_HWJL01 | 07a71328bd9038453cbb1cf9c276a3dd1e416d63 | [
"MIT"
] | null | null | null | sdk/sdk/share/httpserver/httpserver/string_utilities.hpp | doyaGu/C0501Q_HWJL01 | 07a71328bd9038453cbb1cf9c276a3dd1e416d63 | [
"MIT"
] | null | null | null | /*
This file is part of libhttpserver
Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
*/
#if !defined (_HTTPSERVER_HPP_INSIDE_) && !defined (HTTPSERVER_COMPILATION)
#error "Only <httpserver.hpp> or <httpserverpp> can be included directly."
#endif
#ifndef _STRING_UTILITIES_H_
#define _STRING_UTILITIES_H_
#include <string>
#include <vector>
namespace httpserver
{
namespace string_utilities
{
/**
* Function used to convert a string to its uppercase version.
* It generates a new string in output
* @param str The string to turn uppercase
* @return a string that is the uppercase version of the previous
**/
void to_upper_copy(const std::string& str, std::string& result);
void to_lower_copy(const std::string& str, std::string& result);
size_t string_split(const std::string& s,
std::vector<std::string>& result,
char sep = ' ', bool collapse = true
);
void regex_replace(const std::string& str, const std::string& pattern,
const std::string& replace_str, std::string& result
);
void to_upper(std::string& str);
};
};
#endif
| 33 | 78 | 0.728355 | [
"vector"
] |
656bb04438d1fe2712aa0ce8932eed2ddad33262 | 4,336 | hpp | C++ | include/primer/function.hpp | cbeck88/lua-primer | f6b96a24f96bc3bf03896aea0f758d76ae388fb9 | [
"BSL-1.0"
] | 14 | 2016-07-27T18:14:47.000Z | 2018-06-15T19:54:10.000Z | include/primer/function.hpp | garbageslam/lua-primer | f6b96a24f96bc3bf03896aea0f758d76ae388fb9 | [
"BSL-1.0"
] | 5 | 2016-11-01T23:20:35.000Z | 2016-11-29T21:09:53.000Z | include/primer/function.hpp | cbeck88/lua-primer | f6b96a24f96bc3bf03896aea0f758d76ae388fb9 | [
"BSL-1.0"
] | 2 | 2021-02-07T03:42:22.000Z | 2021-02-10T14:12:00.000Z | // (C) Copyright 2015 - 2018 Christopher Beck
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
/***
* Interface to write quick-n-dirty function call code.
*
* While they all handle popping of errors and return values,
* they don't handle memory errors that can occur while popping the return
* values. So they aren't all that safe.
*/
#include <primer/base.hpp>
PRIMER_ASSERT_FILESCOPE;
#include <primer/support/function.hpp>
#include <primer/support/function_return.hpp>
namespace primer {
// Expects: Function, followed by narg arguments, on top of the stack.
// Returns: Either a reference to the value, or an error message. In either case
// the results are cleared from the stack.
inline expected<lua_ref>
fcn_call_one_ret(lua_State * L, int narg) {
expected<lua_ref> result;
detail::fcn_call(result, L, narg);
return result;
}
// Expects: Function, followed by narg arguments, on top of the stack.
// Returns either a reference to the value, or an error message. In either case
// the results are cleared from the stack.
// This one is noexcept because it does not create any lua_ref's.
inline expected<void>
fcn_call_no_ret(lua_State * L, int narg) noexcept {
expected<void> result;
detail::fcn_call(result, L, narg);
return result;
}
// Expects: Function, followed by narg arguments, on top of the stack.
// Returns all of the functions' results or an error message. In either case
// the results are cleared from the stack.
inline expected<lua_ref_seq>
fcn_call(lua_State * L, int narg) {
expected<lua_ref_seq> result;
detail::fcn_call(result, L, narg);
return result;
}
// Expects a thread stack, satisfying the preconditions to call `lua_resume(L,
// nullptr, narg)`.
// (That means, there should be narg arguments on top of the stack.
// If coroutine has not been started, the function should be just beneath
// them.
// Otherwise, it shouldn't be.)
//
// Calls lua_resume with that many arguments.
// If it returns or yields, the single (expected) return value is popped from
// the stack.
// If there is an error, an error object is returned and the error message is
// popped from the stack, after running an error handler over it.
// The expected<lua_ref> is first return value.
// Use `lua_status` to figure out if it was return or yield.
inline expected<lua_ref>
resume_one_ret(lua_State * L, int narg) {
expected<lua_ref> result;
detail::resume_call(result, L, narg);
return result;
}
// Expects a thread stack, satisfying the preconditions to call `lua_resume(L,
// nullptr, narg)`.
// (That means, there should be narg arguments on top of the stack.
// If coroutine has not been started, the function should be just beneath
// them.
// Otherwise, it shouldn't be.)
//
// Calls lua_resume with that many arguments.
// If it returns or yields, the single (expected) return value is popped from
// the stack.
// If there is an error, an error object is returned and the error message is
// popped from the stack, after running an error handler over it.
// The expected<void> is (potentially) the error message.
// Use `lua_status` to figure out if it was return or yield.
// This one is noexcept because it does not create any lua_ref's.
inline expected<void>
resume_no_ret(lua_State * L, int narg) noexcept {
expected<void> result;
detail::resume_call(result, L, narg);
return result;
}
// Expects a thread stack, satisfying the preconditions to call `lua_resume(L,
// nullptr, narg)`.
// (That means, there should be narg arguments on top of the stack.
// If coroutine has not been started, the function should be just beneath
// them.
// Otherwise, it shouldn't be.)
//
// Calls lua_resume with that many arguments.
// If it returns or yields, all of its return values are returned.
// If there is an error, an error object is returned and the error message is
// popped from the stack,
// after running an error handler over it.
// The expected<lua_ref_seq> is return sequence.
// Use `lua_status` to figure out if it was return or yield.
inline expected<lua_ref_seq>
resume(lua_State * L, int narg) {
expected<lua_ref_seq> result;
detail::resume_call(result, L, narg);
return result;
}
} // end namespace primer
| 35.834711 | 80 | 0.732472 | [
"object"
] |
658478e1d665adceb48ae791c2033d424b034d16 | 8,865 | cpp | C++ | sourceCode/scripting/userParameters.cpp | mdecourse/CoppeliaSimLib | 934e65b4b6ea5a07d08919ae35c50fd3ae960ef2 | [
"RSA-MD"
] | null | null | null | sourceCode/scripting/userParameters.cpp | mdecourse/CoppeliaSimLib | 934e65b4b6ea5a07d08919ae35c50fd3ae960ef2 | [
"RSA-MD"
] | null | null | null | sourceCode/scripting/userParameters.cpp | mdecourse/CoppeliaSimLib | 934e65b4b6ea5a07d08919ae35c50fd3ae960ef2 | [
"RSA-MD"
] | null | null | null | #include "userParameters.h"
#include "app.h"
#include "base64.h"
CUserParameters::CUserParameters()
{
_initialValuesInitialized=false;
}
CUserParameters::~CUserParameters()
{
}
void CUserParameters::initializeInitialValues(bool simulationAlreadyRunning)
{ // is called at simulation start, but also after object(s) have been copied into a scene!
clearInitialParameters();
_initialValuesInitialized=true;
for (size_t i=0;i<userParamEntries.size();i++)
{
SUserParamEntry e;
e.name=userParamEntries[i].name;
e.unit=userParamEntries[i].unit;
e.value=userParamEntries[i].value;
e.properties=userParamEntries[i].properties;
_initialUserParamEntries.push_back(e);
}
}
void CUserParameters::simulationEnded()
{ // Remember, this is not guaranteed to be run! (the object can be copied during simulation, and pasted after it ended). For thoses situations there is the initializeInitialValues routine!
if (_initialValuesInitialized&&App::currentWorld->simulation->getResetSceneAtSimulationEnd())
{
std::vector<SUserParamEntry> currentScriptParamEntries(userParamEntries);
userParamEntries.clear();
for (size_t i=0;i<_initialUserParamEntries.size();i++)
{
if (_initialUserParamEntries[i].properties&2)
{ // parameter is persistent
userParamEntries.push_back(currentScriptParamEntries[i]);
}
else
{
userParamEntries.push_back(_initialUserParamEntries[i]);
}
}
}
_initialValuesInitialized=false;
}
void CUserParameters::clearInitialParameters()
{
_initialValuesInitialized=false;
_initialUserParamEntries.clear();
}
void CUserParameters::moveItem(int index,int newIndex)
{ // should only be called when simulation is stopped
if ((index>=0)&&(index<int(userParamEntries.size()))&&(newIndex>=0)&&(newIndex<int(userParamEntries.size())))
{
SUserParamEntry tmp;
tmp.name=userParamEntries[newIndex].name;
tmp.unit=userParamEntries[newIndex].unit;
tmp.value=userParamEntries[newIndex].value;
tmp.properties=userParamEntries[newIndex].properties;
userParamEntries[newIndex].name=userParamEntries[index].name;
userParamEntries[newIndex].unit=userParamEntries[index].unit;
userParamEntries[newIndex].value=userParamEntries[index].value;
userParamEntries[newIndex].properties=userParamEntries[index].properties;
userParamEntries[index].name=tmp.name;
userParamEntries[index].unit=tmp.unit;
userParamEntries[index].value=tmp.value;
userParamEntries[index].properties=tmp.properties;
}
}
bool CUserParameters::setParameterValue(const char* paramName,const char* paramValue,int paramValueLength)
{
int ind=getParameterIndex(paramName);
if (ind>=0)
{
userParamEntries[ind].value.assign(paramValue,paramValueLength);
userParamEntries[ind].properties=(userParamEntries[ind].properties|4)-4; // Indicates that string doesn't contain embedded 0's
for (int i=0;i<paramValueLength;i++)
{
if (paramValue[i]==0)
{
userParamEntries[ind].properties|=4; // Indicates that string contains embedded 0's
break;
}
}
return(true);
}
return(false);
}
bool CUserParameters::getParameterValue(const char* paramName,std::string& paramValue)
{
int ind=getParameterIndex(paramName);
if (ind>=0)
{
paramValue=userParamEntries[ind].value;
return(true);
}
return(false);
}
void CUserParameters::addParameterValue(const char* paramName,const char* unitText,const char* paramValue,int paramValueLength)
{
int ind=getParameterIndex(paramName);
if (ind<0)
{ // parameter not yet present!
SUserParamEntry e;
e.name=paramName;
e.properties=0;
userParamEntries.push_back(e);
ind=(int)userParamEntries.size()-1;
}
userParamEntries[ind].unit=unitText;
userParamEntries[ind].value.assign(paramValue,paramValueLength);
for (int i=0;i<paramValueLength;i++)
{
if (paramValue[i]==0)
{
userParamEntries[ind].properties|=4; // Indicates that string contains embedded 0's
break;
}
}
}
bool CUserParameters::removeParameterValue(int index)
{
if ( (index<0)||(index>=int(userParamEntries.size())) )
return(false);
userParamEntries.erase(userParamEntries.begin()+index);
return(true);
}
bool CUserParameters::removeParameterValue(const char* paramName)
{
int ind=getParameterIndex(paramName);
if (ind<0)
return(false);
return(removeParameterValue(ind));
}
int CUserParameters::getParameterIndex(const char* paramName)
{
for (size_t i=0;i<userParamEntries.size();i++)
{
if (userParamEntries[i].name==paramName)
return((int)i);
}
return(-1);
}
CUserParameters* CUserParameters::copyYourself()
{
// First the regular stuff:
CUserParameters* p=new CUserParameters();
for (size_t i=0;i<userParamEntries.size();i++)
p->userParamEntries.push_back(userParamEntries[i]);
//// Now we also have to copy the temp values (values created/modified/deleted during simulation)
//for (int i=0;i<int(_initialParameterNames.size());i++)
//{
// p->_initialParameterNames.push_back(_initialParameterNames[i]);
// p->_initialParameterUnits.push_back(_initialParameterUnits[i]);
// p->_initialParameterValues.push_back(_initialParameterValues[i]);
// p->_initialParameterProperties.push_back(_initialParameterProperties[i]);
//}
//p->_initialValuesInitialized=_initialValuesInitialized;
return(p);
}
void CUserParameters::serialize(CSer& ar)
{
if (ar.isBinary())
{
if (ar.isStoring())
{ // Storing
ar.storeDataName("Par");
ar << int(userParamEntries.size());
for (size_t i=0;i<userParamEntries.size();i++)
{
ar << userParamEntries[i].name;
ar << userParamEntries[i].unit;
ar << userParamEntries[i].value;
ar << userParamEntries[i].properties;
}
ar.flush();
ar.storeDataName(SER_END_OF_OBJECT);
}
else
{ // Loading
int byteQuantity;
std::string theName="";
while (theName.compare(SER_END_OF_OBJECT)!=0)
{
theName=ar.readDataName();
if (theName.compare(SER_END_OF_OBJECT)!=0)
{
bool noHit=true;
if (theName.compare("Par")==0)
{
noHit=false;
int paramCount;
ar >> byteQuantity;
ar >> paramCount;
for (int i=0;i<paramCount;i++)
{
SUserParamEntry e;
ar >> e.name;
ar >> e.unit;
ar >> e.value;
ar >> e.properties;
userParamEntries.push_back(e);
}
}
if (noHit)
ar.loadUnknownData();
}
}
}
}
else
{
if (ar.isStoring())
{
for (size_t i=0;i<userParamEntries.size();i++)
{
ar.xmlPushNewNode("parameter");
ar.xmlAddNode_string("name",userParamEntries[i].name.c_str());
ar.xmlAddNode_string("unit",userParamEntries[i].unit.c_str());
std::string str(base64_encode((unsigned char*)userParamEntries[i].value.c_str(),userParamEntries[i].value.size()));
ar.xmlAddNode_string("value",str.c_str());
ar.xmlAddNode_int("properties",userParamEntries[i].properties);
ar.xmlPopNode();
}
}
else
{
if (ar.xmlPushChildNode("parameter",false))
{
while (true)
{
SUserParamEntry e;
ar.xmlGetNode_string("name",e.name);
ar.xmlGetNode_string("unit",e.unit);
ar.xmlGetNode_string("value",e.value);
e.value=base64_decode(e.value);
ar.xmlGetNode_int("properties",e.properties);
userParamEntries.push_back(e);
if (!ar.xmlPushSiblingNode("parameter",false))
break;
}
ar.xmlPopNode();
}
}
}
}
| 33.579545 | 189 | 0.589961 | [
"object",
"vector"
] |
6592056a35416b4b9694756c62171419865efeb5 | 7,191 | cpp | C++ | labs/2/13-17-project-realization/code/Game.cpp | triffon/oop-2019-20 | db199631d59ddefdcc0c8eb3d689de0095618f92 | [
"MIT"
] | 19 | 2020-02-21T16:46:50.000Z | 2022-01-26T19:59:49.000Z | labs/1/13-17-project-realization/code/Game.cpp | triffon/oop-2019-20 | db199631d59ddefdcc0c8eb3d689de0095618f92 | [
"MIT"
] | 1 | 2020-03-14T08:09:45.000Z | 2020-03-14T08:09:45.000Z | labs/1/13-17-project-realization/code/Game.cpp | triffon/oop-2019-20 | db199631d59ddefdcc0c8eb3d689de0095618f92 | [
"MIT"
] | 11 | 2020-02-23T12:29:58.000Z | 2021-04-11T08:30:12.000Z | #include <cmath>
#include <iostream>
#include <fstream>
#include "Game.hpp"
#include "PhysicsObj.hpp"
#include "SaveFileFactory.hpp"
#include "LevelFactory.hpp"
#include "Player.hpp"
// The default refresh rate
const unsigned int DEFAULT_FPS = 30;
// The default background color
const sf::Color DEFAULT_BGCOLOR = { 127, 127, 127, 255 };
// The game tiles' size
const float Game::BLOCK_SIZE = 32;
// The default save file name
const char* SAVE_FILE = "prev_save.bin";
// The default font file
const char* DEFAULT_FONT = "Montserrat-Regular.ttf";
// The default font outline thickness
const size_t DEFAULT_FONT_OUTLINE = 1;
// Info message
const char* INFO_MSG = "Use WASD + Space to move.\n"
"Press 'P' to save the game.\n"
"Press 'L' to load the last save.\n"
"Press '1' to load level 1.";
// Info message position
const sf::Vector2f INFO_MSG_POS = { 10, 40 };
// Info message size
const size_t INFO_MSG_SIZE = 14;
// View Y offset factor
const float VIEW_Y_OFFSET_FACTOR = 0.15f;
Game::Game()
: m_viewFollow(nullptr)
, m_bgColor(DEFAULT_BGCOLOR)
, m_FPS(DEFAULT_FPS)
{
if (!m_defaultFont.loadFromFile(DEFAULT_FONT))
std::cout << "Couldn't load the default font: " << DEFAULT_FONT << "!" << std::endl;
}
Game::~Game()
{
deleteGameObjects();
}
void Game::initGame(const sf::VideoMode& vm, const char* title)
{
// Create a window with the specified arguments
m_window.create(vm, title);
// Create the view of the game
m_view = sf::View({ vm.width / 2.0f, vm.height / 2.0f }, { (float)vm.width, (float)vm.height });
// Changed to SFML's framerate instead of our implementation
m_window.setFramerateLimit(m_FPS);
}
Game& Game::i()
{
// Singleton object creation
static Game instance;
return instance;
}
void Game::run()
{
// While the window is open
while (m_window.isOpen())
{
// Clear the window
m_window.clear(m_bgColor);
// Poll user events
pollEvents();
// Update all objects in the game
updateAll();
// Add all objects to the window
drawAll();
// Add all GUI elements to the window
drawAllGUI();
// Set view
if (m_viewFollow) {
sf::Vector2f fPos = m_viewFollow->getPosition();
fPos += m_viewFollow->getSize() * 0.5f; // Center on object
fPos.y -= m_window.getSize().y * VIEW_Y_OFFSET_FACTOR;
m_view.setCenter(fPos);
}
m_window.setView(m_view);
// Render the window
m_window.display();
}
}
void Game::pollEvents()
{
// Iterate through all the window events
sf::Event event;
while (m_window.pollEvent(event))
{
// Close the window if the event is
// "Window's close button is pressed"
if (event.type == sf::Event::Closed)
m_window.close();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::P)) {
createSaveFile();
std::cout << "Game saved!" << std::endl;
} else if (sf::Keyboard::isKeyPressed(sf::Keyboard::L)) {
loadSaveFile();
std::cout << "Game loaded!" << std::endl;
} else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Num1)) {
loadLevel(1);
std::cout << "Level 1 loaded!" << std::endl;
}
}
void Game::updateAll()
{
// Iterate through the game objects and
// updated them if they can be udpated
for (size_t i = 0; i < m_objects.size(); ++i)
if (PhysicsObj* po = dynamic_cast<PhysicsObj*>(m_objects[i]))
po->update();
}
void Game::draw(const sf::Drawable& drawable)
{
// Call the window's draw method
m_window.draw(drawable);
}
void Game::drawAll()
{
// Iterate through all game objects and draw them
for (size_t i = 0; i < m_objects.size(); ++i)
m_objects[i]->draw();
}
void Game::drawAllGUI()
{
// Iterate through all game objects and draw them
for (size_t i = 0; i < m_objects.size(); ++i)
m_objects[i]->drawGUI();
drawGUIText(INFO_MSG_POS, INFO_MSG, INFO_MSG_SIZE, sf::Color::White, sf::Color::Black);
}
void Game::drawText(const sf::Vector2f& pos, const std::string& text, size_t textSize, sf::Color textColor, sf::Color outlineColor)
{
sf::Text t;
t.setPosition(pos);
t.setString(text);
t.setFont(m_defaultFont);
t.setFillColor(textColor);
t.setOutlineColor(outlineColor);
t.setOutlineThickness(DEFAULT_FONT_OUTLINE);
t.setCharacterSize(textSize);
m_window.draw(t);
}
void Game::drawGUIText(const sf::Vector2f& pos, const std::string& text, size_t textSize, sf::Color textColor, sf::Color outlineColor)
{
drawText(pos + m_view.getCenter() - m_view.getSize() / 2.0f, text, textSize, textColor, outlineColor);
}
void Game::addObj(GameObj* obj)
{
// Just adds the polymorphic object
// to our GameObject container
m_objects.push_back(obj);
// Saving a pointer to the player object
// as the camera follow object
if (dynamic_cast<Player*>(obj))
m_viewFollow = obj;
}
void Game::setFPS(unsigned int FPS)
{
m_FPS = FPS;
if (m_window.isOpen())
m_window.setFramerateLimit(m_FPS);
}
void Game::removeObj(const GameObj& obj)
{
for (size_t i = 0; i < m_objects.size(); i++) {
// Compare the target's address and the stored pointer (address)
if (&obj == m_objects[i]) {
// If we're about to remove the viewFollow object
// set the quick access
if (m_objects[i] == m_viewFollow)
m_viewFollow = nullptr;
// Delete the polymorphic object
delete m_objects[i];
// Erase it from the vector
m_objects.erase(m_objects.begin() + i);
return;
}
}
}
void Game::createSaveFile() const
{
std::ofstream file(SAVE_FILE, std::ios::binary);
if (!file) {
std::cout << "Couldn't save the game!" << std::endl;
return;
}
for (size_t i = 0; i < m_objects.size(); i++)
m_objects[i]->serialize(file);
file.close();
}
void Game::loadSaveFile()
{
std::ifstream file(SAVE_FILE, std::ios::binary);
if (!file) {
std::cout << "Couldn't load the game!" << std::endl;
return;
}
deleteGameObjects();
SaveFileFactory fact(file);
while (GameObj* obj = fact.createObj())
addObj(obj);
file.close();
}
void Game::loadLevel(size_t level)
{
std::string fileName = "level" + std::to_string(level);
std::ifstream file(fileName);
if (!file) {
std::cout << "Couldn't load " << fileName << "!" << std::endl;
return;
}
deleteGameObjects();
LevelFactory fac(file);
while (GameObj* obj = fac.createObj())
addObj(obj);
file.close();
}
void Game::deleteGameObjects()
{
// Reset the view follow pointer
m_viewFollow = nullptr;
// Iterate through the game's object container
// and delete them, because they are polymorphic
for (size_t i = 0; i < m_objects.size(); ++i)
delete m_objects[i];
// Clear the vector
m_objects.clear();
}
| 23.811258 | 135 | 0.610346 | [
"render",
"object",
"vector"
] |
659436e76f526cd44aa7d223a1868b8ed59b8c97 | 3,464 | cpp | C++ | Game/Source/SceneManager.cpp | MagiX7/Project-II | 8c62b41cf559a9c3d0ea66a072047060ea97b9a3 | [
"MIT"
] | 3 | 2021-03-01T15:51:16.000Z | 2022-03-24T08:33:47.000Z | Game/Source/SceneManager.cpp | MagiX7/Project-II | 8c62b41cf559a9c3d0ea66a072047060ea97b9a3 | [
"MIT"
] | 1 | 2021-02-25T11:10:17.000Z | 2021-02-25T11:10:17.000Z | Game/Source/SceneManager.cpp | MagiX7/Project-II | 8c62b41cf559a9c3d0ea66a072047060ea97b9a3 | [
"MIT"
] | null | null | null | #include "App.h"
#include "Window.h"
#include "Input.h"
#include "Render.h"
#include "Textures.h"
#include "Audio.h"
#include "SceneManager.h"
#include "Scene.h"
#include "SceneLogo.h"
#include "SceneTitle.h"
#include "SceneGameplay.h"
#include "SceneEnding.h"
#include "TransitionsManager.h"
#include "Defs.h"
#include "Log.h"
#define FADEOUT_TRANSITION_SPEED 2.0f
#define FADEIN_TRANSITION_SPEED 2.0f
SceneManager::SceneManager() : Module()
{
name.Create("scenemanager");
}
// Destructor
SceneManager::~SceneManager()
{}
// Called before render is available
bool SceneManager::Awake(pugi::xml_node& config)
{
LOG("Loading Scene Manager");
bool ret = true;
return ret;
}
// Called before the first frame
bool SceneManager::Start()
{
LOG("Scene Manager Start");
bool ret = true;
current = new SceneLogo();
current->Load();
next = nullptr;
transitionStep = TransitionStep::NONE;
return ret;
}
// Called each loop iteration
bool SceneManager::Update(float dt)
{
//LOG("Updating Current Scene");
bool ret = true;
if (app->input->GetKey(SDL_SCANCODE_F10) == KEY_DOWN || app->input->pad->GetButton(SDL_CONTROLLER_BUTTON_RIGHTSTICK)== KEY_DOWN) current->showColliders = !current->showColliders;
if (transitionStep == TransitionStep::NONE)
{
ret = current->Update(dt);
}
else
{
uint w, h;
app->win->GetWindowSize(w, h);
switch (TransitionsManager::GetInstance()->GetStep())
{
case TransitionStep::ENTERING:
/*transitionStep = */TransitionsManager::GetInstance()->EnteringTransition(dt);
break;
case TransitionStep::CHANGING:
if (app->audio->FadeOutCompleted() == false)
{
//TransitionType tmpEnteringType = current->transitionType;
current->UnLoad();
next->Load();
if (current->win == true) app->LoadGameRequest();
RELEASE(current);
current = next;
next = nullptr;
//current->transitionType = tmpEnteringType;
//transitionStep = TransitionStep::EXITING;
TransitionsManager::GetInstance()->SetStep(TransitionStep::EXITING);
}
break;
case TransitionStep::EXITING:
transitionStep = TransitionsManager::GetInstance()->ExitingTransition(dt);
break;
}
}
// Draw current scene
current->Draw();
// Draw the current transition in front of everything
if(transitionStep != TransitionStep::NONE)
{
TransitionsManager::GetInstance()->Draw();
}
if (current->transitionRequired)
{
TransitionsManager::GetInstance()->SetStep(TransitionStep::ENTERING);
transitionStep = TransitionsManager::GetInstance()->GetStep();
switch (current->nextScene)
{
case SceneType::LOGO: next = new SceneLogo(); break;
case SceneType::TITLE: next = new SceneTitle(); break;
case SceneType::GAMEPLAY: next = new SceneGameplay(); break;
case SceneType::ENDING: next = new SceneEnding(current->win); break;
default: break;
}
current->transitionRequired = false;
}
return ret;
}
// Called before quitting
bool SceneManager::CleanUp()
{
LOG("Freeing Scene Manager");
bool ret = true;
return ret;
}
bool SceneManager::LoadState(pugi::xml_node& load)
{
LOG("Loading Scene Manager");
bool ret = true;
if (next != nullptr) next->LoadState(load.child(next->name.GetString()));
else current->LoadState(load.child(current->name.GetString()));
return ret;
}
bool SceneManager::SaveState(pugi::xml_node& save) const
{
LOG("Saving Scene Manager");
bool ret = true;
current->SaveState(save.append_child(current->name.GetString()));
return ret;
} | 22.205128 | 179 | 0.708718 | [
"render"
] |
659625efdede79a67604a153dadec81163b37b5c | 3,977 | cc | C++ | src/0454_4sum_ii/4sum_ii.cc | youngqqcn/LeetCodeNodes | 62bbd30fbdf1640526d7fc4437cde1b05d67fc8f | [
"MIT"
] | 1 | 2021-05-23T02:15:03.000Z | 2021-05-23T02:15:03.000Z | src/0454_4sum_ii/4sum_ii.cc | youngqqcn/LeetCodeNotes | 62bbd30fbdf1640526d7fc4437cde1b05d67fc8f | [
"MIT"
] | null | null | null | src/0454_4sum_ii/4sum_ii.cc | youngqqcn/LeetCodeNotes | 62bbd30fbdf1640526d7fc4437cde1b05d67fc8f | [
"MIT"
] | null | null | null | // author: yqq
// date: 2021-08-05 18:15:23
// descriptions: https://leetcode-cn.com/problems/4sum-ii
#include <bits/stdc++.h>
#include <iostream>
#include <numeric>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <queue>
#include <stack>
#include <unordered_set>
#include <unordered_map>
#include <string.h>
#include <stdlib.h>
using namespace std;
/*
给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。
为了使问题简单化,所有的 A, B, C, D 具有相同的长度 N,且 0 ≤ N ≤ 500 。所有整数的范围在 -2^28 到 2^28 - 1 之间,最终结果不会超过 2^31 - 1 。
例如:
输入:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]
输出:
2
解释:
两个元组如下:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
*/
class Solution {
public:
// 暴力搜索
int fourSumCount_v2(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4)
{
int result = 0;
for(int i = 0; i < nums1.size(); i++)
{
for(int j = 0; j < nums2.size(); j++)
{
for(int k = 0; k < nums3.size(); k++)
{
for(int l = 0; l < nums4.size(); l++)
{
if(0 == nums1[i] + nums2[j] + nums3[k] + nums4[l]) {
result++;
}
}
}
}
}
return result;
}
// a + b + c + d = 0
// (a + b) = -(c + d)
int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4)
{
unordered_map<int, int> records;
for(const int &a : nums1)
{
for(const int &b : nums2)
{
records[a + b] += 1; // 因为可以重复
}
}
int result = 0;
for(const int &c : nums3)
{
for(const int &d : nums4)
{
if( records.find(-(c + d)) != records.end()) {
result += records[-(c + d ) ];
}
}
}
return result;
}
};
void test(vector<int> nums1, vector<int> nums2, vector<int> nums3, vector<int> nums4, int expected)
{
Solution sol;
int result = sol.fourSumCount(nums1, nums2, nums3, nums4);
if( expected != result) {
cout << "FAILED" << result << endl;
return;
}
cout << "PASSED" << endl;
}
int main()
{
test({1, 2}, {-2, -1}, {-1, 2} , {0, 2}, 2);
test({-1,-1},{-1,1}, {-1,1}, {1,-1}, 6);
test(
{-4,-12,3,-7,6,-27,4,-5,-23,-19,-10,-12,-17,-30,-24,-6,-15,-7,-11,-11,0,-32,-2,-14,5,-28,-2,-22,-29,-30,7,-22,4,-14,-17,2,-12,2,-13,-18,-4,-6,-27,-23,-1,-31,-23,-14,5,7,10,9,-5,-7,-14,-13,-16,8,-28,-7,5,-9,-16,-12,-8,-14,-6,-20,-22,-8,-4,-9,-16,-3,9,1,-25,-6,-10,6,-6,-5,-29,-27,2,-12,-20,10,-22,-9,-32,-8,-16,-6,-16,9,-4,-18,-11,-4},
{3,-30,-17,-20,-20,-21,-29,5,-13,-31,-11,4,-2,-27,-2,-15,-26,-3,0,5,-2,-15,7,-18,9,-19,-4,-15,-6,-30,1,-21,10,-28,-11,-11,-25,1,-7,-17,-6,-9,-26,-28,8,-12,0,-7,1,-9,9,10,-12,-15,-15,-6,-27,-17,-24,2,-30,10,-17,0,-12,-24,-13,-25,-10,-29,5,-10,-28,-9,-3,-32,-12,-9,3,-8,-24,-1,-6,8,4,-10,-15,-4,1,-11,-15,-11,-32,1,-32,-1,7,-27,0,2},
{-23,-20,-11,-10,-19,-26,-14,-9,-21,-24,-10,-13,3,-5,-26,8,5,-15,2,-26,-5,10,-16,-14,-5,5,-16,-12,6,-26,-16,2,-8,10,-29,-6,-14,-22,-4,-29,3,-1,9,0,-21,-1,-22,4,6,-32,-26,-18,-24,-19,-9,-5,-20,-20,4,1,9,-7,-26,-12,-9,6,-20,-19,-18,-29,-11,-8,-29,1,3,-1,-29,-19,-3,-24,-23,-6,10,9,6,-24,-25,4,-25,-14,-32,-32,-25,-4,4,-24,-24,7,-5,-1},
{-24,-3,-26,9,-5,-3,-24,6,7,-9,8,-16,4,-14,-30,-9,4,-29,-24,-20,-6,-22,-20,7,5,-14,-9,0,5,-15,1,-12,2,3,7,3,-24,7,-18,-27,-19,5,-13,-14,1,-26,-6,8,-11,-27,-3,-27,-18,-4,8,4,-25,1,-15,-22,-6,4,10,1,-16,-10,-6,-5,-5,-23,-9,2,0,9,-14,-25,-20,-25,7,-31,-6,-18,-22,-19,-32,-16,-32,1,-22,-26,8,5,-28,3,-26,0,4,-7,-32,-27},
407524
);
return 0;
}
| 32.598361 | 342 | 0.450842 | [
"vector"
] |
659dabca80c3e4ed4e69ac007017f3dc3df29281 | 1,762 | hpp | C++ | test/unit/module/real/core/hermite/regular/hermite.hpp | orao/eve | a8bdc6a9cab06d905e8749354cde63776ab76846 | [
"MIT"
] | null | null | null | test/unit/module/real/core/hermite/regular/hermite.hpp | orao/eve | a8bdc6a9cab06d905e8749354cde63776ab76846 | [
"MIT"
] | null | null | null | test/unit/module/real/core/hermite/regular/hermite.hpp | orao/eve | a8bdc6a9cab06d905e8749354cde63776ab76846 | [
"MIT"
] | null | null | null | //==================================================================================================
/**
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include <boost/math/special_functions/hermite.hpp>
#include <eve/function/hermite.hpp>
#include <eve/constant/inf.hpp>
#include <eve/constant/minf.hpp>
#include <eve/constant/nan.hpp>
#include <eve/platform.hpp>
#include <cmath>
TTS_CASE_TPL("Check eve::hermite return type", EVE_TYPE)
{
TTS_EXPR_IS(eve::hermite(0, T(0)), T);
}
TTS_CASE_TPL("Check eve::hermite behavior", EVE_TYPE)
{
auto eve__hermite = [](auto n, auto x) { return eve::hermite(n, x); };
auto boost_hermite = [](auto n, auto x) { return boost::math::hermite(n, x); };
if constexpr( eve::platform::supports_invalids )
{
TTS_ULP_EQUAL(eve__hermite(2u, eve::minf(eve::as<T>())), eve::inf(eve::as<T>()), 0);
TTS_ULP_EQUAL(eve__hermite(2u, eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0);
TTS_ULP_EQUAL(eve__hermite(3u, eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0);
TTS_ULP_EQUAL(eve__hermite(3u, eve::inf(eve::as<T>())), eve::nan(eve::as<T>()), 0);
TTS_ULP_EQUAL(eve__hermite(3u, eve::inf(eve::as<T>())), eve::nan(eve::as<T>()), 0);
}
for(unsigned int i=0; i < 10; ++i)
{
TTS_ULP_EQUAL(eve__hermite(i, T(10)), T(boost_hermite(i, 10)), 1);
TTS_ULP_EQUAL(eve__hermite(i, T(5)), T(boost_hermite(i, 5)), 1);
TTS_ULP_EQUAL(eve__hermite(i, T(2)), T(boost_hermite(i, 2)), 1);
TTS_ULP_EQUAL(eve__hermite(i, T(1)), T(boost_hermite(i, 1)), 1);
TTS_ULP_EQUAL(eve__hermite(i, T(0)), T(boost_hermite(i, 0)), 1);
}
}
| 40.045455 | 100 | 0.576617 | [
"vector"
] |
4f1d5d10b4ee8e2f076e1166bb7cfa5092a2bc0e | 2,524 | cpp | C++ | codeforces/E - New Year Tree/Wrong answer on test 13.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/E - New Year Tree/Wrong answer on test 13.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/E - New Year Tree/Wrong answer on test 13.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Mar/22/2018 00:30
* solution_verdict: Wrong answer on test 13 language: GNU C++14
* run_time: 30 ms memory_used: 33100 KB
* problem: https://codeforces.com/contest/620/problem/E
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=4e5;
int tim,st[N+2],ed[N+2],n,m,u,v,cl[N+2],lazy[N*4+2],ty,tmm[N+2];
long seg[N*4+2];
vector<int>adj[N+2];
void dfs_timing(int node,int par)
{
tim++;
st[node]=tim;
tmm[tim]=node;
for(auto x:adj[node])
{
if(x==par)continue;
dfs_timing(x,node);
}
ed[node]=tim;
}
void build(int node,int lo,int hi)
{
if(lo==hi)
{
seg[node]=(1<<cl[tmm[lo]]);
return ;
}
int md=(lo+hi)/2;
build(node*2,lo,md);
build(node*2+1,md+1,hi);
seg[node]=seg[node*2]|seg[node*2+1];
}
void upd(int node,int lo,int hi,int lt,int rt,int cr)
{
if(lazy[node])
{
seg[node]=(1<<lazy[node]);
if(lo!=hi)
{
lazy[node*2]=lazy[node];
lazy[node*2+1]=lazy[node];
}
lazy[node]=0;
}
if(lo>rt||hi<lt)return ;
if(lo>=lt&&hi<=rt)
{
seg[node]=(1<<cr);
if(lo!=hi)
{
lazy[node*2]=cr;
lazy[node*2+1]=cr;
}
return ;
}
int md=(lo+hi)/2;
upd(node*2,lo,md,lt,rt,cr);
upd(node*2+1,md+1,hi,lt,rt,cr);
seg[node]=seg[node*2]|seg[node*2+1];
}
long query(int node,int lo,int hi,int lt,int rt)
{
if(lazy[node])
{
seg[node]=(1<<lazy[node]);
if(lo!=hi)
{
lazy[node*2]=lazy[node];
lazy[node*2+1]=lazy[node];
}
lazy[node]=0;
}
if(lo>rt||hi<lt)return 0;
if(lo>=lt&&hi<=rt)return seg[node];
int md=(lo+hi)/2;
return query(node*2,lo,md,lt,rt)|query(node*2+1,md+1,hi,lt,rt);
}
int main()
{
//ofstream cout("out.txt");
ios_base::sync_with_stdio(0);
cin.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++)cin>>cl[i];
for(int i=1;i<n;i++)
{
cin>>u>>v;
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs_timing(1,-1);
build(1,1,n);
while(m--)
{
cin>>ty;
if(ty==1)
{
cin>>u>>v;
upd(1,1,n,st[u],ed[u],v);
}
else
{
cin>>u;
cout<<__builtin_popcount(query(1,1,n,st[u],ed[u]))<<endl;
}
}
return 0;
} | 22.336283 | 111 | 0.472662 | [
"vector"
] |
4f1dd2d499b2512ec0ccbac081ad8b389f536997 | 37,657 | cpp | C++ | examples/projection_perspective_specialfullscreen_texture/projection_perspective_specialfullscreen_texture.cpp | math3d/Vulkan | 2c5f8802a417690d8ce2fd70c06c9a13430ecb1a | [
"MIT"
] | 3 | 2020-11-18T14:20:43.000Z | 2021-12-06T16:19:49.000Z | examples/projection_perspective_specialfullscreen_texture/projection_perspective_specialfullscreen_texture.cpp | math3d/Vulkan | 2c5f8802a417690d8ce2fd70c06c9a13430ecb1a | [
"MIT"
] | null | null | null | examples/projection_perspective_specialfullscreen_texture/projection_perspective_specialfullscreen_texture.cpp | math3d/Vulkan | 2c5f8802a417690d8ce2fd70c06c9a13430ecb1a | [
"MIT"
] | 2 | 2020-11-19T17:26:31.000Z | 2021-12-28T09:30:22.000Z | /*
* Copyright (C) 2016-2017 by Sascha Willems - www.saschawillems.de
* Copyright (C) 2019 by Xu Xing - xu.xing@outlook.com
* This code is licensed under the MIT license (MIT)
* (http://opensource.org/licenses/MIT) Code is based on Sascha Willems's Vulkan
* example: https://github.com/SaschaWillems/Vulkan/tree/master/examples/texture
*
* 3D1 Example - Basic texture mapping
*
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <gli/gli.hpp>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <vulkan/vulkan.h>
#include "VulkanBuffer.hpp"
#include "VulkanDevice.hpp"
#include "vulkanexamplebase.h"
#define VERTEX_BUFFER_BIND_ID 0
#define ENABLE_VALIDATION false
// Vertex layout for this example
struct Vertex {
float pos[3];
float uv[2];
float normal[3];
};
#undef far
#undef near
static float fovY = 60.0f;
static float left, right, bottom, top;
static float aspect;
static float width;
static float height;
float near;
// near = 0.01f;
float far;
// far = 256.0f;
#define PI 3.14159265
float DEG2RAD = PI / 180.0;
static void initGolbalData() {
near = 0.01;
far = 256.0;
}
class VulkanExample : public VulkanExampleBase {
public:
// Contains all Vulkan objects that are required to store and use a texture
// Note that this repository contains a texture class (VulkanTexture.hpp) that
// encapsulates texture loading functionality in a class that is used in
// subsequent demos
struct Texture {
VkSampler sampler;
VkImage image;
VkImageLayout imageLayout;
VkDeviceMemory deviceMemory;
VkImageView view;
uint32_t width, height;
uint32_t mipLevels;
} texture;
struct {
VkPipelineVertexInputStateCreateInfo inputState;
std::vector<VkVertexInputBindingDescription> bindingDescriptions;
std::vector<VkVertexInputAttributeDescription> attributeDescriptions;
} vertices;
vks::Buffer vertexBuffer;
vks::Buffer indexBuffer;
uint32_t indexCount;
vks::Buffer uniformBufferVS;
struct {
glm::mat4 projection;
glm::mat4 model;
glm::vec4 viewPos;
float lodBias = 0.0f;
} uboVS;
struct {
VkPipeline solid;
} pipelines;
VkPipelineLayout pipelineLayout;
VkDescriptorSet descriptorSet;
VkDescriptorSetLayout descriptorSetLayout;
VulkanExample() : VulkanExampleBase(ENABLE_VALIDATION) {
zoom = 0.0f;
rotation = {0.0f, 0.0f, 0.0f};
title = "Texture loading";
settings.overlay = true;
initGolbalData();
}
~VulkanExample() {
// Clean up used Vulkan resources
// Note : Inherited destructor cleans up resources stored in base class
destroyTextureImage(texture);
vkDestroyPipeline(device, pipelines.solid, nullptr);
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
vertexBuffer.destroy();
indexBuffer.destroy();
uniformBufferVS.destroy();
}
// Enable physical device features required for this example
virtual void getEnabledFeatures() {
// Enable anisotropic filtering if supported
if (deviceFeatures.samplerAnisotropy) {
enabledFeatures.samplerAnisotropy = VK_TRUE;
};
}
/*
Upload texture image data to the GPU
Vulkan offers two types of image tiling (memory layout):
Linear tiled images:
These are stored as is and can be copied directly to. But due
to the linear nature they're not a good match for GPUs and format and
feature support is very limited. It's not advised to use linear tiled
images for anything else than copying from host to GPU if buffer copies are
not an option. Linear tiling is thus only implemented for learning
purposes, one should always prefer optimal tiled image.
Optimal tiled images:
These are stored in an implementation specific layout matching
the capability of the hardware. They usually support more formats and
features and are much faster. Optimal tiled images are stored on the device
and not accessible by the host. So they can't be written directly to (like
liner tiled images) and always require some sort of data copy, either from
a buffer or a linear tiled image.
In Short: Always use optimal tiled images for rendering.
*/
void loadTexture() {
// We use the Khronos texture format
// (https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/)
// Step 1: load disk file into CPU texture data.
std::string filename = getAssetPath() + "textures/gorilla.ktx";
// Texture data contains 4 channels (RGBA) with unnormalized 8-bit values,
// this is the most commonly supported format
VkFormat format = VK_FORMAT_R8G8B8A8_UNORM;
#if defined(__ANDROID__)
// Textures are stored inside the apk on Android (compressed)
// So they need to be loaded via the asset manager
AAsset* asset = AAssetManager_open(androidApp->activity->assetManager,
filename.c_str(), AASSET_MODE_STREAMING);
assert(asset);
size_t size = AAsset_getLength(asset);
assert(size > 0);
void* textureData = malloc(size);
AAsset_read(asset, textureData, size);
AAsset_close(asset);
gli::texture2d tex2D(gli::load((const char*)textureData, size));
#else
gli::texture2d tex2D(gli::load(filename));
#endif
assert(!tex2D.empty());
texture.width = static_cast<uint32_t>(tex2D[0].extent().x);
texture.height = static_cast<uint32_t>(tex2D[0].extent().y);
texture.mipLevels = static_cast<uint32_t>(tex2D.levels());
// We prefer using staging to copy the texture data to a device local
// optimal image
VkBool32 useStaging = true;
// Only use linear tiling if forced
bool forceLinearTiling = false;
if (forceLinearTiling) {
// Don't use linear if format is not supported for (linear) shader
// sampling Get device properites for the requested texture format
VkFormatProperties formatProperties;
vkGetPhysicalDeviceFormatProperties(physicalDevice, format,
&formatProperties);
useStaging = !(formatProperties.linearTilingFeatures &
VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT);
}
VkMemoryAllocateInfo memAllocInfo = vks::initializers::memoryAllocateInfo();
VkMemoryRequirements memReqs = {};
// Step 2: load CPU data into VkImage.
if (useStaging) {
// Copy data to an optimal tiled image
// This loads the texture data into a host local buffer that is copied to
// the optimal tiled image on the device
// Create a host-visible staging buffer that contains the raw image data
// This buffer will be the data source for copying texture data to the
// optimal tiled image on the device
// Step 2.1 (staging): copy CPU texture data into HOST_VISIBLE staging
// VkBuffer.
VkBuffer stagingBuffer;
VkDeviceMemory stagingMemory;
VkBufferCreateInfo bufferCreateInfo =
vks::initializers::bufferCreateInfo();
bufferCreateInfo.size = tex2D.size();
// This buffer is used as a transfer source for the buffer copy
bufferCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VK_CHECK_RESULT(
vkCreateBuffer(device, &bufferCreateInfo, nullptr, &stagingBuffer));
// Get memory requirements for the staging buffer (alignment, memory type
// bits)
vkGetBufferMemoryRequirements(device, stagingBuffer, &memReqs);
memAllocInfo.allocationSize = memReqs.size;
// Get memory type index for a host visible buffer
memAllocInfo.memoryTypeIndex = vulkanDevice->getMemoryType(
memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
VK_CHECK_RESULT(
vkAllocateMemory(device, &memAllocInfo, nullptr, &stagingMemory));
VK_CHECK_RESULT(
vkBindBufferMemory(device, stagingBuffer, stagingMemory, 0));
// Copy texture data into host local staging buffer
uint8_t* data;
VK_CHECK_RESULT(vkMapMemory(device, stagingMemory, 0, memReqs.size, 0,
(void**)&data));
memcpy(data, tex2D.data(), tex2D.size());
vkUnmapMemory(device, stagingMemory);
// Step 2.2 (staging): setup comand buffer which can be used to copy
// HOST_VISIBLE staging VkBuffer into DEVICE_LOCAL VkImage.
// Setup buffer copy regions for each mip level
std::vector<VkBufferImageCopy> bufferCopyRegions;
uint32_t offset = 0;
for (uint32_t i = 0; i < texture.mipLevels; i++) {
VkBufferImageCopy bufferCopyRegion = {};
bufferCopyRegion.imageSubresource.aspectMask =
VK_IMAGE_ASPECT_COLOR_BIT;
bufferCopyRegion.imageSubresource.mipLevel = i;
bufferCopyRegion.imageSubresource.baseArrayLayer = 0;
bufferCopyRegion.imageSubresource.layerCount = 1;
bufferCopyRegion.imageExtent.width =
static_cast<uint32_t>(tex2D[i].extent().x);
bufferCopyRegion.imageExtent.height =
static_cast<uint32_t>(tex2D[i].extent().y);
bufferCopyRegion.imageExtent.depth = 1;
bufferCopyRegion.bufferOffset = offset;
bufferCopyRegions.push_back(bufferCopyRegion);
offset += static_cast<uint32_t>(tex2D[i].size());
}
// Create optimal tiled target image on the device
VkImageCreateInfo imageCreateInfo = vks::initializers::imageCreateInfo();
imageCreateInfo.imageType = VK_IMAGE_TYPE_2D;
imageCreateInfo.format = format;
imageCreateInfo.mipLevels = texture.mipLevels;
imageCreateInfo.arrayLayers = 1;
imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
// Set initial layout of the image to undefined
imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageCreateInfo.extent = {texture.width, texture.height, 1};
imageCreateInfo.usage =
VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
VK_CHECK_RESULT(
vkCreateImage(device, &imageCreateInfo, nullptr, &texture.image));
vkGetImageMemoryRequirements(device, texture.image, &memReqs);
memAllocInfo.allocationSize = memReqs.size;
memAllocInfo.memoryTypeIndex = vulkanDevice->getMemoryType(
memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
VK_CHECK_RESULT(vkAllocateMemory(device, &memAllocInfo, nullptr,
&texture.deviceMemory));
VK_CHECK_RESULT(
vkBindImageMemory(device, texture.image, texture.deviceMemory, 0));
VkCommandBuffer copyCmd = VulkanExampleBase::createCommandBuffer(
VK_COMMAND_BUFFER_LEVEL_PRIMARY, true);
// Image memory barriers for the texture image
// The sub resource range describes the regions of the image that will be
// transitioned using the memory barriers below
VkImageSubresourceRange subresourceRange = {};
// Image only contains color data
subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
// Start at first mip level
subresourceRange.baseMipLevel = 0;
// We will transition on all mip levels
subresourceRange.levelCount = texture.mipLevels;
// The 2D texture only has one layer
subresourceRange.layerCount = 1;
// Transition the texture image layout to transfer target, so we can
// safely copy our buffer data to it.
VkImageMemoryBarrier imageMemoryBarrier =
vks::initializers::imageMemoryBarrier();
;
imageMemoryBarrier.image = texture.image;
imageMemoryBarrier.subresourceRange = subresourceRange;
imageMemoryBarrier.srcAccessMask = 0;
imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
imageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageMemoryBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
// Insert a memory dependency at the proper pipeline stages that will
// execute the image layout transition Source pipeline stage is host
// write/read exection (VK_PIPELINE_STAGE_HOST_BIT) Destination pipeline
// stage is copy command exection (VK_PIPELINE_STAGE_TRANSFER_BIT)
vkCmdPipelineBarrier(copyCmd, VK_PIPELINE_STAGE_HOST_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0,
nullptr, 1, &imageMemoryBarrier);
// Copy mip levels from staging buffer
vkCmdCopyBufferToImage(copyCmd, stagingBuffer, texture.image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
static_cast<uint32_t>(bufferCopyRegions.size()),
bufferCopyRegions.data());
// Once the data has been uploaded we transfer to the texture image to the
// shader read layout, so it can be sampled from
imageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
imageMemoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
imageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
imageMemoryBarrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
// Insert a memory dependency at the proper pipeline stages that will
// execute the image layout transition Source pipeline stage stage is copy
// command exection (VK_PIPELINE_STAGE_TRANSFER_BIT) Destination pipeline
// stage fragment shader access (VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT)
vkCmdPipelineBarrier(copyCmd, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr,
0, nullptr, 1, &imageMemoryBarrier);
// Store current layout for later reuse
texture.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
VulkanExampleBase::flushCommandBuffer(copyCmd, queue, true);
// Clean up staging resources
vkFreeMemory(device, stagingMemory, nullptr);
vkDestroyBuffer(device, stagingBuffer, nullptr);
} else {
// Copy data to a linear tiled image
// Step 2.1 (non-staging): copy CPU texture data into HOST_VISIBLE
// VkImage.
VkImage mappableImage;
VkDeviceMemory mappableMemory;
// Load mip map level 0 to linear tiling image
VkImageCreateInfo imageCreateInfo = vks::initializers::imageCreateInfo();
imageCreateInfo.imageType = VK_IMAGE_TYPE_2D;
imageCreateInfo.format = format;
imageCreateInfo.mipLevels = 1;
imageCreateInfo.arrayLayers = 1;
imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imageCreateInfo.tiling = VK_IMAGE_TILING_LINEAR;
imageCreateInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;
imageCreateInfo.extent = {texture.width, texture.height, 1};
VK_CHECK_RESULT(
vkCreateImage(device, &imageCreateInfo, nullptr, &mappableImage));
// Get memory requirements for this image like size and alignment
vkGetImageMemoryRequirements(device, mappableImage, &memReqs);
// Set memory allocation size to required memory size
memAllocInfo.allocationSize = memReqs.size;
// Get memory type that can be mapped to host memory
memAllocInfo.memoryTypeIndex = vulkanDevice->getMemoryType(
memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
VK_CHECK_RESULT(
vkAllocateMemory(device, &memAllocInfo, nullptr, &mappableMemory));
VK_CHECK_RESULT(
vkBindImageMemory(device, mappableImage, mappableMemory, 0));
// Map image memory
void* data;
VK_CHECK_RESULT(
vkMapMemory(device, mappableMemory, 0, memReqs.size, 0, &data));
// Copy image data of the first mip level into memory
memcpy(data, tex2D[0].data(), tex2D[0].size());
vkUnmapMemory(device, mappableMemory);
// Linear tiled images don't need to be staged and can be directly used as
// textures
texture.image = mappableImage;
texture.deviceMemory = mappableMemory;
texture.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
// Setup image memory barrier transfer image to shader read layout
VkCommandBuffer copyCmd = VulkanExampleBase::createCommandBuffer(
VK_COMMAND_BUFFER_LEVEL_PRIMARY, true);
// The sub resource range describes the regions of the image we will be
// transition
VkImageSubresourceRange subresourceRange = {};
subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
subresourceRange.baseMipLevel = 0;
subresourceRange.levelCount = 1;
subresourceRange.layerCount = 1;
// Transition the texture image layout to shader read, so it can be
// sampled from
VkImageMemoryBarrier imageMemoryBarrier =
vks::initializers::imageMemoryBarrier();
;
imageMemoryBarrier.image = texture.image;
imageMemoryBarrier.subresourceRange = subresourceRange;
imageMemoryBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
imageMemoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
imageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;
imageMemoryBarrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
// Insert a memory dependency at the proper pipeline stages that will
// execute the image layout transition Source pipeline stage is host
// write/read exection (VK_PIPELINE_STAGE_HOST_BIT) Destination pipeline
// stage fragment shader access (VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT)
vkCmdPipelineBarrier(copyCmd, VK_PIPELINE_STAGE_HOST_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr,
0, nullptr, 1, &imageMemoryBarrier);
VulkanExampleBase::flushCommandBuffer(copyCmd, queue, true);
}
// Step 3: create VkSampler and VkImageView.
// Create a texture sampler
// In Vulkan textures are accessed by samplers
// This separates all the sampling information from the texture data. This
// means you could have multiple sampler objects for the same texture with
// different settings Note: Similar to the samplers available with
// OpenGL 3.3
VkSamplerCreateInfo sampler = vks::initializers::samplerCreateInfo();
sampler.magFilter = VK_FILTER_LINEAR;
sampler.minFilter = VK_FILTER_LINEAR;
sampler.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
sampler.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
sampler.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
sampler.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
sampler.mipLodBias = 0.0f;
sampler.compareOp = VK_COMPARE_OP_NEVER;
sampler.minLod = 0.0f;
// Set max level-of-detail to mip level count of the texture
sampler.maxLod = (useStaging) ? (float)texture.mipLevels : 0.0f;
// Enable anisotropic filtering
// This feature is optional, so we must check if it's supported on the
// device
if (vulkanDevice->features.samplerAnisotropy) {
// Use max. level of anisotropy for this example
sampler.maxAnisotropy =
vulkanDevice->properties.limits.maxSamplerAnisotropy;
sampler.anisotropyEnable = VK_TRUE;
} else {
// The device does not support anisotropic filtering
sampler.maxAnisotropy = 1.0;
sampler.anisotropyEnable = VK_FALSE;
}
sampler.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE;
VK_CHECK_RESULT(
vkCreateSampler(device, &sampler, nullptr, &texture.sampler));
// Create image view
// Textures are not directly accessed by the shaders and
// are abstracted by image views containing additional
// information and sub resource ranges
VkImageViewCreateInfo view = vks::initializers::imageViewCreateInfo();
view.viewType = VK_IMAGE_VIEW_TYPE_2D;
view.format = format;
view.components = {VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G,
VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A};
// The subresource range describes the set of mip levels (and array layers)
// that can be accessed through this image view It's possible to create
// multiple image views for a single image referring to different (and/or
// overlapping) ranges of the image
view.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
view.subresourceRange.baseMipLevel = 0;
view.subresourceRange.baseArrayLayer = 0;
view.subresourceRange.layerCount = 1;
// Linear tiling usually won't support mip maps
// Only set mip map count if optimal tiling is used
view.subresourceRange.levelCount = (useStaging) ? texture.mipLevels : 1;
// The view will be based on the texture's image
view.image = texture.image;
VK_CHECK_RESULT(vkCreateImageView(device, &view, nullptr, &texture.view));
}
// Free all Vulkan resources used by a texture object
void destroyTextureImage(Texture texture) {
vkDestroyImageView(device, texture.view, nullptr);
vkDestroyImage(device, texture.image, nullptr);
vkDestroySampler(device, texture.sampler, nullptr);
vkFreeMemory(device, texture.deviceMemory, nullptr);
}
void buildCommandBuffers() {
VkCommandBufferBeginInfo cmdBufInfo =
vks::initializers::commandBufferBeginInfo();
VkClearValue clearValues[2];
clearValues[0].color = defaultClearColor;
clearValues[1].depthStencil = {1.0f, 0};
VkRenderPassBeginInfo renderPassBeginInfo =
vks::initializers::renderPassBeginInfo();
renderPassBeginInfo.renderPass = renderPass;
renderPassBeginInfo.renderArea.offset.x = 0;
renderPassBeginInfo.renderArea.offset.y = 0;
renderPassBeginInfo.renderArea.extent.width = viewportWidth;
renderPassBeginInfo.renderArea.extent.height = viewportHeight;
renderPassBeginInfo.clearValueCount = 2;
renderPassBeginInfo.pClearValues = clearValues;
for (int32_t i = 0; i < drawCmdBuffers.size(); ++i) {
// Set target frame buffer
renderPassBeginInfo.framebuffer = frameBuffers[i];
VK_CHECK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[i], &cmdBufInfo));
vkCmdBeginRenderPass(drawCmdBuffers[i], &renderPassBeginInfo,
VK_SUBPASS_CONTENTS_INLINE);
VkViewport viewport = vks::initializers::viewport(
(float)viewportWidth, (float)viewportHeight, 0.0f, 1.0f);
vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport);
VkRect2D scissor =
vks::initializers::rect2D(viewportWidth, viewportHeight, 0, 0);
vkCmdSetScissor(drawCmdBuffers[i], 0, 1, &scissor);
vkCmdBindDescriptorSets(drawCmdBuffers[i],
VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout,
0, 1, &descriptorSet, 0, NULL);
vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS,
pipelines.solid);
VkDeviceSize offsets[1] = {0};
vkCmdBindVertexBuffers(drawCmdBuffers[i], VERTEX_BUFFER_BIND_ID, 1,
&vertexBuffer.buffer, offsets);
vkCmdBindIndexBuffer(drawCmdBuffers[i], indexBuffer.buffer, 0,
VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(drawCmdBuffers[i], indexCount, 1, 0, 0, 0);
// drawUI(drawCmdBuffers[i]);
vkCmdEndRenderPass(drawCmdBuffers[i]);
VK_CHECK_RESULT(vkEndCommandBuffer(drawCmdBuffers[i]));
}
}
void draw() {
VulkanExampleBase::prepareFrame();
// Command buffer to be sumitted to the queue
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
// Submit to queue
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
VulkanExampleBase::submitFrame();
}
void generateQuad() {
aspect = (float)viewportWidth / viewportHeight;
float tangent = tan(fovY / 2 * DEG2RAD);
height = near * tangent; // half height of near plane
width = height * aspect; // half width of near plane
left = -width;
right = width;
bottom = -height;
top = height;
float scale = 1.00;
float zEye = -5.0;
float leftAtAnyZ = left * zEye / (-1 * near) * scale;
float rightAtAnyZ = right * zEye / (-1 * near) * scale;
float bottomAtAnyZ = bottom * zEye / (-1 * near) * scale;
float topAtAnyZ = top * zEye / (-1 * near) * scale;
#if 0 // Works for counter clock wise.
// Setup vertices for a single uv-mapped quad made from two triangles
std::vector<Vertex> vertices = {
{{leftAtAnyZ, bottomAtAnyZ * 3, zEye},
{0.0f, 2.0f},
{ 0.0f,
0.0f,
1.0f }},
{{rightAtAnyZ * 3, topAtAnyZ, zEye},
{2.0f, 0.0f},
{ 0.0f,
0.0f,
1.0f }},
{{leftAtAnyZ, topAtAnyZ, zEye},
{0.0f, 0.0f},
{ 0.0f,
0.0f,
1.0f }},
};
// Setup indices
std::vector<uint32_t> indices = {0, 1, 2}; //, 2, 3, 0};
#endif
#if 1 // Works for clock wise.
// Setup vertices for a single uv-mapped quad made from two triangles
std::vector<Vertex> vertices = {
{{leftAtAnyZ, topAtAnyZ, zEye},
{0.0f, 0.0f},
{ 0.0f,
0.0f,
1.0f }},
{{rightAtAnyZ * 3, topAtAnyZ, zEye},
{2.0f, 0.0f},
{ 0.0f,
0.0f,
1.0f }},
{{leftAtAnyZ, bottomAtAnyZ * 3, zEye},
{0.0f, 2.0f},
{ 0.0f,
0.0f,
1.0f }},
};
// Setup indices
std::vector<uint32_t> indices = {0, 1, 2}; //, 2, 3, 0};
#endif
indexCount = static_cast<uint32_t>(indices.size());
// Create buffers
// For the sake of simplicity we won't stage the vertex data to the gpu
// memory Vertex buffer
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&vertexBuffer, vertices.size() * sizeof(Vertex), vertices.data()));
// Index buffer
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&indexBuffer, indices.size() * sizeof(uint32_t), indices.data()));
}
void setupVertexDescriptions() {
// Binding description
vertices.bindingDescriptions.resize(1);
vertices.bindingDescriptions[0] =
vks::initializers::vertexInputBindingDescription(
VERTEX_BUFFER_BIND_ID, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX);
// Attribute descriptions
// Describes memory layout and shader positions
vertices.attributeDescriptions.resize(3);
// Location 0 : Position
vertices.attributeDescriptions[0] =
vks::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID, 0, VK_FORMAT_R32G32B32_SFLOAT,
offsetof(Vertex, pos));
// Location 1 : Texture coordinates
vertices.attributeDescriptions[1] =
vks::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID, 1, VK_FORMAT_R32G32_SFLOAT,
offsetof(Vertex, uv));
// Location 1 : Vertex normal
vertices.attributeDescriptions[2] =
vks::initializers::vertexInputAttributeDescription(
VERTEX_BUFFER_BIND_ID, 2, VK_FORMAT_R32G32B32_SFLOAT,
offsetof(Vertex, normal));
vertices.inputState =
vks::initializers::pipelineVertexInputStateCreateInfo();
vertices.inputState.vertexBindingDescriptionCount =
static_cast<uint32_t>(vertices.bindingDescriptions.size());
vertices.inputState.pVertexBindingDescriptions =
vertices.bindingDescriptions.data();
vertices.inputState.vertexAttributeDescriptionCount =
static_cast<uint32_t>(vertices.attributeDescriptions.size());
vertices.inputState.pVertexAttributeDescriptions =
vertices.attributeDescriptions.data();
}
void setupDescriptorPool() {
// Example uses one ubo and one image sampler
std::vector<VkDescriptorPoolSize> poolSizes = {
vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
1),
vks::initializers::descriptorPoolSize(
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1)};
VkDescriptorPoolCreateInfo descriptorPoolInfo =
vks::initializers::descriptorPoolCreateInfo(
static_cast<uint32_t>(poolSizes.size()), poolSizes.data(), 2);
VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr,
&descriptorPool));
}
void setupDescriptorSetLayout() {
std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = {
// Binding 0 : Vertex shader uniform buffer
vks::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0),
// Binding 1 : Fragment shader image sampler
vks::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_SHADER_STAGE_FRAGMENT_BIT, 1)};
VkDescriptorSetLayoutCreateInfo descriptorLayout =
vks::initializers::descriptorSetLayoutCreateInfo(
setLayoutBindings.data(),
static_cast<uint32_t>(setLayoutBindings.size()));
VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout,
nullptr, &descriptorSetLayout));
VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo =
vks::initializers::pipelineLayoutCreateInfo(&descriptorSetLayout, 1);
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo,
nullptr, &pipelineLayout));
}
void setupDescriptorSet() {
VkDescriptorSetAllocateInfo allocInfo =
vks::initializers::descriptorSetAllocateInfo(descriptorPool,
&descriptorSetLayout, 1);
VK_CHECK_RESULT(
vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet));
// Setup a descriptor image info for the current texture to be used as a
// combined image sampler
VkDescriptorImageInfo textureDescriptor;
// The image's view (images are never directly accessed by the shader, but
// rather through views defining subresources)
textureDescriptor.imageView = texture.view;
// The sampler (Telling the pipeline how to sample the texture, including
// repeat, border, etc.).
textureDescriptor.sampler = texture.sampler;
// The current layout of the image (Note: Should always fit the actual use,
// e.g. shader read).
textureDescriptor.imageLayout = texture.imageLayout;
std::vector<VkWriteDescriptorSet> writeDescriptorSets = {
// Binding 0 : Vertex shader uniform buffer
vks::initializers::writeDescriptorSet(descriptorSet,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
0, &uniformBufferVS.descriptor),
// Binding 1 : Fragment shader texture sampler
// Fragment shader: layout (binding = 1) uniform sampler2D
// samplerColor;
vks::initializers::writeDescriptorSet(
descriptorSet,
// The descriptor set will use a combined image sampler (sampler and
// image could be split)
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
// Shader binding point 1
1,
// Pointer to the descriptor image for our texture.
&textureDescriptor)};
vkUpdateDescriptorSets(device,
static_cast<uint32_t>(writeDescriptorSets.size()),
writeDescriptorSets.data(), 0, NULL);
}
void preparePipelines() {
VkPipelineInputAssemblyStateCreateInfo inputAssemblyState =
vks::initializers::pipelineInputAssemblyStateCreateInfo(
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE);
VkPipelineRasterizationStateCreateInfo rasterizationState =
vks::initializers::pipelineRasterizationStateCreateInfo(
VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT,
VK_FRONT_FACE_CLOCKWISE, 0);
VkPipelineColorBlendAttachmentState blendAttachmentState =
vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE);
VkPipelineColorBlendStateCreateInfo colorBlendState =
vks::initializers::pipelineColorBlendStateCreateInfo(
1, &blendAttachmentState);
VkPipelineDepthStencilStateCreateInfo depthStencilState =
vks::initializers::pipelineDepthStencilStateCreateInfo(
VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL);
VkPipelineViewportStateCreateInfo viewportState =
vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0);
VkPipelineMultisampleStateCreateInfo multisampleState =
vks::initializers::pipelineMultisampleStateCreateInfo(
VK_SAMPLE_COUNT_1_BIT, 0);
std::vector<VkDynamicState> dynamicStateEnables = {
VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
VkPipelineDynamicStateCreateInfo dynamicState =
vks::initializers::pipelineDynamicStateCreateInfo(
dynamicStateEnables.data(),
static_cast<uint32_t>(dynamicStateEnables.size()), 0);
// Load shaders
std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages;
shaderStages[0] = loadShader(
getAssetPath() +
"shaders/projection_perspective_specialfullscreen_texture/"
"texture.vert.spv",
VK_SHADER_STAGE_VERTEX_BIT);
shaderStages[1] = loadShader(
getAssetPath() +
"shaders/projection_perspective_specialfullscreen_texture/"
"texture.frag.spv",
VK_SHADER_STAGE_FRAGMENT_BIT);
VkGraphicsPipelineCreateInfo pipelineCreateInfo =
vks::initializers::pipelineCreateInfo(pipelineLayout, renderPass, 0);
pipelineCreateInfo.pVertexInputState = &vertices.inputState;
pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState;
pipelineCreateInfo.pRasterizationState = &rasterizationState;
pipelineCreateInfo.pColorBlendState = &colorBlendState;
pipelineCreateInfo.pMultisampleState = &multisampleState;
pipelineCreateInfo.pViewportState = &viewportState;
pipelineCreateInfo.pDepthStencilState = &depthStencilState;
pipelineCreateInfo.pDynamicState = &dynamicState;
pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size());
pipelineCreateInfo.pStages = shaderStages.data();
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1,
&pipelineCreateInfo, nullptr,
&pipelines.solid));
}
// Prepare and initialize uniform buffer containing shader uniforms
void prepareUniformBuffers() {
// Vertex shader uniform buffer block
VK_CHECK_RESULT(
vulkanDevice->createBuffer(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&uniformBufferVS, sizeof(uboVS), &uboVS));
updateUniformBuffers();
}
void updateUniformBuffers() {
// Vertex shader
uboVS.projection = glm::perspective(
glm::radians(60.0f), (float)viewportWidth / (float)viewportHeight, near,
far);
uboVS.projection[1][1] *= -1.0f;
// glm::mat4 viewMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f,
// 0.0f, zoom));
glm::mat4 viewMatrix =
glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f));
uboVS.model = glm::rotate(uboVS.model, glm::radians(rotation.x),
glm::vec3(1.0f, 0.0f, 0.0f));
uboVS.model = glm::rotate(uboVS.model, glm::radians(rotation.y),
glm::vec3(0.0f, 1.0f, 0.0f));
uboVS.model = glm::rotate(uboVS.model, glm::radians(rotation.z),
glm::vec3(0.0f, 0.0f, 1.0f));
// uboVS.viewPos = glm::mat4(1.0f);
uboVS.viewPos = glm::vec4(0.0f, 0.0f, 0.0f, 0.0f);
VK_CHECK_RESULT(uniformBufferVS.map());
memcpy(uniformBufferVS.mapped, &uboVS, sizeof(uboVS));
uniformBufferVS.unmap();
}
void prepare() {
VulkanExampleBase::prepare();
loadTexture();
generateQuad();
setupVertexDescriptions();
prepareUniformBuffers();
setupDescriptorSetLayout();
preparePipelines();
setupDescriptorPool();
setupDescriptorSet();
buildCommandBuffers();
prepared = true;
}
virtual void render() {
if (!prepared)
return;
draw();
}
virtual void viewChanged() { updateUniformBuffers(); }
virtual void OnUpdateUIOverlay(vks::UIOverlay* overlay) {
if (overlay->header("Settings")) {
if (overlay->sliderFloat("LOD bias", &uboVS.lodBias, 0.0f,
(float)texture.mipLevels)) {
updateUniformBuffers();
}
}
}
};
VULKAN_EXAMPLE_MAIN()
| 39.76452 | 80 | 0.689009 | [
"render",
"object",
"vector",
"model",
"solid"
] |
4f21990d861259583b76cb9eee0382980cd8aa3d | 28,667 | hpp | C++ | Blik2D/addon/opencv-3.1.0_for_blik/modules/core/include/opencv2/core/cuda.hpp | BonexGu/Blik2D | 8e0592787e5c8e8a28682d0e1826b8223eae5983 | [
"MIT"
] | 13 | 2017-02-22T02:20:06.000Z | 2018-06-06T04:18:03.000Z | Blik2D/addon/opencv-3.1.0_for_blik/modules/core/include/opencv2/core/cuda.hpp | BonexGu/Blik2D | 8e0592787e5c8e8a28682d0e1826b8223eae5983 | [
"MIT"
] | null | null | null | Blik2D/addon/opencv-3.1.0_for_blik/modules/core/include/opencv2/core/cuda.hpp | BonexGu/Blik2D | 8e0592787e5c8e8a28682d0e1826b8223eae5983 | [
"MIT"
] | null | null | null | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
//M*/
#ifndef __OPENCV_CORE_CUDA_HPP__
#define __OPENCV_CORE_CUDA_HPP__
#ifndef __cplusplus
# error cuda.hpp header must be compiled as C++
#endif
#include BLIK_OPENCV_U_opencv2__core_hpp //original-code:"opencv2/core.hpp"
#include BLIK_OPENCV_U_opencv2__core__cuda_types_hpp //original-code:"opencv2/core/cuda_types.hpp"
/**
@defgroup cuda CUDA-accelerated Computer Vision
@{
@defgroup cudacore Core part
@{
@defgroup cudacore_init Initalization and Information
@defgroup cudacore_struct Data Structures
@}
@}
*/
namespace cv { namespace cuda {
//! @addtogroup cudacore_struct
//! @{
//===================================================================================
// GpuMat
//===================================================================================
/** @brief Base storage class for GPU memory with reference counting.
Its interface matches the Mat interface with the following limitations:
- no arbitrary dimensions support (only 2D)
- no functions that return references to their data (because references on GPU are not valid for
CPU)
- no expression templates technique support
Beware that the latter limitation may lead to overloaded matrix operators that cause memory
allocations. The GpuMat class is convertible to cuda::PtrStepSz and cuda::PtrStep so it can be
passed directly to the kernel.
@note In contrast with Mat, in most cases GpuMat::isContinuous() == false . This means that rows are
aligned to a size depending on the hardware. Single-row GpuMat is always a continuous matrix.
@note You are not recommended to leave static or global GpuMat variables allocated, that is, to rely
on its destructor. The destruction order of such variables and CUDA context is undefined. GPU memory
release function returns error if the CUDA context has been destroyed before.
@sa Mat
*/
class CV_EXPORTS GpuMat
{
public:
class CV_EXPORTS Allocator
{
public:
virtual ~Allocator() {}
// allocator must fill data, step and refcount fields
virtual bool allocate(GpuMat* mat, int rows, int cols, size_t elemSize) = 0;
virtual void free(GpuMat* mat) = 0;
};
//! default allocator
static Allocator* defaultAllocator();
static void setDefaultAllocator(Allocator* allocator);
//! default constructor
explicit GpuMat(Allocator* allocator = defaultAllocator());
//! constructs GpuMat of the specified size and type
GpuMat(int rows, int cols, int type, Allocator* allocator = defaultAllocator());
GpuMat(Size size, int type, Allocator* allocator = defaultAllocator());
//! constucts GpuMat and fills it with the specified value _s
GpuMat(int rows, int cols, int type, Scalar s, Allocator* allocator = defaultAllocator());
GpuMat(Size size, int type, Scalar s, Allocator* allocator = defaultAllocator());
//! copy constructor
GpuMat(const GpuMat& m);
//! constructor for GpuMat headers pointing to user-allocated data
GpuMat(int rows, int cols, int type, void* data, size_t step = Mat::AUTO_STEP);
GpuMat(Size size, int type, void* data, size_t step = Mat::AUTO_STEP);
//! creates a GpuMat header for a part of the bigger matrix
GpuMat(const GpuMat& m, Range rowRange, Range colRange);
GpuMat(const GpuMat& m, Rect roi);
//! builds GpuMat from host memory (Blocking call)
explicit GpuMat(InputArray arr, Allocator* allocator = defaultAllocator());
//! destructor - calls release()
~GpuMat();
//! assignment operators
GpuMat& operator =(const GpuMat& m);
//! allocates new GpuMat data unless the GpuMat already has specified size and type
void create(int rows, int cols, int type);
void create(Size size, int type);
//! decreases reference counter, deallocate the data when reference counter reaches 0
void release();
//! swaps with other smart pointer
void swap(GpuMat& mat);
//! pefroms upload data to GpuMat (Blocking call)
void upload(InputArray arr);
//! pefroms upload data to GpuMat (Non-Blocking call)
void upload(InputArray arr, Stream& stream);
//! pefroms download data from device to host memory (Blocking call)
void download(OutputArray dst) const;
//! pefroms download data from device to host memory (Non-Blocking call)
void download(OutputArray dst, Stream& stream) const;
//! returns deep copy of the GpuMat, i.e. the data is copied
GpuMat clone() const;
//! copies the GpuMat content to device memory (Blocking call)
void copyTo(OutputArray dst) const;
//! copies the GpuMat content to device memory (Non-Blocking call)
void copyTo(OutputArray dst, Stream& stream) const;
//! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Blocking call)
void copyTo(OutputArray dst, InputArray mask) const;
//! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Non-Blocking call)
void copyTo(OutputArray dst, InputArray mask, Stream& stream) const;
//! sets some of the GpuMat elements to s (Blocking call)
GpuMat& setTo(Scalar s);
//! sets some of the GpuMat elements to s (Non-Blocking call)
GpuMat& setTo(Scalar s, Stream& stream);
//! sets some of the GpuMat elements to s, according to the mask (Blocking call)
GpuMat& setTo(Scalar s, InputArray mask);
//! sets some of the GpuMat elements to s, according to the mask (Non-Blocking call)
GpuMat& setTo(Scalar s, InputArray mask, Stream& stream);
//! converts GpuMat to another datatype (Blocking call)
void convertTo(OutputArray dst, int rtype) const;
//! converts GpuMat to another datatype (Non-Blocking call)
void convertTo(OutputArray dst, int rtype, Stream& stream) const;
//! converts GpuMat to another datatype with scaling (Blocking call)
void convertTo(OutputArray dst, int rtype, double alpha, double beta = 0.0) const;
//! converts GpuMat to another datatype with scaling (Non-Blocking call)
void convertTo(OutputArray dst, int rtype, double alpha, Stream& stream) const;
//! converts GpuMat to another datatype with scaling (Non-Blocking call)
void convertTo(OutputArray dst, int rtype, double alpha, double beta, Stream& stream) const;
void assignTo(GpuMat& m, int type=-1) const;
//! returns pointer to y-th row
uchar* ptr(int y = 0);
const uchar* ptr(int y = 0) const;
//! template version of the above method
template<typename _Tp> _Tp* ptr(int y = 0);
template<typename _Tp> const _Tp* ptr(int y = 0) const;
template <typename _Tp> operator PtrStepSz<_Tp>() const;
template <typename _Tp> operator PtrStep<_Tp>() const;
//! returns a new GpuMat header for the specified row
GpuMat row(int y) const;
//! returns a new GpuMat header for the specified column
GpuMat col(int x) const;
//! ... for the specified row span
GpuMat rowRange(int startrow, int endrow) const;
GpuMat rowRange(Range r) const;
//! ... for the specified column span
GpuMat colRange(int startcol, int endcol) const;
GpuMat colRange(Range r) const;
//! extracts a rectangular sub-GpuMat (this is a generalized form of row, rowRange etc.)
GpuMat operator ()(Range rowRange, Range colRange) const;
GpuMat operator ()(Rect roi) const;
//! creates alternative GpuMat header for the same data, with different
//! number of channels and/or different number of rows
GpuMat reshape(int cn, int rows = 0) const;
//! locates GpuMat header within a parent GpuMat
void locateROI(Size& wholeSize, Point& ofs) const;
//! moves/resizes the current GpuMat ROI inside the parent GpuMat
GpuMat& adjustROI(int dtop, int dbottom, int dleft, int dright);
//! returns true iff the GpuMat data is continuous
//! (i.e. when there are no gaps between successive rows)
bool isContinuous() const;
//! returns element size in bytes
size_t elemSize() const;
//! returns the size of element channel in bytes
size_t elemSize1() const;
//! returns element type
int type() const;
//! returns element type
int depth() const;
//! returns number of channels
int channels() const;
//! returns step/elemSize1()
size_t step1() const;
//! returns GpuMat size : width == number of columns, height == number of rows
Size size() const;
//! returns true if GpuMat data is NULL
bool empty() const;
/*! includes several bit-fields:
- the magic signature
- continuity flag
- depth
- number of channels
*/
int flags;
//! the number of rows and columns
int rows, cols;
//! a distance between successive rows in bytes; includes the gap if any
size_t step;
//! pointer to the data
uchar* data;
//! pointer to the reference counter;
//! when GpuMat points to user-allocated data, the pointer is NULL
int* refcount;
//! helper fields used in locateROI and adjustROI
uchar* datastart;
const uchar* dataend;
//! allocator
Allocator* allocator;
};
/** @brief Creates a continuous matrix.
@param rows Row count.
@param cols Column count.
@param type Type of the matrix.
@param arr Destination matrix. This parameter changes only if it has a proper type and area (
\f$\texttt{rows} \times \texttt{cols}\f$ ).
Matrix is called continuous if its elements are stored continuously, that is, without gaps at the
end of each row.
*/
CV_EXPORTS void createContinuous(int rows, int cols, int type, OutputArray arr);
/** @brief Ensures that the size of a matrix is big enough and the matrix has a proper type.
@param rows Minimum desired number of rows.
@param cols Minimum desired number of columns.
@param type Desired matrix type.
@param arr Destination matrix.
The function does not reallocate memory if the matrix has proper attributes already.
*/
CV_EXPORTS void ensureSizeIsEnough(int rows, int cols, int type, OutputArray arr);
//! BufferPool management (must be called before Stream creation)
CV_EXPORTS void setBufferPoolUsage(bool on);
CV_EXPORTS void setBufferPoolConfig(int deviceId, size_t stackSize, int stackCount);
//===================================================================================
// HostMem
//===================================================================================
/** @brief Class with reference counting wrapping special memory type allocation functions from CUDA.
Its interface is also Mat-like but with additional memory type parameters.
- **PAGE_LOCKED** sets a page locked memory type used commonly for fast and asynchronous
uploading/downloading data from/to GPU.
- **SHARED** specifies a zero copy memory allocation that enables mapping the host memory to GPU
address space, if supported.
- **WRITE_COMBINED** sets the write combined buffer that is not cached by CPU. Such buffers are
used to supply GPU with data when GPU only reads it. The advantage is a better CPU cache
utilization.
@note Allocation size of such memory types is usually limited. For more details, see *CUDA 2.2
Pinned Memory APIs* document or *CUDA C Programming Guide*.
*/
class CV_EXPORTS HostMem
{
public:
enum AllocType { PAGE_LOCKED = 1, SHARED = 2, WRITE_COMBINED = 4 };
static MatAllocator* getAllocator(AllocType alloc_type = PAGE_LOCKED);
explicit HostMem(AllocType alloc_type = PAGE_LOCKED);
HostMem(const HostMem& m);
HostMem(int rows, int cols, int type, AllocType alloc_type = PAGE_LOCKED);
HostMem(Size size, int type, AllocType alloc_type = PAGE_LOCKED);
//! creates from host memory with coping data
explicit HostMem(InputArray arr, AllocType alloc_type = PAGE_LOCKED);
~HostMem();
HostMem& operator =(const HostMem& m);
//! swaps with other smart pointer
void swap(HostMem& b);
//! returns deep copy of the matrix, i.e. the data is copied
HostMem clone() const;
//! allocates new matrix data unless the matrix already has specified size and type.
void create(int rows, int cols, int type);
void create(Size size, int type);
//! creates alternative HostMem header for the same data, with different
//! number of channels and/or different number of rows
HostMem reshape(int cn, int rows = 0) const;
//! decrements reference counter and released memory if needed.
void release();
//! returns matrix header with disabled reference counting for HostMem data.
Mat createMatHeader() const;
/** @brief Maps CPU memory to GPU address space and creates the cuda::GpuMat header without reference counting
for it.
This can be done only if memory was allocated with the SHARED flag and if it is supported by the
hardware. Laptops often share video and CPU memory, so address spaces can be mapped, which
eliminates an extra copy.
*/
GpuMat createGpuMatHeader() const;
// Please see cv::Mat for descriptions
bool isContinuous() const;
size_t elemSize() const;
size_t elemSize1() const;
int type() const;
int depth() const;
int channels() const;
size_t step1() const;
Size size() const;
bool empty() const;
// Please see cv::Mat for descriptions
int flags;
int rows, cols;
size_t step;
uchar* data;
int* refcount;
uchar* datastart;
const uchar* dataend;
AllocType alloc_type;
};
/** @brief Page-locks the memory of matrix and maps it for the device(s).
@param m Input matrix.
*/
CV_EXPORTS void registerPageLocked(Mat& m);
/** @brief Unmaps the memory of matrix and makes it pageable again.
@param m Input matrix.
*/
CV_EXPORTS void unregisterPageLocked(Mat& m);
//===================================================================================
// Stream
//===================================================================================
/** @brief This class encapsulates a queue of asynchronous calls.
@note Currently, you may face problems if an operation is enqueued twice with different data. Some
functions use the constant GPU memory, and next call may update the memory before the previous one
has been finished. But calling different operations asynchronously is safe because each operation
has its own constant buffer. Memory copy/upload/download/set operations to the buffers you hold are
also safe. :
*/
class CV_EXPORTS Stream
{
typedef void (Stream::*bool_type)() const;
void this_type_does_not_support_comparisons() const {}
public:
typedef void (*StreamCallback)(int status, void* userData);
//! creates a new asynchronous stream
Stream();
/** @brief Returns true if the current stream queue is finished. Otherwise, it returns false.
*/
bool queryIfComplete() const;
/** @brief Blocks the current CPU thread until all operations in the stream are complete.
*/
void waitForCompletion();
/** @brief Makes a compute stream wait on an event.
*/
void waitEvent(const Event& event);
/** @brief Adds a callback to be called on the host after all currently enqueued items in the stream have
completed.
@note Callbacks must not make any CUDA API calls. Callbacks must not perform any synchronization
that may depend on outstanding device work or other callbacks that are not mandated to run earlier.
Callbacks without a mandated order (in independent streams) execute in undefined order and may be
serialized.
*/
void enqueueHostCallback(StreamCallback callback, void* userData);
//! return Stream object for default CUDA stream
static Stream& Null();
//! returns true if stream object is not default (!= 0)
operator bool_type() const;
class Impl;
private:
Ptr<Impl> impl_;
Stream(const Ptr<Impl>& impl);
friend struct StreamAccessor;
friend class BufferPool;
friend class DefaultDeviceInitializer;
};
class CV_EXPORTS Event
{
public:
enum CreateFlags
{
DEFAULT = 0x00, /**< Default event flag */
BLOCKING_SYNC = 0x01, /**< Event uses blocking synchronization */
DISABLE_TIMING = 0x02, /**< Event will not record timing data */
INTERPROCESS = 0x04 /**< Event is suitable for interprocess use. DisableTiming must be set */
};
explicit Event(CreateFlags flags = DEFAULT);
//! records an event
void record(Stream& stream = Stream::Null());
//! queries an event's status
bool queryIfComplete() const;
//! waits for an event to complete
void waitForCompletion();
//! computes the elapsed time between events
static float elapsedTime(const Event& start, const Event& end);
class Impl;
private:
Ptr<Impl> impl_;
Event(const Ptr<Impl>& impl);
friend struct EventAccessor;
};
//! @} cudacore_struct
//===================================================================================
// Initialization & Info
//===================================================================================
//! @addtogroup cudacore_init
//! @{
/** @brief Returns the number of installed CUDA-enabled devices.
Use this function before any other CUDA functions calls. If OpenCV is compiled without CUDA support,
this function returns 0.
*/
CV_EXPORTS int getCudaEnabledDeviceCount();
/** @brief Sets a device and initializes it for the current thread.
@param device System index of a CUDA device starting with 0.
If the call of this function is omitted, a default device is initialized at the fist CUDA usage.
*/
CV_EXPORTS void setDevice(int device);
/** @brief Returns the current device index set by cuda::setDevice or initialized by default.
*/
CV_EXPORTS int getDevice();
/** @brief Explicitly destroys and cleans up all resources associated with the current device in the current
process.
Any subsequent API call to this device will reinitialize the device.
*/
CV_EXPORTS void resetDevice();
/** @brief Enumeration providing CUDA computing features.
*/
enum FeatureSet
{
FEATURE_SET_COMPUTE_10 = 10,
FEATURE_SET_COMPUTE_11 = 11,
FEATURE_SET_COMPUTE_12 = 12,
FEATURE_SET_COMPUTE_13 = 13,
FEATURE_SET_COMPUTE_20 = 20,
FEATURE_SET_COMPUTE_21 = 21,
FEATURE_SET_COMPUTE_30 = 30,
FEATURE_SET_COMPUTE_32 = 32,
FEATURE_SET_COMPUTE_35 = 35,
FEATURE_SET_COMPUTE_50 = 50,
GLOBAL_ATOMICS = FEATURE_SET_COMPUTE_11,
SHARED_ATOMICS = FEATURE_SET_COMPUTE_12,
NATIVE_DOUBLE = FEATURE_SET_COMPUTE_13,
WARP_SHUFFLE_FUNCTIONS = FEATURE_SET_COMPUTE_30,
DYNAMIC_PARALLELISM = FEATURE_SET_COMPUTE_35
};
//! checks whether current device supports the given feature
CV_EXPORTS bool deviceSupports(FeatureSet feature_set);
/** @brief Class providing a set of static methods to check what NVIDIA\* card architecture the CUDA module was
built for.
According to the CUDA C Programming Guide Version 3.2: "PTX code produced for some specific compute
capability can always be compiled to binary code of greater or equal compute capability".
*/
class CV_EXPORTS TargetArchs
{
public:
/** @brief The following method checks whether the module was built with the support of the given feature:
@param feature_set Features to be checked. See :ocvcuda::FeatureSet.
*/
static bool builtWith(FeatureSet feature_set);
/** @brief There is a set of methods to check whether the module contains intermediate (PTX) or binary CUDA
code for the given architecture(s):
@param major Major compute capability version.
@param minor Minor compute capability version.
*/
static bool has(int major, int minor);
static bool hasPtx(int major, int minor);
static bool hasBin(int major, int minor);
static bool hasEqualOrLessPtx(int major, int minor);
static bool hasEqualOrGreater(int major, int minor);
static bool hasEqualOrGreaterPtx(int major, int minor);
static bool hasEqualOrGreaterBin(int major, int minor);
};
/** @brief Class providing functionality for querying the specified GPU properties.
*/
class CV_EXPORTS DeviceInfo
{
public:
//! creates DeviceInfo object for the current GPU
DeviceInfo();
/** @brief The constructors.
@param device_id System index of the CUDA device starting with 0.
Constructs the DeviceInfo object for the specified device. If device_id parameter is missed, it
constructs an object for the current device.
*/
DeviceInfo(int device_id);
/** @brief Returns system index of the CUDA device starting with 0.
*/
int deviceID() const;
//! ASCII string identifying device
const char* name() const;
//! global memory available on device in bytes
size_t totalGlobalMem() const;
//! shared memory available per block in bytes
size_t sharedMemPerBlock() const;
//! 32-bit registers available per block
int regsPerBlock() const;
//! warp size in threads
int warpSize() const;
//! maximum pitch in bytes allowed by memory copies
size_t memPitch() const;
//! maximum number of threads per block
int maxThreadsPerBlock() const;
//! maximum size of each dimension of a block
Vec3i maxThreadsDim() const;
//! maximum size of each dimension of a grid
Vec3i maxGridSize() const;
//! clock frequency in kilohertz
int clockRate() const;
//! constant memory available on device in bytes
size_t totalConstMem() const;
//! major compute capability
int majorVersion() const;
//! minor compute capability
int minorVersion() const;
//! alignment requirement for textures
size_t textureAlignment() const;
//! pitch alignment requirement for texture references bound to pitched memory
size_t texturePitchAlignment() const;
//! number of multiprocessors on device
int multiProcessorCount() const;
//! specified whether there is a run time limit on kernels
bool kernelExecTimeoutEnabled() const;
//! device is integrated as opposed to discrete
bool integrated() const;
//! device can map host memory with cudaHostAlloc/cudaHostGetDevicePointer
bool canMapHostMemory() const;
enum ComputeMode
{
ComputeModeDefault, /**< default compute mode (Multiple threads can use cudaSetDevice with this device) */
ComputeModeExclusive, /**< compute-exclusive-thread mode (Only one thread in one process will be able to use cudaSetDevice with this device) */
ComputeModeProhibited, /**< compute-prohibited mode (No threads can use cudaSetDevice with this device) */
ComputeModeExclusiveProcess /**< compute-exclusive-process mode (Many threads in one process will be able to use cudaSetDevice with this device) */
};
//! compute mode
ComputeMode computeMode() const;
//! maximum 1D texture size
int maxTexture1D() const;
//! maximum 1D mipmapped texture size
int maxTexture1DMipmap() const;
//! maximum size for 1D textures bound to linear memory
int maxTexture1DLinear() const;
//! maximum 2D texture dimensions
Vec2i maxTexture2D() const;
//! maximum 2D mipmapped texture dimensions
Vec2i maxTexture2DMipmap() const;
//! maximum dimensions (width, height, pitch) for 2D textures bound to pitched memory
Vec3i maxTexture2DLinear() const;
//! maximum 2D texture dimensions if texture gather operations have to be performed
Vec2i maxTexture2DGather() const;
//! maximum 3D texture dimensions
Vec3i maxTexture3D() const;
//! maximum Cubemap texture dimensions
int maxTextureCubemap() const;
//! maximum 1D layered texture dimensions
Vec2i maxTexture1DLayered() const;
//! maximum 2D layered texture dimensions
Vec3i maxTexture2DLayered() const;
//! maximum Cubemap layered texture dimensions
Vec2i maxTextureCubemapLayered() const;
//! maximum 1D surface size
int maxSurface1D() const;
//! maximum 2D surface dimensions
Vec2i maxSurface2D() const;
//! maximum 3D surface dimensions
Vec3i maxSurface3D() const;
//! maximum 1D layered surface dimensions
Vec2i maxSurface1DLayered() const;
//! maximum 2D layered surface dimensions
Vec3i maxSurface2DLayered() const;
//! maximum Cubemap surface dimensions
int maxSurfaceCubemap() const;
//! maximum Cubemap layered surface dimensions
Vec2i maxSurfaceCubemapLayered() const;
//! alignment requirements for surfaces
size_t surfaceAlignment() const;
//! device can possibly execute multiple kernels concurrently
bool concurrentKernels() const;
//! device has ECC support enabled
bool ECCEnabled() const;
//! PCI bus ID of the device
int pciBusID() const;
//! PCI device ID of the device
int pciDeviceID() const;
//! PCI domain ID of the device
int pciDomainID() const;
//! true if device is a Tesla device using TCC driver, false otherwise
bool tccDriver() const;
//! number of asynchronous engines
int asyncEngineCount() const;
//! device shares a unified address space with the host
bool unifiedAddressing() const;
//! peak memory clock frequency in kilohertz
int memoryClockRate() const;
//! global memory bus width in bits
int memoryBusWidth() const;
//! size of L2 cache in bytes
int l2CacheSize() const;
//! maximum resident threads per multiprocessor
int maxThreadsPerMultiProcessor() const;
//! gets free and total device memory
void queryMemory(size_t& totalMemory, size_t& freeMemory) const;
size_t freeMemory() const;
size_t totalMemory() const;
/** @brief Provides information on CUDA feature support.
@param feature_set Features to be checked. See cuda::FeatureSet.
This function returns true if the device has the specified CUDA feature. Otherwise, it returns false
*/
bool supports(FeatureSet feature_set) const;
/** @brief Checks the CUDA module and device compatibility.
This function returns true if the CUDA module can be run on the specified device. Otherwise, it
returns false .
*/
bool isCompatible() const;
private:
int device_id_;
};
CV_EXPORTS void printCudaDeviceInfo(int device);
CV_EXPORTS void printShortCudaDeviceInfo(int device);
//! @} cudacore_init
}} // namespace cv { namespace cuda {
#include BLIK_OPENCV_U_opencv2__core__cuda_D_inl_hpp //original-code:"opencv2/core/cuda.inl.hpp"
#endif /* __OPENCV_CORE_CUDA_HPP__ */
| 33.845336 | 157 | 0.695887 | [
"object",
"3d"
] |
4f2805f32c94ba2ee619f64f3d4e3e42c61398a9 | 22,075 | cc | C++ | src/arch/sparc/isa.cc | He-Liu-ooo/Computer-Architecture-THUEE-2022-spring- | 9d36aaacbc7eea357608524113bec97bae2ea229 | [
"BSD-3-Clause"
] | 8 | 2021-12-17T08:07:14.000Z | 2022-03-23T11:49:06.000Z | src/arch/sparc/isa.cc | He-Liu-ooo/Computer-Architecture-THUEE-2022-spring- | 9d36aaacbc7eea357608524113bec97bae2ea229 | [
"BSD-3-Clause"
] | 3 | 2022-01-09T07:50:03.000Z | 2022-02-05T14:46:57.000Z | src/arch/sparc/isa.cc | He-Liu-ooo/Computer-Architecture-THUEE-2022-spring- | 9d36aaacbc7eea357608524113bec97bae2ea229 | [
"BSD-3-Clause"
] | 5 | 2021-12-27T08:39:13.000Z | 2022-03-08T10:21:37.000Z | /*
* Copyright (c) 2009 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "arch/sparc/isa.hh"
#include "arch/sparc/asi.hh"
#include "arch/sparc/decoder.hh"
#include "arch/sparc/interrupts.hh"
#include "base/bitfield.hh"
#include "base/trace.hh"
#include "cpu/base.hh"
#include "cpu/thread_context.hh"
#include "debug/MiscRegs.hh"
#include "debug/Timer.hh"
#include "params/SparcISA.hh"
namespace SparcISA
{
static PSTATE
buildPstateMask()
{
PSTATE mask = 0;
mask.ie = 1;
mask.priv = 1;
mask.am = 1;
mask.pef = 1;
mask.mm = 3;
mask.tle = 1;
mask.cle = 1;
mask.pid1 = 1;
return mask;
}
static const PSTATE PstateMask = buildPstateMask();
ISA::ISA(Params *p) : BaseISA(p)
{
clear();
}
const SparcISAParams *
ISA::params() const
{
return dynamic_cast<const Params *>(_params);
}
void
ISA::reloadRegMap()
{
installGlobals(gl, CurrentGlobalsOffset);
installWindow(cwp, CurrentWindowOffset);
// Microcode registers.
for (int i = 0; i < NumMicroIntRegs; i++)
intRegMap[MicroIntOffset + i] = i + TotalGlobals + NWindows * 16;
installGlobals(gl, NextGlobalsOffset);
installWindow(cwp - 1, NextWindowOffset);
installGlobals(gl, PreviousGlobalsOffset);
installWindow(cwp + 1, PreviousWindowOffset);
}
void
ISA::installWindow(int cwp, int offset)
{
assert(offset >= 0 && offset + NumWindowedRegs <= NumIntRegs);
RegIndex *mapChunk = intRegMap + offset;
for (int i = 0; i < NumWindowedRegs; i++)
mapChunk[i] = TotalGlobals +
((i - cwp * RegsPerWindow + TotalWindowed) % (TotalWindowed));
}
void
ISA::installGlobals(int gl, int offset)
{
assert(offset >= 0 && offset + NumGlobalRegs <= NumIntRegs);
RegIndex *mapChunk = intRegMap + offset;
mapChunk[0] = 0;
for (int i = 1; i < NumGlobalRegs; i++)
mapChunk[i] = i + gl * NumGlobalRegs;
}
void
ISA::clear()
{
cwp = 0;
gl = 0;
reloadRegMap();
// y = 0;
// ccr = 0;
asi = 0;
tick = ULL(1) << 63;
fprs = 0;
gsr = 0;
softint = 0;
tick_cmpr = 0;
stick = 0;
stick_cmpr = 0;
memset(tpc, 0, sizeof(tpc));
memset(tnpc, 0, sizeof(tnpc));
memset(tstate, 0, sizeof(tstate));
memset(tt, 0, sizeof(tt));
tba = 0;
pstate = 0;
tl = 0;
pil = 0;
// cansave = 0;
// canrestore = 0;
// cleanwin = 0;
// otherwin = 0;
// wstate = 0;
// In a T1, bit 11 is apparently always 1
hpstate = 0;
hpstate.id = 1;
memset(htstate, 0, sizeof(htstate));
hintp = 0;
htba = 0;
hstick_cmpr = 0;
// This is set this way in Legion for some reason
strandStatusReg = 0x50000;
fsr = 0;
priContext = 0;
secContext = 0;
partId = 0;
lsuCtrlReg = 0;
memset(scratchPad, 0, sizeof(scratchPad));
cpu_mondo_head = 0;
cpu_mondo_tail = 0;
dev_mondo_head = 0;
dev_mondo_tail = 0;
res_error_head = 0;
res_error_tail = 0;
nres_error_head = 0;
nres_error_tail = 0;
// If one of these events is active, it's not obvious to me how to get
// rid of it cleanly. For now we'll just assert that they're not.
if (tickCompare != NULL && sTickCompare != NULL && hSTickCompare != NULL)
panic("Tick comparison event active when clearing the ISA object.\n");
}
RegVal
ISA::readMiscRegNoEffect(int miscReg) const
{
// The three miscRegs are moved up from the switch statement
// due to more frequent calls.
if (miscReg == MISCREG_GL)
return gl;
if (miscReg == MISCREG_CWP)
return cwp;
if (miscReg == MISCREG_TLB_DATA) {
/* Package up all the data for the tlb:
* 6666555555555544444444443333333333222222222211111111110000000000
* 3210987654321098765432109876543210987654321098765432109876543210
* secContext | priContext | |tl|partid| |||||^hpriv
* ||||^red
* |||^priv
* ||^am
* |^lsuim
* ^lsudm
*/
return (uint64_t)hpstate.hpriv |
(uint64_t)hpstate.red << 1 |
(uint64_t)pstate.priv << 2 |
(uint64_t)pstate.am << 3 |
bits((uint64_t)lsuCtrlReg,3,2) << 4 |
bits((uint64_t)partId,7,0) << 8 |
bits((uint64_t)tl,2,0) << 16 |
(uint64_t)priContext << 32 |
(uint64_t)secContext << 48;
}
switch (miscReg) {
// case MISCREG_TLB_DATA:
// [original contents see above]
// case MISCREG_Y:
// return y;
// case MISCREG_CCR:
// return ccr;
case MISCREG_ASI:
return asi;
case MISCREG_FPRS:
return fprs;
case MISCREG_TICK:
return tick;
case MISCREG_PCR:
panic("PCR not implemented\n");
case MISCREG_PIC:
panic("PIC not implemented\n");
case MISCREG_GSR:
return gsr;
case MISCREG_SOFTINT:
return softint;
case MISCREG_TICK_CMPR:
return tick_cmpr;
case MISCREG_STICK:
return stick;
case MISCREG_STICK_CMPR:
return stick_cmpr;
/** Privilged Registers */
case MISCREG_TPC:
return tpc[tl-1];
case MISCREG_TNPC:
return tnpc[tl-1];
case MISCREG_TSTATE:
return tstate[tl-1];
case MISCREG_TT:
return tt[tl-1];
case MISCREG_PRIVTICK:
panic("Priviliged access to tick registers not implemented\n");
case MISCREG_TBA:
return tba;
case MISCREG_PSTATE:
return (RegVal)pstate;
case MISCREG_TL:
return tl;
case MISCREG_PIL:
return pil;
// CWP, GL moved
// case MISCREG_CWP:
// return cwp;
// case MISCREG_CANSAVE:
// return cansave;
// case MISCREG_CANRESTORE:
// return canrestore;
// case MISCREG_CLEANWIN:
// return cleanwin;
// case MISCREG_OTHERWIN:
// return otherwin;
// case MISCREG_WSTATE:
// return wstate;
// case MISCREG_GL:
// return gl;
/** Hyper privileged registers */
case MISCREG_HPSTATE:
return (RegVal)hpstate;
case MISCREG_HTSTATE:
return htstate[tl-1];
case MISCREG_HINTP:
return hintp;
case MISCREG_HTBA:
return htba;
case MISCREG_STRAND_STS_REG:
return strandStatusReg;
case MISCREG_HSTICK_CMPR:
return hstick_cmpr;
/** Floating Point Status Register */
case MISCREG_FSR:
DPRINTF(MiscRegs, "FSR read as: %#x\n", fsr);
return fsr;
case MISCREG_MMU_P_CONTEXT:
return priContext;
case MISCREG_MMU_S_CONTEXT:
return secContext;
case MISCREG_MMU_PART_ID:
return partId;
case MISCREG_MMU_LSU_CTRL:
return lsuCtrlReg;
case MISCREG_SCRATCHPAD_R0:
return scratchPad[0];
case MISCREG_SCRATCHPAD_R1:
return scratchPad[1];
case MISCREG_SCRATCHPAD_R2:
return scratchPad[2];
case MISCREG_SCRATCHPAD_R3:
return scratchPad[3];
case MISCREG_SCRATCHPAD_R4:
return scratchPad[4];
case MISCREG_SCRATCHPAD_R5:
return scratchPad[5];
case MISCREG_SCRATCHPAD_R6:
return scratchPad[6];
case MISCREG_SCRATCHPAD_R7:
return scratchPad[7];
case MISCREG_QUEUE_CPU_MONDO_HEAD:
return cpu_mondo_head;
case MISCREG_QUEUE_CPU_MONDO_TAIL:
return cpu_mondo_tail;
case MISCREG_QUEUE_DEV_MONDO_HEAD:
return dev_mondo_head;
case MISCREG_QUEUE_DEV_MONDO_TAIL:
return dev_mondo_tail;
case MISCREG_QUEUE_RES_ERROR_HEAD:
return res_error_head;
case MISCREG_QUEUE_RES_ERROR_TAIL:
return res_error_tail;
case MISCREG_QUEUE_NRES_ERROR_HEAD:
return nres_error_head;
case MISCREG_QUEUE_NRES_ERROR_TAIL:
return nres_error_tail;
default:
panic("Miscellaneous register %d not implemented\n", miscReg);
}
}
RegVal
ISA::readMiscReg(int miscReg)
{
switch (miscReg) {
// tick and stick are aliased to each other in niagra
// well store the tick data in stick and the interrupt bit in tick
case MISCREG_STICK:
case MISCREG_TICK:
case MISCREG_PRIVTICK:
// I'm not sure why legion ignores the lowest two bits, but we'll go
// with it
// change from curCycle() to instCount() until we're done with legion
DPRINTF(Timer, "Instruction Count when TICK read: %#X stick=%#X\n",
tc->getCpuPtr()->instCount(), stick);
return mbits(tc->getCpuPtr()->instCount() + (int64_t)stick,62,2) |
mbits(tick,63,63);
case MISCREG_FPRS:
// in legion if fp is enabled du and dl are set
return fprs | 0x3;
case MISCREG_PCR:
case MISCREG_PIC:
panic("Performance Instrumentation not impl\n");
case MISCREG_SOFTINT_CLR:
case MISCREG_SOFTINT_SET:
panic("Can read from softint clr/set\n");
case MISCREG_SOFTINT:
case MISCREG_TICK_CMPR:
case MISCREG_STICK_CMPR:
case MISCREG_HINTP:
case MISCREG_HTSTATE:
case MISCREG_HTBA:
case MISCREG_HVER:
case MISCREG_STRAND_STS_REG:
case MISCREG_HSTICK_CMPR:
case MISCREG_QUEUE_CPU_MONDO_HEAD:
case MISCREG_QUEUE_CPU_MONDO_TAIL:
case MISCREG_QUEUE_DEV_MONDO_HEAD:
case MISCREG_QUEUE_DEV_MONDO_TAIL:
case MISCREG_QUEUE_RES_ERROR_HEAD:
case MISCREG_QUEUE_RES_ERROR_TAIL:
case MISCREG_QUEUE_NRES_ERROR_HEAD:
case MISCREG_QUEUE_NRES_ERROR_TAIL:
case MISCREG_HPSTATE:
return readFSReg(miscReg);
}
return readMiscRegNoEffect(miscReg);
}
void
ISA::setMiscRegNoEffect(int miscReg, RegVal val)
{
switch (miscReg) {
// case MISCREG_Y:
// y = val;
// break;
// case MISCREG_CCR:
// ccr = val;
// break;
case MISCREG_ASI:
asi = val;
break;
case MISCREG_FPRS:
fprs = val;
break;
case MISCREG_TICK:
tick = val;
break;
case MISCREG_PCR:
panic("PCR not implemented\n");
case MISCREG_PIC:
panic("PIC not implemented\n");
case MISCREG_GSR:
gsr = val;
break;
case MISCREG_SOFTINT:
softint = val;
break;
case MISCREG_TICK_CMPR:
tick_cmpr = val;
break;
case MISCREG_STICK:
stick = val;
break;
case MISCREG_STICK_CMPR:
stick_cmpr = val;
break;
/** Privilged Registers */
case MISCREG_TPC:
tpc[tl-1] = val;
break;
case MISCREG_TNPC:
tnpc[tl-1] = val;
break;
case MISCREG_TSTATE:
tstate[tl-1] = val;
break;
case MISCREG_TT:
tt[tl-1] = val;
break;
case MISCREG_PRIVTICK:
panic("Priviliged access to tick regesiters not implemented\n");
case MISCREG_TBA:
// clear lower 7 bits on writes.
tba = val & ULL(~0x7FFF);
break;
case MISCREG_PSTATE:
pstate = (val & PstateMask);
break;
case MISCREG_TL:
tl = val;
break;
case MISCREG_PIL:
pil = val;
break;
case MISCREG_CWP:
cwp = val;
break;
// case MISCREG_CANSAVE:
// cansave = val;
// break;
// case MISCREG_CANRESTORE:
// canrestore = val;
// break;
// case MISCREG_CLEANWIN:
// cleanwin = val;
// break;
// case MISCREG_OTHERWIN:
// otherwin = val;
// break;
// case MISCREG_WSTATE:
// wstate = val;
// break;
case MISCREG_GL:
gl = val;
break;
/** Hyper privileged registers */
case MISCREG_HPSTATE:
hpstate = val;
break;
case MISCREG_HTSTATE:
htstate[tl-1] = val;
break;
case MISCREG_HINTP:
hintp = val;
break;
case MISCREG_HTBA:
htba = val;
break;
case MISCREG_STRAND_STS_REG:
strandStatusReg = val;
break;
case MISCREG_HSTICK_CMPR:
hstick_cmpr = val;
break;
/** Floating Point Status Register */
case MISCREG_FSR:
fsr = val;
DPRINTF(MiscRegs, "FSR written with: %#x\n", fsr);
break;
case MISCREG_MMU_P_CONTEXT:
priContext = val;
break;
case MISCREG_MMU_S_CONTEXT:
secContext = val;
break;
case MISCREG_MMU_PART_ID:
partId = val;
break;
case MISCREG_MMU_LSU_CTRL:
lsuCtrlReg = val;
break;
case MISCREG_SCRATCHPAD_R0:
scratchPad[0] = val;
break;
case MISCREG_SCRATCHPAD_R1:
scratchPad[1] = val;
break;
case MISCREG_SCRATCHPAD_R2:
scratchPad[2] = val;
break;
case MISCREG_SCRATCHPAD_R3:
scratchPad[3] = val;
break;
case MISCREG_SCRATCHPAD_R4:
scratchPad[4] = val;
break;
case MISCREG_SCRATCHPAD_R5:
scratchPad[5] = val;
break;
case MISCREG_SCRATCHPAD_R6:
scratchPad[6] = val;
break;
case MISCREG_SCRATCHPAD_R7:
scratchPad[7] = val;
break;
case MISCREG_QUEUE_CPU_MONDO_HEAD:
cpu_mondo_head = val;
break;
case MISCREG_QUEUE_CPU_MONDO_TAIL:
cpu_mondo_tail = val;
break;
case MISCREG_QUEUE_DEV_MONDO_HEAD:
dev_mondo_head = val;
break;
case MISCREG_QUEUE_DEV_MONDO_TAIL:
dev_mondo_tail = val;
break;
case MISCREG_QUEUE_RES_ERROR_HEAD:
res_error_head = val;
break;
case MISCREG_QUEUE_RES_ERROR_TAIL:
res_error_tail = val;
break;
case MISCREG_QUEUE_NRES_ERROR_HEAD:
nres_error_head = val;
break;
case MISCREG_QUEUE_NRES_ERROR_TAIL:
nres_error_tail = val;
break;
default:
panic("Miscellaneous register %d not implemented\n", miscReg);
}
}
void
ISA::setMiscReg(int miscReg, RegVal val)
{
RegVal new_val = val;
switch (miscReg) {
case MISCREG_ASI:
tc->getDecoderPtr()->setContext(val);
break;
case MISCREG_STICK:
case MISCREG_TICK:
// stick and tick are same thing on niagra
// use stick for offset and tick for holding intrrupt bit
stick = mbits(val,62,0) - tc->getCpuPtr()->instCount();
tick = mbits(val,63,63);
DPRINTF(Timer, "Writing TICK=%#X\n", val);
break;
case MISCREG_FPRS:
// Configure the fpu based on the fprs
break;
case MISCREG_PCR:
// Set up performance counting based on pcr value
break;
case MISCREG_PSTATE:
pstate = val & PstateMask;
return;
case MISCREG_TL:
{
tl = val;
if (hpstate.tlz && tl == 0 && !hpstate.hpriv)
tc->getCpuPtr()->postInterrupt(0, IT_TRAP_LEVEL_ZERO, 0);
else
tc->getCpuPtr()->clearInterrupt(0, IT_TRAP_LEVEL_ZERO, 0);
return;
}
case MISCREG_CWP:
new_val = val >= NWindows ? NWindows - 1 : val;
if (val >= NWindows)
new_val = NWindows - 1;
installWindow(new_val, CurrentWindowOffset);
installWindow(new_val - 1, NextWindowOffset);
installWindow(new_val + 1, PreviousWindowOffset);
break;
case MISCREG_GL:
installGlobals(val, CurrentGlobalsOffset);
installGlobals(val, NextGlobalsOffset);
installGlobals(val, PreviousGlobalsOffset);
break;
case MISCREG_PIL:
case MISCREG_SOFTINT:
case MISCREG_SOFTINT_SET:
case MISCREG_SOFTINT_CLR:
case MISCREG_TICK_CMPR:
case MISCREG_STICK_CMPR:
case MISCREG_HINTP:
case MISCREG_HTSTATE:
case MISCREG_HTBA:
case MISCREG_HVER:
case MISCREG_STRAND_STS_REG:
case MISCREG_HSTICK_CMPR:
case MISCREG_QUEUE_CPU_MONDO_HEAD:
case MISCREG_QUEUE_CPU_MONDO_TAIL:
case MISCREG_QUEUE_DEV_MONDO_HEAD:
case MISCREG_QUEUE_DEV_MONDO_TAIL:
case MISCREG_QUEUE_RES_ERROR_HEAD:
case MISCREG_QUEUE_RES_ERROR_TAIL:
case MISCREG_QUEUE_NRES_ERROR_HEAD:
case MISCREG_QUEUE_NRES_ERROR_TAIL:
case MISCREG_HPSTATE:
setFSReg(miscReg, val);
return;
}
setMiscRegNoEffect(miscReg, new_val);
}
void
ISA::serialize(CheckpointOut &cp) const
{
SERIALIZE_SCALAR(asi);
SERIALIZE_SCALAR(tick);
SERIALIZE_SCALAR(fprs);
SERIALIZE_SCALAR(gsr);
SERIALIZE_SCALAR(softint);
SERIALIZE_SCALAR(tick_cmpr);
SERIALIZE_SCALAR(stick);
SERIALIZE_SCALAR(stick_cmpr);
SERIALIZE_ARRAY(tpc,MaxTL);
SERIALIZE_ARRAY(tnpc,MaxTL);
SERIALIZE_ARRAY(tstate,MaxTL);
SERIALIZE_ARRAY(tt,MaxTL);
SERIALIZE_SCALAR(tba);
SERIALIZE_SCALAR(pstate);
SERIALIZE_SCALAR(tl);
SERIALIZE_SCALAR(pil);
SERIALIZE_SCALAR(cwp);
SERIALIZE_SCALAR(gl);
SERIALIZE_SCALAR(hpstate);
SERIALIZE_ARRAY(htstate,MaxTL);
SERIALIZE_SCALAR(hintp);
SERIALIZE_SCALAR(htba);
SERIALIZE_SCALAR(hstick_cmpr);
SERIALIZE_SCALAR(strandStatusReg);
SERIALIZE_SCALAR(fsr);
SERIALIZE_SCALAR(priContext);
SERIALIZE_SCALAR(secContext);
SERIALIZE_SCALAR(partId);
SERIALIZE_SCALAR(lsuCtrlReg);
SERIALIZE_ARRAY(scratchPad,8);
SERIALIZE_SCALAR(cpu_mondo_head);
SERIALIZE_SCALAR(cpu_mondo_tail);
SERIALIZE_SCALAR(dev_mondo_head);
SERIALIZE_SCALAR(dev_mondo_tail);
SERIALIZE_SCALAR(res_error_head);
SERIALIZE_SCALAR(res_error_tail);
SERIALIZE_SCALAR(nres_error_head);
SERIALIZE_SCALAR(nres_error_tail);
Tick tick_cmp = 0, stick_cmp = 0, hstick_cmp = 0;
if (tickCompare && tickCompare->scheduled())
tick_cmp = tickCompare->when();
if (sTickCompare && sTickCompare->scheduled())
stick_cmp = sTickCompare->when();
if (hSTickCompare && hSTickCompare->scheduled())
hstick_cmp = hSTickCompare->when();
SERIALIZE_SCALAR(tick_cmp);
SERIALIZE_SCALAR(stick_cmp);
SERIALIZE_SCALAR(hstick_cmp);
}
void
ISA::unserialize(CheckpointIn &cp)
{
UNSERIALIZE_SCALAR(asi);
UNSERIALIZE_SCALAR(tick);
UNSERIALIZE_SCALAR(fprs);
UNSERIALIZE_SCALAR(gsr);
UNSERIALIZE_SCALAR(softint);
UNSERIALIZE_SCALAR(tick_cmpr);
UNSERIALIZE_SCALAR(stick);
UNSERIALIZE_SCALAR(stick_cmpr);
UNSERIALIZE_ARRAY(tpc,MaxTL);
UNSERIALIZE_ARRAY(tnpc,MaxTL);
UNSERIALIZE_ARRAY(tstate,MaxTL);
UNSERIALIZE_ARRAY(tt,MaxTL);
UNSERIALIZE_SCALAR(tba);
{
uint16_t pstate;
UNSERIALIZE_SCALAR(pstate);
this->pstate = pstate;
}
UNSERIALIZE_SCALAR(tl);
UNSERIALIZE_SCALAR(pil);
UNSERIALIZE_SCALAR(cwp);
UNSERIALIZE_SCALAR(gl);
reloadRegMap();
{
uint64_t hpstate;
UNSERIALIZE_SCALAR(hpstate);
this->hpstate = hpstate;
}
UNSERIALIZE_ARRAY(htstate,MaxTL);
UNSERIALIZE_SCALAR(hintp);
UNSERIALIZE_SCALAR(htba);
UNSERIALIZE_SCALAR(hstick_cmpr);
UNSERIALIZE_SCALAR(strandStatusReg);
UNSERIALIZE_SCALAR(fsr);
UNSERIALIZE_SCALAR(priContext);
UNSERIALIZE_SCALAR(secContext);
UNSERIALIZE_SCALAR(partId);
UNSERIALIZE_SCALAR(lsuCtrlReg);
UNSERIALIZE_ARRAY(scratchPad,8);
UNSERIALIZE_SCALAR(cpu_mondo_head);
UNSERIALIZE_SCALAR(cpu_mondo_tail);
UNSERIALIZE_SCALAR(dev_mondo_head);
UNSERIALIZE_SCALAR(dev_mondo_tail);
UNSERIALIZE_SCALAR(res_error_head);
UNSERIALIZE_SCALAR(res_error_tail);
UNSERIALIZE_SCALAR(nres_error_head);
UNSERIALIZE_SCALAR(nres_error_tail);
Tick tick_cmp = 0, stick_cmp = 0, hstick_cmp = 0;
UNSERIALIZE_SCALAR(tick_cmp);
UNSERIALIZE_SCALAR(stick_cmp);
UNSERIALIZE_SCALAR(hstick_cmp);
if (tick_cmp) {
tickCompare = new TickCompareEvent(this);
schedule(tickCompare, tick_cmp);
}
if (stick_cmp) {
sTickCompare = new STickCompareEvent(this);
schedule(sTickCompare, stick_cmp);
}
if (hstick_cmp) {
hSTickCompare = new HSTickCompareEvent(this);
schedule(hSTickCompare, hstick_cmp);
}
}
}
SparcISA::ISA *
SparcISAParams::create()
{
return new SparcISA::ISA(this);
}
| 28.74349 | 78 | 0.624734 | [
"object"
] |
4f2ab987b05a0d58401f9a30eef0af3b04ac49d6 | 3,570 | cxx | C++ | dep/scintilla/scintilla-3.10.6/src/ExternalLexer.cxx | DeadMozay/gitahead | 6c27dda42d99f794089913bc06977042a040bbf7 | [
"MIT"
] | 17 | 2019-06-04T06:22:47.000Z | 2022-02-11T18:27:25.000Z | dep/scintilla/scintilla-3.10.6/src/ExternalLexer.cxx | DeadMozay/gitahead | 6c27dda42d99f794089913bc06977042a040bbf7 | [
"MIT"
] | 1,248 | 2019-02-21T19:32:09.000Z | 2022-03-29T16:50:04.000Z | dep/scintilla/scintilla-3.10.6/src/ExternalLexer.cxx | DeadMozay/gitahead | 6c27dda42d99f794089913bc06977042a040bbf7 | [
"MIT"
] | 17 | 2019-02-12T07:58:23.000Z | 2022-03-10T11:39:21.000Z | // Scintilla source code edit control
/** @file ExternalLexer.cxx
** Support external lexers in DLLs or shared libraries.
**/
// Copyright 2001 Simon Steele <ss@pnotepad.org>, portions copyright Neil Hodgson.
// The License.txt file describes the conditions under which this software may be distributed.
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <stdexcept>
#include <string>
#include <vector>
#include <memory>
#include "Platform.h"
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "LexerModule.h"
#include "Catalogue.h"
#include "ExternalLexer.h"
using namespace Scintilla;
std::unique_ptr<LexerManager> LexerManager::theInstance;
//------------------------------------------
//
// ExternalLexerModule
//
//------------------------------------------
void ExternalLexerModule::SetExternal(GetLexerFactoryFunction fFactory, int index) {
fneFactory = fFactory;
fnFactory = fFactory(index);
}
//------------------------------------------
//
// LexerLibrary
//
//------------------------------------------
LexerLibrary::LexerLibrary(const char *moduleName_) {
// Load the DLL
lib.reset(DynamicLibrary::Load(moduleName_));
if (lib->IsValid()) {
moduleName = moduleName_;
//Cannot use reinterpret_cast because: ANSI C++ forbids casting between pointers to functions and objects
GetLexerCountFn GetLexerCount = (GetLexerCountFn)(sptr_t)lib->FindFunction("GetLexerCount");
if (GetLexerCount) {
// Find functions in the DLL
GetLexerNameFn GetLexerName = (GetLexerNameFn)(sptr_t)lib->FindFunction("GetLexerName");
GetLexerFactoryFunction fnFactory = (GetLexerFactoryFunction)(sptr_t)lib->FindFunction("GetLexerFactory");
const int nl = GetLexerCount();
for (int i = 0; i < nl; i++) {
// Assign a buffer for the lexer name.
char lexname[100] = "";
GetLexerName(i, lexname, sizeof(lexname));
ExternalLexerModule *lex = new ExternalLexerModule(SCLEX_AUTOMATIC, nullptr, lexname, nullptr);
// This is storing a second reference to lex in the Catalogue as well as in modules.
// TODO: Should use std::shared_ptr or similar to ensure allocation safety.
Catalogue::AddLexerModule(lex);
// Remember ExternalLexerModule so we don't leak it
modules.push_back(std::unique_ptr<ExternalLexerModule>(lex));
// The external lexer needs to know how to call into its DLL to
// do its lexing and folding, we tell it here.
lex->SetExternal(fnFactory, i);
}
}
}
}
LexerLibrary::~LexerLibrary() {
}
//------------------------------------------
//
// LexerManager
//
//------------------------------------------
/// Return the single LexerManager instance...
LexerManager *LexerManager::GetInstance() {
if (!theInstance)
theInstance.reset(new LexerManager);
return theInstance.get();
}
/// Delete any LexerManager instance...
void LexerManager::DeleteInstance() {
theInstance.reset();
}
/// protected constructor - this is a singleton...
LexerManager::LexerManager() {
}
LexerManager::~LexerManager() {
Clear();
}
void LexerManager::Load(const char *path) {
for (const std::unique_ptr<LexerLibrary> &ll : libraries) {
if (ll->moduleName == path)
return;
}
LexerLibrary *lib = new LexerLibrary(path);
libraries.push_back(std::unique_ptr<LexerLibrary>(lib));
}
void LexerManager::Clear() {
libraries.clear();
}
//------------------------------------------
//
// LMMinder -- trigger to clean up at exit.
//
//------------------------------------------
LMMinder::~LMMinder() {
LexerManager::DeleteInstance();
}
LMMinder minder;
| 26.25 | 109 | 0.652381 | [
"vector"
] |
4f2b3c93c8c4d07a14e74c8fe6d31756364ef2f5 | 1,597 | cpp | C++ | aws-cpp-sdk-macie2/source/model/GetFindingStatisticsRequest.cpp | orinem/aws-sdk-cpp | f38413cc1f278689ef14e9ebdd74a489a48776be | [
"Apache-2.0"
] | 1 | 2020-07-16T19:02:58.000Z | 2020-07-16T19:02:58.000Z | aws-cpp-sdk-macie2/source/model/GetFindingStatisticsRequest.cpp | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-macie2/source/model/GetFindingStatisticsRequest.cpp | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/macie2/model/GetFindingStatisticsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Macie2::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
GetFindingStatisticsRequest::GetFindingStatisticsRequest() :
m_findingCriteriaHasBeenSet(false),
m_groupBy(GroupBy::NOT_SET),
m_groupByHasBeenSet(false),
m_size(0),
m_sizeHasBeenSet(false),
m_sortCriteriaHasBeenSet(false)
{
}
Aws::String GetFindingStatisticsRequest::SerializePayload() const
{
JsonValue payload;
if(m_findingCriteriaHasBeenSet)
{
payload.WithObject("findingCriteria", m_findingCriteria.Jsonize());
}
if(m_groupByHasBeenSet)
{
payload.WithString("groupBy", GroupByMapper::GetNameForGroupBy(m_groupBy));
}
if(m_sizeHasBeenSet)
{
payload.WithInteger("size", m_size);
}
if(m_sortCriteriaHasBeenSet)
{
payload.WithObject("sortCriteria", m_sortCriteria.Jsonize());
}
return payload.View().WriteReadable();
}
| 23.485294 | 78 | 0.745147 | [
"model"
] |
4f2b6c44627a10b7abce1097d49f034f5f81de67 | 19,763 | cpp | C++ | Dev/Cpp/Viewer/Graphics/Platform/GL/efk.PostEffectsGL.cpp | meshula/Effekseer | a3fc1885907cc97a60d65406a984141c9b532b23 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Dev/Cpp/Viewer/Graphics/Platform/GL/efk.PostEffectsGL.cpp | meshula/Effekseer | a3fc1885907cc97a60d65406a984141c9b532b23 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Dev/Cpp/Viewer/Graphics/Platform/GL/efk.PostEffectsGL.cpp | meshula/Effekseer | a3fc1885907cc97a60d65406a984141c9b532b23 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | #if _WIN32
#define NOMINMAX
#endif
#include <algorithm>
#include <iostream>
#include "efk.PostEffectsGL.h"
#include <EffekseerRendererGL/EffekseerRenderer/EffekseerRendererGL.GLExtension.h>
namespace efk
{
static const char g_basic_vs_src[] =
R"(
IN vec4 a_Position;
IN vec2 a_TexCoord;
OUT vec2 v_TexCoord;
void main() {
gl_Position = a_Position;
v_TexCoord = a_TexCoord.xy;
}
)";
static const char g_copy_fs_src[] =
R"(
IN vec2 v_TexCoord;
uniform sampler2D u_Texture0;
void main() {
vec4 color = TEX2D(u_Texture0, v_TexCoord);
FRAGCOLOR = vec4(color.xyz, 1.0);
}
)";
static const char g_extract_fs_src[] =
R"(
IN vec2 v_TexCoord;
uniform sampler2D u_Texture0;
uniform vec4 u_FilterParams;
uniform vec4 u_Intensity;
void main() {
vec3 color = TEX2D(u_Texture0, v_TexCoord).rgb;
float brightness = dot(color, vec3(0.299, 0.587, 0.114));
float soft = brightness - u_FilterParams.y;
soft = clamp(soft, 0.0, u_FilterParams.z);
soft = soft * soft * u_FilterParams.w;
float contribution = max(soft, brightness - u_FilterParams.x);
contribution /= max(brightness, 0.00001);
FRAGCOLOR = vec4(color.rgb * contribution * u_Intensity.x, 1.0);
}
)";
static const char g_downsample_fs_src[] =
R"(
IN vec2 v_TexCoord;
uniform sampler2D u_Texture0;
const vec4 gain = vec4(0.25, 0.5, 1.0, 2.0);
void main() {
ivec2 size = textureSize(u_Texture0, 0);
vec2 scale = vec2(1.0 / size.x, 1.0 / size.y);
vec4 c0 = TEX2D(u_Texture0, v_TexCoord + vec2(-0.5, -0.5) * scale);
vec4 c1 = TEX2D(u_Texture0, v_TexCoord + vec2(+0.5, -0.5) * scale);
vec4 c2 = TEX2D(u_Texture0, v_TexCoord + vec2(-0.5, +0.5) * scale);
vec4 c3 = TEX2D(u_Texture0, v_TexCoord + vec2(+0.5, +0.5) * scale);
FRAGCOLOR = (c0 + c1 + c2 + c3) * 0.25;
}
)";
static const char g_blend_fs_src[] =
R"(
IN vec2 v_TexCoord;
uniform sampler2D u_Texture0;
uniform sampler2D u_Texture1;
uniform sampler2D u_Texture2;
uniform sampler2D u_Texture3;
void main() {
vec3 c0 = TEX2D(u_Texture0, v_TexCoord).rgb;
vec3 c1 = TEX2D(u_Texture1, v_TexCoord).rgb;
vec3 c2 = TEX2D(u_Texture2, v_TexCoord).rgb;
vec3 c3 = TEX2D(u_Texture3, v_TexCoord).rgb;
FRAGCOLOR = vec4(c0 + c1 + c2 + c3, 1.0);
}
)";
static const char g_blur_h_fs_src[] =
R"(
IN vec2 v_TexCoord;
uniform sampler2D u_Texture0;
void main() {
ivec2 size = textureSize(u_Texture0, 0);
float div = float(size.x);
vec4 color = TEX2D(u_Texture0, v_TexCoord) * 0.223067435;
color += TEX2D(u_Texture0, v_TexCoord + vec2(-5.152032242 / div, 0)) * 0.005291685;
color += TEX2D(u_Texture0, v_TexCoord + vec2(-3.250912787 / div, 0)) * 0.072975516;
color += TEX2D(u_Texture0, v_TexCoord + vec2(-1.384912144 / div, 0)) * 0.310199082;
color += TEX2D(u_Texture0, v_TexCoord + vec2(+1.384912144 / div, 0)) * 0.310199082;
color += TEX2D(u_Texture0, v_TexCoord + vec2(+3.250912787 / div, 0)) * 0.072975516;
color += TEX2D(u_Texture0, v_TexCoord + vec2(+5.152032242 / div, 0)) * 0.005291685;
FRAGCOLOR = vec4(color.rgb, 1.0);
}
)";
static const char g_blur_v_fs_src[] =
R"(
IN vec2 v_TexCoord;
uniform sampler2D u_Texture0;
void main() {
ivec2 size = textureSize(u_Texture0, 0);
float div = float(size.y);
vec4 color = TEX2D(u_Texture0, v_TexCoord) * 0.223067435;
color += TEX2D(u_Texture0, v_TexCoord + vec2(0.0, -5.152032242 / div)) * 0.005291685;
color += TEX2D(u_Texture0, v_TexCoord + vec2(0.0, -3.250912787 / div)) * 0.072975516;
color += TEX2D(u_Texture0, v_TexCoord + vec2(0.0, -1.384912144 / div)) * 0.310199082;
color += TEX2D(u_Texture0, v_TexCoord + vec2(0.0, +1.384912144 / div)) * 0.310199082;
color += TEX2D(u_Texture0, v_TexCoord + vec2(0.0, +3.250912787 / div)) * 0.072975516;
color += TEX2D(u_Texture0, v_TexCoord + vec2(0.0, +5.152032242 / div)) * 0.005291685;
FRAGCOLOR = vec4(color.rgb, 1.0);
}
)";
static const char g_tonemap_reinhard_fs_src[] =
R"(
IN mediump vec2 v_TexCoord;
uniform sampler2D u_Texture0;
uniform vec4 u_Exposure;
void main() {
vec3 color = texture(u_Texture0, v_TexCoord).rgb;
float lum = u_Exposure.x * dot(color, vec3(0.299, 0.587, 0.114));
lum = lum / (1.0 + lum);
FRAGCOLOR = vec4(lum * color, 1.0f);
}
)";
static const char g_linear_to_srgb_fs_src[] =
R"(
IN vec2 v_TexCoord;
uniform sampler2D u_Texture0;
void main() {
vec4 color = TEX2D(u_Texture0, v_TexCoord);
FRAGCOLOR = vec4(pow(color.xyz, vec3(1.0 / 2.2, 1.0 / 2.2, 1.0 / 2.2)), 1.0);
}
)";
const Effekseer::Backend::VertexLayoutElement vlElem[2] = {
{Effekseer::Backend::VertexLayoutFormat::R32G32_FLOAT, "a_Position", "POSITION", 0},
{Effekseer::Backend::VertexLayoutFormat::R32G32_FLOAT, "a_TexCoord", "TEXCOORD", 0},
};
BlitterGL::BlitterGL(Graphics* graphics, const EffekseerRenderer::RendererRef& renderer)
: graphics(graphics)
, renderer_(EffekseerRendererGL::RendererImplementedRef::FromPinned(renderer.Get()))
{
using namespace EffekseerRendererGL;
auto gd = this->renderer_->GetGraphicsDevice().DownCast<EffekseerRendererGL::Backend::GraphicsDevice>();
// Generate vertex data
vertexBuffer.reset(VertexBuffer::Create(gd, true, sizeof(Vertex) * 4, true));
vertexBuffer->Lock();
{
Vertex* verteces = (Vertex*)vertexBuffer->GetBufferDirect(sizeof(Vertex) * 4);
verteces[0] = Vertex{-1.0f, 1.0f, 0.0f, 1.0f};
verteces[1] = Vertex{-1.0f, -1.0f, 0.0f, 0.0f};
verteces[2] = Vertex{1.0f, 1.0f, 1.0f, 1.0f};
verteces[3] = Vertex{1.0f, -1.0f, 1.0f, 0.0f};
}
vertexBuffer->Unlock();
}
BlitterGL::~BlitterGL()
{
}
std::unique_ptr<EffekseerRendererGL::VertexArray> BlitterGL::CreateVAO(Effekseer::Backend::GraphicsDeviceRef graphicsDevice, EffekseerRendererGL::Shader* shader)
{
using namespace EffekseerRendererGL;
auto gd = graphicsDevice.DownCast<EffekseerRendererGL::Backend::GraphicsDevice>();
return std::unique_ptr<VertexArray>(VertexArray::Create(gd, shader, vertexBuffer.get(), renderer_->GetIndexBuffer()));
}
void BlitterGL::Blit(EffekseerRendererGL::Shader* shader,
EffekseerRendererGL::VertexArray* vao,
const std::vector<Effekseer::Backend::TextureRef>& textures,
const void* constantData,
size_t constantDataSize,
Effekseer::Backend::TextureRef dest,
bool isCleared)
{
using namespace Effekseer;
using namespace EffekseerRendererGL;
// Set GLStates
renderer_->SetVertexArray(vao);
renderer_->BeginShader(shader);
// Set shader parameters
if (constantData != nullptr)
{
memcpy(shader->GetPixelConstantBuffer(), constantData, constantDataSize);
shader->SetConstantBuffer();
}
// Set destination texture
graphics->SetRenderTarget({dest}, nullptr);
if (isCleared)
{
graphics->Clear(Effekseer::Color(0, 0, 0, 0));
}
// Set source textures
for (size_t slot = 0; slot < textures.size(); slot++)
{
auto texture = textures[slot];
auto t = texture.DownCast<EffekseerRendererGL::Backend::Texture>();
GLExt::glBindSampler(slot, 0);
GLExt::glActiveTexture(GL_TEXTURE0 + slot);
glBindTexture(GL_TEXTURE_2D, t->GetBuffer());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
GLExt::glUniform1i(shader->GetTextureSlot(slot), slot);
GLCheckError();
}
GLsizei stride = GL_UNSIGNED_SHORT;
if (renderer_->GetIndexBuffer()->GetStride() == 4)
{
stride = GL_UNSIGNED_INT;
}
glDrawElements(GL_TRIANGLES, 6, stride, nullptr);
GLCheckError();
renderer_->EndShader(shader);
}
BloomEffectGL::BloomEffectGL(Graphics* graphics, const EffekseerRenderer::RendererRef& renderer)
: BloomEffect(graphics)
, blitter(graphics, renderer)
, renderer_(EffekseerRendererGL::RendererImplementedRef::FromPinned(renderer.Get()))
{
auto vl = renderer->GetGraphicsDevice()->CreateVertexLayout(vlElem, 2).DownCast<EffekseerRendererGL::Backend::VertexLayout>();
EffekseerRendererGL::ShaderCodeView basicVS(g_basic_vs_src);
// Extract shader
EffekseerRendererGL::ShaderCodeView extractPS(g_extract_fs_src);
using namespace Effekseer::Backend;
Effekseer::CustomVector<Effekseer::Backend::UniformLayoutElement> uniformLayoutElm;
uniformLayoutElm.emplace_back(UniformLayoutElement{ShaderStageType::Pixel, "u_FilterParams", UniformBufferLayoutElementType::Vector4, 1, 0});
uniformLayoutElm.emplace_back(UniformLayoutElement{ShaderStageType::Pixel, "u_Intensity", UniformBufferLayoutElementType::Vector4, 1, sizeof(float) * 4});
auto uniformLayout = Effekseer::MakeRefPtr<Effekseer::Backend::UniformLayout>(Effekseer::CustomVector<Effekseer::CustomString<char>>{"u_Texture0"}, uniformLayoutElm);
auto uniformLayoutSingleImage = Effekseer::MakeRefPtr<Effekseer::Backend::UniformLayout>(Effekseer::CustomVector<Effekseer::CustomString<char>>{"u_Texture0"}, Effekseer::CustomVector<Effekseer::Backend::UniformLayoutElement>{});
auto uniformLayoutImages = Effekseer::MakeRefPtr<Effekseer::Backend::UniformLayout>(Effekseer::CustomVector<Effekseer::CustomString<char>>{"u_Texture0", "u_Texture1", "u_Texture2", "u_Texture3"}, Effekseer::CustomVector<Effekseer::Backend::UniformLayoutElement>{});
shaderExtract.reset(EffekseerRendererGL::Shader::CreateWithHeader(renderer_->GetInternalGraphicsDevice(), basicVS, extractPS, uniformLayout, "Bloom extract"));
shaderExtract->SetVertexLayout(vl);
shaderExtract->SetPixelConstantBufferSize(sizeof(float) * 8);
// Downsample shader
EffekseerRendererGL::ShaderCodeView downSamplePS(g_downsample_fs_src);
shaderDownsample.reset(EffekseerRendererGL::Shader::CreateWithHeader(renderer_->GetInternalGraphicsDevice(), basicVS, downSamplePS, uniformLayoutSingleImage, "Bloom downsample"));
shaderDownsample->SetVertexLayout(vl);
// Blend shader
EffekseerRendererGL::ShaderCodeView blendPS(g_blend_fs_src);
shaderBlend.reset(EffekseerRendererGL::Shader::CreateWithHeader(renderer_->GetInternalGraphicsDevice(), basicVS, blendPS, uniformLayoutImages, "Bloom blend"));
shaderBlend->SetVertexLayout(vl);
// Blur(horizontal) shader
EffekseerRendererGL::ShaderCodeView blend_h_PS(g_blur_h_fs_src);
shaderBlurH.reset(EffekseerRendererGL::Shader::CreateWithHeader(renderer_->GetInternalGraphicsDevice(), basicVS, blend_h_PS, uniformLayoutSingleImage, "Bloom blurH"));
shaderBlurH->SetVertexLayout(vl);
// Blur(vertical) shader
EffekseerRendererGL::ShaderCodeView blend_v_PS(g_blur_v_fs_src);
shaderBlurV.reset(EffekseerRendererGL::Shader::CreateWithHeader(renderer_->GetInternalGraphicsDevice(), basicVS, blend_v_PS, uniformLayoutSingleImage, "Bloom blurV"));
shaderBlurV->SetVertexLayout(vl);
// Setup VAOs
vaoExtract = blitter.CreateVAO(renderer->GetGraphicsDevice(), shaderExtract.get());
vaoDownsample = blitter.CreateVAO(renderer->GetGraphicsDevice(), shaderDownsample.get());
vaoBlend = blitter.CreateVAO(renderer->GetGraphicsDevice(), shaderBlend.get());
vaoBlurH = blitter.CreateVAO(renderer->GetGraphicsDevice(), shaderBlurH.get());
vaoBlurV = blitter.CreateVAO(renderer->GetGraphicsDevice(), shaderBlurV.get());
}
BloomEffectGL::~BloomEffectGL()
{
}
void BloomEffectGL::Render(Effekseer::Backend::TextureRef src, Effekseer::Backend::TextureRef dest)
{
if (!enabled)
{
return;
}
using namespace Effekseer;
using namespace EffekseerRendererGL;
if (renderTextureWidth != src->GetSize()[0] || renderTextureHeight != src->GetSize()[1])
{
SetupBuffers(src->GetSize()[0], src->GetSize()[1]);
}
auto& state = renderer_->GetRenderState()->Push();
state.AlphaBlend = AlphaBlendType::Opacity;
state.DepthWrite = false;
state.DepthTest = false;
state.CullingType = CullingType::Double;
state.TextureFilterTypes[0] = TextureFilterType::Linear;
state.TextureWrapTypes[0] = TextureWrapType::Clamp;
renderer_->GetRenderState()->Update(false);
renderer_->SetRenderMode(RenderMode::Normal);
// Extract pass
{
const float knee = threshold * softKnee;
const float constantData[8] = {
threshold,
threshold - knee,
knee * 2.0f,
0.25f / (knee + 0.00001f),
intensity,
};
blitter.Blit(shaderExtract.get(), vaoExtract.get(), std::vector<Effekseer::Backend::TextureRef>{src}, constantData, sizeof(constantData), extractBuffer->GetAsBackend());
}
// Shrink pass
for (int i = 0; i < BlurIterations; i++)
{
const auto textures = (i == 0) ? extractBuffer->GetAsBackend() : lowresBuffers[0][i - 1]->GetAsBackend();
blitter.Blit(shaderDownsample.get(), vaoDownsample.get(), std::vector<Effekseer::Backend::TextureRef>{textures}, nullptr, 0, lowresBuffers[0][i]->GetAsBackend());
}
// Horizontal gaussian blur pass
for (int i = 0; i < BlurIterations; i++)
{
const std::vector<Effekseer::Backend::TextureRef> textures{lowresBuffers[0][i]->GetAsBackend()};
blitter.Blit(shaderBlurH.get(), vaoBlurH.get(), textures, nullptr, 0, lowresBuffers[1][i]->GetAsBackend());
}
// Vertical gaussian blur pass
for (int i = 0; i < BlurIterations; i++)
{
const std::vector<Effekseer::Backend::TextureRef> textures{lowresBuffers[1][i]->GetAsBackend()};
blitter.Blit(shaderBlurV.get(), vaoBlurV.get(), textures, nullptr, 0, lowresBuffers[0][i]->GetAsBackend());
}
// Blending pass
state.AlphaBlend = AlphaBlendType::Add;
renderer_->GetRenderState()->Update(false);
{
const std::vector<Effekseer::Backend::TextureRef> textures{lowresBuffers[0][0]->GetAsBackend(),
lowresBuffers[0][1]->GetAsBackend(),
lowresBuffers[0][2]->GetAsBackend(),
lowresBuffers[0][3]->GetAsBackend()};
blitter.Blit(shaderBlend.get(), vaoBlend.get(), textures, nullptr, 0, dest, false);
}
GLExt::glActiveTexture(GL_TEXTURE0);
renderer_->GetRenderState()->Update(true);
renderer_->GetRenderState()->Pop();
GLCheckError();
}
void BloomEffectGL::OnLostDevice()
{
ReleaseBuffers();
}
void BloomEffectGL::OnResetDevice()
{
}
void BloomEffectGL::SetupBuffers(int32_t width, int32_t height)
{
ReleaseBuffers();
renderTextureWidth = width;
renderTextureHeight = height;
// Create high brightness extraction buffer
{
auto bufferSize = Effekseer::Tool::Vector2DI(width, height);
extractBuffer.reset(RenderTexture::Create(graphics));
extractBuffer->Initialize(bufferSize, Effekseer::Backend::TextureFormatType::R16G16B16A16_FLOAT);
}
// Create low-resolution buffers
for (int i = 0; i < BlurBuffers; i++)
{
auto bufferSize = Effekseer::Tool::Vector2DI(width, height);
for (int j = 0; j < BlurIterations; j++)
{
bufferSize.X = std::max(1, (bufferSize.X + 1) / 2);
bufferSize.Y = std::max(1, (bufferSize.Y + 1) / 2);
lowresBuffers[i][j].reset(RenderTexture::Create(graphics));
lowresBuffers[i][j]->Initialize(bufferSize, Effekseer::Backend::TextureFormatType::R16G16B16A16_FLOAT);
}
}
}
void BloomEffectGL::ReleaseBuffers()
{
renderTextureWidth = 0;
renderTextureHeight = 0;
extractBuffer.reset();
for (int i = 0; i < BlurBuffers; i++)
{
for (int j = 0; j < BlurIterations; j++)
{
lowresBuffers[i][j].reset();
}
}
}
TonemapEffectGL::TonemapEffectGL(Graphics* graphics, const EffekseerRenderer::RendererRef& renderer)
: TonemapEffect(graphics)
, blitter(graphics, renderer)
, renderer_(EffekseerRendererGL::RendererImplementedRef::FromPinned(renderer.Get()))
{
using namespace EffekseerRendererGL;
auto vl = renderer->GetGraphicsDevice()->CreateVertexLayout(vlElem, 2).DownCast<EffekseerRendererGL::Backend::VertexLayout>();
auto uniformLayoutSingleImage = Effekseer::MakeRefPtr<Effekseer::Backend::UniformLayout>(Effekseer::CustomVector<Effekseer::CustomString<char>>{"u_Texture0"}, Effekseer::CustomVector<Effekseer::Backend::UniformLayoutElement>{});
EffekseerRendererGL::ShaderCodeView basicVS(g_basic_vs_src);
// Copy shader
EffekseerRendererGL::ShaderCodeView copyPS(g_copy_fs_src);
shaderCopy.reset(Shader::CreateWithHeader(renderer_->GetInternalGraphicsDevice(), basicVS, copyPS, uniformLayoutSingleImage, "Tonemap copy"));
shaderCopy->SetVertexLayout(vl);
// Reinhard shader
EffekseerRendererGL::ShaderCodeView tonemapPS(g_tonemap_reinhard_fs_src);
using namespace Effekseer::Backend;
Effekseer::CustomVector<Effekseer::Backend::UniformLayoutElement> uniformLayoutElm;
uniformLayoutElm.emplace_back(UniformLayoutElement{ShaderStageType::Pixel, "u_Exposure", UniformBufferLayoutElementType::Vector4, 1, 0});
auto uniformLayout = Effekseer::MakeRefPtr<Effekseer::Backend::UniformLayout>(Effekseer::CustomVector<Effekseer::CustomString<char>>{"u_Texture0"}, uniformLayoutElm);
shaderReinhard.reset(EffekseerRendererGL::Shader::CreateWithHeader(renderer_->GetInternalGraphicsDevice(), basicVS, tonemapPS, uniformLayout, "Tonemap Reinhard"));
shaderReinhard->SetVertexLayout(vl);
shaderReinhard->SetPixelConstantBufferSize(sizeof(float) * 4);
// Setup VAOs
vaoCopy = blitter.CreateVAO(renderer->GetGraphicsDevice(), shaderCopy.get());
vaoReinhard = blitter.CreateVAO(renderer->GetGraphicsDevice(), shaderReinhard.get());
}
TonemapEffectGL::~TonemapEffectGL()
{
}
void TonemapEffectGL::Render(Effekseer::Backend::TextureRef src, Effekseer::Backend::TextureRef dest)
{
using namespace Effekseer;
using namespace EffekseerRendererGL;
auto& state = renderer_->GetRenderState()->Push();
state.AlphaBlend = AlphaBlendType::Opacity;
state.DepthWrite = false;
state.DepthTest = false;
state.CullingType = CullingType::Double;
renderer_->GetRenderState()->Update(false);
renderer_->SetRenderMode(RenderMode::Normal);
const std::vector<Effekseer::Backend::TextureRef> textures{src};
if (algorithm == Algorithm::Off)
{
blitter.Blit(shaderCopy.get(), vaoCopy.get(), textures, nullptr, 0, dest);
}
else if (algorithm == Algorithm::Reinhard)
{
const float constantData[4] = {exposure, 16.0f * 16.0f};
blitter.Blit(shaderReinhard.get(), vaoReinhard.get(), textures, constantData, sizeof(constantData), dest);
}
GLExt::glActiveTexture(GL_TEXTURE0);
renderer_->GetRenderState()->Update(true);
renderer_->GetRenderState()->Pop();
GLCheckError();
}
LinearToSRGBEffectGL::LinearToSRGBEffectGL(Graphics* graphics, const EffekseerRenderer::RendererRef& renderer)
: LinearToSRGBEffect(graphics)
, blitter(graphics, renderer)
, renderer_(EffekseerRendererGL::RendererImplementedRef::FromPinned(renderer.Get()))
{
using namespace EffekseerRendererGL;
auto vl = renderer->GetGraphicsDevice()->CreateVertexLayout(vlElem, 2).DownCast<EffekseerRendererGL::Backend::VertexLayout>();
auto uniformLayoutSingleImage = Effekseer::MakeRefPtr<Effekseer::Backend::UniformLayout>(Effekseer::CustomVector<Effekseer::CustomString<char>>{"u_Texture0"}, Effekseer::CustomVector<Effekseer::Backend::UniformLayoutElement>{});
EffekseerRendererGL::ShaderCodeView basicVS(g_basic_vs_src);
EffekseerRendererGL::ShaderCodeView linierToSrgbPS(g_linear_to_srgb_fs_src);
// Copy shader
shader_.reset(Shader::CreateWithHeader(renderer_->GetInternalGraphicsDevice(), basicVS, linierToSrgbPS, uniformLayoutSingleImage, "LinearToSRGB"));
shader_->SetVertexLayout(vl);
// Setup VAOs
vao_ = blitter.CreateVAO(renderer->GetGraphicsDevice(), shader_.get());
}
LinearToSRGBEffectGL::~LinearToSRGBEffectGL()
{
}
void LinearToSRGBEffectGL::Render(Effekseer::Backend::TextureRef src, Effekseer::Backend::TextureRef dest)
{
using namespace Effekseer;
using namespace EffekseerRendererGL;
auto& state = renderer_->GetRenderState()->Push();
state.AlphaBlend = AlphaBlendType::Opacity;
state.DepthWrite = false;
state.DepthTest = false;
state.CullingType = CullingType::Double;
renderer_->GetRenderState()->Update(false);
renderer_->SetRenderMode(RenderMode::Normal);
const std::vector<Effekseer::Backend::TextureRef> textures{src};
blitter.Blit(shader_.get(), vao_.get(), textures, nullptr, 0, dest);
GLExt::glActiveTexture(GL_TEXTURE0);
renderer_->GetRenderState()->Update(true);
renderer_->GetRenderState()->Pop();
GLCheckError();
}
} // namespace efk
| 35.481149 | 266 | 0.748874 | [
"render",
"vector"
] |
4f2de78e3eeac860bddf4f448b1051395a1f341c | 90,166 | cpp | C++ | moveit_core/robot_state/src/robot_state.cpp | limcatrina/moveit | f94fcc33882aaac20f7e3c07e5df88a4a77e6e8a | [
"BSD-3-Clause"
] | null | null | null | moveit_core/robot_state/src/robot_state.cpp | limcatrina/moveit | f94fcc33882aaac20f7e3c07e5df88a4a77e6e8a | [
"BSD-3-Clause"
] | null | null | null | moveit_core/robot_state/src/robot_state.cpp | limcatrina/moveit | f94fcc33882aaac20f7e3c07e5df88a4a77e6e8a | [
"BSD-3-Clause"
] | null | null | null | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Ioan A. Sucan
* Copyright (c) 2013, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan, Sachin Chitta, Acorn Pooley, Mario Prats, Dave Coleman */
#include <moveit/robot_state/robot_state.h>
#include <moveit/transforms/transforms.h>
#include <geometric_shapes/shape_operations.h>
#include <tf2_eigen/tf2_eigen.h>
#include <moveit/backtrace/backtrace.h>
#include <moveit/profiler/profiler.h>
#include <boost/bind.hpp>
#include <moveit/robot_model/aabb.h>
namespace moveit
{
namespace core
{
/** \brief It is recommended that there are at least 10 steps per trajectory
* for testing jump thresholds with computeCartesianPath. With less than 10 steps
* it is difficult to choose a jump_threshold parameter that effectively separates
* valid paths from paths with large joint space jumps. */
static const std::size_t MIN_STEPS_FOR_JUMP_THRESH = 10;
const std::string LOGNAME = "robot_state";
RobotState::RobotState(const RobotModelConstPtr& robot_model)
: robot_model_(robot_model)
, has_velocity_(false)
, has_acceleration_(false)
, has_effort_(false)
, dirty_link_transforms_(robot_model_->getRootJoint())
, dirty_collision_body_transforms_(nullptr)
, rng_(nullptr)
{
allocMemory();
initTransforms();
}
RobotState::RobotState(const RobotState& other) : rng_(nullptr)
{
robot_model_ = other.robot_model_;
allocMemory();
copyFrom(other);
}
RobotState::~RobotState()
{
clearAttachedBodies();
free(memory_);
if (rng_)
delete rng_;
}
void RobotState::allocMemory()
{
// memory for the dirty joint transforms
const int nr_doubles_for_dirty_joint_transforms =
1 + robot_model_->getJointModelCount() / (sizeof(double) / sizeof(unsigned char));
const size_t bytes =
sizeof(Eigen::Isometry3d) * (robot_model_->getJointModelCount() + robot_model_->getLinkModelCount() +
robot_model_->getLinkGeometryCount()) +
sizeof(double) * (robot_model_->getVariableCount() * 3 + nr_doubles_for_dirty_joint_transforms) + 15;
memory_ = malloc(bytes);
// make the memory for transforms align at 16 bytes
variable_joint_transforms_ = reinterpret_cast<Eigen::Isometry3d*>(((uintptr_t)memory_ + 15) & ~(uintptr_t)0x0F);
global_link_transforms_ = variable_joint_transforms_ + robot_model_->getJointModelCount();
global_collision_body_transforms_ = global_link_transforms_ + robot_model_->getLinkModelCount();
dirty_joint_transforms_ =
reinterpret_cast<unsigned char*>(global_collision_body_transforms_ + robot_model_->getLinkGeometryCount());
position_ = reinterpret_cast<double*>(dirty_joint_transforms_) + nr_doubles_for_dirty_joint_transforms;
velocity_ = position_ + robot_model_->getVariableCount();
// acceleration and effort share the memory (not both can be specified)
effort_ = acceleration_ = velocity_ + robot_model_->getVariableCount();
}
void RobotState::initTransforms()
{
// mark all transforms as dirty
const int nr_doubles_for_dirty_joint_transforms =
1 + robot_model_->getJointModelCount() / (sizeof(double) / sizeof(unsigned char));
memset(dirty_joint_transforms_, 1, sizeof(double) * nr_doubles_for_dirty_joint_transforms);
// initialize last row of transformation matrices, which will not be modified by transform updates anymore
for (size_t i = 0, end = robot_model_->getJointModelCount() + robot_model_->getLinkModelCount() +
robot_model_->getLinkGeometryCount();
i != end; ++i)
variable_joint_transforms_[i].makeAffine();
}
RobotState& RobotState::operator=(const RobotState& other)
{
if (this != &other)
copyFrom(other);
return *this;
}
void RobotState::copyFrom(const RobotState& other)
{
has_velocity_ = other.has_velocity_;
has_acceleration_ = other.has_acceleration_;
has_effort_ = other.has_effort_;
dirty_collision_body_transforms_ = other.dirty_collision_body_transforms_;
dirty_link_transforms_ = other.dirty_link_transforms_;
if (dirty_link_transforms_ == robot_model_->getRootJoint())
{
// everything is dirty; no point in copying transforms; copy positions, potentially velocity & acceleration
memcpy(position_, other.position_, robot_model_->getVariableCount() * sizeof(double) *
(1 + ((has_velocity_ || has_acceleration_ || has_effort_) ? 1 : 0) +
((has_acceleration_ || has_effort_) ? 1 : 0)));
// and just initialize transforms
initTransforms();
}
else
{
// copy all the memory; maybe avoid copying velocity and acceleration if possible
const int nr_doubles_for_dirty_joint_transforms =
1 + robot_model_->getJointModelCount() / (sizeof(double) / sizeof(unsigned char));
const size_t bytes =
sizeof(Eigen::Isometry3d) * (robot_model_->getJointModelCount() + robot_model_->getLinkModelCount() +
robot_model_->getLinkGeometryCount()) +
sizeof(double) *
(robot_model_->getVariableCount() * (1 + ((has_velocity_ || has_acceleration_ || has_effort_) ? 1 : 0) +
((has_acceleration_ || has_effort_) ? 1 : 0)) +
nr_doubles_for_dirty_joint_transforms);
memcpy(variable_joint_transforms_, other.variable_joint_transforms_, bytes);
}
// copy attached bodies
clearAttachedBodies();
for (std::map<std::string, AttachedBody*>::const_iterator it = other.attached_body_map_.begin();
it != other.attached_body_map_.end(); ++it)
attachBody(it->second->getName(), it->second->getShapes(), it->second->getFixedTransforms(),
it->second->getTouchLinks(), it->second->getAttachedLinkName(), it->second->getDetachPosture());
}
bool RobotState::checkJointTransforms(const JointModel* joint) const
{
if (dirtyJointTransform(joint))
{
ROS_WARN_NAMED(LOGNAME, "Returning dirty joint transforms for joint '%s'", joint->getName().c_str());
return false;
}
return true;
}
bool RobotState::checkLinkTransforms() const
{
if (dirtyLinkTransforms())
{
ROS_WARN_NAMED(LOGNAME, "Returning dirty link transforms");
return false;
}
return true;
}
bool RobotState::checkCollisionTransforms() const
{
if (dirtyCollisionBodyTransforms())
{
ROS_WARN_NAMED(LOGNAME, "Returning dirty collision body transforms");
return false;
}
return true;
}
void RobotState::markVelocity()
{
if (!has_velocity_)
{
has_velocity_ = true;
memset(velocity_, 0, sizeof(double) * robot_model_->getVariableCount());
}
}
void RobotState::markAcceleration()
{
if (!has_acceleration_)
{
has_acceleration_ = true;
has_effort_ = false;
memset(acceleration_, 0, sizeof(double) * robot_model_->getVariableCount());
}
}
void RobotState::markEffort()
{
if (!has_effort_)
{
has_acceleration_ = false;
has_effort_ = true;
memset(effort_, 0, sizeof(double) * robot_model_->getVariableCount());
}
}
void RobotState::setToRandomPositions()
{
random_numbers::RandomNumberGenerator& rng = getRandomNumberGenerator();
robot_model_->getVariableRandomPositions(rng, position_);
memset(dirty_joint_transforms_, 1, robot_model_->getJointModelCount() * sizeof(unsigned char));
dirty_link_transforms_ = robot_model_->getRootJoint();
// mimic values are correctly set in RobotModel
}
void RobotState::setToRandomPositions(const JointModelGroup* group)
{
// we do not make calls to RobotModel for random number generation because mimic joints
// could trigger updates outside the state of the group itself
random_numbers::RandomNumberGenerator& rng = getRandomNumberGenerator();
setToRandomPositions(group, rng);
}
void RobotState::setToRandomPositions(const JointModelGroup* group, random_numbers::RandomNumberGenerator& rng)
{
const std::vector<const JointModel*>& joints = group->getActiveJointModels();
for (std::size_t i = 0; i < joints.size(); ++i)
joints[i]->getVariableRandomPositions(rng, position_ + joints[i]->getFirstVariableIndex());
updateMimicJoints(group);
}
void RobotState::setToRandomPositionsNearBy(const JointModelGroup* group, const RobotState& near,
const std::vector<double>& distances)
{
// we do not make calls to RobotModel for random number generation because mimic joints
// could trigger updates outside the state of the group itself
random_numbers::RandomNumberGenerator& rng = getRandomNumberGenerator();
const std::vector<const JointModel*>& joints = group->getActiveJointModels();
assert(distances.size() == joints.size());
for (std::size_t i = 0; i < joints.size(); ++i)
{
const int idx = joints[i]->getFirstVariableIndex();
joints[i]->getVariableRandomPositionsNearBy(rng, position_ + joints[i]->getFirstVariableIndex(),
near.position_ + idx, distances[i]);
}
updateMimicJoints(group);
}
void RobotState::setToRandomPositionsNearBy(const JointModelGroup* group, const RobotState& near, double distance)
{
// we do not make calls to RobotModel for random number generation because mimic joints
// could trigger updates outside the state of the group itself
random_numbers::RandomNumberGenerator& rng = getRandomNumberGenerator();
const std::vector<const JointModel*>& joints = group->getActiveJointModels();
for (std::size_t i = 0; i < joints.size(); ++i)
{
const int idx = joints[i]->getFirstVariableIndex();
joints[i]->getVariableRandomPositionsNearBy(rng, position_ + joints[i]->getFirstVariableIndex(),
near.position_ + idx, distance);
}
updateMimicJoints(group);
}
bool RobotState::setToDefaultValues(const JointModelGroup* group, const std::string& name)
{
std::map<std::string, double> m;
bool r = group->getVariableDefaultPositions(name, m); // mimic values are updated
setVariablePositions(m);
return r;
}
void RobotState::setToDefaultValues()
{
robot_model_->getVariableDefaultPositions(position_); // mimic values are updated
// set velocity & acceleration to 0
memset(velocity_, 0, sizeof(double) * 2 * robot_model_->getVariableCount());
memset(dirty_joint_transforms_, 1, robot_model_->getJointModelCount() * sizeof(unsigned char));
dirty_link_transforms_ = robot_model_->getRootJoint();
}
void RobotState::setVariablePositions(const double* position)
{
// assume everything is in order in terms of array lengths (for efficiency reasons)
memcpy(position_, position, robot_model_->getVariableCount() * sizeof(double));
// the full state includes mimic joint values, so no need to update mimic here
// Since all joint values have potentially changed, we will need to recompute all transforms
memset(dirty_joint_transforms_, 1, robot_model_->getJointModelCount() * sizeof(unsigned char));
dirty_link_transforms_ = robot_model_->getRootJoint();
}
void RobotState::setVariablePositions(const std::map<std::string, double>& variable_map)
{
for (std::map<std::string, double>::const_iterator it = variable_map.begin(), end = variable_map.end(); it != end;
++it)
{
const int index = robot_model_->getVariableIndex(it->first);
position_[index] = it->second;
const JointModel* jm = robot_model_->getJointOfVariable(index);
markDirtyJointTransforms(jm);
updateMimicJoint(jm);
}
}
void RobotState::getMissingKeys(const std::map<std::string, double>& variable_map,
std::vector<std::string>& missing_variables) const
{
missing_variables.clear();
const std::vector<std::string>& nm = robot_model_->getVariableNames();
for (std::size_t i = 0; i < nm.size(); ++i)
if (variable_map.find(nm[i]) == variable_map.end())
if (robot_model_->getJointOfVariable(nm[i])->getMimic() == nullptr)
missing_variables.push_back(nm[i]);
}
void RobotState::setVariablePositions(const std::map<std::string, double>& variable_map,
std::vector<std::string>& missing_variables)
{
setVariablePositions(variable_map);
getMissingKeys(variable_map, missing_variables);
}
void RobotState::setVariablePositions(const std::vector<std::string>& variable_names,
const std::vector<double>& variable_position)
{
for (std::size_t i = 0; i < variable_names.size(); ++i)
{
const int index = robot_model_->getVariableIndex(variable_names[i]);
position_[index] = variable_position[i];
const JointModel* jm = robot_model_->getJointOfVariable(index);
markDirtyJointTransforms(jm);
updateMimicJoint(jm);
}
}
void RobotState::setVariableVelocities(const std::map<std::string, double>& variable_map)
{
markVelocity();
for (std::map<std::string, double>::const_iterator it = variable_map.begin(), end = variable_map.end(); it != end;
++it)
velocity_[robot_model_->getVariableIndex(it->first)] = it->second;
}
void RobotState::setVariableVelocities(const std::map<std::string, double>& variable_map,
std::vector<std::string>& missing_variables)
{
setVariableVelocities(variable_map);
getMissingKeys(variable_map, missing_variables);
}
void RobotState::setVariableVelocities(const std::vector<std::string>& variable_names,
const std::vector<double>& variable_velocity)
{
markVelocity();
assert(variable_names.size() == variable_velocity.size());
for (std::size_t i = 0; i < variable_names.size(); ++i)
velocity_[robot_model_->getVariableIndex(variable_names[i])] = variable_velocity[i];
}
void RobotState::setVariableAccelerations(const std::map<std::string, double>& variable_map)
{
markAcceleration();
for (std::map<std::string, double>::const_iterator it = variable_map.begin(), end = variable_map.end(); it != end;
++it)
acceleration_[robot_model_->getVariableIndex(it->first)] = it->second;
}
void RobotState::setVariableAccelerations(const std::map<std::string, double>& variable_map,
std::vector<std::string>& missing_variables)
{
setVariableAccelerations(variable_map);
getMissingKeys(variable_map, missing_variables);
}
void RobotState::setVariableAccelerations(const std::vector<std::string>& variable_names,
const std::vector<double>& variable_acceleration)
{
markAcceleration();
assert(variable_names.size() == variable_acceleration.size());
for (std::size_t i = 0; i < variable_names.size(); ++i)
acceleration_[robot_model_->getVariableIndex(variable_names[i])] = variable_acceleration[i];
}
void RobotState::setVariableEffort(const std::map<std::string, double>& variable_map)
{
markEffort();
for (std::map<std::string, double>::const_iterator it = variable_map.begin(), end = variable_map.end(); it != end;
++it)
acceleration_[robot_model_->getVariableIndex(it->first)] = it->second;
}
void RobotState::setVariableEffort(const std::map<std::string, double>& variable_map,
std::vector<std::string>& missing_variables)
{
setVariableEffort(variable_map);
getMissingKeys(variable_map, missing_variables);
}
void RobotState::setVariableEffort(const std::vector<std::string>& variable_names,
const std::vector<double>& variable_effort)
{
markEffort();
assert(variable_names.size() == variable_effort.size());
for (std::size_t i = 0; i < variable_names.size(); ++i)
effort_[robot_model_->getVariableIndex(variable_names[i])] = variable_effort[i];
}
void RobotState::invertVelocity()
{
if (has_velocity_)
{
for (size_t i = 0; i < robot_model_->getVariableCount(); ++i)
velocity_[i] *= -1;
}
}
void RobotState::setJointEfforts(const JointModel* joint, const double* effort)
{
if (has_acceleration_)
{
ROS_ERROR_NAMED(LOGNAME, "Unable to set joint efforts because array is being used for accelerations");
return;
}
has_effort_ = true;
memcpy(effort_ + joint->getFirstVariableIndex(), effort, joint->getVariableCount() * sizeof(double));
}
void RobotState::setJointGroupPositions(const JointModelGroup* group, const double* gstate)
{
const std::vector<int>& il = group->getVariableIndexList();
if (group->isContiguousWithinState())
memcpy(position_ + il[0], gstate, group->getVariableCount() * sizeof(double));
else
{
for (std::size_t i = 0; i < il.size(); ++i)
position_[il[i]] = gstate[i];
}
updateMimicJoints(group);
}
void RobotState::setJointGroupPositions(const JointModelGroup* group, const Eigen::VectorXd& values)
{
const std::vector<int>& il = group->getVariableIndexList();
for (std::size_t i = 0; i < il.size(); ++i)
position_[il[i]] = values(i);
updateMimicJoints(group);
}
void RobotState::copyJointGroupPositions(const JointModelGroup* group, double* gstate) const
{
const std::vector<int>& il = group->getVariableIndexList();
if (group->isContiguousWithinState())
memcpy(gstate, position_ + il[0], group->getVariableCount() * sizeof(double));
else
for (std::size_t i = 0; i < il.size(); ++i)
gstate[i] = position_[il[i]];
}
void RobotState::copyJointGroupPositions(const JointModelGroup* group, Eigen::VectorXd& values) const
{
const std::vector<int>& il = group->getVariableIndexList();
values.resize(il.size());
for (std::size_t i = 0; i < il.size(); ++i)
values(i) = position_[il[i]];
}
void RobotState::setJointGroupVelocities(const JointModelGroup* group, const double* gstate)
{
markVelocity();
const std::vector<int>& il = group->getVariableIndexList();
if (group->isContiguousWithinState())
memcpy(velocity_ + il[0], gstate, group->getVariableCount() * sizeof(double));
else
{
for (std::size_t i = 0; i < il.size(); ++i)
velocity_[il[i]] = gstate[i];
}
}
void RobotState::setJointGroupVelocities(const JointModelGroup* group, const Eigen::VectorXd& values)
{
markVelocity();
const std::vector<int>& il = group->getVariableIndexList();
for (std::size_t i = 0; i < il.size(); ++i)
velocity_[il[i]] = values(i);
}
void RobotState::copyJointGroupVelocities(const JointModelGroup* group, double* gstate) const
{
const std::vector<int>& il = group->getVariableIndexList();
if (group->isContiguousWithinState())
memcpy(gstate, velocity_ + il[0], group->getVariableCount() * sizeof(double));
else
for (std::size_t i = 0; i < il.size(); ++i)
gstate[i] = velocity_[il[i]];
}
void RobotState::copyJointGroupVelocities(const JointModelGroup* group, Eigen::VectorXd& values) const
{
const std::vector<int>& il = group->getVariableIndexList();
values.resize(il.size());
for (std::size_t i = 0; i < il.size(); ++i)
values(i) = velocity_[il[i]];
}
void RobotState::setJointGroupAccelerations(const JointModelGroup* group, const double* gstate)
{
markAcceleration();
const std::vector<int>& il = group->getVariableIndexList();
if (group->isContiguousWithinState())
memcpy(acceleration_ + il[0], gstate, group->getVariableCount() * sizeof(double));
else
{
for (std::size_t i = 0; i < il.size(); ++i)
acceleration_[il[i]] = gstate[i];
}
}
void RobotState::setJointGroupAccelerations(const JointModelGroup* group, const Eigen::VectorXd& values)
{
markAcceleration();
const std::vector<int>& il = group->getVariableIndexList();
for (std::size_t i = 0; i < il.size(); ++i)
acceleration_[il[i]] = values(i);
}
void RobotState::copyJointGroupAccelerations(const JointModelGroup* group, double* gstate) const
{
const std::vector<int>& il = group->getVariableIndexList();
if (group->isContiguousWithinState())
memcpy(gstate, acceleration_ + il[0], group->getVariableCount() * sizeof(double));
else
for (std::size_t i = 0; i < il.size(); ++i)
gstate[i] = acceleration_[il[i]];
}
void RobotState::copyJointGroupAccelerations(const JointModelGroup* group, Eigen::VectorXd& values) const
{
const std::vector<int>& il = group->getVariableIndexList();
values.resize(il.size());
for (std::size_t i = 0; i < il.size(); ++i)
values(i) = acceleration_[il[i]];
}
void RobotState::update(bool force)
{
// make sure we do everything from scratch if needed
if (force)
{
memset(dirty_joint_transforms_, 1, robot_model_->getJointModelCount() * sizeof(unsigned char));
dirty_link_transforms_ = robot_model_->getRootJoint();
}
// this actually triggers all needed updates
updateCollisionBodyTransforms();
}
void RobotState::updateCollisionBodyTransforms()
{
if (dirty_link_transforms_ != nullptr)
updateLinkTransforms();
if (dirty_collision_body_transforms_ != nullptr)
{
const std::vector<const LinkModel*>& links = dirty_collision_body_transforms_->getDescendantLinkModels();
dirty_collision_body_transforms_ = nullptr;
for (const LinkModel* link : links)
{
const EigenSTL::vector_Isometry3d& ot = link->getCollisionOriginTransforms();
const std::vector<int>& ot_id = link->areCollisionOriginTransformsIdentity();
const int index_co = link->getFirstCollisionBodyTransformIndex();
const int index_l = link->getLinkIndex();
for (std::size_t j = 0, end = ot.size(); j != end; ++j)
{
if (ot_id[j])
global_collision_body_transforms_[index_co + j] = global_link_transforms_[index_l];
else
global_collision_body_transforms_[index_co + j].affine().noalias() =
global_link_transforms_[index_l].affine() * ot[j].matrix();
}
}
}
}
void RobotState::updateLinkTransforms()
{
if (dirty_link_transforms_ != nullptr)
{
updateLinkTransformsInternal(dirty_link_transforms_);
if (dirty_collision_body_transforms_)
dirty_collision_body_transforms_ =
robot_model_->getCommonRoot(dirty_collision_body_transforms_, dirty_link_transforms_);
else
dirty_collision_body_transforms_ = dirty_link_transforms_;
dirty_link_transforms_ = nullptr;
}
}
void RobotState::updateLinkTransformsInternal(const JointModel* start)
{
for (const LinkModel* link : start->getDescendantLinkModels())
{
int idx_link = link->getLinkIndex();
const LinkModel* parent = link->getParentLinkModel();
if (parent) // root JointModel will not have a parent
{
int idx_parent = parent->getLinkIndex();
if (link->parentJointIsFixed())
global_link_transforms_[idx_link].affine().noalias() =
global_link_transforms_[idx_parent].affine() * link->getJointOriginTransform().matrix();
else
{
if (link->jointOriginTransformIsIdentity())
global_link_transforms_[idx_link].affine().noalias() =
global_link_transforms_[idx_parent].affine() * getJointTransform(link->getParentJointModel()).matrix();
else
global_link_transforms_[idx_link].affine().noalias() =
global_link_transforms_[idx_parent].affine() * link->getJointOriginTransform().matrix() *
getJointTransform(link->getParentJointModel()).matrix();
}
}
else
{
if (link->jointOriginTransformIsIdentity())
global_link_transforms_[idx_link] = getJointTransform(link->getParentJointModel());
else
global_link_transforms_[idx_link].affine().noalias() =
link->getJointOriginTransform().affine() * getJointTransform(link->getParentJointModel()).matrix();
}
}
// update attached bodies tf; these are usually very few, so we update them all
for (std::map<std::string, AttachedBody*>::const_iterator it = attached_body_map_.begin();
it != attached_body_map_.end(); ++it)
it->second->computeTransform(global_link_transforms_[it->second->getAttachedLink()->getLinkIndex()]);
}
void RobotState::updateStateWithLinkAt(const LinkModel* link, const Eigen::Isometry3d& transform, bool backward)
{
updateLinkTransforms(); // no link transforms must be dirty, otherwise the transform we set will be overwritten
// update the fact that collision body transforms are out of date
if (dirty_collision_body_transforms_)
dirty_collision_body_transforms_ =
robot_model_->getCommonRoot(dirty_collision_body_transforms_, link->getParentJointModel());
else
dirty_collision_body_transforms_ = link->getParentJointModel();
global_link_transforms_[link->getLinkIndex()] = transform;
// update link transforms for descendant links only (leaving the transform for the current link untouched)
const std::vector<const JointModel*>& cj = link->getChildJointModels();
for (std::size_t i = 0; i < cj.size(); ++i)
updateLinkTransformsInternal(cj[i]);
// if we also need to go backward
if (backward)
{
const LinkModel* parent_link = link;
const LinkModel* child_link;
while (parent_link->getParentJointModel()->getParentLinkModel())
{
child_link = parent_link;
parent_link = parent_link->getParentJointModel()->getParentLinkModel();
// update the transform of the parent
global_link_transforms_[parent_link->getLinkIndex()] =
global_link_transforms_[child_link->getLinkIndex()] *
(child_link->getJointOriginTransform() *
variable_joint_transforms_[child_link->getParentJointModel()->getJointIndex()])
.inverse();
// update link transforms for descendant links only (leaving the transform for the current link untouched)
// with the exception of the child link we are coming backwards from
const std::vector<const JointModel*>& cj = parent_link->getChildJointModels();
for (std::size_t i = 0; i < cj.size(); ++i)
if (cj[i] != child_link->getParentJointModel())
updateLinkTransformsInternal(cj[i]);
}
// all collision body transforms are invalid now
dirty_collision_body_transforms_ = parent_link->getParentJointModel();
}
// update attached bodies tf; these are usually very few, so we update them all
for (std::map<std::string, AttachedBody*>::const_iterator it = attached_body_map_.begin();
it != attached_body_map_.end(); ++it)
it->second->computeTransform(global_link_transforms_[it->second->getAttachedLink()->getLinkIndex()]);
}
bool RobotState::satisfiesBounds(double margin) const
{
const std::vector<const JointModel*>& jm = robot_model_->getActiveJointModels();
for (std::size_t i = 0; i < jm.size(); ++i)
if (!satisfiesBounds(jm[i], margin))
return false;
return true;
}
bool RobotState::satisfiesBounds(const JointModelGroup* group, double margin) const
{
const std::vector<const JointModel*>& jm = group->getActiveJointModels();
for (std::size_t i = 0; i < jm.size(); ++i)
if (!satisfiesBounds(jm[i], margin))
return false;
return true;
}
void RobotState::enforceBounds()
{
const std::vector<const JointModel*>& jm = robot_model_->getActiveJointModels();
for (std::size_t i = 0; i < jm.size(); ++i)
enforceBounds(jm[i]);
}
void RobotState::enforceBounds(const JointModelGroup* joint_group)
{
const std::vector<const JointModel*>& jm = joint_group->getActiveJointModels();
for (std::size_t i = 0; i < jm.size(); ++i)
enforceBounds(jm[i]);
}
void RobotState::harmonizePositions()
{
for (const JointModel* jm : robot_model_->getActiveJointModels())
harmonizePosition(jm);
}
void RobotState::harmonizePositions(const JointModelGroup* joint_group)
{
for (const JointModel* jm : joint_group->getActiveJointModels())
harmonizePosition(jm);
}
std::pair<double, const JointModel*> RobotState::getMinDistanceToPositionBounds() const
{
return getMinDistanceToPositionBounds(robot_model_->getActiveJointModels());
}
std::pair<double, const JointModel*> RobotState::getMinDistanceToPositionBounds(const JointModelGroup* group) const
{
return getMinDistanceToPositionBounds(group->getActiveJointModels());
}
std::pair<double, const JointModel*>
RobotState::getMinDistanceToPositionBounds(const std::vector<const JointModel*>& joints) const
{
double distance = std::numeric_limits<double>::max();
const JointModel* index = nullptr;
for (std::size_t i = 0; i < joints.size(); ++i)
{
if (joints[i]->getType() == JointModel::PLANAR || joints[i]->getType() == JointModel::FLOATING)
continue;
if (joints[i]->getType() == JointModel::REVOLUTE)
if (static_cast<const RevoluteJointModel*>(joints[i])->isContinuous())
continue;
const double* joint_values = getJointPositions(joints[i]);
const JointModel::Bounds& bounds = joints[i]->getVariableBounds();
std::vector<double> lower_bounds(bounds.size()), upper_bounds(bounds.size());
for (std::size_t j = 0; j < bounds.size(); ++j)
{
lower_bounds[j] = bounds[j].min_position_;
upper_bounds[j] = bounds[j].max_position_;
}
double new_distance = joints[i]->distance(joint_values, &lower_bounds[0]);
if (new_distance < distance)
{
index = joints[i];
distance = new_distance;
}
new_distance = joints[i]->distance(joint_values, &upper_bounds[0]);
if (new_distance < distance)
{
index = joints[i];
distance = new_distance;
}
}
return std::make_pair(distance, index);
}
bool RobotState::isValidVelocityMove(const RobotState& other, const JointModelGroup* group, double dt) const
{
const std::vector<const JointModel*>& jm = group->getActiveJointModels();
for (std::size_t joint_id = 0; joint_id < jm.size(); ++joint_id)
{
const int idx = jm[joint_id]->getFirstVariableIndex();
const std::vector<VariableBounds>& bounds = jm[joint_id]->getVariableBounds();
// Check velocity for each joint variable
for (std::size_t var_id = 0; var_id < jm[joint_id]->getVariableCount(); ++var_id)
{
const double dtheta = std::abs(*(position_ + idx + var_id) - *(other.getVariablePositions() + idx + var_id));
if (dtheta > dt * bounds[var_id].max_velocity_)
return false;
}
}
return true;
}
double RobotState::distance(const RobotState& other, const JointModelGroup* joint_group) const
{
double d = 0.0;
const std::vector<const JointModel*>& jm = joint_group->getActiveJointModels();
for (std::size_t i = 0; i < jm.size(); ++i)
{
const int idx = jm[i]->getFirstVariableIndex();
d += jm[i]->getDistanceFactor() * jm[i]->distance(position_ + idx, other.position_ + idx);
}
return d;
}
void RobotState::interpolate(const RobotState& to, double t, RobotState& state) const
{
robot_model_->interpolate(getVariablePositions(), to.getVariablePositions(), t, state.getVariablePositions());
memset(state.dirty_joint_transforms_, 1, state.robot_model_->getJointModelCount() * sizeof(unsigned char));
state.dirty_link_transforms_ = state.robot_model_->getRootJoint();
}
void RobotState::interpolate(const RobotState& to, double t, RobotState& state,
const JointModelGroup* joint_group) const
{
const std::vector<const JointModel*>& jm = joint_group->getActiveJointModels();
for (std::size_t i = 0; i < jm.size(); ++i)
{
const int idx = jm[i]->getFirstVariableIndex();
jm[i]->interpolate(position_ + idx, to.position_ + idx, t, state.position_ + idx);
}
state.updateMimicJoints(joint_group);
}
void RobotState::setAttachedBodyUpdateCallback(const AttachedBodyCallback& callback)
{
attached_body_update_callback_ = callback;
}
bool RobotState::hasAttachedBody(const std::string& id) const
{
return attached_body_map_.find(id) != attached_body_map_.end();
}
const AttachedBody* RobotState::getAttachedBody(const std::string& id) const
{
std::map<std::string, AttachedBody*>::const_iterator it = attached_body_map_.find(id);
if (it == attached_body_map_.end())
{
ROS_ERROR_NAMED(LOGNAME, "Attached body '%s' not found", id.c_str());
return nullptr;
}
else
return it->second;
}
void RobotState::attachBody(AttachedBody* attached_body)
{
attached_body_map_[attached_body->getName()] = attached_body;
attached_body->computeTransform(getGlobalLinkTransform(attached_body->getAttachedLink()));
if (attached_body_update_callback_)
attached_body_update_callback_(attached_body, true);
}
void RobotState::attachBody(const std::string& id, const std::vector<shapes::ShapeConstPtr>& shapes,
const EigenSTL::vector_Isometry3d& attach_trans, const std::set<std::string>& touch_links,
const std::string& link, const trajectory_msgs::JointTrajectory& detach_posture)
{
const LinkModel* l = robot_model_->getLinkModel(link);
AttachedBody* ab = new AttachedBody(l, id, shapes, attach_trans, touch_links, detach_posture);
attached_body_map_[id] = ab;
ab->computeTransform(getGlobalLinkTransform(l));
if (attached_body_update_callback_)
attached_body_update_callback_(ab, true);
}
void RobotState::getAttachedBodies(std::vector<const AttachedBody*>& attached_bodies) const
{
attached_bodies.clear();
attached_bodies.reserve(attached_body_map_.size());
for (std::map<std::string, AttachedBody*>::const_iterator it = attached_body_map_.begin();
it != attached_body_map_.end(); ++it)
attached_bodies.push_back(it->second);
}
void RobotState::getAttachedBodies(std::vector<const AttachedBody*>& attached_bodies,
const JointModelGroup* group) const
{
attached_bodies.clear();
for (std::map<std::string, AttachedBody*>::const_iterator it = attached_body_map_.begin();
it != attached_body_map_.end(); ++it)
if (group->hasLinkModel(it->second->getAttachedLinkName()))
attached_bodies.push_back(it->second);
}
void RobotState::getAttachedBodies(std::vector<const AttachedBody*>& attached_bodies, const LinkModel* lm) const
{
attached_bodies.clear();
for (std::map<std::string, AttachedBody*>::const_iterator it = attached_body_map_.begin();
it != attached_body_map_.end(); ++it)
if (it->second->getAttachedLink() == lm)
attached_bodies.push_back(it->second);
}
void RobotState::clearAttachedBodies()
{
for (std::map<std::string, AttachedBody*>::const_iterator it = attached_body_map_.begin();
it != attached_body_map_.end(); ++it)
{
if (attached_body_update_callback_)
attached_body_update_callback_(it->second, false);
delete it->second;
}
attached_body_map_.clear();
}
void RobotState::clearAttachedBodies(const LinkModel* link)
{
std::map<std::string, AttachedBody*>::iterator it = attached_body_map_.begin();
while (it != attached_body_map_.end())
{
if (it->second->getAttachedLink() != link)
{
++it;
continue;
}
if (attached_body_update_callback_)
attached_body_update_callback_(it->second, false);
delete it->second;
std::map<std::string, AttachedBody*>::iterator del = it++;
attached_body_map_.erase(del);
}
}
void RobotState::clearAttachedBodies(const JointModelGroup* group)
{
std::map<std::string, AttachedBody*>::iterator it = attached_body_map_.begin();
while (it != attached_body_map_.end())
{
if (!group->hasLinkModel(it->second->getAttachedLinkName()))
{
++it;
continue;
}
if (attached_body_update_callback_)
attached_body_update_callback_(it->second, false);
delete it->second;
std::map<std::string, AttachedBody*>::iterator del = it++;
attached_body_map_.erase(del);
}
}
bool RobotState::clearAttachedBody(const std::string& id)
{
std::map<std::string, AttachedBody*>::iterator it = attached_body_map_.find(id);
if (it != attached_body_map_.end())
{
if (attached_body_update_callback_)
attached_body_update_callback_(it->second, false);
delete it->second;
attached_body_map_.erase(it);
return true;
}
else
return false;
}
const Eigen::Isometry3d& RobotState::getFrameTransform(const std::string& id)
{
updateLinkTransforms();
return static_cast<const RobotState*>(this)->getFrameTransform(id);
}
const Eigen::Isometry3d& RobotState::getFrameTransform(const std::string& id) const
{
if (!id.empty() && id[0] == '/')
return getFrameTransform(id.substr(1));
BOOST_VERIFY(checkLinkTransforms());
static const Eigen::Isometry3d IDENTITY_TRANSFORM = Eigen::Isometry3d::Identity();
if (id == robot_model_->getModelFrame())
return IDENTITY_TRANSFORM;
if (robot_model_->hasLinkModel(id))
{
const LinkModel* lm = robot_model_->getLinkModel(id);
return global_link_transforms_[lm->getLinkIndex()];
}
std::map<std::string, AttachedBody*>::const_iterator jt = attached_body_map_.find(id);
if (jt == attached_body_map_.end())
{
ROS_ERROR_NAMED(LOGNAME, "Transform from frame '%s' to frame '%s' is not known "
"('%s' should be a link name or an attached body id).",
id.c_str(), robot_model_->getModelFrame().c_str(), id.c_str());
return IDENTITY_TRANSFORM;
}
const EigenSTL::vector_Isometry3d& tf = jt->second->getGlobalCollisionBodyTransforms();
if (tf.empty())
{
ROS_ERROR_NAMED(LOGNAME, "Attached body '%s' has no geometry associated to it. No transform to return.",
id.c_str());
return IDENTITY_TRANSFORM;
}
if (tf.size() > 1)
ROS_DEBUG_NAMED(LOGNAME, "There are multiple geometries associated to attached body '%s'. "
"Returning the transform for the first one.",
id.c_str());
return tf[0];
}
bool RobotState::knowsFrameTransform(const std::string& id) const
{
if (!id.empty() && id[0] == '/')
return knowsFrameTransform(id.substr(1));
if (robot_model_->hasLinkModel(id))
return true;
std::map<std::string, AttachedBody*>::const_iterator it = attached_body_map_.find(id);
return it != attached_body_map_.end() && !it->second->getGlobalCollisionBodyTransforms().empty();
}
void RobotState::getRobotMarkers(visualization_msgs::MarkerArray& arr, const std::vector<std::string>& link_names,
const std_msgs::ColorRGBA& color, const std::string& ns, const ros::Duration& dur,
bool include_attached) const
{
std::size_t cur_num = arr.markers.size();
getRobotMarkers(arr, link_names, include_attached);
unsigned int id = cur_num;
for (std::size_t i = cur_num; i < arr.markers.size(); ++i, ++id)
{
arr.markers[i].ns = ns;
arr.markers[i].id = id;
arr.markers[i].lifetime = dur;
arr.markers[i].color = color;
}
}
void RobotState::getRobotMarkers(visualization_msgs::MarkerArray& arr, const std::vector<std::string>& link_names,
bool include_attached) const
{
ros::Time tm = ros::Time::now();
for (std::size_t i = 0; i < link_names.size(); ++i)
{
ROS_DEBUG_NAMED(LOGNAME, "Trying to get marker for link '%s'", link_names[i].c_str());
const LinkModel* lm = robot_model_->getLinkModel(link_names[i]);
if (!lm)
continue;
if (include_attached)
for (std::map<std::string, AttachedBody*>::const_iterator it = attached_body_map_.begin();
it != attached_body_map_.end(); ++it)
if (it->second->getAttachedLink() == lm)
{
for (std::size_t j = 0; j < it->second->getShapes().size(); ++j)
{
visualization_msgs::Marker att_mark;
att_mark.header.frame_id = robot_model_->getModelFrame();
att_mark.header.stamp = tm;
if (shapes::constructMarkerFromShape(it->second->getShapes()[j].get(), att_mark))
{
// if the object is invisible (0 volume) we skip it
if (fabs(att_mark.scale.x * att_mark.scale.y * att_mark.scale.z) < std::numeric_limits<float>::epsilon())
continue;
att_mark.pose = tf2::toMsg(it->second->getGlobalCollisionBodyTransforms()[j]);
arr.markers.push_back(att_mark);
}
}
}
if (lm->getShapes().empty())
continue;
for (std::size_t j = 0; j < lm->getShapes().size(); ++j)
{
visualization_msgs::Marker mark;
mark.header.frame_id = robot_model_->getModelFrame();
mark.header.stamp = tm;
// we prefer using the visual mesh, if a mesh is available and we have one body to render
const std::string& mesh_resource = lm->getVisualMeshFilename();
if (mesh_resource.empty() || lm->getShapes().size() > 1)
{
if (!shapes::constructMarkerFromShape(lm->getShapes()[j].get(), mark))
continue;
// if the object is invisible (0 volume) we skip it
if (fabs(mark.scale.x * mark.scale.y * mark.scale.z) < std::numeric_limits<float>::epsilon())
continue;
mark.pose = tf2::toMsg(global_collision_body_transforms_[lm->getFirstCollisionBodyTransformIndex() + j]);
}
else
{
mark.type = mark.MESH_RESOURCE;
mark.mesh_use_embedded_materials = false;
mark.mesh_resource = mesh_resource;
const Eigen::Vector3d& mesh_scale = lm->getVisualMeshScale();
mark.scale.x = mesh_scale[0];
mark.scale.y = mesh_scale[1];
mark.scale.z = mesh_scale[2];
mark.pose = tf2::toMsg(global_link_transforms_[lm->getLinkIndex()] * lm->getVisualMeshOrigin());
}
arr.markers.push_back(mark);
}
}
}
Eigen::MatrixXd RobotState::getJacobian(const JointModelGroup* group,
const Eigen::Vector3d& reference_point_position) const
{
Eigen::MatrixXd result;
if (!getJacobian(group, group->getLinkModels().back(), reference_point_position, result, false))
throw Exception("Unable to compute Jacobian");
return result;
}
bool RobotState::getJacobian(const JointModelGroup* group, const LinkModel* link,
const Eigen::Vector3d& reference_point_position, Eigen::MatrixXd& jacobian,
bool use_quaternion_representation) const
{
BOOST_VERIFY(checkLinkTransforms());
if (!group->isChain())
{
ROS_ERROR_NAMED(LOGNAME, "The group '%s' is not a chain. Cannot compute Jacobian.", group->getName().c_str());
return false;
}
if (!group->isLinkUpdated(link->getName()))
{
ROS_ERROR_NAMED(LOGNAME, "Link name '%s' does not exist in the chain '%s' or is not a child for this chain",
link->getName().c_str(), group->getName().c_str());
return false;
}
const robot_model::JointModel* root_joint_model = group->getJointModels()[0]; // group->getJointRoots()[0];
const robot_model::LinkModel* root_link_model = root_joint_model->getParentLinkModel();
Eigen::Isometry3d reference_transform =
root_link_model ? getGlobalLinkTransform(root_link_model).inverse() : Eigen::Isometry3d::Identity();
int rows = use_quaternion_representation ? 7 : 6;
int columns = group->getVariableCount();
jacobian = Eigen::MatrixXd::Zero(rows, columns);
Eigen::Isometry3d link_transform = reference_transform * getGlobalLinkTransform(link);
Eigen::Vector3d point_transform = link_transform * reference_point_position;
/*
ROS_DEBUG_NAMED(LOGNAME, "Point from reference origin expressed in world coordinates: %f %f %f",
point_transform.x(),
point_transform.y(),
point_transform.z());
*/
Eigen::Vector3d joint_axis;
Eigen::Isometry3d joint_transform;
while (link)
{
/*
ROS_DEBUG_NAMED(LOGNAME, "Link: %s, %f %f %f",link_state->getName().c_str(),
link_state->getGlobalLinkTransform().translation().x(),
link_state->getGlobalLinkTransform().translation().y(),
link_state->getGlobalLinkTransform().translation().z());
ROS_DEBUG_NAMED(LOGNAME, "Joint: %s",link_state->getParentJointState()->getName().c_str());
*/
const JointModel* pjm = link->getParentJointModel();
if (pjm->getVariableCount() > 0)
{
if (not group->hasJointModel(pjm->getName()))
{
link = pjm->getParentLinkModel();
continue;
}
unsigned int joint_index = group->getVariableGroupIndex(pjm->getName());
if (pjm->getType() == robot_model::JointModel::REVOLUTE)
{
joint_transform = reference_transform * getGlobalLinkTransform(link);
joint_axis = joint_transform.rotation() * static_cast<const robot_model::RevoluteJointModel*>(pjm)->getAxis();
jacobian.block<3, 1>(0, joint_index) =
jacobian.block<3, 1>(0, joint_index) + joint_axis.cross(point_transform - joint_transform.translation());
jacobian.block<3, 1>(3, joint_index) = jacobian.block<3, 1>(3, joint_index) + joint_axis;
}
else if (pjm->getType() == robot_model::JointModel::PRISMATIC)
{
joint_transform = reference_transform * getGlobalLinkTransform(link);
joint_axis = joint_transform.rotation() * static_cast<const robot_model::PrismaticJointModel*>(pjm)->getAxis();
jacobian.block<3, 1>(0, joint_index) = jacobian.block<3, 1>(0, joint_index) + joint_axis;
}
else if (pjm->getType() == robot_model::JointModel::PLANAR)
{
joint_transform = reference_transform * getGlobalLinkTransform(link);
joint_axis = joint_transform * Eigen::Vector3d(1.0, 0.0, 0.0);
jacobian.block<3, 1>(0, joint_index) = jacobian.block<3, 1>(0, joint_index) + joint_axis;
joint_axis = joint_transform * Eigen::Vector3d(0.0, 1.0, 0.0);
jacobian.block<3, 1>(0, joint_index + 1) = jacobian.block<3, 1>(0, joint_index + 1) + joint_axis;
joint_axis = joint_transform * Eigen::Vector3d(0.0, 0.0, 1.0);
jacobian.block<3, 1>(0, joint_index + 2) = jacobian.block<3, 1>(0, joint_index + 2) +
joint_axis.cross(point_transform - joint_transform.translation());
jacobian.block<3, 1>(3, joint_index + 2) = jacobian.block<3, 1>(3, joint_index + 2) + joint_axis;
}
else
ROS_ERROR_NAMED(LOGNAME, "Unknown type of joint in Jacobian computation");
}
if (pjm == root_joint_model)
break;
link = pjm->getParentLinkModel();
}
if (use_quaternion_representation)
{ // Quaternion representation
// From "Advanced Dynamics and Motion Simulation" by Paul Mitiguy
// d/dt ( [w] ) = 1/2 * [ -x -y -z ] * [ omega_1 ]
// [x] [ w -z y ] [ omega_2 ]
// [y] [ z w -x ] [ omega_3 ]
// [z] [ -y x w ]
Eigen::Quaterniond q(link_transform.rotation());
double w = q.w(), x = q.x(), y = q.y(), z = q.z();
Eigen::MatrixXd quaternion_update_matrix(4, 3);
quaternion_update_matrix << -x, -y, -z, w, -z, y, z, w, -x, -y, x, w;
jacobian.block(3, 0, 4, columns) = 0.5 * quaternion_update_matrix * jacobian.block(3, 0, 3, columns);
}
return true;
}
bool RobotState::setFromDiffIK(const JointModelGroup* jmg, const Eigen::VectorXd& twist, const std::string& tip,
double dt, const GroupStateValidityCallbackFn& constraint)
{
Eigen::VectorXd qdot;
computeVariableVelocity(jmg, qdot, twist, getLinkModel(tip));
return integrateVariableVelocity(jmg, qdot, dt, constraint);
}
bool RobotState::setFromDiffIK(const JointModelGroup* jmg, const geometry_msgs::Twist& twist, const std::string& tip,
double dt, const GroupStateValidityCallbackFn& constraint)
{
Eigen::Matrix<double, 6, 1> t;
tf2::fromMsg(twist, t);
return setFromDiffIK(jmg, t, tip, dt, constraint);
}
void RobotState::computeVariableVelocity(const JointModelGroup* jmg, Eigen::VectorXd& qdot,
const Eigen::VectorXd& twist, const LinkModel* tip) const
{
// Get the Jacobian of the group at the current configuration
Eigen::MatrixXd j(6, jmg->getVariableCount());
Eigen::Vector3d reference_point(0.0, 0.0, 0.0);
getJacobian(jmg, tip, reference_point, j, false);
// Rotate the jacobian to the end-effector frame
Eigen::Isometry3d e_mb = getGlobalLinkTransform(tip).inverse();
Eigen::MatrixXd e_wb = Eigen::ArrayXXd::Zero(6, 6);
e_wb.block(0, 0, 3, 3) = e_mb.matrix().block(0, 0, 3, 3);
e_wb.block(3, 3, 3, 3) = e_mb.matrix().block(0, 0, 3, 3);
j = e_wb * j;
// Do the Jacobian moore-penrose pseudo-inverse
Eigen::JacobiSVD<Eigen::MatrixXd> svd_of_j(j, Eigen::ComputeThinU | Eigen::ComputeThinV);
const Eigen::MatrixXd& u = svd_of_j.matrixU();
const Eigen::MatrixXd& v = svd_of_j.matrixV();
const Eigen::VectorXd& s = svd_of_j.singularValues();
Eigen::VectorXd sinv = s;
static const double PINVTOLER = std::numeric_limits<float>::epsilon();
double maxsv = 0.0;
for (std::size_t i = 0; i < static_cast<std::size_t>(s.rows()); ++i)
if (fabs(s(i)) > maxsv)
maxsv = fabs(s(i));
for (std::size_t i = 0; i < static_cast<std::size_t>(s.rows()); ++i)
{
// Those singular values smaller than a percentage of the maximum singular value are removed
if (fabs(s(i)) > maxsv * PINVTOLER)
sinv(i) = 1.0 / s(i);
else
sinv(i) = 0.0;
}
Eigen::MatrixXd jinv = (v * sinv.asDiagonal() * u.transpose());
// Compute joint velocity
qdot = jinv * twist;
}
bool RobotState::integrateVariableVelocity(const JointModelGroup* jmg, const Eigen::VectorXd& qdot, double dt,
const GroupStateValidityCallbackFn& constraint)
{
Eigen::VectorXd q(jmg->getVariableCount());
copyJointGroupPositions(jmg, q);
q = q + dt * qdot;
setJointGroupPositions(jmg, q);
enforceBounds(jmg);
if (constraint)
{
std::vector<double> values;
copyJointGroupPositions(jmg, values);
return constraint(this, jmg, &values[0]);
}
else
return true;
}
bool RobotState::setFromIK(const JointModelGroup* jmg, const geometry_msgs::Pose& pose, double timeout,
const GroupStateValidityCallbackFn& constraint,
const kinematics::KinematicsQueryOptions& options)
{
const kinematics::KinematicsBaseConstPtr& solver = jmg->getSolverInstance();
if (!solver)
{
ROS_ERROR_NAMED(LOGNAME, "No kinematics solver instantiated for group '%s'", jmg->getName().c_str());
return false;
}
return setFromIK(jmg, pose, solver->getTipFrame(), timeout, constraint, options);
}
bool RobotState::setFromIK(const JointModelGroup* jmg, const geometry_msgs::Pose& pose, const std::string& tip,
double timeout, const GroupStateValidityCallbackFn& constraint,
const kinematics::KinematicsQueryOptions& options)
{
Eigen::Isometry3d mat;
tf2::fromMsg(pose, mat);
static std::vector<double> consistency_limits;
return setFromIK(jmg, mat, tip, consistency_limits, timeout, constraint, options);
}
bool RobotState::setFromIK(const JointModelGroup* jmg, const Eigen::Isometry3d& pose, double timeout,
const GroupStateValidityCallbackFn& constraint,
const kinematics::KinematicsQueryOptions& options)
{
const kinematics::KinematicsBaseConstPtr& solver = jmg->getSolverInstance();
if (!solver)
{
ROS_ERROR_NAMED(LOGNAME, "No kinematics solver instantiated for group '%s'", jmg->getName().c_str());
return false;
}
static std::vector<double> consistency_limits;
return setFromIK(jmg, pose, solver->getTipFrame(), consistency_limits, timeout, constraint, options);
}
bool RobotState::setFromIK(const JointModelGroup* jmg, const Eigen::Isometry3d& pose_in, const std::string& tip_in,
double timeout, const GroupStateValidityCallbackFn& constraint,
const kinematics::KinematicsQueryOptions& options)
{
static std::vector<double> consistency_limits;
return setFromIK(jmg, pose_in, tip_in, consistency_limits, timeout, constraint, options);
}
namespace
{
bool ikCallbackFnAdapter(RobotState* state, const JointModelGroup* group,
const GroupStateValidityCallbackFn& constraint, const geometry_msgs::Pose& /*unused*/,
const std::vector<double>& ik_sol, moveit_msgs::MoveItErrorCodes& error_code)
{
const std::vector<unsigned int>& bij = group->getKinematicsSolverJointBijection();
std::vector<double> solution(bij.size());
for (std::size_t i = 0; i < bij.size(); ++i)
solution[bij[i]] = ik_sol[i];
if (constraint(state, group, &solution[0]))
error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
else
error_code.val = moveit_msgs::MoveItErrorCodes::NO_IK_SOLUTION;
return true;
}
}
bool RobotState::setToIKSolverFrame(Eigen::Isometry3d& pose, const kinematics::KinematicsBaseConstPtr& solver)
{
return setToIKSolverFrame(pose, solver->getBaseFrame());
}
bool RobotState::setToIKSolverFrame(Eigen::Isometry3d& pose, const std::string& ik_frame)
{
// Bring the pose to the frame of the IK solver
if (!Transforms::sameFrame(ik_frame, robot_model_->getModelFrame()))
{
const LinkModel* lm = getLinkModel((!ik_frame.empty() && ik_frame[0] == '/') ? ik_frame.substr(1) : ik_frame);
if (!lm)
{
ROS_ERROR_STREAM_NAMED(LOGNAME, "IK frame '" << ik_frame << "' does not exist.");
return false;
}
pose = getGlobalLinkTransform(lm).inverse() * pose;
}
return true;
}
bool RobotState::setFromIK(const JointModelGroup* jmg, const Eigen::Isometry3d& pose_in, const std::string& tip_in,
const std::vector<double>& consistency_limits_in, double timeout,
const GroupStateValidityCallbackFn& constraint,
const kinematics::KinematicsQueryOptions& options)
{
// Convert from single pose and tip to vectors
EigenSTL::vector_Isometry3d poses;
poses.push_back(pose_in);
std::vector<std::string> tips;
tips.push_back(tip_in);
std::vector<std::vector<double> > consistency_limits;
consistency_limits.push_back(consistency_limits_in);
return setFromIK(jmg, poses, tips, consistency_limits, timeout, constraint, options);
}
bool RobotState::setFromIK(const JointModelGroup* jmg, const EigenSTL::vector_Isometry3d& poses_in,
const std::vector<std::string>& tips_in, double timeout,
const GroupStateValidityCallbackFn& constraint,
const kinematics::KinematicsQueryOptions& options)
{
const std::vector<std::vector<double> > consistency_limits;
return setFromIK(jmg, poses_in, tips_in, consistency_limits, timeout, constraint, options);
}
bool RobotState::setFromIK(const JointModelGroup* jmg, const EigenSTL::vector_Isometry3d& poses_in,
const std::vector<std::string>& tips_in,
const std::vector<std::vector<double> >& consistency_limit_sets, double timeout,
const GroupStateValidityCallbackFn& constraint,
const kinematics::KinematicsQueryOptions& options)
{
// Error check
if (poses_in.size() != tips_in.size())
{
ROS_ERROR_NAMED(LOGNAME, "Number of poses must be the same as number of tips");
return false;
}
// Load solver
const kinematics::KinematicsBaseConstPtr& solver = jmg->getSolverInstance();
// Check if this jmg has a solver
bool valid_solver = true;
if (!solver)
{
valid_solver = false;
}
// Check if this jmg's IK solver can handle multiple tips (non-chain solver)
else if (poses_in.size() > 1)
{
std::string error_msg;
if (!solver->supportsGroup(jmg, &error_msg))
{
ROS_ERROR_NAMED(LOGNAME, "Kinematics solver %s does not support joint group %s. Error: %s",
typeid(*solver).name(), jmg->getName().c_str(), error_msg.c_str());
valid_solver = false;
}
}
if (!valid_solver)
{
// Check if there are subgroups that can solve this for us (non-chains)
if (poses_in.size() > 1)
{
// Forward to setFromIKSubgroups() to allow different subgroup IK solvers to work together
return setFromIKSubgroups(jmg, poses_in, tips_in, consistency_limit_sets, timeout, constraint, options);
}
else
{
ROS_ERROR_NAMED(LOGNAME, "No kinematics solver instantiated for group '%s'", jmg->getName().c_str());
return false;
}
}
// Check that no, or only one set of consistency limits have been passed in, and choose that one
std::vector<double> consistency_limits;
if (consistency_limit_sets.size() > 1)
{
ROS_ERROR_NAMED(LOGNAME, "Invalid number (%zu) of sets of consistency limits for a setFromIK request "
"that is being solved by a single IK solver",
consistency_limit_sets.size());
return false;
}
else if (consistency_limit_sets.size() == 1)
consistency_limits = consistency_limit_sets[0];
const std::vector<std::string>& solver_tip_frames = solver->getTipFrames();
// Track which possible tips frames we have filled in so far
std::vector<bool> tip_frames_used(solver_tip_frames.size(), false);
// Create vector to hold the output frames in the same order as solver_tip_frames
std::vector<geometry_msgs::Pose> ik_queries(solver_tip_frames.size());
// Bring each pose to the frame of the IK solver
for (std::size_t i = 0; i < poses_in.size(); ++i)
{
// Make non-const
Eigen::Isometry3d pose = poses_in[i];
std::string pose_frame = tips_in[i];
// Remove extra slash
if (!pose_frame.empty() && pose_frame[0] == '/')
pose_frame = pose_frame.substr(1);
// bring the pose to the frame of the IK solver
if (!setToIKSolverFrame(pose, solver))
return false;
// try all of the solver's possible tip frames to see if they uniquely align with any of our passed in pose tip
// frames
bool found_valid_frame = false;
std::size_t solver_tip_id; // our current index
for (solver_tip_id = 0; solver_tip_id < solver_tip_frames.size(); ++solver_tip_id)
{
// Check if this tip frame is already accounted for
if (tip_frames_used[solver_tip_id])
continue; // already has a pose
// check if the tip frame can be transformed via fixed transforms to the frame known to the IK solver
std::string solver_tip_frame = solver_tip_frames[solver_tip_id];
// remove the frame '/' if there is one, so we can avoid calling Transforms::sameFrame() which may copy strings
// more often that we need to
if (!solver_tip_frame.empty() && solver_tip_frame[0] == '/')
solver_tip_frame = solver_tip_frame.substr(1);
if (pose_frame != solver_tip_frame)
{
if (hasAttachedBody(pose_frame))
{
const AttachedBody* ab = getAttachedBody(pose_frame);
const EigenSTL::vector_Isometry3d& ab_trans = ab->getFixedTransforms();
if (ab_trans.size() != 1)
{
ROS_ERROR_NAMED(LOGNAME, "Cannot use an attached body "
"with multiple geometries as a reference frame.");
return false;
}
pose_frame = ab->getAttachedLinkName();
pose = pose * ab_trans[0].inverse();
}
if (pose_frame != solver_tip_frame)
{
const robot_model::LinkModel* lm = getLinkModel(pose_frame);
if (!lm)
{
ROS_ERROR_STREAM_NAMED(LOGNAME, "Pose frame '" << pose_frame << "' does not exist.");
return false;
}
const robot_model::LinkTransformMap& fixed_links = lm->getAssociatedFixedTransforms();
for (robot_model::LinkTransformMap::const_iterator it = fixed_links.begin(); it != fixed_links.end(); ++it)
if (Transforms::sameFrame(it->first->getName(), solver_tip_frame))
{
pose_frame = solver_tip_frame;
pose = pose * it->second;
break;
}
}
} // end if pose_frame
// Check if this pose frame works
if (pose_frame == solver_tip_frame)
{
found_valid_frame = true;
break;
}
} // end for solver_tip_frames
// Make sure one of the tip frames worked
if (!found_valid_frame)
{
ROS_ERROR_NAMED(LOGNAME, "Cannot compute IK for query %zu pose reference frame '%s'", i, pose_frame.c_str());
// Debug available tip frames
std::stringstream ss;
for (solver_tip_id = 0; solver_tip_id < solver_tip_frames.size(); ++solver_tip_id)
ss << solver_tip_frames[solver_tip_id] << ", ";
ROS_ERROR_NAMED(LOGNAME, "Available tip frames: [%s]", ss.str().c_str());
return false;
}
// Remove that tip from the list of available tip frames because each can only have one pose
tip_frames_used[solver_tip_id] = true;
// Convert Eigen pose to geometry_msgs pose
geometry_msgs::Pose ik_query;
ik_query = tf2::toMsg(pose);
// Save into vectors
ik_queries[solver_tip_id] = ik_query;
} // end for poses_in
// Create poses for all remaining tips a solver expects, even if not passed into this function
for (std::size_t solver_tip_id = 0; solver_tip_id < solver_tip_frames.size(); ++solver_tip_id)
{
// Check if this tip frame is already accounted for
if (tip_frames_used[solver_tip_id])
continue; // already has a pose
// Process this tip
std::string solver_tip_frame = solver_tip_frames[solver_tip_id];
// remove the frame '/' if there is one, so we can avoid calling Transforms::sameFrame() which may copy strings more
// often that we need to
if (!solver_tip_frame.empty() && solver_tip_frame[0] == '/')
solver_tip_frame = solver_tip_frame.substr(1);
// Get the pose of a different EE tip link
Eigen::Isometry3d current_pose = getGlobalLinkTransform(solver_tip_frame);
// bring the pose to the frame of the IK solver
if (!setToIKSolverFrame(current_pose, solver))
return false;
// Convert Eigen pose to geometry_msgs pose
geometry_msgs::Pose ik_query;
ik_query = tf2::toMsg(current_pose);
// Save into vectors - but this needs to be ordered in the same order as the IK solver expects its tip frames
ik_queries[solver_tip_id] = ik_query;
// Remove that tip from the list of available tip frames because each can only have one pose
tip_frames_used[solver_tip_id] = true;
}
// if no timeout has been specified, use the default one
if (timeout < std::numeric_limits<double>::epsilon())
timeout = jmg->getDefaultIKTimeout();
// set callback function
kinematics::KinematicsBase::IKCallbackFn ik_callback_fn;
if (constraint)
ik_callback_fn = boost::bind(&ikCallbackFnAdapter, this, jmg, constraint, _1, _2, _3);
// Bijection
const std::vector<unsigned int>& bij = jmg->getKinematicsSolverJointBijection();
std::vector<double> initial_values;
copyJointGroupPositions(jmg, initial_values);
std::vector<double> seed(bij.size());
for (std::size_t i = 0; i < bij.size(); ++i)
seed[i] = initial_values[bij[i]];
// compute the IK solution
std::vector<double> ik_sol;
moveit_msgs::MoveItErrorCodes error;
if (solver->searchPositionIK(ik_queries, seed, timeout, consistency_limits, ik_sol, ik_callback_fn, error, options,
this))
{
std::vector<double> solution(bij.size());
for (std::size_t i = 0; i < bij.size(); ++i)
solution[bij[i]] = ik_sol[i];
setJointGroupPositions(jmg, solution);
return true;
}
return false;
}
bool RobotState::setFromIKSubgroups(const JointModelGroup* jmg, const EigenSTL::vector_Isometry3d& poses_in,
const std::vector<std::string>& tips_in,
const std::vector<std::vector<double> >& consistency_limits, double timeout,
const GroupStateValidityCallbackFn& constraint,
const kinematics::KinematicsQueryOptions& options)
{
// Assume we have already ran setFromIK() and those checks
// Get containing subgroups
std::vector<const JointModelGroup*> sub_groups;
jmg->getSubgroups(sub_groups);
// Error check
if (poses_in.size() != sub_groups.size())
{
ROS_ERROR_NAMED(LOGNAME, "Number of poses (%zu) must be the same as number of sub-groups (%zu)", poses_in.size(),
sub_groups.size());
return false;
}
if (tips_in.size() != sub_groups.size())
{
ROS_ERROR_NAMED(LOGNAME, "Number of tip names (%zu) must be same as number of sub-groups (%zu)", tips_in.size(),
sub_groups.size());
return false;
}
if (!consistency_limits.empty() && consistency_limits.size() != sub_groups.size())
{
ROS_ERROR_NAMED(LOGNAME, "Number of consistency limit vectors must be the same as number of sub-groups");
return false;
}
for (std::size_t i = 0; i < consistency_limits.size(); ++i)
{
if (consistency_limits[i].size() != sub_groups[i]->getVariableCount())
{
ROS_ERROR_NAMED(LOGNAME, "Number of joints in consistency_limits is %zu but it should be should be %u", i,
sub_groups[i]->getVariableCount());
return false;
}
}
// Populate list of kin solvers for the various subgroups
std::vector<kinematics::KinematicsBaseConstPtr> solvers;
for (std::size_t i = 0; i < poses_in.size(); ++i)
{
kinematics::KinematicsBaseConstPtr solver = sub_groups[i]->getSolverInstance();
if (!solver)
{
ROS_ERROR_NAMED(LOGNAME, "Could not find solver for group '%s'", sub_groups[i]->getName().c_str());
return false;
}
solvers.push_back(solver);
}
// Make non-const versions
EigenSTL::vector_Isometry3d transformed_poses = poses_in;
std::vector<std::string> pose_frames = tips_in;
// Each each pose's tip frame naming
for (std::size_t i = 0; i < poses_in.size(); ++i)
{
Eigen::Isometry3d& pose = transformed_poses[i];
std::string& pose_frame = pose_frames[i];
// bring the pose to the frame of the IK solver
if (!setToIKSolverFrame(pose, solvers[i]))
return false;
// see if the tip frame can be transformed via fixed transforms to the frame known to the IK solver
std::string solver_tip_frame = solvers[i]->getTipFrame();
// remove the frame '/' if there is one, so we can avoid calling Transforms::sameFrame() which may copy strings more
// often that we need to
if (!solver_tip_frame.empty() && solver_tip_frame[0] == '/')
solver_tip_frame = solver_tip_frame.substr(1);
if (pose_frame != solver_tip_frame)
{
if (hasAttachedBody(pose_frame))
{
const AttachedBody* ab = getAttachedBody(pose_frame);
const EigenSTL::vector_Isometry3d& ab_trans = ab->getFixedTransforms();
if (ab_trans.size() != 1)
{
ROS_ERROR_NAMED(LOGNAME, "Cannot use an attached body with multiple geometries as a reference frame.");
return false;
}
pose_frame = ab->getAttachedLinkName();
pose = pose * ab_trans[0].inverse();
}
if (pose_frame != solver_tip_frame)
{
const robot_model::LinkModel* lm = getLinkModel(pose_frame);
if (!lm)
return false;
const robot_model::LinkTransformMap& fixed_links = lm->getAssociatedFixedTransforms();
for (robot_model::LinkTransformMap::const_iterator it = fixed_links.begin(); it != fixed_links.end(); ++it)
if (it->first->getName() == solver_tip_frame)
{
pose_frame = solver_tip_frame;
pose = pose * it->second;
break;
}
}
}
if (pose_frame != solver_tip_frame)
{
ROS_ERROR_NAMED(LOGNAME, "Cannot compute IK for query pose reference frame '%s', desired: '%s'",
pose_frame.c_str(), solver_tip_frame.c_str());
return false;
}
}
// Convert Eigen poses to geometry_msg format
std::vector<geometry_msgs::Pose> ik_queries(poses_in.size());
kinematics::KinematicsBase::IKCallbackFn ik_callback_fn;
if (constraint)
ik_callback_fn = boost::bind(&ikCallbackFnAdapter, this, jmg, constraint, _1, _2, _3);
for (std::size_t i = 0; i < transformed_poses.size(); ++i)
{
Eigen::Quaterniond quat(transformed_poses[i].rotation());
Eigen::Vector3d point(transformed_poses[i].translation());
ik_queries[i].position.x = point.x();
ik_queries[i].position.y = point.y();
ik_queries[i].position.z = point.z();
ik_queries[i].orientation.x = quat.x();
ik_queries[i].orientation.y = quat.y();
ik_queries[i].orientation.z = quat.z();
ik_queries[i].orientation.w = quat.w();
}
// if no timeout has been specified, use the default one
if (timeout < std::numeric_limits<double>::epsilon())
timeout = jmg->getDefaultIKTimeout();
ros::WallTime start = ros::WallTime::now();
double elapsed = 0;
bool first_seed = true;
unsigned int attempts = 0;
do
{
++attempts;
ROS_DEBUG_NAMED(LOGNAME, "IK attempt: %d", attempts);
bool found_solution = true;
for (std::size_t sg = 0; sg < sub_groups.size(); ++sg)
{
const std::vector<unsigned int>& bij = sub_groups[sg]->getKinematicsSolverJointBijection();
std::vector<double> seed(bij.size());
// the first seed is the initial state
if (first_seed)
{
std::vector<double> initial_values;
copyJointGroupPositions(sub_groups[sg], initial_values);
for (std::size_t i = 0; i < bij.size(); ++i)
seed[i] = initial_values[bij[i]];
}
else
{
// sample a random seed
random_numbers::RandomNumberGenerator& rng = getRandomNumberGenerator();
std::vector<double> random_values;
sub_groups[sg]->getVariableRandomPositions(rng, random_values);
for (std::size_t i = 0; i < bij.size(); ++i)
seed[i] = random_values[bij[i]];
}
// compute the IK solution
std::vector<double> ik_sol;
moveit_msgs::MoveItErrorCodes error;
const std::vector<double>& climits = consistency_limits.empty() ? std::vector<double>() : consistency_limits[sg];
if (solvers[sg]->searchPositionIK(ik_queries[sg], seed, (timeout - elapsed) / sub_groups.size(), climits, ik_sol,
error))
{
std::vector<double> solution(bij.size());
for (std::size_t i = 0; i < bij.size(); ++i)
solution[bij[i]] = ik_sol[i];
setJointGroupPositions(sub_groups[sg], solution);
}
else
{
found_solution = false;
break;
}
}
if (found_solution)
{
std::vector<double> full_solution;
copyJointGroupPositions(jmg, full_solution);
if (constraint ? constraint(this, jmg, &full_solution[0]) : true)
{
ROS_DEBUG_NAMED(LOGNAME, "Found IK solution");
return true;
}
}
elapsed = (ros::WallTime::now() - start).toSec();
first_seed = false;
} while (elapsed < timeout);
return false;
}
double RobotState::computeCartesianPath(const JointModelGroup* group, std::vector<RobotStatePtr>& traj,
const LinkModel* link, const Eigen::Vector3d& direction,
bool global_reference_frame, double distance, const MaxEEFStep& max_step,
const JumpThreshold& jump_threshold,
const GroupStateValidityCallbackFn& validCallback,
const kinematics::KinematicsQueryOptions& options)
{
// this is the Cartesian pose we start from, and have to move in the direction indicated
const Eigen::Isometry3d& start_pose = getGlobalLinkTransform(link);
// the direction can be in the local reference frame (in which case we rotate it)
const Eigen::Vector3d rotated_direction = global_reference_frame ? direction : start_pose.rotation() * direction;
// The target pose is built by applying a translation to the start pose for the desired direction and distance
Eigen::Isometry3d target_pose = start_pose;
target_pose.translation() += rotated_direction * distance;
// call computeCartesianPath for the computed target pose in the global reference frame
return (distance *
computeCartesianPath(group, traj, link, target_pose, true, max_step, jump_threshold, validCallback, options));
}
double RobotState::computeCartesianPath(const JointModelGroup* group, std::vector<RobotStatePtr>& traj,
const LinkModel* link, const Eigen::Isometry3d& target,
bool global_reference_frame, const MaxEEFStep& max_step,
const JumpThreshold& jump_threshold,
const GroupStateValidityCallbackFn& validCallback,
const kinematics::KinematicsQueryOptions& options)
{
const std::vector<const JointModel*>& cjnt = group->getContinuousJointModels();
// make sure that continuous joints wrap
for (std::size_t i = 0; i < cjnt.size(); ++i)
enforceBounds(cjnt[i]);
// this is the Cartesian pose we start from, and we move in the direction indicated
Eigen::Isometry3d start_pose = getGlobalLinkTransform(link);
// the target can be in the local reference frame (in which case we rotate it)
Eigen::Isometry3d rotated_target = global_reference_frame ? target : start_pose * target;
Eigen::Quaterniond start_quaternion(start_pose.rotation());
Eigen::Quaterniond target_quaternion(rotated_target.rotation());
if (max_step.translation <= 0.0 && max_step.rotation <= 0.0)
{
ROS_ERROR_NAMED(LOGNAME,
"Invalid MaxEEFStep passed into computeCartesianPath. Both the MaxEEFStep.rotation and "
"MaxEEFStep.translation components must be non-negative and at least one component must be "
"greater than zero");
return 0.0;
}
double rotation_distance = start_quaternion.angularDistance(target_quaternion);
double translation_distance = (rotated_target.translation() - start_pose.translation()).norm();
// decide how many steps we will need for this trajectory
std::size_t translation_steps = 0;
if (max_step.translation > 0.0)
translation_steps = floor(translation_distance / max_step.translation);
std::size_t rotation_steps = 0;
if (max_step.rotation > 0.0)
rotation_steps = floor(rotation_distance / max_step.rotation);
// If we are testing for relative jumps, we always want at least MIN_STEPS_FOR_JUMP_THRESH steps
std::size_t steps = std::max(translation_steps, rotation_steps) + 1;
if (jump_threshold.factor > 0 && steps < MIN_STEPS_FOR_JUMP_THRESH)
steps = MIN_STEPS_FOR_JUMP_THRESH;
// To limit absolute joint-space jumps, we pass consistency limits to the IK solver
std::vector<double> consistency_limits;
if (jump_threshold.prismatic > 0 || jump_threshold.revolute > 0)
for (const JointModel* jm : group->getActiveJointModels())
{
double limit;
switch (jm->getType())
{
case JointModel::REVOLUTE:
limit = jump_threshold.revolute;
break;
case JointModel::PRISMATIC:
limit = jump_threshold.prismatic;
break;
default:
limit = 0.0;
}
if (limit == 0.0)
limit = jm->getMaximumExtent();
consistency_limits.push_back(limit);
}
traj.clear();
traj.push_back(RobotStatePtr(new RobotState(*this)));
double last_valid_percentage = 0.0;
for (std::size_t i = 1; i <= steps; ++i)
{
double percentage = (double)i / (double)steps;
Eigen::Isometry3d pose(start_quaternion.slerp(percentage, target_quaternion));
pose.translation() = percentage * rotated_target.translation() + (1 - percentage) * start_pose.translation();
// Explicitly use a single IK attempt only: We want a smooth trajectory.
// Random seeding (of additional attempts) would probably create IK jumps.
if (setFromIK(group, pose, link->getName(), consistency_limits, 0.0, validCallback, options))
traj.push_back(RobotStatePtr(new RobotState(*this)));
else
break;
last_valid_percentage = percentage;
}
last_valid_percentage *= testJointSpaceJump(group, traj, jump_threshold);
return last_valid_percentage;
}
double RobotState::computeCartesianPath(const JointModelGroup* group, std::vector<RobotStatePtr>& traj,
const LinkModel* link, const EigenSTL::vector_Isometry3d& waypoints,
bool global_reference_frame, const MaxEEFStep& max_step,
const JumpThreshold& jump_threshold,
const GroupStateValidityCallbackFn& validCallback,
const kinematics::KinematicsQueryOptions& options)
{
double percentage_solved = 0.0;
for (std::size_t i = 0; i < waypoints.size(); ++i)
{
// Don't test joint space jumps for every waypoint, test them later on the whole trajectory.
static const JumpThreshold NO_JOINT_SPACE_JUMP_TEST;
std::vector<RobotStatePtr> waypoint_traj;
double wp_percentage_solved = computeCartesianPath(group, waypoint_traj, link, waypoints[i], global_reference_frame,
max_step, NO_JOINT_SPACE_JUMP_TEST, validCallback, options);
if (fabs(wp_percentage_solved - 1.0) < std::numeric_limits<double>::epsilon())
{
percentage_solved = (double)(i + 1) / (double)waypoints.size();
std::vector<RobotStatePtr>::iterator start = waypoint_traj.begin();
if (i > 0 && !waypoint_traj.empty())
std::advance(start, 1);
traj.insert(traj.end(), start, waypoint_traj.end());
}
else
{
percentage_solved += wp_percentage_solved / (double)waypoints.size();
std::vector<RobotStatePtr>::iterator start = waypoint_traj.begin();
if (i > 0 && !waypoint_traj.empty())
std::advance(start, 1);
traj.insert(traj.end(), start, waypoint_traj.end());
break;
}
}
percentage_solved *= testJointSpaceJump(group, traj, jump_threshold);
return percentage_solved;
}
double RobotState::testJointSpaceJump(const JointModelGroup* group, std::vector<RobotStatePtr>& traj,
const JumpThreshold& jump_threshold)
{
double percentage_solved = 1.0;
if (traj.size() <= 1)
return percentage_solved;
if (jump_threshold.factor > 0.0)
percentage_solved *= testRelativeJointSpaceJump(group, traj, jump_threshold.factor);
if (jump_threshold.revolute > 0.0 || jump_threshold.prismatic > 0.0)
percentage_solved *= testAbsoluteJointSpaceJump(group, traj, jump_threshold.revolute, jump_threshold.prismatic);
return percentage_solved;
}
double RobotState::testRelativeJointSpaceJump(const JointModelGroup* group, std::vector<RobotStatePtr>& traj,
double jump_threshold_factor)
{
if (traj.size() < MIN_STEPS_FOR_JUMP_THRESH)
{
ROS_WARN_NAMED(LOGNAME, "The computed trajectory is too short to detect jumps in joint-space "
"Need at least %zu steps, only got %zu. Try a lower max_step.",
MIN_STEPS_FOR_JUMP_THRESH, traj.size());
}
std::vector<double> dist_vector;
dist_vector.reserve(traj.size() - 1);
double total_dist = 0.0;
for (std::size_t i = 1; i < traj.size(); ++i)
{
double dist_prev_point = traj[i]->distance(*traj[i - 1], group);
dist_vector.push_back(dist_prev_point);
total_dist += dist_prev_point;
}
double percentage = 1.0;
// compute the average distance between the states we looked at
double thres = jump_threshold_factor * (total_dist / (double)dist_vector.size());
for (std::size_t i = 0; i < dist_vector.size(); ++i)
if (dist_vector[i] > thres)
{
ROS_DEBUG_NAMED(LOGNAME, "Truncating Cartesian path due to detected jump in joint-space distance");
percentage = (double)(i + 1) / (double)(traj.size());
traj.resize(i + 1);
break;
}
return percentage;
}
double RobotState::testAbsoluteJointSpaceJump(const JointModelGroup* group, std::vector<RobotStatePtr>& traj,
double revolute_threshold, double prismatic_threshold)
{
struct LimitData
{
double limit_;
bool check_;
};
LimitData data[2] = { { revolute_threshold, revolute_threshold > 0.0 },
{ prismatic_threshold, prismatic_threshold > 0.0 } };
bool still_valid = true;
const std::vector<const JointModel*>& joints = group->getActiveJointModels();
for (std::size_t traj_ix = 0, ix_end = traj.size() - 1; traj_ix != ix_end; ++traj_ix)
{
for (auto& joint : joints)
{
unsigned int type_index;
switch (joint->getType())
{
case JointModel::REVOLUTE:
type_index = 0;
break;
case JointModel::PRISMATIC:
type_index = 1;
break;
default:
ROS_WARN_NAMED(LOGNAME, "Joint %s has not supported type %s. \n"
"testAbsoluteJointSpaceJump only supports prismatic and revolute joints.",
joint->getName().c_str(), joint->getTypeName().c_str());
continue;
}
if (!data[type_index].check_)
continue;
double distance = traj[traj_ix]->distance(*traj[traj_ix + 1], joint);
if (distance > data[type_index].limit_)
{
ROS_DEBUG_NAMED(LOGNAME, "Truncating Cartesian path due to detected jump of %.4f > %.4f in joint %s", distance,
data[type_index].limit_, joint->getName().c_str());
still_valid = false;
break;
}
}
if (!still_valid)
{
double percent_valid = (double)(traj_ix + 1) / (double)(traj.size());
traj.resize(traj_ix + 1);
return percent_valid;
}
}
return 1.0;
}
void RobotState::computeAABB(std::vector<double>& aabb) const
{
BOOST_VERIFY(checkLinkTransforms());
core::AABB bounding_box;
std::vector<const LinkModel*> links = robot_model_->getLinkModelsWithCollisionGeometry();
for (std::size_t i = 0; i < links.size(); ++i)
{
Eigen::Isometry3d transform = getGlobalLinkTransform(links[i]); // intentional copy, we will translate
const Eigen::Vector3d& extents = links[i]->getShapeExtentsAtOrigin();
transform.translate(links[i]->getCenteredBoundingBoxOffset());
bounding_box.extendWithTransformedBox(transform, extents);
}
for (std::map<std::string, AttachedBody*>::const_iterator it = attached_body_map_.begin();
it != attached_body_map_.end(); ++it)
{
const EigenSTL::vector_Isometry3d& transforms = it->second->getGlobalCollisionBodyTransforms();
const std::vector<shapes::ShapeConstPtr>& shapes = it->second->getShapes();
for (std::size_t i = 0; i < transforms.size(); ++i)
{
Eigen::Vector3d extents = shapes::computeShapeExtents(shapes[i].get());
bounding_box.extendWithTransformedBox(transforms[i], extents);
}
}
aabb.clear();
aabb.resize(6, 0.0);
if (!bounding_box.isEmpty())
{
// The following is a shorthand for something like:
// aabb[0, 2, 4] = bounding_box.min(); aabb[1, 3, 5] = bounding_box.max();
Eigen::Map<Eigen::VectorXd, Eigen::Unaligned, Eigen::InnerStride<2> >(aabb.data(), 3) = bounding_box.min();
Eigen::Map<Eigen::VectorXd, Eigen::Unaligned, Eigen::InnerStride<2> >(aabb.data() + 1, 3) = bounding_box.max();
}
}
void RobotState::printStatePositions(std::ostream& out) const
{
const std::vector<std::string>& nm = robot_model_->getVariableNames();
for (std::size_t i = 0; i < nm.size(); ++i)
out << nm[i] << "=" << position_[i] << std::endl;
}
void RobotState::printDirtyInfo(std::ostream& out) const
{
out << " * Dirty Joint Transforms: " << std::endl;
const std::vector<const JointModel*>& jm = robot_model_->getJointModels();
for (std::size_t i = 0; i < jm.size(); ++i)
if (jm[i]->getVariableCount() > 0 && dirtyJointTransform(jm[i]))
out << " " << jm[i]->getName() << std::endl;
out << " * Dirty Link Transforms: " << (dirty_link_transforms_ ? dirty_link_transforms_->getName() : "NULL")
<< std::endl;
out << " * Dirty Collision Body Transforms: "
<< (dirty_collision_body_transforms_ ? dirty_collision_body_transforms_->getName() : "NULL") << std::endl;
}
void RobotState::printStateInfo(std::ostream& out) const
{
out << "Robot State @" << this << std::endl;
std::size_t n = robot_model_->getVariableCount();
if (position_)
{
out << " * Position: ";
for (std::size_t i = 0; i < n; ++i)
out << position_[i] << " ";
out << std::endl;
}
else
out << " * Position: NULL" << std::endl;
if (velocity_)
{
out << " * Velocity: ";
for (std::size_t i = 0; i < n; ++i)
out << velocity_[i] << " ";
out << std::endl;
}
else
out << " * Velocity: NULL" << std::endl;
if (acceleration_)
{
out << " * Acceleration: ";
for (std::size_t i = 0; i < n; ++i)
out << acceleration_[i] << " ";
out << std::endl;
}
else
out << " * Acceleration: NULL" << std::endl;
out << " * Dirty Link Transforms: " << (dirty_link_transforms_ ? dirty_link_transforms_->getName() : "NULL")
<< std::endl;
out << " * Dirty Collision Body Transforms: "
<< (dirty_collision_body_transforms_ ? dirty_collision_body_transforms_->getName() : "NULL") << std::endl;
printTransforms(out);
}
void RobotState::printTransform(const Eigen::Isometry3d& transform, std::ostream& out) const
{
Eigen::Quaterniond q(transform.rotation());
out << "T.xyz = [" << transform.translation().x() << ", " << transform.translation().y() << ", "
<< transform.translation().z() << "], Q.xyzw = [" << q.x() << ", " << q.y() << ", " << q.z() << ", " << q.w()
<< "]" << std::endl;
}
void RobotState::printTransforms(std::ostream& out) const
{
if (!variable_joint_transforms_)
{
out << "No transforms computed" << std::endl;
return;
}
out << "Joint transforms:" << std::endl;
const std::vector<const JointModel*>& jm = robot_model_->getJointModels();
for (std::size_t i = 0; i < jm.size(); ++i)
{
out << " " << jm[i]->getName();
const int idx = jm[i]->getJointIndex();
if (dirty_joint_transforms_[idx])
out << " [dirty]";
out << ": ";
printTransform(variable_joint_transforms_[idx], out);
}
out << "Link poses:" << std::endl;
const std::vector<const LinkModel*>& lm = robot_model_->getLinkModels();
for (std::size_t i = 0; i < lm.size(); ++i)
{
out << " " << lm[i]->getName() << ": ";
printTransform(global_link_transforms_[lm[i]->getLinkIndex()], out);
}
}
std::string RobotState::getStateTreeString(const std::string& prefix) const
{
std::stringstream ss;
ss << "ROBOT: " << robot_model_->getName() << std::endl;
getStateTreeJointString(ss, robot_model_->getRootJoint(), " ", true);
return ss.str();
}
namespace
{
void getPoseString(std::ostream& ss, const Eigen::Isometry3d& pose, const std::string& pfx)
{
ss.precision(3);
for (int y = 0; y < 4; ++y)
{
ss << pfx;
for (int x = 0; x < 4; ++x)
{
ss << std::setw(8) << pose(y, x) << " ";
}
ss << std::endl;
}
}
}
void RobotState::getStateTreeJointString(std::ostream& ss, const JointModel* jm, const std::string& pfx0,
bool last) const
{
std::string pfx = pfx0 + "+--";
ss << pfx << "Joint: " << jm->getName() << std::endl;
pfx = pfx0 + (last ? " " : "| ");
for (std::size_t i = 0; i < jm->getVariableCount(); ++i)
{
ss.precision(3);
ss << pfx << jm->getVariableNames()[i] << std::setw(12) << position_[jm->getFirstVariableIndex() + i] << std::endl;
}
const LinkModel* lm = jm->getChildLinkModel();
ss << pfx << "Link: " << lm->getName() << std::endl;
getPoseString(ss, lm->getJointOriginTransform(), pfx + "joint_origin:");
if (variable_joint_transforms_)
{
getPoseString(ss, variable_joint_transforms_[jm->getJointIndex()], pfx + "joint_variable:");
getPoseString(ss, global_link_transforms_[lm->getLinkIndex()], pfx + "link_global:");
}
for (std::vector<const JointModel*>::const_iterator it = lm->getChildJointModels().begin();
it != lm->getChildJointModels().end(); ++it)
getStateTreeJointString(ss, *it, pfx, it + 1 == lm->getChildJointModels().end());
}
std::ostream& operator<<(std::ostream& out, const RobotState& s)
{
s.printStateInfo(out);
return out;
}
} // end of namespace core
} // end of namespace moveit
| 38.648093 | 120 | 0.668633 | [
"mesh",
"geometry",
"render",
"object",
"vector",
"transform"
] |
4f2e6d9aa6d3b7a32ef5aec61e4c8687eb6d5447 | 3,397 | cpp | C++ | doc/code_examples/Tutorial_PeakIntensityPredictor.cpp | raghav17083/OpenMS | ddcdd3068a93a7c415675c39bac43d796a845f1d | [
"BSL-1.0",
"Apache-2.0",
"Zlib"
] | null | null | null | doc/code_examples/Tutorial_PeakIntensityPredictor.cpp | raghav17083/OpenMS | ddcdd3068a93a7c415675c39bac43d796a845f1d | [
"BSL-1.0",
"Apache-2.0",
"Zlib"
] | null | null | null | doc/code_examples/Tutorial_PeakIntensityPredictor.cpp | raghav17083/OpenMS | ddcdd3068a93a7c415675c39bac43d796a845f1d | [
"BSL-1.0",
"Apache-2.0",
"Zlib"
] | null | null | null | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2017.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#include <OpenMS/ANALYSIS/PIP/PeakIntensityPredictor.h>
#include <iostream>
using namespace OpenMS;
using namespace std;
Int main()
{
//Create a vector for the predicted values that is large enough to hold them all
vector<AASequence> peptides;
peptides.push_back(AASequence::fromString("IVGLMPHPEHAVEK"));
peptides.push_back(AASequence::fromString("LADNISNAMQGISEATEPR"));
peptides.push_back(AASequence::fromString("ELDHSDTIEVIVNPEDIDYDAASEQAR"));
peptides.push_back(AASequence::fromString("AVDTVR"));
peptides.push_back(AASequence::fromString("AAWQVK"));
peptides.push_back(AASequence::fromString("FLGTQGR"));
peptides.push_back(AASequence::fromString("NYPSDWSDVDTK"));
peptides.push_back(AASequence::fromString("GSPSFGPESISTETWSAEPYGR"));
peptides.push_back(AASequence::fromString("TELGFDPEAHFAIDDEVIAHTR"));
//Create new predictor model with vector of AASequences
PeakIntensityPredictor model;
//Perform prediction with LLM model
vector<double> predicted = model.predict(peptides);
//for each element in peptides print sequence as well as corresponding predicted peak intensity value.
for (Size i = 0; i < peptides.size(); i++)
{
cout << "Intensity of " << peptides[i] << " is " << predicted[i] << endl;
}
return 0;
} //end of main
| 48.528571 | 104 | 0.66912 | [
"vector",
"model"
] |
4f33474e647d911053f4fec178c13c99202421c3 | 16,466 | cpp | C++ | Project 10-17/Common/d3dUtil.cpp | MKXJun/DX11-Without-DirectX-SDK | 31756de150248fc8f4ccb6ce0c5e2837da718c2d | [
"MIT"
] | 3 | 2018-05-29T12:18:08.000Z | 2018-06-20T16:14:13.000Z | Project 10-17/Common/d3dUtil.cpp | MKXJun/DX11-Without-DirectX-SDK | 31756de150248fc8f4ccb6ce0c5e2837da718c2d | [
"MIT"
] | null | null | null | Project 10-17/Common/d3dUtil.cpp | MKXJun/DX11-Without-DirectX-SDK | 31756de150248fc8f4ccb6ce0c5e2837da718c2d | [
"MIT"
] | null | null | null | #include "d3dUtil.h"
using namespace DirectX;
//
// 函数定义部分
//
HRESULT CreateShaderFromFile(
const WCHAR * csoFileNameInOut,
const WCHAR * hlslFileName,
LPCSTR entryPoint,
LPCSTR shaderModel,
ID3DBlob ** ppBlobOut)
{
HRESULT hr = S_OK;
// 寻找是否有已经编译好的顶点着色器
if (csoFileNameInOut && D3DReadFileToBlob(csoFileNameInOut, ppBlobOut) == S_OK)
{
return hr;
}
else
{
DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#ifdef _DEBUG
// 设置 D3DCOMPILE_DEBUG 标志用于获取着色器调试信息。该标志可以提升调试体验,
// 但仍然允许着色器进行优化操作
dwShaderFlags |= D3DCOMPILE_DEBUG;
// 在Debug环境下禁用优化以避免出现一些不合理的情况
dwShaderFlags |= D3DCOMPILE_SKIP_OPTIMIZATION;
#endif
ID3DBlob* errorBlob = nullptr;
hr = D3DCompileFromFile(hlslFileName, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryPoint, shaderModel,
dwShaderFlags, 0, ppBlobOut, &errorBlob);
if (FAILED(hr))
{
if (errorBlob != nullptr)
{
OutputDebugStringA(reinterpret_cast<const char*>(errorBlob->GetBufferPointer()));
}
SAFE_RELEASE(errorBlob);
return hr;
}
// 若指定了输出文件名,则将着色器二进制信息输出
if (csoFileNameInOut)
{
return D3DWriteBlobToFile(*ppBlobOut, csoFileNameInOut, FALSE);
}
}
return hr;
}
HRESULT CreateTexture2DArrayFromFile(
ID3D11Device* d3dDevice,
ID3D11DeviceContext* d3dDeviceContext,
const std::vector<std::wstring>& fileNames,
ID3D11Texture2D** textureArray,
ID3D11ShaderResourceView** textureArrayView,
bool generateMips)
{
// 检查设备、文件名数组是否非空
if (!d3dDevice || fileNames.empty())
return E_INVALIDARG;
HRESULT hr;
UINT arraySize = (UINT)fileNames.size();
// ******************
// 读取第一个纹理
//
ID3D11Texture2D* pTexture;
D3D11_TEXTURE2D_DESC texDesc;
hr = CreateDDSTextureFromFileEx(d3dDevice,
fileNames[0].c_str(), 0, D3D11_USAGE_STAGING, 0,
D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ,
0, false, reinterpret_cast<ID3D11Resource**>(&pTexture), nullptr);
if (FAILED(hr))
{
hr = CreateWICTextureFromFileEx(d3dDevice,
fileNames[0].c_str(), 0, D3D11_USAGE_STAGING, 0,
D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ,
0, WIC_LOADER_DEFAULT, reinterpret_cast<ID3D11Resource**>(&pTexture), nullptr);
}
if (FAILED(hr))
return hr;
// 读取创建好的纹理信息
pTexture->GetDesc(&texDesc);
// ******************
// 创建纹理数组
//
D3D11_TEXTURE2D_DESC texArrayDesc;
texArrayDesc.Width = texDesc.Width;
texArrayDesc.Height = texDesc.Height;
texArrayDesc.MipLevels = generateMips ? 0 : texDesc.MipLevels;
texArrayDesc.ArraySize = arraySize;
texArrayDesc.Format = texDesc.Format;
texArrayDesc.SampleDesc.Count = 1; // 不能使用多重采样
texArrayDesc.SampleDesc.Quality = 0;
texArrayDesc.Usage = D3D11_USAGE_DEFAULT;
texArrayDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | (generateMips ? D3D11_BIND_RENDER_TARGET : 0);
texArrayDesc.CPUAccessFlags = 0;
texArrayDesc.MiscFlags = (generateMips ? D3D11_RESOURCE_MISC_GENERATE_MIPS : 0);
ID3D11Texture2D* pTexArray = nullptr;
hr = d3dDevice->CreateTexture2D(&texArrayDesc, nullptr, &pTexArray);
if (FAILED(hr))
{
SAFE_RELEASE(pTexture);
return hr;
}
// 获取实际创建的纹理数组信息
pTexArray->GetDesc(&texArrayDesc);
UINT updateMipLevels = generateMips ? 1 : texArrayDesc.MipLevels;
// 写入到纹理数组第一个元素
D3D11_MAPPED_SUBRESOURCE mappedTex2D;
for (UINT i = 0; i < updateMipLevels; ++i)
{
d3dDeviceContext->Map(pTexture, i, D3D11_MAP_READ, 0, &mappedTex2D);
d3dDeviceContext->UpdateSubresource(pTexArray, i, nullptr,
mappedTex2D.pData, mappedTex2D.RowPitch, mappedTex2D.DepthPitch);
d3dDeviceContext->Unmap(pTexture, i);
}
SAFE_RELEASE(pTexture);
// ******************
// 读取剩余的纹理并加载入纹理数组
//
D3D11_TEXTURE2D_DESC currTexDesc;
for (UINT i = 1; i < texArrayDesc.ArraySize; ++i)
{
hr = CreateDDSTextureFromFileEx(d3dDevice,
fileNames[i].c_str(), 0, D3D11_USAGE_STAGING, 0,
D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ,
0, false, reinterpret_cast<ID3D11Resource**>(&pTexture), nullptr);
if (FAILED(hr))
{
hr = CreateWICTextureFromFileEx(d3dDevice,
fileNames[i].c_str(), 0, D3D11_USAGE_STAGING, 0,
D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ,
0, WIC_LOADER_DEFAULT, reinterpret_cast<ID3D11Resource**>(&pTexture), nullptr);
}
if (FAILED(hr))
{
SAFE_RELEASE(pTexArray);
return hr;
}
pTexture->GetDesc(&currTexDesc);
// 需要检验所有纹理的mipLevels,宽度和高度,数据格式是否一致,
// 若存在数据格式不一致的情况,请使用dxtex.exe(DirectX Texture Tool)
// 将所有的图片转成一致的数据格式
if (currTexDesc.MipLevels != texDesc.MipLevels || currTexDesc.Width != texDesc.Width ||
currTexDesc.Height != texDesc.Height || currTexDesc.Format != texDesc.Format)
{
SAFE_RELEASE(pTexArray);
SAFE_RELEASE(pTexture);
return E_FAIL;
}
// 写入到纹理数组的对应元素
for (UINT j = 0; j < updateMipLevels; ++j)
{
// 允许映射索引i纹理中,索引j的mipmap等级的2D纹理
d3dDeviceContext->Map(pTexture, j, D3D11_MAP_READ, 0, &mappedTex2D);
d3dDeviceContext->UpdateSubresource(pTexArray,
D3D11CalcSubresource(j, i, texArrayDesc.MipLevels), // i * mipLevel + j
nullptr, mappedTex2D.pData, mappedTex2D.RowPitch, mappedTex2D.DepthPitch);
// 停止映射
d3dDeviceContext->Unmap(pTexture, j);
}
SAFE_RELEASE(pTexture);
}
// ******************
// 必要时创建纹理数组的SRV
//
if (generateMips || textureArrayView)
{
D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc;
viewDesc.Format = texArrayDesc.Format;
viewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
viewDesc.Texture2DArray.MostDetailedMip = 0;
viewDesc.Texture2DArray.MipLevels = -1;
viewDesc.Texture2DArray.FirstArraySlice = 0;
viewDesc.Texture2DArray.ArraySize = arraySize;
ID3D11ShaderResourceView* pTexArraySRV;
hr = d3dDevice->CreateShaderResourceView(pTexArray, &viewDesc, &pTexArraySRV);
if (FAILED(hr))
{
SAFE_RELEASE(pTexArray);
return hr;
}
// 生成mipmaps
if (generateMips)
{
d3dDeviceContext->GenerateMips(pTexArraySRV);
}
if (textureArrayView)
*textureArrayView = pTexArraySRV;
else
SAFE_RELEASE(pTexArraySRV);
}
if (textureArray)
*textureArray = pTexArray;
else
SAFE_RELEASE(pTexArray);
return S_OK;
}
HRESULT CreateWICTexture2DCubeFromFile(
ID3D11Device * d3dDevice,
ID3D11DeviceContext * d3dDeviceContext,
const std::wstring & cubeMapFileName,
ID3D11Texture2D ** textureArray,
ID3D11ShaderResourceView ** textureCubeView,
bool generateMips)
{
// 检查设备、设备上下文是否非空
// 纹理数组和纹理立方体视图只要有其中一个非空即可
if (!d3dDevice || !d3dDeviceContext || !(textureArray || textureCubeView))
return E_INVALIDARG;
// ******************
// 读取天空盒纹理
//
ID3D11Texture2D* srcTex = nullptr;
ID3D11ShaderResourceView* srcTexSRV = nullptr;
// 该资源用于GPU复制
HRESULT hResult = CreateWICTextureFromFile(d3dDevice,
(generateMips ? d3dDeviceContext : nullptr),
cubeMapFileName.c_str(),
(ID3D11Resource**)&srcTex,
(generateMips ? &srcTexSRV : nullptr));
// 文件未打开
if (FAILED(hResult))
{
return hResult;
}
D3D11_TEXTURE2D_DESC texDesc, texArrayDesc;
srcTex->GetDesc(&texDesc);
// 要求宽高比4:3
if (texDesc.Width * 3 != texDesc.Height * 4)
{
SAFE_RELEASE(srcTex);
SAFE_RELEASE(srcTexSRV);
return E_FAIL;
}
// ******************
// 创建包含6个纹理的数组
//
UINT squareLength = texDesc.Width / 4;
texArrayDesc.Width = squareLength;
texArrayDesc.Height = squareLength;
texArrayDesc.MipLevels = (generateMips ? texDesc.MipLevels - 2 : 1); // 立方体的mip等级比整张位图的少2
texArrayDesc.ArraySize = 6;
texArrayDesc.Format = texDesc.Format;
texArrayDesc.SampleDesc.Count = 1;
texArrayDesc.SampleDesc.Quality = 0;
texArrayDesc.Usage = D3D11_USAGE_DEFAULT;
texArrayDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
texArrayDesc.CPUAccessFlags = 0;
texArrayDesc.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE; // 允许从中创建TextureCube
ID3D11Texture2D* texArray = nullptr;
hResult = d3dDevice->CreateTexture2D(&texArrayDesc, nullptr, &texArray);
if (FAILED(hResult))
{
SAFE_RELEASE(srcTex);
SAFE_RELEASE(srcTexSRV);
return hResult;
}
// ******************
// 选取原天空盒纹理的6个子正方形区域,拷贝到该数组中
//
D3D11_BOX box;
// box坐标轴如下:
// front
// /
// /_____right
// |
// |
// bottom
box.front = 0;
box.back = 1;
for (UINT i = 0; i < texArrayDesc.MipLevels; ++i)
{
// +X面拷贝
box.left = squareLength * 2;
box.top = squareLength;
box.right = squareLength * 3;
box.bottom = squareLength * 2;
d3dDeviceContext->CopySubresourceRegion(
texArray,
D3D11CalcSubresource(i, D3D11_TEXTURECUBE_FACE_POSITIVE_X, texArrayDesc.MipLevels),
0, 0, 0,
srcTex,
i,
&box);
// -X面拷贝
box.left = 0;
box.top = squareLength;
box.right = squareLength;
box.bottom = squareLength * 2;
d3dDeviceContext->CopySubresourceRegion(
texArray,
D3D11CalcSubresource(i, D3D11_TEXTURECUBE_FACE_NEGATIVE_X, texArrayDesc.MipLevels),
0, 0, 0,
srcTex,
i,
&box);
// +Y面拷贝
box.left = squareLength;
box.top = 0;
box.right = squareLength * 2;
box.bottom = squareLength;
d3dDeviceContext->CopySubresourceRegion(
texArray,
D3D11CalcSubresource(i, D3D11_TEXTURECUBE_FACE_POSITIVE_Y, texArrayDesc.MipLevels),
0, 0, 0,
srcTex,
i,
&box);
// -Y面拷贝
box.left = squareLength;
box.top = squareLength * 2;
box.right = squareLength * 2;
box.bottom = squareLength * 3;
d3dDeviceContext->CopySubresourceRegion(
texArray,
D3D11CalcSubresource(i, D3D11_TEXTURECUBE_FACE_NEGATIVE_Y, texArrayDesc.MipLevels),
0, 0, 0,
srcTex,
i,
&box);
// +Z面拷贝
box.left = squareLength;
box.top = squareLength;
box.right = squareLength * 2;
box.bottom = squareLength * 2;
d3dDeviceContext->CopySubresourceRegion(
texArray,
D3D11CalcSubresource(i, D3D11_TEXTURECUBE_FACE_POSITIVE_Z, texArrayDesc.MipLevels),
0, 0, 0,
srcTex,
i,
&box);
// -Z面拷贝
box.left = squareLength * 3;
box.top = squareLength;
box.right = squareLength * 4;
box.bottom = squareLength * 2;
d3dDeviceContext->CopySubresourceRegion(
texArray,
D3D11CalcSubresource(i, D3D11_TEXTURECUBE_FACE_NEGATIVE_Z, texArrayDesc.MipLevels),
0, 0, 0,
srcTex,
i,
&box);
// 下一个mipLevel的纹理宽高都是原来的1/2
squareLength /= 2;
}
// ******************
// 创建立方体纹理的SRV
//
if (textureCubeView)
{
D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc;
viewDesc.Format = texArrayDesc.Format;
viewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
viewDesc.TextureCube.MostDetailedMip = 0;
viewDesc.TextureCube.MipLevels = texArrayDesc.MipLevels;
hResult = d3dDevice->CreateShaderResourceView(texArray, &viewDesc, textureCubeView);
}
// 检查是否需要纹理数组
if (textureArray)
{
*textureArray = texArray;
}
else
{
SAFE_RELEASE(texArray);
}
SAFE_RELEASE(srcTex);
SAFE_RELEASE(srcTexSRV);
return hResult;
}
HRESULT CreateWICTexture2DCubeFromFile(
ID3D11Device * d3dDevice,
ID3D11DeviceContext * d3dDeviceContext,
const std::vector<std::wstring>& cubeMapFileNames,
ID3D11Texture2D ** textureArray,
ID3D11ShaderResourceView ** textureCubeView,
bool generateMips)
{
// 检查设备与设备上下文是否非空
// 文件名数目需要不小于6
// 纹理数组和资源视图只要有其中一个非空即可
UINT arraySize = (UINT)cubeMapFileNames.size();
if (!d3dDevice || !d3dDeviceContext || arraySize < 6 || !(textureArray || textureCubeView))
return E_INVALIDARG;
// ******************
// 读取纹理
//
HRESULT hResult;
std::vector<ID3D11Texture2D*> srcTexVec(arraySize, nullptr);
std::vector<ID3D11ShaderResourceView*> srcTexSRVVec(arraySize, nullptr);
std::vector<D3D11_TEXTURE2D_DESC> texDescVec(arraySize);
for (UINT i = 0; i < arraySize; ++i)
{
// 该资源用于GPU复制
hResult = CreateWICTextureFromFile(d3dDevice,
(generateMips ? d3dDeviceContext : nullptr),
cubeMapFileNames[i].c_str(),
(ID3D11Resource**)&srcTexVec[i],
(generateMips ? &srcTexSRVVec[i] : nullptr));
// 文件未打开
if (hResult != S_OK)
return hResult;
// 读取创建好的纹理信息
srcTexVec[i]->GetDesc(&texDescVec[i]);
// 需要检验所有纹理的mipLevels,宽度和高度,数据格式是否一致,
// 若存在数据格式不一致的情况,请使用dxtex.exe(DirectX Texture Tool)
// 将所有的图片转成一致的数据格式
if (texDescVec[i].MipLevels != texDescVec[0].MipLevels || texDescVec[i].Width != texDescVec[0].Width ||
texDescVec[i].Height != texDescVec[0].Height || texDescVec[i].Format != texDescVec[0].Format)
{
for (UINT j = 0; j < i; ++j)
{
SAFE_RELEASE(srcTexVec[j]);
SAFE_RELEASE(srcTexSRVVec[j]);
}
return E_FAIL;
}
}
// ******************
// 创建纹理数组
//
D3D11_TEXTURE2D_DESC texArrayDesc;
texArrayDesc.Width = texDescVec[0].Width;
texArrayDesc.Height = texDescVec[0].Height;
texArrayDesc.MipLevels = (generateMips ? texDescVec[0].MipLevels : 1);
texArrayDesc.ArraySize = arraySize;
texArrayDesc.Format = texDescVec[0].Format;
texArrayDesc.SampleDesc.Count = 1;
texArrayDesc.SampleDesc.Quality = 0;
texArrayDesc.Usage = D3D11_USAGE_DEFAULT;
texArrayDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
texArrayDesc.CPUAccessFlags = 0;
texArrayDesc.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE; // 允许从中创建TextureCube
ID3D11Texture2D* texArray = nullptr;
hResult = d3dDevice->CreateTexture2D(&texArrayDesc, nullptr, &texArray);
if (FAILED(hResult))
{
for (UINT i = 0; i < arraySize; ++i)
{
SAFE_RELEASE(srcTexVec[i]);
SAFE_RELEASE(srcTexSRVVec[i]);
}
return hResult;
}
// ******************
// 将原纹理的所有子资源拷贝到该数组中
//
texArray->GetDesc(&texArrayDesc);
for (UINT i = 0; i < arraySize; ++i)
{
for (UINT j = 0; j < texArrayDesc.MipLevels; ++j)
{
d3dDeviceContext->CopySubresourceRegion(
texArray,
D3D11CalcSubresource(j, i, texArrayDesc.MipLevels),
0, 0, 0,
srcTexVec[i],
j,
nullptr);
}
}
// ******************
// 创建立方体纹理的SRV
//
if (textureCubeView)
{
D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc;
viewDesc.Format = texArrayDesc.Format;
viewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
viewDesc.TextureCube.MostDetailedMip = 0;
viewDesc.TextureCube.MipLevels = texArrayDesc.MipLevels;
hResult = d3dDevice->CreateShaderResourceView(texArray, &viewDesc, textureCubeView);
}
// 检查是否需要纹理数组
if (textureArray)
{
*textureArray = texArray;
}
else
{
SAFE_RELEASE(texArray);
}
// 释放所有资源
for (UINT i = 0; i < arraySize; ++i)
{
SAFE_RELEASE(srcTexVec[i]);
SAFE_RELEASE(srcTexSRVVec[i]);
}
return hResult;
}
| 29.195035 | 114 | 0.606765 | [
"vector"
] |
4f340fa1932218d1419b55c4ada7cfdbd0962315 | 5,018 | cc | C++ | chrome/browser/tab/state/tab_state_db.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/tab/state/tab_state_db.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/tab/state/tab_state_db.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/tab/state/tab_state_db.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/files/file_path.h"
#include "base/strings/string_util.h"
#include "base/task/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
#include "components/leveldb_proto/public/proto_database_provider.h"
namespace {
const char kTabStateDBFolder[] = "tab_state_db";
leveldb::ReadOptions CreateReadOptions() {
leveldb::ReadOptions opts;
opts.fill_cache = false;
return opts;
}
bool DatabasePrefixFilter(const std::string& key_prefix,
const std::string& key) {
return base::StartsWith(key, key_prefix, base::CompareCase::SENSITIVE);
}
} // namespace
TabStateDB::~TabStateDB() = default;
bool TabStateDB::IsInitialized() const {
return database_status_ == leveldb_proto::Enums::InitStatus::kOK;
}
void TabStateDB::LoadContent(const std::string& key, LoadCallback callback) {
storage_database_->LoadEntriesWithFilter(
base::BindRepeating(&DatabasePrefixFilter, key), CreateReadOptions(),
/* target_prefix */ "",
base::BindOnce(&TabStateDB::OnLoadContent, weak_ptr_factory_.GetWeakPtr(),
std::move(callback)));
}
void TabStateDB::InsertContent(const std::string& key,
const std::vector<uint8_t>& value,
OperationCallback callback) {
auto contents_to_save = std::make_unique<ContentEntry>();
tab_state_db::TabStateContentProto proto;
proto.set_key(key);
proto.set_content_data(value.data(), value.size());
contents_to_save->emplace_back(proto.key(), std::move(proto));
storage_database_->UpdateEntries(
std::move(contents_to_save), std::make_unique<std::vector<std::string>>(),
base::BindOnce(&TabStateDB::OnOperationCommitted,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void TabStateDB::DeleteContent(const std::string& key,
OperationCallback callback) {
storage_database_->UpdateEntriesWithRemoveFilter(
std::make_unique<ContentEntry>(),
std::move(base::BindRepeating(&DatabasePrefixFilter, std::move(key))),
base::BindOnce(&TabStateDB::OnOperationCommitted,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void TabStateDB::DeleteAllContent(OperationCallback callback) {
storage_database_->Destroy(std::move(callback));
}
TabStateDB::TabStateDB(
leveldb_proto::ProtoDatabaseProvider* proto_database_provider,
const base::FilePath& profile_directory)
: database_status_(leveldb_proto::Enums::InitStatus::kNotInitialized),
storage_database_(
proto_database_provider->GetDB<tab_state_db::TabStateContentProto>(
leveldb_proto::ProtoDbType::TAB_STATE_DATABASE,
profile_directory.AppendASCII(kTabStateDBFolder),
base::CreateSequencedTaskRunner(
{base::ThreadPool(), base::MayBlock(),
base::TaskPriority::USER_VISIBLE}))) {
storage_database_->Init(base::BindOnce(&TabStateDB::OnDatabaseInitialized,
weak_ptr_factory_.GetWeakPtr(),
base::DoNothing::Once()));
}
TabStateDB::TabStateDB(
std::unique_ptr<leveldb_proto::ProtoDatabase<
tab_state_db::TabStateContentProto>> storage_database,
scoped_refptr<base::SequencedTaskRunner> task_runner,
base::OnceClosure closure)
: database_status_(leveldb_proto::Enums::InitStatus::kNotInitialized),
storage_database_(std::move(storage_database)) {
storage_database_->Init(base::BindOnce(&TabStateDB::OnDatabaseInitialized,
weak_ptr_factory_.GetWeakPtr(),
std::move(closure)));
}
void TabStateDB::OnDatabaseInitialized(
base::OnceClosure closure,
leveldb_proto::Enums::InitStatus status) {
DCHECK_EQ(database_status_,
leveldb_proto::Enums::InitStatus::kNotInitialized);
database_status_ = status;
std::move(closure).Run();
}
void TabStateDB::OnLoadContent(
LoadCallback callback,
bool success,
std::unique_ptr<std::vector<tab_state_db::TabStateContentProto>> content) {
std::vector<KeyAndValue> results;
if (success) {
for (const auto& proto : *content) {
DCHECK(proto.has_key());
DCHECK(proto.has_content_data());
results.emplace_back(proto.key(),
std::vector<uint8_t>(proto.content_data().begin(),
proto.content_data().end()));
}
}
std::move(callback).Run(success, std::move(results));
}
void TabStateDB::OnOperationCommitted(OperationCallback callback,
bool success) {
std::move(callback).Run(success);
}
| 38.6 | 80 | 0.674372 | [
"vector"
] |
4f34461e878e2e5ca75d8f8d37046cbc9af2c62a | 2,932 | cpp | C++ | src/chrono/motion_functions/ChFunctionRotation_ABCfunctions.cpp | zzhou292/chrono-collision | c2a20e171bb0eb8819636d370887aa32d68547c6 | [
"BSD-3-Clause"
] | 1 | 2021-12-09T05:24:42.000Z | 2021-12-09T05:24:42.000Z | src/chrono/motion_functions/ChFunctionRotation_ABCfunctions.cpp | zzhou292/chrono-collision | c2a20e171bb0eb8819636d370887aa32d68547c6 | [
"BSD-3-Clause"
] | 7 | 2021-10-20T04:43:35.000Z | 2021-12-24T08:44:31.000Z | src/chrono/motion_functions/ChFunctionRotation_ABCfunctions.cpp | zzhou292/chrono-collision | c2a20e171bb0eb8819636d370887aa32d68547c6 | [
"BSD-3-Clause"
] | 2 | 2021-12-09T05:32:31.000Z | 2021-12-12T17:31:18.000Z | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Alessandro Tasora
// =============================================================================
#include "chrono/motion_functions/ChFunctionRotation_ABCfunctions.h"
#include "chrono/motion_functions/ChFunction_Const.h"
namespace chrono {
// Register into the object factory, to enable run-time dynamic creation and persistence
CH_FACTORY_REGISTER(ChFunctionRotation_ABCfunctions)
ChFunctionRotation_ABCfunctions::ChFunctionRotation_ABCfunctions() {
// default s(t) function. User will provide better fx.
this->angleA = chrono_types::make_shared<ChFunction_Const>(0);
this->angleB = chrono_types::make_shared<ChFunction_Const>(0);
this->angleC = chrono_types::make_shared<ChFunction_Const>(0);
this->angleset = AngleSet::RXYZ;
}
ChFunctionRotation_ABCfunctions::ChFunctionRotation_ABCfunctions(const ChFunctionRotation_ABCfunctions& other) {
this->angleA = std::shared_ptr<ChFunction>(other.angleA->Clone());
this->angleB = std::shared_ptr<ChFunction>(other.angleB->Clone());
this->angleC = std::shared_ptr<ChFunction>(other.angleC->Clone());
this->angleset = other.angleset;
}
ChFunctionRotation_ABCfunctions::~ChFunctionRotation_ABCfunctions() {
}
ChQuaternion<> ChFunctionRotation_ABCfunctions::Get_q(double s) const {
return Angle_to_Quat(this->angleset,
ChVector<>(
this->angleA->Get_y(s),
this->angleB->Get_y(s),
this->angleC->Get_y(s)
)
);
}
void ChFunctionRotation_ABCfunctions::ArchiveOUT(ChArchiveOut& marchive) {
// version number
marchive.VersionWrite<ChFunctionRotation_ABCfunctions>();
// serialize parent class
ChFunctionRotation::ArchiveOUT(marchive);
// serialize all member data:
marchive << CHNVP(angleA);
marchive << CHNVP(angleB);
marchive << CHNVP(angleC);
marchive << CHNVP((int)angleset); //***TODO: use CH_ENUM_MAPPER_BEGIN ... END to serialize enum with readable names
}
void ChFunctionRotation_ABCfunctions::ArchiveIN(ChArchiveIn& marchive) {
// version number
int version = marchive.VersionRead<ChFunctionRotation_ABCfunctions>();
// deserialize parent class
ChFunctionRotation::ArchiveIN(marchive);
// deserialize all member data:
marchive >> CHNVP(angleA);
marchive >> CHNVP(angleB);
marchive >> CHNVP(angleC);
int foo;
marchive >> CHNVP(foo);
angleset = (AngleSet)foo; //***TODO: use CH_ENUM_MAPPER_BEGIN ... END to serialize enum with readable names
}
} // end namespace chrono | 32.577778 | 116 | 0.682128 | [
"object"
] |
4f34f04d5fbeb229c8c1316d27c6f64bd01116f8 | 4,654 | cc | C++ | mindspore/ccsrc/backend/optimizer/graph_kernel/shape_ops_splitter.cc | glucklichste/mindspore | 9df63697af663836fc18d03fef40715f093a3fa1 | [
"Apache-2.0"
] | 3,200 | 2020-02-17T12:45:41.000Z | 2022-03-31T20:21:16.000Z | mindspore/ccsrc/backend/optimizer/graph_kernel/shape_ops_splitter.cc | zimo-geek/mindspore | 665ec683d4af85c71b2a1f0d6829356f2bc0e1ff | [
"Apache-2.0"
] | 176 | 2020-02-12T02:52:11.000Z | 2022-03-28T22:15:55.000Z | mindspore/ccsrc/backend/optimizer/graph_kernel/shape_ops_splitter.cc | zimo-geek/mindspore | 665ec683d4af85c71b2a1f0d6829356f2bc0e1ff | [
"Apache-2.0"
] | 621 | 2020-03-09T01:31:41.000Z | 2022-03-30T03:43:19.000Z | /**
* Copyright 2020-2021 Huawei Technologies Co., Ltd
*
* 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 "backend/optimizer/graph_kernel/shape_ops_splitter.h"
#include <algorithm>
#include <vector>
#include <set>
#include <string>
#include <utility>
#include <queue>
#include <map>
#include "frontend/optimizer/irpass.h"
#include "pipeline/jit/parse/python_adapter.h"
#include "backend/session/anf_runtime_algorithm.h"
#include "backend/kernel_compiler/common_utils.h"
#include "backend/kernel_compiler/akg/akg_kernel_json_decoder.h"
#include "backend/optimizer/graph_kernel/graph_kernel_helper.h"
#include "debug/anf_ir_dump.h"
namespace mindspore::graphkernel {
namespace {
AnfNodePtr CloneCNode(const AnfNodePtr &anf_node) {
auto func_graph = anf_node->func_graph();
MS_EXCEPTION_IF_NULL(func_graph);
auto cnode = anf_node->cast<CNodePtr>();
MS_EXCEPTION_IF_NULL(cnode);
TraceGuard guard(std::make_shared<TraceOpt>(cnode->debug_info()));
CNodePtr node = func_graph->NewCNode(cnode->inputs());
node->set_abstract(cnode->abstract());
node->set_forward(cnode->forward().first, cnode->forward().second);
node->set_inputs_value(cnode->inputs_value());
ScopePtr scope = (anf_node->scope() != kDefaultScope) ? anf_node->scope() : kDefaultScope;
node->set_scope(scope);
node->set_kernel_info(cnode->kernel_info_ptr());
node->set_primal_attrs(cnode->primal_attrs());
node->set_primal_debug_infos(cnode->primal_debug_infos());
return node;
}
void SplitNode(const AnfNodePtr &node, const FuncGraphManagerPtr &mng) {
const auto &index_set = mng->node_users()[node];
std::map<AnfNodePtr, std::vector<int>> users_info;
std::for_each(index_set.cbegin(), index_set.cend(), [&users_info](const std::pair<AnfNodePtr, int> &iter) {
users_info[iter.first].push_back(iter.second);
});
AnfNodePtrList split_nodes;
for (size_t i = 0; i < users_info.size(); ++i) {
split_nodes.push_back(CloneCNode(node));
}
size_t i = 0;
for (auto [user, indices] : users_info) {
auto user_node = user->cast<CNodePtr>();
MS_EXCEPTION_IF_NULL(user_node);
for (auto index : indices) {
user_node->set_input(IntToSize(index), split_nodes[i]);
}
i++;
}
}
} // namespace
bool ShapeOpsSplitter::IsMultiUserShapeOps(const AnfNodePtr &node, const FuncGraphManagerPtr &mng) const {
auto &users = mng->node_users();
std::set<AnfNodePtr> user_set;
std::transform(users[node].cbegin(), users[node].cend(), std::inserter(user_set, user_set.end()),
[](const std::pair<AnfNodePtr, int> &iter) { return iter.first; });
return user_set.size() > 1 && std::any_of(shape_ops_.begin(), shape_ops_.end(),
[&node](const PrimitivePtr &prim) { return IsPrimitiveCNode(node, prim); });
}
bool ShapeOpsSplitter::Process(const FuncGraphPtr &func_graph) {
MS_EXCEPTION_IF_NULL(func_graph);
auto mng = func_graph->manager();
if (mng == nullptr) {
mng = Manage(func_graph, true);
func_graph->set_manager(mng);
}
bool changed = false;
auto todos = TopoSort(func_graph->get_return());
for (const auto &anf_node : todos) {
auto node = anf_node->cast<CNodePtr>();
if (node != nullptr && IsMultiUserShapeOps(node, mng)) {
SplitNode(node, mng);
changed = true;
}
}
if (changed) {
mng->RemoveRoots();
mng->KeepRoots({func_graph});
}
return changed;
}
bool ShapeOpsSplitter::Run(const FuncGraphPtr &func_graph) {
MS_EXCEPTION_IF_NULL(func_graph);
auto mng = func_graph->manager();
if (mng == nullptr) {
mng = Manage(func_graph, true);
func_graph->set_manager(mng);
}
auto todos = TopoSort(func_graph->get_return());
bool result = false;
for (const auto &anf_node : todos) {
if (AnfAlgo::IsGraphKernel(anf_node)) {
auto sub_graph = AnfAlgo::GetCNodeFuncGraphPtr(anf_node);
bool changed = false;
do {
changed = Process(sub_graph);
result = result || changed;
} while (changed);
}
}
if (result) {
mng->RemoveRoots();
mng->KeepRoots({func_graph});
}
return result;
}
} // namespace mindspore::graphkernel
| 34.220588 | 120 | 0.69725 | [
"vector",
"transform"
] |
4f352424083f4e4418abfefbd34b78867998625d | 6,920 | cpp | C++ | tests/unittests/ReproFXLib.cpp | suhib97/glow | 582625add4b99cfc20bdb824285bfeba1a7df4f8 | [
"Apache-2.0"
] | null | null | null | tests/unittests/ReproFXLib.cpp | suhib97/glow | 582625add4b99cfc20bdb824285bfeba1a7df4f8 | [
"Apache-2.0"
] | null | null | null | tests/unittests/ReproFXLib.cpp | suhib97/glow | 582625add4b99cfc20bdb824285bfeba1a7df4f8 | [
"Apache-2.0"
] | 1 | 2022-02-21T23:35:09.000Z | 2022-02-21T23:35:09.000Z | /**
* Copyright (c) Glow Contributors. See CONTRIBUTORS file.
*
* 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 "glow/glow/tests/unittests/ReproFXLib.h"
#include "glow/fb/fx/fx_glow/fx_glow.h"
#include "glow/glow/torch_glow/src/GlowCompileSpec.h"
#include <folly/dynamic.h>
#include <folly/json.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <torch/script.h>
#include <torch/torch.h>
#include <vector>
llvm::cl::OptionCategory reproTestCat("Repro Category");
llvm::cl::opt<std::string>
jsonPathOpt("json", llvm::cl::desc("Path to dumped JSON file"),
llvm::cl::value_desc("json path"), llvm::cl::Required,
llvm::cl::cat(reproTestCat));
llvm::cl::opt<std::string>
weightsPathOpt("weights", llvm::cl::desc("Path to dumped weights file"),
llvm::cl::value_desc("weights path"), llvm::cl::Required,
llvm::cl::cat(reproTestCat));
llvm::cl::opt<std::string>
inputPathOpt("inputs",
llvm::cl::desc("Path to dumped input file; leave blank for "
"when debugging lowering failures."),
llvm::cl::value_desc("input path"),
llvm::cl::cat(reproTestCat));
llvm::cl::opt<std::string>
compileSpecPathOpt("compile_spec",
llvm::cl::desc("Path to dumped compile spec."),
llvm::cl::cat(reproTestCat));
llvm::cl::opt<std::string>
backend("backend", llvm::cl::desc("Backend target for lowering."),
llvm::cl::value_desc("name of backend"), llvm::cl::init("NNPI"),
llvm::cl::cat(reproTestCat));
llvm::cl::opt<std::string> outputPathOpt(
"output",
llvm::cl::desc("Path to output file to be compared with reproFX output"),
llvm::cl::value_desc("output path"), llvm::cl::cat(reproTestCat));
// Parses JSON input, weights, and user inputs
void ReproFXLib::load(const folly::dynamic &data,
const torch::jit::script::Module &container,
const std::vector<char> &input) {
// Get runNetwork paramaters from data
// serialized_graph_json
serializedGraphJson = data[0].asString();
// nodes_json
nodesJson = data[1].asString();
// input_names
for (int i = 0; i < data[2].size(); i++) {
inputNames.push_back(data[2][i].asString());
}
// outputs
for (int i = 0; i < data[3].size(); i++) {
outputs.push_back(data[3][i].asString());
}
// tensor keys
for (int i = 0; i < data[4].size(); i++) {
keys.push_back(data[4][i].asString());
}
// Insert all pairs into TorchDict for passing into loadNetwork.
for (auto &key : keys) {
auto keyRef = llvm::StringRef(key);
auto modPathAndWeightName = keyRef.rsplit(".");
// Attribute is in the base module, i.e. "." isn't found.
if (modPathAndWeightName.second == "") {
torch::Tensor tensor = container.attr(key).toTensor();
weights.insert(key, tensor);
continue;
}
// Attribute is inside some recursive module, e.g. "a.b.c".
llvm::SmallVector<llvm::StringRef, 4> modNames;
modPathAndWeightName.first.split(modNames, ".");
auto currMod = container;
for (const auto &modName : modNames) {
currMod = currMod.attr(modName).toModule();
}
torch::Tensor tensor = currMod.attr(modPathAndWeightName.second).toTensor();
weights.insert(key, tensor);
}
if (input.size() != 0) {
// Load all inputs tensors
std::vector<at::IValue> tensors =
torch::pickle_load(input).toTupleRef().elements();
for (auto &i : tensors) {
torch::Tensor tensor = i.toTensor();
inputs.push_back(tensor);
}
}
}
void ReproFXLib::parseCommandLine(int argc, char **argv) {
llvm::cl::ParseCommandLineOptions(argc, argv);
// Load model JSON file
std::ifstream jsonFile(jsonPathOpt.c_str());
std::stringstream buffer;
buffer << jsonFile.rdbuf();
folly::dynamic data = folly::parseJson(buffer.str());
// Load weights file.
torch::jit::script::Module container =
torch::jit::load(weightsPathOpt.c_str());
// Load inputs file.
std::vector<char> input;
if (!inputPathOpt.empty()) {
std::ifstream inputStream(inputPathOpt.c_str());
inputStream >> std::noskipws;
input.insert(input.begin(), std::istream_iterator<char>(inputStream),
std::istream_iterator<char>());
}
load(data, container, input);
}
std::vector<torch::Tensor> ReproFXLib::run(bool fatalOnNotClose) {
// Create FXGlowCompileSpec.
glow::FXGlowCompileSpec compileSpec;
if (!compileSpecPathOpt.empty()) {
compileSpec.read_from_file(compileSpecPathOpt.c_str());
} else {
compileSpec.set_glow_backend(backend.c_str());
}
glow::FXGlow binding(
c10::make_intrusive<glow::FXGlowCompileSpec>(compileSpec));
// Setup host and load network.
binding.setupHost();
binding.loadNetwork(serializedGraphJson, weights, nodesJson, inputNames,
outputs);
if (inputs.empty()) {
std::cerr << "Did not receive a serialized input values file. Not "
"executing the Neural Net.\n";
return {};
}
// Run network with input and save output to fx_output.pt.
std::vector<torch::Tensor> out = binding.runNetwork(inputs);
// Check to see if user provided output file for comparison.
if (!outputPathOpt.empty()) {
std::ifstream outputStream(outputPathOpt.c_str());
outputStream >> std::noskipws;
std::vector<char> output;
output.insert(output.begin(), std::istream_iterator<char>(outputStream),
std::istream_iterator<char>());
std::vector<at::IValue> outputFileTensors =
torch::pickle_load(output).toTupleRef().elements();
// Calculate cosine similarity between user's output tensors and ReproFX's
// out.
std::vector<torch::Tensor> cosSimilarity;
torch::nn::CosineSimilarity cos(
torch::nn::CosineSimilarityOptions().dim(0));
for (int i = 0; i < out.size() && i < outputFileTensors.size(); i++) {
torch::Tensor a = out[i].flatten();
torch::Tensor b = outputFileTensors[i].toTensor().flatten();
auto c = cos(a, b);
if (fatalOnNotClose && *c.data_ptr<float>() != 1) {
LOG(FATAL) << "Cosine Similarity failure.";
}
cosSimilarity.push_back(c);
}
LOG(INFO) << "Cosine Similarity: " << cosSimilarity;
}
return out;
}
| 34.257426 | 80 | 0.644075 | [
"vector",
"model"
] |
4f38e6facdc5ac32e698cf666ffcb1cefc02472e | 4,208 | cpp | C++ | iRODS/clients/icommands/src/irmtrash.cpp | PlantandFoodResearch/irods | 9dfe7ffe5aa0760b7493bd9392ea1270df9335d4 | [
"BSD-3-Clause"
] | null | null | null | iRODS/clients/icommands/src/irmtrash.cpp | PlantandFoodResearch/irods | 9dfe7ffe5aa0760b7493bd9392ea1270df9335d4 | [
"BSD-3-Clause"
] | null | null | null | iRODS/clients/icommands/src/irmtrash.cpp | PlantandFoodResearch/irods | 9dfe7ffe5aa0760b7493bd9392ea1270df9335d4 | [
"BSD-3-Clause"
] | null | null | null | /*** Copyright (c), The Regents of the University of California ***
*** For more informtrashation please refer to files in the COPYRIGHT directory ***/
/*
* irmtrash - The irods rmtrash utility
*/
#include "rodsClient.hpp"
#include "parseCommandLine.hpp"
#include "rodsPath.hpp"
#include "rmtrashUtil.hpp"
#include "irods_client_api_table.hpp"
#include "irods_pack_table.hpp"
void usage();
int
main( int argc, char **argv ) {
int status;
rodsEnv myEnv;
rErrMsg_t errMsg;
rcComm_t *conn;
rodsArguments_t myRodsArgs;
char *optStr;
rodsPathInp_t rodsPathInp;
optStr = "hru:vVz:MZ";
status = parseCmdLineOpt( argc, argv, optStr, 1, &myRodsArgs );
if ( status < 0 ) {
printf( "Use -h for help.\n" );
exit( 1 );
}
if ( myRodsArgs.help == True ) {
usage();
exit( 0 );
}
status = getRodsEnv( &myEnv );
if ( status < 0 ) {
rodsLogError( LOG_ERROR, status, "main: getRodsEnv error. " );
exit( 1 );
}
/* use the trash home as cwd */
snprintf( myEnv.rodsCwd, LONG_NAME_LEN, "/%s/trash/home/%s",
myEnv.rodsZone, myEnv.rodsUserName );
rstrcpy( myEnv.rodsHome, myEnv.rodsCwd, LONG_NAME_LEN );
status = parseCmdLinePath( argc, argv, optind, &myEnv,
UNKNOWN_OBJ_T, NO_INPUT_T, 0, &rodsPathInp );
if ( status < 0 && status != USER__NULL_INPUT_ERR ) {
rodsLogError( LOG_ERROR, status, "main: parseCmdLinePath error. " );
printf( "Use -h for help.\n" );
exit( 1 );
}
// =-=-=-=-=-=-=-
// initialize pluggable api table
irods::api_entry_table& api_tbl = irods::get_client_api_table();
irods::pack_entry_table& pk_tbl = irods::get_pack_table();
init_api_table( api_tbl, pk_tbl );
conn = rcConnect( myEnv.rodsHost, myEnv.rodsPort, myEnv.rodsUserName,
myEnv.rodsZone, 1, &errMsg );
if ( conn == NULL ) {
exit( 2 );
}
status = clientLogin( conn );
if ( status != 0 ) {
rcDisconnect( conn );
exit( 7 );
}
status = rmtrashUtil( conn, &myEnv, &myRodsArgs, &rodsPathInp );
printErrorStack( conn->rError );
rcDisconnect( conn );
if ( status < 0 ) {
exit( 3 );
}
else {
exit( 0 );
}
}
void
usage() {
char *msgs[] = {
"Usage : irmtrash [-hMrvV] [--orphan] [-u user] [-z zoneName] [--age age_in_minutes] [dataObj|collection ...] ",
"Remove one or more data-object or collection from a RODS trash bin.",
"If the input dataObj|collection is not specified, the entire trash bin",
"of the user (/$myZone/trash/$myUserName) will be removed.",
" ",
"The dataObj|collection can be used to specify the paths of dataObj|collection",
"in the trash bin to be deleted. If the path is relative (does not start",
"with '/'), the path assumed to be relative to be the user's trash home path",
"e.g., /myZone/trash/home/myUserName.",
" ",
"An admin user can use the -M option to delete other users' trash bin.",
"The -u option can be used by an admin user to delete the trash bin of",
"a specific user. If the -u option is not used, the trash bins of all",
"users will be deleted.",
" ",
"Options are:",
" -r recursive - remove the whole subtree; the collection, all data-objects",
" in the collection, and any subcollections and sub-data-objects in the",
" collection.",
" -M admin mode",
" --orphan remove the orphan files in the /myZone/trash/orphan collection",
" It must be used with the -M option.",
" -u user - Used with the -M option allowing an admin user to delete a",
" specific user's trash bin.",
" -v verbose",
" -V Very verbose",
" -z zoneName - the zone where the rm trash will be carried out",
" -h this help",
""
};
int i;
for ( i = 0;; i++ ) {
if ( strlen( msgs[i] ) == 0 ) {
break;
}
printf( "%s\n", msgs[i] );
}
printReleaseInfo( "irmtrash" );
}
| 31.17037 | 120 | 0.574857 | [
"object"
] |
4f3c95f10bc5a6e05e6c4c20844a8f8decfb3b2b | 1,803 | cpp | C++ | acmicpc/5507.cpp | juseongkr/BOJ | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 7 | 2020-02-03T10:00:19.000Z | 2021-11-16T11:03:57.000Z | acmicpc/5507.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2021-01-03T06:58:24.000Z | 2021-01-03T06:58:24.000Z | acmicpc/5507.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2020-01-22T14:34:03.000Z | 2020-01-22T14:34:03.000Z | #include <iostream>
#include <vector>
#include <cmath>
#include <unordered_map>
using namespace std;
#define MAX 101
const int dx[8] = {1, 1, 1, 0, 0, -1, -1, -1};
const int dy[8] = {1, 0, -1, 1, -1, 1, 0, -1};
int n, m, label;
string s[MAX];
int sky[MAX][MAX];
unordered_map<int, bool> dup;
unordered_map<int, char> output;
unordered_map<int, double> shape;
vector<pair<int, int>> vec[MAX*6];
void dfs(int x, int y)
{
sky[x][y] = label;
vec[label].push_back({x, y});
for (int i=0; i<8; ++i) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx < 0 || nx >= n || ny < 0 || ny >= m || s[nx][ny] == '0' || sky[nx][ny])
continue;
dfs(nx, ny);
}
}
inline double dist(pair<int, int> a, pair<int, int> b)
{
return sqrt((double)(a.first - b.first)*(a.first - b.first) + \
(double)(a.second - b.second)*(a.second - b.second));
}
void mark(int k)
{
double ret = 0;
for (int i=0; i<vec[k].size(); ++i)
for (int j=i+1; j<vec[k].size(); ++j)
ret += dist(vec[k][i], vec[k][j]);
int tag = -1;
for (int i=1; i<=k; ++i) {
double err = abs(ret - shape[i]);
if (err <= 1e-6) {
tag = i;
break;
}
}
shape[k] = ret;
if (tag != -1) {
for (int i=0; i<vec[k].size(); ++i) {
auto [u, v] = vec[k][i];
sky[u][v] = tag;
}
}
}
int main()
{
cin >> m >> n;
for (int i=0; i<n; ++i)
cin >> s[i];
for (int i=0; i<n; ++i) {
for (int j=0; j<m; ++j) {
if (s[i][j] == '1' && !sky[i][j]) {
label++;
dfs(i, j);
}
}
}
for (int i=1; i<=label; ++i)
mark(i);
int letter = 0;
for (int i=0; i<n; ++i) {
for (int j=0; j<m; ++j) {
if (s[i][j] == '1') {
int tag = sky[i][j];
if (!dup[tag]) {
dup[tag] = 1;
output[tag] = (letter++)+'a';
}
cout << output[tag];
} else {
cout << '0';
}
}
cout << '\n';
}
return 0;
}
| 17.676471 | 80 | 0.484748 | [
"shape",
"vector"
] |
4f3eb3e7aa2421726f3fc0553ab2f36119582a37 | 6,575 | cpp | C++ | oneflow/core/job/runtime.cpp | JasenWangLab/oneflow | 0131e6ec282a426c2de98825de5fab95c853d8cf | [
"Apache-2.0"
] | null | null | null | oneflow/core/job/runtime.cpp | JasenWangLab/oneflow | 0131e6ec282a426c2de98825de5fab95c853d8cf | [
"Apache-2.0"
] | null | null | null | oneflow/core/job/runtime.cpp | JasenWangLab/oneflow | 0131e6ec282a426c2de98825de5fab95c853d8cf | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "oneflow/core/job/runtime.h"
#include "oneflow/core/job/global_for.h"
#include "oneflow/core/comm_network/epoll/epoll_comm_network.h"
#include "oneflow/core/comm_network/ibverbs/ibverbs_comm_network.h"
#include "oneflow/core/control/ctrl_client.h"
#include "oneflow/core/control/global_process_ctx.h"
#include "oneflow/core/job/resource_desc.h"
#include "oneflow/core/job/global_for.h"
#include "oneflow/core/job/runtime_job_descs.h"
#include "oneflow/core/thread/thread_manager.h"
#include "oneflow/core/actor/act_event_logger.h"
#include "oneflow/core/graph/task_node.h"
#include "oneflow/core/device/cuda_util.h"
#include "oneflow/core/memory/memory_allocator.h"
#include "oneflow/core/register/register_manager.h"
#include "oneflow/user/summary/events_writer.h"
#include "oneflow/core/job/collective_boxing_executor.h"
#include "oneflow/core/job/collective_boxing_device_ctx_poller.h"
namespace oneflow {
namespace {
void SendCmdMsg(const std::vector<const TaskProto*>& tasks, ActorCmd cmd) {
for (const TaskProto* task : tasks) {
ActorMsg msg = ActorMsg::BuildCommandMsg(task->task_id(), cmd);
Global<ActorMsgBus>::Get()->SendMsg(msg);
}
}
void HandoutTasks(const std::vector<const TaskProto*>& tasks) {
for (const TaskProto* task : tasks) {
Global<ThreadMgr>::Get()->GetThrd(task->thrd_id())->AddTask(*task);
}
SendCmdMsg(tasks, ActorCmd::kConstructActor);
}
bool HasNonCtrlConsumedRegstDescId(const TaskProto& task) {
for (const auto& pair : task.consumed_regst_desc_id()) {
if (pair.first == "in_ctrl") { continue; }
return true;
}
return false;
}
} // namespace
Runtime::Runtime(const Plan& plan, size_t total_piece_num, bool is_experiment_phase) {
NewAllGlobal(plan, total_piece_num, is_experiment_phase);
std::vector<const TaskProto*> source_tasks;
std::vector<const TaskProto*> other_tasks;
int64_t this_machine_task_num = 0;
for (const TaskProto& task : plan.task()) {
if (task.machine_id() != GlobalProcessCtx::Rank()) { continue; }
if (!HasNonCtrlConsumedRegstDescId(task)) {
source_tasks.push_back(&task);
} else {
other_tasks.push_back(&task);
}
this_machine_task_num += 1;
}
RuntimeCtx* runtime_ctx = Global<RuntimeCtx>::Get();
runtime_ctx->NewCounter("constructing_actor_cnt", this_machine_task_num);
HandoutTasks(source_tasks);
HandoutTasks(other_tasks);
runtime_ctx->WaitUntilCntEqualZero("constructing_actor_cnt");
LOG(INFO) << "Actors on this machine constructed";
OF_SESSION_BARRIER();
LOG(INFO) << "Actors on every machine constructed";
if (Global<CommNet>::Get()) { Global<CommNet>::Get()->RegisterMemoryDone(); }
OF_SESSION_BARRIER();
runtime_ctx->NewCounter("running_actor_cnt", this_machine_task_num);
SendCmdMsg(source_tasks, ActorCmd::kStart);
}
Runtime::~Runtime() {
Global<RuntimeCtx>::Get()->WaitUntilCntEqualZero("running_actor_cnt");
OF_SESSION_BARRIER();
DeleteAllGlobal();
}
void Runtime::NewAllGlobal(const Plan& plan, size_t total_piece_num, bool is_experiment_phase) {
Global<RuntimeCtx>::New(total_piece_num, is_experiment_phase);
if (GlobalProcessCtx::IsThisProcessMaster() && Global<RuntimeCtx>::Get()->NeedCollectActEvent()) {
Global<ActEventLogger>::New(is_experiment_phase);
}
// TODO(chengcheng)
// this code should be called before Runtime::NewAllGlobal, maybe after Eager ENV init
// and should be called before Global<Transport>::New()
if (Global<ResourceDesc, ForSession>::Get()->TotalMachineNum() > 1) {
#ifdef OF_PLATFORM_POSIX
// NOTE(chengcheng): Global<EpollCommNet> will new in any case.
// if use RDMA,
// The Global<CommNet> is set allocated by new Global<IBVerbsCommNet>
// else,
// The Global<CommNet> is set allocated by Global<EpollCommNet>
Global<EpollCommNet>::New();
if (Global<ResourceDesc, ForSession>::Get()->use_rdma()) {
#ifdef WITH_RDMA
// DEPRECATED
IBVerbsCommNet::Init(plan);
#else
LOG(FATAL) << "RDMA components not found";
#endif
} else {
Global<CommNet>::SetAllocated(Global<EpollCommNet>::Get());
}
#endif
}
Global<boxing::collective::CollectiveBoxingExecutor>::New(plan);
Global<MemoryAllocator>::New();
Global<RegstMgr>::New(plan);
Global<ActorMsgBus>::New();
Global<ThreadMgr>::New(plan);
Global<boxing::collective::CollectiveBoxingDeviceCtxPoller>::New();
Global<RuntimeJobDescs>::New(plan.job_confs().job_id2job_conf());
Global<summary::EventsWriter>::New();
}
void Runtime::DeleteAllGlobal() {
Global<RuntimeJobDescs>::Delete();
Global<boxing::collective::CollectiveBoxingDeviceCtxPoller>::Delete();
Global<ThreadMgr>::Delete();
Global<ActorMsgBus>::Delete();
Global<RegstMgr>::Delete();
Global<MemoryAllocator>::Delete();
Global<boxing::collective::CollectiveBoxingExecutor>::Delete();
// should be called after Global<Transport>::Delete()
if (Global<ResourceDesc, ForSession>::Get()->TotalMachineNum() > 1) {
#ifdef OF_PLATFORM_POSIX
if (Global<ResourceDesc, ForSession>::Get()->use_rdma()) {
#ifdef WITH_RDMA
CHECK(Global<EpollCommNet>::Get() != static_cast<EpollCommNet*>(Global<CommNet>::Get()));
// NOTE(chengcheng): it means that
// Global<CommNet>::SetAllocated(Global<IBVerbsCommNet>::Get())
// so the Global<CommNet> and Global<EpollCommNet> are NOT same global object
// then need delete both.
Global<CommNet>::Delete();
#else
LOG(FATAL) << "RDMA components not found";
#endif
} else {
CHECK(Global<EpollCommNet>::Get() == static_cast<EpollCommNet*>(Global<CommNet>::Get()));
// NOTE(chengcheng): it means that Global<CommNet>::SetAllocated(Global<EpollCommNet>::Get())
// so the Global<CommNet> and Global<EpollCommNet> are same global object
// then only need delete once.
}
Global<EpollCommNet>::Delete();
#endif
}
Global<ActEventLogger>::Delete();
Global<RuntimeCtx>::Delete();
Global<summary::EventsWriter>::Delete();
}
} // namespace oneflow
| 37.787356 | 100 | 0.728669 | [
"object",
"vector"
] |
4f40dc2028b97dbddeb8da3629c4aa3d73da50e9 | 31,630 | cpp | C++ | src/win/win-helpers.cpp | arunabhcode/librealsense | 3cd61ee78b1793091243db888a36979cd9c74dbb | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | src/win/win-helpers.cpp | arunabhcode/librealsense | 3cd61ee78b1793091243db888a36979cd9c74dbb | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | src/win/win-helpers.cpp | arunabhcode/librealsense | 3cd61ee78b1793091243db888a36979cd9c74dbb | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | // License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#ifdef RS2_USE_WMF_BACKEND
#if (_MSC_FULL_VER < 180031101)
#error At least Visual Studio 2013 Update 4 is required to compile this backend
#endif
#include "../types.h"
#include "win-helpers.h"
#include <Cfgmgr32.h>
#include <usbioctl.h>
#include <SetupAPI.h>
#include <comdef.h>
#include <atlstr.h>
#include <Windows.h>
#include <SetupAPI.h>
#include <string>
#include <regex>
#include <Sddl.h>
#pragma comment(lib, "cfgmgr32.lib")
#pragma comment(lib, "setupapi.lib")
#include <initguid.h>
#ifndef WITH_TRACKING
DEFINE_GUID(GUID_DEVINTERFACE_USB_DEVICE, 0xA5DCBF10L, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, \
0xC0, 0x4F, 0xB9, 0x51, 0xED);
#endif
DEFINE_GUID(GUID_DEVINTERFACE_IMAGE, 0x6bdd1fc6L, 0x810f, 0x11d0, 0xbe, 0xc7, 0x08, 0x00, \
0x2b, 0xe2, 0x09, 0x2f);
#define CREATE_MUTEX_RETRY_NUM (5)
namespace librealsense
{
namespace platform
{
std::string hr_to_string(HRESULT hr)
{
_com_error err(hr);
std::wstring errorMessage = (err.ErrorMessage()) ? err.ErrorMessage() : L"";
std::stringstream ss;
ss << "HResult 0x" << std::hex << hr << ": \"" << std::string(errorMessage.begin(), errorMessage.end()) << "\"";
return ss.str();
}
typedef ULONG(__stdcall* fnRtlGetVersion)(PRTL_OSVERSIONINFOW lpVersionInformation);
bool is_win10_redstone2()
{
RTL_OSVERSIONINFOEXW verInfo = { 0 };
verInfo.dwOSVersionInfoSize = sizeof(verInfo);
static auto RtlGetVersion = reinterpret_cast<fnRtlGetVersion>(GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlGetVersion"));
if (RtlGetVersion != nullptr && RtlGetVersion(reinterpret_cast<PRTL_OSVERSIONINFOW>(&verInfo)) == 0)
{
return verInfo.dwMajorVersion >= 0x0A && verInfo.dwBuildNumber >= 15063;
}
else
return false;
}
bool check(const char * call, HRESULT hr, bool to_throw)
{
if (FAILED(hr))
{
std::string descr = to_string() << call << " returned: " << hr_to_string(hr);
if (to_throw)
throw windows_backend_exception(descr);
else
LOG_INFO(descr);
return false;
}
return true;
}
std::string win_to_utf(const WCHAR * s)
{
auto len = WideCharToMultiByte(CP_UTF8, 0, s, -1, nullptr, 0, nullptr, nullptr);
if(len == 0)
throw std::runtime_error(to_string() << "WideCharToMultiByte(...) returned 0 and GetLastError() is " << GetLastError());
std::string buffer(len-1, ' ');
len = WideCharToMultiByte(CP_UTF8, 0, s, -1, &buffer[0], static_cast<int>(buffer.size())+1, nullptr, nullptr);
if(len == 0)
throw std::runtime_error(to_string() << "WideCharToMultiByte(...) returned 0 and GetLastError() is " << GetLastError());
return buffer;
}
std::vector<std::string> tokenize(std::string string, char separator)
{
std::vector<std::string> tokens;
std::string::size_type i1 = 0;
while(true)
{
auto i2 = string.find(separator, i1);
if(i2 == std::string::npos)
{
tokens.push_back(string.substr(i1));
return tokens;
}
tokens.push_back(string.substr(i1, i2-i1));
i1 = i2+1;
}
}
bool parse_usb_path(uint16_t & vid, uint16_t & pid, uint16_t & mi, std::string & unique_id, const std::string & path)
{
auto name = path;
std::transform(begin(name), end(name), begin(name), ::tolower);
auto tokens = tokenize(name, '#');
if(tokens.size() < 1 || (tokens[0] != R"(\\?\usb)" && tokens[0] != R"(\\?\hid)")) return false; // Not a USB device
if(tokens.size() < 3)
{
LOG_ERROR("malformed usb device path: " << name);
return false;
}
auto ids = tokenize(tokens[1], '&');
if(ids[0].size() != 8 || ids[0].substr(0,4) != "vid_" || !(std::istringstream(ids[0].substr(4,4)) >> std::hex >> vid))
{
LOG_ERROR("malformed vid string: " << tokens[1]);
return false;
}
if(ids[1].size() != 8 || ids[1].substr(0,4) != "pid_" || !(std::istringstream(ids[1].substr(4,4)) >> std::hex >> pid))
{
LOG_ERROR("malformed pid string: " << tokens[1]);
return false;
}
if(ids.size() > 2 && (ids[2].size() != 5 || ids[2].substr(0,3) != "mi_" || !(std::istringstream(ids[2].substr(3,2)) >> mi)))
{
LOG_ERROR("malformed mi string: " << tokens[1]);
return false;
}
ids = tokenize(tokens[2], '&');
if(ids.size() == 0)
{
LOG_ERROR("malformed id string: " << tokens[2]);
return false;
}
if (ids.size() > 2)
unique_id = ids[1];
else
unique_id = "";
return true;
}
bool parse_usb_path_from_device_id(uint16_t & vid, uint16_t & pid, uint16_t & mi, std::string & unique_id, const std::string & device_id)
{
auto name = device_id;
std::transform(begin(name), end(name), begin(name), ::tolower);
auto tokens = tokenize(name, '\\');
if (tokens.size() < 1 || tokens[0] != R"(usb)") return false; // Not a USB device
auto ids = tokenize(tokens[1], '&');
if (ids[0].size() != 8 || ids[0].substr(0, 4) != "vid_" || !(std::istringstream(ids[0].substr(4, 4)) >> std::hex >> vid))
{
LOG_ERROR("malformed vid string: " << tokens[1]);
return false;
}
if (ids[1].size() != 8 || ids[1].substr(0, 4) != "pid_" || !(std::istringstream(ids[1].substr(4, 4)) >> std::hex >> pid))
{
LOG_ERROR("malformed pid string: " << tokens[1]);
return false;
}
if (ids[2].size() != 5 || ids[2].substr(0, 3) != "mi_" || !(std::istringstream(ids[2].substr(3, 2)) >> mi))
{
LOG_ERROR("malformed mi string: " << tokens[1]);
return false;
}
ids = tokenize(tokens[2], '&');
if (ids.size() < 2)
{
LOG_ERROR("malformed id string: " << tokens[2]);
return false;
}
unique_id = ids[1];
return true;
}
bool handle_node(const std::wstring & targetKey, HANDLE h, ULONG index)
{
USB_NODE_CONNECTION_DRIVERKEY_NAME key;
key.ConnectionIndex = index;
if (!DeviceIoControl(h, IOCTL_USB_GET_NODE_CONNECTION_DRIVERKEY_NAME, &key, sizeof(key), &key, sizeof(key), nullptr, nullptr))
{
return false;
}
if (key.ActualLength < sizeof(key)) return false;
auto alloc = std::malloc(key.ActualLength);
if (!alloc)
throw std::bad_alloc();
auto pKey = std::shared_ptr<USB_NODE_CONNECTION_DRIVERKEY_NAME>(reinterpret_cast<USB_NODE_CONNECTION_DRIVERKEY_NAME *>(alloc), std::free);
pKey->ConnectionIndex = index;
if (DeviceIoControl(h, IOCTL_USB_GET_NODE_CONNECTION_DRIVERKEY_NAME, pKey.get(), key.ActualLength, pKey.get(), key.ActualLength, nullptr, nullptr))
{
//std::wcout << pKey->DriverKeyName << std::endl;
if (targetKey == pKey->DriverKeyName) {
return true;
}
else return false;
}
return false;
}
std::wstring get_path(HANDLE h, ULONG index)
{
// get name length
USB_NODE_CONNECTION_NAME name;
name.ConnectionIndex = index;
if (!DeviceIoControl(h, IOCTL_USB_GET_NODE_CONNECTION_NAME, &name, sizeof(name), &name, sizeof(name), nullptr, nullptr))
{
return std::wstring(L"");
}
// alloc space
if (name.ActualLength < sizeof(name)) return std::wstring(L"");
auto alloc = std::malloc(name.ActualLength);
auto pName = std::shared_ptr<USB_NODE_CONNECTION_NAME>(reinterpret_cast<USB_NODE_CONNECTION_NAME *>(alloc), std::free);
// get name
pName->ConnectionIndex = index;
if (DeviceIoControl(h, IOCTL_USB_GET_NODE_CONNECTION_NAME, pName.get(), name.ActualLength, pName.get(), name.ActualLength, nullptr, nullptr))
{
return std::wstring(pName->NodeName);
}
return std::wstring(L"");
}
std::tuple<std::string,usb_spec> handle_usb_hub(const std::wstring & targetKey, const std::wstring & path)
{
auto res = std::make_tuple(std::string(""), usb_spec::usb_undefined);
if (path == L"") return res;
std::wstring fullPath = L"\\\\.\\" + path;
HANDLE h = CreateFile(fullPath.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
if (h == INVALID_HANDLE_VALUE) return res;
auto h_gc = std::shared_ptr<void>(h, CloseHandle);
USB_NODE_INFORMATION info{};
if (!DeviceIoControl(h, IOCTL_USB_GET_NODE_INFORMATION, &info, sizeof(info), &info, sizeof(info), nullptr, nullptr))
return res;
// for each port on the hub
for (ULONG i = 1; i <= info.u.HubInformation.HubDescriptor.bNumberOfPorts; ++i)
{
// allocate something or other
char buf[sizeof(USB_NODE_CONNECTION_INFORMATION_EX)] = { 0 };
PUSB_NODE_CONNECTION_INFORMATION_EX pConInfo = reinterpret_cast<PUSB_NODE_CONNECTION_INFORMATION_EX>(buf);
// get info about port i
pConInfo->ConnectionIndex = i;
if (!DeviceIoControl(h, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, pConInfo, sizeof(buf), pConInfo, sizeof(buf), nullptr, nullptr))
{
continue;
}
// check if device is connected
if (pConInfo->ConnectionStatus != DeviceConnected)
{
continue; // almost assuredly silently. I think this flag gets set for any port without a device
}
// if connected, handle correctly, setting the location info if the device is found
if (pConInfo->DeviceIsHub)
res = handle_usb_hub(targetKey, get_path(h, i)); // Invoke recursion to traverse USB hubs chain
else
{
if (handle_node(targetKey, h, i)) // exit condition
{
return std::make_tuple(win_to_utf(fullPath.c_str()) + " " + std::to_string(i),
static_cast<usb_spec>(pConInfo->DeviceDescriptor.bcdUSB));
}
}
if (std::string("") != std::get<0>(res)) return res;
}
return res;
}
// Provides Port Id and the USB Specification (USB type)
std::tuple<std::string,usb_spec> get_usb_descriptors(uint16_t device_vid, uint16_t device_pid,
const std::string& device_uid)
{
SP_DEVINFO_DATA devInfo = { sizeof(SP_DEVINFO_DATA) };
// build a device info represent all imaging devices.
HDEVINFO device_info = SetupDiGetClassDevsEx(static_cast<const GUID *>(&GUID_DEVINTERFACE_IMAGE),
nullptr,
nullptr,
DIGCF_PRESENT,
nullptr,
nullptr,
nullptr);
if (device_info == INVALID_HANDLE_VALUE)
throw std::runtime_error("SetupDiGetClassDevs");
auto di = std::shared_ptr<void>(device_info, SetupDiDestroyDeviceInfoList);
auto res = std::make_tuple(std::string(""), usb_spec::usb_undefined);
// enumerate all imaging devices.
for (int member_index = 0; ; ++member_index)
{
SP_DEVICE_INTERFACE_DATA interfaceData = { sizeof(SP_DEVICE_INTERFACE_DATA) };
unsigned long buf_size = 0;
if (SetupDiEnumDeviceInfo(device_info, member_index, &devInfo) == FALSE)
{
if (GetLastError() == ERROR_NO_MORE_ITEMS) break; // stop when none left
continue; // silently ignore other errors
}
// get the device ID of current device.
if (CM_Get_Device_ID_Size(&buf_size, devInfo.DevInst, 0) != CR_SUCCESS)
{
LOG_ERROR("CM_Get_Device_ID_Size failed");
SetupDiDestroyDeviceInfoList(device_info);
return res;
}
auto alloc = std::malloc(buf_size * sizeof(WCHAR) + sizeof(WCHAR));
if (!alloc)
{
SetupDiDestroyDeviceInfoList(device_info);
throw std::bad_alloc();
}
auto pInstID = std::shared_ptr<WCHAR>(reinterpret_cast<WCHAR *>(alloc), std::free);
if (CM_Get_Device_ID(devInfo.DevInst, pInstID.get(), buf_size * sizeof(WCHAR) + sizeof(WCHAR), 0) != CR_SUCCESS)
{
LOG_ERROR("CM_Get_Device_ID failed");
SetupDiDestroyDeviceInfoList(device_info);
return res;
}
if (pInstID == nullptr) continue;
// Check if this is our device
uint16_t usb_vid, usb_pid, usb_mi; std::string usb_unique_id;
if (!parse_usb_path_from_device_id(usb_vid, usb_pid, usb_mi, usb_unique_id, std::string(win_to_utf(pInstID.get())))) continue;
if (usb_vid != device_vid || usb_pid != device_pid || /* usb_mi != device->mi || */ usb_unique_id != device_uid) continue;
// get parent (composite device) instance
DEVINST instance;
if (CM_Get_Parent(&instance, devInfo.DevInst, 0) != CR_SUCCESS)
{
LOG_ERROR("CM_Get_Parent failed");
SetupDiDestroyDeviceInfoList(device_info);
return res;
}
// get composite device instance id
if (CM_Get_Device_ID_Size(&buf_size, instance, 0) != CR_SUCCESS)
{
LOG_ERROR("CM_Get_Device_ID_Size failed");
SetupDiDestroyDeviceInfoList(device_info);
return res;
}
alloc = std::malloc(buf_size*sizeof(WCHAR) + sizeof(WCHAR));
if (!alloc)
{
SetupDiDestroyDeviceInfoList(device_info);
throw std::bad_alloc();
}
pInstID = std::shared_ptr<WCHAR>(reinterpret_cast<WCHAR *>(alloc), std::free);
if (CM_Get_Device_ID(instance, pInstID.get(), buf_size * sizeof(WCHAR) + sizeof(WCHAR), 0) != CR_SUCCESS) {
LOG_ERROR("CM_Get_Device_ID failed");
SetupDiDestroyDeviceInfoList(device_info);
return res;
}
// upgrade to DEVINFO_DATA for SetupDiGetDeviceRegistryProperty
device_info = SetupDiGetClassDevs(nullptr, pInstID.get(), nullptr, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE | DIGCF_ALLCLASSES);
if (device_info == INVALID_HANDLE_VALUE) {
LOG_ERROR("SetupDiGetClassDevs failed");
SetupDiDestroyDeviceInfoList(device_info);
return res;
}
interfaceData = { sizeof(SP_DEVICE_INTERFACE_DATA) };
if (SetupDiEnumDeviceInterfaces(device_info, nullptr, &GUID_DEVINTERFACE_USB_DEVICE, 0, &interfaceData) == FALSE)
{
LOG_ERROR("SetupDiEnumDeviceInterfaces failed");
SetupDiDestroyDeviceInfoList(device_info);
return res;
}
// get the SP_DEVICE_INTERFACE_DETAIL_DATA object, and also grab the SP_DEVINFO_DATA object for the device
buf_size = 0;
SetupDiGetDeviceInterfaceDetail(device_info, &interfaceData, nullptr, 0, &buf_size, nullptr);
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
{
LOG_ERROR("SetupDiGetDeviceInterfaceDetail failed");
SetupDiDestroyDeviceInfoList(device_info);
return res;
}
alloc = std::malloc(buf_size);
if (!alloc)
{
SetupDiDestroyDeviceInfoList(device_info);
throw std::bad_alloc();
}
auto detail_data = std::shared_ptr<SP_DEVICE_INTERFACE_DETAIL_DATA>(reinterpret_cast<SP_DEVICE_INTERFACE_DETAIL_DATA *>(alloc), std::free);
detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
SP_DEVINFO_DATA parent_data = { sizeof(SP_DEVINFO_DATA) };
if (!SetupDiGetDeviceInterfaceDetail(device_info, &interfaceData, detail_data.get(), buf_size, nullptr, &parent_data))
{
LOG_ERROR("SetupDiGetDeviceInterfaceDetail failed");
SetupDiDestroyDeviceInfoList(device_info);
return res;
}
// get driver key for composite device
buf_size = 0;
SetupDiGetDeviceRegistryProperty(device_info, &parent_data, SPDRP_DRIVER, nullptr, nullptr, 0, &buf_size);
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
{
LOG_ERROR("SetupDiGetDeviceRegistryProperty failed in an unexpected manner");
SetupDiDestroyDeviceInfoList(device_info);
return res;
}
alloc = std::malloc(buf_size);
if (!alloc) throw std::bad_alloc();
auto driver_key = std::shared_ptr<BYTE>(reinterpret_cast<BYTE*>(alloc), std::free);
if (!SetupDiGetDeviceRegistryProperty(device_info, &parent_data, SPDRP_DRIVER, nullptr, driver_key.get(), buf_size, nullptr))
{
LOG_ERROR("SetupDiGetDeviceRegistryProperty failed");
SetupDiDestroyDeviceInfoList(device_info);
return res;
}
// contains composite device key
std::wstring targetKey(reinterpret_cast<const wchar_t*>(driver_key.get()));
// recursively check all hubs, searching for composite device
std::wstringstream buf;
for (int i = 0;; i++)
{
buf << "\\\\.\\HCD" << i;
std::wstring hcd = buf.str();
// grab handle
HANDLE h = CreateFile(hcd.c_str(), GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
auto h_gc = std::shared_ptr<void>(h, CloseHandle);
if (h == INVALID_HANDLE_VALUE)
{
LOG_ERROR("CreateFile failed");
break;
}
else
{
USB_ROOT_HUB_NAME name;
// get required space
if (!DeviceIoControl(h, IOCTL_USB_GET_ROOT_HUB_NAME, nullptr, 0, &name, sizeof(name), nullptr, nullptr)) {
LOG_ERROR("DeviceIoControl failed");
SetupDiDestroyDeviceInfoList(device_info);
return res; // alt: fail silently and hope its on a different root hub
}
// alloc space
alloc = std::malloc(name.ActualLength);
if (!alloc) throw std::bad_alloc();
auto pName = std::shared_ptr<USB_ROOT_HUB_NAME>(reinterpret_cast<USB_ROOT_HUB_NAME *>(alloc), std::free);
// get name
if (!DeviceIoControl(h, IOCTL_USB_GET_ROOT_HUB_NAME, nullptr, 0, pName.get(), name.ActualLength, nullptr, nullptr)) {
LOG_ERROR("DeviceIoControl failed");
SetupDiDestroyDeviceInfoList(device_info);
return res; // alt: fail silently and hope its on a different root hub
}
// return location if device is connected under this root hub, also provide the port USB spec/speed
res = handle_usb_hub(targetKey, std::wstring(pName->RootHubName));
if (std::get<0>(res) != "")
{
SetupDiDestroyDeviceInfoList(device_info);
return res;
}
}
}
}
SetupDiDestroyDeviceInfoList(device_info);
throw std::exception("could not find camera in windows device tree");
}
#define MAX_HANDLES 64
event_base::event_base(HANDLE handle)
:_handle(handle)
{}
event_base::~event_base()
{
if (_handle != nullptr)
{
CloseHandle(_handle);
_handle = nullptr;
}
}
bool event_base::set()
{
if (_handle == nullptr) return false;
SetEvent(_handle);
return true;
}
bool event_base::wait(DWORD timeout) const
{
if (_handle == nullptr) return false;
return WaitForSingleObject(_handle, timeout) == WAIT_OBJECT_0; // Return true only if object was signaled
}
event_base* event_base::wait(const std::vector<event_base*>& events, bool waitAll, int timeout)
{
if (events.size() > MAX_HANDLES) return nullptr; // WaitForMultipleObjects doesn't support waiting on more then 64 handles
HANDLE handles[MAX_HANDLES];
auto i = 0;
for (auto& evnt : events)
{
handles[i] = evnt->get_handle();
++i;
}
auto res = WaitForMultipleObjects(static_cast<DWORD>(events.size()), handles, waitAll, timeout);
if (res < (WAIT_OBJECT_0 + events.size()))
{
return events[res - WAIT_OBJECT_0];
}
else
{
return nullptr;
}
}
event_base* event_base::wait_all(const std::vector<event_base*>& events, int timeout)
{
return wait(events, true, timeout);
}
event_base* event_base::wait_any(const std::vector<event_base*>& events, int timeout)
{
return wait(events, false, timeout);
}
bool manual_reset_event::reset() const
{
if (_handle == nullptr) return false;
return ResetEvent(_handle) != 0;
}
manual_reset_event::manual_reset_event()
:event_base(CreateEvent(nullptr, FALSE, FALSE, nullptr))
{}
auto_reset_event::auto_reset_event()
: event_base(CreateEvent(nullptr, FALSE, FALSE, nullptr))
{}
PSECURITY_DESCRIPTOR make_allow_all_security_descriptor(void)
{
WCHAR *pszStringSecurityDescriptor;
pszStringSecurityDescriptor = L"D:(A;;GA;;;WD)(A;;GA;;;AN)S:(ML;;NW;;;ME)";
PSECURITY_DESCRIPTOR pSecDesc;
if (!ConvertStringSecurityDescriptorToSecurityDescriptor(
pszStringSecurityDescriptor, SDDL_REVISION_1, &pSecDesc, nullptr))
return nullptr;
return pSecDesc;
}
named_mutex::named_mutex(const char* id, unsigned timeout)
: _timeout(timeout),
_winusb_mutex(nullptr)
{
update_id(id);
}
create_and_open_status named_mutex::create_named_mutex(const char* camID)
{
CString lstr;
CString IDstr(camID);
// IVCAM_DLL string is left in librealsense to allow safe
// interoperability with existing tools like DCM
lstr.Format(L"Global\\IVCAM_DLL_WINUSB_MUTEX%s", IDstr);
auto pSecDesc = make_allow_all_security_descriptor();
if (pSecDesc)
{
SECURITY_ATTRIBUTES SecAttr;
SecAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
SecAttr.lpSecurityDescriptor = pSecDesc;
SecAttr.bInheritHandle = FALSE;
_winusb_mutex = CreateMutex(
&SecAttr,
FALSE,
lstr);
LocalFree(pSecDesc);
}
//CreateMutex failed
if (_winusb_mutex == nullptr)
{
return Mutex_TotalFailure;
}
else if (GetLastError() == ERROR_ALREADY_EXISTS)
{
return Mutex_AlreadyExist;
}
return Mutex_Succeed;
}
create_and_open_status named_mutex::open_named_mutex(const char* camID)
{
CString lstr;
CString IDstr(camID);
// IVCAM_DLL string is left in librealsense to allow safe
// interoperability with existing tools like DCM
lstr.Format(L"Global\\IVCAM_DLL_WINUSB_MUTEX%s", IDstr.GetString());
_winusb_mutex = OpenMutex(
MUTEX_ALL_ACCESS, // request full access
FALSE, // handle not inheritable
lstr); // object name
if (_winusb_mutex == nullptr)
{
return Mutex_TotalFailure;
}
else if (GetLastError() == ERROR_ALREADY_EXISTS)
{
return Mutex_AlreadyExist;
}
return Mutex_Succeed;
}
void named_mutex::update_id(const char* camID)
{
auto stsCreateMutex = Mutex_Succeed;
auto stsOpenMutex = Mutex_Succeed;
if (_winusb_mutex == nullptr)
{
for (int i = 0; i < CREATE_MUTEX_RETRY_NUM; i++)
{
stsCreateMutex = create_named_mutex(camID);
switch (stsCreateMutex)
{
case Mutex_Succeed: return;
case Mutex_TotalFailure:
throw std::runtime_error("CreateNamedMutex returned Mutex_TotalFailure");
case Mutex_AlreadyExist:
{
stsOpenMutex = open_named_mutex(camID);
//if OpenMutex failed retry to create the mutex
//it can caused by termination of the process that created the mutex
if (stsOpenMutex == Mutex_TotalFailure)
{
continue;
}
else if (stsOpenMutex == Mutex_Succeed)
{
return;
}
else
{
throw std::runtime_error("OpenNamedMutex returned error " + stsOpenMutex);
}
}
default:
break;
};
}
throw std::runtime_error("Open mutex failed!");
}
//Mutex is already exist this mean that
//the mutex already opened by this process and the method called again after connect event.
else
{
for (auto i = 0; i < CREATE_MUTEX_RETRY_NUM; i++)
{
auto tempMutex = _winusb_mutex;
stsCreateMutex = create_named_mutex(camID);
switch (stsCreateMutex)
{
//if creation succeed this mean that new camera connected
//and we need to close the old mutex
case Mutex_Succeed:
{
auto res = CloseHandle(tempMutex);
if (!res)
{
throw std::runtime_error("CloseHandle failed");
}
return;
}
case Mutex_TotalFailure:
{
throw std::runtime_error("CreateNamedMutex returned Mutex_TotalFailure");
}
//Mutex already created by:
// 1. This process - which mean the same camera connected.
// 2. Other process created the mutex.
case Mutex_AlreadyExist:
{
stsOpenMutex = open_named_mutex(camID);
if (stsOpenMutex == Mutex_TotalFailure)
{
continue;
}
else if (stsOpenMutex == Mutex_Succeed)
{
return;
}
else
{
throw std::runtime_error("OpenNamedMutex failed with error " + stsOpenMutex);
}
}
default:
break;
}
}
throw std::runtime_error("Open mutex failed!");
}
}
bool named_mutex::try_lock() const
{
return (WaitForSingleObject(_winusb_mutex, _timeout) == WAIT_TIMEOUT) ? false : true;
}
void named_mutex::acquire() const
{
if (!try_lock())
{
throw std::runtime_error("Acquire failed!");
}
}
void named_mutex::release() const
{
auto sts = ReleaseMutex(_winusb_mutex);
if (!sts)
{
throw std::runtime_error("Failed to release winUsb named Mutex! LastError: " + GetLastError());
}
}
named_mutex::~named_mutex()
{
close();
}
void named_mutex::close()
{
if (_winusb_mutex != nullptr)
{
CloseHandle(_winusb_mutex);
_winusb_mutex = nullptr;
}
}
}
}
#endif
| 39.438903 | 159 | 0.510275 | [
"object",
"vector",
"transform"
] |
4f4157c56d4b1a88c9de09f9579be3441df291bf | 22,387 | cpp | C++ | examples/pathtracing/app.cpp | sketchbooks99/PRayGround | 07d1779f2e36ad9ed5fd6df457cdc515b9017300 | [
"MIT"
] | 23 | 2021-08-25T10:40:40.000Z | 2022-03-28T13:02:05.000Z | examples/pathtracing/app.cpp | sketchbooks99/PRayGround | 07d1779f2e36ad9ed5fd6df457cdc515b9017300 | [
"MIT"
] | 2 | 2021-12-04T12:50:44.000Z | 2021-12-14T14:55:00.000Z | examples/pathtracing/app.cpp | sketchbooks99/PRayGround | 07d1779f2e36ad9ed5fd6df457cdc515b9017300 | [
"MIT"
] | 1 | 2021-04-15T13:13:17.000Z | 2021-04-15T13:13:17.000Z | #include "app.h"
void App::initResultBufferOnDevice()
{
params.subframe_index = 0;
result_bitmap.allocateDevicePtr();
accum_bitmap.allocateDevicePtr();
normal_bitmap.allocateDevicePtr();
albedo_bitmap.allocateDevicePtr();
depth_bitmap.allocateDevicePtr();
params.result_buffer = reinterpret_cast<uchar4*>(result_bitmap.devicePtr());
params.accum_buffer = reinterpret_cast<float4*>(accum_bitmap.devicePtr());
params.normal_buffer = reinterpret_cast<float3*>(normal_bitmap.devicePtr());
params.albedo_buffer = reinterpret_cast<float3*>(albedo_bitmap.devicePtr());
params.depth_buffer = reinterpret_cast<float*>(depth_bitmap.devicePtr());
CUDA_SYNC_CHECK();
}
void App::handleCameraUpdate()
{
if (!camera_update)
return;
camera_update = false;
float3 U, V, W;
camera.UVWFrame(U, V, W);
RaygenRecord* rg_record = reinterpret_cast<RaygenRecord*>(sbt.raygenRecord());
RaygenData rg_data;
rg_data.camera =
{
.origin = camera.origin(),
.lookat = camera.lookat(),
.U = U,
.V = V,
.W = W,
.farclip = camera.farClip()
};
CUDA_CHECK(cudaMemcpy(
reinterpret_cast<void*>(&rg_record->data),
&rg_data, sizeof(RaygenData),
cudaMemcpyHostToDevice
));
initResultBufferOnDevice();
}
// ----------------------------------------------------------------
void App::setup()
{
// CUDAの初期化とOptixDeviceContextの生成
stream = 0;
CUDA_CHECK(cudaFree(0));
OPTIX_CHECK(optixInit());
context.disableValidation();
context.create();
// Instance acceleration structureの初期化
scene_ias = InstanceAccel{InstanceAccel::Type::Instances};
// パイプラインの設定
pipeline.setLaunchVariableName("params");
pipeline.setDirectCallableDepth(5);
pipeline.setContinuationCallableDepth(5);
pipeline.setNumPayloads(5);
pipeline.setNumAttributes(5);
// OptixModuleをCUDAファイルから生成
Module raygen_module, miss_module, hitgroups_module, textures_module, surfaces_module;
raygen_module = pipeline.createModuleFromCudaFile(context, "cuda/raygen.cu");
miss_module = pipeline.createModuleFromCudaFile(context, "cuda/miss.cu");
hitgroups_module = pipeline.createModuleFromCudaFile(context, "cuda/hitgroups.cu");
textures_module = pipeline.createModuleFromCudaFile(context, "cuda/textures.cu");
surfaces_module = pipeline.createModuleFromCudaFile(context, "cuda/surfaces.cu");
// レンダリング結果を保存する用のBitmapを用意
result_bitmap.allocate(PixelFormat::RGBA, pgGetWidth(), pgGetHeight());
accum_bitmap.allocate(PixelFormat::RGBA, pgGetWidth(), pgGetHeight());
normal_bitmap.allocate(PixelFormat::RGB, pgGetWidth(), pgGetHeight());
albedo_bitmap.allocate(PixelFormat::RGB, pgGetWidth(), pgGetHeight());
depth_bitmap.allocate(PixelFormat::GRAY, pgGetWidth(), pgGetHeight());
// LaunchParamsの設定
params.width = result_bitmap.width();
params.height = result_bitmap.height();
params.samples_per_launch = 1;
params.max_depth = 10;
params.white = 1.0f;
initResultBufferOnDevice();
// カメラの設定
camera.setOrigin(make_float3(-333.0f, 80.0f, -800.0f));
camera.setLookat(make_float3(0.0f, -225.0f, 0.0f));
camera.setUp(make_float3(0.0f, 1.0f, 0.0f));
camera.setFarClip(5000);
camera.setFov(40.0f);
camera.setAspect(static_cast<float>(params.width) / params.height);
camera.enableTracking(pgGetCurrentWindow());
float3 U, V, W;
camera.UVWFrame(U, V, W);
// Raygenプログラム
ProgramGroup raygen_prg = pipeline.createRaygenProgram(context, raygen_module, "__raygen__pinhole");
// Raygenプログラム用のShader Binding Tableデータ
RaygenRecord raygen_record;
raygen_prg.recordPackHeader(&raygen_record);
raygen_record.data.camera =
{
.origin = camera.origin(),
.lookat = camera.lookat(),
.U = U,
.V = V,
.W = W,
.farclip = camera.farClip()
};
sbt.setRaygenRecord(raygen_record);
// Callable関数とShader Binding TableにCallable関数用のデータを登録するLambda関数
auto setupCallable = [&](const Module& module, const std::string& dc, const std::string& cc)
{
EmptyRecord callable_record = {};
auto [prg, id] = pipeline.createCallablesProgram(context, module, dc, cc);
prg.recordPackHeader(&callable_record);
sbt.addCallablesRecord(callable_record);
return id;
};
// テクスチャ用のCallableプログラム
uint32_t constant_prg_id = setupCallable(textures_module, DC_FUNC_STR("constant"), "");
uint32_t checker_prg_id = setupCallable(textures_module, DC_FUNC_STR("checker"), "");
uint32_t bitmap_prg_id = setupCallable(textures_module, DC_FUNC_STR("bitmap"), "");
// Surface用のCallableプログラム
// Diffuse
uint32_t diffuse_sample_bsdf_prg_id = setupCallable(surfaces_module, DC_FUNC_STR("sample_diffuse"), CC_FUNC_STR("bsdf_diffuse"));
uint32_t diffuse_pdf_prg_id = setupCallable(surfaces_module, DC_FUNC_STR("pdf_diffuse"), "");
// Conductor
uint32_t conductor_sample_bsdf_prg_id = setupCallable(surfaces_module, DC_FUNC_STR("sample_conductor"), CC_FUNC_STR("bsdf_conductor"));
uint32_t conductor_pdf_prg_id = setupCallable(surfaces_module, DC_FUNC_STR("pdf_conductor"), "");
// Dielectric
uint32_t dielectric_sample_bsdf_prg_id = setupCallable(surfaces_module, DC_FUNC_STR("sample_dielectric"), CC_FUNC_STR("bsdf_dielectric"));
uint32_t dielectric_pdf_prg_id = setupCallable(surfaces_module, DC_FUNC_STR("pdf_dielectric"), "");
// Disney
uint32_t disney_sample_bsdf_prg_id = setupCallable(surfaces_module, DC_FUNC_STR("sample_disney"), CC_FUNC_STR("bsdf_disney"));
uint32_t disney_pdf_prg_id = setupCallable(surfaces_module, DC_FUNC_STR("pdf_disney"), "");
// AreaEmitter
uint32_t area_emitter_prg_id = setupCallable(surfaces_module, DC_FUNC_STR("area_emitter"), "");
// Shape用のCallableプログラム(主に面光源サンプリング用)
uint32_t plane_sample_pdf_prg_id = setupCallable(hitgroups_module, DC_FUNC_STR("rnd_sample_plane"), CC_FUNC_STR("pdf_plane"));
uint32_t sphere_sample_pdf_prg_id = setupCallable(hitgroups_module, DC_FUNC_STR("rnd_sample_sphere"), CC_FUNC_STR("pdf_sphere"));
// 環境マッピング (Sphere mapping) 用のテクスチャとデータ準備
// 画像ファイルはリポジトリには含まれていないので、任意の画像データを設定してください
// Preparing texture for environment mapping (sphere mapping)
// Since image file is not included in the repository, Please set your HDR image or use any other texture.
auto env_texture = make_shared<FloatBitmapTexture>("resources/image/sepulchral_chapel_basement_4k.exr", bitmap_prg_id);
//auto env_texture = make_shared<ConstantTexture>(make_float3(0.0f), constant_prg_id);
env_texture->copyToDevice();
env = EnvironmentEmitter{env_texture};
env.copyToDevice();
// Missプログラム
ProgramGroup miss_prg = pipeline.createMissProgram(context, miss_module, MS_FUNC_STR("envmap"));
// Missプログラム用のShader Binding Tableデータ
MissRecord miss_record;
miss_prg.recordPackHeader(&miss_record);
miss_record.data.env_data = env.devicePtr();
MissRecord miss_shadow_record;
miss_prg.recordPackHeader(&miss_shadow_record);
sbt.setMissRecord(miss_record, miss_shadow_record);
// Hitgroupプログラム
// Plane
auto plane_prg = pipeline.createHitgroupProgram(context, hitgroups_module, CH_FUNC_STR("plane"), IS_FUNC_STR("plane"));
auto plane_shadow_prg = pipeline.createHitgroupProgram(context, hitgroups_module, CH_FUNC_STR("shadow"), IS_FUNC_STR("plane"));
// Sphere
auto sphere_prg = pipeline.createHitgroupProgram(context, hitgroups_module, CH_FUNC_STR("sphere"), IS_FUNC_STR("sphere"));
auto sphere_shadow_prg = pipeline.createHitgroupProgram(context, hitgroups_module, CH_FUNC_STR("shadow"), IS_FUNC_STR("sphere"));
// Cylinder
auto cylinder_prg = pipeline.createHitgroupProgram(context, hitgroups_module, CH_FUNC_STR("cylinder"), IS_FUNC_STR("cylinder"));
auto cylinder_shadow_prg = pipeline.createHitgroupProgram(context, hitgroups_module, CH_FUNC_STR("shadow"), IS_FUNC_STR("cylinder"));
// Triangle mesh
auto mesh_prg = pipeline.createHitgroupProgram(context, hitgroups_module, CH_FUNC_STR("mesh"));
auto mesh_shadow_prg = pipeline.createHitgroupProgram(context, hitgroups_module, CH_FUNC_STR("shadow"));
struct Primitive
{
shared_ptr<Shape> shape;
shared_ptr<Material> material;
uint32_t sample_bsdf_id;
uint32_t pdf_id;
};
uint32_t sbt_idx = 0;
uint32_t sbt_offset = 0;
uint32_t instance_id = 0;
// ShapeとMaterialのデータをGPU上に準備しHitgroup用のSBTデータを追加するLambda関数
auto setupPrimitive = [&](ProgramGroup& prg, ProgramGroup& shadow_prg, const Primitive& primitive, const Matrix4f& transform)
{
// データをGPU側に用意
primitive.shape->copyToDevice();
primitive.shape->setSbtIndex(sbt_idx);
primitive.material->copyToDevice();
// Shader Binding Table へのデータの登録
HitgroupRecord record;
prg.recordPackHeader(&record);
record.data =
{
.shape_data = primitive.shape->devicePtr(),
.surface_info =
{
.data = primitive.material->devicePtr(),
.sample_id = primitive.sample_bsdf_id,
.bsdf_id = primitive.sample_bsdf_id,
.pdf_id = primitive.pdf_id,
.type = primitive.material->surfaceType()
}
};
HitgroupRecord shadow_record;
shadow_prg.recordPackHeader(&shadow_record);
sbt.addHitgroupRecord(record, shadow_record);
sbt_idx++;
// GASをビルドし、IASに追加
ShapeInstance instance{primitive.shape->type(), primitive.shape, transform};
instance.allowCompaction();
instance.buildAccel(context, stream);
instance.setSBTOffset(sbt_offset);
instance.setId(instance_id);
scene_ias.addInstance(instance);
instance_id++;
sbt_offset += PathTracingSBT::NRay;
};
vector<AreaEmitterInfo> area_emitter_infos;
// 面光源用のSBTデータを用意するLambda関数
auto setupAreaEmitter = [&](
ProgramGroup& prg, ProgramGroup& shadow_prg,
shared_ptr<Shape> shape,
AreaEmitter area, Matrix4f transform,
uint32_t sample_pdf_id
)
{
ASSERT(dynamic_pointer_cast<Plane>(shape) || dynamic_pointer_cast<Sphere>(shape), "The shape of area emitter must be a plane or sphere.");
shape->copyToDevice();
shape->setSbtIndex(sbt_idx);
area.copyToDevice();
HitgroupRecord record;
prg.recordPackHeader(&record);
record.data =
{
.shape_data = shape->devicePtr(),
.surface_info =
{
.data = area.devicePtr(),
.sample_id = area_emitter_prg_id, // 使わない
.bsdf_id = area_emitter_prg_id,
.pdf_id = area_emitter_prg_id, // 使わない
.type = SurfaceType::AreaEmitter
}
};
HitgroupRecord shadow_record = {};
shadow_prg.recordPackHeader(&shadow_record);
sbt_idx++;
sbt.addHitgroupRecord(record, shadow_record);
// GASをビルドし、IASに追加
ShapeInstance instance{shape->type(), shape, transform};
instance.allowCompaction();
instance.buildAccel(context, stream);
instance.setSBTOffset(sbt_offset);
instance.setId(instance_id);
scene_ias.addInstance(instance);
instance_id++;
sbt_offset += PathTracingSBT::NRay;
AreaEmitterInfo area_emitter_info =
{
.shape_data = shape->devicePtr(),
.objToWorld = transform,
.worldToObj = transform.inverse(),
.sample_id = sample_pdf_id,
.pdf_id = sample_pdf_id
};
area_emitter_infos.push_back(area_emitter_info);
};
// Scene ==========================================================================
// Bunny
{
// Shape
auto bunny = make_shared<TriangleMesh>("resources/model/uv_bunny.obj");
// Texture
auto bunny_checker = make_shared<CheckerTexture>(make_float3(0.3f), make_float3(0.8f, 0.05f, 0.05f), 10, checker_prg_id);
bunny_checker->copyToDevice();
// Material
auto bunny_disney = make_shared<Disney>(bunny_checker);
bunny_disney->setRoughness(0.3f);
bunny_disney->setMetallic(1.0f);
// Transform
Matrix4f transform = Matrix4f::translate({-50.0f, -272.0f, 300.0f}) * Matrix4f::rotate(math::pi, {0.0f, 1.0f, 0.0f}) * Matrix4f::scale(1200.0f);
Primitive primitive{bunny, bunny_disney, disney_sample_bsdf_prg_id, disney_pdf_prg_id};
setupPrimitive(mesh_prg, mesh_shadow_prg, primitive, transform);
}
// Armadillo
{
// Shape
auto armadillo = make_shared<TriangleMesh>("resources/model/Armadillo.ply");
armadillo->smooth();
// Texture
auto armadillo_constant = make_shared<ConstantTexture>(make_float3(1.0f), constant_prg_id);
armadillo_constant->copyToDevice();
// Material
auto armadillo_conductor = make_shared<Conductor>(armadillo_constant);
// Transform
Matrix4f transform = Matrix4f::translate({250.0f, -210.0f, -150.0f}) * Matrix4f::scale(1.2f);
Primitive primitive{armadillo, armadillo_conductor, conductor_sample_bsdf_prg_id, conductor_pdf_prg_id};
setupPrimitive(mesh_prg, mesh_shadow_prg, primitive, transform);
}
// Teapot
{
// Shape
auto teapot = make_shared<TriangleMesh>("resources/model/teapot.obj");
// Texture
auto teapot_constant = make_shared<ConstantTexture>(make_float3(0.325f, 0.702f, 0.709f), constant_prg_id);
teapot_constant->copyToDevice();
// Material
auto teapot_diffuse = make_shared<Diffuse>(teapot_constant);
// Transform
Matrix4f transform = Matrix4f::translate({-250.0f, -275.0f, -150.0f}) * Matrix4f::scale(40.0f);
Primitive primitive { teapot, teapot_diffuse, diffuse_sample_bsdf_prg_id, diffuse_pdf_prg_id };
setupPrimitive(mesh_prg, mesh_shadow_prg, primitive, transform);
}
// Earth
{
// Shape
auto earth_sphere = make_shared<Sphere>(make_float3(0.0f), 90.0f);
// Texture
auto earth_bitmap = make_shared<BitmapTexture>("resources/image/earth.jpg", bitmap_prg_id);
earth_bitmap->copyToDevice();
// Material
auto earth_diffuse = make_shared<Diffuse>(earth_bitmap);
// Transform
Matrix4f transform = Matrix4f::translate({-250.0f, -185.0f, 150.0f});
Primitive primitive { earth_sphere, earth_diffuse, diffuse_sample_bsdf_prg_id, diffuse_pdf_prg_id };
setupPrimitive(sphere_prg, sphere_shadow_prg, primitive, transform);
}
// Glass sphere
{
// Shape
auto glass_sphere = make_shared<Sphere>(make_float3(0.0f), 80.0f);
// Texture
auto white_constant = make_shared<ConstantTexture>(make_float3(1.0f), constant_prg_id);
white_constant->copyToDevice();
// Material
auto glass = make_shared<Dielectric>(white_constant, 1.5f);
// Transform
Matrix4f transform = Matrix4f::translate({250.0f, -195.0f, 150.0f}) * Matrix4f::rotate(math::pi, {0.0f, 1.0f, 0.0f});
Primitive primitive { glass_sphere, glass, dielectric_sample_bsdf_prg_id, dielectric_pdf_prg_id };
setupPrimitive(sphere_prg, sphere_shadow_prg, primitive, transform);
}
// Cylinder
{
// Shape
auto cylinder = make_shared<Cylinder>(60.0f, 100.0f);
// Texture
auto cylinder_checker = make_shared<CheckerTexture>(make_float3(0.3f), make_float3(0.9f), 10, checker_prg_id);
cylinder_checker->copyToDevice();
// Material
auto cylinder_diffuse = make_shared<Diffuse>(cylinder_checker);
// Transform
Matrix4f transform = Matrix4f::translate({0.0f, -220.0f, -300.0f});
Primitive primitive { cylinder, cylinder_diffuse, diffuse_sample_bsdf_prg_id, diffuse_pdf_prg_id };
setupPrimitive(cylinder_prg, cylinder_shadow_prg, primitive, transform);
}
// Ground
{
// Shape
auto ground = make_shared<Plane>(make_float2(-500.0f, -500.0f), make_float2(500.0f, 500.0f));
// Texture
auto ground_texture = make_shared<ConstantTexture>(make_float3(0.25f), constant_prg_id);
ground_texture->copyToDevice();
// Material
auto ground_diffuse = make_shared<Diffuse>(ground_texture);
// Transform
Matrix4f transform = Matrix4f::translate({0.0f, -275.0f, 0.0f});
Primitive primitive { ground, ground_diffuse, diffuse_sample_bsdf_prg_id, diffuse_pdf_prg_id };
setupPrimitive(plane_prg, plane_shadow_prg, primitive, transform);
}
// 面光源1 : Plane
{
// Shape
auto plane_light = make_shared<Plane>();
// Texture
auto white = make_shared<ConstantTexture>(make_float3(1.0f), constant_prg_id);
white->copyToDevice();
// Area emitter
auto plane_area_emitter = AreaEmitter(white, 50.0f);
Matrix4f transform = Matrix4f::translate({200.0f, 50.0f, 200.0f}) * Matrix4f::rotate(math::pi / 4.0f, {0.5f, 0.5f, 0.2f}) * Matrix4f::scale(50.0f);
setupAreaEmitter(plane_prg, plane_shadow_prg, plane_light, plane_area_emitter, transform, plane_sample_pdf_prg_id);
}
// 面光源2 : Sphere
{
// Shape
auto sphere_light = make_shared<Sphere>();
// Texture
auto orange = make_shared<ConstantTexture>(make_float3(0.914f, 0.639f, 0.149f), constant_prg_id);
orange->copyToDevice();
// Area emitter
auto sphere_area_emitter = AreaEmitter(orange, 50.0f);
Matrix4f transform = Matrix4f::translate({-200.0f, 50.0f, -200.0f}) * Matrix4f::scale(30.0f);
setupAreaEmitter(sphere_prg, sphere_shadow_prg, sphere_light, sphere_area_emitter, transform, sphere_sample_pdf_prg_id);
}
// 光源データをGPU側にコピー
CUDABuffer<AreaEmitterInfo> d_area_emitter_infos;
d_area_emitter_infos.copyToDevice(area_emitter_infos);
params.lights = d_area_emitter_infos.deviceData();
params.num_lights = static_cast<int>(area_emitter_infos.size());
CUDA_CHECK(cudaStreamCreate(&stream));
scene_ias.build(context, stream);
sbt.createOnDevice();
params.handle = scene_ias.handle();
pipeline.create(context);
d_params.allocate(sizeof(LaunchParams));
// GUI setting
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
const char* glsl_version = "#version 150";
ImGui::StyleColorsDark();
ImGui_ImplGlfw_InitForOpenGL(pgGetCurrentWindow()->windowPtr(), true);
ImGui_ImplOpenGL3_Init(glsl_version);
}
// ----------------------------------------------------------------
void App::update()
{
handleCameraUpdate();
d_params.copyToDeviceAsync(¶ms, sizeof(LaunchParams), stream);
float start_time = pgGetElapsedTimef();
// OptiX レイトレーシングカーネルの起動
optixLaunch(
static_cast<OptixPipeline>(pipeline),
stream,
d_params.devicePtr(),
sizeof(LaunchParams),
&sbt.sbt(),
params.width,
params.height,
1
);
CUDA_CHECK(cudaStreamSynchronize(stream));
CUDA_SYNC_CHECK();
render_time = pgGetElapsedTimef() - start_time;
params.subframe_index++;
// レンダリング結果をデバイスから取ってくる
result_bitmap.copyFromDevice();
normal_bitmap.copyFromDevice();
albedo_bitmap.copyFromDevice();
depth_bitmap.copyFromDevice();
}
// ----------------------------------------------------------------
void App::draw()
{
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGui::Begin("Path tracing GUI");
ImGui::SliderFloat("White", ¶ms.white, 0.01f, 1.0f);
ImGui::Text("Camera info:");
ImGui::Text("Origin: %f %f %f", camera.origin().x, camera.origin().y, camera.origin().z);
ImGui::Text("Lookat: %f %f %f", camera.lookat().x, camera.lookat().y, camera.lookat().z);
ImGui::Text("Up: %f %f %f", camera.up().x, camera.up().y, camera.up().z);
float farclip = camera.farClip();
ImGui::SliderFloat("far clip", &farclip, 500.0f, 10000.0f);
if (farclip != camera.farClip()) {
camera.setFarClip(farclip);
camera_update = true;
}
ImGui::Text("Frame rate: %.3f ms/frame (%.2f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::Text("Render time: %.3f ms/frame", render_time * 1000.0f);
ImGui::Text("Subframe index: %d", params.subframe_index);
ImGui::End();
ImGui::Render();
result_bitmap.draw(0, 0, pgGetWidth() / 2, pgGetHeight() / 2);
normal_bitmap.draw(pgGetWidth() / 2, 0, pgGetWidth() / 2, pgGetHeight() / 2);
albedo_bitmap.draw(0, pgGetHeight() / 2, pgGetWidth() / 2, pgGetHeight() / 2);
depth_bitmap.draw(pgGetWidth() / 2, pgGetHeight() / 2, pgGetWidth() / 2, pgGetHeight() / 2);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
if (params.subframe_index == 4096)
result_bitmap.write(pgPathJoin(pgAppDir(), "pathtracing.jpg"));
}
// ----------------------------------------------------------------
void App::close()
{
env.free();
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
pipeline.destroy();
context.destroy();
}
// ----------------------------------------------------------------
void App::mouseDragged(float x, float y, int button)
{
camera_update = true;
}
// ----------------------------------------------------------------
void App::mouseScrolled(float xoffset, float yoffset)
{
camera_update = true;
} | 39.905526 | 156 | 0.645196 | [
"mesh",
"render",
"shape",
"vector",
"model",
"transform"
] |
4f42aa5796c1e0c2ffb10f01b912b9b9d947448c | 285 | hxx | C++ | odb-tests-2.4.0/evolution/data/test2.hxx | edidada/odb | 78ed750a9dde65a627fc33078225410306c2e78b | [
"MIT"
] | null | null | null | odb-tests-2.4.0/evolution/data/test2.hxx | edidada/odb | 78ed750a9dde65a627fc33078225410306c2e78b | [
"MIT"
] | null | null | null | odb-tests-2.4.0/evolution/data/test2.hxx | edidada/odb | 78ed750a9dde65a627fc33078225410306c2e78b | [
"MIT"
] | null | null | null | // file : evolution/data/test2.hxx
// copyright : Copyright (c) 2009-2015 Code Synthesis Tools CC
// license : GNU GPL v2; see accompanying LICENSE file
#ifndef TEST2_HXX
#define TEST2_HXX
#define MODEL_VERSION 2
#include "model.hxx"
#undef MODEL_VERSION
#endif // TEST2_HXX
| 21.923077 | 62 | 0.736842 | [
"model"
] |
4f42e1857a38144ebea066ab9de374b60c9a214e | 1,711 | hpp | C++ | oms_small/include/okapi/api/chassis/model/threeEncoderSkidSteerModel.hpp | wanton-wind/oms-vex | d2eca00ccfefad5e2f85f8465837bd8a0710359c | [
"Apache-2.0"
] | 1 | 2018-10-28T01:49:16.000Z | 2018-10-28T01:49:16.000Z | oms_small/include/okapi/api/chassis/model/threeEncoderSkidSteerModel.hpp | wanton-wind/oms-vex | d2eca00ccfefad5e2f85f8465837bd8a0710359c | [
"Apache-2.0"
] | 1 | 2018-10-28T01:40:00.000Z | 2018-10-28T01:40:00.000Z | oms_small/include/okapi/api/chassis/model/threeEncoderSkidSteerModel.hpp | wanton-wind/oms-vex | d2eca00ccfefad5e2f85f8465837bd8a0710359c | [
"Apache-2.0"
] | 3 | 2018-10-26T08:45:58.000Z | 2018-10-27T13:36:37.000Z | /**
* @author Ryan Benasutti, WPI
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef _OKAPI_THREEENCODERSKIDSTEERMODEL_HPP_
#define _OKAPI_THREEENCODERSKIDSTEERMODEL_HPP_
#include "okapi/api/chassis/model/skidSteerModel.hpp"
namespace okapi {
class ThreeEncoderSkidSteerModel : public SkidSteerModel {
public:
/**
* Model for a skid steer drive (wheels parallel with robot's direction of motion). When all
* motors are powered +100%, the robot should move forward in a straight line.
*
* @param ileftSideMotor left side motor
* @param irightSideMotor right side motor
* @param ileftEnc left side encoder
* @param imiddleEnc middle encoder (mounted perpendicular to the left and right side encoders)
* @param irightEnc right side encoder
*/
ThreeEncoderSkidSteerModel(std::shared_ptr<AbstractMotor> ileftSideMotor,
std::shared_ptr<AbstractMotor> irightSideMotor,
std::shared_ptr<ContinuousRotarySensor> ileftEnc,
std::shared_ptr<ContinuousRotarySensor> imiddleEnc,
std::shared_ptr<ContinuousRotarySensor> irightEnc,
double imaxVelocity,
double imaxVoltage = 12000);
/**
* Read the sensors.
*
* @return sensor readings in the format {left, right, middle}
*/
std::valarray<std::int32_t> getSensorVals() const override;
protected:
std::shared_ptr<ContinuousRotarySensor> middleSensor;
};
} // namespace okapi
#endif
| 36.404255 | 97 | 0.679135 | [
"model"
] |
4f44c055a4455ecf266019a153f04d03950a0113 | 17,366 | cc | C++ | MUMmer3.20/src/tigr/sw_align.cc | kloetzl/mugsy | 8ccdf32858a7a5ab2f7b9b084d2190970feb97ec | [
"Artistic-2.0"
] | null | null | null | MUMmer3.20/src/tigr/sw_align.cc | kloetzl/mugsy | 8ccdf32858a7a5ab2f7b9b084d2190970feb97ec | [
"Artistic-2.0"
] | null | null | null | MUMmer3.20/src/tigr/sw_align.cc | kloetzl/mugsy | 8ccdf32858a7a5ab2f7b9b084d2190970feb97ec | [
"Artistic-2.0"
] | null | null | null | #include "sw_align.hh"
//-- Number of bases to extend past global high score before giving up
static const int DEFAULT_BREAK_LEN = 200;
//-- Characters used in creating the alignment edit matrix, DO NOT ALTER!
static const int DELETE = 0;
static const int INSERT = 1;
static const int MATCH = 2;
static const int START = 3;
static const int NONE = 4;
int _break_len = DEFAULT_BREAK_LEN;
int _matrix_type = NUCLEOTIDE;
//----------------------------------------- Private Function Declarations ----//
static void generateDelta
(const Diagonal * Diag, long int FinishCt, long int FinishCDi,
long int N, vector<long int> & Delta);
static inline Score * maxScore
(Score S[3]);
static inline long int scoreMatch
(const Diagonal Diag, long int Dct, long int CDi,
const char * A, const char * B, long int N, unsigned int m_o);
static inline void scoreEdit
(Score & curr, const long int del, const long int ins, const long int mat);
//------------------------------------------ Private Function Definitions ----//
bool _alignEngine
(const char * A0, long int Astart, long int & Aend,
const char * B0, long int Bstart, long int & Bend,
vector<long int> & Delta, unsigned int m_o)
// A0 is a sequence such that A [1...\0]
// B0 is a sequence such that B [1...\0]
// The alignment should use bases A [Astart...Aend] (inclusive)
// The alignment should use beses B [Bstart...Bend] (inclusive)
// of [Aend...Astart] etc. if BACKWARD_SEARCH
// Aend must never equal Astart, same goes for Bend and Bstart
// Delta is an integer vector, not necessarily empty
// m_o is the modus operandi of the function:
// FORWARD_ALIGN, FORWARD_SEARCH, BACKWARD_SEARCH
// Returns true on success (Aend & Bend reached) or false on failure
{
Diagonal * Diag; // the list of diagonals to make up edit matrix
bool TargetReached; // the target was reached
const char * A, * B; // the sequence pointers to be used by this func
long int min_score = (-1 * LONG_MAX); // minimum possible score
long int high_score = min_score; // global maximum score
long int xhigh_score = min_score; // non-optimal high score
// max score difference
long int max_diff = GOOD_SCORE [getMatrixType( )] * _break_len;
long int CDi; // conceptual diagonal index (not relating to mem)
long int Dct, Di; // diagonal counter, actual diagonal index
long int PDct, PPDct; // previous diagonal and prev prev diagonal
long int PDi, PPDi; // previous diagonal index and prev prev diag index
long int Ds, PDs, PPDs; // diagonal size, prev, prev prev diagonal size
// where 'size' = rbound - lbound + 1
long int Ll = 100; // capacity of the diagonal list
long int Dl = 2; // current conceptual diagonal length
long int lbound = 0; // current diagonal left(lower) node bound index
long int rbound = 0; // current diagonal right(upper) node bound index
long int FinishCt = 0; // diagonal containing the high_score
long int FinishCDi = 0; // conceptual index of the high_score on FinishCt
long int xFinishCt = 0; // non-optimal ...
long int xFinishCDi = 0; // non-optimal ...
long int N, M, L; // maximum matrix dimensions... N rows, M columns
int Iadj, Dadj, Madj; // insert, delete and match adjust values
#ifdef _DEBUG_VERBOSE
long int MaxL = 0; // biggest diagonal seen
long int TrimCt = 0; // counter of nodes trimmed
long int CalcCt = 0; // counter of nodes calculated
#endif
//-- Set up character pointers for the appropriate m_o
if ( m_o & DIRECTION_BIT )
{
A = A0 + ( Astart - 1 );
B = B0 + ( Bstart - 1 );
N = Aend - Astart + 1;
M = Bend - Bstart + 1;
}
else
{
A = A0 + ( Astart + 1 );
B = B0 + ( Bstart + 1 );
N = Astart - Aend + 1;
M = Bstart - Bend + 1;
}
//-- Initialize the diagonals list
Diag = (Diagonal *) Safe_malloc ( Ll * sizeof(Diagonal) );
//-- Initialize position 0,0 in the matrices
Diag[0] . lbound = lbound;
Diag[0] . rbound = rbound ++;
Diag[0] . I = (Node *) Safe_malloc ( 1 * sizeof(Node) );
Diag[0] . I[0] . S[DELETE] . value = min_score;
Diag[0] . I[0] . S[INSERT] . value = min_score;
Diag[0] . I[0] . S[MATCH] . value = 0;
Diag[0] . I[0] . max = Diag[0] . I[0] . S + MATCH;
Diag[0] . I[0] . S[DELETE] . used = NONE;
Diag[0] . I[0] . S[INSERT] . used = NONE;
Diag[0] . I[0] . S[MATCH] . used = START;
L = N < M ? N : M;
//-- **START** of diagonal processing loop
//-- Calculate the rest of the diagonals until goal reached or score worsens
for ( Dct = 1;
Dct <= N + M && (Dct - FinishCt) <= _break_len && lbound <= rbound;
Dct ++ )
{
//-- If diagonals capacity exceeded, realloc
if ( Dct >= Ll )
{
Ll *= 2;
Diag = (Diagonal *) Safe_realloc
( Diag, sizeof(Diagonal) * Ll );
}
Diag[Dct] . lbound = lbound;
Diag[Dct] . rbound = rbound;
//-- malloc space for the edit char and score nodes
Ds = rbound - lbound + 1;
Diag[Dct] . I = (Node *) Safe_malloc
( Ds * sizeof(Node) );
#ifdef _DEBUG_VERBOSE
//-- Keep count of trimmed and calculated nodes
CalcCt += Ds;
TrimCt += Dl - Ds;
if ( Ds > MaxL )
MaxL = Ds;
#endif
//-- Set diagonal index adjustment values
if ( Dct <= N )
{
Iadj = 0;
Madj = -1;
}
else
{
Iadj = 1;
Madj = Dct == N + 1 ? 0 : 1;
}
Dadj = Iadj - 1;
//-- Set parent diagonal values
PDct = Dct - 1;
PDs = Diag[PDct] . rbound - Diag[PDct] . lbound + 1;
PDi = lbound + Dadj;
PDi = PDi - Diag[PDct] . lbound;
//-- Set grandparent diagonal values
PPDct = Dct - 2;
if ( PPDct >= 0 )
{
PPDs = Diag[PPDct] . rbound - Diag[PPDct] . lbound + 1;
PPDi = lbound + Madj;
PPDi = PPDi - Diag[PPDct] . lbound;
}
else
PPDi = PPDs = 0;
//-- If forced alignment, don't keep track of global max
if ( m_o & FORCED_BIT )
high_score = min_score;
//-- **START** of internal node scoring loop
//-- Calculate scores for every node (within bounds) for diagonal Dct
for ( CDi = lbound; CDi <= rbound; CDi ++ )
{
//-- Set the index (in memory) of current node and clear score
Di = CDi - Diag[Dct] . lbound;
//-- Calculate DELETE score
if ( PDi >= 0 && PDi < PDs )
scoreEdit
(Diag[Dct] . I[Di] . S[DELETE],
Diag[PDct] . I[PDi] . S[DELETE] . used == NONE ?
Diag[PDct] . I[PDi] . S[DELETE] . value :
Diag[PDct] . I[PDi] . S[DELETE] . value +
CONT_GAP_SCORE [_matrix_type],
Diag[PDct] . I[PDi] . S[INSERT] . used == NONE ?
Diag[PDct] . I[PDi] . S[INSERT] . value :
Diag[PDct] . I[PDi] . S[INSERT] . value +
OPEN_GAP_SCORE [_matrix_type],
Diag[PDct] . I[PDi] . S[MATCH] . used == NONE ?
Diag[PDct] . I[PDi] . S[MATCH] . value :
Diag[PDct] . I[PDi] . S[MATCH] . value +
OPEN_GAP_SCORE [_matrix_type]);
else
{
Diag[Dct] . I[Di] . S[DELETE] . value = min_score;
Diag[Dct] . I[Di] . S[DELETE] . used = NONE;
}
PDi ++;
//-- Calculate INSERT score
if ( PDi >= 0 && PDi < PDs )
scoreEdit
(Diag[Dct] . I[Di] . S[INSERT],
Diag[PDct] . I[PDi] . S[DELETE] . used == NONE ?
Diag[PDct] . I[PDi] . S[DELETE] . value :
Diag[PDct] . I[PDi] . S[DELETE] . value +
OPEN_GAP_SCORE [_matrix_type],
Diag[PDct] . I[PDi] . S[INSERT] . used == NONE ?
Diag[PDct] . I[PDi] . S[INSERT] . value :
Diag[PDct] . I[PDi] . S[INSERT] . value +
CONT_GAP_SCORE [_matrix_type],
Diag[PDct] . I[PDi] . S[MATCH] . used == NONE ?
Diag[PDct] . I[PDi] . S[MATCH] . value :
Diag[PDct] . I[PDi] . S[MATCH] . value +
OPEN_GAP_SCORE [_matrix_type]);
else
{
Diag[Dct] . I[Di] . S[INSERT] . value = min_score;
Diag[Dct] . I[Di] . S[INSERT] . used = NONE;
}
//-- Calculate MATCH/MIS-MATCH score
if ( PPDi >= 0 && PPDi < PPDs )
{
scoreEdit
(Diag[Dct] . I[Di] . S[MATCH],
Diag[PPDct] . I[PPDi] . S[DELETE] . value,
Diag[PPDct] . I[PPDi] . S[INSERT] . value,
Diag[PPDct] . I[PPDi] . S[MATCH] . value);
Diag[Dct] . I[Di] . S[MATCH] . value +=
scoreMatch (Diag[Dct], Dct, CDi, A, B, N, m_o);
}
else
{
Diag[Dct] . I[Di] . S[MATCH] . value = min_score;
Diag[Dct] . I[Di] . S[MATCH] . used = NONE;
}
PPDi ++;
Diag[Dct] . I[Di] . max = maxScore (Diag[Dct] . I[Di] . S);
//-- Reset high_score if new global max was found
if ( Diag[Dct] . I[Di] . max->value >= high_score )
{
high_score = Diag[Dct] . I[Di] . max->value;
FinishCt = Dct;
FinishCDi = CDi;
}
}
//-- **END** of internal node scoring loop
//-- Calculate max non-optimal score
if ( m_o & SEQEND_BIT && Dct >= L )
{
if ( L == N )
{
if ( lbound == 0 )
{
if ( Diag[Dct] . I[0] . max->value >= xhigh_score )
{
xhigh_score = Diag[Dct] . I[0] . max->value;
xFinishCt = Dct;
xFinishCDi = 0;
}
}
}
else // L == M
{
if ( rbound == M )
{
if ( Diag[Dct] . I[M-Diag[Dct].lbound] .
max->value >= xhigh_score )
{
xhigh_score = Diag[Dct] . I[M-Diag[Dct].lbound] .
max->value;
xFinishCt = Dct;
xFinishCDi = M;
}
}
}
}
//-- If in extender modus operandi, free soon to be greatgrandparent diag
if ( m_o & SEARCH_BIT && Dct > 1 )
free ( Diag[PPDct] . I );
//-- Trim hopeless diagonal nodes
for ( Di = 0; Di < Ds; Di ++ )
{
if ( high_score - Diag[Dct] . I[Di] . max->value > max_diff )
lbound ++;
else
break;
}
for ( Di = Ds - 1; Di >= 0; Di -- )
{
if ( high_score - Diag[Dct] . I[Di] . max->value > max_diff )
rbound --;
else
break;
}
//-- Grow new diagonal and reset boundaries
if ( Dct < N && Dct < M )
{ Dl ++; rbound ++; }
else if ( Dct >= N && Dct >= M )
{ Dl --; lbound --; }
else if ( Dct >= N )
lbound --;
else
rbound ++;
if ( lbound < 0 )
lbound = 0;
if ( rbound >= Dl )
rbound = Dl - 1;
}
//-- **END** of diagonal processing loop
Dct --;
//-- Check if the target was reached
// If OPTIMAL, backtrack to last high_score to maximize alignment score
TargetReached = false;
if ( Dct == N + M )
{
if ( ~m_o & OPTIMAL_BIT || m_o & SEQEND_BIT )
{
TargetReached = true;
FinishCt = N + M;
FinishCDi = 0;
}
else if ( FinishCt == Dct )
TargetReached = true;
}
else if ( m_o & SEQEND_BIT && xFinishCt != 0 )
{
//-- non-optimal, extend alignment to end of shortest seq if possible
FinishCt = xFinishCt;
FinishCDi = xFinishCDi;
}
//-- Set A/Bend to finish positions
long int Aadj = FinishCt <= N ? FinishCt - FinishCDi - 1 : N - FinishCDi - 1;
long int Badj = FinishCt <= N ? FinishCDi - 1 : FinishCt - N + FinishCDi - 1;
if ( ~m_o & DIRECTION_BIT )
{
Aadj *= -1;
Badj *= -1;
}
Aend = Astart + Aadj;
Bend = Bstart + Badj;
#ifdef _DEBUG_VERBOSE
assert (FinishCt > 1);
//-- Ouput calculation statistics
if ( TargetReached )
fprintf(stderr,"Finish score = %ld : %ld,%ld\n",
Diag[FinishCt] . I[0] . max->value, N, M);
else
fprintf(stderr,"High score = %ld : %ld,%ld\n", high_score,
labs(Aadj) + 1, labs(Badj) + 1);
fprintf(stderr, "%ld nodes calculated, %ld nodes trimmed\n", CalcCt, TrimCt);
if ( m_o & DIRECTION_BIT )
fprintf(stderr, "%ld bytes used\n",
(long int)sizeof(Diagonal) * Dct + (long int)sizeof(Node) * CalcCt);
else
fprintf(stderr, "%ld bytes used\n",
((long int)sizeof(Diagonal) + (long int)sizeof(Node) * MaxL) * 2);
#endif
//-- If in forward alignment m_o, create the Delta information
if ( ~m_o & SEARCH_BIT )
generateDelta (Diag, FinishCt, FinishCDi, N, Delta);
//-- Free the scoring and edit spaces remaining
for ( Di = m_o & SEARCH_BIT ? Dct - 1 : 0; Di <= Dct; Di ++ )
free ( Diag[Di] . I );
free ( Diag );
return TargetReached;
}
static void generateDelta
(const Diagonal * Diag, long int FinishCt, long int FinishCDi,
long int N, vector<long int> & Delta)
// Diag is the list of diagonals that compose the edit matrix
// FinishCt is the diagonal that contains the finishing node
// FinishCDi is the conceptual finishing node, in FinishCt, for the align
// N & M are the target positions for the alignment
// Delta is the vector in which to store the alignment data, new data
// will be appended onto any existing data.
// NOTE: there will be no zero at the end of the data, end of data
// is signaled by the end of the vector
// Return is void
{
//-- Function pre-conditions
#ifdef _DEBUG_ASSERT
assert ( Diag != NULL );
assert ( FinishCt > 1 );
#endif
long int Count; // delta counter
long int Dct = FinishCt; // diagonal index
long int CDi = FinishCDi; // conceptual node index
long int Di = 0; // actual node index
long int Pi = 0; // path index
long int PSize = 100; // capacity of the path space
char * Reverse_Path; // path space
Score curr_score;
int edit;
//-- malloc space for the edit path
Reverse_Path = (char *) Safe_malloc ( PSize * sizeof(char) );
//-- Which Score index is the maximum value in? Store in edit
Di = CDi - Diag[Dct] . lbound;
edit = Diag[Dct] . I[Di] . max - Diag[Dct] . I[Di] . S;
//-- Walk the path backwards through the edit space
while ( Dct >= 0 )
{
//-- remalloc path space if neccessary
if ( Pi >= PSize )
{
PSize *= 2;
Reverse_Path = (char *) Safe_realloc
( Reverse_Path, sizeof(char) * PSize );
}
Di = CDi - Diag[Dct] . lbound;
curr_score = Diag[Dct] . I[Di] . S[edit];
Reverse_Path[Pi ++] = edit;
switch ( edit )
{
case DELETE :
CDi = Dct -- <= N ? CDi - 1 : CDi;
break;
case INSERT :
CDi = Dct -- <= N ? CDi : CDi + 1;
break;
case MATCH :
CDi = Dct <= N ? CDi - 1 : ( Dct == N + 1 ? CDi : CDi + 1 );
Dct -= 2;
break;
case START :
Dct = -1;
break;
default :
fprintf(stderr,"\nERROR: Invalid edit matrix entry,\n"
" please file a bug report\n");
exit ( EXIT_FAILURE );
}
edit = curr_score . used;
}
//-- Generate the delta information
Count = 1;
for (Pi -= 2; Pi >= 0; Pi --)
{
switch ( Reverse_Path[Pi] )
{
case DELETE :
Delta . push_back(-Count);
Count = 1;
break;
case INSERT :
Delta . push_back(Count);
Count = 1;
break;
case MATCH :
Count ++;
break;
case START :
break;
default :
fprintf(stderr,"\nERROR: Invalid path matrix entry,\n"
" please file a bug report\n");
exit ( EXIT_FAILURE );
}
}
free (Reverse_Path);
return;
}
static inline Score * maxScore
(Score S[3])
// Return a pointer to the maximum score in the score array
{
if ( S[DELETE] . value > S[INSERT] . value )
{
if ( S[DELETE] . value > S[MATCH] . value )
return S + DELETE;
else
return S + MATCH;
}
else if ( S[INSERT] . value > S[MATCH] . value )
return S + INSERT;
else
return S + MATCH;
}
static inline void scoreEdit
(Score & curr, const long int del, const long int ins, const long int mat)
// Assign current edit a maximal score using either del, ins or mat
{
if ( del > ins )
{
if ( del > mat )
{
curr.value = del;
curr.used = DELETE;
}
else
{
curr.value = mat;
curr.used = MATCH;
}
}
else if ( ins > mat )
{
curr.value = ins;
curr.used = INSERT;
}
else
{
curr.value = mat;
curr.used = MATCH;
}
return;
}
static inline long int scoreMatch
(const Diagonal Diag, long int Dct, long int CDi,
const char * A, const char * B, long int N, unsigned int m_o)
// Diag is the single diagonal that contains the node to be scored
// Dct is Diag's diagonal index in the edit matrix
// CDi is the conceptual node to be scored in Diag
// A and B are the alignment sequences
// N is the alignment target index in A
// m_o is the modus operandi of the alignment:
// FORWARD_ALIGN, FORWARD_SEARCH, BACKWARD_SEARCH
{
static int Dir;
static char Ac, Bc;
//-- 1 for forward, -1 for reverse
Dir = m_o & DIRECTION_BIT ? 1 : -1;
//-- Locate the characters that need to be compared
if ( Dct <= N )
{
Ac = *( A + ( (Dct - CDi) * Dir ) );
Bc = *( B + ( (CDi) * Dir ) );
}
else
{
Ac = *( A + ( (N - CDi) * Dir ) );
Bc = *( B + ( (Dct - N + CDi) * Dir ) );
}
if ( ! isalpha(Ac) )
Ac = STOP_CHAR;
if ( ! isalpha(Bc) )
Bc = STOP_CHAR;
return MATCH_SCORE [_matrix_type] [toupper(Ac) - 'A'] [toupper(Bc) - 'A'];
}
| 27.434439 | 80 | 0.556778 | [
"vector"
] |
4f44f77ceee944ad0dd2346155195d7f613a0f00 | 2,327 | cpp | C++ | Source/Services/Marketplace/catalog_item_image.cpp | blgrossMS/xbox-live-api | 17c586336e11f0fa3a2a3f3acd665b18c5487b24 | [
"MIT"
] | 2 | 2021-07-17T13:34:20.000Z | 2022-01-09T00:55:51.000Z | Source/Services/Marketplace/catalog_item_image.cpp | blgrossMS/xbox-live-api | 17c586336e11f0fa3a2a3f3acd665b18c5487b24 | [
"MIT"
] | null | null | null | Source/Services/Marketplace/catalog_item_image.cpp | blgrossMS/xbox-live-api | 17c586336e11f0fa3a2a3f3acd665b18c5487b24 | [
"MIT"
] | 1 | 2018-11-18T08:32:40.000Z | 2018-11-18T08:32:40.000Z | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "xsapi/marketplace.h"
NAMESPACE_MICROSOFT_XBOX_SERVICES_MARKETPLACE_CPP_BEGIN
catalog_item_image::catalog_item_image() :
m_height(0),
m_width(0)
{
}
catalog_item_image::catalog_item_image(
_In_ string_t id,
_In_ web::uri resizeUrl,
_In_ std::vector<string_t> purposes,
_In_ string_t purpose,
_In_ uint32_t height,
_In_ uint32_t width
) :
m_id(std::move(id)),
m_resizeUrl(std::move(resizeUrl)),
m_purposes(std::move(purposes)),
m_purpose(std::move(purpose)),
m_height(height),
m_width(width)
{
}
const string_t& catalog_item_image::id() const
{
return m_id;
}
const web::uri& catalog_item_image::resize_url() const
{
return m_resizeUrl;
}
const std::vector<string_t>& catalog_item_image::purposes() const
{
return m_purposes;
}
const string_t& catalog_item_image::purpose() const
{
return m_purpose;
}
uint32_t catalog_item_image::height() const
{
return m_height;
}
uint32_t catalog_item_image::width() const
{
return m_width;
}
xbox_live_result<catalog_item_image>
catalog_item_image::_Deserialize(
_In_ const web::json::value& json
)
{
if (json.is_null()) return xbox_live_result<catalog_item_image>();
std::error_code errc;
catalog_item_image result;
result.m_id = utils::extract_json_string(json, _T("ID"), errc, true);
result.m_resizeUrl = utils::extract_json_string(json, _T("ResizeUrl"), errc, false);
result.m_purpose = utils::extract_json_string(json, _T("Purpose"), errc, false);
result.m_purposes = utils::extract_json_vector<string_t>(utils::json_string_extractor, json, _T("Purposes"), errc, false);
result.m_height = utils::extract_json_int(json, _T("Height"), errc, true);
result.m_width = utils::extract_json_int(json, _T("Width"), errc, true);
return xbox_live_result<catalog_item_image>(result, errc);
}
NAMESPACE_MICROSOFT_XBOX_SERVICES_MARKETPLACE_CPP_END | 27.05814 | 126 | 0.690589 | [
"vector"
] |
4f46e8979ac5aef7bcb8587fc7ad31511bc669dc | 4,923 | cpp | C++ | applications/tests/unit_tests/rpc_function_types.cpp | sagarjha/derecho-unified | f43aa530e1567e75bb99d7ddc70653a338aa7538 | [
"BSD-3-Clause"
] | 1 | 2019-10-03T23:25:12.000Z | 2019-10-03T23:25:12.000Z | applications/tests/unit_tests/rpc_function_types.cpp | sagarjha/derecho-unified | f43aa530e1567e75bb99d7ddc70653a338aa7538 | [
"BSD-3-Clause"
] | null | null | null | applications/tests/unit_tests/rpc_function_types.cpp | sagarjha/derecho-unified | f43aa530e1567e75bb99d7ddc70653a338aa7538 | [
"BSD-3-Clause"
] | null | null | null | #include "derecho/derecho.h"
#include <mutils-serialization/SerializationSupport.hpp>
/*
* The Eclipse CDT parser crashes if it tries to expand the REGISTER_RPC_FUNCTIONS
* macro, probably because there are too many layers of variadic argument expansion.
* This definition makes the RPC macros no-ops when the CDT parser tries to expand
* them, which allows it to continue syntax-highlighting the rest of the file.
*/
#ifdef __CDT_PARSER__
#define REGISTER_RPC_FUNCTIONS(...)
#define RPC_NAME(...) 0ULL
#endif
class ConstTest : public mutils::ByteRepresentable {
int state;
public:
//Const member functions should be allowed
int read_state() const {
return state;
}
void change_state(const int& new_state) {
state = new_state;
}
ConstTest(int initial_state = 0) : state(initial_state) {}
DEFAULT_SERIALIZATION_SUPPORT(ConstTest, state);
REGISTER_RPC_FUNCTIONS(ConstTest, read_state, change_state);
};
class ReferenceTest : public mutils::ByteRepresentable {
std::string state;
public:
//Causes a compile error: you can't return a reference from an RPC function
// std::string& get_state() {
//Correct version:
std::string get_state() {
return state;
}
//Causes a compile error: RPC functions must pass arguments by reference
// void set_state(std::string new_state) {
//Correct version:
void set_state(const std::string& new_state) {
state = new_state;
}
void append_string(const std::string& text) {
state.append(text);
}
ReferenceTest(const std::string& initial_state = "") : state(initial_state) {}
DEFAULT_SERIALIZATION_SUPPORT(ReferenceTest, state);
REGISTER_RPC_FUNCTIONS(ReferenceTest, get_state, set_state, append_string);
};
using derecho::even_sharding_policy;
using derecho::one_subgroup_policy;
int main(int argc, char** argv) {
// Read configurations from the command line options as well as the default config file
derecho::Conf::initialize(argc, argv);
derecho::SubgroupInfo subgroup_function(derecho::DefaultSubgroupAllocator({
{std::type_index(typeid(ConstTest)), one_subgroup_policy(even_sharding_policy(1, 3))},
{std::type_index(typeid(ReferenceTest)), one_subgroup_policy(even_sharding_policy(1, 3))}
}));
auto const_test_factory = [](PersistentRegistry*) { return std::make_unique<ConstTest>(); };
auto reference_test_factory = [](PersistentRegistry*) { return std::make_unique<ReferenceTest>(); };
derecho::Group<ConstTest, ReferenceTest> group(derecho::CallbackSet{}, subgroup_function, nullptr,
std::vector<derecho::view_upcall_t>{},
const_test_factory, reference_test_factory);
int my_id = derecho::getConfInt32(CONF_DERECHO_LOCAL_ID);
const std::vector<node_id_t>& const_test_group_members = group.get_subgroup_members<ConstTest>()[0];
bool in_const_test_group = std::find(const_test_group_members.begin(),
const_test_group_members.end(), my_id) !=
const_test_group_members.end();
if(in_const_test_group) {
derecho::Replicated<ConstTest>& const_test = group.get_subgroup<ConstTest>();
uint32_t my_node_rank = group.get_my_rank();
const_test.ordered_send<RPC_NAME(change_state)>(my_node_rank);
derecho::rpc::QueryResults<int> results = const_test.ordered_send<RPC_NAME(read_state)>();
decltype(results)::ReplyMap& replies = results.get();
int curr_state = 0;
for(auto& reply_pair : replies) {
try {
curr_state = reply_pair.second.get();
} catch(derecho::rpc::node_removed_from_group_exception& ex) {
std::cout << "No query reply due to node_removed_from_group_exception: " << ex.what() << std::endl;
}
}
std::cout << "Current state according to ordered_send: " << curr_state << std::endl;
} else {
derecho::Replicated<ReferenceTest>& reference_test = group.get_subgroup<ReferenceTest>();
reference_test.ordered_send<RPC_NAME(set_state)>("Hello, testing.");
reference_test.ordered_send<RPC_NAME(append_string)>(" Another string. ");
derecho::rpc::QueryResults<std::string> results = reference_test.ordered_send<RPC_NAME(get_state)>();
decltype(results)::ReplyMap& replies = results.get();
for(auto& reply_pair : replies) {
try {
std::cout << "State read from node " << reply_pair.first << " was: " << reply_pair.second.get() << std::endl;
} catch(derecho::rpc::node_removed_from_group_exception& ex) {
std::cout << "No query reply due to node_removed_from_group_exception: " << ex.what() << std::endl;
}
}
}
}
| 43.955357 | 125 | 0.665042 | [
"vector"
] |
4f4b4f4b3713548059e342eec0ef79b58fb076e8 | 1,092 | cpp | C++ | source/data_model/python/src/different_shape/constant_shape/value.cpp | computationalgeography/lue | 71993169bae67a9863d7bd7646d207405dc6f767 | [
"MIT"
] | 2 | 2021-02-26T22:45:56.000Z | 2021-05-02T10:28:48.000Z | source/data_model/python/src/different_shape/constant_shape/value.cpp | pcraster/lue | e64c18f78a8b6d8a602b7578a2572e9740969202 | [
"MIT"
] | 262 | 2016-08-11T10:12:02.000Z | 2020-10-13T18:09:16.000Z | source/data_model/python/src/different_shape/constant_shape/value.cpp | computationalgeography/lue | 71993169bae67a9863d7bd7646d207405dc6f767 | [
"MIT"
] | 1 | 2020-03-11T09:49:41.000Z | 2020-03-11T09:49:41.000Z | #include "submodule.hpp"
#include "lue/array/different_shape/constant_shape/value.hpp"
#include "lue/py/data_model/conversion.hpp"
#include <pybind11/pybind11.h>
namespace py = pybind11;
using namespace pybind11::literals;
namespace lue {
namespace data_model {
namespace different_shape {
namespace constant_shape {
void init_value(
py::module& module)
{
py::class_<Value, ValueGroup>(
module,
"Value",
R"(
Value docstring...
)")
.def("__len__",
&Value::nr_objects)
.def(
"__getitem__",
&Value::operator[]
)
.def("expand",
[](
Value& value,
Index const idx,
py::tuple const& shape,
Count const nr_locations_in_time)
{
auto const shape_ = tuple_to_shape(shape);
return value.expand(idx, shape_, nr_locations_in_time);
})
;
}
} // namespace constant_shape
} // namespace different_shape
} // namespace data_model
} // namespace lue
| 19.854545 | 71 | 0.570513 | [
"shape"
] |
4f4ce1def5a0ee743f61f7b1e0bc36883c3d3b40 | 3,054 | cc | C++ | src/ppl/nn/engines/riscv/optimizer/ops/onnx/non_max_suppression_op.cc | tangyanf/ppl.nn | 744ac02e7d6e363522dc629b35db8a5eca2e7c3c | [
"Apache-2.0"
] | null | null | null | src/ppl/nn/engines/riscv/optimizer/ops/onnx/non_max_suppression_op.cc | tangyanf/ppl.nn | 744ac02e7d6e363522dc629b35db8a5eca2e7c3c | [
"Apache-2.0"
] | null | null | null | src/ppl/nn/engines/riscv/optimizer/ops/onnx/non_max_suppression_op.cc | tangyanf/ppl.nn | 744ac02e7d6e363522dc629b35db8a5eca2e7c3c | [
"Apache-2.0"
] | null | null | null | // 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.
#include "ppl/nn/engines/riscv/optimizer/ops/onnx/non_max_suppression_op.h"
#include "ppl/nn/engines/riscv/kernels/onnx/non_max_suppression_kernel.h"
#include "ppl/nn/oputils/onnx/reshape_non_max_suppression.h"
#include "ppl/nn/common/logger.h"
using namespace std;
using namespace ppl::common;
namespace ppl { namespace nn { namespace riscv {
RetCode NonMaxSupressionOp::Init(const OptKernelOptions& options) {
auto status = GenericLoadParam(options, ¶m_);
if (status != RC_SUCCESS) {
LOG(ERROR) << "load param failed: " << GetRetCodeStr(status);
return status;
}
infer_dims_func_ = [](InputOutputInfo* info) -> RetCode {
return oputils::ReshapeNonMaxSuppression(info);
};
infer_type_func_ = [](InputOutputInfo* info) -> void {
info->GetOutput<TensorImpl>(0)->GetShape()->SetDataType(DATATYPE_INT64);
};
return RC_SUCCESS;
}
RetCode NonMaxSupressionOp::SelectFormat(const InputOutputInfo& info, vector<dataformat_t>* selected_input_formats,
vector<dataformat_t>* selected_output_formats) {
for (uint32_t i = 0; i < selected_input_formats->size(); i++) {
selected_input_formats->at(i) = DATAFORMAT_NDARRAY;
}
selected_output_formats->at(0) = DATAFORMAT_NDARRAY;
return RC_SUCCESS;
}
RetCode NonMaxSupressionOp::SelectDataType(const InputOutputInfo& info, ppl::common::datatype_t forward_precision,
std::vector<datatype_t>* selected_input_data_types,
std::vector<datatype_t>* selected_output_data_types) {
selected_input_data_types->at(0) = DATATYPE_FLOAT32;
selected_input_data_types->at(1) = DATATYPE_FLOAT32;
if (selected_input_data_types->size() > 2) {
selected_input_data_types->at(2) = DATATYPE_INT64;
}
for (uint32_t i = 3; i < selected_input_data_types->size(); i++) {
selected_input_data_types->at(i) = DATATYPE_FLOAT32;
}
selected_output_data_types->at(0) = DATATYPE_INT64;
return RC_SUCCESS;
}
KernelImpl* NonMaxSupressionOp::CreateKernelImpl() const {
return CreateKernelImplWithParam<NonMaxSuppressionKernel>(param_.get());
}
}}} // namespace ppl::nn::riscv | 40.184211 | 115 | 0.707924 | [
"vector"
] |
4f527afd56942dd6d3d66469efef8cba5c9e169b | 16,925 | hpp | C++ | include/GlobalNamespace/BeatmapDifficultyDropdown.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/BeatmapDifficultyDropdown.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/BeatmapDifficultyDropdown.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
// Including type: BeatmapDifficultyMask
#include "GlobalNamespace/BeatmapDifficultyMask.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
}
// Forward declaring namespace: HMUI
namespace HMUI {
// Forward declaring type: SimpleTextDropdown
class SimpleTextDropdown;
// Forward declaring type: DropdownWithTableView
class DropdownWithTableView;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`1<T>
template<typename T>
class Action_1;
// Forward declaring type: Tuple`2<T1, T2>
template<typename T1, typename T2>
class Tuple_2;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: IReadOnlyList`1<T>
template<typename T>
class IReadOnlyList_1;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0x31
#pragma pack(push, 1)
// Autogenerated type: BeatmapDifficultyDropdown
// [TokenAttribute] Offset: FFFFFFFF
class BeatmapDifficultyDropdown : public UnityEngine::MonoBehaviour {
public:
// Nested type: GlobalNamespace::BeatmapDifficultyDropdown::$$c
class $$c;
// private HMUI.SimpleTextDropdown _simpleTextDropdown
// Size: 0x8
// Offset: 0x18
HMUI::SimpleTextDropdown* simpleTextDropdown;
// Field size check
static_assert(sizeof(HMUI::SimpleTextDropdown*) == 0x8);
// private System.Action`1<System.Int32> didSelectCellWithIdxEvent
// Size: 0x8
// Offset: 0x20
System::Action_1<int>* didSelectCellWithIdxEvent;
// Field size check
static_assert(sizeof(System::Action_1<int>*) == 0x8);
// private System.Collections.Generic.IReadOnlyList`1<System.Tuple`2<BeatmapDifficultyMask,System.String>> _beatmapDifficultyData
// Size: 0x8
// Offset: 0x28
System::Collections::Generic::IReadOnlyList_1<System::Tuple_2<GlobalNamespace::BeatmapDifficultyMask, ::Il2CppString*>*>* beatmapDifficultyData;
// Field size check
static_assert(sizeof(System::Collections::Generic::IReadOnlyList_1<System::Tuple_2<GlobalNamespace::BeatmapDifficultyMask, ::Il2CppString*>*>*) == 0x8);
// private System.Boolean <includeAllDifficulties>k__BackingField
// Size: 0x1
// Offset: 0x30
bool includeAllDifficulties;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Creating value type constructor for type: BeatmapDifficultyDropdown
BeatmapDifficultyDropdown(HMUI::SimpleTextDropdown* simpleTextDropdown_ = {}, System::Action_1<int>* didSelectCellWithIdxEvent_ = {}, System::Collections::Generic::IReadOnlyList_1<System::Tuple_2<GlobalNamespace::BeatmapDifficultyMask, ::Il2CppString*>*>* beatmapDifficultyData_ = {}, bool includeAllDifficulties_ = {}) noexcept : simpleTextDropdown{simpleTextDropdown_}, didSelectCellWithIdxEvent{didSelectCellWithIdxEvent_}, beatmapDifficultyData{beatmapDifficultyData_}, includeAllDifficulties{includeAllDifficulties_} {}
// Deleting conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept = delete;
// Get instance field: private HMUI.SimpleTextDropdown _simpleTextDropdown
HMUI::SimpleTextDropdown* _get__simpleTextDropdown();
// Set instance field: private HMUI.SimpleTextDropdown _simpleTextDropdown
void _set__simpleTextDropdown(HMUI::SimpleTextDropdown* value);
// Get instance field: private System.Action`1<System.Int32> didSelectCellWithIdxEvent
System::Action_1<int>* _get_didSelectCellWithIdxEvent();
// Set instance field: private System.Action`1<System.Int32> didSelectCellWithIdxEvent
void _set_didSelectCellWithIdxEvent(System::Action_1<int>* value);
// Get instance field: private System.Collections.Generic.IReadOnlyList`1<System.Tuple`2<BeatmapDifficultyMask,System.String>> _beatmapDifficultyData
System::Collections::Generic::IReadOnlyList_1<System::Tuple_2<GlobalNamespace::BeatmapDifficultyMask, ::Il2CppString*>*>* _get__beatmapDifficultyData();
// Set instance field: private System.Collections.Generic.IReadOnlyList`1<System.Tuple`2<BeatmapDifficultyMask,System.String>> _beatmapDifficultyData
void _set__beatmapDifficultyData(System::Collections::Generic::IReadOnlyList_1<System::Tuple_2<GlobalNamespace::BeatmapDifficultyMask, ::Il2CppString*>*>* value);
// Get instance field: private System.Boolean <includeAllDifficulties>k__BackingField
bool _get_$includeAllDifficulties$k__BackingField();
// Set instance field: private System.Boolean <includeAllDifficulties>k__BackingField
void _set_$includeAllDifficulties$k__BackingField(bool value);
// private System.Collections.Generic.IReadOnlyList`1<System.Tuple`2<BeatmapDifficultyMask,System.String>> get_beatmapDifficultyData()
// Offset: 0x1FD9310
System::Collections::Generic::IReadOnlyList_1<System::Tuple_2<GlobalNamespace::BeatmapDifficultyMask, ::Il2CppString*>*>* get_beatmapDifficultyData();
// public System.Boolean get_includeAllDifficulties()
// Offset: 0x1FD94FC
bool get_includeAllDifficulties();
// public System.Void set_includeAllDifficulties(System.Boolean value)
// Offset: 0x1FD9504
void set_includeAllDifficulties(bool value);
// public System.Void add_didSelectCellWithIdxEvent(System.Action`1<System.Int32> value)
// Offset: 0x1FD91C8
void add_didSelectCellWithIdxEvent(System::Action_1<int>* value);
// public System.Void remove_didSelectCellWithIdxEvent(System.Action`1<System.Int32> value)
// Offset: 0x1FD926C
void remove_didSelectCellWithIdxEvent(System::Action_1<int>* value);
// protected System.Void Start()
// Offset: 0x1FD9510
void Start();
// protected System.Void OnDestroy()
// Offset: 0x1FD9690
void OnDestroy();
// public BeatmapDifficultyMask GetSelectedBeatmapDifficultyMask()
// Offset: 0x1FD976C
GlobalNamespace::BeatmapDifficultyMask GetSelectedBeatmapDifficultyMask();
// public System.Void SelectCellWithBeatmapDifficultyMask(BeatmapDifficultyMask beatmapDifficultyMask)
// Offset: 0x1FD9840
void SelectCellWithBeatmapDifficultyMask(GlobalNamespace::BeatmapDifficultyMask beatmapDifficultyMask);
// private System.Int32 GetIdxForBeatmapDifficultyMask(BeatmapDifficultyMask beatmapDifficultyMask)
// Offset: 0x1FD987C
int GetIdxForBeatmapDifficultyMask(GlobalNamespace::BeatmapDifficultyMask beatmapDifficultyMask);
// private System.Void HandleSimpleTextDropdownDidSelectCellWithIdx(HMUI.DropdownWithTableView dropdownWithTableView, System.Int32 idx)
// Offset: 0x1FD9924
void HandleSimpleTextDropdownDidSelectCellWithIdx(HMUI::DropdownWithTableView* dropdownWithTableView, int idx);
// public System.Void .ctor()
// Offset: 0x1FD9998
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static BeatmapDifficultyDropdown* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::BeatmapDifficultyDropdown::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<BeatmapDifficultyDropdown*, creationType>()));
}
}; // BeatmapDifficultyDropdown
#pragma pack(pop)
static check_size<sizeof(BeatmapDifficultyDropdown), 48 + sizeof(bool)> __GlobalNamespace_BeatmapDifficultyDropdownSizeCheck;
static_assert(sizeof(BeatmapDifficultyDropdown) == 0x31);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::BeatmapDifficultyDropdown*, "", "BeatmapDifficultyDropdown");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::BeatmapDifficultyDropdown::get_beatmapDifficultyData
// Il2CppName: get_beatmapDifficultyData
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Collections::Generic::IReadOnlyList_1<System::Tuple_2<GlobalNamespace::BeatmapDifficultyMask, ::Il2CppString*>*>* (GlobalNamespace::BeatmapDifficultyDropdown::*)()>(&GlobalNamespace::BeatmapDifficultyDropdown::get_beatmapDifficultyData)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDifficultyDropdown*), "get_beatmapDifficultyData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::BeatmapDifficultyDropdown::get_includeAllDifficulties
// Il2CppName: get_includeAllDifficulties
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::BeatmapDifficultyDropdown::*)()>(&GlobalNamespace::BeatmapDifficultyDropdown::get_includeAllDifficulties)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDifficultyDropdown*), "get_includeAllDifficulties", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::BeatmapDifficultyDropdown::set_includeAllDifficulties
// Il2CppName: set_includeAllDifficulties
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::BeatmapDifficultyDropdown::*)(bool)>(&GlobalNamespace::BeatmapDifficultyDropdown::set_includeAllDifficulties)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDifficultyDropdown*), "set_includeAllDifficulties", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::BeatmapDifficultyDropdown::add_didSelectCellWithIdxEvent
// Il2CppName: add_didSelectCellWithIdxEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::BeatmapDifficultyDropdown::*)(System::Action_1<int>*)>(&GlobalNamespace::BeatmapDifficultyDropdown::add_didSelectCellWithIdxEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Int32")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDifficultyDropdown*), "add_didSelectCellWithIdxEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::BeatmapDifficultyDropdown::remove_didSelectCellWithIdxEvent
// Il2CppName: remove_didSelectCellWithIdxEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::BeatmapDifficultyDropdown::*)(System::Action_1<int>*)>(&GlobalNamespace::BeatmapDifficultyDropdown::remove_didSelectCellWithIdxEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Int32")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDifficultyDropdown*), "remove_didSelectCellWithIdxEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::BeatmapDifficultyDropdown::Start
// Il2CppName: Start
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::BeatmapDifficultyDropdown::*)()>(&GlobalNamespace::BeatmapDifficultyDropdown::Start)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDifficultyDropdown*), "Start", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::BeatmapDifficultyDropdown::OnDestroy
// Il2CppName: OnDestroy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::BeatmapDifficultyDropdown::*)()>(&GlobalNamespace::BeatmapDifficultyDropdown::OnDestroy)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDifficultyDropdown*), "OnDestroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::BeatmapDifficultyDropdown::GetSelectedBeatmapDifficultyMask
// Il2CppName: GetSelectedBeatmapDifficultyMask
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::BeatmapDifficultyMask (GlobalNamespace::BeatmapDifficultyDropdown::*)()>(&GlobalNamespace::BeatmapDifficultyDropdown::GetSelectedBeatmapDifficultyMask)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDifficultyDropdown*), "GetSelectedBeatmapDifficultyMask", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::BeatmapDifficultyDropdown::SelectCellWithBeatmapDifficultyMask
// Il2CppName: SelectCellWithBeatmapDifficultyMask
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::BeatmapDifficultyDropdown::*)(GlobalNamespace::BeatmapDifficultyMask)>(&GlobalNamespace::BeatmapDifficultyDropdown::SelectCellWithBeatmapDifficultyMask)> {
static const MethodInfo* get() {
static auto* beatmapDifficultyMask = &::il2cpp_utils::GetClassFromName("", "BeatmapDifficultyMask")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDifficultyDropdown*), "SelectCellWithBeatmapDifficultyMask", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{beatmapDifficultyMask});
}
};
// Writing MetadataGetter for method: GlobalNamespace::BeatmapDifficultyDropdown::GetIdxForBeatmapDifficultyMask
// Il2CppName: GetIdxForBeatmapDifficultyMask
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::BeatmapDifficultyDropdown::*)(GlobalNamespace::BeatmapDifficultyMask)>(&GlobalNamespace::BeatmapDifficultyDropdown::GetIdxForBeatmapDifficultyMask)> {
static const MethodInfo* get() {
static auto* beatmapDifficultyMask = &::il2cpp_utils::GetClassFromName("", "BeatmapDifficultyMask")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDifficultyDropdown*), "GetIdxForBeatmapDifficultyMask", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{beatmapDifficultyMask});
}
};
// Writing MetadataGetter for method: GlobalNamespace::BeatmapDifficultyDropdown::HandleSimpleTextDropdownDidSelectCellWithIdx
// Il2CppName: HandleSimpleTextDropdownDidSelectCellWithIdx
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::BeatmapDifficultyDropdown::*)(HMUI::DropdownWithTableView*, int)>(&GlobalNamespace::BeatmapDifficultyDropdown::HandleSimpleTextDropdownDidSelectCellWithIdx)> {
static const MethodInfo* get() {
static auto* dropdownWithTableView = &::il2cpp_utils::GetClassFromName("HMUI", "DropdownWithTableView")->byval_arg;
static auto* idx = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDifficultyDropdown*), "HandleSimpleTextDropdownDidSelectCellWithIdx", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{dropdownWithTableView, idx});
}
};
// Writing MetadataGetter for method: GlobalNamespace::BeatmapDifficultyDropdown::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 67.7 | 529 | 0.775716 | [
"object",
"vector"
] |
4f53e356ce38db04cf7f21a86d94651755cbd8d3 | 20,202 | cpp | C++ | plugins/datatools/src/table/CSVDataSource.cpp | masrice/megamol | d48fc4889f500528609053a5445202a9c0f6e5fb | [
"BSD-3-Clause"
] | 49 | 2017-08-23T13:24:24.000Z | 2022-03-16T09:10:58.000Z | plugins/datatools/src/table/CSVDataSource.cpp | masrice/megamol | d48fc4889f500528609053a5445202a9c0f6e5fb | [
"BSD-3-Clause"
] | 200 | 2018-07-20T15:18:26.000Z | 2022-03-31T11:01:44.000Z | plugins/datatools/src/table/CSVDataSource.cpp | masrice/megamol | d48fc4889f500528609053a5445202a9c0f6e5fb | [
"BSD-3-Clause"
] | 31 | 2017-07-31T16:19:29.000Z | 2022-02-14T23:41:03.000Z | /*
* CSVDataSource.cpp
*
* Copyright (C) 2015-2016 by CGV (TU Dresden)
* Alle Rechte vorbehalten.
*/
#include "CSVDataSource.h"
#include "stdafx.h"
#include "mmcore/CoreInstance.h"
#include "mmcore/param/BoolParam.h"
#include "mmcore/param/ButtonParam.h"
#include "mmcore/param/EnumParam.h"
#include "mmcore/param/FilePathParam.h"
#include "mmcore/param/IntParam.h"
#include "mmcore/param/StringParam.h"
#include "mmcore/utility/sys/ASCIIFileBuffer.h"
#include "vislib/StringTokeniser.h"
#include <limits>
#include <list>
#include <map>
#include <omp.h>
#include <random>
#include <sstream>
#include <vector>
using namespace megamol::datatools;
using namespace megamol::datatools::table;
using namespace megamol;
enum class DecimalSeparator : int { Unknown = 0, US = 1, DE = 2 };
template<char C>
std::istream& expect(std::istream& is) {
if ((is >> std::ws).peek() == C) {
is.ignore();
} else {
is.setstate(std::ios_base::failbit);
}
return is;
}
double parseValue(const char* tokenStart, const char* tokenEnd) {
std::string token(tokenStart, tokenEnd - tokenStart);
std::istringstream iss(token);
iss.imbue(std::locale::classic());
if (iss.rdbuf()->in_avail() == 0) {
return NAN;
}
// Try to parse as number.
double number;
iss >> number;
if (!iss.fail() && iss.eof()) {
return number;
}
// Reset stream.
iss.str(token);
// Timestamp fractions (to be converted to milliseconds).
unsigned short fractions[4];
// Try to parse as timestamp (HH:mm:ss)
iss >> fractions[0] >> expect<':'> >> fractions[1] >> expect<':'> >> fractions[2];
if (!iss.fail() && iss.eof()) {
return fractions[0] * (60 * 60 * 1000) + fractions[1] * (60 * 1000) + fractions[2] * 1000;
}
// Try to parse as timestamp (HH:mm:ss.SSS)
iss >> expect<'.'> >> fractions[3];
if (!iss.fail() && iss.eof()) {
return fractions[0] * (60 * 60 * 1000) + fractions[1] * (60 * 1000) + fractions[2] * 1000 + fractions[3];
}
// Bail out.
return NAN;
}
CSVDataSource::CSVDataSource(void)
: core::Module()
, filenameSlot("filename", "Filename to read from")
, skipPrefaceSlot("skipPreface", "Number of lines to skip before parsing")
, headerNamesSlot("headerNames", "Interpret the first data row as column names")
, headerTypesSlot("headerTypes", "Interpret the second data row as column types (quantitative or categorical)")
, commentPrefixSlot("commentPrefix", "Prefix that indicates a line-comment")
, clearSlot("clear", "Clears the data")
, colSepSlot("colSep", "The column separator (detected if empty)")
, decSepSlot("decSep", "The decimal point parser format type")
, shuffleSlot("shuffle", "Shuffle data points")
, getDataSlot("getData", "Slot providing the data")
, dataHash(0)
, columns()
, values() {
this->filenameSlot << new core::param::FilePathParam("");
this->MakeSlotAvailable(&this->filenameSlot);
this->skipPrefaceSlot.SetParameter(new core::param::IntParam(0));
this->MakeSlotAvailable(&this->skipPrefaceSlot);
this->headerNamesSlot.SetParameter(new core::param::BoolParam(true));
this->MakeSlotAvailable(&this->headerNamesSlot);
this->headerTypesSlot.SetParameter(new core::param::BoolParam(false));
this->MakeSlotAvailable(&this->headerTypesSlot);
this->commentPrefixSlot.SetParameter(new core::param::StringParam(""));
this->MakeSlotAvailable(&this->commentPrefixSlot);
this->clearSlot << new core::param::ButtonParam();
this->clearSlot.SetUpdateCallback(&CSVDataSource::clearData);
this->MakeSlotAvailable(&this->clearSlot);
this->colSepSlot << new core::param::StringParam("");
this->MakeSlotAvailable(&this->colSepSlot);
core::param::EnumParam* ep = new core::param::EnumParam(0);
ep->SetTypePair(static_cast<int>(DecimalSeparator::Unknown), "Auto");
ep->SetTypePair(static_cast<int>(DecimalSeparator::US), "US (3.141)");
ep->SetTypePair(static_cast<int>(DecimalSeparator::DE), "DE (3,141)");
this->decSepSlot << ep;
this->MakeSlotAvailable(&this->decSepSlot);
this->shuffleSlot.SetParameter(new core::param::BoolParam(false));
this->MakeSlotAvailable(&this->shuffleSlot);
this->getDataSlot.SetCallback(TableDataCall::ClassName(), "GetData", &CSVDataSource::getDataCallback);
this->getDataSlot.SetCallback(TableDataCall::ClassName(), "GetHash", &CSVDataSource::getHashCallback);
this->MakeSlotAvailable(&this->getDataSlot);
}
CSVDataSource::~CSVDataSource(void) {
this->Release();
}
bool CSVDataSource::create(void) {
// nothing to do
return true;
}
void CSVDataSource::release(void) {
this->columns.clear();
this->values.clear();
}
void CSVDataSource::assertData(void) {
if (!this->filenameSlot.IsDirty() && !this->skipPrefaceSlot.IsDirty() && !this->headerNamesSlot.IsDirty() &&
!this->headerTypesSlot.IsDirty() && !this->commentPrefixSlot.IsDirty() && !this->colSepSlot.IsDirty() &&
!this->decSepSlot.IsDirty()) {
if (this->shuffleSlot.IsDirty()) {
shuffleData();
this->shuffleSlot.ResetDirty();
this->dataHash++;
}
return; // nothing to do
}
this->filenameSlot.ResetDirty();
this->skipPrefaceSlot.ResetDirty();
this->headerNamesSlot.ResetDirty();
this->headerTypesSlot.ResetDirty();
this->commentPrefixSlot.ResetDirty();
this->colSepSlot.ResetDirty();
this->decSepSlot.ResetDirty();
this->shuffleSlot.ResetDirty();
this->columns.clear();
this->values.clear();
auto filename = this->filenameSlot.Param<core::param::FilePathParam>()->Value();
try {
vislib::sys::ASCIIFileBuffer file;
// 1. Load the whole file into memory (FAST!)
//////////////////////////////////////////////////////////////////////
if (!file.LoadFile(filename.native().c_str(), vislib::sys::ASCIIFileBuffer::PARSING_LINES))
throw vislib::Exception(__FILE__, __LINE__);
if (file.Count() < 2)
throw vislib::Exception("No data in CSV file", __FILE__, __LINE__);
// 2. Determine the first row, column separator, and decimal point
//////////////////////////////////////////////////////////////////////
int firstHeaRow = this->skipPrefaceSlot.Param<core::param::IntParam>()->Value();
int firstDatRow = this->skipPrefaceSlot.Param<core::param::IntParam>()->Value();
if (headerNamesSlot.Param<core::param::BoolParam>()->Value())
firstDatRow++;
if (headerTypesSlot.Param<core::param::BoolParam>()->Value())
firstDatRow++;
auto comment = vislib::StringA(this->commentPrefixSlot.Param<core::param::StringParam>()->Value().c_str());
if (!comment.IsEmpty()) {
// Skip comments at the beginning of the file.
while (firstHeaRow < file.Count()) {
if (!vislib::StringA(file[firstHeaRow]).StartsWith(comment)) {
break;
}
firstHeaRow++;
firstDatRow++;
}
}
vislib::StringA colSep(this->colSepSlot.Param<core::param::StringParam>()->Value().c_str());
if (colSep.IsEmpty()) {
// Detect column separator
const char ColSepCanidates[] = {'\t', ';', ',', '|'};
vislib::StringA l1(file[firstHeaRow]);
vislib::StringA l2(file[firstHeaRow]);
for (int i = 0; i < sizeof(ColSepCanidates) / sizeof(char); ++i) {
SIZE_T c1 = l1.Count(ColSepCanidates[i]);
if ((c1 > 0) && (c1 == l2.Count(ColSepCanidates[i]))) {
colSep.Append(ColSepCanidates[i]);
break;
}
}
if (colSep.IsEmpty()) {
throw vislib::Exception("Failed to detect column separator", __FILE__, __LINE__);
}
}
DecimalSeparator decType =
static_cast<DecimalSeparator>(this->decSepSlot.Param<core::param::EnumParam>()->Value());
if (decType == DecimalSeparator::Unknown) {
// Detect decimal type
vislib::Array<vislib::StringA> tokens(vislib::StringTokeniserA::Split(file[firstDatRow], colSep, false));
for (SIZE_T i = 0; i < tokens.Count(); i++) {
bool hasDot = tokens[i].Contains('.');
bool hasComma = tokens[i].Contains(',');
if (hasDot && !hasComma) {
decType = DecimalSeparator::US;
break;
} else if (hasComma && !hasDot) {
decType = DecimalSeparator::DE;
break;
}
}
if (decType == DecimalSeparator::Unknown) {
// Assume US format if detection failed.
decType = DecimalSeparator::US;
}
}
// 3. Table layout is now clear... determine column headers.
//////////////////////////////////////////////////////////////////////
vislib::Array<vislib::StringA> dimNames;
if (headerNamesSlot.Param<core::param::BoolParam>()->Value()) {
dimNames = vislib::StringTokeniserA::Split(file[firstHeaRow], colSep, false);
firstHeaRow++;
} else {
dimNames = vislib::StringTokeniserA::Split(file[firstHeaRow], colSep, false);
for (SIZE_T i = 0; i < dimNames.Count(); ++i) {
dimNames[i].Format("Dim %d", static_cast<int>(i));
}
}
this->columns.resize(dimNames.Count());
this->values.clear();
bool hasCatDims = false;
if (headerTypesSlot.Param<core::param::BoolParam>()->Value()) {
vislib::Array<vislib::StringA> tokens(vislib::StringTokeniserA::Split(file[firstHeaRow], colSep, false));
for (SIZE_T i = 0; i < dimNames.Count(); i++) {
TableDataCall::ColumnType type = TableDataCall::ColumnType::QUANTITATIVE;
if (tokens.Count() > i && tokens[i].Equals("CATEGORICAL", true)) {
type = TableDataCall::ColumnType::CATEGORICAL;
hasCatDims = true;
}
this->columns[i]
.SetName(dimNames[i].PeekBuffer())
.SetType(type)
.SetMinimumValue(0.0f)
.SetMaximumValue(1.0f);
}
} else {
for (SIZE_T i = 0; i < dimNames.Count(); i++) {
this->columns[i]
.SetName(dimNames[i].PeekBuffer())
.SetType(TableDataCall::ColumnType::QUANTITATIVE)
.SetMinimumValue(0.0f)
.SetMaximumValue(1.0f);
}
}
// 4. Data format is now clear... finally parse actual data
//////////////////////////////////////////////////////////////////////
size_t colCnt = static_cast<size_t>(this->columns.size());
size_t rowCnt = static_cast<size_t>(file.Count() - firstDatRow);
int colSepEnd = colSep.Length() - 1;
// Test for empty lines at the end
for (; rowCnt > 0; --rowCnt) {
const char* start = file[firstDatRow + rowCnt - 1];
const char* end = start;
size_t col = 0;
while ((*end != '\0') && (col < colCnt)) {
int colSepPos = 0;
while ((*end != '\0') && ((*end != colSep[colSepEnd]) || (colSepEnd != colSepPos))) {
if (*end == colSep[colSepPos])
colSepPos++;
else
colSepPos = 0;
++end;
}
col++;
}
if (col >= colCnt)
break; // we found the last line containing a full data set
}
// Parse in parallel, assuming all lines will work
std::vector<std::map<std::string, float>> catMaps;
int thCnt = omp_get_max_threads();
catMaps.resize(colCnt * thCnt);
values.resize(colCnt * rowCnt);
bool hasInvalids = false;
#pragma omp parallel for
for (long long idx = 0; idx < static_cast<long long>(rowCnt); ++idx) {
int thId = omp_get_thread_num();
const char* start = file[static_cast<size_t>(firstDatRow + idx)];
const char* end = start;
size_t col = 0;
while ((*end != '\0') && (col < colCnt)) {
std::map<std::string, float>& catMap = catMaps[thId + col * thCnt];
int colSepPos = 0;
while ((*end != '\0') && ((*end != colSep[colSepEnd]) || (colSepEnd != colSepPos))) {
if (*end == colSep[colSepPos])
colSepPos++;
else
colSepPos = 0;
++end;
}
if (this->columns[col].Type() == TableDataCall::ColumnType::QUANTITATIVE) {
if (decType == DecimalSeparator::DE) {
for (char* ez = const_cast<char*>(start); ez != end; ++ez)
if (*ez == ',')
*ez = '.';
}
double value = parseValue(start, end);
values[static_cast<size_t>(idx * colCnt + col)] = static_cast<float>(value);
if (std::isnan(value)) {
hasInvalids = true;
}
} else if (this->columns[col].Type() == TableDataCall::ColumnType::CATEGORICAL) {
assert(hasCatDims);
std::map<std::string, float>::iterator cmi = catMap.find(start);
if (cmi == catMap.end()) {
cmi = catMap
.insert(std::pair<std::string, float>(
start, static_cast<float>(thId + thCnt * catMap.size())))
.first;
}
values[static_cast<size_t>(idx * colCnt + col)] = cmi->second;
} else {
assert(false);
}
col++;
if (*end != '\0') {
start = end + 1;
end = start;
}
}
for (; col < colCnt; ++col) {
values[static_cast<size_t>(idx * colCnt + col)] = std::numeric_limits<float>::quiet_NaN();
hasInvalids = true;
}
}
// Report invalid data if present (note: do not drop data!)
if (hasInvalids) {
megamol::core::utility::log::Log::DefaultLog.WriteWarn("CSV file contains invalid data:");
for (size_t c = 0; c < colCnt; ++c) {
std::stringstream ss;
bool invalidColumn = true;
for (size_t r = 0; r < rowCnt; ++r) {
float value = values[r * colCnt + c];
if (std::isnan(value)) {
size_t line = 1 + firstDatRow + r;
ss << line << " ";
} else {
invalidColumn = false;
}
}
std::string lines = ss.str();
if (invalidColumn) {
megamol::core::utility::log::Log::DefaultLog.WriteWarn(" lines in column %d: all", 1 + c);
} else if (!lines.empty()) {
megamol::core::utility::log::Log::DefaultLog.WriteWarn(
" lines in column %d: %s", 1 + c, lines.c_str());
}
}
}
// Merge categorical data so that all `value indices` map to one `string key`
if (hasCatDims) {
for (size_t c = 0; c < colCnt; ++c) {
if (columns[c].Type() != TableDataCall::ColumnType::CATEGORICAL)
continue;
std::map<int, int> catRemap;
std::map<std::string, int> catMap;
for (int ci = static_cast<int>(c) * thCnt; ci < static_cast<int>(c + 1) * thCnt; ++ci) {
for (const std::pair<std::string, float>& p : catMaps[ci]) {
int vi = static_cast<int>(p.second + 0.49f);
std::map<std::string, int>::iterator cmi = catMap.find(p.first);
if (cmi == catMap.end()) {
int nv = static_cast<int>(catMap.size());
catMap[p.first] = nv;
catRemap[vi] = nv;
} else {
catRemap[vi] = cmi->second;
}
}
}
for (size_t r = 0; r < rowCnt; ++r) {
int vi = static_cast<int>(values[r * colCnt + c] + 0.49f);
values[r * colCnt + c] = static_cast<float>(catRemap[vi]);
}
}
}
// Collect min/max
std::vector<float> minVals(colCnt, std::numeric_limits<float>::max());
std::vector<float> maxVals(colCnt, -std::numeric_limits<float>::max());
for (size_t r = 0; r < rowCnt; ++r) {
for (size_t c = 0; c < colCnt; ++c) {
float f = values[r * colCnt + c];
if (f < minVals[c])
minVals[c] = f;
if (f > maxVals[c])
maxVals[c] = f;
}
}
for (size_t c = 0; c < colCnt; ++c) {
columns[c].SetMinimumValue(minVals[c]).SetMaximumValue(maxVals[c]);
}
// 5. All done... report summary
//////////////////////////////////////////////////////////////////////
megamol::core::utility::log::Log::DefaultLog.WriteInfo("Tabular data loaded: %u dimensions; %u samples\n",
static_cast<unsigned int>(colCnt), static_cast<unsigned int>(rowCnt));
} catch (const vislib::Exception& ex) {
megamol::core::utility::log::Log::DefaultLog.WriteError("Could not load \"%s\": %s [%s, %d]",
filename.generic_u8string().c_str(), ex.GetMsgA(), ex.GetFile(), ex.GetLine());
this->columns.clear();
this->values.clear();
} catch (...) {
this->columns.clear();
this->values.clear();
}
shuffleData();
this->dataHash++;
}
void CSVDataSource::shuffleData() {
if (!this->shuffleSlot.Param<core::param::BoolParam>()->Value()) {
// Do not shuffle, unless requested
return;
}
std::default_random_engine eng(static_cast<unsigned int>(dataHash));
size_t numCols = columns.size();
size_t numRows = values.size() / numCols;
std::uniform_int_distribution<size_t> dist(0, numRows - 1);
for (size_t i = 0; i < numRows; ++i) {
size_t idx2 = dist(eng);
for (size_t j = 0; j < numCols; ++j) {
std::swap(values[j + i * numCols], values[j + idx2 * numCols]);
}
}
}
bool CSVDataSource::getDataCallback(core::Call& caller) {
TableDataCall* tfd = dynamic_cast<TableDataCall*>(&caller);
if (tfd == nullptr)
return false;
this->assertData();
tfd->SetDataHash(this->dataHash);
if (values.size() == 0) {
tfd->Set(0, 0, nullptr, nullptr);
} else {
assert((values.size() % columns.size()) == 0);
tfd->Set(columns.size(), values.size() / columns.size(), columns.data(), values.data());
}
tfd->SetUnlocker(nullptr);
return true;
}
bool CSVDataSource::getHashCallback(core::Call& caller) {
TableDataCall* tfd = dynamic_cast<TableDataCall*>(&caller);
if (tfd == nullptr)
return false;
this->assertData();
tfd->SetDataHash(this->dataHash);
tfd->SetUnlocker(nullptr);
tfd->SetFrameCount(1);
tfd->SetFrameID(0);
return true;
}
bool CSVDataSource::clearData(core::param::ParamSlot& caller) {
this->columns.clear();
this->values.clear();
return true;
}
| 38.85 | 119 | 0.526037 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.